blob: 5134ed7bdf44915f77ca3b4580c7e67268c782ff [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
Guido van Rossumb6775db1994-08-01 11:34:53 +000088
Thomas Wouters0e3f5912006-08-11 14:57:12 +000089#ifdef HAVE_SIGNAL_H
Guido van Rossuma376cc51996-12-05 23:43:35 +000090#include <signal.h>
Thomas Wouters0e3f5912006-08-11 14:57:12 +000091#endif
Guido van Rossuma376cc51996-12-05 23:43:35 +000092
Guido van Rossumb6775db1994-08-01 11:34:53 +000093#ifdef HAVE_FCNTL_H
94#include <fcntl.h>
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +000095#endif /* HAVE_FCNTL_H */
Guido van Rossumb6775db1994-08-01 11:34:53 +000096
Guido van Rossuma6535fd2001-10-18 19:44:10 +000097#ifdef HAVE_GRP_H
98#include <grp.h>
99#endif
100
Barry Warsaw5676bd12003-01-07 20:57:09 +0000101#ifdef HAVE_SYSEXITS_H
102#include <sysexits.h>
103#endif /* HAVE_SYSEXITS_H */
104
Anthony Baxter8a560de2004-10-13 15:30:56 +0000105#ifdef HAVE_SYS_LOADAVG_H
106#include <sys/loadavg.h>
107#endif
108
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +0000109#ifdef HAVE_SYS_SENDFILE_H
110#include <sys/sendfile.h>
111#endif
112
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +0200113#if defined(__APPLE__)
114#include <copyfile.h>
115#endif
116
Benjamin Peterson94b580d2011-08-02 17:30:04 -0500117#ifdef HAVE_SCHED_H
118#include <sched.h>
119#endif
120
Pablo Galindoaac4d032019-05-31 19:39:47 +0100121#ifdef HAVE_COPY_FILE_RANGE
122#include <unistd.h>
123#endif
124
Benjamin Peterson2dbda072012-03-16 10:12:55 -0500125#if !defined(CPU_ALLOC) && defined(HAVE_SCHED_SETAFFINITY)
Benjamin Peterson7b51b8d2012-03-14 22:28:25 -0500126#undef HAVE_SCHED_SETAFFINITY
127#endif
128
doko@ubuntu.com4a173bc2014-04-17 19:47:16 +0200129#if defined(HAVE_SYS_XATTR_H) && defined(__GLIBC__) && !defined(__FreeBSD_kernel__) && !defined(__GNU__)
Benjamin Peterson9428d532011-09-14 11:45:52 -0400130#define USE_XATTRS
131#endif
132
133#ifdef USE_XATTRS
Benjamin Petersonb77fe172011-09-13 17:20:47 -0400134#include <sys/xattr.h>
Benjamin Peterson799bd802011-08-31 22:15:17 -0400135#endif
136
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +0000137#if defined(__FreeBSD__) || defined(__DragonFly__) || defined(__APPLE__)
138#ifdef HAVE_SYS_SOCKET_H
139#include <sys/socket.h>
140#endif
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +0000141#endif
142
Victor Stinner8b905bd2011-10-25 13:34:04 +0200143#ifdef HAVE_DLFCN_H
144#include <dlfcn.h>
145#endif
146
Charles-Francois Natali44feda32013-05-20 14:40:46 +0200147#ifdef __hpux
148#include <sys/mpctl.h>
149#endif
150
151#if defined(__DragonFly__) || \
152 defined(__OpenBSD__) || \
153 defined(__FreeBSD__) || \
154 defined(__NetBSD__) || \
155 defined(__APPLE__)
156#include <sys/sysctl.h>
157#endif
158
Victor Stinner9b1f4742016-09-06 16:18:52 -0700159#ifdef HAVE_LINUX_RANDOM_H
160# include <linux/random.h>
161#endif
162#ifdef HAVE_GETRANDOM_SYSCALL
163# include <sys/syscall.h>
164#endif
165
Antoine Pitroubcf2b592012-02-08 23:28:36 +0100166#if defined(MS_WINDOWS)
167# define TERMSIZE_USE_CONIO
168#elif defined(HAVE_SYS_IOCTL_H)
169# include <sys/ioctl.h>
170# if defined(HAVE_TERMIOS_H)
171# include <termios.h>
172# endif
173# if defined(TIOCGWINSZ)
174# define TERMSIZE_USE_IOCTL
175# endif
176#endif /* MS_WINDOWS */
177
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000178/* Various compilers have only certain posix functions */
Martin v. Löwis4f1cd8b2001-07-26 13:41:06 +0000179/* XXX Gosh I wish these were all moved into pyconfig.h */
Victor Stinner8c62be82010-05-06 00:08:46 +0000180#if defined(__WATCOMC__) && !defined(__QNX__) /* Watcom compiler */
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000181#define HAVE_OPENDIR 1
Victor Stinner8c62be82010-05-06 00:08:46 +0000182#define HAVE_SYSTEM 1
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000183#include <process.h>
184#else
Victor Stinner8c62be82010-05-06 00:08:46 +0000185#ifdef _MSC_VER /* Microsoft compiler */
Amaury Forgeot d'Arc4b6fdf32010-09-07 21:31:17 +0000186#define HAVE_GETPPID 1
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +0000187#define HAVE_GETLOGIN 1
Victor Stinner8c62be82010-05-06 00:08:46 +0000188#define HAVE_SPAWNV 1
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000189#define HAVE_EXECV 1
Steve Dowercc16be82016-09-08 10:35:16 -0700190#define HAVE_WSPAWNV 1
191#define HAVE_WEXECV 1
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000192#define HAVE_PIPE 1
Victor Stinner8c62be82010-05-06 00:08:46 +0000193#define HAVE_SYSTEM 1
194#define HAVE_CWAIT 1
195#define HAVE_FSYNC 1
Tim Peters11b23062003-04-23 02:39:17 +0000196#define fsync _commit
Andrew MacIntyre6c73af22002-03-03 03:07:07 +0000197#else
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000198/* Unix functions that the configure script doesn't check for */
pxinwrf2d7ac72019-05-21 18:46:37 +0800199#ifndef __VXWORKS__
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000200#define HAVE_EXECV 1
201#define HAVE_FORK 1
Victor Stinner8c62be82010-05-06 00:08:46 +0000202#if defined(__USLC__) && defined(__SCO_VERSION__) /* SCO UDK Compiler */
Guido van Rossum2242f2f2001-04-11 20:58:20 +0000203#define HAVE_FORK1 1
204#endif
pxinwrf2d7ac72019-05-21 18:46:37 +0800205#endif
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000206#define HAVE_GETEGID 1
207#define HAVE_GETEUID 1
208#define HAVE_GETGID 1
209#define HAVE_GETPPID 1
210#define HAVE_GETUID 1
211#define HAVE_KILL 1
212#define HAVE_OPENDIR 1
213#define HAVE_PIPE 1
Victor Stinner8c62be82010-05-06 00:08:46 +0000214#define HAVE_SYSTEM 1
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000215#define HAVE_WAIT 1
Victor Stinner8c62be82010-05-06 00:08:46 +0000216#define HAVE_TTYNAME 1
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000217#endif /* _MSC_VER */
Guido van Rossumc5a0f531997-12-02 20:36:02 +0000218#endif /* ! __WATCOMC__ || __QNX__ */
Guido van Rossumad0ee831995-03-01 10:34:45 +0000219
Victor Stinnera2f7c002012-02-08 03:36:25 +0100220
Larry Hastings61272b72014-01-07 12:41:53 -0800221/*[clinic input]
Larry Hastings2f936352014-08-05 14:04:04 +1000222# one of the few times we lie about this name!
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800223module os
Larry Hastings61272b72014-01-07 12:41:53 -0800224[clinic start generated code]*/
Larry Hastings2f936352014-08-05 14:04:04 +1000225/*[clinic end generated code: output=da39a3ee5e6b4b0d input=94a0f0f978acae17]*/
Victor Stinnera2f7c002012-02-08 03:36:25 +0100226
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000227#ifndef _MSC_VER
Guido van Rossum36bc6801995-06-14 22:54:23 +0000228
Martin v. Löwis8eb92a02002-09-19 08:03:21 +0000229#if defined(__sgi)&&_COMPILER_VERSION>=700
230/* declare ctermid_r if compiling with MIPSPro 7.x in ANSI C mode
231 (default) */
232extern char *ctermid_r(char *);
233#endif
234
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000235#endif /* !_MSC_VER */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000236
pxinwrf2d7ac72019-05-21 18:46:37 +0800237#if defined(__VXWORKS__)
238#include <vxCpuLib.h>
239#include <rtpLib.h>
240#include <wait.h>
241#include <taskLib.h>
242#ifndef _P_WAIT
243#define _P_WAIT 0
244#define _P_NOWAIT 1
245#define _P_NOWAITO 1
246#endif
247#endif /* __VXWORKS__ */
248
Pablo Galindo6c6ddf92018-01-29 01:56:10 +0000249#ifdef HAVE_POSIX_SPAWN
250#include <spawn.h>
251#endif
252
Guido van Rossumb6775db1994-08-01 11:34:53 +0000253#ifdef HAVE_UTIME_H
254#include <utime.h>
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +0000255#endif /* HAVE_UTIME_H */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000256
Guido van Rossum14ed0b21994-09-29 09:50:09 +0000257#ifdef HAVE_SYS_UTIME_H
258#include <sys/utime.h>
259#define HAVE_UTIME_H /* pretend we do for the rest of this file */
260#endif /* HAVE_SYS_UTIME_H */
261
Guido van Rossumb6775db1994-08-01 11:34:53 +0000262#ifdef HAVE_SYS_TIMES_H
263#include <sys/times.h>
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +0000264#endif /* HAVE_SYS_TIMES_H */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000265
266#ifdef HAVE_SYS_PARAM_H
267#include <sys/param.h>
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +0000268#endif /* HAVE_SYS_PARAM_H */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000269
270#ifdef HAVE_SYS_UTSNAME_H
271#include <sys/utsname.h>
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +0000272#endif /* HAVE_SYS_UTSNAME_H */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000273
Guido van Rossum3bbc62e1995-01-02 19:30:30 +0000274#ifdef HAVE_DIRENT_H
Guido van Rossumb6775db1994-08-01 11:34:53 +0000275#include <dirent.h>
Guido van Rossum3bbc62e1995-01-02 19:30:30 +0000276#define NAMLEN(dirent) strlen((dirent)->d_name)
277#else
Guido van Rossumc5a0f531997-12-02 20:36:02 +0000278#if defined(__WATCOMC__) && !defined(__QNX__)
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000279#include <direct.h>
280#define NAMLEN(dirent) strlen((dirent)->d_name)
281#else
Guido van Rossumb6775db1994-08-01 11:34:53 +0000282#define dirent direct
Guido van Rossum3bbc62e1995-01-02 19:30:30 +0000283#define NAMLEN(dirent) (dirent)->d_namlen
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000284#endif
Guido van Rossum3bbc62e1995-01-02 19:30:30 +0000285#ifdef HAVE_SYS_NDIR_H
Guido van Rossumb6775db1994-08-01 11:34:53 +0000286#include <sys/ndir.h>
Guido van Rossum3bbc62e1995-01-02 19:30:30 +0000287#endif
288#ifdef HAVE_SYS_DIR_H
Guido van Rossumb6775db1994-08-01 11:34:53 +0000289#include <sys/dir.h>
Guido van Rossum3bbc62e1995-01-02 19:30:30 +0000290#endif
291#ifdef HAVE_NDIR_H
Guido van Rossumb6775db1994-08-01 11:34:53 +0000292#include <ndir.h>
Guido van Rossum3bbc62e1995-01-02 19:30:30 +0000293#endif
294#endif
Guido van Rossumb6775db1994-08-01 11:34:53 +0000295
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000296#ifdef _MSC_VER
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000297#ifdef HAVE_DIRECT_H
Guido van Rossumb6775db1994-08-01 11:34:53 +0000298#include <direct.h>
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000299#endif
300#ifdef HAVE_IO_H
Guido van Rossumb6775db1994-08-01 11:34:53 +0000301#include <io.h>
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000302#endif
303#ifdef HAVE_PROCESS_H
Guido van Rossumb6775db1994-08-01 11:34:53 +0000304#include <process.h>
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000305#endif
Raymond Hettinger0291c9f2010-08-01 21:10:35 +0000306#ifndef IO_REPARSE_TAG_SYMLINK
Amaury Forgeot d'Arc844807e2010-08-16 22:16:51 +0000307#define IO_REPARSE_TAG_SYMLINK (0xA000000CL)
Raymond Hettinger0291c9f2010-08-01 21:10:35 +0000308#endif
Tim Golden0321cf22014-05-05 19:46:17 +0100309#ifndef IO_REPARSE_TAG_MOUNT_POINT
310#define IO_REPARSE_TAG_MOUNT_POINT (0xA0000003L)
311#endif
Tim Petersbc2e10e2002-03-03 23:17:02 +0000312#include "osdefs.h"
Kristján Valur Jónssonf64e6512009-04-13 10:16:14 +0000313#include <malloc.h>
Guido van Rossumb6775db1994-08-01 11:34:53 +0000314#include <windows.h>
Victor Stinner8c62be82010-05-06 00:08:46 +0000315#include <shellapi.h> /* for ShellExecute() */
Brian Curtine8e4b3b2010-09-23 20:04:14 +0000316#include <lmcons.h> /* for UNLEN */
Brian Curtin52173d42010-12-02 18:29:18 +0000317#define HAVE_SYMLINK
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000318#endif /* _MSC_VER */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000319
Tim Petersbc2e10e2002-03-03 23:17:02 +0000320#ifndef MAXPATHLEN
Thomas Wouters477c8d52006-05-27 19:21:47 +0000321#if defined(PATH_MAX) && PATH_MAX > 1024
322#define MAXPATHLEN PATH_MAX
323#else
Tim Petersbc2e10e2002-03-03 23:17:02 +0000324#define MAXPATHLEN 1024
Thomas Wouters477c8d52006-05-27 19:21:47 +0000325#endif
Tim Petersbc2e10e2002-03-03 23:17:02 +0000326#endif /* MAXPATHLEN */
327
Guido van Rossum54ecc3d1999-01-27 17:53:11 +0000328#ifdef UNION_WAIT
329/* Emulate some macros on systems that have a union instead of macros */
330
331#ifndef WIFEXITED
332#define WIFEXITED(u_wait) (!(u_wait).w_termsig && !(u_wait).w_coredump)
333#endif
334
335#ifndef WEXITSTATUS
336#define WEXITSTATUS(u_wait) (WIFEXITED(u_wait)?((u_wait).w_retcode):-1)
337#endif
338
339#ifndef WTERMSIG
340#define WTERMSIG(u_wait) ((u_wait).w_termsig)
341#endif
342
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000343#define WAIT_TYPE union wait
344#define WAIT_STATUS_INT(s) (s.w_status)
345
346#else /* !UNION_WAIT */
347#define WAIT_TYPE int
348#define WAIT_STATUS_INT(s) (s)
Guido van Rossum54ecc3d1999-01-27 17:53:11 +0000349#endif /* UNION_WAIT */
350
Greg Wardb48bc172000-03-01 21:51:56 +0000351/* Don't use the "_r" form if we don't need it (also, won't have a
352 prototype for it, at least on Solaris -- maybe others as well?). */
Antoine Pitroua6a4dc82017-09-07 18:56:24 +0200353#if defined(HAVE_CTERMID_R)
Greg Wardb48bc172000-03-01 21:51:56 +0000354#define USE_CTERMID_R
355#endif
356
Fred Drake699f3522000-06-29 21:12:41 +0000357/* choose the appropriate stat and fstat functions and return structs */
Guido van Rossum64529cd2000-06-30 22:45:12 +0000358#undef STAT
Antoine Pitroue47e0932011-01-19 15:21:35 +0000359#undef FSTAT
360#undef STRUCT_STAT
Victor Stinner14b9b112013-06-25 00:37:25 +0200361#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +0000362# define STAT win32_stat
Larry Hastings9cf065c2012-06-22 16:30:09 -0700363# define LSTAT win32_lstat
Victor Stinnere134a7f2015-03-30 10:09:31 +0200364# define FSTAT _Py_fstat_noraise
Steve Dowerf2f373f2015-02-21 08:44:05 -0800365# define STRUCT_STAT struct _Py_stat_struct
Fred Drake699f3522000-06-29 21:12:41 +0000366#else
Victor Stinner8c62be82010-05-06 00:08:46 +0000367# define STAT stat
Larry Hastings9cf065c2012-06-22 16:30:09 -0700368# define LSTAT lstat
Victor Stinner8c62be82010-05-06 00:08:46 +0000369# define FSTAT fstat
370# define STRUCT_STAT struct stat
Fred Drake699f3522000-06-29 21:12:41 +0000371#endif
372
Tim Peters11b23062003-04-23 02:39:17 +0000373#if defined(MAJOR_IN_MKDEV)
Martin v. Löwisdbe3f762002-10-10 14:27:30 +0000374#include <sys/mkdev.h>
375#else
376#if defined(MAJOR_IN_SYSMACROS)
377#include <sys/sysmacros.h>
378#endif
Neal Norwitz3d949422002-04-20 13:46:43 +0000379#if defined(HAVE_MKNOD) && defined(HAVE_SYS_MKDEV_H)
380#include <sys/mkdev.h>
381#endif
Martin v. Löwisdbe3f762002-10-10 14:27:30 +0000382#endif
Fred Drake699f3522000-06-29 21:12:41 +0000383
Serhiy Storchaka06a13f82015-02-22 21:34:54 +0200384#ifdef MS_WINDOWS
Victor Stinner6036e442015-03-08 01:58:04 +0100385#define INITFUNC PyInit_nt
386#define MODNAME "nt"
387#else
388#define INITFUNC PyInit_posix
389#define MODNAME "posix"
390#endif
391
jcea6c51d512018-01-28 14:00:08 +0100392#if defined(__sun)
393/* Something to implement in autoconf, not present in autoconf 2.69 */
394#define HAVE_STRUCT_STAT_ST_FSTYPE 1
395#endif
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200396
Zackery Spytz43fdbd22019-05-29 13:57:07 -0600397/* memfd_create is either defined in sys/mman.h or sys/memfd.h
398 * linux/memfd.h defines additional flags
399 */
400#ifdef HAVE_SYS_MMAN_H
401#include <sys/mman.h>
402#endif
403#ifdef HAVE_SYS_MEMFD_H
404#include <sys/memfd.h>
405#endif
406#ifdef HAVE_LINUX_MEMFD_H
407#include <linux/memfd.h>
408#endif
409
Gregory P. Smith1d300ce2018-12-30 21:13:02 -0800410#ifdef _Py_MEMORY_SANITIZER
411# include <sanitizer/msan_interface.h>
412#endif
413
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200414#ifdef HAVE_FORK
415static void
416run_at_forkers(PyObject *lst, int reverse)
417{
418 Py_ssize_t i;
419 PyObject *cpy;
420
421 if (lst != NULL) {
422 assert(PyList_CheckExact(lst));
423
424 /* Use a list copy in case register_at_fork() is called from
425 * one of the callbacks.
426 */
427 cpy = PyList_GetSlice(lst, 0, PyList_GET_SIZE(lst));
428 if (cpy == NULL)
429 PyErr_WriteUnraisable(lst);
430 else {
431 if (reverse)
432 PyList_Reverse(cpy);
433 for (i = 0; i < PyList_GET_SIZE(cpy); i++) {
434 PyObject *func, *res;
435 func = PyList_GET_ITEM(cpy, i);
436 res = PyObject_CallObject(func, NULL);
437 if (res == NULL)
438 PyErr_WriteUnraisable(func);
439 else
440 Py_DECREF(res);
441 }
442 Py_DECREF(cpy);
443 }
444 }
445}
446
447void
448PyOS_BeforeFork(void)
449{
Victor Stinnercaba55b2018-08-03 15:33:52 +0200450 run_at_forkers(_PyInterpreterState_Get()->before_forkers, 1);
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200451
452 _PyImport_AcquireLock();
453}
454
455void
456PyOS_AfterFork_Parent(void)
457{
458 if (_PyImport_ReleaseLock() <= 0)
459 Py_FatalError("failed releasing import lock after fork");
460
Victor Stinnercaba55b2018-08-03 15:33:52 +0200461 run_at_forkers(_PyInterpreterState_Get()->after_forkers_parent, 0);
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200462}
463
464void
465PyOS_AfterFork_Child(void)
466{
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200467 _PyRuntimeState *runtime = &_PyRuntime;
468 _PyGILState_Reinit(runtime);
Victor Stinnerd5d9e812019-05-13 12:35:37 +0200469 _PyEval_ReInitThreads(runtime);
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200470 _PyImport_ReInitLock();
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200471 _PySignal_AfterFork();
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200472 _PyRuntimeState_ReInitThreads(runtime);
Victor Stinnerb49858b2019-05-24 15:20:23 +0200473 _PyInterpreterState_DeleteExceptMain(runtime);
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200474
Victor Stinnercaba55b2018-08-03 15:33:52 +0200475 run_at_forkers(_PyInterpreterState_Get()->after_forkers_child, 0);
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200476}
477
478static int
479register_at_forker(PyObject **lst, PyObject *func)
480{
Gregory P. Smith163468a2017-05-29 10:03:41 -0700481 if (func == NULL) /* nothing to register? do nothing. */
482 return 0;
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200483 if (*lst == NULL) {
484 *lst = PyList_New(0);
485 if (*lst == NULL)
486 return -1;
487 }
488 return PyList_Append(*lst, func);
489}
490#endif
491
492/* Legacy wrapper */
493void
494PyOS_AfterFork(void)
495{
496#ifdef HAVE_FORK
497 PyOS_AfterFork_Child();
498#endif
499}
500
501
Victor Stinner6036e442015-03-08 01:58:04 +0100502#ifdef MS_WINDOWS
Serhiy Storchaka06a13f82015-02-22 21:34:54 +0200503/* defined in fileutils.c */
Benjamin Petersone5024512018-09-12 12:06:42 -0700504void _Py_time_t_to_FILE_TIME(time_t, int, FILETIME *);
505void _Py_attribute_data_to_stat(BY_HANDLE_FILE_INFORMATION *,
Serhiy Storchaka06a13f82015-02-22 21:34:54 +0200506 ULONG, struct _Py_stat_struct *);
507#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -0700508
Larry Hastings9cf065c2012-06-22 16:30:09 -0700509
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200510#ifndef MS_WINDOWS
511PyObject *
512_PyLong_FromUid(uid_t uid)
513{
514 if (uid == (uid_t)-1)
515 return PyLong_FromLong(-1);
516 return PyLong_FromUnsignedLong(uid);
517}
518
519PyObject *
520_PyLong_FromGid(gid_t gid)
521{
522 if (gid == (gid_t)-1)
523 return PyLong_FromLong(-1);
524 return PyLong_FromUnsignedLong(gid);
525}
526
527int
528_Py_Uid_Converter(PyObject *obj, void *p)
529{
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700530 uid_t uid;
531 PyObject *index;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200532 int overflow;
Serhiy Storchakab4621892013-02-10 23:28:02 +0200533 long result;
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700534 unsigned long uresult;
535
536 index = PyNumber_Index(obj);
537 if (index == NULL) {
538 PyErr_Format(PyExc_TypeError,
539 "uid should be integer, not %.200s",
540 Py_TYPE(obj)->tp_name);
Serhiy Storchakab4621892013-02-10 23:28:02 +0200541 return 0;
542 }
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700543
544 /*
545 * Handling uid_t is complicated for two reasons:
546 * * Although uid_t is (always?) unsigned, it still
547 * accepts -1.
548 * * We don't know its size in advance--it may be
549 * bigger than an int, or it may be smaller than
550 * a long.
551 *
552 * So a bit of defensive programming is in order.
553 * Start with interpreting the value passed
554 * in as a signed long and see if it works.
555 */
556
557 result = PyLong_AsLongAndOverflow(index, &overflow);
558
559 if (!overflow) {
560 uid = (uid_t)result;
561
562 if (result == -1) {
563 if (PyErr_Occurred())
564 goto fail;
565 /* It's a legitimate -1, we're done. */
566 goto success;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200567 }
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700568
569 /* Any other negative number is disallowed. */
570 if (result < 0)
571 goto underflow;
572
573 /* Ensure the value wasn't truncated. */
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200574 if (sizeof(uid_t) < sizeof(long) &&
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700575 (long)uid != result)
576 goto underflow;
577 goto success;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200578 }
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700579
580 if (overflow < 0)
581 goto underflow;
582
583 /*
584 * Okay, the value overflowed a signed long. If it
585 * fits in an *unsigned* long, it may still be okay,
586 * as uid_t may be unsigned long on this platform.
587 */
588 uresult = PyLong_AsUnsignedLong(index);
589 if (PyErr_Occurred()) {
590 if (PyErr_ExceptionMatches(PyExc_OverflowError))
591 goto overflow;
592 goto fail;
593 }
594
595 uid = (uid_t)uresult;
596
597 /*
598 * If uid == (uid_t)-1, the user actually passed in ULONG_MAX,
599 * but this value would get interpreted as (uid_t)-1 by chown
600 * and its siblings. That's not what the user meant! So we
601 * throw an overflow exception instead. (We already
Tim Golden23005082013-10-25 11:22:37 +0100602 * handled a real -1 with PyLong_AsLongAndOverflow() above.)
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700603 */
604 if (uid == (uid_t)-1)
605 goto overflow;
606
607 /* Ensure the value wasn't truncated. */
608 if (sizeof(uid_t) < sizeof(long) &&
609 (unsigned long)uid != uresult)
610 goto overflow;
611 /* fallthrough */
612
613success:
614 Py_DECREF(index);
615 *(uid_t *)p = uid;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200616 return 1;
617
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700618underflow:
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200619 PyErr_SetString(PyExc_OverflowError,
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700620 "uid is less than minimum");
621 goto fail;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200622
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700623overflow:
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200624 PyErr_SetString(PyExc_OverflowError,
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700625 "uid is greater than maximum");
626 /* fallthrough */
627
628fail:
629 Py_DECREF(index);
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200630 return 0;
631}
632
633int
634_Py_Gid_Converter(PyObject *obj, void *p)
635{
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700636 gid_t gid;
637 PyObject *index;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200638 int overflow;
Serhiy Storchakab4621892013-02-10 23:28:02 +0200639 long result;
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700640 unsigned long uresult;
641
642 index = PyNumber_Index(obj);
643 if (index == NULL) {
644 PyErr_Format(PyExc_TypeError,
645 "gid should be integer, not %.200s",
646 Py_TYPE(obj)->tp_name);
Serhiy Storchakab4621892013-02-10 23:28:02 +0200647 return 0;
648 }
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700649
650 /*
651 * Handling gid_t is complicated for two reasons:
652 * * Although gid_t is (always?) unsigned, it still
653 * accepts -1.
654 * * We don't know its size in advance--it may be
655 * bigger than an int, or it may be smaller than
656 * a long.
657 *
658 * So a bit of defensive programming is in order.
659 * Start with interpreting the value passed
660 * in as a signed long and see if it works.
661 */
662
663 result = PyLong_AsLongAndOverflow(index, &overflow);
664
665 if (!overflow) {
666 gid = (gid_t)result;
667
668 if (result == -1) {
669 if (PyErr_Occurred())
670 goto fail;
671 /* It's a legitimate -1, we're done. */
672 goto success;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200673 }
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700674
675 /* Any other negative number is disallowed. */
676 if (result < 0) {
677 goto underflow;
678 }
679
680 /* Ensure the value wasn't truncated. */
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200681 if (sizeof(gid_t) < sizeof(long) &&
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700682 (long)gid != result)
683 goto underflow;
684 goto success;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200685 }
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700686
687 if (overflow < 0)
688 goto underflow;
689
690 /*
691 * Okay, the value overflowed a signed long. If it
692 * fits in an *unsigned* long, it may still be okay,
693 * as gid_t may be unsigned long on this platform.
694 */
695 uresult = PyLong_AsUnsignedLong(index);
696 if (PyErr_Occurred()) {
697 if (PyErr_ExceptionMatches(PyExc_OverflowError))
698 goto overflow;
699 goto fail;
700 }
701
702 gid = (gid_t)uresult;
703
704 /*
705 * If gid == (gid_t)-1, the user actually passed in ULONG_MAX,
706 * but this value would get interpreted as (gid_t)-1 by chown
707 * and its siblings. That's not what the user meant! So we
708 * throw an overflow exception instead. (We already
Tim Golden23005082013-10-25 11:22:37 +0100709 * handled a real -1 with PyLong_AsLongAndOverflow() above.)
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700710 */
711 if (gid == (gid_t)-1)
712 goto overflow;
713
714 /* Ensure the value wasn't truncated. */
715 if (sizeof(gid_t) < sizeof(long) &&
716 (unsigned long)gid != uresult)
717 goto overflow;
718 /* fallthrough */
719
720success:
721 Py_DECREF(index);
722 *(gid_t *)p = gid;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200723 return 1;
724
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700725underflow:
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200726 PyErr_SetString(PyExc_OverflowError,
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700727 "gid is less than minimum");
728 goto fail;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200729
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700730overflow:
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200731 PyErr_SetString(PyExc_OverflowError,
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700732 "gid is greater than maximum");
733 /* fallthrough */
734
735fail:
736 Py_DECREF(index);
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200737 return 0;
738}
739#endif /* MS_WINDOWS */
740
741
Benjamin Petersoned4aa832016-09-05 17:44:18 -0700742#define _PyLong_FromDev PyLong_FromLongLong
Gregory P. Smith702dada2015-01-28 16:07:52 -0800743
744
Serhiy Storchakab2653b32015-01-18 11:12:11 +0200745#if defined(HAVE_MKNOD) && defined(HAVE_MAKEDEV)
746static int
747_Py_Dev_Converter(PyObject *obj, void *p)
748{
Serhiy Storchakab2653b32015-01-18 11:12:11 +0200749 *((dev_t *)p) = PyLong_AsUnsignedLongLong(obj);
Serhiy Storchakab2653b32015-01-18 11:12:11 +0200750 if (PyErr_Occurred())
751 return 0;
752 return 1;
753}
Gregory P. Smith702dada2015-01-28 16:07:52 -0800754#endif /* HAVE_MKNOD && HAVE_MAKEDEV */
Serhiy Storchakab2653b32015-01-18 11:12:11 +0200755
756
Larry Hastings9cf065c2012-06-22 16:30:09 -0700757#ifdef AT_FDCWD
Trent Nelson9a461052012-09-18 21:50:06 -0400758/*
759 * Why the (int) cast? Solaris 10 defines AT_FDCWD as 0xffd19553 (-3041965);
760 * without the int cast, the value gets interpreted as uint (4291925331),
761 * which doesn't play nicely with all the initializer lines in this file that
762 * look like this:
763 * int dir_fd = DEFAULT_DIR_FD;
764 */
765#define DEFAULT_DIR_FD (int)AT_FDCWD
Larry Hastings9cf065c2012-06-22 16:30:09 -0700766#else
767#define DEFAULT_DIR_FD (-100)
768#endif
769
770static int
Serhiy Storchaka819399b2016-04-06 22:17:52 +0300771_fd_converter(PyObject *o, int *p)
Serhiy Storchakaa2ad5c32013-01-07 23:13:46 +0200772{
773 int overflow;
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700774 long long_value;
775
776 PyObject *index = PyNumber_Index(o);
777 if (index == NULL) {
Larry Hastings9cf065c2012-06-22 16:30:09 -0700778 return 0;
779 }
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700780
Serhiy Storchaka819399b2016-04-06 22:17:52 +0300781 assert(PyLong_Check(index));
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700782 long_value = PyLong_AsLongAndOverflow(index, &overflow);
783 Py_DECREF(index);
Serhiy Storchaka819399b2016-04-06 22:17:52 +0300784 assert(!PyErr_Occurred());
Serhiy Storchakaa2ad5c32013-01-07 23:13:46 +0200785 if (overflow > 0 || long_value > INT_MAX) {
Larry Hastings9cf065c2012-06-22 16:30:09 -0700786 PyErr_SetString(PyExc_OverflowError,
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700787 "fd is greater than maximum");
Larry Hastings9cf065c2012-06-22 16:30:09 -0700788 return 0;
789 }
Serhiy Storchakaa2ad5c32013-01-07 23:13:46 +0200790 if (overflow < 0 || long_value < INT_MIN) {
Larry Hastings9cf065c2012-06-22 16:30:09 -0700791 PyErr_SetString(PyExc_OverflowError,
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700792 "fd is less than minimum");
Larry Hastings9cf065c2012-06-22 16:30:09 -0700793 return 0;
794 }
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700795
Larry Hastings9cf065c2012-06-22 16:30:09 -0700796 *p = (int)long_value;
797 return 1;
798}
799
800static int
Serhiy Storchakaa2ad5c32013-01-07 23:13:46 +0200801dir_fd_converter(PyObject *o, void *p)
802{
803 if (o == Py_None) {
804 *(int *)p = DEFAULT_DIR_FD;
805 return 1;
806 }
Serhiy Storchaka819399b2016-04-06 22:17:52 +0300807 else if (PyIndex_Check(o)) {
808 return _fd_converter(o, (int *)p);
809 }
810 else {
811 PyErr_Format(PyExc_TypeError,
812 "argument should be integer or None, not %.200s",
813 Py_TYPE(o)->tp_name);
814 return 0;
815 }
Larry Hastings9cf065c2012-06-22 16:30:09 -0700816}
817
818
Larry Hastings9cf065c2012-06-22 16:30:09 -0700819/*
820 * A PyArg_ParseTuple "converter" function
821 * that handles filesystem paths in the manner
822 * preferred by the os module.
823 *
824 * path_converter accepts (Unicode) strings and their
825 * subclasses, and bytes and their subclasses. What
826 * it does with the argument depends on the platform:
827 *
828 * * On Windows, if we get a (Unicode) string we
829 * extract the wchar_t * and return it; if we get
Steve Dowercc16be82016-09-08 10:35:16 -0700830 * bytes we decode to wchar_t * and return that.
Larry Hastings9cf065c2012-06-22 16:30:09 -0700831 *
832 * * On all other platforms, strings are encoded
833 * to bytes using PyUnicode_FSConverter, then we
834 * extract the char * from the bytes object and
835 * return that.
836 *
837 * path_converter also optionally accepts signed
838 * integers (representing open file descriptors) instead
839 * of path strings.
840 *
841 * Input fields:
842 * path.nullable
843 * If nonzero, the path is permitted to be None.
844 * path.allow_fd
845 * If nonzero, the path is permitted to be a file handle
846 * (a signed int) instead of a string.
847 * path.function_name
848 * If non-NULL, path_converter will use that as the name
849 * of the function in error messages.
Larry Hastings31826802013-10-19 00:09:25 -0700850 * (If path.function_name is NULL it omits the function name.)
Larry Hastings9cf065c2012-06-22 16:30:09 -0700851 * path.argument_name
852 * If non-NULL, path_converter will use that as the name
853 * of the parameter in error messages.
854 * (If path.argument_name is NULL it uses "path".)
855 *
856 * Output fields:
857 * path.wide
858 * Points to the path if it was expressed as Unicode
859 * and was not encoded. (Only used on Windows.)
860 * path.narrow
861 * Points to the path if it was expressed as bytes,
Steve Dowercc16be82016-09-08 10:35:16 -0700862 * or it was Unicode and was encoded to bytes. (On Windows,
Martin Panterb1321fb2016-10-10 00:38:21 +0000863 * is a non-zero integer if the path was expressed as bytes.
Steve Dowercc16be82016-09-08 10:35:16 -0700864 * The type is deliberately incompatible to prevent misuse.)
Larry Hastings9cf065c2012-06-22 16:30:09 -0700865 * path.fd
866 * Contains a file descriptor if path.accept_fd was true
867 * and the caller provided a signed integer instead of any
868 * sort of string.
869 *
870 * WARNING: if your "path" parameter is optional, and is
871 * unspecified, path_converter will never get called.
872 * So if you set allow_fd, you *MUST* initialize path.fd = -1
873 * yourself!
874 * path.length
875 * The length of the path in characters, if specified as
876 * a string.
877 * path.object
Xiang Zhang04316c42017-01-08 23:26:57 +0800878 * The original object passed in (if get a PathLike object,
879 * the result of PyOS_FSPath() is treated as the original object).
880 * Own a reference to the object.
Larry Hastings9cf065c2012-06-22 16:30:09 -0700881 * path.cleanup
882 * For internal use only. May point to a temporary object.
883 * (Pay no attention to the man behind the curtain.)
884 *
885 * At most one of path.wide or path.narrow will be non-NULL.
886 * If path was None and path.nullable was set,
887 * or if path was an integer and path.allow_fd was set,
888 * both path.wide and path.narrow will be NULL
889 * and path.length will be 0.
Georg Brandlf7875592012-06-24 13:58:31 +0200890 *
Larry Hastings9cf065c2012-06-22 16:30:09 -0700891 * path_converter takes care to not write to the path_t
892 * unless it's successful. However it must reset the
893 * "cleanup" field each time it's called.
894 *
895 * Use as follows:
896 * path_t path;
897 * memset(&path, 0, sizeof(path));
898 * PyArg_ParseTuple(args, "O&", path_converter, &path);
899 * // ... use values from path ...
900 * path_cleanup(&path);
901 *
902 * (Note that if PyArg_Parse fails you don't need to call
903 * path_cleanup(). However it is safe to do so.)
904 */
905typedef struct {
Victor Stinner292c8352012-10-30 02:17:38 +0100906 const char *function_name;
907 const char *argument_name;
Larry Hastings9cf065c2012-06-22 16:30:09 -0700908 int nullable;
909 int allow_fd;
Serhiy Storchakadeab18d2016-05-07 16:45:18 +0300910 const wchar_t *wide;
Steve Dowercc16be82016-09-08 10:35:16 -0700911#ifdef MS_WINDOWS
912 BOOL narrow;
913#else
Serhiy Storchakadeab18d2016-05-07 16:45:18 +0300914 const char *narrow;
Steve Dowercc16be82016-09-08 10:35:16 -0700915#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -0700916 int fd;
917 Py_ssize_t length;
918 PyObject *object;
919 PyObject *cleanup;
920} path_t;
921
Steve Dowercc16be82016-09-08 10:35:16 -0700922#ifdef MS_WINDOWS
923#define PATH_T_INITIALIZE(function_name, argument_name, nullable, allow_fd) \
924 {function_name, argument_name, nullable, allow_fd, NULL, FALSE, -1, 0, NULL, NULL}
925#else
Larry Hastings2f936352014-08-05 14:04:04 +1000926#define PATH_T_INITIALIZE(function_name, argument_name, nullable, allow_fd) \
927 {function_name, argument_name, nullable, allow_fd, NULL, NULL, -1, 0, NULL, NULL}
Steve Dowercc16be82016-09-08 10:35:16 -0700928#endif
Larry Hastings31826802013-10-19 00:09:25 -0700929
Larry Hastings9cf065c2012-06-22 16:30:09 -0700930static void
Xiang Zhang04316c42017-01-08 23:26:57 +0800931path_cleanup(path_t *path)
932{
933 Py_CLEAR(path->object);
934 Py_CLEAR(path->cleanup);
Larry Hastings9cf065c2012-06-22 16:30:09 -0700935}
936
937static int
Serhiy Storchaka819399b2016-04-06 22:17:52 +0300938path_converter(PyObject *o, void *p)
939{
Larry Hastings9cf065c2012-06-22 16:30:09 -0700940 path_t *path = (path_t *)p;
Xiang Zhang04316c42017-01-08 23:26:57 +0800941 PyObject *bytes = NULL;
942 Py_ssize_t length = 0;
Brett Cannon3f9183b2016-08-26 14:44:48 -0700943 int is_index, is_buffer, is_bytes, is_unicode;
Serhiy Storchakadeab18d2016-05-07 16:45:18 +0300944 const char *narrow;
Steve Dowercc16be82016-09-08 10:35:16 -0700945#ifdef MS_WINDOWS
Xiang Zhang04316c42017-01-08 23:26:57 +0800946 PyObject *wo = NULL;
Steve Dowercc16be82016-09-08 10:35:16 -0700947 const wchar_t *wide;
948#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -0700949
950#define FORMAT_EXCEPTION(exc, fmt) \
951 PyErr_Format(exc, "%s%s" fmt, \
952 path->function_name ? path->function_name : "", \
953 path->function_name ? ": " : "", \
954 path->argument_name ? path->argument_name : "path")
955
956 /* Py_CLEANUP_SUPPORTED support */
957 if (o == NULL) {
958 path_cleanup(path);
959 return 1;
960 }
961
Brett Cannon3f9183b2016-08-26 14:44:48 -0700962 /* Ensure it's always safe to call path_cleanup(). */
Xiang Zhang04316c42017-01-08 23:26:57 +0800963 path->object = path->cleanup = NULL;
964 /* path->object owns a reference to the original object */
965 Py_INCREF(o);
Larry Hastings9cf065c2012-06-22 16:30:09 -0700966
Serhiy Storchaka819399b2016-04-06 22:17:52 +0300967 if ((o == Py_None) && path->nullable) {
Larry Hastings9cf065c2012-06-22 16:30:09 -0700968 path->wide = NULL;
Steve Dowercc16be82016-09-08 10:35:16 -0700969#ifdef MS_WINDOWS
970 path->narrow = FALSE;
971#else
Larry Hastings9cf065c2012-06-22 16:30:09 -0700972 path->narrow = NULL;
Steve Dowercc16be82016-09-08 10:35:16 -0700973#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -0700974 path->fd = -1;
Xiang Zhang04316c42017-01-08 23:26:57 +0800975 goto success_exit;
Larry Hastings9cf065c2012-06-22 16:30:09 -0700976 }
977
Brett Cannon3f9183b2016-08-26 14:44:48 -0700978 /* Only call this here so that we don't treat the return value of
979 os.fspath() as an fd or buffer. */
980 is_index = path->allow_fd && PyIndex_Check(o);
981 is_buffer = PyObject_CheckBuffer(o);
982 is_bytes = PyBytes_Check(o);
983 is_unicode = PyUnicode_Check(o);
984
985 if (!is_index && !is_buffer && !is_unicode && !is_bytes) {
986 /* Inline PyOS_FSPath() for better error messages. */
987 _Py_IDENTIFIER(__fspath__);
Pablo Galindo09fbcd62019-02-18 10:46:34 +0000988 PyObject *func, *res;
Brett Cannon3f9183b2016-08-26 14:44:48 -0700989
990 func = _PyObject_LookupSpecial(o, &PyId___fspath__);
991 if (NULL == func) {
Xiang Zhang04316c42017-01-08 23:26:57 +0800992 goto error_format;
Brett Cannon3f9183b2016-08-26 14:44:48 -0700993 }
Pablo Galindo09fbcd62019-02-18 10:46:34 +0000994 res = _PyObject_CallNoArg(func);
Brett Cannon3f9183b2016-08-26 14:44:48 -0700995 Py_DECREF(func);
Pablo Galindo09fbcd62019-02-18 10:46:34 +0000996 if (NULL == res) {
Brett Cannon3f9183b2016-08-26 14:44:48 -0700997 goto error_exit;
998 }
Pablo Galindo09fbcd62019-02-18 10:46:34 +0000999 else if (PyUnicode_Check(res)) {
Brett Cannon3f9183b2016-08-26 14:44:48 -07001000 is_unicode = 1;
1001 }
Pablo Galindo09fbcd62019-02-18 10:46:34 +00001002 else if (PyBytes_Check(res)) {
Brett Cannon3f9183b2016-08-26 14:44:48 -07001003 is_bytes = 1;
1004 }
1005 else {
Pablo Galindo09fbcd62019-02-18 10:46:34 +00001006 PyErr_Format(PyExc_TypeError,
1007 "expected %.200s.__fspath__() to return str or bytes, "
1008 "not %.200s", Py_TYPE(o)->tp_name,
1009 Py_TYPE(res)->tp_name);
1010 Py_DECREF(res);
1011 goto error_exit;
Brett Cannon3f9183b2016-08-26 14:44:48 -07001012 }
Pablo Galindo09fbcd62019-02-18 10:46:34 +00001013
1014 /* still owns a reference to the original object */
1015 Py_DECREF(o);
1016 o = res;
Brett Cannon3f9183b2016-08-26 14:44:48 -07001017 }
1018
1019 if (is_unicode) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07001020#ifdef MS_WINDOWS
Victor Stinner26c03bd2016-09-19 11:55:44 +02001021 wide = PyUnicode_AsUnicodeAndSize(o, &length);
Victor Stinner59799a82013-11-13 14:17:30 +01001022 if (!wide) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001023 goto error_exit;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001024 }
Victor Stinner59799a82013-11-13 14:17:30 +01001025 if (length > 32767) {
1026 FORMAT_EXCEPTION(PyExc_ValueError, "%s too long for Windows");
Xiang Zhang04316c42017-01-08 23:26:57 +08001027 goto error_exit;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001028 }
Serhiy Storchaka2b0d2002015-04-20 09:53:58 +03001029 if (wcslen(wide) != length) {
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001030 FORMAT_EXCEPTION(PyExc_ValueError, "embedded null character in %s");
Xiang Zhang04316c42017-01-08 23:26:57 +08001031 goto error_exit;
Serhiy Storchaka2b0d2002015-04-20 09:53:58 +03001032 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07001033
1034 path->wide = wide;
Xiang Zhang04316c42017-01-08 23:26:57 +08001035 path->narrow = FALSE;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001036 path->fd = -1;
Xiang Zhang04316c42017-01-08 23:26:57 +08001037 goto success_exit;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001038#else
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001039 if (!PyUnicode_FSConverter(o, &bytes)) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001040 goto error_exit;
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001041 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07001042#endif
1043 }
Brett Cannon3f9183b2016-08-26 14:44:48 -07001044 else if (is_bytes) {
Serhiy Storchakad73c3182016-08-06 23:22:08 +03001045 bytes = o;
1046 Py_INCREF(bytes);
1047 }
Brett Cannon3f9183b2016-08-26 14:44:48 -07001048 else if (is_buffer) {
Serhiy Storchaka1180e5a2017-07-11 06:36:46 +03001049 /* XXX Replace PyObject_CheckBuffer with PyBytes_Check in other code
Ville Skyttä49b27342017-08-03 09:00:59 +03001050 after removing support of non-bytes buffer objects. */
Serhiy Storchakad73c3182016-08-06 23:22:08 +03001051 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
1052 "%s%s%s should be %s, not %.200s",
1053 path->function_name ? path->function_name : "",
1054 path->function_name ? ": " : "",
1055 path->argument_name ? path->argument_name : "path",
Brett Cannon3f9183b2016-08-26 14:44:48 -07001056 path->allow_fd && path->nullable ? "string, bytes, os.PathLike, "
1057 "integer or None" :
1058 path->allow_fd ? "string, bytes, os.PathLike or integer" :
1059 path->nullable ? "string, bytes, os.PathLike or None" :
1060 "string, bytes or os.PathLike",
Serhiy Storchakad73c3182016-08-06 23:22:08 +03001061 Py_TYPE(o)->tp_name)) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001062 goto error_exit;
Serhiy Storchakad73c3182016-08-06 23:22:08 +03001063 }
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001064 bytes = PyBytes_FromObject(o);
Larry Hastings9cf065c2012-06-22 16:30:09 -07001065 if (!bytes) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001066 goto error_exit;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001067 }
1068 }
Steve Dowercc16be82016-09-08 10:35:16 -07001069 else if (is_index) {
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001070 if (!_fd_converter(o, &path->fd)) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001071 goto error_exit;
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001072 }
1073 path->wide = NULL;
Steve Dowercc16be82016-09-08 10:35:16 -07001074#ifdef MS_WINDOWS
1075 path->narrow = FALSE;
1076#else
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001077 path->narrow = NULL;
Steve Dowercc16be82016-09-08 10:35:16 -07001078#endif
Xiang Zhang04316c42017-01-08 23:26:57 +08001079 goto success_exit;
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001080 }
1081 else {
Xiang Zhang04316c42017-01-08 23:26:57 +08001082 error_format:
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001083 PyErr_Format(PyExc_TypeError, "%s%s%s should be %s, not %.200s",
1084 path->function_name ? path->function_name : "",
1085 path->function_name ? ": " : "",
1086 path->argument_name ? path->argument_name : "path",
Brett Cannon3f9183b2016-08-26 14:44:48 -07001087 path->allow_fd && path->nullable ? "string, bytes, os.PathLike, "
1088 "integer or None" :
1089 path->allow_fd ? "string, bytes, os.PathLike or integer" :
1090 path->nullable ? "string, bytes, os.PathLike or None" :
1091 "string, bytes or os.PathLike",
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001092 Py_TYPE(o)->tp_name);
Xiang Zhang04316c42017-01-08 23:26:57 +08001093 goto error_exit;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001094 }
1095
Larry Hastings9cf065c2012-06-22 16:30:09 -07001096 length = PyBytes_GET_SIZE(bytes);
Larry Hastings9cf065c2012-06-22 16:30:09 -07001097 narrow = PyBytes_AS_STRING(bytes);
Victor Stinner706768c2014-08-16 01:03:39 +02001098 if ((size_t)length != strlen(narrow)) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +03001099 FORMAT_EXCEPTION(PyExc_ValueError, "embedded null character in %s");
Xiang Zhang04316c42017-01-08 23:26:57 +08001100 goto error_exit;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001101 }
1102
Steve Dowercc16be82016-09-08 10:35:16 -07001103#ifdef MS_WINDOWS
1104 wo = PyUnicode_DecodeFSDefaultAndSize(
1105 narrow,
1106 length
1107 );
1108 if (!wo) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001109 goto error_exit;
Steve Dowercc16be82016-09-08 10:35:16 -07001110 }
1111
Xiang Zhang04316c42017-01-08 23:26:57 +08001112 wide = PyUnicode_AsUnicodeAndSize(wo, &length);
Steve Dowercc16be82016-09-08 10:35:16 -07001113 if (!wide) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001114 goto error_exit;
Steve Dowercc16be82016-09-08 10:35:16 -07001115 }
1116 if (length > 32767) {
1117 FORMAT_EXCEPTION(PyExc_ValueError, "%s too long for Windows");
Xiang Zhang04316c42017-01-08 23:26:57 +08001118 goto error_exit;
Steve Dowercc16be82016-09-08 10:35:16 -07001119 }
1120 if (wcslen(wide) != length) {
1121 FORMAT_EXCEPTION(PyExc_ValueError, "embedded null character in %s");
Xiang Zhang04316c42017-01-08 23:26:57 +08001122 goto error_exit;
Steve Dowercc16be82016-09-08 10:35:16 -07001123 }
1124 path->wide = wide;
1125 path->narrow = TRUE;
Xiang Zhang04316c42017-01-08 23:26:57 +08001126 path->cleanup = wo;
1127 Py_DECREF(bytes);
Steve Dowercc16be82016-09-08 10:35:16 -07001128#else
Larry Hastings9cf065c2012-06-22 16:30:09 -07001129 path->wide = NULL;
1130 path->narrow = narrow;
Serhiy Storchakad73c3182016-08-06 23:22:08 +03001131 if (bytes == o) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001132 /* Still a reference owned by path->object, don't have to
1133 worry about path->narrow is used after free. */
Serhiy Storchakad73c3182016-08-06 23:22:08 +03001134 Py_DECREF(bytes);
Serhiy Storchakad73c3182016-08-06 23:22:08 +03001135 }
1136 else {
1137 path->cleanup = bytes;
Serhiy Storchakad73c3182016-08-06 23:22:08 +03001138 }
Xiang Zhang04316c42017-01-08 23:26:57 +08001139#endif
1140 path->fd = -1;
1141
1142 success_exit:
1143 path->length = length;
1144 path->object = o;
1145 return Py_CLEANUP_SUPPORTED;
1146
1147 error_exit:
1148 Py_XDECREF(o);
1149 Py_XDECREF(bytes);
1150#ifdef MS_WINDOWS
1151 Py_XDECREF(wo);
1152#endif
1153 return 0;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001154}
1155
1156static void
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001157argument_unavailable_error(const char *function_name, const char *argument_name)
1158{
Larry Hastings9cf065c2012-06-22 16:30:09 -07001159 PyErr_Format(PyExc_NotImplementedError,
1160 "%s%s%s unavailable on this platform",
1161 (function_name != NULL) ? function_name : "",
1162 (function_name != NULL) ? ": ": "",
1163 argument_name);
1164}
1165
1166static int
Serhiy Storchakaa2ad5c32013-01-07 23:13:46 +02001167dir_fd_unavailable(PyObject *o, void *p)
1168{
1169 int dir_fd;
1170 if (!dir_fd_converter(o, &dir_fd))
Larry Hastings9cf065c2012-06-22 16:30:09 -07001171 return 0;
Serhiy Storchakaa2ad5c32013-01-07 23:13:46 +02001172 if (dir_fd != DEFAULT_DIR_FD) {
1173 argument_unavailable_error(NULL, "dir_fd");
1174 return 0;
1175 }
1176 *(int *)p = dir_fd;
1177 return 1;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001178}
1179
1180static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001181fd_specified(const char *function_name, int fd)
1182{
Larry Hastings9cf065c2012-06-22 16:30:09 -07001183 if (fd == -1)
1184 return 0;
1185
1186 argument_unavailable_error(function_name, "fd");
1187 return 1;
1188}
1189
1190static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001191follow_symlinks_specified(const char *function_name, int follow_symlinks)
1192{
Larry Hastings9cf065c2012-06-22 16:30:09 -07001193 if (follow_symlinks)
1194 return 0;
1195
1196 argument_unavailable_error(function_name, "follow_symlinks");
1197 return 1;
1198}
1199
1200static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001201path_and_dir_fd_invalid(const char *function_name, path_t *path, int dir_fd)
1202{
Steve Dowercc16be82016-09-08 10:35:16 -07001203 if (!path->wide && (dir_fd != DEFAULT_DIR_FD)
1204#ifndef MS_WINDOWS
1205 && !path->narrow
1206#endif
1207 ) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07001208 PyErr_Format(PyExc_ValueError,
1209 "%s: can't specify dir_fd without matching path",
1210 function_name);
1211 return 1;
1212 }
1213 return 0;
1214}
1215
1216static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001217dir_fd_and_fd_invalid(const char *function_name, int dir_fd, int fd)
1218{
Larry Hastings9cf065c2012-06-22 16:30:09 -07001219 if ((dir_fd != DEFAULT_DIR_FD) && (fd != -1)) {
1220 PyErr_Format(PyExc_ValueError,
1221 "%s: can't specify both dir_fd and fd",
1222 function_name);
1223 return 1;
1224 }
1225 return 0;
1226}
1227
1228static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001229fd_and_follow_symlinks_invalid(const char *function_name, int fd,
1230 int follow_symlinks)
1231{
Larry Hastings9cf065c2012-06-22 16:30:09 -07001232 if ((fd > 0) && (!follow_symlinks)) {
1233 PyErr_Format(PyExc_ValueError,
1234 "%s: cannot use fd and follow_symlinks together",
1235 function_name);
1236 return 1;
1237 }
1238 return 0;
1239}
1240
1241static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001242dir_fd_and_follow_symlinks_invalid(const char *function_name, int dir_fd,
1243 int follow_symlinks)
1244{
Larry Hastings9cf065c2012-06-22 16:30:09 -07001245 if ((dir_fd != DEFAULT_DIR_FD) && (!follow_symlinks)) {
1246 PyErr_Format(PyExc_ValueError,
1247 "%s: cannot use dir_fd and follow_symlinks together",
1248 function_name);
1249 return 1;
1250 }
1251 return 0;
1252}
1253
Larry Hastings2f936352014-08-05 14:04:04 +10001254#ifdef MS_WINDOWS
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001255 typedef long long Py_off_t;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001256#else
Larry Hastings2f936352014-08-05 14:04:04 +10001257 typedef off_t Py_off_t;
1258#endif
1259
1260static int
1261Py_off_t_converter(PyObject *arg, void *addr)
1262{
1263#ifdef HAVE_LARGEFILE_SUPPORT
1264 *((Py_off_t *)addr) = PyLong_AsLongLong(arg);
1265#else
1266 *((Py_off_t *)addr) = PyLong_AsLong(arg);
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001267#endif
1268 if (PyErr_Occurred())
1269 return 0;
1270 return 1;
1271}
Larry Hastings2f936352014-08-05 14:04:04 +10001272
1273static PyObject *
1274PyLong_FromPy_off_t(Py_off_t offset)
1275{
1276#ifdef HAVE_LARGEFILE_SUPPORT
1277 return PyLong_FromLongLong(offset);
1278#else
1279 return PyLong_FromLong(offset);
Ross Lagerwallb1e5d592011-09-19 08:30:43 +02001280#endif
Larry Hastings2f936352014-08-05 14:04:04 +10001281}
1282
Serhiy Storchakad54cfb12018-05-08 07:48:50 +03001283#ifdef HAVE_SIGSET_T
1284/* Convert an iterable of integers to a sigset.
1285 Return 1 on success, return 0 and raise an exception on error. */
1286int
1287_Py_Sigset_Converter(PyObject *obj, void *addr)
1288{
1289 sigset_t *mask = (sigset_t *)addr;
1290 PyObject *iterator, *item;
1291 long signum;
1292 int overflow;
1293
Rémi Lapeyref0900192019-05-04 01:30:53 +02001294 // The extra parens suppress the unreachable-code warning with clang on MacOS
1295 if (sigemptyset(mask) < (0)) {
Serhiy Storchakad54cfb12018-05-08 07:48:50 +03001296 /* Probably only if mask == NULL. */
1297 PyErr_SetFromErrno(PyExc_OSError);
1298 return 0;
1299 }
1300
1301 iterator = PyObject_GetIter(obj);
1302 if (iterator == NULL) {
1303 return 0;
1304 }
1305
1306 while ((item = PyIter_Next(iterator)) != NULL) {
1307 signum = PyLong_AsLongAndOverflow(item, &overflow);
1308 Py_DECREF(item);
1309 if (signum <= 0 || signum >= NSIG) {
1310 if (overflow || signum != -1 || !PyErr_Occurred()) {
1311 PyErr_Format(PyExc_ValueError,
1312 "signal number %ld out of range", signum);
1313 }
1314 goto error;
1315 }
1316 if (sigaddset(mask, (int)signum)) {
1317 if (errno != EINVAL) {
1318 /* Probably impossible */
1319 PyErr_SetFromErrno(PyExc_OSError);
1320 goto error;
1321 }
1322 /* For backwards compatibility, allow idioms such as
1323 * `range(1, NSIG)` but warn about invalid signal numbers
1324 */
1325 const char msg[] =
1326 "invalid signal number %ld, please use valid_signals()";
1327 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1, msg, signum)) {
1328 goto error;
1329 }
1330 }
1331 }
1332 if (!PyErr_Occurred()) {
1333 Py_DECREF(iterator);
1334 return 1;
1335 }
1336
1337error:
1338 Py_DECREF(iterator);
1339 return 0;
1340}
1341#endif /* HAVE_SIGSET_T */
1342
Brian Curtinfc1be6d2010-11-24 13:23:18 +00001343#ifdef MS_WINDOWS
Brian Curtinf5e76d02010-11-24 13:14:05 +00001344
1345static int
Brian Curtind25aef52011-06-13 15:16:04 -05001346win32_get_reparse_tag(HANDLE reparse_point_handle, ULONG *reparse_tag)
Brian Curtinf5e76d02010-11-24 13:14:05 +00001347{
Martin Panter70214ad2016-08-04 02:38:59 +00001348 char target_buffer[_Py_MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
1349 _Py_REPARSE_DATA_BUFFER *rdb = (_Py_REPARSE_DATA_BUFFER *)target_buffer;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001350 DWORD n_bytes_returned;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001351
1352 if (0 == DeviceIoControl(
1353 reparse_point_handle,
1354 FSCTL_GET_REPARSE_POINT,
1355 NULL, 0, /* in buffer */
1356 target_buffer, sizeof(target_buffer),
1357 &n_bytes_returned,
1358 NULL)) /* we're not using OVERLAPPED_IO */
Brian Curtind25aef52011-06-13 15:16:04 -05001359 return FALSE;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001360
1361 if (reparse_tag)
1362 *reparse_tag = rdb->ReparseTag;
1363
Brian Curtind25aef52011-06-13 15:16:04 -05001364 return TRUE;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001365}
Victor Stinner1ab6c2d2011-11-15 22:27:41 +01001366
Brian Curtinfc1be6d2010-11-24 13:23:18 +00001367#endif /* MS_WINDOWS */
Brian Curtinf5e76d02010-11-24 13:14:05 +00001368
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001369/* Return a dictionary corresponding to the POSIX environment table */
Ronald Oussoren697e56d2013-01-25 17:57:13 +01001370#if defined(WITH_NEXT_FRAMEWORK) || (defined(__APPLE__) && defined(Py_ENABLE_SHARED))
Jack Jansenea0c3822002-08-01 21:57:49 +00001371/* On Darwin/MacOSX a shared library or framework has no access to
Ronald Oussoren697e56d2013-01-25 17:57:13 +01001372** environ directly, we must obtain it with _NSGetEnviron(). See also
1373** man environ(7).
Jack Jansenea0c3822002-08-01 21:57:49 +00001374*/
1375#include <crt_externs.h>
1376static char **environ;
pxinwrf2d7ac72019-05-21 18:46:37 +08001377#elif !defined(_MSC_VER) && (!defined(__WATCOMC__) || defined(__QNX__) || defined(__VXWORKS__))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001378extern char **environ;
Guido van Rossuma4916fa1996-05-23 22:58:55 +00001379#endif /* !_MSC_VER */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001380
Barry Warsaw53699e91996-12-10 23:23:01 +00001381static PyObject *
Thomas Woutersf3f33dc2000-07-21 06:00:07 +00001382convertenviron(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001383{
Victor Stinner8c62be82010-05-06 00:08:46 +00001384 PyObject *d;
Thomas Hellerf78f12a2007-11-08 19:33:05 +00001385#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +00001386 wchar_t **e;
Thomas Hellerf78f12a2007-11-08 19:33:05 +00001387#else
Victor Stinner8c62be82010-05-06 00:08:46 +00001388 char **e;
Thomas Hellerf78f12a2007-11-08 19:33:05 +00001389#endif
Guido van Rossumd48f2521997-12-05 22:19:34 +00001390
Victor Stinner8c62be82010-05-06 00:08:46 +00001391 d = PyDict_New();
1392 if (d == NULL)
1393 return NULL;
Ronald Oussoren697e56d2013-01-25 17:57:13 +01001394#if defined(WITH_NEXT_FRAMEWORK) || (defined(__APPLE__) && defined(Py_ENABLE_SHARED))
Victor Stinner8c62be82010-05-06 00:08:46 +00001395 if (environ == NULL)
1396 environ = *_NSGetEnviron();
1397#endif
1398#ifdef MS_WINDOWS
1399 /* _wenviron must be initialized in this way if the program is started
1400 through main() instead of wmain(). */
1401 _wgetenv(L"");
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001402 e = _wenviron;
Victor Stinner8c62be82010-05-06 00:08:46 +00001403#else
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001404 e = environ;
1405#endif
1406 if (e == NULL)
Victor Stinner8c62be82010-05-06 00:08:46 +00001407 return d;
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001408 for (; *e != NULL; e++) {
Victor Stinner8c62be82010-05-06 00:08:46 +00001409 PyObject *k;
1410 PyObject *v;
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001411#ifdef MS_WINDOWS
1412 const wchar_t *p = wcschr(*e, L'=');
1413#else
Serhiy Storchakadeab18d2016-05-07 16:45:18 +03001414 const char *p = strchr(*e, '=');
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001415#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00001416 if (p == NULL)
1417 continue;
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001418#ifdef MS_WINDOWS
1419 k = PyUnicode_FromWideChar(*e, (Py_ssize_t)(p-*e));
1420#else
Victor Stinner84ae1182010-05-06 22:05:07 +00001421 k = PyBytes_FromStringAndSize(*e, (int)(p-*e));
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001422#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00001423 if (k == NULL) {
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001424 Py_DECREF(d);
1425 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00001426 }
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001427#ifdef MS_WINDOWS
1428 v = PyUnicode_FromWideChar(p+1, wcslen(p+1));
1429#else
Victor Stinner84ae1182010-05-06 22:05:07 +00001430 v = PyBytes_FromStringAndSize(p+1, strlen(p+1));
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001431#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00001432 if (v == NULL) {
Victor Stinner8c62be82010-05-06 00:08:46 +00001433 Py_DECREF(k);
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001434 Py_DECREF(d);
1435 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00001436 }
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001437 if (PyDict_GetItemWithError(d, k) == NULL) {
1438 if (PyErr_Occurred() || PyDict_SetItem(d, k, v) != 0) {
1439 Py_DECREF(v);
1440 Py_DECREF(k);
1441 Py_DECREF(d);
1442 return NULL;
1443 }
Victor Stinner8c62be82010-05-06 00:08:46 +00001444 }
1445 Py_DECREF(k);
1446 Py_DECREF(v);
Guido van Rossumd48f2521997-12-05 22:19:34 +00001447 }
Victor Stinner8c62be82010-05-06 00:08:46 +00001448 return d;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001449}
1450
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001451/* Set a POSIX-specific error from errno, and return NULL */
1452
Barry Warsawd58d7641998-07-23 16:14:40 +00001453static PyObject *
Thomas Woutersf3f33dc2000-07-21 06:00:07 +00001454posix_error(void)
Guido van Rossumad0ee831995-03-01 10:34:45 +00001455{
Victor Stinner8c62be82010-05-06 00:08:46 +00001456 return PyErr_SetFromErrno(PyExc_OSError);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001457}
Mark Hammondef8b6542001-05-13 08:04:26 +00001458
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001459#ifdef MS_WINDOWS
Fredrik Lundhffb9c772000-07-09 14:49:51 +00001460static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001461win32_error(const char* function, const char* filename)
Fredrik Lundhffb9c772000-07-09 14:49:51 +00001462{
Victor Stinner8c62be82010-05-06 00:08:46 +00001463 /* XXX We should pass the function name along in the future.
1464 (winreg.c also wants to pass the function name.)
1465 This would however require an additional param to the
1466 Windows error object, which is non-trivial.
1467 */
1468 errno = GetLastError();
1469 if (filename)
1470 return PyErr_SetFromWindowsErrWithFilename(errno, filename);
1471 else
1472 return PyErr_SetFromWindowsErr(errno);
Fredrik Lundhffb9c772000-07-09 14:49:51 +00001473}
Mark Hammondc2e85bd2002-10-03 05:10:39 +00001474
Mark Hammondc2e85bd2002-10-03 05:10:39 +00001475static PyObject *
Steve Dower2438cdf2019-03-29 16:37:16 -07001476win32_error_object_err(const char* function, PyObject* filename, DWORD err)
Victor Stinnereb5657a2011-09-30 01:44:27 +02001477{
1478 /* XXX - see win32_error for comments on 'function' */
Victor Stinnereb5657a2011-09-30 01:44:27 +02001479 if (filename)
1480 return PyErr_SetExcFromWindowsErrWithFilenameObject(
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02001481 PyExc_OSError,
Steve Dower2438cdf2019-03-29 16:37:16 -07001482 err,
Victor Stinnereb5657a2011-09-30 01:44:27 +02001483 filename);
1484 else
Steve Dower2438cdf2019-03-29 16:37:16 -07001485 return PyErr_SetFromWindowsErr(err);
1486}
1487
1488static PyObject *
1489win32_error_object(const char* function, PyObject* filename)
1490{
1491 errno = GetLastError();
1492 return win32_error_object_err(function, filename, errno);
Victor Stinnereb5657a2011-09-30 01:44:27 +02001493}
1494
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00001495#endif /* MS_WINDOWS */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001496
Larry Hastings9cf065c2012-06-22 16:30:09 -07001497static PyObject *
Alexey Izbyshev83460312018-10-20 03:28:22 +03001498posix_path_object_error(PyObject *path)
1499{
1500 return PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, path);
1501}
1502
1503static PyObject *
Serhiy Storchaka2674bc72016-10-08 20:16:57 +03001504path_object_error(PyObject *path)
Larry Hastings9cf065c2012-06-22 16:30:09 -07001505{
1506#ifdef MS_WINDOWS
Serhiy Storchaka2674bc72016-10-08 20:16:57 +03001507 return PyErr_SetExcFromWindowsErrWithFilenameObject(
1508 PyExc_OSError, 0, path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07001509#else
Alexey Izbyshev83460312018-10-20 03:28:22 +03001510 return posix_path_object_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07001511#endif
1512}
1513
Serhiy Storchaka2674bc72016-10-08 20:16:57 +03001514static PyObject *
1515path_object_error2(PyObject *path, PyObject *path2)
1516{
1517#ifdef MS_WINDOWS
1518 return PyErr_SetExcFromWindowsErrWithFilenameObjects(
1519 PyExc_OSError, 0, path, path2);
1520#else
1521 return PyErr_SetFromErrnoWithFilenameObjects(PyExc_OSError, path, path2);
1522#endif
1523}
1524
1525static PyObject *
1526path_error(path_t *path)
1527{
1528 return path_object_error(path->object);
1529}
Larry Hastings31826802013-10-19 00:09:25 -07001530
Larry Hastingsb0827312014-02-09 22:05:19 -08001531static PyObject *
Alexey Izbyshev83460312018-10-20 03:28:22 +03001532posix_path_error(path_t *path)
1533{
1534 return posix_path_object_error(path->object);
1535}
1536
1537static PyObject *
Larry Hastingsb0827312014-02-09 22:05:19 -08001538path_error2(path_t *path, path_t *path2)
1539{
Serhiy Storchaka2674bc72016-10-08 20:16:57 +03001540 return path_object_error2(path->object, path2->object);
Larry Hastingsb0827312014-02-09 22:05:19 -08001541}
1542
1543
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001544/* POSIX generic methods */
1545
Larry Hastings2f936352014-08-05 14:04:04 +10001546static int
1547fildes_converter(PyObject *o, void *p)
Fred Drake4d1e64b2002-04-15 19:40:07 +00001548{
Victor Stinner8c62be82010-05-06 00:08:46 +00001549 int fd;
Larry Hastings2f936352014-08-05 14:04:04 +10001550 int *pointer = (int *)p;
1551 fd = PyObject_AsFileDescriptor(o);
Victor Stinner8c62be82010-05-06 00:08:46 +00001552 if (fd < 0)
Larry Hastings2f936352014-08-05 14:04:04 +10001553 return 0;
Larry Hastings2f936352014-08-05 14:04:04 +10001554 *pointer = fd;
1555 return 1;
1556}
1557
1558static PyObject *
1559posix_fildes_fd(int fd, int (*func)(int))
1560{
1561 int res;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00001562 int async_err = 0;
1563
1564 do {
1565 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04001566 _Py_BEGIN_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00001567 res = (*func)(fd);
Steve Dower8fc89802015-04-12 00:26:27 -04001568 _Py_END_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00001569 Py_END_ALLOW_THREADS
1570 } while (res != 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
1571 if (res != 0)
1572 return (!async_err) ? posix_error() : NULL;
1573 Py_RETURN_NONE;
Fred Drake4d1e64b2002-04-15 19:40:07 +00001574}
Guido van Rossum21142a01999-01-08 21:05:37 +00001575
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001576
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00001577#ifdef MS_WINDOWS
Thomas Wouters477c8d52006-05-27 19:21:47 +00001578/* This is a reimplementation of the C library's chdir function,
1579 but one that produces Win32 errors instead of DOS error codes.
1580 chdir is essentially a wrapper around SetCurrentDirectory; however,
1581 it also needs to set "magic" environment variables indicating
1582 the per-drive current directory, which are of the form =<drive>: */
Benjamin Peterson206e3072008-10-19 14:07:49 +00001583static BOOL __stdcall
Thomas Wouters477c8d52006-05-27 19:21:47 +00001584win32_wchdir(LPCWSTR path)
1585{
Victor Stinnered537822015-12-13 21:40:26 +01001586 wchar_t path_buf[MAX_PATH], *new_path = path_buf;
Victor Stinner8c62be82010-05-06 00:08:46 +00001587 int result;
1588 wchar_t env[4] = L"=x:";
Thomas Wouters477c8d52006-05-27 19:21:47 +00001589
Victor Stinner8c62be82010-05-06 00:08:46 +00001590 if(!SetCurrentDirectoryW(path))
1591 return FALSE;
Victor Stinnered537822015-12-13 21:40:26 +01001592 result = GetCurrentDirectoryW(Py_ARRAY_LENGTH(path_buf), new_path);
Victor Stinner8c62be82010-05-06 00:08:46 +00001593 if (!result)
1594 return FALSE;
Victor Stinnere847d712015-12-14 00:21:50 +01001595 if (result > Py_ARRAY_LENGTH(path_buf)) {
Victor Stinnerb6404912013-07-07 16:21:41 +02001596 new_path = PyMem_RawMalloc(result * sizeof(wchar_t));
Victor Stinner8c62be82010-05-06 00:08:46 +00001597 if (!new_path) {
1598 SetLastError(ERROR_OUTOFMEMORY);
1599 return FALSE;
1600 }
1601 result = GetCurrentDirectoryW(result, new_path);
1602 if (!result) {
Victor Stinnerb6404912013-07-07 16:21:41 +02001603 PyMem_RawFree(new_path);
Victor Stinner8c62be82010-05-06 00:08:46 +00001604 return FALSE;
1605 }
1606 }
Alexey Izbyshev3e197c72018-03-01 12:13:56 +03001607 int is_unc_like_path = (wcsncmp(new_path, L"\\\\", 2) == 0 ||
1608 wcsncmp(new_path, L"//", 2) == 0);
1609 if (!is_unc_like_path) {
1610 env[1] = new_path[0];
1611 result = SetEnvironmentVariableW(env, new_path);
1612 }
Victor Stinnered537822015-12-13 21:40:26 +01001613 if (new_path != path_buf)
Victor Stinnerb6404912013-07-07 16:21:41 +02001614 PyMem_RawFree(new_path);
Alexey Izbyshev3e197c72018-03-01 12:13:56 +03001615 return result ? TRUE : FALSE;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001616}
1617#endif
1618
Martin v. Löwis14694662006-02-03 12:54:16 +00001619#ifdef MS_WINDOWS
1620/* The CRT of Windows has a number of flaws wrt. its stat() implementation:
1621 - time stamps are restricted to second resolution
1622 - file modification times suffer from forth-and-back conversions between
1623 UTC and local time
1624 Therefore, we implement our own stat, based on the Win32 API directly.
1625*/
Victor Stinner8c62be82010-05-06 00:08:46 +00001626#define HAVE_STAT_NSEC 1
Zachary Ware63f277b2014-06-19 09:46:37 -05001627#define HAVE_STRUCT_STAT_ST_FILE_ATTRIBUTES 1
Martin v. Löwis14694662006-02-03 12:54:16 +00001628
Victor Stinner6036e442015-03-08 01:58:04 +01001629static void
Steve Dowercc16be82016-09-08 10:35:16 -07001630find_data_to_file_info(WIN32_FIND_DATAW *pFileData,
1631 BY_HANDLE_FILE_INFORMATION *info,
1632 ULONG *reparse_tag)
Victor Stinner6036e442015-03-08 01:58:04 +01001633{
1634 memset(info, 0, sizeof(*info));
1635 info->dwFileAttributes = pFileData->dwFileAttributes;
1636 info->ftCreationTime = pFileData->ftCreationTime;
1637 info->ftLastAccessTime = pFileData->ftLastAccessTime;
1638 info->ftLastWriteTime = pFileData->ftLastWriteTime;
1639 info->nFileSizeHigh = pFileData->nFileSizeHigh;
1640 info->nFileSizeLow = pFileData->nFileSizeLow;
1641/* info->nNumberOfLinks = 1; */
1642 if (pFileData->dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT)
1643 *reparse_tag = pFileData->dwReserved0;
1644 else
1645 *reparse_tag = 0;
1646}
1647
Guido van Rossumd8faa362007-04-27 19:54:29 +00001648static BOOL
Steve Dowercc16be82016-09-08 10:35:16 -07001649attributes_from_dir(LPCWSTR pszFile, BY_HANDLE_FILE_INFORMATION *info, ULONG *reparse_tag)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001650{
Victor Stinner8c62be82010-05-06 00:08:46 +00001651 HANDLE hFindFile;
1652 WIN32_FIND_DATAW FileData;
1653 hFindFile = FindFirstFileW(pszFile, &FileData);
1654 if (hFindFile == INVALID_HANDLE_VALUE)
1655 return FALSE;
1656 FindClose(hFindFile);
Steve Dowercc16be82016-09-08 10:35:16 -07001657 find_data_to_file_info(&FileData, info, reparse_tag);
Victor Stinner8c62be82010-05-06 00:08:46 +00001658 return TRUE;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001659}
1660
Brian Curtind25aef52011-06-13 15:16:04 -05001661static BOOL
1662get_target_path(HANDLE hdl, wchar_t **target_path)
1663{
1664 int buf_size, result_length;
1665 wchar_t *buf;
1666
1667 /* We have a good handle to the target, use it to determine
1668 the target path name (then we'll call lstat on it). */
Steve Dower2ea51c92015-03-20 21:49:12 -07001669 buf_size = GetFinalPathNameByHandleW(hdl, 0, 0,
1670 VOLUME_NAME_DOS);
Brian Curtind25aef52011-06-13 15:16:04 -05001671 if(!buf_size)
1672 return FALSE;
1673
Victor Stinnerc36674a2016-03-16 14:30:16 +01001674 buf = (wchar_t *)PyMem_RawMalloc((buf_size + 1) * sizeof(wchar_t));
Brian Curtinc8be8402011-06-14 09:52:50 -05001675 if (!buf) {
1676 SetLastError(ERROR_OUTOFMEMORY);
1677 return FALSE;
1678 }
1679
Steve Dower2ea51c92015-03-20 21:49:12 -07001680 result_length = GetFinalPathNameByHandleW(hdl,
Brian Curtind25aef52011-06-13 15:16:04 -05001681 buf, buf_size, VOLUME_NAME_DOS);
1682
1683 if(!result_length) {
Victor Stinnerc36674a2016-03-16 14:30:16 +01001684 PyMem_RawFree(buf);
Brian Curtind25aef52011-06-13 15:16:04 -05001685 return FALSE;
1686 }
1687
Brian Curtind25aef52011-06-13 15:16:04 -05001688 buf[result_length] = 0;
1689
1690 *target_path = buf;
1691 return TRUE;
1692}
1693
1694static int
Steve Dowercc16be82016-09-08 10:35:16 -07001695win32_xstat_impl(const wchar_t *path, struct _Py_stat_struct *result,
Brian Curtind25aef52011-06-13 15:16:04 -05001696 BOOL traverse)
1697{
Victor Stinner26de69d2011-06-17 15:15:38 +02001698 int code;
Brian Curtind25aef52011-06-13 15:16:04 -05001699 HANDLE hFile, hFile2;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001700 BY_HANDLE_FILE_INFORMATION info;
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001701 ULONG reparse_tag = 0;
Victor Stinner26de69d2011-06-17 15:15:38 +02001702 wchar_t *target_path;
Steve Dowercc16be82016-09-08 10:35:16 -07001703 const wchar_t *dot;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001704
Steve Dowercc16be82016-09-08 10:35:16 -07001705 hFile = CreateFileW(
Brian Curtinf5e76d02010-11-24 13:14:05 +00001706 path,
Brian Curtind25aef52011-06-13 15:16:04 -05001707 FILE_READ_ATTRIBUTES, /* desired access */
Brian Curtinf5e76d02010-11-24 13:14:05 +00001708 0, /* share mode */
1709 NULL, /* security attributes */
1710 OPEN_EXISTING,
1711 /* FILE_FLAG_BACKUP_SEMANTICS is required to open a directory */
Brian Curtind25aef52011-06-13 15:16:04 -05001712 /* FILE_FLAG_OPEN_REPARSE_POINT does not follow the symlink.
1713 Because of this, calls like GetFinalPathNameByHandle will return
R David Murrayfc069992013-12-13 20:52:19 -05001714 the symlink path again and not the actual final path. */
Brian Curtind25aef52011-06-13 15:16:04 -05001715 FILE_ATTRIBUTE_NORMAL|FILE_FLAG_BACKUP_SEMANTICS|
1716 FILE_FLAG_OPEN_REPARSE_POINT,
Brian Curtinf5e76d02010-11-24 13:14:05 +00001717 NULL);
1718
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001719 if (hFile == INVALID_HANDLE_VALUE) {
Brian Curtinf5e76d02010-11-24 13:14:05 +00001720 /* Either the target doesn't exist, or we don't have access to
1721 get a handle to it. If the former, we need to return an error.
1722 If the latter, we can use attributes_from_dir. */
Berker Peksag0b4dc482016-09-17 15:49:59 +03001723 DWORD lastError = GetLastError();
1724 if (lastError != ERROR_ACCESS_DENIED &&
1725 lastError != ERROR_SHARING_VIOLATION)
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001726 return -1;
1727 /* Could not get attributes on open file. Fall back to
1728 reading the directory. */
1729 if (!attributes_from_dir(path, &info, &reparse_tag))
1730 /* Very strange. This should not fail now */
1731 return -1;
1732 if (info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1733 if (traverse) {
1734 /* Should traverse, but could not open reparse point handle */
Berker Peksag0b4dc482016-09-17 15:49:59 +03001735 SetLastError(lastError);
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001736 return -1;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001737 }
Brian Curtinf5e76d02010-11-24 13:14:05 +00001738 }
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001739 } else {
1740 if (!GetFileInformationByHandle(hFile, &info)) {
1741 CloseHandle(hFile);
Brian Curtind25aef52011-06-13 15:16:04 -05001742 return -1;
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001743 }
1744 if (info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
Mark Becwarb82bfac2019-02-02 16:08:23 -05001745 if (!win32_get_reparse_tag(hFile, &reparse_tag)) {
1746 CloseHandle(hFile);
Brian Curtind25aef52011-06-13 15:16:04 -05001747 return -1;
Mark Becwarb82bfac2019-02-02 16:08:23 -05001748 }
Brian Curtind25aef52011-06-13 15:16:04 -05001749 /* Close the outer open file handle now that we're about to
1750 reopen it with different flags. */
1751 if (!CloseHandle(hFile))
1752 return -1;
1753
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001754 if (traverse) {
Brian Curtind25aef52011-06-13 15:16:04 -05001755 /* In order to call GetFinalPathNameByHandle we need to open
1756 the file without the reparse handling flag set. */
Brian Curtind25aef52011-06-13 15:16:04 -05001757 hFile2 = CreateFileW(
1758 path, FILE_READ_ATTRIBUTES, FILE_SHARE_READ,
1759 NULL, OPEN_EXISTING,
1760 FILE_ATTRIBUTE_NORMAL|FILE_FLAG_BACKUP_SEMANTICS,
1761 NULL);
1762 if (hFile2 == INVALID_HANDLE_VALUE)
1763 return -1;
1764
Mark Becwarb82bfac2019-02-02 16:08:23 -05001765 if (!get_target_path(hFile2, &target_path)) {
1766 CloseHandle(hFile2);
Brian Curtind25aef52011-06-13 15:16:04 -05001767 return -1;
Mark Becwarb82bfac2019-02-02 16:08:23 -05001768 }
1769
1770 if (!CloseHandle(hFile2)) {
1771 return -1;
1772 }
Brian Curtind25aef52011-06-13 15:16:04 -05001773
Steve Dowercc16be82016-09-08 10:35:16 -07001774 code = win32_xstat_impl(target_path, result, FALSE);
Victor Stinnerc36674a2016-03-16 14:30:16 +01001775 PyMem_RawFree(target_path);
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001776 return code;
1777 }
Hirokazu Yamamoto7ed117a2010-12-07 10:24:37 +00001778 } else
1779 CloseHandle(hFile);
Brian Curtinf5e76d02010-11-24 13:14:05 +00001780 }
Steve Dowera2af1a52015-02-21 10:04:10 -08001781 _Py_attribute_data_to_stat(&info, reparse_tag, result);
Brian Curtinf5e76d02010-11-24 13:14:05 +00001782
1783 /* Set S_IEXEC if it is an .exe, .bat, ... */
1784 dot = wcsrchr(path, '.');
1785 if (dot) {
1786 if (_wcsicmp(dot, L".bat") == 0 || _wcsicmp(dot, L".cmd") == 0 ||
1787 _wcsicmp(dot, L".exe") == 0 || _wcsicmp(dot, L".com") == 0)
1788 result->st_mode |= 0111;
1789 }
1790 return 0;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001791}
1792
1793static int
Steve Dowercc16be82016-09-08 10:35:16 -07001794win32_xstat(const wchar_t *path, struct _Py_stat_struct *result, BOOL traverse)
Brian Curtinf5e76d02010-11-24 13:14:05 +00001795{
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001796 /* Protocol violation: we explicitly clear errno, instead of
1797 setting it to a POSIX error. Callers should use GetLastError. */
Brian Curtind25aef52011-06-13 15:16:04 -05001798 int code = win32_xstat_impl(path, result, traverse);
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001799 errno = 0;
1800 return code;
1801}
Brian Curtind25aef52011-06-13 15:16:04 -05001802/* About the following functions: win32_lstat_w, win32_stat, win32_stat_w
Brian Curtind40e6f72010-07-08 21:39:08 +00001803
1804 In Posix, stat automatically traverses symlinks and returns the stat
1805 structure for the target. In Windows, the equivalent GetFileAttributes by
1806 default does not traverse symlinks and instead returns attributes for
1807 the symlink.
1808
1809 Therefore, win32_lstat will get the attributes traditionally, and
1810 win32_stat will first explicitly resolve the symlink target and then will
Steve Dowercc16be82016-09-08 10:35:16 -07001811 call win32_lstat on that result. */
Brian Curtind40e6f72010-07-08 21:39:08 +00001812
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001813static int
Steve Dowercc16be82016-09-08 10:35:16 -07001814win32_lstat(const wchar_t* path, struct _Py_stat_struct *result)
Martin v. Löwis14694662006-02-03 12:54:16 +00001815{
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001816 return win32_xstat(path, result, FALSE);
Martin v. Löwis14694662006-02-03 12:54:16 +00001817}
1818
Victor Stinner8c62be82010-05-06 00:08:46 +00001819static int
Steve Dowercc16be82016-09-08 10:35:16 -07001820win32_stat(const wchar_t* path, struct _Py_stat_struct *result)
Brian Curtind40e6f72010-07-08 21:39:08 +00001821{
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001822 return win32_xstat(path, result, TRUE);
Brian Curtind40e6f72010-07-08 21:39:08 +00001823}
1824
Martin v. Löwis14694662006-02-03 12:54:16 +00001825#endif /* MS_WINDOWS */
1826
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001827PyDoc_STRVAR(stat_result__doc__,
Larry Hastings9cf065c2012-06-22 16:30:09 -07001828"stat_result: Result from stat, fstat, or lstat.\n\n\
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001829This object may be accessed either as a tuple of\n\
Fred Drakef7ce04d2002-06-20 18:31:21 +00001830 (mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime)\n\
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001831or via the attributes st_mode, st_ino, st_dev, st_nlink, st_uid, and so on.\n\
1832\n\
Hye-Shik Chang5f937a72005-06-02 13:09:30 +00001833Posix/windows: If your platform supports st_blksize, st_blocks, st_rdev,\n\
1834or st_flags, they are available as attributes only.\n\
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001835\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001836See os.stat for more information.");
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001837
1838static PyStructSequence_Field stat_result_fields[] = {
Victor Stinner8c62be82010-05-06 00:08:46 +00001839 {"st_mode", "protection bits"},
1840 {"st_ino", "inode"},
1841 {"st_dev", "device"},
1842 {"st_nlink", "number of hard links"},
1843 {"st_uid", "user ID of owner"},
1844 {"st_gid", "group ID of owner"},
1845 {"st_size", "total size, in bytes"},
1846 /* The NULL is replaced with PyStructSequence_UnnamedField later. */
1847 {NULL, "integer time of last access"},
1848 {NULL, "integer time of last modification"},
1849 {NULL, "integer time of last change"},
1850 {"st_atime", "time of last access"},
1851 {"st_mtime", "time of last modification"},
1852 {"st_ctime", "time of last change"},
Larry Hastings6fe20b32012-04-19 15:07:49 -07001853 {"st_atime_ns", "time of last access in nanoseconds"},
1854 {"st_mtime_ns", "time of last modification in nanoseconds"},
1855 {"st_ctime_ns", "time of last change in nanoseconds"},
Martin v. Löwis60a5d722002-10-16 20:28:25 +00001856#ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
Victor Stinner8c62be82010-05-06 00:08:46 +00001857 {"st_blksize", "blocksize for filesystem I/O"},
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001858#endif
Martin v. Löwis60a5d722002-10-16 20:28:25 +00001859#ifdef HAVE_STRUCT_STAT_ST_BLOCKS
Victor Stinner8c62be82010-05-06 00:08:46 +00001860 {"st_blocks", "number of blocks allocated"},
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001861#endif
Martin v. Löwis60a5d722002-10-16 20:28:25 +00001862#ifdef HAVE_STRUCT_STAT_ST_RDEV
Victor Stinner8c62be82010-05-06 00:08:46 +00001863 {"st_rdev", "device type (if inode device)"},
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001864#endif
Hye-Shik Chang5f937a72005-06-02 13:09:30 +00001865#ifdef HAVE_STRUCT_STAT_ST_FLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +00001866 {"st_flags", "user defined flags for file"},
Hye-Shik Chang5f937a72005-06-02 13:09:30 +00001867#endif
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00001868#ifdef HAVE_STRUCT_STAT_ST_GEN
Victor Stinner8c62be82010-05-06 00:08:46 +00001869 {"st_gen", "generation number"},
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00001870#endif
1871#ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME
Victor Stinner8c62be82010-05-06 00:08:46 +00001872 {"st_birthtime", "time of creation"},
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00001873#endif
Zachary Ware63f277b2014-06-19 09:46:37 -05001874#ifdef HAVE_STRUCT_STAT_ST_FILE_ATTRIBUTES
1875 {"st_file_attributes", "Windows file attribute bits"},
1876#endif
jcea6c51d512018-01-28 14:00:08 +01001877#ifdef HAVE_STRUCT_STAT_ST_FSTYPE
1878 {"st_fstype", "Type of filesystem"},
1879#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00001880 {0}
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001881};
1882
Martin v. Löwis60a5d722002-10-16 20:28:25 +00001883#ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
Larry Hastings6fe20b32012-04-19 15:07:49 -07001884#define ST_BLKSIZE_IDX 16
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001885#else
Larry Hastings6fe20b32012-04-19 15:07:49 -07001886#define ST_BLKSIZE_IDX 15
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001887#endif
1888
Martin v. Löwis60a5d722002-10-16 20:28:25 +00001889#ifdef HAVE_STRUCT_STAT_ST_BLOCKS
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001890#define ST_BLOCKS_IDX (ST_BLKSIZE_IDX+1)
1891#else
1892#define ST_BLOCKS_IDX ST_BLKSIZE_IDX
1893#endif
1894
Martin v. Löwis60a5d722002-10-16 20:28:25 +00001895#ifdef HAVE_STRUCT_STAT_ST_RDEV
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001896#define ST_RDEV_IDX (ST_BLOCKS_IDX+1)
1897#else
1898#define ST_RDEV_IDX ST_BLOCKS_IDX
1899#endif
1900
Hye-Shik Chang5f937a72005-06-02 13:09:30 +00001901#ifdef HAVE_STRUCT_STAT_ST_FLAGS
1902#define ST_FLAGS_IDX (ST_RDEV_IDX+1)
1903#else
1904#define ST_FLAGS_IDX ST_RDEV_IDX
1905#endif
1906
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00001907#ifdef HAVE_STRUCT_STAT_ST_GEN
Martin v. Löwisf09582e2005-08-14 21:42:34 +00001908#define ST_GEN_IDX (ST_FLAGS_IDX+1)
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00001909#else
Martin v. Löwisf09582e2005-08-14 21:42:34 +00001910#define ST_GEN_IDX ST_FLAGS_IDX
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00001911#endif
1912
1913#ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME
1914#define ST_BIRTHTIME_IDX (ST_GEN_IDX+1)
1915#else
1916#define ST_BIRTHTIME_IDX ST_GEN_IDX
1917#endif
1918
Zachary Ware63f277b2014-06-19 09:46:37 -05001919#ifdef HAVE_STRUCT_STAT_ST_FILE_ATTRIBUTES
1920#define ST_FILE_ATTRIBUTES_IDX (ST_BIRTHTIME_IDX+1)
1921#else
1922#define ST_FILE_ATTRIBUTES_IDX ST_BIRTHTIME_IDX
1923#endif
1924
jcea6c51d512018-01-28 14:00:08 +01001925#ifdef HAVE_STRUCT_STAT_ST_FSTYPE
1926#define ST_FSTYPE_IDX (ST_FILE_ATTRIBUTES_IDX+1)
1927#else
1928#define ST_FSTYPE_IDX ST_FILE_ATTRIBUTES_IDX
1929#endif
1930
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001931static PyStructSequence_Desc stat_result_desc = {
Victor Stinner8c62be82010-05-06 00:08:46 +00001932 "stat_result", /* name */
1933 stat_result__doc__, /* doc */
1934 stat_result_fields,
1935 10
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001936};
1937
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001938PyDoc_STRVAR(statvfs_result__doc__,
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001939"statvfs_result: Result from statvfs or fstatvfs.\n\n\
1940This object may be accessed either as a tuple of\n\
Fred Drakef7ce04d2002-06-20 18:31:21 +00001941 (bsize, frsize, blocks, bfree, bavail, files, ffree, favail, flag, namemax),\n\
Guido van Rossuma4dc73e2001-10-18 20:53:15 +00001942or via the attributes f_bsize, f_frsize, f_blocks, f_bfree, and so on.\n\
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001943\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001944See os.statvfs for more information.");
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001945
1946static PyStructSequence_Field statvfs_result_fields[] = {
Victor Stinner8c62be82010-05-06 00:08:46 +00001947 {"f_bsize", },
1948 {"f_frsize", },
1949 {"f_blocks", },
1950 {"f_bfree", },
1951 {"f_bavail", },
1952 {"f_files", },
1953 {"f_ffree", },
1954 {"f_favail", },
1955 {"f_flag", },
1956 {"f_namemax",},
Giuseppe Scrivano96a5e502017-12-14 23:46:46 +01001957 {"f_fsid", },
Victor Stinner8c62be82010-05-06 00:08:46 +00001958 {0}
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001959};
1960
1961static PyStructSequence_Desc statvfs_result_desc = {
Victor Stinner8c62be82010-05-06 00:08:46 +00001962 "statvfs_result", /* name */
1963 statvfs_result__doc__, /* doc */
1964 statvfs_result_fields,
1965 10
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001966};
1967
Ross Lagerwall7807c352011-03-17 20:20:30 +02001968#if defined(HAVE_WAITID) && !defined(__APPLE__)
1969PyDoc_STRVAR(waitid_result__doc__,
1970"waitid_result: Result from waitid.\n\n\
1971This object may be accessed either as a tuple of\n\
1972 (si_pid, si_uid, si_signo, si_status, si_code),\n\
1973or via the attributes si_pid, si_uid, and so on.\n\
1974\n\
1975See os.waitid for more information.");
1976
1977static PyStructSequence_Field waitid_result_fields[] = {
1978 {"si_pid", },
1979 {"si_uid", },
1980 {"si_signo", },
1981 {"si_status", },
1982 {"si_code", },
1983 {0}
1984};
1985
1986static PyStructSequence_Desc waitid_result_desc = {
1987 "waitid_result", /* name */
1988 waitid_result__doc__, /* doc */
1989 waitid_result_fields,
1990 5
1991};
Eddie Elizondo474eedf2018-11-13 04:09:31 -08001992static PyTypeObject* WaitidResultType;
Ross Lagerwall7807c352011-03-17 20:20:30 +02001993#endif
1994
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001995static int initialized;
Eddie Elizondo474eedf2018-11-13 04:09:31 -08001996static PyTypeObject* StatResultType;
1997static PyTypeObject* StatVFSResultType;
William Orr81574b82018-10-01 22:19:56 -07001998#if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
Eddie Elizondo474eedf2018-11-13 04:09:31 -08001999static PyTypeObject* SchedParamType;
Benjamin Petersonbad9c2f2011-08-02 18:42:14 -05002000#endif
Martin v. Löwisf607bda2002-10-16 18:27:39 +00002001static newfunc structseq_new;
2002
2003static PyObject *
2004statresult_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2005{
Victor Stinner8c62be82010-05-06 00:08:46 +00002006 PyStructSequence *result;
2007 int i;
Martin v. Löwisf607bda2002-10-16 18:27:39 +00002008
Victor Stinner8c62be82010-05-06 00:08:46 +00002009 result = (PyStructSequence*)structseq_new(type, args, kwds);
2010 if (!result)
2011 return NULL;
2012 /* If we have been initialized from a tuple,
2013 st_?time might be set to None. Initialize it
2014 from the int slots. */
2015 for (i = 7; i <= 9; i++) {
2016 if (result->ob_item[i+3] == Py_None) {
2017 Py_DECREF(Py_None);
2018 Py_INCREF(result->ob_item[i]);
2019 result->ob_item[i+3] = result->ob_item[i];
2020 }
2021 }
2022 return (PyObject*)result;
Martin v. Löwisf607bda2002-10-16 18:27:39 +00002023}
2024
2025
Larry Hastings6fe20b32012-04-19 15:07:49 -07002026static PyObject *billion = NULL;
2027
Martin v. Löwis94717ed2002-09-09 14:24:16 +00002028static void
Victor Stinner4195b5c2012-02-08 23:03:19 +01002029fill_time(PyObject *v, int index, time_t sec, unsigned long nsec)
Martin v. Löwis94717ed2002-09-09 14:24:16 +00002030{
Larry Hastings6fe20b32012-04-19 15:07:49 -07002031 PyObject *s = _PyLong_FromTime_t(sec);
2032 PyObject *ns_fractional = PyLong_FromUnsignedLong(nsec);
2033 PyObject *s_in_ns = NULL;
2034 PyObject *ns_total = NULL;
2035 PyObject *float_s = NULL;
2036
2037 if (!(s && ns_fractional))
2038 goto exit;
2039
2040 s_in_ns = PyNumber_Multiply(s, billion);
2041 if (!s_in_ns)
2042 goto exit;
2043
2044 ns_total = PyNumber_Add(s_in_ns, ns_fractional);
2045 if (!ns_total)
2046 goto exit;
2047
Victor Stinner01b5aab2017-10-24 02:02:00 -07002048 float_s = PyFloat_FromDouble(sec + 1e-9*nsec);
2049 if (!float_s) {
2050 goto exit;
Larry Hastings6fe20b32012-04-19 15:07:49 -07002051 }
2052
2053 PyStructSequence_SET_ITEM(v, index, s);
2054 PyStructSequence_SET_ITEM(v, index+3, float_s);
2055 PyStructSequence_SET_ITEM(v, index+6, ns_total);
2056 s = NULL;
2057 float_s = NULL;
2058 ns_total = NULL;
2059exit:
2060 Py_XDECREF(s);
2061 Py_XDECREF(ns_fractional);
2062 Py_XDECREF(s_in_ns);
2063 Py_XDECREF(ns_total);
2064 Py_XDECREF(float_s);
Martin v. Löwis94717ed2002-09-09 14:24:16 +00002065}
2066
Tim Peters5aa91602002-01-30 05:46:57 +00002067/* pack a system stat C structure into the Python stat tuple
Fred Drake699f3522000-06-29 21:12:41 +00002068 (used by posix_stat() and posix_fstat()) */
2069static PyObject*
Victor Stinner4195b5c2012-02-08 23:03:19 +01002070_pystat_fromstructstat(STRUCT_STAT *st)
Fred Drake699f3522000-06-29 21:12:41 +00002071{
Victor Stinner8c62be82010-05-06 00:08:46 +00002072 unsigned long ansec, mnsec, cnsec;
Eddie Elizondo474eedf2018-11-13 04:09:31 -08002073 PyObject *v = PyStructSequence_New(StatResultType);
Victor Stinner8c62be82010-05-06 00:08:46 +00002074 if (v == NULL)
2075 return NULL;
Fred Drake699f3522000-06-29 21:12:41 +00002076
Victor Stinner8c62be82010-05-06 00:08:46 +00002077 PyStructSequence_SET_ITEM(v, 0, PyLong_FromLong((long)st->st_mode));
Victor Stinner0f6d7332017-03-09 17:34:28 +01002078 Py_BUILD_ASSERT(sizeof(unsigned long long) >= sizeof(st->st_ino));
xdegaye50e86032017-05-22 11:15:08 +02002079 PyStructSequence_SET_ITEM(v, 1, PyLong_FromUnsignedLongLong(st->st_ino));
Serhiy Storchaka404fa922013-01-02 18:22:23 +02002080#ifdef MS_WINDOWS
2081 PyStructSequence_SET_ITEM(v, 2, PyLong_FromUnsignedLong(st->st_dev));
Fred Drake699f3522000-06-29 21:12:41 +00002082#else
Serhiy Storchakab2653b32015-01-18 11:12:11 +02002083 PyStructSequence_SET_ITEM(v, 2, _PyLong_FromDev(st->st_dev));
Fred Drake699f3522000-06-29 21:12:41 +00002084#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00002085 PyStructSequence_SET_ITEM(v, 3, PyLong_FromLong((long)st->st_nlink));
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02002086#if defined(MS_WINDOWS)
2087 PyStructSequence_SET_ITEM(v, 4, PyLong_FromLong(0));
2088 PyStructSequence_SET_ITEM(v, 5, PyLong_FromLong(0));
2089#else
2090 PyStructSequence_SET_ITEM(v, 4, _PyLong_FromUid(st->st_uid));
2091 PyStructSequence_SET_ITEM(v, 5, _PyLong_FromGid(st->st_gid));
2092#endif
xdegaye50e86032017-05-22 11:15:08 +02002093 Py_BUILD_ASSERT(sizeof(long long) >= sizeof(st->st_size));
2094 PyStructSequence_SET_ITEM(v, 6, PyLong_FromLongLong(st->st_size));
Martin v. Löwis94717ed2002-09-09 14:24:16 +00002095
Martin v. Löwis14694662006-02-03 12:54:16 +00002096#if defined(HAVE_STAT_TV_NSEC)
Victor Stinner8c62be82010-05-06 00:08:46 +00002097 ansec = st->st_atim.tv_nsec;
2098 mnsec = st->st_mtim.tv_nsec;
2099 cnsec = st->st_ctim.tv_nsec;
Martin v. Löwis14694662006-02-03 12:54:16 +00002100#elif defined(HAVE_STAT_TV_NSEC2)
Victor Stinner8c62be82010-05-06 00:08:46 +00002101 ansec = st->st_atimespec.tv_nsec;
2102 mnsec = st->st_mtimespec.tv_nsec;
2103 cnsec = st->st_ctimespec.tv_nsec;
Martin v. Löwis14694662006-02-03 12:54:16 +00002104#elif defined(HAVE_STAT_NSEC)
Victor Stinner8c62be82010-05-06 00:08:46 +00002105 ansec = st->st_atime_nsec;
2106 mnsec = st->st_mtime_nsec;
2107 cnsec = st->st_ctime_nsec;
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002108#else
Victor Stinner8c62be82010-05-06 00:08:46 +00002109 ansec = mnsec = cnsec = 0;
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002110#endif
Victor Stinner4195b5c2012-02-08 23:03:19 +01002111 fill_time(v, 7, st->st_atime, ansec);
2112 fill_time(v, 8, st->st_mtime, mnsec);
2113 fill_time(v, 9, st->st_ctime, cnsec);
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002114
Martin v. Löwis60a5d722002-10-16 20:28:25 +00002115#ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
Victor Stinner8c62be82010-05-06 00:08:46 +00002116 PyStructSequence_SET_ITEM(v, ST_BLKSIZE_IDX,
2117 PyLong_FromLong((long)st->st_blksize));
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002118#endif
Martin v. Löwis60a5d722002-10-16 20:28:25 +00002119#ifdef HAVE_STRUCT_STAT_ST_BLOCKS
Victor Stinner8c62be82010-05-06 00:08:46 +00002120 PyStructSequence_SET_ITEM(v, ST_BLOCKS_IDX,
2121 PyLong_FromLong((long)st->st_blocks));
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002122#endif
Martin v. Löwis60a5d722002-10-16 20:28:25 +00002123#ifdef HAVE_STRUCT_STAT_ST_RDEV
Victor Stinner8c62be82010-05-06 00:08:46 +00002124 PyStructSequence_SET_ITEM(v, ST_RDEV_IDX,
2125 PyLong_FromLong((long)st->st_rdev));
Fred Drake699f3522000-06-29 21:12:41 +00002126#endif
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002127#ifdef HAVE_STRUCT_STAT_ST_GEN
Victor Stinner8c62be82010-05-06 00:08:46 +00002128 PyStructSequence_SET_ITEM(v, ST_GEN_IDX,
2129 PyLong_FromLong((long)st->st_gen));
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002130#endif
2131#ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME
Victor Stinner8c62be82010-05-06 00:08:46 +00002132 {
Victor Stinner4195b5c2012-02-08 23:03:19 +01002133 PyObject *val;
2134 unsigned long bsec,bnsec;
2135 bsec = (long)st->st_birthtime;
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002136#ifdef HAVE_STAT_TV_NSEC2
Victor Stinner4195b5c2012-02-08 23:03:19 +01002137 bnsec = st->st_birthtimespec.tv_nsec;
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002138#else
Victor Stinner4195b5c2012-02-08 23:03:19 +01002139 bnsec = 0;
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002140#endif
Victor Stinner01b5aab2017-10-24 02:02:00 -07002141 val = PyFloat_FromDouble(bsec + 1e-9*bnsec);
Victor Stinner4195b5c2012-02-08 23:03:19 +01002142 PyStructSequence_SET_ITEM(v, ST_BIRTHTIME_IDX,
2143 val);
Victor Stinner8c62be82010-05-06 00:08:46 +00002144 }
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002145#endif
Hye-Shik Chang5f937a72005-06-02 13:09:30 +00002146#ifdef HAVE_STRUCT_STAT_ST_FLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +00002147 PyStructSequence_SET_ITEM(v, ST_FLAGS_IDX,
2148 PyLong_FromLong((long)st->st_flags));
Hye-Shik Chang5f937a72005-06-02 13:09:30 +00002149#endif
Zachary Ware63f277b2014-06-19 09:46:37 -05002150#ifdef HAVE_STRUCT_STAT_ST_FILE_ATTRIBUTES
2151 PyStructSequence_SET_ITEM(v, ST_FILE_ATTRIBUTES_IDX,
2152 PyLong_FromUnsignedLong(st->st_file_attributes));
2153#endif
jcea6c51d512018-01-28 14:00:08 +01002154#ifdef HAVE_STRUCT_STAT_ST_FSTYPE
2155 PyStructSequence_SET_ITEM(v, ST_FSTYPE_IDX,
2156 PyUnicode_FromString(st->st_fstype));
2157#endif
Fred Drake699f3522000-06-29 21:12:41 +00002158
Victor Stinner8c62be82010-05-06 00:08:46 +00002159 if (PyErr_Occurred()) {
2160 Py_DECREF(v);
2161 return NULL;
2162 }
Fred Drake699f3522000-06-29 21:12:41 +00002163
Victor Stinner8c62be82010-05-06 00:08:46 +00002164 return v;
Fred Drake699f3522000-06-29 21:12:41 +00002165}
2166
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002167/* POSIX methods */
2168
Guido van Rossum94f6f721999-01-06 18:42:14 +00002169
2170static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02002171posix_do_stat(const char *function_name, path_t *path,
Larry Hastings9cf065c2012-06-22 16:30:09 -07002172 int dir_fd, int follow_symlinks)
Guido van Rossum94f6f721999-01-06 18:42:14 +00002173{
Larry Hastings9cf065c2012-06-22 16:30:09 -07002174 STRUCT_STAT st;
2175 int result;
2176
2177#if !defined(MS_WINDOWS) && !defined(HAVE_FSTATAT) && !defined(HAVE_LSTAT)
2178 if (follow_symlinks_specified(function_name, follow_symlinks))
2179 return NULL;
2180#endif
2181
2182 if (path_and_dir_fd_invalid("stat", path, dir_fd) ||
2183 dir_fd_and_fd_invalid("stat", dir_fd, path->fd) ||
2184 fd_and_follow_symlinks_invalid("stat", path->fd, follow_symlinks))
2185 return NULL;
2186
2187 Py_BEGIN_ALLOW_THREADS
2188 if (path->fd != -1)
2189 result = FSTAT(path->fd, &st);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002190#ifdef MS_WINDOWS
Steve Dower513d7472016-09-08 10:41:50 -07002191 else if (follow_symlinks)
Steve Dowercc16be82016-09-08 10:35:16 -07002192 result = win32_stat(path->wide, &st);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002193 else
Steve Dowercc16be82016-09-08 10:35:16 -07002194 result = win32_lstat(path->wide, &st);
2195#else
2196 else
2197#if defined(HAVE_LSTAT)
Larry Hastings9cf065c2012-06-22 16:30:09 -07002198 if ((!follow_symlinks) && (dir_fd == DEFAULT_DIR_FD))
2199 result = LSTAT(path->narrow, &st);
2200 else
Steve Dowercc16be82016-09-08 10:35:16 -07002201#endif /* HAVE_LSTAT */
Larry Hastings9cf065c2012-06-22 16:30:09 -07002202#ifdef HAVE_FSTATAT
2203 if ((dir_fd != DEFAULT_DIR_FD) || !follow_symlinks)
2204 result = fstatat(dir_fd, path->narrow, &st,
2205 follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW);
2206 else
Steve Dowercc16be82016-09-08 10:35:16 -07002207#endif /* HAVE_FSTATAT */
Larry Hastings9cf065c2012-06-22 16:30:09 -07002208 result = STAT(path->narrow, &st);
Steve Dowercc16be82016-09-08 10:35:16 -07002209#endif /* MS_WINDOWS */
Larry Hastings9cf065c2012-06-22 16:30:09 -07002210 Py_END_ALLOW_THREADS
2211
Victor Stinner292c8352012-10-30 02:17:38 +01002212 if (result != 0) {
2213 return path_error(path);
2214 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07002215
2216 return _pystat_fromstructstat(&st);
2217}
2218
Larry Hastings2f936352014-08-05 14:04:04 +10002219/*[python input]
2220
2221for s in """
2222
2223FACCESSAT
2224FCHMODAT
2225FCHOWNAT
2226FSTATAT
2227LINKAT
2228MKDIRAT
2229MKFIFOAT
2230MKNODAT
2231OPENAT
2232READLINKAT
2233SYMLINKAT
2234UNLINKAT
2235
2236""".strip().split():
2237 s = s.strip()
2238 print("""
2239#ifdef HAVE_{s}
2240 #define {s}_DIR_FD_CONVERTER dir_fd_converter
Larry Hastings31826802013-10-19 00:09:25 -07002241#else
Larry Hastings2f936352014-08-05 14:04:04 +10002242 #define {s}_DIR_FD_CONVERTER dir_fd_unavailable
Larry Hastings31826802013-10-19 00:09:25 -07002243#endif
Larry Hastings2f936352014-08-05 14:04:04 +10002244""".rstrip().format(s=s))
2245
2246for s in """
2247
2248FCHDIR
2249FCHMOD
2250FCHOWN
2251FDOPENDIR
2252FEXECVE
2253FPATHCONF
2254FSTATVFS
2255FTRUNCATE
2256
2257""".strip().split():
2258 s = s.strip()
2259 print("""
2260#ifdef HAVE_{s}
2261 #define PATH_HAVE_{s} 1
2262#else
2263 #define PATH_HAVE_{s} 0
2264#endif
2265
2266""".rstrip().format(s=s))
2267[python start generated code]*/
2268
2269#ifdef HAVE_FACCESSAT
2270 #define FACCESSAT_DIR_FD_CONVERTER dir_fd_converter
2271#else
2272 #define FACCESSAT_DIR_FD_CONVERTER dir_fd_unavailable
2273#endif
2274
2275#ifdef HAVE_FCHMODAT
2276 #define FCHMODAT_DIR_FD_CONVERTER dir_fd_converter
2277#else
2278 #define FCHMODAT_DIR_FD_CONVERTER dir_fd_unavailable
2279#endif
2280
2281#ifdef HAVE_FCHOWNAT
2282 #define FCHOWNAT_DIR_FD_CONVERTER dir_fd_converter
2283#else
2284 #define FCHOWNAT_DIR_FD_CONVERTER dir_fd_unavailable
2285#endif
2286
2287#ifdef HAVE_FSTATAT
2288 #define FSTATAT_DIR_FD_CONVERTER dir_fd_converter
2289#else
2290 #define FSTATAT_DIR_FD_CONVERTER dir_fd_unavailable
2291#endif
2292
2293#ifdef HAVE_LINKAT
2294 #define LINKAT_DIR_FD_CONVERTER dir_fd_converter
2295#else
2296 #define LINKAT_DIR_FD_CONVERTER dir_fd_unavailable
2297#endif
2298
2299#ifdef HAVE_MKDIRAT
2300 #define MKDIRAT_DIR_FD_CONVERTER dir_fd_converter
2301#else
2302 #define MKDIRAT_DIR_FD_CONVERTER dir_fd_unavailable
2303#endif
2304
2305#ifdef HAVE_MKFIFOAT
2306 #define MKFIFOAT_DIR_FD_CONVERTER dir_fd_converter
2307#else
2308 #define MKFIFOAT_DIR_FD_CONVERTER dir_fd_unavailable
2309#endif
2310
2311#ifdef HAVE_MKNODAT
2312 #define MKNODAT_DIR_FD_CONVERTER dir_fd_converter
2313#else
2314 #define MKNODAT_DIR_FD_CONVERTER dir_fd_unavailable
2315#endif
2316
2317#ifdef HAVE_OPENAT
2318 #define OPENAT_DIR_FD_CONVERTER dir_fd_converter
2319#else
2320 #define OPENAT_DIR_FD_CONVERTER dir_fd_unavailable
2321#endif
2322
2323#ifdef HAVE_READLINKAT
2324 #define READLINKAT_DIR_FD_CONVERTER dir_fd_converter
2325#else
2326 #define READLINKAT_DIR_FD_CONVERTER dir_fd_unavailable
2327#endif
2328
2329#ifdef HAVE_SYMLINKAT
2330 #define SYMLINKAT_DIR_FD_CONVERTER dir_fd_converter
2331#else
2332 #define SYMLINKAT_DIR_FD_CONVERTER dir_fd_unavailable
2333#endif
2334
2335#ifdef HAVE_UNLINKAT
2336 #define UNLINKAT_DIR_FD_CONVERTER dir_fd_converter
2337#else
2338 #define UNLINKAT_DIR_FD_CONVERTER dir_fd_unavailable
2339#endif
2340
2341#ifdef HAVE_FCHDIR
2342 #define PATH_HAVE_FCHDIR 1
2343#else
2344 #define PATH_HAVE_FCHDIR 0
2345#endif
2346
2347#ifdef HAVE_FCHMOD
2348 #define PATH_HAVE_FCHMOD 1
2349#else
2350 #define PATH_HAVE_FCHMOD 0
2351#endif
2352
2353#ifdef HAVE_FCHOWN
2354 #define PATH_HAVE_FCHOWN 1
2355#else
2356 #define PATH_HAVE_FCHOWN 0
2357#endif
2358
2359#ifdef HAVE_FDOPENDIR
2360 #define PATH_HAVE_FDOPENDIR 1
2361#else
2362 #define PATH_HAVE_FDOPENDIR 0
2363#endif
2364
2365#ifdef HAVE_FEXECVE
2366 #define PATH_HAVE_FEXECVE 1
2367#else
2368 #define PATH_HAVE_FEXECVE 0
2369#endif
2370
2371#ifdef HAVE_FPATHCONF
2372 #define PATH_HAVE_FPATHCONF 1
2373#else
2374 #define PATH_HAVE_FPATHCONF 0
2375#endif
2376
2377#ifdef HAVE_FSTATVFS
2378 #define PATH_HAVE_FSTATVFS 1
2379#else
2380 #define PATH_HAVE_FSTATVFS 0
2381#endif
2382
2383#ifdef HAVE_FTRUNCATE
2384 #define PATH_HAVE_FTRUNCATE 1
2385#else
2386 #define PATH_HAVE_FTRUNCATE 0
2387#endif
2388/*[python end generated code: output=4bd4f6f7d41267f1 input=80b4c890b6774ea5]*/
Larry Hastings31826802013-10-19 00:09:25 -07002389
Steve Dowerfe0a41a2015-03-20 19:50:46 -07002390#ifdef MS_WINDOWS
2391 #undef PATH_HAVE_FTRUNCATE
2392 #define PATH_HAVE_FTRUNCATE 1
2393#endif
Larry Hastings31826802013-10-19 00:09:25 -07002394
Larry Hastings61272b72014-01-07 12:41:53 -08002395/*[python input]
Larry Hastings31826802013-10-19 00:09:25 -07002396
2397class path_t_converter(CConverter):
2398
2399 type = "path_t"
2400 impl_by_reference = True
2401 parse_by_reference = True
2402
2403 converter = 'path_converter'
2404
2405 def converter_init(self, *, allow_fd=False, nullable=False):
Larry Hastings31826802013-10-19 00:09:25 -07002406 # right now path_t doesn't support default values.
2407 # to support a default value, you'll need to override initialize().
Larry Hastings2f936352014-08-05 14:04:04 +10002408 if self.default not in (unspecified, None):
Larry Hastings7726ac92014-01-31 22:03:12 -08002409 fail("Can't specify a default to the path_t converter!")
Larry Hastings31826802013-10-19 00:09:25 -07002410
Larry Hastings2f936352014-08-05 14:04:04 +10002411 if self.c_default not in (None, 'Py_None'):
2412 raise RuntimeError("Can't specify a c_default to the path_t converter!")
Larry Hastings31826802013-10-19 00:09:25 -07002413
2414 self.nullable = nullable
2415 self.allow_fd = allow_fd
2416
Larry Hastings7726ac92014-01-31 22:03:12 -08002417 def pre_render(self):
2418 def strify(value):
Larry Hastings2f936352014-08-05 14:04:04 +10002419 if isinstance(value, str):
2420 return value
Larry Hastings7726ac92014-01-31 22:03:12 -08002421 return str(int(bool(value)))
2422
2423 # add self.py_name here when merging with posixmodule conversion
Larry Hastings2f936352014-08-05 14:04:04 +10002424 self.c_default = 'PATH_T_INITIALIZE("{}", "{}", {}, {})'.format(
Larry Hastings31826802013-10-19 00:09:25 -07002425 self.function.name,
Larry Hastings2f936352014-08-05 14:04:04 +10002426 self.name,
Larry Hastings7726ac92014-01-31 22:03:12 -08002427 strify(self.nullable),
2428 strify(self.allow_fd),
Larry Hastings31826802013-10-19 00:09:25 -07002429 )
2430
2431 def cleanup(self):
2432 return "path_cleanup(&" + self.name + ");\n"
2433
2434
2435class dir_fd_converter(CConverter):
2436 type = 'int'
Larry Hastings31826802013-10-19 00:09:25 -07002437
Larry Hastings2f936352014-08-05 14:04:04 +10002438 def converter_init(self, requires=None):
Larry Hastings31826802013-10-19 00:09:25 -07002439 if self.default in (unspecified, None):
2440 self.c_default = 'DEFAULT_DIR_FD'
Larry Hastings2f936352014-08-05 14:04:04 +10002441 if isinstance(requires, str):
2442 self.converter = requires.upper() + '_DIR_FD_CONVERTER'
2443 else:
2444 self.converter = 'dir_fd_converter'
Larry Hastings31826802013-10-19 00:09:25 -07002445
Larry Hastings2f936352014-08-05 14:04:04 +10002446class fildes_converter(CConverter):
2447 type = 'int'
2448 converter = 'fildes_converter'
2449
2450class uid_t_converter(CConverter):
2451 type = "uid_t"
2452 converter = '_Py_Uid_Converter'
2453
2454class gid_t_converter(CConverter):
2455 type = "gid_t"
2456 converter = '_Py_Gid_Converter'
2457
Serhiy Storchakaacdb7c12015-01-18 11:17:39 +02002458class dev_t_converter(CConverter):
2459 type = 'dev_t'
2460 converter = '_Py_Dev_Converter'
2461
2462class dev_t_return_converter(unsigned_long_return_converter):
2463 type = 'dev_t'
2464 conversion_fn = '_PyLong_FromDev'
2465 unsigned_cast = '(dev_t)'
2466
Larry Hastings2f936352014-08-05 14:04:04 +10002467class FSConverter_converter(CConverter):
2468 type = 'PyObject *'
2469 converter = 'PyUnicode_FSConverter'
2470 def converter_init(self):
2471 if self.default is not unspecified:
2472 fail("FSConverter_converter does not support default values")
2473 self.c_default = 'NULL'
2474
2475 def cleanup(self):
2476 return "Py_XDECREF(" + self.name + ");\n"
2477
2478class pid_t_converter(CConverter):
2479 type = 'pid_t'
2480 format_unit = '" _Py_PARSE_PID "'
2481
2482class idtype_t_converter(int_converter):
2483 type = 'idtype_t'
2484
2485class id_t_converter(CConverter):
2486 type = 'id_t'
2487 format_unit = '" _Py_PARSE_PID "'
2488
Benjamin Petersonca470632016-09-06 13:47:26 -07002489class intptr_t_converter(CConverter):
2490 type = 'intptr_t'
Larry Hastings2f936352014-08-05 14:04:04 +10002491 format_unit = '" _Py_PARSE_INTPTR "'
2492
2493class Py_off_t_converter(CConverter):
2494 type = 'Py_off_t'
2495 converter = 'Py_off_t_converter'
2496
2497class Py_off_t_return_converter(long_return_converter):
2498 type = 'Py_off_t'
2499 conversion_fn = 'PyLong_FromPy_off_t'
2500
2501class path_confname_converter(CConverter):
2502 type="int"
2503 converter="conv_path_confname"
2504
2505class confstr_confname_converter(path_confname_converter):
2506 converter='conv_confstr_confname'
2507
2508class sysconf_confname_converter(path_confname_converter):
2509 converter="conv_sysconf_confname"
2510
2511class sched_param_converter(CConverter):
2512 type = 'struct sched_param'
2513 converter = 'convert_sched_param'
2514 impl_by_reference = True;
Larry Hastings31826802013-10-19 00:09:25 -07002515
Larry Hastings61272b72014-01-07 12:41:53 -08002516[python start generated code]*/
Victor Stinner581139c2016-09-06 15:54:20 -07002517/*[python end generated code: output=da39a3ee5e6b4b0d input=418fce0e01144461]*/
Larry Hastings31826802013-10-19 00:09:25 -07002518
Larry Hastings61272b72014-01-07 12:41:53 -08002519/*[clinic input]
Larry Hastings31826802013-10-19 00:09:25 -07002520
Larry Hastings2a727912014-01-16 11:32:01 -08002521os.stat
Larry Hastings31826802013-10-19 00:09:25 -07002522
2523 path : path_t(allow_fd=True)
BNMetricsb9427072018-11-02 15:20:19 +00002524 Path to be examined; can be string, bytes, a path-like object or
Xiang Zhang4459e002017-01-22 13:04:17 +08002525 open-file-descriptor int.
Larry Hastings31826802013-10-19 00:09:25 -07002526
2527 *
2528
Larry Hastings2f936352014-08-05 14:04:04 +10002529 dir_fd : dir_fd(requires='fstatat') = None
Larry Hastings31826802013-10-19 00:09:25 -07002530 If not None, it should be a file descriptor open to a directory,
2531 and path should be a relative string; path will then be relative to
2532 that directory.
2533
2534 follow_symlinks: bool = True
2535 If False, and the last element of the path is a symbolic link,
2536 stat will examine the symbolic link itself instead of the file
2537 the link points to.
2538
2539Perform a stat system call on the given path.
2540
2541dir_fd and follow_symlinks may not be implemented
2542 on your platform. If they are unavailable, using them will raise a
2543 NotImplementedError.
2544
2545It's an error to use dir_fd or follow_symlinks when specifying path as
2546 an open file descriptor.
2547
Larry Hastings61272b72014-01-07 12:41:53 -08002548[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -07002549
Larry Hastings31826802013-10-19 00:09:25 -07002550static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002551os_stat_impl(PyObject *module, path_t *path, int dir_fd, int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +00002552/*[clinic end generated code: output=7d4976e6f18a59c5 input=01d362ebcc06996b]*/
Larry Hastings31826802013-10-19 00:09:25 -07002553{
2554 return posix_do_stat("stat", path, dir_fd, follow_symlinks);
2555}
2556
Larry Hastings2f936352014-08-05 14:04:04 +10002557
2558/*[clinic input]
2559os.lstat
2560
2561 path : path_t
2562
2563 *
2564
2565 dir_fd : dir_fd(requires='fstatat') = None
2566
2567Perform a stat system call on the given path, without following symbolic links.
2568
2569Like stat(), but do not follow symbolic links.
2570Equivalent to stat(path, follow_symlinks=False).
2571[clinic start generated code]*/
2572
Larry Hastings2f936352014-08-05 14:04:04 +10002573static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002574os_lstat_impl(PyObject *module, path_t *path, int dir_fd)
2575/*[clinic end generated code: output=ef82a5d35ce8ab37 input=0b7474765927b925]*/
Larry Hastings2f936352014-08-05 14:04:04 +10002576{
2577 int follow_symlinks = 0;
2578 return posix_do_stat("lstat", path, dir_fd, follow_symlinks);
2579}
Larry Hastings31826802013-10-19 00:09:25 -07002580
Larry Hastings2f936352014-08-05 14:04:04 +10002581
Larry Hastings61272b72014-01-07 12:41:53 -08002582/*[clinic input]
Larry Hastings2f936352014-08-05 14:04:04 +10002583os.access -> bool
Larry Hastings31826802013-10-19 00:09:25 -07002584
Benjamin Peterson768f3b42016-09-05 15:29:33 -07002585 path: path_t
BNMetricsb9427072018-11-02 15:20:19 +00002586 Path to be tested; can be string, bytes, or a path-like object.
Larry Hastings31826802013-10-19 00:09:25 -07002587
2588 mode: int
2589 Operating-system mode bitfield. Can be F_OK to test existence,
2590 or the inclusive-OR of R_OK, W_OK, and X_OK.
2591
2592 *
2593
Larry Hastings2f936352014-08-05 14:04:04 +10002594 dir_fd : dir_fd(requires='faccessat') = None
Larry Hastings31826802013-10-19 00:09:25 -07002595 If not None, it should be a file descriptor open to a directory,
2596 and path should be relative; path will then be relative to that
2597 directory.
2598
2599 effective_ids: bool = False
2600 If True, access will use the effective uid/gid instead of
2601 the real uid/gid.
2602
2603 follow_symlinks: bool = True
2604 If False, and the last element of the path is a symbolic link,
2605 access will examine the symbolic link itself instead of the file
2606 the link points to.
2607
2608Use the real uid/gid to test for access to a path.
2609
2610{parameters}
2611dir_fd, effective_ids, and follow_symlinks may not be implemented
2612 on your platform. If they are unavailable, using them will raise a
2613 NotImplementedError.
2614
2615Note that most operations will use the effective uid/gid, therefore this
2616 routine can be used in a suid/sgid environment to test if the invoking user
2617 has the specified access to the path.
2618
Larry Hastings61272b72014-01-07 12:41:53 -08002619[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -07002620
Larry Hastings2f936352014-08-05 14:04:04 +10002621static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002622os_access_impl(PyObject *module, path_t *path, int mode, int dir_fd,
Larry Hastings89964c42015-04-14 18:07:59 -04002623 int effective_ids, int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +00002624/*[clinic end generated code: output=cf84158bc90b1a77 input=3ffe4e650ee3bf20]*/
Larry Hastings31826802013-10-19 00:09:25 -07002625{
Larry Hastings2f936352014-08-05 14:04:04 +10002626 int return_value;
Victor Stinner8c62be82010-05-06 00:08:46 +00002627
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00002628#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +00002629 DWORD attr;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002630#else
Larry Hastings9cf065c2012-06-22 16:30:09 -07002631 int result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002632#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -07002633
Larry Hastings9cf065c2012-06-22 16:30:09 -07002634#ifndef HAVE_FACCESSAT
2635 if (follow_symlinks_specified("access", follow_symlinks))
Larry Hastings2f936352014-08-05 14:04:04 +10002636 return -1;
Larry Hastings9cf065c2012-06-22 16:30:09 -07002637
2638 if (effective_ids) {
2639 argument_unavailable_error("access", "effective_ids");
Larry Hastings2f936352014-08-05 14:04:04 +10002640 return -1;
Larry Hastings9cf065c2012-06-22 16:30:09 -07002641 }
2642#endif
2643
2644#ifdef MS_WINDOWS
2645 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -07002646 attr = GetFileAttributesW(path->wide);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002647 Py_END_ALLOW_THREADS
2648
2649 /*
Georg Brandlf7875592012-06-24 13:58:31 +02002650 * Access is possible if
Larry Hastings9cf065c2012-06-22 16:30:09 -07002651 * * we didn't get a -1, and
2652 * * write access wasn't requested,
2653 * * or the file isn't read-only,
2654 * * or it's a directory.
2655 * (Directories cannot be read-only on Windows.)
2656 */
Larry Hastings2f936352014-08-05 14:04:04 +10002657 return_value = (attr != INVALID_FILE_ATTRIBUTES) &&
Georg Brandl5bb7aa92012-06-23 12:48:40 +02002658 (!(mode & 2) ||
Larry Hastings9cf065c2012-06-22 16:30:09 -07002659 !(attr & FILE_ATTRIBUTE_READONLY) ||
Larry Hastings2f936352014-08-05 14:04:04 +10002660 (attr & FILE_ATTRIBUTE_DIRECTORY));
Larry Hastings9cf065c2012-06-22 16:30:09 -07002661#else
2662
2663 Py_BEGIN_ALLOW_THREADS
2664#ifdef HAVE_FACCESSAT
2665 if ((dir_fd != DEFAULT_DIR_FD) ||
2666 effective_ids ||
2667 !follow_symlinks) {
2668 int flags = 0;
2669 if (!follow_symlinks)
2670 flags |= AT_SYMLINK_NOFOLLOW;
2671 if (effective_ids)
2672 flags |= AT_EACCESS;
Larry Hastings31826802013-10-19 00:09:25 -07002673 result = faccessat(dir_fd, path->narrow, mode, flags);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002674 }
2675 else
2676#endif
Larry Hastings31826802013-10-19 00:09:25 -07002677 result = access(path->narrow, mode);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002678 Py_END_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10002679 return_value = !result;
Larry Hastings9cf065c2012-06-22 16:30:09 -07002680#endif
2681
Larry Hastings9cf065c2012-06-22 16:30:09 -07002682 return return_value;
Guido van Rossum94f6f721999-01-06 18:42:14 +00002683}
2684
Guido van Rossumd371ff11999-01-25 16:12:23 +00002685#ifndef F_OK
2686#define F_OK 0
2687#endif
2688#ifndef R_OK
2689#define R_OK 4
2690#endif
2691#ifndef W_OK
2692#define W_OK 2
2693#endif
2694#ifndef X_OK
2695#define X_OK 1
2696#endif
2697
Larry Hastings31826802013-10-19 00:09:25 -07002698
Guido van Rossumd371ff11999-01-25 16:12:23 +00002699#ifdef HAVE_TTYNAME
Larry Hastings61272b72014-01-07 12:41:53 -08002700/*[clinic input]
Serhiy Storchaka4db62e12018-12-17 16:47:45 +02002701os.ttyname
Larry Hastings31826802013-10-19 00:09:25 -07002702
2703 fd: int
2704 Integer file descriptor handle.
2705
2706 /
2707
2708Return the name of the terminal device connected to 'fd'.
Larry Hastings61272b72014-01-07 12:41:53 -08002709[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -07002710
Serhiy Storchaka4db62e12018-12-17 16:47:45 +02002711static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002712os_ttyname_impl(PyObject *module, int fd)
Serhiy Storchaka4db62e12018-12-17 16:47:45 +02002713/*[clinic end generated code: output=c424d2e9d1cd636a input=9ff5a58b08115c55]*/
Larry Hastings31826802013-10-19 00:09:25 -07002714{
2715 char *ret;
Guido van Rossum94f6f721999-01-06 18:42:14 +00002716
Larry Hastings31826802013-10-19 00:09:25 -07002717 ret = ttyname(fd);
Serhiy Storchaka4db62e12018-12-17 16:47:45 +02002718 if (ret == NULL) {
2719 return posix_error();
2720 }
2721 return PyUnicode_DecodeFSDefault(ret);
Guido van Rossum94f6f721999-01-06 18:42:14 +00002722}
Guido van Rossumd371ff11999-01-25 16:12:23 +00002723#endif
Guido van Rossum94f6f721999-01-06 18:42:14 +00002724
Fred Drake5ab8eaf1999-12-09 21:13:07 +00002725#ifdef HAVE_CTERMID
Larry Hastings2f936352014-08-05 14:04:04 +10002726/*[clinic input]
2727os.ctermid
2728
2729Return the name of the controlling terminal for this process.
2730[clinic start generated code]*/
2731
Larry Hastings2f936352014-08-05 14:04:04 +10002732static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002733os_ctermid_impl(PyObject *module)
2734/*[clinic end generated code: output=02f017e6c9e620db input=3b87fdd52556382d]*/
Fred Drake5ab8eaf1999-12-09 21:13:07 +00002735{
Victor Stinner8c62be82010-05-06 00:08:46 +00002736 char *ret;
2737 char buffer[L_ctermid];
Fred Drake5ab8eaf1999-12-09 21:13:07 +00002738
Greg Wardb48bc172000-03-01 21:51:56 +00002739#ifdef USE_CTERMID_R
Victor Stinner8c62be82010-05-06 00:08:46 +00002740 ret = ctermid_r(buffer);
Fred Drake5ab8eaf1999-12-09 21:13:07 +00002741#else
Victor Stinner8c62be82010-05-06 00:08:46 +00002742 ret = ctermid(buffer);
Fred Drake5ab8eaf1999-12-09 21:13:07 +00002743#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00002744 if (ret == NULL)
2745 return posix_error();
Victor Stinner5fe6de82010-08-15 09:12:51 +00002746 return PyUnicode_DecodeFSDefault(buffer);
Fred Drake5ab8eaf1999-12-09 21:13:07 +00002747}
Larry Hastings2f936352014-08-05 14:04:04 +10002748#endif /* HAVE_CTERMID */
Fred Drake5ab8eaf1999-12-09 21:13:07 +00002749
Larry Hastings2f936352014-08-05 14:04:04 +10002750
2751/*[clinic input]
2752os.chdir
2753
2754 path: path_t(allow_fd='PATH_HAVE_FCHDIR')
2755
2756Change the current working directory to the specified path.
2757
2758path may always be specified as a string.
2759On some platforms, path may also be specified as an open file descriptor.
2760 If this functionality is unavailable, using it raises an exception.
2761[clinic start generated code]*/
2762
Larry Hastings2f936352014-08-05 14:04:04 +10002763static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002764os_chdir_impl(PyObject *module, path_t *path)
2765/*[clinic end generated code: output=3be6400eee26eaae input=1a4a15b4d12cb15d]*/
Larry Hastings2f936352014-08-05 14:04:04 +10002766{
2767 int result;
Larry Hastings9cf065c2012-06-22 16:30:09 -07002768
2769 Py_BEGIN_ALLOW_THREADS
2770#ifdef MS_WINDOWS
Steve Dowercc16be82016-09-08 10:35:16 -07002771 /* on unix, success = 0, on windows, success = !0 */
2772 result = !win32_wchdir(path->wide);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002773#else
2774#ifdef HAVE_FCHDIR
Larry Hastings2f936352014-08-05 14:04:04 +10002775 if (path->fd != -1)
2776 result = fchdir(path->fd);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002777 else
2778#endif
Larry Hastings2f936352014-08-05 14:04:04 +10002779 result = chdir(path->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002780#endif
2781 Py_END_ALLOW_THREADS
2782
2783 if (result) {
Larry Hastings2f936352014-08-05 14:04:04 +10002784 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002785 }
2786
Larry Hastings2f936352014-08-05 14:04:04 +10002787 Py_RETURN_NONE;
2788}
2789
2790
2791#ifdef HAVE_FCHDIR
2792/*[clinic input]
2793os.fchdir
2794
2795 fd: fildes
2796
2797Change to the directory of the given file descriptor.
2798
2799fd must be opened on a directory, not a file.
2800Equivalent to os.chdir(fd).
2801
2802[clinic start generated code]*/
2803
Fred Drake4d1e64b2002-04-15 19:40:07 +00002804static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002805os_fchdir_impl(PyObject *module, int fd)
2806/*[clinic end generated code: output=42e064ec4dc00ab0 input=18e816479a2fa985]*/
Fred Drake4d1e64b2002-04-15 19:40:07 +00002807{
Larry Hastings2f936352014-08-05 14:04:04 +10002808 return posix_fildes_fd(fd, fchdir);
Fred Drake4d1e64b2002-04-15 19:40:07 +00002809}
2810#endif /* HAVE_FCHDIR */
2811
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00002812
Larry Hastings2f936352014-08-05 14:04:04 +10002813/*[clinic input]
2814os.chmod
2815
2816 path: path_t(allow_fd='PATH_HAVE_FCHMOD')
BNMetricsb9427072018-11-02 15:20:19 +00002817 Path to be modified. May always be specified as a str, bytes, or a path-like object.
Larry Hastings2f936352014-08-05 14:04:04 +10002818 On some platforms, path may also be specified as an open file descriptor.
2819 If this functionality is unavailable, using it raises an exception.
2820
2821 mode: int
2822 Operating-system mode bitfield.
2823
2824 *
2825
2826 dir_fd : dir_fd(requires='fchmodat') = None
2827 If not None, it should be a file descriptor open to a directory,
2828 and path should be relative; path will then be relative to that
2829 directory.
2830
2831 follow_symlinks: bool = True
2832 If False, and the last element of the path is a symbolic link,
2833 chmod will modify the symbolic link itself instead of the file
2834 the link points to.
2835
2836Change the access permissions of a file.
2837
2838It is an error to use dir_fd or follow_symlinks when specifying path as
2839 an open file descriptor.
2840dir_fd and follow_symlinks may not be implemented on your platform.
2841 If they are unavailable, using them will raise a NotImplementedError.
2842
2843[clinic start generated code]*/
2844
Larry Hastings2f936352014-08-05 14:04:04 +10002845static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002846os_chmod_impl(PyObject *module, path_t *path, int mode, int dir_fd,
Larry Hastings89964c42015-04-14 18:07:59 -04002847 int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +00002848/*[clinic end generated code: output=5cf6a94915cc7bff input=989081551c00293b]*/
Larry Hastings2f936352014-08-05 14:04:04 +10002849{
Larry Hastings9cf065c2012-06-22 16:30:09 -07002850 int result;
Larry Hastings9cf065c2012-06-22 16:30:09 -07002851
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00002852#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +00002853 DWORD attr;
Larry Hastings9cf065c2012-06-22 16:30:09 -07002854#endif
Hirokazu Yamamoto892a37a2009-06-28 11:07:03 +00002855
Larry Hastings9cf065c2012-06-22 16:30:09 -07002856#ifdef HAVE_FCHMODAT
2857 int fchmodat_nofollow_unsupported = 0;
2858#endif
2859
Larry Hastings9cf065c2012-06-22 16:30:09 -07002860#if !(defined(HAVE_FCHMODAT) || defined(HAVE_LCHMOD))
2861 if (follow_symlinks_specified("chmod", follow_symlinks))
Larry Hastings2f936352014-08-05 14:04:04 +10002862 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07002863#endif
2864
2865#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +00002866 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -07002867 attr = GetFileAttributesW(path->wide);
Tim Golden23005082013-10-25 11:22:37 +01002868 if (attr == INVALID_FILE_ATTRIBUTES)
Larry Hastings9cf065c2012-06-22 16:30:09 -07002869 result = 0;
2870 else {
2871 if (mode & _S_IWRITE)
Victor Stinner8c62be82010-05-06 00:08:46 +00002872 attr &= ~FILE_ATTRIBUTE_READONLY;
2873 else
2874 attr |= FILE_ATTRIBUTE_READONLY;
Steve Dowercc16be82016-09-08 10:35:16 -07002875 result = SetFileAttributesW(path->wide, attr);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002876 }
2877 Py_END_ALLOW_THREADS
2878
2879 if (!result) {
Larry Hastings2f936352014-08-05 14:04:04 +10002880 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002881 }
2882#else /* MS_WINDOWS */
2883 Py_BEGIN_ALLOW_THREADS
2884#ifdef HAVE_FCHMOD
Larry Hastings2f936352014-08-05 14:04:04 +10002885 if (path->fd != -1)
2886 result = fchmod(path->fd, mode);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002887 else
2888#endif
2889#ifdef HAVE_LCHMOD
2890 if ((!follow_symlinks) && (dir_fd == DEFAULT_DIR_FD))
Larry Hastings2f936352014-08-05 14:04:04 +10002891 result = lchmod(path->narrow, mode);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002892 else
2893#endif
2894#ifdef HAVE_FCHMODAT
2895 if ((dir_fd != DEFAULT_DIR_FD) || !follow_symlinks) {
2896 /*
2897 * fchmodat() doesn't currently support AT_SYMLINK_NOFOLLOW!
2898 * The documentation specifically shows how to use it,
Larry Hastingsdbbc0c82012-06-22 19:50:21 -07002899 * and then says it isn't implemented yet.
2900 * (true on linux with glibc 2.15, and openindiana 3.x)
Larry Hastings9cf065c2012-06-22 16:30:09 -07002901 *
2902 * Once it is supported, os.chmod will automatically
2903 * support dir_fd and follow_symlinks=False. (Hopefully.)
2904 * Until then, we need to be careful what exception we raise.
2905 */
Larry Hastings2f936352014-08-05 14:04:04 +10002906 result = fchmodat(dir_fd, path->narrow, mode,
Larry Hastings9cf065c2012-06-22 16:30:09 -07002907 follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW);
2908 /*
2909 * But wait! We can't throw the exception without allowing threads,
2910 * and we can't do that in this nested scope. (Macro trickery, sigh.)
2911 */
2912 fchmodat_nofollow_unsupported =
Larry Hastingsdbbc0c82012-06-22 19:50:21 -07002913 result &&
2914 ((errno == ENOTSUP) || (errno == EOPNOTSUPP)) &&
2915 !follow_symlinks;
Victor Stinner8c62be82010-05-06 00:08:46 +00002916 }
2917 else
Thomas Wouters477c8d52006-05-27 19:21:47 +00002918#endif
Larry Hastings2f936352014-08-05 14:04:04 +10002919 result = chmod(path->narrow, mode);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002920 Py_END_ALLOW_THREADS
2921
2922 if (result) {
2923#ifdef HAVE_FCHMODAT
2924 if (fchmodat_nofollow_unsupported) {
2925 if (dir_fd != DEFAULT_DIR_FD)
2926 dir_fd_and_follow_symlinks_invalid("chmod",
2927 dir_fd, follow_symlinks);
2928 else
2929 follow_symlinks_specified("chmod", follow_symlinks);
Anthony Sottile233ef242017-12-14 08:57:55 -08002930 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07002931 }
2932 else
2933#endif
Larry Hastings2f936352014-08-05 14:04:04 +10002934 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002935 }
2936#endif
2937
Larry Hastings2f936352014-08-05 14:04:04 +10002938 Py_RETURN_NONE;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002939}
2940
Larry Hastings9cf065c2012-06-22 16:30:09 -07002941
Christian Heimes4e30a842007-11-30 22:12:06 +00002942#ifdef HAVE_FCHMOD
Larry Hastings2f936352014-08-05 14:04:04 +10002943/*[clinic input]
2944os.fchmod
2945
2946 fd: int
2947 mode: int
2948
2949Change the access permissions of the file given by file descriptor fd.
2950
2951Equivalent to os.chmod(fd, mode).
2952[clinic start generated code]*/
2953
Larry Hastings2f936352014-08-05 14:04:04 +10002954static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002955os_fchmod_impl(PyObject *module, int fd, int mode)
2956/*[clinic end generated code: output=afd9bc05b4e426b3 input=8ab11975ca01ee5b]*/
Larry Hastings2f936352014-08-05 14:04:04 +10002957{
2958 int res;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00002959 int async_err = 0;
2960
2961 do {
2962 Py_BEGIN_ALLOW_THREADS
2963 res = fchmod(fd, mode);
2964 Py_END_ALLOW_THREADS
2965 } while (res != 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
2966 if (res != 0)
2967 return (!async_err) ? posix_error() : NULL;
2968
Victor Stinner8c62be82010-05-06 00:08:46 +00002969 Py_RETURN_NONE;
Christian Heimes4e30a842007-11-30 22:12:06 +00002970}
2971#endif /* HAVE_FCHMOD */
2972
Larry Hastings2f936352014-08-05 14:04:04 +10002973
Christian Heimes4e30a842007-11-30 22:12:06 +00002974#ifdef HAVE_LCHMOD
Larry Hastings2f936352014-08-05 14:04:04 +10002975/*[clinic input]
2976os.lchmod
2977
2978 path: path_t
2979 mode: int
2980
2981Change the access permissions of a file, without following symbolic links.
2982
2983If path is a symlink, this affects the link itself rather than the target.
2984Equivalent to chmod(path, mode, follow_symlinks=False)."
2985[clinic start generated code]*/
2986
Larry Hastings2f936352014-08-05 14:04:04 +10002987static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002988os_lchmod_impl(PyObject *module, path_t *path, int mode)
2989/*[clinic end generated code: output=082344022b51a1d5 input=90c5663c7465d24f]*/
Larry Hastings2f936352014-08-05 14:04:04 +10002990{
Victor Stinner8c62be82010-05-06 00:08:46 +00002991 int res;
Victor Stinner8c62be82010-05-06 00:08:46 +00002992 Py_BEGIN_ALLOW_THREADS
Larry Hastingsb1dc1122014-08-05 16:06:16 +10002993 res = lchmod(path->narrow, mode);
Victor Stinner8c62be82010-05-06 00:08:46 +00002994 Py_END_ALLOW_THREADS
Victor Stinner292c8352012-10-30 02:17:38 +01002995 if (res < 0) {
Larry Hastings2f936352014-08-05 14:04:04 +10002996 path_error(path);
Victor Stinner292c8352012-10-30 02:17:38 +01002997 return NULL;
2998 }
Victor Stinner8c62be82010-05-06 00:08:46 +00002999 Py_RETURN_NONE;
Christian Heimes4e30a842007-11-30 22:12:06 +00003000}
3001#endif /* HAVE_LCHMOD */
3002
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00003003
Thomas Wouterscf297e42007-02-23 15:07:44 +00003004#ifdef HAVE_CHFLAGS
Larry Hastings2f936352014-08-05 14:04:04 +10003005/*[clinic input]
3006os.chflags
3007
3008 path: path_t
3009 flags: unsigned_long(bitwise=True)
3010 follow_symlinks: bool=True
3011
3012Set file flags.
3013
3014If follow_symlinks is False, and the last element of the path is a symbolic
3015 link, chflags will change flags on the symbolic link itself instead of the
3016 file the link points to.
3017follow_symlinks may not be implemented on your platform. If it is
3018unavailable, using it will raise a NotImplementedError.
3019
3020[clinic start generated code]*/
3021
Larry Hastings2f936352014-08-05 14:04:04 +10003022static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003023os_chflags_impl(PyObject *module, path_t *path, unsigned long flags,
Larry Hastings89964c42015-04-14 18:07:59 -04003024 int follow_symlinks)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003025/*[clinic end generated code: output=85571c6737661ce9 input=0327e29feb876236]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003026{
3027 int result;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003028
3029#ifndef HAVE_LCHFLAGS
3030 if (follow_symlinks_specified("chflags", follow_symlinks))
Larry Hastings2f936352014-08-05 14:04:04 +10003031 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003032#endif
3033
Victor Stinner8c62be82010-05-06 00:08:46 +00003034 Py_BEGIN_ALLOW_THREADS
Larry Hastings9cf065c2012-06-22 16:30:09 -07003035#ifdef HAVE_LCHFLAGS
3036 if (!follow_symlinks)
Larry Hastings2f936352014-08-05 14:04:04 +10003037 result = lchflags(path->narrow, flags);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003038 else
3039#endif
Larry Hastings2f936352014-08-05 14:04:04 +10003040 result = chflags(path->narrow, flags);
Victor Stinner8c62be82010-05-06 00:08:46 +00003041 Py_END_ALLOW_THREADS
Larry Hastings9cf065c2012-06-22 16:30:09 -07003042
Larry Hastings2f936352014-08-05 14:04:04 +10003043 if (result)
3044 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003045
Larry Hastings2f936352014-08-05 14:04:04 +10003046 Py_RETURN_NONE;
Thomas Wouterscf297e42007-02-23 15:07:44 +00003047}
3048#endif /* HAVE_CHFLAGS */
3049
Larry Hastings2f936352014-08-05 14:04:04 +10003050
Thomas Wouterscf297e42007-02-23 15:07:44 +00003051#ifdef HAVE_LCHFLAGS
Larry Hastings2f936352014-08-05 14:04:04 +10003052/*[clinic input]
3053os.lchflags
3054
3055 path: path_t
3056 flags: unsigned_long(bitwise=True)
3057
3058Set file flags.
3059
3060This function will not follow symbolic links.
3061Equivalent to chflags(path, flags, follow_symlinks=False).
3062[clinic start generated code]*/
3063
Larry Hastings2f936352014-08-05 14:04:04 +10003064static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003065os_lchflags_impl(PyObject *module, path_t *path, unsigned long flags)
3066/*[clinic end generated code: output=30ae958695c07316 input=f9f82ea8b585ca9d]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003067{
Victor Stinner8c62be82010-05-06 00:08:46 +00003068 int res;
Victor Stinner8c62be82010-05-06 00:08:46 +00003069 Py_BEGIN_ALLOW_THREADS
Larry Hastingsb1dc1122014-08-05 16:06:16 +10003070 res = lchflags(path->narrow, flags);
Victor Stinner8c62be82010-05-06 00:08:46 +00003071 Py_END_ALLOW_THREADS
Victor Stinner292c8352012-10-30 02:17:38 +01003072 if (res < 0) {
Larry Hastings2f936352014-08-05 14:04:04 +10003073 return path_error(path);
Victor Stinner292c8352012-10-30 02:17:38 +01003074 }
Victor Stinner292c8352012-10-30 02:17:38 +01003075 Py_RETURN_NONE;
Thomas Wouterscf297e42007-02-23 15:07:44 +00003076}
3077#endif /* HAVE_LCHFLAGS */
3078
Larry Hastings2f936352014-08-05 14:04:04 +10003079
Martin v. Löwis244edc82001-10-04 22:44:26 +00003080#ifdef HAVE_CHROOT
Larry Hastings2f936352014-08-05 14:04:04 +10003081/*[clinic input]
3082os.chroot
3083 path: path_t
3084
3085Change root directory to path.
3086
3087[clinic start generated code]*/
3088
Larry Hastings2f936352014-08-05 14:04:04 +10003089static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003090os_chroot_impl(PyObject *module, path_t *path)
3091/*[clinic end generated code: output=de80befc763a4475 input=14822965652c3dc3]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003092{
3093 int res;
3094 Py_BEGIN_ALLOW_THREADS
3095 res = chroot(path->narrow);
3096 Py_END_ALLOW_THREADS
3097 if (res < 0)
3098 return path_error(path);
3099 Py_RETURN_NONE;
3100}
3101#endif /* HAVE_CHROOT */
3102
Martin v. Löwis244edc82001-10-04 22:44:26 +00003103
Guido van Rossum21142a01999-01-08 21:05:37 +00003104#ifdef HAVE_FSYNC
Larry Hastings2f936352014-08-05 14:04:04 +10003105/*[clinic input]
3106os.fsync
3107
3108 fd: fildes
3109
3110Force write of fd to disk.
3111[clinic start generated code]*/
3112
Larry Hastings2f936352014-08-05 14:04:04 +10003113static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003114os_fsync_impl(PyObject *module, int fd)
3115/*[clinic end generated code: output=4a10d773f52b3584 input=21c3645c056967f2]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003116{
3117 return posix_fildes_fd(fd, fsync);
Guido van Rossum21142a01999-01-08 21:05:37 +00003118}
3119#endif /* HAVE_FSYNC */
3120
Larry Hastings2f936352014-08-05 14:04:04 +10003121
Ross Lagerwall7807c352011-03-17 20:20:30 +02003122#ifdef HAVE_SYNC
Larry Hastings2f936352014-08-05 14:04:04 +10003123/*[clinic input]
3124os.sync
3125
3126Force write of everything to disk.
3127[clinic start generated code]*/
3128
Larry Hastings2f936352014-08-05 14:04:04 +10003129static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003130os_sync_impl(PyObject *module)
3131/*[clinic end generated code: output=2796b1f0818cd71c input=84749fe5e9b404ff]*/
Ross Lagerwall7807c352011-03-17 20:20:30 +02003132{
3133 Py_BEGIN_ALLOW_THREADS
3134 sync();
3135 Py_END_ALLOW_THREADS
3136 Py_RETURN_NONE;
3137}
Larry Hastings2f936352014-08-05 14:04:04 +10003138#endif /* HAVE_SYNC */
3139
Ross Lagerwall7807c352011-03-17 20:20:30 +02003140
Guido van Rossum21142a01999-01-08 21:05:37 +00003141#ifdef HAVE_FDATASYNC
Guido van Rossum7f58e2e2000-09-22 17:26:14 +00003142#ifdef __hpux
Guido van Rossumecc23b02000-09-22 16:01:05 +00003143extern int fdatasync(int); /* On HP-UX, in libc but not in unistd.h */
3144#endif
3145
Larry Hastings2f936352014-08-05 14:04:04 +10003146/*[clinic input]
3147os.fdatasync
3148
3149 fd: fildes
3150
3151Force write of fd to disk without forcing update of metadata.
3152[clinic start generated code]*/
3153
Larry Hastings2f936352014-08-05 14:04:04 +10003154static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003155os_fdatasync_impl(PyObject *module, int fd)
3156/*[clinic end generated code: output=b4b9698b5d7e26dd input=bc74791ee54dd291]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003157{
3158 return posix_fildes_fd(fd, fdatasync);
Guido van Rossum21142a01999-01-08 21:05:37 +00003159}
3160#endif /* HAVE_FDATASYNC */
3161
3162
Fredrik Lundh10723342000-07-10 16:38:09 +00003163#ifdef HAVE_CHOWN
Larry Hastings2f936352014-08-05 14:04:04 +10003164/*[clinic input]
3165os.chown
3166
3167 path : path_t(allow_fd='PATH_HAVE_FCHOWN')
BNMetricsb9427072018-11-02 15:20:19 +00003168 Path to be examined; can be string, bytes, a path-like object, or open-file-descriptor int.
Larry Hastings2f936352014-08-05 14:04:04 +10003169
3170 uid: uid_t
3171
3172 gid: gid_t
3173
3174 *
3175
3176 dir_fd : dir_fd(requires='fchownat') = None
3177 If not None, it should be a file descriptor open to a directory,
3178 and path should be relative; path will then be relative to that
3179 directory.
3180
3181 follow_symlinks: bool = True
3182 If False, and the last element of the path is a symbolic link,
3183 stat will examine the symbolic link itself instead of the file
3184 the link points to.
3185
3186Change the owner and group id of path to the numeric uid and gid.\
3187
3188path may always be specified as a string.
3189On some platforms, path may also be specified as an open file descriptor.
3190 If this functionality is unavailable, using it raises an exception.
3191If dir_fd is not None, it should be a file descriptor open to a directory,
3192 and path should be relative; path will then be relative to that directory.
3193If follow_symlinks is False, and the last element of the path is a symbolic
3194 link, chown will modify the symbolic link itself instead of the file the
3195 link points to.
3196It is an error to use dir_fd or follow_symlinks when specifying path as
3197 an open file descriptor.
3198dir_fd and follow_symlinks may not be implemented on your platform.
3199 If they are unavailable, using them will raise a NotImplementedError.
3200
3201[clinic start generated code]*/
3202
Larry Hastings2f936352014-08-05 14:04:04 +10003203static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003204os_chown_impl(PyObject *module, path_t *path, uid_t uid, gid_t gid,
Larry Hastings89964c42015-04-14 18:07:59 -04003205 int dir_fd, int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +00003206/*[clinic end generated code: output=4beadab0db5f70cd input=b08c5ec67996a97d]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003207{
3208 int result;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003209
3210#if !(defined(HAVE_LCHOWN) || defined(HAVE_FCHOWNAT))
3211 if (follow_symlinks_specified("chown", follow_symlinks))
Larry Hastings2f936352014-08-05 14:04:04 +10003212 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003213#endif
Larry Hastings2f936352014-08-05 14:04:04 +10003214 if (dir_fd_and_fd_invalid("chown", dir_fd, path->fd) ||
3215 fd_and_follow_symlinks_invalid("chown", path->fd, follow_symlinks))
3216 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003217
3218#ifdef __APPLE__
3219 /*
3220 * This is for Mac OS X 10.3, which doesn't have lchown.
3221 * (But we still have an lchown symbol because of weak-linking.)
3222 * It doesn't have fchownat either. So there's no possibility
3223 * of a graceful failover.
Georg Brandlf7875592012-06-24 13:58:31 +02003224 */
Larry Hastings9cf065c2012-06-22 16:30:09 -07003225 if ((!follow_symlinks) && (lchown == NULL)) {
3226 follow_symlinks_specified("chown", follow_symlinks);
Larry Hastings2f936352014-08-05 14:04:04 +10003227 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003228 }
3229#endif
3230
Victor Stinner8c62be82010-05-06 00:08:46 +00003231 Py_BEGIN_ALLOW_THREADS
Larry Hastings9cf065c2012-06-22 16:30:09 -07003232#ifdef HAVE_FCHOWN
Larry Hastings2f936352014-08-05 14:04:04 +10003233 if (path->fd != -1)
3234 result = fchown(path->fd, uid, gid);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003235 else
3236#endif
3237#ifdef HAVE_LCHOWN
3238 if ((!follow_symlinks) && (dir_fd == DEFAULT_DIR_FD))
Larry Hastings2f936352014-08-05 14:04:04 +10003239 result = lchown(path->narrow, uid, gid);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003240 else
3241#endif
3242#ifdef HAVE_FCHOWNAT
3243 if ((dir_fd != DEFAULT_DIR_FD) || (!follow_symlinks))
Larry Hastings2f936352014-08-05 14:04:04 +10003244 result = fchownat(dir_fd, path->narrow, uid, gid,
Larry Hastings9cf065c2012-06-22 16:30:09 -07003245 follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW);
3246 else
3247#endif
Larry Hastings2f936352014-08-05 14:04:04 +10003248 result = chown(path->narrow, uid, gid);
Victor Stinner8c62be82010-05-06 00:08:46 +00003249 Py_END_ALLOW_THREADS
Larry Hastings9cf065c2012-06-22 16:30:09 -07003250
Larry Hastings2f936352014-08-05 14:04:04 +10003251 if (result)
3252 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003253
Larry Hastings2f936352014-08-05 14:04:04 +10003254 Py_RETURN_NONE;
Guido van Rossumb6775db1994-08-01 11:34:53 +00003255}
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +00003256#endif /* HAVE_CHOWN */
Guido van Rossumb6775db1994-08-01 11:34:53 +00003257
Larry Hastings2f936352014-08-05 14:04:04 +10003258
Christian Heimes4e30a842007-11-30 22:12:06 +00003259#ifdef HAVE_FCHOWN
Larry Hastings2f936352014-08-05 14:04:04 +10003260/*[clinic input]
3261os.fchown
3262
3263 fd: int
3264 uid: uid_t
3265 gid: gid_t
3266
3267Change the owner and group id of the file specified by file descriptor.
3268
3269Equivalent to os.chown(fd, uid, gid).
3270
3271[clinic start generated code]*/
3272
Larry Hastings2f936352014-08-05 14:04:04 +10003273static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003274os_fchown_impl(PyObject *module, int fd, uid_t uid, gid_t gid)
3275/*[clinic end generated code: output=97d21cbd5a4350a6 input=3af544ba1b13a0d7]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003276{
Victor Stinner8c62be82010-05-06 00:08:46 +00003277 int res;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00003278 int async_err = 0;
3279
3280 do {
3281 Py_BEGIN_ALLOW_THREADS
3282 res = fchown(fd, uid, gid);
3283 Py_END_ALLOW_THREADS
3284 } while (res != 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
3285 if (res != 0)
3286 return (!async_err) ? posix_error() : NULL;
3287
Victor Stinner8c62be82010-05-06 00:08:46 +00003288 Py_RETURN_NONE;
Christian Heimes4e30a842007-11-30 22:12:06 +00003289}
3290#endif /* HAVE_FCHOWN */
3291
Larry Hastings2f936352014-08-05 14:04:04 +10003292
Martin v. Löwis0cec0ff2002-07-28 16:33:45 +00003293#ifdef HAVE_LCHOWN
Larry Hastings2f936352014-08-05 14:04:04 +10003294/*[clinic input]
3295os.lchown
3296
3297 path : path_t
3298 uid: uid_t
3299 gid: gid_t
3300
3301Change the owner and group id of path to the numeric uid and gid.
3302
3303This function will not follow symbolic links.
3304Equivalent to os.chown(path, uid, gid, follow_symlinks=False).
3305[clinic start generated code]*/
3306
Larry Hastings2f936352014-08-05 14:04:04 +10003307static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003308os_lchown_impl(PyObject *module, path_t *path, uid_t uid, gid_t gid)
3309/*[clinic end generated code: output=25eaf6af412fdf2f input=b1c6014d563a7161]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003310{
Victor Stinner8c62be82010-05-06 00:08:46 +00003311 int res;
Victor Stinner8c62be82010-05-06 00:08:46 +00003312 Py_BEGIN_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10003313 res = lchown(path->narrow, uid, gid);
Victor Stinner8c62be82010-05-06 00:08:46 +00003314 Py_END_ALLOW_THREADS
Victor Stinner292c8352012-10-30 02:17:38 +01003315 if (res < 0) {
Larry Hastings2f936352014-08-05 14:04:04 +10003316 return path_error(path);
Victor Stinner292c8352012-10-30 02:17:38 +01003317 }
Larry Hastings2f936352014-08-05 14:04:04 +10003318 Py_RETURN_NONE;
Martin v. Löwis0cec0ff2002-07-28 16:33:45 +00003319}
3320#endif /* HAVE_LCHOWN */
3321
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00003322
Barry Warsaw53699e91996-12-10 23:23:01 +00003323static PyObject *
Guido van Rossumf0af3e32008-10-02 18:55:37 +00003324posix_getcwd(int use_bytes)
Mark Hammondc2e85bd2002-10-03 05:10:39 +00003325{
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00003326#ifdef MS_WINDOWS
Victor Stinner689830e2019-06-26 17:31:12 +02003327 wchar_t wbuf[MAXPATHLEN];
3328 wchar_t *wbuf2 = wbuf;
3329 DWORD len;
3330
3331 Py_BEGIN_ALLOW_THREADS
3332 len = GetCurrentDirectoryW(Py_ARRAY_LENGTH(wbuf), wbuf);
3333 /* If the buffer is large enough, len does not include the
3334 terminating \0. If the buffer is too small, len includes
3335 the space needed for the terminator. */
3336 if (len >= Py_ARRAY_LENGTH(wbuf)) {
3337 if (len >= PY_SSIZE_T_MAX / sizeof(wchar_t)) {
Victor Stinnerb6404912013-07-07 16:21:41 +02003338 wbuf2 = PyMem_RawMalloc(len * sizeof(wchar_t));
Victor Stinner8c62be82010-05-06 00:08:46 +00003339 }
Victor Stinner689830e2019-06-26 17:31:12 +02003340 else {
3341 wbuf2 = NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00003342 }
Victor Stinner689830e2019-06-26 17:31:12 +02003343 if (wbuf2) {
3344 len = GetCurrentDirectoryW(len, wbuf2);
Victor Stinner8c62be82010-05-06 00:08:46 +00003345 }
Victor Stinner689830e2019-06-26 17:31:12 +02003346 }
3347 Py_END_ALLOW_THREADS
3348
3349 if (!wbuf2) {
3350 PyErr_NoMemory();
3351 return NULL;
3352 }
3353 if (!len) {
Victor Stinnerb024e842012-10-31 22:24:06 +01003354 if (wbuf2 != wbuf)
Victor Stinnerb6404912013-07-07 16:21:41 +02003355 PyMem_RawFree(wbuf2);
Victor Stinner689830e2019-06-26 17:31:12 +02003356 return PyErr_SetFromWindowsErr(0);
Victor Stinner8c62be82010-05-06 00:08:46 +00003357 }
Victor Stinnerf7c5ae22011-11-16 23:43:07 +01003358
Victor Stinner689830e2019-06-26 17:31:12 +02003359 PyObject *resobj = PyUnicode_FromWideChar(wbuf2, len);
3360 if (wbuf2 != wbuf) {
3361 PyMem_RawFree(wbuf2);
3362 }
Mark Hammondc2e85bd2002-10-03 05:10:39 +00003363
Victor Stinner689830e2019-06-26 17:31:12 +02003364 if (use_bytes) {
3365 if (resobj == NULL) {
3366 return NULL;
3367 }
3368 Py_SETREF(resobj, PyUnicode_EncodeFSDefault(resobj));
3369 }
3370
3371 return resobj;
3372#else
3373 const size_t chunk = 1024;
3374
3375 char *buf = NULL;
3376 char *cwd = NULL;
3377 size_t buflen = 0;
3378
Victor Stinner8c62be82010-05-06 00:08:46 +00003379 Py_BEGIN_ALLOW_THREADS
Victor Stinner4403d7d2015-04-25 00:16:10 +02003380 do {
Victor Stinner689830e2019-06-26 17:31:12 +02003381 char *newbuf;
3382 if (buflen <= PY_SSIZE_T_MAX - chunk) {
3383 buflen += chunk;
3384 newbuf = PyMem_RawRealloc(buf, buflen);
3385 }
3386 else {
3387 newbuf = NULL;
3388 }
3389 if (newbuf == NULL) {
3390 PyMem_RawFree(buf);
3391 buf = NULL;
Victor Stinnerc44f7072016-03-14 18:07:53 +01003392 break;
3393 }
Victor Stinner689830e2019-06-26 17:31:12 +02003394 buf = newbuf;
Victor Stinner4403d7d2015-04-25 00:16:10 +02003395
Victor Stinner4403d7d2015-04-25 00:16:10 +02003396 cwd = getcwd(buf, buflen);
3397 } while (cwd == NULL && errno == ERANGE);
Victor Stinner8c62be82010-05-06 00:08:46 +00003398 Py_END_ALLOW_THREADS
Victor Stinner4403d7d2015-04-25 00:16:10 +02003399
Victor Stinner689830e2019-06-26 17:31:12 +02003400 if (buf == NULL) {
3401 return PyErr_NoMemory();
3402 }
Victor Stinner4403d7d2015-04-25 00:16:10 +02003403 if (cwd == NULL) {
3404 PyMem_RawFree(buf);
Victor Stinner8c62be82010-05-06 00:08:46 +00003405 return posix_error();
Victor Stinner4403d7d2015-04-25 00:16:10 +02003406 }
3407
Victor Stinner689830e2019-06-26 17:31:12 +02003408 PyObject *obj;
3409 if (use_bytes) {
Victor Stinner4403d7d2015-04-25 00:16:10 +02003410 obj = PyBytes_FromStringAndSize(buf, strlen(buf));
Victor Stinner689830e2019-06-26 17:31:12 +02003411 }
3412 else {
Victor Stinner4403d7d2015-04-25 00:16:10 +02003413 obj = PyUnicode_DecodeFSDefault(buf);
Victor Stinner689830e2019-06-26 17:31:12 +02003414 }
Victor Stinner4403d7d2015-04-25 00:16:10 +02003415 PyMem_RawFree(buf);
3416
3417 return obj;
Victor Stinner689830e2019-06-26 17:31:12 +02003418#endif /* !MS_WINDOWS */
Mark Hammondc2e85bd2002-10-03 05:10:39 +00003419}
Guido van Rossumf0af3e32008-10-02 18:55:37 +00003420
Larry Hastings2f936352014-08-05 14:04:04 +10003421
3422/*[clinic input]
3423os.getcwd
3424
3425Return a unicode string representing the current working directory.
3426[clinic start generated code]*/
3427
Larry Hastings2f936352014-08-05 14:04:04 +10003428static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003429os_getcwd_impl(PyObject *module)
3430/*[clinic end generated code: output=21badfae2ea99ddc input=f069211bb70e3d39]*/
Guido van Rossumf0af3e32008-10-02 18:55:37 +00003431{
3432 return posix_getcwd(0);
3433}
3434
Larry Hastings2f936352014-08-05 14:04:04 +10003435
3436/*[clinic input]
3437os.getcwdb
3438
3439Return a bytes string representing the current working directory.
3440[clinic start generated code]*/
3441
Larry Hastings2f936352014-08-05 14:04:04 +10003442static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003443os_getcwdb_impl(PyObject *module)
3444/*[clinic end generated code: output=3dd47909480e4824 input=f6f6a378dad3d9cb]*/
Guido van Rossumf0af3e32008-10-02 18:55:37 +00003445{
3446 return posix_getcwd(1);
3447}
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003448
Larry Hastings2f936352014-08-05 14:04:04 +10003449
Larry Hastings9cf065c2012-06-22 16:30:09 -07003450#if ((!defined(HAVE_LINK)) && defined(MS_WINDOWS))
3451#define HAVE_LINK 1
3452#endif
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00003453
Guido van Rossumb6775db1994-08-01 11:34:53 +00003454#ifdef HAVE_LINK
Larry Hastings2f936352014-08-05 14:04:04 +10003455/*[clinic input]
3456
3457os.link
3458
3459 src : path_t
3460 dst : path_t
3461 *
3462 src_dir_fd : dir_fd = None
3463 dst_dir_fd : dir_fd = None
3464 follow_symlinks: bool = True
3465
3466Create a hard link to a file.
3467
3468If either src_dir_fd or dst_dir_fd is not None, it should be a file
3469 descriptor open to a directory, and the respective path string (src or dst)
3470 should be relative; the path will then be relative to that directory.
3471If follow_symlinks is False, and the last element of src is a symbolic
3472 link, link will create a link to the symbolic link itself instead of the
3473 file the link points to.
3474src_dir_fd, dst_dir_fd, and follow_symlinks may not be implemented on your
3475 platform. If they are unavailable, using them will raise a
3476 NotImplementedError.
3477[clinic start generated code]*/
3478
Larry Hastings2f936352014-08-05 14:04:04 +10003479static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003480os_link_impl(PyObject *module, path_t *src, path_t *dst, int src_dir_fd,
Larry Hastings89964c42015-04-14 18:07:59 -04003481 int dst_dir_fd, int follow_symlinks)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003482/*[clinic end generated code: output=7f00f6007fd5269a input=b0095ebbcbaa7e04]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003483{
Larry Hastings9cf065c2012-06-22 16:30:09 -07003484#ifdef MS_WINDOWS
Steve Dowercc16be82016-09-08 10:35:16 -07003485 BOOL result = FALSE;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003486#else
3487 int result;
3488#endif
3489
Larry Hastings9cf065c2012-06-22 16:30:09 -07003490#ifndef HAVE_LINKAT
3491 if ((src_dir_fd != DEFAULT_DIR_FD) || (dst_dir_fd != DEFAULT_DIR_FD)) {
3492 argument_unavailable_error("link", "src_dir_fd and dst_dir_fd");
Larry Hastings2f936352014-08-05 14:04:04 +10003493 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003494 }
3495#endif
3496
Steve Dowercc16be82016-09-08 10:35:16 -07003497#ifndef MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +10003498 if ((src->narrow && dst->wide) || (src->wide && dst->narrow)) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07003499 PyErr_SetString(PyExc_NotImplementedError,
3500 "link: src and dst must be the same type");
Larry Hastings2f936352014-08-05 14:04:04 +10003501 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003502 }
Steve Dowercc16be82016-09-08 10:35:16 -07003503#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003504
Brian Curtin1b9df392010-11-24 20:24:31 +00003505#ifdef MS_WINDOWS
Larry Hastings9cf065c2012-06-22 16:30:09 -07003506 Py_BEGIN_ALLOW_THREADS
Steve Dowerc3630612016-11-19 18:41:16 -08003507 result = CreateHardLinkW(dst->wide, src->wide, NULL);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003508 Py_END_ALLOW_THREADS
Brian Curtin1b9df392010-11-24 20:24:31 +00003509
Larry Hastings2f936352014-08-05 14:04:04 +10003510 if (!result)
3511 return path_error2(src, dst);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003512#else
3513 Py_BEGIN_ALLOW_THREADS
Larry Hastings67cbf7b2012-06-22 17:06:48 -07003514#ifdef HAVE_LINKAT
Larry Hastings9cf065c2012-06-22 16:30:09 -07003515 if ((src_dir_fd != DEFAULT_DIR_FD) ||
3516 (dst_dir_fd != DEFAULT_DIR_FD) ||
3517 (!follow_symlinks))
Larry Hastings2f936352014-08-05 14:04:04 +10003518 result = linkat(src_dir_fd, src->narrow,
3519 dst_dir_fd, dst->narrow,
Larry Hastings9cf065c2012-06-22 16:30:09 -07003520 follow_symlinks ? AT_SYMLINK_FOLLOW : 0);
3521 else
Steve Dowercc16be82016-09-08 10:35:16 -07003522#endif /* HAVE_LINKAT */
Larry Hastings2f936352014-08-05 14:04:04 +10003523 result = link(src->narrow, dst->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003524 Py_END_ALLOW_THREADS
Brian Curtinfc889c42010-11-28 23:59:46 +00003525
Larry Hastings2f936352014-08-05 14:04:04 +10003526 if (result)
3527 return path_error2(src, dst);
Steve Dowercc16be82016-09-08 10:35:16 -07003528#endif /* MS_WINDOWS */
Larry Hastings9cf065c2012-06-22 16:30:09 -07003529
Larry Hastings2f936352014-08-05 14:04:04 +10003530 Py_RETURN_NONE;
Brian Curtin1b9df392010-11-24 20:24:31 +00003531}
Larry Hastings9cf065c2012-06-22 16:30:09 -07003532#endif
3533
Brian Curtin1b9df392010-11-24 20:24:31 +00003534
Gregory P. Smith16ea14a2013-03-20 18:51:33 -07003535#if defined(MS_WINDOWS) && !defined(HAVE_OPENDIR)
Barry Warsaw53699e91996-12-10 23:23:01 +00003536static PyObject *
Gregory P. Smith40a21602013-03-20 20:52:50 -07003537_listdir_windows_no_opendir(path_t *path, PyObject *list)
Guido van Rossumb6775db1994-08-01 11:34:53 +00003538{
Larry Hastings9cf065c2012-06-22 16:30:09 -07003539 PyObject *v;
3540 HANDLE hFindFile = INVALID_HANDLE_VALUE;
3541 BOOL result;
Steve Dowercc16be82016-09-08 10:35:16 -07003542 wchar_t namebuf[MAX_PATH+4]; /* Overallocate for "\*.*" */
Larry Hastings9cf065c2012-06-22 16:30:09 -07003543 /* only claim to have space for MAX_PATH */
Victor Stinner75875072013-11-24 19:23:25 +01003544 Py_ssize_t len = Py_ARRAY_LENGTH(namebuf)-4;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003545 wchar_t *wnamebuf = NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003546
Steve Dowercc16be82016-09-08 10:35:16 -07003547 WIN32_FIND_DATAW wFileData;
3548 const wchar_t *po_wchars;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00003549
Steve Dowercc16be82016-09-08 10:35:16 -07003550 if (!path->wide) { /* Default arg: "." */
3551 po_wchars = L".";
3552 len = 1;
3553 } else {
3554 po_wchars = path->wide;
3555 len = wcslen(path->wide);
3556 }
3557 /* The +5 is so we can append "\\*.*\0" */
3558 wnamebuf = PyMem_New(wchar_t, len + 5);
3559 if (!wnamebuf) {
3560 PyErr_NoMemory();
Larry Hastings9cf065c2012-06-22 16:30:09 -07003561 goto exit;
Victor Stinner8c62be82010-05-06 00:08:46 +00003562 }
Steve Dowercc16be82016-09-08 10:35:16 -07003563 wcscpy(wnamebuf, po_wchars);
Victor Stinner8c62be82010-05-06 00:08:46 +00003564 if (len > 0) {
Steve Dowercc16be82016-09-08 10:35:16 -07003565 wchar_t wch = wnamebuf[len-1];
3566 if (wch != SEP && wch != ALTSEP && wch != L':')
3567 wnamebuf[len++] = SEP;
3568 wcscpy(wnamebuf + len, L"*.*");
Victor Stinner8c62be82010-05-06 00:08:46 +00003569 }
Steve Dowercc16be82016-09-08 10:35:16 -07003570 if ((list = PyList_New(0)) == NULL) {
3571 goto exit;
3572 }
Antoine Pitroub73caab2010-08-09 23:39:31 +00003573 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -07003574 hFindFile = FindFirstFileW(wnamebuf, &wFileData);
Antoine Pitroub73caab2010-08-09 23:39:31 +00003575 Py_END_ALLOW_THREADS
Victor Stinner8c62be82010-05-06 00:08:46 +00003576 if (hFindFile == INVALID_HANDLE_VALUE) {
3577 int error = GetLastError();
3578 if (error == ERROR_FILE_NOT_FOUND)
Larry Hastings9cf065c2012-06-22 16:30:09 -07003579 goto exit;
3580 Py_DECREF(list);
Gregory P. Smith40a21602013-03-20 20:52:50 -07003581 list = path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003582 goto exit;
Victor Stinner8c62be82010-05-06 00:08:46 +00003583 }
3584 do {
3585 /* Skip over . and .. */
Steve Dowercc16be82016-09-08 10:35:16 -07003586 if (wcscmp(wFileData.cFileName, L".") != 0 &&
3587 wcscmp(wFileData.cFileName, L"..") != 0) {
3588 v = PyUnicode_FromWideChar(wFileData.cFileName,
3589 wcslen(wFileData.cFileName));
3590 if (path->narrow && v) {
3591 Py_SETREF(v, PyUnicode_EncodeFSDefault(v));
3592 }
Victor Stinner8c62be82010-05-06 00:08:46 +00003593 if (v == NULL) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07003594 Py_DECREF(list);
3595 list = NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00003596 break;
3597 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07003598 if (PyList_Append(list, v) != 0) {
Victor Stinner8c62be82010-05-06 00:08:46 +00003599 Py_DECREF(v);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003600 Py_DECREF(list);
3601 list = NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00003602 break;
3603 }
3604 Py_DECREF(v);
3605 }
3606 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -07003607 result = FindNextFileW(hFindFile, &wFileData);
Victor Stinner8c62be82010-05-06 00:08:46 +00003608 Py_END_ALLOW_THREADS
3609 /* FindNextFile sets error to ERROR_NO_MORE_FILES if
3610 it got to the end of the directory. */
3611 if (!result && GetLastError() != ERROR_NO_MORE_FILES) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07003612 Py_DECREF(list);
Gregory P. Smith40a21602013-03-20 20:52:50 -07003613 list = path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003614 goto exit;
Victor Stinner8c62be82010-05-06 00:08:46 +00003615 }
3616 } while (result == TRUE);
Guido van Rossumb6775db1994-08-01 11:34:53 +00003617
Larry Hastings9cf065c2012-06-22 16:30:09 -07003618exit:
3619 if (hFindFile != INVALID_HANDLE_VALUE) {
3620 if (FindClose(hFindFile) == FALSE) {
3621 if (list != NULL) {
3622 Py_DECREF(list);
Gregory P. Smith40a21602013-03-20 20:52:50 -07003623 list = path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003624 }
3625 }
Victor Stinner8c62be82010-05-06 00:08:46 +00003626 }
Victor Stinnerb6404912013-07-07 16:21:41 +02003627 PyMem_Free(wnamebuf);
Guido van Rossumb6775db1994-08-01 11:34:53 +00003628
Larry Hastings9cf065c2012-06-22 16:30:09 -07003629 return list;
Gregory P. Smith16ea14a2013-03-20 18:51:33 -07003630} /* end of _listdir_windows_no_opendir */
3631
3632#else /* thus POSIX, ie: not (MS_WINDOWS and not HAVE_OPENDIR) */
3633
3634static PyObject *
Gregory P. Smith40a21602013-03-20 20:52:50 -07003635_posix_listdir(path_t *path, PyObject *list)
Gregory P. Smith16ea14a2013-03-20 18:51:33 -07003636{
Gregory P. Smith16ea14a2013-03-20 18:51:33 -07003637 PyObject *v;
3638 DIR *dirp = NULL;
3639 struct dirent *ep;
3640 int return_str; /* if false, return bytes */
Larry Hastings4dbc95e2013-08-01 18:18:56 -07003641#ifdef HAVE_FDOPENDIR
3642 int fd = -1;
3643#endif
Gregory P. Smith16ea14a2013-03-20 18:51:33 -07003644
Victor Stinner8c62be82010-05-06 00:08:46 +00003645 errno = 0;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003646#ifdef HAVE_FDOPENDIR
Gregory P. Smith40a21602013-03-20 20:52:50 -07003647 if (path->fd != -1) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07003648 /* closedir() closes the FD, so we duplicate it */
Victor Stinnerdaf45552013-08-28 00:53:59 +02003649 fd = _Py_dup(path->fd);
Victor Stinnerf3266652013-12-19 13:24:49 +01003650 if (fd == -1)
3651 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003652
Larry Hastingsfdaea062012-06-25 04:42:23 -07003653 return_str = 1;
3654
Larry Hastings9cf065c2012-06-22 16:30:09 -07003655 Py_BEGIN_ALLOW_THREADS
3656 dirp = fdopendir(fd);
3657 Py_END_ALLOW_THREADS
3658 }
3659 else
3660#endif
3661 {
Serhiy Storchakadeab18d2016-05-07 16:45:18 +03003662 const char *name;
Gregory P. Smith40a21602013-03-20 20:52:50 -07003663 if (path->narrow) {
3664 name = path->narrow;
Serhiy Storchaka1180e5a2017-07-11 06:36:46 +03003665 /* only return bytes if they specified a bytes-like object */
3666 return_str = !PyObject_CheckBuffer(path->object);
Larry Hastingsfdaea062012-06-25 04:42:23 -07003667 }
3668 else {
3669 name = ".";
3670 return_str = 1;
3671 }
3672
Larry Hastings9cf065c2012-06-22 16:30:09 -07003673 Py_BEGIN_ALLOW_THREADS
3674 dirp = opendir(name);
3675 Py_END_ALLOW_THREADS
3676 }
3677
3678 if (dirp == NULL) {
Gregory P. Smith40a21602013-03-20 20:52:50 -07003679 list = path_error(path);
Larry Hastings4dbc95e2013-08-01 18:18:56 -07003680#ifdef HAVE_FDOPENDIR
3681 if (fd != -1) {
3682 Py_BEGIN_ALLOW_THREADS
3683 close(fd);
3684 Py_END_ALLOW_THREADS
3685 }
3686#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -07003687 goto exit;
3688 }
3689 if ((list = PyList_New(0)) == NULL) {
3690 goto exit;
Victor Stinner8c62be82010-05-06 00:08:46 +00003691 }
3692 for (;;) {
3693 errno = 0;
3694 Py_BEGIN_ALLOW_THREADS
3695 ep = readdir(dirp);
3696 Py_END_ALLOW_THREADS
3697 if (ep == NULL) {
3698 if (errno == 0) {
3699 break;
3700 } else {
Larry Hastings9cf065c2012-06-22 16:30:09 -07003701 Py_DECREF(list);
Gregory P. Smith40a21602013-03-20 20:52:50 -07003702 list = path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003703 goto exit;
Victor Stinner8c62be82010-05-06 00:08:46 +00003704 }
3705 }
3706 if (ep->d_name[0] == '.' &&
3707 (NAMLEN(ep) == 1 ||
3708 (ep->d_name[1] == '.' && NAMLEN(ep) == 2)))
3709 continue;
Larry Hastingsfdaea062012-06-25 04:42:23 -07003710 if (return_str)
Victor Stinnera45598a2010-05-14 16:35:39 +00003711 v = PyUnicode_DecodeFSDefaultAndSize(ep->d_name, NAMLEN(ep));
3712 else
3713 v = PyBytes_FromStringAndSize(ep->d_name, NAMLEN(ep));
Victor Stinner8c62be82010-05-06 00:08:46 +00003714 if (v == NULL) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07003715 Py_CLEAR(list);
Victor Stinner8c62be82010-05-06 00:08:46 +00003716 break;
3717 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07003718 if (PyList_Append(list, v) != 0) {
Victor Stinner8c62be82010-05-06 00:08:46 +00003719 Py_DECREF(v);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003720 Py_CLEAR(list);
Victor Stinner8c62be82010-05-06 00:08:46 +00003721 break;
3722 }
3723 Py_DECREF(v);
3724 }
Guido van Rossum0ee42cd1991-04-08 21:01:03 +00003725
Larry Hastings9cf065c2012-06-22 16:30:09 -07003726exit:
3727 if (dirp != NULL) {
3728 Py_BEGIN_ALLOW_THREADS
Larry Hastings4dbc95e2013-08-01 18:18:56 -07003729#ifdef HAVE_FDOPENDIR
Larry Hastings9cf065c2012-06-22 16:30:09 -07003730 if (fd > -1)
3731 rewinddir(dirp);
Larry Hastings4dbc95e2013-08-01 18:18:56 -07003732#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -07003733 closedir(dirp);
3734 Py_END_ALLOW_THREADS
3735 }
3736
Larry Hastings9cf065c2012-06-22 16:30:09 -07003737 return list;
Gregory P. Smith16ea14a2013-03-20 18:51:33 -07003738} /* end of _posix_listdir */
3739#endif /* which OS */
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +00003740
Larry Hastings2f936352014-08-05 14:04:04 +10003741
3742/*[clinic input]
3743os.listdir
3744
3745 path : path_t(nullable=True, allow_fd='PATH_HAVE_FDOPENDIR') = None
3746
3747Return a list containing the names of the files in the directory.
3748
BNMetricsb9427072018-11-02 15:20:19 +00003749path can be specified as either str, bytes, or a path-like object. If path is bytes,
Larry Hastings2f936352014-08-05 14:04:04 +10003750 the filenames returned will also be bytes; in all other circumstances
3751 the filenames returned will be str.
3752If path is None, uses the path='.'.
3753On some platforms, path may also be specified as an open file descriptor;\
3754 the file descriptor must refer to a directory.
3755 If this functionality is unavailable, using it raises NotImplementedError.
3756
3757The list is in arbitrary order. It does not include the special
3758entries '.' and '..' even if they are present in the directory.
3759
3760
3761[clinic start generated code]*/
3762
Larry Hastings2f936352014-08-05 14:04:04 +10003763static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003764os_listdir_impl(PyObject *module, path_t *path)
BNMetricsb9427072018-11-02 15:20:19 +00003765/*[clinic end generated code: output=293045673fcd1a75 input=e3f58030f538295d]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003766{
Steve Dower60419a72019-06-24 08:42:54 -07003767 if (PySys_Audit("os.listdir", "O",
3768 path->object ? path->object : Py_None) < 0) {
3769 return NULL;
3770 }
Larry Hastings2f936352014-08-05 14:04:04 +10003771#if defined(MS_WINDOWS) && !defined(HAVE_OPENDIR)
3772 return _listdir_windows_no_opendir(path, NULL);
3773#else
3774 return _posix_listdir(path, NULL);
3775#endif
3776}
3777
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00003778#ifdef MS_WINDOWS
Mark Hammondef8b6542001-05-13 08:04:26 +00003779/* A helper function for abspath on win32 */
Serhiy Storchakaf0b50152015-05-13 00:52:39 +03003780/*[clinic input]
3781os._getfullpathname
Victor Stinnereb5657a2011-09-30 01:44:27 +02003782
Serhiy Storchakaf0b50152015-05-13 00:52:39 +03003783 path: path_t
3784 /
3785
3786[clinic start generated code]*/
3787
3788static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003789os__getfullpathname_impl(PyObject *module, path_t *path)
3790/*[clinic end generated code: output=bb8679d56845bc9b input=332ed537c29d0a3e]*/
Serhiy Storchakaf0b50152015-05-13 00:52:39 +03003791{
Victor Stinner3939c322019-06-25 15:02:43 +02003792 wchar_t *abspath;
Victor Stinnereb5657a2011-09-30 01:44:27 +02003793
Victor Stinner3939c322019-06-25 15:02:43 +02003794 /* _Py_abspath() is implemented with GetFullPathNameW() on Windows */
3795 if (_Py_abspath(path->wide, &abspath) < 0) {
3796 return win32_error_object("GetFullPathNameW", path->object);
Victor Stinner8c62be82010-05-06 00:08:46 +00003797 }
Victor Stinner3939c322019-06-25 15:02:43 +02003798 if (abspath == NULL) {
3799 return PyErr_NoMemory();
3800 }
3801
3802 PyObject *str = PyUnicode_FromWideChar(abspath, wcslen(abspath));
3803 PyMem_RawFree(abspath);
3804 if (str == NULL) {
3805 return NULL;
3806 }
3807 if (path->narrow) {
3808 Py_SETREF(str, PyUnicode_EncodeFSDefault(str));
3809 }
3810 return str;
Larry Hastings2f936352014-08-05 14:04:04 +10003811}
Brian Curtind40e6f72010-07-08 21:39:08 +00003812
Brian Curtind25aef52011-06-13 15:16:04 -05003813
Larry Hastings2f936352014-08-05 14:04:04 +10003814/*[clinic input]
3815os._getfinalpathname
Brian Curtinf5e76d02010-11-24 13:14:05 +00003816
Steve Dower23ad6d02018-02-22 10:39:10 -08003817 path: path_t
Larry Hastings2f936352014-08-05 14:04:04 +10003818 /
3819
3820A helper function for samepath on windows.
3821[clinic start generated code]*/
3822
Larry Hastings2f936352014-08-05 14:04:04 +10003823static PyObject *
Steve Dower23ad6d02018-02-22 10:39:10 -08003824os__getfinalpathname_impl(PyObject *module, path_t *path)
3825/*[clinic end generated code: output=621a3c79bc29ebfa input=2b6b6c7cbad5fb84]*/
Brian Curtind40e6f72010-07-08 21:39:08 +00003826{
3827 HANDLE hFile;
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03003828 wchar_t buf[MAXPATHLEN], *target_path = buf;
3829 int buf_size = Py_ARRAY_LENGTH(buf);
Brian Curtind40e6f72010-07-08 21:39:08 +00003830 int result_length;
Larry Hastings2f936352014-08-05 14:04:04 +10003831 PyObject *result;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00003832
Steve Dower23ad6d02018-02-22 10:39:10 -08003833 Py_BEGIN_ALLOW_THREADS
Brian Curtind40e6f72010-07-08 21:39:08 +00003834 hFile = CreateFileW(
Steve Dower23ad6d02018-02-22 10:39:10 -08003835 path->wide,
Brian Curtind40e6f72010-07-08 21:39:08 +00003836 0, /* desired access */
3837 0, /* share mode */
3838 NULL, /* security attributes */
3839 OPEN_EXISTING,
3840 /* FILE_FLAG_BACKUP_SEMANTICS is required to open a directory */
3841 FILE_FLAG_BACKUP_SEMANTICS,
3842 NULL);
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03003843 Py_END_ALLOW_THREADS
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00003844
Steve Dower23ad6d02018-02-22 10:39:10 -08003845 if (hFile == INVALID_HANDLE_VALUE) {
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03003846 return win32_error_object("CreateFileW", path->object);
Steve Dower23ad6d02018-02-22 10:39:10 -08003847 }
Brian Curtind40e6f72010-07-08 21:39:08 +00003848
3849 /* We have a good handle to the target, use it to determine the
3850 target path name. */
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03003851 while (1) {
3852 Py_BEGIN_ALLOW_THREADS
3853 result_length = GetFinalPathNameByHandleW(hFile, target_path,
3854 buf_size, VOLUME_NAME_DOS);
3855 Py_END_ALLOW_THREADS
Brian Curtind40e6f72010-07-08 21:39:08 +00003856
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03003857 if (!result_length) {
3858 result = win32_error_object("GetFinalPathNameByHandleW",
3859 path->object);
3860 goto cleanup;
3861 }
Brian Curtind40e6f72010-07-08 21:39:08 +00003862
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03003863 if (result_length < buf_size) {
3864 break;
3865 }
Brian Curtind40e6f72010-07-08 21:39:08 +00003866
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03003867 wchar_t *tmp;
3868 tmp = PyMem_Realloc(target_path != buf ? target_path : NULL,
3869 result_length * sizeof(*tmp));
3870 if (!tmp) {
3871 result = PyErr_NoMemory();
3872 goto cleanup;
3873 }
3874
3875 buf_size = result_length;
3876 target_path = tmp;
Steve Dower23ad6d02018-02-22 10:39:10 -08003877 }
Brian Curtind40e6f72010-07-08 21:39:08 +00003878
Victor Stinner9d3b93b2011-11-22 02:27:30 +01003879 result = PyUnicode_FromWideChar(target_path, result_length);
Steve Dower23ad6d02018-02-22 10:39:10 -08003880 if (path->narrow)
3881 Py_SETREF(result, PyUnicode_EncodeFSDefault(result));
Steve Dower23ad6d02018-02-22 10:39:10 -08003882
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03003883cleanup:
3884 if (target_path != buf) {
3885 PyMem_Free(target_path);
3886 }
3887 CloseHandle(hFile);
3888 return result;
Larry Hastings2f936352014-08-05 14:04:04 +10003889}
Brian Curtin62857742010-09-06 17:07:27 +00003890
Serhiy Storchakaf0b50152015-05-13 00:52:39 +03003891/*[clinic input]
3892os._isdir
3893
Serhiy Storchaka0185f342018-09-18 11:28:51 +03003894 path as arg: object
Serhiy Storchakaf0b50152015-05-13 00:52:39 +03003895 /
3896
Serhiy Storchaka579f0382016-11-08 20:21:22 +02003897Return true if the pathname refers to an existing directory.
Serhiy Storchakaf0b50152015-05-13 00:52:39 +03003898[clinic start generated code]*/
3899
Brian Curtin9c669cc2011-06-08 18:17:18 -05003900static PyObject *
Serhiy Storchaka0185f342018-09-18 11:28:51 +03003901os__isdir(PyObject *module, PyObject *arg)
3902/*[clinic end generated code: output=404f334d85d4bf25 input=36cb6785874d479e]*/
Brian Curtin9c669cc2011-06-08 18:17:18 -05003903{
Brian Curtin9c669cc2011-06-08 18:17:18 -05003904 DWORD attributes;
Serhiy Storchaka0185f342018-09-18 11:28:51 +03003905 path_t path = PATH_T_INITIALIZE("_isdir", "path", 0, 0);
3906
3907 if (!path_converter(arg, &path)) {
3908 if (PyErr_ExceptionMatches(PyExc_ValueError)) {
3909 PyErr_Clear();
3910 Py_RETURN_FALSE;
3911 }
3912 return NULL;
3913 }
Brian Curtin9c669cc2011-06-08 18:17:18 -05003914
Steve Dowerb22a6772016-07-17 20:49:38 -07003915 Py_BEGIN_ALLOW_THREADS
Serhiy Storchaka0185f342018-09-18 11:28:51 +03003916 attributes = GetFileAttributesW(path.wide);
Steve Dowerb22a6772016-07-17 20:49:38 -07003917 Py_END_ALLOW_THREADS
Brian Curtin9c669cc2011-06-08 18:17:18 -05003918
Serhiy Storchaka0185f342018-09-18 11:28:51 +03003919 path_cleanup(&path);
Brian Curtin9c669cc2011-06-08 18:17:18 -05003920 if (attributes == INVALID_FILE_ATTRIBUTES)
3921 Py_RETURN_FALSE;
3922
Brian Curtin9c669cc2011-06-08 18:17:18 -05003923 if (attributes & FILE_ATTRIBUTE_DIRECTORY)
3924 Py_RETURN_TRUE;
3925 else
3926 Py_RETURN_FALSE;
3927}
Tim Golden6b528062013-08-01 12:44:00 +01003928
Tim Golden6b528062013-08-01 12:44:00 +01003929
Larry Hastings2f936352014-08-05 14:04:04 +10003930/*[clinic input]
3931os._getvolumepathname
3932
Steve Dower23ad6d02018-02-22 10:39:10 -08003933 path: path_t
Larry Hastings2f936352014-08-05 14:04:04 +10003934
3935A helper function for ismount on Win32.
3936[clinic start generated code]*/
3937
Larry Hastings2f936352014-08-05 14:04:04 +10003938static PyObject *
Steve Dower23ad6d02018-02-22 10:39:10 -08003939os__getvolumepathname_impl(PyObject *module, path_t *path)
3940/*[clinic end generated code: output=804c63fd13a1330b input=722b40565fa21552]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003941{
3942 PyObject *result;
Serhiy Storchakadeab18d2016-05-07 16:45:18 +03003943 wchar_t *mountpath=NULL;
Victor Stinner6edddfa2013-11-24 19:22:57 +01003944 size_t buflen;
Tim Golden6b528062013-08-01 12:44:00 +01003945 BOOL ret;
3946
Tim Golden6b528062013-08-01 12:44:00 +01003947 /* Volume path should be shorter than entire path */
Steve Dower23ad6d02018-02-22 10:39:10 -08003948 buflen = Py_MAX(path->length, MAX_PATH);
Victor Stinner6edddfa2013-11-24 19:22:57 +01003949
Victor Stinner850a18e2017-10-24 16:53:32 -07003950 if (buflen > PY_DWORD_MAX) {
Victor Stinner6edddfa2013-11-24 19:22:57 +01003951 PyErr_SetString(PyExc_OverflowError, "path too long");
3952 return NULL;
3953 }
3954
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02003955 mountpath = PyMem_New(wchar_t, buflen);
Tim Golden6b528062013-08-01 12:44:00 +01003956 if (mountpath == NULL)
3957 return PyErr_NoMemory();
3958
3959 Py_BEGIN_ALLOW_THREADS
Steve Dower23ad6d02018-02-22 10:39:10 -08003960 ret = GetVolumePathNameW(path->wide, mountpath,
Victor Stinner6edddfa2013-11-24 19:22:57 +01003961 Py_SAFE_DOWNCAST(buflen, size_t, DWORD));
Tim Golden6b528062013-08-01 12:44:00 +01003962 Py_END_ALLOW_THREADS
3963
3964 if (!ret) {
Steve Dower23ad6d02018-02-22 10:39:10 -08003965 result = win32_error_object("_getvolumepathname", path->object);
Tim Golden6b528062013-08-01 12:44:00 +01003966 goto exit;
3967 }
3968 result = PyUnicode_FromWideChar(mountpath, wcslen(mountpath));
Steve Dower23ad6d02018-02-22 10:39:10 -08003969 if (path->narrow)
3970 Py_SETREF(result, PyUnicode_EncodeFSDefault(result));
Tim Golden6b528062013-08-01 12:44:00 +01003971
3972exit:
3973 PyMem_Free(mountpath);
3974 return result;
3975}
Tim Golden6b528062013-08-01 12:44:00 +01003976
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00003977#endif /* MS_WINDOWS */
Mark Hammondef8b6542001-05-13 08:04:26 +00003978
Larry Hastings2f936352014-08-05 14:04:04 +10003979
3980/*[clinic input]
3981os.mkdir
3982
3983 path : path_t
3984
3985 mode: int = 0o777
3986
3987 *
3988
3989 dir_fd : dir_fd(requires='mkdirat') = None
3990
3991# "mkdir(path, mode=0o777, *, dir_fd=None)\n\n\
3992
3993Create a directory.
3994
3995If dir_fd is not None, it should be a file descriptor open to a directory,
3996 and path should be relative; path will then be relative to that directory.
3997dir_fd may not be implemented on your platform.
3998 If it is unavailable, using it will raise a NotImplementedError.
3999
4000The mode argument is ignored on Windows.
4001[clinic start generated code]*/
4002
Larry Hastings2f936352014-08-05 14:04:04 +10004003static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004004os_mkdir_impl(PyObject *module, path_t *path, int mode, int dir_fd)
4005/*[clinic end generated code: output=a70446903abe821f input=e965f68377e9b1ce]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004006{
4007 int result;
Mark Hammondc2e85bd2002-10-03 05:10:39 +00004008
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00004009#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +00004010 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -07004011 result = CreateDirectoryW(path->wide, NULL);
Victor Stinner8c62be82010-05-06 00:08:46 +00004012 Py_END_ALLOW_THREADS
Mark Hammondc2e85bd2002-10-03 05:10:39 +00004013
Larry Hastings2f936352014-08-05 14:04:04 +10004014 if (!result)
4015 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004016#else
Victor Stinner8c62be82010-05-06 00:08:46 +00004017 Py_BEGIN_ALLOW_THREADS
Larry Hastings9cf065c2012-06-22 16:30:09 -07004018#if HAVE_MKDIRAT
4019 if (dir_fd != DEFAULT_DIR_FD)
Larry Hastings2f936352014-08-05 14:04:04 +10004020 result = mkdirat(dir_fd, path->narrow, mode);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004021 else
4022#endif
Erik Bray03eb11f2017-10-27 14:27:06 +02004023#if defined(__WATCOMC__) && !defined(__QNX__)
Larry Hastings2f936352014-08-05 14:04:04 +10004024 result = mkdir(path->narrow);
Guido van Rossuma4916fa1996-05-23 22:58:55 +00004025#else
Larry Hastings2f936352014-08-05 14:04:04 +10004026 result = mkdir(path->narrow, mode);
Guido van Rossuma4916fa1996-05-23 22:58:55 +00004027#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00004028 Py_END_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10004029 if (result < 0)
4030 return path_error(path);
Steve Dowercc16be82016-09-08 10:35:16 -07004031#endif /* MS_WINDOWS */
Larry Hastings2f936352014-08-05 14:04:04 +10004032 Py_RETURN_NONE;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00004033}
4034
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00004035
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004036/* sys/resource.h is needed for at least: wait3(), wait4(), broken nice. */
4037#if defined(HAVE_SYS_RESOURCE_H)
Thomas Wouterse38b2f12001-07-11 22:35:31 +00004038#include <sys/resource.h>
4039#endif
Thomas Wouterse38b2f12001-07-11 22:35:31 +00004040
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004041
4042#ifdef HAVE_NICE
Larry Hastings2f936352014-08-05 14:04:04 +10004043/*[clinic input]
4044os.nice
4045
4046 increment: int
4047 /
4048
4049Add increment to the priority of process and return the new priority.
4050[clinic start generated code]*/
4051
Larry Hastings2f936352014-08-05 14:04:04 +10004052static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004053os_nice_impl(PyObject *module, int increment)
4054/*[clinic end generated code: output=9dad8a9da8109943 input=864be2d402a21da2]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004055{
4056 int value;
Thomas Woutersc2c12dc2001-07-11 14:45:34 +00004057
Victor Stinner8c62be82010-05-06 00:08:46 +00004058 /* There are two flavours of 'nice': one that returns the new
4059 priority (as required by almost all standards out there) and the
Benjamin Peterson288d1da2017-09-28 22:44:27 -07004060 Linux/FreeBSD one, which returns '0' on success and advices
Victor Stinner8c62be82010-05-06 00:08:46 +00004061 the use of getpriority() to get the new priority.
Tim Peters5aa91602002-01-30 05:46:57 +00004062
Victor Stinner8c62be82010-05-06 00:08:46 +00004063 If we are of the nice family that returns the new priority, we
4064 need to clear errno before the call, and check if errno is filled
4065 before calling posix_error() on a returnvalue of -1, because the
4066 -1 may be the actual new priority! */
Thomas Woutersc2c12dc2001-07-11 14:45:34 +00004067
Victor Stinner8c62be82010-05-06 00:08:46 +00004068 errno = 0;
4069 value = nice(increment);
Thomas Wouterse38b2f12001-07-11 22:35:31 +00004070#if defined(HAVE_BROKEN_NICE) && defined(HAVE_GETPRIORITY)
Victor Stinner8c62be82010-05-06 00:08:46 +00004071 if (value == 0)
4072 value = getpriority(PRIO_PROCESS, 0);
Thomas Woutersc2c12dc2001-07-11 14:45:34 +00004073#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00004074 if (value == -1 && errno != 0)
4075 /* either nice() or getpriority() returned an error */
4076 return posix_error();
4077 return PyLong_FromLong((long) value);
Guido van Rossum775f4da1993-01-09 17:18:52 +00004078}
Guido van Rossumb6775db1994-08-01 11:34:53 +00004079#endif /* HAVE_NICE */
Guido van Rossum1ff6cb41991-04-08 20:59:13 +00004080
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00004081
4082#ifdef HAVE_GETPRIORITY
Larry Hastings2f936352014-08-05 14:04:04 +10004083/*[clinic input]
4084os.getpriority
4085
4086 which: int
4087 who: int
4088
4089Return program scheduling priority.
4090[clinic start generated code]*/
4091
Larry Hastings2f936352014-08-05 14:04:04 +10004092static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004093os_getpriority_impl(PyObject *module, int which, int who)
4094/*[clinic end generated code: output=c41b7b63c7420228 input=9be615d40e2544ef]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004095{
4096 int retval;
4097
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00004098 errno = 0;
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00004099 retval = getpriority(which, who);
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00004100 if (errno != 0)
4101 return posix_error();
4102 return PyLong_FromLong((long)retval);
4103}
4104#endif /* HAVE_GETPRIORITY */
4105
4106
4107#ifdef HAVE_SETPRIORITY
Larry Hastings2f936352014-08-05 14:04:04 +10004108/*[clinic input]
4109os.setpriority
4110
4111 which: int
4112 who: int
4113 priority: int
4114
4115Set program scheduling priority.
4116[clinic start generated code]*/
4117
Larry Hastings2f936352014-08-05 14:04:04 +10004118static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004119os_setpriority_impl(PyObject *module, int which, int who, int priority)
4120/*[clinic end generated code: output=3d910d95a7771eb2 input=710ccbf65b9dc513]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004121{
4122 int retval;
4123
4124 retval = setpriority(which, who, priority);
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00004125 if (retval == -1)
4126 return posix_error();
4127 Py_RETURN_NONE;
4128}
4129#endif /* HAVE_SETPRIORITY */
4130
4131
Barry Warsaw53699e91996-12-10 23:23:01 +00004132static PyObject *
Larry Hastings2f936352014-08-05 14:04:04 +10004133internal_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 +00004134{
Serhiy Storchakadeab18d2016-05-07 16:45:18 +03004135 const char *function_name = is_replace ? "replace" : "rename";
Larry Hastings9cf065c2012-06-22 16:30:09 -07004136 int dir_fd_specified;
Larry Hastings9cf065c2012-06-22 16:30:09 -07004137
Mark Hammondc2e85bd2002-10-03 05:10:39 +00004138#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +00004139 BOOL result;
Antoine Pitrouf3b2d882012-01-30 22:08:52 +01004140 int flags = is_replace ? MOVEFILE_REPLACE_EXISTING : 0;
Mark Hammondc2e85bd2002-10-03 05:10:39 +00004141#else
Larry Hastings9cf065c2012-06-22 16:30:09 -07004142 int result;
Mark Hammondc2e85bd2002-10-03 05:10:39 +00004143#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -07004144
Larry Hastings9cf065c2012-06-22 16:30:09 -07004145 dir_fd_specified = (src_dir_fd != DEFAULT_DIR_FD) ||
4146 (dst_dir_fd != DEFAULT_DIR_FD);
4147#ifndef HAVE_RENAMEAT
4148 if (dir_fd_specified) {
4149 argument_unavailable_error(function_name, "src_dir_fd and dst_dir_fd");
Larry Hastings2f936352014-08-05 14:04:04 +10004150 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07004151 }
4152#endif
4153
Larry Hastings9cf065c2012-06-22 16:30:09 -07004154#ifdef MS_WINDOWS
4155 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -07004156 result = MoveFileExW(src->wide, dst->wide, flags);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004157 Py_END_ALLOW_THREADS
4158
Larry Hastings2f936352014-08-05 14:04:04 +10004159 if (!result)
4160 return path_error2(src, dst);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004161
4162#else
Steve Dowercc16be82016-09-08 10:35:16 -07004163 if ((src->narrow && dst->wide) || (src->wide && dst->narrow)) {
4164 PyErr_Format(PyExc_ValueError,
4165 "%s: src and dst must be the same type", function_name);
4166 return NULL;
4167 }
4168
Larry Hastings9cf065c2012-06-22 16:30:09 -07004169 Py_BEGIN_ALLOW_THREADS
4170#ifdef HAVE_RENAMEAT
4171 if (dir_fd_specified)
Larry Hastings2f936352014-08-05 14:04:04 +10004172 result = renameat(src_dir_fd, src->narrow, dst_dir_fd, dst->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004173 else
4174#endif
Steve Dowercc16be82016-09-08 10:35:16 -07004175 result = rename(src->narrow, dst->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004176 Py_END_ALLOW_THREADS
4177
Larry Hastings2f936352014-08-05 14:04:04 +10004178 if (result)
4179 return path_error2(src, dst);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004180#endif
Larry Hastings2f936352014-08-05 14:04:04 +10004181 Py_RETURN_NONE;
4182}
Larry Hastings9cf065c2012-06-22 16:30:09 -07004183
Larry Hastings2f936352014-08-05 14:04:04 +10004184
4185/*[clinic input]
4186os.rename
4187
4188 src : path_t
4189 dst : path_t
4190 *
4191 src_dir_fd : dir_fd = None
4192 dst_dir_fd : dir_fd = None
4193
4194Rename a file or directory.
4195
4196If either src_dir_fd or dst_dir_fd is not None, it should be a file
4197 descriptor open to a directory, and the respective path string (src or dst)
4198 should be relative; the path will then be relative to that directory.
4199src_dir_fd and dst_dir_fd, may not be implemented on your platform.
4200 If they are unavailable, using them will raise a NotImplementedError.
4201[clinic start generated code]*/
4202
Antoine Pitrouf3b2d882012-01-30 22:08:52 +01004203static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004204os_rename_impl(PyObject *module, path_t *src, path_t *dst, int src_dir_fd,
Larry Hastings89964c42015-04-14 18:07:59 -04004205 int dst_dir_fd)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004206/*[clinic end generated code: output=59e803072cf41230 input=faa61c847912c850]*/
Antoine Pitrouf3b2d882012-01-30 22:08:52 +01004207{
Larry Hastings2f936352014-08-05 14:04:04 +10004208 return internal_rename(src, dst, src_dir_fd, dst_dir_fd, 0);
Antoine Pitrouf3b2d882012-01-30 22:08:52 +01004209}
4210
Larry Hastings2f936352014-08-05 14:04:04 +10004211
4212/*[clinic input]
4213os.replace = os.rename
4214
4215Rename a file or directory, overwriting the destination.
4216
4217If either src_dir_fd or dst_dir_fd is not None, it should be a file
4218 descriptor open to a directory, and the respective path string (src or dst)
4219 should be relative; the path will then be relative to that directory.
4220src_dir_fd and dst_dir_fd, may not be implemented on your platform.
Anthony Sottile73d60022019-02-12 23:15:54 -05004221 If they are unavailable, using them will raise a NotImplementedError.
Larry Hastings2f936352014-08-05 14:04:04 +10004222[clinic start generated code]*/
4223
Larry Hastings2f936352014-08-05 14:04:04 +10004224static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004225os_replace_impl(PyObject *module, path_t *src, path_t *dst, int src_dir_fd,
4226 int dst_dir_fd)
Anthony Sottile73d60022019-02-12 23:15:54 -05004227/*[clinic end generated code: output=1968c02e7857422b input=c003f0def43378ef]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004228{
4229 return internal_rename(src, dst, src_dir_fd, dst_dir_fd, 1);
4230}
4231
4232
4233/*[clinic input]
4234os.rmdir
4235
4236 path: path_t
4237 *
4238 dir_fd: dir_fd(requires='unlinkat') = None
4239
4240Remove a directory.
4241
4242If dir_fd is not None, it should be a file descriptor open to a directory,
4243 and path should be relative; path will then be relative to that directory.
4244dir_fd may not be implemented on your platform.
4245 If it is unavailable, using it will raise a NotImplementedError.
4246[clinic start generated code]*/
4247
Larry Hastings2f936352014-08-05 14:04:04 +10004248static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004249os_rmdir_impl(PyObject *module, path_t *path, int dir_fd)
4250/*[clinic end generated code: output=080eb54f506e8301 input=38c8b375ca34a7e2]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004251{
4252 int result;
Larry Hastingsb698d8e2012-06-23 16:55:07 -07004253
4254 Py_BEGIN_ALLOW_THREADS
4255#ifdef MS_WINDOWS
Steve Dowercc16be82016-09-08 10:35:16 -07004256 /* Windows, success=1, UNIX, success=0 */
4257 result = !RemoveDirectoryW(path->wide);
Larry Hastingsb698d8e2012-06-23 16:55:07 -07004258#else
4259#ifdef HAVE_UNLINKAT
4260 if (dir_fd != DEFAULT_DIR_FD)
Larry Hastings2f936352014-08-05 14:04:04 +10004261 result = unlinkat(dir_fd, path->narrow, AT_REMOVEDIR);
Larry Hastingsb698d8e2012-06-23 16:55:07 -07004262 else
4263#endif
Larry Hastings2f936352014-08-05 14:04:04 +10004264 result = rmdir(path->narrow);
Larry Hastingsb698d8e2012-06-23 16:55:07 -07004265#endif
4266 Py_END_ALLOW_THREADS
4267
Larry Hastings2f936352014-08-05 14:04:04 +10004268 if (result)
4269 return path_error(path);
Larry Hastingsb698d8e2012-06-23 16:55:07 -07004270
Larry Hastings2f936352014-08-05 14:04:04 +10004271 Py_RETURN_NONE;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00004272}
4273
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00004274
Guido van Rossuma4916fa1996-05-23 22:58:55 +00004275#ifdef HAVE_SYSTEM
Larry Hastings2f936352014-08-05 14:04:04 +10004276#ifdef MS_WINDOWS
4277/*[clinic input]
4278os.system -> long
4279
4280 command: Py_UNICODE
4281
4282Execute the command in a subshell.
4283[clinic start generated code]*/
4284
Larry Hastings2f936352014-08-05 14:04:04 +10004285static long
Serhiy Storchakaafb3e712018-12-14 11:19:51 +02004286os_system_impl(PyObject *module, const Py_UNICODE *command)
4287/*[clinic end generated code: output=5b7c3599c068ca42 input=303f5ce97df606b0]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004288{
4289 long result;
Steve Dowerb82e17e2019-05-23 08:45:22 -07004290
4291 if (PySys_Audit("system", "(u)", command) < 0) {
4292 return -1;
4293 }
4294
Victor Stinner8c62be82010-05-06 00:08:46 +00004295 Py_BEGIN_ALLOW_THREADS
Steve Dowerc3630612016-11-19 18:41:16 -08004296 _Py_BEGIN_SUPPRESS_IPH
Larry Hastings2f936352014-08-05 14:04:04 +10004297 result = _wsystem(command);
Steve Dowerc3630612016-11-19 18:41:16 -08004298 _Py_END_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00004299 Py_END_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10004300 return result;
4301}
4302#else /* MS_WINDOWS */
4303/*[clinic input]
4304os.system -> long
4305
4306 command: FSConverter
4307
4308Execute the command in a subshell.
4309[clinic start generated code]*/
4310
Larry Hastings2f936352014-08-05 14:04:04 +10004311static long
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004312os_system_impl(PyObject *module, PyObject *command)
4313/*[clinic end generated code: output=290fc437dd4f33a0 input=86a58554ba6094af]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004314{
4315 long result;
Serhiy Storchakadeab18d2016-05-07 16:45:18 +03004316 const char *bytes = PyBytes_AsString(command);
Steve Dowerb82e17e2019-05-23 08:45:22 -07004317
4318 if (PySys_Audit("system", "(O)", command) < 0) {
4319 return -1;
4320 }
4321
Larry Hastings2f936352014-08-05 14:04:04 +10004322 Py_BEGIN_ALLOW_THREADS
4323 result = system(bytes);
4324 Py_END_ALLOW_THREADS
4325 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00004326}
Guido van Rossuma4916fa1996-05-23 22:58:55 +00004327#endif
Larry Hastings2f936352014-08-05 14:04:04 +10004328#endif /* HAVE_SYSTEM */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00004329
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00004330
Larry Hastings2f936352014-08-05 14:04:04 +10004331/*[clinic input]
4332os.umask
4333
4334 mask: int
4335 /
4336
4337Set the current numeric umask and return the previous umask.
4338[clinic start generated code]*/
4339
Larry Hastings2f936352014-08-05 14:04:04 +10004340static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004341os_umask_impl(PyObject *module, int mask)
4342/*[clinic end generated code: output=a2e33ce3bc1a6e33 input=ab6bfd9b24d8a7e8]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004343{
4344 int i = (int)umask(mask);
Victor Stinner8c62be82010-05-06 00:08:46 +00004345 if (i < 0)
4346 return posix_error();
4347 return PyLong_FromLong((long)i);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00004348}
4349
Brian Curtind40e6f72010-07-08 21:39:08 +00004350#ifdef MS_WINDOWS
4351
4352/* override the default DeleteFileW behavior so that directory
4353symlinks can be removed with this function, the same as with
4354Unix symlinks */
4355BOOL WINAPI Py_DeleteFileW(LPCWSTR lpFileName)
4356{
4357 WIN32_FILE_ATTRIBUTE_DATA info;
4358 WIN32_FIND_DATAW find_data;
4359 HANDLE find_data_handle;
4360 int is_directory = 0;
4361 int is_link = 0;
4362
4363 if (GetFileAttributesExW(lpFileName, GetFileExInfoStandard, &info)) {
4364 is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00004365
Brian Curtind40e6f72010-07-08 21:39:08 +00004366 /* Get WIN32_FIND_DATA structure for the path to determine if
4367 it is a symlink */
4368 if(is_directory &&
4369 info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
4370 find_data_handle = FindFirstFileW(lpFileName, &find_data);
4371
4372 if(find_data_handle != INVALID_HANDLE_VALUE) {
Tim Golden0321cf22014-05-05 19:46:17 +01004373 /* IO_REPARSE_TAG_SYMLINK if it is a symlink and
4374 IO_REPARSE_TAG_MOUNT_POINT if it is a junction point. */
4375 is_link = find_data.dwReserved0 == IO_REPARSE_TAG_SYMLINK ||
4376 find_data.dwReserved0 == IO_REPARSE_TAG_MOUNT_POINT;
Brian Curtind40e6f72010-07-08 21:39:08 +00004377 FindClose(find_data_handle);
4378 }
4379 }
4380 }
4381
4382 if (is_directory && is_link)
4383 return RemoveDirectoryW(lpFileName);
4384
4385 return DeleteFileW(lpFileName);
4386}
4387#endif /* MS_WINDOWS */
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00004388
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00004389
Larry Hastings2f936352014-08-05 14:04:04 +10004390/*[clinic input]
4391os.unlink
4392
4393 path: path_t
4394 *
4395 dir_fd: dir_fd(requires='unlinkat')=None
4396
4397Remove a file (same as remove()).
4398
4399If dir_fd is not None, it should be a file descriptor open to a directory,
4400 and path should be relative; path will then be relative to that directory.
4401dir_fd may not be implemented on your platform.
4402 If it is unavailable, using it will raise a NotImplementedError.
4403
4404[clinic start generated code]*/
4405
Larry Hastings2f936352014-08-05 14:04:04 +10004406static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004407os_unlink_impl(PyObject *module, path_t *path, int dir_fd)
4408/*[clinic end generated code: output=621797807b9963b1 input=d7bcde2b1b2a2552]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004409{
4410 int result;
Larry Hastings9cf065c2012-06-22 16:30:09 -07004411
4412 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04004413 _Py_BEGIN_SUPPRESS_IPH
Larry Hastings9cf065c2012-06-22 16:30:09 -07004414#ifdef MS_WINDOWS
Steve Dowercc16be82016-09-08 10:35:16 -07004415 /* Windows, success=1, UNIX, success=0 */
4416 result = !Py_DeleteFileW(path->wide);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004417#else
Larry Hastings9cf065c2012-06-22 16:30:09 -07004418#ifdef HAVE_UNLINKAT
4419 if (dir_fd != DEFAULT_DIR_FD)
Larry Hastings2f936352014-08-05 14:04:04 +10004420 result = unlinkat(dir_fd, path->narrow, 0);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004421 else
4422#endif /* HAVE_UNLINKAT */
Larry Hastings2f936352014-08-05 14:04:04 +10004423 result = unlink(path->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004424#endif
Steve Dower8fc89802015-04-12 00:26:27 -04004425 _Py_END_SUPPRESS_IPH
Larry Hastings9cf065c2012-06-22 16:30:09 -07004426 Py_END_ALLOW_THREADS
4427
Larry Hastings2f936352014-08-05 14:04:04 +10004428 if (result)
4429 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004430
Larry Hastings2f936352014-08-05 14:04:04 +10004431 Py_RETURN_NONE;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00004432}
4433
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00004434
Larry Hastings2f936352014-08-05 14:04:04 +10004435/*[clinic input]
4436os.remove = os.unlink
4437
4438Remove a file (same as unlink()).
4439
4440If dir_fd is not None, it should be a file descriptor open to a directory,
4441 and path should be relative; path will then be relative to that directory.
4442dir_fd may not be implemented on your platform.
4443 If it is unavailable, using it will raise a NotImplementedError.
4444[clinic start generated code]*/
4445
Larry Hastings2f936352014-08-05 14:04:04 +10004446static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004447os_remove_impl(PyObject *module, path_t *path, int dir_fd)
4448/*[clinic end generated code: output=a8535b28f0068883 input=e05c5ab55cd30983]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004449{
4450 return os_unlink_impl(module, path, dir_fd);
4451}
4452
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00004453
Larry Hastings605a62d2012-06-24 04:33:36 -07004454static PyStructSequence_Field uname_result_fields[] = {
4455 {"sysname", "operating system name"},
4456 {"nodename", "name of machine on network (implementation-defined)"},
4457 {"release", "operating system release"},
4458 {"version", "operating system version"},
4459 {"machine", "hardware identifier"},
4460 {NULL}
4461};
4462
4463PyDoc_STRVAR(uname_result__doc__,
4464"uname_result: Result from os.uname().\n\n\
4465This object may be accessed either as a tuple of\n\
4466 (sysname, nodename, release, version, machine),\n\
4467or via the attributes sysname, nodename, release, version, and machine.\n\
4468\n\
4469See os.uname for more information.");
4470
4471static PyStructSequence_Desc uname_result_desc = {
4472 "uname_result", /* name */
4473 uname_result__doc__, /* doc */
4474 uname_result_fields,
4475 5
4476};
4477
Eddie Elizondo474eedf2018-11-13 04:09:31 -08004478static PyTypeObject* UnameResultType;
Larry Hastings605a62d2012-06-24 04:33:36 -07004479
4480
4481#ifdef HAVE_UNAME
Larry Hastings2f936352014-08-05 14:04:04 +10004482/*[clinic input]
4483os.uname
4484
4485Return an object identifying the current operating system.
4486
4487The object behaves like a named tuple with the following fields:
4488 (sysname, nodename, release, version, machine)
4489
4490[clinic start generated code]*/
4491
Larry Hastings2f936352014-08-05 14:04:04 +10004492static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004493os_uname_impl(PyObject *module)
4494/*[clinic end generated code: output=e6a49cf1a1508a19 input=e68bd246db3043ed]*/
Guido van Rossumc39de5f1992-02-05 11:15:54 +00004495{
Victor Stinner8c62be82010-05-06 00:08:46 +00004496 struct utsname u;
4497 int res;
Larry Hastings605a62d2012-06-24 04:33:36 -07004498 PyObject *value;
Neal Norwitze241ce82003-02-17 18:17:05 +00004499
Victor Stinner8c62be82010-05-06 00:08:46 +00004500 Py_BEGIN_ALLOW_THREADS
4501 res = uname(&u);
4502 Py_END_ALLOW_THREADS
4503 if (res < 0)
4504 return posix_error();
Larry Hastings605a62d2012-06-24 04:33:36 -07004505
Eddie Elizondo474eedf2018-11-13 04:09:31 -08004506 value = PyStructSequence_New(UnameResultType);
Larry Hastings605a62d2012-06-24 04:33:36 -07004507 if (value == NULL)
4508 return NULL;
4509
4510#define SET(i, field) \
4511 { \
Victor Stinnera534fc42013-06-03 22:07:27 +02004512 PyObject *o = PyUnicode_DecodeFSDefault(field); \
Larry Hastings605a62d2012-06-24 04:33:36 -07004513 if (!o) { \
4514 Py_DECREF(value); \
4515 return NULL; \
4516 } \
4517 PyStructSequence_SET_ITEM(value, i, o); \
4518 } \
4519
4520 SET(0, u.sysname);
4521 SET(1, u.nodename);
4522 SET(2, u.release);
4523 SET(3, u.version);
4524 SET(4, u.machine);
4525
4526#undef SET
4527
4528 return value;
Guido van Rossumc39de5f1992-02-05 11:15:54 +00004529}
Guido van Rossumb6775db1994-08-01 11:34:53 +00004530#endif /* HAVE_UNAME */
Guido van Rossum1ff6cb41991-04-08 20:59:13 +00004531
Larry Hastings9e3e70b2011-09-08 19:29:07 -07004532
Larry Hastings9cf065c2012-06-22 16:30:09 -07004533
4534typedef struct {
4535 int now;
4536 time_t atime_s;
4537 long atime_ns;
4538 time_t mtime_s;
4539 long mtime_ns;
4540} utime_t;
4541
4542/*
Victor Stinner484df002014-10-09 13:52:31 +02004543 * these macros assume that "ut" is a pointer to a utime_t
Larry Hastings9cf065c2012-06-22 16:30:09 -07004544 * they also intentionally leak the declaration of a pointer named "time"
4545 */
4546#define UTIME_TO_TIMESPEC \
4547 struct timespec ts[2]; \
4548 struct timespec *time; \
Victor Stinner484df002014-10-09 13:52:31 +02004549 if (ut->now) \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004550 time = NULL; \
4551 else { \
Victor Stinner484df002014-10-09 13:52:31 +02004552 ts[0].tv_sec = ut->atime_s; \
4553 ts[0].tv_nsec = ut->atime_ns; \
4554 ts[1].tv_sec = ut->mtime_s; \
4555 ts[1].tv_nsec = ut->mtime_ns; \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004556 time = ts; \
4557 } \
4558
4559#define UTIME_TO_TIMEVAL \
4560 struct timeval tv[2]; \
4561 struct timeval *time; \
Victor Stinner484df002014-10-09 13:52:31 +02004562 if (ut->now) \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004563 time = NULL; \
4564 else { \
Victor Stinner484df002014-10-09 13:52:31 +02004565 tv[0].tv_sec = ut->atime_s; \
4566 tv[0].tv_usec = ut->atime_ns / 1000; \
4567 tv[1].tv_sec = ut->mtime_s; \
4568 tv[1].tv_usec = ut->mtime_ns / 1000; \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004569 time = tv; \
4570 } \
4571
4572#define UTIME_TO_UTIMBUF \
Georg Brandle1a7d9d2014-10-12 08:45:15 +02004573 struct utimbuf u; \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004574 struct utimbuf *time; \
Victor Stinner484df002014-10-09 13:52:31 +02004575 if (ut->now) \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004576 time = NULL; \
4577 else { \
Georg Brandle1a7d9d2014-10-12 08:45:15 +02004578 u.actime = ut->atime_s; \
4579 u.modtime = ut->mtime_s; \
4580 time = &u; \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004581 }
4582
4583#define UTIME_TO_TIME_T \
4584 time_t timet[2]; \
Georg Brandle1a7d9d2014-10-12 08:45:15 +02004585 time_t *time; \
Victor Stinner484df002014-10-09 13:52:31 +02004586 if (ut->now) \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004587 time = NULL; \
4588 else { \
Victor Stinner484df002014-10-09 13:52:31 +02004589 timet[0] = ut->atime_s; \
4590 timet[1] = ut->mtime_s; \
Georg Brandle1a7d9d2014-10-12 08:45:15 +02004591 time = timet; \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004592 } \
4593
4594
Victor Stinner528a9ab2015-09-03 21:30:26 +02004595#if defined(HAVE_FUTIMESAT) || defined(HAVE_UTIMENSAT)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004596
4597static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02004598utime_dir_fd(utime_t *ut, int dir_fd, const char *path, int follow_symlinks)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004599{
4600#ifdef HAVE_UTIMENSAT
4601 int flags = follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW;
4602 UTIME_TO_TIMESPEC;
4603 return utimensat(dir_fd, path, time, flags);
4604#elif defined(HAVE_FUTIMESAT)
4605 UTIME_TO_TIMEVAL;
4606 /*
4607 * follow_symlinks will never be false here;
4608 * we only allow !follow_symlinks and dir_fd together
4609 * if we have utimensat()
4610 */
4611 assert(follow_symlinks);
4612 return futimesat(dir_fd, path, time);
4613#endif
4614}
4615
Larry Hastings2f936352014-08-05 14:04:04 +10004616 #define FUTIMENSAT_DIR_FD_CONVERTER dir_fd_converter
4617#else
4618 #define FUTIMENSAT_DIR_FD_CONVERTER dir_fd_unavailable
Larry Hastings9cf065c2012-06-22 16:30:09 -07004619#endif
4620
Victor Stinner528a9ab2015-09-03 21:30:26 +02004621#if defined(HAVE_FUTIMES) || defined(HAVE_FUTIMENS)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004622
4623static int
Victor Stinner484df002014-10-09 13:52:31 +02004624utime_fd(utime_t *ut, int fd)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004625{
4626#ifdef HAVE_FUTIMENS
4627 UTIME_TO_TIMESPEC;
4628 return futimens(fd, time);
4629#else
4630 UTIME_TO_TIMEVAL;
4631 return futimes(fd, time);
4632#endif
4633}
4634
Larry Hastings2f936352014-08-05 14:04:04 +10004635 #define PATH_UTIME_HAVE_FD 1
4636#else
4637 #define PATH_UTIME_HAVE_FD 0
Larry Hastings9cf065c2012-06-22 16:30:09 -07004638#endif
4639
Victor Stinner5ebae872015-09-22 01:29:33 +02004640#if defined(HAVE_UTIMENSAT) || defined(HAVE_LUTIMES)
4641# define UTIME_HAVE_NOFOLLOW_SYMLINKS
4642#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -07004643
Victor Stinner4552ced2015-09-21 22:37:15 +02004644#ifdef UTIME_HAVE_NOFOLLOW_SYMLINKS
Larry Hastings9cf065c2012-06-22 16:30:09 -07004645
4646static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02004647utime_nofollow_symlinks(utime_t *ut, const char *path)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004648{
4649#ifdef HAVE_UTIMENSAT
4650 UTIME_TO_TIMESPEC;
4651 return utimensat(DEFAULT_DIR_FD, path, time, AT_SYMLINK_NOFOLLOW);
4652#else
4653 UTIME_TO_TIMEVAL;
4654 return lutimes(path, time);
4655#endif
4656}
4657
4658#endif
4659
4660#ifndef MS_WINDOWS
4661
4662static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02004663utime_default(utime_t *ut, const char *path)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004664{
4665#ifdef HAVE_UTIMENSAT
4666 UTIME_TO_TIMESPEC;
4667 return utimensat(DEFAULT_DIR_FD, path, time, 0);
4668#elif defined(HAVE_UTIMES)
4669 UTIME_TO_TIMEVAL;
4670 return utimes(path, time);
4671#elif defined(HAVE_UTIME_H)
4672 UTIME_TO_UTIMBUF;
4673 return utime(path, time);
4674#else
4675 UTIME_TO_TIME_T;
4676 return utime(path, time);
4677#endif
4678}
4679
4680#endif
4681
Larry Hastings76ad59b2012-05-03 00:30:07 -07004682static int
4683split_py_long_to_s_and_ns(PyObject *py_long, time_t *s, long *ns)
4684{
4685 int result = 0;
Benjamin Petersonfbd85a02012-05-04 11:06:09 -04004686 PyObject *divmod;
Larry Hastings76ad59b2012-05-03 00:30:07 -07004687 divmod = PyNumber_Divmod(py_long, billion);
4688 if (!divmod)
4689 goto exit;
Oren Milman0bd1a2d2018-09-12 22:14:35 +03004690 if (!PyTuple_Check(divmod) || PyTuple_GET_SIZE(divmod) != 2) {
4691 PyErr_Format(PyExc_TypeError,
4692 "%.200s.__divmod__() must return a 2-tuple, not %.200s",
4693 Py_TYPE(py_long)->tp_name, Py_TYPE(divmod)->tp_name);
4694 goto exit;
4695 }
Larry Hastings76ad59b2012-05-03 00:30:07 -07004696 *s = _PyLong_AsTime_t(PyTuple_GET_ITEM(divmod, 0));
4697 if ((*s == -1) && PyErr_Occurred())
4698 goto exit;
4699 *ns = PyLong_AsLong(PyTuple_GET_ITEM(divmod, 1));
Benjamin Peterson35a8f0d2012-05-04 01:10:59 -04004700 if ((*ns == -1) && PyErr_Occurred())
Larry Hastings76ad59b2012-05-03 00:30:07 -07004701 goto exit;
4702
4703 result = 1;
4704exit:
4705 Py_XDECREF(divmod);
4706 return result;
4707}
4708
Larry Hastings2f936352014-08-05 14:04:04 +10004709
4710/*[clinic input]
4711os.utime
4712
4713 path: path_t(allow_fd='PATH_UTIME_HAVE_FD')
4714 times: object = NULL
4715 *
4716 ns: object = NULL
4717 dir_fd: dir_fd(requires='futimensat') = None
4718 follow_symlinks: bool=True
4719
Martin Panter0ff89092015-09-09 01:56:53 +00004720# "utime(path, times=None, *[, ns], dir_fd=None, follow_symlinks=True)\n\
Larry Hastings2f936352014-08-05 14:04:04 +10004721
4722Set the access and modified time of path.
4723
4724path may always be specified as a string.
4725On some platforms, path may also be specified as an open file descriptor.
4726 If this functionality is unavailable, using it raises an exception.
4727
4728If times is not None, it must be a tuple (atime, mtime);
4729 atime and mtime should be expressed as float seconds since the epoch.
Martin Panter0ff89092015-09-09 01:56:53 +00004730If ns is specified, it must be a tuple (atime_ns, mtime_ns);
Larry Hastings2f936352014-08-05 14:04:04 +10004731 atime_ns and mtime_ns should be expressed as integer nanoseconds
4732 since the epoch.
Martin Panter0ff89092015-09-09 01:56:53 +00004733If times is None and ns is unspecified, utime uses the current time.
Larry Hastings2f936352014-08-05 14:04:04 +10004734Specifying tuples for both times and ns is an error.
4735
4736If dir_fd is not None, it should be a file descriptor open to a directory,
4737 and path should be relative; path will then be relative to that directory.
4738If follow_symlinks is False, and the last element of the path is a symbolic
4739 link, utime will modify the symbolic link itself instead of the file the
4740 link points to.
4741It is an error to use dir_fd or follow_symlinks when specifying path
4742 as an open file descriptor.
4743dir_fd and follow_symlinks may not be available on your platform.
4744 If they are unavailable, using them will raise a NotImplementedError.
4745
4746[clinic start generated code]*/
4747
Larry Hastings2f936352014-08-05 14:04:04 +10004748static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004749os_utime_impl(PyObject *module, path_t *path, PyObject *times, PyObject *ns,
4750 int dir_fd, int follow_symlinks)
4751/*[clinic end generated code: output=cfcac69d027b82cf input=081cdc54ca685385]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004752{
Larry Hastings9cf065c2012-06-22 16:30:09 -07004753#ifdef MS_WINDOWS
4754 HANDLE hFile;
4755 FILETIME atime, mtime;
4756#else
4757 int result;
4758#endif
Larry Hastings76ad59b2012-05-03 00:30:07 -07004759
Larry Hastings2f936352014-08-05 14:04:04 +10004760 utime_t utime;
Larry Hastings76ad59b2012-05-03 00:30:07 -07004761
Christian Heimesb3c87242013-08-01 00:08:16 +02004762 memset(&utime, 0, sizeof(utime_t));
Larry Hastings76ad59b2012-05-03 00:30:07 -07004763
Larry Hastings9cf065c2012-06-22 16:30:09 -07004764 if (times && (times != Py_None) && ns) {
4765 PyErr_SetString(PyExc_ValueError,
4766 "utime: you may specify either 'times'"
4767 " or 'ns' but not both");
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004768 return NULL;
Larry Hastings76ad59b2012-05-03 00:30:07 -07004769 }
4770
4771 if (times && (times != Py_None)) {
Antoine Pitroucf8a1e52013-04-17 22:06:44 +02004772 time_t a_sec, m_sec;
4773 long a_nsec, m_nsec;
Larry Hastings76ad59b2012-05-03 00:30:07 -07004774 if (!PyTuple_CheckExact(times) || (PyTuple_Size(times) != 2)) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07004775 PyErr_SetString(PyExc_TypeError,
4776 "utime: 'times' must be either"
4777 " a tuple of two ints or None");
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004778 return NULL;
Larry Hastings76ad59b2012-05-03 00:30:07 -07004779 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07004780 utime.now = 0;
Benjamin Petersonb399ab22012-05-04 01:31:13 -04004781 if (_PyTime_ObjectToTimespec(PyTuple_GET_ITEM(times, 0),
Victor Stinnerdca028b2015-03-30 01:02:57 +02004782 &a_sec, &a_nsec, _PyTime_ROUND_FLOOR) == -1 ||
Benjamin Petersonb399ab22012-05-04 01:31:13 -04004783 _PyTime_ObjectToTimespec(PyTuple_GET_ITEM(times, 1),
Victor Stinnerdca028b2015-03-30 01:02:57 +02004784 &m_sec, &m_nsec, _PyTime_ROUND_FLOOR) == -1) {
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004785 return NULL;
Larry Hastingsb3336402012-05-04 02:31:57 -07004786 }
Antoine Pitroucf8a1e52013-04-17 22:06:44 +02004787 utime.atime_s = a_sec;
4788 utime.atime_ns = a_nsec;
4789 utime.mtime_s = m_sec;
4790 utime.mtime_ns = m_nsec;
Larry Hastings76ad59b2012-05-03 00:30:07 -07004791 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07004792 else if (ns) {
Larry Hastings76ad59b2012-05-03 00:30:07 -07004793 if (!PyTuple_CheckExact(ns) || (PyTuple_Size(ns) != 2)) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07004794 PyErr_SetString(PyExc_TypeError,
4795 "utime: 'ns' must be a tuple of two ints");
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004796 return NULL;
Larry Hastings76ad59b2012-05-03 00:30:07 -07004797 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07004798 utime.now = 0;
Benjamin Petersonb399ab22012-05-04 01:31:13 -04004799 if (!split_py_long_to_s_and_ns(PyTuple_GET_ITEM(ns, 0),
Larry Hastings9cf065c2012-06-22 16:30:09 -07004800 &utime.atime_s, &utime.atime_ns) ||
Benjamin Petersonb399ab22012-05-04 01:31:13 -04004801 !split_py_long_to_s_and_ns(PyTuple_GET_ITEM(ns, 1),
Larry Hastings9cf065c2012-06-22 16:30:09 -07004802 &utime.mtime_s, &utime.mtime_ns)) {
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004803 return NULL;
Larry Hastingsb3336402012-05-04 02:31:57 -07004804 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07004805 }
4806 else {
4807 /* times and ns are both None/unspecified. use "now". */
4808 utime.now = 1;
Larry Hastings76ad59b2012-05-03 00:30:07 -07004809 }
4810
Victor Stinner4552ced2015-09-21 22:37:15 +02004811#if !defined(UTIME_HAVE_NOFOLLOW_SYMLINKS)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004812 if (follow_symlinks_specified("utime", follow_symlinks))
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004813 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07004814#endif
Benjamin Petersonb399ab22012-05-04 01:31:13 -04004815
Larry Hastings2f936352014-08-05 14:04:04 +10004816 if (path_and_dir_fd_invalid("utime", path, dir_fd) ||
4817 dir_fd_and_fd_invalid("utime", dir_fd, path->fd) ||
4818 fd_and_follow_symlinks_invalid("utime", path->fd, follow_symlinks))
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004819 return NULL;
Larry Hastings76ad59b2012-05-03 00:30:07 -07004820
Larry Hastings9cf065c2012-06-22 16:30:09 -07004821#if !defined(HAVE_UTIMENSAT)
4822 if ((dir_fd != DEFAULT_DIR_FD) && (!follow_symlinks)) {
Georg Brandl969288e2012-06-26 09:25:44 +02004823 PyErr_SetString(PyExc_ValueError,
Larry Hastings9cf065c2012-06-22 16:30:09 -07004824 "utime: cannot use dir_fd and follow_symlinks "
4825 "together on this platform");
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004826 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07004827 }
4828#endif
Larry Hastings76ad59b2012-05-03 00:30:07 -07004829
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00004830#ifdef MS_WINDOWS
Larry Hastings9cf065c2012-06-22 16:30:09 -07004831 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -07004832 hFile = CreateFileW(path->wide, FILE_WRITE_ATTRIBUTES, 0,
4833 NULL, OPEN_EXISTING,
4834 FILE_FLAG_BACKUP_SEMANTICS, NULL);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004835 Py_END_ALLOW_THREADS
4836 if (hFile == INVALID_HANDLE_VALUE) {
Larry Hastings2f936352014-08-05 14:04:04 +10004837 path_error(path);
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004838 return NULL;
Larry Hastingsb3336402012-05-04 02:31:57 -07004839 }
4840
Larry Hastings9cf065c2012-06-22 16:30:09 -07004841 if (utime.now) {
Antoine Pitrou91a7af32013-11-23 15:23:26 +01004842 GetSystemTimeAsFileTime(&mtime);
4843 atime = mtime;
Victor Stinner8c62be82010-05-06 00:08:46 +00004844 }
Victor Stinner8c62be82010-05-06 00:08:46 +00004845 else {
Steve Dowerbf1f3762015-02-21 15:26:02 -08004846 _Py_time_t_to_FILE_TIME(utime.atime_s, utime.atime_ns, &atime);
4847 _Py_time_t_to_FILE_TIME(utime.mtime_s, utime.mtime_ns, &mtime);
Victor Stinner8c62be82010-05-06 00:08:46 +00004848 }
4849 if (!SetFileTime(hFile, NULL, &atime, &mtime)) {
4850 /* Avoid putting the file name into the error here,
4851 as that may confuse the user into believing that
4852 something is wrong with the file, when it also
4853 could be the time stamp that gives a problem. */
Victor Stinnerb024e842012-10-31 22:24:06 +01004854 PyErr_SetFromWindowsErr(0);
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004855 CloseHandle(hFile);
4856 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00004857 }
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004858 CloseHandle(hFile);
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00004859#else /* MS_WINDOWS */
Larry Hastings9cf065c2012-06-22 16:30:09 -07004860 Py_BEGIN_ALLOW_THREADS
Guido van Rossum1ff6cb41991-04-08 20:59:13 +00004861
Victor Stinner4552ced2015-09-21 22:37:15 +02004862#ifdef UTIME_HAVE_NOFOLLOW_SYMLINKS
Larry Hastings9cf065c2012-06-22 16:30:09 -07004863 if ((!follow_symlinks) && (dir_fd == DEFAULT_DIR_FD))
Larry Hastings2f936352014-08-05 14:04:04 +10004864 result = utime_nofollow_symlinks(&utime, path->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004865 else
Larry Hastings9e3e70b2011-09-08 19:29:07 -07004866#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -07004867
Victor Stinner528a9ab2015-09-03 21:30:26 +02004868#if defined(HAVE_FUTIMESAT) || defined(HAVE_UTIMENSAT)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004869 if ((dir_fd != DEFAULT_DIR_FD) || (!follow_symlinks))
Larry Hastings2f936352014-08-05 14:04:04 +10004870 result = utime_dir_fd(&utime, dir_fd, path->narrow, follow_symlinks);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004871 else
4872#endif
4873
Victor Stinner528a9ab2015-09-03 21:30:26 +02004874#if defined(HAVE_FUTIMES) || defined(HAVE_FUTIMENS)
Larry Hastings2f936352014-08-05 14:04:04 +10004875 if (path->fd != -1)
4876 result = utime_fd(&utime, path->fd);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004877 else
4878#endif
4879
Larry Hastings2f936352014-08-05 14:04:04 +10004880 result = utime_default(&utime, path->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004881
4882 Py_END_ALLOW_THREADS
4883
4884 if (result < 0) {
4885 /* see previous comment about not putting filename in error here */
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004886 posix_error();
4887 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00004888 }
Larry Hastings76ad59b2012-05-03 00:30:07 -07004889
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00004890#endif /* MS_WINDOWS */
Larry Hastings9cf065c2012-06-22 16:30:09 -07004891
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004892 Py_RETURN_NONE;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00004893}
4894
Guido van Rossum3b066191991-06-04 19:40:25 +00004895/* Process operations */
Guido van Rossum85e3b011991-06-03 12:42:10 +00004896
Larry Hastings2f936352014-08-05 14:04:04 +10004897
4898/*[clinic input]
4899os._exit
4900
4901 status: int
4902
4903Exit to the system with specified status, without normal exit processing.
4904[clinic start generated code]*/
4905
Larry Hastings2f936352014-08-05 14:04:04 +10004906static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004907os__exit_impl(PyObject *module, int status)
4908/*[clinic end generated code: output=116e52d9c2260d54 input=5e6d57556b0c4a62]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004909{
4910 _exit(status);
Victor Stinner8c62be82010-05-06 00:08:46 +00004911 return NULL; /* Make gcc -Wall happy */
Guido van Rossum85e3b011991-06-03 12:42:10 +00004912}
4913
Steve Dowercc16be82016-09-08 10:35:16 -07004914#if defined(HAVE_WEXECV) || defined(HAVE_WSPAWNV)
4915#define EXECV_CHAR wchar_t
4916#else
4917#define EXECV_CHAR char
4918#endif
4919
pxinwrf2d7ac72019-05-21 18:46:37 +08004920#if defined(HAVE_EXECV) || defined(HAVE_SPAWNV) || defined(HAVE_RTPSPAWN)
Martin v. Löwis114619e2002-10-07 06:44:21 +00004921static void
Steve Dowercc16be82016-09-08 10:35:16 -07004922free_string_array(EXECV_CHAR **array, Py_ssize_t count)
Martin v. Löwis114619e2002-10-07 06:44:21 +00004923{
Victor Stinner8c62be82010-05-06 00:08:46 +00004924 Py_ssize_t i;
4925 for (i = 0; i < count; i++)
4926 PyMem_Free(array[i]);
4927 PyMem_DEL(array);
Martin v. Löwis114619e2002-10-07 06:44:21 +00004928}
Martin v. Löwis011e8422009-05-05 04:43:17 +00004929
Berker Peksag81816462016-09-15 20:19:47 +03004930static int
4931fsconvert_strdup(PyObject *o, EXECV_CHAR **out)
Martin v. Löwis011e8422009-05-05 04:43:17 +00004932{
Victor Stinner8c62be82010-05-06 00:08:46 +00004933 Py_ssize_t size;
Berker Peksag81816462016-09-15 20:19:47 +03004934 PyObject *ub;
4935 int result = 0;
Steve Dowercc16be82016-09-08 10:35:16 -07004936#if defined(HAVE_WEXECV) || defined(HAVE_WSPAWNV)
Berker Peksag81816462016-09-15 20:19:47 +03004937 if (!PyUnicode_FSDecoder(o, &ub))
Steve Dowercc16be82016-09-08 10:35:16 -07004938 return 0;
Berker Peksag81816462016-09-15 20:19:47 +03004939 *out = PyUnicode_AsWideCharString(ub, &size);
4940 if (*out)
4941 result = 1;
Steve Dowercc16be82016-09-08 10:35:16 -07004942#else
Berker Peksag81816462016-09-15 20:19:47 +03004943 if (!PyUnicode_FSConverter(o, &ub))
Victor Stinner8c62be82010-05-06 00:08:46 +00004944 return 0;
Berker Peksag81816462016-09-15 20:19:47 +03004945 size = PyBytes_GET_SIZE(ub);
4946 *out = PyMem_Malloc(size + 1);
4947 if (*out) {
4948 memcpy(*out, PyBytes_AS_STRING(ub), size + 1);
4949 result = 1;
4950 } else
Victor Stinner50abf222013-11-07 23:56:10 +01004951 PyErr_NoMemory();
Steve Dowercc16be82016-09-08 10:35:16 -07004952#endif
Berker Peksag81816462016-09-15 20:19:47 +03004953 Py_DECREF(ub);
4954 return result;
Martin v. Löwis011e8422009-05-05 04:43:17 +00004955}
Martin v. Löwis114619e2002-10-07 06:44:21 +00004956#endif
4957
pxinwrf2d7ac72019-05-21 18:46:37 +08004958#if defined(HAVE_EXECV) || defined (HAVE_FEXECVE) || defined(HAVE_RTPSPAWN)
Steve Dowercc16be82016-09-08 10:35:16 -07004959static EXECV_CHAR**
Victor Stinner13bb71c2010-04-23 21:41:56 +00004960parse_envlist(PyObject* env, Py_ssize_t *envc_ptr)
4961{
Victor Stinner8c62be82010-05-06 00:08:46 +00004962 Py_ssize_t i, pos, envc;
4963 PyObject *keys=NULL, *vals=NULL;
Berker Peksag81816462016-09-15 20:19:47 +03004964 PyObject *key, *val, *key2, *val2, *keyval;
Steve Dowercc16be82016-09-08 10:35:16 -07004965 EXECV_CHAR **envlist;
Victor Stinner13bb71c2010-04-23 21:41:56 +00004966
Victor Stinner8c62be82010-05-06 00:08:46 +00004967 i = PyMapping_Size(env);
4968 if (i < 0)
4969 return NULL;
Steve Dowercc16be82016-09-08 10:35:16 -07004970 envlist = PyMem_NEW(EXECV_CHAR *, i + 1);
Victor Stinner8c62be82010-05-06 00:08:46 +00004971 if (envlist == NULL) {
4972 PyErr_NoMemory();
4973 return NULL;
4974 }
4975 envc = 0;
4976 keys = PyMapping_Keys(env);
Victor Stinnerb0314272013-11-14 21:37:05 +01004977 if (!keys)
4978 goto error;
Victor Stinner8c62be82010-05-06 00:08:46 +00004979 vals = PyMapping_Values(env);
Victor Stinnerb0314272013-11-14 21:37:05 +01004980 if (!vals)
Victor Stinner8c62be82010-05-06 00:08:46 +00004981 goto error;
4982 if (!PyList_Check(keys) || !PyList_Check(vals)) {
4983 PyErr_Format(PyExc_TypeError,
4984 "env.keys() or env.values() is not a list");
4985 goto error;
4986 }
Victor Stinner13bb71c2010-04-23 21:41:56 +00004987
Victor Stinner8c62be82010-05-06 00:08:46 +00004988 for (pos = 0; pos < i; pos++) {
4989 key = PyList_GetItem(keys, pos);
4990 val = PyList_GetItem(vals, pos);
4991 if (!key || !val)
4992 goto error;
Victor Stinner13bb71c2010-04-23 21:41:56 +00004993
Berker Peksag81816462016-09-15 20:19:47 +03004994#if defined(HAVE_WEXECV) || defined(HAVE_WSPAWNV)
4995 if (!PyUnicode_FSDecoder(key, &key2))
4996 goto error;
4997 if (!PyUnicode_FSDecoder(val, &val2)) {
4998 Py_DECREF(key2);
4999 goto error;
5000 }
Serhiy Storchaka77703942017-06-25 07:33:01 +03005001 /* Search from index 1 because on Windows starting '=' is allowed for
5002 defining hidden environment variables. */
5003 if (PyUnicode_GET_LENGTH(key2) == 0 ||
5004 PyUnicode_FindChar(key2, '=', 1, PyUnicode_GET_LENGTH(key2), 1) != -1)
5005 {
5006 PyErr_SetString(PyExc_ValueError, "illegal environment variable name");
Eric N. Vander Weelea7874c72017-06-26 21:35:20 -04005007 Py_DECREF(key2);
5008 Py_DECREF(val2);
Serhiy Storchaka77703942017-06-25 07:33:01 +03005009 goto error;
5010 }
Berker Peksag81816462016-09-15 20:19:47 +03005011 keyval = PyUnicode_FromFormat("%U=%U", key2, val2);
5012#else
5013 if (!PyUnicode_FSConverter(key, &key2))
5014 goto error;
5015 if (!PyUnicode_FSConverter(val, &val2)) {
5016 Py_DECREF(key2);
5017 goto error;
5018 }
Serhiy Storchaka77703942017-06-25 07:33:01 +03005019 if (PyBytes_GET_SIZE(key2) == 0 ||
5020 strchr(PyBytes_AS_STRING(key2) + 1, '=') != NULL)
5021 {
5022 PyErr_SetString(PyExc_ValueError, "illegal environment variable name");
Eric N. Vander Weelea7874c72017-06-26 21:35:20 -04005023 Py_DECREF(key2);
5024 Py_DECREF(val2);
Serhiy Storchaka77703942017-06-25 07:33:01 +03005025 goto error;
5026 }
Berker Peksag81816462016-09-15 20:19:47 +03005027 keyval = PyBytes_FromFormat("%s=%s", PyBytes_AS_STRING(key2),
5028 PyBytes_AS_STRING(val2));
5029#endif
5030 Py_DECREF(key2);
5031 Py_DECREF(val2);
Steve Dowercc16be82016-09-08 10:35:16 -07005032 if (!keyval)
Victor Stinner8c62be82010-05-06 00:08:46 +00005033 goto error;
Steve Dowercc16be82016-09-08 10:35:16 -07005034
5035 if (!fsconvert_strdup(keyval, &envlist[envc++])) {
5036 Py_DECREF(keyval);
Victor Stinner8c62be82010-05-06 00:08:46 +00005037 goto error;
5038 }
Berker Peksag81816462016-09-15 20:19:47 +03005039
Steve Dowercc16be82016-09-08 10:35:16 -07005040 Py_DECREF(keyval);
Victor Stinner8c62be82010-05-06 00:08:46 +00005041 }
5042 Py_DECREF(vals);
5043 Py_DECREF(keys);
Victor Stinner13bb71c2010-04-23 21:41:56 +00005044
Victor Stinner8c62be82010-05-06 00:08:46 +00005045 envlist[envc] = 0;
5046 *envc_ptr = envc;
5047 return envlist;
Victor Stinner13bb71c2010-04-23 21:41:56 +00005048
5049error:
Victor Stinner8c62be82010-05-06 00:08:46 +00005050 Py_XDECREF(keys);
5051 Py_XDECREF(vals);
Steve Dowercc16be82016-09-08 10:35:16 -07005052 free_string_array(envlist, envc);
Victor Stinner8c62be82010-05-06 00:08:46 +00005053 return NULL;
Victor Stinner13bb71c2010-04-23 21:41:56 +00005054}
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00005055
Steve Dowercc16be82016-09-08 10:35:16 -07005056static EXECV_CHAR**
Ross Lagerwall7807c352011-03-17 20:20:30 +02005057parse_arglist(PyObject* argv, Py_ssize_t *argc)
5058{
5059 int i;
Steve Dowercc16be82016-09-08 10:35:16 -07005060 EXECV_CHAR **argvlist = PyMem_NEW(EXECV_CHAR *, *argc+1);
Ross Lagerwall7807c352011-03-17 20:20:30 +02005061 if (argvlist == NULL) {
5062 PyErr_NoMemory();
5063 return NULL;
5064 }
5065 for (i = 0; i < *argc; i++) {
Ross Lagerwall9ad63e02011-03-19 09:11:14 +02005066 PyObject* item = PySequence_ITEM(argv, i);
5067 if (item == NULL)
5068 goto fail;
5069 if (!fsconvert_strdup(item, &argvlist[i])) {
5070 Py_DECREF(item);
Ross Lagerwall7807c352011-03-17 20:20:30 +02005071 goto fail;
5072 }
Ross Lagerwall9ad63e02011-03-19 09:11:14 +02005073 Py_DECREF(item);
Ross Lagerwall7807c352011-03-17 20:20:30 +02005074 }
5075 argvlist[*argc] = NULL;
5076 return argvlist;
5077fail:
Ross Lagerwall9ad63e02011-03-19 09:11:14 +02005078 *argc = i;
Ross Lagerwall7807c352011-03-17 20:20:30 +02005079 free_string_array(argvlist, *argc);
5080 return NULL;
5081}
Steve Dowercc16be82016-09-08 10:35:16 -07005082
Ross Lagerwall7807c352011-03-17 20:20:30 +02005083#endif
5084
Larry Hastings2f936352014-08-05 14:04:04 +10005085
Ross Lagerwall7807c352011-03-17 20:20:30 +02005086#ifdef HAVE_EXECV
Larry Hastings2f936352014-08-05 14:04:04 +10005087/*[clinic input]
5088os.execv
5089
Steve Dowercc16be82016-09-08 10:35:16 -07005090 path: path_t
Larry Hastings2f936352014-08-05 14:04:04 +10005091 Path of executable file.
5092 argv: object
5093 Tuple or list of strings.
5094 /
5095
5096Execute an executable path with arguments, replacing current process.
5097[clinic start generated code]*/
5098
Larry Hastings2f936352014-08-05 14:04:04 +10005099static PyObject *
Steve Dowercc16be82016-09-08 10:35:16 -07005100os_execv_impl(PyObject *module, path_t *path, PyObject *argv)
5101/*[clinic end generated code: output=3b52fec34cd0dafd input=9bac31efae07dac7]*/
Larry Hastings2f936352014-08-05 14:04:04 +10005102{
Steve Dowercc16be82016-09-08 10:35:16 -07005103 EXECV_CHAR **argvlist;
Ross Lagerwall7807c352011-03-17 20:20:30 +02005104 Py_ssize_t argc;
5105
5106 /* execv has two arguments: (path, argv), where
5107 argv is a list or tuple of strings. */
5108
Ross Lagerwall7807c352011-03-17 20:20:30 +02005109 if (!PyList_Check(argv) && !PyTuple_Check(argv)) {
5110 PyErr_SetString(PyExc_TypeError,
5111 "execv() arg 2 must be a tuple or list");
Ross Lagerwall7807c352011-03-17 20:20:30 +02005112 return NULL;
5113 }
5114 argc = PySequence_Size(argv);
5115 if (argc < 1) {
5116 PyErr_SetString(PyExc_ValueError, "execv() arg 2 must not be empty");
Ross Lagerwall7807c352011-03-17 20:20:30 +02005117 return NULL;
5118 }
5119
5120 argvlist = parse_arglist(argv, &argc);
5121 if (argvlist == NULL) {
Ross Lagerwall7807c352011-03-17 20:20:30 +02005122 return NULL;
5123 }
Steve Dowerbce26262016-11-19 19:17:26 -08005124 if (!argvlist[0][0]) {
5125 PyErr_SetString(PyExc_ValueError,
5126 "execv() arg 2 first element cannot be empty");
5127 free_string_array(argvlist, argc);
5128 return NULL;
5129 }
Ross Lagerwall7807c352011-03-17 20:20:30 +02005130
Steve Dowerbce26262016-11-19 19:17:26 -08005131 _Py_BEGIN_SUPPRESS_IPH
Steve Dowercc16be82016-09-08 10:35:16 -07005132#ifdef HAVE_WEXECV
5133 _wexecv(path->wide, argvlist);
5134#else
5135 execv(path->narrow, argvlist);
5136#endif
Steve Dowerbce26262016-11-19 19:17:26 -08005137 _Py_END_SUPPRESS_IPH
Ross Lagerwall7807c352011-03-17 20:20:30 +02005138
5139 /* If we get here it's definitely an error */
5140
5141 free_string_array(argvlist, argc);
Ross Lagerwall7807c352011-03-17 20:20:30 +02005142 return posix_error();
5143}
5144
Larry Hastings2f936352014-08-05 14:04:04 +10005145
5146/*[clinic input]
5147os.execve
5148
5149 path: path_t(allow_fd='PATH_HAVE_FEXECVE')
5150 Path of executable file.
5151 argv: object
5152 Tuple or list of strings.
5153 env: object
5154 Dictionary of strings mapping to strings.
5155
5156Execute an executable path with arguments, replacing current process.
5157[clinic start generated code]*/
5158
Larry Hastings2f936352014-08-05 14:04:04 +10005159static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005160os_execve_impl(PyObject *module, path_t *path, PyObject *argv, PyObject *env)
5161/*[clinic end generated code: output=ff9fa8e4da8bde58 input=626804fa092606d9]*/
Larry Hastings2f936352014-08-05 14:04:04 +10005162{
Steve Dowercc16be82016-09-08 10:35:16 -07005163 EXECV_CHAR **argvlist = NULL;
5164 EXECV_CHAR **envlist;
Ross Lagerwall7807c352011-03-17 20:20:30 +02005165 Py_ssize_t argc, envc;
Guido van Rossumc6dcc9f1993-11-05 10:15:19 +00005166
Victor Stinner8c62be82010-05-06 00:08:46 +00005167 /* execve has three arguments: (path, argv, env), where
5168 argv is a list or tuple of strings and env is a dictionary
5169 like posix.environ. */
Guido van Rossumc6dcc9f1993-11-05 10:15:19 +00005170
Ross Lagerwall7807c352011-03-17 20:20:30 +02005171 if (!PyList_Check(argv) && !PyTuple_Check(argv)) {
Victor Stinner8c62be82010-05-06 00:08:46 +00005172 PyErr_SetString(PyExc_TypeError,
Larry Hastings9cf065c2012-06-22 16:30:09 -07005173 "execve: argv must be a tuple or list");
5174 goto fail;
Victor Stinner8c62be82010-05-06 00:08:46 +00005175 }
Ross Lagerwall7807c352011-03-17 20:20:30 +02005176 argc = PySequence_Size(argv);
Steve Dowerbce26262016-11-19 19:17:26 -08005177 if (argc < 1) {
5178 PyErr_SetString(PyExc_ValueError, "execve: argv must not be empty");
5179 return NULL;
5180 }
5181
Victor Stinner8c62be82010-05-06 00:08:46 +00005182 if (!PyMapping_Check(env)) {
5183 PyErr_SetString(PyExc_TypeError,
Larry Hastings9cf065c2012-06-22 16:30:09 -07005184 "execve: environment must be a mapping object");
5185 goto fail;
Victor Stinner8c62be82010-05-06 00:08:46 +00005186 }
Guido van Rossumc6dcc9f1993-11-05 10:15:19 +00005187
Ross Lagerwall7807c352011-03-17 20:20:30 +02005188 argvlist = parse_arglist(argv, &argc);
Victor Stinner8c62be82010-05-06 00:08:46 +00005189 if (argvlist == NULL) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07005190 goto fail;
Victor Stinner8c62be82010-05-06 00:08:46 +00005191 }
Steve Dowerbce26262016-11-19 19:17:26 -08005192 if (!argvlist[0][0]) {
5193 PyErr_SetString(PyExc_ValueError,
5194 "execve: argv first element cannot be empty");
5195 goto fail;
5196 }
Guido van Rossumc6dcc9f1993-11-05 10:15:19 +00005197
Victor Stinner8c62be82010-05-06 00:08:46 +00005198 envlist = parse_envlist(env, &envc);
5199 if (envlist == NULL)
Ross Lagerwall7807c352011-03-17 20:20:30 +02005200 goto fail;
5201
Steve Dowerbce26262016-11-19 19:17:26 -08005202 _Py_BEGIN_SUPPRESS_IPH
Larry Hastings9cf065c2012-06-22 16:30:09 -07005203#ifdef HAVE_FEXECVE
Larry Hastings2f936352014-08-05 14:04:04 +10005204 if (path->fd > -1)
5205 fexecve(path->fd, argvlist, envlist);
Larry Hastings9cf065c2012-06-22 16:30:09 -07005206 else
5207#endif
Steve Dowercc16be82016-09-08 10:35:16 -07005208#ifdef HAVE_WEXECV
5209 _wexecve(path->wide, argvlist, envlist);
5210#else
Larry Hastings2f936352014-08-05 14:04:04 +10005211 execve(path->narrow, argvlist, envlist);
Steve Dowercc16be82016-09-08 10:35:16 -07005212#endif
Steve Dowerbce26262016-11-19 19:17:26 -08005213 _Py_END_SUPPRESS_IPH
Ross Lagerwall7807c352011-03-17 20:20:30 +02005214
5215 /* If we get here it's definitely an error */
5216
Alexey Izbyshev83460312018-10-20 03:28:22 +03005217 posix_path_error(path);
Ross Lagerwall7807c352011-03-17 20:20:30 +02005218
Steve Dowercc16be82016-09-08 10:35:16 -07005219 free_string_array(envlist, envc);
Ross Lagerwall7807c352011-03-17 20:20:30 +02005220 fail:
Larry Hastings9cf065c2012-06-22 16:30:09 -07005221 if (argvlist)
5222 free_string_array(argvlist, argc);
Ross Lagerwall7807c352011-03-17 20:20:30 +02005223 return NULL;
5224}
Steve Dowercc16be82016-09-08 10:35:16 -07005225
Larry Hastings9cf065c2012-06-22 16:30:09 -07005226#endif /* HAVE_EXECV */
5227
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005228#ifdef HAVE_POSIX_SPAWN
5229
5230enum posix_spawn_file_actions_identifier {
5231 POSIX_SPAWN_OPEN,
5232 POSIX_SPAWN_CLOSE,
5233 POSIX_SPAWN_DUP2
5234};
5235
William Orr81574b82018-10-01 22:19:56 -07005236#if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
Serhiy Storchakaef347532018-05-01 16:45:04 +03005237static int
Pablo Galindo254a4662018-09-07 16:44:24 +01005238convert_sched_param(PyObject *param, struct sched_param *res);
William Orr81574b82018-10-01 22:19:56 -07005239#endif
Pablo Galindo254a4662018-09-07 16:44:24 +01005240
5241static int
Victor Stinner325e4ba2019-02-01 15:47:24 +01005242parse_posix_spawn_flags(const char *func_name, PyObject *setpgroup,
5243 int resetids, int setsid, PyObject *setsigmask,
Pablo Galindo254a4662018-09-07 16:44:24 +01005244 PyObject *setsigdef, PyObject *scheduler,
5245 posix_spawnattr_t *attrp)
5246{
5247 long all_flags = 0;
5248
5249 errno = posix_spawnattr_init(attrp);
5250 if (errno) {
5251 posix_error();
5252 return -1;
5253 }
5254
5255 if (setpgroup) {
5256 pid_t pgid = PyLong_AsPid(setpgroup);
5257 if (pgid == (pid_t)-1 && PyErr_Occurred()) {
5258 goto fail;
5259 }
5260 errno = posix_spawnattr_setpgroup(attrp, pgid);
5261 if (errno) {
5262 posix_error();
5263 goto fail;
5264 }
5265 all_flags |= POSIX_SPAWN_SETPGROUP;
5266 }
5267
5268 if (resetids) {
5269 all_flags |= POSIX_SPAWN_RESETIDS;
5270 }
5271
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005272 if (setsid) {
5273#ifdef POSIX_SPAWN_SETSID
5274 all_flags |= POSIX_SPAWN_SETSID;
5275#elif defined(POSIX_SPAWN_SETSID_NP)
5276 all_flags |= POSIX_SPAWN_SETSID_NP;
5277#else
5278 argument_unavailable_error(func_name, "setsid");
5279 return -1;
5280#endif
5281 }
5282
Pablo Galindo254a4662018-09-07 16:44:24 +01005283 if (setsigmask) {
5284 sigset_t set;
5285 if (!_Py_Sigset_Converter(setsigmask, &set)) {
5286 goto fail;
5287 }
5288 errno = posix_spawnattr_setsigmask(attrp, &set);
5289 if (errno) {
5290 posix_error();
5291 goto fail;
5292 }
5293 all_flags |= POSIX_SPAWN_SETSIGMASK;
5294 }
5295
5296 if (setsigdef) {
5297 sigset_t set;
5298 if (!_Py_Sigset_Converter(setsigdef, &set)) {
5299 goto fail;
5300 }
5301 errno = posix_spawnattr_setsigdefault(attrp, &set);
5302 if (errno) {
5303 posix_error();
5304 goto fail;
5305 }
5306 all_flags |= POSIX_SPAWN_SETSIGDEF;
5307 }
5308
5309 if (scheduler) {
5310#ifdef POSIX_SPAWN_SETSCHEDULER
5311 PyObject *py_schedpolicy;
5312 struct sched_param schedparam;
5313
5314 if (!PyArg_ParseTuple(scheduler, "OO&"
5315 ";A scheduler tuple must have two elements",
5316 &py_schedpolicy, convert_sched_param, &schedparam)) {
5317 goto fail;
5318 }
5319 if (py_schedpolicy != Py_None) {
5320 int schedpolicy = _PyLong_AsInt(py_schedpolicy);
5321
5322 if (schedpolicy == -1 && PyErr_Occurred()) {
5323 goto fail;
5324 }
5325 errno = posix_spawnattr_setschedpolicy(attrp, schedpolicy);
5326 if (errno) {
5327 posix_error();
5328 goto fail;
5329 }
5330 all_flags |= POSIX_SPAWN_SETSCHEDULER;
5331 }
5332 errno = posix_spawnattr_setschedparam(attrp, &schedparam);
5333 if (errno) {
5334 posix_error();
5335 goto fail;
5336 }
5337 all_flags |= POSIX_SPAWN_SETSCHEDPARAM;
5338#else
5339 PyErr_SetString(PyExc_NotImplementedError,
5340 "The scheduler option is not supported in this system.");
5341 goto fail;
5342#endif
5343 }
5344
5345 errno = posix_spawnattr_setflags(attrp, all_flags);
5346 if (errno) {
5347 posix_error();
5348 goto fail;
5349 }
5350
5351 return 0;
5352
5353fail:
5354 (void)posix_spawnattr_destroy(attrp);
5355 return -1;
5356}
5357
5358static int
Serhiy Storchakaef347532018-05-01 16:45:04 +03005359parse_file_actions(PyObject *file_actions,
Pablo Galindocb970732018-06-19 09:19:50 +01005360 posix_spawn_file_actions_t *file_actionsp,
5361 PyObject *temp_buffer)
Serhiy Storchakaef347532018-05-01 16:45:04 +03005362{
5363 PyObject *seq;
5364 PyObject *file_action = NULL;
5365 PyObject *tag_obj;
5366
5367 seq = PySequence_Fast(file_actions,
5368 "file_actions must be a sequence or None");
5369 if (seq == NULL) {
5370 return -1;
5371 }
5372
5373 errno = posix_spawn_file_actions_init(file_actionsp);
5374 if (errno) {
5375 posix_error();
5376 Py_DECREF(seq);
5377 return -1;
5378 }
5379
5380 for (int i = 0; i < PySequence_Fast_GET_SIZE(seq); ++i) {
5381 file_action = PySequence_Fast_GET_ITEM(seq, i);
5382 Py_INCREF(file_action);
5383 if (!PyTuple_Check(file_action) || !PyTuple_GET_SIZE(file_action)) {
5384 PyErr_SetString(PyExc_TypeError,
5385 "Each file_actions element must be a non-empty tuple");
5386 goto fail;
5387 }
5388 long tag = PyLong_AsLong(PyTuple_GET_ITEM(file_action, 0));
5389 if (tag == -1 && PyErr_Occurred()) {
5390 goto fail;
5391 }
5392
5393 /* Populate the file_actions object */
5394 switch (tag) {
5395 case POSIX_SPAWN_OPEN: {
5396 int fd, oflag;
5397 PyObject *path;
5398 unsigned long mode;
5399 if (!PyArg_ParseTuple(file_action, "OiO&ik"
5400 ";A open file_action tuple must have 5 elements",
5401 &tag_obj, &fd, PyUnicode_FSConverter, &path,
5402 &oflag, &mode))
5403 {
5404 goto fail;
5405 }
Pablo Galindocb970732018-06-19 09:19:50 +01005406 if (PyList_Append(temp_buffer, path)) {
5407 Py_DECREF(path);
5408 goto fail;
5409 }
Serhiy Storchakaef347532018-05-01 16:45:04 +03005410 errno = posix_spawn_file_actions_addopen(file_actionsp,
5411 fd, PyBytes_AS_STRING(path), oflag, (mode_t)mode);
Pablo Galindocb970732018-06-19 09:19:50 +01005412 Py_DECREF(path);
Serhiy Storchakaef347532018-05-01 16:45:04 +03005413 if (errno) {
5414 posix_error();
5415 goto fail;
5416 }
5417 break;
5418 }
5419 case POSIX_SPAWN_CLOSE: {
5420 int fd;
5421 if (!PyArg_ParseTuple(file_action, "Oi"
5422 ";A close file_action tuple must have 2 elements",
5423 &tag_obj, &fd))
5424 {
5425 goto fail;
5426 }
5427 errno = posix_spawn_file_actions_addclose(file_actionsp, fd);
5428 if (errno) {
5429 posix_error();
5430 goto fail;
5431 }
5432 break;
5433 }
5434 case POSIX_SPAWN_DUP2: {
5435 int fd1, fd2;
5436 if (!PyArg_ParseTuple(file_action, "Oii"
5437 ";A dup2 file_action tuple must have 3 elements",
5438 &tag_obj, &fd1, &fd2))
5439 {
5440 goto fail;
5441 }
5442 errno = posix_spawn_file_actions_adddup2(file_actionsp,
5443 fd1, fd2);
5444 if (errno) {
5445 posix_error();
5446 goto fail;
5447 }
5448 break;
5449 }
5450 default: {
5451 PyErr_SetString(PyExc_TypeError,
5452 "Unknown file_actions identifier");
5453 goto fail;
5454 }
5455 }
5456 Py_DECREF(file_action);
5457 }
Pablo Galindo254a4662018-09-07 16:44:24 +01005458
Serhiy Storchakaef347532018-05-01 16:45:04 +03005459 Py_DECREF(seq);
5460 return 0;
5461
5462fail:
5463 Py_DECREF(seq);
5464 Py_DECREF(file_action);
5465 (void)posix_spawn_file_actions_destroy(file_actionsp);
5466 return -1;
5467}
5468
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005469
5470static PyObject *
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005471py_posix_spawn(int use_posix_spawnp, PyObject *module, path_t *path, PyObject *argv,
5472 PyObject *env, PyObject *file_actions,
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005473 PyObject *setpgroup, int resetids, int setsid, PyObject *setsigmask,
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005474 PyObject *setsigdef, PyObject *scheduler)
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005475{
Victor Stinner325e4ba2019-02-01 15:47:24 +01005476 const char *func_name = use_posix_spawnp ? "posix_spawnp" : "posix_spawn";
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005477 EXECV_CHAR **argvlist = NULL;
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005478 EXECV_CHAR **envlist = NULL;
Serhiy Storchakaef347532018-05-01 16:45:04 +03005479 posix_spawn_file_actions_t file_actions_buf;
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005480 posix_spawn_file_actions_t *file_actionsp = NULL;
Pablo Galindo254a4662018-09-07 16:44:24 +01005481 posix_spawnattr_t attr;
5482 posix_spawnattr_t *attrp = NULL;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005483 Py_ssize_t argc, envc;
Serhiy Storchakaef347532018-05-01 16:45:04 +03005484 PyObject *result = NULL;
Pablo Galindocb970732018-06-19 09:19:50 +01005485 PyObject *temp_buffer = NULL;
Serhiy Storchakaef347532018-05-01 16:45:04 +03005486 pid_t pid;
5487 int err_code;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005488
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005489 /* posix_spawn and posix_spawnp have three arguments: (path, argv, env), where
Serhiy Storchakaef347532018-05-01 16:45:04 +03005490 argv is a list or tuple of strings and env is a dictionary
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005491 like posix.environ. */
5492
Serhiy Storchakaef347532018-05-01 16:45:04 +03005493 if (!PyList_Check(argv) && !PyTuple_Check(argv)) {
Victor Stinner325e4ba2019-02-01 15:47:24 +01005494 PyErr_Format(PyExc_TypeError,
5495 "%s: argv must be a tuple or list", func_name);
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005496 goto exit;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005497 }
5498 argc = PySequence_Size(argv);
5499 if (argc < 1) {
Victor Stinner325e4ba2019-02-01 15:47:24 +01005500 PyErr_Format(PyExc_ValueError,
5501 "%s: argv must not be empty", func_name);
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005502 return NULL;
5503 }
5504
5505 if (!PyMapping_Check(env)) {
Victor Stinner325e4ba2019-02-01 15:47:24 +01005506 PyErr_Format(PyExc_TypeError,
5507 "%s: environment must be a mapping object", func_name);
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005508 goto exit;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005509 }
5510
5511 argvlist = parse_arglist(argv, &argc);
5512 if (argvlist == NULL) {
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005513 goto exit;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005514 }
5515 if (!argvlist[0][0]) {
Victor Stinner325e4ba2019-02-01 15:47:24 +01005516 PyErr_Format(PyExc_ValueError,
5517 "%s: argv first element cannot be empty", func_name);
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005518 goto exit;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005519 }
5520
5521 envlist = parse_envlist(env, &envc);
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005522 if (envlist == NULL) {
5523 goto exit;
5524 }
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005525
Anthony Shaw948ed8c2019-05-10 12:00:06 +10005526 if (file_actions != NULL && file_actions != Py_None) {
Pablo Galindocb970732018-06-19 09:19:50 +01005527 /* There is a bug in old versions of glibc that makes some of the
5528 * helper functions for manipulating file actions not copy the provided
5529 * buffers. The problem is that posix_spawn_file_actions_addopen does not
5530 * copy the value of path for some old versions of glibc (<2.20).
5531 * The use of temp_buffer here is a workaround that keeps the
5532 * python objects that own the buffers alive until posix_spawn gets called.
5533 * Check https://bugs.python.org/issue33630 and
5534 * https://sourceware.org/bugzilla/show_bug.cgi?id=17048 for more info.*/
5535 temp_buffer = PyList_New(0);
5536 if (!temp_buffer) {
5537 goto exit;
5538 }
5539 if (parse_file_actions(file_actions, &file_actions_buf, temp_buffer)) {
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005540 goto exit;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005541 }
Serhiy Storchakaef347532018-05-01 16:45:04 +03005542 file_actionsp = &file_actions_buf;
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005543 }
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005544
Victor Stinner325e4ba2019-02-01 15:47:24 +01005545 if (parse_posix_spawn_flags(func_name, setpgroup, resetids, setsid,
5546 setsigmask, setsigdef, scheduler, &attr)) {
Pablo Galindo254a4662018-09-07 16:44:24 +01005547 goto exit;
5548 }
5549 attrp = &attr;
5550
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005551 _Py_BEGIN_SUPPRESS_IPH
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005552#ifdef HAVE_POSIX_SPAWNP
5553 if (use_posix_spawnp) {
5554 err_code = posix_spawnp(&pid, path->narrow,
5555 file_actionsp, attrp, argvlist, envlist);
5556 }
5557 else
5558#endif /* HAVE_POSIX_SPAWNP */
5559 {
5560 err_code = posix_spawn(&pid, path->narrow,
5561 file_actionsp, attrp, argvlist, envlist);
5562 }
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005563 _Py_END_SUPPRESS_IPH
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005564
Serhiy Storchakaef347532018-05-01 16:45:04 +03005565 if (err_code) {
5566 errno = err_code;
5567 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, path->object);
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005568 goto exit;
5569 }
Gregory P. Smith1d300ce2018-12-30 21:13:02 -08005570#ifdef _Py_MEMORY_SANITIZER
5571 __msan_unpoison(&pid, sizeof(pid));
5572#endif
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005573 result = PyLong_FromPid(pid);
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005574
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005575exit:
Serhiy Storchakaef347532018-05-01 16:45:04 +03005576 if (file_actionsp) {
5577 (void)posix_spawn_file_actions_destroy(file_actionsp);
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005578 }
Pablo Galindo254a4662018-09-07 16:44:24 +01005579 if (attrp) {
5580 (void)posix_spawnattr_destroy(attrp);
5581 }
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005582 if (envlist) {
5583 free_string_array(envlist, envc);
5584 }
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005585 if (argvlist) {
5586 free_string_array(argvlist, argc);
5587 }
Pablo Galindocb970732018-06-19 09:19:50 +01005588 Py_XDECREF(temp_buffer);
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005589 return result;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005590}
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005591
5592
5593/*[clinic input]
5594
5595os.posix_spawn
5596 path: path_t
5597 Path of executable file.
5598 argv: object
5599 Tuple or list of strings.
5600 env: object
5601 Dictionary of strings mapping to strings.
5602 /
5603 *
5604 file_actions: object(c_default='NULL') = ()
5605 A sequence of file action tuples.
5606 setpgroup: object = NULL
5607 The pgroup to use with the POSIX_SPAWN_SETPGROUP flag.
5608 resetids: bool(accept={int}) = False
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005609 If the value is `true` the POSIX_SPAWN_RESETIDS will be activated.
5610 setsid: bool(accept={int}) = False
5611 If the value is `true` the POSIX_SPAWN_SETSID or POSIX_SPAWN_SETSID_NP will be activated.
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005612 setsigmask: object(c_default='NULL') = ()
5613 The sigmask to use with the POSIX_SPAWN_SETSIGMASK flag.
5614 setsigdef: object(c_default='NULL') = ()
5615 The sigmask to use with the POSIX_SPAWN_SETSIGDEF flag.
5616 scheduler: object = NULL
5617 A tuple with the scheduler policy (optional) and parameters.
5618
5619Execute the program specified by path in a new process.
5620[clinic start generated code]*/
5621
5622static PyObject *
5623os_posix_spawn_impl(PyObject *module, path_t *path, PyObject *argv,
5624 PyObject *env, PyObject *file_actions,
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005625 PyObject *setpgroup, int resetids, int setsid,
5626 PyObject *setsigmask, PyObject *setsigdef,
5627 PyObject *scheduler)
5628/*[clinic end generated code: output=14a1098c566bc675 input=8c6305619a00ad04]*/
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005629{
5630 return py_posix_spawn(0, module, path, argv, env, file_actions,
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005631 setpgroup, resetids, setsid, setsigmask, setsigdef,
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005632 scheduler);
5633}
5634 #endif /* HAVE_POSIX_SPAWN */
5635
5636
5637
5638#ifdef HAVE_POSIX_SPAWNP
5639/*[clinic input]
5640
5641os.posix_spawnp
5642 path: path_t
5643 Path of executable file.
5644 argv: object
5645 Tuple or list of strings.
5646 env: object
5647 Dictionary of strings mapping to strings.
5648 /
5649 *
5650 file_actions: object(c_default='NULL') = ()
5651 A sequence of file action tuples.
5652 setpgroup: object = NULL
5653 The pgroup to use with the POSIX_SPAWN_SETPGROUP flag.
5654 resetids: bool(accept={int}) = False
5655 If the value is `True` the POSIX_SPAWN_RESETIDS will be activated.
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005656 setsid: bool(accept={int}) = False
5657 If the value is `True` the POSIX_SPAWN_SETSID or POSIX_SPAWN_SETSID_NP will be activated.
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005658 setsigmask: object(c_default='NULL') = ()
5659 The sigmask to use with the POSIX_SPAWN_SETSIGMASK flag.
5660 setsigdef: object(c_default='NULL') = ()
5661 The sigmask to use with the POSIX_SPAWN_SETSIGDEF flag.
5662 scheduler: object = NULL
5663 A tuple with the scheduler policy (optional) and parameters.
5664
5665Execute the program specified by path in a new process.
5666[clinic start generated code]*/
5667
5668static PyObject *
5669os_posix_spawnp_impl(PyObject *module, path_t *path, PyObject *argv,
5670 PyObject *env, PyObject *file_actions,
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005671 PyObject *setpgroup, int resetids, int setsid,
5672 PyObject *setsigmask, PyObject *setsigdef,
5673 PyObject *scheduler)
5674/*[clinic end generated code: output=7b9aaefe3031238d input=c1911043a22028da]*/
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005675{
5676 return py_posix_spawn(1, module, path, argv, env, file_actions,
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005677 setpgroup, resetids, setsid, setsigmask, setsigdef,
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005678 scheduler);
5679}
5680#endif /* HAVE_POSIX_SPAWNP */
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005681
pxinwrf2d7ac72019-05-21 18:46:37 +08005682#ifdef HAVE_RTPSPAWN
5683static intptr_t
5684_rtp_spawn(int mode, const char *rtpFileName, const char *argv[],
5685 const char *envp[])
5686{
5687 RTP_ID rtpid;
5688 int status;
5689 pid_t res;
5690 int async_err = 0;
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00005691
pxinwrf2d7ac72019-05-21 18:46:37 +08005692 /* Set priority=100 and uStackSize=16 MiB (0x1000000) for new processes.
5693 uStackSize=0 cannot be used, the default stack size is too small for
5694 Python. */
5695 if (envp) {
5696 rtpid = rtpSpawn(rtpFileName, argv, envp,
5697 100, 0x1000000, 0, VX_FP_TASK);
5698 }
5699 else {
5700 rtpid = rtpSpawn(rtpFileName, argv, (const char **)environ,
5701 100, 0x1000000, 0, VX_FP_TASK);
5702 }
5703 if ((rtpid != RTP_ID_ERROR) && (mode == _P_WAIT)) {
5704 do {
5705 res = waitpid((pid_t)rtpid, &status, 0);
5706 } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
5707
5708 if (res < 0)
5709 return RTP_ID_ERROR;
5710 return ((intptr_t)status);
5711 }
5712 return ((intptr_t)rtpid);
5713}
5714#endif
5715
5716#if defined(HAVE_SPAWNV) || defined(HAVE_WSPAWNV) || defined(HAVE_RTPSPAWN)
Larry Hastings2f936352014-08-05 14:04:04 +10005717/*[clinic input]
5718os.spawnv
5719
5720 mode: int
5721 Mode of process creation.
Steve Dowercc16be82016-09-08 10:35:16 -07005722 path: path_t
Larry Hastings2f936352014-08-05 14:04:04 +10005723 Path of executable file.
5724 argv: object
5725 Tuple or list of strings.
5726 /
5727
5728Execute the program specified by path in a new process.
5729[clinic start generated code]*/
5730
Larry Hastings2f936352014-08-05 14:04:04 +10005731static PyObject *
Steve Dowercc16be82016-09-08 10:35:16 -07005732os_spawnv_impl(PyObject *module, int mode, path_t *path, PyObject *argv)
5733/*[clinic end generated code: output=71cd037a9d96b816 input=43224242303291be]*/
Larry Hastings2f936352014-08-05 14:04:04 +10005734{
Steve Dowercc16be82016-09-08 10:35:16 -07005735 EXECV_CHAR **argvlist;
Larry Hastings2f936352014-08-05 14:04:04 +10005736 int i;
Victor Stinner8c62be82010-05-06 00:08:46 +00005737 Py_ssize_t argc;
Benjamin Petersonca470632016-09-06 13:47:26 -07005738 intptr_t spawnval;
Victor Stinner8c62be82010-05-06 00:08:46 +00005739 PyObject *(*getitem)(PyObject *, Py_ssize_t);
Guido van Rossuma1065681999-01-25 23:20:23 +00005740
Victor Stinner8c62be82010-05-06 00:08:46 +00005741 /* spawnv has three arguments: (mode, path, argv), where
5742 argv is a list or tuple of strings. */
Guido van Rossuma1065681999-01-25 23:20:23 +00005743
Victor Stinner8c62be82010-05-06 00:08:46 +00005744 if (PyList_Check(argv)) {
5745 argc = PyList_Size(argv);
5746 getitem = PyList_GetItem;
5747 }
5748 else if (PyTuple_Check(argv)) {
5749 argc = PyTuple_Size(argv);
5750 getitem = PyTuple_GetItem;
5751 }
5752 else {
5753 PyErr_SetString(PyExc_TypeError,
5754 "spawnv() arg 2 must be a tuple or list");
Victor Stinner8c62be82010-05-06 00:08:46 +00005755 return NULL;
5756 }
Steve Dower859fd7b2016-11-19 18:53:19 -08005757 if (argc == 0) {
5758 PyErr_SetString(PyExc_ValueError,
5759 "spawnv() arg 2 cannot be empty");
5760 return NULL;
5761 }
Guido van Rossuma1065681999-01-25 23:20:23 +00005762
Steve Dowercc16be82016-09-08 10:35:16 -07005763 argvlist = PyMem_NEW(EXECV_CHAR *, argc+1);
Victor Stinner8c62be82010-05-06 00:08:46 +00005764 if (argvlist == NULL) {
Victor Stinner8c62be82010-05-06 00:08:46 +00005765 return PyErr_NoMemory();
5766 }
5767 for (i = 0; i < argc; i++) {
5768 if (!fsconvert_strdup((*getitem)(argv, i),
5769 &argvlist[i])) {
5770 free_string_array(argvlist, i);
5771 PyErr_SetString(
5772 PyExc_TypeError,
5773 "spawnv() arg 2 must contain only strings");
Victor Stinner8c62be82010-05-06 00:08:46 +00005774 return NULL;
5775 }
Steve Dower93ff8722016-11-19 19:03:54 -08005776 if (i == 0 && !argvlist[0][0]) {
Victor Stinner8acb4cf2017-06-15 15:30:40 +02005777 free_string_array(argvlist, i + 1);
Steve Dower93ff8722016-11-19 19:03:54 -08005778 PyErr_SetString(
5779 PyExc_ValueError,
5780 "spawnv() arg 2 first element cannot be empty");
5781 return NULL;
5782 }
Victor Stinner8c62be82010-05-06 00:08:46 +00005783 }
5784 argvlist[argc] = NULL;
Guido van Rossuma1065681999-01-25 23:20:23 +00005785
pxinwrf2d7ac72019-05-21 18:46:37 +08005786#if !defined(HAVE_RTPSPAWN)
Victor Stinner8c62be82010-05-06 00:08:46 +00005787 if (mode == _OLD_P_OVERLAY)
5788 mode = _P_OVERLAY;
pxinwrf2d7ac72019-05-21 18:46:37 +08005789#endif
Tim Peters5aa91602002-01-30 05:46:57 +00005790
Victor Stinner8c62be82010-05-06 00:08:46 +00005791 Py_BEGIN_ALLOW_THREADS
Steve Dower654a7bd2016-09-11 20:19:32 -07005792 _Py_BEGIN_SUPPRESS_IPH
Steve Dowercc16be82016-09-08 10:35:16 -07005793#ifdef HAVE_WSPAWNV
5794 spawnval = _wspawnv(mode, path->wide, argvlist);
pxinwrf2d7ac72019-05-21 18:46:37 +08005795#elif defined(HAVE_RTPSPAWN)
5796 spawnval = _rtp_spawn(mode, path->narrow, (const char **)argvlist, NULL);
Steve Dowercc16be82016-09-08 10:35:16 -07005797#else
5798 spawnval = _spawnv(mode, path->narrow, argvlist);
5799#endif
Steve Dower654a7bd2016-09-11 20:19:32 -07005800 _Py_END_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00005801 Py_END_ALLOW_THREADS
Tim Peters5aa91602002-01-30 05:46:57 +00005802
Victor Stinner8c62be82010-05-06 00:08:46 +00005803 free_string_array(argvlist, argc);
Guido van Rossuma1065681999-01-25 23:20:23 +00005804
Victor Stinner8c62be82010-05-06 00:08:46 +00005805 if (spawnval == -1)
5806 return posix_error();
5807 else
Richard Oudkerkac0ad882013-06-05 23:29:30 +01005808 return Py_BuildValue(_Py_PARSE_INTPTR, spawnval);
Guido van Rossuma1065681999-01-25 23:20:23 +00005809}
5810
Larry Hastings2f936352014-08-05 14:04:04 +10005811/*[clinic input]
5812os.spawnve
5813
5814 mode: int
5815 Mode of process creation.
Steve Dowercc16be82016-09-08 10:35:16 -07005816 path: path_t
Larry Hastings2f936352014-08-05 14:04:04 +10005817 Path of executable file.
5818 argv: object
5819 Tuple or list of strings.
5820 env: object
5821 Dictionary of strings mapping to strings.
5822 /
5823
5824Execute the program specified by path in a new process.
5825[clinic start generated code]*/
5826
Larry Hastings2f936352014-08-05 14:04:04 +10005827static PyObject *
Steve Dowercc16be82016-09-08 10:35:16 -07005828os_spawnve_impl(PyObject *module, int mode, path_t *path, PyObject *argv,
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005829 PyObject *env)
Steve Dowercc16be82016-09-08 10:35:16 -07005830/*[clinic end generated code: output=30fe85be56fe37ad input=3e40803ee7c4c586]*/
Larry Hastings2f936352014-08-05 14:04:04 +10005831{
Steve Dowercc16be82016-09-08 10:35:16 -07005832 EXECV_CHAR **argvlist;
5833 EXECV_CHAR **envlist;
Victor Stinner8c62be82010-05-06 00:08:46 +00005834 PyObject *res = NULL;
Antoine Pitrou22e41552010-08-15 18:07:50 +00005835 Py_ssize_t argc, i, envc;
Benjamin Petersonca470632016-09-06 13:47:26 -07005836 intptr_t spawnval;
Victor Stinner8c62be82010-05-06 00:08:46 +00005837 PyObject *(*getitem)(PyObject *, Py_ssize_t);
Victor Stinnerc8d6ab22017-06-23 15:04:46 +02005838 Py_ssize_t lastarg = 0;
Guido van Rossuma1065681999-01-25 23:20:23 +00005839
Victor Stinner8c62be82010-05-06 00:08:46 +00005840 /* spawnve has four arguments: (mode, path, argv, env), where
5841 argv is a list or tuple of strings and env is a dictionary
5842 like posix.environ. */
Guido van Rossuma1065681999-01-25 23:20:23 +00005843
Victor Stinner8c62be82010-05-06 00:08:46 +00005844 if (PyList_Check(argv)) {
5845 argc = PyList_Size(argv);
5846 getitem = PyList_GetItem;
5847 }
5848 else if (PyTuple_Check(argv)) {
5849 argc = PyTuple_Size(argv);
5850 getitem = PyTuple_GetItem;
5851 }
5852 else {
5853 PyErr_SetString(PyExc_TypeError,
5854 "spawnve() arg 2 must be a tuple or list");
5855 goto fail_0;
5856 }
Steve Dower859fd7b2016-11-19 18:53:19 -08005857 if (argc == 0) {
5858 PyErr_SetString(PyExc_ValueError,
5859 "spawnve() arg 2 cannot be empty");
5860 goto fail_0;
5861 }
Victor Stinner8c62be82010-05-06 00:08:46 +00005862 if (!PyMapping_Check(env)) {
5863 PyErr_SetString(PyExc_TypeError,
5864 "spawnve() arg 3 must be a mapping object");
5865 goto fail_0;
5866 }
Guido van Rossuma1065681999-01-25 23:20:23 +00005867
Steve Dowercc16be82016-09-08 10:35:16 -07005868 argvlist = PyMem_NEW(EXECV_CHAR *, argc+1);
Victor Stinner8c62be82010-05-06 00:08:46 +00005869 if (argvlist == NULL) {
5870 PyErr_NoMemory();
5871 goto fail_0;
5872 }
5873 for (i = 0; i < argc; i++) {
5874 if (!fsconvert_strdup((*getitem)(argv, i),
5875 &argvlist[i]))
5876 {
5877 lastarg = i;
5878 goto fail_1;
5879 }
Steve Dowerbce26262016-11-19 19:17:26 -08005880 if (i == 0 && !argvlist[0][0]) {
Victor Stinnerc8d6ab22017-06-23 15:04:46 +02005881 lastarg = i + 1;
Steve Dowerbce26262016-11-19 19:17:26 -08005882 PyErr_SetString(
5883 PyExc_ValueError,
5884 "spawnv() arg 2 first element cannot be empty");
5885 goto fail_1;
5886 }
Victor Stinner8c62be82010-05-06 00:08:46 +00005887 }
5888 lastarg = argc;
5889 argvlist[argc] = NULL;
Guido van Rossuma1065681999-01-25 23:20:23 +00005890
Victor Stinner8c62be82010-05-06 00:08:46 +00005891 envlist = parse_envlist(env, &envc);
5892 if (envlist == NULL)
5893 goto fail_1;
Guido van Rossuma1065681999-01-25 23:20:23 +00005894
pxinwrf2d7ac72019-05-21 18:46:37 +08005895#if !defined(HAVE_RTPSPAWN)
Victor Stinner8c62be82010-05-06 00:08:46 +00005896 if (mode == _OLD_P_OVERLAY)
5897 mode = _P_OVERLAY;
pxinwrf2d7ac72019-05-21 18:46:37 +08005898#endif
Tim Peters25059d32001-12-07 20:35:43 +00005899
Victor Stinner8c62be82010-05-06 00:08:46 +00005900 Py_BEGIN_ALLOW_THREADS
Steve Dower654a7bd2016-09-11 20:19:32 -07005901 _Py_BEGIN_SUPPRESS_IPH
Steve Dowercc16be82016-09-08 10:35:16 -07005902#ifdef HAVE_WSPAWNV
5903 spawnval = _wspawnve(mode, path->wide, argvlist, envlist);
pxinwrf2d7ac72019-05-21 18:46:37 +08005904#elif defined(HAVE_RTPSPAWN)
5905 spawnval = _rtp_spawn(mode, path->narrow, (const char **)argvlist,
5906 (const char **)envlist);
Steve Dowercc16be82016-09-08 10:35:16 -07005907#else
5908 spawnval = _spawnve(mode, path->narrow, argvlist, envlist);
5909#endif
Steve Dower654a7bd2016-09-11 20:19:32 -07005910 _Py_END_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00005911 Py_END_ALLOW_THREADS
Tim Peters25059d32001-12-07 20:35:43 +00005912
Victor Stinner8c62be82010-05-06 00:08:46 +00005913 if (spawnval == -1)
5914 (void) posix_error();
5915 else
Richard Oudkerkac0ad882013-06-05 23:29:30 +01005916 res = Py_BuildValue(_Py_PARSE_INTPTR, spawnval);
Guido van Rossuma1065681999-01-25 23:20:23 +00005917
Victor Stinner8c62be82010-05-06 00:08:46 +00005918 while (--envc >= 0)
5919 PyMem_DEL(envlist[envc]);
5920 PyMem_DEL(envlist);
Guido van Rossum0847c5c2002-12-13 18:36:22 +00005921 fail_1:
Victor Stinnerc8d6ab22017-06-23 15:04:46 +02005922 free_string_array(argvlist, lastarg);
Martin v. Löwis114619e2002-10-07 06:44:21 +00005923 fail_0:
Victor Stinner8c62be82010-05-06 00:08:46 +00005924 return res;
Guido van Rossuma1065681999-01-25 23:20:23 +00005925}
Andrew MacIntyre69e18c92004-04-04 07:11:43 +00005926
Guido van Rossuma1065681999-01-25 23:20:23 +00005927#endif /* HAVE_SPAWNV */
5928
5929
Antoine Pitrou346cbd32017-05-27 17:50:54 +02005930#ifdef HAVE_FORK
Gregory P. Smith163468a2017-05-29 10:03:41 -07005931
5932/* Helper function to validate arguments.
5933 Returns 0 on success. non-zero on failure with a TypeError raised.
5934 If obj is non-NULL it must be callable. */
5935static int
5936check_null_or_callable(PyObject *obj, const char* obj_name)
5937{
5938 if (obj && !PyCallable_Check(obj)) {
5939 PyErr_Format(PyExc_TypeError, "'%s' must be callable, not %s",
5940 obj_name, Py_TYPE(obj)->tp_name);
5941 return -1;
5942 }
5943 return 0;
5944}
5945
Antoine Pitrou346cbd32017-05-27 17:50:54 +02005946/*[clinic input]
5947os.register_at_fork
5948
Gregory P. Smith163468a2017-05-29 10:03:41 -07005949 *
5950 before: object=NULL
5951 A callable to be called in the parent before the fork() syscall.
5952 after_in_child: object=NULL
5953 A callable to be called in the child after fork().
5954 after_in_parent: object=NULL
5955 A callable to be called in the parent after fork().
Antoine Pitrou346cbd32017-05-27 17:50:54 +02005956
Gregory P. Smith163468a2017-05-29 10:03:41 -07005957Register callables to be called when forking a new process.
Antoine Pitrou346cbd32017-05-27 17:50:54 +02005958
Gregory P. Smith163468a2017-05-29 10:03:41 -07005959'before' callbacks are called in reverse order.
5960'after_in_child' and 'after_in_parent' callbacks are called in order.
Antoine Pitrou346cbd32017-05-27 17:50:54 +02005961
5962[clinic start generated code]*/
5963
5964static PyObject *
Gregory P. Smith163468a2017-05-29 10:03:41 -07005965os_register_at_fork_impl(PyObject *module, PyObject *before,
5966 PyObject *after_in_child, PyObject *after_in_parent)
5967/*[clinic end generated code: output=5398ac75e8e97625 input=cd1187aa85d2312e]*/
Antoine Pitrou346cbd32017-05-27 17:50:54 +02005968{
5969 PyInterpreterState *interp;
Antoine Pitrou346cbd32017-05-27 17:50:54 +02005970
Gregory P. Smith163468a2017-05-29 10:03:41 -07005971 if (!before && !after_in_child && !after_in_parent) {
5972 PyErr_SetString(PyExc_TypeError, "At least one argument is required.");
5973 return NULL;
5974 }
5975 if (check_null_or_callable(before, "before") ||
5976 check_null_or_callable(after_in_child, "after_in_child") ||
5977 check_null_or_callable(after_in_parent, "after_in_parent")) {
Antoine Pitrou346cbd32017-05-27 17:50:54 +02005978 return NULL;
5979 }
Victor Stinnercaba55b2018-08-03 15:33:52 +02005980 interp = _PyInterpreterState_Get();
Antoine Pitrou346cbd32017-05-27 17:50:54 +02005981
Gregory P. Smith163468a2017-05-29 10:03:41 -07005982 if (register_at_forker(&interp->before_forkers, before)) {
Antoine Pitrou346cbd32017-05-27 17:50:54 +02005983 return NULL;
5984 }
Gregory P. Smith163468a2017-05-29 10:03:41 -07005985 if (register_at_forker(&interp->after_forkers_child, after_in_child)) {
Antoine Pitrou346cbd32017-05-27 17:50:54 +02005986 return NULL;
Gregory P. Smith163468a2017-05-29 10:03:41 -07005987 }
5988 if (register_at_forker(&interp->after_forkers_parent, after_in_parent)) {
5989 return NULL;
5990 }
5991 Py_RETURN_NONE;
Antoine Pitrou346cbd32017-05-27 17:50:54 +02005992}
5993#endif /* HAVE_FORK */
5994
5995
Guido van Rossum2242f2f2001-04-11 20:58:20 +00005996#ifdef HAVE_FORK1
Larry Hastings2f936352014-08-05 14:04:04 +10005997/*[clinic input]
5998os.fork1
5999
6000Fork a child process with a single multiplexed (i.e., not bound) thread.
6001
6002Return 0 to child process and PID of child to parent process.
6003[clinic start generated code]*/
6004
Larry Hastings2f936352014-08-05 14:04:04 +10006005static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006006os_fork1_impl(PyObject *module)
6007/*[clinic end generated code: output=0de8e67ce2a310bc input=12db02167893926e]*/
Guido van Rossum2242f2f2001-04-11 20:58:20 +00006008{
Victor Stinner8c62be82010-05-06 00:08:46 +00006009 pid_t pid;
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006010
Eric Snow59032962018-09-14 14:17:20 -07006011 if (_PyInterpreterState_Get() != PyInterpreterState_Main()) {
6012 PyErr_SetString(PyExc_RuntimeError, "fork not supported for subinterpreters");
6013 return NULL;
6014 }
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006015 PyOS_BeforeFork();
Victor Stinner8c62be82010-05-06 00:08:46 +00006016 pid = fork1();
6017 if (pid == 0) {
6018 /* child: this clobbers and resets the import lock. */
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006019 PyOS_AfterFork_Child();
Victor Stinner8c62be82010-05-06 00:08:46 +00006020 } else {
6021 /* parent: release the import lock. */
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006022 PyOS_AfterFork_Parent();
Victor Stinner8c62be82010-05-06 00:08:46 +00006023 }
6024 if (pid == -1)
6025 return posix_error();
Victor Stinner8c62be82010-05-06 00:08:46 +00006026 return PyLong_FromPid(pid);
Guido van Rossum2242f2f2001-04-11 20:58:20 +00006027}
Larry Hastings2f936352014-08-05 14:04:04 +10006028#endif /* HAVE_FORK1 */
Guido van Rossum2242f2f2001-04-11 20:58:20 +00006029
6030
Guido van Rossumad0ee831995-03-01 10:34:45 +00006031#ifdef HAVE_FORK
Larry Hastings2f936352014-08-05 14:04:04 +10006032/*[clinic input]
6033os.fork
6034
6035Fork a child process.
6036
6037Return 0 to child process and PID of child to parent process.
6038[clinic start generated code]*/
6039
Larry Hastings2f936352014-08-05 14:04:04 +10006040static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006041os_fork_impl(PyObject *module)
6042/*[clinic end generated code: output=3626c81f98985d49 input=13c956413110eeaa]*/
Guido van Rossum85e3b011991-06-03 12:42:10 +00006043{
Victor Stinner8c62be82010-05-06 00:08:46 +00006044 pid_t pid;
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006045
Eric Snow59032962018-09-14 14:17:20 -07006046 if (_PyInterpreterState_Get() != PyInterpreterState_Main()) {
6047 PyErr_SetString(PyExc_RuntimeError, "fork not supported for subinterpreters");
6048 return NULL;
6049 }
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006050 PyOS_BeforeFork();
Victor Stinner8c62be82010-05-06 00:08:46 +00006051 pid = fork();
6052 if (pid == 0) {
6053 /* child: this clobbers and resets the import lock. */
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006054 PyOS_AfterFork_Child();
Victor Stinner8c62be82010-05-06 00:08:46 +00006055 } else {
6056 /* parent: release the import lock. */
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006057 PyOS_AfterFork_Parent();
Victor Stinner8c62be82010-05-06 00:08:46 +00006058 }
6059 if (pid == -1)
6060 return posix_error();
Victor Stinner8c62be82010-05-06 00:08:46 +00006061 return PyLong_FromPid(pid);
Guido van Rossum85e3b011991-06-03 12:42:10 +00006062}
Larry Hastings2f936352014-08-05 14:04:04 +10006063#endif /* HAVE_FORK */
6064
Guido van Rossum85e3b011991-06-03 12:42:10 +00006065
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006066#ifdef HAVE_SCHED_H
Charles-François Nataliea0d5fc2011-09-06 19:03:35 +02006067#ifdef HAVE_SCHED_GET_PRIORITY_MAX
Larry Hastings2f936352014-08-05 14:04:04 +10006068/*[clinic input]
6069os.sched_get_priority_max
Charles-François Nataliea0d5fc2011-09-06 19:03:35 +02006070
Larry Hastings2f936352014-08-05 14:04:04 +10006071 policy: int
6072
6073Get the maximum scheduling priority for policy.
6074[clinic start generated code]*/
6075
Larry Hastings2f936352014-08-05 14:04:04 +10006076static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006077os_sched_get_priority_max_impl(PyObject *module, int policy)
6078/*[clinic end generated code: output=9e465c6e43130521 input=2097b7998eca6874]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006079{
6080 int max;
6081
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006082 max = sched_get_priority_max(policy);
6083 if (max < 0)
6084 return posix_error();
6085 return PyLong_FromLong(max);
6086}
6087
Larry Hastings2f936352014-08-05 14:04:04 +10006088
6089/*[clinic input]
6090os.sched_get_priority_min
6091
6092 policy: int
6093
6094Get the minimum scheduling priority for policy.
6095[clinic start generated code]*/
6096
Larry Hastings2f936352014-08-05 14:04:04 +10006097static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006098os_sched_get_priority_min_impl(PyObject *module, int policy)
6099/*[clinic end generated code: output=7595c1138cc47a6d input=21bc8fa0d70983bf]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006100{
6101 int min = sched_get_priority_min(policy);
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006102 if (min < 0)
6103 return posix_error();
6104 return PyLong_FromLong(min);
6105}
Charles-François Nataliea0d5fc2011-09-06 19:03:35 +02006106#endif /* HAVE_SCHED_GET_PRIORITY_MAX */
6107
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006108
Larry Hastings2f936352014-08-05 14:04:04 +10006109#ifdef HAVE_SCHED_SETSCHEDULER
6110/*[clinic input]
6111os.sched_getscheduler
6112 pid: pid_t
6113 /
6114
6115Get the scheduling policy for the process identifiedy by pid.
6116
6117Passing 0 for pid returns the scheduling policy for the calling process.
6118[clinic start generated code]*/
6119
Larry Hastings2f936352014-08-05 14:04:04 +10006120static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006121os_sched_getscheduler_impl(PyObject *module, pid_t pid)
6122/*[clinic end generated code: output=dce4c0bd3f1b34c8 input=5f14cfd1f189e1a0]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006123{
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006124 int policy;
6125
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006126 policy = sched_getscheduler(pid);
6127 if (policy < 0)
6128 return posix_error();
6129 return PyLong_FromLong(policy);
6130}
Larry Hastings2f936352014-08-05 14:04:04 +10006131#endif /* HAVE_SCHED_SETSCHEDULER */
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006132
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006133
William Orr81574b82018-10-01 22:19:56 -07006134#if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
Larry Hastings2f936352014-08-05 14:04:04 +10006135/*[clinic input]
Eddie Elizondo474eedf2018-11-13 04:09:31 -08006136class os.sched_param "PyObject *" "SchedParamType"
Larry Hastings2f936352014-08-05 14:04:04 +10006137
6138@classmethod
6139os.sched_param.__new__
6140
6141 sched_priority: object
6142 A scheduling parameter.
6143
6144Current has only one field: sched_priority");
6145[clinic start generated code]*/
6146
Larry Hastings2f936352014-08-05 14:04:04 +10006147static PyObject *
6148os_sched_param_impl(PyTypeObject *type, PyObject *sched_priority)
Eddie Elizondo474eedf2018-11-13 04:09:31 -08006149/*[clinic end generated code: output=48f4067d60f48c13 input=ab4de35a9a7811f2]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006150{
6151 PyObject *res;
6152
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006153 res = PyStructSequence_New(type);
6154 if (!res)
6155 return NULL;
Larry Hastings2f936352014-08-05 14:04:04 +10006156 Py_INCREF(sched_priority);
6157 PyStructSequence_SET_ITEM(res, 0, sched_priority);
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006158 return res;
6159}
6160
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006161
Serhiy Storchaka1009bf12015-04-03 23:53:51 +03006162PyDoc_VAR(os_sched_param__doc__);
6163
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006164static PyStructSequence_Field sched_param_fields[] = {
6165 {"sched_priority", "the scheduling priority"},
6166 {0}
6167};
6168
6169static PyStructSequence_Desc sched_param_desc = {
6170 "sched_param", /* name */
Larry Hastings2f936352014-08-05 14:04:04 +10006171 os_sched_param__doc__, /* doc */
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006172 sched_param_fields,
6173 1
6174};
6175
6176static int
6177convert_sched_param(PyObject *param, struct sched_param *res)
6178{
6179 long priority;
6180
Eddie Elizondo474eedf2018-11-13 04:09:31 -08006181 if (Py_TYPE(param) != SchedParamType) {
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006182 PyErr_SetString(PyExc_TypeError, "must have a sched_param object");
6183 return 0;
6184 }
6185 priority = PyLong_AsLong(PyStructSequence_GET_ITEM(param, 0));
6186 if (priority == -1 && PyErr_Occurred())
6187 return 0;
6188 if (priority > INT_MAX || priority < INT_MIN) {
6189 PyErr_SetString(PyExc_OverflowError, "sched_priority out of range");
6190 return 0;
6191 }
6192 res->sched_priority = Py_SAFE_DOWNCAST(priority, long, int);
6193 return 1;
6194}
William Orr81574b82018-10-01 22:19:56 -07006195#endif /* defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM) */
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006196
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006197
6198#ifdef HAVE_SCHED_SETSCHEDULER
Larry Hastings2f936352014-08-05 14:04:04 +10006199/*[clinic input]
6200os.sched_setscheduler
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006201
Larry Hastings2f936352014-08-05 14:04:04 +10006202 pid: pid_t
6203 policy: int
6204 param: sched_param
6205 /
6206
6207Set the scheduling policy for the process identified by pid.
6208
6209If pid is 0, the calling process is changed.
6210param is an instance of sched_param.
6211[clinic start generated code]*/
6212
Larry Hastings2f936352014-08-05 14:04:04 +10006213static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006214os_sched_setscheduler_impl(PyObject *module, pid_t pid, int policy,
Larry Hastings89964c42015-04-14 18:07:59 -04006215 struct sched_param *param)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006216/*[clinic end generated code: output=b0ac0a70d3b1d705 input=c581f9469a5327dd]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006217{
Jesus Cea9c822272011-09-10 01:40:52 +02006218 /*
Jesus Cea54b01492011-09-10 01:53:19 +02006219 ** sched_setscheduler() returns 0 in Linux, but the previous
6220 ** scheduling policy under Solaris/Illumos, and others.
6221 ** On error, -1 is returned in all Operating Systems.
Jesus Cea9c822272011-09-10 01:40:52 +02006222 */
Larry Hastings2f936352014-08-05 14:04:04 +10006223 if (sched_setscheduler(pid, policy, param) == -1)
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006224 return posix_error();
6225 Py_RETURN_NONE;
6226}
Larry Hastings2f936352014-08-05 14:04:04 +10006227#endif /* HAVE_SCHED_SETSCHEDULER*/
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006228
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006229
6230#ifdef HAVE_SCHED_SETPARAM
Larry Hastings2f936352014-08-05 14:04:04 +10006231/*[clinic input]
6232os.sched_getparam
6233 pid: pid_t
6234 /
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006235
Larry Hastings2f936352014-08-05 14:04:04 +10006236Returns scheduling parameters for the process identified by pid.
6237
6238If pid is 0, returns parameters for the calling process.
6239Return value is an instance of sched_param.
6240[clinic start generated code]*/
6241
Larry Hastings2f936352014-08-05 14:04:04 +10006242static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006243os_sched_getparam_impl(PyObject *module, pid_t pid)
6244/*[clinic end generated code: output=b194e8708dcf2db8 input=18a1ef9c2efae296]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006245{
6246 struct sched_param param;
6247 PyObject *result;
6248 PyObject *priority;
6249
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006250 if (sched_getparam(pid, &param))
6251 return posix_error();
Eddie Elizondo474eedf2018-11-13 04:09:31 -08006252 result = PyStructSequence_New(SchedParamType);
Larry Hastings2f936352014-08-05 14:04:04 +10006253 if (!result)
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006254 return NULL;
6255 priority = PyLong_FromLong(param.sched_priority);
6256 if (!priority) {
Larry Hastings2f936352014-08-05 14:04:04 +10006257 Py_DECREF(result);
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006258 return NULL;
6259 }
Larry Hastings2f936352014-08-05 14:04:04 +10006260 PyStructSequence_SET_ITEM(result, 0, priority);
6261 return result;
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006262}
6263
Larry Hastings2f936352014-08-05 14:04:04 +10006264
6265/*[clinic input]
6266os.sched_setparam
6267 pid: pid_t
6268 param: sched_param
6269 /
6270
6271Set scheduling parameters for the process identified by pid.
6272
6273If pid is 0, sets parameters for the calling process.
6274param should be an instance of sched_param.
6275[clinic start generated code]*/
6276
Larry Hastings2f936352014-08-05 14:04:04 +10006277static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006278os_sched_setparam_impl(PyObject *module, pid_t pid,
Larry Hastings89964c42015-04-14 18:07:59 -04006279 struct sched_param *param)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006280/*[clinic end generated code: output=8af013f78a32b591 input=6b8d6dfcecdc21bd]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006281{
6282 if (sched_setparam(pid, param))
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006283 return posix_error();
6284 Py_RETURN_NONE;
6285}
Larry Hastings2f936352014-08-05 14:04:04 +10006286#endif /* HAVE_SCHED_SETPARAM */
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006287
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006288
6289#ifdef HAVE_SCHED_RR_GET_INTERVAL
Larry Hastings2f936352014-08-05 14:04:04 +10006290/*[clinic input]
6291os.sched_rr_get_interval -> double
6292 pid: pid_t
6293 /
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006294
Larry Hastings2f936352014-08-05 14:04:04 +10006295Return the round-robin quantum for the process identified by pid, in seconds.
6296
6297Value returned is a float.
6298[clinic start generated code]*/
6299
Larry Hastings2f936352014-08-05 14:04:04 +10006300static double
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006301os_sched_rr_get_interval_impl(PyObject *module, pid_t pid)
6302/*[clinic end generated code: output=7e2d935833ab47dc input=2a973da15cca6fae]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006303{
6304 struct timespec interval;
6305 if (sched_rr_get_interval(pid, &interval)) {
6306 posix_error();
6307 return -1.0;
6308 }
Gregory P. Smith1d300ce2018-12-30 21:13:02 -08006309#ifdef _Py_MEMORY_SANITIZER
6310 __msan_unpoison(&interval, sizeof(interval));
6311#endif
Larry Hastings2f936352014-08-05 14:04:04 +10006312 return (double)interval.tv_sec + 1e-9*interval.tv_nsec;
6313}
6314#endif /* HAVE_SCHED_RR_GET_INTERVAL */
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006315
Larry Hastings2f936352014-08-05 14:04:04 +10006316
6317/*[clinic input]
6318os.sched_yield
6319
6320Voluntarily relinquish the CPU.
6321[clinic start generated code]*/
6322
Larry Hastings2f936352014-08-05 14:04:04 +10006323static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006324os_sched_yield_impl(PyObject *module)
6325/*[clinic end generated code: output=902323500f222cac input=e54d6f98189391d4]*/
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006326{
6327 if (sched_yield())
6328 return posix_error();
6329 Py_RETURN_NONE;
6330}
6331
Benjamin Peterson2740af82011-08-02 17:41:34 -05006332#ifdef HAVE_SCHED_SETAFFINITY
Antoine Pitrou84869872012-08-04 16:16:35 +02006333/* The minimum number of CPUs allocated in a cpu_set_t */
6334static const int NCPUS_START = sizeof(unsigned long) * CHAR_BIT;
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006335
Larry Hastings2f936352014-08-05 14:04:04 +10006336/*[clinic input]
6337os.sched_setaffinity
6338 pid: pid_t
6339 mask : object
6340 /
6341
6342Set the CPU affinity of the process identified by pid to mask.
6343
6344mask should be an iterable of integers identifying CPUs.
6345[clinic start generated code]*/
6346
Larry Hastings2f936352014-08-05 14:04:04 +10006347static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006348os_sched_setaffinity_impl(PyObject *module, pid_t pid, PyObject *mask)
6349/*[clinic end generated code: output=882d7dd9a229335b input=a0791a597c7085ba]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006350{
Antoine Pitrou84869872012-08-04 16:16:35 +02006351 int ncpus;
6352 size_t setsize;
Larry Hastings2f936352014-08-05 14:04:04 +10006353 cpu_set_t *cpu_set = NULL;
6354 PyObject *iterator = NULL, *item;
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006355
Larry Hastings2f936352014-08-05 14:04:04 +10006356 iterator = PyObject_GetIter(mask);
Antoine Pitrou84869872012-08-04 16:16:35 +02006357 if (iterator == NULL)
6358 return NULL;
6359
6360 ncpus = NCPUS_START;
6361 setsize = CPU_ALLOC_SIZE(ncpus);
Larry Hastings2f936352014-08-05 14:04:04 +10006362 cpu_set = CPU_ALLOC(ncpus);
6363 if (cpu_set == NULL) {
Antoine Pitrou84869872012-08-04 16:16:35 +02006364 PyErr_NoMemory();
6365 goto error;
6366 }
Larry Hastings2f936352014-08-05 14:04:04 +10006367 CPU_ZERO_S(setsize, cpu_set);
Antoine Pitrou84869872012-08-04 16:16:35 +02006368
6369 while ((item = PyIter_Next(iterator))) {
6370 long cpu;
6371 if (!PyLong_Check(item)) {
6372 PyErr_Format(PyExc_TypeError,
6373 "expected an iterator of ints, "
6374 "but iterator yielded %R",
6375 Py_TYPE(item));
6376 Py_DECREF(item);
6377 goto error;
6378 }
6379 cpu = PyLong_AsLong(item);
6380 Py_DECREF(item);
6381 if (cpu < 0) {
6382 if (!PyErr_Occurred())
6383 PyErr_SetString(PyExc_ValueError, "negative CPU number");
6384 goto error;
6385 }
6386 if (cpu > INT_MAX - 1) {
6387 PyErr_SetString(PyExc_OverflowError, "CPU number too large");
6388 goto error;
6389 }
6390 if (cpu >= ncpus) {
6391 /* Grow CPU mask to fit the CPU number */
6392 int newncpus = ncpus;
6393 cpu_set_t *newmask;
6394 size_t newsetsize;
6395 while (newncpus <= cpu) {
6396 if (newncpus > INT_MAX / 2)
6397 newncpus = cpu + 1;
6398 else
6399 newncpus = newncpus * 2;
6400 }
6401 newmask = CPU_ALLOC(newncpus);
6402 if (newmask == NULL) {
6403 PyErr_NoMemory();
6404 goto error;
6405 }
6406 newsetsize = CPU_ALLOC_SIZE(newncpus);
6407 CPU_ZERO_S(newsetsize, newmask);
Larry Hastings2f936352014-08-05 14:04:04 +10006408 memcpy(newmask, cpu_set, setsize);
6409 CPU_FREE(cpu_set);
Antoine Pitrou84869872012-08-04 16:16:35 +02006410 setsize = newsetsize;
Larry Hastings2f936352014-08-05 14:04:04 +10006411 cpu_set = newmask;
Antoine Pitrou84869872012-08-04 16:16:35 +02006412 ncpus = newncpus;
6413 }
Larry Hastings2f936352014-08-05 14:04:04 +10006414 CPU_SET_S(cpu, setsize, cpu_set);
Antoine Pitrou84869872012-08-04 16:16:35 +02006415 }
6416 Py_CLEAR(iterator);
6417
Larry Hastings2f936352014-08-05 14:04:04 +10006418 if (sched_setaffinity(pid, setsize, cpu_set)) {
Antoine Pitrou84869872012-08-04 16:16:35 +02006419 posix_error();
6420 goto error;
6421 }
Larry Hastings2f936352014-08-05 14:04:04 +10006422 CPU_FREE(cpu_set);
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006423 Py_RETURN_NONE;
Antoine Pitrou84869872012-08-04 16:16:35 +02006424
6425error:
Larry Hastings2f936352014-08-05 14:04:04 +10006426 if (cpu_set)
6427 CPU_FREE(cpu_set);
Antoine Pitrou84869872012-08-04 16:16:35 +02006428 Py_XDECREF(iterator);
6429 return NULL;
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006430}
6431
Larry Hastings2f936352014-08-05 14:04:04 +10006432
6433/*[clinic input]
6434os.sched_getaffinity
6435 pid: pid_t
6436 /
6437
Charles-François Natalidc87e4b2015-07-13 21:01:39 +01006438Return the affinity of the process identified by pid (or the current process if zero).
Larry Hastings2f936352014-08-05 14:04:04 +10006439
6440The affinity is returned as a set of CPU identifiers.
6441[clinic start generated code]*/
6442
Larry Hastings2f936352014-08-05 14:04:04 +10006443static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006444os_sched_getaffinity_impl(PyObject *module, pid_t pid)
Serhiy Storchaka2954f832016-07-07 18:20:03 +03006445/*[clinic end generated code: output=f726f2c193c17a4f input=983ce7cb4a565980]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006446{
Antoine Pitrou84869872012-08-04 16:16:35 +02006447 int cpu, ncpus, count;
6448 size_t setsize;
6449 cpu_set_t *mask = NULL;
6450 PyObject *res = NULL;
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006451
Antoine Pitrou84869872012-08-04 16:16:35 +02006452 ncpus = NCPUS_START;
6453 while (1) {
6454 setsize = CPU_ALLOC_SIZE(ncpus);
6455 mask = CPU_ALLOC(ncpus);
6456 if (mask == NULL)
6457 return PyErr_NoMemory();
6458 if (sched_getaffinity(pid, setsize, mask) == 0)
6459 break;
6460 CPU_FREE(mask);
6461 if (errno != EINVAL)
6462 return posix_error();
6463 if (ncpus > INT_MAX / 2) {
6464 PyErr_SetString(PyExc_OverflowError, "could not allocate "
6465 "a large enough CPU set");
6466 return NULL;
6467 }
6468 ncpus = ncpus * 2;
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006469 }
Antoine Pitrou84869872012-08-04 16:16:35 +02006470
6471 res = PySet_New(NULL);
6472 if (res == NULL)
6473 goto error;
6474 for (cpu = 0, count = CPU_COUNT_S(setsize, mask); count; cpu++) {
6475 if (CPU_ISSET_S(cpu, setsize, mask)) {
6476 PyObject *cpu_num = PyLong_FromLong(cpu);
6477 --count;
6478 if (cpu_num == NULL)
6479 goto error;
6480 if (PySet_Add(res, cpu_num)) {
6481 Py_DECREF(cpu_num);
6482 goto error;
6483 }
6484 Py_DECREF(cpu_num);
6485 }
6486 }
6487 CPU_FREE(mask);
6488 return res;
6489
6490error:
6491 if (mask)
6492 CPU_FREE(mask);
6493 Py_XDECREF(res);
6494 return NULL;
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006495}
6496
Benjamin Peterson2740af82011-08-02 17:41:34 -05006497#endif /* HAVE_SCHED_SETAFFINITY */
6498
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006499#endif /* HAVE_SCHED_H */
6500
Larry Hastings2f936352014-08-05 14:04:04 +10006501
Neal Norwitzb59798b2003-03-21 01:43:31 +00006502/* AIX uses /dev/ptc but is otherwise the same as /dev/ptmx */
Neal Norwitz2deaddb2003-03-21 03:08:31 +00006503/* IRIX has both /dev/ptc and /dev/ptmx, use ptmx */
6504#if defined(HAVE_DEV_PTC) && !defined(HAVE_DEV_PTMX)
Neal Norwitzb59798b2003-03-21 01:43:31 +00006505#define DEV_PTY_FILE "/dev/ptc"
6506#define HAVE_DEV_PTMX
6507#else
6508#define DEV_PTY_FILE "/dev/ptmx"
6509#endif
6510
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006511#if defined(HAVE_OPENPTY) || defined(HAVE_FORKPTY) || defined(HAVE_DEV_PTMX)
Fred Drake8cef4cf2000-06-28 16:40:38 +00006512#ifdef HAVE_PTY_H
6513#include <pty.h>
6514#else
6515#ifdef HAVE_LIBUTIL_H
6516#include <libutil.h>
Ronald Oussoren755740f2010-02-07 19:56:39 +00006517#else
6518#ifdef HAVE_UTIL_H
6519#include <util.h>
6520#endif /* HAVE_UTIL_H */
Fred Drake8cef4cf2000-06-28 16:40:38 +00006521#endif /* HAVE_LIBUTIL_H */
6522#endif /* HAVE_PTY_H */
Martin v. Löwis14e73b12003-01-01 09:51:12 +00006523#ifdef HAVE_STROPTS_H
6524#include <stropts.h>
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006525#endif
ngie-eign7745ec42018-02-14 11:54:28 -08006526#endif /* defined(HAVE_OPENPTY) || defined(HAVE_FORKPTY) || defined(HAVE_DEV_PTMX) */
Fred Drake8cef4cf2000-06-28 16:40:38 +00006527
Larry Hastings2f936352014-08-05 14:04:04 +10006528
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006529#if defined(HAVE_OPENPTY) || defined(HAVE__GETPTY) || defined(HAVE_DEV_PTMX)
Larry Hastings2f936352014-08-05 14:04:04 +10006530/*[clinic input]
6531os.openpty
6532
6533Open a pseudo-terminal.
6534
6535Return a tuple of (master_fd, slave_fd) containing open file descriptors
6536for both the master and slave ends.
6537[clinic start generated code]*/
6538
Larry Hastings2f936352014-08-05 14:04:04 +10006539static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006540os_openpty_impl(PyObject *module)
6541/*[clinic end generated code: output=98841ce5ec9cef3c input=f3d99fd99e762907]*/
Fred Drake8cef4cf2000-06-28 16:40:38 +00006542{
Victor Stinnerdaf45552013-08-28 00:53:59 +02006543 int master_fd = -1, slave_fd = -1;
Thomas Wouters70c21a12000-07-14 14:28:33 +00006544#ifndef HAVE_OPENPTY
Victor Stinner8c62be82010-05-06 00:08:46 +00006545 char * slave_name;
Thomas Wouters70c21a12000-07-14 14:28:33 +00006546#endif
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006547#if defined(HAVE_DEV_PTMX) && !defined(HAVE_OPENPTY) && !defined(HAVE__GETPTY)
Victor Stinner8c62be82010-05-06 00:08:46 +00006548 PyOS_sighandler_t sig_saved;
Jakub Kulík6f9bc722018-12-31 03:16:40 +01006549#if defined(__sun) && defined(__SVR4)
Victor Stinner8c62be82010-05-06 00:08:46 +00006550 extern char *ptsname(int fildes);
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006551#endif
6552#endif
Thomas Wouters70c21a12000-07-14 14:28:33 +00006553
Thomas Wouters70c21a12000-07-14 14:28:33 +00006554#ifdef HAVE_OPENPTY
Victor Stinner8c62be82010-05-06 00:08:46 +00006555 if (openpty(&master_fd, &slave_fd, NULL, NULL, NULL) != 0)
Victor Stinnerdaf45552013-08-28 00:53:59 +02006556 goto posix_error;
6557
6558 if (_Py_set_inheritable(master_fd, 0, NULL) < 0)
6559 goto error;
6560 if (_Py_set_inheritable(slave_fd, 0, NULL) < 0)
6561 goto error;
6562
Neal Norwitzb59798b2003-03-21 01:43:31 +00006563#elif defined(HAVE__GETPTY)
Victor Stinner8c62be82010-05-06 00:08:46 +00006564 slave_name = _getpty(&master_fd, O_RDWR, 0666, 0);
6565 if (slave_name == NULL)
Victor Stinnerdaf45552013-08-28 00:53:59 +02006566 goto posix_error;
6567 if (_Py_set_inheritable(master_fd, 0, NULL) < 0)
6568 goto error;
Thomas Wouters70c21a12000-07-14 14:28:33 +00006569
Victor Stinnerdaf45552013-08-28 00:53:59 +02006570 slave_fd = _Py_open(slave_name, O_RDWR);
Victor Stinner8c62be82010-05-06 00:08:46 +00006571 if (slave_fd < 0)
Victor Stinnera555cfc2015-03-18 00:22:14 +01006572 goto error;
Victor Stinnerdaf45552013-08-28 00:53:59 +02006573
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006574#else
Victor Stinner000de532013-11-25 23:19:58 +01006575 master_fd = open(DEV_PTY_FILE, O_RDWR | O_NOCTTY); /* open master */
Victor Stinner8c62be82010-05-06 00:08:46 +00006576 if (master_fd < 0)
Victor Stinnerdaf45552013-08-28 00:53:59 +02006577 goto posix_error;
6578
Victor Stinner8c62be82010-05-06 00:08:46 +00006579 sig_saved = PyOS_setsig(SIGCHLD, SIG_DFL);
Victor Stinnerdaf45552013-08-28 00:53:59 +02006580
Victor Stinner8c62be82010-05-06 00:08:46 +00006581 /* change permission of slave */
6582 if (grantpt(master_fd) < 0) {
6583 PyOS_setsig(SIGCHLD, sig_saved);
Victor Stinnerdaf45552013-08-28 00:53:59 +02006584 goto posix_error;
Victor Stinner8c62be82010-05-06 00:08:46 +00006585 }
Victor Stinnerdaf45552013-08-28 00:53:59 +02006586
Victor Stinner8c62be82010-05-06 00:08:46 +00006587 /* unlock slave */
6588 if (unlockpt(master_fd) < 0) {
6589 PyOS_setsig(SIGCHLD, sig_saved);
Victor Stinnerdaf45552013-08-28 00:53:59 +02006590 goto posix_error;
Victor Stinner8c62be82010-05-06 00:08:46 +00006591 }
Victor Stinnerdaf45552013-08-28 00:53:59 +02006592
Victor Stinner8c62be82010-05-06 00:08:46 +00006593 PyOS_setsig(SIGCHLD, sig_saved);
Victor Stinnerdaf45552013-08-28 00:53:59 +02006594
Victor Stinner8c62be82010-05-06 00:08:46 +00006595 slave_name = ptsname(master_fd); /* get name of slave */
6596 if (slave_name == NULL)
Victor Stinnerdaf45552013-08-28 00:53:59 +02006597 goto posix_error;
6598
6599 slave_fd = _Py_open(slave_name, O_RDWR | O_NOCTTY); /* open slave */
Victor Stinnera555cfc2015-03-18 00:22:14 +01006600 if (slave_fd == -1)
6601 goto error;
Victor Stinner000de532013-11-25 23:19:58 +01006602
6603 if (_Py_set_inheritable(master_fd, 0, NULL) < 0)
6604 goto posix_error;
6605
Stefan Krahfb7c8ae2016-04-26 17:04:18 +02006606#if !defined(__CYGWIN__) && !defined(__ANDROID__) && !defined(HAVE_DEV_PTC)
Victor Stinner8c62be82010-05-06 00:08:46 +00006607 ioctl(slave_fd, I_PUSH, "ptem"); /* push ptem */
6608 ioctl(slave_fd, I_PUSH, "ldterm"); /* push ldterm */
Neal Norwitz6700e472002-12-31 16:16:07 +00006609#ifndef __hpux
Victor Stinner8c62be82010-05-06 00:08:46 +00006610 ioctl(slave_fd, I_PUSH, "ttcompat"); /* push ttcompat */
Neal Norwitz6700e472002-12-31 16:16:07 +00006611#endif /* __hpux */
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006612#endif /* HAVE_CYGWIN */
Thomas Wouters1e0c2f42000-07-24 16:06:23 +00006613#endif /* HAVE_OPENPTY */
Thomas Wouters70c21a12000-07-14 14:28:33 +00006614
Victor Stinner8c62be82010-05-06 00:08:46 +00006615 return Py_BuildValue("(ii)", master_fd, slave_fd);
Thomas Wouters70c21a12000-07-14 14:28:33 +00006616
Victor Stinnerdaf45552013-08-28 00:53:59 +02006617posix_error:
6618 posix_error();
6619error:
6620 if (master_fd != -1)
6621 close(master_fd);
6622 if (slave_fd != -1)
6623 close(slave_fd);
6624 return NULL;
Fred Drake8cef4cf2000-06-28 16:40:38 +00006625}
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006626#endif /* defined(HAVE_OPENPTY) || defined(HAVE__GETPTY) || defined(HAVE_DEV_PTMX) */
Fred Drake8cef4cf2000-06-28 16:40:38 +00006627
Larry Hastings2f936352014-08-05 14:04:04 +10006628
Fred Drake8cef4cf2000-06-28 16:40:38 +00006629#ifdef HAVE_FORKPTY
Larry Hastings2f936352014-08-05 14:04:04 +10006630/*[clinic input]
6631os.forkpty
6632
6633Fork a new process with a new pseudo-terminal as controlling tty.
6634
6635Returns a tuple of (pid, master_fd).
6636Like fork(), return pid of 0 to the child process,
6637and pid of child to the parent process.
6638To both, return fd of newly opened pseudo-terminal.
6639[clinic start generated code]*/
6640
Larry Hastings2f936352014-08-05 14:04:04 +10006641static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006642os_forkpty_impl(PyObject *module)
6643/*[clinic end generated code: output=60d0a5c7512e4087 input=f1f7f4bae3966010]*/
Fred Drake8cef4cf2000-06-28 16:40:38 +00006644{
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006645 int master_fd = -1;
Victor Stinner8c62be82010-05-06 00:08:46 +00006646 pid_t pid;
Tim Peters5aa91602002-01-30 05:46:57 +00006647
Eric Snow59032962018-09-14 14:17:20 -07006648 if (_PyInterpreterState_Get() != PyInterpreterState_Main()) {
6649 PyErr_SetString(PyExc_RuntimeError, "fork not supported for subinterpreters");
6650 return NULL;
6651 }
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006652 PyOS_BeforeFork();
Victor Stinner8c62be82010-05-06 00:08:46 +00006653 pid = forkpty(&master_fd, NULL, NULL, NULL);
6654 if (pid == 0) {
6655 /* child: this clobbers and resets the import lock. */
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006656 PyOS_AfterFork_Child();
Victor Stinner8c62be82010-05-06 00:08:46 +00006657 } else {
6658 /* parent: release the import lock. */
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006659 PyOS_AfterFork_Parent();
Victor Stinner8c62be82010-05-06 00:08:46 +00006660 }
6661 if (pid == -1)
6662 return posix_error();
Victor Stinner8c62be82010-05-06 00:08:46 +00006663 return Py_BuildValue("(Ni)", PyLong_FromPid(pid), master_fd);
Fred Drake8cef4cf2000-06-28 16:40:38 +00006664}
Larry Hastings2f936352014-08-05 14:04:04 +10006665#endif /* HAVE_FORKPTY */
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00006666
Ross Lagerwall7807c352011-03-17 20:20:30 +02006667
Guido van Rossumad0ee831995-03-01 10:34:45 +00006668#ifdef HAVE_GETEGID
Larry Hastings2f936352014-08-05 14:04:04 +10006669/*[clinic input]
6670os.getegid
6671
6672Return the current process's effective group id.
6673[clinic start generated code]*/
6674
Larry Hastings2f936352014-08-05 14:04:04 +10006675static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006676os_getegid_impl(PyObject *module)
6677/*[clinic end generated code: output=67d9be7ac68898a2 input=1596f79ad1107d5d]*/
Guido van Rossum46003ff1992-05-15 11:05:24 +00006678{
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02006679 return _PyLong_FromGid(getegid());
Guido van Rossum46003ff1992-05-15 11:05:24 +00006680}
Larry Hastings2f936352014-08-05 14:04:04 +10006681#endif /* HAVE_GETEGID */
Guido van Rossum46003ff1992-05-15 11:05:24 +00006682
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00006683
Guido van Rossumad0ee831995-03-01 10:34:45 +00006684#ifdef HAVE_GETEUID
Larry Hastings2f936352014-08-05 14:04:04 +10006685/*[clinic input]
6686os.geteuid
6687
6688Return the current process's effective user id.
6689[clinic start generated code]*/
6690
Larry Hastings2f936352014-08-05 14:04:04 +10006691static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006692os_geteuid_impl(PyObject *module)
6693/*[clinic end generated code: output=ea1b60f0d6abb66e input=4644c662d3bd9f19]*/
Guido van Rossum46003ff1992-05-15 11:05:24 +00006694{
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02006695 return _PyLong_FromUid(geteuid());
Guido van Rossum46003ff1992-05-15 11:05:24 +00006696}
Larry Hastings2f936352014-08-05 14:04:04 +10006697#endif /* HAVE_GETEUID */
Guido van Rossum46003ff1992-05-15 11:05:24 +00006698
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00006699
Guido van Rossumad0ee831995-03-01 10:34:45 +00006700#ifdef HAVE_GETGID
Larry Hastings2f936352014-08-05 14:04:04 +10006701/*[clinic input]
6702os.getgid
6703
6704Return the current process's group id.
6705[clinic start generated code]*/
6706
Larry Hastings2f936352014-08-05 14:04:04 +10006707static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006708os_getgid_impl(PyObject *module)
6709/*[clinic end generated code: output=4f28ebc9d3e5dfcf input=58796344cd87c0f6]*/
Guido van Rossum46003ff1992-05-15 11:05:24 +00006710{
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02006711 return _PyLong_FromGid(getgid());
Guido van Rossum46003ff1992-05-15 11:05:24 +00006712}
Larry Hastings2f936352014-08-05 14:04:04 +10006713#endif /* HAVE_GETGID */
Guido van Rossum46003ff1992-05-15 11:05:24 +00006714
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00006715
Berker Peksag39404992016-09-15 20:45:16 +03006716#ifdef HAVE_GETPID
Larry Hastings2f936352014-08-05 14:04:04 +10006717/*[clinic input]
6718os.getpid
6719
6720Return the current process id.
6721[clinic start generated code]*/
6722
Larry Hastings2f936352014-08-05 14:04:04 +10006723static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006724os_getpid_impl(PyObject *module)
6725/*[clinic end generated code: output=9ea6fdac01ed2b3c input=5a9a00f0ab68aa00]*/
Guido van Rossum85e3b011991-06-03 12:42:10 +00006726{
Victor Stinner8c62be82010-05-06 00:08:46 +00006727 return PyLong_FromPid(getpid());
Guido van Rossum85e3b011991-06-03 12:42:10 +00006728}
Berker Peksag39404992016-09-15 20:45:16 +03006729#endif /* HAVE_GETPID */
Guido van Rossum85e3b011991-06-03 12:42:10 +00006730
Jeffrey Kintscher8725c832019-06-13 00:01:29 -07006731#ifdef NGROUPS_MAX
6732#define MAX_GROUPS NGROUPS_MAX
6733#else
6734 /* defined to be 16 on Solaris7, so this should be a small number */
6735#define MAX_GROUPS 64
6736#endif
6737
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006738#ifdef HAVE_GETGROUPLIST
Larry Hastings2f936352014-08-05 14:04:04 +10006739
6740/* AC 3.5: funny apple logic below */
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006741PyDoc_STRVAR(posix_getgrouplist__doc__,
6742"getgrouplist(user, group) -> list of groups to which a user belongs\n\n\
6743Returns a list of groups to which a user belongs.\n\n\
6744 user: username to lookup\n\
6745 group: base group id of the user");
6746
6747static PyObject *
6748posix_getgrouplist(PyObject *self, PyObject *args)
6749{
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006750 const char *user;
6751 int i, ngroups;
6752 PyObject *list;
6753#ifdef __APPLE__
6754 int *groups, basegid;
6755#else
6756 gid_t *groups, basegid;
6757#endif
Jeffrey Kintscher8725c832019-06-13 00:01:29 -07006758
6759 /*
6760 * NGROUPS_MAX is defined by POSIX.1 as the maximum
6761 * number of supplimental groups a users can belong to.
6762 * We have to increment it by one because
6763 * getgrouplist() returns both the supplemental groups
6764 * and the primary group, i.e. all of the groups the
6765 * user belongs to.
6766 */
6767 ngroups = 1 + MAX_GROUPS;
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006768
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02006769#ifdef __APPLE__
6770 if (!PyArg_ParseTuple(args, "si:getgrouplist", &user, &basegid))
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006771 return NULL;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02006772#else
6773 if (!PyArg_ParseTuple(args, "sO&:getgrouplist", &user,
6774 _Py_Gid_Converter, &basegid))
6775 return NULL;
6776#endif
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006777
6778#ifdef __APPLE__
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02006779 groups = PyMem_New(int, ngroups);
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006780#else
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02006781 groups = PyMem_New(gid_t, ngroups);
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006782#endif
6783 if (groups == NULL)
6784 return PyErr_NoMemory();
6785
6786 if (getgrouplist(user, basegid, groups, &ngroups) == -1) {
6787 PyMem_Del(groups);
6788 return posix_error();
6789 }
6790
Gregory P. Smith1d300ce2018-12-30 21:13:02 -08006791#ifdef _Py_MEMORY_SANITIZER
6792 /* Clang memory sanitizer libc intercepts don't know getgrouplist. */
6793 __msan_unpoison(&ngroups, sizeof(ngroups));
6794 __msan_unpoison(groups, ngroups*sizeof(*groups));
6795#endif
6796
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006797 list = PyList_New(ngroups);
6798 if (list == NULL) {
6799 PyMem_Del(groups);
6800 return NULL;
6801 }
6802
6803 for (i = 0; i < ngroups; i++) {
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02006804#ifdef __APPLE__
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006805 PyObject *o = PyLong_FromUnsignedLong((unsigned long)groups[i]);
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02006806#else
6807 PyObject *o = _PyLong_FromGid(groups[i]);
6808#endif
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006809 if (o == NULL) {
6810 Py_DECREF(list);
6811 PyMem_Del(groups);
6812 return NULL;
6813 }
6814 PyList_SET_ITEM(list, i, o);
6815 }
6816
6817 PyMem_Del(groups);
6818
6819 return list;
6820}
Larry Hastings2f936352014-08-05 14:04:04 +10006821#endif /* HAVE_GETGROUPLIST */
6822
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00006823
Fred Drakec9680921999-12-13 16:37:25 +00006824#ifdef HAVE_GETGROUPS
Larry Hastings2f936352014-08-05 14:04:04 +10006825/*[clinic input]
6826os.getgroups
6827
6828Return list of supplemental group IDs for the process.
6829[clinic start generated code]*/
6830
Larry Hastings2f936352014-08-05 14:04:04 +10006831static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006832os_getgroups_impl(PyObject *module)
6833/*[clinic end generated code: output=42b0c17758561b56 input=d3f109412e6a155c]*/
Fred Drakec9680921999-12-13 16:37:25 +00006834{
6835 PyObject *result = NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00006836 gid_t grouplist[MAX_GROUPS];
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00006837
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00006838 /* On MacOSX getgroups(2) can return more than MAX_GROUPS results
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00006839 * This is a helper variable to store the intermediate result when
6840 * that happens.
6841 *
6842 * To keep the code readable the OSX behaviour is unconditional,
6843 * according to the POSIX spec this should be safe on all unix-y
6844 * systems.
6845 */
6846 gid_t* alt_grouplist = grouplist;
Victor Stinner8c62be82010-05-06 00:08:46 +00006847 int n;
Fred Drakec9680921999-12-13 16:37:25 +00006848
Ned Deilyb5dd6d22013-08-01 21:21:15 -07006849#ifdef __APPLE__
6850 /* Issue #17557: As of OS X 10.8, getgroups(2) no longer raises EINVAL if
6851 * there are more groups than can fit in grouplist. Therefore, on OS X
6852 * always first call getgroups with length 0 to get the actual number
6853 * of groups.
6854 */
6855 n = getgroups(0, NULL);
6856 if (n < 0) {
6857 return posix_error();
6858 } else if (n <= MAX_GROUPS) {
6859 /* groups will fit in existing array */
6860 alt_grouplist = grouplist;
6861 } else {
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02006862 alt_grouplist = PyMem_New(gid_t, n);
Ned Deilyb5dd6d22013-08-01 21:21:15 -07006863 if (alt_grouplist == NULL) {
Zackery Spytz4c49da02018-12-07 03:11:30 -07006864 return PyErr_NoMemory();
Ned Deilyb5dd6d22013-08-01 21:21:15 -07006865 }
6866 }
6867
6868 n = getgroups(n, alt_grouplist);
6869 if (n == -1) {
6870 if (alt_grouplist != grouplist) {
6871 PyMem_Free(alt_grouplist);
6872 }
6873 return posix_error();
6874 }
6875#else
Victor Stinner8c62be82010-05-06 00:08:46 +00006876 n = getgroups(MAX_GROUPS, grouplist);
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00006877 if (n < 0) {
6878 if (errno == EINVAL) {
6879 n = getgroups(0, NULL);
6880 if (n == -1) {
6881 return posix_error();
6882 }
6883 if (n == 0) {
6884 /* Avoid malloc(0) */
6885 alt_grouplist = grouplist;
6886 } else {
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02006887 alt_grouplist = PyMem_New(gid_t, n);
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00006888 if (alt_grouplist == NULL) {
Zackery Spytz4c49da02018-12-07 03:11:30 -07006889 return PyErr_NoMemory();
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00006890 }
6891 n = getgroups(n, alt_grouplist);
6892 if (n == -1) {
6893 PyMem_Free(alt_grouplist);
6894 return posix_error();
6895 }
6896 }
6897 } else {
6898 return posix_error();
6899 }
6900 }
Ned Deilyb5dd6d22013-08-01 21:21:15 -07006901#endif
6902
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00006903 result = PyList_New(n);
6904 if (result != NULL) {
Victor Stinner8c62be82010-05-06 00:08:46 +00006905 int i;
6906 for (i = 0; i < n; ++i) {
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02006907 PyObject *o = _PyLong_FromGid(alt_grouplist[i]);
Victor Stinner8c62be82010-05-06 00:08:46 +00006908 if (o == NULL) {
Stefan Krah0e803b32010-11-26 16:16:47 +00006909 Py_DECREF(result);
6910 result = NULL;
6911 break;
Fred Drakec9680921999-12-13 16:37:25 +00006912 }
Victor Stinner8c62be82010-05-06 00:08:46 +00006913 PyList_SET_ITEM(result, i, o);
Fred Drakec9680921999-12-13 16:37:25 +00006914 }
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00006915 }
6916
6917 if (alt_grouplist != grouplist) {
6918 PyMem_Free(alt_grouplist);
Victor Stinner8c62be82010-05-06 00:08:46 +00006919 }
Neal Norwitze241ce82003-02-17 18:17:05 +00006920
Fred Drakec9680921999-12-13 16:37:25 +00006921 return result;
6922}
Larry Hastings2f936352014-08-05 14:04:04 +10006923#endif /* HAVE_GETGROUPS */
Fred Drakec9680921999-12-13 16:37:25 +00006924
Antoine Pitroub7572f02009-12-02 20:46:48 +00006925#ifdef HAVE_INITGROUPS
6926PyDoc_STRVAR(posix_initgroups__doc__,
6927"initgroups(username, gid) -> None\n\n\
6928Call the system initgroups() to initialize the group access list with all of\n\
6929the groups of which the specified username is a member, plus the specified\n\
6930group id.");
6931
Larry Hastings2f936352014-08-05 14:04:04 +10006932/* AC 3.5: funny apple logic */
Antoine Pitroub7572f02009-12-02 20:46:48 +00006933static PyObject *
6934posix_initgroups(PyObject *self, PyObject *args)
6935{
Victor Stinner61ec5dc2010-08-15 09:22:44 +00006936 PyObject *oname;
Serhiy Storchakadeab18d2016-05-07 16:45:18 +03006937 const char *username;
Victor Stinner61ec5dc2010-08-15 09:22:44 +00006938 int res;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02006939#ifdef __APPLE__
6940 int gid;
6941#else
6942 gid_t gid;
6943#endif
Antoine Pitroub7572f02009-12-02 20:46:48 +00006944
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02006945#ifdef __APPLE__
6946 if (!PyArg_ParseTuple(args, "O&i:initgroups",
6947 PyUnicode_FSConverter, &oname,
6948 &gid))
6949#else
6950 if (!PyArg_ParseTuple(args, "O&O&:initgroups",
6951 PyUnicode_FSConverter, &oname,
6952 _Py_Gid_Converter, &gid))
6953#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00006954 return NULL;
Victor Stinner61ec5dc2010-08-15 09:22:44 +00006955 username = PyBytes_AS_STRING(oname);
Antoine Pitroub7572f02009-12-02 20:46:48 +00006956
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02006957 res = initgroups(username, gid);
Victor Stinner61ec5dc2010-08-15 09:22:44 +00006958 Py_DECREF(oname);
6959 if (res == -1)
Victor Stinner8c62be82010-05-06 00:08:46 +00006960 return PyErr_SetFromErrno(PyExc_OSError);
Antoine Pitroub7572f02009-12-02 20:46:48 +00006961
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02006962 Py_RETURN_NONE;
Antoine Pitroub7572f02009-12-02 20:46:48 +00006963}
Larry Hastings2f936352014-08-05 14:04:04 +10006964#endif /* HAVE_INITGROUPS */
6965
Antoine Pitroub7572f02009-12-02 20:46:48 +00006966
Martin v. Löwis606edc12002-06-13 21:09:11 +00006967#ifdef HAVE_GETPGID
Larry Hastings2f936352014-08-05 14:04:04 +10006968/*[clinic input]
6969os.getpgid
6970
6971 pid: pid_t
6972
6973Call the system call getpgid(), and return the result.
6974[clinic start generated code]*/
6975
Larry Hastings2f936352014-08-05 14:04:04 +10006976static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006977os_getpgid_impl(PyObject *module, pid_t pid)
6978/*[clinic end generated code: output=1db95a97be205d18 input=39d710ae3baaf1c7]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006979{
6980 pid_t pgid = getpgid(pid);
Victor Stinner8c62be82010-05-06 00:08:46 +00006981 if (pgid < 0)
6982 return posix_error();
6983 return PyLong_FromPid(pgid);
Martin v. Löwis606edc12002-06-13 21:09:11 +00006984}
6985#endif /* HAVE_GETPGID */
6986
6987
Guido van Rossumb6775db1994-08-01 11:34:53 +00006988#ifdef HAVE_GETPGRP
Larry Hastings2f936352014-08-05 14:04:04 +10006989/*[clinic input]
6990os.getpgrp
6991
6992Return the current process group id.
6993[clinic start generated code]*/
6994
Larry Hastings2f936352014-08-05 14:04:04 +10006995static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006996os_getpgrp_impl(PyObject *module)
6997/*[clinic end generated code: output=c4fc381e51103cf3 input=6846fb2bb9a3705e]*/
Guido van Rossum04814471991-06-04 20:23:49 +00006998{
Guido van Rossumb6775db1994-08-01 11:34:53 +00006999#ifdef GETPGRP_HAVE_ARG
Victor Stinner8c62be82010-05-06 00:08:46 +00007000 return PyLong_FromPid(getpgrp(0));
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +00007001#else /* GETPGRP_HAVE_ARG */
Victor Stinner8c62be82010-05-06 00:08:46 +00007002 return PyLong_FromPid(getpgrp());
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +00007003#endif /* GETPGRP_HAVE_ARG */
Guido van Rossum04814471991-06-04 20:23:49 +00007004}
Guido van Rossumb6775db1994-08-01 11:34:53 +00007005#endif /* HAVE_GETPGRP */
Guido van Rossum04814471991-06-04 20:23:49 +00007006
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007007
Guido van Rossumb6775db1994-08-01 11:34:53 +00007008#ifdef HAVE_SETPGRP
Larry Hastings2f936352014-08-05 14:04:04 +10007009/*[clinic input]
7010os.setpgrp
7011
7012Make the current process the leader of its process group.
7013[clinic start generated code]*/
7014
Larry Hastings2f936352014-08-05 14:04:04 +10007015static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007016os_setpgrp_impl(PyObject *module)
7017/*[clinic end generated code: output=2554735b0a60f0a0 input=1f0619fcb5731e7e]*/
Guido van Rossumc2670a01992-09-13 20:07:29 +00007018{
Guido van Rossum64933891994-10-20 21:56:42 +00007019#ifdef SETPGRP_HAVE_ARG
Victor Stinner8c62be82010-05-06 00:08:46 +00007020 if (setpgrp(0, 0) < 0)
Guido van Rossum64933891994-10-20 21:56:42 +00007021#else /* SETPGRP_HAVE_ARG */
Victor Stinner8c62be82010-05-06 00:08:46 +00007022 if (setpgrp() < 0)
Guido van Rossum64933891994-10-20 21:56:42 +00007023#endif /* SETPGRP_HAVE_ARG */
Victor Stinner8c62be82010-05-06 00:08:46 +00007024 return posix_error();
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02007025 Py_RETURN_NONE;
Guido van Rossumc2670a01992-09-13 20:07:29 +00007026}
Guido van Rossumb6775db1994-08-01 11:34:53 +00007027#endif /* HAVE_SETPGRP */
7028
Guido van Rossumad0ee831995-03-01 10:34:45 +00007029#ifdef HAVE_GETPPID
Amaury Forgeot d'Arc4b6fdf32010-09-07 21:31:17 +00007030
7031#ifdef MS_WINDOWS
7032#include <tlhelp32.h>
7033
7034static PyObject*
7035win32_getppid()
7036{
7037 HANDLE snapshot;
7038 pid_t mypid;
7039 PyObject* result = NULL;
7040 BOOL have_record;
7041 PROCESSENTRY32 pe;
7042
7043 mypid = getpid(); /* This function never fails */
7044
7045 snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
7046 if (snapshot == INVALID_HANDLE_VALUE)
7047 return PyErr_SetFromWindowsErr(GetLastError());
7048
7049 pe.dwSize = sizeof(pe);
7050 have_record = Process32First(snapshot, &pe);
7051 while (have_record) {
7052 if (mypid == (pid_t)pe.th32ProcessID) {
7053 /* We could cache the ulong value in a static variable. */
7054 result = PyLong_FromPid((pid_t)pe.th32ParentProcessID);
7055 break;
7056 }
7057
7058 have_record = Process32Next(snapshot, &pe);
7059 }
7060
7061 /* If our loop exits and our pid was not found (result will be NULL)
7062 * then GetLastError will return ERROR_NO_MORE_FILES. This is an
7063 * error anyway, so let's raise it. */
7064 if (!result)
7065 result = PyErr_SetFromWindowsErr(GetLastError());
7066
7067 CloseHandle(snapshot);
7068
7069 return result;
7070}
7071#endif /*MS_WINDOWS*/
7072
Larry Hastings2f936352014-08-05 14:04:04 +10007073
7074/*[clinic input]
7075os.getppid
7076
7077Return the parent's process id.
7078
7079If the parent process has already exited, Windows machines will still
7080return its id; others systems will return the id of the 'init' process (1).
7081[clinic start generated code]*/
7082
Larry Hastings2f936352014-08-05 14:04:04 +10007083static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007084os_getppid_impl(PyObject *module)
7085/*[clinic end generated code: output=43b2a946a8c603b4 input=e637cb87539c030e]*/
Guido van Rossum85e3b011991-06-03 12:42:10 +00007086{
Amaury Forgeot d'Arc4b6fdf32010-09-07 21:31:17 +00007087#ifdef MS_WINDOWS
7088 return win32_getppid();
7089#else
Victor Stinner8c62be82010-05-06 00:08:46 +00007090 return PyLong_FromPid(getppid());
Guido van Rossumad0ee831995-03-01 10:34:45 +00007091#endif
Amaury Forgeot d'Arc4b6fdf32010-09-07 21:31:17 +00007092}
7093#endif /* HAVE_GETPPID */
Guido van Rossum85e3b011991-06-03 12:42:10 +00007094
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007095
Fred Drake12c6e2d1999-12-14 21:25:03 +00007096#ifdef HAVE_GETLOGIN
Larry Hastings2f936352014-08-05 14:04:04 +10007097/*[clinic input]
7098os.getlogin
7099
7100Return the actual login name.
7101[clinic start generated code]*/
7102
Larry Hastings2f936352014-08-05 14:04:04 +10007103static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007104os_getlogin_impl(PyObject *module)
7105/*[clinic end generated code: output=a32e66a7e5715dac input=2a21ab1e917163df]*/
Fred Drake12c6e2d1999-12-14 21:25:03 +00007106{
Victor Stinner8c62be82010-05-06 00:08:46 +00007107 PyObject *result = NULL;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00007108#ifdef MS_WINDOWS
Brian Curtine8e4b3b2010-09-23 20:04:14 +00007109 wchar_t user_name[UNLEN + 1];
Victor Stinner63941882011-09-29 00:42:28 +02007110 DWORD num_chars = Py_ARRAY_LENGTH(user_name);
Brian Curtine8e4b3b2010-09-23 20:04:14 +00007111
7112 if (GetUserNameW(user_name, &num_chars)) {
7113 /* num_chars is the number of unicode chars plus null terminator */
7114 result = PyUnicode_FromWideChar(user_name, num_chars - 1);
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00007115 }
7116 else
Brian Curtine8e4b3b2010-09-23 20:04:14 +00007117 result = PyErr_SetFromWindowsErr(GetLastError());
7118#else
Victor Stinner8c62be82010-05-06 00:08:46 +00007119 char *name;
7120 int old_errno = errno;
Fred Drake12c6e2d1999-12-14 21:25:03 +00007121
Victor Stinner8c62be82010-05-06 00:08:46 +00007122 errno = 0;
7123 name = getlogin();
7124 if (name == NULL) {
7125 if (errno)
Victor Stinnere039ffe2010-08-15 09:33:08 +00007126 posix_error();
Fred Drake12c6e2d1999-12-14 21:25:03 +00007127 else
Victor Stinnere039ffe2010-08-15 09:33:08 +00007128 PyErr_SetString(PyExc_OSError, "unable to determine login name");
Victor Stinner8c62be82010-05-06 00:08:46 +00007129 }
7130 else
Victor Stinnere039ffe2010-08-15 09:33:08 +00007131 result = PyUnicode_DecodeFSDefault(name);
Victor Stinner8c62be82010-05-06 00:08:46 +00007132 errno = old_errno;
Brian Curtine8e4b3b2010-09-23 20:04:14 +00007133#endif
Fred Drake12c6e2d1999-12-14 21:25:03 +00007134 return result;
7135}
Brian Curtine8e4b3b2010-09-23 20:04:14 +00007136#endif /* HAVE_GETLOGIN */
Fred Drake12c6e2d1999-12-14 21:25:03 +00007137
Larry Hastings2f936352014-08-05 14:04:04 +10007138
Guido van Rossumad0ee831995-03-01 10:34:45 +00007139#ifdef HAVE_GETUID
Larry Hastings2f936352014-08-05 14:04:04 +10007140/*[clinic input]
7141os.getuid
7142
7143Return the current process's user id.
7144[clinic start generated code]*/
7145
Larry Hastings2f936352014-08-05 14:04:04 +10007146static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007147os_getuid_impl(PyObject *module)
7148/*[clinic end generated code: output=415c0b401ebed11a input=b53c8b35f110a516]*/
Guido van Rossum46003ff1992-05-15 11:05:24 +00007149{
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02007150 return _PyLong_FromUid(getuid());
Guido van Rossum46003ff1992-05-15 11:05:24 +00007151}
Larry Hastings2f936352014-08-05 14:04:04 +10007152#endif /* HAVE_GETUID */
Guido van Rossum46003ff1992-05-15 11:05:24 +00007153
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007154
Brian Curtineb24d742010-04-12 17:16:38 +00007155#ifdef MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +10007156#define HAVE_KILL
7157#endif /* MS_WINDOWS */
7158
7159#ifdef HAVE_KILL
7160/*[clinic input]
7161os.kill
7162
7163 pid: pid_t
7164 signal: Py_ssize_t
7165 /
7166
7167Kill a process with a signal.
7168[clinic start generated code]*/
7169
Larry Hastings2f936352014-08-05 14:04:04 +10007170static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007171os_kill_impl(PyObject *module, pid_t pid, Py_ssize_t signal)
7172/*[clinic end generated code: output=8e346a6701c88568 input=61a36b86ca275ab9]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007173#ifndef MS_WINDOWS
7174{
7175 if (kill(pid, (int)signal) == -1)
7176 return posix_error();
7177 Py_RETURN_NONE;
7178}
7179#else /* !MS_WINDOWS */
Brian Curtineb24d742010-04-12 17:16:38 +00007180{
Amaury Forgeot d'Arc0a589c92010-05-15 20:35:12 +00007181 PyObject *result;
Larry Hastings2f936352014-08-05 14:04:04 +10007182 DWORD sig = (DWORD)signal;
7183 DWORD err;
Victor Stinner8c62be82010-05-06 00:08:46 +00007184 HANDLE handle;
Brian Curtineb24d742010-04-12 17:16:38 +00007185
Victor Stinner8c62be82010-05-06 00:08:46 +00007186 /* Console processes which share a common console can be sent CTRL+C or
7187 CTRL+BREAK events, provided they handle said events. */
7188 if (sig == CTRL_C_EVENT || sig == CTRL_BREAK_EVENT) {
Richard Oudkerkac0ad882013-06-05 23:29:30 +01007189 if (GenerateConsoleCtrlEvent(sig, (DWORD)pid) == 0) {
Victor Stinner8c62be82010-05-06 00:08:46 +00007190 err = GetLastError();
7191 PyErr_SetFromWindowsErr(err);
7192 }
7193 else
7194 Py_RETURN_NONE;
7195 }
Brian Curtineb24d742010-04-12 17:16:38 +00007196
Victor Stinner8c62be82010-05-06 00:08:46 +00007197 /* If the signal is outside of what GenerateConsoleCtrlEvent can use,
7198 attempt to open and terminate the process. */
Richard Oudkerkac0ad882013-06-05 23:29:30 +01007199 handle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, (DWORD)pid);
Victor Stinner8c62be82010-05-06 00:08:46 +00007200 if (handle == NULL) {
7201 err = GetLastError();
7202 return PyErr_SetFromWindowsErr(err);
7203 }
Brian Curtineb24d742010-04-12 17:16:38 +00007204
Victor Stinner8c62be82010-05-06 00:08:46 +00007205 if (TerminateProcess(handle, sig) == 0) {
7206 err = GetLastError();
7207 result = PyErr_SetFromWindowsErr(err);
7208 } else {
7209 Py_INCREF(Py_None);
7210 result = Py_None;
7211 }
Brian Curtineb24d742010-04-12 17:16:38 +00007212
Victor Stinner8c62be82010-05-06 00:08:46 +00007213 CloseHandle(handle);
7214 return result;
Brian Curtineb24d742010-04-12 17:16:38 +00007215}
Larry Hastings2f936352014-08-05 14:04:04 +10007216#endif /* !MS_WINDOWS */
7217#endif /* HAVE_KILL */
7218
7219
7220#ifdef HAVE_KILLPG
7221/*[clinic input]
7222os.killpg
7223
7224 pgid: pid_t
7225 signal: int
7226 /
7227
7228Kill a process group with a signal.
7229[clinic start generated code]*/
7230
Larry Hastings2f936352014-08-05 14:04:04 +10007231static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007232os_killpg_impl(PyObject *module, pid_t pgid, int signal)
7233/*[clinic end generated code: output=6dbcd2f1fdf5fdba input=38b5449eb8faec19]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007234{
7235 /* XXX some man pages make the `pgid` parameter an int, others
7236 a pid_t. Since getpgrp() returns a pid_t, we assume killpg should
7237 take the same type. Moreover, pid_t is always at least as wide as
7238 int (else compilation of this module fails), which is safe. */
7239 if (killpg(pgid, signal) == -1)
7240 return posix_error();
7241 Py_RETURN_NONE;
7242}
7243#endif /* HAVE_KILLPG */
7244
Brian Curtineb24d742010-04-12 17:16:38 +00007245
Guido van Rossumc0125471996-06-28 18:55:32 +00007246#ifdef HAVE_PLOCK
Guido van Rossumc0125471996-06-28 18:55:32 +00007247#ifdef HAVE_SYS_LOCK_H
7248#include <sys/lock.h>
7249#endif
7250
Larry Hastings2f936352014-08-05 14:04:04 +10007251/*[clinic input]
7252os.plock
7253 op: int
7254 /
7255
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007256Lock program segments into memory.");
Larry Hastings2f936352014-08-05 14:04:04 +10007257[clinic start generated code]*/
7258
Larry Hastings2f936352014-08-05 14:04:04 +10007259static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007260os_plock_impl(PyObject *module, int op)
7261/*[clinic end generated code: output=81424167033b168e input=e6e5e348e1525f60]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007262{
Victor Stinner8c62be82010-05-06 00:08:46 +00007263 if (plock(op) == -1)
7264 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10007265 Py_RETURN_NONE;
Guido van Rossumc0125471996-06-28 18:55:32 +00007266}
Larry Hastings2f936352014-08-05 14:04:04 +10007267#endif /* HAVE_PLOCK */
7268
Guido van Rossumc0125471996-06-28 18:55:32 +00007269
Guido van Rossumb6775db1994-08-01 11:34:53 +00007270#ifdef HAVE_SETUID
Larry Hastings2f936352014-08-05 14:04:04 +10007271/*[clinic input]
7272os.setuid
7273
7274 uid: uid_t
7275 /
7276
7277Set the current process's user id.
7278[clinic start generated code]*/
7279
Larry Hastings2f936352014-08-05 14:04:04 +10007280static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007281os_setuid_impl(PyObject *module, uid_t uid)
7282/*[clinic end generated code: output=a0a41fd0d1ec555f input=c921a3285aa22256]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007283{
Victor Stinner8c62be82010-05-06 00:08:46 +00007284 if (setuid(uid) < 0)
7285 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10007286 Py_RETURN_NONE;
Guido van Rossuma3d78fb1993-11-10 09:23:53 +00007287}
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +00007288#endif /* HAVE_SETUID */
Guido van Rossuma3d78fb1993-11-10 09:23:53 +00007289
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007290
Andrew M. Kuchling8d2f2b22000-07-13 01:26:58 +00007291#ifdef HAVE_SETEUID
Larry Hastings2f936352014-08-05 14:04:04 +10007292/*[clinic input]
7293os.seteuid
7294
7295 euid: uid_t
7296 /
7297
7298Set the current process's effective user id.
7299[clinic start generated code]*/
7300
Larry Hastings2f936352014-08-05 14:04:04 +10007301static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007302os_seteuid_impl(PyObject *module, uid_t euid)
7303/*[clinic end generated code: output=102e3ad98361519a input=ba93d927e4781aa9]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007304{
7305 if (seteuid(euid) < 0)
Victor Stinner8c62be82010-05-06 00:08:46 +00007306 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10007307 Py_RETURN_NONE;
Andrew M. Kuchling8d2f2b22000-07-13 01:26:58 +00007308}
7309#endif /* HAVE_SETEUID */
7310
Larry Hastings2f936352014-08-05 14:04:04 +10007311
Andrew M. Kuchling8d2f2b22000-07-13 01:26:58 +00007312#ifdef HAVE_SETEGID
Larry Hastings2f936352014-08-05 14:04:04 +10007313/*[clinic input]
7314os.setegid
7315
7316 egid: gid_t
7317 /
7318
7319Set the current process's effective group id.
7320[clinic start generated code]*/
7321
Larry Hastings2f936352014-08-05 14:04:04 +10007322static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007323os_setegid_impl(PyObject *module, gid_t egid)
7324/*[clinic end generated code: output=4e4b825a6a10258d input=4080526d0ccd6ce3]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007325{
7326 if (setegid(egid) < 0)
Victor Stinner8c62be82010-05-06 00:08:46 +00007327 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10007328 Py_RETURN_NONE;
Andrew M. Kuchling8d2f2b22000-07-13 01:26:58 +00007329}
7330#endif /* HAVE_SETEGID */
7331
Larry Hastings2f936352014-08-05 14:04:04 +10007332
Andrew M. Kuchling8d2f2b22000-07-13 01:26:58 +00007333#ifdef HAVE_SETREUID
Larry Hastings2f936352014-08-05 14:04:04 +10007334/*[clinic input]
7335os.setreuid
7336
7337 ruid: uid_t
7338 euid: uid_t
7339 /
7340
7341Set the current process's real and effective user ids.
7342[clinic start generated code]*/
7343
Larry Hastings2f936352014-08-05 14:04:04 +10007344static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007345os_setreuid_impl(PyObject *module, uid_t ruid, uid_t euid)
7346/*[clinic end generated code: output=62d991210006530a input=0ca8978de663880c]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007347{
Victor Stinner8c62be82010-05-06 00:08:46 +00007348 if (setreuid(ruid, euid) < 0) {
7349 return posix_error();
7350 } else {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02007351 Py_RETURN_NONE;
Victor Stinner8c62be82010-05-06 00:08:46 +00007352 }
Andrew M. Kuchling8d2f2b22000-07-13 01:26:58 +00007353}
7354#endif /* HAVE_SETREUID */
7355
Larry Hastings2f936352014-08-05 14:04:04 +10007356
Andrew M. Kuchling8d2f2b22000-07-13 01:26:58 +00007357#ifdef HAVE_SETREGID
Larry Hastings2f936352014-08-05 14:04:04 +10007358/*[clinic input]
7359os.setregid
7360
7361 rgid: gid_t
7362 egid: gid_t
7363 /
7364
7365Set the current process's real and effective group ids.
7366[clinic start generated code]*/
7367
Larry Hastings2f936352014-08-05 14:04:04 +10007368static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007369os_setregid_impl(PyObject *module, gid_t rgid, gid_t egid)
7370/*[clinic end generated code: output=aa803835cf5342f3 input=c59499f72846db78]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007371{
7372 if (setregid(rgid, egid) < 0)
Victor Stinner8c62be82010-05-06 00:08:46 +00007373 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10007374 Py_RETURN_NONE;
Andrew M. Kuchling8d2f2b22000-07-13 01:26:58 +00007375}
7376#endif /* HAVE_SETREGID */
7377
Larry Hastings2f936352014-08-05 14:04:04 +10007378
Guido van Rossumb6775db1994-08-01 11:34:53 +00007379#ifdef HAVE_SETGID
Larry Hastings2f936352014-08-05 14:04:04 +10007380/*[clinic input]
7381os.setgid
7382 gid: gid_t
7383 /
7384
7385Set the current process's group id.
7386[clinic start generated code]*/
7387
Larry Hastings2f936352014-08-05 14:04:04 +10007388static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007389os_setgid_impl(PyObject *module, gid_t gid)
7390/*[clinic end generated code: output=bdccd7403f6ad8c3 input=27d30c4059045dc6]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007391{
Victor Stinner8c62be82010-05-06 00:08:46 +00007392 if (setgid(gid) < 0)
7393 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10007394 Py_RETURN_NONE;
Guido van Rossuma3d78fb1993-11-10 09:23:53 +00007395}
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +00007396#endif /* HAVE_SETGID */
Guido van Rossuma3d78fb1993-11-10 09:23:53 +00007397
Larry Hastings2f936352014-08-05 14:04:04 +10007398
Martin v. Löwis61c5edf2001-10-18 04:06:00 +00007399#ifdef HAVE_SETGROUPS
Larry Hastings2f936352014-08-05 14:04:04 +10007400/*[clinic input]
7401os.setgroups
7402
7403 groups: object
7404 /
7405
7406Set the groups of the current process to list.
7407[clinic start generated code]*/
7408
Martin v. Löwis61c5edf2001-10-18 04:06:00 +00007409static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007410os_setgroups(PyObject *module, PyObject *groups)
7411/*[clinic end generated code: output=3fcb32aad58c5ecd input=fa742ca3daf85a7e]*/
Martin v. Löwis61c5edf2001-10-18 04:06:00 +00007412{
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03007413 Py_ssize_t i, len;
Victor Stinner8c62be82010-05-06 00:08:46 +00007414 gid_t grouplist[MAX_GROUPS];
Tim Peters5aa91602002-01-30 05:46:57 +00007415
Victor Stinner8c62be82010-05-06 00:08:46 +00007416 if (!PySequence_Check(groups)) {
7417 PyErr_SetString(PyExc_TypeError, "setgroups argument must be a sequence");
7418 return NULL;
7419 }
7420 len = PySequence_Size(groups);
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03007421 if (len < 0) {
7422 return NULL;
7423 }
Victor Stinner8c62be82010-05-06 00:08:46 +00007424 if (len > MAX_GROUPS) {
7425 PyErr_SetString(PyExc_ValueError, "too many groups");
7426 return NULL;
7427 }
7428 for(i = 0; i < len; i++) {
7429 PyObject *elem;
7430 elem = PySequence_GetItem(groups, i);
7431 if (!elem)
7432 return NULL;
7433 if (!PyLong_Check(elem)) {
7434 PyErr_SetString(PyExc_TypeError,
7435 "groups must be integers");
7436 Py_DECREF(elem);
7437 return NULL;
7438 } else {
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02007439 if (!_Py_Gid_Converter(elem, &grouplist[i])) {
Victor Stinner8c62be82010-05-06 00:08:46 +00007440 Py_DECREF(elem);
7441 return NULL;
7442 }
7443 }
7444 Py_DECREF(elem);
7445 }
Martin v. Löwis61c5edf2001-10-18 04:06:00 +00007446
Victor Stinner8c62be82010-05-06 00:08:46 +00007447 if (setgroups(len, grouplist) < 0)
7448 return posix_error();
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02007449 Py_RETURN_NONE;
Martin v. Löwis61c5edf2001-10-18 04:06:00 +00007450}
7451#endif /* HAVE_SETGROUPS */
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007452
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007453#if defined(HAVE_WAIT3) || defined(HAVE_WAIT4)
7454static PyObject *
Victor Stinner4195b5c2012-02-08 23:03:19 +01007455wait_helper(pid_t pid, int status, struct rusage *ru)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007456{
Victor Stinner8c62be82010-05-06 00:08:46 +00007457 PyObject *result;
7458 static PyObject *struct_rusage;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02007459 _Py_IDENTIFIER(struct_rusage);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007460
Victor Stinner8c62be82010-05-06 00:08:46 +00007461 if (pid == -1)
7462 return posix_error();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007463
Victor Stinner8c62be82010-05-06 00:08:46 +00007464 if (struct_rusage == NULL) {
7465 PyObject *m = PyImport_ImportModuleNoBlock("resource");
7466 if (m == NULL)
7467 return NULL;
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02007468 struct_rusage = _PyObject_GetAttrId(m, &PyId_struct_rusage);
Victor Stinner8c62be82010-05-06 00:08:46 +00007469 Py_DECREF(m);
7470 if (struct_rusage == NULL)
7471 return NULL;
7472 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007473
Victor Stinner8c62be82010-05-06 00:08:46 +00007474 /* XXX(nnorwitz): Copied (w/mods) from resource.c, there should be only one. */
7475 result = PyStructSequence_New((PyTypeObject*) struct_rusage);
7476 if (!result)
7477 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007478
7479#ifndef doubletime
7480#define doubletime(TV) ((double)(TV).tv_sec + (TV).tv_usec * 0.000001)
7481#endif
7482
Victor Stinner8c62be82010-05-06 00:08:46 +00007483 PyStructSequence_SET_ITEM(result, 0,
Victor Stinner4195b5c2012-02-08 23:03:19 +01007484 PyFloat_FromDouble(doubletime(ru->ru_utime)));
Victor Stinner8c62be82010-05-06 00:08:46 +00007485 PyStructSequence_SET_ITEM(result, 1,
Victor Stinner4195b5c2012-02-08 23:03:19 +01007486 PyFloat_FromDouble(doubletime(ru->ru_stime)));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007487#define SET_INT(result, index, value)\
Victor Stinner8c62be82010-05-06 00:08:46 +00007488 PyStructSequence_SET_ITEM(result, index, PyLong_FromLong(value))
7489 SET_INT(result, 2, ru->ru_maxrss);
7490 SET_INT(result, 3, ru->ru_ixrss);
7491 SET_INT(result, 4, ru->ru_idrss);
7492 SET_INT(result, 5, ru->ru_isrss);
7493 SET_INT(result, 6, ru->ru_minflt);
7494 SET_INT(result, 7, ru->ru_majflt);
7495 SET_INT(result, 8, ru->ru_nswap);
7496 SET_INT(result, 9, ru->ru_inblock);
7497 SET_INT(result, 10, ru->ru_oublock);
7498 SET_INT(result, 11, ru->ru_msgsnd);
7499 SET_INT(result, 12, ru->ru_msgrcv);
7500 SET_INT(result, 13, ru->ru_nsignals);
7501 SET_INT(result, 14, ru->ru_nvcsw);
7502 SET_INT(result, 15, ru->ru_nivcsw);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007503#undef SET_INT
7504
Victor Stinner8c62be82010-05-06 00:08:46 +00007505 if (PyErr_Occurred()) {
7506 Py_DECREF(result);
7507 return NULL;
7508 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007509
Victor Stinner8c62be82010-05-06 00:08:46 +00007510 return Py_BuildValue("NiN", PyLong_FromPid(pid), status, result);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007511}
7512#endif /* HAVE_WAIT3 || HAVE_WAIT4 */
7513
Larry Hastings2f936352014-08-05 14:04:04 +10007514
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007515#ifdef HAVE_WAIT3
Larry Hastings2f936352014-08-05 14:04:04 +10007516/*[clinic input]
7517os.wait3
7518
7519 options: int
7520Wait for completion of a child process.
7521
7522Returns a tuple of information about the child process:
7523 (pid, status, rusage)
7524[clinic start generated code]*/
7525
Larry Hastings2f936352014-08-05 14:04:04 +10007526static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007527os_wait3_impl(PyObject *module, int options)
7528/*[clinic end generated code: output=92c3224e6f28217a input=8ac4c56956b61710]*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007529{
Victor Stinner8c62be82010-05-06 00:08:46 +00007530 pid_t pid;
Victor Stinner8c62be82010-05-06 00:08:46 +00007531 struct rusage ru;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007532 int async_err = 0;
Victor Stinner8c62be82010-05-06 00:08:46 +00007533 WAIT_TYPE status;
7534 WAIT_STATUS_INT(status) = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007535
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007536 do {
7537 Py_BEGIN_ALLOW_THREADS
7538 pid = wait3(&status, options, &ru);
7539 Py_END_ALLOW_THREADS
7540 } while (pid < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
7541 if (pid < 0)
7542 return (!async_err) ? posix_error() : NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007543
Victor Stinner4195b5c2012-02-08 23:03:19 +01007544 return wait_helper(pid, WAIT_STATUS_INT(status), &ru);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007545}
7546#endif /* HAVE_WAIT3 */
7547
Larry Hastings2f936352014-08-05 14:04:04 +10007548
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007549#ifdef HAVE_WAIT4
Larry Hastings2f936352014-08-05 14:04:04 +10007550/*[clinic input]
7551
7552os.wait4
7553
7554 pid: pid_t
7555 options: int
7556
7557Wait for completion of a specific child process.
7558
7559Returns a tuple of information about the child process:
7560 (pid, status, rusage)
7561[clinic start generated code]*/
7562
Larry Hastings2f936352014-08-05 14:04:04 +10007563static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007564os_wait4_impl(PyObject *module, pid_t pid, int options)
7565/*[clinic end generated code: output=66195aa507b35f70 input=d11deed0750600ba]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007566{
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007567 pid_t res;
Victor Stinner8c62be82010-05-06 00:08:46 +00007568 struct rusage ru;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007569 int async_err = 0;
Victor Stinner8c62be82010-05-06 00:08:46 +00007570 WAIT_TYPE status;
7571 WAIT_STATUS_INT(status) = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007572
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007573 do {
7574 Py_BEGIN_ALLOW_THREADS
7575 res = wait4(pid, &status, options, &ru);
7576 Py_END_ALLOW_THREADS
7577 } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
7578 if (res < 0)
7579 return (!async_err) ? posix_error() : NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007580
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007581 return wait_helper(res, WAIT_STATUS_INT(status), &ru);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007582}
7583#endif /* HAVE_WAIT4 */
7584
Larry Hastings2f936352014-08-05 14:04:04 +10007585
Ross Lagerwall7807c352011-03-17 20:20:30 +02007586#if defined(HAVE_WAITID) && !defined(__APPLE__)
Larry Hastings2f936352014-08-05 14:04:04 +10007587/*[clinic input]
7588os.waitid
7589
7590 idtype: idtype_t
7591 Must be one of be P_PID, P_PGID or P_ALL.
7592 id: id_t
7593 The id to wait on.
7594 options: int
7595 Constructed from the ORing of one or more of WEXITED, WSTOPPED
7596 or WCONTINUED and additionally may be ORed with WNOHANG or WNOWAIT.
7597 /
7598
7599Returns the result of waiting for a process or processes.
7600
7601Returns either waitid_result or None if WNOHANG is specified and there are
7602no children in a waitable state.
7603[clinic start generated code]*/
7604
Larry Hastings2f936352014-08-05 14:04:04 +10007605static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007606os_waitid_impl(PyObject *module, idtype_t idtype, id_t id, int options)
7607/*[clinic end generated code: output=5d2e1c0bde61f4d8 input=d8e7f76e052b7920]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007608{
7609 PyObject *result;
7610 int res;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007611 int async_err = 0;
Ross Lagerwall7807c352011-03-17 20:20:30 +02007612 siginfo_t si;
7613 si.si_pid = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10007614
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007615 do {
7616 Py_BEGIN_ALLOW_THREADS
7617 res = waitid(idtype, id, &si, options);
7618 Py_END_ALLOW_THREADS
7619 } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
7620 if (res < 0)
7621 return (!async_err) ? posix_error() : NULL;
Ross Lagerwall7807c352011-03-17 20:20:30 +02007622
7623 if (si.si_pid == 0)
7624 Py_RETURN_NONE;
7625
Eddie Elizondo474eedf2018-11-13 04:09:31 -08007626 result = PyStructSequence_New(WaitidResultType);
Ross Lagerwall7807c352011-03-17 20:20:30 +02007627 if (!result)
7628 return NULL;
7629
7630 PyStructSequence_SET_ITEM(result, 0, PyLong_FromPid(si.si_pid));
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02007631 PyStructSequence_SET_ITEM(result, 1, _PyLong_FromUid(si.si_uid));
Ross Lagerwall7807c352011-03-17 20:20:30 +02007632 PyStructSequence_SET_ITEM(result, 2, PyLong_FromLong((long)(si.si_signo)));
7633 PyStructSequence_SET_ITEM(result, 3, PyLong_FromLong((long)(si.si_status)));
7634 PyStructSequence_SET_ITEM(result, 4, PyLong_FromLong((long)(si.si_code)));
7635 if (PyErr_Occurred()) {
7636 Py_DECREF(result);
7637 return NULL;
7638 }
7639
7640 return result;
7641}
Larry Hastings2f936352014-08-05 14:04:04 +10007642#endif /* defined(HAVE_WAITID) && !defined(__APPLE__) */
Ross Lagerwall7807c352011-03-17 20:20:30 +02007643
Larry Hastings2f936352014-08-05 14:04:04 +10007644
7645#if defined(HAVE_WAITPID)
7646/*[clinic input]
7647os.waitpid
7648 pid: pid_t
7649 options: int
7650 /
7651
7652Wait for completion of a given child process.
7653
7654Returns a tuple of information regarding the child process:
7655 (pid, status)
7656
7657The options argument is ignored on Windows.
7658[clinic start generated code]*/
7659
Larry Hastings2f936352014-08-05 14:04:04 +10007660static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007661os_waitpid_impl(PyObject *module, pid_t pid, int options)
7662/*[clinic end generated code: output=5c37c06887a20270 input=0bf1666b8758fda3]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007663{
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007664 pid_t res;
7665 int async_err = 0;
Victor Stinner8c62be82010-05-06 00:08:46 +00007666 WAIT_TYPE status;
7667 WAIT_STATUS_INT(status) = 0;
Guido van Rossum54ecc3d1999-01-27 17:53:11 +00007668
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007669 do {
7670 Py_BEGIN_ALLOW_THREADS
7671 res = waitpid(pid, &status, options);
7672 Py_END_ALLOW_THREADS
7673 } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
7674 if (res < 0)
7675 return (!async_err) ? posix_error() : NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007676
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007677 return Py_BuildValue("Ni", PyLong_FromPid(res), WAIT_STATUS_INT(status));
Guido van Rossum21803b81992-08-09 12:55:27 +00007678}
Tim Petersab034fa2002-02-01 11:27:43 +00007679#elif defined(HAVE_CWAIT)
Tim Petersab034fa2002-02-01 11:27:43 +00007680/* MS C has a variant of waitpid() that's usable for most purposes. */
Larry Hastings2f936352014-08-05 14:04:04 +10007681/*[clinic input]
7682os.waitpid
Benjamin Petersonca470632016-09-06 13:47:26 -07007683 pid: intptr_t
Larry Hastings2f936352014-08-05 14:04:04 +10007684 options: int
7685 /
7686
7687Wait for completion of a given process.
7688
7689Returns a tuple of information regarding the process:
7690 (pid, status << 8)
7691
7692The options argument is ignored on Windows.
7693[clinic start generated code]*/
7694
Larry Hastings2f936352014-08-05 14:04:04 +10007695static PyObject *
Benjamin Petersonca470632016-09-06 13:47:26 -07007696os_waitpid_impl(PyObject *module, intptr_t pid, int options)
Victor Stinner581139c2016-09-06 15:54:20 -07007697/*[clinic end generated code: output=be836b221271d538 input=40f2440c515410f8]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007698{
7699 int status;
Benjamin Petersonca470632016-09-06 13:47:26 -07007700 intptr_t res;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007701 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10007702
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007703 do {
7704 Py_BEGIN_ALLOW_THREADS
Steve Dower11f43262016-11-19 18:33:39 -08007705 _Py_BEGIN_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007706 res = _cwait(&status, pid, options);
Steve Dower11f43262016-11-19 18:33:39 -08007707 _Py_END_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007708 Py_END_ALLOW_THREADS
7709 } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Victor Stinnerd3ffd322015-09-15 10:11:03 +02007710 if (res < 0)
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007711 return (!async_err) ? posix_error() : NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007712
Victor Stinner8c62be82010-05-06 00:08:46 +00007713 /* shift the status left a byte so this is more like the POSIX waitpid */
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007714 return Py_BuildValue(_Py_PARSE_INTPTR "i", res, status << 8);
Tim Petersab034fa2002-02-01 11:27:43 +00007715}
Larry Hastings2f936352014-08-05 14:04:04 +10007716#endif
7717
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007718
Guido van Rossumad0ee831995-03-01 10:34:45 +00007719#ifdef HAVE_WAIT
Larry Hastings2f936352014-08-05 14:04:04 +10007720/*[clinic input]
7721os.wait
7722
7723Wait for completion of a child process.
7724
7725Returns a tuple of information about the child process:
7726 (pid, status)
7727[clinic start generated code]*/
7728
Larry Hastings2f936352014-08-05 14:04:04 +10007729static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007730os_wait_impl(PyObject *module)
7731/*[clinic end generated code: output=6bc419ac32fb364b input=03b0182d4a4700ce]*/
Guido van Rossum21803b81992-08-09 12:55:27 +00007732{
Victor Stinner8c62be82010-05-06 00:08:46 +00007733 pid_t pid;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007734 int async_err = 0;
Victor Stinner8c62be82010-05-06 00:08:46 +00007735 WAIT_TYPE status;
7736 WAIT_STATUS_INT(status) = 0;
Neal Norwitze241ce82003-02-17 18:17:05 +00007737
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007738 do {
7739 Py_BEGIN_ALLOW_THREADS
7740 pid = wait(&status);
7741 Py_END_ALLOW_THREADS
7742 } while (pid < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
7743 if (pid < 0)
7744 return (!async_err) ? posix_error() : NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007745
Victor Stinner8c62be82010-05-06 00:08:46 +00007746 return Py_BuildValue("Ni", PyLong_FromPid(pid), WAIT_STATUS_INT(status));
Guido van Rossum85e3b011991-06-03 12:42:10 +00007747}
Larry Hastings2f936352014-08-05 14:04:04 +10007748#endif /* HAVE_WAIT */
Guido van Rossum85e3b011991-06-03 12:42:10 +00007749
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007750
Larry Hastings9cf065c2012-06-22 16:30:09 -07007751#if defined(HAVE_READLINK) || defined(MS_WINDOWS)
Serhiy Storchaka12a69db2018-09-17 15:38:27 +03007752/*[clinic input]
7753os.readlink
7754
7755 path: path_t
7756 *
7757 dir_fd: dir_fd(requires='readlinkat') = None
7758
7759Return a string representing the path to which the symbolic link points.
7760
7761If dir_fd is not None, it should be a file descriptor open to a directory,
7762and path should be relative; path will then be relative to that directory.
7763
7764dir_fd may not be implemented on your platform. If it is unavailable,
7765using it will raise a NotImplementedError.
7766[clinic start generated code]*/
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007767
Barry Warsaw53699e91996-12-10 23:23:01 +00007768static PyObject *
Serhiy Storchaka12a69db2018-09-17 15:38:27 +03007769os_readlink_impl(PyObject *module, path_t *path, int dir_fd)
7770/*[clinic end generated code: output=d21b732a2e814030 input=113c87e0db1ecaf2]*/
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00007771{
Berker Peksage0b5b202018-08-15 13:03:41 +03007772#if defined(HAVE_READLINK)
Christian Heimes3cb091e2016-09-23 20:24:28 +02007773 char buffer[MAXPATHLEN+1];
Larry Hastings9cf065c2012-06-22 16:30:09 -07007774 ssize_t length;
Serhiy Storchaka12a69db2018-09-17 15:38:27 +03007775
7776 Py_BEGIN_ALLOW_THREADS
7777#ifdef HAVE_READLINKAT
7778 if (dir_fd != DEFAULT_DIR_FD)
7779 length = readlinkat(dir_fd, path->narrow, buffer, MAXPATHLEN);
7780 else
7781#endif
7782 length = readlink(path->narrow, buffer, MAXPATHLEN);
7783 Py_END_ALLOW_THREADS
7784
7785 if (length < 0) {
7786 return path_error(path);
7787 }
7788 buffer[length] = '\0';
7789
7790 if (PyUnicode_Check(path->object))
7791 return PyUnicode_DecodeFSDefaultAndSize(buffer, length);
7792 else
7793 return PyBytes_FromStringAndSize(buffer, length);
Berker Peksage0b5b202018-08-15 13:03:41 +03007794#elif defined(MS_WINDOWS)
7795 DWORD n_bytes_returned;
7796 DWORD io_result;
7797 HANDLE reparse_point_handle;
Berker Peksage0b5b202018-08-15 13:03:41 +03007798 char target_buffer[_Py_MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
7799 _Py_REPARSE_DATA_BUFFER *rdb = (_Py_REPARSE_DATA_BUFFER *)target_buffer;
7800 const wchar_t *print_name;
Serhiy Storchaka12a69db2018-09-17 15:38:27 +03007801 PyObject *result;
Thomas Wouters89f507f2006-12-13 04:49:30 +00007802
Larry Hastings2f936352014-08-05 14:04:04 +10007803 /* First get a handle to the reparse point */
7804 Py_BEGIN_ALLOW_THREADS
7805 reparse_point_handle = CreateFileW(
Serhiy Storchaka12a69db2018-09-17 15:38:27 +03007806 path->wide,
Larry Hastings2f936352014-08-05 14:04:04 +10007807 0,
7808 0,
7809 0,
7810 OPEN_EXISTING,
7811 FILE_FLAG_OPEN_REPARSE_POINT|FILE_FLAG_BACKUP_SEMANTICS,
7812 0);
7813 Py_END_ALLOW_THREADS
7814
Berker Peksage0b5b202018-08-15 13:03:41 +03007815 if (reparse_point_handle == INVALID_HANDLE_VALUE) {
Serhiy Storchaka12a69db2018-09-17 15:38:27 +03007816 return path_error(path);
Berker Peksage0b5b202018-08-15 13:03:41 +03007817 }
Larry Hastings2f936352014-08-05 14:04:04 +10007818
7819 Py_BEGIN_ALLOW_THREADS
7820 /* New call DeviceIoControl to read the reparse point */
7821 io_result = DeviceIoControl(
7822 reparse_point_handle,
7823 FSCTL_GET_REPARSE_POINT,
7824 0, 0, /* in buffer */
7825 target_buffer, sizeof(target_buffer),
7826 &n_bytes_returned,
7827 0 /* we're not using OVERLAPPED_IO */
7828 );
7829 CloseHandle(reparse_point_handle);
7830 Py_END_ALLOW_THREADS
7831
Berker Peksage0b5b202018-08-15 13:03:41 +03007832 if (io_result == 0) {
Serhiy Storchaka12a69db2018-09-17 15:38:27 +03007833 return path_error(path);
Berker Peksage0b5b202018-08-15 13:03:41 +03007834 }
Larry Hastings2f936352014-08-05 14:04:04 +10007835
7836 if (rdb->ReparseTag != IO_REPARSE_TAG_SYMLINK)
7837 {
7838 PyErr_SetString(PyExc_ValueError,
7839 "not a symbolic link");
Serhiy Storchaka12a69db2018-09-17 15:38:27 +03007840 return NULL;
Larry Hastings2f936352014-08-05 14:04:04 +10007841 }
SSE43c34aad2018-02-13 00:10:35 +07007842 print_name = (wchar_t *)((char*)rdb->SymbolicLinkReparseBuffer.PathBuffer +
7843 rdb->SymbolicLinkReparseBuffer.PrintNameOffset);
Larry Hastings2f936352014-08-05 14:04:04 +10007844
Serhiy Storchaka12a69db2018-09-17 15:38:27 +03007845 result = PyUnicode_FromWideChar(print_name,
7846 rdb->SymbolicLinkReparseBuffer.PrintNameLength / sizeof(wchar_t));
7847 if (path->narrow) {
7848 Py_SETREF(result, PyUnicode_EncodeFSDefault(result));
Berker Peksage0b5b202018-08-15 13:03:41 +03007849 }
Serhiy Storchaka12a69db2018-09-17 15:38:27 +03007850 return result;
Berker Peksage0b5b202018-08-15 13:03:41 +03007851#endif
Larry Hastings2f936352014-08-05 14:04:04 +10007852}
Berker Peksage0b5b202018-08-15 13:03:41 +03007853#endif /* defined(HAVE_READLINK) || defined(MS_WINDOWS) */
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007854
Larry Hastings9cf065c2012-06-22 16:30:09 -07007855#ifdef HAVE_SYMLINK
Larry Hastings9cf065c2012-06-22 16:30:09 -07007856
7857#if defined(MS_WINDOWS)
7858
Steve Dower6921e732018-03-05 14:26:08 -08007859/* Remove the last portion of the path - return 0 on success */
7860static int
Victor Stinner31b3b922013-06-05 01:49:17 +02007861_dirnameW(WCHAR *path)
7862{
Jason R. Coombs3a092862013-05-27 23:21:28 -04007863 WCHAR *ptr;
Steve Dower6921e732018-03-05 14:26:08 -08007864 size_t length = wcsnlen_s(path, MAX_PATH);
7865 if (length == MAX_PATH) {
7866 return -1;
7867 }
Jason R. Coombs3a092862013-05-27 23:21:28 -04007868
7869 /* walk the path from the end until a backslash is encountered */
Steve Dower6921e732018-03-05 14:26:08 -08007870 for(ptr = path + length; ptr != path; ptr--) {
7871 if (*ptr == L'\\' || *ptr == L'/') {
Jason R. Coombs3a092862013-05-27 23:21:28 -04007872 break;
Steve Dower6921e732018-03-05 14:26:08 -08007873 }
Jason R. Coombs3a092862013-05-27 23:21:28 -04007874 }
7875 *ptr = 0;
Steve Dower6921e732018-03-05 14:26:08 -08007876 return 0;
Jason R. Coombs3a092862013-05-27 23:21:28 -04007877}
7878
Victor Stinner31b3b922013-06-05 01:49:17 +02007879/* Is this path absolute? */
7880static int
7881_is_absW(const WCHAR *path)
7882{
Steve Dower6921e732018-03-05 14:26:08 -08007883 return path[0] == L'\\' || path[0] == L'/' ||
7884 (path[0] && path[1] == L':');
Jason R. Coombs3a092862013-05-27 23:21:28 -04007885}
7886
Steve Dower6921e732018-03-05 14:26:08 -08007887/* join root and rest with a backslash - return 0 on success */
7888static int
Victor Stinner31b3b922013-06-05 01:49:17 +02007889_joinW(WCHAR *dest_path, const WCHAR *root, const WCHAR *rest)
7890{
Victor Stinner31b3b922013-06-05 01:49:17 +02007891 if (_is_absW(rest)) {
Steve Dower6921e732018-03-05 14:26:08 -08007892 return wcscpy_s(dest_path, MAX_PATH, rest);
Jason R. Coombs3a092862013-05-27 23:21:28 -04007893 }
7894
Steve Dower6921e732018-03-05 14:26:08 -08007895 if (wcscpy_s(dest_path, MAX_PATH, root)) {
7896 return -1;
Jason R. Coombs3a092862013-05-27 23:21:28 -04007897 }
Steve Dower6921e732018-03-05 14:26:08 -08007898
7899 if (dest_path[0] && wcscat_s(dest_path, MAX_PATH, L"\\")) {
7900 return -1;
7901 }
7902
7903 return wcscat_s(dest_path, MAX_PATH, rest);
Jason R. Coombs3a092862013-05-27 23:21:28 -04007904}
7905
Victor Stinner31b3b922013-06-05 01:49:17 +02007906/* Return True if the path at src relative to dest is a directory */
7907static int
Serhiy Storchakadeab18d2016-05-07 16:45:18 +03007908_check_dirW(LPCWSTR src, LPCWSTR dest)
Jason R. Coombs3a092862013-05-27 23:21:28 -04007909{
Jason R. Coombs3a092862013-05-27 23:21:28 -04007910 WIN32_FILE_ATTRIBUTE_DATA src_info;
7911 WCHAR dest_parent[MAX_PATH];
7912 WCHAR src_resolved[MAX_PATH] = L"";
7913
7914 /* dest_parent = os.path.dirname(dest) */
Steve Dower6921e732018-03-05 14:26:08 -08007915 if (wcscpy_s(dest_parent, MAX_PATH, dest) ||
7916 _dirnameW(dest_parent)) {
7917 return 0;
7918 }
Jason R. Coombs3a092862013-05-27 23:21:28 -04007919 /* src_resolved = os.path.join(dest_parent, src) */
Steve Dower6921e732018-03-05 14:26:08 -08007920 if (_joinW(src_resolved, dest_parent, src)) {
7921 return 0;
7922 }
Jason R. Coombs3a092862013-05-27 23:21:28 -04007923 return (
7924 GetFileAttributesExW(src_resolved, GetFileExInfoStandard, &src_info)
7925 && src_info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY
7926 );
7927}
Larry Hastings9cf065c2012-06-22 16:30:09 -07007928#endif
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007929
Larry Hastings2f936352014-08-05 14:04:04 +10007930
7931/*[clinic input]
7932os.symlink
7933 src: path_t
7934 dst: path_t
7935 target_is_directory: bool = False
7936 *
7937 dir_fd: dir_fd(requires='symlinkat')=None
7938
7939# "symlink(src, dst, target_is_directory=False, *, dir_fd=None)\n\n\
7940
7941Create a symbolic link pointing to src named dst.
7942
7943target_is_directory is required on Windows if the target is to be
7944 interpreted as a directory. (On Windows, symlink requires
7945 Windows 6.0 or greater, and raises a NotImplementedError otherwise.)
7946 target_is_directory is ignored on non-Windows platforms.
7947
7948If dir_fd is not None, it should be a file descriptor open to a directory,
7949 and path should be relative; path will then be relative to that directory.
7950dir_fd may not be implemented on your platform.
7951 If it is unavailable, using it will raise a NotImplementedError.
7952
7953[clinic start generated code]*/
7954
Larry Hastings2f936352014-08-05 14:04:04 +10007955static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007956os_symlink_impl(PyObject *module, path_t *src, path_t *dst,
Larry Hastings89964c42015-04-14 18:07:59 -04007957 int target_is_directory, int dir_fd)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007958/*[clinic end generated code: output=08ca9f3f3cf960f6 input=e820ec4472547bc3]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007959{
Larry Hastings9cf065c2012-06-22 16:30:09 -07007960#ifdef MS_WINDOWS
7961 DWORD result;
Vidar Tonaas Fauske0e107662019-04-09 20:19:46 +02007962 DWORD flags = 0;
7963
7964 /* Assumed true, set to false if detected to not be available. */
7965 static int windows_has_symlink_unprivileged_flag = TRUE;
Larry Hastings9cf065c2012-06-22 16:30:09 -07007966#else
7967 int result;
7968#endif
7969
Larry Hastings9cf065c2012-06-22 16:30:09 -07007970#ifdef MS_WINDOWS
Larry Hastings9cf065c2012-06-22 16:30:09 -07007971
Vidar Tonaas Fauske0e107662019-04-09 20:19:46 +02007972 if (windows_has_symlink_unprivileged_flag) {
7973 /* Allow non-admin symlinks if system allows it. */
7974 flags |= SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE;
7975 }
Jason R. Coombs3a092862013-05-27 23:21:28 -04007976
Larry Hastings9cf065c2012-06-22 16:30:09 -07007977 Py_BEGIN_ALLOW_THREADS
Steve Dower6921e732018-03-05 14:26:08 -08007978 _Py_BEGIN_SUPPRESS_IPH
Vidar Tonaas Fauske0e107662019-04-09 20:19:46 +02007979 /* if src is a directory, ensure flags==1 (target_is_directory bit) */
7980 if (target_is_directory || _check_dirW(src->wide, dst->wide)) {
7981 flags |= SYMBOLIC_LINK_FLAG_DIRECTORY;
7982 }
7983
7984 result = CreateSymbolicLinkW(dst->wide, src->wide, flags);
Steve Dower6921e732018-03-05 14:26:08 -08007985 _Py_END_SUPPRESS_IPH
Larry Hastings9cf065c2012-06-22 16:30:09 -07007986 Py_END_ALLOW_THREADS
7987
Vidar Tonaas Fauske0e107662019-04-09 20:19:46 +02007988 if (windows_has_symlink_unprivileged_flag && !result &&
7989 ERROR_INVALID_PARAMETER == GetLastError()) {
7990
7991 Py_BEGIN_ALLOW_THREADS
7992 _Py_BEGIN_SUPPRESS_IPH
7993 /* This error might be caused by
7994 SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE not being supported.
7995 Try again, and update windows_has_symlink_unprivileged_flag if we
7996 are successful this time.
7997
7998 NOTE: There is a risk of a race condition here if there are other
7999 conditions than the flag causing ERROR_INVALID_PARAMETER, and
8000 another process (or thread) changes that condition in between our
8001 calls to CreateSymbolicLink.
8002 */
8003 flags &= ~(SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE);
8004 result = CreateSymbolicLinkW(dst->wide, src->wide, flags);
8005 _Py_END_SUPPRESS_IPH
8006 Py_END_ALLOW_THREADS
8007
8008 if (result || ERROR_INVALID_PARAMETER != GetLastError()) {
8009 windows_has_symlink_unprivileged_flag = FALSE;
8010 }
8011 }
8012
Larry Hastings2f936352014-08-05 14:04:04 +10008013 if (!result)
8014 return path_error2(src, dst);
Larry Hastings9cf065c2012-06-22 16:30:09 -07008015
8016#else
8017
Steve Dower6921e732018-03-05 14:26:08 -08008018 if ((src->narrow && dst->wide) || (src->wide && dst->narrow)) {
8019 PyErr_SetString(PyExc_ValueError,
8020 "symlink: src and dst must be the same type");
8021 return NULL;
8022 }
8023
Larry Hastings9cf065c2012-06-22 16:30:09 -07008024 Py_BEGIN_ALLOW_THREADS
8025#if HAVE_SYMLINKAT
8026 if (dir_fd != DEFAULT_DIR_FD)
Larry Hastings2f936352014-08-05 14:04:04 +10008027 result = symlinkat(src->narrow, dir_fd, dst->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07008028 else
8029#endif
Larry Hastings2f936352014-08-05 14:04:04 +10008030 result = symlink(src->narrow, dst->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07008031 Py_END_ALLOW_THREADS
8032
Larry Hastings2f936352014-08-05 14:04:04 +10008033 if (result)
8034 return path_error2(src, dst);
Larry Hastings9cf065c2012-06-22 16:30:09 -07008035#endif
8036
Larry Hastings2f936352014-08-05 14:04:04 +10008037 Py_RETURN_NONE;
Guido van Rossumbfaf3d61997-12-29 20:02:27 +00008038}
8039#endif /* HAVE_SYMLINK */
8040
Larry Hastings9cf065c2012-06-22 16:30:09 -07008041
Brian Curtind40e6f72010-07-08 21:39:08 +00008042
Guido van Rossumbfaf3d61997-12-29 20:02:27 +00008043
Larry Hastings605a62d2012-06-24 04:33:36 -07008044static PyStructSequence_Field times_result_fields[] = {
8045 {"user", "user time"},
8046 {"system", "system time"},
8047 {"children_user", "user time of children"},
8048 {"children_system", "system time of children"},
8049 {"elapsed", "elapsed time since an arbitrary point in the past"},
8050 {NULL}
8051};
8052
8053PyDoc_STRVAR(times_result__doc__,
8054"times_result: Result from os.times().\n\n\
8055This object may be accessed either as a tuple of\n\
8056 (user, system, children_user, children_system, elapsed),\n\
8057or via the attributes user, system, children_user, children_system,\n\
8058and elapsed.\n\
8059\n\
8060See os.times for more information.");
8061
8062static PyStructSequence_Desc times_result_desc = {
8063 "times_result", /* name */
8064 times_result__doc__, /* doc */
8065 times_result_fields,
8066 5
8067};
8068
Eddie Elizondo474eedf2018-11-13 04:09:31 -08008069static PyTypeObject* TimesResultType;
Larry Hastings605a62d2012-06-24 04:33:36 -07008070
Antoine Pitrouf3923e92012-07-24 21:23:53 +02008071#ifdef MS_WINDOWS
8072#define HAVE_TIMES /* mandatory, for the method table */
8073#endif
Larry Hastings605a62d2012-06-24 04:33:36 -07008074
Antoine Pitrouf3923e92012-07-24 21:23:53 +02008075#ifdef HAVE_TIMES
Larry Hastings605a62d2012-06-24 04:33:36 -07008076
8077static PyObject *
8078build_times_result(double user, double system,
8079 double children_user, double children_system,
8080 double elapsed)
8081{
Eddie Elizondo474eedf2018-11-13 04:09:31 -08008082 PyObject *value = PyStructSequence_New(TimesResultType);
Larry Hastings605a62d2012-06-24 04:33:36 -07008083 if (value == NULL)
8084 return NULL;
8085
8086#define SET(i, field) \
8087 { \
8088 PyObject *o = PyFloat_FromDouble(field); \
8089 if (!o) { \
8090 Py_DECREF(value); \
8091 return NULL; \
8092 } \
8093 PyStructSequence_SET_ITEM(value, i, o); \
8094 } \
8095
8096 SET(0, user);
8097 SET(1, system);
8098 SET(2, children_user);
8099 SET(3, children_system);
8100 SET(4, elapsed);
8101
8102#undef SET
8103
8104 return value;
8105}
8106
Larry Hastings605a62d2012-06-24 04:33:36 -07008107
Larry Hastings2f936352014-08-05 14:04:04 +10008108#ifndef MS_WINDOWS
8109#define NEED_TICKS_PER_SECOND
8110static long ticks_per_second = -1;
8111#endif /* MS_WINDOWS */
8112
8113/*[clinic input]
8114os.times
8115
8116Return a collection containing process timing information.
8117
8118The object returned behaves like a named tuple with these fields:
8119 (utime, stime, cutime, cstime, elapsed_time)
8120All fields are floating point numbers.
8121[clinic start generated code]*/
8122
Larry Hastings2f936352014-08-05 14:04:04 +10008123static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008124os_times_impl(PyObject *module)
8125/*[clinic end generated code: output=35f640503557d32a input=2bf9df3d6ab2e48b]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008126#ifdef MS_WINDOWS
Guido van Rossum14ed0b21994-09-29 09:50:09 +00008127{
Victor Stinner8c62be82010-05-06 00:08:46 +00008128 FILETIME create, exit, kernel, user;
8129 HANDLE hProc;
8130 hProc = GetCurrentProcess();
8131 GetProcessTimes(hProc, &create, &exit, &kernel, &user);
8132 /* The fields of a FILETIME structure are the hi and lo part
8133 of a 64-bit value expressed in 100 nanosecond units.
8134 1e7 is one second in such units; 1e-7 the inverse.
8135 429.4967296 is 2**32 / 1e7 or 2**32 * 1e-7.
8136 */
Larry Hastings605a62d2012-06-24 04:33:36 -07008137 return build_times_result(
Victor Stinner8c62be82010-05-06 00:08:46 +00008138 (double)(user.dwHighDateTime*429.4967296 +
8139 user.dwLowDateTime*1e-7),
8140 (double)(kernel.dwHighDateTime*429.4967296 +
8141 kernel.dwLowDateTime*1e-7),
8142 (double)0,
8143 (double)0,
8144 (double)0);
Guido van Rossum14ed0b21994-09-29 09:50:09 +00008145}
Larry Hastings2f936352014-08-05 14:04:04 +10008146#else /* MS_WINDOWS */
Antoine Pitrouf3923e92012-07-24 21:23:53 +02008147{
Larry Hastings2f936352014-08-05 14:04:04 +10008148
8149
Antoine Pitrouf3923e92012-07-24 21:23:53 +02008150 struct tms t;
8151 clock_t c;
8152 errno = 0;
8153 c = times(&t);
8154 if (c == (clock_t) -1)
8155 return posix_error();
8156 return build_times_result(
8157 (double)t.tms_utime / ticks_per_second,
8158 (double)t.tms_stime / ticks_per_second,
8159 (double)t.tms_cutime / ticks_per_second,
8160 (double)t.tms_cstime / ticks_per_second,
8161 (double)c / ticks_per_second);
8162}
Larry Hastings2f936352014-08-05 14:04:04 +10008163#endif /* MS_WINDOWS */
Antoine Pitrouf3923e92012-07-24 21:23:53 +02008164#endif /* HAVE_TIMES */
8165
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008166
Martin v. Löwis49ee14d2003-11-10 06:35:36 +00008167#ifdef HAVE_GETSID
Larry Hastings2f936352014-08-05 14:04:04 +10008168/*[clinic input]
8169os.getsid
8170
8171 pid: pid_t
8172 /
8173
8174Call the system call getsid(pid) and return the result.
8175[clinic start generated code]*/
8176
Larry Hastings2f936352014-08-05 14:04:04 +10008177static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008178os_getsid_impl(PyObject *module, pid_t pid)
8179/*[clinic end generated code: output=112deae56b306460 input=eeb2b923a30ce04e]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008180{
Victor Stinner8c62be82010-05-06 00:08:46 +00008181 int sid;
Victor Stinner8c62be82010-05-06 00:08:46 +00008182 sid = getsid(pid);
8183 if (sid < 0)
8184 return posix_error();
8185 return PyLong_FromLong((long)sid);
Martin v. Löwis49ee14d2003-11-10 06:35:36 +00008186}
8187#endif /* HAVE_GETSID */
8188
8189
Guido van Rossumb6775db1994-08-01 11:34:53 +00008190#ifdef HAVE_SETSID
Larry Hastings2f936352014-08-05 14:04:04 +10008191/*[clinic input]
8192os.setsid
8193
8194Call the system call setsid().
8195[clinic start generated code]*/
8196
Larry Hastings2f936352014-08-05 14:04:04 +10008197static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008198os_setsid_impl(PyObject *module)
8199/*[clinic end generated code: output=e2ddedd517086d77 input=5fff45858e2f0776]*/
Guido van Rossumc2670a01992-09-13 20:07:29 +00008200{
Victor Stinner8c62be82010-05-06 00:08:46 +00008201 if (setsid() < 0)
8202 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10008203 Py_RETURN_NONE;
Guido van Rossumc2670a01992-09-13 20:07:29 +00008204}
Guido van Rossumb6775db1994-08-01 11:34:53 +00008205#endif /* HAVE_SETSID */
Guido van Rossumc2670a01992-09-13 20:07:29 +00008206
Larry Hastings2f936352014-08-05 14:04:04 +10008207
Guido van Rossumb6775db1994-08-01 11:34:53 +00008208#ifdef HAVE_SETPGID
Larry Hastings2f936352014-08-05 14:04:04 +10008209/*[clinic input]
8210os.setpgid
8211
8212 pid: pid_t
8213 pgrp: pid_t
8214 /
8215
8216Call the system call setpgid(pid, pgrp).
8217[clinic start generated code]*/
8218
Larry Hastings2f936352014-08-05 14:04:04 +10008219static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008220os_setpgid_impl(PyObject *module, pid_t pid, pid_t pgrp)
8221/*[clinic end generated code: output=6461160319a43d6a input=fceb395eca572e1a]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008222{
Victor Stinner8c62be82010-05-06 00:08:46 +00008223 if (setpgid(pid, pgrp) < 0)
8224 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10008225 Py_RETURN_NONE;
Guido van Rossumc2670a01992-09-13 20:07:29 +00008226}
Guido van Rossumb6775db1994-08-01 11:34:53 +00008227#endif /* HAVE_SETPGID */
Guido van Rossumc2670a01992-09-13 20:07:29 +00008228
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008229
Guido van Rossumb6775db1994-08-01 11:34:53 +00008230#ifdef HAVE_TCGETPGRP
Larry Hastings2f936352014-08-05 14:04:04 +10008231/*[clinic input]
8232os.tcgetpgrp
8233
8234 fd: int
8235 /
8236
8237Return the process group associated with the terminal specified by fd.
8238[clinic start generated code]*/
8239
Larry Hastings2f936352014-08-05 14:04:04 +10008240static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008241os_tcgetpgrp_impl(PyObject *module, int fd)
8242/*[clinic end generated code: output=f865e88be86c272b input=7f6c18eac10ada86]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008243{
8244 pid_t pgid = tcgetpgrp(fd);
Victor Stinner8c62be82010-05-06 00:08:46 +00008245 if (pgid < 0)
8246 return posix_error();
8247 return PyLong_FromPid(pgid);
Guido van Rossum7066dd71992-09-17 17:54:56 +00008248}
Guido van Rossumb6775db1994-08-01 11:34:53 +00008249#endif /* HAVE_TCGETPGRP */
Guido van Rossum7066dd71992-09-17 17:54:56 +00008250
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008251
Guido van Rossumb6775db1994-08-01 11:34:53 +00008252#ifdef HAVE_TCSETPGRP
Larry Hastings2f936352014-08-05 14:04:04 +10008253/*[clinic input]
8254os.tcsetpgrp
8255
8256 fd: int
8257 pgid: pid_t
8258 /
8259
8260Set the process group associated with the terminal specified by fd.
8261[clinic start generated code]*/
8262
Larry Hastings2f936352014-08-05 14:04:04 +10008263static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008264os_tcsetpgrp_impl(PyObject *module, int fd, pid_t pgid)
8265/*[clinic end generated code: output=f1821a381b9daa39 input=5bdc997c6a619020]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008266{
Victor Stinner8c62be82010-05-06 00:08:46 +00008267 if (tcsetpgrp(fd, pgid) < 0)
8268 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10008269 Py_RETURN_NONE;
Guido van Rossum7066dd71992-09-17 17:54:56 +00008270}
Guido van Rossumb6775db1994-08-01 11:34:53 +00008271#endif /* HAVE_TCSETPGRP */
Guido van Rossum22db57e1992-04-05 14:25:30 +00008272
Guido van Rossum687dd131993-05-17 08:34:16 +00008273/* Functions acting on file descriptors */
8274
Victor Stinnerdaf45552013-08-28 00:53:59 +02008275#ifdef O_CLOEXEC
8276extern int _Py_open_cloexec_works;
8277#endif
8278
Larry Hastings2f936352014-08-05 14:04:04 +10008279
8280/*[clinic input]
8281os.open -> int
8282 path: path_t
8283 flags: int
8284 mode: int = 0o777
8285 *
8286 dir_fd: dir_fd(requires='openat') = None
8287
8288# "open(path, flags, mode=0o777, *, dir_fd=None)\n\n\
8289
8290Open a file for low level IO. Returns a file descriptor (integer).
8291
8292If dir_fd is not None, it should be a file descriptor open to a directory,
8293 and path should be relative; path will then be relative to that directory.
8294dir_fd may not be implemented on your platform.
8295 If it is unavailable, using it will raise a NotImplementedError.
8296[clinic start generated code]*/
8297
Larry Hastings2f936352014-08-05 14:04:04 +10008298static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008299os_open_impl(PyObject *module, path_t *path, int flags, int mode, int dir_fd)
8300/*[clinic end generated code: output=abc7227888c8bc73 input=ad8623b29acd2934]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008301{
8302 int fd;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008303 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10008304
Victor Stinnerdaf45552013-08-28 00:53:59 +02008305#ifdef O_CLOEXEC
8306 int *atomic_flag_works = &_Py_open_cloexec_works;
8307#elif !defined(MS_WINDOWS)
8308 int *atomic_flag_works = NULL;
8309#endif
Mark Hammondc2e85bd2002-10-03 05:10:39 +00008310
Victor Stinnerdaf45552013-08-28 00:53:59 +02008311#ifdef MS_WINDOWS
8312 flags |= O_NOINHERIT;
8313#elif defined(O_CLOEXEC)
8314 flags |= O_CLOEXEC;
8315#endif
8316
Steve Dowerb82e17e2019-05-23 08:45:22 -07008317 if (PySys_Audit("open", "OOi", path->object, Py_None, flags) < 0) {
8318 return -1;
8319 }
8320
Steve Dower8fc89802015-04-12 00:26:27 -04008321 _Py_BEGIN_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008322 do {
8323 Py_BEGIN_ALLOW_THREADS
Larry Hastings9cf065c2012-06-22 16:30:09 -07008324#ifdef MS_WINDOWS
Steve Dowercc16be82016-09-08 10:35:16 -07008325 fd = _wopen(path->wide, flags, mode);
Steve Dower6230aaf2016-09-09 09:03:15 -07008326#else
Larry Hastings9cf065c2012-06-22 16:30:09 -07008327#ifdef HAVE_OPENAT
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008328 if (dir_fd != DEFAULT_DIR_FD)
8329 fd = openat(dir_fd, path->narrow, flags, mode);
8330 else
Steve Dower6230aaf2016-09-09 09:03:15 -07008331#endif /* HAVE_OPENAT */
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008332 fd = open(path->narrow, flags, mode);
Steve Dower6230aaf2016-09-09 09:03:15 -07008333#endif /* !MS_WINDOWS */
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008334 Py_END_ALLOW_THREADS
8335 } while (fd < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Steve Dower8fc89802015-04-12 00:26:27 -04008336 _Py_END_SUPPRESS_IPH
Guido van Rossum687dd131993-05-17 08:34:16 +00008337
Victor Stinnerd3ffd322015-09-15 10:11:03 +02008338 if (fd < 0) {
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008339 if (!async_err)
8340 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, path->object);
Larry Hastings2f936352014-08-05 14:04:04 +10008341 return -1;
Larry Hastings9cf065c2012-06-22 16:30:09 -07008342 }
8343
Victor Stinnerdaf45552013-08-28 00:53:59 +02008344#ifndef MS_WINDOWS
8345 if (_Py_set_inheritable(fd, 0, atomic_flag_works) < 0) {
8346 close(fd);
Larry Hastings2f936352014-08-05 14:04:04 +10008347 return -1;
Victor Stinnerdaf45552013-08-28 00:53:59 +02008348 }
8349#endif
8350
Larry Hastings2f936352014-08-05 14:04:04 +10008351 return fd;
8352}
8353
8354
8355/*[clinic input]
8356os.close
8357
8358 fd: int
8359
8360Close a file descriptor.
8361[clinic start generated code]*/
8362
Barry Warsaw53699e91996-12-10 23:23:01 +00008363static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008364os_close_impl(PyObject *module, int fd)
8365/*[clinic end generated code: output=2fe4e93602822c14 input=2bc42451ca5c3223]*/
Guido van Rossum687dd131993-05-17 08:34:16 +00008366{
Larry Hastings2f936352014-08-05 14:04:04 +10008367 int res;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008368 /* We do not want to retry upon EINTR: see http://lwn.net/Articles/576478/
8369 * and http://linux.derkeiler.com/Mailing-Lists/Kernel/2005-09/3000.html
8370 * for more details.
8371 */
Victor Stinner8c62be82010-05-06 00:08:46 +00008372 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04008373 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00008374 res = close(fd);
Steve Dower8fc89802015-04-12 00:26:27 -04008375 _Py_END_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00008376 Py_END_ALLOW_THREADS
8377 if (res < 0)
8378 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10008379 Py_RETURN_NONE;
Guido van Rossum687dd131993-05-17 08:34:16 +00008380}
8381
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008382
Larry Hastings2f936352014-08-05 14:04:04 +10008383/*[clinic input]
8384os.closerange
8385
8386 fd_low: int
8387 fd_high: int
8388 /
8389
8390Closes all file descriptors in [fd_low, fd_high), ignoring errors.
8391[clinic start generated code]*/
8392
Larry Hastings2f936352014-08-05 14:04:04 +10008393static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008394os_closerange_impl(PyObject *module, int fd_low, int fd_high)
8395/*[clinic end generated code: output=0ce5c20fcda681c2 input=5855a3d053ebd4ec]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008396{
8397 int i;
Victor Stinner8c62be82010-05-06 00:08:46 +00008398 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04008399 _Py_BEGIN_SUPPRESS_IPH
Benjamin Peterson207116b2016-09-08 11:28:06 -07008400 for (i = Py_MAX(fd_low, 0); i < fd_high; i++)
Steve Dower940f33a2016-09-08 11:21:54 -07008401 close(i);
Steve Dower8fc89802015-04-12 00:26:27 -04008402 _Py_END_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00008403 Py_END_ALLOW_THREADS
8404 Py_RETURN_NONE;
Christian Heimesfdab48e2008-01-20 09:06:41 +00008405}
8406
8407
Larry Hastings2f936352014-08-05 14:04:04 +10008408/*[clinic input]
8409os.dup -> int
8410
8411 fd: int
8412 /
8413
8414Return a duplicate of a file descriptor.
8415[clinic start generated code]*/
8416
Larry Hastings2f936352014-08-05 14:04:04 +10008417static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008418os_dup_impl(PyObject *module, int fd)
8419/*[clinic end generated code: output=486f4860636b2a9f input=6f10f7ea97f7852a]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008420{
8421 return _Py_dup(fd);
Guido van Rossum687dd131993-05-17 08:34:16 +00008422}
8423
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008424
Larry Hastings2f936352014-08-05 14:04:04 +10008425/*[clinic input]
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008426os.dup2 -> int
Larry Hastings2f936352014-08-05 14:04:04 +10008427 fd: int
8428 fd2: int
8429 inheritable: bool=True
8430
8431Duplicate file descriptor.
8432[clinic start generated code]*/
8433
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008434static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008435os_dup2_impl(PyObject *module, int fd, int fd2, int inheritable)
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008436/*[clinic end generated code: output=bc059d34a73404d1 input=c3cddda8922b038d]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008437{
Stéphane Wirtel3d86e482018-01-30 07:04:36 +01008438 int res = 0;
Victor Stinnerdaf45552013-08-28 00:53:59 +02008439#if defined(HAVE_DUP3) && \
8440 !(defined(HAVE_FCNTL_H) && defined(F_DUP2FD_CLOEXEC))
8441 /* dup3() is available on Linux 2.6.27+ and glibc 2.9 */
Alexey Izbyshevb3caf382018-02-20 10:25:46 +03008442 static int dup3_works = -1;
Victor Stinnerdaf45552013-08-28 00:53:59 +02008443#endif
8444
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008445 if (fd < 0 || fd2 < 0) {
8446 posix_error();
8447 return -1;
8448 }
Victor Stinnerdaf45552013-08-28 00:53:59 +02008449
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008450 /* dup2() can fail with EINTR if the target FD is already open, because it
8451 * then has to be closed. See os_close_impl() for why we don't handle EINTR
8452 * upon close(), and therefore below.
8453 */
Victor Stinnerdaf45552013-08-28 00:53:59 +02008454#ifdef MS_WINDOWS
8455 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04008456 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00008457 res = dup2(fd, fd2);
Steve Dower8fc89802015-04-12 00:26:27 -04008458 _Py_END_SUPPRESS_IPH
Victor Stinnerdaf45552013-08-28 00:53:59 +02008459 Py_END_ALLOW_THREADS
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008460 if (res < 0) {
8461 posix_error();
8462 return -1;
8463 }
8464 res = fd2; // msvcrt dup2 returns 0 on success.
Victor Stinnerdaf45552013-08-28 00:53:59 +02008465
8466 /* Character files like console cannot be make non-inheritable */
8467 if (!inheritable && _Py_set_inheritable(fd2, 0, NULL) < 0) {
8468 close(fd2);
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008469 return -1;
Victor Stinnerdaf45552013-08-28 00:53:59 +02008470 }
8471
8472#elif defined(HAVE_FCNTL_H) && defined(F_DUP2FD_CLOEXEC)
8473 Py_BEGIN_ALLOW_THREADS
8474 if (!inheritable)
8475 res = fcntl(fd, F_DUP2FD_CLOEXEC, fd2);
8476 else
8477 res = dup2(fd, fd2);
8478 Py_END_ALLOW_THREADS
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008479 if (res < 0) {
8480 posix_error();
8481 return -1;
8482 }
Victor Stinnerdaf45552013-08-28 00:53:59 +02008483
8484#else
8485
8486#ifdef HAVE_DUP3
8487 if (!inheritable && dup3_works != 0) {
8488 Py_BEGIN_ALLOW_THREADS
8489 res = dup3(fd, fd2, O_CLOEXEC);
8490 Py_END_ALLOW_THREADS
8491 if (res < 0) {
8492 if (dup3_works == -1)
8493 dup3_works = (errno != ENOSYS);
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008494 if (dup3_works) {
8495 posix_error();
8496 return -1;
8497 }
Victor Stinnerdaf45552013-08-28 00:53:59 +02008498 }
8499 }
8500
8501 if (inheritable || dup3_works == 0)
8502 {
8503#endif
8504 Py_BEGIN_ALLOW_THREADS
8505 res = dup2(fd, fd2);
8506 Py_END_ALLOW_THREADS
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008507 if (res < 0) {
8508 posix_error();
8509 return -1;
8510 }
Victor Stinnerdaf45552013-08-28 00:53:59 +02008511
8512 if (!inheritable && _Py_set_inheritable(fd2, 0, NULL) < 0) {
8513 close(fd2);
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008514 return -1;
Victor Stinnerdaf45552013-08-28 00:53:59 +02008515 }
8516#ifdef HAVE_DUP3
8517 }
8518#endif
8519
8520#endif
8521
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008522 return res;
Guido van Rossum687dd131993-05-17 08:34:16 +00008523}
8524
Larry Hastings2f936352014-08-05 14:04:04 +10008525
Ross Lagerwall7807c352011-03-17 20:20:30 +02008526#ifdef HAVE_LOCKF
Larry Hastings2f936352014-08-05 14:04:04 +10008527/*[clinic input]
8528os.lockf
8529
8530 fd: int
8531 An open file descriptor.
8532 command: int
8533 One of F_LOCK, F_TLOCK, F_ULOCK or F_TEST.
8534 length: Py_off_t
8535 The number of bytes to lock, starting at the current position.
8536 /
8537
8538Apply, test or remove a POSIX lock on an open file descriptor.
8539
8540[clinic start generated code]*/
8541
Larry Hastings2f936352014-08-05 14:04:04 +10008542static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008543os_lockf_impl(PyObject *module, int fd, int command, Py_off_t length)
8544/*[clinic end generated code: output=af7051f3e7c29651 input=65da41d2106e9b79]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008545{
8546 int res;
Ross Lagerwall7807c352011-03-17 20:20:30 +02008547
8548 Py_BEGIN_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10008549 res = lockf(fd, command, length);
Ross Lagerwall7807c352011-03-17 20:20:30 +02008550 Py_END_ALLOW_THREADS
8551
8552 if (res < 0)
8553 return posix_error();
8554
8555 Py_RETURN_NONE;
8556}
Larry Hastings2f936352014-08-05 14:04:04 +10008557#endif /* HAVE_LOCKF */
Ross Lagerwall7807c352011-03-17 20:20:30 +02008558
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008559
Larry Hastings2f936352014-08-05 14:04:04 +10008560/*[clinic input]
8561os.lseek -> Py_off_t
8562
8563 fd: int
8564 position: Py_off_t
8565 how: int
8566 /
8567
8568Set the position of a file descriptor. Return the new position.
8569
8570Return the new cursor position in number of bytes
8571relative to the beginning of the file.
8572[clinic start generated code]*/
8573
Larry Hastings2f936352014-08-05 14:04:04 +10008574static Py_off_t
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008575os_lseek_impl(PyObject *module, int fd, Py_off_t position, int how)
8576/*[clinic end generated code: output=971e1efb6b30bd2f input=902654ad3f96a6d3]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008577{
8578 Py_off_t result;
8579
Guido van Rossum687dd131993-05-17 08:34:16 +00008580#ifdef SEEK_SET
Victor Stinner8c62be82010-05-06 00:08:46 +00008581 /* Turn 0, 1, 2 into SEEK_{SET,CUR,END} */
8582 switch (how) {
Larry Hastings2f936352014-08-05 14:04:04 +10008583 case 0: how = SEEK_SET; break;
8584 case 1: how = SEEK_CUR; break;
8585 case 2: how = SEEK_END; break;
Victor Stinner8c62be82010-05-06 00:08:46 +00008586 }
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +00008587#endif /* SEEK_END */
Guido van Rossum94f6f721999-01-06 18:42:14 +00008588
Victor Stinner8c62be82010-05-06 00:08:46 +00008589 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04008590 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner14b9b112013-06-25 00:37:25 +02008591#ifdef MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +10008592 result = _lseeki64(fd, position, how);
Fred Drake699f3522000-06-29 21:12:41 +00008593#else
Larry Hastings2f936352014-08-05 14:04:04 +10008594 result = lseek(fd, position, how);
Fred Drake699f3522000-06-29 21:12:41 +00008595#endif
Steve Dower8fc89802015-04-12 00:26:27 -04008596 _Py_END_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00008597 Py_END_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10008598 if (result < 0)
8599 posix_error();
Guido van Rossum94f6f721999-01-06 18:42:14 +00008600
Larry Hastings2f936352014-08-05 14:04:04 +10008601 return result;
Guido van Rossum687dd131993-05-17 08:34:16 +00008602}
8603
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008604
Larry Hastings2f936352014-08-05 14:04:04 +10008605/*[clinic input]
8606os.read
8607 fd: int
8608 length: Py_ssize_t
8609 /
8610
8611Read from a file descriptor. Returns a bytes object.
8612[clinic start generated code]*/
8613
Larry Hastings2f936352014-08-05 14:04:04 +10008614static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008615os_read_impl(PyObject *module, int fd, Py_ssize_t length)
8616/*[clinic end generated code: output=dafbe9a5cddb987b input=1df2eaa27c0bf1d3]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008617{
Victor Stinner8c62be82010-05-06 00:08:46 +00008618 Py_ssize_t n;
8619 PyObject *buffer;
Larry Hastings2f936352014-08-05 14:04:04 +10008620
8621 if (length < 0) {
Victor Stinner8c62be82010-05-06 00:08:46 +00008622 errno = EINVAL;
8623 return posix_error();
8624 }
Larry Hastings2f936352014-08-05 14:04:04 +10008625
Victor Stinner9a0d7a72018-11-22 15:03:40 +01008626 length = Py_MIN(length, _PY_READ_MAX);
Larry Hastings2f936352014-08-05 14:04:04 +10008627
8628 buffer = PyBytes_FromStringAndSize((char *)NULL, length);
Victor Stinner8c62be82010-05-06 00:08:46 +00008629 if (buffer == NULL)
8630 return NULL;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008631
Victor Stinner66aab0c2015-03-19 22:53:20 +01008632 n = _Py_read(fd, PyBytes_AS_STRING(buffer), length);
8633 if (n == -1) {
Victor Stinner8c62be82010-05-06 00:08:46 +00008634 Py_DECREF(buffer);
Victor Stinner66aab0c2015-03-19 22:53:20 +01008635 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00008636 }
Larry Hastings2f936352014-08-05 14:04:04 +10008637
8638 if (n != length)
Victor Stinner8c62be82010-05-06 00:08:46 +00008639 _PyBytes_Resize(&buffer, n);
Larry Hastings2f936352014-08-05 14:04:04 +10008640
Victor Stinner8c62be82010-05-06 00:08:46 +00008641 return buffer;
Guido van Rossum687dd131993-05-17 08:34:16 +00008642}
8643
Ross Lagerwall7807c352011-03-17 20:20:30 +02008644#if (defined(HAVE_SENDFILE) && (defined(__FreeBSD__) || defined(__DragonFly__) \
Serhiy Storchaka9d572732018-07-31 10:24:54 +03008645 || defined(__APPLE__))) \
8646 || defined(HAVE_READV) || defined(HAVE_PREADV) || defined (HAVE_PREADV2) \
8647 || defined(HAVE_WRITEV) || defined(HAVE_PWRITEV) || defined (HAVE_PWRITEV2)
8648static int
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03008649iov_setup(struct iovec **iov, Py_buffer **buf, PyObject *seq, Py_ssize_t cnt, int type)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008650{
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03008651 Py_ssize_t i, j;
Giampaolo Rodolàacdad9a2011-03-03 16:10:51 +00008652
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008653 *iov = PyMem_New(struct iovec, cnt);
8654 if (*iov == NULL) {
8655 PyErr_NoMemory();
Victor Stinner57ddf782014-01-08 15:21:28 +01008656 return -1;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008657 }
Giampaolo Rodolàacdad9a2011-03-03 16:10:51 +00008658
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008659 *buf = PyMem_New(Py_buffer, cnt);
8660 if (*buf == NULL) {
8661 PyMem_Del(*iov);
8662 PyErr_NoMemory();
Victor Stinner57ddf782014-01-08 15:21:28 +01008663 return -1;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008664 }
8665
8666 for (i = 0; i < cnt; i++) {
Ross Lagerwall9ad63e02011-03-19 09:11:14 +02008667 PyObject *item = PySequence_GetItem(seq, i);
8668 if (item == NULL)
8669 goto fail;
8670 if (PyObject_GetBuffer(item, &(*buf)[i], type) == -1) {
8671 Py_DECREF(item);
8672 goto fail;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008673 }
Ross Lagerwall9ad63e02011-03-19 09:11:14 +02008674 Py_DECREF(item);
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008675 (*iov)[i].iov_base = (*buf)[i].buf;
Serhiy Storchaka9d572732018-07-31 10:24:54 +03008676 (*iov)[i].iov_len = (*buf)[i].len;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008677 }
Serhiy Storchaka9d572732018-07-31 10:24:54 +03008678 return 0;
Ross Lagerwall9ad63e02011-03-19 09:11:14 +02008679
8680fail:
8681 PyMem_Del(*iov);
8682 for (j = 0; j < i; j++) {
8683 PyBuffer_Release(&(*buf)[j]);
8684 }
8685 PyMem_Del(*buf);
Victor Stinner57ddf782014-01-08 15:21:28 +01008686 return -1;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008687}
8688
8689static void
8690iov_cleanup(struct iovec *iov, Py_buffer *buf, int cnt)
8691{
8692 int i;
8693 PyMem_Del(iov);
8694 for (i = 0; i < cnt; i++) {
8695 PyBuffer_Release(&buf[i]);
8696 }
8697 PyMem_Del(buf);
8698}
8699#endif
8700
Larry Hastings2f936352014-08-05 14:04:04 +10008701
Ross Lagerwall7807c352011-03-17 20:20:30 +02008702#ifdef HAVE_READV
Larry Hastings2f936352014-08-05 14:04:04 +10008703/*[clinic input]
8704os.readv -> Py_ssize_t
8705
8706 fd: int
8707 buffers: object
8708 /
8709
8710Read from a file descriptor fd into an iterable of buffers.
8711
8712The buffers should be mutable buffers accepting bytes.
8713readv will transfer data into each buffer until it is full
8714and then move on to the next buffer in the sequence to hold
8715the rest of the data.
8716
8717readv returns the total number of bytes read,
8718which may be less than the total capacity of all the buffers.
8719[clinic start generated code]*/
8720
Larry Hastings2f936352014-08-05 14:04:04 +10008721static Py_ssize_t
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008722os_readv_impl(PyObject *module, int fd, PyObject *buffers)
8723/*[clinic end generated code: output=792da062d3fcebdb input=e679eb5dbfa0357d]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008724{
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03008725 Py_ssize_t cnt, n;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008726 int async_err = 0;
Ross Lagerwall7807c352011-03-17 20:20:30 +02008727 struct iovec *iov;
8728 Py_buffer *buf;
8729
Larry Hastings2f936352014-08-05 14:04:04 +10008730 if (!PySequence_Check(buffers)) {
Ross Lagerwall7807c352011-03-17 20:20:30 +02008731 PyErr_SetString(PyExc_TypeError,
8732 "readv() arg 2 must be a sequence");
Larry Hastings2f936352014-08-05 14:04:04 +10008733 return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +02008734 }
Ross Lagerwall7807c352011-03-17 20:20:30 +02008735
Larry Hastings2f936352014-08-05 14:04:04 +10008736 cnt = PySequence_Size(buffers);
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03008737 if (cnt < 0)
8738 return -1;
Larry Hastings2f936352014-08-05 14:04:04 +10008739
8740 if (iov_setup(&iov, &buf, buffers, cnt, PyBUF_WRITABLE) < 0)
8741 return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +02008742
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008743 do {
8744 Py_BEGIN_ALLOW_THREADS
8745 n = readv(fd, iov, cnt);
8746 Py_END_ALLOW_THREADS
8747 } while (n < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Ross Lagerwall7807c352011-03-17 20:20:30 +02008748
8749 iov_cleanup(iov, buf, cnt);
Larry Hastings2f936352014-08-05 14:04:04 +10008750 if (n < 0) {
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008751 if (!async_err)
8752 posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10008753 return -1;
8754 }
Victor Stinner57ddf782014-01-08 15:21:28 +01008755
Larry Hastings2f936352014-08-05 14:04:04 +10008756 return n;
Ross Lagerwall7807c352011-03-17 20:20:30 +02008757}
Larry Hastings2f936352014-08-05 14:04:04 +10008758#endif /* HAVE_READV */
8759
Ross Lagerwall7807c352011-03-17 20:20:30 +02008760
8761#ifdef HAVE_PREAD
Larry Hastings2f936352014-08-05 14:04:04 +10008762/*[clinic input]
8763# TODO length should be size_t! but Python doesn't support parsing size_t yet.
8764os.pread
8765
8766 fd: int
8767 length: int
8768 offset: Py_off_t
8769 /
8770
8771Read a number of bytes from a file descriptor starting at a particular offset.
8772
8773Read length bytes from file descriptor fd, starting at offset bytes from
8774the beginning of the file. The file offset remains unchanged.
8775[clinic start generated code]*/
8776
Larry Hastings2f936352014-08-05 14:04:04 +10008777static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008778os_pread_impl(PyObject *module, int fd, int length, Py_off_t offset)
8779/*[clinic end generated code: output=435b29ee32b54a78 input=084948dcbaa35d4c]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008780{
Ross Lagerwall7807c352011-03-17 20:20:30 +02008781 Py_ssize_t n;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008782 int async_err = 0;
Ross Lagerwall7807c352011-03-17 20:20:30 +02008783 PyObject *buffer;
Ross Lagerwall7807c352011-03-17 20:20:30 +02008784
Larry Hastings2f936352014-08-05 14:04:04 +10008785 if (length < 0) {
Ross Lagerwall7807c352011-03-17 20:20:30 +02008786 errno = EINVAL;
8787 return posix_error();
8788 }
Larry Hastings2f936352014-08-05 14:04:04 +10008789 buffer = PyBytes_FromStringAndSize((char *)NULL, length);
Ross Lagerwall7807c352011-03-17 20:20:30 +02008790 if (buffer == NULL)
8791 return NULL;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008792
8793 do {
8794 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04008795 _Py_BEGIN_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008796 n = pread(fd, PyBytes_AS_STRING(buffer), length, offset);
Steve Dower8fc89802015-04-12 00:26:27 -04008797 _Py_END_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008798 Py_END_ALLOW_THREADS
8799 } while (n < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
8800
Ross Lagerwall7807c352011-03-17 20:20:30 +02008801 if (n < 0) {
8802 Py_DECREF(buffer);
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008803 return (!async_err) ? posix_error() : NULL;
Ross Lagerwall7807c352011-03-17 20:20:30 +02008804 }
Larry Hastings2f936352014-08-05 14:04:04 +10008805 if (n != length)
Ross Lagerwall7807c352011-03-17 20:20:30 +02008806 _PyBytes_Resize(&buffer, n);
8807 return buffer;
8808}
Larry Hastings2f936352014-08-05 14:04:04 +10008809#endif /* HAVE_PREAD */
Ross Lagerwall7807c352011-03-17 20:20:30 +02008810
Pablo Galindo4defba32018-01-27 16:16:37 +00008811#if defined(HAVE_PREADV) || defined (HAVE_PREADV2)
8812/*[clinic input]
8813os.preadv -> Py_ssize_t
8814
8815 fd: int
8816 buffers: object
8817 offset: Py_off_t
8818 flags: int = 0
8819 /
8820
8821Reads from a file descriptor into a number of mutable bytes-like objects.
8822
8823Combines the functionality of readv() and pread(). As readv(), it will
8824transfer data into each buffer until it is full and then move on to the next
8825buffer in the sequence to hold the rest of the data. Its fourth argument,
8826specifies the file offset at which the input operation is to be performed. It
8827will return the total number of bytes read (which can be less than the total
8828capacity of all the objects).
8829
8830The flags argument contains a bitwise OR of zero or more of the following flags:
8831
8832- RWF_HIPRI
8833- RWF_NOWAIT
8834
8835Using non-zero flags requires Linux 4.6 or newer.
8836[clinic start generated code]*/
8837
8838static Py_ssize_t
8839os_preadv_impl(PyObject *module, int fd, PyObject *buffers, Py_off_t offset,
8840 int flags)
8841/*[clinic end generated code: output=26fc9c6e58e7ada5 input=4173919dc1f7ed99]*/
8842{
8843 Py_ssize_t cnt, n;
8844 int async_err = 0;
8845 struct iovec *iov;
8846 Py_buffer *buf;
8847
8848 if (!PySequence_Check(buffers)) {
8849 PyErr_SetString(PyExc_TypeError,
8850 "preadv2() arg 2 must be a sequence");
8851 return -1;
8852 }
8853
8854 cnt = PySequence_Size(buffers);
8855 if (cnt < 0) {
8856 return -1;
8857 }
8858
8859#ifndef HAVE_PREADV2
8860 if(flags != 0) {
8861 argument_unavailable_error("preadv2", "flags");
8862 return -1;
8863 }
8864#endif
8865
8866 if (iov_setup(&iov, &buf, buffers, cnt, PyBUF_WRITABLE) < 0) {
8867 return -1;
8868 }
8869#ifdef HAVE_PREADV2
8870 do {
8871 Py_BEGIN_ALLOW_THREADS
8872 _Py_BEGIN_SUPPRESS_IPH
8873 n = preadv2(fd, iov, cnt, offset, flags);
8874 _Py_END_SUPPRESS_IPH
8875 Py_END_ALLOW_THREADS
8876 } while (n < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
8877#else
8878 do {
8879 Py_BEGIN_ALLOW_THREADS
8880 _Py_BEGIN_SUPPRESS_IPH
8881 n = preadv(fd, iov, cnt, offset);
8882 _Py_END_SUPPRESS_IPH
8883 Py_END_ALLOW_THREADS
8884 } while (n < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
8885#endif
8886
8887 iov_cleanup(iov, buf, cnt);
8888 if (n < 0) {
8889 if (!async_err) {
8890 posix_error();
8891 }
8892 return -1;
8893 }
8894
8895 return n;
8896}
8897#endif /* HAVE_PREADV */
8898
Larry Hastings2f936352014-08-05 14:04:04 +10008899
8900/*[clinic input]
8901os.write -> Py_ssize_t
8902
8903 fd: int
8904 data: Py_buffer
8905 /
8906
8907Write a bytes object to a file descriptor.
8908[clinic start generated code]*/
8909
Larry Hastings2f936352014-08-05 14:04:04 +10008910static Py_ssize_t
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008911os_write_impl(PyObject *module, int fd, Py_buffer *data)
8912/*[clinic end generated code: output=e4ef5bc904b58ef9 input=3207e28963234f3c]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008913{
Victor Stinner66aab0c2015-03-19 22:53:20 +01008914 return _Py_write(fd, data->buf, data->len);
Ross Lagerwall7807c352011-03-17 20:20:30 +02008915}
8916
8917#ifdef HAVE_SENDFILE
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008918PyDoc_STRVAR(posix_sendfile__doc__,
Martin Panterbf19d162015-09-09 01:01:13 +00008919"sendfile(out, in, offset, count) -> byteswritten\n\
Martin Panter94994132015-09-09 05:29:24 +00008920sendfile(out, in, offset, count[, headers][, trailers], flags=0)\n\
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008921 -> byteswritten\n\
Martin Panterbf19d162015-09-09 01:01:13 +00008922Copy count bytes from file descriptor in to file descriptor out.");
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008923
Larry Hastings2f936352014-08-05 14:04:04 +10008924/* AC 3.5: don't bother converting, has optional group*/
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008925static PyObject *
8926posix_sendfile(PyObject *self, PyObject *args, PyObject *kwdict)
8927{
8928 int in, out;
8929 Py_ssize_t ret;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008930 int async_err = 0;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008931 off_t offset;
8932
8933#if defined(__FreeBSD__) || defined(__DragonFly__) || defined(__APPLE__)
8934#ifndef __APPLE__
8935 Py_ssize_t len;
8936#endif
8937 PyObject *headers = NULL, *trailers = NULL;
8938 Py_buffer *hbuf, *tbuf;
8939 off_t sbytes;
8940 struct sf_hdtr sf;
8941 int flags = 0;
Martin Panterbf19d162015-09-09 01:01:13 +00008942 /* Beware that "in" clashes with Python's own "in" operator keyword */
Benjamin Petersond8a43b42011-02-26 21:35:16 +00008943 static char *keywords[] = {"out", "in",
8944 "offset", "count",
8945 "headers", "trailers", "flags", NULL};
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008946
Victor Stinner6ce0dbf2013-07-07 16:32:36 +02008947 sf.headers = NULL;
8948 sf.trailers = NULL;
8949
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008950#ifdef __APPLE__
8951 if (!PyArg_ParseTupleAndKeywords(args, kwdict, "iiO&O&|OOi:sendfile",
Larry Hastings2f936352014-08-05 14:04:04 +10008952 keywords, &out, &in, Py_off_t_converter, &offset, Py_off_t_converter, &sbytes,
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008953#else
8954 if (!PyArg_ParseTupleAndKeywords(args, kwdict, "iiO&n|OOi:sendfile",
Larry Hastings2f936352014-08-05 14:04:04 +10008955 keywords, &out, &in, Py_off_t_converter, &offset, &len,
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008956#endif
8957 &headers, &trailers, &flags))
8958 return NULL;
8959 if (headers != NULL) {
8960 if (!PySequence_Check(headers)) {
8961 PyErr_SetString(PyExc_TypeError,
Martin Panter94994132015-09-09 05:29:24 +00008962 "sendfile() headers must be a sequence");
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008963 return NULL;
8964 } else {
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03008965 Py_ssize_t i = PySequence_Size(headers);
8966 if (i < 0)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008967 return NULL;
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03008968 if (i > INT_MAX) {
8969 PyErr_SetString(PyExc_OverflowError,
8970 "sendfile() header is too large");
8971 return NULL;
8972 }
8973 if (i > 0) {
8974 sf.hdr_cnt = (int)i;
Serhiy Storchaka9d572732018-07-31 10:24:54 +03008975 if (iov_setup(&(sf.headers), &hbuf,
8976 headers, sf.hdr_cnt, PyBUF_SIMPLE) < 0)
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03008977 return NULL;
Giampaolo Rodolàacdad9a2011-03-03 16:10:51 +00008978#ifdef __APPLE__
Serhiy Storchaka9d572732018-07-31 10:24:54 +03008979 for (i = 0; i < sf.hdr_cnt; i++) {
8980 Py_ssize_t blen = sf.headers[i].iov_len;
8981# define OFF_T_MAX 0x7fffffffffffffff
8982 if (sbytes >= OFF_T_MAX - blen) {
8983 PyErr_SetString(PyExc_OverflowError,
8984 "sendfile() header is too large");
8985 return NULL;
8986 }
8987 sbytes += blen;
8988 }
Giampaolo Rodolàacdad9a2011-03-03 16:10:51 +00008989#endif
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03008990 }
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008991 }
8992 }
8993 if (trailers != NULL) {
8994 if (!PySequence_Check(trailers)) {
8995 PyErr_SetString(PyExc_TypeError,
Martin Panter94994132015-09-09 05:29:24 +00008996 "sendfile() trailers must be a sequence");
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008997 return NULL;
8998 } else {
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03008999 Py_ssize_t i = PySequence_Size(trailers);
9000 if (i < 0)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009001 return NULL;
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009002 if (i > INT_MAX) {
9003 PyErr_SetString(PyExc_OverflowError,
9004 "sendfile() trailer is too large");
9005 return NULL;
9006 }
9007 if (i > 0) {
9008 sf.trl_cnt = (int)i;
Serhiy Storchaka9d572732018-07-31 10:24:54 +03009009 if (iov_setup(&(sf.trailers), &tbuf,
9010 trailers, sf.trl_cnt, PyBUF_SIMPLE) < 0)
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009011 return NULL;
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009012 }
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009013 }
9014 }
9015
Steve Dower8fc89802015-04-12 00:26:27 -04009016 _Py_BEGIN_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009017 do {
9018 Py_BEGIN_ALLOW_THREADS
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009019#ifdef __APPLE__
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009020 ret = sendfile(in, out, offset, &sbytes, &sf, flags);
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009021#else
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009022 ret = sendfile(in, out, offset, len, &sf, &sbytes, flags);
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009023#endif
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009024 Py_END_ALLOW_THREADS
9025 } while (ret < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Steve Dower8fc89802015-04-12 00:26:27 -04009026 _Py_END_SUPPRESS_IPH
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009027
9028 if (sf.headers != NULL)
9029 iov_cleanup(sf.headers, hbuf, sf.hdr_cnt);
9030 if (sf.trailers != NULL)
9031 iov_cleanup(sf.trailers, tbuf, sf.trl_cnt);
9032
9033 if (ret < 0) {
9034 if ((errno == EAGAIN) || (errno == EBUSY)) {
9035 if (sbytes != 0) {
9036 // some data has been sent
9037 goto done;
9038 }
9039 else {
9040 // no data has been sent; upper application is supposed
9041 // to retry on EAGAIN or EBUSY
9042 return posix_error();
9043 }
9044 }
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009045 return (!async_err) ? posix_error() : NULL;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009046 }
9047 goto done;
9048
9049done:
9050 #if !defined(HAVE_LARGEFILE_SUPPORT)
9051 return Py_BuildValue("l", sbytes);
9052 #else
9053 return Py_BuildValue("L", sbytes);
9054 #endif
9055
9056#else
9057 Py_ssize_t count;
9058 PyObject *offobj;
9059 static char *keywords[] = {"out", "in",
9060 "offset", "count", NULL};
9061 if (!PyArg_ParseTupleAndKeywords(args, kwdict, "iiOn:sendfile",
9062 keywords, &out, &in, &offobj, &count))
9063 return NULL;
Benjamin Peterson840ef8f2016-09-07 14:45:10 -07009064#ifdef __linux__
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009065 if (offobj == Py_None) {
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009066 do {
9067 Py_BEGIN_ALLOW_THREADS
9068 ret = sendfile(out, in, NULL, count);
9069 Py_END_ALLOW_THREADS
9070 } while (ret < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009071 if (ret < 0)
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009072 return (!async_err) ? posix_error() : NULL;
Giampaolo Rodola'ff1a7352011-04-19 09:47:16 +02009073 return Py_BuildValue("n", ret);
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009074 }
9075#endif
Larry Hastings2f936352014-08-05 14:04:04 +10009076 if (!Py_off_t_converter(offobj, &offset))
Antoine Pitroudcc20b82011-02-26 13:38:35 +00009077 return NULL;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009078
9079 do {
9080 Py_BEGIN_ALLOW_THREADS
9081 ret = sendfile(out, in, &offset, count);
9082 Py_END_ALLOW_THREADS
9083 } while (ret < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009084 if (ret < 0)
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009085 return (!async_err) ? posix_error() : NULL;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009086 return Py_BuildValue("n", ret);
9087#endif
9088}
Larry Hastings2f936352014-08-05 14:04:04 +10009089#endif /* HAVE_SENDFILE */
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00009090
Larry Hastings2f936352014-08-05 14:04:04 +10009091
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +02009092#if defined(__APPLE__)
9093/*[clinic input]
9094os._fcopyfile
9095
9096 infd: int
9097 outfd: int
9098 flags: int
9099 /
9100
Giampaolo Rodolac7f02a92018-06-19 08:27:29 -07009101Efficiently copy content or metadata of 2 regular file descriptors (macOS).
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +02009102[clinic start generated code]*/
9103
9104static PyObject *
9105os__fcopyfile_impl(PyObject *module, int infd, int outfd, int flags)
Giampaolo Rodolac7f02a92018-06-19 08:27:29 -07009106/*[clinic end generated code: output=8e8885c721ec38e3 input=69e0770e600cb44f]*/
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +02009107{
9108 int ret;
9109
9110 Py_BEGIN_ALLOW_THREADS
9111 ret = fcopyfile(infd, outfd, NULL, flags);
9112 Py_END_ALLOW_THREADS
9113 if (ret < 0)
9114 return posix_error();
9115 Py_RETURN_NONE;
9116}
9117#endif
9118
9119
Larry Hastings2f936352014-08-05 14:04:04 +10009120/*[clinic input]
9121os.fstat
9122
9123 fd : int
9124
9125Perform a stat system call on the given file descriptor.
9126
9127Like stat(), but for an open file descriptor.
9128Equivalent to os.stat(fd).
9129[clinic start generated code]*/
9130
Larry Hastings2f936352014-08-05 14:04:04 +10009131static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009132os_fstat_impl(PyObject *module, int fd)
9133/*[clinic end generated code: output=efc038cb5f654492 input=27e0e0ebbe5600c9]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009134{
Victor Stinner8c62be82010-05-06 00:08:46 +00009135 STRUCT_STAT st;
9136 int res;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009137 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10009138
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009139 do {
9140 Py_BEGIN_ALLOW_THREADS
9141 res = FSTAT(fd, &st);
9142 Py_END_ALLOW_THREADS
9143 } while (res != 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Victor Stinner8c62be82010-05-06 00:08:46 +00009144 if (res != 0) {
Martin v. Löwis14694662006-02-03 12:54:16 +00009145#ifdef MS_WINDOWS
Victor Stinnerb024e842012-10-31 22:24:06 +01009146 return PyErr_SetFromWindowsErr(0);
Martin v. Löwis14694662006-02-03 12:54:16 +00009147#else
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009148 return (!async_err) ? posix_error() : NULL;
Martin v. Löwis14694662006-02-03 12:54:16 +00009149#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00009150 }
Tim Peters5aa91602002-01-30 05:46:57 +00009151
Victor Stinner4195b5c2012-02-08 23:03:19 +01009152 return _pystat_fromstructstat(&st);
Guido van Rossum687dd131993-05-17 08:34:16 +00009153}
9154
Larry Hastings2f936352014-08-05 14:04:04 +10009155
9156/*[clinic input]
9157os.isatty -> bool
9158 fd: int
9159 /
9160
9161Return True if the fd is connected to a terminal.
9162
9163Return True if the file descriptor is an open file descriptor
9164connected to the slave end of a terminal.
9165[clinic start generated code]*/
9166
Larry Hastings2f936352014-08-05 14:04:04 +10009167static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009168os_isatty_impl(PyObject *module, int fd)
9169/*[clinic end generated code: output=6a48c8b4e644ca00 input=08ce94aa1eaf7b5e]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009170{
Steve Dower8fc89802015-04-12 00:26:27 -04009171 int return_value;
Steve Dower8fc89802015-04-12 00:26:27 -04009172 _Py_BEGIN_SUPPRESS_IPH
9173 return_value = isatty(fd);
9174 _Py_END_SUPPRESS_IPH
9175 return return_value;
Larry Hastings2f936352014-08-05 14:04:04 +10009176}
9177
9178
Guido van Rossuma4916fa1996-05-23 22:58:55 +00009179#ifdef HAVE_PIPE
Larry Hastings2f936352014-08-05 14:04:04 +10009180/*[clinic input]
9181os.pipe
9182
9183Create a pipe.
9184
9185Returns a tuple of two file descriptors:
9186 (read_fd, write_fd)
9187[clinic start generated code]*/
9188
Larry Hastings2f936352014-08-05 14:04:04 +10009189static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009190os_pipe_impl(PyObject *module)
9191/*[clinic end generated code: output=ff9b76255793b440 input=02535e8c8fa6c4d4]*/
Guido van Rossum687dd131993-05-17 08:34:16 +00009192{
Victor Stinner8c62be82010-05-06 00:08:46 +00009193 int fds[2];
Victor Stinnerdaf45552013-08-28 00:53:59 +02009194#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +00009195 HANDLE read, write;
Victor Stinnerdaf45552013-08-28 00:53:59 +02009196 SECURITY_ATTRIBUTES attr;
Victor Stinner8c62be82010-05-06 00:08:46 +00009197 BOOL ok;
Victor Stinnerdaf45552013-08-28 00:53:59 +02009198#else
9199 int res;
9200#endif
9201
9202#ifdef MS_WINDOWS
9203 attr.nLength = sizeof(attr);
9204 attr.lpSecurityDescriptor = NULL;
9205 attr.bInheritHandle = FALSE;
9206
9207 Py_BEGIN_ALLOW_THREADS
Steve Dowerc3630612016-11-19 18:41:16 -08009208 _Py_BEGIN_SUPPRESS_IPH
Victor Stinnerdaf45552013-08-28 00:53:59 +02009209 ok = CreatePipe(&read, &write, &attr, 0);
9210 if (ok) {
Benjamin Petersonca470632016-09-06 13:47:26 -07009211 fds[0] = _open_osfhandle((intptr_t)read, _O_RDONLY);
9212 fds[1] = _open_osfhandle((intptr_t)write, _O_WRONLY);
Victor Stinnerdaf45552013-08-28 00:53:59 +02009213 if (fds[0] == -1 || fds[1] == -1) {
9214 CloseHandle(read);
9215 CloseHandle(write);
9216 ok = 0;
9217 }
9218 }
Steve Dowerc3630612016-11-19 18:41:16 -08009219 _Py_END_SUPPRESS_IPH
Victor Stinnerdaf45552013-08-28 00:53:59 +02009220 Py_END_ALLOW_THREADS
9221
Victor Stinner8c62be82010-05-06 00:08:46 +00009222 if (!ok)
Victor Stinnerb024e842012-10-31 22:24:06 +01009223 return PyErr_SetFromWindowsErr(0);
Victor Stinnerdaf45552013-08-28 00:53:59 +02009224#else
9225
9226#ifdef HAVE_PIPE2
9227 Py_BEGIN_ALLOW_THREADS
9228 res = pipe2(fds, O_CLOEXEC);
9229 Py_END_ALLOW_THREADS
9230
9231 if (res != 0 && errno == ENOSYS)
9232 {
9233#endif
9234 Py_BEGIN_ALLOW_THREADS
9235 res = pipe(fds);
9236 Py_END_ALLOW_THREADS
9237
9238 if (res == 0) {
9239 if (_Py_set_inheritable(fds[0], 0, NULL) < 0) {
9240 close(fds[0]);
9241 close(fds[1]);
9242 return NULL;
9243 }
9244 if (_Py_set_inheritable(fds[1], 0, NULL) < 0) {
9245 close(fds[0]);
9246 close(fds[1]);
9247 return NULL;
9248 }
9249 }
9250#ifdef HAVE_PIPE2
9251 }
9252#endif
9253
9254 if (res != 0)
9255 return PyErr_SetFromErrno(PyExc_OSError);
9256#endif /* !MS_WINDOWS */
9257 return Py_BuildValue("(ii)", fds[0], fds[1]);
Guido van Rossum687dd131993-05-17 08:34:16 +00009258}
Guido van Rossuma4916fa1996-05-23 22:58:55 +00009259#endif /* HAVE_PIPE */
9260
Larry Hastings2f936352014-08-05 14:04:04 +10009261
Charles-François Natalidaafdd52011-05-29 20:07:40 +02009262#ifdef HAVE_PIPE2
Larry Hastings2f936352014-08-05 14:04:04 +10009263/*[clinic input]
9264os.pipe2
9265
9266 flags: int
9267 /
9268
9269Create a pipe with flags set atomically.
9270
9271Returns a tuple of two file descriptors:
9272 (read_fd, write_fd)
9273
9274flags can be constructed by ORing together one or more of these values:
9275O_NONBLOCK, O_CLOEXEC.
9276[clinic start generated code]*/
9277
Larry Hastings2f936352014-08-05 14:04:04 +10009278static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009279os_pipe2_impl(PyObject *module, int flags)
9280/*[clinic end generated code: output=25751fb43a45540f input=f261b6e7e63c6817]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009281{
Charles-François Natalidaafdd52011-05-29 20:07:40 +02009282 int fds[2];
9283 int res;
9284
Charles-François Natalidaafdd52011-05-29 20:07:40 +02009285 res = pipe2(fds, flags);
9286 if (res != 0)
9287 return posix_error();
9288 return Py_BuildValue("(ii)", fds[0], fds[1]);
9289}
9290#endif /* HAVE_PIPE2 */
9291
Larry Hastings2f936352014-08-05 14:04:04 +10009292
Ross Lagerwall7807c352011-03-17 20:20:30 +02009293#ifdef HAVE_WRITEV
Larry Hastings2f936352014-08-05 14:04:04 +10009294/*[clinic input]
9295os.writev -> Py_ssize_t
9296 fd: int
9297 buffers: object
9298 /
9299
9300Iterate over buffers, and write the contents of each to a file descriptor.
9301
9302Returns the total number of bytes written.
9303buffers must be a sequence of bytes-like objects.
9304[clinic start generated code]*/
9305
Larry Hastings2f936352014-08-05 14:04:04 +10009306static Py_ssize_t
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009307os_writev_impl(PyObject *module, int fd, PyObject *buffers)
9308/*[clinic end generated code: output=56565cfac3aac15b input=5b8d17fe4189d2fe]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009309{
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009310 Py_ssize_t cnt;
Larry Hastings2f936352014-08-05 14:04:04 +10009311 Py_ssize_t result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009312 int async_err = 0;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009313 struct iovec *iov;
9314 Py_buffer *buf;
Larry Hastings2f936352014-08-05 14:04:04 +10009315
9316 if (!PySequence_Check(buffers)) {
Ross Lagerwall7807c352011-03-17 20:20:30 +02009317 PyErr_SetString(PyExc_TypeError,
9318 "writev() arg 2 must be a sequence");
Larry Hastings2f936352014-08-05 14:04:04 +10009319 return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009320 }
Larry Hastings2f936352014-08-05 14:04:04 +10009321 cnt = PySequence_Size(buffers);
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009322 if (cnt < 0)
9323 return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009324
Larry Hastings2f936352014-08-05 14:04:04 +10009325 if (iov_setup(&iov, &buf, buffers, cnt, PyBUF_SIMPLE) < 0) {
9326 return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009327 }
9328
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009329 do {
9330 Py_BEGIN_ALLOW_THREADS
9331 result = writev(fd, iov, cnt);
9332 Py_END_ALLOW_THREADS
9333 } while (result < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Ross Lagerwall7807c352011-03-17 20:20:30 +02009334
9335 iov_cleanup(iov, buf, cnt);
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009336 if (result < 0 && !async_err)
Larry Hastings2f936352014-08-05 14:04:04 +10009337 posix_error();
Victor Stinner57ddf782014-01-08 15:21:28 +01009338
Georg Brandl306336b2012-06-24 12:55:33 +02009339 return result;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009340}
Larry Hastings2f936352014-08-05 14:04:04 +10009341#endif /* HAVE_WRITEV */
9342
9343
9344#ifdef HAVE_PWRITE
9345/*[clinic input]
9346os.pwrite -> Py_ssize_t
9347
9348 fd: int
9349 buffer: Py_buffer
9350 offset: Py_off_t
9351 /
9352
9353Write bytes to a file descriptor starting at a particular offset.
9354
9355Write buffer to fd, starting at offset bytes from the beginning of
9356the file. Returns the number of bytes writte. Does not change the
9357current file offset.
9358[clinic start generated code]*/
9359
Larry Hastings2f936352014-08-05 14:04:04 +10009360static Py_ssize_t
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009361os_pwrite_impl(PyObject *module, int fd, Py_buffer *buffer, Py_off_t offset)
9362/*[clinic end generated code: output=c74da630758ee925 input=19903f1b3dd26377]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009363{
9364 Py_ssize_t size;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009365 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10009366
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009367 do {
9368 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04009369 _Py_BEGIN_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009370 size = pwrite(fd, buffer->buf, (size_t)buffer->len, offset);
Steve Dower8fc89802015-04-12 00:26:27 -04009371 _Py_END_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009372 Py_END_ALLOW_THREADS
9373 } while (size < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Larry Hastings2f936352014-08-05 14:04:04 +10009374
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009375 if (size < 0 && !async_err)
Larry Hastings2f936352014-08-05 14:04:04 +10009376 posix_error();
9377 return size;
9378}
9379#endif /* HAVE_PWRITE */
9380
Pablo Galindo4defba32018-01-27 16:16:37 +00009381#if defined(HAVE_PWRITEV) || defined (HAVE_PWRITEV2)
9382/*[clinic input]
9383os.pwritev -> Py_ssize_t
9384
9385 fd: int
9386 buffers: object
9387 offset: Py_off_t
9388 flags: int = 0
9389 /
9390
9391Writes the contents of bytes-like objects to a file descriptor at a given offset.
9392
9393Combines the functionality of writev() and pwrite(). All buffers must be a sequence
9394of bytes-like objects. Buffers are processed in array order. Entire contents of first
9395buffer is written before proceeding to second, and so on. The operating system may
9396set a limit (sysconf() value SC_IOV_MAX) on the number of buffers that can be used.
9397This function writes the contents of each object to the file descriptor and returns
9398the total number of bytes written.
9399
9400The flags argument contains a bitwise OR of zero or more of the following flags:
9401
9402- RWF_DSYNC
9403- RWF_SYNC
9404
9405Using non-zero flags requires Linux 4.7 or newer.
9406[clinic start generated code]*/
9407
9408static Py_ssize_t
9409os_pwritev_impl(PyObject *module, int fd, PyObject *buffers, Py_off_t offset,
9410 int flags)
9411/*[clinic end generated code: output=e3dd3e9d11a6a5c7 input=803dc5ddbf0cfd3b]*/
9412{
9413 Py_ssize_t cnt;
9414 Py_ssize_t result;
9415 int async_err = 0;
9416 struct iovec *iov;
9417 Py_buffer *buf;
9418
9419 if (!PySequence_Check(buffers)) {
9420 PyErr_SetString(PyExc_TypeError,
9421 "pwritev() arg 2 must be a sequence");
9422 return -1;
9423 }
9424
9425 cnt = PySequence_Size(buffers);
9426 if (cnt < 0) {
9427 return -1;
9428 }
9429
9430#ifndef HAVE_PWRITEV2
9431 if(flags != 0) {
9432 argument_unavailable_error("pwritev2", "flags");
9433 return -1;
9434 }
9435#endif
9436
9437 if (iov_setup(&iov, &buf, buffers, cnt, PyBUF_SIMPLE) < 0) {
9438 return -1;
9439 }
9440#ifdef HAVE_PWRITEV2
9441 do {
9442 Py_BEGIN_ALLOW_THREADS
9443 _Py_BEGIN_SUPPRESS_IPH
9444 result = pwritev2(fd, iov, cnt, offset, flags);
9445 _Py_END_SUPPRESS_IPH
9446 Py_END_ALLOW_THREADS
9447 } while (result < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
9448#else
9449 do {
9450 Py_BEGIN_ALLOW_THREADS
9451 _Py_BEGIN_SUPPRESS_IPH
9452 result = pwritev(fd, iov, cnt, offset);
9453 _Py_END_SUPPRESS_IPH
9454 Py_END_ALLOW_THREADS
9455 } while (result < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
9456#endif
9457
9458 iov_cleanup(iov, buf, cnt);
9459 if (result < 0) {
9460 if (!async_err) {
9461 posix_error();
9462 }
9463 return -1;
9464 }
9465
9466 return result;
9467}
9468#endif /* HAVE_PWRITEV */
9469
Pablo Galindoaac4d032019-05-31 19:39:47 +01009470#ifdef HAVE_COPY_FILE_RANGE
9471/*[clinic input]
9472
9473os.copy_file_range
9474 src: int
9475 Source file descriptor.
9476 dst: int
9477 Destination file descriptor.
9478 count: Py_ssize_t
9479 Number of bytes to copy.
9480 offset_src: object = None
9481 Starting offset in src.
9482 offset_dst: object = None
9483 Starting offset in dst.
9484
9485Copy count bytes from one file descriptor to another.
9486
9487If offset_src is None, then src is read from the current position;
9488respectively for offset_dst.
9489[clinic start generated code]*/
9490
9491static PyObject *
9492os_copy_file_range_impl(PyObject *module, int src, int dst, Py_ssize_t count,
9493 PyObject *offset_src, PyObject *offset_dst)
9494/*[clinic end generated code: output=1a91713a1d99fc7a input=42fdce72681b25a9]*/
9495{
9496 off_t offset_src_val, offset_dst_val;
9497 off_t *p_offset_src = NULL;
9498 off_t *p_offset_dst = NULL;
9499 Py_ssize_t ret;
9500 int async_err = 0;
9501 /* The flags argument is provided to allow
9502 * for future extensions and currently must be to 0. */
9503 int flags = 0;
Pablo Galindo4defba32018-01-27 16:16:37 +00009504
9505
Pablo Galindoaac4d032019-05-31 19:39:47 +01009506 if (count < 0) {
9507 PyErr_SetString(PyExc_ValueError, "negative value for 'count' not allowed");
9508 return NULL;
9509 }
9510
9511 if (offset_src != Py_None) {
9512 if (!Py_off_t_converter(offset_src, &offset_src_val)) {
9513 return NULL;
9514 }
9515 p_offset_src = &offset_src_val;
9516 }
9517
9518 if (offset_dst != Py_None) {
9519 if (!Py_off_t_converter(offset_dst, &offset_dst_val)) {
9520 return NULL;
9521 }
9522 p_offset_dst = &offset_dst_val;
9523 }
9524
9525 do {
9526 Py_BEGIN_ALLOW_THREADS
9527 ret = copy_file_range(src, p_offset_src, dst, p_offset_dst, count, flags);
9528 Py_END_ALLOW_THREADS
9529 } while (ret < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
9530
9531 if (ret < 0) {
9532 return (!async_err) ? posix_error() : NULL;
9533 }
9534
9535 return PyLong_FromSsize_t(ret);
9536}
9537#endif /* HAVE_COPY_FILE_RANGE*/
Larry Hastings2f936352014-08-05 14:04:04 +10009538
9539#ifdef HAVE_MKFIFO
9540/*[clinic input]
9541os.mkfifo
9542
9543 path: path_t
9544 mode: int=0o666
9545 *
9546 dir_fd: dir_fd(requires='mkfifoat')=None
9547
9548Create a "fifo" (a POSIX named pipe).
9549
9550If dir_fd is not None, it should be a file descriptor open to a directory,
9551 and path should be relative; path will then be relative to that directory.
9552dir_fd may not be implemented on your platform.
9553 If it is unavailable, using it will raise a NotImplementedError.
9554[clinic start generated code]*/
9555
Larry Hastings2f936352014-08-05 14:04:04 +10009556static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009557os_mkfifo_impl(PyObject *module, path_t *path, int mode, int dir_fd)
9558/*[clinic end generated code: output=ce41cfad0e68c940 input=73032e98a36e0e19]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009559{
9560 int result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009561 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10009562
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009563 do {
9564 Py_BEGIN_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10009565#ifdef HAVE_MKFIFOAT
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009566 if (dir_fd != DEFAULT_DIR_FD)
9567 result = mkfifoat(dir_fd, path->narrow, mode);
9568 else
Ross Lagerwall7807c352011-03-17 20:20:30 +02009569#endif
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009570 result = mkfifo(path->narrow, mode);
9571 Py_END_ALLOW_THREADS
9572 } while (result != 0 && errno == EINTR &&
9573 !(async_err = PyErr_CheckSignals()));
9574 if (result != 0)
9575 return (!async_err) ? posix_error() : NULL;
Larry Hastings2f936352014-08-05 14:04:04 +10009576
9577 Py_RETURN_NONE;
9578}
9579#endif /* HAVE_MKFIFO */
9580
9581
9582#if defined(HAVE_MKNOD) && defined(HAVE_MAKEDEV)
9583/*[clinic input]
9584os.mknod
9585
9586 path: path_t
9587 mode: int=0o600
Serhiy Storchakaacdb7c12015-01-18 11:17:39 +02009588 device: dev_t=0
Larry Hastings2f936352014-08-05 14:04:04 +10009589 *
9590 dir_fd: dir_fd(requires='mknodat')=None
9591
9592Create a node in the file system.
9593
9594Create a node in the file system (file, device special file or named pipe)
9595at path. mode specifies both the permissions to use and the
9596type of node to be created, being combined (bitwise OR) with one of
9597S_IFREG, S_IFCHR, S_IFBLK, and S_IFIFO. If S_IFCHR or S_IFBLK is set on mode,
9598device defines the newly created device special file (probably using
9599os.makedev()). Otherwise device is ignored.
9600
9601If dir_fd is not None, it should be a file descriptor open to a directory,
9602 and path should be relative; path will then be relative to that directory.
9603dir_fd may not be implemented on your platform.
9604 If it is unavailable, using it will raise a NotImplementedError.
9605[clinic start generated code]*/
9606
Larry Hastings2f936352014-08-05 14:04:04 +10009607static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009608os_mknod_impl(PyObject *module, path_t *path, int mode, dev_t device,
Larry Hastings89964c42015-04-14 18:07:59 -04009609 int dir_fd)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009610/*[clinic end generated code: output=92e55d3ca8917461 input=ee44531551a4d83b]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009611{
9612 int result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009613 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10009614
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009615 do {
9616 Py_BEGIN_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10009617#ifdef HAVE_MKNODAT
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009618 if (dir_fd != DEFAULT_DIR_FD)
9619 result = mknodat(dir_fd, path->narrow, mode, device);
9620 else
Larry Hastings2f936352014-08-05 14:04:04 +10009621#endif
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009622 result = mknod(path->narrow, mode, device);
9623 Py_END_ALLOW_THREADS
9624 } while (result != 0 && errno == EINTR &&
9625 !(async_err = PyErr_CheckSignals()));
9626 if (result != 0)
9627 return (!async_err) ? posix_error() : NULL;
Larry Hastings2f936352014-08-05 14:04:04 +10009628
9629 Py_RETURN_NONE;
9630}
9631#endif /* defined(HAVE_MKNOD) && defined(HAVE_MAKEDEV) */
9632
9633
9634#ifdef HAVE_DEVICE_MACROS
9635/*[clinic input]
9636os.major -> unsigned_int
9637
Serhiy Storchakaacdb7c12015-01-18 11:17:39 +02009638 device: dev_t
Larry Hastings2f936352014-08-05 14:04:04 +10009639 /
9640
9641Extracts a device major number from a raw device number.
9642[clinic start generated code]*/
9643
Larry Hastings2f936352014-08-05 14:04:04 +10009644static unsigned int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009645os_major_impl(PyObject *module, dev_t device)
9646/*[clinic end generated code: output=5b3b2589bafb498e input=1e16a4d30c4d4462]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009647{
9648 return major(device);
9649}
9650
9651
9652/*[clinic input]
9653os.minor -> unsigned_int
9654
Serhiy Storchakaacdb7c12015-01-18 11:17:39 +02009655 device: dev_t
Larry Hastings2f936352014-08-05 14:04:04 +10009656 /
9657
9658Extracts a device minor number from a raw device number.
9659[clinic start generated code]*/
9660
Larry Hastings2f936352014-08-05 14:04:04 +10009661static unsigned int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009662os_minor_impl(PyObject *module, dev_t device)
9663/*[clinic end generated code: output=5e1a25e630b0157d input=0842c6d23f24c65e]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009664{
9665 return minor(device);
9666}
9667
9668
9669/*[clinic input]
Serhiy Storchakaacdb7c12015-01-18 11:17:39 +02009670os.makedev -> dev_t
Larry Hastings2f936352014-08-05 14:04:04 +10009671
9672 major: int
9673 minor: int
9674 /
9675
9676Composes a raw device number from the major and minor device numbers.
9677[clinic start generated code]*/
9678
Serhiy Storchakaacdb7c12015-01-18 11:17:39 +02009679static dev_t
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009680os_makedev_impl(PyObject *module, int major, int minor)
9681/*[clinic end generated code: output=881aaa4aba6f6a52 input=4b9fd8fc73cbe48f]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009682{
9683 return makedev(major, minor);
9684}
9685#endif /* HAVE_DEVICE_MACROS */
9686
9687
Steve Dowerfe0a41a2015-03-20 19:50:46 -07009688#if defined HAVE_FTRUNCATE || defined MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +10009689/*[clinic input]
9690os.ftruncate
9691
9692 fd: int
9693 length: Py_off_t
9694 /
9695
9696Truncate a file, specified by file descriptor, to a specific length.
9697[clinic start generated code]*/
9698
Larry Hastings2f936352014-08-05 14:04:04 +10009699static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009700os_ftruncate_impl(PyObject *module, int fd, Py_off_t length)
9701/*[clinic end generated code: output=fba15523721be7e4 input=63b43641e52818f2]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009702{
9703 int result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009704 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10009705
Steve Dowerb82e17e2019-05-23 08:45:22 -07009706 if (PySys_Audit("os.truncate", "in", fd, length) < 0) {
9707 return NULL;
9708 }
9709
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009710 do {
9711 Py_BEGIN_ALLOW_THREADS
Steve Dowera1c7e722015-04-12 00:26:43 -04009712 _Py_BEGIN_SUPPRESS_IPH
Steve Dowerfe0a41a2015-03-20 19:50:46 -07009713#ifdef MS_WINDOWS
9714 result = _chsize_s(fd, length);
9715#else
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009716 result = ftruncate(fd, length);
Steve Dowerfe0a41a2015-03-20 19:50:46 -07009717#endif
Steve Dowera1c7e722015-04-12 00:26:43 -04009718 _Py_END_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009719 Py_END_ALLOW_THREADS
9720 } while (result != 0 && errno == EINTR &&
9721 !(async_err = PyErr_CheckSignals()));
9722 if (result != 0)
9723 return (!async_err) ? posix_error() : NULL;
Larry Hastings2f936352014-08-05 14:04:04 +10009724 Py_RETURN_NONE;
9725}
Steve Dowerfe0a41a2015-03-20 19:50:46 -07009726#endif /* HAVE_FTRUNCATE || MS_WINDOWS */
Larry Hastings2f936352014-08-05 14:04:04 +10009727
9728
Steve Dowerfe0a41a2015-03-20 19:50:46 -07009729#if defined HAVE_TRUNCATE || defined MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +10009730/*[clinic input]
9731os.truncate
9732 path: path_t(allow_fd='PATH_HAVE_FTRUNCATE')
9733 length: Py_off_t
9734
9735Truncate a file, specified by path, to a specific length.
9736
9737On some platforms, path may also be specified as an open file descriptor.
9738 If this functionality is unavailable, using it raises an exception.
9739[clinic start generated code]*/
9740
Larry Hastings2f936352014-08-05 14:04:04 +10009741static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009742os_truncate_impl(PyObject *module, path_t *path, Py_off_t length)
9743/*[clinic end generated code: output=43009c8df5c0a12b input=77229cf0b50a9b77]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009744{
9745 int result;
Steve Dowerfe0a41a2015-03-20 19:50:46 -07009746#ifdef MS_WINDOWS
9747 int fd;
9748#endif
9749
9750 if (path->fd != -1)
9751 return os_ftruncate_impl(module, path->fd, length);
Larry Hastings2f936352014-08-05 14:04:04 +10009752
Steve Dowerb82e17e2019-05-23 08:45:22 -07009753 if (PySys_Audit("os.truncate", "On", path->object, length) < 0) {
9754 return NULL;
9755 }
9756
Larry Hastings2f936352014-08-05 14:04:04 +10009757 Py_BEGIN_ALLOW_THREADS
Steve Dowera1c7e722015-04-12 00:26:43 -04009758 _Py_BEGIN_SUPPRESS_IPH
Steve Dowerfe0a41a2015-03-20 19:50:46 -07009759#ifdef MS_WINDOWS
Steve Dowercc16be82016-09-08 10:35:16 -07009760 fd = _wopen(path->wide, _O_WRONLY | _O_BINARY | _O_NOINHERIT);
Victor Stinnercc0bbbc2015-04-25 00:21:52 +02009761 if (fd < 0)
Steve Dowerfe0a41a2015-03-20 19:50:46 -07009762 result = -1;
9763 else {
9764 result = _chsize_s(fd, length);
9765 close(fd);
9766 if (result < 0)
9767 errno = result;
9768 }
9769#else
9770 result = truncate(path->narrow, length);
Larry Hastings2f936352014-08-05 14:04:04 +10009771#endif
Steve Dowera1c7e722015-04-12 00:26:43 -04009772 _Py_END_SUPPRESS_IPH
Larry Hastings2f936352014-08-05 14:04:04 +10009773 Py_END_ALLOW_THREADS
9774 if (result < 0)
Alexey Izbyshev83460312018-10-20 03:28:22 +03009775 return posix_path_error(path);
Larry Hastings2f936352014-08-05 14:04:04 +10009776
9777 Py_RETURN_NONE;
9778}
Steve Dowerfe0a41a2015-03-20 19:50:46 -07009779#endif /* HAVE_TRUNCATE || MS_WINDOWS */
Larry Hastings2f936352014-08-05 14:04:04 +10009780
Ross Lagerwall7807c352011-03-17 20:20:30 +02009781
Victor Stinnerd6b17692014-09-30 12:20:05 +02009782/* Issue #22396: On 32-bit AIX platform, the prototypes of os.posix_fadvise()
9783 and os.posix_fallocate() in system headers are wrong if _LARGE_FILES is
9784 defined, which is the case in Python on AIX. AIX bug report:
9785 http://www-01.ibm.com/support/docview.wss?uid=isg1IV56170 */
9786#if defined(_AIX) && defined(_LARGE_FILES) && !defined(__64BIT__)
9787# define POSIX_FADVISE_AIX_BUG
9788#endif
9789
Victor Stinnerec39e262014-09-30 12:35:58 +02009790
Victor Stinnerd6b17692014-09-30 12:20:05 +02009791#if defined(HAVE_POSIX_FALLOCATE) && !defined(POSIX_FADVISE_AIX_BUG)
Larry Hastings2f936352014-08-05 14:04:04 +10009792/*[clinic input]
9793os.posix_fallocate
9794
9795 fd: int
9796 offset: Py_off_t
9797 length: Py_off_t
9798 /
9799
9800Ensure a file has allocated at least a particular number of bytes on disk.
9801
9802Ensure that the file specified by fd encompasses a range of bytes
9803starting at offset bytes from the beginning and continuing for length bytes.
9804[clinic start generated code]*/
9805
Larry Hastings2f936352014-08-05 14:04:04 +10009806static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009807os_posix_fallocate_impl(PyObject *module, int fd, Py_off_t offset,
Larry Hastings89964c42015-04-14 18:07:59 -04009808 Py_off_t length)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009809/*[clinic end generated code: output=73f107139564aa9d input=d7a2ef0ab2ca52fb]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009810{
9811 int result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009812 int async_err = 0;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009813
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009814 do {
9815 Py_BEGIN_ALLOW_THREADS
9816 result = posix_fallocate(fd, offset, length);
9817 Py_END_ALLOW_THREADS
Коренберг Маркd4b93e22017-08-14 18:55:16 +05009818 } while (result == EINTR && !(async_err = PyErr_CheckSignals()));
9819
9820 if (result == 0)
9821 Py_RETURN_NONE;
9822
9823 if (async_err)
9824 return NULL;
9825
9826 errno = result;
9827 return posix_error();
Ross Lagerwall7807c352011-03-17 20:20:30 +02009828}
Victor Stinnerec39e262014-09-30 12:35:58 +02009829#endif /* HAVE_POSIX_FALLOCATE) && !POSIX_FADVISE_AIX_BUG */
Larry Hastings2f936352014-08-05 14:04:04 +10009830
Ross Lagerwall7807c352011-03-17 20:20:30 +02009831
Victor Stinnerd6b17692014-09-30 12:20:05 +02009832#if defined(HAVE_POSIX_FADVISE) && !defined(POSIX_FADVISE_AIX_BUG)
Larry Hastings2f936352014-08-05 14:04:04 +10009833/*[clinic input]
9834os.posix_fadvise
9835
9836 fd: int
9837 offset: Py_off_t
9838 length: Py_off_t
9839 advice: int
9840 /
9841
9842Announce an intention to access data in a specific pattern.
9843
9844Announce an intention to access data in a specific pattern, thus allowing
9845the kernel to make optimizations.
9846The advice applies to the region of the file specified by fd starting at
9847offset and continuing for length bytes.
9848advice is one of POSIX_FADV_NORMAL, POSIX_FADV_SEQUENTIAL,
9849POSIX_FADV_RANDOM, POSIX_FADV_NOREUSE, POSIX_FADV_WILLNEED, or
9850POSIX_FADV_DONTNEED.
9851[clinic start generated code]*/
9852
Larry Hastings2f936352014-08-05 14:04:04 +10009853static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009854os_posix_fadvise_impl(PyObject *module, int fd, Py_off_t offset,
Larry Hastings89964c42015-04-14 18:07:59 -04009855 Py_off_t length, int advice)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009856/*[clinic end generated code: output=412ef4aa70c98642 input=0fbe554edc2f04b5]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009857{
9858 int result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009859 int async_err = 0;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009860
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009861 do {
9862 Py_BEGIN_ALLOW_THREADS
9863 result = posix_fadvise(fd, offset, length, advice);
9864 Py_END_ALLOW_THREADS
Коренберг Маркd4b93e22017-08-14 18:55:16 +05009865 } while (result == EINTR && !(async_err = PyErr_CheckSignals()));
9866
9867 if (result == 0)
9868 Py_RETURN_NONE;
9869
9870 if (async_err)
9871 return NULL;
9872
9873 errno = result;
9874 return posix_error();
Ross Lagerwall7807c352011-03-17 20:20:30 +02009875}
Victor Stinnerec39e262014-09-30 12:35:58 +02009876#endif /* HAVE_POSIX_FADVISE && !POSIX_FADVISE_AIX_BUG */
Ross Lagerwall7807c352011-03-17 20:20:30 +02009877
Guido van Rossumf1af3fe1996-07-23 19:18:10 +00009878#ifdef HAVE_PUTENV
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00009879
Fred Drake762e2061999-08-26 17:23:54 +00009880/* Save putenv() parameters as values here, so we can collect them when they
9881 * get re-set with another call for the same key. */
9882static PyObject *posix_putenv_garbage;
9883
Larry Hastings2f936352014-08-05 14:04:04 +10009884static void
9885posix_putenv_garbage_setitem(PyObject *name, PyObject *value)
Guido van Rossumf1af3fe1996-07-23 19:18:10 +00009886{
Larry Hastings2f936352014-08-05 14:04:04 +10009887 /* Install the first arg and newstr in posix_putenv_garbage;
9888 * this will cause previous value to be collected. This has to
9889 * happen after the real putenv() call because the old value
9890 * was still accessible until then. */
9891 if (PyDict_SetItem(posix_putenv_garbage, name, value))
9892 /* really not much we can do; just leak */
9893 PyErr_Clear();
9894 else
9895 Py_DECREF(value);
9896}
9897
9898
Thomas Hellerf78f12a2007-11-08 19:33:05 +00009899#ifdef MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +10009900/*[clinic input]
9901os.putenv
9902
9903 name: unicode
9904 value: unicode
9905 /
9906
9907Change or add an environment variable.
9908[clinic start generated code]*/
9909
Larry Hastings2f936352014-08-05 14:04:04 +10009910static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009911os_putenv_impl(PyObject *module, PyObject *name, PyObject *value)
9912/*[clinic end generated code: output=d29a567d6b2327d2 input=ba586581c2e6105f]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009913{
Serhiy Storchakadeab18d2016-05-07 16:45:18 +03009914 const wchar_t *env;
Serhiy Storchakaf7eae0a2017-06-28 08:30:06 +03009915 Py_ssize_t size;
Larry Hastings2f936352014-08-05 14:04:04 +10009916
Serhiy Storchaka77703942017-06-25 07:33:01 +03009917 /* Search from index 1 because on Windows starting '=' is allowed for
9918 defining hidden environment variables. */
9919 if (PyUnicode_GET_LENGTH(name) == 0 ||
9920 PyUnicode_FindChar(name, '=', 1, PyUnicode_GET_LENGTH(name), 1) != -1)
9921 {
9922 PyErr_SetString(PyExc_ValueError, "illegal environment variable name");
9923 return NULL;
9924 }
Larry Hastings2f936352014-08-05 14:04:04 +10009925 PyObject *unicode = PyUnicode_FromFormat("%U=%U", name, value);
9926 if (unicode == NULL) {
Larry Hastings2f936352014-08-05 14:04:04 +10009927 return NULL;
Victor Stinner84ae1182010-05-06 22:05:07 +00009928 }
Serhiy Storchakaf7eae0a2017-06-28 08:30:06 +03009929
9930 env = PyUnicode_AsUnicodeAndSize(unicode, &size);
9931 if (env == NULL)
9932 goto error;
9933 if (size > _MAX_ENV) {
Victor Stinner65170952011-11-22 22:16:17 +01009934 PyErr_Format(PyExc_ValueError,
9935 "the environment variable is longer than %u characters",
9936 _MAX_ENV);
9937 goto error;
9938 }
Serhiy Storchakaf7eae0a2017-06-28 08:30:06 +03009939 if (wcslen(env) != (size_t)size) {
9940 PyErr_SetString(PyExc_ValueError, "embedded null character");
Victor Stinnereb5657a2011-09-30 01:44:27 +02009941 goto error;
Serhiy Storchakaf7eae0a2017-06-28 08:30:06 +03009942 }
9943
Larry Hastings2f936352014-08-05 14:04:04 +10009944 if (_wputenv(env)) {
Victor Stinner8c62be82010-05-06 00:08:46 +00009945 posix_error();
Victor Stinner84ae1182010-05-06 22:05:07 +00009946 goto error;
Victor Stinner8c62be82010-05-06 00:08:46 +00009947 }
Guido van Rossumf1af3fe1996-07-23 19:18:10 +00009948
Larry Hastings2f936352014-08-05 14:04:04 +10009949 posix_putenv_garbage_setitem(name, unicode);
Victor Stinner84ae1182010-05-06 22:05:07 +00009950 Py_RETURN_NONE;
9951
9952error:
Larry Hastings2f936352014-08-05 14:04:04 +10009953 Py_DECREF(unicode);
Victor Stinner84ae1182010-05-06 22:05:07 +00009954 return NULL;
Guido van Rossumf1af3fe1996-07-23 19:18:10 +00009955}
Larry Hastings2f936352014-08-05 14:04:04 +10009956#else /* MS_WINDOWS */
9957/*[clinic input]
9958os.putenv
Guido van Rossumb6a47161997-09-15 22:54:34 +00009959
Larry Hastings2f936352014-08-05 14:04:04 +10009960 name: FSConverter
9961 value: FSConverter
9962 /
9963
9964Change or add an environment variable.
9965[clinic start generated code]*/
9966
Larry Hastings2f936352014-08-05 14:04:04 +10009967static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009968os_putenv_impl(PyObject *module, PyObject *name, PyObject *value)
9969/*[clinic end generated code: output=d29a567d6b2327d2 input=a97bc6152f688d31]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009970{
9971 PyObject *bytes = NULL;
9972 char *env;
Serhiy Storchaka77703942017-06-25 07:33:01 +03009973 const char *name_string = PyBytes_AS_STRING(name);
9974 const char *value_string = PyBytes_AS_STRING(value);
Larry Hastings2f936352014-08-05 14:04:04 +10009975
Serhiy Storchaka77703942017-06-25 07:33:01 +03009976 if (strchr(name_string, '=') != NULL) {
9977 PyErr_SetString(PyExc_ValueError, "illegal environment variable name");
9978 return NULL;
9979 }
Larry Hastings2f936352014-08-05 14:04:04 +10009980 bytes = PyBytes_FromFormat("%s=%s", name_string, value_string);
9981 if (bytes == NULL) {
Larry Hastings2f936352014-08-05 14:04:04 +10009982 return NULL;
9983 }
9984
9985 env = PyBytes_AS_STRING(bytes);
9986 if (putenv(env)) {
9987 Py_DECREF(bytes);
9988 return posix_error();
9989 }
9990
9991 posix_putenv_garbage_setitem(name, bytes);
9992 Py_RETURN_NONE;
9993}
9994#endif /* MS_WINDOWS */
9995#endif /* HAVE_PUTENV */
9996
9997
9998#ifdef HAVE_UNSETENV
9999/*[clinic input]
10000os.unsetenv
10001 name: FSConverter
10002 /
10003
10004Delete an environment variable.
10005[clinic start generated code]*/
10006
Larry Hastings2f936352014-08-05 14:04:04 +100010007static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010008os_unsetenv_impl(PyObject *module, PyObject *name)
10009/*[clinic end generated code: output=54c4137ab1834f02 input=2bb5288a599c7107]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010010{
Victor Stinner984890f2011-11-24 13:53:38 +010010011#ifndef HAVE_BROKEN_UNSETENV
Victor Stinner60b385e2011-11-22 22:01:28 +010010012 int err;
Victor Stinner984890f2011-11-24 13:53:38 +010010013#endif
Victor Stinner84ae1182010-05-06 22:05:07 +000010014
Victor Stinner984890f2011-11-24 13:53:38 +010010015#ifdef HAVE_BROKEN_UNSETENV
10016 unsetenv(PyBytes_AS_STRING(name));
10017#else
Victor Stinner65170952011-11-22 22:16:17 +010010018 err = unsetenv(PyBytes_AS_STRING(name));
Larry Hastings2f936352014-08-05 14:04:04 +100010019 if (err)
Victor Stinner60b385e2011-11-22 22:01:28 +010010020 return posix_error();
Victor Stinner984890f2011-11-24 13:53:38 +010010021#endif
Guido van Rossumc524d952001-10-19 01:31:59 +000010022
Victor Stinner8c62be82010-05-06 00:08:46 +000010023 /* Remove the key from posix_putenv_garbage;
10024 * this will cause it to be collected. This has to
10025 * happen after the real unsetenv() call because the
10026 * old value was still accessible until then.
10027 */
Victor Stinner65170952011-11-22 22:16:17 +010010028 if (PyDict_DelItem(posix_putenv_garbage, name)) {
Victor Stinner8c62be82010-05-06 00:08:46 +000010029 /* really not much we can do; just leak */
Serhiy Storchakaa24107b2019-02-25 17:59:46 +020010030 if (!PyErr_ExceptionMatches(PyExc_KeyError)) {
10031 return NULL;
10032 }
Victor Stinner8c62be82010-05-06 00:08:46 +000010033 PyErr_Clear();
10034 }
Victor Stinner84ae1182010-05-06 22:05:07 +000010035 Py_RETURN_NONE;
Guido van Rossumc524d952001-10-19 01:31:59 +000010036}
Larry Hastings2f936352014-08-05 14:04:04 +100010037#endif /* HAVE_UNSETENV */
Guido van Rossumc524d952001-10-19 01:31:59 +000010038
Larry Hastings2f936352014-08-05 14:04:04 +100010039
10040/*[clinic input]
10041os.strerror
10042
10043 code: int
10044 /
10045
10046Translate an error code to a message string.
10047[clinic start generated code]*/
10048
Larry Hastings2f936352014-08-05 14:04:04 +100010049static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010050os_strerror_impl(PyObject *module, int code)
10051/*[clinic end generated code: output=baebf09fa02a78f2 input=75a8673d97915a91]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010052{
10053 char *message = strerror(code);
Victor Stinner8c62be82010-05-06 00:08:46 +000010054 if (message == NULL) {
10055 PyErr_SetString(PyExc_ValueError,
10056 "strerror() argument out of range");
10057 return NULL;
10058 }
Victor Stinner1b579672011-12-17 05:47:23 +010010059 return PyUnicode_DecodeLocale(message, "surrogateescape");
Guido van Rossumb6a47161997-09-15 22:54:34 +000010060}
Guido van Rossumb6a47161997-09-15 22:54:34 +000010061
Guido van Rossumf1af3fe1996-07-23 19:18:10 +000010062
Guido van Rossumc9641791998-08-04 15:26:23 +000010063#ifdef HAVE_SYS_WAIT_H
Fred Drake106c1a02002-04-23 15:58:02 +000010064#ifdef WCOREDUMP
Larry Hastings2f936352014-08-05 14:04:04 +100010065/*[clinic input]
10066os.WCOREDUMP -> bool
10067
10068 status: int
10069 /
10070
10071Return True if the process returning status was dumped to a core file.
10072[clinic start generated code]*/
10073
Larry Hastings2f936352014-08-05 14:04:04 +100010074static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010075os_WCOREDUMP_impl(PyObject *module, int status)
10076/*[clinic end generated code: output=1a584b147b16bd18 input=8b05e7ab38528d04]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010077{
10078 WAIT_TYPE wait_status;
10079 WAIT_STATUS_INT(wait_status) = status;
10080 return WCOREDUMP(wait_status);
Fred Drake106c1a02002-04-23 15:58:02 +000010081}
10082#endif /* WCOREDUMP */
10083
Larry Hastings2f936352014-08-05 14:04:04 +100010084
Fred Drake106c1a02002-04-23 15:58:02 +000010085#ifdef WIFCONTINUED
Larry Hastings2f936352014-08-05 14:04:04 +100010086/*[clinic input]
10087os.WIFCONTINUED -> bool
10088
10089 status: int
10090
10091Return True if a particular process was continued from a job control stop.
10092
10093Return True if the process returning status was continued from a
10094job control stop.
10095[clinic start generated code]*/
10096
Larry Hastings2f936352014-08-05 14:04:04 +100010097static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010098os_WIFCONTINUED_impl(PyObject *module, int status)
10099/*[clinic end generated code: output=1e35295d844364bd input=e777e7d38eb25bd9]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010100{
10101 WAIT_TYPE wait_status;
10102 WAIT_STATUS_INT(wait_status) = status;
10103 return WIFCONTINUED(wait_status);
Fred Drake106c1a02002-04-23 15:58:02 +000010104}
10105#endif /* WIFCONTINUED */
10106
Larry Hastings2f936352014-08-05 14:04:04 +100010107
Guido van Rossumc9641791998-08-04 15:26:23 +000010108#ifdef WIFSTOPPED
Larry Hastings2f936352014-08-05 14:04:04 +100010109/*[clinic input]
10110os.WIFSTOPPED -> bool
10111
10112 status: int
10113
10114Return True if the process returning status was stopped.
10115[clinic start generated code]*/
10116
Larry Hastings2f936352014-08-05 14:04:04 +100010117static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010118os_WIFSTOPPED_impl(PyObject *module, int status)
10119/*[clinic end generated code: output=fdb57122a5c9b4cb input=043cb7f1289ef904]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010120{
10121 WAIT_TYPE wait_status;
10122 WAIT_STATUS_INT(wait_status) = status;
10123 return WIFSTOPPED(wait_status);
Guido van Rossumc9641791998-08-04 15:26:23 +000010124}
10125#endif /* WIFSTOPPED */
10126
Larry Hastings2f936352014-08-05 14:04:04 +100010127
Guido van Rossumc9641791998-08-04 15:26:23 +000010128#ifdef WIFSIGNALED
Larry Hastings2f936352014-08-05 14:04:04 +100010129/*[clinic input]
10130os.WIFSIGNALED -> bool
10131
10132 status: int
10133
10134Return True if the process returning status was terminated by a signal.
10135[clinic start generated code]*/
10136
Larry Hastings2f936352014-08-05 14:04:04 +100010137static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010138os_WIFSIGNALED_impl(PyObject *module, int status)
10139/*[clinic end generated code: output=d1dde4dcc819a5f5 input=d55ba7cc9ce5dc43]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010140{
10141 WAIT_TYPE wait_status;
10142 WAIT_STATUS_INT(wait_status) = status;
10143 return WIFSIGNALED(wait_status);
Guido van Rossumc9641791998-08-04 15:26:23 +000010144}
10145#endif /* WIFSIGNALED */
10146
Larry Hastings2f936352014-08-05 14:04:04 +100010147
Guido van Rossumc9641791998-08-04 15:26:23 +000010148#ifdef WIFEXITED
Larry Hastings2f936352014-08-05 14:04:04 +100010149/*[clinic input]
10150os.WIFEXITED -> bool
10151
10152 status: int
10153
10154Return True if the process returning status exited via the exit() system call.
10155[clinic start generated code]*/
10156
Larry Hastings2f936352014-08-05 14:04:04 +100010157static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010158os_WIFEXITED_impl(PyObject *module, int status)
10159/*[clinic end generated code: output=01c09d6ebfeea397 input=d63775a6791586c0]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010160{
10161 WAIT_TYPE wait_status;
10162 WAIT_STATUS_INT(wait_status) = status;
10163 return WIFEXITED(wait_status);
Guido van Rossumc9641791998-08-04 15:26:23 +000010164}
10165#endif /* WIFEXITED */
10166
Larry Hastings2f936352014-08-05 14:04:04 +100010167
Guido van Rossum54ecc3d1999-01-27 17:53:11 +000010168#ifdef WEXITSTATUS
Larry Hastings2f936352014-08-05 14:04:04 +100010169/*[clinic input]
10170os.WEXITSTATUS -> int
10171
10172 status: int
10173
10174Return the process return code from status.
10175[clinic start generated code]*/
10176
Larry Hastings2f936352014-08-05 14:04:04 +100010177static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010178os_WEXITSTATUS_impl(PyObject *module, int status)
10179/*[clinic end generated code: output=6e3efbba11f6488d input=e1fb4944e377585b]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010180{
10181 WAIT_TYPE wait_status;
10182 WAIT_STATUS_INT(wait_status) = status;
10183 return WEXITSTATUS(wait_status);
Guido van Rossumc9641791998-08-04 15:26:23 +000010184}
10185#endif /* WEXITSTATUS */
10186
Larry Hastings2f936352014-08-05 14:04:04 +100010187
Guido van Rossumc9641791998-08-04 15:26:23 +000010188#ifdef WTERMSIG
Larry Hastings2f936352014-08-05 14:04:04 +100010189/*[clinic input]
10190os.WTERMSIG -> int
10191
10192 status: int
10193
10194Return the signal that terminated the process that provided the status value.
10195[clinic start generated code]*/
10196
Larry Hastings2f936352014-08-05 14:04:04 +100010197static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010198os_WTERMSIG_impl(PyObject *module, int status)
10199/*[clinic end generated code: output=172f7dfc8dcfc3ad input=727fd7f84ec3f243]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010200{
10201 WAIT_TYPE wait_status;
10202 WAIT_STATUS_INT(wait_status) = status;
10203 return WTERMSIG(wait_status);
Guido van Rossumc9641791998-08-04 15:26:23 +000010204}
10205#endif /* WTERMSIG */
10206
Larry Hastings2f936352014-08-05 14:04:04 +100010207
Guido van Rossumc9641791998-08-04 15:26:23 +000010208#ifdef WSTOPSIG
Larry Hastings2f936352014-08-05 14:04:04 +100010209/*[clinic input]
10210os.WSTOPSIG -> int
10211
10212 status: int
10213
10214Return the signal that stopped the process that provided the status value.
10215[clinic start generated code]*/
10216
Larry Hastings2f936352014-08-05 14:04:04 +100010217static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010218os_WSTOPSIG_impl(PyObject *module, int status)
10219/*[clinic end generated code: output=0ab7586396f5d82b input=46ebf1d1b293c5c1]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010220{
10221 WAIT_TYPE wait_status;
10222 WAIT_STATUS_INT(wait_status) = status;
10223 return WSTOPSIG(wait_status);
Guido van Rossumc9641791998-08-04 15:26:23 +000010224}
10225#endif /* WSTOPSIG */
Guido van Rossumc9641791998-08-04 15:26:23 +000010226#endif /* HAVE_SYS_WAIT_H */
10227
10228
Thomas Wouters477c8d52006-05-27 19:21:47 +000010229#if defined(HAVE_FSTATVFS) && defined(HAVE_SYS_STATVFS_H)
Guido van Rossumd5753e11999-10-19 13:29:23 +000010230#ifdef _SCO_DS
10231/* SCO OpenServer 5.0 and later requires _SVID3 before it reveals the
10232 needed definitions in sys/statvfs.h */
10233#define _SVID3
10234#endif
Guido van Rossum94f6f721999-01-06 18:42:14 +000010235#include <sys/statvfs.h>
10236
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010237static PyObject*
10238_pystatvfs_fromstructstatvfs(struct statvfs st) {
Eddie Elizondo474eedf2018-11-13 04:09:31 -080010239 PyObject *v = PyStructSequence_New(StatVFSResultType);
Victor Stinner8c62be82010-05-06 00:08:46 +000010240 if (v == NULL)
10241 return NULL;
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010242
10243#if !defined(HAVE_LARGEFILE_SUPPORT)
Victor Stinner8c62be82010-05-06 00:08:46 +000010244 PyStructSequence_SET_ITEM(v, 0, PyLong_FromLong((long) st.f_bsize));
10245 PyStructSequence_SET_ITEM(v, 1, PyLong_FromLong((long) st.f_frsize));
10246 PyStructSequence_SET_ITEM(v, 2, PyLong_FromLong((long) st.f_blocks));
10247 PyStructSequence_SET_ITEM(v, 3, PyLong_FromLong((long) st.f_bfree));
10248 PyStructSequence_SET_ITEM(v, 4, PyLong_FromLong((long) st.f_bavail));
10249 PyStructSequence_SET_ITEM(v, 5, PyLong_FromLong((long) st.f_files));
10250 PyStructSequence_SET_ITEM(v, 6, PyLong_FromLong((long) st.f_ffree));
10251 PyStructSequence_SET_ITEM(v, 7, PyLong_FromLong((long) st.f_favail));
10252 PyStructSequence_SET_ITEM(v, 8, PyLong_FromLong((long) st.f_flag));
10253 PyStructSequence_SET_ITEM(v, 9, PyLong_FromLong((long) st.f_namemax));
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010254#else
Victor Stinner8c62be82010-05-06 00:08:46 +000010255 PyStructSequence_SET_ITEM(v, 0, PyLong_FromLong((long) st.f_bsize));
10256 PyStructSequence_SET_ITEM(v, 1, PyLong_FromLong((long) st.f_frsize));
10257 PyStructSequence_SET_ITEM(v, 2,
Benjamin Petersonaf580df2016-09-06 10:46:49 -070010258 PyLong_FromLongLong((long long) st.f_blocks));
Victor Stinner8c62be82010-05-06 00:08:46 +000010259 PyStructSequence_SET_ITEM(v, 3,
Benjamin Petersonaf580df2016-09-06 10:46:49 -070010260 PyLong_FromLongLong((long long) st.f_bfree));
Victor Stinner8c62be82010-05-06 00:08:46 +000010261 PyStructSequence_SET_ITEM(v, 4,
Benjamin Petersonaf580df2016-09-06 10:46:49 -070010262 PyLong_FromLongLong((long long) st.f_bavail));
Victor Stinner8c62be82010-05-06 00:08:46 +000010263 PyStructSequence_SET_ITEM(v, 5,
Benjamin Petersonaf580df2016-09-06 10:46:49 -070010264 PyLong_FromLongLong((long long) st.f_files));
Victor Stinner8c62be82010-05-06 00:08:46 +000010265 PyStructSequence_SET_ITEM(v, 6,
Benjamin Petersonaf580df2016-09-06 10:46:49 -070010266 PyLong_FromLongLong((long long) st.f_ffree));
Victor Stinner8c62be82010-05-06 00:08:46 +000010267 PyStructSequence_SET_ITEM(v, 7,
Benjamin Petersonaf580df2016-09-06 10:46:49 -070010268 PyLong_FromLongLong((long long) st.f_favail));
Victor Stinner8c62be82010-05-06 00:08:46 +000010269 PyStructSequence_SET_ITEM(v, 8, PyLong_FromLong((long) st.f_flag));
10270 PyStructSequence_SET_ITEM(v, 9, PyLong_FromLong((long) st.f_namemax));
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010271#endif
Michael Felt502d5512018-01-05 13:01:58 +010010272/* The _ALL_SOURCE feature test macro defines f_fsid as a structure
10273 * (issue #32390). */
10274#if defined(_AIX) && defined(_ALL_SOURCE)
10275 PyStructSequence_SET_ITEM(v, 10, PyLong_FromUnsignedLong(st.f_fsid.val[0]));
10276#else
Giuseppe Scrivano96a5e502017-12-14 23:46:46 +010010277 PyStructSequence_SET_ITEM(v, 10, PyLong_FromUnsignedLong(st.f_fsid));
Michael Felt502d5512018-01-05 13:01:58 +010010278#endif
Victor Stinnerf0a7bac2013-10-30 18:55:24 +010010279 if (PyErr_Occurred()) {
10280 Py_DECREF(v);
10281 return NULL;
10282 }
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010283
Victor Stinner8c62be82010-05-06 00:08:46 +000010284 return v;
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010285}
10286
Larry Hastings2f936352014-08-05 14:04:04 +100010287
10288/*[clinic input]
10289os.fstatvfs
10290 fd: int
10291 /
10292
10293Perform an fstatvfs system call on the given fd.
10294
10295Equivalent to statvfs(fd).
10296[clinic start generated code]*/
10297
Larry Hastings2f936352014-08-05 14:04:04 +100010298static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010299os_fstatvfs_impl(PyObject *module, int fd)
10300/*[clinic end generated code: output=53547cf0cc55e6c5 input=d8122243ac50975e]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010301{
10302 int result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010303 int async_err = 0;
Victor Stinner8c62be82010-05-06 00:08:46 +000010304 struct statvfs st;
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010305
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010306 do {
10307 Py_BEGIN_ALLOW_THREADS
10308 result = fstatvfs(fd, &st);
10309 Py_END_ALLOW_THREADS
10310 } while (result != 0 && errno == EINTR &&
10311 !(async_err = PyErr_CheckSignals()));
Larry Hastings2f936352014-08-05 14:04:04 +100010312 if (result != 0)
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010313 return (!async_err) ? posix_error() : NULL;
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010314
Victor Stinner8c62be82010-05-06 00:08:46 +000010315 return _pystatvfs_fromstructstatvfs(st);
Guido van Rossum94f6f721999-01-06 18:42:14 +000010316}
Larry Hastings2f936352014-08-05 14:04:04 +100010317#endif /* defined(HAVE_FSTATVFS) && defined(HAVE_SYS_STATVFS_H) */
Guido van Rossum94f6f721999-01-06 18:42:14 +000010318
10319
Thomas Wouters477c8d52006-05-27 19:21:47 +000010320#if defined(HAVE_STATVFS) && defined(HAVE_SYS_STATVFS_H)
Guido van Rossum94f6f721999-01-06 18:42:14 +000010321#include <sys/statvfs.h>
Larry Hastings2f936352014-08-05 14:04:04 +100010322/*[clinic input]
10323os.statvfs
Guido van Rossum94f6f721999-01-06 18:42:14 +000010324
Larry Hastings2f936352014-08-05 14:04:04 +100010325 path: path_t(allow_fd='PATH_HAVE_FSTATVFS')
10326
10327Perform a statvfs system call on the given path.
10328
10329path may always be specified as a string.
10330On some platforms, path may also be specified as an open file descriptor.
10331 If this functionality is unavailable, using it raises an exception.
10332[clinic start generated code]*/
10333
Larry Hastings2f936352014-08-05 14:04:04 +100010334static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010335os_statvfs_impl(PyObject *module, path_t *path)
10336/*[clinic end generated code: output=87106dd1beb8556e input=3f5c35791c669bd9]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010337{
10338 int result;
10339 struct statvfs st;
Larry Hastings9cf065c2012-06-22 16:30:09 -070010340
10341 Py_BEGIN_ALLOW_THREADS
10342#ifdef HAVE_FSTATVFS
Larry Hastings2f936352014-08-05 14:04:04 +100010343 if (path->fd != -1) {
Larry Hastings9cf065c2012-06-22 16:30:09 -070010344#ifdef __APPLE__
10345 /* handle weak-linking on Mac OS X 10.3 */
10346 if (fstatvfs == NULL) {
Larry Hastings2f936352014-08-05 14:04:04 +100010347 fd_specified("statvfs", path->fd);
10348 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -070010349 }
10350#endif
Larry Hastings2f936352014-08-05 14:04:04 +100010351 result = fstatvfs(path->fd, &st);
Larry Hastings9cf065c2012-06-22 16:30:09 -070010352 }
10353 else
10354#endif
Larry Hastings2f936352014-08-05 14:04:04 +100010355 result = statvfs(path->narrow, &st);
Larry Hastings9cf065c2012-06-22 16:30:09 -070010356 Py_END_ALLOW_THREADS
10357
10358 if (result) {
Larry Hastings2f936352014-08-05 14:04:04 +100010359 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -070010360 }
10361
Larry Hastings2f936352014-08-05 14:04:04 +100010362 return _pystatvfs_fromstructstatvfs(st);
Guido van Rossum94f6f721999-01-06 18:42:14 +000010363}
Larry Hastings2f936352014-08-05 14:04:04 +100010364#endif /* defined(HAVE_STATVFS) && defined(HAVE_SYS_STATVFS_H) */
10365
Guido van Rossum94f6f721999-01-06 18:42:14 +000010366
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010367#ifdef MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +100010368/*[clinic input]
10369os._getdiskusage
10370
Steve Dower23ad6d02018-02-22 10:39:10 -080010371 path: path_t
Larry Hastings2f936352014-08-05 14:04:04 +100010372
10373Return disk usage statistics about the given path as a (total, free) tuple.
10374[clinic start generated code]*/
10375
Larry Hastings2f936352014-08-05 14:04:04 +100010376static PyObject *
Steve Dower23ad6d02018-02-22 10:39:10 -080010377os__getdiskusage_impl(PyObject *module, path_t *path)
10378/*[clinic end generated code: output=3bd3991f5e5c5dfb input=6af8d1b7781cc042]*/
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010379{
10380 BOOL retval;
10381 ULARGE_INTEGER _, total, free;
Joe Pamerc8c02492018-09-25 10:57:36 -040010382 DWORD err = 0;
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010383
10384 Py_BEGIN_ALLOW_THREADS
Steve Dower23ad6d02018-02-22 10:39:10 -080010385 retval = GetDiskFreeSpaceExW(path->wide, &_, &total, &free);
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010386 Py_END_ALLOW_THREADS
Joe Pamerc8c02492018-09-25 10:57:36 -040010387 if (retval == 0) {
10388 if (GetLastError() == ERROR_DIRECTORY) {
10389 wchar_t *dir_path = NULL;
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010390
Joe Pamerc8c02492018-09-25 10:57:36 -040010391 dir_path = PyMem_New(wchar_t, path->length + 1);
10392 if (dir_path == NULL) {
10393 return PyErr_NoMemory();
10394 }
10395
10396 wcscpy_s(dir_path, path->length + 1, path->wide);
10397
10398 if (_dirnameW(dir_path) != -1) {
10399 Py_BEGIN_ALLOW_THREADS
10400 retval = GetDiskFreeSpaceExW(dir_path, &_, &total, &free);
10401 Py_END_ALLOW_THREADS
10402 }
10403 /* Record the last error in case it's modified by PyMem_Free. */
10404 err = GetLastError();
10405 PyMem_Free(dir_path);
10406 if (retval) {
10407 goto success;
10408 }
10409 }
10410 return PyErr_SetFromWindowsErr(err);
10411 }
10412
10413success:
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010414 return Py_BuildValue("(LL)", total.QuadPart, free.QuadPart);
10415}
Larry Hastings2f936352014-08-05 14:04:04 +100010416#endif /* MS_WINDOWS */
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010417
10418
Fred Drakec9680921999-12-13 16:37:25 +000010419/* This is used for fpathconf(), pathconf(), confstr() and sysconf().
10420 * It maps strings representing configuration variable names to
10421 * integer values, allowing those functions to be called with the
Thomas Wouters7e474022000-07-16 12:04:32 +000010422 * magic names instead of polluting the module's namespace with tons of
Fred Drake12c6e2d1999-12-14 21:25:03 +000010423 * rarely-used constants. There are three separate tables that use
10424 * these definitions.
Fred Drakebec628d1999-12-15 18:31:10 +000010425 *
10426 * This code is always included, even if none of the interfaces that
10427 * need it are included. The #if hackery needed to avoid it would be
10428 * sufficiently pervasive that it's not worth the loss of readability.
Fred Drakec9680921999-12-13 16:37:25 +000010429 */
10430struct constdef {
Serhiy Storchaka2d06e842015-12-25 19:53:18 +020010431 const char *name;
Serhiy Storchaka56f6e762015-09-06 21:25:30 +030010432 int value;
Fred Drakec9680921999-12-13 16:37:25 +000010433};
10434
Fred Drake12c6e2d1999-12-14 21:25:03 +000010435static int
Fredrik Lundhff7df9d2000-07-08 22:48:53 +000010436conv_confname(PyObject *arg, int *valuep, struct constdef *table,
Guido van Rossum7d5baac2007-08-27 23:24:46 +000010437 size_t tablesize)
Fred Drake12c6e2d1999-12-14 21:25:03 +000010438{
Christian Heimes217cfd12007-12-02 14:31:20 +000010439 if (PyLong_Check(arg)) {
Serhiy Storchaka56f6e762015-09-06 21:25:30 +030010440 int value = _PyLong_AsInt(arg);
10441 if (value == -1 && PyErr_Occurred())
10442 return 0;
10443 *valuep = value;
Stefan Krah0e803b32010-11-26 16:16:47 +000010444 return 1;
Fred Drake12c6e2d1999-12-14 21:25:03 +000010445 }
Guido van Rossumbce56a62007-05-10 18:04:33 +000010446 else {
Stefan Krah0e803b32010-11-26 16:16:47 +000010447 /* look up the value in the table using a binary search */
10448 size_t lo = 0;
10449 size_t mid;
10450 size_t hi = tablesize;
10451 int cmp;
10452 const char *confname;
10453 if (!PyUnicode_Check(arg)) {
10454 PyErr_SetString(PyExc_TypeError,
10455 "configuration names must be strings or integers");
10456 return 0;
Victor Stinner8c62be82010-05-06 00:08:46 +000010457 }
Serhiy Storchaka06515832016-11-20 09:13:07 +020010458 confname = PyUnicode_AsUTF8(arg);
Stefan Krah0e803b32010-11-26 16:16:47 +000010459 if (confname == NULL)
10460 return 0;
10461 while (lo < hi) {
10462 mid = (lo + hi) / 2;
10463 cmp = strcmp(confname, table[mid].name);
10464 if (cmp < 0)
10465 hi = mid;
10466 else if (cmp > 0)
10467 lo = mid + 1;
10468 else {
10469 *valuep = table[mid].value;
10470 return 1;
10471 }
10472 }
10473 PyErr_SetString(PyExc_ValueError, "unrecognized configuration name");
10474 return 0;
Victor Stinner8c62be82010-05-06 00:08:46 +000010475 }
Fred Drake12c6e2d1999-12-14 21:25:03 +000010476}
10477
10478
10479#if defined(HAVE_FPATHCONF) || defined(HAVE_PATHCONF)
10480static struct constdef posix_constants_pathconf[] = {
Fred Draked86ed291999-12-15 15:34:33 +000010481#ifdef _PC_ABI_AIO_XFER_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010482 {"PC_ABI_AIO_XFER_MAX", _PC_ABI_AIO_XFER_MAX},
Fred Draked86ed291999-12-15 15:34:33 +000010483#endif
10484#ifdef _PC_ABI_ASYNC_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000010485 {"PC_ABI_ASYNC_IO", _PC_ABI_ASYNC_IO},
Fred Draked86ed291999-12-15 15:34:33 +000010486#endif
Fred Drakec9680921999-12-13 16:37:25 +000010487#ifdef _PC_ASYNC_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000010488 {"PC_ASYNC_IO", _PC_ASYNC_IO},
Fred Drakec9680921999-12-13 16:37:25 +000010489#endif
10490#ifdef _PC_CHOWN_RESTRICTED
Victor Stinner8c62be82010-05-06 00:08:46 +000010491 {"PC_CHOWN_RESTRICTED", _PC_CHOWN_RESTRICTED},
Fred Drakec9680921999-12-13 16:37:25 +000010492#endif
10493#ifdef _PC_FILESIZEBITS
Victor Stinner8c62be82010-05-06 00:08:46 +000010494 {"PC_FILESIZEBITS", _PC_FILESIZEBITS},
Fred Drakec9680921999-12-13 16:37:25 +000010495#endif
10496#ifdef _PC_LAST
Victor Stinner8c62be82010-05-06 00:08:46 +000010497 {"PC_LAST", _PC_LAST},
Fred Drakec9680921999-12-13 16:37:25 +000010498#endif
10499#ifdef _PC_LINK_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010500 {"PC_LINK_MAX", _PC_LINK_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010501#endif
10502#ifdef _PC_MAX_CANON
Victor Stinner8c62be82010-05-06 00:08:46 +000010503 {"PC_MAX_CANON", _PC_MAX_CANON},
Fred Drakec9680921999-12-13 16:37:25 +000010504#endif
10505#ifdef _PC_MAX_INPUT
Victor Stinner8c62be82010-05-06 00:08:46 +000010506 {"PC_MAX_INPUT", _PC_MAX_INPUT},
Fred Drakec9680921999-12-13 16:37:25 +000010507#endif
10508#ifdef _PC_NAME_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010509 {"PC_NAME_MAX", _PC_NAME_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010510#endif
10511#ifdef _PC_NO_TRUNC
Victor Stinner8c62be82010-05-06 00:08:46 +000010512 {"PC_NO_TRUNC", _PC_NO_TRUNC},
Fred Drakec9680921999-12-13 16:37:25 +000010513#endif
10514#ifdef _PC_PATH_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010515 {"PC_PATH_MAX", _PC_PATH_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010516#endif
10517#ifdef _PC_PIPE_BUF
Victor Stinner8c62be82010-05-06 00:08:46 +000010518 {"PC_PIPE_BUF", _PC_PIPE_BUF},
Fred Drakec9680921999-12-13 16:37:25 +000010519#endif
10520#ifdef _PC_PRIO_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000010521 {"PC_PRIO_IO", _PC_PRIO_IO},
Fred Drakec9680921999-12-13 16:37:25 +000010522#endif
10523#ifdef _PC_SOCK_MAXBUF
Victor Stinner8c62be82010-05-06 00:08:46 +000010524 {"PC_SOCK_MAXBUF", _PC_SOCK_MAXBUF},
Fred Drakec9680921999-12-13 16:37:25 +000010525#endif
10526#ifdef _PC_SYNC_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000010527 {"PC_SYNC_IO", _PC_SYNC_IO},
Fred Drakec9680921999-12-13 16:37:25 +000010528#endif
10529#ifdef _PC_VDISABLE
Victor Stinner8c62be82010-05-06 00:08:46 +000010530 {"PC_VDISABLE", _PC_VDISABLE},
Fred Drakec9680921999-12-13 16:37:25 +000010531#endif
Jesus Cea7e9065c2010-10-25 13:02:04 +000010532#ifdef _PC_ACL_ENABLED
10533 {"PC_ACL_ENABLED", _PC_ACL_ENABLED},
10534#endif
10535#ifdef _PC_MIN_HOLE_SIZE
10536 {"PC_MIN_HOLE_SIZE", _PC_MIN_HOLE_SIZE},
10537#endif
10538#ifdef _PC_ALLOC_SIZE_MIN
10539 {"PC_ALLOC_SIZE_MIN", _PC_ALLOC_SIZE_MIN},
10540#endif
10541#ifdef _PC_REC_INCR_XFER_SIZE
10542 {"PC_REC_INCR_XFER_SIZE", _PC_REC_INCR_XFER_SIZE},
10543#endif
10544#ifdef _PC_REC_MAX_XFER_SIZE
10545 {"PC_REC_MAX_XFER_SIZE", _PC_REC_MAX_XFER_SIZE},
10546#endif
10547#ifdef _PC_REC_MIN_XFER_SIZE
10548 {"PC_REC_MIN_XFER_SIZE", _PC_REC_MIN_XFER_SIZE},
10549#endif
10550#ifdef _PC_REC_XFER_ALIGN
10551 {"PC_REC_XFER_ALIGN", _PC_REC_XFER_ALIGN},
10552#endif
10553#ifdef _PC_SYMLINK_MAX
10554 {"PC_SYMLINK_MAX", _PC_SYMLINK_MAX},
10555#endif
10556#ifdef _PC_XATTR_ENABLED
10557 {"PC_XATTR_ENABLED", _PC_XATTR_ENABLED},
10558#endif
10559#ifdef _PC_XATTR_EXISTS
10560 {"PC_XATTR_EXISTS", _PC_XATTR_EXISTS},
10561#endif
10562#ifdef _PC_TIMESTAMP_RESOLUTION
10563 {"PC_TIMESTAMP_RESOLUTION", _PC_TIMESTAMP_RESOLUTION},
10564#endif
Fred Drakec9680921999-12-13 16:37:25 +000010565};
10566
Fred Drakec9680921999-12-13 16:37:25 +000010567static int
Fredrik Lundhff7df9d2000-07-08 22:48:53 +000010568conv_path_confname(PyObject *arg, int *valuep)
Fred Drakec9680921999-12-13 16:37:25 +000010569{
10570 return conv_confname(arg, valuep, posix_constants_pathconf,
10571 sizeof(posix_constants_pathconf)
10572 / sizeof(struct constdef));
10573}
10574#endif
10575
Larry Hastings2f936352014-08-05 14:04:04 +100010576
Fred Drakec9680921999-12-13 16:37:25 +000010577#ifdef HAVE_FPATHCONF
Larry Hastings2f936352014-08-05 14:04:04 +100010578/*[clinic input]
10579os.fpathconf -> long
10580
10581 fd: int
10582 name: path_confname
10583 /
10584
10585Return the configuration limit name for the file descriptor fd.
10586
10587If there is no limit, return -1.
10588[clinic start generated code]*/
10589
Larry Hastings2f936352014-08-05 14:04:04 +100010590static long
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010591os_fpathconf_impl(PyObject *module, int fd, int name)
10592/*[clinic end generated code: output=d5b7042425fc3e21 input=5942a024d3777810]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010593{
10594 long limit;
10595
10596 errno = 0;
10597 limit = fpathconf(fd, name);
10598 if (limit == -1 && errno != 0)
10599 posix_error();
10600
10601 return limit;
10602}
10603#endif /* HAVE_FPATHCONF */
Fred Drakec9680921999-12-13 16:37:25 +000010604
10605
10606#ifdef HAVE_PATHCONF
Larry Hastings2f936352014-08-05 14:04:04 +100010607/*[clinic input]
10608os.pathconf -> long
10609 path: path_t(allow_fd='PATH_HAVE_FPATHCONF')
10610 name: path_confname
10611
10612Return the configuration limit name for the file or directory path.
10613
10614If there is no limit, return -1.
10615On some platforms, path may also be specified as an open file descriptor.
10616 If this functionality is unavailable, using it raises an exception.
10617[clinic start generated code]*/
10618
Larry Hastings2f936352014-08-05 14:04:04 +100010619static long
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010620os_pathconf_impl(PyObject *module, path_t *path, int name)
10621/*[clinic end generated code: output=5bedee35b293a089 input=bc3e2a985af27e5e]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010622{
Victor Stinner8c62be82010-05-06 00:08:46 +000010623 long limit;
Fred Drakec9680921999-12-13 16:37:25 +000010624
Victor Stinner8c62be82010-05-06 00:08:46 +000010625 errno = 0;
Georg Brandl306336b2012-06-24 12:55:33 +020010626#ifdef HAVE_FPATHCONF
Larry Hastings2f936352014-08-05 14:04:04 +100010627 if (path->fd != -1)
10628 limit = fpathconf(path->fd, name);
Georg Brandl306336b2012-06-24 12:55:33 +020010629 else
10630#endif
Larry Hastings2f936352014-08-05 14:04:04 +100010631 limit = pathconf(path->narrow, name);
Victor Stinner8c62be82010-05-06 00:08:46 +000010632 if (limit == -1 && errno != 0) {
10633 if (errno == EINVAL)
Stefan Krah99439262010-11-26 12:58:05 +000010634 /* could be a path or name problem */
10635 posix_error();
Fred Drakec9680921999-12-13 16:37:25 +000010636 else
Larry Hastings2f936352014-08-05 14:04:04 +100010637 path_error(path);
Victor Stinner8c62be82010-05-06 00:08:46 +000010638 }
Larry Hastings2f936352014-08-05 14:04:04 +100010639
10640 return limit;
Fred Drakec9680921999-12-13 16:37:25 +000010641}
Larry Hastings2f936352014-08-05 14:04:04 +100010642#endif /* HAVE_PATHCONF */
Fred Drakec9680921999-12-13 16:37:25 +000010643
10644#ifdef HAVE_CONFSTR
10645static struct constdef posix_constants_confstr[] = {
Fred Draked86ed291999-12-15 15:34:33 +000010646#ifdef _CS_ARCHITECTURE
Victor Stinner8c62be82010-05-06 00:08:46 +000010647 {"CS_ARCHITECTURE", _CS_ARCHITECTURE},
Fred Draked86ed291999-12-15 15:34:33 +000010648#endif
Mark Dickinson876d7c82010-04-16 12:47:52 +000010649#ifdef _CS_GNU_LIBC_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000010650 {"CS_GNU_LIBC_VERSION", _CS_GNU_LIBC_VERSION},
Mark Dickinson876d7c82010-04-16 12:47:52 +000010651#endif
10652#ifdef _CS_GNU_LIBPTHREAD_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000010653 {"CS_GNU_LIBPTHREAD_VERSION", _CS_GNU_LIBPTHREAD_VERSION},
Mark Dickinson876d7c82010-04-16 12:47:52 +000010654#endif
Fred Draked86ed291999-12-15 15:34:33 +000010655#ifdef _CS_HOSTNAME
Victor Stinner8c62be82010-05-06 00:08:46 +000010656 {"CS_HOSTNAME", _CS_HOSTNAME},
Fred Draked86ed291999-12-15 15:34:33 +000010657#endif
10658#ifdef _CS_HW_PROVIDER
Victor Stinner8c62be82010-05-06 00:08:46 +000010659 {"CS_HW_PROVIDER", _CS_HW_PROVIDER},
Fred Draked86ed291999-12-15 15:34:33 +000010660#endif
10661#ifdef _CS_HW_SERIAL
Victor Stinner8c62be82010-05-06 00:08:46 +000010662 {"CS_HW_SERIAL", _CS_HW_SERIAL},
Fred Draked86ed291999-12-15 15:34:33 +000010663#endif
10664#ifdef _CS_INITTAB_NAME
Victor Stinner8c62be82010-05-06 00:08:46 +000010665 {"CS_INITTAB_NAME", _CS_INITTAB_NAME},
Fred Draked86ed291999-12-15 15:34:33 +000010666#endif
Fred Drakec9680921999-12-13 16:37:25 +000010667#ifdef _CS_LFS64_CFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010668 {"CS_LFS64_CFLAGS", _CS_LFS64_CFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010669#endif
10670#ifdef _CS_LFS64_LDFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010671 {"CS_LFS64_LDFLAGS", _CS_LFS64_LDFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010672#endif
10673#ifdef _CS_LFS64_LIBS
Victor Stinner8c62be82010-05-06 00:08:46 +000010674 {"CS_LFS64_LIBS", _CS_LFS64_LIBS},
Fred Drakec9680921999-12-13 16:37:25 +000010675#endif
10676#ifdef _CS_LFS64_LINTFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010677 {"CS_LFS64_LINTFLAGS", _CS_LFS64_LINTFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010678#endif
10679#ifdef _CS_LFS_CFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010680 {"CS_LFS_CFLAGS", _CS_LFS_CFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010681#endif
10682#ifdef _CS_LFS_LDFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010683 {"CS_LFS_LDFLAGS", _CS_LFS_LDFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010684#endif
10685#ifdef _CS_LFS_LIBS
Victor Stinner8c62be82010-05-06 00:08:46 +000010686 {"CS_LFS_LIBS", _CS_LFS_LIBS},
Fred Drakec9680921999-12-13 16:37:25 +000010687#endif
10688#ifdef _CS_LFS_LINTFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010689 {"CS_LFS_LINTFLAGS", _CS_LFS_LINTFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010690#endif
Fred Draked86ed291999-12-15 15:34:33 +000010691#ifdef _CS_MACHINE
Victor Stinner8c62be82010-05-06 00:08:46 +000010692 {"CS_MACHINE", _CS_MACHINE},
Fred Draked86ed291999-12-15 15:34:33 +000010693#endif
Fred Drakec9680921999-12-13 16:37:25 +000010694#ifdef _CS_PATH
Victor Stinner8c62be82010-05-06 00:08:46 +000010695 {"CS_PATH", _CS_PATH},
Fred Drakec9680921999-12-13 16:37:25 +000010696#endif
Fred Draked86ed291999-12-15 15:34:33 +000010697#ifdef _CS_RELEASE
Victor Stinner8c62be82010-05-06 00:08:46 +000010698 {"CS_RELEASE", _CS_RELEASE},
Fred Draked86ed291999-12-15 15:34:33 +000010699#endif
10700#ifdef _CS_SRPC_DOMAIN
Victor Stinner8c62be82010-05-06 00:08:46 +000010701 {"CS_SRPC_DOMAIN", _CS_SRPC_DOMAIN},
Fred Draked86ed291999-12-15 15:34:33 +000010702#endif
10703#ifdef _CS_SYSNAME
Victor Stinner8c62be82010-05-06 00:08:46 +000010704 {"CS_SYSNAME", _CS_SYSNAME},
Fred Draked86ed291999-12-15 15:34:33 +000010705#endif
10706#ifdef _CS_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000010707 {"CS_VERSION", _CS_VERSION},
Fred Draked86ed291999-12-15 15:34:33 +000010708#endif
Fred Drakec9680921999-12-13 16:37:25 +000010709#ifdef _CS_XBS5_ILP32_OFF32_CFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010710 {"CS_XBS5_ILP32_OFF32_CFLAGS", _CS_XBS5_ILP32_OFF32_CFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010711#endif
10712#ifdef _CS_XBS5_ILP32_OFF32_LDFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010713 {"CS_XBS5_ILP32_OFF32_LDFLAGS", _CS_XBS5_ILP32_OFF32_LDFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010714#endif
10715#ifdef _CS_XBS5_ILP32_OFF32_LIBS
Victor Stinner8c62be82010-05-06 00:08:46 +000010716 {"CS_XBS5_ILP32_OFF32_LIBS", _CS_XBS5_ILP32_OFF32_LIBS},
Fred Drakec9680921999-12-13 16:37:25 +000010717#endif
10718#ifdef _CS_XBS5_ILP32_OFF32_LINTFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010719 {"CS_XBS5_ILP32_OFF32_LINTFLAGS", _CS_XBS5_ILP32_OFF32_LINTFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010720#endif
10721#ifdef _CS_XBS5_ILP32_OFFBIG_CFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010722 {"CS_XBS5_ILP32_OFFBIG_CFLAGS", _CS_XBS5_ILP32_OFFBIG_CFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010723#endif
10724#ifdef _CS_XBS5_ILP32_OFFBIG_LDFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010725 {"CS_XBS5_ILP32_OFFBIG_LDFLAGS", _CS_XBS5_ILP32_OFFBIG_LDFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010726#endif
10727#ifdef _CS_XBS5_ILP32_OFFBIG_LIBS
Victor Stinner8c62be82010-05-06 00:08:46 +000010728 {"CS_XBS5_ILP32_OFFBIG_LIBS", _CS_XBS5_ILP32_OFFBIG_LIBS},
Fred Drakec9680921999-12-13 16:37:25 +000010729#endif
10730#ifdef _CS_XBS5_ILP32_OFFBIG_LINTFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010731 {"CS_XBS5_ILP32_OFFBIG_LINTFLAGS", _CS_XBS5_ILP32_OFFBIG_LINTFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010732#endif
10733#ifdef _CS_XBS5_LP64_OFF64_CFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010734 {"CS_XBS5_LP64_OFF64_CFLAGS", _CS_XBS5_LP64_OFF64_CFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010735#endif
10736#ifdef _CS_XBS5_LP64_OFF64_LDFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010737 {"CS_XBS5_LP64_OFF64_LDFLAGS", _CS_XBS5_LP64_OFF64_LDFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010738#endif
10739#ifdef _CS_XBS5_LP64_OFF64_LIBS
Victor Stinner8c62be82010-05-06 00:08:46 +000010740 {"CS_XBS5_LP64_OFF64_LIBS", _CS_XBS5_LP64_OFF64_LIBS},
Fred Drakec9680921999-12-13 16:37:25 +000010741#endif
10742#ifdef _CS_XBS5_LP64_OFF64_LINTFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010743 {"CS_XBS5_LP64_OFF64_LINTFLAGS", _CS_XBS5_LP64_OFF64_LINTFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010744#endif
10745#ifdef _CS_XBS5_LPBIG_OFFBIG_CFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010746 {"CS_XBS5_LPBIG_OFFBIG_CFLAGS", _CS_XBS5_LPBIG_OFFBIG_CFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010747#endif
10748#ifdef _CS_XBS5_LPBIG_OFFBIG_LDFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010749 {"CS_XBS5_LPBIG_OFFBIG_LDFLAGS", _CS_XBS5_LPBIG_OFFBIG_LDFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010750#endif
10751#ifdef _CS_XBS5_LPBIG_OFFBIG_LIBS
Victor Stinner8c62be82010-05-06 00:08:46 +000010752 {"CS_XBS5_LPBIG_OFFBIG_LIBS", _CS_XBS5_LPBIG_OFFBIG_LIBS},
Fred Drakec9680921999-12-13 16:37:25 +000010753#endif
10754#ifdef _CS_XBS5_LPBIG_OFFBIG_LINTFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010755 {"CS_XBS5_LPBIG_OFFBIG_LINTFLAGS", _CS_XBS5_LPBIG_OFFBIG_LINTFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010756#endif
Fred Draked86ed291999-12-15 15:34:33 +000010757#ifdef _MIPS_CS_AVAIL_PROCESSORS
Victor Stinner8c62be82010-05-06 00:08:46 +000010758 {"MIPS_CS_AVAIL_PROCESSORS", _MIPS_CS_AVAIL_PROCESSORS},
Fred Draked86ed291999-12-15 15:34:33 +000010759#endif
10760#ifdef _MIPS_CS_BASE
Victor Stinner8c62be82010-05-06 00:08:46 +000010761 {"MIPS_CS_BASE", _MIPS_CS_BASE},
Fred Draked86ed291999-12-15 15:34:33 +000010762#endif
10763#ifdef _MIPS_CS_HOSTID
Victor Stinner8c62be82010-05-06 00:08:46 +000010764 {"MIPS_CS_HOSTID", _MIPS_CS_HOSTID},
Fred Draked86ed291999-12-15 15:34:33 +000010765#endif
10766#ifdef _MIPS_CS_HW_NAME
Victor Stinner8c62be82010-05-06 00:08:46 +000010767 {"MIPS_CS_HW_NAME", _MIPS_CS_HW_NAME},
Fred Draked86ed291999-12-15 15:34:33 +000010768#endif
10769#ifdef _MIPS_CS_NUM_PROCESSORS
Victor Stinner8c62be82010-05-06 00:08:46 +000010770 {"MIPS_CS_NUM_PROCESSORS", _MIPS_CS_NUM_PROCESSORS},
Fred Draked86ed291999-12-15 15:34:33 +000010771#endif
10772#ifdef _MIPS_CS_OSREL_MAJ
Victor Stinner8c62be82010-05-06 00:08:46 +000010773 {"MIPS_CS_OSREL_MAJ", _MIPS_CS_OSREL_MAJ},
Fred Draked86ed291999-12-15 15:34:33 +000010774#endif
10775#ifdef _MIPS_CS_OSREL_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000010776 {"MIPS_CS_OSREL_MIN", _MIPS_CS_OSREL_MIN},
Fred Draked86ed291999-12-15 15:34:33 +000010777#endif
10778#ifdef _MIPS_CS_OSREL_PATCH
Victor Stinner8c62be82010-05-06 00:08:46 +000010779 {"MIPS_CS_OSREL_PATCH", _MIPS_CS_OSREL_PATCH},
Fred Draked86ed291999-12-15 15:34:33 +000010780#endif
10781#ifdef _MIPS_CS_OS_NAME
Victor Stinner8c62be82010-05-06 00:08:46 +000010782 {"MIPS_CS_OS_NAME", _MIPS_CS_OS_NAME},
Fred Draked86ed291999-12-15 15:34:33 +000010783#endif
10784#ifdef _MIPS_CS_OS_PROVIDER
Victor Stinner8c62be82010-05-06 00:08:46 +000010785 {"MIPS_CS_OS_PROVIDER", _MIPS_CS_OS_PROVIDER},
Fred Draked86ed291999-12-15 15:34:33 +000010786#endif
10787#ifdef _MIPS_CS_PROCESSORS
Victor Stinner8c62be82010-05-06 00:08:46 +000010788 {"MIPS_CS_PROCESSORS", _MIPS_CS_PROCESSORS},
Fred Draked86ed291999-12-15 15:34:33 +000010789#endif
10790#ifdef _MIPS_CS_SERIAL
Victor Stinner8c62be82010-05-06 00:08:46 +000010791 {"MIPS_CS_SERIAL", _MIPS_CS_SERIAL},
Fred Draked86ed291999-12-15 15:34:33 +000010792#endif
10793#ifdef _MIPS_CS_VENDOR
Victor Stinner8c62be82010-05-06 00:08:46 +000010794 {"MIPS_CS_VENDOR", _MIPS_CS_VENDOR},
Fred Draked86ed291999-12-15 15:34:33 +000010795#endif
Fred Drakec9680921999-12-13 16:37:25 +000010796};
10797
10798static int
Fredrik Lundhff7df9d2000-07-08 22:48:53 +000010799conv_confstr_confname(PyObject *arg, int *valuep)
Fred Drakec9680921999-12-13 16:37:25 +000010800{
10801 return conv_confname(arg, valuep, posix_constants_confstr,
10802 sizeof(posix_constants_confstr)
10803 / sizeof(struct constdef));
10804}
10805
Larry Hastings2f936352014-08-05 14:04:04 +100010806
10807/*[clinic input]
10808os.confstr
10809
10810 name: confstr_confname
10811 /
10812
10813Return a string-valued system configuration variable.
10814[clinic start generated code]*/
10815
Larry Hastings2f936352014-08-05 14:04:04 +100010816static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010817os_confstr_impl(PyObject *module, int name)
10818/*[clinic end generated code: output=bfb0b1b1e49b9383 input=18fb4d0567242e65]*/
Fred Drakec9680921999-12-13 16:37:25 +000010819{
10820 PyObject *result = NULL;
Victor Stinnercb043522010-09-10 23:49:04 +000010821 char buffer[255];
Victor Stinnerdd3a6a52013-06-25 23:13:47 +020010822 size_t len;
Fred Drakec9680921999-12-13 16:37:25 +000010823
Victor Stinnercb043522010-09-10 23:49:04 +000010824 errno = 0;
10825 len = confstr(name, buffer, sizeof(buffer));
10826 if (len == 0) {
10827 if (errno) {
10828 posix_error();
10829 return NULL;
Fred Drakec9680921999-12-13 16:37:25 +000010830 }
10831 else {
Victor Stinnercb043522010-09-10 23:49:04 +000010832 Py_RETURN_NONE;
Fred Drakec9680921999-12-13 16:37:25 +000010833 }
10834 }
Victor Stinnercb043522010-09-10 23:49:04 +000010835
Victor Stinnerdd3a6a52013-06-25 23:13:47 +020010836 if (len >= sizeof(buffer)) {
Victor Stinnercbc18f32014-12-05 22:51:51 +010010837 size_t len2;
Victor Stinnercb043522010-09-10 23:49:04 +000010838 char *buf = PyMem_Malloc(len);
10839 if (buf == NULL)
10840 return PyErr_NoMemory();
Victor Stinnercbc18f32014-12-05 22:51:51 +010010841 len2 = confstr(name, buf, len);
10842 assert(len == len2);
Christian Heimes8714cfd2015-04-21 10:57:41 +020010843 result = PyUnicode_DecodeFSDefaultAndSize(buf, len2-1);
Victor Stinnercb043522010-09-10 23:49:04 +000010844 PyMem_Free(buf);
10845 }
10846 else
10847 result = PyUnicode_DecodeFSDefaultAndSize(buffer, len-1);
Fred Drakec9680921999-12-13 16:37:25 +000010848 return result;
10849}
Larry Hastings2f936352014-08-05 14:04:04 +100010850#endif /* HAVE_CONFSTR */
Fred Drakec9680921999-12-13 16:37:25 +000010851
10852
10853#ifdef HAVE_SYSCONF
10854static struct constdef posix_constants_sysconf[] = {
10855#ifdef _SC_2_CHAR_TERM
Victor Stinner8c62be82010-05-06 00:08:46 +000010856 {"SC_2_CHAR_TERM", _SC_2_CHAR_TERM},
Fred Drakec9680921999-12-13 16:37:25 +000010857#endif
10858#ifdef _SC_2_C_BIND
Victor Stinner8c62be82010-05-06 00:08:46 +000010859 {"SC_2_C_BIND", _SC_2_C_BIND},
Fred Drakec9680921999-12-13 16:37:25 +000010860#endif
10861#ifdef _SC_2_C_DEV
Victor Stinner8c62be82010-05-06 00:08:46 +000010862 {"SC_2_C_DEV", _SC_2_C_DEV},
Fred Drakec9680921999-12-13 16:37:25 +000010863#endif
10864#ifdef _SC_2_C_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000010865 {"SC_2_C_VERSION", _SC_2_C_VERSION},
Fred Drakec9680921999-12-13 16:37:25 +000010866#endif
10867#ifdef _SC_2_FORT_DEV
Victor Stinner8c62be82010-05-06 00:08:46 +000010868 {"SC_2_FORT_DEV", _SC_2_FORT_DEV},
Fred Drakec9680921999-12-13 16:37:25 +000010869#endif
10870#ifdef _SC_2_FORT_RUN
Victor Stinner8c62be82010-05-06 00:08:46 +000010871 {"SC_2_FORT_RUN", _SC_2_FORT_RUN},
Fred Drakec9680921999-12-13 16:37:25 +000010872#endif
10873#ifdef _SC_2_LOCALEDEF
Victor Stinner8c62be82010-05-06 00:08:46 +000010874 {"SC_2_LOCALEDEF", _SC_2_LOCALEDEF},
Fred Drakec9680921999-12-13 16:37:25 +000010875#endif
10876#ifdef _SC_2_SW_DEV
Victor Stinner8c62be82010-05-06 00:08:46 +000010877 {"SC_2_SW_DEV", _SC_2_SW_DEV},
Fred Drakec9680921999-12-13 16:37:25 +000010878#endif
10879#ifdef _SC_2_UPE
Victor Stinner8c62be82010-05-06 00:08:46 +000010880 {"SC_2_UPE", _SC_2_UPE},
Fred Drakec9680921999-12-13 16:37:25 +000010881#endif
10882#ifdef _SC_2_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000010883 {"SC_2_VERSION", _SC_2_VERSION},
Fred Drakec9680921999-12-13 16:37:25 +000010884#endif
Fred Draked86ed291999-12-15 15:34:33 +000010885#ifdef _SC_ABI_ASYNCHRONOUS_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000010886 {"SC_ABI_ASYNCHRONOUS_IO", _SC_ABI_ASYNCHRONOUS_IO},
Fred Draked86ed291999-12-15 15:34:33 +000010887#endif
10888#ifdef _SC_ACL
Victor Stinner8c62be82010-05-06 00:08:46 +000010889 {"SC_ACL", _SC_ACL},
Fred Draked86ed291999-12-15 15:34:33 +000010890#endif
Fred Drakec9680921999-12-13 16:37:25 +000010891#ifdef _SC_AIO_LISTIO_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010892 {"SC_AIO_LISTIO_MAX", _SC_AIO_LISTIO_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010893#endif
Fred Drakec9680921999-12-13 16:37:25 +000010894#ifdef _SC_AIO_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010895 {"SC_AIO_MAX", _SC_AIO_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010896#endif
10897#ifdef _SC_AIO_PRIO_DELTA_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010898 {"SC_AIO_PRIO_DELTA_MAX", _SC_AIO_PRIO_DELTA_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010899#endif
10900#ifdef _SC_ARG_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010901 {"SC_ARG_MAX", _SC_ARG_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010902#endif
10903#ifdef _SC_ASYNCHRONOUS_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000010904 {"SC_ASYNCHRONOUS_IO", _SC_ASYNCHRONOUS_IO},
Fred Drakec9680921999-12-13 16:37:25 +000010905#endif
10906#ifdef _SC_ATEXIT_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010907 {"SC_ATEXIT_MAX", _SC_ATEXIT_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010908#endif
Fred Draked86ed291999-12-15 15:34:33 +000010909#ifdef _SC_AUDIT
Victor Stinner8c62be82010-05-06 00:08:46 +000010910 {"SC_AUDIT", _SC_AUDIT},
Fred Draked86ed291999-12-15 15:34:33 +000010911#endif
Fred Drakec9680921999-12-13 16:37:25 +000010912#ifdef _SC_AVPHYS_PAGES
Victor Stinner8c62be82010-05-06 00:08:46 +000010913 {"SC_AVPHYS_PAGES", _SC_AVPHYS_PAGES},
Fred Drakec9680921999-12-13 16:37:25 +000010914#endif
10915#ifdef _SC_BC_BASE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010916 {"SC_BC_BASE_MAX", _SC_BC_BASE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010917#endif
10918#ifdef _SC_BC_DIM_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010919 {"SC_BC_DIM_MAX", _SC_BC_DIM_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010920#endif
10921#ifdef _SC_BC_SCALE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010922 {"SC_BC_SCALE_MAX", _SC_BC_SCALE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010923#endif
10924#ifdef _SC_BC_STRING_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010925 {"SC_BC_STRING_MAX", _SC_BC_STRING_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010926#endif
Fred Draked86ed291999-12-15 15:34:33 +000010927#ifdef _SC_CAP
Victor Stinner8c62be82010-05-06 00:08:46 +000010928 {"SC_CAP", _SC_CAP},
Fred Draked86ed291999-12-15 15:34:33 +000010929#endif
Fred Drakec9680921999-12-13 16:37:25 +000010930#ifdef _SC_CHARCLASS_NAME_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010931 {"SC_CHARCLASS_NAME_MAX", _SC_CHARCLASS_NAME_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010932#endif
10933#ifdef _SC_CHAR_BIT
Victor Stinner8c62be82010-05-06 00:08:46 +000010934 {"SC_CHAR_BIT", _SC_CHAR_BIT},
Fred Drakec9680921999-12-13 16:37:25 +000010935#endif
10936#ifdef _SC_CHAR_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010937 {"SC_CHAR_MAX", _SC_CHAR_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010938#endif
10939#ifdef _SC_CHAR_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000010940 {"SC_CHAR_MIN", _SC_CHAR_MIN},
Fred Drakec9680921999-12-13 16:37:25 +000010941#endif
10942#ifdef _SC_CHILD_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010943 {"SC_CHILD_MAX", _SC_CHILD_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010944#endif
10945#ifdef _SC_CLK_TCK
Victor Stinner8c62be82010-05-06 00:08:46 +000010946 {"SC_CLK_TCK", _SC_CLK_TCK},
Fred Drakec9680921999-12-13 16:37:25 +000010947#endif
10948#ifdef _SC_COHER_BLKSZ
Victor Stinner8c62be82010-05-06 00:08:46 +000010949 {"SC_COHER_BLKSZ", _SC_COHER_BLKSZ},
Fred Drakec9680921999-12-13 16:37:25 +000010950#endif
10951#ifdef _SC_COLL_WEIGHTS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010952 {"SC_COLL_WEIGHTS_MAX", _SC_COLL_WEIGHTS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010953#endif
10954#ifdef _SC_DCACHE_ASSOC
Victor Stinner8c62be82010-05-06 00:08:46 +000010955 {"SC_DCACHE_ASSOC", _SC_DCACHE_ASSOC},
Fred Drakec9680921999-12-13 16:37:25 +000010956#endif
10957#ifdef _SC_DCACHE_BLKSZ
Victor Stinner8c62be82010-05-06 00:08:46 +000010958 {"SC_DCACHE_BLKSZ", _SC_DCACHE_BLKSZ},
Fred Drakec9680921999-12-13 16:37:25 +000010959#endif
10960#ifdef _SC_DCACHE_LINESZ
Victor Stinner8c62be82010-05-06 00:08:46 +000010961 {"SC_DCACHE_LINESZ", _SC_DCACHE_LINESZ},
Fred Drakec9680921999-12-13 16:37:25 +000010962#endif
10963#ifdef _SC_DCACHE_SZ
Victor Stinner8c62be82010-05-06 00:08:46 +000010964 {"SC_DCACHE_SZ", _SC_DCACHE_SZ},
Fred Drakec9680921999-12-13 16:37:25 +000010965#endif
10966#ifdef _SC_DCACHE_TBLKSZ
Victor Stinner8c62be82010-05-06 00:08:46 +000010967 {"SC_DCACHE_TBLKSZ", _SC_DCACHE_TBLKSZ},
Fred Drakec9680921999-12-13 16:37:25 +000010968#endif
10969#ifdef _SC_DELAYTIMER_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010970 {"SC_DELAYTIMER_MAX", _SC_DELAYTIMER_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010971#endif
10972#ifdef _SC_EQUIV_CLASS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010973 {"SC_EQUIV_CLASS_MAX", _SC_EQUIV_CLASS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010974#endif
10975#ifdef _SC_EXPR_NEST_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010976 {"SC_EXPR_NEST_MAX", _SC_EXPR_NEST_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010977#endif
10978#ifdef _SC_FSYNC
Victor Stinner8c62be82010-05-06 00:08:46 +000010979 {"SC_FSYNC", _SC_FSYNC},
Fred Drakec9680921999-12-13 16:37:25 +000010980#endif
10981#ifdef _SC_GETGR_R_SIZE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010982 {"SC_GETGR_R_SIZE_MAX", _SC_GETGR_R_SIZE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010983#endif
10984#ifdef _SC_GETPW_R_SIZE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010985 {"SC_GETPW_R_SIZE_MAX", _SC_GETPW_R_SIZE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010986#endif
10987#ifdef _SC_ICACHE_ASSOC
Victor Stinner8c62be82010-05-06 00:08:46 +000010988 {"SC_ICACHE_ASSOC", _SC_ICACHE_ASSOC},
Fred Drakec9680921999-12-13 16:37:25 +000010989#endif
10990#ifdef _SC_ICACHE_BLKSZ
Victor Stinner8c62be82010-05-06 00:08:46 +000010991 {"SC_ICACHE_BLKSZ", _SC_ICACHE_BLKSZ},
Fred Drakec9680921999-12-13 16:37:25 +000010992#endif
10993#ifdef _SC_ICACHE_LINESZ
Victor Stinner8c62be82010-05-06 00:08:46 +000010994 {"SC_ICACHE_LINESZ", _SC_ICACHE_LINESZ},
Fred Drakec9680921999-12-13 16:37:25 +000010995#endif
10996#ifdef _SC_ICACHE_SZ
Victor Stinner8c62be82010-05-06 00:08:46 +000010997 {"SC_ICACHE_SZ", _SC_ICACHE_SZ},
Fred Drakec9680921999-12-13 16:37:25 +000010998#endif
Fred Draked86ed291999-12-15 15:34:33 +000010999#ifdef _SC_INF
Victor Stinner8c62be82010-05-06 00:08:46 +000011000 {"SC_INF", _SC_INF},
Fred Draked86ed291999-12-15 15:34:33 +000011001#endif
Fred Drakec9680921999-12-13 16:37:25 +000011002#ifdef _SC_INT_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011003 {"SC_INT_MAX", _SC_INT_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011004#endif
11005#ifdef _SC_INT_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000011006 {"SC_INT_MIN", _SC_INT_MIN},
Fred Drakec9680921999-12-13 16:37:25 +000011007#endif
11008#ifdef _SC_IOV_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011009 {"SC_IOV_MAX", _SC_IOV_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011010#endif
Fred Draked86ed291999-12-15 15:34:33 +000011011#ifdef _SC_IP_SECOPTS
Victor Stinner8c62be82010-05-06 00:08:46 +000011012 {"SC_IP_SECOPTS", _SC_IP_SECOPTS},
Fred Draked86ed291999-12-15 15:34:33 +000011013#endif
Fred Drakec9680921999-12-13 16:37:25 +000011014#ifdef _SC_JOB_CONTROL
Victor Stinner8c62be82010-05-06 00:08:46 +000011015 {"SC_JOB_CONTROL", _SC_JOB_CONTROL},
Fred Drakec9680921999-12-13 16:37:25 +000011016#endif
Fred Draked86ed291999-12-15 15:34:33 +000011017#ifdef _SC_KERN_POINTERS
Victor Stinner8c62be82010-05-06 00:08:46 +000011018 {"SC_KERN_POINTERS", _SC_KERN_POINTERS},
Fred Draked86ed291999-12-15 15:34:33 +000011019#endif
11020#ifdef _SC_KERN_SIM
Victor Stinner8c62be82010-05-06 00:08:46 +000011021 {"SC_KERN_SIM", _SC_KERN_SIM},
Fred Draked86ed291999-12-15 15:34:33 +000011022#endif
Fred Drakec9680921999-12-13 16:37:25 +000011023#ifdef _SC_LINE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011024 {"SC_LINE_MAX", _SC_LINE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011025#endif
11026#ifdef _SC_LOGIN_NAME_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011027 {"SC_LOGIN_NAME_MAX", _SC_LOGIN_NAME_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011028#endif
11029#ifdef _SC_LOGNAME_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011030 {"SC_LOGNAME_MAX", _SC_LOGNAME_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011031#endif
11032#ifdef _SC_LONG_BIT
Victor Stinner8c62be82010-05-06 00:08:46 +000011033 {"SC_LONG_BIT", _SC_LONG_BIT},
Fred Drakec9680921999-12-13 16:37:25 +000011034#endif
Fred Draked86ed291999-12-15 15:34:33 +000011035#ifdef _SC_MAC
Victor Stinner8c62be82010-05-06 00:08:46 +000011036 {"SC_MAC", _SC_MAC},
Fred Draked86ed291999-12-15 15:34:33 +000011037#endif
Fred Drakec9680921999-12-13 16:37:25 +000011038#ifdef _SC_MAPPED_FILES
Victor Stinner8c62be82010-05-06 00:08:46 +000011039 {"SC_MAPPED_FILES", _SC_MAPPED_FILES},
Fred Drakec9680921999-12-13 16:37:25 +000011040#endif
11041#ifdef _SC_MAXPID
Victor Stinner8c62be82010-05-06 00:08:46 +000011042 {"SC_MAXPID", _SC_MAXPID},
Fred Drakec9680921999-12-13 16:37:25 +000011043#endif
11044#ifdef _SC_MB_LEN_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011045 {"SC_MB_LEN_MAX", _SC_MB_LEN_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011046#endif
11047#ifdef _SC_MEMLOCK
Victor Stinner8c62be82010-05-06 00:08:46 +000011048 {"SC_MEMLOCK", _SC_MEMLOCK},
Fred Drakec9680921999-12-13 16:37:25 +000011049#endif
11050#ifdef _SC_MEMLOCK_RANGE
Victor Stinner8c62be82010-05-06 00:08:46 +000011051 {"SC_MEMLOCK_RANGE", _SC_MEMLOCK_RANGE},
Fred Drakec9680921999-12-13 16:37:25 +000011052#endif
11053#ifdef _SC_MEMORY_PROTECTION
Victor Stinner8c62be82010-05-06 00:08:46 +000011054 {"SC_MEMORY_PROTECTION", _SC_MEMORY_PROTECTION},
Fred Drakec9680921999-12-13 16:37:25 +000011055#endif
11056#ifdef _SC_MESSAGE_PASSING
Victor Stinner8c62be82010-05-06 00:08:46 +000011057 {"SC_MESSAGE_PASSING", _SC_MESSAGE_PASSING},
Fred Drakec9680921999-12-13 16:37:25 +000011058#endif
Fred Draked86ed291999-12-15 15:34:33 +000011059#ifdef _SC_MMAP_FIXED_ALIGNMENT
Victor Stinner8c62be82010-05-06 00:08:46 +000011060 {"SC_MMAP_FIXED_ALIGNMENT", _SC_MMAP_FIXED_ALIGNMENT},
Fred Draked86ed291999-12-15 15:34:33 +000011061#endif
Fred Drakec9680921999-12-13 16:37:25 +000011062#ifdef _SC_MQ_OPEN_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011063 {"SC_MQ_OPEN_MAX", _SC_MQ_OPEN_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011064#endif
11065#ifdef _SC_MQ_PRIO_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011066 {"SC_MQ_PRIO_MAX", _SC_MQ_PRIO_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011067#endif
Fred Draked86ed291999-12-15 15:34:33 +000011068#ifdef _SC_NACLS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011069 {"SC_NACLS_MAX", _SC_NACLS_MAX},
Fred Draked86ed291999-12-15 15:34:33 +000011070#endif
Fred Drakec9680921999-12-13 16:37:25 +000011071#ifdef _SC_NGROUPS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011072 {"SC_NGROUPS_MAX", _SC_NGROUPS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011073#endif
11074#ifdef _SC_NL_ARGMAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011075 {"SC_NL_ARGMAX", _SC_NL_ARGMAX},
Fred Drakec9680921999-12-13 16:37:25 +000011076#endif
11077#ifdef _SC_NL_LANGMAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011078 {"SC_NL_LANGMAX", _SC_NL_LANGMAX},
Fred Drakec9680921999-12-13 16:37:25 +000011079#endif
11080#ifdef _SC_NL_MSGMAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011081 {"SC_NL_MSGMAX", _SC_NL_MSGMAX},
Fred Drakec9680921999-12-13 16:37:25 +000011082#endif
11083#ifdef _SC_NL_NMAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011084 {"SC_NL_NMAX", _SC_NL_NMAX},
Fred Drakec9680921999-12-13 16:37:25 +000011085#endif
11086#ifdef _SC_NL_SETMAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011087 {"SC_NL_SETMAX", _SC_NL_SETMAX},
Fred Drakec9680921999-12-13 16:37:25 +000011088#endif
11089#ifdef _SC_NL_TEXTMAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011090 {"SC_NL_TEXTMAX", _SC_NL_TEXTMAX},
Fred Drakec9680921999-12-13 16:37:25 +000011091#endif
11092#ifdef _SC_NPROCESSORS_CONF
Victor Stinner8c62be82010-05-06 00:08:46 +000011093 {"SC_NPROCESSORS_CONF", _SC_NPROCESSORS_CONF},
Fred Drakec9680921999-12-13 16:37:25 +000011094#endif
11095#ifdef _SC_NPROCESSORS_ONLN
Victor Stinner8c62be82010-05-06 00:08:46 +000011096 {"SC_NPROCESSORS_ONLN", _SC_NPROCESSORS_ONLN},
Fred Drakec9680921999-12-13 16:37:25 +000011097#endif
Fred Draked86ed291999-12-15 15:34:33 +000011098#ifdef _SC_NPROC_CONF
Victor Stinner8c62be82010-05-06 00:08:46 +000011099 {"SC_NPROC_CONF", _SC_NPROC_CONF},
Fred Draked86ed291999-12-15 15:34:33 +000011100#endif
11101#ifdef _SC_NPROC_ONLN
Victor Stinner8c62be82010-05-06 00:08:46 +000011102 {"SC_NPROC_ONLN", _SC_NPROC_ONLN},
Fred Draked86ed291999-12-15 15:34:33 +000011103#endif
Fred Drakec9680921999-12-13 16:37:25 +000011104#ifdef _SC_NZERO
Victor Stinner8c62be82010-05-06 00:08:46 +000011105 {"SC_NZERO", _SC_NZERO},
Fred Drakec9680921999-12-13 16:37:25 +000011106#endif
11107#ifdef _SC_OPEN_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011108 {"SC_OPEN_MAX", _SC_OPEN_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011109#endif
11110#ifdef _SC_PAGESIZE
Victor Stinner8c62be82010-05-06 00:08:46 +000011111 {"SC_PAGESIZE", _SC_PAGESIZE},
Fred Drakec9680921999-12-13 16:37:25 +000011112#endif
11113#ifdef _SC_PAGE_SIZE
Victor Stinner8c62be82010-05-06 00:08:46 +000011114 {"SC_PAGE_SIZE", _SC_PAGE_SIZE},
Fred Drakec9680921999-12-13 16:37:25 +000011115#endif
11116#ifdef _SC_PASS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011117 {"SC_PASS_MAX", _SC_PASS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011118#endif
11119#ifdef _SC_PHYS_PAGES
Victor Stinner8c62be82010-05-06 00:08:46 +000011120 {"SC_PHYS_PAGES", _SC_PHYS_PAGES},
Fred Drakec9680921999-12-13 16:37:25 +000011121#endif
11122#ifdef _SC_PII
Victor Stinner8c62be82010-05-06 00:08:46 +000011123 {"SC_PII", _SC_PII},
Fred Drakec9680921999-12-13 16:37:25 +000011124#endif
11125#ifdef _SC_PII_INTERNET
Victor Stinner8c62be82010-05-06 00:08:46 +000011126 {"SC_PII_INTERNET", _SC_PII_INTERNET},
Fred Drakec9680921999-12-13 16:37:25 +000011127#endif
11128#ifdef _SC_PII_INTERNET_DGRAM
Victor Stinner8c62be82010-05-06 00:08:46 +000011129 {"SC_PII_INTERNET_DGRAM", _SC_PII_INTERNET_DGRAM},
Fred Drakec9680921999-12-13 16:37:25 +000011130#endif
11131#ifdef _SC_PII_INTERNET_STREAM
Victor Stinner8c62be82010-05-06 00:08:46 +000011132 {"SC_PII_INTERNET_STREAM", _SC_PII_INTERNET_STREAM},
Fred Drakec9680921999-12-13 16:37:25 +000011133#endif
11134#ifdef _SC_PII_OSI
Victor Stinner8c62be82010-05-06 00:08:46 +000011135 {"SC_PII_OSI", _SC_PII_OSI},
Fred Drakec9680921999-12-13 16:37:25 +000011136#endif
11137#ifdef _SC_PII_OSI_CLTS
Victor Stinner8c62be82010-05-06 00:08:46 +000011138 {"SC_PII_OSI_CLTS", _SC_PII_OSI_CLTS},
Fred Drakec9680921999-12-13 16:37:25 +000011139#endif
11140#ifdef _SC_PII_OSI_COTS
Victor Stinner8c62be82010-05-06 00:08:46 +000011141 {"SC_PII_OSI_COTS", _SC_PII_OSI_COTS},
Fred Drakec9680921999-12-13 16:37:25 +000011142#endif
11143#ifdef _SC_PII_OSI_M
Victor Stinner8c62be82010-05-06 00:08:46 +000011144 {"SC_PII_OSI_M", _SC_PII_OSI_M},
Fred Drakec9680921999-12-13 16:37:25 +000011145#endif
11146#ifdef _SC_PII_SOCKET
Victor Stinner8c62be82010-05-06 00:08:46 +000011147 {"SC_PII_SOCKET", _SC_PII_SOCKET},
Fred Drakec9680921999-12-13 16:37:25 +000011148#endif
11149#ifdef _SC_PII_XTI
Victor Stinner8c62be82010-05-06 00:08:46 +000011150 {"SC_PII_XTI", _SC_PII_XTI},
Fred Drakec9680921999-12-13 16:37:25 +000011151#endif
11152#ifdef _SC_POLL
Victor Stinner8c62be82010-05-06 00:08:46 +000011153 {"SC_POLL", _SC_POLL},
Fred Drakec9680921999-12-13 16:37:25 +000011154#endif
11155#ifdef _SC_PRIORITIZED_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000011156 {"SC_PRIORITIZED_IO", _SC_PRIORITIZED_IO},
Fred Drakec9680921999-12-13 16:37:25 +000011157#endif
11158#ifdef _SC_PRIORITY_SCHEDULING
Victor Stinner8c62be82010-05-06 00:08:46 +000011159 {"SC_PRIORITY_SCHEDULING", _SC_PRIORITY_SCHEDULING},
Fred Drakec9680921999-12-13 16:37:25 +000011160#endif
11161#ifdef _SC_REALTIME_SIGNALS
Victor Stinner8c62be82010-05-06 00:08:46 +000011162 {"SC_REALTIME_SIGNALS", _SC_REALTIME_SIGNALS},
Fred Drakec9680921999-12-13 16:37:25 +000011163#endif
11164#ifdef _SC_RE_DUP_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011165 {"SC_RE_DUP_MAX", _SC_RE_DUP_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011166#endif
11167#ifdef _SC_RTSIG_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011168 {"SC_RTSIG_MAX", _SC_RTSIG_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011169#endif
11170#ifdef _SC_SAVED_IDS
Victor Stinner8c62be82010-05-06 00:08:46 +000011171 {"SC_SAVED_IDS", _SC_SAVED_IDS},
Fred Drakec9680921999-12-13 16:37:25 +000011172#endif
11173#ifdef _SC_SCHAR_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011174 {"SC_SCHAR_MAX", _SC_SCHAR_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011175#endif
11176#ifdef _SC_SCHAR_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000011177 {"SC_SCHAR_MIN", _SC_SCHAR_MIN},
Fred Drakec9680921999-12-13 16:37:25 +000011178#endif
11179#ifdef _SC_SELECT
Victor Stinner8c62be82010-05-06 00:08:46 +000011180 {"SC_SELECT", _SC_SELECT},
Fred Drakec9680921999-12-13 16:37:25 +000011181#endif
11182#ifdef _SC_SEMAPHORES
Victor Stinner8c62be82010-05-06 00:08:46 +000011183 {"SC_SEMAPHORES", _SC_SEMAPHORES},
Fred Drakec9680921999-12-13 16:37:25 +000011184#endif
11185#ifdef _SC_SEM_NSEMS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011186 {"SC_SEM_NSEMS_MAX", _SC_SEM_NSEMS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011187#endif
11188#ifdef _SC_SEM_VALUE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011189 {"SC_SEM_VALUE_MAX", _SC_SEM_VALUE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011190#endif
11191#ifdef _SC_SHARED_MEMORY_OBJECTS
Victor Stinner8c62be82010-05-06 00:08:46 +000011192 {"SC_SHARED_MEMORY_OBJECTS", _SC_SHARED_MEMORY_OBJECTS},
Fred Drakec9680921999-12-13 16:37:25 +000011193#endif
11194#ifdef _SC_SHRT_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011195 {"SC_SHRT_MAX", _SC_SHRT_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011196#endif
11197#ifdef _SC_SHRT_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000011198 {"SC_SHRT_MIN", _SC_SHRT_MIN},
Fred Drakec9680921999-12-13 16:37:25 +000011199#endif
11200#ifdef _SC_SIGQUEUE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011201 {"SC_SIGQUEUE_MAX", _SC_SIGQUEUE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011202#endif
11203#ifdef _SC_SIGRT_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011204 {"SC_SIGRT_MAX", _SC_SIGRT_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011205#endif
11206#ifdef _SC_SIGRT_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000011207 {"SC_SIGRT_MIN", _SC_SIGRT_MIN},
Fred Drakec9680921999-12-13 16:37:25 +000011208#endif
Fred Draked86ed291999-12-15 15:34:33 +000011209#ifdef _SC_SOFTPOWER
Victor Stinner8c62be82010-05-06 00:08:46 +000011210 {"SC_SOFTPOWER", _SC_SOFTPOWER},
Fred Draked86ed291999-12-15 15:34:33 +000011211#endif
Fred Drakec9680921999-12-13 16:37:25 +000011212#ifdef _SC_SPLIT_CACHE
Victor Stinner8c62be82010-05-06 00:08:46 +000011213 {"SC_SPLIT_CACHE", _SC_SPLIT_CACHE},
Fred Drakec9680921999-12-13 16:37:25 +000011214#endif
11215#ifdef _SC_SSIZE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011216 {"SC_SSIZE_MAX", _SC_SSIZE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011217#endif
11218#ifdef _SC_STACK_PROT
Victor Stinner8c62be82010-05-06 00:08:46 +000011219 {"SC_STACK_PROT", _SC_STACK_PROT},
Fred Drakec9680921999-12-13 16:37:25 +000011220#endif
11221#ifdef _SC_STREAM_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011222 {"SC_STREAM_MAX", _SC_STREAM_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011223#endif
11224#ifdef _SC_SYNCHRONIZED_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000011225 {"SC_SYNCHRONIZED_IO", _SC_SYNCHRONIZED_IO},
Fred Drakec9680921999-12-13 16:37:25 +000011226#endif
11227#ifdef _SC_THREADS
Victor Stinner8c62be82010-05-06 00:08:46 +000011228 {"SC_THREADS", _SC_THREADS},
Fred Drakec9680921999-12-13 16:37:25 +000011229#endif
11230#ifdef _SC_THREAD_ATTR_STACKADDR
Victor Stinner8c62be82010-05-06 00:08:46 +000011231 {"SC_THREAD_ATTR_STACKADDR", _SC_THREAD_ATTR_STACKADDR},
Fred Drakec9680921999-12-13 16:37:25 +000011232#endif
11233#ifdef _SC_THREAD_ATTR_STACKSIZE
Victor Stinner8c62be82010-05-06 00:08:46 +000011234 {"SC_THREAD_ATTR_STACKSIZE", _SC_THREAD_ATTR_STACKSIZE},
Fred Drakec9680921999-12-13 16:37:25 +000011235#endif
11236#ifdef _SC_THREAD_DESTRUCTOR_ITERATIONS
Victor Stinner8c62be82010-05-06 00:08:46 +000011237 {"SC_THREAD_DESTRUCTOR_ITERATIONS", _SC_THREAD_DESTRUCTOR_ITERATIONS},
Fred Drakec9680921999-12-13 16:37:25 +000011238#endif
11239#ifdef _SC_THREAD_KEYS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011240 {"SC_THREAD_KEYS_MAX", _SC_THREAD_KEYS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011241#endif
11242#ifdef _SC_THREAD_PRIORITY_SCHEDULING
Victor Stinner8c62be82010-05-06 00:08:46 +000011243 {"SC_THREAD_PRIORITY_SCHEDULING", _SC_THREAD_PRIORITY_SCHEDULING},
Fred Drakec9680921999-12-13 16:37:25 +000011244#endif
11245#ifdef _SC_THREAD_PRIO_INHERIT
Victor Stinner8c62be82010-05-06 00:08:46 +000011246 {"SC_THREAD_PRIO_INHERIT", _SC_THREAD_PRIO_INHERIT},
Fred Drakec9680921999-12-13 16:37:25 +000011247#endif
11248#ifdef _SC_THREAD_PRIO_PROTECT
Victor Stinner8c62be82010-05-06 00:08:46 +000011249 {"SC_THREAD_PRIO_PROTECT", _SC_THREAD_PRIO_PROTECT},
Fred Drakec9680921999-12-13 16:37:25 +000011250#endif
11251#ifdef _SC_THREAD_PROCESS_SHARED
Victor Stinner8c62be82010-05-06 00:08:46 +000011252 {"SC_THREAD_PROCESS_SHARED", _SC_THREAD_PROCESS_SHARED},
Fred Drakec9680921999-12-13 16:37:25 +000011253#endif
11254#ifdef _SC_THREAD_SAFE_FUNCTIONS
Victor Stinner8c62be82010-05-06 00:08:46 +000011255 {"SC_THREAD_SAFE_FUNCTIONS", _SC_THREAD_SAFE_FUNCTIONS},
Fred Drakec9680921999-12-13 16:37:25 +000011256#endif
11257#ifdef _SC_THREAD_STACK_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000011258 {"SC_THREAD_STACK_MIN", _SC_THREAD_STACK_MIN},
Fred Drakec9680921999-12-13 16:37:25 +000011259#endif
11260#ifdef _SC_THREAD_THREADS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011261 {"SC_THREAD_THREADS_MAX", _SC_THREAD_THREADS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011262#endif
11263#ifdef _SC_TIMERS
Victor Stinner8c62be82010-05-06 00:08:46 +000011264 {"SC_TIMERS", _SC_TIMERS},
Fred Drakec9680921999-12-13 16:37:25 +000011265#endif
11266#ifdef _SC_TIMER_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011267 {"SC_TIMER_MAX", _SC_TIMER_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011268#endif
11269#ifdef _SC_TTY_NAME_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011270 {"SC_TTY_NAME_MAX", _SC_TTY_NAME_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011271#endif
11272#ifdef _SC_TZNAME_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011273 {"SC_TZNAME_MAX", _SC_TZNAME_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011274#endif
11275#ifdef _SC_T_IOV_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011276 {"SC_T_IOV_MAX", _SC_T_IOV_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011277#endif
11278#ifdef _SC_UCHAR_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011279 {"SC_UCHAR_MAX", _SC_UCHAR_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011280#endif
11281#ifdef _SC_UINT_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011282 {"SC_UINT_MAX", _SC_UINT_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011283#endif
11284#ifdef _SC_UIO_MAXIOV
Victor Stinner8c62be82010-05-06 00:08:46 +000011285 {"SC_UIO_MAXIOV", _SC_UIO_MAXIOV},
Fred Drakec9680921999-12-13 16:37:25 +000011286#endif
11287#ifdef _SC_ULONG_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011288 {"SC_ULONG_MAX", _SC_ULONG_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011289#endif
11290#ifdef _SC_USHRT_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011291 {"SC_USHRT_MAX", _SC_USHRT_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011292#endif
11293#ifdef _SC_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000011294 {"SC_VERSION", _SC_VERSION},
Fred Drakec9680921999-12-13 16:37:25 +000011295#endif
11296#ifdef _SC_WORD_BIT
Victor Stinner8c62be82010-05-06 00:08:46 +000011297 {"SC_WORD_BIT", _SC_WORD_BIT},
Fred Drakec9680921999-12-13 16:37:25 +000011298#endif
11299#ifdef _SC_XBS5_ILP32_OFF32
Victor Stinner8c62be82010-05-06 00:08:46 +000011300 {"SC_XBS5_ILP32_OFF32", _SC_XBS5_ILP32_OFF32},
Fred Drakec9680921999-12-13 16:37:25 +000011301#endif
11302#ifdef _SC_XBS5_ILP32_OFFBIG
Victor Stinner8c62be82010-05-06 00:08:46 +000011303 {"SC_XBS5_ILP32_OFFBIG", _SC_XBS5_ILP32_OFFBIG},
Fred Drakec9680921999-12-13 16:37:25 +000011304#endif
11305#ifdef _SC_XBS5_LP64_OFF64
Victor Stinner8c62be82010-05-06 00:08:46 +000011306 {"SC_XBS5_LP64_OFF64", _SC_XBS5_LP64_OFF64},
Fred Drakec9680921999-12-13 16:37:25 +000011307#endif
11308#ifdef _SC_XBS5_LPBIG_OFFBIG
Victor Stinner8c62be82010-05-06 00:08:46 +000011309 {"SC_XBS5_LPBIG_OFFBIG", _SC_XBS5_LPBIG_OFFBIG},
Fred Drakec9680921999-12-13 16:37:25 +000011310#endif
11311#ifdef _SC_XOPEN_CRYPT
Victor Stinner8c62be82010-05-06 00:08:46 +000011312 {"SC_XOPEN_CRYPT", _SC_XOPEN_CRYPT},
Fred Drakec9680921999-12-13 16:37:25 +000011313#endif
11314#ifdef _SC_XOPEN_ENH_I18N
Victor Stinner8c62be82010-05-06 00:08:46 +000011315 {"SC_XOPEN_ENH_I18N", _SC_XOPEN_ENH_I18N},
Fred Drakec9680921999-12-13 16:37:25 +000011316#endif
11317#ifdef _SC_XOPEN_LEGACY
Victor Stinner8c62be82010-05-06 00:08:46 +000011318 {"SC_XOPEN_LEGACY", _SC_XOPEN_LEGACY},
Fred Drakec9680921999-12-13 16:37:25 +000011319#endif
11320#ifdef _SC_XOPEN_REALTIME
Victor Stinner8c62be82010-05-06 00:08:46 +000011321 {"SC_XOPEN_REALTIME", _SC_XOPEN_REALTIME},
Fred Drakec9680921999-12-13 16:37:25 +000011322#endif
11323#ifdef _SC_XOPEN_REALTIME_THREADS
Victor Stinner8c62be82010-05-06 00:08:46 +000011324 {"SC_XOPEN_REALTIME_THREADS", _SC_XOPEN_REALTIME_THREADS},
Fred Drakec9680921999-12-13 16:37:25 +000011325#endif
11326#ifdef _SC_XOPEN_SHM
Victor Stinner8c62be82010-05-06 00:08:46 +000011327 {"SC_XOPEN_SHM", _SC_XOPEN_SHM},
Fred Drakec9680921999-12-13 16:37:25 +000011328#endif
11329#ifdef _SC_XOPEN_UNIX
Victor Stinner8c62be82010-05-06 00:08:46 +000011330 {"SC_XOPEN_UNIX", _SC_XOPEN_UNIX},
Fred Drakec9680921999-12-13 16:37:25 +000011331#endif
11332#ifdef _SC_XOPEN_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000011333 {"SC_XOPEN_VERSION", _SC_XOPEN_VERSION},
Fred Drakec9680921999-12-13 16:37:25 +000011334#endif
11335#ifdef _SC_XOPEN_XCU_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000011336 {"SC_XOPEN_XCU_VERSION", _SC_XOPEN_XCU_VERSION},
Fred Drakec9680921999-12-13 16:37:25 +000011337#endif
11338#ifdef _SC_XOPEN_XPG2
Victor Stinner8c62be82010-05-06 00:08:46 +000011339 {"SC_XOPEN_XPG2", _SC_XOPEN_XPG2},
Fred Drakec9680921999-12-13 16:37:25 +000011340#endif
11341#ifdef _SC_XOPEN_XPG3
Victor Stinner8c62be82010-05-06 00:08:46 +000011342 {"SC_XOPEN_XPG3", _SC_XOPEN_XPG3},
Fred Drakec9680921999-12-13 16:37:25 +000011343#endif
11344#ifdef _SC_XOPEN_XPG4
Victor Stinner8c62be82010-05-06 00:08:46 +000011345 {"SC_XOPEN_XPG4", _SC_XOPEN_XPG4},
Fred Drakec9680921999-12-13 16:37:25 +000011346#endif
11347};
11348
11349static int
Fredrik Lundhff7df9d2000-07-08 22:48:53 +000011350conv_sysconf_confname(PyObject *arg, int *valuep)
Fred Drakec9680921999-12-13 16:37:25 +000011351{
11352 return conv_confname(arg, valuep, posix_constants_sysconf,
11353 sizeof(posix_constants_sysconf)
11354 / sizeof(struct constdef));
11355}
11356
Larry Hastings2f936352014-08-05 14:04:04 +100011357
11358/*[clinic input]
11359os.sysconf -> long
11360 name: sysconf_confname
11361 /
11362
11363Return an integer-valued system configuration variable.
11364[clinic start generated code]*/
11365
Larry Hastings2f936352014-08-05 14:04:04 +100011366static long
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011367os_sysconf_impl(PyObject *module, int name)
11368/*[clinic end generated code: output=3662f945fc0cc756 input=279e3430a33f29e4]*/
Larry Hastings2f936352014-08-05 14:04:04 +100011369{
11370 long value;
11371
11372 errno = 0;
11373 value = sysconf(name);
11374 if (value == -1 && errno != 0)
11375 posix_error();
11376 return value;
11377}
11378#endif /* HAVE_SYSCONF */
Fred Drakec9680921999-12-13 16:37:25 +000011379
11380
Fred Drakebec628d1999-12-15 18:31:10 +000011381/* This code is used to ensure that the tables of configuration value names
Serhiy Storchaka56a6d852014-12-01 18:28:43 +020011382 * are in sorted order as required by conv_confname(), and also to build
Fred Drakebec628d1999-12-15 18:31:10 +000011383 * the exported dictionaries that are used to publish information about the
11384 * names available on the host platform.
11385 *
11386 * Sorting the table at runtime ensures that the table is properly ordered
11387 * when used, even for platforms we're not able to test on. It also makes
11388 * it easier to add additional entries to the tables.
Fred Draked86ed291999-12-15 15:34:33 +000011389 */
Fred Drakebec628d1999-12-15 18:31:10 +000011390
11391static int
Fredrik Lundhff7df9d2000-07-08 22:48:53 +000011392cmp_constdefs(const void *v1, const void *v2)
Fred Drakebec628d1999-12-15 18:31:10 +000011393{
11394 const struct constdef *c1 =
Victor Stinner8c62be82010-05-06 00:08:46 +000011395 (const struct constdef *) v1;
Fred Drakebec628d1999-12-15 18:31:10 +000011396 const struct constdef *c2 =
Victor Stinner8c62be82010-05-06 00:08:46 +000011397 (const struct constdef *) v2;
Fred Drakebec628d1999-12-15 18:31:10 +000011398
11399 return strcmp(c1->name, c2->name);
11400}
11401
11402static int
Fredrik Lundhff7df9d2000-07-08 22:48:53 +000011403setup_confname_table(struct constdef *table, size_t tablesize,
Serhiy Storchakadeab18d2016-05-07 16:45:18 +030011404 const char *tablename, PyObject *module)
Fred Draked86ed291999-12-15 15:34:33 +000011405{
Fred Drakebec628d1999-12-15 18:31:10 +000011406 PyObject *d = NULL;
Barry Warsaw3155db32000-04-13 15:20:40 +000011407 size_t i;
Fred Drakebec628d1999-12-15 18:31:10 +000011408
11409 qsort(table, tablesize, sizeof(struct constdef), cmp_constdefs);
11410 d = PyDict_New();
Barry Warsaw3155db32000-04-13 15:20:40 +000011411 if (d == NULL)
Victor Stinner8c62be82010-05-06 00:08:46 +000011412 return -1;
Fred Draked86ed291999-12-15 15:34:33 +000011413
Barry Warsaw3155db32000-04-13 15:20:40 +000011414 for (i=0; i < tablesize; ++i) {
Victor Stinner8c62be82010-05-06 00:08:46 +000011415 PyObject *o = PyLong_FromLong(table[i].value);
11416 if (o == NULL || PyDict_SetItemString(d, table[i].name, o) == -1) {
11417 Py_XDECREF(o);
11418 Py_DECREF(d);
11419 return -1;
11420 }
11421 Py_DECREF(o);
Fred Draked86ed291999-12-15 15:34:33 +000011422 }
Fred Drake4d1e64b2002-04-15 19:40:07 +000011423 return PyModule_AddObject(module, tablename, d);
Fred Draked86ed291999-12-15 15:34:33 +000011424}
11425
Fred Drakebec628d1999-12-15 18:31:10 +000011426/* Return -1 on failure, 0 on success. */
11427static int
Fred Drake4d1e64b2002-04-15 19:40:07 +000011428setup_confname_tables(PyObject *module)
Fred Draked86ed291999-12-15 15:34:33 +000011429{
11430#if defined(HAVE_FPATHCONF) || defined(HAVE_PATHCONF)
Fred Drakebec628d1999-12-15 18:31:10 +000011431 if (setup_confname_table(posix_constants_pathconf,
Fred Draked86ed291999-12-15 15:34:33 +000011432 sizeof(posix_constants_pathconf)
11433 / sizeof(struct constdef),
Fred Drake4d1e64b2002-04-15 19:40:07 +000011434 "pathconf_names", module))
Stefan Krah0e803b32010-11-26 16:16:47 +000011435 return -1;
Fred Draked86ed291999-12-15 15:34:33 +000011436#endif
11437#ifdef HAVE_CONFSTR
Fred Drakebec628d1999-12-15 18:31:10 +000011438 if (setup_confname_table(posix_constants_confstr,
Fred Draked86ed291999-12-15 15:34:33 +000011439 sizeof(posix_constants_confstr)
11440 / sizeof(struct constdef),
Fred Drake4d1e64b2002-04-15 19:40:07 +000011441 "confstr_names", module))
Stefan Krah0e803b32010-11-26 16:16:47 +000011442 return -1;
Fred Draked86ed291999-12-15 15:34:33 +000011443#endif
11444#ifdef HAVE_SYSCONF
Fred Drakebec628d1999-12-15 18:31:10 +000011445 if (setup_confname_table(posix_constants_sysconf,
Fred Draked86ed291999-12-15 15:34:33 +000011446 sizeof(posix_constants_sysconf)
11447 / sizeof(struct constdef),
Fred Drake4d1e64b2002-04-15 19:40:07 +000011448 "sysconf_names", module))
Stefan Krah0e803b32010-11-26 16:16:47 +000011449 return -1;
Fred Draked86ed291999-12-15 15:34:33 +000011450#endif
Fred Drakebec628d1999-12-15 18:31:10 +000011451 return 0;
Fred Draked86ed291999-12-15 15:34:33 +000011452}
Fred Draked86ed291999-12-15 15:34:33 +000011453
11454
Larry Hastings2f936352014-08-05 14:04:04 +100011455/*[clinic input]
11456os.abort
11457
11458Abort the interpreter immediately.
11459
11460This function 'dumps core' or otherwise fails in the hardest way possible
11461on the hosting operating system. This function never returns.
11462[clinic start generated code]*/
11463
Larry Hastings2f936352014-08-05 14:04:04 +100011464static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011465os_abort_impl(PyObject *module)
11466/*[clinic end generated code: output=dcf52586dad2467c input=cf2c7d98bc504047]*/
Fred Drake5ab8eaf1999-12-09 21:13:07 +000011467{
Fred Drake5ab8eaf1999-12-09 21:13:07 +000011468 abort();
11469 /*NOTREACHED*/
Victor Stinner9a2329f2016-12-05 17:56:36 +010011470#ifndef __clang__
11471 /* Issue #28152: abort() is declared with __attribute__((__noreturn__)).
11472 GCC emits a warning without "return NULL;" (compiler bug?), but Clang
11473 is smarter and emits a warning on the return. */
Fred Drake5ab8eaf1999-12-09 21:13:07 +000011474 Py_FatalError("abort() called from Python code didn't abort!");
11475 return NULL;
Victor Stinner9a2329f2016-12-05 17:56:36 +010011476#endif
Fred Drake5ab8eaf1999-12-09 21:13:07 +000011477}
Fred Drakebec628d1999-12-15 18:31:10 +000011478
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000011479#ifdef MS_WINDOWS
Steve Dower7d0e0c92015-01-24 08:18:24 -080011480/* Grab ShellExecute dynamically from shell32 */
11481static int has_ShellExecute = -1;
Steve Dower7d0e0c92015-01-24 08:18:24 -080011482static HINSTANCE (CALLBACK *Py_ShellExecuteW)(HWND, LPCWSTR, LPCWSTR, LPCWSTR,
11483 LPCWSTR, INT);
11484static int
11485check_ShellExecute()
11486{
11487 HINSTANCE hShell32;
11488
11489 /* only recheck */
11490 if (-1 == has_ShellExecute) {
11491 Py_BEGIN_ALLOW_THREADS
Victor Stinnera9912152017-10-13 13:46:57 -070011492 /* Security note: this call is not vulnerable to "DLL hijacking".
11493 SHELL32 is part of "KnownDLLs" and so Windows always load
11494 the system SHELL32.DLL, even if there is another SHELL32.DLL
11495 in the DLL search path. */
Steve Dower7d0e0c92015-01-24 08:18:24 -080011496 hShell32 = LoadLibraryW(L"SHELL32");
Steve Dower7d0e0c92015-01-24 08:18:24 -080011497 if (hShell32) {
Steve Dower7d0e0c92015-01-24 08:18:24 -080011498 *(FARPROC*)&Py_ShellExecuteW = GetProcAddress(hShell32,
11499 "ShellExecuteW");
Steve Dowercc16be82016-09-08 10:35:16 -070011500 has_ShellExecute = Py_ShellExecuteW != NULL;
Steve Dower7d0e0c92015-01-24 08:18:24 -080011501 } else {
11502 has_ShellExecute = 0;
11503 }
Tony Roberts4860f012019-02-02 18:16:42 +010011504 Py_END_ALLOW_THREADS
Steve Dower7d0e0c92015-01-24 08:18:24 -080011505 }
11506 return has_ShellExecute;
11507}
11508
11509
Steve Dowercc16be82016-09-08 10:35:16 -070011510/*[clinic input]
11511os.startfile
11512 filepath: path_t
11513 operation: Py_UNICODE = NULL
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +000011514
Steve Dowercc16be82016-09-08 10:35:16 -070011515startfile(filepath [, operation])
11516
11517Start a file with its associated application.
11518
11519When "operation" is not specified or "open", this acts like
11520double-clicking the file in Explorer, or giving the file name as an
11521argument to the DOS "start" command: the file is opened with whatever
11522application (if any) its extension is associated.
11523When another "operation" is given, it specifies what should be done with
11524the file. A typical operation is "print".
11525
11526startfile returns as soon as the associated application is launched.
11527There is no option to wait for the application to close, and no way
11528to retrieve the application's exit status.
11529
11530The filepath is relative to the current directory. If you want to use
11531an absolute path, make sure the first character is not a slash ("/");
11532the underlying Win32 ShellExecute function doesn't work if it is.
11533[clinic start generated code]*/
11534
11535static PyObject *
Serhiy Storchakaafb3e712018-12-14 11:19:51 +020011536os_startfile_impl(PyObject *module, path_t *filepath,
11537 const Py_UNICODE *operation)
11538/*[clinic end generated code: output=66dc311c94d50797 input=63950bf2986380d0]*/
Steve Dowercc16be82016-09-08 10:35:16 -070011539{
11540 HINSTANCE rc;
Steve Dower7d0e0c92015-01-24 08:18:24 -080011541
11542 if(!check_ShellExecute()) {
11543 /* If the OS doesn't have ShellExecute, return a
11544 NotImplementedError. */
11545 return PyErr_Format(PyExc_NotImplementedError,
11546 "startfile not available on this platform");
11547 }
11548
Victor Stinner8c62be82010-05-06 00:08:46 +000011549 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -070011550 rc = Py_ShellExecuteW((HWND)0, operation, filepath->wide,
Steve Dower7d0e0c92015-01-24 08:18:24 -080011551 NULL, NULL, SW_SHOWNORMAL);
Victor Stinner8c62be82010-05-06 00:08:46 +000011552 Py_END_ALLOW_THREADS
11553
Victor Stinner8c62be82010-05-06 00:08:46 +000011554 if (rc <= (HINSTANCE)32) {
Steve Dowercc16be82016-09-08 10:35:16 -070011555 win32_error_object("startfile", filepath->object);
Victor Stinnereb5657a2011-09-30 01:44:27 +020011556 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +000011557 }
Steve Dowercc16be82016-09-08 10:35:16 -070011558 Py_RETURN_NONE;
Tim Petersf58a7aa2000-09-22 10:05:54 +000011559}
Larry Hastings2f936352014-08-05 14:04:04 +100011560#endif /* MS_WINDOWS */
11561
Fred Drake5ab8eaf1999-12-09 21:13:07 +000011562
Martin v. Löwis438b5342002-12-27 10:16:42 +000011563#ifdef HAVE_GETLOADAVG
Larry Hastings2f936352014-08-05 14:04:04 +100011564/*[clinic input]
11565os.getloadavg
11566
11567Return average recent system load information.
11568
11569Return the number of processes in the system run queue averaged over
11570the last 1, 5, and 15 minutes as a tuple of three floats.
11571Raises OSError if the load average was unobtainable.
11572[clinic start generated code]*/
11573
Larry Hastings2f936352014-08-05 14:04:04 +100011574static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011575os_getloadavg_impl(PyObject *module)
11576/*[clinic end generated code: output=9ad3a11bfb4f4bd2 input=3d6d826b76d8a34e]*/
Martin v. Löwis438b5342002-12-27 10:16:42 +000011577{
11578 double loadavg[3];
Martin v. Löwis438b5342002-12-27 10:16:42 +000011579 if (getloadavg(loadavg, 3)!=3) {
Stefan Krah0e803b32010-11-26 16:16:47 +000011580 PyErr_SetString(PyExc_OSError, "Load averages are unobtainable");
11581 return NULL;
Martin v. Löwis438b5342002-12-27 10:16:42 +000011582 } else
Stefan Krah0e803b32010-11-26 16:16:47 +000011583 return Py_BuildValue("ddd", loadavg[0], loadavg[1], loadavg[2]);
Martin v. Löwis438b5342002-12-27 10:16:42 +000011584}
Larry Hastings2f936352014-08-05 14:04:04 +100011585#endif /* HAVE_GETLOADAVG */
Martin v. Löwis438b5342002-12-27 10:16:42 +000011586
Larry Hastings2f936352014-08-05 14:04:04 +100011587
11588/*[clinic input]
11589os.device_encoding
11590 fd: int
11591
11592Return a string describing the encoding of a terminal's file descriptor.
11593
11594The file descriptor must be attached to a terminal.
11595If the device is not a terminal, return None.
11596[clinic start generated code]*/
11597
Larry Hastings2f936352014-08-05 14:04:04 +100011598static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011599os_device_encoding_impl(PyObject *module, int fd)
11600/*[clinic end generated code: output=e0d294bbab7e8c2b input=9e1d4a42b66df312]*/
Larry Hastings2f936352014-08-05 14:04:04 +100011601{
Brett Cannonefb00c02012-02-29 18:31:31 -050011602 return _Py_device_encoding(fd);
Martin v. Löwisd1cd4d42007-08-11 14:02:14 +000011603}
11604
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011605
Larry Hastings2f936352014-08-05 14:04:04 +100011606#ifdef HAVE_SETRESUID
11607/*[clinic input]
11608os.setresuid
11609
11610 ruid: uid_t
11611 euid: uid_t
11612 suid: uid_t
11613 /
11614
11615Set the current process's real, effective, and saved user ids.
11616[clinic start generated code]*/
11617
Larry Hastings2f936352014-08-05 14:04:04 +100011618static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011619os_setresuid_impl(PyObject *module, uid_t ruid, uid_t euid, uid_t suid)
11620/*[clinic end generated code: output=834a641e15373e97 input=9e33cb79a82792f3]*/
Larry Hastings2f936352014-08-05 14:04:04 +100011621{
Victor Stinner8c62be82010-05-06 00:08:46 +000011622 if (setresuid(ruid, euid, suid) < 0)
11623 return posix_error();
11624 Py_RETURN_NONE;
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011625}
Larry Hastings2f936352014-08-05 14:04:04 +100011626#endif /* HAVE_SETRESUID */
11627
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011628
11629#ifdef HAVE_SETRESGID
Larry Hastings2f936352014-08-05 14:04:04 +100011630/*[clinic input]
11631os.setresgid
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011632
Larry Hastings2f936352014-08-05 14:04:04 +100011633 rgid: gid_t
11634 egid: gid_t
11635 sgid: gid_t
11636 /
11637
11638Set the current process's real, effective, and saved group ids.
11639[clinic start generated code]*/
11640
Larry Hastings2f936352014-08-05 14:04:04 +100011641static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011642os_setresgid_impl(PyObject *module, gid_t rgid, gid_t egid, gid_t sgid)
11643/*[clinic end generated code: output=6aa402f3d2e514a9 input=33e9e0785ef426b1]*/
Larry Hastings2f936352014-08-05 14:04:04 +100011644{
Victor Stinner8c62be82010-05-06 00:08:46 +000011645 if (setresgid(rgid, egid, sgid) < 0)
11646 return posix_error();
11647 Py_RETURN_NONE;
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011648}
Larry Hastings2f936352014-08-05 14:04:04 +100011649#endif /* HAVE_SETRESGID */
11650
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011651
11652#ifdef HAVE_GETRESUID
Larry Hastings2f936352014-08-05 14:04:04 +100011653/*[clinic input]
11654os.getresuid
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011655
Larry Hastings2f936352014-08-05 14:04:04 +100011656Return a tuple of the current process's real, effective, and saved user ids.
11657[clinic start generated code]*/
11658
Larry Hastings2f936352014-08-05 14:04:04 +100011659static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011660os_getresuid_impl(PyObject *module)
11661/*[clinic end generated code: output=8e0becff5dece5bf input=41ccfa8e1f6517ad]*/
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011662{
Victor Stinner8c62be82010-05-06 00:08:46 +000011663 uid_t ruid, euid, suid;
Victor Stinner8c62be82010-05-06 00:08:46 +000011664 if (getresuid(&ruid, &euid, &suid) < 0)
11665 return posix_error();
Serhiy Storchaka7cf55992013-02-10 21:56:49 +020011666 return Py_BuildValue("(NNN)", _PyLong_FromUid(ruid),
11667 _PyLong_FromUid(euid),
11668 _PyLong_FromUid(suid));
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011669}
Larry Hastings2f936352014-08-05 14:04:04 +100011670#endif /* HAVE_GETRESUID */
11671
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011672
11673#ifdef HAVE_GETRESGID
Larry Hastings2f936352014-08-05 14:04:04 +100011674/*[clinic input]
11675os.getresgid
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011676
Larry Hastings2f936352014-08-05 14:04:04 +100011677Return a tuple of the current process's real, effective, and saved group ids.
11678[clinic start generated code]*/
11679
Larry Hastings2f936352014-08-05 14:04:04 +100011680static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011681os_getresgid_impl(PyObject *module)
11682/*[clinic end generated code: output=2719c4bfcf27fb9f input=517e68db9ca32df6]*/
Larry Hastings2f936352014-08-05 14:04:04 +100011683{
11684 gid_t rgid, egid, sgid;
Victor Stinner8c62be82010-05-06 00:08:46 +000011685 if (getresgid(&rgid, &egid, &sgid) < 0)
11686 return posix_error();
Serhiy Storchaka7cf55992013-02-10 21:56:49 +020011687 return Py_BuildValue("(NNN)", _PyLong_FromGid(rgid),
11688 _PyLong_FromGid(egid),
11689 _PyLong_FromGid(sgid));
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011690}
Larry Hastings2f936352014-08-05 14:04:04 +100011691#endif /* HAVE_GETRESGID */
11692
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011693
Benjamin Peterson9428d532011-09-14 11:45:52 -040011694#ifdef USE_XATTRS
Larry Hastings2f936352014-08-05 14:04:04 +100011695/*[clinic input]
11696os.getxattr
Benjamin Peterson799bd802011-08-31 22:15:17 -040011697
Larry Hastings2f936352014-08-05 14:04:04 +100011698 path: path_t(allow_fd=True)
11699 attribute: path_t
11700 *
11701 follow_symlinks: bool = True
11702
11703Return the value of extended attribute attribute on path.
11704
BNMetricsb9427072018-11-02 15:20:19 +000011705path may be either a string, a path-like object, or an open file descriptor.
Larry Hastings2f936352014-08-05 14:04:04 +100011706If follow_symlinks is False, and the last element of the path is a symbolic
11707 link, getxattr will examine the symbolic link itself instead of the file
11708 the link points to.
11709
11710[clinic start generated code]*/
11711
Larry Hastings2f936352014-08-05 14:04:04 +100011712static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011713os_getxattr_impl(PyObject *module, path_t *path, path_t *attribute,
Larry Hastings89964c42015-04-14 18:07:59 -040011714 int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +000011715/*[clinic end generated code: output=5f2f44200a43cff2 input=025789491708f7eb]*/
Larry Hastings2f936352014-08-05 14:04:04 +100011716{
11717 Py_ssize_t i;
11718 PyObject *buffer = NULL;
11719
11720 if (fd_and_follow_symlinks_invalid("getxattr", path->fd, follow_symlinks))
11721 return NULL;
Benjamin Peterson799bd802011-08-31 22:15:17 -040011722
Larry Hastings9cf065c2012-06-22 16:30:09 -070011723 for (i = 0; ; i++) {
11724 void *ptr;
11725 ssize_t result;
Serhiy Storchaka2d06e842015-12-25 19:53:18 +020011726 static const Py_ssize_t buffer_sizes[] = {128, XATTR_SIZE_MAX, 0};
Larry Hastings9cf065c2012-06-22 16:30:09 -070011727 Py_ssize_t buffer_size = buffer_sizes[i];
11728 if (!buffer_size) {
Larry Hastings2f936352014-08-05 14:04:04 +100011729 path_error(path);
11730 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -070011731 }
11732 buffer = PyBytes_FromStringAndSize(NULL, buffer_size);
11733 if (!buffer)
Larry Hastings2f936352014-08-05 14:04:04 +100011734 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -070011735 ptr = PyBytes_AS_STRING(buffer);
Benjamin Peterson799bd802011-08-31 22:15:17 -040011736
Larry Hastings9cf065c2012-06-22 16:30:09 -070011737 Py_BEGIN_ALLOW_THREADS;
Larry Hastings2f936352014-08-05 14:04:04 +100011738 if (path->fd >= 0)
11739 result = fgetxattr(path->fd, attribute->narrow, ptr, buffer_size);
Larry Hastings9cf065c2012-06-22 16:30:09 -070011740 else if (follow_symlinks)
Larry Hastings2f936352014-08-05 14:04:04 +100011741 result = getxattr(path->narrow, attribute->narrow, ptr, buffer_size);
Larry Hastings9cf065c2012-06-22 16:30:09 -070011742 else
Larry Hastings2f936352014-08-05 14:04:04 +100011743 result = lgetxattr(path->narrow, attribute->narrow, ptr, buffer_size);
Larry Hastings9cf065c2012-06-22 16:30:09 -070011744 Py_END_ALLOW_THREADS;
Benjamin Peterson799bd802011-08-31 22:15:17 -040011745
Larry Hastings9cf065c2012-06-22 16:30:09 -070011746 if (result < 0) {
11747 Py_DECREF(buffer);
Larry Hastings9cf065c2012-06-22 16:30:09 -070011748 if (errno == ERANGE)
11749 continue;
Larry Hastings2f936352014-08-05 14:04:04 +100011750 path_error(path);
11751 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -070011752 }
Benjamin Peterson799bd802011-08-31 22:15:17 -040011753
Larry Hastings9cf065c2012-06-22 16:30:09 -070011754 if (result != buffer_size) {
11755 /* Can only shrink. */
11756 _PyBytes_Resize(&buffer, result);
11757 }
11758 break;
11759 }
Benjamin Peterson799bd802011-08-31 22:15:17 -040011760
Larry Hastings9cf065c2012-06-22 16:30:09 -070011761 return buffer;
Benjamin Peterson799bd802011-08-31 22:15:17 -040011762}
11763
Larry Hastings2f936352014-08-05 14:04:04 +100011764
11765/*[clinic input]
11766os.setxattr
11767
11768 path: path_t(allow_fd=True)
11769 attribute: path_t
11770 value: Py_buffer
11771 flags: int = 0
11772 *
11773 follow_symlinks: bool = True
11774
11775Set extended attribute attribute on path to value.
11776
BNMetricsb9427072018-11-02 15:20:19 +000011777path may be either a string, a path-like object, or an open file descriptor.
Larry Hastings2f936352014-08-05 14:04:04 +100011778If follow_symlinks is False, and the last element of the path is a symbolic
11779 link, setxattr will modify the symbolic link itself instead of the file
11780 the link points to.
11781
11782[clinic start generated code]*/
11783
Benjamin Peterson799bd802011-08-31 22:15:17 -040011784static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011785os_setxattr_impl(PyObject *module, path_t *path, path_t *attribute,
Larry Hastings89964c42015-04-14 18:07:59 -040011786 Py_buffer *value, int flags, int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +000011787/*[clinic end generated code: output=98b83f63fdde26bb input=c17c0103009042f0]*/
Benjamin Peterson799bd802011-08-31 22:15:17 -040011788{
Larry Hastings2f936352014-08-05 14:04:04 +100011789 ssize_t result;
Benjamin Peterson799bd802011-08-31 22:15:17 -040011790
Larry Hastings2f936352014-08-05 14:04:04 +100011791 if (fd_and_follow_symlinks_invalid("setxattr", path->fd, follow_symlinks))
Benjamin Peterson799bd802011-08-31 22:15:17 -040011792 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -070011793
Benjamin Peterson799bd802011-08-31 22:15:17 -040011794 Py_BEGIN_ALLOW_THREADS;
Larry Hastings2f936352014-08-05 14:04:04 +100011795 if (path->fd > -1)
11796 result = fsetxattr(path->fd, attribute->narrow,
11797 value->buf, value->len, flags);
Larry Hastings9cf065c2012-06-22 16:30:09 -070011798 else if (follow_symlinks)
Larry Hastings2f936352014-08-05 14:04:04 +100011799 result = setxattr(path->narrow, attribute->narrow,
11800 value->buf, value->len, flags);
Larry Hastings9cf065c2012-06-22 16:30:09 -070011801 else
Larry Hastings2f936352014-08-05 14:04:04 +100011802 result = lsetxattr(path->narrow, attribute->narrow,
11803 value->buf, value->len, flags);
Benjamin Peterson799bd802011-08-31 22:15:17 -040011804 Py_END_ALLOW_THREADS;
Benjamin Peterson799bd802011-08-31 22:15:17 -040011805
Larry Hastings9cf065c2012-06-22 16:30:09 -070011806 if (result) {
Larry Hastings2f936352014-08-05 14:04:04 +100011807 path_error(path);
11808 return NULL;
Benjamin Peterson799bd802011-08-31 22:15:17 -040011809 }
Benjamin Peterson799bd802011-08-31 22:15:17 -040011810
Larry Hastings2f936352014-08-05 14:04:04 +100011811 Py_RETURN_NONE;
11812}
11813
11814
11815/*[clinic input]
11816os.removexattr
11817
11818 path: path_t(allow_fd=True)
11819 attribute: path_t
11820 *
11821 follow_symlinks: bool = True
11822
11823Remove extended attribute attribute on path.
11824
BNMetricsb9427072018-11-02 15:20:19 +000011825path may be either a string, a path-like object, or an open file descriptor.
Larry Hastings2f936352014-08-05 14:04:04 +100011826If follow_symlinks is False, and the last element of the path is a symbolic
11827 link, removexattr will modify the symbolic link itself instead of the file
11828 the link points to.
11829
11830[clinic start generated code]*/
11831
Larry Hastings2f936352014-08-05 14:04:04 +100011832static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011833os_removexattr_impl(PyObject *module, path_t *path, path_t *attribute,
Larry Hastings89964c42015-04-14 18:07:59 -040011834 int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +000011835/*[clinic end generated code: output=521a51817980cda6 input=3d9a7d36fe2f7c4e]*/
Larry Hastings2f936352014-08-05 14:04:04 +100011836{
11837 ssize_t result;
11838
11839 if (fd_and_follow_symlinks_invalid("removexattr", path->fd, follow_symlinks))
11840 return NULL;
11841
11842 Py_BEGIN_ALLOW_THREADS;
11843 if (path->fd > -1)
11844 result = fremovexattr(path->fd, attribute->narrow);
11845 else if (follow_symlinks)
11846 result = removexattr(path->narrow, attribute->narrow);
11847 else
11848 result = lremovexattr(path->narrow, attribute->narrow);
11849 Py_END_ALLOW_THREADS;
11850
11851 if (result) {
11852 return path_error(path);
11853 }
11854
11855 Py_RETURN_NONE;
11856}
11857
11858
11859/*[clinic input]
11860os.listxattr
11861
11862 path: path_t(allow_fd=True, nullable=True) = None
11863 *
11864 follow_symlinks: bool = True
11865
11866Return a list of extended attributes on path.
11867
BNMetricsb9427072018-11-02 15:20:19 +000011868path may be either None, a string, a path-like object, or an open file descriptor.
Larry Hastings2f936352014-08-05 14:04:04 +100011869if path is None, listxattr will examine the current directory.
11870If follow_symlinks is False, and the last element of the path is a symbolic
11871 link, listxattr will examine the symbolic link itself instead of the file
11872 the link points to.
11873[clinic start generated code]*/
11874
Larry Hastings2f936352014-08-05 14:04:04 +100011875static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011876os_listxattr_impl(PyObject *module, path_t *path, int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +000011877/*[clinic end generated code: output=bebdb4e2ad0ce435 input=9826edf9fdb90869]*/
Larry Hastings2f936352014-08-05 14:04:04 +100011878{
Larry Hastings9cf065c2012-06-22 16:30:09 -070011879 Py_ssize_t i;
11880 PyObject *result = NULL;
Larry Hastings2f936352014-08-05 14:04:04 +100011881 const char *name;
Larry Hastings9cf065c2012-06-22 16:30:09 -070011882 char *buffer = NULL;
Benjamin Peterson799bd802011-08-31 22:15:17 -040011883
Larry Hastings2f936352014-08-05 14:04:04 +100011884 if (fd_and_follow_symlinks_invalid("listxattr", path->fd, follow_symlinks))
Larry Hastings9cf065c2012-06-22 16:30:09 -070011885 goto exit;
Benjamin Peterson799bd802011-08-31 22:15:17 -040011886
Larry Hastings2f936352014-08-05 14:04:04 +100011887 name = path->narrow ? path->narrow : ".";
11888
Larry Hastings9cf065c2012-06-22 16:30:09 -070011889 for (i = 0; ; i++) {
Serhiy Storchakadeab18d2016-05-07 16:45:18 +030011890 const char *start, *trace, *end;
Larry Hastings9cf065c2012-06-22 16:30:09 -070011891 ssize_t length;
Serhiy Storchaka2d06e842015-12-25 19:53:18 +020011892 static const Py_ssize_t buffer_sizes[] = { 256, XATTR_LIST_MAX, 0 };
Larry Hastings9cf065c2012-06-22 16:30:09 -070011893 Py_ssize_t buffer_size = buffer_sizes[i];
11894 if (!buffer_size) {
Christian Heimes3b9493b2012-09-23 16:11:15 +020011895 /* ERANGE */
Larry Hastings2f936352014-08-05 14:04:04 +100011896 path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -070011897 break;
11898 }
11899 buffer = PyMem_MALLOC(buffer_size);
11900 if (!buffer) {
11901 PyErr_NoMemory();
11902 break;
11903 }
Benjamin Peterson799bd802011-08-31 22:15:17 -040011904
Larry Hastings9cf065c2012-06-22 16:30:09 -070011905 Py_BEGIN_ALLOW_THREADS;
Larry Hastings2f936352014-08-05 14:04:04 +100011906 if (path->fd > -1)
11907 length = flistxattr(path->fd, buffer, buffer_size);
Larry Hastings9cf065c2012-06-22 16:30:09 -070011908 else if (follow_symlinks)
11909 length = listxattr(name, buffer, buffer_size);
11910 else
11911 length = llistxattr(name, buffer, buffer_size);
11912 Py_END_ALLOW_THREADS;
Benjamin Peterson799bd802011-08-31 22:15:17 -040011913
Larry Hastings9cf065c2012-06-22 16:30:09 -070011914 if (length < 0) {
Antoine Pitrou7f987392013-05-13 19:46:29 +020011915 if (errno == ERANGE) {
11916 PyMem_FREE(buffer);
Benjamin Petersondedac522013-05-13 19:55:40 -050011917 buffer = NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -070011918 continue;
Antoine Pitrou7f987392013-05-13 19:46:29 +020011919 }
Larry Hastings2f936352014-08-05 14:04:04 +100011920 path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -070011921 break;
11922 }
Benjamin Peterson799bd802011-08-31 22:15:17 -040011923
Larry Hastings9cf065c2012-06-22 16:30:09 -070011924 result = PyList_New(0);
11925 if (!result) {
11926 goto exit;
11927 }
Benjamin Peterson799bd802011-08-31 22:15:17 -040011928
Larry Hastings9cf065c2012-06-22 16:30:09 -070011929 end = buffer + length;
11930 for (trace = start = buffer; trace != end; trace++) {
11931 if (!*trace) {
11932 int error;
11933 PyObject *attribute = PyUnicode_DecodeFSDefaultAndSize(start,
11934 trace - start);
11935 if (!attribute) {
11936 Py_DECREF(result);
11937 result = NULL;
11938 goto exit;
11939 }
11940 error = PyList_Append(result, attribute);
11941 Py_DECREF(attribute);
11942 if (error) {
11943 Py_DECREF(result);
11944 result = NULL;
11945 goto exit;
11946 }
11947 start = trace + 1;
11948 }
11949 }
11950 break;
11951 }
11952exit:
Larry Hastings9cf065c2012-06-22 16:30:09 -070011953 if (buffer)
11954 PyMem_FREE(buffer);
11955 return result;
Benjamin Peterson799bd802011-08-31 22:15:17 -040011956}
Benjamin Peterson9428d532011-09-14 11:45:52 -040011957#endif /* USE_XATTRS */
Benjamin Peterson799bd802011-08-31 22:15:17 -040011958
Antoine Pitroubcf2b592012-02-08 23:28:36 +010011959
Larry Hastings2f936352014-08-05 14:04:04 +100011960/*[clinic input]
11961os.urandom
11962
11963 size: Py_ssize_t
11964 /
11965
11966Return a bytes object containing random bytes suitable for cryptographic use.
11967[clinic start generated code]*/
11968
Larry Hastings2f936352014-08-05 14:04:04 +100011969static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011970os_urandom_impl(PyObject *module, Py_ssize_t size)
11971/*[clinic end generated code: output=42c5cca9d18068e9 input=4067cdb1b6776c29]*/
Larry Hastings2f936352014-08-05 14:04:04 +100011972{
11973 PyObject *bytes;
11974 int result;
11975
Georg Brandl2fb477c2012-02-21 00:33:36 +010011976 if (size < 0)
11977 return PyErr_Format(PyExc_ValueError,
11978 "negative argument not allowed");
Larry Hastings2f936352014-08-05 14:04:04 +100011979 bytes = PyBytes_FromStringAndSize(NULL, size);
11980 if (bytes == NULL)
Georg Brandl2fb477c2012-02-21 00:33:36 +010011981 return NULL;
11982
Victor Stinnere66987e2016-09-06 16:33:52 -070011983 result = _PyOS_URandom(PyBytes_AS_STRING(bytes), PyBytes_GET_SIZE(bytes));
Larry Hastings2f936352014-08-05 14:04:04 +100011984 if (result == -1) {
11985 Py_DECREF(bytes);
Georg Brandl2fb477c2012-02-21 00:33:36 +010011986 return NULL;
11987 }
Larry Hastings2f936352014-08-05 14:04:04 +100011988 return bytes;
Georg Brandl2fb477c2012-02-21 00:33:36 +010011989}
11990
Zackery Spytz43fdbd22019-05-29 13:57:07 -060011991#ifdef HAVE_MEMFD_CREATE
11992/*[clinic input]
11993os.memfd_create
11994
11995 name: FSConverter
11996 flags: unsigned_int(bitwise=True, c_default="MFD_CLOEXEC") = MFD_CLOEXEC
11997
11998[clinic start generated code]*/
11999
12000static PyObject *
12001os_memfd_create_impl(PyObject *module, PyObject *name, unsigned int flags)
12002/*[clinic end generated code: output=6681ede983bdb9a6 input=a42cfc199bcd56e9]*/
12003{
12004 int fd;
12005 const char *bytes = PyBytes_AS_STRING(name);
12006 Py_BEGIN_ALLOW_THREADS
12007 fd = memfd_create(bytes, flags);
12008 Py_END_ALLOW_THREADS
12009 if (fd == -1) {
12010 return PyErr_SetFromErrno(PyExc_OSError);
12011 }
12012 return PyLong_FromLong(fd);
12013}
12014#endif
12015
Antoine Pitroubcf2b592012-02-08 23:28:36 +010012016/* Terminal size querying */
12017
Eddie Elizondo474eedf2018-11-13 04:09:31 -080012018static PyTypeObject* TerminalSizeType;
Antoine Pitroubcf2b592012-02-08 23:28:36 +010012019
12020PyDoc_STRVAR(TerminalSize_docstring,
12021 "A tuple of (columns, lines) for holding terminal window size");
12022
12023static PyStructSequence_Field TerminalSize_fields[] = {
12024 {"columns", "width of the terminal window in characters"},
12025 {"lines", "height of the terminal window in characters"},
12026 {NULL, NULL}
12027};
12028
12029static PyStructSequence_Desc TerminalSize_desc = {
12030 "os.terminal_size",
12031 TerminalSize_docstring,
12032 TerminalSize_fields,
12033 2,
12034};
12035
12036#if defined(TERMSIZE_USE_CONIO) || defined(TERMSIZE_USE_IOCTL)
Larry Hastings2f936352014-08-05 14:04:04 +100012037/* AC 3.5: fd should accept None */
Antoine Pitroubcf2b592012-02-08 23:28:36 +010012038PyDoc_STRVAR(termsize__doc__,
12039 "Return the size of the terminal window as (columns, lines).\n" \
12040 "\n" \
12041 "The optional argument fd (default standard output) specifies\n" \
12042 "which file descriptor should be queried.\n" \
12043 "\n" \
12044 "If the file descriptor is not connected to a terminal, an OSError\n" \
12045 "is thrown.\n" \
12046 "\n" \
12047 "This function will only be defined if an implementation is\n" \
12048 "available for this system.\n" \
12049 "\n" \
oldkaa0735f2018-02-02 16:52:55 +080012050 "shutil.get_terminal_size is the high-level function which should\n" \
Antoine Pitroubcf2b592012-02-08 23:28:36 +010012051 "normally be used, os.get_terminal_size is the low-level implementation.");
12052
12053static PyObject*
12054get_terminal_size(PyObject *self, PyObject *args)
12055{
12056 int columns, lines;
12057 PyObject *termsize;
12058
12059 int fd = fileno(stdout);
12060 /* Under some conditions stdout may not be connected and
12061 * fileno(stdout) may point to an invalid file descriptor. For example
12062 * GUI apps don't have valid standard streams by default.
12063 *
12064 * If this happens, and the optional fd argument is not present,
12065 * the ioctl below will fail returning EBADF. This is what we want.
12066 */
12067
12068 if (!PyArg_ParseTuple(args, "|i", &fd))
12069 return NULL;
12070
12071#ifdef TERMSIZE_USE_IOCTL
12072 {
12073 struct winsize w;
12074 if (ioctl(fd, TIOCGWINSZ, &w))
12075 return PyErr_SetFromErrno(PyExc_OSError);
12076 columns = w.ws_col;
12077 lines = w.ws_row;
12078 }
12079#endif /* TERMSIZE_USE_IOCTL */
12080
12081#ifdef TERMSIZE_USE_CONIO
12082 {
12083 DWORD nhandle;
12084 HANDLE handle;
12085 CONSOLE_SCREEN_BUFFER_INFO csbi;
12086 switch (fd) {
12087 case 0: nhandle = STD_INPUT_HANDLE;
12088 break;
12089 case 1: nhandle = STD_OUTPUT_HANDLE;
12090 break;
12091 case 2: nhandle = STD_ERROR_HANDLE;
12092 break;
12093 default:
12094 return PyErr_Format(PyExc_ValueError, "bad file descriptor");
12095 }
12096 handle = GetStdHandle(nhandle);
12097 if (handle == NULL)
12098 return PyErr_Format(PyExc_OSError, "handle cannot be retrieved");
12099 if (handle == INVALID_HANDLE_VALUE)
12100 return PyErr_SetFromWindowsErr(0);
12101
12102 if (!GetConsoleScreenBufferInfo(handle, &csbi))
12103 return PyErr_SetFromWindowsErr(0);
12104
12105 columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
12106 lines = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
12107 }
12108#endif /* TERMSIZE_USE_CONIO */
12109
Eddie Elizondo474eedf2018-11-13 04:09:31 -080012110 termsize = PyStructSequence_New(TerminalSizeType);
Antoine Pitroubcf2b592012-02-08 23:28:36 +010012111 if (termsize == NULL)
12112 return NULL;
12113 PyStructSequence_SET_ITEM(termsize, 0, PyLong_FromLong(columns));
12114 PyStructSequence_SET_ITEM(termsize, 1, PyLong_FromLong(lines));
12115 if (PyErr_Occurred()) {
12116 Py_DECREF(termsize);
12117 return NULL;
12118 }
12119 return termsize;
12120}
12121#endif /* defined(TERMSIZE_USE_CONIO) || defined(TERMSIZE_USE_IOCTL) */
12122
Larry Hastings2f936352014-08-05 14:04:04 +100012123
12124/*[clinic input]
12125os.cpu_count
12126
Charles-François Natali80d62e62015-08-13 20:37:08 +010012127Return the number of CPUs in the system; return None if indeterminable.
12128
12129This number is not equivalent to the number of CPUs the current process can
12130use. The number of usable CPUs can be obtained with
12131``len(os.sched_getaffinity(0))``
Larry Hastings2f936352014-08-05 14:04:04 +100012132[clinic start generated code]*/
12133
Larry Hastings2f936352014-08-05 14:04:04 +100012134static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030012135os_cpu_count_impl(PyObject *module)
Serhiy Storchaka2954f832016-07-07 18:20:03 +030012136/*[clinic end generated code: output=5fc29463c3936a9c input=e7c8f4ba6dbbadd3]*/
Charles-Francois Natali44feda32013-05-20 14:40:46 +020012137{
Charles-Francois Natalid59087d2013-05-20 17:31:06 +020012138 int ncpu = 0;
Charles-Francois Natali44feda32013-05-20 14:40:46 +020012139#ifdef MS_WINDOWS
Christopher Wilcoxc67bae02017-08-30 05:01:08 -040012140 /* Vista is supported and the GetMaximumProcessorCount API is Win7+
12141 Need to fallback to Vista behavior if this call isn't present */
12142 HINSTANCE hKernel32;
Christopher Wilcoxc67bae02017-08-30 05:01:08 -040012143 static DWORD(CALLBACK *_GetMaximumProcessorCount)(WORD) = NULL;
Tony Roberts4860f012019-02-02 18:16:42 +010012144 Py_BEGIN_ALLOW_THREADS
12145 hKernel32 = GetModuleHandleW(L"KERNEL32");
Christopher Wilcoxc67bae02017-08-30 05:01:08 -040012146 *(FARPROC*)&_GetMaximumProcessorCount = GetProcAddress(hKernel32,
12147 "GetMaximumProcessorCount");
Tony Roberts4860f012019-02-02 18:16:42 +010012148 Py_END_ALLOW_THREADS
Christopher Wilcoxc67bae02017-08-30 05:01:08 -040012149 if (_GetMaximumProcessorCount != NULL) {
12150 ncpu = _GetMaximumProcessorCount(ALL_PROCESSOR_GROUPS);
12151 }
12152 else {
12153 SYSTEM_INFO sysinfo;
12154 GetSystemInfo(&sysinfo);
12155 ncpu = sysinfo.dwNumberOfProcessors;
12156 }
Charles-Francois Natali44feda32013-05-20 14:40:46 +020012157#elif defined(__hpux)
12158 ncpu = mpctl(MPC_GETNUMSPUS, NULL, NULL);
12159#elif defined(HAVE_SYSCONF) && defined(_SC_NPROCESSORS_ONLN)
12160 ncpu = sysconf(_SC_NPROCESSORS_ONLN);
Charles-Francois Natali44feda32013-05-20 14:40:46 +020012161#elif defined(__DragonFly__) || \
12162 defined(__OpenBSD__) || \
12163 defined(__FreeBSD__) || \
Charles-Francois Natalid59087d2013-05-20 17:31:06 +020012164 defined(__NetBSD__) || \
12165 defined(__APPLE__)
Charles-Francois Natali7c4f8da2013-05-20 17:40:32 +020012166 int mib[2];
12167 size_t len = sizeof(ncpu);
12168 mib[0] = CTL_HW;
12169 mib[1] = HW_NCPU;
12170 if (sysctl(mib, 2, &ncpu, &len, NULL, 0) != 0)
12171 ncpu = 0;
Charles-Francois Natali44feda32013-05-20 14:40:46 +020012172#endif
12173 if (ncpu >= 1)
12174 return PyLong_FromLong(ncpu);
12175 else
12176 Py_RETURN_NONE;
12177}
12178
Victor Stinnerdaf45552013-08-28 00:53:59 +020012179
Larry Hastings2f936352014-08-05 14:04:04 +100012180/*[clinic input]
12181os.get_inheritable -> bool
12182
12183 fd: int
12184 /
12185
12186Get the close-on-exe flag of the specified file descriptor.
12187[clinic start generated code]*/
12188
Larry Hastings2f936352014-08-05 14:04:04 +100012189static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030012190os_get_inheritable_impl(PyObject *module, int fd)
12191/*[clinic end generated code: output=0445e20e149aa5b8 input=89ac008dc9ab6b95]*/
Larry Hastings2f936352014-08-05 14:04:04 +100012192{
Steve Dower8fc89802015-04-12 00:26:27 -040012193 int return_value;
Steve Dower8fc89802015-04-12 00:26:27 -040012194 _Py_BEGIN_SUPPRESS_IPH
12195 return_value = _Py_get_inheritable(fd);
12196 _Py_END_SUPPRESS_IPH
12197 return return_value;
Larry Hastings2f936352014-08-05 14:04:04 +100012198}
12199
12200
12201/*[clinic input]
12202os.set_inheritable
12203 fd: int
12204 inheritable: int
12205 /
12206
12207Set the inheritable flag of the specified file descriptor.
12208[clinic start generated code]*/
12209
Larry Hastings2f936352014-08-05 14:04:04 +100012210static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030012211os_set_inheritable_impl(PyObject *module, int fd, int inheritable)
12212/*[clinic end generated code: output=f1b1918a2f3c38c2 input=9ceaead87a1e2402]*/
Victor Stinnerdaf45552013-08-28 00:53:59 +020012213{
Steve Dower8fc89802015-04-12 00:26:27 -040012214 int result;
Victor Stinnerdaf45552013-08-28 00:53:59 +020012215
Steve Dower8fc89802015-04-12 00:26:27 -040012216 _Py_BEGIN_SUPPRESS_IPH
12217 result = _Py_set_inheritable(fd, inheritable, NULL);
12218 _Py_END_SUPPRESS_IPH
12219 if (result < 0)
Victor Stinnerdaf45552013-08-28 00:53:59 +020012220 return NULL;
12221 Py_RETURN_NONE;
12222}
12223
12224
12225#ifdef MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +100012226/*[clinic input]
12227os.get_handle_inheritable -> bool
Benjamin Petersonca470632016-09-06 13:47:26 -070012228 handle: intptr_t
Larry Hastings2f936352014-08-05 14:04:04 +100012229 /
Victor Stinnerdaf45552013-08-28 00:53:59 +020012230
Larry Hastings2f936352014-08-05 14:04:04 +100012231Get the close-on-exe flag of the specified file descriptor.
12232[clinic start generated code]*/
12233
Larry Hastings2f936352014-08-05 14:04:04 +100012234static int
Benjamin Petersonca470632016-09-06 13:47:26 -070012235os_get_handle_inheritable_impl(PyObject *module, intptr_t handle)
Victor Stinner581139c2016-09-06 15:54:20 -070012236/*[clinic end generated code: output=36be5afca6ea84d8 input=cfe99f9c05c70ad1]*/
Larry Hastings2f936352014-08-05 14:04:04 +100012237{
12238 DWORD flags;
Victor Stinnerdaf45552013-08-28 00:53:59 +020012239
12240 if (!GetHandleInformation((HANDLE)handle, &flags)) {
12241 PyErr_SetFromWindowsErr(0);
Larry Hastings2f936352014-08-05 14:04:04 +100012242 return -1;
Victor Stinnerdaf45552013-08-28 00:53:59 +020012243 }
12244
Larry Hastings2f936352014-08-05 14:04:04 +100012245 return flags & HANDLE_FLAG_INHERIT;
Victor Stinnerdaf45552013-08-28 00:53:59 +020012246}
12247
Victor Stinnerdaf45552013-08-28 00:53:59 +020012248
Larry Hastings2f936352014-08-05 14:04:04 +100012249/*[clinic input]
12250os.set_handle_inheritable
Benjamin Petersonca470632016-09-06 13:47:26 -070012251 handle: intptr_t
Larry Hastings2f936352014-08-05 14:04:04 +100012252 inheritable: bool
12253 /
12254
12255Set the inheritable flag of the specified handle.
12256[clinic start generated code]*/
12257
Larry Hastings2f936352014-08-05 14:04:04 +100012258static PyObject *
Benjamin Petersonca470632016-09-06 13:47:26 -070012259os_set_handle_inheritable_impl(PyObject *module, intptr_t handle,
Larry Hastings89964c42015-04-14 18:07:59 -040012260 int inheritable)
Victor Stinner581139c2016-09-06 15:54:20 -070012261/*[clinic end generated code: output=021d74fe6c96baa3 input=7a7641390d8364fc]*/
Larry Hastings2f936352014-08-05 14:04:04 +100012262{
12263 DWORD flags = inheritable ? HANDLE_FLAG_INHERIT : 0;
Victor Stinnerdaf45552013-08-28 00:53:59 +020012264 if (!SetHandleInformation((HANDLE)handle, HANDLE_FLAG_INHERIT, flags)) {
12265 PyErr_SetFromWindowsErr(0);
12266 return NULL;
12267 }
12268 Py_RETURN_NONE;
12269}
Larry Hastings2f936352014-08-05 14:04:04 +100012270#endif /* MS_WINDOWS */
Antoine Pitroubcf2b592012-02-08 23:28:36 +010012271
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012272#ifndef MS_WINDOWS
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030012273/*[clinic input]
12274os.get_blocking -> bool
12275 fd: int
12276 /
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012277
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030012278Get the blocking mode of the file descriptor.
12279
12280Return False if the O_NONBLOCK flag is set, True if the flag is cleared.
12281[clinic start generated code]*/
12282
12283static int
12284os_get_blocking_impl(PyObject *module, int fd)
12285/*[clinic end generated code: output=336a12ad76a61482 input=f4afb59d51560179]*/
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012286{
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012287 int blocking;
12288
Steve Dower8fc89802015-04-12 00:26:27 -040012289 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012290 blocking = _Py_get_blocking(fd);
Steve Dower8fc89802015-04-12 00:26:27 -040012291 _Py_END_SUPPRESS_IPH
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030012292 return blocking;
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012293}
12294
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030012295/*[clinic input]
12296os.set_blocking
12297 fd: int
12298 blocking: bool(accept={int})
12299 /
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012300
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030012301Set the blocking mode of the specified file descriptor.
12302
12303Set the O_NONBLOCK flag if blocking is False,
12304clear the O_NONBLOCK flag otherwise.
12305[clinic start generated code]*/
12306
12307static PyObject *
12308os_set_blocking_impl(PyObject *module, int fd, int blocking)
12309/*[clinic end generated code: output=384eb43aa0762a9d input=bf5c8efdc5860ff3]*/
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012310{
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030012311 int result;
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012312
Steve Dower8fc89802015-04-12 00:26:27 -040012313 _Py_BEGIN_SUPPRESS_IPH
12314 result = _Py_set_blocking(fd, blocking);
12315 _Py_END_SUPPRESS_IPH
12316 if (result < 0)
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012317 return NULL;
12318 Py_RETURN_NONE;
12319}
12320#endif /* !MS_WINDOWS */
12321
12322
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012323/*[clinic input]
12324class os.DirEntry "DirEntry *" "&DirEntryType"
12325[clinic start generated code]*/
12326/*[clinic end generated code: output=da39a3ee5e6b4b0d input=3138f09f7c683f1d]*/
Victor Stinner6036e442015-03-08 01:58:04 +010012327
12328typedef struct {
12329 PyObject_HEAD
12330 PyObject *name;
12331 PyObject *path;
12332 PyObject *stat;
12333 PyObject *lstat;
12334#ifdef MS_WINDOWS
12335 struct _Py_stat_struct win32_lstat;
Victor Stinner0f6d7332017-03-09 17:34:28 +010012336 uint64_t win32_file_index;
Victor Stinner6036e442015-03-08 01:58:04 +010012337 int got_file_index;
12338#else /* POSIX */
Victor Stinner35a97c02015-03-08 02:59:09 +010012339#ifdef HAVE_DIRENT_D_TYPE
Victor Stinner6036e442015-03-08 01:58:04 +010012340 unsigned char d_type;
Victor Stinner35a97c02015-03-08 02:59:09 +010012341#endif
Victor Stinner6036e442015-03-08 01:58:04 +010012342 ino_t d_ino;
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012343 int dir_fd;
Victor Stinner6036e442015-03-08 01:58:04 +010012344#endif
12345} DirEntry;
12346
12347static void
12348DirEntry_dealloc(DirEntry *entry)
12349{
12350 Py_XDECREF(entry->name);
12351 Py_XDECREF(entry->path);
12352 Py_XDECREF(entry->stat);
12353 Py_XDECREF(entry->lstat);
12354 Py_TYPE(entry)->tp_free((PyObject *)entry);
12355}
12356
12357/* Forward reference */
12358static int
12359DirEntry_test_mode(DirEntry *self, int follow_symlinks, unsigned short mode_bits);
12360
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012361/*[clinic input]
12362os.DirEntry.is_symlink -> bool
12363
12364Return True if the entry is a symbolic link; cached per entry.
12365[clinic start generated code]*/
12366
Victor Stinner6036e442015-03-08 01:58:04 +010012367static int
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012368os_DirEntry_is_symlink_impl(DirEntry *self)
12369/*[clinic end generated code: output=42244667d7bcfc25 input=1605a1b4b96976c3]*/
Victor Stinner6036e442015-03-08 01:58:04 +010012370{
12371#ifdef MS_WINDOWS
12372 return (self->win32_lstat.st_mode & S_IFMT) == S_IFLNK;
Victor Stinner35a97c02015-03-08 02:59:09 +010012373#elif defined(HAVE_DIRENT_D_TYPE)
12374 /* POSIX */
Victor Stinner6036e442015-03-08 01:58:04 +010012375 if (self->d_type != DT_UNKNOWN)
12376 return self->d_type == DT_LNK;
12377 else
12378 return DirEntry_test_mode(self, 0, S_IFLNK);
Victor Stinner35a97c02015-03-08 02:59:09 +010012379#else
12380 /* POSIX without d_type */
12381 return DirEntry_test_mode(self, 0, S_IFLNK);
Victor Stinner6036e442015-03-08 01:58:04 +010012382#endif
12383}
12384
12385static PyObject *
Victor Stinner6036e442015-03-08 01:58:04 +010012386DirEntry_fetch_stat(DirEntry *self, int follow_symlinks)
12387{
12388 int result;
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012389 STRUCT_STAT st;
12390 PyObject *ub;
Victor Stinner6036e442015-03-08 01:58:04 +010012391
12392#ifdef MS_WINDOWS
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012393 if (!PyUnicode_FSDecoder(self->path, &ub))
12394 return NULL;
12395 const wchar_t *path = PyUnicode_AsUnicode(ub);
Victor Stinner6036e442015-03-08 01:58:04 +010012396#else /* POSIX */
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012397 if (!PyUnicode_FSConverter(self->path, &ub))
12398 return NULL;
12399 const char *path = PyBytes_AS_STRING(ub);
12400 if (self->dir_fd != DEFAULT_DIR_FD) {
12401#ifdef HAVE_FSTATAT
12402 result = fstatat(self->dir_fd, path, &st,
12403 follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW);
12404#else
12405 PyErr_SetString(PyExc_NotImplementedError, "can't fetch stat");
12406 return NULL;
12407#endif /* HAVE_FSTATAT */
12408 }
12409 else
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012410#endif
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012411 {
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012412 if (follow_symlinks)
12413 result = STAT(path, &st);
12414 else
12415 result = LSTAT(path, &st);
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012416 }
12417 Py_DECREF(ub);
Victor Stinner6036e442015-03-08 01:58:04 +010012418
12419 if (result != 0)
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012420 return path_object_error(self->path);
Victor Stinner6036e442015-03-08 01:58:04 +010012421
12422 return _pystat_fromstructstat(&st);
12423}
12424
12425static PyObject *
12426DirEntry_get_lstat(DirEntry *self)
12427{
12428 if (!self->lstat) {
12429#ifdef MS_WINDOWS
12430 self->lstat = _pystat_fromstructstat(&self->win32_lstat);
12431#else /* POSIX */
12432 self->lstat = DirEntry_fetch_stat(self, 0);
12433#endif
12434 }
12435 Py_XINCREF(self->lstat);
12436 return self->lstat;
12437}
12438
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012439/*[clinic input]
12440os.DirEntry.stat
12441 *
12442 follow_symlinks: bool = True
12443
12444Return stat_result object for the entry; cached per entry.
12445[clinic start generated code]*/
12446
Victor Stinner6036e442015-03-08 01:58:04 +010012447static PyObject *
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012448os_DirEntry_stat_impl(DirEntry *self, int follow_symlinks)
12449/*[clinic end generated code: output=008593b3a6d01305 input=280d14c1d6f1d00d]*/
Victor Stinner6036e442015-03-08 01:58:04 +010012450{
12451 if (!follow_symlinks)
12452 return DirEntry_get_lstat(self);
12453
12454 if (!self->stat) {
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012455 int result = os_DirEntry_is_symlink_impl(self);
Victor Stinner6036e442015-03-08 01:58:04 +010012456 if (result == -1)
12457 return NULL;
12458 else if (result)
12459 self->stat = DirEntry_fetch_stat(self, 1);
12460 else
12461 self->stat = DirEntry_get_lstat(self);
12462 }
12463
12464 Py_XINCREF(self->stat);
12465 return self->stat;
12466}
12467
Victor Stinner6036e442015-03-08 01:58:04 +010012468/* Set exception and return -1 on error, 0 for False, 1 for True */
12469static int
12470DirEntry_test_mode(DirEntry *self, int follow_symlinks, unsigned short mode_bits)
12471{
12472 PyObject *stat = NULL;
12473 PyObject *st_mode = NULL;
12474 long mode;
12475 int result;
Victor Stinner35a97c02015-03-08 02:59:09 +010012476#if defined(MS_WINDOWS) || defined(HAVE_DIRENT_D_TYPE)
Victor Stinner6036e442015-03-08 01:58:04 +010012477 int is_symlink;
12478 int need_stat;
Victor Stinner35a97c02015-03-08 02:59:09 +010012479#endif
Victor Stinner6036e442015-03-08 01:58:04 +010012480#ifdef MS_WINDOWS
12481 unsigned long dir_bits;
12482#endif
Victor Stinner35a97c02015-03-08 02:59:09 +010012483 _Py_IDENTIFIER(st_mode);
Victor Stinner6036e442015-03-08 01:58:04 +010012484
12485#ifdef MS_WINDOWS
12486 is_symlink = (self->win32_lstat.st_mode & S_IFMT) == S_IFLNK;
12487 need_stat = follow_symlinks && is_symlink;
Victor Stinner35a97c02015-03-08 02:59:09 +010012488#elif defined(HAVE_DIRENT_D_TYPE)
Victor Stinner6036e442015-03-08 01:58:04 +010012489 is_symlink = self->d_type == DT_LNK;
12490 need_stat = self->d_type == DT_UNKNOWN || (follow_symlinks && is_symlink);
12491#endif
12492
Victor Stinner35a97c02015-03-08 02:59:09 +010012493#if defined(MS_WINDOWS) || defined(HAVE_DIRENT_D_TYPE)
Victor Stinner6036e442015-03-08 01:58:04 +010012494 if (need_stat) {
Victor Stinner35a97c02015-03-08 02:59:09 +010012495#endif
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012496 stat = os_DirEntry_stat_impl(self, follow_symlinks);
Victor Stinner6036e442015-03-08 01:58:04 +010012497 if (!stat) {
12498 if (PyErr_ExceptionMatches(PyExc_FileNotFoundError)) {
12499 /* If file doesn't exist (anymore), then return False
12500 (i.e., say it's not a file/directory) */
12501 PyErr_Clear();
12502 return 0;
12503 }
12504 goto error;
12505 }
12506 st_mode = _PyObject_GetAttrId(stat, &PyId_st_mode);
12507 if (!st_mode)
12508 goto error;
12509
12510 mode = PyLong_AsLong(st_mode);
12511 if (mode == -1 && PyErr_Occurred())
12512 goto error;
12513 Py_CLEAR(st_mode);
12514 Py_CLEAR(stat);
12515 result = (mode & S_IFMT) == mode_bits;
Victor Stinner35a97c02015-03-08 02:59:09 +010012516#if defined(MS_WINDOWS) || defined(HAVE_DIRENT_D_TYPE)
Victor Stinner6036e442015-03-08 01:58:04 +010012517 }
12518 else if (is_symlink) {
12519 assert(mode_bits != S_IFLNK);
12520 result = 0;
12521 }
12522 else {
12523 assert(mode_bits == S_IFDIR || mode_bits == S_IFREG);
12524#ifdef MS_WINDOWS
12525 dir_bits = self->win32_lstat.st_file_attributes & FILE_ATTRIBUTE_DIRECTORY;
12526 if (mode_bits == S_IFDIR)
12527 result = dir_bits != 0;
12528 else
12529 result = dir_bits == 0;
12530#else /* POSIX */
12531 if (mode_bits == S_IFDIR)
12532 result = self->d_type == DT_DIR;
12533 else
12534 result = self->d_type == DT_REG;
12535#endif
12536 }
Victor Stinner35a97c02015-03-08 02:59:09 +010012537#endif
Victor Stinner6036e442015-03-08 01:58:04 +010012538
12539 return result;
12540
12541error:
12542 Py_XDECREF(st_mode);
12543 Py_XDECREF(stat);
12544 return -1;
12545}
12546
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012547/*[clinic input]
12548os.DirEntry.is_dir -> bool
12549 *
12550 follow_symlinks: bool = True
Victor Stinner6036e442015-03-08 01:58:04 +010012551
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012552Return True if the entry is a directory; cached per entry.
12553[clinic start generated code]*/
12554
12555static int
12556os_DirEntry_is_dir_impl(DirEntry *self, int follow_symlinks)
12557/*[clinic end generated code: output=ad2e8d54365da287 input=0135232766f53f58]*/
12558{
12559 return DirEntry_test_mode(self, follow_symlinks, S_IFDIR);
Victor Stinner6036e442015-03-08 01:58:04 +010012560}
12561
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012562/*[clinic input]
12563os.DirEntry.is_file -> bool
12564 *
12565 follow_symlinks: bool = True
12566
12567Return True if the entry is a file; cached per entry.
12568[clinic start generated code]*/
12569
12570static int
12571os_DirEntry_is_file_impl(DirEntry *self, int follow_symlinks)
12572/*[clinic end generated code: output=8462ade481d8a476 input=0dc90be168b041ee]*/
Victor Stinner6036e442015-03-08 01:58:04 +010012573{
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012574 return DirEntry_test_mode(self, follow_symlinks, S_IFREG);
Victor Stinner6036e442015-03-08 01:58:04 +010012575}
12576
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012577/*[clinic input]
12578os.DirEntry.inode
Victor Stinner6036e442015-03-08 01:58:04 +010012579
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012580Return inode of the entry; cached per entry.
12581[clinic start generated code]*/
Victor Stinner6036e442015-03-08 01:58:04 +010012582
12583static PyObject *
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012584os_DirEntry_inode_impl(DirEntry *self)
12585/*[clinic end generated code: output=156bb3a72162440e input=3ee7b872ae8649f0]*/
Victor Stinner6036e442015-03-08 01:58:04 +010012586{
12587#ifdef MS_WINDOWS
12588 if (!self->got_file_index) {
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012589 PyObject *unicode;
Serhiy Storchakadeab18d2016-05-07 16:45:18 +030012590 const wchar_t *path;
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012591 STRUCT_STAT stat;
12592 int result;
Victor Stinner6036e442015-03-08 01:58:04 +010012593
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012594 if (!PyUnicode_FSDecoder(self->path, &unicode))
Victor Stinner6036e442015-03-08 01:58:04 +010012595 return NULL;
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012596 path = PyUnicode_AsUnicode(unicode);
12597 result = LSTAT(path, &stat);
12598 Py_DECREF(unicode);
Victor Stinner6036e442015-03-08 01:58:04 +010012599
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012600 if (result != 0)
12601 return path_object_error(self->path);
Victor Stinner6036e442015-03-08 01:58:04 +010012602
12603 self->win32_file_index = stat.st_ino;
12604 self->got_file_index = 1;
12605 }
Victor Stinner0f6d7332017-03-09 17:34:28 +010012606 Py_BUILD_ASSERT(sizeof(unsigned long long) >= sizeof(self->win32_file_index));
12607 return PyLong_FromUnsignedLongLong(self->win32_file_index);
Victor Stinner6036e442015-03-08 01:58:04 +010012608#else /* POSIX */
xdegaye50e86032017-05-22 11:15:08 +020012609 Py_BUILD_ASSERT(sizeof(unsigned long long) >= sizeof(self->d_ino));
12610 return PyLong_FromUnsignedLongLong(self->d_ino);
Victor Stinner6036e442015-03-08 01:58:04 +010012611#endif
12612}
12613
12614static PyObject *
12615DirEntry_repr(DirEntry *self)
12616{
12617 return PyUnicode_FromFormat("<DirEntry %R>", self->name);
12618}
12619
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012620/*[clinic input]
12621os.DirEntry.__fspath__
12622
12623Returns the path for the entry.
12624[clinic start generated code]*/
12625
Brett Cannon96881cd2016-06-10 14:37:21 -070012626static PyObject *
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012627os_DirEntry___fspath___impl(DirEntry *self)
12628/*[clinic end generated code: output=6dd7f7ef752e6f4f input=3c49d0cf38df4fac]*/
Brett Cannon96881cd2016-06-10 14:37:21 -070012629{
12630 Py_INCREF(self->path);
12631 return self->path;
12632}
12633
Victor Stinner6036e442015-03-08 01:58:04 +010012634static PyMemberDef DirEntry_members[] = {
12635 {"name", T_OBJECT_EX, offsetof(DirEntry, name), READONLY,
12636 "the entry's base filename, relative to scandir() \"path\" argument"},
12637 {"path", T_OBJECT_EX, offsetof(DirEntry, path), READONLY,
12638 "the entry's full path name; equivalent to os.path.join(scandir_path, entry.name)"},
12639 {NULL}
12640};
12641
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012642#include "clinic/posixmodule.c.h"
12643
Victor Stinner6036e442015-03-08 01:58:04 +010012644static PyMethodDef DirEntry_methods[] = {
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012645 OS_DIRENTRY_IS_DIR_METHODDEF
12646 OS_DIRENTRY_IS_FILE_METHODDEF
12647 OS_DIRENTRY_IS_SYMLINK_METHODDEF
12648 OS_DIRENTRY_STAT_METHODDEF
12649 OS_DIRENTRY_INODE_METHODDEF
12650 OS_DIRENTRY___FSPATH___METHODDEF
Victor Stinner6036e442015-03-08 01:58:04 +010012651 {NULL}
12652};
12653
Benjamin Peterson5646de42015-04-12 17:56:34 -040012654static PyTypeObject DirEntryType = {
Victor Stinner6036e442015-03-08 01:58:04 +010012655 PyVarObject_HEAD_INIT(NULL, 0)
12656 MODNAME ".DirEntry", /* tp_name */
12657 sizeof(DirEntry), /* tp_basicsize */
12658 0, /* tp_itemsize */
12659 /* methods */
12660 (destructor)DirEntry_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +020012661 0, /* tp_vectorcall_offset */
Victor Stinner6036e442015-03-08 01:58:04 +010012662 0, /* tp_getattr */
12663 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +020012664 0, /* tp_as_async */
Victor Stinner6036e442015-03-08 01:58:04 +010012665 (reprfunc)DirEntry_repr, /* tp_repr */
12666 0, /* tp_as_number */
12667 0, /* tp_as_sequence */
12668 0, /* tp_as_mapping */
12669 0, /* tp_hash */
12670 0, /* tp_call */
12671 0, /* tp_str */
12672 0, /* tp_getattro */
12673 0, /* tp_setattro */
12674 0, /* tp_as_buffer */
12675 Py_TPFLAGS_DEFAULT, /* tp_flags */
12676 0, /* tp_doc */
12677 0, /* tp_traverse */
12678 0, /* tp_clear */
12679 0, /* tp_richcompare */
12680 0, /* tp_weaklistoffset */
12681 0, /* tp_iter */
12682 0, /* tp_iternext */
12683 DirEntry_methods, /* tp_methods */
12684 DirEntry_members, /* tp_members */
12685};
12686
12687#ifdef MS_WINDOWS
12688
12689static wchar_t *
Serhiy Storchakadeab18d2016-05-07 16:45:18 +030012690join_path_filenameW(const wchar_t *path_wide, const wchar_t *filename)
Victor Stinner6036e442015-03-08 01:58:04 +010012691{
12692 Py_ssize_t path_len;
12693 Py_ssize_t size;
12694 wchar_t *result;
12695 wchar_t ch;
12696
12697 if (!path_wide) { /* Default arg: "." */
12698 path_wide = L".";
12699 path_len = 1;
12700 }
12701 else {
12702 path_len = wcslen(path_wide);
12703 }
12704
12705 /* The +1's are for the path separator and the NUL */
12706 size = path_len + 1 + wcslen(filename) + 1;
12707 result = PyMem_New(wchar_t, size);
12708 if (!result) {
12709 PyErr_NoMemory();
12710 return NULL;
12711 }
12712 wcscpy(result, path_wide);
12713 if (path_len > 0) {
12714 ch = result[path_len - 1];
12715 if (ch != SEP && ch != ALTSEP && ch != L':')
12716 result[path_len++] = SEP;
12717 wcscpy(result + path_len, filename);
12718 }
12719 return result;
12720}
12721
12722static PyObject *
12723DirEntry_from_find_data(path_t *path, WIN32_FIND_DATAW *dataW)
12724{
12725 DirEntry *entry;
12726 BY_HANDLE_FILE_INFORMATION file_info;
12727 ULONG reparse_tag;
12728 wchar_t *joined_path;
12729
12730 entry = PyObject_New(DirEntry, &DirEntryType);
12731 if (!entry)
12732 return NULL;
12733 entry->name = NULL;
12734 entry->path = NULL;
12735 entry->stat = NULL;
12736 entry->lstat = NULL;
12737 entry->got_file_index = 0;
12738
12739 entry->name = PyUnicode_FromWideChar(dataW->cFileName, -1);
12740 if (!entry->name)
12741 goto error;
Steve Dowercc16be82016-09-08 10:35:16 -070012742 if (path->narrow) {
12743 Py_SETREF(entry->name, PyUnicode_EncodeFSDefault(entry->name));
12744 if (!entry->name)
12745 goto error;
12746 }
Victor Stinner6036e442015-03-08 01:58:04 +010012747
12748 joined_path = join_path_filenameW(path->wide, dataW->cFileName);
12749 if (!joined_path)
12750 goto error;
12751
12752 entry->path = PyUnicode_FromWideChar(joined_path, -1);
12753 PyMem_Free(joined_path);
12754 if (!entry->path)
12755 goto error;
Steve Dowercc16be82016-09-08 10:35:16 -070012756 if (path->narrow) {
12757 Py_SETREF(entry->path, PyUnicode_EncodeFSDefault(entry->path));
12758 if (!entry->path)
12759 goto error;
12760 }
Victor Stinner6036e442015-03-08 01:58:04 +010012761
Steve Dowercc16be82016-09-08 10:35:16 -070012762 find_data_to_file_info(dataW, &file_info, &reparse_tag);
Victor Stinner6036e442015-03-08 01:58:04 +010012763 _Py_attribute_data_to_stat(&file_info, reparse_tag, &entry->win32_lstat);
12764
12765 return (PyObject *)entry;
12766
12767error:
12768 Py_DECREF(entry);
12769 return NULL;
12770}
12771
12772#else /* POSIX */
12773
12774static char *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +020012775join_path_filename(const char *path_narrow, const char* filename, Py_ssize_t filename_len)
Victor Stinner6036e442015-03-08 01:58:04 +010012776{
12777 Py_ssize_t path_len;
12778 Py_ssize_t size;
12779 char *result;
12780
12781 if (!path_narrow) { /* Default arg: "." */
12782 path_narrow = ".";
12783 path_len = 1;
12784 }
12785 else {
12786 path_len = strlen(path_narrow);
12787 }
12788
12789 if (filename_len == -1)
12790 filename_len = strlen(filename);
12791
12792 /* The +1's are for the path separator and the NUL */
12793 size = path_len + 1 + filename_len + 1;
12794 result = PyMem_New(char, size);
12795 if (!result) {
12796 PyErr_NoMemory();
12797 return NULL;
12798 }
12799 strcpy(result, path_narrow);
12800 if (path_len > 0 && result[path_len - 1] != '/')
12801 result[path_len++] = '/';
12802 strcpy(result + path_len, filename);
12803 return result;
12804}
12805
12806static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +020012807DirEntry_from_posix_info(path_t *path, const char *name, Py_ssize_t name_len,
Victor Stinner35a97c02015-03-08 02:59:09 +010012808 ino_t d_ino
12809#ifdef HAVE_DIRENT_D_TYPE
12810 , unsigned char d_type
12811#endif
12812 )
Victor Stinner6036e442015-03-08 01:58:04 +010012813{
12814 DirEntry *entry;
12815 char *joined_path;
12816
12817 entry = PyObject_New(DirEntry, &DirEntryType);
12818 if (!entry)
12819 return NULL;
12820 entry->name = NULL;
12821 entry->path = NULL;
12822 entry->stat = NULL;
12823 entry->lstat = NULL;
12824
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012825 if (path->fd != -1) {
12826 entry->dir_fd = path->fd;
12827 joined_path = NULL;
12828 }
12829 else {
12830 entry->dir_fd = DEFAULT_DIR_FD;
12831 joined_path = join_path_filename(path->narrow, name, name_len);
12832 if (!joined_path)
12833 goto error;
12834 }
Victor Stinner6036e442015-03-08 01:58:04 +010012835
Serhiy Storchaka1180e5a2017-07-11 06:36:46 +030012836 if (!path->narrow || !PyObject_CheckBuffer(path->object)) {
Victor Stinner6036e442015-03-08 01:58:04 +010012837 entry->name = PyUnicode_DecodeFSDefaultAndSize(name, name_len);
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012838 if (joined_path)
12839 entry->path = PyUnicode_DecodeFSDefault(joined_path);
Victor Stinner6036e442015-03-08 01:58:04 +010012840 }
12841 else {
12842 entry->name = PyBytes_FromStringAndSize(name, name_len);
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012843 if (joined_path)
12844 entry->path = PyBytes_FromString(joined_path);
Victor Stinner6036e442015-03-08 01:58:04 +010012845 }
12846 PyMem_Free(joined_path);
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012847 if (!entry->name)
12848 goto error;
12849
12850 if (path->fd != -1) {
12851 entry->path = entry->name;
12852 Py_INCREF(entry->path);
12853 }
12854 else if (!entry->path)
Victor Stinner6036e442015-03-08 01:58:04 +010012855 goto error;
12856
Victor Stinner35a97c02015-03-08 02:59:09 +010012857#ifdef HAVE_DIRENT_D_TYPE
Victor Stinner6036e442015-03-08 01:58:04 +010012858 entry->d_type = d_type;
Victor Stinner35a97c02015-03-08 02:59:09 +010012859#endif
Victor Stinner6036e442015-03-08 01:58:04 +010012860 entry->d_ino = d_ino;
12861
12862 return (PyObject *)entry;
12863
12864error:
12865 Py_XDECREF(entry);
12866 return NULL;
12867}
12868
12869#endif
12870
12871
12872typedef struct {
12873 PyObject_HEAD
12874 path_t path;
12875#ifdef MS_WINDOWS
12876 HANDLE handle;
12877 WIN32_FIND_DATAW file_data;
12878 int first_time;
12879#else /* POSIX */
12880 DIR *dirp;
12881#endif
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012882#ifdef HAVE_FDOPENDIR
12883 int fd;
12884#endif
Victor Stinner6036e442015-03-08 01:58:04 +010012885} ScandirIterator;
12886
12887#ifdef MS_WINDOWS
12888
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020012889static int
12890ScandirIterator_is_closed(ScandirIterator *iterator)
12891{
12892 return iterator->handle == INVALID_HANDLE_VALUE;
12893}
12894
Victor Stinner6036e442015-03-08 01:58:04 +010012895static void
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020012896ScandirIterator_closedir(ScandirIterator *iterator)
Victor Stinner6036e442015-03-08 01:58:04 +010012897{
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030012898 HANDLE handle = iterator->handle;
12899
12900 if (handle == INVALID_HANDLE_VALUE)
Victor Stinner6036e442015-03-08 01:58:04 +010012901 return;
12902
Victor Stinner6036e442015-03-08 01:58:04 +010012903 iterator->handle = INVALID_HANDLE_VALUE;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030012904 Py_BEGIN_ALLOW_THREADS
12905 FindClose(handle);
12906 Py_END_ALLOW_THREADS
Victor Stinner6036e442015-03-08 01:58:04 +010012907}
12908
12909static PyObject *
12910ScandirIterator_iternext(ScandirIterator *iterator)
12911{
12912 WIN32_FIND_DATAW *file_data = &iterator->file_data;
12913 BOOL success;
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020012914 PyObject *entry;
Victor Stinner6036e442015-03-08 01:58:04 +010012915
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020012916 /* Happens if the iterator is iterated twice, or closed explicitly */
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020012917 if (iterator->handle == INVALID_HANDLE_VALUE)
Victor Stinner6036e442015-03-08 01:58:04 +010012918 return NULL;
Victor Stinner6036e442015-03-08 01:58:04 +010012919
12920 while (1) {
12921 if (!iterator->first_time) {
12922 Py_BEGIN_ALLOW_THREADS
12923 success = FindNextFileW(iterator->handle, file_data);
12924 Py_END_ALLOW_THREADS
12925 if (!success) {
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020012926 /* Error or no more files */
Victor Stinner6036e442015-03-08 01:58:04 +010012927 if (GetLastError() != ERROR_NO_MORE_FILES)
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020012928 path_error(&iterator->path);
Victor Stinner6036e442015-03-08 01:58:04 +010012929 break;
12930 }
12931 }
12932 iterator->first_time = 0;
12933
12934 /* Skip over . and .. */
12935 if (wcscmp(file_data->cFileName, L".") != 0 &&
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020012936 wcscmp(file_data->cFileName, L"..") != 0) {
12937 entry = DirEntry_from_find_data(&iterator->path, file_data);
12938 if (!entry)
12939 break;
12940 return entry;
12941 }
Victor Stinner6036e442015-03-08 01:58:04 +010012942
12943 /* Loop till we get a non-dot directory or finish iterating */
12944 }
12945
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020012946 /* Error or no more files */
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020012947 ScandirIterator_closedir(iterator);
Victor Stinner6036e442015-03-08 01:58:04 +010012948 return NULL;
12949}
12950
12951#else /* POSIX */
12952
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020012953static int
12954ScandirIterator_is_closed(ScandirIterator *iterator)
12955{
12956 return !iterator->dirp;
12957}
12958
Victor Stinner6036e442015-03-08 01:58:04 +010012959static void
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020012960ScandirIterator_closedir(ScandirIterator *iterator)
Victor Stinner6036e442015-03-08 01:58:04 +010012961{
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030012962 DIR *dirp = iterator->dirp;
12963
12964 if (!dirp)
Victor Stinner6036e442015-03-08 01:58:04 +010012965 return;
12966
Victor Stinner6036e442015-03-08 01:58:04 +010012967 iterator->dirp = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030012968 Py_BEGIN_ALLOW_THREADS
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012969#ifdef HAVE_FDOPENDIR
12970 if (iterator->path.fd != -1)
12971 rewinddir(dirp);
12972#endif
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030012973 closedir(dirp);
12974 Py_END_ALLOW_THREADS
Victor Stinner6036e442015-03-08 01:58:04 +010012975 return;
12976}
12977
12978static PyObject *
12979ScandirIterator_iternext(ScandirIterator *iterator)
12980{
12981 struct dirent *direntp;
12982 Py_ssize_t name_len;
12983 int is_dot;
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020012984 PyObject *entry;
Victor Stinner6036e442015-03-08 01:58:04 +010012985
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020012986 /* Happens if the iterator is iterated twice, or closed explicitly */
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020012987 if (!iterator->dirp)
Victor Stinner6036e442015-03-08 01:58:04 +010012988 return NULL;
Victor Stinner6036e442015-03-08 01:58:04 +010012989
12990 while (1) {
12991 errno = 0;
12992 Py_BEGIN_ALLOW_THREADS
12993 direntp = readdir(iterator->dirp);
12994 Py_END_ALLOW_THREADS
12995
12996 if (!direntp) {
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020012997 /* Error or no more files */
Victor Stinner6036e442015-03-08 01:58:04 +010012998 if (errno != 0)
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020012999 path_error(&iterator->path);
Victor Stinner6036e442015-03-08 01:58:04 +010013000 break;
13001 }
13002
13003 /* Skip over . and .. */
13004 name_len = NAMLEN(direntp);
13005 is_dot = direntp->d_name[0] == '.' &&
13006 (name_len == 1 || (direntp->d_name[1] == '.' && name_len == 2));
13007 if (!is_dot) {
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013008 entry = DirEntry_from_posix_info(&iterator->path, direntp->d_name,
Victor Stinner35a97c02015-03-08 02:59:09 +010013009 name_len, direntp->d_ino
13010#ifdef HAVE_DIRENT_D_TYPE
13011 , direntp->d_type
13012#endif
13013 );
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013014 if (!entry)
13015 break;
13016 return entry;
Victor Stinner6036e442015-03-08 01:58:04 +010013017 }
13018
13019 /* Loop till we get a non-dot directory or finish iterating */
13020 }
13021
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013022 /* Error or no more files */
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013023 ScandirIterator_closedir(iterator);
Victor Stinner6036e442015-03-08 01:58:04 +010013024 return NULL;
13025}
13026
13027#endif
13028
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013029static PyObject *
13030ScandirIterator_close(ScandirIterator *self, PyObject *args)
13031{
13032 ScandirIterator_closedir(self);
13033 Py_RETURN_NONE;
13034}
13035
13036static PyObject *
13037ScandirIterator_enter(PyObject *self, PyObject *args)
13038{
13039 Py_INCREF(self);
13040 return self;
13041}
13042
13043static PyObject *
13044ScandirIterator_exit(ScandirIterator *self, PyObject *args)
13045{
13046 ScandirIterator_closedir(self);
13047 Py_RETURN_NONE;
13048}
13049
Victor Stinner6036e442015-03-08 01:58:04 +010013050static void
Victor Stinner7bfa4092016-03-23 00:43:54 +010013051ScandirIterator_finalize(ScandirIterator *iterator)
13052{
13053 PyObject *error_type, *error_value, *error_traceback;
13054
13055 /* Save the current exception, if any. */
13056 PyErr_Fetch(&error_type, &error_value, &error_traceback);
13057
13058 if (!ScandirIterator_is_closed(iterator)) {
13059 ScandirIterator_closedir(iterator);
13060
13061 if (PyErr_ResourceWarning((PyObject *)iterator, 1,
13062 "unclosed scandir iterator %R", iterator)) {
13063 /* Spurious errors can appear at shutdown */
13064 if (PyErr_ExceptionMatches(PyExc_Warning)) {
13065 PyErr_WriteUnraisable((PyObject *) iterator);
13066 }
13067 }
13068 }
13069
Victor Stinner7bfa4092016-03-23 00:43:54 +010013070 path_cleanup(&iterator->path);
13071
13072 /* Restore the saved exception. */
13073 PyErr_Restore(error_type, error_value, error_traceback);
13074}
13075
13076static void
Victor Stinner6036e442015-03-08 01:58:04 +010013077ScandirIterator_dealloc(ScandirIterator *iterator)
13078{
Victor Stinner7bfa4092016-03-23 00:43:54 +010013079 if (PyObject_CallFinalizerFromDealloc((PyObject *)iterator) < 0)
13080 return;
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013081
Victor Stinner6036e442015-03-08 01:58:04 +010013082 Py_TYPE(iterator)->tp_free((PyObject *)iterator);
13083}
13084
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013085static PyMethodDef ScandirIterator_methods[] = {
13086 {"__enter__", (PyCFunction)ScandirIterator_enter, METH_NOARGS},
13087 {"__exit__", (PyCFunction)ScandirIterator_exit, METH_VARARGS},
13088 {"close", (PyCFunction)ScandirIterator_close, METH_NOARGS},
13089 {NULL}
13090};
13091
Benjamin Peterson5646de42015-04-12 17:56:34 -040013092static PyTypeObject ScandirIteratorType = {
Victor Stinner6036e442015-03-08 01:58:04 +010013093 PyVarObject_HEAD_INIT(NULL, 0)
13094 MODNAME ".ScandirIterator", /* tp_name */
13095 sizeof(ScandirIterator), /* tp_basicsize */
13096 0, /* tp_itemsize */
13097 /* methods */
13098 (destructor)ScandirIterator_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +020013099 0, /* tp_vectorcall_offset */
Victor Stinner6036e442015-03-08 01:58:04 +010013100 0, /* tp_getattr */
13101 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +020013102 0, /* tp_as_async */
Victor Stinner6036e442015-03-08 01:58:04 +010013103 0, /* tp_repr */
13104 0, /* tp_as_number */
13105 0, /* tp_as_sequence */
13106 0, /* tp_as_mapping */
13107 0, /* tp_hash */
13108 0, /* tp_call */
13109 0, /* tp_str */
13110 0, /* tp_getattro */
13111 0, /* tp_setattro */
13112 0, /* tp_as_buffer */
Antoine Pitrouada319b2019-05-29 22:12:38 +020013113 Py_TPFLAGS_DEFAULT, /* tp_flags */
Victor Stinner6036e442015-03-08 01:58:04 +010013114 0, /* tp_doc */
13115 0, /* tp_traverse */
13116 0, /* tp_clear */
13117 0, /* tp_richcompare */
13118 0, /* tp_weaklistoffset */
13119 PyObject_SelfIter, /* tp_iter */
13120 (iternextfunc)ScandirIterator_iternext, /* tp_iternext */
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013121 ScandirIterator_methods, /* tp_methods */
Victor Stinner7bfa4092016-03-23 00:43:54 +010013122 0, /* tp_members */
13123 0, /* tp_getset */
13124 0, /* tp_base */
13125 0, /* tp_dict */
13126 0, /* tp_descr_get */
13127 0, /* tp_descr_set */
13128 0, /* tp_dictoffset */
13129 0, /* tp_init */
13130 0, /* tp_alloc */
13131 0, /* tp_new */
13132 0, /* tp_free */
13133 0, /* tp_is_gc */
13134 0, /* tp_bases */
13135 0, /* tp_mro */
13136 0, /* tp_cache */
13137 0, /* tp_subclasses */
13138 0, /* tp_weaklist */
13139 0, /* tp_del */
13140 0, /* tp_version_tag */
13141 (destructor)ScandirIterator_finalize, /* tp_finalize */
Victor Stinner6036e442015-03-08 01:58:04 +010013142};
13143
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013144/*[clinic input]
13145os.scandir
13146
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013147 path : path_t(nullable=True, allow_fd='PATH_HAVE_FDOPENDIR') = None
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013148
13149Return an iterator of DirEntry objects for given path.
13150
BNMetricsb9427072018-11-02 15:20:19 +000013151path can be specified as either str, bytes, or a path-like object. If path
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013152is bytes, the names of yielded DirEntry objects will also be bytes; in
13153all other circumstances they will be str.
13154
13155If path is None, uses the path='.'.
13156[clinic start generated code]*/
13157
Victor Stinner6036e442015-03-08 01:58:04 +010013158static PyObject *
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013159os_scandir_impl(PyObject *module, path_t *path)
BNMetricsb9427072018-11-02 15:20:19 +000013160/*[clinic end generated code: output=6eb2668b675ca89e input=6bdd312708fc3bb0]*/
Victor Stinner6036e442015-03-08 01:58:04 +010013161{
13162 ScandirIterator *iterator;
Victor Stinner6036e442015-03-08 01:58:04 +010013163#ifdef MS_WINDOWS
13164 wchar_t *path_strW;
13165#else
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013166 const char *path_str;
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013167#ifdef HAVE_FDOPENDIR
13168 int fd = -1;
13169#endif
Victor Stinner6036e442015-03-08 01:58:04 +010013170#endif
13171
Steve Dower60419a72019-06-24 08:42:54 -070013172 if (PySys_Audit("os.scandir", "O",
13173 path->object ? path->object : Py_None) < 0) {
13174 return NULL;
13175 }
13176
Victor Stinner6036e442015-03-08 01:58:04 +010013177 iterator = PyObject_New(ScandirIterator, &ScandirIteratorType);
13178 if (!iterator)
13179 return NULL;
Victor Stinner6036e442015-03-08 01:58:04 +010013180
13181#ifdef MS_WINDOWS
13182 iterator->handle = INVALID_HANDLE_VALUE;
13183#else
13184 iterator->dirp = NULL;
13185#endif
13186
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013187 memcpy(&iterator->path, path, sizeof(path_t));
Serhiy Storchaka095ef732017-02-09 20:05:51 +020013188 /* Move the ownership to iterator->path */
13189 path->object = NULL;
13190 path->cleanup = NULL;
Victor Stinner6036e442015-03-08 01:58:04 +010013191
13192#ifdef MS_WINDOWS
Victor Stinner6036e442015-03-08 01:58:04 +010013193 iterator->first_time = 1;
13194
13195 path_strW = join_path_filenameW(iterator->path.wide, L"*.*");
13196 if (!path_strW)
13197 goto error;
13198
13199 Py_BEGIN_ALLOW_THREADS
13200 iterator->handle = FindFirstFileW(path_strW, &iterator->file_data);
13201 Py_END_ALLOW_THREADS
13202
13203 PyMem_Free(path_strW);
13204
13205 if (iterator->handle == INVALID_HANDLE_VALUE) {
13206 path_error(&iterator->path);
13207 goto error;
13208 }
13209#else /* POSIX */
Victor Stinner6036e442015-03-08 01:58:04 +010013210 errno = 0;
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013211#ifdef HAVE_FDOPENDIR
13212 if (path->fd != -1) {
13213 /* closedir() closes the FD, so we duplicate it */
13214 fd = _Py_dup(path->fd);
13215 if (fd == -1)
13216 goto error;
13217
13218 Py_BEGIN_ALLOW_THREADS
13219 iterator->dirp = fdopendir(fd);
13220 Py_END_ALLOW_THREADS
13221 }
13222 else
13223#endif
13224 {
13225 if (iterator->path.narrow)
13226 path_str = iterator->path.narrow;
13227 else
13228 path_str = ".";
13229
13230 Py_BEGIN_ALLOW_THREADS
13231 iterator->dirp = opendir(path_str);
13232 Py_END_ALLOW_THREADS
13233 }
Victor Stinner6036e442015-03-08 01:58:04 +010013234
13235 if (!iterator->dirp) {
13236 path_error(&iterator->path);
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013237#ifdef HAVE_FDOPENDIR
13238 if (fd != -1) {
13239 Py_BEGIN_ALLOW_THREADS
13240 close(fd);
13241 Py_END_ALLOW_THREADS
13242 }
13243#endif
Victor Stinner6036e442015-03-08 01:58:04 +010013244 goto error;
13245 }
13246#endif
13247
13248 return (PyObject *)iterator;
13249
13250error:
13251 Py_DECREF(iterator);
13252 return NULL;
13253}
13254
Ethan Furman410ef8e2016-06-04 12:06:26 -070013255/*
13256 Return the file system path representation of the object.
13257
13258 If the object is str or bytes, then allow it to pass through with
13259 an incremented refcount. If the object defines __fspath__(), then
13260 return the result of that method. All other types raise a TypeError.
13261*/
13262PyObject *
13263PyOS_FSPath(PyObject *path)
13264{
Brett Cannon3f9183b2016-08-26 14:44:48 -070013265 /* For error message reasons, this function is manually inlined in
13266 path_converter(). */
Ethan Furman410ef8e2016-06-04 12:06:26 -070013267 _Py_IDENTIFIER(__fspath__);
13268 PyObject *func = NULL;
13269 PyObject *path_repr = NULL;
13270
13271 if (PyUnicode_Check(path) || PyBytes_Check(path)) {
13272 Py_INCREF(path);
13273 return path;
13274 }
13275
13276 func = _PyObject_LookupSpecial(path, &PyId___fspath__);
13277 if (NULL == func) {
13278 return PyErr_Format(PyExc_TypeError,
13279 "expected str, bytes or os.PathLike object, "
Brett Cannonc78ca1e2016-06-24 12:03:43 -070013280 "not %.200s",
13281 Py_TYPE(path)->tp_name);
Ethan Furman410ef8e2016-06-04 12:06:26 -070013282 }
13283
Victor Stinnerf17c3de2016-12-06 18:46:19 +010013284 path_repr = _PyObject_CallNoArg(func);
Ethan Furman410ef8e2016-06-04 12:06:26 -070013285 Py_DECREF(func);
Brett Cannon044283a2016-07-15 10:41:49 -070013286 if (NULL == path_repr) {
13287 return NULL;
13288 }
13289
Brett Cannonc78ca1e2016-06-24 12:03:43 -070013290 if (!(PyUnicode_Check(path_repr) || PyBytes_Check(path_repr))) {
13291 PyErr_Format(PyExc_TypeError,
13292 "expected %.200s.__fspath__() to return str or bytes, "
13293 "not %.200s", Py_TYPE(path)->tp_name,
13294 Py_TYPE(path_repr)->tp_name);
13295 Py_DECREF(path_repr);
13296 return NULL;
13297 }
13298
Ethan Furman410ef8e2016-06-04 12:06:26 -070013299 return path_repr;
13300}
13301
13302/*[clinic input]
13303os.fspath
13304
13305 path: object
13306
13307Return the file system path representation of the object.
13308
Brett Cannonb4f43e92016-06-09 14:32:08 -070013309If the object is str or bytes, then allow it to pass through as-is. If the
13310object defines __fspath__(), then return the result of that method. All other
13311types raise a TypeError.
Ethan Furman410ef8e2016-06-04 12:06:26 -070013312[clinic start generated code]*/
13313
13314static PyObject *
Serhiy Storchaka2954f832016-07-07 18:20:03 +030013315os_fspath_impl(PyObject *module, PyObject *path)
13316/*[clinic end generated code: output=c3c3b78ecff2914f input=e357165f7b22490f]*/
Ethan Furman410ef8e2016-06-04 12:06:26 -070013317{
13318 return PyOS_FSPath(path);
13319}
Victor Stinner6036e442015-03-08 01:58:04 +010013320
Victor Stinner9b1f4742016-09-06 16:18:52 -070013321#ifdef HAVE_GETRANDOM_SYSCALL
13322/*[clinic input]
13323os.getrandom
13324
13325 size: Py_ssize_t
13326 flags: int=0
13327
13328Obtain a series of random bytes.
13329[clinic start generated code]*/
13330
13331static PyObject *
13332os_getrandom_impl(PyObject *module, Py_ssize_t size, int flags)
13333/*[clinic end generated code: output=b3a618196a61409c input=59bafac39c594947]*/
13334{
Victor Stinner9b1f4742016-09-06 16:18:52 -070013335 PyObject *bytes;
Victor Stinnerec2319c2016-09-20 23:00:59 +020013336 Py_ssize_t n;
Victor Stinner9b1f4742016-09-06 16:18:52 -070013337
13338 if (size < 0) {
13339 errno = EINVAL;
13340 return posix_error();
13341 }
13342
Victor Stinnerec2319c2016-09-20 23:00:59 +020013343 bytes = PyBytes_FromStringAndSize(NULL, size);
13344 if (bytes == NULL) {
Victor Stinner9b1f4742016-09-06 16:18:52 -070013345 PyErr_NoMemory();
13346 return NULL;
13347 }
13348
13349 while (1) {
Victor Stinnerec2319c2016-09-20 23:00:59 +020013350 n = syscall(SYS_getrandom,
13351 PyBytes_AS_STRING(bytes),
13352 PyBytes_GET_SIZE(bytes),
13353 flags);
Victor Stinner9b1f4742016-09-06 16:18:52 -070013354 if (n < 0 && errno == EINTR) {
13355 if (PyErr_CheckSignals() < 0) {
Victor Stinnerec2319c2016-09-20 23:00:59 +020013356 goto error;
Victor Stinner9b1f4742016-09-06 16:18:52 -070013357 }
Victor Stinnerec2319c2016-09-20 23:00:59 +020013358
13359 /* getrandom() was interrupted by a signal: retry */
Victor Stinner9b1f4742016-09-06 16:18:52 -070013360 continue;
13361 }
13362 break;
13363 }
13364
13365 if (n < 0) {
Victor Stinner9b1f4742016-09-06 16:18:52 -070013366 PyErr_SetFromErrno(PyExc_OSError);
Victor Stinnerec2319c2016-09-20 23:00:59 +020013367 goto error;
Victor Stinner9b1f4742016-09-06 16:18:52 -070013368 }
13369
Victor Stinnerec2319c2016-09-20 23:00:59 +020013370 if (n != size) {
13371 _PyBytes_Resize(&bytes, n);
13372 }
Victor Stinner9b1f4742016-09-06 16:18:52 -070013373
13374 return bytes;
Victor Stinnerec2319c2016-09-20 23:00:59 +020013375
13376error:
13377 Py_DECREF(bytes);
13378 return NULL;
Victor Stinner9b1f4742016-09-06 16:18:52 -070013379}
13380#endif /* HAVE_GETRANDOM_SYSCALL */
13381
Steve Dower2438cdf2019-03-29 16:37:16 -070013382#ifdef MS_WINDOWS
13383/* bpo-36085: Helper functions for managing DLL search directories
13384 * on win32
13385 */
13386
13387typedef DLL_DIRECTORY_COOKIE (WINAPI *PAddDllDirectory)(PCWSTR newDirectory);
13388typedef BOOL (WINAPI *PRemoveDllDirectory)(DLL_DIRECTORY_COOKIE cookie);
13389
13390/*[clinic input]
13391os._add_dll_directory
13392
13393 path: path_t
13394
13395Add a path to the DLL search path.
13396
13397This search path is used when resolving dependencies for imported
13398extension modules (the module itself is resolved through sys.path),
13399and also by ctypes.
13400
13401Returns an opaque value that may be passed to os.remove_dll_directory
13402to remove this directory from the search path.
13403[clinic start generated code]*/
13404
13405static PyObject *
13406os__add_dll_directory_impl(PyObject *module, path_t *path)
13407/*[clinic end generated code: output=80b025daebb5d683 input=1de3e6c13a5808c8]*/
13408{
13409 HMODULE hKernel32;
13410 PAddDllDirectory AddDllDirectory;
13411 DLL_DIRECTORY_COOKIE cookie = 0;
13412 DWORD err = 0;
13413
13414 /* For Windows 7, we have to load this. As this will be a fairly
13415 infrequent operation, just do it each time. Kernel32 is always
13416 loaded. */
13417 Py_BEGIN_ALLOW_THREADS
13418 if (!(hKernel32 = GetModuleHandleW(L"kernel32")) ||
13419 !(AddDllDirectory = (PAddDllDirectory)GetProcAddress(
13420 hKernel32, "AddDllDirectory")) ||
13421 !(cookie = (*AddDllDirectory)(path->wide))) {
13422 err = GetLastError();
13423 }
13424 Py_END_ALLOW_THREADS
13425
13426 if (err) {
13427 return win32_error_object_err("add_dll_directory",
13428 path->object, err);
13429 }
13430
13431 return PyCapsule_New(cookie, "DLL directory cookie", NULL);
13432}
13433
13434/*[clinic input]
13435os._remove_dll_directory
13436
13437 cookie: object
13438
13439Removes a path from the DLL search path.
13440
13441The parameter is an opaque value that was returned from
13442os.add_dll_directory. You can only remove directories that you added
13443yourself.
13444[clinic start generated code]*/
13445
13446static PyObject *
13447os__remove_dll_directory_impl(PyObject *module, PyObject *cookie)
13448/*[clinic end generated code: output=594350433ae535bc input=c1d16a7e7d9dc5dc]*/
13449{
13450 HMODULE hKernel32;
13451 PRemoveDllDirectory RemoveDllDirectory;
13452 DLL_DIRECTORY_COOKIE cookieValue;
13453 DWORD err = 0;
13454
13455 if (!PyCapsule_IsValid(cookie, "DLL directory cookie")) {
13456 PyErr_SetString(PyExc_TypeError,
13457 "Provided cookie was not returned from os.add_dll_directory");
13458 return NULL;
13459 }
13460
13461 cookieValue = (DLL_DIRECTORY_COOKIE)PyCapsule_GetPointer(
13462 cookie, "DLL directory cookie");
13463
13464 /* For Windows 7, we have to load this. As this will be a fairly
13465 infrequent operation, just do it each time. Kernel32 is always
13466 loaded. */
13467 Py_BEGIN_ALLOW_THREADS
13468 if (!(hKernel32 = GetModuleHandleW(L"kernel32")) ||
13469 !(RemoveDllDirectory = (PRemoveDllDirectory)GetProcAddress(
13470 hKernel32, "RemoveDllDirectory")) ||
13471 !(*RemoveDllDirectory)(cookieValue)) {
13472 err = GetLastError();
13473 }
13474 Py_END_ALLOW_THREADS
13475
13476 if (err) {
13477 return win32_error_object_err("remove_dll_directory",
13478 NULL, err);
13479 }
13480
13481 if (PyCapsule_SetName(cookie, NULL)) {
13482 return NULL;
13483 }
13484
13485 Py_RETURN_NONE;
13486}
13487
13488#endif
Larry Hastings31826802013-10-19 00:09:25 -070013489
Fred Drake5ab8eaf1999-12-09 21:13:07 +000013490static PyMethodDef posix_methods[] = {
Larry Hastings31826802013-10-19 00:09:25 -070013491
13492 OS_STAT_METHODDEF
13493 OS_ACCESS_METHODDEF
13494 OS_TTYNAME_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100013495 OS_CHDIR_METHODDEF
13496 OS_CHFLAGS_METHODDEF
13497 OS_CHMOD_METHODDEF
13498 OS_FCHMOD_METHODDEF
13499 OS_LCHMOD_METHODDEF
13500 OS_CHOWN_METHODDEF
13501 OS_FCHOWN_METHODDEF
13502 OS_LCHOWN_METHODDEF
13503 OS_LCHFLAGS_METHODDEF
13504 OS_CHROOT_METHODDEF
13505 OS_CTERMID_METHODDEF
13506 OS_GETCWD_METHODDEF
13507 OS_GETCWDB_METHODDEF
13508 OS_LINK_METHODDEF
13509 OS_LISTDIR_METHODDEF
13510 OS_LSTAT_METHODDEF
13511 OS_MKDIR_METHODDEF
13512 OS_NICE_METHODDEF
13513 OS_GETPRIORITY_METHODDEF
13514 OS_SETPRIORITY_METHODDEF
Pablo Galindo6c6ddf92018-01-29 01:56:10 +000013515 OS_POSIX_SPAWN_METHODDEF
Joannah Nanjekye92b83222019-01-16 16:29:26 +030013516 OS_POSIX_SPAWNP_METHODDEF
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030013517 OS_READLINK_METHODDEF
Pablo Galindoaac4d032019-05-31 19:39:47 +010013518 OS_COPY_FILE_RANGE_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100013519 OS_RENAME_METHODDEF
13520 OS_REPLACE_METHODDEF
13521 OS_RMDIR_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100013522 OS_SYMLINK_METHODDEF
13523 OS_SYSTEM_METHODDEF
13524 OS_UMASK_METHODDEF
13525 OS_UNAME_METHODDEF
13526 OS_UNLINK_METHODDEF
13527 OS_REMOVE_METHODDEF
13528 OS_UTIME_METHODDEF
13529 OS_TIMES_METHODDEF
13530 OS__EXIT_METHODDEF
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +020013531 OS__FCOPYFILE_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100013532 OS_EXECV_METHODDEF
13533 OS_EXECVE_METHODDEF
13534 OS_SPAWNV_METHODDEF
13535 OS_SPAWNVE_METHODDEF
13536 OS_FORK1_METHODDEF
13537 OS_FORK_METHODDEF
Antoine Pitrou346cbd32017-05-27 17:50:54 +020013538 OS_REGISTER_AT_FORK_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100013539 OS_SCHED_GET_PRIORITY_MAX_METHODDEF
13540 OS_SCHED_GET_PRIORITY_MIN_METHODDEF
13541 OS_SCHED_GETPARAM_METHODDEF
13542 OS_SCHED_GETSCHEDULER_METHODDEF
13543 OS_SCHED_RR_GET_INTERVAL_METHODDEF
13544 OS_SCHED_SETPARAM_METHODDEF
13545 OS_SCHED_SETSCHEDULER_METHODDEF
13546 OS_SCHED_YIELD_METHODDEF
13547 OS_SCHED_SETAFFINITY_METHODDEF
13548 OS_SCHED_GETAFFINITY_METHODDEF
13549 OS_OPENPTY_METHODDEF
13550 OS_FORKPTY_METHODDEF
13551 OS_GETEGID_METHODDEF
13552 OS_GETEUID_METHODDEF
13553 OS_GETGID_METHODDEF
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +020013554#ifdef HAVE_GETGROUPLIST
13555 {"getgrouplist", posix_getgrouplist, METH_VARARGS, posix_getgrouplist__doc__},
13556#endif
Larry Hastings2f936352014-08-05 14:04:04 +100013557 OS_GETGROUPS_METHODDEF
13558 OS_GETPID_METHODDEF
13559 OS_GETPGRP_METHODDEF
13560 OS_GETPPID_METHODDEF
13561 OS_GETUID_METHODDEF
13562 OS_GETLOGIN_METHODDEF
13563 OS_KILL_METHODDEF
13564 OS_KILLPG_METHODDEF
13565 OS_PLOCK_METHODDEF
Thomas Heller8b7a9572007-08-31 06:44:36 +000013566#ifdef MS_WINDOWS
Steve Dowercc16be82016-09-08 10:35:16 -070013567 OS_STARTFILE_METHODDEF
Thomas Heller8b7a9572007-08-31 06:44:36 +000013568#endif
Larry Hastings2f936352014-08-05 14:04:04 +100013569 OS_SETUID_METHODDEF
13570 OS_SETEUID_METHODDEF
13571 OS_SETREUID_METHODDEF
13572 OS_SETGID_METHODDEF
13573 OS_SETEGID_METHODDEF
13574 OS_SETREGID_METHODDEF
13575 OS_SETGROUPS_METHODDEF
Antoine Pitroub7572f02009-12-02 20:46:48 +000013576#ifdef HAVE_INITGROUPS
Victor Stinner8c62be82010-05-06 00:08:46 +000013577 {"initgroups", posix_initgroups, METH_VARARGS, posix_initgroups__doc__},
Antoine Pitroub7572f02009-12-02 20:46:48 +000013578#endif /* HAVE_INITGROUPS */
Larry Hastings2f936352014-08-05 14:04:04 +100013579 OS_GETPGID_METHODDEF
13580 OS_SETPGRP_METHODDEF
13581 OS_WAIT_METHODDEF
13582 OS_WAIT3_METHODDEF
13583 OS_WAIT4_METHODDEF
13584 OS_WAITID_METHODDEF
13585 OS_WAITPID_METHODDEF
13586 OS_GETSID_METHODDEF
13587 OS_SETSID_METHODDEF
13588 OS_SETPGID_METHODDEF
13589 OS_TCGETPGRP_METHODDEF
13590 OS_TCSETPGRP_METHODDEF
13591 OS_OPEN_METHODDEF
13592 OS_CLOSE_METHODDEF
13593 OS_CLOSERANGE_METHODDEF
13594 OS_DEVICE_ENCODING_METHODDEF
13595 OS_DUP_METHODDEF
13596 OS_DUP2_METHODDEF
13597 OS_LOCKF_METHODDEF
13598 OS_LSEEK_METHODDEF
13599 OS_READ_METHODDEF
13600 OS_READV_METHODDEF
13601 OS_PREAD_METHODDEF
Pablo Galindo4defba32018-01-27 16:16:37 +000013602 OS_PREADV_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100013603 OS_WRITE_METHODDEF
13604 OS_WRITEV_METHODDEF
13605 OS_PWRITE_METHODDEF
Pablo Galindo4defba32018-01-27 16:16:37 +000013606 OS_PWRITEV_METHODDEF
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +000013607#ifdef HAVE_SENDFILE
Serhiy Storchaka62be7422018-11-27 13:27:31 +020013608 {"sendfile", (PyCFunction)(void(*)(void))posix_sendfile, METH_VARARGS | METH_KEYWORDS,
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +000013609 posix_sendfile__doc__},
13610#endif
Larry Hastings2f936352014-08-05 14:04:04 +100013611 OS_FSTAT_METHODDEF
13612 OS_ISATTY_METHODDEF
13613 OS_PIPE_METHODDEF
13614 OS_PIPE2_METHODDEF
13615 OS_MKFIFO_METHODDEF
13616 OS_MKNOD_METHODDEF
13617 OS_MAJOR_METHODDEF
13618 OS_MINOR_METHODDEF
13619 OS_MAKEDEV_METHODDEF
13620 OS_FTRUNCATE_METHODDEF
13621 OS_TRUNCATE_METHODDEF
13622 OS_POSIX_FALLOCATE_METHODDEF
13623 OS_POSIX_FADVISE_METHODDEF
13624 OS_PUTENV_METHODDEF
13625 OS_UNSETENV_METHODDEF
13626 OS_STRERROR_METHODDEF
13627 OS_FCHDIR_METHODDEF
13628 OS_FSYNC_METHODDEF
13629 OS_SYNC_METHODDEF
13630 OS_FDATASYNC_METHODDEF
13631 OS_WCOREDUMP_METHODDEF
13632 OS_WIFCONTINUED_METHODDEF
13633 OS_WIFSTOPPED_METHODDEF
13634 OS_WIFSIGNALED_METHODDEF
13635 OS_WIFEXITED_METHODDEF
13636 OS_WEXITSTATUS_METHODDEF
13637 OS_WTERMSIG_METHODDEF
13638 OS_WSTOPSIG_METHODDEF
13639 OS_FSTATVFS_METHODDEF
13640 OS_STATVFS_METHODDEF
13641 OS_CONFSTR_METHODDEF
13642 OS_SYSCONF_METHODDEF
13643 OS_FPATHCONF_METHODDEF
13644 OS_PATHCONF_METHODDEF
13645 OS_ABORT_METHODDEF
Serhiy Storchakaf0b50152015-05-13 00:52:39 +030013646 OS__GETFULLPATHNAME_METHODDEF
13647 OS__ISDIR_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100013648 OS__GETDISKUSAGE_METHODDEF
13649 OS__GETFINALPATHNAME_METHODDEF
13650 OS__GETVOLUMEPATHNAME_METHODDEF
13651 OS_GETLOADAVG_METHODDEF
13652 OS_URANDOM_METHODDEF
13653 OS_SETRESUID_METHODDEF
13654 OS_SETRESGID_METHODDEF
13655 OS_GETRESUID_METHODDEF
13656 OS_GETRESGID_METHODDEF
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000013657
Larry Hastings2f936352014-08-05 14:04:04 +100013658 OS_GETXATTR_METHODDEF
13659 OS_SETXATTR_METHODDEF
13660 OS_REMOVEXATTR_METHODDEF
13661 OS_LISTXATTR_METHODDEF
13662
Antoine Pitroubcf2b592012-02-08 23:28:36 +010013663#if defined(TERMSIZE_USE_CONIO) || defined(TERMSIZE_USE_IOCTL)
13664 {"get_terminal_size", get_terminal_size, METH_VARARGS, termsize__doc__},
13665#endif
Larry Hastings2f936352014-08-05 14:04:04 +100013666 OS_CPU_COUNT_METHODDEF
13667 OS_GET_INHERITABLE_METHODDEF
13668 OS_SET_INHERITABLE_METHODDEF
13669 OS_GET_HANDLE_INHERITABLE_METHODDEF
13670 OS_SET_HANDLE_INHERITABLE_METHODDEF
Victor Stinner1db9e7b2014-07-29 22:32:47 +020013671#ifndef MS_WINDOWS
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030013672 OS_GET_BLOCKING_METHODDEF
13673 OS_SET_BLOCKING_METHODDEF
Victor Stinner1db9e7b2014-07-29 22:32:47 +020013674#endif
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013675 OS_SCANDIR_METHODDEF
Ethan Furman410ef8e2016-06-04 12:06:26 -070013676 OS_FSPATH_METHODDEF
Victor Stinner9b1f4742016-09-06 16:18:52 -070013677 OS_GETRANDOM_METHODDEF
Zackery Spytz43fdbd22019-05-29 13:57:07 -060013678 OS_MEMFD_CREATE_METHODDEF
Steve Dower2438cdf2019-03-29 16:37:16 -070013679#ifdef MS_WINDOWS
13680 OS__ADD_DLL_DIRECTORY_METHODDEF
13681 OS__REMOVE_DLL_DIRECTORY_METHODDEF
13682#endif
Victor Stinner8c62be82010-05-06 00:08:46 +000013683 {NULL, NULL} /* Sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000013684};
13685
Barry Warsaw4a342091996-12-19 23:50:02 +000013686static int
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013687all_ins(PyObject *m)
Barry Warsaw4a342091996-12-19 23:50:02 +000013688{
Guido van Rossum94f6f721999-01-06 18:42:14 +000013689#ifdef F_OK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013690 if (PyModule_AddIntMacro(m, F_OK)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013691#endif
Guido van Rossum94f6f721999-01-06 18:42:14 +000013692#ifdef R_OK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013693 if (PyModule_AddIntMacro(m, R_OK)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013694#endif
Guido van Rossum94f6f721999-01-06 18:42:14 +000013695#ifdef W_OK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013696 if (PyModule_AddIntMacro(m, W_OK)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013697#endif
Guido van Rossum94f6f721999-01-06 18:42:14 +000013698#ifdef X_OK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013699 if (PyModule_AddIntMacro(m, X_OK)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013700#endif
Fred Drakec9680921999-12-13 16:37:25 +000013701#ifdef NGROUPS_MAX
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013702 if (PyModule_AddIntMacro(m, NGROUPS_MAX)) return -1;
Fred Drakec9680921999-12-13 16:37:25 +000013703#endif
Fred Drake5ab8eaf1999-12-09 21:13:07 +000013704#ifdef TMP_MAX
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013705 if (PyModule_AddIntMacro(m, TMP_MAX)) return -1;
Fred Drake5ab8eaf1999-12-09 21:13:07 +000013706#endif
Fred Drake106c1a02002-04-23 15:58:02 +000013707#ifdef WCONTINUED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013708 if (PyModule_AddIntMacro(m, WCONTINUED)) return -1;
Fred Drake106c1a02002-04-23 15:58:02 +000013709#endif
Barry Warsaw4a342091996-12-19 23:50:02 +000013710#ifdef WNOHANG
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013711 if (PyModule_AddIntMacro(m, WNOHANG)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013712#endif
Fred Drake106c1a02002-04-23 15:58:02 +000013713#ifdef WUNTRACED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013714 if (PyModule_AddIntMacro(m, WUNTRACED)) return -1;
Fred Drake106c1a02002-04-23 15:58:02 +000013715#endif
Barry Warsaw4a342091996-12-19 23:50:02 +000013716#ifdef O_RDONLY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013717 if (PyModule_AddIntMacro(m, O_RDONLY)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013718#endif
13719#ifdef O_WRONLY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013720 if (PyModule_AddIntMacro(m, O_WRONLY)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013721#endif
13722#ifdef O_RDWR
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013723 if (PyModule_AddIntMacro(m, O_RDWR)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013724#endif
13725#ifdef O_NDELAY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013726 if (PyModule_AddIntMacro(m, O_NDELAY)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013727#endif
13728#ifdef O_NONBLOCK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013729 if (PyModule_AddIntMacro(m, O_NONBLOCK)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013730#endif
13731#ifdef O_APPEND
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013732 if (PyModule_AddIntMacro(m, O_APPEND)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013733#endif
13734#ifdef O_DSYNC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013735 if (PyModule_AddIntMacro(m, O_DSYNC)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013736#endif
13737#ifdef O_RSYNC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013738 if (PyModule_AddIntMacro(m, O_RSYNC)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013739#endif
13740#ifdef O_SYNC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013741 if (PyModule_AddIntMacro(m, O_SYNC)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013742#endif
13743#ifdef O_NOCTTY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013744 if (PyModule_AddIntMacro(m, O_NOCTTY)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013745#endif
13746#ifdef O_CREAT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013747 if (PyModule_AddIntMacro(m, O_CREAT)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013748#endif
13749#ifdef O_EXCL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013750 if (PyModule_AddIntMacro(m, O_EXCL)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013751#endif
13752#ifdef O_TRUNC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013753 if (PyModule_AddIntMacro(m, O_TRUNC)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013754#endif
Guido van Rossum98d9d091997-08-08 21:48:51 +000013755#ifdef O_BINARY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013756 if (PyModule_AddIntMacro(m, O_BINARY)) return -1;
Guido van Rossum98d9d091997-08-08 21:48:51 +000013757#endif
13758#ifdef O_TEXT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013759 if (PyModule_AddIntMacro(m, O_TEXT)) return -1;
Guido van Rossum98d9d091997-08-08 21:48:51 +000013760#endif
Jesus Cea1d642d22012-04-24 20:59:17 +020013761#ifdef O_XATTR
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013762 if (PyModule_AddIntMacro(m, O_XATTR)) return -1;
Jesus Cea1d642d22012-04-24 20:59:17 +020013763#endif
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000013764#ifdef O_LARGEFILE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013765 if (PyModule_AddIntMacro(m, O_LARGEFILE)) return -1;
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000013766#endif
doko@ubuntu.comfcff4372016-06-13 16:33:04 +020013767#ifndef __GNU__
Skip Montanaro5ff14922005-05-16 02:42:22 +000013768#ifdef O_SHLOCK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013769 if (PyModule_AddIntMacro(m, O_SHLOCK)) return -1;
Skip Montanaro5ff14922005-05-16 02:42:22 +000013770#endif
13771#ifdef O_EXLOCK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013772 if (PyModule_AddIntMacro(m, O_EXLOCK)) return -1;
Skip Montanaro5ff14922005-05-16 02:42:22 +000013773#endif
doko@ubuntu.comfcff4372016-06-13 16:33:04 +020013774#endif
Jesus Ceacf381202012-04-24 20:44:40 +020013775#ifdef O_EXEC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013776 if (PyModule_AddIntMacro(m, O_EXEC)) return -1;
Jesus Ceacf381202012-04-24 20:44:40 +020013777#endif
13778#ifdef O_SEARCH
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013779 if (PyModule_AddIntMacro(m, O_SEARCH)) return -1;
Jesus Ceacf381202012-04-24 20:44:40 +020013780#endif
Benjamin Peterson3b965a22013-03-13 10:27:41 -050013781#ifdef O_PATH
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013782 if (PyModule_AddIntMacro(m, O_PATH)) return -1;
Benjamin Peterson3b965a22013-03-13 10:27:41 -050013783#endif
Jesus Ceacf381202012-04-24 20:44:40 +020013784#ifdef O_TTY_INIT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013785 if (PyModule_AddIntMacro(m, O_TTY_INIT)) return -1;
Jesus Ceacf381202012-04-24 20:44:40 +020013786#endif
Christian Heimes177b3f92013-08-16 14:35:09 +020013787#ifdef O_TMPFILE
13788 if (PyModule_AddIntMacro(m, O_TMPFILE)) return -1;
13789#endif
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +000013790#ifdef PRIO_PROCESS
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013791 if (PyModule_AddIntMacro(m, PRIO_PROCESS)) return -1;
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +000013792#endif
13793#ifdef PRIO_PGRP
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013794 if (PyModule_AddIntMacro(m, PRIO_PGRP)) return -1;
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +000013795#endif
13796#ifdef PRIO_USER
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013797 if (PyModule_AddIntMacro(m, PRIO_USER)) return -1;
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +000013798#endif
Charles-François Natali1e045b12011-05-22 20:42:32 +020013799#ifdef O_CLOEXEC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013800 if (PyModule_AddIntMacro(m, O_CLOEXEC)) return -1;
Charles-François Natali1e045b12011-05-22 20:42:32 +020013801#endif
Jesus Cea1d642d22012-04-24 20:59:17 +020013802#ifdef O_ACCMODE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013803 if (PyModule_AddIntMacro(m, O_ACCMODE)) return -1;
Jesus Cea1d642d22012-04-24 20:59:17 +020013804#endif
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +000013805
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000013806
Jesus Cea94363612012-06-22 18:32:07 +020013807#ifdef SEEK_HOLE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013808 if (PyModule_AddIntMacro(m, SEEK_HOLE)) return -1;
Jesus Cea94363612012-06-22 18:32:07 +020013809#endif
13810#ifdef SEEK_DATA
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013811 if (PyModule_AddIntMacro(m, SEEK_DATA)) return -1;
Jesus Cea94363612012-06-22 18:32:07 +020013812#endif
13813
Tim Peters5aa91602002-01-30 05:46:57 +000013814/* MS Windows */
13815#ifdef O_NOINHERIT
Victor Stinner8c62be82010-05-06 00:08:46 +000013816 /* Don't inherit in child processes. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013817 if (PyModule_AddIntMacro(m, O_NOINHERIT)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013818#endif
13819#ifdef _O_SHORT_LIVED
Victor Stinner8c62be82010-05-06 00:08:46 +000013820 /* Optimize for short life (keep in memory). */
13821 /* MS forgot to define this one with a non-underscore form too. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013822 if (PyModule_AddIntConstant(m, "O_SHORT_LIVED", _O_SHORT_LIVED)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013823#endif
13824#ifdef O_TEMPORARY
Victor Stinner8c62be82010-05-06 00:08:46 +000013825 /* Automatically delete when last handle is closed. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013826 if (PyModule_AddIntMacro(m, O_TEMPORARY)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013827#endif
13828#ifdef O_RANDOM
Victor Stinner8c62be82010-05-06 00:08:46 +000013829 /* Optimize for random access. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013830 if (PyModule_AddIntMacro(m, O_RANDOM)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013831#endif
13832#ifdef O_SEQUENTIAL
Victor Stinner8c62be82010-05-06 00:08:46 +000013833 /* Optimize for sequential access. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013834 if (PyModule_AddIntMacro(m, O_SEQUENTIAL)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013835#endif
13836
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000013837/* GNU extensions. */
Alexandre Vassalottibee32532008-05-16 18:15:12 +000013838#ifdef O_ASYNC
Victor Stinner8c62be82010-05-06 00:08:46 +000013839 /* Send a SIGIO signal whenever input or output
13840 becomes available on file descriptor */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013841 if (PyModule_AddIntMacro(m, O_ASYNC)) return -1;
Alexandre Vassalottibee32532008-05-16 18:15:12 +000013842#endif
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000013843#ifdef O_DIRECT
Victor Stinner8c62be82010-05-06 00:08:46 +000013844 /* Direct disk access. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013845 if (PyModule_AddIntMacro(m, O_DIRECT)) return -1;
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000013846#endif
13847#ifdef O_DIRECTORY
Victor Stinner8c62be82010-05-06 00:08:46 +000013848 /* Must be a directory. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013849 if (PyModule_AddIntMacro(m, O_DIRECTORY)) return -1;
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000013850#endif
13851#ifdef O_NOFOLLOW
Victor Stinner8c62be82010-05-06 00:08:46 +000013852 /* Do not follow links. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013853 if (PyModule_AddIntMacro(m, O_NOFOLLOW)) return -1;
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000013854#endif
Jesus Cea1d642d22012-04-24 20:59:17 +020013855#ifdef O_NOLINKS
13856 /* Fails if link count of the named file is greater than 1 */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013857 if (PyModule_AddIntMacro(m, O_NOLINKS)) return -1;
Jesus Cea1d642d22012-04-24 20:59:17 +020013858#endif
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +000013859#ifdef O_NOATIME
Victor Stinner8c62be82010-05-06 00:08:46 +000013860 /* Do not update the access time. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013861 if (PyModule_AddIntMacro(m, O_NOATIME)) return -1;
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +000013862#endif
Guido van Rossumd48f2521997-12-05 22:19:34 +000013863
Victor Stinner8c62be82010-05-06 00:08:46 +000013864 /* These come from sysexits.h */
Barry Warsaw5676bd12003-01-07 20:57:09 +000013865#ifdef EX_OK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013866 if (PyModule_AddIntMacro(m, EX_OK)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000013867#endif /* EX_OK */
Barry Warsaw5676bd12003-01-07 20:57:09 +000013868#ifdef EX_USAGE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013869 if (PyModule_AddIntMacro(m, EX_USAGE)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000013870#endif /* EX_USAGE */
Barry Warsaw5676bd12003-01-07 20:57:09 +000013871#ifdef EX_DATAERR
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013872 if (PyModule_AddIntMacro(m, EX_DATAERR)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000013873#endif /* EX_DATAERR */
Barry Warsaw5676bd12003-01-07 20:57:09 +000013874#ifdef EX_NOINPUT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013875 if (PyModule_AddIntMacro(m, EX_NOINPUT)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000013876#endif /* EX_NOINPUT */
Barry Warsaw5676bd12003-01-07 20:57:09 +000013877#ifdef EX_NOUSER
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013878 if (PyModule_AddIntMacro(m, EX_NOUSER)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000013879#endif /* EX_NOUSER */
Barry Warsaw5676bd12003-01-07 20:57:09 +000013880#ifdef EX_NOHOST
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013881 if (PyModule_AddIntMacro(m, EX_NOHOST)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000013882#endif /* EX_NOHOST */
Barry Warsaw5676bd12003-01-07 20:57:09 +000013883#ifdef EX_UNAVAILABLE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013884 if (PyModule_AddIntMacro(m, EX_UNAVAILABLE)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000013885#endif /* EX_UNAVAILABLE */
Barry Warsaw5676bd12003-01-07 20:57:09 +000013886#ifdef EX_SOFTWARE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013887 if (PyModule_AddIntMacro(m, EX_SOFTWARE)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000013888#endif /* EX_SOFTWARE */
Barry Warsaw5676bd12003-01-07 20:57:09 +000013889#ifdef EX_OSERR
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013890 if (PyModule_AddIntMacro(m, EX_OSERR)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000013891#endif /* EX_OSERR */
Barry Warsaw5676bd12003-01-07 20:57:09 +000013892#ifdef EX_OSFILE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013893 if (PyModule_AddIntMacro(m, EX_OSFILE)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000013894#endif /* EX_OSFILE */
Barry Warsaw5676bd12003-01-07 20:57:09 +000013895#ifdef EX_CANTCREAT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013896 if (PyModule_AddIntMacro(m, EX_CANTCREAT)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000013897#endif /* EX_CANTCREAT */
Barry Warsaw5676bd12003-01-07 20:57:09 +000013898#ifdef EX_IOERR
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013899 if (PyModule_AddIntMacro(m, EX_IOERR)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000013900#endif /* EX_IOERR */
Barry Warsaw5676bd12003-01-07 20:57:09 +000013901#ifdef EX_TEMPFAIL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013902 if (PyModule_AddIntMacro(m, EX_TEMPFAIL)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000013903#endif /* EX_TEMPFAIL */
Barry Warsaw5676bd12003-01-07 20:57:09 +000013904#ifdef EX_PROTOCOL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013905 if (PyModule_AddIntMacro(m, EX_PROTOCOL)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000013906#endif /* EX_PROTOCOL */
Barry Warsaw5676bd12003-01-07 20:57:09 +000013907#ifdef EX_NOPERM
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013908 if (PyModule_AddIntMacro(m, EX_NOPERM)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000013909#endif /* EX_NOPERM */
Barry Warsaw5676bd12003-01-07 20:57:09 +000013910#ifdef EX_CONFIG
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013911 if (PyModule_AddIntMacro(m, EX_CONFIG)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000013912#endif /* EX_CONFIG */
Barry Warsaw5676bd12003-01-07 20:57:09 +000013913#ifdef EX_NOTFOUND
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013914 if (PyModule_AddIntMacro(m, EX_NOTFOUND)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000013915#endif /* EX_NOTFOUND */
Barry Warsaw5676bd12003-01-07 20:57:09 +000013916
Amaury Forgeot d'Arc66d00ad2010-09-10 18:11:45 +000013917 /* statvfs */
Andrew M. Kuchling4ea04a32010-08-18 22:30:34 +000013918#ifdef ST_RDONLY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013919 if (PyModule_AddIntMacro(m, ST_RDONLY)) return -1;
Andrew M. Kuchling4ea04a32010-08-18 22:30:34 +000013920#endif /* ST_RDONLY */
13921#ifdef ST_NOSUID
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013922 if (PyModule_AddIntMacro(m, ST_NOSUID)) return -1;
Andrew M. Kuchling4ea04a32010-08-18 22:30:34 +000013923#endif /* ST_NOSUID */
13924
doko@ubuntu.comca616a22013-12-08 15:23:07 +010013925 /* GNU extensions */
13926#ifdef ST_NODEV
13927 if (PyModule_AddIntMacro(m, ST_NODEV)) return -1;
13928#endif /* ST_NODEV */
13929#ifdef ST_NOEXEC
13930 if (PyModule_AddIntMacro(m, ST_NOEXEC)) return -1;
13931#endif /* ST_NOEXEC */
13932#ifdef ST_SYNCHRONOUS
13933 if (PyModule_AddIntMacro(m, ST_SYNCHRONOUS)) return -1;
13934#endif /* ST_SYNCHRONOUS */
13935#ifdef ST_MANDLOCK
13936 if (PyModule_AddIntMacro(m, ST_MANDLOCK)) return -1;
13937#endif /* ST_MANDLOCK */
13938#ifdef ST_WRITE
13939 if (PyModule_AddIntMacro(m, ST_WRITE)) return -1;
13940#endif /* ST_WRITE */
13941#ifdef ST_APPEND
13942 if (PyModule_AddIntMacro(m, ST_APPEND)) return -1;
13943#endif /* ST_APPEND */
13944#ifdef ST_NOATIME
13945 if (PyModule_AddIntMacro(m, ST_NOATIME)) return -1;
13946#endif /* ST_NOATIME */
13947#ifdef ST_NODIRATIME
13948 if (PyModule_AddIntMacro(m, ST_NODIRATIME)) return -1;
13949#endif /* ST_NODIRATIME */
13950#ifdef ST_RELATIME
13951 if (PyModule_AddIntMacro(m, ST_RELATIME)) return -1;
13952#endif /* ST_RELATIME */
13953
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +000013954 /* FreeBSD sendfile() constants */
13955#ifdef SF_NODISKIO
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013956 if (PyModule_AddIntMacro(m, SF_NODISKIO)) return -1;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +000013957#endif
13958#ifdef SF_MNOWAIT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013959 if (PyModule_AddIntMacro(m, SF_MNOWAIT)) return -1;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +000013960#endif
13961#ifdef SF_SYNC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013962 if (PyModule_AddIntMacro(m, SF_SYNC)) return -1;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +000013963#endif
13964
Ross Lagerwall7807c352011-03-17 20:20:30 +020013965 /* constants for posix_fadvise */
13966#ifdef POSIX_FADV_NORMAL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013967 if (PyModule_AddIntMacro(m, POSIX_FADV_NORMAL)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020013968#endif
13969#ifdef POSIX_FADV_SEQUENTIAL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013970 if (PyModule_AddIntMacro(m, POSIX_FADV_SEQUENTIAL)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020013971#endif
13972#ifdef POSIX_FADV_RANDOM
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013973 if (PyModule_AddIntMacro(m, POSIX_FADV_RANDOM)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020013974#endif
13975#ifdef POSIX_FADV_NOREUSE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013976 if (PyModule_AddIntMacro(m, POSIX_FADV_NOREUSE)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020013977#endif
13978#ifdef POSIX_FADV_WILLNEED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013979 if (PyModule_AddIntMacro(m, POSIX_FADV_WILLNEED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020013980#endif
13981#ifdef POSIX_FADV_DONTNEED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013982 if (PyModule_AddIntMacro(m, POSIX_FADV_DONTNEED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020013983#endif
13984
13985 /* constants for waitid */
13986#if defined(HAVE_SYS_WAIT_H) && defined(HAVE_WAITID)
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013987 if (PyModule_AddIntMacro(m, P_PID)) return -1;
13988 if (PyModule_AddIntMacro(m, P_PGID)) return -1;
13989 if (PyModule_AddIntMacro(m, P_ALL)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020013990#endif
13991#ifdef WEXITED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013992 if (PyModule_AddIntMacro(m, WEXITED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020013993#endif
13994#ifdef WNOWAIT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013995 if (PyModule_AddIntMacro(m, WNOWAIT)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020013996#endif
13997#ifdef WSTOPPED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013998 if (PyModule_AddIntMacro(m, WSTOPPED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020013999#endif
14000#ifdef CLD_EXITED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014001 if (PyModule_AddIntMacro(m, CLD_EXITED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014002#endif
14003#ifdef CLD_DUMPED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014004 if (PyModule_AddIntMacro(m, CLD_DUMPED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014005#endif
14006#ifdef CLD_TRAPPED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014007 if (PyModule_AddIntMacro(m, CLD_TRAPPED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014008#endif
14009#ifdef CLD_CONTINUED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014010 if (PyModule_AddIntMacro(m, CLD_CONTINUED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014011#endif
14012
14013 /* constants for lockf */
14014#ifdef F_LOCK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014015 if (PyModule_AddIntMacro(m, F_LOCK)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014016#endif
14017#ifdef F_TLOCK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014018 if (PyModule_AddIntMacro(m, F_TLOCK)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014019#endif
14020#ifdef F_ULOCK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014021 if (PyModule_AddIntMacro(m, F_ULOCK)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014022#endif
14023#ifdef F_TEST
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014024 if (PyModule_AddIntMacro(m, F_TEST)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014025#endif
14026
Pablo Galindo4defba32018-01-27 16:16:37 +000014027#ifdef RWF_DSYNC
14028 if (PyModule_AddIntConstant(m, "RWF_DSYNC", RWF_DSYNC)) return -1;
14029#endif
14030#ifdef RWF_HIPRI
14031 if (PyModule_AddIntConstant(m, "RWF_HIPRI", RWF_HIPRI)) return -1;
14032#endif
14033#ifdef RWF_SYNC
14034 if (PyModule_AddIntConstant(m, "RWF_SYNC", RWF_SYNC)) return -1;
14035#endif
14036#ifdef RWF_NOWAIT
14037 if (PyModule_AddIntConstant(m, "RWF_NOWAIT", RWF_NOWAIT)) return -1;
14038#endif
14039
Pablo Galindo6c6ddf92018-01-29 01:56:10 +000014040/* constants for posix_spawn */
14041#ifdef HAVE_POSIX_SPAWN
14042 if (PyModule_AddIntConstant(m, "POSIX_SPAWN_OPEN", POSIX_SPAWN_OPEN)) return -1;
14043 if (PyModule_AddIntConstant(m, "POSIX_SPAWN_CLOSE", POSIX_SPAWN_CLOSE)) return -1;
14044 if (PyModule_AddIntConstant(m, "POSIX_SPAWN_DUP2", POSIX_SPAWN_DUP2)) return -1;
14045#endif
14046
pxinwrf2d7ac72019-05-21 18:46:37 +080014047#if defined(HAVE_SPAWNV) || defined (HAVE_RTPSPAWN)
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014048 if (PyModule_AddIntConstant(m, "P_WAIT", _P_WAIT)) return -1;
14049 if (PyModule_AddIntConstant(m, "P_NOWAIT", _P_NOWAIT)) return -1;
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014050 if (PyModule_AddIntConstant(m, "P_NOWAITO", _P_NOWAITO)) return -1;
pxinwrf2d7ac72019-05-21 18:46:37 +080014051#endif
14052#ifdef HAVE_SPAWNV
14053 if (PyModule_AddIntConstant(m, "P_OVERLAY", _OLD_P_OVERLAY)) return -1;
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014054 if (PyModule_AddIntConstant(m, "P_DETACH", _P_DETACH)) return -1;
Guido van Rossum246bc171999-02-01 23:54:31 +000014055#endif
14056
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014057#ifdef HAVE_SCHED_H
Benjamin Petersondbaa5592016-07-30 23:21:50 -070014058#ifdef SCHED_OTHER
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014059 if (PyModule_AddIntMacro(m, SCHED_OTHER)) return -1;
Benjamin Petersondbaa5592016-07-30 23:21:50 -070014060#endif
14061#ifdef SCHED_FIFO
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014062 if (PyModule_AddIntMacro(m, SCHED_FIFO)) return -1;
Benjamin Petersondbaa5592016-07-30 23:21:50 -070014063#endif
14064#ifdef SCHED_RR
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014065 if (PyModule_AddIntMacro(m, SCHED_RR)) return -1;
Benjamin Petersondbaa5592016-07-30 23:21:50 -070014066#endif
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014067#ifdef SCHED_SPORADIC
messi Liao0d322182017-06-13 22:30:43 +080014068 if (PyModule_AddIntMacro(m, SCHED_SPORADIC)) return -1;
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014069#endif
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014070#ifdef SCHED_BATCH
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014071 if (PyModule_AddIntMacro(m, SCHED_BATCH)) return -1;
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014072#endif
14073#ifdef SCHED_IDLE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014074 if (PyModule_AddIntMacro(m, SCHED_IDLE)) return -1;
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014075#endif
14076#ifdef SCHED_RESET_ON_FORK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014077 if (PyModule_AddIntMacro(m, SCHED_RESET_ON_FORK)) return -1;
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014078#endif
Jesus Ceaf2cb4e82011-09-09 23:55:42 +020014079#ifdef SCHED_SYS
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014080 if (PyModule_AddIntMacro(m, SCHED_SYS)) return -1;
Jesus Ceaf2cb4e82011-09-09 23:55:42 +020014081#endif
14082#ifdef SCHED_IA
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014083 if (PyModule_AddIntMacro(m, SCHED_IA)) return -1;
Jesus Ceaf2cb4e82011-09-09 23:55:42 +020014084#endif
14085#ifdef SCHED_FSS
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014086 if (PyModule_AddIntMacro(m, SCHED_FSS)) return -1;
Jesus Ceaf2cb4e82011-09-09 23:55:42 +020014087#endif
14088#ifdef SCHED_FX
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014089 if (PyModule_AddIntConstant(m, "SCHED_FX", SCHED_FSS)) return -1;
Jesus Ceaf2cb4e82011-09-09 23:55:42 +020014090#endif
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014091#endif
14092
Benjamin Peterson9428d532011-09-14 11:45:52 -040014093#ifdef USE_XATTRS
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014094 if (PyModule_AddIntMacro(m, XATTR_CREATE)) return -1;
14095 if (PyModule_AddIntMacro(m, XATTR_REPLACE)) return -1;
14096 if (PyModule_AddIntMacro(m, XATTR_SIZE_MAX)) return -1;
Benjamin Peterson799bd802011-08-31 22:15:17 -040014097#endif
14098
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030014099#if HAVE_DECL_RTLD_LAZY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014100 if (PyModule_AddIntMacro(m, RTLD_LAZY)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020014101#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030014102#if HAVE_DECL_RTLD_NOW
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014103 if (PyModule_AddIntMacro(m, RTLD_NOW)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020014104#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030014105#if HAVE_DECL_RTLD_GLOBAL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014106 if (PyModule_AddIntMacro(m, RTLD_GLOBAL)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020014107#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030014108#if HAVE_DECL_RTLD_LOCAL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014109 if (PyModule_AddIntMacro(m, RTLD_LOCAL)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020014110#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030014111#if HAVE_DECL_RTLD_NODELETE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014112 if (PyModule_AddIntMacro(m, RTLD_NODELETE)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020014113#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030014114#if HAVE_DECL_RTLD_NOLOAD
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014115 if (PyModule_AddIntMacro(m, RTLD_NOLOAD)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020014116#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030014117#if HAVE_DECL_RTLD_DEEPBIND
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014118 if (PyModule_AddIntMacro(m, RTLD_DEEPBIND)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020014119#endif
Michael Feltc5ae1692017-12-19 13:58:49 +010014120#if HAVE_DECL_RTLD_MEMBER
14121 if (PyModule_AddIntMacro(m, RTLD_MEMBER)) return -1;
14122#endif
Victor Stinner8b905bd2011-10-25 13:34:04 +020014123
Victor Stinner9b1f4742016-09-06 16:18:52 -070014124#ifdef HAVE_GETRANDOM_SYSCALL
14125 if (PyModule_AddIntMacro(m, GRND_RANDOM)) return -1;
14126 if (PyModule_AddIntMacro(m, GRND_NONBLOCK)) return -1;
14127#endif
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014128#ifdef HAVE_MEMFD_CREATE
14129 if (PyModule_AddIntMacro(m, MFD_CLOEXEC)) return -1;
14130 if (PyModule_AddIntMacro(m, MFD_ALLOW_SEALING)) return -1;
14131#ifdef MFD_HUGETLB
14132 if (PyModule_AddIntMacro(m, MFD_HUGETLB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014133#endif
14134#ifdef MFD_HUGE_SHIFT
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014135 if (PyModule_AddIntMacro(m, MFD_HUGE_SHIFT)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014136#endif
14137#ifdef MFD_HUGE_MASK
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014138 if (PyModule_AddIntMacro(m, MFD_HUGE_MASK)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014139#endif
14140#ifdef MFD_HUGE_64KB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014141 if (PyModule_AddIntMacro(m, MFD_HUGE_64KB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014142#endif
14143#ifdef MFD_HUGE_512KB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014144 if (PyModule_AddIntMacro(m, MFD_HUGE_512KB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014145#endif
14146#ifdef MFD_HUGE_1MB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014147 if (PyModule_AddIntMacro(m, MFD_HUGE_1MB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014148#endif
14149#ifdef MFD_HUGE_2MB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014150 if (PyModule_AddIntMacro(m, MFD_HUGE_2MB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014151#endif
14152#ifdef MFD_HUGE_8MB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014153 if (PyModule_AddIntMacro(m, MFD_HUGE_8MB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014154#endif
14155#ifdef MFD_HUGE_16MB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014156 if (PyModule_AddIntMacro(m, MFD_HUGE_16MB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014157#endif
14158#ifdef MFD_HUGE_32MB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014159 if (PyModule_AddIntMacro(m, MFD_HUGE_32MB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014160#endif
14161#ifdef MFD_HUGE_256MB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014162 if (PyModule_AddIntMacro(m, MFD_HUGE_256MB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014163#endif
14164#ifdef MFD_HUGE_512MB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014165 if (PyModule_AddIntMacro(m, MFD_HUGE_512MB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014166#endif
14167#ifdef MFD_HUGE_1GB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014168 if (PyModule_AddIntMacro(m, MFD_HUGE_1GB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014169#endif
14170#ifdef MFD_HUGE_2GB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014171 if (PyModule_AddIntMacro(m, MFD_HUGE_2GB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014172#endif
14173#ifdef MFD_HUGE_16GB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014174 if (PyModule_AddIntMacro(m, MFD_HUGE_16GB)) return -1;
14175#endif
14176#endif
Victor Stinner9b1f4742016-09-06 16:18:52 -070014177
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +020014178#if defined(__APPLE__)
14179 if (PyModule_AddIntConstant(m, "_COPYFILE_DATA", COPYFILE_DATA)) return -1;
14180#endif
14181
Steve Dower2438cdf2019-03-29 16:37:16 -070014182#ifdef MS_WINDOWS
14183 if (PyModule_AddIntConstant(m, "_LOAD_LIBRARY_SEARCH_DEFAULT_DIRS", LOAD_LIBRARY_SEARCH_DEFAULT_DIRS)) return -1;
14184 if (PyModule_AddIntConstant(m, "_LOAD_LIBRARY_SEARCH_APPLICATION_DIR", LOAD_LIBRARY_SEARCH_APPLICATION_DIR)) return -1;
14185 if (PyModule_AddIntConstant(m, "_LOAD_LIBRARY_SEARCH_SYSTEM32", LOAD_LIBRARY_SEARCH_SYSTEM32)) return -1;
14186 if (PyModule_AddIntConstant(m, "_LOAD_LIBRARY_SEARCH_USER_DIRS", LOAD_LIBRARY_SEARCH_USER_DIRS)) return -1;
14187 if (PyModule_AddIntConstant(m, "_LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR", LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR)) return -1;
14188#endif
14189
Victor Stinner8c62be82010-05-06 00:08:46 +000014190 return 0;
Barry Warsaw4a342091996-12-19 23:50:02 +000014191}
14192
14193
Martin v. Löwis1a214512008-06-11 05:26:20 +000014194static struct PyModuleDef posixmodule = {
Victor Stinner8c62be82010-05-06 00:08:46 +000014195 PyModuleDef_HEAD_INIT,
14196 MODNAME,
14197 posix__doc__,
14198 -1,
14199 posix_methods,
14200 NULL,
14201 NULL,
14202 NULL,
14203 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +000014204};
14205
14206
Serhiy Storchaka2d06e842015-12-25 19:53:18 +020014207static const char * const have_functions[] = {
Larry Hastings9cf065c2012-06-22 16:30:09 -070014208
14209#ifdef HAVE_FACCESSAT
14210 "HAVE_FACCESSAT",
14211#endif
14212
14213#ifdef HAVE_FCHDIR
14214 "HAVE_FCHDIR",
14215#endif
14216
14217#ifdef HAVE_FCHMOD
14218 "HAVE_FCHMOD",
14219#endif
14220
14221#ifdef HAVE_FCHMODAT
14222 "HAVE_FCHMODAT",
14223#endif
14224
14225#ifdef HAVE_FCHOWN
14226 "HAVE_FCHOWN",
14227#endif
14228
Larry Hastings00964ed2013-08-12 13:49:30 -040014229#ifdef HAVE_FCHOWNAT
14230 "HAVE_FCHOWNAT",
14231#endif
14232
Larry Hastings9cf065c2012-06-22 16:30:09 -070014233#ifdef HAVE_FEXECVE
14234 "HAVE_FEXECVE",
14235#endif
14236
14237#ifdef HAVE_FDOPENDIR
14238 "HAVE_FDOPENDIR",
14239#endif
14240
Georg Brandl306336b2012-06-24 12:55:33 +020014241#ifdef HAVE_FPATHCONF
14242 "HAVE_FPATHCONF",
14243#endif
14244
Larry Hastings9cf065c2012-06-22 16:30:09 -070014245#ifdef HAVE_FSTATAT
14246 "HAVE_FSTATAT",
14247#endif
14248
14249#ifdef HAVE_FSTATVFS
14250 "HAVE_FSTATVFS",
14251#endif
14252
Steve Dowerfe0a41a2015-03-20 19:50:46 -070014253#if defined HAVE_FTRUNCATE || defined MS_WINDOWS
Georg Brandl306336b2012-06-24 12:55:33 +020014254 "HAVE_FTRUNCATE",
14255#endif
14256
Larry Hastings9cf065c2012-06-22 16:30:09 -070014257#ifdef HAVE_FUTIMENS
14258 "HAVE_FUTIMENS",
14259#endif
14260
14261#ifdef HAVE_FUTIMES
14262 "HAVE_FUTIMES",
14263#endif
14264
14265#ifdef HAVE_FUTIMESAT
14266 "HAVE_FUTIMESAT",
14267#endif
14268
14269#ifdef HAVE_LINKAT
14270 "HAVE_LINKAT",
14271#endif
14272
14273#ifdef HAVE_LCHFLAGS
14274 "HAVE_LCHFLAGS",
14275#endif
14276
14277#ifdef HAVE_LCHMOD
14278 "HAVE_LCHMOD",
14279#endif
14280
14281#ifdef HAVE_LCHOWN
14282 "HAVE_LCHOWN",
14283#endif
14284
14285#ifdef HAVE_LSTAT
14286 "HAVE_LSTAT",
14287#endif
14288
14289#ifdef HAVE_LUTIMES
14290 "HAVE_LUTIMES",
14291#endif
14292
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014293#ifdef HAVE_MEMFD_CREATE
14294 "HAVE_MEMFD_CREATE",
14295#endif
14296
Larry Hastings9cf065c2012-06-22 16:30:09 -070014297#ifdef HAVE_MKDIRAT
14298 "HAVE_MKDIRAT",
14299#endif
14300
14301#ifdef HAVE_MKFIFOAT
14302 "HAVE_MKFIFOAT",
14303#endif
14304
14305#ifdef HAVE_MKNODAT
14306 "HAVE_MKNODAT",
14307#endif
14308
14309#ifdef HAVE_OPENAT
14310 "HAVE_OPENAT",
14311#endif
14312
14313#ifdef HAVE_READLINKAT
14314 "HAVE_READLINKAT",
14315#endif
14316
14317#ifdef HAVE_RENAMEAT
14318 "HAVE_RENAMEAT",
14319#endif
14320
14321#ifdef HAVE_SYMLINKAT
14322 "HAVE_SYMLINKAT",
14323#endif
14324
14325#ifdef HAVE_UNLINKAT
14326 "HAVE_UNLINKAT",
14327#endif
14328
14329#ifdef HAVE_UTIMENSAT
14330 "HAVE_UTIMENSAT",
14331#endif
14332
14333#ifdef MS_WINDOWS
14334 "MS_WINDOWS",
14335#endif
14336
14337 NULL
14338};
14339
14340
Mark Hammondfe51c6d2002-08-02 02:27:13 +000014341PyMODINIT_FUNC
Thomas Woutersf3f33dc2000-07-21 06:00:07 +000014342INITFUNC(void)
Guido van Rossumb6775db1994-08-01 11:34:53 +000014343{
Victor Stinner8c62be82010-05-06 00:08:46 +000014344 PyObject *m, *v;
Larry Hastings9cf065c2012-06-22 16:30:09 -070014345 PyObject *list;
Serhiy Storchaka2d06e842015-12-25 19:53:18 +020014346 const char * const *trace;
Tim Peters5aa91602002-01-30 05:46:57 +000014347
Victor Stinner8c62be82010-05-06 00:08:46 +000014348 m = PyModule_Create(&posixmodule);
14349 if (m == NULL)
14350 return NULL;
Tim Peters5aa91602002-01-30 05:46:57 +000014351
Victor Stinner8c62be82010-05-06 00:08:46 +000014352 /* Initialize environ dictionary */
14353 v = convertenviron();
14354 Py_XINCREF(v);
14355 if (v == NULL || PyModule_AddObject(m, "environ", v) != 0)
14356 return NULL;
14357 Py_DECREF(v);
Fred Drakec9680921999-12-13 16:37:25 +000014358
Victor Stinner8c62be82010-05-06 00:08:46 +000014359 if (all_ins(m))
14360 return NULL;
Barry Warsaw4a342091996-12-19 23:50:02 +000014361
Victor Stinner8c62be82010-05-06 00:08:46 +000014362 if (setup_confname_tables(m))
14363 return NULL;
Fred Drakebec628d1999-12-15 18:31:10 +000014364
Victor Stinner8c62be82010-05-06 00:08:46 +000014365 Py_INCREF(PyExc_OSError);
14366 PyModule_AddObject(m, "error", PyExc_OSError);
Fred Drake762e2061999-08-26 17:23:54 +000014367
Guido van Rossumb3d39562000-01-31 18:41:26 +000014368#ifdef HAVE_PUTENV
Victor Stinner8c62be82010-05-06 00:08:46 +000014369 if (posix_putenv_garbage == NULL)
14370 posix_putenv_garbage = PyDict_New();
Guido van Rossumb3d39562000-01-31 18:41:26 +000014371#endif
Guido van Rossum98bf58f2001-10-18 20:34:25 +000014372
Victor Stinner8c62be82010-05-06 00:08:46 +000014373 if (!initialized) {
Ross Lagerwall7807c352011-03-17 20:20:30 +020014374#if defined(HAVE_WAITID) && !defined(__APPLE__)
14375 waitid_result_desc.name = MODNAME ".waitid_result";
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014376 WaitidResultType = PyStructSequence_NewType(&waitid_result_desc);
14377 if (WaitidResultType == NULL) {
Victor Stinner1c8f0592013-07-22 22:24:54 +020014378 return NULL;
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014379 }
Ross Lagerwall7807c352011-03-17 20:20:30 +020014380#endif
14381
Christian Heimes25827622013-10-12 01:27:08 +020014382 stat_result_desc.name = "os.stat_result"; /* see issue #19209 */
Victor Stinner8c62be82010-05-06 00:08:46 +000014383 stat_result_desc.fields[7].name = PyStructSequence_UnnamedField;
14384 stat_result_desc.fields[8].name = PyStructSequence_UnnamedField;
14385 stat_result_desc.fields[9].name = PyStructSequence_UnnamedField;
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014386 StatResultType = PyStructSequence_NewType(&stat_result_desc);
14387 if (StatResultType == NULL) {
Victor Stinner1c8f0592013-07-22 22:24:54 +020014388 return NULL;
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014389 }
14390 structseq_new = StatResultType->tp_new;
14391 StatResultType->tp_new = statresult_new;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000014392
Christian Heimes25827622013-10-12 01:27:08 +020014393 statvfs_result_desc.name = "os.statvfs_result"; /* see issue #19209 */
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014394 StatVFSResultType = PyStructSequence_NewType(&statvfs_result_desc);
14395 if (StatVFSResultType == NULL) {
Victor Stinner1c8f0592013-07-22 22:24:54 +020014396 return NULL;
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014397 }
Martin v. Löwis05bfe1f2008-12-29 18:21:47 +000014398#ifdef NEED_TICKS_PER_SECOND
14399# if defined(HAVE_SYSCONF) && defined(_SC_CLK_TCK)
Victor Stinner8c62be82010-05-06 00:08:46 +000014400 ticks_per_second = sysconf(_SC_CLK_TCK);
Martin v. Löwis05bfe1f2008-12-29 18:21:47 +000014401# elif defined(HZ)
Victor Stinner8c62be82010-05-06 00:08:46 +000014402 ticks_per_second = HZ;
Martin v. Löwis05bfe1f2008-12-29 18:21:47 +000014403# else
Victor Stinner8c62be82010-05-06 00:08:46 +000014404 ticks_per_second = 60; /* magic fallback value; may be bogus */
Martin v. Löwis05bfe1f2008-12-29 18:21:47 +000014405# endif
14406#endif
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014407
William Orr81574b82018-10-01 22:19:56 -070014408#if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014409 sched_param_desc.name = MODNAME ".sched_param";
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014410 SchedParamType = PyStructSequence_NewType(&sched_param_desc);
14411 if (SchedParamType == NULL) {
Victor Stinner1c8f0592013-07-22 22:24:54 +020014412 return NULL;
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014413 }
14414 SchedParamType->tp_new = os_sched_param;
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014415#endif
Antoine Pitroubcf2b592012-02-08 23:28:36 +010014416
14417 /* initialize TerminalSize_info */
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014418 TerminalSizeType = PyStructSequence_NewType(&TerminalSize_desc);
14419 if (TerminalSizeType == NULL) {
Victor Stinner1c8f0592013-07-22 22:24:54 +020014420 return NULL;
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014421 }
Victor Stinner6036e442015-03-08 01:58:04 +010014422
14423 /* initialize scandir types */
14424 if (PyType_Ready(&ScandirIteratorType) < 0)
14425 return NULL;
14426 if (PyType_Ready(&DirEntryType) < 0)
14427 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +000014428 }
Ross Lagerwall7807c352011-03-17 20:20:30 +020014429#if defined(HAVE_WAITID) && !defined(__APPLE__)
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014430 Py_INCREF((PyObject*) WaitidResultType);
14431 PyModule_AddObject(m, "waitid_result", (PyObject*) WaitidResultType);
Ross Lagerwall7807c352011-03-17 20:20:30 +020014432#endif
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014433 Py_INCREF((PyObject*) StatResultType);
14434 PyModule_AddObject(m, "stat_result", (PyObject*) StatResultType);
14435 Py_INCREF((PyObject*) StatVFSResultType);
Victor Stinner8c62be82010-05-06 00:08:46 +000014436 PyModule_AddObject(m, "statvfs_result",
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014437 (PyObject*) StatVFSResultType);
Benjamin Petersone3298dd2011-08-02 18:40:46 -050014438
14439#if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER)
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014440 Py_INCREF(SchedParamType);
14441 PyModule_AddObject(m, "sched_param", (PyObject *)SchedParamType);
Benjamin Petersone3298dd2011-08-02 18:40:46 -050014442#endif
Thomas Wouters477c8d52006-05-27 19:21:47 +000014443
Larry Hastings605a62d2012-06-24 04:33:36 -070014444 times_result_desc.name = MODNAME ".times_result";
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014445 TimesResultType = PyStructSequence_NewType(&times_result_desc);
14446 if (TimesResultType == NULL) {
Victor Stinner1c8f0592013-07-22 22:24:54 +020014447 return NULL;
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014448 }
14449 PyModule_AddObject(m, "times_result", (PyObject *)TimesResultType);
Larry Hastings605a62d2012-06-24 04:33:36 -070014450
14451 uname_result_desc.name = MODNAME ".uname_result";
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014452 UnameResultType = PyStructSequence_NewType(&uname_result_desc);
14453 if (UnameResultType == NULL) {
Victor Stinner1c8f0592013-07-22 22:24:54 +020014454 return NULL;
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014455 }
14456 PyModule_AddObject(m, "uname_result", (PyObject *)UnameResultType);
Larry Hastings605a62d2012-06-24 04:33:36 -070014457
Thomas Wouters477c8d52006-05-27 19:21:47 +000014458#ifdef __APPLE__
Victor Stinner8c62be82010-05-06 00:08:46 +000014459 /*
14460 * Step 2 of weak-linking support on Mac OS X.
14461 *
14462 * The code below removes functions that are not available on the
14463 * currently active platform.
14464 *
14465 * This block allow one to use a python binary that was build on
Larry Hastings9cf065c2012-06-22 16:30:09 -070014466 * OSX 10.4 on OSX 10.3, without losing access to new APIs on
Victor Stinner8c62be82010-05-06 00:08:46 +000014467 * OSX 10.4.
14468 */
Thomas Wouters477c8d52006-05-27 19:21:47 +000014469#ifdef HAVE_FSTATVFS
Victor Stinner8c62be82010-05-06 00:08:46 +000014470 if (fstatvfs == NULL) {
14471 if (PyObject_DelAttrString(m, "fstatvfs") == -1) {
14472 return NULL;
14473 }
14474 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000014475#endif /* HAVE_FSTATVFS */
14476
14477#ifdef HAVE_STATVFS
Victor Stinner8c62be82010-05-06 00:08:46 +000014478 if (statvfs == NULL) {
14479 if (PyObject_DelAttrString(m, "statvfs") == -1) {
14480 return NULL;
14481 }
14482 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000014483#endif /* HAVE_STATVFS */
14484
14485# ifdef HAVE_LCHOWN
Victor Stinner8c62be82010-05-06 00:08:46 +000014486 if (lchown == NULL) {
14487 if (PyObject_DelAttrString(m, "lchown") == -1) {
14488 return NULL;
14489 }
14490 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000014491#endif /* HAVE_LCHOWN */
14492
14493
14494#endif /* __APPLE__ */
Antoine Pitroubcf2b592012-02-08 23:28:36 +010014495
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014496 Py_INCREF(TerminalSizeType);
14497 PyModule_AddObject(m, "terminal_size", (PyObject*)TerminalSizeType);
Antoine Pitroubcf2b592012-02-08 23:28:36 +010014498
Larry Hastings6fe20b32012-04-19 15:07:49 -070014499 billion = PyLong_FromLong(1000000000);
14500 if (!billion)
14501 return NULL;
14502
Larry Hastings9cf065c2012-06-22 16:30:09 -070014503 /* suppress "function not used" warnings */
14504 {
14505 int ignored;
14506 fd_specified("", -1);
14507 follow_symlinks_specified("", 1);
14508 dir_fd_and_follow_symlinks_invalid("chmod", DEFAULT_DIR_FD, 1);
14509 dir_fd_converter(Py_None, &ignored);
14510 dir_fd_unavailable(Py_None, &ignored);
14511 }
14512
14513 /*
14514 * provide list of locally available functions
14515 * so os.py can populate support_* lists
14516 */
14517 list = PyList_New(0);
14518 if (!list)
14519 return NULL;
14520 for (trace = have_functions; *trace; trace++) {
14521 PyObject *unicode = PyUnicode_DecodeASCII(*trace, strlen(*trace), NULL);
14522 if (!unicode)
14523 return NULL;
14524 if (PyList_Append(list, unicode))
14525 return NULL;
14526 Py_DECREF(unicode);
14527 }
14528 PyModule_AddObject(m, "_have_functions", list);
Ned Deilyeb3be662016-08-15 14:40:38 -040014529
14530 Py_INCREF((PyObject *) &DirEntryType);
Brett Cannona32c4d02016-06-24 14:14:44 -070014531 PyModule_AddObject(m, "DirEntry", (PyObject *)&DirEntryType);
Larry Hastings9cf065c2012-06-22 16:30:09 -070014532
14533 initialized = 1;
14534
Victor Stinner8c62be82010-05-06 00:08:46 +000014535 return m;
Guido van Rossumb6775db1994-08-01 11:34:53 +000014536}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000014537
14538#ifdef __cplusplus
14539}
14540#endif