blob: b9e8c0d94c20e1fcf44c9b6f2067dba6bf01f52e [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() */
39#include "pycore_pystate.h" /* _PyRuntime */
Antoine Pitrou346cbd32017-05-27 17:50:54 +020040#include "pythread.h"
Victor Stinner6036e442015-03-08 01:58:04 +010041#include "structmember.h"
Serhiy Storchaka7cf55992013-02-10 21:56:49 +020042#ifndef MS_WINDOWS
Victor Stinnerd5d9e812019-05-13 12:35:37 +020043# include "posixmodule.h"
Tim Golden0321cf22014-05-05 19:46:17 +010044#else
Victor Stinnerd5d9e812019-05-13 12:35:37 +020045# include "winreparse.h"
Serhiy Storchaka7cf55992013-02-10 21:56:49 +020046#endif
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000047
Stefan Krahfb7c8ae2016-04-26 17:04:18 +020048/* On android API level 21, 'AT_EACCESS' is not declared although
49 * HAVE_FACCESSAT is defined. */
50#ifdef __ANDROID__
51#undef HAVE_FACCESSAT
52#endif
53
Gregory P. Smith ext:(%20%5BGoogle%20Inc.%5D)fa76eee2016-05-28 21:03:48 +000054#include <stdio.h> /* needed for ctermid() */
55
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000056#ifdef __cplusplus
57extern "C" {
58#endif
59
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000060PyDoc_STRVAR(posix__doc__,
Guido van Rossumec4f4ac1997-06-02 22:20:51 +000061"This module provides access to operating system functionality that is\n\
62standardized by the C Standard and the POSIX standard (a thinly\n\
63disguised Unix interface). Refer to the library manual and\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +000064corresponding Unix manual entries for more information on calls.");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000065
Martin v. Löwis0073f2e2002-11-21 23:52:35 +000066
Ross Lagerwall4d076da2011-03-18 06:56:53 +020067#ifdef HAVE_SYS_UIO_H
68#include <sys/uio.h>
69#endif
70
Christian Heimes75b96182017-09-05 15:53:09 +020071#ifdef HAVE_SYS_SYSMACROS_H
72/* GNU C Library: major(), minor(), makedev() */
73#include <sys/sysmacros.h>
74#endif
75
Thomas Wouters0e3f5912006-08-11 14:57:12 +000076#ifdef HAVE_SYS_TYPES_H
Guido van Rossumb6775db1994-08-01 11:34:53 +000077#include <sys/types.h>
Thomas Wouters0e3f5912006-08-11 14:57:12 +000078#endif /* HAVE_SYS_TYPES_H */
79
80#ifdef HAVE_SYS_STAT_H
Guido van Rossumb6775db1994-08-01 11:34:53 +000081#include <sys/stat.h>
Thomas Wouters0e3f5912006-08-11 14:57:12 +000082#endif /* HAVE_SYS_STAT_H */
Guido van Rossuma6535fd2001-10-18 19:44:10 +000083
Guido van Rossum36bc6801995-06-14 22:54:23 +000084#ifdef HAVE_SYS_WAIT_H
Victor Stinner8c62be82010-05-06 00:08:46 +000085#include <sys/wait.h> /* For WNOHANG */
Guido van Rossum36bc6801995-06-14 22:54:23 +000086#endif
Guido van Rossumb6775db1994-08-01 11:34:53 +000087
Thomas Wouters0e3f5912006-08-11 14:57:12 +000088#ifdef HAVE_SIGNAL_H
Guido van Rossuma376cc51996-12-05 23:43:35 +000089#include <signal.h>
Thomas Wouters0e3f5912006-08-11 14:57:12 +000090#endif
Guido van Rossuma376cc51996-12-05 23:43:35 +000091
Guido van Rossumb6775db1994-08-01 11:34:53 +000092#ifdef HAVE_FCNTL_H
93#include <fcntl.h>
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +000094#endif /* HAVE_FCNTL_H */
Guido van Rossumb6775db1994-08-01 11:34:53 +000095
Guido van Rossuma6535fd2001-10-18 19:44:10 +000096#ifdef HAVE_GRP_H
97#include <grp.h>
98#endif
99
Barry Warsaw5676bd12003-01-07 20:57:09 +0000100#ifdef HAVE_SYSEXITS_H
101#include <sysexits.h>
102#endif /* HAVE_SYSEXITS_H */
103
Anthony Baxter8a560de2004-10-13 15:30:56 +0000104#ifdef HAVE_SYS_LOADAVG_H
105#include <sys/loadavg.h>
106#endif
107
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +0000108#ifdef HAVE_SYS_SENDFILE_H
109#include <sys/sendfile.h>
110#endif
111
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +0200112#if defined(__APPLE__)
113#include <copyfile.h>
114#endif
115
Benjamin Peterson94b580d2011-08-02 17:30:04 -0500116#ifdef HAVE_SCHED_H
117#include <sched.h>
118#endif
119
Pablo Galindoaac4d032019-05-31 19:39:47 +0100120#ifdef HAVE_COPY_FILE_RANGE
121#include <unistd.h>
122#endif
123
Benjamin Peterson2dbda072012-03-16 10:12:55 -0500124#if !defined(CPU_ALLOC) && defined(HAVE_SCHED_SETAFFINITY)
Benjamin Peterson7b51b8d2012-03-14 22:28:25 -0500125#undef HAVE_SCHED_SETAFFINITY
126#endif
127
doko@ubuntu.com4a173bc2014-04-17 19:47:16 +0200128#if defined(HAVE_SYS_XATTR_H) && defined(__GLIBC__) && !defined(__FreeBSD_kernel__) && !defined(__GNU__)
Benjamin Peterson9428d532011-09-14 11:45:52 -0400129#define USE_XATTRS
130#endif
131
132#ifdef USE_XATTRS
Benjamin Petersonb77fe172011-09-13 17:20:47 -0400133#include <sys/xattr.h>
Benjamin Peterson799bd802011-08-31 22:15:17 -0400134#endif
135
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +0000136#if defined(__FreeBSD__) || defined(__DragonFly__) || defined(__APPLE__)
137#ifdef HAVE_SYS_SOCKET_H
138#include <sys/socket.h>
139#endif
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +0000140#endif
141
Victor Stinner8b905bd2011-10-25 13:34:04 +0200142#ifdef HAVE_DLFCN_H
143#include <dlfcn.h>
144#endif
145
Charles-Francois Natali44feda32013-05-20 14:40:46 +0200146#ifdef __hpux
147#include <sys/mpctl.h>
148#endif
149
150#if defined(__DragonFly__) || \
151 defined(__OpenBSD__) || \
152 defined(__FreeBSD__) || \
153 defined(__NetBSD__) || \
154 defined(__APPLE__)
155#include <sys/sysctl.h>
156#endif
157
Victor Stinner9b1f4742016-09-06 16:18:52 -0700158#ifdef HAVE_LINUX_RANDOM_H
159# include <linux/random.h>
160#endif
161#ifdef HAVE_GETRANDOM_SYSCALL
162# include <sys/syscall.h>
163#endif
164
Antoine Pitroubcf2b592012-02-08 23:28:36 +0100165#if defined(MS_WINDOWS)
166# define TERMSIZE_USE_CONIO
167#elif defined(HAVE_SYS_IOCTL_H)
168# include <sys/ioctl.h>
169# if defined(HAVE_TERMIOS_H)
170# include <termios.h>
171# endif
172# if defined(TIOCGWINSZ)
173# define TERMSIZE_USE_IOCTL
174# endif
175#endif /* MS_WINDOWS */
176
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000177/* Various compilers have only certain posix functions */
Martin v. Löwis4f1cd8b2001-07-26 13:41:06 +0000178/* XXX Gosh I wish these were all moved into pyconfig.h */
Victor Stinner8c62be82010-05-06 00:08:46 +0000179#if defined(__WATCOMC__) && !defined(__QNX__) /* Watcom compiler */
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000180#define HAVE_OPENDIR 1
Victor Stinner8c62be82010-05-06 00:08:46 +0000181#define HAVE_SYSTEM 1
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000182#include <process.h>
183#else
Victor Stinner8c62be82010-05-06 00:08:46 +0000184#ifdef _MSC_VER /* Microsoft compiler */
Amaury Forgeot d'Arc4b6fdf32010-09-07 21:31:17 +0000185#define HAVE_GETPPID 1
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +0000186#define HAVE_GETLOGIN 1
Victor Stinner8c62be82010-05-06 00:08:46 +0000187#define HAVE_SPAWNV 1
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000188#define HAVE_EXECV 1
Steve Dowercc16be82016-09-08 10:35:16 -0700189#define HAVE_WSPAWNV 1
190#define HAVE_WEXECV 1
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000191#define HAVE_PIPE 1
Victor Stinner8c62be82010-05-06 00:08:46 +0000192#define HAVE_SYSTEM 1
193#define HAVE_CWAIT 1
194#define HAVE_FSYNC 1
Tim Peters11b23062003-04-23 02:39:17 +0000195#define fsync _commit
Andrew MacIntyre6c73af22002-03-03 03:07:07 +0000196#else
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000197/* Unix functions that the configure script doesn't check for */
pxinwrf2d7ac72019-05-21 18:46:37 +0800198#ifndef __VXWORKS__
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000199#define HAVE_EXECV 1
200#define HAVE_FORK 1
Victor Stinner8c62be82010-05-06 00:08:46 +0000201#if defined(__USLC__) && defined(__SCO_VERSION__) /* SCO UDK Compiler */
Guido van Rossum2242f2f2001-04-11 20:58:20 +0000202#define HAVE_FORK1 1
203#endif
pxinwrf2d7ac72019-05-21 18:46:37 +0800204#endif
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000205#define HAVE_GETEGID 1
206#define HAVE_GETEUID 1
207#define HAVE_GETGID 1
208#define HAVE_GETPPID 1
209#define HAVE_GETUID 1
210#define HAVE_KILL 1
211#define HAVE_OPENDIR 1
212#define HAVE_PIPE 1
Victor Stinner8c62be82010-05-06 00:08:46 +0000213#define HAVE_SYSTEM 1
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000214#define HAVE_WAIT 1
Victor Stinner8c62be82010-05-06 00:08:46 +0000215#define HAVE_TTYNAME 1
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000216#endif /* _MSC_VER */
Guido van Rossumc5a0f531997-12-02 20:36:02 +0000217#endif /* ! __WATCOMC__ || __QNX__ */
Guido van Rossumad0ee831995-03-01 10:34:45 +0000218
Victor Stinnera2f7c002012-02-08 03:36:25 +0100219
Larry Hastings61272b72014-01-07 12:41:53 -0800220/*[clinic input]
Larry Hastings2f936352014-08-05 14:04:04 +1000221# one of the few times we lie about this name!
Larry Hastings44e2eaa2013-11-23 15:37:55 -0800222module os
Larry Hastings61272b72014-01-07 12:41:53 -0800223[clinic start generated code]*/
Larry Hastings2f936352014-08-05 14:04:04 +1000224/*[clinic end generated code: output=da39a3ee5e6b4b0d input=94a0f0f978acae17]*/
Victor Stinnera2f7c002012-02-08 03:36:25 +0100225
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000226#ifndef _MSC_VER
Guido van Rossum36bc6801995-06-14 22:54:23 +0000227
Martin v. Löwis8eb92a02002-09-19 08:03:21 +0000228#if defined(__sgi)&&_COMPILER_VERSION>=700
229/* declare ctermid_r if compiling with MIPSPro 7.x in ANSI C mode
230 (default) */
231extern char *ctermid_r(char *);
232#endif
233
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000234#endif /* !_MSC_VER */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000235
pxinwrf2d7ac72019-05-21 18:46:37 +0800236#if defined(__VXWORKS__)
237#include <vxCpuLib.h>
238#include <rtpLib.h>
239#include <wait.h>
240#include <taskLib.h>
241#ifndef _P_WAIT
242#define _P_WAIT 0
243#define _P_NOWAIT 1
244#define _P_NOWAITO 1
245#endif
246#endif /* __VXWORKS__ */
247
Pablo Galindo6c6ddf92018-01-29 01:56:10 +0000248#ifdef HAVE_POSIX_SPAWN
249#include <spawn.h>
250#endif
251
Guido van Rossumb6775db1994-08-01 11:34:53 +0000252#ifdef HAVE_UTIME_H
253#include <utime.h>
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +0000254#endif /* HAVE_UTIME_H */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000255
Guido van Rossum14ed0b21994-09-29 09:50:09 +0000256#ifdef HAVE_SYS_UTIME_H
257#include <sys/utime.h>
258#define HAVE_UTIME_H /* pretend we do for the rest of this file */
259#endif /* HAVE_SYS_UTIME_H */
260
Guido van Rossumb6775db1994-08-01 11:34:53 +0000261#ifdef HAVE_SYS_TIMES_H
262#include <sys/times.h>
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +0000263#endif /* HAVE_SYS_TIMES_H */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000264
265#ifdef HAVE_SYS_PARAM_H
266#include <sys/param.h>
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +0000267#endif /* HAVE_SYS_PARAM_H */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000268
269#ifdef HAVE_SYS_UTSNAME_H
270#include <sys/utsname.h>
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +0000271#endif /* HAVE_SYS_UTSNAME_H */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000272
Guido van Rossum3bbc62e1995-01-02 19:30:30 +0000273#ifdef HAVE_DIRENT_H
Guido van Rossumb6775db1994-08-01 11:34:53 +0000274#include <dirent.h>
Guido van Rossum3bbc62e1995-01-02 19:30:30 +0000275#define NAMLEN(dirent) strlen((dirent)->d_name)
276#else
Guido van Rossumc5a0f531997-12-02 20:36:02 +0000277#if defined(__WATCOMC__) && !defined(__QNX__)
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000278#include <direct.h>
279#define NAMLEN(dirent) strlen((dirent)->d_name)
280#else
Guido van Rossumb6775db1994-08-01 11:34:53 +0000281#define dirent direct
Guido van Rossum3bbc62e1995-01-02 19:30:30 +0000282#define NAMLEN(dirent) (dirent)->d_namlen
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000283#endif
Guido van Rossum3bbc62e1995-01-02 19:30:30 +0000284#ifdef HAVE_SYS_NDIR_H
Guido van Rossumb6775db1994-08-01 11:34:53 +0000285#include <sys/ndir.h>
Guido van Rossum3bbc62e1995-01-02 19:30:30 +0000286#endif
287#ifdef HAVE_SYS_DIR_H
Guido van Rossumb6775db1994-08-01 11:34:53 +0000288#include <sys/dir.h>
Guido van Rossum3bbc62e1995-01-02 19:30:30 +0000289#endif
290#ifdef HAVE_NDIR_H
Guido van Rossumb6775db1994-08-01 11:34:53 +0000291#include <ndir.h>
Guido van Rossum3bbc62e1995-01-02 19:30:30 +0000292#endif
293#endif
Guido van Rossumb6775db1994-08-01 11:34:53 +0000294
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000295#ifdef _MSC_VER
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000296#ifdef HAVE_DIRECT_H
Guido van Rossumb6775db1994-08-01 11:34:53 +0000297#include <direct.h>
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000298#endif
299#ifdef HAVE_IO_H
Guido van Rossumb6775db1994-08-01 11:34:53 +0000300#include <io.h>
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000301#endif
302#ifdef HAVE_PROCESS_H
Guido van Rossumb6775db1994-08-01 11:34:53 +0000303#include <process.h>
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000304#endif
Raymond Hettinger0291c9f2010-08-01 21:10:35 +0000305#ifndef IO_REPARSE_TAG_SYMLINK
Amaury Forgeot d'Arc844807e2010-08-16 22:16:51 +0000306#define IO_REPARSE_TAG_SYMLINK (0xA000000CL)
Raymond Hettinger0291c9f2010-08-01 21:10:35 +0000307#endif
Tim Golden0321cf22014-05-05 19:46:17 +0100308#ifndef IO_REPARSE_TAG_MOUNT_POINT
309#define IO_REPARSE_TAG_MOUNT_POINT (0xA0000003L)
310#endif
Tim Petersbc2e10e2002-03-03 23:17:02 +0000311#include "osdefs.h"
Kristján Valur Jónssonf64e6512009-04-13 10:16:14 +0000312#include <malloc.h>
Guido van Rossumb6775db1994-08-01 11:34:53 +0000313#include <windows.h>
Victor Stinner8c62be82010-05-06 00:08:46 +0000314#include <shellapi.h> /* for ShellExecute() */
Brian Curtine8e4b3b2010-09-23 20:04:14 +0000315#include <lmcons.h> /* for UNLEN */
Brian Curtin52173d42010-12-02 18:29:18 +0000316#define HAVE_SYMLINK
Guido van Rossuma4916fa1996-05-23 22:58:55 +0000317#endif /* _MSC_VER */
Guido van Rossumb6775db1994-08-01 11:34:53 +0000318
Tim Petersbc2e10e2002-03-03 23:17:02 +0000319#ifndef MAXPATHLEN
Thomas Wouters477c8d52006-05-27 19:21:47 +0000320#if defined(PATH_MAX) && PATH_MAX > 1024
321#define MAXPATHLEN PATH_MAX
322#else
Tim Petersbc2e10e2002-03-03 23:17:02 +0000323#define MAXPATHLEN 1024
Thomas Wouters477c8d52006-05-27 19:21:47 +0000324#endif
Tim Petersbc2e10e2002-03-03 23:17:02 +0000325#endif /* MAXPATHLEN */
326
Guido van Rossum54ecc3d1999-01-27 17:53:11 +0000327#ifdef UNION_WAIT
328/* Emulate some macros on systems that have a union instead of macros */
329
330#ifndef WIFEXITED
331#define WIFEXITED(u_wait) (!(u_wait).w_termsig && !(u_wait).w_coredump)
332#endif
333
334#ifndef WEXITSTATUS
335#define WEXITSTATUS(u_wait) (WIFEXITED(u_wait)?((u_wait).w_retcode):-1)
336#endif
337
338#ifndef WTERMSIG
339#define WTERMSIG(u_wait) ((u_wait).w_termsig)
340#endif
341
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000342#define WAIT_TYPE union wait
343#define WAIT_STATUS_INT(s) (s.w_status)
344
345#else /* !UNION_WAIT */
346#define WAIT_TYPE int
347#define WAIT_STATUS_INT(s) (s)
Guido van Rossum54ecc3d1999-01-27 17:53:11 +0000348#endif /* UNION_WAIT */
349
Greg Wardb48bc172000-03-01 21:51:56 +0000350/* Don't use the "_r" form if we don't need it (also, won't have a
351 prototype for it, at least on Solaris -- maybe others as well?). */
Antoine Pitroua6a4dc82017-09-07 18:56:24 +0200352#if defined(HAVE_CTERMID_R)
Greg Wardb48bc172000-03-01 21:51:56 +0000353#define USE_CTERMID_R
354#endif
355
Fred Drake699f3522000-06-29 21:12:41 +0000356/* choose the appropriate stat and fstat functions and return structs */
Guido van Rossum64529cd2000-06-30 22:45:12 +0000357#undef STAT
Antoine Pitroue47e0932011-01-19 15:21:35 +0000358#undef FSTAT
359#undef STRUCT_STAT
Victor Stinner14b9b112013-06-25 00:37:25 +0200360#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +0000361# define STAT win32_stat
Larry Hastings9cf065c2012-06-22 16:30:09 -0700362# define LSTAT win32_lstat
Victor Stinnere134a7f2015-03-30 10:09:31 +0200363# define FSTAT _Py_fstat_noraise
Steve Dowerf2f373f2015-02-21 08:44:05 -0800364# define STRUCT_STAT struct _Py_stat_struct
Fred Drake699f3522000-06-29 21:12:41 +0000365#else
Victor Stinner8c62be82010-05-06 00:08:46 +0000366# define STAT stat
Larry Hastings9cf065c2012-06-22 16:30:09 -0700367# define LSTAT lstat
Victor Stinner8c62be82010-05-06 00:08:46 +0000368# define FSTAT fstat
369# define STRUCT_STAT struct stat
Fred Drake699f3522000-06-29 21:12:41 +0000370#endif
371
Tim Peters11b23062003-04-23 02:39:17 +0000372#if defined(MAJOR_IN_MKDEV)
Martin v. Löwisdbe3f762002-10-10 14:27:30 +0000373#include <sys/mkdev.h>
374#else
375#if defined(MAJOR_IN_SYSMACROS)
376#include <sys/sysmacros.h>
377#endif
Neal Norwitz3d949422002-04-20 13:46:43 +0000378#if defined(HAVE_MKNOD) && defined(HAVE_SYS_MKDEV_H)
379#include <sys/mkdev.h>
380#endif
Martin v. Löwisdbe3f762002-10-10 14:27:30 +0000381#endif
Fred Drake699f3522000-06-29 21:12:41 +0000382
Serhiy Storchaka06a13f82015-02-22 21:34:54 +0200383#ifdef MS_WINDOWS
Victor Stinner6036e442015-03-08 01:58:04 +0100384#define INITFUNC PyInit_nt
385#define MODNAME "nt"
386#else
387#define INITFUNC PyInit_posix
388#define MODNAME "posix"
389#endif
390
jcea6c51d512018-01-28 14:00:08 +0100391#if defined(__sun)
392/* Something to implement in autoconf, not present in autoconf 2.69 */
393#define HAVE_STRUCT_STAT_ST_FSTYPE 1
394#endif
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200395
Zackery Spytz43fdbd22019-05-29 13:57:07 -0600396/* memfd_create is either defined in sys/mman.h or sys/memfd.h
397 * linux/memfd.h defines additional flags
398 */
399#ifdef HAVE_SYS_MMAN_H
400#include <sys/mman.h>
401#endif
402#ifdef HAVE_SYS_MEMFD_H
403#include <sys/memfd.h>
404#endif
405#ifdef HAVE_LINUX_MEMFD_H
406#include <linux/memfd.h>
407#endif
408
Gregory P. Smith1d300ce2018-12-30 21:13:02 -0800409#ifdef _Py_MEMORY_SANITIZER
410# include <sanitizer/msan_interface.h>
411#endif
412
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200413#ifdef HAVE_FORK
414static void
415run_at_forkers(PyObject *lst, int reverse)
416{
417 Py_ssize_t i;
418 PyObject *cpy;
419
420 if (lst != NULL) {
421 assert(PyList_CheckExact(lst));
422
423 /* Use a list copy in case register_at_fork() is called from
424 * one of the callbacks.
425 */
426 cpy = PyList_GetSlice(lst, 0, PyList_GET_SIZE(lst));
427 if (cpy == NULL)
428 PyErr_WriteUnraisable(lst);
429 else {
430 if (reverse)
431 PyList_Reverse(cpy);
432 for (i = 0; i < PyList_GET_SIZE(cpy); i++) {
433 PyObject *func, *res;
434 func = PyList_GET_ITEM(cpy, i);
435 res = PyObject_CallObject(func, NULL);
436 if (res == NULL)
437 PyErr_WriteUnraisable(func);
438 else
439 Py_DECREF(res);
440 }
441 Py_DECREF(cpy);
442 }
443 }
444}
445
446void
447PyOS_BeforeFork(void)
448{
Victor Stinnercaba55b2018-08-03 15:33:52 +0200449 run_at_forkers(_PyInterpreterState_Get()->before_forkers, 1);
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200450
451 _PyImport_AcquireLock();
452}
453
454void
455PyOS_AfterFork_Parent(void)
456{
457 if (_PyImport_ReleaseLock() <= 0)
458 Py_FatalError("failed releasing import lock after fork");
459
Victor Stinnercaba55b2018-08-03 15:33:52 +0200460 run_at_forkers(_PyInterpreterState_Get()->after_forkers_parent, 0);
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200461}
462
463void
464PyOS_AfterFork_Child(void)
465{
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200466 _PyRuntimeState *runtime = &_PyRuntime;
467 _PyGILState_Reinit(runtime);
Victor Stinnerd5d9e812019-05-13 12:35:37 +0200468 _PyEval_ReInitThreads(runtime);
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200469 _PyImport_ReInitLock();
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200470 _PySignal_AfterFork();
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200471 _PyRuntimeState_ReInitThreads(runtime);
Victor Stinnerb49858b2019-05-24 15:20:23 +0200472 _PyInterpreterState_DeleteExceptMain(runtime);
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200473
Victor Stinnercaba55b2018-08-03 15:33:52 +0200474 run_at_forkers(_PyInterpreterState_Get()->after_forkers_child, 0);
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200475}
476
477static int
478register_at_forker(PyObject **lst, PyObject *func)
479{
Gregory P. Smith163468a2017-05-29 10:03:41 -0700480 if (func == NULL) /* nothing to register? do nothing. */
481 return 0;
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200482 if (*lst == NULL) {
483 *lst = PyList_New(0);
484 if (*lst == NULL)
485 return -1;
486 }
487 return PyList_Append(*lst, func);
488}
489#endif
490
491/* Legacy wrapper */
492void
493PyOS_AfterFork(void)
494{
495#ifdef HAVE_FORK
496 PyOS_AfterFork_Child();
497#endif
498}
499
500
Victor Stinner6036e442015-03-08 01:58:04 +0100501#ifdef MS_WINDOWS
Serhiy Storchaka06a13f82015-02-22 21:34:54 +0200502/* defined in fileutils.c */
Benjamin Petersone5024512018-09-12 12:06:42 -0700503void _Py_time_t_to_FILE_TIME(time_t, int, FILETIME *);
504void _Py_attribute_data_to_stat(BY_HANDLE_FILE_INFORMATION *,
Serhiy Storchaka06a13f82015-02-22 21:34:54 +0200505 ULONG, struct _Py_stat_struct *);
506#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -0700507
Larry Hastings9cf065c2012-06-22 16:30:09 -0700508
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200509#ifndef MS_WINDOWS
510PyObject *
511_PyLong_FromUid(uid_t uid)
512{
513 if (uid == (uid_t)-1)
514 return PyLong_FromLong(-1);
515 return PyLong_FromUnsignedLong(uid);
516}
517
518PyObject *
519_PyLong_FromGid(gid_t gid)
520{
521 if (gid == (gid_t)-1)
522 return PyLong_FromLong(-1);
523 return PyLong_FromUnsignedLong(gid);
524}
525
526int
527_Py_Uid_Converter(PyObject *obj, void *p)
528{
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700529 uid_t uid;
530 PyObject *index;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200531 int overflow;
Serhiy Storchakab4621892013-02-10 23:28:02 +0200532 long result;
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700533 unsigned long uresult;
534
535 index = PyNumber_Index(obj);
536 if (index == NULL) {
537 PyErr_Format(PyExc_TypeError,
538 "uid should be integer, not %.200s",
539 Py_TYPE(obj)->tp_name);
Serhiy Storchakab4621892013-02-10 23:28:02 +0200540 return 0;
541 }
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700542
543 /*
544 * Handling uid_t is complicated for two reasons:
545 * * Although uid_t is (always?) unsigned, it still
546 * accepts -1.
547 * * We don't know its size in advance--it may be
548 * bigger than an int, or it may be smaller than
549 * a long.
550 *
551 * So a bit of defensive programming is in order.
552 * Start with interpreting the value passed
553 * in as a signed long and see if it works.
554 */
555
556 result = PyLong_AsLongAndOverflow(index, &overflow);
557
558 if (!overflow) {
559 uid = (uid_t)result;
560
561 if (result == -1) {
562 if (PyErr_Occurred())
563 goto fail;
564 /* It's a legitimate -1, we're done. */
565 goto success;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200566 }
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700567
568 /* Any other negative number is disallowed. */
569 if (result < 0)
570 goto underflow;
571
572 /* Ensure the value wasn't truncated. */
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200573 if (sizeof(uid_t) < sizeof(long) &&
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700574 (long)uid != result)
575 goto underflow;
576 goto success;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200577 }
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700578
579 if (overflow < 0)
580 goto underflow;
581
582 /*
583 * Okay, the value overflowed a signed long. If it
584 * fits in an *unsigned* long, it may still be okay,
585 * as uid_t may be unsigned long on this platform.
586 */
587 uresult = PyLong_AsUnsignedLong(index);
588 if (PyErr_Occurred()) {
589 if (PyErr_ExceptionMatches(PyExc_OverflowError))
590 goto overflow;
591 goto fail;
592 }
593
594 uid = (uid_t)uresult;
595
596 /*
597 * If uid == (uid_t)-1, the user actually passed in ULONG_MAX,
598 * but this value would get interpreted as (uid_t)-1 by chown
599 * and its siblings. That's not what the user meant! So we
600 * throw an overflow exception instead. (We already
Tim Golden23005082013-10-25 11:22:37 +0100601 * handled a real -1 with PyLong_AsLongAndOverflow() above.)
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700602 */
603 if (uid == (uid_t)-1)
604 goto overflow;
605
606 /* Ensure the value wasn't truncated. */
607 if (sizeof(uid_t) < sizeof(long) &&
608 (unsigned long)uid != uresult)
609 goto overflow;
610 /* fallthrough */
611
612success:
613 Py_DECREF(index);
614 *(uid_t *)p = uid;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200615 return 1;
616
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700617underflow:
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200618 PyErr_SetString(PyExc_OverflowError,
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700619 "uid is less than minimum");
620 goto fail;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200621
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700622overflow:
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200623 PyErr_SetString(PyExc_OverflowError,
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700624 "uid is greater than maximum");
625 /* fallthrough */
626
627fail:
628 Py_DECREF(index);
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200629 return 0;
630}
631
632int
633_Py_Gid_Converter(PyObject *obj, void *p)
634{
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700635 gid_t gid;
636 PyObject *index;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200637 int overflow;
Serhiy Storchakab4621892013-02-10 23:28:02 +0200638 long result;
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700639 unsigned long uresult;
640
641 index = PyNumber_Index(obj);
642 if (index == NULL) {
643 PyErr_Format(PyExc_TypeError,
644 "gid should be integer, not %.200s",
645 Py_TYPE(obj)->tp_name);
Serhiy Storchakab4621892013-02-10 23:28:02 +0200646 return 0;
647 }
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700648
649 /*
650 * Handling gid_t is complicated for two reasons:
651 * * Although gid_t is (always?) unsigned, it still
652 * accepts -1.
653 * * We don't know its size in advance--it may be
654 * bigger than an int, or it may be smaller than
655 * a long.
656 *
657 * So a bit of defensive programming is in order.
658 * Start with interpreting the value passed
659 * in as a signed long and see if it works.
660 */
661
662 result = PyLong_AsLongAndOverflow(index, &overflow);
663
664 if (!overflow) {
665 gid = (gid_t)result;
666
667 if (result == -1) {
668 if (PyErr_Occurred())
669 goto fail;
670 /* It's a legitimate -1, we're done. */
671 goto success;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200672 }
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700673
674 /* Any other negative number is disallowed. */
675 if (result < 0) {
676 goto underflow;
677 }
678
679 /* Ensure the value wasn't truncated. */
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200680 if (sizeof(gid_t) < sizeof(long) &&
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700681 (long)gid != result)
682 goto underflow;
683 goto success;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200684 }
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700685
686 if (overflow < 0)
687 goto underflow;
688
689 /*
690 * Okay, the value overflowed a signed long. If it
691 * fits in an *unsigned* long, it may still be okay,
692 * as gid_t may be unsigned long on this platform.
693 */
694 uresult = PyLong_AsUnsignedLong(index);
695 if (PyErr_Occurred()) {
696 if (PyErr_ExceptionMatches(PyExc_OverflowError))
697 goto overflow;
698 goto fail;
699 }
700
701 gid = (gid_t)uresult;
702
703 /*
704 * If gid == (gid_t)-1, the user actually passed in ULONG_MAX,
705 * but this value would get interpreted as (gid_t)-1 by chown
706 * and its siblings. That's not what the user meant! So we
707 * throw an overflow exception instead. (We already
Tim Golden23005082013-10-25 11:22:37 +0100708 * handled a real -1 with PyLong_AsLongAndOverflow() above.)
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700709 */
710 if (gid == (gid_t)-1)
711 goto overflow;
712
713 /* Ensure the value wasn't truncated. */
714 if (sizeof(gid_t) < sizeof(long) &&
715 (unsigned long)gid != uresult)
716 goto overflow;
717 /* fallthrough */
718
719success:
720 Py_DECREF(index);
721 *(gid_t *)p = gid;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200722 return 1;
723
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700724underflow:
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200725 PyErr_SetString(PyExc_OverflowError,
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700726 "gid is less than minimum");
727 goto fail;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200728
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700729overflow:
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200730 PyErr_SetString(PyExc_OverflowError,
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700731 "gid is greater than maximum");
732 /* fallthrough */
733
734fail:
735 Py_DECREF(index);
Serhiy Storchaka7cf55992013-02-10 21:56:49 +0200736 return 0;
737}
738#endif /* MS_WINDOWS */
739
740
Benjamin Petersoned4aa832016-09-05 17:44:18 -0700741#define _PyLong_FromDev PyLong_FromLongLong
Gregory P. Smith702dada2015-01-28 16:07:52 -0800742
743
Serhiy Storchakab2653b32015-01-18 11:12:11 +0200744#if defined(HAVE_MKNOD) && defined(HAVE_MAKEDEV)
745static int
746_Py_Dev_Converter(PyObject *obj, void *p)
747{
Serhiy Storchakab2653b32015-01-18 11:12:11 +0200748 *((dev_t *)p) = PyLong_AsUnsignedLongLong(obj);
Serhiy Storchakab2653b32015-01-18 11:12:11 +0200749 if (PyErr_Occurred())
750 return 0;
751 return 1;
752}
Gregory P. Smith702dada2015-01-28 16:07:52 -0800753#endif /* HAVE_MKNOD && HAVE_MAKEDEV */
Serhiy Storchakab2653b32015-01-18 11:12:11 +0200754
755
Larry Hastings9cf065c2012-06-22 16:30:09 -0700756#ifdef AT_FDCWD
Trent Nelson9a461052012-09-18 21:50:06 -0400757/*
758 * Why the (int) cast? Solaris 10 defines AT_FDCWD as 0xffd19553 (-3041965);
759 * without the int cast, the value gets interpreted as uint (4291925331),
760 * which doesn't play nicely with all the initializer lines in this file that
761 * look like this:
762 * int dir_fd = DEFAULT_DIR_FD;
763 */
764#define DEFAULT_DIR_FD (int)AT_FDCWD
Larry Hastings9cf065c2012-06-22 16:30:09 -0700765#else
766#define DEFAULT_DIR_FD (-100)
767#endif
768
769static int
Serhiy Storchaka819399b2016-04-06 22:17:52 +0300770_fd_converter(PyObject *o, int *p)
Serhiy Storchakaa2ad5c32013-01-07 23:13:46 +0200771{
772 int overflow;
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700773 long long_value;
774
775 PyObject *index = PyNumber_Index(o);
776 if (index == NULL) {
Larry Hastings9cf065c2012-06-22 16:30:09 -0700777 return 0;
778 }
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700779
Serhiy Storchaka819399b2016-04-06 22:17:52 +0300780 assert(PyLong_Check(index));
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700781 long_value = PyLong_AsLongAndOverflow(index, &overflow);
782 Py_DECREF(index);
Serhiy Storchaka819399b2016-04-06 22:17:52 +0300783 assert(!PyErr_Occurred());
Serhiy Storchakaa2ad5c32013-01-07 23:13:46 +0200784 if (overflow > 0 || long_value > INT_MAX) {
Larry Hastings9cf065c2012-06-22 16:30:09 -0700785 PyErr_SetString(PyExc_OverflowError,
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700786 "fd is greater than maximum");
Larry Hastings9cf065c2012-06-22 16:30:09 -0700787 return 0;
788 }
Serhiy Storchakaa2ad5c32013-01-07 23:13:46 +0200789 if (overflow < 0 || long_value < INT_MIN) {
Larry Hastings9cf065c2012-06-22 16:30:09 -0700790 PyErr_SetString(PyExc_OverflowError,
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700791 "fd is less than minimum");
Larry Hastings9cf065c2012-06-22 16:30:09 -0700792 return 0;
793 }
Larry Hastingsa27b83a2013-08-08 00:19:50 -0700794
Larry Hastings9cf065c2012-06-22 16:30:09 -0700795 *p = (int)long_value;
796 return 1;
797}
798
799static int
Serhiy Storchakaa2ad5c32013-01-07 23:13:46 +0200800dir_fd_converter(PyObject *o, void *p)
801{
802 if (o == Py_None) {
803 *(int *)p = DEFAULT_DIR_FD;
804 return 1;
805 }
Serhiy Storchaka819399b2016-04-06 22:17:52 +0300806 else if (PyIndex_Check(o)) {
807 return _fd_converter(o, (int *)p);
808 }
809 else {
810 PyErr_Format(PyExc_TypeError,
811 "argument should be integer or None, not %.200s",
812 Py_TYPE(o)->tp_name);
813 return 0;
814 }
Larry Hastings9cf065c2012-06-22 16:30:09 -0700815}
816
817
Larry Hastings9cf065c2012-06-22 16:30:09 -0700818/*
819 * A PyArg_ParseTuple "converter" function
820 * that handles filesystem paths in the manner
821 * preferred by the os module.
822 *
823 * path_converter accepts (Unicode) strings and their
824 * subclasses, and bytes and their subclasses. What
825 * it does with the argument depends on the platform:
826 *
827 * * On Windows, if we get a (Unicode) string we
828 * extract the wchar_t * and return it; if we get
Steve Dowercc16be82016-09-08 10:35:16 -0700829 * bytes we decode to wchar_t * and return that.
Larry Hastings9cf065c2012-06-22 16:30:09 -0700830 *
831 * * On all other platforms, strings are encoded
832 * to bytes using PyUnicode_FSConverter, then we
833 * extract the char * from the bytes object and
834 * return that.
835 *
836 * path_converter also optionally accepts signed
837 * integers (representing open file descriptors) instead
838 * of path strings.
839 *
840 * Input fields:
841 * path.nullable
842 * If nonzero, the path is permitted to be None.
843 * path.allow_fd
844 * If nonzero, the path is permitted to be a file handle
845 * (a signed int) instead of a string.
846 * path.function_name
847 * If non-NULL, path_converter will use that as the name
848 * of the function in error messages.
Larry Hastings31826802013-10-19 00:09:25 -0700849 * (If path.function_name is NULL it omits the function name.)
Larry Hastings9cf065c2012-06-22 16:30:09 -0700850 * path.argument_name
851 * If non-NULL, path_converter will use that as the name
852 * of the parameter in error messages.
853 * (If path.argument_name is NULL it uses "path".)
854 *
855 * Output fields:
856 * path.wide
857 * Points to the path if it was expressed as Unicode
858 * and was not encoded. (Only used on Windows.)
859 * path.narrow
860 * Points to the path if it was expressed as bytes,
Steve Dowercc16be82016-09-08 10:35:16 -0700861 * or it was Unicode and was encoded to bytes. (On Windows,
Martin Panterb1321fb2016-10-10 00:38:21 +0000862 * is a non-zero integer if the path was expressed as bytes.
Steve Dowercc16be82016-09-08 10:35:16 -0700863 * The type is deliberately incompatible to prevent misuse.)
Larry Hastings9cf065c2012-06-22 16:30:09 -0700864 * path.fd
865 * Contains a file descriptor if path.accept_fd was true
866 * and the caller provided a signed integer instead of any
867 * sort of string.
868 *
869 * WARNING: if your "path" parameter is optional, and is
870 * unspecified, path_converter will never get called.
871 * So if you set allow_fd, you *MUST* initialize path.fd = -1
872 * yourself!
873 * path.length
874 * The length of the path in characters, if specified as
875 * a string.
876 * path.object
Xiang Zhang04316c42017-01-08 23:26:57 +0800877 * The original object passed in (if get a PathLike object,
878 * the result of PyOS_FSPath() is treated as the original object).
879 * Own a reference to the object.
Larry Hastings9cf065c2012-06-22 16:30:09 -0700880 * path.cleanup
881 * For internal use only. May point to a temporary object.
882 * (Pay no attention to the man behind the curtain.)
883 *
884 * At most one of path.wide or path.narrow will be non-NULL.
885 * If path was None and path.nullable was set,
886 * or if path was an integer and path.allow_fd was set,
887 * both path.wide and path.narrow will be NULL
888 * and path.length will be 0.
Georg Brandlf7875592012-06-24 13:58:31 +0200889 *
Larry Hastings9cf065c2012-06-22 16:30:09 -0700890 * path_converter takes care to not write to the path_t
891 * unless it's successful. However it must reset the
892 * "cleanup" field each time it's called.
893 *
894 * Use as follows:
895 * path_t path;
896 * memset(&path, 0, sizeof(path));
897 * PyArg_ParseTuple(args, "O&", path_converter, &path);
898 * // ... use values from path ...
899 * path_cleanup(&path);
900 *
901 * (Note that if PyArg_Parse fails you don't need to call
902 * path_cleanup(). However it is safe to do so.)
903 */
904typedef struct {
Victor Stinner292c8352012-10-30 02:17:38 +0100905 const char *function_name;
906 const char *argument_name;
Larry Hastings9cf065c2012-06-22 16:30:09 -0700907 int nullable;
908 int allow_fd;
Serhiy Storchakadeab18d2016-05-07 16:45:18 +0300909 const wchar_t *wide;
Steve Dowercc16be82016-09-08 10:35:16 -0700910#ifdef MS_WINDOWS
911 BOOL narrow;
912#else
Serhiy Storchakadeab18d2016-05-07 16:45:18 +0300913 const char *narrow;
Steve Dowercc16be82016-09-08 10:35:16 -0700914#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -0700915 int fd;
916 Py_ssize_t length;
917 PyObject *object;
918 PyObject *cleanup;
919} path_t;
920
Steve Dowercc16be82016-09-08 10:35:16 -0700921#ifdef MS_WINDOWS
922#define PATH_T_INITIALIZE(function_name, argument_name, nullable, allow_fd) \
923 {function_name, argument_name, nullable, allow_fd, NULL, FALSE, -1, 0, NULL, NULL}
924#else
Larry Hastings2f936352014-08-05 14:04:04 +1000925#define PATH_T_INITIALIZE(function_name, argument_name, nullable, allow_fd) \
926 {function_name, argument_name, nullable, allow_fd, NULL, NULL, -1, 0, NULL, NULL}
Steve Dowercc16be82016-09-08 10:35:16 -0700927#endif
Larry Hastings31826802013-10-19 00:09:25 -0700928
Larry Hastings9cf065c2012-06-22 16:30:09 -0700929static void
Xiang Zhang04316c42017-01-08 23:26:57 +0800930path_cleanup(path_t *path)
931{
932 Py_CLEAR(path->object);
933 Py_CLEAR(path->cleanup);
Larry Hastings9cf065c2012-06-22 16:30:09 -0700934}
935
936static int
Serhiy Storchaka819399b2016-04-06 22:17:52 +0300937path_converter(PyObject *o, void *p)
938{
Larry Hastings9cf065c2012-06-22 16:30:09 -0700939 path_t *path = (path_t *)p;
Xiang Zhang04316c42017-01-08 23:26:57 +0800940 PyObject *bytes = NULL;
941 Py_ssize_t length = 0;
Brett Cannon3f9183b2016-08-26 14:44:48 -0700942 int is_index, is_buffer, is_bytes, is_unicode;
Serhiy Storchakadeab18d2016-05-07 16:45:18 +0300943 const char *narrow;
Steve Dowercc16be82016-09-08 10:35:16 -0700944#ifdef MS_WINDOWS
Xiang Zhang04316c42017-01-08 23:26:57 +0800945 PyObject *wo = NULL;
Steve Dowercc16be82016-09-08 10:35:16 -0700946 const wchar_t *wide;
947#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -0700948
949#define FORMAT_EXCEPTION(exc, fmt) \
950 PyErr_Format(exc, "%s%s" fmt, \
951 path->function_name ? path->function_name : "", \
952 path->function_name ? ": " : "", \
953 path->argument_name ? path->argument_name : "path")
954
955 /* Py_CLEANUP_SUPPORTED support */
956 if (o == NULL) {
957 path_cleanup(path);
958 return 1;
959 }
960
Brett Cannon3f9183b2016-08-26 14:44:48 -0700961 /* Ensure it's always safe to call path_cleanup(). */
Xiang Zhang04316c42017-01-08 23:26:57 +0800962 path->object = path->cleanup = NULL;
963 /* path->object owns a reference to the original object */
964 Py_INCREF(o);
Larry Hastings9cf065c2012-06-22 16:30:09 -0700965
Serhiy Storchaka819399b2016-04-06 22:17:52 +0300966 if ((o == Py_None) && path->nullable) {
Larry Hastings9cf065c2012-06-22 16:30:09 -0700967 path->wide = NULL;
Steve Dowercc16be82016-09-08 10:35:16 -0700968#ifdef MS_WINDOWS
969 path->narrow = FALSE;
970#else
Larry Hastings9cf065c2012-06-22 16:30:09 -0700971 path->narrow = NULL;
Steve Dowercc16be82016-09-08 10:35:16 -0700972#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -0700973 path->fd = -1;
Xiang Zhang04316c42017-01-08 23:26:57 +0800974 goto success_exit;
Larry Hastings9cf065c2012-06-22 16:30:09 -0700975 }
976
Brett Cannon3f9183b2016-08-26 14:44:48 -0700977 /* Only call this here so that we don't treat the return value of
978 os.fspath() as an fd or buffer. */
979 is_index = path->allow_fd && PyIndex_Check(o);
980 is_buffer = PyObject_CheckBuffer(o);
981 is_bytes = PyBytes_Check(o);
982 is_unicode = PyUnicode_Check(o);
983
984 if (!is_index && !is_buffer && !is_unicode && !is_bytes) {
985 /* Inline PyOS_FSPath() for better error messages. */
986 _Py_IDENTIFIER(__fspath__);
Pablo Galindo09fbcd62019-02-18 10:46:34 +0000987 PyObject *func, *res;
Brett Cannon3f9183b2016-08-26 14:44:48 -0700988
989 func = _PyObject_LookupSpecial(o, &PyId___fspath__);
990 if (NULL == func) {
Xiang Zhang04316c42017-01-08 23:26:57 +0800991 goto error_format;
Brett Cannon3f9183b2016-08-26 14:44:48 -0700992 }
Pablo Galindo09fbcd62019-02-18 10:46:34 +0000993 res = _PyObject_CallNoArg(func);
Brett Cannon3f9183b2016-08-26 14:44:48 -0700994 Py_DECREF(func);
Pablo Galindo09fbcd62019-02-18 10:46:34 +0000995 if (NULL == res) {
Brett Cannon3f9183b2016-08-26 14:44:48 -0700996 goto error_exit;
997 }
Pablo Galindo09fbcd62019-02-18 10:46:34 +0000998 else if (PyUnicode_Check(res)) {
Brett Cannon3f9183b2016-08-26 14:44:48 -0700999 is_unicode = 1;
1000 }
Pablo Galindo09fbcd62019-02-18 10:46:34 +00001001 else if (PyBytes_Check(res)) {
Brett Cannon3f9183b2016-08-26 14:44:48 -07001002 is_bytes = 1;
1003 }
1004 else {
Pablo Galindo09fbcd62019-02-18 10:46:34 +00001005 PyErr_Format(PyExc_TypeError,
1006 "expected %.200s.__fspath__() to return str or bytes, "
1007 "not %.200s", Py_TYPE(o)->tp_name,
1008 Py_TYPE(res)->tp_name);
1009 Py_DECREF(res);
1010 goto error_exit;
Brett Cannon3f9183b2016-08-26 14:44:48 -07001011 }
Pablo Galindo09fbcd62019-02-18 10:46:34 +00001012
1013 /* still owns a reference to the original object */
1014 Py_DECREF(o);
1015 o = res;
Brett Cannon3f9183b2016-08-26 14:44:48 -07001016 }
1017
1018 if (is_unicode) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07001019#ifdef MS_WINDOWS
Victor Stinner26c03bd2016-09-19 11:55:44 +02001020 wide = PyUnicode_AsUnicodeAndSize(o, &length);
Victor Stinner59799a82013-11-13 14:17:30 +01001021 if (!wide) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001022 goto error_exit;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001023 }
Victor Stinner59799a82013-11-13 14:17:30 +01001024 if (length > 32767) {
1025 FORMAT_EXCEPTION(PyExc_ValueError, "%s too long for Windows");
Xiang Zhang04316c42017-01-08 23:26:57 +08001026 goto error_exit;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001027 }
Serhiy Storchaka2b0d2002015-04-20 09:53:58 +03001028 if (wcslen(wide) != length) {
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001029 FORMAT_EXCEPTION(PyExc_ValueError, "embedded null character in %s");
Xiang Zhang04316c42017-01-08 23:26:57 +08001030 goto error_exit;
Serhiy Storchaka2b0d2002015-04-20 09:53:58 +03001031 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07001032
1033 path->wide = wide;
Xiang Zhang04316c42017-01-08 23:26:57 +08001034 path->narrow = FALSE;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001035 path->fd = -1;
Xiang Zhang04316c42017-01-08 23:26:57 +08001036 goto success_exit;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001037#else
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001038 if (!PyUnicode_FSConverter(o, &bytes)) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001039 goto error_exit;
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001040 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07001041#endif
1042 }
Brett Cannon3f9183b2016-08-26 14:44:48 -07001043 else if (is_bytes) {
Serhiy Storchakad73c3182016-08-06 23:22:08 +03001044 bytes = o;
1045 Py_INCREF(bytes);
1046 }
Brett Cannon3f9183b2016-08-26 14:44:48 -07001047 else if (is_buffer) {
Serhiy Storchaka1180e5a2017-07-11 06:36:46 +03001048 /* XXX Replace PyObject_CheckBuffer with PyBytes_Check in other code
Ville Skyttä49b27342017-08-03 09:00:59 +03001049 after removing support of non-bytes buffer objects. */
Serhiy Storchakad73c3182016-08-06 23:22:08 +03001050 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
1051 "%s%s%s should be %s, not %.200s",
1052 path->function_name ? path->function_name : "",
1053 path->function_name ? ": " : "",
1054 path->argument_name ? path->argument_name : "path",
Brett Cannon3f9183b2016-08-26 14:44:48 -07001055 path->allow_fd && path->nullable ? "string, bytes, os.PathLike, "
1056 "integer or None" :
1057 path->allow_fd ? "string, bytes, os.PathLike or integer" :
1058 path->nullable ? "string, bytes, os.PathLike or None" :
1059 "string, bytes or os.PathLike",
Serhiy Storchakad73c3182016-08-06 23:22:08 +03001060 Py_TYPE(o)->tp_name)) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001061 goto error_exit;
Serhiy Storchakad73c3182016-08-06 23:22:08 +03001062 }
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001063 bytes = PyBytes_FromObject(o);
Larry Hastings9cf065c2012-06-22 16:30:09 -07001064 if (!bytes) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001065 goto error_exit;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001066 }
1067 }
Steve Dowercc16be82016-09-08 10:35:16 -07001068 else if (is_index) {
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001069 if (!_fd_converter(o, &path->fd)) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001070 goto error_exit;
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001071 }
1072 path->wide = NULL;
Steve Dowercc16be82016-09-08 10:35:16 -07001073#ifdef MS_WINDOWS
1074 path->narrow = FALSE;
1075#else
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001076 path->narrow = NULL;
Steve Dowercc16be82016-09-08 10:35:16 -07001077#endif
Xiang Zhang04316c42017-01-08 23:26:57 +08001078 goto success_exit;
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001079 }
1080 else {
Xiang Zhang04316c42017-01-08 23:26:57 +08001081 error_format:
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001082 PyErr_Format(PyExc_TypeError, "%s%s%s should be %s, not %.200s",
1083 path->function_name ? path->function_name : "",
1084 path->function_name ? ": " : "",
1085 path->argument_name ? path->argument_name : "path",
Brett Cannon3f9183b2016-08-26 14:44:48 -07001086 path->allow_fd && path->nullable ? "string, bytes, os.PathLike, "
1087 "integer or None" :
1088 path->allow_fd ? "string, bytes, os.PathLike or integer" :
1089 path->nullable ? "string, bytes, os.PathLike or None" :
1090 "string, bytes or os.PathLike",
Serhiy Storchaka819399b2016-04-06 22:17:52 +03001091 Py_TYPE(o)->tp_name);
Xiang Zhang04316c42017-01-08 23:26:57 +08001092 goto error_exit;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001093 }
1094
Larry Hastings9cf065c2012-06-22 16:30:09 -07001095 length = PyBytes_GET_SIZE(bytes);
Larry Hastings9cf065c2012-06-22 16:30:09 -07001096 narrow = PyBytes_AS_STRING(bytes);
Victor Stinner706768c2014-08-16 01:03:39 +02001097 if ((size_t)length != strlen(narrow)) {
Serhiy Storchakad8a14472014-09-06 20:07:17 +03001098 FORMAT_EXCEPTION(PyExc_ValueError, "embedded null character in %s");
Xiang Zhang04316c42017-01-08 23:26:57 +08001099 goto error_exit;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001100 }
1101
Steve Dowercc16be82016-09-08 10:35:16 -07001102#ifdef MS_WINDOWS
1103 wo = PyUnicode_DecodeFSDefaultAndSize(
1104 narrow,
1105 length
1106 );
1107 if (!wo) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001108 goto error_exit;
Steve Dowercc16be82016-09-08 10:35:16 -07001109 }
1110
Xiang Zhang04316c42017-01-08 23:26:57 +08001111 wide = PyUnicode_AsUnicodeAndSize(wo, &length);
Steve Dowercc16be82016-09-08 10:35:16 -07001112 if (!wide) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001113 goto error_exit;
Steve Dowercc16be82016-09-08 10:35:16 -07001114 }
1115 if (length > 32767) {
1116 FORMAT_EXCEPTION(PyExc_ValueError, "%s too long for Windows");
Xiang Zhang04316c42017-01-08 23:26:57 +08001117 goto error_exit;
Steve Dowercc16be82016-09-08 10:35:16 -07001118 }
1119 if (wcslen(wide) != length) {
1120 FORMAT_EXCEPTION(PyExc_ValueError, "embedded null character in %s");
Xiang Zhang04316c42017-01-08 23:26:57 +08001121 goto error_exit;
Steve Dowercc16be82016-09-08 10:35:16 -07001122 }
1123 path->wide = wide;
1124 path->narrow = TRUE;
Xiang Zhang04316c42017-01-08 23:26:57 +08001125 path->cleanup = wo;
1126 Py_DECREF(bytes);
Steve Dowercc16be82016-09-08 10:35:16 -07001127#else
Larry Hastings9cf065c2012-06-22 16:30:09 -07001128 path->wide = NULL;
1129 path->narrow = narrow;
Serhiy Storchakad73c3182016-08-06 23:22:08 +03001130 if (bytes == o) {
Xiang Zhang04316c42017-01-08 23:26:57 +08001131 /* Still a reference owned by path->object, don't have to
1132 worry about path->narrow is used after free. */
Serhiy Storchakad73c3182016-08-06 23:22:08 +03001133 Py_DECREF(bytes);
Serhiy Storchakad73c3182016-08-06 23:22:08 +03001134 }
1135 else {
1136 path->cleanup = bytes;
Serhiy Storchakad73c3182016-08-06 23:22:08 +03001137 }
Xiang Zhang04316c42017-01-08 23:26:57 +08001138#endif
1139 path->fd = -1;
1140
1141 success_exit:
1142 path->length = length;
1143 path->object = o;
1144 return Py_CLEANUP_SUPPORTED;
1145
1146 error_exit:
1147 Py_XDECREF(o);
1148 Py_XDECREF(bytes);
1149#ifdef MS_WINDOWS
1150 Py_XDECREF(wo);
1151#endif
1152 return 0;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001153}
1154
1155static void
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001156argument_unavailable_error(const char *function_name, const char *argument_name)
1157{
Larry Hastings9cf065c2012-06-22 16:30:09 -07001158 PyErr_Format(PyExc_NotImplementedError,
1159 "%s%s%s unavailable on this platform",
1160 (function_name != NULL) ? function_name : "",
1161 (function_name != NULL) ? ": ": "",
1162 argument_name);
1163}
1164
1165static int
Serhiy Storchakaa2ad5c32013-01-07 23:13:46 +02001166dir_fd_unavailable(PyObject *o, void *p)
1167{
1168 int dir_fd;
1169 if (!dir_fd_converter(o, &dir_fd))
Larry Hastings9cf065c2012-06-22 16:30:09 -07001170 return 0;
Serhiy Storchakaa2ad5c32013-01-07 23:13:46 +02001171 if (dir_fd != DEFAULT_DIR_FD) {
1172 argument_unavailable_error(NULL, "dir_fd");
1173 return 0;
1174 }
1175 *(int *)p = dir_fd;
1176 return 1;
Larry Hastings9cf065c2012-06-22 16:30:09 -07001177}
1178
1179static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001180fd_specified(const char *function_name, int fd)
1181{
Larry Hastings9cf065c2012-06-22 16:30:09 -07001182 if (fd == -1)
1183 return 0;
1184
1185 argument_unavailable_error(function_name, "fd");
1186 return 1;
1187}
1188
1189static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001190follow_symlinks_specified(const char *function_name, int follow_symlinks)
1191{
Larry Hastings9cf065c2012-06-22 16:30:09 -07001192 if (follow_symlinks)
1193 return 0;
1194
1195 argument_unavailable_error(function_name, "follow_symlinks");
1196 return 1;
1197}
1198
1199static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001200path_and_dir_fd_invalid(const char *function_name, path_t *path, int dir_fd)
1201{
Steve Dowercc16be82016-09-08 10:35:16 -07001202 if (!path->wide && (dir_fd != DEFAULT_DIR_FD)
1203#ifndef MS_WINDOWS
1204 && !path->narrow
1205#endif
1206 ) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07001207 PyErr_Format(PyExc_ValueError,
1208 "%s: can't specify dir_fd without matching path",
1209 function_name);
1210 return 1;
1211 }
1212 return 0;
1213}
1214
1215static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001216dir_fd_and_fd_invalid(const char *function_name, int dir_fd, int fd)
1217{
Larry Hastings9cf065c2012-06-22 16:30:09 -07001218 if ((dir_fd != DEFAULT_DIR_FD) && (fd != -1)) {
1219 PyErr_Format(PyExc_ValueError,
1220 "%s: can't specify both dir_fd and fd",
1221 function_name);
1222 return 1;
1223 }
1224 return 0;
1225}
1226
1227static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001228fd_and_follow_symlinks_invalid(const char *function_name, int fd,
1229 int follow_symlinks)
1230{
Larry Hastings9cf065c2012-06-22 16:30:09 -07001231 if ((fd > 0) && (!follow_symlinks)) {
1232 PyErr_Format(PyExc_ValueError,
1233 "%s: cannot use fd and follow_symlinks together",
1234 function_name);
1235 return 1;
1236 }
1237 return 0;
1238}
1239
1240static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001241dir_fd_and_follow_symlinks_invalid(const char *function_name, int dir_fd,
1242 int follow_symlinks)
1243{
Larry Hastings9cf065c2012-06-22 16:30:09 -07001244 if ((dir_fd != DEFAULT_DIR_FD) && (!follow_symlinks)) {
1245 PyErr_Format(PyExc_ValueError,
1246 "%s: cannot use dir_fd and follow_symlinks together",
1247 function_name);
1248 return 1;
1249 }
1250 return 0;
1251}
1252
Larry Hastings2f936352014-08-05 14:04:04 +10001253#ifdef MS_WINDOWS
Benjamin Petersonaf580df2016-09-06 10:46:49 -07001254 typedef long long Py_off_t;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001255#else
Larry Hastings2f936352014-08-05 14:04:04 +10001256 typedef off_t Py_off_t;
1257#endif
1258
1259static int
1260Py_off_t_converter(PyObject *arg, void *addr)
1261{
1262#ifdef HAVE_LARGEFILE_SUPPORT
1263 *((Py_off_t *)addr) = PyLong_AsLongLong(arg);
1264#else
1265 *((Py_off_t *)addr) = PyLong_AsLong(arg);
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001266#endif
1267 if (PyErr_Occurred())
1268 return 0;
1269 return 1;
1270}
Larry Hastings2f936352014-08-05 14:04:04 +10001271
1272static PyObject *
1273PyLong_FromPy_off_t(Py_off_t offset)
1274{
1275#ifdef HAVE_LARGEFILE_SUPPORT
1276 return PyLong_FromLongLong(offset);
1277#else
1278 return PyLong_FromLong(offset);
Ross Lagerwallb1e5d592011-09-19 08:30:43 +02001279#endif
Larry Hastings2f936352014-08-05 14:04:04 +10001280}
1281
Serhiy Storchakad54cfb12018-05-08 07:48:50 +03001282#ifdef HAVE_SIGSET_T
1283/* Convert an iterable of integers to a sigset.
1284 Return 1 on success, return 0 and raise an exception on error. */
1285int
1286_Py_Sigset_Converter(PyObject *obj, void *addr)
1287{
1288 sigset_t *mask = (sigset_t *)addr;
1289 PyObject *iterator, *item;
1290 long signum;
1291 int overflow;
1292
Rémi Lapeyref0900192019-05-04 01:30:53 +02001293 // The extra parens suppress the unreachable-code warning with clang on MacOS
1294 if (sigemptyset(mask) < (0)) {
Serhiy Storchakad54cfb12018-05-08 07:48:50 +03001295 /* Probably only if mask == NULL. */
1296 PyErr_SetFromErrno(PyExc_OSError);
1297 return 0;
1298 }
1299
1300 iterator = PyObject_GetIter(obj);
1301 if (iterator == NULL) {
1302 return 0;
1303 }
1304
1305 while ((item = PyIter_Next(iterator)) != NULL) {
1306 signum = PyLong_AsLongAndOverflow(item, &overflow);
1307 Py_DECREF(item);
1308 if (signum <= 0 || signum >= NSIG) {
1309 if (overflow || signum != -1 || !PyErr_Occurred()) {
1310 PyErr_Format(PyExc_ValueError,
1311 "signal number %ld out of range", signum);
1312 }
1313 goto error;
1314 }
1315 if (sigaddset(mask, (int)signum)) {
1316 if (errno != EINVAL) {
1317 /* Probably impossible */
1318 PyErr_SetFromErrno(PyExc_OSError);
1319 goto error;
1320 }
1321 /* For backwards compatibility, allow idioms such as
1322 * `range(1, NSIG)` but warn about invalid signal numbers
1323 */
1324 const char msg[] =
1325 "invalid signal number %ld, please use valid_signals()";
1326 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1, msg, signum)) {
1327 goto error;
1328 }
1329 }
1330 }
1331 if (!PyErr_Occurred()) {
1332 Py_DECREF(iterator);
1333 return 1;
1334 }
1335
1336error:
1337 Py_DECREF(iterator);
1338 return 0;
1339}
1340#endif /* HAVE_SIGSET_T */
1341
Brian Curtinfc1be6d2010-11-24 13:23:18 +00001342#ifdef MS_WINDOWS
Brian Curtinf5e76d02010-11-24 13:14:05 +00001343
1344static int
Brian Curtind25aef52011-06-13 15:16:04 -05001345win32_get_reparse_tag(HANDLE reparse_point_handle, ULONG *reparse_tag)
Brian Curtinf5e76d02010-11-24 13:14:05 +00001346{
Martin Panter70214ad2016-08-04 02:38:59 +00001347 char target_buffer[_Py_MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
1348 _Py_REPARSE_DATA_BUFFER *rdb = (_Py_REPARSE_DATA_BUFFER *)target_buffer;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001349 DWORD n_bytes_returned;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001350
1351 if (0 == DeviceIoControl(
1352 reparse_point_handle,
1353 FSCTL_GET_REPARSE_POINT,
1354 NULL, 0, /* in buffer */
1355 target_buffer, sizeof(target_buffer),
1356 &n_bytes_returned,
1357 NULL)) /* we're not using OVERLAPPED_IO */
Brian Curtind25aef52011-06-13 15:16:04 -05001358 return FALSE;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001359
1360 if (reparse_tag)
1361 *reparse_tag = rdb->ReparseTag;
1362
Brian Curtind25aef52011-06-13 15:16:04 -05001363 return TRUE;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001364}
Victor Stinner1ab6c2d2011-11-15 22:27:41 +01001365
Brian Curtinfc1be6d2010-11-24 13:23:18 +00001366#endif /* MS_WINDOWS */
Brian Curtinf5e76d02010-11-24 13:14:05 +00001367
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001368/* Return a dictionary corresponding to the POSIX environment table */
Ronald Oussoren697e56d2013-01-25 17:57:13 +01001369#if defined(WITH_NEXT_FRAMEWORK) || (defined(__APPLE__) && defined(Py_ENABLE_SHARED))
Jack Jansenea0c3822002-08-01 21:57:49 +00001370/* On Darwin/MacOSX a shared library or framework has no access to
Ronald Oussoren697e56d2013-01-25 17:57:13 +01001371** environ directly, we must obtain it with _NSGetEnviron(). See also
1372** man environ(7).
Jack Jansenea0c3822002-08-01 21:57:49 +00001373*/
1374#include <crt_externs.h>
1375static char **environ;
pxinwrf2d7ac72019-05-21 18:46:37 +08001376#elif !defined(_MSC_VER) && (!defined(__WATCOMC__) || defined(__QNX__) || defined(__VXWORKS__))
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001377extern char **environ;
Guido van Rossuma4916fa1996-05-23 22:58:55 +00001378#endif /* !_MSC_VER */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001379
Barry Warsaw53699e91996-12-10 23:23:01 +00001380static PyObject *
Thomas Woutersf3f33dc2000-07-21 06:00:07 +00001381convertenviron(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001382{
Victor Stinner8c62be82010-05-06 00:08:46 +00001383 PyObject *d;
Thomas Hellerf78f12a2007-11-08 19:33:05 +00001384#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +00001385 wchar_t **e;
Thomas Hellerf78f12a2007-11-08 19:33:05 +00001386#else
Victor Stinner8c62be82010-05-06 00:08:46 +00001387 char **e;
Thomas Hellerf78f12a2007-11-08 19:33:05 +00001388#endif
Guido van Rossumd48f2521997-12-05 22:19:34 +00001389
Victor Stinner8c62be82010-05-06 00:08:46 +00001390 d = PyDict_New();
1391 if (d == NULL)
1392 return NULL;
Ronald Oussoren697e56d2013-01-25 17:57:13 +01001393#if defined(WITH_NEXT_FRAMEWORK) || (defined(__APPLE__) && defined(Py_ENABLE_SHARED))
Victor Stinner8c62be82010-05-06 00:08:46 +00001394 if (environ == NULL)
1395 environ = *_NSGetEnviron();
1396#endif
1397#ifdef MS_WINDOWS
1398 /* _wenviron must be initialized in this way if the program is started
1399 through main() instead of wmain(). */
1400 _wgetenv(L"");
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001401 e = _wenviron;
Victor Stinner8c62be82010-05-06 00:08:46 +00001402#else
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001403 e = environ;
1404#endif
1405 if (e == NULL)
Victor Stinner8c62be82010-05-06 00:08:46 +00001406 return d;
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001407 for (; *e != NULL; e++) {
Victor Stinner8c62be82010-05-06 00:08:46 +00001408 PyObject *k;
1409 PyObject *v;
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001410#ifdef MS_WINDOWS
1411 const wchar_t *p = wcschr(*e, L'=');
1412#else
Serhiy Storchakadeab18d2016-05-07 16:45:18 +03001413 const char *p = strchr(*e, '=');
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001414#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00001415 if (p == NULL)
1416 continue;
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001417#ifdef MS_WINDOWS
1418 k = PyUnicode_FromWideChar(*e, (Py_ssize_t)(p-*e));
1419#else
Victor Stinner84ae1182010-05-06 22:05:07 +00001420 k = PyBytes_FromStringAndSize(*e, (int)(p-*e));
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001421#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00001422 if (k == NULL) {
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001423 Py_DECREF(d);
1424 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00001425 }
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001426#ifdef MS_WINDOWS
1427 v = PyUnicode_FromWideChar(p+1, wcslen(p+1));
1428#else
Victor Stinner84ae1182010-05-06 22:05:07 +00001429 v = PyBytes_FromStringAndSize(p+1, strlen(p+1));
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001430#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00001431 if (v == NULL) {
Victor Stinner8c62be82010-05-06 00:08:46 +00001432 Py_DECREF(k);
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001433 Py_DECREF(d);
1434 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00001435 }
Serhiy Storchaka6fef0f12018-12-10 12:10:56 +02001436 if (PyDict_GetItemWithError(d, k) == NULL) {
1437 if (PyErr_Occurred() || PyDict_SetItem(d, k, v) != 0) {
1438 Py_DECREF(v);
1439 Py_DECREF(k);
1440 Py_DECREF(d);
1441 return NULL;
1442 }
Victor Stinner8c62be82010-05-06 00:08:46 +00001443 }
1444 Py_DECREF(k);
1445 Py_DECREF(v);
Guido van Rossumd48f2521997-12-05 22:19:34 +00001446 }
Victor Stinner8c62be82010-05-06 00:08:46 +00001447 return d;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001448}
1449
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001450/* Set a POSIX-specific error from errno, and return NULL */
1451
Barry Warsawd58d7641998-07-23 16:14:40 +00001452static PyObject *
Thomas Woutersf3f33dc2000-07-21 06:00:07 +00001453posix_error(void)
Guido van Rossumad0ee831995-03-01 10:34:45 +00001454{
Victor Stinner8c62be82010-05-06 00:08:46 +00001455 return PyErr_SetFromErrno(PyExc_OSError);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001456}
Mark Hammondef8b6542001-05-13 08:04:26 +00001457
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001458#ifdef MS_WINDOWS
Fredrik Lundhffb9c772000-07-09 14:49:51 +00001459static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001460win32_error(const char* function, const char* filename)
Fredrik Lundhffb9c772000-07-09 14:49:51 +00001461{
Victor Stinner8c62be82010-05-06 00:08:46 +00001462 /* XXX We should pass the function name along in the future.
1463 (winreg.c also wants to pass the function name.)
1464 This would however require an additional param to the
1465 Windows error object, which is non-trivial.
1466 */
1467 errno = GetLastError();
1468 if (filename)
1469 return PyErr_SetFromWindowsErrWithFilename(errno, filename);
1470 else
1471 return PyErr_SetFromWindowsErr(errno);
Fredrik Lundhffb9c772000-07-09 14:49:51 +00001472}
Mark Hammondc2e85bd2002-10-03 05:10:39 +00001473
Mark Hammondc2e85bd2002-10-03 05:10:39 +00001474static PyObject *
Steve Dower2438cdf2019-03-29 16:37:16 -07001475win32_error_object_err(const char* function, PyObject* filename, DWORD err)
Victor Stinnereb5657a2011-09-30 01:44:27 +02001476{
1477 /* XXX - see win32_error for comments on 'function' */
Victor Stinnereb5657a2011-09-30 01:44:27 +02001478 if (filename)
1479 return PyErr_SetExcFromWindowsErrWithFilenameObject(
Andrew Svetlov2606a6f2012-12-19 14:33:35 +02001480 PyExc_OSError,
Steve Dower2438cdf2019-03-29 16:37:16 -07001481 err,
Victor Stinnereb5657a2011-09-30 01:44:27 +02001482 filename);
1483 else
Steve Dower2438cdf2019-03-29 16:37:16 -07001484 return PyErr_SetFromWindowsErr(err);
1485}
1486
1487static PyObject *
1488win32_error_object(const char* function, PyObject* filename)
1489{
1490 errno = GetLastError();
1491 return win32_error_object_err(function, filename, errno);
Victor Stinnereb5657a2011-09-30 01:44:27 +02001492}
1493
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00001494#endif /* MS_WINDOWS */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001495
Larry Hastings9cf065c2012-06-22 16:30:09 -07001496static PyObject *
Alexey Izbyshev83460312018-10-20 03:28:22 +03001497posix_path_object_error(PyObject *path)
1498{
1499 return PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, path);
1500}
1501
1502static PyObject *
Serhiy Storchaka2674bc72016-10-08 20:16:57 +03001503path_object_error(PyObject *path)
Larry Hastings9cf065c2012-06-22 16:30:09 -07001504{
1505#ifdef MS_WINDOWS
Serhiy Storchaka2674bc72016-10-08 20:16:57 +03001506 return PyErr_SetExcFromWindowsErrWithFilenameObject(
1507 PyExc_OSError, 0, path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07001508#else
Alexey Izbyshev83460312018-10-20 03:28:22 +03001509 return posix_path_object_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07001510#endif
1511}
1512
Serhiy Storchaka2674bc72016-10-08 20:16:57 +03001513static PyObject *
1514path_object_error2(PyObject *path, PyObject *path2)
1515{
1516#ifdef MS_WINDOWS
1517 return PyErr_SetExcFromWindowsErrWithFilenameObjects(
1518 PyExc_OSError, 0, path, path2);
1519#else
1520 return PyErr_SetFromErrnoWithFilenameObjects(PyExc_OSError, path, path2);
1521#endif
1522}
1523
1524static PyObject *
1525path_error(path_t *path)
1526{
1527 return path_object_error(path->object);
1528}
Larry Hastings31826802013-10-19 00:09:25 -07001529
Larry Hastingsb0827312014-02-09 22:05:19 -08001530static PyObject *
Alexey Izbyshev83460312018-10-20 03:28:22 +03001531posix_path_error(path_t *path)
1532{
1533 return posix_path_object_error(path->object);
1534}
1535
1536static PyObject *
Larry Hastingsb0827312014-02-09 22:05:19 -08001537path_error2(path_t *path, path_t *path2)
1538{
Serhiy Storchaka2674bc72016-10-08 20:16:57 +03001539 return path_object_error2(path->object, path2->object);
Larry Hastingsb0827312014-02-09 22:05:19 -08001540}
1541
1542
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001543/* POSIX generic methods */
1544
Larry Hastings2f936352014-08-05 14:04:04 +10001545static int
1546fildes_converter(PyObject *o, void *p)
Fred Drake4d1e64b2002-04-15 19:40:07 +00001547{
Victor Stinner8c62be82010-05-06 00:08:46 +00001548 int fd;
Larry Hastings2f936352014-08-05 14:04:04 +10001549 int *pointer = (int *)p;
1550 fd = PyObject_AsFileDescriptor(o);
Victor Stinner8c62be82010-05-06 00:08:46 +00001551 if (fd < 0)
Larry Hastings2f936352014-08-05 14:04:04 +10001552 return 0;
Larry Hastings2f936352014-08-05 14:04:04 +10001553 *pointer = fd;
1554 return 1;
1555}
1556
1557static PyObject *
1558posix_fildes_fd(int fd, int (*func)(int))
1559{
1560 int res;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00001561 int async_err = 0;
1562
1563 do {
1564 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04001565 _Py_BEGIN_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00001566 res = (*func)(fd);
Steve Dower8fc89802015-04-12 00:26:27 -04001567 _Py_END_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00001568 Py_END_ALLOW_THREADS
1569 } while (res != 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
1570 if (res != 0)
1571 return (!async_err) ? posix_error() : NULL;
1572 Py_RETURN_NONE;
Fred Drake4d1e64b2002-04-15 19:40:07 +00001573}
Guido van Rossum21142a01999-01-08 21:05:37 +00001574
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001575
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00001576#ifdef MS_WINDOWS
Thomas Wouters477c8d52006-05-27 19:21:47 +00001577/* This is a reimplementation of the C library's chdir function,
1578 but one that produces Win32 errors instead of DOS error codes.
1579 chdir is essentially a wrapper around SetCurrentDirectory; however,
1580 it also needs to set "magic" environment variables indicating
1581 the per-drive current directory, which are of the form =<drive>: */
Benjamin Peterson206e3072008-10-19 14:07:49 +00001582static BOOL __stdcall
Thomas Wouters477c8d52006-05-27 19:21:47 +00001583win32_wchdir(LPCWSTR path)
1584{
Victor Stinnered537822015-12-13 21:40:26 +01001585 wchar_t path_buf[MAX_PATH], *new_path = path_buf;
Victor Stinner8c62be82010-05-06 00:08:46 +00001586 int result;
1587 wchar_t env[4] = L"=x:";
Thomas Wouters477c8d52006-05-27 19:21:47 +00001588
Victor Stinner8c62be82010-05-06 00:08:46 +00001589 if(!SetCurrentDirectoryW(path))
1590 return FALSE;
Victor Stinnered537822015-12-13 21:40:26 +01001591 result = GetCurrentDirectoryW(Py_ARRAY_LENGTH(path_buf), new_path);
Victor Stinner8c62be82010-05-06 00:08:46 +00001592 if (!result)
1593 return FALSE;
Victor Stinnere847d712015-12-14 00:21:50 +01001594 if (result > Py_ARRAY_LENGTH(path_buf)) {
Victor Stinnerb6404912013-07-07 16:21:41 +02001595 new_path = PyMem_RawMalloc(result * sizeof(wchar_t));
Victor Stinner8c62be82010-05-06 00:08:46 +00001596 if (!new_path) {
1597 SetLastError(ERROR_OUTOFMEMORY);
1598 return FALSE;
1599 }
1600 result = GetCurrentDirectoryW(result, new_path);
1601 if (!result) {
Victor Stinnerb6404912013-07-07 16:21:41 +02001602 PyMem_RawFree(new_path);
Victor Stinner8c62be82010-05-06 00:08:46 +00001603 return FALSE;
1604 }
1605 }
Alexey Izbyshev3e197c72018-03-01 12:13:56 +03001606 int is_unc_like_path = (wcsncmp(new_path, L"\\\\", 2) == 0 ||
1607 wcsncmp(new_path, L"//", 2) == 0);
1608 if (!is_unc_like_path) {
1609 env[1] = new_path[0];
1610 result = SetEnvironmentVariableW(env, new_path);
1611 }
Victor Stinnered537822015-12-13 21:40:26 +01001612 if (new_path != path_buf)
Victor Stinnerb6404912013-07-07 16:21:41 +02001613 PyMem_RawFree(new_path);
Alexey Izbyshev3e197c72018-03-01 12:13:56 +03001614 return result ? TRUE : FALSE;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001615}
1616#endif
1617
Martin v. Löwis14694662006-02-03 12:54:16 +00001618#ifdef MS_WINDOWS
1619/* The CRT of Windows has a number of flaws wrt. its stat() implementation:
1620 - time stamps are restricted to second resolution
1621 - file modification times suffer from forth-and-back conversions between
1622 UTC and local time
1623 Therefore, we implement our own stat, based on the Win32 API directly.
1624*/
Victor Stinner8c62be82010-05-06 00:08:46 +00001625#define HAVE_STAT_NSEC 1
Zachary Ware63f277b2014-06-19 09:46:37 -05001626#define HAVE_STRUCT_STAT_ST_FILE_ATTRIBUTES 1
Steve Dower9eb3d542019-08-21 15:52:42 -07001627#define HAVE_STRUCT_STAT_ST_REPARSE_TAG 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 int
Steve Dowercc16be82016-09-08 10:35:16 -07001662win32_xstat_impl(const wchar_t *path, struct _Py_stat_struct *result,
Brian Curtind25aef52011-06-13 15:16:04 -05001663 BOOL traverse)
1664{
Steve Dower9eb3d542019-08-21 15:52:42 -07001665 HANDLE hFile;
1666 BY_HANDLE_FILE_INFORMATION fileInfo;
1667 FILE_ATTRIBUTE_TAG_INFO tagInfo = { 0 };
1668 DWORD fileType, error;
1669 BOOL isUnhandledTag = FALSE;
1670 int retval = 0;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001671
Steve Dower9eb3d542019-08-21 15:52:42 -07001672 DWORD access = FILE_READ_ATTRIBUTES;
1673 DWORD flags = FILE_FLAG_BACKUP_SEMANTICS; /* Allow opening directories. */
1674 if (!traverse) {
1675 flags |= FILE_FLAG_OPEN_REPARSE_POINT;
1676 }
Brian Curtinf5e76d02010-11-24 13:14:05 +00001677
Steve Dower9eb3d542019-08-21 15:52:42 -07001678 hFile = CreateFileW(path, access, 0, NULL, OPEN_EXISTING, flags, NULL);
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001679 if (hFile == INVALID_HANDLE_VALUE) {
Steve Dower9eb3d542019-08-21 15:52:42 -07001680 /* Either the path doesn't exist, or the caller lacks access. */
1681 error = GetLastError();
1682 switch (error) {
1683 case ERROR_ACCESS_DENIED: /* Cannot sync or read attributes. */
1684 case ERROR_SHARING_VIOLATION: /* It's a paging file. */
1685 /* Try reading the parent directory. */
1686 if (!attributes_from_dir(path, &fileInfo, &tagInfo.ReparseTag)) {
1687 /* Cannot read the parent directory. */
1688 SetLastError(error);
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001689 return -1;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001690 }
Steve Dower9eb3d542019-08-21 15:52:42 -07001691 if (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1692 if (traverse ||
1693 !IsReparseTagNameSurrogate(tagInfo.ReparseTag)) {
1694 /* The stat call has to traverse but cannot, so fail. */
1695 SetLastError(error);
Brian Curtind25aef52011-06-13 15:16:04 -05001696 return -1;
Mark Becwarb82bfac2019-02-02 16:08:23 -05001697 }
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001698 }
Steve Dower9eb3d542019-08-21 15:52:42 -07001699 break;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001700
Steve Dower9eb3d542019-08-21 15:52:42 -07001701 case ERROR_INVALID_PARAMETER:
1702 /* \\.\con requires read or write access. */
1703 hFile = CreateFileW(path, access | GENERIC_READ,
1704 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
1705 OPEN_EXISTING, flags, NULL);
1706 if (hFile == INVALID_HANDLE_VALUE) {
1707 SetLastError(error);
1708 return -1;
1709 }
1710 break;
1711
1712 case ERROR_CANT_ACCESS_FILE:
1713 /* bpo37834: open unhandled reparse points if traverse fails. */
1714 if (traverse) {
1715 traverse = FALSE;
1716 isUnhandledTag = TRUE;
1717 hFile = CreateFileW(path, access, 0, NULL, OPEN_EXISTING,
1718 flags | FILE_FLAG_OPEN_REPARSE_POINT, NULL);
1719 }
1720 if (hFile == INVALID_HANDLE_VALUE) {
1721 SetLastError(error);
1722 return -1;
1723 }
1724 break;
1725
1726 default:
1727 return -1;
1728 }
Brian Curtinf5e76d02010-11-24 13:14:05 +00001729 }
Steve Dower9eb3d542019-08-21 15:52:42 -07001730
1731 if (hFile != INVALID_HANDLE_VALUE) {
1732 /* Handle types other than files on disk. */
1733 fileType = GetFileType(hFile);
1734 if (fileType != FILE_TYPE_DISK) {
1735 if (fileType == FILE_TYPE_UNKNOWN && GetLastError() != 0) {
1736 retval = -1;
1737 goto cleanup;
1738 }
1739 DWORD fileAttributes = GetFileAttributesW(path);
1740 memset(result, 0, sizeof(*result));
1741 if (fileAttributes != INVALID_FILE_ATTRIBUTES &&
1742 fileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
1743 /* \\.\pipe\ or \\.\mailslot\ */
1744 result->st_mode = _S_IFDIR;
1745 } else if (fileType == FILE_TYPE_CHAR) {
1746 /* \\.\nul */
1747 result->st_mode = _S_IFCHR;
1748 } else if (fileType == FILE_TYPE_PIPE) {
1749 /* \\.\pipe\spam */
1750 result->st_mode = _S_IFIFO;
1751 }
1752 /* FILE_TYPE_UNKNOWN, e.g. \\.\mailslot\waitfor.exe\spam */
1753 goto cleanup;
1754 }
1755
1756 /* Query the reparse tag, and traverse a non-link. */
1757 if (!traverse) {
1758 if (!GetFileInformationByHandleEx(hFile, FileAttributeTagInfo,
1759 &tagInfo, sizeof(tagInfo))) {
1760 /* Allow devices that do not support FileAttributeTagInfo. */
1761 switch (GetLastError()) {
1762 case ERROR_INVALID_PARAMETER:
1763 case ERROR_INVALID_FUNCTION:
1764 case ERROR_NOT_SUPPORTED:
1765 tagInfo.FileAttributes = FILE_ATTRIBUTE_NORMAL;
1766 tagInfo.ReparseTag = 0;
1767 break;
1768 default:
1769 retval = -1;
1770 goto cleanup;
1771 }
1772 } else if (tagInfo.FileAttributes &
1773 FILE_ATTRIBUTE_REPARSE_POINT) {
1774 if (IsReparseTagNameSurrogate(tagInfo.ReparseTag)) {
1775 if (isUnhandledTag) {
1776 /* Traversing previously failed for either this link
1777 or its target. */
1778 SetLastError(ERROR_CANT_ACCESS_FILE);
1779 retval = -1;
1780 goto cleanup;
1781 }
1782 /* Traverse a non-link, but not if traversing already failed
1783 for an unhandled tag. */
1784 } else if (!isUnhandledTag) {
1785 CloseHandle(hFile);
1786 return win32_xstat_impl(path, result, TRUE);
1787 }
1788 }
1789 }
1790
1791 if (!GetFileInformationByHandle(hFile, &fileInfo)) {
1792 switch (GetLastError()) {
1793 case ERROR_INVALID_PARAMETER:
1794 case ERROR_INVALID_FUNCTION:
1795 case ERROR_NOT_SUPPORTED:
1796 retval = -1;
1797 goto cleanup;
1798 }
1799 /* Volumes and physical disks are block devices, e.g.
1800 \\.\C: and \\.\PhysicalDrive0. */
1801 memset(result, 0, sizeof(*result));
1802 result->st_mode = 0x6000; /* S_IFBLK */
1803 goto cleanup;
1804 }
1805 }
1806
1807 _Py_attribute_data_to_stat(&fileInfo, tagInfo.ReparseTag, result);
1808
1809 if (!(fileInfo.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
1810 /* Fix the file execute permissions. This hack sets S_IEXEC if
1811 the filename has an extension that is commonly used by files
1812 that CreateProcessW can execute. A real implementation calls
1813 GetSecurityInfo, OpenThreadToken/OpenProcessToken, and
1814 AccessCheck to check for generic read, write, and execute
1815 access. */
1816 const wchar_t *fileExtension = wcsrchr(path, '.');
1817 if (fileExtension) {
1818 if (_wcsicmp(fileExtension, L".exe") == 0 ||
1819 _wcsicmp(fileExtension, L".bat") == 0 ||
1820 _wcsicmp(fileExtension, L".cmd") == 0 ||
1821 _wcsicmp(fileExtension, L".com") == 0) {
1822 result->st_mode |= 0111;
1823 }
1824 }
1825 }
1826
1827cleanup:
1828 if (hFile != INVALID_HANDLE_VALUE) {
1829 CloseHandle(hFile);
1830 }
1831
1832 return retval;
Brian Curtinf5e76d02010-11-24 13:14:05 +00001833}
1834
1835static int
Steve Dowercc16be82016-09-08 10:35:16 -07001836win32_xstat(const wchar_t *path, struct _Py_stat_struct *result, BOOL traverse)
Brian Curtinf5e76d02010-11-24 13:14:05 +00001837{
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001838 /* Protocol violation: we explicitly clear errno, instead of
1839 setting it to a POSIX error. Callers should use GetLastError. */
Brian Curtind25aef52011-06-13 15:16:04 -05001840 int code = win32_xstat_impl(path, result, traverse);
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001841 errno = 0;
1842 return code;
1843}
Brian Curtind25aef52011-06-13 15:16:04 -05001844/* About the following functions: win32_lstat_w, win32_stat, win32_stat_w
Brian Curtind40e6f72010-07-08 21:39:08 +00001845
1846 In Posix, stat automatically traverses symlinks and returns the stat
1847 structure for the target. In Windows, the equivalent GetFileAttributes by
1848 default does not traverse symlinks and instead returns attributes for
1849 the symlink.
1850
Steve Dower9eb3d542019-08-21 15:52:42 -07001851 Instead, we will open the file (which *does* traverse symlinks by default)
1852 and GetFileInformationByHandle(). */
Brian Curtind40e6f72010-07-08 21:39:08 +00001853
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001854static int
Steve Dowercc16be82016-09-08 10:35:16 -07001855win32_lstat(const wchar_t* path, struct _Py_stat_struct *result)
Martin v. Löwis14694662006-02-03 12:54:16 +00001856{
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001857 return win32_xstat(path, result, FALSE);
Martin v. Löwis14694662006-02-03 12:54:16 +00001858}
1859
Victor Stinner8c62be82010-05-06 00:08:46 +00001860static int
Steve Dowercc16be82016-09-08 10:35:16 -07001861win32_stat(const wchar_t* path, struct _Py_stat_struct *result)
Brian Curtind40e6f72010-07-08 21:39:08 +00001862{
Hirokazu Yamamoto427d3142010-12-04 10:16:05 +00001863 return win32_xstat(path, result, TRUE);
Brian Curtind40e6f72010-07-08 21:39:08 +00001864}
1865
Martin v. Löwis14694662006-02-03 12:54:16 +00001866#endif /* MS_WINDOWS */
1867
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001868PyDoc_STRVAR(stat_result__doc__,
Larry Hastings9cf065c2012-06-22 16:30:09 -07001869"stat_result: Result from stat, fstat, or lstat.\n\n\
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001870This object may be accessed either as a tuple of\n\
Fred Drakef7ce04d2002-06-20 18:31:21 +00001871 (mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime)\n\
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001872or via the attributes st_mode, st_ino, st_dev, st_nlink, st_uid, and so on.\n\
1873\n\
Hye-Shik Chang5f937a72005-06-02 13:09:30 +00001874Posix/windows: If your platform supports st_blksize, st_blocks, st_rdev,\n\
1875or st_flags, they are available as attributes only.\n\
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001876\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001877See os.stat for more information.");
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001878
1879static PyStructSequence_Field stat_result_fields[] = {
Victor Stinner8c62be82010-05-06 00:08:46 +00001880 {"st_mode", "protection bits"},
1881 {"st_ino", "inode"},
1882 {"st_dev", "device"},
1883 {"st_nlink", "number of hard links"},
1884 {"st_uid", "user ID of owner"},
1885 {"st_gid", "group ID of owner"},
1886 {"st_size", "total size, in bytes"},
1887 /* The NULL is replaced with PyStructSequence_UnnamedField later. */
1888 {NULL, "integer time of last access"},
1889 {NULL, "integer time of last modification"},
1890 {NULL, "integer time of last change"},
1891 {"st_atime", "time of last access"},
1892 {"st_mtime", "time of last modification"},
1893 {"st_ctime", "time of last change"},
Larry Hastings6fe20b32012-04-19 15:07:49 -07001894 {"st_atime_ns", "time of last access in nanoseconds"},
1895 {"st_mtime_ns", "time of last modification in nanoseconds"},
1896 {"st_ctime_ns", "time of last change in nanoseconds"},
Martin v. Löwis60a5d722002-10-16 20:28:25 +00001897#ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
Victor Stinner8c62be82010-05-06 00:08:46 +00001898 {"st_blksize", "blocksize for filesystem I/O"},
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001899#endif
Martin v. Löwis60a5d722002-10-16 20:28:25 +00001900#ifdef HAVE_STRUCT_STAT_ST_BLOCKS
Victor Stinner8c62be82010-05-06 00:08:46 +00001901 {"st_blocks", "number of blocks allocated"},
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001902#endif
Martin v. Löwis60a5d722002-10-16 20:28:25 +00001903#ifdef HAVE_STRUCT_STAT_ST_RDEV
Victor Stinner8c62be82010-05-06 00:08:46 +00001904 {"st_rdev", "device type (if inode device)"},
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001905#endif
Hye-Shik Chang5f937a72005-06-02 13:09:30 +00001906#ifdef HAVE_STRUCT_STAT_ST_FLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +00001907 {"st_flags", "user defined flags for file"},
Hye-Shik Chang5f937a72005-06-02 13:09:30 +00001908#endif
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00001909#ifdef HAVE_STRUCT_STAT_ST_GEN
Victor Stinner8c62be82010-05-06 00:08:46 +00001910 {"st_gen", "generation number"},
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00001911#endif
1912#ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME
Victor Stinner8c62be82010-05-06 00:08:46 +00001913 {"st_birthtime", "time of creation"},
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00001914#endif
Zachary Ware63f277b2014-06-19 09:46:37 -05001915#ifdef HAVE_STRUCT_STAT_ST_FILE_ATTRIBUTES
1916 {"st_file_attributes", "Windows file attribute bits"},
1917#endif
jcea6c51d512018-01-28 14:00:08 +01001918#ifdef HAVE_STRUCT_STAT_ST_FSTYPE
1919 {"st_fstype", "Type of filesystem"},
1920#endif
Steve Dower9eb3d542019-08-21 15:52:42 -07001921#ifdef HAVE_STRUCT_STAT_ST_REPARSE_TAG
1922 {"st_reparse_tag", "Windows reparse tag"},
1923#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00001924 {0}
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001925};
1926
Martin v. Löwis60a5d722002-10-16 20:28:25 +00001927#ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
Larry Hastings6fe20b32012-04-19 15:07:49 -07001928#define ST_BLKSIZE_IDX 16
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001929#else
Larry Hastings6fe20b32012-04-19 15:07:49 -07001930#define ST_BLKSIZE_IDX 15
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001931#endif
1932
Martin v. Löwis60a5d722002-10-16 20:28:25 +00001933#ifdef HAVE_STRUCT_STAT_ST_BLOCKS
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001934#define ST_BLOCKS_IDX (ST_BLKSIZE_IDX+1)
1935#else
1936#define ST_BLOCKS_IDX ST_BLKSIZE_IDX
1937#endif
1938
Martin v. Löwis60a5d722002-10-16 20:28:25 +00001939#ifdef HAVE_STRUCT_STAT_ST_RDEV
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001940#define ST_RDEV_IDX (ST_BLOCKS_IDX+1)
1941#else
1942#define ST_RDEV_IDX ST_BLOCKS_IDX
1943#endif
1944
Hye-Shik Chang5f937a72005-06-02 13:09:30 +00001945#ifdef HAVE_STRUCT_STAT_ST_FLAGS
1946#define ST_FLAGS_IDX (ST_RDEV_IDX+1)
1947#else
1948#define ST_FLAGS_IDX ST_RDEV_IDX
1949#endif
1950
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00001951#ifdef HAVE_STRUCT_STAT_ST_GEN
Martin v. Löwisf09582e2005-08-14 21:42:34 +00001952#define ST_GEN_IDX (ST_FLAGS_IDX+1)
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00001953#else
Martin v. Löwisf09582e2005-08-14 21:42:34 +00001954#define ST_GEN_IDX ST_FLAGS_IDX
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00001955#endif
1956
1957#ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME
1958#define ST_BIRTHTIME_IDX (ST_GEN_IDX+1)
1959#else
1960#define ST_BIRTHTIME_IDX ST_GEN_IDX
1961#endif
1962
Zachary Ware63f277b2014-06-19 09:46:37 -05001963#ifdef HAVE_STRUCT_STAT_ST_FILE_ATTRIBUTES
1964#define ST_FILE_ATTRIBUTES_IDX (ST_BIRTHTIME_IDX+1)
1965#else
1966#define ST_FILE_ATTRIBUTES_IDX ST_BIRTHTIME_IDX
1967#endif
1968
jcea6c51d512018-01-28 14:00:08 +01001969#ifdef HAVE_STRUCT_STAT_ST_FSTYPE
1970#define ST_FSTYPE_IDX (ST_FILE_ATTRIBUTES_IDX+1)
1971#else
1972#define ST_FSTYPE_IDX ST_FILE_ATTRIBUTES_IDX
1973#endif
1974
Steve Dower9eb3d542019-08-21 15:52:42 -07001975#ifdef HAVE_STRUCT_STAT_ST_REPARSE_TAG
1976#define ST_REPARSE_TAG_IDX (ST_FSTYPE_IDX+1)
1977#else
1978#define ST_REPARSE_TAG_IDX ST_FSTYPE_IDX
1979#endif
1980
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001981static PyStructSequence_Desc stat_result_desc = {
Victor Stinner8c62be82010-05-06 00:08:46 +00001982 "stat_result", /* name */
1983 stat_result__doc__, /* doc */
1984 stat_result_fields,
1985 10
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001986};
1987
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001988PyDoc_STRVAR(statvfs_result__doc__,
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001989"statvfs_result: Result from statvfs or fstatvfs.\n\n\
1990This object may be accessed either as a tuple of\n\
Fred Drakef7ce04d2002-06-20 18:31:21 +00001991 (bsize, frsize, blocks, bfree, bavail, files, ffree, favail, flag, namemax),\n\
Guido van Rossuma4dc73e2001-10-18 20:53:15 +00001992or via the attributes f_bsize, f_frsize, f_blocks, f_bfree, and so on.\n\
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001993\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001994See os.statvfs for more information.");
Guido van Rossum98bf58f2001-10-18 20:34:25 +00001995
1996static PyStructSequence_Field statvfs_result_fields[] = {
Victor Stinner8c62be82010-05-06 00:08:46 +00001997 {"f_bsize", },
1998 {"f_frsize", },
1999 {"f_blocks", },
2000 {"f_bfree", },
2001 {"f_bavail", },
2002 {"f_files", },
2003 {"f_ffree", },
2004 {"f_favail", },
2005 {"f_flag", },
2006 {"f_namemax",},
Giuseppe Scrivano96a5e502017-12-14 23:46:46 +01002007 {"f_fsid", },
Victor Stinner8c62be82010-05-06 00:08:46 +00002008 {0}
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002009};
2010
2011static PyStructSequence_Desc statvfs_result_desc = {
Victor Stinner8c62be82010-05-06 00:08:46 +00002012 "statvfs_result", /* name */
2013 statvfs_result__doc__, /* doc */
2014 statvfs_result_fields,
2015 10
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002016};
2017
Ross Lagerwall7807c352011-03-17 20:20:30 +02002018#if defined(HAVE_WAITID) && !defined(__APPLE__)
2019PyDoc_STRVAR(waitid_result__doc__,
2020"waitid_result: Result from waitid.\n\n\
2021This object may be accessed either as a tuple of\n\
2022 (si_pid, si_uid, si_signo, si_status, si_code),\n\
2023or via the attributes si_pid, si_uid, and so on.\n\
2024\n\
2025See os.waitid for more information.");
2026
2027static PyStructSequence_Field waitid_result_fields[] = {
2028 {"si_pid", },
2029 {"si_uid", },
2030 {"si_signo", },
2031 {"si_status", },
2032 {"si_code", },
2033 {0}
2034};
2035
2036static PyStructSequence_Desc waitid_result_desc = {
2037 "waitid_result", /* name */
2038 waitid_result__doc__, /* doc */
2039 waitid_result_fields,
2040 5
2041};
Eddie Elizondo474eedf2018-11-13 04:09:31 -08002042static PyTypeObject* WaitidResultType;
Ross Lagerwall7807c352011-03-17 20:20:30 +02002043#endif
2044
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002045static int initialized;
Eddie Elizondo474eedf2018-11-13 04:09:31 -08002046static PyTypeObject* StatResultType;
2047static PyTypeObject* StatVFSResultType;
William Orr81574b82018-10-01 22:19:56 -07002048#if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
Eddie Elizondo474eedf2018-11-13 04:09:31 -08002049static PyTypeObject* SchedParamType;
Benjamin Petersonbad9c2f2011-08-02 18:42:14 -05002050#endif
Martin v. Löwisf607bda2002-10-16 18:27:39 +00002051static newfunc structseq_new;
2052
2053static PyObject *
2054statresult_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2055{
Victor Stinner8c62be82010-05-06 00:08:46 +00002056 PyStructSequence *result;
2057 int i;
Martin v. Löwisf607bda2002-10-16 18:27:39 +00002058
Victor Stinner8c62be82010-05-06 00:08:46 +00002059 result = (PyStructSequence*)structseq_new(type, args, kwds);
2060 if (!result)
2061 return NULL;
2062 /* If we have been initialized from a tuple,
2063 st_?time might be set to None. Initialize it
2064 from the int slots. */
2065 for (i = 7; i <= 9; i++) {
2066 if (result->ob_item[i+3] == Py_None) {
2067 Py_DECREF(Py_None);
2068 Py_INCREF(result->ob_item[i]);
2069 result->ob_item[i+3] = result->ob_item[i];
2070 }
2071 }
2072 return (PyObject*)result;
Martin v. Löwisf607bda2002-10-16 18:27:39 +00002073}
2074
2075
Larry Hastings6fe20b32012-04-19 15:07:49 -07002076static PyObject *billion = NULL;
2077
Martin v. Löwis94717ed2002-09-09 14:24:16 +00002078static void
Victor Stinner4195b5c2012-02-08 23:03:19 +01002079fill_time(PyObject *v, int index, time_t sec, unsigned long nsec)
Martin v. Löwis94717ed2002-09-09 14:24:16 +00002080{
Larry Hastings6fe20b32012-04-19 15:07:49 -07002081 PyObject *s = _PyLong_FromTime_t(sec);
2082 PyObject *ns_fractional = PyLong_FromUnsignedLong(nsec);
2083 PyObject *s_in_ns = NULL;
2084 PyObject *ns_total = NULL;
2085 PyObject *float_s = NULL;
2086
2087 if (!(s && ns_fractional))
2088 goto exit;
2089
2090 s_in_ns = PyNumber_Multiply(s, billion);
2091 if (!s_in_ns)
2092 goto exit;
2093
2094 ns_total = PyNumber_Add(s_in_ns, ns_fractional);
2095 if (!ns_total)
2096 goto exit;
2097
Victor Stinner01b5aab2017-10-24 02:02:00 -07002098 float_s = PyFloat_FromDouble(sec + 1e-9*nsec);
2099 if (!float_s) {
2100 goto exit;
Larry Hastings6fe20b32012-04-19 15:07:49 -07002101 }
2102
2103 PyStructSequence_SET_ITEM(v, index, s);
2104 PyStructSequence_SET_ITEM(v, index+3, float_s);
2105 PyStructSequence_SET_ITEM(v, index+6, ns_total);
2106 s = NULL;
2107 float_s = NULL;
2108 ns_total = NULL;
2109exit:
2110 Py_XDECREF(s);
2111 Py_XDECREF(ns_fractional);
2112 Py_XDECREF(s_in_ns);
2113 Py_XDECREF(ns_total);
2114 Py_XDECREF(float_s);
Martin v. Löwis94717ed2002-09-09 14:24:16 +00002115}
2116
Tim Peters5aa91602002-01-30 05:46:57 +00002117/* pack a system stat C structure into the Python stat tuple
Fred Drake699f3522000-06-29 21:12:41 +00002118 (used by posix_stat() and posix_fstat()) */
2119static PyObject*
Victor Stinner4195b5c2012-02-08 23:03:19 +01002120_pystat_fromstructstat(STRUCT_STAT *st)
Fred Drake699f3522000-06-29 21:12:41 +00002121{
Victor Stinner8c62be82010-05-06 00:08:46 +00002122 unsigned long ansec, mnsec, cnsec;
Eddie Elizondo474eedf2018-11-13 04:09:31 -08002123 PyObject *v = PyStructSequence_New(StatResultType);
Victor Stinner8c62be82010-05-06 00:08:46 +00002124 if (v == NULL)
2125 return NULL;
Fred Drake699f3522000-06-29 21:12:41 +00002126
Victor Stinner8c62be82010-05-06 00:08:46 +00002127 PyStructSequence_SET_ITEM(v, 0, PyLong_FromLong((long)st->st_mode));
Victor Stinner0f6d7332017-03-09 17:34:28 +01002128 Py_BUILD_ASSERT(sizeof(unsigned long long) >= sizeof(st->st_ino));
xdegaye50e86032017-05-22 11:15:08 +02002129 PyStructSequence_SET_ITEM(v, 1, PyLong_FromUnsignedLongLong(st->st_ino));
Serhiy Storchaka404fa922013-01-02 18:22:23 +02002130#ifdef MS_WINDOWS
2131 PyStructSequence_SET_ITEM(v, 2, PyLong_FromUnsignedLong(st->st_dev));
Fred Drake699f3522000-06-29 21:12:41 +00002132#else
Serhiy Storchakab2653b32015-01-18 11:12:11 +02002133 PyStructSequence_SET_ITEM(v, 2, _PyLong_FromDev(st->st_dev));
Fred Drake699f3522000-06-29 21:12:41 +00002134#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00002135 PyStructSequence_SET_ITEM(v, 3, PyLong_FromLong((long)st->st_nlink));
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02002136#if defined(MS_WINDOWS)
2137 PyStructSequence_SET_ITEM(v, 4, PyLong_FromLong(0));
2138 PyStructSequence_SET_ITEM(v, 5, PyLong_FromLong(0));
2139#else
2140 PyStructSequence_SET_ITEM(v, 4, _PyLong_FromUid(st->st_uid));
2141 PyStructSequence_SET_ITEM(v, 5, _PyLong_FromGid(st->st_gid));
2142#endif
xdegaye50e86032017-05-22 11:15:08 +02002143 Py_BUILD_ASSERT(sizeof(long long) >= sizeof(st->st_size));
2144 PyStructSequence_SET_ITEM(v, 6, PyLong_FromLongLong(st->st_size));
Martin v. Löwis94717ed2002-09-09 14:24:16 +00002145
Martin v. Löwis14694662006-02-03 12:54:16 +00002146#if defined(HAVE_STAT_TV_NSEC)
Victor Stinner8c62be82010-05-06 00:08:46 +00002147 ansec = st->st_atim.tv_nsec;
2148 mnsec = st->st_mtim.tv_nsec;
2149 cnsec = st->st_ctim.tv_nsec;
Martin v. Löwis14694662006-02-03 12:54:16 +00002150#elif defined(HAVE_STAT_TV_NSEC2)
Victor Stinner8c62be82010-05-06 00:08:46 +00002151 ansec = st->st_atimespec.tv_nsec;
2152 mnsec = st->st_mtimespec.tv_nsec;
2153 cnsec = st->st_ctimespec.tv_nsec;
Martin v. Löwis14694662006-02-03 12:54:16 +00002154#elif defined(HAVE_STAT_NSEC)
Victor Stinner8c62be82010-05-06 00:08:46 +00002155 ansec = st->st_atime_nsec;
2156 mnsec = st->st_mtime_nsec;
2157 cnsec = st->st_ctime_nsec;
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002158#else
Victor Stinner8c62be82010-05-06 00:08:46 +00002159 ansec = mnsec = cnsec = 0;
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002160#endif
Victor Stinner4195b5c2012-02-08 23:03:19 +01002161 fill_time(v, 7, st->st_atime, ansec);
2162 fill_time(v, 8, st->st_mtime, mnsec);
2163 fill_time(v, 9, st->st_ctime, cnsec);
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002164
Martin v. Löwis60a5d722002-10-16 20:28:25 +00002165#ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
Victor Stinner8c62be82010-05-06 00:08:46 +00002166 PyStructSequence_SET_ITEM(v, ST_BLKSIZE_IDX,
2167 PyLong_FromLong((long)st->st_blksize));
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002168#endif
Martin v. Löwis60a5d722002-10-16 20:28:25 +00002169#ifdef HAVE_STRUCT_STAT_ST_BLOCKS
Victor Stinner8c62be82010-05-06 00:08:46 +00002170 PyStructSequence_SET_ITEM(v, ST_BLOCKS_IDX,
2171 PyLong_FromLong((long)st->st_blocks));
Guido van Rossum98bf58f2001-10-18 20:34:25 +00002172#endif
Martin v. Löwis60a5d722002-10-16 20:28:25 +00002173#ifdef HAVE_STRUCT_STAT_ST_RDEV
Victor Stinner8c62be82010-05-06 00:08:46 +00002174 PyStructSequence_SET_ITEM(v, ST_RDEV_IDX,
2175 PyLong_FromLong((long)st->st_rdev));
Fred Drake699f3522000-06-29 21:12:41 +00002176#endif
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002177#ifdef HAVE_STRUCT_STAT_ST_GEN
Victor Stinner8c62be82010-05-06 00:08:46 +00002178 PyStructSequence_SET_ITEM(v, ST_GEN_IDX,
2179 PyLong_FromLong((long)st->st_gen));
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002180#endif
2181#ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME
Victor Stinner8c62be82010-05-06 00:08:46 +00002182 {
Victor Stinner4195b5c2012-02-08 23:03:19 +01002183 PyObject *val;
2184 unsigned long bsec,bnsec;
2185 bsec = (long)st->st_birthtime;
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002186#ifdef HAVE_STAT_TV_NSEC2
Victor Stinner4195b5c2012-02-08 23:03:19 +01002187 bnsec = st->st_birthtimespec.tv_nsec;
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002188#else
Victor Stinner4195b5c2012-02-08 23:03:19 +01002189 bnsec = 0;
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002190#endif
Victor Stinner01b5aab2017-10-24 02:02:00 -07002191 val = PyFloat_FromDouble(bsec + 1e-9*bnsec);
Victor Stinner4195b5c2012-02-08 23:03:19 +01002192 PyStructSequence_SET_ITEM(v, ST_BIRTHTIME_IDX,
2193 val);
Victor Stinner8c62be82010-05-06 00:08:46 +00002194 }
Martin v. Löwisebd9d5b2005-08-09 15:00:59 +00002195#endif
Hye-Shik Chang5f937a72005-06-02 13:09:30 +00002196#ifdef HAVE_STRUCT_STAT_ST_FLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +00002197 PyStructSequence_SET_ITEM(v, ST_FLAGS_IDX,
2198 PyLong_FromLong((long)st->st_flags));
Hye-Shik Chang5f937a72005-06-02 13:09:30 +00002199#endif
Zachary Ware63f277b2014-06-19 09:46:37 -05002200#ifdef HAVE_STRUCT_STAT_ST_FILE_ATTRIBUTES
2201 PyStructSequence_SET_ITEM(v, ST_FILE_ATTRIBUTES_IDX,
2202 PyLong_FromUnsignedLong(st->st_file_attributes));
2203#endif
jcea6c51d512018-01-28 14:00:08 +01002204#ifdef HAVE_STRUCT_STAT_ST_FSTYPE
2205 PyStructSequence_SET_ITEM(v, ST_FSTYPE_IDX,
2206 PyUnicode_FromString(st->st_fstype));
2207#endif
Steve Dower9eb3d542019-08-21 15:52:42 -07002208#ifdef HAVE_STRUCT_STAT_ST_REPARSE_TAG
2209 PyStructSequence_SET_ITEM(v, ST_REPARSE_TAG_IDX,
2210 PyLong_FromUnsignedLong(st->st_reparse_tag));
2211#endif
Fred Drake699f3522000-06-29 21:12:41 +00002212
Victor Stinner8c62be82010-05-06 00:08:46 +00002213 if (PyErr_Occurred()) {
2214 Py_DECREF(v);
2215 return NULL;
2216 }
Fred Drake699f3522000-06-29 21:12:41 +00002217
Victor Stinner8c62be82010-05-06 00:08:46 +00002218 return v;
Fred Drake699f3522000-06-29 21:12:41 +00002219}
2220
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002221/* POSIX methods */
2222
Guido van Rossum94f6f721999-01-06 18:42:14 +00002223
2224static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02002225posix_do_stat(const char *function_name, path_t *path,
Larry Hastings9cf065c2012-06-22 16:30:09 -07002226 int dir_fd, int follow_symlinks)
Guido van Rossum94f6f721999-01-06 18:42:14 +00002227{
Larry Hastings9cf065c2012-06-22 16:30:09 -07002228 STRUCT_STAT st;
2229 int result;
2230
2231#if !defined(MS_WINDOWS) && !defined(HAVE_FSTATAT) && !defined(HAVE_LSTAT)
2232 if (follow_symlinks_specified(function_name, follow_symlinks))
2233 return NULL;
2234#endif
2235
2236 if (path_and_dir_fd_invalid("stat", path, dir_fd) ||
2237 dir_fd_and_fd_invalid("stat", dir_fd, path->fd) ||
2238 fd_and_follow_symlinks_invalid("stat", path->fd, follow_symlinks))
2239 return NULL;
2240
2241 Py_BEGIN_ALLOW_THREADS
2242 if (path->fd != -1)
2243 result = FSTAT(path->fd, &st);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002244#ifdef MS_WINDOWS
Steve Dower513d7472016-09-08 10:41:50 -07002245 else if (follow_symlinks)
Steve Dowercc16be82016-09-08 10:35:16 -07002246 result = win32_stat(path->wide, &st);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002247 else
Steve Dowercc16be82016-09-08 10:35:16 -07002248 result = win32_lstat(path->wide, &st);
2249#else
2250 else
2251#if defined(HAVE_LSTAT)
Larry Hastings9cf065c2012-06-22 16:30:09 -07002252 if ((!follow_symlinks) && (dir_fd == DEFAULT_DIR_FD))
2253 result = LSTAT(path->narrow, &st);
2254 else
Steve Dowercc16be82016-09-08 10:35:16 -07002255#endif /* HAVE_LSTAT */
Larry Hastings9cf065c2012-06-22 16:30:09 -07002256#ifdef HAVE_FSTATAT
2257 if ((dir_fd != DEFAULT_DIR_FD) || !follow_symlinks)
2258 result = fstatat(dir_fd, path->narrow, &st,
2259 follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW);
2260 else
Steve Dowercc16be82016-09-08 10:35:16 -07002261#endif /* HAVE_FSTATAT */
Larry Hastings9cf065c2012-06-22 16:30:09 -07002262 result = STAT(path->narrow, &st);
Steve Dowercc16be82016-09-08 10:35:16 -07002263#endif /* MS_WINDOWS */
Larry Hastings9cf065c2012-06-22 16:30:09 -07002264 Py_END_ALLOW_THREADS
2265
Victor Stinner292c8352012-10-30 02:17:38 +01002266 if (result != 0) {
2267 return path_error(path);
2268 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07002269
2270 return _pystat_fromstructstat(&st);
2271}
2272
Larry Hastings2f936352014-08-05 14:04:04 +10002273/*[python input]
2274
2275for s in """
2276
2277FACCESSAT
2278FCHMODAT
2279FCHOWNAT
2280FSTATAT
2281LINKAT
2282MKDIRAT
2283MKFIFOAT
2284MKNODAT
2285OPENAT
2286READLINKAT
2287SYMLINKAT
2288UNLINKAT
2289
2290""".strip().split():
2291 s = s.strip()
2292 print("""
2293#ifdef HAVE_{s}
2294 #define {s}_DIR_FD_CONVERTER dir_fd_converter
Larry Hastings31826802013-10-19 00:09:25 -07002295#else
Larry Hastings2f936352014-08-05 14:04:04 +10002296 #define {s}_DIR_FD_CONVERTER dir_fd_unavailable
Larry Hastings31826802013-10-19 00:09:25 -07002297#endif
Larry Hastings2f936352014-08-05 14:04:04 +10002298""".rstrip().format(s=s))
2299
2300for s in """
2301
2302FCHDIR
2303FCHMOD
2304FCHOWN
2305FDOPENDIR
2306FEXECVE
2307FPATHCONF
2308FSTATVFS
2309FTRUNCATE
2310
2311""".strip().split():
2312 s = s.strip()
2313 print("""
2314#ifdef HAVE_{s}
2315 #define PATH_HAVE_{s} 1
2316#else
2317 #define PATH_HAVE_{s} 0
2318#endif
2319
2320""".rstrip().format(s=s))
2321[python start generated code]*/
2322
2323#ifdef HAVE_FACCESSAT
2324 #define FACCESSAT_DIR_FD_CONVERTER dir_fd_converter
2325#else
2326 #define FACCESSAT_DIR_FD_CONVERTER dir_fd_unavailable
2327#endif
2328
2329#ifdef HAVE_FCHMODAT
2330 #define FCHMODAT_DIR_FD_CONVERTER dir_fd_converter
2331#else
2332 #define FCHMODAT_DIR_FD_CONVERTER dir_fd_unavailable
2333#endif
2334
2335#ifdef HAVE_FCHOWNAT
2336 #define FCHOWNAT_DIR_FD_CONVERTER dir_fd_converter
2337#else
2338 #define FCHOWNAT_DIR_FD_CONVERTER dir_fd_unavailable
2339#endif
2340
2341#ifdef HAVE_FSTATAT
2342 #define FSTATAT_DIR_FD_CONVERTER dir_fd_converter
2343#else
2344 #define FSTATAT_DIR_FD_CONVERTER dir_fd_unavailable
2345#endif
2346
2347#ifdef HAVE_LINKAT
2348 #define LINKAT_DIR_FD_CONVERTER dir_fd_converter
2349#else
2350 #define LINKAT_DIR_FD_CONVERTER dir_fd_unavailable
2351#endif
2352
2353#ifdef HAVE_MKDIRAT
2354 #define MKDIRAT_DIR_FD_CONVERTER dir_fd_converter
2355#else
2356 #define MKDIRAT_DIR_FD_CONVERTER dir_fd_unavailable
2357#endif
2358
2359#ifdef HAVE_MKFIFOAT
2360 #define MKFIFOAT_DIR_FD_CONVERTER dir_fd_converter
2361#else
2362 #define MKFIFOAT_DIR_FD_CONVERTER dir_fd_unavailable
2363#endif
2364
2365#ifdef HAVE_MKNODAT
2366 #define MKNODAT_DIR_FD_CONVERTER dir_fd_converter
2367#else
2368 #define MKNODAT_DIR_FD_CONVERTER dir_fd_unavailable
2369#endif
2370
2371#ifdef HAVE_OPENAT
2372 #define OPENAT_DIR_FD_CONVERTER dir_fd_converter
2373#else
2374 #define OPENAT_DIR_FD_CONVERTER dir_fd_unavailable
2375#endif
2376
2377#ifdef HAVE_READLINKAT
2378 #define READLINKAT_DIR_FD_CONVERTER dir_fd_converter
2379#else
2380 #define READLINKAT_DIR_FD_CONVERTER dir_fd_unavailable
2381#endif
2382
2383#ifdef HAVE_SYMLINKAT
2384 #define SYMLINKAT_DIR_FD_CONVERTER dir_fd_converter
2385#else
2386 #define SYMLINKAT_DIR_FD_CONVERTER dir_fd_unavailable
2387#endif
2388
2389#ifdef HAVE_UNLINKAT
2390 #define UNLINKAT_DIR_FD_CONVERTER dir_fd_converter
2391#else
2392 #define UNLINKAT_DIR_FD_CONVERTER dir_fd_unavailable
2393#endif
2394
2395#ifdef HAVE_FCHDIR
2396 #define PATH_HAVE_FCHDIR 1
2397#else
2398 #define PATH_HAVE_FCHDIR 0
2399#endif
2400
2401#ifdef HAVE_FCHMOD
2402 #define PATH_HAVE_FCHMOD 1
2403#else
2404 #define PATH_HAVE_FCHMOD 0
2405#endif
2406
2407#ifdef HAVE_FCHOWN
2408 #define PATH_HAVE_FCHOWN 1
2409#else
2410 #define PATH_HAVE_FCHOWN 0
2411#endif
2412
2413#ifdef HAVE_FDOPENDIR
2414 #define PATH_HAVE_FDOPENDIR 1
2415#else
2416 #define PATH_HAVE_FDOPENDIR 0
2417#endif
2418
2419#ifdef HAVE_FEXECVE
2420 #define PATH_HAVE_FEXECVE 1
2421#else
2422 #define PATH_HAVE_FEXECVE 0
2423#endif
2424
2425#ifdef HAVE_FPATHCONF
2426 #define PATH_HAVE_FPATHCONF 1
2427#else
2428 #define PATH_HAVE_FPATHCONF 0
2429#endif
2430
2431#ifdef HAVE_FSTATVFS
2432 #define PATH_HAVE_FSTATVFS 1
2433#else
2434 #define PATH_HAVE_FSTATVFS 0
2435#endif
2436
2437#ifdef HAVE_FTRUNCATE
2438 #define PATH_HAVE_FTRUNCATE 1
2439#else
2440 #define PATH_HAVE_FTRUNCATE 0
2441#endif
2442/*[python end generated code: output=4bd4f6f7d41267f1 input=80b4c890b6774ea5]*/
Larry Hastings31826802013-10-19 00:09:25 -07002443
Steve Dowerfe0a41a2015-03-20 19:50:46 -07002444#ifdef MS_WINDOWS
2445 #undef PATH_HAVE_FTRUNCATE
2446 #define PATH_HAVE_FTRUNCATE 1
2447#endif
Larry Hastings31826802013-10-19 00:09:25 -07002448
Larry Hastings61272b72014-01-07 12:41:53 -08002449/*[python input]
Larry Hastings31826802013-10-19 00:09:25 -07002450
2451class path_t_converter(CConverter):
2452
2453 type = "path_t"
2454 impl_by_reference = True
2455 parse_by_reference = True
2456
2457 converter = 'path_converter'
2458
2459 def converter_init(self, *, allow_fd=False, nullable=False):
Larry Hastings31826802013-10-19 00:09:25 -07002460 # right now path_t doesn't support default values.
2461 # to support a default value, you'll need to override initialize().
Larry Hastings2f936352014-08-05 14:04:04 +10002462 if self.default not in (unspecified, None):
Larry Hastings7726ac92014-01-31 22:03:12 -08002463 fail("Can't specify a default to the path_t converter!")
Larry Hastings31826802013-10-19 00:09:25 -07002464
Larry Hastings2f936352014-08-05 14:04:04 +10002465 if self.c_default not in (None, 'Py_None'):
2466 raise RuntimeError("Can't specify a c_default to the path_t converter!")
Larry Hastings31826802013-10-19 00:09:25 -07002467
2468 self.nullable = nullable
2469 self.allow_fd = allow_fd
2470
Larry Hastings7726ac92014-01-31 22:03:12 -08002471 def pre_render(self):
2472 def strify(value):
Larry Hastings2f936352014-08-05 14:04:04 +10002473 if isinstance(value, str):
2474 return value
Larry Hastings7726ac92014-01-31 22:03:12 -08002475 return str(int(bool(value)))
2476
2477 # add self.py_name here when merging with posixmodule conversion
Larry Hastings2f936352014-08-05 14:04:04 +10002478 self.c_default = 'PATH_T_INITIALIZE("{}", "{}", {}, {})'.format(
Larry Hastings31826802013-10-19 00:09:25 -07002479 self.function.name,
Larry Hastings2f936352014-08-05 14:04:04 +10002480 self.name,
Larry Hastings7726ac92014-01-31 22:03:12 -08002481 strify(self.nullable),
2482 strify(self.allow_fd),
Larry Hastings31826802013-10-19 00:09:25 -07002483 )
2484
2485 def cleanup(self):
2486 return "path_cleanup(&" + self.name + ");\n"
2487
2488
2489class dir_fd_converter(CConverter):
2490 type = 'int'
Larry Hastings31826802013-10-19 00:09:25 -07002491
Larry Hastings2f936352014-08-05 14:04:04 +10002492 def converter_init(self, requires=None):
Larry Hastings31826802013-10-19 00:09:25 -07002493 if self.default in (unspecified, None):
2494 self.c_default = 'DEFAULT_DIR_FD'
Larry Hastings2f936352014-08-05 14:04:04 +10002495 if isinstance(requires, str):
2496 self.converter = requires.upper() + '_DIR_FD_CONVERTER'
2497 else:
2498 self.converter = 'dir_fd_converter'
Larry Hastings31826802013-10-19 00:09:25 -07002499
Larry Hastings2f936352014-08-05 14:04:04 +10002500class fildes_converter(CConverter):
2501 type = 'int'
2502 converter = 'fildes_converter'
2503
2504class uid_t_converter(CConverter):
2505 type = "uid_t"
2506 converter = '_Py_Uid_Converter'
2507
2508class gid_t_converter(CConverter):
2509 type = "gid_t"
2510 converter = '_Py_Gid_Converter'
2511
Serhiy Storchakaacdb7c12015-01-18 11:17:39 +02002512class dev_t_converter(CConverter):
2513 type = 'dev_t'
2514 converter = '_Py_Dev_Converter'
2515
2516class dev_t_return_converter(unsigned_long_return_converter):
2517 type = 'dev_t'
2518 conversion_fn = '_PyLong_FromDev'
2519 unsigned_cast = '(dev_t)'
2520
Larry Hastings2f936352014-08-05 14:04:04 +10002521class FSConverter_converter(CConverter):
2522 type = 'PyObject *'
2523 converter = 'PyUnicode_FSConverter'
2524 def converter_init(self):
2525 if self.default is not unspecified:
2526 fail("FSConverter_converter does not support default values")
2527 self.c_default = 'NULL'
2528
2529 def cleanup(self):
2530 return "Py_XDECREF(" + self.name + ");\n"
2531
2532class pid_t_converter(CConverter):
2533 type = 'pid_t'
2534 format_unit = '" _Py_PARSE_PID "'
2535
2536class idtype_t_converter(int_converter):
2537 type = 'idtype_t'
2538
2539class id_t_converter(CConverter):
2540 type = 'id_t'
2541 format_unit = '" _Py_PARSE_PID "'
2542
Benjamin Petersonca470632016-09-06 13:47:26 -07002543class intptr_t_converter(CConverter):
2544 type = 'intptr_t'
Larry Hastings2f936352014-08-05 14:04:04 +10002545 format_unit = '" _Py_PARSE_INTPTR "'
2546
2547class Py_off_t_converter(CConverter):
2548 type = 'Py_off_t'
2549 converter = 'Py_off_t_converter'
2550
2551class Py_off_t_return_converter(long_return_converter):
2552 type = 'Py_off_t'
2553 conversion_fn = 'PyLong_FromPy_off_t'
2554
2555class path_confname_converter(CConverter):
2556 type="int"
2557 converter="conv_path_confname"
2558
2559class confstr_confname_converter(path_confname_converter):
2560 converter='conv_confstr_confname'
2561
2562class sysconf_confname_converter(path_confname_converter):
2563 converter="conv_sysconf_confname"
2564
2565class sched_param_converter(CConverter):
2566 type = 'struct sched_param'
2567 converter = 'convert_sched_param'
2568 impl_by_reference = True;
Larry Hastings31826802013-10-19 00:09:25 -07002569
Larry Hastings61272b72014-01-07 12:41:53 -08002570[python start generated code]*/
Victor Stinner581139c2016-09-06 15:54:20 -07002571/*[python end generated code: output=da39a3ee5e6b4b0d input=418fce0e01144461]*/
Larry Hastings31826802013-10-19 00:09:25 -07002572
Larry Hastings61272b72014-01-07 12:41:53 -08002573/*[clinic input]
Larry Hastings31826802013-10-19 00:09:25 -07002574
Larry Hastings2a727912014-01-16 11:32:01 -08002575os.stat
Larry Hastings31826802013-10-19 00:09:25 -07002576
2577 path : path_t(allow_fd=True)
BNMetricsb9427072018-11-02 15:20:19 +00002578 Path to be examined; can be string, bytes, a path-like object or
Xiang Zhang4459e002017-01-22 13:04:17 +08002579 open-file-descriptor int.
Larry Hastings31826802013-10-19 00:09:25 -07002580
2581 *
2582
Larry Hastings2f936352014-08-05 14:04:04 +10002583 dir_fd : dir_fd(requires='fstatat') = None
Larry Hastings31826802013-10-19 00:09:25 -07002584 If not None, it should be a file descriptor open to a directory,
2585 and path should be a relative string; path will then be relative to
2586 that directory.
2587
2588 follow_symlinks: bool = True
2589 If False, and the last element of the path is a symbolic link,
2590 stat will examine the symbolic link itself instead of the file
2591 the link points to.
2592
2593Perform a stat system call on the given path.
2594
2595dir_fd and follow_symlinks may not be implemented
2596 on your platform. If they are unavailable, using them will raise a
2597 NotImplementedError.
2598
2599It's an error to use dir_fd or follow_symlinks when specifying path as
2600 an open file descriptor.
2601
Larry Hastings61272b72014-01-07 12:41:53 -08002602[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -07002603
Larry Hastings31826802013-10-19 00:09:25 -07002604static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002605os_stat_impl(PyObject *module, path_t *path, int dir_fd, int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +00002606/*[clinic end generated code: output=7d4976e6f18a59c5 input=01d362ebcc06996b]*/
Larry Hastings31826802013-10-19 00:09:25 -07002607{
2608 return posix_do_stat("stat", path, dir_fd, follow_symlinks);
2609}
2610
Larry Hastings2f936352014-08-05 14:04:04 +10002611
2612/*[clinic input]
2613os.lstat
2614
2615 path : path_t
2616
2617 *
2618
2619 dir_fd : dir_fd(requires='fstatat') = None
2620
2621Perform a stat system call on the given path, without following symbolic links.
2622
2623Like stat(), but do not follow symbolic links.
2624Equivalent to stat(path, follow_symlinks=False).
2625[clinic start generated code]*/
2626
Larry Hastings2f936352014-08-05 14:04:04 +10002627static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002628os_lstat_impl(PyObject *module, path_t *path, int dir_fd)
2629/*[clinic end generated code: output=ef82a5d35ce8ab37 input=0b7474765927b925]*/
Larry Hastings2f936352014-08-05 14:04:04 +10002630{
2631 int follow_symlinks = 0;
2632 return posix_do_stat("lstat", path, dir_fd, follow_symlinks);
2633}
Larry Hastings31826802013-10-19 00:09:25 -07002634
Larry Hastings2f936352014-08-05 14:04:04 +10002635
Larry Hastings61272b72014-01-07 12:41:53 -08002636/*[clinic input]
Larry Hastings2f936352014-08-05 14:04:04 +10002637os.access -> bool
Larry Hastings31826802013-10-19 00:09:25 -07002638
Benjamin Peterson768f3b42016-09-05 15:29:33 -07002639 path: path_t
BNMetricsb9427072018-11-02 15:20:19 +00002640 Path to be tested; can be string, bytes, or a path-like object.
Larry Hastings31826802013-10-19 00:09:25 -07002641
2642 mode: int
2643 Operating-system mode bitfield. Can be F_OK to test existence,
2644 or the inclusive-OR of R_OK, W_OK, and X_OK.
2645
2646 *
2647
Larry Hastings2f936352014-08-05 14:04:04 +10002648 dir_fd : dir_fd(requires='faccessat') = None
Larry Hastings31826802013-10-19 00:09:25 -07002649 If not None, it should be a file descriptor open to a directory,
2650 and path should be relative; path will then be relative to that
2651 directory.
2652
2653 effective_ids: bool = False
2654 If True, access will use the effective uid/gid instead of
2655 the real uid/gid.
2656
2657 follow_symlinks: bool = True
2658 If False, and the last element of the path is a symbolic link,
2659 access will examine the symbolic link itself instead of the file
2660 the link points to.
2661
2662Use the real uid/gid to test for access to a path.
2663
2664{parameters}
2665dir_fd, effective_ids, and follow_symlinks may not be implemented
2666 on your platform. If they are unavailable, using them will raise a
2667 NotImplementedError.
2668
2669Note that most operations will use the effective uid/gid, therefore this
2670 routine can be used in a suid/sgid environment to test if the invoking user
2671 has the specified access to the path.
2672
Larry Hastings61272b72014-01-07 12:41:53 -08002673[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -07002674
Larry Hastings2f936352014-08-05 14:04:04 +10002675static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002676os_access_impl(PyObject *module, path_t *path, int mode, int dir_fd,
Larry Hastings89964c42015-04-14 18:07:59 -04002677 int effective_ids, int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +00002678/*[clinic end generated code: output=cf84158bc90b1a77 input=3ffe4e650ee3bf20]*/
Larry Hastings31826802013-10-19 00:09:25 -07002679{
Larry Hastings2f936352014-08-05 14:04:04 +10002680 int return_value;
Victor Stinner8c62be82010-05-06 00:08:46 +00002681
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00002682#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +00002683 DWORD attr;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002684#else
Larry Hastings9cf065c2012-06-22 16:30:09 -07002685 int result;
Thomas Wouters477c8d52006-05-27 19:21:47 +00002686#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -07002687
Larry Hastings9cf065c2012-06-22 16:30:09 -07002688#ifndef HAVE_FACCESSAT
2689 if (follow_symlinks_specified("access", follow_symlinks))
Larry Hastings2f936352014-08-05 14:04:04 +10002690 return -1;
Larry Hastings9cf065c2012-06-22 16:30:09 -07002691
2692 if (effective_ids) {
2693 argument_unavailable_error("access", "effective_ids");
Larry Hastings2f936352014-08-05 14:04:04 +10002694 return -1;
Larry Hastings9cf065c2012-06-22 16:30:09 -07002695 }
2696#endif
2697
2698#ifdef MS_WINDOWS
2699 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -07002700 attr = GetFileAttributesW(path->wide);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002701 Py_END_ALLOW_THREADS
2702
2703 /*
Georg Brandlf7875592012-06-24 13:58:31 +02002704 * Access is possible if
Larry Hastings9cf065c2012-06-22 16:30:09 -07002705 * * we didn't get a -1, and
2706 * * write access wasn't requested,
2707 * * or the file isn't read-only,
2708 * * or it's a directory.
2709 * (Directories cannot be read-only on Windows.)
2710 */
Larry Hastings2f936352014-08-05 14:04:04 +10002711 return_value = (attr != INVALID_FILE_ATTRIBUTES) &&
Georg Brandl5bb7aa92012-06-23 12:48:40 +02002712 (!(mode & 2) ||
Larry Hastings9cf065c2012-06-22 16:30:09 -07002713 !(attr & FILE_ATTRIBUTE_READONLY) ||
Larry Hastings2f936352014-08-05 14:04:04 +10002714 (attr & FILE_ATTRIBUTE_DIRECTORY));
Larry Hastings9cf065c2012-06-22 16:30:09 -07002715#else
2716
2717 Py_BEGIN_ALLOW_THREADS
2718#ifdef HAVE_FACCESSAT
2719 if ((dir_fd != DEFAULT_DIR_FD) ||
2720 effective_ids ||
2721 !follow_symlinks) {
2722 int flags = 0;
2723 if (!follow_symlinks)
2724 flags |= AT_SYMLINK_NOFOLLOW;
2725 if (effective_ids)
2726 flags |= AT_EACCESS;
Larry Hastings31826802013-10-19 00:09:25 -07002727 result = faccessat(dir_fd, path->narrow, mode, flags);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002728 }
2729 else
2730#endif
Larry Hastings31826802013-10-19 00:09:25 -07002731 result = access(path->narrow, mode);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002732 Py_END_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10002733 return_value = !result;
Larry Hastings9cf065c2012-06-22 16:30:09 -07002734#endif
2735
Larry Hastings9cf065c2012-06-22 16:30:09 -07002736 return return_value;
Guido van Rossum94f6f721999-01-06 18:42:14 +00002737}
2738
Guido van Rossumd371ff11999-01-25 16:12:23 +00002739#ifndef F_OK
2740#define F_OK 0
2741#endif
2742#ifndef R_OK
2743#define R_OK 4
2744#endif
2745#ifndef W_OK
2746#define W_OK 2
2747#endif
2748#ifndef X_OK
2749#define X_OK 1
2750#endif
2751
Larry Hastings31826802013-10-19 00:09:25 -07002752
Guido van Rossumd371ff11999-01-25 16:12:23 +00002753#ifdef HAVE_TTYNAME
Larry Hastings61272b72014-01-07 12:41:53 -08002754/*[clinic input]
Serhiy Storchaka4db62e12018-12-17 16:47:45 +02002755os.ttyname
Larry Hastings31826802013-10-19 00:09:25 -07002756
2757 fd: int
2758 Integer file descriptor handle.
2759
2760 /
2761
2762Return the name of the terminal device connected to 'fd'.
Larry Hastings61272b72014-01-07 12:41:53 -08002763[clinic start generated code]*/
Larry Hastings31826802013-10-19 00:09:25 -07002764
Serhiy Storchaka4db62e12018-12-17 16:47:45 +02002765static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002766os_ttyname_impl(PyObject *module, int fd)
Serhiy Storchaka4db62e12018-12-17 16:47:45 +02002767/*[clinic end generated code: output=c424d2e9d1cd636a input=9ff5a58b08115c55]*/
Larry Hastings31826802013-10-19 00:09:25 -07002768{
2769 char *ret;
Guido van Rossum94f6f721999-01-06 18:42:14 +00002770
Larry Hastings31826802013-10-19 00:09:25 -07002771 ret = ttyname(fd);
Serhiy Storchaka4db62e12018-12-17 16:47:45 +02002772 if (ret == NULL) {
2773 return posix_error();
2774 }
2775 return PyUnicode_DecodeFSDefault(ret);
Guido van Rossum94f6f721999-01-06 18:42:14 +00002776}
Guido van Rossumd371ff11999-01-25 16:12:23 +00002777#endif
Guido van Rossum94f6f721999-01-06 18:42:14 +00002778
Fred Drake5ab8eaf1999-12-09 21:13:07 +00002779#ifdef HAVE_CTERMID
Larry Hastings2f936352014-08-05 14:04:04 +10002780/*[clinic input]
2781os.ctermid
2782
2783Return the name of the controlling terminal for this process.
2784[clinic start generated code]*/
2785
Larry Hastings2f936352014-08-05 14:04:04 +10002786static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002787os_ctermid_impl(PyObject *module)
2788/*[clinic end generated code: output=02f017e6c9e620db input=3b87fdd52556382d]*/
Fred Drake5ab8eaf1999-12-09 21:13:07 +00002789{
Victor Stinner8c62be82010-05-06 00:08:46 +00002790 char *ret;
2791 char buffer[L_ctermid];
Fred Drake5ab8eaf1999-12-09 21:13:07 +00002792
Greg Wardb48bc172000-03-01 21:51:56 +00002793#ifdef USE_CTERMID_R
Victor Stinner8c62be82010-05-06 00:08:46 +00002794 ret = ctermid_r(buffer);
Fred Drake5ab8eaf1999-12-09 21:13:07 +00002795#else
Victor Stinner8c62be82010-05-06 00:08:46 +00002796 ret = ctermid(buffer);
Fred Drake5ab8eaf1999-12-09 21:13:07 +00002797#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00002798 if (ret == NULL)
2799 return posix_error();
Victor Stinner5fe6de82010-08-15 09:12:51 +00002800 return PyUnicode_DecodeFSDefault(buffer);
Fred Drake5ab8eaf1999-12-09 21:13:07 +00002801}
Larry Hastings2f936352014-08-05 14:04:04 +10002802#endif /* HAVE_CTERMID */
Fred Drake5ab8eaf1999-12-09 21:13:07 +00002803
Larry Hastings2f936352014-08-05 14:04:04 +10002804
2805/*[clinic input]
2806os.chdir
2807
2808 path: path_t(allow_fd='PATH_HAVE_FCHDIR')
2809
2810Change the current working directory to the specified path.
2811
2812path may always be specified as a string.
2813On some platforms, path may also be specified as an open file descriptor.
2814 If this functionality is unavailable, using it raises an exception.
2815[clinic start generated code]*/
2816
Larry Hastings2f936352014-08-05 14:04:04 +10002817static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002818os_chdir_impl(PyObject *module, path_t *path)
2819/*[clinic end generated code: output=3be6400eee26eaae input=1a4a15b4d12cb15d]*/
Larry Hastings2f936352014-08-05 14:04:04 +10002820{
2821 int result;
Larry Hastings9cf065c2012-06-22 16:30:09 -07002822
2823 Py_BEGIN_ALLOW_THREADS
2824#ifdef MS_WINDOWS
Steve Dowercc16be82016-09-08 10:35:16 -07002825 /* on unix, success = 0, on windows, success = !0 */
2826 result = !win32_wchdir(path->wide);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002827#else
2828#ifdef HAVE_FCHDIR
Larry Hastings2f936352014-08-05 14:04:04 +10002829 if (path->fd != -1)
2830 result = fchdir(path->fd);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002831 else
2832#endif
Larry Hastings2f936352014-08-05 14:04:04 +10002833 result = chdir(path->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002834#endif
2835 Py_END_ALLOW_THREADS
2836
2837 if (result) {
Larry Hastings2f936352014-08-05 14:04:04 +10002838 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002839 }
2840
Larry Hastings2f936352014-08-05 14:04:04 +10002841 Py_RETURN_NONE;
2842}
2843
2844
2845#ifdef HAVE_FCHDIR
2846/*[clinic input]
2847os.fchdir
2848
2849 fd: fildes
2850
2851Change to the directory of the given file descriptor.
2852
2853fd must be opened on a directory, not a file.
2854Equivalent to os.chdir(fd).
2855
2856[clinic start generated code]*/
2857
Fred Drake4d1e64b2002-04-15 19:40:07 +00002858static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002859os_fchdir_impl(PyObject *module, int fd)
2860/*[clinic end generated code: output=42e064ec4dc00ab0 input=18e816479a2fa985]*/
Fred Drake4d1e64b2002-04-15 19:40:07 +00002861{
Larry Hastings2f936352014-08-05 14:04:04 +10002862 return posix_fildes_fd(fd, fchdir);
Fred Drake4d1e64b2002-04-15 19:40:07 +00002863}
2864#endif /* HAVE_FCHDIR */
2865
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00002866
Larry Hastings2f936352014-08-05 14:04:04 +10002867/*[clinic input]
2868os.chmod
2869
2870 path: path_t(allow_fd='PATH_HAVE_FCHMOD')
BNMetricsb9427072018-11-02 15:20:19 +00002871 Path to be modified. May always be specified as a str, bytes, or a path-like object.
Larry Hastings2f936352014-08-05 14:04:04 +10002872 On some platforms, path may also be specified as an open file descriptor.
2873 If this functionality is unavailable, using it raises an exception.
2874
2875 mode: int
2876 Operating-system mode bitfield.
2877
2878 *
2879
2880 dir_fd : dir_fd(requires='fchmodat') = None
2881 If not None, it should be a file descriptor open to a directory,
2882 and path should be relative; path will then be relative to that
2883 directory.
2884
2885 follow_symlinks: bool = True
2886 If False, and the last element of the path is a symbolic link,
2887 chmod will modify the symbolic link itself instead of the file
2888 the link points to.
2889
2890Change the access permissions of a file.
2891
2892It is an error to use dir_fd or follow_symlinks when specifying path as
2893 an open file descriptor.
2894dir_fd and follow_symlinks may not be implemented on your platform.
2895 If they are unavailable, using them will raise a NotImplementedError.
2896
2897[clinic start generated code]*/
2898
Larry Hastings2f936352014-08-05 14:04:04 +10002899static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03002900os_chmod_impl(PyObject *module, path_t *path, int mode, int dir_fd,
Larry Hastings89964c42015-04-14 18:07:59 -04002901 int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +00002902/*[clinic end generated code: output=5cf6a94915cc7bff input=989081551c00293b]*/
Larry Hastings2f936352014-08-05 14:04:04 +10002903{
Larry Hastings9cf065c2012-06-22 16:30:09 -07002904 int result;
Larry Hastings9cf065c2012-06-22 16:30:09 -07002905
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00002906#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +00002907 DWORD attr;
Larry Hastings9cf065c2012-06-22 16:30:09 -07002908#endif
Hirokazu Yamamoto892a37a2009-06-28 11:07:03 +00002909
Larry Hastings9cf065c2012-06-22 16:30:09 -07002910#ifdef HAVE_FCHMODAT
2911 int fchmodat_nofollow_unsupported = 0;
2912#endif
2913
Larry Hastings9cf065c2012-06-22 16:30:09 -07002914#if !(defined(HAVE_FCHMODAT) || defined(HAVE_LCHMOD))
2915 if (follow_symlinks_specified("chmod", follow_symlinks))
Larry Hastings2f936352014-08-05 14:04:04 +10002916 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07002917#endif
2918
2919#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +00002920 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -07002921 attr = GetFileAttributesW(path->wide);
Tim Golden23005082013-10-25 11:22:37 +01002922 if (attr == INVALID_FILE_ATTRIBUTES)
Larry Hastings9cf065c2012-06-22 16:30:09 -07002923 result = 0;
2924 else {
2925 if (mode & _S_IWRITE)
Victor Stinner8c62be82010-05-06 00:08:46 +00002926 attr &= ~FILE_ATTRIBUTE_READONLY;
2927 else
2928 attr |= FILE_ATTRIBUTE_READONLY;
Steve Dowercc16be82016-09-08 10:35:16 -07002929 result = SetFileAttributesW(path->wide, attr);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002930 }
2931 Py_END_ALLOW_THREADS
2932
2933 if (!result) {
Larry Hastings2f936352014-08-05 14:04:04 +10002934 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002935 }
2936#else /* MS_WINDOWS */
2937 Py_BEGIN_ALLOW_THREADS
2938#ifdef HAVE_FCHMOD
Larry Hastings2f936352014-08-05 14:04:04 +10002939 if (path->fd != -1)
2940 result = fchmod(path->fd, mode);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002941 else
2942#endif
2943#ifdef HAVE_LCHMOD
2944 if ((!follow_symlinks) && (dir_fd == DEFAULT_DIR_FD))
Larry Hastings2f936352014-08-05 14:04:04 +10002945 result = lchmod(path->narrow, mode);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002946 else
2947#endif
2948#ifdef HAVE_FCHMODAT
2949 if ((dir_fd != DEFAULT_DIR_FD) || !follow_symlinks) {
2950 /*
2951 * fchmodat() doesn't currently support AT_SYMLINK_NOFOLLOW!
2952 * The documentation specifically shows how to use it,
Larry Hastingsdbbc0c82012-06-22 19:50:21 -07002953 * and then says it isn't implemented yet.
2954 * (true on linux with glibc 2.15, and openindiana 3.x)
Larry Hastings9cf065c2012-06-22 16:30:09 -07002955 *
2956 * Once it is supported, os.chmod will automatically
2957 * support dir_fd and follow_symlinks=False. (Hopefully.)
2958 * Until then, we need to be careful what exception we raise.
2959 */
Larry Hastings2f936352014-08-05 14:04:04 +10002960 result = fchmodat(dir_fd, path->narrow, mode,
Larry Hastings9cf065c2012-06-22 16:30:09 -07002961 follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW);
2962 /*
2963 * But wait! We can't throw the exception without allowing threads,
2964 * and we can't do that in this nested scope. (Macro trickery, sigh.)
2965 */
2966 fchmodat_nofollow_unsupported =
Larry Hastingsdbbc0c82012-06-22 19:50:21 -07002967 result &&
2968 ((errno == ENOTSUP) || (errno == EOPNOTSUPP)) &&
2969 !follow_symlinks;
Victor Stinner8c62be82010-05-06 00:08:46 +00002970 }
2971 else
Thomas Wouters477c8d52006-05-27 19:21:47 +00002972#endif
Larry Hastings2f936352014-08-05 14:04:04 +10002973 result = chmod(path->narrow, mode);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002974 Py_END_ALLOW_THREADS
2975
2976 if (result) {
2977#ifdef HAVE_FCHMODAT
2978 if (fchmodat_nofollow_unsupported) {
2979 if (dir_fd != DEFAULT_DIR_FD)
2980 dir_fd_and_follow_symlinks_invalid("chmod",
2981 dir_fd, follow_symlinks);
2982 else
2983 follow_symlinks_specified("chmod", follow_symlinks);
Anthony Sottile233ef242017-12-14 08:57:55 -08002984 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07002985 }
2986 else
2987#endif
Larry Hastings2f936352014-08-05 14:04:04 +10002988 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07002989 }
2990#endif
2991
Larry Hastings2f936352014-08-05 14:04:04 +10002992 Py_RETURN_NONE;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002993}
2994
Larry Hastings9cf065c2012-06-22 16:30:09 -07002995
Christian Heimes4e30a842007-11-30 22:12:06 +00002996#ifdef HAVE_FCHMOD
Larry Hastings2f936352014-08-05 14:04:04 +10002997/*[clinic input]
2998os.fchmod
2999
3000 fd: int
3001 mode: int
3002
3003Change the access permissions of the file given by file descriptor fd.
3004
3005Equivalent to os.chmod(fd, mode).
3006[clinic start generated code]*/
3007
Larry Hastings2f936352014-08-05 14:04:04 +10003008static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003009os_fchmod_impl(PyObject *module, int fd, int mode)
3010/*[clinic end generated code: output=afd9bc05b4e426b3 input=8ab11975ca01ee5b]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003011{
3012 int res;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00003013 int async_err = 0;
3014
3015 do {
3016 Py_BEGIN_ALLOW_THREADS
3017 res = fchmod(fd, mode);
3018 Py_END_ALLOW_THREADS
3019 } while (res != 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
3020 if (res != 0)
3021 return (!async_err) ? posix_error() : NULL;
3022
Victor Stinner8c62be82010-05-06 00:08:46 +00003023 Py_RETURN_NONE;
Christian Heimes4e30a842007-11-30 22:12:06 +00003024}
3025#endif /* HAVE_FCHMOD */
3026
Larry Hastings2f936352014-08-05 14:04:04 +10003027
Christian Heimes4e30a842007-11-30 22:12:06 +00003028#ifdef HAVE_LCHMOD
Larry Hastings2f936352014-08-05 14:04:04 +10003029/*[clinic input]
3030os.lchmod
3031
3032 path: path_t
3033 mode: int
3034
3035Change the access permissions of a file, without following symbolic links.
3036
3037If path is a symlink, this affects the link itself rather than the target.
3038Equivalent to chmod(path, mode, follow_symlinks=False)."
3039[clinic start generated code]*/
3040
Larry Hastings2f936352014-08-05 14:04:04 +10003041static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003042os_lchmod_impl(PyObject *module, path_t *path, int mode)
3043/*[clinic end generated code: output=082344022b51a1d5 input=90c5663c7465d24f]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003044{
Victor Stinner8c62be82010-05-06 00:08:46 +00003045 int res;
Victor Stinner8c62be82010-05-06 00:08:46 +00003046 Py_BEGIN_ALLOW_THREADS
Larry Hastingsb1dc1122014-08-05 16:06:16 +10003047 res = lchmod(path->narrow, mode);
Victor Stinner8c62be82010-05-06 00:08:46 +00003048 Py_END_ALLOW_THREADS
Victor Stinner292c8352012-10-30 02:17:38 +01003049 if (res < 0) {
Larry Hastings2f936352014-08-05 14:04:04 +10003050 path_error(path);
Victor Stinner292c8352012-10-30 02:17:38 +01003051 return NULL;
3052 }
Victor Stinner8c62be82010-05-06 00:08:46 +00003053 Py_RETURN_NONE;
Christian Heimes4e30a842007-11-30 22:12:06 +00003054}
3055#endif /* HAVE_LCHMOD */
3056
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00003057
Thomas Wouterscf297e42007-02-23 15:07:44 +00003058#ifdef HAVE_CHFLAGS
Larry Hastings2f936352014-08-05 14:04:04 +10003059/*[clinic input]
3060os.chflags
3061
3062 path: path_t
3063 flags: unsigned_long(bitwise=True)
3064 follow_symlinks: bool=True
3065
3066Set file flags.
3067
3068If follow_symlinks is False, and the last element of the path is a symbolic
3069 link, chflags will change flags on the symbolic link itself instead of the
3070 file the link points to.
3071follow_symlinks may not be implemented on your platform. If it is
3072unavailable, using it will raise a NotImplementedError.
3073
3074[clinic start generated code]*/
3075
Larry Hastings2f936352014-08-05 14:04:04 +10003076static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003077os_chflags_impl(PyObject *module, path_t *path, unsigned long flags,
Larry Hastings89964c42015-04-14 18:07:59 -04003078 int follow_symlinks)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003079/*[clinic end generated code: output=85571c6737661ce9 input=0327e29feb876236]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003080{
3081 int result;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003082
3083#ifndef HAVE_LCHFLAGS
3084 if (follow_symlinks_specified("chflags", follow_symlinks))
Larry Hastings2f936352014-08-05 14:04:04 +10003085 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003086#endif
3087
Victor Stinner8c62be82010-05-06 00:08:46 +00003088 Py_BEGIN_ALLOW_THREADS
Larry Hastings9cf065c2012-06-22 16:30:09 -07003089#ifdef HAVE_LCHFLAGS
3090 if (!follow_symlinks)
Larry Hastings2f936352014-08-05 14:04:04 +10003091 result = lchflags(path->narrow, flags);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003092 else
3093#endif
Larry Hastings2f936352014-08-05 14:04:04 +10003094 result = chflags(path->narrow, flags);
Victor Stinner8c62be82010-05-06 00:08:46 +00003095 Py_END_ALLOW_THREADS
Larry Hastings9cf065c2012-06-22 16:30:09 -07003096
Larry Hastings2f936352014-08-05 14:04:04 +10003097 if (result)
3098 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003099
Larry Hastings2f936352014-08-05 14:04:04 +10003100 Py_RETURN_NONE;
Thomas Wouterscf297e42007-02-23 15:07:44 +00003101}
3102#endif /* HAVE_CHFLAGS */
3103
Larry Hastings2f936352014-08-05 14:04:04 +10003104
Thomas Wouterscf297e42007-02-23 15:07:44 +00003105#ifdef HAVE_LCHFLAGS
Larry Hastings2f936352014-08-05 14:04:04 +10003106/*[clinic input]
3107os.lchflags
3108
3109 path: path_t
3110 flags: unsigned_long(bitwise=True)
3111
3112Set file flags.
3113
3114This function will not follow symbolic links.
3115Equivalent to chflags(path, flags, follow_symlinks=False).
3116[clinic start generated code]*/
3117
Larry Hastings2f936352014-08-05 14:04:04 +10003118static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003119os_lchflags_impl(PyObject *module, path_t *path, unsigned long flags)
3120/*[clinic end generated code: output=30ae958695c07316 input=f9f82ea8b585ca9d]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003121{
Victor Stinner8c62be82010-05-06 00:08:46 +00003122 int res;
Victor Stinner8c62be82010-05-06 00:08:46 +00003123 Py_BEGIN_ALLOW_THREADS
Larry Hastingsb1dc1122014-08-05 16:06:16 +10003124 res = lchflags(path->narrow, flags);
Victor Stinner8c62be82010-05-06 00:08:46 +00003125 Py_END_ALLOW_THREADS
Victor Stinner292c8352012-10-30 02:17:38 +01003126 if (res < 0) {
Larry Hastings2f936352014-08-05 14:04:04 +10003127 return path_error(path);
Victor Stinner292c8352012-10-30 02:17:38 +01003128 }
Victor Stinner292c8352012-10-30 02:17:38 +01003129 Py_RETURN_NONE;
Thomas Wouterscf297e42007-02-23 15:07:44 +00003130}
3131#endif /* HAVE_LCHFLAGS */
3132
Larry Hastings2f936352014-08-05 14:04:04 +10003133
Martin v. Löwis244edc82001-10-04 22:44:26 +00003134#ifdef HAVE_CHROOT
Larry Hastings2f936352014-08-05 14:04:04 +10003135/*[clinic input]
3136os.chroot
3137 path: path_t
3138
3139Change root directory to path.
3140
3141[clinic start generated code]*/
3142
Larry Hastings2f936352014-08-05 14:04:04 +10003143static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003144os_chroot_impl(PyObject *module, path_t *path)
3145/*[clinic end generated code: output=de80befc763a4475 input=14822965652c3dc3]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003146{
3147 int res;
3148 Py_BEGIN_ALLOW_THREADS
3149 res = chroot(path->narrow);
3150 Py_END_ALLOW_THREADS
3151 if (res < 0)
3152 return path_error(path);
3153 Py_RETURN_NONE;
3154}
3155#endif /* HAVE_CHROOT */
3156
Martin v. Löwis244edc82001-10-04 22:44:26 +00003157
Guido van Rossum21142a01999-01-08 21:05:37 +00003158#ifdef HAVE_FSYNC
Larry Hastings2f936352014-08-05 14:04:04 +10003159/*[clinic input]
3160os.fsync
3161
3162 fd: fildes
3163
3164Force write of fd to disk.
3165[clinic start generated code]*/
3166
Larry Hastings2f936352014-08-05 14:04:04 +10003167static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003168os_fsync_impl(PyObject *module, int fd)
3169/*[clinic end generated code: output=4a10d773f52b3584 input=21c3645c056967f2]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003170{
3171 return posix_fildes_fd(fd, fsync);
Guido van Rossum21142a01999-01-08 21:05:37 +00003172}
3173#endif /* HAVE_FSYNC */
3174
Larry Hastings2f936352014-08-05 14:04:04 +10003175
Ross Lagerwall7807c352011-03-17 20:20:30 +02003176#ifdef HAVE_SYNC
Larry Hastings2f936352014-08-05 14:04:04 +10003177/*[clinic input]
3178os.sync
3179
3180Force write of everything to disk.
3181[clinic start generated code]*/
3182
Larry Hastings2f936352014-08-05 14:04:04 +10003183static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003184os_sync_impl(PyObject *module)
3185/*[clinic end generated code: output=2796b1f0818cd71c input=84749fe5e9b404ff]*/
Ross Lagerwall7807c352011-03-17 20:20:30 +02003186{
3187 Py_BEGIN_ALLOW_THREADS
3188 sync();
3189 Py_END_ALLOW_THREADS
3190 Py_RETURN_NONE;
3191}
Larry Hastings2f936352014-08-05 14:04:04 +10003192#endif /* HAVE_SYNC */
3193
Ross Lagerwall7807c352011-03-17 20:20:30 +02003194
Guido van Rossum21142a01999-01-08 21:05:37 +00003195#ifdef HAVE_FDATASYNC
Guido van Rossum7f58e2e2000-09-22 17:26:14 +00003196#ifdef __hpux
Guido van Rossumecc23b02000-09-22 16:01:05 +00003197extern int fdatasync(int); /* On HP-UX, in libc but not in unistd.h */
3198#endif
3199
Larry Hastings2f936352014-08-05 14:04:04 +10003200/*[clinic input]
3201os.fdatasync
3202
3203 fd: fildes
3204
3205Force write of fd to disk without forcing update of metadata.
3206[clinic start generated code]*/
3207
Larry Hastings2f936352014-08-05 14:04:04 +10003208static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003209os_fdatasync_impl(PyObject *module, int fd)
3210/*[clinic end generated code: output=b4b9698b5d7e26dd input=bc74791ee54dd291]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003211{
3212 return posix_fildes_fd(fd, fdatasync);
Guido van Rossum21142a01999-01-08 21:05:37 +00003213}
3214#endif /* HAVE_FDATASYNC */
3215
3216
Fredrik Lundh10723342000-07-10 16:38:09 +00003217#ifdef HAVE_CHOWN
Larry Hastings2f936352014-08-05 14:04:04 +10003218/*[clinic input]
3219os.chown
3220
3221 path : path_t(allow_fd='PATH_HAVE_FCHOWN')
BNMetricsb9427072018-11-02 15:20:19 +00003222 Path to be examined; can be string, bytes, a path-like object, or open-file-descriptor int.
Larry Hastings2f936352014-08-05 14:04:04 +10003223
3224 uid: uid_t
3225
3226 gid: gid_t
3227
3228 *
3229
3230 dir_fd : dir_fd(requires='fchownat') = None
3231 If not None, it should be a file descriptor open to a directory,
3232 and path should be relative; path will then be relative to that
3233 directory.
3234
3235 follow_symlinks: bool = True
3236 If False, and the last element of the path is a symbolic link,
3237 stat will examine the symbolic link itself instead of the file
3238 the link points to.
3239
3240Change the owner and group id of path to the numeric uid and gid.\
3241
3242path may always be specified as a string.
3243On some platforms, path may also be specified as an open file descriptor.
3244 If this functionality is unavailable, using it raises an exception.
3245If dir_fd is not None, it should be a file descriptor open to a directory,
3246 and path should be relative; path will then be relative to that directory.
3247If follow_symlinks is False, and the last element of the path is a symbolic
3248 link, chown will modify the symbolic link itself instead of the file the
3249 link points to.
3250It is an error to use dir_fd or follow_symlinks when specifying path as
3251 an open file descriptor.
3252dir_fd and follow_symlinks may not be implemented on your platform.
3253 If they are unavailable, using them will raise a NotImplementedError.
3254
3255[clinic start generated code]*/
3256
Larry Hastings2f936352014-08-05 14:04:04 +10003257static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003258os_chown_impl(PyObject *module, path_t *path, uid_t uid, gid_t gid,
Larry Hastings89964c42015-04-14 18:07:59 -04003259 int dir_fd, int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +00003260/*[clinic end generated code: output=4beadab0db5f70cd input=b08c5ec67996a97d]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003261{
3262 int result;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003263
3264#if !(defined(HAVE_LCHOWN) || defined(HAVE_FCHOWNAT))
3265 if (follow_symlinks_specified("chown", follow_symlinks))
Larry Hastings2f936352014-08-05 14:04:04 +10003266 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003267#endif
Larry Hastings2f936352014-08-05 14:04:04 +10003268 if (dir_fd_and_fd_invalid("chown", dir_fd, path->fd) ||
3269 fd_and_follow_symlinks_invalid("chown", path->fd, follow_symlinks))
3270 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003271
3272#ifdef __APPLE__
3273 /*
3274 * This is for Mac OS X 10.3, which doesn't have lchown.
3275 * (But we still have an lchown symbol because of weak-linking.)
3276 * It doesn't have fchownat either. So there's no possibility
3277 * of a graceful failover.
Georg Brandlf7875592012-06-24 13:58:31 +02003278 */
Larry Hastings9cf065c2012-06-22 16:30:09 -07003279 if ((!follow_symlinks) && (lchown == NULL)) {
3280 follow_symlinks_specified("chown", follow_symlinks);
Larry Hastings2f936352014-08-05 14:04:04 +10003281 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003282 }
3283#endif
3284
Victor Stinner8c62be82010-05-06 00:08:46 +00003285 Py_BEGIN_ALLOW_THREADS
Larry Hastings9cf065c2012-06-22 16:30:09 -07003286#ifdef HAVE_FCHOWN
Larry Hastings2f936352014-08-05 14:04:04 +10003287 if (path->fd != -1)
3288 result = fchown(path->fd, uid, gid);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003289 else
3290#endif
3291#ifdef HAVE_LCHOWN
3292 if ((!follow_symlinks) && (dir_fd == DEFAULT_DIR_FD))
Larry Hastings2f936352014-08-05 14:04:04 +10003293 result = lchown(path->narrow, uid, gid);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003294 else
3295#endif
3296#ifdef HAVE_FCHOWNAT
3297 if ((dir_fd != DEFAULT_DIR_FD) || (!follow_symlinks))
Larry Hastings2f936352014-08-05 14:04:04 +10003298 result = fchownat(dir_fd, path->narrow, uid, gid,
Larry Hastings9cf065c2012-06-22 16:30:09 -07003299 follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW);
3300 else
3301#endif
Larry Hastings2f936352014-08-05 14:04:04 +10003302 result = chown(path->narrow, uid, gid);
Victor Stinner8c62be82010-05-06 00:08:46 +00003303 Py_END_ALLOW_THREADS
Larry Hastings9cf065c2012-06-22 16:30:09 -07003304
Larry Hastings2f936352014-08-05 14:04:04 +10003305 if (result)
3306 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003307
Larry Hastings2f936352014-08-05 14:04:04 +10003308 Py_RETURN_NONE;
Guido van Rossumb6775db1994-08-01 11:34:53 +00003309}
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +00003310#endif /* HAVE_CHOWN */
Guido van Rossumb6775db1994-08-01 11:34:53 +00003311
Larry Hastings2f936352014-08-05 14:04:04 +10003312
Christian Heimes4e30a842007-11-30 22:12:06 +00003313#ifdef HAVE_FCHOWN
Larry Hastings2f936352014-08-05 14:04:04 +10003314/*[clinic input]
3315os.fchown
3316
3317 fd: int
3318 uid: uid_t
3319 gid: gid_t
3320
3321Change the owner and group id of the file specified by file descriptor.
3322
3323Equivalent to os.chown(fd, uid, gid).
3324
3325[clinic start generated code]*/
3326
Larry Hastings2f936352014-08-05 14:04:04 +10003327static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003328os_fchown_impl(PyObject *module, int fd, uid_t uid, gid_t gid)
3329/*[clinic end generated code: output=97d21cbd5a4350a6 input=3af544ba1b13a0d7]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003330{
Victor Stinner8c62be82010-05-06 00:08:46 +00003331 int res;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00003332 int async_err = 0;
3333
3334 do {
3335 Py_BEGIN_ALLOW_THREADS
3336 res = fchown(fd, uid, gid);
3337 Py_END_ALLOW_THREADS
3338 } while (res != 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
3339 if (res != 0)
3340 return (!async_err) ? posix_error() : NULL;
3341
Victor Stinner8c62be82010-05-06 00:08:46 +00003342 Py_RETURN_NONE;
Christian Heimes4e30a842007-11-30 22:12:06 +00003343}
3344#endif /* HAVE_FCHOWN */
3345
Larry Hastings2f936352014-08-05 14:04:04 +10003346
Martin v. Löwis0cec0ff2002-07-28 16:33:45 +00003347#ifdef HAVE_LCHOWN
Larry Hastings2f936352014-08-05 14:04:04 +10003348/*[clinic input]
3349os.lchown
3350
3351 path : path_t
3352 uid: uid_t
3353 gid: gid_t
3354
3355Change the owner and group id of path to the numeric uid and gid.
3356
3357This function will not follow symbolic links.
3358Equivalent to os.chown(path, uid, gid, follow_symlinks=False).
3359[clinic start generated code]*/
3360
Larry Hastings2f936352014-08-05 14:04:04 +10003361static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003362os_lchown_impl(PyObject *module, path_t *path, uid_t uid, gid_t gid)
3363/*[clinic end generated code: output=25eaf6af412fdf2f input=b1c6014d563a7161]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003364{
Victor Stinner8c62be82010-05-06 00:08:46 +00003365 int res;
Victor Stinner8c62be82010-05-06 00:08:46 +00003366 Py_BEGIN_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10003367 res = lchown(path->narrow, uid, gid);
Victor Stinner8c62be82010-05-06 00:08:46 +00003368 Py_END_ALLOW_THREADS
Victor Stinner292c8352012-10-30 02:17:38 +01003369 if (res < 0) {
Larry Hastings2f936352014-08-05 14:04:04 +10003370 return path_error(path);
Victor Stinner292c8352012-10-30 02:17:38 +01003371 }
Larry Hastings2f936352014-08-05 14:04:04 +10003372 Py_RETURN_NONE;
Martin v. Löwis0cec0ff2002-07-28 16:33:45 +00003373}
3374#endif /* HAVE_LCHOWN */
3375
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00003376
Barry Warsaw53699e91996-12-10 23:23:01 +00003377static PyObject *
Guido van Rossumf0af3e32008-10-02 18:55:37 +00003378posix_getcwd(int use_bytes)
Mark Hammondc2e85bd2002-10-03 05:10:39 +00003379{
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00003380#ifdef MS_WINDOWS
Miss Islington (bot)63429c82019-06-26 09:14:30 -07003381 wchar_t wbuf[MAXPATHLEN];
3382 wchar_t *wbuf2 = wbuf;
3383 DWORD len;
3384
3385 Py_BEGIN_ALLOW_THREADS
3386 len = GetCurrentDirectoryW(Py_ARRAY_LENGTH(wbuf), wbuf);
3387 /* If the buffer is large enough, len does not include the
3388 terminating \0. If the buffer is too small, len includes
3389 the space needed for the terminator. */
3390 if (len >= Py_ARRAY_LENGTH(wbuf)) {
Miss Islington (bot)68c1c392019-06-28 09:23:06 -07003391 if (len <= PY_SSIZE_T_MAX / sizeof(wchar_t)) {
Victor Stinnerb6404912013-07-07 16:21:41 +02003392 wbuf2 = PyMem_RawMalloc(len * sizeof(wchar_t));
Victor Stinner8c62be82010-05-06 00:08:46 +00003393 }
Miss Islington (bot)63429c82019-06-26 09:14:30 -07003394 else {
3395 wbuf2 = NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00003396 }
Miss Islington (bot)63429c82019-06-26 09:14:30 -07003397 if (wbuf2) {
3398 len = GetCurrentDirectoryW(len, wbuf2);
Victor Stinner8c62be82010-05-06 00:08:46 +00003399 }
Miss Islington (bot)63429c82019-06-26 09:14:30 -07003400 }
3401 Py_END_ALLOW_THREADS
3402
3403 if (!wbuf2) {
3404 PyErr_NoMemory();
3405 return NULL;
3406 }
3407 if (!len) {
Victor Stinnerb024e842012-10-31 22:24:06 +01003408 if (wbuf2 != wbuf)
Victor Stinnerb6404912013-07-07 16:21:41 +02003409 PyMem_RawFree(wbuf2);
Miss Islington (bot)63429c82019-06-26 09:14:30 -07003410 return PyErr_SetFromWindowsErr(0);
Victor Stinner8c62be82010-05-06 00:08:46 +00003411 }
Victor Stinnerf7c5ae22011-11-16 23:43:07 +01003412
Miss Islington (bot)63429c82019-06-26 09:14:30 -07003413 PyObject *resobj = PyUnicode_FromWideChar(wbuf2, len);
3414 if (wbuf2 != wbuf) {
3415 PyMem_RawFree(wbuf2);
3416 }
Mark Hammondc2e85bd2002-10-03 05:10:39 +00003417
Miss Islington (bot)63429c82019-06-26 09:14:30 -07003418 if (use_bytes) {
3419 if (resobj == NULL) {
3420 return NULL;
3421 }
3422 Py_SETREF(resobj, PyUnicode_EncodeFSDefault(resobj));
3423 }
3424
3425 return resobj;
3426#else
3427 const size_t chunk = 1024;
3428
3429 char *buf = NULL;
3430 char *cwd = NULL;
3431 size_t buflen = 0;
3432
Victor Stinner8c62be82010-05-06 00:08:46 +00003433 Py_BEGIN_ALLOW_THREADS
Victor Stinner4403d7d2015-04-25 00:16:10 +02003434 do {
Miss Islington (bot)63429c82019-06-26 09:14:30 -07003435 char *newbuf;
3436 if (buflen <= PY_SSIZE_T_MAX - chunk) {
3437 buflen += chunk;
3438 newbuf = PyMem_RawRealloc(buf, buflen);
3439 }
3440 else {
3441 newbuf = NULL;
3442 }
3443 if (newbuf == NULL) {
3444 PyMem_RawFree(buf);
3445 buf = NULL;
Victor Stinnerc44f7072016-03-14 18:07:53 +01003446 break;
3447 }
Miss Islington (bot)63429c82019-06-26 09:14:30 -07003448 buf = newbuf;
Victor Stinner4403d7d2015-04-25 00:16:10 +02003449
Victor Stinner4403d7d2015-04-25 00:16:10 +02003450 cwd = getcwd(buf, buflen);
3451 } while (cwd == NULL && errno == ERANGE);
Victor Stinner8c62be82010-05-06 00:08:46 +00003452 Py_END_ALLOW_THREADS
Victor Stinner4403d7d2015-04-25 00:16:10 +02003453
Miss Islington (bot)63429c82019-06-26 09:14:30 -07003454 if (buf == NULL) {
3455 return PyErr_NoMemory();
3456 }
Victor Stinner4403d7d2015-04-25 00:16:10 +02003457 if (cwd == NULL) {
3458 PyMem_RawFree(buf);
Victor Stinner8c62be82010-05-06 00:08:46 +00003459 return posix_error();
Victor Stinner4403d7d2015-04-25 00:16:10 +02003460 }
3461
Miss Islington (bot)63429c82019-06-26 09:14:30 -07003462 PyObject *obj;
3463 if (use_bytes) {
Victor Stinner4403d7d2015-04-25 00:16:10 +02003464 obj = PyBytes_FromStringAndSize(buf, strlen(buf));
Miss Islington (bot)63429c82019-06-26 09:14:30 -07003465 }
3466 else {
Victor Stinner4403d7d2015-04-25 00:16:10 +02003467 obj = PyUnicode_DecodeFSDefault(buf);
Miss Islington (bot)63429c82019-06-26 09:14:30 -07003468 }
Victor Stinner4403d7d2015-04-25 00:16:10 +02003469 PyMem_RawFree(buf);
3470
3471 return obj;
Miss Islington (bot)63429c82019-06-26 09:14:30 -07003472#endif /* !MS_WINDOWS */
Mark Hammondc2e85bd2002-10-03 05:10:39 +00003473}
Guido van Rossumf0af3e32008-10-02 18:55:37 +00003474
Larry Hastings2f936352014-08-05 14:04:04 +10003475
3476/*[clinic input]
3477os.getcwd
3478
3479Return a unicode string representing the current working directory.
3480[clinic start generated code]*/
3481
Larry Hastings2f936352014-08-05 14:04:04 +10003482static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003483os_getcwd_impl(PyObject *module)
3484/*[clinic end generated code: output=21badfae2ea99ddc input=f069211bb70e3d39]*/
Guido van Rossumf0af3e32008-10-02 18:55:37 +00003485{
3486 return posix_getcwd(0);
3487}
3488
Larry Hastings2f936352014-08-05 14:04:04 +10003489
3490/*[clinic input]
3491os.getcwdb
3492
3493Return a bytes string representing the current working directory.
3494[clinic start generated code]*/
3495
Larry Hastings2f936352014-08-05 14:04:04 +10003496static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003497os_getcwdb_impl(PyObject *module)
3498/*[clinic end generated code: output=3dd47909480e4824 input=f6f6a378dad3d9cb]*/
Guido van Rossumf0af3e32008-10-02 18:55:37 +00003499{
3500 return posix_getcwd(1);
3501}
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003502
Larry Hastings2f936352014-08-05 14:04:04 +10003503
Larry Hastings9cf065c2012-06-22 16:30:09 -07003504#if ((!defined(HAVE_LINK)) && defined(MS_WINDOWS))
3505#define HAVE_LINK 1
3506#endif
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00003507
Guido van Rossumb6775db1994-08-01 11:34:53 +00003508#ifdef HAVE_LINK
Larry Hastings2f936352014-08-05 14:04:04 +10003509/*[clinic input]
3510
3511os.link
3512
3513 src : path_t
3514 dst : path_t
3515 *
3516 src_dir_fd : dir_fd = None
3517 dst_dir_fd : dir_fd = None
3518 follow_symlinks: bool = True
3519
3520Create a hard link to a file.
3521
3522If either src_dir_fd or dst_dir_fd is not None, it should be a file
3523 descriptor open to a directory, and the respective path string (src or dst)
3524 should be relative; the path will then be relative to that directory.
3525If follow_symlinks is False, and the last element of src is a symbolic
3526 link, link will create a link to the symbolic link itself instead of the
3527 file the link points to.
3528src_dir_fd, dst_dir_fd, and follow_symlinks may not be implemented on your
3529 platform. If they are unavailable, using them will raise a
3530 NotImplementedError.
3531[clinic start generated code]*/
3532
Larry Hastings2f936352014-08-05 14:04:04 +10003533static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003534os_link_impl(PyObject *module, path_t *src, path_t *dst, int src_dir_fd,
Larry Hastings89964c42015-04-14 18:07:59 -04003535 int dst_dir_fd, int follow_symlinks)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003536/*[clinic end generated code: output=7f00f6007fd5269a input=b0095ebbcbaa7e04]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003537{
Larry Hastings9cf065c2012-06-22 16:30:09 -07003538#ifdef MS_WINDOWS
Steve Dowercc16be82016-09-08 10:35:16 -07003539 BOOL result = FALSE;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003540#else
3541 int result;
3542#endif
3543
Larry Hastings9cf065c2012-06-22 16:30:09 -07003544#ifndef HAVE_LINKAT
3545 if ((src_dir_fd != DEFAULT_DIR_FD) || (dst_dir_fd != DEFAULT_DIR_FD)) {
3546 argument_unavailable_error("link", "src_dir_fd and dst_dir_fd");
Larry Hastings2f936352014-08-05 14:04:04 +10003547 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003548 }
3549#endif
3550
Steve Dowercc16be82016-09-08 10:35:16 -07003551#ifndef MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +10003552 if ((src->narrow && dst->wide) || (src->wide && dst->narrow)) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07003553 PyErr_SetString(PyExc_NotImplementedError,
3554 "link: src and dst must be the same type");
Larry Hastings2f936352014-08-05 14:04:04 +10003555 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003556 }
Steve Dowercc16be82016-09-08 10:35:16 -07003557#endif
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003558
Brian Curtin1b9df392010-11-24 20:24:31 +00003559#ifdef MS_WINDOWS
Larry Hastings9cf065c2012-06-22 16:30:09 -07003560 Py_BEGIN_ALLOW_THREADS
Steve Dowerc3630612016-11-19 18:41:16 -08003561 result = CreateHardLinkW(dst->wide, src->wide, NULL);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003562 Py_END_ALLOW_THREADS
Brian Curtin1b9df392010-11-24 20:24:31 +00003563
Larry Hastings2f936352014-08-05 14:04:04 +10003564 if (!result)
3565 return path_error2(src, dst);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003566#else
3567 Py_BEGIN_ALLOW_THREADS
Larry Hastings67cbf7b2012-06-22 17:06:48 -07003568#ifdef HAVE_LINKAT
Larry Hastings9cf065c2012-06-22 16:30:09 -07003569 if ((src_dir_fd != DEFAULT_DIR_FD) ||
3570 (dst_dir_fd != DEFAULT_DIR_FD) ||
3571 (!follow_symlinks))
Larry Hastings2f936352014-08-05 14:04:04 +10003572 result = linkat(src_dir_fd, src->narrow,
3573 dst_dir_fd, dst->narrow,
Larry Hastings9cf065c2012-06-22 16:30:09 -07003574 follow_symlinks ? AT_SYMLINK_FOLLOW : 0);
3575 else
Steve Dowercc16be82016-09-08 10:35:16 -07003576#endif /* HAVE_LINKAT */
Larry Hastings2f936352014-08-05 14:04:04 +10003577 result = link(src->narrow, dst->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003578 Py_END_ALLOW_THREADS
Brian Curtinfc889c42010-11-28 23:59:46 +00003579
Larry Hastings2f936352014-08-05 14:04:04 +10003580 if (result)
3581 return path_error2(src, dst);
Steve Dowercc16be82016-09-08 10:35:16 -07003582#endif /* MS_WINDOWS */
Larry Hastings9cf065c2012-06-22 16:30:09 -07003583
Larry Hastings2f936352014-08-05 14:04:04 +10003584 Py_RETURN_NONE;
Brian Curtin1b9df392010-11-24 20:24:31 +00003585}
Larry Hastings9cf065c2012-06-22 16:30:09 -07003586#endif
3587
Brian Curtin1b9df392010-11-24 20:24:31 +00003588
Gregory P. Smith16ea14a2013-03-20 18:51:33 -07003589#if defined(MS_WINDOWS) && !defined(HAVE_OPENDIR)
Barry Warsaw53699e91996-12-10 23:23:01 +00003590static PyObject *
Gregory P. Smith40a21602013-03-20 20:52:50 -07003591_listdir_windows_no_opendir(path_t *path, PyObject *list)
Guido van Rossumb6775db1994-08-01 11:34:53 +00003592{
Larry Hastings9cf065c2012-06-22 16:30:09 -07003593 PyObject *v;
3594 HANDLE hFindFile = INVALID_HANDLE_VALUE;
3595 BOOL result;
Steve Dowercc16be82016-09-08 10:35:16 -07003596 wchar_t namebuf[MAX_PATH+4]; /* Overallocate for "\*.*" */
Larry Hastings9cf065c2012-06-22 16:30:09 -07003597 /* only claim to have space for MAX_PATH */
Victor Stinner75875072013-11-24 19:23:25 +01003598 Py_ssize_t len = Py_ARRAY_LENGTH(namebuf)-4;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003599 wchar_t *wnamebuf = NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003600
Steve Dowercc16be82016-09-08 10:35:16 -07003601 WIN32_FIND_DATAW wFileData;
3602 const wchar_t *po_wchars;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00003603
Steve Dowercc16be82016-09-08 10:35:16 -07003604 if (!path->wide) { /* Default arg: "." */
3605 po_wchars = L".";
3606 len = 1;
3607 } else {
3608 po_wchars = path->wide;
3609 len = wcslen(path->wide);
3610 }
3611 /* The +5 is so we can append "\\*.*\0" */
3612 wnamebuf = PyMem_New(wchar_t, len + 5);
3613 if (!wnamebuf) {
3614 PyErr_NoMemory();
Larry Hastings9cf065c2012-06-22 16:30:09 -07003615 goto exit;
Victor Stinner8c62be82010-05-06 00:08:46 +00003616 }
Steve Dowercc16be82016-09-08 10:35:16 -07003617 wcscpy(wnamebuf, po_wchars);
Victor Stinner8c62be82010-05-06 00:08:46 +00003618 if (len > 0) {
Steve Dowercc16be82016-09-08 10:35:16 -07003619 wchar_t wch = wnamebuf[len-1];
3620 if (wch != SEP && wch != ALTSEP && wch != L':')
3621 wnamebuf[len++] = SEP;
3622 wcscpy(wnamebuf + len, L"*.*");
Victor Stinner8c62be82010-05-06 00:08:46 +00003623 }
Steve Dowercc16be82016-09-08 10:35:16 -07003624 if ((list = PyList_New(0)) == NULL) {
3625 goto exit;
3626 }
Antoine Pitroub73caab2010-08-09 23:39:31 +00003627 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -07003628 hFindFile = FindFirstFileW(wnamebuf, &wFileData);
Antoine Pitroub73caab2010-08-09 23:39:31 +00003629 Py_END_ALLOW_THREADS
Victor Stinner8c62be82010-05-06 00:08:46 +00003630 if (hFindFile == INVALID_HANDLE_VALUE) {
3631 int error = GetLastError();
3632 if (error == ERROR_FILE_NOT_FOUND)
Larry Hastings9cf065c2012-06-22 16:30:09 -07003633 goto exit;
3634 Py_DECREF(list);
Gregory P. Smith40a21602013-03-20 20:52:50 -07003635 list = path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003636 goto exit;
Victor Stinner8c62be82010-05-06 00:08:46 +00003637 }
3638 do {
3639 /* Skip over . and .. */
Steve Dowercc16be82016-09-08 10:35:16 -07003640 if (wcscmp(wFileData.cFileName, L".") != 0 &&
3641 wcscmp(wFileData.cFileName, L"..") != 0) {
3642 v = PyUnicode_FromWideChar(wFileData.cFileName,
3643 wcslen(wFileData.cFileName));
3644 if (path->narrow && v) {
3645 Py_SETREF(v, PyUnicode_EncodeFSDefault(v));
3646 }
Victor Stinner8c62be82010-05-06 00:08:46 +00003647 if (v == NULL) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07003648 Py_DECREF(list);
3649 list = NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00003650 break;
3651 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07003652 if (PyList_Append(list, v) != 0) {
Victor Stinner8c62be82010-05-06 00:08:46 +00003653 Py_DECREF(v);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003654 Py_DECREF(list);
3655 list = NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00003656 break;
3657 }
3658 Py_DECREF(v);
3659 }
3660 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -07003661 result = FindNextFileW(hFindFile, &wFileData);
Victor Stinner8c62be82010-05-06 00:08:46 +00003662 Py_END_ALLOW_THREADS
3663 /* FindNextFile sets error to ERROR_NO_MORE_FILES if
3664 it got to the end of the directory. */
3665 if (!result && GetLastError() != ERROR_NO_MORE_FILES) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07003666 Py_DECREF(list);
Gregory P. Smith40a21602013-03-20 20:52:50 -07003667 list = path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003668 goto exit;
Victor Stinner8c62be82010-05-06 00:08:46 +00003669 }
3670 } while (result == TRUE);
Guido van Rossumb6775db1994-08-01 11:34:53 +00003671
Larry Hastings9cf065c2012-06-22 16:30:09 -07003672exit:
3673 if (hFindFile != INVALID_HANDLE_VALUE) {
3674 if (FindClose(hFindFile) == FALSE) {
3675 if (list != NULL) {
3676 Py_DECREF(list);
Gregory P. Smith40a21602013-03-20 20:52:50 -07003677 list = path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003678 }
3679 }
Victor Stinner8c62be82010-05-06 00:08:46 +00003680 }
Victor Stinnerb6404912013-07-07 16:21:41 +02003681 PyMem_Free(wnamebuf);
Guido van Rossumb6775db1994-08-01 11:34:53 +00003682
Larry Hastings9cf065c2012-06-22 16:30:09 -07003683 return list;
Gregory P. Smith16ea14a2013-03-20 18:51:33 -07003684} /* end of _listdir_windows_no_opendir */
3685
3686#else /* thus POSIX, ie: not (MS_WINDOWS and not HAVE_OPENDIR) */
3687
3688static PyObject *
Gregory P. Smith40a21602013-03-20 20:52:50 -07003689_posix_listdir(path_t *path, PyObject *list)
Gregory P. Smith16ea14a2013-03-20 18:51:33 -07003690{
Gregory P. Smith16ea14a2013-03-20 18:51:33 -07003691 PyObject *v;
3692 DIR *dirp = NULL;
3693 struct dirent *ep;
3694 int return_str; /* if false, return bytes */
Larry Hastings4dbc95e2013-08-01 18:18:56 -07003695#ifdef HAVE_FDOPENDIR
3696 int fd = -1;
3697#endif
Gregory P. Smith16ea14a2013-03-20 18:51:33 -07003698
Victor Stinner8c62be82010-05-06 00:08:46 +00003699 errno = 0;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003700#ifdef HAVE_FDOPENDIR
Gregory P. Smith40a21602013-03-20 20:52:50 -07003701 if (path->fd != -1) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07003702 /* closedir() closes the FD, so we duplicate it */
Victor Stinnerdaf45552013-08-28 00:53:59 +02003703 fd = _Py_dup(path->fd);
Victor Stinnerf3266652013-12-19 13:24:49 +01003704 if (fd == -1)
3705 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07003706
Larry Hastingsfdaea062012-06-25 04:42:23 -07003707 return_str = 1;
3708
Larry Hastings9cf065c2012-06-22 16:30:09 -07003709 Py_BEGIN_ALLOW_THREADS
3710 dirp = fdopendir(fd);
3711 Py_END_ALLOW_THREADS
3712 }
3713 else
3714#endif
3715 {
Serhiy Storchakadeab18d2016-05-07 16:45:18 +03003716 const char *name;
Gregory P. Smith40a21602013-03-20 20:52:50 -07003717 if (path->narrow) {
3718 name = path->narrow;
Serhiy Storchaka1180e5a2017-07-11 06:36:46 +03003719 /* only return bytes if they specified a bytes-like object */
3720 return_str = !PyObject_CheckBuffer(path->object);
Larry Hastingsfdaea062012-06-25 04:42:23 -07003721 }
3722 else {
3723 name = ".";
3724 return_str = 1;
3725 }
3726
Larry Hastings9cf065c2012-06-22 16:30:09 -07003727 Py_BEGIN_ALLOW_THREADS
3728 dirp = opendir(name);
3729 Py_END_ALLOW_THREADS
3730 }
3731
3732 if (dirp == NULL) {
Gregory P. Smith40a21602013-03-20 20:52:50 -07003733 list = path_error(path);
Larry Hastings4dbc95e2013-08-01 18:18:56 -07003734#ifdef HAVE_FDOPENDIR
3735 if (fd != -1) {
3736 Py_BEGIN_ALLOW_THREADS
3737 close(fd);
3738 Py_END_ALLOW_THREADS
3739 }
3740#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -07003741 goto exit;
3742 }
3743 if ((list = PyList_New(0)) == NULL) {
3744 goto exit;
Victor Stinner8c62be82010-05-06 00:08:46 +00003745 }
3746 for (;;) {
3747 errno = 0;
3748 Py_BEGIN_ALLOW_THREADS
3749 ep = readdir(dirp);
3750 Py_END_ALLOW_THREADS
3751 if (ep == NULL) {
3752 if (errno == 0) {
3753 break;
3754 } else {
Larry Hastings9cf065c2012-06-22 16:30:09 -07003755 Py_DECREF(list);
Gregory P. Smith40a21602013-03-20 20:52:50 -07003756 list = path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003757 goto exit;
Victor Stinner8c62be82010-05-06 00:08:46 +00003758 }
3759 }
3760 if (ep->d_name[0] == '.' &&
3761 (NAMLEN(ep) == 1 ||
3762 (ep->d_name[1] == '.' && NAMLEN(ep) == 2)))
3763 continue;
Larry Hastingsfdaea062012-06-25 04:42:23 -07003764 if (return_str)
Victor Stinnera45598a2010-05-14 16:35:39 +00003765 v = PyUnicode_DecodeFSDefaultAndSize(ep->d_name, NAMLEN(ep));
3766 else
3767 v = PyBytes_FromStringAndSize(ep->d_name, NAMLEN(ep));
Victor Stinner8c62be82010-05-06 00:08:46 +00003768 if (v == NULL) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07003769 Py_CLEAR(list);
Victor Stinner8c62be82010-05-06 00:08:46 +00003770 break;
3771 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07003772 if (PyList_Append(list, v) != 0) {
Victor Stinner8c62be82010-05-06 00:08:46 +00003773 Py_DECREF(v);
Larry Hastings9cf065c2012-06-22 16:30:09 -07003774 Py_CLEAR(list);
Victor Stinner8c62be82010-05-06 00:08:46 +00003775 break;
3776 }
3777 Py_DECREF(v);
3778 }
Guido van Rossum0ee42cd1991-04-08 21:01:03 +00003779
Larry Hastings9cf065c2012-06-22 16:30:09 -07003780exit:
3781 if (dirp != NULL) {
3782 Py_BEGIN_ALLOW_THREADS
Larry Hastings4dbc95e2013-08-01 18:18:56 -07003783#ifdef HAVE_FDOPENDIR
Larry Hastings9cf065c2012-06-22 16:30:09 -07003784 if (fd > -1)
3785 rewinddir(dirp);
Larry Hastings4dbc95e2013-08-01 18:18:56 -07003786#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -07003787 closedir(dirp);
3788 Py_END_ALLOW_THREADS
3789 }
3790
Larry Hastings9cf065c2012-06-22 16:30:09 -07003791 return list;
Gregory P. Smith16ea14a2013-03-20 18:51:33 -07003792} /* end of _posix_listdir */
3793#endif /* which OS */
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +00003794
Larry Hastings2f936352014-08-05 14:04:04 +10003795
3796/*[clinic input]
3797os.listdir
3798
3799 path : path_t(nullable=True, allow_fd='PATH_HAVE_FDOPENDIR') = None
3800
3801Return a list containing the names of the files in the directory.
3802
BNMetricsb9427072018-11-02 15:20:19 +00003803path can be specified as either str, bytes, or a path-like object. If path is bytes,
Larry Hastings2f936352014-08-05 14:04:04 +10003804 the filenames returned will also be bytes; in all other circumstances
3805 the filenames returned will be str.
3806If path is None, uses the path='.'.
3807On some platforms, path may also be specified as an open file descriptor;\
3808 the file descriptor must refer to a directory.
3809 If this functionality is unavailable, using it raises NotImplementedError.
3810
3811The list is in arbitrary order. It does not include the special
3812entries '.' and '..' even if they are present in the directory.
3813
3814
3815[clinic start generated code]*/
3816
Larry Hastings2f936352014-08-05 14:04:04 +10003817static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003818os_listdir_impl(PyObject *module, path_t *path)
BNMetricsb9427072018-11-02 15:20:19 +00003819/*[clinic end generated code: output=293045673fcd1a75 input=e3f58030f538295d]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003820{
Miss Islington (bot)8763d432019-06-24 09:09:47 -07003821 if (PySys_Audit("os.listdir", "O",
3822 path->object ? path->object : Py_None) < 0) {
3823 return NULL;
3824 }
Larry Hastings2f936352014-08-05 14:04:04 +10003825#if defined(MS_WINDOWS) && !defined(HAVE_OPENDIR)
3826 return _listdir_windows_no_opendir(path, NULL);
3827#else
3828 return _posix_listdir(path, NULL);
3829#endif
3830}
3831
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00003832#ifdef MS_WINDOWS
Mark Hammondef8b6542001-05-13 08:04:26 +00003833/* A helper function for abspath on win32 */
Serhiy Storchakaf0b50152015-05-13 00:52:39 +03003834/*[clinic input]
3835os._getfullpathname
Victor Stinnereb5657a2011-09-30 01:44:27 +02003836
Serhiy Storchakaf0b50152015-05-13 00:52:39 +03003837 path: path_t
3838 /
3839
3840[clinic start generated code]*/
3841
3842static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03003843os__getfullpathname_impl(PyObject *module, path_t *path)
3844/*[clinic end generated code: output=bb8679d56845bc9b input=332ed537c29d0a3e]*/
Serhiy Storchakaf0b50152015-05-13 00:52:39 +03003845{
Steve Dowercc16be82016-09-08 10:35:16 -07003846 wchar_t woutbuf[MAX_PATH], *woutbufp = woutbuf;
3847 wchar_t *wtemp;
3848 DWORD result;
3849 PyObject *v;
Victor Stinnereb5657a2011-09-30 01:44:27 +02003850
Steve Dowercc16be82016-09-08 10:35:16 -07003851 result = GetFullPathNameW(path->wide,
3852 Py_ARRAY_LENGTH(woutbuf),
3853 woutbuf, &wtemp);
3854 if (result > Py_ARRAY_LENGTH(woutbuf)) {
3855 woutbufp = PyMem_New(wchar_t, result);
3856 if (!woutbufp)
3857 return PyErr_NoMemory();
3858 result = GetFullPathNameW(path->wide, result, woutbufp, &wtemp);
Victor Stinner8c62be82010-05-06 00:08:46 +00003859 }
Steve Dowercc16be82016-09-08 10:35:16 -07003860 if (result) {
3861 v = PyUnicode_FromWideChar(woutbufp, wcslen(woutbufp));
3862 if (path->narrow)
3863 Py_SETREF(v, PyUnicode_EncodeFSDefault(v));
3864 } else
3865 v = win32_error_object("GetFullPathNameW", path->object);
3866 if (woutbufp != woutbuf)
3867 PyMem_Free(woutbufp);
3868 return v;
Larry Hastings2f936352014-08-05 14:04:04 +10003869}
Brian Curtind40e6f72010-07-08 21:39:08 +00003870
Brian Curtind25aef52011-06-13 15:16:04 -05003871
Larry Hastings2f936352014-08-05 14:04:04 +10003872/*[clinic input]
3873os._getfinalpathname
Brian Curtinf5e76d02010-11-24 13:14:05 +00003874
Steve Dower23ad6d02018-02-22 10:39:10 -08003875 path: path_t
Larry Hastings2f936352014-08-05 14:04:04 +10003876 /
3877
3878A helper function for samepath on windows.
3879[clinic start generated code]*/
3880
Larry Hastings2f936352014-08-05 14:04:04 +10003881static PyObject *
Steve Dower23ad6d02018-02-22 10:39:10 -08003882os__getfinalpathname_impl(PyObject *module, path_t *path)
3883/*[clinic end generated code: output=621a3c79bc29ebfa input=2b6b6c7cbad5fb84]*/
Brian Curtind40e6f72010-07-08 21:39:08 +00003884{
3885 HANDLE hFile;
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03003886 wchar_t buf[MAXPATHLEN], *target_path = buf;
3887 int buf_size = Py_ARRAY_LENGTH(buf);
Brian Curtind40e6f72010-07-08 21:39:08 +00003888 int result_length;
Larry Hastings2f936352014-08-05 14:04:04 +10003889 PyObject *result;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00003890
Steve Dower23ad6d02018-02-22 10:39:10 -08003891 Py_BEGIN_ALLOW_THREADS
Brian Curtind40e6f72010-07-08 21:39:08 +00003892 hFile = CreateFileW(
Steve Dower23ad6d02018-02-22 10:39:10 -08003893 path->wide,
Brian Curtind40e6f72010-07-08 21:39:08 +00003894 0, /* desired access */
3895 0, /* share mode */
3896 NULL, /* security attributes */
3897 OPEN_EXISTING,
3898 /* FILE_FLAG_BACKUP_SEMANTICS is required to open a directory */
3899 FILE_FLAG_BACKUP_SEMANTICS,
3900 NULL);
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03003901 Py_END_ALLOW_THREADS
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00003902
Steve Dower23ad6d02018-02-22 10:39:10 -08003903 if (hFile == INVALID_HANDLE_VALUE) {
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03003904 return win32_error_object("CreateFileW", path->object);
Steve Dower23ad6d02018-02-22 10:39:10 -08003905 }
Brian Curtind40e6f72010-07-08 21:39:08 +00003906
3907 /* We have a good handle to the target, use it to determine the
3908 target path name. */
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03003909 while (1) {
3910 Py_BEGIN_ALLOW_THREADS
3911 result_length = GetFinalPathNameByHandleW(hFile, target_path,
3912 buf_size, VOLUME_NAME_DOS);
3913 Py_END_ALLOW_THREADS
Brian Curtind40e6f72010-07-08 21:39:08 +00003914
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03003915 if (!result_length) {
3916 result = win32_error_object("GetFinalPathNameByHandleW",
3917 path->object);
3918 goto cleanup;
3919 }
Brian Curtind40e6f72010-07-08 21:39:08 +00003920
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03003921 if (result_length < buf_size) {
3922 break;
3923 }
Brian Curtind40e6f72010-07-08 21:39:08 +00003924
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03003925 wchar_t *tmp;
3926 tmp = PyMem_Realloc(target_path != buf ? target_path : NULL,
3927 result_length * sizeof(*tmp));
3928 if (!tmp) {
3929 result = PyErr_NoMemory();
3930 goto cleanup;
3931 }
3932
3933 buf_size = result_length;
3934 target_path = tmp;
Steve Dower23ad6d02018-02-22 10:39:10 -08003935 }
Brian Curtind40e6f72010-07-08 21:39:08 +00003936
Victor Stinner9d3b93b2011-11-22 02:27:30 +01003937 result = PyUnicode_FromWideChar(target_path, result_length);
Steve Dower9eb3d542019-08-21 15:52:42 -07003938 if (result && path->narrow) {
Steve Dower23ad6d02018-02-22 10:39:10 -08003939 Py_SETREF(result, PyUnicode_EncodeFSDefault(result));
Steve Dower9eb3d542019-08-21 15:52:42 -07003940 }
Steve Dower23ad6d02018-02-22 10:39:10 -08003941
Alexey Izbyshev3b20d342018-03-08 19:03:25 +03003942cleanup:
3943 if (target_path != buf) {
3944 PyMem_Free(target_path);
3945 }
3946 CloseHandle(hFile);
3947 return result;
Larry Hastings2f936352014-08-05 14:04:04 +10003948}
Brian Curtin62857742010-09-06 17:07:27 +00003949
Tim Golden6b528062013-08-01 12:44:00 +01003950
Larry Hastings2f936352014-08-05 14:04:04 +10003951/*[clinic input]
3952os._getvolumepathname
3953
Steve Dower23ad6d02018-02-22 10:39:10 -08003954 path: path_t
Larry Hastings2f936352014-08-05 14:04:04 +10003955
3956A helper function for ismount on Win32.
3957[clinic start generated code]*/
3958
Larry Hastings2f936352014-08-05 14:04:04 +10003959static PyObject *
Steve Dower23ad6d02018-02-22 10:39:10 -08003960os__getvolumepathname_impl(PyObject *module, path_t *path)
3961/*[clinic end generated code: output=804c63fd13a1330b input=722b40565fa21552]*/
Larry Hastings2f936352014-08-05 14:04:04 +10003962{
3963 PyObject *result;
Serhiy Storchakadeab18d2016-05-07 16:45:18 +03003964 wchar_t *mountpath=NULL;
Victor Stinner6edddfa2013-11-24 19:22:57 +01003965 size_t buflen;
Tim Golden6b528062013-08-01 12:44:00 +01003966 BOOL ret;
3967
Tim Golden6b528062013-08-01 12:44:00 +01003968 /* Volume path should be shorter than entire path */
Steve Dower23ad6d02018-02-22 10:39:10 -08003969 buflen = Py_MAX(path->length, MAX_PATH);
Victor Stinner6edddfa2013-11-24 19:22:57 +01003970
Victor Stinner850a18e2017-10-24 16:53:32 -07003971 if (buflen > PY_DWORD_MAX) {
Victor Stinner6edddfa2013-11-24 19:22:57 +01003972 PyErr_SetString(PyExc_OverflowError, "path too long");
3973 return NULL;
3974 }
3975
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02003976 mountpath = PyMem_New(wchar_t, buflen);
Tim Golden6b528062013-08-01 12:44:00 +01003977 if (mountpath == NULL)
3978 return PyErr_NoMemory();
3979
3980 Py_BEGIN_ALLOW_THREADS
Steve Dower23ad6d02018-02-22 10:39:10 -08003981 ret = GetVolumePathNameW(path->wide, mountpath,
Victor Stinner6edddfa2013-11-24 19:22:57 +01003982 Py_SAFE_DOWNCAST(buflen, size_t, DWORD));
Tim Golden6b528062013-08-01 12:44:00 +01003983 Py_END_ALLOW_THREADS
3984
3985 if (!ret) {
Steve Dower23ad6d02018-02-22 10:39:10 -08003986 result = win32_error_object("_getvolumepathname", path->object);
Tim Golden6b528062013-08-01 12:44:00 +01003987 goto exit;
3988 }
3989 result = PyUnicode_FromWideChar(mountpath, wcslen(mountpath));
Steve Dower23ad6d02018-02-22 10:39:10 -08003990 if (path->narrow)
3991 Py_SETREF(result, PyUnicode_EncodeFSDefault(result));
Tim Golden6b528062013-08-01 12:44:00 +01003992
3993exit:
3994 PyMem_Free(mountpath);
3995 return result;
3996}
Tim Golden6b528062013-08-01 12:44:00 +01003997
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00003998#endif /* MS_WINDOWS */
Mark Hammondef8b6542001-05-13 08:04:26 +00003999
Larry Hastings2f936352014-08-05 14:04:04 +10004000
4001/*[clinic input]
4002os.mkdir
4003
4004 path : path_t
4005
4006 mode: int = 0o777
4007
4008 *
4009
4010 dir_fd : dir_fd(requires='mkdirat') = None
4011
4012# "mkdir(path, mode=0o777, *, dir_fd=None)\n\n\
4013
4014Create a directory.
4015
4016If dir_fd is not None, it should be a file descriptor open to a directory,
4017 and path should be relative; path will then be relative to that directory.
4018dir_fd may not be implemented on your platform.
4019 If it is unavailable, using it will raise a NotImplementedError.
4020
4021The mode argument is ignored on Windows.
4022[clinic start generated code]*/
4023
Larry Hastings2f936352014-08-05 14:04:04 +10004024static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004025os_mkdir_impl(PyObject *module, path_t *path, int mode, int dir_fd)
4026/*[clinic end generated code: output=a70446903abe821f input=e965f68377e9b1ce]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004027{
4028 int result;
Mark Hammondc2e85bd2002-10-03 05:10:39 +00004029
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00004030#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +00004031 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -07004032 result = CreateDirectoryW(path->wide, NULL);
Victor Stinner8c62be82010-05-06 00:08:46 +00004033 Py_END_ALLOW_THREADS
Mark Hammondc2e85bd2002-10-03 05:10:39 +00004034
Larry Hastings2f936352014-08-05 14:04:04 +10004035 if (!result)
4036 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004037#else
Victor Stinner8c62be82010-05-06 00:08:46 +00004038 Py_BEGIN_ALLOW_THREADS
Larry Hastings9cf065c2012-06-22 16:30:09 -07004039#if HAVE_MKDIRAT
4040 if (dir_fd != DEFAULT_DIR_FD)
Larry Hastings2f936352014-08-05 14:04:04 +10004041 result = mkdirat(dir_fd, path->narrow, mode);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004042 else
4043#endif
Erik Bray03eb11f2017-10-27 14:27:06 +02004044#if defined(__WATCOMC__) && !defined(__QNX__)
Larry Hastings2f936352014-08-05 14:04:04 +10004045 result = mkdir(path->narrow);
Guido van Rossuma4916fa1996-05-23 22:58:55 +00004046#else
Larry Hastings2f936352014-08-05 14:04:04 +10004047 result = mkdir(path->narrow, mode);
Guido van Rossuma4916fa1996-05-23 22:58:55 +00004048#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00004049 Py_END_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10004050 if (result < 0)
4051 return path_error(path);
Steve Dowercc16be82016-09-08 10:35:16 -07004052#endif /* MS_WINDOWS */
Larry Hastings2f936352014-08-05 14:04:04 +10004053 Py_RETURN_NONE;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00004054}
4055
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00004056
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004057/* sys/resource.h is needed for at least: wait3(), wait4(), broken nice. */
4058#if defined(HAVE_SYS_RESOURCE_H)
Thomas Wouterse38b2f12001-07-11 22:35:31 +00004059#include <sys/resource.h>
4060#endif
Thomas Wouterse38b2f12001-07-11 22:35:31 +00004061
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004062
4063#ifdef HAVE_NICE
Larry Hastings2f936352014-08-05 14:04:04 +10004064/*[clinic input]
4065os.nice
4066
4067 increment: int
4068 /
4069
4070Add increment to the priority of process and return the new priority.
4071[clinic start generated code]*/
4072
Larry Hastings2f936352014-08-05 14:04:04 +10004073static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004074os_nice_impl(PyObject *module, int increment)
4075/*[clinic end generated code: output=9dad8a9da8109943 input=864be2d402a21da2]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004076{
4077 int value;
Thomas Woutersc2c12dc2001-07-11 14:45:34 +00004078
Victor Stinner8c62be82010-05-06 00:08:46 +00004079 /* There are two flavours of 'nice': one that returns the new
4080 priority (as required by almost all standards out there) and the
Benjamin Peterson288d1da2017-09-28 22:44:27 -07004081 Linux/FreeBSD one, which returns '0' on success and advices
Victor Stinner8c62be82010-05-06 00:08:46 +00004082 the use of getpriority() to get the new priority.
Tim Peters5aa91602002-01-30 05:46:57 +00004083
Victor Stinner8c62be82010-05-06 00:08:46 +00004084 If we are of the nice family that returns the new priority, we
4085 need to clear errno before the call, and check if errno is filled
4086 before calling posix_error() on a returnvalue of -1, because the
4087 -1 may be the actual new priority! */
Thomas Woutersc2c12dc2001-07-11 14:45:34 +00004088
Victor Stinner8c62be82010-05-06 00:08:46 +00004089 errno = 0;
4090 value = nice(increment);
Thomas Wouterse38b2f12001-07-11 22:35:31 +00004091#if defined(HAVE_BROKEN_NICE) && defined(HAVE_GETPRIORITY)
Victor Stinner8c62be82010-05-06 00:08:46 +00004092 if (value == 0)
4093 value = getpriority(PRIO_PROCESS, 0);
Thomas Woutersc2c12dc2001-07-11 14:45:34 +00004094#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00004095 if (value == -1 && errno != 0)
4096 /* either nice() or getpriority() returned an error */
4097 return posix_error();
4098 return PyLong_FromLong((long) value);
Guido van Rossum775f4da1993-01-09 17:18:52 +00004099}
Guido van Rossumb6775db1994-08-01 11:34:53 +00004100#endif /* HAVE_NICE */
Guido van Rossum1ff6cb41991-04-08 20:59:13 +00004101
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00004102
4103#ifdef HAVE_GETPRIORITY
Larry Hastings2f936352014-08-05 14:04:04 +10004104/*[clinic input]
4105os.getpriority
4106
4107 which: int
4108 who: int
4109
4110Return program scheduling priority.
4111[clinic start generated code]*/
4112
Larry Hastings2f936352014-08-05 14:04:04 +10004113static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004114os_getpriority_impl(PyObject *module, int which, int who)
4115/*[clinic end generated code: output=c41b7b63c7420228 input=9be615d40e2544ef]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004116{
4117 int retval;
4118
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00004119 errno = 0;
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00004120 retval = getpriority(which, who);
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00004121 if (errno != 0)
4122 return posix_error();
4123 return PyLong_FromLong((long)retval);
4124}
4125#endif /* HAVE_GETPRIORITY */
4126
4127
4128#ifdef HAVE_SETPRIORITY
Larry Hastings2f936352014-08-05 14:04:04 +10004129/*[clinic input]
4130os.setpriority
4131
4132 which: int
4133 who: int
4134 priority: int
4135
4136Set program scheduling priority.
4137[clinic start generated code]*/
4138
Larry Hastings2f936352014-08-05 14:04:04 +10004139static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004140os_setpriority_impl(PyObject *module, int which, int who, int priority)
4141/*[clinic end generated code: output=3d910d95a7771eb2 input=710ccbf65b9dc513]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004142{
4143 int retval;
4144
4145 retval = setpriority(which, who, priority);
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00004146 if (retval == -1)
4147 return posix_error();
4148 Py_RETURN_NONE;
4149}
4150#endif /* HAVE_SETPRIORITY */
4151
4152
Barry Warsaw53699e91996-12-10 23:23:01 +00004153static PyObject *
Larry Hastings2f936352014-08-05 14:04:04 +10004154internal_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 +00004155{
Serhiy Storchakadeab18d2016-05-07 16:45:18 +03004156 const char *function_name = is_replace ? "replace" : "rename";
Larry Hastings9cf065c2012-06-22 16:30:09 -07004157 int dir_fd_specified;
Larry Hastings9cf065c2012-06-22 16:30:09 -07004158
Mark Hammondc2e85bd2002-10-03 05:10:39 +00004159#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +00004160 BOOL result;
Antoine Pitrouf3b2d882012-01-30 22:08:52 +01004161 int flags = is_replace ? MOVEFILE_REPLACE_EXISTING : 0;
Mark Hammondc2e85bd2002-10-03 05:10:39 +00004162#else
Larry Hastings9cf065c2012-06-22 16:30:09 -07004163 int result;
Mark Hammondc2e85bd2002-10-03 05:10:39 +00004164#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -07004165
Larry Hastings9cf065c2012-06-22 16:30:09 -07004166 dir_fd_specified = (src_dir_fd != DEFAULT_DIR_FD) ||
4167 (dst_dir_fd != DEFAULT_DIR_FD);
4168#ifndef HAVE_RENAMEAT
4169 if (dir_fd_specified) {
4170 argument_unavailable_error(function_name, "src_dir_fd and dst_dir_fd");
Larry Hastings2f936352014-08-05 14:04:04 +10004171 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07004172 }
4173#endif
4174
Larry Hastings9cf065c2012-06-22 16:30:09 -07004175#ifdef MS_WINDOWS
4176 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -07004177 result = MoveFileExW(src->wide, dst->wide, flags);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004178 Py_END_ALLOW_THREADS
4179
Larry Hastings2f936352014-08-05 14:04:04 +10004180 if (!result)
4181 return path_error2(src, dst);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004182
4183#else
Steve Dowercc16be82016-09-08 10:35:16 -07004184 if ((src->narrow && dst->wide) || (src->wide && dst->narrow)) {
4185 PyErr_Format(PyExc_ValueError,
4186 "%s: src and dst must be the same type", function_name);
4187 return NULL;
4188 }
4189
Larry Hastings9cf065c2012-06-22 16:30:09 -07004190 Py_BEGIN_ALLOW_THREADS
4191#ifdef HAVE_RENAMEAT
4192 if (dir_fd_specified)
Larry Hastings2f936352014-08-05 14:04:04 +10004193 result = renameat(src_dir_fd, src->narrow, dst_dir_fd, dst->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004194 else
4195#endif
Steve Dowercc16be82016-09-08 10:35:16 -07004196 result = rename(src->narrow, dst->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004197 Py_END_ALLOW_THREADS
4198
Larry Hastings2f936352014-08-05 14:04:04 +10004199 if (result)
4200 return path_error2(src, dst);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004201#endif
Larry Hastings2f936352014-08-05 14:04:04 +10004202 Py_RETURN_NONE;
4203}
Larry Hastings9cf065c2012-06-22 16:30:09 -07004204
Larry Hastings2f936352014-08-05 14:04:04 +10004205
4206/*[clinic input]
4207os.rename
4208
4209 src : path_t
4210 dst : path_t
4211 *
4212 src_dir_fd : dir_fd = None
4213 dst_dir_fd : dir_fd = None
4214
4215Rename a file or directory.
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.
4221 If they are unavailable, using them will raise a NotImplementedError.
4222[clinic start generated code]*/
4223
Antoine Pitrouf3b2d882012-01-30 22:08:52 +01004224static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004225os_rename_impl(PyObject *module, path_t *src, path_t *dst, int src_dir_fd,
Larry Hastings89964c42015-04-14 18:07:59 -04004226 int dst_dir_fd)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004227/*[clinic end generated code: output=59e803072cf41230 input=faa61c847912c850]*/
Antoine Pitrouf3b2d882012-01-30 22:08:52 +01004228{
Larry Hastings2f936352014-08-05 14:04:04 +10004229 return internal_rename(src, dst, src_dir_fd, dst_dir_fd, 0);
Antoine Pitrouf3b2d882012-01-30 22:08:52 +01004230}
4231
Larry Hastings2f936352014-08-05 14:04:04 +10004232
4233/*[clinic input]
4234os.replace = os.rename
4235
4236Rename a file or directory, overwriting the destination.
4237
4238If either src_dir_fd or dst_dir_fd is not None, it should be a file
4239 descriptor open to a directory, and the respective path string (src or dst)
4240 should be relative; the path will then be relative to that directory.
4241src_dir_fd and dst_dir_fd, may not be implemented on your platform.
Anthony Sottile73d60022019-02-12 23:15:54 -05004242 If they are unavailable, using them will raise a NotImplementedError.
Larry Hastings2f936352014-08-05 14:04:04 +10004243[clinic start generated code]*/
4244
Larry Hastings2f936352014-08-05 14:04:04 +10004245static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004246os_replace_impl(PyObject *module, path_t *src, path_t *dst, int src_dir_fd,
4247 int dst_dir_fd)
Anthony Sottile73d60022019-02-12 23:15:54 -05004248/*[clinic end generated code: output=1968c02e7857422b input=c003f0def43378ef]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004249{
4250 return internal_rename(src, dst, src_dir_fd, dst_dir_fd, 1);
4251}
4252
4253
4254/*[clinic input]
4255os.rmdir
4256
4257 path: path_t
4258 *
4259 dir_fd: dir_fd(requires='unlinkat') = None
4260
4261Remove a directory.
4262
4263If dir_fd is not None, it should be a file descriptor open to a directory,
4264 and path should be relative; path will then be relative to that directory.
4265dir_fd may not be implemented on your platform.
4266 If it is unavailable, using it will raise a NotImplementedError.
4267[clinic start generated code]*/
4268
Larry Hastings2f936352014-08-05 14:04:04 +10004269static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004270os_rmdir_impl(PyObject *module, path_t *path, int dir_fd)
4271/*[clinic end generated code: output=080eb54f506e8301 input=38c8b375ca34a7e2]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004272{
4273 int result;
Larry Hastingsb698d8e2012-06-23 16:55:07 -07004274
4275 Py_BEGIN_ALLOW_THREADS
4276#ifdef MS_WINDOWS
Steve Dowercc16be82016-09-08 10:35:16 -07004277 /* Windows, success=1, UNIX, success=0 */
4278 result = !RemoveDirectoryW(path->wide);
Larry Hastingsb698d8e2012-06-23 16:55:07 -07004279#else
4280#ifdef HAVE_UNLINKAT
4281 if (dir_fd != DEFAULT_DIR_FD)
Larry Hastings2f936352014-08-05 14:04:04 +10004282 result = unlinkat(dir_fd, path->narrow, AT_REMOVEDIR);
Larry Hastingsb698d8e2012-06-23 16:55:07 -07004283 else
4284#endif
Larry Hastings2f936352014-08-05 14:04:04 +10004285 result = rmdir(path->narrow);
Larry Hastingsb698d8e2012-06-23 16:55:07 -07004286#endif
4287 Py_END_ALLOW_THREADS
4288
Larry Hastings2f936352014-08-05 14:04:04 +10004289 if (result)
4290 return path_error(path);
Larry Hastingsb698d8e2012-06-23 16:55:07 -07004291
Larry Hastings2f936352014-08-05 14:04:04 +10004292 Py_RETURN_NONE;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00004293}
4294
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00004295
Guido van Rossuma4916fa1996-05-23 22:58:55 +00004296#ifdef HAVE_SYSTEM
Larry Hastings2f936352014-08-05 14:04:04 +10004297#ifdef MS_WINDOWS
4298/*[clinic input]
4299os.system -> long
4300
4301 command: Py_UNICODE
4302
4303Execute the command in a subshell.
4304[clinic start generated code]*/
4305
Larry Hastings2f936352014-08-05 14:04:04 +10004306static long
Serhiy Storchakaafb3e712018-12-14 11:19:51 +02004307os_system_impl(PyObject *module, const Py_UNICODE *command)
4308/*[clinic end generated code: output=5b7c3599c068ca42 input=303f5ce97df606b0]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004309{
4310 long result;
Steve Dowerb82e17e2019-05-23 08:45:22 -07004311
4312 if (PySys_Audit("system", "(u)", command) < 0) {
4313 return -1;
4314 }
4315
Victor Stinner8c62be82010-05-06 00:08:46 +00004316 Py_BEGIN_ALLOW_THREADS
Steve Dowerc3630612016-11-19 18:41:16 -08004317 _Py_BEGIN_SUPPRESS_IPH
Larry Hastings2f936352014-08-05 14:04:04 +10004318 result = _wsystem(command);
Steve Dowerc3630612016-11-19 18:41:16 -08004319 _Py_END_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00004320 Py_END_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10004321 return result;
4322}
4323#else /* MS_WINDOWS */
4324/*[clinic input]
4325os.system -> long
4326
4327 command: FSConverter
4328
4329Execute the command in a subshell.
4330[clinic start generated code]*/
4331
Larry Hastings2f936352014-08-05 14:04:04 +10004332static long
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004333os_system_impl(PyObject *module, PyObject *command)
4334/*[clinic end generated code: output=290fc437dd4f33a0 input=86a58554ba6094af]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004335{
4336 long result;
Serhiy Storchakadeab18d2016-05-07 16:45:18 +03004337 const char *bytes = PyBytes_AsString(command);
Steve Dowerb82e17e2019-05-23 08:45:22 -07004338
4339 if (PySys_Audit("system", "(O)", command) < 0) {
4340 return -1;
4341 }
4342
Larry Hastings2f936352014-08-05 14:04:04 +10004343 Py_BEGIN_ALLOW_THREADS
4344 result = system(bytes);
4345 Py_END_ALLOW_THREADS
4346 return result;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00004347}
Guido van Rossuma4916fa1996-05-23 22:58:55 +00004348#endif
Larry Hastings2f936352014-08-05 14:04:04 +10004349#endif /* HAVE_SYSTEM */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00004350
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00004351
Larry Hastings2f936352014-08-05 14:04:04 +10004352/*[clinic input]
4353os.umask
4354
4355 mask: int
4356 /
4357
4358Set the current numeric umask and return the previous umask.
4359[clinic start generated code]*/
4360
Larry Hastings2f936352014-08-05 14:04:04 +10004361static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004362os_umask_impl(PyObject *module, int mask)
4363/*[clinic end generated code: output=a2e33ce3bc1a6e33 input=ab6bfd9b24d8a7e8]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004364{
4365 int i = (int)umask(mask);
Victor Stinner8c62be82010-05-06 00:08:46 +00004366 if (i < 0)
4367 return posix_error();
4368 return PyLong_FromLong((long)i);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00004369}
4370
Brian Curtind40e6f72010-07-08 21:39:08 +00004371#ifdef MS_WINDOWS
4372
4373/* override the default DeleteFileW behavior so that directory
4374symlinks can be removed with this function, the same as with
4375Unix symlinks */
4376BOOL WINAPI Py_DeleteFileW(LPCWSTR lpFileName)
4377{
4378 WIN32_FILE_ATTRIBUTE_DATA info;
4379 WIN32_FIND_DATAW find_data;
4380 HANDLE find_data_handle;
4381 int is_directory = 0;
4382 int is_link = 0;
4383
4384 if (GetFileAttributesExW(lpFileName, GetFileExInfoStandard, &info)) {
4385 is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00004386
Brian Curtind40e6f72010-07-08 21:39:08 +00004387 /* Get WIN32_FIND_DATA structure for the path to determine if
4388 it is a symlink */
4389 if(is_directory &&
4390 info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
4391 find_data_handle = FindFirstFileW(lpFileName, &find_data);
4392
4393 if(find_data_handle != INVALID_HANDLE_VALUE) {
Tim Golden0321cf22014-05-05 19:46:17 +01004394 /* IO_REPARSE_TAG_SYMLINK if it is a symlink and
4395 IO_REPARSE_TAG_MOUNT_POINT if it is a junction point. */
4396 is_link = find_data.dwReserved0 == IO_REPARSE_TAG_SYMLINK ||
4397 find_data.dwReserved0 == IO_REPARSE_TAG_MOUNT_POINT;
Brian Curtind40e6f72010-07-08 21:39:08 +00004398 FindClose(find_data_handle);
4399 }
4400 }
4401 }
4402
4403 if (is_directory && is_link)
4404 return RemoveDirectoryW(lpFileName);
4405
4406 return DeleteFileW(lpFileName);
4407}
4408#endif /* MS_WINDOWS */
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00004409
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00004410
Larry Hastings2f936352014-08-05 14:04:04 +10004411/*[clinic input]
4412os.unlink
4413
4414 path: path_t
4415 *
4416 dir_fd: dir_fd(requires='unlinkat')=None
4417
4418Remove a file (same as remove()).
4419
4420If dir_fd is not None, it should be a file descriptor open to a directory,
4421 and path should be relative; path will then be relative to that directory.
4422dir_fd may not be implemented on your platform.
4423 If it is unavailable, using it will raise a NotImplementedError.
4424
4425[clinic start generated code]*/
4426
Larry Hastings2f936352014-08-05 14:04:04 +10004427static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004428os_unlink_impl(PyObject *module, path_t *path, int dir_fd)
4429/*[clinic end generated code: output=621797807b9963b1 input=d7bcde2b1b2a2552]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004430{
4431 int result;
Larry Hastings9cf065c2012-06-22 16:30:09 -07004432
4433 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04004434 _Py_BEGIN_SUPPRESS_IPH
Larry Hastings9cf065c2012-06-22 16:30:09 -07004435#ifdef MS_WINDOWS
Steve Dowercc16be82016-09-08 10:35:16 -07004436 /* Windows, success=1, UNIX, success=0 */
4437 result = !Py_DeleteFileW(path->wide);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004438#else
Larry Hastings9cf065c2012-06-22 16:30:09 -07004439#ifdef HAVE_UNLINKAT
4440 if (dir_fd != DEFAULT_DIR_FD)
Larry Hastings2f936352014-08-05 14:04:04 +10004441 result = unlinkat(dir_fd, path->narrow, 0);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004442 else
4443#endif /* HAVE_UNLINKAT */
Larry Hastings2f936352014-08-05 14:04:04 +10004444 result = unlink(path->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004445#endif
Steve Dower8fc89802015-04-12 00:26:27 -04004446 _Py_END_SUPPRESS_IPH
Larry Hastings9cf065c2012-06-22 16:30:09 -07004447 Py_END_ALLOW_THREADS
4448
Larry Hastings2f936352014-08-05 14:04:04 +10004449 if (result)
4450 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004451
Larry Hastings2f936352014-08-05 14:04:04 +10004452 Py_RETURN_NONE;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00004453}
4454
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00004455
Larry Hastings2f936352014-08-05 14:04:04 +10004456/*[clinic input]
4457os.remove = os.unlink
4458
4459Remove a file (same as unlink()).
4460
4461If dir_fd is not None, it should be a file descriptor open to a directory,
4462 and path should be relative; path will then be relative to that directory.
4463dir_fd may not be implemented on your platform.
4464 If it is unavailable, using it will raise a NotImplementedError.
4465[clinic start generated code]*/
4466
Larry Hastings2f936352014-08-05 14:04:04 +10004467static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004468os_remove_impl(PyObject *module, path_t *path, int dir_fd)
4469/*[clinic end generated code: output=a8535b28f0068883 input=e05c5ab55cd30983]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004470{
4471 return os_unlink_impl(module, path, dir_fd);
4472}
4473
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00004474
Larry Hastings605a62d2012-06-24 04:33:36 -07004475static PyStructSequence_Field uname_result_fields[] = {
4476 {"sysname", "operating system name"},
4477 {"nodename", "name of machine on network (implementation-defined)"},
4478 {"release", "operating system release"},
4479 {"version", "operating system version"},
4480 {"machine", "hardware identifier"},
4481 {NULL}
4482};
4483
4484PyDoc_STRVAR(uname_result__doc__,
4485"uname_result: Result from os.uname().\n\n\
4486This object may be accessed either as a tuple of\n\
4487 (sysname, nodename, release, version, machine),\n\
4488or via the attributes sysname, nodename, release, version, and machine.\n\
4489\n\
4490See os.uname for more information.");
4491
4492static PyStructSequence_Desc uname_result_desc = {
4493 "uname_result", /* name */
4494 uname_result__doc__, /* doc */
4495 uname_result_fields,
4496 5
4497};
4498
Eddie Elizondo474eedf2018-11-13 04:09:31 -08004499static PyTypeObject* UnameResultType;
Larry Hastings605a62d2012-06-24 04:33:36 -07004500
4501
4502#ifdef HAVE_UNAME
Larry Hastings2f936352014-08-05 14:04:04 +10004503/*[clinic input]
4504os.uname
4505
4506Return an object identifying the current operating system.
4507
4508The object behaves like a named tuple with the following fields:
4509 (sysname, nodename, release, version, machine)
4510
4511[clinic start generated code]*/
4512
Larry Hastings2f936352014-08-05 14:04:04 +10004513static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004514os_uname_impl(PyObject *module)
4515/*[clinic end generated code: output=e6a49cf1a1508a19 input=e68bd246db3043ed]*/
Guido van Rossumc39de5f1992-02-05 11:15:54 +00004516{
Victor Stinner8c62be82010-05-06 00:08:46 +00004517 struct utsname u;
4518 int res;
Larry Hastings605a62d2012-06-24 04:33:36 -07004519 PyObject *value;
Neal Norwitze241ce82003-02-17 18:17:05 +00004520
Victor Stinner8c62be82010-05-06 00:08:46 +00004521 Py_BEGIN_ALLOW_THREADS
4522 res = uname(&u);
4523 Py_END_ALLOW_THREADS
4524 if (res < 0)
4525 return posix_error();
Larry Hastings605a62d2012-06-24 04:33:36 -07004526
Eddie Elizondo474eedf2018-11-13 04:09:31 -08004527 value = PyStructSequence_New(UnameResultType);
Larry Hastings605a62d2012-06-24 04:33:36 -07004528 if (value == NULL)
4529 return NULL;
4530
4531#define SET(i, field) \
4532 { \
Victor Stinnera534fc42013-06-03 22:07:27 +02004533 PyObject *o = PyUnicode_DecodeFSDefault(field); \
Larry Hastings605a62d2012-06-24 04:33:36 -07004534 if (!o) { \
4535 Py_DECREF(value); \
4536 return NULL; \
4537 } \
4538 PyStructSequence_SET_ITEM(value, i, o); \
4539 } \
4540
4541 SET(0, u.sysname);
4542 SET(1, u.nodename);
4543 SET(2, u.release);
4544 SET(3, u.version);
4545 SET(4, u.machine);
4546
4547#undef SET
4548
4549 return value;
Guido van Rossumc39de5f1992-02-05 11:15:54 +00004550}
Guido van Rossumb6775db1994-08-01 11:34:53 +00004551#endif /* HAVE_UNAME */
Guido van Rossum1ff6cb41991-04-08 20:59:13 +00004552
Larry Hastings9e3e70b2011-09-08 19:29:07 -07004553
Larry Hastings9cf065c2012-06-22 16:30:09 -07004554
4555typedef struct {
4556 int now;
4557 time_t atime_s;
4558 long atime_ns;
4559 time_t mtime_s;
4560 long mtime_ns;
4561} utime_t;
4562
4563/*
Victor Stinner484df002014-10-09 13:52:31 +02004564 * these macros assume that "ut" is a pointer to a utime_t
Larry Hastings9cf065c2012-06-22 16:30:09 -07004565 * they also intentionally leak the declaration of a pointer named "time"
4566 */
4567#define UTIME_TO_TIMESPEC \
4568 struct timespec ts[2]; \
4569 struct timespec *time; \
Victor Stinner484df002014-10-09 13:52:31 +02004570 if (ut->now) \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004571 time = NULL; \
4572 else { \
Victor Stinner484df002014-10-09 13:52:31 +02004573 ts[0].tv_sec = ut->atime_s; \
4574 ts[0].tv_nsec = ut->atime_ns; \
4575 ts[1].tv_sec = ut->mtime_s; \
4576 ts[1].tv_nsec = ut->mtime_ns; \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004577 time = ts; \
4578 } \
4579
4580#define UTIME_TO_TIMEVAL \
4581 struct timeval tv[2]; \
4582 struct timeval *time; \
Victor Stinner484df002014-10-09 13:52:31 +02004583 if (ut->now) \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004584 time = NULL; \
4585 else { \
Victor Stinner484df002014-10-09 13:52:31 +02004586 tv[0].tv_sec = ut->atime_s; \
4587 tv[0].tv_usec = ut->atime_ns / 1000; \
4588 tv[1].tv_sec = ut->mtime_s; \
4589 tv[1].tv_usec = ut->mtime_ns / 1000; \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004590 time = tv; \
4591 } \
4592
4593#define UTIME_TO_UTIMBUF \
Georg Brandle1a7d9d2014-10-12 08:45:15 +02004594 struct utimbuf u; \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004595 struct utimbuf *time; \
Victor Stinner484df002014-10-09 13:52:31 +02004596 if (ut->now) \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004597 time = NULL; \
4598 else { \
Georg Brandle1a7d9d2014-10-12 08:45:15 +02004599 u.actime = ut->atime_s; \
4600 u.modtime = ut->mtime_s; \
4601 time = &u; \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004602 }
4603
4604#define UTIME_TO_TIME_T \
4605 time_t timet[2]; \
Georg Brandle1a7d9d2014-10-12 08:45:15 +02004606 time_t *time; \
Victor Stinner484df002014-10-09 13:52:31 +02004607 if (ut->now) \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004608 time = NULL; \
4609 else { \
Victor Stinner484df002014-10-09 13:52:31 +02004610 timet[0] = ut->atime_s; \
4611 timet[1] = ut->mtime_s; \
Georg Brandle1a7d9d2014-10-12 08:45:15 +02004612 time = timet; \
Larry Hastings9cf065c2012-06-22 16:30:09 -07004613 } \
4614
4615
Victor Stinner528a9ab2015-09-03 21:30:26 +02004616#if defined(HAVE_FUTIMESAT) || defined(HAVE_UTIMENSAT)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004617
4618static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02004619utime_dir_fd(utime_t *ut, int dir_fd, const char *path, int follow_symlinks)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004620{
4621#ifdef HAVE_UTIMENSAT
4622 int flags = follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW;
4623 UTIME_TO_TIMESPEC;
4624 return utimensat(dir_fd, path, time, flags);
4625#elif defined(HAVE_FUTIMESAT)
4626 UTIME_TO_TIMEVAL;
4627 /*
4628 * follow_symlinks will never be false here;
4629 * we only allow !follow_symlinks and dir_fd together
4630 * if we have utimensat()
4631 */
4632 assert(follow_symlinks);
4633 return futimesat(dir_fd, path, time);
4634#endif
4635}
4636
Larry Hastings2f936352014-08-05 14:04:04 +10004637 #define FUTIMENSAT_DIR_FD_CONVERTER dir_fd_converter
4638#else
4639 #define FUTIMENSAT_DIR_FD_CONVERTER dir_fd_unavailable
Larry Hastings9cf065c2012-06-22 16:30:09 -07004640#endif
4641
Victor Stinner528a9ab2015-09-03 21:30:26 +02004642#if defined(HAVE_FUTIMES) || defined(HAVE_FUTIMENS)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004643
4644static int
Victor Stinner484df002014-10-09 13:52:31 +02004645utime_fd(utime_t *ut, int fd)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004646{
4647#ifdef HAVE_FUTIMENS
4648 UTIME_TO_TIMESPEC;
4649 return futimens(fd, time);
4650#else
4651 UTIME_TO_TIMEVAL;
4652 return futimes(fd, time);
4653#endif
4654}
4655
Larry Hastings2f936352014-08-05 14:04:04 +10004656 #define PATH_UTIME_HAVE_FD 1
4657#else
4658 #define PATH_UTIME_HAVE_FD 0
Larry Hastings9cf065c2012-06-22 16:30:09 -07004659#endif
4660
Victor Stinner5ebae872015-09-22 01:29:33 +02004661#if defined(HAVE_UTIMENSAT) || defined(HAVE_LUTIMES)
4662# define UTIME_HAVE_NOFOLLOW_SYMLINKS
4663#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -07004664
Victor Stinner4552ced2015-09-21 22:37:15 +02004665#ifdef UTIME_HAVE_NOFOLLOW_SYMLINKS
Larry Hastings9cf065c2012-06-22 16:30:09 -07004666
4667static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02004668utime_nofollow_symlinks(utime_t *ut, const char *path)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004669{
4670#ifdef HAVE_UTIMENSAT
4671 UTIME_TO_TIMESPEC;
4672 return utimensat(DEFAULT_DIR_FD, path, time, AT_SYMLINK_NOFOLLOW);
4673#else
4674 UTIME_TO_TIMEVAL;
4675 return lutimes(path, time);
4676#endif
4677}
4678
4679#endif
4680
4681#ifndef MS_WINDOWS
4682
4683static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02004684utime_default(utime_t *ut, const char *path)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004685{
4686#ifdef HAVE_UTIMENSAT
4687 UTIME_TO_TIMESPEC;
4688 return utimensat(DEFAULT_DIR_FD, path, time, 0);
4689#elif defined(HAVE_UTIMES)
4690 UTIME_TO_TIMEVAL;
4691 return utimes(path, time);
4692#elif defined(HAVE_UTIME_H)
4693 UTIME_TO_UTIMBUF;
4694 return utime(path, time);
4695#else
4696 UTIME_TO_TIME_T;
4697 return utime(path, time);
4698#endif
4699}
4700
4701#endif
4702
Larry Hastings76ad59b2012-05-03 00:30:07 -07004703static int
4704split_py_long_to_s_and_ns(PyObject *py_long, time_t *s, long *ns)
4705{
4706 int result = 0;
Benjamin Petersonfbd85a02012-05-04 11:06:09 -04004707 PyObject *divmod;
Larry Hastings76ad59b2012-05-03 00:30:07 -07004708 divmod = PyNumber_Divmod(py_long, billion);
4709 if (!divmod)
4710 goto exit;
Oren Milman0bd1a2d2018-09-12 22:14:35 +03004711 if (!PyTuple_Check(divmod) || PyTuple_GET_SIZE(divmod) != 2) {
4712 PyErr_Format(PyExc_TypeError,
4713 "%.200s.__divmod__() must return a 2-tuple, not %.200s",
4714 Py_TYPE(py_long)->tp_name, Py_TYPE(divmod)->tp_name);
4715 goto exit;
4716 }
Larry Hastings76ad59b2012-05-03 00:30:07 -07004717 *s = _PyLong_AsTime_t(PyTuple_GET_ITEM(divmod, 0));
4718 if ((*s == -1) && PyErr_Occurred())
4719 goto exit;
4720 *ns = PyLong_AsLong(PyTuple_GET_ITEM(divmod, 1));
Benjamin Peterson35a8f0d2012-05-04 01:10:59 -04004721 if ((*ns == -1) && PyErr_Occurred())
Larry Hastings76ad59b2012-05-03 00:30:07 -07004722 goto exit;
4723
4724 result = 1;
4725exit:
4726 Py_XDECREF(divmod);
4727 return result;
4728}
4729
Larry Hastings2f936352014-08-05 14:04:04 +10004730
4731/*[clinic input]
4732os.utime
4733
4734 path: path_t(allow_fd='PATH_UTIME_HAVE_FD')
4735 times: object = NULL
4736 *
4737 ns: object = NULL
4738 dir_fd: dir_fd(requires='futimensat') = None
4739 follow_symlinks: bool=True
4740
Martin Panter0ff89092015-09-09 01:56:53 +00004741# "utime(path, times=None, *[, ns], dir_fd=None, follow_symlinks=True)\n\
Larry Hastings2f936352014-08-05 14:04:04 +10004742
4743Set the access and modified time of path.
4744
4745path may always be specified as a string.
4746On some platforms, path may also be specified as an open file descriptor.
4747 If this functionality is unavailable, using it raises an exception.
4748
4749If times is not None, it must be a tuple (atime, mtime);
4750 atime and mtime should be expressed as float seconds since the epoch.
Martin Panter0ff89092015-09-09 01:56:53 +00004751If ns is specified, it must be a tuple (atime_ns, mtime_ns);
Larry Hastings2f936352014-08-05 14:04:04 +10004752 atime_ns and mtime_ns should be expressed as integer nanoseconds
4753 since the epoch.
Martin Panter0ff89092015-09-09 01:56:53 +00004754If times is None and ns is unspecified, utime uses the current time.
Larry Hastings2f936352014-08-05 14:04:04 +10004755Specifying tuples for both times and ns is an error.
4756
4757If dir_fd is not None, it should be a file descriptor open to a directory,
4758 and path should be relative; path will then be relative to that directory.
4759If follow_symlinks is False, and the last element of the path is a symbolic
4760 link, utime will modify the symbolic link itself instead of the file the
4761 link points to.
4762It is an error to use dir_fd or follow_symlinks when specifying path
4763 as an open file descriptor.
4764dir_fd and follow_symlinks may not be available on your platform.
4765 If they are unavailable, using them will raise a NotImplementedError.
4766
4767[clinic start generated code]*/
4768
Larry Hastings2f936352014-08-05 14:04:04 +10004769static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004770os_utime_impl(PyObject *module, path_t *path, PyObject *times, PyObject *ns,
4771 int dir_fd, int follow_symlinks)
4772/*[clinic end generated code: output=cfcac69d027b82cf input=081cdc54ca685385]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004773{
Larry Hastings9cf065c2012-06-22 16:30:09 -07004774#ifdef MS_WINDOWS
4775 HANDLE hFile;
4776 FILETIME atime, mtime;
4777#else
4778 int result;
4779#endif
Larry Hastings76ad59b2012-05-03 00:30:07 -07004780
Larry Hastings2f936352014-08-05 14:04:04 +10004781 utime_t utime;
Larry Hastings76ad59b2012-05-03 00:30:07 -07004782
Christian Heimesb3c87242013-08-01 00:08:16 +02004783 memset(&utime, 0, sizeof(utime_t));
Larry Hastings76ad59b2012-05-03 00:30:07 -07004784
Larry Hastings9cf065c2012-06-22 16:30:09 -07004785 if (times && (times != Py_None) && ns) {
4786 PyErr_SetString(PyExc_ValueError,
4787 "utime: you may specify either 'times'"
4788 " or 'ns' but not both");
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004789 return NULL;
Larry Hastings76ad59b2012-05-03 00:30:07 -07004790 }
4791
4792 if (times && (times != Py_None)) {
Antoine Pitroucf8a1e52013-04-17 22:06:44 +02004793 time_t a_sec, m_sec;
4794 long a_nsec, m_nsec;
Larry Hastings76ad59b2012-05-03 00:30:07 -07004795 if (!PyTuple_CheckExact(times) || (PyTuple_Size(times) != 2)) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07004796 PyErr_SetString(PyExc_TypeError,
4797 "utime: 'times' must be either"
4798 " a tuple of two ints or None");
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004799 return NULL;
Larry Hastings76ad59b2012-05-03 00:30:07 -07004800 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07004801 utime.now = 0;
Benjamin Petersonb399ab22012-05-04 01:31:13 -04004802 if (_PyTime_ObjectToTimespec(PyTuple_GET_ITEM(times, 0),
Victor Stinnerdca028b2015-03-30 01:02:57 +02004803 &a_sec, &a_nsec, _PyTime_ROUND_FLOOR) == -1 ||
Benjamin Petersonb399ab22012-05-04 01:31:13 -04004804 _PyTime_ObjectToTimespec(PyTuple_GET_ITEM(times, 1),
Victor Stinnerdca028b2015-03-30 01:02:57 +02004805 &m_sec, &m_nsec, _PyTime_ROUND_FLOOR) == -1) {
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004806 return NULL;
Larry Hastingsb3336402012-05-04 02:31:57 -07004807 }
Antoine Pitroucf8a1e52013-04-17 22:06:44 +02004808 utime.atime_s = a_sec;
4809 utime.atime_ns = a_nsec;
4810 utime.mtime_s = m_sec;
4811 utime.mtime_ns = m_nsec;
Larry Hastings76ad59b2012-05-03 00:30:07 -07004812 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07004813 else if (ns) {
Larry Hastings76ad59b2012-05-03 00:30:07 -07004814 if (!PyTuple_CheckExact(ns) || (PyTuple_Size(ns) != 2)) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07004815 PyErr_SetString(PyExc_TypeError,
4816 "utime: 'ns' must be a tuple of two ints");
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004817 return NULL;
Larry Hastings76ad59b2012-05-03 00:30:07 -07004818 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07004819 utime.now = 0;
Benjamin Petersonb399ab22012-05-04 01:31:13 -04004820 if (!split_py_long_to_s_and_ns(PyTuple_GET_ITEM(ns, 0),
Larry Hastings9cf065c2012-06-22 16:30:09 -07004821 &utime.atime_s, &utime.atime_ns) ||
Benjamin Petersonb399ab22012-05-04 01:31:13 -04004822 !split_py_long_to_s_and_ns(PyTuple_GET_ITEM(ns, 1),
Larry Hastings9cf065c2012-06-22 16:30:09 -07004823 &utime.mtime_s, &utime.mtime_ns)) {
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004824 return NULL;
Larry Hastingsb3336402012-05-04 02:31:57 -07004825 }
Larry Hastings9cf065c2012-06-22 16:30:09 -07004826 }
4827 else {
4828 /* times and ns are both None/unspecified. use "now". */
4829 utime.now = 1;
Larry Hastings76ad59b2012-05-03 00:30:07 -07004830 }
4831
Victor Stinner4552ced2015-09-21 22:37:15 +02004832#if !defined(UTIME_HAVE_NOFOLLOW_SYMLINKS)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004833 if (follow_symlinks_specified("utime", follow_symlinks))
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004834 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07004835#endif
Benjamin Petersonb399ab22012-05-04 01:31:13 -04004836
Larry Hastings2f936352014-08-05 14:04:04 +10004837 if (path_and_dir_fd_invalid("utime", path, dir_fd) ||
4838 dir_fd_and_fd_invalid("utime", dir_fd, path->fd) ||
4839 fd_and_follow_symlinks_invalid("utime", path->fd, follow_symlinks))
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004840 return NULL;
Larry Hastings76ad59b2012-05-03 00:30:07 -07004841
Larry Hastings9cf065c2012-06-22 16:30:09 -07004842#if !defined(HAVE_UTIMENSAT)
4843 if ((dir_fd != DEFAULT_DIR_FD) && (!follow_symlinks)) {
Georg Brandl969288e2012-06-26 09:25:44 +02004844 PyErr_SetString(PyExc_ValueError,
Larry Hastings9cf065c2012-06-22 16:30:09 -07004845 "utime: cannot use dir_fd and follow_symlinks "
4846 "together on this platform");
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004847 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -07004848 }
4849#endif
Larry Hastings76ad59b2012-05-03 00:30:07 -07004850
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00004851#ifdef MS_WINDOWS
Larry Hastings9cf065c2012-06-22 16:30:09 -07004852 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -07004853 hFile = CreateFileW(path->wide, FILE_WRITE_ATTRIBUTES, 0,
4854 NULL, OPEN_EXISTING,
4855 FILE_FLAG_BACKUP_SEMANTICS, NULL);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004856 Py_END_ALLOW_THREADS
4857 if (hFile == INVALID_HANDLE_VALUE) {
Larry Hastings2f936352014-08-05 14:04:04 +10004858 path_error(path);
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004859 return NULL;
Larry Hastingsb3336402012-05-04 02:31:57 -07004860 }
4861
Larry Hastings9cf065c2012-06-22 16:30:09 -07004862 if (utime.now) {
Antoine Pitrou91a7af32013-11-23 15:23:26 +01004863 GetSystemTimeAsFileTime(&mtime);
4864 atime = mtime;
Victor Stinner8c62be82010-05-06 00:08:46 +00004865 }
Victor Stinner8c62be82010-05-06 00:08:46 +00004866 else {
Steve Dowerbf1f3762015-02-21 15:26:02 -08004867 _Py_time_t_to_FILE_TIME(utime.atime_s, utime.atime_ns, &atime);
4868 _Py_time_t_to_FILE_TIME(utime.mtime_s, utime.mtime_ns, &mtime);
Victor Stinner8c62be82010-05-06 00:08:46 +00004869 }
4870 if (!SetFileTime(hFile, NULL, &atime, &mtime)) {
4871 /* Avoid putting the file name into the error here,
4872 as that may confuse the user into believing that
4873 something is wrong with the file, when it also
4874 could be the time stamp that gives a problem. */
Victor Stinnerb024e842012-10-31 22:24:06 +01004875 PyErr_SetFromWindowsErr(0);
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004876 CloseHandle(hFile);
4877 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00004878 }
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004879 CloseHandle(hFile);
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00004880#else /* MS_WINDOWS */
Larry Hastings9cf065c2012-06-22 16:30:09 -07004881 Py_BEGIN_ALLOW_THREADS
Guido van Rossum1ff6cb41991-04-08 20:59:13 +00004882
Victor Stinner4552ced2015-09-21 22:37:15 +02004883#ifdef UTIME_HAVE_NOFOLLOW_SYMLINKS
Larry Hastings9cf065c2012-06-22 16:30:09 -07004884 if ((!follow_symlinks) && (dir_fd == DEFAULT_DIR_FD))
Larry Hastings2f936352014-08-05 14:04:04 +10004885 result = utime_nofollow_symlinks(&utime, path->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004886 else
Larry Hastings9e3e70b2011-09-08 19:29:07 -07004887#endif
Larry Hastings9cf065c2012-06-22 16:30:09 -07004888
Victor Stinner528a9ab2015-09-03 21:30:26 +02004889#if defined(HAVE_FUTIMESAT) || defined(HAVE_UTIMENSAT)
Larry Hastings9cf065c2012-06-22 16:30:09 -07004890 if ((dir_fd != DEFAULT_DIR_FD) || (!follow_symlinks))
Larry Hastings2f936352014-08-05 14:04:04 +10004891 result = utime_dir_fd(&utime, dir_fd, path->narrow, follow_symlinks);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004892 else
4893#endif
4894
Victor Stinner528a9ab2015-09-03 21:30:26 +02004895#if defined(HAVE_FUTIMES) || defined(HAVE_FUTIMENS)
Larry Hastings2f936352014-08-05 14:04:04 +10004896 if (path->fd != -1)
4897 result = utime_fd(&utime, path->fd);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004898 else
4899#endif
4900
Larry Hastings2f936352014-08-05 14:04:04 +10004901 result = utime_default(&utime, path->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07004902
4903 Py_END_ALLOW_THREADS
4904
4905 if (result < 0) {
4906 /* see previous comment about not putting filename in error here */
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004907 posix_error();
4908 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00004909 }
Larry Hastings76ad59b2012-05-03 00:30:07 -07004910
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +00004911#endif /* MS_WINDOWS */
Larry Hastings9cf065c2012-06-22 16:30:09 -07004912
Serhiy Storchaka32bc11c2018-12-01 14:30:20 +02004913 Py_RETURN_NONE;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00004914}
4915
Guido van Rossum3b066191991-06-04 19:40:25 +00004916/* Process operations */
Guido van Rossum85e3b011991-06-03 12:42:10 +00004917
Larry Hastings2f936352014-08-05 14:04:04 +10004918
4919/*[clinic input]
4920os._exit
4921
4922 status: int
4923
4924Exit to the system with specified status, without normal exit processing.
4925[clinic start generated code]*/
4926
Larry Hastings2f936352014-08-05 14:04:04 +10004927static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004928os__exit_impl(PyObject *module, int status)
4929/*[clinic end generated code: output=116e52d9c2260d54 input=5e6d57556b0c4a62]*/
Larry Hastings2f936352014-08-05 14:04:04 +10004930{
4931 _exit(status);
Victor Stinner8c62be82010-05-06 00:08:46 +00004932 return NULL; /* Make gcc -Wall happy */
Guido van Rossum85e3b011991-06-03 12:42:10 +00004933}
4934
Steve Dowercc16be82016-09-08 10:35:16 -07004935#if defined(HAVE_WEXECV) || defined(HAVE_WSPAWNV)
4936#define EXECV_CHAR wchar_t
4937#else
4938#define EXECV_CHAR char
4939#endif
4940
pxinwrf2d7ac72019-05-21 18:46:37 +08004941#if defined(HAVE_EXECV) || defined(HAVE_SPAWNV) || defined(HAVE_RTPSPAWN)
Martin v. Löwis114619e2002-10-07 06:44:21 +00004942static void
Steve Dowercc16be82016-09-08 10:35:16 -07004943free_string_array(EXECV_CHAR **array, Py_ssize_t count)
Martin v. Löwis114619e2002-10-07 06:44:21 +00004944{
Victor Stinner8c62be82010-05-06 00:08:46 +00004945 Py_ssize_t i;
4946 for (i = 0; i < count; i++)
4947 PyMem_Free(array[i]);
4948 PyMem_DEL(array);
Martin v. Löwis114619e2002-10-07 06:44:21 +00004949}
Martin v. Löwis011e8422009-05-05 04:43:17 +00004950
Berker Peksag81816462016-09-15 20:19:47 +03004951static int
4952fsconvert_strdup(PyObject *o, EXECV_CHAR **out)
Martin v. Löwis011e8422009-05-05 04:43:17 +00004953{
Victor Stinner8c62be82010-05-06 00:08:46 +00004954 Py_ssize_t size;
Berker Peksag81816462016-09-15 20:19:47 +03004955 PyObject *ub;
4956 int result = 0;
Steve Dowercc16be82016-09-08 10:35:16 -07004957#if defined(HAVE_WEXECV) || defined(HAVE_WSPAWNV)
Berker Peksag81816462016-09-15 20:19:47 +03004958 if (!PyUnicode_FSDecoder(o, &ub))
Steve Dowercc16be82016-09-08 10:35:16 -07004959 return 0;
Berker Peksag81816462016-09-15 20:19:47 +03004960 *out = PyUnicode_AsWideCharString(ub, &size);
4961 if (*out)
4962 result = 1;
Steve Dowercc16be82016-09-08 10:35:16 -07004963#else
Berker Peksag81816462016-09-15 20:19:47 +03004964 if (!PyUnicode_FSConverter(o, &ub))
Victor Stinner8c62be82010-05-06 00:08:46 +00004965 return 0;
Berker Peksag81816462016-09-15 20:19:47 +03004966 size = PyBytes_GET_SIZE(ub);
4967 *out = PyMem_Malloc(size + 1);
4968 if (*out) {
4969 memcpy(*out, PyBytes_AS_STRING(ub), size + 1);
4970 result = 1;
4971 } else
Victor Stinner50abf222013-11-07 23:56:10 +01004972 PyErr_NoMemory();
Steve Dowercc16be82016-09-08 10:35:16 -07004973#endif
Berker Peksag81816462016-09-15 20:19:47 +03004974 Py_DECREF(ub);
4975 return result;
Martin v. Löwis011e8422009-05-05 04:43:17 +00004976}
Martin v. Löwis114619e2002-10-07 06:44:21 +00004977#endif
4978
pxinwrf2d7ac72019-05-21 18:46:37 +08004979#if defined(HAVE_EXECV) || defined (HAVE_FEXECVE) || defined(HAVE_RTPSPAWN)
Steve Dowercc16be82016-09-08 10:35:16 -07004980static EXECV_CHAR**
Victor Stinner13bb71c2010-04-23 21:41:56 +00004981parse_envlist(PyObject* env, Py_ssize_t *envc_ptr)
4982{
Victor Stinner8c62be82010-05-06 00:08:46 +00004983 Py_ssize_t i, pos, envc;
4984 PyObject *keys=NULL, *vals=NULL;
Berker Peksag81816462016-09-15 20:19:47 +03004985 PyObject *key, *val, *key2, *val2, *keyval;
Steve Dowercc16be82016-09-08 10:35:16 -07004986 EXECV_CHAR **envlist;
Victor Stinner13bb71c2010-04-23 21:41:56 +00004987
Victor Stinner8c62be82010-05-06 00:08:46 +00004988 i = PyMapping_Size(env);
4989 if (i < 0)
4990 return NULL;
Steve Dowercc16be82016-09-08 10:35:16 -07004991 envlist = PyMem_NEW(EXECV_CHAR *, i + 1);
Victor Stinner8c62be82010-05-06 00:08:46 +00004992 if (envlist == NULL) {
4993 PyErr_NoMemory();
4994 return NULL;
4995 }
4996 envc = 0;
4997 keys = PyMapping_Keys(env);
Victor Stinnerb0314272013-11-14 21:37:05 +01004998 if (!keys)
4999 goto error;
Victor Stinner8c62be82010-05-06 00:08:46 +00005000 vals = PyMapping_Values(env);
Victor Stinnerb0314272013-11-14 21:37:05 +01005001 if (!vals)
Victor Stinner8c62be82010-05-06 00:08:46 +00005002 goto error;
5003 if (!PyList_Check(keys) || !PyList_Check(vals)) {
5004 PyErr_Format(PyExc_TypeError,
5005 "env.keys() or env.values() is not a list");
5006 goto error;
5007 }
Victor Stinner13bb71c2010-04-23 21:41:56 +00005008
Victor Stinner8c62be82010-05-06 00:08:46 +00005009 for (pos = 0; pos < i; pos++) {
5010 key = PyList_GetItem(keys, pos);
5011 val = PyList_GetItem(vals, pos);
5012 if (!key || !val)
5013 goto error;
Victor Stinner13bb71c2010-04-23 21:41:56 +00005014
Berker Peksag81816462016-09-15 20:19:47 +03005015#if defined(HAVE_WEXECV) || defined(HAVE_WSPAWNV)
5016 if (!PyUnicode_FSDecoder(key, &key2))
5017 goto error;
5018 if (!PyUnicode_FSDecoder(val, &val2)) {
5019 Py_DECREF(key2);
5020 goto error;
5021 }
Serhiy Storchaka77703942017-06-25 07:33:01 +03005022 /* Search from index 1 because on Windows starting '=' is allowed for
5023 defining hidden environment variables. */
5024 if (PyUnicode_GET_LENGTH(key2) == 0 ||
5025 PyUnicode_FindChar(key2, '=', 1, PyUnicode_GET_LENGTH(key2), 1) != -1)
5026 {
5027 PyErr_SetString(PyExc_ValueError, "illegal environment variable name");
Eric N. Vander Weelea7874c72017-06-26 21:35:20 -04005028 Py_DECREF(key2);
5029 Py_DECREF(val2);
Serhiy Storchaka77703942017-06-25 07:33:01 +03005030 goto error;
5031 }
Berker Peksag81816462016-09-15 20:19:47 +03005032 keyval = PyUnicode_FromFormat("%U=%U", key2, val2);
5033#else
5034 if (!PyUnicode_FSConverter(key, &key2))
5035 goto error;
5036 if (!PyUnicode_FSConverter(val, &val2)) {
5037 Py_DECREF(key2);
5038 goto error;
5039 }
Serhiy Storchaka77703942017-06-25 07:33:01 +03005040 if (PyBytes_GET_SIZE(key2) == 0 ||
5041 strchr(PyBytes_AS_STRING(key2) + 1, '=') != NULL)
5042 {
5043 PyErr_SetString(PyExc_ValueError, "illegal environment variable name");
Eric N. Vander Weelea7874c72017-06-26 21:35:20 -04005044 Py_DECREF(key2);
5045 Py_DECREF(val2);
Serhiy Storchaka77703942017-06-25 07:33:01 +03005046 goto error;
5047 }
Berker Peksag81816462016-09-15 20:19:47 +03005048 keyval = PyBytes_FromFormat("%s=%s", PyBytes_AS_STRING(key2),
5049 PyBytes_AS_STRING(val2));
5050#endif
5051 Py_DECREF(key2);
5052 Py_DECREF(val2);
Steve Dowercc16be82016-09-08 10:35:16 -07005053 if (!keyval)
Victor Stinner8c62be82010-05-06 00:08:46 +00005054 goto error;
Steve Dowercc16be82016-09-08 10:35:16 -07005055
5056 if (!fsconvert_strdup(keyval, &envlist[envc++])) {
5057 Py_DECREF(keyval);
Victor Stinner8c62be82010-05-06 00:08:46 +00005058 goto error;
5059 }
Berker Peksag81816462016-09-15 20:19:47 +03005060
Steve Dowercc16be82016-09-08 10:35:16 -07005061 Py_DECREF(keyval);
Victor Stinner8c62be82010-05-06 00:08:46 +00005062 }
5063 Py_DECREF(vals);
5064 Py_DECREF(keys);
Victor Stinner13bb71c2010-04-23 21:41:56 +00005065
Victor Stinner8c62be82010-05-06 00:08:46 +00005066 envlist[envc] = 0;
5067 *envc_ptr = envc;
5068 return envlist;
Victor Stinner13bb71c2010-04-23 21:41:56 +00005069
5070error:
Victor Stinner8c62be82010-05-06 00:08:46 +00005071 Py_XDECREF(keys);
5072 Py_XDECREF(vals);
Steve Dowercc16be82016-09-08 10:35:16 -07005073 free_string_array(envlist, envc);
Victor Stinner8c62be82010-05-06 00:08:46 +00005074 return NULL;
Victor Stinner13bb71c2010-04-23 21:41:56 +00005075}
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00005076
Steve Dowercc16be82016-09-08 10:35:16 -07005077static EXECV_CHAR**
Ross Lagerwall7807c352011-03-17 20:20:30 +02005078parse_arglist(PyObject* argv, Py_ssize_t *argc)
5079{
5080 int i;
Steve Dowercc16be82016-09-08 10:35:16 -07005081 EXECV_CHAR **argvlist = PyMem_NEW(EXECV_CHAR *, *argc+1);
Ross Lagerwall7807c352011-03-17 20:20:30 +02005082 if (argvlist == NULL) {
5083 PyErr_NoMemory();
5084 return NULL;
5085 }
5086 for (i = 0; i < *argc; i++) {
Ross Lagerwall9ad63e02011-03-19 09:11:14 +02005087 PyObject* item = PySequence_ITEM(argv, i);
5088 if (item == NULL)
5089 goto fail;
5090 if (!fsconvert_strdup(item, &argvlist[i])) {
5091 Py_DECREF(item);
Ross Lagerwall7807c352011-03-17 20:20:30 +02005092 goto fail;
5093 }
Ross Lagerwall9ad63e02011-03-19 09:11:14 +02005094 Py_DECREF(item);
Ross Lagerwall7807c352011-03-17 20:20:30 +02005095 }
5096 argvlist[*argc] = NULL;
5097 return argvlist;
5098fail:
Ross Lagerwall9ad63e02011-03-19 09:11:14 +02005099 *argc = i;
Ross Lagerwall7807c352011-03-17 20:20:30 +02005100 free_string_array(argvlist, *argc);
5101 return NULL;
5102}
Steve Dowercc16be82016-09-08 10:35:16 -07005103
Ross Lagerwall7807c352011-03-17 20:20:30 +02005104#endif
5105
Larry Hastings2f936352014-08-05 14:04:04 +10005106
Ross Lagerwall7807c352011-03-17 20:20:30 +02005107#ifdef HAVE_EXECV
Larry Hastings2f936352014-08-05 14:04:04 +10005108/*[clinic input]
5109os.execv
5110
Steve Dowercc16be82016-09-08 10:35:16 -07005111 path: path_t
Larry Hastings2f936352014-08-05 14:04:04 +10005112 Path of executable file.
5113 argv: object
5114 Tuple or list of strings.
5115 /
5116
5117Execute an executable path with arguments, replacing current process.
5118[clinic start generated code]*/
5119
Larry Hastings2f936352014-08-05 14:04:04 +10005120static PyObject *
Steve Dowercc16be82016-09-08 10:35:16 -07005121os_execv_impl(PyObject *module, path_t *path, PyObject *argv)
5122/*[clinic end generated code: output=3b52fec34cd0dafd input=9bac31efae07dac7]*/
Larry Hastings2f936352014-08-05 14:04:04 +10005123{
Steve Dowercc16be82016-09-08 10:35:16 -07005124 EXECV_CHAR **argvlist;
Ross Lagerwall7807c352011-03-17 20:20:30 +02005125 Py_ssize_t argc;
5126
5127 /* execv has two arguments: (path, argv), where
5128 argv is a list or tuple of strings. */
5129
Ross Lagerwall7807c352011-03-17 20:20:30 +02005130 if (!PyList_Check(argv) && !PyTuple_Check(argv)) {
5131 PyErr_SetString(PyExc_TypeError,
5132 "execv() arg 2 must be a tuple or list");
Ross Lagerwall7807c352011-03-17 20:20:30 +02005133 return NULL;
5134 }
5135 argc = PySequence_Size(argv);
5136 if (argc < 1) {
5137 PyErr_SetString(PyExc_ValueError, "execv() arg 2 must not be empty");
Ross Lagerwall7807c352011-03-17 20:20:30 +02005138 return NULL;
5139 }
5140
5141 argvlist = parse_arglist(argv, &argc);
5142 if (argvlist == NULL) {
Ross Lagerwall7807c352011-03-17 20:20:30 +02005143 return NULL;
5144 }
Steve Dowerbce26262016-11-19 19:17:26 -08005145 if (!argvlist[0][0]) {
5146 PyErr_SetString(PyExc_ValueError,
5147 "execv() arg 2 first element cannot be empty");
5148 free_string_array(argvlist, argc);
5149 return NULL;
5150 }
Ross Lagerwall7807c352011-03-17 20:20:30 +02005151
Steve Dowerbce26262016-11-19 19:17:26 -08005152 _Py_BEGIN_SUPPRESS_IPH
Steve Dowercc16be82016-09-08 10:35:16 -07005153#ifdef HAVE_WEXECV
5154 _wexecv(path->wide, argvlist);
5155#else
5156 execv(path->narrow, argvlist);
5157#endif
Steve Dowerbce26262016-11-19 19:17:26 -08005158 _Py_END_SUPPRESS_IPH
Ross Lagerwall7807c352011-03-17 20:20:30 +02005159
5160 /* If we get here it's definitely an error */
5161
5162 free_string_array(argvlist, argc);
Ross Lagerwall7807c352011-03-17 20:20:30 +02005163 return posix_error();
5164}
5165
Larry Hastings2f936352014-08-05 14:04:04 +10005166
5167/*[clinic input]
5168os.execve
5169
5170 path: path_t(allow_fd='PATH_HAVE_FEXECVE')
5171 Path of executable file.
5172 argv: object
5173 Tuple or list of strings.
5174 env: object
5175 Dictionary of strings mapping to strings.
5176
5177Execute an executable path with arguments, replacing current process.
5178[clinic start generated code]*/
5179
Larry Hastings2f936352014-08-05 14:04:04 +10005180static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005181os_execve_impl(PyObject *module, path_t *path, PyObject *argv, PyObject *env)
5182/*[clinic end generated code: output=ff9fa8e4da8bde58 input=626804fa092606d9]*/
Larry Hastings2f936352014-08-05 14:04:04 +10005183{
Steve Dowercc16be82016-09-08 10:35:16 -07005184 EXECV_CHAR **argvlist = NULL;
5185 EXECV_CHAR **envlist;
Ross Lagerwall7807c352011-03-17 20:20:30 +02005186 Py_ssize_t argc, envc;
Guido van Rossumc6dcc9f1993-11-05 10:15:19 +00005187
Victor Stinner8c62be82010-05-06 00:08:46 +00005188 /* execve has three arguments: (path, argv, env), where
5189 argv is a list or tuple of strings and env is a dictionary
5190 like posix.environ. */
Guido van Rossumc6dcc9f1993-11-05 10:15:19 +00005191
Ross Lagerwall7807c352011-03-17 20:20:30 +02005192 if (!PyList_Check(argv) && !PyTuple_Check(argv)) {
Victor Stinner8c62be82010-05-06 00:08:46 +00005193 PyErr_SetString(PyExc_TypeError,
Larry Hastings9cf065c2012-06-22 16:30:09 -07005194 "execve: argv must be a tuple or list");
5195 goto fail;
Victor Stinner8c62be82010-05-06 00:08:46 +00005196 }
Ross Lagerwall7807c352011-03-17 20:20:30 +02005197 argc = PySequence_Size(argv);
Steve Dowerbce26262016-11-19 19:17:26 -08005198 if (argc < 1) {
5199 PyErr_SetString(PyExc_ValueError, "execve: argv must not be empty");
5200 return NULL;
5201 }
5202
Victor Stinner8c62be82010-05-06 00:08:46 +00005203 if (!PyMapping_Check(env)) {
5204 PyErr_SetString(PyExc_TypeError,
Larry Hastings9cf065c2012-06-22 16:30:09 -07005205 "execve: environment must be a mapping object");
5206 goto fail;
Victor Stinner8c62be82010-05-06 00:08:46 +00005207 }
Guido van Rossumc6dcc9f1993-11-05 10:15:19 +00005208
Ross Lagerwall7807c352011-03-17 20:20:30 +02005209 argvlist = parse_arglist(argv, &argc);
Victor Stinner8c62be82010-05-06 00:08:46 +00005210 if (argvlist == NULL) {
Larry Hastings9cf065c2012-06-22 16:30:09 -07005211 goto fail;
Victor Stinner8c62be82010-05-06 00:08:46 +00005212 }
Steve Dowerbce26262016-11-19 19:17:26 -08005213 if (!argvlist[0][0]) {
5214 PyErr_SetString(PyExc_ValueError,
5215 "execve: argv first element cannot be empty");
5216 goto fail;
5217 }
Guido van Rossumc6dcc9f1993-11-05 10:15:19 +00005218
Victor Stinner8c62be82010-05-06 00:08:46 +00005219 envlist = parse_envlist(env, &envc);
5220 if (envlist == NULL)
Ross Lagerwall7807c352011-03-17 20:20:30 +02005221 goto fail;
5222
Steve Dowerbce26262016-11-19 19:17:26 -08005223 _Py_BEGIN_SUPPRESS_IPH
Larry Hastings9cf065c2012-06-22 16:30:09 -07005224#ifdef HAVE_FEXECVE
Larry Hastings2f936352014-08-05 14:04:04 +10005225 if (path->fd > -1)
5226 fexecve(path->fd, argvlist, envlist);
Larry Hastings9cf065c2012-06-22 16:30:09 -07005227 else
5228#endif
Steve Dowercc16be82016-09-08 10:35:16 -07005229#ifdef HAVE_WEXECV
5230 _wexecve(path->wide, argvlist, envlist);
5231#else
Larry Hastings2f936352014-08-05 14:04:04 +10005232 execve(path->narrow, argvlist, envlist);
Steve Dowercc16be82016-09-08 10:35:16 -07005233#endif
Steve Dowerbce26262016-11-19 19:17:26 -08005234 _Py_END_SUPPRESS_IPH
Ross Lagerwall7807c352011-03-17 20:20:30 +02005235
5236 /* If we get here it's definitely an error */
5237
Alexey Izbyshev83460312018-10-20 03:28:22 +03005238 posix_path_error(path);
Ross Lagerwall7807c352011-03-17 20:20:30 +02005239
Steve Dowercc16be82016-09-08 10:35:16 -07005240 free_string_array(envlist, envc);
Ross Lagerwall7807c352011-03-17 20:20:30 +02005241 fail:
Larry Hastings9cf065c2012-06-22 16:30:09 -07005242 if (argvlist)
5243 free_string_array(argvlist, argc);
Ross Lagerwall7807c352011-03-17 20:20:30 +02005244 return NULL;
5245}
Steve Dowercc16be82016-09-08 10:35:16 -07005246
Larry Hastings9cf065c2012-06-22 16:30:09 -07005247#endif /* HAVE_EXECV */
5248
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005249#ifdef HAVE_POSIX_SPAWN
5250
5251enum posix_spawn_file_actions_identifier {
5252 POSIX_SPAWN_OPEN,
5253 POSIX_SPAWN_CLOSE,
5254 POSIX_SPAWN_DUP2
5255};
5256
William Orr81574b82018-10-01 22:19:56 -07005257#if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
Serhiy Storchakaef347532018-05-01 16:45:04 +03005258static int
Pablo Galindo254a4662018-09-07 16:44:24 +01005259convert_sched_param(PyObject *param, struct sched_param *res);
William Orr81574b82018-10-01 22:19:56 -07005260#endif
Pablo Galindo254a4662018-09-07 16:44:24 +01005261
5262static int
Victor Stinner325e4ba2019-02-01 15:47:24 +01005263parse_posix_spawn_flags(const char *func_name, PyObject *setpgroup,
5264 int resetids, int setsid, PyObject *setsigmask,
Pablo Galindo254a4662018-09-07 16:44:24 +01005265 PyObject *setsigdef, PyObject *scheduler,
5266 posix_spawnattr_t *attrp)
5267{
5268 long all_flags = 0;
5269
5270 errno = posix_spawnattr_init(attrp);
5271 if (errno) {
5272 posix_error();
5273 return -1;
5274 }
5275
5276 if (setpgroup) {
5277 pid_t pgid = PyLong_AsPid(setpgroup);
5278 if (pgid == (pid_t)-1 && PyErr_Occurred()) {
5279 goto fail;
5280 }
5281 errno = posix_spawnattr_setpgroup(attrp, pgid);
5282 if (errno) {
5283 posix_error();
5284 goto fail;
5285 }
5286 all_flags |= POSIX_SPAWN_SETPGROUP;
5287 }
5288
5289 if (resetids) {
5290 all_flags |= POSIX_SPAWN_RESETIDS;
5291 }
5292
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005293 if (setsid) {
5294#ifdef POSIX_SPAWN_SETSID
5295 all_flags |= POSIX_SPAWN_SETSID;
5296#elif defined(POSIX_SPAWN_SETSID_NP)
5297 all_flags |= POSIX_SPAWN_SETSID_NP;
5298#else
5299 argument_unavailable_error(func_name, "setsid");
5300 return -1;
5301#endif
5302 }
5303
Pablo Galindo254a4662018-09-07 16:44:24 +01005304 if (setsigmask) {
5305 sigset_t set;
5306 if (!_Py_Sigset_Converter(setsigmask, &set)) {
5307 goto fail;
5308 }
5309 errno = posix_spawnattr_setsigmask(attrp, &set);
5310 if (errno) {
5311 posix_error();
5312 goto fail;
5313 }
5314 all_flags |= POSIX_SPAWN_SETSIGMASK;
5315 }
5316
5317 if (setsigdef) {
5318 sigset_t set;
5319 if (!_Py_Sigset_Converter(setsigdef, &set)) {
5320 goto fail;
5321 }
5322 errno = posix_spawnattr_setsigdefault(attrp, &set);
5323 if (errno) {
5324 posix_error();
5325 goto fail;
5326 }
5327 all_flags |= POSIX_SPAWN_SETSIGDEF;
5328 }
5329
5330 if (scheduler) {
5331#ifdef POSIX_SPAWN_SETSCHEDULER
5332 PyObject *py_schedpolicy;
5333 struct sched_param schedparam;
5334
5335 if (!PyArg_ParseTuple(scheduler, "OO&"
5336 ";A scheduler tuple must have two elements",
5337 &py_schedpolicy, convert_sched_param, &schedparam)) {
5338 goto fail;
5339 }
5340 if (py_schedpolicy != Py_None) {
5341 int schedpolicy = _PyLong_AsInt(py_schedpolicy);
5342
5343 if (schedpolicy == -1 && PyErr_Occurred()) {
5344 goto fail;
5345 }
5346 errno = posix_spawnattr_setschedpolicy(attrp, schedpolicy);
5347 if (errno) {
5348 posix_error();
5349 goto fail;
5350 }
5351 all_flags |= POSIX_SPAWN_SETSCHEDULER;
5352 }
5353 errno = posix_spawnattr_setschedparam(attrp, &schedparam);
5354 if (errno) {
5355 posix_error();
5356 goto fail;
5357 }
5358 all_flags |= POSIX_SPAWN_SETSCHEDPARAM;
5359#else
5360 PyErr_SetString(PyExc_NotImplementedError,
5361 "The scheduler option is not supported in this system.");
5362 goto fail;
5363#endif
5364 }
5365
5366 errno = posix_spawnattr_setflags(attrp, all_flags);
5367 if (errno) {
5368 posix_error();
5369 goto fail;
5370 }
5371
5372 return 0;
5373
5374fail:
5375 (void)posix_spawnattr_destroy(attrp);
5376 return -1;
5377}
5378
5379static int
Serhiy Storchakaef347532018-05-01 16:45:04 +03005380parse_file_actions(PyObject *file_actions,
Pablo Galindocb970732018-06-19 09:19:50 +01005381 posix_spawn_file_actions_t *file_actionsp,
5382 PyObject *temp_buffer)
Serhiy Storchakaef347532018-05-01 16:45:04 +03005383{
5384 PyObject *seq;
5385 PyObject *file_action = NULL;
5386 PyObject *tag_obj;
5387
5388 seq = PySequence_Fast(file_actions,
5389 "file_actions must be a sequence or None");
5390 if (seq == NULL) {
5391 return -1;
5392 }
5393
5394 errno = posix_spawn_file_actions_init(file_actionsp);
5395 if (errno) {
5396 posix_error();
5397 Py_DECREF(seq);
5398 return -1;
5399 }
5400
Miss Islington (bot)04d46922019-06-26 14:20:09 -07005401 for (Py_ssize_t i = 0; i < PySequence_Fast_GET_SIZE(seq); ++i) {
Serhiy Storchakaef347532018-05-01 16:45:04 +03005402 file_action = PySequence_Fast_GET_ITEM(seq, i);
5403 Py_INCREF(file_action);
5404 if (!PyTuple_Check(file_action) || !PyTuple_GET_SIZE(file_action)) {
5405 PyErr_SetString(PyExc_TypeError,
5406 "Each file_actions element must be a non-empty tuple");
5407 goto fail;
5408 }
5409 long tag = PyLong_AsLong(PyTuple_GET_ITEM(file_action, 0));
5410 if (tag == -1 && PyErr_Occurred()) {
5411 goto fail;
5412 }
5413
5414 /* Populate the file_actions object */
5415 switch (tag) {
5416 case POSIX_SPAWN_OPEN: {
5417 int fd, oflag;
5418 PyObject *path;
5419 unsigned long mode;
5420 if (!PyArg_ParseTuple(file_action, "OiO&ik"
5421 ";A open file_action tuple must have 5 elements",
5422 &tag_obj, &fd, PyUnicode_FSConverter, &path,
5423 &oflag, &mode))
5424 {
5425 goto fail;
5426 }
Pablo Galindocb970732018-06-19 09:19:50 +01005427 if (PyList_Append(temp_buffer, path)) {
5428 Py_DECREF(path);
5429 goto fail;
5430 }
Serhiy Storchakaef347532018-05-01 16:45:04 +03005431 errno = posix_spawn_file_actions_addopen(file_actionsp,
5432 fd, PyBytes_AS_STRING(path), oflag, (mode_t)mode);
Pablo Galindocb970732018-06-19 09:19:50 +01005433 Py_DECREF(path);
Serhiy Storchakaef347532018-05-01 16:45:04 +03005434 if (errno) {
5435 posix_error();
5436 goto fail;
5437 }
5438 break;
5439 }
5440 case POSIX_SPAWN_CLOSE: {
5441 int fd;
5442 if (!PyArg_ParseTuple(file_action, "Oi"
5443 ";A close file_action tuple must have 2 elements",
5444 &tag_obj, &fd))
5445 {
5446 goto fail;
5447 }
5448 errno = posix_spawn_file_actions_addclose(file_actionsp, fd);
5449 if (errno) {
5450 posix_error();
5451 goto fail;
5452 }
5453 break;
5454 }
5455 case POSIX_SPAWN_DUP2: {
5456 int fd1, fd2;
5457 if (!PyArg_ParseTuple(file_action, "Oii"
5458 ";A dup2 file_action tuple must have 3 elements",
5459 &tag_obj, &fd1, &fd2))
5460 {
5461 goto fail;
5462 }
5463 errno = posix_spawn_file_actions_adddup2(file_actionsp,
5464 fd1, fd2);
5465 if (errno) {
5466 posix_error();
5467 goto fail;
5468 }
5469 break;
5470 }
5471 default: {
5472 PyErr_SetString(PyExc_TypeError,
5473 "Unknown file_actions identifier");
5474 goto fail;
5475 }
5476 }
5477 Py_DECREF(file_action);
5478 }
Pablo Galindo254a4662018-09-07 16:44:24 +01005479
Serhiy Storchakaef347532018-05-01 16:45:04 +03005480 Py_DECREF(seq);
5481 return 0;
5482
5483fail:
5484 Py_DECREF(seq);
5485 Py_DECREF(file_action);
5486 (void)posix_spawn_file_actions_destroy(file_actionsp);
5487 return -1;
5488}
5489
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005490
5491static PyObject *
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005492py_posix_spawn(int use_posix_spawnp, PyObject *module, path_t *path, PyObject *argv,
5493 PyObject *env, PyObject *file_actions,
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005494 PyObject *setpgroup, int resetids, int setsid, PyObject *setsigmask,
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005495 PyObject *setsigdef, PyObject *scheduler)
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005496{
Victor Stinner325e4ba2019-02-01 15:47:24 +01005497 const char *func_name = use_posix_spawnp ? "posix_spawnp" : "posix_spawn";
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005498 EXECV_CHAR **argvlist = NULL;
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005499 EXECV_CHAR **envlist = NULL;
Serhiy Storchakaef347532018-05-01 16:45:04 +03005500 posix_spawn_file_actions_t file_actions_buf;
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005501 posix_spawn_file_actions_t *file_actionsp = NULL;
Pablo Galindo254a4662018-09-07 16:44:24 +01005502 posix_spawnattr_t attr;
5503 posix_spawnattr_t *attrp = NULL;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005504 Py_ssize_t argc, envc;
Serhiy Storchakaef347532018-05-01 16:45:04 +03005505 PyObject *result = NULL;
Pablo Galindocb970732018-06-19 09:19:50 +01005506 PyObject *temp_buffer = NULL;
Serhiy Storchakaef347532018-05-01 16:45:04 +03005507 pid_t pid;
5508 int err_code;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005509
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005510 /* posix_spawn and posix_spawnp have three arguments: (path, argv, env), where
Serhiy Storchakaef347532018-05-01 16:45:04 +03005511 argv is a list or tuple of strings and env is a dictionary
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005512 like posix.environ. */
5513
Serhiy Storchakaef347532018-05-01 16:45:04 +03005514 if (!PyList_Check(argv) && !PyTuple_Check(argv)) {
Victor Stinner325e4ba2019-02-01 15:47:24 +01005515 PyErr_Format(PyExc_TypeError,
5516 "%s: argv must be a tuple or list", func_name);
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005517 goto exit;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005518 }
5519 argc = PySequence_Size(argv);
5520 if (argc < 1) {
Victor Stinner325e4ba2019-02-01 15:47:24 +01005521 PyErr_Format(PyExc_ValueError,
5522 "%s: argv must not be empty", func_name);
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005523 return NULL;
5524 }
5525
5526 if (!PyMapping_Check(env)) {
Victor Stinner325e4ba2019-02-01 15:47:24 +01005527 PyErr_Format(PyExc_TypeError,
5528 "%s: environment must be a mapping object", func_name);
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005529 goto exit;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005530 }
5531
5532 argvlist = parse_arglist(argv, &argc);
5533 if (argvlist == NULL) {
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005534 goto exit;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005535 }
5536 if (!argvlist[0][0]) {
Victor Stinner325e4ba2019-02-01 15:47:24 +01005537 PyErr_Format(PyExc_ValueError,
5538 "%s: argv first element cannot be empty", func_name);
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005539 goto exit;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005540 }
5541
5542 envlist = parse_envlist(env, &envc);
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005543 if (envlist == NULL) {
5544 goto exit;
5545 }
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005546
Anthony Shaw948ed8c2019-05-10 12:00:06 +10005547 if (file_actions != NULL && file_actions != Py_None) {
Pablo Galindocb970732018-06-19 09:19:50 +01005548 /* There is a bug in old versions of glibc that makes some of the
5549 * helper functions for manipulating file actions not copy the provided
5550 * buffers. The problem is that posix_spawn_file_actions_addopen does not
5551 * copy the value of path for some old versions of glibc (<2.20).
5552 * The use of temp_buffer here is a workaround that keeps the
5553 * python objects that own the buffers alive until posix_spawn gets called.
5554 * Check https://bugs.python.org/issue33630 and
5555 * https://sourceware.org/bugzilla/show_bug.cgi?id=17048 for more info.*/
5556 temp_buffer = PyList_New(0);
5557 if (!temp_buffer) {
5558 goto exit;
5559 }
5560 if (parse_file_actions(file_actions, &file_actions_buf, temp_buffer)) {
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005561 goto exit;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005562 }
Serhiy Storchakaef347532018-05-01 16:45:04 +03005563 file_actionsp = &file_actions_buf;
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005564 }
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005565
Victor Stinner325e4ba2019-02-01 15:47:24 +01005566 if (parse_posix_spawn_flags(func_name, setpgroup, resetids, setsid,
5567 setsigmask, setsigdef, scheduler, &attr)) {
Pablo Galindo254a4662018-09-07 16:44:24 +01005568 goto exit;
5569 }
5570 attrp = &attr;
5571
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005572 _Py_BEGIN_SUPPRESS_IPH
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005573#ifdef HAVE_POSIX_SPAWNP
5574 if (use_posix_spawnp) {
5575 err_code = posix_spawnp(&pid, path->narrow,
5576 file_actionsp, attrp, argvlist, envlist);
5577 }
5578 else
5579#endif /* HAVE_POSIX_SPAWNP */
5580 {
5581 err_code = posix_spawn(&pid, path->narrow,
5582 file_actionsp, attrp, argvlist, envlist);
5583 }
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005584 _Py_END_SUPPRESS_IPH
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005585
Serhiy Storchakaef347532018-05-01 16:45:04 +03005586 if (err_code) {
5587 errno = err_code;
5588 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, path->object);
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005589 goto exit;
5590 }
Gregory P. Smith1d300ce2018-12-30 21:13:02 -08005591#ifdef _Py_MEMORY_SANITIZER
5592 __msan_unpoison(&pid, sizeof(pid));
5593#endif
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005594 result = PyLong_FromPid(pid);
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005595
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005596exit:
Serhiy Storchakaef347532018-05-01 16:45:04 +03005597 if (file_actionsp) {
5598 (void)posix_spawn_file_actions_destroy(file_actionsp);
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005599 }
Pablo Galindo254a4662018-09-07 16:44:24 +01005600 if (attrp) {
5601 (void)posix_spawnattr_destroy(attrp);
5602 }
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005603 if (envlist) {
5604 free_string_array(envlist, envc);
5605 }
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005606 if (argvlist) {
5607 free_string_array(argvlist, argc);
5608 }
Pablo Galindocb970732018-06-19 09:19:50 +01005609 Py_XDECREF(temp_buffer);
Pablo Galindo0cd6bca2018-01-29 20:34:42 +00005610 return result;
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005611}
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005612
5613
5614/*[clinic input]
5615
5616os.posix_spawn
5617 path: path_t
5618 Path of executable file.
5619 argv: object
5620 Tuple or list of strings.
5621 env: object
5622 Dictionary of strings mapping to strings.
5623 /
5624 *
5625 file_actions: object(c_default='NULL') = ()
5626 A sequence of file action tuples.
5627 setpgroup: object = NULL
5628 The pgroup to use with the POSIX_SPAWN_SETPGROUP flag.
5629 resetids: bool(accept={int}) = False
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005630 If the value is `true` the POSIX_SPAWN_RESETIDS will be activated.
5631 setsid: bool(accept={int}) = False
5632 If the value is `true` the POSIX_SPAWN_SETSID or POSIX_SPAWN_SETSID_NP will be activated.
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005633 setsigmask: object(c_default='NULL') = ()
5634 The sigmask to use with the POSIX_SPAWN_SETSIGMASK flag.
5635 setsigdef: object(c_default='NULL') = ()
5636 The sigmask to use with the POSIX_SPAWN_SETSIGDEF flag.
5637 scheduler: object = NULL
5638 A tuple with the scheduler policy (optional) and parameters.
5639
5640Execute the program specified by path in a new process.
5641[clinic start generated code]*/
5642
5643static PyObject *
5644os_posix_spawn_impl(PyObject *module, path_t *path, PyObject *argv,
5645 PyObject *env, PyObject *file_actions,
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005646 PyObject *setpgroup, int resetids, int setsid,
5647 PyObject *setsigmask, PyObject *setsigdef,
5648 PyObject *scheduler)
5649/*[clinic end generated code: output=14a1098c566bc675 input=8c6305619a00ad04]*/
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005650{
5651 return py_posix_spawn(0, module, path, argv, env, file_actions,
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005652 setpgroup, resetids, setsid, setsigmask, setsigdef,
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005653 scheduler);
5654}
5655 #endif /* HAVE_POSIX_SPAWN */
5656
5657
5658
5659#ifdef HAVE_POSIX_SPAWNP
5660/*[clinic input]
5661
5662os.posix_spawnp
5663 path: path_t
5664 Path of executable file.
5665 argv: object
5666 Tuple or list of strings.
5667 env: object
5668 Dictionary of strings mapping to strings.
5669 /
5670 *
5671 file_actions: object(c_default='NULL') = ()
5672 A sequence of file action tuples.
5673 setpgroup: object = NULL
5674 The pgroup to use with the POSIX_SPAWN_SETPGROUP flag.
5675 resetids: bool(accept={int}) = False
5676 If the value is `True` the POSIX_SPAWN_RESETIDS will be activated.
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005677 setsid: bool(accept={int}) = False
5678 If the value is `True` the POSIX_SPAWN_SETSID or POSIX_SPAWN_SETSID_NP will be activated.
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005679 setsigmask: object(c_default='NULL') = ()
5680 The sigmask to use with the POSIX_SPAWN_SETSIGMASK flag.
5681 setsigdef: object(c_default='NULL') = ()
5682 The sigmask to use with the POSIX_SPAWN_SETSIGDEF flag.
5683 scheduler: object = NULL
5684 A tuple with the scheduler policy (optional) and parameters.
5685
5686Execute the program specified by path in a new process.
5687[clinic start generated code]*/
5688
5689static PyObject *
5690os_posix_spawnp_impl(PyObject *module, path_t *path, PyObject *argv,
5691 PyObject *env, PyObject *file_actions,
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005692 PyObject *setpgroup, int resetids, int setsid,
5693 PyObject *setsigmask, PyObject *setsigdef,
5694 PyObject *scheduler)
5695/*[clinic end generated code: output=7b9aaefe3031238d input=c1911043a22028da]*/
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005696{
5697 return py_posix_spawn(1, module, path, argv, env, file_actions,
Joannah Nanjekye80c5dfe2019-02-01 13:05:22 +03005698 setpgroup, resetids, setsid, setsigmask, setsigdef,
Joannah Nanjekye92b83222019-01-16 16:29:26 +03005699 scheduler);
5700}
5701#endif /* HAVE_POSIX_SPAWNP */
Pablo Galindo6c6ddf92018-01-29 01:56:10 +00005702
pxinwrf2d7ac72019-05-21 18:46:37 +08005703#ifdef HAVE_RTPSPAWN
5704static intptr_t
5705_rtp_spawn(int mode, const char *rtpFileName, const char *argv[],
5706 const char *envp[])
5707{
5708 RTP_ID rtpid;
5709 int status;
5710 pid_t res;
5711 int async_err = 0;
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00005712
pxinwrf2d7ac72019-05-21 18:46:37 +08005713 /* Set priority=100 and uStackSize=16 MiB (0x1000000) for new processes.
5714 uStackSize=0 cannot be used, the default stack size is too small for
5715 Python. */
5716 if (envp) {
5717 rtpid = rtpSpawn(rtpFileName, argv, envp,
5718 100, 0x1000000, 0, VX_FP_TASK);
5719 }
5720 else {
5721 rtpid = rtpSpawn(rtpFileName, argv, (const char **)environ,
5722 100, 0x1000000, 0, VX_FP_TASK);
5723 }
5724 if ((rtpid != RTP_ID_ERROR) && (mode == _P_WAIT)) {
5725 do {
5726 res = waitpid((pid_t)rtpid, &status, 0);
5727 } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
5728
5729 if (res < 0)
5730 return RTP_ID_ERROR;
5731 return ((intptr_t)status);
5732 }
5733 return ((intptr_t)rtpid);
5734}
5735#endif
5736
5737#if defined(HAVE_SPAWNV) || defined(HAVE_WSPAWNV) || defined(HAVE_RTPSPAWN)
Larry Hastings2f936352014-08-05 14:04:04 +10005738/*[clinic input]
5739os.spawnv
5740
5741 mode: int
5742 Mode of process creation.
Steve Dowercc16be82016-09-08 10:35:16 -07005743 path: path_t
Larry Hastings2f936352014-08-05 14:04:04 +10005744 Path of executable file.
5745 argv: object
5746 Tuple or list of strings.
5747 /
5748
5749Execute the program specified by path in a new process.
5750[clinic start generated code]*/
5751
Larry Hastings2f936352014-08-05 14:04:04 +10005752static PyObject *
Steve Dowercc16be82016-09-08 10:35:16 -07005753os_spawnv_impl(PyObject *module, int mode, path_t *path, PyObject *argv)
5754/*[clinic end generated code: output=71cd037a9d96b816 input=43224242303291be]*/
Larry Hastings2f936352014-08-05 14:04:04 +10005755{
Steve Dowercc16be82016-09-08 10:35:16 -07005756 EXECV_CHAR **argvlist;
Larry Hastings2f936352014-08-05 14:04:04 +10005757 int i;
Victor Stinner8c62be82010-05-06 00:08:46 +00005758 Py_ssize_t argc;
Benjamin Petersonca470632016-09-06 13:47:26 -07005759 intptr_t spawnval;
Victor Stinner8c62be82010-05-06 00:08:46 +00005760 PyObject *(*getitem)(PyObject *, Py_ssize_t);
Guido van Rossuma1065681999-01-25 23:20:23 +00005761
Victor Stinner8c62be82010-05-06 00:08:46 +00005762 /* spawnv has three arguments: (mode, path, argv), where
5763 argv is a list or tuple of strings. */
Guido van Rossuma1065681999-01-25 23:20:23 +00005764
Victor Stinner8c62be82010-05-06 00:08:46 +00005765 if (PyList_Check(argv)) {
5766 argc = PyList_Size(argv);
5767 getitem = PyList_GetItem;
5768 }
5769 else if (PyTuple_Check(argv)) {
5770 argc = PyTuple_Size(argv);
5771 getitem = PyTuple_GetItem;
5772 }
5773 else {
5774 PyErr_SetString(PyExc_TypeError,
5775 "spawnv() arg 2 must be a tuple or list");
Victor Stinner8c62be82010-05-06 00:08:46 +00005776 return NULL;
5777 }
Steve Dower859fd7b2016-11-19 18:53:19 -08005778 if (argc == 0) {
5779 PyErr_SetString(PyExc_ValueError,
5780 "spawnv() arg 2 cannot be empty");
5781 return NULL;
5782 }
Guido van Rossuma1065681999-01-25 23:20:23 +00005783
Steve Dowercc16be82016-09-08 10:35:16 -07005784 argvlist = PyMem_NEW(EXECV_CHAR *, argc+1);
Victor Stinner8c62be82010-05-06 00:08:46 +00005785 if (argvlist == NULL) {
Victor Stinner8c62be82010-05-06 00:08:46 +00005786 return PyErr_NoMemory();
5787 }
5788 for (i = 0; i < argc; i++) {
5789 if (!fsconvert_strdup((*getitem)(argv, i),
5790 &argvlist[i])) {
5791 free_string_array(argvlist, i);
5792 PyErr_SetString(
5793 PyExc_TypeError,
5794 "spawnv() arg 2 must contain only strings");
Victor Stinner8c62be82010-05-06 00:08:46 +00005795 return NULL;
5796 }
Steve Dower93ff8722016-11-19 19:03:54 -08005797 if (i == 0 && !argvlist[0][0]) {
Victor Stinner8acb4cf2017-06-15 15:30:40 +02005798 free_string_array(argvlist, i + 1);
Steve Dower93ff8722016-11-19 19:03:54 -08005799 PyErr_SetString(
5800 PyExc_ValueError,
5801 "spawnv() arg 2 first element cannot be empty");
5802 return NULL;
5803 }
Victor Stinner8c62be82010-05-06 00:08:46 +00005804 }
5805 argvlist[argc] = NULL;
Guido van Rossuma1065681999-01-25 23:20:23 +00005806
pxinwrf2d7ac72019-05-21 18:46:37 +08005807#if !defined(HAVE_RTPSPAWN)
Victor Stinner8c62be82010-05-06 00:08:46 +00005808 if (mode == _OLD_P_OVERLAY)
5809 mode = _P_OVERLAY;
pxinwrf2d7ac72019-05-21 18:46:37 +08005810#endif
Tim Peters5aa91602002-01-30 05:46:57 +00005811
Victor Stinner8c62be82010-05-06 00:08:46 +00005812 Py_BEGIN_ALLOW_THREADS
Steve Dower654a7bd2016-09-11 20:19:32 -07005813 _Py_BEGIN_SUPPRESS_IPH
Steve Dowercc16be82016-09-08 10:35:16 -07005814#ifdef HAVE_WSPAWNV
5815 spawnval = _wspawnv(mode, path->wide, argvlist);
pxinwrf2d7ac72019-05-21 18:46:37 +08005816#elif defined(HAVE_RTPSPAWN)
5817 spawnval = _rtp_spawn(mode, path->narrow, (const char **)argvlist, NULL);
Steve Dowercc16be82016-09-08 10:35:16 -07005818#else
5819 spawnval = _spawnv(mode, path->narrow, argvlist);
5820#endif
Steve Dower654a7bd2016-09-11 20:19:32 -07005821 _Py_END_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00005822 Py_END_ALLOW_THREADS
Tim Peters5aa91602002-01-30 05:46:57 +00005823
Victor Stinner8c62be82010-05-06 00:08:46 +00005824 free_string_array(argvlist, argc);
Guido van Rossuma1065681999-01-25 23:20:23 +00005825
Victor Stinner8c62be82010-05-06 00:08:46 +00005826 if (spawnval == -1)
5827 return posix_error();
5828 else
Richard Oudkerkac0ad882013-06-05 23:29:30 +01005829 return Py_BuildValue(_Py_PARSE_INTPTR, spawnval);
Guido van Rossuma1065681999-01-25 23:20:23 +00005830}
5831
Larry Hastings2f936352014-08-05 14:04:04 +10005832/*[clinic input]
5833os.spawnve
5834
5835 mode: int
5836 Mode of process creation.
Steve Dowercc16be82016-09-08 10:35:16 -07005837 path: path_t
Larry Hastings2f936352014-08-05 14:04:04 +10005838 Path of executable file.
5839 argv: object
5840 Tuple or list of strings.
5841 env: object
5842 Dictionary of strings mapping to strings.
5843 /
5844
5845Execute the program specified by path in a new process.
5846[clinic start generated code]*/
5847
Larry Hastings2f936352014-08-05 14:04:04 +10005848static PyObject *
Steve Dowercc16be82016-09-08 10:35:16 -07005849os_spawnve_impl(PyObject *module, int mode, path_t *path, PyObject *argv,
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005850 PyObject *env)
Steve Dowercc16be82016-09-08 10:35:16 -07005851/*[clinic end generated code: output=30fe85be56fe37ad input=3e40803ee7c4c586]*/
Larry Hastings2f936352014-08-05 14:04:04 +10005852{
Steve Dowercc16be82016-09-08 10:35:16 -07005853 EXECV_CHAR **argvlist;
5854 EXECV_CHAR **envlist;
Victor Stinner8c62be82010-05-06 00:08:46 +00005855 PyObject *res = NULL;
Antoine Pitrou22e41552010-08-15 18:07:50 +00005856 Py_ssize_t argc, i, envc;
Benjamin Petersonca470632016-09-06 13:47:26 -07005857 intptr_t spawnval;
Victor Stinner8c62be82010-05-06 00:08:46 +00005858 PyObject *(*getitem)(PyObject *, Py_ssize_t);
Victor Stinnerc8d6ab22017-06-23 15:04:46 +02005859 Py_ssize_t lastarg = 0;
Guido van Rossuma1065681999-01-25 23:20:23 +00005860
Victor Stinner8c62be82010-05-06 00:08:46 +00005861 /* spawnve has four arguments: (mode, path, argv, env), where
5862 argv is a list or tuple of strings and env is a dictionary
5863 like posix.environ. */
Guido van Rossuma1065681999-01-25 23:20:23 +00005864
Victor Stinner8c62be82010-05-06 00:08:46 +00005865 if (PyList_Check(argv)) {
5866 argc = PyList_Size(argv);
5867 getitem = PyList_GetItem;
5868 }
5869 else if (PyTuple_Check(argv)) {
5870 argc = PyTuple_Size(argv);
5871 getitem = PyTuple_GetItem;
5872 }
5873 else {
5874 PyErr_SetString(PyExc_TypeError,
5875 "spawnve() arg 2 must be a tuple or list");
5876 goto fail_0;
5877 }
Steve Dower859fd7b2016-11-19 18:53:19 -08005878 if (argc == 0) {
5879 PyErr_SetString(PyExc_ValueError,
5880 "spawnve() arg 2 cannot be empty");
5881 goto fail_0;
5882 }
Victor Stinner8c62be82010-05-06 00:08:46 +00005883 if (!PyMapping_Check(env)) {
5884 PyErr_SetString(PyExc_TypeError,
5885 "spawnve() arg 3 must be a mapping object");
5886 goto fail_0;
5887 }
Guido van Rossuma1065681999-01-25 23:20:23 +00005888
Steve Dowercc16be82016-09-08 10:35:16 -07005889 argvlist = PyMem_NEW(EXECV_CHAR *, argc+1);
Victor Stinner8c62be82010-05-06 00:08:46 +00005890 if (argvlist == NULL) {
5891 PyErr_NoMemory();
5892 goto fail_0;
5893 }
5894 for (i = 0; i < argc; i++) {
5895 if (!fsconvert_strdup((*getitem)(argv, i),
5896 &argvlist[i]))
5897 {
5898 lastarg = i;
5899 goto fail_1;
5900 }
Steve Dowerbce26262016-11-19 19:17:26 -08005901 if (i == 0 && !argvlist[0][0]) {
Victor Stinnerc8d6ab22017-06-23 15:04:46 +02005902 lastarg = i + 1;
Steve Dowerbce26262016-11-19 19:17:26 -08005903 PyErr_SetString(
5904 PyExc_ValueError,
5905 "spawnv() arg 2 first element cannot be empty");
5906 goto fail_1;
5907 }
Victor Stinner8c62be82010-05-06 00:08:46 +00005908 }
5909 lastarg = argc;
5910 argvlist[argc] = NULL;
Guido van Rossuma1065681999-01-25 23:20:23 +00005911
Victor Stinner8c62be82010-05-06 00:08:46 +00005912 envlist = parse_envlist(env, &envc);
5913 if (envlist == NULL)
5914 goto fail_1;
Guido van Rossuma1065681999-01-25 23:20:23 +00005915
pxinwrf2d7ac72019-05-21 18:46:37 +08005916#if !defined(HAVE_RTPSPAWN)
Victor Stinner8c62be82010-05-06 00:08:46 +00005917 if (mode == _OLD_P_OVERLAY)
5918 mode = _P_OVERLAY;
pxinwrf2d7ac72019-05-21 18:46:37 +08005919#endif
Tim Peters25059d32001-12-07 20:35:43 +00005920
Victor Stinner8c62be82010-05-06 00:08:46 +00005921 Py_BEGIN_ALLOW_THREADS
Steve Dower654a7bd2016-09-11 20:19:32 -07005922 _Py_BEGIN_SUPPRESS_IPH
Steve Dowercc16be82016-09-08 10:35:16 -07005923#ifdef HAVE_WSPAWNV
5924 spawnval = _wspawnve(mode, path->wide, argvlist, envlist);
pxinwrf2d7ac72019-05-21 18:46:37 +08005925#elif defined(HAVE_RTPSPAWN)
5926 spawnval = _rtp_spawn(mode, path->narrow, (const char **)argvlist,
5927 (const char **)envlist);
Steve Dowercc16be82016-09-08 10:35:16 -07005928#else
5929 spawnval = _spawnve(mode, path->narrow, argvlist, envlist);
5930#endif
Steve Dower654a7bd2016-09-11 20:19:32 -07005931 _Py_END_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00005932 Py_END_ALLOW_THREADS
Tim Peters25059d32001-12-07 20:35:43 +00005933
Victor Stinner8c62be82010-05-06 00:08:46 +00005934 if (spawnval == -1)
5935 (void) posix_error();
5936 else
Richard Oudkerkac0ad882013-06-05 23:29:30 +01005937 res = Py_BuildValue(_Py_PARSE_INTPTR, spawnval);
Guido van Rossuma1065681999-01-25 23:20:23 +00005938
Victor Stinner8c62be82010-05-06 00:08:46 +00005939 while (--envc >= 0)
5940 PyMem_DEL(envlist[envc]);
5941 PyMem_DEL(envlist);
Guido van Rossum0847c5c2002-12-13 18:36:22 +00005942 fail_1:
Victor Stinnerc8d6ab22017-06-23 15:04:46 +02005943 free_string_array(argvlist, lastarg);
Martin v. Löwis114619e2002-10-07 06:44:21 +00005944 fail_0:
Victor Stinner8c62be82010-05-06 00:08:46 +00005945 return res;
Guido van Rossuma1065681999-01-25 23:20:23 +00005946}
Andrew MacIntyre69e18c92004-04-04 07:11:43 +00005947
Guido van Rossuma1065681999-01-25 23:20:23 +00005948#endif /* HAVE_SPAWNV */
5949
5950
Antoine Pitrou346cbd32017-05-27 17:50:54 +02005951#ifdef HAVE_FORK
Gregory P. Smith163468a2017-05-29 10:03:41 -07005952
5953/* Helper function to validate arguments.
5954 Returns 0 on success. non-zero on failure with a TypeError raised.
5955 If obj is non-NULL it must be callable. */
5956static int
5957check_null_or_callable(PyObject *obj, const char* obj_name)
5958{
5959 if (obj && !PyCallable_Check(obj)) {
5960 PyErr_Format(PyExc_TypeError, "'%s' must be callable, not %s",
5961 obj_name, Py_TYPE(obj)->tp_name);
5962 return -1;
5963 }
5964 return 0;
5965}
5966
Antoine Pitrou346cbd32017-05-27 17:50:54 +02005967/*[clinic input]
5968os.register_at_fork
5969
Gregory P. Smith163468a2017-05-29 10:03:41 -07005970 *
5971 before: object=NULL
5972 A callable to be called in the parent before the fork() syscall.
5973 after_in_child: object=NULL
5974 A callable to be called in the child after fork().
5975 after_in_parent: object=NULL
5976 A callable to be called in the parent after fork().
Antoine Pitrou346cbd32017-05-27 17:50:54 +02005977
Gregory P. Smith163468a2017-05-29 10:03:41 -07005978Register callables to be called when forking a new process.
Antoine Pitrou346cbd32017-05-27 17:50:54 +02005979
Gregory P. Smith163468a2017-05-29 10:03:41 -07005980'before' callbacks are called in reverse order.
5981'after_in_child' and 'after_in_parent' callbacks are called in order.
Antoine Pitrou346cbd32017-05-27 17:50:54 +02005982
5983[clinic start generated code]*/
5984
5985static PyObject *
Gregory P. Smith163468a2017-05-29 10:03:41 -07005986os_register_at_fork_impl(PyObject *module, PyObject *before,
5987 PyObject *after_in_child, PyObject *after_in_parent)
5988/*[clinic end generated code: output=5398ac75e8e97625 input=cd1187aa85d2312e]*/
Antoine Pitrou346cbd32017-05-27 17:50:54 +02005989{
5990 PyInterpreterState *interp;
Antoine Pitrou346cbd32017-05-27 17:50:54 +02005991
Gregory P. Smith163468a2017-05-29 10:03:41 -07005992 if (!before && !after_in_child && !after_in_parent) {
5993 PyErr_SetString(PyExc_TypeError, "At least one argument is required.");
5994 return NULL;
5995 }
5996 if (check_null_or_callable(before, "before") ||
5997 check_null_or_callable(after_in_child, "after_in_child") ||
5998 check_null_or_callable(after_in_parent, "after_in_parent")) {
Antoine Pitrou346cbd32017-05-27 17:50:54 +02005999 return NULL;
6000 }
Victor Stinnercaba55b2018-08-03 15:33:52 +02006001 interp = _PyInterpreterState_Get();
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006002
Gregory P. Smith163468a2017-05-29 10:03:41 -07006003 if (register_at_forker(&interp->before_forkers, before)) {
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006004 return NULL;
6005 }
Gregory P. Smith163468a2017-05-29 10:03:41 -07006006 if (register_at_forker(&interp->after_forkers_child, after_in_child)) {
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006007 return NULL;
Gregory P. Smith163468a2017-05-29 10:03:41 -07006008 }
6009 if (register_at_forker(&interp->after_forkers_parent, after_in_parent)) {
6010 return NULL;
6011 }
6012 Py_RETURN_NONE;
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006013}
6014#endif /* HAVE_FORK */
6015
6016
Guido van Rossum2242f2f2001-04-11 20:58:20 +00006017#ifdef HAVE_FORK1
Larry Hastings2f936352014-08-05 14:04:04 +10006018/*[clinic input]
6019os.fork1
6020
6021Fork a child process with a single multiplexed (i.e., not bound) thread.
6022
6023Return 0 to child process and PID of child to parent process.
6024[clinic start generated code]*/
6025
Larry Hastings2f936352014-08-05 14:04:04 +10006026static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006027os_fork1_impl(PyObject *module)
6028/*[clinic end generated code: output=0de8e67ce2a310bc input=12db02167893926e]*/
Guido van Rossum2242f2f2001-04-11 20:58:20 +00006029{
Victor Stinner8c62be82010-05-06 00:08:46 +00006030 pid_t pid;
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006031
Eric Snow59032962018-09-14 14:17:20 -07006032 if (_PyInterpreterState_Get() != PyInterpreterState_Main()) {
6033 PyErr_SetString(PyExc_RuntimeError, "fork not supported for subinterpreters");
6034 return NULL;
6035 }
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006036 PyOS_BeforeFork();
Victor Stinner8c62be82010-05-06 00:08:46 +00006037 pid = fork1();
6038 if (pid == 0) {
6039 /* child: this clobbers and resets the import lock. */
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006040 PyOS_AfterFork_Child();
Victor Stinner8c62be82010-05-06 00:08:46 +00006041 } else {
6042 /* parent: release the import lock. */
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006043 PyOS_AfterFork_Parent();
Victor Stinner8c62be82010-05-06 00:08:46 +00006044 }
6045 if (pid == -1)
6046 return posix_error();
Victor Stinner8c62be82010-05-06 00:08:46 +00006047 return PyLong_FromPid(pid);
Guido van Rossum2242f2f2001-04-11 20:58:20 +00006048}
Larry Hastings2f936352014-08-05 14:04:04 +10006049#endif /* HAVE_FORK1 */
Guido van Rossum2242f2f2001-04-11 20:58:20 +00006050
6051
Guido van Rossumad0ee831995-03-01 10:34:45 +00006052#ifdef HAVE_FORK
Larry Hastings2f936352014-08-05 14:04:04 +10006053/*[clinic input]
6054os.fork
6055
6056Fork a child process.
6057
6058Return 0 to child process and PID of child to parent process.
6059[clinic start generated code]*/
6060
Larry Hastings2f936352014-08-05 14:04:04 +10006061static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006062os_fork_impl(PyObject *module)
6063/*[clinic end generated code: output=3626c81f98985d49 input=13c956413110eeaa]*/
Guido van Rossum85e3b011991-06-03 12:42:10 +00006064{
Victor Stinner8c62be82010-05-06 00:08:46 +00006065 pid_t pid;
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006066
Eric Snow59032962018-09-14 14:17:20 -07006067 if (_PyInterpreterState_Get() != PyInterpreterState_Main()) {
6068 PyErr_SetString(PyExc_RuntimeError, "fork not supported for subinterpreters");
6069 return NULL;
6070 }
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006071 PyOS_BeforeFork();
Victor Stinner8c62be82010-05-06 00:08:46 +00006072 pid = fork();
6073 if (pid == 0) {
6074 /* child: this clobbers and resets the import lock. */
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006075 PyOS_AfterFork_Child();
Victor Stinner8c62be82010-05-06 00:08:46 +00006076 } else {
6077 /* parent: release the import lock. */
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006078 PyOS_AfterFork_Parent();
Victor Stinner8c62be82010-05-06 00:08:46 +00006079 }
6080 if (pid == -1)
6081 return posix_error();
Victor Stinner8c62be82010-05-06 00:08:46 +00006082 return PyLong_FromPid(pid);
Guido van Rossum85e3b011991-06-03 12:42:10 +00006083}
Larry Hastings2f936352014-08-05 14:04:04 +10006084#endif /* HAVE_FORK */
6085
Guido van Rossum85e3b011991-06-03 12:42:10 +00006086
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006087#ifdef HAVE_SCHED_H
Charles-François Nataliea0d5fc2011-09-06 19:03:35 +02006088#ifdef HAVE_SCHED_GET_PRIORITY_MAX
Larry Hastings2f936352014-08-05 14:04:04 +10006089/*[clinic input]
6090os.sched_get_priority_max
Charles-François Nataliea0d5fc2011-09-06 19:03:35 +02006091
Larry Hastings2f936352014-08-05 14:04:04 +10006092 policy: int
6093
6094Get the maximum 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_max_impl(PyObject *module, int policy)
6099/*[clinic end generated code: output=9e465c6e43130521 input=2097b7998eca6874]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006100{
6101 int max;
6102
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006103 max = sched_get_priority_max(policy);
6104 if (max < 0)
6105 return posix_error();
6106 return PyLong_FromLong(max);
6107}
6108
Larry Hastings2f936352014-08-05 14:04:04 +10006109
6110/*[clinic input]
6111os.sched_get_priority_min
6112
6113 policy: int
6114
6115Get the minimum scheduling priority for policy.
6116[clinic start generated code]*/
6117
Larry Hastings2f936352014-08-05 14:04:04 +10006118static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006119os_sched_get_priority_min_impl(PyObject *module, int policy)
6120/*[clinic end generated code: output=7595c1138cc47a6d input=21bc8fa0d70983bf]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006121{
6122 int min = sched_get_priority_min(policy);
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006123 if (min < 0)
6124 return posix_error();
6125 return PyLong_FromLong(min);
6126}
Charles-François Nataliea0d5fc2011-09-06 19:03:35 +02006127#endif /* HAVE_SCHED_GET_PRIORITY_MAX */
6128
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006129
Larry Hastings2f936352014-08-05 14:04:04 +10006130#ifdef HAVE_SCHED_SETSCHEDULER
6131/*[clinic input]
6132os.sched_getscheduler
6133 pid: pid_t
6134 /
6135
6136Get the scheduling policy for the process identifiedy by pid.
6137
6138Passing 0 for pid returns the scheduling policy for the calling process.
6139[clinic start generated code]*/
6140
Larry Hastings2f936352014-08-05 14:04:04 +10006141static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006142os_sched_getscheduler_impl(PyObject *module, pid_t pid)
6143/*[clinic end generated code: output=dce4c0bd3f1b34c8 input=5f14cfd1f189e1a0]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006144{
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006145 int policy;
6146
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006147 policy = sched_getscheduler(pid);
6148 if (policy < 0)
6149 return posix_error();
6150 return PyLong_FromLong(policy);
6151}
Larry Hastings2f936352014-08-05 14:04:04 +10006152#endif /* HAVE_SCHED_SETSCHEDULER */
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006153
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006154
William Orr81574b82018-10-01 22:19:56 -07006155#if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
Larry Hastings2f936352014-08-05 14:04:04 +10006156/*[clinic input]
Eddie Elizondo474eedf2018-11-13 04:09:31 -08006157class os.sched_param "PyObject *" "SchedParamType"
Larry Hastings2f936352014-08-05 14:04:04 +10006158
6159@classmethod
6160os.sched_param.__new__
6161
6162 sched_priority: object
6163 A scheduling parameter.
6164
6165Current has only one field: sched_priority");
6166[clinic start generated code]*/
6167
Larry Hastings2f936352014-08-05 14:04:04 +10006168static PyObject *
6169os_sched_param_impl(PyTypeObject *type, PyObject *sched_priority)
Eddie Elizondo474eedf2018-11-13 04:09:31 -08006170/*[clinic end generated code: output=48f4067d60f48c13 input=ab4de35a9a7811f2]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006171{
6172 PyObject *res;
6173
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006174 res = PyStructSequence_New(type);
6175 if (!res)
6176 return NULL;
Larry Hastings2f936352014-08-05 14:04:04 +10006177 Py_INCREF(sched_priority);
6178 PyStructSequence_SET_ITEM(res, 0, sched_priority);
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006179 return res;
6180}
6181
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006182
Serhiy Storchaka1009bf12015-04-03 23:53:51 +03006183PyDoc_VAR(os_sched_param__doc__);
6184
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006185static PyStructSequence_Field sched_param_fields[] = {
6186 {"sched_priority", "the scheduling priority"},
6187 {0}
6188};
6189
6190static PyStructSequence_Desc sched_param_desc = {
6191 "sched_param", /* name */
Larry Hastings2f936352014-08-05 14:04:04 +10006192 os_sched_param__doc__, /* doc */
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006193 sched_param_fields,
6194 1
6195};
6196
6197static int
6198convert_sched_param(PyObject *param, struct sched_param *res)
6199{
6200 long priority;
6201
Eddie Elizondo474eedf2018-11-13 04:09:31 -08006202 if (Py_TYPE(param) != SchedParamType) {
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006203 PyErr_SetString(PyExc_TypeError, "must have a sched_param object");
6204 return 0;
6205 }
6206 priority = PyLong_AsLong(PyStructSequence_GET_ITEM(param, 0));
6207 if (priority == -1 && PyErr_Occurred())
6208 return 0;
6209 if (priority > INT_MAX || priority < INT_MIN) {
6210 PyErr_SetString(PyExc_OverflowError, "sched_priority out of range");
6211 return 0;
6212 }
6213 res->sched_priority = Py_SAFE_DOWNCAST(priority, long, int);
6214 return 1;
6215}
William Orr81574b82018-10-01 22:19:56 -07006216#endif /* defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM) */
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006217
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006218
6219#ifdef HAVE_SCHED_SETSCHEDULER
Larry Hastings2f936352014-08-05 14:04:04 +10006220/*[clinic input]
6221os.sched_setscheduler
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006222
Larry Hastings2f936352014-08-05 14:04:04 +10006223 pid: pid_t
6224 policy: int
6225 param: sched_param
6226 /
6227
6228Set the scheduling policy for the process identified by pid.
6229
6230If pid is 0, the calling process is changed.
6231param is an instance of sched_param.
6232[clinic start generated code]*/
6233
Larry Hastings2f936352014-08-05 14:04:04 +10006234static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006235os_sched_setscheduler_impl(PyObject *module, pid_t pid, int policy,
Larry Hastings89964c42015-04-14 18:07:59 -04006236 struct sched_param *param)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006237/*[clinic end generated code: output=b0ac0a70d3b1d705 input=c581f9469a5327dd]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006238{
Jesus Cea9c822272011-09-10 01:40:52 +02006239 /*
Jesus Cea54b01492011-09-10 01:53:19 +02006240 ** sched_setscheduler() returns 0 in Linux, but the previous
6241 ** scheduling policy under Solaris/Illumos, and others.
6242 ** On error, -1 is returned in all Operating Systems.
Jesus Cea9c822272011-09-10 01:40:52 +02006243 */
Larry Hastings2f936352014-08-05 14:04:04 +10006244 if (sched_setscheduler(pid, policy, param) == -1)
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006245 return posix_error();
6246 Py_RETURN_NONE;
6247}
Larry Hastings2f936352014-08-05 14:04:04 +10006248#endif /* HAVE_SCHED_SETSCHEDULER*/
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006249
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006250
6251#ifdef HAVE_SCHED_SETPARAM
Larry Hastings2f936352014-08-05 14:04:04 +10006252/*[clinic input]
6253os.sched_getparam
6254 pid: pid_t
6255 /
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006256
Larry Hastings2f936352014-08-05 14:04:04 +10006257Returns scheduling parameters for the process identified by pid.
6258
6259If pid is 0, returns parameters for the calling process.
6260Return value is an instance of sched_param.
6261[clinic start generated code]*/
6262
Larry Hastings2f936352014-08-05 14:04:04 +10006263static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006264os_sched_getparam_impl(PyObject *module, pid_t pid)
6265/*[clinic end generated code: output=b194e8708dcf2db8 input=18a1ef9c2efae296]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006266{
6267 struct sched_param param;
6268 PyObject *result;
6269 PyObject *priority;
6270
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006271 if (sched_getparam(pid, &param))
6272 return posix_error();
Eddie Elizondo474eedf2018-11-13 04:09:31 -08006273 result = PyStructSequence_New(SchedParamType);
Larry Hastings2f936352014-08-05 14:04:04 +10006274 if (!result)
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006275 return NULL;
6276 priority = PyLong_FromLong(param.sched_priority);
6277 if (!priority) {
Larry Hastings2f936352014-08-05 14:04:04 +10006278 Py_DECREF(result);
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006279 return NULL;
6280 }
Larry Hastings2f936352014-08-05 14:04:04 +10006281 PyStructSequence_SET_ITEM(result, 0, priority);
6282 return result;
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006283}
6284
Larry Hastings2f936352014-08-05 14:04:04 +10006285
6286/*[clinic input]
6287os.sched_setparam
6288 pid: pid_t
6289 param: sched_param
6290 /
6291
6292Set scheduling parameters for the process identified by pid.
6293
6294If pid is 0, sets parameters for the calling process.
6295param should be an instance of sched_param.
6296[clinic start generated code]*/
6297
Larry Hastings2f936352014-08-05 14:04:04 +10006298static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006299os_sched_setparam_impl(PyObject *module, pid_t pid,
Larry Hastings89964c42015-04-14 18:07:59 -04006300 struct sched_param *param)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006301/*[clinic end generated code: output=8af013f78a32b591 input=6b8d6dfcecdc21bd]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006302{
6303 if (sched_setparam(pid, param))
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006304 return posix_error();
6305 Py_RETURN_NONE;
6306}
Larry Hastings2f936352014-08-05 14:04:04 +10006307#endif /* HAVE_SCHED_SETPARAM */
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006308
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006309
6310#ifdef HAVE_SCHED_RR_GET_INTERVAL
Larry Hastings2f936352014-08-05 14:04:04 +10006311/*[clinic input]
6312os.sched_rr_get_interval -> double
6313 pid: pid_t
6314 /
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006315
Larry Hastings2f936352014-08-05 14:04:04 +10006316Return the round-robin quantum for the process identified by pid, in seconds.
6317
6318Value returned is a float.
6319[clinic start generated code]*/
6320
Larry Hastings2f936352014-08-05 14:04:04 +10006321static double
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006322os_sched_rr_get_interval_impl(PyObject *module, pid_t pid)
6323/*[clinic end generated code: output=7e2d935833ab47dc input=2a973da15cca6fae]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006324{
6325 struct timespec interval;
6326 if (sched_rr_get_interval(pid, &interval)) {
6327 posix_error();
6328 return -1.0;
6329 }
Gregory P. Smith1d300ce2018-12-30 21:13:02 -08006330#ifdef _Py_MEMORY_SANITIZER
6331 __msan_unpoison(&interval, sizeof(interval));
6332#endif
Larry Hastings2f936352014-08-05 14:04:04 +10006333 return (double)interval.tv_sec + 1e-9*interval.tv_nsec;
6334}
6335#endif /* HAVE_SCHED_RR_GET_INTERVAL */
Benjamin Petersonc5fce4d2011-08-02 18:07:32 -05006336
Larry Hastings2f936352014-08-05 14:04:04 +10006337
6338/*[clinic input]
6339os.sched_yield
6340
6341Voluntarily relinquish the CPU.
6342[clinic start generated code]*/
6343
Larry Hastings2f936352014-08-05 14:04:04 +10006344static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006345os_sched_yield_impl(PyObject *module)
6346/*[clinic end generated code: output=902323500f222cac input=e54d6f98189391d4]*/
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006347{
6348 if (sched_yield())
6349 return posix_error();
6350 Py_RETURN_NONE;
6351}
6352
Benjamin Peterson2740af82011-08-02 17:41:34 -05006353#ifdef HAVE_SCHED_SETAFFINITY
Antoine Pitrou84869872012-08-04 16:16:35 +02006354/* The minimum number of CPUs allocated in a cpu_set_t */
6355static const int NCPUS_START = sizeof(unsigned long) * CHAR_BIT;
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006356
Larry Hastings2f936352014-08-05 14:04:04 +10006357/*[clinic input]
6358os.sched_setaffinity
6359 pid: pid_t
6360 mask : object
6361 /
6362
6363Set the CPU affinity of the process identified by pid to mask.
6364
6365mask should be an iterable of integers identifying CPUs.
6366[clinic start generated code]*/
6367
Larry Hastings2f936352014-08-05 14:04:04 +10006368static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006369os_sched_setaffinity_impl(PyObject *module, pid_t pid, PyObject *mask)
6370/*[clinic end generated code: output=882d7dd9a229335b input=a0791a597c7085ba]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006371{
Antoine Pitrou84869872012-08-04 16:16:35 +02006372 int ncpus;
6373 size_t setsize;
Larry Hastings2f936352014-08-05 14:04:04 +10006374 cpu_set_t *cpu_set = NULL;
6375 PyObject *iterator = NULL, *item;
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006376
Larry Hastings2f936352014-08-05 14:04:04 +10006377 iterator = PyObject_GetIter(mask);
Antoine Pitrou84869872012-08-04 16:16:35 +02006378 if (iterator == NULL)
6379 return NULL;
6380
6381 ncpus = NCPUS_START;
6382 setsize = CPU_ALLOC_SIZE(ncpus);
Larry Hastings2f936352014-08-05 14:04:04 +10006383 cpu_set = CPU_ALLOC(ncpus);
6384 if (cpu_set == NULL) {
Antoine Pitrou84869872012-08-04 16:16:35 +02006385 PyErr_NoMemory();
6386 goto error;
6387 }
Larry Hastings2f936352014-08-05 14:04:04 +10006388 CPU_ZERO_S(setsize, cpu_set);
Antoine Pitrou84869872012-08-04 16:16:35 +02006389
6390 while ((item = PyIter_Next(iterator))) {
6391 long cpu;
6392 if (!PyLong_Check(item)) {
6393 PyErr_Format(PyExc_TypeError,
6394 "expected an iterator of ints, "
6395 "but iterator yielded %R",
6396 Py_TYPE(item));
6397 Py_DECREF(item);
6398 goto error;
6399 }
6400 cpu = PyLong_AsLong(item);
6401 Py_DECREF(item);
6402 if (cpu < 0) {
6403 if (!PyErr_Occurred())
6404 PyErr_SetString(PyExc_ValueError, "negative CPU number");
6405 goto error;
6406 }
6407 if (cpu > INT_MAX - 1) {
6408 PyErr_SetString(PyExc_OverflowError, "CPU number too large");
6409 goto error;
6410 }
6411 if (cpu >= ncpus) {
6412 /* Grow CPU mask to fit the CPU number */
6413 int newncpus = ncpus;
6414 cpu_set_t *newmask;
6415 size_t newsetsize;
6416 while (newncpus <= cpu) {
6417 if (newncpus > INT_MAX / 2)
6418 newncpus = cpu + 1;
6419 else
6420 newncpus = newncpus * 2;
6421 }
6422 newmask = CPU_ALLOC(newncpus);
6423 if (newmask == NULL) {
6424 PyErr_NoMemory();
6425 goto error;
6426 }
6427 newsetsize = CPU_ALLOC_SIZE(newncpus);
6428 CPU_ZERO_S(newsetsize, newmask);
Larry Hastings2f936352014-08-05 14:04:04 +10006429 memcpy(newmask, cpu_set, setsize);
6430 CPU_FREE(cpu_set);
Antoine Pitrou84869872012-08-04 16:16:35 +02006431 setsize = newsetsize;
Larry Hastings2f936352014-08-05 14:04:04 +10006432 cpu_set = newmask;
Antoine Pitrou84869872012-08-04 16:16:35 +02006433 ncpus = newncpus;
6434 }
Larry Hastings2f936352014-08-05 14:04:04 +10006435 CPU_SET_S(cpu, setsize, cpu_set);
Antoine Pitrou84869872012-08-04 16:16:35 +02006436 }
Miss Islington (bot)6fbed532019-06-27 09:45:30 -07006437 if (PyErr_Occurred()) {
6438 goto error;
6439 }
Antoine Pitrou84869872012-08-04 16:16:35 +02006440 Py_CLEAR(iterator);
6441
Larry Hastings2f936352014-08-05 14:04:04 +10006442 if (sched_setaffinity(pid, setsize, cpu_set)) {
Antoine Pitrou84869872012-08-04 16:16:35 +02006443 posix_error();
6444 goto error;
6445 }
Larry Hastings2f936352014-08-05 14:04:04 +10006446 CPU_FREE(cpu_set);
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006447 Py_RETURN_NONE;
Antoine Pitrou84869872012-08-04 16:16:35 +02006448
6449error:
Larry Hastings2f936352014-08-05 14:04:04 +10006450 if (cpu_set)
6451 CPU_FREE(cpu_set);
Antoine Pitrou84869872012-08-04 16:16:35 +02006452 Py_XDECREF(iterator);
6453 return NULL;
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006454}
6455
Larry Hastings2f936352014-08-05 14:04:04 +10006456
6457/*[clinic input]
6458os.sched_getaffinity
6459 pid: pid_t
6460 /
6461
Charles-François Natalidc87e4b2015-07-13 21:01:39 +01006462Return the affinity of the process identified by pid (or the current process if zero).
Larry Hastings2f936352014-08-05 14:04:04 +10006463
6464The affinity is returned as a set of CPU identifiers.
6465[clinic start generated code]*/
6466
Larry Hastings2f936352014-08-05 14:04:04 +10006467static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006468os_sched_getaffinity_impl(PyObject *module, pid_t pid)
Serhiy Storchaka2954f832016-07-07 18:20:03 +03006469/*[clinic end generated code: output=f726f2c193c17a4f input=983ce7cb4a565980]*/
Larry Hastings2f936352014-08-05 14:04:04 +10006470{
Antoine Pitrou84869872012-08-04 16:16:35 +02006471 int cpu, ncpus, count;
6472 size_t setsize;
6473 cpu_set_t *mask = NULL;
6474 PyObject *res = NULL;
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006475
Antoine Pitrou84869872012-08-04 16:16:35 +02006476 ncpus = NCPUS_START;
6477 while (1) {
6478 setsize = CPU_ALLOC_SIZE(ncpus);
6479 mask = CPU_ALLOC(ncpus);
6480 if (mask == NULL)
6481 return PyErr_NoMemory();
6482 if (sched_getaffinity(pid, setsize, mask) == 0)
6483 break;
6484 CPU_FREE(mask);
6485 if (errno != EINVAL)
6486 return posix_error();
6487 if (ncpus > INT_MAX / 2) {
6488 PyErr_SetString(PyExc_OverflowError, "could not allocate "
6489 "a large enough CPU set");
6490 return NULL;
6491 }
6492 ncpus = ncpus * 2;
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006493 }
Antoine Pitrou84869872012-08-04 16:16:35 +02006494
6495 res = PySet_New(NULL);
6496 if (res == NULL)
6497 goto error;
6498 for (cpu = 0, count = CPU_COUNT_S(setsize, mask); count; cpu++) {
6499 if (CPU_ISSET_S(cpu, setsize, mask)) {
6500 PyObject *cpu_num = PyLong_FromLong(cpu);
6501 --count;
6502 if (cpu_num == NULL)
6503 goto error;
6504 if (PySet_Add(res, cpu_num)) {
6505 Py_DECREF(cpu_num);
6506 goto error;
6507 }
6508 Py_DECREF(cpu_num);
6509 }
6510 }
6511 CPU_FREE(mask);
6512 return res;
6513
6514error:
6515 if (mask)
6516 CPU_FREE(mask);
6517 Py_XDECREF(res);
6518 return NULL;
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006519}
6520
Benjamin Peterson2740af82011-08-02 17:41:34 -05006521#endif /* HAVE_SCHED_SETAFFINITY */
6522
Benjamin Peterson94b580d2011-08-02 17:30:04 -05006523#endif /* HAVE_SCHED_H */
6524
Larry Hastings2f936352014-08-05 14:04:04 +10006525
Neal Norwitzb59798b2003-03-21 01:43:31 +00006526/* AIX uses /dev/ptc but is otherwise the same as /dev/ptmx */
Neal Norwitz2deaddb2003-03-21 03:08:31 +00006527/* IRIX has both /dev/ptc and /dev/ptmx, use ptmx */
6528#if defined(HAVE_DEV_PTC) && !defined(HAVE_DEV_PTMX)
Neal Norwitzb59798b2003-03-21 01:43:31 +00006529#define DEV_PTY_FILE "/dev/ptc"
6530#define HAVE_DEV_PTMX
6531#else
6532#define DEV_PTY_FILE "/dev/ptmx"
6533#endif
6534
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006535#if defined(HAVE_OPENPTY) || defined(HAVE_FORKPTY) || defined(HAVE_DEV_PTMX)
Fred Drake8cef4cf2000-06-28 16:40:38 +00006536#ifdef HAVE_PTY_H
6537#include <pty.h>
6538#else
6539#ifdef HAVE_LIBUTIL_H
6540#include <libutil.h>
Ronald Oussoren755740f2010-02-07 19:56:39 +00006541#else
6542#ifdef HAVE_UTIL_H
6543#include <util.h>
6544#endif /* HAVE_UTIL_H */
Fred Drake8cef4cf2000-06-28 16:40:38 +00006545#endif /* HAVE_LIBUTIL_H */
6546#endif /* HAVE_PTY_H */
Martin v. Löwis14e73b12003-01-01 09:51:12 +00006547#ifdef HAVE_STROPTS_H
6548#include <stropts.h>
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006549#endif
ngie-eign7745ec42018-02-14 11:54:28 -08006550#endif /* defined(HAVE_OPENPTY) || defined(HAVE_FORKPTY) || defined(HAVE_DEV_PTMX) */
Fred Drake8cef4cf2000-06-28 16:40:38 +00006551
Larry Hastings2f936352014-08-05 14:04:04 +10006552
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006553#if defined(HAVE_OPENPTY) || defined(HAVE__GETPTY) || defined(HAVE_DEV_PTMX)
Larry Hastings2f936352014-08-05 14:04:04 +10006554/*[clinic input]
6555os.openpty
6556
6557Open a pseudo-terminal.
6558
6559Return a tuple of (master_fd, slave_fd) containing open file descriptors
6560for both the master and slave ends.
6561[clinic start generated code]*/
6562
Larry Hastings2f936352014-08-05 14:04:04 +10006563static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006564os_openpty_impl(PyObject *module)
6565/*[clinic end generated code: output=98841ce5ec9cef3c input=f3d99fd99e762907]*/
Fred Drake8cef4cf2000-06-28 16:40:38 +00006566{
Victor Stinnerdaf45552013-08-28 00:53:59 +02006567 int master_fd = -1, slave_fd = -1;
Thomas Wouters70c21a12000-07-14 14:28:33 +00006568#ifndef HAVE_OPENPTY
Victor Stinner8c62be82010-05-06 00:08:46 +00006569 char * slave_name;
Thomas Wouters70c21a12000-07-14 14:28:33 +00006570#endif
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006571#if defined(HAVE_DEV_PTMX) && !defined(HAVE_OPENPTY) && !defined(HAVE__GETPTY)
Victor Stinner8c62be82010-05-06 00:08:46 +00006572 PyOS_sighandler_t sig_saved;
Jakub Kulík6f9bc722018-12-31 03:16:40 +01006573#if defined(__sun) && defined(__SVR4)
Victor Stinner8c62be82010-05-06 00:08:46 +00006574 extern char *ptsname(int fildes);
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006575#endif
6576#endif
Thomas Wouters70c21a12000-07-14 14:28:33 +00006577
Thomas Wouters70c21a12000-07-14 14:28:33 +00006578#ifdef HAVE_OPENPTY
Victor Stinner8c62be82010-05-06 00:08:46 +00006579 if (openpty(&master_fd, &slave_fd, NULL, NULL, NULL) != 0)
Victor Stinnerdaf45552013-08-28 00:53:59 +02006580 goto posix_error;
6581
6582 if (_Py_set_inheritable(master_fd, 0, NULL) < 0)
6583 goto error;
6584 if (_Py_set_inheritable(slave_fd, 0, NULL) < 0)
6585 goto error;
6586
Neal Norwitzb59798b2003-03-21 01:43:31 +00006587#elif defined(HAVE__GETPTY)
Victor Stinner8c62be82010-05-06 00:08:46 +00006588 slave_name = _getpty(&master_fd, O_RDWR, 0666, 0);
6589 if (slave_name == NULL)
Victor Stinnerdaf45552013-08-28 00:53:59 +02006590 goto posix_error;
6591 if (_Py_set_inheritable(master_fd, 0, NULL) < 0)
6592 goto error;
Thomas Wouters70c21a12000-07-14 14:28:33 +00006593
Victor Stinnerdaf45552013-08-28 00:53:59 +02006594 slave_fd = _Py_open(slave_name, O_RDWR);
Victor Stinner8c62be82010-05-06 00:08:46 +00006595 if (slave_fd < 0)
Victor Stinnera555cfc2015-03-18 00:22:14 +01006596 goto error;
Victor Stinnerdaf45552013-08-28 00:53:59 +02006597
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006598#else
Victor Stinner000de532013-11-25 23:19:58 +01006599 master_fd = open(DEV_PTY_FILE, O_RDWR | O_NOCTTY); /* open master */
Victor Stinner8c62be82010-05-06 00:08:46 +00006600 if (master_fd < 0)
Victor Stinnerdaf45552013-08-28 00:53:59 +02006601 goto posix_error;
6602
Victor Stinner8c62be82010-05-06 00:08:46 +00006603 sig_saved = PyOS_setsig(SIGCHLD, SIG_DFL);
Victor Stinnerdaf45552013-08-28 00:53:59 +02006604
Victor Stinner8c62be82010-05-06 00:08:46 +00006605 /* change permission of slave */
6606 if (grantpt(master_fd) < 0) {
6607 PyOS_setsig(SIGCHLD, sig_saved);
Victor Stinnerdaf45552013-08-28 00:53:59 +02006608 goto posix_error;
Victor Stinner8c62be82010-05-06 00:08:46 +00006609 }
Victor Stinnerdaf45552013-08-28 00:53:59 +02006610
Victor Stinner8c62be82010-05-06 00:08:46 +00006611 /* unlock slave */
6612 if (unlockpt(master_fd) < 0) {
6613 PyOS_setsig(SIGCHLD, sig_saved);
Victor Stinnerdaf45552013-08-28 00:53:59 +02006614 goto posix_error;
Victor Stinner8c62be82010-05-06 00:08:46 +00006615 }
Victor Stinnerdaf45552013-08-28 00:53:59 +02006616
Victor Stinner8c62be82010-05-06 00:08:46 +00006617 PyOS_setsig(SIGCHLD, sig_saved);
Victor Stinnerdaf45552013-08-28 00:53:59 +02006618
Victor Stinner8c62be82010-05-06 00:08:46 +00006619 slave_name = ptsname(master_fd); /* get name of slave */
6620 if (slave_name == NULL)
Victor Stinnerdaf45552013-08-28 00:53:59 +02006621 goto posix_error;
6622
6623 slave_fd = _Py_open(slave_name, O_RDWR | O_NOCTTY); /* open slave */
Victor Stinnera555cfc2015-03-18 00:22:14 +01006624 if (slave_fd == -1)
6625 goto error;
Victor Stinner000de532013-11-25 23:19:58 +01006626
6627 if (_Py_set_inheritable(master_fd, 0, NULL) < 0)
6628 goto posix_error;
6629
Stefan Krahfb7c8ae2016-04-26 17:04:18 +02006630#if !defined(__CYGWIN__) && !defined(__ANDROID__) && !defined(HAVE_DEV_PTC)
Victor Stinner8c62be82010-05-06 00:08:46 +00006631 ioctl(slave_fd, I_PUSH, "ptem"); /* push ptem */
6632 ioctl(slave_fd, I_PUSH, "ldterm"); /* push ldterm */
Neal Norwitz6700e472002-12-31 16:16:07 +00006633#ifndef __hpux
Victor Stinner8c62be82010-05-06 00:08:46 +00006634 ioctl(slave_fd, I_PUSH, "ttcompat"); /* push ttcompat */
Neal Norwitz6700e472002-12-31 16:16:07 +00006635#endif /* __hpux */
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006636#endif /* HAVE_CYGWIN */
Thomas Wouters1e0c2f42000-07-24 16:06:23 +00006637#endif /* HAVE_OPENPTY */
Thomas Wouters70c21a12000-07-14 14:28:33 +00006638
Victor Stinner8c62be82010-05-06 00:08:46 +00006639 return Py_BuildValue("(ii)", master_fd, slave_fd);
Thomas Wouters70c21a12000-07-14 14:28:33 +00006640
Victor Stinnerdaf45552013-08-28 00:53:59 +02006641posix_error:
6642 posix_error();
6643error:
6644 if (master_fd != -1)
6645 close(master_fd);
6646 if (slave_fd != -1)
6647 close(slave_fd);
6648 return NULL;
Fred Drake8cef4cf2000-06-28 16:40:38 +00006649}
Martin v. Löwis24a880b2002-12-31 12:55:15 +00006650#endif /* defined(HAVE_OPENPTY) || defined(HAVE__GETPTY) || defined(HAVE_DEV_PTMX) */
Fred Drake8cef4cf2000-06-28 16:40:38 +00006651
Larry Hastings2f936352014-08-05 14:04:04 +10006652
Fred Drake8cef4cf2000-06-28 16:40:38 +00006653#ifdef HAVE_FORKPTY
Larry Hastings2f936352014-08-05 14:04:04 +10006654/*[clinic input]
6655os.forkpty
6656
6657Fork a new process with a new pseudo-terminal as controlling tty.
6658
6659Returns a tuple of (pid, master_fd).
6660Like fork(), return pid of 0 to the child process,
6661and pid of child to the parent process.
6662To both, return fd of newly opened pseudo-terminal.
6663[clinic start generated code]*/
6664
Larry Hastings2f936352014-08-05 14:04:04 +10006665static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006666os_forkpty_impl(PyObject *module)
6667/*[clinic end generated code: output=60d0a5c7512e4087 input=f1f7f4bae3966010]*/
Fred Drake8cef4cf2000-06-28 16:40:38 +00006668{
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006669 int master_fd = -1;
Victor Stinner8c62be82010-05-06 00:08:46 +00006670 pid_t pid;
Tim Peters5aa91602002-01-30 05:46:57 +00006671
Eric Snow59032962018-09-14 14:17:20 -07006672 if (_PyInterpreterState_Get() != PyInterpreterState_Main()) {
6673 PyErr_SetString(PyExc_RuntimeError, "fork not supported for subinterpreters");
6674 return NULL;
6675 }
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006676 PyOS_BeforeFork();
Victor Stinner8c62be82010-05-06 00:08:46 +00006677 pid = forkpty(&master_fd, NULL, NULL, NULL);
6678 if (pid == 0) {
6679 /* child: this clobbers and resets the import lock. */
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006680 PyOS_AfterFork_Child();
Victor Stinner8c62be82010-05-06 00:08:46 +00006681 } else {
6682 /* parent: release the import lock. */
Antoine Pitrou346cbd32017-05-27 17:50:54 +02006683 PyOS_AfterFork_Parent();
Victor Stinner8c62be82010-05-06 00:08:46 +00006684 }
6685 if (pid == -1)
6686 return posix_error();
Victor Stinner8c62be82010-05-06 00:08:46 +00006687 return Py_BuildValue("(Ni)", PyLong_FromPid(pid), master_fd);
Fred Drake8cef4cf2000-06-28 16:40:38 +00006688}
Larry Hastings2f936352014-08-05 14:04:04 +10006689#endif /* HAVE_FORKPTY */
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00006690
Ross Lagerwall7807c352011-03-17 20:20:30 +02006691
Guido van Rossumad0ee831995-03-01 10:34:45 +00006692#ifdef HAVE_GETEGID
Larry Hastings2f936352014-08-05 14:04:04 +10006693/*[clinic input]
6694os.getegid
6695
6696Return the current process's effective group id.
6697[clinic start generated code]*/
6698
Larry Hastings2f936352014-08-05 14:04:04 +10006699static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006700os_getegid_impl(PyObject *module)
6701/*[clinic end generated code: output=67d9be7ac68898a2 input=1596f79ad1107d5d]*/
Guido van Rossum46003ff1992-05-15 11:05:24 +00006702{
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02006703 return _PyLong_FromGid(getegid());
Guido van Rossum46003ff1992-05-15 11:05:24 +00006704}
Larry Hastings2f936352014-08-05 14:04:04 +10006705#endif /* HAVE_GETEGID */
Guido van Rossum46003ff1992-05-15 11:05:24 +00006706
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00006707
Guido van Rossumad0ee831995-03-01 10:34:45 +00006708#ifdef HAVE_GETEUID
Larry Hastings2f936352014-08-05 14:04:04 +10006709/*[clinic input]
6710os.geteuid
6711
6712Return the current process's effective user id.
6713[clinic start generated code]*/
6714
Larry Hastings2f936352014-08-05 14:04:04 +10006715static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006716os_geteuid_impl(PyObject *module)
6717/*[clinic end generated code: output=ea1b60f0d6abb66e input=4644c662d3bd9f19]*/
Guido van Rossum46003ff1992-05-15 11:05:24 +00006718{
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02006719 return _PyLong_FromUid(geteuid());
Guido van Rossum46003ff1992-05-15 11:05:24 +00006720}
Larry Hastings2f936352014-08-05 14:04:04 +10006721#endif /* HAVE_GETEUID */
Guido van Rossum46003ff1992-05-15 11:05:24 +00006722
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00006723
Guido van Rossumad0ee831995-03-01 10:34:45 +00006724#ifdef HAVE_GETGID
Larry Hastings2f936352014-08-05 14:04:04 +10006725/*[clinic input]
6726os.getgid
6727
6728Return the current process's group id.
6729[clinic start generated code]*/
6730
Larry Hastings2f936352014-08-05 14:04:04 +10006731static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006732os_getgid_impl(PyObject *module)
6733/*[clinic end generated code: output=4f28ebc9d3e5dfcf input=58796344cd87c0f6]*/
Guido van Rossum46003ff1992-05-15 11:05:24 +00006734{
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02006735 return _PyLong_FromGid(getgid());
Guido van Rossum46003ff1992-05-15 11:05:24 +00006736}
Larry Hastings2f936352014-08-05 14:04:04 +10006737#endif /* HAVE_GETGID */
Guido van Rossum46003ff1992-05-15 11:05:24 +00006738
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00006739
Berker Peksag39404992016-09-15 20:45:16 +03006740#ifdef HAVE_GETPID
Larry Hastings2f936352014-08-05 14:04:04 +10006741/*[clinic input]
6742os.getpid
6743
6744Return the current process id.
6745[clinic start generated code]*/
6746
Larry Hastings2f936352014-08-05 14:04:04 +10006747static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006748os_getpid_impl(PyObject *module)
6749/*[clinic end generated code: output=9ea6fdac01ed2b3c input=5a9a00f0ab68aa00]*/
Guido van Rossum85e3b011991-06-03 12:42:10 +00006750{
Victor Stinner8c62be82010-05-06 00:08:46 +00006751 return PyLong_FromPid(getpid());
Guido van Rossum85e3b011991-06-03 12:42:10 +00006752}
Berker Peksag39404992016-09-15 20:45:16 +03006753#endif /* HAVE_GETPID */
Guido van Rossum85e3b011991-06-03 12:42:10 +00006754
Miss Islington (bot)c80183e2019-06-13 00:27:23 -07006755#ifdef NGROUPS_MAX
6756#define MAX_GROUPS NGROUPS_MAX
6757#else
6758 /* defined to be 16 on Solaris7, so this should be a small number */
6759#define MAX_GROUPS 64
6760#endif
6761
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006762#ifdef HAVE_GETGROUPLIST
Larry Hastings2f936352014-08-05 14:04:04 +10006763
6764/* AC 3.5: funny apple logic below */
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006765PyDoc_STRVAR(posix_getgrouplist__doc__,
6766"getgrouplist(user, group) -> list of groups to which a user belongs\n\n\
6767Returns a list of groups to which a user belongs.\n\n\
6768 user: username to lookup\n\
6769 group: base group id of the user");
6770
6771static PyObject *
6772posix_getgrouplist(PyObject *self, PyObject *args)
6773{
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006774 const char *user;
6775 int i, ngroups;
6776 PyObject *list;
6777#ifdef __APPLE__
6778 int *groups, basegid;
6779#else
6780 gid_t *groups, basegid;
6781#endif
Miss Islington (bot)c80183e2019-06-13 00:27:23 -07006782
6783 /*
6784 * NGROUPS_MAX is defined by POSIX.1 as the maximum
6785 * number of supplimental groups a users can belong to.
6786 * We have to increment it by one because
6787 * getgrouplist() returns both the supplemental groups
6788 * and the primary group, i.e. all of the groups the
6789 * user belongs to.
6790 */
6791 ngroups = 1 + MAX_GROUPS;
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006792
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02006793#ifdef __APPLE__
6794 if (!PyArg_ParseTuple(args, "si:getgrouplist", &user, &basegid))
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006795 return NULL;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02006796#else
6797 if (!PyArg_ParseTuple(args, "sO&:getgrouplist", &user,
6798 _Py_Gid_Converter, &basegid))
6799 return NULL;
6800#endif
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006801
6802#ifdef __APPLE__
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02006803 groups = PyMem_New(int, ngroups);
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006804#else
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02006805 groups = PyMem_New(gid_t, ngroups);
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006806#endif
6807 if (groups == NULL)
6808 return PyErr_NoMemory();
6809
6810 if (getgrouplist(user, basegid, groups, &ngroups) == -1) {
6811 PyMem_Del(groups);
6812 return posix_error();
6813 }
6814
Gregory P. Smith1d300ce2018-12-30 21:13:02 -08006815#ifdef _Py_MEMORY_SANITIZER
6816 /* Clang memory sanitizer libc intercepts don't know getgrouplist. */
6817 __msan_unpoison(&ngroups, sizeof(ngroups));
6818 __msan_unpoison(groups, ngroups*sizeof(*groups));
6819#endif
6820
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006821 list = PyList_New(ngroups);
6822 if (list == NULL) {
6823 PyMem_Del(groups);
6824 return NULL;
6825 }
6826
6827 for (i = 0; i < ngroups; i++) {
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02006828#ifdef __APPLE__
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006829 PyObject *o = PyLong_FromUnsignedLong((unsigned long)groups[i]);
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02006830#else
6831 PyObject *o = _PyLong_FromGid(groups[i]);
6832#endif
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +02006833 if (o == NULL) {
6834 Py_DECREF(list);
6835 PyMem_Del(groups);
6836 return NULL;
6837 }
6838 PyList_SET_ITEM(list, i, o);
6839 }
6840
6841 PyMem_Del(groups);
6842
6843 return list;
6844}
Larry Hastings2f936352014-08-05 14:04:04 +10006845#endif /* HAVE_GETGROUPLIST */
6846
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00006847
Fred Drakec9680921999-12-13 16:37:25 +00006848#ifdef HAVE_GETGROUPS
Larry Hastings2f936352014-08-05 14:04:04 +10006849/*[clinic input]
6850os.getgroups
6851
6852Return list of supplemental group IDs for the process.
6853[clinic start generated code]*/
6854
Larry Hastings2f936352014-08-05 14:04:04 +10006855static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03006856os_getgroups_impl(PyObject *module)
6857/*[clinic end generated code: output=42b0c17758561b56 input=d3f109412e6a155c]*/
Fred Drakec9680921999-12-13 16:37:25 +00006858{
6859 PyObject *result = NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00006860 gid_t grouplist[MAX_GROUPS];
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00006861
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00006862 /* On MacOSX getgroups(2) can return more than MAX_GROUPS results
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00006863 * This is a helper variable to store the intermediate result when
6864 * that happens.
6865 *
6866 * To keep the code readable the OSX behaviour is unconditional,
6867 * according to the POSIX spec this should be safe on all unix-y
6868 * systems.
6869 */
6870 gid_t* alt_grouplist = grouplist;
Victor Stinner8c62be82010-05-06 00:08:46 +00006871 int n;
Fred Drakec9680921999-12-13 16:37:25 +00006872
Ned Deilyb5dd6d22013-08-01 21:21:15 -07006873#ifdef __APPLE__
6874 /* Issue #17557: As of OS X 10.8, getgroups(2) no longer raises EINVAL if
6875 * there are more groups than can fit in grouplist. Therefore, on OS X
6876 * always first call getgroups with length 0 to get the actual number
6877 * of groups.
6878 */
6879 n = getgroups(0, NULL);
6880 if (n < 0) {
6881 return posix_error();
6882 } else if (n <= MAX_GROUPS) {
6883 /* groups will fit in existing array */
6884 alt_grouplist = grouplist;
6885 } else {
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02006886 alt_grouplist = PyMem_New(gid_t, n);
Ned Deilyb5dd6d22013-08-01 21:21:15 -07006887 if (alt_grouplist == NULL) {
Zackery Spytz4c49da02018-12-07 03:11:30 -07006888 return PyErr_NoMemory();
Ned Deilyb5dd6d22013-08-01 21:21:15 -07006889 }
6890 }
6891
6892 n = getgroups(n, alt_grouplist);
6893 if (n == -1) {
6894 if (alt_grouplist != grouplist) {
6895 PyMem_Free(alt_grouplist);
6896 }
6897 return posix_error();
6898 }
6899#else
Victor Stinner8c62be82010-05-06 00:08:46 +00006900 n = getgroups(MAX_GROUPS, grouplist);
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00006901 if (n < 0) {
6902 if (errno == EINVAL) {
6903 n = getgroups(0, NULL);
6904 if (n == -1) {
6905 return posix_error();
6906 }
6907 if (n == 0) {
6908 /* Avoid malloc(0) */
6909 alt_grouplist = grouplist;
6910 } else {
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02006911 alt_grouplist = PyMem_New(gid_t, n);
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00006912 if (alt_grouplist == NULL) {
Zackery Spytz4c49da02018-12-07 03:11:30 -07006913 return PyErr_NoMemory();
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00006914 }
6915 n = getgroups(n, alt_grouplist);
6916 if (n == -1) {
6917 PyMem_Free(alt_grouplist);
6918 return posix_error();
6919 }
6920 }
6921 } else {
6922 return posix_error();
6923 }
6924 }
Ned Deilyb5dd6d22013-08-01 21:21:15 -07006925#endif
6926
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00006927 result = PyList_New(n);
6928 if (result != NULL) {
Victor Stinner8c62be82010-05-06 00:08:46 +00006929 int i;
6930 for (i = 0; i < n; ++i) {
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02006931 PyObject *o = _PyLong_FromGid(alt_grouplist[i]);
Victor Stinner8c62be82010-05-06 00:08:46 +00006932 if (o == NULL) {
Stefan Krah0e803b32010-11-26 16:16:47 +00006933 Py_DECREF(result);
6934 result = NULL;
6935 break;
Fred Drakec9680921999-12-13 16:37:25 +00006936 }
Victor Stinner8c62be82010-05-06 00:08:46 +00006937 PyList_SET_ITEM(result, i, o);
Fred Drakec9680921999-12-13 16:37:25 +00006938 }
Ronald Oussorenb6ee4f52010-07-23 13:53:51 +00006939 }
6940
6941 if (alt_grouplist != grouplist) {
6942 PyMem_Free(alt_grouplist);
Victor Stinner8c62be82010-05-06 00:08:46 +00006943 }
Neal Norwitze241ce82003-02-17 18:17:05 +00006944
Fred Drakec9680921999-12-13 16:37:25 +00006945 return result;
6946}
Larry Hastings2f936352014-08-05 14:04:04 +10006947#endif /* HAVE_GETGROUPS */
Fred Drakec9680921999-12-13 16:37:25 +00006948
Antoine Pitroub7572f02009-12-02 20:46:48 +00006949#ifdef HAVE_INITGROUPS
6950PyDoc_STRVAR(posix_initgroups__doc__,
6951"initgroups(username, gid) -> None\n\n\
6952Call the system initgroups() to initialize the group access list with all of\n\
6953the groups of which the specified username is a member, plus the specified\n\
6954group id.");
6955
Larry Hastings2f936352014-08-05 14:04:04 +10006956/* AC 3.5: funny apple logic */
Antoine Pitroub7572f02009-12-02 20:46:48 +00006957static PyObject *
6958posix_initgroups(PyObject *self, PyObject *args)
6959{
Victor Stinner61ec5dc2010-08-15 09:22:44 +00006960 PyObject *oname;
Serhiy Storchakadeab18d2016-05-07 16:45:18 +03006961 const char *username;
Victor Stinner61ec5dc2010-08-15 09:22:44 +00006962 int res;
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02006963#ifdef __APPLE__
6964 int gid;
6965#else
6966 gid_t gid;
6967#endif
Antoine Pitroub7572f02009-12-02 20:46:48 +00006968
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02006969#ifdef __APPLE__
6970 if (!PyArg_ParseTuple(args, "O&i:initgroups",
6971 PyUnicode_FSConverter, &oname,
6972 &gid))
6973#else
6974 if (!PyArg_ParseTuple(args, "O&O&:initgroups",
6975 PyUnicode_FSConverter, &oname,
6976 _Py_Gid_Converter, &gid))
6977#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00006978 return NULL;
Victor Stinner61ec5dc2010-08-15 09:22:44 +00006979 username = PyBytes_AS_STRING(oname);
Antoine Pitroub7572f02009-12-02 20:46:48 +00006980
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02006981 res = initgroups(username, gid);
Victor Stinner61ec5dc2010-08-15 09:22:44 +00006982 Py_DECREF(oname);
6983 if (res == -1)
Victor Stinner8c62be82010-05-06 00:08:46 +00006984 return PyErr_SetFromErrno(PyExc_OSError);
Antoine Pitroub7572f02009-12-02 20:46:48 +00006985
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02006986 Py_RETURN_NONE;
Antoine Pitroub7572f02009-12-02 20:46:48 +00006987}
Larry Hastings2f936352014-08-05 14:04:04 +10006988#endif /* HAVE_INITGROUPS */
6989
Antoine Pitroub7572f02009-12-02 20:46:48 +00006990
Martin v. Löwis606edc12002-06-13 21:09:11 +00006991#ifdef HAVE_GETPGID
Larry Hastings2f936352014-08-05 14:04:04 +10006992/*[clinic input]
6993os.getpgid
6994
6995 pid: pid_t
6996
6997Call the system call getpgid(), and return the result.
6998[clinic start generated code]*/
6999
Larry Hastings2f936352014-08-05 14:04:04 +10007000static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007001os_getpgid_impl(PyObject *module, pid_t pid)
7002/*[clinic end generated code: output=1db95a97be205d18 input=39d710ae3baaf1c7]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007003{
7004 pid_t pgid = getpgid(pid);
Victor Stinner8c62be82010-05-06 00:08:46 +00007005 if (pgid < 0)
7006 return posix_error();
7007 return PyLong_FromPid(pgid);
Martin v. Löwis606edc12002-06-13 21:09:11 +00007008}
7009#endif /* HAVE_GETPGID */
7010
7011
Guido van Rossumb6775db1994-08-01 11:34:53 +00007012#ifdef HAVE_GETPGRP
Larry Hastings2f936352014-08-05 14:04:04 +10007013/*[clinic input]
7014os.getpgrp
7015
7016Return the current process group id.
7017[clinic start generated code]*/
7018
Larry Hastings2f936352014-08-05 14:04:04 +10007019static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007020os_getpgrp_impl(PyObject *module)
7021/*[clinic end generated code: output=c4fc381e51103cf3 input=6846fb2bb9a3705e]*/
Guido van Rossum04814471991-06-04 20:23:49 +00007022{
Guido van Rossumb6775db1994-08-01 11:34:53 +00007023#ifdef GETPGRP_HAVE_ARG
Victor Stinner8c62be82010-05-06 00:08:46 +00007024 return PyLong_FromPid(getpgrp(0));
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +00007025#else /* GETPGRP_HAVE_ARG */
Victor Stinner8c62be82010-05-06 00:08:46 +00007026 return PyLong_FromPid(getpgrp());
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +00007027#endif /* GETPGRP_HAVE_ARG */
Guido van Rossum04814471991-06-04 20:23:49 +00007028}
Guido van Rossumb6775db1994-08-01 11:34:53 +00007029#endif /* HAVE_GETPGRP */
Guido van Rossum04814471991-06-04 20:23:49 +00007030
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007031
Guido van Rossumb6775db1994-08-01 11:34:53 +00007032#ifdef HAVE_SETPGRP
Larry Hastings2f936352014-08-05 14:04:04 +10007033/*[clinic input]
7034os.setpgrp
7035
7036Make the current process the leader of its process group.
7037[clinic start generated code]*/
7038
Larry Hastings2f936352014-08-05 14:04:04 +10007039static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007040os_setpgrp_impl(PyObject *module)
7041/*[clinic end generated code: output=2554735b0a60f0a0 input=1f0619fcb5731e7e]*/
Guido van Rossumc2670a01992-09-13 20:07:29 +00007042{
Guido van Rossum64933891994-10-20 21:56:42 +00007043#ifdef SETPGRP_HAVE_ARG
Victor Stinner8c62be82010-05-06 00:08:46 +00007044 if (setpgrp(0, 0) < 0)
Guido van Rossum64933891994-10-20 21:56:42 +00007045#else /* SETPGRP_HAVE_ARG */
Victor Stinner8c62be82010-05-06 00:08:46 +00007046 if (setpgrp() < 0)
Guido van Rossum64933891994-10-20 21:56:42 +00007047#endif /* SETPGRP_HAVE_ARG */
Victor Stinner8c62be82010-05-06 00:08:46 +00007048 return posix_error();
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02007049 Py_RETURN_NONE;
Guido van Rossumc2670a01992-09-13 20:07:29 +00007050}
Guido van Rossumb6775db1994-08-01 11:34:53 +00007051#endif /* HAVE_SETPGRP */
7052
Guido van Rossumad0ee831995-03-01 10:34:45 +00007053#ifdef HAVE_GETPPID
Amaury Forgeot d'Arc4b6fdf32010-09-07 21:31:17 +00007054
7055#ifdef MS_WINDOWS
7056#include <tlhelp32.h>
7057
7058static PyObject*
7059win32_getppid()
7060{
7061 HANDLE snapshot;
7062 pid_t mypid;
7063 PyObject* result = NULL;
7064 BOOL have_record;
7065 PROCESSENTRY32 pe;
7066
7067 mypid = getpid(); /* This function never fails */
7068
7069 snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
7070 if (snapshot == INVALID_HANDLE_VALUE)
7071 return PyErr_SetFromWindowsErr(GetLastError());
7072
7073 pe.dwSize = sizeof(pe);
7074 have_record = Process32First(snapshot, &pe);
7075 while (have_record) {
7076 if (mypid == (pid_t)pe.th32ProcessID) {
7077 /* We could cache the ulong value in a static variable. */
7078 result = PyLong_FromPid((pid_t)pe.th32ParentProcessID);
7079 break;
7080 }
7081
7082 have_record = Process32Next(snapshot, &pe);
7083 }
7084
7085 /* If our loop exits and our pid was not found (result will be NULL)
7086 * then GetLastError will return ERROR_NO_MORE_FILES. This is an
7087 * error anyway, so let's raise it. */
7088 if (!result)
7089 result = PyErr_SetFromWindowsErr(GetLastError());
7090
7091 CloseHandle(snapshot);
7092
7093 return result;
7094}
7095#endif /*MS_WINDOWS*/
7096
Larry Hastings2f936352014-08-05 14:04:04 +10007097
7098/*[clinic input]
7099os.getppid
7100
7101Return the parent's process id.
7102
7103If the parent process has already exited, Windows machines will still
7104return its id; others systems will return the id of the 'init' process (1).
7105[clinic start generated code]*/
7106
Larry Hastings2f936352014-08-05 14:04:04 +10007107static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007108os_getppid_impl(PyObject *module)
7109/*[clinic end generated code: output=43b2a946a8c603b4 input=e637cb87539c030e]*/
Guido van Rossum85e3b011991-06-03 12:42:10 +00007110{
Amaury Forgeot d'Arc4b6fdf32010-09-07 21:31:17 +00007111#ifdef MS_WINDOWS
7112 return win32_getppid();
7113#else
Victor Stinner8c62be82010-05-06 00:08:46 +00007114 return PyLong_FromPid(getppid());
Guido van Rossumad0ee831995-03-01 10:34:45 +00007115#endif
Amaury Forgeot d'Arc4b6fdf32010-09-07 21:31:17 +00007116}
7117#endif /* HAVE_GETPPID */
Guido van Rossum85e3b011991-06-03 12:42:10 +00007118
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007119
Fred Drake12c6e2d1999-12-14 21:25:03 +00007120#ifdef HAVE_GETLOGIN
Larry Hastings2f936352014-08-05 14:04:04 +10007121/*[clinic input]
7122os.getlogin
7123
7124Return the actual login name.
7125[clinic start generated code]*/
7126
Larry Hastings2f936352014-08-05 14:04:04 +10007127static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007128os_getlogin_impl(PyObject *module)
7129/*[clinic end generated code: output=a32e66a7e5715dac input=2a21ab1e917163df]*/
Fred Drake12c6e2d1999-12-14 21:25:03 +00007130{
Victor Stinner8c62be82010-05-06 00:08:46 +00007131 PyObject *result = NULL;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00007132#ifdef MS_WINDOWS
Brian Curtine8e4b3b2010-09-23 20:04:14 +00007133 wchar_t user_name[UNLEN + 1];
Victor Stinner63941882011-09-29 00:42:28 +02007134 DWORD num_chars = Py_ARRAY_LENGTH(user_name);
Brian Curtine8e4b3b2010-09-23 20:04:14 +00007135
7136 if (GetUserNameW(user_name, &num_chars)) {
7137 /* num_chars is the number of unicode chars plus null terminator */
7138 result = PyUnicode_FromWideChar(user_name, num_chars - 1);
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00007139 }
7140 else
Brian Curtine8e4b3b2010-09-23 20:04:14 +00007141 result = PyErr_SetFromWindowsErr(GetLastError());
7142#else
Victor Stinner8c62be82010-05-06 00:08:46 +00007143 char *name;
7144 int old_errno = errno;
Fred Drake12c6e2d1999-12-14 21:25:03 +00007145
Victor Stinner8c62be82010-05-06 00:08:46 +00007146 errno = 0;
7147 name = getlogin();
7148 if (name == NULL) {
7149 if (errno)
Victor Stinnere039ffe2010-08-15 09:33:08 +00007150 posix_error();
Fred Drake12c6e2d1999-12-14 21:25:03 +00007151 else
Victor Stinnere039ffe2010-08-15 09:33:08 +00007152 PyErr_SetString(PyExc_OSError, "unable to determine login name");
Victor Stinner8c62be82010-05-06 00:08:46 +00007153 }
7154 else
Victor Stinnere039ffe2010-08-15 09:33:08 +00007155 result = PyUnicode_DecodeFSDefault(name);
Victor Stinner8c62be82010-05-06 00:08:46 +00007156 errno = old_errno;
Brian Curtine8e4b3b2010-09-23 20:04:14 +00007157#endif
Fred Drake12c6e2d1999-12-14 21:25:03 +00007158 return result;
7159}
Brian Curtine8e4b3b2010-09-23 20:04:14 +00007160#endif /* HAVE_GETLOGIN */
Fred Drake12c6e2d1999-12-14 21:25:03 +00007161
Larry Hastings2f936352014-08-05 14:04:04 +10007162
Guido van Rossumad0ee831995-03-01 10:34:45 +00007163#ifdef HAVE_GETUID
Larry Hastings2f936352014-08-05 14:04:04 +10007164/*[clinic input]
7165os.getuid
7166
7167Return the current process's user id.
7168[clinic start generated code]*/
7169
Larry Hastings2f936352014-08-05 14:04:04 +10007170static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007171os_getuid_impl(PyObject *module)
7172/*[clinic end generated code: output=415c0b401ebed11a input=b53c8b35f110a516]*/
Guido van Rossum46003ff1992-05-15 11:05:24 +00007173{
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02007174 return _PyLong_FromUid(getuid());
Guido van Rossum46003ff1992-05-15 11:05:24 +00007175}
Larry Hastings2f936352014-08-05 14:04:04 +10007176#endif /* HAVE_GETUID */
Guido van Rossum46003ff1992-05-15 11:05:24 +00007177
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007178
Brian Curtineb24d742010-04-12 17:16:38 +00007179#ifdef MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +10007180#define HAVE_KILL
7181#endif /* MS_WINDOWS */
7182
7183#ifdef HAVE_KILL
7184/*[clinic input]
7185os.kill
7186
7187 pid: pid_t
7188 signal: Py_ssize_t
7189 /
7190
7191Kill a process with a signal.
7192[clinic start generated code]*/
7193
Larry Hastings2f936352014-08-05 14:04:04 +10007194static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007195os_kill_impl(PyObject *module, pid_t pid, Py_ssize_t signal)
7196/*[clinic end generated code: output=8e346a6701c88568 input=61a36b86ca275ab9]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007197#ifndef MS_WINDOWS
7198{
7199 if (kill(pid, (int)signal) == -1)
7200 return posix_error();
7201 Py_RETURN_NONE;
7202}
7203#else /* !MS_WINDOWS */
Brian Curtineb24d742010-04-12 17:16:38 +00007204{
Amaury Forgeot d'Arc0a589c92010-05-15 20:35:12 +00007205 PyObject *result;
Larry Hastings2f936352014-08-05 14:04:04 +10007206 DWORD sig = (DWORD)signal;
7207 DWORD err;
Victor Stinner8c62be82010-05-06 00:08:46 +00007208 HANDLE handle;
Brian Curtineb24d742010-04-12 17:16:38 +00007209
Victor Stinner8c62be82010-05-06 00:08:46 +00007210 /* Console processes which share a common console can be sent CTRL+C or
7211 CTRL+BREAK events, provided they handle said events. */
7212 if (sig == CTRL_C_EVENT || sig == CTRL_BREAK_EVENT) {
Richard Oudkerkac0ad882013-06-05 23:29:30 +01007213 if (GenerateConsoleCtrlEvent(sig, (DWORD)pid) == 0) {
Victor Stinner8c62be82010-05-06 00:08:46 +00007214 err = GetLastError();
7215 PyErr_SetFromWindowsErr(err);
7216 }
7217 else
7218 Py_RETURN_NONE;
7219 }
Brian Curtineb24d742010-04-12 17:16:38 +00007220
Victor Stinner8c62be82010-05-06 00:08:46 +00007221 /* If the signal is outside of what GenerateConsoleCtrlEvent can use,
7222 attempt to open and terminate the process. */
Richard Oudkerkac0ad882013-06-05 23:29:30 +01007223 handle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, (DWORD)pid);
Victor Stinner8c62be82010-05-06 00:08:46 +00007224 if (handle == NULL) {
7225 err = GetLastError();
7226 return PyErr_SetFromWindowsErr(err);
7227 }
Brian Curtineb24d742010-04-12 17:16:38 +00007228
Victor Stinner8c62be82010-05-06 00:08:46 +00007229 if (TerminateProcess(handle, sig) == 0) {
7230 err = GetLastError();
7231 result = PyErr_SetFromWindowsErr(err);
7232 } else {
7233 Py_INCREF(Py_None);
7234 result = Py_None;
7235 }
Brian Curtineb24d742010-04-12 17:16:38 +00007236
Victor Stinner8c62be82010-05-06 00:08:46 +00007237 CloseHandle(handle);
7238 return result;
Brian Curtineb24d742010-04-12 17:16:38 +00007239}
Larry Hastings2f936352014-08-05 14:04:04 +10007240#endif /* !MS_WINDOWS */
7241#endif /* HAVE_KILL */
7242
7243
7244#ifdef HAVE_KILLPG
7245/*[clinic input]
7246os.killpg
7247
7248 pgid: pid_t
7249 signal: int
7250 /
7251
7252Kill a process group with a signal.
7253[clinic start generated code]*/
7254
Larry Hastings2f936352014-08-05 14:04:04 +10007255static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007256os_killpg_impl(PyObject *module, pid_t pgid, int signal)
7257/*[clinic end generated code: output=6dbcd2f1fdf5fdba input=38b5449eb8faec19]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007258{
7259 /* XXX some man pages make the `pgid` parameter an int, others
7260 a pid_t. Since getpgrp() returns a pid_t, we assume killpg should
7261 take the same type. Moreover, pid_t is always at least as wide as
7262 int (else compilation of this module fails), which is safe. */
7263 if (killpg(pgid, signal) == -1)
7264 return posix_error();
7265 Py_RETURN_NONE;
7266}
7267#endif /* HAVE_KILLPG */
7268
Brian Curtineb24d742010-04-12 17:16:38 +00007269
Guido van Rossumc0125471996-06-28 18:55:32 +00007270#ifdef HAVE_PLOCK
Guido van Rossumc0125471996-06-28 18:55:32 +00007271#ifdef HAVE_SYS_LOCK_H
7272#include <sys/lock.h>
7273#endif
7274
Larry Hastings2f936352014-08-05 14:04:04 +10007275/*[clinic input]
7276os.plock
7277 op: int
7278 /
7279
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00007280Lock program segments into memory.");
Larry Hastings2f936352014-08-05 14:04:04 +10007281[clinic start generated code]*/
7282
Larry Hastings2f936352014-08-05 14:04:04 +10007283static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007284os_plock_impl(PyObject *module, int op)
7285/*[clinic end generated code: output=81424167033b168e input=e6e5e348e1525f60]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007286{
Victor Stinner8c62be82010-05-06 00:08:46 +00007287 if (plock(op) == -1)
7288 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10007289 Py_RETURN_NONE;
Guido van Rossumc0125471996-06-28 18:55:32 +00007290}
Larry Hastings2f936352014-08-05 14:04:04 +10007291#endif /* HAVE_PLOCK */
7292
Guido van Rossumc0125471996-06-28 18:55:32 +00007293
Guido van Rossumb6775db1994-08-01 11:34:53 +00007294#ifdef HAVE_SETUID
Larry Hastings2f936352014-08-05 14:04:04 +10007295/*[clinic input]
7296os.setuid
7297
7298 uid: uid_t
7299 /
7300
7301Set the current process's user id.
7302[clinic start generated code]*/
7303
Larry Hastings2f936352014-08-05 14:04:04 +10007304static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007305os_setuid_impl(PyObject *module, uid_t uid)
7306/*[clinic end generated code: output=a0a41fd0d1ec555f input=c921a3285aa22256]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007307{
Victor Stinner8c62be82010-05-06 00:08:46 +00007308 if (setuid(uid) < 0)
7309 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10007310 Py_RETURN_NONE;
Guido van Rossuma3d78fb1993-11-10 09:23:53 +00007311}
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +00007312#endif /* HAVE_SETUID */
Guido van Rossuma3d78fb1993-11-10 09:23:53 +00007313
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007314
Andrew M. Kuchling8d2f2b2d2000-07-13 01:26:58 +00007315#ifdef HAVE_SETEUID
Larry Hastings2f936352014-08-05 14:04:04 +10007316/*[clinic input]
7317os.seteuid
7318
7319 euid: uid_t
7320 /
7321
7322Set the current process's effective user id.
7323[clinic start generated code]*/
7324
Larry Hastings2f936352014-08-05 14:04:04 +10007325static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007326os_seteuid_impl(PyObject *module, uid_t euid)
7327/*[clinic end generated code: output=102e3ad98361519a input=ba93d927e4781aa9]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007328{
7329 if (seteuid(euid) < 0)
Victor Stinner8c62be82010-05-06 00:08:46 +00007330 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10007331 Py_RETURN_NONE;
Andrew M. Kuchling8d2f2b2d2000-07-13 01:26:58 +00007332}
7333#endif /* HAVE_SETEUID */
7334
Larry Hastings2f936352014-08-05 14:04:04 +10007335
Andrew M. Kuchling8d2f2b2d2000-07-13 01:26:58 +00007336#ifdef HAVE_SETEGID
Larry Hastings2f936352014-08-05 14:04:04 +10007337/*[clinic input]
7338os.setegid
7339
7340 egid: gid_t
7341 /
7342
7343Set the current process's effective group id.
7344[clinic start generated code]*/
7345
Larry Hastings2f936352014-08-05 14:04:04 +10007346static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007347os_setegid_impl(PyObject *module, gid_t egid)
7348/*[clinic end generated code: output=4e4b825a6a10258d input=4080526d0ccd6ce3]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007349{
7350 if (setegid(egid) < 0)
Victor Stinner8c62be82010-05-06 00:08:46 +00007351 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10007352 Py_RETURN_NONE;
Andrew M. Kuchling8d2f2b2d2000-07-13 01:26:58 +00007353}
7354#endif /* HAVE_SETEGID */
7355
Larry Hastings2f936352014-08-05 14:04:04 +10007356
Andrew M. Kuchling8d2f2b2d2000-07-13 01:26:58 +00007357#ifdef HAVE_SETREUID
Larry Hastings2f936352014-08-05 14:04:04 +10007358/*[clinic input]
7359os.setreuid
7360
7361 ruid: uid_t
7362 euid: uid_t
7363 /
7364
7365Set the current process's real and effective user ids.
7366[clinic start generated code]*/
7367
Larry Hastings2f936352014-08-05 14:04:04 +10007368static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007369os_setreuid_impl(PyObject *module, uid_t ruid, uid_t euid)
7370/*[clinic end generated code: output=62d991210006530a input=0ca8978de663880c]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007371{
Victor Stinner8c62be82010-05-06 00:08:46 +00007372 if (setreuid(ruid, euid) < 0) {
7373 return posix_error();
7374 } else {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02007375 Py_RETURN_NONE;
Victor Stinner8c62be82010-05-06 00:08:46 +00007376 }
Andrew M. Kuchling8d2f2b2d2000-07-13 01:26:58 +00007377}
7378#endif /* HAVE_SETREUID */
7379
Larry Hastings2f936352014-08-05 14:04:04 +10007380
Andrew M. Kuchling8d2f2b2d2000-07-13 01:26:58 +00007381#ifdef HAVE_SETREGID
Larry Hastings2f936352014-08-05 14:04:04 +10007382/*[clinic input]
7383os.setregid
7384
7385 rgid: gid_t
7386 egid: gid_t
7387 /
7388
7389Set the current process's real and effective group ids.
7390[clinic start generated code]*/
7391
Larry Hastings2f936352014-08-05 14:04:04 +10007392static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007393os_setregid_impl(PyObject *module, gid_t rgid, gid_t egid)
7394/*[clinic end generated code: output=aa803835cf5342f3 input=c59499f72846db78]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007395{
7396 if (setregid(rgid, egid) < 0)
Victor Stinner8c62be82010-05-06 00:08:46 +00007397 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10007398 Py_RETURN_NONE;
Andrew M. Kuchling8d2f2b2d2000-07-13 01:26:58 +00007399}
7400#endif /* HAVE_SETREGID */
7401
Larry Hastings2f936352014-08-05 14:04:04 +10007402
Guido van Rossumb6775db1994-08-01 11:34:53 +00007403#ifdef HAVE_SETGID
Larry Hastings2f936352014-08-05 14:04:04 +10007404/*[clinic input]
7405os.setgid
7406 gid: gid_t
7407 /
7408
7409Set the current process's group id.
7410[clinic start generated code]*/
7411
Larry Hastings2f936352014-08-05 14:04:04 +10007412static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007413os_setgid_impl(PyObject *module, gid_t gid)
7414/*[clinic end generated code: output=bdccd7403f6ad8c3 input=27d30c4059045dc6]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007415{
Victor Stinner8c62be82010-05-06 00:08:46 +00007416 if (setgid(gid) < 0)
7417 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10007418 Py_RETURN_NONE;
Guido van Rossuma3d78fb1993-11-10 09:23:53 +00007419}
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +00007420#endif /* HAVE_SETGID */
Guido van Rossuma3d78fb1993-11-10 09:23:53 +00007421
Larry Hastings2f936352014-08-05 14:04:04 +10007422
Martin v. Löwis61c5edf2001-10-18 04:06:00 +00007423#ifdef HAVE_SETGROUPS
Larry Hastings2f936352014-08-05 14:04:04 +10007424/*[clinic input]
7425os.setgroups
7426
7427 groups: object
7428 /
7429
7430Set the groups of the current process to list.
7431[clinic start generated code]*/
7432
Martin v. Löwis61c5edf2001-10-18 04:06:00 +00007433static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007434os_setgroups(PyObject *module, PyObject *groups)
7435/*[clinic end generated code: output=3fcb32aad58c5ecd input=fa742ca3daf85a7e]*/
Martin v. Löwis61c5edf2001-10-18 04:06:00 +00007436{
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03007437 Py_ssize_t i, len;
Victor Stinner8c62be82010-05-06 00:08:46 +00007438 gid_t grouplist[MAX_GROUPS];
Tim Peters5aa91602002-01-30 05:46:57 +00007439
Victor Stinner8c62be82010-05-06 00:08:46 +00007440 if (!PySequence_Check(groups)) {
7441 PyErr_SetString(PyExc_TypeError, "setgroups argument must be a sequence");
7442 return NULL;
7443 }
7444 len = PySequence_Size(groups);
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03007445 if (len < 0) {
7446 return NULL;
7447 }
Victor Stinner8c62be82010-05-06 00:08:46 +00007448 if (len > MAX_GROUPS) {
7449 PyErr_SetString(PyExc_ValueError, "too many groups");
7450 return NULL;
7451 }
7452 for(i = 0; i < len; i++) {
7453 PyObject *elem;
7454 elem = PySequence_GetItem(groups, i);
7455 if (!elem)
7456 return NULL;
7457 if (!PyLong_Check(elem)) {
7458 PyErr_SetString(PyExc_TypeError,
7459 "groups must be integers");
7460 Py_DECREF(elem);
7461 return NULL;
7462 } else {
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02007463 if (!_Py_Gid_Converter(elem, &grouplist[i])) {
Victor Stinner8c62be82010-05-06 00:08:46 +00007464 Py_DECREF(elem);
7465 return NULL;
7466 }
7467 }
7468 Py_DECREF(elem);
7469 }
Martin v. Löwis61c5edf2001-10-18 04:06:00 +00007470
Victor Stinner8c62be82010-05-06 00:08:46 +00007471 if (setgroups(len, grouplist) < 0)
7472 return posix_error();
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02007473 Py_RETURN_NONE;
Martin v. Löwis61c5edf2001-10-18 04:06:00 +00007474}
7475#endif /* HAVE_SETGROUPS */
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007476
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007477#if defined(HAVE_WAIT3) || defined(HAVE_WAIT4)
7478static PyObject *
Victor Stinner4195b5c2012-02-08 23:03:19 +01007479wait_helper(pid_t pid, int status, struct rusage *ru)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007480{
Victor Stinner8c62be82010-05-06 00:08:46 +00007481 PyObject *result;
7482 static PyObject *struct_rusage;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02007483 _Py_IDENTIFIER(struct_rusage);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007484
Victor Stinner8c62be82010-05-06 00:08:46 +00007485 if (pid == -1)
7486 return posix_error();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007487
Victor Stinner8c62be82010-05-06 00:08:46 +00007488 if (struct_rusage == NULL) {
7489 PyObject *m = PyImport_ImportModuleNoBlock("resource");
7490 if (m == NULL)
7491 return NULL;
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02007492 struct_rusage = _PyObject_GetAttrId(m, &PyId_struct_rusage);
Victor Stinner8c62be82010-05-06 00:08:46 +00007493 Py_DECREF(m);
7494 if (struct_rusage == NULL)
7495 return NULL;
7496 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007497
Victor Stinner8c62be82010-05-06 00:08:46 +00007498 /* XXX(nnorwitz): Copied (w/mods) from resource.c, there should be only one. */
7499 result = PyStructSequence_New((PyTypeObject*) struct_rusage);
7500 if (!result)
7501 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007502
7503#ifndef doubletime
7504#define doubletime(TV) ((double)(TV).tv_sec + (TV).tv_usec * 0.000001)
7505#endif
7506
Victor Stinner8c62be82010-05-06 00:08:46 +00007507 PyStructSequence_SET_ITEM(result, 0,
Victor Stinner4195b5c2012-02-08 23:03:19 +01007508 PyFloat_FromDouble(doubletime(ru->ru_utime)));
Victor Stinner8c62be82010-05-06 00:08:46 +00007509 PyStructSequence_SET_ITEM(result, 1,
Victor Stinner4195b5c2012-02-08 23:03:19 +01007510 PyFloat_FromDouble(doubletime(ru->ru_stime)));
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007511#define SET_INT(result, index, value)\
Victor Stinner8c62be82010-05-06 00:08:46 +00007512 PyStructSequence_SET_ITEM(result, index, PyLong_FromLong(value))
7513 SET_INT(result, 2, ru->ru_maxrss);
7514 SET_INT(result, 3, ru->ru_ixrss);
7515 SET_INT(result, 4, ru->ru_idrss);
7516 SET_INT(result, 5, ru->ru_isrss);
7517 SET_INT(result, 6, ru->ru_minflt);
7518 SET_INT(result, 7, ru->ru_majflt);
7519 SET_INT(result, 8, ru->ru_nswap);
7520 SET_INT(result, 9, ru->ru_inblock);
7521 SET_INT(result, 10, ru->ru_oublock);
7522 SET_INT(result, 11, ru->ru_msgsnd);
7523 SET_INT(result, 12, ru->ru_msgrcv);
7524 SET_INT(result, 13, ru->ru_nsignals);
7525 SET_INT(result, 14, ru->ru_nvcsw);
7526 SET_INT(result, 15, ru->ru_nivcsw);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007527#undef SET_INT
7528
Victor Stinner8c62be82010-05-06 00:08:46 +00007529 if (PyErr_Occurred()) {
7530 Py_DECREF(result);
7531 return NULL;
7532 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007533
Victor Stinner8c62be82010-05-06 00:08:46 +00007534 return Py_BuildValue("NiN", PyLong_FromPid(pid), status, result);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007535}
7536#endif /* HAVE_WAIT3 || HAVE_WAIT4 */
7537
Larry Hastings2f936352014-08-05 14:04:04 +10007538
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007539#ifdef HAVE_WAIT3
Larry Hastings2f936352014-08-05 14:04:04 +10007540/*[clinic input]
7541os.wait3
7542
7543 options: int
7544Wait for completion of a child process.
7545
7546Returns a tuple of information about the child process:
7547 (pid, status, rusage)
7548[clinic start generated code]*/
7549
Larry Hastings2f936352014-08-05 14:04:04 +10007550static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007551os_wait3_impl(PyObject *module, int options)
7552/*[clinic end generated code: output=92c3224e6f28217a input=8ac4c56956b61710]*/
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007553{
Victor Stinner8c62be82010-05-06 00:08:46 +00007554 pid_t pid;
Victor Stinner8c62be82010-05-06 00:08:46 +00007555 struct rusage ru;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007556 int async_err = 0;
Victor Stinner8c62be82010-05-06 00:08:46 +00007557 WAIT_TYPE status;
7558 WAIT_STATUS_INT(status) = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007559
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007560 do {
7561 Py_BEGIN_ALLOW_THREADS
7562 pid = wait3(&status, options, &ru);
7563 Py_END_ALLOW_THREADS
7564 } while (pid < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
7565 if (pid < 0)
7566 return (!async_err) ? posix_error() : NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007567
Victor Stinner4195b5c2012-02-08 23:03:19 +01007568 return wait_helper(pid, WAIT_STATUS_INT(status), &ru);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007569}
7570#endif /* HAVE_WAIT3 */
7571
Larry Hastings2f936352014-08-05 14:04:04 +10007572
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007573#ifdef HAVE_WAIT4
Larry Hastings2f936352014-08-05 14:04:04 +10007574/*[clinic input]
7575
7576os.wait4
7577
7578 pid: pid_t
7579 options: int
7580
7581Wait for completion of a specific child process.
7582
7583Returns a tuple of information about the child process:
7584 (pid, status, rusage)
7585[clinic start generated code]*/
7586
Larry Hastings2f936352014-08-05 14:04:04 +10007587static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007588os_wait4_impl(PyObject *module, pid_t pid, int options)
7589/*[clinic end generated code: output=66195aa507b35f70 input=d11deed0750600ba]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007590{
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007591 pid_t res;
Victor Stinner8c62be82010-05-06 00:08:46 +00007592 struct rusage ru;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007593 int async_err = 0;
Victor Stinner8c62be82010-05-06 00:08:46 +00007594 WAIT_TYPE status;
7595 WAIT_STATUS_INT(status) = 0;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007596
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007597 do {
7598 Py_BEGIN_ALLOW_THREADS
7599 res = wait4(pid, &status, options, &ru);
7600 Py_END_ALLOW_THREADS
7601 } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
7602 if (res < 0)
7603 return (!async_err) ? posix_error() : NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007604
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007605 return wait_helper(res, WAIT_STATUS_INT(status), &ru);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007606}
7607#endif /* HAVE_WAIT4 */
7608
Larry Hastings2f936352014-08-05 14:04:04 +10007609
Ross Lagerwall7807c352011-03-17 20:20:30 +02007610#if defined(HAVE_WAITID) && !defined(__APPLE__)
Larry Hastings2f936352014-08-05 14:04:04 +10007611/*[clinic input]
7612os.waitid
7613
7614 idtype: idtype_t
7615 Must be one of be P_PID, P_PGID or P_ALL.
7616 id: id_t
7617 The id to wait on.
7618 options: int
7619 Constructed from the ORing of one or more of WEXITED, WSTOPPED
7620 or WCONTINUED and additionally may be ORed with WNOHANG or WNOWAIT.
7621 /
7622
7623Returns the result of waiting for a process or processes.
7624
7625Returns either waitid_result or None if WNOHANG is specified and there are
7626no children in a waitable state.
7627[clinic start generated code]*/
7628
Larry Hastings2f936352014-08-05 14:04:04 +10007629static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007630os_waitid_impl(PyObject *module, idtype_t idtype, id_t id, int options)
7631/*[clinic end generated code: output=5d2e1c0bde61f4d8 input=d8e7f76e052b7920]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007632{
7633 PyObject *result;
7634 int res;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007635 int async_err = 0;
Ross Lagerwall7807c352011-03-17 20:20:30 +02007636 siginfo_t si;
7637 si.si_pid = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10007638
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007639 do {
7640 Py_BEGIN_ALLOW_THREADS
7641 res = waitid(idtype, id, &si, options);
7642 Py_END_ALLOW_THREADS
7643 } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
7644 if (res < 0)
7645 return (!async_err) ? posix_error() : NULL;
Ross Lagerwall7807c352011-03-17 20:20:30 +02007646
7647 if (si.si_pid == 0)
7648 Py_RETURN_NONE;
7649
Eddie Elizondo474eedf2018-11-13 04:09:31 -08007650 result = PyStructSequence_New(WaitidResultType);
Ross Lagerwall7807c352011-03-17 20:20:30 +02007651 if (!result)
7652 return NULL;
7653
7654 PyStructSequence_SET_ITEM(result, 0, PyLong_FromPid(si.si_pid));
Serhiy Storchaka7cf55992013-02-10 21:56:49 +02007655 PyStructSequence_SET_ITEM(result, 1, _PyLong_FromUid(si.si_uid));
Ross Lagerwall7807c352011-03-17 20:20:30 +02007656 PyStructSequence_SET_ITEM(result, 2, PyLong_FromLong((long)(si.si_signo)));
7657 PyStructSequence_SET_ITEM(result, 3, PyLong_FromLong((long)(si.si_status)));
7658 PyStructSequence_SET_ITEM(result, 4, PyLong_FromLong((long)(si.si_code)));
7659 if (PyErr_Occurred()) {
7660 Py_DECREF(result);
7661 return NULL;
7662 }
7663
7664 return result;
7665}
Larry Hastings2f936352014-08-05 14:04:04 +10007666#endif /* defined(HAVE_WAITID) && !defined(__APPLE__) */
Ross Lagerwall7807c352011-03-17 20:20:30 +02007667
Larry Hastings2f936352014-08-05 14:04:04 +10007668
7669#if defined(HAVE_WAITPID)
7670/*[clinic input]
7671os.waitpid
7672 pid: pid_t
7673 options: int
7674 /
7675
7676Wait for completion of a given child process.
7677
7678Returns a tuple of information regarding the child process:
7679 (pid, status)
7680
7681The options argument is ignored on Windows.
7682[clinic start generated code]*/
7683
Larry Hastings2f936352014-08-05 14:04:04 +10007684static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007685os_waitpid_impl(PyObject *module, pid_t pid, int options)
7686/*[clinic end generated code: output=5c37c06887a20270 input=0bf1666b8758fda3]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007687{
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007688 pid_t res;
7689 int async_err = 0;
Victor Stinner8c62be82010-05-06 00:08:46 +00007690 WAIT_TYPE status;
7691 WAIT_STATUS_INT(status) = 0;
Guido van Rossum54ecc3d1999-01-27 17:53:11 +00007692
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007693 do {
7694 Py_BEGIN_ALLOW_THREADS
7695 res = waitpid(pid, &status, options);
7696 Py_END_ALLOW_THREADS
7697 } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
7698 if (res < 0)
7699 return (!async_err) ? posix_error() : NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007700
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007701 return Py_BuildValue("Ni", PyLong_FromPid(res), WAIT_STATUS_INT(status));
Guido van Rossum21803b81992-08-09 12:55:27 +00007702}
Tim Petersab034fa2002-02-01 11:27:43 +00007703#elif defined(HAVE_CWAIT)
Tim Petersab034fa2002-02-01 11:27:43 +00007704/* MS C has a variant of waitpid() that's usable for most purposes. */
Larry Hastings2f936352014-08-05 14:04:04 +10007705/*[clinic input]
7706os.waitpid
Benjamin Petersonca470632016-09-06 13:47:26 -07007707 pid: intptr_t
Larry Hastings2f936352014-08-05 14:04:04 +10007708 options: int
7709 /
7710
7711Wait for completion of a given process.
7712
7713Returns a tuple of information regarding the process:
7714 (pid, status << 8)
7715
7716The options argument is ignored on Windows.
7717[clinic start generated code]*/
7718
Larry Hastings2f936352014-08-05 14:04:04 +10007719static PyObject *
Benjamin Petersonca470632016-09-06 13:47:26 -07007720os_waitpid_impl(PyObject *module, intptr_t pid, int options)
Victor Stinner581139c2016-09-06 15:54:20 -07007721/*[clinic end generated code: output=be836b221271d538 input=40f2440c515410f8]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007722{
7723 int status;
Benjamin Petersonca470632016-09-06 13:47:26 -07007724 intptr_t res;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007725 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10007726
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007727 do {
7728 Py_BEGIN_ALLOW_THREADS
Steve Dower11f43262016-11-19 18:33:39 -08007729 _Py_BEGIN_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007730 res = _cwait(&status, pid, options);
Steve Dower11f43262016-11-19 18:33:39 -08007731 _Py_END_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007732 Py_END_ALLOW_THREADS
7733 } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Victor Stinnerd3ffd322015-09-15 10:11:03 +02007734 if (res < 0)
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007735 return (!async_err) ? posix_error() : NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007736
Victor Stinner8c62be82010-05-06 00:08:46 +00007737 /* shift the status left a byte so this is more like the POSIX waitpid */
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007738 return Py_BuildValue(_Py_PARSE_INTPTR "i", res, status << 8);
Tim Petersab034fa2002-02-01 11:27:43 +00007739}
Larry Hastings2f936352014-08-05 14:04:04 +10007740#endif
7741
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007742
Guido van Rossumad0ee831995-03-01 10:34:45 +00007743#ifdef HAVE_WAIT
Larry Hastings2f936352014-08-05 14:04:04 +10007744/*[clinic input]
7745os.wait
7746
7747Wait for completion of a child process.
7748
7749Returns a tuple of information about the child process:
7750 (pid, status)
7751[clinic start generated code]*/
7752
Larry Hastings2f936352014-08-05 14:04:04 +10007753static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007754os_wait_impl(PyObject *module)
7755/*[clinic end generated code: output=6bc419ac32fb364b input=03b0182d4a4700ce]*/
Guido van Rossum21803b81992-08-09 12:55:27 +00007756{
Victor Stinner8c62be82010-05-06 00:08:46 +00007757 pid_t pid;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007758 int async_err = 0;
Victor Stinner8c62be82010-05-06 00:08:46 +00007759 WAIT_TYPE status;
7760 WAIT_STATUS_INT(status) = 0;
Neal Norwitze241ce82003-02-17 18:17:05 +00007761
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00007762 do {
7763 Py_BEGIN_ALLOW_THREADS
7764 pid = wait(&status);
7765 Py_END_ALLOW_THREADS
7766 } while (pid < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
7767 if (pid < 0)
7768 return (!async_err) ? posix_error() : NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007769
Victor Stinner8c62be82010-05-06 00:08:46 +00007770 return Py_BuildValue("Ni", PyLong_FromPid(pid), WAIT_STATUS_INT(status));
Guido van Rossum85e3b011991-06-03 12:42:10 +00007771}
Larry Hastings2f936352014-08-05 14:04:04 +10007772#endif /* HAVE_WAIT */
Guido van Rossum85e3b011991-06-03 12:42:10 +00007773
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007774
Larry Hastings9cf065c2012-06-22 16:30:09 -07007775#if defined(HAVE_READLINK) || defined(MS_WINDOWS)
Serhiy Storchaka12a69db2018-09-17 15:38:27 +03007776/*[clinic input]
7777os.readlink
7778
7779 path: path_t
7780 *
7781 dir_fd: dir_fd(requires='readlinkat') = None
7782
7783Return a string representing the path to which the symbolic link points.
7784
7785If dir_fd is not None, it should be a file descriptor open to a directory,
7786and path should be relative; path will then be relative to that directory.
7787
7788dir_fd may not be implemented on your platform. If it is unavailable,
7789using it will raise a NotImplementedError.
7790[clinic start generated code]*/
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007791
Barry Warsaw53699e91996-12-10 23:23:01 +00007792static PyObject *
Serhiy Storchaka12a69db2018-09-17 15:38:27 +03007793os_readlink_impl(PyObject *module, path_t *path, int dir_fd)
7794/*[clinic end generated code: output=d21b732a2e814030 input=113c87e0db1ecaf2]*/
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00007795{
Berker Peksage0b5b202018-08-15 13:03:41 +03007796#if defined(HAVE_READLINK)
Christian Heimes3cb091e2016-09-23 20:24:28 +02007797 char buffer[MAXPATHLEN+1];
Larry Hastings9cf065c2012-06-22 16:30:09 -07007798 ssize_t length;
Serhiy Storchaka12a69db2018-09-17 15:38:27 +03007799
7800 Py_BEGIN_ALLOW_THREADS
7801#ifdef HAVE_READLINKAT
7802 if (dir_fd != DEFAULT_DIR_FD)
7803 length = readlinkat(dir_fd, path->narrow, buffer, MAXPATHLEN);
7804 else
7805#endif
7806 length = readlink(path->narrow, buffer, MAXPATHLEN);
7807 Py_END_ALLOW_THREADS
7808
7809 if (length < 0) {
7810 return path_error(path);
7811 }
7812 buffer[length] = '\0';
7813
7814 if (PyUnicode_Check(path->object))
7815 return PyUnicode_DecodeFSDefaultAndSize(buffer, length);
7816 else
7817 return PyBytes_FromStringAndSize(buffer, length);
Berker Peksage0b5b202018-08-15 13:03:41 +03007818#elif defined(MS_WINDOWS)
7819 DWORD n_bytes_returned;
Steve Dower9eb3d542019-08-21 15:52:42 -07007820 DWORD io_result = 0;
Berker Peksage0b5b202018-08-15 13:03:41 +03007821 HANDLE reparse_point_handle;
Berker Peksage0b5b202018-08-15 13:03:41 +03007822 char target_buffer[_Py_MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
7823 _Py_REPARSE_DATA_BUFFER *rdb = (_Py_REPARSE_DATA_BUFFER *)target_buffer;
Miss Islington (bot)54dac6c2019-09-03 13:13:41 -07007824 PyObject *result = NULL;
Thomas Wouters89f507f2006-12-13 04:49:30 +00007825
Larry Hastings2f936352014-08-05 14:04:04 +10007826 /* First get a handle to the reparse point */
7827 Py_BEGIN_ALLOW_THREADS
7828 reparse_point_handle = CreateFileW(
Serhiy Storchaka12a69db2018-09-17 15:38:27 +03007829 path->wide,
Larry Hastings2f936352014-08-05 14:04:04 +10007830 0,
7831 0,
7832 0,
7833 OPEN_EXISTING,
7834 FILE_FLAG_OPEN_REPARSE_POINT|FILE_FLAG_BACKUP_SEMANTICS,
7835 0);
Steve Dower9eb3d542019-08-21 15:52:42 -07007836 if (reparse_point_handle != INVALID_HANDLE_VALUE) {
7837 /* New call DeviceIoControl to read the reparse point */
7838 io_result = DeviceIoControl(
7839 reparse_point_handle,
7840 FSCTL_GET_REPARSE_POINT,
7841 0, 0, /* in buffer */
7842 target_buffer, sizeof(target_buffer),
7843 &n_bytes_returned,
7844 0 /* we're not using OVERLAPPED_IO */
7845 );
7846 CloseHandle(reparse_point_handle);
Berker Peksage0b5b202018-08-15 13:03:41 +03007847 }
Larry Hastings2f936352014-08-05 14:04:04 +10007848 Py_END_ALLOW_THREADS
7849
Berker Peksage0b5b202018-08-15 13:03:41 +03007850 if (io_result == 0) {
Serhiy Storchaka12a69db2018-09-17 15:38:27 +03007851 return path_error(path);
Berker Peksage0b5b202018-08-15 13:03:41 +03007852 }
Larry Hastings2f936352014-08-05 14:04:04 +10007853
Steve Dower9eb3d542019-08-21 15:52:42 -07007854 wchar_t *name = NULL;
7855 Py_ssize_t nameLen = 0;
7856 if (rdb->ReparseTag == IO_REPARSE_TAG_SYMLINK)
Larry Hastings2f936352014-08-05 14:04:04 +10007857 {
Steve Dower9eb3d542019-08-21 15:52:42 -07007858 name = (wchar_t *)((char*)rdb->SymbolicLinkReparseBuffer.PathBuffer +
7859 rdb->SymbolicLinkReparseBuffer.SubstituteNameOffset);
7860 nameLen = rdb->SymbolicLinkReparseBuffer.SubstituteNameLength / sizeof(wchar_t);
Larry Hastings2f936352014-08-05 14:04:04 +10007861 }
Steve Dower9eb3d542019-08-21 15:52:42 -07007862 else if (rdb->ReparseTag == IO_REPARSE_TAG_MOUNT_POINT)
7863 {
7864 name = (wchar_t *)((char*)rdb->MountPointReparseBuffer.PathBuffer +
7865 rdb->MountPointReparseBuffer.SubstituteNameOffset);
7866 nameLen = rdb->MountPointReparseBuffer.SubstituteNameLength / sizeof(wchar_t);
7867 }
7868 else
7869 {
7870 PyErr_SetString(PyExc_ValueError, "not a symbolic link");
7871 }
7872 if (name) {
7873 if (nameLen > 4 && wcsncmp(name, L"\\??\\", 4) == 0) {
7874 /* Our buffer is mutable, so this is okay */
7875 name[1] = L'\\';
7876 }
7877 result = PyUnicode_FromWideChar(name, nameLen);
Miss Islington (bot)54dac6c2019-09-03 13:13:41 -07007878 if (result && path->narrow) {
Steve Dower9eb3d542019-08-21 15:52:42 -07007879 Py_SETREF(result, PyUnicode_EncodeFSDefault(result));
7880 }
Berker Peksage0b5b202018-08-15 13:03:41 +03007881 }
Serhiy Storchaka12a69db2018-09-17 15:38:27 +03007882 return result;
Berker Peksage0b5b202018-08-15 13:03:41 +03007883#endif
Larry Hastings2f936352014-08-05 14:04:04 +10007884}
Berker Peksage0b5b202018-08-15 13:03:41 +03007885#endif /* defined(HAVE_READLINK) || defined(MS_WINDOWS) */
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007886
Larry Hastings9cf065c2012-06-22 16:30:09 -07007887#ifdef HAVE_SYMLINK
Larry Hastings9cf065c2012-06-22 16:30:09 -07007888
7889#if defined(MS_WINDOWS)
7890
Steve Dower6921e732018-03-05 14:26:08 -08007891/* Remove the last portion of the path - return 0 on success */
7892static int
Victor Stinner31b3b922013-06-05 01:49:17 +02007893_dirnameW(WCHAR *path)
7894{
Jason R. Coombs3a092862013-05-27 23:21:28 -04007895 WCHAR *ptr;
Steve Dower6921e732018-03-05 14:26:08 -08007896 size_t length = wcsnlen_s(path, MAX_PATH);
7897 if (length == MAX_PATH) {
7898 return -1;
7899 }
Jason R. Coombs3a092862013-05-27 23:21:28 -04007900
7901 /* walk the path from the end until a backslash is encountered */
Steve Dower6921e732018-03-05 14:26:08 -08007902 for(ptr = path + length; ptr != path; ptr--) {
7903 if (*ptr == L'\\' || *ptr == L'/') {
Jason R. Coombs3a092862013-05-27 23:21:28 -04007904 break;
Steve Dower6921e732018-03-05 14:26:08 -08007905 }
Jason R. Coombs3a092862013-05-27 23:21:28 -04007906 }
7907 *ptr = 0;
Steve Dower6921e732018-03-05 14:26:08 -08007908 return 0;
Jason R. Coombs3a092862013-05-27 23:21:28 -04007909}
7910
Victor Stinner31b3b922013-06-05 01:49:17 +02007911/* Is this path absolute? */
7912static int
7913_is_absW(const WCHAR *path)
7914{
Steve Dower6921e732018-03-05 14:26:08 -08007915 return path[0] == L'\\' || path[0] == L'/' ||
7916 (path[0] && path[1] == L':');
Jason R. Coombs3a092862013-05-27 23:21:28 -04007917}
7918
Steve Dower6921e732018-03-05 14:26:08 -08007919/* join root and rest with a backslash - return 0 on success */
7920static int
Victor Stinner31b3b922013-06-05 01:49:17 +02007921_joinW(WCHAR *dest_path, const WCHAR *root, const WCHAR *rest)
7922{
Victor Stinner31b3b922013-06-05 01:49:17 +02007923 if (_is_absW(rest)) {
Steve Dower6921e732018-03-05 14:26:08 -08007924 return wcscpy_s(dest_path, MAX_PATH, rest);
Jason R. Coombs3a092862013-05-27 23:21:28 -04007925 }
7926
Steve Dower6921e732018-03-05 14:26:08 -08007927 if (wcscpy_s(dest_path, MAX_PATH, root)) {
7928 return -1;
Jason R. Coombs3a092862013-05-27 23:21:28 -04007929 }
Steve Dower6921e732018-03-05 14:26:08 -08007930
7931 if (dest_path[0] && wcscat_s(dest_path, MAX_PATH, L"\\")) {
7932 return -1;
7933 }
7934
7935 return wcscat_s(dest_path, MAX_PATH, rest);
Jason R. Coombs3a092862013-05-27 23:21:28 -04007936}
7937
Victor Stinner31b3b922013-06-05 01:49:17 +02007938/* Return True if the path at src relative to dest is a directory */
7939static int
Serhiy Storchakadeab18d2016-05-07 16:45:18 +03007940_check_dirW(LPCWSTR src, LPCWSTR dest)
Jason R. Coombs3a092862013-05-27 23:21:28 -04007941{
Jason R. Coombs3a092862013-05-27 23:21:28 -04007942 WIN32_FILE_ATTRIBUTE_DATA src_info;
7943 WCHAR dest_parent[MAX_PATH];
7944 WCHAR src_resolved[MAX_PATH] = L"";
7945
7946 /* dest_parent = os.path.dirname(dest) */
Steve Dower6921e732018-03-05 14:26:08 -08007947 if (wcscpy_s(dest_parent, MAX_PATH, dest) ||
7948 _dirnameW(dest_parent)) {
7949 return 0;
7950 }
Jason R. Coombs3a092862013-05-27 23:21:28 -04007951 /* src_resolved = os.path.join(dest_parent, src) */
Steve Dower6921e732018-03-05 14:26:08 -08007952 if (_joinW(src_resolved, dest_parent, src)) {
7953 return 0;
7954 }
Jason R. Coombs3a092862013-05-27 23:21:28 -04007955 return (
7956 GetFileAttributesExW(src_resolved, GetFileExInfoStandard, &src_info)
7957 && src_info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY
7958 );
7959}
Larry Hastings9cf065c2012-06-22 16:30:09 -07007960#endif
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00007961
Larry Hastings2f936352014-08-05 14:04:04 +10007962
7963/*[clinic input]
7964os.symlink
7965 src: path_t
7966 dst: path_t
7967 target_is_directory: bool = False
7968 *
7969 dir_fd: dir_fd(requires='symlinkat')=None
7970
7971# "symlink(src, dst, target_is_directory=False, *, dir_fd=None)\n\n\
7972
7973Create a symbolic link pointing to src named dst.
7974
7975target_is_directory is required on Windows if the target is to be
7976 interpreted as a directory. (On Windows, symlink requires
7977 Windows 6.0 or greater, and raises a NotImplementedError otherwise.)
7978 target_is_directory is ignored on non-Windows platforms.
7979
7980If dir_fd is not None, it should be a file descriptor open to a directory,
7981 and path should be relative; path will then be relative to that directory.
7982dir_fd may not be implemented on your platform.
7983 If it is unavailable, using it will raise a NotImplementedError.
7984
7985[clinic start generated code]*/
7986
Larry Hastings2f936352014-08-05 14:04:04 +10007987static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007988os_symlink_impl(PyObject *module, path_t *src, path_t *dst,
Larry Hastings89964c42015-04-14 18:07:59 -04007989 int target_is_directory, int dir_fd)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03007990/*[clinic end generated code: output=08ca9f3f3cf960f6 input=e820ec4472547bc3]*/
Larry Hastings2f936352014-08-05 14:04:04 +10007991{
Larry Hastings9cf065c2012-06-22 16:30:09 -07007992#ifdef MS_WINDOWS
7993 DWORD result;
Vidar Tonaas Fauske0e107662019-04-09 20:19:46 +02007994 DWORD flags = 0;
7995
7996 /* Assumed true, set to false if detected to not be available. */
7997 static int windows_has_symlink_unprivileged_flag = TRUE;
Larry Hastings9cf065c2012-06-22 16:30:09 -07007998#else
7999 int result;
8000#endif
8001
Larry Hastings9cf065c2012-06-22 16:30:09 -07008002#ifdef MS_WINDOWS
Larry Hastings9cf065c2012-06-22 16:30:09 -07008003
Vidar Tonaas Fauske0e107662019-04-09 20:19:46 +02008004 if (windows_has_symlink_unprivileged_flag) {
8005 /* Allow non-admin symlinks if system allows it. */
8006 flags |= SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE;
8007 }
Jason R. Coombs3a092862013-05-27 23:21:28 -04008008
Larry Hastings9cf065c2012-06-22 16:30:09 -07008009 Py_BEGIN_ALLOW_THREADS
Steve Dower6921e732018-03-05 14:26:08 -08008010 _Py_BEGIN_SUPPRESS_IPH
Vidar Tonaas Fauske0e107662019-04-09 20:19:46 +02008011 /* if src is a directory, ensure flags==1 (target_is_directory bit) */
8012 if (target_is_directory || _check_dirW(src->wide, dst->wide)) {
8013 flags |= SYMBOLIC_LINK_FLAG_DIRECTORY;
8014 }
8015
8016 result = CreateSymbolicLinkW(dst->wide, src->wide, flags);
Steve Dower6921e732018-03-05 14:26:08 -08008017 _Py_END_SUPPRESS_IPH
Larry Hastings9cf065c2012-06-22 16:30:09 -07008018 Py_END_ALLOW_THREADS
8019
Vidar Tonaas Fauske0e107662019-04-09 20:19:46 +02008020 if (windows_has_symlink_unprivileged_flag && !result &&
8021 ERROR_INVALID_PARAMETER == GetLastError()) {
8022
8023 Py_BEGIN_ALLOW_THREADS
8024 _Py_BEGIN_SUPPRESS_IPH
8025 /* This error might be caused by
8026 SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE not being supported.
8027 Try again, and update windows_has_symlink_unprivileged_flag if we
8028 are successful this time.
8029
8030 NOTE: There is a risk of a race condition here if there are other
8031 conditions than the flag causing ERROR_INVALID_PARAMETER, and
8032 another process (or thread) changes that condition in between our
8033 calls to CreateSymbolicLink.
8034 */
8035 flags &= ~(SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE);
8036 result = CreateSymbolicLinkW(dst->wide, src->wide, flags);
8037 _Py_END_SUPPRESS_IPH
8038 Py_END_ALLOW_THREADS
8039
8040 if (result || ERROR_INVALID_PARAMETER != GetLastError()) {
8041 windows_has_symlink_unprivileged_flag = FALSE;
8042 }
8043 }
8044
Larry Hastings2f936352014-08-05 14:04:04 +10008045 if (!result)
8046 return path_error2(src, dst);
Larry Hastings9cf065c2012-06-22 16:30:09 -07008047
8048#else
8049
Steve Dower6921e732018-03-05 14:26:08 -08008050 if ((src->narrow && dst->wide) || (src->wide && dst->narrow)) {
8051 PyErr_SetString(PyExc_ValueError,
8052 "symlink: src and dst must be the same type");
8053 return NULL;
8054 }
8055
Larry Hastings9cf065c2012-06-22 16:30:09 -07008056 Py_BEGIN_ALLOW_THREADS
8057#if HAVE_SYMLINKAT
8058 if (dir_fd != DEFAULT_DIR_FD)
Larry Hastings2f936352014-08-05 14:04:04 +10008059 result = symlinkat(src->narrow, dir_fd, dst->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07008060 else
8061#endif
Larry Hastings2f936352014-08-05 14:04:04 +10008062 result = symlink(src->narrow, dst->narrow);
Larry Hastings9cf065c2012-06-22 16:30:09 -07008063 Py_END_ALLOW_THREADS
8064
Larry Hastings2f936352014-08-05 14:04:04 +10008065 if (result)
8066 return path_error2(src, dst);
Larry Hastings9cf065c2012-06-22 16:30:09 -07008067#endif
8068
Larry Hastings2f936352014-08-05 14:04:04 +10008069 Py_RETURN_NONE;
Guido van Rossumbfaf3d61997-12-29 20:02:27 +00008070}
8071#endif /* HAVE_SYMLINK */
8072
Larry Hastings9cf065c2012-06-22 16:30:09 -07008073
Brian Curtind40e6f72010-07-08 21:39:08 +00008074
Guido van Rossumbfaf3d61997-12-29 20:02:27 +00008075
Larry Hastings605a62d2012-06-24 04:33:36 -07008076static PyStructSequence_Field times_result_fields[] = {
8077 {"user", "user time"},
8078 {"system", "system time"},
8079 {"children_user", "user time of children"},
8080 {"children_system", "system time of children"},
8081 {"elapsed", "elapsed time since an arbitrary point in the past"},
8082 {NULL}
8083};
8084
8085PyDoc_STRVAR(times_result__doc__,
8086"times_result: Result from os.times().\n\n\
8087This object may be accessed either as a tuple of\n\
8088 (user, system, children_user, children_system, elapsed),\n\
8089or via the attributes user, system, children_user, children_system,\n\
8090and elapsed.\n\
8091\n\
8092See os.times for more information.");
8093
8094static PyStructSequence_Desc times_result_desc = {
8095 "times_result", /* name */
8096 times_result__doc__, /* doc */
8097 times_result_fields,
8098 5
8099};
8100
Eddie Elizondo474eedf2018-11-13 04:09:31 -08008101static PyTypeObject* TimesResultType;
Larry Hastings605a62d2012-06-24 04:33:36 -07008102
Antoine Pitrouf3923e92012-07-24 21:23:53 +02008103#ifdef MS_WINDOWS
8104#define HAVE_TIMES /* mandatory, for the method table */
8105#endif
Larry Hastings605a62d2012-06-24 04:33:36 -07008106
Antoine Pitrouf3923e92012-07-24 21:23:53 +02008107#ifdef HAVE_TIMES
Larry Hastings605a62d2012-06-24 04:33:36 -07008108
8109static PyObject *
8110build_times_result(double user, double system,
8111 double children_user, double children_system,
8112 double elapsed)
8113{
Eddie Elizondo474eedf2018-11-13 04:09:31 -08008114 PyObject *value = PyStructSequence_New(TimesResultType);
Larry Hastings605a62d2012-06-24 04:33:36 -07008115 if (value == NULL)
8116 return NULL;
8117
8118#define SET(i, field) \
8119 { \
8120 PyObject *o = PyFloat_FromDouble(field); \
8121 if (!o) { \
8122 Py_DECREF(value); \
8123 return NULL; \
8124 } \
8125 PyStructSequence_SET_ITEM(value, i, o); \
8126 } \
8127
8128 SET(0, user);
8129 SET(1, system);
8130 SET(2, children_user);
8131 SET(3, children_system);
8132 SET(4, elapsed);
8133
8134#undef SET
8135
8136 return value;
8137}
8138
Larry Hastings605a62d2012-06-24 04:33:36 -07008139
Larry Hastings2f936352014-08-05 14:04:04 +10008140#ifndef MS_WINDOWS
8141#define NEED_TICKS_PER_SECOND
8142static long ticks_per_second = -1;
8143#endif /* MS_WINDOWS */
8144
8145/*[clinic input]
8146os.times
8147
8148Return a collection containing process timing information.
8149
8150The object returned behaves like a named tuple with these fields:
8151 (utime, stime, cutime, cstime, elapsed_time)
8152All fields are floating point numbers.
8153[clinic start generated code]*/
8154
Larry Hastings2f936352014-08-05 14:04:04 +10008155static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008156os_times_impl(PyObject *module)
8157/*[clinic end generated code: output=35f640503557d32a input=2bf9df3d6ab2e48b]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008158#ifdef MS_WINDOWS
Guido van Rossum14ed0b21994-09-29 09:50:09 +00008159{
Victor Stinner8c62be82010-05-06 00:08:46 +00008160 FILETIME create, exit, kernel, user;
8161 HANDLE hProc;
8162 hProc = GetCurrentProcess();
8163 GetProcessTimes(hProc, &create, &exit, &kernel, &user);
8164 /* The fields of a FILETIME structure are the hi and lo part
8165 of a 64-bit value expressed in 100 nanosecond units.
8166 1e7 is one second in such units; 1e-7 the inverse.
8167 429.4967296 is 2**32 / 1e7 or 2**32 * 1e-7.
8168 */
Larry Hastings605a62d2012-06-24 04:33:36 -07008169 return build_times_result(
Victor Stinner8c62be82010-05-06 00:08:46 +00008170 (double)(user.dwHighDateTime*429.4967296 +
8171 user.dwLowDateTime*1e-7),
8172 (double)(kernel.dwHighDateTime*429.4967296 +
8173 kernel.dwLowDateTime*1e-7),
8174 (double)0,
8175 (double)0,
8176 (double)0);
Guido van Rossum14ed0b21994-09-29 09:50:09 +00008177}
Larry Hastings2f936352014-08-05 14:04:04 +10008178#else /* MS_WINDOWS */
Antoine Pitrouf3923e92012-07-24 21:23:53 +02008179{
Larry Hastings2f936352014-08-05 14:04:04 +10008180
8181
Antoine Pitrouf3923e92012-07-24 21:23:53 +02008182 struct tms t;
8183 clock_t c;
8184 errno = 0;
8185 c = times(&t);
8186 if (c == (clock_t) -1)
8187 return posix_error();
8188 return build_times_result(
8189 (double)t.tms_utime / ticks_per_second,
8190 (double)t.tms_stime / ticks_per_second,
8191 (double)t.tms_cutime / ticks_per_second,
8192 (double)t.tms_cstime / ticks_per_second,
8193 (double)c / ticks_per_second);
8194}
Larry Hastings2f936352014-08-05 14:04:04 +10008195#endif /* MS_WINDOWS */
Antoine Pitrouf3923e92012-07-24 21:23:53 +02008196#endif /* HAVE_TIMES */
8197
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008198
Martin v. Löwis49ee14d2003-11-10 06:35:36 +00008199#ifdef HAVE_GETSID
Larry Hastings2f936352014-08-05 14:04:04 +10008200/*[clinic input]
8201os.getsid
8202
8203 pid: pid_t
8204 /
8205
8206Call the system call getsid(pid) and return the result.
8207[clinic start generated code]*/
8208
Larry Hastings2f936352014-08-05 14:04:04 +10008209static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008210os_getsid_impl(PyObject *module, pid_t pid)
8211/*[clinic end generated code: output=112deae56b306460 input=eeb2b923a30ce04e]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008212{
Victor Stinner8c62be82010-05-06 00:08:46 +00008213 int sid;
Victor Stinner8c62be82010-05-06 00:08:46 +00008214 sid = getsid(pid);
8215 if (sid < 0)
8216 return posix_error();
8217 return PyLong_FromLong((long)sid);
Martin v. Löwis49ee14d2003-11-10 06:35:36 +00008218}
8219#endif /* HAVE_GETSID */
8220
8221
Guido van Rossumb6775db1994-08-01 11:34:53 +00008222#ifdef HAVE_SETSID
Larry Hastings2f936352014-08-05 14:04:04 +10008223/*[clinic input]
8224os.setsid
8225
8226Call the system call setsid().
8227[clinic start generated code]*/
8228
Larry Hastings2f936352014-08-05 14:04:04 +10008229static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008230os_setsid_impl(PyObject *module)
8231/*[clinic end generated code: output=e2ddedd517086d77 input=5fff45858e2f0776]*/
Guido van Rossumc2670a01992-09-13 20:07:29 +00008232{
Victor Stinner8c62be82010-05-06 00:08:46 +00008233 if (setsid() < 0)
8234 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10008235 Py_RETURN_NONE;
Guido van Rossumc2670a01992-09-13 20:07:29 +00008236}
Guido van Rossumb6775db1994-08-01 11:34:53 +00008237#endif /* HAVE_SETSID */
Guido van Rossumc2670a01992-09-13 20:07:29 +00008238
Larry Hastings2f936352014-08-05 14:04:04 +10008239
Guido van Rossumb6775db1994-08-01 11:34:53 +00008240#ifdef HAVE_SETPGID
Larry Hastings2f936352014-08-05 14:04:04 +10008241/*[clinic input]
8242os.setpgid
8243
8244 pid: pid_t
8245 pgrp: pid_t
8246 /
8247
8248Call the system call setpgid(pid, pgrp).
8249[clinic start generated code]*/
8250
Larry Hastings2f936352014-08-05 14:04:04 +10008251static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008252os_setpgid_impl(PyObject *module, pid_t pid, pid_t pgrp)
8253/*[clinic end generated code: output=6461160319a43d6a input=fceb395eca572e1a]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008254{
Victor Stinner8c62be82010-05-06 00:08:46 +00008255 if (setpgid(pid, pgrp) < 0)
8256 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10008257 Py_RETURN_NONE;
Guido van Rossumc2670a01992-09-13 20:07:29 +00008258}
Guido van Rossumb6775db1994-08-01 11:34:53 +00008259#endif /* HAVE_SETPGID */
Guido van Rossumc2670a01992-09-13 20:07:29 +00008260
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008261
Guido van Rossumb6775db1994-08-01 11:34:53 +00008262#ifdef HAVE_TCGETPGRP
Larry Hastings2f936352014-08-05 14:04:04 +10008263/*[clinic input]
8264os.tcgetpgrp
8265
8266 fd: int
8267 /
8268
8269Return the process group associated with the terminal specified by fd.
8270[clinic start generated code]*/
8271
Larry Hastings2f936352014-08-05 14:04:04 +10008272static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008273os_tcgetpgrp_impl(PyObject *module, int fd)
8274/*[clinic end generated code: output=f865e88be86c272b input=7f6c18eac10ada86]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008275{
8276 pid_t pgid = tcgetpgrp(fd);
Victor Stinner8c62be82010-05-06 00:08:46 +00008277 if (pgid < 0)
8278 return posix_error();
8279 return PyLong_FromPid(pgid);
Guido van Rossum7066dd71992-09-17 17:54:56 +00008280}
Guido van Rossumb6775db1994-08-01 11:34:53 +00008281#endif /* HAVE_TCGETPGRP */
Guido van Rossum7066dd71992-09-17 17:54:56 +00008282
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008283
Guido van Rossumb6775db1994-08-01 11:34:53 +00008284#ifdef HAVE_TCSETPGRP
Larry Hastings2f936352014-08-05 14:04:04 +10008285/*[clinic input]
8286os.tcsetpgrp
8287
8288 fd: int
8289 pgid: pid_t
8290 /
8291
8292Set the process group associated with the terminal specified by fd.
8293[clinic start generated code]*/
8294
Larry Hastings2f936352014-08-05 14:04:04 +10008295static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008296os_tcsetpgrp_impl(PyObject *module, int fd, pid_t pgid)
8297/*[clinic end generated code: output=f1821a381b9daa39 input=5bdc997c6a619020]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008298{
Victor Stinner8c62be82010-05-06 00:08:46 +00008299 if (tcsetpgrp(fd, pgid) < 0)
8300 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10008301 Py_RETURN_NONE;
Guido van Rossum7066dd71992-09-17 17:54:56 +00008302}
Guido van Rossumb6775db1994-08-01 11:34:53 +00008303#endif /* HAVE_TCSETPGRP */
Guido van Rossum22db57e1992-04-05 14:25:30 +00008304
Guido van Rossum687dd131993-05-17 08:34:16 +00008305/* Functions acting on file descriptors */
8306
Victor Stinnerdaf45552013-08-28 00:53:59 +02008307#ifdef O_CLOEXEC
8308extern int _Py_open_cloexec_works;
8309#endif
8310
Larry Hastings2f936352014-08-05 14:04:04 +10008311
8312/*[clinic input]
8313os.open -> int
8314 path: path_t
8315 flags: int
8316 mode: int = 0o777
8317 *
8318 dir_fd: dir_fd(requires='openat') = None
8319
8320# "open(path, flags, mode=0o777, *, dir_fd=None)\n\n\
8321
8322Open a file for low level IO. Returns a file descriptor (integer).
8323
8324If dir_fd is not None, it should be a file descriptor open to a directory,
8325 and path should be relative; path will then be relative to that directory.
8326dir_fd may not be implemented on your platform.
8327 If it is unavailable, using it will raise a NotImplementedError.
8328[clinic start generated code]*/
8329
Larry Hastings2f936352014-08-05 14:04:04 +10008330static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008331os_open_impl(PyObject *module, path_t *path, int flags, int mode, int dir_fd)
8332/*[clinic end generated code: output=abc7227888c8bc73 input=ad8623b29acd2934]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008333{
8334 int fd;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008335 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10008336
Victor Stinnerdaf45552013-08-28 00:53:59 +02008337#ifdef O_CLOEXEC
8338 int *atomic_flag_works = &_Py_open_cloexec_works;
8339#elif !defined(MS_WINDOWS)
8340 int *atomic_flag_works = NULL;
8341#endif
Mark Hammondc2e85bd2002-10-03 05:10:39 +00008342
Victor Stinnerdaf45552013-08-28 00:53:59 +02008343#ifdef MS_WINDOWS
8344 flags |= O_NOINHERIT;
8345#elif defined(O_CLOEXEC)
8346 flags |= O_CLOEXEC;
8347#endif
8348
Steve Dowerb82e17e2019-05-23 08:45:22 -07008349 if (PySys_Audit("open", "OOi", path->object, Py_None, flags) < 0) {
8350 return -1;
8351 }
8352
Steve Dower8fc89802015-04-12 00:26:27 -04008353 _Py_BEGIN_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008354 do {
8355 Py_BEGIN_ALLOW_THREADS
Larry Hastings9cf065c2012-06-22 16:30:09 -07008356#ifdef MS_WINDOWS
Steve Dowercc16be82016-09-08 10:35:16 -07008357 fd = _wopen(path->wide, flags, mode);
Steve Dower6230aaf2016-09-09 09:03:15 -07008358#else
Larry Hastings9cf065c2012-06-22 16:30:09 -07008359#ifdef HAVE_OPENAT
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008360 if (dir_fd != DEFAULT_DIR_FD)
8361 fd = openat(dir_fd, path->narrow, flags, mode);
8362 else
Steve Dower6230aaf2016-09-09 09:03:15 -07008363#endif /* HAVE_OPENAT */
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008364 fd = open(path->narrow, flags, mode);
Steve Dower6230aaf2016-09-09 09:03:15 -07008365#endif /* !MS_WINDOWS */
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008366 Py_END_ALLOW_THREADS
8367 } while (fd < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Steve Dower8fc89802015-04-12 00:26:27 -04008368 _Py_END_SUPPRESS_IPH
Guido van Rossum687dd131993-05-17 08:34:16 +00008369
Victor Stinnerd3ffd322015-09-15 10:11:03 +02008370 if (fd < 0) {
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008371 if (!async_err)
8372 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, path->object);
Larry Hastings2f936352014-08-05 14:04:04 +10008373 return -1;
Larry Hastings9cf065c2012-06-22 16:30:09 -07008374 }
8375
Victor Stinnerdaf45552013-08-28 00:53:59 +02008376#ifndef MS_WINDOWS
8377 if (_Py_set_inheritable(fd, 0, atomic_flag_works) < 0) {
8378 close(fd);
Larry Hastings2f936352014-08-05 14:04:04 +10008379 return -1;
Victor Stinnerdaf45552013-08-28 00:53:59 +02008380 }
8381#endif
8382
Larry Hastings2f936352014-08-05 14:04:04 +10008383 return fd;
8384}
8385
8386
8387/*[clinic input]
8388os.close
8389
8390 fd: int
8391
8392Close a file descriptor.
8393[clinic start generated code]*/
8394
Barry Warsaw53699e91996-12-10 23:23:01 +00008395static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008396os_close_impl(PyObject *module, int fd)
8397/*[clinic end generated code: output=2fe4e93602822c14 input=2bc42451ca5c3223]*/
Guido van Rossum687dd131993-05-17 08:34:16 +00008398{
Larry Hastings2f936352014-08-05 14:04:04 +10008399 int res;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008400 /* We do not want to retry upon EINTR: see http://lwn.net/Articles/576478/
8401 * and http://linux.derkeiler.com/Mailing-Lists/Kernel/2005-09/3000.html
8402 * for more details.
8403 */
Victor Stinner8c62be82010-05-06 00:08:46 +00008404 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04008405 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00008406 res = close(fd);
Steve Dower8fc89802015-04-12 00:26:27 -04008407 _Py_END_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00008408 Py_END_ALLOW_THREADS
8409 if (res < 0)
8410 return posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10008411 Py_RETURN_NONE;
Guido van Rossum687dd131993-05-17 08:34:16 +00008412}
8413
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008414
Larry Hastings2f936352014-08-05 14:04:04 +10008415/*[clinic input]
8416os.closerange
8417
8418 fd_low: int
8419 fd_high: int
8420 /
8421
8422Closes all file descriptors in [fd_low, fd_high), ignoring errors.
8423[clinic start generated code]*/
8424
Larry Hastings2f936352014-08-05 14:04:04 +10008425static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008426os_closerange_impl(PyObject *module, int fd_low, int fd_high)
8427/*[clinic end generated code: output=0ce5c20fcda681c2 input=5855a3d053ebd4ec]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008428{
8429 int i;
Victor Stinner8c62be82010-05-06 00:08:46 +00008430 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04008431 _Py_BEGIN_SUPPRESS_IPH
Benjamin Peterson207116b2016-09-08 11:28:06 -07008432 for (i = Py_MAX(fd_low, 0); i < fd_high; i++)
Steve Dower940f33a2016-09-08 11:21:54 -07008433 close(i);
Steve Dower8fc89802015-04-12 00:26:27 -04008434 _Py_END_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00008435 Py_END_ALLOW_THREADS
8436 Py_RETURN_NONE;
Christian Heimesfdab48e2008-01-20 09:06:41 +00008437}
8438
8439
Larry Hastings2f936352014-08-05 14:04:04 +10008440/*[clinic input]
8441os.dup -> int
8442
8443 fd: int
8444 /
8445
8446Return a duplicate of a file descriptor.
8447[clinic start generated code]*/
8448
Larry Hastings2f936352014-08-05 14:04:04 +10008449static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008450os_dup_impl(PyObject *module, int fd)
8451/*[clinic end generated code: output=486f4860636b2a9f input=6f10f7ea97f7852a]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008452{
8453 return _Py_dup(fd);
Guido van Rossum687dd131993-05-17 08:34:16 +00008454}
8455
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008456
Larry Hastings2f936352014-08-05 14:04:04 +10008457/*[clinic input]
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008458os.dup2 -> int
Larry Hastings2f936352014-08-05 14:04:04 +10008459 fd: int
8460 fd2: int
8461 inheritable: bool=True
8462
8463Duplicate file descriptor.
8464[clinic start generated code]*/
8465
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008466static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008467os_dup2_impl(PyObject *module, int fd, int fd2, int inheritable)
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008468/*[clinic end generated code: output=bc059d34a73404d1 input=c3cddda8922b038d]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008469{
Stéphane Wirtel3d86e482018-01-30 07:04:36 +01008470 int res = 0;
Victor Stinnerdaf45552013-08-28 00:53:59 +02008471#if defined(HAVE_DUP3) && \
8472 !(defined(HAVE_FCNTL_H) && defined(F_DUP2FD_CLOEXEC))
8473 /* dup3() is available on Linux 2.6.27+ and glibc 2.9 */
Alexey Izbyshevb3caf382018-02-20 10:25:46 +03008474 static int dup3_works = -1;
Victor Stinnerdaf45552013-08-28 00:53:59 +02008475#endif
8476
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008477 if (fd < 0 || fd2 < 0) {
8478 posix_error();
8479 return -1;
8480 }
Victor Stinnerdaf45552013-08-28 00:53:59 +02008481
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008482 /* dup2() can fail with EINTR if the target FD is already open, because it
8483 * then has to be closed. See os_close_impl() for why we don't handle EINTR
8484 * upon close(), and therefore below.
8485 */
Victor Stinnerdaf45552013-08-28 00:53:59 +02008486#ifdef MS_WINDOWS
8487 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04008488 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00008489 res = dup2(fd, fd2);
Steve Dower8fc89802015-04-12 00:26:27 -04008490 _Py_END_SUPPRESS_IPH
Victor Stinnerdaf45552013-08-28 00:53:59 +02008491 Py_END_ALLOW_THREADS
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008492 if (res < 0) {
8493 posix_error();
8494 return -1;
8495 }
8496 res = fd2; // msvcrt dup2 returns 0 on success.
Victor Stinnerdaf45552013-08-28 00:53:59 +02008497
8498 /* Character files like console cannot be make non-inheritable */
8499 if (!inheritable && _Py_set_inheritable(fd2, 0, NULL) < 0) {
8500 close(fd2);
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008501 return -1;
Victor Stinnerdaf45552013-08-28 00:53:59 +02008502 }
8503
8504#elif defined(HAVE_FCNTL_H) && defined(F_DUP2FD_CLOEXEC)
8505 Py_BEGIN_ALLOW_THREADS
8506 if (!inheritable)
8507 res = fcntl(fd, F_DUP2FD_CLOEXEC, fd2);
8508 else
8509 res = dup2(fd, fd2);
8510 Py_END_ALLOW_THREADS
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008511 if (res < 0) {
8512 posix_error();
8513 return -1;
8514 }
Victor Stinnerdaf45552013-08-28 00:53:59 +02008515
8516#else
8517
8518#ifdef HAVE_DUP3
8519 if (!inheritable && dup3_works != 0) {
8520 Py_BEGIN_ALLOW_THREADS
8521 res = dup3(fd, fd2, O_CLOEXEC);
8522 Py_END_ALLOW_THREADS
8523 if (res < 0) {
8524 if (dup3_works == -1)
8525 dup3_works = (errno != ENOSYS);
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008526 if (dup3_works) {
8527 posix_error();
8528 return -1;
8529 }
Victor Stinnerdaf45552013-08-28 00:53:59 +02008530 }
8531 }
8532
8533 if (inheritable || dup3_works == 0)
8534 {
8535#endif
8536 Py_BEGIN_ALLOW_THREADS
8537 res = dup2(fd, fd2);
8538 Py_END_ALLOW_THREADS
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008539 if (res < 0) {
8540 posix_error();
8541 return -1;
8542 }
Victor Stinnerdaf45552013-08-28 00:53:59 +02008543
8544 if (!inheritable && _Py_set_inheritable(fd2, 0, NULL) < 0) {
8545 close(fd2);
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008546 return -1;
Victor Stinnerdaf45552013-08-28 00:53:59 +02008547 }
8548#ifdef HAVE_DUP3
8549 }
8550#endif
8551
8552#endif
8553
Benjamin Petersonbbdb17d2017-12-29 13:13:06 -08008554 return res;
Guido van Rossum687dd131993-05-17 08:34:16 +00008555}
8556
Larry Hastings2f936352014-08-05 14:04:04 +10008557
Ross Lagerwall7807c352011-03-17 20:20:30 +02008558#ifdef HAVE_LOCKF
Larry Hastings2f936352014-08-05 14:04:04 +10008559/*[clinic input]
8560os.lockf
8561
8562 fd: int
8563 An open file descriptor.
8564 command: int
8565 One of F_LOCK, F_TLOCK, F_ULOCK or F_TEST.
8566 length: Py_off_t
8567 The number of bytes to lock, starting at the current position.
8568 /
8569
8570Apply, test or remove a POSIX lock on an open file descriptor.
8571
8572[clinic start generated code]*/
8573
Larry Hastings2f936352014-08-05 14:04:04 +10008574static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008575os_lockf_impl(PyObject *module, int fd, int command, Py_off_t length)
8576/*[clinic end generated code: output=af7051f3e7c29651 input=65da41d2106e9b79]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008577{
8578 int res;
Ross Lagerwall7807c352011-03-17 20:20:30 +02008579
8580 Py_BEGIN_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10008581 res = lockf(fd, command, length);
Ross Lagerwall7807c352011-03-17 20:20:30 +02008582 Py_END_ALLOW_THREADS
8583
8584 if (res < 0)
8585 return posix_error();
8586
8587 Py_RETURN_NONE;
8588}
Larry Hastings2f936352014-08-05 14:04:04 +10008589#endif /* HAVE_LOCKF */
Ross Lagerwall7807c352011-03-17 20:20:30 +02008590
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008591
Larry Hastings2f936352014-08-05 14:04:04 +10008592/*[clinic input]
8593os.lseek -> Py_off_t
8594
8595 fd: int
8596 position: Py_off_t
8597 how: int
8598 /
8599
8600Set the position of a file descriptor. Return the new position.
8601
8602Return the new cursor position in number of bytes
8603relative to the beginning of the file.
8604[clinic start generated code]*/
8605
Larry Hastings2f936352014-08-05 14:04:04 +10008606static Py_off_t
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008607os_lseek_impl(PyObject *module, int fd, Py_off_t position, int how)
8608/*[clinic end generated code: output=971e1efb6b30bd2f input=902654ad3f96a6d3]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008609{
8610 Py_off_t result;
8611
Guido van Rossum687dd131993-05-17 08:34:16 +00008612#ifdef SEEK_SET
Victor Stinner8c62be82010-05-06 00:08:46 +00008613 /* Turn 0, 1, 2 into SEEK_{SET,CUR,END} */
8614 switch (how) {
Larry Hastings2f936352014-08-05 14:04:04 +10008615 case 0: how = SEEK_SET; break;
8616 case 1: how = SEEK_CUR; break;
8617 case 2: how = SEEK_END; break;
Victor Stinner8c62be82010-05-06 00:08:46 +00008618 }
Guido van Rossum6a3eb5f1994-08-18 15:42:46 +00008619#endif /* SEEK_END */
Guido van Rossum94f6f721999-01-06 18:42:14 +00008620
Victor Stinner8c62be82010-05-06 00:08:46 +00008621 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04008622 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner14b9b112013-06-25 00:37:25 +02008623#ifdef MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +10008624 result = _lseeki64(fd, position, how);
Fred Drake699f3522000-06-29 21:12:41 +00008625#else
Larry Hastings2f936352014-08-05 14:04:04 +10008626 result = lseek(fd, position, how);
Fred Drake699f3522000-06-29 21:12:41 +00008627#endif
Steve Dower8fc89802015-04-12 00:26:27 -04008628 _Py_END_SUPPRESS_IPH
Victor Stinner8c62be82010-05-06 00:08:46 +00008629 Py_END_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10008630 if (result < 0)
8631 posix_error();
Guido van Rossum94f6f721999-01-06 18:42:14 +00008632
Larry Hastings2f936352014-08-05 14:04:04 +10008633 return result;
Guido van Rossum687dd131993-05-17 08:34:16 +00008634}
8635
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00008636
Larry Hastings2f936352014-08-05 14:04:04 +10008637/*[clinic input]
8638os.read
8639 fd: int
8640 length: Py_ssize_t
8641 /
8642
8643Read from a file descriptor. Returns a bytes object.
8644[clinic start generated code]*/
8645
Larry Hastings2f936352014-08-05 14:04:04 +10008646static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008647os_read_impl(PyObject *module, int fd, Py_ssize_t length)
8648/*[clinic end generated code: output=dafbe9a5cddb987b input=1df2eaa27c0bf1d3]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008649{
Victor Stinner8c62be82010-05-06 00:08:46 +00008650 Py_ssize_t n;
8651 PyObject *buffer;
Larry Hastings2f936352014-08-05 14:04:04 +10008652
8653 if (length < 0) {
Victor Stinner8c62be82010-05-06 00:08:46 +00008654 errno = EINVAL;
8655 return posix_error();
8656 }
Larry Hastings2f936352014-08-05 14:04:04 +10008657
Victor Stinner9a0d7a72018-11-22 15:03:40 +01008658 length = Py_MIN(length, _PY_READ_MAX);
Larry Hastings2f936352014-08-05 14:04:04 +10008659
8660 buffer = PyBytes_FromStringAndSize((char *)NULL, length);
Victor Stinner8c62be82010-05-06 00:08:46 +00008661 if (buffer == NULL)
8662 return NULL;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008663
Victor Stinner66aab0c2015-03-19 22:53:20 +01008664 n = _Py_read(fd, PyBytes_AS_STRING(buffer), length);
8665 if (n == -1) {
Victor Stinner8c62be82010-05-06 00:08:46 +00008666 Py_DECREF(buffer);
Victor Stinner66aab0c2015-03-19 22:53:20 +01008667 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +00008668 }
Larry Hastings2f936352014-08-05 14:04:04 +10008669
8670 if (n != length)
Victor Stinner8c62be82010-05-06 00:08:46 +00008671 _PyBytes_Resize(&buffer, n);
Larry Hastings2f936352014-08-05 14:04:04 +10008672
Victor Stinner8c62be82010-05-06 00:08:46 +00008673 return buffer;
Guido van Rossum687dd131993-05-17 08:34:16 +00008674}
8675
Ross Lagerwall7807c352011-03-17 20:20:30 +02008676#if (defined(HAVE_SENDFILE) && (defined(__FreeBSD__) || defined(__DragonFly__) \
Serhiy Storchaka9d572732018-07-31 10:24:54 +03008677 || defined(__APPLE__))) \
8678 || defined(HAVE_READV) || defined(HAVE_PREADV) || defined (HAVE_PREADV2) \
8679 || defined(HAVE_WRITEV) || defined(HAVE_PWRITEV) || defined (HAVE_PWRITEV2)
8680static int
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03008681iov_setup(struct iovec **iov, Py_buffer **buf, PyObject *seq, Py_ssize_t cnt, int type)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008682{
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03008683 Py_ssize_t i, j;
Giampaolo Rodolàacdad9a2011-03-03 16:10:51 +00008684
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008685 *iov = PyMem_New(struct iovec, cnt);
8686 if (*iov == NULL) {
8687 PyErr_NoMemory();
Victor Stinner57ddf782014-01-08 15:21:28 +01008688 return -1;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008689 }
Giampaolo Rodolàacdad9a2011-03-03 16:10:51 +00008690
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008691 *buf = PyMem_New(Py_buffer, cnt);
8692 if (*buf == NULL) {
8693 PyMem_Del(*iov);
8694 PyErr_NoMemory();
Victor Stinner57ddf782014-01-08 15:21:28 +01008695 return -1;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008696 }
8697
8698 for (i = 0; i < cnt; i++) {
Ross Lagerwall9ad63e02011-03-19 09:11:14 +02008699 PyObject *item = PySequence_GetItem(seq, i);
8700 if (item == NULL)
8701 goto fail;
8702 if (PyObject_GetBuffer(item, &(*buf)[i], type) == -1) {
8703 Py_DECREF(item);
8704 goto fail;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008705 }
Ross Lagerwall9ad63e02011-03-19 09:11:14 +02008706 Py_DECREF(item);
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008707 (*iov)[i].iov_base = (*buf)[i].buf;
Serhiy Storchaka9d572732018-07-31 10:24:54 +03008708 (*iov)[i].iov_len = (*buf)[i].len;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008709 }
Serhiy Storchaka9d572732018-07-31 10:24:54 +03008710 return 0;
Ross Lagerwall9ad63e02011-03-19 09:11:14 +02008711
8712fail:
8713 PyMem_Del(*iov);
8714 for (j = 0; j < i; j++) {
8715 PyBuffer_Release(&(*buf)[j]);
8716 }
8717 PyMem_Del(*buf);
Victor Stinner57ddf782014-01-08 15:21:28 +01008718 return -1;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008719}
8720
8721static void
8722iov_cleanup(struct iovec *iov, Py_buffer *buf, int cnt)
8723{
8724 int i;
8725 PyMem_Del(iov);
8726 for (i = 0; i < cnt; i++) {
8727 PyBuffer_Release(&buf[i]);
8728 }
8729 PyMem_Del(buf);
8730}
8731#endif
8732
Larry Hastings2f936352014-08-05 14:04:04 +10008733
Ross Lagerwall7807c352011-03-17 20:20:30 +02008734#ifdef HAVE_READV
Larry Hastings2f936352014-08-05 14:04:04 +10008735/*[clinic input]
8736os.readv -> Py_ssize_t
8737
8738 fd: int
8739 buffers: object
8740 /
8741
8742Read from a file descriptor fd into an iterable of buffers.
8743
8744The buffers should be mutable buffers accepting bytes.
8745readv will transfer data into each buffer until it is full
8746and then move on to the next buffer in the sequence to hold
8747the rest of the data.
8748
8749readv returns the total number of bytes read,
8750which may be less than the total capacity of all the buffers.
8751[clinic start generated code]*/
8752
Larry Hastings2f936352014-08-05 14:04:04 +10008753static Py_ssize_t
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008754os_readv_impl(PyObject *module, int fd, PyObject *buffers)
8755/*[clinic end generated code: output=792da062d3fcebdb input=e679eb5dbfa0357d]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008756{
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03008757 Py_ssize_t cnt, n;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008758 int async_err = 0;
Ross Lagerwall7807c352011-03-17 20:20:30 +02008759 struct iovec *iov;
8760 Py_buffer *buf;
8761
Larry Hastings2f936352014-08-05 14:04:04 +10008762 if (!PySequence_Check(buffers)) {
Ross Lagerwall7807c352011-03-17 20:20:30 +02008763 PyErr_SetString(PyExc_TypeError,
8764 "readv() arg 2 must be a sequence");
Larry Hastings2f936352014-08-05 14:04:04 +10008765 return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +02008766 }
Ross Lagerwall7807c352011-03-17 20:20:30 +02008767
Larry Hastings2f936352014-08-05 14:04:04 +10008768 cnt = PySequence_Size(buffers);
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03008769 if (cnt < 0)
8770 return -1;
Larry Hastings2f936352014-08-05 14:04:04 +10008771
8772 if (iov_setup(&iov, &buf, buffers, cnt, PyBUF_WRITABLE) < 0)
8773 return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +02008774
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008775 do {
8776 Py_BEGIN_ALLOW_THREADS
8777 n = readv(fd, iov, cnt);
8778 Py_END_ALLOW_THREADS
8779 } while (n < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Ross Lagerwall7807c352011-03-17 20:20:30 +02008780
8781 iov_cleanup(iov, buf, cnt);
Larry Hastings2f936352014-08-05 14:04:04 +10008782 if (n < 0) {
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008783 if (!async_err)
8784 posix_error();
Larry Hastings2f936352014-08-05 14:04:04 +10008785 return -1;
8786 }
Victor Stinner57ddf782014-01-08 15:21:28 +01008787
Larry Hastings2f936352014-08-05 14:04:04 +10008788 return n;
Ross Lagerwall7807c352011-03-17 20:20:30 +02008789}
Larry Hastings2f936352014-08-05 14:04:04 +10008790#endif /* HAVE_READV */
8791
Ross Lagerwall7807c352011-03-17 20:20:30 +02008792
8793#ifdef HAVE_PREAD
Larry Hastings2f936352014-08-05 14:04:04 +10008794/*[clinic input]
8795# TODO length should be size_t! but Python doesn't support parsing size_t yet.
8796os.pread
8797
8798 fd: int
8799 length: int
8800 offset: Py_off_t
8801 /
8802
8803Read a number of bytes from a file descriptor starting at a particular offset.
8804
8805Read length bytes from file descriptor fd, starting at offset bytes from
8806the beginning of the file. The file offset remains unchanged.
8807[clinic start generated code]*/
8808
Larry Hastings2f936352014-08-05 14:04:04 +10008809static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008810os_pread_impl(PyObject *module, int fd, int length, Py_off_t offset)
8811/*[clinic end generated code: output=435b29ee32b54a78 input=084948dcbaa35d4c]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008812{
Ross Lagerwall7807c352011-03-17 20:20:30 +02008813 Py_ssize_t n;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008814 int async_err = 0;
Ross Lagerwall7807c352011-03-17 20:20:30 +02008815 PyObject *buffer;
Ross Lagerwall7807c352011-03-17 20:20:30 +02008816
Larry Hastings2f936352014-08-05 14:04:04 +10008817 if (length < 0) {
Ross Lagerwall7807c352011-03-17 20:20:30 +02008818 errno = EINVAL;
8819 return posix_error();
8820 }
Larry Hastings2f936352014-08-05 14:04:04 +10008821 buffer = PyBytes_FromStringAndSize((char *)NULL, length);
Ross Lagerwall7807c352011-03-17 20:20:30 +02008822 if (buffer == NULL)
8823 return NULL;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008824
8825 do {
8826 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04008827 _Py_BEGIN_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008828 n = pread(fd, PyBytes_AS_STRING(buffer), length, offset);
Steve Dower8fc89802015-04-12 00:26:27 -04008829 _Py_END_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008830 Py_END_ALLOW_THREADS
8831 } while (n < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
8832
Ross Lagerwall7807c352011-03-17 20:20:30 +02008833 if (n < 0) {
8834 Py_DECREF(buffer);
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008835 return (!async_err) ? posix_error() : NULL;
Ross Lagerwall7807c352011-03-17 20:20:30 +02008836 }
Larry Hastings2f936352014-08-05 14:04:04 +10008837 if (n != length)
Ross Lagerwall7807c352011-03-17 20:20:30 +02008838 _PyBytes_Resize(&buffer, n);
8839 return buffer;
8840}
Larry Hastings2f936352014-08-05 14:04:04 +10008841#endif /* HAVE_PREAD */
Ross Lagerwall7807c352011-03-17 20:20:30 +02008842
Pablo Galindo4defba32018-01-27 16:16:37 +00008843#if defined(HAVE_PREADV) || defined (HAVE_PREADV2)
8844/*[clinic input]
8845os.preadv -> Py_ssize_t
8846
8847 fd: int
8848 buffers: object
8849 offset: Py_off_t
8850 flags: int = 0
8851 /
8852
8853Reads from a file descriptor into a number of mutable bytes-like objects.
8854
8855Combines the functionality of readv() and pread(). As readv(), it will
8856transfer data into each buffer until it is full and then move on to the next
8857buffer in the sequence to hold the rest of the data. Its fourth argument,
8858specifies the file offset at which the input operation is to be performed. It
8859will return the total number of bytes read (which can be less than the total
8860capacity of all the objects).
8861
8862The flags argument contains a bitwise OR of zero or more of the following flags:
8863
8864- RWF_HIPRI
8865- RWF_NOWAIT
8866
8867Using non-zero flags requires Linux 4.6 or newer.
8868[clinic start generated code]*/
8869
8870static Py_ssize_t
8871os_preadv_impl(PyObject *module, int fd, PyObject *buffers, Py_off_t offset,
8872 int flags)
8873/*[clinic end generated code: output=26fc9c6e58e7ada5 input=4173919dc1f7ed99]*/
8874{
8875 Py_ssize_t cnt, n;
8876 int async_err = 0;
8877 struct iovec *iov;
8878 Py_buffer *buf;
8879
8880 if (!PySequence_Check(buffers)) {
8881 PyErr_SetString(PyExc_TypeError,
8882 "preadv2() arg 2 must be a sequence");
8883 return -1;
8884 }
8885
8886 cnt = PySequence_Size(buffers);
8887 if (cnt < 0) {
8888 return -1;
8889 }
8890
8891#ifndef HAVE_PREADV2
8892 if(flags != 0) {
8893 argument_unavailable_error("preadv2", "flags");
8894 return -1;
8895 }
8896#endif
8897
8898 if (iov_setup(&iov, &buf, buffers, cnt, PyBUF_WRITABLE) < 0) {
8899 return -1;
8900 }
8901#ifdef HAVE_PREADV2
8902 do {
8903 Py_BEGIN_ALLOW_THREADS
8904 _Py_BEGIN_SUPPRESS_IPH
8905 n = preadv2(fd, iov, cnt, offset, flags);
8906 _Py_END_SUPPRESS_IPH
8907 Py_END_ALLOW_THREADS
8908 } while (n < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
8909#else
8910 do {
8911 Py_BEGIN_ALLOW_THREADS
8912 _Py_BEGIN_SUPPRESS_IPH
8913 n = preadv(fd, iov, cnt, offset);
8914 _Py_END_SUPPRESS_IPH
8915 Py_END_ALLOW_THREADS
8916 } while (n < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
8917#endif
8918
8919 iov_cleanup(iov, buf, cnt);
8920 if (n < 0) {
8921 if (!async_err) {
8922 posix_error();
8923 }
8924 return -1;
8925 }
8926
8927 return n;
8928}
8929#endif /* HAVE_PREADV */
8930
Larry Hastings2f936352014-08-05 14:04:04 +10008931
8932/*[clinic input]
8933os.write -> Py_ssize_t
8934
8935 fd: int
8936 data: Py_buffer
8937 /
8938
8939Write a bytes object to a file descriptor.
8940[clinic start generated code]*/
8941
Larry Hastings2f936352014-08-05 14:04:04 +10008942static Py_ssize_t
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03008943os_write_impl(PyObject *module, int fd, Py_buffer *data)
8944/*[clinic end generated code: output=e4ef5bc904b58ef9 input=3207e28963234f3c]*/
Larry Hastings2f936352014-08-05 14:04:04 +10008945{
Victor Stinner66aab0c2015-03-19 22:53:20 +01008946 return _Py_write(fd, data->buf, data->len);
Ross Lagerwall7807c352011-03-17 20:20:30 +02008947}
8948
8949#ifdef HAVE_SENDFILE
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008950PyDoc_STRVAR(posix_sendfile__doc__,
Martin Panterbf19d162015-09-09 01:01:13 +00008951"sendfile(out, in, offset, count) -> byteswritten\n\
Martin Panter94994132015-09-09 05:29:24 +00008952sendfile(out, in, offset, count[, headers][, trailers], flags=0)\n\
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008953 -> byteswritten\n\
Martin Panterbf19d162015-09-09 01:01:13 +00008954Copy count bytes from file descriptor in to file descriptor out.");
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008955
Larry Hastings2f936352014-08-05 14:04:04 +10008956/* AC 3.5: don't bother converting, has optional group*/
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008957static PyObject *
8958posix_sendfile(PyObject *self, PyObject *args, PyObject *kwdict)
8959{
8960 int in, out;
8961 Py_ssize_t ret;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00008962 int async_err = 0;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008963 off_t offset;
8964
8965#if defined(__FreeBSD__) || defined(__DragonFly__) || defined(__APPLE__)
8966#ifndef __APPLE__
8967 Py_ssize_t len;
8968#endif
8969 PyObject *headers = NULL, *trailers = NULL;
8970 Py_buffer *hbuf, *tbuf;
8971 off_t sbytes;
8972 struct sf_hdtr sf;
8973 int flags = 0;
Martin Panterbf19d162015-09-09 01:01:13 +00008974 /* Beware that "in" clashes with Python's own "in" operator keyword */
Benjamin Petersond8a43b42011-02-26 21:35:16 +00008975 static char *keywords[] = {"out", "in",
8976 "offset", "count",
8977 "headers", "trailers", "flags", NULL};
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008978
Victor Stinner6ce0dbf2013-07-07 16:32:36 +02008979 sf.headers = NULL;
8980 sf.trailers = NULL;
8981
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008982#ifdef __APPLE__
8983 if (!PyArg_ParseTupleAndKeywords(args, kwdict, "iiO&O&|OOi:sendfile",
Larry Hastings2f936352014-08-05 14:04:04 +10008984 keywords, &out, &in, Py_off_t_converter, &offset, Py_off_t_converter, &sbytes,
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008985#else
8986 if (!PyArg_ParseTupleAndKeywords(args, kwdict, "iiO&n|OOi:sendfile",
Larry Hastings2f936352014-08-05 14:04:04 +10008987 keywords, &out, &in, Py_off_t_converter, &offset, &len,
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008988#endif
8989 &headers, &trailers, &flags))
8990 return NULL;
8991 if (headers != NULL) {
8992 if (!PySequence_Check(headers)) {
8993 PyErr_SetString(PyExc_TypeError,
Martin Panter94994132015-09-09 05:29:24 +00008994 "sendfile() headers must be a sequence");
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008995 return NULL;
8996 } else {
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03008997 Py_ssize_t i = PySequence_Size(headers);
8998 if (i < 0)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00008999 return NULL;
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009000 if (i > INT_MAX) {
9001 PyErr_SetString(PyExc_OverflowError,
9002 "sendfile() header is too large");
9003 return NULL;
9004 }
9005 if (i > 0) {
9006 sf.hdr_cnt = (int)i;
Serhiy Storchaka9d572732018-07-31 10:24:54 +03009007 if (iov_setup(&(sf.headers), &hbuf,
9008 headers, sf.hdr_cnt, PyBUF_SIMPLE) < 0)
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009009 return NULL;
Giampaolo Rodolàacdad9a2011-03-03 16:10:51 +00009010#ifdef __APPLE__
Serhiy Storchaka9d572732018-07-31 10:24:54 +03009011 for (i = 0; i < sf.hdr_cnt; i++) {
9012 Py_ssize_t blen = sf.headers[i].iov_len;
9013# define OFF_T_MAX 0x7fffffffffffffff
9014 if (sbytes >= OFF_T_MAX - blen) {
9015 PyErr_SetString(PyExc_OverflowError,
9016 "sendfile() header is too large");
9017 return NULL;
9018 }
9019 sbytes += blen;
9020 }
Giampaolo Rodolàacdad9a2011-03-03 16:10:51 +00009021#endif
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009022 }
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009023 }
9024 }
9025 if (trailers != NULL) {
9026 if (!PySequence_Check(trailers)) {
9027 PyErr_SetString(PyExc_TypeError,
Martin Panter94994132015-09-09 05:29:24 +00009028 "sendfile() trailers must be a sequence");
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009029 return NULL;
9030 } else {
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009031 Py_ssize_t i = PySequence_Size(trailers);
9032 if (i < 0)
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009033 return NULL;
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009034 if (i > INT_MAX) {
9035 PyErr_SetString(PyExc_OverflowError,
9036 "sendfile() trailer is too large");
9037 return NULL;
9038 }
9039 if (i > 0) {
9040 sf.trl_cnt = (int)i;
Serhiy Storchaka9d572732018-07-31 10:24:54 +03009041 if (iov_setup(&(sf.trailers), &tbuf,
9042 trailers, sf.trl_cnt, PyBUF_SIMPLE) < 0)
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009043 return NULL;
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009044 }
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009045 }
9046 }
9047
Steve Dower8fc89802015-04-12 00:26:27 -04009048 _Py_BEGIN_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009049 do {
9050 Py_BEGIN_ALLOW_THREADS
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009051#ifdef __APPLE__
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009052 ret = sendfile(in, out, offset, &sbytes, &sf, flags);
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009053#else
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009054 ret = sendfile(in, out, offset, len, &sf, &sbytes, flags);
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009055#endif
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009056 Py_END_ALLOW_THREADS
9057 } while (ret < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Steve Dower8fc89802015-04-12 00:26:27 -04009058 _Py_END_SUPPRESS_IPH
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009059
9060 if (sf.headers != NULL)
9061 iov_cleanup(sf.headers, hbuf, sf.hdr_cnt);
9062 if (sf.trailers != NULL)
9063 iov_cleanup(sf.trailers, tbuf, sf.trl_cnt);
9064
9065 if (ret < 0) {
9066 if ((errno == EAGAIN) || (errno == EBUSY)) {
9067 if (sbytes != 0) {
9068 // some data has been sent
9069 goto done;
9070 }
9071 else {
9072 // no data has been sent; upper application is supposed
9073 // to retry on EAGAIN or EBUSY
9074 return posix_error();
9075 }
9076 }
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009077 return (!async_err) ? posix_error() : NULL;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009078 }
9079 goto done;
9080
9081done:
9082 #if !defined(HAVE_LARGEFILE_SUPPORT)
9083 return Py_BuildValue("l", sbytes);
9084 #else
9085 return Py_BuildValue("L", sbytes);
9086 #endif
9087
9088#else
9089 Py_ssize_t count;
9090 PyObject *offobj;
9091 static char *keywords[] = {"out", "in",
9092 "offset", "count", NULL};
9093 if (!PyArg_ParseTupleAndKeywords(args, kwdict, "iiOn:sendfile",
9094 keywords, &out, &in, &offobj, &count))
9095 return NULL;
Benjamin Peterson840ef8f2016-09-07 14:45:10 -07009096#ifdef __linux__
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009097 if (offobj == Py_None) {
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009098 do {
9099 Py_BEGIN_ALLOW_THREADS
9100 ret = sendfile(out, in, NULL, count);
9101 Py_END_ALLOW_THREADS
9102 } while (ret < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009103 if (ret < 0)
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009104 return (!async_err) ? posix_error() : NULL;
Giampaolo Rodola'ff1a7352011-04-19 09:47:16 +02009105 return Py_BuildValue("n", ret);
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009106 }
9107#endif
Larry Hastings2f936352014-08-05 14:04:04 +10009108 if (!Py_off_t_converter(offobj, &offset))
Antoine Pitroudcc20b82011-02-26 13:38:35 +00009109 return NULL;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009110
9111 do {
9112 Py_BEGIN_ALLOW_THREADS
9113 ret = sendfile(out, in, &offset, count);
9114 Py_END_ALLOW_THREADS
9115 } while (ret < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009116 if (ret < 0)
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009117 return (!async_err) ? posix_error() : NULL;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00009118 return Py_BuildValue("n", ret);
9119#endif
9120}
Larry Hastings2f936352014-08-05 14:04:04 +10009121#endif /* HAVE_SENDFILE */
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00009122
Larry Hastings2f936352014-08-05 14:04:04 +10009123
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +02009124#if defined(__APPLE__)
9125/*[clinic input]
9126os._fcopyfile
9127
9128 infd: int
9129 outfd: int
9130 flags: int
9131 /
9132
Giampaolo Rodolac7f02a92018-06-19 08:27:29 -07009133Efficiently copy content or metadata of 2 regular file descriptors (macOS).
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +02009134[clinic start generated code]*/
9135
9136static PyObject *
9137os__fcopyfile_impl(PyObject *module, int infd, int outfd, int flags)
Giampaolo Rodolac7f02a92018-06-19 08:27:29 -07009138/*[clinic end generated code: output=8e8885c721ec38e3 input=69e0770e600cb44f]*/
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +02009139{
9140 int ret;
9141
9142 Py_BEGIN_ALLOW_THREADS
9143 ret = fcopyfile(infd, outfd, NULL, flags);
9144 Py_END_ALLOW_THREADS
9145 if (ret < 0)
9146 return posix_error();
9147 Py_RETURN_NONE;
9148}
9149#endif
9150
9151
Larry Hastings2f936352014-08-05 14:04:04 +10009152/*[clinic input]
9153os.fstat
9154
9155 fd : int
9156
9157Perform a stat system call on the given file descriptor.
9158
9159Like stat(), but for an open file descriptor.
9160Equivalent to os.stat(fd).
9161[clinic start generated code]*/
9162
Larry Hastings2f936352014-08-05 14:04:04 +10009163static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009164os_fstat_impl(PyObject *module, int fd)
9165/*[clinic end generated code: output=efc038cb5f654492 input=27e0e0ebbe5600c9]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009166{
Victor Stinner8c62be82010-05-06 00:08:46 +00009167 STRUCT_STAT st;
9168 int res;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009169 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10009170
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009171 do {
9172 Py_BEGIN_ALLOW_THREADS
9173 res = FSTAT(fd, &st);
9174 Py_END_ALLOW_THREADS
9175 } while (res != 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Victor Stinner8c62be82010-05-06 00:08:46 +00009176 if (res != 0) {
Martin v. Löwis14694662006-02-03 12:54:16 +00009177#ifdef MS_WINDOWS
Victor Stinnerb024e842012-10-31 22:24:06 +01009178 return PyErr_SetFromWindowsErr(0);
Martin v. Löwis14694662006-02-03 12:54:16 +00009179#else
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009180 return (!async_err) ? posix_error() : NULL;
Martin v. Löwis14694662006-02-03 12:54:16 +00009181#endif
Victor Stinner8c62be82010-05-06 00:08:46 +00009182 }
Tim Peters5aa91602002-01-30 05:46:57 +00009183
Victor Stinner4195b5c2012-02-08 23:03:19 +01009184 return _pystat_fromstructstat(&st);
Guido van Rossum687dd131993-05-17 08:34:16 +00009185}
9186
Larry Hastings2f936352014-08-05 14:04:04 +10009187
9188/*[clinic input]
9189os.isatty -> bool
9190 fd: int
9191 /
9192
9193Return True if the fd is connected to a terminal.
9194
9195Return True if the file descriptor is an open file descriptor
9196connected to the slave end of a terminal.
9197[clinic start generated code]*/
9198
Larry Hastings2f936352014-08-05 14:04:04 +10009199static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009200os_isatty_impl(PyObject *module, int fd)
9201/*[clinic end generated code: output=6a48c8b4e644ca00 input=08ce94aa1eaf7b5e]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009202{
Steve Dower8fc89802015-04-12 00:26:27 -04009203 int return_value;
Steve Dower8fc89802015-04-12 00:26:27 -04009204 _Py_BEGIN_SUPPRESS_IPH
9205 return_value = isatty(fd);
9206 _Py_END_SUPPRESS_IPH
9207 return return_value;
Larry Hastings2f936352014-08-05 14:04:04 +10009208}
9209
9210
Guido van Rossuma4916fa1996-05-23 22:58:55 +00009211#ifdef HAVE_PIPE
Larry Hastings2f936352014-08-05 14:04:04 +10009212/*[clinic input]
9213os.pipe
9214
9215Create a pipe.
9216
9217Returns a tuple of two file descriptors:
9218 (read_fd, write_fd)
9219[clinic start generated code]*/
9220
Larry Hastings2f936352014-08-05 14:04:04 +10009221static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009222os_pipe_impl(PyObject *module)
9223/*[clinic end generated code: output=ff9b76255793b440 input=02535e8c8fa6c4d4]*/
Guido van Rossum687dd131993-05-17 08:34:16 +00009224{
Victor Stinner8c62be82010-05-06 00:08:46 +00009225 int fds[2];
Victor Stinnerdaf45552013-08-28 00:53:59 +02009226#ifdef MS_WINDOWS
Victor Stinner8c62be82010-05-06 00:08:46 +00009227 HANDLE read, write;
Victor Stinnerdaf45552013-08-28 00:53:59 +02009228 SECURITY_ATTRIBUTES attr;
Victor Stinner8c62be82010-05-06 00:08:46 +00009229 BOOL ok;
Victor Stinnerdaf45552013-08-28 00:53:59 +02009230#else
9231 int res;
9232#endif
9233
9234#ifdef MS_WINDOWS
9235 attr.nLength = sizeof(attr);
9236 attr.lpSecurityDescriptor = NULL;
9237 attr.bInheritHandle = FALSE;
9238
9239 Py_BEGIN_ALLOW_THREADS
Steve Dowerc3630612016-11-19 18:41:16 -08009240 _Py_BEGIN_SUPPRESS_IPH
Victor Stinnerdaf45552013-08-28 00:53:59 +02009241 ok = CreatePipe(&read, &write, &attr, 0);
9242 if (ok) {
Benjamin Petersonca470632016-09-06 13:47:26 -07009243 fds[0] = _open_osfhandle((intptr_t)read, _O_RDONLY);
9244 fds[1] = _open_osfhandle((intptr_t)write, _O_WRONLY);
Victor Stinnerdaf45552013-08-28 00:53:59 +02009245 if (fds[0] == -1 || fds[1] == -1) {
9246 CloseHandle(read);
9247 CloseHandle(write);
9248 ok = 0;
9249 }
9250 }
Steve Dowerc3630612016-11-19 18:41:16 -08009251 _Py_END_SUPPRESS_IPH
Victor Stinnerdaf45552013-08-28 00:53:59 +02009252 Py_END_ALLOW_THREADS
9253
Victor Stinner8c62be82010-05-06 00:08:46 +00009254 if (!ok)
Victor Stinnerb024e842012-10-31 22:24:06 +01009255 return PyErr_SetFromWindowsErr(0);
Victor Stinnerdaf45552013-08-28 00:53:59 +02009256#else
9257
9258#ifdef HAVE_PIPE2
9259 Py_BEGIN_ALLOW_THREADS
9260 res = pipe2(fds, O_CLOEXEC);
9261 Py_END_ALLOW_THREADS
9262
9263 if (res != 0 && errno == ENOSYS)
9264 {
9265#endif
9266 Py_BEGIN_ALLOW_THREADS
9267 res = pipe(fds);
9268 Py_END_ALLOW_THREADS
9269
9270 if (res == 0) {
9271 if (_Py_set_inheritable(fds[0], 0, NULL) < 0) {
9272 close(fds[0]);
9273 close(fds[1]);
9274 return NULL;
9275 }
9276 if (_Py_set_inheritable(fds[1], 0, NULL) < 0) {
9277 close(fds[0]);
9278 close(fds[1]);
9279 return NULL;
9280 }
9281 }
9282#ifdef HAVE_PIPE2
9283 }
9284#endif
9285
9286 if (res != 0)
9287 return PyErr_SetFromErrno(PyExc_OSError);
9288#endif /* !MS_WINDOWS */
9289 return Py_BuildValue("(ii)", fds[0], fds[1]);
Guido van Rossum687dd131993-05-17 08:34:16 +00009290}
Guido van Rossuma4916fa1996-05-23 22:58:55 +00009291#endif /* HAVE_PIPE */
9292
Larry Hastings2f936352014-08-05 14:04:04 +10009293
Charles-François Natalidaafdd52011-05-29 20:07:40 +02009294#ifdef HAVE_PIPE2
Larry Hastings2f936352014-08-05 14:04:04 +10009295/*[clinic input]
9296os.pipe2
9297
9298 flags: int
9299 /
9300
9301Create a pipe with flags set atomically.
9302
9303Returns a tuple of two file descriptors:
9304 (read_fd, write_fd)
9305
9306flags can be constructed by ORing together one or more of these values:
9307O_NONBLOCK, O_CLOEXEC.
9308[clinic start generated code]*/
9309
Larry Hastings2f936352014-08-05 14:04:04 +10009310static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009311os_pipe2_impl(PyObject *module, int flags)
9312/*[clinic end generated code: output=25751fb43a45540f input=f261b6e7e63c6817]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009313{
Charles-François Natalidaafdd52011-05-29 20:07:40 +02009314 int fds[2];
9315 int res;
9316
Charles-François Natalidaafdd52011-05-29 20:07:40 +02009317 res = pipe2(fds, flags);
9318 if (res != 0)
9319 return posix_error();
9320 return Py_BuildValue("(ii)", fds[0], fds[1]);
9321}
9322#endif /* HAVE_PIPE2 */
9323
Larry Hastings2f936352014-08-05 14:04:04 +10009324
Ross Lagerwall7807c352011-03-17 20:20:30 +02009325#ifdef HAVE_WRITEV
Larry Hastings2f936352014-08-05 14:04:04 +10009326/*[clinic input]
9327os.writev -> Py_ssize_t
9328 fd: int
9329 buffers: object
9330 /
9331
9332Iterate over buffers, and write the contents of each to a file descriptor.
9333
9334Returns the total number of bytes written.
9335buffers must be a sequence of bytes-like objects.
9336[clinic start generated code]*/
9337
Larry Hastings2f936352014-08-05 14:04:04 +10009338static Py_ssize_t
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009339os_writev_impl(PyObject *module, int fd, PyObject *buffers)
9340/*[clinic end generated code: output=56565cfac3aac15b input=5b8d17fe4189d2fe]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009341{
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009342 Py_ssize_t cnt;
Larry Hastings2f936352014-08-05 14:04:04 +10009343 Py_ssize_t result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009344 int async_err = 0;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009345 struct iovec *iov;
9346 Py_buffer *buf;
Larry Hastings2f936352014-08-05 14:04:04 +10009347
9348 if (!PySequence_Check(buffers)) {
Ross Lagerwall7807c352011-03-17 20:20:30 +02009349 PyErr_SetString(PyExc_TypeError,
9350 "writev() arg 2 must be a sequence");
Larry Hastings2f936352014-08-05 14:04:04 +10009351 return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009352 }
Larry Hastings2f936352014-08-05 14:04:04 +10009353 cnt = PySequence_Size(buffers);
Serhiy Storchakabf623ae2017-04-19 20:03:52 +03009354 if (cnt < 0)
9355 return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009356
Larry Hastings2f936352014-08-05 14:04:04 +10009357 if (iov_setup(&iov, &buf, buffers, cnt, PyBUF_SIMPLE) < 0) {
9358 return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009359 }
9360
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009361 do {
9362 Py_BEGIN_ALLOW_THREADS
9363 result = writev(fd, iov, cnt);
9364 Py_END_ALLOW_THREADS
9365 } while (result < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Ross Lagerwall7807c352011-03-17 20:20:30 +02009366
9367 iov_cleanup(iov, buf, cnt);
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009368 if (result < 0 && !async_err)
Larry Hastings2f936352014-08-05 14:04:04 +10009369 posix_error();
Victor Stinner57ddf782014-01-08 15:21:28 +01009370
Georg Brandl306336b2012-06-24 12:55:33 +02009371 return result;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009372}
Larry Hastings2f936352014-08-05 14:04:04 +10009373#endif /* HAVE_WRITEV */
9374
9375
9376#ifdef HAVE_PWRITE
9377/*[clinic input]
9378os.pwrite -> Py_ssize_t
9379
9380 fd: int
9381 buffer: Py_buffer
9382 offset: Py_off_t
9383 /
9384
9385Write bytes to a file descriptor starting at a particular offset.
9386
9387Write buffer to fd, starting at offset bytes from the beginning of
9388the file. Returns the number of bytes writte. Does not change the
9389current file offset.
9390[clinic start generated code]*/
9391
Larry Hastings2f936352014-08-05 14:04:04 +10009392static Py_ssize_t
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009393os_pwrite_impl(PyObject *module, int fd, Py_buffer *buffer, Py_off_t offset)
9394/*[clinic end generated code: output=c74da630758ee925 input=19903f1b3dd26377]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009395{
9396 Py_ssize_t size;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009397 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10009398
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009399 do {
9400 Py_BEGIN_ALLOW_THREADS
Steve Dower8fc89802015-04-12 00:26:27 -04009401 _Py_BEGIN_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009402 size = pwrite(fd, buffer->buf, (size_t)buffer->len, offset);
Steve Dower8fc89802015-04-12 00:26:27 -04009403 _Py_END_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009404 Py_END_ALLOW_THREADS
9405 } while (size < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
Larry Hastings2f936352014-08-05 14:04:04 +10009406
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009407 if (size < 0 && !async_err)
Larry Hastings2f936352014-08-05 14:04:04 +10009408 posix_error();
9409 return size;
9410}
9411#endif /* HAVE_PWRITE */
9412
Pablo Galindo4defba32018-01-27 16:16:37 +00009413#if defined(HAVE_PWRITEV) || defined (HAVE_PWRITEV2)
9414/*[clinic input]
9415os.pwritev -> Py_ssize_t
9416
9417 fd: int
9418 buffers: object
9419 offset: Py_off_t
9420 flags: int = 0
9421 /
9422
9423Writes the contents of bytes-like objects to a file descriptor at a given offset.
9424
9425Combines the functionality of writev() and pwrite(). All buffers must be a sequence
9426of bytes-like objects. Buffers are processed in array order. Entire contents of first
9427buffer is written before proceeding to second, and so on. The operating system may
9428set a limit (sysconf() value SC_IOV_MAX) on the number of buffers that can be used.
9429This function writes the contents of each object to the file descriptor and returns
9430the total number of bytes written.
9431
9432The flags argument contains a bitwise OR of zero or more of the following flags:
9433
9434- RWF_DSYNC
9435- RWF_SYNC
9436
9437Using non-zero flags requires Linux 4.7 or newer.
9438[clinic start generated code]*/
9439
9440static Py_ssize_t
9441os_pwritev_impl(PyObject *module, int fd, PyObject *buffers, Py_off_t offset,
9442 int flags)
9443/*[clinic end generated code: output=e3dd3e9d11a6a5c7 input=803dc5ddbf0cfd3b]*/
9444{
9445 Py_ssize_t cnt;
9446 Py_ssize_t result;
9447 int async_err = 0;
9448 struct iovec *iov;
9449 Py_buffer *buf;
9450
9451 if (!PySequence_Check(buffers)) {
9452 PyErr_SetString(PyExc_TypeError,
9453 "pwritev() arg 2 must be a sequence");
9454 return -1;
9455 }
9456
9457 cnt = PySequence_Size(buffers);
9458 if (cnt < 0) {
9459 return -1;
9460 }
9461
9462#ifndef HAVE_PWRITEV2
9463 if(flags != 0) {
9464 argument_unavailable_error("pwritev2", "flags");
9465 return -1;
9466 }
9467#endif
9468
9469 if (iov_setup(&iov, &buf, buffers, cnt, PyBUF_SIMPLE) < 0) {
9470 return -1;
9471 }
9472#ifdef HAVE_PWRITEV2
9473 do {
9474 Py_BEGIN_ALLOW_THREADS
9475 _Py_BEGIN_SUPPRESS_IPH
9476 result = pwritev2(fd, iov, cnt, offset, flags);
9477 _Py_END_SUPPRESS_IPH
9478 Py_END_ALLOW_THREADS
9479 } while (result < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
9480#else
9481 do {
9482 Py_BEGIN_ALLOW_THREADS
9483 _Py_BEGIN_SUPPRESS_IPH
9484 result = pwritev(fd, iov, cnt, offset);
9485 _Py_END_SUPPRESS_IPH
9486 Py_END_ALLOW_THREADS
9487 } while (result < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
9488#endif
9489
9490 iov_cleanup(iov, buf, cnt);
9491 if (result < 0) {
9492 if (!async_err) {
9493 posix_error();
9494 }
9495 return -1;
9496 }
9497
9498 return result;
9499}
9500#endif /* HAVE_PWRITEV */
9501
Pablo Galindoaac4d032019-05-31 19:39:47 +01009502#ifdef HAVE_COPY_FILE_RANGE
9503/*[clinic input]
9504
9505os.copy_file_range
9506 src: int
9507 Source file descriptor.
9508 dst: int
9509 Destination file descriptor.
9510 count: Py_ssize_t
9511 Number of bytes to copy.
9512 offset_src: object = None
9513 Starting offset in src.
9514 offset_dst: object = None
9515 Starting offset in dst.
9516
9517Copy count bytes from one file descriptor to another.
9518
9519If offset_src is None, then src is read from the current position;
9520respectively for offset_dst.
9521[clinic start generated code]*/
9522
9523static PyObject *
9524os_copy_file_range_impl(PyObject *module, int src, int dst, Py_ssize_t count,
9525 PyObject *offset_src, PyObject *offset_dst)
9526/*[clinic end generated code: output=1a91713a1d99fc7a input=42fdce72681b25a9]*/
9527{
9528 off_t offset_src_val, offset_dst_val;
9529 off_t *p_offset_src = NULL;
9530 off_t *p_offset_dst = NULL;
9531 Py_ssize_t ret;
9532 int async_err = 0;
9533 /* The flags argument is provided to allow
9534 * for future extensions and currently must be to 0. */
9535 int flags = 0;
Pablo Galindo4defba32018-01-27 16:16:37 +00009536
9537
Pablo Galindoaac4d032019-05-31 19:39:47 +01009538 if (count < 0) {
9539 PyErr_SetString(PyExc_ValueError, "negative value for 'count' not allowed");
9540 return NULL;
9541 }
9542
9543 if (offset_src != Py_None) {
9544 if (!Py_off_t_converter(offset_src, &offset_src_val)) {
9545 return NULL;
9546 }
9547 p_offset_src = &offset_src_val;
9548 }
9549
9550 if (offset_dst != Py_None) {
9551 if (!Py_off_t_converter(offset_dst, &offset_dst_val)) {
9552 return NULL;
9553 }
9554 p_offset_dst = &offset_dst_val;
9555 }
9556
9557 do {
9558 Py_BEGIN_ALLOW_THREADS
9559 ret = copy_file_range(src, p_offset_src, dst, p_offset_dst, count, flags);
9560 Py_END_ALLOW_THREADS
9561 } while (ret < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
9562
9563 if (ret < 0) {
9564 return (!async_err) ? posix_error() : NULL;
9565 }
9566
9567 return PyLong_FromSsize_t(ret);
9568}
9569#endif /* HAVE_COPY_FILE_RANGE*/
Larry Hastings2f936352014-08-05 14:04:04 +10009570
9571#ifdef HAVE_MKFIFO
9572/*[clinic input]
9573os.mkfifo
9574
9575 path: path_t
9576 mode: int=0o666
9577 *
9578 dir_fd: dir_fd(requires='mkfifoat')=None
9579
9580Create a "fifo" (a POSIX named pipe).
9581
9582If dir_fd is not None, it should be a file descriptor open to a directory,
9583 and path should be relative; path will then be relative to that directory.
9584dir_fd may not be implemented on your platform.
9585 If it is unavailable, using it will raise a NotImplementedError.
9586[clinic start generated code]*/
9587
Larry Hastings2f936352014-08-05 14:04:04 +10009588static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009589os_mkfifo_impl(PyObject *module, path_t *path, int mode, int dir_fd)
9590/*[clinic end generated code: output=ce41cfad0e68c940 input=73032e98a36e0e19]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009591{
9592 int result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009593 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10009594
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009595 do {
9596 Py_BEGIN_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10009597#ifdef HAVE_MKFIFOAT
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009598 if (dir_fd != DEFAULT_DIR_FD)
9599 result = mkfifoat(dir_fd, path->narrow, mode);
9600 else
Ross Lagerwall7807c352011-03-17 20:20:30 +02009601#endif
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009602 result = mkfifo(path->narrow, mode);
9603 Py_END_ALLOW_THREADS
9604 } while (result != 0 && errno == EINTR &&
9605 !(async_err = PyErr_CheckSignals()));
9606 if (result != 0)
9607 return (!async_err) ? posix_error() : NULL;
Larry Hastings2f936352014-08-05 14:04:04 +10009608
9609 Py_RETURN_NONE;
9610}
9611#endif /* HAVE_MKFIFO */
9612
9613
9614#if defined(HAVE_MKNOD) && defined(HAVE_MAKEDEV)
9615/*[clinic input]
9616os.mknod
9617
9618 path: path_t
9619 mode: int=0o600
Serhiy Storchakaacdb7c12015-01-18 11:17:39 +02009620 device: dev_t=0
Larry Hastings2f936352014-08-05 14:04:04 +10009621 *
9622 dir_fd: dir_fd(requires='mknodat')=None
9623
9624Create a node in the file system.
9625
9626Create a node in the file system (file, device special file or named pipe)
9627at path. mode specifies both the permissions to use and the
9628type of node to be created, being combined (bitwise OR) with one of
9629S_IFREG, S_IFCHR, S_IFBLK, and S_IFIFO. If S_IFCHR or S_IFBLK is set on mode,
9630device defines the newly created device special file (probably using
9631os.makedev()). Otherwise device is ignored.
9632
9633If dir_fd is not None, it should be a file descriptor open to a directory,
9634 and path should be relative; path will then be relative to that directory.
9635dir_fd may not be implemented on your platform.
9636 If it is unavailable, using it will raise a NotImplementedError.
9637[clinic start generated code]*/
9638
Larry Hastings2f936352014-08-05 14:04:04 +10009639static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009640os_mknod_impl(PyObject *module, path_t *path, int mode, dev_t device,
Larry Hastings89964c42015-04-14 18:07:59 -04009641 int dir_fd)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009642/*[clinic end generated code: output=92e55d3ca8917461 input=ee44531551a4d83b]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009643{
9644 int result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009645 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10009646
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009647 do {
9648 Py_BEGIN_ALLOW_THREADS
Larry Hastings2f936352014-08-05 14:04:04 +10009649#ifdef HAVE_MKNODAT
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009650 if (dir_fd != DEFAULT_DIR_FD)
9651 result = mknodat(dir_fd, path->narrow, mode, device);
9652 else
Larry Hastings2f936352014-08-05 14:04:04 +10009653#endif
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009654 result = mknod(path->narrow, mode, device);
9655 Py_END_ALLOW_THREADS
9656 } while (result != 0 && errno == EINTR &&
9657 !(async_err = PyErr_CheckSignals()));
9658 if (result != 0)
9659 return (!async_err) ? posix_error() : NULL;
Larry Hastings2f936352014-08-05 14:04:04 +10009660
9661 Py_RETURN_NONE;
9662}
9663#endif /* defined(HAVE_MKNOD) && defined(HAVE_MAKEDEV) */
9664
9665
9666#ifdef HAVE_DEVICE_MACROS
9667/*[clinic input]
9668os.major -> unsigned_int
9669
Serhiy Storchakaacdb7c12015-01-18 11:17:39 +02009670 device: dev_t
Larry Hastings2f936352014-08-05 14:04:04 +10009671 /
9672
9673Extracts a device major number from a raw device number.
9674[clinic start generated code]*/
9675
Larry Hastings2f936352014-08-05 14:04:04 +10009676static unsigned int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009677os_major_impl(PyObject *module, dev_t device)
9678/*[clinic end generated code: output=5b3b2589bafb498e input=1e16a4d30c4d4462]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009679{
9680 return major(device);
9681}
9682
9683
9684/*[clinic input]
9685os.minor -> unsigned_int
9686
Serhiy Storchakaacdb7c12015-01-18 11:17:39 +02009687 device: dev_t
Larry Hastings2f936352014-08-05 14:04:04 +10009688 /
9689
9690Extracts a device minor number from a raw device number.
9691[clinic start generated code]*/
9692
Larry Hastings2f936352014-08-05 14:04:04 +10009693static unsigned int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009694os_minor_impl(PyObject *module, dev_t device)
9695/*[clinic end generated code: output=5e1a25e630b0157d input=0842c6d23f24c65e]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009696{
9697 return minor(device);
9698}
9699
9700
9701/*[clinic input]
Serhiy Storchakaacdb7c12015-01-18 11:17:39 +02009702os.makedev -> dev_t
Larry Hastings2f936352014-08-05 14:04:04 +10009703
9704 major: int
9705 minor: int
9706 /
9707
9708Composes a raw device number from the major and minor device numbers.
9709[clinic start generated code]*/
9710
Serhiy Storchakaacdb7c12015-01-18 11:17:39 +02009711static dev_t
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009712os_makedev_impl(PyObject *module, int major, int minor)
9713/*[clinic end generated code: output=881aaa4aba6f6a52 input=4b9fd8fc73cbe48f]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009714{
9715 return makedev(major, minor);
9716}
9717#endif /* HAVE_DEVICE_MACROS */
9718
9719
Steve Dowerfe0a41a2015-03-20 19:50:46 -07009720#if defined HAVE_FTRUNCATE || defined MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +10009721/*[clinic input]
9722os.ftruncate
9723
9724 fd: int
9725 length: Py_off_t
9726 /
9727
9728Truncate a file, specified by file descriptor, to a specific length.
9729[clinic start generated code]*/
9730
Larry Hastings2f936352014-08-05 14:04:04 +10009731static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009732os_ftruncate_impl(PyObject *module, int fd, Py_off_t length)
9733/*[clinic end generated code: output=fba15523721be7e4 input=63b43641e52818f2]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009734{
9735 int result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009736 int async_err = 0;
Larry Hastings2f936352014-08-05 14:04:04 +10009737
Steve Dowerb82e17e2019-05-23 08:45:22 -07009738 if (PySys_Audit("os.truncate", "in", fd, length) < 0) {
9739 return NULL;
9740 }
9741
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009742 do {
9743 Py_BEGIN_ALLOW_THREADS
Steve Dowera1c7e722015-04-12 00:26:43 -04009744 _Py_BEGIN_SUPPRESS_IPH
Steve Dowerfe0a41a2015-03-20 19:50:46 -07009745#ifdef MS_WINDOWS
9746 result = _chsize_s(fd, length);
9747#else
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009748 result = ftruncate(fd, length);
Steve Dowerfe0a41a2015-03-20 19:50:46 -07009749#endif
Steve Dowera1c7e722015-04-12 00:26:43 -04009750 _Py_END_SUPPRESS_IPH
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009751 Py_END_ALLOW_THREADS
9752 } while (result != 0 && errno == EINTR &&
9753 !(async_err = PyErr_CheckSignals()));
9754 if (result != 0)
9755 return (!async_err) ? posix_error() : NULL;
Larry Hastings2f936352014-08-05 14:04:04 +10009756 Py_RETURN_NONE;
9757}
Steve Dowerfe0a41a2015-03-20 19:50:46 -07009758#endif /* HAVE_FTRUNCATE || MS_WINDOWS */
Larry Hastings2f936352014-08-05 14:04:04 +10009759
9760
Steve Dowerfe0a41a2015-03-20 19:50:46 -07009761#if defined HAVE_TRUNCATE || defined MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +10009762/*[clinic input]
9763os.truncate
9764 path: path_t(allow_fd='PATH_HAVE_FTRUNCATE')
9765 length: Py_off_t
9766
9767Truncate a file, specified by path, to a specific length.
9768
9769On some platforms, path may also be specified as an open file descriptor.
9770 If this functionality is unavailable, using it raises an exception.
9771[clinic start generated code]*/
9772
Larry Hastings2f936352014-08-05 14:04:04 +10009773static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009774os_truncate_impl(PyObject *module, path_t *path, Py_off_t length)
9775/*[clinic end generated code: output=43009c8df5c0a12b input=77229cf0b50a9b77]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009776{
9777 int result;
Steve Dowerfe0a41a2015-03-20 19:50:46 -07009778#ifdef MS_WINDOWS
9779 int fd;
9780#endif
9781
9782 if (path->fd != -1)
9783 return os_ftruncate_impl(module, path->fd, length);
Larry Hastings2f936352014-08-05 14:04:04 +10009784
Steve Dowerb82e17e2019-05-23 08:45:22 -07009785 if (PySys_Audit("os.truncate", "On", path->object, length) < 0) {
9786 return NULL;
9787 }
9788
Larry Hastings2f936352014-08-05 14:04:04 +10009789 Py_BEGIN_ALLOW_THREADS
Steve Dowera1c7e722015-04-12 00:26:43 -04009790 _Py_BEGIN_SUPPRESS_IPH
Steve Dowerfe0a41a2015-03-20 19:50:46 -07009791#ifdef MS_WINDOWS
Steve Dowercc16be82016-09-08 10:35:16 -07009792 fd = _wopen(path->wide, _O_WRONLY | _O_BINARY | _O_NOINHERIT);
Victor Stinnercc0bbbc2015-04-25 00:21:52 +02009793 if (fd < 0)
Steve Dowerfe0a41a2015-03-20 19:50:46 -07009794 result = -1;
9795 else {
9796 result = _chsize_s(fd, length);
9797 close(fd);
9798 if (result < 0)
9799 errno = result;
9800 }
9801#else
9802 result = truncate(path->narrow, length);
Larry Hastings2f936352014-08-05 14:04:04 +10009803#endif
Steve Dowera1c7e722015-04-12 00:26:43 -04009804 _Py_END_SUPPRESS_IPH
Larry Hastings2f936352014-08-05 14:04:04 +10009805 Py_END_ALLOW_THREADS
9806 if (result < 0)
Alexey Izbyshev83460312018-10-20 03:28:22 +03009807 return posix_path_error(path);
Larry Hastings2f936352014-08-05 14:04:04 +10009808
9809 Py_RETURN_NONE;
9810}
Steve Dowerfe0a41a2015-03-20 19:50:46 -07009811#endif /* HAVE_TRUNCATE || MS_WINDOWS */
Larry Hastings2f936352014-08-05 14:04:04 +10009812
Ross Lagerwall7807c352011-03-17 20:20:30 +02009813
Victor Stinnerd6b17692014-09-30 12:20:05 +02009814/* Issue #22396: On 32-bit AIX platform, the prototypes of os.posix_fadvise()
9815 and os.posix_fallocate() in system headers are wrong if _LARGE_FILES is
9816 defined, which is the case in Python on AIX. AIX bug report:
9817 http://www-01.ibm.com/support/docview.wss?uid=isg1IV56170 */
9818#if defined(_AIX) && defined(_LARGE_FILES) && !defined(__64BIT__)
9819# define POSIX_FADVISE_AIX_BUG
9820#endif
9821
Victor Stinnerec39e262014-09-30 12:35:58 +02009822
Victor Stinnerd6b17692014-09-30 12:20:05 +02009823#if defined(HAVE_POSIX_FALLOCATE) && !defined(POSIX_FADVISE_AIX_BUG)
Larry Hastings2f936352014-08-05 14:04:04 +10009824/*[clinic input]
9825os.posix_fallocate
9826
9827 fd: int
9828 offset: Py_off_t
9829 length: Py_off_t
9830 /
9831
9832Ensure a file has allocated at least a particular number of bytes on disk.
9833
9834Ensure that the file specified by fd encompasses a range of bytes
9835starting at offset bytes from the beginning and continuing for length bytes.
9836[clinic start generated code]*/
9837
Larry Hastings2f936352014-08-05 14:04:04 +10009838static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009839os_posix_fallocate_impl(PyObject *module, int fd, Py_off_t offset,
Larry Hastings89964c42015-04-14 18:07:59 -04009840 Py_off_t length)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009841/*[clinic end generated code: output=73f107139564aa9d input=d7a2ef0ab2ca52fb]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009842{
9843 int result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009844 int async_err = 0;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009845
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009846 do {
9847 Py_BEGIN_ALLOW_THREADS
9848 result = posix_fallocate(fd, offset, length);
9849 Py_END_ALLOW_THREADS
Коренберг Маркd4b93e22017-08-14 18:55:16 +05009850 } while (result == EINTR && !(async_err = PyErr_CheckSignals()));
9851
9852 if (result == 0)
9853 Py_RETURN_NONE;
9854
9855 if (async_err)
9856 return NULL;
9857
9858 errno = result;
9859 return posix_error();
Ross Lagerwall7807c352011-03-17 20:20:30 +02009860}
Victor Stinnerec39e262014-09-30 12:35:58 +02009861#endif /* HAVE_POSIX_FALLOCATE) && !POSIX_FADVISE_AIX_BUG */
Larry Hastings2f936352014-08-05 14:04:04 +10009862
Ross Lagerwall7807c352011-03-17 20:20:30 +02009863
Victor Stinnerd6b17692014-09-30 12:20:05 +02009864#if defined(HAVE_POSIX_FADVISE) && !defined(POSIX_FADVISE_AIX_BUG)
Larry Hastings2f936352014-08-05 14:04:04 +10009865/*[clinic input]
9866os.posix_fadvise
9867
9868 fd: int
9869 offset: Py_off_t
9870 length: Py_off_t
9871 advice: int
9872 /
9873
9874Announce an intention to access data in a specific pattern.
9875
9876Announce an intention to access data in a specific pattern, thus allowing
9877the kernel to make optimizations.
9878The advice applies to the region of the file specified by fd starting at
9879offset and continuing for length bytes.
9880advice is one of POSIX_FADV_NORMAL, POSIX_FADV_SEQUENTIAL,
9881POSIX_FADV_RANDOM, POSIX_FADV_NOREUSE, POSIX_FADV_WILLNEED, or
9882POSIX_FADV_DONTNEED.
9883[clinic start generated code]*/
9884
Larry Hastings2f936352014-08-05 14:04:04 +10009885static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009886os_posix_fadvise_impl(PyObject *module, int fd, Py_off_t offset,
Larry Hastings89964c42015-04-14 18:07:59 -04009887 Py_off_t length, int advice)
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009888/*[clinic end generated code: output=412ef4aa70c98642 input=0fbe554edc2f04b5]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009889{
9890 int result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009891 int async_err = 0;
Ross Lagerwall7807c352011-03-17 20:20:30 +02009892
Charles-François Natali6e6c59b2015-02-07 13:27:50 +00009893 do {
9894 Py_BEGIN_ALLOW_THREADS
9895 result = posix_fadvise(fd, offset, length, advice);
9896 Py_END_ALLOW_THREADS
Коренберг Маркd4b93e22017-08-14 18:55:16 +05009897 } while (result == EINTR && !(async_err = PyErr_CheckSignals()));
9898
9899 if (result == 0)
9900 Py_RETURN_NONE;
9901
9902 if (async_err)
9903 return NULL;
9904
9905 errno = result;
9906 return posix_error();
Ross Lagerwall7807c352011-03-17 20:20:30 +02009907}
Victor Stinnerec39e262014-09-30 12:35:58 +02009908#endif /* HAVE_POSIX_FADVISE && !POSIX_FADVISE_AIX_BUG */
Ross Lagerwall7807c352011-03-17 20:20:30 +02009909
Guido van Rossumf1af3fe1996-07-23 19:18:10 +00009910#ifdef HAVE_PUTENV
Guido van Rossumec4f4ac1997-06-02 22:20:51 +00009911
Fred Drake762e2061999-08-26 17:23:54 +00009912/* Save putenv() parameters as values here, so we can collect them when they
9913 * get re-set with another call for the same key. */
9914static PyObject *posix_putenv_garbage;
9915
Larry Hastings2f936352014-08-05 14:04:04 +10009916static void
9917posix_putenv_garbage_setitem(PyObject *name, PyObject *value)
Guido van Rossumf1af3fe1996-07-23 19:18:10 +00009918{
Larry Hastings2f936352014-08-05 14:04:04 +10009919 /* Install the first arg and newstr in posix_putenv_garbage;
9920 * this will cause previous value to be collected. This has to
9921 * happen after the real putenv() call because the old value
9922 * was still accessible until then. */
9923 if (PyDict_SetItem(posix_putenv_garbage, name, value))
9924 /* really not much we can do; just leak */
9925 PyErr_Clear();
9926 else
9927 Py_DECREF(value);
9928}
9929
9930
Thomas Hellerf78f12a2007-11-08 19:33:05 +00009931#ifdef MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +10009932/*[clinic input]
9933os.putenv
9934
9935 name: unicode
9936 value: unicode
9937 /
9938
9939Change or add an environment variable.
9940[clinic start generated code]*/
9941
Larry Hastings2f936352014-08-05 14:04:04 +10009942static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03009943os_putenv_impl(PyObject *module, PyObject *name, PyObject *value)
9944/*[clinic end generated code: output=d29a567d6b2327d2 input=ba586581c2e6105f]*/
Larry Hastings2f936352014-08-05 14:04:04 +10009945{
Serhiy Storchakadeab18d2016-05-07 16:45:18 +03009946 const wchar_t *env;
Serhiy Storchakaf7eae0a2017-06-28 08:30:06 +03009947 Py_ssize_t size;
Larry Hastings2f936352014-08-05 14:04:04 +10009948
Serhiy Storchaka77703942017-06-25 07:33:01 +03009949 /* Search from index 1 because on Windows starting '=' is allowed for
9950 defining hidden environment variables. */
9951 if (PyUnicode_GET_LENGTH(name) == 0 ||
9952 PyUnicode_FindChar(name, '=', 1, PyUnicode_GET_LENGTH(name), 1) != -1)
9953 {
9954 PyErr_SetString(PyExc_ValueError, "illegal environment variable name");
9955 return NULL;
9956 }
Larry Hastings2f936352014-08-05 14:04:04 +10009957 PyObject *unicode = PyUnicode_FromFormat("%U=%U", name, value);
9958 if (unicode == NULL) {
Larry Hastings2f936352014-08-05 14:04:04 +10009959 return NULL;
Victor Stinner84ae1182010-05-06 22:05:07 +00009960 }
Serhiy Storchakaf7eae0a2017-06-28 08:30:06 +03009961
9962 env = PyUnicode_AsUnicodeAndSize(unicode, &size);
9963 if (env == NULL)
9964 goto error;
9965 if (size > _MAX_ENV) {
Victor Stinner65170952011-11-22 22:16:17 +01009966 PyErr_Format(PyExc_ValueError,
9967 "the environment variable is longer than %u characters",
9968 _MAX_ENV);
9969 goto error;
9970 }
Serhiy Storchakaf7eae0a2017-06-28 08:30:06 +03009971 if (wcslen(env) != (size_t)size) {
9972 PyErr_SetString(PyExc_ValueError, "embedded null character");
Victor Stinnereb5657a2011-09-30 01:44:27 +02009973 goto error;
Serhiy Storchakaf7eae0a2017-06-28 08:30:06 +03009974 }
9975
Larry Hastings2f936352014-08-05 14:04:04 +10009976 if (_wputenv(env)) {
Victor Stinner8c62be82010-05-06 00:08:46 +00009977 posix_error();
Victor Stinner84ae1182010-05-06 22:05:07 +00009978 goto error;
Victor Stinner8c62be82010-05-06 00:08:46 +00009979 }
Guido van Rossumf1af3fe1996-07-23 19:18:10 +00009980
Larry Hastings2f936352014-08-05 14:04:04 +10009981 posix_putenv_garbage_setitem(name, unicode);
Victor Stinner84ae1182010-05-06 22:05:07 +00009982 Py_RETURN_NONE;
9983
9984error:
Larry Hastings2f936352014-08-05 14:04:04 +10009985 Py_DECREF(unicode);
Victor Stinner84ae1182010-05-06 22:05:07 +00009986 return NULL;
Guido van Rossumf1af3fe1996-07-23 19:18:10 +00009987}
Larry Hastings2f936352014-08-05 14:04:04 +10009988#else /* MS_WINDOWS */
9989/*[clinic input]
9990os.putenv
Guido van Rossumb6a47161997-09-15 22:54:34 +00009991
Larry Hastings2f936352014-08-05 14:04:04 +10009992 name: FSConverter
9993 value: FSConverter
9994 /
9995
9996Change or add an environment variable.
9997[clinic start generated code]*/
9998
Larry Hastings2f936352014-08-05 14:04:04 +10009999static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010000os_putenv_impl(PyObject *module, PyObject *name, PyObject *value)
10001/*[clinic end generated code: output=d29a567d6b2327d2 input=a97bc6152f688d31]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010002{
10003 PyObject *bytes = NULL;
10004 char *env;
Serhiy Storchaka77703942017-06-25 07:33:01 +030010005 const char *name_string = PyBytes_AS_STRING(name);
10006 const char *value_string = PyBytes_AS_STRING(value);
Larry Hastings2f936352014-08-05 14:04:04 +100010007
Serhiy Storchaka77703942017-06-25 07:33:01 +030010008 if (strchr(name_string, '=') != NULL) {
10009 PyErr_SetString(PyExc_ValueError, "illegal environment variable name");
10010 return NULL;
10011 }
Larry Hastings2f936352014-08-05 14:04:04 +100010012 bytes = PyBytes_FromFormat("%s=%s", name_string, value_string);
10013 if (bytes == NULL) {
Larry Hastings2f936352014-08-05 14:04:04 +100010014 return NULL;
10015 }
10016
10017 env = PyBytes_AS_STRING(bytes);
10018 if (putenv(env)) {
10019 Py_DECREF(bytes);
10020 return posix_error();
10021 }
10022
10023 posix_putenv_garbage_setitem(name, bytes);
10024 Py_RETURN_NONE;
10025}
10026#endif /* MS_WINDOWS */
10027#endif /* HAVE_PUTENV */
10028
10029
10030#ifdef HAVE_UNSETENV
10031/*[clinic input]
10032os.unsetenv
10033 name: FSConverter
10034 /
10035
10036Delete an environment variable.
10037[clinic start generated code]*/
10038
Larry Hastings2f936352014-08-05 14:04:04 +100010039static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010040os_unsetenv_impl(PyObject *module, PyObject *name)
10041/*[clinic end generated code: output=54c4137ab1834f02 input=2bb5288a599c7107]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010042{
Victor Stinner984890f2011-11-24 13:53:38 +010010043#ifndef HAVE_BROKEN_UNSETENV
Victor Stinner60b385e2011-11-22 22:01:28 +010010044 int err;
Victor Stinner984890f2011-11-24 13:53:38 +010010045#endif
Victor Stinner84ae1182010-05-06 22:05:07 +000010046
Victor Stinner984890f2011-11-24 13:53:38 +010010047#ifdef HAVE_BROKEN_UNSETENV
10048 unsetenv(PyBytes_AS_STRING(name));
10049#else
Victor Stinner65170952011-11-22 22:16:17 +010010050 err = unsetenv(PyBytes_AS_STRING(name));
Larry Hastings2f936352014-08-05 14:04:04 +100010051 if (err)
Victor Stinner60b385e2011-11-22 22:01:28 +010010052 return posix_error();
Victor Stinner984890f2011-11-24 13:53:38 +010010053#endif
Guido van Rossumc524d952001-10-19 01:31:59 +000010054
Victor Stinner8c62be82010-05-06 00:08:46 +000010055 /* Remove the key from posix_putenv_garbage;
10056 * this will cause it to be collected. This has to
10057 * happen after the real unsetenv() call because the
10058 * old value was still accessible until then.
10059 */
Victor Stinner65170952011-11-22 22:16:17 +010010060 if (PyDict_DelItem(posix_putenv_garbage, name)) {
Victor Stinner8c62be82010-05-06 00:08:46 +000010061 /* really not much we can do; just leak */
Serhiy Storchakaa24107b2019-02-25 17:59:46 +020010062 if (!PyErr_ExceptionMatches(PyExc_KeyError)) {
10063 return NULL;
10064 }
Victor Stinner8c62be82010-05-06 00:08:46 +000010065 PyErr_Clear();
10066 }
Victor Stinner84ae1182010-05-06 22:05:07 +000010067 Py_RETURN_NONE;
Guido van Rossumc524d952001-10-19 01:31:59 +000010068}
Larry Hastings2f936352014-08-05 14:04:04 +100010069#endif /* HAVE_UNSETENV */
Guido van Rossumc524d952001-10-19 01:31:59 +000010070
Larry Hastings2f936352014-08-05 14:04:04 +100010071
10072/*[clinic input]
10073os.strerror
10074
10075 code: int
10076 /
10077
10078Translate an error code to a message string.
10079[clinic start generated code]*/
10080
Larry Hastings2f936352014-08-05 14:04:04 +100010081static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010082os_strerror_impl(PyObject *module, int code)
10083/*[clinic end generated code: output=baebf09fa02a78f2 input=75a8673d97915a91]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010084{
10085 char *message = strerror(code);
Victor Stinner8c62be82010-05-06 00:08:46 +000010086 if (message == NULL) {
10087 PyErr_SetString(PyExc_ValueError,
10088 "strerror() argument out of range");
10089 return NULL;
10090 }
Victor Stinner1b579672011-12-17 05:47:23 +010010091 return PyUnicode_DecodeLocale(message, "surrogateescape");
Guido van Rossumb6a47161997-09-15 22:54:34 +000010092}
Guido van Rossumb6a47161997-09-15 22:54:34 +000010093
Guido van Rossumf1af3fe1996-07-23 19:18:10 +000010094
Guido van Rossumc9641791998-08-04 15:26:23 +000010095#ifdef HAVE_SYS_WAIT_H
Fred Drake106c1a02002-04-23 15:58:02 +000010096#ifdef WCOREDUMP
Larry Hastings2f936352014-08-05 14:04:04 +100010097/*[clinic input]
10098os.WCOREDUMP -> bool
10099
10100 status: int
10101 /
10102
10103Return True if the process returning status was dumped to a core file.
10104[clinic start generated code]*/
10105
Larry Hastings2f936352014-08-05 14:04:04 +100010106static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010107os_WCOREDUMP_impl(PyObject *module, int status)
10108/*[clinic end generated code: output=1a584b147b16bd18 input=8b05e7ab38528d04]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010109{
10110 WAIT_TYPE wait_status;
10111 WAIT_STATUS_INT(wait_status) = status;
10112 return WCOREDUMP(wait_status);
Fred Drake106c1a02002-04-23 15:58:02 +000010113}
10114#endif /* WCOREDUMP */
10115
Larry Hastings2f936352014-08-05 14:04:04 +100010116
Fred Drake106c1a02002-04-23 15:58:02 +000010117#ifdef WIFCONTINUED
Larry Hastings2f936352014-08-05 14:04:04 +100010118/*[clinic input]
10119os.WIFCONTINUED -> bool
10120
10121 status: int
10122
10123Return True if a particular process was continued from a job control stop.
10124
10125Return True if the process returning status was continued from a
10126job control stop.
10127[clinic start generated code]*/
10128
Larry Hastings2f936352014-08-05 14:04:04 +100010129static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010130os_WIFCONTINUED_impl(PyObject *module, int status)
10131/*[clinic end generated code: output=1e35295d844364bd input=e777e7d38eb25bd9]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010132{
10133 WAIT_TYPE wait_status;
10134 WAIT_STATUS_INT(wait_status) = status;
10135 return WIFCONTINUED(wait_status);
Fred Drake106c1a02002-04-23 15:58:02 +000010136}
10137#endif /* WIFCONTINUED */
10138
Larry Hastings2f936352014-08-05 14:04:04 +100010139
Guido van Rossumc9641791998-08-04 15:26:23 +000010140#ifdef WIFSTOPPED
Larry Hastings2f936352014-08-05 14:04:04 +100010141/*[clinic input]
10142os.WIFSTOPPED -> bool
10143
10144 status: int
10145
10146Return True if the process returning status was stopped.
10147[clinic start generated code]*/
10148
Larry Hastings2f936352014-08-05 14:04:04 +100010149static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010150os_WIFSTOPPED_impl(PyObject *module, int status)
10151/*[clinic end generated code: output=fdb57122a5c9b4cb input=043cb7f1289ef904]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010152{
10153 WAIT_TYPE wait_status;
10154 WAIT_STATUS_INT(wait_status) = status;
10155 return WIFSTOPPED(wait_status);
Guido van Rossumc9641791998-08-04 15:26:23 +000010156}
10157#endif /* WIFSTOPPED */
10158
Larry Hastings2f936352014-08-05 14:04:04 +100010159
Guido van Rossumc9641791998-08-04 15:26:23 +000010160#ifdef WIFSIGNALED
Larry Hastings2f936352014-08-05 14:04:04 +100010161/*[clinic input]
10162os.WIFSIGNALED -> bool
10163
10164 status: int
10165
10166Return True if the process returning status was terminated by a signal.
10167[clinic start generated code]*/
10168
Larry Hastings2f936352014-08-05 14:04:04 +100010169static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010170os_WIFSIGNALED_impl(PyObject *module, int status)
10171/*[clinic end generated code: output=d1dde4dcc819a5f5 input=d55ba7cc9ce5dc43]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010172{
10173 WAIT_TYPE wait_status;
10174 WAIT_STATUS_INT(wait_status) = status;
10175 return WIFSIGNALED(wait_status);
Guido van Rossumc9641791998-08-04 15:26:23 +000010176}
10177#endif /* WIFSIGNALED */
10178
Larry Hastings2f936352014-08-05 14:04:04 +100010179
Guido van Rossumc9641791998-08-04 15:26:23 +000010180#ifdef WIFEXITED
Larry Hastings2f936352014-08-05 14:04:04 +100010181/*[clinic input]
10182os.WIFEXITED -> bool
10183
10184 status: int
10185
10186Return True if the process returning status exited via the exit() system call.
10187[clinic start generated code]*/
10188
Larry Hastings2f936352014-08-05 14:04:04 +100010189static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010190os_WIFEXITED_impl(PyObject *module, int status)
10191/*[clinic end generated code: output=01c09d6ebfeea397 input=d63775a6791586c0]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010192{
10193 WAIT_TYPE wait_status;
10194 WAIT_STATUS_INT(wait_status) = status;
10195 return WIFEXITED(wait_status);
Guido van Rossumc9641791998-08-04 15:26:23 +000010196}
10197#endif /* WIFEXITED */
10198
Larry Hastings2f936352014-08-05 14:04:04 +100010199
Guido van Rossum54ecc3d1999-01-27 17:53:11 +000010200#ifdef WEXITSTATUS
Larry Hastings2f936352014-08-05 14:04:04 +100010201/*[clinic input]
10202os.WEXITSTATUS -> int
10203
10204 status: int
10205
10206Return the process return code from status.
10207[clinic start generated code]*/
10208
Larry Hastings2f936352014-08-05 14:04:04 +100010209static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010210os_WEXITSTATUS_impl(PyObject *module, int status)
10211/*[clinic end generated code: output=6e3efbba11f6488d input=e1fb4944e377585b]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010212{
10213 WAIT_TYPE wait_status;
10214 WAIT_STATUS_INT(wait_status) = status;
10215 return WEXITSTATUS(wait_status);
Guido van Rossumc9641791998-08-04 15:26:23 +000010216}
10217#endif /* WEXITSTATUS */
10218
Larry Hastings2f936352014-08-05 14:04:04 +100010219
Guido van Rossumc9641791998-08-04 15:26:23 +000010220#ifdef WTERMSIG
Larry Hastings2f936352014-08-05 14:04:04 +100010221/*[clinic input]
10222os.WTERMSIG -> int
10223
10224 status: int
10225
10226Return the signal that terminated the process that provided the status value.
10227[clinic start generated code]*/
10228
Larry Hastings2f936352014-08-05 14:04:04 +100010229static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010230os_WTERMSIG_impl(PyObject *module, int status)
10231/*[clinic end generated code: output=172f7dfc8dcfc3ad input=727fd7f84ec3f243]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010232{
10233 WAIT_TYPE wait_status;
10234 WAIT_STATUS_INT(wait_status) = status;
10235 return WTERMSIG(wait_status);
Guido van Rossumc9641791998-08-04 15:26:23 +000010236}
10237#endif /* WTERMSIG */
10238
Larry Hastings2f936352014-08-05 14:04:04 +100010239
Guido van Rossumc9641791998-08-04 15:26:23 +000010240#ifdef WSTOPSIG
Larry Hastings2f936352014-08-05 14:04:04 +100010241/*[clinic input]
10242os.WSTOPSIG -> int
10243
10244 status: int
10245
10246Return the signal that stopped the process that provided the status value.
10247[clinic start generated code]*/
10248
Larry Hastings2f936352014-08-05 14:04:04 +100010249static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010250os_WSTOPSIG_impl(PyObject *module, int status)
10251/*[clinic end generated code: output=0ab7586396f5d82b input=46ebf1d1b293c5c1]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010252{
10253 WAIT_TYPE wait_status;
10254 WAIT_STATUS_INT(wait_status) = status;
10255 return WSTOPSIG(wait_status);
Guido van Rossumc9641791998-08-04 15:26:23 +000010256}
10257#endif /* WSTOPSIG */
Guido van Rossumc9641791998-08-04 15:26:23 +000010258#endif /* HAVE_SYS_WAIT_H */
10259
10260
Thomas Wouters477c8d52006-05-27 19:21:47 +000010261#if defined(HAVE_FSTATVFS) && defined(HAVE_SYS_STATVFS_H)
Guido van Rossumd5753e11999-10-19 13:29:23 +000010262#ifdef _SCO_DS
10263/* SCO OpenServer 5.0 and later requires _SVID3 before it reveals the
10264 needed definitions in sys/statvfs.h */
10265#define _SVID3
10266#endif
Guido van Rossum94f6f721999-01-06 18:42:14 +000010267#include <sys/statvfs.h>
10268
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010269static PyObject*
10270_pystatvfs_fromstructstatvfs(struct statvfs st) {
Eddie Elizondo474eedf2018-11-13 04:09:31 -080010271 PyObject *v = PyStructSequence_New(StatVFSResultType);
Victor Stinner8c62be82010-05-06 00:08:46 +000010272 if (v == NULL)
10273 return NULL;
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010274
10275#if !defined(HAVE_LARGEFILE_SUPPORT)
Victor Stinner8c62be82010-05-06 00:08:46 +000010276 PyStructSequence_SET_ITEM(v, 0, PyLong_FromLong((long) st.f_bsize));
10277 PyStructSequence_SET_ITEM(v, 1, PyLong_FromLong((long) st.f_frsize));
10278 PyStructSequence_SET_ITEM(v, 2, PyLong_FromLong((long) st.f_blocks));
10279 PyStructSequence_SET_ITEM(v, 3, PyLong_FromLong((long) st.f_bfree));
10280 PyStructSequence_SET_ITEM(v, 4, PyLong_FromLong((long) st.f_bavail));
10281 PyStructSequence_SET_ITEM(v, 5, PyLong_FromLong((long) st.f_files));
10282 PyStructSequence_SET_ITEM(v, 6, PyLong_FromLong((long) st.f_ffree));
10283 PyStructSequence_SET_ITEM(v, 7, PyLong_FromLong((long) st.f_favail));
10284 PyStructSequence_SET_ITEM(v, 8, PyLong_FromLong((long) st.f_flag));
10285 PyStructSequence_SET_ITEM(v, 9, PyLong_FromLong((long) st.f_namemax));
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010286#else
Victor Stinner8c62be82010-05-06 00:08:46 +000010287 PyStructSequence_SET_ITEM(v, 0, PyLong_FromLong((long) st.f_bsize));
10288 PyStructSequence_SET_ITEM(v, 1, PyLong_FromLong((long) st.f_frsize));
10289 PyStructSequence_SET_ITEM(v, 2,
Benjamin Petersonaf580df2016-09-06 10:46:49 -070010290 PyLong_FromLongLong((long long) st.f_blocks));
Victor Stinner8c62be82010-05-06 00:08:46 +000010291 PyStructSequence_SET_ITEM(v, 3,
Benjamin Petersonaf580df2016-09-06 10:46:49 -070010292 PyLong_FromLongLong((long long) st.f_bfree));
Victor Stinner8c62be82010-05-06 00:08:46 +000010293 PyStructSequence_SET_ITEM(v, 4,
Benjamin Petersonaf580df2016-09-06 10:46:49 -070010294 PyLong_FromLongLong((long long) st.f_bavail));
Victor Stinner8c62be82010-05-06 00:08:46 +000010295 PyStructSequence_SET_ITEM(v, 5,
Benjamin Petersonaf580df2016-09-06 10:46:49 -070010296 PyLong_FromLongLong((long long) st.f_files));
Victor Stinner8c62be82010-05-06 00:08:46 +000010297 PyStructSequence_SET_ITEM(v, 6,
Benjamin Petersonaf580df2016-09-06 10:46:49 -070010298 PyLong_FromLongLong((long long) st.f_ffree));
Victor Stinner8c62be82010-05-06 00:08:46 +000010299 PyStructSequence_SET_ITEM(v, 7,
Benjamin Petersonaf580df2016-09-06 10:46:49 -070010300 PyLong_FromLongLong((long long) st.f_favail));
Victor Stinner8c62be82010-05-06 00:08:46 +000010301 PyStructSequence_SET_ITEM(v, 8, PyLong_FromLong((long) st.f_flag));
10302 PyStructSequence_SET_ITEM(v, 9, PyLong_FromLong((long) st.f_namemax));
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010303#endif
Michael Felt502d5512018-01-05 13:01:58 +010010304/* The _ALL_SOURCE feature test macro defines f_fsid as a structure
10305 * (issue #32390). */
10306#if defined(_AIX) && defined(_ALL_SOURCE)
10307 PyStructSequence_SET_ITEM(v, 10, PyLong_FromUnsignedLong(st.f_fsid.val[0]));
10308#else
Giuseppe Scrivano96a5e502017-12-14 23:46:46 +010010309 PyStructSequence_SET_ITEM(v, 10, PyLong_FromUnsignedLong(st.f_fsid));
Michael Felt502d5512018-01-05 13:01:58 +010010310#endif
Victor Stinnerf0a7bac2013-10-30 18:55:24 +010010311 if (PyErr_Occurred()) {
10312 Py_DECREF(v);
10313 return NULL;
10314 }
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010315
Victor Stinner8c62be82010-05-06 00:08:46 +000010316 return v;
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010317}
10318
Larry Hastings2f936352014-08-05 14:04:04 +100010319
10320/*[clinic input]
10321os.fstatvfs
10322 fd: int
10323 /
10324
10325Perform an fstatvfs system call on the given fd.
10326
10327Equivalent to statvfs(fd).
10328[clinic start generated code]*/
10329
Larry Hastings2f936352014-08-05 14:04:04 +100010330static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010331os_fstatvfs_impl(PyObject *module, int fd)
10332/*[clinic end generated code: output=53547cf0cc55e6c5 input=d8122243ac50975e]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010333{
10334 int result;
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010335 int async_err = 0;
Victor Stinner8c62be82010-05-06 00:08:46 +000010336 struct statvfs st;
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010337
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010338 do {
10339 Py_BEGIN_ALLOW_THREADS
10340 result = fstatvfs(fd, &st);
10341 Py_END_ALLOW_THREADS
10342 } while (result != 0 && errno == EINTR &&
10343 !(async_err = PyErr_CheckSignals()));
Larry Hastings2f936352014-08-05 14:04:04 +100010344 if (result != 0)
Charles-François Natali6e6c59b2015-02-07 13:27:50 +000010345 return (!async_err) ? posix_error() : NULL;
Guido van Rossum98bf58f2001-10-18 20:34:25 +000010346
Victor Stinner8c62be82010-05-06 00:08:46 +000010347 return _pystatvfs_fromstructstatvfs(st);
Guido van Rossum94f6f721999-01-06 18:42:14 +000010348}
Larry Hastings2f936352014-08-05 14:04:04 +100010349#endif /* defined(HAVE_FSTATVFS) && defined(HAVE_SYS_STATVFS_H) */
Guido van Rossum94f6f721999-01-06 18:42:14 +000010350
10351
Thomas Wouters477c8d52006-05-27 19:21:47 +000010352#if defined(HAVE_STATVFS) && defined(HAVE_SYS_STATVFS_H)
Guido van Rossum94f6f721999-01-06 18:42:14 +000010353#include <sys/statvfs.h>
Larry Hastings2f936352014-08-05 14:04:04 +100010354/*[clinic input]
10355os.statvfs
Guido van Rossum94f6f721999-01-06 18:42:14 +000010356
Larry Hastings2f936352014-08-05 14:04:04 +100010357 path: path_t(allow_fd='PATH_HAVE_FSTATVFS')
10358
10359Perform a statvfs system call on the given path.
10360
10361path may always be specified as a string.
10362On some platforms, path may also be specified as an open file descriptor.
10363 If this functionality is unavailable, using it raises an exception.
10364[clinic start generated code]*/
10365
Larry Hastings2f936352014-08-05 14:04:04 +100010366static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010367os_statvfs_impl(PyObject *module, path_t *path)
10368/*[clinic end generated code: output=87106dd1beb8556e input=3f5c35791c669bd9]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010369{
10370 int result;
10371 struct statvfs st;
Larry Hastings9cf065c2012-06-22 16:30:09 -070010372
10373 Py_BEGIN_ALLOW_THREADS
10374#ifdef HAVE_FSTATVFS
Larry Hastings2f936352014-08-05 14:04:04 +100010375 if (path->fd != -1) {
Larry Hastings9cf065c2012-06-22 16:30:09 -070010376#ifdef __APPLE__
10377 /* handle weak-linking on Mac OS X 10.3 */
10378 if (fstatvfs == NULL) {
Larry Hastings2f936352014-08-05 14:04:04 +100010379 fd_specified("statvfs", path->fd);
10380 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -070010381 }
10382#endif
Larry Hastings2f936352014-08-05 14:04:04 +100010383 result = fstatvfs(path->fd, &st);
Larry Hastings9cf065c2012-06-22 16:30:09 -070010384 }
10385 else
10386#endif
Larry Hastings2f936352014-08-05 14:04:04 +100010387 result = statvfs(path->narrow, &st);
Larry Hastings9cf065c2012-06-22 16:30:09 -070010388 Py_END_ALLOW_THREADS
10389
10390 if (result) {
Larry Hastings2f936352014-08-05 14:04:04 +100010391 return path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -070010392 }
10393
Larry Hastings2f936352014-08-05 14:04:04 +100010394 return _pystatvfs_fromstructstatvfs(st);
Guido van Rossum94f6f721999-01-06 18:42:14 +000010395}
Larry Hastings2f936352014-08-05 14:04:04 +100010396#endif /* defined(HAVE_STATVFS) && defined(HAVE_SYS_STATVFS_H) */
10397
Guido van Rossum94f6f721999-01-06 18:42:14 +000010398
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010399#ifdef MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +100010400/*[clinic input]
10401os._getdiskusage
10402
Steve Dower23ad6d02018-02-22 10:39:10 -080010403 path: path_t
Larry Hastings2f936352014-08-05 14:04:04 +100010404
10405Return disk usage statistics about the given path as a (total, free) tuple.
10406[clinic start generated code]*/
10407
Larry Hastings2f936352014-08-05 14:04:04 +100010408static PyObject *
Steve Dower23ad6d02018-02-22 10:39:10 -080010409os__getdiskusage_impl(PyObject *module, path_t *path)
10410/*[clinic end generated code: output=3bd3991f5e5c5dfb input=6af8d1b7781cc042]*/
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010411{
10412 BOOL retval;
10413 ULARGE_INTEGER _, total, free;
Joe Pamerc8c02492018-09-25 10:57:36 -040010414 DWORD err = 0;
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010415
10416 Py_BEGIN_ALLOW_THREADS
Steve Dower23ad6d02018-02-22 10:39:10 -080010417 retval = GetDiskFreeSpaceExW(path->wide, &_, &total, &free);
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010418 Py_END_ALLOW_THREADS
Joe Pamerc8c02492018-09-25 10:57:36 -040010419 if (retval == 0) {
10420 if (GetLastError() == ERROR_DIRECTORY) {
10421 wchar_t *dir_path = NULL;
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010422
Joe Pamerc8c02492018-09-25 10:57:36 -040010423 dir_path = PyMem_New(wchar_t, path->length + 1);
10424 if (dir_path == NULL) {
10425 return PyErr_NoMemory();
10426 }
10427
10428 wcscpy_s(dir_path, path->length + 1, path->wide);
10429
10430 if (_dirnameW(dir_path) != -1) {
10431 Py_BEGIN_ALLOW_THREADS
10432 retval = GetDiskFreeSpaceExW(dir_path, &_, &total, &free);
10433 Py_END_ALLOW_THREADS
10434 }
10435 /* Record the last error in case it's modified by PyMem_Free. */
10436 err = GetLastError();
10437 PyMem_Free(dir_path);
10438 if (retval) {
10439 goto success;
10440 }
10441 }
10442 return PyErr_SetFromWindowsErr(err);
10443 }
10444
10445success:
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010446 return Py_BuildValue("(LL)", total.QuadPart, free.QuadPart);
10447}
Larry Hastings2f936352014-08-05 14:04:04 +100010448#endif /* MS_WINDOWS */
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +020010449
10450
Fred Drakec9680921999-12-13 16:37:25 +000010451/* This is used for fpathconf(), pathconf(), confstr() and sysconf().
10452 * It maps strings representing configuration variable names to
10453 * integer values, allowing those functions to be called with the
Thomas Wouters7e474022000-07-16 12:04:32 +000010454 * magic names instead of polluting the module's namespace with tons of
Fred Drake12c6e2d1999-12-14 21:25:03 +000010455 * rarely-used constants. There are three separate tables that use
10456 * these definitions.
Fred Drakebec628d1999-12-15 18:31:10 +000010457 *
10458 * This code is always included, even if none of the interfaces that
10459 * need it are included. The #if hackery needed to avoid it would be
10460 * sufficiently pervasive that it's not worth the loss of readability.
Fred Drakec9680921999-12-13 16:37:25 +000010461 */
10462struct constdef {
Serhiy Storchaka2d06e842015-12-25 19:53:18 +020010463 const char *name;
Serhiy Storchaka56f6e762015-09-06 21:25:30 +030010464 int value;
Fred Drakec9680921999-12-13 16:37:25 +000010465};
10466
Fred Drake12c6e2d1999-12-14 21:25:03 +000010467static int
Fredrik Lundhff7df9d2000-07-08 22:48:53 +000010468conv_confname(PyObject *arg, int *valuep, struct constdef *table,
Guido van Rossum7d5baac2007-08-27 23:24:46 +000010469 size_t tablesize)
Fred Drake12c6e2d1999-12-14 21:25:03 +000010470{
Christian Heimes217cfd12007-12-02 14:31:20 +000010471 if (PyLong_Check(arg)) {
Serhiy Storchaka56f6e762015-09-06 21:25:30 +030010472 int value = _PyLong_AsInt(arg);
10473 if (value == -1 && PyErr_Occurred())
10474 return 0;
10475 *valuep = value;
Stefan Krah0e803b32010-11-26 16:16:47 +000010476 return 1;
Fred Drake12c6e2d1999-12-14 21:25:03 +000010477 }
Guido van Rossumbce56a62007-05-10 18:04:33 +000010478 else {
Stefan Krah0e803b32010-11-26 16:16:47 +000010479 /* look up the value in the table using a binary search */
10480 size_t lo = 0;
10481 size_t mid;
10482 size_t hi = tablesize;
10483 int cmp;
10484 const char *confname;
10485 if (!PyUnicode_Check(arg)) {
10486 PyErr_SetString(PyExc_TypeError,
10487 "configuration names must be strings or integers");
10488 return 0;
Victor Stinner8c62be82010-05-06 00:08:46 +000010489 }
Serhiy Storchaka06515832016-11-20 09:13:07 +020010490 confname = PyUnicode_AsUTF8(arg);
Stefan Krah0e803b32010-11-26 16:16:47 +000010491 if (confname == NULL)
10492 return 0;
10493 while (lo < hi) {
10494 mid = (lo + hi) / 2;
10495 cmp = strcmp(confname, table[mid].name);
10496 if (cmp < 0)
10497 hi = mid;
10498 else if (cmp > 0)
10499 lo = mid + 1;
10500 else {
10501 *valuep = table[mid].value;
10502 return 1;
10503 }
10504 }
10505 PyErr_SetString(PyExc_ValueError, "unrecognized configuration name");
10506 return 0;
Victor Stinner8c62be82010-05-06 00:08:46 +000010507 }
Fred Drake12c6e2d1999-12-14 21:25:03 +000010508}
10509
10510
10511#if defined(HAVE_FPATHCONF) || defined(HAVE_PATHCONF)
10512static struct constdef posix_constants_pathconf[] = {
Fred Draked86ed291999-12-15 15:34:33 +000010513#ifdef _PC_ABI_AIO_XFER_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010514 {"PC_ABI_AIO_XFER_MAX", _PC_ABI_AIO_XFER_MAX},
Fred Draked86ed291999-12-15 15:34:33 +000010515#endif
10516#ifdef _PC_ABI_ASYNC_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000010517 {"PC_ABI_ASYNC_IO", _PC_ABI_ASYNC_IO},
Fred Draked86ed291999-12-15 15:34:33 +000010518#endif
Fred Drakec9680921999-12-13 16:37:25 +000010519#ifdef _PC_ASYNC_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000010520 {"PC_ASYNC_IO", _PC_ASYNC_IO},
Fred Drakec9680921999-12-13 16:37:25 +000010521#endif
10522#ifdef _PC_CHOWN_RESTRICTED
Victor Stinner8c62be82010-05-06 00:08:46 +000010523 {"PC_CHOWN_RESTRICTED", _PC_CHOWN_RESTRICTED},
Fred Drakec9680921999-12-13 16:37:25 +000010524#endif
10525#ifdef _PC_FILESIZEBITS
Victor Stinner8c62be82010-05-06 00:08:46 +000010526 {"PC_FILESIZEBITS", _PC_FILESIZEBITS},
Fred Drakec9680921999-12-13 16:37:25 +000010527#endif
10528#ifdef _PC_LAST
Victor Stinner8c62be82010-05-06 00:08:46 +000010529 {"PC_LAST", _PC_LAST},
Fred Drakec9680921999-12-13 16:37:25 +000010530#endif
10531#ifdef _PC_LINK_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010532 {"PC_LINK_MAX", _PC_LINK_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010533#endif
10534#ifdef _PC_MAX_CANON
Victor Stinner8c62be82010-05-06 00:08:46 +000010535 {"PC_MAX_CANON", _PC_MAX_CANON},
Fred Drakec9680921999-12-13 16:37:25 +000010536#endif
10537#ifdef _PC_MAX_INPUT
Victor Stinner8c62be82010-05-06 00:08:46 +000010538 {"PC_MAX_INPUT", _PC_MAX_INPUT},
Fred Drakec9680921999-12-13 16:37:25 +000010539#endif
10540#ifdef _PC_NAME_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010541 {"PC_NAME_MAX", _PC_NAME_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010542#endif
10543#ifdef _PC_NO_TRUNC
Victor Stinner8c62be82010-05-06 00:08:46 +000010544 {"PC_NO_TRUNC", _PC_NO_TRUNC},
Fred Drakec9680921999-12-13 16:37:25 +000010545#endif
10546#ifdef _PC_PATH_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010547 {"PC_PATH_MAX", _PC_PATH_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010548#endif
10549#ifdef _PC_PIPE_BUF
Victor Stinner8c62be82010-05-06 00:08:46 +000010550 {"PC_PIPE_BUF", _PC_PIPE_BUF},
Fred Drakec9680921999-12-13 16:37:25 +000010551#endif
10552#ifdef _PC_PRIO_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000010553 {"PC_PRIO_IO", _PC_PRIO_IO},
Fred Drakec9680921999-12-13 16:37:25 +000010554#endif
10555#ifdef _PC_SOCK_MAXBUF
Victor Stinner8c62be82010-05-06 00:08:46 +000010556 {"PC_SOCK_MAXBUF", _PC_SOCK_MAXBUF},
Fred Drakec9680921999-12-13 16:37:25 +000010557#endif
10558#ifdef _PC_SYNC_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000010559 {"PC_SYNC_IO", _PC_SYNC_IO},
Fred Drakec9680921999-12-13 16:37:25 +000010560#endif
10561#ifdef _PC_VDISABLE
Victor Stinner8c62be82010-05-06 00:08:46 +000010562 {"PC_VDISABLE", _PC_VDISABLE},
Fred Drakec9680921999-12-13 16:37:25 +000010563#endif
Jesus Cea7e9065c2010-10-25 13:02:04 +000010564#ifdef _PC_ACL_ENABLED
10565 {"PC_ACL_ENABLED", _PC_ACL_ENABLED},
10566#endif
10567#ifdef _PC_MIN_HOLE_SIZE
10568 {"PC_MIN_HOLE_SIZE", _PC_MIN_HOLE_SIZE},
10569#endif
10570#ifdef _PC_ALLOC_SIZE_MIN
10571 {"PC_ALLOC_SIZE_MIN", _PC_ALLOC_SIZE_MIN},
10572#endif
10573#ifdef _PC_REC_INCR_XFER_SIZE
10574 {"PC_REC_INCR_XFER_SIZE", _PC_REC_INCR_XFER_SIZE},
10575#endif
10576#ifdef _PC_REC_MAX_XFER_SIZE
10577 {"PC_REC_MAX_XFER_SIZE", _PC_REC_MAX_XFER_SIZE},
10578#endif
10579#ifdef _PC_REC_MIN_XFER_SIZE
10580 {"PC_REC_MIN_XFER_SIZE", _PC_REC_MIN_XFER_SIZE},
10581#endif
10582#ifdef _PC_REC_XFER_ALIGN
10583 {"PC_REC_XFER_ALIGN", _PC_REC_XFER_ALIGN},
10584#endif
10585#ifdef _PC_SYMLINK_MAX
10586 {"PC_SYMLINK_MAX", _PC_SYMLINK_MAX},
10587#endif
10588#ifdef _PC_XATTR_ENABLED
10589 {"PC_XATTR_ENABLED", _PC_XATTR_ENABLED},
10590#endif
10591#ifdef _PC_XATTR_EXISTS
10592 {"PC_XATTR_EXISTS", _PC_XATTR_EXISTS},
10593#endif
10594#ifdef _PC_TIMESTAMP_RESOLUTION
10595 {"PC_TIMESTAMP_RESOLUTION", _PC_TIMESTAMP_RESOLUTION},
10596#endif
Fred Drakec9680921999-12-13 16:37:25 +000010597};
10598
Fred Drakec9680921999-12-13 16:37:25 +000010599static int
Fredrik Lundhff7df9d2000-07-08 22:48:53 +000010600conv_path_confname(PyObject *arg, int *valuep)
Fred Drakec9680921999-12-13 16:37:25 +000010601{
10602 return conv_confname(arg, valuep, posix_constants_pathconf,
10603 sizeof(posix_constants_pathconf)
10604 / sizeof(struct constdef));
10605}
10606#endif
10607
Larry Hastings2f936352014-08-05 14:04:04 +100010608
Fred Drakec9680921999-12-13 16:37:25 +000010609#ifdef HAVE_FPATHCONF
Larry Hastings2f936352014-08-05 14:04:04 +100010610/*[clinic input]
10611os.fpathconf -> long
10612
10613 fd: int
10614 name: path_confname
10615 /
10616
10617Return the configuration limit name for the file descriptor fd.
10618
10619If there is no limit, return -1.
10620[clinic start generated code]*/
10621
Larry Hastings2f936352014-08-05 14:04:04 +100010622static long
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010623os_fpathconf_impl(PyObject *module, int fd, int name)
10624/*[clinic end generated code: output=d5b7042425fc3e21 input=5942a024d3777810]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010625{
10626 long limit;
10627
10628 errno = 0;
10629 limit = fpathconf(fd, name);
10630 if (limit == -1 && errno != 0)
10631 posix_error();
10632
10633 return limit;
10634}
10635#endif /* HAVE_FPATHCONF */
Fred Drakec9680921999-12-13 16:37:25 +000010636
10637
10638#ifdef HAVE_PATHCONF
Larry Hastings2f936352014-08-05 14:04:04 +100010639/*[clinic input]
10640os.pathconf -> long
10641 path: path_t(allow_fd='PATH_HAVE_FPATHCONF')
10642 name: path_confname
10643
10644Return the configuration limit name for the file or directory path.
10645
10646If there is no limit, return -1.
10647On some platforms, path may also be specified as an open file descriptor.
10648 If this functionality is unavailable, using it raises an exception.
10649[clinic start generated code]*/
10650
Larry Hastings2f936352014-08-05 14:04:04 +100010651static long
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010652os_pathconf_impl(PyObject *module, path_t *path, int name)
10653/*[clinic end generated code: output=5bedee35b293a089 input=bc3e2a985af27e5e]*/
Larry Hastings2f936352014-08-05 14:04:04 +100010654{
Victor Stinner8c62be82010-05-06 00:08:46 +000010655 long limit;
Fred Drakec9680921999-12-13 16:37:25 +000010656
Victor Stinner8c62be82010-05-06 00:08:46 +000010657 errno = 0;
Georg Brandl306336b2012-06-24 12:55:33 +020010658#ifdef HAVE_FPATHCONF
Larry Hastings2f936352014-08-05 14:04:04 +100010659 if (path->fd != -1)
10660 limit = fpathconf(path->fd, name);
Georg Brandl306336b2012-06-24 12:55:33 +020010661 else
10662#endif
Larry Hastings2f936352014-08-05 14:04:04 +100010663 limit = pathconf(path->narrow, name);
Victor Stinner8c62be82010-05-06 00:08:46 +000010664 if (limit == -1 && errno != 0) {
10665 if (errno == EINVAL)
Stefan Krah99439262010-11-26 12:58:05 +000010666 /* could be a path or name problem */
10667 posix_error();
Fred Drakec9680921999-12-13 16:37:25 +000010668 else
Larry Hastings2f936352014-08-05 14:04:04 +100010669 path_error(path);
Victor Stinner8c62be82010-05-06 00:08:46 +000010670 }
Larry Hastings2f936352014-08-05 14:04:04 +100010671
10672 return limit;
Fred Drakec9680921999-12-13 16:37:25 +000010673}
Larry Hastings2f936352014-08-05 14:04:04 +100010674#endif /* HAVE_PATHCONF */
Fred Drakec9680921999-12-13 16:37:25 +000010675
10676#ifdef HAVE_CONFSTR
10677static struct constdef posix_constants_confstr[] = {
Fred Draked86ed291999-12-15 15:34:33 +000010678#ifdef _CS_ARCHITECTURE
Victor Stinner8c62be82010-05-06 00:08:46 +000010679 {"CS_ARCHITECTURE", _CS_ARCHITECTURE},
Fred Draked86ed291999-12-15 15:34:33 +000010680#endif
Mark Dickinson876d7c82010-04-16 12:47:52 +000010681#ifdef _CS_GNU_LIBC_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000010682 {"CS_GNU_LIBC_VERSION", _CS_GNU_LIBC_VERSION},
Mark Dickinson876d7c82010-04-16 12:47:52 +000010683#endif
10684#ifdef _CS_GNU_LIBPTHREAD_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000010685 {"CS_GNU_LIBPTHREAD_VERSION", _CS_GNU_LIBPTHREAD_VERSION},
Mark Dickinson876d7c82010-04-16 12:47:52 +000010686#endif
Fred Draked86ed291999-12-15 15:34:33 +000010687#ifdef _CS_HOSTNAME
Victor Stinner8c62be82010-05-06 00:08:46 +000010688 {"CS_HOSTNAME", _CS_HOSTNAME},
Fred Draked86ed291999-12-15 15:34:33 +000010689#endif
10690#ifdef _CS_HW_PROVIDER
Victor Stinner8c62be82010-05-06 00:08:46 +000010691 {"CS_HW_PROVIDER", _CS_HW_PROVIDER},
Fred Draked86ed291999-12-15 15:34:33 +000010692#endif
10693#ifdef _CS_HW_SERIAL
Victor Stinner8c62be82010-05-06 00:08:46 +000010694 {"CS_HW_SERIAL", _CS_HW_SERIAL},
Fred Draked86ed291999-12-15 15:34:33 +000010695#endif
10696#ifdef _CS_INITTAB_NAME
Victor Stinner8c62be82010-05-06 00:08:46 +000010697 {"CS_INITTAB_NAME", _CS_INITTAB_NAME},
Fred Draked86ed291999-12-15 15:34:33 +000010698#endif
Fred Drakec9680921999-12-13 16:37:25 +000010699#ifdef _CS_LFS64_CFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010700 {"CS_LFS64_CFLAGS", _CS_LFS64_CFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010701#endif
10702#ifdef _CS_LFS64_LDFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010703 {"CS_LFS64_LDFLAGS", _CS_LFS64_LDFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010704#endif
10705#ifdef _CS_LFS64_LIBS
Victor Stinner8c62be82010-05-06 00:08:46 +000010706 {"CS_LFS64_LIBS", _CS_LFS64_LIBS},
Fred Drakec9680921999-12-13 16:37:25 +000010707#endif
10708#ifdef _CS_LFS64_LINTFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010709 {"CS_LFS64_LINTFLAGS", _CS_LFS64_LINTFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010710#endif
10711#ifdef _CS_LFS_CFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010712 {"CS_LFS_CFLAGS", _CS_LFS_CFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010713#endif
10714#ifdef _CS_LFS_LDFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010715 {"CS_LFS_LDFLAGS", _CS_LFS_LDFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010716#endif
10717#ifdef _CS_LFS_LIBS
Victor Stinner8c62be82010-05-06 00:08:46 +000010718 {"CS_LFS_LIBS", _CS_LFS_LIBS},
Fred Drakec9680921999-12-13 16:37:25 +000010719#endif
10720#ifdef _CS_LFS_LINTFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010721 {"CS_LFS_LINTFLAGS", _CS_LFS_LINTFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010722#endif
Fred Draked86ed291999-12-15 15:34:33 +000010723#ifdef _CS_MACHINE
Victor Stinner8c62be82010-05-06 00:08:46 +000010724 {"CS_MACHINE", _CS_MACHINE},
Fred Draked86ed291999-12-15 15:34:33 +000010725#endif
Fred Drakec9680921999-12-13 16:37:25 +000010726#ifdef _CS_PATH
Victor Stinner8c62be82010-05-06 00:08:46 +000010727 {"CS_PATH", _CS_PATH},
Fred Drakec9680921999-12-13 16:37:25 +000010728#endif
Fred Draked86ed291999-12-15 15:34:33 +000010729#ifdef _CS_RELEASE
Victor Stinner8c62be82010-05-06 00:08:46 +000010730 {"CS_RELEASE", _CS_RELEASE},
Fred Draked86ed291999-12-15 15:34:33 +000010731#endif
10732#ifdef _CS_SRPC_DOMAIN
Victor Stinner8c62be82010-05-06 00:08:46 +000010733 {"CS_SRPC_DOMAIN", _CS_SRPC_DOMAIN},
Fred Draked86ed291999-12-15 15:34:33 +000010734#endif
10735#ifdef _CS_SYSNAME
Victor Stinner8c62be82010-05-06 00:08:46 +000010736 {"CS_SYSNAME", _CS_SYSNAME},
Fred Draked86ed291999-12-15 15:34:33 +000010737#endif
10738#ifdef _CS_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000010739 {"CS_VERSION", _CS_VERSION},
Fred Draked86ed291999-12-15 15:34:33 +000010740#endif
Fred Drakec9680921999-12-13 16:37:25 +000010741#ifdef _CS_XBS5_ILP32_OFF32_CFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010742 {"CS_XBS5_ILP32_OFF32_CFLAGS", _CS_XBS5_ILP32_OFF32_CFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010743#endif
10744#ifdef _CS_XBS5_ILP32_OFF32_LDFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010745 {"CS_XBS5_ILP32_OFF32_LDFLAGS", _CS_XBS5_ILP32_OFF32_LDFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010746#endif
10747#ifdef _CS_XBS5_ILP32_OFF32_LIBS
Victor Stinner8c62be82010-05-06 00:08:46 +000010748 {"CS_XBS5_ILP32_OFF32_LIBS", _CS_XBS5_ILP32_OFF32_LIBS},
Fred Drakec9680921999-12-13 16:37:25 +000010749#endif
10750#ifdef _CS_XBS5_ILP32_OFF32_LINTFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010751 {"CS_XBS5_ILP32_OFF32_LINTFLAGS", _CS_XBS5_ILP32_OFF32_LINTFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010752#endif
10753#ifdef _CS_XBS5_ILP32_OFFBIG_CFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010754 {"CS_XBS5_ILP32_OFFBIG_CFLAGS", _CS_XBS5_ILP32_OFFBIG_CFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010755#endif
10756#ifdef _CS_XBS5_ILP32_OFFBIG_LDFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010757 {"CS_XBS5_ILP32_OFFBIG_LDFLAGS", _CS_XBS5_ILP32_OFFBIG_LDFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010758#endif
10759#ifdef _CS_XBS5_ILP32_OFFBIG_LIBS
Victor Stinner8c62be82010-05-06 00:08:46 +000010760 {"CS_XBS5_ILP32_OFFBIG_LIBS", _CS_XBS5_ILP32_OFFBIG_LIBS},
Fred Drakec9680921999-12-13 16:37:25 +000010761#endif
10762#ifdef _CS_XBS5_ILP32_OFFBIG_LINTFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010763 {"CS_XBS5_ILP32_OFFBIG_LINTFLAGS", _CS_XBS5_ILP32_OFFBIG_LINTFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010764#endif
10765#ifdef _CS_XBS5_LP64_OFF64_CFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010766 {"CS_XBS5_LP64_OFF64_CFLAGS", _CS_XBS5_LP64_OFF64_CFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010767#endif
10768#ifdef _CS_XBS5_LP64_OFF64_LDFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010769 {"CS_XBS5_LP64_OFF64_LDFLAGS", _CS_XBS5_LP64_OFF64_LDFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010770#endif
10771#ifdef _CS_XBS5_LP64_OFF64_LIBS
Victor Stinner8c62be82010-05-06 00:08:46 +000010772 {"CS_XBS5_LP64_OFF64_LIBS", _CS_XBS5_LP64_OFF64_LIBS},
Fred Drakec9680921999-12-13 16:37:25 +000010773#endif
10774#ifdef _CS_XBS5_LP64_OFF64_LINTFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010775 {"CS_XBS5_LP64_OFF64_LINTFLAGS", _CS_XBS5_LP64_OFF64_LINTFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010776#endif
10777#ifdef _CS_XBS5_LPBIG_OFFBIG_CFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010778 {"CS_XBS5_LPBIG_OFFBIG_CFLAGS", _CS_XBS5_LPBIG_OFFBIG_CFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010779#endif
10780#ifdef _CS_XBS5_LPBIG_OFFBIG_LDFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010781 {"CS_XBS5_LPBIG_OFFBIG_LDFLAGS", _CS_XBS5_LPBIG_OFFBIG_LDFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010782#endif
10783#ifdef _CS_XBS5_LPBIG_OFFBIG_LIBS
Victor Stinner8c62be82010-05-06 00:08:46 +000010784 {"CS_XBS5_LPBIG_OFFBIG_LIBS", _CS_XBS5_LPBIG_OFFBIG_LIBS},
Fred Drakec9680921999-12-13 16:37:25 +000010785#endif
10786#ifdef _CS_XBS5_LPBIG_OFFBIG_LINTFLAGS
Victor Stinner8c62be82010-05-06 00:08:46 +000010787 {"CS_XBS5_LPBIG_OFFBIG_LINTFLAGS", _CS_XBS5_LPBIG_OFFBIG_LINTFLAGS},
Fred Drakec9680921999-12-13 16:37:25 +000010788#endif
Fred Draked86ed291999-12-15 15:34:33 +000010789#ifdef _MIPS_CS_AVAIL_PROCESSORS
Victor Stinner8c62be82010-05-06 00:08:46 +000010790 {"MIPS_CS_AVAIL_PROCESSORS", _MIPS_CS_AVAIL_PROCESSORS},
Fred Draked86ed291999-12-15 15:34:33 +000010791#endif
10792#ifdef _MIPS_CS_BASE
Victor Stinner8c62be82010-05-06 00:08:46 +000010793 {"MIPS_CS_BASE", _MIPS_CS_BASE},
Fred Draked86ed291999-12-15 15:34:33 +000010794#endif
10795#ifdef _MIPS_CS_HOSTID
Victor Stinner8c62be82010-05-06 00:08:46 +000010796 {"MIPS_CS_HOSTID", _MIPS_CS_HOSTID},
Fred Draked86ed291999-12-15 15:34:33 +000010797#endif
10798#ifdef _MIPS_CS_HW_NAME
Victor Stinner8c62be82010-05-06 00:08:46 +000010799 {"MIPS_CS_HW_NAME", _MIPS_CS_HW_NAME},
Fred Draked86ed291999-12-15 15:34:33 +000010800#endif
10801#ifdef _MIPS_CS_NUM_PROCESSORS
Victor Stinner8c62be82010-05-06 00:08:46 +000010802 {"MIPS_CS_NUM_PROCESSORS", _MIPS_CS_NUM_PROCESSORS},
Fred Draked86ed291999-12-15 15:34:33 +000010803#endif
10804#ifdef _MIPS_CS_OSREL_MAJ
Victor Stinner8c62be82010-05-06 00:08:46 +000010805 {"MIPS_CS_OSREL_MAJ", _MIPS_CS_OSREL_MAJ},
Fred Draked86ed291999-12-15 15:34:33 +000010806#endif
10807#ifdef _MIPS_CS_OSREL_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000010808 {"MIPS_CS_OSREL_MIN", _MIPS_CS_OSREL_MIN},
Fred Draked86ed291999-12-15 15:34:33 +000010809#endif
10810#ifdef _MIPS_CS_OSREL_PATCH
Victor Stinner8c62be82010-05-06 00:08:46 +000010811 {"MIPS_CS_OSREL_PATCH", _MIPS_CS_OSREL_PATCH},
Fred Draked86ed291999-12-15 15:34:33 +000010812#endif
10813#ifdef _MIPS_CS_OS_NAME
Victor Stinner8c62be82010-05-06 00:08:46 +000010814 {"MIPS_CS_OS_NAME", _MIPS_CS_OS_NAME},
Fred Draked86ed291999-12-15 15:34:33 +000010815#endif
10816#ifdef _MIPS_CS_OS_PROVIDER
Victor Stinner8c62be82010-05-06 00:08:46 +000010817 {"MIPS_CS_OS_PROVIDER", _MIPS_CS_OS_PROVIDER},
Fred Draked86ed291999-12-15 15:34:33 +000010818#endif
10819#ifdef _MIPS_CS_PROCESSORS
Victor Stinner8c62be82010-05-06 00:08:46 +000010820 {"MIPS_CS_PROCESSORS", _MIPS_CS_PROCESSORS},
Fred Draked86ed291999-12-15 15:34:33 +000010821#endif
10822#ifdef _MIPS_CS_SERIAL
Victor Stinner8c62be82010-05-06 00:08:46 +000010823 {"MIPS_CS_SERIAL", _MIPS_CS_SERIAL},
Fred Draked86ed291999-12-15 15:34:33 +000010824#endif
10825#ifdef _MIPS_CS_VENDOR
Victor Stinner8c62be82010-05-06 00:08:46 +000010826 {"MIPS_CS_VENDOR", _MIPS_CS_VENDOR},
Fred Draked86ed291999-12-15 15:34:33 +000010827#endif
Fred Drakec9680921999-12-13 16:37:25 +000010828};
10829
10830static int
Fredrik Lundhff7df9d2000-07-08 22:48:53 +000010831conv_confstr_confname(PyObject *arg, int *valuep)
Fred Drakec9680921999-12-13 16:37:25 +000010832{
10833 return conv_confname(arg, valuep, posix_constants_confstr,
10834 sizeof(posix_constants_confstr)
10835 / sizeof(struct constdef));
10836}
10837
Larry Hastings2f936352014-08-05 14:04:04 +100010838
10839/*[clinic input]
10840os.confstr
10841
10842 name: confstr_confname
10843 /
10844
10845Return a string-valued system configuration variable.
10846[clinic start generated code]*/
10847
Larry Hastings2f936352014-08-05 14:04:04 +100010848static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030010849os_confstr_impl(PyObject *module, int name)
10850/*[clinic end generated code: output=bfb0b1b1e49b9383 input=18fb4d0567242e65]*/
Fred Drakec9680921999-12-13 16:37:25 +000010851{
10852 PyObject *result = NULL;
Victor Stinnercb043522010-09-10 23:49:04 +000010853 char buffer[255];
Victor Stinnerdd3a6a52013-06-25 23:13:47 +020010854 size_t len;
Fred Drakec9680921999-12-13 16:37:25 +000010855
Victor Stinnercb043522010-09-10 23:49:04 +000010856 errno = 0;
10857 len = confstr(name, buffer, sizeof(buffer));
10858 if (len == 0) {
10859 if (errno) {
10860 posix_error();
10861 return NULL;
Fred Drakec9680921999-12-13 16:37:25 +000010862 }
10863 else {
Victor Stinnercb043522010-09-10 23:49:04 +000010864 Py_RETURN_NONE;
Fred Drakec9680921999-12-13 16:37:25 +000010865 }
10866 }
Victor Stinnercb043522010-09-10 23:49:04 +000010867
Victor Stinnerdd3a6a52013-06-25 23:13:47 +020010868 if (len >= sizeof(buffer)) {
Victor Stinnercbc18f32014-12-05 22:51:51 +010010869 size_t len2;
Victor Stinnercb043522010-09-10 23:49:04 +000010870 char *buf = PyMem_Malloc(len);
10871 if (buf == NULL)
10872 return PyErr_NoMemory();
Victor Stinnercbc18f32014-12-05 22:51:51 +010010873 len2 = confstr(name, buf, len);
10874 assert(len == len2);
Christian Heimes8714cfd2015-04-21 10:57:41 +020010875 result = PyUnicode_DecodeFSDefaultAndSize(buf, len2-1);
Victor Stinnercb043522010-09-10 23:49:04 +000010876 PyMem_Free(buf);
10877 }
10878 else
10879 result = PyUnicode_DecodeFSDefaultAndSize(buffer, len-1);
Fred Drakec9680921999-12-13 16:37:25 +000010880 return result;
10881}
Larry Hastings2f936352014-08-05 14:04:04 +100010882#endif /* HAVE_CONFSTR */
Fred Drakec9680921999-12-13 16:37:25 +000010883
10884
10885#ifdef HAVE_SYSCONF
10886static struct constdef posix_constants_sysconf[] = {
10887#ifdef _SC_2_CHAR_TERM
Victor Stinner8c62be82010-05-06 00:08:46 +000010888 {"SC_2_CHAR_TERM", _SC_2_CHAR_TERM},
Fred Drakec9680921999-12-13 16:37:25 +000010889#endif
10890#ifdef _SC_2_C_BIND
Victor Stinner8c62be82010-05-06 00:08:46 +000010891 {"SC_2_C_BIND", _SC_2_C_BIND},
Fred Drakec9680921999-12-13 16:37:25 +000010892#endif
10893#ifdef _SC_2_C_DEV
Victor Stinner8c62be82010-05-06 00:08:46 +000010894 {"SC_2_C_DEV", _SC_2_C_DEV},
Fred Drakec9680921999-12-13 16:37:25 +000010895#endif
10896#ifdef _SC_2_C_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000010897 {"SC_2_C_VERSION", _SC_2_C_VERSION},
Fred Drakec9680921999-12-13 16:37:25 +000010898#endif
10899#ifdef _SC_2_FORT_DEV
Victor Stinner8c62be82010-05-06 00:08:46 +000010900 {"SC_2_FORT_DEV", _SC_2_FORT_DEV},
Fred Drakec9680921999-12-13 16:37:25 +000010901#endif
10902#ifdef _SC_2_FORT_RUN
Victor Stinner8c62be82010-05-06 00:08:46 +000010903 {"SC_2_FORT_RUN", _SC_2_FORT_RUN},
Fred Drakec9680921999-12-13 16:37:25 +000010904#endif
10905#ifdef _SC_2_LOCALEDEF
Victor Stinner8c62be82010-05-06 00:08:46 +000010906 {"SC_2_LOCALEDEF", _SC_2_LOCALEDEF},
Fred Drakec9680921999-12-13 16:37:25 +000010907#endif
10908#ifdef _SC_2_SW_DEV
Victor Stinner8c62be82010-05-06 00:08:46 +000010909 {"SC_2_SW_DEV", _SC_2_SW_DEV},
Fred Drakec9680921999-12-13 16:37:25 +000010910#endif
10911#ifdef _SC_2_UPE
Victor Stinner8c62be82010-05-06 00:08:46 +000010912 {"SC_2_UPE", _SC_2_UPE},
Fred Drakec9680921999-12-13 16:37:25 +000010913#endif
10914#ifdef _SC_2_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000010915 {"SC_2_VERSION", _SC_2_VERSION},
Fred Drakec9680921999-12-13 16:37:25 +000010916#endif
Fred Draked86ed291999-12-15 15:34:33 +000010917#ifdef _SC_ABI_ASYNCHRONOUS_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000010918 {"SC_ABI_ASYNCHRONOUS_IO", _SC_ABI_ASYNCHRONOUS_IO},
Fred Draked86ed291999-12-15 15:34:33 +000010919#endif
10920#ifdef _SC_ACL
Victor Stinner8c62be82010-05-06 00:08:46 +000010921 {"SC_ACL", _SC_ACL},
Fred Draked86ed291999-12-15 15:34:33 +000010922#endif
Fred Drakec9680921999-12-13 16:37:25 +000010923#ifdef _SC_AIO_LISTIO_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010924 {"SC_AIO_LISTIO_MAX", _SC_AIO_LISTIO_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010925#endif
Fred Drakec9680921999-12-13 16:37:25 +000010926#ifdef _SC_AIO_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010927 {"SC_AIO_MAX", _SC_AIO_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010928#endif
10929#ifdef _SC_AIO_PRIO_DELTA_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010930 {"SC_AIO_PRIO_DELTA_MAX", _SC_AIO_PRIO_DELTA_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010931#endif
10932#ifdef _SC_ARG_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010933 {"SC_ARG_MAX", _SC_ARG_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010934#endif
10935#ifdef _SC_ASYNCHRONOUS_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000010936 {"SC_ASYNCHRONOUS_IO", _SC_ASYNCHRONOUS_IO},
Fred Drakec9680921999-12-13 16:37:25 +000010937#endif
10938#ifdef _SC_ATEXIT_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010939 {"SC_ATEXIT_MAX", _SC_ATEXIT_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010940#endif
Fred Draked86ed291999-12-15 15:34:33 +000010941#ifdef _SC_AUDIT
Victor Stinner8c62be82010-05-06 00:08:46 +000010942 {"SC_AUDIT", _SC_AUDIT},
Fred Draked86ed291999-12-15 15:34:33 +000010943#endif
Fred Drakec9680921999-12-13 16:37:25 +000010944#ifdef _SC_AVPHYS_PAGES
Victor Stinner8c62be82010-05-06 00:08:46 +000010945 {"SC_AVPHYS_PAGES", _SC_AVPHYS_PAGES},
Fred Drakec9680921999-12-13 16:37:25 +000010946#endif
10947#ifdef _SC_BC_BASE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010948 {"SC_BC_BASE_MAX", _SC_BC_BASE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010949#endif
10950#ifdef _SC_BC_DIM_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010951 {"SC_BC_DIM_MAX", _SC_BC_DIM_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010952#endif
10953#ifdef _SC_BC_SCALE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010954 {"SC_BC_SCALE_MAX", _SC_BC_SCALE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010955#endif
10956#ifdef _SC_BC_STRING_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010957 {"SC_BC_STRING_MAX", _SC_BC_STRING_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010958#endif
Fred Draked86ed291999-12-15 15:34:33 +000010959#ifdef _SC_CAP
Victor Stinner8c62be82010-05-06 00:08:46 +000010960 {"SC_CAP", _SC_CAP},
Fred Draked86ed291999-12-15 15:34:33 +000010961#endif
Fred Drakec9680921999-12-13 16:37:25 +000010962#ifdef _SC_CHARCLASS_NAME_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010963 {"SC_CHARCLASS_NAME_MAX", _SC_CHARCLASS_NAME_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010964#endif
10965#ifdef _SC_CHAR_BIT
Victor Stinner8c62be82010-05-06 00:08:46 +000010966 {"SC_CHAR_BIT", _SC_CHAR_BIT},
Fred Drakec9680921999-12-13 16:37:25 +000010967#endif
10968#ifdef _SC_CHAR_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010969 {"SC_CHAR_MAX", _SC_CHAR_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010970#endif
10971#ifdef _SC_CHAR_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000010972 {"SC_CHAR_MIN", _SC_CHAR_MIN},
Fred Drakec9680921999-12-13 16:37:25 +000010973#endif
10974#ifdef _SC_CHILD_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010975 {"SC_CHILD_MAX", _SC_CHILD_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010976#endif
10977#ifdef _SC_CLK_TCK
Victor Stinner8c62be82010-05-06 00:08:46 +000010978 {"SC_CLK_TCK", _SC_CLK_TCK},
Fred Drakec9680921999-12-13 16:37:25 +000010979#endif
10980#ifdef _SC_COHER_BLKSZ
Victor Stinner8c62be82010-05-06 00:08:46 +000010981 {"SC_COHER_BLKSZ", _SC_COHER_BLKSZ},
Fred Drakec9680921999-12-13 16:37:25 +000010982#endif
10983#ifdef _SC_COLL_WEIGHTS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000010984 {"SC_COLL_WEIGHTS_MAX", _SC_COLL_WEIGHTS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000010985#endif
10986#ifdef _SC_DCACHE_ASSOC
Victor Stinner8c62be82010-05-06 00:08:46 +000010987 {"SC_DCACHE_ASSOC", _SC_DCACHE_ASSOC},
Fred Drakec9680921999-12-13 16:37:25 +000010988#endif
10989#ifdef _SC_DCACHE_BLKSZ
Victor Stinner8c62be82010-05-06 00:08:46 +000010990 {"SC_DCACHE_BLKSZ", _SC_DCACHE_BLKSZ},
Fred Drakec9680921999-12-13 16:37:25 +000010991#endif
10992#ifdef _SC_DCACHE_LINESZ
Victor Stinner8c62be82010-05-06 00:08:46 +000010993 {"SC_DCACHE_LINESZ", _SC_DCACHE_LINESZ},
Fred Drakec9680921999-12-13 16:37:25 +000010994#endif
10995#ifdef _SC_DCACHE_SZ
Victor Stinner8c62be82010-05-06 00:08:46 +000010996 {"SC_DCACHE_SZ", _SC_DCACHE_SZ},
Fred Drakec9680921999-12-13 16:37:25 +000010997#endif
10998#ifdef _SC_DCACHE_TBLKSZ
Victor Stinner8c62be82010-05-06 00:08:46 +000010999 {"SC_DCACHE_TBLKSZ", _SC_DCACHE_TBLKSZ},
Fred Drakec9680921999-12-13 16:37:25 +000011000#endif
11001#ifdef _SC_DELAYTIMER_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011002 {"SC_DELAYTIMER_MAX", _SC_DELAYTIMER_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011003#endif
11004#ifdef _SC_EQUIV_CLASS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011005 {"SC_EQUIV_CLASS_MAX", _SC_EQUIV_CLASS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011006#endif
11007#ifdef _SC_EXPR_NEST_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011008 {"SC_EXPR_NEST_MAX", _SC_EXPR_NEST_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011009#endif
11010#ifdef _SC_FSYNC
Victor Stinner8c62be82010-05-06 00:08:46 +000011011 {"SC_FSYNC", _SC_FSYNC},
Fred Drakec9680921999-12-13 16:37:25 +000011012#endif
11013#ifdef _SC_GETGR_R_SIZE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011014 {"SC_GETGR_R_SIZE_MAX", _SC_GETGR_R_SIZE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011015#endif
11016#ifdef _SC_GETPW_R_SIZE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011017 {"SC_GETPW_R_SIZE_MAX", _SC_GETPW_R_SIZE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011018#endif
11019#ifdef _SC_ICACHE_ASSOC
Victor Stinner8c62be82010-05-06 00:08:46 +000011020 {"SC_ICACHE_ASSOC", _SC_ICACHE_ASSOC},
Fred Drakec9680921999-12-13 16:37:25 +000011021#endif
11022#ifdef _SC_ICACHE_BLKSZ
Victor Stinner8c62be82010-05-06 00:08:46 +000011023 {"SC_ICACHE_BLKSZ", _SC_ICACHE_BLKSZ},
Fred Drakec9680921999-12-13 16:37:25 +000011024#endif
11025#ifdef _SC_ICACHE_LINESZ
Victor Stinner8c62be82010-05-06 00:08:46 +000011026 {"SC_ICACHE_LINESZ", _SC_ICACHE_LINESZ},
Fred Drakec9680921999-12-13 16:37:25 +000011027#endif
11028#ifdef _SC_ICACHE_SZ
Victor Stinner8c62be82010-05-06 00:08:46 +000011029 {"SC_ICACHE_SZ", _SC_ICACHE_SZ},
Fred Drakec9680921999-12-13 16:37:25 +000011030#endif
Fred Draked86ed291999-12-15 15:34:33 +000011031#ifdef _SC_INF
Victor Stinner8c62be82010-05-06 00:08:46 +000011032 {"SC_INF", _SC_INF},
Fred Draked86ed291999-12-15 15:34:33 +000011033#endif
Fred Drakec9680921999-12-13 16:37:25 +000011034#ifdef _SC_INT_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011035 {"SC_INT_MAX", _SC_INT_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011036#endif
11037#ifdef _SC_INT_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000011038 {"SC_INT_MIN", _SC_INT_MIN},
Fred Drakec9680921999-12-13 16:37:25 +000011039#endif
11040#ifdef _SC_IOV_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011041 {"SC_IOV_MAX", _SC_IOV_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011042#endif
Fred Draked86ed291999-12-15 15:34:33 +000011043#ifdef _SC_IP_SECOPTS
Victor Stinner8c62be82010-05-06 00:08:46 +000011044 {"SC_IP_SECOPTS", _SC_IP_SECOPTS},
Fred Draked86ed291999-12-15 15:34:33 +000011045#endif
Fred Drakec9680921999-12-13 16:37:25 +000011046#ifdef _SC_JOB_CONTROL
Victor Stinner8c62be82010-05-06 00:08:46 +000011047 {"SC_JOB_CONTROL", _SC_JOB_CONTROL},
Fred Drakec9680921999-12-13 16:37:25 +000011048#endif
Fred Draked86ed291999-12-15 15:34:33 +000011049#ifdef _SC_KERN_POINTERS
Victor Stinner8c62be82010-05-06 00:08:46 +000011050 {"SC_KERN_POINTERS", _SC_KERN_POINTERS},
Fred Draked86ed291999-12-15 15:34:33 +000011051#endif
11052#ifdef _SC_KERN_SIM
Victor Stinner8c62be82010-05-06 00:08:46 +000011053 {"SC_KERN_SIM", _SC_KERN_SIM},
Fred Draked86ed291999-12-15 15:34:33 +000011054#endif
Fred Drakec9680921999-12-13 16:37:25 +000011055#ifdef _SC_LINE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011056 {"SC_LINE_MAX", _SC_LINE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011057#endif
11058#ifdef _SC_LOGIN_NAME_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011059 {"SC_LOGIN_NAME_MAX", _SC_LOGIN_NAME_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011060#endif
11061#ifdef _SC_LOGNAME_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011062 {"SC_LOGNAME_MAX", _SC_LOGNAME_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011063#endif
11064#ifdef _SC_LONG_BIT
Victor Stinner8c62be82010-05-06 00:08:46 +000011065 {"SC_LONG_BIT", _SC_LONG_BIT},
Fred Drakec9680921999-12-13 16:37:25 +000011066#endif
Fred Draked86ed291999-12-15 15:34:33 +000011067#ifdef _SC_MAC
Victor Stinner8c62be82010-05-06 00:08:46 +000011068 {"SC_MAC", _SC_MAC},
Fred Draked86ed291999-12-15 15:34:33 +000011069#endif
Fred Drakec9680921999-12-13 16:37:25 +000011070#ifdef _SC_MAPPED_FILES
Victor Stinner8c62be82010-05-06 00:08:46 +000011071 {"SC_MAPPED_FILES", _SC_MAPPED_FILES},
Fred Drakec9680921999-12-13 16:37:25 +000011072#endif
11073#ifdef _SC_MAXPID
Victor Stinner8c62be82010-05-06 00:08:46 +000011074 {"SC_MAXPID", _SC_MAXPID},
Fred Drakec9680921999-12-13 16:37:25 +000011075#endif
11076#ifdef _SC_MB_LEN_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011077 {"SC_MB_LEN_MAX", _SC_MB_LEN_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011078#endif
11079#ifdef _SC_MEMLOCK
Victor Stinner8c62be82010-05-06 00:08:46 +000011080 {"SC_MEMLOCK", _SC_MEMLOCK},
Fred Drakec9680921999-12-13 16:37:25 +000011081#endif
11082#ifdef _SC_MEMLOCK_RANGE
Victor Stinner8c62be82010-05-06 00:08:46 +000011083 {"SC_MEMLOCK_RANGE", _SC_MEMLOCK_RANGE},
Fred Drakec9680921999-12-13 16:37:25 +000011084#endif
11085#ifdef _SC_MEMORY_PROTECTION
Victor Stinner8c62be82010-05-06 00:08:46 +000011086 {"SC_MEMORY_PROTECTION", _SC_MEMORY_PROTECTION},
Fred Drakec9680921999-12-13 16:37:25 +000011087#endif
11088#ifdef _SC_MESSAGE_PASSING
Victor Stinner8c62be82010-05-06 00:08:46 +000011089 {"SC_MESSAGE_PASSING", _SC_MESSAGE_PASSING},
Fred Drakec9680921999-12-13 16:37:25 +000011090#endif
Fred Draked86ed291999-12-15 15:34:33 +000011091#ifdef _SC_MMAP_FIXED_ALIGNMENT
Victor Stinner8c62be82010-05-06 00:08:46 +000011092 {"SC_MMAP_FIXED_ALIGNMENT", _SC_MMAP_FIXED_ALIGNMENT},
Fred Draked86ed291999-12-15 15:34:33 +000011093#endif
Fred Drakec9680921999-12-13 16:37:25 +000011094#ifdef _SC_MQ_OPEN_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011095 {"SC_MQ_OPEN_MAX", _SC_MQ_OPEN_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011096#endif
11097#ifdef _SC_MQ_PRIO_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011098 {"SC_MQ_PRIO_MAX", _SC_MQ_PRIO_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011099#endif
Fred Draked86ed291999-12-15 15:34:33 +000011100#ifdef _SC_NACLS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011101 {"SC_NACLS_MAX", _SC_NACLS_MAX},
Fred Draked86ed291999-12-15 15:34:33 +000011102#endif
Fred Drakec9680921999-12-13 16:37:25 +000011103#ifdef _SC_NGROUPS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011104 {"SC_NGROUPS_MAX", _SC_NGROUPS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011105#endif
11106#ifdef _SC_NL_ARGMAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011107 {"SC_NL_ARGMAX", _SC_NL_ARGMAX},
Fred Drakec9680921999-12-13 16:37:25 +000011108#endif
11109#ifdef _SC_NL_LANGMAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011110 {"SC_NL_LANGMAX", _SC_NL_LANGMAX},
Fred Drakec9680921999-12-13 16:37:25 +000011111#endif
11112#ifdef _SC_NL_MSGMAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011113 {"SC_NL_MSGMAX", _SC_NL_MSGMAX},
Fred Drakec9680921999-12-13 16:37:25 +000011114#endif
11115#ifdef _SC_NL_NMAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011116 {"SC_NL_NMAX", _SC_NL_NMAX},
Fred Drakec9680921999-12-13 16:37:25 +000011117#endif
11118#ifdef _SC_NL_SETMAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011119 {"SC_NL_SETMAX", _SC_NL_SETMAX},
Fred Drakec9680921999-12-13 16:37:25 +000011120#endif
11121#ifdef _SC_NL_TEXTMAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011122 {"SC_NL_TEXTMAX", _SC_NL_TEXTMAX},
Fred Drakec9680921999-12-13 16:37:25 +000011123#endif
11124#ifdef _SC_NPROCESSORS_CONF
Victor Stinner8c62be82010-05-06 00:08:46 +000011125 {"SC_NPROCESSORS_CONF", _SC_NPROCESSORS_CONF},
Fred Drakec9680921999-12-13 16:37:25 +000011126#endif
11127#ifdef _SC_NPROCESSORS_ONLN
Victor Stinner8c62be82010-05-06 00:08:46 +000011128 {"SC_NPROCESSORS_ONLN", _SC_NPROCESSORS_ONLN},
Fred Drakec9680921999-12-13 16:37:25 +000011129#endif
Fred Draked86ed291999-12-15 15:34:33 +000011130#ifdef _SC_NPROC_CONF
Victor Stinner8c62be82010-05-06 00:08:46 +000011131 {"SC_NPROC_CONF", _SC_NPROC_CONF},
Fred Draked86ed291999-12-15 15:34:33 +000011132#endif
11133#ifdef _SC_NPROC_ONLN
Victor Stinner8c62be82010-05-06 00:08:46 +000011134 {"SC_NPROC_ONLN", _SC_NPROC_ONLN},
Fred Draked86ed291999-12-15 15:34:33 +000011135#endif
Fred Drakec9680921999-12-13 16:37:25 +000011136#ifdef _SC_NZERO
Victor Stinner8c62be82010-05-06 00:08:46 +000011137 {"SC_NZERO", _SC_NZERO},
Fred Drakec9680921999-12-13 16:37:25 +000011138#endif
11139#ifdef _SC_OPEN_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011140 {"SC_OPEN_MAX", _SC_OPEN_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011141#endif
11142#ifdef _SC_PAGESIZE
Victor Stinner8c62be82010-05-06 00:08:46 +000011143 {"SC_PAGESIZE", _SC_PAGESIZE},
Fred Drakec9680921999-12-13 16:37:25 +000011144#endif
11145#ifdef _SC_PAGE_SIZE
Victor Stinner8c62be82010-05-06 00:08:46 +000011146 {"SC_PAGE_SIZE", _SC_PAGE_SIZE},
Fred Drakec9680921999-12-13 16:37:25 +000011147#endif
11148#ifdef _SC_PASS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011149 {"SC_PASS_MAX", _SC_PASS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011150#endif
11151#ifdef _SC_PHYS_PAGES
Victor Stinner8c62be82010-05-06 00:08:46 +000011152 {"SC_PHYS_PAGES", _SC_PHYS_PAGES},
Fred Drakec9680921999-12-13 16:37:25 +000011153#endif
11154#ifdef _SC_PII
Victor Stinner8c62be82010-05-06 00:08:46 +000011155 {"SC_PII", _SC_PII},
Fred Drakec9680921999-12-13 16:37:25 +000011156#endif
11157#ifdef _SC_PII_INTERNET
Victor Stinner8c62be82010-05-06 00:08:46 +000011158 {"SC_PII_INTERNET", _SC_PII_INTERNET},
Fred Drakec9680921999-12-13 16:37:25 +000011159#endif
11160#ifdef _SC_PII_INTERNET_DGRAM
Victor Stinner8c62be82010-05-06 00:08:46 +000011161 {"SC_PII_INTERNET_DGRAM", _SC_PII_INTERNET_DGRAM},
Fred Drakec9680921999-12-13 16:37:25 +000011162#endif
11163#ifdef _SC_PII_INTERNET_STREAM
Victor Stinner8c62be82010-05-06 00:08:46 +000011164 {"SC_PII_INTERNET_STREAM", _SC_PII_INTERNET_STREAM},
Fred Drakec9680921999-12-13 16:37:25 +000011165#endif
11166#ifdef _SC_PII_OSI
Victor Stinner8c62be82010-05-06 00:08:46 +000011167 {"SC_PII_OSI", _SC_PII_OSI},
Fred Drakec9680921999-12-13 16:37:25 +000011168#endif
11169#ifdef _SC_PII_OSI_CLTS
Victor Stinner8c62be82010-05-06 00:08:46 +000011170 {"SC_PII_OSI_CLTS", _SC_PII_OSI_CLTS},
Fred Drakec9680921999-12-13 16:37:25 +000011171#endif
11172#ifdef _SC_PII_OSI_COTS
Victor Stinner8c62be82010-05-06 00:08:46 +000011173 {"SC_PII_OSI_COTS", _SC_PII_OSI_COTS},
Fred Drakec9680921999-12-13 16:37:25 +000011174#endif
11175#ifdef _SC_PII_OSI_M
Victor Stinner8c62be82010-05-06 00:08:46 +000011176 {"SC_PII_OSI_M", _SC_PII_OSI_M},
Fred Drakec9680921999-12-13 16:37:25 +000011177#endif
11178#ifdef _SC_PII_SOCKET
Victor Stinner8c62be82010-05-06 00:08:46 +000011179 {"SC_PII_SOCKET", _SC_PII_SOCKET},
Fred Drakec9680921999-12-13 16:37:25 +000011180#endif
11181#ifdef _SC_PII_XTI
Victor Stinner8c62be82010-05-06 00:08:46 +000011182 {"SC_PII_XTI", _SC_PII_XTI},
Fred Drakec9680921999-12-13 16:37:25 +000011183#endif
11184#ifdef _SC_POLL
Victor Stinner8c62be82010-05-06 00:08:46 +000011185 {"SC_POLL", _SC_POLL},
Fred Drakec9680921999-12-13 16:37:25 +000011186#endif
11187#ifdef _SC_PRIORITIZED_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000011188 {"SC_PRIORITIZED_IO", _SC_PRIORITIZED_IO},
Fred Drakec9680921999-12-13 16:37:25 +000011189#endif
11190#ifdef _SC_PRIORITY_SCHEDULING
Victor Stinner8c62be82010-05-06 00:08:46 +000011191 {"SC_PRIORITY_SCHEDULING", _SC_PRIORITY_SCHEDULING},
Fred Drakec9680921999-12-13 16:37:25 +000011192#endif
11193#ifdef _SC_REALTIME_SIGNALS
Victor Stinner8c62be82010-05-06 00:08:46 +000011194 {"SC_REALTIME_SIGNALS", _SC_REALTIME_SIGNALS},
Fred Drakec9680921999-12-13 16:37:25 +000011195#endif
11196#ifdef _SC_RE_DUP_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011197 {"SC_RE_DUP_MAX", _SC_RE_DUP_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011198#endif
11199#ifdef _SC_RTSIG_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011200 {"SC_RTSIG_MAX", _SC_RTSIG_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011201#endif
11202#ifdef _SC_SAVED_IDS
Victor Stinner8c62be82010-05-06 00:08:46 +000011203 {"SC_SAVED_IDS", _SC_SAVED_IDS},
Fred Drakec9680921999-12-13 16:37:25 +000011204#endif
11205#ifdef _SC_SCHAR_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011206 {"SC_SCHAR_MAX", _SC_SCHAR_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011207#endif
11208#ifdef _SC_SCHAR_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000011209 {"SC_SCHAR_MIN", _SC_SCHAR_MIN},
Fred Drakec9680921999-12-13 16:37:25 +000011210#endif
11211#ifdef _SC_SELECT
Victor Stinner8c62be82010-05-06 00:08:46 +000011212 {"SC_SELECT", _SC_SELECT},
Fred Drakec9680921999-12-13 16:37:25 +000011213#endif
11214#ifdef _SC_SEMAPHORES
Victor Stinner8c62be82010-05-06 00:08:46 +000011215 {"SC_SEMAPHORES", _SC_SEMAPHORES},
Fred Drakec9680921999-12-13 16:37:25 +000011216#endif
11217#ifdef _SC_SEM_NSEMS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011218 {"SC_SEM_NSEMS_MAX", _SC_SEM_NSEMS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011219#endif
11220#ifdef _SC_SEM_VALUE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011221 {"SC_SEM_VALUE_MAX", _SC_SEM_VALUE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011222#endif
11223#ifdef _SC_SHARED_MEMORY_OBJECTS
Victor Stinner8c62be82010-05-06 00:08:46 +000011224 {"SC_SHARED_MEMORY_OBJECTS", _SC_SHARED_MEMORY_OBJECTS},
Fred Drakec9680921999-12-13 16:37:25 +000011225#endif
11226#ifdef _SC_SHRT_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011227 {"SC_SHRT_MAX", _SC_SHRT_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011228#endif
11229#ifdef _SC_SHRT_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000011230 {"SC_SHRT_MIN", _SC_SHRT_MIN},
Fred Drakec9680921999-12-13 16:37:25 +000011231#endif
11232#ifdef _SC_SIGQUEUE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011233 {"SC_SIGQUEUE_MAX", _SC_SIGQUEUE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011234#endif
11235#ifdef _SC_SIGRT_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011236 {"SC_SIGRT_MAX", _SC_SIGRT_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011237#endif
11238#ifdef _SC_SIGRT_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000011239 {"SC_SIGRT_MIN", _SC_SIGRT_MIN},
Fred Drakec9680921999-12-13 16:37:25 +000011240#endif
Fred Draked86ed291999-12-15 15:34:33 +000011241#ifdef _SC_SOFTPOWER
Victor Stinner8c62be82010-05-06 00:08:46 +000011242 {"SC_SOFTPOWER", _SC_SOFTPOWER},
Fred Draked86ed291999-12-15 15:34:33 +000011243#endif
Fred Drakec9680921999-12-13 16:37:25 +000011244#ifdef _SC_SPLIT_CACHE
Victor Stinner8c62be82010-05-06 00:08:46 +000011245 {"SC_SPLIT_CACHE", _SC_SPLIT_CACHE},
Fred Drakec9680921999-12-13 16:37:25 +000011246#endif
11247#ifdef _SC_SSIZE_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011248 {"SC_SSIZE_MAX", _SC_SSIZE_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011249#endif
11250#ifdef _SC_STACK_PROT
Victor Stinner8c62be82010-05-06 00:08:46 +000011251 {"SC_STACK_PROT", _SC_STACK_PROT},
Fred Drakec9680921999-12-13 16:37:25 +000011252#endif
11253#ifdef _SC_STREAM_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011254 {"SC_STREAM_MAX", _SC_STREAM_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011255#endif
11256#ifdef _SC_SYNCHRONIZED_IO
Victor Stinner8c62be82010-05-06 00:08:46 +000011257 {"SC_SYNCHRONIZED_IO", _SC_SYNCHRONIZED_IO},
Fred Drakec9680921999-12-13 16:37:25 +000011258#endif
11259#ifdef _SC_THREADS
Victor Stinner8c62be82010-05-06 00:08:46 +000011260 {"SC_THREADS", _SC_THREADS},
Fred Drakec9680921999-12-13 16:37:25 +000011261#endif
11262#ifdef _SC_THREAD_ATTR_STACKADDR
Victor Stinner8c62be82010-05-06 00:08:46 +000011263 {"SC_THREAD_ATTR_STACKADDR", _SC_THREAD_ATTR_STACKADDR},
Fred Drakec9680921999-12-13 16:37:25 +000011264#endif
11265#ifdef _SC_THREAD_ATTR_STACKSIZE
Victor Stinner8c62be82010-05-06 00:08:46 +000011266 {"SC_THREAD_ATTR_STACKSIZE", _SC_THREAD_ATTR_STACKSIZE},
Fred Drakec9680921999-12-13 16:37:25 +000011267#endif
11268#ifdef _SC_THREAD_DESTRUCTOR_ITERATIONS
Victor Stinner8c62be82010-05-06 00:08:46 +000011269 {"SC_THREAD_DESTRUCTOR_ITERATIONS", _SC_THREAD_DESTRUCTOR_ITERATIONS},
Fred Drakec9680921999-12-13 16:37:25 +000011270#endif
11271#ifdef _SC_THREAD_KEYS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011272 {"SC_THREAD_KEYS_MAX", _SC_THREAD_KEYS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011273#endif
11274#ifdef _SC_THREAD_PRIORITY_SCHEDULING
Victor Stinner8c62be82010-05-06 00:08:46 +000011275 {"SC_THREAD_PRIORITY_SCHEDULING", _SC_THREAD_PRIORITY_SCHEDULING},
Fred Drakec9680921999-12-13 16:37:25 +000011276#endif
11277#ifdef _SC_THREAD_PRIO_INHERIT
Victor Stinner8c62be82010-05-06 00:08:46 +000011278 {"SC_THREAD_PRIO_INHERIT", _SC_THREAD_PRIO_INHERIT},
Fred Drakec9680921999-12-13 16:37:25 +000011279#endif
11280#ifdef _SC_THREAD_PRIO_PROTECT
Victor Stinner8c62be82010-05-06 00:08:46 +000011281 {"SC_THREAD_PRIO_PROTECT", _SC_THREAD_PRIO_PROTECT},
Fred Drakec9680921999-12-13 16:37:25 +000011282#endif
11283#ifdef _SC_THREAD_PROCESS_SHARED
Victor Stinner8c62be82010-05-06 00:08:46 +000011284 {"SC_THREAD_PROCESS_SHARED", _SC_THREAD_PROCESS_SHARED},
Fred Drakec9680921999-12-13 16:37:25 +000011285#endif
11286#ifdef _SC_THREAD_SAFE_FUNCTIONS
Victor Stinner8c62be82010-05-06 00:08:46 +000011287 {"SC_THREAD_SAFE_FUNCTIONS", _SC_THREAD_SAFE_FUNCTIONS},
Fred Drakec9680921999-12-13 16:37:25 +000011288#endif
11289#ifdef _SC_THREAD_STACK_MIN
Victor Stinner8c62be82010-05-06 00:08:46 +000011290 {"SC_THREAD_STACK_MIN", _SC_THREAD_STACK_MIN},
Fred Drakec9680921999-12-13 16:37:25 +000011291#endif
11292#ifdef _SC_THREAD_THREADS_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011293 {"SC_THREAD_THREADS_MAX", _SC_THREAD_THREADS_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011294#endif
11295#ifdef _SC_TIMERS
Victor Stinner8c62be82010-05-06 00:08:46 +000011296 {"SC_TIMERS", _SC_TIMERS},
Fred Drakec9680921999-12-13 16:37:25 +000011297#endif
11298#ifdef _SC_TIMER_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011299 {"SC_TIMER_MAX", _SC_TIMER_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011300#endif
11301#ifdef _SC_TTY_NAME_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011302 {"SC_TTY_NAME_MAX", _SC_TTY_NAME_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011303#endif
11304#ifdef _SC_TZNAME_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011305 {"SC_TZNAME_MAX", _SC_TZNAME_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011306#endif
11307#ifdef _SC_T_IOV_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011308 {"SC_T_IOV_MAX", _SC_T_IOV_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011309#endif
11310#ifdef _SC_UCHAR_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011311 {"SC_UCHAR_MAX", _SC_UCHAR_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011312#endif
11313#ifdef _SC_UINT_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011314 {"SC_UINT_MAX", _SC_UINT_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011315#endif
11316#ifdef _SC_UIO_MAXIOV
Victor Stinner8c62be82010-05-06 00:08:46 +000011317 {"SC_UIO_MAXIOV", _SC_UIO_MAXIOV},
Fred Drakec9680921999-12-13 16:37:25 +000011318#endif
11319#ifdef _SC_ULONG_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011320 {"SC_ULONG_MAX", _SC_ULONG_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011321#endif
11322#ifdef _SC_USHRT_MAX
Victor Stinner8c62be82010-05-06 00:08:46 +000011323 {"SC_USHRT_MAX", _SC_USHRT_MAX},
Fred Drakec9680921999-12-13 16:37:25 +000011324#endif
11325#ifdef _SC_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000011326 {"SC_VERSION", _SC_VERSION},
Fred Drakec9680921999-12-13 16:37:25 +000011327#endif
11328#ifdef _SC_WORD_BIT
Victor Stinner8c62be82010-05-06 00:08:46 +000011329 {"SC_WORD_BIT", _SC_WORD_BIT},
Fred Drakec9680921999-12-13 16:37:25 +000011330#endif
11331#ifdef _SC_XBS5_ILP32_OFF32
Victor Stinner8c62be82010-05-06 00:08:46 +000011332 {"SC_XBS5_ILP32_OFF32", _SC_XBS5_ILP32_OFF32},
Fred Drakec9680921999-12-13 16:37:25 +000011333#endif
11334#ifdef _SC_XBS5_ILP32_OFFBIG
Victor Stinner8c62be82010-05-06 00:08:46 +000011335 {"SC_XBS5_ILP32_OFFBIG", _SC_XBS5_ILP32_OFFBIG},
Fred Drakec9680921999-12-13 16:37:25 +000011336#endif
11337#ifdef _SC_XBS5_LP64_OFF64
Victor Stinner8c62be82010-05-06 00:08:46 +000011338 {"SC_XBS5_LP64_OFF64", _SC_XBS5_LP64_OFF64},
Fred Drakec9680921999-12-13 16:37:25 +000011339#endif
11340#ifdef _SC_XBS5_LPBIG_OFFBIG
Victor Stinner8c62be82010-05-06 00:08:46 +000011341 {"SC_XBS5_LPBIG_OFFBIG", _SC_XBS5_LPBIG_OFFBIG},
Fred Drakec9680921999-12-13 16:37:25 +000011342#endif
11343#ifdef _SC_XOPEN_CRYPT
Victor Stinner8c62be82010-05-06 00:08:46 +000011344 {"SC_XOPEN_CRYPT", _SC_XOPEN_CRYPT},
Fred Drakec9680921999-12-13 16:37:25 +000011345#endif
11346#ifdef _SC_XOPEN_ENH_I18N
Victor Stinner8c62be82010-05-06 00:08:46 +000011347 {"SC_XOPEN_ENH_I18N", _SC_XOPEN_ENH_I18N},
Fred Drakec9680921999-12-13 16:37:25 +000011348#endif
11349#ifdef _SC_XOPEN_LEGACY
Victor Stinner8c62be82010-05-06 00:08:46 +000011350 {"SC_XOPEN_LEGACY", _SC_XOPEN_LEGACY},
Fred Drakec9680921999-12-13 16:37:25 +000011351#endif
11352#ifdef _SC_XOPEN_REALTIME
Victor Stinner8c62be82010-05-06 00:08:46 +000011353 {"SC_XOPEN_REALTIME", _SC_XOPEN_REALTIME},
Fred Drakec9680921999-12-13 16:37:25 +000011354#endif
11355#ifdef _SC_XOPEN_REALTIME_THREADS
Victor Stinner8c62be82010-05-06 00:08:46 +000011356 {"SC_XOPEN_REALTIME_THREADS", _SC_XOPEN_REALTIME_THREADS},
Fred Drakec9680921999-12-13 16:37:25 +000011357#endif
11358#ifdef _SC_XOPEN_SHM
Victor Stinner8c62be82010-05-06 00:08:46 +000011359 {"SC_XOPEN_SHM", _SC_XOPEN_SHM},
Fred Drakec9680921999-12-13 16:37:25 +000011360#endif
11361#ifdef _SC_XOPEN_UNIX
Victor Stinner8c62be82010-05-06 00:08:46 +000011362 {"SC_XOPEN_UNIX", _SC_XOPEN_UNIX},
Fred Drakec9680921999-12-13 16:37:25 +000011363#endif
11364#ifdef _SC_XOPEN_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000011365 {"SC_XOPEN_VERSION", _SC_XOPEN_VERSION},
Fred Drakec9680921999-12-13 16:37:25 +000011366#endif
11367#ifdef _SC_XOPEN_XCU_VERSION
Victor Stinner8c62be82010-05-06 00:08:46 +000011368 {"SC_XOPEN_XCU_VERSION", _SC_XOPEN_XCU_VERSION},
Fred Drakec9680921999-12-13 16:37:25 +000011369#endif
11370#ifdef _SC_XOPEN_XPG2
Victor Stinner8c62be82010-05-06 00:08:46 +000011371 {"SC_XOPEN_XPG2", _SC_XOPEN_XPG2},
Fred Drakec9680921999-12-13 16:37:25 +000011372#endif
11373#ifdef _SC_XOPEN_XPG3
Victor Stinner8c62be82010-05-06 00:08:46 +000011374 {"SC_XOPEN_XPG3", _SC_XOPEN_XPG3},
Fred Drakec9680921999-12-13 16:37:25 +000011375#endif
11376#ifdef _SC_XOPEN_XPG4
Victor Stinner8c62be82010-05-06 00:08:46 +000011377 {"SC_XOPEN_XPG4", _SC_XOPEN_XPG4},
Fred Drakec9680921999-12-13 16:37:25 +000011378#endif
11379};
11380
11381static int
Fredrik Lundhff7df9d2000-07-08 22:48:53 +000011382conv_sysconf_confname(PyObject *arg, int *valuep)
Fred Drakec9680921999-12-13 16:37:25 +000011383{
11384 return conv_confname(arg, valuep, posix_constants_sysconf,
11385 sizeof(posix_constants_sysconf)
11386 / sizeof(struct constdef));
11387}
11388
Larry Hastings2f936352014-08-05 14:04:04 +100011389
11390/*[clinic input]
11391os.sysconf -> long
11392 name: sysconf_confname
11393 /
11394
11395Return an integer-valued system configuration variable.
11396[clinic start generated code]*/
11397
Larry Hastings2f936352014-08-05 14:04:04 +100011398static long
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011399os_sysconf_impl(PyObject *module, int name)
11400/*[clinic end generated code: output=3662f945fc0cc756 input=279e3430a33f29e4]*/
Larry Hastings2f936352014-08-05 14:04:04 +100011401{
11402 long value;
11403
11404 errno = 0;
11405 value = sysconf(name);
11406 if (value == -1 && errno != 0)
11407 posix_error();
11408 return value;
11409}
11410#endif /* HAVE_SYSCONF */
Fred Drakec9680921999-12-13 16:37:25 +000011411
11412
Fred Drakebec628d1999-12-15 18:31:10 +000011413/* This code is used to ensure that the tables of configuration value names
Serhiy Storchaka56a6d852014-12-01 18:28:43 +020011414 * are in sorted order as required by conv_confname(), and also to build
Fred Drakebec628d1999-12-15 18:31:10 +000011415 * the exported dictionaries that are used to publish information about the
11416 * names available on the host platform.
11417 *
11418 * Sorting the table at runtime ensures that the table is properly ordered
11419 * when used, even for platforms we're not able to test on. It also makes
11420 * it easier to add additional entries to the tables.
Fred Draked86ed291999-12-15 15:34:33 +000011421 */
Fred Drakebec628d1999-12-15 18:31:10 +000011422
11423static int
Fredrik Lundhff7df9d2000-07-08 22:48:53 +000011424cmp_constdefs(const void *v1, const void *v2)
Fred Drakebec628d1999-12-15 18:31:10 +000011425{
11426 const struct constdef *c1 =
Victor Stinner8c62be82010-05-06 00:08:46 +000011427 (const struct constdef *) v1;
Fred Drakebec628d1999-12-15 18:31:10 +000011428 const struct constdef *c2 =
Victor Stinner8c62be82010-05-06 00:08:46 +000011429 (const struct constdef *) v2;
Fred Drakebec628d1999-12-15 18:31:10 +000011430
11431 return strcmp(c1->name, c2->name);
11432}
11433
11434static int
Fredrik Lundhff7df9d2000-07-08 22:48:53 +000011435setup_confname_table(struct constdef *table, size_t tablesize,
Serhiy Storchakadeab18d2016-05-07 16:45:18 +030011436 const char *tablename, PyObject *module)
Fred Draked86ed291999-12-15 15:34:33 +000011437{
Fred Drakebec628d1999-12-15 18:31:10 +000011438 PyObject *d = NULL;
Barry Warsaw3155db32000-04-13 15:20:40 +000011439 size_t i;
Fred Drakebec628d1999-12-15 18:31:10 +000011440
11441 qsort(table, tablesize, sizeof(struct constdef), cmp_constdefs);
11442 d = PyDict_New();
Barry Warsaw3155db32000-04-13 15:20:40 +000011443 if (d == NULL)
Victor Stinner8c62be82010-05-06 00:08:46 +000011444 return -1;
Fred Draked86ed291999-12-15 15:34:33 +000011445
Barry Warsaw3155db32000-04-13 15:20:40 +000011446 for (i=0; i < tablesize; ++i) {
Victor Stinner8c62be82010-05-06 00:08:46 +000011447 PyObject *o = PyLong_FromLong(table[i].value);
11448 if (o == NULL || PyDict_SetItemString(d, table[i].name, o) == -1) {
11449 Py_XDECREF(o);
11450 Py_DECREF(d);
11451 return -1;
11452 }
11453 Py_DECREF(o);
Fred Draked86ed291999-12-15 15:34:33 +000011454 }
Fred Drake4d1e64b2002-04-15 19:40:07 +000011455 return PyModule_AddObject(module, tablename, d);
Fred Draked86ed291999-12-15 15:34:33 +000011456}
11457
Fred Drakebec628d1999-12-15 18:31:10 +000011458/* Return -1 on failure, 0 on success. */
11459static int
Fred Drake4d1e64b2002-04-15 19:40:07 +000011460setup_confname_tables(PyObject *module)
Fred Draked86ed291999-12-15 15:34:33 +000011461{
11462#if defined(HAVE_FPATHCONF) || defined(HAVE_PATHCONF)
Fred Drakebec628d1999-12-15 18:31:10 +000011463 if (setup_confname_table(posix_constants_pathconf,
Fred Draked86ed291999-12-15 15:34:33 +000011464 sizeof(posix_constants_pathconf)
11465 / sizeof(struct constdef),
Fred Drake4d1e64b2002-04-15 19:40:07 +000011466 "pathconf_names", module))
Stefan Krah0e803b32010-11-26 16:16:47 +000011467 return -1;
Fred Draked86ed291999-12-15 15:34:33 +000011468#endif
11469#ifdef HAVE_CONFSTR
Fred Drakebec628d1999-12-15 18:31:10 +000011470 if (setup_confname_table(posix_constants_confstr,
Fred Draked86ed291999-12-15 15:34:33 +000011471 sizeof(posix_constants_confstr)
11472 / sizeof(struct constdef),
Fred Drake4d1e64b2002-04-15 19:40:07 +000011473 "confstr_names", module))
Stefan Krah0e803b32010-11-26 16:16:47 +000011474 return -1;
Fred Draked86ed291999-12-15 15:34:33 +000011475#endif
11476#ifdef HAVE_SYSCONF
Fred Drakebec628d1999-12-15 18:31:10 +000011477 if (setup_confname_table(posix_constants_sysconf,
Fred Draked86ed291999-12-15 15:34:33 +000011478 sizeof(posix_constants_sysconf)
11479 / sizeof(struct constdef),
Fred Drake4d1e64b2002-04-15 19:40:07 +000011480 "sysconf_names", module))
Stefan Krah0e803b32010-11-26 16:16:47 +000011481 return -1;
Fred Draked86ed291999-12-15 15:34:33 +000011482#endif
Fred Drakebec628d1999-12-15 18:31:10 +000011483 return 0;
Fred Draked86ed291999-12-15 15:34:33 +000011484}
Fred Draked86ed291999-12-15 15:34:33 +000011485
11486
Larry Hastings2f936352014-08-05 14:04:04 +100011487/*[clinic input]
11488os.abort
11489
11490Abort the interpreter immediately.
11491
11492This function 'dumps core' or otherwise fails in the hardest way possible
11493on the hosting operating system. This function never returns.
11494[clinic start generated code]*/
11495
Larry Hastings2f936352014-08-05 14:04:04 +100011496static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011497os_abort_impl(PyObject *module)
11498/*[clinic end generated code: output=dcf52586dad2467c input=cf2c7d98bc504047]*/
Fred Drake5ab8eaf1999-12-09 21:13:07 +000011499{
Fred Drake5ab8eaf1999-12-09 21:13:07 +000011500 abort();
11501 /*NOTREACHED*/
Victor Stinner9a2329f2016-12-05 17:56:36 +010011502#ifndef __clang__
11503 /* Issue #28152: abort() is declared with __attribute__((__noreturn__)).
11504 GCC emits a warning without "return NULL;" (compiler bug?), but Clang
11505 is smarter and emits a warning on the return. */
Fred Drake5ab8eaf1999-12-09 21:13:07 +000011506 Py_FatalError("abort() called from Python code didn't abort!");
11507 return NULL;
Victor Stinner9a2329f2016-12-05 17:56:36 +010011508#endif
Fred Drake5ab8eaf1999-12-09 21:13:07 +000011509}
Fred Drakebec628d1999-12-15 18:31:10 +000011510
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000011511#ifdef MS_WINDOWS
Steve Dower7d0e0c92015-01-24 08:18:24 -080011512/* Grab ShellExecute dynamically from shell32 */
11513static int has_ShellExecute = -1;
Steve Dower7d0e0c92015-01-24 08:18:24 -080011514static HINSTANCE (CALLBACK *Py_ShellExecuteW)(HWND, LPCWSTR, LPCWSTR, LPCWSTR,
11515 LPCWSTR, INT);
11516static int
11517check_ShellExecute()
11518{
11519 HINSTANCE hShell32;
11520
11521 /* only recheck */
11522 if (-1 == has_ShellExecute) {
11523 Py_BEGIN_ALLOW_THREADS
Victor Stinnera9912152017-10-13 13:46:57 -070011524 /* Security note: this call is not vulnerable to "DLL hijacking".
11525 SHELL32 is part of "KnownDLLs" and so Windows always load
11526 the system SHELL32.DLL, even if there is another SHELL32.DLL
11527 in the DLL search path. */
Steve Dower7d0e0c92015-01-24 08:18:24 -080011528 hShell32 = LoadLibraryW(L"SHELL32");
Steve Dower7d0e0c92015-01-24 08:18:24 -080011529 if (hShell32) {
Steve Dower7d0e0c92015-01-24 08:18:24 -080011530 *(FARPROC*)&Py_ShellExecuteW = GetProcAddress(hShell32,
11531 "ShellExecuteW");
Steve Dowercc16be82016-09-08 10:35:16 -070011532 has_ShellExecute = Py_ShellExecuteW != NULL;
Steve Dower7d0e0c92015-01-24 08:18:24 -080011533 } else {
11534 has_ShellExecute = 0;
11535 }
Tony Roberts4860f012019-02-02 18:16:42 +010011536 Py_END_ALLOW_THREADS
Steve Dower7d0e0c92015-01-24 08:18:24 -080011537 }
11538 return has_ShellExecute;
11539}
11540
11541
Steve Dowercc16be82016-09-08 10:35:16 -070011542/*[clinic input]
11543os.startfile
11544 filepath: path_t
11545 operation: Py_UNICODE = NULL
Hirokazu Yamamoto8223c242009-05-17 04:21:53 +000011546
Steve Dowercc16be82016-09-08 10:35:16 -070011547startfile(filepath [, operation])
11548
11549Start a file with its associated application.
11550
11551When "operation" is not specified or "open", this acts like
11552double-clicking the file in Explorer, or giving the file name as an
11553argument to the DOS "start" command: the file is opened with whatever
11554application (if any) its extension is associated.
11555When another "operation" is given, it specifies what should be done with
11556the file. A typical operation is "print".
11557
11558startfile returns as soon as the associated application is launched.
11559There is no option to wait for the application to close, and no way
11560to retrieve the application's exit status.
11561
11562The filepath is relative to the current directory. If you want to use
11563an absolute path, make sure the first character is not a slash ("/");
11564the underlying Win32 ShellExecute function doesn't work if it is.
11565[clinic start generated code]*/
11566
11567static PyObject *
Serhiy Storchakaafb3e712018-12-14 11:19:51 +020011568os_startfile_impl(PyObject *module, path_t *filepath,
11569 const Py_UNICODE *operation)
11570/*[clinic end generated code: output=66dc311c94d50797 input=63950bf2986380d0]*/
Steve Dowercc16be82016-09-08 10:35:16 -070011571{
11572 HINSTANCE rc;
Steve Dower7d0e0c92015-01-24 08:18:24 -080011573
11574 if(!check_ShellExecute()) {
11575 /* If the OS doesn't have ShellExecute, return a
11576 NotImplementedError. */
11577 return PyErr_Format(PyExc_NotImplementedError,
11578 "startfile not available on this platform");
11579 }
11580
Victor Stinner8c62be82010-05-06 00:08:46 +000011581 Py_BEGIN_ALLOW_THREADS
Steve Dowercc16be82016-09-08 10:35:16 -070011582 rc = Py_ShellExecuteW((HWND)0, operation, filepath->wide,
Steve Dower7d0e0c92015-01-24 08:18:24 -080011583 NULL, NULL, SW_SHOWNORMAL);
Victor Stinner8c62be82010-05-06 00:08:46 +000011584 Py_END_ALLOW_THREADS
11585
Victor Stinner8c62be82010-05-06 00:08:46 +000011586 if (rc <= (HINSTANCE)32) {
Steve Dowercc16be82016-09-08 10:35:16 -070011587 win32_error_object("startfile", filepath->object);
Victor Stinnereb5657a2011-09-30 01:44:27 +020011588 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +000011589 }
Steve Dowercc16be82016-09-08 10:35:16 -070011590 Py_RETURN_NONE;
Tim Petersf58a7aa2000-09-22 10:05:54 +000011591}
Larry Hastings2f936352014-08-05 14:04:04 +100011592#endif /* MS_WINDOWS */
11593
Fred Drake5ab8eaf1999-12-09 21:13:07 +000011594
Martin v. Löwis438b5342002-12-27 10:16:42 +000011595#ifdef HAVE_GETLOADAVG
Larry Hastings2f936352014-08-05 14:04:04 +100011596/*[clinic input]
11597os.getloadavg
11598
11599Return average recent system load information.
11600
11601Return the number of processes in the system run queue averaged over
11602the last 1, 5, and 15 minutes as a tuple of three floats.
11603Raises OSError if the load average was unobtainable.
11604[clinic start generated code]*/
11605
Larry Hastings2f936352014-08-05 14:04:04 +100011606static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011607os_getloadavg_impl(PyObject *module)
11608/*[clinic end generated code: output=9ad3a11bfb4f4bd2 input=3d6d826b76d8a34e]*/
Martin v. Löwis438b5342002-12-27 10:16:42 +000011609{
11610 double loadavg[3];
Martin v. Löwis438b5342002-12-27 10:16:42 +000011611 if (getloadavg(loadavg, 3)!=3) {
Stefan Krah0e803b32010-11-26 16:16:47 +000011612 PyErr_SetString(PyExc_OSError, "Load averages are unobtainable");
11613 return NULL;
Martin v. Löwis438b5342002-12-27 10:16:42 +000011614 } else
Stefan Krah0e803b32010-11-26 16:16:47 +000011615 return Py_BuildValue("ddd", loadavg[0], loadavg[1], loadavg[2]);
Martin v. Löwis438b5342002-12-27 10:16:42 +000011616}
Larry Hastings2f936352014-08-05 14:04:04 +100011617#endif /* HAVE_GETLOADAVG */
Martin v. Löwis438b5342002-12-27 10:16:42 +000011618
Larry Hastings2f936352014-08-05 14:04:04 +100011619
11620/*[clinic input]
11621os.device_encoding
11622 fd: int
11623
11624Return a string describing the encoding of a terminal's file descriptor.
11625
11626The file descriptor must be attached to a terminal.
11627If the device is not a terminal, return None.
11628[clinic start generated code]*/
11629
Larry Hastings2f936352014-08-05 14:04:04 +100011630static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011631os_device_encoding_impl(PyObject *module, int fd)
11632/*[clinic end generated code: output=e0d294bbab7e8c2b input=9e1d4a42b66df312]*/
Larry Hastings2f936352014-08-05 14:04:04 +100011633{
Brett Cannonefb00c02012-02-29 18:31:31 -050011634 return _Py_device_encoding(fd);
Martin v. Löwisd1cd4d42007-08-11 14:02:14 +000011635}
11636
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011637
Larry Hastings2f936352014-08-05 14:04:04 +100011638#ifdef HAVE_SETRESUID
11639/*[clinic input]
11640os.setresuid
11641
11642 ruid: uid_t
11643 euid: uid_t
11644 suid: uid_t
11645 /
11646
11647Set the current process's real, effective, and saved user ids.
11648[clinic start generated code]*/
11649
Larry Hastings2f936352014-08-05 14:04:04 +100011650static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011651os_setresuid_impl(PyObject *module, uid_t ruid, uid_t euid, uid_t suid)
11652/*[clinic end generated code: output=834a641e15373e97 input=9e33cb79a82792f3]*/
Larry Hastings2f936352014-08-05 14:04:04 +100011653{
Victor Stinner8c62be82010-05-06 00:08:46 +000011654 if (setresuid(ruid, euid, suid) < 0)
11655 return posix_error();
11656 Py_RETURN_NONE;
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011657}
Larry Hastings2f936352014-08-05 14:04:04 +100011658#endif /* HAVE_SETRESUID */
11659
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011660
11661#ifdef HAVE_SETRESGID
Larry Hastings2f936352014-08-05 14:04:04 +100011662/*[clinic input]
11663os.setresgid
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011664
Larry Hastings2f936352014-08-05 14:04:04 +100011665 rgid: gid_t
11666 egid: gid_t
11667 sgid: gid_t
11668 /
11669
11670Set the current process's real, effective, and saved group ids.
11671[clinic start generated code]*/
11672
Larry Hastings2f936352014-08-05 14:04:04 +100011673static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011674os_setresgid_impl(PyObject *module, gid_t rgid, gid_t egid, gid_t sgid)
11675/*[clinic end generated code: output=6aa402f3d2e514a9 input=33e9e0785ef426b1]*/
Larry Hastings2f936352014-08-05 14:04:04 +100011676{
Victor Stinner8c62be82010-05-06 00:08:46 +000011677 if (setresgid(rgid, egid, sgid) < 0)
11678 return posix_error();
11679 Py_RETURN_NONE;
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011680}
Larry Hastings2f936352014-08-05 14:04:04 +100011681#endif /* HAVE_SETRESGID */
11682
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011683
11684#ifdef HAVE_GETRESUID
Larry Hastings2f936352014-08-05 14:04:04 +100011685/*[clinic input]
11686os.getresuid
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011687
Larry Hastings2f936352014-08-05 14:04:04 +100011688Return a tuple of the current process's real, effective, and saved user ids.
11689[clinic start generated code]*/
11690
Larry Hastings2f936352014-08-05 14:04:04 +100011691static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011692os_getresuid_impl(PyObject *module)
11693/*[clinic end generated code: output=8e0becff5dece5bf input=41ccfa8e1f6517ad]*/
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011694{
Victor Stinner8c62be82010-05-06 00:08:46 +000011695 uid_t ruid, euid, suid;
Victor Stinner8c62be82010-05-06 00:08:46 +000011696 if (getresuid(&ruid, &euid, &suid) < 0)
11697 return posix_error();
Serhiy Storchaka7cf55992013-02-10 21:56:49 +020011698 return Py_BuildValue("(NNN)", _PyLong_FromUid(ruid),
11699 _PyLong_FromUid(euid),
11700 _PyLong_FromUid(suid));
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011701}
Larry Hastings2f936352014-08-05 14:04:04 +100011702#endif /* HAVE_GETRESUID */
11703
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011704
11705#ifdef HAVE_GETRESGID
Larry Hastings2f936352014-08-05 14:04:04 +100011706/*[clinic input]
11707os.getresgid
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011708
Larry Hastings2f936352014-08-05 14:04:04 +100011709Return a tuple of the current process's real, effective, and saved group ids.
11710[clinic start generated code]*/
11711
Larry Hastings2f936352014-08-05 14:04:04 +100011712static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011713os_getresgid_impl(PyObject *module)
11714/*[clinic end generated code: output=2719c4bfcf27fb9f input=517e68db9ca32df6]*/
Larry Hastings2f936352014-08-05 14:04:04 +100011715{
11716 gid_t rgid, egid, sgid;
Victor Stinner8c62be82010-05-06 00:08:46 +000011717 if (getresgid(&rgid, &egid, &sgid) < 0)
11718 return posix_error();
Serhiy Storchaka7cf55992013-02-10 21:56:49 +020011719 return Py_BuildValue("(NNN)", _PyLong_FromGid(rgid),
11720 _PyLong_FromGid(egid),
11721 _PyLong_FromGid(sgid));
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011722}
Larry Hastings2f936352014-08-05 14:04:04 +100011723#endif /* HAVE_GETRESGID */
11724
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000011725
Benjamin Peterson9428d532011-09-14 11:45:52 -040011726#ifdef USE_XATTRS
Larry Hastings2f936352014-08-05 14:04:04 +100011727/*[clinic input]
11728os.getxattr
Benjamin Peterson799bd802011-08-31 22:15:17 -040011729
Larry Hastings2f936352014-08-05 14:04:04 +100011730 path: path_t(allow_fd=True)
11731 attribute: path_t
11732 *
11733 follow_symlinks: bool = True
11734
11735Return the value of extended attribute attribute on path.
11736
BNMetricsb9427072018-11-02 15:20:19 +000011737path may be either a string, a path-like object, or an open file descriptor.
Larry Hastings2f936352014-08-05 14:04:04 +100011738If follow_symlinks is False, and the last element of the path is a symbolic
11739 link, getxattr will examine the symbolic link itself instead of the file
11740 the link points to.
11741
11742[clinic start generated code]*/
11743
Larry Hastings2f936352014-08-05 14:04:04 +100011744static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011745os_getxattr_impl(PyObject *module, path_t *path, path_t *attribute,
Larry Hastings89964c42015-04-14 18:07:59 -040011746 int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +000011747/*[clinic end generated code: output=5f2f44200a43cff2 input=025789491708f7eb]*/
Larry Hastings2f936352014-08-05 14:04:04 +100011748{
11749 Py_ssize_t i;
11750 PyObject *buffer = NULL;
11751
11752 if (fd_and_follow_symlinks_invalid("getxattr", path->fd, follow_symlinks))
11753 return NULL;
Benjamin Peterson799bd802011-08-31 22:15:17 -040011754
Larry Hastings9cf065c2012-06-22 16:30:09 -070011755 for (i = 0; ; i++) {
11756 void *ptr;
11757 ssize_t result;
Serhiy Storchaka2d06e842015-12-25 19:53:18 +020011758 static const Py_ssize_t buffer_sizes[] = {128, XATTR_SIZE_MAX, 0};
Larry Hastings9cf065c2012-06-22 16:30:09 -070011759 Py_ssize_t buffer_size = buffer_sizes[i];
11760 if (!buffer_size) {
Larry Hastings2f936352014-08-05 14:04:04 +100011761 path_error(path);
11762 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -070011763 }
11764 buffer = PyBytes_FromStringAndSize(NULL, buffer_size);
11765 if (!buffer)
Larry Hastings2f936352014-08-05 14:04:04 +100011766 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -070011767 ptr = PyBytes_AS_STRING(buffer);
Benjamin Peterson799bd802011-08-31 22:15:17 -040011768
Larry Hastings9cf065c2012-06-22 16:30:09 -070011769 Py_BEGIN_ALLOW_THREADS;
Larry Hastings2f936352014-08-05 14:04:04 +100011770 if (path->fd >= 0)
11771 result = fgetxattr(path->fd, attribute->narrow, ptr, buffer_size);
Larry Hastings9cf065c2012-06-22 16:30:09 -070011772 else if (follow_symlinks)
Larry Hastings2f936352014-08-05 14:04:04 +100011773 result = getxattr(path->narrow, attribute->narrow, ptr, buffer_size);
Larry Hastings9cf065c2012-06-22 16:30:09 -070011774 else
Larry Hastings2f936352014-08-05 14:04:04 +100011775 result = lgetxattr(path->narrow, attribute->narrow, ptr, buffer_size);
Larry Hastings9cf065c2012-06-22 16:30:09 -070011776 Py_END_ALLOW_THREADS;
Benjamin Peterson799bd802011-08-31 22:15:17 -040011777
Larry Hastings9cf065c2012-06-22 16:30:09 -070011778 if (result < 0) {
11779 Py_DECREF(buffer);
Larry Hastings9cf065c2012-06-22 16:30:09 -070011780 if (errno == ERANGE)
11781 continue;
Larry Hastings2f936352014-08-05 14:04:04 +100011782 path_error(path);
11783 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -070011784 }
Benjamin Peterson799bd802011-08-31 22:15:17 -040011785
Larry Hastings9cf065c2012-06-22 16:30:09 -070011786 if (result != buffer_size) {
11787 /* Can only shrink. */
11788 _PyBytes_Resize(&buffer, result);
11789 }
11790 break;
11791 }
Benjamin Peterson799bd802011-08-31 22:15:17 -040011792
Larry Hastings9cf065c2012-06-22 16:30:09 -070011793 return buffer;
Benjamin Peterson799bd802011-08-31 22:15:17 -040011794}
11795
Larry Hastings2f936352014-08-05 14:04:04 +100011796
11797/*[clinic input]
11798os.setxattr
11799
11800 path: path_t(allow_fd=True)
11801 attribute: path_t
11802 value: Py_buffer
11803 flags: int = 0
11804 *
11805 follow_symlinks: bool = True
11806
11807Set extended attribute attribute on path to value.
11808
BNMetricsb9427072018-11-02 15:20:19 +000011809path may be either a string, a path-like object, or an open file descriptor.
Larry Hastings2f936352014-08-05 14:04:04 +100011810If follow_symlinks is False, and the last element of the path is a symbolic
11811 link, setxattr will modify the symbolic link itself instead of the file
11812 the link points to.
11813
11814[clinic start generated code]*/
11815
Benjamin Peterson799bd802011-08-31 22:15:17 -040011816static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011817os_setxattr_impl(PyObject *module, path_t *path, path_t *attribute,
Larry Hastings89964c42015-04-14 18:07:59 -040011818 Py_buffer *value, int flags, int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +000011819/*[clinic end generated code: output=98b83f63fdde26bb input=c17c0103009042f0]*/
Benjamin Peterson799bd802011-08-31 22:15:17 -040011820{
Larry Hastings2f936352014-08-05 14:04:04 +100011821 ssize_t result;
Benjamin Peterson799bd802011-08-31 22:15:17 -040011822
Larry Hastings2f936352014-08-05 14:04:04 +100011823 if (fd_and_follow_symlinks_invalid("setxattr", path->fd, follow_symlinks))
Benjamin Peterson799bd802011-08-31 22:15:17 -040011824 return NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -070011825
Benjamin Peterson799bd802011-08-31 22:15:17 -040011826 Py_BEGIN_ALLOW_THREADS;
Larry Hastings2f936352014-08-05 14:04:04 +100011827 if (path->fd > -1)
11828 result = fsetxattr(path->fd, attribute->narrow,
11829 value->buf, value->len, flags);
Larry Hastings9cf065c2012-06-22 16:30:09 -070011830 else if (follow_symlinks)
Larry Hastings2f936352014-08-05 14:04:04 +100011831 result = setxattr(path->narrow, attribute->narrow,
11832 value->buf, value->len, flags);
Larry Hastings9cf065c2012-06-22 16:30:09 -070011833 else
Larry Hastings2f936352014-08-05 14:04:04 +100011834 result = lsetxattr(path->narrow, attribute->narrow,
11835 value->buf, value->len, flags);
Benjamin Peterson799bd802011-08-31 22:15:17 -040011836 Py_END_ALLOW_THREADS;
Benjamin Peterson799bd802011-08-31 22:15:17 -040011837
Larry Hastings9cf065c2012-06-22 16:30:09 -070011838 if (result) {
Larry Hastings2f936352014-08-05 14:04:04 +100011839 path_error(path);
11840 return NULL;
Benjamin Peterson799bd802011-08-31 22:15:17 -040011841 }
Benjamin Peterson799bd802011-08-31 22:15:17 -040011842
Larry Hastings2f936352014-08-05 14:04:04 +100011843 Py_RETURN_NONE;
11844}
11845
11846
11847/*[clinic input]
11848os.removexattr
11849
11850 path: path_t(allow_fd=True)
11851 attribute: path_t
11852 *
11853 follow_symlinks: bool = True
11854
11855Remove extended attribute attribute on path.
11856
BNMetricsb9427072018-11-02 15:20:19 +000011857path may be either a string, a path-like object, or an open file descriptor.
Larry Hastings2f936352014-08-05 14:04:04 +100011858If follow_symlinks is False, and the last element of the path is a symbolic
11859 link, removexattr will modify the symbolic link itself instead of the file
11860 the link points to.
11861
11862[clinic start generated code]*/
11863
Larry Hastings2f936352014-08-05 14:04:04 +100011864static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011865os_removexattr_impl(PyObject *module, path_t *path, path_t *attribute,
Larry Hastings89964c42015-04-14 18:07:59 -040011866 int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +000011867/*[clinic end generated code: output=521a51817980cda6 input=3d9a7d36fe2f7c4e]*/
Larry Hastings2f936352014-08-05 14:04:04 +100011868{
11869 ssize_t result;
11870
11871 if (fd_and_follow_symlinks_invalid("removexattr", path->fd, follow_symlinks))
11872 return NULL;
11873
11874 Py_BEGIN_ALLOW_THREADS;
11875 if (path->fd > -1)
11876 result = fremovexattr(path->fd, attribute->narrow);
11877 else if (follow_symlinks)
11878 result = removexattr(path->narrow, attribute->narrow);
11879 else
11880 result = lremovexattr(path->narrow, attribute->narrow);
11881 Py_END_ALLOW_THREADS;
11882
11883 if (result) {
11884 return path_error(path);
11885 }
11886
11887 Py_RETURN_NONE;
11888}
11889
11890
11891/*[clinic input]
11892os.listxattr
11893
11894 path: path_t(allow_fd=True, nullable=True) = None
11895 *
11896 follow_symlinks: bool = True
11897
11898Return a list of extended attributes on path.
11899
BNMetricsb9427072018-11-02 15:20:19 +000011900path may be either None, a string, a path-like object, or an open file descriptor.
Larry Hastings2f936352014-08-05 14:04:04 +100011901if path is None, listxattr will examine the current directory.
11902If follow_symlinks is False, and the last element of the path is a symbolic
11903 link, listxattr will examine the symbolic link itself instead of the file
11904 the link points to.
11905[clinic start generated code]*/
11906
Larry Hastings2f936352014-08-05 14:04:04 +100011907static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030011908os_listxattr_impl(PyObject *module, path_t *path, int follow_symlinks)
BNMetricsb9427072018-11-02 15:20:19 +000011909/*[clinic end generated code: output=bebdb4e2ad0ce435 input=9826edf9fdb90869]*/
Larry Hastings2f936352014-08-05 14:04:04 +100011910{
Larry Hastings9cf065c2012-06-22 16:30:09 -070011911 Py_ssize_t i;
11912 PyObject *result = NULL;
Larry Hastings2f936352014-08-05 14:04:04 +100011913 const char *name;
Larry Hastings9cf065c2012-06-22 16:30:09 -070011914 char *buffer = NULL;
Benjamin Peterson799bd802011-08-31 22:15:17 -040011915
Larry Hastings2f936352014-08-05 14:04:04 +100011916 if (fd_and_follow_symlinks_invalid("listxattr", path->fd, follow_symlinks))
Larry Hastings9cf065c2012-06-22 16:30:09 -070011917 goto exit;
Benjamin Peterson799bd802011-08-31 22:15:17 -040011918
Larry Hastings2f936352014-08-05 14:04:04 +100011919 name = path->narrow ? path->narrow : ".";
11920
Larry Hastings9cf065c2012-06-22 16:30:09 -070011921 for (i = 0; ; i++) {
Serhiy Storchakadeab18d2016-05-07 16:45:18 +030011922 const char *start, *trace, *end;
Larry Hastings9cf065c2012-06-22 16:30:09 -070011923 ssize_t length;
Serhiy Storchaka2d06e842015-12-25 19:53:18 +020011924 static const Py_ssize_t buffer_sizes[] = { 256, XATTR_LIST_MAX, 0 };
Larry Hastings9cf065c2012-06-22 16:30:09 -070011925 Py_ssize_t buffer_size = buffer_sizes[i];
11926 if (!buffer_size) {
Christian Heimes3b9493b2012-09-23 16:11:15 +020011927 /* ERANGE */
Larry Hastings2f936352014-08-05 14:04:04 +100011928 path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -070011929 break;
11930 }
11931 buffer = PyMem_MALLOC(buffer_size);
11932 if (!buffer) {
11933 PyErr_NoMemory();
11934 break;
11935 }
Benjamin Peterson799bd802011-08-31 22:15:17 -040011936
Larry Hastings9cf065c2012-06-22 16:30:09 -070011937 Py_BEGIN_ALLOW_THREADS;
Larry Hastings2f936352014-08-05 14:04:04 +100011938 if (path->fd > -1)
11939 length = flistxattr(path->fd, buffer, buffer_size);
Larry Hastings9cf065c2012-06-22 16:30:09 -070011940 else if (follow_symlinks)
11941 length = listxattr(name, buffer, buffer_size);
11942 else
11943 length = llistxattr(name, buffer, buffer_size);
11944 Py_END_ALLOW_THREADS;
Benjamin Peterson799bd802011-08-31 22:15:17 -040011945
Larry Hastings9cf065c2012-06-22 16:30:09 -070011946 if (length < 0) {
Antoine Pitrou7f987392013-05-13 19:46:29 +020011947 if (errno == ERANGE) {
11948 PyMem_FREE(buffer);
Benjamin Petersondedac522013-05-13 19:55:40 -050011949 buffer = NULL;
Larry Hastings9cf065c2012-06-22 16:30:09 -070011950 continue;
Antoine Pitrou7f987392013-05-13 19:46:29 +020011951 }
Larry Hastings2f936352014-08-05 14:04:04 +100011952 path_error(path);
Larry Hastings9cf065c2012-06-22 16:30:09 -070011953 break;
11954 }
Benjamin Peterson799bd802011-08-31 22:15:17 -040011955
Larry Hastings9cf065c2012-06-22 16:30:09 -070011956 result = PyList_New(0);
11957 if (!result) {
11958 goto exit;
11959 }
Benjamin Peterson799bd802011-08-31 22:15:17 -040011960
Larry Hastings9cf065c2012-06-22 16:30:09 -070011961 end = buffer + length;
11962 for (trace = start = buffer; trace != end; trace++) {
11963 if (!*trace) {
11964 int error;
11965 PyObject *attribute = PyUnicode_DecodeFSDefaultAndSize(start,
11966 trace - start);
11967 if (!attribute) {
11968 Py_DECREF(result);
11969 result = NULL;
11970 goto exit;
11971 }
11972 error = PyList_Append(result, attribute);
11973 Py_DECREF(attribute);
11974 if (error) {
11975 Py_DECREF(result);
11976 result = NULL;
11977 goto exit;
11978 }
11979 start = trace + 1;
11980 }
11981 }
11982 break;
11983 }
11984exit:
Larry Hastings9cf065c2012-06-22 16:30:09 -070011985 if (buffer)
11986 PyMem_FREE(buffer);
11987 return result;
Benjamin Peterson799bd802011-08-31 22:15:17 -040011988}
Benjamin Peterson9428d532011-09-14 11:45:52 -040011989#endif /* USE_XATTRS */
Benjamin Peterson799bd802011-08-31 22:15:17 -040011990
Antoine Pitroubcf2b592012-02-08 23:28:36 +010011991
Larry Hastings2f936352014-08-05 14:04:04 +100011992/*[clinic input]
11993os.urandom
11994
11995 size: Py_ssize_t
11996 /
11997
11998Return a bytes object containing random bytes suitable for cryptographic use.
11999[clinic start generated code]*/
12000
Larry Hastings2f936352014-08-05 14:04:04 +100012001static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030012002os_urandom_impl(PyObject *module, Py_ssize_t size)
12003/*[clinic end generated code: output=42c5cca9d18068e9 input=4067cdb1b6776c29]*/
Larry Hastings2f936352014-08-05 14:04:04 +100012004{
12005 PyObject *bytes;
12006 int result;
12007
Georg Brandl2fb477c2012-02-21 00:33:36 +010012008 if (size < 0)
12009 return PyErr_Format(PyExc_ValueError,
12010 "negative argument not allowed");
Larry Hastings2f936352014-08-05 14:04:04 +100012011 bytes = PyBytes_FromStringAndSize(NULL, size);
12012 if (bytes == NULL)
Georg Brandl2fb477c2012-02-21 00:33:36 +010012013 return NULL;
12014
Victor Stinnere66987e2016-09-06 16:33:52 -070012015 result = _PyOS_URandom(PyBytes_AS_STRING(bytes), PyBytes_GET_SIZE(bytes));
Larry Hastings2f936352014-08-05 14:04:04 +100012016 if (result == -1) {
12017 Py_DECREF(bytes);
Georg Brandl2fb477c2012-02-21 00:33:36 +010012018 return NULL;
12019 }
Larry Hastings2f936352014-08-05 14:04:04 +100012020 return bytes;
Georg Brandl2fb477c2012-02-21 00:33:36 +010012021}
12022
Zackery Spytz43fdbd22019-05-29 13:57:07 -060012023#ifdef HAVE_MEMFD_CREATE
12024/*[clinic input]
12025os.memfd_create
12026
12027 name: FSConverter
12028 flags: unsigned_int(bitwise=True, c_default="MFD_CLOEXEC") = MFD_CLOEXEC
12029
12030[clinic start generated code]*/
12031
12032static PyObject *
12033os_memfd_create_impl(PyObject *module, PyObject *name, unsigned int flags)
12034/*[clinic end generated code: output=6681ede983bdb9a6 input=a42cfc199bcd56e9]*/
12035{
12036 int fd;
12037 const char *bytes = PyBytes_AS_STRING(name);
12038 Py_BEGIN_ALLOW_THREADS
12039 fd = memfd_create(bytes, flags);
12040 Py_END_ALLOW_THREADS
12041 if (fd == -1) {
12042 return PyErr_SetFromErrno(PyExc_OSError);
12043 }
12044 return PyLong_FromLong(fd);
12045}
12046#endif
12047
Antoine Pitroubcf2b592012-02-08 23:28:36 +010012048/* Terminal size querying */
12049
Eddie Elizondo474eedf2018-11-13 04:09:31 -080012050static PyTypeObject* TerminalSizeType;
Antoine Pitroubcf2b592012-02-08 23:28:36 +010012051
12052PyDoc_STRVAR(TerminalSize_docstring,
12053 "A tuple of (columns, lines) for holding terminal window size");
12054
12055static PyStructSequence_Field TerminalSize_fields[] = {
12056 {"columns", "width of the terminal window in characters"},
12057 {"lines", "height of the terminal window in characters"},
12058 {NULL, NULL}
12059};
12060
12061static PyStructSequence_Desc TerminalSize_desc = {
12062 "os.terminal_size",
12063 TerminalSize_docstring,
12064 TerminalSize_fields,
12065 2,
12066};
12067
12068#if defined(TERMSIZE_USE_CONIO) || defined(TERMSIZE_USE_IOCTL)
Larry Hastings2f936352014-08-05 14:04:04 +100012069/* AC 3.5: fd should accept None */
Antoine Pitroubcf2b592012-02-08 23:28:36 +010012070PyDoc_STRVAR(termsize__doc__,
12071 "Return the size of the terminal window as (columns, lines).\n" \
12072 "\n" \
12073 "The optional argument fd (default standard output) specifies\n" \
12074 "which file descriptor should be queried.\n" \
12075 "\n" \
12076 "If the file descriptor is not connected to a terminal, an OSError\n" \
12077 "is thrown.\n" \
12078 "\n" \
12079 "This function will only be defined if an implementation is\n" \
12080 "available for this system.\n" \
12081 "\n" \
oldkaa0735f2018-02-02 16:52:55 +080012082 "shutil.get_terminal_size is the high-level function which should\n" \
Antoine Pitroubcf2b592012-02-08 23:28:36 +010012083 "normally be used, os.get_terminal_size is the low-level implementation.");
12084
12085static PyObject*
12086get_terminal_size(PyObject *self, PyObject *args)
12087{
12088 int columns, lines;
12089 PyObject *termsize;
12090
12091 int fd = fileno(stdout);
12092 /* Under some conditions stdout may not be connected and
12093 * fileno(stdout) may point to an invalid file descriptor. For example
12094 * GUI apps don't have valid standard streams by default.
12095 *
12096 * If this happens, and the optional fd argument is not present,
12097 * the ioctl below will fail returning EBADF. This is what we want.
12098 */
12099
12100 if (!PyArg_ParseTuple(args, "|i", &fd))
12101 return NULL;
12102
12103#ifdef TERMSIZE_USE_IOCTL
12104 {
12105 struct winsize w;
12106 if (ioctl(fd, TIOCGWINSZ, &w))
12107 return PyErr_SetFromErrno(PyExc_OSError);
12108 columns = w.ws_col;
12109 lines = w.ws_row;
12110 }
12111#endif /* TERMSIZE_USE_IOCTL */
12112
12113#ifdef TERMSIZE_USE_CONIO
12114 {
12115 DWORD nhandle;
12116 HANDLE handle;
12117 CONSOLE_SCREEN_BUFFER_INFO csbi;
12118 switch (fd) {
12119 case 0: nhandle = STD_INPUT_HANDLE;
12120 break;
12121 case 1: nhandle = STD_OUTPUT_HANDLE;
12122 break;
12123 case 2: nhandle = STD_ERROR_HANDLE;
12124 break;
12125 default:
12126 return PyErr_Format(PyExc_ValueError, "bad file descriptor");
12127 }
12128 handle = GetStdHandle(nhandle);
12129 if (handle == NULL)
12130 return PyErr_Format(PyExc_OSError, "handle cannot be retrieved");
12131 if (handle == INVALID_HANDLE_VALUE)
12132 return PyErr_SetFromWindowsErr(0);
12133
12134 if (!GetConsoleScreenBufferInfo(handle, &csbi))
12135 return PyErr_SetFromWindowsErr(0);
12136
12137 columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
12138 lines = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
12139 }
12140#endif /* TERMSIZE_USE_CONIO */
12141
Eddie Elizondo474eedf2018-11-13 04:09:31 -080012142 termsize = PyStructSequence_New(TerminalSizeType);
Antoine Pitroubcf2b592012-02-08 23:28:36 +010012143 if (termsize == NULL)
12144 return NULL;
12145 PyStructSequence_SET_ITEM(termsize, 0, PyLong_FromLong(columns));
12146 PyStructSequence_SET_ITEM(termsize, 1, PyLong_FromLong(lines));
12147 if (PyErr_Occurred()) {
12148 Py_DECREF(termsize);
12149 return NULL;
12150 }
12151 return termsize;
12152}
12153#endif /* defined(TERMSIZE_USE_CONIO) || defined(TERMSIZE_USE_IOCTL) */
12154
Larry Hastings2f936352014-08-05 14:04:04 +100012155
12156/*[clinic input]
12157os.cpu_count
12158
Charles-François Natali80d62e62015-08-13 20:37:08 +010012159Return the number of CPUs in the system; return None if indeterminable.
12160
12161This number is not equivalent to the number of CPUs the current process can
12162use. The number of usable CPUs can be obtained with
12163``len(os.sched_getaffinity(0))``
Larry Hastings2f936352014-08-05 14:04:04 +100012164[clinic start generated code]*/
12165
Larry Hastings2f936352014-08-05 14:04:04 +100012166static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030012167os_cpu_count_impl(PyObject *module)
Serhiy Storchaka2954f832016-07-07 18:20:03 +030012168/*[clinic end generated code: output=5fc29463c3936a9c input=e7c8f4ba6dbbadd3]*/
Charles-Francois Natali44feda32013-05-20 14:40:46 +020012169{
Charles-Francois Natalid59087d2013-05-20 17:31:06 +020012170 int ncpu = 0;
Charles-Francois Natali44feda32013-05-20 14:40:46 +020012171#ifdef MS_WINDOWS
Christopher Wilcoxc67bae02017-08-30 05:01:08 -040012172 /* Vista is supported and the GetMaximumProcessorCount API is Win7+
12173 Need to fallback to Vista behavior if this call isn't present */
12174 HINSTANCE hKernel32;
Christopher Wilcoxc67bae02017-08-30 05:01:08 -040012175 static DWORD(CALLBACK *_GetMaximumProcessorCount)(WORD) = NULL;
Tony Roberts4860f012019-02-02 18:16:42 +010012176 Py_BEGIN_ALLOW_THREADS
12177 hKernel32 = GetModuleHandleW(L"KERNEL32");
Christopher Wilcoxc67bae02017-08-30 05:01:08 -040012178 *(FARPROC*)&_GetMaximumProcessorCount = GetProcAddress(hKernel32,
12179 "GetMaximumProcessorCount");
Tony Roberts4860f012019-02-02 18:16:42 +010012180 Py_END_ALLOW_THREADS
Christopher Wilcoxc67bae02017-08-30 05:01:08 -040012181 if (_GetMaximumProcessorCount != NULL) {
12182 ncpu = _GetMaximumProcessorCount(ALL_PROCESSOR_GROUPS);
12183 }
12184 else {
12185 SYSTEM_INFO sysinfo;
12186 GetSystemInfo(&sysinfo);
12187 ncpu = sysinfo.dwNumberOfProcessors;
12188 }
Charles-Francois Natali44feda32013-05-20 14:40:46 +020012189#elif defined(__hpux)
12190 ncpu = mpctl(MPC_GETNUMSPUS, NULL, NULL);
12191#elif defined(HAVE_SYSCONF) && defined(_SC_NPROCESSORS_ONLN)
12192 ncpu = sysconf(_SC_NPROCESSORS_ONLN);
Charles-Francois Natali44feda32013-05-20 14:40:46 +020012193#elif defined(__DragonFly__) || \
12194 defined(__OpenBSD__) || \
12195 defined(__FreeBSD__) || \
Charles-Francois Natalid59087d2013-05-20 17:31:06 +020012196 defined(__NetBSD__) || \
12197 defined(__APPLE__)
Charles-Francois Natali7c4f8da2013-05-20 17:40:32 +020012198 int mib[2];
12199 size_t len = sizeof(ncpu);
12200 mib[0] = CTL_HW;
12201 mib[1] = HW_NCPU;
12202 if (sysctl(mib, 2, &ncpu, &len, NULL, 0) != 0)
12203 ncpu = 0;
Charles-Francois Natali44feda32013-05-20 14:40:46 +020012204#endif
12205 if (ncpu >= 1)
12206 return PyLong_FromLong(ncpu);
12207 else
12208 Py_RETURN_NONE;
12209}
12210
Victor Stinnerdaf45552013-08-28 00:53:59 +020012211
Larry Hastings2f936352014-08-05 14:04:04 +100012212/*[clinic input]
12213os.get_inheritable -> bool
12214
12215 fd: int
12216 /
12217
12218Get the close-on-exe flag of the specified file descriptor.
12219[clinic start generated code]*/
12220
Larry Hastings2f936352014-08-05 14:04:04 +100012221static int
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030012222os_get_inheritable_impl(PyObject *module, int fd)
12223/*[clinic end generated code: output=0445e20e149aa5b8 input=89ac008dc9ab6b95]*/
Larry Hastings2f936352014-08-05 14:04:04 +100012224{
Steve Dower8fc89802015-04-12 00:26:27 -040012225 int return_value;
Steve Dower8fc89802015-04-12 00:26:27 -040012226 _Py_BEGIN_SUPPRESS_IPH
12227 return_value = _Py_get_inheritable(fd);
12228 _Py_END_SUPPRESS_IPH
12229 return return_value;
Larry Hastings2f936352014-08-05 14:04:04 +100012230}
12231
12232
12233/*[clinic input]
12234os.set_inheritable
12235 fd: int
12236 inheritable: int
12237 /
12238
12239Set the inheritable flag of the specified file descriptor.
12240[clinic start generated code]*/
12241
Larry Hastings2f936352014-08-05 14:04:04 +100012242static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +030012243os_set_inheritable_impl(PyObject *module, int fd, int inheritable)
12244/*[clinic end generated code: output=f1b1918a2f3c38c2 input=9ceaead87a1e2402]*/
Victor Stinnerdaf45552013-08-28 00:53:59 +020012245{
Steve Dower8fc89802015-04-12 00:26:27 -040012246 int result;
Victor Stinnerdaf45552013-08-28 00:53:59 +020012247
Steve Dower8fc89802015-04-12 00:26:27 -040012248 _Py_BEGIN_SUPPRESS_IPH
12249 result = _Py_set_inheritable(fd, inheritable, NULL);
12250 _Py_END_SUPPRESS_IPH
12251 if (result < 0)
Victor Stinnerdaf45552013-08-28 00:53:59 +020012252 return NULL;
12253 Py_RETURN_NONE;
12254}
12255
12256
12257#ifdef MS_WINDOWS
Larry Hastings2f936352014-08-05 14:04:04 +100012258/*[clinic input]
12259os.get_handle_inheritable -> bool
Benjamin Petersonca470632016-09-06 13:47:26 -070012260 handle: intptr_t
Larry Hastings2f936352014-08-05 14:04:04 +100012261 /
Victor Stinnerdaf45552013-08-28 00:53:59 +020012262
Larry Hastings2f936352014-08-05 14:04:04 +100012263Get the close-on-exe flag of the specified file descriptor.
12264[clinic start generated code]*/
12265
Larry Hastings2f936352014-08-05 14:04:04 +100012266static int
Benjamin Petersonca470632016-09-06 13:47:26 -070012267os_get_handle_inheritable_impl(PyObject *module, intptr_t handle)
Victor Stinner581139c2016-09-06 15:54:20 -070012268/*[clinic end generated code: output=36be5afca6ea84d8 input=cfe99f9c05c70ad1]*/
Larry Hastings2f936352014-08-05 14:04:04 +100012269{
12270 DWORD flags;
Victor Stinnerdaf45552013-08-28 00:53:59 +020012271
12272 if (!GetHandleInformation((HANDLE)handle, &flags)) {
12273 PyErr_SetFromWindowsErr(0);
Larry Hastings2f936352014-08-05 14:04:04 +100012274 return -1;
Victor Stinnerdaf45552013-08-28 00:53:59 +020012275 }
12276
Larry Hastings2f936352014-08-05 14:04:04 +100012277 return flags & HANDLE_FLAG_INHERIT;
Victor Stinnerdaf45552013-08-28 00:53:59 +020012278}
12279
Victor Stinnerdaf45552013-08-28 00:53:59 +020012280
Larry Hastings2f936352014-08-05 14:04:04 +100012281/*[clinic input]
12282os.set_handle_inheritable
Benjamin Petersonca470632016-09-06 13:47:26 -070012283 handle: intptr_t
Larry Hastings2f936352014-08-05 14:04:04 +100012284 inheritable: bool
12285 /
12286
12287Set the inheritable flag of the specified handle.
12288[clinic start generated code]*/
12289
Larry Hastings2f936352014-08-05 14:04:04 +100012290static PyObject *
Benjamin Petersonca470632016-09-06 13:47:26 -070012291os_set_handle_inheritable_impl(PyObject *module, intptr_t handle,
Larry Hastings89964c42015-04-14 18:07:59 -040012292 int inheritable)
Victor Stinner581139c2016-09-06 15:54:20 -070012293/*[clinic end generated code: output=021d74fe6c96baa3 input=7a7641390d8364fc]*/
Larry Hastings2f936352014-08-05 14:04:04 +100012294{
12295 DWORD flags = inheritable ? HANDLE_FLAG_INHERIT : 0;
Victor Stinnerdaf45552013-08-28 00:53:59 +020012296 if (!SetHandleInformation((HANDLE)handle, HANDLE_FLAG_INHERIT, flags)) {
12297 PyErr_SetFromWindowsErr(0);
12298 return NULL;
12299 }
12300 Py_RETURN_NONE;
12301}
Larry Hastings2f936352014-08-05 14:04:04 +100012302#endif /* MS_WINDOWS */
Antoine Pitroubcf2b592012-02-08 23:28:36 +010012303
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012304#ifndef MS_WINDOWS
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030012305/*[clinic input]
12306os.get_blocking -> bool
12307 fd: int
12308 /
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012309
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030012310Get the blocking mode of the file descriptor.
12311
12312Return False if the O_NONBLOCK flag is set, True if the flag is cleared.
12313[clinic start generated code]*/
12314
12315static int
12316os_get_blocking_impl(PyObject *module, int fd)
12317/*[clinic end generated code: output=336a12ad76a61482 input=f4afb59d51560179]*/
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012318{
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012319 int blocking;
12320
Steve Dower8fc89802015-04-12 00:26:27 -040012321 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012322 blocking = _Py_get_blocking(fd);
Steve Dower8fc89802015-04-12 00:26:27 -040012323 _Py_END_SUPPRESS_IPH
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030012324 return blocking;
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012325}
12326
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030012327/*[clinic input]
12328os.set_blocking
12329 fd: int
12330 blocking: bool(accept={int})
12331 /
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012332
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030012333Set the blocking mode of the specified file descriptor.
12334
12335Set the O_NONBLOCK flag if blocking is False,
12336clear the O_NONBLOCK flag otherwise.
12337[clinic start generated code]*/
12338
12339static PyObject *
12340os_set_blocking_impl(PyObject *module, int fd, int blocking)
12341/*[clinic end generated code: output=384eb43aa0762a9d input=bf5c8efdc5860ff3]*/
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012342{
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030012343 int result;
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012344
Steve Dower8fc89802015-04-12 00:26:27 -040012345 _Py_BEGIN_SUPPRESS_IPH
12346 result = _Py_set_blocking(fd, blocking);
12347 _Py_END_SUPPRESS_IPH
12348 if (result < 0)
Victor Stinner1db9e7b2014-07-29 22:32:47 +020012349 return NULL;
12350 Py_RETURN_NONE;
12351}
12352#endif /* !MS_WINDOWS */
12353
12354
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012355/*[clinic input]
12356class os.DirEntry "DirEntry *" "&DirEntryType"
12357[clinic start generated code]*/
12358/*[clinic end generated code: output=da39a3ee5e6b4b0d input=3138f09f7c683f1d]*/
Victor Stinner6036e442015-03-08 01:58:04 +010012359
12360typedef struct {
12361 PyObject_HEAD
12362 PyObject *name;
12363 PyObject *path;
12364 PyObject *stat;
12365 PyObject *lstat;
12366#ifdef MS_WINDOWS
12367 struct _Py_stat_struct win32_lstat;
Victor Stinner0f6d7332017-03-09 17:34:28 +010012368 uint64_t win32_file_index;
Victor Stinner6036e442015-03-08 01:58:04 +010012369 int got_file_index;
12370#else /* POSIX */
Victor Stinner35a97c02015-03-08 02:59:09 +010012371#ifdef HAVE_DIRENT_D_TYPE
Victor Stinner6036e442015-03-08 01:58:04 +010012372 unsigned char d_type;
Victor Stinner35a97c02015-03-08 02:59:09 +010012373#endif
Victor Stinner6036e442015-03-08 01:58:04 +010012374 ino_t d_ino;
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012375 int dir_fd;
Victor Stinner6036e442015-03-08 01:58:04 +010012376#endif
12377} DirEntry;
12378
12379static void
12380DirEntry_dealloc(DirEntry *entry)
12381{
12382 Py_XDECREF(entry->name);
12383 Py_XDECREF(entry->path);
12384 Py_XDECREF(entry->stat);
12385 Py_XDECREF(entry->lstat);
12386 Py_TYPE(entry)->tp_free((PyObject *)entry);
12387}
12388
12389/* Forward reference */
12390static int
12391DirEntry_test_mode(DirEntry *self, int follow_symlinks, unsigned short mode_bits);
12392
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012393/*[clinic input]
12394os.DirEntry.is_symlink -> bool
12395
12396Return True if the entry is a symbolic link; cached per entry.
12397[clinic start generated code]*/
12398
Victor Stinner6036e442015-03-08 01:58:04 +010012399static int
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012400os_DirEntry_is_symlink_impl(DirEntry *self)
12401/*[clinic end generated code: output=42244667d7bcfc25 input=1605a1b4b96976c3]*/
Victor Stinner6036e442015-03-08 01:58:04 +010012402{
12403#ifdef MS_WINDOWS
12404 return (self->win32_lstat.st_mode & S_IFMT) == S_IFLNK;
Victor Stinner35a97c02015-03-08 02:59:09 +010012405#elif defined(HAVE_DIRENT_D_TYPE)
12406 /* POSIX */
Victor Stinner6036e442015-03-08 01:58:04 +010012407 if (self->d_type != DT_UNKNOWN)
12408 return self->d_type == DT_LNK;
12409 else
12410 return DirEntry_test_mode(self, 0, S_IFLNK);
Victor Stinner35a97c02015-03-08 02:59:09 +010012411#else
12412 /* POSIX without d_type */
12413 return DirEntry_test_mode(self, 0, S_IFLNK);
Victor Stinner6036e442015-03-08 01:58:04 +010012414#endif
12415}
12416
12417static PyObject *
Victor Stinner6036e442015-03-08 01:58:04 +010012418DirEntry_fetch_stat(DirEntry *self, int follow_symlinks)
12419{
12420 int result;
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012421 STRUCT_STAT st;
12422 PyObject *ub;
Victor Stinner6036e442015-03-08 01:58:04 +010012423
12424#ifdef MS_WINDOWS
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012425 if (!PyUnicode_FSDecoder(self->path, &ub))
12426 return NULL;
12427 const wchar_t *path = PyUnicode_AsUnicode(ub);
Victor Stinner6036e442015-03-08 01:58:04 +010012428#else /* POSIX */
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012429 if (!PyUnicode_FSConverter(self->path, &ub))
12430 return NULL;
12431 const char *path = PyBytes_AS_STRING(ub);
12432 if (self->dir_fd != DEFAULT_DIR_FD) {
12433#ifdef HAVE_FSTATAT
12434 result = fstatat(self->dir_fd, path, &st,
12435 follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW);
12436#else
12437 PyErr_SetString(PyExc_NotImplementedError, "can't fetch stat");
12438 return NULL;
12439#endif /* HAVE_FSTATAT */
12440 }
12441 else
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012442#endif
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012443 {
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012444 if (follow_symlinks)
12445 result = STAT(path, &st);
12446 else
12447 result = LSTAT(path, &st);
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012448 }
12449 Py_DECREF(ub);
Victor Stinner6036e442015-03-08 01:58:04 +010012450
12451 if (result != 0)
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012452 return path_object_error(self->path);
Victor Stinner6036e442015-03-08 01:58:04 +010012453
12454 return _pystat_fromstructstat(&st);
12455}
12456
12457static PyObject *
12458DirEntry_get_lstat(DirEntry *self)
12459{
12460 if (!self->lstat) {
12461#ifdef MS_WINDOWS
12462 self->lstat = _pystat_fromstructstat(&self->win32_lstat);
12463#else /* POSIX */
12464 self->lstat = DirEntry_fetch_stat(self, 0);
12465#endif
12466 }
12467 Py_XINCREF(self->lstat);
12468 return self->lstat;
12469}
12470
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012471/*[clinic input]
12472os.DirEntry.stat
12473 *
12474 follow_symlinks: bool = True
12475
12476Return stat_result object for the entry; cached per entry.
12477[clinic start generated code]*/
12478
Victor Stinner6036e442015-03-08 01:58:04 +010012479static PyObject *
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012480os_DirEntry_stat_impl(DirEntry *self, int follow_symlinks)
12481/*[clinic end generated code: output=008593b3a6d01305 input=280d14c1d6f1d00d]*/
Victor Stinner6036e442015-03-08 01:58:04 +010012482{
12483 if (!follow_symlinks)
12484 return DirEntry_get_lstat(self);
12485
12486 if (!self->stat) {
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012487 int result = os_DirEntry_is_symlink_impl(self);
Victor Stinner6036e442015-03-08 01:58:04 +010012488 if (result == -1)
12489 return NULL;
12490 else if (result)
12491 self->stat = DirEntry_fetch_stat(self, 1);
12492 else
12493 self->stat = DirEntry_get_lstat(self);
12494 }
12495
12496 Py_XINCREF(self->stat);
12497 return self->stat;
12498}
12499
Victor Stinner6036e442015-03-08 01:58:04 +010012500/* Set exception and return -1 on error, 0 for False, 1 for True */
12501static int
12502DirEntry_test_mode(DirEntry *self, int follow_symlinks, unsigned short mode_bits)
12503{
12504 PyObject *stat = NULL;
12505 PyObject *st_mode = NULL;
12506 long mode;
12507 int result;
Victor Stinner35a97c02015-03-08 02:59:09 +010012508#if defined(MS_WINDOWS) || defined(HAVE_DIRENT_D_TYPE)
Victor Stinner6036e442015-03-08 01:58:04 +010012509 int is_symlink;
12510 int need_stat;
Victor Stinner35a97c02015-03-08 02:59:09 +010012511#endif
Victor Stinner6036e442015-03-08 01:58:04 +010012512#ifdef MS_WINDOWS
12513 unsigned long dir_bits;
12514#endif
Victor Stinner35a97c02015-03-08 02:59:09 +010012515 _Py_IDENTIFIER(st_mode);
Victor Stinner6036e442015-03-08 01:58:04 +010012516
12517#ifdef MS_WINDOWS
12518 is_symlink = (self->win32_lstat.st_mode & S_IFMT) == S_IFLNK;
12519 need_stat = follow_symlinks && is_symlink;
Victor Stinner35a97c02015-03-08 02:59:09 +010012520#elif defined(HAVE_DIRENT_D_TYPE)
Victor Stinner6036e442015-03-08 01:58:04 +010012521 is_symlink = self->d_type == DT_LNK;
12522 need_stat = self->d_type == DT_UNKNOWN || (follow_symlinks && is_symlink);
12523#endif
12524
Victor Stinner35a97c02015-03-08 02:59:09 +010012525#if defined(MS_WINDOWS) || defined(HAVE_DIRENT_D_TYPE)
Victor Stinner6036e442015-03-08 01:58:04 +010012526 if (need_stat) {
Victor Stinner35a97c02015-03-08 02:59:09 +010012527#endif
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012528 stat = os_DirEntry_stat_impl(self, follow_symlinks);
Victor Stinner6036e442015-03-08 01:58:04 +010012529 if (!stat) {
12530 if (PyErr_ExceptionMatches(PyExc_FileNotFoundError)) {
12531 /* If file doesn't exist (anymore), then return False
12532 (i.e., say it's not a file/directory) */
12533 PyErr_Clear();
12534 return 0;
12535 }
12536 goto error;
12537 }
12538 st_mode = _PyObject_GetAttrId(stat, &PyId_st_mode);
12539 if (!st_mode)
12540 goto error;
12541
12542 mode = PyLong_AsLong(st_mode);
12543 if (mode == -1 && PyErr_Occurred())
12544 goto error;
12545 Py_CLEAR(st_mode);
12546 Py_CLEAR(stat);
12547 result = (mode & S_IFMT) == mode_bits;
Victor Stinner35a97c02015-03-08 02:59:09 +010012548#if defined(MS_WINDOWS) || defined(HAVE_DIRENT_D_TYPE)
Victor Stinner6036e442015-03-08 01:58:04 +010012549 }
12550 else if (is_symlink) {
12551 assert(mode_bits != S_IFLNK);
12552 result = 0;
12553 }
12554 else {
12555 assert(mode_bits == S_IFDIR || mode_bits == S_IFREG);
12556#ifdef MS_WINDOWS
12557 dir_bits = self->win32_lstat.st_file_attributes & FILE_ATTRIBUTE_DIRECTORY;
12558 if (mode_bits == S_IFDIR)
12559 result = dir_bits != 0;
12560 else
12561 result = dir_bits == 0;
12562#else /* POSIX */
12563 if (mode_bits == S_IFDIR)
12564 result = self->d_type == DT_DIR;
12565 else
12566 result = self->d_type == DT_REG;
12567#endif
12568 }
Victor Stinner35a97c02015-03-08 02:59:09 +010012569#endif
Victor Stinner6036e442015-03-08 01:58:04 +010012570
12571 return result;
12572
12573error:
12574 Py_XDECREF(st_mode);
12575 Py_XDECREF(stat);
12576 return -1;
12577}
12578
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012579/*[clinic input]
12580os.DirEntry.is_dir -> bool
12581 *
12582 follow_symlinks: bool = True
Victor Stinner6036e442015-03-08 01:58:04 +010012583
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012584Return True if the entry is a directory; cached per entry.
12585[clinic start generated code]*/
12586
12587static int
12588os_DirEntry_is_dir_impl(DirEntry *self, int follow_symlinks)
12589/*[clinic end generated code: output=ad2e8d54365da287 input=0135232766f53f58]*/
12590{
12591 return DirEntry_test_mode(self, follow_symlinks, S_IFDIR);
Victor Stinner6036e442015-03-08 01:58:04 +010012592}
12593
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012594/*[clinic input]
12595os.DirEntry.is_file -> bool
12596 *
12597 follow_symlinks: bool = True
12598
12599Return True if the entry is a file; cached per entry.
12600[clinic start generated code]*/
12601
12602static int
12603os_DirEntry_is_file_impl(DirEntry *self, int follow_symlinks)
12604/*[clinic end generated code: output=8462ade481d8a476 input=0dc90be168b041ee]*/
Victor Stinner6036e442015-03-08 01:58:04 +010012605{
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012606 return DirEntry_test_mode(self, follow_symlinks, S_IFREG);
Victor Stinner6036e442015-03-08 01:58:04 +010012607}
12608
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012609/*[clinic input]
12610os.DirEntry.inode
Victor Stinner6036e442015-03-08 01:58:04 +010012611
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012612Return inode of the entry; cached per entry.
12613[clinic start generated code]*/
Victor Stinner6036e442015-03-08 01:58:04 +010012614
12615static PyObject *
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012616os_DirEntry_inode_impl(DirEntry *self)
12617/*[clinic end generated code: output=156bb3a72162440e input=3ee7b872ae8649f0]*/
Victor Stinner6036e442015-03-08 01:58:04 +010012618{
12619#ifdef MS_WINDOWS
12620 if (!self->got_file_index) {
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012621 PyObject *unicode;
Serhiy Storchakadeab18d2016-05-07 16:45:18 +030012622 const wchar_t *path;
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012623 STRUCT_STAT stat;
12624 int result;
Victor Stinner6036e442015-03-08 01:58:04 +010012625
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012626 if (!PyUnicode_FSDecoder(self->path, &unicode))
Victor Stinner6036e442015-03-08 01:58:04 +010012627 return NULL;
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012628 path = PyUnicode_AsUnicode(unicode);
12629 result = LSTAT(path, &stat);
12630 Py_DECREF(unicode);
Victor Stinner6036e442015-03-08 01:58:04 +010012631
Serhiy Storchaka2674bc72016-10-08 20:16:57 +030012632 if (result != 0)
12633 return path_object_error(self->path);
Victor Stinner6036e442015-03-08 01:58:04 +010012634
12635 self->win32_file_index = stat.st_ino;
12636 self->got_file_index = 1;
12637 }
Victor Stinner0f6d7332017-03-09 17:34:28 +010012638 Py_BUILD_ASSERT(sizeof(unsigned long long) >= sizeof(self->win32_file_index));
12639 return PyLong_FromUnsignedLongLong(self->win32_file_index);
Victor Stinner6036e442015-03-08 01:58:04 +010012640#else /* POSIX */
xdegaye50e86032017-05-22 11:15:08 +020012641 Py_BUILD_ASSERT(sizeof(unsigned long long) >= sizeof(self->d_ino));
12642 return PyLong_FromUnsignedLongLong(self->d_ino);
Victor Stinner6036e442015-03-08 01:58:04 +010012643#endif
12644}
12645
12646static PyObject *
12647DirEntry_repr(DirEntry *self)
12648{
12649 return PyUnicode_FromFormat("<DirEntry %R>", self->name);
12650}
12651
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012652/*[clinic input]
12653os.DirEntry.__fspath__
12654
12655Returns the path for the entry.
12656[clinic start generated code]*/
12657
Brett Cannon96881cd2016-06-10 14:37:21 -070012658static PyObject *
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012659os_DirEntry___fspath___impl(DirEntry *self)
12660/*[clinic end generated code: output=6dd7f7ef752e6f4f input=3c49d0cf38df4fac]*/
Brett Cannon96881cd2016-06-10 14:37:21 -070012661{
12662 Py_INCREF(self->path);
12663 return self->path;
12664}
12665
Victor Stinner6036e442015-03-08 01:58:04 +010012666static PyMemberDef DirEntry_members[] = {
12667 {"name", T_OBJECT_EX, offsetof(DirEntry, name), READONLY,
12668 "the entry's base filename, relative to scandir() \"path\" argument"},
12669 {"path", T_OBJECT_EX, offsetof(DirEntry, path), READONLY,
12670 "the entry's full path name; equivalent to os.path.join(scandir_path, entry.name)"},
12671 {NULL}
12672};
12673
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012674#include "clinic/posixmodule.c.h"
12675
Victor Stinner6036e442015-03-08 01:58:04 +010012676static PyMethodDef DirEntry_methods[] = {
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020012677 OS_DIRENTRY_IS_DIR_METHODDEF
12678 OS_DIRENTRY_IS_FILE_METHODDEF
12679 OS_DIRENTRY_IS_SYMLINK_METHODDEF
12680 OS_DIRENTRY_STAT_METHODDEF
12681 OS_DIRENTRY_INODE_METHODDEF
12682 OS_DIRENTRY___FSPATH___METHODDEF
Victor Stinner6036e442015-03-08 01:58:04 +010012683 {NULL}
12684};
12685
Benjamin Peterson5646de42015-04-12 17:56:34 -040012686static PyTypeObject DirEntryType = {
Victor Stinner6036e442015-03-08 01:58:04 +010012687 PyVarObject_HEAD_INIT(NULL, 0)
12688 MODNAME ".DirEntry", /* tp_name */
12689 sizeof(DirEntry), /* tp_basicsize */
12690 0, /* tp_itemsize */
12691 /* methods */
12692 (destructor)DirEntry_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +020012693 0, /* tp_vectorcall_offset */
Victor Stinner6036e442015-03-08 01:58:04 +010012694 0, /* tp_getattr */
12695 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +020012696 0, /* tp_as_async */
Victor Stinner6036e442015-03-08 01:58:04 +010012697 (reprfunc)DirEntry_repr, /* tp_repr */
12698 0, /* tp_as_number */
12699 0, /* tp_as_sequence */
12700 0, /* tp_as_mapping */
12701 0, /* tp_hash */
12702 0, /* tp_call */
12703 0, /* tp_str */
12704 0, /* tp_getattro */
12705 0, /* tp_setattro */
12706 0, /* tp_as_buffer */
12707 Py_TPFLAGS_DEFAULT, /* tp_flags */
12708 0, /* tp_doc */
12709 0, /* tp_traverse */
12710 0, /* tp_clear */
12711 0, /* tp_richcompare */
12712 0, /* tp_weaklistoffset */
12713 0, /* tp_iter */
12714 0, /* tp_iternext */
12715 DirEntry_methods, /* tp_methods */
12716 DirEntry_members, /* tp_members */
12717};
12718
12719#ifdef MS_WINDOWS
12720
12721static wchar_t *
Serhiy Storchakadeab18d2016-05-07 16:45:18 +030012722join_path_filenameW(const wchar_t *path_wide, const wchar_t *filename)
Victor Stinner6036e442015-03-08 01:58:04 +010012723{
12724 Py_ssize_t path_len;
12725 Py_ssize_t size;
12726 wchar_t *result;
12727 wchar_t ch;
12728
12729 if (!path_wide) { /* Default arg: "." */
12730 path_wide = L".";
12731 path_len = 1;
12732 }
12733 else {
12734 path_len = wcslen(path_wide);
12735 }
12736
12737 /* The +1's are for the path separator and the NUL */
12738 size = path_len + 1 + wcslen(filename) + 1;
12739 result = PyMem_New(wchar_t, size);
12740 if (!result) {
12741 PyErr_NoMemory();
12742 return NULL;
12743 }
12744 wcscpy(result, path_wide);
12745 if (path_len > 0) {
12746 ch = result[path_len - 1];
12747 if (ch != SEP && ch != ALTSEP && ch != L':')
12748 result[path_len++] = SEP;
12749 wcscpy(result + path_len, filename);
12750 }
12751 return result;
12752}
12753
12754static PyObject *
12755DirEntry_from_find_data(path_t *path, WIN32_FIND_DATAW *dataW)
12756{
12757 DirEntry *entry;
12758 BY_HANDLE_FILE_INFORMATION file_info;
12759 ULONG reparse_tag;
12760 wchar_t *joined_path;
12761
12762 entry = PyObject_New(DirEntry, &DirEntryType);
12763 if (!entry)
12764 return NULL;
12765 entry->name = NULL;
12766 entry->path = NULL;
12767 entry->stat = NULL;
12768 entry->lstat = NULL;
12769 entry->got_file_index = 0;
12770
12771 entry->name = PyUnicode_FromWideChar(dataW->cFileName, -1);
12772 if (!entry->name)
12773 goto error;
Steve Dowercc16be82016-09-08 10:35:16 -070012774 if (path->narrow) {
12775 Py_SETREF(entry->name, PyUnicode_EncodeFSDefault(entry->name));
12776 if (!entry->name)
12777 goto error;
12778 }
Victor Stinner6036e442015-03-08 01:58:04 +010012779
12780 joined_path = join_path_filenameW(path->wide, dataW->cFileName);
12781 if (!joined_path)
12782 goto error;
12783
12784 entry->path = PyUnicode_FromWideChar(joined_path, -1);
12785 PyMem_Free(joined_path);
12786 if (!entry->path)
12787 goto error;
Steve Dowercc16be82016-09-08 10:35:16 -070012788 if (path->narrow) {
12789 Py_SETREF(entry->path, PyUnicode_EncodeFSDefault(entry->path));
12790 if (!entry->path)
12791 goto error;
12792 }
Victor Stinner6036e442015-03-08 01:58:04 +010012793
Steve Dowercc16be82016-09-08 10:35:16 -070012794 find_data_to_file_info(dataW, &file_info, &reparse_tag);
Victor Stinner6036e442015-03-08 01:58:04 +010012795 _Py_attribute_data_to_stat(&file_info, reparse_tag, &entry->win32_lstat);
12796
12797 return (PyObject *)entry;
12798
12799error:
12800 Py_DECREF(entry);
12801 return NULL;
12802}
12803
12804#else /* POSIX */
12805
12806static char *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +020012807join_path_filename(const char *path_narrow, const char* filename, Py_ssize_t filename_len)
Victor Stinner6036e442015-03-08 01:58:04 +010012808{
12809 Py_ssize_t path_len;
12810 Py_ssize_t size;
12811 char *result;
12812
12813 if (!path_narrow) { /* Default arg: "." */
12814 path_narrow = ".";
12815 path_len = 1;
12816 }
12817 else {
12818 path_len = strlen(path_narrow);
12819 }
12820
12821 if (filename_len == -1)
12822 filename_len = strlen(filename);
12823
12824 /* The +1's are for the path separator and the NUL */
12825 size = path_len + 1 + filename_len + 1;
12826 result = PyMem_New(char, size);
12827 if (!result) {
12828 PyErr_NoMemory();
12829 return NULL;
12830 }
12831 strcpy(result, path_narrow);
12832 if (path_len > 0 && result[path_len - 1] != '/')
12833 result[path_len++] = '/';
12834 strcpy(result + path_len, filename);
12835 return result;
12836}
12837
12838static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +020012839DirEntry_from_posix_info(path_t *path, const char *name, Py_ssize_t name_len,
Victor Stinner35a97c02015-03-08 02:59:09 +010012840 ino_t d_ino
12841#ifdef HAVE_DIRENT_D_TYPE
12842 , unsigned char d_type
12843#endif
12844 )
Victor Stinner6036e442015-03-08 01:58:04 +010012845{
12846 DirEntry *entry;
12847 char *joined_path;
12848
12849 entry = PyObject_New(DirEntry, &DirEntryType);
12850 if (!entry)
12851 return NULL;
12852 entry->name = NULL;
12853 entry->path = NULL;
12854 entry->stat = NULL;
12855 entry->lstat = NULL;
12856
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012857 if (path->fd != -1) {
12858 entry->dir_fd = path->fd;
12859 joined_path = NULL;
12860 }
12861 else {
12862 entry->dir_fd = DEFAULT_DIR_FD;
12863 joined_path = join_path_filename(path->narrow, name, name_len);
12864 if (!joined_path)
12865 goto error;
12866 }
Victor Stinner6036e442015-03-08 01:58:04 +010012867
Serhiy Storchaka1180e5a2017-07-11 06:36:46 +030012868 if (!path->narrow || !PyObject_CheckBuffer(path->object)) {
Victor Stinner6036e442015-03-08 01:58:04 +010012869 entry->name = PyUnicode_DecodeFSDefaultAndSize(name, name_len);
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012870 if (joined_path)
12871 entry->path = PyUnicode_DecodeFSDefault(joined_path);
Victor Stinner6036e442015-03-08 01:58:04 +010012872 }
12873 else {
12874 entry->name = PyBytes_FromStringAndSize(name, name_len);
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012875 if (joined_path)
12876 entry->path = PyBytes_FromString(joined_path);
Victor Stinner6036e442015-03-08 01:58:04 +010012877 }
12878 PyMem_Free(joined_path);
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012879 if (!entry->name)
12880 goto error;
12881
12882 if (path->fd != -1) {
12883 entry->path = entry->name;
12884 Py_INCREF(entry->path);
12885 }
12886 else if (!entry->path)
Victor Stinner6036e442015-03-08 01:58:04 +010012887 goto error;
12888
Victor Stinner35a97c02015-03-08 02:59:09 +010012889#ifdef HAVE_DIRENT_D_TYPE
Victor Stinner6036e442015-03-08 01:58:04 +010012890 entry->d_type = d_type;
Victor Stinner35a97c02015-03-08 02:59:09 +010012891#endif
Victor Stinner6036e442015-03-08 01:58:04 +010012892 entry->d_ino = d_ino;
12893
12894 return (PyObject *)entry;
12895
12896error:
12897 Py_XDECREF(entry);
12898 return NULL;
12899}
12900
12901#endif
12902
12903
12904typedef struct {
12905 PyObject_HEAD
12906 path_t path;
12907#ifdef MS_WINDOWS
12908 HANDLE handle;
12909 WIN32_FIND_DATAW file_data;
12910 int first_time;
12911#else /* POSIX */
12912 DIR *dirp;
12913#endif
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030012914#ifdef HAVE_FDOPENDIR
12915 int fd;
12916#endif
Victor Stinner6036e442015-03-08 01:58:04 +010012917} ScandirIterator;
12918
12919#ifdef MS_WINDOWS
12920
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020012921static int
12922ScandirIterator_is_closed(ScandirIterator *iterator)
12923{
12924 return iterator->handle == INVALID_HANDLE_VALUE;
12925}
12926
Victor Stinner6036e442015-03-08 01:58:04 +010012927static void
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020012928ScandirIterator_closedir(ScandirIterator *iterator)
Victor Stinner6036e442015-03-08 01:58:04 +010012929{
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030012930 HANDLE handle = iterator->handle;
12931
12932 if (handle == INVALID_HANDLE_VALUE)
Victor Stinner6036e442015-03-08 01:58:04 +010012933 return;
12934
Victor Stinner6036e442015-03-08 01:58:04 +010012935 iterator->handle = INVALID_HANDLE_VALUE;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030012936 Py_BEGIN_ALLOW_THREADS
12937 FindClose(handle);
12938 Py_END_ALLOW_THREADS
Victor Stinner6036e442015-03-08 01:58:04 +010012939}
12940
12941static PyObject *
12942ScandirIterator_iternext(ScandirIterator *iterator)
12943{
12944 WIN32_FIND_DATAW *file_data = &iterator->file_data;
12945 BOOL success;
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020012946 PyObject *entry;
Victor Stinner6036e442015-03-08 01:58:04 +010012947
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020012948 /* Happens if the iterator is iterated twice, or closed explicitly */
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020012949 if (iterator->handle == INVALID_HANDLE_VALUE)
Victor Stinner6036e442015-03-08 01:58:04 +010012950 return NULL;
Victor Stinner6036e442015-03-08 01:58:04 +010012951
12952 while (1) {
12953 if (!iterator->first_time) {
12954 Py_BEGIN_ALLOW_THREADS
12955 success = FindNextFileW(iterator->handle, file_data);
12956 Py_END_ALLOW_THREADS
12957 if (!success) {
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020012958 /* Error or no more files */
Victor Stinner6036e442015-03-08 01:58:04 +010012959 if (GetLastError() != ERROR_NO_MORE_FILES)
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020012960 path_error(&iterator->path);
Victor Stinner6036e442015-03-08 01:58:04 +010012961 break;
12962 }
12963 }
12964 iterator->first_time = 0;
12965
12966 /* Skip over . and .. */
12967 if (wcscmp(file_data->cFileName, L".") != 0 &&
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020012968 wcscmp(file_data->cFileName, L"..") != 0) {
12969 entry = DirEntry_from_find_data(&iterator->path, file_data);
12970 if (!entry)
12971 break;
12972 return entry;
12973 }
Victor Stinner6036e442015-03-08 01:58:04 +010012974
12975 /* Loop till we get a non-dot directory or finish iterating */
12976 }
12977
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020012978 /* Error or no more files */
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020012979 ScandirIterator_closedir(iterator);
Victor Stinner6036e442015-03-08 01:58:04 +010012980 return NULL;
12981}
12982
12983#else /* POSIX */
12984
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020012985static int
12986ScandirIterator_is_closed(ScandirIterator *iterator)
12987{
12988 return !iterator->dirp;
12989}
12990
Victor Stinner6036e442015-03-08 01:58:04 +010012991static void
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020012992ScandirIterator_closedir(ScandirIterator *iterator)
Victor Stinner6036e442015-03-08 01:58:04 +010012993{
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030012994 DIR *dirp = iterator->dirp;
12995
12996 if (!dirp)
Victor Stinner6036e442015-03-08 01:58:04 +010012997 return;
12998
Victor Stinner6036e442015-03-08 01:58:04 +010012999 iterator->dirp = NULL;
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030013000 Py_BEGIN_ALLOW_THREADS
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013001#ifdef HAVE_FDOPENDIR
13002 if (iterator->path.fd != -1)
13003 rewinddir(dirp);
13004#endif
Serhiy Storchakafbb1c5e2016-03-30 20:40:02 +030013005 closedir(dirp);
13006 Py_END_ALLOW_THREADS
Victor Stinner6036e442015-03-08 01:58:04 +010013007 return;
13008}
13009
13010static PyObject *
13011ScandirIterator_iternext(ScandirIterator *iterator)
13012{
13013 struct dirent *direntp;
13014 Py_ssize_t name_len;
13015 int is_dot;
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013016 PyObject *entry;
Victor Stinner6036e442015-03-08 01:58:04 +010013017
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013018 /* Happens if the iterator is iterated twice, or closed explicitly */
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013019 if (!iterator->dirp)
Victor Stinner6036e442015-03-08 01:58:04 +010013020 return NULL;
Victor Stinner6036e442015-03-08 01:58:04 +010013021
13022 while (1) {
13023 errno = 0;
13024 Py_BEGIN_ALLOW_THREADS
13025 direntp = readdir(iterator->dirp);
13026 Py_END_ALLOW_THREADS
13027
13028 if (!direntp) {
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013029 /* Error or no more files */
Victor Stinner6036e442015-03-08 01:58:04 +010013030 if (errno != 0)
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013031 path_error(&iterator->path);
Victor Stinner6036e442015-03-08 01:58:04 +010013032 break;
13033 }
13034
13035 /* Skip over . and .. */
13036 name_len = NAMLEN(direntp);
13037 is_dot = direntp->d_name[0] == '.' &&
13038 (name_len == 1 || (direntp->d_name[1] == '.' && name_len == 2));
13039 if (!is_dot) {
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013040 entry = DirEntry_from_posix_info(&iterator->path, direntp->d_name,
Victor Stinner35a97c02015-03-08 02:59:09 +010013041 name_len, direntp->d_ino
13042#ifdef HAVE_DIRENT_D_TYPE
13043 , direntp->d_type
13044#endif
13045 );
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013046 if (!entry)
13047 break;
13048 return entry;
Victor Stinner6036e442015-03-08 01:58:04 +010013049 }
13050
13051 /* Loop till we get a non-dot directory or finish iterating */
13052 }
13053
Serhiy Storchaka988b9bc2016-02-08 17:56:36 +020013054 /* Error or no more files */
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013055 ScandirIterator_closedir(iterator);
Victor Stinner6036e442015-03-08 01:58:04 +010013056 return NULL;
13057}
13058
13059#endif
13060
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013061static PyObject *
13062ScandirIterator_close(ScandirIterator *self, PyObject *args)
13063{
13064 ScandirIterator_closedir(self);
13065 Py_RETURN_NONE;
13066}
13067
13068static PyObject *
13069ScandirIterator_enter(PyObject *self, PyObject *args)
13070{
13071 Py_INCREF(self);
13072 return self;
13073}
13074
13075static PyObject *
13076ScandirIterator_exit(ScandirIterator *self, PyObject *args)
13077{
13078 ScandirIterator_closedir(self);
13079 Py_RETURN_NONE;
13080}
13081
Victor Stinner6036e442015-03-08 01:58:04 +010013082static void
Victor Stinner7bfa4092016-03-23 00:43:54 +010013083ScandirIterator_finalize(ScandirIterator *iterator)
13084{
13085 PyObject *error_type, *error_value, *error_traceback;
13086
13087 /* Save the current exception, if any. */
13088 PyErr_Fetch(&error_type, &error_value, &error_traceback);
13089
13090 if (!ScandirIterator_is_closed(iterator)) {
13091 ScandirIterator_closedir(iterator);
13092
13093 if (PyErr_ResourceWarning((PyObject *)iterator, 1,
13094 "unclosed scandir iterator %R", iterator)) {
13095 /* Spurious errors can appear at shutdown */
13096 if (PyErr_ExceptionMatches(PyExc_Warning)) {
13097 PyErr_WriteUnraisable((PyObject *) iterator);
13098 }
13099 }
13100 }
13101
Victor Stinner7bfa4092016-03-23 00:43:54 +010013102 path_cleanup(&iterator->path);
13103
13104 /* Restore the saved exception. */
13105 PyErr_Restore(error_type, error_value, error_traceback);
13106}
13107
13108static void
Victor Stinner6036e442015-03-08 01:58:04 +010013109ScandirIterator_dealloc(ScandirIterator *iterator)
13110{
Victor Stinner7bfa4092016-03-23 00:43:54 +010013111 if (PyObject_CallFinalizerFromDealloc((PyObject *)iterator) < 0)
13112 return;
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013113
Victor Stinner6036e442015-03-08 01:58:04 +010013114 Py_TYPE(iterator)->tp_free((PyObject *)iterator);
13115}
13116
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013117static PyMethodDef ScandirIterator_methods[] = {
13118 {"__enter__", (PyCFunction)ScandirIterator_enter, METH_NOARGS},
13119 {"__exit__", (PyCFunction)ScandirIterator_exit, METH_VARARGS},
13120 {"close", (PyCFunction)ScandirIterator_close, METH_NOARGS},
13121 {NULL}
13122};
13123
Benjamin Peterson5646de42015-04-12 17:56:34 -040013124static PyTypeObject ScandirIteratorType = {
Victor Stinner6036e442015-03-08 01:58:04 +010013125 PyVarObject_HEAD_INIT(NULL, 0)
13126 MODNAME ".ScandirIterator", /* tp_name */
13127 sizeof(ScandirIterator), /* tp_basicsize */
13128 0, /* tp_itemsize */
13129 /* methods */
13130 (destructor)ScandirIterator_dealloc, /* tp_dealloc */
Jeroen Demeyer530f5062019-05-31 04:13:39 +020013131 0, /* tp_vectorcall_offset */
Victor Stinner6036e442015-03-08 01:58:04 +010013132 0, /* tp_getattr */
13133 0, /* tp_setattr */
Jeroen Demeyer530f5062019-05-31 04:13:39 +020013134 0, /* tp_as_async */
Victor Stinner6036e442015-03-08 01:58:04 +010013135 0, /* tp_repr */
13136 0, /* tp_as_number */
13137 0, /* tp_as_sequence */
13138 0, /* tp_as_mapping */
13139 0, /* tp_hash */
13140 0, /* tp_call */
13141 0, /* tp_str */
13142 0, /* tp_getattro */
13143 0, /* tp_setattro */
13144 0, /* tp_as_buffer */
Antoine Pitrouada319b2019-05-29 22:12:38 +020013145 Py_TPFLAGS_DEFAULT, /* tp_flags */
Victor Stinner6036e442015-03-08 01:58:04 +010013146 0, /* tp_doc */
13147 0, /* tp_traverse */
13148 0, /* tp_clear */
13149 0, /* tp_richcompare */
13150 0, /* tp_weaklistoffset */
13151 PyObject_SelfIter, /* tp_iter */
13152 (iternextfunc)ScandirIterator_iternext, /* tp_iternext */
Serhiy Storchakaffe96ae2016-02-11 13:21:30 +020013153 ScandirIterator_methods, /* tp_methods */
Victor Stinner7bfa4092016-03-23 00:43:54 +010013154 0, /* tp_members */
13155 0, /* tp_getset */
13156 0, /* tp_base */
13157 0, /* tp_dict */
13158 0, /* tp_descr_get */
13159 0, /* tp_descr_set */
13160 0, /* tp_dictoffset */
13161 0, /* tp_init */
13162 0, /* tp_alloc */
13163 0, /* tp_new */
13164 0, /* tp_free */
13165 0, /* tp_is_gc */
13166 0, /* tp_bases */
13167 0, /* tp_mro */
13168 0, /* tp_cache */
13169 0, /* tp_subclasses */
13170 0, /* tp_weaklist */
13171 0, /* tp_del */
13172 0, /* tp_version_tag */
13173 (destructor)ScandirIterator_finalize, /* tp_finalize */
Victor Stinner6036e442015-03-08 01:58:04 +010013174};
13175
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013176/*[clinic input]
13177os.scandir
13178
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013179 path : path_t(nullable=True, allow_fd='PATH_HAVE_FDOPENDIR') = None
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013180
13181Return an iterator of DirEntry objects for given path.
13182
BNMetricsb9427072018-11-02 15:20:19 +000013183path can be specified as either str, bytes, or a path-like object. If path
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013184is bytes, the names of yielded DirEntry objects will also be bytes; in
13185all other circumstances they will be str.
13186
13187If path is None, uses the path='.'.
13188[clinic start generated code]*/
13189
Victor Stinner6036e442015-03-08 01:58:04 +010013190static PyObject *
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013191os_scandir_impl(PyObject *module, path_t *path)
BNMetricsb9427072018-11-02 15:20:19 +000013192/*[clinic end generated code: output=6eb2668b675ca89e input=6bdd312708fc3bb0]*/
Victor Stinner6036e442015-03-08 01:58:04 +010013193{
13194 ScandirIterator *iterator;
Victor Stinner6036e442015-03-08 01:58:04 +010013195#ifdef MS_WINDOWS
13196 wchar_t *path_strW;
13197#else
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013198 const char *path_str;
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013199#ifdef HAVE_FDOPENDIR
13200 int fd = -1;
13201#endif
Victor Stinner6036e442015-03-08 01:58:04 +010013202#endif
13203
Miss Islington (bot)8763d432019-06-24 09:09:47 -070013204 if (PySys_Audit("os.scandir", "O",
13205 path->object ? path->object : Py_None) < 0) {
13206 return NULL;
13207 }
13208
Victor Stinner6036e442015-03-08 01:58:04 +010013209 iterator = PyObject_New(ScandirIterator, &ScandirIteratorType);
13210 if (!iterator)
13211 return NULL;
Victor Stinner6036e442015-03-08 01:58:04 +010013212
13213#ifdef MS_WINDOWS
13214 iterator->handle = INVALID_HANDLE_VALUE;
13215#else
13216 iterator->dirp = NULL;
13217#endif
13218
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013219 memcpy(&iterator->path, path, sizeof(path_t));
Serhiy Storchaka095ef732017-02-09 20:05:51 +020013220 /* Move the ownership to iterator->path */
13221 path->object = NULL;
13222 path->cleanup = NULL;
Victor Stinner6036e442015-03-08 01:58:04 +010013223
13224#ifdef MS_WINDOWS
Victor Stinner6036e442015-03-08 01:58:04 +010013225 iterator->first_time = 1;
13226
13227 path_strW = join_path_filenameW(iterator->path.wide, L"*.*");
13228 if (!path_strW)
13229 goto error;
13230
13231 Py_BEGIN_ALLOW_THREADS
13232 iterator->handle = FindFirstFileW(path_strW, &iterator->file_data);
13233 Py_END_ALLOW_THREADS
13234
13235 PyMem_Free(path_strW);
13236
13237 if (iterator->handle == INVALID_HANDLE_VALUE) {
13238 path_error(&iterator->path);
13239 goto error;
13240 }
13241#else /* POSIX */
Victor Stinner6036e442015-03-08 01:58:04 +010013242 errno = 0;
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013243#ifdef HAVE_FDOPENDIR
13244 if (path->fd != -1) {
13245 /* closedir() closes the FD, so we duplicate it */
13246 fd = _Py_dup(path->fd);
13247 if (fd == -1)
13248 goto error;
13249
13250 Py_BEGIN_ALLOW_THREADS
13251 iterator->dirp = fdopendir(fd);
13252 Py_END_ALLOW_THREADS
13253 }
13254 else
13255#endif
13256 {
13257 if (iterator->path.narrow)
13258 path_str = iterator->path.narrow;
13259 else
13260 path_str = ".";
13261
13262 Py_BEGIN_ALLOW_THREADS
13263 iterator->dirp = opendir(path_str);
13264 Py_END_ALLOW_THREADS
13265 }
Victor Stinner6036e442015-03-08 01:58:04 +010013266
13267 if (!iterator->dirp) {
13268 path_error(&iterator->path);
Serhiy Storchakaea720fe2017-03-30 09:12:31 +030013269#ifdef HAVE_FDOPENDIR
13270 if (fd != -1) {
13271 Py_BEGIN_ALLOW_THREADS
13272 close(fd);
13273 Py_END_ALLOW_THREADS
13274 }
13275#endif
Victor Stinner6036e442015-03-08 01:58:04 +010013276 goto error;
13277 }
13278#endif
13279
13280 return (PyObject *)iterator;
13281
13282error:
13283 Py_DECREF(iterator);
13284 return NULL;
13285}
13286
Ethan Furman410ef8e2016-06-04 12:06:26 -070013287/*
13288 Return the file system path representation of the object.
13289
13290 If the object is str or bytes, then allow it to pass through with
13291 an incremented refcount. If the object defines __fspath__(), then
13292 return the result of that method. All other types raise a TypeError.
13293*/
13294PyObject *
13295PyOS_FSPath(PyObject *path)
13296{
Brett Cannon3f9183b2016-08-26 14:44:48 -070013297 /* For error message reasons, this function is manually inlined in
13298 path_converter(). */
Ethan Furman410ef8e2016-06-04 12:06:26 -070013299 _Py_IDENTIFIER(__fspath__);
13300 PyObject *func = NULL;
13301 PyObject *path_repr = NULL;
13302
13303 if (PyUnicode_Check(path) || PyBytes_Check(path)) {
13304 Py_INCREF(path);
13305 return path;
13306 }
13307
13308 func = _PyObject_LookupSpecial(path, &PyId___fspath__);
13309 if (NULL == func) {
13310 return PyErr_Format(PyExc_TypeError,
13311 "expected str, bytes or os.PathLike object, "
Brett Cannonc78ca1e2016-06-24 12:03:43 -070013312 "not %.200s",
13313 Py_TYPE(path)->tp_name);
Ethan Furman410ef8e2016-06-04 12:06:26 -070013314 }
13315
Victor Stinnerf17c3de2016-12-06 18:46:19 +010013316 path_repr = _PyObject_CallNoArg(func);
Ethan Furman410ef8e2016-06-04 12:06:26 -070013317 Py_DECREF(func);
Brett Cannon044283a2016-07-15 10:41:49 -070013318 if (NULL == path_repr) {
13319 return NULL;
13320 }
13321
Brett Cannonc78ca1e2016-06-24 12:03:43 -070013322 if (!(PyUnicode_Check(path_repr) || PyBytes_Check(path_repr))) {
13323 PyErr_Format(PyExc_TypeError,
13324 "expected %.200s.__fspath__() to return str or bytes, "
13325 "not %.200s", Py_TYPE(path)->tp_name,
13326 Py_TYPE(path_repr)->tp_name);
13327 Py_DECREF(path_repr);
13328 return NULL;
13329 }
13330
Ethan Furman410ef8e2016-06-04 12:06:26 -070013331 return path_repr;
13332}
13333
13334/*[clinic input]
13335os.fspath
13336
13337 path: object
13338
13339Return the file system path representation of the object.
13340
Brett Cannonb4f43e92016-06-09 14:32:08 -070013341If the object is str or bytes, then allow it to pass through as-is. If the
13342object defines __fspath__(), then return the result of that method. All other
13343types raise a TypeError.
Ethan Furman410ef8e2016-06-04 12:06:26 -070013344[clinic start generated code]*/
13345
13346static PyObject *
Serhiy Storchaka2954f832016-07-07 18:20:03 +030013347os_fspath_impl(PyObject *module, PyObject *path)
13348/*[clinic end generated code: output=c3c3b78ecff2914f input=e357165f7b22490f]*/
Ethan Furman410ef8e2016-06-04 12:06:26 -070013349{
13350 return PyOS_FSPath(path);
13351}
Victor Stinner6036e442015-03-08 01:58:04 +010013352
Victor Stinner9b1f4742016-09-06 16:18:52 -070013353#ifdef HAVE_GETRANDOM_SYSCALL
13354/*[clinic input]
13355os.getrandom
13356
13357 size: Py_ssize_t
13358 flags: int=0
13359
13360Obtain a series of random bytes.
13361[clinic start generated code]*/
13362
13363static PyObject *
13364os_getrandom_impl(PyObject *module, Py_ssize_t size, int flags)
13365/*[clinic end generated code: output=b3a618196a61409c input=59bafac39c594947]*/
13366{
Victor Stinner9b1f4742016-09-06 16:18:52 -070013367 PyObject *bytes;
Victor Stinnerec2319c2016-09-20 23:00:59 +020013368 Py_ssize_t n;
Victor Stinner9b1f4742016-09-06 16:18:52 -070013369
13370 if (size < 0) {
13371 errno = EINVAL;
13372 return posix_error();
13373 }
13374
Victor Stinnerec2319c2016-09-20 23:00:59 +020013375 bytes = PyBytes_FromStringAndSize(NULL, size);
13376 if (bytes == NULL) {
Victor Stinner9b1f4742016-09-06 16:18:52 -070013377 PyErr_NoMemory();
13378 return NULL;
13379 }
13380
13381 while (1) {
Victor Stinnerec2319c2016-09-20 23:00:59 +020013382 n = syscall(SYS_getrandom,
13383 PyBytes_AS_STRING(bytes),
13384 PyBytes_GET_SIZE(bytes),
13385 flags);
Victor Stinner9b1f4742016-09-06 16:18:52 -070013386 if (n < 0 && errno == EINTR) {
13387 if (PyErr_CheckSignals() < 0) {
Victor Stinnerec2319c2016-09-20 23:00:59 +020013388 goto error;
Victor Stinner9b1f4742016-09-06 16:18:52 -070013389 }
Victor Stinnerec2319c2016-09-20 23:00:59 +020013390
13391 /* getrandom() was interrupted by a signal: retry */
Victor Stinner9b1f4742016-09-06 16:18:52 -070013392 continue;
13393 }
13394 break;
13395 }
13396
13397 if (n < 0) {
Victor Stinner9b1f4742016-09-06 16:18:52 -070013398 PyErr_SetFromErrno(PyExc_OSError);
Victor Stinnerec2319c2016-09-20 23:00:59 +020013399 goto error;
Victor Stinner9b1f4742016-09-06 16:18:52 -070013400 }
13401
Victor Stinnerec2319c2016-09-20 23:00:59 +020013402 if (n != size) {
13403 _PyBytes_Resize(&bytes, n);
13404 }
Victor Stinner9b1f4742016-09-06 16:18:52 -070013405
13406 return bytes;
Victor Stinnerec2319c2016-09-20 23:00:59 +020013407
13408error:
13409 Py_DECREF(bytes);
13410 return NULL;
Victor Stinner9b1f4742016-09-06 16:18:52 -070013411}
13412#endif /* HAVE_GETRANDOM_SYSCALL */
13413
Steve Dower2438cdf2019-03-29 16:37:16 -070013414#ifdef MS_WINDOWS
13415/* bpo-36085: Helper functions for managing DLL search directories
13416 * on win32
13417 */
13418
13419typedef DLL_DIRECTORY_COOKIE (WINAPI *PAddDllDirectory)(PCWSTR newDirectory);
13420typedef BOOL (WINAPI *PRemoveDllDirectory)(DLL_DIRECTORY_COOKIE cookie);
13421
13422/*[clinic input]
13423os._add_dll_directory
13424
13425 path: path_t
13426
13427Add a path to the DLL search path.
13428
13429This search path is used when resolving dependencies for imported
13430extension modules (the module itself is resolved through sys.path),
13431and also by ctypes.
13432
13433Returns an opaque value that may be passed to os.remove_dll_directory
13434to remove this directory from the search path.
13435[clinic start generated code]*/
13436
13437static PyObject *
13438os__add_dll_directory_impl(PyObject *module, path_t *path)
13439/*[clinic end generated code: output=80b025daebb5d683 input=1de3e6c13a5808c8]*/
13440{
13441 HMODULE hKernel32;
13442 PAddDllDirectory AddDllDirectory;
13443 DLL_DIRECTORY_COOKIE cookie = 0;
13444 DWORD err = 0;
13445
13446 /* For Windows 7, we have to load this. As this will be a fairly
13447 infrequent operation, just do it each time. Kernel32 is always
13448 loaded. */
13449 Py_BEGIN_ALLOW_THREADS
13450 if (!(hKernel32 = GetModuleHandleW(L"kernel32")) ||
13451 !(AddDllDirectory = (PAddDllDirectory)GetProcAddress(
13452 hKernel32, "AddDllDirectory")) ||
13453 !(cookie = (*AddDllDirectory)(path->wide))) {
13454 err = GetLastError();
13455 }
13456 Py_END_ALLOW_THREADS
13457
13458 if (err) {
13459 return win32_error_object_err("add_dll_directory",
13460 path->object, err);
13461 }
13462
13463 return PyCapsule_New(cookie, "DLL directory cookie", NULL);
13464}
13465
13466/*[clinic input]
13467os._remove_dll_directory
13468
13469 cookie: object
13470
13471Removes a path from the DLL search path.
13472
13473The parameter is an opaque value that was returned from
13474os.add_dll_directory. You can only remove directories that you added
13475yourself.
13476[clinic start generated code]*/
13477
13478static PyObject *
13479os__remove_dll_directory_impl(PyObject *module, PyObject *cookie)
13480/*[clinic end generated code: output=594350433ae535bc input=c1d16a7e7d9dc5dc]*/
13481{
13482 HMODULE hKernel32;
13483 PRemoveDllDirectory RemoveDllDirectory;
13484 DLL_DIRECTORY_COOKIE cookieValue;
13485 DWORD err = 0;
13486
13487 if (!PyCapsule_IsValid(cookie, "DLL directory cookie")) {
13488 PyErr_SetString(PyExc_TypeError,
13489 "Provided cookie was not returned from os.add_dll_directory");
13490 return NULL;
13491 }
13492
13493 cookieValue = (DLL_DIRECTORY_COOKIE)PyCapsule_GetPointer(
13494 cookie, "DLL directory cookie");
13495
13496 /* For Windows 7, we have to load this. As this will be a fairly
13497 infrequent operation, just do it each time. Kernel32 is always
13498 loaded. */
13499 Py_BEGIN_ALLOW_THREADS
13500 if (!(hKernel32 = GetModuleHandleW(L"kernel32")) ||
13501 !(RemoveDllDirectory = (PRemoveDllDirectory)GetProcAddress(
13502 hKernel32, "RemoveDllDirectory")) ||
13503 !(*RemoveDllDirectory)(cookieValue)) {
13504 err = GetLastError();
13505 }
13506 Py_END_ALLOW_THREADS
13507
13508 if (err) {
13509 return win32_error_object_err("remove_dll_directory",
13510 NULL, err);
13511 }
13512
13513 if (PyCapsule_SetName(cookie, NULL)) {
13514 return NULL;
13515 }
13516
13517 Py_RETURN_NONE;
13518}
13519
13520#endif
Larry Hastings31826802013-10-19 00:09:25 -070013521
Fred Drake5ab8eaf1999-12-09 21:13:07 +000013522static PyMethodDef posix_methods[] = {
Larry Hastings31826802013-10-19 00:09:25 -070013523
13524 OS_STAT_METHODDEF
13525 OS_ACCESS_METHODDEF
13526 OS_TTYNAME_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100013527 OS_CHDIR_METHODDEF
13528 OS_CHFLAGS_METHODDEF
13529 OS_CHMOD_METHODDEF
13530 OS_FCHMOD_METHODDEF
13531 OS_LCHMOD_METHODDEF
13532 OS_CHOWN_METHODDEF
13533 OS_FCHOWN_METHODDEF
13534 OS_LCHOWN_METHODDEF
13535 OS_LCHFLAGS_METHODDEF
13536 OS_CHROOT_METHODDEF
13537 OS_CTERMID_METHODDEF
13538 OS_GETCWD_METHODDEF
13539 OS_GETCWDB_METHODDEF
13540 OS_LINK_METHODDEF
13541 OS_LISTDIR_METHODDEF
13542 OS_LSTAT_METHODDEF
13543 OS_MKDIR_METHODDEF
13544 OS_NICE_METHODDEF
13545 OS_GETPRIORITY_METHODDEF
13546 OS_SETPRIORITY_METHODDEF
Pablo Galindo6c6ddf92018-01-29 01:56:10 +000013547 OS_POSIX_SPAWN_METHODDEF
Joannah Nanjekye92b83222019-01-16 16:29:26 +030013548 OS_POSIX_SPAWNP_METHODDEF
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030013549 OS_READLINK_METHODDEF
Pablo Galindoaac4d032019-05-31 19:39:47 +010013550 OS_COPY_FILE_RANGE_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100013551 OS_RENAME_METHODDEF
13552 OS_REPLACE_METHODDEF
13553 OS_RMDIR_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100013554 OS_SYMLINK_METHODDEF
13555 OS_SYSTEM_METHODDEF
13556 OS_UMASK_METHODDEF
13557 OS_UNAME_METHODDEF
13558 OS_UNLINK_METHODDEF
13559 OS_REMOVE_METHODDEF
13560 OS_UTIME_METHODDEF
13561 OS_TIMES_METHODDEF
13562 OS__EXIT_METHODDEF
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +020013563 OS__FCOPYFILE_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100013564 OS_EXECV_METHODDEF
13565 OS_EXECVE_METHODDEF
13566 OS_SPAWNV_METHODDEF
13567 OS_SPAWNVE_METHODDEF
13568 OS_FORK1_METHODDEF
13569 OS_FORK_METHODDEF
Antoine Pitrou346cbd32017-05-27 17:50:54 +020013570 OS_REGISTER_AT_FORK_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100013571 OS_SCHED_GET_PRIORITY_MAX_METHODDEF
13572 OS_SCHED_GET_PRIORITY_MIN_METHODDEF
13573 OS_SCHED_GETPARAM_METHODDEF
13574 OS_SCHED_GETSCHEDULER_METHODDEF
13575 OS_SCHED_RR_GET_INTERVAL_METHODDEF
13576 OS_SCHED_SETPARAM_METHODDEF
13577 OS_SCHED_SETSCHEDULER_METHODDEF
13578 OS_SCHED_YIELD_METHODDEF
13579 OS_SCHED_SETAFFINITY_METHODDEF
13580 OS_SCHED_GETAFFINITY_METHODDEF
13581 OS_OPENPTY_METHODDEF
13582 OS_FORKPTY_METHODDEF
13583 OS_GETEGID_METHODDEF
13584 OS_GETEUID_METHODDEF
13585 OS_GETGID_METHODDEF
Ross Lagerwallb0ae53d2011-06-10 07:30:30 +020013586#ifdef HAVE_GETGROUPLIST
13587 {"getgrouplist", posix_getgrouplist, METH_VARARGS, posix_getgrouplist__doc__},
13588#endif
Larry Hastings2f936352014-08-05 14:04:04 +100013589 OS_GETGROUPS_METHODDEF
13590 OS_GETPID_METHODDEF
13591 OS_GETPGRP_METHODDEF
13592 OS_GETPPID_METHODDEF
13593 OS_GETUID_METHODDEF
13594 OS_GETLOGIN_METHODDEF
13595 OS_KILL_METHODDEF
13596 OS_KILLPG_METHODDEF
13597 OS_PLOCK_METHODDEF
Thomas Heller8b7a9572007-08-31 06:44:36 +000013598#ifdef MS_WINDOWS
Steve Dowercc16be82016-09-08 10:35:16 -070013599 OS_STARTFILE_METHODDEF
Thomas Heller8b7a9572007-08-31 06:44:36 +000013600#endif
Larry Hastings2f936352014-08-05 14:04:04 +100013601 OS_SETUID_METHODDEF
13602 OS_SETEUID_METHODDEF
13603 OS_SETREUID_METHODDEF
13604 OS_SETGID_METHODDEF
13605 OS_SETEGID_METHODDEF
13606 OS_SETREGID_METHODDEF
13607 OS_SETGROUPS_METHODDEF
Antoine Pitroub7572f02009-12-02 20:46:48 +000013608#ifdef HAVE_INITGROUPS
Victor Stinner8c62be82010-05-06 00:08:46 +000013609 {"initgroups", posix_initgroups, METH_VARARGS, posix_initgroups__doc__},
Antoine Pitroub7572f02009-12-02 20:46:48 +000013610#endif /* HAVE_INITGROUPS */
Larry Hastings2f936352014-08-05 14:04:04 +100013611 OS_GETPGID_METHODDEF
13612 OS_SETPGRP_METHODDEF
13613 OS_WAIT_METHODDEF
13614 OS_WAIT3_METHODDEF
13615 OS_WAIT4_METHODDEF
13616 OS_WAITID_METHODDEF
13617 OS_WAITPID_METHODDEF
13618 OS_GETSID_METHODDEF
13619 OS_SETSID_METHODDEF
13620 OS_SETPGID_METHODDEF
13621 OS_TCGETPGRP_METHODDEF
13622 OS_TCSETPGRP_METHODDEF
13623 OS_OPEN_METHODDEF
13624 OS_CLOSE_METHODDEF
13625 OS_CLOSERANGE_METHODDEF
13626 OS_DEVICE_ENCODING_METHODDEF
13627 OS_DUP_METHODDEF
13628 OS_DUP2_METHODDEF
13629 OS_LOCKF_METHODDEF
13630 OS_LSEEK_METHODDEF
13631 OS_READ_METHODDEF
13632 OS_READV_METHODDEF
13633 OS_PREAD_METHODDEF
Pablo Galindo4defba32018-01-27 16:16:37 +000013634 OS_PREADV_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100013635 OS_WRITE_METHODDEF
13636 OS_WRITEV_METHODDEF
13637 OS_PWRITE_METHODDEF
Pablo Galindo4defba32018-01-27 16:16:37 +000013638 OS_PWRITEV_METHODDEF
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +000013639#ifdef HAVE_SENDFILE
Serhiy Storchaka62be7422018-11-27 13:27:31 +020013640 {"sendfile", (PyCFunction)(void(*)(void))posix_sendfile, METH_VARARGS | METH_KEYWORDS,
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +000013641 posix_sendfile__doc__},
13642#endif
Larry Hastings2f936352014-08-05 14:04:04 +100013643 OS_FSTAT_METHODDEF
13644 OS_ISATTY_METHODDEF
13645 OS_PIPE_METHODDEF
13646 OS_PIPE2_METHODDEF
13647 OS_MKFIFO_METHODDEF
13648 OS_MKNOD_METHODDEF
13649 OS_MAJOR_METHODDEF
13650 OS_MINOR_METHODDEF
13651 OS_MAKEDEV_METHODDEF
13652 OS_FTRUNCATE_METHODDEF
13653 OS_TRUNCATE_METHODDEF
13654 OS_POSIX_FALLOCATE_METHODDEF
13655 OS_POSIX_FADVISE_METHODDEF
13656 OS_PUTENV_METHODDEF
13657 OS_UNSETENV_METHODDEF
13658 OS_STRERROR_METHODDEF
13659 OS_FCHDIR_METHODDEF
13660 OS_FSYNC_METHODDEF
13661 OS_SYNC_METHODDEF
13662 OS_FDATASYNC_METHODDEF
13663 OS_WCOREDUMP_METHODDEF
13664 OS_WIFCONTINUED_METHODDEF
13665 OS_WIFSTOPPED_METHODDEF
13666 OS_WIFSIGNALED_METHODDEF
13667 OS_WIFEXITED_METHODDEF
13668 OS_WEXITSTATUS_METHODDEF
13669 OS_WTERMSIG_METHODDEF
13670 OS_WSTOPSIG_METHODDEF
13671 OS_FSTATVFS_METHODDEF
13672 OS_STATVFS_METHODDEF
13673 OS_CONFSTR_METHODDEF
13674 OS_SYSCONF_METHODDEF
13675 OS_FPATHCONF_METHODDEF
13676 OS_PATHCONF_METHODDEF
13677 OS_ABORT_METHODDEF
Serhiy Storchakaf0b50152015-05-13 00:52:39 +030013678 OS__GETFULLPATHNAME_METHODDEF
Larry Hastings2f936352014-08-05 14:04:04 +100013679 OS__GETDISKUSAGE_METHODDEF
13680 OS__GETFINALPATHNAME_METHODDEF
13681 OS__GETVOLUMEPATHNAME_METHODDEF
13682 OS_GETLOADAVG_METHODDEF
13683 OS_URANDOM_METHODDEF
13684 OS_SETRESUID_METHODDEF
13685 OS_SETRESGID_METHODDEF
13686 OS_GETRESUID_METHODDEF
13687 OS_GETRESGID_METHODDEF
Martin v. Löwis7aed61a2009-11-27 14:09:49 +000013688
Larry Hastings2f936352014-08-05 14:04:04 +100013689 OS_GETXATTR_METHODDEF
13690 OS_SETXATTR_METHODDEF
13691 OS_REMOVEXATTR_METHODDEF
13692 OS_LISTXATTR_METHODDEF
13693
Antoine Pitroubcf2b592012-02-08 23:28:36 +010013694#if defined(TERMSIZE_USE_CONIO) || defined(TERMSIZE_USE_IOCTL)
13695 {"get_terminal_size", get_terminal_size, METH_VARARGS, termsize__doc__},
13696#endif
Larry Hastings2f936352014-08-05 14:04:04 +100013697 OS_CPU_COUNT_METHODDEF
13698 OS_GET_INHERITABLE_METHODDEF
13699 OS_SET_INHERITABLE_METHODDEF
13700 OS_GET_HANDLE_INHERITABLE_METHODDEF
13701 OS_SET_HANDLE_INHERITABLE_METHODDEF
Victor Stinner1db9e7b2014-07-29 22:32:47 +020013702#ifndef MS_WINDOWS
Serhiy Storchaka12a69db2018-09-17 15:38:27 +030013703 OS_GET_BLOCKING_METHODDEF
13704 OS_SET_BLOCKING_METHODDEF
Victor Stinner1db9e7b2014-07-29 22:32:47 +020013705#endif
Serhiy Storchaka49d02d12016-11-06 13:45:33 +020013706 OS_SCANDIR_METHODDEF
Ethan Furman410ef8e2016-06-04 12:06:26 -070013707 OS_FSPATH_METHODDEF
Victor Stinner9b1f4742016-09-06 16:18:52 -070013708 OS_GETRANDOM_METHODDEF
Zackery Spytz43fdbd22019-05-29 13:57:07 -060013709 OS_MEMFD_CREATE_METHODDEF
Steve Dower2438cdf2019-03-29 16:37:16 -070013710#ifdef MS_WINDOWS
13711 OS__ADD_DLL_DIRECTORY_METHODDEF
13712 OS__REMOVE_DLL_DIRECTORY_METHODDEF
13713#endif
Victor Stinner8c62be82010-05-06 00:08:46 +000013714 {NULL, NULL} /* Sentinel */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000013715};
13716
Barry Warsaw4a342091996-12-19 23:50:02 +000013717static int
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013718all_ins(PyObject *m)
Barry Warsaw4a342091996-12-19 23:50:02 +000013719{
Guido van Rossum94f6f721999-01-06 18:42:14 +000013720#ifdef F_OK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013721 if (PyModule_AddIntMacro(m, F_OK)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013722#endif
Guido van Rossum94f6f721999-01-06 18:42:14 +000013723#ifdef R_OK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013724 if (PyModule_AddIntMacro(m, R_OK)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013725#endif
Guido van Rossum94f6f721999-01-06 18:42:14 +000013726#ifdef W_OK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013727 if (PyModule_AddIntMacro(m, W_OK)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013728#endif
Guido van Rossum94f6f721999-01-06 18:42:14 +000013729#ifdef X_OK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013730 if (PyModule_AddIntMacro(m, X_OK)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013731#endif
Fred Drakec9680921999-12-13 16:37:25 +000013732#ifdef NGROUPS_MAX
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013733 if (PyModule_AddIntMacro(m, NGROUPS_MAX)) return -1;
Fred Drakec9680921999-12-13 16:37:25 +000013734#endif
Fred Drake5ab8eaf1999-12-09 21:13:07 +000013735#ifdef TMP_MAX
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013736 if (PyModule_AddIntMacro(m, TMP_MAX)) return -1;
Fred Drake5ab8eaf1999-12-09 21:13:07 +000013737#endif
Fred Drake106c1a02002-04-23 15:58:02 +000013738#ifdef WCONTINUED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013739 if (PyModule_AddIntMacro(m, WCONTINUED)) return -1;
Fred Drake106c1a02002-04-23 15:58:02 +000013740#endif
Barry Warsaw4a342091996-12-19 23:50:02 +000013741#ifdef WNOHANG
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013742 if (PyModule_AddIntMacro(m, WNOHANG)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013743#endif
Fred Drake106c1a02002-04-23 15:58:02 +000013744#ifdef WUNTRACED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013745 if (PyModule_AddIntMacro(m, WUNTRACED)) return -1;
Fred Drake106c1a02002-04-23 15:58:02 +000013746#endif
Barry Warsaw4a342091996-12-19 23:50:02 +000013747#ifdef O_RDONLY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013748 if (PyModule_AddIntMacro(m, O_RDONLY)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013749#endif
13750#ifdef O_WRONLY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013751 if (PyModule_AddIntMacro(m, O_WRONLY)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013752#endif
13753#ifdef O_RDWR
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013754 if (PyModule_AddIntMacro(m, O_RDWR)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013755#endif
13756#ifdef O_NDELAY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013757 if (PyModule_AddIntMacro(m, O_NDELAY)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013758#endif
13759#ifdef O_NONBLOCK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013760 if (PyModule_AddIntMacro(m, O_NONBLOCK)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013761#endif
13762#ifdef O_APPEND
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013763 if (PyModule_AddIntMacro(m, O_APPEND)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013764#endif
13765#ifdef O_DSYNC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013766 if (PyModule_AddIntMacro(m, O_DSYNC)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013767#endif
13768#ifdef O_RSYNC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013769 if (PyModule_AddIntMacro(m, O_RSYNC)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013770#endif
13771#ifdef O_SYNC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013772 if (PyModule_AddIntMacro(m, O_SYNC)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013773#endif
13774#ifdef O_NOCTTY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013775 if (PyModule_AddIntMacro(m, O_NOCTTY)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013776#endif
13777#ifdef O_CREAT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013778 if (PyModule_AddIntMacro(m, O_CREAT)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013779#endif
13780#ifdef O_EXCL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013781 if (PyModule_AddIntMacro(m, O_EXCL)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013782#endif
13783#ifdef O_TRUNC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013784 if (PyModule_AddIntMacro(m, O_TRUNC)) return -1;
Barry Warsaw4a342091996-12-19 23:50:02 +000013785#endif
Guido van Rossum98d9d091997-08-08 21:48:51 +000013786#ifdef O_BINARY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013787 if (PyModule_AddIntMacro(m, O_BINARY)) return -1;
Guido van Rossum98d9d091997-08-08 21:48:51 +000013788#endif
13789#ifdef O_TEXT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013790 if (PyModule_AddIntMacro(m, O_TEXT)) return -1;
Guido van Rossum98d9d091997-08-08 21:48:51 +000013791#endif
Jesus Cea1d642d22012-04-24 20:59:17 +020013792#ifdef O_XATTR
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013793 if (PyModule_AddIntMacro(m, O_XATTR)) return -1;
Jesus Cea1d642d22012-04-24 20:59:17 +020013794#endif
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000013795#ifdef O_LARGEFILE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013796 if (PyModule_AddIntMacro(m, O_LARGEFILE)) return -1;
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000013797#endif
doko@ubuntu.comfcff4372016-06-13 16:33:04 +020013798#ifndef __GNU__
Skip Montanaro5ff14922005-05-16 02:42:22 +000013799#ifdef O_SHLOCK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013800 if (PyModule_AddIntMacro(m, O_SHLOCK)) return -1;
Skip Montanaro5ff14922005-05-16 02:42:22 +000013801#endif
13802#ifdef O_EXLOCK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013803 if (PyModule_AddIntMacro(m, O_EXLOCK)) return -1;
Skip Montanaro5ff14922005-05-16 02:42:22 +000013804#endif
doko@ubuntu.comfcff4372016-06-13 16:33:04 +020013805#endif
Jesus Ceacf381202012-04-24 20:44:40 +020013806#ifdef O_EXEC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013807 if (PyModule_AddIntMacro(m, O_EXEC)) return -1;
Jesus Ceacf381202012-04-24 20:44:40 +020013808#endif
13809#ifdef O_SEARCH
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013810 if (PyModule_AddIntMacro(m, O_SEARCH)) return -1;
Jesus Ceacf381202012-04-24 20:44:40 +020013811#endif
Benjamin Peterson3b965a22013-03-13 10:27:41 -050013812#ifdef O_PATH
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013813 if (PyModule_AddIntMacro(m, O_PATH)) return -1;
Benjamin Peterson3b965a22013-03-13 10:27:41 -050013814#endif
Jesus Ceacf381202012-04-24 20:44:40 +020013815#ifdef O_TTY_INIT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013816 if (PyModule_AddIntMacro(m, O_TTY_INIT)) return -1;
Jesus Ceacf381202012-04-24 20:44:40 +020013817#endif
Christian Heimes177b3f92013-08-16 14:35:09 +020013818#ifdef O_TMPFILE
13819 if (PyModule_AddIntMacro(m, O_TMPFILE)) return -1;
13820#endif
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +000013821#ifdef PRIO_PROCESS
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013822 if (PyModule_AddIntMacro(m, PRIO_PROCESS)) return -1;
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +000013823#endif
13824#ifdef PRIO_PGRP
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013825 if (PyModule_AddIntMacro(m, PRIO_PGRP)) return -1;
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +000013826#endif
13827#ifdef PRIO_USER
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013828 if (PyModule_AddIntMacro(m, PRIO_USER)) return -1;
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +000013829#endif
Charles-François Natali1e045b12011-05-22 20:42:32 +020013830#ifdef O_CLOEXEC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013831 if (PyModule_AddIntMacro(m, O_CLOEXEC)) return -1;
Charles-François Natali1e045b12011-05-22 20:42:32 +020013832#endif
Jesus Cea1d642d22012-04-24 20:59:17 +020013833#ifdef O_ACCMODE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013834 if (PyModule_AddIntMacro(m, O_ACCMODE)) return -1;
Jesus Cea1d642d22012-04-24 20:59:17 +020013835#endif
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +000013836
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000013837
Jesus Cea94363612012-06-22 18:32:07 +020013838#ifdef SEEK_HOLE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013839 if (PyModule_AddIntMacro(m, SEEK_HOLE)) return -1;
Jesus Cea94363612012-06-22 18:32:07 +020013840#endif
13841#ifdef SEEK_DATA
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013842 if (PyModule_AddIntMacro(m, SEEK_DATA)) return -1;
Jesus Cea94363612012-06-22 18:32:07 +020013843#endif
13844
Tim Peters5aa91602002-01-30 05:46:57 +000013845/* MS Windows */
13846#ifdef O_NOINHERIT
Victor Stinner8c62be82010-05-06 00:08:46 +000013847 /* Don't inherit in child processes. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013848 if (PyModule_AddIntMacro(m, O_NOINHERIT)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013849#endif
13850#ifdef _O_SHORT_LIVED
Victor Stinner8c62be82010-05-06 00:08:46 +000013851 /* Optimize for short life (keep in memory). */
13852 /* MS forgot to define this one with a non-underscore form too. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013853 if (PyModule_AddIntConstant(m, "O_SHORT_LIVED", _O_SHORT_LIVED)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013854#endif
13855#ifdef O_TEMPORARY
Victor Stinner8c62be82010-05-06 00:08:46 +000013856 /* Automatically delete when last handle is closed. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013857 if (PyModule_AddIntMacro(m, O_TEMPORARY)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013858#endif
13859#ifdef O_RANDOM
Victor Stinner8c62be82010-05-06 00:08:46 +000013860 /* Optimize for random access. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013861 if (PyModule_AddIntMacro(m, O_RANDOM)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013862#endif
13863#ifdef O_SEQUENTIAL
Victor Stinner8c62be82010-05-06 00:08:46 +000013864 /* Optimize for sequential access. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013865 if (PyModule_AddIntMacro(m, O_SEQUENTIAL)) return -1;
Tim Peters5aa91602002-01-30 05:46:57 +000013866#endif
13867
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000013868/* GNU extensions. */
Alexandre Vassalottibee32532008-05-16 18:15:12 +000013869#ifdef O_ASYNC
Victor Stinner8c62be82010-05-06 00:08:46 +000013870 /* Send a SIGIO signal whenever input or output
13871 becomes available on file descriptor */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013872 if (PyModule_AddIntMacro(m, O_ASYNC)) return -1;
Alexandre Vassalottibee32532008-05-16 18:15:12 +000013873#endif
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000013874#ifdef O_DIRECT
Victor Stinner8c62be82010-05-06 00:08:46 +000013875 /* Direct disk access. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013876 if (PyModule_AddIntMacro(m, O_DIRECT)) return -1;
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000013877#endif
13878#ifdef O_DIRECTORY
Victor Stinner8c62be82010-05-06 00:08:46 +000013879 /* Must be a directory. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013880 if (PyModule_AddIntMacro(m, O_DIRECTORY)) return -1;
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000013881#endif
13882#ifdef O_NOFOLLOW
Victor Stinner8c62be82010-05-06 00:08:46 +000013883 /* Do not follow links. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013884 if (PyModule_AddIntMacro(m, O_NOFOLLOW)) return -1;
Martin v. Löwis4fe3c272001-10-18 22:05:36 +000013885#endif
Jesus Cea1d642d22012-04-24 20:59:17 +020013886#ifdef O_NOLINKS
13887 /* Fails if link count of the named file is greater than 1 */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013888 if (PyModule_AddIntMacro(m, O_NOLINKS)) return -1;
Jesus Cea1d642d22012-04-24 20:59:17 +020013889#endif
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +000013890#ifdef O_NOATIME
Victor Stinner8c62be82010-05-06 00:08:46 +000013891 /* Do not update the access time. */
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013892 if (PyModule_AddIntMacro(m, O_NOATIME)) return -1;
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +000013893#endif
Guido van Rossumd48f2521997-12-05 22:19:34 +000013894
Victor Stinner8c62be82010-05-06 00:08:46 +000013895 /* These come from sysexits.h */
Barry Warsaw5676bd12003-01-07 20:57:09 +000013896#ifdef EX_OK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013897 if (PyModule_AddIntMacro(m, EX_OK)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000013898#endif /* EX_OK */
Barry Warsaw5676bd12003-01-07 20:57:09 +000013899#ifdef EX_USAGE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013900 if (PyModule_AddIntMacro(m, EX_USAGE)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000013901#endif /* EX_USAGE */
Barry Warsaw5676bd12003-01-07 20:57:09 +000013902#ifdef EX_DATAERR
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013903 if (PyModule_AddIntMacro(m, EX_DATAERR)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000013904#endif /* EX_DATAERR */
Barry Warsaw5676bd12003-01-07 20:57:09 +000013905#ifdef EX_NOINPUT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013906 if (PyModule_AddIntMacro(m, EX_NOINPUT)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000013907#endif /* EX_NOINPUT */
Barry Warsaw5676bd12003-01-07 20:57:09 +000013908#ifdef EX_NOUSER
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013909 if (PyModule_AddIntMacro(m, EX_NOUSER)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000013910#endif /* EX_NOUSER */
Barry Warsaw5676bd12003-01-07 20:57:09 +000013911#ifdef EX_NOHOST
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013912 if (PyModule_AddIntMacro(m, EX_NOHOST)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000013913#endif /* EX_NOHOST */
Barry Warsaw5676bd12003-01-07 20:57:09 +000013914#ifdef EX_UNAVAILABLE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013915 if (PyModule_AddIntMacro(m, EX_UNAVAILABLE)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000013916#endif /* EX_UNAVAILABLE */
Barry Warsaw5676bd12003-01-07 20:57:09 +000013917#ifdef EX_SOFTWARE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013918 if (PyModule_AddIntMacro(m, EX_SOFTWARE)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000013919#endif /* EX_SOFTWARE */
Barry Warsaw5676bd12003-01-07 20:57:09 +000013920#ifdef EX_OSERR
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013921 if (PyModule_AddIntMacro(m, EX_OSERR)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000013922#endif /* EX_OSERR */
Barry Warsaw5676bd12003-01-07 20:57:09 +000013923#ifdef EX_OSFILE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013924 if (PyModule_AddIntMacro(m, EX_OSFILE)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000013925#endif /* EX_OSFILE */
Barry Warsaw5676bd12003-01-07 20:57:09 +000013926#ifdef EX_CANTCREAT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013927 if (PyModule_AddIntMacro(m, EX_CANTCREAT)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000013928#endif /* EX_CANTCREAT */
Barry Warsaw5676bd12003-01-07 20:57:09 +000013929#ifdef EX_IOERR
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013930 if (PyModule_AddIntMacro(m, EX_IOERR)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000013931#endif /* EX_IOERR */
Barry Warsaw5676bd12003-01-07 20:57:09 +000013932#ifdef EX_TEMPFAIL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013933 if (PyModule_AddIntMacro(m, EX_TEMPFAIL)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000013934#endif /* EX_TEMPFAIL */
Barry Warsaw5676bd12003-01-07 20:57:09 +000013935#ifdef EX_PROTOCOL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013936 if (PyModule_AddIntMacro(m, EX_PROTOCOL)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000013937#endif /* EX_PROTOCOL */
Barry Warsaw5676bd12003-01-07 20:57:09 +000013938#ifdef EX_NOPERM
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013939 if (PyModule_AddIntMacro(m, EX_NOPERM)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000013940#endif /* EX_NOPERM */
Barry Warsaw5676bd12003-01-07 20:57:09 +000013941#ifdef EX_CONFIG
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013942 if (PyModule_AddIntMacro(m, EX_CONFIG)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000013943#endif /* EX_CONFIG */
Barry Warsaw5676bd12003-01-07 20:57:09 +000013944#ifdef EX_NOTFOUND
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013945 if (PyModule_AddIntMacro(m, EX_NOTFOUND)) return -1;
Neal Norwitz8e914d92003-01-10 15:29:16 +000013946#endif /* EX_NOTFOUND */
Barry Warsaw5676bd12003-01-07 20:57:09 +000013947
Amaury Forgeot d'Arc66d00ad2010-09-10 18:11:45 +000013948 /* statvfs */
Andrew M. Kuchling4ea04a32010-08-18 22:30:34 +000013949#ifdef ST_RDONLY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013950 if (PyModule_AddIntMacro(m, ST_RDONLY)) return -1;
Andrew M. Kuchling4ea04a32010-08-18 22:30:34 +000013951#endif /* ST_RDONLY */
13952#ifdef ST_NOSUID
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013953 if (PyModule_AddIntMacro(m, ST_NOSUID)) return -1;
Andrew M. Kuchling4ea04a32010-08-18 22:30:34 +000013954#endif /* ST_NOSUID */
13955
doko@ubuntu.comca616a22013-12-08 15:23:07 +010013956 /* GNU extensions */
13957#ifdef ST_NODEV
13958 if (PyModule_AddIntMacro(m, ST_NODEV)) return -1;
13959#endif /* ST_NODEV */
13960#ifdef ST_NOEXEC
13961 if (PyModule_AddIntMacro(m, ST_NOEXEC)) return -1;
13962#endif /* ST_NOEXEC */
13963#ifdef ST_SYNCHRONOUS
13964 if (PyModule_AddIntMacro(m, ST_SYNCHRONOUS)) return -1;
13965#endif /* ST_SYNCHRONOUS */
13966#ifdef ST_MANDLOCK
13967 if (PyModule_AddIntMacro(m, ST_MANDLOCK)) return -1;
13968#endif /* ST_MANDLOCK */
13969#ifdef ST_WRITE
13970 if (PyModule_AddIntMacro(m, ST_WRITE)) return -1;
13971#endif /* ST_WRITE */
13972#ifdef ST_APPEND
13973 if (PyModule_AddIntMacro(m, ST_APPEND)) return -1;
13974#endif /* ST_APPEND */
13975#ifdef ST_NOATIME
13976 if (PyModule_AddIntMacro(m, ST_NOATIME)) return -1;
13977#endif /* ST_NOATIME */
13978#ifdef ST_NODIRATIME
13979 if (PyModule_AddIntMacro(m, ST_NODIRATIME)) return -1;
13980#endif /* ST_NODIRATIME */
13981#ifdef ST_RELATIME
13982 if (PyModule_AddIntMacro(m, ST_RELATIME)) return -1;
13983#endif /* ST_RELATIME */
13984
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +000013985 /* FreeBSD sendfile() constants */
13986#ifdef SF_NODISKIO
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013987 if (PyModule_AddIntMacro(m, SF_NODISKIO)) return -1;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +000013988#endif
13989#ifdef SF_MNOWAIT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013990 if (PyModule_AddIntMacro(m, SF_MNOWAIT)) return -1;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +000013991#endif
13992#ifdef SF_SYNC
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013993 if (PyModule_AddIntMacro(m, SF_SYNC)) return -1;
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +000013994#endif
13995
Ross Lagerwall7807c352011-03-17 20:20:30 +020013996 /* constants for posix_fadvise */
13997#ifdef POSIX_FADV_NORMAL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020013998 if (PyModule_AddIntMacro(m, POSIX_FADV_NORMAL)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020013999#endif
14000#ifdef POSIX_FADV_SEQUENTIAL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014001 if (PyModule_AddIntMacro(m, POSIX_FADV_SEQUENTIAL)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014002#endif
14003#ifdef POSIX_FADV_RANDOM
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014004 if (PyModule_AddIntMacro(m, POSIX_FADV_RANDOM)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014005#endif
14006#ifdef POSIX_FADV_NOREUSE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014007 if (PyModule_AddIntMacro(m, POSIX_FADV_NOREUSE)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014008#endif
14009#ifdef POSIX_FADV_WILLNEED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014010 if (PyModule_AddIntMacro(m, POSIX_FADV_WILLNEED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014011#endif
14012#ifdef POSIX_FADV_DONTNEED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014013 if (PyModule_AddIntMacro(m, POSIX_FADV_DONTNEED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014014#endif
14015
14016 /* constants for waitid */
14017#if defined(HAVE_SYS_WAIT_H) && defined(HAVE_WAITID)
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014018 if (PyModule_AddIntMacro(m, P_PID)) return -1;
14019 if (PyModule_AddIntMacro(m, P_PGID)) return -1;
14020 if (PyModule_AddIntMacro(m, P_ALL)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014021#endif
14022#ifdef WEXITED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014023 if (PyModule_AddIntMacro(m, WEXITED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014024#endif
14025#ifdef WNOWAIT
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014026 if (PyModule_AddIntMacro(m, WNOWAIT)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014027#endif
14028#ifdef WSTOPPED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014029 if (PyModule_AddIntMacro(m, WSTOPPED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014030#endif
14031#ifdef CLD_EXITED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014032 if (PyModule_AddIntMacro(m, CLD_EXITED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014033#endif
14034#ifdef CLD_DUMPED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014035 if (PyModule_AddIntMacro(m, CLD_DUMPED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014036#endif
14037#ifdef CLD_TRAPPED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014038 if (PyModule_AddIntMacro(m, CLD_TRAPPED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014039#endif
14040#ifdef CLD_CONTINUED
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014041 if (PyModule_AddIntMacro(m, CLD_CONTINUED)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014042#endif
14043
14044 /* constants for lockf */
14045#ifdef F_LOCK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014046 if (PyModule_AddIntMacro(m, F_LOCK)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014047#endif
14048#ifdef F_TLOCK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014049 if (PyModule_AddIntMacro(m, F_TLOCK)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014050#endif
14051#ifdef F_ULOCK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014052 if (PyModule_AddIntMacro(m, F_ULOCK)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014053#endif
14054#ifdef F_TEST
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014055 if (PyModule_AddIntMacro(m, F_TEST)) return -1;
Ross Lagerwall7807c352011-03-17 20:20:30 +020014056#endif
14057
Pablo Galindo4defba32018-01-27 16:16:37 +000014058#ifdef RWF_DSYNC
14059 if (PyModule_AddIntConstant(m, "RWF_DSYNC", RWF_DSYNC)) return -1;
14060#endif
14061#ifdef RWF_HIPRI
14062 if (PyModule_AddIntConstant(m, "RWF_HIPRI", RWF_HIPRI)) return -1;
14063#endif
14064#ifdef RWF_SYNC
14065 if (PyModule_AddIntConstant(m, "RWF_SYNC", RWF_SYNC)) return -1;
14066#endif
14067#ifdef RWF_NOWAIT
14068 if (PyModule_AddIntConstant(m, "RWF_NOWAIT", RWF_NOWAIT)) return -1;
14069#endif
14070
Pablo Galindo6c6ddf92018-01-29 01:56:10 +000014071/* constants for posix_spawn */
14072#ifdef HAVE_POSIX_SPAWN
14073 if (PyModule_AddIntConstant(m, "POSIX_SPAWN_OPEN", POSIX_SPAWN_OPEN)) return -1;
14074 if (PyModule_AddIntConstant(m, "POSIX_SPAWN_CLOSE", POSIX_SPAWN_CLOSE)) return -1;
14075 if (PyModule_AddIntConstant(m, "POSIX_SPAWN_DUP2", POSIX_SPAWN_DUP2)) return -1;
14076#endif
14077
pxinwrf2d7ac72019-05-21 18:46:37 +080014078#if defined(HAVE_SPAWNV) || defined (HAVE_RTPSPAWN)
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014079 if (PyModule_AddIntConstant(m, "P_WAIT", _P_WAIT)) return -1;
14080 if (PyModule_AddIntConstant(m, "P_NOWAIT", _P_NOWAIT)) return -1;
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014081 if (PyModule_AddIntConstant(m, "P_NOWAITO", _P_NOWAITO)) return -1;
pxinwrf2d7ac72019-05-21 18:46:37 +080014082#endif
14083#ifdef HAVE_SPAWNV
14084 if (PyModule_AddIntConstant(m, "P_OVERLAY", _OLD_P_OVERLAY)) return -1;
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014085 if (PyModule_AddIntConstant(m, "P_DETACH", _P_DETACH)) return -1;
Guido van Rossum246bc171999-02-01 23:54:31 +000014086#endif
14087
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014088#ifdef HAVE_SCHED_H
Benjamin Petersondbaa5592016-07-30 23:21:50 -070014089#ifdef SCHED_OTHER
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014090 if (PyModule_AddIntMacro(m, SCHED_OTHER)) return -1;
Benjamin Petersondbaa5592016-07-30 23:21:50 -070014091#endif
14092#ifdef SCHED_FIFO
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014093 if (PyModule_AddIntMacro(m, SCHED_FIFO)) return -1;
Benjamin Petersondbaa5592016-07-30 23:21:50 -070014094#endif
14095#ifdef SCHED_RR
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014096 if (PyModule_AddIntMacro(m, SCHED_RR)) return -1;
Benjamin Petersondbaa5592016-07-30 23:21:50 -070014097#endif
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014098#ifdef SCHED_SPORADIC
messi Liao0d322182017-06-13 22:30:43 +080014099 if (PyModule_AddIntMacro(m, SCHED_SPORADIC)) return -1;
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014100#endif
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014101#ifdef SCHED_BATCH
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014102 if (PyModule_AddIntMacro(m, SCHED_BATCH)) return -1;
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014103#endif
14104#ifdef SCHED_IDLE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014105 if (PyModule_AddIntMacro(m, SCHED_IDLE)) return -1;
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014106#endif
14107#ifdef SCHED_RESET_ON_FORK
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014108 if (PyModule_AddIntMacro(m, SCHED_RESET_ON_FORK)) return -1;
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014109#endif
Jesus Ceaf2cb4e82011-09-09 23:55:42 +020014110#ifdef SCHED_SYS
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014111 if (PyModule_AddIntMacro(m, SCHED_SYS)) return -1;
Jesus Ceaf2cb4e82011-09-09 23:55:42 +020014112#endif
14113#ifdef SCHED_IA
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014114 if (PyModule_AddIntMacro(m, SCHED_IA)) return -1;
Jesus Ceaf2cb4e82011-09-09 23:55:42 +020014115#endif
14116#ifdef SCHED_FSS
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014117 if (PyModule_AddIntMacro(m, SCHED_FSS)) return -1;
Jesus Ceaf2cb4e82011-09-09 23:55:42 +020014118#endif
14119#ifdef SCHED_FX
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014120 if (PyModule_AddIntConstant(m, "SCHED_FX", SCHED_FSS)) return -1;
Jesus Ceaf2cb4e82011-09-09 23:55:42 +020014121#endif
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014122#endif
14123
Benjamin Peterson9428d532011-09-14 11:45:52 -040014124#ifdef USE_XATTRS
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014125 if (PyModule_AddIntMacro(m, XATTR_CREATE)) return -1;
14126 if (PyModule_AddIntMacro(m, XATTR_REPLACE)) return -1;
14127 if (PyModule_AddIntMacro(m, XATTR_SIZE_MAX)) return -1;
Benjamin Peterson799bd802011-08-31 22:15:17 -040014128#endif
14129
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030014130#if HAVE_DECL_RTLD_LAZY
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014131 if (PyModule_AddIntMacro(m, RTLD_LAZY)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020014132#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030014133#if HAVE_DECL_RTLD_NOW
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014134 if (PyModule_AddIntMacro(m, RTLD_NOW)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020014135#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030014136#if HAVE_DECL_RTLD_GLOBAL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014137 if (PyModule_AddIntMacro(m, RTLD_GLOBAL)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020014138#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030014139#if HAVE_DECL_RTLD_LOCAL
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014140 if (PyModule_AddIntMacro(m, RTLD_LOCAL)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020014141#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030014142#if HAVE_DECL_RTLD_NODELETE
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014143 if (PyModule_AddIntMacro(m, RTLD_NODELETE)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020014144#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030014145#if HAVE_DECL_RTLD_NOLOAD
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014146 if (PyModule_AddIntMacro(m, RTLD_NOLOAD)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020014147#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030014148#if HAVE_DECL_RTLD_DEEPBIND
Charles-Francois Natali74ca8862013-05-20 19:13:19 +020014149 if (PyModule_AddIntMacro(m, RTLD_DEEPBIND)) return -1;
Victor Stinner8b905bd2011-10-25 13:34:04 +020014150#endif
Michael Feltc5ae1692017-12-19 13:58:49 +010014151#if HAVE_DECL_RTLD_MEMBER
14152 if (PyModule_AddIntMacro(m, RTLD_MEMBER)) return -1;
14153#endif
Victor Stinner8b905bd2011-10-25 13:34:04 +020014154
Victor Stinner9b1f4742016-09-06 16:18:52 -070014155#ifdef HAVE_GETRANDOM_SYSCALL
14156 if (PyModule_AddIntMacro(m, GRND_RANDOM)) return -1;
14157 if (PyModule_AddIntMacro(m, GRND_NONBLOCK)) return -1;
14158#endif
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014159#ifdef HAVE_MEMFD_CREATE
14160 if (PyModule_AddIntMacro(m, MFD_CLOEXEC)) return -1;
14161 if (PyModule_AddIntMacro(m, MFD_ALLOW_SEALING)) return -1;
14162#ifdef MFD_HUGETLB
14163 if (PyModule_AddIntMacro(m, MFD_HUGETLB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014164#endif
14165#ifdef MFD_HUGE_SHIFT
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014166 if (PyModule_AddIntMacro(m, MFD_HUGE_SHIFT)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014167#endif
14168#ifdef MFD_HUGE_MASK
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014169 if (PyModule_AddIntMacro(m, MFD_HUGE_MASK)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014170#endif
14171#ifdef MFD_HUGE_64KB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014172 if (PyModule_AddIntMacro(m, MFD_HUGE_64KB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014173#endif
14174#ifdef MFD_HUGE_512KB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014175 if (PyModule_AddIntMacro(m, MFD_HUGE_512KB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014176#endif
14177#ifdef MFD_HUGE_1MB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014178 if (PyModule_AddIntMacro(m, MFD_HUGE_1MB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014179#endif
14180#ifdef MFD_HUGE_2MB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014181 if (PyModule_AddIntMacro(m, MFD_HUGE_2MB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014182#endif
14183#ifdef MFD_HUGE_8MB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014184 if (PyModule_AddIntMacro(m, MFD_HUGE_8MB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014185#endif
14186#ifdef MFD_HUGE_16MB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014187 if (PyModule_AddIntMacro(m, MFD_HUGE_16MB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014188#endif
14189#ifdef MFD_HUGE_32MB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014190 if (PyModule_AddIntMacro(m, MFD_HUGE_32MB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014191#endif
14192#ifdef MFD_HUGE_256MB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014193 if (PyModule_AddIntMacro(m, MFD_HUGE_256MB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014194#endif
14195#ifdef MFD_HUGE_512MB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014196 if (PyModule_AddIntMacro(m, MFD_HUGE_512MB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014197#endif
14198#ifdef MFD_HUGE_1GB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014199 if (PyModule_AddIntMacro(m, MFD_HUGE_1GB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014200#endif
14201#ifdef MFD_HUGE_2GB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014202 if (PyModule_AddIntMacro(m, MFD_HUGE_2GB)) return -1;
Zackery Spytze70bfa952019-05-29 14:43:50 -060014203#endif
14204#ifdef MFD_HUGE_16GB
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014205 if (PyModule_AddIntMacro(m, MFD_HUGE_16GB)) return -1;
14206#endif
14207#endif
Victor Stinner9b1f4742016-09-06 16:18:52 -070014208
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +020014209#if defined(__APPLE__)
14210 if (PyModule_AddIntConstant(m, "_COPYFILE_DATA", COPYFILE_DATA)) return -1;
14211#endif
14212
Steve Dower2438cdf2019-03-29 16:37:16 -070014213#ifdef MS_WINDOWS
14214 if (PyModule_AddIntConstant(m, "_LOAD_LIBRARY_SEARCH_DEFAULT_DIRS", LOAD_LIBRARY_SEARCH_DEFAULT_DIRS)) return -1;
14215 if (PyModule_AddIntConstant(m, "_LOAD_LIBRARY_SEARCH_APPLICATION_DIR", LOAD_LIBRARY_SEARCH_APPLICATION_DIR)) return -1;
14216 if (PyModule_AddIntConstant(m, "_LOAD_LIBRARY_SEARCH_SYSTEM32", LOAD_LIBRARY_SEARCH_SYSTEM32)) return -1;
14217 if (PyModule_AddIntConstant(m, "_LOAD_LIBRARY_SEARCH_USER_DIRS", LOAD_LIBRARY_SEARCH_USER_DIRS)) return -1;
14218 if (PyModule_AddIntConstant(m, "_LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR", LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR)) return -1;
14219#endif
14220
Victor Stinner8c62be82010-05-06 00:08:46 +000014221 return 0;
Barry Warsaw4a342091996-12-19 23:50:02 +000014222}
14223
14224
Martin v. Löwis1a214512008-06-11 05:26:20 +000014225static struct PyModuleDef posixmodule = {
Victor Stinner8c62be82010-05-06 00:08:46 +000014226 PyModuleDef_HEAD_INIT,
14227 MODNAME,
14228 posix__doc__,
14229 -1,
14230 posix_methods,
14231 NULL,
14232 NULL,
14233 NULL,
14234 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +000014235};
14236
14237
Serhiy Storchaka2d06e842015-12-25 19:53:18 +020014238static const char * const have_functions[] = {
Larry Hastings9cf065c2012-06-22 16:30:09 -070014239
14240#ifdef HAVE_FACCESSAT
14241 "HAVE_FACCESSAT",
14242#endif
14243
14244#ifdef HAVE_FCHDIR
14245 "HAVE_FCHDIR",
14246#endif
14247
14248#ifdef HAVE_FCHMOD
14249 "HAVE_FCHMOD",
14250#endif
14251
14252#ifdef HAVE_FCHMODAT
14253 "HAVE_FCHMODAT",
14254#endif
14255
14256#ifdef HAVE_FCHOWN
14257 "HAVE_FCHOWN",
14258#endif
14259
Larry Hastings00964ed2013-08-12 13:49:30 -040014260#ifdef HAVE_FCHOWNAT
14261 "HAVE_FCHOWNAT",
14262#endif
14263
Larry Hastings9cf065c2012-06-22 16:30:09 -070014264#ifdef HAVE_FEXECVE
14265 "HAVE_FEXECVE",
14266#endif
14267
14268#ifdef HAVE_FDOPENDIR
14269 "HAVE_FDOPENDIR",
14270#endif
14271
Georg Brandl306336b2012-06-24 12:55:33 +020014272#ifdef HAVE_FPATHCONF
14273 "HAVE_FPATHCONF",
14274#endif
14275
Larry Hastings9cf065c2012-06-22 16:30:09 -070014276#ifdef HAVE_FSTATAT
14277 "HAVE_FSTATAT",
14278#endif
14279
14280#ifdef HAVE_FSTATVFS
14281 "HAVE_FSTATVFS",
14282#endif
14283
Steve Dowerfe0a41a2015-03-20 19:50:46 -070014284#if defined HAVE_FTRUNCATE || defined MS_WINDOWS
Georg Brandl306336b2012-06-24 12:55:33 +020014285 "HAVE_FTRUNCATE",
14286#endif
14287
Larry Hastings9cf065c2012-06-22 16:30:09 -070014288#ifdef HAVE_FUTIMENS
14289 "HAVE_FUTIMENS",
14290#endif
14291
14292#ifdef HAVE_FUTIMES
14293 "HAVE_FUTIMES",
14294#endif
14295
14296#ifdef HAVE_FUTIMESAT
14297 "HAVE_FUTIMESAT",
14298#endif
14299
14300#ifdef HAVE_LINKAT
14301 "HAVE_LINKAT",
14302#endif
14303
14304#ifdef HAVE_LCHFLAGS
14305 "HAVE_LCHFLAGS",
14306#endif
14307
14308#ifdef HAVE_LCHMOD
14309 "HAVE_LCHMOD",
14310#endif
14311
14312#ifdef HAVE_LCHOWN
14313 "HAVE_LCHOWN",
14314#endif
14315
14316#ifdef HAVE_LSTAT
14317 "HAVE_LSTAT",
14318#endif
14319
14320#ifdef HAVE_LUTIMES
14321 "HAVE_LUTIMES",
14322#endif
14323
Zackery Spytz43fdbd22019-05-29 13:57:07 -060014324#ifdef HAVE_MEMFD_CREATE
14325 "HAVE_MEMFD_CREATE",
14326#endif
14327
Larry Hastings9cf065c2012-06-22 16:30:09 -070014328#ifdef HAVE_MKDIRAT
14329 "HAVE_MKDIRAT",
14330#endif
14331
14332#ifdef HAVE_MKFIFOAT
14333 "HAVE_MKFIFOAT",
14334#endif
14335
14336#ifdef HAVE_MKNODAT
14337 "HAVE_MKNODAT",
14338#endif
14339
14340#ifdef HAVE_OPENAT
14341 "HAVE_OPENAT",
14342#endif
14343
14344#ifdef HAVE_READLINKAT
14345 "HAVE_READLINKAT",
14346#endif
14347
14348#ifdef HAVE_RENAMEAT
14349 "HAVE_RENAMEAT",
14350#endif
14351
14352#ifdef HAVE_SYMLINKAT
14353 "HAVE_SYMLINKAT",
14354#endif
14355
14356#ifdef HAVE_UNLINKAT
14357 "HAVE_UNLINKAT",
14358#endif
14359
14360#ifdef HAVE_UTIMENSAT
14361 "HAVE_UTIMENSAT",
14362#endif
14363
14364#ifdef MS_WINDOWS
14365 "MS_WINDOWS",
14366#endif
14367
14368 NULL
14369};
14370
14371
Mark Hammondfe51c6d2002-08-02 02:27:13 +000014372PyMODINIT_FUNC
Thomas Woutersf3f33dc2000-07-21 06:00:07 +000014373INITFUNC(void)
Guido van Rossumb6775db1994-08-01 11:34:53 +000014374{
Victor Stinner8c62be82010-05-06 00:08:46 +000014375 PyObject *m, *v;
Larry Hastings9cf065c2012-06-22 16:30:09 -070014376 PyObject *list;
Serhiy Storchaka2d06e842015-12-25 19:53:18 +020014377 const char * const *trace;
Tim Peters5aa91602002-01-30 05:46:57 +000014378
Victor Stinner8c62be82010-05-06 00:08:46 +000014379 m = PyModule_Create(&posixmodule);
14380 if (m == NULL)
14381 return NULL;
Tim Peters5aa91602002-01-30 05:46:57 +000014382
Victor Stinner8c62be82010-05-06 00:08:46 +000014383 /* Initialize environ dictionary */
14384 v = convertenviron();
14385 Py_XINCREF(v);
14386 if (v == NULL || PyModule_AddObject(m, "environ", v) != 0)
14387 return NULL;
14388 Py_DECREF(v);
Fred Drakec9680921999-12-13 16:37:25 +000014389
Victor Stinner8c62be82010-05-06 00:08:46 +000014390 if (all_ins(m))
14391 return NULL;
Barry Warsaw4a342091996-12-19 23:50:02 +000014392
Victor Stinner8c62be82010-05-06 00:08:46 +000014393 if (setup_confname_tables(m))
14394 return NULL;
Fred Drakebec628d1999-12-15 18:31:10 +000014395
Victor Stinner8c62be82010-05-06 00:08:46 +000014396 Py_INCREF(PyExc_OSError);
14397 PyModule_AddObject(m, "error", PyExc_OSError);
Fred Drake762e2061999-08-26 17:23:54 +000014398
Guido van Rossumb3d39562000-01-31 18:41:26 +000014399#ifdef HAVE_PUTENV
Victor Stinner8c62be82010-05-06 00:08:46 +000014400 if (posix_putenv_garbage == NULL)
14401 posix_putenv_garbage = PyDict_New();
Guido van Rossumb3d39562000-01-31 18:41:26 +000014402#endif
Guido van Rossum98bf58f2001-10-18 20:34:25 +000014403
Victor Stinner8c62be82010-05-06 00:08:46 +000014404 if (!initialized) {
Ross Lagerwall7807c352011-03-17 20:20:30 +020014405#if defined(HAVE_WAITID) && !defined(__APPLE__)
14406 waitid_result_desc.name = MODNAME ".waitid_result";
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014407 WaitidResultType = PyStructSequence_NewType(&waitid_result_desc);
14408 if (WaitidResultType == NULL) {
Victor Stinner1c8f0592013-07-22 22:24:54 +020014409 return NULL;
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014410 }
Ross Lagerwall7807c352011-03-17 20:20:30 +020014411#endif
14412
Christian Heimes25827622013-10-12 01:27:08 +020014413 stat_result_desc.name = "os.stat_result"; /* see issue #19209 */
Victor Stinner8c62be82010-05-06 00:08:46 +000014414 stat_result_desc.fields[7].name = PyStructSequence_UnnamedField;
14415 stat_result_desc.fields[8].name = PyStructSequence_UnnamedField;
14416 stat_result_desc.fields[9].name = PyStructSequence_UnnamedField;
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014417 StatResultType = PyStructSequence_NewType(&stat_result_desc);
14418 if (StatResultType == NULL) {
Victor Stinner1c8f0592013-07-22 22:24:54 +020014419 return NULL;
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014420 }
14421 structseq_new = StatResultType->tp_new;
14422 StatResultType->tp_new = statresult_new;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000014423
Christian Heimes25827622013-10-12 01:27:08 +020014424 statvfs_result_desc.name = "os.statvfs_result"; /* see issue #19209 */
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014425 StatVFSResultType = PyStructSequence_NewType(&statvfs_result_desc);
14426 if (StatVFSResultType == NULL) {
Victor Stinner1c8f0592013-07-22 22:24:54 +020014427 return NULL;
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014428 }
Martin v. Löwis05bfe1f2008-12-29 18:21:47 +000014429#ifdef NEED_TICKS_PER_SECOND
14430# if defined(HAVE_SYSCONF) && defined(_SC_CLK_TCK)
Victor Stinner8c62be82010-05-06 00:08:46 +000014431 ticks_per_second = sysconf(_SC_CLK_TCK);
Martin v. Löwis05bfe1f2008-12-29 18:21:47 +000014432# elif defined(HZ)
Victor Stinner8c62be82010-05-06 00:08:46 +000014433 ticks_per_second = HZ;
Martin v. Löwis05bfe1f2008-12-29 18:21:47 +000014434# else
Victor Stinner8c62be82010-05-06 00:08:46 +000014435 ticks_per_second = 60; /* magic fallback value; may be bogus */
Martin v. Löwis05bfe1f2008-12-29 18:21:47 +000014436# endif
14437#endif
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014438
William Orr81574b82018-10-01 22:19:56 -070014439#if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014440 sched_param_desc.name = MODNAME ".sched_param";
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014441 SchedParamType = PyStructSequence_NewType(&sched_param_desc);
14442 if (SchedParamType == NULL) {
Victor Stinner1c8f0592013-07-22 22:24:54 +020014443 return NULL;
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014444 }
14445 SchedParamType->tp_new = os_sched_param;
Benjamin Peterson94b580d2011-08-02 17:30:04 -050014446#endif
Antoine Pitroubcf2b592012-02-08 23:28:36 +010014447
14448 /* initialize TerminalSize_info */
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014449 TerminalSizeType = PyStructSequence_NewType(&TerminalSize_desc);
14450 if (TerminalSizeType == NULL) {
Victor Stinner1c8f0592013-07-22 22:24:54 +020014451 return NULL;
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014452 }
Victor Stinner6036e442015-03-08 01:58:04 +010014453
14454 /* initialize scandir types */
14455 if (PyType_Ready(&ScandirIteratorType) < 0)
14456 return NULL;
14457 if (PyType_Ready(&DirEntryType) < 0)
14458 return NULL;
Victor Stinner8c62be82010-05-06 00:08:46 +000014459 }
Ross Lagerwall7807c352011-03-17 20:20:30 +020014460#if defined(HAVE_WAITID) && !defined(__APPLE__)
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014461 Py_INCREF((PyObject*) WaitidResultType);
14462 PyModule_AddObject(m, "waitid_result", (PyObject*) WaitidResultType);
Ross Lagerwall7807c352011-03-17 20:20:30 +020014463#endif
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014464 Py_INCREF((PyObject*) StatResultType);
14465 PyModule_AddObject(m, "stat_result", (PyObject*) StatResultType);
14466 Py_INCREF((PyObject*) StatVFSResultType);
Victor Stinner8c62be82010-05-06 00:08:46 +000014467 PyModule_AddObject(m, "statvfs_result",
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014468 (PyObject*) StatVFSResultType);
Benjamin Petersone3298dd2011-08-02 18:40:46 -050014469
14470#if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER)
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014471 Py_INCREF(SchedParamType);
14472 PyModule_AddObject(m, "sched_param", (PyObject *)SchedParamType);
Benjamin Petersone3298dd2011-08-02 18:40:46 -050014473#endif
Thomas Wouters477c8d52006-05-27 19:21:47 +000014474
Larry Hastings605a62d2012-06-24 04:33:36 -070014475 times_result_desc.name = MODNAME ".times_result";
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014476 TimesResultType = PyStructSequence_NewType(&times_result_desc);
14477 if (TimesResultType == NULL) {
Victor Stinner1c8f0592013-07-22 22:24:54 +020014478 return NULL;
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014479 }
14480 PyModule_AddObject(m, "times_result", (PyObject *)TimesResultType);
Larry Hastings605a62d2012-06-24 04:33:36 -070014481
14482 uname_result_desc.name = MODNAME ".uname_result";
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014483 UnameResultType = PyStructSequence_NewType(&uname_result_desc);
14484 if (UnameResultType == NULL) {
Victor Stinner1c8f0592013-07-22 22:24:54 +020014485 return NULL;
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014486 }
14487 PyModule_AddObject(m, "uname_result", (PyObject *)UnameResultType);
Larry Hastings605a62d2012-06-24 04:33:36 -070014488
Thomas Wouters477c8d52006-05-27 19:21:47 +000014489#ifdef __APPLE__
Victor Stinner8c62be82010-05-06 00:08:46 +000014490 /*
14491 * Step 2 of weak-linking support on Mac OS X.
14492 *
14493 * The code below removes functions that are not available on the
14494 * currently active platform.
14495 *
14496 * This block allow one to use a python binary that was build on
Larry Hastings9cf065c2012-06-22 16:30:09 -070014497 * OSX 10.4 on OSX 10.3, without losing access to new APIs on
Victor Stinner8c62be82010-05-06 00:08:46 +000014498 * OSX 10.4.
14499 */
Thomas Wouters477c8d52006-05-27 19:21:47 +000014500#ifdef HAVE_FSTATVFS
Victor Stinner8c62be82010-05-06 00:08:46 +000014501 if (fstatvfs == NULL) {
14502 if (PyObject_DelAttrString(m, "fstatvfs") == -1) {
14503 return NULL;
14504 }
14505 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000014506#endif /* HAVE_FSTATVFS */
14507
14508#ifdef HAVE_STATVFS
Victor Stinner8c62be82010-05-06 00:08:46 +000014509 if (statvfs == NULL) {
14510 if (PyObject_DelAttrString(m, "statvfs") == -1) {
14511 return NULL;
14512 }
14513 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000014514#endif /* HAVE_STATVFS */
14515
14516# ifdef HAVE_LCHOWN
Victor Stinner8c62be82010-05-06 00:08:46 +000014517 if (lchown == NULL) {
14518 if (PyObject_DelAttrString(m, "lchown") == -1) {
14519 return NULL;
14520 }
14521 }
Thomas Wouters477c8d52006-05-27 19:21:47 +000014522#endif /* HAVE_LCHOWN */
14523
14524
14525#endif /* __APPLE__ */
Antoine Pitroubcf2b592012-02-08 23:28:36 +010014526
Eddie Elizondo474eedf2018-11-13 04:09:31 -080014527 Py_INCREF(TerminalSizeType);
14528 PyModule_AddObject(m, "terminal_size", (PyObject*)TerminalSizeType);
Antoine Pitroubcf2b592012-02-08 23:28:36 +010014529
Larry Hastings6fe20b32012-04-19 15:07:49 -070014530 billion = PyLong_FromLong(1000000000);
14531 if (!billion)
14532 return NULL;
14533
Larry Hastings9cf065c2012-06-22 16:30:09 -070014534 /* suppress "function not used" warnings */
14535 {
14536 int ignored;
14537 fd_specified("", -1);
14538 follow_symlinks_specified("", 1);
14539 dir_fd_and_follow_symlinks_invalid("chmod", DEFAULT_DIR_FD, 1);
14540 dir_fd_converter(Py_None, &ignored);
14541 dir_fd_unavailable(Py_None, &ignored);
14542 }
14543
14544 /*
14545 * provide list of locally available functions
14546 * so os.py can populate support_* lists
14547 */
14548 list = PyList_New(0);
14549 if (!list)
14550 return NULL;
14551 for (trace = have_functions; *trace; trace++) {
14552 PyObject *unicode = PyUnicode_DecodeASCII(*trace, strlen(*trace), NULL);
14553 if (!unicode)
14554 return NULL;
14555 if (PyList_Append(list, unicode))
14556 return NULL;
14557 Py_DECREF(unicode);
14558 }
14559 PyModule_AddObject(m, "_have_functions", list);
Ned Deilyeb3be662016-08-15 14:40:38 -040014560
14561 Py_INCREF((PyObject *) &DirEntryType);
Brett Cannona32c4d02016-06-24 14:14:44 -070014562 PyModule_AddObject(m, "DirEntry", (PyObject *)&DirEntryType);
Larry Hastings9cf065c2012-06-22 16:30:09 -070014563
14564 initialized = 1;
14565
Victor Stinner8c62be82010-05-06 00:08:46 +000014566 return m;
Guido van Rossumb6775db1994-08-01 11:34:53 +000014567}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000014568
14569#ifdef __cplusplus
14570}
14571#endif