blob: e0eecfa6d1143e23a0c9c31f8854c93f311bda7e [file] [log] [blame]
Guido van Rossumf70e43a1991-02-19 12:39:46 +00001
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002/* POSIX module implementation */
3
Jesus Ceaab70e2a2012-10-05 01:48:08 +02004/* This file is also used for Windows NT/MS-Win. In that case the
5 module actually calls itself 'nt', not 'posix', and a few
Andrew MacIntyre6c73af22002-03-03 03:07:07 +00006 functions are either unimplemented or implemented differently. The source
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00007 assumes that for Windows NT, the macro 'MS_WINDOWS' is defined independent
Guido van Rossumad0ee831995-03-01 10:34:45 +00008 of the compiler used. Different compilers define their own feature
Victor Stinnerf427a142014-10-22 12:33:23 +02009 test macro, e.g. '_MSC_VER'. */
Guido van Rossumad0ee831995-03-01 10:34:45 +000010
Larry Hastings31826802013-10-19 00:09:25 -070011
12
Thomas Wouters477c8d52006-05-27 19:21:47 +000013#ifdef __APPLE__
14 /*
Victor Stinner8c62be82010-05-06 00:08:46 +000015 * Step 1 of support for weak-linking a number of symbols existing on
Thomas Wouters477c8d52006-05-27 19:21:47 +000016 * OSX 10.4 and later, see the comment in the #ifdef __APPLE__ block
17 * at the end of this file for more information.
18 */
19# pragma weak lchown
20# pragma weak statvfs
21# pragma weak fstatvfs
22
23#endif /* __APPLE__ */
24
Thomas Wouters68bc4f92006-03-01 01:05:10 +000025#define PY_SSIZE_T_CLEAN
26
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000027#include "Python.h"
Victor Stinnerd5d9e812019-05-13 12:35:37 +020028#ifdef MS_WINDOWS
29 /* include <windows.h> early to avoid conflict with pycore_condvar.h:
30
31 #define WIN32_LEAN_AND_MEAN
32 #include <windows.h>
33
34 FSCTL_GET_REPARSE_POINT is not exported with WIN32_LEAN_AND_MEAN. */
35# include <windows.h>
36#endif
37
38#include "pycore_ceval.h" /* _PyEval_ReInitThreads() */
Victor Stinner01b63ec2019-06-19 00:48:09 +020039#include "pycore_import.h" /* _PyImport_ReInitLock() */
Victor Stinnerd5d9e812019-05-13 12:35:37 +020040#include "pycore_pystate.h" /* _PyRuntime */
Antoine Pitrou346cbd32017-05-27 17:50:54 +020041#include "pythread.h"
Victor Stinner6036e442015-03-08 01:58:04 +010042#include "structmember.h"
Serhiy Storchaka7cf55992013-02-10 21:56:49 +020043#ifndef MS_WINDOWS
Victor Stinnerd5d9e812019-05-13 12:35:37 +020044# include "posixmodule.h"
Tim Golden0321cf22014-05-05 19:46:17 +010045#else
Victor Stinnerd5d9e812019-05-13 12:35:37 +020046# include "winreparse.h"
Serhiy Storchaka7cf55992013-02-10 21:56:49 +020047#endif
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000048
Stefan Krahfb7c8ae2016-04-26 17:04:18 +020049/* On android API level 21, 'AT_EACCESS' is not declared although
50 * HAVE_FACCESSAT is defined. */
51#ifdef __ANDROID__
52#undef HAVE_FACCESSAT
53#endif
54
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)fa76eee2016-05-28 21:03:48 +000055#include <stdio.h> /* needed for ctermid() */
56
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000057#ifdef __cplusplus
58extern "C" {
59#endif
60
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000061PyDoc_STRVAR(posix__doc__,
Guido van Rossumec4f4ac1997-06-02 22:20:51 +000062"This module provides access to operating system functionality that is\n\
63standardized by the C Standard and the POSIX standard (a thinly\n\
64disguised Unix interface). Refer to the library manual and\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000065corresponding Unix manual entries for more information on calls.");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000066
Martin v. Löwis0073f2e2002-11-21 23:52:35 +000067
Ross Lagerwall4d076da2011-03-18 06:56:53 +020068#ifdef HAVE_SYS_UIO_H
69#include <sys/uio.h>
70#endif
71
Christian Heimes75b96182017-09-05 15:53:09 +020072#ifdef HAVE_SYS_SYSMACROS_H
73/* GNU C Library: major(), minor(), makedev() */
74#include <sys/sysmacros.h>
75#endif
76
Thomas Wouters0e3f5912006-08-11 14:57:12 +000077#ifdef HAVE_SYS_TYPES_H
Guido van Rossumb6775db1994-08-01 11:34:53 +000078#include <sys/types.h>
Thomas Wouters0e3f5912006-08-11 14:57:12 +000079#endif /* HAVE_SYS_TYPES_H */
80
81#ifdef HAVE_SYS_STAT_H
Guido van Rossumb6775db1994-08-01 11:34:53 +000082#include <sys/stat.h>
Thomas Wouters0e3f5912006-08-11 14:57:12 +000083#endif /* HAVE_SYS_STAT_H */
Guido van Rossuma6535fd2001-10-18 19:44:10 +000084
Guido van Rossum36bc6801995-06-14 22:54:23 +000085#ifdef HAVE_SYS_WAIT_H
Victor Stinner8c62be82010-05-06 00:08:46 +000086#include <sys/wait.h> /* For WNOHANG */
Guido van Rossum36bc6801995-06-14 22:54:23 +000087#endif
Benjamin Peterson5c0c3252019-11-05 21:58:31 -080088#ifdef HAVE_LINUX_WAIT_H
89#include <linux/wait.h> // For P_PIDFD
90#endif
Guido van Rossumb6775db1994-08-01 11:34:53 +000091
Thomas Wouters0e3f5912006-08-11 14:57:12 +000092#ifdef HAVE_SIGNAL_H
Guido van Rossuma376cc51996-12-05 23:43:35 +000093#include <signal.h>
Thomas Wouters0e3f5912006-08-11 14:57:12 +000094#endif
Guido van Rossuma376cc51996-12-05 23:43:35 +000095
Guido van Rossumb6775db1994-08-01 11:34:53 +000096#ifdef HAVE_FCNTL_H
97#include <fcntl.h>
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +000098#endif /* HAVE_FCNTL_H */
Guido van Rossumb6775db1994-08-01 11:34:53 +000099
Guido van Rossuma6535fd2001-10-18 19:44:10 +0000100#ifdef HAVE_GRP_H
101#include <grp.h>
102#endif
103
Barry Warsaw5676bd12003-01-07 20:57:09 +0000104#ifdef HAVE_SYSEXITS_H
105#include <sysexits.h>
106#endif /* HAVE_SYSEXITS_H */
107
Anthony Baxter8a560de2004-10-13 15:30:56 +0000108#ifdef HAVE_SYS_LOADAVG_H
109#include <sys/loadavg.h>
110#endif
111
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +0000112#ifdef HAVE_SYS_SENDFILE_H
113#include <sys/sendfile.h>
114#endif
115
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +0200116#if defined(__APPLE__)
117#include <copyfile.h>
118#endif
119
Benjamin Peterson94b580d2011-08-02 17:30:04 -0500120#ifdef HAVE_SCHED_H
121#include <sched.h>
122#endif
123
Pablo Galindoaac4d032019-05-31 19:39:47 +0100124#ifdef HAVE_COPY_FILE_RANGE
125#include <unistd.h>
126#endif
127
Benjamin Peterson2dbda072012-03-16 10:12:55 -0500128#if !defined(CPU_ALLOC) && defined(HAVE_SCHED_SETAFFINITY)
Benjamin Peterson7b51b8d2012-03-14 22:28:25 -0500129#undef HAVE_SCHED_SETAFFINITY
130#endif
131
doko@ubuntu.com4a173bc2014-04-17 19:47:16 +0200132#if defined(HAVE_SYS_XATTR_H) && defined(__GLIBC__) && !defined(__FreeBSD_kernel__) && !defined(__GNU__)
Benjamin Peterson9428d532011-09-14 11:45:52 -0400133#define USE_XATTRS
134#endif
135
136#ifdef USE_XATTRS
Benjamin Petersonb77fe172011-09-13 17:20:47 -0400137#include <sys/xattr.h>
Benjamin Peterson799bd802011-08-31 22:15:17 -0400138#endif
139
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +0000140#if defined(__FreeBSD__) || defined(__DragonFly__) || defined(__APPLE__)
141#ifdef HAVE_SYS_SOCKET_H
142#include <sys/socket.h>
143#endif
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +0000144#endif
145
Victor Stinner8b905bd2011-10-25 13:34:04 +0200146#ifdef HAVE_DLFCN_H
147#include <dlfcn.h>
148#endif
149
Charles-Francois Natali44feda32013-05-20 14:40:46 +0200150#ifdef __hpux
151#include <sys/mpctl.h>
152#endif
153
154#if defined(__DragonFly__) || \
155 defined(__OpenBSD__) || \
156 defined(__FreeBSD__) || \
157 defined(__NetBSD__) || \
158 defined(__APPLE__)
159#include <sys/sysctl.h>
160#endif
161
Victor Stinner9b1f4742016-09-06 16:18:52 -0700162#ifdef HAVE_LINUX_RANDOM_H
163# include <linux/random.h>
164#endif
165#ifdef HAVE_GETRANDOM_SYSCALL
166# include <sys/syscall.h>
167#endif
168
Antoine Pitroubcf2b592012-02-08 23:28:36 +0100169#if defined(MS_WINDOWS)
170# define TERMSIZE_USE_CONIO
171#elif defined(HAVE_SYS_IOCTL_H)
172# include <sys/ioctl.h>
173# if defined(HAVE_TERMIOS_H)
174# include <termios.h>
175# endif
176# if defined(TIOCGWINSZ)
177# define TERMSIZE_USE_IOCTL
178# endif
179#endif /* MS_WINDOWS */
180
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000181/* Various compilers have only certain posix functions */
Martin v. Löwis4f1cd8b2001-07-26 13:41:06 +0000182/* XXX Gosh I wish these were all moved into pyconfig.h */
Victor Stinner8c62be82010-05-06 00:08:46 +0000183#if defined(__WATCOMC__) && !defined(__QNX__) /* Watcom compiler */
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000184#define HAVE_OPENDIR 1
Victor Stinner8c62be82010-05-06 00:08:46 +0000185#define HAVE_SYSTEM 1
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000186#include <process.h>
187#else
Victor Stinner8c62be82010-05-06 00:08:46 +0000188#ifdef _MSC_VER /* Microsoft compiler */
Amaury Forgeot d'Arc4b6fdf32010-09-07 21:31:17 +0000189#define HAVE_GETPPID 1
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +0000190#define HAVE_GETLOGIN 1
Victor Stinner8c62be82010-05-06 00:08:46 +0000191#define HAVE_SPAWNV 1
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000192#define HAVE_EXECV 1
Steve Dowercc16be82016-09-08 10:35:16 -0700193#define HAVE_WSPAWNV 1
194#define HAVE_WEXECV 1
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000195#define HAVE_PIPE 1
Victor Stinner8c62be82010-05-06 00:08:46 +0000196#define HAVE_SYSTEM 1
197#define HAVE_CWAIT 1
198#define HAVE_FSYNC 1
Tim Peters11b23062003-04-23 02:39:17 +0000199#define fsync _commit
Andrew MacIntyre6c73af22002-03-03 03:07:07 +0000200#else
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000201/* Unix functions that the configure script doesn't check for */
pxinwrf2d7ac72019-05-21 18:46:37 +0800202#ifndef __VXWORKS__
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000203#define HAVE_EXECV 1
204#define HAVE_FORK 1
Victor Stinner8c62be82010-05-06 00:08:46 +0000205#if defined(__USLC__) && defined(__SCO_VERSION__) /* SCO UDK Compiler */
Guido van Rossum2242f2f2001-04-11 20:58:20 +0000206#define HAVE_FORK1 1
207#endif
pxinwrf2d7ac72019-05-21 18:46:37 +0800208#endif
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000209#define HAVE_GETEGID 1
210#define HAVE_GETEUID 1
211#define HAVE_GETGID 1
212#define HAVE_GETPPID 1
213#define HAVE_GETUID 1
214#define HAVE_KILL 1
215#define HAVE_OPENDIR 1
216#define HAVE_PIPE 1
Victor Stinner8c62be82010-05-06 00:08:46 +0000217#define HAVE_SYSTEM 1
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000218#define HAVE_WAIT 1
Victor Stinner8c62be82010-05-06 00:08:46 +0000219#define HAVE_TTYNAME 1
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000220#endif /* _MSC_VER */
Guido van Rossumc5a0f531997-12-02 20:36:02 +0000221#endif /* ! __WATCOMC__ || __QNX__ */
Guido van Rossumad0ee831995-03-01 10:34:45 +0000222
Eddie Elizondob3966632019-11-05 07:16:14 -0800223_Py_IDENTIFIER(__fspath__);
Victor Stinnera2f7c002012-02-08 03:36:25 +0100224
Larry Hastings61272b72014-01-07 12:41:53 -0800225/*[clinic input]
Larry Hastings2f936352014-08-05 14:04:04 +1000226# one of the few times we lie about this name!
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800227module os
Larry Hastings61272b72014-01-07 12:41:53 -0800228[clinic start generated code]*/
Larry Hastings2f936352014-08-05 14:04:04 +1000229/*[clinic end generated code: output=da39a3ee5e6b4b0d input=94a0f0f978acae17]*/
Victor Stinnera2f7c002012-02-08 03:36:25 +0100230
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000231#ifndef _MSC_VER
Guido van Rossum36bc6801995-06-14 22:54:23 +0000232
Martin v. Löwis8eb92a02002-09-19 08:03:21 +0000233#if defined(__sgi)&&_COMPILER_VERSION>=700
234/* declare ctermid_r if compiling with MIPSPro 7.x in ANSI C mode
235 (default) */
236extern char *ctermid_r(char *);
237#endif
238
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000239#endif /* !_MSC_VER */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000240
pxinwrf2d7ac72019-05-21 18:46:37 +0800241#if defined(__VXWORKS__)
242#include <vxCpuLib.h>
243#include <rtpLib.h>
244#include <wait.h>
245#include <taskLib.h>
246#ifndef _P_WAIT
247#define _P_WAIT 0
248#define _P_NOWAIT 1
249#define _P_NOWAITO 1
250#endif
251#endif /* __VXWORKS__ */
252
Pablo Galindo6c6ddf92018-01-29 01:56:10 +0000253#ifdef HAVE_POSIX_SPAWN
254#include <spawn.h>
255#endif
256
Guido van Rossumb6775db1994-08-01 11:34:53 +0000257#ifdef HAVE_UTIME_H
258#include <utime.h>
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +0000259#endif /* HAVE_UTIME_H */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000260
Guido van Rossum14ed0b21994-09-29 09:50:09 +0000261#ifdef HAVE_SYS_UTIME_H
262#include <sys/utime.h>
263#define HAVE_UTIME_H /* pretend we do for the rest of this file */
264#endif /* HAVE_SYS_UTIME_H */
265
Guido van Rossumb6775db1994-08-01 11:34:53 +0000266#ifdef HAVE_SYS_TIMES_H
267#include <sys/times.h>
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +0000268#endif /* HAVE_SYS_TIMES_H */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000269
270#ifdef HAVE_SYS_PARAM_H
271#include <sys/param.h>
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +0000272#endif /* HAVE_SYS_PARAM_H */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000273
274#ifdef HAVE_SYS_UTSNAME_H
275#include <sys/utsname.h>
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +0000276#endif /* HAVE_SYS_UTSNAME_H */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000277
Guido van Rossum3bbc62e1995-01-02 19:30:30 +0000278#ifdef HAVE_DIRENT_H
Guido van Rossumb6775db1994-08-01 11:34:53 +0000279#include <dirent.h>
Guido van Rossum3bbc62e1995-01-02 19:30:30 +0000280#define NAMLEN(dirent) strlen((dirent)->d_name)
281#else
Guido van Rossumc5a0f531997-12-02 20:36:02 +0000282#if defined(__WATCOMC__) && !defined(__QNX__)
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000283#include <direct.h>
284#define NAMLEN(dirent) strlen((dirent)->d_name)
285#else
Guido van Rossumb6775db1994-08-01 11:34:53 +0000286#define dirent direct
Guido van Rossum3bbc62e1995-01-02 19:30:30 +0000287#define NAMLEN(dirent) (dirent)->d_namlen
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000288#endif
Guido van Rossum3bbc62e1995-01-02 19:30:30 +0000289#ifdef HAVE_SYS_NDIR_H
Guido van Rossumb6775db1994-08-01 11:34:53 +0000290#include <sys/ndir.h>
Guido van Rossum3bbc62e1995-01-02 19:30:30 +0000291#endif
292#ifdef HAVE_SYS_DIR_H
Guido van Rossumb6775db1994-08-01 11:34:53 +0000293#include <sys/dir.h>
Guido van Rossum3bbc62e1995-01-02 19:30:30 +0000294#endif
295#ifdef HAVE_NDIR_H
Guido van Rossumb6775db1994-08-01 11:34:53 +0000296#include <ndir.h>
Guido van Rossum3bbc62e1995-01-02 19:30:30 +0000297#endif
298#endif
Guido van Rossumb6775db1994-08-01 11:34:53 +0000299
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000300#ifdef _MSC_VER
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000301#ifdef HAVE_DIRECT_H
Guido van Rossumb6775db1994-08-01 11:34:53 +0000302#include <direct.h>
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000303#endif
304#ifdef HAVE_IO_H
Guido van Rossumb6775db1994-08-01 11:34:53 +0000305#include <io.h>
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000306#endif
307#ifdef HAVE_PROCESS_H
Guido van Rossumb6775db1994-08-01 11:34:53 +0000308#include <process.h>
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000309#endif
Raymond Hettinger0291c9f2010-08-01 21:10:35 +0000310#ifndef IO_REPARSE_TAG_SYMLINK
Amaury Forgeot d'Arc844807e2010-08-16 22:16:51 +0000311#define IO_REPARSE_TAG_SYMLINK (0xA000000CL)
Raymond Hettinger0291c9f2010-08-01 21:10:35 +0000312#endif
Tim Golden0321cf22014-05-05 19:46:17 +0100313#ifndef IO_REPARSE_TAG_MOUNT_POINT
314#define IO_REPARSE_TAG_MOUNT_POINT (0xA0000003L)
315#endif
Tim Petersbc2e10e2002-03-03 23:17:02 +0000316#include "osdefs.h"
Kristján Valur Jónssonf64e6512009-04-13 10:16:14 +0000317#include <malloc.h>
Guido van Rossumb6775db1994-08-01 11:34:53 +0000318#include <windows.h>
Victor Stinner8c62be82010-05-06 00:08:46 +0000319#include <shellapi.h> /* for ShellExecute() */
Brian Curtine8e4b3b2010-09-23 20:04:14 +0000320#include <lmcons.h> /* for UNLEN */
Brian Curtin52173d42010-12-02 18:29:18 +0000321#define HAVE_SYMLINK
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000322#endif /* _MSC_VER */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000323
Tim Petersbc2e10e2002-03-03 23:17:02 +0000324#ifndef MAXPATHLEN
Thomas Wouters477c8d52006-05-27 19:21:47 +0000325#if defined(PATH_MAX) && PATH_MAX > 1024
326#define MAXPATHLEN PATH_MAX
327#else
Tim Petersbc2e10e2002-03-03 23:17:02 +0000328#define MAXPATHLEN 1024
Thomas Wouters477c8d52006-05-27 19:21:47 +0000329#endif
Tim Petersbc2e10e2002-03-03 23:17:02 +0000330#endif /* MAXPATHLEN */
331
Guido van Rossum54ecc3d1999-01-27 17:53:11 +0000332#ifdef UNION_WAIT
333/* Emulate some macros on systems that have a union instead of macros */
334
335#ifndef WIFEXITED
336#define WIFEXITED(u_wait) (!(u_wait).w_termsig && !(u_wait).w_coredump)
337#endif
338
339#ifndef WEXITSTATUS
340#define WEXITSTATUS(u_wait) (WIFEXITED(u_wait)?((u_wait).w_retcode):-1)
341#endif
342
343#ifndef WTERMSIG
344#define WTERMSIG(u_wait) ((u_wait).w_termsig)
345#endif
346
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000347#define WAIT_TYPE union wait
348#define WAIT_STATUS_INT(s) (s.w_status)
349
350#else /* !UNION_WAIT */
351#define WAIT_TYPE int
352#define WAIT_STATUS_INT(s) (s)
Guido van Rossum54ecc3d1999-01-27 17:53:11 +0000353#endif /* UNION_WAIT */
354
Greg Wardb48bc172000-03-01 21:51:56 +0000355/* Don't use the "_r" form if we don't need it (also, won't have a
356 prototype for it, at least on Solaris -- maybe others as well?). */
Antoine Pitroua6a4dc82017-09-07 18:56:24 +0200357#if defined(HAVE_CTERMID_R)
Greg Wardb48bc172000-03-01 21:51:56 +0000358#define USE_CTERMID_R
359#endif
360
Fred Drake699f3522000-06-29 21:12:41 +0000361/* choose the appropriate stat and fstat functions and return structs */
Guido van Rossum64529cd2000-06-30 22:45:12 +0000362#undef STAT
Antoine Pitroue47e0932011-01-19 15:21:35 +0000363#undef FSTAT
364#undef STRUCT_STAT
Victor Stinner14b9b112013-06-25 00:37:25 +0200365#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +0000366# define STAT win32_stat
Larry Hastings9cf065c2012-06-22 16:30:09 -0700367# define LSTAT win32_lstat
Victor Stinnere134a7f2015-03-30 10:09:31 +0200368# define FSTAT _Py_fstat_noraise
Steve Dowerf2f373f2015-02-21 08:44:05 -0800369# define STRUCT_STAT struct _Py_stat_struct
Fred Drake699f3522000-06-29 21:12:41 +0000370#else
Victor Stinner8c62be82010-05-06 00:08:46 +0000371# define STAT stat
Larry Hastings9cf065c2012-06-22 16:30:09 -0700372# define LSTAT lstat
Victor Stinner8c62be82010-05-06 00:08:46 +0000373# define FSTAT fstat
374# define STRUCT_STAT struct stat
Fred Drake699f3522000-06-29 21:12:41 +0000375#endif
376
Tim Peters11b23062003-04-23 02:39:17 +0000377#if defined(MAJOR_IN_MKDEV)
Martin v. Löwisdbe3f762002-10-10 14:27:30 +0000378#include <sys/mkdev.h>
379#else
380#if defined(MAJOR_IN_SYSMACROS)
381#include <sys/sysmacros.h>
382#endif
Neal Norwitz3d949422002-04-20 13:46:43 +0000383#if defined(HAVE_MKNOD) && defined(HAVE_SYS_MKDEV_H)
384#include <sys/mkdev.h>
385#endif
Martin v. Löwisdbe3f762002-10-10 14:27:30 +0000386#endif
Fred Drake699f3522000-06-29 21:12:41 +0000387
Serhiy Storchaka06a13f82015-02-22 21:34:54 +0200388#ifdef MS_WINDOWS
Victor Stinner6036e442015-03-08 01:58:04 +0100389#define INITFUNC PyInit_nt
390#define MODNAME "nt"
391#else
392#define INITFUNC PyInit_posix
393#define MODNAME "posix"
394#endif
395
jcea6c51d512018-01-28 14:00:08 +0100396#if defined(__sun)
397/* Something to implement in autoconf, not present in autoconf 2.69 */
398#define HAVE_STRUCT_STAT_ST_FSTYPE 1
399#endif
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200400
Zackery Spytz43fdbd22019-05-29 13:57:07 -0600401/* memfd_create is either defined in sys/mman.h or sys/memfd.h
402 * linux/memfd.h defines additional flags
403 */
404#ifdef HAVE_SYS_MMAN_H
405#include <sys/mman.h>
406#endif
407#ifdef HAVE_SYS_MEMFD_H
408#include <sys/memfd.h>
409#endif
410#ifdef HAVE_LINUX_MEMFD_H
411#include <linux/memfd.h>
412#endif
413
Gregory P. Smith1d300ce2018-12-30 21:13:02 -0800414#ifdef _Py_MEMORY_SANITIZER
415# include <sanitizer/msan_interface.h>
416#endif
417
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200418#ifdef HAVE_FORK
419static void
420run_at_forkers(PyObject *lst, int reverse)
421{
422 Py_ssize_t i;
423 PyObject *cpy;
424
425 if (lst != NULL) {
426 assert(PyList_CheckExact(lst));
427
428 /* Use a list copy in case register_at_fork() is called from
429 * one of the callbacks.
430 */
431 cpy = PyList_GetSlice(lst, 0, PyList_GET_SIZE(lst));
432 if (cpy == NULL)
433 PyErr_WriteUnraisable(lst);
434 else {
435 if (reverse)
436 PyList_Reverse(cpy);
437 for (i = 0; i < PyList_GET_SIZE(cpy); i++) {
438 PyObject *func, *res;
439 func = PyList_GET_ITEM(cpy, i);
Jeroen Demeyer7f41c8e2019-07-04 12:35:31 +0200440 res = _PyObject_CallNoArg(func);
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200441 if (res == NULL)
442 PyErr_WriteUnraisable(func);
443 else
444 Py_DECREF(res);
445 }
446 Py_DECREF(cpy);
447 }
448 }
449}
450
451void
452PyOS_BeforeFork(void)
453{
Victor Stinnercaba55b2018-08-03 15:33:52 +0200454 run_at_forkers(_PyInterpreterState_Get()->before_forkers, 1);
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200455
456 _PyImport_AcquireLock();
457}
458
459void
460PyOS_AfterFork_Parent(void)
461{
462 if (_PyImport_ReleaseLock() <= 0)
463 Py_FatalError("failed releasing import lock after fork");
464
Victor Stinnercaba55b2018-08-03 15:33:52 +0200465 run_at_forkers(_PyInterpreterState_Get()->after_forkers_parent, 0);
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200466}
467
468void
469PyOS_AfterFork_Child(void)
470{
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200471 _PyRuntimeState *runtime = &_PyRuntime;
472 _PyGILState_Reinit(runtime);
Victor Stinnerd5d9e812019-05-13 12:35:37 +0200473 _PyEval_ReInitThreads(runtime);
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200474 _PyImport_ReInitLock();
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200475 _PySignal_AfterFork();
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200476 _PyRuntimeState_ReInitThreads(runtime);
Victor Stinnerb49858b2019-05-24 15:20:23 +0200477 _PyInterpreterState_DeleteExceptMain(runtime);
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200478
Victor Stinnercaba55b2018-08-03 15:33:52 +0200479 run_at_forkers(_PyInterpreterState_Get()->after_forkers_child, 0);
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200480}
481
482static int
483register_at_forker(PyObject **lst, PyObject *func)
484{
Gregory P. Smith163468a2017-05-29 10:03:41 -0700485 if (func == NULL) /* nothing to register? do nothing. */
486 return 0;
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200487 if (*lst == NULL) {
488 *lst = PyList_New(0);
489 if (*lst == NULL)
490 return -1;
491 }
492 return PyList_Append(*lst, func);
493}
494#endif
495
496/* Legacy wrapper */
497void
498PyOS_AfterFork(void)
499{
500#ifdef HAVE_FORK
501 PyOS_AfterFork_Child();
502#endif
503}
504
505
Victor Stinner6036e442015-03-08 01:58:04 +0100506#ifdef MS_WINDOWS
Serhiy Storchaka06a13f82015-02-22 21:34:54 +0200507/* defined in fileutils.c */
Benjamin Petersone5024512018-09-12 12:06:42 -0700508void _Py_time_t_to_FILE_TIME(time_t, int, FILETIME *);
509void _Py_attribute_data_to_stat(BY_HANDLE_FILE_INFORMATION *,
Serhiy Storchaka06a13f82015-02-22 21:34:54 +0200510 ULONG, struct _Py_stat_struct *);
511#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -0700512
Larry Hastings9cf065c2012-06-22 16:30:09 -0700513
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200514#ifndef MS_WINDOWS
515PyObject *
516_PyLong_FromUid(uid_t uid)
517{
518 if (uid == (uid_t)-1)
519 return PyLong_FromLong(-1);
520 return PyLong_FromUnsignedLong(uid);
521}
522
523PyObject *
524_PyLong_FromGid(gid_t gid)
525{
526 if (gid == (gid_t)-1)
527 return PyLong_FromLong(-1);
528 return PyLong_FromUnsignedLong(gid);
529}
530
531int
532_Py_Uid_Converter(PyObject *obj, void *p)
533{
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700534 uid_t uid;
535 PyObject *index;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200536 int overflow;
Serhiy Storchakab4621892013-02-10 23:28:02 +0200537 long result;
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700538 unsigned long uresult;
539
540 index = PyNumber_Index(obj);
541 if (index == NULL) {
542 PyErr_Format(PyExc_TypeError,
543 "uid should be integer, not %.200s",
Eddie Elizondob3966632019-11-05 07:16:14 -0800544 _PyType_Name(Py_TYPE(obj)));
Serhiy Storchakab4621892013-02-10 23:28:02 +0200545 return 0;
546 }
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700547
548 /*
549 * Handling uid_t is complicated for two reasons:
550 * * Although uid_t is (always?) unsigned, it still
551 * accepts -1.
552 * * We don't know its size in advance--it may be
553 * bigger than an int, or it may be smaller than
554 * a long.
555 *
556 * So a bit of defensive programming is in order.
557 * Start with interpreting the value passed
558 * in as a signed long and see if it works.
559 */
560
561 result = PyLong_AsLongAndOverflow(index, &overflow);
562
563 if (!overflow) {
564 uid = (uid_t)result;
565
566 if (result == -1) {
567 if (PyErr_Occurred())
568 goto fail;
569 /* It's a legitimate -1, we're done. */
570 goto success;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200571 }
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700572
573 /* Any other negative number is disallowed. */
574 if (result < 0)
575 goto underflow;
576
577 /* Ensure the value wasn't truncated. */
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200578 if (sizeof(uid_t) < sizeof(long) &&
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700579 (long)uid != result)
580 goto underflow;
581 goto success;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200582 }
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700583
584 if (overflow < 0)
585 goto underflow;
586
587 /*
588 * Okay, the value overflowed a signed long. If it
589 * fits in an *unsigned* long, it may still be okay,
590 * as uid_t may be unsigned long on this platform.
591 */
592 uresult = PyLong_AsUnsignedLong(index);
593 if (PyErr_Occurred()) {
594 if (PyErr_ExceptionMatches(PyExc_OverflowError))
595 goto overflow;
596 goto fail;
597 }
598
599 uid = (uid_t)uresult;
600
601 /*
602 * If uid == (uid_t)-1, the user actually passed in ULONG_MAX,
603 * but this value would get interpreted as (uid_t)-1 by chown
604 * and its siblings. That's not what the user meant! So we
605 * throw an overflow exception instead. (We already
Tim Golden23005082013-10-25 11:22:37 +0100606 * handled a real -1 with PyLong_AsLongAndOverflow() above.)
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700607 */
608 if (uid == (uid_t)-1)
609 goto overflow;
610
611 /* Ensure the value wasn't truncated. */
612 if (sizeof(uid_t) < sizeof(long) &&
613 (unsigned long)uid != uresult)
614 goto overflow;
615 /* fallthrough */
616
617success:
618 Py_DECREF(index);
619 *(uid_t *)p = uid;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200620 return 1;
621
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700622underflow:
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200623 PyErr_SetString(PyExc_OverflowError,
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700624 "uid is less than minimum");
625 goto fail;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200626
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700627overflow:
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200628 PyErr_SetString(PyExc_OverflowError,
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700629 "uid is greater than maximum");
630 /* fallthrough */
631
632fail:
633 Py_DECREF(index);
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200634 return 0;
635}
636
637int
638_Py_Gid_Converter(PyObject *obj, void *p)
639{
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700640 gid_t gid;
641 PyObject *index;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200642 int overflow;
Serhiy Storchakab4621892013-02-10 23:28:02 +0200643 long result;
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700644 unsigned long uresult;
645
646 index = PyNumber_Index(obj);
647 if (index == NULL) {
648 PyErr_Format(PyExc_TypeError,
649 "gid should be integer, not %.200s",
Eddie Elizondob3966632019-11-05 07:16:14 -0800650 _PyType_Name(Py_TYPE(obj)));
Serhiy Storchakab4621892013-02-10 23:28:02 +0200651 return 0;
652 }
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700653
654 /*
655 * Handling gid_t is complicated for two reasons:
656 * * Although gid_t is (always?) unsigned, it still
657 * accepts -1.
658 * * We don't know its size in advance--it may be
659 * bigger than an int, or it may be smaller than
660 * a long.
661 *
662 * So a bit of defensive programming is in order.
663 * Start with interpreting the value passed
664 * in as a signed long and see if it works.
665 */
666
667 result = PyLong_AsLongAndOverflow(index, &overflow);
668
669 if (!overflow) {
670 gid = (gid_t)result;
671
672 if (result == -1) {
673 if (PyErr_Occurred())
674 goto fail;
675 /* It's a legitimate -1, we're done. */
676 goto success;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200677 }
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700678
679 /* Any other negative number is disallowed. */
680 if (result < 0) {
681 goto underflow;
682 }
683
684 /* Ensure the value wasn't truncated. */
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200685 if (sizeof(gid_t) < sizeof(long) &&
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700686 (long)gid != result)
687 goto underflow;
688 goto success;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200689 }
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700690
691 if (overflow < 0)
692 goto underflow;
693
694 /*
695 * Okay, the value overflowed a signed long. If it
696 * fits in an *unsigned* long, it may still be okay,
697 * as gid_t may be unsigned long on this platform.
698 */
699 uresult = PyLong_AsUnsignedLong(index);
700 if (PyErr_Occurred()) {
701 if (PyErr_ExceptionMatches(PyExc_OverflowError))
702 goto overflow;
703 goto fail;
704 }
705
706 gid = (gid_t)uresult;
707
708 /*
709 * If gid == (gid_t)-1, the user actually passed in ULONG_MAX,
710 * but this value would get interpreted as (gid_t)-1 by chown
711 * and its siblings. That's not what the user meant! So we
712 * throw an overflow exception instead. (We already
Tim Golden23005082013-10-25 11:22:37 +0100713 * handled a real -1 with PyLong_AsLongAndOverflow() above.)
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700714 */
715 if (gid == (gid_t)-1)
716 goto overflow;
717
718 /* Ensure the value wasn't truncated. */
719 if (sizeof(gid_t) < sizeof(long) &&
720 (unsigned long)gid != uresult)
721 goto overflow;
722 /* fallthrough */
723
724success:
725 Py_DECREF(index);
726 *(gid_t *)p = gid;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200727 return 1;
728
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700729underflow:
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200730 PyErr_SetString(PyExc_OverflowError,
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700731 "gid is less than minimum");
732 goto fail;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200733
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700734overflow:
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200735 PyErr_SetString(PyExc_OverflowError,
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700736 "gid is greater than maximum");
737 /* fallthrough */
738
739fail:
740 Py_DECREF(index);
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200741 return 0;
742}
743#endif /* MS_WINDOWS */
744
745
Benjamin Petersoned4aa832016-09-05 17:44:18 -0700746#define _PyLong_FromDev PyLong_FromLongLong
Gregory P. Smith702dada2015-01-28 16:07:52 -0800747
748
Serhiy Storchakab2653b32015-01-18 11:12:11 +0200749#if defined(HAVE_MKNOD) && defined(HAVE_MAKEDEV)
750static int
751_Py_Dev_Converter(PyObject *obj, void *p)
752{
Serhiy Storchakab2653b32015-01-18 11:12:11 +0200753 *((dev_t *)p) = PyLong_AsUnsignedLongLong(obj);
Serhiy Storchakab2653b32015-01-18 11:12:11 +0200754 if (PyErr_Occurred())
755 return 0;
756 return 1;
757}
Gregory P. Smith702dada2015-01-28 16:07:52 -0800758#endif /* HAVE_MKNOD && HAVE_MAKEDEV */
Serhiy Storchakab2653b32015-01-18 11:12:11 +0200759
760
Larry Hastings9cf065c2012-06-22 16:30:09 -0700761#ifdef AT_FDCWD
Trent Nelson9a461052012-09-18 21:50:06 -0400762/*
763 * Why the (int) cast? Solaris 10 defines AT_FDCWD as 0xffd19553 (-3041965);
764 * without the int cast, the value gets interpreted as uint (4291925331),
765 * which doesn't play nicely with all the initializer lines in this file that
766 * look like this:
767 * int dir_fd = DEFAULT_DIR_FD;
768 */
769#define DEFAULT_DIR_FD (int)AT_FDCWD
Larry Hastings9cf065c2012-06-22 16:30:09 -0700770#else
771#define DEFAULT_DIR_FD (-100)
772#endif
773
774static int
Serhiy Storchaka819399b2016-04-06 22:17:52 +0300775_fd_converter(PyObject *o, int *p)
Serhiy Storchakaa2ad5c32013-01-07 23:13:46 +0200776{
777 int overflow;
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700778 long long_value;
779
780 PyObject *index = PyNumber_Index(o);
781 if (index == NULL) {
Larry Hastings9cf065c2012-06-22 16:30:09 -0700782 return 0;
783 }
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700784
Serhiy Storchaka819399b2016-04-06 22:17:52 +0300785 assert(PyLong_Check(index));
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700786 long_value = PyLong_AsLongAndOverflow(index, &overflow);
787 Py_DECREF(index);
Serhiy Storchaka819399b2016-04-06 22:17:52 +0300788 assert(!PyErr_Occurred());
Serhiy Storchakaa2ad5c32013-01-07 23:13:46 +0200789 if (overflow > 0 || long_value > INT_MAX) {
Larry Hastings9cf065c2012-06-22 16:30:09 -0700790 PyErr_SetString(PyExc_OverflowError,
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700791 "fd is greater than maximum");
Larry Hastings9cf065c2012-06-22 16:30:09 -0700792 return 0;
793 }
Serhiy Storchakaa2ad5c32013-01-07 23:13:46 +0200794 if (overflow < 0 || long_value < INT_MIN) {
Larry Hastings9cf065c2012-06-22 16:30:09 -0700795 PyErr_SetString(PyExc_OverflowError,
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700796 "fd is less than minimum");
Larry Hastings9cf065c2012-06-22 16:30:09 -0700797 return 0;
798 }
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700799
Larry Hastings9cf065c2012-06-22 16:30:09 -0700800 *p = (int)long_value;
801 return 1;
802}
803
804static int
Serhiy Storchakaa2ad5c32013-01-07 23:13:46 +0200805dir_fd_converter(PyObject *o, void *p)
806{
807 if (o == Py_None) {
808 *(int *)p = DEFAULT_DIR_FD;
809 return 1;
810 }
Serhiy Storchaka819399b2016-04-06 22:17:52 +0300811 else if (PyIndex_Check(o)) {
812 return _fd_converter(o, (int *)p);
813 }
814 else {
815 PyErr_Format(PyExc_TypeError,
816 "argument should be integer or None, not %.200s",
Eddie Elizondob3966632019-11-05 07:16:14 -0800817 _PyType_Name(Py_TYPE(o)));
Serhiy Storchaka819399b2016-04-06 22:17:52 +0300818 return 0;
819 }
Larry Hastings9cf065c2012-06-22 16:30:09 -0700820}
821
Victor Stinner623ed612020-01-21 19:25:32 +0100822#ifdef HAVE_PUTENV
823# define PY_PUTENV_DICT
824#endif
825
Eddie Elizondob3966632019-11-05 07:16:14 -0800826typedef struct {
827 PyObject *billion;
Victor Stinner623ed612020-01-21 19:25:32 +0100828#ifdef PY_PUTENV_DICT
829 /* putenv() and _wputenv() requires that the caller manages the environment
830 variable memory. Use a Python dictionary for that: name => env, where
831 env is a string like "name=value". On Windows, dict keys and values are
832 Unicode strings. On Unix, they are bytes strings. */
833 PyObject *putenv_dict;
834#endif
Eddie Elizondob3966632019-11-05 07:16:14 -0800835 PyObject *DirEntryType;
836 PyObject *ScandirIteratorType;
837#if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
838 PyObject *SchedParamType;
839#endif
840 PyObject *StatResultType;
841 PyObject *StatVFSResultType;
842 PyObject *TerminalSizeType;
843 PyObject *TimesResultType;
844 PyObject *UnameResultType;
845#if defined(HAVE_WAITID) && !defined(__APPLE__)
846 PyObject *WaitidResultType;
847#endif
848#if defined(HAVE_WAIT3) || defined(HAVE_WAIT4)
849 PyObject *struct_rusage;
850#endif
851 PyObject *st_mode;
852} _posixstate;
853
854static struct PyModuleDef posixmodule;
855
856#define _posixstate(o) ((_posixstate *)PyModule_GetState(o))
857#define _posixstate_global ((_posixstate *)PyModule_GetState(PyState_FindModule(&posixmodule)))
Larry Hastings9cf065c2012-06-22 16:30:09 -0700858
Larry Hastings9cf065c2012-06-22 16:30:09 -0700859/*
860 * A PyArg_ParseTuple "converter" function
861 * that handles filesystem paths in the manner
862 * preferred by the os module.
863 *
864 * path_converter accepts (Unicode) strings and their
865 * subclasses, and bytes and their subclasses. What
866 * it does with the argument depends on the platform:
867 *
868 * * On Windows, if we get a (Unicode) string we
869 * extract the wchar_t * and return it; if we get
Steve Dowercc16be82016-09-08 10:35:16 -0700870 * bytes we decode to wchar_t * and return that.
Larry Hastings9cf065c2012-06-22 16:30:09 -0700871 *
872 * * On all other platforms, strings are encoded
873 * to bytes using PyUnicode_FSConverter, then we
874 * extract the char * from the bytes object and
875 * return that.
876 *
877 * path_converter also optionally accepts signed
878 * integers (representing open file descriptors) instead
879 * of path strings.
880 *
881 * Input fields:
882 * path.nullable
883 * If nonzero, the path is permitted to be None.
884 * path.allow_fd
885 * If nonzero, the path is permitted to be a file handle
886 * (a signed int) instead of a string.
887 * path.function_name
888 * If non-NULL, path_converter will use that as the name
889 * of the function in error messages.
Larry Hastings31826802013-10-19 00:09:25 -0700890 * (If path.function_name is NULL it omits the function name.)
Larry Hastings9cf065c2012-06-22 16:30:09 -0700891 * path.argument_name
892 * If non-NULL, path_converter will use that as the name
893 * of the parameter in error messages.
894 * (If path.argument_name is NULL it uses "path".)
895 *
896 * Output fields:
897 * path.wide
898 * Points to the path if it was expressed as Unicode
899 * and was not encoded. (Only used on Windows.)
900 * path.narrow
901 * Points to the path if it was expressed as bytes,
Steve Dowercc16be82016-09-08 10:35:16 -0700902 * or it was Unicode and was encoded to bytes. (On Windows,
Martin Panterb1321fb2016-10-10 00:38:21 +0000903 * is a non-zero integer if the path was expressed as bytes.
Steve Dowercc16be82016-09-08 10:35:16 -0700904 * The type is deliberately incompatible to prevent misuse.)
Larry Hastings9cf065c2012-06-22 16:30:09 -0700905 * path.fd
906 * Contains a file descriptor if path.accept_fd was true
907 * and the caller provided a signed integer instead of any
908 * sort of string.
909 *
910 * WARNING: if your "path" parameter is optional, and is
911 * unspecified, path_converter will never get called.
912 * So if you set allow_fd, you *MUST* initialize path.fd = -1
913 * yourself!
914 * path.length
915 * The length of the path in characters, if specified as
916 * a string.
917 * path.object
Xiang Zhang04316c42017-01-08 23:26:57 +0800918 * The original object passed in (if get a PathLike object,
919 * the result of PyOS_FSPath() is treated as the original object).
920 * Own a reference to the object.
Larry Hastings9cf065c2012-06-22 16:30:09 -0700921 * path.cleanup
922 * For internal use only. May point to a temporary object.
923 * (Pay no attention to the man behind the curtain.)
924 *
925 * At most one of path.wide or path.narrow will be non-NULL.
926 * If path was None and path.nullable was set,
927 * or if path was an integer and path.allow_fd was set,
928 * both path.wide and path.narrow will be NULL
929 * and path.length will be 0.
Georg Brandlf7875592012-06-24 13:58:31 +0200930 *
Larry Hastings9cf065c2012-06-22 16:30:09 -0700931 * path_converter takes care to not write to the path_t
932 * unless it's successful. However it must reset the
933 * "cleanup" field each time it's called.
934 *
935 * Use as follows:
936 * path_t path;
937 * memset(&path, 0, sizeof(path));
938 * PyArg_ParseTuple(args, "O&", path_converter, &path);
939 * // ... use values from path ...
940 * path_cleanup(&path);
941 *
942 * (Note that if PyArg_Parse fails you don't need to call
943 * path_cleanup(). However it is safe to do so.)
944 */
945typedef struct {
Victor Stinner292c8352012-10-30 02:17:38 +0100946 const char *function_name;
947 const char *argument_name;
Larry Hastings9cf065c2012-06-22 16:30:09 -0700948 int nullable;
949 int allow_fd;
Serhiy Storchakadeab18d2016-05-07 16:45:18 +0300950 const wchar_t *wide;
Steve Dowercc16be82016-09-08 10:35:16 -0700951#ifdef MS_WINDOWS
952 BOOL narrow;
953#else
Serhiy Storchakadeab18d2016-05-07 16:45:18 +0300954 const char *narrow;
Steve Dowercc16be82016-09-08 10:35:16 -0700955#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -0700956 int fd;
957 Py_ssize_t length;
958 PyObject *object;
959 PyObject *cleanup;
960} path_t;
961
Steve Dowercc16be82016-09-08 10:35:16 -0700962#ifdef MS_WINDOWS
963#define PATH_T_INITIALIZE(function_name, argument_name, nullable, allow_fd) \
964 {function_name, argument_name, nullable, allow_fd, NULL, FALSE, -1, 0, NULL, NULL}
965#else
Larry Hastings2f936352014-08-05 14:04:04 +1000966#define PATH_T_INITIALIZE(function_name, argument_name, nullable, allow_fd) \
967 {function_name, argument_name, nullable, allow_fd, NULL, NULL, -1, 0, NULL, NULL}
Steve Dowercc16be82016-09-08 10:35:16 -0700968#endif
Larry Hastings31826802013-10-19 00:09:25 -0700969
Larry Hastings9cf065c2012-06-22 16:30:09 -0700970static void
Xiang Zhang04316c42017-01-08 23:26:57 +0800971path_cleanup(path_t *path)
972{
973 Py_CLEAR(path->object);
974 Py_CLEAR(path->cleanup);
Larry Hastings9cf065c2012-06-22 16:30:09 -0700975}
976
977static int
Serhiy Storchaka819399b2016-04-06 22:17:52 +0300978path_converter(PyObject *o, void *p)
979{
Larry Hastings9cf065c2012-06-22 16:30:09 -0700980 path_t *path = (path_t *)p;
Xiang Zhang04316c42017-01-08 23:26:57 +0800981 PyObject *bytes = NULL;
982 Py_ssize_t length = 0;
Brett Cannon3f9183b2016-08-26 14:44:48 -0700983 int is_index, is_buffer, is_bytes, is_unicode;
Serhiy Storchakadeab18d2016-05-07 16:45:18 +0300984 const char *narrow;
Steve Dowercc16be82016-09-08 10:35:16 -0700985#ifdef MS_WINDOWS
Xiang Zhang04316c42017-01-08 23:26:57 +0800986 PyObject *wo = NULL;
Steve Dowercc16be82016-09-08 10:35:16 -0700987 const wchar_t *wide;
988#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -0700989
990#define FORMAT_EXCEPTION(exc, fmt) \
991 PyErr_Format(exc, "%s%s" fmt, \
992 path->function_name ? path->function_name : "", \
993 path->function_name ? ": " : "", \
994 path->argument_name ? path->argument_name : "path")
995
996 /* Py_CLEANUP_SUPPORTED support */
997 if (o == NULL) {
998 path_cleanup(path);
999 return 1;
1000 }
1001
Brett Cannon3f9183b2016-08-26 14:44:48 -07001002 /* Ensure it's always safe to call path_cleanup(). */
Xiang Zhang04316c42017-01-08 23:26:57 +08001003 path->object = path->cleanup = NULL;
1004 /* path->object owns a reference to the original object */
1005 Py_INCREF(o);
Larry Hastings9cf065c2012-06-22 16:30:09 -07001006
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001007 if ((o == Py_None) && path->nullable) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07001008 path->wide = NULL;
Steve Dowercc16be82016-09-08 10:35:16 -07001009#ifdef MS_WINDOWS
1010 path->narrow = FALSE;
1011#else
Larry Hastings9cf065c2012-06-22 16:30:09 -07001012 path->narrow = NULL;
Steve Dowercc16be82016-09-08 10:35:16 -07001013#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -07001014 path->fd = -1;
Xiang Zhang04316c42017-01-08 23:26:57 +08001015 goto success_exit;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001016 }
1017
Brett Cannon3f9183b2016-08-26 14:44:48 -07001018 /* Only call this here so that we don't treat the return value of
1019 os.fspath() as an fd or buffer. */
1020 is_index = path->allow_fd && PyIndex_Check(o);
1021 is_buffer = PyObject_CheckBuffer(o);
1022 is_bytes = PyBytes_Check(o);
1023 is_unicode = PyUnicode_Check(o);
1024
1025 if (!is_index && !is_buffer && !is_unicode && !is_bytes) {
1026 /* Inline PyOS_FSPath() for better error messages. */
Pablo Galindo09fbcd62019-02-18 10:46:34 +00001027 PyObject *func, *res;
Brett Cannon3f9183b2016-08-26 14:44:48 -07001028
1029 func = _PyObject_LookupSpecial(o, &PyId___fspath__);
1030 if (NULL == func) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001031 goto error_format;
Brett Cannon3f9183b2016-08-26 14:44:48 -07001032 }
Pablo Galindo09fbcd62019-02-18 10:46:34 +00001033 res = _PyObject_CallNoArg(func);
Brett Cannon3f9183b2016-08-26 14:44:48 -07001034 Py_DECREF(func);
Pablo Galindo09fbcd62019-02-18 10:46:34 +00001035 if (NULL == res) {
Brett Cannon3f9183b2016-08-26 14:44:48 -07001036 goto error_exit;
1037 }
Pablo Galindo09fbcd62019-02-18 10:46:34 +00001038 else if (PyUnicode_Check(res)) {
Brett Cannon3f9183b2016-08-26 14:44:48 -07001039 is_unicode = 1;
1040 }
Pablo Galindo09fbcd62019-02-18 10:46:34 +00001041 else if (PyBytes_Check(res)) {
Brett Cannon3f9183b2016-08-26 14:44:48 -07001042 is_bytes = 1;
1043 }
1044 else {
Pablo Galindo09fbcd62019-02-18 10:46:34 +00001045 PyErr_Format(PyExc_TypeError,
1046 "expected %.200s.__fspath__() to return str or bytes, "
Eddie Elizondob3966632019-11-05 07:16:14 -08001047 "not %.200s", _PyType_Name(Py_TYPE(o)),
1048 _PyType_Name(Py_TYPE(res)));
Pablo Galindo09fbcd62019-02-18 10:46:34 +00001049 Py_DECREF(res);
1050 goto error_exit;
Brett Cannon3f9183b2016-08-26 14:44:48 -07001051 }
Pablo Galindo09fbcd62019-02-18 10:46:34 +00001052
1053 /* still owns a reference to the original object */
1054 Py_DECREF(o);
1055 o = res;
Brett Cannon3f9183b2016-08-26 14:44:48 -07001056 }
1057
1058 if (is_unicode) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07001059#ifdef MS_WINDOWS
Victor Stinner26c03bd2016-09-19 11:55:44 +02001060 wide = PyUnicode_AsUnicodeAndSize(o, &length);
Victor Stinner59799a82013-11-13 14:17:30 +01001061 if (!wide) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001062 goto error_exit;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001063 }
Victor Stinner59799a82013-11-13 14:17:30 +01001064 if (length > 32767) {
1065 FORMAT_EXCEPTION(PyExc_ValueError, "%s too long for Windows");
Xiang Zhang04316c42017-01-08 23:26:57 +08001066 goto error_exit;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001067 }
Serhiy Storchaka2b0d2002015-04-20 09:53:58 +03001068 if (wcslen(wide) != length) {
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001069 FORMAT_EXCEPTION(PyExc_ValueError, "embedded null character in %s");
Xiang Zhang04316c42017-01-08 23:26:57 +08001070 goto error_exit;
Serhiy Storchaka2b0d2002015-04-20 09:53:58 +03001071 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07001072
1073 path->wide = wide;
Xiang Zhang04316c42017-01-08 23:26:57 +08001074 path->narrow = FALSE;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001075 path->fd = -1;
Xiang Zhang04316c42017-01-08 23:26:57 +08001076 goto success_exit;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001077#else
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001078 if (!PyUnicode_FSConverter(o, &bytes)) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001079 goto error_exit;
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001080 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07001081#endif
1082 }
Brett Cannon3f9183b2016-08-26 14:44:48 -07001083 else if (is_bytes) {
Serhiy Storchakad73c3182016-08-06 23:22:08 +03001084 bytes = o;
1085 Py_INCREF(bytes);
1086 }
Brett Cannon3f9183b2016-08-26 14:44:48 -07001087 else if (is_buffer) {
Serhiy Storchaka1180e5a2017-07-11 06:36:46 +03001088 /* XXX Replace PyObject_CheckBuffer with PyBytes_Check in other code
Ville Skyttä49b27342017-08-03 09:00:59 +03001089 after removing support of non-bytes buffer objects. */
Serhiy Storchakad73c3182016-08-06 23:22:08 +03001090 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
1091 "%s%s%s should be %s, not %.200s",
1092 path->function_name ? path->function_name : "",
1093 path->function_name ? ": " : "",
1094 path->argument_name ? path->argument_name : "path",
Brett Cannon3f9183b2016-08-26 14:44:48 -07001095 path->allow_fd && path->nullable ? "string, bytes, os.PathLike, "
1096 "integer or None" :
1097 path->allow_fd ? "string, bytes, os.PathLike or integer" :
1098 path->nullable ? "string, bytes, os.PathLike or None" :
1099 "string, bytes or os.PathLike",
Eddie Elizondob3966632019-11-05 07:16:14 -08001100 _PyType_Name(Py_TYPE(o)))) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001101 goto error_exit;
Serhiy Storchakad73c3182016-08-06 23:22:08 +03001102 }
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001103 bytes = PyBytes_FromObject(o);
Larry Hastings9cf065c2012-06-22 16:30:09 -07001104 if (!bytes) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001105 goto error_exit;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001106 }
1107 }
Steve Dowercc16be82016-09-08 10:35:16 -07001108 else if (is_index) {
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001109 if (!_fd_converter(o, &path->fd)) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001110 goto error_exit;
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001111 }
1112 path->wide = NULL;
Steve Dowercc16be82016-09-08 10:35:16 -07001113#ifdef MS_WINDOWS
1114 path->narrow = FALSE;
1115#else
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001116 path->narrow = NULL;
Steve Dowercc16be82016-09-08 10:35:16 -07001117#endif
Xiang Zhang04316c42017-01-08 23:26:57 +08001118 goto success_exit;
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001119 }
1120 else {
Xiang Zhang04316c42017-01-08 23:26:57 +08001121 error_format:
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001122 PyErr_Format(PyExc_TypeError, "%s%s%s should be %s, not %.200s",
1123 path->function_name ? path->function_name : "",
1124 path->function_name ? ": " : "",
1125 path->argument_name ? path->argument_name : "path",
Brett Cannon3f9183b2016-08-26 14:44:48 -07001126 path->allow_fd && path->nullable ? "string, bytes, os.PathLike, "
1127 "integer or None" :
1128 path->allow_fd ? "string, bytes, os.PathLike or integer" :
1129 path->nullable ? "string, bytes, os.PathLike or None" :
1130 "string, bytes or os.PathLike",
Eddie Elizondob3966632019-11-05 07:16:14 -08001131 _PyType_Name(Py_TYPE(o)));
Xiang Zhang04316c42017-01-08 23:26:57 +08001132 goto error_exit;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001133 }
1134
Larry Hastings9cf065c2012-06-22 16:30:09 -07001135 length = PyBytes_GET_SIZE(bytes);
Larry Hastings9cf065c2012-06-22 16:30:09 -07001136 narrow = PyBytes_AS_STRING(bytes);
Victor Stinner706768c2014-08-16 01:03:39 +02001137 if ((size_t)length != strlen(narrow)) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +03001138 FORMAT_EXCEPTION(PyExc_ValueError, "embedded null character in %s");
Xiang Zhang04316c42017-01-08 23:26:57 +08001139 goto error_exit;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001140 }
1141
Steve Dowercc16be82016-09-08 10:35:16 -07001142#ifdef MS_WINDOWS
1143 wo = PyUnicode_DecodeFSDefaultAndSize(
1144 narrow,
1145 length
1146 );
1147 if (!wo) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001148 goto error_exit;
Steve Dowercc16be82016-09-08 10:35:16 -07001149 }
1150
Xiang Zhang04316c42017-01-08 23:26:57 +08001151 wide = PyUnicode_AsUnicodeAndSize(wo, &length);
Steve Dowercc16be82016-09-08 10:35:16 -07001152 if (!wide) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001153 goto error_exit;
Steve Dowercc16be82016-09-08 10:35:16 -07001154 }
1155 if (length > 32767) {
1156 FORMAT_EXCEPTION(PyExc_ValueError, "%s too long for Windows");
Xiang Zhang04316c42017-01-08 23:26:57 +08001157 goto error_exit;
Steve Dowercc16be82016-09-08 10:35:16 -07001158 }
1159 if (wcslen(wide) != length) {
1160 FORMAT_EXCEPTION(PyExc_ValueError, "embedded null character in %s");
Xiang Zhang04316c42017-01-08 23:26:57 +08001161 goto error_exit;
Steve Dowercc16be82016-09-08 10:35:16 -07001162 }
1163 path->wide = wide;
1164 path->narrow = TRUE;
Xiang Zhang04316c42017-01-08 23:26:57 +08001165 path->cleanup = wo;
1166 Py_DECREF(bytes);
Steve Dowercc16be82016-09-08 10:35:16 -07001167#else
Larry Hastings9cf065c2012-06-22 16:30:09 -07001168 path->wide = NULL;
1169 path->narrow = narrow;
Serhiy Storchakad73c3182016-08-06 23:22:08 +03001170 if (bytes == o) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001171 /* Still a reference owned by path->object, don't have to
1172 worry about path->narrow is used after free. */
Serhiy Storchakad73c3182016-08-06 23:22:08 +03001173 Py_DECREF(bytes);
Serhiy Storchakad73c3182016-08-06 23:22:08 +03001174 }
1175 else {
1176 path->cleanup = bytes;
Serhiy Storchakad73c3182016-08-06 23:22:08 +03001177 }
Xiang Zhang04316c42017-01-08 23:26:57 +08001178#endif
1179 path->fd = -1;
1180
1181 success_exit:
1182 path->length = length;
1183 path->object = o;
1184 return Py_CLEANUP_SUPPORTED;
1185
1186 error_exit:
1187 Py_XDECREF(o);
1188 Py_XDECREF(bytes);
1189#ifdef MS_WINDOWS
1190 Py_XDECREF(wo);
1191#endif
1192 return 0;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001193}
1194
1195static void
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001196argument_unavailable_error(const char *function_name, const char *argument_name)
1197{
Larry Hastings9cf065c2012-06-22 16:30:09 -07001198 PyErr_Format(PyExc_NotImplementedError,
1199 "%s%s%s unavailable on this platform",
1200 (function_name != NULL) ? function_name : "",
1201 (function_name != NULL) ? ": ": "",
1202 argument_name);
1203}
1204
1205static int
Serhiy Storchakaa2ad5c32013-01-07 23:13:46 +02001206dir_fd_unavailable(PyObject *o, void *p)
1207{
1208 int dir_fd;
1209 if (!dir_fd_converter(o, &dir_fd))
Larry Hastings9cf065c2012-06-22 16:30:09 -07001210 return 0;
Serhiy Storchakaa2ad5c32013-01-07 23:13:46 +02001211 if (dir_fd != DEFAULT_DIR_FD) {
1212 argument_unavailable_error(NULL, "dir_fd");
1213 return 0;
1214 }
1215 *(int *)p = dir_fd;
1216 return 1;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001217}
1218
1219static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001220fd_specified(const char *function_name, int fd)
1221{
Larry Hastings9cf065c2012-06-22 16:30:09 -07001222 if (fd == -1)
1223 return 0;
1224
1225 argument_unavailable_error(function_name, "fd");
1226 return 1;
1227}
1228
1229static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001230follow_symlinks_specified(const char *function_name, int follow_symlinks)
1231{
Larry Hastings9cf065c2012-06-22 16:30:09 -07001232 if (follow_symlinks)
1233 return 0;
1234
1235 argument_unavailable_error(function_name, "follow_symlinks");
1236 return 1;
1237}
1238
1239static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001240path_and_dir_fd_invalid(const char *function_name, path_t *path, int dir_fd)
1241{
Steve Dowercc16be82016-09-08 10:35:16 -07001242 if (!path->wide && (dir_fd != DEFAULT_DIR_FD)
1243#ifndef MS_WINDOWS
1244 && !path->narrow
1245#endif
1246 ) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07001247 PyErr_Format(PyExc_ValueError,
1248 "%s: can't specify dir_fd without matching path",
1249 function_name);
1250 return 1;
1251 }
1252 return 0;
1253}
1254
1255static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001256dir_fd_and_fd_invalid(const char *function_name, int dir_fd, int fd)
1257{
Larry Hastings9cf065c2012-06-22 16:30:09 -07001258 if ((dir_fd != DEFAULT_DIR_FD) && (fd != -1)) {
1259 PyErr_Format(PyExc_ValueError,
1260 "%s: can't specify both dir_fd and fd",
1261 function_name);
1262 return 1;
1263 }
1264 return 0;
1265}
1266
1267static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001268fd_and_follow_symlinks_invalid(const char *function_name, int fd,
1269 int follow_symlinks)
1270{
Larry Hastings9cf065c2012-06-22 16:30:09 -07001271 if ((fd > 0) && (!follow_symlinks)) {
1272 PyErr_Format(PyExc_ValueError,
1273 "%s: cannot use fd and follow_symlinks together",
1274 function_name);
1275 return 1;
1276 }
1277 return 0;
1278}
1279
1280static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001281dir_fd_and_follow_symlinks_invalid(const char *function_name, int dir_fd,
1282 int follow_symlinks)
1283{
Larry Hastings9cf065c2012-06-22 16:30:09 -07001284 if ((dir_fd != DEFAULT_DIR_FD) && (!follow_symlinks)) {
1285 PyErr_Format(PyExc_ValueError,
1286 "%s: cannot use dir_fd and follow_symlinks together",
1287 function_name);
1288 return 1;
1289 }
1290 return 0;
1291}
1292
Larry Hastings2f936352014-08-05 14:04:04 +10001293#ifdef MS_WINDOWS
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001294 typedef long long Py_off_t;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001295#else
Larry Hastings2f936352014-08-05 14:04:04 +10001296 typedef off_t Py_off_t;
1297#endif
1298
1299static int
1300Py_off_t_converter(PyObject *arg, void *addr)
1301{
1302#ifdef HAVE_LARGEFILE_SUPPORT
1303 *((Py_off_t *)addr) = PyLong_AsLongLong(arg);
1304#else
1305 *((Py_off_t *)addr) = PyLong_AsLong(arg);
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001306#endif
1307 if (PyErr_Occurred())
1308 return 0;
1309 return 1;
1310}
Larry Hastings2f936352014-08-05 14:04:04 +10001311
1312static PyObject *
1313PyLong_FromPy_off_t(Py_off_t offset)
1314{
1315#ifdef HAVE_LARGEFILE_SUPPORT
1316 return PyLong_FromLongLong(offset);
1317#else
1318 return PyLong_FromLong(offset);
Ross Lagerwallb1e5d592011-09-19 08:30:43 +02001319#endif
Larry Hastings2f936352014-08-05 14:04:04 +10001320}
1321
Serhiy Storchakad54cfb12018-05-08 07:48:50 +03001322#ifdef HAVE_SIGSET_T
1323/* Convert an iterable of integers to a sigset.
1324 Return 1 on success, return 0 and raise an exception on error. */
1325int
1326_Py_Sigset_Converter(PyObject *obj, void *addr)
1327{
1328 sigset_t *mask = (sigset_t *)addr;
1329 PyObject *iterator, *item;
1330 long signum;
1331 int overflow;
1332
Rémi Lapeyref0900192019-05-04 01:30:53 +02001333 // The extra parens suppress the unreachable-code warning with clang on MacOS
1334 if (sigemptyset(mask) < (0)) {
Serhiy Storchakad54cfb12018-05-08 07:48:50 +03001335 /* Probably only if mask == NULL. */
1336 PyErr_SetFromErrno(PyExc_OSError);
1337 return 0;
1338 }
1339
1340 iterator = PyObject_GetIter(obj);
1341 if (iterator == NULL) {
1342 return 0;
1343 }
1344
1345 while ((item = PyIter_Next(iterator)) != NULL) {
1346 signum = PyLong_AsLongAndOverflow(item, &overflow);
1347 Py_DECREF(item);
1348 if (signum <= 0 || signum >= NSIG) {
1349 if (overflow || signum != -1 || !PyErr_Occurred()) {
1350 PyErr_Format(PyExc_ValueError,
1351 "signal number %ld out of range", signum);
1352 }
1353 goto error;
1354 }
1355 if (sigaddset(mask, (int)signum)) {
1356 if (errno != EINVAL) {
1357 /* Probably impossible */
1358 PyErr_SetFromErrno(PyExc_OSError);
1359 goto error;
1360 }
1361 /* For backwards compatibility, allow idioms such as
1362 * `range(1, NSIG)` but warn about invalid signal numbers
1363 */
1364 const char msg[] =
1365 "invalid signal number %ld, please use valid_signals()";
1366 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1, msg, signum)) {
1367 goto error;
1368 }
1369 }
1370 }
1371 if (!PyErr_Occurred()) {
1372 Py_DECREF(iterator);
1373 return 1;
1374 }
1375
1376error:
1377 Py_DECREF(iterator);
1378 return 0;
1379}
1380#endif /* HAVE_SIGSET_T */
1381
Brian Curtinfc1be6d2010-11-24 13:23:18 +00001382#ifdef MS_WINDOWS
Brian Curtinf5e76d02010-11-24 13:14:05 +00001383
1384static int
Brian Curtind25aef52011-06-13 15:16:04 -05001385win32_get_reparse_tag(HANDLE reparse_point_handle, ULONG *reparse_tag)
Brian Curtinf5e76d02010-11-24 13:14:05 +00001386{
Martin Panter70214ad2016-08-04 02:38:59 +00001387 char target_buffer[_Py_MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
1388 _Py_REPARSE_DATA_BUFFER *rdb = (_Py_REPARSE_DATA_BUFFER *)target_buffer;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001389 DWORD n_bytes_returned;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001390
1391 if (0 == DeviceIoControl(
1392 reparse_point_handle,
1393 FSCTL_GET_REPARSE_POINT,
1394 NULL, 0, /* in buffer */
1395 target_buffer, sizeof(target_buffer),
1396 &n_bytes_returned,
1397 NULL)) /* we're not using OVERLAPPED_IO */
Brian Curtind25aef52011-06-13 15:16:04 -05001398 return FALSE;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001399
1400 if (reparse_tag)
1401 *reparse_tag = rdb->ReparseTag;
1402
Brian Curtind25aef52011-06-13 15:16:04 -05001403 return TRUE;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001404}
Victor Stinner1ab6c2d2011-11-15 22:27:41 +01001405
Brian Curtinfc1be6d2010-11-24 13:23:18 +00001406#endif /* MS_WINDOWS */
Brian Curtinf5e76d02010-11-24 13:14:05 +00001407
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001408/* Return a dictionary corresponding to the POSIX environment table */
Ronald Oussoren697e56d2013-01-25 17:57:13 +01001409#if defined(WITH_NEXT_FRAMEWORK) || (defined(__APPLE__) && defined(Py_ENABLE_SHARED))
Jack Jansenea0c3822002-08-01 21:57:49 +00001410/* On Darwin/MacOSX a shared library or framework has no access to
Ronald Oussoren697e56d2013-01-25 17:57:13 +01001411** environ directly, we must obtain it with _NSGetEnviron(). See also
1412** man environ(7).
Jack Jansenea0c3822002-08-01 21:57:49 +00001413*/
1414#include <crt_externs.h>
pxinwrf2d7ac72019-05-21 18:46:37 +08001415#elif !defined(_MSC_VER) && (!defined(__WATCOMC__) || defined(__QNX__) || defined(__VXWORKS__))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001416extern char **environ;
Guido van Rossuma4916fa1996-05-23 22:58:55 +00001417#endif /* !_MSC_VER */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001418
Barry Warsaw53699e91996-12-10 23:23:01 +00001419static PyObject *
Thomas Woutersf3f33dc2000-07-21 06:00:07 +00001420convertenviron(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001421{
Victor Stinner8c62be82010-05-06 00:08:46 +00001422 PyObject *d;
Thomas Hellerf78f12a2007-11-08 19:33:05 +00001423#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +00001424 wchar_t **e;
Thomas Hellerf78f12a2007-11-08 19:33:05 +00001425#else
Victor Stinner8c62be82010-05-06 00:08:46 +00001426 char **e;
Thomas Hellerf78f12a2007-11-08 19:33:05 +00001427#endif
Guido van Rossumd48f2521997-12-05 22:19:34 +00001428
Victor Stinner8c62be82010-05-06 00:08:46 +00001429 d = PyDict_New();
1430 if (d == NULL)
1431 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00001432#ifdef MS_WINDOWS
1433 /* _wenviron must be initialized in this way if the program is started
1434 through main() instead of wmain(). */
1435 _wgetenv(L"");
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001436 e = _wenviron;
Benoit Hudson723f71a2019-12-06 14:15:03 -05001437#elif defined(WITH_NEXT_FRAMEWORK) || (defined(__APPLE__) && defined(Py_ENABLE_SHARED))
1438 /* environ is not accessible as an extern in a shared object on OSX; use
1439 _NSGetEnviron to resolve it. The value changes if you add environment
1440 variables between calls to Py_Initialize, so don't cache the value. */
1441 e = *_NSGetEnviron();
Victor Stinner8c62be82010-05-06 00:08:46 +00001442#else
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001443 e = environ;
1444#endif
1445 if (e == NULL)
Victor Stinner8c62be82010-05-06 00:08:46 +00001446 return d;
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001447 for (; *e != NULL; e++) {
Victor Stinner8c62be82010-05-06 00:08:46 +00001448 PyObject *k;
1449 PyObject *v;
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001450#ifdef MS_WINDOWS
1451 const wchar_t *p = wcschr(*e, L'=');
1452#else
Serhiy Storchakadeab18d2016-05-07 16:45:18 +03001453 const char *p = strchr(*e, '=');
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001454#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00001455 if (p == NULL)
1456 continue;
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001457#ifdef MS_WINDOWS
1458 k = PyUnicode_FromWideChar(*e, (Py_ssize_t)(p-*e));
1459#else
Victor Stinner84ae1182010-05-06 22:05:07 +00001460 k = PyBytes_FromStringAndSize(*e, (int)(p-*e));
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001461#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00001462 if (k == NULL) {
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#ifdef MS_WINDOWS
1467 v = PyUnicode_FromWideChar(p+1, wcslen(p+1));
1468#else
Victor Stinner84ae1182010-05-06 22:05:07 +00001469 v = PyBytes_FromStringAndSize(p+1, strlen(p+1));
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001470#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00001471 if (v == NULL) {
Victor Stinner8c62be82010-05-06 00:08:46 +00001472 Py_DECREF(k);
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001473 Py_DECREF(d);
1474 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00001475 }
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001476 if (PyDict_GetItemWithError(d, k) == NULL) {
1477 if (PyErr_Occurred() || PyDict_SetItem(d, k, v) != 0) {
1478 Py_DECREF(v);
1479 Py_DECREF(k);
1480 Py_DECREF(d);
1481 return NULL;
1482 }
Victor Stinner8c62be82010-05-06 00:08:46 +00001483 }
1484 Py_DECREF(k);
1485 Py_DECREF(v);
Guido van Rossumd48f2521997-12-05 22:19:34 +00001486 }
Victor Stinner8c62be82010-05-06 00:08:46 +00001487 return d;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001488}
1489
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001490/* Set a POSIX-specific error from errno, and return NULL */
1491
Barry Warsawd58d7641998-07-23 16:14:40 +00001492static PyObject *
Thomas Woutersf3f33dc2000-07-21 06:00:07 +00001493posix_error(void)
Guido van Rossumad0ee831995-03-01 10:34:45 +00001494{
Victor Stinner8c62be82010-05-06 00:08:46 +00001495 return PyErr_SetFromErrno(PyExc_OSError);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001496}
Mark Hammondef8b6542001-05-13 08:04:26 +00001497
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001498#ifdef MS_WINDOWS
Fredrik Lundhffb9c772000-07-09 14:49:51 +00001499static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001500win32_error(const char* function, const char* filename)
Fredrik Lundhffb9c772000-07-09 14:49:51 +00001501{
Victor Stinner8c62be82010-05-06 00:08:46 +00001502 /* XXX We should pass the function name along in the future.
1503 (winreg.c also wants to pass the function name.)
1504 This would however require an additional param to the
1505 Windows error object, which is non-trivial.
1506 */
1507 errno = GetLastError();
1508 if (filename)
1509 return PyErr_SetFromWindowsErrWithFilename(errno, filename);
1510 else
1511 return PyErr_SetFromWindowsErr(errno);
Fredrik Lundhffb9c772000-07-09 14:49:51 +00001512}
Mark Hammondc2e85bd2002-10-03 05:10:39 +00001513
Mark Hammondc2e85bd2002-10-03 05:10:39 +00001514static PyObject *
Steve Dower2438cdf2019-03-29 16:37:16 -07001515win32_error_object_err(const char* function, PyObject* filename, DWORD err)
Victor Stinnereb5657a2011-09-30 01:44:27 +02001516{
1517 /* XXX - see win32_error for comments on 'function' */
Victor Stinnereb5657a2011-09-30 01:44:27 +02001518 if (filename)
1519 return PyErr_SetExcFromWindowsErrWithFilenameObject(
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02001520 PyExc_OSError,
Steve Dower2438cdf2019-03-29 16:37:16 -07001521 err,
Victor Stinnereb5657a2011-09-30 01:44:27 +02001522 filename);
1523 else
Steve Dower2438cdf2019-03-29 16:37:16 -07001524 return PyErr_SetFromWindowsErr(err);
1525}
1526
1527static PyObject *
1528win32_error_object(const char* function, PyObject* filename)
1529{
1530 errno = GetLastError();
1531 return win32_error_object_err(function, filename, errno);
Victor Stinnereb5657a2011-09-30 01:44:27 +02001532}
1533
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00001534#endif /* MS_WINDOWS */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001535
Larry Hastings9cf065c2012-06-22 16:30:09 -07001536static PyObject *
Alexey Izbyshev83460312018-10-20 03:28:22 +03001537posix_path_object_error(PyObject *path)
1538{
1539 return PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, path);
1540}
1541
1542static PyObject *
Serhiy Storchaka2674bc72016-10-08 20:16:57 +03001543path_object_error(PyObject *path)
Larry Hastings9cf065c2012-06-22 16:30:09 -07001544{
1545#ifdef MS_WINDOWS
Serhiy Storchaka2674bc72016-10-08 20:16:57 +03001546 return PyErr_SetExcFromWindowsErrWithFilenameObject(
1547 PyExc_OSError, 0, path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07001548#else
Alexey Izbyshev83460312018-10-20 03:28:22 +03001549 return posix_path_object_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07001550#endif
1551}
1552
Serhiy Storchaka2674bc72016-10-08 20:16:57 +03001553static PyObject *
1554path_object_error2(PyObject *path, PyObject *path2)
1555{
1556#ifdef MS_WINDOWS
1557 return PyErr_SetExcFromWindowsErrWithFilenameObjects(
1558 PyExc_OSError, 0, path, path2);
1559#else
1560 return PyErr_SetFromErrnoWithFilenameObjects(PyExc_OSError, path, path2);
1561#endif
1562}
1563
1564static PyObject *
1565path_error(path_t *path)
1566{
1567 return path_object_error(path->object);
1568}
Larry Hastings31826802013-10-19 00:09:25 -07001569
Larry Hastingsb0827312014-02-09 22:05:19 -08001570static PyObject *
Alexey Izbyshev83460312018-10-20 03:28:22 +03001571posix_path_error(path_t *path)
1572{
1573 return posix_path_object_error(path->object);
1574}
1575
1576static PyObject *
Larry Hastingsb0827312014-02-09 22:05:19 -08001577path_error2(path_t *path, path_t *path2)
1578{
Serhiy Storchaka2674bc72016-10-08 20:16:57 +03001579 return path_object_error2(path->object, path2->object);
Larry Hastingsb0827312014-02-09 22:05:19 -08001580}
1581
1582
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001583/* POSIX generic methods */
1584
Larry Hastings2f936352014-08-05 14:04:04 +10001585static int
1586fildes_converter(PyObject *o, void *p)
Fred Drake4d1e64b2002-04-15 19:40:07 +00001587{
Victor Stinner8c62be82010-05-06 00:08:46 +00001588 int fd;
Larry Hastings2f936352014-08-05 14:04:04 +10001589 int *pointer = (int *)p;
1590 fd = PyObject_AsFileDescriptor(o);
Victor Stinner8c62be82010-05-06 00:08:46 +00001591 if (fd < 0)
Larry Hastings2f936352014-08-05 14:04:04 +10001592 return 0;
Larry Hastings2f936352014-08-05 14:04:04 +10001593 *pointer = fd;
1594 return 1;
1595}
1596
1597static PyObject *
1598posix_fildes_fd(int fd, int (*func)(int))
1599{
1600 int res;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00001601 int async_err = 0;
1602
1603 do {
1604 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04001605 _Py_BEGIN_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00001606 res = (*func)(fd);
Steve Dower8fc89802015-04-12 00:26:27 -04001607 _Py_END_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00001608 Py_END_ALLOW_THREADS
1609 } while (res != 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
1610 if (res != 0)
1611 return (!async_err) ? posix_error() : NULL;
1612 Py_RETURN_NONE;
Fred Drake4d1e64b2002-04-15 19:40:07 +00001613}
Guido van Rossum21142a01999-01-08 21:05:37 +00001614
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001615
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00001616#ifdef MS_WINDOWS
Thomas Wouters477c8d52006-05-27 19:21:47 +00001617/* This is a reimplementation of the C library's chdir function,
1618 but one that produces Win32 errors instead of DOS error codes.
1619 chdir is essentially a wrapper around SetCurrentDirectory; however,
1620 it also needs to set "magic" environment variables indicating
1621 the per-drive current directory, which are of the form =<drive>: */
Benjamin Peterson206e3072008-10-19 14:07:49 +00001622static BOOL __stdcall
Thomas Wouters477c8d52006-05-27 19:21:47 +00001623win32_wchdir(LPCWSTR path)
1624{
Victor Stinnered537822015-12-13 21:40:26 +01001625 wchar_t path_buf[MAX_PATH], *new_path = path_buf;
Victor Stinner8c62be82010-05-06 00:08:46 +00001626 int result;
1627 wchar_t env[4] = L"=x:";
Thomas Wouters477c8d52006-05-27 19:21:47 +00001628
Victor Stinner8c62be82010-05-06 00:08:46 +00001629 if(!SetCurrentDirectoryW(path))
1630 return FALSE;
Victor Stinnered537822015-12-13 21:40:26 +01001631 result = GetCurrentDirectoryW(Py_ARRAY_LENGTH(path_buf), new_path);
Victor Stinner8c62be82010-05-06 00:08:46 +00001632 if (!result)
1633 return FALSE;
Victor Stinnere847d712015-12-14 00:21:50 +01001634 if (result > Py_ARRAY_LENGTH(path_buf)) {
Victor Stinnerb6404912013-07-07 16:21:41 +02001635 new_path = PyMem_RawMalloc(result * sizeof(wchar_t));
Victor Stinner8c62be82010-05-06 00:08:46 +00001636 if (!new_path) {
1637 SetLastError(ERROR_OUTOFMEMORY);
1638 return FALSE;
1639 }
1640 result = GetCurrentDirectoryW(result, new_path);
1641 if (!result) {
Victor Stinnerb6404912013-07-07 16:21:41 +02001642 PyMem_RawFree(new_path);
Victor Stinner8c62be82010-05-06 00:08:46 +00001643 return FALSE;
1644 }
1645 }
Alexey Izbyshev3e197c72018-03-01 12:13:56 +03001646 int is_unc_like_path = (wcsncmp(new_path, L"\\\\", 2) == 0 ||
1647 wcsncmp(new_path, L"//", 2) == 0);
1648 if (!is_unc_like_path) {
1649 env[1] = new_path[0];
1650 result = SetEnvironmentVariableW(env, new_path);
1651 }
Victor Stinnered537822015-12-13 21:40:26 +01001652 if (new_path != path_buf)
Victor Stinnerb6404912013-07-07 16:21:41 +02001653 PyMem_RawFree(new_path);
Alexey Izbyshev3e197c72018-03-01 12:13:56 +03001654 return result ? TRUE : FALSE;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001655}
1656#endif
1657
Martin v. Löwis14694662006-02-03 12:54:16 +00001658#ifdef MS_WINDOWS
1659/* The CRT of Windows has a number of flaws wrt. its stat() implementation:
1660 - time stamps are restricted to second resolution
1661 - file modification times suffer from forth-and-back conversions between
1662 UTC and local time
1663 Therefore, we implement our own stat, based on the Win32 API directly.
1664*/
Victor Stinner8c62be82010-05-06 00:08:46 +00001665#define HAVE_STAT_NSEC 1
Zachary Ware63f277b2014-06-19 09:46:37 -05001666#define HAVE_STRUCT_STAT_ST_FILE_ATTRIBUTES 1
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001667#define HAVE_STRUCT_STAT_ST_REPARSE_TAG 1
Martin v. Löwis14694662006-02-03 12:54:16 +00001668
Victor Stinner6036e442015-03-08 01:58:04 +01001669static void
Steve Dowercc16be82016-09-08 10:35:16 -07001670find_data_to_file_info(WIN32_FIND_DATAW *pFileData,
1671 BY_HANDLE_FILE_INFORMATION *info,
1672 ULONG *reparse_tag)
Victor Stinner6036e442015-03-08 01:58:04 +01001673{
1674 memset(info, 0, sizeof(*info));
1675 info->dwFileAttributes = pFileData->dwFileAttributes;
1676 info->ftCreationTime = pFileData->ftCreationTime;
1677 info->ftLastAccessTime = pFileData->ftLastAccessTime;
1678 info->ftLastWriteTime = pFileData->ftLastWriteTime;
1679 info->nFileSizeHigh = pFileData->nFileSizeHigh;
1680 info->nFileSizeLow = pFileData->nFileSizeLow;
1681/* info->nNumberOfLinks = 1; */
1682 if (pFileData->dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT)
1683 *reparse_tag = pFileData->dwReserved0;
1684 else
1685 *reparse_tag = 0;
1686}
1687
Guido van Rossumd8faa362007-04-27 19:54:29 +00001688static BOOL
Steve Dowercc16be82016-09-08 10:35:16 -07001689attributes_from_dir(LPCWSTR pszFile, BY_HANDLE_FILE_INFORMATION *info, ULONG *reparse_tag)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001690{
Victor Stinner8c62be82010-05-06 00:08:46 +00001691 HANDLE hFindFile;
1692 WIN32_FIND_DATAW FileData;
1693 hFindFile = FindFirstFileW(pszFile, &FileData);
1694 if (hFindFile == INVALID_HANDLE_VALUE)
1695 return FALSE;
1696 FindClose(hFindFile);
Steve Dowercc16be82016-09-08 10:35:16 -07001697 find_data_to_file_info(&FileData, info, reparse_tag);
Victor Stinner8c62be82010-05-06 00:08:46 +00001698 return TRUE;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001699}
1700
Brian Curtind25aef52011-06-13 15:16:04 -05001701static int
Steve Dowercc16be82016-09-08 10:35:16 -07001702win32_xstat_impl(const wchar_t *path, struct _Py_stat_struct *result,
Brian Curtind25aef52011-06-13 15:16:04 -05001703 BOOL traverse)
1704{
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001705 HANDLE hFile;
1706 BY_HANDLE_FILE_INFORMATION fileInfo;
1707 FILE_ATTRIBUTE_TAG_INFO tagInfo = { 0 };
1708 DWORD fileType, error;
1709 BOOL isUnhandledTag = FALSE;
1710 int retval = 0;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001711
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001712 DWORD access = FILE_READ_ATTRIBUTES;
1713 DWORD flags = FILE_FLAG_BACKUP_SEMANTICS; /* Allow opening directories. */
1714 if (!traverse) {
1715 flags |= FILE_FLAG_OPEN_REPARSE_POINT;
1716 }
Brian Curtinf5e76d02010-11-24 13:14:05 +00001717
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001718 hFile = CreateFileW(path, access, 0, NULL, OPEN_EXISTING, flags, NULL);
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001719 if (hFile == INVALID_HANDLE_VALUE) {
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001720 /* Either the path doesn't exist, or the caller lacks access. */
1721 error = GetLastError();
1722 switch (error) {
1723 case ERROR_ACCESS_DENIED: /* Cannot sync or read attributes. */
1724 case ERROR_SHARING_VIOLATION: /* It's a paging file. */
1725 /* Try reading the parent directory. */
1726 if (!attributes_from_dir(path, &fileInfo, &tagInfo.ReparseTag)) {
1727 /* Cannot read the parent directory. */
1728 SetLastError(error);
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001729 return -1;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001730 }
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001731 if (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1732 if (traverse ||
1733 !IsReparseTagNameSurrogate(tagInfo.ReparseTag)) {
1734 /* The stat call has to traverse but cannot, so fail. */
1735 SetLastError(error);
Brian Curtind25aef52011-06-13 15:16:04 -05001736 return -1;
Mark Becwarb82bfac2019-02-02 16:08:23 -05001737 }
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001738 }
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001739 break;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001740
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001741 case ERROR_INVALID_PARAMETER:
1742 /* \\.\con requires read or write access. */
1743 hFile = CreateFileW(path, access | GENERIC_READ,
1744 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
1745 OPEN_EXISTING, flags, NULL);
1746 if (hFile == INVALID_HANDLE_VALUE) {
1747 SetLastError(error);
1748 return -1;
1749 }
1750 break;
1751
1752 case ERROR_CANT_ACCESS_FILE:
1753 /* bpo37834: open unhandled reparse points if traverse fails. */
1754 if (traverse) {
1755 traverse = FALSE;
1756 isUnhandledTag = TRUE;
1757 hFile = CreateFileW(path, access, 0, NULL, OPEN_EXISTING,
1758 flags | FILE_FLAG_OPEN_REPARSE_POINT, NULL);
1759 }
1760 if (hFile == INVALID_HANDLE_VALUE) {
1761 SetLastError(error);
1762 return -1;
1763 }
1764 break;
1765
1766 default:
1767 return -1;
1768 }
Brian Curtinf5e76d02010-11-24 13:14:05 +00001769 }
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001770
1771 if (hFile != INVALID_HANDLE_VALUE) {
1772 /* Handle types other than files on disk. */
1773 fileType = GetFileType(hFile);
1774 if (fileType != FILE_TYPE_DISK) {
1775 if (fileType == FILE_TYPE_UNKNOWN && GetLastError() != 0) {
1776 retval = -1;
1777 goto cleanup;
1778 }
1779 DWORD fileAttributes = GetFileAttributesW(path);
1780 memset(result, 0, sizeof(*result));
1781 if (fileAttributes != INVALID_FILE_ATTRIBUTES &&
1782 fileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
1783 /* \\.\pipe\ or \\.\mailslot\ */
1784 result->st_mode = _S_IFDIR;
1785 } else if (fileType == FILE_TYPE_CHAR) {
1786 /* \\.\nul */
1787 result->st_mode = _S_IFCHR;
1788 } else if (fileType == FILE_TYPE_PIPE) {
1789 /* \\.\pipe\spam */
1790 result->st_mode = _S_IFIFO;
1791 }
1792 /* FILE_TYPE_UNKNOWN, e.g. \\.\mailslot\waitfor.exe\spam */
1793 goto cleanup;
1794 }
1795
1796 /* Query the reparse tag, and traverse a non-link. */
1797 if (!traverse) {
1798 if (!GetFileInformationByHandleEx(hFile, FileAttributeTagInfo,
1799 &tagInfo, sizeof(tagInfo))) {
1800 /* Allow devices that do not support FileAttributeTagInfo. */
1801 switch (GetLastError()) {
1802 case ERROR_INVALID_PARAMETER:
1803 case ERROR_INVALID_FUNCTION:
1804 case ERROR_NOT_SUPPORTED:
1805 tagInfo.FileAttributes = FILE_ATTRIBUTE_NORMAL;
1806 tagInfo.ReparseTag = 0;
1807 break;
1808 default:
1809 retval = -1;
1810 goto cleanup;
1811 }
1812 } else if (tagInfo.FileAttributes &
1813 FILE_ATTRIBUTE_REPARSE_POINT) {
1814 if (IsReparseTagNameSurrogate(tagInfo.ReparseTag)) {
1815 if (isUnhandledTag) {
1816 /* Traversing previously failed for either this link
1817 or its target. */
1818 SetLastError(ERROR_CANT_ACCESS_FILE);
1819 retval = -1;
1820 goto cleanup;
1821 }
1822 /* Traverse a non-link, but not if traversing already failed
1823 for an unhandled tag. */
1824 } else if (!isUnhandledTag) {
1825 CloseHandle(hFile);
1826 return win32_xstat_impl(path, result, TRUE);
1827 }
1828 }
1829 }
1830
1831 if (!GetFileInformationByHandle(hFile, &fileInfo)) {
1832 switch (GetLastError()) {
1833 case ERROR_INVALID_PARAMETER:
1834 case ERROR_INVALID_FUNCTION:
1835 case ERROR_NOT_SUPPORTED:
Steve Dower772ec0f2019-09-04 14:42:54 -07001836 /* Volumes and physical disks are block devices, e.g.
1837 \\.\C: and \\.\PhysicalDrive0. */
1838 memset(result, 0, sizeof(*result));
1839 result->st_mode = 0x6000; /* S_IFBLK */
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001840 goto cleanup;
1841 }
Steve Dower772ec0f2019-09-04 14:42:54 -07001842 retval = -1;
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001843 goto cleanup;
1844 }
1845 }
1846
1847 _Py_attribute_data_to_stat(&fileInfo, tagInfo.ReparseTag, result);
1848
1849 if (!(fileInfo.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
1850 /* Fix the file execute permissions. This hack sets S_IEXEC if
1851 the filename has an extension that is commonly used by files
1852 that CreateProcessW can execute. A real implementation calls
1853 GetSecurityInfo, OpenThreadToken/OpenProcessToken, and
1854 AccessCheck to check for generic read, write, and execute
1855 access. */
1856 const wchar_t *fileExtension = wcsrchr(path, '.');
1857 if (fileExtension) {
1858 if (_wcsicmp(fileExtension, L".exe") == 0 ||
1859 _wcsicmp(fileExtension, L".bat") == 0 ||
1860 _wcsicmp(fileExtension, L".cmd") == 0 ||
1861 _wcsicmp(fileExtension, L".com") == 0) {
1862 result->st_mode |= 0111;
1863 }
1864 }
1865 }
1866
1867cleanup:
1868 if (hFile != INVALID_HANDLE_VALUE) {
Steve Dower772ec0f2019-09-04 14:42:54 -07001869 /* Preserve last error if we are failing */
1870 error = retval ? GetLastError() : 0;
1871 if (!CloseHandle(hFile)) {
1872 retval = -1;
1873 } else if (retval) {
1874 /* Restore last error */
1875 SetLastError(error);
1876 }
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001877 }
1878
1879 return retval;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001880}
1881
1882static int
Steve Dowercc16be82016-09-08 10:35:16 -07001883win32_xstat(const wchar_t *path, struct _Py_stat_struct *result, BOOL traverse)
Brian Curtinf5e76d02010-11-24 13:14:05 +00001884{
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001885 /* Protocol violation: we explicitly clear errno, instead of
1886 setting it to a POSIX error. Callers should use GetLastError. */
Brian Curtind25aef52011-06-13 15:16:04 -05001887 int code = win32_xstat_impl(path, result, traverse);
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001888 errno = 0;
1889 return code;
1890}
Brian Curtind25aef52011-06-13 15:16:04 -05001891/* About the following functions: win32_lstat_w, win32_stat, win32_stat_w
Brian Curtind40e6f72010-07-08 21:39:08 +00001892
1893 In Posix, stat automatically traverses symlinks and returns the stat
1894 structure for the target. In Windows, the equivalent GetFileAttributes by
1895 default does not traverse symlinks and instead returns attributes for
1896 the symlink.
1897
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001898 Instead, we will open the file (which *does* traverse symlinks by default)
1899 and GetFileInformationByHandle(). */
Brian Curtind40e6f72010-07-08 21:39:08 +00001900
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001901static int
Steve Dowercc16be82016-09-08 10:35:16 -07001902win32_lstat(const wchar_t* path, struct _Py_stat_struct *result)
Martin v. Löwis14694662006-02-03 12:54:16 +00001903{
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001904 return win32_xstat(path, result, FALSE);
Martin v. Löwis14694662006-02-03 12:54:16 +00001905}
1906
Victor Stinner8c62be82010-05-06 00:08:46 +00001907static int
Steve Dowercc16be82016-09-08 10:35:16 -07001908win32_stat(const wchar_t* path, struct _Py_stat_struct *result)
Brian Curtind40e6f72010-07-08 21:39:08 +00001909{
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001910 return win32_xstat(path, result, TRUE);
Brian Curtind40e6f72010-07-08 21:39:08 +00001911}
1912
Martin v. Löwis14694662006-02-03 12:54:16 +00001913#endif /* MS_WINDOWS */
1914
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001915PyDoc_STRVAR(stat_result__doc__,
Larry Hastings9cf065c2012-06-22 16:30:09 -07001916"stat_result: Result from stat, fstat, or lstat.\n\n\
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001917This object may be accessed either as a tuple of\n\
Fred Drakef7ce04d2002-06-20 18:31:21 +00001918 (mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime)\n\
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001919or via the attributes st_mode, st_ino, st_dev, st_nlink, st_uid, and so on.\n\
1920\n\
Hye-Shik Chang5f937a72005-06-02 13:09:30 +00001921Posix/windows: If your platform supports st_blksize, st_blocks, st_rdev,\n\
1922or st_flags, they are available as attributes only.\n\
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001923\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001924See os.stat for more information.");
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001925
1926static PyStructSequence_Field stat_result_fields[] = {
Victor Stinner8c62be82010-05-06 00:08:46 +00001927 {"st_mode", "protection bits"},
1928 {"st_ino", "inode"},
1929 {"st_dev", "device"},
1930 {"st_nlink", "number of hard links"},
1931 {"st_uid", "user ID of owner"},
1932 {"st_gid", "group ID of owner"},
1933 {"st_size", "total size, in bytes"},
1934 /* The NULL is replaced with PyStructSequence_UnnamedField later. */
1935 {NULL, "integer time of last access"},
1936 {NULL, "integer time of last modification"},
1937 {NULL, "integer time of last change"},
1938 {"st_atime", "time of last access"},
1939 {"st_mtime", "time of last modification"},
1940 {"st_ctime", "time of last change"},
Larry Hastings6fe20b32012-04-19 15:07:49 -07001941 {"st_atime_ns", "time of last access in nanoseconds"},
1942 {"st_mtime_ns", "time of last modification in nanoseconds"},
1943 {"st_ctime_ns", "time of last change in nanoseconds"},
Martin v. Löwis60a5d722002-10-16 20:28:25 +00001944#ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
Victor Stinner8c62be82010-05-06 00:08:46 +00001945 {"st_blksize", "blocksize for filesystem I/O"},
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001946#endif
Martin v. Löwis60a5d722002-10-16 20:28:25 +00001947#ifdef HAVE_STRUCT_STAT_ST_BLOCKS
Victor Stinner8c62be82010-05-06 00:08:46 +00001948 {"st_blocks", "number of blocks allocated"},
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001949#endif
Martin v. Löwis60a5d722002-10-16 20:28:25 +00001950#ifdef HAVE_STRUCT_STAT_ST_RDEV
Victor Stinner8c62be82010-05-06 00:08:46 +00001951 {"st_rdev", "device type (if inode device)"},
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001952#endif
Hye-Shik Chang5f937a72005-06-02 13:09:30 +00001953#ifdef HAVE_STRUCT_STAT_ST_FLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +00001954 {"st_flags", "user defined flags for file"},
Hye-Shik Chang5f937a72005-06-02 13:09:30 +00001955#endif
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00001956#ifdef HAVE_STRUCT_STAT_ST_GEN
Victor Stinner8c62be82010-05-06 00:08:46 +00001957 {"st_gen", "generation number"},
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00001958#endif
1959#ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME
Victor Stinner8c62be82010-05-06 00:08:46 +00001960 {"st_birthtime", "time of creation"},
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00001961#endif
Zachary Ware63f277b2014-06-19 09:46:37 -05001962#ifdef HAVE_STRUCT_STAT_ST_FILE_ATTRIBUTES
1963 {"st_file_attributes", "Windows file attribute bits"},
1964#endif
jcea6c51d512018-01-28 14:00:08 +01001965#ifdef HAVE_STRUCT_STAT_ST_FSTYPE
1966 {"st_fstype", "Type of filesystem"},
1967#endif
Steve Dowerdf2d4a62019-08-21 15:27:33 -07001968#ifdef HAVE_STRUCT_STAT_ST_REPARSE_TAG
1969 {"st_reparse_tag", "Windows reparse tag"},
1970#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00001971 {0}
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001972};
1973
Martin v. Löwis60a5d722002-10-16 20:28:25 +00001974#ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
Larry Hastings6fe20b32012-04-19 15:07:49 -07001975#define ST_BLKSIZE_IDX 16
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001976#else
Larry Hastings6fe20b32012-04-19 15:07:49 -07001977#define ST_BLKSIZE_IDX 15
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001978#endif
1979
Martin v. Löwis60a5d722002-10-16 20:28:25 +00001980#ifdef HAVE_STRUCT_STAT_ST_BLOCKS
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001981#define ST_BLOCKS_IDX (ST_BLKSIZE_IDX+1)
1982#else
1983#define ST_BLOCKS_IDX ST_BLKSIZE_IDX
1984#endif
1985
Martin v. Löwis60a5d722002-10-16 20:28:25 +00001986#ifdef HAVE_STRUCT_STAT_ST_RDEV
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001987#define ST_RDEV_IDX (ST_BLOCKS_IDX+1)
1988#else
1989#define ST_RDEV_IDX ST_BLOCKS_IDX
1990#endif
1991
Hye-Shik Chang5f937a72005-06-02 13:09:30 +00001992#ifdef HAVE_STRUCT_STAT_ST_FLAGS
1993#define ST_FLAGS_IDX (ST_RDEV_IDX+1)
1994#else
1995#define ST_FLAGS_IDX ST_RDEV_IDX
1996#endif
1997
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00001998#ifdef HAVE_STRUCT_STAT_ST_GEN
Martin v. Löwisf09582e2005-08-14 21:42:34 +00001999#define ST_GEN_IDX (ST_FLAGS_IDX+1)
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002000#else
Martin v. Löwisf09582e2005-08-14 21:42:34 +00002001#define ST_GEN_IDX ST_FLAGS_IDX
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002002#endif
2003
2004#ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME
2005#define ST_BIRTHTIME_IDX (ST_GEN_IDX+1)
2006#else
2007#define ST_BIRTHTIME_IDX ST_GEN_IDX
2008#endif
2009
Zachary Ware63f277b2014-06-19 09:46:37 -05002010#ifdef HAVE_STRUCT_STAT_ST_FILE_ATTRIBUTES
2011#define ST_FILE_ATTRIBUTES_IDX (ST_BIRTHTIME_IDX+1)
2012#else
2013#define ST_FILE_ATTRIBUTES_IDX ST_BIRTHTIME_IDX
2014#endif
2015
jcea6c51d512018-01-28 14:00:08 +01002016#ifdef HAVE_STRUCT_STAT_ST_FSTYPE
2017#define ST_FSTYPE_IDX (ST_FILE_ATTRIBUTES_IDX+1)
2018#else
2019#define ST_FSTYPE_IDX ST_FILE_ATTRIBUTES_IDX
2020#endif
2021
Steve Dowerdf2d4a62019-08-21 15:27:33 -07002022#ifdef HAVE_STRUCT_STAT_ST_REPARSE_TAG
2023#define ST_REPARSE_TAG_IDX (ST_FSTYPE_IDX+1)
2024#else
2025#define ST_REPARSE_TAG_IDX ST_FSTYPE_IDX
2026#endif
2027
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002028static PyStructSequence_Desc stat_result_desc = {
Victor Stinner8c62be82010-05-06 00:08:46 +00002029 "stat_result", /* name */
2030 stat_result__doc__, /* doc */
2031 stat_result_fields,
2032 10
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002033};
2034
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002035PyDoc_STRVAR(statvfs_result__doc__,
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002036"statvfs_result: Result from statvfs or fstatvfs.\n\n\
2037This object may be accessed either as a tuple of\n\
Fred Drakef7ce04d2002-06-20 18:31:21 +00002038 (bsize, frsize, blocks, bfree, bavail, files, ffree, favail, flag, namemax),\n\
Guido van Rossuma4dc73e2001-10-18 20:53:15 +00002039or via the attributes f_bsize, f_frsize, f_blocks, f_bfree, and so on.\n\
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002040\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002041See os.statvfs for more information.");
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002042
2043static PyStructSequence_Field statvfs_result_fields[] = {
Victor Stinner8c62be82010-05-06 00:08:46 +00002044 {"f_bsize", },
2045 {"f_frsize", },
2046 {"f_blocks", },
2047 {"f_bfree", },
2048 {"f_bavail", },
2049 {"f_files", },
2050 {"f_ffree", },
2051 {"f_favail", },
2052 {"f_flag", },
2053 {"f_namemax",},
Giuseppe Scrivano96a5e502017-12-14 23:46:46 +01002054 {"f_fsid", },
Victor Stinner8c62be82010-05-06 00:08:46 +00002055 {0}
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002056};
2057
2058static PyStructSequence_Desc statvfs_result_desc = {
Victor Stinner8c62be82010-05-06 00:08:46 +00002059 "statvfs_result", /* name */
2060 statvfs_result__doc__, /* doc */
2061 statvfs_result_fields,
2062 10
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002063};
2064
Ross Lagerwall7807c352011-03-17 20:20:30 +02002065#if defined(HAVE_WAITID) && !defined(__APPLE__)
2066PyDoc_STRVAR(waitid_result__doc__,
2067"waitid_result: Result from waitid.\n\n\
2068This object may be accessed either as a tuple of\n\
2069 (si_pid, si_uid, si_signo, si_status, si_code),\n\
2070or via the attributes si_pid, si_uid, and so on.\n\
2071\n\
2072See os.waitid for more information.");
2073
2074static PyStructSequence_Field waitid_result_fields[] = {
2075 {"si_pid", },
2076 {"si_uid", },
2077 {"si_signo", },
2078 {"si_status", },
2079 {"si_code", },
2080 {0}
2081};
2082
2083static PyStructSequence_Desc waitid_result_desc = {
2084 "waitid_result", /* name */
2085 waitid_result__doc__, /* doc */
2086 waitid_result_fields,
2087 5
2088};
Benjamin Petersonbad9c2f2011-08-02 18:42:14 -05002089#endif
Martin v. Löwisf607bda2002-10-16 18:27:39 +00002090static newfunc structseq_new;
2091
2092static PyObject *
2093statresult_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2094{
Victor Stinner8c62be82010-05-06 00:08:46 +00002095 PyStructSequence *result;
2096 int i;
Martin v. Löwisf607bda2002-10-16 18:27:39 +00002097
Victor Stinner8c62be82010-05-06 00:08:46 +00002098 result = (PyStructSequence*)structseq_new(type, args, kwds);
2099 if (!result)
2100 return NULL;
2101 /* If we have been initialized from a tuple,
2102 st_?time might be set to None. Initialize it
2103 from the int slots. */
2104 for (i = 7; i <= 9; i++) {
2105 if (result->ob_item[i+3] == Py_None) {
2106 Py_DECREF(Py_None);
2107 Py_INCREF(result->ob_item[i]);
2108 result->ob_item[i+3] = result->ob_item[i];
2109 }
2110 }
2111 return (PyObject*)result;
Martin v. Löwisf607bda2002-10-16 18:27:39 +00002112}
2113
Eddie Elizondob3966632019-11-05 07:16:14 -08002114static int
2115_posix_clear(PyObject *module)
2116{
2117 Py_CLEAR(_posixstate(module)->billion);
Victor Stinner623ed612020-01-21 19:25:32 +01002118#ifdef PY_PUTENV_DICT
2119 Py_CLEAR(_posixstate(module)->putenv_dict);
2120#endif
Eddie Elizondob3966632019-11-05 07:16:14 -08002121 Py_CLEAR(_posixstate(module)->DirEntryType);
2122 Py_CLEAR(_posixstate(module)->ScandirIteratorType);
2123#if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
2124 Py_CLEAR(_posixstate(module)->SchedParamType);
2125#endif
2126 Py_CLEAR(_posixstate(module)->StatResultType);
2127 Py_CLEAR(_posixstate(module)->StatVFSResultType);
2128 Py_CLEAR(_posixstate(module)->TerminalSizeType);
2129 Py_CLEAR(_posixstate(module)->TimesResultType);
2130 Py_CLEAR(_posixstate(module)->UnameResultType);
2131#if defined(HAVE_WAITID) && !defined(__APPLE__)
2132 Py_CLEAR(_posixstate(module)->WaitidResultType);
2133#endif
2134#if defined(HAVE_WAIT3) || defined(HAVE_WAIT4)
2135 Py_CLEAR(_posixstate(module)->struct_rusage);
2136#endif
2137 Py_CLEAR(_posixstate(module)->st_mode);
2138 return 0;
2139}
Martin v. Löwisf607bda2002-10-16 18:27:39 +00002140
Eddie Elizondob3966632019-11-05 07:16:14 -08002141static int
2142_posix_traverse(PyObject *module, visitproc visit, void *arg)
2143{
2144 Py_VISIT(_posixstate(module)->billion);
Victor Stinner623ed612020-01-21 19:25:32 +01002145#ifdef PY_PUTENV_DICT
2146 Py_VISIT(_posixstate(module)->putenv_dict);
2147#endif
Eddie Elizondob3966632019-11-05 07:16:14 -08002148 Py_VISIT(_posixstate(module)->DirEntryType);
2149 Py_VISIT(_posixstate(module)->ScandirIteratorType);
2150#if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
2151 Py_VISIT(_posixstate(module)->SchedParamType);
2152#endif
2153 Py_VISIT(_posixstate(module)->StatResultType);
2154 Py_VISIT(_posixstate(module)->StatVFSResultType);
2155 Py_VISIT(_posixstate(module)->TerminalSizeType);
2156 Py_VISIT(_posixstate(module)->TimesResultType);
2157 Py_VISIT(_posixstate(module)->UnameResultType);
2158#if defined(HAVE_WAITID) && !defined(__APPLE__)
2159 Py_VISIT(_posixstate(module)->WaitidResultType);
2160#endif
2161#if defined(HAVE_WAIT3) || defined(HAVE_WAIT4)
2162 Py_VISIT(_posixstate(module)->struct_rusage);
2163#endif
2164 Py_VISIT(_posixstate(module)->st_mode);
2165 return 0;
2166}
2167
2168static void
2169_posix_free(void *module)
2170{
2171 _posix_clear((PyObject *)module);
2172}
Larry Hastings6fe20b32012-04-19 15:07:49 -07002173
Martin v. Löwis94717ed2002-09-09 14:24:16 +00002174static void
Victor Stinner4195b5c2012-02-08 23:03:19 +01002175fill_time(PyObject *v, int index, time_t sec, unsigned long nsec)
Martin v. Löwis94717ed2002-09-09 14:24:16 +00002176{
Larry Hastings6fe20b32012-04-19 15:07:49 -07002177 PyObject *s = _PyLong_FromTime_t(sec);
2178 PyObject *ns_fractional = PyLong_FromUnsignedLong(nsec);
2179 PyObject *s_in_ns = NULL;
2180 PyObject *ns_total = NULL;
2181 PyObject *float_s = NULL;
2182
2183 if (!(s && ns_fractional))
2184 goto exit;
2185
Eddie Elizondob3966632019-11-05 07:16:14 -08002186 s_in_ns = PyNumber_Multiply(s, _posixstate_global->billion);
Larry Hastings6fe20b32012-04-19 15:07:49 -07002187 if (!s_in_ns)
2188 goto exit;
2189
2190 ns_total = PyNumber_Add(s_in_ns, ns_fractional);
2191 if (!ns_total)
2192 goto exit;
2193
Victor Stinner01b5aab2017-10-24 02:02:00 -07002194 float_s = PyFloat_FromDouble(sec + 1e-9*nsec);
2195 if (!float_s) {
2196 goto exit;
Larry Hastings6fe20b32012-04-19 15:07:49 -07002197 }
2198
2199 PyStructSequence_SET_ITEM(v, index, s);
2200 PyStructSequence_SET_ITEM(v, index+3, float_s);
2201 PyStructSequence_SET_ITEM(v, index+6, ns_total);
2202 s = NULL;
2203 float_s = NULL;
2204 ns_total = NULL;
2205exit:
2206 Py_XDECREF(s);
2207 Py_XDECREF(ns_fractional);
2208 Py_XDECREF(s_in_ns);
2209 Py_XDECREF(ns_total);
2210 Py_XDECREF(float_s);
Martin v. Löwis94717ed2002-09-09 14:24:16 +00002211}
2212
Tim Peters5aa91602002-01-30 05:46:57 +00002213/* pack a system stat C structure into the Python stat tuple
Fred Drake699f3522000-06-29 21:12:41 +00002214 (used by posix_stat() and posix_fstat()) */
2215static PyObject*
Victor Stinner4195b5c2012-02-08 23:03:19 +01002216_pystat_fromstructstat(STRUCT_STAT *st)
Fred Drake699f3522000-06-29 21:12:41 +00002217{
Victor Stinner8c62be82010-05-06 00:08:46 +00002218 unsigned long ansec, mnsec, cnsec;
Eddie Elizondob3966632019-11-05 07:16:14 -08002219 PyObject *StatResultType = _posixstate_global->StatResultType;
2220 PyObject *v = PyStructSequence_New((PyTypeObject *)StatResultType);
Victor Stinner8c62be82010-05-06 00:08:46 +00002221 if (v == NULL)
2222 return NULL;
Fred Drake699f3522000-06-29 21:12:41 +00002223
Victor Stinner8c62be82010-05-06 00:08:46 +00002224 PyStructSequence_SET_ITEM(v, 0, PyLong_FromLong((long)st->st_mode));
Victor Stinner0f6d7332017-03-09 17:34:28 +01002225 Py_BUILD_ASSERT(sizeof(unsigned long long) >= sizeof(st->st_ino));
xdegaye50e86032017-05-22 11:15:08 +02002226 PyStructSequence_SET_ITEM(v, 1, PyLong_FromUnsignedLongLong(st->st_ino));
Serhiy Storchaka404fa922013-01-02 18:22:23 +02002227#ifdef MS_WINDOWS
2228 PyStructSequence_SET_ITEM(v, 2, PyLong_FromUnsignedLong(st->st_dev));
Fred Drake699f3522000-06-29 21:12:41 +00002229#else
Serhiy Storchakab2653b32015-01-18 11:12:11 +02002230 PyStructSequence_SET_ITEM(v, 2, _PyLong_FromDev(st->st_dev));
Fred Drake699f3522000-06-29 21:12:41 +00002231#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00002232 PyStructSequence_SET_ITEM(v, 3, PyLong_FromLong((long)st->st_nlink));
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02002233#if defined(MS_WINDOWS)
2234 PyStructSequence_SET_ITEM(v, 4, PyLong_FromLong(0));
2235 PyStructSequence_SET_ITEM(v, 5, PyLong_FromLong(0));
2236#else
2237 PyStructSequence_SET_ITEM(v, 4, _PyLong_FromUid(st->st_uid));
2238 PyStructSequence_SET_ITEM(v, 5, _PyLong_FromGid(st->st_gid));
2239#endif
xdegaye50e86032017-05-22 11:15:08 +02002240 Py_BUILD_ASSERT(sizeof(long long) >= sizeof(st->st_size));
2241 PyStructSequence_SET_ITEM(v, 6, PyLong_FromLongLong(st->st_size));
Martin v. Löwis94717ed2002-09-09 14:24:16 +00002242
Martin v. Löwis14694662006-02-03 12:54:16 +00002243#if defined(HAVE_STAT_TV_NSEC)
Victor Stinner8c62be82010-05-06 00:08:46 +00002244 ansec = st->st_atim.tv_nsec;
2245 mnsec = st->st_mtim.tv_nsec;
2246 cnsec = st->st_ctim.tv_nsec;
Martin v. Löwis14694662006-02-03 12:54:16 +00002247#elif defined(HAVE_STAT_TV_NSEC2)
Victor Stinner8c62be82010-05-06 00:08:46 +00002248 ansec = st->st_atimespec.tv_nsec;
2249 mnsec = st->st_mtimespec.tv_nsec;
2250 cnsec = st->st_ctimespec.tv_nsec;
Martin v. Löwis14694662006-02-03 12:54:16 +00002251#elif defined(HAVE_STAT_NSEC)
Victor Stinner8c62be82010-05-06 00:08:46 +00002252 ansec = st->st_atime_nsec;
2253 mnsec = st->st_mtime_nsec;
2254 cnsec = st->st_ctime_nsec;
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002255#else
Victor Stinner8c62be82010-05-06 00:08:46 +00002256 ansec = mnsec = cnsec = 0;
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002257#endif
Victor Stinner4195b5c2012-02-08 23:03:19 +01002258 fill_time(v, 7, st->st_atime, ansec);
2259 fill_time(v, 8, st->st_mtime, mnsec);
2260 fill_time(v, 9, st->st_ctime, cnsec);
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002261
Martin v. Löwis60a5d722002-10-16 20:28:25 +00002262#ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
Victor Stinner8c62be82010-05-06 00:08:46 +00002263 PyStructSequence_SET_ITEM(v, ST_BLKSIZE_IDX,
2264 PyLong_FromLong((long)st->st_blksize));
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002265#endif
Martin v. Löwis60a5d722002-10-16 20:28:25 +00002266#ifdef HAVE_STRUCT_STAT_ST_BLOCKS
Victor Stinner8c62be82010-05-06 00:08:46 +00002267 PyStructSequence_SET_ITEM(v, ST_BLOCKS_IDX,
2268 PyLong_FromLong((long)st->st_blocks));
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002269#endif
Martin v. Löwis60a5d722002-10-16 20:28:25 +00002270#ifdef HAVE_STRUCT_STAT_ST_RDEV
Victor Stinner8c62be82010-05-06 00:08:46 +00002271 PyStructSequence_SET_ITEM(v, ST_RDEV_IDX,
2272 PyLong_FromLong((long)st->st_rdev));
Fred Drake699f3522000-06-29 21:12:41 +00002273#endif
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002274#ifdef HAVE_STRUCT_STAT_ST_GEN
Victor Stinner8c62be82010-05-06 00:08:46 +00002275 PyStructSequence_SET_ITEM(v, ST_GEN_IDX,
2276 PyLong_FromLong((long)st->st_gen));
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002277#endif
2278#ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME
Victor Stinner8c62be82010-05-06 00:08:46 +00002279 {
Victor Stinner4195b5c2012-02-08 23:03:19 +01002280 PyObject *val;
2281 unsigned long bsec,bnsec;
2282 bsec = (long)st->st_birthtime;
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002283#ifdef HAVE_STAT_TV_NSEC2
Victor Stinner4195b5c2012-02-08 23:03:19 +01002284 bnsec = st->st_birthtimespec.tv_nsec;
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002285#else
Victor Stinner4195b5c2012-02-08 23:03:19 +01002286 bnsec = 0;
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002287#endif
Victor Stinner01b5aab2017-10-24 02:02:00 -07002288 val = PyFloat_FromDouble(bsec + 1e-9*bnsec);
Victor Stinner4195b5c2012-02-08 23:03:19 +01002289 PyStructSequence_SET_ITEM(v, ST_BIRTHTIME_IDX,
2290 val);
Victor Stinner8c62be82010-05-06 00:08:46 +00002291 }
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002292#endif
Hye-Shik Chang5f937a72005-06-02 13:09:30 +00002293#ifdef HAVE_STRUCT_STAT_ST_FLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +00002294 PyStructSequence_SET_ITEM(v, ST_FLAGS_IDX,
2295 PyLong_FromLong((long)st->st_flags));
Hye-Shik Chang5f937a72005-06-02 13:09:30 +00002296#endif
Zachary Ware63f277b2014-06-19 09:46:37 -05002297#ifdef HAVE_STRUCT_STAT_ST_FILE_ATTRIBUTES
2298 PyStructSequence_SET_ITEM(v, ST_FILE_ATTRIBUTES_IDX,
2299 PyLong_FromUnsignedLong(st->st_file_attributes));
2300#endif
jcea6c51d512018-01-28 14:00:08 +01002301#ifdef HAVE_STRUCT_STAT_ST_FSTYPE
2302 PyStructSequence_SET_ITEM(v, ST_FSTYPE_IDX,
2303 PyUnicode_FromString(st->st_fstype));
2304#endif
Steve Dowerdf2d4a62019-08-21 15:27:33 -07002305#ifdef HAVE_STRUCT_STAT_ST_REPARSE_TAG
2306 PyStructSequence_SET_ITEM(v, ST_REPARSE_TAG_IDX,
2307 PyLong_FromUnsignedLong(st->st_reparse_tag));
2308#endif
Fred Drake699f3522000-06-29 21:12:41 +00002309
Victor Stinner8c62be82010-05-06 00:08:46 +00002310 if (PyErr_Occurred()) {
2311 Py_DECREF(v);
2312 return NULL;
2313 }
Fred Drake699f3522000-06-29 21:12:41 +00002314
Victor Stinner8c62be82010-05-06 00:08:46 +00002315 return v;
Fred Drake699f3522000-06-29 21:12:41 +00002316}
2317
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002318/* POSIX methods */
2319
Guido van Rossum94f6f721999-01-06 18:42:14 +00002320
2321static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02002322posix_do_stat(const char *function_name, path_t *path,
Larry Hastings9cf065c2012-06-22 16:30:09 -07002323 int dir_fd, int follow_symlinks)
Guido van Rossum94f6f721999-01-06 18:42:14 +00002324{
Larry Hastings9cf065c2012-06-22 16:30:09 -07002325 STRUCT_STAT st;
2326 int result;
2327
2328#if !defined(MS_WINDOWS) && !defined(HAVE_FSTATAT) && !defined(HAVE_LSTAT)
2329 if (follow_symlinks_specified(function_name, follow_symlinks))
2330 return NULL;
2331#endif
2332
2333 if (path_and_dir_fd_invalid("stat", path, dir_fd) ||
2334 dir_fd_and_fd_invalid("stat", dir_fd, path->fd) ||
2335 fd_and_follow_symlinks_invalid("stat", path->fd, follow_symlinks))
2336 return NULL;
2337
2338 Py_BEGIN_ALLOW_THREADS
2339 if (path->fd != -1)
2340 result = FSTAT(path->fd, &st);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002341#ifdef MS_WINDOWS
Steve Dower513d7472016-09-08 10:41:50 -07002342 else if (follow_symlinks)
Steve Dowercc16be82016-09-08 10:35:16 -07002343 result = win32_stat(path->wide, &st);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002344 else
Steve Dowercc16be82016-09-08 10:35:16 -07002345 result = win32_lstat(path->wide, &st);
2346#else
2347 else
2348#if defined(HAVE_LSTAT)
Larry Hastings9cf065c2012-06-22 16:30:09 -07002349 if ((!follow_symlinks) && (dir_fd == DEFAULT_DIR_FD))
2350 result = LSTAT(path->narrow, &st);
2351 else
Steve Dowercc16be82016-09-08 10:35:16 -07002352#endif /* HAVE_LSTAT */
Larry Hastings9cf065c2012-06-22 16:30:09 -07002353#ifdef HAVE_FSTATAT
2354 if ((dir_fd != DEFAULT_DIR_FD) || !follow_symlinks)
2355 result = fstatat(dir_fd, path->narrow, &st,
2356 follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW);
2357 else
Steve Dowercc16be82016-09-08 10:35:16 -07002358#endif /* HAVE_FSTATAT */
Larry Hastings9cf065c2012-06-22 16:30:09 -07002359 result = STAT(path->narrow, &st);
Steve Dowercc16be82016-09-08 10:35:16 -07002360#endif /* MS_WINDOWS */
Larry Hastings9cf065c2012-06-22 16:30:09 -07002361 Py_END_ALLOW_THREADS
2362
Victor Stinner292c8352012-10-30 02:17:38 +01002363 if (result != 0) {
2364 return path_error(path);
2365 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07002366
2367 return _pystat_fromstructstat(&st);
2368}
2369
Larry Hastings2f936352014-08-05 14:04:04 +10002370/*[python input]
2371
2372for s in """
2373
2374FACCESSAT
2375FCHMODAT
2376FCHOWNAT
2377FSTATAT
2378LINKAT
2379MKDIRAT
2380MKFIFOAT
2381MKNODAT
2382OPENAT
2383READLINKAT
2384SYMLINKAT
2385UNLINKAT
2386
2387""".strip().split():
2388 s = s.strip()
2389 print("""
2390#ifdef HAVE_{s}
2391 #define {s}_DIR_FD_CONVERTER dir_fd_converter
Larry Hastings31826802013-10-19 00:09:25 -07002392#else
Larry Hastings2f936352014-08-05 14:04:04 +10002393 #define {s}_DIR_FD_CONVERTER dir_fd_unavailable
Larry Hastings31826802013-10-19 00:09:25 -07002394#endif
Larry Hastings2f936352014-08-05 14:04:04 +10002395""".rstrip().format(s=s))
2396
2397for s in """
2398
2399FCHDIR
2400FCHMOD
2401FCHOWN
2402FDOPENDIR
2403FEXECVE
2404FPATHCONF
2405FSTATVFS
2406FTRUNCATE
2407
2408""".strip().split():
2409 s = s.strip()
2410 print("""
2411#ifdef HAVE_{s}
2412 #define PATH_HAVE_{s} 1
2413#else
2414 #define PATH_HAVE_{s} 0
2415#endif
2416
2417""".rstrip().format(s=s))
2418[python start generated code]*/
2419
2420#ifdef HAVE_FACCESSAT
2421 #define FACCESSAT_DIR_FD_CONVERTER dir_fd_converter
2422#else
2423 #define FACCESSAT_DIR_FD_CONVERTER dir_fd_unavailable
2424#endif
2425
2426#ifdef HAVE_FCHMODAT
2427 #define FCHMODAT_DIR_FD_CONVERTER dir_fd_converter
2428#else
2429 #define FCHMODAT_DIR_FD_CONVERTER dir_fd_unavailable
2430#endif
2431
2432#ifdef HAVE_FCHOWNAT
2433 #define FCHOWNAT_DIR_FD_CONVERTER dir_fd_converter
2434#else
2435 #define FCHOWNAT_DIR_FD_CONVERTER dir_fd_unavailable
2436#endif
2437
2438#ifdef HAVE_FSTATAT
2439 #define FSTATAT_DIR_FD_CONVERTER dir_fd_converter
2440#else
2441 #define FSTATAT_DIR_FD_CONVERTER dir_fd_unavailable
2442#endif
2443
2444#ifdef HAVE_LINKAT
2445 #define LINKAT_DIR_FD_CONVERTER dir_fd_converter
2446#else
2447 #define LINKAT_DIR_FD_CONVERTER dir_fd_unavailable
2448#endif
2449
2450#ifdef HAVE_MKDIRAT
2451 #define MKDIRAT_DIR_FD_CONVERTER dir_fd_converter
2452#else
2453 #define MKDIRAT_DIR_FD_CONVERTER dir_fd_unavailable
2454#endif
2455
2456#ifdef HAVE_MKFIFOAT
2457 #define MKFIFOAT_DIR_FD_CONVERTER dir_fd_converter
2458#else
2459 #define MKFIFOAT_DIR_FD_CONVERTER dir_fd_unavailable
2460#endif
2461
2462#ifdef HAVE_MKNODAT
2463 #define MKNODAT_DIR_FD_CONVERTER dir_fd_converter
2464#else
2465 #define MKNODAT_DIR_FD_CONVERTER dir_fd_unavailable
2466#endif
2467
2468#ifdef HAVE_OPENAT
2469 #define OPENAT_DIR_FD_CONVERTER dir_fd_converter
2470#else
2471 #define OPENAT_DIR_FD_CONVERTER dir_fd_unavailable
2472#endif
2473
2474#ifdef HAVE_READLINKAT
2475 #define READLINKAT_DIR_FD_CONVERTER dir_fd_converter
2476#else
2477 #define READLINKAT_DIR_FD_CONVERTER dir_fd_unavailable
2478#endif
2479
2480#ifdef HAVE_SYMLINKAT
2481 #define SYMLINKAT_DIR_FD_CONVERTER dir_fd_converter
2482#else
2483 #define SYMLINKAT_DIR_FD_CONVERTER dir_fd_unavailable
2484#endif
2485
2486#ifdef HAVE_UNLINKAT
2487 #define UNLINKAT_DIR_FD_CONVERTER dir_fd_converter
2488#else
2489 #define UNLINKAT_DIR_FD_CONVERTER dir_fd_unavailable
2490#endif
2491
2492#ifdef HAVE_FCHDIR
2493 #define PATH_HAVE_FCHDIR 1
2494#else
2495 #define PATH_HAVE_FCHDIR 0
2496#endif
2497
2498#ifdef HAVE_FCHMOD
2499 #define PATH_HAVE_FCHMOD 1
2500#else
2501 #define PATH_HAVE_FCHMOD 0
2502#endif
2503
2504#ifdef HAVE_FCHOWN
2505 #define PATH_HAVE_FCHOWN 1
2506#else
2507 #define PATH_HAVE_FCHOWN 0
2508#endif
2509
2510#ifdef HAVE_FDOPENDIR
2511 #define PATH_HAVE_FDOPENDIR 1
2512#else
2513 #define PATH_HAVE_FDOPENDIR 0
2514#endif
2515
2516#ifdef HAVE_FEXECVE
2517 #define PATH_HAVE_FEXECVE 1
2518#else
2519 #define PATH_HAVE_FEXECVE 0
2520#endif
2521
2522#ifdef HAVE_FPATHCONF
2523 #define PATH_HAVE_FPATHCONF 1
2524#else
2525 #define PATH_HAVE_FPATHCONF 0
2526#endif
2527
2528#ifdef HAVE_FSTATVFS
2529 #define PATH_HAVE_FSTATVFS 1
2530#else
2531 #define PATH_HAVE_FSTATVFS 0
2532#endif
2533
2534#ifdef HAVE_FTRUNCATE
2535 #define PATH_HAVE_FTRUNCATE 1
2536#else
2537 #define PATH_HAVE_FTRUNCATE 0
2538#endif
2539/*[python end generated code: output=4bd4f6f7d41267f1 input=80b4c890b6774ea5]*/
Larry Hastings31826802013-10-19 00:09:25 -07002540
Steve Dowerfe0a41a2015-03-20 19:50:46 -07002541#ifdef MS_WINDOWS
2542 #undef PATH_HAVE_FTRUNCATE
2543 #define PATH_HAVE_FTRUNCATE 1
2544#endif
Larry Hastings31826802013-10-19 00:09:25 -07002545
Larry Hastings61272b72014-01-07 12:41:53 -08002546/*[python input]
Larry Hastings31826802013-10-19 00:09:25 -07002547
2548class path_t_converter(CConverter):
2549
2550 type = "path_t"
2551 impl_by_reference = True
2552 parse_by_reference = True
2553
2554 converter = 'path_converter'
2555
2556 def converter_init(self, *, allow_fd=False, nullable=False):
Larry Hastings31826802013-10-19 00:09:25 -07002557 # right now path_t doesn't support default values.
2558 # to support a default value, you'll need to override initialize().
Larry Hastings2f936352014-08-05 14:04:04 +10002559 if self.default not in (unspecified, None):
Larry Hastings7726ac92014-01-31 22:03:12 -08002560 fail("Can't specify a default to the path_t converter!")
Larry Hastings31826802013-10-19 00:09:25 -07002561
Larry Hastings2f936352014-08-05 14:04:04 +10002562 if self.c_default not in (None, 'Py_None'):
2563 raise RuntimeError("Can't specify a c_default to the path_t converter!")
Larry Hastings31826802013-10-19 00:09:25 -07002564
2565 self.nullable = nullable
2566 self.allow_fd = allow_fd
2567
Larry Hastings7726ac92014-01-31 22:03:12 -08002568 def pre_render(self):
2569 def strify(value):
Larry Hastings2f936352014-08-05 14:04:04 +10002570 if isinstance(value, str):
2571 return value
Larry Hastings7726ac92014-01-31 22:03:12 -08002572 return str(int(bool(value)))
2573
2574 # add self.py_name here when merging with posixmodule conversion
Larry Hastings2f936352014-08-05 14:04:04 +10002575 self.c_default = 'PATH_T_INITIALIZE("{}", "{}", {}, {})'.format(
Larry Hastings31826802013-10-19 00:09:25 -07002576 self.function.name,
Larry Hastings2f936352014-08-05 14:04:04 +10002577 self.name,
Larry Hastings7726ac92014-01-31 22:03:12 -08002578 strify(self.nullable),
2579 strify(self.allow_fd),
Larry Hastings31826802013-10-19 00:09:25 -07002580 )
2581
2582 def cleanup(self):
2583 return "path_cleanup(&" + self.name + ");\n"
2584
2585
2586class dir_fd_converter(CConverter):
2587 type = 'int'
Larry Hastings31826802013-10-19 00:09:25 -07002588
Larry Hastings2f936352014-08-05 14:04:04 +10002589 def converter_init(self, requires=None):
Larry Hastings31826802013-10-19 00:09:25 -07002590 if self.default in (unspecified, None):
2591 self.c_default = 'DEFAULT_DIR_FD'
Larry Hastings2f936352014-08-05 14:04:04 +10002592 if isinstance(requires, str):
2593 self.converter = requires.upper() + '_DIR_FD_CONVERTER'
2594 else:
2595 self.converter = 'dir_fd_converter'
Larry Hastings31826802013-10-19 00:09:25 -07002596
Larry Hastings2f936352014-08-05 14:04:04 +10002597class fildes_converter(CConverter):
2598 type = 'int'
2599 converter = 'fildes_converter'
2600
2601class uid_t_converter(CConverter):
2602 type = "uid_t"
2603 converter = '_Py_Uid_Converter'
2604
2605class gid_t_converter(CConverter):
2606 type = "gid_t"
2607 converter = '_Py_Gid_Converter'
2608
Serhiy Storchakaacdb7c12015-01-18 11:17:39 +02002609class dev_t_converter(CConverter):
2610 type = 'dev_t'
2611 converter = '_Py_Dev_Converter'
2612
2613class dev_t_return_converter(unsigned_long_return_converter):
2614 type = 'dev_t'
2615 conversion_fn = '_PyLong_FromDev'
2616 unsigned_cast = '(dev_t)'
2617
Larry Hastings2f936352014-08-05 14:04:04 +10002618class FSConverter_converter(CConverter):
2619 type = 'PyObject *'
2620 converter = 'PyUnicode_FSConverter'
2621 def converter_init(self):
2622 if self.default is not unspecified:
2623 fail("FSConverter_converter does not support default values")
2624 self.c_default = 'NULL'
2625
2626 def cleanup(self):
2627 return "Py_XDECREF(" + self.name + ");\n"
2628
2629class pid_t_converter(CConverter):
2630 type = 'pid_t'
2631 format_unit = '" _Py_PARSE_PID "'
2632
2633class idtype_t_converter(int_converter):
2634 type = 'idtype_t'
2635
2636class id_t_converter(CConverter):
2637 type = 'id_t'
2638 format_unit = '" _Py_PARSE_PID "'
2639
Benjamin Petersonca470632016-09-06 13:47:26 -07002640class intptr_t_converter(CConverter):
2641 type = 'intptr_t'
Larry Hastings2f936352014-08-05 14:04:04 +10002642 format_unit = '" _Py_PARSE_INTPTR "'
2643
2644class Py_off_t_converter(CConverter):
2645 type = 'Py_off_t'
2646 converter = 'Py_off_t_converter'
2647
2648class Py_off_t_return_converter(long_return_converter):
2649 type = 'Py_off_t'
2650 conversion_fn = 'PyLong_FromPy_off_t'
2651
2652class path_confname_converter(CConverter):
2653 type="int"
2654 converter="conv_path_confname"
2655
2656class confstr_confname_converter(path_confname_converter):
2657 converter='conv_confstr_confname'
2658
2659class sysconf_confname_converter(path_confname_converter):
2660 converter="conv_sysconf_confname"
2661
2662class sched_param_converter(CConverter):
2663 type = 'struct sched_param'
2664 converter = 'convert_sched_param'
2665 impl_by_reference = True;
Larry Hastings31826802013-10-19 00:09:25 -07002666
Larry Hastings61272b72014-01-07 12:41:53 -08002667[python start generated code]*/
Victor Stinner581139c2016-09-06 15:54:20 -07002668/*[python end generated code: output=da39a3ee5e6b4b0d input=418fce0e01144461]*/
Larry Hastings31826802013-10-19 00:09:25 -07002669
Larry Hastings61272b72014-01-07 12:41:53 -08002670/*[clinic input]
Larry Hastings31826802013-10-19 00:09:25 -07002671
Larry Hastings2a727912014-01-16 11:32:01 -08002672os.stat
Larry Hastings31826802013-10-19 00:09:25 -07002673
2674 path : path_t(allow_fd=True)
BNMetricsb9427072018-11-02 15:20:19 +00002675 Path to be examined; can be string, bytes, a path-like object or
Xiang Zhang4459e002017-01-22 13:04:17 +08002676 open-file-descriptor int.
Larry Hastings31826802013-10-19 00:09:25 -07002677
2678 *
2679
Larry Hastings2f936352014-08-05 14:04:04 +10002680 dir_fd : dir_fd(requires='fstatat') = None
Larry Hastings31826802013-10-19 00:09:25 -07002681 If not None, it should be a file descriptor open to a directory,
2682 and path should be a relative string; path will then be relative to
2683 that directory.
2684
2685 follow_symlinks: bool = True
2686 If False, and the last element of the path is a symbolic link,
2687 stat will examine the symbolic link itself instead of the file
2688 the link points to.
2689
2690Perform a stat system call on the given path.
2691
2692dir_fd and follow_symlinks may not be implemented
2693 on your platform. If they are unavailable, using them will raise a
2694 NotImplementedError.
2695
2696It's an error to use dir_fd or follow_symlinks when specifying path as
2697 an open file descriptor.
2698
Larry Hastings61272b72014-01-07 12:41:53 -08002699[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -07002700
Larry Hastings31826802013-10-19 00:09:25 -07002701static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002702os_stat_impl(PyObject *module, path_t *path, int dir_fd, int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +00002703/*[clinic end generated code: output=7d4976e6f18a59c5 input=01d362ebcc06996b]*/
Larry Hastings31826802013-10-19 00:09:25 -07002704{
2705 return posix_do_stat("stat", path, dir_fd, follow_symlinks);
2706}
2707
Larry Hastings2f936352014-08-05 14:04:04 +10002708
2709/*[clinic input]
2710os.lstat
2711
2712 path : path_t
2713
2714 *
2715
2716 dir_fd : dir_fd(requires='fstatat') = None
2717
2718Perform a stat system call on the given path, without following symbolic links.
2719
2720Like stat(), but do not follow symbolic links.
2721Equivalent to stat(path, follow_symlinks=False).
2722[clinic start generated code]*/
2723
Larry Hastings2f936352014-08-05 14:04:04 +10002724static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002725os_lstat_impl(PyObject *module, path_t *path, int dir_fd)
2726/*[clinic end generated code: output=ef82a5d35ce8ab37 input=0b7474765927b925]*/
Larry Hastings2f936352014-08-05 14:04:04 +10002727{
2728 int follow_symlinks = 0;
2729 return posix_do_stat("lstat", path, dir_fd, follow_symlinks);
2730}
Larry Hastings31826802013-10-19 00:09:25 -07002731
Larry Hastings2f936352014-08-05 14:04:04 +10002732
Larry Hastings61272b72014-01-07 12:41:53 -08002733/*[clinic input]
Larry Hastings2f936352014-08-05 14:04:04 +10002734os.access -> bool
Larry Hastings31826802013-10-19 00:09:25 -07002735
Benjamin Peterson768f3b42016-09-05 15:29:33 -07002736 path: path_t
BNMetricsb9427072018-11-02 15:20:19 +00002737 Path to be tested; can be string, bytes, or a path-like object.
Larry Hastings31826802013-10-19 00:09:25 -07002738
2739 mode: int
2740 Operating-system mode bitfield. Can be F_OK to test existence,
2741 or the inclusive-OR of R_OK, W_OK, and X_OK.
2742
2743 *
2744
Larry Hastings2f936352014-08-05 14:04:04 +10002745 dir_fd : dir_fd(requires='faccessat') = None
Larry Hastings31826802013-10-19 00:09:25 -07002746 If not None, it should be a file descriptor open to a directory,
2747 and path should be relative; path will then be relative to that
2748 directory.
2749
2750 effective_ids: bool = False
2751 If True, access will use the effective uid/gid instead of
2752 the real uid/gid.
2753
2754 follow_symlinks: bool = True
2755 If False, and the last element of the path is a symbolic link,
2756 access will examine the symbolic link itself instead of the file
2757 the link points to.
2758
2759Use the real uid/gid to test for access to a path.
2760
2761{parameters}
2762dir_fd, effective_ids, and follow_symlinks may not be implemented
2763 on your platform. If they are unavailable, using them will raise a
2764 NotImplementedError.
2765
2766Note that most operations will use the effective uid/gid, therefore this
2767 routine can be used in a suid/sgid environment to test if the invoking user
2768 has the specified access to the path.
2769
Larry Hastings61272b72014-01-07 12:41:53 -08002770[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -07002771
Larry Hastings2f936352014-08-05 14:04:04 +10002772static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002773os_access_impl(PyObject *module, path_t *path, int mode, int dir_fd,
Larry Hastings89964c42015-04-14 18:07:59 -04002774 int effective_ids, int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +00002775/*[clinic end generated code: output=cf84158bc90b1a77 input=3ffe4e650ee3bf20]*/
Larry Hastings31826802013-10-19 00:09:25 -07002776{
Larry Hastings2f936352014-08-05 14:04:04 +10002777 int return_value;
Victor Stinner8c62be82010-05-06 00:08:46 +00002778
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00002779#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +00002780 DWORD attr;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002781#else
Larry Hastings9cf065c2012-06-22 16:30:09 -07002782 int result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002783#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -07002784
Larry Hastings9cf065c2012-06-22 16:30:09 -07002785#ifndef HAVE_FACCESSAT
2786 if (follow_symlinks_specified("access", follow_symlinks))
Larry Hastings2f936352014-08-05 14:04:04 +10002787 return -1;
Larry Hastings9cf065c2012-06-22 16:30:09 -07002788
2789 if (effective_ids) {
2790 argument_unavailable_error("access", "effective_ids");
Larry Hastings2f936352014-08-05 14:04:04 +10002791 return -1;
Larry Hastings9cf065c2012-06-22 16:30:09 -07002792 }
2793#endif
2794
2795#ifdef MS_WINDOWS
2796 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -07002797 attr = GetFileAttributesW(path->wide);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002798 Py_END_ALLOW_THREADS
2799
2800 /*
Georg Brandlf7875592012-06-24 13:58:31 +02002801 * Access is possible if
Larry Hastings9cf065c2012-06-22 16:30:09 -07002802 * * we didn't get a -1, and
2803 * * write access wasn't requested,
2804 * * or the file isn't read-only,
2805 * * or it's a directory.
2806 * (Directories cannot be read-only on Windows.)
2807 */
Larry Hastings2f936352014-08-05 14:04:04 +10002808 return_value = (attr != INVALID_FILE_ATTRIBUTES) &&
Georg Brandl5bb7aa92012-06-23 12:48:40 +02002809 (!(mode & 2) ||
Larry Hastings9cf065c2012-06-22 16:30:09 -07002810 !(attr & FILE_ATTRIBUTE_READONLY) ||
Larry Hastings2f936352014-08-05 14:04:04 +10002811 (attr & FILE_ATTRIBUTE_DIRECTORY));
Larry Hastings9cf065c2012-06-22 16:30:09 -07002812#else
2813
2814 Py_BEGIN_ALLOW_THREADS
2815#ifdef HAVE_FACCESSAT
2816 if ((dir_fd != DEFAULT_DIR_FD) ||
2817 effective_ids ||
2818 !follow_symlinks) {
2819 int flags = 0;
2820 if (!follow_symlinks)
2821 flags |= AT_SYMLINK_NOFOLLOW;
2822 if (effective_ids)
2823 flags |= AT_EACCESS;
Larry Hastings31826802013-10-19 00:09:25 -07002824 result = faccessat(dir_fd, path->narrow, mode, flags);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002825 }
2826 else
2827#endif
Larry Hastings31826802013-10-19 00:09:25 -07002828 result = access(path->narrow, mode);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002829 Py_END_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10002830 return_value = !result;
Larry Hastings9cf065c2012-06-22 16:30:09 -07002831#endif
2832
Larry Hastings9cf065c2012-06-22 16:30:09 -07002833 return return_value;
Guido van Rossum94f6f721999-01-06 18:42:14 +00002834}
2835
Guido van Rossumd371ff11999-01-25 16:12:23 +00002836#ifndef F_OK
2837#define F_OK 0
2838#endif
2839#ifndef R_OK
2840#define R_OK 4
2841#endif
2842#ifndef W_OK
2843#define W_OK 2
2844#endif
2845#ifndef X_OK
2846#define X_OK 1
2847#endif
2848
Larry Hastings31826802013-10-19 00:09:25 -07002849
Guido van Rossumd371ff11999-01-25 16:12:23 +00002850#ifdef HAVE_TTYNAME
Larry Hastings61272b72014-01-07 12:41:53 -08002851/*[clinic input]
Serhiy Storchaka4db62e12018-12-17 16:47:45 +02002852os.ttyname
Larry Hastings31826802013-10-19 00:09:25 -07002853
2854 fd: int
2855 Integer file descriptor handle.
2856
2857 /
2858
2859Return the name of the terminal device connected to 'fd'.
Larry Hastings61272b72014-01-07 12:41:53 -08002860[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -07002861
Serhiy Storchaka4db62e12018-12-17 16:47:45 +02002862static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002863os_ttyname_impl(PyObject *module, int fd)
Serhiy Storchaka4db62e12018-12-17 16:47:45 +02002864/*[clinic end generated code: output=c424d2e9d1cd636a input=9ff5a58b08115c55]*/
Larry Hastings31826802013-10-19 00:09:25 -07002865{
Guido van Rossum94f6f721999-01-06 18:42:14 +00002866
Antonio Gutierrez594e2ed2019-10-09 04:19:48 +02002867 long size = sysconf(_SC_TTY_NAME_MAX);
2868 if (size == -1) {
Serhiy Storchaka4db62e12018-12-17 16:47:45 +02002869 return posix_error();
2870 }
Antonio Gutierrez594e2ed2019-10-09 04:19:48 +02002871 char *buffer = (char *)PyMem_RawMalloc(size);
2872 if (buffer == NULL) {
2873 return PyErr_NoMemory();
2874 }
2875 int ret = ttyname_r(fd, buffer, size);
2876 if (ret != 0) {
2877 PyMem_RawFree(buffer);
2878 errno = ret;
2879 return posix_error();
2880 }
2881 PyObject *res = PyUnicode_DecodeFSDefault(buffer);
2882 PyMem_RawFree(buffer);
2883 return res;
Guido van Rossum94f6f721999-01-06 18:42:14 +00002884}
Guido van Rossumd371ff11999-01-25 16:12:23 +00002885#endif
Guido van Rossum94f6f721999-01-06 18:42:14 +00002886
Fred Drake5ab8eaf1999-12-09 21:13:07 +00002887#ifdef HAVE_CTERMID
Larry Hastings2f936352014-08-05 14:04:04 +10002888/*[clinic input]
2889os.ctermid
2890
2891Return the name of the controlling terminal for this process.
2892[clinic start generated code]*/
2893
Larry Hastings2f936352014-08-05 14:04:04 +10002894static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002895os_ctermid_impl(PyObject *module)
2896/*[clinic end generated code: output=02f017e6c9e620db input=3b87fdd52556382d]*/
Fred Drake5ab8eaf1999-12-09 21:13:07 +00002897{
Victor Stinner8c62be82010-05-06 00:08:46 +00002898 char *ret;
2899 char buffer[L_ctermid];
Fred Drake5ab8eaf1999-12-09 21:13:07 +00002900
Greg Wardb48bc172000-03-01 21:51:56 +00002901#ifdef USE_CTERMID_R
Victor Stinner8c62be82010-05-06 00:08:46 +00002902 ret = ctermid_r(buffer);
Fred Drake5ab8eaf1999-12-09 21:13:07 +00002903#else
Victor Stinner8c62be82010-05-06 00:08:46 +00002904 ret = ctermid(buffer);
Fred Drake5ab8eaf1999-12-09 21:13:07 +00002905#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00002906 if (ret == NULL)
2907 return posix_error();
Victor Stinner5fe6de82010-08-15 09:12:51 +00002908 return PyUnicode_DecodeFSDefault(buffer);
Fred Drake5ab8eaf1999-12-09 21:13:07 +00002909}
Larry Hastings2f936352014-08-05 14:04:04 +10002910#endif /* HAVE_CTERMID */
Fred Drake5ab8eaf1999-12-09 21:13:07 +00002911
Larry Hastings2f936352014-08-05 14:04:04 +10002912
2913/*[clinic input]
2914os.chdir
2915
2916 path: path_t(allow_fd='PATH_HAVE_FCHDIR')
2917
2918Change the current working directory to the specified path.
2919
2920path may always be specified as a string.
2921On some platforms, path may also be specified as an open file descriptor.
2922 If this functionality is unavailable, using it raises an exception.
2923[clinic start generated code]*/
2924
Larry Hastings2f936352014-08-05 14:04:04 +10002925static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002926os_chdir_impl(PyObject *module, path_t *path)
2927/*[clinic end generated code: output=3be6400eee26eaae input=1a4a15b4d12cb15d]*/
Larry Hastings2f936352014-08-05 14:04:04 +10002928{
2929 int result;
Larry Hastings9cf065c2012-06-22 16:30:09 -07002930
2931 Py_BEGIN_ALLOW_THREADS
2932#ifdef MS_WINDOWS
Steve Dowercc16be82016-09-08 10:35:16 -07002933 /* on unix, success = 0, on windows, success = !0 */
2934 result = !win32_wchdir(path->wide);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002935#else
2936#ifdef HAVE_FCHDIR
Larry Hastings2f936352014-08-05 14:04:04 +10002937 if (path->fd != -1)
2938 result = fchdir(path->fd);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002939 else
2940#endif
Larry Hastings2f936352014-08-05 14:04:04 +10002941 result = chdir(path->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002942#endif
2943 Py_END_ALLOW_THREADS
2944
2945 if (result) {
Larry Hastings2f936352014-08-05 14:04:04 +10002946 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002947 }
2948
Larry Hastings2f936352014-08-05 14:04:04 +10002949 Py_RETURN_NONE;
2950}
2951
2952
2953#ifdef HAVE_FCHDIR
2954/*[clinic input]
2955os.fchdir
2956
2957 fd: fildes
2958
2959Change to the directory of the given file descriptor.
2960
2961fd must be opened on a directory, not a file.
2962Equivalent to os.chdir(fd).
2963
2964[clinic start generated code]*/
2965
Fred Drake4d1e64b2002-04-15 19:40:07 +00002966static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002967os_fchdir_impl(PyObject *module, int fd)
2968/*[clinic end generated code: output=42e064ec4dc00ab0 input=18e816479a2fa985]*/
Fred Drake4d1e64b2002-04-15 19:40:07 +00002969{
Larry Hastings2f936352014-08-05 14:04:04 +10002970 return posix_fildes_fd(fd, fchdir);
Fred Drake4d1e64b2002-04-15 19:40:07 +00002971}
2972#endif /* HAVE_FCHDIR */
2973
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00002974
Larry Hastings2f936352014-08-05 14:04:04 +10002975/*[clinic input]
2976os.chmod
2977
2978 path: path_t(allow_fd='PATH_HAVE_FCHMOD')
BNMetricsb9427072018-11-02 15:20:19 +00002979 Path to be modified. May always be specified as a str, bytes, or a path-like object.
Larry Hastings2f936352014-08-05 14:04:04 +10002980 On some platforms, path may also be specified as an open file descriptor.
2981 If this functionality is unavailable, using it raises an exception.
2982
2983 mode: int
2984 Operating-system mode bitfield.
2985
2986 *
2987
2988 dir_fd : dir_fd(requires='fchmodat') = None
2989 If not None, it should be a file descriptor open to a directory,
2990 and path should be relative; path will then be relative to that
2991 directory.
2992
2993 follow_symlinks: bool = True
2994 If False, and the last element of the path is a symbolic link,
2995 chmod will modify the symbolic link itself instead of the file
2996 the link points to.
2997
2998Change the access permissions of a file.
2999
3000It is an error to use dir_fd or follow_symlinks when specifying path as
3001 an open file descriptor.
3002dir_fd and follow_symlinks may not be implemented on your platform.
3003 If they are unavailable, using them will raise a NotImplementedError.
3004
3005[clinic start generated code]*/
3006
Larry Hastings2f936352014-08-05 14:04:04 +10003007static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003008os_chmod_impl(PyObject *module, path_t *path, int mode, int dir_fd,
Larry Hastings89964c42015-04-14 18:07:59 -04003009 int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +00003010/*[clinic end generated code: output=5cf6a94915cc7bff input=989081551c00293b]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003011{
Larry Hastings9cf065c2012-06-22 16:30:09 -07003012 int result;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003013
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00003014#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +00003015 DWORD attr;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003016#endif
Hirokazu Yamamoto892a37a2009-06-28 11:07:03 +00003017
Larry Hastings9cf065c2012-06-22 16:30:09 -07003018#ifdef HAVE_FCHMODAT
3019 int fchmodat_nofollow_unsupported = 0;
3020#endif
3021
Larry Hastings9cf065c2012-06-22 16:30:09 -07003022#if !(defined(HAVE_FCHMODAT) || defined(HAVE_LCHMOD))
3023 if (follow_symlinks_specified("chmod", follow_symlinks))
Larry Hastings2f936352014-08-05 14:04:04 +10003024 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003025#endif
3026
3027#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +00003028 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -07003029 attr = GetFileAttributesW(path->wide);
Tim Golden23005082013-10-25 11:22:37 +01003030 if (attr == INVALID_FILE_ATTRIBUTES)
Larry Hastings9cf065c2012-06-22 16:30:09 -07003031 result = 0;
3032 else {
3033 if (mode & _S_IWRITE)
Victor Stinner8c62be82010-05-06 00:08:46 +00003034 attr &= ~FILE_ATTRIBUTE_READONLY;
3035 else
3036 attr |= FILE_ATTRIBUTE_READONLY;
Steve Dowercc16be82016-09-08 10:35:16 -07003037 result = SetFileAttributesW(path->wide, attr);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003038 }
3039 Py_END_ALLOW_THREADS
3040
3041 if (!result) {
Larry Hastings2f936352014-08-05 14:04:04 +10003042 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003043 }
3044#else /* MS_WINDOWS */
3045 Py_BEGIN_ALLOW_THREADS
3046#ifdef HAVE_FCHMOD
Larry Hastings2f936352014-08-05 14:04:04 +10003047 if (path->fd != -1)
3048 result = fchmod(path->fd, mode);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003049 else
3050#endif
3051#ifdef HAVE_LCHMOD
3052 if ((!follow_symlinks) && (dir_fd == DEFAULT_DIR_FD))
Larry Hastings2f936352014-08-05 14:04:04 +10003053 result = lchmod(path->narrow, mode);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003054 else
3055#endif
3056#ifdef HAVE_FCHMODAT
3057 if ((dir_fd != DEFAULT_DIR_FD) || !follow_symlinks) {
3058 /*
3059 * fchmodat() doesn't currently support AT_SYMLINK_NOFOLLOW!
3060 * The documentation specifically shows how to use it,
Larry Hastingsdbbc0c82012-06-22 19:50:21 -07003061 * and then says it isn't implemented yet.
3062 * (true on linux with glibc 2.15, and openindiana 3.x)
Larry Hastings9cf065c2012-06-22 16:30:09 -07003063 *
3064 * Once it is supported, os.chmod will automatically
3065 * support dir_fd and follow_symlinks=False. (Hopefully.)
3066 * Until then, we need to be careful what exception we raise.
3067 */
Larry Hastings2f936352014-08-05 14:04:04 +10003068 result = fchmodat(dir_fd, path->narrow, mode,
Larry Hastings9cf065c2012-06-22 16:30:09 -07003069 follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW);
3070 /*
3071 * But wait! We can't throw the exception without allowing threads,
3072 * and we can't do that in this nested scope. (Macro trickery, sigh.)
3073 */
3074 fchmodat_nofollow_unsupported =
Larry Hastingsdbbc0c82012-06-22 19:50:21 -07003075 result &&
3076 ((errno == ENOTSUP) || (errno == EOPNOTSUPP)) &&
3077 !follow_symlinks;
Victor Stinner8c62be82010-05-06 00:08:46 +00003078 }
3079 else
Thomas Wouters477c8d52006-05-27 19:21:47 +00003080#endif
Larry Hastings2f936352014-08-05 14:04:04 +10003081 result = chmod(path->narrow, mode);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003082 Py_END_ALLOW_THREADS
3083
3084 if (result) {
3085#ifdef HAVE_FCHMODAT
3086 if (fchmodat_nofollow_unsupported) {
3087 if (dir_fd != DEFAULT_DIR_FD)
3088 dir_fd_and_follow_symlinks_invalid("chmod",
3089 dir_fd, follow_symlinks);
3090 else
3091 follow_symlinks_specified("chmod", follow_symlinks);
Anthony Sottile233ef242017-12-14 08:57:55 -08003092 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003093 }
3094 else
3095#endif
Larry Hastings2f936352014-08-05 14:04:04 +10003096 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003097 }
3098#endif
3099
Larry Hastings2f936352014-08-05 14:04:04 +10003100 Py_RETURN_NONE;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003101}
3102
Larry Hastings9cf065c2012-06-22 16:30:09 -07003103
Christian Heimes4e30a842007-11-30 22:12:06 +00003104#ifdef HAVE_FCHMOD
Larry Hastings2f936352014-08-05 14:04:04 +10003105/*[clinic input]
3106os.fchmod
3107
3108 fd: int
3109 mode: int
3110
3111Change the access permissions of the file given by file descriptor fd.
3112
3113Equivalent to os.chmod(fd, mode).
3114[clinic start generated code]*/
3115
Larry Hastings2f936352014-08-05 14:04:04 +10003116static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003117os_fchmod_impl(PyObject *module, int fd, int mode)
3118/*[clinic end generated code: output=afd9bc05b4e426b3 input=8ab11975ca01ee5b]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003119{
3120 int res;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00003121 int async_err = 0;
3122
3123 do {
3124 Py_BEGIN_ALLOW_THREADS
3125 res = fchmod(fd, mode);
3126 Py_END_ALLOW_THREADS
3127 } while (res != 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
3128 if (res != 0)
3129 return (!async_err) ? posix_error() : NULL;
3130
Victor Stinner8c62be82010-05-06 00:08:46 +00003131 Py_RETURN_NONE;
Christian Heimes4e30a842007-11-30 22:12:06 +00003132}
3133#endif /* HAVE_FCHMOD */
3134
Larry Hastings2f936352014-08-05 14:04:04 +10003135
Christian Heimes4e30a842007-11-30 22:12:06 +00003136#ifdef HAVE_LCHMOD
Larry Hastings2f936352014-08-05 14:04:04 +10003137/*[clinic input]
3138os.lchmod
3139
3140 path: path_t
3141 mode: int
3142
3143Change the access permissions of a file, without following symbolic links.
3144
3145If path is a symlink, this affects the link itself rather than the target.
3146Equivalent to chmod(path, mode, follow_symlinks=False)."
3147[clinic start generated code]*/
3148
Larry Hastings2f936352014-08-05 14:04:04 +10003149static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003150os_lchmod_impl(PyObject *module, path_t *path, int mode)
3151/*[clinic end generated code: output=082344022b51a1d5 input=90c5663c7465d24f]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003152{
Victor Stinner8c62be82010-05-06 00:08:46 +00003153 int res;
Victor Stinner8c62be82010-05-06 00:08:46 +00003154 Py_BEGIN_ALLOW_THREADS
Larry Hastingsb1dc1122014-08-05 16:06:16 +10003155 res = lchmod(path->narrow, mode);
Victor Stinner8c62be82010-05-06 00:08:46 +00003156 Py_END_ALLOW_THREADS
Victor Stinner292c8352012-10-30 02:17:38 +01003157 if (res < 0) {
Larry Hastings2f936352014-08-05 14:04:04 +10003158 path_error(path);
Victor Stinner292c8352012-10-30 02:17:38 +01003159 return NULL;
3160 }
Victor Stinner8c62be82010-05-06 00:08:46 +00003161 Py_RETURN_NONE;
Christian Heimes4e30a842007-11-30 22:12:06 +00003162}
3163#endif /* HAVE_LCHMOD */
3164
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00003165
Thomas Wouterscf297e42007-02-23 15:07:44 +00003166#ifdef HAVE_CHFLAGS
Larry Hastings2f936352014-08-05 14:04:04 +10003167/*[clinic input]
3168os.chflags
3169
3170 path: path_t
3171 flags: unsigned_long(bitwise=True)
3172 follow_symlinks: bool=True
3173
3174Set file flags.
3175
3176If follow_symlinks is False, and the last element of the path is a symbolic
3177 link, chflags will change flags on the symbolic link itself instead of the
3178 file the link points to.
3179follow_symlinks may not be implemented on your platform. If it is
3180unavailable, using it will raise a NotImplementedError.
3181
3182[clinic start generated code]*/
3183
Larry Hastings2f936352014-08-05 14:04:04 +10003184static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003185os_chflags_impl(PyObject *module, path_t *path, unsigned long flags,
Larry Hastings89964c42015-04-14 18:07:59 -04003186 int follow_symlinks)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003187/*[clinic end generated code: output=85571c6737661ce9 input=0327e29feb876236]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003188{
3189 int result;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003190
3191#ifndef HAVE_LCHFLAGS
3192 if (follow_symlinks_specified("chflags", follow_symlinks))
Larry Hastings2f936352014-08-05 14:04:04 +10003193 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003194#endif
3195
Victor Stinner8c62be82010-05-06 00:08:46 +00003196 Py_BEGIN_ALLOW_THREADS
Larry Hastings9cf065c2012-06-22 16:30:09 -07003197#ifdef HAVE_LCHFLAGS
3198 if (!follow_symlinks)
Larry Hastings2f936352014-08-05 14:04:04 +10003199 result = lchflags(path->narrow, flags);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003200 else
3201#endif
Larry Hastings2f936352014-08-05 14:04:04 +10003202 result = chflags(path->narrow, flags);
Victor Stinner8c62be82010-05-06 00:08:46 +00003203 Py_END_ALLOW_THREADS
Larry Hastings9cf065c2012-06-22 16:30:09 -07003204
Larry Hastings2f936352014-08-05 14:04:04 +10003205 if (result)
3206 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003207
Larry Hastings2f936352014-08-05 14:04:04 +10003208 Py_RETURN_NONE;
Thomas Wouterscf297e42007-02-23 15:07:44 +00003209}
3210#endif /* HAVE_CHFLAGS */
3211
Larry Hastings2f936352014-08-05 14:04:04 +10003212
Thomas Wouterscf297e42007-02-23 15:07:44 +00003213#ifdef HAVE_LCHFLAGS
Larry Hastings2f936352014-08-05 14:04:04 +10003214/*[clinic input]
3215os.lchflags
3216
3217 path: path_t
3218 flags: unsigned_long(bitwise=True)
3219
3220Set file flags.
3221
3222This function will not follow symbolic links.
3223Equivalent to chflags(path, flags, follow_symlinks=False).
3224[clinic start generated code]*/
3225
Larry Hastings2f936352014-08-05 14:04:04 +10003226static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003227os_lchflags_impl(PyObject *module, path_t *path, unsigned long flags)
3228/*[clinic end generated code: output=30ae958695c07316 input=f9f82ea8b585ca9d]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003229{
Victor Stinner8c62be82010-05-06 00:08:46 +00003230 int res;
Victor Stinner8c62be82010-05-06 00:08:46 +00003231 Py_BEGIN_ALLOW_THREADS
Larry Hastingsb1dc1122014-08-05 16:06:16 +10003232 res = lchflags(path->narrow, flags);
Victor Stinner8c62be82010-05-06 00:08:46 +00003233 Py_END_ALLOW_THREADS
Victor Stinner292c8352012-10-30 02:17:38 +01003234 if (res < 0) {
Larry Hastings2f936352014-08-05 14:04:04 +10003235 return path_error(path);
Victor Stinner292c8352012-10-30 02:17:38 +01003236 }
Victor Stinner292c8352012-10-30 02:17:38 +01003237 Py_RETURN_NONE;
Thomas Wouterscf297e42007-02-23 15:07:44 +00003238}
3239#endif /* HAVE_LCHFLAGS */
3240
Larry Hastings2f936352014-08-05 14:04:04 +10003241
Martin v. Löwis244edc82001-10-04 22:44:26 +00003242#ifdef HAVE_CHROOT
Larry Hastings2f936352014-08-05 14:04:04 +10003243/*[clinic input]
3244os.chroot
3245 path: path_t
3246
3247Change root directory to path.
3248
3249[clinic start generated code]*/
3250
Larry Hastings2f936352014-08-05 14:04:04 +10003251static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003252os_chroot_impl(PyObject *module, path_t *path)
3253/*[clinic end generated code: output=de80befc763a4475 input=14822965652c3dc3]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003254{
3255 int res;
3256 Py_BEGIN_ALLOW_THREADS
3257 res = chroot(path->narrow);
3258 Py_END_ALLOW_THREADS
3259 if (res < 0)
3260 return path_error(path);
3261 Py_RETURN_NONE;
3262}
3263#endif /* HAVE_CHROOT */
3264
Martin v. Löwis244edc82001-10-04 22:44:26 +00003265
Guido van Rossum21142a01999-01-08 21:05:37 +00003266#ifdef HAVE_FSYNC
Larry Hastings2f936352014-08-05 14:04:04 +10003267/*[clinic input]
3268os.fsync
3269
3270 fd: fildes
3271
3272Force write of fd to disk.
3273[clinic start generated code]*/
3274
Larry Hastings2f936352014-08-05 14:04:04 +10003275static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003276os_fsync_impl(PyObject *module, int fd)
3277/*[clinic end generated code: output=4a10d773f52b3584 input=21c3645c056967f2]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003278{
3279 return posix_fildes_fd(fd, fsync);
Guido van Rossum21142a01999-01-08 21:05:37 +00003280}
3281#endif /* HAVE_FSYNC */
3282
Larry Hastings2f936352014-08-05 14:04:04 +10003283
Ross Lagerwall7807c352011-03-17 20:20:30 +02003284#ifdef HAVE_SYNC
Larry Hastings2f936352014-08-05 14:04:04 +10003285/*[clinic input]
3286os.sync
3287
3288Force write of everything to disk.
3289[clinic start generated code]*/
3290
Larry Hastings2f936352014-08-05 14:04:04 +10003291static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003292os_sync_impl(PyObject *module)
3293/*[clinic end generated code: output=2796b1f0818cd71c input=84749fe5e9b404ff]*/
Ross Lagerwall7807c352011-03-17 20:20:30 +02003294{
3295 Py_BEGIN_ALLOW_THREADS
3296 sync();
3297 Py_END_ALLOW_THREADS
3298 Py_RETURN_NONE;
3299}
Larry Hastings2f936352014-08-05 14:04:04 +10003300#endif /* HAVE_SYNC */
3301
Ross Lagerwall7807c352011-03-17 20:20:30 +02003302
Guido van Rossum21142a01999-01-08 21:05:37 +00003303#ifdef HAVE_FDATASYNC
Guido van Rossum7f58e2e2000-09-22 17:26:14 +00003304#ifdef __hpux
Guido van Rossumecc23b02000-09-22 16:01:05 +00003305extern int fdatasync(int); /* On HP-UX, in libc but not in unistd.h */
3306#endif
3307
Larry Hastings2f936352014-08-05 14:04:04 +10003308/*[clinic input]
3309os.fdatasync
3310
3311 fd: fildes
3312
3313Force write of fd to disk without forcing update of metadata.
3314[clinic start generated code]*/
3315
Larry Hastings2f936352014-08-05 14:04:04 +10003316static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003317os_fdatasync_impl(PyObject *module, int fd)
3318/*[clinic end generated code: output=b4b9698b5d7e26dd input=bc74791ee54dd291]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003319{
3320 return posix_fildes_fd(fd, fdatasync);
Guido van Rossum21142a01999-01-08 21:05:37 +00003321}
3322#endif /* HAVE_FDATASYNC */
3323
3324
Fredrik Lundh10723342000-07-10 16:38:09 +00003325#ifdef HAVE_CHOWN
Larry Hastings2f936352014-08-05 14:04:04 +10003326/*[clinic input]
3327os.chown
3328
3329 path : path_t(allow_fd='PATH_HAVE_FCHOWN')
BNMetricsb9427072018-11-02 15:20:19 +00003330 Path to be examined; can be string, bytes, a path-like object, or open-file-descriptor int.
Larry Hastings2f936352014-08-05 14:04:04 +10003331
3332 uid: uid_t
3333
3334 gid: gid_t
3335
3336 *
3337
3338 dir_fd : dir_fd(requires='fchownat') = None
3339 If 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
3341 directory.
3342
3343 follow_symlinks: bool = True
3344 If False, and the last element of the path is a symbolic link,
3345 stat will examine the symbolic link itself instead of the file
3346 the link points to.
3347
3348Change the owner and group id of path to the numeric uid and gid.\
3349
3350path may always be specified as a string.
3351On some platforms, path may also be specified as an open file descriptor.
3352 If this functionality is unavailable, using it raises an exception.
3353If dir_fd is not None, it should be a file descriptor open to a directory,
3354 and path should be relative; path will then be relative to that directory.
3355If follow_symlinks is False, and the last element of the path is a symbolic
3356 link, chown will modify the symbolic link itself instead of the file the
3357 link points to.
3358It is an error to use dir_fd or follow_symlinks when specifying path as
3359 an open file descriptor.
3360dir_fd and follow_symlinks may not be implemented on your platform.
3361 If they are unavailable, using them will raise a NotImplementedError.
3362
3363[clinic start generated code]*/
3364
Larry Hastings2f936352014-08-05 14:04:04 +10003365static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003366os_chown_impl(PyObject *module, path_t *path, uid_t uid, gid_t gid,
Larry Hastings89964c42015-04-14 18:07:59 -04003367 int dir_fd, int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +00003368/*[clinic end generated code: output=4beadab0db5f70cd input=b08c5ec67996a97d]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003369{
3370 int result;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003371
3372#if !(defined(HAVE_LCHOWN) || defined(HAVE_FCHOWNAT))
3373 if (follow_symlinks_specified("chown", follow_symlinks))
Larry Hastings2f936352014-08-05 14:04:04 +10003374 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003375#endif
Larry Hastings2f936352014-08-05 14:04:04 +10003376 if (dir_fd_and_fd_invalid("chown", dir_fd, path->fd) ||
3377 fd_and_follow_symlinks_invalid("chown", path->fd, follow_symlinks))
3378 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003379
3380#ifdef __APPLE__
3381 /*
3382 * This is for Mac OS X 10.3, which doesn't have lchown.
3383 * (But we still have an lchown symbol because of weak-linking.)
3384 * It doesn't have fchownat either. So there's no possibility
3385 * of a graceful failover.
Georg Brandlf7875592012-06-24 13:58:31 +02003386 */
Larry Hastings9cf065c2012-06-22 16:30:09 -07003387 if ((!follow_symlinks) && (lchown == NULL)) {
3388 follow_symlinks_specified("chown", follow_symlinks);
Larry Hastings2f936352014-08-05 14:04:04 +10003389 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003390 }
3391#endif
3392
Victor Stinner8c62be82010-05-06 00:08:46 +00003393 Py_BEGIN_ALLOW_THREADS
Larry Hastings9cf065c2012-06-22 16:30:09 -07003394#ifdef HAVE_FCHOWN
Larry Hastings2f936352014-08-05 14:04:04 +10003395 if (path->fd != -1)
3396 result = fchown(path->fd, uid, gid);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003397 else
3398#endif
3399#ifdef HAVE_LCHOWN
3400 if ((!follow_symlinks) && (dir_fd == DEFAULT_DIR_FD))
Larry Hastings2f936352014-08-05 14:04:04 +10003401 result = lchown(path->narrow, uid, gid);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003402 else
3403#endif
3404#ifdef HAVE_FCHOWNAT
3405 if ((dir_fd != DEFAULT_DIR_FD) || (!follow_symlinks))
Larry Hastings2f936352014-08-05 14:04:04 +10003406 result = fchownat(dir_fd, path->narrow, uid, gid,
Larry Hastings9cf065c2012-06-22 16:30:09 -07003407 follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW);
3408 else
3409#endif
Larry Hastings2f936352014-08-05 14:04:04 +10003410 result = chown(path->narrow, uid, gid);
Victor Stinner8c62be82010-05-06 00:08:46 +00003411 Py_END_ALLOW_THREADS
Larry Hastings9cf065c2012-06-22 16:30:09 -07003412
Larry Hastings2f936352014-08-05 14:04:04 +10003413 if (result)
3414 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003415
Larry Hastings2f936352014-08-05 14:04:04 +10003416 Py_RETURN_NONE;
Guido van Rossumb6775db1994-08-01 11:34:53 +00003417}
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +00003418#endif /* HAVE_CHOWN */
Guido van Rossumb6775db1994-08-01 11:34:53 +00003419
Larry Hastings2f936352014-08-05 14:04:04 +10003420
Christian Heimes4e30a842007-11-30 22:12:06 +00003421#ifdef HAVE_FCHOWN
Larry Hastings2f936352014-08-05 14:04:04 +10003422/*[clinic input]
3423os.fchown
3424
3425 fd: int
3426 uid: uid_t
3427 gid: gid_t
3428
3429Change the owner and group id of the file specified by file descriptor.
3430
3431Equivalent to os.chown(fd, uid, gid).
3432
3433[clinic start generated code]*/
3434
Larry Hastings2f936352014-08-05 14:04:04 +10003435static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003436os_fchown_impl(PyObject *module, int fd, uid_t uid, gid_t gid)
3437/*[clinic end generated code: output=97d21cbd5a4350a6 input=3af544ba1b13a0d7]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003438{
Victor Stinner8c62be82010-05-06 00:08:46 +00003439 int res;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00003440 int async_err = 0;
3441
3442 do {
3443 Py_BEGIN_ALLOW_THREADS
3444 res = fchown(fd, uid, gid);
3445 Py_END_ALLOW_THREADS
3446 } while (res != 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
3447 if (res != 0)
3448 return (!async_err) ? posix_error() : NULL;
3449
Victor Stinner8c62be82010-05-06 00:08:46 +00003450 Py_RETURN_NONE;
Christian Heimes4e30a842007-11-30 22:12:06 +00003451}
3452#endif /* HAVE_FCHOWN */
3453
Larry Hastings2f936352014-08-05 14:04:04 +10003454
Martin v. Löwis0cec0ff2002-07-28 16:33:45 +00003455#ifdef HAVE_LCHOWN
Larry Hastings2f936352014-08-05 14:04:04 +10003456/*[clinic input]
3457os.lchown
3458
3459 path : path_t
3460 uid: uid_t
3461 gid: gid_t
3462
3463Change the owner and group id of path to the numeric uid and gid.
3464
3465This function will not follow symbolic links.
3466Equivalent to os.chown(path, uid, gid, follow_symlinks=False).
3467[clinic start generated code]*/
3468
Larry Hastings2f936352014-08-05 14:04:04 +10003469static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003470os_lchown_impl(PyObject *module, path_t *path, uid_t uid, gid_t gid)
3471/*[clinic end generated code: output=25eaf6af412fdf2f input=b1c6014d563a7161]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003472{
Victor Stinner8c62be82010-05-06 00:08:46 +00003473 int res;
Victor Stinner8c62be82010-05-06 00:08:46 +00003474 Py_BEGIN_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10003475 res = lchown(path->narrow, uid, gid);
Victor Stinner8c62be82010-05-06 00:08:46 +00003476 Py_END_ALLOW_THREADS
Victor Stinner292c8352012-10-30 02:17:38 +01003477 if (res < 0) {
Larry Hastings2f936352014-08-05 14:04:04 +10003478 return path_error(path);
Victor Stinner292c8352012-10-30 02:17:38 +01003479 }
Larry Hastings2f936352014-08-05 14:04:04 +10003480 Py_RETURN_NONE;
Martin v. Löwis0cec0ff2002-07-28 16:33:45 +00003481}
3482#endif /* HAVE_LCHOWN */
3483
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00003484
Barry Warsaw53699e91996-12-10 23:23:01 +00003485static PyObject *
Guido van Rossumf0af3e32008-10-02 18:55:37 +00003486posix_getcwd(int use_bytes)
Mark Hammondc2e85bd2002-10-03 05:10:39 +00003487{
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00003488#ifdef MS_WINDOWS
Victor Stinner689830e2019-06-26 17:31:12 +02003489 wchar_t wbuf[MAXPATHLEN];
3490 wchar_t *wbuf2 = wbuf;
3491 DWORD len;
3492
3493 Py_BEGIN_ALLOW_THREADS
3494 len = GetCurrentDirectoryW(Py_ARRAY_LENGTH(wbuf), wbuf);
3495 /* If the buffer is large enough, len does not include the
3496 terminating \0. If the buffer is too small, len includes
3497 the space needed for the terminator. */
3498 if (len >= Py_ARRAY_LENGTH(wbuf)) {
Victor Stinnerec3e20a2019-06-28 18:01:59 +02003499 if (len <= PY_SSIZE_T_MAX / sizeof(wchar_t)) {
Victor Stinnerb6404912013-07-07 16:21:41 +02003500 wbuf2 = PyMem_RawMalloc(len * sizeof(wchar_t));
Victor Stinner8c62be82010-05-06 00:08:46 +00003501 }
Victor Stinner689830e2019-06-26 17:31:12 +02003502 else {
3503 wbuf2 = NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00003504 }
Victor Stinner689830e2019-06-26 17:31:12 +02003505 if (wbuf2) {
3506 len = GetCurrentDirectoryW(len, wbuf2);
Victor Stinner8c62be82010-05-06 00:08:46 +00003507 }
Victor Stinner689830e2019-06-26 17:31:12 +02003508 }
3509 Py_END_ALLOW_THREADS
3510
3511 if (!wbuf2) {
3512 PyErr_NoMemory();
3513 return NULL;
3514 }
3515 if (!len) {
Victor Stinnerb024e842012-10-31 22:24:06 +01003516 if (wbuf2 != wbuf)
Victor Stinnerb6404912013-07-07 16:21:41 +02003517 PyMem_RawFree(wbuf2);
Victor Stinner689830e2019-06-26 17:31:12 +02003518 return PyErr_SetFromWindowsErr(0);
Victor Stinner8c62be82010-05-06 00:08:46 +00003519 }
Victor Stinnerf7c5ae22011-11-16 23:43:07 +01003520
Victor Stinner689830e2019-06-26 17:31:12 +02003521 PyObject *resobj = PyUnicode_FromWideChar(wbuf2, len);
3522 if (wbuf2 != wbuf) {
3523 PyMem_RawFree(wbuf2);
3524 }
Mark Hammondc2e85bd2002-10-03 05:10:39 +00003525
Victor Stinner689830e2019-06-26 17:31:12 +02003526 if (use_bytes) {
3527 if (resobj == NULL) {
3528 return NULL;
3529 }
3530 Py_SETREF(resobj, PyUnicode_EncodeFSDefault(resobj));
3531 }
3532
3533 return resobj;
3534#else
3535 const size_t chunk = 1024;
3536
3537 char *buf = NULL;
3538 char *cwd = NULL;
3539 size_t buflen = 0;
3540
Victor Stinner8c62be82010-05-06 00:08:46 +00003541 Py_BEGIN_ALLOW_THREADS
Victor Stinner4403d7d2015-04-25 00:16:10 +02003542 do {
Victor Stinner689830e2019-06-26 17:31:12 +02003543 char *newbuf;
3544 if (buflen <= PY_SSIZE_T_MAX - chunk) {
3545 buflen += chunk;
3546 newbuf = PyMem_RawRealloc(buf, buflen);
3547 }
3548 else {
3549 newbuf = NULL;
3550 }
3551 if (newbuf == NULL) {
3552 PyMem_RawFree(buf);
3553 buf = NULL;
Victor Stinnerc44f7072016-03-14 18:07:53 +01003554 break;
3555 }
Victor Stinner689830e2019-06-26 17:31:12 +02003556 buf = newbuf;
Victor Stinner4403d7d2015-04-25 00:16:10 +02003557
Victor Stinner4403d7d2015-04-25 00:16:10 +02003558 cwd = getcwd(buf, buflen);
3559 } while (cwd == NULL && errno == ERANGE);
Victor Stinner8c62be82010-05-06 00:08:46 +00003560 Py_END_ALLOW_THREADS
Victor Stinner4403d7d2015-04-25 00:16:10 +02003561
Victor Stinner689830e2019-06-26 17:31:12 +02003562 if (buf == NULL) {
3563 return PyErr_NoMemory();
3564 }
Victor Stinner4403d7d2015-04-25 00:16:10 +02003565 if (cwd == NULL) {
3566 PyMem_RawFree(buf);
Victor Stinner8c62be82010-05-06 00:08:46 +00003567 return posix_error();
Victor Stinner4403d7d2015-04-25 00:16:10 +02003568 }
3569
Victor Stinner689830e2019-06-26 17:31:12 +02003570 PyObject *obj;
3571 if (use_bytes) {
Victor Stinner4403d7d2015-04-25 00:16:10 +02003572 obj = PyBytes_FromStringAndSize(buf, strlen(buf));
Victor Stinner689830e2019-06-26 17:31:12 +02003573 }
3574 else {
Victor Stinner4403d7d2015-04-25 00:16:10 +02003575 obj = PyUnicode_DecodeFSDefault(buf);
Victor Stinner689830e2019-06-26 17:31:12 +02003576 }
Victor Stinner4403d7d2015-04-25 00:16:10 +02003577 PyMem_RawFree(buf);
3578
3579 return obj;
Victor Stinner689830e2019-06-26 17:31:12 +02003580#endif /* !MS_WINDOWS */
Mark Hammondc2e85bd2002-10-03 05:10:39 +00003581}
Guido van Rossumf0af3e32008-10-02 18:55:37 +00003582
Larry Hastings2f936352014-08-05 14:04:04 +10003583
3584/*[clinic input]
3585os.getcwd
3586
3587Return a unicode 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_getcwd_impl(PyObject *module)
3592/*[clinic end generated code: output=21badfae2ea99ddc input=f069211bb70e3d39]*/
Guido van Rossumf0af3e32008-10-02 18:55:37 +00003593{
3594 return posix_getcwd(0);
3595}
3596
Larry Hastings2f936352014-08-05 14:04:04 +10003597
3598/*[clinic input]
3599os.getcwdb
3600
3601Return a bytes string representing the current working directory.
3602[clinic start generated code]*/
3603
Larry Hastings2f936352014-08-05 14:04:04 +10003604static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003605os_getcwdb_impl(PyObject *module)
3606/*[clinic end generated code: output=3dd47909480e4824 input=f6f6a378dad3d9cb]*/
Guido van Rossumf0af3e32008-10-02 18:55:37 +00003607{
3608 return posix_getcwd(1);
3609}
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003610
Larry Hastings2f936352014-08-05 14:04:04 +10003611
Larry Hastings9cf065c2012-06-22 16:30:09 -07003612#if ((!defined(HAVE_LINK)) && defined(MS_WINDOWS))
3613#define HAVE_LINK 1
3614#endif
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00003615
Guido van Rossumb6775db1994-08-01 11:34:53 +00003616#ifdef HAVE_LINK
Larry Hastings2f936352014-08-05 14:04:04 +10003617/*[clinic input]
3618
3619os.link
3620
3621 src : path_t
3622 dst : path_t
3623 *
3624 src_dir_fd : dir_fd = None
3625 dst_dir_fd : dir_fd = None
3626 follow_symlinks: bool = True
3627
3628Create a hard link to a file.
3629
3630If either src_dir_fd or dst_dir_fd is not None, it should be a file
3631 descriptor open to a directory, and the respective path string (src or dst)
3632 should be relative; the path will then be relative to that directory.
3633If follow_symlinks is False, and the last element of src is a symbolic
3634 link, link will create a link to the symbolic link itself instead of the
3635 file the link points to.
3636src_dir_fd, dst_dir_fd, and follow_symlinks may not be implemented on your
3637 platform. If they are unavailable, using them will raise a
3638 NotImplementedError.
3639[clinic start generated code]*/
3640
Larry Hastings2f936352014-08-05 14:04:04 +10003641static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003642os_link_impl(PyObject *module, path_t *src, path_t *dst, int src_dir_fd,
Larry Hastings89964c42015-04-14 18:07:59 -04003643 int dst_dir_fd, int follow_symlinks)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003644/*[clinic end generated code: output=7f00f6007fd5269a input=b0095ebbcbaa7e04]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003645{
Larry Hastings9cf065c2012-06-22 16:30:09 -07003646#ifdef MS_WINDOWS
Steve Dowercc16be82016-09-08 10:35:16 -07003647 BOOL result = FALSE;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003648#else
3649 int result;
3650#endif
3651
Larry Hastings9cf065c2012-06-22 16:30:09 -07003652#ifndef HAVE_LINKAT
3653 if ((src_dir_fd != DEFAULT_DIR_FD) || (dst_dir_fd != DEFAULT_DIR_FD)) {
3654 argument_unavailable_error("link", "src_dir_fd and dst_dir_fd");
Larry Hastings2f936352014-08-05 14:04:04 +10003655 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003656 }
3657#endif
3658
Steve Dowercc16be82016-09-08 10:35:16 -07003659#ifndef MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +10003660 if ((src->narrow && dst->wide) || (src->wide && dst->narrow)) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07003661 PyErr_SetString(PyExc_NotImplementedError,
3662 "link: src and dst must be the same type");
Larry Hastings2f936352014-08-05 14:04:04 +10003663 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003664 }
Steve Dowercc16be82016-09-08 10:35:16 -07003665#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003666
Brian Curtin1b9df392010-11-24 20:24:31 +00003667#ifdef MS_WINDOWS
Larry Hastings9cf065c2012-06-22 16:30:09 -07003668 Py_BEGIN_ALLOW_THREADS
Steve Dowerc3630612016-11-19 18:41:16 -08003669 result = CreateHardLinkW(dst->wide, src->wide, NULL);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003670 Py_END_ALLOW_THREADS
Brian Curtin1b9df392010-11-24 20:24:31 +00003671
Larry Hastings2f936352014-08-05 14:04:04 +10003672 if (!result)
3673 return path_error2(src, dst);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003674#else
3675 Py_BEGIN_ALLOW_THREADS
Larry Hastings67cbf7b2012-06-22 17:06:48 -07003676#ifdef HAVE_LINKAT
Larry Hastings9cf065c2012-06-22 16:30:09 -07003677 if ((src_dir_fd != DEFAULT_DIR_FD) ||
3678 (dst_dir_fd != DEFAULT_DIR_FD) ||
3679 (!follow_symlinks))
Larry Hastings2f936352014-08-05 14:04:04 +10003680 result = linkat(src_dir_fd, src->narrow,
3681 dst_dir_fd, dst->narrow,
Larry Hastings9cf065c2012-06-22 16:30:09 -07003682 follow_symlinks ? AT_SYMLINK_FOLLOW : 0);
3683 else
Steve Dowercc16be82016-09-08 10:35:16 -07003684#endif /* HAVE_LINKAT */
Larry Hastings2f936352014-08-05 14:04:04 +10003685 result = link(src->narrow, dst->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003686 Py_END_ALLOW_THREADS
Brian Curtinfc889c42010-11-28 23:59:46 +00003687
Larry Hastings2f936352014-08-05 14:04:04 +10003688 if (result)
3689 return path_error2(src, dst);
Steve Dowercc16be82016-09-08 10:35:16 -07003690#endif /* MS_WINDOWS */
Larry Hastings9cf065c2012-06-22 16:30:09 -07003691
Larry Hastings2f936352014-08-05 14:04:04 +10003692 Py_RETURN_NONE;
Brian Curtin1b9df392010-11-24 20:24:31 +00003693}
Larry Hastings9cf065c2012-06-22 16:30:09 -07003694#endif
3695
Brian Curtin1b9df392010-11-24 20:24:31 +00003696
Gregory P. Smith16ea14a2013-03-20 18:51:33 -07003697#if defined(MS_WINDOWS) && !defined(HAVE_OPENDIR)
Barry Warsaw53699e91996-12-10 23:23:01 +00003698static PyObject *
Gregory P. Smith40a21602013-03-20 20:52:50 -07003699_listdir_windows_no_opendir(path_t *path, PyObject *list)
Guido van Rossumb6775db1994-08-01 11:34:53 +00003700{
Larry Hastings9cf065c2012-06-22 16:30:09 -07003701 PyObject *v;
3702 HANDLE hFindFile = INVALID_HANDLE_VALUE;
3703 BOOL result;
Steve Dowercc16be82016-09-08 10:35:16 -07003704 wchar_t namebuf[MAX_PATH+4]; /* Overallocate for "\*.*" */
Larry Hastings9cf065c2012-06-22 16:30:09 -07003705 /* only claim to have space for MAX_PATH */
Victor Stinner75875072013-11-24 19:23:25 +01003706 Py_ssize_t len = Py_ARRAY_LENGTH(namebuf)-4;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003707 wchar_t *wnamebuf = NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003708
Steve Dowercc16be82016-09-08 10:35:16 -07003709 WIN32_FIND_DATAW wFileData;
3710 const wchar_t *po_wchars;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00003711
Steve Dowercc16be82016-09-08 10:35:16 -07003712 if (!path->wide) { /* Default arg: "." */
3713 po_wchars = L".";
3714 len = 1;
3715 } else {
3716 po_wchars = path->wide;
3717 len = wcslen(path->wide);
3718 }
3719 /* The +5 is so we can append "\\*.*\0" */
3720 wnamebuf = PyMem_New(wchar_t, len + 5);
3721 if (!wnamebuf) {
3722 PyErr_NoMemory();
Larry Hastings9cf065c2012-06-22 16:30:09 -07003723 goto exit;
Victor Stinner8c62be82010-05-06 00:08:46 +00003724 }
Steve Dowercc16be82016-09-08 10:35:16 -07003725 wcscpy(wnamebuf, po_wchars);
Victor Stinner8c62be82010-05-06 00:08:46 +00003726 if (len > 0) {
Steve Dowercc16be82016-09-08 10:35:16 -07003727 wchar_t wch = wnamebuf[len-1];
3728 if (wch != SEP && wch != ALTSEP && wch != L':')
3729 wnamebuf[len++] = SEP;
3730 wcscpy(wnamebuf + len, L"*.*");
Victor Stinner8c62be82010-05-06 00:08:46 +00003731 }
Steve Dowercc16be82016-09-08 10:35:16 -07003732 if ((list = PyList_New(0)) == NULL) {
3733 goto exit;
3734 }
Antoine Pitroub73caab2010-08-09 23:39:31 +00003735 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -07003736 hFindFile = FindFirstFileW(wnamebuf, &wFileData);
Antoine Pitroub73caab2010-08-09 23:39:31 +00003737 Py_END_ALLOW_THREADS
Victor Stinner8c62be82010-05-06 00:08:46 +00003738 if (hFindFile == INVALID_HANDLE_VALUE) {
3739 int error = GetLastError();
3740 if (error == ERROR_FILE_NOT_FOUND)
Larry Hastings9cf065c2012-06-22 16:30:09 -07003741 goto exit;
3742 Py_DECREF(list);
Gregory P. Smith40a21602013-03-20 20:52:50 -07003743 list = path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003744 goto exit;
Victor Stinner8c62be82010-05-06 00:08:46 +00003745 }
3746 do {
3747 /* Skip over . and .. */
Steve Dowercc16be82016-09-08 10:35:16 -07003748 if (wcscmp(wFileData.cFileName, L".") != 0 &&
3749 wcscmp(wFileData.cFileName, L"..") != 0) {
3750 v = PyUnicode_FromWideChar(wFileData.cFileName,
3751 wcslen(wFileData.cFileName));
3752 if (path->narrow && v) {
3753 Py_SETREF(v, PyUnicode_EncodeFSDefault(v));
3754 }
Victor Stinner8c62be82010-05-06 00:08:46 +00003755 if (v == NULL) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07003756 Py_DECREF(list);
3757 list = NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00003758 break;
3759 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07003760 if (PyList_Append(list, v) != 0) {
Victor Stinner8c62be82010-05-06 00:08:46 +00003761 Py_DECREF(v);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003762 Py_DECREF(list);
3763 list = NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00003764 break;
3765 }
3766 Py_DECREF(v);
3767 }
3768 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -07003769 result = FindNextFileW(hFindFile, &wFileData);
Victor Stinner8c62be82010-05-06 00:08:46 +00003770 Py_END_ALLOW_THREADS
3771 /* FindNextFile sets error to ERROR_NO_MORE_FILES if
3772 it got to the end of the directory. */
3773 if (!result && GetLastError() != ERROR_NO_MORE_FILES) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07003774 Py_DECREF(list);
Gregory P. Smith40a21602013-03-20 20:52:50 -07003775 list = path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003776 goto exit;
Victor Stinner8c62be82010-05-06 00:08:46 +00003777 }
3778 } while (result == TRUE);
Guido van Rossumb6775db1994-08-01 11:34:53 +00003779
Larry Hastings9cf065c2012-06-22 16:30:09 -07003780exit:
3781 if (hFindFile != INVALID_HANDLE_VALUE) {
3782 if (FindClose(hFindFile) == FALSE) {
3783 if (list != NULL) {
3784 Py_DECREF(list);
Gregory P. Smith40a21602013-03-20 20:52:50 -07003785 list = path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003786 }
3787 }
Victor Stinner8c62be82010-05-06 00:08:46 +00003788 }
Victor Stinnerb6404912013-07-07 16:21:41 +02003789 PyMem_Free(wnamebuf);
Guido van Rossumb6775db1994-08-01 11:34:53 +00003790
Larry Hastings9cf065c2012-06-22 16:30:09 -07003791 return list;
Gregory P. Smith16ea14a2013-03-20 18:51:33 -07003792} /* end of _listdir_windows_no_opendir */
3793
3794#else /* thus POSIX, ie: not (MS_WINDOWS and not HAVE_OPENDIR) */
3795
3796static PyObject *
Gregory P. Smith40a21602013-03-20 20:52:50 -07003797_posix_listdir(path_t *path, PyObject *list)
Gregory P. Smith16ea14a2013-03-20 18:51:33 -07003798{
Gregory P. Smith16ea14a2013-03-20 18:51:33 -07003799 PyObject *v;
3800 DIR *dirp = NULL;
3801 struct dirent *ep;
3802 int return_str; /* if false, return bytes */
Larry Hastings4dbc95e2013-08-01 18:18:56 -07003803#ifdef HAVE_FDOPENDIR
3804 int fd = -1;
3805#endif
Gregory P. Smith16ea14a2013-03-20 18:51:33 -07003806
Victor Stinner8c62be82010-05-06 00:08:46 +00003807 errno = 0;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003808#ifdef HAVE_FDOPENDIR
Gregory P. Smith40a21602013-03-20 20:52:50 -07003809 if (path->fd != -1) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07003810 /* closedir() closes the FD, so we duplicate it */
Victor Stinnerdaf45552013-08-28 00:53:59 +02003811 fd = _Py_dup(path->fd);
Victor Stinnerf3266652013-12-19 13:24:49 +01003812 if (fd == -1)
3813 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003814
Larry Hastingsfdaea062012-06-25 04:42:23 -07003815 return_str = 1;
3816
Larry Hastings9cf065c2012-06-22 16:30:09 -07003817 Py_BEGIN_ALLOW_THREADS
3818 dirp = fdopendir(fd);
3819 Py_END_ALLOW_THREADS
3820 }
3821 else
3822#endif
3823 {
Serhiy Storchakadeab18d2016-05-07 16:45:18 +03003824 const char *name;
Gregory P. Smith40a21602013-03-20 20:52:50 -07003825 if (path->narrow) {
3826 name = path->narrow;
Serhiy Storchaka1180e5a2017-07-11 06:36:46 +03003827 /* only return bytes if they specified a bytes-like object */
3828 return_str = !PyObject_CheckBuffer(path->object);
Larry Hastingsfdaea062012-06-25 04:42:23 -07003829 }
3830 else {
3831 name = ".";
3832 return_str = 1;
3833 }
3834
Larry Hastings9cf065c2012-06-22 16:30:09 -07003835 Py_BEGIN_ALLOW_THREADS
3836 dirp = opendir(name);
3837 Py_END_ALLOW_THREADS
3838 }
3839
3840 if (dirp == NULL) {
Gregory P. Smith40a21602013-03-20 20:52:50 -07003841 list = path_error(path);
Larry Hastings4dbc95e2013-08-01 18:18:56 -07003842#ifdef HAVE_FDOPENDIR
3843 if (fd != -1) {
3844 Py_BEGIN_ALLOW_THREADS
3845 close(fd);
3846 Py_END_ALLOW_THREADS
3847 }
3848#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -07003849 goto exit;
3850 }
3851 if ((list = PyList_New(0)) == NULL) {
3852 goto exit;
Victor Stinner8c62be82010-05-06 00:08:46 +00003853 }
3854 for (;;) {
3855 errno = 0;
3856 Py_BEGIN_ALLOW_THREADS
3857 ep = readdir(dirp);
3858 Py_END_ALLOW_THREADS
3859 if (ep == NULL) {
3860 if (errno == 0) {
3861 break;
3862 } else {
Larry Hastings9cf065c2012-06-22 16:30:09 -07003863 Py_DECREF(list);
Gregory P. Smith40a21602013-03-20 20:52:50 -07003864 list = path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003865 goto exit;
Victor Stinner8c62be82010-05-06 00:08:46 +00003866 }
3867 }
3868 if (ep->d_name[0] == '.' &&
3869 (NAMLEN(ep) == 1 ||
3870 (ep->d_name[1] == '.' && NAMLEN(ep) == 2)))
3871 continue;
Larry Hastingsfdaea062012-06-25 04:42:23 -07003872 if (return_str)
Victor Stinnera45598a2010-05-14 16:35:39 +00003873 v = PyUnicode_DecodeFSDefaultAndSize(ep->d_name, NAMLEN(ep));
3874 else
3875 v = PyBytes_FromStringAndSize(ep->d_name, NAMLEN(ep));
Victor Stinner8c62be82010-05-06 00:08:46 +00003876 if (v == NULL) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07003877 Py_CLEAR(list);
Victor Stinner8c62be82010-05-06 00:08:46 +00003878 break;
3879 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07003880 if (PyList_Append(list, v) != 0) {
Victor Stinner8c62be82010-05-06 00:08:46 +00003881 Py_DECREF(v);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003882 Py_CLEAR(list);
Victor Stinner8c62be82010-05-06 00:08:46 +00003883 break;
3884 }
3885 Py_DECREF(v);
3886 }
Guido van Rossum0ee42cd1991-04-08 21:01:03 +00003887
Larry Hastings9cf065c2012-06-22 16:30:09 -07003888exit:
3889 if (dirp != NULL) {
3890 Py_BEGIN_ALLOW_THREADS
Larry Hastings4dbc95e2013-08-01 18:18:56 -07003891#ifdef HAVE_FDOPENDIR
Larry Hastings9cf065c2012-06-22 16:30:09 -07003892 if (fd > -1)
3893 rewinddir(dirp);
Larry Hastings4dbc95e2013-08-01 18:18:56 -07003894#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -07003895 closedir(dirp);
3896 Py_END_ALLOW_THREADS
3897 }
3898
Larry Hastings9cf065c2012-06-22 16:30:09 -07003899 return list;
Gregory P. Smith16ea14a2013-03-20 18:51:33 -07003900} /* end of _posix_listdir */
3901#endif /* which OS */
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +00003902
Larry Hastings2f936352014-08-05 14:04:04 +10003903
3904/*[clinic input]
3905os.listdir
3906
3907 path : path_t(nullable=True, allow_fd='PATH_HAVE_FDOPENDIR') = None
3908
3909Return a list containing the names of the files in the directory.
3910
BNMetricsb9427072018-11-02 15:20:19 +00003911path can be specified as either str, bytes, or a path-like object. If path is bytes,
Larry Hastings2f936352014-08-05 14:04:04 +10003912 the filenames returned will also be bytes; in all other circumstances
3913 the filenames returned will be str.
3914If path is None, uses the path='.'.
3915On some platforms, path may also be specified as an open file descriptor;\
3916 the file descriptor must refer to a directory.
3917 If this functionality is unavailable, using it raises NotImplementedError.
3918
3919The list is in arbitrary order. It does not include the special
3920entries '.' and '..' even if they are present in the directory.
3921
3922
3923[clinic start generated code]*/
3924
Larry Hastings2f936352014-08-05 14:04:04 +10003925static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003926os_listdir_impl(PyObject *module, path_t *path)
BNMetricsb9427072018-11-02 15:20:19 +00003927/*[clinic end generated code: output=293045673fcd1a75 input=e3f58030f538295d]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003928{
Steve Dower60419a72019-06-24 08:42:54 -07003929 if (PySys_Audit("os.listdir", "O",
3930 path->object ? path->object : Py_None) < 0) {
3931 return NULL;
3932 }
Larry Hastings2f936352014-08-05 14:04:04 +10003933#if defined(MS_WINDOWS) && !defined(HAVE_OPENDIR)
3934 return _listdir_windows_no_opendir(path, NULL);
3935#else
3936 return _posix_listdir(path, NULL);
3937#endif
3938}
3939
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00003940#ifdef MS_WINDOWS
Mark Hammondef8b6542001-05-13 08:04:26 +00003941/* A helper function for abspath on win32 */
Serhiy Storchakaf0b50152015-05-13 00:52:39 +03003942/*[clinic input]
3943os._getfullpathname
Victor Stinnereb5657a2011-09-30 01:44:27 +02003944
Serhiy Storchakaf0b50152015-05-13 00:52:39 +03003945 path: path_t
3946 /
3947
3948[clinic start generated code]*/
3949
3950static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003951os__getfullpathname_impl(PyObject *module, path_t *path)
3952/*[clinic end generated code: output=bb8679d56845bc9b input=332ed537c29d0a3e]*/
Serhiy Storchakaf0b50152015-05-13 00:52:39 +03003953{
Victor Stinner3939c322019-06-25 15:02:43 +02003954 wchar_t *abspath;
Victor Stinnereb5657a2011-09-30 01:44:27 +02003955
Victor Stinner3939c322019-06-25 15:02:43 +02003956 /* _Py_abspath() is implemented with GetFullPathNameW() on Windows */
3957 if (_Py_abspath(path->wide, &abspath) < 0) {
3958 return win32_error_object("GetFullPathNameW", path->object);
Victor Stinner8c62be82010-05-06 00:08:46 +00003959 }
Victor Stinner3939c322019-06-25 15:02:43 +02003960 if (abspath == NULL) {
3961 return PyErr_NoMemory();
3962 }
3963
3964 PyObject *str = PyUnicode_FromWideChar(abspath, wcslen(abspath));
3965 PyMem_RawFree(abspath);
3966 if (str == NULL) {
3967 return NULL;
3968 }
3969 if (path->narrow) {
3970 Py_SETREF(str, PyUnicode_EncodeFSDefault(str));
3971 }
3972 return str;
Larry Hastings2f936352014-08-05 14:04:04 +10003973}
Brian Curtind40e6f72010-07-08 21:39:08 +00003974
Brian Curtind25aef52011-06-13 15:16:04 -05003975
Larry Hastings2f936352014-08-05 14:04:04 +10003976/*[clinic input]
3977os._getfinalpathname
Brian Curtinf5e76d02010-11-24 13:14:05 +00003978
Steve Dower23ad6d02018-02-22 10:39:10 -08003979 path: path_t
Larry Hastings2f936352014-08-05 14:04:04 +10003980 /
3981
3982A helper function for samepath on windows.
3983[clinic start generated code]*/
3984
Larry Hastings2f936352014-08-05 14:04:04 +10003985static PyObject *
Steve Dower23ad6d02018-02-22 10:39:10 -08003986os__getfinalpathname_impl(PyObject *module, path_t *path)
3987/*[clinic end generated code: output=621a3c79bc29ebfa input=2b6b6c7cbad5fb84]*/
Brian Curtind40e6f72010-07-08 21:39:08 +00003988{
3989 HANDLE hFile;
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03003990 wchar_t buf[MAXPATHLEN], *target_path = buf;
3991 int buf_size = Py_ARRAY_LENGTH(buf);
Brian Curtind40e6f72010-07-08 21:39:08 +00003992 int result_length;
Larry Hastings2f936352014-08-05 14:04:04 +10003993 PyObject *result;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00003994
Steve Dower23ad6d02018-02-22 10:39:10 -08003995 Py_BEGIN_ALLOW_THREADS
Brian Curtind40e6f72010-07-08 21:39:08 +00003996 hFile = CreateFileW(
Steve Dower23ad6d02018-02-22 10:39:10 -08003997 path->wide,
Brian Curtind40e6f72010-07-08 21:39:08 +00003998 0, /* desired access */
3999 0, /* share mode */
4000 NULL, /* security attributes */
4001 OPEN_EXISTING,
4002 /* FILE_FLAG_BACKUP_SEMANTICS is required to open a directory */
4003 FILE_FLAG_BACKUP_SEMANTICS,
4004 NULL);
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03004005 Py_END_ALLOW_THREADS
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00004006
Steve Dower23ad6d02018-02-22 10:39:10 -08004007 if (hFile == INVALID_HANDLE_VALUE) {
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03004008 return win32_error_object("CreateFileW", path->object);
Steve Dower23ad6d02018-02-22 10:39:10 -08004009 }
Brian Curtind40e6f72010-07-08 21:39:08 +00004010
4011 /* We have a good handle to the target, use it to determine the
4012 target path name. */
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03004013 while (1) {
4014 Py_BEGIN_ALLOW_THREADS
4015 result_length = GetFinalPathNameByHandleW(hFile, target_path,
4016 buf_size, VOLUME_NAME_DOS);
4017 Py_END_ALLOW_THREADS
Brian Curtind40e6f72010-07-08 21:39:08 +00004018
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03004019 if (!result_length) {
4020 result = win32_error_object("GetFinalPathNameByHandleW",
4021 path->object);
4022 goto cleanup;
4023 }
Brian Curtind40e6f72010-07-08 21:39:08 +00004024
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03004025 if (result_length < buf_size) {
4026 break;
4027 }
Brian Curtind40e6f72010-07-08 21:39:08 +00004028
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03004029 wchar_t *tmp;
4030 tmp = PyMem_Realloc(target_path != buf ? target_path : NULL,
4031 result_length * sizeof(*tmp));
4032 if (!tmp) {
4033 result = PyErr_NoMemory();
4034 goto cleanup;
4035 }
4036
4037 buf_size = result_length;
4038 target_path = tmp;
Steve Dower23ad6d02018-02-22 10:39:10 -08004039 }
Brian Curtind40e6f72010-07-08 21:39:08 +00004040
Victor Stinner9d3b93b2011-11-22 02:27:30 +01004041 result = PyUnicode_FromWideChar(target_path, result_length);
Steve Dowerdf2d4a62019-08-21 15:27:33 -07004042 if (result && path->narrow) {
Steve Dower23ad6d02018-02-22 10:39:10 -08004043 Py_SETREF(result, PyUnicode_EncodeFSDefault(result));
Steve Dowerdf2d4a62019-08-21 15:27:33 -07004044 }
Steve Dower23ad6d02018-02-22 10:39:10 -08004045
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03004046cleanup:
4047 if (target_path != buf) {
4048 PyMem_Free(target_path);
4049 }
4050 CloseHandle(hFile);
4051 return result;
Larry Hastings2f936352014-08-05 14:04:04 +10004052}
Brian Curtin62857742010-09-06 17:07:27 +00004053
Tim Golden6b528062013-08-01 12:44:00 +01004054
Larry Hastings2f936352014-08-05 14:04:04 +10004055/*[clinic input]
4056os._getvolumepathname
4057
Steve Dower23ad6d02018-02-22 10:39:10 -08004058 path: path_t
Larry Hastings2f936352014-08-05 14:04:04 +10004059
4060A helper function for ismount on Win32.
4061[clinic start generated code]*/
4062
Larry Hastings2f936352014-08-05 14:04:04 +10004063static PyObject *
Steve Dower23ad6d02018-02-22 10:39:10 -08004064os__getvolumepathname_impl(PyObject *module, path_t *path)
4065/*[clinic end generated code: output=804c63fd13a1330b input=722b40565fa21552]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004066{
4067 PyObject *result;
Serhiy Storchakadeab18d2016-05-07 16:45:18 +03004068 wchar_t *mountpath=NULL;
Victor Stinner6edddfa2013-11-24 19:22:57 +01004069 size_t buflen;
Tim Golden6b528062013-08-01 12:44:00 +01004070 BOOL ret;
4071
Tim Golden6b528062013-08-01 12:44:00 +01004072 /* Volume path should be shorter than entire path */
Steve Dower23ad6d02018-02-22 10:39:10 -08004073 buflen = Py_MAX(path->length, MAX_PATH);
Victor Stinner6edddfa2013-11-24 19:22:57 +01004074
Victor Stinner850a18e2017-10-24 16:53:32 -07004075 if (buflen > PY_DWORD_MAX) {
Victor Stinner6edddfa2013-11-24 19:22:57 +01004076 PyErr_SetString(PyExc_OverflowError, "path too long");
4077 return NULL;
4078 }
4079
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02004080 mountpath = PyMem_New(wchar_t, buflen);
Tim Golden6b528062013-08-01 12:44:00 +01004081 if (mountpath == NULL)
4082 return PyErr_NoMemory();
4083
4084 Py_BEGIN_ALLOW_THREADS
Steve Dower23ad6d02018-02-22 10:39:10 -08004085 ret = GetVolumePathNameW(path->wide, mountpath,
Victor Stinner6edddfa2013-11-24 19:22:57 +01004086 Py_SAFE_DOWNCAST(buflen, size_t, DWORD));
Tim Golden6b528062013-08-01 12:44:00 +01004087 Py_END_ALLOW_THREADS
4088
4089 if (!ret) {
Steve Dower23ad6d02018-02-22 10:39:10 -08004090 result = win32_error_object("_getvolumepathname", path->object);
Tim Golden6b528062013-08-01 12:44:00 +01004091 goto exit;
4092 }
4093 result = PyUnicode_FromWideChar(mountpath, wcslen(mountpath));
Steve Dower23ad6d02018-02-22 10:39:10 -08004094 if (path->narrow)
4095 Py_SETREF(result, PyUnicode_EncodeFSDefault(result));
Tim Golden6b528062013-08-01 12:44:00 +01004096
4097exit:
4098 PyMem_Free(mountpath);
4099 return result;
4100}
Tim Golden6b528062013-08-01 12:44:00 +01004101
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00004102#endif /* MS_WINDOWS */
Mark Hammondef8b6542001-05-13 08:04:26 +00004103
Larry Hastings2f936352014-08-05 14:04:04 +10004104
4105/*[clinic input]
4106os.mkdir
4107
4108 path : path_t
4109
4110 mode: int = 0o777
4111
4112 *
4113
4114 dir_fd : dir_fd(requires='mkdirat') = None
4115
4116# "mkdir(path, mode=0o777, *, dir_fd=None)\n\n\
4117
4118Create a directory.
4119
4120If dir_fd is not None, it should be a file descriptor open to a directory,
4121 and path should be relative; path will then be relative to that directory.
4122dir_fd may not be implemented on your platform.
4123 If it is unavailable, using it will raise a NotImplementedError.
4124
4125The mode argument is ignored on Windows.
4126[clinic start generated code]*/
4127
Larry Hastings2f936352014-08-05 14:04:04 +10004128static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004129os_mkdir_impl(PyObject *module, path_t *path, int mode, int dir_fd)
4130/*[clinic end generated code: output=a70446903abe821f input=e965f68377e9b1ce]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004131{
4132 int result;
Mark Hammondc2e85bd2002-10-03 05:10:39 +00004133
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00004134#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +00004135 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -07004136 result = CreateDirectoryW(path->wide, NULL);
Victor Stinner8c62be82010-05-06 00:08:46 +00004137 Py_END_ALLOW_THREADS
Mark Hammondc2e85bd2002-10-03 05:10:39 +00004138
Larry Hastings2f936352014-08-05 14:04:04 +10004139 if (!result)
4140 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004141#else
Victor Stinner8c62be82010-05-06 00:08:46 +00004142 Py_BEGIN_ALLOW_THREADS
Larry Hastings9cf065c2012-06-22 16:30:09 -07004143#if HAVE_MKDIRAT
4144 if (dir_fd != DEFAULT_DIR_FD)
Larry Hastings2f936352014-08-05 14:04:04 +10004145 result = mkdirat(dir_fd, path->narrow, mode);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004146 else
4147#endif
Erik Bray03eb11f2017-10-27 14:27:06 +02004148#if defined(__WATCOMC__) && !defined(__QNX__)
Larry Hastings2f936352014-08-05 14:04:04 +10004149 result = mkdir(path->narrow);
Guido van Rossuma4916fa1996-05-23 22:58:55 +00004150#else
Larry Hastings2f936352014-08-05 14:04:04 +10004151 result = mkdir(path->narrow, mode);
Guido van Rossuma4916fa1996-05-23 22:58:55 +00004152#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00004153 Py_END_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10004154 if (result < 0)
4155 return path_error(path);
Steve Dowercc16be82016-09-08 10:35:16 -07004156#endif /* MS_WINDOWS */
Larry Hastings2f936352014-08-05 14:04:04 +10004157 Py_RETURN_NONE;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00004158}
4159
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00004160
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004161/* sys/resource.h is needed for at least: wait3(), wait4(), broken nice. */
4162#if defined(HAVE_SYS_RESOURCE_H)
Thomas Wouterse38b2f12001-07-11 22:35:31 +00004163#include <sys/resource.h>
4164#endif
Thomas Wouterse38b2f12001-07-11 22:35:31 +00004165
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004166
4167#ifdef HAVE_NICE
Larry Hastings2f936352014-08-05 14:04:04 +10004168/*[clinic input]
4169os.nice
4170
4171 increment: int
4172 /
4173
4174Add increment to the priority of process and return the new priority.
4175[clinic start generated code]*/
4176
Larry Hastings2f936352014-08-05 14:04:04 +10004177static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004178os_nice_impl(PyObject *module, int increment)
4179/*[clinic end generated code: output=9dad8a9da8109943 input=864be2d402a21da2]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004180{
4181 int value;
Thomas Woutersc2c12dc2001-07-11 14:45:34 +00004182
Victor Stinner8c62be82010-05-06 00:08:46 +00004183 /* There are two flavours of 'nice': one that returns the new
4184 priority (as required by almost all standards out there) and the
Benjamin Peterson288d1da2017-09-28 22:44:27 -07004185 Linux/FreeBSD one, which returns '0' on success and advices
Victor Stinner8c62be82010-05-06 00:08:46 +00004186 the use of getpriority() to get the new priority.
Tim Peters5aa91602002-01-30 05:46:57 +00004187
Victor Stinner8c62be82010-05-06 00:08:46 +00004188 If we are of the nice family that returns the new priority, we
4189 need to clear errno before the call, and check if errno is filled
4190 before calling posix_error() on a returnvalue of -1, because the
4191 -1 may be the actual new priority! */
Thomas Woutersc2c12dc2001-07-11 14:45:34 +00004192
Victor Stinner8c62be82010-05-06 00:08:46 +00004193 errno = 0;
4194 value = nice(increment);
Thomas Wouterse38b2f12001-07-11 22:35:31 +00004195#if defined(HAVE_BROKEN_NICE) && defined(HAVE_GETPRIORITY)
Victor Stinner8c62be82010-05-06 00:08:46 +00004196 if (value == 0)
4197 value = getpriority(PRIO_PROCESS, 0);
Thomas Woutersc2c12dc2001-07-11 14:45:34 +00004198#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00004199 if (value == -1 && errno != 0)
4200 /* either nice() or getpriority() returned an error */
4201 return posix_error();
4202 return PyLong_FromLong((long) value);
Guido van Rossum775f4da1993-01-09 17:18:52 +00004203}
Guido van Rossumb6775db1994-08-01 11:34:53 +00004204#endif /* HAVE_NICE */
Guido van Rossum1ff6cb41991-04-08 20:59:13 +00004205
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00004206
4207#ifdef HAVE_GETPRIORITY
Larry Hastings2f936352014-08-05 14:04:04 +10004208/*[clinic input]
4209os.getpriority
4210
4211 which: int
4212 who: int
4213
4214Return program scheduling priority.
4215[clinic start generated code]*/
4216
Larry Hastings2f936352014-08-05 14:04:04 +10004217static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004218os_getpriority_impl(PyObject *module, int which, int who)
4219/*[clinic end generated code: output=c41b7b63c7420228 input=9be615d40e2544ef]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004220{
4221 int retval;
4222
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00004223 errno = 0;
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00004224 retval = getpriority(which, who);
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00004225 if (errno != 0)
4226 return posix_error();
4227 return PyLong_FromLong((long)retval);
4228}
4229#endif /* HAVE_GETPRIORITY */
4230
4231
4232#ifdef HAVE_SETPRIORITY
Larry Hastings2f936352014-08-05 14:04:04 +10004233/*[clinic input]
4234os.setpriority
4235
4236 which: int
4237 who: int
4238 priority: int
4239
4240Set program scheduling priority.
4241[clinic start generated code]*/
4242
Larry Hastings2f936352014-08-05 14:04:04 +10004243static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004244os_setpriority_impl(PyObject *module, int which, int who, int priority)
4245/*[clinic end generated code: output=3d910d95a7771eb2 input=710ccbf65b9dc513]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004246{
4247 int retval;
4248
4249 retval = setpriority(which, who, priority);
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00004250 if (retval == -1)
4251 return posix_error();
4252 Py_RETURN_NONE;
4253}
4254#endif /* HAVE_SETPRIORITY */
4255
4256
Barry Warsaw53699e91996-12-10 23:23:01 +00004257static PyObject *
Larry Hastings2f936352014-08-05 14:04:04 +10004258internal_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 +00004259{
Serhiy Storchakadeab18d2016-05-07 16:45:18 +03004260 const char *function_name = is_replace ? "replace" : "rename";
Larry Hastings9cf065c2012-06-22 16:30:09 -07004261 int dir_fd_specified;
Larry Hastings9cf065c2012-06-22 16:30:09 -07004262
Mark Hammondc2e85bd2002-10-03 05:10:39 +00004263#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +00004264 BOOL result;
Antoine Pitrouf3b2d882012-01-30 22:08:52 +01004265 int flags = is_replace ? MOVEFILE_REPLACE_EXISTING : 0;
Mark Hammondc2e85bd2002-10-03 05:10:39 +00004266#else
Larry Hastings9cf065c2012-06-22 16:30:09 -07004267 int result;
Mark Hammondc2e85bd2002-10-03 05:10:39 +00004268#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -07004269
Larry Hastings9cf065c2012-06-22 16:30:09 -07004270 dir_fd_specified = (src_dir_fd != DEFAULT_DIR_FD) ||
4271 (dst_dir_fd != DEFAULT_DIR_FD);
4272#ifndef HAVE_RENAMEAT
4273 if (dir_fd_specified) {
4274 argument_unavailable_error(function_name, "src_dir_fd and dst_dir_fd");
Larry Hastings2f936352014-08-05 14:04:04 +10004275 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07004276 }
4277#endif
4278
Larry Hastings9cf065c2012-06-22 16:30:09 -07004279#ifdef MS_WINDOWS
4280 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -07004281 result = MoveFileExW(src->wide, dst->wide, flags);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004282 Py_END_ALLOW_THREADS
4283
Larry Hastings2f936352014-08-05 14:04:04 +10004284 if (!result)
4285 return path_error2(src, dst);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004286
4287#else
Steve Dowercc16be82016-09-08 10:35:16 -07004288 if ((src->narrow && dst->wide) || (src->wide && dst->narrow)) {
4289 PyErr_Format(PyExc_ValueError,
4290 "%s: src and dst must be the same type", function_name);
4291 return NULL;
4292 }
4293
Larry Hastings9cf065c2012-06-22 16:30:09 -07004294 Py_BEGIN_ALLOW_THREADS
4295#ifdef HAVE_RENAMEAT
4296 if (dir_fd_specified)
Larry Hastings2f936352014-08-05 14:04:04 +10004297 result = renameat(src_dir_fd, src->narrow, dst_dir_fd, dst->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004298 else
4299#endif
Steve Dowercc16be82016-09-08 10:35:16 -07004300 result = rename(src->narrow, dst->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004301 Py_END_ALLOW_THREADS
4302
Larry Hastings2f936352014-08-05 14:04:04 +10004303 if (result)
4304 return path_error2(src, dst);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004305#endif
Larry Hastings2f936352014-08-05 14:04:04 +10004306 Py_RETURN_NONE;
4307}
Larry Hastings9cf065c2012-06-22 16:30:09 -07004308
Larry Hastings2f936352014-08-05 14:04:04 +10004309
4310/*[clinic input]
4311os.rename
4312
4313 src : path_t
4314 dst : path_t
4315 *
4316 src_dir_fd : dir_fd = None
4317 dst_dir_fd : dir_fd = None
4318
4319Rename a file or directory.
4320
4321If either src_dir_fd or dst_dir_fd is not None, it should be a file
4322 descriptor open to a directory, and the respective path string (src or dst)
4323 should be relative; the path will then be relative to that directory.
4324src_dir_fd and dst_dir_fd, may not be implemented on your platform.
4325 If they are unavailable, using them will raise a NotImplementedError.
4326[clinic start generated code]*/
4327
Antoine Pitrouf3b2d882012-01-30 22:08:52 +01004328static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004329os_rename_impl(PyObject *module, path_t *src, path_t *dst, int src_dir_fd,
Larry Hastings89964c42015-04-14 18:07:59 -04004330 int dst_dir_fd)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004331/*[clinic end generated code: output=59e803072cf41230 input=faa61c847912c850]*/
Antoine Pitrouf3b2d882012-01-30 22:08:52 +01004332{
Larry Hastings2f936352014-08-05 14:04:04 +10004333 return internal_rename(src, dst, src_dir_fd, dst_dir_fd, 0);
Antoine Pitrouf3b2d882012-01-30 22:08:52 +01004334}
4335
Larry Hastings2f936352014-08-05 14:04:04 +10004336
4337/*[clinic input]
4338os.replace = os.rename
4339
4340Rename a file or directory, overwriting the destination.
4341
4342If either src_dir_fd or dst_dir_fd is not None, it should be a file
4343 descriptor open to a directory, and the respective path string (src or dst)
4344 should be relative; the path will then be relative to that directory.
4345src_dir_fd and dst_dir_fd, may not be implemented on your platform.
Anthony Sottile73d60022019-02-12 23:15:54 -05004346 If they are unavailable, using them will raise a NotImplementedError.
Larry Hastings2f936352014-08-05 14:04:04 +10004347[clinic start generated code]*/
4348
Larry Hastings2f936352014-08-05 14:04:04 +10004349static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004350os_replace_impl(PyObject *module, path_t *src, path_t *dst, int src_dir_fd,
4351 int dst_dir_fd)
Anthony Sottile73d60022019-02-12 23:15:54 -05004352/*[clinic end generated code: output=1968c02e7857422b input=c003f0def43378ef]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004353{
4354 return internal_rename(src, dst, src_dir_fd, dst_dir_fd, 1);
4355}
4356
4357
4358/*[clinic input]
4359os.rmdir
4360
4361 path: path_t
4362 *
4363 dir_fd: dir_fd(requires='unlinkat') = None
4364
4365Remove a directory.
4366
4367If dir_fd is not None, it should be a file descriptor open to a directory,
4368 and path should be relative; path will then be relative to that directory.
4369dir_fd may not be implemented on your platform.
4370 If it is unavailable, using it will raise a NotImplementedError.
4371[clinic start generated code]*/
4372
Larry Hastings2f936352014-08-05 14:04:04 +10004373static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004374os_rmdir_impl(PyObject *module, path_t *path, int dir_fd)
4375/*[clinic end generated code: output=080eb54f506e8301 input=38c8b375ca34a7e2]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004376{
4377 int result;
Larry Hastingsb698d8e2012-06-23 16:55:07 -07004378
4379 Py_BEGIN_ALLOW_THREADS
4380#ifdef MS_WINDOWS
Steve Dowercc16be82016-09-08 10:35:16 -07004381 /* Windows, success=1, UNIX, success=0 */
4382 result = !RemoveDirectoryW(path->wide);
Larry Hastingsb698d8e2012-06-23 16:55:07 -07004383#else
4384#ifdef HAVE_UNLINKAT
4385 if (dir_fd != DEFAULT_DIR_FD)
Larry Hastings2f936352014-08-05 14:04:04 +10004386 result = unlinkat(dir_fd, path->narrow, AT_REMOVEDIR);
Larry Hastingsb698d8e2012-06-23 16:55:07 -07004387 else
4388#endif
Larry Hastings2f936352014-08-05 14:04:04 +10004389 result = rmdir(path->narrow);
Larry Hastingsb698d8e2012-06-23 16:55:07 -07004390#endif
4391 Py_END_ALLOW_THREADS
4392
Larry Hastings2f936352014-08-05 14:04:04 +10004393 if (result)
4394 return path_error(path);
Larry Hastingsb698d8e2012-06-23 16:55:07 -07004395
Larry Hastings2f936352014-08-05 14:04:04 +10004396 Py_RETURN_NONE;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00004397}
4398
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00004399
Guido van Rossuma4916fa1996-05-23 22:58:55 +00004400#ifdef HAVE_SYSTEM
Larry Hastings2f936352014-08-05 14:04:04 +10004401#ifdef MS_WINDOWS
4402/*[clinic input]
4403os.system -> long
4404
4405 command: Py_UNICODE
4406
4407Execute the command in a subshell.
4408[clinic start generated code]*/
4409
Larry Hastings2f936352014-08-05 14:04:04 +10004410static long
Serhiy Storchakaafb3e712018-12-14 11:19:51 +02004411os_system_impl(PyObject *module, const Py_UNICODE *command)
4412/*[clinic end generated code: output=5b7c3599c068ca42 input=303f5ce97df606b0]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004413{
4414 long result;
Steve Dowerb82e17e2019-05-23 08:45:22 -07004415
Steve Dowerfbe3c762019-10-18 00:52:15 -07004416 if (PySys_Audit("os.system", "(u)", command) < 0) {
Steve Dowerb82e17e2019-05-23 08:45:22 -07004417 return -1;
4418 }
4419
Victor Stinner8c62be82010-05-06 00:08:46 +00004420 Py_BEGIN_ALLOW_THREADS
Steve Dowerc3630612016-11-19 18:41:16 -08004421 _Py_BEGIN_SUPPRESS_IPH
Larry Hastings2f936352014-08-05 14:04:04 +10004422 result = _wsystem(command);
Steve Dowerc3630612016-11-19 18:41:16 -08004423 _Py_END_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00004424 Py_END_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10004425 return result;
4426}
4427#else /* MS_WINDOWS */
4428/*[clinic input]
4429os.system -> long
4430
4431 command: FSConverter
4432
4433Execute the command in a subshell.
4434[clinic start generated code]*/
4435
Larry Hastings2f936352014-08-05 14:04:04 +10004436static long
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004437os_system_impl(PyObject *module, PyObject *command)
4438/*[clinic end generated code: output=290fc437dd4f33a0 input=86a58554ba6094af]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004439{
4440 long result;
Serhiy Storchakadeab18d2016-05-07 16:45:18 +03004441 const char *bytes = PyBytes_AsString(command);
Steve Dowerb82e17e2019-05-23 08:45:22 -07004442
Steve Dowerfbe3c762019-10-18 00:52:15 -07004443 if (PySys_Audit("os.system", "(O)", command) < 0) {
Steve Dowerb82e17e2019-05-23 08:45:22 -07004444 return -1;
4445 }
4446
Larry Hastings2f936352014-08-05 14:04:04 +10004447 Py_BEGIN_ALLOW_THREADS
4448 result = system(bytes);
4449 Py_END_ALLOW_THREADS
4450 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00004451}
Guido van Rossuma4916fa1996-05-23 22:58:55 +00004452#endif
Larry Hastings2f936352014-08-05 14:04:04 +10004453#endif /* HAVE_SYSTEM */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00004454
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00004455
Larry Hastings2f936352014-08-05 14:04:04 +10004456/*[clinic input]
4457os.umask
4458
4459 mask: int
4460 /
4461
4462Set the current numeric umask and return the previous umask.
4463[clinic start generated code]*/
4464
Larry Hastings2f936352014-08-05 14:04:04 +10004465static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004466os_umask_impl(PyObject *module, int mask)
4467/*[clinic end generated code: output=a2e33ce3bc1a6e33 input=ab6bfd9b24d8a7e8]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004468{
4469 int i = (int)umask(mask);
Victor Stinner8c62be82010-05-06 00:08:46 +00004470 if (i < 0)
4471 return posix_error();
4472 return PyLong_FromLong((long)i);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00004473}
4474
Brian Curtind40e6f72010-07-08 21:39:08 +00004475#ifdef MS_WINDOWS
4476
4477/* override the default DeleteFileW behavior so that directory
4478symlinks can be removed with this function, the same as with
4479Unix symlinks */
4480BOOL WINAPI Py_DeleteFileW(LPCWSTR lpFileName)
4481{
4482 WIN32_FILE_ATTRIBUTE_DATA info;
4483 WIN32_FIND_DATAW find_data;
4484 HANDLE find_data_handle;
4485 int is_directory = 0;
4486 int is_link = 0;
4487
4488 if (GetFileAttributesExW(lpFileName, GetFileExInfoStandard, &info)) {
4489 is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00004490
Brian Curtind40e6f72010-07-08 21:39:08 +00004491 /* Get WIN32_FIND_DATA structure for the path to determine if
4492 it is a symlink */
4493 if(is_directory &&
4494 info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
4495 find_data_handle = FindFirstFileW(lpFileName, &find_data);
4496
4497 if(find_data_handle != INVALID_HANDLE_VALUE) {
Tim Golden0321cf22014-05-05 19:46:17 +01004498 /* IO_REPARSE_TAG_SYMLINK if it is a symlink and
4499 IO_REPARSE_TAG_MOUNT_POINT if it is a junction point. */
4500 is_link = find_data.dwReserved0 == IO_REPARSE_TAG_SYMLINK ||
4501 find_data.dwReserved0 == IO_REPARSE_TAG_MOUNT_POINT;
Brian Curtind40e6f72010-07-08 21:39:08 +00004502 FindClose(find_data_handle);
4503 }
4504 }
4505 }
4506
4507 if (is_directory && is_link)
4508 return RemoveDirectoryW(lpFileName);
4509
4510 return DeleteFileW(lpFileName);
4511}
4512#endif /* MS_WINDOWS */
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00004513
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00004514
Larry Hastings2f936352014-08-05 14:04:04 +10004515/*[clinic input]
4516os.unlink
4517
4518 path: path_t
4519 *
4520 dir_fd: dir_fd(requires='unlinkat')=None
4521
4522Remove a file (same as remove()).
4523
4524If dir_fd is not None, it should be a file descriptor open to a directory,
4525 and path should be relative; path will then be relative to that directory.
4526dir_fd may not be implemented on your platform.
4527 If it is unavailable, using it will raise a NotImplementedError.
4528
4529[clinic start generated code]*/
4530
Larry Hastings2f936352014-08-05 14:04:04 +10004531static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004532os_unlink_impl(PyObject *module, path_t *path, int dir_fd)
4533/*[clinic end generated code: output=621797807b9963b1 input=d7bcde2b1b2a2552]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004534{
4535 int result;
Larry Hastings9cf065c2012-06-22 16:30:09 -07004536
4537 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04004538 _Py_BEGIN_SUPPRESS_IPH
Larry Hastings9cf065c2012-06-22 16:30:09 -07004539#ifdef MS_WINDOWS
Steve Dowercc16be82016-09-08 10:35:16 -07004540 /* Windows, success=1, UNIX, success=0 */
4541 result = !Py_DeleteFileW(path->wide);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004542#else
Larry Hastings9cf065c2012-06-22 16:30:09 -07004543#ifdef HAVE_UNLINKAT
4544 if (dir_fd != DEFAULT_DIR_FD)
Larry Hastings2f936352014-08-05 14:04:04 +10004545 result = unlinkat(dir_fd, path->narrow, 0);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004546 else
4547#endif /* HAVE_UNLINKAT */
Larry Hastings2f936352014-08-05 14:04:04 +10004548 result = unlink(path->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004549#endif
Steve Dower8fc89802015-04-12 00:26:27 -04004550 _Py_END_SUPPRESS_IPH
Larry Hastings9cf065c2012-06-22 16:30:09 -07004551 Py_END_ALLOW_THREADS
4552
Larry Hastings2f936352014-08-05 14:04:04 +10004553 if (result)
4554 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004555
Larry Hastings2f936352014-08-05 14:04:04 +10004556 Py_RETURN_NONE;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00004557}
4558
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00004559
Larry Hastings2f936352014-08-05 14:04:04 +10004560/*[clinic input]
4561os.remove = os.unlink
4562
4563Remove a file (same as unlink()).
4564
4565If dir_fd is not None, it should be a file descriptor open to a directory,
4566 and path should be relative; path will then be relative to that directory.
4567dir_fd may not be implemented on your platform.
4568 If it is unavailable, using it will raise a NotImplementedError.
4569[clinic start generated code]*/
4570
Larry Hastings2f936352014-08-05 14:04:04 +10004571static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004572os_remove_impl(PyObject *module, path_t *path, int dir_fd)
4573/*[clinic end generated code: output=a8535b28f0068883 input=e05c5ab55cd30983]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004574{
4575 return os_unlink_impl(module, path, dir_fd);
4576}
4577
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00004578
Larry Hastings605a62d2012-06-24 04:33:36 -07004579static PyStructSequence_Field uname_result_fields[] = {
4580 {"sysname", "operating system name"},
4581 {"nodename", "name of machine on network (implementation-defined)"},
4582 {"release", "operating system release"},
4583 {"version", "operating system version"},
4584 {"machine", "hardware identifier"},
4585 {NULL}
4586};
4587
4588PyDoc_STRVAR(uname_result__doc__,
4589"uname_result: Result from os.uname().\n\n\
4590This object may be accessed either as a tuple of\n\
4591 (sysname, nodename, release, version, machine),\n\
4592or via the attributes sysname, nodename, release, version, and machine.\n\
4593\n\
4594See os.uname for more information.");
4595
4596static PyStructSequence_Desc uname_result_desc = {
Eddie Elizondob3966632019-11-05 07:16:14 -08004597 MODNAME ".uname_result", /* name */
Larry Hastings605a62d2012-06-24 04:33:36 -07004598 uname_result__doc__, /* doc */
4599 uname_result_fields,
4600 5
4601};
4602
Larry Hastings605a62d2012-06-24 04:33:36 -07004603#ifdef HAVE_UNAME
Larry Hastings2f936352014-08-05 14:04:04 +10004604/*[clinic input]
4605os.uname
4606
4607Return an object identifying the current operating system.
4608
4609The object behaves like a named tuple with the following fields:
4610 (sysname, nodename, release, version, machine)
4611
4612[clinic start generated code]*/
4613
Larry Hastings2f936352014-08-05 14:04:04 +10004614static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004615os_uname_impl(PyObject *module)
4616/*[clinic end generated code: output=e6a49cf1a1508a19 input=e68bd246db3043ed]*/
Guido van Rossumc39de5f1992-02-05 11:15:54 +00004617{
Victor Stinner8c62be82010-05-06 00:08:46 +00004618 struct utsname u;
4619 int res;
Larry Hastings605a62d2012-06-24 04:33:36 -07004620 PyObject *value;
Neal Norwitze241ce82003-02-17 18:17:05 +00004621
Victor Stinner8c62be82010-05-06 00:08:46 +00004622 Py_BEGIN_ALLOW_THREADS
4623 res = uname(&u);
4624 Py_END_ALLOW_THREADS
4625 if (res < 0)
4626 return posix_error();
Larry Hastings605a62d2012-06-24 04:33:36 -07004627
Eddie Elizondob3966632019-11-05 07:16:14 -08004628 PyObject *UnameResultType = _posixstate(module)->UnameResultType;
4629 value = PyStructSequence_New((PyTypeObject *)UnameResultType);
Larry Hastings605a62d2012-06-24 04:33:36 -07004630 if (value == NULL)
4631 return NULL;
4632
4633#define SET(i, field) \
4634 { \
Victor Stinnera534fc42013-06-03 22:07:27 +02004635 PyObject *o = PyUnicode_DecodeFSDefault(field); \
Larry Hastings605a62d2012-06-24 04:33:36 -07004636 if (!o) { \
4637 Py_DECREF(value); \
4638 return NULL; \
4639 } \
4640 PyStructSequence_SET_ITEM(value, i, o); \
4641 } \
4642
4643 SET(0, u.sysname);
4644 SET(1, u.nodename);
4645 SET(2, u.release);
4646 SET(3, u.version);
4647 SET(4, u.machine);
4648
4649#undef SET
4650
4651 return value;
Guido van Rossumc39de5f1992-02-05 11:15:54 +00004652}
Guido van Rossumb6775db1994-08-01 11:34:53 +00004653#endif /* HAVE_UNAME */
Guido van Rossum1ff6cb41991-04-08 20:59:13 +00004654
Larry Hastings9e3e70b2011-09-08 19:29:07 -07004655
Larry Hastings9cf065c2012-06-22 16:30:09 -07004656
4657typedef struct {
4658 int now;
4659 time_t atime_s;
4660 long atime_ns;
4661 time_t mtime_s;
4662 long mtime_ns;
4663} utime_t;
4664
4665/*
Victor Stinner484df002014-10-09 13:52:31 +02004666 * these macros assume that "ut" is a pointer to a utime_t
Larry Hastings9cf065c2012-06-22 16:30:09 -07004667 * they also intentionally leak the declaration of a pointer named "time"
4668 */
4669#define UTIME_TO_TIMESPEC \
4670 struct timespec ts[2]; \
4671 struct timespec *time; \
Victor Stinner484df002014-10-09 13:52:31 +02004672 if (ut->now) \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004673 time = NULL; \
4674 else { \
Victor Stinner484df002014-10-09 13:52:31 +02004675 ts[0].tv_sec = ut->atime_s; \
4676 ts[0].tv_nsec = ut->atime_ns; \
4677 ts[1].tv_sec = ut->mtime_s; \
4678 ts[1].tv_nsec = ut->mtime_ns; \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004679 time = ts; \
4680 } \
4681
4682#define UTIME_TO_TIMEVAL \
4683 struct timeval tv[2]; \
4684 struct timeval *time; \
Victor Stinner484df002014-10-09 13:52:31 +02004685 if (ut->now) \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004686 time = NULL; \
4687 else { \
Victor Stinner484df002014-10-09 13:52:31 +02004688 tv[0].tv_sec = ut->atime_s; \
4689 tv[0].tv_usec = ut->atime_ns / 1000; \
4690 tv[1].tv_sec = ut->mtime_s; \
4691 tv[1].tv_usec = ut->mtime_ns / 1000; \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004692 time = tv; \
4693 } \
4694
4695#define UTIME_TO_UTIMBUF \
Georg Brandle1a7d9d2014-10-12 08:45:15 +02004696 struct utimbuf u; \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004697 struct utimbuf *time; \
Victor Stinner484df002014-10-09 13:52:31 +02004698 if (ut->now) \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004699 time = NULL; \
4700 else { \
Georg Brandle1a7d9d2014-10-12 08:45:15 +02004701 u.actime = ut->atime_s; \
4702 u.modtime = ut->mtime_s; \
4703 time = &u; \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004704 }
4705
4706#define UTIME_TO_TIME_T \
4707 time_t timet[2]; \
Georg Brandle1a7d9d2014-10-12 08:45:15 +02004708 time_t *time; \
Victor Stinner484df002014-10-09 13:52:31 +02004709 if (ut->now) \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004710 time = NULL; \
4711 else { \
Victor Stinner484df002014-10-09 13:52:31 +02004712 timet[0] = ut->atime_s; \
4713 timet[1] = ut->mtime_s; \
Georg Brandle1a7d9d2014-10-12 08:45:15 +02004714 time = timet; \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004715 } \
4716
4717
Victor Stinner528a9ab2015-09-03 21:30:26 +02004718#if defined(HAVE_FUTIMESAT) || defined(HAVE_UTIMENSAT)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004719
4720static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02004721utime_dir_fd(utime_t *ut, int dir_fd, const char *path, int follow_symlinks)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004722{
4723#ifdef HAVE_UTIMENSAT
4724 int flags = follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW;
4725 UTIME_TO_TIMESPEC;
4726 return utimensat(dir_fd, path, time, flags);
4727#elif defined(HAVE_FUTIMESAT)
4728 UTIME_TO_TIMEVAL;
4729 /*
4730 * follow_symlinks will never be false here;
4731 * we only allow !follow_symlinks and dir_fd together
4732 * if we have utimensat()
4733 */
4734 assert(follow_symlinks);
4735 return futimesat(dir_fd, path, time);
4736#endif
4737}
4738
Larry Hastings2f936352014-08-05 14:04:04 +10004739 #define FUTIMENSAT_DIR_FD_CONVERTER dir_fd_converter
4740#else
4741 #define FUTIMENSAT_DIR_FD_CONVERTER dir_fd_unavailable
Larry Hastings9cf065c2012-06-22 16:30:09 -07004742#endif
4743
Victor Stinner528a9ab2015-09-03 21:30:26 +02004744#if defined(HAVE_FUTIMES) || defined(HAVE_FUTIMENS)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004745
4746static int
Victor Stinner484df002014-10-09 13:52:31 +02004747utime_fd(utime_t *ut, int fd)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004748{
4749#ifdef HAVE_FUTIMENS
4750 UTIME_TO_TIMESPEC;
4751 return futimens(fd, time);
4752#else
4753 UTIME_TO_TIMEVAL;
4754 return futimes(fd, time);
4755#endif
4756}
4757
Larry Hastings2f936352014-08-05 14:04:04 +10004758 #define PATH_UTIME_HAVE_FD 1
4759#else
4760 #define PATH_UTIME_HAVE_FD 0
Larry Hastings9cf065c2012-06-22 16:30:09 -07004761#endif
4762
Victor Stinner5ebae872015-09-22 01:29:33 +02004763#if defined(HAVE_UTIMENSAT) || defined(HAVE_LUTIMES)
4764# define UTIME_HAVE_NOFOLLOW_SYMLINKS
4765#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -07004766
Victor Stinner4552ced2015-09-21 22:37:15 +02004767#ifdef UTIME_HAVE_NOFOLLOW_SYMLINKS
Larry Hastings9cf065c2012-06-22 16:30:09 -07004768
4769static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02004770utime_nofollow_symlinks(utime_t *ut, const char *path)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004771{
4772#ifdef HAVE_UTIMENSAT
4773 UTIME_TO_TIMESPEC;
4774 return utimensat(DEFAULT_DIR_FD, path, time, AT_SYMLINK_NOFOLLOW);
4775#else
4776 UTIME_TO_TIMEVAL;
4777 return lutimes(path, time);
4778#endif
4779}
4780
4781#endif
4782
4783#ifndef MS_WINDOWS
4784
4785static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02004786utime_default(utime_t *ut, const char *path)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004787{
4788#ifdef HAVE_UTIMENSAT
4789 UTIME_TO_TIMESPEC;
4790 return utimensat(DEFAULT_DIR_FD, path, time, 0);
4791#elif defined(HAVE_UTIMES)
4792 UTIME_TO_TIMEVAL;
4793 return utimes(path, time);
4794#elif defined(HAVE_UTIME_H)
4795 UTIME_TO_UTIMBUF;
4796 return utime(path, time);
4797#else
4798 UTIME_TO_TIME_T;
4799 return utime(path, time);
4800#endif
4801}
4802
4803#endif
4804
Larry Hastings76ad59b2012-05-03 00:30:07 -07004805static int
4806split_py_long_to_s_and_ns(PyObject *py_long, time_t *s, long *ns)
4807{
4808 int result = 0;
Benjamin Petersonfbd85a02012-05-04 11:06:09 -04004809 PyObject *divmod;
Eddie Elizondob3966632019-11-05 07:16:14 -08004810 divmod = PyNumber_Divmod(py_long, _posixstate_global->billion);
Larry Hastings76ad59b2012-05-03 00:30:07 -07004811 if (!divmod)
4812 goto exit;
Oren Milman0bd1a2d2018-09-12 22:14:35 +03004813 if (!PyTuple_Check(divmod) || PyTuple_GET_SIZE(divmod) != 2) {
4814 PyErr_Format(PyExc_TypeError,
4815 "%.200s.__divmod__() must return a 2-tuple, not %.200s",
Eddie Elizondob3966632019-11-05 07:16:14 -08004816 _PyType_Name(Py_TYPE(py_long)), _PyType_Name(Py_TYPE(divmod)));
Oren Milman0bd1a2d2018-09-12 22:14:35 +03004817 goto exit;
4818 }
Larry Hastings76ad59b2012-05-03 00:30:07 -07004819 *s = _PyLong_AsTime_t(PyTuple_GET_ITEM(divmod, 0));
4820 if ((*s == -1) && PyErr_Occurred())
4821 goto exit;
4822 *ns = PyLong_AsLong(PyTuple_GET_ITEM(divmod, 1));
Benjamin Peterson35a8f0d2012-05-04 01:10:59 -04004823 if ((*ns == -1) && PyErr_Occurred())
Larry Hastings76ad59b2012-05-03 00:30:07 -07004824 goto exit;
4825
4826 result = 1;
4827exit:
4828 Py_XDECREF(divmod);
4829 return result;
4830}
4831
Larry Hastings2f936352014-08-05 14:04:04 +10004832
4833/*[clinic input]
4834os.utime
4835
4836 path: path_t(allow_fd='PATH_UTIME_HAVE_FD')
Serhiy Storchaka279f4462019-09-14 12:24:05 +03004837 times: object = None
Larry Hastings2f936352014-08-05 14:04:04 +10004838 *
4839 ns: object = NULL
4840 dir_fd: dir_fd(requires='futimensat') = None
4841 follow_symlinks: bool=True
4842
Martin Panter0ff89092015-09-09 01:56:53 +00004843# "utime(path, times=None, *[, ns], dir_fd=None, follow_symlinks=True)\n\
Larry Hastings2f936352014-08-05 14:04:04 +10004844
4845Set the access and modified time of path.
4846
4847path may always be specified as a string.
4848On some platforms, path may also be specified as an open file descriptor.
4849 If this functionality is unavailable, using it raises an exception.
4850
4851If times is not None, it must be a tuple (atime, mtime);
4852 atime and mtime should be expressed as float seconds since the epoch.
Martin Panter0ff89092015-09-09 01:56:53 +00004853If ns is specified, it must be a tuple (atime_ns, mtime_ns);
Larry Hastings2f936352014-08-05 14:04:04 +10004854 atime_ns and mtime_ns should be expressed as integer nanoseconds
4855 since the epoch.
Martin Panter0ff89092015-09-09 01:56:53 +00004856If times is None and ns is unspecified, utime uses the current time.
Larry Hastings2f936352014-08-05 14:04:04 +10004857Specifying tuples for both times and ns is an error.
4858
4859If dir_fd is not None, it should be a file descriptor open to a directory,
4860 and path should be relative; path will then be relative to that directory.
4861If follow_symlinks is False, and the last element of the path is a symbolic
4862 link, utime will modify the symbolic link itself instead of the file the
4863 link points to.
4864It is an error to use dir_fd or follow_symlinks when specifying path
4865 as an open file descriptor.
4866dir_fd and follow_symlinks may not be available on your platform.
4867 If they are unavailable, using them will raise a NotImplementedError.
4868
4869[clinic start generated code]*/
4870
Larry Hastings2f936352014-08-05 14:04:04 +10004871static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004872os_utime_impl(PyObject *module, path_t *path, PyObject *times, PyObject *ns,
4873 int dir_fd, int follow_symlinks)
Serhiy Storchaka279f4462019-09-14 12:24:05 +03004874/*[clinic end generated code: output=cfcac69d027b82cf input=2fbd62a2f228f8f4]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004875{
Larry Hastings9cf065c2012-06-22 16:30:09 -07004876#ifdef MS_WINDOWS
4877 HANDLE hFile;
4878 FILETIME atime, mtime;
4879#else
4880 int result;
4881#endif
Larry Hastings76ad59b2012-05-03 00:30:07 -07004882
Larry Hastings2f936352014-08-05 14:04:04 +10004883 utime_t utime;
Larry Hastings76ad59b2012-05-03 00:30:07 -07004884
Christian Heimesb3c87242013-08-01 00:08:16 +02004885 memset(&utime, 0, sizeof(utime_t));
Larry Hastings76ad59b2012-05-03 00:30:07 -07004886
Serhiy Storchaka279f4462019-09-14 12:24:05 +03004887 if (times != Py_None && ns) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07004888 PyErr_SetString(PyExc_ValueError,
4889 "utime: you may specify either 'times'"
4890 " or 'ns' but not both");
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004891 return NULL;
Larry Hastings76ad59b2012-05-03 00:30:07 -07004892 }
4893
Serhiy Storchaka279f4462019-09-14 12:24:05 +03004894 if (times != Py_None) {
Antoine Pitroucf8a1e52013-04-17 22:06:44 +02004895 time_t a_sec, m_sec;
4896 long a_nsec, m_nsec;
Larry Hastings76ad59b2012-05-03 00:30:07 -07004897 if (!PyTuple_CheckExact(times) || (PyTuple_Size(times) != 2)) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07004898 PyErr_SetString(PyExc_TypeError,
4899 "utime: 'times' must be either"
4900 " a tuple of two ints or None");
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004901 return NULL;
Larry Hastings76ad59b2012-05-03 00:30:07 -07004902 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07004903 utime.now = 0;
Benjamin Petersonb399ab22012-05-04 01:31:13 -04004904 if (_PyTime_ObjectToTimespec(PyTuple_GET_ITEM(times, 0),
Victor Stinnerdca028b2015-03-30 01:02:57 +02004905 &a_sec, &a_nsec, _PyTime_ROUND_FLOOR) == -1 ||
Benjamin Petersonb399ab22012-05-04 01:31:13 -04004906 _PyTime_ObjectToTimespec(PyTuple_GET_ITEM(times, 1),
Victor Stinnerdca028b2015-03-30 01:02:57 +02004907 &m_sec, &m_nsec, _PyTime_ROUND_FLOOR) == -1) {
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004908 return NULL;
Larry Hastingsb3336402012-05-04 02:31:57 -07004909 }
Antoine Pitroucf8a1e52013-04-17 22:06:44 +02004910 utime.atime_s = a_sec;
4911 utime.atime_ns = a_nsec;
4912 utime.mtime_s = m_sec;
4913 utime.mtime_ns = m_nsec;
Larry Hastings76ad59b2012-05-03 00:30:07 -07004914 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07004915 else if (ns) {
Larry Hastings76ad59b2012-05-03 00:30:07 -07004916 if (!PyTuple_CheckExact(ns) || (PyTuple_Size(ns) != 2)) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07004917 PyErr_SetString(PyExc_TypeError,
4918 "utime: 'ns' must be a tuple of two ints");
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004919 return NULL;
Larry Hastings76ad59b2012-05-03 00:30:07 -07004920 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07004921 utime.now = 0;
Benjamin Petersonb399ab22012-05-04 01:31:13 -04004922 if (!split_py_long_to_s_and_ns(PyTuple_GET_ITEM(ns, 0),
Larry Hastings9cf065c2012-06-22 16:30:09 -07004923 &utime.atime_s, &utime.atime_ns) ||
Benjamin Petersonb399ab22012-05-04 01:31:13 -04004924 !split_py_long_to_s_and_ns(PyTuple_GET_ITEM(ns, 1),
Larry Hastings9cf065c2012-06-22 16:30:09 -07004925 &utime.mtime_s, &utime.mtime_ns)) {
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004926 return NULL;
Larry Hastingsb3336402012-05-04 02:31:57 -07004927 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07004928 }
4929 else {
4930 /* times and ns are both None/unspecified. use "now". */
4931 utime.now = 1;
Larry Hastings76ad59b2012-05-03 00:30:07 -07004932 }
4933
Victor Stinner4552ced2015-09-21 22:37:15 +02004934#if !defined(UTIME_HAVE_NOFOLLOW_SYMLINKS)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004935 if (follow_symlinks_specified("utime", follow_symlinks))
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004936 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07004937#endif
Benjamin Petersonb399ab22012-05-04 01:31:13 -04004938
Larry Hastings2f936352014-08-05 14:04:04 +10004939 if (path_and_dir_fd_invalid("utime", path, dir_fd) ||
4940 dir_fd_and_fd_invalid("utime", dir_fd, path->fd) ||
4941 fd_and_follow_symlinks_invalid("utime", path->fd, follow_symlinks))
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004942 return NULL;
Larry Hastings76ad59b2012-05-03 00:30:07 -07004943
Larry Hastings9cf065c2012-06-22 16:30:09 -07004944#if !defined(HAVE_UTIMENSAT)
4945 if ((dir_fd != DEFAULT_DIR_FD) && (!follow_symlinks)) {
Georg Brandl969288e2012-06-26 09:25:44 +02004946 PyErr_SetString(PyExc_ValueError,
Larry Hastings9cf065c2012-06-22 16:30:09 -07004947 "utime: cannot use dir_fd and follow_symlinks "
4948 "together on this platform");
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004949 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07004950 }
4951#endif
Larry Hastings76ad59b2012-05-03 00:30:07 -07004952
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00004953#ifdef MS_WINDOWS
Larry Hastings9cf065c2012-06-22 16:30:09 -07004954 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -07004955 hFile = CreateFileW(path->wide, FILE_WRITE_ATTRIBUTES, 0,
4956 NULL, OPEN_EXISTING,
4957 FILE_FLAG_BACKUP_SEMANTICS, NULL);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004958 Py_END_ALLOW_THREADS
4959 if (hFile == INVALID_HANDLE_VALUE) {
Larry Hastings2f936352014-08-05 14:04:04 +10004960 path_error(path);
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004961 return NULL;
Larry Hastingsb3336402012-05-04 02:31:57 -07004962 }
4963
Larry Hastings9cf065c2012-06-22 16:30:09 -07004964 if (utime.now) {
Antoine Pitrou91a7af32013-11-23 15:23:26 +01004965 GetSystemTimeAsFileTime(&mtime);
4966 atime = mtime;
Victor Stinner8c62be82010-05-06 00:08:46 +00004967 }
Victor Stinner8c62be82010-05-06 00:08:46 +00004968 else {
Steve Dowerbf1f3762015-02-21 15:26:02 -08004969 _Py_time_t_to_FILE_TIME(utime.atime_s, utime.atime_ns, &atime);
4970 _Py_time_t_to_FILE_TIME(utime.mtime_s, utime.mtime_ns, &mtime);
Victor Stinner8c62be82010-05-06 00:08:46 +00004971 }
4972 if (!SetFileTime(hFile, NULL, &atime, &mtime)) {
4973 /* Avoid putting the file name into the error here,
4974 as that may confuse the user into believing that
4975 something is wrong with the file, when it also
4976 could be the time stamp that gives a problem. */
Victor Stinnerb024e842012-10-31 22:24:06 +01004977 PyErr_SetFromWindowsErr(0);
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004978 CloseHandle(hFile);
4979 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00004980 }
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004981 CloseHandle(hFile);
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00004982#else /* MS_WINDOWS */
Larry Hastings9cf065c2012-06-22 16:30:09 -07004983 Py_BEGIN_ALLOW_THREADS
Guido van Rossum1ff6cb41991-04-08 20:59:13 +00004984
Victor Stinner4552ced2015-09-21 22:37:15 +02004985#ifdef UTIME_HAVE_NOFOLLOW_SYMLINKS
Larry Hastings9cf065c2012-06-22 16:30:09 -07004986 if ((!follow_symlinks) && (dir_fd == DEFAULT_DIR_FD))
Larry Hastings2f936352014-08-05 14:04:04 +10004987 result = utime_nofollow_symlinks(&utime, path->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004988 else
Larry Hastings9e3e70b2011-09-08 19:29:07 -07004989#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -07004990
Victor Stinner528a9ab2015-09-03 21:30:26 +02004991#if defined(HAVE_FUTIMESAT) || defined(HAVE_UTIMENSAT)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004992 if ((dir_fd != DEFAULT_DIR_FD) || (!follow_symlinks))
Larry Hastings2f936352014-08-05 14:04:04 +10004993 result = utime_dir_fd(&utime, dir_fd, path->narrow, follow_symlinks);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004994 else
4995#endif
4996
Victor Stinner528a9ab2015-09-03 21:30:26 +02004997#if defined(HAVE_FUTIMES) || defined(HAVE_FUTIMENS)
Larry Hastings2f936352014-08-05 14:04:04 +10004998 if (path->fd != -1)
4999 result = utime_fd(&utime, path->fd);
Larry Hastings9cf065c2012-06-22 16:30:09 -07005000 else
5001#endif
5002
Larry Hastings2f936352014-08-05 14:04:04 +10005003 result = utime_default(&utime, path->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07005004
5005 Py_END_ALLOW_THREADS
5006
5007 if (result < 0) {
5008 /* see previous comment about not putting filename in error here */
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02005009 posix_error();
5010 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00005011 }
Larry Hastings76ad59b2012-05-03 00:30:07 -07005012
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00005013#endif /* MS_WINDOWS */
Larry Hastings9cf065c2012-06-22 16:30:09 -07005014
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02005015 Py_RETURN_NONE;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00005016}
5017
Guido van Rossum3b066191991-06-04 19:40:25 +00005018/* Process operations */
Guido van Rossum85e3b011991-06-03 12:42:10 +00005019
Larry Hastings2f936352014-08-05 14:04:04 +10005020
5021/*[clinic input]
5022os._exit
5023
5024 status: int
5025
5026Exit to the system with specified status, without normal exit processing.
5027[clinic start generated code]*/
5028
Larry Hastings2f936352014-08-05 14:04:04 +10005029static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005030os__exit_impl(PyObject *module, int status)
5031/*[clinic end generated code: output=116e52d9c2260d54 input=5e6d57556b0c4a62]*/
Larry Hastings2f936352014-08-05 14:04:04 +10005032{
5033 _exit(status);
Victor Stinner8c62be82010-05-06 00:08:46 +00005034 return NULL; /* Make gcc -Wall happy */
Guido van Rossum85e3b011991-06-03 12:42:10 +00005035}
5036
Steve Dowercc16be82016-09-08 10:35:16 -07005037#if defined(HAVE_WEXECV) || defined(HAVE_WSPAWNV)
5038#define EXECV_CHAR wchar_t
5039#else
5040#define EXECV_CHAR char
5041#endif
5042
pxinwrf2d7ac72019-05-21 18:46:37 +08005043#if defined(HAVE_EXECV) || defined(HAVE_SPAWNV) || defined(HAVE_RTPSPAWN)
Martin v. Löwis114619e2002-10-07 06:44:21 +00005044static void
Steve Dowercc16be82016-09-08 10:35:16 -07005045free_string_array(EXECV_CHAR **array, Py_ssize_t count)
Martin v. Löwis114619e2002-10-07 06:44:21 +00005046{
Victor Stinner8c62be82010-05-06 00:08:46 +00005047 Py_ssize_t i;
5048 for (i = 0; i < count; i++)
5049 PyMem_Free(array[i]);
5050 PyMem_DEL(array);
Martin v. Löwis114619e2002-10-07 06:44:21 +00005051}
Martin v. Löwis011e8422009-05-05 04:43:17 +00005052
Berker Peksag81816462016-09-15 20:19:47 +03005053static int
5054fsconvert_strdup(PyObject *o, EXECV_CHAR **out)
Martin v. Löwis011e8422009-05-05 04:43:17 +00005055{
Victor Stinner8c62be82010-05-06 00:08:46 +00005056 Py_ssize_t size;
Berker Peksag81816462016-09-15 20:19:47 +03005057 PyObject *ub;
5058 int result = 0;
Steve Dowercc16be82016-09-08 10:35:16 -07005059#if defined(HAVE_WEXECV) || defined(HAVE_WSPAWNV)
Berker Peksag81816462016-09-15 20:19:47 +03005060 if (!PyUnicode_FSDecoder(o, &ub))
Steve Dowercc16be82016-09-08 10:35:16 -07005061 return 0;
Berker Peksag81816462016-09-15 20:19:47 +03005062 *out = PyUnicode_AsWideCharString(ub, &size);
5063 if (*out)
5064 result = 1;
Steve Dowercc16be82016-09-08 10:35:16 -07005065#else
Berker Peksag81816462016-09-15 20:19:47 +03005066 if (!PyUnicode_FSConverter(o, &ub))
Victor Stinner8c62be82010-05-06 00:08:46 +00005067 return 0;
Berker Peksag81816462016-09-15 20:19:47 +03005068 size = PyBytes_GET_SIZE(ub);
5069 *out = PyMem_Malloc(size + 1);
5070 if (*out) {
5071 memcpy(*out, PyBytes_AS_STRING(ub), size + 1);
5072 result = 1;
5073 } else
Victor Stinner50abf222013-11-07 23:56:10 +01005074 PyErr_NoMemory();
Steve Dowercc16be82016-09-08 10:35:16 -07005075#endif
Berker Peksag81816462016-09-15 20:19:47 +03005076 Py_DECREF(ub);
5077 return result;
Martin v. Löwis011e8422009-05-05 04:43:17 +00005078}
Martin v. Löwis114619e2002-10-07 06:44:21 +00005079#endif
5080
pxinwrf2d7ac72019-05-21 18:46:37 +08005081#if defined(HAVE_EXECV) || defined (HAVE_FEXECVE) || defined(HAVE_RTPSPAWN)
Steve Dowercc16be82016-09-08 10:35:16 -07005082static EXECV_CHAR**
Victor Stinner13bb71c2010-04-23 21:41:56 +00005083parse_envlist(PyObject* env, Py_ssize_t *envc_ptr)
5084{
Victor Stinner8c62be82010-05-06 00:08:46 +00005085 Py_ssize_t i, pos, envc;
5086 PyObject *keys=NULL, *vals=NULL;
Berker Peksag81816462016-09-15 20:19:47 +03005087 PyObject *key, *val, *key2, *val2, *keyval;
Steve Dowercc16be82016-09-08 10:35:16 -07005088 EXECV_CHAR **envlist;
Victor Stinner13bb71c2010-04-23 21:41:56 +00005089
Victor Stinner8c62be82010-05-06 00:08:46 +00005090 i = PyMapping_Size(env);
5091 if (i < 0)
5092 return NULL;
Steve Dowercc16be82016-09-08 10:35:16 -07005093 envlist = PyMem_NEW(EXECV_CHAR *, i + 1);
Victor Stinner8c62be82010-05-06 00:08:46 +00005094 if (envlist == NULL) {
5095 PyErr_NoMemory();
5096 return NULL;
5097 }
5098 envc = 0;
5099 keys = PyMapping_Keys(env);
Victor Stinnerb0314272013-11-14 21:37:05 +01005100 if (!keys)
5101 goto error;
Victor Stinner8c62be82010-05-06 00:08:46 +00005102 vals = PyMapping_Values(env);
Victor Stinnerb0314272013-11-14 21:37:05 +01005103 if (!vals)
Victor Stinner8c62be82010-05-06 00:08:46 +00005104 goto error;
5105 if (!PyList_Check(keys) || !PyList_Check(vals)) {
5106 PyErr_Format(PyExc_TypeError,
5107 "env.keys() or env.values() is not a list");
5108 goto error;
5109 }
Victor Stinner13bb71c2010-04-23 21:41:56 +00005110
Victor Stinner8c62be82010-05-06 00:08:46 +00005111 for (pos = 0; pos < i; pos++) {
5112 key = PyList_GetItem(keys, pos);
5113 val = PyList_GetItem(vals, pos);
5114 if (!key || !val)
5115 goto error;
Victor Stinner13bb71c2010-04-23 21:41:56 +00005116
Berker Peksag81816462016-09-15 20:19:47 +03005117#if defined(HAVE_WEXECV) || defined(HAVE_WSPAWNV)
5118 if (!PyUnicode_FSDecoder(key, &key2))
5119 goto error;
5120 if (!PyUnicode_FSDecoder(val, &val2)) {
5121 Py_DECREF(key2);
5122 goto error;
5123 }
Serhiy Storchaka77703942017-06-25 07:33:01 +03005124 /* Search from index 1 because on Windows starting '=' is allowed for
5125 defining hidden environment variables. */
5126 if (PyUnicode_GET_LENGTH(key2) == 0 ||
5127 PyUnicode_FindChar(key2, '=', 1, PyUnicode_GET_LENGTH(key2), 1) != -1)
5128 {
5129 PyErr_SetString(PyExc_ValueError, "illegal environment variable name");
Eric N. Vander Weelea7874c72017-06-26 21:35:20 -04005130 Py_DECREF(key2);
5131 Py_DECREF(val2);
Serhiy Storchaka77703942017-06-25 07:33:01 +03005132 goto error;
5133 }
Berker Peksag81816462016-09-15 20:19:47 +03005134 keyval = PyUnicode_FromFormat("%U=%U", key2, val2);
5135#else
5136 if (!PyUnicode_FSConverter(key, &key2))
5137 goto error;
5138 if (!PyUnicode_FSConverter(val, &val2)) {
5139 Py_DECREF(key2);
5140 goto error;
5141 }
Serhiy Storchaka77703942017-06-25 07:33:01 +03005142 if (PyBytes_GET_SIZE(key2) == 0 ||
5143 strchr(PyBytes_AS_STRING(key2) + 1, '=') != NULL)
5144 {
5145 PyErr_SetString(PyExc_ValueError, "illegal environment variable name");
Eric N. Vander Weelea7874c72017-06-26 21:35:20 -04005146 Py_DECREF(key2);
5147 Py_DECREF(val2);
Serhiy Storchaka77703942017-06-25 07:33:01 +03005148 goto error;
5149 }
Berker Peksag81816462016-09-15 20:19:47 +03005150 keyval = PyBytes_FromFormat("%s=%s", PyBytes_AS_STRING(key2),
5151 PyBytes_AS_STRING(val2));
5152#endif
5153 Py_DECREF(key2);
5154 Py_DECREF(val2);
Steve Dowercc16be82016-09-08 10:35:16 -07005155 if (!keyval)
Victor Stinner8c62be82010-05-06 00:08:46 +00005156 goto error;
Steve Dowercc16be82016-09-08 10:35:16 -07005157
5158 if (!fsconvert_strdup(keyval, &envlist[envc++])) {
5159 Py_DECREF(keyval);
Victor Stinner8c62be82010-05-06 00:08:46 +00005160 goto error;
5161 }
Berker Peksag81816462016-09-15 20:19:47 +03005162
Steve Dowercc16be82016-09-08 10:35:16 -07005163 Py_DECREF(keyval);
Victor Stinner8c62be82010-05-06 00:08:46 +00005164 }
5165 Py_DECREF(vals);
5166 Py_DECREF(keys);
Victor Stinner13bb71c2010-04-23 21:41:56 +00005167
Victor Stinner8c62be82010-05-06 00:08:46 +00005168 envlist[envc] = 0;
5169 *envc_ptr = envc;
5170 return envlist;
Victor Stinner13bb71c2010-04-23 21:41:56 +00005171
5172error:
Victor Stinner8c62be82010-05-06 00:08:46 +00005173 Py_XDECREF(keys);
5174 Py_XDECREF(vals);
Steve Dowercc16be82016-09-08 10:35:16 -07005175 free_string_array(envlist, envc);
Victor Stinner8c62be82010-05-06 00:08:46 +00005176 return NULL;
Victor Stinner13bb71c2010-04-23 21:41:56 +00005177}
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00005178
Steve Dowercc16be82016-09-08 10:35:16 -07005179static EXECV_CHAR**
Ross Lagerwall7807c352011-03-17 20:20:30 +02005180parse_arglist(PyObject* argv, Py_ssize_t *argc)
5181{
5182 int i;
Steve Dowercc16be82016-09-08 10:35:16 -07005183 EXECV_CHAR **argvlist = PyMem_NEW(EXECV_CHAR *, *argc+1);
Ross Lagerwall7807c352011-03-17 20:20:30 +02005184 if (argvlist == NULL) {
5185 PyErr_NoMemory();
5186 return NULL;
5187 }
5188 for (i = 0; i < *argc; i++) {
Ross Lagerwall9ad63e02011-03-19 09:11:14 +02005189 PyObject* item = PySequence_ITEM(argv, i);
5190 if (item == NULL)
5191 goto fail;
5192 if (!fsconvert_strdup(item, &argvlist[i])) {
5193 Py_DECREF(item);
Ross Lagerwall7807c352011-03-17 20:20:30 +02005194 goto fail;
5195 }
Ross Lagerwall9ad63e02011-03-19 09:11:14 +02005196 Py_DECREF(item);
Ross Lagerwall7807c352011-03-17 20:20:30 +02005197 }
5198 argvlist[*argc] = NULL;
5199 return argvlist;
5200fail:
Ross Lagerwall9ad63e02011-03-19 09:11:14 +02005201 *argc = i;
Ross Lagerwall7807c352011-03-17 20:20:30 +02005202 free_string_array(argvlist, *argc);
5203 return NULL;
5204}
Steve Dowercc16be82016-09-08 10:35:16 -07005205
Ross Lagerwall7807c352011-03-17 20:20:30 +02005206#endif
5207
Larry Hastings2f936352014-08-05 14:04:04 +10005208
Ross Lagerwall7807c352011-03-17 20:20:30 +02005209#ifdef HAVE_EXECV
Larry Hastings2f936352014-08-05 14:04:04 +10005210/*[clinic input]
5211os.execv
5212
Steve Dowercc16be82016-09-08 10:35:16 -07005213 path: path_t
Larry Hastings2f936352014-08-05 14:04:04 +10005214 Path of executable file.
5215 argv: object
5216 Tuple or list of strings.
5217 /
5218
5219Execute an executable path with arguments, replacing current process.
5220[clinic start generated code]*/
5221
Larry Hastings2f936352014-08-05 14:04:04 +10005222static PyObject *
Steve Dowercc16be82016-09-08 10:35:16 -07005223os_execv_impl(PyObject *module, path_t *path, PyObject *argv)
5224/*[clinic end generated code: output=3b52fec34cd0dafd input=9bac31efae07dac7]*/
Larry Hastings2f936352014-08-05 14:04:04 +10005225{
Steve Dowercc16be82016-09-08 10:35:16 -07005226 EXECV_CHAR **argvlist;
Ross Lagerwall7807c352011-03-17 20:20:30 +02005227 Py_ssize_t argc;
5228
5229 /* execv has two arguments: (path, argv), where
5230 argv is a list or tuple of strings. */
5231
Ross Lagerwall7807c352011-03-17 20:20:30 +02005232 if (!PyList_Check(argv) && !PyTuple_Check(argv)) {
5233 PyErr_SetString(PyExc_TypeError,
5234 "execv() arg 2 must be a tuple or list");
Ross Lagerwall7807c352011-03-17 20:20:30 +02005235 return NULL;
5236 }
5237 argc = PySequence_Size(argv);
5238 if (argc < 1) {
5239 PyErr_SetString(PyExc_ValueError, "execv() arg 2 must not be empty");
Ross Lagerwall7807c352011-03-17 20:20:30 +02005240 return NULL;
5241 }
5242
5243 argvlist = parse_arglist(argv, &argc);
5244 if (argvlist == NULL) {
Ross Lagerwall7807c352011-03-17 20:20:30 +02005245 return NULL;
5246 }
Steve Dowerbce26262016-11-19 19:17:26 -08005247 if (!argvlist[0][0]) {
5248 PyErr_SetString(PyExc_ValueError,
5249 "execv() arg 2 first element cannot be empty");
5250 free_string_array(argvlist, argc);
5251 return NULL;
5252 }
Ross Lagerwall7807c352011-03-17 20:20:30 +02005253
Steve Dowerbce26262016-11-19 19:17:26 -08005254 _Py_BEGIN_SUPPRESS_IPH
Steve Dowercc16be82016-09-08 10:35:16 -07005255#ifdef HAVE_WEXECV
5256 _wexecv(path->wide, argvlist);
5257#else
5258 execv(path->narrow, argvlist);
5259#endif
Steve Dowerbce26262016-11-19 19:17:26 -08005260 _Py_END_SUPPRESS_IPH
Ross Lagerwall7807c352011-03-17 20:20:30 +02005261
5262 /* If we get here it's definitely an error */
5263
5264 free_string_array(argvlist, argc);
Ross Lagerwall7807c352011-03-17 20:20:30 +02005265 return posix_error();
5266}
5267
Larry Hastings2f936352014-08-05 14:04:04 +10005268
5269/*[clinic input]
5270os.execve
5271
5272 path: path_t(allow_fd='PATH_HAVE_FEXECVE')
5273 Path of executable file.
5274 argv: object
5275 Tuple or list of strings.
5276 env: object
5277 Dictionary of strings mapping to strings.
5278
5279Execute an executable path with arguments, replacing current process.
5280[clinic start generated code]*/
5281
Larry Hastings2f936352014-08-05 14:04:04 +10005282static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005283os_execve_impl(PyObject *module, path_t *path, PyObject *argv, PyObject *env)
5284/*[clinic end generated code: output=ff9fa8e4da8bde58 input=626804fa092606d9]*/
Larry Hastings2f936352014-08-05 14:04:04 +10005285{
Steve Dowercc16be82016-09-08 10:35:16 -07005286 EXECV_CHAR **argvlist = NULL;
5287 EXECV_CHAR **envlist;
Ross Lagerwall7807c352011-03-17 20:20:30 +02005288 Py_ssize_t argc, envc;
Guido van Rossumc6dcc9f1993-11-05 10:15:19 +00005289
Victor Stinner8c62be82010-05-06 00:08:46 +00005290 /* execve has three arguments: (path, argv, env), where
5291 argv is a list or tuple of strings and env is a dictionary
5292 like posix.environ. */
Guido van Rossumc6dcc9f1993-11-05 10:15:19 +00005293
Ross Lagerwall7807c352011-03-17 20:20:30 +02005294 if (!PyList_Check(argv) && !PyTuple_Check(argv)) {
Victor Stinner8c62be82010-05-06 00:08:46 +00005295 PyErr_SetString(PyExc_TypeError,
Larry Hastings9cf065c2012-06-22 16:30:09 -07005296 "execve: argv must be a tuple or list");
5297 goto fail;
Victor Stinner8c62be82010-05-06 00:08:46 +00005298 }
Ross Lagerwall7807c352011-03-17 20:20:30 +02005299 argc = PySequence_Size(argv);
Steve Dowerbce26262016-11-19 19:17:26 -08005300 if (argc < 1) {
5301 PyErr_SetString(PyExc_ValueError, "execve: argv must not be empty");
5302 return NULL;
5303 }
5304
Victor Stinner8c62be82010-05-06 00:08:46 +00005305 if (!PyMapping_Check(env)) {
5306 PyErr_SetString(PyExc_TypeError,
Larry Hastings9cf065c2012-06-22 16:30:09 -07005307 "execve: environment must be a mapping object");
5308 goto fail;
Victor Stinner8c62be82010-05-06 00:08:46 +00005309 }
Guido van Rossumc6dcc9f1993-11-05 10:15:19 +00005310
Ross Lagerwall7807c352011-03-17 20:20:30 +02005311 argvlist = parse_arglist(argv, &argc);
Victor Stinner8c62be82010-05-06 00:08:46 +00005312 if (argvlist == NULL) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07005313 goto fail;
Victor Stinner8c62be82010-05-06 00:08:46 +00005314 }
Steve Dowerbce26262016-11-19 19:17:26 -08005315 if (!argvlist[0][0]) {
5316 PyErr_SetString(PyExc_ValueError,
5317 "execve: argv first element cannot be empty");
5318 goto fail;
5319 }
Guido van Rossumc6dcc9f1993-11-05 10:15:19 +00005320
Victor Stinner8c62be82010-05-06 00:08:46 +00005321 envlist = parse_envlist(env, &envc);
5322 if (envlist == NULL)
Ross Lagerwall7807c352011-03-17 20:20:30 +02005323 goto fail;
5324
Steve Dowerbce26262016-11-19 19:17:26 -08005325 _Py_BEGIN_SUPPRESS_IPH
Larry Hastings9cf065c2012-06-22 16:30:09 -07005326#ifdef HAVE_FEXECVE
Larry Hastings2f936352014-08-05 14:04:04 +10005327 if (path->fd > -1)
5328 fexecve(path->fd, argvlist, envlist);
Larry Hastings9cf065c2012-06-22 16:30:09 -07005329 else
5330#endif
Steve Dowercc16be82016-09-08 10:35:16 -07005331#ifdef HAVE_WEXECV
5332 _wexecve(path->wide, argvlist, envlist);
5333#else
Larry Hastings2f936352014-08-05 14:04:04 +10005334 execve(path->narrow, argvlist, envlist);
Steve Dowercc16be82016-09-08 10:35:16 -07005335#endif
Steve Dowerbce26262016-11-19 19:17:26 -08005336 _Py_END_SUPPRESS_IPH
Ross Lagerwall7807c352011-03-17 20:20:30 +02005337
5338 /* If we get here it's definitely an error */
5339
Alexey Izbyshev83460312018-10-20 03:28:22 +03005340 posix_path_error(path);
Ross Lagerwall7807c352011-03-17 20:20:30 +02005341
Steve Dowercc16be82016-09-08 10:35:16 -07005342 free_string_array(envlist, envc);
Ross Lagerwall7807c352011-03-17 20:20:30 +02005343 fail:
Larry Hastings9cf065c2012-06-22 16:30:09 -07005344 if (argvlist)
5345 free_string_array(argvlist, argc);
Ross Lagerwall7807c352011-03-17 20:20:30 +02005346 return NULL;
5347}
Steve Dowercc16be82016-09-08 10:35:16 -07005348
Larry Hastings9cf065c2012-06-22 16:30:09 -07005349#endif /* HAVE_EXECV */
5350
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005351#ifdef HAVE_POSIX_SPAWN
5352
5353enum posix_spawn_file_actions_identifier {
5354 POSIX_SPAWN_OPEN,
5355 POSIX_SPAWN_CLOSE,
5356 POSIX_SPAWN_DUP2
5357};
5358
William Orr81574b82018-10-01 22:19:56 -07005359#if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
Serhiy Storchakaef347532018-05-01 16:45:04 +03005360static int
Pablo Galindo254a4662018-09-07 16:44:24 +01005361convert_sched_param(PyObject *param, struct sched_param *res);
William Orr81574b82018-10-01 22:19:56 -07005362#endif
Pablo Galindo254a4662018-09-07 16:44:24 +01005363
5364static int
Victor Stinner325e4ba2019-02-01 15:47:24 +01005365parse_posix_spawn_flags(const char *func_name, PyObject *setpgroup,
5366 int resetids, int setsid, PyObject *setsigmask,
Pablo Galindo254a4662018-09-07 16:44:24 +01005367 PyObject *setsigdef, PyObject *scheduler,
5368 posix_spawnattr_t *attrp)
5369{
5370 long all_flags = 0;
5371
5372 errno = posix_spawnattr_init(attrp);
5373 if (errno) {
5374 posix_error();
5375 return -1;
5376 }
5377
5378 if (setpgroup) {
5379 pid_t pgid = PyLong_AsPid(setpgroup);
5380 if (pgid == (pid_t)-1 && PyErr_Occurred()) {
5381 goto fail;
5382 }
5383 errno = posix_spawnattr_setpgroup(attrp, pgid);
5384 if (errno) {
5385 posix_error();
5386 goto fail;
5387 }
5388 all_flags |= POSIX_SPAWN_SETPGROUP;
5389 }
5390
5391 if (resetids) {
5392 all_flags |= POSIX_SPAWN_RESETIDS;
5393 }
5394
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005395 if (setsid) {
5396#ifdef POSIX_SPAWN_SETSID
5397 all_flags |= POSIX_SPAWN_SETSID;
5398#elif defined(POSIX_SPAWN_SETSID_NP)
5399 all_flags |= POSIX_SPAWN_SETSID_NP;
5400#else
5401 argument_unavailable_error(func_name, "setsid");
5402 return -1;
5403#endif
5404 }
5405
Pablo Galindo254a4662018-09-07 16:44:24 +01005406 if (setsigmask) {
5407 sigset_t set;
5408 if (!_Py_Sigset_Converter(setsigmask, &set)) {
5409 goto fail;
5410 }
5411 errno = posix_spawnattr_setsigmask(attrp, &set);
5412 if (errno) {
5413 posix_error();
5414 goto fail;
5415 }
5416 all_flags |= POSIX_SPAWN_SETSIGMASK;
5417 }
5418
5419 if (setsigdef) {
5420 sigset_t set;
5421 if (!_Py_Sigset_Converter(setsigdef, &set)) {
5422 goto fail;
5423 }
5424 errno = posix_spawnattr_setsigdefault(attrp, &set);
5425 if (errno) {
5426 posix_error();
5427 goto fail;
5428 }
5429 all_flags |= POSIX_SPAWN_SETSIGDEF;
5430 }
5431
5432 if (scheduler) {
5433#ifdef POSIX_SPAWN_SETSCHEDULER
5434 PyObject *py_schedpolicy;
5435 struct sched_param schedparam;
5436
5437 if (!PyArg_ParseTuple(scheduler, "OO&"
5438 ";A scheduler tuple must have two elements",
5439 &py_schedpolicy, convert_sched_param, &schedparam)) {
5440 goto fail;
5441 }
5442 if (py_schedpolicy != Py_None) {
5443 int schedpolicy = _PyLong_AsInt(py_schedpolicy);
5444
5445 if (schedpolicy == -1 && PyErr_Occurred()) {
5446 goto fail;
5447 }
5448 errno = posix_spawnattr_setschedpolicy(attrp, schedpolicy);
5449 if (errno) {
5450 posix_error();
5451 goto fail;
5452 }
5453 all_flags |= POSIX_SPAWN_SETSCHEDULER;
5454 }
5455 errno = posix_spawnattr_setschedparam(attrp, &schedparam);
5456 if (errno) {
5457 posix_error();
5458 goto fail;
5459 }
5460 all_flags |= POSIX_SPAWN_SETSCHEDPARAM;
5461#else
5462 PyErr_SetString(PyExc_NotImplementedError,
5463 "The scheduler option is not supported in this system.");
5464 goto fail;
5465#endif
5466 }
5467
5468 errno = posix_spawnattr_setflags(attrp, all_flags);
5469 if (errno) {
5470 posix_error();
5471 goto fail;
5472 }
5473
5474 return 0;
5475
5476fail:
5477 (void)posix_spawnattr_destroy(attrp);
5478 return -1;
5479}
5480
5481static int
Serhiy Storchakaef347532018-05-01 16:45:04 +03005482parse_file_actions(PyObject *file_actions,
Pablo Galindocb970732018-06-19 09:19:50 +01005483 posix_spawn_file_actions_t *file_actionsp,
5484 PyObject *temp_buffer)
Serhiy Storchakaef347532018-05-01 16:45:04 +03005485{
5486 PyObject *seq;
5487 PyObject *file_action = NULL;
5488 PyObject *tag_obj;
5489
5490 seq = PySequence_Fast(file_actions,
5491 "file_actions must be a sequence or None");
5492 if (seq == NULL) {
5493 return -1;
5494 }
5495
5496 errno = posix_spawn_file_actions_init(file_actionsp);
5497 if (errno) {
5498 posix_error();
5499 Py_DECREF(seq);
5500 return -1;
5501 }
5502
Zackery Spytzd52a83a2019-06-26 14:54:20 -06005503 for (Py_ssize_t i = 0; i < PySequence_Fast_GET_SIZE(seq); ++i) {
Serhiy Storchakaef347532018-05-01 16:45:04 +03005504 file_action = PySequence_Fast_GET_ITEM(seq, i);
5505 Py_INCREF(file_action);
5506 if (!PyTuple_Check(file_action) || !PyTuple_GET_SIZE(file_action)) {
5507 PyErr_SetString(PyExc_TypeError,
5508 "Each file_actions element must be a non-empty tuple");
5509 goto fail;
5510 }
5511 long tag = PyLong_AsLong(PyTuple_GET_ITEM(file_action, 0));
5512 if (tag == -1 && PyErr_Occurred()) {
5513 goto fail;
5514 }
5515
5516 /* Populate the file_actions object */
5517 switch (tag) {
5518 case POSIX_SPAWN_OPEN: {
5519 int fd, oflag;
5520 PyObject *path;
5521 unsigned long mode;
5522 if (!PyArg_ParseTuple(file_action, "OiO&ik"
5523 ";A open file_action tuple must have 5 elements",
5524 &tag_obj, &fd, PyUnicode_FSConverter, &path,
5525 &oflag, &mode))
5526 {
5527 goto fail;
5528 }
Pablo Galindocb970732018-06-19 09:19:50 +01005529 if (PyList_Append(temp_buffer, path)) {
5530 Py_DECREF(path);
5531 goto fail;
5532 }
Serhiy Storchakaef347532018-05-01 16:45:04 +03005533 errno = posix_spawn_file_actions_addopen(file_actionsp,
5534 fd, PyBytes_AS_STRING(path), oflag, (mode_t)mode);
Pablo Galindocb970732018-06-19 09:19:50 +01005535 Py_DECREF(path);
Serhiy Storchakaef347532018-05-01 16:45:04 +03005536 if (errno) {
5537 posix_error();
5538 goto fail;
5539 }
5540 break;
5541 }
5542 case POSIX_SPAWN_CLOSE: {
5543 int fd;
5544 if (!PyArg_ParseTuple(file_action, "Oi"
5545 ";A close file_action tuple must have 2 elements",
5546 &tag_obj, &fd))
5547 {
5548 goto fail;
5549 }
5550 errno = posix_spawn_file_actions_addclose(file_actionsp, fd);
5551 if (errno) {
5552 posix_error();
5553 goto fail;
5554 }
5555 break;
5556 }
5557 case POSIX_SPAWN_DUP2: {
5558 int fd1, fd2;
5559 if (!PyArg_ParseTuple(file_action, "Oii"
5560 ";A dup2 file_action tuple must have 3 elements",
5561 &tag_obj, &fd1, &fd2))
5562 {
5563 goto fail;
5564 }
5565 errno = posix_spawn_file_actions_adddup2(file_actionsp,
5566 fd1, fd2);
5567 if (errno) {
5568 posix_error();
5569 goto fail;
5570 }
5571 break;
5572 }
5573 default: {
5574 PyErr_SetString(PyExc_TypeError,
5575 "Unknown file_actions identifier");
5576 goto fail;
5577 }
5578 }
5579 Py_DECREF(file_action);
5580 }
Pablo Galindo254a4662018-09-07 16:44:24 +01005581
Serhiy Storchakaef347532018-05-01 16:45:04 +03005582 Py_DECREF(seq);
5583 return 0;
5584
5585fail:
5586 Py_DECREF(seq);
5587 Py_DECREF(file_action);
5588 (void)posix_spawn_file_actions_destroy(file_actionsp);
5589 return -1;
5590}
5591
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005592
5593static PyObject *
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005594py_posix_spawn(int use_posix_spawnp, PyObject *module, path_t *path, PyObject *argv,
5595 PyObject *env, PyObject *file_actions,
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005596 PyObject *setpgroup, int resetids, int setsid, PyObject *setsigmask,
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005597 PyObject *setsigdef, PyObject *scheduler)
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005598{
Victor Stinner325e4ba2019-02-01 15:47:24 +01005599 const char *func_name = use_posix_spawnp ? "posix_spawnp" : "posix_spawn";
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005600 EXECV_CHAR **argvlist = NULL;
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005601 EXECV_CHAR **envlist = NULL;
Serhiy Storchakaef347532018-05-01 16:45:04 +03005602 posix_spawn_file_actions_t file_actions_buf;
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005603 posix_spawn_file_actions_t *file_actionsp = NULL;
Pablo Galindo254a4662018-09-07 16:44:24 +01005604 posix_spawnattr_t attr;
5605 posix_spawnattr_t *attrp = NULL;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005606 Py_ssize_t argc, envc;
Serhiy Storchakaef347532018-05-01 16:45:04 +03005607 PyObject *result = NULL;
Pablo Galindocb970732018-06-19 09:19:50 +01005608 PyObject *temp_buffer = NULL;
Serhiy Storchakaef347532018-05-01 16:45:04 +03005609 pid_t pid;
5610 int err_code;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005611
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005612 /* posix_spawn and posix_spawnp have three arguments: (path, argv, env), where
Serhiy Storchakaef347532018-05-01 16:45:04 +03005613 argv is a list or tuple of strings and env is a dictionary
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005614 like posix.environ. */
5615
Serhiy Storchakaef347532018-05-01 16:45:04 +03005616 if (!PyList_Check(argv) && !PyTuple_Check(argv)) {
Victor Stinner325e4ba2019-02-01 15:47:24 +01005617 PyErr_Format(PyExc_TypeError,
5618 "%s: argv must be a tuple or list", func_name);
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005619 goto exit;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005620 }
5621 argc = PySequence_Size(argv);
5622 if (argc < 1) {
Victor Stinner325e4ba2019-02-01 15:47:24 +01005623 PyErr_Format(PyExc_ValueError,
5624 "%s: argv must not be empty", func_name);
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005625 return NULL;
5626 }
5627
5628 if (!PyMapping_Check(env)) {
Victor Stinner325e4ba2019-02-01 15:47:24 +01005629 PyErr_Format(PyExc_TypeError,
5630 "%s: environment must be a mapping object", func_name);
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005631 goto exit;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005632 }
5633
5634 argvlist = parse_arglist(argv, &argc);
5635 if (argvlist == NULL) {
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005636 goto exit;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005637 }
5638 if (!argvlist[0][0]) {
Victor Stinner325e4ba2019-02-01 15:47:24 +01005639 PyErr_Format(PyExc_ValueError,
5640 "%s: argv first element cannot be empty", func_name);
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005641 goto exit;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005642 }
5643
5644 envlist = parse_envlist(env, &envc);
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005645 if (envlist == NULL) {
5646 goto exit;
5647 }
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005648
Anthony Shaw948ed8c2019-05-10 12:00:06 +10005649 if (file_actions != NULL && file_actions != Py_None) {
Pablo Galindocb970732018-06-19 09:19:50 +01005650 /* There is a bug in old versions of glibc that makes some of the
5651 * helper functions for manipulating file actions not copy the provided
5652 * buffers. The problem is that posix_spawn_file_actions_addopen does not
5653 * copy the value of path for some old versions of glibc (<2.20).
5654 * The use of temp_buffer here is a workaround that keeps the
5655 * python objects that own the buffers alive until posix_spawn gets called.
5656 * Check https://bugs.python.org/issue33630 and
5657 * https://sourceware.org/bugzilla/show_bug.cgi?id=17048 for more info.*/
5658 temp_buffer = PyList_New(0);
5659 if (!temp_buffer) {
5660 goto exit;
5661 }
5662 if (parse_file_actions(file_actions, &file_actions_buf, temp_buffer)) {
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005663 goto exit;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005664 }
Serhiy Storchakaef347532018-05-01 16:45:04 +03005665 file_actionsp = &file_actions_buf;
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005666 }
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005667
Victor Stinner325e4ba2019-02-01 15:47:24 +01005668 if (parse_posix_spawn_flags(func_name, setpgroup, resetids, setsid,
5669 setsigmask, setsigdef, scheduler, &attr)) {
Pablo Galindo254a4662018-09-07 16:44:24 +01005670 goto exit;
5671 }
5672 attrp = &attr;
5673
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005674 _Py_BEGIN_SUPPRESS_IPH
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005675#ifdef HAVE_POSIX_SPAWNP
5676 if (use_posix_spawnp) {
5677 err_code = posix_spawnp(&pid, path->narrow,
5678 file_actionsp, attrp, argvlist, envlist);
5679 }
5680 else
5681#endif /* HAVE_POSIX_SPAWNP */
5682 {
5683 err_code = posix_spawn(&pid, path->narrow,
5684 file_actionsp, attrp, argvlist, envlist);
5685 }
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005686 _Py_END_SUPPRESS_IPH
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005687
Serhiy Storchakaef347532018-05-01 16:45:04 +03005688 if (err_code) {
5689 errno = err_code;
5690 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, path->object);
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005691 goto exit;
5692 }
Gregory P. Smith1d300ce2018-12-30 21:13:02 -08005693#ifdef _Py_MEMORY_SANITIZER
5694 __msan_unpoison(&pid, sizeof(pid));
5695#endif
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005696 result = PyLong_FromPid(pid);
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005697
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005698exit:
Serhiy Storchakaef347532018-05-01 16:45:04 +03005699 if (file_actionsp) {
5700 (void)posix_spawn_file_actions_destroy(file_actionsp);
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005701 }
Pablo Galindo254a4662018-09-07 16:44:24 +01005702 if (attrp) {
5703 (void)posix_spawnattr_destroy(attrp);
5704 }
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005705 if (envlist) {
5706 free_string_array(envlist, envc);
5707 }
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005708 if (argvlist) {
5709 free_string_array(argvlist, argc);
5710 }
Pablo Galindocb970732018-06-19 09:19:50 +01005711 Py_XDECREF(temp_buffer);
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005712 return result;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005713}
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005714
5715
5716/*[clinic input]
5717
5718os.posix_spawn
5719 path: path_t
5720 Path of executable file.
5721 argv: object
5722 Tuple or list of strings.
5723 env: object
5724 Dictionary of strings mapping to strings.
5725 /
5726 *
5727 file_actions: object(c_default='NULL') = ()
5728 A sequence of file action tuples.
5729 setpgroup: object = NULL
5730 The pgroup to use with the POSIX_SPAWN_SETPGROUP flag.
5731 resetids: bool(accept={int}) = False
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005732 If the value is `true` the POSIX_SPAWN_RESETIDS will be activated.
5733 setsid: bool(accept={int}) = False
5734 If the value is `true` the POSIX_SPAWN_SETSID or POSIX_SPAWN_SETSID_NP will be activated.
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005735 setsigmask: object(c_default='NULL') = ()
5736 The sigmask to use with the POSIX_SPAWN_SETSIGMASK flag.
5737 setsigdef: object(c_default='NULL') = ()
5738 The sigmask to use with the POSIX_SPAWN_SETSIGDEF flag.
5739 scheduler: object = NULL
5740 A tuple with the scheduler policy (optional) and parameters.
5741
5742Execute the program specified by path in a new process.
5743[clinic start generated code]*/
5744
5745static PyObject *
5746os_posix_spawn_impl(PyObject *module, path_t *path, PyObject *argv,
5747 PyObject *env, PyObject *file_actions,
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005748 PyObject *setpgroup, int resetids, int setsid,
5749 PyObject *setsigmask, PyObject *setsigdef,
5750 PyObject *scheduler)
5751/*[clinic end generated code: output=14a1098c566bc675 input=8c6305619a00ad04]*/
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005752{
5753 return py_posix_spawn(0, module, path, argv, env, file_actions,
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005754 setpgroup, resetids, setsid, setsigmask, setsigdef,
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005755 scheduler);
5756}
5757 #endif /* HAVE_POSIX_SPAWN */
5758
5759
5760
5761#ifdef HAVE_POSIX_SPAWNP
5762/*[clinic input]
5763
5764os.posix_spawnp
5765 path: path_t
5766 Path of executable file.
5767 argv: object
5768 Tuple or list of strings.
5769 env: object
5770 Dictionary of strings mapping to strings.
5771 /
5772 *
5773 file_actions: object(c_default='NULL') = ()
5774 A sequence of file action tuples.
5775 setpgroup: object = NULL
5776 The pgroup to use with the POSIX_SPAWN_SETPGROUP flag.
5777 resetids: bool(accept={int}) = False
5778 If the value is `True` the POSIX_SPAWN_RESETIDS will be activated.
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005779 setsid: bool(accept={int}) = False
5780 If the value is `True` the POSIX_SPAWN_SETSID or POSIX_SPAWN_SETSID_NP will be activated.
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005781 setsigmask: object(c_default='NULL') = ()
5782 The sigmask to use with the POSIX_SPAWN_SETSIGMASK flag.
5783 setsigdef: object(c_default='NULL') = ()
5784 The sigmask to use with the POSIX_SPAWN_SETSIGDEF flag.
5785 scheduler: object = NULL
5786 A tuple with the scheduler policy (optional) and parameters.
5787
5788Execute the program specified by path in a new process.
5789[clinic start generated code]*/
5790
5791static PyObject *
5792os_posix_spawnp_impl(PyObject *module, path_t *path, PyObject *argv,
5793 PyObject *env, PyObject *file_actions,
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005794 PyObject *setpgroup, int resetids, int setsid,
5795 PyObject *setsigmask, PyObject *setsigdef,
5796 PyObject *scheduler)
5797/*[clinic end generated code: output=7b9aaefe3031238d input=c1911043a22028da]*/
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005798{
5799 return py_posix_spawn(1, module, path, argv, env, file_actions,
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005800 setpgroup, resetids, setsid, setsigmask, setsigdef,
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005801 scheduler);
5802}
5803#endif /* HAVE_POSIX_SPAWNP */
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005804
pxinwrf2d7ac72019-05-21 18:46:37 +08005805#ifdef HAVE_RTPSPAWN
5806static intptr_t
5807_rtp_spawn(int mode, const char *rtpFileName, const char *argv[],
5808 const char *envp[])
5809{
5810 RTP_ID rtpid;
5811 int status;
5812 pid_t res;
5813 int async_err = 0;
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00005814
pxinwrf2d7ac72019-05-21 18:46:37 +08005815 /* Set priority=100 and uStackSize=16 MiB (0x1000000) for new processes.
5816 uStackSize=0 cannot be used, the default stack size is too small for
5817 Python. */
5818 if (envp) {
5819 rtpid = rtpSpawn(rtpFileName, argv, envp,
5820 100, 0x1000000, 0, VX_FP_TASK);
5821 }
5822 else {
5823 rtpid = rtpSpawn(rtpFileName, argv, (const char **)environ,
5824 100, 0x1000000, 0, VX_FP_TASK);
5825 }
5826 if ((rtpid != RTP_ID_ERROR) && (mode == _P_WAIT)) {
5827 do {
5828 res = waitpid((pid_t)rtpid, &status, 0);
5829 } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
5830
5831 if (res < 0)
5832 return RTP_ID_ERROR;
5833 return ((intptr_t)status);
5834 }
5835 return ((intptr_t)rtpid);
5836}
5837#endif
5838
5839#if defined(HAVE_SPAWNV) || defined(HAVE_WSPAWNV) || defined(HAVE_RTPSPAWN)
Larry Hastings2f936352014-08-05 14:04:04 +10005840/*[clinic input]
5841os.spawnv
5842
5843 mode: int
5844 Mode of process creation.
Steve Dowercc16be82016-09-08 10:35:16 -07005845 path: path_t
Larry Hastings2f936352014-08-05 14:04:04 +10005846 Path of executable file.
5847 argv: object
5848 Tuple or list of strings.
5849 /
5850
5851Execute the program specified by path in a new process.
5852[clinic start generated code]*/
5853
Larry Hastings2f936352014-08-05 14:04:04 +10005854static PyObject *
Steve Dowercc16be82016-09-08 10:35:16 -07005855os_spawnv_impl(PyObject *module, int mode, path_t *path, PyObject *argv)
5856/*[clinic end generated code: output=71cd037a9d96b816 input=43224242303291be]*/
Larry Hastings2f936352014-08-05 14:04:04 +10005857{
Steve Dowercc16be82016-09-08 10:35:16 -07005858 EXECV_CHAR **argvlist;
Larry Hastings2f936352014-08-05 14:04:04 +10005859 int i;
Victor Stinner8c62be82010-05-06 00:08:46 +00005860 Py_ssize_t argc;
Benjamin Petersonca470632016-09-06 13:47:26 -07005861 intptr_t spawnval;
Victor Stinner8c62be82010-05-06 00:08:46 +00005862 PyObject *(*getitem)(PyObject *, Py_ssize_t);
Guido van Rossuma1065681999-01-25 23:20:23 +00005863
Victor Stinner8c62be82010-05-06 00:08:46 +00005864 /* spawnv has three arguments: (mode, path, argv), where
5865 argv is a list or tuple of strings. */
Guido van Rossuma1065681999-01-25 23:20:23 +00005866
Victor Stinner8c62be82010-05-06 00:08:46 +00005867 if (PyList_Check(argv)) {
5868 argc = PyList_Size(argv);
5869 getitem = PyList_GetItem;
5870 }
5871 else if (PyTuple_Check(argv)) {
5872 argc = PyTuple_Size(argv);
5873 getitem = PyTuple_GetItem;
5874 }
5875 else {
5876 PyErr_SetString(PyExc_TypeError,
5877 "spawnv() arg 2 must be a tuple or list");
Victor Stinner8c62be82010-05-06 00:08:46 +00005878 return NULL;
5879 }
Steve Dower859fd7b2016-11-19 18:53:19 -08005880 if (argc == 0) {
5881 PyErr_SetString(PyExc_ValueError,
5882 "spawnv() arg 2 cannot be empty");
5883 return NULL;
5884 }
Guido van Rossuma1065681999-01-25 23:20:23 +00005885
Steve Dowercc16be82016-09-08 10:35:16 -07005886 argvlist = PyMem_NEW(EXECV_CHAR *, argc+1);
Victor Stinner8c62be82010-05-06 00:08:46 +00005887 if (argvlist == NULL) {
Victor Stinner8c62be82010-05-06 00:08:46 +00005888 return PyErr_NoMemory();
5889 }
5890 for (i = 0; i < argc; i++) {
5891 if (!fsconvert_strdup((*getitem)(argv, i),
5892 &argvlist[i])) {
5893 free_string_array(argvlist, i);
5894 PyErr_SetString(
5895 PyExc_TypeError,
5896 "spawnv() arg 2 must contain only strings");
Victor Stinner8c62be82010-05-06 00:08:46 +00005897 return NULL;
5898 }
Steve Dower93ff8722016-11-19 19:03:54 -08005899 if (i == 0 && !argvlist[0][0]) {
Victor Stinner8acb4cf2017-06-15 15:30:40 +02005900 free_string_array(argvlist, i + 1);
Steve Dower93ff8722016-11-19 19:03:54 -08005901 PyErr_SetString(
5902 PyExc_ValueError,
5903 "spawnv() arg 2 first element cannot be empty");
5904 return NULL;
5905 }
Victor Stinner8c62be82010-05-06 00:08:46 +00005906 }
5907 argvlist[argc] = NULL;
Guido van Rossuma1065681999-01-25 23:20:23 +00005908
pxinwrf2d7ac72019-05-21 18:46:37 +08005909#if !defined(HAVE_RTPSPAWN)
Victor Stinner8c62be82010-05-06 00:08:46 +00005910 if (mode == _OLD_P_OVERLAY)
5911 mode = _P_OVERLAY;
pxinwrf2d7ac72019-05-21 18:46:37 +08005912#endif
Tim Peters5aa91602002-01-30 05:46:57 +00005913
Victor Stinner8c62be82010-05-06 00:08:46 +00005914 Py_BEGIN_ALLOW_THREADS
Steve Dower654a7bd2016-09-11 20:19:32 -07005915 _Py_BEGIN_SUPPRESS_IPH
Steve Dowercc16be82016-09-08 10:35:16 -07005916#ifdef HAVE_WSPAWNV
5917 spawnval = _wspawnv(mode, path->wide, argvlist);
pxinwrf2d7ac72019-05-21 18:46:37 +08005918#elif defined(HAVE_RTPSPAWN)
5919 spawnval = _rtp_spawn(mode, path->narrow, (const char **)argvlist, NULL);
Steve Dowercc16be82016-09-08 10:35:16 -07005920#else
5921 spawnval = _spawnv(mode, path->narrow, argvlist);
5922#endif
Steve Dower654a7bd2016-09-11 20:19:32 -07005923 _Py_END_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00005924 Py_END_ALLOW_THREADS
Tim Peters5aa91602002-01-30 05:46:57 +00005925
Victor Stinner8c62be82010-05-06 00:08:46 +00005926 free_string_array(argvlist, argc);
Guido van Rossuma1065681999-01-25 23:20:23 +00005927
Victor Stinner8c62be82010-05-06 00:08:46 +00005928 if (spawnval == -1)
5929 return posix_error();
5930 else
Richard Oudkerkac0ad882013-06-05 23:29:30 +01005931 return Py_BuildValue(_Py_PARSE_INTPTR, spawnval);
Guido van Rossuma1065681999-01-25 23:20:23 +00005932}
5933
Larry Hastings2f936352014-08-05 14:04:04 +10005934/*[clinic input]
5935os.spawnve
5936
5937 mode: int
5938 Mode of process creation.
Steve Dowercc16be82016-09-08 10:35:16 -07005939 path: path_t
Larry Hastings2f936352014-08-05 14:04:04 +10005940 Path of executable file.
5941 argv: object
5942 Tuple or list of strings.
5943 env: object
5944 Dictionary of strings mapping to strings.
5945 /
5946
5947Execute the program specified by path in a new process.
5948[clinic start generated code]*/
5949
Larry Hastings2f936352014-08-05 14:04:04 +10005950static PyObject *
Steve Dowercc16be82016-09-08 10:35:16 -07005951os_spawnve_impl(PyObject *module, int mode, path_t *path, PyObject *argv,
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005952 PyObject *env)
Steve Dowercc16be82016-09-08 10:35:16 -07005953/*[clinic end generated code: output=30fe85be56fe37ad input=3e40803ee7c4c586]*/
Larry Hastings2f936352014-08-05 14:04:04 +10005954{
Steve Dowercc16be82016-09-08 10:35:16 -07005955 EXECV_CHAR **argvlist;
5956 EXECV_CHAR **envlist;
Victor Stinner8c62be82010-05-06 00:08:46 +00005957 PyObject *res = NULL;
Antoine Pitrou22e41552010-08-15 18:07:50 +00005958 Py_ssize_t argc, i, envc;
Benjamin Petersonca470632016-09-06 13:47:26 -07005959 intptr_t spawnval;
Victor Stinner8c62be82010-05-06 00:08:46 +00005960 PyObject *(*getitem)(PyObject *, Py_ssize_t);
Victor Stinnerc8d6ab22017-06-23 15:04:46 +02005961 Py_ssize_t lastarg = 0;
Guido van Rossuma1065681999-01-25 23:20:23 +00005962
Victor Stinner8c62be82010-05-06 00:08:46 +00005963 /* spawnve has four arguments: (mode, path, argv, env), where
5964 argv is a list or tuple of strings and env is a dictionary
5965 like posix.environ. */
Guido van Rossuma1065681999-01-25 23:20:23 +00005966
Victor Stinner8c62be82010-05-06 00:08:46 +00005967 if (PyList_Check(argv)) {
5968 argc = PyList_Size(argv);
5969 getitem = PyList_GetItem;
5970 }
5971 else if (PyTuple_Check(argv)) {
5972 argc = PyTuple_Size(argv);
5973 getitem = PyTuple_GetItem;
5974 }
5975 else {
5976 PyErr_SetString(PyExc_TypeError,
5977 "spawnve() arg 2 must be a tuple or list");
5978 goto fail_0;
5979 }
Steve Dower859fd7b2016-11-19 18:53:19 -08005980 if (argc == 0) {
5981 PyErr_SetString(PyExc_ValueError,
5982 "spawnve() arg 2 cannot be empty");
5983 goto fail_0;
5984 }
Victor Stinner8c62be82010-05-06 00:08:46 +00005985 if (!PyMapping_Check(env)) {
5986 PyErr_SetString(PyExc_TypeError,
5987 "spawnve() arg 3 must be a mapping object");
5988 goto fail_0;
5989 }
Guido van Rossuma1065681999-01-25 23:20:23 +00005990
Steve Dowercc16be82016-09-08 10:35:16 -07005991 argvlist = PyMem_NEW(EXECV_CHAR *, argc+1);
Victor Stinner8c62be82010-05-06 00:08:46 +00005992 if (argvlist == NULL) {
5993 PyErr_NoMemory();
5994 goto fail_0;
5995 }
5996 for (i = 0; i < argc; i++) {
5997 if (!fsconvert_strdup((*getitem)(argv, i),
5998 &argvlist[i]))
5999 {
6000 lastarg = i;
6001 goto fail_1;
6002 }
Steve Dowerbce26262016-11-19 19:17:26 -08006003 if (i == 0 && !argvlist[0][0]) {
Victor Stinnerc8d6ab22017-06-23 15:04:46 +02006004 lastarg = i + 1;
Steve Dowerbce26262016-11-19 19:17:26 -08006005 PyErr_SetString(
6006 PyExc_ValueError,
6007 "spawnv() arg 2 first element cannot be empty");
6008 goto fail_1;
6009 }
Victor Stinner8c62be82010-05-06 00:08:46 +00006010 }
6011 lastarg = argc;
6012 argvlist[argc] = NULL;
Guido van Rossuma1065681999-01-25 23:20:23 +00006013
Victor Stinner8c62be82010-05-06 00:08:46 +00006014 envlist = parse_envlist(env, &envc);
6015 if (envlist == NULL)
6016 goto fail_1;
Guido van Rossuma1065681999-01-25 23:20:23 +00006017
pxinwrf2d7ac72019-05-21 18:46:37 +08006018#if !defined(HAVE_RTPSPAWN)
Victor Stinner8c62be82010-05-06 00:08:46 +00006019 if (mode == _OLD_P_OVERLAY)
6020 mode = _P_OVERLAY;
pxinwrf2d7ac72019-05-21 18:46:37 +08006021#endif
Tim Peters25059d32001-12-07 20:35:43 +00006022
Victor Stinner8c62be82010-05-06 00:08:46 +00006023 Py_BEGIN_ALLOW_THREADS
Steve Dower654a7bd2016-09-11 20:19:32 -07006024 _Py_BEGIN_SUPPRESS_IPH
Steve Dowercc16be82016-09-08 10:35:16 -07006025#ifdef HAVE_WSPAWNV
6026 spawnval = _wspawnve(mode, path->wide, argvlist, envlist);
pxinwrf2d7ac72019-05-21 18:46:37 +08006027#elif defined(HAVE_RTPSPAWN)
6028 spawnval = _rtp_spawn(mode, path->narrow, (const char **)argvlist,
6029 (const char **)envlist);
Steve Dowercc16be82016-09-08 10:35:16 -07006030#else
6031 spawnval = _spawnve(mode, path->narrow, argvlist, envlist);
6032#endif
Steve Dower654a7bd2016-09-11 20:19:32 -07006033 _Py_END_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00006034 Py_END_ALLOW_THREADS
Tim Peters25059d32001-12-07 20:35:43 +00006035
Victor Stinner8c62be82010-05-06 00:08:46 +00006036 if (spawnval == -1)
6037 (void) posix_error();
6038 else
Richard Oudkerkac0ad882013-06-05 23:29:30 +01006039 res = Py_BuildValue(_Py_PARSE_INTPTR, spawnval);
Guido van Rossuma1065681999-01-25 23:20:23 +00006040
Victor Stinner8c62be82010-05-06 00:08:46 +00006041 while (--envc >= 0)
6042 PyMem_DEL(envlist[envc]);
6043 PyMem_DEL(envlist);
Guido van Rossum0847c5c2002-12-13 18:36:22 +00006044 fail_1:
Victor Stinnerc8d6ab22017-06-23 15:04:46 +02006045 free_string_array(argvlist, lastarg);
Martin v. Löwis114619e2002-10-07 06:44:21 +00006046 fail_0:
Victor Stinner8c62be82010-05-06 00:08:46 +00006047 return res;
Guido van Rossuma1065681999-01-25 23:20:23 +00006048}
Andrew MacIntyre69e18c92004-04-04 07:11:43 +00006049
Guido van Rossuma1065681999-01-25 23:20:23 +00006050#endif /* HAVE_SPAWNV */
6051
6052
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006053#ifdef HAVE_FORK
Gregory P. Smith163468a2017-05-29 10:03:41 -07006054
6055/* Helper function to validate arguments.
6056 Returns 0 on success. non-zero on failure with a TypeError raised.
6057 If obj is non-NULL it must be callable. */
6058static int
6059check_null_or_callable(PyObject *obj, const char* obj_name)
6060{
6061 if (obj && !PyCallable_Check(obj)) {
6062 PyErr_Format(PyExc_TypeError, "'%s' must be callable, not %s",
Eddie Elizondob3966632019-11-05 07:16:14 -08006063 obj_name, _PyType_Name(Py_TYPE(obj)));
Gregory P. Smith163468a2017-05-29 10:03:41 -07006064 return -1;
6065 }
6066 return 0;
6067}
6068
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006069/*[clinic input]
6070os.register_at_fork
6071
Gregory P. Smith163468a2017-05-29 10:03:41 -07006072 *
6073 before: object=NULL
6074 A callable to be called in the parent before the fork() syscall.
6075 after_in_child: object=NULL
6076 A callable to be called in the child after fork().
6077 after_in_parent: object=NULL
6078 A callable to be called in the parent after fork().
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006079
Gregory P. Smith163468a2017-05-29 10:03:41 -07006080Register callables to be called when forking a new process.
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006081
Gregory P. Smith163468a2017-05-29 10:03:41 -07006082'before' callbacks are called in reverse order.
6083'after_in_child' and 'after_in_parent' callbacks are called in order.
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006084
6085[clinic start generated code]*/
6086
6087static PyObject *
Gregory P. Smith163468a2017-05-29 10:03:41 -07006088os_register_at_fork_impl(PyObject *module, PyObject *before,
6089 PyObject *after_in_child, PyObject *after_in_parent)
6090/*[clinic end generated code: output=5398ac75e8e97625 input=cd1187aa85d2312e]*/
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006091{
6092 PyInterpreterState *interp;
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006093
Gregory P. Smith163468a2017-05-29 10:03:41 -07006094 if (!before && !after_in_child && !after_in_parent) {
6095 PyErr_SetString(PyExc_TypeError, "At least one argument is required.");
6096 return NULL;
6097 }
6098 if (check_null_or_callable(before, "before") ||
6099 check_null_or_callable(after_in_child, "after_in_child") ||
6100 check_null_or_callable(after_in_parent, "after_in_parent")) {
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006101 return NULL;
6102 }
Victor Stinnercaba55b2018-08-03 15:33:52 +02006103 interp = _PyInterpreterState_Get();
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006104
Gregory P. Smith163468a2017-05-29 10:03:41 -07006105 if (register_at_forker(&interp->before_forkers, before)) {
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006106 return NULL;
6107 }
Gregory P. Smith163468a2017-05-29 10:03:41 -07006108 if (register_at_forker(&interp->after_forkers_child, after_in_child)) {
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006109 return NULL;
Gregory P. Smith163468a2017-05-29 10:03:41 -07006110 }
6111 if (register_at_forker(&interp->after_forkers_parent, after_in_parent)) {
6112 return NULL;
6113 }
6114 Py_RETURN_NONE;
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006115}
6116#endif /* HAVE_FORK */
6117
6118
Guido van Rossum2242f2f2001-04-11 20:58:20 +00006119#ifdef HAVE_FORK1
Larry Hastings2f936352014-08-05 14:04:04 +10006120/*[clinic input]
6121os.fork1
6122
6123Fork a child process with a single multiplexed (i.e., not bound) thread.
6124
6125Return 0 to child process and PID of child to parent process.
6126[clinic start generated code]*/
6127
Larry Hastings2f936352014-08-05 14:04:04 +10006128static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006129os_fork1_impl(PyObject *module)
6130/*[clinic end generated code: output=0de8e67ce2a310bc input=12db02167893926e]*/
Guido van Rossum2242f2f2001-04-11 20:58:20 +00006131{
Victor Stinner8c62be82010-05-06 00:08:46 +00006132 pid_t pid;
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006133
Eric Snow59032962018-09-14 14:17:20 -07006134 if (_PyInterpreterState_Get() != PyInterpreterState_Main()) {
6135 PyErr_SetString(PyExc_RuntimeError, "fork not supported for subinterpreters");
6136 return NULL;
6137 }
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006138 PyOS_BeforeFork();
Victor Stinner8c62be82010-05-06 00:08:46 +00006139 pid = fork1();
6140 if (pid == 0) {
6141 /* child: this clobbers and resets the import lock. */
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006142 PyOS_AfterFork_Child();
Victor Stinner8c62be82010-05-06 00:08:46 +00006143 } else {
6144 /* parent: release the import lock. */
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006145 PyOS_AfterFork_Parent();
Victor Stinner8c62be82010-05-06 00:08:46 +00006146 }
6147 if (pid == -1)
6148 return posix_error();
Victor Stinner8c62be82010-05-06 00:08:46 +00006149 return PyLong_FromPid(pid);
Guido van Rossum2242f2f2001-04-11 20:58:20 +00006150}
Larry Hastings2f936352014-08-05 14:04:04 +10006151#endif /* HAVE_FORK1 */
Guido van Rossum2242f2f2001-04-11 20:58:20 +00006152
6153
Guido van Rossumad0ee831995-03-01 10:34:45 +00006154#ifdef HAVE_FORK
Larry Hastings2f936352014-08-05 14:04:04 +10006155/*[clinic input]
6156os.fork
6157
6158Fork a child process.
6159
6160Return 0 to child process and PID of child to parent process.
6161[clinic start generated code]*/
6162
Larry Hastings2f936352014-08-05 14:04:04 +10006163static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006164os_fork_impl(PyObject *module)
6165/*[clinic end generated code: output=3626c81f98985d49 input=13c956413110eeaa]*/
Guido van Rossum85e3b011991-06-03 12:42:10 +00006166{
Victor Stinner8c62be82010-05-06 00:08:46 +00006167 pid_t pid;
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006168
Eric Snow59032962018-09-14 14:17:20 -07006169 if (_PyInterpreterState_Get() != PyInterpreterState_Main()) {
6170 PyErr_SetString(PyExc_RuntimeError, "fork not supported for subinterpreters");
6171 return NULL;
6172 }
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006173 PyOS_BeforeFork();
Victor Stinner8c62be82010-05-06 00:08:46 +00006174 pid = fork();
6175 if (pid == 0) {
6176 /* child: this clobbers and resets the import lock. */
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006177 PyOS_AfterFork_Child();
Victor Stinner8c62be82010-05-06 00:08:46 +00006178 } else {
6179 /* parent: release the import lock. */
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006180 PyOS_AfterFork_Parent();
Victor Stinner8c62be82010-05-06 00:08:46 +00006181 }
6182 if (pid == -1)
6183 return posix_error();
Victor Stinner8c62be82010-05-06 00:08:46 +00006184 return PyLong_FromPid(pid);
Guido van Rossum85e3b011991-06-03 12:42:10 +00006185}
Larry Hastings2f936352014-08-05 14:04:04 +10006186#endif /* HAVE_FORK */
6187
Guido van Rossum85e3b011991-06-03 12:42:10 +00006188
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006189#ifdef HAVE_SCHED_H
Charles-François Nataliea0d5fc2011-09-06 19:03:35 +02006190#ifdef HAVE_SCHED_GET_PRIORITY_MAX
Larry Hastings2f936352014-08-05 14:04:04 +10006191/*[clinic input]
6192os.sched_get_priority_max
Charles-François Nataliea0d5fc2011-09-06 19:03:35 +02006193
Larry Hastings2f936352014-08-05 14:04:04 +10006194 policy: int
6195
6196Get the maximum scheduling priority for policy.
6197[clinic start generated code]*/
6198
Larry Hastings2f936352014-08-05 14:04:04 +10006199static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006200os_sched_get_priority_max_impl(PyObject *module, int policy)
6201/*[clinic end generated code: output=9e465c6e43130521 input=2097b7998eca6874]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006202{
6203 int max;
6204
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006205 max = sched_get_priority_max(policy);
6206 if (max < 0)
6207 return posix_error();
6208 return PyLong_FromLong(max);
6209}
6210
Larry Hastings2f936352014-08-05 14:04:04 +10006211
6212/*[clinic input]
6213os.sched_get_priority_min
6214
6215 policy: int
6216
6217Get the minimum scheduling priority for policy.
6218[clinic start generated code]*/
6219
Larry Hastings2f936352014-08-05 14:04:04 +10006220static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006221os_sched_get_priority_min_impl(PyObject *module, int policy)
6222/*[clinic end generated code: output=7595c1138cc47a6d input=21bc8fa0d70983bf]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006223{
6224 int min = sched_get_priority_min(policy);
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006225 if (min < 0)
6226 return posix_error();
6227 return PyLong_FromLong(min);
6228}
Charles-François Nataliea0d5fc2011-09-06 19:03:35 +02006229#endif /* HAVE_SCHED_GET_PRIORITY_MAX */
6230
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006231
Larry Hastings2f936352014-08-05 14:04:04 +10006232#ifdef HAVE_SCHED_SETSCHEDULER
6233/*[clinic input]
6234os.sched_getscheduler
6235 pid: pid_t
6236 /
6237
Min ho Kimc4cacc82019-07-31 08:16:13 +10006238Get the scheduling policy for the process identified by pid.
Larry Hastings2f936352014-08-05 14:04:04 +10006239
6240Passing 0 for pid returns the scheduling policy for the calling process.
6241[clinic start generated code]*/
6242
Larry Hastings2f936352014-08-05 14:04:04 +10006243static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006244os_sched_getscheduler_impl(PyObject *module, pid_t pid)
Min ho Kimc4cacc82019-07-31 08:16:13 +10006245/*[clinic end generated code: output=dce4c0bd3f1b34c8 input=8d99dac505485ac8]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006246{
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006247 int policy;
6248
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006249 policy = sched_getscheduler(pid);
6250 if (policy < 0)
6251 return posix_error();
6252 return PyLong_FromLong(policy);
6253}
Larry Hastings2f936352014-08-05 14:04:04 +10006254#endif /* HAVE_SCHED_SETSCHEDULER */
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006255
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006256
William Orr81574b82018-10-01 22:19:56 -07006257#if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
Larry Hastings2f936352014-08-05 14:04:04 +10006258/*[clinic input]
Eddie Elizondo474eedf2018-11-13 04:09:31 -08006259class os.sched_param "PyObject *" "SchedParamType"
Larry Hastings2f936352014-08-05 14:04:04 +10006260
6261@classmethod
6262os.sched_param.__new__
6263
6264 sched_priority: object
6265 A scheduling parameter.
6266
Eddie Elizondob3966632019-11-05 07:16:14 -08006267Currently has only one field: sched_priority
Larry Hastings2f936352014-08-05 14:04:04 +10006268[clinic start generated code]*/
6269
Larry Hastings2f936352014-08-05 14:04:04 +10006270static PyObject *
6271os_sched_param_impl(PyTypeObject *type, PyObject *sched_priority)
Eddie Elizondob3966632019-11-05 07:16:14 -08006272/*[clinic end generated code: output=48f4067d60f48c13 input=eb42909a2c0e3e6c]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006273{
6274 PyObject *res;
6275
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006276 res = PyStructSequence_New(type);
6277 if (!res)
6278 return NULL;
Larry Hastings2f936352014-08-05 14:04:04 +10006279 Py_INCREF(sched_priority);
6280 PyStructSequence_SET_ITEM(res, 0, sched_priority);
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006281 return res;
6282}
6283
Serhiy Storchaka1009bf12015-04-03 23:53:51 +03006284PyDoc_VAR(os_sched_param__doc__);
6285
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006286static PyStructSequence_Field sched_param_fields[] = {
6287 {"sched_priority", "the scheduling priority"},
6288 {0}
6289};
6290
6291static PyStructSequence_Desc sched_param_desc = {
6292 "sched_param", /* name */
Larry Hastings2f936352014-08-05 14:04:04 +10006293 os_sched_param__doc__, /* doc */
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006294 sched_param_fields,
6295 1
6296};
6297
6298static int
6299convert_sched_param(PyObject *param, struct sched_param *res)
6300{
6301 long priority;
6302
Eddie Elizondob3966632019-11-05 07:16:14 -08006303 PyObject *SchedParamType = _posixstate_global->SchedParamType;
6304 if (Py_TYPE(param) != (PyTypeObject *)SchedParamType) {
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006305 PyErr_SetString(PyExc_TypeError, "must have a sched_param object");
6306 return 0;
6307 }
6308 priority = PyLong_AsLong(PyStructSequence_GET_ITEM(param, 0));
6309 if (priority == -1 && PyErr_Occurred())
6310 return 0;
6311 if (priority > INT_MAX || priority < INT_MIN) {
6312 PyErr_SetString(PyExc_OverflowError, "sched_priority out of range");
6313 return 0;
6314 }
6315 res->sched_priority = Py_SAFE_DOWNCAST(priority, long, int);
6316 return 1;
6317}
William Orr81574b82018-10-01 22:19:56 -07006318#endif /* defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM) */
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006319
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006320
6321#ifdef HAVE_SCHED_SETSCHEDULER
Larry Hastings2f936352014-08-05 14:04:04 +10006322/*[clinic input]
6323os.sched_setscheduler
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006324
Larry Hastings2f936352014-08-05 14:04:04 +10006325 pid: pid_t
6326 policy: int
6327 param: sched_param
6328 /
6329
6330Set the scheduling policy for the process identified by pid.
6331
6332If pid is 0, the calling process is changed.
6333param is an instance of sched_param.
6334[clinic start generated code]*/
6335
Larry Hastings2f936352014-08-05 14:04:04 +10006336static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006337os_sched_setscheduler_impl(PyObject *module, pid_t pid, int policy,
Larry Hastings89964c42015-04-14 18:07:59 -04006338 struct sched_param *param)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006339/*[clinic end generated code: output=b0ac0a70d3b1d705 input=c581f9469a5327dd]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006340{
Jesus Cea9c822272011-09-10 01:40:52 +02006341 /*
Jesus Cea54b01492011-09-10 01:53:19 +02006342 ** sched_setscheduler() returns 0 in Linux, but the previous
6343 ** scheduling policy under Solaris/Illumos, and others.
6344 ** On error, -1 is returned in all Operating Systems.
Jesus Cea9c822272011-09-10 01:40:52 +02006345 */
Larry Hastings2f936352014-08-05 14:04:04 +10006346 if (sched_setscheduler(pid, policy, param) == -1)
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006347 return posix_error();
6348 Py_RETURN_NONE;
6349}
Larry Hastings2f936352014-08-05 14:04:04 +10006350#endif /* HAVE_SCHED_SETSCHEDULER*/
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006351
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006352
6353#ifdef HAVE_SCHED_SETPARAM
Larry Hastings2f936352014-08-05 14:04:04 +10006354/*[clinic input]
6355os.sched_getparam
6356 pid: pid_t
6357 /
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006358
Larry Hastings2f936352014-08-05 14:04:04 +10006359Returns scheduling parameters for the process identified by pid.
6360
6361If pid is 0, returns parameters for the calling process.
6362Return value is an instance of sched_param.
6363[clinic start generated code]*/
6364
Larry Hastings2f936352014-08-05 14:04:04 +10006365static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006366os_sched_getparam_impl(PyObject *module, pid_t pid)
6367/*[clinic end generated code: output=b194e8708dcf2db8 input=18a1ef9c2efae296]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006368{
6369 struct sched_param param;
6370 PyObject *result;
6371 PyObject *priority;
6372
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006373 if (sched_getparam(pid, &param))
6374 return posix_error();
Eddie Elizondob3966632019-11-05 07:16:14 -08006375 PyObject *SchedParamType = _posixstate_global->SchedParamType;
6376 result = PyStructSequence_New((PyTypeObject *)SchedParamType);
Larry Hastings2f936352014-08-05 14:04:04 +10006377 if (!result)
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006378 return NULL;
6379 priority = PyLong_FromLong(param.sched_priority);
6380 if (!priority) {
Larry Hastings2f936352014-08-05 14:04:04 +10006381 Py_DECREF(result);
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006382 return NULL;
6383 }
Larry Hastings2f936352014-08-05 14:04:04 +10006384 PyStructSequence_SET_ITEM(result, 0, priority);
6385 return result;
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006386}
6387
Larry Hastings2f936352014-08-05 14:04:04 +10006388
6389/*[clinic input]
6390os.sched_setparam
6391 pid: pid_t
6392 param: sched_param
6393 /
6394
6395Set scheduling parameters for the process identified by pid.
6396
6397If pid is 0, sets parameters for the calling process.
6398param should be an instance of sched_param.
6399[clinic start generated code]*/
6400
Larry Hastings2f936352014-08-05 14:04:04 +10006401static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006402os_sched_setparam_impl(PyObject *module, pid_t pid,
Larry Hastings89964c42015-04-14 18:07:59 -04006403 struct sched_param *param)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006404/*[clinic end generated code: output=8af013f78a32b591 input=6b8d6dfcecdc21bd]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006405{
6406 if (sched_setparam(pid, param))
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006407 return posix_error();
6408 Py_RETURN_NONE;
6409}
Larry Hastings2f936352014-08-05 14:04:04 +10006410#endif /* HAVE_SCHED_SETPARAM */
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006411
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006412
6413#ifdef HAVE_SCHED_RR_GET_INTERVAL
Larry Hastings2f936352014-08-05 14:04:04 +10006414/*[clinic input]
6415os.sched_rr_get_interval -> double
6416 pid: pid_t
6417 /
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006418
Larry Hastings2f936352014-08-05 14:04:04 +10006419Return the round-robin quantum for the process identified by pid, in seconds.
6420
6421Value returned is a float.
6422[clinic start generated code]*/
6423
Larry Hastings2f936352014-08-05 14:04:04 +10006424static double
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006425os_sched_rr_get_interval_impl(PyObject *module, pid_t pid)
6426/*[clinic end generated code: output=7e2d935833ab47dc input=2a973da15cca6fae]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006427{
6428 struct timespec interval;
6429 if (sched_rr_get_interval(pid, &interval)) {
6430 posix_error();
6431 return -1.0;
6432 }
Gregory P. Smith1d300ce2018-12-30 21:13:02 -08006433#ifdef _Py_MEMORY_SANITIZER
6434 __msan_unpoison(&interval, sizeof(interval));
6435#endif
Larry Hastings2f936352014-08-05 14:04:04 +10006436 return (double)interval.tv_sec + 1e-9*interval.tv_nsec;
6437}
6438#endif /* HAVE_SCHED_RR_GET_INTERVAL */
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006439
Larry Hastings2f936352014-08-05 14:04:04 +10006440
6441/*[clinic input]
6442os.sched_yield
6443
6444Voluntarily relinquish the CPU.
6445[clinic start generated code]*/
6446
Larry Hastings2f936352014-08-05 14:04:04 +10006447static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006448os_sched_yield_impl(PyObject *module)
6449/*[clinic end generated code: output=902323500f222cac input=e54d6f98189391d4]*/
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006450{
6451 if (sched_yield())
6452 return posix_error();
6453 Py_RETURN_NONE;
6454}
6455
Benjamin Peterson2740af82011-08-02 17:41:34 -05006456#ifdef HAVE_SCHED_SETAFFINITY
Antoine Pitrou84869872012-08-04 16:16:35 +02006457/* The minimum number of CPUs allocated in a cpu_set_t */
6458static const int NCPUS_START = sizeof(unsigned long) * CHAR_BIT;
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006459
Larry Hastings2f936352014-08-05 14:04:04 +10006460/*[clinic input]
6461os.sched_setaffinity
6462 pid: pid_t
6463 mask : object
6464 /
6465
6466Set the CPU affinity of the process identified by pid to mask.
6467
6468mask should be an iterable of integers identifying CPUs.
6469[clinic start generated code]*/
6470
Larry Hastings2f936352014-08-05 14:04:04 +10006471static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006472os_sched_setaffinity_impl(PyObject *module, pid_t pid, PyObject *mask)
6473/*[clinic end generated code: output=882d7dd9a229335b input=a0791a597c7085ba]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006474{
Antoine Pitrou84869872012-08-04 16:16:35 +02006475 int ncpus;
6476 size_t setsize;
Larry Hastings2f936352014-08-05 14:04:04 +10006477 cpu_set_t *cpu_set = NULL;
6478 PyObject *iterator = NULL, *item;
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006479
Larry Hastings2f936352014-08-05 14:04:04 +10006480 iterator = PyObject_GetIter(mask);
Antoine Pitrou84869872012-08-04 16:16:35 +02006481 if (iterator == NULL)
6482 return NULL;
6483
6484 ncpus = NCPUS_START;
6485 setsize = CPU_ALLOC_SIZE(ncpus);
Larry Hastings2f936352014-08-05 14:04:04 +10006486 cpu_set = CPU_ALLOC(ncpus);
6487 if (cpu_set == NULL) {
Antoine Pitrou84869872012-08-04 16:16:35 +02006488 PyErr_NoMemory();
6489 goto error;
6490 }
Larry Hastings2f936352014-08-05 14:04:04 +10006491 CPU_ZERO_S(setsize, cpu_set);
Antoine Pitrou84869872012-08-04 16:16:35 +02006492
6493 while ((item = PyIter_Next(iterator))) {
6494 long cpu;
6495 if (!PyLong_Check(item)) {
6496 PyErr_Format(PyExc_TypeError,
6497 "expected an iterator of ints, "
6498 "but iterator yielded %R",
6499 Py_TYPE(item));
6500 Py_DECREF(item);
6501 goto error;
6502 }
6503 cpu = PyLong_AsLong(item);
6504 Py_DECREF(item);
6505 if (cpu < 0) {
6506 if (!PyErr_Occurred())
6507 PyErr_SetString(PyExc_ValueError, "negative CPU number");
6508 goto error;
6509 }
6510 if (cpu > INT_MAX - 1) {
6511 PyErr_SetString(PyExc_OverflowError, "CPU number too large");
6512 goto error;
6513 }
6514 if (cpu >= ncpus) {
6515 /* Grow CPU mask to fit the CPU number */
6516 int newncpus = ncpus;
6517 cpu_set_t *newmask;
6518 size_t newsetsize;
6519 while (newncpus <= cpu) {
6520 if (newncpus > INT_MAX / 2)
6521 newncpus = cpu + 1;
6522 else
6523 newncpus = newncpus * 2;
6524 }
6525 newmask = CPU_ALLOC(newncpus);
6526 if (newmask == NULL) {
6527 PyErr_NoMemory();
6528 goto error;
6529 }
6530 newsetsize = CPU_ALLOC_SIZE(newncpus);
6531 CPU_ZERO_S(newsetsize, newmask);
Larry Hastings2f936352014-08-05 14:04:04 +10006532 memcpy(newmask, cpu_set, setsize);
6533 CPU_FREE(cpu_set);
Antoine Pitrou84869872012-08-04 16:16:35 +02006534 setsize = newsetsize;
Larry Hastings2f936352014-08-05 14:04:04 +10006535 cpu_set = newmask;
Antoine Pitrou84869872012-08-04 16:16:35 +02006536 ncpus = newncpus;
6537 }
Larry Hastings2f936352014-08-05 14:04:04 +10006538 CPU_SET_S(cpu, setsize, cpu_set);
Antoine Pitrou84869872012-08-04 16:16:35 +02006539 }
Brandt Bucher45a30af2019-06-27 09:10:57 -07006540 if (PyErr_Occurred()) {
6541 goto error;
6542 }
Antoine Pitrou84869872012-08-04 16:16:35 +02006543 Py_CLEAR(iterator);
6544
Larry Hastings2f936352014-08-05 14:04:04 +10006545 if (sched_setaffinity(pid, setsize, cpu_set)) {
Antoine Pitrou84869872012-08-04 16:16:35 +02006546 posix_error();
6547 goto error;
6548 }
Larry Hastings2f936352014-08-05 14:04:04 +10006549 CPU_FREE(cpu_set);
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006550 Py_RETURN_NONE;
Antoine Pitrou84869872012-08-04 16:16:35 +02006551
6552error:
Larry Hastings2f936352014-08-05 14:04:04 +10006553 if (cpu_set)
6554 CPU_FREE(cpu_set);
Antoine Pitrou84869872012-08-04 16:16:35 +02006555 Py_XDECREF(iterator);
6556 return NULL;
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006557}
6558
Larry Hastings2f936352014-08-05 14:04:04 +10006559
6560/*[clinic input]
6561os.sched_getaffinity
6562 pid: pid_t
6563 /
6564
Charles-François Natalidc87e4b2015-07-13 21:01:39 +01006565Return the affinity of the process identified by pid (or the current process if zero).
Larry Hastings2f936352014-08-05 14:04:04 +10006566
6567The affinity is returned as a set of CPU identifiers.
6568[clinic start generated code]*/
6569
Larry Hastings2f936352014-08-05 14:04:04 +10006570static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006571os_sched_getaffinity_impl(PyObject *module, pid_t pid)
Serhiy Storchaka2954f832016-07-07 18:20:03 +03006572/*[clinic end generated code: output=f726f2c193c17a4f input=983ce7cb4a565980]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006573{
Antoine Pitrou84869872012-08-04 16:16:35 +02006574 int cpu, ncpus, count;
6575 size_t setsize;
6576 cpu_set_t *mask = NULL;
6577 PyObject *res = NULL;
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006578
Antoine Pitrou84869872012-08-04 16:16:35 +02006579 ncpus = NCPUS_START;
6580 while (1) {
6581 setsize = CPU_ALLOC_SIZE(ncpus);
6582 mask = CPU_ALLOC(ncpus);
6583 if (mask == NULL)
6584 return PyErr_NoMemory();
6585 if (sched_getaffinity(pid, setsize, mask) == 0)
6586 break;
6587 CPU_FREE(mask);
6588 if (errno != EINVAL)
6589 return posix_error();
6590 if (ncpus > INT_MAX / 2) {
6591 PyErr_SetString(PyExc_OverflowError, "could not allocate "
6592 "a large enough CPU set");
6593 return NULL;
6594 }
6595 ncpus = ncpus * 2;
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006596 }
Antoine Pitrou84869872012-08-04 16:16:35 +02006597
6598 res = PySet_New(NULL);
6599 if (res == NULL)
6600 goto error;
6601 for (cpu = 0, count = CPU_COUNT_S(setsize, mask); count; cpu++) {
6602 if (CPU_ISSET_S(cpu, setsize, mask)) {
6603 PyObject *cpu_num = PyLong_FromLong(cpu);
6604 --count;
6605 if (cpu_num == NULL)
6606 goto error;
6607 if (PySet_Add(res, cpu_num)) {
6608 Py_DECREF(cpu_num);
6609 goto error;
6610 }
6611 Py_DECREF(cpu_num);
6612 }
6613 }
6614 CPU_FREE(mask);
6615 return res;
6616
6617error:
6618 if (mask)
6619 CPU_FREE(mask);
6620 Py_XDECREF(res);
6621 return NULL;
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006622}
6623
Benjamin Peterson2740af82011-08-02 17:41:34 -05006624#endif /* HAVE_SCHED_SETAFFINITY */
6625
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006626#endif /* HAVE_SCHED_H */
6627
Larry Hastings2f936352014-08-05 14:04:04 +10006628
Neal Norwitzb59798b2003-03-21 01:43:31 +00006629/* AIX uses /dev/ptc but is otherwise the same as /dev/ptmx */
Neal Norwitz2deaddb2003-03-21 03:08:31 +00006630/* IRIX has both /dev/ptc and /dev/ptmx, use ptmx */
6631#if defined(HAVE_DEV_PTC) && !defined(HAVE_DEV_PTMX)
Neal Norwitzb59798b2003-03-21 01:43:31 +00006632#define DEV_PTY_FILE "/dev/ptc"
6633#define HAVE_DEV_PTMX
6634#else
6635#define DEV_PTY_FILE "/dev/ptmx"
6636#endif
6637
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006638#if defined(HAVE_OPENPTY) || defined(HAVE_FORKPTY) || defined(HAVE_DEV_PTMX)
Fred Drake8cef4cf2000-06-28 16:40:38 +00006639#ifdef HAVE_PTY_H
6640#include <pty.h>
6641#else
6642#ifdef HAVE_LIBUTIL_H
6643#include <libutil.h>
Ronald Oussoren755740f2010-02-07 19:56:39 +00006644#else
6645#ifdef HAVE_UTIL_H
6646#include <util.h>
6647#endif /* HAVE_UTIL_H */
Fred Drake8cef4cf2000-06-28 16:40:38 +00006648#endif /* HAVE_LIBUTIL_H */
6649#endif /* HAVE_PTY_H */
Martin v. Löwis14e73b12003-01-01 09:51:12 +00006650#ifdef HAVE_STROPTS_H
6651#include <stropts.h>
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006652#endif
ngie-eign7745ec42018-02-14 11:54:28 -08006653#endif /* defined(HAVE_OPENPTY) || defined(HAVE_FORKPTY) || defined(HAVE_DEV_PTMX) */
Fred Drake8cef4cf2000-06-28 16:40:38 +00006654
Larry Hastings2f936352014-08-05 14:04:04 +10006655
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006656#if defined(HAVE_OPENPTY) || defined(HAVE__GETPTY) || defined(HAVE_DEV_PTMX)
Larry Hastings2f936352014-08-05 14:04:04 +10006657/*[clinic input]
6658os.openpty
6659
6660Open a pseudo-terminal.
6661
6662Return a tuple of (master_fd, slave_fd) containing open file descriptors
6663for both the master and slave ends.
6664[clinic start generated code]*/
6665
Larry Hastings2f936352014-08-05 14:04:04 +10006666static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006667os_openpty_impl(PyObject *module)
6668/*[clinic end generated code: output=98841ce5ec9cef3c input=f3d99fd99e762907]*/
Fred Drake8cef4cf2000-06-28 16:40:38 +00006669{
Victor Stinnerdaf45552013-08-28 00:53:59 +02006670 int master_fd = -1, slave_fd = -1;
Thomas Wouters70c21a12000-07-14 14:28:33 +00006671#ifndef HAVE_OPENPTY
Victor Stinner8c62be82010-05-06 00:08:46 +00006672 char * slave_name;
Thomas Wouters70c21a12000-07-14 14:28:33 +00006673#endif
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006674#if defined(HAVE_DEV_PTMX) && !defined(HAVE_OPENPTY) && !defined(HAVE__GETPTY)
Victor Stinner8c62be82010-05-06 00:08:46 +00006675 PyOS_sighandler_t sig_saved;
Jakub Kulík6f9bc722018-12-31 03:16:40 +01006676#if defined(__sun) && defined(__SVR4)
Victor Stinner8c62be82010-05-06 00:08:46 +00006677 extern char *ptsname(int fildes);
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006678#endif
6679#endif
Thomas Wouters70c21a12000-07-14 14:28:33 +00006680
Thomas Wouters70c21a12000-07-14 14:28:33 +00006681#ifdef HAVE_OPENPTY
Victor Stinner8c62be82010-05-06 00:08:46 +00006682 if (openpty(&master_fd, &slave_fd, NULL, NULL, NULL) != 0)
Victor Stinnerdaf45552013-08-28 00:53:59 +02006683 goto posix_error;
6684
6685 if (_Py_set_inheritable(master_fd, 0, NULL) < 0)
6686 goto error;
6687 if (_Py_set_inheritable(slave_fd, 0, NULL) < 0)
6688 goto error;
6689
Neal Norwitzb59798b2003-03-21 01:43:31 +00006690#elif defined(HAVE__GETPTY)
Victor Stinner8c62be82010-05-06 00:08:46 +00006691 slave_name = _getpty(&master_fd, O_RDWR, 0666, 0);
6692 if (slave_name == NULL)
Victor Stinnerdaf45552013-08-28 00:53:59 +02006693 goto posix_error;
6694 if (_Py_set_inheritable(master_fd, 0, NULL) < 0)
6695 goto error;
Thomas Wouters70c21a12000-07-14 14:28:33 +00006696
Victor Stinnerdaf45552013-08-28 00:53:59 +02006697 slave_fd = _Py_open(slave_name, O_RDWR);
Victor Stinner8c62be82010-05-06 00:08:46 +00006698 if (slave_fd < 0)
Victor Stinnera555cfc2015-03-18 00:22:14 +01006699 goto error;
Victor Stinnerdaf45552013-08-28 00:53:59 +02006700
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006701#else
Victor Stinner000de532013-11-25 23:19:58 +01006702 master_fd = open(DEV_PTY_FILE, O_RDWR | O_NOCTTY); /* open master */
Victor Stinner8c62be82010-05-06 00:08:46 +00006703 if (master_fd < 0)
Victor Stinnerdaf45552013-08-28 00:53:59 +02006704 goto posix_error;
6705
Victor Stinner8c62be82010-05-06 00:08:46 +00006706 sig_saved = PyOS_setsig(SIGCHLD, SIG_DFL);
Victor Stinnerdaf45552013-08-28 00:53:59 +02006707
Victor Stinner8c62be82010-05-06 00:08:46 +00006708 /* change permission of slave */
6709 if (grantpt(master_fd) < 0) {
6710 PyOS_setsig(SIGCHLD, sig_saved);
Victor Stinnerdaf45552013-08-28 00:53:59 +02006711 goto posix_error;
Victor Stinner8c62be82010-05-06 00:08:46 +00006712 }
Victor Stinnerdaf45552013-08-28 00:53:59 +02006713
Victor Stinner8c62be82010-05-06 00:08:46 +00006714 /* unlock slave */
6715 if (unlockpt(master_fd) < 0) {
6716 PyOS_setsig(SIGCHLD, sig_saved);
Victor Stinnerdaf45552013-08-28 00:53:59 +02006717 goto posix_error;
Victor Stinner8c62be82010-05-06 00:08:46 +00006718 }
Victor Stinnerdaf45552013-08-28 00:53:59 +02006719
Victor Stinner8c62be82010-05-06 00:08:46 +00006720 PyOS_setsig(SIGCHLD, sig_saved);
Victor Stinnerdaf45552013-08-28 00:53:59 +02006721
Victor Stinner8c62be82010-05-06 00:08:46 +00006722 slave_name = ptsname(master_fd); /* get name of slave */
6723 if (slave_name == NULL)
Victor Stinnerdaf45552013-08-28 00:53:59 +02006724 goto posix_error;
6725
6726 slave_fd = _Py_open(slave_name, O_RDWR | O_NOCTTY); /* open slave */
Victor Stinnera555cfc2015-03-18 00:22:14 +01006727 if (slave_fd == -1)
6728 goto error;
Victor Stinner000de532013-11-25 23:19:58 +01006729
6730 if (_Py_set_inheritable(master_fd, 0, NULL) < 0)
6731 goto posix_error;
6732
Stefan Krahfb7c8ae2016-04-26 17:04:18 +02006733#if !defined(__CYGWIN__) && !defined(__ANDROID__) && !defined(HAVE_DEV_PTC)
Victor Stinner8c62be82010-05-06 00:08:46 +00006734 ioctl(slave_fd, I_PUSH, "ptem"); /* push ptem */
6735 ioctl(slave_fd, I_PUSH, "ldterm"); /* push ldterm */
Neal Norwitz6700e472002-12-31 16:16:07 +00006736#ifndef __hpux
Victor Stinner8c62be82010-05-06 00:08:46 +00006737 ioctl(slave_fd, I_PUSH, "ttcompat"); /* push ttcompat */
Neal Norwitz6700e472002-12-31 16:16:07 +00006738#endif /* __hpux */
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006739#endif /* HAVE_CYGWIN */
Thomas Wouters1e0c2f42000-07-24 16:06:23 +00006740#endif /* HAVE_OPENPTY */
Thomas Wouters70c21a12000-07-14 14:28:33 +00006741
Victor Stinner8c62be82010-05-06 00:08:46 +00006742 return Py_BuildValue("(ii)", master_fd, slave_fd);
Thomas Wouters70c21a12000-07-14 14:28:33 +00006743
Victor Stinnerdaf45552013-08-28 00:53:59 +02006744posix_error:
6745 posix_error();
6746error:
6747 if (master_fd != -1)
6748 close(master_fd);
6749 if (slave_fd != -1)
6750 close(slave_fd);
6751 return NULL;
Fred Drake8cef4cf2000-06-28 16:40:38 +00006752}
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006753#endif /* defined(HAVE_OPENPTY) || defined(HAVE__GETPTY) || defined(HAVE_DEV_PTMX) */
Fred Drake8cef4cf2000-06-28 16:40:38 +00006754
Larry Hastings2f936352014-08-05 14:04:04 +10006755
Fred Drake8cef4cf2000-06-28 16:40:38 +00006756#ifdef HAVE_FORKPTY
Larry Hastings2f936352014-08-05 14:04:04 +10006757/*[clinic input]
6758os.forkpty
6759
6760Fork a new process with a new pseudo-terminal as controlling tty.
6761
6762Returns a tuple of (pid, master_fd).
6763Like fork(), return pid of 0 to the child process,
6764and pid of child to the parent process.
6765To both, return fd of newly opened pseudo-terminal.
6766[clinic start generated code]*/
6767
Larry Hastings2f936352014-08-05 14:04:04 +10006768static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006769os_forkpty_impl(PyObject *module)
6770/*[clinic end generated code: output=60d0a5c7512e4087 input=f1f7f4bae3966010]*/
Fred Drake8cef4cf2000-06-28 16:40:38 +00006771{
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006772 int master_fd = -1;
Victor Stinner8c62be82010-05-06 00:08:46 +00006773 pid_t pid;
Tim Peters5aa91602002-01-30 05:46:57 +00006774
Eric Snow59032962018-09-14 14:17:20 -07006775 if (_PyInterpreterState_Get() != PyInterpreterState_Main()) {
6776 PyErr_SetString(PyExc_RuntimeError, "fork not supported for subinterpreters");
6777 return NULL;
6778 }
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006779 PyOS_BeforeFork();
Victor Stinner8c62be82010-05-06 00:08:46 +00006780 pid = forkpty(&master_fd, NULL, NULL, NULL);
6781 if (pid == 0) {
6782 /* child: this clobbers and resets the import lock. */
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006783 PyOS_AfterFork_Child();
Victor Stinner8c62be82010-05-06 00:08:46 +00006784 } else {
6785 /* parent: release the import lock. */
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006786 PyOS_AfterFork_Parent();
Victor Stinner8c62be82010-05-06 00:08:46 +00006787 }
6788 if (pid == -1)
6789 return posix_error();
Victor Stinner8c62be82010-05-06 00:08:46 +00006790 return Py_BuildValue("(Ni)", PyLong_FromPid(pid), master_fd);
Fred Drake8cef4cf2000-06-28 16:40:38 +00006791}
Larry Hastings2f936352014-08-05 14:04:04 +10006792#endif /* HAVE_FORKPTY */
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00006793
Ross Lagerwall7807c352011-03-17 20:20:30 +02006794
Guido van Rossumad0ee831995-03-01 10:34:45 +00006795#ifdef HAVE_GETEGID
Larry Hastings2f936352014-08-05 14:04:04 +10006796/*[clinic input]
6797os.getegid
6798
6799Return the current process's effective group id.
6800[clinic start generated code]*/
6801
Larry Hastings2f936352014-08-05 14:04:04 +10006802static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006803os_getegid_impl(PyObject *module)
6804/*[clinic end generated code: output=67d9be7ac68898a2 input=1596f79ad1107d5d]*/
Guido van Rossum46003ff1992-05-15 11:05:24 +00006805{
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02006806 return _PyLong_FromGid(getegid());
Guido van Rossum46003ff1992-05-15 11:05:24 +00006807}
Larry Hastings2f936352014-08-05 14:04:04 +10006808#endif /* HAVE_GETEGID */
Guido van Rossum46003ff1992-05-15 11:05:24 +00006809
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00006810
Guido van Rossumad0ee831995-03-01 10:34:45 +00006811#ifdef HAVE_GETEUID
Larry Hastings2f936352014-08-05 14:04:04 +10006812/*[clinic input]
6813os.geteuid
6814
6815Return the current process's effective user id.
6816[clinic start generated code]*/
6817
Larry Hastings2f936352014-08-05 14:04:04 +10006818static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006819os_geteuid_impl(PyObject *module)
6820/*[clinic end generated code: output=ea1b60f0d6abb66e input=4644c662d3bd9f19]*/
Guido van Rossum46003ff1992-05-15 11:05:24 +00006821{
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02006822 return _PyLong_FromUid(geteuid());
Guido van Rossum46003ff1992-05-15 11:05:24 +00006823}
Larry Hastings2f936352014-08-05 14:04:04 +10006824#endif /* HAVE_GETEUID */
Guido van Rossum46003ff1992-05-15 11:05:24 +00006825
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00006826
Guido van Rossumad0ee831995-03-01 10:34:45 +00006827#ifdef HAVE_GETGID
Larry Hastings2f936352014-08-05 14:04:04 +10006828/*[clinic input]
6829os.getgid
6830
6831Return the current process's group id.
6832[clinic start generated code]*/
6833
Larry Hastings2f936352014-08-05 14:04:04 +10006834static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006835os_getgid_impl(PyObject *module)
6836/*[clinic end generated code: output=4f28ebc9d3e5dfcf input=58796344cd87c0f6]*/
Guido van Rossum46003ff1992-05-15 11:05:24 +00006837{
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02006838 return _PyLong_FromGid(getgid());
Guido van Rossum46003ff1992-05-15 11:05:24 +00006839}
Larry Hastings2f936352014-08-05 14:04:04 +10006840#endif /* HAVE_GETGID */
Guido van Rossum46003ff1992-05-15 11:05:24 +00006841
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00006842
Berker Peksag39404992016-09-15 20:45:16 +03006843#ifdef HAVE_GETPID
Larry Hastings2f936352014-08-05 14:04:04 +10006844/*[clinic input]
6845os.getpid
6846
6847Return the current process id.
6848[clinic start generated code]*/
6849
Larry Hastings2f936352014-08-05 14:04:04 +10006850static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006851os_getpid_impl(PyObject *module)
6852/*[clinic end generated code: output=9ea6fdac01ed2b3c input=5a9a00f0ab68aa00]*/
Guido van Rossum85e3b011991-06-03 12:42:10 +00006853{
Victor Stinner8c62be82010-05-06 00:08:46 +00006854 return PyLong_FromPid(getpid());
Guido van Rossum85e3b011991-06-03 12:42:10 +00006855}
Berker Peksag39404992016-09-15 20:45:16 +03006856#endif /* HAVE_GETPID */
Guido van Rossum85e3b011991-06-03 12:42:10 +00006857
Jeffrey Kintscher8725c832019-06-13 00:01:29 -07006858#ifdef NGROUPS_MAX
6859#define MAX_GROUPS NGROUPS_MAX
6860#else
6861 /* defined to be 16 on Solaris7, so this should be a small number */
6862#define MAX_GROUPS 64
6863#endif
6864
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006865#ifdef HAVE_GETGROUPLIST
Larry Hastings2f936352014-08-05 14:04:04 +10006866
6867/* AC 3.5: funny apple logic below */
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006868PyDoc_STRVAR(posix_getgrouplist__doc__,
6869"getgrouplist(user, group) -> list of groups to which a user belongs\n\n\
6870Returns a list of groups to which a user belongs.\n\n\
6871 user: username to lookup\n\
6872 group: base group id of the user");
6873
6874static PyObject *
6875posix_getgrouplist(PyObject *self, PyObject *args)
6876{
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006877 const char *user;
6878 int i, ngroups;
6879 PyObject *list;
6880#ifdef __APPLE__
6881 int *groups, basegid;
6882#else
6883 gid_t *groups, basegid;
6884#endif
Jeffrey Kintscher8725c832019-06-13 00:01:29 -07006885
6886 /*
6887 * NGROUPS_MAX is defined by POSIX.1 as the maximum
6888 * number of supplimental groups a users can belong to.
6889 * We have to increment it by one because
6890 * getgrouplist() returns both the supplemental groups
6891 * and the primary group, i.e. all of the groups the
6892 * user belongs to.
6893 */
6894 ngroups = 1 + MAX_GROUPS;
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006895
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02006896#ifdef __APPLE__
6897 if (!PyArg_ParseTuple(args, "si:getgrouplist", &user, &basegid))
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006898 return NULL;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02006899#else
6900 if (!PyArg_ParseTuple(args, "sO&:getgrouplist", &user,
6901 _Py_Gid_Converter, &basegid))
6902 return NULL;
6903#endif
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006904
6905#ifdef __APPLE__
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02006906 groups = PyMem_New(int, ngroups);
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006907#else
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02006908 groups = PyMem_New(gid_t, ngroups);
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006909#endif
6910 if (groups == NULL)
6911 return PyErr_NoMemory();
6912
6913 if (getgrouplist(user, basegid, groups, &ngroups) == -1) {
6914 PyMem_Del(groups);
6915 return posix_error();
6916 }
6917
Gregory P. Smith1d300ce2018-12-30 21:13:02 -08006918#ifdef _Py_MEMORY_SANITIZER
6919 /* Clang memory sanitizer libc intercepts don't know getgrouplist. */
6920 __msan_unpoison(&ngroups, sizeof(ngroups));
6921 __msan_unpoison(groups, ngroups*sizeof(*groups));
6922#endif
6923
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006924 list = PyList_New(ngroups);
6925 if (list == NULL) {
6926 PyMem_Del(groups);
6927 return NULL;
6928 }
6929
6930 for (i = 0; i < ngroups; i++) {
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02006931#ifdef __APPLE__
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006932 PyObject *o = PyLong_FromUnsignedLong((unsigned long)groups[i]);
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02006933#else
6934 PyObject *o = _PyLong_FromGid(groups[i]);
6935#endif
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006936 if (o == NULL) {
6937 Py_DECREF(list);
6938 PyMem_Del(groups);
6939 return NULL;
6940 }
6941 PyList_SET_ITEM(list, i, o);
6942 }
6943
6944 PyMem_Del(groups);
6945
6946 return list;
6947}
Larry Hastings2f936352014-08-05 14:04:04 +10006948#endif /* HAVE_GETGROUPLIST */
6949
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00006950
Fred Drakec9680921999-12-13 16:37:25 +00006951#ifdef HAVE_GETGROUPS
Larry Hastings2f936352014-08-05 14:04:04 +10006952/*[clinic input]
6953os.getgroups
6954
6955Return list of supplemental group IDs for the process.
6956[clinic start generated code]*/
6957
Larry Hastings2f936352014-08-05 14:04:04 +10006958static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006959os_getgroups_impl(PyObject *module)
6960/*[clinic end generated code: output=42b0c17758561b56 input=d3f109412e6a155c]*/
Fred Drakec9680921999-12-13 16:37:25 +00006961{
6962 PyObject *result = NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00006963 gid_t grouplist[MAX_GROUPS];
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00006964
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00006965 /* On MacOSX getgroups(2) can return more than MAX_GROUPS results
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00006966 * This is a helper variable to store the intermediate result when
6967 * that happens.
6968 *
6969 * To keep the code readable the OSX behaviour is unconditional,
6970 * according to the POSIX spec this should be safe on all unix-y
6971 * systems.
6972 */
6973 gid_t* alt_grouplist = grouplist;
Victor Stinner8c62be82010-05-06 00:08:46 +00006974 int n;
Fred Drakec9680921999-12-13 16:37:25 +00006975
Ned Deilyb5dd6d22013-08-01 21:21:15 -07006976#ifdef __APPLE__
6977 /* Issue #17557: As of OS X 10.8, getgroups(2) no longer raises EINVAL if
6978 * there are more groups than can fit in grouplist. Therefore, on OS X
6979 * always first call getgroups with length 0 to get the actual number
6980 * of groups.
6981 */
6982 n = getgroups(0, NULL);
6983 if (n < 0) {
6984 return posix_error();
6985 } else if (n <= MAX_GROUPS) {
6986 /* groups will fit in existing array */
6987 alt_grouplist = grouplist;
6988 } else {
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02006989 alt_grouplist = PyMem_New(gid_t, n);
Ned Deilyb5dd6d22013-08-01 21:21:15 -07006990 if (alt_grouplist == NULL) {
Zackery Spytz4c49da02018-12-07 03:11:30 -07006991 return PyErr_NoMemory();
Ned Deilyb5dd6d22013-08-01 21:21:15 -07006992 }
6993 }
6994
6995 n = getgroups(n, alt_grouplist);
6996 if (n == -1) {
6997 if (alt_grouplist != grouplist) {
6998 PyMem_Free(alt_grouplist);
6999 }
7000 return posix_error();
7001 }
7002#else
Victor Stinner8c62be82010-05-06 00:08:46 +00007003 n = getgroups(MAX_GROUPS, grouplist);
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00007004 if (n < 0) {
7005 if (errno == EINVAL) {
7006 n = getgroups(0, NULL);
7007 if (n == -1) {
7008 return posix_error();
7009 }
7010 if (n == 0) {
7011 /* Avoid malloc(0) */
7012 alt_grouplist = grouplist;
7013 } else {
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02007014 alt_grouplist = PyMem_New(gid_t, n);
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00007015 if (alt_grouplist == NULL) {
Zackery Spytz4c49da02018-12-07 03:11:30 -07007016 return PyErr_NoMemory();
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00007017 }
7018 n = getgroups(n, alt_grouplist);
7019 if (n == -1) {
7020 PyMem_Free(alt_grouplist);
7021 return posix_error();
7022 }
7023 }
7024 } else {
7025 return posix_error();
7026 }
7027 }
Ned Deilyb5dd6d22013-08-01 21:21:15 -07007028#endif
7029
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00007030 result = PyList_New(n);
7031 if (result != NULL) {
Victor Stinner8c62be82010-05-06 00:08:46 +00007032 int i;
7033 for (i = 0; i < n; ++i) {
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02007034 PyObject *o = _PyLong_FromGid(alt_grouplist[i]);
Victor Stinner8c62be82010-05-06 00:08:46 +00007035 if (o == NULL) {
Stefan Krah0e803b32010-11-26 16:16:47 +00007036 Py_DECREF(result);
7037 result = NULL;
7038 break;
Fred Drakec9680921999-12-13 16:37:25 +00007039 }
Victor Stinner8c62be82010-05-06 00:08:46 +00007040 PyList_SET_ITEM(result, i, o);
Fred Drakec9680921999-12-13 16:37:25 +00007041 }
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00007042 }
7043
7044 if (alt_grouplist != grouplist) {
7045 PyMem_Free(alt_grouplist);
Victor Stinner8c62be82010-05-06 00:08:46 +00007046 }
Neal Norwitze241ce82003-02-17 18:17:05 +00007047
Fred Drakec9680921999-12-13 16:37:25 +00007048 return result;
7049}
Larry Hastings2f936352014-08-05 14:04:04 +10007050#endif /* HAVE_GETGROUPS */
Fred Drakec9680921999-12-13 16:37:25 +00007051
Antoine Pitroub7572f02009-12-02 20:46:48 +00007052#ifdef HAVE_INITGROUPS
7053PyDoc_STRVAR(posix_initgroups__doc__,
7054"initgroups(username, gid) -> None\n\n\
7055Call the system initgroups() to initialize the group access list with all of\n\
7056the groups of which the specified username is a member, plus the specified\n\
7057group id.");
7058
Larry Hastings2f936352014-08-05 14:04:04 +10007059/* AC 3.5: funny apple logic */
Antoine Pitroub7572f02009-12-02 20:46:48 +00007060static PyObject *
7061posix_initgroups(PyObject *self, PyObject *args)
7062{
Victor Stinner61ec5dc2010-08-15 09:22:44 +00007063 PyObject *oname;
Serhiy Storchakadeab18d2016-05-07 16:45:18 +03007064 const char *username;
Victor Stinner61ec5dc2010-08-15 09:22:44 +00007065 int res;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02007066#ifdef __APPLE__
7067 int gid;
7068#else
7069 gid_t gid;
7070#endif
Antoine Pitroub7572f02009-12-02 20:46:48 +00007071
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02007072#ifdef __APPLE__
7073 if (!PyArg_ParseTuple(args, "O&i:initgroups",
7074 PyUnicode_FSConverter, &oname,
7075 &gid))
7076#else
7077 if (!PyArg_ParseTuple(args, "O&O&:initgroups",
7078 PyUnicode_FSConverter, &oname,
7079 _Py_Gid_Converter, &gid))
7080#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00007081 return NULL;
Victor Stinner61ec5dc2010-08-15 09:22:44 +00007082 username = PyBytes_AS_STRING(oname);
Antoine Pitroub7572f02009-12-02 20:46:48 +00007083
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02007084 res = initgroups(username, gid);
Victor Stinner61ec5dc2010-08-15 09:22:44 +00007085 Py_DECREF(oname);
7086 if (res == -1)
Victor Stinner8c62be82010-05-06 00:08:46 +00007087 return PyErr_SetFromErrno(PyExc_OSError);
Antoine Pitroub7572f02009-12-02 20:46:48 +00007088
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02007089 Py_RETURN_NONE;
Antoine Pitroub7572f02009-12-02 20:46:48 +00007090}
Larry Hastings2f936352014-08-05 14:04:04 +10007091#endif /* HAVE_INITGROUPS */
7092
Antoine Pitroub7572f02009-12-02 20:46:48 +00007093
Martin v. Löwis606edc12002-06-13 21:09:11 +00007094#ifdef HAVE_GETPGID
Larry Hastings2f936352014-08-05 14:04:04 +10007095/*[clinic input]
7096os.getpgid
7097
7098 pid: pid_t
7099
7100Call the system call getpgid(), and return the result.
7101[clinic start generated code]*/
7102
Larry Hastings2f936352014-08-05 14:04:04 +10007103static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007104os_getpgid_impl(PyObject *module, pid_t pid)
7105/*[clinic end generated code: output=1db95a97be205d18 input=39d710ae3baaf1c7]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007106{
7107 pid_t pgid = getpgid(pid);
Victor Stinner8c62be82010-05-06 00:08:46 +00007108 if (pgid < 0)
7109 return posix_error();
7110 return PyLong_FromPid(pgid);
Martin v. Löwis606edc12002-06-13 21:09:11 +00007111}
7112#endif /* HAVE_GETPGID */
7113
7114
Guido van Rossumb6775db1994-08-01 11:34:53 +00007115#ifdef HAVE_GETPGRP
Larry Hastings2f936352014-08-05 14:04:04 +10007116/*[clinic input]
7117os.getpgrp
7118
7119Return the current process group id.
7120[clinic start generated code]*/
7121
Larry Hastings2f936352014-08-05 14:04:04 +10007122static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007123os_getpgrp_impl(PyObject *module)
7124/*[clinic end generated code: output=c4fc381e51103cf3 input=6846fb2bb9a3705e]*/
Guido van Rossum04814471991-06-04 20:23:49 +00007125{
Guido van Rossumb6775db1994-08-01 11:34:53 +00007126#ifdef GETPGRP_HAVE_ARG
Victor Stinner8c62be82010-05-06 00:08:46 +00007127 return PyLong_FromPid(getpgrp(0));
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +00007128#else /* GETPGRP_HAVE_ARG */
Victor Stinner8c62be82010-05-06 00:08:46 +00007129 return PyLong_FromPid(getpgrp());
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +00007130#endif /* GETPGRP_HAVE_ARG */
Guido van Rossum04814471991-06-04 20:23:49 +00007131}
Guido van Rossumb6775db1994-08-01 11:34:53 +00007132#endif /* HAVE_GETPGRP */
Guido van Rossum04814471991-06-04 20:23:49 +00007133
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007134
Guido van Rossumb6775db1994-08-01 11:34:53 +00007135#ifdef HAVE_SETPGRP
Larry Hastings2f936352014-08-05 14:04:04 +10007136/*[clinic input]
7137os.setpgrp
7138
7139Make the current process the leader of its process group.
7140[clinic start generated code]*/
7141
Larry Hastings2f936352014-08-05 14:04:04 +10007142static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007143os_setpgrp_impl(PyObject *module)
7144/*[clinic end generated code: output=2554735b0a60f0a0 input=1f0619fcb5731e7e]*/
Guido van Rossumc2670a01992-09-13 20:07:29 +00007145{
Guido van Rossum64933891994-10-20 21:56:42 +00007146#ifdef SETPGRP_HAVE_ARG
Victor Stinner8c62be82010-05-06 00:08:46 +00007147 if (setpgrp(0, 0) < 0)
Guido van Rossum64933891994-10-20 21:56:42 +00007148#else /* SETPGRP_HAVE_ARG */
Victor Stinner8c62be82010-05-06 00:08:46 +00007149 if (setpgrp() < 0)
Guido van Rossum64933891994-10-20 21:56:42 +00007150#endif /* SETPGRP_HAVE_ARG */
Victor Stinner8c62be82010-05-06 00:08:46 +00007151 return posix_error();
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02007152 Py_RETURN_NONE;
Guido van Rossumc2670a01992-09-13 20:07:29 +00007153}
Guido van Rossumb6775db1994-08-01 11:34:53 +00007154#endif /* HAVE_SETPGRP */
7155
Guido van Rossumad0ee831995-03-01 10:34:45 +00007156#ifdef HAVE_GETPPID
Amaury Forgeot d'Arc4b6fdf32010-09-07 21:31:17 +00007157
7158#ifdef MS_WINDOWS
7159#include <tlhelp32.h>
7160
7161static PyObject*
7162win32_getppid()
7163{
7164 HANDLE snapshot;
7165 pid_t mypid;
7166 PyObject* result = NULL;
7167 BOOL have_record;
7168 PROCESSENTRY32 pe;
7169
7170 mypid = getpid(); /* This function never fails */
7171
7172 snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
7173 if (snapshot == INVALID_HANDLE_VALUE)
7174 return PyErr_SetFromWindowsErr(GetLastError());
7175
7176 pe.dwSize = sizeof(pe);
7177 have_record = Process32First(snapshot, &pe);
7178 while (have_record) {
7179 if (mypid == (pid_t)pe.th32ProcessID) {
7180 /* We could cache the ulong value in a static variable. */
7181 result = PyLong_FromPid((pid_t)pe.th32ParentProcessID);
7182 break;
7183 }
7184
7185 have_record = Process32Next(snapshot, &pe);
7186 }
7187
7188 /* If our loop exits and our pid was not found (result will be NULL)
7189 * then GetLastError will return ERROR_NO_MORE_FILES. This is an
7190 * error anyway, so let's raise it. */
7191 if (!result)
7192 result = PyErr_SetFromWindowsErr(GetLastError());
7193
7194 CloseHandle(snapshot);
7195
7196 return result;
7197}
7198#endif /*MS_WINDOWS*/
7199
Larry Hastings2f936352014-08-05 14:04:04 +10007200
7201/*[clinic input]
7202os.getppid
7203
7204Return the parent's process id.
7205
7206If the parent process has already exited, Windows machines will still
7207return its id; others systems will return the id of the 'init' process (1).
7208[clinic start generated code]*/
7209
Larry Hastings2f936352014-08-05 14:04:04 +10007210static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007211os_getppid_impl(PyObject *module)
7212/*[clinic end generated code: output=43b2a946a8c603b4 input=e637cb87539c030e]*/
Guido van Rossum85e3b011991-06-03 12:42:10 +00007213{
Amaury Forgeot d'Arc4b6fdf32010-09-07 21:31:17 +00007214#ifdef MS_WINDOWS
7215 return win32_getppid();
7216#else
Victor Stinner8c62be82010-05-06 00:08:46 +00007217 return PyLong_FromPid(getppid());
Guido van Rossumad0ee831995-03-01 10:34:45 +00007218#endif
Amaury Forgeot d'Arc4b6fdf32010-09-07 21:31:17 +00007219}
7220#endif /* HAVE_GETPPID */
Guido van Rossum85e3b011991-06-03 12:42:10 +00007221
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007222
Fred Drake12c6e2d1999-12-14 21:25:03 +00007223#ifdef HAVE_GETLOGIN
Larry Hastings2f936352014-08-05 14:04:04 +10007224/*[clinic input]
7225os.getlogin
7226
7227Return the actual login name.
7228[clinic start generated code]*/
7229
Larry Hastings2f936352014-08-05 14:04:04 +10007230static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007231os_getlogin_impl(PyObject *module)
7232/*[clinic end generated code: output=a32e66a7e5715dac input=2a21ab1e917163df]*/
Fred Drake12c6e2d1999-12-14 21:25:03 +00007233{
Victor Stinner8c62be82010-05-06 00:08:46 +00007234 PyObject *result = NULL;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00007235#ifdef MS_WINDOWS
Brian Curtine8e4b3b2010-09-23 20:04:14 +00007236 wchar_t user_name[UNLEN + 1];
Victor Stinner63941882011-09-29 00:42:28 +02007237 DWORD num_chars = Py_ARRAY_LENGTH(user_name);
Brian Curtine8e4b3b2010-09-23 20:04:14 +00007238
7239 if (GetUserNameW(user_name, &num_chars)) {
7240 /* num_chars is the number of unicode chars plus null terminator */
7241 result = PyUnicode_FromWideChar(user_name, num_chars - 1);
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00007242 }
7243 else
Brian Curtine8e4b3b2010-09-23 20:04:14 +00007244 result = PyErr_SetFromWindowsErr(GetLastError());
7245#else
Victor Stinner8c62be82010-05-06 00:08:46 +00007246 char *name;
7247 int old_errno = errno;
Fred Drake12c6e2d1999-12-14 21:25:03 +00007248
Victor Stinner8c62be82010-05-06 00:08:46 +00007249 errno = 0;
7250 name = getlogin();
7251 if (name == NULL) {
7252 if (errno)
Victor Stinnere039ffe2010-08-15 09:33:08 +00007253 posix_error();
Fred Drake12c6e2d1999-12-14 21:25:03 +00007254 else
Victor Stinnere039ffe2010-08-15 09:33:08 +00007255 PyErr_SetString(PyExc_OSError, "unable to determine login name");
Victor Stinner8c62be82010-05-06 00:08:46 +00007256 }
7257 else
Victor Stinnere039ffe2010-08-15 09:33:08 +00007258 result = PyUnicode_DecodeFSDefault(name);
Victor Stinner8c62be82010-05-06 00:08:46 +00007259 errno = old_errno;
Brian Curtine8e4b3b2010-09-23 20:04:14 +00007260#endif
Fred Drake12c6e2d1999-12-14 21:25:03 +00007261 return result;
7262}
Brian Curtine8e4b3b2010-09-23 20:04:14 +00007263#endif /* HAVE_GETLOGIN */
Fred Drake12c6e2d1999-12-14 21:25:03 +00007264
Larry Hastings2f936352014-08-05 14:04:04 +10007265
Guido van Rossumad0ee831995-03-01 10:34:45 +00007266#ifdef HAVE_GETUID
Larry Hastings2f936352014-08-05 14:04:04 +10007267/*[clinic input]
7268os.getuid
7269
7270Return the current process's user id.
7271[clinic start generated code]*/
7272
Larry Hastings2f936352014-08-05 14:04:04 +10007273static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007274os_getuid_impl(PyObject *module)
7275/*[clinic end generated code: output=415c0b401ebed11a input=b53c8b35f110a516]*/
Guido van Rossum46003ff1992-05-15 11:05:24 +00007276{
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02007277 return _PyLong_FromUid(getuid());
Guido van Rossum46003ff1992-05-15 11:05:24 +00007278}
Larry Hastings2f936352014-08-05 14:04:04 +10007279#endif /* HAVE_GETUID */
Guido van Rossum46003ff1992-05-15 11:05:24 +00007280
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007281
Brian Curtineb24d742010-04-12 17:16:38 +00007282#ifdef MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +10007283#define HAVE_KILL
7284#endif /* MS_WINDOWS */
7285
7286#ifdef HAVE_KILL
7287/*[clinic input]
7288os.kill
7289
7290 pid: pid_t
7291 signal: Py_ssize_t
7292 /
7293
7294Kill a process with a signal.
7295[clinic start generated code]*/
7296
Larry Hastings2f936352014-08-05 14:04:04 +10007297static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007298os_kill_impl(PyObject *module, pid_t pid, Py_ssize_t signal)
7299/*[clinic end generated code: output=8e346a6701c88568 input=61a36b86ca275ab9]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007300#ifndef MS_WINDOWS
7301{
7302 if (kill(pid, (int)signal) == -1)
7303 return posix_error();
7304 Py_RETURN_NONE;
7305}
7306#else /* !MS_WINDOWS */
Brian Curtineb24d742010-04-12 17:16:38 +00007307{
Amaury Forgeot d'Arc0a589c92010-05-15 20:35:12 +00007308 PyObject *result;
Larry Hastings2f936352014-08-05 14:04:04 +10007309 DWORD sig = (DWORD)signal;
7310 DWORD err;
Victor Stinner8c62be82010-05-06 00:08:46 +00007311 HANDLE handle;
Brian Curtineb24d742010-04-12 17:16:38 +00007312
Victor Stinner8c62be82010-05-06 00:08:46 +00007313 /* Console processes which share a common console can be sent CTRL+C or
7314 CTRL+BREAK events, provided they handle said events. */
7315 if (sig == CTRL_C_EVENT || sig == CTRL_BREAK_EVENT) {
Richard Oudkerkac0ad882013-06-05 23:29:30 +01007316 if (GenerateConsoleCtrlEvent(sig, (DWORD)pid) == 0) {
Victor Stinner8c62be82010-05-06 00:08:46 +00007317 err = GetLastError();
7318 PyErr_SetFromWindowsErr(err);
7319 }
7320 else
7321 Py_RETURN_NONE;
7322 }
Brian Curtineb24d742010-04-12 17:16:38 +00007323
Victor Stinner8c62be82010-05-06 00:08:46 +00007324 /* If the signal is outside of what GenerateConsoleCtrlEvent can use,
7325 attempt to open and terminate the process. */
Richard Oudkerkac0ad882013-06-05 23:29:30 +01007326 handle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, (DWORD)pid);
Victor Stinner8c62be82010-05-06 00:08:46 +00007327 if (handle == NULL) {
7328 err = GetLastError();
7329 return PyErr_SetFromWindowsErr(err);
7330 }
Brian Curtineb24d742010-04-12 17:16:38 +00007331
Victor Stinner8c62be82010-05-06 00:08:46 +00007332 if (TerminateProcess(handle, sig) == 0) {
7333 err = GetLastError();
7334 result = PyErr_SetFromWindowsErr(err);
7335 } else {
7336 Py_INCREF(Py_None);
7337 result = Py_None;
7338 }
Brian Curtineb24d742010-04-12 17:16:38 +00007339
Victor Stinner8c62be82010-05-06 00:08:46 +00007340 CloseHandle(handle);
7341 return result;
Brian Curtineb24d742010-04-12 17:16:38 +00007342}
Larry Hastings2f936352014-08-05 14:04:04 +10007343#endif /* !MS_WINDOWS */
7344#endif /* HAVE_KILL */
7345
7346
7347#ifdef HAVE_KILLPG
7348/*[clinic input]
7349os.killpg
7350
7351 pgid: pid_t
7352 signal: int
7353 /
7354
7355Kill a process group with a signal.
7356[clinic start generated code]*/
7357
Larry Hastings2f936352014-08-05 14:04:04 +10007358static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007359os_killpg_impl(PyObject *module, pid_t pgid, int signal)
7360/*[clinic end generated code: output=6dbcd2f1fdf5fdba input=38b5449eb8faec19]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007361{
7362 /* XXX some man pages make the `pgid` parameter an int, others
7363 a pid_t. Since getpgrp() returns a pid_t, we assume killpg should
7364 take the same type. Moreover, pid_t is always at least as wide as
7365 int (else compilation of this module fails), which is safe. */
7366 if (killpg(pgid, signal) == -1)
7367 return posix_error();
7368 Py_RETURN_NONE;
7369}
7370#endif /* HAVE_KILLPG */
7371
Brian Curtineb24d742010-04-12 17:16:38 +00007372
Guido van Rossumc0125471996-06-28 18:55:32 +00007373#ifdef HAVE_PLOCK
Guido van Rossumc0125471996-06-28 18:55:32 +00007374#ifdef HAVE_SYS_LOCK_H
7375#include <sys/lock.h>
7376#endif
7377
Larry Hastings2f936352014-08-05 14:04:04 +10007378/*[clinic input]
7379os.plock
7380 op: int
7381 /
7382
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007383Lock program segments into memory.");
Larry Hastings2f936352014-08-05 14:04:04 +10007384[clinic start generated code]*/
7385
Larry Hastings2f936352014-08-05 14:04:04 +10007386static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007387os_plock_impl(PyObject *module, int op)
7388/*[clinic end generated code: output=81424167033b168e input=e6e5e348e1525f60]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007389{
Victor Stinner8c62be82010-05-06 00:08:46 +00007390 if (plock(op) == -1)
7391 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10007392 Py_RETURN_NONE;
Guido van Rossumc0125471996-06-28 18:55:32 +00007393}
Larry Hastings2f936352014-08-05 14:04:04 +10007394#endif /* HAVE_PLOCK */
7395
Guido van Rossumc0125471996-06-28 18:55:32 +00007396
Guido van Rossumb6775db1994-08-01 11:34:53 +00007397#ifdef HAVE_SETUID
Larry Hastings2f936352014-08-05 14:04:04 +10007398/*[clinic input]
7399os.setuid
7400
7401 uid: uid_t
7402 /
7403
7404Set the current process's user id.
7405[clinic start generated code]*/
7406
Larry Hastings2f936352014-08-05 14:04:04 +10007407static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007408os_setuid_impl(PyObject *module, uid_t uid)
7409/*[clinic end generated code: output=a0a41fd0d1ec555f input=c921a3285aa22256]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007410{
Victor Stinner8c62be82010-05-06 00:08:46 +00007411 if (setuid(uid) < 0)
7412 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10007413 Py_RETURN_NONE;
Guido van Rossuma3d78fb1993-11-10 09:23:53 +00007414}
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +00007415#endif /* HAVE_SETUID */
Guido van Rossuma3d78fb1993-11-10 09:23:53 +00007416
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007417
Andrew M. Kuchling8d2f2b22000-07-13 01:26:58 +00007418#ifdef HAVE_SETEUID
Larry Hastings2f936352014-08-05 14:04:04 +10007419/*[clinic input]
7420os.seteuid
7421
7422 euid: uid_t
7423 /
7424
7425Set the current process's effective user id.
7426[clinic start generated code]*/
7427
Larry Hastings2f936352014-08-05 14:04:04 +10007428static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007429os_seteuid_impl(PyObject *module, uid_t euid)
7430/*[clinic end generated code: output=102e3ad98361519a input=ba93d927e4781aa9]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007431{
7432 if (seteuid(euid) < 0)
Victor Stinner8c62be82010-05-06 00:08:46 +00007433 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10007434 Py_RETURN_NONE;
Andrew M. Kuchling8d2f2b22000-07-13 01:26:58 +00007435}
7436#endif /* HAVE_SETEUID */
7437
Larry Hastings2f936352014-08-05 14:04:04 +10007438
Andrew M. Kuchling8d2f2b22000-07-13 01:26:58 +00007439#ifdef HAVE_SETEGID
Larry Hastings2f936352014-08-05 14:04:04 +10007440/*[clinic input]
7441os.setegid
7442
7443 egid: gid_t
7444 /
7445
7446Set the current process's effective group id.
7447[clinic start generated code]*/
7448
Larry Hastings2f936352014-08-05 14:04:04 +10007449static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007450os_setegid_impl(PyObject *module, gid_t egid)
7451/*[clinic end generated code: output=4e4b825a6a10258d input=4080526d0ccd6ce3]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007452{
7453 if (setegid(egid) < 0)
Victor Stinner8c62be82010-05-06 00:08:46 +00007454 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10007455 Py_RETURN_NONE;
Andrew M. Kuchling8d2f2b22000-07-13 01:26:58 +00007456}
7457#endif /* HAVE_SETEGID */
7458
Larry Hastings2f936352014-08-05 14:04:04 +10007459
Andrew M. Kuchling8d2f2b22000-07-13 01:26:58 +00007460#ifdef HAVE_SETREUID
Larry Hastings2f936352014-08-05 14:04:04 +10007461/*[clinic input]
7462os.setreuid
7463
7464 ruid: uid_t
7465 euid: uid_t
7466 /
7467
7468Set the current process's real and effective user ids.
7469[clinic start generated code]*/
7470
Larry Hastings2f936352014-08-05 14:04:04 +10007471static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007472os_setreuid_impl(PyObject *module, uid_t ruid, uid_t euid)
7473/*[clinic end generated code: output=62d991210006530a input=0ca8978de663880c]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007474{
Victor Stinner8c62be82010-05-06 00:08:46 +00007475 if (setreuid(ruid, euid) < 0) {
7476 return posix_error();
7477 } else {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02007478 Py_RETURN_NONE;
Victor Stinner8c62be82010-05-06 00:08:46 +00007479 }
Andrew M. Kuchling8d2f2b22000-07-13 01:26:58 +00007480}
7481#endif /* HAVE_SETREUID */
7482
Larry Hastings2f936352014-08-05 14:04:04 +10007483
Andrew M. Kuchling8d2f2b22000-07-13 01:26:58 +00007484#ifdef HAVE_SETREGID
Larry Hastings2f936352014-08-05 14:04:04 +10007485/*[clinic input]
7486os.setregid
7487
7488 rgid: gid_t
7489 egid: gid_t
7490 /
7491
7492Set the current process's real and effective group ids.
7493[clinic start generated code]*/
7494
Larry Hastings2f936352014-08-05 14:04:04 +10007495static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007496os_setregid_impl(PyObject *module, gid_t rgid, gid_t egid)
7497/*[clinic end generated code: output=aa803835cf5342f3 input=c59499f72846db78]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007498{
7499 if (setregid(rgid, egid) < 0)
Victor Stinner8c62be82010-05-06 00:08:46 +00007500 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10007501 Py_RETURN_NONE;
Andrew M. Kuchling8d2f2b22000-07-13 01:26:58 +00007502}
7503#endif /* HAVE_SETREGID */
7504
Larry Hastings2f936352014-08-05 14:04:04 +10007505
Guido van Rossumb6775db1994-08-01 11:34:53 +00007506#ifdef HAVE_SETGID
Larry Hastings2f936352014-08-05 14:04:04 +10007507/*[clinic input]
7508os.setgid
7509 gid: gid_t
7510 /
7511
7512Set the current process's group id.
7513[clinic start generated code]*/
7514
Larry Hastings2f936352014-08-05 14:04:04 +10007515static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007516os_setgid_impl(PyObject *module, gid_t gid)
7517/*[clinic end generated code: output=bdccd7403f6ad8c3 input=27d30c4059045dc6]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007518{
Victor Stinner8c62be82010-05-06 00:08:46 +00007519 if (setgid(gid) < 0)
7520 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10007521 Py_RETURN_NONE;
Guido van Rossuma3d78fb1993-11-10 09:23:53 +00007522}
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +00007523#endif /* HAVE_SETGID */
Guido van Rossuma3d78fb1993-11-10 09:23:53 +00007524
Larry Hastings2f936352014-08-05 14:04:04 +10007525
Martin v. Löwis61c5edf2001-10-18 04:06:00 +00007526#ifdef HAVE_SETGROUPS
Larry Hastings2f936352014-08-05 14:04:04 +10007527/*[clinic input]
7528os.setgroups
7529
7530 groups: object
7531 /
7532
7533Set the groups of the current process to list.
7534[clinic start generated code]*/
7535
Martin v. Löwis61c5edf2001-10-18 04:06:00 +00007536static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007537os_setgroups(PyObject *module, PyObject *groups)
7538/*[clinic end generated code: output=3fcb32aad58c5ecd input=fa742ca3daf85a7e]*/
Martin v. Löwis61c5edf2001-10-18 04:06:00 +00007539{
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03007540 Py_ssize_t i, len;
Victor Stinner8c62be82010-05-06 00:08:46 +00007541 gid_t grouplist[MAX_GROUPS];
Tim Peters5aa91602002-01-30 05:46:57 +00007542
Victor Stinner8c62be82010-05-06 00:08:46 +00007543 if (!PySequence_Check(groups)) {
7544 PyErr_SetString(PyExc_TypeError, "setgroups argument must be a sequence");
7545 return NULL;
7546 }
7547 len = PySequence_Size(groups);
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03007548 if (len < 0) {
7549 return NULL;
7550 }
Victor Stinner8c62be82010-05-06 00:08:46 +00007551 if (len > MAX_GROUPS) {
7552 PyErr_SetString(PyExc_ValueError, "too many groups");
7553 return NULL;
7554 }
7555 for(i = 0; i < len; i++) {
7556 PyObject *elem;
7557 elem = PySequence_GetItem(groups, i);
7558 if (!elem)
7559 return NULL;
7560 if (!PyLong_Check(elem)) {
7561 PyErr_SetString(PyExc_TypeError,
7562 "groups must be integers");
7563 Py_DECREF(elem);
7564 return NULL;
7565 } else {
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02007566 if (!_Py_Gid_Converter(elem, &grouplist[i])) {
Victor Stinner8c62be82010-05-06 00:08:46 +00007567 Py_DECREF(elem);
7568 return NULL;
7569 }
7570 }
7571 Py_DECREF(elem);
7572 }
Martin v. Löwis61c5edf2001-10-18 04:06:00 +00007573
Victor Stinner8c62be82010-05-06 00:08:46 +00007574 if (setgroups(len, grouplist) < 0)
7575 return posix_error();
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02007576 Py_RETURN_NONE;
Martin v. Löwis61c5edf2001-10-18 04:06:00 +00007577}
7578#endif /* HAVE_SETGROUPS */
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007579
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007580#if defined(HAVE_WAIT3) || defined(HAVE_WAIT4)
7581static PyObject *
Victor Stinner4195b5c2012-02-08 23:03:19 +01007582wait_helper(pid_t pid, int status, struct rusage *ru)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007583{
Victor Stinner8c62be82010-05-06 00:08:46 +00007584 PyObject *result;
Eddie Elizondob3966632019-11-05 07:16:14 -08007585 PyObject *struct_rusage;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007586
Victor Stinner8c62be82010-05-06 00:08:46 +00007587 if (pid == -1)
7588 return posix_error();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007589
Zackery Spytz682107c2019-09-09 09:48:32 -06007590 // If wait succeeded but no child was ready to report status, ru will not
7591 // have been populated.
7592 if (pid == 0) {
7593 memset(ru, 0, sizeof(*ru));
7594 }
7595
Eddie Elizondob3966632019-11-05 07:16:14 -08007596 PyObject *m = PyImport_ImportModuleNoBlock("resource");
7597 if (m == NULL)
7598 return NULL;
7599 struct_rusage = PyObject_GetAttr(m, _posixstate_global->struct_rusage);
7600 Py_DECREF(m);
7601 if (struct_rusage == NULL)
7602 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007603
Victor Stinner8c62be82010-05-06 00:08:46 +00007604 /* XXX(nnorwitz): Copied (w/mods) from resource.c, there should be only one. */
7605 result = PyStructSequence_New((PyTypeObject*) struct_rusage);
Eddie Elizondoe4db1f02019-11-25 19:07:37 -08007606 Py_DECREF(struct_rusage);
Victor Stinner8c62be82010-05-06 00:08:46 +00007607 if (!result)
7608 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007609
7610#ifndef doubletime
7611#define doubletime(TV) ((double)(TV).tv_sec + (TV).tv_usec * 0.000001)
7612#endif
7613
Victor Stinner8c62be82010-05-06 00:08:46 +00007614 PyStructSequence_SET_ITEM(result, 0,
Victor Stinner4195b5c2012-02-08 23:03:19 +01007615 PyFloat_FromDouble(doubletime(ru->ru_utime)));
Victor Stinner8c62be82010-05-06 00:08:46 +00007616 PyStructSequence_SET_ITEM(result, 1,
Victor Stinner4195b5c2012-02-08 23:03:19 +01007617 PyFloat_FromDouble(doubletime(ru->ru_stime)));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007618#define SET_INT(result, index, value)\
Victor Stinner8c62be82010-05-06 00:08:46 +00007619 PyStructSequence_SET_ITEM(result, index, PyLong_FromLong(value))
7620 SET_INT(result, 2, ru->ru_maxrss);
7621 SET_INT(result, 3, ru->ru_ixrss);
7622 SET_INT(result, 4, ru->ru_idrss);
7623 SET_INT(result, 5, ru->ru_isrss);
7624 SET_INT(result, 6, ru->ru_minflt);
7625 SET_INT(result, 7, ru->ru_majflt);
7626 SET_INT(result, 8, ru->ru_nswap);
7627 SET_INT(result, 9, ru->ru_inblock);
7628 SET_INT(result, 10, ru->ru_oublock);
7629 SET_INT(result, 11, ru->ru_msgsnd);
7630 SET_INT(result, 12, ru->ru_msgrcv);
7631 SET_INT(result, 13, ru->ru_nsignals);
7632 SET_INT(result, 14, ru->ru_nvcsw);
7633 SET_INT(result, 15, ru->ru_nivcsw);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007634#undef SET_INT
7635
Victor Stinner8c62be82010-05-06 00:08:46 +00007636 if (PyErr_Occurred()) {
7637 Py_DECREF(result);
7638 return NULL;
7639 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007640
Victor Stinner8c62be82010-05-06 00:08:46 +00007641 return Py_BuildValue("NiN", PyLong_FromPid(pid), status, result);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007642}
7643#endif /* HAVE_WAIT3 || HAVE_WAIT4 */
7644
Larry Hastings2f936352014-08-05 14:04:04 +10007645
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007646#ifdef HAVE_WAIT3
Larry Hastings2f936352014-08-05 14:04:04 +10007647/*[clinic input]
7648os.wait3
7649
7650 options: int
7651Wait for completion of a child process.
7652
7653Returns a tuple of information about the child process:
7654 (pid, status, rusage)
7655[clinic start generated code]*/
7656
Larry Hastings2f936352014-08-05 14:04:04 +10007657static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007658os_wait3_impl(PyObject *module, int options)
7659/*[clinic end generated code: output=92c3224e6f28217a input=8ac4c56956b61710]*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007660{
Victor Stinner8c62be82010-05-06 00:08:46 +00007661 pid_t pid;
Victor Stinner8c62be82010-05-06 00:08:46 +00007662 struct rusage ru;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007663 int async_err = 0;
Victor Stinner8c62be82010-05-06 00:08:46 +00007664 WAIT_TYPE status;
7665 WAIT_STATUS_INT(status) = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007666
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007667 do {
7668 Py_BEGIN_ALLOW_THREADS
7669 pid = wait3(&status, options, &ru);
7670 Py_END_ALLOW_THREADS
7671 } while (pid < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
7672 if (pid < 0)
7673 return (!async_err) ? posix_error() : NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007674
Victor Stinner4195b5c2012-02-08 23:03:19 +01007675 return wait_helper(pid, WAIT_STATUS_INT(status), &ru);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007676}
7677#endif /* HAVE_WAIT3 */
7678
Larry Hastings2f936352014-08-05 14:04:04 +10007679
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007680#ifdef HAVE_WAIT4
Larry Hastings2f936352014-08-05 14:04:04 +10007681/*[clinic input]
7682
7683os.wait4
7684
7685 pid: pid_t
7686 options: int
7687
7688Wait for completion of a specific child process.
7689
7690Returns a tuple of information about the child process:
7691 (pid, status, rusage)
7692[clinic start generated code]*/
7693
Larry Hastings2f936352014-08-05 14:04:04 +10007694static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007695os_wait4_impl(PyObject *module, pid_t pid, int options)
7696/*[clinic end generated code: output=66195aa507b35f70 input=d11deed0750600ba]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007697{
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007698 pid_t res;
Victor Stinner8c62be82010-05-06 00:08:46 +00007699 struct rusage ru;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007700 int async_err = 0;
Victor Stinner8c62be82010-05-06 00:08:46 +00007701 WAIT_TYPE status;
7702 WAIT_STATUS_INT(status) = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007703
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007704 do {
7705 Py_BEGIN_ALLOW_THREADS
7706 res = wait4(pid, &status, options, &ru);
7707 Py_END_ALLOW_THREADS
7708 } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
7709 if (res < 0)
7710 return (!async_err) ? posix_error() : NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007711
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007712 return wait_helper(res, WAIT_STATUS_INT(status), &ru);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007713}
7714#endif /* HAVE_WAIT4 */
7715
Larry Hastings2f936352014-08-05 14:04:04 +10007716
Ross Lagerwall7807c352011-03-17 20:20:30 +02007717#if defined(HAVE_WAITID) && !defined(__APPLE__)
Larry Hastings2f936352014-08-05 14:04:04 +10007718/*[clinic input]
7719os.waitid
7720
7721 idtype: idtype_t
7722 Must be one of be P_PID, P_PGID or P_ALL.
7723 id: id_t
7724 The id to wait on.
7725 options: int
7726 Constructed from the ORing of one or more of WEXITED, WSTOPPED
7727 or WCONTINUED and additionally may be ORed with WNOHANG or WNOWAIT.
7728 /
7729
7730Returns the result of waiting for a process or processes.
7731
7732Returns either waitid_result or None if WNOHANG is specified and there are
7733no children in a waitable state.
7734[clinic start generated code]*/
7735
Larry Hastings2f936352014-08-05 14:04:04 +10007736static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007737os_waitid_impl(PyObject *module, idtype_t idtype, id_t id, int options)
7738/*[clinic end generated code: output=5d2e1c0bde61f4d8 input=d8e7f76e052b7920]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007739{
7740 PyObject *result;
7741 int res;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007742 int async_err = 0;
Ross Lagerwall7807c352011-03-17 20:20:30 +02007743 siginfo_t si;
7744 si.si_pid = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10007745
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007746 do {
7747 Py_BEGIN_ALLOW_THREADS
7748 res = waitid(idtype, id, &si, options);
7749 Py_END_ALLOW_THREADS
7750 } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
7751 if (res < 0)
7752 return (!async_err) ? posix_error() : NULL;
Ross Lagerwall7807c352011-03-17 20:20:30 +02007753
7754 if (si.si_pid == 0)
7755 Py_RETURN_NONE;
7756
Eddie Elizondob3966632019-11-05 07:16:14 -08007757 PyObject *WaitidResultType = _posixstate(module)->WaitidResultType;
7758 result = PyStructSequence_New((PyTypeObject *)WaitidResultType);
Ross Lagerwall7807c352011-03-17 20:20:30 +02007759 if (!result)
7760 return NULL;
7761
7762 PyStructSequence_SET_ITEM(result, 0, PyLong_FromPid(si.si_pid));
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02007763 PyStructSequence_SET_ITEM(result, 1, _PyLong_FromUid(si.si_uid));
Ross Lagerwall7807c352011-03-17 20:20:30 +02007764 PyStructSequence_SET_ITEM(result, 2, PyLong_FromLong((long)(si.si_signo)));
7765 PyStructSequence_SET_ITEM(result, 3, PyLong_FromLong((long)(si.si_status)));
7766 PyStructSequence_SET_ITEM(result, 4, PyLong_FromLong((long)(si.si_code)));
7767 if (PyErr_Occurred()) {
7768 Py_DECREF(result);
7769 return NULL;
7770 }
7771
7772 return result;
7773}
Larry Hastings2f936352014-08-05 14:04:04 +10007774#endif /* defined(HAVE_WAITID) && !defined(__APPLE__) */
Ross Lagerwall7807c352011-03-17 20:20:30 +02007775
Larry Hastings2f936352014-08-05 14:04:04 +10007776
7777#if defined(HAVE_WAITPID)
7778/*[clinic input]
7779os.waitpid
7780 pid: pid_t
7781 options: int
7782 /
7783
7784Wait for completion of a given child process.
7785
7786Returns a tuple of information regarding the child process:
7787 (pid, status)
7788
7789The options argument is ignored on Windows.
7790[clinic start generated code]*/
7791
Larry Hastings2f936352014-08-05 14:04:04 +10007792static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007793os_waitpid_impl(PyObject *module, pid_t pid, int options)
7794/*[clinic end generated code: output=5c37c06887a20270 input=0bf1666b8758fda3]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007795{
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007796 pid_t res;
7797 int async_err = 0;
Victor Stinner8c62be82010-05-06 00:08:46 +00007798 WAIT_TYPE status;
7799 WAIT_STATUS_INT(status) = 0;
Guido van Rossum54ecc3d1999-01-27 17:53:11 +00007800
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007801 do {
7802 Py_BEGIN_ALLOW_THREADS
7803 res = waitpid(pid, &status, options);
7804 Py_END_ALLOW_THREADS
7805 } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
7806 if (res < 0)
7807 return (!async_err) ? posix_error() : NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007808
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007809 return Py_BuildValue("Ni", PyLong_FromPid(res), WAIT_STATUS_INT(status));
Guido van Rossum21803b81992-08-09 12:55:27 +00007810}
Tim Petersab034fa2002-02-01 11:27:43 +00007811#elif defined(HAVE_CWAIT)
Tim Petersab034fa2002-02-01 11:27:43 +00007812/* MS C has a variant of waitpid() that's usable for most purposes. */
Larry Hastings2f936352014-08-05 14:04:04 +10007813/*[clinic input]
7814os.waitpid
Benjamin Petersonca470632016-09-06 13:47:26 -07007815 pid: intptr_t
Larry Hastings2f936352014-08-05 14:04:04 +10007816 options: int
7817 /
7818
7819Wait for completion of a given process.
7820
7821Returns a tuple of information regarding the process:
7822 (pid, status << 8)
7823
7824The options argument is ignored on Windows.
7825[clinic start generated code]*/
7826
Larry Hastings2f936352014-08-05 14:04:04 +10007827static PyObject *
Benjamin Petersonca470632016-09-06 13:47:26 -07007828os_waitpid_impl(PyObject *module, intptr_t pid, int options)
Victor Stinner581139c2016-09-06 15:54:20 -07007829/*[clinic end generated code: output=be836b221271d538 input=40f2440c515410f8]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007830{
7831 int status;
Benjamin Petersonca470632016-09-06 13:47:26 -07007832 intptr_t res;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007833 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10007834
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007835 do {
7836 Py_BEGIN_ALLOW_THREADS
Steve Dower11f43262016-11-19 18:33:39 -08007837 _Py_BEGIN_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007838 res = _cwait(&status, pid, options);
Steve Dower11f43262016-11-19 18:33:39 -08007839 _Py_END_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007840 Py_END_ALLOW_THREADS
7841 } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Victor Stinnerd3ffd322015-09-15 10:11:03 +02007842 if (res < 0)
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007843 return (!async_err) ? posix_error() : NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007844
Victor Stinner8c62be82010-05-06 00:08:46 +00007845 /* shift the status left a byte so this is more like the POSIX waitpid */
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007846 return Py_BuildValue(_Py_PARSE_INTPTR "i", res, status << 8);
Tim Petersab034fa2002-02-01 11:27:43 +00007847}
Larry Hastings2f936352014-08-05 14:04:04 +10007848#endif
7849
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007850
Guido van Rossumad0ee831995-03-01 10:34:45 +00007851#ifdef HAVE_WAIT
Larry Hastings2f936352014-08-05 14:04:04 +10007852/*[clinic input]
7853os.wait
7854
7855Wait for completion of a child process.
7856
7857Returns a tuple of information about the child process:
7858 (pid, status)
7859[clinic start generated code]*/
7860
Larry Hastings2f936352014-08-05 14:04:04 +10007861static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007862os_wait_impl(PyObject *module)
7863/*[clinic end generated code: output=6bc419ac32fb364b input=03b0182d4a4700ce]*/
Guido van Rossum21803b81992-08-09 12:55:27 +00007864{
Victor Stinner8c62be82010-05-06 00:08:46 +00007865 pid_t pid;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007866 int async_err = 0;
Victor Stinner8c62be82010-05-06 00:08:46 +00007867 WAIT_TYPE status;
7868 WAIT_STATUS_INT(status) = 0;
Neal Norwitze241ce82003-02-17 18:17:05 +00007869
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007870 do {
7871 Py_BEGIN_ALLOW_THREADS
7872 pid = wait(&status);
7873 Py_END_ALLOW_THREADS
7874 } while (pid < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
7875 if (pid < 0)
7876 return (!async_err) ? posix_error() : NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007877
Victor Stinner8c62be82010-05-06 00:08:46 +00007878 return Py_BuildValue("Ni", PyLong_FromPid(pid), WAIT_STATUS_INT(status));
Guido van Rossum85e3b011991-06-03 12:42:10 +00007879}
Larry Hastings2f936352014-08-05 14:04:04 +10007880#endif /* HAVE_WAIT */
Guido van Rossum85e3b011991-06-03 12:42:10 +00007881
Benjamin Peterson6c4c45e2019-11-05 19:21:29 -08007882#if defined(__linux__) && defined(__NR_pidfd_open)
7883/*[clinic input]
7884os.pidfd_open
7885 pid: pid_t
7886 flags: unsigned_int = 0
7887
7888Return a file descriptor referring to the process *pid*.
7889
7890The descriptor can be used to perform process management without races and
7891signals.
7892[clinic start generated code]*/
7893
7894static PyObject *
7895os_pidfd_open_impl(PyObject *module, pid_t pid, unsigned int flags)
7896/*[clinic end generated code: output=5c7252698947dc41 input=c3fd99ce947ccfef]*/
7897{
7898 int fd = syscall(__NR_pidfd_open, pid, flags);
7899 if (fd < 0) {
7900 return posix_error();
7901 }
7902 return PyLong_FromLong(fd);
7903}
7904#endif
7905
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007906
Larry Hastings9cf065c2012-06-22 16:30:09 -07007907#if defined(HAVE_READLINK) || defined(MS_WINDOWS)
Serhiy Storchaka12a69db2018-09-17 15:38:27 +03007908/*[clinic input]
7909os.readlink
7910
7911 path: path_t
7912 *
7913 dir_fd: dir_fd(requires='readlinkat') = None
7914
7915Return a string representing the path to which the symbolic link points.
7916
7917If dir_fd is not None, it should be a file descriptor open to a directory,
7918and path should be relative; path will then be relative to that directory.
7919
7920dir_fd may not be implemented on your platform. If it is unavailable,
7921using it will raise a NotImplementedError.
7922[clinic start generated code]*/
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007923
Barry Warsaw53699e91996-12-10 23:23:01 +00007924static PyObject *
Serhiy Storchaka12a69db2018-09-17 15:38:27 +03007925os_readlink_impl(PyObject *module, path_t *path, int dir_fd)
7926/*[clinic end generated code: output=d21b732a2e814030 input=113c87e0db1ecaf2]*/
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00007927{
Berker Peksage0b5b202018-08-15 13:03:41 +03007928#if defined(HAVE_READLINK)
Christian Heimes3cb091e2016-09-23 20:24:28 +02007929 char buffer[MAXPATHLEN+1];
Larry Hastings9cf065c2012-06-22 16:30:09 -07007930 ssize_t length;
Serhiy Storchaka12a69db2018-09-17 15:38:27 +03007931
7932 Py_BEGIN_ALLOW_THREADS
7933#ifdef HAVE_READLINKAT
7934 if (dir_fd != DEFAULT_DIR_FD)
7935 length = readlinkat(dir_fd, path->narrow, buffer, MAXPATHLEN);
7936 else
7937#endif
7938 length = readlink(path->narrow, buffer, MAXPATHLEN);
7939 Py_END_ALLOW_THREADS
7940
7941 if (length < 0) {
7942 return path_error(path);
7943 }
7944 buffer[length] = '\0';
7945
7946 if (PyUnicode_Check(path->object))
7947 return PyUnicode_DecodeFSDefaultAndSize(buffer, length);
7948 else
7949 return PyBytes_FromStringAndSize(buffer, length);
Berker Peksage0b5b202018-08-15 13:03:41 +03007950#elif defined(MS_WINDOWS)
7951 DWORD n_bytes_returned;
Steve Dowerdf2d4a62019-08-21 15:27:33 -07007952 DWORD io_result = 0;
Berker Peksage0b5b202018-08-15 13:03:41 +03007953 HANDLE reparse_point_handle;
Berker Peksage0b5b202018-08-15 13:03:41 +03007954 char target_buffer[_Py_MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
7955 _Py_REPARSE_DATA_BUFFER *rdb = (_Py_REPARSE_DATA_BUFFER *)target_buffer;
Steve Dower993ac922019-09-03 12:50:51 -07007956 PyObject *result = NULL;
Thomas Wouters89f507f2006-12-13 04:49:30 +00007957
Larry Hastings2f936352014-08-05 14:04:04 +10007958 /* First get a handle to the reparse point */
7959 Py_BEGIN_ALLOW_THREADS
7960 reparse_point_handle = CreateFileW(
Serhiy Storchaka12a69db2018-09-17 15:38:27 +03007961 path->wide,
Larry Hastings2f936352014-08-05 14:04:04 +10007962 0,
7963 0,
7964 0,
7965 OPEN_EXISTING,
7966 FILE_FLAG_OPEN_REPARSE_POINT|FILE_FLAG_BACKUP_SEMANTICS,
7967 0);
Steve Dowerdf2d4a62019-08-21 15:27:33 -07007968 if (reparse_point_handle != INVALID_HANDLE_VALUE) {
7969 /* New call DeviceIoControl to read the reparse point */
7970 io_result = DeviceIoControl(
7971 reparse_point_handle,
7972 FSCTL_GET_REPARSE_POINT,
7973 0, 0, /* in buffer */
7974 target_buffer, sizeof(target_buffer),
7975 &n_bytes_returned,
7976 0 /* we're not using OVERLAPPED_IO */
7977 );
7978 CloseHandle(reparse_point_handle);
Berker Peksage0b5b202018-08-15 13:03:41 +03007979 }
Larry Hastings2f936352014-08-05 14:04:04 +10007980 Py_END_ALLOW_THREADS
7981
Berker Peksage0b5b202018-08-15 13:03:41 +03007982 if (io_result == 0) {
Serhiy Storchaka12a69db2018-09-17 15:38:27 +03007983 return path_error(path);
Berker Peksage0b5b202018-08-15 13:03:41 +03007984 }
Larry Hastings2f936352014-08-05 14:04:04 +10007985
Steve Dowerdf2d4a62019-08-21 15:27:33 -07007986 wchar_t *name = NULL;
7987 Py_ssize_t nameLen = 0;
7988 if (rdb->ReparseTag == IO_REPARSE_TAG_SYMLINK)
Larry Hastings2f936352014-08-05 14:04:04 +10007989 {
Steve Dowerdf2d4a62019-08-21 15:27:33 -07007990 name = (wchar_t *)((char*)rdb->SymbolicLinkReparseBuffer.PathBuffer +
7991 rdb->SymbolicLinkReparseBuffer.SubstituteNameOffset);
7992 nameLen = rdb->SymbolicLinkReparseBuffer.SubstituteNameLength / sizeof(wchar_t);
Larry Hastings2f936352014-08-05 14:04:04 +10007993 }
Steve Dowerdf2d4a62019-08-21 15:27:33 -07007994 else if (rdb->ReparseTag == IO_REPARSE_TAG_MOUNT_POINT)
7995 {
7996 name = (wchar_t *)((char*)rdb->MountPointReparseBuffer.PathBuffer +
7997 rdb->MountPointReparseBuffer.SubstituteNameOffset);
7998 nameLen = rdb->MountPointReparseBuffer.SubstituteNameLength / sizeof(wchar_t);
7999 }
8000 else
8001 {
8002 PyErr_SetString(PyExc_ValueError, "not a symbolic link");
8003 }
8004 if (name) {
8005 if (nameLen > 4 && wcsncmp(name, L"\\??\\", 4) == 0) {
8006 /* Our buffer is mutable, so this is okay */
8007 name[1] = L'\\';
8008 }
8009 result = PyUnicode_FromWideChar(name, nameLen);
Steve Dower993ac922019-09-03 12:50:51 -07008010 if (result && path->narrow) {
Steve Dowerdf2d4a62019-08-21 15:27:33 -07008011 Py_SETREF(result, PyUnicode_EncodeFSDefault(result));
8012 }
Berker Peksage0b5b202018-08-15 13:03:41 +03008013 }
Serhiy Storchaka12a69db2018-09-17 15:38:27 +03008014 return result;
Berker Peksage0b5b202018-08-15 13:03:41 +03008015#endif
Larry Hastings2f936352014-08-05 14:04:04 +10008016}
Berker Peksage0b5b202018-08-15 13:03:41 +03008017#endif /* defined(HAVE_READLINK) || defined(MS_WINDOWS) */
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008018
Larry Hastings9cf065c2012-06-22 16:30:09 -07008019#ifdef HAVE_SYMLINK
Larry Hastings9cf065c2012-06-22 16:30:09 -07008020
8021#if defined(MS_WINDOWS)
8022
Steve Dower6921e732018-03-05 14:26:08 -08008023/* Remove the last portion of the path - return 0 on success */
8024static int
Victor Stinner31b3b922013-06-05 01:49:17 +02008025_dirnameW(WCHAR *path)
8026{
Jason R. Coombs3a092862013-05-27 23:21:28 -04008027 WCHAR *ptr;
Steve Dower6921e732018-03-05 14:26:08 -08008028 size_t length = wcsnlen_s(path, MAX_PATH);
8029 if (length == MAX_PATH) {
8030 return -1;
8031 }
Jason R. Coombs3a092862013-05-27 23:21:28 -04008032
8033 /* walk the path from the end until a backslash is encountered */
Steve Dower6921e732018-03-05 14:26:08 -08008034 for(ptr = path + length; ptr != path; ptr--) {
8035 if (*ptr == L'\\' || *ptr == L'/') {
Jason R. Coombs3a092862013-05-27 23:21:28 -04008036 break;
Steve Dower6921e732018-03-05 14:26:08 -08008037 }
Jason R. Coombs3a092862013-05-27 23:21:28 -04008038 }
8039 *ptr = 0;
Steve Dower6921e732018-03-05 14:26:08 -08008040 return 0;
Jason R. Coombs3a092862013-05-27 23:21:28 -04008041}
8042
Victor Stinner31b3b922013-06-05 01:49:17 +02008043/* Is this path absolute? */
8044static int
8045_is_absW(const WCHAR *path)
8046{
Steve Dower6921e732018-03-05 14:26:08 -08008047 return path[0] == L'\\' || path[0] == L'/' ||
8048 (path[0] && path[1] == L':');
Jason R. Coombs3a092862013-05-27 23:21:28 -04008049}
8050
Steve Dower6921e732018-03-05 14:26:08 -08008051/* join root and rest with a backslash - return 0 on success */
8052static int
Victor Stinner31b3b922013-06-05 01:49:17 +02008053_joinW(WCHAR *dest_path, const WCHAR *root, const WCHAR *rest)
8054{
Victor Stinner31b3b922013-06-05 01:49:17 +02008055 if (_is_absW(rest)) {
Steve Dower6921e732018-03-05 14:26:08 -08008056 return wcscpy_s(dest_path, MAX_PATH, rest);
Jason R. Coombs3a092862013-05-27 23:21:28 -04008057 }
8058
Steve Dower6921e732018-03-05 14:26:08 -08008059 if (wcscpy_s(dest_path, MAX_PATH, root)) {
8060 return -1;
Jason R. Coombs3a092862013-05-27 23:21:28 -04008061 }
Steve Dower6921e732018-03-05 14:26:08 -08008062
8063 if (dest_path[0] && wcscat_s(dest_path, MAX_PATH, L"\\")) {
8064 return -1;
8065 }
8066
8067 return wcscat_s(dest_path, MAX_PATH, rest);
Jason R. Coombs3a092862013-05-27 23:21:28 -04008068}
8069
Victor Stinner31b3b922013-06-05 01:49:17 +02008070/* Return True if the path at src relative to dest is a directory */
8071static int
Serhiy Storchakadeab18d2016-05-07 16:45:18 +03008072_check_dirW(LPCWSTR src, LPCWSTR dest)
Jason R. Coombs3a092862013-05-27 23:21:28 -04008073{
Jason R. Coombs3a092862013-05-27 23:21:28 -04008074 WIN32_FILE_ATTRIBUTE_DATA src_info;
8075 WCHAR dest_parent[MAX_PATH];
8076 WCHAR src_resolved[MAX_PATH] = L"";
8077
8078 /* dest_parent = os.path.dirname(dest) */
Steve Dower6921e732018-03-05 14:26:08 -08008079 if (wcscpy_s(dest_parent, MAX_PATH, dest) ||
8080 _dirnameW(dest_parent)) {
8081 return 0;
8082 }
Jason R. Coombs3a092862013-05-27 23:21:28 -04008083 /* src_resolved = os.path.join(dest_parent, src) */
Steve Dower6921e732018-03-05 14:26:08 -08008084 if (_joinW(src_resolved, dest_parent, src)) {
8085 return 0;
8086 }
Jason R. Coombs3a092862013-05-27 23:21:28 -04008087 return (
8088 GetFileAttributesExW(src_resolved, GetFileExInfoStandard, &src_info)
8089 && src_info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY
8090 );
8091}
Larry Hastings9cf065c2012-06-22 16:30:09 -07008092#endif
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008093
Larry Hastings2f936352014-08-05 14:04:04 +10008094
8095/*[clinic input]
8096os.symlink
8097 src: path_t
8098 dst: path_t
8099 target_is_directory: bool = False
8100 *
8101 dir_fd: dir_fd(requires='symlinkat')=None
8102
8103# "symlink(src, dst, target_is_directory=False, *, dir_fd=None)\n\n\
8104
8105Create a symbolic link pointing to src named dst.
8106
8107target_is_directory is required on Windows if the target is to be
8108 interpreted as a directory. (On Windows, symlink requires
8109 Windows 6.0 or greater, and raises a NotImplementedError otherwise.)
8110 target_is_directory is ignored on non-Windows platforms.
8111
8112If dir_fd is not None, it should be a file descriptor open to a directory,
8113 and path should be relative; path will then be relative to that directory.
8114dir_fd may not be implemented on your platform.
8115 If it is unavailable, using it will raise a NotImplementedError.
8116
8117[clinic start generated code]*/
8118
Larry Hastings2f936352014-08-05 14:04:04 +10008119static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008120os_symlink_impl(PyObject *module, path_t *src, path_t *dst,
Larry Hastings89964c42015-04-14 18:07:59 -04008121 int target_is_directory, int dir_fd)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008122/*[clinic end generated code: output=08ca9f3f3cf960f6 input=e820ec4472547bc3]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008123{
Larry Hastings9cf065c2012-06-22 16:30:09 -07008124#ifdef MS_WINDOWS
8125 DWORD result;
Vidar Tonaas Fauske0e107662019-04-09 20:19:46 +02008126 DWORD flags = 0;
8127
8128 /* Assumed true, set to false if detected to not be available. */
8129 static int windows_has_symlink_unprivileged_flag = TRUE;
Larry Hastings9cf065c2012-06-22 16:30:09 -07008130#else
8131 int result;
8132#endif
8133
Larry Hastings9cf065c2012-06-22 16:30:09 -07008134#ifdef MS_WINDOWS
Larry Hastings9cf065c2012-06-22 16:30:09 -07008135
Vidar Tonaas Fauske0e107662019-04-09 20:19:46 +02008136 if (windows_has_symlink_unprivileged_flag) {
8137 /* Allow non-admin symlinks if system allows it. */
8138 flags |= SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE;
8139 }
Jason R. Coombs3a092862013-05-27 23:21:28 -04008140
Larry Hastings9cf065c2012-06-22 16:30:09 -07008141 Py_BEGIN_ALLOW_THREADS
Steve Dower6921e732018-03-05 14:26:08 -08008142 _Py_BEGIN_SUPPRESS_IPH
Vidar Tonaas Fauske0e107662019-04-09 20:19:46 +02008143 /* if src is a directory, ensure flags==1 (target_is_directory bit) */
8144 if (target_is_directory || _check_dirW(src->wide, dst->wide)) {
8145 flags |= SYMBOLIC_LINK_FLAG_DIRECTORY;
8146 }
8147
8148 result = CreateSymbolicLinkW(dst->wide, src->wide, flags);
Steve Dower6921e732018-03-05 14:26:08 -08008149 _Py_END_SUPPRESS_IPH
Larry Hastings9cf065c2012-06-22 16:30:09 -07008150 Py_END_ALLOW_THREADS
8151
Vidar Tonaas Fauske0e107662019-04-09 20:19:46 +02008152 if (windows_has_symlink_unprivileged_flag && !result &&
8153 ERROR_INVALID_PARAMETER == GetLastError()) {
8154
8155 Py_BEGIN_ALLOW_THREADS
8156 _Py_BEGIN_SUPPRESS_IPH
8157 /* This error might be caused by
8158 SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE not being supported.
8159 Try again, and update windows_has_symlink_unprivileged_flag if we
8160 are successful this time.
8161
8162 NOTE: There is a risk of a race condition here if there are other
8163 conditions than the flag causing ERROR_INVALID_PARAMETER, and
8164 another process (or thread) changes that condition in between our
8165 calls to CreateSymbolicLink.
8166 */
8167 flags &= ~(SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE);
8168 result = CreateSymbolicLinkW(dst->wide, src->wide, flags);
8169 _Py_END_SUPPRESS_IPH
8170 Py_END_ALLOW_THREADS
8171
8172 if (result || ERROR_INVALID_PARAMETER != GetLastError()) {
8173 windows_has_symlink_unprivileged_flag = FALSE;
8174 }
8175 }
8176
Larry Hastings2f936352014-08-05 14:04:04 +10008177 if (!result)
8178 return path_error2(src, dst);
Larry Hastings9cf065c2012-06-22 16:30:09 -07008179
8180#else
8181
Steve Dower6921e732018-03-05 14:26:08 -08008182 if ((src->narrow && dst->wide) || (src->wide && dst->narrow)) {
8183 PyErr_SetString(PyExc_ValueError,
8184 "symlink: src and dst must be the same type");
8185 return NULL;
8186 }
8187
Larry Hastings9cf065c2012-06-22 16:30:09 -07008188 Py_BEGIN_ALLOW_THREADS
8189#if HAVE_SYMLINKAT
8190 if (dir_fd != DEFAULT_DIR_FD)
Larry Hastings2f936352014-08-05 14:04:04 +10008191 result = symlinkat(src->narrow, dir_fd, dst->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07008192 else
8193#endif
Larry Hastings2f936352014-08-05 14:04:04 +10008194 result = symlink(src->narrow, dst->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07008195 Py_END_ALLOW_THREADS
8196
Larry Hastings2f936352014-08-05 14:04:04 +10008197 if (result)
8198 return path_error2(src, dst);
Larry Hastings9cf065c2012-06-22 16:30:09 -07008199#endif
8200
Larry Hastings2f936352014-08-05 14:04:04 +10008201 Py_RETURN_NONE;
Guido van Rossumbfaf3d61997-12-29 20:02:27 +00008202}
8203#endif /* HAVE_SYMLINK */
8204
Larry Hastings9cf065c2012-06-22 16:30:09 -07008205
Brian Curtind40e6f72010-07-08 21:39:08 +00008206
Guido van Rossumbfaf3d61997-12-29 20:02:27 +00008207
Larry Hastings605a62d2012-06-24 04:33:36 -07008208static PyStructSequence_Field times_result_fields[] = {
8209 {"user", "user time"},
8210 {"system", "system time"},
8211 {"children_user", "user time of children"},
8212 {"children_system", "system time of children"},
8213 {"elapsed", "elapsed time since an arbitrary point in the past"},
8214 {NULL}
8215};
8216
8217PyDoc_STRVAR(times_result__doc__,
8218"times_result: Result from os.times().\n\n\
8219This object may be accessed either as a tuple of\n\
8220 (user, system, children_user, children_system, elapsed),\n\
8221or via the attributes user, system, children_user, children_system,\n\
8222and elapsed.\n\
8223\n\
8224See os.times for more information.");
8225
8226static PyStructSequence_Desc times_result_desc = {
8227 "times_result", /* name */
8228 times_result__doc__, /* doc */
8229 times_result_fields,
8230 5
8231};
8232
Antoine Pitrouf3923e92012-07-24 21:23:53 +02008233#ifdef MS_WINDOWS
8234#define HAVE_TIMES /* mandatory, for the method table */
8235#endif
Larry Hastings605a62d2012-06-24 04:33:36 -07008236
Antoine Pitrouf3923e92012-07-24 21:23:53 +02008237#ifdef HAVE_TIMES
Larry Hastings605a62d2012-06-24 04:33:36 -07008238
8239static PyObject *
8240build_times_result(double user, double system,
8241 double children_user, double children_system,
8242 double elapsed)
8243{
Eddie Elizondob3966632019-11-05 07:16:14 -08008244 PyObject *TimesResultType = _posixstate_global->TimesResultType;
8245 PyObject *value = PyStructSequence_New((PyTypeObject *)TimesResultType);
Larry Hastings605a62d2012-06-24 04:33:36 -07008246 if (value == NULL)
8247 return NULL;
8248
8249#define SET(i, field) \
8250 { \
8251 PyObject *o = PyFloat_FromDouble(field); \
8252 if (!o) { \
8253 Py_DECREF(value); \
8254 return NULL; \
8255 } \
8256 PyStructSequence_SET_ITEM(value, i, o); \
8257 } \
8258
8259 SET(0, user);
8260 SET(1, system);
8261 SET(2, children_user);
8262 SET(3, children_system);
8263 SET(4, elapsed);
8264
8265#undef SET
8266
8267 return value;
8268}
8269
Larry Hastings605a62d2012-06-24 04:33:36 -07008270
Larry Hastings2f936352014-08-05 14:04:04 +10008271#ifndef MS_WINDOWS
8272#define NEED_TICKS_PER_SECOND
8273static long ticks_per_second = -1;
8274#endif /* MS_WINDOWS */
8275
8276/*[clinic input]
8277os.times
8278
8279Return a collection containing process timing information.
8280
8281The object returned behaves like a named tuple with these fields:
8282 (utime, stime, cutime, cstime, elapsed_time)
8283All fields are floating point numbers.
8284[clinic start generated code]*/
8285
Larry Hastings2f936352014-08-05 14:04:04 +10008286static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008287os_times_impl(PyObject *module)
8288/*[clinic end generated code: output=35f640503557d32a input=2bf9df3d6ab2e48b]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008289#ifdef MS_WINDOWS
Guido van Rossum14ed0b21994-09-29 09:50:09 +00008290{
Victor Stinner8c62be82010-05-06 00:08:46 +00008291 FILETIME create, exit, kernel, user;
8292 HANDLE hProc;
8293 hProc = GetCurrentProcess();
8294 GetProcessTimes(hProc, &create, &exit, &kernel, &user);
8295 /* The fields of a FILETIME structure are the hi and lo part
8296 of a 64-bit value expressed in 100 nanosecond units.
8297 1e7 is one second in such units; 1e-7 the inverse.
8298 429.4967296 is 2**32 / 1e7 or 2**32 * 1e-7.
8299 */
Larry Hastings605a62d2012-06-24 04:33:36 -07008300 return build_times_result(
Victor Stinner8c62be82010-05-06 00:08:46 +00008301 (double)(user.dwHighDateTime*429.4967296 +
8302 user.dwLowDateTime*1e-7),
8303 (double)(kernel.dwHighDateTime*429.4967296 +
8304 kernel.dwLowDateTime*1e-7),
8305 (double)0,
8306 (double)0,
8307 (double)0);
Guido van Rossum14ed0b21994-09-29 09:50:09 +00008308}
Larry Hastings2f936352014-08-05 14:04:04 +10008309#else /* MS_WINDOWS */
Antoine Pitrouf3923e92012-07-24 21:23:53 +02008310{
Larry Hastings2f936352014-08-05 14:04:04 +10008311
8312
Antoine Pitrouf3923e92012-07-24 21:23:53 +02008313 struct tms t;
8314 clock_t c;
8315 errno = 0;
8316 c = times(&t);
8317 if (c == (clock_t) -1)
8318 return posix_error();
8319 return build_times_result(
8320 (double)t.tms_utime / ticks_per_second,
8321 (double)t.tms_stime / ticks_per_second,
8322 (double)t.tms_cutime / ticks_per_second,
8323 (double)t.tms_cstime / ticks_per_second,
8324 (double)c / ticks_per_second);
8325}
Larry Hastings2f936352014-08-05 14:04:04 +10008326#endif /* MS_WINDOWS */
Antoine Pitrouf3923e92012-07-24 21:23:53 +02008327#endif /* HAVE_TIMES */
8328
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008329
Martin v. Löwis49ee14d2003-11-10 06:35:36 +00008330#ifdef HAVE_GETSID
Larry Hastings2f936352014-08-05 14:04:04 +10008331/*[clinic input]
8332os.getsid
8333
8334 pid: pid_t
8335 /
8336
8337Call the system call getsid(pid) and return the result.
8338[clinic start generated code]*/
8339
Larry Hastings2f936352014-08-05 14:04:04 +10008340static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008341os_getsid_impl(PyObject *module, pid_t pid)
8342/*[clinic end generated code: output=112deae56b306460 input=eeb2b923a30ce04e]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008343{
Victor Stinner8c62be82010-05-06 00:08:46 +00008344 int sid;
Victor Stinner8c62be82010-05-06 00:08:46 +00008345 sid = getsid(pid);
8346 if (sid < 0)
8347 return posix_error();
8348 return PyLong_FromLong((long)sid);
Martin v. Löwis49ee14d2003-11-10 06:35:36 +00008349}
8350#endif /* HAVE_GETSID */
8351
8352
Guido van Rossumb6775db1994-08-01 11:34:53 +00008353#ifdef HAVE_SETSID
Larry Hastings2f936352014-08-05 14:04:04 +10008354/*[clinic input]
8355os.setsid
8356
8357Call the system call setsid().
8358[clinic start generated code]*/
8359
Larry Hastings2f936352014-08-05 14:04:04 +10008360static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008361os_setsid_impl(PyObject *module)
8362/*[clinic end generated code: output=e2ddedd517086d77 input=5fff45858e2f0776]*/
Guido van Rossumc2670a01992-09-13 20:07:29 +00008363{
Victor Stinner8c62be82010-05-06 00:08:46 +00008364 if (setsid() < 0)
8365 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10008366 Py_RETURN_NONE;
Guido van Rossumc2670a01992-09-13 20:07:29 +00008367}
Guido van Rossumb6775db1994-08-01 11:34:53 +00008368#endif /* HAVE_SETSID */
Guido van Rossumc2670a01992-09-13 20:07:29 +00008369
Larry Hastings2f936352014-08-05 14:04:04 +10008370
Guido van Rossumb6775db1994-08-01 11:34:53 +00008371#ifdef HAVE_SETPGID
Larry Hastings2f936352014-08-05 14:04:04 +10008372/*[clinic input]
8373os.setpgid
8374
8375 pid: pid_t
8376 pgrp: pid_t
8377 /
8378
8379Call the system call setpgid(pid, pgrp).
8380[clinic start generated code]*/
8381
Larry Hastings2f936352014-08-05 14:04:04 +10008382static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008383os_setpgid_impl(PyObject *module, pid_t pid, pid_t pgrp)
8384/*[clinic end generated code: output=6461160319a43d6a input=fceb395eca572e1a]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008385{
Victor Stinner8c62be82010-05-06 00:08:46 +00008386 if (setpgid(pid, pgrp) < 0)
8387 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10008388 Py_RETURN_NONE;
Guido van Rossumc2670a01992-09-13 20:07:29 +00008389}
Guido van Rossumb6775db1994-08-01 11:34:53 +00008390#endif /* HAVE_SETPGID */
Guido van Rossumc2670a01992-09-13 20:07:29 +00008391
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008392
Guido van Rossumb6775db1994-08-01 11:34:53 +00008393#ifdef HAVE_TCGETPGRP
Larry Hastings2f936352014-08-05 14:04:04 +10008394/*[clinic input]
8395os.tcgetpgrp
8396
8397 fd: int
8398 /
8399
8400Return the process group associated with the terminal specified by fd.
8401[clinic start generated code]*/
8402
Larry Hastings2f936352014-08-05 14:04:04 +10008403static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008404os_tcgetpgrp_impl(PyObject *module, int fd)
8405/*[clinic end generated code: output=f865e88be86c272b input=7f6c18eac10ada86]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008406{
8407 pid_t pgid = tcgetpgrp(fd);
Victor Stinner8c62be82010-05-06 00:08:46 +00008408 if (pgid < 0)
8409 return posix_error();
8410 return PyLong_FromPid(pgid);
Guido van Rossum7066dd71992-09-17 17:54:56 +00008411}
Guido van Rossumb6775db1994-08-01 11:34:53 +00008412#endif /* HAVE_TCGETPGRP */
Guido van Rossum7066dd71992-09-17 17:54:56 +00008413
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008414
Guido van Rossumb6775db1994-08-01 11:34:53 +00008415#ifdef HAVE_TCSETPGRP
Larry Hastings2f936352014-08-05 14:04:04 +10008416/*[clinic input]
8417os.tcsetpgrp
8418
8419 fd: int
8420 pgid: pid_t
8421 /
8422
8423Set the process group associated with the terminal specified by fd.
8424[clinic start generated code]*/
8425
Larry Hastings2f936352014-08-05 14:04:04 +10008426static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008427os_tcsetpgrp_impl(PyObject *module, int fd, pid_t pgid)
8428/*[clinic end generated code: output=f1821a381b9daa39 input=5bdc997c6a619020]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008429{
Victor Stinner8c62be82010-05-06 00:08:46 +00008430 if (tcsetpgrp(fd, pgid) < 0)
8431 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10008432 Py_RETURN_NONE;
Guido van Rossum7066dd71992-09-17 17:54:56 +00008433}
Guido van Rossumb6775db1994-08-01 11:34:53 +00008434#endif /* HAVE_TCSETPGRP */
Guido van Rossum22db57e1992-04-05 14:25:30 +00008435
Guido van Rossum687dd131993-05-17 08:34:16 +00008436/* Functions acting on file descriptors */
8437
Victor Stinnerdaf45552013-08-28 00:53:59 +02008438#ifdef O_CLOEXEC
8439extern int _Py_open_cloexec_works;
8440#endif
8441
Larry Hastings2f936352014-08-05 14:04:04 +10008442
8443/*[clinic input]
8444os.open -> int
8445 path: path_t
8446 flags: int
8447 mode: int = 0o777
8448 *
8449 dir_fd: dir_fd(requires='openat') = None
8450
8451# "open(path, flags, mode=0o777, *, dir_fd=None)\n\n\
8452
8453Open a file for low level IO. Returns a file descriptor (integer).
8454
8455If dir_fd is not None, it should be a file descriptor open to a directory,
8456 and path should be relative; path will then be relative to that directory.
8457dir_fd may not be implemented on your platform.
8458 If it is unavailable, using it will raise a NotImplementedError.
8459[clinic start generated code]*/
8460
Larry Hastings2f936352014-08-05 14:04:04 +10008461static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008462os_open_impl(PyObject *module, path_t *path, int flags, int mode, int dir_fd)
8463/*[clinic end generated code: output=abc7227888c8bc73 input=ad8623b29acd2934]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008464{
8465 int fd;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008466 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10008467
Victor Stinnerdaf45552013-08-28 00:53:59 +02008468#ifdef O_CLOEXEC
8469 int *atomic_flag_works = &_Py_open_cloexec_works;
8470#elif !defined(MS_WINDOWS)
8471 int *atomic_flag_works = NULL;
8472#endif
Mark Hammondc2e85bd2002-10-03 05:10:39 +00008473
Victor Stinnerdaf45552013-08-28 00:53:59 +02008474#ifdef MS_WINDOWS
8475 flags |= O_NOINHERIT;
8476#elif defined(O_CLOEXEC)
8477 flags |= O_CLOEXEC;
8478#endif
8479
Steve Dowerb82e17e2019-05-23 08:45:22 -07008480 if (PySys_Audit("open", "OOi", path->object, Py_None, flags) < 0) {
8481 return -1;
8482 }
8483
Steve Dower8fc89802015-04-12 00:26:27 -04008484 _Py_BEGIN_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008485 do {
8486 Py_BEGIN_ALLOW_THREADS
Larry Hastings9cf065c2012-06-22 16:30:09 -07008487#ifdef MS_WINDOWS
Steve Dowercc16be82016-09-08 10:35:16 -07008488 fd = _wopen(path->wide, flags, mode);
Steve Dower6230aaf2016-09-09 09:03:15 -07008489#else
Larry Hastings9cf065c2012-06-22 16:30:09 -07008490#ifdef HAVE_OPENAT
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008491 if (dir_fd != DEFAULT_DIR_FD)
8492 fd = openat(dir_fd, path->narrow, flags, mode);
8493 else
Steve Dower6230aaf2016-09-09 09:03:15 -07008494#endif /* HAVE_OPENAT */
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008495 fd = open(path->narrow, flags, mode);
Steve Dower6230aaf2016-09-09 09:03:15 -07008496#endif /* !MS_WINDOWS */
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008497 Py_END_ALLOW_THREADS
8498 } while (fd < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Steve Dower8fc89802015-04-12 00:26:27 -04008499 _Py_END_SUPPRESS_IPH
Guido van Rossum687dd131993-05-17 08:34:16 +00008500
Victor Stinnerd3ffd322015-09-15 10:11:03 +02008501 if (fd < 0) {
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008502 if (!async_err)
8503 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, path->object);
Larry Hastings2f936352014-08-05 14:04:04 +10008504 return -1;
Larry Hastings9cf065c2012-06-22 16:30:09 -07008505 }
8506
Victor Stinnerdaf45552013-08-28 00:53:59 +02008507#ifndef MS_WINDOWS
8508 if (_Py_set_inheritable(fd, 0, atomic_flag_works) < 0) {
8509 close(fd);
Larry Hastings2f936352014-08-05 14:04:04 +10008510 return -1;
Victor Stinnerdaf45552013-08-28 00:53:59 +02008511 }
8512#endif
8513
Larry Hastings2f936352014-08-05 14:04:04 +10008514 return fd;
8515}
8516
8517
8518/*[clinic input]
8519os.close
8520
8521 fd: int
8522
8523Close a file descriptor.
8524[clinic start generated code]*/
8525
Barry Warsaw53699e91996-12-10 23:23:01 +00008526static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008527os_close_impl(PyObject *module, int fd)
8528/*[clinic end generated code: output=2fe4e93602822c14 input=2bc42451ca5c3223]*/
Guido van Rossum687dd131993-05-17 08:34:16 +00008529{
Larry Hastings2f936352014-08-05 14:04:04 +10008530 int res;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008531 /* We do not want to retry upon EINTR: see http://lwn.net/Articles/576478/
8532 * and http://linux.derkeiler.com/Mailing-Lists/Kernel/2005-09/3000.html
8533 * for more details.
8534 */
Victor Stinner8c62be82010-05-06 00:08:46 +00008535 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04008536 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00008537 res = close(fd);
Steve Dower8fc89802015-04-12 00:26:27 -04008538 _Py_END_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00008539 Py_END_ALLOW_THREADS
8540 if (res < 0)
8541 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10008542 Py_RETURN_NONE;
Guido van Rossum687dd131993-05-17 08:34:16 +00008543}
8544
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008545
Jakub Kulíke20134f2019-09-11 17:11:57 +02008546#ifdef HAVE_FDWALK
8547static int
8548_fdwalk_close_func(void *lohi, int fd)
8549{
8550 int lo = ((int *)lohi)[0];
8551 int hi = ((int *)lohi)[1];
8552
8553 if (fd >= hi)
8554 return 1;
8555 else if (fd >= lo)
8556 close(fd);
8557 return 0;
8558}
8559#endif /* HAVE_FDWALK */
8560
Larry Hastings2f936352014-08-05 14:04:04 +10008561/*[clinic input]
8562os.closerange
8563
8564 fd_low: int
8565 fd_high: int
8566 /
8567
8568Closes all file descriptors in [fd_low, fd_high), ignoring errors.
8569[clinic start generated code]*/
8570
Larry Hastings2f936352014-08-05 14:04:04 +10008571static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008572os_closerange_impl(PyObject *module, int fd_low, int fd_high)
8573/*[clinic end generated code: output=0ce5c20fcda681c2 input=5855a3d053ebd4ec]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008574{
Jakub Kulíke20134f2019-09-11 17:11:57 +02008575#ifdef HAVE_FDWALK
8576 int lohi[2];
8577#else
Larry Hastings2f936352014-08-05 14:04:04 +10008578 int i;
Jakub Kulíke20134f2019-09-11 17:11:57 +02008579#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00008580 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04008581 _Py_BEGIN_SUPPRESS_IPH
Jakub Kulíke20134f2019-09-11 17:11:57 +02008582#ifdef HAVE_FDWALK
8583 lohi[0] = Py_MAX(fd_low, 0);
8584 lohi[1] = fd_high;
8585 fdwalk(_fdwalk_close_func, lohi);
8586#else
Benjamin Peterson207116b2016-09-08 11:28:06 -07008587 for (i = Py_MAX(fd_low, 0); i < fd_high; i++)
Steve Dower940f33a2016-09-08 11:21:54 -07008588 close(i);
Jakub Kulíke20134f2019-09-11 17:11:57 +02008589#endif
Steve Dower8fc89802015-04-12 00:26:27 -04008590 _Py_END_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00008591 Py_END_ALLOW_THREADS
8592 Py_RETURN_NONE;
Christian Heimesfdab48e2008-01-20 09:06:41 +00008593}
8594
8595
Larry Hastings2f936352014-08-05 14:04:04 +10008596/*[clinic input]
8597os.dup -> int
8598
8599 fd: int
8600 /
8601
8602Return a duplicate of a file descriptor.
8603[clinic start generated code]*/
8604
Larry Hastings2f936352014-08-05 14:04:04 +10008605static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008606os_dup_impl(PyObject *module, int fd)
8607/*[clinic end generated code: output=486f4860636b2a9f input=6f10f7ea97f7852a]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008608{
8609 return _Py_dup(fd);
Guido van Rossum687dd131993-05-17 08:34:16 +00008610}
8611
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008612
Larry Hastings2f936352014-08-05 14:04:04 +10008613/*[clinic input]
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008614os.dup2 -> int
Larry Hastings2f936352014-08-05 14:04:04 +10008615 fd: int
8616 fd2: int
8617 inheritable: bool=True
8618
8619Duplicate file descriptor.
8620[clinic start generated code]*/
8621
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008622static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008623os_dup2_impl(PyObject *module, int fd, int fd2, int inheritable)
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008624/*[clinic end generated code: output=bc059d34a73404d1 input=c3cddda8922b038d]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008625{
Stéphane Wirtel3d86e482018-01-30 07:04:36 +01008626 int res = 0;
Victor Stinnerdaf45552013-08-28 00:53:59 +02008627#if defined(HAVE_DUP3) && \
8628 !(defined(HAVE_FCNTL_H) && defined(F_DUP2FD_CLOEXEC))
8629 /* dup3() is available on Linux 2.6.27+ and glibc 2.9 */
Alexey Izbyshevb3caf382018-02-20 10:25:46 +03008630 static int dup3_works = -1;
Victor Stinnerdaf45552013-08-28 00:53:59 +02008631#endif
8632
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008633 if (fd < 0 || fd2 < 0) {
8634 posix_error();
8635 return -1;
8636 }
Victor Stinnerdaf45552013-08-28 00:53:59 +02008637
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008638 /* dup2() can fail with EINTR if the target FD is already open, because it
8639 * then has to be closed. See os_close_impl() for why we don't handle EINTR
8640 * upon close(), and therefore below.
8641 */
Victor Stinnerdaf45552013-08-28 00:53:59 +02008642#ifdef MS_WINDOWS
8643 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04008644 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00008645 res = dup2(fd, fd2);
Steve Dower8fc89802015-04-12 00:26:27 -04008646 _Py_END_SUPPRESS_IPH
Victor Stinnerdaf45552013-08-28 00:53:59 +02008647 Py_END_ALLOW_THREADS
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008648 if (res < 0) {
8649 posix_error();
8650 return -1;
8651 }
8652 res = fd2; // msvcrt dup2 returns 0 on success.
Victor Stinnerdaf45552013-08-28 00:53:59 +02008653
8654 /* Character files like console cannot be make non-inheritable */
8655 if (!inheritable && _Py_set_inheritable(fd2, 0, NULL) < 0) {
8656 close(fd2);
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008657 return -1;
Victor Stinnerdaf45552013-08-28 00:53:59 +02008658 }
8659
8660#elif defined(HAVE_FCNTL_H) && defined(F_DUP2FD_CLOEXEC)
8661 Py_BEGIN_ALLOW_THREADS
8662 if (!inheritable)
8663 res = fcntl(fd, F_DUP2FD_CLOEXEC, fd2);
8664 else
8665 res = dup2(fd, fd2);
8666 Py_END_ALLOW_THREADS
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008667 if (res < 0) {
8668 posix_error();
8669 return -1;
8670 }
Victor Stinnerdaf45552013-08-28 00:53:59 +02008671
8672#else
8673
8674#ifdef HAVE_DUP3
8675 if (!inheritable && dup3_works != 0) {
8676 Py_BEGIN_ALLOW_THREADS
8677 res = dup3(fd, fd2, O_CLOEXEC);
8678 Py_END_ALLOW_THREADS
8679 if (res < 0) {
8680 if (dup3_works == -1)
8681 dup3_works = (errno != ENOSYS);
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008682 if (dup3_works) {
8683 posix_error();
8684 return -1;
8685 }
Victor Stinnerdaf45552013-08-28 00:53:59 +02008686 }
8687 }
8688
8689 if (inheritable || dup3_works == 0)
8690 {
8691#endif
8692 Py_BEGIN_ALLOW_THREADS
8693 res = dup2(fd, fd2);
8694 Py_END_ALLOW_THREADS
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008695 if (res < 0) {
8696 posix_error();
8697 return -1;
8698 }
Victor Stinnerdaf45552013-08-28 00:53:59 +02008699
8700 if (!inheritable && _Py_set_inheritable(fd2, 0, NULL) < 0) {
8701 close(fd2);
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008702 return -1;
Victor Stinnerdaf45552013-08-28 00:53:59 +02008703 }
8704#ifdef HAVE_DUP3
8705 }
8706#endif
8707
8708#endif
8709
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008710 return res;
Guido van Rossum687dd131993-05-17 08:34:16 +00008711}
8712
Larry Hastings2f936352014-08-05 14:04:04 +10008713
Ross Lagerwall7807c352011-03-17 20:20:30 +02008714#ifdef HAVE_LOCKF
Larry Hastings2f936352014-08-05 14:04:04 +10008715/*[clinic input]
8716os.lockf
8717
8718 fd: int
8719 An open file descriptor.
8720 command: int
8721 One of F_LOCK, F_TLOCK, F_ULOCK or F_TEST.
8722 length: Py_off_t
8723 The number of bytes to lock, starting at the current position.
8724 /
8725
8726Apply, test or remove a POSIX lock on an open file descriptor.
8727
8728[clinic start generated code]*/
8729
Larry Hastings2f936352014-08-05 14:04:04 +10008730static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008731os_lockf_impl(PyObject *module, int fd, int command, Py_off_t length)
8732/*[clinic end generated code: output=af7051f3e7c29651 input=65da41d2106e9b79]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008733{
8734 int res;
Ross Lagerwall7807c352011-03-17 20:20:30 +02008735
8736 Py_BEGIN_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10008737 res = lockf(fd, command, length);
Ross Lagerwall7807c352011-03-17 20:20:30 +02008738 Py_END_ALLOW_THREADS
8739
8740 if (res < 0)
8741 return posix_error();
8742
8743 Py_RETURN_NONE;
8744}
Larry Hastings2f936352014-08-05 14:04:04 +10008745#endif /* HAVE_LOCKF */
Ross Lagerwall7807c352011-03-17 20:20:30 +02008746
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008747
Larry Hastings2f936352014-08-05 14:04:04 +10008748/*[clinic input]
8749os.lseek -> Py_off_t
8750
8751 fd: int
8752 position: Py_off_t
8753 how: int
8754 /
8755
8756Set the position of a file descriptor. Return the new position.
8757
8758Return the new cursor position in number of bytes
8759relative to the beginning of the file.
8760[clinic start generated code]*/
8761
Larry Hastings2f936352014-08-05 14:04:04 +10008762static Py_off_t
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008763os_lseek_impl(PyObject *module, int fd, Py_off_t position, int how)
8764/*[clinic end generated code: output=971e1efb6b30bd2f input=902654ad3f96a6d3]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008765{
8766 Py_off_t result;
8767
Guido van Rossum687dd131993-05-17 08:34:16 +00008768#ifdef SEEK_SET
Victor Stinner8c62be82010-05-06 00:08:46 +00008769 /* Turn 0, 1, 2 into SEEK_{SET,CUR,END} */
8770 switch (how) {
Larry Hastings2f936352014-08-05 14:04:04 +10008771 case 0: how = SEEK_SET; break;
8772 case 1: how = SEEK_CUR; break;
8773 case 2: how = SEEK_END; break;
Victor Stinner8c62be82010-05-06 00:08:46 +00008774 }
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +00008775#endif /* SEEK_END */
Guido van Rossum94f6f721999-01-06 18:42:14 +00008776
Victor Stinner8c62be82010-05-06 00:08:46 +00008777 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04008778 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner14b9b112013-06-25 00:37:25 +02008779#ifdef MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +10008780 result = _lseeki64(fd, position, how);
Fred Drake699f3522000-06-29 21:12:41 +00008781#else
Larry Hastings2f936352014-08-05 14:04:04 +10008782 result = lseek(fd, position, how);
Fred Drake699f3522000-06-29 21:12:41 +00008783#endif
Steve Dower8fc89802015-04-12 00:26:27 -04008784 _Py_END_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00008785 Py_END_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10008786 if (result < 0)
8787 posix_error();
Guido van Rossum94f6f721999-01-06 18:42:14 +00008788
Larry Hastings2f936352014-08-05 14:04:04 +10008789 return result;
Guido van Rossum687dd131993-05-17 08:34:16 +00008790}
8791
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008792
Larry Hastings2f936352014-08-05 14:04:04 +10008793/*[clinic input]
8794os.read
8795 fd: int
8796 length: Py_ssize_t
8797 /
8798
8799Read from a file descriptor. Returns a bytes object.
8800[clinic start generated code]*/
8801
Larry Hastings2f936352014-08-05 14:04:04 +10008802static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008803os_read_impl(PyObject *module, int fd, Py_ssize_t length)
8804/*[clinic end generated code: output=dafbe9a5cddb987b input=1df2eaa27c0bf1d3]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008805{
Victor Stinner8c62be82010-05-06 00:08:46 +00008806 Py_ssize_t n;
8807 PyObject *buffer;
Larry Hastings2f936352014-08-05 14:04:04 +10008808
8809 if (length < 0) {
Victor Stinner8c62be82010-05-06 00:08:46 +00008810 errno = EINVAL;
8811 return posix_error();
8812 }
Larry Hastings2f936352014-08-05 14:04:04 +10008813
Victor Stinner9a0d7a72018-11-22 15:03:40 +01008814 length = Py_MIN(length, _PY_READ_MAX);
Larry Hastings2f936352014-08-05 14:04:04 +10008815
8816 buffer = PyBytes_FromStringAndSize((char *)NULL, length);
Victor Stinner8c62be82010-05-06 00:08:46 +00008817 if (buffer == NULL)
8818 return NULL;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008819
Victor Stinner66aab0c2015-03-19 22:53:20 +01008820 n = _Py_read(fd, PyBytes_AS_STRING(buffer), length);
8821 if (n == -1) {
Victor Stinner8c62be82010-05-06 00:08:46 +00008822 Py_DECREF(buffer);
Victor Stinner66aab0c2015-03-19 22:53:20 +01008823 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00008824 }
Larry Hastings2f936352014-08-05 14:04:04 +10008825
8826 if (n != length)
Victor Stinner8c62be82010-05-06 00:08:46 +00008827 _PyBytes_Resize(&buffer, n);
Larry Hastings2f936352014-08-05 14:04:04 +10008828
Victor Stinner8c62be82010-05-06 00:08:46 +00008829 return buffer;
Guido van Rossum687dd131993-05-17 08:34:16 +00008830}
8831
Ross Lagerwall7807c352011-03-17 20:20:30 +02008832#if (defined(HAVE_SENDFILE) && (defined(__FreeBSD__) || defined(__DragonFly__) \
Serhiy Storchaka9d572732018-07-31 10:24:54 +03008833 || defined(__APPLE__))) \
8834 || defined(HAVE_READV) || defined(HAVE_PREADV) || defined (HAVE_PREADV2) \
8835 || defined(HAVE_WRITEV) || defined(HAVE_PWRITEV) || defined (HAVE_PWRITEV2)
8836static int
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03008837iov_setup(struct iovec **iov, Py_buffer **buf, PyObject *seq, Py_ssize_t cnt, int type)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008838{
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03008839 Py_ssize_t i, j;
Giampaolo Rodolàacdad9a2011-03-03 16:10:51 +00008840
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008841 *iov = PyMem_New(struct iovec, cnt);
8842 if (*iov == NULL) {
8843 PyErr_NoMemory();
Victor Stinner57ddf782014-01-08 15:21:28 +01008844 return -1;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008845 }
Giampaolo Rodolàacdad9a2011-03-03 16:10:51 +00008846
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008847 *buf = PyMem_New(Py_buffer, cnt);
8848 if (*buf == NULL) {
8849 PyMem_Del(*iov);
8850 PyErr_NoMemory();
Victor Stinner57ddf782014-01-08 15:21:28 +01008851 return -1;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008852 }
8853
8854 for (i = 0; i < cnt; i++) {
Ross Lagerwall9ad63e02011-03-19 09:11:14 +02008855 PyObject *item = PySequence_GetItem(seq, i);
8856 if (item == NULL)
8857 goto fail;
8858 if (PyObject_GetBuffer(item, &(*buf)[i], type) == -1) {
8859 Py_DECREF(item);
8860 goto fail;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008861 }
Ross Lagerwall9ad63e02011-03-19 09:11:14 +02008862 Py_DECREF(item);
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008863 (*iov)[i].iov_base = (*buf)[i].buf;
Serhiy Storchaka9d572732018-07-31 10:24:54 +03008864 (*iov)[i].iov_len = (*buf)[i].len;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008865 }
Serhiy Storchaka9d572732018-07-31 10:24:54 +03008866 return 0;
Ross Lagerwall9ad63e02011-03-19 09:11:14 +02008867
8868fail:
8869 PyMem_Del(*iov);
8870 for (j = 0; j < i; j++) {
8871 PyBuffer_Release(&(*buf)[j]);
8872 }
8873 PyMem_Del(*buf);
Victor Stinner57ddf782014-01-08 15:21:28 +01008874 return -1;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008875}
8876
8877static void
8878iov_cleanup(struct iovec *iov, Py_buffer *buf, int cnt)
8879{
8880 int i;
8881 PyMem_Del(iov);
8882 for (i = 0; i < cnt; i++) {
8883 PyBuffer_Release(&buf[i]);
8884 }
8885 PyMem_Del(buf);
8886}
8887#endif
8888
Larry Hastings2f936352014-08-05 14:04:04 +10008889
Ross Lagerwall7807c352011-03-17 20:20:30 +02008890#ifdef HAVE_READV
Larry Hastings2f936352014-08-05 14:04:04 +10008891/*[clinic input]
8892os.readv -> Py_ssize_t
8893
8894 fd: int
8895 buffers: object
8896 /
8897
8898Read from a file descriptor fd into an iterable of buffers.
8899
8900The buffers should be mutable buffers accepting bytes.
8901readv will transfer data into each buffer until it is full
8902and then move on to the next buffer in the sequence to hold
8903the rest of the data.
8904
8905readv returns the total number of bytes read,
8906which may be less than the total capacity of all the buffers.
8907[clinic start generated code]*/
8908
Larry Hastings2f936352014-08-05 14:04:04 +10008909static Py_ssize_t
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008910os_readv_impl(PyObject *module, int fd, PyObject *buffers)
8911/*[clinic end generated code: output=792da062d3fcebdb input=e679eb5dbfa0357d]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008912{
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03008913 Py_ssize_t cnt, n;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008914 int async_err = 0;
Ross Lagerwall7807c352011-03-17 20:20:30 +02008915 struct iovec *iov;
8916 Py_buffer *buf;
8917
Larry Hastings2f936352014-08-05 14:04:04 +10008918 if (!PySequence_Check(buffers)) {
Ross Lagerwall7807c352011-03-17 20:20:30 +02008919 PyErr_SetString(PyExc_TypeError,
8920 "readv() arg 2 must be a sequence");
Larry Hastings2f936352014-08-05 14:04:04 +10008921 return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +02008922 }
Ross Lagerwall7807c352011-03-17 20:20:30 +02008923
Larry Hastings2f936352014-08-05 14:04:04 +10008924 cnt = PySequence_Size(buffers);
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03008925 if (cnt < 0)
8926 return -1;
Larry Hastings2f936352014-08-05 14:04:04 +10008927
8928 if (iov_setup(&iov, &buf, buffers, cnt, PyBUF_WRITABLE) < 0)
8929 return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +02008930
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008931 do {
8932 Py_BEGIN_ALLOW_THREADS
8933 n = readv(fd, iov, cnt);
8934 Py_END_ALLOW_THREADS
8935 } while (n < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Ross Lagerwall7807c352011-03-17 20:20:30 +02008936
8937 iov_cleanup(iov, buf, cnt);
Larry Hastings2f936352014-08-05 14:04:04 +10008938 if (n < 0) {
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008939 if (!async_err)
8940 posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10008941 return -1;
8942 }
Victor Stinner57ddf782014-01-08 15:21:28 +01008943
Larry Hastings2f936352014-08-05 14:04:04 +10008944 return n;
Ross Lagerwall7807c352011-03-17 20:20:30 +02008945}
Larry Hastings2f936352014-08-05 14:04:04 +10008946#endif /* HAVE_READV */
8947
Ross Lagerwall7807c352011-03-17 20:20:30 +02008948
8949#ifdef HAVE_PREAD
Larry Hastings2f936352014-08-05 14:04:04 +10008950/*[clinic input]
Larry Hastings2f936352014-08-05 14:04:04 +10008951os.pread
8952
8953 fd: int
Dong-hee Naad7736f2019-09-25 14:47:04 +09008954 length: Py_ssize_t
Larry Hastings2f936352014-08-05 14:04:04 +10008955 offset: Py_off_t
8956 /
8957
8958Read a number of bytes from a file descriptor starting at a particular offset.
8959
8960Read length bytes from file descriptor fd, starting at offset bytes from
8961the beginning of the file. The file offset remains unchanged.
8962[clinic start generated code]*/
8963
Larry Hastings2f936352014-08-05 14:04:04 +10008964static PyObject *
Dong-hee Naad7736f2019-09-25 14:47:04 +09008965os_pread_impl(PyObject *module, int fd, Py_ssize_t length, Py_off_t offset)
8966/*[clinic end generated code: output=3f875c1eef82e32f input=85cb4a5589627144]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008967{
Ross Lagerwall7807c352011-03-17 20:20:30 +02008968 Py_ssize_t n;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008969 int async_err = 0;
Ross Lagerwall7807c352011-03-17 20:20:30 +02008970 PyObject *buffer;
Ross Lagerwall7807c352011-03-17 20:20:30 +02008971
Larry Hastings2f936352014-08-05 14:04:04 +10008972 if (length < 0) {
Ross Lagerwall7807c352011-03-17 20:20:30 +02008973 errno = EINVAL;
8974 return posix_error();
8975 }
Larry Hastings2f936352014-08-05 14:04:04 +10008976 buffer = PyBytes_FromStringAndSize((char *)NULL, length);
Ross Lagerwall7807c352011-03-17 20:20:30 +02008977 if (buffer == NULL)
8978 return NULL;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008979
8980 do {
8981 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04008982 _Py_BEGIN_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008983 n = pread(fd, PyBytes_AS_STRING(buffer), length, offset);
Steve Dower8fc89802015-04-12 00:26:27 -04008984 _Py_END_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008985 Py_END_ALLOW_THREADS
8986 } while (n < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
8987
Ross Lagerwall7807c352011-03-17 20:20:30 +02008988 if (n < 0) {
8989 Py_DECREF(buffer);
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008990 return (!async_err) ? posix_error() : NULL;
Ross Lagerwall7807c352011-03-17 20:20:30 +02008991 }
Larry Hastings2f936352014-08-05 14:04:04 +10008992 if (n != length)
Ross Lagerwall7807c352011-03-17 20:20:30 +02008993 _PyBytes_Resize(&buffer, n);
8994 return buffer;
8995}
Larry Hastings2f936352014-08-05 14:04:04 +10008996#endif /* HAVE_PREAD */
Ross Lagerwall7807c352011-03-17 20:20:30 +02008997
Pablo Galindo4defba32018-01-27 16:16:37 +00008998#if defined(HAVE_PREADV) || defined (HAVE_PREADV2)
8999/*[clinic input]
9000os.preadv -> Py_ssize_t
9001
9002 fd: int
9003 buffers: object
9004 offset: Py_off_t
9005 flags: int = 0
9006 /
9007
9008Reads from a file descriptor into a number of mutable bytes-like objects.
9009
9010Combines the functionality of readv() and pread(). As readv(), it will
9011transfer data into each buffer until it is full and then move on to the next
9012buffer in the sequence to hold the rest of the data. Its fourth argument,
9013specifies the file offset at which the input operation is to be performed. It
9014will return the total number of bytes read (which can be less than the total
9015capacity of all the objects).
9016
9017The flags argument contains a bitwise OR of zero or more of the following flags:
9018
9019- RWF_HIPRI
9020- RWF_NOWAIT
9021
9022Using non-zero flags requires Linux 4.6 or newer.
9023[clinic start generated code]*/
9024
9025static Py_ssize_t
9026os_preadv_impl(PyObject *module, int fd, PyObject *buffers, Py_off_t offset,
9027 int flags)
9028/*[clinic end generated code: output=26fc9c6e58e7ada5 input=4173919dc1f7ed99]*/
9029{
9030 Py_ssize_t cnt, n;
9031 int async_err = 0;
9032 struct iovec *iov;
9033 Py_buffer *buf;
9034
9035 if (!PySequence_Check(buffers)) {
9036 PyErr_SetString(PyExc_TypeError,
9037 "preadv2() arg 2 must be a sequence");
9038 return -1;
9039 }
9040
9041 cnt = PySequence_Size(buffers);
9042 if (cnt < 0) {
9043 return -1;
9044 }
9045
9046#ifndef HAVE_PREADV2
9047 if(flags != 0) {
9048 argument_unavailable_error("preadv2", "flags");
9049 return -1;
9050 }
9051#endif
9052
9053 if (iov_setup(&iov, &buf, buffers, cnt, PyBUF_WRITABLE) < 0) {
9054 return -1;
9055 }
9056#ifdef HAVE_PREADV2
9057 do {
9058 Py_BEGIN_ALLOW_THREADS
9059 _Py_BEGIN_SUPPRESS_IPH
9060 n = preadv2(fd, iov, cnt, offset, flags);
9061 _Py_END_SUPPRESS_IPH
9062 Py_END_ALLOW_THREADS
9063 } while (n < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
9064#else
9065 do {
9066 Py_BEGIN_ALLOW_THREADS
9067 _Py_BEGIN_SUPPRESS_IPH
9068 n = preadv(fd, iov, cnt, offset);
9069 _Py_END_SUPPRESS_IPH
9070 Py_END_ALLOW_THREADS
9071 } while (n < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
9072#endif
9073
9074 iov_cleanup(iov, buf, cnt);
9075 if (n < 0) {
9076 if (!async_err) {
9077 posix_error();
9078 }
9079 return -1;
9080 }
9081
9082 return n;
9083}
9084#endif /* HAVE_PREADV */
9085
Larry Hastings2f936352014-08-05 14:04:04 +10009086
9087/*[clinic input]
9088os.write -> Py_ssize_t
9089
9090 fd: int
9091 data: Py_buffer
9092 /
9093
9094Write a bytes object to a file descriptor.
9095[clinic start generated code]*/
9096
Larry Hastings2f936352014-08-05 14:04:04 +10009097static Py_ssize_t
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009098os_write_impl(PyObject *module, int fd, Py_buffer *data)
9099/*[clinic end generated code: output=e4ef5bc904b58ef9 input=3207e28963234f3c]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009100{
Victor Stinner66aab0c2015-03-19 22:53:20 +01009101 return _Py_write(fd, data->buf, data->len);
Ross Lagerwall7807c352011-03-17 20:20:30 +02009102}
9103
9104#ifdef HAVE_SENDFILE
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009105PyDoc_STRVAR(posix_sendfile__doc__,
Serhiy Storchaka140a7d12019-10-13 11:59:31 +03009106"sendfile(out_fd, in_fd, offset, count) -> byteswritten\n\
9107sendfile(out_fd, in_fd, offset, count[, headers][, trailers], flags=0)\n\
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009108 -> byteswritten\n\
Serhiy Storchaka140a7d12019-10-13 11:59:31 +03009109Copy count bytes from file descriptor in_fd to file descriptor out_fd.");
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009110
Larry Hastings2f936352014-08-05 14:04:04 +10009111/* AC 3.5: don't bother converting, has optional group*/
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009112static PyObject *
9113posix_sendfile(PyObject *self, PyObject *args, PyObject *kwdict)
9114{
9115 int in, out;
9116 Py_ssize_t ret;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009117 int async_err = 0;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009118 off_t offset;
9119
9120#if defined(__FreeBSD__) || defined(__DragonFly__) || defined(__APPLE__)
9121#ifndef __APPLE__
9122 Py_ssize_t len;
9123#endif
9124 PyObject *headers = NULL, *trailers = NULL;
9125 Py_buffer *hbuf, *tbuf;
9126 off_t sbytes;
9127 struct sf_hdtr sf;
9128 int flags = 0;
Serhiy Storchaka140a7d12019-10-13 11:59:31 +03009129 static char *keywords[] = {"out_fd", "in_fd",
Benjamin Petersond8a43b42011-02-26 21:35:16 +00009130 "offset", "count",
9131 "headers", "trailers", "flags", NULL};
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009132
Victor Stinner6ce0dbf2013-07-07 16:32:36 +02009133 sf.headers = NULL;
9134 sf.trailers = NULL;
9135
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009136#ifdef __APPLE__
9137 if (!PyArg_ParseTupleAndKeywords(args, kwdict, "iiO&O&|OOi:sendfile",
Larry Hastings2f936352014-08-05 14:04:04 +10009138 keywords, &out, &in, Py_off_t_converter, &offset, Py_off_t_converter, &sbytes,
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009139#else
9140 if (!PyArg_ParseTupleAndKeywords(args, kwdict, "iiO&n|OOi:sendfile",
Larry Hastings2f936352014-08-05 14:04:04 +10009141 keywords, &out, &in, Py_off_t_converter, &offset, &len,
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009142#endif
9143 &headers, &trailers, &flags))
9144 return NULL;
9145 if (headers != NULL) {
9146 if (!PySequence_Check(headers)) {
9147 PyErr_SetString(PyExc_TypeError,
Martin Panter94994132015-09-09 05:29:24 +00009148 "sendfile() headers must be a sequence");
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009149 return NULL;
9150 } else {
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009151 Py_ssize_t i = PySequence_Size(headers);
9152 if (i < 0)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009153 return NULL;
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009154 if (i > INT_MAX) {
9155 PyErr_SetString(PyExc_OverflowError,
9156 "sendfile() header is too large");
9157 return NULL;
9158 }
9159 if (i > 0) {
9160 sf.hdr_cnt = (int)i;
Serhiy Storchaka9d572732018-07-31 10:24:54 +03009161 if (iov_setup(&(sf.headers), &hbuf,
9162 headers, sf.hdr_cnt, PyBUF_SIMPLE) < 0)
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009163 return NULL;
Giampaolo Rodolàacdad9a2011-03-03 16:10:51 +00009164#ifdef __APPLE__
Serhiy Storchaka9d572732018-07-31 10:24:54 +03009165 for (i = 0; i < sf.hdr_cnt; i++) {
9166 Py_ssize_t blen = sf.headers[i].iov_len;
9167# define OFF_T_MAX 0x7fffffffffffffff
9168 if (sbytes >= OFF_T_MAX - blen) {
9169 PyErr_SetString(PyExc_OverflowError,
9170 "sendfile() header is too large");
9171 return NULL;
9172 }
9173 sbytes += blen;
9174 }
Giampaolo Rodolàacdad9a2011-03-03 16:10:51 +00009175#endif
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009176 }
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009177 }
9178 }
9179 if (trailers != NULL) {
9180 if (!PySequence_Check(trailers)) {
9181 PyErr_SetString(PyExc_TypeError,
Martin Panter94994132015-09-09 05:29:24 +00009182 "sendfile() trailers must be a sequence");
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009183 return NULL;
9184 } else {
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009185 Py_ssize_t i = PySequence_Size(trailers);
9186 if (i < 0)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009187 return NULL;
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009188 if (i > INT_MAX) {
9189 PyErr_SetString(PyExc_OverflowError,
9190 "sendfile() trailer is too large");
9191 return NULL;
9192 }
9193 if (i > 0) {
9194 sf.trl_cnt = (int)i;
Serhiy Storchaka9d572732018-07-31 10:24:54 +03009195 if (iov_setup(&(sf.trailers), &tbuf,
9196 trailers, sf.trl_cnt, PyBUF_SIMPLE) < 0)
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009197 return NULL;
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009198 }
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009199 }
9200 }
9201
Steve Dower8fc89802015-04-12 00:26:27 -04009202 _Py_BEGIN_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009203 do {
9204 Py_BEGIN_ALLOW_THREADS
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009205#ifdef __APPLE__
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009206 ret = sendfile(in, out, offset, &sbytes, &sf, flags);
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009207#else
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009208 ret = sendfile(in, out, offset, len, &sf, &sbytes, flags);
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009209#endif
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009210 Py_END_ALLOW_THREADS
9211 } while (ret < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Steve Dower8fc89802015-04-12 00:26:27 -04009212 _Py_END_SUPPRESS_IPH
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009213
9214 if (sf.headers != NULL)
9215 iov_cleanup(sf.headers, hbuf, sf.hdr_cnt);
9216 if (sf.trailers != NULL)
9217 iov_cleanup(sf.trailers, tbuf, sf.trl_cnt);
9218
9219 if (ret < 0) {
9220 if ((errno == EAGAIN) || (errno == EBUSY)) {
9221 if (sbytes != 0) {
9222 // some data has been sent
9223 goto done;
9224 }
9225 else {
9226 // no data has been sent; upper application is supposed
9227 // to retry on EAGAIN or EBUSY
9228 return posix_error();
9229 }
9230 }
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009231 return (!async_err) ? posix_error() : NULL;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009232 }
9233 goto done;
9234
9235done:
9236 #if !defined(HAVE_LARGEFILE_SUPPORT)
9237 return Py_BuildValue("l", sbytes);
9238 #else
9239 return Py_BuildValue("L", sbytes);
9240 #endif
9241
9242#else
9243 Py_ssize_t count;
9244 PyObject *offobj;
Serhiy Storchaka140a7d12019-10-13 11:59:31 +03009245 static char *keywords[] = {"out_fd", "in_fd",
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009246 "offset", "count", NULL};
9247 if (!PyArg_ParseTupleAndKeywords(args, kwdict, "iiOn:sendfile",
9248 keywords, &out, &in, &offobj, &count))
9249 return NULL;
Benjamin Peterson840ef8f2016-09-07 14:45:10 -07009250#ifdef __linux__
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009251 if (offobj == Py_None) {
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009252 do {
9253 Py_BEGIN_ALLOW_THREADS
9254 ret = sendfile(out, in, NULL, count);
9255 Py_END_ALLOW_THREADS
9256 } while (ret < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009257 if (ret < 0)
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009258 return (!async_err) ? posix_error() : NULL;
Giampaolo Rodola'ff1a7352011-04-19 09:47:16 +02009259 return Py_BuildValue("n", ret);
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009260 }
9261#endif
Larry Hastings2f936352014-08-05 14:04:04 +10009262 if (!Py_off_t_converter(offobj, &offset))
Antoine Pitroudcc20b82011-02-26 13:38:35 +00009263 return NULL;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009264
9265 do {
9266 Py_BEGIN_ALLOW_THREADS
9267 ret = sendfile(out, in, &offset, count);
9268 Py_END_ALLOW_THREADS
9269 } while (ret < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009270 if (ret < 0)
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009271 return (!async_err) ? posix_error() : NULL;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009272 return Py_BuildValue("n", ret);
9273#endif
9274}
Larry Hastings2f936352014-08-05 14:04:04 +10009275#endif /* HAVE_SENDFILE */
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00009276
Larry Hastings2f936352014-08-05 14:04:04 +10009277
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +02009278#if defined(__APPLE__)
9279/*[clinic input]
9280os._fcopyfile
9281
Serhiy Storchaka140a7d12019-10-13 11:59:31 +03009282 in_fd: int
9283 out_fd: int
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +02009284 flags: int
9285 /
9286
Giampaolo Rodolac7f02a92018-06-19 08:27:29 -07009287Efficiently copy content or metadata of 2 regular file descriptors (macOS).
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +02009288[clinic start generated code]*/
9289
9290static PyObject *
Serhiy Storchaka140a7d12019-10-13 11:59:31 +03009291os__fcopyfile_impl(PyObject *module, int in_fd, int out_fd, int flags)
9292/*[clinic end generated code: output=c9d1a35a992e401b input=1e34638a86948795]*/
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +02009293{
9294 int ret;
9295
9296 Py_BEGIN_ALLOW_THREADS
Serhiy Storchaka140a7d12019-10-13 11:59:31 +03009297 ret = fcopyfile(in_fd, out_fd, NULL, flags);
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +02009298 Py_END_ALLOW_THREADS
9299 if (ret < 0)
9300 return posix_error();
9301 Py_RETURN_NONE;
9302}
9303#endif
9304
9305
Larry Hastings2f936352014-08-05 14:04:04 +10009306/*[clinic input]
9307os.fstat
9308
9309 fd : int
9310
9311Perform a stat system call on the given file descriptor.
9312
9313Like stat(), but for an open file descriptor.
9314Equivalent to os.stat(fd).
9315[clinic start generated code]*/
9316
Larry Hastings2f936352014-08-05 14:04:04 +10009317static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009318os_fstat_impl(PyObject *module, int fd)
9319/*[clinic end generated code: output=efc038cb5f654492 input=27e0e0ebbe5600c9]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009320{
Victor Stinner8c62be82010-05-06 00:08:46 +00009321 STRUCT_STAT st;
9322 int res;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009323 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10009324
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009325 do {
9326 Py_BEGIN_ALLOW_THREADS
9327 res = FSTAT(fd, &st);
9328 Py_END_ALLOW_THREADS
9329 } while (res != 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Victor Stinner8c62be82010-05-06 00:08:46 +00009330 if (res != 0) {
Martin v. Löwis14694662006-02-03 12:54:16 +00009331#ifdef MS_WINDOWS
Victor Stinnerb024e842012-10-31 22:24:06 +01009332 return PyErr_SetFromWindowsErr(0);
Martin v. Löwis14694662006-02-03 12:54:16 +00009333#else
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009334 return (!async_err) ? posix_error() : NULL;
Martin v. Löwis14694662006-02-03 12:54:16 +00009335#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00009336 }
Tim Peters5aa91602002-01-30 05:46:57 +00009337
Victor Stinner4195b5c2012-02-08 23:03:19 +01009338 return _pystat_fromstructstat(&st);
Guido van Rossum687dd131993-05-17 08:34:16 +00009339}
9340
Larry Hastings2f936352014-08-05 14:04:04 +10009341
9342/*[clinic input]
9343os.isatty -> bool
9344 fd: int
9345 /
9346
9347Return True if the fd is connected to a terminal.
9348
9349Return True if the file descriptor is an open file descriptor
9350connected to the slave end of a terminal.
9351[clinic start generated code]*/
9352
Larry Hastings2f936352014-08-05 14:04:04 +10009353static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009354os_isatty_impl(PyObject *module, int fd)
9355/*[clinic end generated code: output=6a48c8b4e644ca00 input=08ce94aa1eaf7b5e]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009356{
Steve Dower8fc89802015-04-12 00:26:27 -04009357 int return_value;
Steve Dower8fc89802015-04-12 00:26:27 -04009358 _Py_BEGIN_SUPPRESS_IPH
9359 return_value = isatty(fd);
9360 _Py_END_SUPPRESS_IPH
9361 return return_value;
Larry Hastings2f936352014-08-05 14:04:04 +10009362}
9363
9364
Guido van Rossuma4916fa1996-05-23 22:58:55 +00009365#ifdef HAVE_PIPE
Larry Hastings2f936352014-08-05 14:04:04 +10009366/*[clinic input]
9367os.pipe
9368
9369Create a pipe.
9370
9371Returns a tuple of two file descriptors:
9372 (read_fd, write_fd)
9373[clinic start generated code]*/
9374
Larry Hastings2f936352014-08-05 14:04:04 +10009375static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009376os_pipe_impl(PyObject *module)
9377/*[clinic end generated code: output=ff9b76255793b440 input=02535e8c8fa6c4d4]*/
Guido van Rossum687dd131993-05-17 08:34:16 +00009378{
Victor Stinner8c62be82010-05-06 00:08:46 +00009379 int fds[2];
Victor Stinnerdaf45552013-08-28 00:53:59 +02009380#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +00009381 HANDLE read, write;
Victor Stinnerdaf45552013-08-28 00:53:59 +02009382 SECURITY_ATTRIBUTES attr;
Victor Stinner8c62be82010-05-06 00:08:46 +00009383 BOOL ok;
Victor Stinnerdaf45552013-08-28 00:53:59 +02009384#else
9385 int res;
9386#endif
9387
9388#ifdef MS_WINDOWS
9389 attr.nLength = sizeof(attr);
9390 attr.lpSecurityDescriptor = NULL;
9391 attr.bInheritHandle = FALSE;
9392
9393 Py_BEGIN_ALLOW_THREADS
Steve Dowerc3630612016-11-19 18:41:16 -08009394 _Py_BEGIN_SUPPRESS_IPH
Victor Stinnerdaf45552013-08-28 00:53:59 +02009395 ok = CreatePipe(&read, &write, &attr, 0);
9396 if (ok) {
Benjamin Petersonca470632016-09-06 13:47:26 -07009397 fds[0] = _open_osfhandle((intptr_t)read, _O_RDONLY);
9398 fds[1] = _open_osfhandle((intptr_t)write, _O_WRONLY);
Victor Stinnerdaf45552013-08-28 00:53:59 +02009399 if (fds[0] == -1 || fds[1] == -1) {
9400 CloseHandle(read);
9401 CloseHandle(write);
9402 ok = 0;
9403 }
9404 }
Steve Dowerc3630612016-11-19 18:41:16 -08009405 _Py_END_SUPPRESS_IPH
Victor Stinnerdaf45552013-08-28 00:53:59 +02009406 Py_END_ALLOW_THREADS
9407
Victor Stinner8c62be82010-05-06 00:08:46 +00009408 if (!ok)
Victor Stinnerb024e842012-10-31 22:24:06 +01009409 return PyErr_SetFromWindowsErr(0);
Victor Stinnerdaf45552013-08-28 00:53:59 +02009410#else
9411
9412#ifdef HAVE_PIPE2
9413 Py_BEGIN_ALLOW_THREADS
9414 res = pipe2(fds, O_CLOEXEC);
9415 Py_END_ALLOW_THREADS
9416
9417 if (res != 0 && errno == ENOSYS)
9418 {
9419#endif
9420 Py_BEGIN_ALLOW_THREADS
9421 res = pipe(fds);
9422 Py_END_ALLOW_THREADS
9423
9424 if (res == 0) {
9425 if (_Py_set_inheritable(fds[0], 0, NULL) < 0) {
9426 close(fds[0]);
9427 close(fds[1]);
9428 return NULL;
9429 }
9430 if (_Py_set_inheritable(fds[1], 0, NULL) < 0) {
9431 close(fds[0]);
9432 close(fds[1]);
9433 return NULL;
9434 }
9435 }
9436#ifdef HAVE_PIPE2
9437 }
9438#endif
9439
9440 if (res != 0)
9441 return PyErr_SetFromErrno(PyExc_OSError);
9442#endif /* !MS_WINDOWS */
9443 return Py_BuildValue("(ii)", fds[0], fds[1]);
Guido van Rossum687dd131993-05-17 08:34:16 +00009444}
Guido van Rossuma4916fa1996-05-23 22:58:55 +00009445#endif /* HAVE_PIPE */
9446
Larry Hastings2f936352014-08-05 14:04:04 +10009447
Charles-François Natalidaafdd52011-05-29 20:07:40 +02009448#ifdef HAVE_PIPE2
Larry Hastings2f936352014-08-05 14:04:04 +10009449/*[clinic input]
9450os.pipe2
9451
9452 flags: int
9453 /
9454
9455Create a pipe with flags set atomically.
9456
9457Returns a tuple of two file descriptors:
9458 (read_fd, write_fd)
9459
9460flags can be constructed by ORing together one or more of these values:
9461O_NONBLOCK, O_CLOEXEC.
9462[clinic start generated code]*/
9463
Larry Hastings2f936352014-08-05 14:04:04 +10009464static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009465os_pipe2_impl(PyObject *module, int flags)
9466/*[clinic end generated code: output=25751fb43a45540f input=f261b6e7e63c6817]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009467{
Charles-François Natalidaafdd52011-05-29 20:07:40 +02009468 int fds[2];
9469 int res;
9470
Charles-François Natalidaafdd52011-05-29 20:07:40 +02009471 res = pipe2(fds, flags);
9472 if (res != 0)
9473 return posix_error();
9474 return Py_BuildValue("(ii)", fds[0], fds[1]);
9475}
9476#endif /* HAVE_PIPE2 */
9477
Larry Hastings2f936352014-08-05 14:04:04 +10009478
Ross Lagerwall7807c352011-03-17 20:20:30 +02009479#ifdef HAVE_WRITEV
Larry Hastings2f936352014-08-05 14:04:04 +10009480/*[clinic input]
9481os.writev -> Py_ssize_t
9482 fd: int
9483 buffers: object
9484 /
9485
9486Iterate over buffers, and write the contents of each to a file descriptor.
9487
9488Returns the total number of bytes written.
9489buffers must be a sequence of bytes-like objects.
9490[clinic start generated code]*/
9491
Larry Hastings2f936352014-08-05 14:04:04 +10009492static Py_ssize_t
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009493os_writev_impl(PyObject *module, int fd, PyObject *buffers)
9494/*[clinic end generated code: output=56565cfac3aac15b input=5b8d17fe4189d2fe]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009495{
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009496 Py_ssize_t cnt;
Larry Hastings2f936352014-08-05 14:04:04 +10009497 Py_ssize_t result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009498 int async_err = 0;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009499 struct iovec *iov;
9500 Py_buffer *buf;
Larry Hastings2f936352014-08-05 14:04:04 +10009501
9502 if (!PySequence_Check(buffers)) {
Ross Lagerwall7807c352011-03-17 20:20:30 +02009503 PyErr_SetString(PyExc_TypeError,
9504 "writev() arg 2 must be a sequence");
Larry Hastings2f936352014-08-05 14:04:04 +10009505 return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009506 }
Larry Hastings2f936352014-08-05 14:04:04 +10009507 cnt = PySequence_Size(buffers);
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009508 if (cnt < 0)
9509 return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009510
Larry Hastings2f936352014-08-05 14:04:04 +10009511 if (iov_setup(&iov, &buf, buffers, cnt, PyBUF_SIMPLE) < 0) {
9512 return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009513 }
9514
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009515 do {
9516 Py_BEGIN_ALLOW_THREADS
9517 result = writev(fd, iov, cnt);
9518 Py_END_ALLOW_THREADS
9519 } while (result < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Ross Lagerwall7807c352011-03-17 20:20:30 +02009520
9521 iov_cleanup(iov, buf, cnt);
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009522 if (result < 0 && !async_err)
Larry Hastings2f936352014-08-05 14:04:04 +10009523 posix_error();
Victor Stinner57ddf782014-01-08 15:21:28 +01009524
Georg Brandl306336b2012-06-24 12:55:33 +02009525 return result;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009526}
Larry Hastings2f936352014-08-05 14:04:04 +10009527#endif /* HAVE_WRITEV */
9528
9529
9530#ifdef HAVE_PWRITE
9531/*[clinic input]
9532os.pwrite -> Py_ssize_t
9533
9534 fd: int
9535 buffer: Py_buffer
9536 offset: Py_off_t
9537 /
9538
9539Write bytes to a file descriptor starting at a particular offset.
9540
9541Write buffer to fd, starting at offset bytes from the beginning of
9542the file. Returns the number of bytes writte. Does not change the
9543current file offset.
9544[clinic start generated code]*/
9545
Larry Hastings2f936352014-08-05 14:04:04 +10009546static Py_ssize_t
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009547os_pwrite_impl(PyObject *module, int fd, Py_buffer *buffer, Py_off_t offset)
9548/*[clinic end generated code: output=c74da630758ee925 input=19903f1b3dd26377]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009549{
9550 Py_ssize_t size;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009551 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10009552
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009553 do {
9554 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04009555 _Py_BEGIN_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009556 size = pwrite(fd, buffer->buf, (size_t)buffer->len, offset);
Steve Dower8fc89802015-04-12 00:26:27 -04009557 _Py_END_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009558 Py_END_ALLOW_THREADS
9559 } while (size < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Larry Hastings2f936352014-08-05 14:04:04 +10009560
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009561 if (size < 0 && !async_err)
Larry Hastings2f936352014-08-05 14:04:04 +10009562 posix_error();
9563 return size;
9564}
9565#endif /* HAVE_PWRITE */
9566
Pablo Galindo4defba32018-01-27 16:16:37 +00009567#if defined(HAVE_PWRITEV) || defined (HAVE_PWRITEV2)
9568/*[clinic input]
9569os.pwritev -> Py_ssize_t
9570
9571 fd: int
9572 buffers: object
9573 offset: Py_off_t
9574 flags: int = 0
9575 /
9576
9577Writes the contents of bytes-like objects to a file descriptor at a given offset.
9578
9579Combines the functionality of writev() and pwrite(). All buffers must be a sequence
9580of bytes-like objects. Buffers are processed in array order. Entire contents of first
9581buffer is written before proceeding to second, and so on. The operating system may
9582set a limit (sysconf() value SC_IOV_MAX) on the number of buffers that can be used.
9583This function writes the contents of each object to the file descriptor and returns
9584the total number of bytes written.
9585
9586The flags argument contains a bitwise OR of zero or more of the following flags:
9587
9588- RWF_DSYNC
9589- RWF_SYNC
9590
9591Using non-zero flags requires Linux 4.7 or newer.
9592[clinic start generated code]*/
9593
9594static Py_ssize_t
9595os_pwritev_impl(PyObject *module, int fd, PyObject *buffers, Py_off_t offset,
9596 int flags)
9597/*[clinic end generated code: output=e3dd3e9d11a6a5c7 input=803dc5ddbf0cfd3b]*/
9598{
9599 Py_ssize_t cnt;
9600 Py_ssize_t result;
9601 int async_err = 0;
9602 struct iovec *iov;
9603 Py_buffer *buf;
9604
9605 if (!PySequence_Check(buffers)) {
9606 PyErr_SetString(PyExc_TypeError,
9607 "pwritev() arg 2 must be a sequence");
9608 return -1;
9609 }
9610
9611 cnt = PySequence_Size(buffers);
9612 if (cnt < 0) {
9613 return -1;
9614 }
9615
9616#ifndef HAVE_PWRITEV2
9617 if(flags != 0) {
9618 argument_unavailable_error("pwritev2", "flags");
9619 return -1;
9620 }
9621#endif
9622
9623 if (iov_setup(&iov, &buf, buffers, cnt, PyBUF_SIMPLE) < 0) {
9624 return -1;
9625 }
9626#ifdef HAVE_PWRITEV2
9627 do {
9628 Py_BEGIN_ALLOW_THREADS
9629 _Py_BEGIN_SUPPRESS_IPH
9630 result = pwritev2(fd, iov, cnt, offset, flags);
9631 _Py_END_SUPPRESS_IPH
9632 Py_END_ALLOW_THREADS
9633 } while (result < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
9634#else
9635 do {
9636 Py_BEGIN_ALLOW_THREADS
9637 _Py_BEGIN_SUPPRESS_IPH
9638 result = pwritev(fd, iov, cnt, offset);
9639 _Py_END_SUPPRESS_IPH
9640 Py_END_ALLOW_THREADS
9641 } while (result < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
9642#endif
9643
9644 iov_cleanup(iov, buf, cnt);
9645 if (result < 0) {
9646 if (!async_err) {
9647 posix_error();
9648 }
9649 return -1;
9650 }
9651
9652 return result;
9653}
9654#endif /* HAVE_PWRITEV */
9655
Pablo Galindoaac4d032019-05-31 19:39:47 +01009656#ifdef HAVE_COPY_FILE_RANGE
9657/*[clinic input]
9658
9659os.copy_file_range
9660 src: int
9661 Source file descriptor.
9662 dst: int
9663 Destination file descriptor.
9664 count: Py_ssize_t
9665 Number of bytes to copy.
9666 offset_src: object = None
9667 Starting offset in src.
9668 offset_dst: object = None
9669 Starting offset in dst.
9670
9671Copy count bytes from one file descriptor to another.
9672
9673If offset_src is None, then src is read from the current position;
9674respectively for offset_dst.
9675[clinic start generated code]*/
9676
9677static PyObject *
9678os_copy_file_range_impl(PyObject *module, int src, int dst, Py_ssize_t count,
9679 PyObject *offset_src, PyObject *offset_dst)
9680/*[clinic end generated code: output=1a91713a1d99fc7a input=42fdce72681b25a9]*/
9681{
9682 off_t offset_src_val, offset_dst_val;
9683 off_t *p_offset_src = NULL;
9684 off_t *p_offset_dst = NULL;
9685 Py_ssize_t ret;
9686 int async_err = 0;
9687 /* The flags argument is provided to allow
9688 * for future extensions and currently must be to 0. */
9689 int flags = 0;
Pablo Galindo4defba32018-01-27 16:16:37 +00009690
9691
Pablo Galindoaac4d032019-05-31 19:39:47 +01009692 if (count < 0) {
9693 PyErr_SetString(PyExc_ValueError, "negative value for 'count' not allowed");
9694 return NULL;
9695 }
9696
9697 if (offset_src != Py_None) {
9698 if (!Py_off_t_converter(offset_src, &offset_src_val)) {
9699 return NULL;
9700 }
9701 p_offset_src = &offset_src_val;
9702 }
9703
9704 if (offset_dst != Py_None) {
9705 if (!Py_off_t_converter(offset_dst, &offset_dst_val)) {
9706 return NULL;
9707 }
9708 p_offset_dst = &offset_dst_val;
9709 }
9710
9711 do {
9712 Py_BEGIN_ALLOW_THREADS
9713 ret = copy_file_range(src, p_offset_src, dst, p_offset_dst, count, flags);
9714 Py_END_ALLOW_THREADS
9715 } while (ret < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
9716
9717 if (ret < 0) {
9718 return (!async_err) ? posix_error() : NULL;
9719 }
9720
9721 return PyLong_FromSsize_t(ret);
9722}
9723#endif /* HAVE_COPY_FILE_RANGE*/
Larry Hastings2f936352014-08-05 14:04:04 +10009724
9725#ifdef HAVE_MKFIFO
9726/*[clinic input]
9727os.mkfifo
9728
9729 path: path_t
9730 mode: int=0o666
9731 *
9732 dir_fd: dir_fd(requires='mkfifoat')=None
9733
9734Create a "fifo" (a POSIX named pipe).
9735
9736If dir_fd is not None, it should be a file descriptor open to a directory,
9737 and path should be relative; path will then be relative to that directory.
9738dir_fd may not be implemented on your platform.
9739 If it is unavailable, using it will raise a NotImplementedError.
9740[clinic start generated code]*/
9741
Larry Hastings2f936352014-08-05 14:04:04 +10009742static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009743os_mkfifo_impl(PyObject *module, path_t *path, int mode, int dir_fd)
9744/*[clinic end generated code: output=ce41cfad0e68c940 input=73032e98a36e0e19]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009745{
9746 int result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009747 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10009748
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009749 do {
9750 Py_BEGIN_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10009751#ifdef HAVE_MKFIFOAT
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009752 if (dir_fd != DEFAULT_DIR_FD)
9753 result = mkfifoat(dir_fd, path->narrow, mode);
9754 else
Ross Lagerwall7807c352011-03-17 20:20:30 +02009755#endif
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009756 result = mkfifo(path->narrow, mode);
9757 Py_END_ALLOW_THREADS
9758 } while (result != 0 && errno == EINTR &&
9759 !(async_err = PyErr_CheckSignals()));
9760 if (result != 0)
9761 return (!async_err) ? posix_error() : NULL;
Larry Hastings2f936352014-08-05 14:04:04 +10009762
9763 Py_RETURN_NONE;
9764}
9765#endif /* HAVE_MKFIFO */
9766
9767
9768#if defined(HAVE_MKNOD) && defined(HAVE_MAKEDEV)
9769/*[clinic input]
9770os.mknod
9771
9772 path: path_t
9773 mode: int=0o600
Serhiy Storchakaacdb7c12015-01-18 11:17:39 +02009774 device: dev_t=0
Larry Hastings2f936352014-08-05 14:04:04 +10009775 *
9776 dir_fd: dir_fd(requires='mknodat')=None
9777
9778Create a node in the file system.
9779
9780Create a node in the file system (file, device special file or named pipe)
9781at path. mode specifies both the permissions to use and the
9782type of node to be created, being combined (bitwise OR) with one of
9783S_IFREG, S_IFCHR, S_IFBLK, and S_IFIFO. If S_IFCHR or S_IFBLK is set on mode,
9784device defines the newly created device special file (probably using
9785os.makedev()). Otherwise device is ignored.
9786
9787If dir_fd is not None, it should be a file descriptor open to a directory,
9788 and path should be relative; path will then be relative to that directory.
9789dir_fd may not be implemented on your platform.
9790 If it is unavailable, using it will raise a NotImplementedError.
9791[clinic start generated code]*/
9792
Larry Hastings2f936352014-08-05 14:04:04 +10009793static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009794os_mknod_impl(PyObject *module, path_t *path, int mode, dev_t device,
Larry Hastings89964c42015-04-14 18:07:59 -04009795 int dir_fd)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009796/*[clinic end generated code: output=92e55d3ca8917461 input=ee44531551a4d83b]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009797{
9798 int result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009799 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10009800
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009801 do {
9802 Py_BEGIN_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10009803#ifdef HAVE_MKNODAT
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009804 if (dir_fd != DEFAULT_DIR_FD)
9805 result = mknodat(dir_fd, path->narrow, mode, device);
9806 else
Larry Hastings2f936352014-08-05 14:04:04 +10009807#endif
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009808 result = mknod(path->narrow, mode, device);
9809 Py_END_ALLOW_THREADS
9810 } while (result != 0 && errno == EINTR &&
9811 !(async_err = PyErr_CheckSignals()));
9812 if (result != 0)
9813 return (!async_err) ? posix_error() : NULL;
Larry Hastings2f936352014-08-05 14:04:04 +10009814
9815 Py_RETURN_NONE;
9816}
9817#endif /* defined(HAVE_MKNOD) && defined(HAVE_MAKEDEV) */
9818
9819
9820#ifdef HAVE_DEVICE_MACROS
9821/*[clinic input]
9822os.major -> unsigned_int
9823
Serhiy Storchakaacdb7c12015-01-18 11:17:39 +02009824 device: dev_t
Larry Hastings2f936352014-08-05 14:04:04 +10009825 /
9826
9827Extracts a device major number from a raw device number.
9828[clinic start generated code]*/
9829
Larry Hastings2f936352014-08-05 14:04:04 +10009830static unsigned int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009831os_major_impl(PyObject *module, dev_t device)
9832/*[clinic end generated code: output=5b3b2589bafb498e input=1e16a4d30c4d4462]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009833{
9834 return major(device);
9835}
9836
9837
9838/*[clinic input]
9839os.minor -> unsigned_int
9840
Serhiy Storchakaacdb7c12015-01-18 11:17:39 +02009841 device: dev_t
Larry Hastings2f936352014-08-05 14:04:04 +10009842 /
9843
9844Extracts a device minor number from a raw device number.
9845[clinic start generated code]*/
9846
Larry Hastings2f936352014-08-05 14:04:04 +10009847static unsigned int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009848os_minor_impl(PyObject *module, dev_t device)
9849/*[clinic end generated code: output=5e1a25e630b0157d input=0842c6d23f24c65e]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009850{
9851 return minor(device);
9852}
9853
9854
9855/*[clinic input]
Serhiy Storchakaacdb7c12015-01-18 11:17:39 +02009856os.makedev -> dev_t
Larry Hastings2f936352014-08-05 14:04:04 +10009857
9858 major: int
9859 minor: int
9860 /
9861
9862Composes a raw device number from the major and minor device numbers.
9863[clinic start generated code]*/
9864
Serhiy Storchakaacdb7c12015-01-18 11:17:39 +02009865static dev_t
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009866os_makedev_impl(PyObject *module, int major, int minor)
9867/*[clinic end generated code: output=881aaa4aba6f6a52 input=4b9fd8fc73cbe48f]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009868{
9869 return makedev(major, minor);
9870}
9871#endif /* HAVE_DEVICE_MACROS */
9872
9873
Steve Dowerfe0a41a2015-03-20 19:50:46 -07009874#if defined HAVE_FTRUNCATE || defined MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +10009875/*[clinic input]
9876os.ftruncate
9877
9878 fd: int
9879 length: Py_off_t
9880 /
9881
9882Truncate a file, specified by file descriptor, to a specific length.
9883[clinic start generated code]*/
9884
Larry Hastings2f936352014-08-05 14:04:04 +10009885static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009886os_ftruncate_impl(PyObject *module, int fd, Py_off_t length)
9887/*[clinic end generated code: output=fba15523721be7e4 input=63b43641e52818f2]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009888{
9889 int result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009890 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10009891
Steve Dowerb82e17e2019-05-23 08:45:22 -07009892 if (PySys_Audit("os.truncate", "in", fd, length) < 0) {
9893 return NULL;
9894 }
9895
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009896 do {
9897 Py_BEGIN_ALLOW_THREADS
Steve Dowera1c7e722015-04-12 00:26:43 -04009898 _Py_BEGIN_SUPPRESS_IPH
Steve Dowerfe0a41a2015-03-20 19:50:46 -07009899#ifdef MS_WINDOWS
9900 result = _chsize_s(fd, length);
9901#else
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009902 result = ftruncate(fd, length);
Steve Dowerfe0a41a2015-03-20 19:50:46 -07009903#endif
Steve Dowera1c7e722015-04-12 00:26:43 -04009904 _Py_END_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009905 Py_END_ALLOW_THREADS
9906 } while (result != 0 && errno == EINTR &&
9907 !(async_err = PyErr_CheckSignals()));
9908 if (result != 0)
9909 return (!async_err) ? posix_error() : NULL;
Larry Hastings2f936352014-08-05 14:04:04 +10009910 Py_RETURN_NONE;
9911}
Steve Dowerfe0a41a2015-03-20 19:50:46 -07009912#endif /* HAVE_FTRUNCATE || MS_WINDOWS */
Larry Hastings2f936352014-08-05 14:04:04 +10009913
9914
Steve Dowerfe0a41a2015-03-20 19:50:46 -07009915#if defined HAVE_TRUNCATE || defined MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +10009916/*[clinic input]
9917os.truncate
9918 path: path_t(allow_fd='PATH_HAVE_FTRUNCATE')
9919 length: Py_off_t
9920
9921Truncate a file, specified by path, to a specific length.
9922
9923On some platforms, path may also be specified as an open file descriptor.
9924 If this functionality is unavailable, using it raises an exception.
9925[clinic start generated code]*/
9926
Larry Hastings2f936352014-08-05 14:04:04 +10009927static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009928os_truncate_impl(PyObject *module, path_t *path, Py_off_t length)
9929/*[clinic end generated code: output=43009c8df5c0a12b input=77229cf0b50a9b77]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009930{
9931 int result;
Steve Dowerfe0a41a2015-03-20 19:50:46 -07009932#ifdef MS_WINDOWS
9933 int fd;
9934#endif
9935
9936 if (path->fd != -1)
9937 return os_ftruncate_impl(module, path->fd, length);
Larry Hastings2f936352014-08-05 14:04:04 +10009938
Steve Dowerb82e17e2019-05-23 08:45:22 -07009939 if (PySys_Audit("os.truncate", "On", path->object, length) < 0) {
9940 return NULL;
9941 }
9942
Larry Hastings2f936352014-08-05 14:04:04 +10009943 Py_BEGIN_ALLOW_THREADS
Steve Dowera1c7e722015-04-12 00:26:43 -04009944 _Py_BEGIN_SUPPRESS_IPH
Steve Dowerfe0a41a2015-03-20 19:50:46 -07009945#ifdef MS_WINDOWS
Steve Dowercc16be82016-09-08 10:35:16 -07009946 fd = _wopen(path->wide, _O_WRONLY | _O_BINARY | _O_NOINHERIT);
Victor Stinnercc0bbbc2015-04-25 00:21:52 +02009947 if (fd < 0)
Steve Dowerfe0a41a2015-03-20 19:50:46 -07009948 result = -1;
9949 else {
9950 result = _chsize_s(fd, length);
9951 close(fd);
9952 if (result < 0)
9953 errno = result;
9954 }
9955#else
9956 result = truncate(path->narrow, length);
Larry Hastings2f936352014-08-05 14:04:04 +10009957#endif
Steve Dowera1c7e722015-04-12 00:26:43 -04009958 _Py_END_SUPPRESS_IPH
Larry Hastings2f936352014-08-05 14:04:04 +10009959 Py_END_ALLOW_THREADS
9960 if (result < 0)
Alexey Izbyshev83460312018-10-20 03:28:22 +03009961 return posix_path_error(path);
Larry Hastings2f936352014-08-05 14:04:04 +10009962
9963 Py_RETURN_NONE;
9964}
Steve Dowerfe0a41a2015-03-20 19:50:46 -07009965#endif /* HAVE_TRUNCATE || MS_WINDOWS */
Larry Hastings2f936352014-08-05 14:04:04 +10009966
Ross Lagerwall7807c352011-03-17 20:20:30 +02009967
Victor Stinnerd6b17692014-09-30 12:20:05 +02009968/* Issue #22396: On 32-bit AIX platform, the prototypes of os.posix_fadvise()
9969 and os.posix_fallocate() in system headers are wrong if _LARGE_FILES is
9970 defined, which is the case in Python on AIX. AIX bug report:
9971 http://www-01.ibm.com/support/docview.wss?uid=isg1IV56170 */
9972#if defined(_AIX) && defined(_LARGE_FILES) && !defined(__64BIT__)
9973# define POSIX_FADVISE_AIX_BUG
9974#endif
9975
Victor Stinnerec39e262014-09-30 12:35:58 +02009976
Victor Stinnerd6b17692014-09-30 12:20:05 +02009977#if defined(HAVE_POSIX_FALLOCATE) && !defined(POSIX_FADVISE_AIX_BUG)
Larry Hastings2f936352014-08-05 14:04:04 +10009978/*[clinic input]
9979os.posix_fallocate
9980
9981 fd: int
9982 offset: Py_off_t
9983 length: Py_off_t
9984 /
9985
9986Ensure a file has allocated at least a particular number of bytes on disk.
9987
9988Ensure that the file specified by fd encompasses a range of bytes
9989starting at offset bytes from the beginning and continuing for length bytes.
9990[clinic start generated code]*/
9991
Larry Hastings2f936352014-08-05 14:04:04 +10009992static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009993os_posix_fallocate_impl(PyObject *module, int fd, Py_off_t offset,
Larry Hastings89964c42015-04-14 18:07:59 -04009994 Py_off_t length)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009995/*[clinic end generated code: output=73f107139564aa9d input=d7a2ef0ab2ca52fb]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009996{
9997 int result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009998 int async_err = 0;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009999
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010000 do {
10001 Py_BEGIN_ALLOW_THREADS
10002 result = posix_fallocate(fd, offset, length);
10003 Py_END_ALLOW_THREADS
Коренберг Маркd4b93e22017-08-14 18:55:16 +050010004 } while (result == EINTR && !(async_err = PyErr_CheckSignals()));
10005
10006 if (result == 0)
10007 Py_RETURN_NONE;
10008
10009 if (async_err)
10010 return NULL;
10011
10012 errno = result;
10013 return posix_error();
Ross Lagerwall7807c352011-03-17 20:20:30 +020010014}
Victor Stinnerec39e262014-09-30 12:35:58 +020010015#endif /* HAVE_POSIX_FALLOCATE) && !POSIX_FADVISE_AIX_BUG */
Larry Hastings2f936352014-08-05 14:04:04 +100010016
Ross Lagerwall7807c352011-03-17 20:20:30 +020010017
Victor Stinnerd6b17692014-09-30 12:20:05 +020010018#if defined(HAVE_POSIX_FADVISE) && !defined(POSIX_FADVISE_AIX_BUG)
Larry Hastings2f936352014-08-05 14:04:04 +100010019/*[clinic input]
10020os.posix_fadvise
10021
10022 fd: int
10023 offset: Py_off_t
10024 length: Py_off_t
10025 advice: int
10026 /
10027
10028Announce an intention to access data in a specific pattern.
10029
10030Announce an intention to access data in a specific pattern, thus allowing
10031the kernel to make optimizations.
10032The advice applies to the region of the file specified by fd starting at
10033offset and continuing for length bytes.
10034advice is one of POSIX_FADV_NORMAL, POSIX_FADV_SEQUENTIAL,
10035POSIX_FADV_RANDOM, POSIX_FADV_NOREUSE, POSIX_FADV_WILLNEED, or
10036POSIX_FADV_DONTNEED.
10037[clinic start generated code]*/
10038
Larry Hastings2f936352014-08-05 14:04:04 +100010039static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010040os_posix_fadvise_impl(PyObject *module, int fd, Py_off_t offset,
Larry Hastings89964c42015-04-14 18:07:59 -040010041 Py_off_t length, int advice)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010042/*[clinic end generated code: output=412ef4aa70c98642 input=0fbe554edc2f04b5]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010043{
10044 int result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010045 int async_err = 0;
Ross Lagerwall7807c352011-03-17 20:20:30 +020010046
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010047 do {
10048 Py_BEGIN_ALLOW_THREADS
10049 result = posix_fadvise(fd, offset, length, advice);
10050 Py_END_ALLOW_THREADS
Коренберг Маркd4b93e22017-08-14 18:55:16 +050010051 } while (result == EINTR && !(async_err = PyErr_CheckSignals()));
10052
10053 if (result == 0)
10054 Py_RETURN_NONE;
10055
10056 if (async_err)
10057 return NULL;
10058
10059 errno = result;
10060 return posix_error();
Ross Lagerwall7807c352011-03-17 20:20:30 +020010061}
Victor Stinnerec39e262014-09-30 12:35:58 +020010062#endif /* HAVE_POSIX_FADVISE && !POSIX_FADVISE_AIX_BUG */
Ross Lagerwall7807c352011-03-17 20:20:30 +020010063
Guido van Rossumec4f4ac1997-06-02 22:20:51 +000010064
Victor Stinner623ed612020-01-21 19:25:32 +010010065#ifdef PY_PUTENV_DICT
Larry Hastings2f936352014-08-05 14:04:04 +100010066static void
Victor Stinner623ed612020-01-21 19:25:32 +010010067posix_putenv_dict_setitem(PyObject *name, PyObject *value)
Guido van Rossumf1af3fe1996-07-23 19:18:10 +000010068{
Victor Stinner623ed612020-01-21 19:25:32 +010010069 /* Install the first arg and newstr in putenv_dict;
Larry Hastings2f936352014-08-05 14:04:04 +100010070 * this will cause previous value to be collected. This has to
10071 * happen after the real putenv() call because the old value
10072 * was still accessible until then. */
Victor Stinner623ed612020-01-21 19:25:32 +010010073 if (PyDict_SetItem(_posixstate_global->putenv_dict, name, value))
Larry Hastings2f936352014-08-05 14:04:04 +100010074 /* really not much we can do; just leak */
10075 PyErr_Clear();
10076 else
10077 Py_DECREF(value);
10078}
Victor Stinner623ed612020-01-21 19:25:32 +010010079#endif /* PY_PUTENV_DICT */
Larry Hastings2f936352014-08-05 14:04:04 +100010080
10081
Victor Stinner623ed612020-01-21 19:25:32 +010010082#ifdef HAVE_PUTENV
10083
Thomas Hellerf78f12a2007-11-08 19:33:05 +000010084#ifdef MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +100010085/*[clinic input]
10086os.putenv
10087
10088 name: unicode
10089 value: unicode
10090 /
10091
10092Change or add an environment variable.
10093[clinic start generated code]*/
10094
Larry Hastings2f936352014-08-05 14:04:04 +100010095static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010096os_putenv_impl(PyObject *module, PyObject *name, PyObject *value)
10097/*[clinic end generated code: output=d29a567d6b2327d2 input=ba586581c2e6105f]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010098{
Serhiy Storchakadeab18d2016-05-07 16:45:18 +030010099 const wchar_t *env;
Serhiy Storchakaf7eae0a2017-06-28 08:30:06 +030010100 Py_ssize_t size;
Larry Hastings2f936352014-08-05 14:04:04 +100010101
Serhiy Storchaka77703942017-06-25 07:33:01 +030010102 /* Search from index 1 because on Windows starting '=' is allowed for
10103 defining hidden environment variables. */
10104 if (PyUnicode_GET_LENGTH(name) == 0 ||
10105 PyUnicode_FindChar(name, '=', 1, PyUnicode_GET_LENGTH(name), 1) != -1)
10106 {
10107 PyErr_SetString(PyExc_ValueError, "illegal environment variable name");
10108 return NULL;
10109 }
Larry Hastings2f936352014-08-05 14:04:04 +100010110 PyObject *unicode = PyUnicode_FromFormat("%U=%U", name, value);
10111 if (unicode == NULL) {
Larry Hastings2f936352014-08-05 14:04:04 +100010112 return NULL;
Victor Stinner84ae1182010-05-06 22:05:07 +000010113 }
Serhiy Storchakaf7eae0a2017-06-28 08:30:06 +030010114
10115 env = PyUnicode_AsUnicodeAndSize(unicode, &size);
10116 if (env == NULL)
10117 goto error;
10118 if (size > _MAX_ENV) {
Victor Stinner65170952011-11-22 22:16:17 +010010119 PyErr_Format(PyExc_ValueError,
10120 "the environment variable is longer than %u characters",
10121 _MAX_ENV);
10122 goto error;
10123 }
Serhiy Storchakaf7eae0a2017-06-28 08:30:06 +030010124 if (wcslen(env) != (size_t)size) {
10125 PyErr_SetString(PyExc_ValueError, "embedded null character");
Victor Stinnereb5657a2011-09-30 01:44:27 +020010126 goto error;
Serhiy Storchakaf7eae0a2017-06-28 08:30:06 +030010127 }
10128
Larry Hastings2f936352014-08-05 14:04:04 +100010129 if (_wputenv(env)) {
Victor Stinner8c62be82010-05-06 00:08:46 +000010130 posix_error();
Victor Stinner84ae1182010-05-06 22:05:07 +000010131 goto error;
Victor Stinner8c62be82010-05-06 00:08:46 +000010132 }
Guido van Rossumf1af3fe1996-07-23 19:18:10 +000010133
Victor Stinner623ed612020-01-21 19:25:32 +010010134 posix_putenv_dict_setitem(name, unicode);
Victor Stinner84ae1182010-05-06 22:05:07 +000010135 Py_RETURN_NONE;
10136
10137error:
Larry Hastings2f936352014-08-05 14:04:04 +100010138 Py_DECREF(unicode);
Victor Stinner84ae1182010-05-06 22:05:07 +000010139 return NULL;
Guido van Rossumf1af3fe1996-07-23 19:18:10 +000010140}
Larry Hastings2f936352014-08-05 14:04:04 +100010141#else /* MS_WINDOWS */
10142/*[clinic input]
10143os.putenv
Guido van Rossumb6a47161997-09-15 22:54:34 +000010144
Larry Hastings2f936352014-08-05 14:04:04 +100010145 name: FSConverter
10146 value: FSConverter
10147 /
10148
10149Change or add an environment variable.
10150[clinic start generated code]*/
10151
Larry Hastings2f936352014-08-05 14:04:04 +100010152static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010153os_putenv_impl(PyObject *module, PyObject *name, PyObject *value)
10154/*[clinic end generated code: output=d29a567d6b2327d2 input=a97bc6152f688d31]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010155{
10156 PyObject *bytes = NULL;
10157 char *env;
Serhiy Storchaka77703942017-06-25 07:33:01 +030010158 const char *name_string = PyBytes_AS_STRING(name);
10159 const char *value_string = PyBytes_AS_STRING(value);
Larry Hastings2f936352014-08-05 14:04:04 +100010160
Serhiy Storchaka77703942017-06-25 07:33:01 +030010161 if (strchr(name_string, '=') != NULL) {
10162 PyErr_SetString(PyExc_ValueError, "illegal environment variable name");
10163 return NULL;
10164 }
Larry Hastings2f936352014-08-05 14:04:04 +100010165 bytes = PyBytes_FromFormat("%s=%s", name_string, value_string);
10166 if (bytes == NULL) {
Larry Hastings2f936352014-08-05 14:04:04 +100010167 return NULL;
10168 }
10169
10170 env = PyBytes_AS_STRING(bytes);
10171 if (putenv(env)) {
10172 Py_DECREF(bytes);
10173 return posix_error();
10174 }
10175
Victor Stinner623ed612020-01-21 19:25:32 +010010176 posix_putenv_dict_setitem(name, bytes);
Larry Hastings2f936352014-08-05 14:04:04 +100010177 Py_RETURN_NONE;
10178}
10179#endif /* MS_WINDOWS */
10180#endif /* HAVE_PUTENV */
10181
10182
Victor Stinnerb73dd022020-01-22 21:11:17 +010010183#ifdef HAVE_UNSETENV
Larry Hastings2f936352014-08-05 14:04:04 +100010184/*[clinic input]
10185os.unsetenv
10186 name: FSConverter
10187 /
10188
10189Delete an environment variable.
10190[clinic start generated code]*/
10191
Larry Hastings2f936352014-08-05 14:04:04 +100010192static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010193os_unsetenv_impl(PyObject *module, PyObject *name)
10194/*[clinic end generated code: output=54c4137ab1834f02 input=2bb5288a599c7107]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010195{
Victor Stinner984890f2011-11-24 13:53:38 +010010196#ifndef HAVE_BROKEN_UNSETENV
Victor Stinner60b385e2011-11-22 22:01:28 +010010197 int err;
Victor Stinner984890f2011-11-24 13:53:38 +010010198#endif
Victor Stinner84ae1182010-05-06 22:05:07 +000010199
Victor Stinner984890f2011-11-24 13:53:38 +010010200#ifdef HAVE_BROKEN_UNSETENV
10201 unsetenv(PyBytes_AS_STRING(name));
10202#else
Victor Stinner65170952011-11-22 22:16:17 +010010203 err = unsetenv(PyBytes_AS_STRING(name));
Larry Hastings2f936352014-08-05 14:04:04 +100010204 if (err)
Victor Stinner60b385e2011-11-22 22:01:28 +010010205 return posix_error();
Victor Stinner984890f2011-11-24 13:53:38 +010010206#endif
Guido van Rossumc524d952001-10-19 01:31:59 +000010207
Victor Stinner623ed612020-01-21 19:25:32 +010010208#ifdef PY_PUTENV_DICT
10209 /* Remove the key from putenv_dict;
Victor Stinner8c62be82010-05-06 00:08:46 +000010210 * this will cause it to be collected. This has to
10211 * happen after the real unsetenv() call because the
10212 * old value was still accessible until then.
10213 */
Victor Stinner623ed612020-01-21 19:25:32 +010010214 if (PyDict_DelItem(_posixstate(module)->putenv_dict, name)) {
Victor Stinner8c62be82010-05-06 00:08:46 +000010215 /* really not much we can do; just leak */
Serhiy Storchakaa24107b2019-02-25 17:59:46 +020010216 if (!PyErr_ExceptionMatches(PyExc_KeyError)) {
10217 return NULL;
10218 }
Victor Stinner8c62be82010-05-06 00:08:46 +000010219 PyErr_Clear();
10220 }
Victor Stinner623ed612020-01-21 19:25:32 +010010221#endif
10222
Victor Stinner84ae1182010-05-06 22:05:07 +000010223 Py_RETURN_NONE;
Guido van Rossumc524d952001-10-19 01:31:59 +000010224}
Larry Hastings2f936352014-08-05 14:04:04 +100010225#endif /* HAVE_UNSETENV */
Guido van Rossumc524d952001-10-19 01:31:59 +000010226
Larry Hastings2f936352014-08-05 14:04:04 +100010227
10228/*[clinic input]
10229os.strerror
10230
10231 code: int
10232 /
10233
10234Translate an error code to a message string.
10235[clinic start generated code]*/
10236
Larry Hastings2f936352014-08-05 14:04:04 +100010237static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010238os_strerror_impl(PyObject *module, int code)
10239/*[clinic end generated code: output=baebf09fa02a78f2 input=75a8673d97915a91]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010240{
10241 char *message = strerror(code);
Victor Stinner8c62be82010-05-06 00:08:46 +000010242 if (message == NULL) {
10243 PyErr_SetString(PyExc_ValueError,
10244 "strerror() argument out of range");
10245 return NULL;
10246 }
Victor Stinner1b579672011-12-17 05:47:23 +010010247 return PyUnicode_DecodeLocale(message, "surrogateescape");
Guido van Rossumb6a47161997-09-15 22:54:34 +000010248}
Guido van Rossumb6a47161997-09-15 22:54:34 +000010249
Guido van Rossumf1af3fe1996-07-23 19:18:10 +000010250
Guido van Rossumc9641791998-08-04 15:26:23 +000010251#ifdef HAVE_SYS_WAIT_H
Fred Drake106c1a02002-04-23 15:58:02 +000010252#ifdef WCOREDUMP
Larry Hastings2f936352014-08-05 14:04:04 +100010253/*[clinic input]
10254os.WCOREDUMP -> bool
10255
10256 status: int
10257 /
10258
10259Return True if the process returning status was dumped to a core file.
10260[clinic start generated code]*/
10261
Larry Hastings2f936352014-08-05 14:04:04 +100010262static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010263os_WCOREDUMP_impl(PyObject *module, int status)
10264/*[clinic end generated code: output=1a584b147b16bd18 input=8b05e7ab38528d04]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010265{
10266 WAIT_TYPE wait_status;
10267 WAIT_STATUS_INT(wait_status) = status;
10268 return WCOREDUMP(wait_status);
Fred Drake106c1a02002-04-23 15:58:02 +000010269}
10270#endif /* WCOREDUMP */
10271
Larry Hastings2f936352014-08-05 14:04:04 +100010272
Fred Drake106c1a02002-04-23 15:58:02 +000010273#ifdef WIFCONTINUED
Larry Hastings2f936352014-08-05 14:04:04 +100010274/*[clinic input]
10275os.WIFCONTINUED -> bool
10276
10277 status: int
10278
10279Return True if a particular process was continued from a job control stop.
10280
10281Return True if the process returning status was continued from a
10282job control stop.
10283[clinic start generated code]*/
10284
Larry Hastings2f936352014-08-05 14:04:04 +100010285static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010286os_WIFCONTINUED_impl(PyObject *module, int status)
10287/*[clinic end generated code: output=1e35295d844364bd input=e777e7d38eb25bd9]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010288{
10289 WAIT_TYPE wait_status;
10290 WAIT_STATUS_INT(wait_status) = status;
10291 return WIFCONTINUED(wait_status);
Fred Drake106c1a02002-04-23 15:58:02 +000010292}
10293#endif /* WIFCONTINUED */
10294
Larry Hastings2f936352014-08-05 14:04:04 +100010295
Guido van Rossumc9641791998-08-04 15:26:23 +000010296#ifdef WIFSTOPPED
Larry Hastings2f936352014-08-05 14:04:04 +100010297/*[clinic input]
10298os.WIFSTOPPED -> bool
10299
10300 status: int
10301
10302Return True if the process returning status was stopped.
10303[clinic start generated code]*/
10304
Larry Hastings2f936352014-08-05 14:04:04 +100010305static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010306os_WIFSTOPPED_impl(PyObject *module, int status)
10307/*[clinic end generated code: output=fdb57122a5c9b4cb input=043cb7f1289ef904]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010308{
10309 WAIT_TYPE wait_status;
10310 WAIT_STATUS_INT(wait_status) = status;
10311 return WIFSTOPPED(wait_status);
Guido van Rossumc9641791998-08-04 15:26:23 +000010312}
10313#endif /* WIFSTOPPED */
10314
Larry Hastings2f936352014-08-05 14:04:04 +100010315
Guido van Rossumc9641791998-08-04 15:26:23 +000010316#ifdef WIFSIGNALED
Larry Hastings2f936352014-08-05 14:04:04 +100010317/*[clinic input]
10318os.WIFSIGNALED -> bool
10319
10320 status: int
10321
10322Return True if the process returning status was terminated by a signal.
10323[clinic start generated code]*/
10324
Larry Hastings2f936352014-08-05 14:04:04 +100010325static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010326os_WIFSIGNALED_impl(PyObject *module, int status)
10327/*[clinic end generated code: output=d1dde4dcc819a5f5 input=d55ba7cc9ce5dc43]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010328{
10329 WAIT_TYPE wait_status;
10330 WAIT_STATUS_INT(wait_status) = status;
10331 return WIFSIGNALED(wait_status);
Guido van Rossumc9641791998-08-04 15:26:23 +000010332}
10333#endif /* WIFSIGNALED */
10334
Larry Hastings2f936352014-08-05 14:04:04 +100010335
Guido van Rossumc9641791998-08-04 15:26:23 +000010336#ifdef WIFEXITED
Larry Hastings2f936352014-08-05 14:04:04 +100010337/*[clinic input]
10338os.WIFEXITED -> bool
10339
10340 status: int
10341
10342Return True if the process returning status exited via the exit() system call.
10343[clinic start generated code]*/
10344
Larry Hastings2f936352014-08-05 14:04:04 +100010345static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010346os_WIFEXITED_impl(PyObject *module, int status)
10347/*[clinic end generated code: output=01c09d6ebfeea397 input=d63775a6791586c0]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010348{
10349 WAIT_TYPE wait_status;
10350 WAIT_STATUS_INT(wait_status) = status;
10351 return WIFEXITED(wait_status);
Guido van Rossumc9641791998-08-04 15:26:23 +000010352}
10353#endif /* WIFEXITED */
10354
Larry Hastings2f936352014-08-05 14:04:04 +100010355
Guido van Rossum54ecc3d1999-01-27 17:53:11 +000010356#ifdef WEXITSTATUS
Larry Hastings2f936352014-08-05 14:04:04 +100010357/*[clinic input]
10358os.WEXITSTATUS -> int
10359
10360 status: int
10361
10362Return the process return code from status.
10363[clinic start generated code]*/
10364
Larry Hastings2f936352014-08-05 14:04:04 +100010365static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010366os_WEXITSTATUS_impl(PyObject *module, int status)
10367/*[clinic end generated code: output=6e3efbba11f6488d input=e1fb4944e377585b]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010368{
10369 WAIT_TYPE wait_status;
10370 WAIT_STATUS_INT(wait_status) = status;
10371 return WEXITSTATUS(wait_status);
Guido van Rossumc9641791998-08-04 15:26:23 +000010372}
10373#endif /* WEXITSTATUS */
10374
Larry Hastings2f936352014-08-05 14:04:04 +100010375
Guido van Rossumc9641791998-08-04 15:26:23 +000010376#ifdef WTERMSIG
Larry Hastings2f936352014-08-05 14:04:04 +100010377/*[clinic input]
10378os.WTERMSIG -> int
10379
10380 status: int
10381
10382Return the signal that terminated the process that provided the status value.
10383[clinic start generated code]*/
10384
Larry Hastings2f936352014-08-05 14:04:04 +100010385static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010386os_WTERMSIG_impl(PyObject *module, int status)
10387/*[clinic end generated code: output=172f7dfc8dcfc3ad input=727fd7f84ec3f243]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010388{
10389 WAIT_TYPE wait_status;
10390 WAIT_STATUS_INT(wait_status) = status;
10391 return WTERMSIG(wait_status);
Guido van Rossumc9641791998-08-04 15:26:23 +000010392}
10393#endif /* WTERMSIG */
10394
Larry Hastings2f936352014-08-05 14:04:04 +100010395
Guido van Rossumc9641791998-08-04 15:26:23 +000010396#ifdef WSTOPSIG
Larry Hastings2f936352014-08-05 14:04:04 +100010397/*[clinic input]
10398os.WSTOPSIG -> int
10399
10400 status: int
10401
10402Return the signal that stopped the process that provided the status value.
10403[clinic start generated code]*/
10404
Larry Hastings2f936352014-08-05 14:04:04 +100010405static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010406os_WSTOPSIG_impl(PyObject *module, int status)
10407/*[clinic end generated code: output=0ab7586396f5d82b input=46ebf1d1b293c5c1]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010408{
10409 WAIT_TYPE wait_status;
10410 WAIT_STATUS_INT(wait_status) = status;
10411 return WSTOPSIG(wait_status);
Guido van Rossumc9641791998-08-04 15:26:23 +000010412}
10413#endif /* WSTOPSIG */
Guido van Rossumc9641791998-08-04 15:26:23 +000010414#endif /* HAVE_SYS_WAIT_H */
10415
10416
Thomas Wouters477c8d52006-05-27 19:21:47 +000010417#if defined(HAVE_FSTATVFS) && defined(HAVE_SYS_STATVFS_H)
Guido van Rossumd5753e11999-10-19 13:29:23 +000010418#ifdef _SCO_DS
10419/* SCO OpenServer 5.0 and later requires _SVID3 before it reveals the
10420 needed definitions in sys/statvfs.h */
10421#define _SVID3
10422#endif
Guido van Rossum94f6f721999-01-06 18:42:14 +000010423#include <sys/statvfs.h>
10424
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010425static PyObject*
10426_pystatvfs_fromstructstatvfs(struct statvfs st) {
Eddie Elizondob3966632019-11-05 07:16:14 -080010427 PyObject *StatVFSResultType = _posixstate_global->StatVFSResultType;
10428 PyObject *v = PyStructSequence_New((PyTypeObject *)StatVFSResultType);
Victor Stinner8c62be82010-05-06 00:08:46 +000010429 if (v == NULL)
10430 return NULL;
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010431
10432#if !defined(HAVE_LARGEFILE_SUPPORT)
Victor Stinner8c62be82010-05-06 00:08:46 +000010433 PyStructSequence_SET_ITEM(v, 0, PyLong_FromLong((long) st.f_bsize));
10434 PyStructSequence_SET_ITEM(v, 1, PyLong_FromLong((long) st.f_frsize));
10435 PyStructSequence_SET_ITEM(v, 2, PyLong_FromLong((long) st.f_blocks));
10436 PyStructSequence_SET_ITEM(v, 3, PyLong_FromLong((long) st.f_bfree));
10437 PyStructSequence_SET_ITEM(v, 4, PyLong_FromLong((long) st.f_bavail));
10438 PyStructSequence_SET_ITEM(v, 5, PyLong_FromLong((long) st.f_files));
10439 PyStructSequence_SET_ITEM(v, 6, PyLong_FromLong((long) st.f_ffree));
10440 PyStructSequence_SET_ITEM(v, 7, PyLong_FromLong((long) st.f_favail));
10441 PyStructSequence_SET_ITEM(v, 8, PyLong_FromLong((long) st.f_flag));
10442 PyStructSequence_SET_ITEM(v, 9, PyLong_FromLong((long) st.f_namemax));
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010443#else
Victor Stinner8c62be82010-05-06 00:08:46 +000010444 PyStructSequence_SET_ITEM(v, 0, PyLong_FromLong((long) st.f_bsize));
10445 PyStructSequence_SET_ITEM(v, 1, PyLong_FromLong((long) st.f_frsize));
10446 PyStructSequence_SET_ITEM(v, 2,
Benjamin Petersonaf580df2016-09-06 10:46:49 -070010447 PyLong_FromLongLong((long long) st.f_blocks));
Victor Stinner8c62be82010-05-06 00:08:46 +000010448 PyStructSequence_SET_ITEM(v, 3,
Benjamin Petersonaf580df2016-09-06 10:46:49 -070010449 PyLong_FromLongLong((long long) st.f_bfree));
Victor Stinner8c62be82010-05-06 00:08:46 +000010450 PyStructSequence_SET_ITEM(v, 4,
Benjamin Petersonaf580df2016-09-06 10:46:49 -070010451 PyLong_FromLongLong((long long) st.f_bavail));
Victor Stinner8c62be82010-05-06 00:08:46 +000010452 PyStructSequence_SET_ITEM(v, 5,
Benjamin Petersonaf580df2016-09-06 10:46:49 -070010453 PyLong_FromLongLong((long long) st.f_files));
Victor Stinner8c62be82010-05-06 00:08:46 +000010454 PyStructSequence_SET_ITEM(v, 6,
Benjamin Petersonaf580df2016-09-06 10:46:49 -070010455 PyLong_FromLongLong((long long) st.f_ffree));
Victor Stinner8c62be82010-05-06 00:08:46 +000010456 PyStructSequence_SET_ITEM(v, 7,
Benjamin Petersonaf580df2016-09-06 10:46:49 -070010457 PyLong_FromLongLong((long long) st.f_favail));
Victor Stinner8c62be82010-05-06 00:08:46 +000010458 PyStructSequence_SET_ITEM(v, 8, PyLong_FromLong((long) st.f_flag));
10459 PyStructSequence_SET_ITEM(v, 9, PyLong_FromLong((long) st.f_namemax));
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010460#endif
Michael Felt502d5512018-01-05 13:01:58 +010010461/* The _ALL_SOURCE feature test macro defines f_fsid as a structure
10462 * (issue #32390). */
10463#if defined(_AIX) && defined(_ALL_SOURCE)
10464 PyStructSequence_SET_ITEM(v, 10, PyLong_FromUnsignedLong(st.f_fsid.val[0]));
10465#else
Giuseppe Scrivano96a5e502017-12-14 23:46:46 +010010466 PyStructSequence_SET_ITEM(v, 10, PyLong_FromUnsignedLong(st.f_fsid));
Michael Felt502d5512018-01-05 13:01:58 +010010467#endif
Victor Stinnerf0a7bac2013-10-30 18:55:24 +010010468 if (PyErr_Occurred()) {
10469 Py_DECREF(v);
10470 return NULL;
10471 }
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010472
Victor Stinner8c62be82010-05-06 00:08:46 +000010473 return v;
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010474}
10475
Larry Hastings2f936352014-08-05 14:04:04 +100010476
10477/*[clinic input]
10478os.fstatvfs
10479 fd: int
10480 /
10481
10482Perform an fstatvfs system call on the given fd.
10483
10484Equivalent to statvfs(fd).
10485[clinic start generated code]*/
10486
Larry Hastings2f936352014-08-05 14:04:04 +100010487static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010488os_fstatvfs_impl(PyObject *module, int fd)
10489/*[clinic end generated code: output=53547cf0cc55e6c5 input=d8122243ac50975e]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010490{
10491 int result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010492 int async_err = 0;
Victor Stinner8c62be82010-05-06 00:08:46 +000010493 struct statvfs st;
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010494
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010495 do {
10496 Py_BEGIN_ALLOW_THREADS
10497 result = fstatvfs(fd, &st);
10498 Py_END_ALLOW_THREADS
10499 } while (result != 0 && errno == EINTR &&
10500 !(async_err = PyErr_CheckSignals()));
Larry Hastings2f936352014-08-05 14:04:04 +100010501 if (result != 0)
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010502 return (!async_err) ? posix_error() : NULL;
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010503
Victor Stinner8c62be82010-05-06 00:08:46 +000010504 return _pystatvfs_fromstructstatvfs(st);
Guido van Rossum94f6f721999-01-06 18:42:14 +000010505}
Larry Hastings2f936352014-08-05 14:04:04 +100010506#endif /* defined(HAVE_FSTATVFS) && defined(HAVE_SYS_STATVFS_H) */
Guido van Rossum94f6f721999-01-06 18:42:14 +000010507
10508
Thomas Wouters477c8d52006-05-27 19:21:47 +000010509#if defined(HAVE_STATVFS) && defined(HAVE_SYS_STATVFS_H)
Guido van Rossum94f6f721999-01-06 18:42:14 +000010510#include <sys/statvfs.h>
Larry Hastings2f936352014-08-05 14:04:04 +100010511/*[clinic input]
10512os.statvfs
Guido van Rossum94f6f721999-01-06 18:42:14 +000010513
Larry Hastings2f936352014-08-05 14:04:04 +100010514 path: path_t(allow_fd='PATH_HAVE_FSTATVFS')
10515
10516Perform a statvfs system call on the given path.
10517
10518path may always be specified as a string.
10519On some platforms, path may also be specified as an open file descriptor.
10520 If this functionality is unavailable, using it raises an exception.
10521[clinic start generated code]*/
10522
Larry Hastings2f936352014-08-05 14:04:04 +100010523static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010524os_statvfs_impl(PyObject *module, path_t *path)
10525/*[clinic end generated code: output=87106dd1beb8556e input=3f5c35791c669bd9]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010526{
10527 int result;
10528 struct statvfs st;
Larry Hastings9cf065c2012-06-22 16:30:09 -070010529
10530 Py_BEGIN_ALLOW_THREADS
10531#ifdef HAVE_FSTATVFS
Larry Hastings2f936352014-08-05 14:04:04 +100010532 if (path->fd != -1) {
Larry Hastings9cf065c2012-06-22 16:30:09 -070010533#ifdef __APPLE__
10534 /* handle weak-linking on Mac OS X 10.3 */
10535 if (fstatvfs == NULL) {
Larry Hastings2f936352014-08-05 14:04:04 +100010536 fd_specified("statvfs", path->fd);
10537 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -070010538 }
10539#endif
Larry Hastings2f936352014-08-05 14:04:04 +100010540 result = fstatvfs(path->fd, &st);
Larry Hastings9cf065c2012-06-22 16:30:09 -070010541 }
10542 else
10543#endif
Larry Hastings2f936352014-08-05 14:04:04 +100010544 result = statvfs(path->narrow, &st);
Larry Hastings9cf065c2012-06-22 16:30:09 -070010545 Py_END_ALLOW_THREADS
10546
10547 if (result) {
Larry Hastings2f936352014-08-05 14:04:04 +100010548 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -070010549 }
10550
Larry Hastings2f936352014-08-05 14:04:04 +100010551 return _pystatvfs_fromstructstatvfs(st);
Guido van Rossum94f6f721999-01-06 18:42:14 +000010552}
Larry Hastings2f936352014-08-05 14:04:04 +100010553#endif /* defined(HAVE_STATVFS) && defined(HAVE_SYS_STATVFS_H) */
10554
Guido van Rossum94f6f721999-01-06 18:42:14 +000010555
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010556#ifdef MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +100010557/*[clinic input]
10558os._getdiskusage
10559
Steve Dower23ad6d02018-02-22 10:39:10 -080010560 path: path_t
Larry Hastings2f936352014-08-05 14:04:04 +100010561
10562Return disk usage statistics about the given path as a (total, free) tuple.
10563[clinic start generated code]*/
10564
Larry Hastings2f936352014-08-05 14:04:04 +100010565static PyObject *
Steve Dower23ad6d02018-02-22 10:39:10 -080010566os__getdiskusage_impl(PyObject *module, path_t *path)
10567/*[clinic end generated code: output=3bd3991f5e5c5dfb input=6af8d1b7781cc042]*/
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010568{
10569 BOOL retval;
10570 ULARGE_INTEGER _, total, free;
Joe Pamerc8c02492018-09-25 10:57:36 -040010571 DWORD err = 0;
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010572
10573 Py_BEGIN_ALLOW_THREADS
Steve Dower23ad6d02018-02-22 10:39:10 -080010574 retval = GetDiskFreeSpaceExW(path->wide, &_, &total, &free);
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010575 Py_END_ALLOW_THREADS
Joe Pamerc8c02492018-09-25 10:57:36 -040010576 if (retval == 0) {
10577 if (GetLastError() == ERROR_DIRECTORY) {
10578 wchar_t *dir_path = NULL;
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010579
Joe Pamerc8c02492018-09-25 10:57:36 -040010580 dir_path = PyMem_New(wchar_t, path->length + 1);
10581 if (dir_path == NULL) {
10582 return PyErr_NoMemory();
10583 }
10584
10585 wcscpy_s(dir_path, path->length + 1, path->wide);
10586
10587 if (_dirnameW(dir_path) != -1) {
10588 Py_BEGIN_ALLOW_THREADS
10589 retval = GetDiskFreeSpaceExW(dir_path, &_, &total, &free);
10590 Py_END_ALLOW_THREADS
10591 }
10592 /* Record the last error in case it's modified by PyMem_Free. */
10593 err = GetLastError();
10594 PyMem_Free(dir_path);
10595 if (retval) {
10596 goto success;
10597 }
10598 }
10599 return PyErr_SetFromWindowsErr(err);
10600 }
10601
10602success:
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010603 return Py_BuildValue("(LL)", total.QuadPart, free.QuadPart);
10604}
Larry Hastings2f936352014-08-05 14:04:04 +100010605#endif /* MS_WINDOWS */
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010606
10607
Fred Drakec9680921999-12-13 16:37:25 +000010608/* This is used for fpathconf(), pathconf(), confstr() and sysconf().
10609 * It maps strings representing configuration variable names to
10610 * integer values, allowing those functions to be called with the
Thomas Wouters7e474022000-07-16 12:04:32 +000010611 * magic names instead of polluting the module's namespace with tons of
Fred Drake12c6e2d1999-12-14 21:25:03 +000010612 * rarely-used constants. There are three separate tables that use
10613 * these definitions.
Fred Drakebec628d1999-12-15 18:31:10 +000010614 *
10615 * This code is always included, even if none of the interfaces that
10616 * need it are included. The #if hackery needed to avoid it would be
10617 * sufficiently pervasive that it's not worth the loss of readability.
Fred Drakec9680921999-12-13 16:37:25 +000010618 */
10619struct constdef {
Serhiy Storchaka2d06e842015-12-25 19:53:18 +020010620 const char *name;
Serhiy Storchaka56f6e762015-09-06 21:25:30 +030010621 int value;
Fred Drakec9680921999-12-13 16:37:25 +000010622};
10623
Fred Drake12c6e2d1999-12-14 21:25:03 +000010624static int
Fredrik Lundhff7df9d2000-07-08 22:48:53 +000010625conv_confname(PyObject *arg, int *valuep, struct constdef *table,
Guido van Rossum7d5baac2007-08-27 23:24:46 +000010626 size_t tablesize)
Fred Drake12c6e2d1999-12-14 21:25:03 +000010627{
Christian Heimes217cfd12007-12-02 14:31:20 +000010628 if (PyLong_Check(arg)) {
Serhiy Storchaka56f6e762015-09-06 21:25:30 +030010629 int value = _PyLong_AsInt(arg);
10630 if (value == -1 && PyErr_Occurred())
10631 return 0;
10632 *valuep = value;
Stefan Krah0e803b32010-11-26 16:16:47 +000010633 return 1;
Fred Drake12c6e2d1999-12-14 21:25:03 +000010634 }
Guido van Rossumbce56a62007-05-10 18:04:33 +000010635 else {
Stefan Krah0e803b32010-11-26 16:16:47 +000010636 /* look up the value in the table using a binary search */
10637 size_t lo = 0;
10638 size_t mid;
10639 size_t hi = tablesize;
10640 int cmp;
10641 const char *confname;
10642 if (!PyUnicode_Check(arg)) {
10643 PyErr_SetString(PyExc_TypeError,
10644 "configuration names must be strings or integers");
10645 return 0;
Victor Stinner8c62be82010-05-06 00:08:46 +000010646 }
Serhiy Storchaka06515832016-11-20 09:13:07 +020010647 confname = PyUnicode_AsUTF8(arg);
Stefan Krah0e803b32010-11-26 16:16:47 +000010648 if (confname == NULL)
10649 return 0;
10650 while (lo < hi) {
10651 mid = (lo + hi) / 2;
10652 cmp = strcmp(confname, table[mid].name);
10653 if (cmp < 0)
10654 hi = mid;
10655 else if (cmp > 0)
10656 lo = mid + 1;
10657 else {
10658 *valuep = table[mid].value;
10659 return 1;
10660 }
10661 }
10662 PyErr_SetString(PyExc_ValueError, "unrecognized configuration name");
10663 return 0;
Victor Stinner8c62be82010-05-06 00:08:46 +000010664 }
Fred Drake12c6e2d1999-12-14 21:25:03 +000010665}
10666
10667
10668#if defined(HAVE_FPATHCONF) || defined(HAVE_PATHCONF)
10669static struct constdef posix_constants_pathconf[] = {
Fred Draked86ed291999-12-15 15:34:33 +000010670#ifdef _PC_ABI_AIO_XFER_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010671 {"PC_ABI_AIO_XFER_MAX", _PC_ABI_AIO_XFER_MAX},
Fred Draked86ed291999-12-15 15:34:33 +000010672#endif
10673#ifdef _PC_ABI_ASYNC_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000010674 {"PC_ABI_ASYNC_IO", _PC_ABI_ASYNC_IO},
Fred Draked86ed291999-12-15 15:34:33 +000010675#endif
Fred Drakec9680921999-12-13 16:37:25 +000010676#ifdef _PC_ASYNC_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000010677 {"PC_ASYNC_IO", _PC_ASYNC_IO},
Fred Drakec9680921999-12-13 16:37:25 +000010678#endif
10679#ifdef _PC_CHOWN_RESTRICTED
Victor Stinner8c62be82010-05-06 00:08:46 +000010680 {"PC_CHOWN_RESTRICTED", _PC_CHOWN_RESTRICTED},
Fred Drakec9680921999-12-13 16:37:25 +000010681#endif
10682#ifdef _PC_FILESIZEBITS
Victor Stinner8c62be82010-05-06 00:08:46 +000010683 {"PC_FILESIZEBITS", _PC_FILESIZEBITS},
Fred Drakec9680921999-12-13 16:37:25 +000010684#endif
10685#ifdef _PC_LAST
Victor Stinner8c62be82010-05-06 00:08:46 +000010686 {"PC_LAST", _PC_LAST},
Fred Drakec9680921999-12-13 16:37:25 +000010687#endif
10688#ifdef _PC_LINK_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010689 {"PC_LINK_MAX", _PC_LINK_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010690#endif
10691#ifdef _PC_MAX_CANON
Victor Stinner8c62be82010-05-06 00:08:46 +000010692 {"PC_MAX_CANON", _PC_MAX_CANON},
Fred Drakec9680921999-12-13 16:37:25 +000010693#endif
10694#ifdef _PC_MAX_INPUT
Victor Stinner8c62be82010-05-06 00:08:46 +000010695 {"PC_MAX_INPUT", _PC_MAX_INPUT},
Fred Drakec9680921999-12-13 16:37:25 +000010696#endif
10697#ifdef _PC_NAME_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010698 {"PC_NAME_MAX", _PC_NAME_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010699#endif
10700#ifdef _PC_NO_TRUNC
Victor Stinner8c62be82010-05-06 00:08:46 +000010701 {"PC_NO_TRUNC", _PC_NO_TRUNC},
Fred Drakec9680921999-12-13 16:37:25 +000010702#endif
10703#ifdef _PC_PATH_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010704 {"PC_PATH_MAX", _PC_PATH_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010705#endif
10706#ifdef _PC_PIPE_BUF
Victor Stinner8c62be82010-05-06 00:08:46 +000010707 {"PC_PIPE_BUF", _PC_PIPE_BUF},
Fred Drakec9680921999-12-13 16:37:25 +000010708#endif
10709#ifdef _PC_PRIO_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000010710 {"PC_PRIO_IO", _PC_PRIO_IO},
Fred Drakec9680921999-12-13 16:37:25 +000010711#endif
10712#ifdef _PC_SOCK_MAXBUF
Victor Stinner8c62be82010-05-06 00:08:46 +000010713 {"PC_SOCK_MAXBUF", _PC_SOCK_MAXBUF},
Fred Drakec9680921999-12-13 16:37:25 +000010714#endif
10715#ifdef _PC_SYNC_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000010716 {"PC_SYNC_IO", _PC_SYNC_IO},
Fred Drakec9680921999-12-13 16:37:25 +000010717#endif
10718#ifdef _PC_VDISABLE
Victor Stinner8c62be82010-05-06 00:08:46 +000010719 {"PC_VDISABLE", _PC_VDISABLE},
Fred Drakec9680921999-12-13 16:37:25 +000010720#endif
Jesus Cea7e9065c2010-10-25 13:02:04 +000010721#ifdef _PC_ACL_ENABLED
10722 {"PC_ACL_ENABLED", _PC_ACL_ENABLED},
10723#endif
10724#ifdef _PC_MIN_HOLE_SIZE
10725 {"PC_MIN_HOLE_SIZE", _PC_MIN_HOLE_SIZE},
10726#endif
10727#ifdef _PC_ALLOC_SIZE_MIN
10728 {"PC_ALLOC_SIZE_MIN", _PC_ALLOC_SIZE_MIN},
10729#endif
10730#ifdef _PC_REC_INCR_XFER_SIZE
10731 {"PC_REC_INCR_XFER_SIZE", _PC_REC_INCR_XFER_SIZE},
10732#endif
10733#ifdef _PC_REC_MAX_XFER_SIZE
10734 {"PC_REC_MAX_XFER_SIZE", _PC_REC_MAX_XFER_SIZE},
10735#endif
10736#ifdef _PC_REC_MIN_XFER_SIZE
10737 {"PC_REC_MIN_XFER_SIZE", _PC_REC_MIN_XFER_SIZE},
10738#endif
10739#ifdef _PC_REC_XFER_ALIGN
10740 {"PC_REC_XFER_ALIGN", _PC_REC_XFER_ALIGN},
10741#endif
10742#ifdef _PC_SYMLINK_MAX
10743 {"PC_SYMLINK_MAX", _PC_SYMLINK_MAX},
10744#endif
10745#ifdef _PC_XATTR_ENABLED
10746 {"PC_XATTR_ENABLED", _PC_XATTR_ENABLED},
10747#endif
10748#ifdef _PC_XATTR_EXISTS
10749 {"PC_XATTR_EXISTS", _PC_XATTR_EXISTS},
10750#endif
10751#ifdef _PC_TIMESTAMP_RESOLUTION
10752 {"PC_TIMESTAMP_RESOLUTION", _PC_TIMESTAMP_RESOLUTION},
10753#endif
Fred Drakec9680921999-12-13 16:37:25 +000010754};
10755
Fred Drakec9680921999-12-13 16:37:25 +000010756static int
Fredrik Lundhff7df9d2000-07-08 22:48:53 +000010757conv_path_confname(PyObject *arg, int *valuep)
Fred Drakec9680921999-12-13 16:37:25 +000010758{
10759 return conv_confname(arg, valuep, posix_constants_pathconf,
10760 sizeof(posix_constants_pathconf)
10761 / sizeof(struct constdef));
10762}
10763#endif
10764
Larry Hastings2f936352014-08-05 14:04:04 +100010765
Fred Drakec9680921999-12-13 16:37:25 +000010766#ifdef HAVE_FPATHCONF
Larry Hastings2f936352014-08-05 14:04:04 +100010767/*[clinic input]
10768os.fpathconf -> long
10769
10770 fd: int
10771 name: path_confname
10772 /
10773
10774Return the configuration limit name for the file descriptor fd.
10775
10776If there is no limit, return -1.
10777[clinic start generated code]*/
10778
Larry Hastings2f936352014-08-05 14:04:04 +100010779static long
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010780os_fpathconf_impl(PyObject *module, int fd, int name)
10781/*[clinic end generated code: output=d5b7042425fc3e21 input=5942a024d3777810]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010782{
10783 long limit;
10784
10785 errno = 0;
10786 limit = fpathconf(fd, name);
10787 if (limit == -1 && errno != 0)
10788 posix_error();
10789
10790 return limit;
10791}
10792#endif /* HAVE_FPATHCONF */
Fred Drakec9680921999-12-13 16:37:25 +000010793
10794
10795#ifdef HAVE_PATHCONF
Larry Hastings2f936352014-08-05 14:04:04 +100010796/*[clinic input]
10797os.pathconf -> long
10798 path: path_t(allow_fd='PATH_HAVE_FPATHCONF')
10799 name: path_confname
10800
10801Return the configuration limit name for the file or directory path.
10802
10803If there is no limit, return -1.
10804On some platforms, path may also be specified as an open file descriptor.
10805 If this functionality is unavailable, using it raises an exception.
10806[clinic start generated code]*/
10807
Larry Hastings2f936352014-08-05 14:04:04 +100010808static long
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010809os_pathconf_impl(PyObject *module, path_t *path, int name)
10810/*[clinic end generated code: output=5bedee35b293a089 input=bc3e2a985af27e5e]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010811{
Victor Stinner8c62be82010-05-06 00:08:46 +000010812 long limit;
Fred Drakec9680921999-12-13 16:37:25 +000010813
Victor Stinner8c62be82010-05-06 00:08:46 +000010814 errno = 0;
Georg Brandl306336b2012-06-24 12:55:33 +020010815#ifdef HAVE_FPATHCONF
Larry Hastings2f936352014-08-05 14:04:04 +100010816 if (path->fd != -1)
10817 limit = fpathconf(path->fd, name);
Georg Brandl306336b2012-06-24 12:55:33 +020010818 else
10819#endif
Larry Hastings2f936352014-08-05 14:04:04 +100010820 limit = pathconf(path->narrow, name);
Victor Stinner8c62be82010-05-06 00:08:46 +000010821 if (limit == -1 && errno != 0) {
10822 if (errno == EINVAL)
Stefan Krah99439262010-11-26 12:58:05 +000010823 /* could be a path or name problem */
10824 posix_error();
Fred Drakec9680921999-12-13 16:37:25 +000010825 else
Larry Hastings2f936352014-08-05 14:04:04 +100010826 path_error(path);
Victor Stinner8c62be82010-05-06 00:08:46 +000010827 }
Larry Hastings2f936352014-08-05 14:04:04 +100010828
10829 return limit;
Fred Drakec9680921999-12-13 16:37:25 +000010830}
Larry Hastings2f936352014-08-05 14:04:04 +100010831#endif /* HAVE_PATHCONF */
Fred Drakec9680921999-12-13 16:37:25 +000010832
10833#ifdef HAVE_CONFSTR
10834static struct constdef posix_constants_confstr[] = {
Fred Draked86ed291999-12-15 15:34:33 +000010835#ifdef _CS_ARCHITECTURE
Victor Stinner8c62be82010-05-06 00:08:46 +000010836 {"CS_ARCHITECTURE", _CS_ARCHITECTURE},
Fred Draked86ed291999-12-15 15:34:33 +000010837#endif
Mark Dickinson876d7c82010-04-16 12:47:52 +000010838#ifdef _CS_GNU_LIBC_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000010839 {"CS_GNU_LIBC_VERSION", _CS_GNU_LIBC_VERSION},
Mark Dickinson876d7c82010-04-16 12:47:52 +000010840#endif
10841#ifdef _CS_GNU_LIBPTHREAD_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000010842 {"CS_GNU_LIBPTHREAD_VERSION", _CS_GNU_LIBPTHREAD_VERSION},
Mark Dickinson876d7c82010-04-16 12:47:52 +000010843#endif
Fred Draked86ed291999-12-15 15:34:33 +000010844#ifdef _CS_HOSTNAME
Victor Stinner8c62be82010-05-06 00:08:46 +000010845 {"CS_HOSTNAME", _CS_HOSTNAME},
Fred Draked86ed291999-12-15 15:34:33 +000010846#endif
10847#ifdef _CS_HW_PROVIDER
Victor Stinner8c62be82010-05-06 00:08:46 +000010848 {"CS_HW_PROVIDER", _CS_HW_PROVIDER},
Fred Draked86ed291999-12-15 15:34:33 +000010849#endif
10850#ifdef _CS_HW_SERIAL
Victor Stinner8c62be82010-05-06 00:08:46 +000010851 {"CS_HW_SERIAL", _CS_HW_SERIAL},
Fred Draked86ed291999-12-15 15:34:33 +000010852#endif
10853#ifdef _CS_INITTAB_NAME
Victor Stinner8c62be82010-05-06 00:08:46 +000010854 {"CS_INITTAB_NAME", _CS_INITTAB_NAME},
Fred Draked86ed291999-12-15 15:34:33 +000010855#endif
Fred Drakec9680921999-12-13 16:37:25 +000010856#ifdef _CS_LFS64_CFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010857 {"CS_LFS64_CFLAGS", _CS_LFS64_CFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010858#endif
10859#ifdef _CS_LFS64_LDFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010860 {"CS_LFS64_LDFLAGS", _CS_LFS64_LDFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010861#endif
10862#ifdef _CS_LFS64_LIBS
Victor Stinner8c62be82010-05-06 00:08:46 +000010863 {"CS_LFS64_LIBS", _CS_LFS64_LIBS},
Fred Drakec9680921999-12-13 16:37:25 +000010864#endif
10865#ifdef _CS_LFS64_LINTFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010866 {"CS_LFS64_LINTFLAGS", _CS_LFS64_LINTFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010867#endif
10868#ifdef _CS_LFS_CFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010869 {"CS_LFS_CFLAGS", _CS_LFS_CFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010870#endif
10871#ifdef _CS_LFS_LDFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010872 {"CS_LFS_LDFLAGS", _CS_LFS_LDFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010873#endif
10874#ifdef _CS_LFS_LIBS
Victor Stinner8c62be82010-05-06 00:08:46 +000010875 {"CS_LFS_LIBS", _CS_LFS_LIBS},
Fred Drakec9680921999-12-13 16:37:25 +000010876#endif
10877#ifdef _CS_LFS_LINTFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010878 {"CS_LFS_LINTFLAGS", _CS_LFS_LINTFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010879#endif
Fred Draked86ed291999-12-15 15:34:33 +000010880#ifdef _CS_MACHINE
Victor Stinner8c62be82010-05-06 00:08:46 +000010881 {"CS_MACHINE", _CS_MACHINE},
Fred Draked86ed291999-12-15 15:34:33 +000010882#endif
Fred Drakec9680921999-12-13 16:37:25 +000010883#ifdef _CS_PATH
Victor Stinner8c62be82010-05-06 00:08:46 +000010884 {"CS_PATH", _CS_PATH},
Fred Drakec9680921999-12-13 16:37:25 +000010885#endif
Fred Draked86ed291999-12-15 15:34:33 +000010886#ifdef _CS_RELEASE
Victor Stinner8c62be82010-05-06 00:08:46 +000010887 {"CS_RELEASE", _CS_RELEASE},
Fred Draked86ed291999-12-15 15:34:33 +000010888#endif
10889#ifdef _CS_SRPC_DOMAIN
Victor Stinner8c62be82010-05-06 00:08:46 +000010890 {"CS_SRPC_DOMAIN", _CS_SRPC_DOMAIN},
Fred Draked86ed291999-12-15 15:34:33 +000010891#endif
10892#ifdef _CS_SYSNAME
Victor Stinner8c62be82010-05-06 00:08:46 +000010893 {"CS_SYSNAME", _CS_SYSNAME},
Fred Draked86ed291999-12-15 15:34:33 +000010894#endif
10895#ifdef _CS_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000010896 {"CS_VERSION", _CS_VERSION},
Fred Draked86ed291999-12-15 15:34:33 +000010897#endif
Fred Drakec9680921999-12-13 16:37:25 +000010898#ifdef _CS_XBS5_ILP32_OFF32_CFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010899 {"CS_XBS5_ILP32_OFF32_CFLAGS", _CS_XBS5_ILP32_OFF32_CFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010900#endif
10901#ifdef _CS_XBS5_ILP32_OFF32_LDFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010902 {"CS_XBS5_ILP32_OFF32_LDFLAGS", _CS_XBS5_ILP32_OFF32_LDFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010903#endif
10904#ifdef _CS_XBS5_ILP32_OFF32_LIBS
Victor Stinner8c62be82010-05-06 00:08:46 +000010905 {"CS_XBS5_ILP32_OFF32_LIBS", _CS_XBS5_ILP32_OFF32_LIBS},
Fred Drakec9680921999-12-13 16:37:25 +000010906#endif
10907#ifdef _CS_XBS5_ILP32_OFF32_LINTFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010908 {"CS_XBS5_ILP32_OFF32_LINTFLAGS", _CS_XBS5_ILP32_OFF32_LINTFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010909#endif
10910#ifdef _CS_XBS5_ILP32_OFFBIG_CFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010911 {"CS_XBS5_ILP32_OFFBIG_CFLAGS", _CS_XBS5_ILP32_OFFBIG_CFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010912#endif
10913#ifdef _CS_XBS5_ILP32_OFFBIG_LDFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010914 {"CS_XBS5_ILP32_OFFBIG_LDFLAGS", _CS_XBS5_ILP32_OFFBIG_LDFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010915#endif
10916#ifdef _CS_XBS5_ILP32_OFFBIG_LIBS
Victor Stinner8c62be82010-05-06 00:08:46 +000010917 {"CS_XBS5_ILP32_OFFBIG_LIBS", _CS_XBS5_ILP32_OFFBIG_LIBS},
Fred Drakec9680921999-12-13 16:37:25 +000010918#endif
10919#ifdef _CS_XBS5_ILP32_OFFBIG_LINTFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010920 {"CS_XBS5_ILP32_OFFBIG_LINTFLAGS", _CS_XBS5_ILP32_OFFBIG_LINTFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010921#endif
10922#ifdef _CS_XBS5_LP64_OFF64_CFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010923 {"CS_XBS5_LP64_OFF64_CFLAGS", _CS_XBS5_LP64_OFF64_CFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010924#endif
10925#ifdef _CS_XBS5_LP64_OFF64_LDFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010926 {"CS_XBS5_LP64_OFF64_LDFLAGS", _CS_XBS5_LP64_OFF64_LDFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010927#endif
10928#ifdef _CS_XBS5_LP64_OFF64_LIBS
Victor Stinner8c62be82010-05-06 00:08:46 +000010929 {"CS_XBS5_LP64_OFF64_LIBS", _CS_XBS5_LP64_OFF64_LIBS},
Fred Drakec9680921999-12-13 16:37:25 +000010930#endif
10931#ifdef _CS_XBS5_LP64_OFF64_LINTFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010932 {"CS_XBS5_LP64_OFF64_LINTFLAGS", _CS_XBS5_LP64_OFF64_LINTFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010933#endif
10934#ifdef _CS_XBS5_LPBIG_OFFBIG_CFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010935 {"CS_XBS5_LPBIG_OFFBIG_CFLAGS", _CS_XBS5_LPBIG_OFFBIG_CFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010936#endif
10937#ifdef _CS_XBS5_LPBIG_OFFBIG_LDFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010938 {"CS_XBS5_LPBIG_OFFBIG_LDFLAGS", _CS_XBS5_LPBIG_OFFBIG_LDFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010939#endif
10940#ifdef _CS_XBS5_LPBIG_OFFBIG_LIBS
Victor Stinner8c62be82010-05-06 00:08:46 +000010941 {"CS_XBS5_LPBIG_OFFBIG_LIBS", _CS_XBS5_LPBIG_OFFBIG_LIBS},
Fred Drakec9680921999-12-13 16:37:25 +000010942#endif
10943#ifdef _CS_XBS5_LPBIG_OFFBIG_LINTFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010944 {"CS_XBS5_LPBIG_OFFBIG_LINTFLAGS", _CS_XBS5_LPBIG_OFFBIG_LINTFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010945#endif
Fred Draked86ed291999-12-15 15:34:33 +000010946#ifdef _MIPS_CS_AVAIL_PROCESSORS
Victor Stinner8c62be82010-05-06 00:08:46 +000010947 {"MIPS_CS_AVAIL_PROCESSORS", _MIPS_CS_AVAIL_PROCESSORS},
Fred Draked86ed291999-12-15 15:34:33 +000010948#endif
10949#ifdef _MIPS_CS_BASE
Victor Stinner8c62be82010-05-06 00:08:46 +000010950 {"MIPS_CS_BASE", _MIPS_CS_BASE},
Fred Draked86ed291999-12-15 15:34:33 +000010951#endif
10952#ifdef _MIPS_CS_HOSTID
Victor Stinner8c62be82010-05-06 00:08:46 +000010953 {"MIPS_CS_HOSTID", _MIPS_CS_HOSTID},
Fred Draked86ed291999-12-15 15:34:33 +000010954#endif
10955#ifdef _MIPS_CS_HW_NAME
Victor Stinner8c62be82010-05-06 00:08:46 +000010956 {"MIPS_CS_HW_NAME", _MIPS_CS_HW_NAME},
Fred Draked86ed291999-12-15 15:34:33 +000010957#endif
10958#ifdef _MIPS_CS_NUM_PROCESSORS
Victor Stinner8c62be82010-05-06 00:08:46 +000010959 {"MIPS_CS_NUM_PROCESSORS", _MIPS_CS_NUM_PROCESSORS},
Fred Draked86ed291999-12-15 15:34:33 +000010960#endif
10961#ifdef _MIPS_CS_OSREL_MAJ
Victor Stinner8c62be82010-05-06 00:08:46 +000010962 {"MIPS_CS_OSREL_MAJ", _MIPS_CS_OSREL_MAJ},
Fred Draked86ed291999-12-15 15:34:33 +000010963#endif
10964#ifdef _MIPS_CS_OSREL_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000010965 {"MIPS_CS_OSREL_MIN", _MIPS_CS_OSREL_MIN},
Fred Draked86ed291999-12-15 15:34:33 +000010966#endif
10967#ifdef _MIPS_CS_OSREL_PATCH
Victor Stinner8c62be82010-05-06 00:08:46 +000010968 {"MIPS_CS_OSREL_PATCH", _MIPS_CS_OSREL_PATCH},
Fred Draked86ed291999-12-15 15:34:33 +000010969#endif
10970#ifdef _MIPS_CS_OS_NAME
Victor Stinner8c62be82010-05-06 00:08:46 +000010971 {"MIPS_CS_OS_NAME", _MIPS_CS_OS_NAME},
Fred Draked86ed291999-12-15 15:34:33 +000010972#endif
10973#ifdef _MIPS_CS_OS_PROVIDER
Victor Stinner8c62be82010-05-06 00:08:46 +000010974 {"MIPS_CS_OS_PROVIDER", _MIPS_CS_OS_PROVIDER},
Fred Draked86ed291999-12-15 15:34:33 +000010975#endif
10976#ifdef _MIPS_CS_PROCESSORS
Victor Stinner8c62be82010-05-06 00:08:46 +000010977 {"MIPS_CS_PROCESSORS", _MIPS_CS_PROCESSORS},
Fred Draked86ed291999-12-15 15:34:33 +000010978#endif
10979#ifdef _MIPS_CS_SERIAL
Victor Stinner8c62be82010-05-06 00:08:46 +000010980 {"MIPS_CS_SERIAL", _MIPS_CS_SERIAL},
Fred Draked86ed291999-12-15 15:34:33 +000010981#endif
10982#ifdef _MIPS_CS_VENDOR
Victor Stinner8c62be82010-05-06 00:08:46 +000010983 {"MIPS_CS_VENDOR", _MIPS_CS_VENDOR},
Fred Draked86ed291999-12-15 15:34:33 +000010984#endif
Fred Drakec9680921999-12-13 16:37:25 +000010985};
10986
10987static int
Fredrik Lundhff7df9d2000-07-08 22:48:53 +000010988conv_confstr_confname(PyObject *arg, int *valuep)
Fred Drakec9680921999-12-13 16:37:25 +000010989{
10990 return conv_confname(arg, valuep, posix_constants_confstr,
10991 sizeof(posix_constants_confstr)
10992 / sizeof(struct constdef));
10993}
10994
Larry Hastings2f936352014-08-05 14:04:04 +100010995
10996/*[clinic input]
10997os.confstr
10998
10999 name: confstr_confname
11000 /
11001
11002Return a string-valued system configuration variable.
11003[clinic start generated code]*/
11004
Larry Hastings2f936352014-08-05 14:04:04 +100011005static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011006os_confstr_impl(PyObject *module, int name)
11007/*[clinic end generated code: output=bfb0b1b1e49b9383 input=18fb4d0567242e65]*/
Fred Drakec9680921999-12-13 16:37:25 +000011008{
11009 PyObject *result = NULL;
Victor Stinnercb043522010-09-10 23:49:04 +000011010 char buffer[255];
Victor Stinnerdd3a6a52013-06-25 23:13:47 +020011011 size_t len;
Fred Drakec9680921999-12-13 16:37:25 +000011012
Victor Stinnercb043522010-09-10 23:49:04 +000011013 errno = 0;
11014 len = confstr(name, buffer, sizeof(buffer));
11015 if (len == 0) {
11016 if (errno) {
11017 posix_error();
11018 return NULL;
Fred Drakec9680921999-12-13 16:37:25 +000011019 }
11020 else {
Victor Stinnercb043522010-09-10 23:49:04 +000011021 Py_RETURN_NONE;
Fred Drakec9680921999-12-13 16:37:25 +000011022 }
11023 }
Victor Stinnercb043522010-09-10 23:49:04 +000011024
Victor Stinnerdd3a6a52013-06-25 23:13:47 +020011025 if (len >= sizeof(buffer)) {
Victor Stinnercbc18f32014-12-05 22:51:51 +010011026 size_t len2;
Victor Stinnercb043522010-09-10 23:49:04 +000011027 char *buf = PyMem_Malloc(len);
11028 if (buf == NULL)
11029 return PyErr_NoMemory();
Victor Stinnercbc18f32014-12-05 22:51:51 +010011030 len2 = confstr(name, buf, len);
11031 assert(len == len2);
Christian Heimes8714cfd2015-04-21 10:57:41 +020011032 result = PyUnicode_DecodeFSDefaultAndSize(buf, len2-1);
Victor Stinnercb043522010-09-10 23:49:04 +000011033 PyMem_Free(buf);
11034 }
11035 else
11036 result = PyUnicode_DecodeFSDefaultAndSize(buffer, len-1);
Fred Drakec9680921999-12-13 16:37:25 +000011037 return result;
11038}
Larry Hastings2f936352014-08-05 14:04:04 +100011039#endif /* HAVE_CONFSTR */
Fred Drakec9680921999-12-13 16:37:25 +000011040
11041
11042#ifdef HAVE_SYSCONF
11043static struct constdef posix_constants_sysconf[] = {
11044#ifdef _SC_2_CHAR_TERM
Victor Stinner8c62be82010-05-06 00:08:46 +000011045 {"SC_2_CHAR_TERM", _SC_2_CHAR_TERM},
Fred Drakec9680921999-12-13 16:37:25 +000011046#endif
11047#ifdef _SC_2_C_BIND
Victor Stinner8c62be82010-05-06 00:08:46 +000011048 {"SC_2_C_BIND", _SC_2_C_BIND},
Fred Drakec9680921999-12-13 16:37:25 +000011049#endif
11050#ifdef _SC_2_C_DEV
Victor Stinner8c62be82010-05-06 00:08:46 +000011051 {"SC_2_C_DEV", _SC_2_C_DEV},
Fred Drakec9680921999-12-13 16:37:25 +000011052#endif
11053#ifdef _SC_2_C_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000011054 {"SC_2_C_VERSION", _SC_2_C_VERSION},
Fred Drakec9680921999-12-13 16:37:25 +000011055#endif
11056#ifdef _SC_2_FORT_DEV
Victor Stinner8c62be82010-05-06 00:08:46 +000011057 {"SC_2_FORT_DEV", _SC_2_FORT_DEV},
Fred Drakec9680921999-12-13 16:37:25 +000011058#endif
11059#ifdef _SC_2_FORT_RUN
Victor Stinner8c62be82010-05-06 00:08:46 +000011060 {"SC_2_FORT_RUN", _SC_2_FORT_RUN},
Fred Drakec9680921999-12-13 16:37:25 +000011061#endif
11062#ifdef _SC_2_LOCALEDEF
Victor Stinner8c62be82010-05-06 00:08:46 +000011063 {"SC_2_LOCALEDEF", _SC_2_LOCALEDEF},
Fred Drakec9680921999-12-13 16:37:25 +000011064#endif
11065#ifdef _SC_2_SW_DEV
Victor Stinner8c62be82010-05-06 00:08:46 +000011066 {"SC_2_SW_DEV", _SC_2_SW_DEV},
Fred Drakec9680921999-12-13 16:37:25 +000011067#endif
11068#ifdef _SC_2_UPE
Victor Stinner8c62be82010-05-06 00:08:46 +000011069 {"SC_2_UPE", _SC_2_UPE},
Fred Drakec9680921999-12-13 16:37:25 +000011070#endif
11071#ifdef _SC_2_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000011072 {"SC_2_VERSION", _SC_2_VERSION},
Fred Drakec9680921999-12-13 16:37:25 +000011073#endif
Fred Draked86ed291999-12-15 15:34:33 +000011074#ifdef _SC_ABI_ASYNCHRONOUS_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000011075 {"SC_ABI_ASYNCHRONOUS_IO", _SC_ABI_ASYNCHRONOUS_IO},
Fred Draked86ed291999-12-15 15:34:33 +000011076#endif
11077#ifdef _SC_ACL
Victor Stinner8c62be82010-05-06 00:08:46 +000011078 {"SC_ACL", _SC_ACL},
Fred Draked86ed291999-12-15 15:34:33 +000011079#endif
Fred Drakec9680921999-12-13 16:37:25 +000011080#ifdef _SC_AIO_LISTIO_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011081 {"SC_AIO_LISTIO_MAX", _SC_AIO_LISTIO_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011082#endif
Fred Drakec9680921999-12-13 16:37:25 +000011083#ifdef _SC_AIO_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011084 {"SC_AIO_MAX", _SC_AIO_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011085#endif
11086#ifdef _SC_AIO_PRIO_DELTA_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011087 {"SC_AIO_PRIO_DELTA_MAX", _SC_AIO_PRIO_DELTA_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011088#endif
11089#ifdef _SC_ARG_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011090 {"SC_ARG_MAX", _SC_ARG_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011091#endif
11092#ifdef _SC_ASYNCHRONOUS_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000011093 {"SC_ASYNCHRONOUS_IO", _SC_ASYNCHRONOUS_IO},
Fred Drakec9680921999-12-13 16:37:25 +000011094#endif
11095#ifdef _SC_ATEXIT_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011096 {"SC_ATEXIT_MAX", _SC_ATEXIT_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011097#endif
Fred Draked86ed291999-12-15 15:34:33 +000011098#ifdef _SC_AUDIT
Victor Stinner8c62be82010-05-06 00:08:46 +000011099 {"SC_AUDIT", _SC_AUDIT},
Fred Draked86ed291999-12-15 15:34:33 +000011100#endif
Fred Drakec9680921999-12-13 16:37:25 +000011101#ifdef _SC_AVPHYS_PAGES
Victor Stinner8c62be82010-05-06 00:08:46 +000011102 {"SC_AVPHYS_PAGES", _SC_AVPHYS_PAGES},
Fred Drakec9680921999-12-13 16:37:25 +000011103#endif
11104#ifdef _SC_BC_BASE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011105 {"SC_BC_BASE_MAX", _SC_BC_BASE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011106#endif
11107#ifdef _SC_BC_DIM_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011108 {"SC_BC_DIM_MAX", _SC_BC_DIM_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011109#endif
11110#ifdef _SC_BC_SCALE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011111 {"SC_BC_SCALE_MAX", _SC_BC_SCALE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011112#endif
11113#ifdef _SC_BC_STRING_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011114 {"SC_BC_STRING_MAX", _SC_BC_STRING_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011115#endif
Fred Draked86ed291999-12-15 15:34:33 +000011116#ifdef _SC_CAP
Victor Stinner8c62be82010-05-06 00:08:46 +000011117 {"SC_CAP", _SC_CAP},
Fred Draked86ed291999-12-15 15:34:33 +000011118#endif
Fred Drakec9680921999-12-13 16:37:25 +000011119#ifdef _SC_CHARCLASS_NAME_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011120 {"SC_CHARCLASS_NAME_MAX", _SC_CHARCLASS_NAME_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011121#endif
11122#ifdef _SC_CHAR_BIT
Victor Stinner8c62be82010-05-06 00:08:46 +000011123 {"SC_CHAR_BIT", _SC_CHAR_BIT},
Fred Drakec9680921999-12-13 16:37:25 +000011124#endif
11125#ifdef _SC_CHAR_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011126 {"SC_CHAR_MAX", _SC_CHAR_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011127#endif
11128#ifdef _SC_CHAR_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000011129 {"SC_CHAR_MIN", _SC_CHAR_MIN},
Fred Drakec9680921999-12-13 16:37:25 +000011130#endif
11131#ifdef _SC_CHILD_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011132 {"SC_CHILD_MAX", _SC_CHILD_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011133#endif
11134#ifdef _SC_CLK_TCK
Victor Stinner8c62be82010-05-06 00:08:46 +000011135 {"SC_CLK_TCK", _SC_CLK_TCK},
Fred Drakec9680921999-12-13 16:37:25 +000011136#endif
11137#ifdef _SC_COHER_BLKSZ
Victor Stinner8c62be82010-05-06 00:08:46 +000011138 {"SC_COHER_BLKSZ", _SC_COHER_BLKSZ},
Fred Drakec9680921999-12-13 16:37:25 +000011139#endif
11140#ifdef _SC_COLL_WEIGHTS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011141 {"SC_COLL_WEIGHTS_MAX", _SC_COLL_WEIGHTS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011142#endif
11143#ifdef _SC_DCACHE_ASSOC
Victor Stinner8c62be82010-05-06 00:08:46 +000011144 {"SC_DCACHE_ASSOC", _SC_DCACHE_ASSOC},
Fred Drakec9680921999-12-13 16:37:25 +000011145#endif
11146#ifdef _SC_DCACHE_BLKSZ
Victor Stinner8c62be82010-05-06 00:08:46 +000011147 {"SC_DCACHE_BLKSZ", _SC_DCACHE_BLKSZ},
Fred Drakec9680921999-12-13 16:37:25 +000011148#endif
11149#ifdef _SC_DCACHE_LINESZ
Victor Stinner8c62be82010-05-06 00:08:46 +000011150 {"SC_DCACHE_LINESZ", _SC_DCACHE_LINESZ},
Fred Drakec9680921999-12-13 16:37:25 +000011151#endif
11152#ifdef _SC_DCACHE_SZ
Victor Stinner8c62be82010-05-06 00:08:46 +000011153 {"SC_DCACHE_SZ", _SC_DCACHE_SZ},
Fred Drakec9680921999-12-13 16:37:25 +000011154#endif
11155#ifdef _SC_DCACHE_TBLKSZ
Victor Stinner8c62be82010-05-06 00:08:46 +000011156 {"SC_DCACHE_TBLKSZ", _SC_DCACHE_TBLKSZ},
Fred Drakec9680921999-12-13 16:37:25 +000011157#endif
11158#ifdef _SC_DELAYTIMER_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011159 {"SC_DELAYTIMER_MAX", _SC_DELAYTIMER_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011160#endif
11161#ifdef _SC_EQUIV_CLASS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011162 {"SC_EQUIV_CLASS_MAX", _SC_EQUIV_CLASS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011163#endif
11164#ifdef _SC_EXPR_NEST_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011165 {"SC_EXPR_NEST_MAX", _SC_EXPR_NEST_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011166#endif
11167#ifdef _SC_FSYNC
Victor Stinner8c62be82010-05-06 00:08:46 +000011168 {"SC_FSYNC", _SC_FSYNC},
Fred Drakec9680921999-12-13 16:37:25 +000011169#endif
11170#ifdef _SC_GETGR_R_SIZE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011171 {"SC_GETGR_R_SIZE_MAX", _SC_GETGR_R_SIZE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011172#endif
11173#ifdef _SC_GETPW_R_SIZE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011174 {"SC_GETPW_R_SIZE_MAX", _SC_GETPW_R_SIZE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011175#endif
11176#ifdef _SC_ICACHE_ASSOC
Victor Stinner8c62be82010-05-06 00:08:46 +000011177 {"SC_ICACHE_ASSOC", _SC_ICACHE_ASSOC},
Fred Drakec9680921999-12-13 16:37:25 +000011178#endif
11179#ifdef _SC_ICACHE_BLKSZ
Victor Stinner8c62be82010-05-06 00:08:46 +000011180 {"SC_ICACHE_BLKSZ", _SC_ICACHE_BLKSZ},
Fred Drakec9680921999-12-13 16:37:25 +000011181#endif
11182#ifdef _SC_ICACHE_LINESZ
Victor Stinner8c62be82010-05-06 00:08:46 +000011183 {"SC_ICACHE_LINESZ", _SC_ICACHE_LINESZ},
Fred Drakec9680921999-12-13 16:37:25 +000011184#endif
11185#ifdef _SC_ICACHE_SZ
Victor Stinner8c62be82010-05-06 00:08:46 +000011186 {"SC_ICACHE_SZ", _SC_ICACHE_SZ},
Fred Drakec9680921999-12-13 16:37:25 +000011187#endif
Fred Draked86ed291999-12-15 15:34:33 +000011188#ifdef _SC_INF
Victor Stinner8c62be82010-05-06 00:08:46 +000011189 {"SC_INF", _SC_INF},
Fred Draked86ed291999-12-15 15:34:33 +000011190#endif
Fred Drakec9680921999-12-13 16:37:25 +000011191#ifdef _SC_INT_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011192 {"SC_INT_MAX", _SC_INT_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011193#endif
11194#ifdef _SC_INT_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000011195 {"SC_INT_MIN", _SC_INT_MIN},
Fred Drakec9680921999-12-13 16:37:25 +000011196#endif
11197#ifdef _SC_IOV_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011198 {"SC_IOV_MAX", _SC_IOV_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011199#endif
Fred Draked86ed291999-12-15 15:34:33 +000011200#ifdef _SC_IP_SECOPTS
Victor Stinner8c62be82010-05-06 00:08:46 +000011201 {"SC_IP_SECOPTS", _SC_IP_SECOPTS},
Fred Draked86ed291999-12-15 15:34:33 +000011202#endif
Fred Drakec9680921999-12-13 16:37:25 +000011203#ifdef _SC_JOB_CONTROL
Victor Stinner8c62be82010-05-06 00:08:46 +000011204 {"SC_JOB_CONTROL", _SC_JOB_CONTROL},
Fred Drakec9680921999-12-13 16:37:25 +000011205#endif
Fred Draked86ed291999-12-15 15:34:33 +000011206#ifdef _SC_KERN_POINTERS
Victor Stinner8c62be82010-05-06 00:08:46 +000011207 {"SC_KERN_POINTERS", _SC_KERN_POINTERS},
Fred Draked86ed291999-12-15 15:34:33 +000011208#endif
11209#ifdef _SC_KERN_SIM
Victor Stinner8c62be82010-05-06 00:08:46 +000011210 {"SC_KERN_SIM", _SC_KERN_SIM},
Fred Draked86ed291999-12-15 15:34:33 +000011211#endif
Fred Drakec9680921999-12-13 16:37:25 +000011212#ifdef _SC_LINE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011213 {"SC_LINE_MAX", _SC_LINE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011214#endif
11215#ifdef _SC_LOGIN_NAME_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011216 {"SC_LOGIN_NAME_MAX", _SC_LOGIN_NAME_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011217#endif
11218#ifdef _SC_LOGNAME_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011219 {"SC_LOGNAME_MAX", _SC_LOGNAME_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011220#endif
11221#ifdef _SC_LONG_BIT
Victor Stinner8c62be82010-05-06 00:08:46 +000011222 {"SC_LONG_BIT", _SC_LONG_BIT},
Fred Drakec9680921999-12-13 16:37:25 +000011223#endif
Fred Draked86ed291999-12-15 15:34:33 +000011224#ifdef _SC_MAC
Victor Stinner8c62be82010-05-06 00:08:46 +000011225 {"SC_MAC", _SC_MAC},
Fred Draked86ed291999-12-15 15:34:33 +000011226#endif
Fred Drakec9680921999-12-13 16:37:25 +000011227#ifdef _SC_MAPPED_FILES
Victor Stinner8c62be82010-05-06 00:08:46 +000011228 {"SC_MAPPED_FILES", _SC_MAPPED_FILES},
Fred Drakec9680921999-12-13 16:37:25 +000011229#endif
11230#ifdef _SC_MAXPID
Victor Stinner8c62be82010-05-06 00:08:46 +000011231 {"SC_MAXPID", _SC_MAXPID},
Fred Drakec9680921999-12-13 16:37:25 +000011232#endif
11233#ifdef _SC_MB_LEN_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011234 {"SC_MB_LEN_MAX", _SC_MB_LEN_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011235#endif
11236#ifdef _SC_MEMLOCK
Victor Stinner8c62be82010-05-06 00:08:46 +000011237 {"SC_MEMLOCK", _SC_MEMLOCK},
Fred Drakec9680921999-12-13 16:37:25 +000011238#endif
11239#ifdef _SC_MEMLOCK_RANGE
Victor Stinner8c62be82010-05-06 00:08:46 +000011240 {"SC_MEMLOCK_RANGE", _SC_MEMLOCK_RANGE},
Fred Drakec9680921999-12-13 16:37:25 +000011241#endif
11242#ifdef _SC_MEMORY_PROTECTION
Victor Stinner8c62be82010-05-06 00:08:46 +000011243 {"SC_MEMORY_PROTECTION", _SC_MEMORY_PROTECTION},
Fred Drakec9680921999-12-13 16:37:25 +000011244#endif
11245#ifdef _SC_MESSAGE_PASSING
Victor Stinner8c62be82010-05-06 00:08:46 +000011246 {"SC_MESSAGE_PASSING", _SC_MESSAGE_PASSING},
Fred Drakec9680921999-12-13 16:37:25 +000011247#endif
Fred Draked86ed291999-12-15 15:34:33 +000011248#ifdef _SC_MMAP_FIXED_ALIGNMENT
Victor Stinner8c62be82010-05-06 00:08:46 +000011249 {"SC_MMAP_FIXED_ALIGNMENT", _SC_MMAP_FIXED_ALIGNMENT},
Fred Draked86ed291999-12-15 15:34:33 +000011250#endif
Fred Drakec9680921999-12-13 16:37:25 +000011251#ifdef _SC_MQ_OPEN_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011252 {"SC_MQ_OPEN_MAX", _SC_MQ_OPEN_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011253#endif
11254#ifdef _SC_MQ_PRIO_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011255 {"SC_MQ_PRIO_MAX", _SC_MQ_PRIO_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011256#endif
Fred Draked86ed291999-12-15 15:34:33 +000011257#ifdef _SC_NACLS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011258 {"SC_NACLS_MAX", _SC_NACLS_MAX},
Fred Draked86ed291999-12-15 15:34:33 +000011259#endif
Fred Drakec9680921999-12-13 16:37:25 +000011260#ifdef _SC_NGROUPS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011261 {"SC_NGROUPS_MAX", _SC_NGROUPS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011262#endif
11263#ifdef _SC_NL_ARGMAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011264 {"SC_NL_ARGMAX", _SC_NL_ARGMAX},
Fred Drakec9680921999-12-13 16:37:25 +000011265#endif
11266#ifdef _SC_NL_LANGMAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011267 {"SC_NL_LANGMAX", _SC_NL_LANGMAX},
Fred Drakec9680921999-12-13 16:37:25 +000011268#endif
11269#ifdef _SC_NL_MSGMAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011270 {"SC_NL_MSGMAX", _SC_NL_MSGMAX},
Fred Drakec9680921999-12-13 16:37:25 +000011271#endif
11272#ifdef _SC_NL_NMAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011273 {"SC_NL_NMAX", _SC_NL_NMAX},
Fred Drakec9680921999-12-13 16:37:25 +000011274#endif
11275#ifdef _SC_NL_SETMAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011276 {"SC_NL_SETMAX", _SC_NL_SETMAX},
Fred Drakec9680921999-12-13 16:37:25 +000011277#endif
11278#ifdef _SC_NL_TEXTMAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011279 {"SC_NL_TEXTMAX", _SC_NL_TEXTMAX},
Fred Drakec9680921999-12-13 16:37:25 +000011280#endif
11281#ifdef _SC_NPROCESSORS_CONF
Victor Stinner8c62be82010-05-06 00:08:46 +000011282 {"SC_NPROCESSORS_CONF", _SC_NPROCESSORS_CONF},
Fred Drakec9680921999-12-13 16:37:25 +000011283#endif
11284#ifdef _SC_NPROCESSORS_ONLN
Victor Stinner8c62be82010-05-06 00:08:46 +000011285 {"SC_NPROCESSORS_ONLN", _SC_NPROCESSORS_ONLN},
Fred Drakec9680921999-12-13 16:37:25 +000011286#endif
Fred Draked86ed291999-12-15 15:34:33 +000011287#ifdef _SC_NPROC_CONF
Victor Stinner8c62be82010-05-06 00:08:46 +000011288 {"SC_NPROC_CONF", _SC_NPROC_CONF},
Fred Draked86ed291999-12-15 15:34:33 +000011289#endif
11290#ifdef _SC_NPROC_ONLN
Victor Stinner8c62be82010-05-06 00:08:46 +000011291 {"SC_NPROC_ONLN", _SC_NPROC_ONLN},
Fred Draked86ed291999-12-15 15:34:33 +000011292#endif
Fred Drakec9680921999-12-13 16:37:25 +000011293#ifdef _SC_NZERO
Victor Stinner8c62be82010-05-06 00:08:46 +000011294 {"SC_NZERO", _SC_NZERO},
Fred Drakec9680921999-12-13 16:37:25 +000011295#endif
11296#ifdef _SC_OPEN_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011297 {"SC_OPEN_MAX", _SC_OPEN_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011298#endif
11299#ifdef _SC_PAGESIZE
Victor Stinner8c62be82010-05-06 00:08:46 +000011300 {"SC_PAGESIZE", _SC_PAGESIZE},
Fred Drakec9680921999-12-13 16:37:25 +000011301#endif
11302#ifdef _SC_PAGE_SIZE
Victor Stinner8c62be82010-05-06 00:08:46 +000011303 {"SC_PAGE_SIZE", _SC_PAGE_SIZE},
Fred Drakec9680921999-12-13 16:37:25 +000011304#endif
11305#ifdef _SC_PASS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011306 {"SC_PASS_MAX", _SC_PASS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011307#endif
11308#ifdef _SC_PHYS_PAGES
Victor Stinner8c62be82010-05-06 00:08:46 +000011309 {"SC_PHYS_PAGES", _SC_PHYS_PAGES},
Fred Drakec9680921999-12-13 16:37:25 +000011310#endif
11311#ifdef _SC_PII
Victor Stinner8c62be82010-05-06 00:08:46 +000011312 {"SC_PII", _SC_PII},
Fred Drakec9680921999-12-13 16:37:25 +000011313#endif
11314#ifdef _SC_PII_INTERNET
Victor Stinner8c62be82010-05-06 00:08:46 +000011315 {"SC_PII_INTERNET", _SC_PII_INTERNET},
Fred Drakec9680921999-12-13 16:37:25 +000011316#endif
11317#ifdef _SC_PII_INTERNET_DGRAM
Victor Stinner8c62be82010-05-06 00:08:46 +000011318 {"SC_PII_INTERNET_DGRAM", _SC_PII_INTERNET_DGRAM},
Fred Drakec9680921999-12-13 16:37:25 +000011319#endif
11320#ifdef _SC_PII_INTERNET_STREAM
Victor Stinner8c62be82010-05-06 00:08:46 +000011321 {"SC_PII_INTERNET_STREAM", _SC_PII_INTERNET_STREAM},
Fred Drakec9680921999-12-13 16:37:25 +000011322#endif
11323#ifdef _SC_PII_OSI
Victor Stinner8c62be82010-05-06 00:08:46 +000011324 {"SC_PII_OSI", _SC_PII_OSI},
Fred Drakec9680921999-12-13 16:37:25 +000011325#endif
11326#ifdef _SC_PII_OSI_CLTS
Victor Stinner8c62be82010-05-06 00:08:46 +000011327 {"SC_PII_OSI_CLTS", _SC_PII_OSI_CLTS},
Fred Drakec9680921999-12-13 16:37:25 +000011328#endif
11329#ifdef _SC_PII_OSI_COTS
Victor Stinner8c62be82010-05-06 00:08:46 +000011330 {"SC_PII_OSI_COTS", _SC_PII_OSI_COTS},
Fred Drakec9680921999-12-13 16:37:25 +000011331#endif
11332#ifdef _SC_PII_OSI_M
Victor Stinner8c62be82010-05-06 00:08:46 +000011333 {"SC_PII_OSI_M", _SC_PII_OSI_M},
Fred Drakec9680921999-12-13 16:37:25 +000011334#endif
11335#ifdef _SC_PII_SOCKET
Victor Stinner8c62be82010-05-06 00:08:46 +000011336 {"SC_PII_SOCKET", _SC_PII_SOCKET},
Fred Drakec9680921999-12-13 16:37:25 +000011337#endif
11338#ifdef _SC_PII_XTI
Victor Stinner8c62be82010-05-06 00:08:46 +000011339 {"SC_PII_XTI", _SC_PII_XTI},
Fred Drakec9680921999-12-13 16:37:25 +000011340#endif
11341#ifdef _SC_POLL
Victor Stinner8c62be82010-05-06 00:08:46 +000011342 {"SC_POLL", _SC_POLL},
Fred Drakec9680921999-12-13 16:37:25 +000011343#endif
11344#ifdef _SC_PRIORITIZED_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000011345 {"SC_PRIORITIZED_IO", _SC_PRIORITIZED_IO},
Fred Drakec9680921999-12-13 16:37:25 +000011346#endif
11347#ifdef _SC_PRIORITY_SCHEDULING
Victor Stinner8c62be82010-05-06 00:08:46 +000011348 {"SC_PRIORITY_SCHEDULING", _SC_PRIORITY_SCHEDULING},
Fred Drakec9680921999-12-13 16:37:25 +000011349#endif
11350#ifdef _SC_REALTIME_SIGNALS
Victor Stinner8c62be82010-05-06 00:08:46 +000011351 {"SC_REALTIME_SIGNALS", _SC_REALTIME_SIGNALS},
Fred Drakec9680921999-12-13 16:37:25 +000011352#endif
11353#ifdef _SC_RE_DUP_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011354 {"SC_RE_DUP_MAX", _SC_RE_DUP_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011355#endif
11356#ifdef _SC_RTSIG_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011357 {"SC_RTSIG_MAX", _SC_RTSIG_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011358#endif
11359#ifdef _SC_SAVED_IDS
Victor Stinner8c62be82010-05-06 00:08:46 +000011360 {"SC_SAVED_IDS", _SC_SAVED_IDS},
Fred Drakec9680921999-12-13 16:37:25 +000011361#endif
11362#ifdef _SC_SCHAR_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011363 {"SC_SCHAR_MAX", _SC_SCHAR_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011364#endif
11365#ifdef _SC_SCHAR_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000011366 {"SC_SCHAR_MIN", _SC_SCHAR_MIN},
Fred Drakec9680921999-12-13 16:37:25 +000011367#endif
11368#ifdef _SC_SELECT
Victor Stinner8c62be82010-05-06 00:08:46 +000011369 {"SC_SELECT", _SC_SELECT},
Fred Drakec9680921999-12-13 16:37:25 +000011370#endif
11371#ifdef _SC_SEMAPHORES
Victor Stinner8c62be82010-05-06 00:08:46 +000011372 {"SC_SEMAPHORES", _SC_SEMAPHORES},
Fred Drakec9680921999-12-13 16:37:25 +000011373#endif
11374#ifdef _SC_SEM_NSEMS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011375 {"SC_SEM_NSEMS_MAX", _SC_SEM_NSEMS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011376#endif
11377#ifdef _SC_SEM_VALUE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011378 {"SC_SEM_VALUE_MAX", _SC_SEM_VALUE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011379#endif
11380#ifdef _SC_SHARED_MEMORY_OBJECTS
Victor Stinner8c62be82010-05-06 00:08:46 +000011381 {"SC_SHARED_MEMORY_OBJECTS", _SC_SHARED_MEMORY_OBJECTS},
Fred Drakec9680921999-12-13 16:37:25 +000011382#endif
11383#ifdef _SC_SHRT_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011384 {"SC_SHRT_MAX", _SC_SHRT_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011385#endif
11386#ifdef _SC_SHRT_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000011387 {"SC_SHRT_MIN", _SC_SHRT_MIN},
Fred Drakec9680921999-12-13 16:37:25 +000011388#endif
11389#ifdef _SC_SIGQUEUE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011390 {"SC_SIGQUEUE_MAX", _SC_SIGQUEUE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011391#endif
11392#ifdef _SC_SIGRT_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011393 {"SC_SIGRT_MAX", _SC_SIGRT_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011394#endif
11395#ifdef _SC_SIGRT_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000011396 {"SC_SIGRT_MIN", _SC_SIGRT_MIN},
Fred Drakec9680921999-12-13 16:37:25 +000011397#endif
Fred Draked86ed291999-12-15 15:34:33 +000011398#ifdef _SC_SOFTPOWER
Victor Stinner8c62be82010-05-06 00:08:46 +000011399 {"SC_SOFTPOWER", _SC_SOFTPOWER},
Fred Draked86ed291999-12-15 15:34:33 +000011400#endif
Fred Drakec9680921999-12-13 16:37:25 +000011401#ifdef _SC_SPLIT_CACHE
Victor Stinner8c62be82010-05-06 00:08:46 +000011402 {"SC_SPLIT_CACHE", _SC_SPLIT_CACHE},
Fred Drakec9680921999-12-13 16:37:25 +000011403#endif
11404#ifdef _SC_SSIZE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011405 {"SC_SSIZE_MAX", _SC_SSIZE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011406#endif
11407#ifdef _SC_STACK_PROT
Victor Stinner8c62be82010-05-06 00:08:46 +000011408 {"SC_STACK_PROT", _SC_STACK_PROT},
Fred Drakec9680921999-12-13 16:37:25 +000011409#endif
11410#ifdef _SC_STREAM_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011411 {"SC_STREAM_MAX", _SC_STREAM_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011412#endif
11413#ifdef _SC_SYNCHRONIZED_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000011414 {"SC_SYNCHRONIZED_IO", _SC_SYNCHRONIZED_IO},
Fred Drakec9680921999-12-13 16:37:25 +000011415#endif
11416#ifdef _SC_THREADS
Victor Stinner8c62be82010-05-06 00:08:46 +000011417 {"SC_THREADS", _SC_THREADS},
Fred Drakec9680921999-12-13 16:37:25 +000011418#endif
11419#ifdef _SC_THREAD_ATTR_STACKADDR
Victor Stinner8c62be82010-05-06 00:08:46 +000011420 {"SC_THREAD_ATTR_STACKADDR", _SC_THREAD_ATTR_STACKADDR},
Fred Drakec9680921999-12-13 16:37:25 +000011421#endif
11422#ifdef _SC_THREAD_ATTR_STACKSIZE
Victor Stinner8c62be82010-05-06 00:08:46 +000011423 {"SC_THREAD_ATTR_STACKSIZE", _SC_THREAD_ATTR_STACKSIZE},
Fred Drakec9680921999-12-13 16:37:25 +000011424#endif
11425#ifdef _SC_THREAD_DESTRUCTOR_ITERATIONS
Victor Stinner8c62be82010-05-06 00:08:46 +000011426 {"SC_THREAD_DESTRUCTOR_ITERATIONS", _SC_THREAD_DESTRUCTOR_ITERATIONS},
Fred Drakec9680921999-12-13 16:37:25 +000011427#endif
11428#ifdef _SC_THREAD_KEYS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011429 {"SC_THREAD_KEYS_MAX", _SC_THREAD_KEYS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011430#endif
11431#ifdef _SC_THREAD_PRIORITY_SCHEDULING
Victor Stinner8c62be82010-05-06 00:08:46 +000011432 {"SC_THREAD_PRIORITY_SCHEDULING", _SC_THREAD_PRIORITY_SCHEDULING},
Fred Drakec9680921999-12-13 16:37:25 +000011433#endif
11434#ifdef _SC_THREAD_PRIO_INHERIT
Victor Stinner8c62be82010-05-06 00:08:46 +000011435 {"SC_THREAD_PRIO_INHERIT", _SC_THREAD_PRIO_INHERIT},
Fred Drakec9680921999-12-13 16:37:25 +000011436#endif
11437#ifdef _SC_THREAD_PRIO_PROTECT
Victor Stinner8c62be82010-05-06 00:08:46 +000011438 {"SC_THREAD_PRIO_PROTECT", _SC_THREAD_PRIO_PROTECT},
Fred Drakec9680921999-12-13 16:37:25 +000011439#endif
11440#ifdef _SC_THREAD_PROCESS_SHARED
Victor Stinner8c62be82010-05-06 00:08:46 +000011441 {"SC_THREAD_PROCESS_SHARED", _SC_THREAD_PROCESS_SHARED},
Fred Drakec9680921999-12-13 16:37:25 +000011442#endif
11443#ifdef _SC_THREAD_SAFE_FUNCTIONS
Victor Stinner8c62be82010-05-06 00:08:46 +000011444 {"SC_THREAD_SAFE_FUNCTIONS", _SC_THREAD_SAFE_FUNCTIONS},
Fred Drakec9680921999-12-13 16:37:25 +000011445#endif
11446#ifdef _SC_THREAD_STACK_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000011447 {"SC_THREAD_STACK_MIN", _SC_THREAD_STACK_MIN},
Fred Drakec9680921999-12-13 16:37:25 +000011448#endif
11449#ifdef _SC_THREAD_THREADS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011450 {"SC_THREAD_THREADS_MAX", _SC_THREAD_THREADS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011451#endif
11452#ifdef _SC_TIMERS
Victor Stinner8c62be82010-05-06 00:08:46 +000011453 {"SC_TIMERS", _SC_TIMERS},
Fred Drakec9680921999-12-13 16:37:25 +000011454#endif
11455#ifdef _SC_TIMER_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011456 {"SC_TIMER_MAX", _SC_TIMER_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011457#endif
11458#ifdef _SC_TTY_NAME_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011459 {"SC_TTY_NAME_MAX", _SC_TTY_NAME_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011460#endif
11461#ifdef _SC_TZNAME_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011462 {"SC_TZNAME_MAX", _SC_TZNAME_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011463#endif
11464#ifdef _SC_T_IOV_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011465 {"SC_T_IOV_MAX", _SC_T_IOV_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011466#endif
11467#ifdef _SC_UCHAR_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011468 {"SC_UCHAR_MAX", _SC_UCHAR_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011469#endif
11470#ifdef _SC_UINT_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011471 {"SC_UINT_MAX", _SC_UINT_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011472#endif
11473#ifdef _SC_UIO_MAXIOV
Victor Stinner8c62be82010-05-06 00:08:46 +000011474 {"SC_UIO_MAXIOV", _SC_UIO_MAXIOV},
Fred Drakec9680921999-12-13 16:37:25 +000011475#endif
11476#ifdef _SC_ULONG_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011477 {"SC_ULONG_MAX", _SC_ULONG_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011478#endif
11479#ifdef _SC_USHRT_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011480 {"SC_USHRT_MAX", _SC_USHRT_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011481#endif
11482#ifdef _SC_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000011483 {"SC_VERSION", _SC_VERSION},
Fred Drakec9680921999-12-13 16:37:25 +000011484#endif
11485#ifdef _SC_WORD_BIT
Victor Stinner8c62be82010-05-06 00:08:46 +000011486 {"SC_WORD_BIT", _SC_WORD_BIT},
Fred Drakec9680921999-12-13 16:37:25 +000011487#endif
11488#ifdef _SC_XBS5_ILP32_OFF32
Victor Stinner8c62be82010-05-06 00:08:46 +000011489 {"SC_XBS5_ILP32_OFF32", _SC_XBS5_ILP32_OFF32},
Fred Drakec9680921999-12-13 16:37:25 +000011490#endif
11491#ifdef _SC_XBS5_ILP32_OFFBIG
Victor Stinner8c62be82010-05-06 00:08:46 +000011492 {"SC_XBS5_ILP32_OFFBIG", _SC_XBS5_ILP32_OFFBIG},
Fred Drakec9680921999-12-13 16:37:25 +000011493#endif
11494#ifdef _SC_XBS5_LP64_OFF64
Victor Stinner8c62be82010-05-06 00:08:46 +000011495 {"SC_XBS5_LP64_OFF64", _SC_XBS5_LP64_OFF64},
Fred Drakec9680921999-12-13 16:37:25 +000011496#endif
11497#ifdef _SC_XBS5_LPBIG_OFFBIG
Victor Stinner8c62be82010-05-06 00:08:46 +000011498 {"SC_XBS5_LPBIG_OFFBIG", _SC_XBS5_LPBIG_OFFBIG},
Fred Drakec9680921999-12-13 16:37:25 +000011499#endif
11500#ifdef _SC_XOPEN_CRYPT
Victor Stinner8c62be82010-05-06 00:08:46 +000011501 {"SC_XOPEN_CRYPT", _SC_XOPEN_CRYPT},
Fred Drakec9680921999-12-13 16:37:25 +000011502#endif
11503#ifdef _SC_XOPEN_ENH_I18N
Victor Stinner8c62be82010-05-06 00:08:46 +000011504 {"SC_XOPEN_ENH_I18N", _SC_XOPEN_ENH_I18N},
Fred Drakec9680921999-12-13 16:37:25 +000011505#endif
11506#ifdef _SC_XOPEN_LEGACY
Victor Stinner8c62be82010-05-06 00:08:46 +000011507 {"SC_XOPEN_LEGACY", _SC_XOPEN_LEGACY},
Fred Drakec9680921999-12-13 16:37:25 +000011508#endif
11509#ifdef _SC_XOPEN_REALTIME
Victor Stinner8c62be82010-05-06 00:08:46 +000011510 {"SC_XOPEN_REALTIME", _SC_XOPEN_REALTIME},
Fred Drakec9680921999-12-13 16:37:25 +000011511#endif
11512#ifdef _SC_XOPEN_REALTIME_THREADS
Victor Stinner8c62be82010-05-06 00:08:46 +000011513 {"SC_XOPEN_REALTIME_THREADS", _SC_XOPEN_REALTIME_THREADS},
Fred Drakec9680921999-12-13 16:37:25 +000011514#endif
11515#ifdef _SC_XOPEN_SHM
Victor Stinner8c62be82010-05-06 00:08:46 +000011516 {"SC_XOPEN_SHM", _SC_XOPEN_SHM},
Fred Drakec9680921999-12-13 16:37:25 +000011517#endif
11518#ifdef _SC_XOPEN_UNIX
Victor Stinner8c62be82010-05-06 00:08:46 +000011519 {"SC_XOPEN_UNIX", _SC_XOPEN_UNIX},
Fred Drakec9680921999-12-13 16:37:25 +000011520#endif
11521#ifdef _SC_XOPEN_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000011522 {"SC_XOPEN_VERSION", _SC_XOPEN_VERSION},
Fred Drakec9680921999-12-13 16:37:25 +000011523#endif
11524#ifdef _SC_XOPEN_XCU_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000011525 {"SC_XOPEN_XCU_VERSION", _SC_XOPEN_XCU_VERSION},
Fred Drakec9680921999-12-13 16:37:25 +000011526#endif
11527#ifdef _SC_XOPEN_XPG2
Victor Stinner8c62be82010-05-06 00:08:46 +000011528 {"SC_XOPEN_XPG2", _SC_XOPEN_XPG2},
Fred Drakec9680921999-12-13 16:37:25 +000011529#endif
11530#ifdef _SC_XOPEN_XPG3
Victor Stinner8c62be82010-05-06 00:08:46 +000011531 {"SC_XOPEN_XPG3", _SC_XOPEN_XPG3},
Fred Drakec9680921999-12-13 16:37:25 +000011532#endif
11533#ifdef _SC_XOPEN_XPG4
Victor Stinner8c62be82010-05-06 00:08:46 +000011534 {"SC_XOPEN_XPG4", _SC_XOPEN_XPG4},
Fred Drakec9680921999-12-13 16:37:25 +000011535#endif
11536};
11537
11538static int
Fredrik Lundhff7df9d2000-07-08 22:48:53 +000011539conv_sysconf_confname(PyObject *arg, int *valuep)
Fred Drakec9680921999-12-13 16:37:25 +000011540{
11541 return conv_confname(arg, valuep, posix_constants_sysconf,
11542 sizeof(posix_constants_sysconf)
11543 / sizeof(struct constdef));
11544}
11545
Larry Hastings2f936352014-08-05 14:04:04 +100011546
11547/*[clinic input]
11548os.sysconf -> long
11549 name: sysconf_confname
11550 /
11551
11552Return an integer-valued system configuration variable.
11553[clinic start generated code]*/
11554
Larry Hastings2f936352014-08-05 14:04:04 +100011555static long
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011556os_sysconf_impl(PyObject *module, int name)
11557/*[clinic end generated code: output=3662f945fc0cc756 input=279e3430a33f29e4]*/
Larry Hastings2f936352014-08-05 14:04:04 +100011558{
11559 long value;
11560
11561 errno = 0;
11562 value = sysconf(name);
11563 if (value == -1 && errno != 0)
11564 posix_error();
11565 return value;
11566}
11567#endif /* HAVE_SYSCONF */
Fred Drakec9680921999-12-13 16:37:25 +000011568
11569
Fred Drakebec628d1999-12-15 18:31:10 +000011570/* This code is used to ensure that the tables of configuration value names
Serhiy Storchaka56a6d852014-12-01 18:28:43 +020011571 * are in sorted order as required by conv_confname(), and also to build
Fred Drakebec628d1999-12-15 18:31:10 +000011572 * the exported dictionaries that are used to publish information about the
11573 * names available on the host platform.
11574 *
11575 * Sorting the table at runtime ensures that the table is properly ordered
11576 * when used, even for platforms we're not able to test on. It also makes
11577 * it easier to add additional entries to the tables.
Fred Draked86ed291999-12-15 15:34:33 +000011578 */
Fred Drakebec628d1999-12-15 18:31:10 +000011579
11580static int
Fredrik Lundhff7df9d2000-07-08 22:48:53 +000011581cmp_constdefs(const void *v1, const void *v2)
Fred Drakebec628d1999-12-15 18:31:10 +000011582{
11583 const struct constdef *c1 =
Victor Stinner8c62be82010-05-06 00:08:46 +000011584 (const struct constdef *) v1;
Fred Drakebec628d1999-12-15 18:31:10 +000011585 const struct constdef *c2 =
Victor Stinner8c62be82010-05-06 00:08:46 +000011586 (const struct constdef *) v2;
Fred Drakebec628d1999-12-15 18:31:10 +000011587
11588 return strcmp(c1->name, c2->name);
11589}
11590
11591static int
Fredrik Lundhff7df9d2000-07-08 22:48:53 +000011592setup_confname_table(struct constdef *table, size_t tablesize,
Serhiy Storchakadeab18d2016-05-07 16:45:18 +030011593 const char *tablename, PyObject *module)
Fred Draked86ed291999-12-15 15:34:33 +000011594{
Fred Drakebec628d1999-12-15 18:31:10 +000011595 PyObject *d = NULL;
Barry Warsaw3155db32000-04-13 15:20:40 +000011596 size_t i;
Fred Drakebec628d1999-12-15 18:31:10 +000011597
11598 qsort(table, tablesize, sizeof(struct constdef), cmp_constdefs);
11599 d = PyDict_New();
Barry Warsaw3155db32000-04-13 15:20:40 +000011600 if (d == NULL)
Victor Stinner8c62be82010-05-06 00:08:46 +000011601 return -1;
Fred Draked86ed291999-12-15 15:34:33 +000011602
Barry Warsaw3155db32000-04-13 15:20:40 +000011603 for (i=0; i < tablesize; ++i) {
Victor Stinner8c62be82010-05-06 00:08:46 +000011604 PyObject *o = PyLong_FromLong(table[i].value);
11605 if (o == NULL || PyDict_SetItemString(d, table[i].name, o) == -1) {
11606 Py_XDECREF(o);
11607 Py_DECREF(d);
11608 return -1;
11609 }
11610 Py_DECREF(o);
Fred Draked86ed291999-12-15 15:34:33 +000011611 }
Fred Drake4d1e64b2002-04-15 19:40:07 +000011612 return PyModule_AddObject(module, tablename, d);
Fred Draked86ed291999-12-15 15:34:33 +000011613}
11614
Fred Drakebec628d1999-12-15 18:31:10 +000011615/* Return -1 on failure, 0 on success. */
11616static int
Fred Drake4d1e64b2002-04-15 19:40:07 +000011617setup_confname_tables(PyObject *module)
Fred Draked86ed291999-12-15 15:34:33 +000011618{
11619#if defined(HAVE_FPATHCONF) || defined(HAVE_PATHCONF)
Fred Drakebec628d1999-12-15 18:31:10 +000011620 if (setup_confname_table(posix_constants_pathconf,
Fred Draked86ed291999-12-15 15:34:33 +000011621 sizeof(posix_constants_pathconf)
11622 / sizeof(struct constdef),
Fred Drake4d1e64b2002-04-15 19:40:07 +000011623 "pathconf_names", module))
Stefan Krah0e803b32010-11-26 16:16:47 +000011624 return -1;
Fred Draked86ed291999-12-15 15:34:33 +000011625#endif
11626#ifdef HAVE_CONFSTR
Fred Drakebec628d1999-12-15 18:31:10 +000011627 if (setup_confname_table(posix_constants_confstr,
Fred Draked86ed291999-12-15 15:34:33 +000011628 sizeof(posix_constants_confstr)
11629 / sizeof(struct constdef),
Fred Drake4d1e64b2002-04-15 19:40:07 +000011630 "confstr_names", module))
Stefan Krah0e803b32010-11-26 16:16:47 +000011631 return -1;
Fred Draked86ed291999-12-15 15:34:33 +000011632#endif
11633#ifdef HAVE_SYSCONF
Fred Drakebec628d1999-12-15 18:31:10 +000011634 if (setup_confname_table(posix_constants_sysconf,
Fred Draked86ed291999-12-15 15:34:33 +000011635 sizeof(posix_constants_sysconf)
11636 / sizeof(struct constdef),
Fred Drake4d1e64b2002-04-15 19:40:07 +000011637 "sysconf_names", module))
Stefan Krah0e803b32010-11-26 16:16:47 +000011638 return -1;
Fred Draked86ed291999-12-15 15:34:33 +000011639#endif
Fred Drakebec628d1999-12-15 18:31:10 +000011640 return 0;
Fred Draked86ed291999-12-15 15:34:33 +000011641}
Fred Draked86ed291999-12-15 15:34:33 +000011642
11643
Larry Hastings2f936352014-08-05 14:04:04 +100011644/*[clinic input]
11645os.abort
11646
11647Abort the interpreter immediately.
11648
11649This function 'dumps core' or otherwise fails in the hardest way possible
11650on the hosting operating system. This function never returns.
11651[clinic start generated code]*/
11652
Larry Hastings2f936352014-08-05 14:04:04 +100011653static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011654os_abort_impl(PyObject *module)
11655/*[clinic end generated code: output=dcf52586dad2467c input=cf2c7d98bc504047]*/
Fred Drake5ab8eaf1999-12-09 21:13:07 +000011656{
Fred Drake5ab8eaf1999-12-09 21:13:07 +000011657 abort();
11658 /*NOTREACHED*/
Victor Stinner9a2329f2016-12-05 17:56:36 +010011659#ifndef __clang__
11660 /* Issue #28152: abort() is declared with __attribute__((__noreturn__)).
11661 GCC emits a warning without "return NULL;" (compiler bug?), but Clang
11662 is smarter and emits a warning on the return. */
Fred Drake5ab8eaf1999-12-09 21:13:07 +000011663 Py_FatalError("abort() called from Python code didn't abort!");
11664 return NULL;
Victor Stinner9a2329f2016-12-05 17:56:36 +010011665#endif
Fred Drake5ab8eaf1999-12-09 21:13:07 +000011666}
Fred Drakebec628d1999-12-15 18:31:10 +000011667
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000011668#ifdef MS_WINDOWS
Steve Dower7d0e0c92015-01-24 08:18:24 -080011669/* Grab ShellExecute dynamically from shell32 */
11670static int has_ShellExecute = -1;
Steve Dower7d0e0c92015-01-24 08:18:24 -080011671static HINSTANCE (CALLBACK *Py_ShellExecuteW)(HWND, LPCWSTR, LPCWSTR, LPCWSTR,
11672 LPCWSTR, INT);
11673static int
11674check_ShellExecute()
11675{
11676 HINSTANCE hShell32;
11677
11678 /* only recheck */
11679 if (-1 == has_ShellExecute) {
11680 Py_BEGIN_ALLOW_THREADS
Victor Stinnera9912152017-10-13 13:46:57 -070011681 /* Security note: this call is not vulnerable to "DLL hijacking".
11682 SHELL32 is part of "KnownDLLs" and so Windows always load
11683 the system SHELL32.DLL, even if there is another SHELL32.DLL
11684 in the DLL search path. */
Steve Dower7d0e0c92015-01-24 08:18:24 -080011685 hShell32 = LoadLibraryW(L"SHELL32");
Steve Dower7d0e0c92015-01-24 08:18:24 -080011686 if (hShell32) {
Steve Dower7d0e0c92015-01-24 08:18:24 -080011687 *(FARPROC*)&Py_ShellExecuteW = GetProcAddress(hShell32,
11688 "ShellExecuteW");
Steve Dowercc16be82016-09-08 10:35:16 -070011689 has_ShellExecute = Py_ShellExecuteW != NULL;
Steve Dower7d0e0c92015-01-24 08:18:24 -080011690 } else {
11691 has_ShellExecute = 0;
11692 }
Tony Roberts4860f012019-02-02 18:16:42 +010011693 Py_END_ALLOW_THREADS
Steve Dower7d0e0c92015-01-24 08:18:24 -080011694 }
11695 return has_ShellExecute;
11696}
11697
11698
Steve Dowercc16be82016-09-08 10:35:16 -070011699/*[clinic input]
11700os.startfile
11701 filepath: path_t
11702 operation: Py_UNICODE = NULL
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +000011703
Steve Dowercc16be82016-09-08 10:35:16 -070011704Start a file with its associated application.
11705
11706When "operation" is not specified or "open", this acts like
11707double-clicking the file in Explorer, or giving the file name as an
11708argument to the DOS "start" command: the file is opened with whatever
11709application (if any) its extension is associated.
11710When another "operation" is given, it specifies what should be done with
11711the file. A typical operation is "print".
11712
11713startfile returns as soon as the associated application is launched.
11714There is no option to wait for the application to close, and no way
11715to retrieve the application's exit status.
11716
11717The filepath is relative to the current directory. If you want to use
11718an absolute path, make sure the first character is not a slash ("/");
11719the underlying Win32 ShellExecute function doesn't work if it is.
11720[clinic start generated code]*/
11721
11722static PyObject *
Serhiy Storchakaafb3e712018-12-14 11:19:51 +020011723os_startfile_impl(PyObject *module, path_t *filepath,
11724 const Py_UNICODE *operation)
Serhiy Storchaka279f4462019-09-14 12:24:05 +030011725/*[clinic end generated code: output=66dc311c94d50797 input=c940888a5390f039]*/
Steve Dowercc16be82016-09-08 10:35:16 -070011726{
11727 HINSTANCE rc;
Steve Dower7d0e0c92015-01-24 08:18:24 -080011728
11729 if(!check_ShellExecute()) {
11730 /* If the OS doesn't have ShellExecute, return a
11731 NotImplementedError. */
11732 return PyErr_Format(PyExc_NotImplementedError,
11733 "startfile not available on this platform");
11734 }
11735
Victor Stinner8c62be82010-05-06 00:08:46 +000011736 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -070011737 rc = Py_ShellExecuteW((HWND)0, operation, filepath->wide,
Steve Dower7d0e0c92015-01-24 08:18:24 -080011738 NULL, NULL, SW_SHOWNORMAL);
Victor Stinner8c62be82010-05-06 00:08:46 +000011739 Py_END_ALLOW_THREADS
11740
Victor Stinner8c62be82010-05-06 00:08:46 +000011741 if (rc <= (HINSTANCE)32) {
Steve Dowercc16be82016-09-08 10:35:16 -070011742 win32_error_object("startfile", filepath->object);
Victor Stinnereb5657a2011-09-30 01:44:27 +020011743 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +000011744 }
Steve Dowercc16be82016-09-08 10:35:16 -070011745 Py_RETURN_NONE;
Tim Petersf58a7aa2000-09-22 10:05:54 +000011746}
Larry Hastings2f936352014-08-05 14:04:04 +100011747#endif /* MS_WINDOWS */
11748
Fred Drake5ab8eaf1999-12-09 21:13:07 +000011749
Martin v. Löwis438b5342002-12-27 10:16:42 +000011750#ifdef HAVE_GETLOADAVG
Larry Hastings2f936352014-08-05 14:04:04 +100011751/*[clinic input]
11752os.getloadavg
11753
11754Return average recent system load information.
11755
11756Return the number of processes in the system run queue averaged over
11757the last 1, 5, and 15 minutes as a tuple of three floats.
11758Raises OSError if the load average was unobtainable.
11759[clinic start generated code]*/
11760
Larry Hastings2f936352014-08-05 14:04:04 +100011761static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011762os_getloadavg_impl(PyObject *module)
11763/*[clinic end generated code: output=9ad3a11bfb4f4bd2 input=3d6d826b76d8a34e]*/
Martin v. Löwis438b5342002-12-27 10:16:42 +000011764{
11765 double loadavg[3];
Martin v. Löwis438b5342002-12-27 10:16:42 +000011766 if (getloadavg(loadavg, 3)!=3) {
Stefan Krah0e803b32010-11-26 16:16:47 +000011767 PyErr_SetString(PyExc_OSError, "Load averages are unobtainable");
11768 return NULL;
Martin v. Löwis438b5342002-12-27 10:16:42 +000011769 } else
Stefan Krah0e803b32010-11-26 16:16:47 +000011770 return Py_BuildValue("ddd", loadavg[0], loadavg[1], loadavg[2]);
Martin v. Löwis438b5342002-12-27 10:16:42 +000011771}
Larry Hastings2f936352014-08-05 14:04:04 +100011772#endif /* HAVE_GETLOADAVG */
Martin v. Löwis438b5342002-12-27 10:16:42 +000011773
Larry Hastings2f936352014-08-05 14:04:04 +100011774
11775/*[clinic input]
11776os.device_encoding
11777 fd: int
11778
11779Return a string describing the encoding of a terminal's file descriptor.
11780
11781The file descriptor must be attached to a terminal.
11782If the device is not a terminal, return None.
11783[clinic start generated code]*/
11784
Larry Hastings2f936352014-08-05 14:04:04 +100011785static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011786os_device_encoding_impl(PyObject *module, int fd)
11787/*[clinic end generated code: output=e0d294bbab7e8c2b input=9e1d4a42b66df312]*/
Larry Hastings2f936352014-08-05 14:04:04 +100011788{
Brett Cannonefb00c02012-02-29 18:31:31 -050011789 return _Py_device_encoding(fd);
Martin v. Löwisd1cd4d42007-08-11 14:02:14 +000011790}
11791
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011792
Larry Hastings2f936352014-08-05 14:04:04 +100011793#ifdef HAVE_SETRESUID
11794/*[clinic input]
11795os.setresuid
11796
11797 ruid: uid_t
11798 euid: uid_t
11799 suid: uid_t
11800 /
11801
11802Set the current process's real, effective, and saved user ids.
11803[clinic start generated code]*/
11804
Larry Hastings2f936352014-08-05 14:04:04 +100011805static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011806os_setresuid_impl(PyObject *module, uid_t ruid, uid_t euid, uid_t suid)
11807/*[clinic end generated code: output=834a641e15373e97 input=9e33cb79a82792f3]*/
Larry Hastings2f936352014-08-05 14:04:04 +100011808{
Victor Stinner8c62be82010-05-06 00:08:46 +000011809 if (setresuid(ruid, euid, suid) < 0)
11810 return posix_error();
11811 Py_RETURN_NONE;
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011812}
Larry Hastings2f936352014-08-05 14:04:04 +100011813#endif /* HAVE_SETRESUID */
11814
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011815
11816#ifdef HAVE_SETRESGID
Larry Hastings2f936352014-08-05 14:04:04 +100011817/*[clinic input]
11818os.setresgid
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011819
Larry Hastings2f936352014-08-05 14:04:04 +100011820 rgid: gid_t
11821 egid: gid_t
11822 sgid: gid_t
11823 /
11824
11825Set the current process's real, effective, and saved group ids.
11826[clinic start generated code]*/
11827
Larry Hastings2f936352014-08-05 14:04:04 +100011828static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011829os_setresgid_impl(PyObject *module, gid_t rgid, gid_t egid, gid_t sgid)
11830/*[clinic end generated code: output=6aa402f3d2e514a9 input=33e9e0785ef426b1]*/
Larry Hastings2f936352014-08-05 14:04:04 +100011831{
Victor Stinner8c62be82010-05-06 00:08:46 +000011832 if (setresgid(rgid, egid, sgid) < 0)
11833 return posix_error();
11834 Py_RETURN_NONE;
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011835}
Larry Hastings2f936352014-08-05 14:04:04 +100011836#endif /* HAVE_SETRESGID */
11837
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011838
11839#ifdef HAVE_GETRESUID
Larry Hastings2f936352014-08-05 14:04:04 +100011840/*[clinic input]
11841os.getresuid
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 user ids.
11844[clinic start generated code]*/
11845
Larry Hastings2f936352014-08-05 14:04:04 +100011846static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011847os_getresuid_impl(PyObject *module)
11848/*[clinic end generated code: output=8e0becff5dece5bf input=41ccfa8e1f6517ad]*/
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011849{
Victor Stinner8c62be82010-05-06 00:08:46 +000011850 uid_t ruid, euid, suid;
Victor Stinner8c62be82010-05-06 00:08:46 +000011851 if (getresuid(&ruid, &euid, &suid) < 0)
11852 return posix_error();
Serhiy Storchaka7cf55992013-02-10 21:56:49 +020011853 return Py_BuildValue("(NNN)", _PyLong_FromUid(ruid),
11854 _PyLong_FromUid(euid),
11855 _PyLong_FromUid(suid));
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011856}
Larry Hastings2f936352014-08-05 14:04:04 +100011857#endif /* HAVE_GETRESUID */
11858
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011859
11860#ifdef HAVE_GETRESGID
Larry Hastings2f936352014-08-05 14:04:04 +100011861/*[clinic input]
11862os.getresgid
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011863
Larry Hastings2f936352014-08-05 14:04:04 +100011864Return a tuple of the current process's real, effective, and saved group ids.
11865[clinic start generated code]*/
11866
Larry Hastings2f936352014-08-05 14:04:04 +100011867static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011868os_getresgid_impl(PyObject *module)
11869/*[clinic end generated code: output=2719c4bfcf27fb9f input=517e68db9ca32df6]*/
Larry Hastings2f936352014-08-05 14:04:04 +100011870{
11871 gid_t rgid, egid, sgid;
Victor Stinner8c62be82010-05-06 00:08:46 +000011872 if (getresgid(&rgid, &egid, &sgid) < 0)
11873 return posix_error();
Serhiy Storchaka7cf55992013-02-10 21:56:49 +020011874 return Py_BuildValue("(NNN)", _PyLong_FromGid(rgid),
11875 _PyLong_FromGid(egid),
11876 _PyLong_FromGid(sgid));
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011877}
Larry Hastings2f936352014-08-05 14:04:04 +100011878#endif /* HAVE_GETRESGID */
11879
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011880
Benjamin Peterson9428d532011-09-14 11:45:52 -040011881#ifdef USE_XATTRS
Larry Hastings2f936352014-08-05 14:04:04 +100011882/*[clinic input]
11883os.getxattr
Benjamin Peterson799bd802011-08-31 22:15:17 -040011884
Larry Hastings2f936352014-08-05 14:04:04 +100011885 path: path_t(allow_fd=True)
11886 attribute: path_t
11887 *
11888 follow_symlinks: bool = True
11889
11890Return the value of extended attribute attribute on path.
11891
BNMetricsb9427072018-11-02 15:20:19 +000011892path may be either a string, a path-like object, or an open file descriptor.
Larry Hastings2f936352014-08-05 14:04:04 +100011893If follow_symlinks is False, and the last element of the path is a symbolic
11894 link, getxattr will examine the symbolic link itself instead of the file
11895 the link points to.
11896
11897[clinic start generated code]*/
11898
Larry Hastings2f936352014-08-05 14:04:04 +100011899static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011900os_getxattr_impl(PyObject *module, path_t *path, path_t *attribute,
Larry Hastings89964c42015-04-14 18:07:59 -040011901 int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +000011902/*[clinic end generated code: output=5f2f44200a43cff2 input=025789491708f7eb]*/
Larry Hastings2f936352014-08-05 14:04:04 +100011903{
11904 Py_ssize_t i;
11905 PyObject *buffer = NULL;
11906
11907 if (fd_and_follow_symlinks_invalid("getxattr", path->fd, follow_symlinks))
11908 return NULL;
Benjamin Peterson799bd802011-08-31 22:15:17 -040011909
Larry Hastings9cf065c2012-06-22 16:30:09 -070011910 for (i = 0; ; i++) {
11911 void *ptr;
11912 ssize_t result;
Serhiy Storchaka2d06e842015-12-25 19:53:18 +020011913 static const Py_ssize_t buffer_sizes[] = {128, XATTR_SIZE_MAX, 0};
Larry Hastings9cf065c2012-06-22 16:30:09 -070011914 Py_ssize_t buffer_size = buffer_sizes[i];
11915 if (!buffer_size) {
Larry Hastings2f936352014-08-05 14:04:04 +100011916 path_error(path);
11917 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -070011918 }
11919 buffer = PyBytes_FromStringAndSize(NULL, buffer_size);
11920 if (!buffer)
Larry Hastings2f936352014-08-05 14:04:04 +100011921 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -070011922 ptr = PyBytes_AS_STRING(buffer);
Benjamin Peterson799bd802011-08-31 22:15:17 -040011923
Larry Hastings9cf065c2012-06-22 16:30:09 -070011924 Py_BEGIN_ALLOW_THREADS;
Larry Hastings2f936352014-08-05 14:04:04 +100011925 if (path->fd >= 0)
11926 result = fgetxattr(path->fd, attribute->narrow, ptr, buffer_size);
Larry Hastings9cf065c2012-06-22 16:30:09 -070011927 else if (follow_symlinks)
Larry Hastings2f936352014-08-05 14:04:04 +100011928 result = getxattr(path->narrow, attribute->narrow, ptr, buffer_size);
Larry Hastings9cf065c2012-06-22 16:30:09 -070011929 else
Larry Hastings2f936352014-08-05 14:04:04 +100011930 result = lgetxattr(path->narrow, attribute->narrow, ptr, buffer_size);
Larry Hastings9cf065c2012-06-22 16:30:09 -070011931 Py_END_ALLOW_THREADS;
Benjamin Peterson799bd802011-08-31 22:15:17 -040011932
Larry Hastings9cf065c2012-06-22 16:30:09 -070011933 if (result < 0) {
11934 Py_DECREF(buffer);
Larry Hastings9cf065c2012-06-22 16:30:09 -070011935 if (errno == ERANGE)
11936 continue;
Larry Hastings2f936352014-08-05 14:04:04 +100011937 path_error(path);
11938 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -070011939 }
Benjamin Peterson799bd802011-08-31 22:15:17 -040011940
Larry Hastings9cf065c2012-06-22 16:30:09 -070011941 if (result != buffer_size) {
11942 /* Can only shrink. */
11943 _PyBytes_Resize(&buffer, result);
11944 }
11945 break;
11946 }
Benjamin Peterson799bd802011-08-31 22:15:17 -040011947
Larry Hastings9cf065c2012-06-22 16:30:09 -070011948 return buffer;
Benjamin Peterson799bd802011-08-31 22:15:17 -040011949}
11950
Larry Hastings2f936352014-08-05 14:04:04 +100011951
11952/*[clinic input]
11953os.setxattr
11954
11955 path: path_t(allow_fd=True)
11956 attribute: path_t
11957 value: Py_buffer
11958 flags: int = 0
11959 *
11960 follow_symlinks: bool = True
11961
11962Set extended attribute attribute on path to value.
11963
BNMetricsb9427072018-11-02 15:20:19 +000011964path may be either a string, a path-like object, or an open file descriptor.
Larry Hastings2f936352014-08-05 14:04:04 +100011965If follow_symlinks is False, and the last element of the path is a symbolic
11966 link, setxattr will modify the symbolic link itself instead of the file
11967 the link points to.
11968
11969[clinic start generated code]*/
11970
Benjamin Peterson799bd802011-08-31 22:15:17 -040011971static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011972os_setxattr_impl(PyObject *module, path_t *path, path_t *attribute,
Larry Hastings89964c42015-04-14 18:07:59 -040011973 Py_buffer *value, int flags, int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +000011974/*[clinic end generated code: output=98b83f63fdde26bb input=c17c0103009042f0]*/
Benjamin Peterson799bd802011-08-31 22:15:17 -040011975{
Larry Hastings2f936352014-08-05 14:04:04 +100011976 ssize_t result;
Benjamin Peterson799bd802011-08-31 22:15:17 -040011977
Larry Hastings2f936352014-08-05 14:04:04 +100011978 if (fd_and_follow_symlinks_invalid("setxattr", path->fd, follow_symlinks))
Benjamin Peterson799bd802011-08-31 22:15:17 -040011979 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -070011980
Benjamin Peterson799bd802011-08-31 22:15:17 -040011981 Py_BEGIN_ALLOW_THREADS;
Larry Hastings2f936352014-08-05 14:04:04 +100011982 if (path->fd > -1)
11983 result = fsetxattr(path->fd, attribute->narrow,
11984 value->buf, value->len, flags);
Larry Hastings9cf065c2012-06-22 16:30:09 -070011985 else if (follow_symlinks)
Larry Hastings2f936352014-08-05 14:04:04 +100011986 result = setxattr(path->narrow, attribute->narrow,
11987 value->buf, value->len, flags);
Larry Hastings9cf065c2012-06-22 16:30:09 -070011988 else
Larry Hastings2f936352014-08-05 14:04:04 +100011989 result = lsetxattr(path->narrow, attribute->narrow,
11990 value->buf, value->len, flags);
Benjamin Peterson799bd802011-08-31 22:15:17 -040011991 Py_END_ALLOW_THREADS;
Benjamin Peterson799bd802011-08-31 22:15:17 -040011992
Larry Hastings9cf065c2012-06-22 16:30:09 -070011993 if (result) {
Larry Hastings2f936352014-08-05 14:04:04 +100011994 path_error(path);
11995 return NULL;
Benjamin Peterson799bd802011-08-31 22:15:17 -040011996 }
Benjamin Peterson799bd802011-08-31 22:15:17 -040011997
Larry Hastings2f936352014-08-05 14:04:04 +100011998 Py_RETURN_NONE;
11999}
12000
12001
12002/*[clinic input]
12003os.removexattr
12004
12005 path: path_t(allow_fd=True)
12006 attribute: path_t
12007 *
12008 follow_symlinks: bool = True
12009
12010Remove extended attribute attribute on path.
12011
BNMetricsb9427072018-11-02 15:20:19 +000012012path may be either a string, a path-like object, or an open file descriptor.
Larry Hastings2f936352014-08-05 14:04:04 +100012013If follow_symlinks is False, and the last element of the path is a symbolic
12014 link, removexattr will modify the symbolic link itself instead of the file
12015 the link points to.
12016
12017[clinic start generated code]*/
12018
Larry Hastings2f936352014-08-05 14:04:04 +100012019static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030012020os_removexattr_impl(PyObject *module, path_t *path, path_t *attribute,
Larry Hastings89964c42015-04-14 18:07:59 -040012021 int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +000012022/*[clinic end generated code: output=521a51817980cda6 input=3d9a7d36fe2f7c4e]*/
Larry Hastings2f936352014-08-05 14:04:04 +100012023{
12024 ssize_t result;
12025
12026 if (fd_and_follow_symlinks_invalid("removexattr", path->fd, follow_symlinks))
12027 return NULL;
12028
12029 Py_BEGIN_ALLOW_THREADS;
12030 if (path->fd > -1)
12031 result = fremovexattr(path->fd, attribute->narrow);
12032 else if (follow_symlinks)
12033 result = removexattr(path->narrow, attribute->narrow);
12034 else
12035 result = lremovexattr(path->narrow, attribute->narrow);
12036 Py_END_ALLOW_THREADS;
12037
12038 if (result) {
12039 return path_error(path);
12040 }
12041
12042 Py_RETURN_NONE;
12043}
12044
12045
12046/*[clinic input]
12047os.listxattr
12048
12049 path: path_t(allow_fd=True, nullable=True) = None
12050 *
12051 follow_symlinks: bool = True
12052
12053Return a list of extended attributes on path.
12054
BNMetricsb9427072018-11-02 15:20:19 +000012055path may be either None, a string, a path-like object, or an open file descriptor.
Larry Hastings2f936352014-08-05 14:04:04 +100012056if path is None, listxattr will examine the current directory.
12057If follow_symlinks is False, and the last element of the path is a symbolic
12058 link, listxattr will examine the symbolic link itself instead of the file
12059 the link points to.
12060[clinic start generated code]*/
12061
Larry Hastings2f936352014-08-05 14:04:04 +100012062static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030012063os_listxattr_impl(PyObject *module, path_t *path, int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +000012064/*[clinic end generated code: output=bebdb4e2ad0ce435 input=9826edf9fdb90869]*/
Larry Hastings2f936352014-08-05 14:04:04 +100012065{
Larry Hastings9cf065c2012-06-22 16:30:09 -070012066 Py_ssize_t i;
12067 PyObject *result = NULL;
Larry Hastings2f936352014-08-05 14:04:04 +100012068 const char *name;
Larry Hastings9cf065c2012-06-22 16:30:09 -070012069 char *buffer = NULL;
Benjamin Peterson799bd802011-08-31 22:15:17 -040012070
Larry Hastings2f936352014-08-05 14:04:04 +100012071 if (fd_and_follow_symlinks_invalid("listxattr", path->fd, follow_symlinks))
Larry Hastings9cf065c2012-06-22 16:30:09 -070012072 goto exit;
Benjamin Peterson799bd802011-08-31 22:15:17 -040012073
Larry Hastings2f936352014-08-05 14:04:04 +100012074 name = path->narrow ? path->narrow : ".";
12075
Larry Hastings9cf065c2012-06-22 16:30:09 -070012076 for (i = 0; ; i++) {
Serhiy Storchakadeab18d2016-05-07 16:45:18 +030012077 const char *start, *trace, *end;
Larry Hastings9cf065c2012-06-22 16:30:09 -070012078 ssize_t length;
Serhiy Storchaka2d06e842015-12-25 19:53:18 +020012079 static const Py_ssize_t buffer_sizes[] = { 256, XATTR_LIST_MAX, 0 };
Larry Hastings9cf065c2012-06-22 16:30:09 -070012080 Py_ssize_t buffer_size = buffer_sizes[i];
12081 if (!buffer_size) {
Christian Heimes3b9493b2012-09-23 16:11:15 +020012082 /* ERANGE */
Larry Hastings2f936352014-08-05 14:04:04 +100012083 path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -070012084 break;
12085 }
12086 buffer = PyMem_MALLOC(buffer_size);
12087 if (!buffer) {
12088 PyErr_NoMemory();
12089 break;
12090 }
Benjamin Peterson799bd802011-08-31 22:15:17 -040012091
Larry Hastings9cf065c2012-06-22 16:30:09 -070012092 Py_BEGIN_ALLOW_THREADS;
Larry Hastings2f936352014-08-05 14:04:04 +100012093 if (path->fd > -1)
12094 length = flistxattr(path->fd, buffer, buffer_size);
Larry Hastings9cf065c2012-06-22 16:30:09 -070012095 else if (follow_symlinks)
12096 length = listxattr(name, buffer, buffer_size);
12097 else
12098 length = llistxattr(name, buffer, buffer_size);
12099 Py_END_ALLOW_THREADS;
Benjamin Peterson799bd802011-08-31 22:15:17 -040012100
Larry Hastings9cf065c2012-06-22 16:30:09 -070012101 if (length < 0) {
Antoine Pitrou7f987392013-05-13 19:46:29 +020012102 if (errno == ERANGE) {
12103 PyMem_FREE(buffer);
Benjamin Petersondedac522013-05-13 19:55:40 -050012104 buffer = NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -070012105 continue;
Antoine Pitrou7f987392013-05-13 19:46:29 +020012106 }
Larry Hastings2f936352014-08-05 14:04:04 +100012107 path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -070012108 break;
12109 }
Benjamin Peterson799bd802011-08-31 22:15:17 -040012110
Larry Hastings9cf065c2012-06-22 16:30:09 -070012111 result = PyList_New(0);
12112 if (!result) {
12113 goto exit;
12114 }
Benjamin Peterson799bd802011-08-31 22:15:17 -040012115
Larry Hastings9cf065c2012-06-22 16:30:09 -070012116 end = buffer + length;
12117 for (trace = start = buffer; trace != end; trace++) {
12118 if (!*trace) {
12119 int error;
12120 PyObject *attribute = PyUnicode_DecodeFSDefaultAndSize(start,
12121 trace - start);
12122 if (!attribute) {
12123 Py_DECREF(result);
12124 result = NULL;
12125 goto exit;
12126 }
12127 error = PyList_Append(result, attribute);
12128 Py_DECREF(attribute);
12129 if (error) {
12130 Py_DECREF(result);
12131 result = NULL;
12132 goto exit;
12133 }
12134 start = trace + 1;
12135 }
12136 }
12137 break;
12138 }
12139exit:
Larry Hastings9cf065c2012-06-22 16:30:09 -070012140 if (buffer)
12141 PyMem_FREE(buffer);
12142 return result;
Benjamin Peterson799bd802011-08-31 22:15:17 -040012143}
Benjamin Peterson9428d532011-09-14 11:45:52 -040012144#endif /* USE_XATTRS */
Benjamin Peterson799bd802011-08-31 22:15:17 -040012145
Antoine Pitroubcf2b592012-02-08 23:28:36 +010012146
Larry Hastings2f936352014-08-05 14:04:04 +100012147/*[clinic input]
12148os.urandom
12149
12150 size: Py_ssize_t
12151 /
12152
12153Return a bytes object containing random bytes suitable for cryptographic use.
12154[clinic start generated code]*/
12155
Larry Hastings2f936352014-08-05 14:04:04 +100012156static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030012157os_urandom_impl(PyObject *module, Py_ssize_t size)
12158/*[clinic end generated code: output=42c5cca9d18068e9 input=4067cdb1b6776c29]*/
Larry Hastings2f936352014-08-05 14:04:04 +100012159{
12160 PyObject *bytes;
12161 int result;
12162
Georg Brandl2fb477c2012-02-21 00:33:36 +010012163 if (size < 0)
12164 return PyErr_Format(PyExc_ValueError,
12165 "negative argument not allowed");
Larry Hastings2f936352014-08-05 14:04:04 +100012166 bytes = PyBytes_FromStringAndSize(NULL, size);
12167 if (bytes == NULL)
Georg Brandl2fb477c2012-02-21 00:33:36 +010012168 return NULL;
12169
Victor Stinnere66987e2016-09-06 16:33:52 -070012170 result = _PyOS_URandom(PyBytes_AS_STRING(bytes), PyBytes_GET_SIZE(bytes));
Larry Hastings2f936352014-08-05 14:04:04 +100012171 if (result == -1) {
12172 Py_DECREF(bytes);
Georg Brandl2fb477c2012-02-21 00:33:36 +010012173 return NULL;
12174 }
Larry Hastings2f936352014-08-05 14:04:04 +100012175 return bytes;
Georg Brandl2fb477c2012-02-21 00:33:36 +010012176}
12177
Zackery Spytz43fdbd22019-05-29 13:57:07 -060012178#ifdef HAVE_MEMFD_CREATE
12179/*[clinic input]
12180os.memfd_create
12181
12182 name: FSConverter
12183 flags: unsigned_int(bitwise=True, c_default="MFD_CLOEXEC") = MFD_CLOEXEC
12184
12185[clinic start generated code]*/
12186
12187static PyObject *
12188os_memfd_create_impl(PyObject *module, PyObject *name, unsigned int flags)
12189/*[clinic end generated code: output=6681ede983bdb9a6 input=a42cfc199bcd56e9]*/
12190{
12191 int fd;
12192 const char *bytes = PyBytes_AS_STRING(name);
12193 Py_BEGIN_ALLOW_THREADS
12194 fd = memfd_create(bytes, flags);
12195 Py_END_ALLOW_THREADS
12196 if (fd == -1) {
12197 return PyErr_SetFromErrno(PyExc_OSError);
12198 }
12199 return PyLong_FromLong(fd);
12200}
12201#endif
12202
Antoine Pitroubcf2b592012-02-08 23:28:36 +010012203/* Terminal size querying */
12204
Antoine Pitroubcf2b592012-02-08 23:28:36 +010012205PyDoc_STRVAR(TerminalSize_docstring,
12206 "A tuple of (columns, lines) for holding terminal window size");
12207
12208static PyStructSequence_Field TerminalSize_fields[] = {
12209 {"columns", "width of the terminal window in characters"},
12210 {"lines", "height of the terminal window in characters"},
12211 {NULL, NULL}
12212};
12213
12214static PyStructSequence_Desc TerminalSize_desc = {
12215 "os.terminal_size",
12216 TerminalSize_docstring,
12217 TerminalSize_fields,
12218 2,
12219};
12220
12221#if defined(TERMSIZE_USE_CONIO) || defined(TERMSIZE_USE_IOCTL)
Larry Hastings2f936352014-08-05 14:04:04 +100012222/* AC 3.5: fd should accept None */
Antoine Pitroubcf2b592012-02-08 23:28:36 +010012223PyDoc_STRVAR(termsize__doc__,
12224 "Return the size of the terminal window as (columns, lines).\n" \
12225 "\n" \
12226 "The optional argument fd (default standard output) specifies\n" \
12227 "which file descriptor should be queried.\n" \
12228 "\n" \
12229 "If the file descriptor is not connected to a terminal, an OSError\n" \
12230 "is thrown.\n" \
12231 "\n" \
12232 "This function will only be defined if an implementation is\n" \
12233 "available for this system.\n" \
12234 "\n" \
oldkaa0735f2018-02-02 16:52:55 +080012235 "shutil.get_terminal_size is the high-level function which should\n" \
Antoine Pitroubcf2b592012-02-08 23:28:36 +010012236 "normally be used, os.get_terminal_size is the low-level implementation.");
12237
12238static PyObject*
12239get_terminal_size(PyObject *self, PyObject *args)
12240{
12241 int columns, lines;
12242 PyObject *termsize;
12243
12244 int fd = fileno(stdout);
12245 /* Under some conditions stdout may not be connected and
12246 * fileno(stdout) may point to an invalid file descriptor. For example
12247 * GUI apps don't have valid standard streams by default.
12248 *
12249 * If this happens, and the optional fd argument is not present,
12250 * the ioctl below will fail returning EBADF. This is what we want.
12251 */
12252
12253 if (!PyArg_ParseTuple(args, "|i", &fd))
12254 return NULL;
12255
12256#ifdef TERMSIZE_USE_IOCTL
12257 {
12258 struct winsize w;
12259 if (ioctl(fd, TIOCGWINSZ, &w))
12260 return PyErr_SetFromErrno(PyExc_OSError);
12261 columns = w.ws_col;
12262 lines = w.ws_row;
12263 }
12264#endif /* TERMSIZE_USE_IOCTL */
12265
12266#ifdef TERMSIZE_USE_CONIO
12267 {
12268 DWORD nhandle;
12269 HANDLE handle;
12270 CONSOLE_SCREEN_BUFFER_INFO csbi;
12271 switch (fd) {
12272 case 0: nhandle = STD_INPUT_HANDLE;
12273 break;
12274 case 1: nhandle = STD_OUTPUT_HANDLE;
12275 break;
12276 case 2: nhandle = STD_ERROR_HANDLE;
12277 break;
12278 default:
12279 return PyErr_Format(PyExc_ValueError, "bad file descriptor");
12280 }
12281 handle = GetStdHandle(nhandle);
12282 if (handle == NULL)
12283 return PyErr_Format(PyExc_OSError, "handle cannot be retrieved");
12284 if (handle == INVALID_HANDLE_VALUE)
12285 return PyErr_SetFromWindowsErr(0);
12286
12287 if (!GetConsoleScreenBufferInfo(handle, &csbi))
12288 return PyErr_SetFromWindowsErr(0);
12289
12290 columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
12291 lines = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
12292 }
12293#endif /* TERMSIZE_USE_CONIO */
12294
Eddie Elizondob3966632019-11-05 07:16:14 -080012295 PyObject *TerminalSizeType = _posixstate(self)->TerminalSizeType;
12296 termsize = PyStructSequence_New((PyTypeObject *)TerminalSizeType);
Antoine Pitroubcf2b592012-02-08 23:28:36 +010012297 if (termsize == NULL)
12298 return NULL;
12299 PyStructSequence_SET_ITEM(termsize, 0, PyLong_FromLong(columns));
12300 PyStructSequence_SET_ITEM(termsize, 1, PyLong_FromLong(lines));
12301 if (PyErr_Occurred()) {
12302 Py_DECREF(termsize);
12303 return NULL;
12304 }
12305 return termsize;
12306}
12307#endif /* defined(TERMSIZE_USE_CONIO) || defined(TERMSIZE_USE_IOCTL) */
12308
Larry Hastings2f936352014-08-05 14:04:04 +100012309
12310/*[clinic input]
12311os.cpu_count
12312
Charles-François Natali80d62e62015-08-13 20:37:08 +010012313Return the number of CPUs in the system; return None if indeterminable.
12314
12315This number is not equivalent to the number of CPUs the current process can
12316use. The number of usable CPUs can be obtained with
12317``len(os.sched_getaffinity(0))``
Larry Hastings2f936352014-08-05 14:04:04 +100012318[clinic start generated code]*/
12319
Larry Hastings2f936352014-08-05 14:04:04 +100012320static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030012321os_cpu_count_impl(PyObject *module)
Serhiy Storchaka2954f832016-07-07 18:20:03 +030012322/*[clinic end generated code: output=5fc29463c3936a9c input=e7c8f4ba6dbbadd3]*/
Charles-Francois Natali44feda32013-05-20 14:40:46 +020012323{
Charles-Francois Natalid59087d2013-05-20 17:31:06 +020012324 int ncpu = 0;
Charles-Francois Natali44feda32013-05-20 14:40:46 +020012325#ifdef MS_WINDOWS
Steve Doweraa929272019-09-11 16:15:39 +010012326 ncpu = GetActiveProcessorCount(ALL_PROCESSOR_GROUPS);
Charles-Francois Natali44feda32013-05-20 14:40:46 +020012327#elif defined(__hpux)
12328 ncpu = mpctl(MPC_GETNUMSPUS, NULL, NULL);
12329#elif defined(HAVE_SYSCONF) && defined(_SC_NPROCESSORS_ONLN)
12330 ncpu = sysconf(_SC_NPROCESSORS_ONLN);
Charles-Francois Natali44feda32013-05-20 14:40:46 +020012331#elif defined(__DragonFly__) || \
12332 defined(__OpenBSD__) || \
12333 defined(__FreeBSD__) || \
Charles-Francois Natalid59087d2013-05-20 17:31:06 +020012334 defined(__NetBSD__) || \
12335 defined(__APPLE__)
Charles-Francois Natali7c4f8da2013-05-20 17:40:32 +020012336 int mib[2];
12337 size_t len = sizeof(ncpu);
12338 mib[0] = CTL_HW;
12339 mib[1] = HW_NCPU;
12340 if (sysctl(mib, 2, &ncpu, &len, NULL, 0) != 0)
12341 ncpu = 0;
Charles-Francois Natali44feda32013-05-20 14:40:46 +020012342#endif
12343 if (ncpu >= 1)
12344 return PyLong_FromLong(ncpu);
12345 else
12346 Py_RETURN_NONE;
12347}
12348
Victor Stinnerdaf45552013-08-28 00:53:59 +020012349
Larry Hastings2f936352014-08-05 14:04:04 +100012350/*[clinic input]
12351os.get_inheritable -> bool
12352
12353 fd: int
12354 /
12355
12356Get the close-on-exe flag of the specified file descriptor.
12357[clinic start generated code]*/
12358
Larry Hastings2f936352014-08-05 14:04:04 +100012359static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030012360os_get_inheritable_impl(PyObject *module, int fd)
12361/*[clinic end generated code: output=0445e20e149aa5b8 input=89ac008dc9ab6b95]*/
Larry Hastings2f936352014-08-05 14:04:04 +100012362{
Steve Dower8fc89802015-04-12 00:26:27 -040012363 int return_value;
Steve Dower8fc89802015-04-12 00:26:27 -040012364 _Py_BEGIN_SUPPRESS_IPH
12365 return_value = _Py_get_inheritable(fd);
12366 _Py_END_SUPPRESS_IPH
12367 return return_value;
Larry Hastings2f936352014-08-05 14:04:04 +100012368}
12369
12370
12371/*[clinic input]
12372os.set_inheritable
12373 fd: int
12374 inheritable: int
12375 /
12376
12377Set the inheritable flag of the specified file descriptor.
12378[clinic start generated code]*/
12379
Larry Hastings2f936352014-08-05 14:04:04 +100012380static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030012381os_set_inheritable_impl(PyObject *module, int fd, int inheritable)
12382/*[clinic end generated code: output=f1b1918a2f3c38c2 input=9ceaead87a1e2402]*/
Victor Stinnerdaf45552013-08-28 00:53:59 +020012383{
Steve Dower8fc89802015-04-12 00:26:27 -040012384 int result;
Victor Stinnerdaf45552013-08-28 00:53:59 +020012385
Steve Dower8fc89802015-04-12 00:26:27 -040012386 _Py_BEGIN_SUPPRESS_IPH
12387 result = _Py_set_inheritable(fd, inheritable, NULL);
12388 _Py_END_SUPPRESS_IPH
12389 if (result < 0)
Victor Stinnerdaf45552013-08-28 00:53:59 +020012390 return NULL;
12391 Py_RETURN_NONE;
12392}
12393
12394
12395#ifdef MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +100012396/*[clinic input]
12397os.get_handle_inheritable -> bool
Benjamin Petersonca470632016-09-06 13:47:26 -070012398 handle: intptr_t
Larry Hastings2f936352014-08-05 14:04:04 +100012399 /
Victor Stinnerdaf45552013-08-28 00:53:59 +020012400
Larry Hastings2f936352014-08-05 14:04:04 +100012401Get the close-on-exe flag of the specified file descriptor.
12402[clinic start generated code]*/
12403
Larry Hastings2f936352014-08-05 14:04:04 +100012404static int
Benjamin Petersonca470632016-09-06 13:47:26 -070012405os_get_handle_inheritable_impl(PyObject *module, intptr_t handle)
Victor Stinner581139c2016-09-06 15:54:20 -070012406/*[clinic end generated code: output=36be5afca6ea84d8 input=cfe99f9c05c70ad1]*/
Larry Hastings2f936352014-08-05 14:04:04 +100012407{
12408 DWORD flags;
Victor Stinnerdaf45552013-08-28 00:53:59 +020012409
12410 if (!GetHandleInformation((HANDLE)handle, &flags)) {
12411 PyErr_SetFromWindowsErr(0);
Larry Hastings2f936352014-08-05 14:04:04 +100012412 return -1;
Victor Stinnerdaf45552013-08-28 00:53:59 +020012413 }
12414
Larry Hastings2f936352014-08-05 14:04:04 +100012415 return flags & HANDLE_FLAG_INHERIT;
Victor Stinnerdaf45552013-08-28 00:53:59 +020012416}
12417
Victor Stinnerdaf45552013-08-28 00:53:59 +020012418
Larry Hastings2f936352014-08-05 14:04:04 +100012419/*[clinic input]
12420os.set_handle_inheritable
Benjamin Petersonca470632016-09-06 13:47:26 -070012421 handle: intptr_t
Larry Hastings2f936352014-08-05 14:04:04 +100012422 inheritable: bool
12423 /
12424
12425Set the inheritable flag of the specified handle.
12426[clinic start generated code]*/
12427
Larry Hastings2f936352014-08-05 14:04:04 +100012428static PyObject *
Benjamin Petersonca470632016-09-06 13:47:26 -070012429os_set_handle_inheritable_impl(PyObject *module, intptr_t handle,
Larry Hastings89964c42015-04-14 18:07:59 -040012430 int inheritable)
Victor Stinner581139c2016-09-06 15:54:20 -070012431/*[clinic end generated code: output=021d74fe6c96baa3 input=7a7641390d8364fc]*/
Larry Hastings2f936352014-08-05 14:04:04 +100012432{
12433 DWORD flags = inheritable ? HANDLE_FLAG_INHERIT : 0;
Victor Stinnerdaf45552013-08-28 00:53:59 +020012434 if (!SetHandleInformation((HANDLE)handle, HANDLE_FLAG_INHERIT, flags)) {
12435 PyErr_SetFromWindowsErr(0);
12436 return NULL;
12437 }
12438 Py_RETURN_NONE;
12439}
Larry Hastings2f936352014-08-05 14:04:04 +100012440#endif /* MS_WINDOWS */
Antoine Pitroubcf2b592012-02-08 23:28:36 +010012441
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012442#ifndef MS_WINDOWS
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030012443/*[clinic input]
12444os.get_blocking -> bool
12445 fd: int
12446 /
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012447
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030012448Get the blocking mode of the file descriptor.
12449
12450Return False if the O_NONBLOCK flag is set, True if the flag is cleared.
12451[clinic start generated code]*/
12452
12453static int
12454os_get_blocking_impl(PyObject *module, int fd)
12455/*[clinic end generated code: output=336a12ad76a61482 input=f4afb59d51560179]*/
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012456{
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012457 int blocking;
12458
Steve Dower8fc89802015-04-12 00:26:27 -040012459 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012460 blocking = _Py_get_blocking(fd);
Steve Dower8fc89802015-04-12 00:26:27 -040012461 _Py_END_SUPPRESS_IPH
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030012462 return blocking;
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012463}
12464
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030012465/*[clinic input]
12466os.set_blocking
12467 fd: int
12468 blocking: bool(accept={int})
12469 /
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012470
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030012471Set the blocking mode of the specified file descriptor.
12472
12473Set the O_NONBLOCK flag if blocking is False,
12474clear the O_NONBLOCK flag otherwise.
12475[clinic start generated code]*/
12476
12477static PyObject *
12478os_set_blocking_impl(PyObject *module, int fd, int blocking)
12479/*[clinic end generated code: output=384eb43aa0762a9d input=bf5c8efdc5860ff3]*/
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012480{
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030012481 int result;
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012482
Steve Dower8fc89802015-04-12 00:26:27 -040012483 _Py_BEGIN_SUPPRESS_IPH
12484 result = _Py_set_blocking(fd, blocking);
12485 _Py_END_SUPPRESS_IPH
12486 if (result < 0)
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012487 return NULL;
12488 Py_RETURN_NONE;
12489}
12490#endif /* !MS_WINDOWS */
12491
12492
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012493/*[clinic input]
Eddie Elizondob3966632019-11-05 07:16:14 -080012494class os.DirEntry "DirEntry *" "DirEntryType"
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012495[clinic start generated code]*/
Eddie Elizondob3966632019-11-05 07:16:14 -080012496/*[clinic end generated code: output=da39a3ee5e6b4b0d input=3c18c7a448247980]*/
Victor Stinner6036e442015-03-08 01:58:04 +010012497
12498typedef struct {
12499 PyObject_HEAD
12500 PyObject *name;
12501 PyObject *path;
12502 PyObject *stat;
12503 PyObject *lstat;
12504#ifdef MS_WINDOWS
12505 struct _Py_stat_struct win32_lstat;
Victor Stinner0f6d7332017-03-09 17:34:28 +010012506 uint64_t win32_file_index;
Victor Stinner6036e442015-03-08 01:58:04 +010012507 int got_file_index;
12508#else /* POSIX */
Victor Stinner35a97c02015-03-08 02:59:09 +010012509#ifdef HAVE_DIRENT_D_TYPE
Victor Stinner6036e442015-03-08 01:58:04 +010012510 unsigned char d_type;
Victor Stinner35a97c02015-03-08 02:59:09 +010012511#endif
Victor Stinner6036e442015-03-08 01:58:04 +010012512 ino_t d_ino;
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012513 int dir_fd;
Victor Stinner6036e442015-03-08 01:58:04 +010012514#endif
12515} DirEntry;
12516
Eddie Elizondob3966632019-11-05 07:16:14 -080012517static PyObject *
12518_disabled_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
12519{
12520 PyErr_Format(PyExc_TypeError,
12521 "cannot create '%.100s' instances", _PyType_Name(type));
12522 return NULL;
12523}
12524
Victor Stinner6036e442015-03-08 01:58:04 +010012525static void
12526DirEntry_dealloc(DirEntry *entry)
12527{
Eddie Elizondob3966632019-11-05 07:16:14 -080012528 PyTypeObject *tp = Py_TYPE(entry);
Victor Stinner6036e442015-03-08 01:58:04 +010012529 Py_XDECREF(entry->name);
12530 Py_XDECREF(entry->path);
12531 Py_XDECREF(entry->stat);
12532 Py_XDECREF(entry->lstat);
Eddie Elizondob3966632019-11-05 07:16:14 -080012533 freefunc free_func = PyType_GetSlot(tp, Py_tp_free);
12534 free_func(entry);
12535 Py_DECREF(tp);
Victor Stinner6036e442015-03-08 01:58:04 +010012536}
12537
12538/* Forward reference */
12539static int
12540DirEntry_test_mode(DirEntry *self, int follow_symlinks, unsigned short mode_bits);
12541
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012542/*[clinic input]
12543os.DirEntry.is_symlink -> bool
12544
12545Return True if the entry is a symbolic link; cached per entry.
12546[clinic start generated code]*/
12547
Victor Stinner6036e442015-03-08 01:58:04 +010012548static int
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012549os_DirEntry_is_symlink_impl(DirEntry *self)
12550/*[clinic end generated code: output=42244667d7bcfc25 input=1605a1b4b96976c3]*/
Victor Stinner6036e442015-03-08 01:58:04 +010012551{
12552#ifdef MS_WINDOWS
12553 return (self->win32_lstat.st_mode & S_IFMT) == S_IFLNK;
Victor Stinner35a97c02015-03-08 02:59:09 +010012554#elif defined(HAVE_DIRENT_D_TYPE)
12555 /* POSIX */
Victor Stinner6036e442015-03-08 01:58:04 +010012556 if (self->d_type != DT_UNKNOWN)
12557 return self->d_type == DT_LNK;
12558 else
12559 return DirEntry_test_mode(self, 0, S_IFLNK);
Victor Stinner35a97c02015-03-08 02:59:09 +010012560#else
12561 /* POSIX without d_type */
12562 return DirEntry_test_mode(self, 0, S_IFLNK);
Victor Stinner6036e442015-03-08 01:58:04 +010012563#endif
12564}
12565
12566static PyObject *
Victor Stinner6036e442015-03-08 01:58:04 +010012567DirEntry_fetch_stat(DirEntry *self, int follow_symlinks)
12568{
12569 int result;
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012570 STRUCT_STAT st;
12571 PyObject *ub;
Victor Stinner6036e442015-03-08 01:58:04 +010012572
12573#ifdef MS_WINDOWS
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012574 if (!PyUnicode_FSDecoder(self->path, &ub))
12575 return NULL;
12576 const wchar_t *path = PyUnicode_AsUnicode(ub);
Victor Stinner6036e442015-03-08 01:58:04 +010012577#else /* POSIX */
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012578 if (!PyUnicode_FSConverter(self->path, &ub))
12579 return NULL;
12580 const char *path = PyBytes_AS_STRING(ub);
12581 if (self->dir_fd != DEFAULT_DIR_FD) {
12582#ifdef HAVE_FSTATAT
12583 result = fstatat(self->dir_fd, path, &st,
12584 follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW);
12585#else
12586 PyErr_SetString(PyExc_NotImplementedError, "can't fetch stat");
12587 return NULL;
12588#endif /* HAVE_FSTATAT */
12589 }
12590 else
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012591#endif
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012592 {
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012593 if (follow_symlinks)
12594 result = STAT(path, &st);
12595 else
12596 result = LSTAT(path, &st);
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012597 }
12598 Py_DECREF(ub);
Victor Stinner6036e442015-03-08 01:58:04 +010012599
12600 if (result != 0)
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012601 return path_object_error(self->path);
Victor Stinner6036e442015-03-08 01:58:04 +010012602
12603 return _pystat_fromstructstat(&st);
12604}
12605
12606static PyObject *
12607DirEntry_get_lstat(DirEntry *self)
12608{
12609 if (!self->lstat) {
12610#ifdef MS_WINDOWS
12611 self->lstat = _pystat_fromstructstat(&self->win32_lstat);
12612#else /* POSIX */
12613 self->lstat = DirEntry_fetch_stat(self, 0);
12614#endif
12615 }
12616 Py_XINCREF(self->lstat);
12617 return self->lstat;
12618}
12619
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012620/*[clinic input]
12621os.DirEntry.stat
12622 *
12623 follow_symlinks: bool = True
12624
12625Return stat_result object for the entry; cached per entry.
12626[clinic start generated code]*/
12627
Victor Stinner6036e442015-03-08 01:58:04 +010012628static PyObject *
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012629os_DirEntry_stat_impl(DirEntry *self, int follow_symlinks)
12630/*[clinic end generated code: output=008593b3a6d01305 input=280d14c1d6f1d00d]*/
Victor Stinner6036e442015-03-08 01:58:04 +010012631{
12632 if (!follow_symlinks)
12633 return DirEntry_get_lstat(self);
12634
12635 if (!self->stat) {
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012636 int result = os_DirEntry_is_symlink_impl(self);
Victor Stinner6036e442015-03-08 01:58:04 +010012637 if (result == -1)
12638 return NULL;
12639 else if (result)
12640 self->stat = DirEntry_fetch_stat(self, 1);
12641 else
12642 self->stat = DirEntry_get_lstat(self);
12643 }
12644
12645 Py_XINCREF(self->stat);
12646 return self->stat;
12647}
12648
Victor Stinner6036e442015-03-08 01:58:04 +010012649/* Set exception and return -1 on error, 0 for False, 1 for True */
12650static int
12651DirEntry_test_mode(DirEntry *self, int follow_symlinks, unsigned short mode_bits)
12652{
12653 PyObject *stat = NULL;
12654 PyObject *st_mode = NULL;
12655 long mode;
12656 int result;
Victor Stinner35a97c02015-03-08 02:59:09 +010012657#if defined(MS_WINDOWS) || defined(HAVE_DIRENT_D_TYPE)
Victor Stinner6036e442015-03-08 01:58:04 +010012658 int is_symlink;
12659 int need_stat;
Victor Stinner35a97c02015-03-08 02:59:09 +010012660#endif
Victor Stinner6036e442015-03-08 01:58:04 +010012661#ifdef MS_WINDOWS
12662 unsigned long dir_bits;
12663#endif
12664
12665#ifdef MS_WINDOWS
12666 is_symlink = (self->win32_lstat.st_mode & S_IFMT) == S_IFLNK;
12667 need_stat = follow_symlinks && is_symlink;
Victor Stinner35a97c02015-03-08 02:59:09 +010012668#elif defined(HAVE_DIRENT_D_TYPE)
Victor Stinner6036e442015-03-08 01:58:04 +010012669 is_symlink = self->d_type == DT_LNK;
12670 need_stat = self->d_type == DT_UNKNOWN || (follow_symlinks && is_symlink);
12671#endif
12672
Victor Stinner35a97c02015-03-08 02:59:09 +010012673#if defined(MS_WINDOWS) || defined(HAVE_DIRENT_D_TYPE)
Victor Stinner6036e442015-03-08 01:58:04 +010012674 if (need_stat) {
Victor Stinner35a97c02015-03-08 02:59:09 +010012675#endif
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012676 stat = os_DirEntry_stat_impl(self, follow_symlinks);
Victor Stinner6036e442015-03-08 01:58:04 +010012677 if (!stat) {
12678 if (PyErr_ExceptionMatches(PyExc_FileNotFoundError)) {
12679 /* If file doesn't exist (anymore), then return False
12680 (i.e., say it's not a file/directory) */
12681 PyErr_Clear();
12682 return 0;
12683 }
12684 goto error;
12685 }
Eddie Elizondob3966632019-11-05 07:16:14 -080012686 st_mode = PyObject_GetAttr(stat, _posixstate_global->st_mode);
Victor Stinner6036e442015-03-08 01:58:04 +010012687 if (!st_mode)
12688 goto error;
12689
12690 mode = PyLong_AsLong(st_mode);
12691 if (mode == -1 && PyErr_Occurred())
12692 goto error;
12693 Py_CLEAR(st_mode);
12694 Py_CLEAR(stat);
12695 result = (mode & S_IFMT) == mode_bits;
Victor Stinner35a97c02015-03-08 02:59:09 +010012696#if defined(MS_WINDOWS) || defined(HAVE_DIRENT_D_TYPE)
Victor Stinner6036e442015-03-08 01:58:04 +010012697 }
12698 else if (is_symlink) {
12699 assert(mode_bits != S_IFLNK);
12700 result = 0;
12701 }
12702 else {
12703 assert(mode_bits == S_IFDIR || mode_bits == S_IFREG);
12704#ifdef MS_WINDOWS
12705 dir_bits = self->win32_lstat.st_file_attributes & FILE_ATTRIBUTE_DIRECTORY;
12706 if (mode_bits == S_IFDIR)
12707 result = dir_bits != 0;
12708 else
12709 result = dir_bits == 0;
12710#else /* POSIX */
12711 if (mode_bits == S_IFDIR)
12712 result = self->d_type == DT_DIR;
12713 else
12714 result = self->d_type == DT_REG;
12715#endif
12716 }
Victor Stinner35a97c02015-03-08 02:59:09 +010012717#endif
Victor Stinner6036e442015-03-08 01:58:04 +010012718
12719 return result;
12720
12721error:
12722 Py_XDECREF(st_mode);
12723 Py_XDECREF(stat);
12724 return -1;
12725}
12726
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012727/*[clinic input]
12728os.DirEntry.is_dir -> bool
12729 *
12730 follow_symlinks: bool = True
Victor Stinner6036e442015-03-08 01:58:04 +010012731
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012732Return True if the entry is a directory; cached per entry.
12733[clinic start generated code]*/
12734
12735static int
12736os_DirEntry_is_dir_impl(DirEntry *self, int follow_symlinks)
12737/*[clinic end generated code: output=ad2e8d54365da287 input=0135232766f53f58]*/
12738{
12739 return DirEntry_test_mode(self, follow_symlinks, S_IFDIR);
Victor Stinner6036e442015-03-08 01:58:04 +010012740}
12741
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012742/*[clinic input]
12743os.DirEntry.is_file -> bool
12744 *
12745 follow_symlinks: bool = True
12746
12747Return True if the entry is a file; cached per entry.
12748[clinic start generated code]*/
12749
12750static int
12751os_DirEntry_is_file_impl(DirEntry *self, int follow_symlinks)
12752/*[clinic end generated code: output=8462ade481d8a476 input=0dc90be168b041ee]*/
Victor Stinner6036e442015-03-08 01:58:04 +010012753{
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012754 return DirEntry_test_mode(self, follow_symlinks, S_IFREG);
Victor Stinner6036e442015-03-08 01:58:04 +010012755}
12756
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012757/*[clinic input]
12758os.DirEntry.inode
Victor Stinner6036e442015-03-08 01:58:04 +010012759
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012760Return inode of the entry; cached per entry.
12761[clinic start generated code]*/
Victor Stinner6036e442015-03-08 01:58:04 +010012762
12763static PyObject *
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012764os_DirEntry_inode_impl(DirEntry *self)
12765/*[clinic end generated code: output=156bb3a72162440e input=3ee7b872ae8649f0]*/
Victor Stinner6036e442015-03-08 01:58:04 +010012766{
12767#ifdef MS_WINDOWS
12768 if (!self->got_file_index) {
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012769 PyObject *unicode;
Serhiy Storchakadeab18d2016-05-07 16:45:18 +030012770 const wchar_t *path;
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012771 STRUCT_STAT stat;
12772 int result;
Victor Stinner6036e442015-03-08 01:58:04 +010012773
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012774 if (!PyUnicode_FSDecoder(self->path, &unicode))
Victor Stinner6036e442015-03-08 01:58:04 +010012775 return NULL;
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012776 path = PyUnicode_AsUnicode(unicode);
12777 result = LSTAT(path, &stat);
12778 Py_DECREF(unicode);
Victor Stinner6036e442015-03-08 01:58:04 +010012779
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012780 if (result != 0)
12781 return path_object_error(self->path);
Victor Stinner6036e442015-03-08 01:58:04 +010012782
12783 self->win32_file_index = stat.st_ino;
12784 self->got_file_index = 1;
12785 }
Victor Stinner0f6d7332017-03-09 17:34:28 +010012786 Py_BUILD_ASSERT(sizeof(unsigned long long) >= sizeof(self->win32_file_index));
12787 return PyLong_FromUnsignedLongLong(self->win32_file_index);
Victor Stinner6036e442015-03-08 01:58:04 +010012788#else /* POSIX */
xdegaye50e86032017-05-22 11:15:08 +020012789 Py_BUILD_ASSERT(sizeof(unsigned long long) >= sizeof(self->d_ino));
12790 return PyLong_FromUnsignedLongLong(self->d_ino);
Victor Stinner6036e442015-03-08 01:58:04 +010012791#endif
12792}
12793
12794static PyObject *
12795DirEntry_repr(DirEntry *self)
12796{
12797 return PyUnicode_FromFormat("<DirEntry %R>", self->name);
12798}
12799
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012800/*[clinic input]
12801os.DirEntry.__fspath__
12802
12803Returns the path for the entry.
12804[clinic start generated code]*/
12805
Brett Cannon96881cd2016-06-10 14:37:21 -070012806static PyObject *
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012807os_DirEntry___fspath___impl(DirEntry *self)
12808/*[clinic end generated code: output=6dd7f7ef752e6f4f input=3c49d0cf38df4fac]*/
Brett Cannon96881cd2016-06-10 14:37:21 -070012809{
12810 Py_INCREF(self->path);
12811 return self->path;
12812}
12813
Victor Stinner6036e442015-03-08 01:58:04 +010012814static PyMemberDef DirEntry_members[] = {
12815 {"name", T_OBJECT_EX, offsetof(DirEntry, name), READONLY,
12816 "the entry's base filename, relative to scandir() \"path\" argument"},
12817 {"path", T_OBJECT_EX, offsetof(DirEntry, path), READONLY,
12818 "the entry's full path name; equivalent to os.path.join(scandir_path, entry.name)"},
12819 {NULL}
12820};
12821
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012822#include "clinic/posixmodule.c.h"
12823
Victor Stinner6036e442015-03-08 01:58:04 +010012824static PyMethodDef DirEntry_methods[] = {
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012825 OS_DIRENTRY_IS_DIR_METHODDEF
12826 OS_DIRENTRY_IS_FILE_METHODDEF
12827 OS_DIRENTRY_IS_SYMLINK_METHODDEF
12828 OS_DIRENTRY_STAT_METHODDEF
12829 OS_DIRENTRY_INODE_METHODDEF
12830 OS_DIRENTRY___FSPATH___METHODDEF
Victor Stinner6036e442015-03-08 01:58:04 +010012831 {NULL}
12832};
12833
Eddie Elizondob3966632019-11-05 07:16:14 -080012834static PyType_Slot DirEntryType_slots[] = {
12835 {Py_tp_new, _disabled_new},
12836 {Py_tp_dealloc, DirEntry_dealloc},
12837 {Py_tp_repr, DirEntry_repr},
12838 {Py_tp_methods, DirEntry_methods},
12839 {Py_tp_members, DirEntry_members},
12840 {0, 0},
Victor Stinner6036e442015-03-08 01:58:04 +010012841};
12842
Eddie Elizondob3966632019-11-05 07:16:14 -080012843static PyType_Spec DirEntryType_spec = {
12844 MODNAME ".DirEntry",
12845 sizeof(DirEntry),
12846 0,
12847 Py_TPFLAGS_DEFAULT,
12848 DirEntryType_slots
12849};
12850
12851
Victor Stinner6036e442015-03-08 01:58:04 +010012852#ifdef MS_WINDOWS
12853
12854static wchar_t *
Serhiy Storchakadeab18d2016-05-07 16:45:18 +030012855join_path_filenameW(const wchar_t *path_wide, const wchar_t *filename)
Victor Stinner6036e442015-03-08 01:58:04 +010012856{
12857 Py_ssize_t path_len;
12858 Py_ssize_t size;
12859 wchar_t *result;
12860 wchar_t ch;
12861
12862 if (!path_wide) { /* Default arg: "." */
12863 path_wide = L".";
12864 path_len = 1;
12865 }
12866 else {
12867 path_len = wcslen(path_wide);
12868 }
12869
12870 /* The +1's are for the path separator and the NUL */
12871 size = path_len + 1 + wcslen(filename) + 1;
12872 result = PyMem_New(wchar_t, size);
12873 if (!result) {
12874 PyErr_NoMemory();
12875 return NULL;
12876 }
12877 wcscpy(result, path_wide);
12878 if (path_len > 0) {
12879 ch = result[path_len - 1];
12880 if (ch != SEP && ch != ALTSEP && ch != L':')
12881 result[path_len++] = SEP;
12882 wcscpy(result + path_len, filename);
12883 }
12884 return result;
12885}
12886
12887static PyObject *
12888DirEntry_from_find_data(path_t *path, WIN32_FIND_DATAW *dataW)
12889{
12890 DirEntry *entry;
12891 BY_HANDLE_FILE_INFORMATION file_info;
12892 ULONG reparse_tag;
12893 wchar_t *joined_path;
12894
Eddie Elizondob3966632019-11-05 07:16:14 -080012895 PyObject *DirEntryType = _posixstate_global->DirEntryType;
12896 entry = PyObject_New(DirEntry, (PyTypeObject *)DirEntryType);
Victor Stinner6036e442015-03-08 01:58:04 +010012897 if (!entry)
12898 return NULL;
12899 entry->name = NULL;
12900 entry->path = NULL;
12901 entry->stat = NULL;
12902 entry->lstat = NULL;
12903 entry->got_file_index = 0;
12904
12905 entry->name = PyUnicode_FromWideChar(dataW->cFileName, -1);
12906 if (!entry->name)
12907 goto error;
Steve Dowercc16be82016-09-08 10:35:16 -070012908 if (path->narrow) {
12909 Py_SETREF(entry->name, PyUnicode_EncodeFSDefault(entry->name));
12910 if (!entry->name)
12911 goto error;
12912 }
Victor Stinner6036e442015-03-08 01:58:04 +010012913
12914 joined_path = join_path_filenameW(path->wide, dataW->cFileName);
12915 if (!joined_path)
12916 goto error;
12917
12918 entry->path = PyUnicode_FromWideChar(joined_path, -1);
12919 PyMem_Free(joined_path);
12920 if (!entry->path)
12921 goto error;
Steve Dowercc16be82016-09-08 10:35:16 -070012922 if (path->narrow) {
12923 Py_SETREF(entry->path, PyUnicode_EncodeFSDefault(entry->path));
12924 if (!entry->path)
12925 goto error;
12926 }
Victor Stinner6036e442015-03-08 01:58:04 +010012927
Steve Dowercc16be82016-09-08 10:35:16 -070012928 find_data_to_file_info(dataW, &file_info, &reparse_tag);
Victor Stinner6036e442015-03-08 01:58:04 +010012929 _Py_attribute_data_to_stat(&file_info, reparse_tag, &entry->win32_lstat);
12930
12931 return (PyObject *)entry;
12932
12933error:
12934 Py_DECREF(entry);
12935 return NULL;
12936}
12937
12938#else /* POSIX */
12939
12940static char *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +020012941join_path_filename(const char *path_narrow, const char* filename, Py_ssize_t filename_len)
Victor Stinner6036e442015-03-08 01:58:04 +010012942{
12943 Py_ssize_t path_len;
12944 Py_ssize_t size;
12945 char *result;
12946
12947 if (!path_narrow) { /* Default arg: "." */
12948 path_narrow = ".";
12949 path_len = 1;
12950 }
12951 else {
12952 path_len = strlen(path_narrow);
12953 }
12954
12955 if (filename_len == -1)
12956 filename_len = strlen(filename);
12957
12958 /* The +1's are for the path separator and the NUL */
12959 size = path_len + 1 + filename_len + 1;
12960 result = PyMem_New(char, size);
12961 if (!result) {
12962 PyErr_NoMemory();
12963 return NULL;
12964 }
12965 strcpy(result, path_narrow);
12966 if (path_len > 0 && result[path_len - 1] != '/')
12967 result[path_len++] = '/';
12968 strcpy(result + path_len, filename);
12969 return result;
12970}
12971
12972static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +020012973DirEntry_from_posix_info(path_t *path, const char *name, Py_ssize_t name_len,
Victor Stinner35a97c02015-03-08 02:59:09 +010012974 ino_t d_ino
12975#ifdef HAVE_DIRENT_D_TYPE
12976 , unsigned char d_type
12977#endif
12978 )
Victor Stinner6036e442015-03-08 01:58:04 +010012979{
12980 DirEntry *entry;
12981 char *joined_path;
12982
Eddie Elizondob3966632019-11-05 07:16:14 -080012983 PyObject *DirEntryType = _posixstate_global->DirEntryType;
12984 entry = PyObject_New(DirEntry, (PyTypeObject *)DirEntryType);
Victor Stinner6036e442015-03-08 01:58:04 +010012985 if (!entry)
12986 return NULL;
12987 entry->name = NULL;
12988 entry->path = NULL;
12989 entry->stat = NULL;
12990 entry->lstat = NULL;
12991
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012992 if (path->fd != -1) {
12993 entry->dir_fd = path->fd;
12994 joined_path = NULL;
12995 }
12996 else {
12997 entry->dir_fd = DEFAULT_DIR_FD;
12998 joined_path = join_path_filename(path->narrow, name, name_len);
12999 if (!joined_path)
13000 goto error;
13001 }
Victor Stinner6036e442015-03-08 01:58:04 +010013002
Serhiy Storchaka1180e5a2017-07-11 06:36:46 +030013003 if (!path->narrow || !PyObject_CheckBuffer(path->object)) {
Victor Stinner6036e442015-03-08 01:58:04 +010013004 entry->name = PyUnicode_DecodeFSDefaultAndSize(name, name_len);
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013005 if (joined_path)
13006 entry->path = PyUnicode_DecodeFSDefault(joined_path);
Victor Stinner6036e442015-03-08 01:58:04 +010013007 }
13008 else {
13009 entry->name = PyBytes_FromStringAndSize(name, name_len);
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013010 if (joined_path)
13011 entry->path = PyBytes_FromString(joined_path);
Victor Stinner6036e442015-03-08 01:58:04 +010013012 }
13013 PyMem_Free(joined_path);
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013014 if (!entry->name)
13015 goto error;
13016
13017 if (path->fd != -1) {
13018 entry->path = entry->name;
13019 Py_INCREF(entry->path);
13020 }
13021 else if (!entry->path)
Victor Stinner6036e442015-03-08 01:58:04 +010013022 goto error;
13023
Victor Stinner35a97c02015-03-08 02:59:09 +010013024#ifdef HAVE_DIRENT_D_TYPE
Victor Stinner6036e442015-03-08 01:58:04 +010013025 entry->d_type = d_type;
Victor Stinner35a97c02015-03-08 02:59:09 +010013026#endif
Victor Stinner6036e442015-03-08 01:58:04 +010013027 entry->d_ino = d_ino;
13028
13029 return (PyObject *)entry;
13030
13031error:
13032 Py_XDECREF(entry);
13033 return NULL;
13034}
13035
13036#endif
13037
13038
13039typedef struct {
13040 PyObject_HEAD
13041 path_t path;
13042#ifdef MS_WINDOWS
13043 HANDLE handle;
13044 WIN32_FIND_DATAW file_data;
13045 int first_time;
13046#else /* POSIX */
13047 DIR *dirp;
13048#endif
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013049#ifdef HAVE_FDOPENDIR
13050 int fd;
13051#endif
Victor Stinner6036e442015-03-08 01:58:04 +010013052} ScandirIterator;
13053
13054#ifdef MS_WINDOWS
13055
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013056static int
13057ScandirIterator_is_closed(ScandirIterator *iterator)
13058{
13059 return iterator->handle == INVALID_HANDLE_VALUE;
13060}
13061
Victor Stinner6036e442015-03-08 01:58:04 +010013062static void
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013063ScandirIterator_closedir(ScandirIterator *iterator)
Victor Stinner6036e442015-03-08 01:58:04 +010013064{
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030013065 HANDLE handle = iterator->handle;
13066
13067 if (handle == INVALID_HANDLE_VALUE)
Victor Stinner6036e442015-03-08 01:58:04 +010013068 return;
13069
Victor Stinner6036e442015-03-08 01:58:04 +010013070 iterator->handle = INVALID_HANDLE_VALUE;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030013071 Py_BEGIN_ALLOW_THREADS
13072 FindClose(handle);
13073 Py_END_ALLOW_THREADS
Victor Stinner6036e442015-03-08 01:58:04 +010013074}
13075
13076static PyObject *
13077ScandirIterator_iternext(ScandirIterator *iterator)
13078{
13079 WIN32_FIND_DATAW *file_data = &iterator->file_data;
13080 BOOL success;
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013081 PyObject *entry;
Victor Stinner6036e442015-03-08 01:58:04 +010013082
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013083 /* Happens if the iterator is iterated twice, or closed explicitly */
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013084 if (iterator->handle == INVALID_HANDLE_VALUE)
Victor Stinner6036e442015-03-08 01:58:04 +010013085 return NULL;
Victor Stinner6036e442015-03-08 01:58:04 +010013086
13087 while (1) {
13088 if (!iterator->first_time) {
13089 Py_BEGIN_ALLOW_THREADS
13090 success = FindNextFileW(iterator->handle, file_data);
13091 Py_END_ALLOW_THREADS
13092 if (!success) {
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013093 /* Error or no more files */
Victor Stinner6036e442015-03-08 01:58:04 +010013094 if (GetLastError() != ERROR_NO_MORE_FILES)
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013095 path_error(&iterator->path);
Victor Stinner6036e442015-03-08 01:58:04 +010013096 break;
13097 }
13098 }
13099 iterator->first_time = 0;
13100
13101 /* Skip over . and .. */
13102 if (wcscmp(file_data->cFileName, L".") != 0 &&
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013103 wcscmp(file_data->cFileName, L"..") != 0) {
13104 entry = DirEntry_from_find_data(&iterator->path, file_data);
13105 if (!entry)
13106 break;
13107 return entry;
13108 }
Victor Stinner6036e442015-03-08 01:58:04 +010013109
13110 /* Loop till we get a non-dot directory or finish iterating */
13111 }
13112
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013113 /* Error or no more files */
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013114 ScandirIterator_closedir(iterator);
Victor Stinner6036e442015-03-08 01:58:04 +010013115 return NULL;
13116}
13117
13118#else /* POSIX */
13119
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013120static int
13121ScandirIterator_is_closed(ScandirIterator *iterator)
13122{
13123 return !iterator->dirp;
13124}
13125
Victor Stinner6036e442015-03-08 01:58:04 +010013126static void
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013127ScandirIterator_closedir(ScandirIterator *iterator)
Victor Stinner6036e442015-03-08 01:58:04 +010013128{
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030013129 DIR *dirp = iterator->dirp;
13130
13131 if (!dirp)
Victor Stinner6036e442015-03-08 01:58:04 +010013132 return;
13133
Victor Stinner6036e442015-03-08 01:58:04 +010013134 iterator->dirp = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030013135 Py_BEGIN_ALLOW_THREADS
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013136#ifdef HAVE_FDOPENDIR
13137 if (iterator->path.fd != -1)
13138 rewinddir(dirp);
13139#endif
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030013140 closedir(dirp);
13141 Py_END_ALLOW_THREADS
Victor Stinner6036e442015-03-08 01:58:04 +010013142 return;
13143}
13144
13145static PyObject *
13146ScandirIterator_iternext(ScandirIterator *iterator)
13147{
13148 struct dirent *direntp;
13149 Py_ssize_t name_len;
13150 int is_dot;
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013151 PyObject *entry;
Victor Stinner6036e442015-03-08 01:58:04 +010013152
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013153 /* Happens if the iterator is iterated twice, or closed explicitly */
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013154 if (!iterator->dirp)
Victor Stinner6036e442015-03-08 01:58:04 +010013155 return NULL;
Victor Stinner6036e442015-03-08 01:58:04 +010013156
13157 while (1) {
13158 errno = 0;
13159 Py_BEGIN_ALLOW_THREADS
13160 direntp = readdir(iterator->dirp);
13161 Py_END_ALLOW_THREADS
13162
13163 if (!direntp) {
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013164 /* Error or no more files */
Victor Stinner6036e442015-03-08 01:58:04 +010013165 if (errno != 0)
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013166 path_error(&iterator->path);
Victor Stinner6036e442015-03-08 01:58:04 +010013167 break;
13168 }
13169
13170 /* Skip over . and .. */
13171 name_len = NAMLEN(direntp);
13172 is_dot = direntp->d_name[0] == '.' &&
13173 (name_len == 1 || (direntp->d_name[1] == '.' && name_len == 2));
13174 if (!is_dot) {
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013175 entry = DirEntry_from_posix_info(&iterator->path, direntp->d_name,
Victor Stinner35a97c02015-03-08 02:59:09 +010013176 name_len, direntp->d_ino
13177#ifdef HAVE_DIRENT_D_TYPE
13178 , direntp->d_type
13179#endif
13180 );
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013181 if (!entry)
13182 break;
13183 return entry;
Victor Stinner6036e442015-03-08 01:58:04 +010013184 }
13185
13186 /* Loop till we get a non-dot directory or finish iterating */
13187 }
13188
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013189 /* Error or no more files */
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013190 ScandirIterator_closedir(iterator);
Victor Stinner6036e442015-03-08 01:58:04 +010013191 return NULL;
13192}
13193
13194#endif
13195
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013196static PyObject *
13197ScandirIterator_close(ScandirIterator *self, PyObject *args)
13198{
13199 ScandirIterator_closedir(self);
13200 Py_RETURN_NONE;
13201}
13202
13203static PyObject *
13204ScandirIterator_enter(PyObject *self, PyObject *args)
13205{
13206 Py_INCREF(self);
13207 return self;
13208}
13209
13210static PyObject *
13211ScandirIterator_exit(ScandirIterator *self, PyObject *args)
13212{
13213 ScandirIterator_closedir(self);
13214 Py_RETURN_NONE;
13215}
13216
Victor Stinner6036e442015-03-08 01:58:04 +010013217static void
Victor Stinner7bfa4092016-03-23 00:43:54 +010013218ScandirIterator_finalize(ScandirIterator *iterator)
13219{
13220 PyObject *error_type, *error_value, *error_traceback;
13221
13222 /* Save the current exception, if any. */
13223 PyErr_Fetch(&error_type, &error_value, &error_traceback);
13224
13225 if (!ScandirIterator_is_closed(iterator)) {
13226 ScandirIterator_closedir(iterator);
13227
13228 if (PyErr_ResourceWarning((PyObject *)iterator, 1,
13229 "unclosed scandir iterator %R", iterator)) {
13230 /* Spurious errors can appear at shutdown */
13231 if (PyErr_ExceptionMatches(PyExc_Warning)) {
13232 PyErr_WriteUnraisable((PyObject *) iterator);
13233 }
13234 }
13235 }
13236
Victor Stinner7bfa4092016-03-23 00:43:54 +010013237 path_cleanup(&iterator->path);
13238
13239 /* Restore the saved exception. */
13240 PyErr_Restore(error_type, error_value, error_traceback);
13241}
13242
13243static void
Victor Stinner6036e442015-03-08 01:58:04 +010013244ScandirIterator_dealloc(ScandirIterator *iterator)
13245{
Eddie Elizondob3966632019-11-05 07:16:14 -080013246 PyTypeObject *tp = Py_TYPE(iterator);
Victor Stinner7bfa4092016-03-23 00:43:54 +010013247 if (PyObject_CallFinalizerFromDealloc((PyObject *)iterator) < 0)
13248 return;
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013249
Eddie Elizondob3966632019-11-05 07:16:14 -080013250 freefunc free_func = PyType_GetSlot(tp, Py_tp_free);
13251 free_func(iterator);
13252 Py_DECREF(tp);
Victor Stinner6036e442015-03-08 01:58:04 +010013253}
13254
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013255static PyMethodDef ScandirIterator_methods[] = {
13256 {"__enter__", (PyCFunction)ScandirIterator_enter, METH_NOARGS},
13257 {"__exit__", (PyCFunction)ScandirIterator_exit, METH_VARARGS},
13258 {"close", (PyCFunction)ScandirIterator_close, METH_NOARGS},
13259 {NULL}
13260};
13261
Eddie Elizondob3966632019-11-05 07:16:14 -080013262static PyType_Slot ScandirIteratorType_slots[] = {
13263 {Py_tp_new, _disabled_new},
13264 {Py_tp_dealloc, ScandirIterator_dealloc},
13265 {Py_tp_finalize, ScandirIterator_finalize},
13266 {Py_tp_iter, PyObject_SelfIter},
13267 {Py_tp_iternext, ScandirIterator_iternext},
13268 {Py_tp_methods, ScandirIterator_methods},
13269 {0, 0},
13270};
13271
13272static PyType_Spec ScandirIteratorType_spec = {
13273 MODNAME ".ScandirIterator",
13274 sizeof(ScandirIterator),
13275 0,
13276 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_FINALIZE,
13277 ScandirIteratorType_slots
Victor Stinner6036e442015-03-08 01:58:04 +010013278};
13279
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013280/*[clinic input]
13281os.scandir
13282
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013283 path : path_t(nullable=True, allow_fd='PATH_HAVE_FDOPENDIR') = None
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013284
13285Return an iterator of DirEntry objects for given path.
13286
BNMetricsb9427072018-11-02 15:20:19 +000013287path can be specified as either str, bytes, or a path-like object. If path
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013288is bytes, the names of yielded DirEntry objects will also be bytes; in
13289all other circumstances they will be str.
13290
13291If path is None, uses the path='.'.
13292[clinic start generated code]*/
13293
Victor Stinner6036e442015-03-08 01:58:04 +010013294static PyObject *
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013295os_scandir_impl(PyObject *module, path_t *path)
BNMetricsb9427072018-11-02 15:20:19 +000013296/*[clinic end generated code: output=6eb2668b675ca89e input=6bdd312708fc3bb0]*/
Victor Stinner6036e442015-03-08 01:58:04 +010013297{
13298 ScandirIterator *iterator;
Victor Stinner6036e442015-03-08 01:58:04 +010013299#ifdef MS_WINDOWS
13300 wchar_t *path_strW;
13301#else
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013302 const char *path_str;
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013303#ifdef HAVE_FDOPENDIR
13304 int fd = -1;
13305#endif
Victor Stinner6036e442015-03-08 01:58:04 +010013306#endif
13307
Steve Dower60419a72019-06-24 08:42:54 -070013308 if (PySys_Audit("os.scandir", "O",
13309 path->object ? path->object : Py_None) < 0) {
13310 return NULL;
13311 }
13312
Eddie Elizondob3966632019-11-05 07:16:14 -080013313 PyObject *ScandirIteratorType = _posixstate(module)->ScandirIteratorType;
13314 iterator = PyObject_New(ScandirIterator, (PyTypeObject *)ScandirIteratorType);
Victor Stinner6036e442015-03-08 01:58:04 +010013315 if (!iterator)
13316 return NULL;
Victor Stinner6036e442015-03-08 01:58:04 +010013317
13318#ifdef MS_WINDOWS
13319 iterator->handle = INVALID_HANDLE_VALUE;
13320#else
13321 iterator->dirp = NULL;
13322#endif
13323
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013324 memcpy(&iterator->path, path, sizeof(path_t));
Serhiy Storchaka095ef732017-02-09 20:05:51 +020013325 /* Move the ownership to iterator->path */
13326 path->object = NULL;
13327 path->cleanup = NULL;
Victor Stinner6036e442015-03-08 01:58:04 +010013328
13329#ifdef MS_WINDOWS
Victor Stinner6036e442015-03-08 01:58:04 +010013330 iterator->first_time = 1;
13331
13332 path_strW = join_path_filenameW(iterator->path.wide, L"*.*");
13333 if (!path_strW)
13334 goto error;
13335
13336 Py_BEGIN_ALLOW_THREADS
13337 iterator->handle = FindFirstFileW(path_strW, &iterator->file_data);
13338 Py_END_ALLOW_THREADS
13339
13340 PyMem_Free(path_strW);
13341
13342 if (iterator->handle == INVALID_HANDLE_VALUE) {
13343 path_error(&iterator->path);
13344 goto error;
13345 }
13346#else /* POSIX */
Victor Stinner6036e442015-03-08 01:58:04 +010013347 errno = 0;
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013348#ifdef HAVE_FDOPENDIR
13349 if (path->fd != -1) {
13350 /* closedir() closes the FD, so we duplicate it */
13351 fd = _Py_dup(path->fd);
13352 if (fd == -1)
13353 goto error;
13354
13355 Py_BEGIN_ALLOW_THREADS
13356 iterator->dirp = fdopendir(fd);
13357 Py_END_ALLOW_THREADS
13358 }
13359 else
13360#endif
13361 {
13362 if (iterator->path.narrow)
13363 path_str = iterator->path.narrow;
13364 else
13365 path_str = ".";
13366
13367 Py_BEGIN_ALLOW_THREADS
13368 iterator->dirp = opendir(path_str);
13369 Py_END_ALLOW_THREADS
13370 }
Victor Stinner6036e442015-03-08 01:58:04 +010013371
13372 if (!iterator->dirp) {
13373 path_error(&iterator->path);
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013374#ifdef HAVE_FDOPENDIR
13375 if (fd != -1) {
13376 Py_BEGIN_ALLOW_THREADS
13377 close(fd);
13378 Py_END_ALLOW_THREADS
13379 }
13380#endif
Victor Stinner6036e442015-03-08 01:58:04 +010013381 goto error;
13382 }
13383#endif
13384
13385 return (PyObject *)iterator;
13386
13387error:
13388 Py_DECREF(iterator);
13389 return NULL;
13390}
13391
Ethan Furman410ef8e2016-06-04 12:06:26 -070013392/*
13393 Return the file system path representation of the object.
13394
13395 If the object is str or bytes, then allow it to pass through with
13396 an incremented refcount. If the object defines __fspath__(), then
13397 return the result of that method. All other types raise a TypeError.
13398*/
13399PyObject *
13400PyOS_FSPath(PyObject *path)
13401{
Brett Cannon3f9183b2016-08-26 14:44:48 -070013402 /* For error message reasons, this function is manually inlined in
13403 path_converter(). */
Ethan Furman410ef8e2016-06-04 12:06:26 -070013404 PyObject *func = NULL;
13405 PyObject *path_repr = NULL;
13406
13407 if (PyUnicode_Check(path) || PyBytes_Check(path)) {
13408 Py_INCREF(path);
13409 return path;
13410 }
13411
13412 func = _PyObject_LookupSpecial(path, &PyId___fspath__);
13413 if (NULL == func) {
13414 return PyErr_Format(PyExc_TypeError,
13415 "expected str, bytes or os.PathLike object, "
Brett Cannonc78ca1e2016-06-24 12:03:43 -070013416 "not %.200s",
Eddie Elizondob3966632019-11-05 07:16:14 -080013417 _PyType_Name(Py_TYPE(path)));
Ethan Furman410ef8e2016-06-04 12:06:26 -070013418 }
13419
Victor Stinnerf17c3de2016-12-06 18:46:19 +010013420 path_repr = _PyObject_CallNoArg(func);
Ethan Furman410ef8e2016-06-04 12:06:26 -070013421 Py_DECREF(func);
Brett Cannon044283a2016-07-15 10:41:49 -070013422 if (NULL == path_repr) {
13423 return NULL;
13424 }
13425
Brett Cannonc78ca1e2016-06-24 12:03:43 -070013426 if (!(PyUnicode_Check(path_repr) || PyBytes_Check(path_repr))) {
13427 PyErr_Format(PyExc_TypeError,
13428 "expected %.200s.__fspath__() to return str or bytes, "
Eddie Elizondob3966632019-11-05 07:16:14 -080013429 "not %.200s", _PyType_Name(Py_TYPE(path)),
13430 _PyType_Name(Py_TYPE(path_repr)));
Brett Cannonc78ca1e2016-06-24 12:03:43 -070013431 Py_DECREF(path_repr);
13432 return NULL;
13433 }
13434
Ethan Furman410ef8e2016-06-04 12:06:26 -070013435 return path_repr;
13436}
13437
13438/*[clinic input]
13439os.fspath
13440
13441 path: object
13442
13443Return the file system path representation of the object.
13444
Brett Cannonb4f43e92016-06-09 14:32:08 -070013445If the object is str or bytes, then allow it to pass through as-is. If the
13446object defines __fspath__(), then return the result of that method. All other
13447types raise a TypeError.
Ethan Furman410ef8e2016-06-04 12:06:26 -070013448[clinic start generated code]*/
13449
13450static PyObject *
Serhiy Storchaka2954f832016-07-07 18:20:03 +030013451os_fspath_impl(PyObject *module, PyObject *path)
13452/*[clinic end generated code: output=c3c3b78ecff2914f input=e357165f7b22490f]*/
Ethan Furman410ef8e2016-06-04 12:06:26 -070013453{
13454 return PyOS_FSPath(path);
13455}
Victor Stinner6036e442015-03-08 01:58:04 +010013456
Victor Stinner9b1f4742016-09-06 16:18:52 -070013457#ifdef HAVE_GETRANDOM_SYSCALL
13458/*[clinic input]
13459os.getrandom
13460
13461 size: Py_ssize_t
13462 flags: int=0
13463
13464Obtain a series of random bytes.
13465[clinic start generated code]*/
13466
13467static PyObject *
13468os_getrandom_impl(PyObject *module, Py_ssize_t size, int flags)
13469/*[clinic end generated code: output=b3a618196a61409c input=59bafac39c594947]*/
13470{
Victor Stinner9b1f4742016-09-06 16:18:52 -070013471 PyObject *bytes;
Victor Stinnerec2319c2016-09-20 23:00:59 +020013472 Py_ssize_t n;
Victor Stinner9b1f4742016-09-06 16:18:52 -070013473
13474 if (size < 0) {
13475 errno = EINVAL;
13476 return posix_error();
13477 }
13478
Victor Stinnerec2319c2016-09-20 23:00:59 +020013479 bytes = PyBytes_FromStringAndSize(NULL, size);
13480 if (bytes == NULL) {
Victor Stinner9b1f4742016-09-06 16:18:52 -070013481 PyErr_NoMemory();
13482 return NULL;
13483 }
13484
13485 while (1) {
Victor Stinnerec2319c2016-09-20 23:00:59 +020013486 n = syscall(SYS_getrandom,
13487 PyBytes_AS_STRING(bytes),
13488 PyBytes_GET_SIZE(bytes),
13489 flags);
Victor Stinner9b1f4742016-09-06 16:18:52 -070013490 if (n < 0 && errno == EINTR) {
13491 if (PyErr_CheckSignals() < 0) {
Victor Stinnerec2319c2016-09-20 23:00:59 +020013492 goto error;
Victor Stinner9b1f4742016-09-06 16:18:52 -070013493 }
Victor Stinnerec2319c2016-09-20 23:00:59 +020013494
13495 /* getrandom() was interrupted by a signal: retry */
Victor Stinner9b1f4742016-09-06 16:18:52 -070013496 continue;
13497 }
13498 break;
13499 }
13500
13501 if (n < 0) {
Victor Stinner9b1f4742016-09-06 16:18:52 -070013502 PyErr_SetFromErrno(PyExc_OSError);
Victor Stinnerec2319c2016-09-20 23:00:59 +020013503 goto error;
Victor Stinner9b1f4742016-09-06 16:18:52 -070013504 }
13505
Victor Stinnerec2319c2016-09-20 23:00:59 +020013506 if (n != size) {
13507 _PyBytes_Resize(&bytes, n);
13508 }
Victor Stinner9b1f4742016-09-06 16:18:52 -070013509
13510 return bytes;
Victor Stinnerec2319c2016-09-20 23:00:59 +020013511
13512error:
13513 Py_DECREF(bytes);
13514 return NULL;
Victor Stinner9b1f4742016-09-06 16:18:52 -070013515}
13516#endif /* HAVE_GETRANDOM_SYSCALL */
13517
Steve Dower2438cdf2019-03-29 16:37:16 -070013518#ifdef MS_WINDOWS
13519/* bpo-36085: Helper functions for managing DLL search directories
13520 * on win32
13521 */
13522
13523typedef DLL_DIRECTORY_COOKIE (WINAPI *PAddDllDirectory)(PCWSTR newDirectory);
13524typedef BOOL (WINAPI *PRemoveDllDirectory)(DLL_DIRECTORY_COOKIE cookie);
13525
13526/*[clinic input]
13527os._add_dll_directory
13528
13529 path: path_t
13530
13531Add a path to the DLL search path.
13532
13533This search path is used when resolving dependencies for imported
13534extension modules (the module itself is resolved through sys.path),
13535and also by ctypes.
13536
13537Returns an opaque value that may be passed to os.remove_dll_directory
13538to remove this directory from the search path.
13539[clinic start generated code]*/
13540
13541static PyObject *
13542os__add_dll_directory_impl(PyObject *module, path_t *path)
13543/*[clinic end generated code: output=80b025daebb5d683 input=1de3e6c13a5808c8]*/
13544{
13545 HMODULE hKernel32;
13546 PAddDllDirectory AddDllDirectory;
13547 DLL_DIRECTORY_COOKIE cookie = 0;
13548 DWORD err = 0;
13549
13550 /* For Windows 7, we have to load this. As this will be a fairly
13551 infrequent operation, just do it each time. Kernel32 is always
13552 loaded. */
13553 Py_BEGIN_ALLOW_THREADS
13554 if (!(hKernel32 = GetModuleHandleW(L"kernel32")) ||
13555 !(AddDllDirectory = (PAddDllDirectory)GetProcAddress(
13556 hKernel32, "AddDllDirectory")) ||
13557 !(cookie = (*AddDllDirectory)(path->wide))) {
13558 err = GetLastError();
13559 }
13560 Py_END_ALLOW_THREADS
13561
13562 if (err) {
13563 return win32_error_object_err("add_dll_directory",
13564 path->object, err);
13565 }
13566
13567 return PyCapsule_New(cookie, "DLL directory cookie", NULL);
13568}
13569
13570/*[clinic input]
13571os._remove_dll_directory
13572
13573 cookie: object
13574
13575Removes a path from the DLL search path.
13576
13577The parameter is an opaque value that was returned from
13578os.add_dll_directory. You can only remove directories that you added
13579yourself.
13580[clinic start generated code]*/
13581
13582static PyObject *
13583os__remove_dll_directory_impl(PyObject *module, PyObject *cookie)
13584/*[clinic end generated code: output=594350433ae535bc input=c1d16a7e7d9dc5dc]*/
13585{
13586 HMODULE hKernel32;
13587 PRemoveDllDirectory RemoveDllDirectory;
13588 DLL_DIRECTORY_COOKIE cookieValue;
13589 DWORD err = 0;
13590
13591 if (!PyCapsule_IsValid(cookie, "DLL directory cookie")) {
13592 PyErr_SetString(PyExc_TypeError,
13593 "Provided cookie was not returned from os.add_dll_directory");
13594 return NULL;
13595 }
13596
13597 cookieValue = (DLL_DIRECTORY_COOKIE)PyCapsule_GetPointer(
13598 cookie, "DLL directory cookie");
13599
13600 /* For Windows 7, we have to load this. As this will be a fairly
13601 infrequent operation, just do it each time. Kernel32 is always
13602 loaded. */
13603 Py_BEGIN_ALLOW_THREADS
13604 if (!(hKernel32 = GetModuleHandleW(L"kernel32")) ||
13605 !(RemoveDllDirectory = (PRemoveDllDirectory)GetProcAddress(
13606 hKernel32, "RemoveDllDirectory")) ||
13607 !(*RemoveDllDirectory)(cookieValue)) {
13608 err = GetLastError();
13609 }
13610 Py_END_ALLOW_THREADS
13611
13612 if (err) {
13613 return win32_error_object_err("remove_dll_directory",
13614 NULL, err);
13615 }
13616
13617 if (PyCapsule_SetName(cookie, NULL)) {
13618 return NULL;
13619 }
13620
13621 Py_RETURN_NONE;
13622}
13623
13624#endif
Larry Hastings31826802013-10-19 00:09:25 -070013625
Fred Drake5ab8eaf1999-12-09 21:13:07 +000013626static PyMethodDef posix_methods[] = {
Larry Hastings31826802013-10-19 00:09:25 -070013627
13628 OS_STAT_METHODDEF
13629 OS_ACCESS_METHODDEF
13630 OS_TTYNAME_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100013631 OS_CHDIR_METHODDEF
13632 OS_CHFLAGS_METHODDEF
13633 OS_CHMOD_METHODDEF
13634 OS_FCHMOD_METHODDEF
13635 OS_LCHMOD_METHODDEF
13636 OS_CHOWN_METHODDEF
13637 OS_FCHOWN_METHODDEF
13638 OS_LCHOWN_METHODDEF
13639 OS_LCHFLAGS_METHODDEF
13640 OS_CHROOT_METHODDEF
13641 OS_CTERMID_METHODDEF
13642 OS_GETCWD_METHODDEF
13643 OS_GETCWDB_METHODDEF
13644 OS_LINK_METHODDEF
13645 OS_LISTDIR_METHODDEF
13646 OS_LSTAT_METHODDEF
13647 OS_MKDIR_METHODDEF
13648 OS_NICE_METHODDEF
13649 OS_GETPRIORITY_METHODDEF
13650 OS_SETPRIORITY_METHODDEF
Pablo Galindo6c6ddf92018-01-29 01:56:10 +000013651 OS_POSIX_SPAWN_METHODDEF
Joannah Nanjekye92b83222019-01-16 16:29:26 +030013652 OS_POSIX_SPAWNP_METHODDEF
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030013653 OS_READLINK_METHODDEF
Pablo Galindoaac4d032019-05-31 19:39:47 +010013654 OS_COPY_FILE_RANGE_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100013655 OS_RENAME_METHODDEF
13656 OS_REPLACE_METHODDEF
13657 OS_RMDIR_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100013658 OS_SYMLINK_METHODDEF
13659 OS_SYSTEM_METHODDEF
13660 OS_UMASK_METHODDEF
13661 OS_UNAME_METHODDEF
13662 OS_UNLINK_METHODDEF
13663 OS_REMOVE_METHODDEF
13664 OS_UTIME_METHODDEF
13665 OS_TIMES_METHODDEF
13666 OS__EXIT_METHODDEF
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +020013667 OS__FCOPYFILE_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100013668 OS_EXECV_METHODDEF
13669 OS_EXECVE_METHODDEF
13670 OS_SPAWNV_METHODDEF
13671 OS_SPAWNVE_METHODDEF
13672 OS_FORK1_METHODDEF
13673 OS_FORK_METHODDEF
Antoine Pitrou346cbd32017-05-27 17:50:54 +020013674 OS_REGISTER_AT_FORK_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100013675 OS_SCHED_GET_PRIORITY_MAX_METHODDEF
13676 OS_SCHED_GET_PRIORITY_MIN_METHODDEF
13677 OS_SCHED_GETPARAM_METHODDEF
13678 OS_SCHED_GETSCHEDULER_METHODDEF
13679 OS_SCHED_RR_GET_INTERVAL_METHODDEF
13680 OS_SCHED_SETPARAM_METHODDEF
13681 OS_SCHED_SETSCHEDULER_METHODDEF
13682 OS_SCHED_YIELD_METHODDEF
13683 OS_SCHED_SETAFFINITY_METHODDEF
13684 OS_SCHED_GETAFFINITY_METHODDEF
13685 OS_OPENPTY_METHODDEF
13686 OS_FORKPTY_METHODDEF
13687 OS_GETEGID_METHODDEF
13688 OS_GETEUID_METHODDEF
13689 OS_GETGID_METHODDEF
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +020013690#ifdef HAVE_GETGROUPLIST
13691 {"getgrouplist", posix_getgrouplist, METH_VARARGS, posix_getgrouplist__doc__},
13692#endif
Larry Hastings2f936352014-08-05 14:04:04 +100013693 OS_GETGROUPS_METHODDEF
13694 OS_GETPID_METHODDEF
13695 OS_GETPGRP_METHODDEF
13696 OS_GETPPID_METHODDEF
13697 OS_GETUID_METHODDEF
13698 OS_GETLOGIN_METHODDEF
13699 OS_KILL_METHODDEF
13700 OS_KILLPG_METHODDEF
13701 OS_PLOCK_METHODDEF
Thomas Heller8b7a9572007-08-31 06:44:36 +000013702#ifdef MS_WINDOWS
Steve Dowercc16be82016-09-08 10:35:16 -070013703 OS_STARTFILE_METHODDEF
Thomas Heller8b7a9572007-08-31 06:44:36 +000013704#endif
Larry Hastings2f936352014-08-05 14:04:04 +100013705 OS_SETUID_METHODDEF
13706 OS_SETEUID_METHODDEF
13707 OS_SETREUID_METHODDEF
13708 OS_SETGID_METHODDEF
13709 OS_SETEGID_METHODDEF
13710 OS_SETREGID_METHODDEF
13711 OS_SETGROUPS_METHODDEF
Antoine Pitroub7572f02009-12-02 20:46:48 +000013712#ifdef HAVE_INITGROUPS
Victor Stinner8c62be82010-05-06 00:08:46 +000013713 {"initgroups", posix_initgroups, METH_VARARGS, posix_initgroups__doc__},
Antoine Pitroub7572f02009-12-02 20:46:48 +000013714#endif /* HAVE_INITGROUPS */
Larry Hastings2f936352014-08-05 14:04:04 +100013715 OS_GETPGID_METHODDEF
13716 OS_SETPGRP_METHODDEF
13717 OS_WAIT_METHODDEF
13718 OS_WAIT3_METHODDEF
13719 OS_WAIT4_METHODDEF
13720 OS_WAITID_METHODDEF
13721 OS_WAITPID_METHODDEF
Benjamin Peterson6c4c45e2019-11-05 19:21:29 -080013722 OS_PIDFD_OPEN_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100013723 OS_GETSID_METHODDEF
13724 OS_SETSID_METHODDEF
13725 OS_SETPGID_METHODDEF
13726 OS_TCGETPGRP_METHODDEF
13727 OS_TCSETPGRP_METHODDEF
13728 OS_OPEN_METHODDEF
13729 OS_CLOSE_METHODDEF
13730 OS_CLOSERANGE_METHODDEF
13731 OS_DEVICE_ENCODING_METHODDEF
13732 OS_DUP_METHODDEF
13733 OS_DUP2_METHODDEF
13734 OS_LOCKF_METHODDEF
13735 OS_LSEEK_METHODDEF
13736 OS_READ_METHODDEF
13737 OS_READV_METHODDEF
13738 OS_PREAD_METHODDEF
Pablo Galindo4defba32018-01-27 16:16:37 +000013739 OS_PREADV_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100013740 OS_WRITE_METHODDEF
13741 OS_WRITEV_METHODDEF
13742 OS_PWRITE_METHODDEF
Pablo Galindo4defba32018-01-27 16:16:37 +000013743 OS_PWRITEV_METHODDEF
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +000013744#ifdef HAVE_SENDFILE
Serhiy Storchaka62be7422018-11-27 13:27:31 +020013745 {"sendfile", (PyCFunction)(void(*)(void))posix_sendfile, METH_VARARGS | METH_KEYWORDS,
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +000013746 posix_sendfile__doc__},
13747#endif
Larry Hastings2f936352014-08-05 14:04:04 +100013748 OS_FSTAT_METHODDEF
13749 OS_ISATTY_METHODDEF
13750 OS_PIPE_METHODDEF
13751 OS_PIPE2_METHODDEF
13752 OS_MKFIFO_METHODDEF
13753 OS_MKNOD_METHODDEF
13754 OS_MAJOR_METHODDEF
13755 OS_MINOR_METHODDEF
13756 OS_MAKEDEV_METHODDEF
13757 OS_FTRUNCATE_METHODDEF
13758 OS_TRUNCATE_METHODDEF
13759 OS_POSIX_FALLOCATE_METHODDEF
13760 OS_POSIX_FADVISE_METHODDEF
13761 OS_PUTENV_METHODDEF
13762 OS_UNSETENV_METHODDEF
13763 OS_STRERROR_METHODDEF
13764 OS_FCHDIR_METHODDEF
13765 OS_FSYNC_METHODDEF
13766 OS_SYNC_METHODDEF
13767 OS_FDATASYNC_METHODDEF
13768 OS_WCOREDUMP_METHODDEF
13769 OS_WIFCONTINUED_METHODDEF
13770 OS_WIFSTOPPED_METHODDEF
13771 OS_WIFSIGNALED_METHODDEF
13772 OS_WIFEXITED_METHODDEF
13773 OS_WEXITSTATUS_METHODDEF
13774 OS_WTERMSIG_METHODDEF
13775 OS_WSTOPSIG_METHODDEF
13776 OS_FSTATVFS_METHODDEF
13777 OS_STATVFS_METHODDEF
13778 OS_CONFSTR_METHODDEF
13779 OS_SYSCONF_METHODDEF
13780 OS_FPATHCONF_METHODDEF
13781 OS_PATHCONF_METHODDEF
13782 OS_ABORT_METHODDEF
Serhiy Storchakaf0b50152015-05-13 00:52:39 +030013783 OS__GETFULLPATHNAME_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100013784 OS__GETDISKUSAGE_METHODDEF
13785 OS__GETFINALPATHNAME_METHODDEF
13786 OS__GETVOLUMEPATHNAME_METHODDEF
13787 OS_GETLOADAVG_METHODDEF
13788 OS_URANDOM_METHODDEF
13789 OS_SETRESUID_METHODDEF
13790 OS_SETRESGID_METHODDEF
13791 OS_GETRESUID_METHODDEF
13792 OS_GETRESGID_METHODDEF
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000013793
Larry Hastings2f936352014-08-05 14:04:04 +100013794 OS_GETXATTR_METHODDEF
13795 OS_SETXATTR_METHODDEF
13796 OS_REMOVEXATTR_METHODDEF
13797 OS_LISTXATTR_METHODDEF
13798
Antoine Pitroubcf2b592012-02-08 23:28:36 +010013799#if defined(TERMSIZE_USE_CONIO) || defined(TERMSIZE_USE_IOCTL)
13800 {"get_terminal_size", get_terminal_size, METH_VARARGS, termsize__doc__},
13801#endif
Larry Hastings2f936352014-08-05 14:04:04 +100013802 OS_CPU_COUNT_METHODDEF
13803 OS_GET_INHERITABLE_METHODDEF
13804 OS_SET_INHERITABLE_METHODDEF
13805 OS_GET_HANDLE_INHERITABLE_METHODDEF
13806 OS_SET_HANDLE_INHERITABLE_METHODDEF
Victor Stinner1db9e7b2014-07-29 22:32:47 +020013807#ifndef MS_WINDOWS
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030013808 OS_GET_BLOCKING_METHODDEF
13809 OS_SET_BLOCKING_METHODDEF
Victor Stinner1db9e7b2014-07-29 22:32:47 +020013810#endif
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013811 OS_SCANDIR_METHODDEF
Ethan Furman410ef8e2016-06-04 12:06:26 -070013812 OS_FSPATH_METHODDEF
Victor Stinner9b1f4742016-09-06 16:18:52 -070013813 OS_GETRANDOM_METHODDEF
Zackery Spytz43fdbd22019-05-29 13:57:07 -060013814 OS_MEMFD_CREATE_METHODDEF
Steve Dower2438cdf2019-03-29 16:37:16 -070013815#ifdef MS_WINDOWS
13816 OS__ADD_DLL_DIRECTORY_METHODDEF
13817 OS__REMOVE_DLL_DIRECTORY_METHODDEF
13818#endif
Victor Stinner8c62be82010-05-06 00:08:46 +000013819 {NULL, NULL} /* Sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000013820};
13821
Barry Warsaw4a342091996-12-19 23:50:02 +000013822static int
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013823all_ins(PyObject *m)
Barry Warsaw4a342091996-12-19 23:50:02 +000013824{
Guido van Rossum94f6f721999-01-06 18:42:14 +000013825#ifdef F_OK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013826 if (PyModule_AddIntMacro(m, F_OK)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013827#endif
Guido van Rossum94f6f721999-01-06 18:42:14 +000013828#ifdef R_OK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013829 if (PyModule_AddIntMacro(m, R_OK)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013830#endif
Guido van Rossum94f6f721999-01-06 18:42:14 +000013831#ifdef W_OK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013832 if (PyModule_AddIntMacro(m, W_OK)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013833#endif
Guido van Rossum94f6f721999-01-06 18:42:14 +000013834#ifdef X_OK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013835 if (PyModule_AddIntMacro(m, X_OK)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013836#endif
Fred Drakec9680921999-12-13 16:37:25 +000013837#ifdef NGROUPS_MAX
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013838 if (PyModule_AddIntMacro(m, NGROUPS_MAX)) return -1;
Fred Drakec9680921999-12-13 16:37:25 +000013839#endif
Fred Drake5ab8eaf1999-12-09 21:13:07 +000013840#ifdef TMP_MAX
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013841 if (PyModule_AddIntMacro(m, TMP_MAX)) return -1;
Fred Drake5ab8eaf1999-12-09 21:13:07 +000013842#endif
Fred Drake106c1a02002-04-23 15:58:02 +000013843#ifdef WCONTINUED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013844 if (PyModule_AddIntMacro(m, WCONTINUED)) return -1;
Fred Drake106c1a02002-04-23 15:58:02 +000013845#endif
Barry Warsaw4a342091996-12-19 23:50:02 +000013846#ifdef WNOHANG
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013847 if (PyModule_AddIntMacro(m, WNOHANG)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013848#endif
Fred Drake106c1a02002-04-23 15:58:02 +000013849#ifdef WUNTRACED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013850 if (PyModule_AddIntMacro(m, WUNTRACED)) return -1;
Fred Drake106c1a02002-04-23 15:58:02 +000013851#endif
Barry Warsaw4a342091996-12-19 23:50:02 +000013852#ifdef O_RDONLY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013853 if (PyModule_AddIntMacro(m, O_RDONLY)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013854#endif
13855#ifdef O_WRONLY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013856 if (PyModule_AddIntMacro(m, O_WRONLY)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013857#endif
13858#ifdef O_RDWR
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013859 if (PyModule_AddIntMacro(m, O_RDWR)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013860#endif
13861#ifdef O_NDELAY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013862 if (PyModule_AddIntMacro(m, O_NDELAY)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013863#endif
13864#ifdef O_NONBLOCK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013865 if (PyModule_AddIntMacro(m, O_NONBLOCK)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013866#endif
13867#ifdef O_APPEND
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013868 if (PyModule_AddIntMacro(m, O_APPEND)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013869#endif
13870#ifdef O_DSYNC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013871 if (PyModule_AddIntMacro(m, O_DSYNC)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013872#endif
13873#ifdef O_RSYNC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013874 if (PyModule_AddIntMacro(m, O_RSYNC)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013875#endif
13876#ifdef O_SYNC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013877 if (PyModule_AddIntMacro(m, O_SYNC)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013878#endif
13879#ifdef O_NOCTTY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013880 if (PyModule_AddIntMacro(m, O_NOCTTY)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013881#endif
13882#ifdef O_CREAT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013883 if (PyModule_AddIntMacro(m, O_CREAT)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013884#endif
13885#ifdef O_EXCL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013886 if (PyModule_AddIntMacro(m, O_EXCL)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013887#endif
13888#ifdef O_TRUNC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013889 if (PyModule_AddIntMacro(m, O_TRUNC)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013890#endif
Guido van Rossum98d9d091997-08-08 21:48:51 +000013891#ifdef O_BINARY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013892 if (PyModule_AddIntMacro(m, O_BINARY)) return -1;
Guido van Rossum98d9d091997-08-08 21:48:51 +000013893#endif
13894#ifdef O_TEXT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013895 if (PyModule_AddIntMacro(m, O_TEXT)) return -1;
Guido van Rossum98d9d091997-08-08 21:48:51 +000013896#endif
Jesus Cea1d642d22012-04-24 20:59:17 +020013897#ifdef O_XATTR
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013898 if (PyModule_AddIntMacro(m, O_XATTR)) return -1;
Jesus Cea1d642d22012-04-24 20:59:17 +020013899#endif
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000013900#ifdef O_LARGEFILE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013901 if (PyModule_AddIntMacro(m, O_LARGEFILE)) return -1;
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000013902#endif
doko@ubuntu.comfcff4372016-06-13 16:33:04 +020013903#ifndef __GNU__
Skip Montanaro5ff14922005-05-16 02:42:22 +000013904#ifdef O_SHLOCK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013905 if (PyModule_AddIntMacro(m, O_SHLOCK)) return -1;
Skip Montanaro5ff14922005-05-16 02:42:22 +000013906#endif
13907#ifdef O_EXLOCK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013908 if (PyModule_AddIntMacro(m, O_EXLOCK)) return -1;
Skip Montanaro5ff14922005-05-16 02:42:22 +000013909#endif
doko@ubuntu.comfcff4372016-06-13 16:33:04 +020013910#endif
Jesus Ceacf381202012-04-24 20:44:40 +020013911#ifdef O_EXEC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013912 if (PyModule_AddIntMacro(m, O_EXEC)) return -1;
Jesus Ceacf381202012-04-24 20:44:40 +020013913#endif
13914#ifdef O_SEARCH
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013915 if (PyModule_AddIntMacro(m, O_SEARCH)) return -1;
Jesus Ceacf381202012-04-24 20:44:40 +020013916#endif
Benjamin Peterson3b965a22013-03-13 10:27:41 -050013917#ifdef O_PATH
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013918 if (PyModule_AddIntMacro(m, O_PATH)) return -1;
Benjamin Peterson3b965a22013-03-13 10:27:41 -050013919#endif
Jesus Ceacf381202012-04-24 20:44:40 +020013920#ifdef O_TTY_INIT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013921 if (PyModule_AddIntMacro(m, O_TTY_INIT)) return -1;
Jesus Ceacf381202012-04-24 20:44:40 +020013922#endif
Christian Heimes177b3f92013-08-16 14:35:09 +020013923#ifdef O_TMPFILE
13924 if (PyModule_AddIntMacro(m, O_TMPFILE)) return -1;
13925#endif
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +000013926#ifdef PRIO_PROCESS
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013927 if (PyModule_AddIntMacro(m, PRIO_PROCESS)) return -1;
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +000013928#endif
13929#ifdef PRIO_PGRP
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013930 if (PyModule_AddIntMacro(m, PRIO_PGRP)) return -1;
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +000013931#endif
13932#ifdef PRIO_USER
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013933 if (PyModule_AddIntMacro(m, PRIO_USER)) return -1;
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +000013934#endif
Charles-François Natali1e045b12011-05-22 20:42:32 +020013935#ifdef O_CLOEXEC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013936 if (PyModule_AddIntMacro(m, O_CLOEXEC)) return -1;
Charles-François Natali1e045b12011-05-22 20:42:32 +020013937#endif
Jesus Cea1d642d22012-04-24 20:59:17 +020013938#ifdef O_ACCMODE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013939 if (PyModule_AddIntMacro(m, O_ACCMODE)) return -1;
Jesus Cea1d642d22012-04-24 20:59:17 +020013940#endif
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +000013941
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000013942
Jesus Cea94363612012-06-22 18:32:07 +020013943#ifdef SEEK_HOLE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013944 if (PyModule_AddIntMacro(m, SEEK_HOLE)) return -1;
Jesus Cea94363612012-06-22 18:32:07 +020013945#endif
13946#ifdef SEEK_DATA
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013947 if (PyModule_AddIntMacro(m, SEEK_DATA)) return -1;
Jesus Cea94363612012-06-22 18:32:07 +020013948#endif
13949
Tim Peters5aa91602002-01-30 05:46:57 +000013950/* MS Windows */
13951#ifdef O_NOINHERIT
Victor Stinner8c62be82010-05-06 00:08:46 +000013952 /* Don't inherit in child processes. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013953 if (PyModule_AddIntMacro(m, O_NOINHERIT)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013954#endif
13955#ifdef _O_SHORT_LIVED
Victor Stinner8c62be82010-05-06 00:08:46 +000013956 /* Optimize for short life (keep in memory). */
13957 /* MS forgot to define this one with a non-underscore form too. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013958 if (PyModule_AddIntConstant(m, "O_SHORT_LIVED", _O_SHORT_LIVED)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013959#endif
13960#ifdef O_TEMPORARY
Victor Stinner8c62be82010-05-06 00:08:46 +000013961 /* Automatically delete when last handle is closed. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013962 if (PyModule_AddIntMacro(m, O_TEMPORARY)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013963#endif
13964#ifdef O_RANDOM
Victor Stinner8c62be82010-05-06 00:08:46 +000013965 /* Optimize for random access. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013966 if (PyModule_AddIntMacro(m, O_RANDOM)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013967#endif
13968#ifdef O_SEQUENTIAL
Victor Stinner8c62be82010-05-06 00:08:46 +000013969 /* Optimize for sequential access. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013970 if (PyModule_AddIntMacro(m, O_SEQUENTIAL)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013971#endif
13972
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000013973/* GNU extensions. */
Alexandre Vassalottibee32532008-05-16 18:15:12 +000013974#ifdef O_ASYNC
Victor Stinner8c62be82010-05-06 00:08:46 +000013975 /* Send a SIGIO signal whenever input or output
13976 becomes available on file descriptor */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013977 if (PyModule_AddIntMacro(m, O_ASYNC)) return -1;
Alexandre Vassalottibee32532008-05-16 18:15:12 +000013978#endif
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000013979#ifdef O_DIRECT
Victor Stinner8c62be82010-05-06 00:08:46 +000013980 /* Direct disk access. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013981 if (PyModule_AddIntMacro(m, O_DIRECT)) return -1;
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000013982#endif
13983#ifdef O_DIRECTORY
Victor Stinner8c62be82010-05-06 00:08:46 +000013984 /* Must be a directory. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013985 if (PyModule_AddIntMacro(m, O_DIRECTORY)) return -1;
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000013986#endif
13987#ifdef O_NOFOLLOW
Victor Stinner8c62be82010-05-06 00:08:46 +000013988 /* Do not follow links. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013989 if (PyModule_AddIntMacro(m, O_NOFOLLOW)) return -1;
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000013990#endif
Jesus Cea1d642d22012-04-24 20:59:17 +020013991#ifdef O_NOLINKS
13992 /* Fails if link count of the named file is greater than 1 */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013993 if (PyModule_AddIntMacro(m, O_NOLINKS)) return -1;
Jesus Cea1d642d22012-04-24 20:59:17 +020013994#endif
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +000013995#ifdef O_NOATIME
Victor Stinner8c62be82010-05-06 00:08:46 +000013996 /* Do not update the access time. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013997 if (PyModule_AddIntMacro(m, O_NOATIME)) return -1;
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +000013998#endif
Guido van Rossumd48f2521997-12-05 22:19:34 +000013999
Victor Stinner8c62be82010-05-06 00:08:46 +000014000 /* These come from sysexits.h */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014001#ifdef EX_OK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014002 if (PyModule_AddIntMacro(m, EX_OK)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014003#endif /* EX_OK */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014004#ifdef EX_USAGE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014005 if (PyModule_AddIntMacro(m, EX_USAGE)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014006#endif /* EX_USAGE */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014007#ifdef EX_DATAERR
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014008 if (PyModule_AddIntMacro(m, EX_DATAERR)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014009#endif /* EX_DATAERR */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014010#ifdef EX_NOINPUT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014011 if (PyModule_AddIntMacro(m, EX_NOINPUT)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014012#endif /* EX_NOINPUT */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014013#ifdef EX_NOUSER
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014014 if (PyModule_AddIntMacro(m, EX_NOUSER)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014015#endif /* EX_NOUSER */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014016#ifdef EX_NOHOST
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014017 if (PyModule_AddIntMacro(m, EX_NOHOST)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014018#endif /* EX_NOHOST */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014019#ifdef EX_UNAVAILABLE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014020 if (PyModule_AddIntMacro(m, EX_UNAVAILABLE)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014021#endif /* EX_UNAVAILABLE */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014022#ifdef EX_SOFTWARE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014023 if (PyModule_AddIntMacro(m, EX_SOFTWARE)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014024#endif /* EX_SOFTWARE */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014025#ifdef EX_OSERR
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014026 if (PyModule_AddIntMacro(m, EX_OSERR)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014027#endif /* EX_OSERR */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014028#ifdef EX_OSFILE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014029 if (PyModule_AddIntMacro(m, EX_OSFILE)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014030#endif /* EX_OSFILE */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014031#ifdef EX_CANTCREAT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014032 if (PyModule_AddIntMacro(m, EX_CANTCREAT)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014033#endif /* EX_CANTCREAT */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014034#ifdef EX_IOERR
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014035 if (PyModule_AddIntMacro(m, EX_IOERR)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014036#endif /* EX_IOERR */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014037#ifdef EX_TEMPFAIL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014038 if (PyModule_AddIntMacro(m, EX_TEMPFAIL)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014039#endif /* EX_TEMPFAIL */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014040#ifdef EX_PROTOCOL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014041 if (PyModule_AddIntMacro(m, EX_PROTOCOL)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014042#endif /* EX_PROTOCOL */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014043#ifdef EX_NOPERM
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014044 if (PyModule_AddIntMacro(m, EX_NOPERM)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014045#endif /* EX_NOPERM */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014046#ifdef EX_CONFIG
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014047 if (PyModule_AddIntMacro(m, EX_CONFIG)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014048#endif /* EX_CONFIG */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014049#ifdef EX_NOTFOUND
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014050 if (PyModule_AddIntMacro(m, EX_NOTFOUND)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000014051#endif /* EX_NOTFOUND */
Barry Warsaw5676bd12003-01-07 20:57:09 +000014052
Amaury Forgeot d'Arc66d00ad2010-09-10 18:11:45 +000014053 /* statvfs */
Andrew M. Kuchling4ea04a32010-08-18 22:30:34 +000014054#ifdef ST_RDONLY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014055 if (PyModule_AddIntMacro(m, ST_RDONLY)) return -1;
Andrew M. Kuchling4ea04a32010-08-18 22:30:34 +000014056#endif /* ST_RDONLY */
14057#ifdef ST_NOSUID
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014058 if (PyModule_AddIntMacro(m, ST_NOSUID)) return -1;
Andrew M. Kuchling4ea04a32010-08-18 22:30:34 +000014059#endif /* ST_NOSUID */
14060
doko@ubuntu.comca616a22013-12-08 15:23:07 +010014061 /* GNU extensions */
14062#ifdef ST_NODEV
14063 if (PyModule_AddIntMacro(m, ST_NODEV)) return -1;
14064#endif /* ST_NODEV */
14065#ifdef ST_NOEXEC
14066 if (PyModule_AddIntMacro(m, ST_NOEXEC)) return -1;
14067#endif /* ST_NOEXEC */
14068#ifdef ST_SYNCHRONOUS
14069 if (PyModule_AddIntMacro(m, ST_SYNCHRONOUS)) return -1;
14070#endif /* ST_SYNCHRONOUS */
14071#ifdef ST_MANDLOCK
14072 if (PyModule_AddIntMacro(m, ST_MANDLOCK)) return -1;
14073#endif /* ST_MANDLOCK */
14074#ifdef ST_WRITE
14075 if (PyModule_AddIntMacro(m, ST_WRITE)) return -1;
14076#endif /* ST_WRITE */
14077#ifdef ST_APPEND
14078 if (PyModule_AddIntMacro(m, ST_APPEND)) return -1;
14079#endif /* ST_APPEND */
14080#ifdef ST_NOATIME
14081 if (PyModule_AddIntMacro(m, ST_NOATIME)) return -1;
14082#endif /* ST_NOATIME */
14083#ifdef ST_NODIRATIME
14084 if (PyModule_AddIntMacro(m, ST_NODIRATIME)) return -1;
14085#endif /* ST_NODIRATIME */
14086#ifdef ST_RELATIME
14087 if (PyModule_AddIntMacro(m, ST_RELATIME)) return -1;
14088#endif /* ST_RELATIME */
14089
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +000014090 /* FreeBSD sendfile() constants */
14091#ifdef SF_NODISKIO
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014092 if (PyModule_AddIntMacro(m, SF_NODISKIO)) return -1;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +000014093#endif
14094#ifdef SF_MNOWAIT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014095 if (PyModule_AddIntMacro(m, SF_MNOWAIT)) return -1;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +000014096#endif
14097#ifdef SF_SYNC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014098 if (PyModule_AddIntMacro(m, SF_SYNC)) return -1;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +000014099#endif
14100
Ross Lagerwall7807c352011-03-17 20:20:30 +020014101 /* constants for posix_fadvise */
14102#ifdef POSIX_FADV_NORMAL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014103 if (PyModule_AddIntMacro(m, POSIX_FADV_NORMAL)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014104#endif
14105#ifdef POSIX_FADV_SEQUENTIAL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014106 if (PyModule_AddIntMacro(m, POSIX_FADV_SEQUENTIAL)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014107#endif
14108#ifdef POSIX_FADV_RANDOM
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014109 if (PyModule_AddIntMacro(m, POSIX_FADV_RANDOM)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014110#endif
14111#ifdef POSIX_FADV_NOREUSE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014112 if (PyModule_AddIntMacro(m, POSIX_FADV_NOREUSE)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014113#endif
14114#ifdef POSIX_FADV_WILLNEED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014115 if (PyModule_AddIntMacro(m, POSIX_FADV_WILLNEED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014116#endif
14117#ifdef POSIX_FADV_DONTNEED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014118 if (PyModule_AddIntMacro(m, POSIX_FADV_DONTNEED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014119#endif
14120
14121 /* constants for waitid */
14122#if defined(HAVE_SYS_WAIT_H) && defined(HAVE_WAITID)
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014123 if (PyModule_AddIntMacro(m, P_PID)) return -1;
14124 if (PyModule_AddIntMacro(m, P_PGID)) return -1;
14125 if (PyModule_AddIntMacro(m, P_ALL)) return -1;
Benjamin Peterson5c0c3252019-11-05 21:58:31 -080014126#ifdef P_PIDFD
14127 if (PyModule_AddIntMacro(m, P_PIDFD)) return -1;
14128#endif
Ross Lagerwall7807c352011-03-17 20:20:30 +020014129#endif
14130#ifdef WEXITED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014131 if (PyModule_AddIntMacro(m, WEXITED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014132#endif
14133#ifdef WNOWAIT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014134 if (PyModule_AddIntMacro(m, WNOWAIT)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014135#endif
14136#ifdef WSTOPPED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014137 if (PyModule_AddIntMacro(m, WSTOPPED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014138#endif
14139#ifdef CLD_EXITED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014140 if (PyModule_AddIntMacro(m, CLD_EXITED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014141#endif
Dong-hee Na2eba6ad2019-10-21 16:01:05 +090014142#ifdef CLD_KILLED
14143 if (PyModule_AddIntMacro(m, CLD_KILLED)) return -1;
14144#endif
Ross Lagerwall7807c352011-03-17 20:20:30 +020014145#ifdef CLD_DUMPED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014146 if (PyModule_AddIntMacro(m, CLD_DUMPED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014147#endif
14148#ifdef CLD_TRAPPED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014149 if (PyModule_AddIntMacro(m, CLD_TRAPPED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014150#endif
Dong-hee Na2eba6ad2019-10-21 16:01:05 +090014151#ifdef CLD_STOPPED
14152 if (PyModule_AddIntMacro(m, CLD_STOPPED)) return -1;
14153#endif
Ross Lagerwall7807c352011-03-17 20:20:30 +020014154#ifdef CLD_CONTINUED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014155 if (PyModule_AddIntMacro(m, CLD_CONTINUED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014156#endif
14157
14158 /* constants for lockf */
14159#ifdef F_LOCK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014160 if (PyModule_AddIntMacro(m, F_LOCK)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014161#endif
14162#ifdef F_TLOCK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014163 if (PyModule_AddIntMacro(m, F_TLOCK)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014164#endif
14165#ifdef F_ULOCK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014166 if (PyModule_AddIntMacro(m, F_ULOCK)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014167#endif
14168#ifdef F_TEST
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014169 if (PyModule_AddIntMacro(m, F_TEST)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014170#endif
14171
Pablo Galindo4defba32018-01-27 16:16:37 +000014172#ifdef RWF_DSYNC
14173 if (PyModule_AddIntConstant(m, "RWF_DSYNC", RWF_DSYNC)) return -1;
14174#endif
14175#ifdef RWF_HIPRI
14176 if (PyModule_AddIntConstant(m, "RWF_HIPRI", RWF_HIPRI)) return -1;
14177#endif
14178#ifdef RWF_SYNC
14179 if (PyModule_AddIntConstant(m, "RWF_SYNC", RWF_SYNC)) return -1;
14180#endif
14181#ifdef RWF_NOWAIT
14182 if (PyModule_AddIntConstant(m, "RWF_NOWAIT", RWF_NOWAIT)) return -1;
14183#endif
14184
Pablo Galindo6c6ddf92018-01-29 01:56:10 +000014185/* constants for posix_spawn */
14186#ifdef HAVE_POSIX_SPAWN
14187 if (PyModule_AddIntConstant(m, "POSIX_SPAWN_OPEN", POSIX_SPAWN_OPEN)) return -1;
14188 if (PyModule_AddIntConstant(m, "POSIX_SPAWN_CLOSE", POSIX_SPAWN_CLOSE)) return -1;
14189 if (PyModule_AddIntConstant(m, "POSIX_SPAWN_DUP2", POSIX_SPAWN_DUP2)) return -1;
14190#endif
14191
pxinwrf2d7ac72019-05-21 18:46:37 +080014192#if defined(HAVE_SPAWNV) || defined (HAVE_RTPSPAWN)
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014193 if (PyModule_AddIntConstant(m, "P_WAIT", _P_WAIT)) return -1;
14194 if (PyModule_AddIntConstant(m, "P_NOWAIT", _P_NOWAIT)) return -1;
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014195 if (PyModule_AddIntConstant(m, "P_NOWAITO", _P_NOWAITO)) return -1;
pxinwrf2d7ac72019-05-21 18:46:37 +080014196#endif
14197#ifdef HAVE_SPAWNV
14198 if (PyModule_AddIntConstant(m, "P_OVERLAY", _OLD_P_OVERLAY)) return -1;
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014199 if (PyModule_AddIntConstant(m, "P_DETACH", _P_DETACH)) return -1;
Guido van Rossum246bc171999-02-01 23:54:31 +000014200#endif
14201
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014202#ifdef HAVE_SCHED_H
Benjamin Petersondbaa5592016-07-30 23:21:50 -070014203#ifdef SCHED_OTHER
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014204 if (PyModule_AddIntMacro(m, SCHED_OTHER)) return -1;
Benjamin Petersondbaa5592016-07-30 23:21:50 -070014205#endif
14206#ifdef SCHED_FIFO
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014207 if (PyModule_AddIntMacro(m, SCHED_FIFO)) return -1;
Benjamin Petersondbaa5592016-07-30 23:21:50 -070014208#endif
14209#ifdef SCHED_RR
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014210 if (PyModule_AddIntMacro(m, SCHED_RR)) return -1;
Benjamin Petersondbaa5592016-07-30 23:21:50 -070014211#endif
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014212#ifdef SCHED_SPORADIC
messi Liao0d322182017-06-13 22:30:43 +080014213 if (PyModule_AddIntMacro(m, SCHED_SPORADIC)) return -1;
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014214#endif
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014215#ifdef SCHED_BATCH
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014216 if (PyModule_AddIntMacro(m, SCHED_BATCH)) return -1;
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014217#endif
14218#ifdef SCHED_IDLE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014219 if (PyModule_AddIntMacro(m, SCHED_IDLE)) return -1;
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014220#endif
14221#ifdef SCHED_RESET_ON_FORK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014222 if (PyModule_AddIntMacro(m, SCHED_RESET_ON_FORK)) return -1;
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014223#endif
Jesus Ceaf2cb4e82011-09-09 23:55:42 +020014224#ifdef SCHED_SYS
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014225 if (PyModule_AddIntMacro(m, SCHED_SYS)) return -1;
Jesus Ceaf2cb4e82011-09-09 23:55:42 +020014226#endif
14227#ifdef SCHED_IA
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014228 if (PyModule_AddIntMacro(m, SCHED_IA)) return -1;
Jesus Ceaf2cb4e82011-09-09 23:55:42 +020014229#endif
14230#ifdef SCHED_FSS
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014231 if (PyModule_AddIntMacro(m, SCHED_FSS)) return -1;
Jesus Ceaf2cb4e82011-09-09 23:55:42 +020014232#endif
14233#ifdef SCHED_FX
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014234 if (PyModule_AddIntConstant(m, "SCHED_FX", SCHED_FSS)) return -1;
Jesus Ceaf2cb4e82011-09-09 23:55:42 +020014235#endif
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014236#endif
14237
Benjamin Peterson9428d532011-09-14 11:45:52 -040014238#ifdef USE_XATTRS
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014239 if (PyModule_AddIntMacro(m, XATTR_CREATE)) return -1;
14240 if (PyModule_AddIntMacro(m, XATTR_REPLACE)) return -1;
14241 if (PyModule_AddIntMacro(m, XATTR_SIZE_MAX)) return -1;
Benjamin Peterson799bd802011-08-31 22:15:17 -040014242#endif
14243
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030014244#if HAVE_DECL_RTLD_LAZY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014245 if (PyModule_AddIntMacro(m, RTLD_LAZY)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020014246#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030014247#if HAVE_DECL_RTLD_NOW
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014248 if (PyModule_AddIntMacro(m, RTLD_NOW)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020014249#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030014250#if HAVE_DECL_RTLD_GLOBAL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014251 if (PyModule_AddIntMacro(m, RTLD_GLOBAL)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020014252#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030014253#if HAVE_DECL_RTLD_LOCAL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014254 if (PyModule_AddIntMacro(m, RTLD_LOCAL)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020014255#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030014256#if HAVE_DECL_RTLD_NODELETE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014257 if (PyModule_AddIntMacro(m, RTLD_NODELETE)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020014258#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030014259#if HAVE_DECL_RTLD_NOLOAD
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014260 if (PyModule_AddIntMacro(m, RTLD_NOLOAD)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020014261#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030014262#if HAVE_DECL_RTLD_DEEPBIND
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014263 if (PyModule_AddIntMacro(m, RTLD_DEEPBIND)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020014264#endif
Michael Feltc5ae1692017-12-19 13:58:49 +010014265#if HAVE_DECL_RTLD_MEMBER
14266 if (PyModule_AddIntMacro(m, RTLD_MEMBER)) return -1;
14267#endif
Victor Stinner8b905bd2011-10-25 13:34:04 +020014268
Victor Stinner9b1f4742016-09-06 16:18:52 -070014269#ifdef HAVE_GETRANDOM_SYSCALL
14270 if (PyModule_AddIntMacro(m, GRND_RANDOM)) return -1;
14271 if (PyModule_AddIntMacro(m, GRND_NONBLOCK)) return -1;
14272#endif
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014273#ifdef HAVE_MEMFD_CREATE
14274 if (PyModule_AddIntMacro(m, MFD_CLOEXEC)) return -1;
14275 if (PyModule_AddIntMacro(m, MFD_ALLOW_SEALING)) return -1;
14276#ifdef MFD_HUGETLB
14277 if (PyModule_AddIntMacro(m, MFD_HUGETLB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014278#endif
14279#ifdef MFD_HUGE_SHIFT
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014280 if (PyModule_AddIntMacro(m, MFD_HUGE_SHIFT)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014281#endif
14282#ifdef MFD_HUGE_MASK
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014283 if (PyModule_AddIntMacro(m, MFD_HUGE_MASK)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014284#endif
14285#ifdef MFD_HUGE_64KB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014286 if (PyModule_AddIntMacro(m, MFD_HUGE_64KB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014287#endif
14288#ifdef MFD_HUGE_512KB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014289 if (PyModule_AddIntMacro(m, MFD_HUGE_512KB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014290#endif
14291#ifdef MFD_HUGE_1MB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014292 if (PyModule_AddIntMacro(m, MFD_HUGE_1MB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014293#endif
14294#ifdef MFD_HUGE_2MB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014295 if (PyModule_AddIntMacro(m, MFD_HUGE_2MB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014296#endif
14297#ifdef MFD_HUGE_8MB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014298 if (PyModule_AddIntMacro(m, MFD_HUGE_8MB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014299#endif
14300#ifdef MFD_HUGE_16MB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014301 if (PyModule_AddIntMacro(m, MFD_HUGE_16MB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014302#endif
14303#ifdef MFD_HUGE_32MB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014304 if (PyModule_AddIntMacro(m, MFD_HUGE_32MB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014305#endif
14306#ifdef MFD_HUGE_256MB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014307 if (PyModule_AddIntMacro(m, MFD_HUGE_256MB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014308#endif
14309#ifdef MFD_HUGE_512MB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014310 if (PyModule_AddIntMacro(m, MFD_HUGE_512MB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014311#endif
14312#ifdef MFD_HUGE_1GB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014313 if (PyModule_AddIntMacro(m, MFD_HUGE_1GB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014314#endif
14315#ifdef MFD_HUGE_2GB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014316 if (PyModule_AddIntMacro(m, MFD_HUGE_2GB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014317#endif
14318#ifdef MFD_HUGE_16GB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014319 if (PyModule_AddIntMacro(m, MFD_HUGE_16GB)) return -1;
14320#endif
14321#endif
Victor Stinner9b1f4742016-09-06 16:18:52 -070014322
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +020014323#if defined(__APPLE__)
14324 if (PyModule_AddIntConstant(m, "_COPYFILE_DATA", COPYFILE_DATA)) return -1;
14325#endif
14326
Steve Dower2438cdf2019-03-29 16:37:16 -070014327#ifdef MS_WINDOWS
14328 if (PyModule_AddIntConstant(m, "_LOAD_LIBRARY_SEARCH_DEFAULT_DIRS", LOAD_LIBRARY_SEARCH_DEFAULT_DIRS)) return -1;
14329 if (PyModule_AddIntConstant(m, "_LOAD_LIBRARY_SEARCH_APPLICATION_DIR", LOAD_LIBRARY_SEARCH_APPLICATION_DIR)) return -1;
14330 if (PyModule_AddIntConstant(m, "_LOAD_LIBRARY_SEARCH_SYSTEM32", LOAD_LIBRARY_SEARCH_SYSTEM32)) return -1;
14331 if (PyModule_AddIntConstant(m, "_LOAD_LIBRARY_SEARCH_USER_DIRS", LOAD_LIBRARY_SEARCH_USER_DIRS)) return -1;
14332 if (PyModule_AddIntConstant(m, "_LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR", LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR)) return -1;
14333#endif
14334
Victor Stinner8c62be82010-05-06 00:08:46 +000014335 return 0;
Barry Warsaw4a342091996-12-19 23:50:02 +000014336}
14337
14338
Martin v. Löwis1a214512008-06-11 05:26:20 +000014339static struct PyModuleDef posixmodule = {
Victor Stinner8c62be82010-05-06 00:08:46 +000014340 PyModuleDef_HEAD_INIT,
14341 MODNAME,
14342 posix__doc__,
Eddie Elizondob3966632019-11-05 07:16:14 -080014343 sizeof(_posixstate),
Victor Stinner8c62be82010-05-06 00:08:46 +000014344 posix_methods,
14345 NULL,
Eddie Elizondob3966632019-11-05 07:16:14 -080014346 _posix_traverse,
14347 _posix_clear,
14348 _posix_free,
Martin v. Löwis1a214512008-06-11 05:26:20 +000014349};
14350
14351
Serhiy Storchaka2d06e842015-12-25 19:53:18 +020014352static const char * const have_functions[] = {
Larry Hastings9cf065c2012-06-22 16:30:09 -070014353
14354#ifdef HAVE_FACCESSAT
14355 "HAVE_FACCESSAT",
14356#endif
14357
14358#ifdef HAVE_FCHDIR
14359 "HAVE_FCHDIR",
14360#endif
14361
14362#ifdef HAVE_FCHMOD
14363 "HAVE_FCHMOD",
14364#endif
14365
14366#ifdef HAVE_FCHMODAT
14367 "HAVE_FCHMODAT",
14368#endif
14369
14370#ifdef HAVE_FCHOWN
14371 "HAVE_FCHOWN",
14372#endif
14373
Larry Hastings00964ed2013-08-12 13:49:30 -040014374#ifdef HAVE_FCHOWNAT
14375 "HAVE_FCHOWNAT",
14376#endif
14377
Larry Hastings9cf065c2012-06-22 16:30:09 -070014378#ifdef HAVE_FEXECVE
14379 "HAVE_FEXECVE",
14380#endif
14381
14382#ifdef HAVE_FDOPENDIR
14383 "HAVE_FDOPENDIR",
14384#endif
14385
Georg Brandl306336b2012-06-24 12:55:33 +020014386#ifdef HAVE_FPATHCONF
14387 "HAVE_FPATHCONF",
14388#endif
14389
Larry Hastings9cf065c2012-06-22 16:30:09 -070014390#ifdef HAVE_FSTATAT
14391 "HAVE_FSTATAT",
14392#endif
14393
14394#ifdef HAVE_FSTATVFS
14395 "HAVE_FSTATVFS",
14396#endif
14397
Steve Dowerfe0a41a2015-03-20 19:50:46 -070014398#if defined HAVE_FTRUNCATE || defined MS_WINDOWS
Georg Brandl306336b2012-06-24 12:55:33 +020014399 "HAVE_FTRUNCATE",
14400#endif
14401
Larry Hastings9cf065c2012-06-22 16:30:09 -070014402#ifdef HAVE_FUTIMENS
14403 "HAVE_FUTIMENS",
14404#endif
14405
14406#ifdef HAVE_FUTIMES
14407 "HAVE_FUTIMES",
14408#endif
14409
14410#ifdef HAVE_FUTIMESAT
14411 "HAVE_FUTIMESAT",
14412#endif
14413
14414#ifdef HAVE_LINKAT
14415 "HAVE_LINKAT",
14416#endif
14417
14418#ifdef HAVE_LCHFLAGS
14419 "HAVE_LCHFLAGS",
14420#endif
14421
14422#ifdef HAVE_LCHMOD
14423 "HAVE_LCHMOD",
14424#endif
14425
14426#ifdef HAVE_LCHOWN
14427 "HAVE_LCHOWN",
14428#endif
14429
14430#ifdef HAVE_LSTAT
14431 "HAVE_LSTAT",
14432#endif
14433
14434#ifdef HAVE_LUTIMES
14435 "HAVE_LUTIMES",
14436#endif
14437
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014438#ifdef HAVE_MEMFD_CREATE
14439 "HAVE_MEMFD_CREATE",
14440#endif
14441
Larry Hastings9cf065c2012-06-22 16:30:09 -070014442#ifdef HAVE_MKDIRAT
14443 "HAVE_MKDIRAT",
14444#endif
14445
14446#ifdef HAVE_MKFIFOAT
14447 "HAVE_MKFIFOAT",
14448#endif
14449
14450#ifdef HAVE_MKNODAT
14451 "HAVE_MKNODAT",
14452#endif
14453
14454#ifdef HAVE_OPENAT
14455 "HAVE_OPENAT",
14456#endif
14457
14458#ifdef HAVE_READLINKAT
14459 "HAVE_READLINKAT",
14460#endif
14461
14462#ifdef HAVE_RENAMEAT
14463 "HAVE_RENAMEAT",
14464#endif
14465
14466#ifdef HAVE_SYMLINKAT
14467 "HAVE_SYMLINKAT",
14468#endif
14469
14470#ifdef HAVE_UNLINKAT
14471 "HAVE_UNLINKAT",
14472#endif
14473
14474#ifdef HAVE_UTIMENSAT
14475 "HAVE_UTIMENSAT",
14476#endif
14477
14478#ifdef MS_WINDOWS
14479 "MS_WINDOWS",
14480#endif
14481
14482 NULL
14483};
14484
14485
Mark Hammondfe51c6d2002-08-02 02:27:13 +000014486PyMODINIT_FUNC
Thomas Woutersf3f33dc2000-07-21 06:00:07 +000014487INITFUNC(void)
Guido van Rossumb6775db1994-08-01 11:34:53 +000014488{
Victor Stinner8c62be82010-05-06 00:08:46 +000014489 PyObject *m, *v;
Larry Hastings9cf065c2012-06-22 16:30:09 -070014490 PyObject *list;
Serhiy Storchaka2d06e842015-12-25 19:53:18 +020014491 const char * const *trace;
Tim Peters5aa91602002-01-30 05:46:57 +000014492
Eddie Elizondob3966632019-11-05 07:16:14 -080014493 m = PyState_FindModule(&posixmodule);
14494 if (m != NULL) {
14495 Py_INCREF(m);
14496 return m;
14497 }
14498
Victor Stinner8c62be82010-05-06 00:08:46 +000014499 m = PyModule_Create(&posixmodule);
14500 if (m == NULL)
14501 return NULL;
Tim Peters5aa91602002-01-30 05:46:57 +000014502
Victor Stinner8c62be82010-05-06 00:08:46 +000014503 /* Initialize environ dictionary */
14504 v = convertenviron();
14505 Py_XINCREF(v);
14506 if (v == NULL || PyModule_AddObject(m, "environ", v) != 0)
14507 return NULL;
14508 Py_DECREF(v);
Fred Drakec9680921999-12-13 16:37:25 +000014509
Victor Stinner8c62be82010-05-06 00:08:46 +000014510 if (all_ins(m))
14511 return NULL;
Barry Warsaw4a342091996-12-19 23:50:02 +000014512
Victor Stinner8c62be82010-05-06 00:08:46 +000014513 if (setup_confname_tables(m))
14514 return NULL;
Fred Drakebec628d1999-12-15 18:31:10 +000014515
Victor Stinner8c62be82010-05-06 00:08:46 +000014516 Py_INCREF(PyExc_OSError);
14517 PyModule_AddObject(m, "error", PyExc_OSError);
Fred Drake762e2061999-08-26 17:23:54 +000014518
Victor Stinner623ed612020-01-21 19:25:32 +010014519#ifdef PY_PUTENV_DICT
Eddie Elizondob3966632019-11-05 07:16:14 -080014520 /* Save putenv() parameters as values here, so we can collect them when they
14521 * get re-set with another call for the same key. */
Victor Stinner623ed612020-01-21 19:25:32 +010014522 _posixstate(m)->putenv_dict = PyDict_New();
Guido van Rossumb3d39562000-01-31 18:41:26 +000014523#endif
Guido van Rossum98bf58f2001-10-18 20:34:25 +000014524
Ross Lagerwall7807c352011-03-17 20:20:30 +020014525#if defined(HAVE_WAITID) && !defined(__APPLE__)
Eddie Elizondob3966632019-11-05 07:16:14 -080014526 waitid_result_desc.name = MODNAME ".waitid_result";
14527 PyObject *WaitidResultType = (PyObject *)PyStructSequence_NewType(&waitid_result_desc);
14528 if (WaitidResultType == NULL) {
14529 return NULL;
14530 }
14531 Py_INCREF(WaitidResultType);
14532 PyModule_AddObject(m, "waitid_result", WaitidResultType);
14533 _posixstate(m)->WaitidResultType = WaitidResultType;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014534#endif
14535
Eddie Elizondob3966632019-11-05 07:16:14 -080014536 stat_result_desc.name = "os.stat_result"; /* see issue #19209 */
14537 stat_result_desc.fields[7].name = PyStructSequence_UnnamedField;
14538 stat_result_desc.fields[8].name = PyStructSequence_UnnamedField;
14539 stat_result_desc.fields[9].name = PyStructSequence_UnnamedField;
14540 PyObject *StatResultType = (PyObject *)PyStructSequence_NewType(&stat_result_desc);
14541 if (StatResultType == NULL) {
14542 return NULL;
14543 }
14544 Py_INCREF(StatResultType);
14545 PyModule_AddObject(m, "stat_result", StatResultType);
14546 _posixstate(m)->StatResultType = StatResultType;
14547 structseq_new = ((PyTypeObject *)StatResultType)->tp_new;
14548 ((PyTypeObject *)StatResultType)->tp_new = statresult_new;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000014549
Eddie Elizondob3966632019-11-05 07:16:14 -080014550 statvfs_result_desc.name = "os.statvfs_result"; /* see issue #19209 */
14551 PyObject *StatVFSResultType = (PyObject *)PyStructSequence_NewType(&statvfs_result_desc);
14552 if (StatVFSResultType == NULL) {
14553 return NULL;
14554 }
14555 Py_INCREF(StatVFSResultType);
14556 PyModule_AddObject(m, "statvfs_result", StatVFSResultType);
14557 _posixstate(m)->StatVFSResultType = StatVFSResultType;
Martin v. Löwis05bfe1f2008-12-29 18:21:47 +000014558#ifdef NEED_TICKS_PER_SECOND
14559# if defined(HAVE_SYSCONF) && defined(_SC_CLK_TCK)
Eddie Elizondob3966632019-11-05 07:16:14 -080014560 ticks_per_second = sysconf(_SC_CLK_TCK);
Martin v. Löwis05bfe1f2008-12-29 18:21:47 +000014561# elif defined(HZ)
Eddie Elizondob3966632019-11-05 07:16:14 -080014562 ticks_per_second = HZ;
Martin v. Löwis05bfe1f2008-12-29 18:21:47 +000014563# else
Eddie Elizondob3966632019-11-05 07:16:14 -080014564 ticks_per_second = 60; /* magic fallback value; may be bogus */
Martin v. Löwis05bfe1f2008-12-29 18:21:47 +000014565# endif
14566#endif
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014567
William Orr81574b82018-10-01 22:19:56 -070014568#if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
Eddie Elizondob3966632019-11-05 07:16:14 -080014569 sched_param_desc.name = MODNAME ".sched_param";
14570 PyObject *SchedParamType = (PyObject *)PyStructSequence_NewType(&sched_param_desc);
14571 if (SchedParamType == NULL) {
14572 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +000014573 }
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014574 Py_INCREF(SchedParamType);
Eddie Elizondob3966632019-11-05 07:16:14 -080014575 PyModule_AddObject(m, "sched_param", SchedParamType);
14576 _posixstate(m)->SchedParamType = SchedParamType;
14577 ((PyTypeObject *)SchedParamType)->tp_new = os_sched_param;
Benjamin Petersone3298dd2011-08-02 18:40:46 -050014578#endif
Thomas Wouters477c8d52006-05-27 19:21:47 +000014579
Eddie Elizondob3966632019-11-05 07:16:14 -080014580 /* initialize TerminalSize_info */
14581 PyObject *TerminalSizeType = (PyObject *)PyStructSequence_NewType(&TerminalSize_desc);
14582 if (TerminalSizeType == NULL) {
14583 return NULL;
14584 }
14585 Py_INCREF(TerminalSizeType);
14586 PyModule_AddObject(m, "terminal_size", TerminalSizeType);
14587 _posixstate(m)->TerminalSizeType = TerminalSizeType;
14588
14589 /* initialize scandir types */
14590 PyObject *ScandirIteratorType = PyType_FromSpec(&ScandirIteratorType_spec);
14591 if (ScandirIteratorType == NULL) {
14592 return NULL;
14593 }
14594 _posixstate(m)->ScandirIteratorType = ScandirIteratorType;
14595
14596 PyObject *DirEntryType = PyType_FromSpec(&DirEntryType_spec);
14597 if (DirEntryType == NULL) {
14598 return NULL;
14599 }
14600 Py_INCREF(DirEntryType);
14601 PyModule_AddObject(m, "DirEntry", DirEntryType);
14602 _posixstate(m)->DirEntryType = DirEntryType;
14603
Larry Hastings605a62d2012-06-24 04:33:36 -070014604 times_result_desc.name = MODNAME ".times_result";
Eddie Elizondob3966632019-11-05 07:16:14 -080014605 PyObject *TimesResultType = (PyObject *)PyStructSequence_NewType(&times_result_desc);
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014606 if (TimesResultType == NULL) {
Victor Stinner1c8f0592013-07-22 22:24:54 +020014607 return NULL;
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014608 }
Eddie Elizondob3966632019-11-05 07:16:14 -080014609 Py_INCREF(TimesResultType);
14610 PyModule_AddObject(m, "times_result", TimesResultType);
14611 _posixstate(m)->TimesResultType = TimesResultType;
Larry Hastings605a62d2012-06-24 04:33:36 -070014612
Eddie Elizondob3966632019-11-05 07:16:14 -080014613 PyTypeObject *UnameResultType = PyStructSequence_NewType(&uname_result_desc);
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014614 if (UnameResultType == NULL) {
Victor Stinner1c8f0592013-07-22 22:24:54 +020014615 return NULL;
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014616 }
Eddie Elizondob3966632019-11-05 07:16:14 -080014617 Py_INCREF(UnameResultType);
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014618 PyModule_AddObject(m, "uname_result", (PyObject *)UnameResultType);
Eddie Elizondob3966632019-11-05 07:16:14 -080014619 _posixstate(m)->UnameResultType = (PyObject *)UnameResultType;
Larry Hastings605a62d2012-06-24 04:33:36 -070014620
Thomas Wouters477c8d52006-05-27 19:21:47 +000014621#ifdef __APPLE__
Victor Stinner8c62be82010-05-06 00:08:46 +000014622 /*
14623 * Step 2 of weak-linking support on Mac OS X.
14624 *
14625 * The code below removes functions that are not available on the
14626 * currently active platform.
14627 *
14628 * This block allow one to use a python binary that was build on
Larry Hastings9cf065c2012-06-22 16:30:09 -070014629 * OSX 10.4 on OSX 10.3, without losing access to new APIs on
Victor Stinner8c62be82010-05-06 00:08:46 +000014630 * OSX 10.4.
14631 */
Thomas Wouters477c8d52006-05-27 19:21:47 +000014632#ifdef HAVE_FSTATVFS
Victor Stinner8c62be82010-05-06 00:08:46 +000014633 if (fstatvfs == NULL) {
14634 if (PyObject_DelAttrString(m, "fstatvfs") == -1) {
14635 return NULL;
14636 }
14637 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000014638#endif /* HAVE_FSTATVFS */
14639
14640#ifdef HAVE_STATVFS
Victor Stinner8c62be82010-05-06 00:08:46 +000014641 if (statvfs == NULL) {
14642 if (PyObject_DelAttrString(m, "statvfs") == -1) {
14643 return NULL;
14644 }
14645 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000014646#endif /* HAVE_STATVFS */
14647
14648# ifdef HAVE_LCHOWN
Victor Stinner8c62be82010-05-06 00:08:46 +000014649 if (lchown == NULL) {
14650 if (PyObject_DelAttrString(m, "lchown") == -1) {
14651 return NULL;
14652 }
14653 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000014654#endif /* HAVE_LCHOWN */
14655
14656
14657#endif /* __APPLE__ */
Antoine Pitroubcf2b592012-02-08 23:28:36 +010014658
Eddie Elizondob3966632019-11-05 07:16:14 -080014659 if ((_posixstate(m)->billion = PyLong_FromLong(1000000000)) == NULL)
14660 return NULL;
14661#if defined(HAVE_WAIT3) || defined(HAVE_WAIT4)
14662 _posixstate(m)->struct_rusage = PyUnicode_InternFromString("struct_rusage");
14663 if (_posixstate(m)->struct_rusage == NULL)
14664 return NULL;
14665#endif
14666 _posixstate(m)->st_mode = PyUnicode_InternFromString("st_mode");
14667 if (_posixstate(m)->st_mode == NULL)
Larry Hastings6fe20b32012-04-19 15:07:49 -070014668 return NULL;
14669
Larry Hastings9cf065c2012-06-22 16:30:09 -070014670 /* suppress "function not used" warnings */
14671 {
14672 int ignored;
14673 fd_specified("", -1);
14674 follow_symlinks_specified("", 1);
14675 dir_fd_and_follow_symlinks_invalid("chmod", DEFAULT_DIR_FD, 1);
14676 dir_fd_converter(Py_None, &ignored);
14677 dir_fd_unavailable(Py_None, &ignored);
14678 }
14679
14680 /*
14681 * provide list of locally available functions
14682 * so os.py can populate support_* lists
14683 */
14684 list = PyList_New(0);
14685 if (!list)
14686 return NULL;
14687 for (trace = have_functions; *trace; trace++) {
14688 PyObject *unicode = PyUnicode_DecodeASCII(*trace, strlen(*trace), NULL);
14689 if (!unicode)
14690 return NULL;
14691 if (PyList_Append(list, unicode))
14692 return NULL;
14693 Py_DECREF(unicode);
14694 }
14695 PyModule_AddObject(m, "_have_functions", list);
Ned Deilyeb3be662016-08-15 14:40:38 -040014696
Victor Stinner8c62be82010-05-06 00:08:46 +000014697 return m;
Guido van Rossumb6775db1994-08-01 11:34:53 +000014698}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000014699
14700#ifdef __cplusplus
14701}
14702#endif