· 6 years ago · Mar 26, 2020, 10:34 AM
1
2/* POSIX module implementation */
3
4/* 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
6 functions are either unimplemented or implemented differently. The source
7 assumes that for Windows NT, the macro 'MS_WINDOWS' is defined independent
8 of the compiler used. Different compilers define their own feature
9 test macro, e.g. '_MSC_VER'. */
10
11
12
13#ifdef __APPLE__
14 /*
15 * Step 1 of support for weak-linking a number of symbols existing on
16 * 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
25#define PY_SSIZE_T_CLEAN
26
27#include "Python.h"
28#include "pythread.h"
29#include "structmember.h"
30#ifndef MS_WINDOWS
31#include "posixmodule.h"
32#else
33#include "winreparse.h"
34#endif
35
36/* On android API level 21, 'AT_EACCESS' is not declared although
37 * HAVE_FACCESSAT is defined. */
38#ifdef __ANDROID__
39#undef HAVE_FACCESSAT
40#endif
41
42#include <stdio.h> /* needed for ctermid() */
43
44#ifdef __cplusplus
45extern "C" {
46#endif
47
48PyDoc_STRVAR(posix__doc__,
49"This module provides access to operating system functionality that is\n\
50standardized by the C Standard and the POSIX standard (a thinly\n\
51disguised Unix interface). Refer to the library manual and\n\
52corresponding Unix manual entries for more information on calls.");
53
54
55#ifdef HAVE_SYS_UIO_H
56#include <sys/uio.h>
57#endif
58
59#ifdef HAVE_SYS_SYSMACROS_H
60/* GNU C Library: major(), minor(), makedev() */
61#include <sys/sysmacros.h>
62#endif
63
64#ifdef HAVE_SYS_TYPES_H
65#include <sys/types.h>
66#endif /* HAVE_SYS_TYPES_H */
67
68#ifdef HAVE_SYS_STAT_H
69#include <sys/stat.h>
70#endif /* HAVE_SYS_STAT_H */
71
72#ifdef HAVE_SYS_WAIT_H
73#include <sys/wait.h> /* For WNOHANG */
74#endif
75
76#ifdef HAVE_SIGNAL_H
77#include <signal.h>
78#endif
79
80#ifdef HAVE_FCNTL_H
81#include <fcntl.h>
82#endif /* HAVE_FCNTL_H */
83
84#ifdef HAVE_GRP_H
85#include <grp.h>
86#endif
87
88#ifdef HAVE_SYSEXITS_H
89#include <sysexits.h>
90#endif /* HAVE_SYSEXITS_H */
91
92#ifdef HAVE_SYS_LOADAVG_H
93#include <sys/loadavg.h>
94#endif
95
96#ifdef HAVE_SYS_SENDFILE_H
97#include <sys/sendfile.h>
98#endif
99
100#ifdef HAVE_SCHED_H
101#include <sched.h>
102#endif
103
104#if !defined(CPU_ALLOC) && defined(HAVE_SCHED_SETAFFINITY)
105#undef HAVE_SCHED_SETAFFINITY
106#endif
107
108#if defined(HAVE_SYS_XATTR_H) && defined(__GLIBC__) && !defined(__FreeBSD_kernel__) && !defined(__GNU__)
109#define USE_XATTRS
110#endif
111
112#ifdef USE_XATTRS
113#include <sys/xattr.h>
114#endif
115
116#if defined(__FreeBSD__) || defined(__DragonFly__) || defined(__APPLE__)
117#ifdef HAVE_SYS_SOCKET_H
118#include <sys/socket.h>
119#endif
120#endif
121
122#ifdef HAVE_DLFCN_H
123#include <dlfcn.h>
124#endif
125
126#ifdef __hpux
127#include <sys/mpctl.h>
128#endif
129
130#if defined(__DragonFly__) || \
131 defined(__OpenBSD__) || \
132 defined(__FreeBSD__) || \
133 defined(__NetBSD__) || \
134 defined(__APPLE__)
135#include <sys/sysctl.h>
136#endif
137
138#ifdef HAVE_LINUX_RANDOM_H
139# include <linux/random.h>
140#endif
141#ifdef HAVE_GETRANDOM_SYSCALL
142# include <sys/syscall.h>
143#endif
144
145#if defined(MS_WINDOWS)
146# define TERMSIZE_USE_CONIO
147#elif defined(HAVE_SYS_IOCTL_H)
148# include <sys/ioctl.h>
149# if defined(HAVE_TERMIOS_H)
150# include <termios.h>
151# endif
152# if defined(TIOCGWINSZ)
153# define TERMSIZE_USE_IOCTL
154# endif
155#endif /* MS_WINDOWS */
156
157/* Various compilers have only certain posix functions */
158/* XXX Gosh I wish these were all moved into pyconfig.h */
159#if defined(__WATCOMC__) && !defined(__QNX__) /* Watcom compiler */
160#define HAVE_OPENDIR 1
161#define HAVE_SYSTEM 1
162#include <process.h>
163#else
164#ifdef _MSC_VER /* Microsoft compiler */
165#define HAVE_GETPPID 1
166#define HAVE_GETLOGIN 1
167#define HAVE_SPAWNV 1
168#define HAVE_EXECV 1
169#define HAVE_WSPAWNV 1
170#define HAVE_WEXECV 1
171#define HAVE_PIPE 1
172#define HAVE_SYSTEM 1
173#define HAVE_CWAIT 1
174#define HAVE_FSYNC 1
175#define fsync _commit
176#else
177/* Unix functions that the configure script doesn't check for */
178#define HAVE_EXECV 1
179#define HAVE_FORK 1
180#if defined(__USLC__) && defined(__SCO_VERSION__) /* SCO UDK Compiler */
181#define HAVE_FORK1 1
182#endif
183#define HAVE_GETEGID 1
184#define HAVE_GETEUID 1
185#define HAVE_GETGID 1
186#define HAVE_GETPPID 1
187#define HAVE_GETUID 1
188#define HAVE_KILL 1
189#define HAVE_OPENDIR 1
190#define HAVE_PIPE 1
191#define HAVE_SYSTEM 1
192#define HAVE_WAIT 1
193#define HAVE_TTYNAME 1
194#endif /* _MSC_VER */
195#endif /* ! __WATCOMC__ || __QNX__ */
196
197
198/*[clinic input]
199# one of the few times we lie about this name!
200module os
201[clinic start generated code]*/
202/*[clinic end generated code: output=da39a3ee5e6b4b0d input=94a0f0f978acae17]*/
203
204#ifndef _MSC_VER
205
206#if defined(__sgi)&&_COMPILER_VERSION>=700
207/* declare ctermid_r if compiling with MIPSPro 7.x in ANSI C mode
208 (default) */
209extern char *ctermid_r(char *);
210#endif
211
212#ifndef HAVE_UNISTD_H
213#if ( defined(__WATCOMC__) || defined(_MSC_VER) ) && !defined(__QNX__)
214extern int mkdir(const char *);
215#else
216extern int mkdir(const char *, mode_t);
217#endif
218#if defined(__IBMC__) || defined(__IBMCPP__)
219extern int chdir(char *);
220extern int rmdir(char *);
221#else
222extern int chdir(const char *);
223extern int rmdir(const char *);
224#endif
225extern int chmod(const char *, mode_t);
226/*#ifdef HAVE_FCHMOD
227extern int fchmod(int, mode_t);
228#endif*/
229/*#ifdef HAVE_LCHMOD
230extern int lchmod(const char *, mode_t);
231#endif*/
232extern int chown(const char *, uid_t, gid_t);
233extern char *getcwd(char *, int);
234extern char *strerror(int);
235extern int link(const char *, const char *);
236extern int rename(const char *, const char *);
237extern int stat(const char *, struct stat *);
238extern int unlink(const char *);
239#ifdef HAVE_SYMLINK
240extern int symlink(const char *, const char *);
241#endif /* HAVE_SYMLINK */
242#ifdef HAVE_LSTAT
243extern int lstat(const char *, struct stat *);
244#endif /* HAVE_LSTAT */
245#endif /* !HAVE_UNISTD_H */
246
247#endif /* !_MSC_VER */
248
249#ifdef HAVE_UTIME_H
250#include <utime.h>
251#endif /* HAVE_UTIME_H */
252
253#ifdef HAVE_SYS_UTIME_H
254#include <sys/utime.h>
255#define HAVE_UTIME_H /* pretend we do for the rest of this file */
256#endif /* HAVE_SYS_UTIME_H */
257
258#ifdef HAVE_SYS_TIMES_H
259#include <sys/times.h>
260#endif /* HAVE_SYS_TIMES_H */
261
262#ifdef HAVE_SYS_PARAM_H
263#include <sys/param.h>
264#endif /* HAVE_SYS_PARAM_H */
265
266#ifdef HAVE_SYS_UTSNAME_H
267#include <sys/utsname.h>
268#endif /* HAVE_SYS_UTSNAME_H */
269
270#ifdef HAVE_DIRENT_H
271#include <dirent.h>
272#define NAMLEN(dirent) strlen((dirent)->d_name)
273#else
274#if defined(__WATCOMC__) && !defined(__QNX__)
275#include <direct.h>
276#define NAMLEN(dirent) strlen((dirent)->d_name)
277#else
278#define dirent direct
279#define NAMLEN(dirent) (dirent)->d_namlen
280#endif
281#ifdef HAVE_SYS_NDIR_H
282#include <sys/ndir.h>
283#endif
284#ifdef HAVE_SYS_DIR_H
285#include <sys/dir.h>
286#endif
287#ifdef HAVE_NDIR_H
288#include <ndir.h>
289#endif
290#endif
291
292#ifdef _MSC_VER
293#ifdef HAVE_DIRECT_H
294#include <direct.h>
295#endif
296#ifdef HAVE_IO_H
297#include <io.h>
298#endif
299#ifdef HAVE_PROCESS_H
300#include <process.h>
301#endif
302#ifndef IO_REPARSE_TAG_SYMLINK
303#define IO_REPARSE_TAG_SYMLINK (0xA000000CL)
304#endif
305#ifndef IO_REPARSE_TAG_MOUNT_POINT
306#define IO_REPARSE_TAG_MOUNT_POINT (0xA0000003L)
307#endif
308#include "osdefs.h"
309#include <malloc.h>
310#include <windows.h>
311#include <shellapi.h> /* for ShellExecute() */
312#include <lmcons.h> /* for UNLEN */
313#ifdef SE_CREATE_SYMBOLIC_LINK_NAME /* Available starting with Vista */
314#define HAVE_SYMLINK
315static int win32_can_symlink = 0;
316#endif
317#endif /* _MSC_VER */
318
319#ifndef MAXPATHLEN
320#if defined(PATH_MAX) && PATH_MAX > 1024
321#define MAXPATHLEN PATH_MAX
322#else
323#define MAXPATHLEN 1024
324#endif
325#endif /* MAXPATHLEN */
326
327#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
342#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)
348#endif /* UNION_WAIT */
349
350/* 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?). */
352#if defined(HAVE_CTERMID_R)
353#define USE_CTERMID_R
354#endif
355
356/* choose the appropriate stat and fstat functions and return structs */
357#undef STAT
358#undef FSTAT
359#undef STRUCT_STAT
360#ifdef MS_WINDOWS
361# define STAT win32_stat
362# define LSTAT win32_lstat
363# define FSTAT _Py_fstat_noraise
364# define STRUCT_STAT struct _Py_stat_struct
365#else
366# define STAT stat
367# define LSTAT lstat
368# define FSTAT fstat
369# define STRUCT_STAT struct stat
370#endif
371
372#if defined(MAJOR_IN_MKDEV)
373#include <sys/mkdev.h>
374#else
375#if defined(MAJOR_IN_SYSMACROS)
376#include <sys/sysmacros.h>
377#endif
378#if defined(HAVE_MKNOD) && defined(HAVE_SYS_MKDEV_H)
379#include <sys/mkdev.h>
380#endif
381#endif
382
383#ifdef MS_WINDOWS
384#define INITFUNC PyInit_nt
385#define MODNAME "nt"
386#else
387#define INITFUNC PyInit_posix
388#define MODNAME "posix"
389#endif
390
391#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
395
396#ifdef _Py_MEMORY_SANITIZER
397# include <sanitizer/msan_interface.h>
398#endif
399
400#ifdef HAVE_FORK
401static void
402run_at_forkers(PyObject *lst, int reverse)
403{
404 Py_ssize_t i;
405 PyObject *cpy;
406
407 if (lst != NULL) {
408 assert(PyList_CheckExact(lst));
409
410 /* Use a list copy in case register_at_fork() is called from
411 * one of the callbacks.
412 */
413 cpy = PyList_GetSlice(lst, 0, PyList_GET_SIZE(lst));
414 if (cpy == NULL)
415 PyErr_WriteUnraisable(lst);
416 else {
417 if (reverse)
418 PyList_Reverse(cpy);
419 for (i = 0; i < PyList_GET_SIZE(cpy); i++) {
420 PyObject *func, *res;
421 func = PyList_GET_ITEM(cpy, i);
422 res = PyObject_CallObject(func, NULL);
423 if (res == NULL)
424 PyErr_WriteUnraisable(func);
425 else
426 Py_DECREF(res);
427 }
428 Py_DECREF(cpy);
429 }
430 }
431}
432
433void
434PyOS_BeforeFork(void)
435{
436 run_at_forkers(PyThreadState_Get()->interp->before_forkers, 1);
437
438 _PyImport_AcquireLock();
439}
440
441void
442PyOS_AfterFork_Parent(void)
443{
444 if (_PyImport_ReleaseLock() <= 0)
445 Py_FatalError("failed releasing import lock after fork");
446
447 run_at_forkers(PyThreadState_Get()->interp->after_forkers_parent, 0);
448}
449
450void
451PyOS_AfterFork_Child(void)
452{
453 _PyGILState_Reinit();
454 PyEval_ReInitThreads();
455 _PyImport_ReInitLock();
456 _PySignal_AfterFork();
457
458 run_at_forkers(PyThreadState_Get()->interp->after_forkers_child, 0);
459}
460
461static int
462register_at_forker(PyObject **lst, PyObject *func)
463{
464 if (func == NULL) /* nothing to register? do nothing. */
465 return 0;
466 if (*lst == NULL) {
467 *lst = PyList_New(0);
468 if (*lst == NULL)
469 return -1;
470 }
471 return PyList_Append(*lst, func);
472}
473#endif
474
475/* Legacy wrapper */
476void
477PyOS_AfterFork(void)
478{
479#ifdef HAVE_FORK
480 PyOS_AfterFork_Child();
481#endif
482}
483
484
485#ifdef MS_WINDOWS
486/* defined in fileutils.c */
487PyAPI_FUNC(void) _Py_time_t_to_FILE_TIME(time_t, int, FILETIME *);
488PyAPI_FUNC(void) _Py_attribute_data_to_stat(BY_HANDLE_FILE_INFORMATION *,
489 ULONG, struct _Py_stat_struct *);
490#endif
491
492#ifdef MS_WINDOWS
493static int
494win32_warn_bytes_api()
495{
496 return PyErr_WarnEx(PyExc_DeprecationWarning,
497 "The Windows bytes API has been deprecated, "
498 "use Unicode filenames instead",
499 1);
500}
501#endif
502
503
504#ifndef MS_WINDOWS
505PyObject *
506_PyLong_FromUid(uid_t uid)
507{
508 if (uid == (uid_t)-1)
509 return PyLong_FromLong(-1);
510 return PyLong_FromUnsignedLong(uid);
511}
512
513PyObject *
514_PyLong_FromGid(gid_t gid)
515{
516 if (gid == (gid_t)-1)
517 return PyLong_FromLong(-1);
518 return PyLong_FromUnsignedLong(gid);
519}
520
521int
522_Py_Uid_Converter(PyObject *obj, void *p)
523{
524 uid_t uid;
525 PyObject *index;
526 int overflow;
527 long result;
528 unsigned long uresult;
529
530 index = PyNumber_Index(obj);
531 if (index == NULL) {
532 PyErr_Format(PyExc_TypeError,
533 "uid should be integer, not %.200s",
534 Py_TYPE(obj)->tp_name);
535 return 0;
536 }
537
538 /*
539 * Handling uid_t is complicated for two reasons:
540 * * Although uid_t is (always?) unsigned, it still
541 * accepts -1.
542 * * We don't know its size in advance--it may be
543 * bigger than an int, or it may be smaller than
544 * a long.
545 *
546 * So a bit of defensive programming is in order.
547 * Start with interpreting the value passed
548 * in as a signed long and see if it works.
549 */
550
551 result = PyLong_AsLongAndOverflow(index, &overflow);
552
553 if (!overflow) {
554 uid = (uid_t)result;
555
556 if (result == -1) {
557 if (PyErr_Occurred())
558 goto fail;
559 /* It's a legitimate -1, we're done. */
560 goto success;
561 }
562
563 /* Any other negative number is disallowed. */
564 if (result < 0)
565 goto underflow;
566
567 /* Ensure the value wasn't truncated. */
568 if (sizeof(uid_t) < sizeof(long) &&
569 (long)uid != result)
570 goto underflow;
571 goto success;
572 }
573
574 if (overflow < 0)
575 goto underflow;
576
577 /*
578 * Okay, the value overflowed a signed long. If it
579 * fits in an *unsigned* long, it may still be okay,
580 * as uid_t may be unsigned long on this platform.
581 */
582 uresult = PyLong_AsUnsignedLong(index);
583 if (PyErr_Occurred()) {
584 if (PyErr_ExceptionMatches(PyExc_OverflowError))
585 goto overflow;
586 goto fail;
587 }
588
589 uid = (uid_t)uresult;
590
591 /*
592 * If uid == (uid_t)-1, the user actually passed in ULONG_MAX,
593 * but this value would get interpreted as (uid_t)-1 by chown
594 * and its siblings. That's not what the user meant! So we
595 * throw an overflow exception instead. (We already
596 * handled a real -1 with PyLong_AsLongAndOverflow() above.)
597 */
598 if (uid == (uid_t)-1)
599 goto overflow;
600
601 /* Ensure the value wasn't truncated. */
602 if (sizeof(uid_t) < sizeof(long) &&
603 (unsigned long)uid != uresult)
604 goto overflow;
605 /* fallthrough */
606
607success:
608 Py_DECREF(index);
609 *(uid_t *)p = uid;
610 return 1;
611
612underflow:
613 PyErr_SetString(PyExc_OverflowError,
614 "uid is less than minimum");
615 goto fail;
616
617overflow:
618 PyErr_SetString(PyExc_OverflowError,
619 "uid is greater than maximum");
620 /* fallthrough */
621
622fail:
623 Py_DECREF(index);
624 return 0;
625}
626
627int
628_Py_Gid_Converter(PyObject *obj, void *p)
629{
630 gid_t gid;
631 PyObject *index;
632 int overflow;
633 long result;
634 unsigned long uresult;
635
636 index = PyNumber_Index(obj);
637 if (index == NULL) {
638 PyErr_Format(PyExc_TypeError,
639 "gid should be integer, not %.200s",
640 Py_TYPE(obj)->tp_name);
641 return 0;
642 }
643
644 /*
645 * Handling gid_t is complicated for two reasons:
646 * * Although gid_t is (always?) unsigned, it still
647 * accepts -1.
648 * * We don't know its size in advance--it may be
649 * bigger than an int, or it may be smaller than
650 * a long.
651 *
652 * So a bit of defensive programming is in order.
653 * Start with interpreting the value passed
654 * in as a signed long and see if it works.
655 */
656
657 result = PyLong_AsLongAndOverflow(index, &overflow);
658
659 if (!overflow) {
660 gid = (gid_t)result;
661
662 if (result == -1) {
663 if (PyErr_Occurred())
664 goto fail;
665 /* It's a legitimate -1, we're done. */
666 goto success;
667 }
668
669 /* Any other negative number is disallowed. */
670 if (result < 0) {
671 goto underflow;
672 }
673
674 /* Ensure the value wasn't truncated. */
675 if (sizeof(gid_t) < sizeof(long) &&
676 (long)gid != result)
677 goto underflow;
678 goto success;
679 }
680
681 if (overflow < 0)
682 goto underflow;
683
684 /*
685 * Okay, the value overflowed a signed long. If it
686 * fits in an *unsigned* long, it may still be okay,
687 * as gid_t may be unsigned long on this platform.
688 */
689 uresult = PyLong_AsUnsignedLong(index);
690 if (PyErr_Occurred()) {
691 if (PyErr_ExceptionMatches(PyExc_OverflowError))
692 goto overflow;
693 goto fail;
694 }
695
696 gid = (gid_t)uresult;
697
698 /*
699 * If gid == (gid_t)-1, the user actually passed in ULONG_MAX,
700 * but this value would get interpreted as (gid_t)-1 by chown
701 * and its siblings. That's not what the user meant! So we
702 * throw an overflow exception instead. (We already
703 * handled a real -1 with PyLong_AsLongAndOverflow() above.)
704 */
705 if (gid == (gid_t)-1)
706 goto overflow;
707
708 /* Ensure the value wasn't truncated. */
709 if (sizeof(gid_t) < sizeof(long) &&
710 (unsigned long)gid != uresult)
711 goto overflow;
712 /* fallthrough */
713
714success:
715 Py_DECREF(index);
716 *(gid_t *)p = gid;
717 return 1;
718
719underflow:
720 PyErr_SetString(PyExc_OverflowError,
721 "gid is less than minimum");
722 goto fail;
723
724overflow:
725 PyErr_SetString(PyExc_OverflowError,
726 "gid is greater than maximum");
727 /* fallthrough */
728
729fail:
730 Py_DECREF(index);
731 return 0;
732}
733#endif /* MS_WINDOWS */
734
735
736#define _PyLong_FromDev PyLong_FromLongLong
737
738
739#if defined(HAVE_MKNOD) && defined(HAVE_MAKEDEV)
740static int
741_Py_Dev_Converter(PyObject *obj, void *p)
742{
743 *((dev_t *)p) = PyLong_AsUnsignedLongLong(obj);
744 if (PyErr_Occurred())
745 return 0;
746 return 1;
747}
748#endif /* HAVE_MKNOD && HAVE_MAKEDEV */
749
750
751#ifdef AT_FDCWD
752/*
753 * Why the (int) cast? Solaris 10 defines AT_FDCWD as 0xffd19553 (-3041965);
754 * without the int cast, the value gets interpreted as uint (4291925331),
755 * which doesn't play nicely with all the initializer lines in this file that
756 * look like this:
757 * int dir_fd = DEFAULT_DIR_FD;
758 */
759#define DEFAULT_DIR_FD (int)AT_FDCWD
760#else
761#define DEFAULT_DIR_FD (-100)
762#endif
763
764static int
765_fd_converter(PyObject *o, int *p)
766{
767 int overflow;
768 long long_value;
769
770 PyObject *index = PyNumber_Index(o);
771 if (index == NULL) {
772 return 0;
773 }
774
775 assert(PyLong_Check(index));
776 long_value = PyLong_AsLongAndOverflow(index, &overflow);
777 Py_DECREF(index);
778 assert(!PyErr_Occurred());
779 if (overflow > 0 || long_value > INT_MAX) {
780 PyErr_SetString(PyExc_OverflowError,
781 "fd is greater than maximum");
782 return 0;
783 }
784 if (overflow < 0 || long_value < INT_MIN) {
785 PyErr_SetString(PyExc_OverflowError,
786 "fd is less than minimum");
787 return 0;
788 }
789
790 *p = (int)long_value;
791 return 1;
792}
793
794static int
795dir_fd_converter(PyObject *o, void *p)
796{
797 if (o == Py_None) {
798 *(int *)p = DEFAULT_DIR_FD;
799 return 1;
800 }
801 else if (PyIndex_Check(o)) {
802 return _fd_converter(o, (int *)p);
803 }
804 else {
805 PyErr_Format(PyExc_TypeError,
806 "argument should be integer or None, not %.200s",
807 Py_TYPE(o)->tp_name);
808 return 0;
809 }
810}
811
812
813/*
814 * A PyArg_ParseTuple "converter" function
815 * that handles filesystem paths in the manner
816 * preferred by the os module.
817 *
818 * path_converter accepts (Unicode) strings and their
819 * subclasses, and bytes and their subclasses. What
820 * it does with the argument depends on the platform:
821 *
822 * * On Windows, if we get a (Unicode) string we
823 * extract the wchar_t * and return it; if we get
824 * bytes we decode to wchar_t * and return that.
825 *
826 * * On all other platforms, strings are encoded
827 * to bytes using PyUnicode_FSConverter, then we
828 * extract the char * from the bytes object and
829 * return that.
830 *
831 * path_converter also optionally accepts signed
832 * integers (representing open file descriptors) instead
833 * of path strings.
834 *
835 * Input fields:
836 * path.nullable
837 * If nonzero, the path is permitted to be None.
838 * path.allow_fd
839 * If nonzero, the path is permitted to be a file handle
840 * (a signed int) instead of a string.
841 * path.function_name
842 * If non-NULL, path_converter will use that as the name
843 * of the function in error messages.
844 * (If path.function_name is NULL it omits the function name.)
845 * path.argument_name
846 * If non-NULL, path_converter will use that as the name
847 * of the parameter in error messages.
848 * (If path.argument_name is NULL it uses "path".)
849 *
850 * Output fields:
851 * path.wide
852 * Points to the path if it was expressed as Unicode
853 * and was not encoded. (Only used on Windows.)
854 * path.narrow
855 * Points to the path if it was expressed as bytes,
856 * or it was Unicode and was encoded to bytes. (On Windows,
857 * is a non-zero integer if the path was expressed as bytes.
858 * The type is deliberately incompatible to prevent misuse.)
859 * path.fd
860 * Contains a file descriptor if path.accept_fd was true
861 * and the caller provided a signed integer instead of any
862 * sort of string.
863 *
864 * WARNING: if your "path" parameter is optional, and is
865 * unspecified, path_converter will never get called.
866 * So if you set allow_fd, you *MUST* initialize path.fd = -1
867 * yourself!
868 * path.length
869 * The length of the path in characters, if specified as
870 * a string.
871 * path.object
872 * The original object passed in (if get a PathLike object,
873 * the result of PyOS_FSPath() is treated as the original object).
874 * Own a reference to the object.
875 * path.cleanup
876 * For internal use only. May point to a temporary object.
877 * (Pay no attention to the man behind the curtain.)
878 *
879 * At most one of path.wide or path.narrow will be non-NULL.
880 * If path was None and path.nullable was set,
881 * or if path was an integer and path.allow_fd was set,
882 * both path.wide and path.narrow will be NULL
883 * and path.length will be 0.
884 *
885 * path_converter takes care to not write to the path_t
886 * unless it's successful. However it must reset the
887 * "cleanup" field each time it's called.
888 *
889 * Use as follows:
890 * path_t path;
891 * memset(&path, 0, sizeof(path));
892 * PyArg_ParseTuple(args, "O&", path_converter, &path);
893 * // ... use values from path ...
894 * path_cleanup(&path);
895 *
896 * (Note that if PyArg_Parse fails you don't need to call
897 * path_cleanup(). However it is safe to do so.)
898 */
899typedef struct {
900 const char *function_name;
901 const char *argument_name;
902 int nullable;
903 int allow_fd;
904 const wchar_t *wide;
905#ifdef MS_WINDOWS
906 BOOL narrow;
907#else
908 const char *narrow;
909#endif
910 int fd;
911 Py_ssize_t length;
912 PyObject *object;
913 PyObject *cleanup;
914} path_t;
915
916#ifdef MS_WINDOWS
917#define PATH_T_INITIALIZE(function_name, argument_name, nullable, allow_fd) \
918 {function_name, argument_name, nullable, allow_fd, NULL, FALSE, -1, 0, NULL, NULL}
919#else
920#define PATH_T_INITIALIZE(function_name, argument_name, nullable, allow_fd) \
921 {function_name, argument_name, nullable, allow_fd, NULL, NULL, -1, 0, NULL, NULL}
922#endif
923
924static void
925path_cleanup(path_t *path)
926{
927 Py_CLEAR(path->object);
928 Py_CLEAR(path->cleanup);
929}
930
931static int
932path_converter(PyObject *o, void *p)
933{
934 path_t *path = (path_t *)p;
935 PyObject *bytes = NULL;
936 Py_ssize_t length = 0;
937 int is_index, is_buffer, is_bytes, is_unicode;
938 const char *narrow;
939#ifdef MS_WINDOWS
940 PyObject *wo = NULL;
941 const wchar_t *wide;
942#endif
943
944#define FORMAT_EXCEPTION(exc, fmt) \
945 PyErr_Format(exc, "%s%s" fmt, \
946 path->function_name ? path->function_name : "", \
947 path->function_name ? ": " : "", \
948 path->argument_name ? path->argument_name : "path")
949
950 /* Py_CLEANUP_SUPPORTED support */
951 if (o == NULL) {
952 path_cleanup(path);
953 return 1;
954 }
955
956 /* Ensure it's always safe to call path_cleanup(). */
957 path->object = path->cleanup = NULL;
958 /* path->object owns a reference to the original object */
959 Py_INCREF(o);
960
961 if ((o == Py_None) && path->nullable) {
962 path->wide = NULL;
963#ifdef MS_WINDOWS
964 path->narrow = FALSE;
965#else
966 path->narrow = NULL;
967#endif
968 path->fd = -1;
969 goto success_exit;
970 }
971
972 /* Only call this here so that we don't treat the return value of
973 os.fspath() as an fd or buffer. */
974 is_index = path->allow_fd && PyIndex_Check(o);
975 is_buffer = PyObject_CheckBuffer(o);
976 is_bytes = PyBytes_Check(o);
977 is_unicode = PyUnicode_Check(o);
978
979 if (!is_index && !is_buffer && !is_unicode && !is_bytes) {
980 /* Inline PyOS_FSPath() for better error messages. */
981 _Py_IDENTIFIER(__fspath__);
982 PyObject *func, *res;
983
984 func = _PyObject_LookupSpecial(o, &PyId___fspath__);
985 if (NULL == func) {
986 goto error_format;
987 }
988 res = _PyObject_CallNoArg(func);
989 Py_DECREF(func);
990 if (NULL == res) {
991 goto error_exit;
992 }
993 else if (PyUnicode_Check(res)) {
994 is_unicode = 1;
995 }
996 else if (PyBytes_Check(res)) {
997 is_bytes = 1;
998 }
999 else {
1000 PyErr_Format(PyExc_TypeError,
1001 "expected %.200s.__fspath__() to return str or bytes, "
1002 "not %.200s", Py_TYPE(o)->tp_name,
1003 Py_TYPE(res)->tp_name);
1004 Py_DECREF(res);
1005 goto error_exit;
1006 }
1007
1008 /* still owns a reference to the original object */
1009 Py_DECREF(o);
1010 o = res;
1011 }
1012
1013 if (is_unicode) {
1014#ifdef MS_WINDOWS
1015 wide = PyUnicode_AsUnicodeAndSize(o, &length);
1016 if (!wide) {
1017 goto error_exit;
1018 }
1019 if (length > 32767) {
1020 FORMAT_EXCEPTION(PyExc_ValueError, "%s too long for Windows");
1021 goto error_exit;
1022 }
1023 if (wcslen(wide) != length) {
1024 FORMAT_EXCEPTION(PyExc_ValueError, "embedded null character in %s");
1025 goto error_exit;
1026 }
1027
1028 path->wide = wide;
1029 path->narrow = FALSE;
1030 path->fd = -1;
1031 goto success_exit;
1032#else
1033 if (!PyUnicode_FSConverter(o, &bytes)) {
1034 goto error_exit;
1035 }
1036#endif
1037 }
1038 else if (is_bytes) {
1039 bytes = o;
1040 Py_INCREF(bytes);
1041 }
1042 else if (is_buffer) {
1043 /* XXX Replace PyObject_CheckBuffer with PyBytes_Check in other code
1044 after removing support of non-bytes buffer objects. */
1045 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
1046 "%s%s%s should be %s, not %.200s",
1047 path->function_name ? path->function_name : "",
1048 path->function_name ? ": " : "",
1049 path->argument_name ? path->argument_name : "path",
1050 path->allow_fd && path->nullable ? "string, bytes, os.PathLike, "
1051 "integer or None" :
1052 path->allow_fd ? "string, bytes, os.PathLike or integer" :
1053 path->nullable ? "string, bytes, os.PathLike or None" :
1054 "string, bytes or os.PathLike",
1055 Py_TYPE(o)->tp_name)) {
1056 goto error_exit;
1057 }
1058 bytes = PyBytes_FromObject(o);
1059 if (!bytes) {
1060 goto error_exit;
1061 }
1062 }
1063 else if (is_index) {
1064 if (!_fd_converter(o, &path->fd)) {
1065 goto error_exit;
1066 }
1067 path->wide = NULL;
1068#ifdef MS_WINDOWS
1069 path->narrow = FALSE;
1070#else
1071 path->narrow = NULL;
1072#endif
1073 goto success_exit;
1074 }
1075 else {
1076 error_format:
1077 PyErr_Format(PyExc_TypeError, "%s%s%s should be %s, not %.200s",
1078 path->function_name ? path->function_name : "",
1079 path->function_name ? ": " : "",
1080 path->argument_name ? path->argument_name : "path",
1081 path->allow_fd && path->nullable ? "string, bytes, os.PathLike, "
1082 "integer or None" :
1083 path->allow_fd ? "string, bytes, os.PathLike or integer" :
1084 path->nullable ? "string, bytes, os.PathLike or None" :
1085 "string, bytes or os.PathLike",
1086 Py_TYPE(o)->tp_name);
1087 goto error_exit;
1088 }
1089
1090 length = PyBytes_GET_SIZE(bytes);
1091 narrow = PyBytes_AS_STRING(bytes);
1092 if ((size_t)length != strlen(narrow)) {
1093 FORMAT_EXCEPTION(PyExc_ValueError, "embedded null character in %s");
1094 goto error_exit;
1095 }
1096
1097#ifdef MS_WINDOWS
1098 wo = PyUnicode_DecodeFSDefaultAndSize(
1099 narrow,
1100 length
1101 );
1102 if (!wo) {
1103 goto error_exit;
1104 }
1105
1106 wide = PyUnicode_AsUnicodeAndSize(wo, &length);
1107 if (!wide) {
1108 goto error_exit;
1109 }
1110 if (length > 32767) {
1111 FORMAT_EXCEPTION(PyExc_ValueError, "%s too long for Windows");
1112 goto error_exit;
1113 }
1114 if (wcslen(wide) != length) {
1115 FORMAT_EXCEPTION(PyExc_ValueError, "embedded null character in %s");
1116 goto error_exit;
1117 }
1118 path->wide = wide;
1119 path->narrow = TRUE;
1120 path->cleanup = wo;
1121 Py_DECREF(bytes);
1122#else
1123 path->wide = NULL;
1124 path->narrow = narrow;
1125 if (bytes == o) {
1126 /* Still a reference owned by path->object, don't have to
1127 worry about path->narrow is used after free. */
1128 Py_DECREF(bytes);
1129 }
1130 else {
1131 path->cleanup = bytes;
1132 }
1133#endif
1134 path->fd = -1;
1135
1136 success_exit:
1137 path->length = length;
1138 path->object = o;
1139 return Py_CLEANUP_SUPPORTED;
1140
1141 error_exit:
1142 Py_XDECREF(o);
1143 Py_XDECREF(bytes);
1144#ifdef MS_WINDOWS
1145 Py_XDECREF(wo);
1146#endif
1147 return 0;
1148}
1149
1150static void
1151argument_unavailable_error(const char *function_name, const char *argument_name)
1152{
1153 PyErr_Format(PyExc_NotImplementedError,
1154 "%s%s%s unavailable on this platform",
1155 (function_name != NULL) ? function_name : "",
1156 (function_name != NULL) ? ": ": "",
1157 argument_name);
1158}
1159
1160static int
1161dir_fd_unavailable(PyObject *o, void *p)
1162{
1163 int dir_fd;
1164 if (!dir_fd_converter(o, &dir_fd))
1165 return 0;
1166 if (dir_fd != DEFAULT_DIR_FD) {
1167 argument_unavailable_error(NULL, "dir_fd");
1168 return 0;
1169 }
1170 *(int *)p = dir_fd;
1171 return 1;
1172}
1173
1174static int
1175fd_specified(const char *function_name, int fd)
1176{
1177 if (fd == -1)
1178 return 0;
1179
1180 argument_unavailable_error(function_name, "fd");
1181 return 1;
1182}
1183
1184static int
1185follow_symlinks_specified(const char *function_name, int follow_symlinks)
1186{
1187 if (follow_symlinks)
1188 return 0;
1189
1190 argument_unavailable_error(function_name, "follow_symlinks");
1191 return 1;
1192}
1193
1194static int
1195path_and_dir_fd_invalid(const char *function_name, path_t *path, int dir_fd)
1196{
1197 if (!path->wide && (dir_fd != DEFAULT_DIR_FD)
1198#ifndef MS_WINDOWS
1199 && !path->narrow
1200#endif
1201 ) {
1202 PyErr_Format(PyExc_ValueError,
1203 "%s: can't specify dir_fd without matching path",
1204 function_name);
1205 return 1;
1206 }
1207 return 0;
1208}
1209
1210static int
1211dir_fd_and_fd_invalid(const char *function_name, int dir_fd, int fd)
1212{
1213 if ((dir_fd != DEFAULT_DIR_FD) && (fd != -1)) {
1214 PyErr_Format(PyExc_ValueError,
1215 "%s: can't specify both dir_fd and fd",
1216 function_name);
1217 return 1;
1218 }
1219 return 0;
1220}
1221
1222static int
1223fd_and_follow_symlinks_invalid(const char *function_name, int fd,
1224 int follow_symlinks)
1225{
1226 if ((fd > 0) && (!follow_symlinks)) {
1227 PyErr_Format(PyExc_ValueError,
1228 "%s: cannot use fd and follow_symlinks together",
1229 function_name);
1230 return 1;
1231 }
1232 return 0;
1233}
1234
1235static int
1236dir_fd_and_follow_symlinks_invalid(const char *function_name, int dir_fd,
1237 int follow_symlinks)
1238{
1239 if ((dir_fd != DEFAULT_DIR_FD) && (!follow_symlinks)) {
1240 PyErr_Format(PyExc_ValueError,
1241 "%s: cannot use dir_fd and follow_symlinks together",
1242 function_name);
1243 return 1;
1244 }
1245 return 0;
1246}
1247
1248#ifdef MS_WINDOWS
1249 typedef long long Py_off_t;
1250#else
1251 typedef off_t Py_off_t;
1252#endif
1253
1254static int
1255Py_off_t_converter(PyObject *arg, void *addr)
1256{
1257#ifdef HAVE_LARGEFILE_SUPPORT
1258 *((Py_off_t *)addr) = PyLong_AsLongLong(arg);
1259#else
1260 *((Py_off_t *)addr) = PyLong_AsLong(arg);
1261#endif
1262 if (PyErr_Occurred())
1263 return 0;
1264 return 1;
1265}
1266
1267static PyObject *
1268PyLong_FromPy_off_t(Py_off_t offset)
1269{
1270#ifdef HAVE_LARGEFILE_SUPPORT
1271 return PyLong_FromLongLong(offset);
1272#else
1273 return PyLong_FromLong(offset);
1274#endif
1275}
1276
1277#ifdef MS_WINDOWS
1278
1279static int
1280win32_get_reparse_tag(HANDLE reparse_point_handle, ULONG *reparse_tag)
1281{
1282 char target_buffer[_Py_MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
1283 _Py_REPARSE_DATA_BUFFER *rdb = (_Py_REPARSE_DATA_BUFFER *)target_buffer;
1284 DWORD n_bytes_returned;
1285
1286 if (0 == DeviceIoControl(
1287 reparse_point_handle,
1288 FSCTL_GET_REPARSE_POINT,
1289 NULL, 0, /* in buffer */
1290 target_buffer, sizeof(target_buffer),
1291 &n_bytes_returned,
1292 NULL)) /* we're not using OVERLAPPED_IO */
1293 return FALSE;
1294
1295 if (reparse_tag)
1296 *reparse_tag = rdb->ReparseTag;
1297
1298 return TRUE;
1299}
1300
1301#endif /* MS_WINDOWS */
1302
1303/* Return a dictionary corresponding to the POSIX environment table */
1304#if defined(WITH_NEXT_FRAMEWORK) || (defined(__APPLE__) && defined(Py_ENABLE_SHARED))
1305/* On Darwin/MacOSX a shared library or framework has no access to
1306** environ directly, we must obtain it with _NSGetEnviron(). See also
1307** man environ(7).
1308*/
1309#include <crt_externs.h>
1310static char **environ;
1311#elif !defined(_MSC_VER) && ( !defined(__WATCOMC__) || defined(__QNX__) )
1312extern char **environ;
1313#endif /* !_MSC_VER */
1314
1315static PyObject *
1316convertenviron(void)
1317{
1318 PyObject *d;
1319#ifdef MS_WINDOWS
1320 wchar_t **e;
1321#else
1322 char **e;
1323#endif
1324
1325 d = PyDict_New();
1326 if (d == NULL)
1327 return NULL;
1328#if defined(WITH_NEXT_FRAMEWORK) || (defined(__APPLE__) && defined(Py_ENABLE_SHARED))
1329 if (environ == NULL)
1330 environ = *_NSGetEnviron();
1331#endif
1332#ifdef MS_WINDOWS
1333 /* _wenviron must be initialized in this way if the program is started
1334 through main() instead of wmain(). */
1335 _wgetenv(L"");
1336 if (_wenviron == NULL)
1337 return d;
1338 /* This part ignores errors */
1339 for (e = _wenviron; *e != NULL; e++) {
1340 PyObject *k;
1341 PyObject *v;
1342 const wchar_t *p = wcschr(*e, L'=');
1343 if (p == NULL)
1344 continue;
1345 k = PyUnicode_FromWideChar(*e, (Py_ssize_t)(p-*e));
1346 if (k == NULL) {
1347 PyErr_Clear();
1348 continue;
1349 }
1350 v = PyUnicode_FromWideChar(p+1, wcslen(p+1));
1351 if (v == NULL) {
1352 PyErr_Clear();
1353 Py_DECREF(k);
1354 continue;
1355 }
1356 if (PyDict_GetItem(d, k) == NULL) {
1357 if (PyDict_SetItem(d, k, v) != 0)
1358 PyErr_Clear();
1359 }
1360 Py_DECREF(k);
1361 Py_DECREF(v);
1362 }
1363#else
1364 if (environ == NULL)
1365 return d;
1366 /* This part ignores errors */
1367 for (e = environ; *e != NULL; e++) {
1368 PyObject *k;
1369 PyObject *v;
1370 const char *p = strchr(*e, '=');
1371 if (p == NULL)
1372 continue;
1373 k = PyBytes_FromStringAndSize(*e, (int)(p-*e));
1374 if (k == NULL) {
1375 PyErr_Clear();
1376 continue;
1377 }
1378 v = PyBytes_FromStringAndSize(p+1, strlen(p+1));
1379 if (v == NULL) {
1380 PyErr_Clear();
1381 Py_DECREF(k);
1382 continue;
1383 }
1384 if (PyDict_GetItem(d, k) == NULL) {
1385 if (PyDict_SetItem(d, k, v) != 0)
1386 PyErr_Clear();
1387 }
1388 Py_DECREF(k);
1389 Py_DECREF(v);
1390 }
1391#endif
1392 return d;
1393}
1394
1395/* Set a POSIX-specific error from errno, and return NULL */
1396
1397static PyObject *
1398posix_error(void)
1399{
1400 return PyErr_SetFromErrno(PyExc_OSError);
1401}
1402
1403#ifdef MS_WINDOWS
1404static PyObject *
1405win32_error(const char* function, const char* filename)
1406{
1407 /* XXX We should pass the function name along in the future.
1408 (winreg.c also wants to pass the function name.)
1409 This would however require an additional param to the
1410 Windows error object, which is non-trivial.
1411 */
1412 errno = GetLastError();
1413 if (filename)
1414 return PyErr_SetFromWindowsErrWithFilename(errno, filename);
1415 else
1416 return PyErr_SetFromWindowsErr(errno);
1417}
1418
1419static PyObject *
1420win32_error_object(const char* function, PyObject* filename)
1421{
1422 /* XXX - see win32_error for comments on 'function' */
1423 errno = GetLastError();
1424 if (filename)
1425 return PyErr_SetExcFromWindowsErrWithFilenameObject(
1426 PyExc_OSError,
1427 errno,
1428 filename);
1429 else
1430 return PyErr_SetFromWindowsErr(errno);
1431}
1432
1433#endif /* MS_WINDOWS */
1434
1435static PyObject *
1436posix_path_object_error(PyObject *path)
1437{
1438 return PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, path);
1439}
1440
1441static PyObject *
1442path_object_error(PyObject *path)
1443{
1444#ifdef MS_WINDOWS
1445 return PyErr_SetExcFromWindowsErrWithFilenameObject(
1446 PyExc_OSError, 0, path);
1447#else
1448 return posix_path_object_error(path);
1449#endif
1450}
1451
1452static PyObject *
1453path_object_error2(PyObject *path, PyObject *path2)
1454{
1455#ifdef MS_WINDOWS
1456 return PyErr_SetExcFromWindowsErrWithFilenameObjects(
1457 PyExc_OSError, 0, path, path2);
1458#else
1459 return PyErr_SetFromErrnoWithFilenameObjects(PyExc_OSError, path, path2);
1460#endif
1461}
1462
1463static PyObject *
1464path_error(path_t *path)
1465{
1466 return path_object_error(path->object);
1467}
1468
1469static PyObject *
1470posix_path_error(path_t *path)
1471{
1472 return posix_path_object_error(path->object);
1473}
1474
1475static PyObject *
1476path_error2(path_t *path, path_t *path2)
1477{
1478 return path_object_error2(path->object, path2->object);
1479}
1480
1481
1482/* POSIX generic methods */
1483
1484static int
1485fildes_converter(PyObject *o, void *p)
1486{
1487 int fd;
1488 int *pointer = (int *)p;
1489 fd = PyObject_AsFileDescriptor(o);
1490 if (fd < 0)
1491 return 0;
1492 *pointer = fd;
1493 return 1;
1494}
1495
1496static PyObject *
1497posix_fildes_fd(int fd, int (*func)(int))
1498{
1499 int res;
1500 int async_err = 0;
1501
1502 do {
1503 Py_BEGIN_ALLOW_THREADS
1504 _Py_BEGIN_SUPPRESS_IPH
1505 res = (*func)(fd);
1506 _Py_END_SUPPRESS_IPH
1507 Py_END_ALLOW_THREADS
1508 } while (res != 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
1509 if (res != 0)
1510 return (!async_err) ? posix_error() : NULL;
1511 Py_RETURN_NONE;
1512}
1513
1514
1515#ifdef MS_WINDOWS
1516/* This is a reimplementation of the C library's chdir function,
1517 but one that produces Win32 errors instead of DOS error codes.
1518 chdir is essentially a wrapper around SetCurrentDirectory; however,
1519 it also needs to set "magic" environment variables indicating
1520 the per-drive current directory, which are of the form =<drive>: */
1521static BOOL __stdcall
1522win32_wchdir(LPCWSTR path)
1523{
1524 wchar_t path_buf[MAX_PATH], *new_path = path_buf;
1525 int result;
1526 wchar_t env[4] = L"=x:";
1527
1528 if(!SetCurrentDirectoryW(path))
1529 return FALSE;
1530 result = GetCurrentDirectoryW(Py_ARRAY_LENGTH(path_buf), new_path);
1531 if (!result)
1532 return FALSE;
1533 if (result > Py_ARRAY_LENGTH(path_buf)) {
1534 new_path = PyMem_RawMalloc(result * sizeof(wchar_t));
1535 if (!new_path) {
1536 SetLastError(ERROR_OUTOFMEMORY);
1537 return FALSE;
1538 }
1539 result = GetCurrentDirectoryW(result, new_path);
1540 if (!result) {
1541 PyMem_RawFree(new_path);
1542 return FALSE;
1543 }
1544 }
1545 int is_unc_like_path = (wcsncmp(new_path, L"\\\\", 2) == 0 ||
1546 wcsncmp(new_path, L"//", 2) == 0);
1547 if (!is_unc_like_path) {
1548 env[1] = new_path[0];
1549 result = SetEnvironmentVariableW(env, new_path);
1550 }
1551 if (new_path != path_buf)
1552 PyMem_RawFree(new_path);
1553 return result ? TRUE : FALSE;
1554}
1555#endif
1556
1557#ifdef MS_WINDOWS
1558/* The CRT of Windows has a number of flaws wrt. its stat() implementation:
1559 - time stamps are restricted to second resolution
1560 - file modification times suffer from forth-and-back conversions between
1561 UTC and local time
1562 Therefore, we implement our own stat, based on the Win32 API directly.
1563*/
1564#define HAVE_STAT_NSEC 1
1565#define HAVE_STRUCT_STAT_ST_FILE_ATTRIBUTES 1
1566
1567static void
1568find_data_to_file_info(WIN32_FIND_DATAW *pFileData,
1569 BY_HANDLE_FILE_INFORMATION *info,
1570 ULONG *reparse_tag)
1571{
1572 memset(info, 0, sizeof(*info));
1573 info->dwFileAttributes = pFileData->dwFileAttributes;
1574 info->ftCreationTime = pFileData->ftCreationTime;
1575 info->ftLastAccessTime = pFileData->ftLastAccessTime;
1576 info->ftLastWriteTime = pFileData->ftLastWriteTime;
1577 info->nFileSizeHigh = pFileData->nFileSizeHigh;
1578 info->nFileSizeLow = pFileData->nFileSizeLow;
1579/* info->nNumberOfLinks = 1; */
1580 if (pFileData->dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT)
1581 *reparse_tag = pFileData->dwReserved0;
1582 else
1583 *reparse_tag = 0;
1584}
1585
1586static BOOL
1587attributes_from_dir(LPCWSTR pszFile, BY_HANDLE_FILE_INFORMATION *info, ULONG *reparse_tag)
1588{
1589 HANDLE hFindFile;
1590 WIN32_FIND_DATAW FileData;
1591 hFindFile = FindFirstFileW(pszFile, &FileData);
1592 if (hFindFile == INVALID_HANDLE_VALUE)
1593 return FALSE;
1594 FindClose(hFindFile);
1595 find_data_to_file_info(&FileData, info, reparse_tag);
1596 return TRUE;
1597}
1598
1599static BOOL
1600get_target_path(HANDLE hdl, wchar_t **target_path)
1601{
1602 int buf_size, result_length;
1603 wchar_t *buf;
1604
1605 /* We have a good handle to the target, use it to determine
1606 the target path name (then we'll call lstat on it). */
1607 buf_size = GetFinalPathNameByHandleW(hdl, 0, 0,
1608 VOLUME_NAME_DOS);
1609 if(!buf_size)
1610 return FALSE;
1611
1612 buf = (wchar_t *)PyMem_RawMalloc((buf_size + 1) * sizeof(wchar_t));
1613 if (!buf) {
1614 SetLastError(ERROR_OUTOFMEMORY);
1615 return FALSE;
1616 }
1617
1618 result_length = GetFinalPathNameByHandleW(hdl,
1619 buf, buf_size, VOLUME_NAME_DOS);
1620
1621 if(!result_length) {
1622 PyMem_RawFree(buf);
1623 return FALSE;
1624 }
1625
1626 buf[result_length] = 0;
1627
1628 *target_path = buf;
1629 return TRUE;
1630}
1631
1632static int
1633win32_xstat_impl(const wchar_t *path, struct _Py_stat_struct *result,
1634 BOOL traverse)
1635{
1636 int code;
1637 HANDLE hFile, hFile2;
1638 BY_HANDLE_FILE_INFORMATION info;
1639 ULONG reparse_tag = 0;
1640 wchar_t *target_path;
1641 const wchar_t *dot;
1642
1643 hFile = CreateFileW(
1644 path,
1645 FILE_READ_ATTRIBUTES, /* desired access */
1646 0, /* share mode */
1647 NULL, /* security attributes */
1648 OPEN_EXISTING,
1649 /* FILE_FLAG_BACKUP_SEMANTICS is required to open a directory */
1650 /* FILE_FLAG_OPEN_REPARSE_POINT does not follow the symlink.
1651 Because of this, calls like GetFinalPathNameByHandle will return
1652 the symlink path again and not the actual final path. */
1653 FILE_ATTRIBUTE_NORMAL|FILE_FLAG_BACKUP_SEMANTICS|
1654 FILE_FLAG_OPEN_REPARSE_POINT,
1655 NULL);
1656
1657 if (hFile == INVALID_HANDLE_VALUE) {
1658 /* Either the target doesn't exist, or we don't have access to
1659 get a handle to it. If the former, we need to return an error.
1660 If the latter, we can use attributes_from_dir. */
1661 DWORD lastError = GetLastError();
1662 if (lastError != ERROR_ACCESS_DENIED &&
1663 lastError != ERROR_SHARING_VIOLATION)
1664 return -1;
1665 /* Could not get attributes on open file. Fall back to
1666 reading the directory. */
1667 if (!attributes_from_dir(path, &info, &reparse_tag))
1668 /* Very strange. This should not fail now */
1669 return -1;
1670 if (info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1671 if (traverse) {
1672 /* Should traverse, but could not open reparse point handle */
1673 SetLastError(lastError);
1674 return -1;
1675 }
1676 }
1677 } else {
1678 if (!GetFileInformationByHandle(hFile, &info)) {
1679 CloseHandle(hFile);
1680 return -1;
1681 }
1682 if (info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1683 if (!win32_get_reparse_tag(hFile, &reparse_tag)) {
1684 CloseHandle(hFile);
1685 return -1;
1686 }
1687 /* Close the outer open file handle now that we're about to
1688 reopen it with different flags. */
1689 if (!CloseHandle(hFile))
1690 return -1;
1691
1692 if (traverse) {
1693 /* In order to call GetFinalPathNameByHandle we need to open
1694 the file without the reparse handling flag set. */
1695 hFile2 = CreateFileW(
1696 path, FILE_READ_ATTRIBUTES, FILE_SHARE_READ,
1697 NULL, OPEN_EXISTING,
1698 FILE_ATTRIBUTE_NORMAL|FILE_FLAG_BACKUP_SEMANTICS,
1699 NULL);
1700 if (hFile2 == INVALID_HANDLE_VALUE)
1701 return -1;
1702
1703 if (!get_target_path(hFile2, &target_path)) {
1704 CloseHandle(hFile2);
1705 return -1;
1706 }
1707
1708 if (!CloseHandle(hFile2)) {
1709 return -1;
1710 }
1711
1712 code = win32_xstat_impl(target_path, result, FALSE);
1713 PyMem_RawFree(target_path);
1714 return code;
1715 }
1716 } else
1717 CloseHandle(hFile);
1718 }
1719 _Py_attribute_data_to_stat(&info, reparse_tag, result);
1720
1721 /* Set S_IEXEC if it is an .exe, .bat, ... */
1722 dot = wcsrchr(path, '.');
1723 if (dot) {
1724 if (_wcsicmp(dot, L".bat") == 0 || _wcsicmp(dot, L".cmd") == 0 ||
1725 _wcsicmp(dot, L".exe") == 0 || _wcsicmp(dot, L".com") == 0)
1726 result->st_mode |= 0111;
1727 }
1728 return 0;
1729}
1730
1731static int
1732win32_xstat(const wchar_t *path, struct _Py_stat_struct *result, BOOL traverse)
1733{
1734 /* Protocol violation: we explicitly clear errno, instead of
1735 setting it to a POSIX error. Callers should use GetLastError. */
1736 int code = win32_xstat_impl(path, result, traverse);
1737 errno = 0;
1738 return code;
1739}
1740/* About the following functions: win32_lstat_w, win32_stat, win32_stat_w
1741
1742 In Posix, stat automatically traverses symlinks and returns the stat
1743 structure for the target. In Windows, the equivalent GetFileAttributes by
1744 default does not traverse symlinks and instead returns attributes for
1745 the symlink.
1746
1747 Therefore, win32_lstat will get the attributes traditionally, and
1748 win32_stat will first explicitly resolve the symlink target and then will
1749 call win32_lstat on that result. */
1750
1751static int
1752win32_lstat(const wchar_t* path, struct _Py_stat_struct *result)
1753{
1754 return win32_xstat(path, result, FALSE);
1755}
1756
1757static int
1758win32_stat(const wchar_t* path, struct _Py_stat_struct *result)
1759{
1760 return win32_xstat(path, result, TRUE);
1761}
1762
1763#endif /* MS_WINDOWS */
1764
1765PyDoc_STRVAR(stat_result__doc__,
1766"stat_result: Result from stat, fstat, or lstat.\n\n\
1767This object may be accessed either as a tuple of\n\
1768 (mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime)\n\
1769or via the attributes st_mode, st_ino, st_dev, st_nlink, st_uid, and so on.\n\
1770\n\
1771Posix/windows: If your platform supports st_blksize, st_blocks, st_rdev,\n\
1772or st_flags, they are available as attributes only.\n\
1773\n\
1774See os.stat for more information.");
1775
1776static PyStructSequence_Field stat_result_fields[] = {
1777 {"st_mode", "protection bits"},
1778 {"st_ino", "inode"},
1779 {"st_dev", "device"},
1780 {"st_nlink", "number of hard links"},
1781 {"st_uid", "user ID of owner"},
1782 {"st_gid", "group ID of owner"},
1783 {"st_size", "total size, in bytes"},
1784 /* The NULL is replaced with PyStructSequence_UnnamedField later. */
1785 {NULL, "integer time of last access"},
1786 {NULL, "integer time of last modification"},
1787 {NULL, "integer time of last change"},
1788 {"st_atime", "time of last access"},
1789 {"st_mtime", "time of last modification"},
1790 {"st_ctime", "time of last change"},
1791 {"st_atime_ns", "time of last access in nanoseconds"},
1792 {"st_mtime_ns", "time of last modification in nanoseconds"},
1793 {"st_ctime_ns", "time of last change in nanoseconds"},
1794#ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
1795 {"st_blksize", "blocksize for filesystem I/O"},
1796#endif
1797#ifdef HAVE_STRUCT_STAT_ST_BLOCKS
1798 {"st_blocks", "number of blocks allocated"},
1799#endif
1800#ifdef HAVE_STRUCT_STAT_ST_RDEV
1801 {"st_rdev", "device type (if inode device)"},
1802#endif
1803#ifdef HAVE_STRUCT_STAT_ST_FLAGS
1804 {"st_flags", "user defined flags for file"},
1805#endif
1806#ifdef HAVE_STRUCT_STAT_ST_GEN
1807 {"st_gen", "generation number"},
1808#endif
1809#ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME
1810 {"st_birthtime", "time of creation"},
1811#endif
1812#ifdef HAVE_STRUCT_STAT_ST_FILE_ATTRIBUTES
1813 {"st_file_attributes", "Windows file attribute bits"},
1814#endif
1815#ifdef HAVE_STRUCT_STAT_ST_FSTYPE
1816 {"st_fstype", "Type of filesystem"},
1817#endif
1818 {0}
1819};
1820
1821#ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
1822#define ST_BLKSIZE_IDX 16
1823#else
1824#define ST_BLKSIZE_IDX 15
1825#endif
1826
1827#ifdef HAVE_STRUCT_STAT_ST_BLOCKS
1828#define ST_BLOCKS_IDX (ST_BLKSIZE_IDX+1)
1829#else
1830#define ST_BLOCKS_IDX ST_BLKSIZE_IDX
1831#endif
1832
1833#ifdef HAVE_STRUCT_STAT_ST_RDEV
1834#define ST_RDEV_IDX (ST_BLOCKS_IDX+1)
1835#else
1836#define ST_RDEV_IDX ST_BLOCKS_IDX
1837#endif
1838
1839#ifdef HAVE_STRUCT_STAT_ST_FLAGS
1840#define ST_FLAGS_IDX (ST_RDEV_IDX+1)
1841#else
1842#define ST_FLAGS_IDX ST_RDEV_IDX
1843#endif
1844
1845#ifdef HAVE_STRUCT_STAT_ST_GEN
1846#define ST_GEN_IDX (ST_FLAGS_IDX+1)
1847#else
1848#define ST_GEN_IDX ST_FLAGS_IDX
1849#endif
1850
1851#ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME
1852#define ST_BIRTHTIME_IDX (ST_GEN_IDX+1)
1853#else
1854#define ST_BIRTHTIME_IDX ST_GEN_IDX
1855#endif
1856
1857#ifdef HAVE_STRUCT_STAT_ST_FILE_ATTRIBUTES
1858#define ST_FILE_ATTRIBUTES_IDX (ST_BIRTHTIME_IDX+1)
1859#else
1860#define ST_FILE_ATTRIBUTES_IDX ST_BIRTHTIME_IDX
1861#endif
1862
1863#ifdef HAVE_STRUCT_STAT_ST_FSTYPE
1864#define ST_FSTYPE_IDX (ST_FILE_ATTRIBUTES_IDX+1)
1865#else
1866#define ST_FSTYPE_IDX ST_FILE_ATTRIBUTES_IDX
1867#endif
1868
1869static PyStructSequence_Desc stat_result_desc = {
1870 "stat_result", /* name */
1871 stat_result__doc__, /* doc */
1872 stat_result_fields,
1873 10
1874};
1875
1876PyDoc_STRVAR(statvfs_result__doc__,
1877"statvfs_result: Result from statvfs or fstatvfs.\n\n\
1878This object may be accessed either as a tuple of\n\
1879 (bsize, frsize, blocks, bfree, bavail, files, ffree, favail, flag, namemax),\n\
1880or via the attributes f_bsize, f_frsize, f_blocks, f_bfree, and so on.\n\
1881\n\
1882See os.statvfs for more information.");
1883
1884static PyStructSequence_Field statvfs_result_fields[] = {
1885 {"f_bsize", },
1886 {"f_frsize", },
1887 {"f_blocks", },
1888 {"f_bfree", },
1889 {"f_bavail", },
1890 {"f_files", },
1891 {"f_ffree", },
1892 {"f_favail", },
1893 {"f_flag", },
1894 {"f_namemax",},
1895 {"f_fsid", },
1896 {0}
1897};
1898
1899static PyStructSequence_Desc statvfs_result_desc = {
1900 "statvfs_result", /* name */
1901 statvfs_result__doc__, /* doc */
1902 statvfs_result_fields,
1903 10
1904};
1905
1906#if defined(HAVE_WAITID) && !defined(__APPLE__)
1907PyDoc_STRVAR(waitid_result__doc__,
1908"waitid_result: Result from waitid.\n\n\
1909This object may be accessed either as a tuple of\n\
1910 (si_pid, si_uid, si_signo, si_status, si_code),\n\
1911or via the attributes si_pid, si_uid, and so on.\n\
1912\n\
1913See os.waitid for more information.");
1914
1915static PyStructSequence_Field waitid_result_fields[] = {
1916 {"si_pid", },
1917 {"si_uid", },
1918 {"si_signo", },
1919 {"si_status", },
1920 {"si_code", },
1921 {0}
1922};
1923
1924static PyStructSequence_Desc waitid_result_desc = {
1925 "waitid_result", /* name */
1926 waitid_result__doc__, /* doc */
1927 waitid_result_fields,
1928 5
1929};
1930static PyTypeObject WaitidResultType;
1931#endif
1932
1933static int initialized;
1934static PyTypeObject StatResultType;
1935static PyTypeObject StatVFSResultType;
1936#if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER)
1937static PyTypeObject SchedParamType;
1938#endif
1939static newfunc structseq_new;
1940
1941static PyObject *
1942statresult_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
1943{
1944 PyStructSequence *result;
1945 int i;
1946
1947 result = (PyStructSequence*)structseq_new(type, args, kwds);
1948 if (!result)
1949 return NULL;
1950 /* If we have been initialized from a tuple,
1951 st_?time might be set to None. Initialize it
1952 from the int slots. */
1953 for (i = 7; i <= 9; i++) {
1954 if (result->ob_item[i+3] == Py_None) {
1955 Py_DECREF(Py_None);
1956 Py_INCREF(result->ob_item[i]);
1957 result->ob_item[i+3] = result->ob_item[i];
1958 }
1959 }
1960 return (PyObject*)result;
1961}
1962
1963
1964static PyObject *billion = NULL;
1965
1966static void
1967fill_time(PyObject *v, int index, time_t sec, unsigned long nsec)
1968{
1969 PyObject *s = _PyLong_FromTime_t(sec);
1970 PyObject *ns_fractional = PyLong_FromUnsignedLong(nsec);
1971 PyObject *s_in_ns = NULL;
1972 PyObject *ns_total = NULL;
1973 PyObject *float_s = NULL;
1974
1975 if (!(s && ns_fractional))
1976 goto exit;
1977
1978 s_in_ns = PyNumber_Multiply(s, billion);
1979 if (!s_in_ns)
1980 goto exit;
1981
1982 ns_total = PyNumber_Add(s_in_ns, ns_fractional);
1983 if (!ns_total)
1984 goto exit;
1985
1986 float_s = PyFloat_FromDouble(sec + 1e-9*nsec);
1987 if (!float_s) {
1988 goto exit;
1989 }
1990
1991 PyStructSequence_SET_ITEM(v, index, s);
1992 PyStructSequence_SET_ITEM(v, index+3, float_s);
1993 PyStructSequence_SET_ITEM(v, index+6, ns_total);
1994 s = NULL;
1995 float_s = NULL;
1996 ns_total = NULL;
1997exit:
1998 Py_XDECREF(s);
1999 Py_XDECREF(ns_fractional);
2000 Py_XDECREF(s_in_ns);
2001 Py_XDECREF(ns_total);
2002 Py_XDECREF(float_s);
2003}
2004
2005/* pack a system stat C structure into the Python stat tuple
2006 (used by posix_stat() and posix_fstat()) */
2007static PyObject*
2008_pystat_fromstructstat(STRUCT_STAT *st)
2009{
2010 unsigned long ansec, mnsec, cnsec;
2011 PyObject *v = PyStructSequence_New(&StatResultType);
2012 if (v == NULL)
2013 return NULL;
2014
2015 PyStructSequence_SET_ITEM(v, 0, PyLong_FromLong((long)st->st_mode));
2016 Py_BUILD_ASSERT(sizeof(unsigned long long) >= sizeof(st->st_ino));
2017 PyStructSequence_SET_ITEM(v, 1, PyLong_FromUnsignedLongLong(st->st_ino));
2018#ifdef MS_WINDOWS
2019 PyStructSequence_SET_ITEM(v, 2, PyLong_FromUnsignedLong(st->st_dev));
2020#else
2021 PyStructSequence_SET_ITEM(v, 2, _PyLong_FromDev(st->st_dev));
2022#endif
2023 PyStructSequence_SET_ITEM(v, 3, PyLong_FromLong((long)st->st_nlink));
2024#if defined(MS_WINDOWS)
2025 PyStructSequence_SET_ITEM(v, 4, PyLong_FromLong(0));
2026 PyStructSequence_SET_ITEM(v, 5, PyLong_FromLong(0));
2027#else
2028 PyStructSequence_SET_ITEM(v, 4, _PyLong_FromUid(st->st_uid));
2029 PyStructSequence_SET_ITEM(v, 5, _PyLong_FromGid(st->st_gid));
2030#endif
2031 Py_BUILD_ASSERT(sizeof(long long) >= sizeof(st->st_size));
2032 PyStructSequence_SET_ITEM(v, 6, PyLong_FromLongLong(st->st_size));
2033
2034#if defined(HAVE_STAT_TV_NSEC)
2035 ansec = st->st_atim.tv_nsec;
2036 mnsec = st->st_mtim.tv_nsec;
2037 cnsec = st->st_ctim.tv_nsec;
2038#elif defined(HAVE_STAT_TV_NSEC2)
2039 ansec = st->st_atimespec.tv_nsec;
2040 mnsec = st->st_mtimespec.tv_nsec;
2041 cnsec = st->st_ctimespec.tv_nsec;
2042#elif defined(HAVE_STAT_NSEC)
2043 ansec = st->st_atime_nsec;
2044 mnsec = st->st_mtime_nsec;
2045 cnsec = st->st_ctime_nsec;
2046#else
2047 ansec = mnsec = cnsec = 0;
2048#endif
2049 fill_time(v, 7, st->st_atime, ansec);
2050 fill_time(v, 8, st->st_mtime, mnsec);
2051 fill_time(v, 9, st->st_ctime, cnsec);
2052
2053#ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
2054 PyStructSequence_SET_ITEM(v, ST_BLKSIZE_IDX,
2055 PyLong_FromLong((long)st->st_blksize));
2056#endif
2057#ifdef HAVE_STRUCT_STAT_ST_BLOCKS
2058 PyStructSequence_SET_ITEM(v, ST_BLOCKS_IDX,
2059 PyLong_FromLong((long)st->st_blocks));
2060#endif
2061#ifdef HAVE_STRUCT_STAT_ST_RDEV
2062 PyStructSequence_SET_ITEM(v, ST_RDEV_IDX,
2063 PyLong_FromLong((long)st->st_rdev));
2064#endif
2065#ifdef HAVE_STRUCT_STAT_ST_GEN
2066 PyStructSequence_SET_ITEM(v, ST_GEN_IDX,
2067 PyLong_FromLong((long)st->st_gen));
2068#endif
2069#ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME
2070 {
2071 PyObject *val;
2072 unsigned long bsec,bnsec;
2073 bsec = (long)st->st_birthtime;
2074#ifdef HAVE_STAT_TV_NSEC2
2075 bnsec = st->st_birthtimespec.tv_nsec;
2076#else
2077 bnsec = 0;
2078#endif
2079 val = PyFloat_FromDouble(bsec + 1e-9*bnsec);
2080 PyStructSequence_SET_ITEM(v, ST_BIRTHTIME_IDX,
2081 val);
2082 }
2083#endif
2084#ifdef HAVE_STRUCT_STAT_ST_FLAGS
2085 PyStructSequence_SET_ITEM(v, ST_FLAGS_IDX,
2086 PyLong_FromLong((long)st->st_flags));
2087#endif
2088#ifdef HAVE_STRUCT_STAT_ST_FILE_ATTRIBUTES
2089 PyStructSequence_SET_ITEM(v, ST_FILE_ATTRIBUTES_IDX,
2090 PyLong_FromUnsignedLong(st->st_file_attributes));
2091#endif
2092#ifdef HAVE_STRUCT_STAT_ST_FSTYPE
2093 PyStructSequence_SET_ITEM(v, ST_FSTYPE_IDX,
2094 PyUnicode_FromString(st->st_fstype));
2095#endif
2096
2097 if (PyErr_Occurred()) {
2098 Py_DECREF(v);
2099 return NULL;
2100 }
2101
2102 return v;
2103}
2104
2105/* POSIX methods */
2106
2107
2108static PyObject *
2109posix_do_stat(const char *function_name, path_t *path,
2110 int dir_fd, int follow_symlinks)
2111{
2112 STRUCT_STAT st;
2113 int result;
2114
2115#if !defined(MS_WINDOWS) && !defined(HAVE_FSTATAT) && !defined(HAVE_LSTAT)
2116 if (follow_symlinks_specified(function_name, follow_symlinks))
2117 return NULL;
2118#endif
2119
2120 if (path_and_dir_fd_invalid("stat", path, dir_fd) ||
2121 dir_fd_and_fd_invalid("stat", dir_fd, path->fd) ||
2122 fd_and_follow_symlinks_invalid("stat", path->fd, follow_symlinks))
2123 return NULL;
2124
2125 Py_BEGIN_ALLOW_THREADS
2126 if (path->fd != -1)
2127 result = FSTAT(path->fd, &st);
2128#ifdef MS_WINDOWS
2129 else if (follow_symlinks)
2130 result = win32_stat(path->wide, &st);
2131 else
2132 result = win32_lstat(path->wide, &st);
2133#else
2134 else
2135#if defined(HAVE_LSTAT)
2136 if ((!follow_symlinks) && (dir_fd == DEFAULT_DIR_FD))
2137 result = LSTAT(path->narrow, &st);
2138 else
2139#endif /* HAVE_LSTAT */
2140#ifdef HAVE_FSTATAT
2141 if ((dir_fd != DEFAULT_DIR_FD) || !follow_symlinks)
2142 result = fstatat(dir_fd, path->narrow, &st,
2143 follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW);
2144 else
2145#endif /* HAVE_FSTATAT */
2146 result = STAT(path->narrow, &st);
2147#endif /* MS_WINDOWS */
2148 Py_END_ALLOW_THREADS
2149
2150 if (result != 0) {
2151 return path_error(path);
2152 }
2153
2154 return _pystat_fromstructstat(&st);
2155}
2156
2157/*[python input]
2158
2159for s in """
2160
2161FACCESSAT
2162FCHMODAT
2163FCHOWNAT
2164FSTATAT
2165LINKAT
2166MKDIRAT
2167MKFIFOAT
2168MKNODAT
2169OPENAT
2170READLINKAT
2171SYMLINKAT
2172UNLINKAT
2173
2174""".strip().split():
2175 s = s.strip()
2176 print("""
2177#ifdef HAVE_{s}
2178 #define {s}_DIR_FD_CONVERTER dir_fd_converter
2179#else
2180 #define {s}_DIR_FD_CONVERTER dir_fd_unavailable
2181#endif
2182""".rstrip().format(s=s))
2183
2184for s in """
2185
2186FCHDIR
2187FCHMOD
2188FCHOWN
2189FDOPENDIR
2190FEXECVE
2191FPATHCONF
2192FSTATVFS
2193FTRUNCATE
2194
2195""".strip().split():
2196 s = s.strip()
2197 print("""
2198#ifdef HAVE_{s}
2199 #define PATH_HAVE_{s} 1
2200#else
2201 #define PATH_HAVE_{s} 0
2202#endif
2203
2204""".rstrip().format(s=s))
2205[python start generated code]*/
2206
2207#ifdef HAVE_FACCESSAT
2208 #define FACCESSAT_DIR_FD_CONVERTER dir_fd_converter
2209#else
2210 #define FACCESSAT_DIR_FD_CONVERTER dir_fd_unavailable
2211#endif
2212
2213#ifdef HAVE_FCHMODAT
2214 #define FCHMODAT_DIR_FD_CONVERTER dir_fd_converter
2215#else
2216 #define FCHMODAT_DIR_FD_CONVERTER dir_fd_unavailable
2217#endif
2218
2219#ifdef HAVE_FCHOWNAT
2220 #define FCHOWNAT_DIR_FD_CONVERTER dir_fd_converter
2221#else
2222 #define FCHOWNAT_DIR_FD_CONVERTER dir_fd_unavailable
2223#endif
2224
2225#ifdef HAVE_FSTATAT
2226 #define FSTATAT_DIR_FD_CONVERTER dir_fd_converter
2227#else
2228 #define FSTATAT_DIR_FD_CONVERTER dir_fd_unavailable
2229#endif
2230
2231#ifdef HAVE_LINKAT
2232 #define LINKAT_DIR_FD_CONVERTER dir_fd_converter
2233#else
2234 #define LINKAT_DIR_FD_CONVERTER dir_fd_unavailable
2235#endif
2236
2237#ifdef HAVE_MKDIRAT
2238 #define MKDIRAT_DIR_FD_CONVERTER dir_fd_converter
2239#else
2240 #define MKDIRAT_DIR_FD_CONVERTER dir_fd_unavailable
2241#endif
2242
2243#ifdef HAVE_MKFIFOAT
2244 #define MKFIFOAT_DIR_FD_CONVERTER dir_fd_converter
2245#else
2246 #define MKFIFOAT_DIR_FD_CONVERTER dir_fd_unavailable
2247#endif
2248
2249#ifdef HAVE_MKNODAT
2250 #define MKNODAT_DIR_FD_CONVERTER dir_fd_converter
2251#else
2252 #define MKNODAT_DIR_FD_CONVERTER dir_fd_unavailable
2253#endif
2254
2255#ifdef HAVE_OPENAT
2256 #define OPENAT_DIR_FD_CONVERTER dir_fd_converter
2257#else
2258 #define OPENAT_DIR_FD_CONVERTER dir_fd_unavailable
2259#endif
2260
2261#ifdef HAVE_READLINKAT
2262 #define READLINKAT_DIR_FD_CONVERTER dir_fd_converter
2263#else
2264 #define READLINKAT_DIR_FD_CONVERTER dir_fd_unavailable
2265#endif
2266
2267#ifdef HAVE_SYMLINKAT
2268 #define SYMLINKAT_DIR_FD_CONVERTER dir_fd_converter
2269#else
2270 #define SYMLINKAT_DIR_FD_CONVERTER dir_fd_unavailable
2271#endif
2272
2273#ifdef HAVE_UNLINKAT
2274 #define UNLINKAT_DIR_FD_CONVERTER dir_fd_converter
2275#else
2276 #define UNLINKAT_DIR_FD_CONVERTER dir_fd_unavailable
2277#endif
2278
2279#ifdef HAVE_FCHDIR
2280 #define PATH_HAVE_FCHDIR 1
2281#else
2282 #define PATH_HAVE_FCHDIR 0
2283#endif
2284
2285#ifdef HAVE_FCHMOD
2286 #define PATH_HAVE_FCHMOD 1
2287#else
2288 #define PATH_HAVE_FCHMOD 0
2289#endif
2290
2291#ifdef HAVE_FCHOWN
2292 #define PATH_HAVE_FCHOWN 1
2293#else
2294 #define PATH_HAVE_FCHOWN 0
2295#endif
2296
2297#ifdef HAVE_FDOPENDIR
2298 #define PATH_HAVE_FDOPENDIR 1
2299#else
2300 #define PATH_HAVE_FDOPENDIR 0
2301#endif
2302
2303#ifdef HAVE_FEXECVE
2304 #define PATH_HAVE_FEXECVE 1
2305#else
2306 #define PATH_HAVE_FEXECVE 0
2307#endif
2308
2309#ifdef HAVE_FPATHCONF
2310 #define PATH_HAVE_FPATHCONF 1
2311#else
2312 #define PATH_HAVE_FPATHCONF 0
2313#endif
2314
2315#ifdef HAVE_FSTATVFS
2316 #define PATH_HAVE_FSTATVFS 1
2317#else
2318 #define PATH_HAVE_FSTATVFS 0
2319#endif
2320
2321#ifdef HAVE_FTRUNCATE
2322 #define PATH_HAVE_FTRUNCATE 1
2323#else
2324 #define PATH_HAVE_FTRUNCATE 0
2325#endif
2326/*[python end generated code: output=4bd4f6f7d41267f1 input=80b4c890b6774ea5]*/
2327
2328#ifdef MS_WINDOWS
2329 #undef PATH_HAVE_FTRUNCATE
2330 #define PATH_HAVE_FTRUNCATE 1
2331#endif
2332
2333/*[python input]
2334
2335class path_t_converter(CConverter):
2336
2337 type = "path_t"
2338 impl_by_reference = True
2339 parse_by_reference = True
2340
2341 converter = 'path_converter'
2342
2343 def converter_init(self, *, allow_fd=False, nullable=False):
2344 # right now path_t doesn't support default values.
2345 # to support a default value, you'll need to override initialize().
2346 if self.default not in (unspecified, None):
2347 fail("Can't specify a default to the path_t converter!")
2348
2349 if self.c_default not in (None, 'Py_None'):
2350 raise RuntimeError("Can't specify a c_default to the path_t converter!")
2351
2352 self.nullable = nullable
2353 self.allow_fd = allow_fd
2354
2355 def pre_render(self):
2356 def strify(value):
2357 if isinstance(value, str):
2358 return value
2359 return str(int(bool(value)))
2360
2361 # add self.py_name here when merging with posixmodule conversion
2362 self.c_default = 'PATH_T_INITIALIZE("{}", "{}", {}, {})'.format(
2363 self.function.name,
2364 self.name,
2365 strify(self.nullable),
2366 strify(self.allow_fd),
2367 )
2368
2369 def cleanup(self):
2370 return "path_cleanup(&" + self.name + ");\n"
2371
2372
2373class dir_fd_converter(CConverter):
2374 type = 'int'
2375
2376 def converter_init(self, requires=None):
2377 if self.default in (unspecified, None):
2378 self.c_default = 'DEFAULT_DIR_FD'
2379 if isinstance(requires, str):
2380 self.converter = requires.upper() + '_DIR_FD_CONVERTER'
2381 else:
2382 self.converter = 'dir_fd_converter'
2383
2384class fildes_converter(CConverter):
2385 type = 'int'
2386 converter = 'fildes_converter'
2387
2388class uid_t_converter(CConverter):
2389 type = "uid_t"
2390 converter = '_Py_Uid_Converter'
2391
2392class gid_t_converter(CConverter):
2393 type = "gid_t"
2394 converter = '_Py_Gid_Converter'
2395
2396class dev_t_converter(CConverter):
2397 type = 'dev_t'
2398 converter = '_Py_Dev_Converter'
2399
2400class dev_t_return_converter(unsigned_long_return_converter):
2401 type = 'dev_t'
2402 conversion_fn = '_PyLong_FromDev'
2403 unsigned_cast = '(dev_t)'
2404
2405class FSConverter_converter(CConverter):
2406 type = 'PyObject *'
2407 converter = 'PyUnicode_FSConverter'
2408 def converter_init(self):
2409 if self.default is not unspecified:
2410 fail("FSConverter_converter does not support default values")
2411 self.c_default = 'NULL'
2412
2413 def cleanup(self):
2414 return "Py_XDECREF(" + self.name + ");\n"
2415
2416class pid_t_converter(CConverter):
2417 type = 'pid_t'
2418 format_unit = '" _Py_PARSE_PID "'
2419
2420class idtype_t_converter(int_converter):
2421 type = 'idtype_t'
2422
2423class id_t_converter(CConverter):
2424 type = 'id_t'
2425 format_unit = '" _Py_PARSE_PID "'
2426
2427class intptr_t_converter(CConverter):
2428 type = 'intptr_t'
2429 format_unit = '" _Py_PARSE_INTPTR "'
2430
2431class Py_off_t_converter(CConverter):
2432 type = 'Py_off_t'
2433 converter = 'Py_off_t_converter'
2434
2435class Py_off_t_return_converter(long_return_converter):
2436 type = 'Py_off_t'
2437 conversion_fn = 'PyLong_FromPy_off_t'
2438
2439class path_confname_converter(CConverter):
2440 type="int"
2441 converter="conv_path_confname"
2442
2443class confstr_confname_converter(path_confname_converter):
2444 converter='conv_confstr_confname'
2445
2446class sysconf_confname_converter(path_confname_converter):
2447 converter="conv_sysconf_confname"
2448
2449class sched_param_converter(CConverter):
2450 type = 'struct sched_param'
2451 converter = 'convert_sched_param'
2452 impl_by_reference = True;
2453
2454[python start generated code]*/
2455/*[python end generated code: output=da39a3ee5e6b4b0d input=418fce0e01144461]*/
2456
2457/*[clinic input]
2458
2459os.stat
2460
2461 path : path_t(allow_fd=True)
2462 Path to be examined; can be string, bytes, a path-like object or
2463 open-file-descriptor int.
2464
2465 *
2466
2467 dir_fd : dir_fd(requires='fstatat') = None
2468 If not None, it should be a file descriptor open to a directory,
2469 and path should be a relative string; path will then be relative to
2470 that directory.
2471
2472 follow_symlinks: bool = True
2473 If False, and the last element of the path is a symbolic link,
2474 stat will examine the symbolic link itself instead of the file
2475 the link points to.
2476
2477Perform a stat system call on the given path.
2478
2479dir_fd and follow_symlinks may not be implemented
2480 on your platform. If they are unavailable, using them will raise a
2481 NotImplementedError.
2482
2483It's an error to use dir_fd or follow_symlinks when specifying path as
2484 an open file descriptor.
2485
2486[clinic start generated code]*/
2487
2488static PyObject *
2489os_stat_impl(PyObject *module, path_t *path, int dir_fd, int follow_symlinks)
2490/*[clinic end generated code: output=7d4976e6f18a59c5 input=01d362ebcc06996b]*/
2491{
2492 return posix_do_stat("stat", path, dir_fd, follow_symlinks);
2493}
2494
2495
2496/*[clinic input]
2497os.lstat
2498
2499 path : path_t
2500
2501 *
2502
2503 dir_fd : dir_fd(requires='fstatat') = None
2504
2505Perform a stat system call on the given path, without following symbolic links.
2506
2507Like stat(), but do not follow symbolic links.
2508Equivalent to stat(path, follow_symlinks=False).
2509[clinic start generated code]*/
2510
2511static PyObject *
2512os_lstat_impl(PyObject *module, path_t *path, int dir_fd)
2513/*[clinic end generated code: output=ef82a5d35ce8ab37 input=0b7474765927b925]*/
2514{
2515 int follow_symlinks = 0;
2516 return posix_do_stat("lstat", path, dir_fd, follow_symlinks);
2517}
2518
2519
2520/*[clinic input]
2521os.access -> bool
2522
2523 path: path_t
2524 Path to be tested; can be string, bytes, or a path-like object.
2525
2526 mode: int
2527 Operating-system mode bitfield. Can be F_OK to test existence,
2528 or the inclusive-OR of R_OK, W_OK, and X_OK.
2529
2530 *
2531
2532 dir_fd : dir_fd(requires='faccessat') = None
2533 If not None, it should be a file descriptor open to a directory,
2534 and path should be relative; path will then be relative to that
2535 directory.
2536
2537 effective_ids: bool = False
2538 If True, access will use the effective uid/gid instead of
2539 the real uid/gid.
2540
2541 follow_symlinks: bool = True
2542 If False, and the last element of the path is a symbolic link,
2543 access will examine the symbolic link itself instead of the file
2544 the link points to.
2545
2546Use the real uid/gid to test for access to a path.
2547
2548{parameters}
2549dir_fd, effective_ids, and follow_symlinks may not be implemented
2550 on your platform. If they are unavailable, using them will raise a
2551 NotImplementedError.
2552
2553Note that most operations will use the effective uid/gid, therefore this
2554 routine can be used in a suid/sgid environment to test if the invoking user
2555 has the specified access to the path.
2556
2557[clinic start generated code]*/
2558
2559static int
2560os_access_impl(PyObject *module, path_t *path, int mode, int dir_fd,
2561 int effective_ids, int follow_symlinks)
2562/*[clinic end generated code: output=cf84158bc90b1a77 input=3ffe4e650ee3bf20]*/
2563{
2564 int return_value;
2565
2566#ifdef MS_WINDOWS
2567 DWORD attr;
2568#else
2569 int result;
2570#endif
2571
2572#ifndef HAVE_FACCESSAT
2573 if (follow_symlinks_specified("access", follow_symlinks))
2574 return -1;
2575
2576 if (effective_ids) {
2577 argument_unavailable_error("access", "effective_ids");
2578 return -1;
2579 }
2580#endif
2581
2582#ifdef MS_WINDOWS
2583 Py_BEGIN_ALLOW_THREADS
2584 attr = GetFileAttributesW(path->wide);
2585 Py_END_ALLOW_THREADS
2586
2587 /*
2588 * Access is possible if
2589 * * we didn't get a -1, and
2590 * * write access wasn't requested,
2591 * * or the file isn't read-only,
2592 * * or it's a directory.
2593 * (Directories cannot be read-only on Windows.)
2594 */
2595 return_value = (attr != INVALID_FILE_ATTRIBUTES) &&
2596 (!(mode & 2) ||
2597 !(attr & FILE_ATTRIBUTE_READONLY) ||
2598 (attr & FILE_ATTRIBUTE_DIRECTORY));
2599#else
2600
2601 Py_BEGIN_ALLOW_THREADS
2602#ifdef HAVE_FACCESSAT
2603 if ((dir_fd != DEFAULT_DIR_FD) ||
2604 effective_ids ||
2605 !follow_symlinks) {
2606 int flags = 0;
2607 if (!follow_symlinks)
2608 flags |= AT_SYMLINK_NOFOLLOW;
2609 if (effective_ids)
2610 flags |= AT_EACCESS;
2611 result = faccessat(dir_fd, path->narrow, mode, flags);
2612 }
2613 else
2614#endif
2615 result = access(path->narrow, mode);
2616 Py_END_ALLOW_THREADS
2617 return_value = !result;
2618#endif
2619
2620 return return_value;
2621}
2622
2623#ifndef F_OK
2624#define F_OK 0
2625#endif
2626#ifndef R_OK
2627#define R_OK 4
2628#endif
2629#ifndef W_OK
2630#define W_OK 2
2631#endif
2632#ifndef X_OK
2633#define X_OK 1
2634#endif
2635
2636
2637#ifdef HAVE_TTYNAME
2638/*[clinic input]
2639os.ttyname -> DecodeFSDefault
2640
2641 fd: int
2642 Integer file descriptor handle.
2643
2644 /
2645
2646Return the name of the terminal device connected to 'fd'.
2647[clinic start generated code]*/
2648
2649static char *
2650os_ttyname_impl(PyObject *module, int fd)
2651/*[clinic end generated code: output=ed16ad216d813591 input=5f72ca83e76b3b45]*/
2652{
2653 char *ret;
2654
2655 ret = ttyname(fd);
2656 if (ret == NULL)
2657 posix_error();
2658 return ret;
2659}
2660#endif
2661
2662#ifdef HAVE_CTERMID
2663/*[clinic input]
2664os.ctermid
2665
2666Return the name of the controlling terminal for this process.
2667[clinic start generated code]*/
2668
2669static PyObject *
2670os_ctermid_impl(PyObject *module)
2671/*[clinic end generated code: output=02f017e6c9e620db input=3b87fdd52556382d]*/
2672{
2673 char *ret;
2674 char buffer[L_ctermid];
2675
2676#ifdef USE_CTERMID_R
2677 ret = ctermid_r(buffer);
2678#else
2679 ret = ctermid(buffer);
2680#endif
2681 if (ret == NULL)
2682 return posix_error();
2683 return PyUnicode_DecodeFSDefault(buffer);
2684}
2685#endif /* HAVE_CTERMID */
2686
2687
2688/*[clinic input]
2689os.chdir
2690
2691 path: path_t(allow_fd='PATH_HAVE_FCHDIR')
2692
2693Change the current working directory to the specified path.
2694
2695path may always be specified as a string.
2696On some platforms, path may also be specified as an open file descriptor.
2697 If this functionality is unavailable, using it raises an exception.
2698[clinic start generated code]*/
2699
2700static PyObject *
2701os_chdir_impl(PyObject *module, path_t *path)
2702/*[clinic end generated code: output=3be6400eee26eaae input=1a4a15b4d12cb15d]*/
2703{
2704 int result;
2705
2706 Py_BEGIN_ALLOW_THREADS
2707#ifdef MS_WINDOWS
2708 /* on unix, success = 0, on windows, success = !0 */
2709 result = !win32_wchdir(path->wide);
2710#else
2711#ifdef HAVE_FCHDIR
2712 if (path->fd != -1)
2713 result = fchdir(path->fd);
2714 else
2715#endif
2716 result = chdir(path->narrow);
2717#endif
2718 Py_END_ALLOW_THREADS
2719
2720 if (result) {
2721 return path_error(path);
2722 }
2723
2724 Py_RETURN_NONE;
2725}
2726
2727
2728#ifdef HAVE_FCHDIR
2729/*[clinic input]
2730os.fchdir
2731
2732 fd: fildes
2733
2734Change to the directory of the given file descriptor.
2735
2736fd must be opened on a directory, not a file.
2737Equivalent to os.chdir(fd).
2738
2739[clinic start generated code]*/
2740
2741static PyObject *
2742os_fchdir_impl(PyObject *module, int fd)
2743/*[clinic end generated code: output=42e064ec4dc00ab0 input=18e816479a2fa985]*/
2744{
2745 return posix_fildes_fd(fd, fchdir);
2746}
2747#endif /* HAVE_FCHDIR */
2748
2749
2750/*[clinic input]
2751os.chmod
2752
2753 path: path_t(allow_fd='PATH_HAVE_FCHMOD')
2754 Path to be modified. May always be specified as a str, bytes, or a path-like object.
2755 On some platforms, path may also be specified as an open file descriptor.
2756 If this functionality is unavailable, using it raises an exception.
2757
2758 mode: int
2759 Operating-system mode bitfield.
2760
2761 *
2762
2763 dir_fd : dir_fd(requires='fchmodat') = None
2764 If not None, it should be a file descriptor open to a directory,
2765 and path should be relative; path will then be relative to that
2766 directory.
2767
2768 follow_symlinks: bool = True
2769 If False, and the last element of the path is a symbolic link,
2770 chmod will modify the symbolic link itself instead of the file
2771 the link points to.
2772
2773Change the access permissions of a file.
2774
2775It is an error to use dir_fd or follow_symlinks when specifying path as
2776 an open file descriptor.
2777dir_fd and follow_symlinks may not be implemented on your platform.
2778 If they are unavailable, using them will raise a NotImplementedError.
2779
2780[clinic start generated code]*/
2781
2782static PyObject *
2783os_chmod_impl(PyObject *module, path_t *path, int mode, int dir_fd,
2784 int follow_symlinks)
2785/*[clinic end generated code: output=5cf6a94915cc7bff input=989081551c00293b]*/
2786{
2787 int result;
2788
2789#ifdef MS_WINDOWS
2790 DWORD attr;
2791#endif
2792
2793#ifdef HAVE_FCHMODAT
2794 int fchmodat_nofollow_unsupported = 0;
2795#endif
2796
2797#if !(defined(HAVE_FCHMODAT) || defined(HAVE_LCHMOD))
2798 if (follow_symlinks_specified("chmod", follow_symlinks))
2799 return NULL;
2800#endif
2801
2802#ifdef MS_WINDOWS
2803 Py_BEGIN_ALLOW_THREADS
2804 attr = GetFileAttributesW(path->wide);
2805 if (attr == INVALID_FILE_ATTRIBUTES)
2806 result = 0;
2807 else {
2808 if (mode & _S_IWRITE)
2809 attr &= ~FILE_ATTRIBUTE_READONLY;
2810 else
2811 attr |= FILE_ATTRIBUTE_READONLY;
2812 result = SetFileAttributesW(path->wide, attr);
2813 }
2814 Py_END_ALLOW_THREADS
2815
2816 if (!result) {
2817 return path_error(path);
2818 }
2819#else /* MS_WINDOWS */
2820 Py_BEGIN_ALLOW_THREADS
2821#ifdef HAVE_FCHMOD
2822 if (path->fd != -1)
2823 result = fchmod(path->fd, mode);
2824 else
2825#endif
2826#ifdef HAVE_LCHMOD
2827 if ((!follow_symlinks) && (dir_fd == DEFAULT_DIR_FD))
2828 result = lchmod(path->narrow, mode);
2829 else
2830#endif
2831#ifdef HAVE_FCHMODAT
2832 if ((dir_fd != DEFAULT_DIR_FD) || !follow_symlinks) {
2833 /*
2834 * fchmodat() doesn't currently support AT_SYMLINK_NOFOLLOW!
2835 * The documentation specifically shows how to use it,
2836 * and then says it isn't implemented yet.
2837 * (true on linux with glibc 2.15, and openindiana 3.x)
2838 *
2839 * Once it is supported, os.chmod will automatically
2840 * support dir_fd and follow_symlinks=False. (Hopefully.)
2841 * Until then, we need to be careful what exception we raise.
2842 */
2843 result = fchmodat(dir_fd, path->narrow, mode,
2844 follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW);
2845 /*
2846 * But wait! We can't throw the exception without allowing threads,
2847 * and we can't do that in this nested scope. (Macro trickery, sigh.)
2848 */
2849 fchmodat_nofollow_unsupported =
2850 result &&
2851 ((errno == ENOTSUP) || (errno == EOPNOTSUPP)) &&
2852 !follow_symlinks;
2853 }
2854 else
2855#endif
2856 result = chmod(path->narrow, mode);
2857 Py_END_ALLOW_THREADS
2858
2859 if (result) {
2860#ifdef HAVE_FCHMODAT
2861 if (fchmodat_nofollow_unsupported) {
2862 if (dir_fd != DEFAULT_DIR_FD)
2863 dir_fd_and_follow_symlinks_invalid("chmod",
2864 dir_fd, follow_symlinks);
2865 else
2866 follow_symlinks_specified("chmod", follow_symlinks);
2867 return NULL;
2868 }
2869 else
2870#endif
2871 return path_error(path);
2872 }
2873#endif
2874
2875 Py_RETURN_NONE;
2876}
2877
2878
2879#ifdef HAVE_FCHMOD
2880/*[clinic input]
2881os.fchmod
2882
2883 fd: int
2884 mode: int
2885
2886Change the access permissions of the file given by file descriptor fd.
2887
2888Equivalent to os.chmod(fd, mode).
2889[clinic start generated code]*/
2890
2891static PyObject *
2892os_fchmod_impl(PyObject *module, int fd, int mode)
2893/*[clinic end generated code: output=afd9bc05b4e426b3 input=8ab11975ca01ee5b]*/
2894{
2895 int res;
2896 int async_err = 0;
2897
2898 do {
2899 Py_BEGIN_ALLOW_THREADS
2900 res = fchmod(fd, mode);
2901 Py_END_ALLOW_THREADS
2902 } while (res != 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
2903 if (res != 0)
2904 return (!async_err) ? posix_error() : NULL;
2905
2906 Py_RETURN_NONE;
2907}
2908#endif /* HAVE_FCHMOD */
2909
2910
2911#ifdef HAVE_LCHMOD
2912/*[clinic input]
2913os.lchmod
2914
2915 path: path_t
2916 mode: int
2917
2918Change the access permissions of a file, without following symbolic links.
2919
2920If path is a symlink, this affects the link itself rather than the target.
2921Equivalent to chmod(path, mode, follow_symlinks=False)."
2922[clinic start generated code]*/
2923
2924static PyObject *
2925os_lchmod_impl(PyObject *module, path_t *path, int mode)
2926/*[clinic end generated code: output=082344022b51a1d5 input=90c5663c7465d24f]*/
2927{
2928 int res;
2929 Py_BEGIN_ALLOW_THREADS
2930 res = lchmod(path->narrow, mode);
2931 Py_END_ALLOW_THREADS
2932 if (res < 0) {
2933 path_error(path);
2934 return NULL;
2935 }
2936 Py_RETURN_NONE;
2937}
2938#endif /* HAVE_LCHMOD */
2939
2940
2941#ifdef HAVE_CHFLAGS
2942/*[clinic input]
2943os.chflags
2944
2945 path: path_t
2946 flags: unsigned_long(bitwise=True)
2947 follow_symlinks: bool=True
2948
2949Set file flags.
2950
2951If follow_symlinks is False, and the last element of the path is a symbolic
2952 link, chflags will change flags on the symbolic link itself instead of the
2953 file the link points to.
2954follow_symlinks may not be implemented on your platform. If it is
2955unavailable, using it will raise a NotImplementedError.
2956
2957[clinic start generated code]*/
2958
2959static PyObject *
2960os_chflags_impl(PyObject *module, path_t *path, unsigned long flags,
2961 int follow_symlinks)
2962/*[clinic end generated code: output=85571c6737661ce9 input=0327e29feb876236]*/
2963{
2964 int result;
2965
2966#ifndef HAVE_LCHFLAGS
2967 if (follow_symlinks_specified("chflags", follow_symlinks))
2968 return NULL;
2969#endif
2970
2971 Py_BEGIN_ALLOW_THREADS
2972#ifdef HAVE_LCHFLAGS
2973 if (!follow_symlinks)
2974 result = lchflags(path->narrow, flags);
2975 else
2976#endif
2977 result = chflags(path->narrow, flags);
2978 Py_END_ALLOW_THREADS
2979
2980 if (result)
2981 return path_error(path);
2982
2983 Py_RETURN_NONE;
2984}
2985#endif /* HAVE_CHFLAGS */
2986
2987
2988#ifdef HAVE_LCHFLAGS
2989/*[clinic input]
2990os.lchflags
2991
2992 path: path_t
2993 flags: unsigned_long(bitwise=True)
2994
2995Set file flags.
2996
2997This function will not follow symbolic links.
2998Equivalent to chflags(path, flags, follow_symlinks=False).
2999[clinic start generated code]*/
3000
3001static PyObject *
3002os_lchflags_impl(PyObject *module, path_t *path, unsigned long flags)
3003/*[clinic end generated code: output=30ae958695c07316 input=f9f82ea8b585ca9d]*/
3004{
3005 int res;
3006 Py_BEGIN_ALLOW_THREADS
3007 res = lchflags(path->narrow, flags);
3008 Py_END_ALLOW_THREADS
3009 if (res < 0) {
3010 return path_error(path);
3011 }
3012 Py_RETURN_NONE;
3013}
3014#endif /* HAVE_LCHFLAGS */
3015
3016
3017#ifdef HAVE_CHROOT
3018/*[clinic input]
3019os.chroot
3020 path: path_t
3021
3022Change root directory to path.
3023
3024[clinic start generated code]*/
3025
3026static PyObject *
3027os_chroot_impl(PyObject *module, path_t *path)
3028/*[clinic end generated code: output=de80befc763a4475 input=14822965652c3dc3]*/
3029{
3030 int res;
3031 Py_BEGIN_ALLOW_THREADS
3032 res = chroot(path->narrow);
3033 Py_END_ALLOW_THREADS
3034 if (res < 0)
3035 return path_error(path);
3036 Py_RETURN_NONE;
3037}
3038#endif /* HAVE_CHROOT */
3039
3040
3041#ifdef HAVE_FSYNC
3042/*[clinic input]
3043os.fsync
3044
3045 fd: fildes
3046
3047Force write of fd to disk.
3048[clinic start generated code]*/
3049
3050static PyObject *
3051os_fsync_impl(PyObject *module, int fd)
3052/*[clinic end generated code: output=4a10d773f52b3584 input=21c3645c056967f2]*/
3053{
3054 return posix_fildes_fd(fd, fsync);
3055}
3056#endif /* HAVE_FSYNC */
3057
3058
3059#ifdef HAVE_SYNC
3060/*[clinic input]
3061os.sync
3062
3063Force write of everything to disk.
3064[clinic start generated code]*/
3065
3066static PyObject *
3067os_sync_impl(PyObject *module)
3068/*[clinic end generated code: output=2796b1f0818cd71c input=84749fe5e9b404ff]*/
3069{
3070 Py_BEGIN_ALLOW_THREADS
3071 sync();
3072 Py_END_ALLOW_THREADS
3073 Py_RETURN_NONE;
3074}
3075#endif /* HAVE_SYNC */
3076
3077
3078#ifdef HAVE_FDATASYNC
3079#ifdef __hpux
3080extern int fdatasync(int); /* On HP-UX, in libc but not in unistd.h */
3081#endif
3082
3083/*[clinic input]
3084os.fdatasync
3085
3086 fd: fildes
3087
3088Force write of fd to disk without forcing update of metadata.
3089[clinic start generated code]*/
3090
3091static PyObject *
3092os_fdatasync_impl(PyObject *module, int fd)
3093/*[clinic end generated code: output=b4b9698b5d7e26dd input=bc74791ee54dd291]*/
3094{
3095 return posix_fildes_fd(fd, fdatasync);
3096}
3097#endif /* HAVE_FDATASYNC */
3098
3099
3100#ifdef HAVE_CHOWN
3101/*[clinic input]
3102os.chown
3103
3104 path : path_t(allow_fd='PATH_HAVE_FCHOWN')
3105 Path to be examined; can be string, bytes, a path-like object, or open-file-descriptor int.
3106
3107 uid: uid_t
3108
3109 gid: gid_t
3110
3111 *
3112
3113 dir_fd : dir_fd(requires='fchownat') = None
3114 If not None, it should be a file descriptor open to a directory,
3115 and path should be relative; path will then be relative to that
3116 directory.
3117
3118 follow_symlinks: bool = True
3119 If False, and the last element of the path is a symbolic link,
3120 stat will examine the symbolic link itself instead of the file
3121 the link points to.
3122
3123Change the owner and group id of path to the numeric uid and gid.\
3124
3125path may always be specified as a string.
3126On some platforms, path may also be specified as an open file descriptor.
3127 If this functionality is unavailable, using it raises an exception.
3128If dir_fd is not None, it should be a file descriptor open to a directory,
3129 and path should be relative; path will then be relative to that directory.
3130If follow_symlinks is False, and the last element of the path is a symbolic
3131 link, chown will modify the symbolic link itself instead of the file the
3132 link points to.
3133It is an error to use dir_fd or follow_symlinks when specifying path as
3134 an open file descriptor.
3135dir_fd and follow_symlinks may not be implemented on your platform.
3136 If they are unavailable, using them will raise a NotImplementedError.
3137
3138[clinic start generated code]*/
3139
3140static PyObject *
3141os_chown_impl(PyObject *module, path_t *path, uid_t uid, gid_t gid,
3142 int dir_fd, int follow_symlinks)
3143/*[clinic end generated code: output=4beadab0db5f70cd input=b08c5ec67996a97d]*/
3144{
3145 int result;
3146
3147#if !(defined(HAVE_LCHOWN) || defined(HAVE_FCHOWNAT))
3148 if (follow_symlinks_specified("chown", follow_symlinks))
3149 return NULL;
3150#endif
3151 if (dir_fd_and_fd_invalid("chown", dir_fd, path->fd) ||
3152 fd_and_follow_symlinks_invalid("chown", path->fd, follow_symlinks))
3153 return NULL;
3154
3155#ifdef __APPLE__
3156 /*
3157 * This is for Mac OS X 10.3, which doesn't have lchown.
3158 * (But we still have an lchown symbol because of weak-linking.)
3159 * It doesn't have fchownat either. So there's no possibility
3160 * of a graceful failover.
3161 */
3162 if ((!follow_symlinks) && (lchown == NULL)) {
3163 follow_symlinks_specified("chown", follow_symlinks);
3164 return NULL;
3165 }
3166#endif
3167
3168 Py_BEGIN_ALLOW_THREADS
3169#ifdef HAVE_FCHOWN
3170 if (path->fd != -1)
3171 result = fchown(path->fd, uid, gid);
3172 else
3173#endif
3174#ifdef HAVE_LCHOWN
3175 if ((!follow_symlinks) && (dir_fd == DEFAULT_DIR_FD))
3176 result = lchown(path->narrow, uid, gid);
3177 else
3178#endif
3179#ifdef HAVE_FCHOWNAT
3180 if ((dir_fd != DEFAULT_DIR_FD) || (!follow_symlinks))
3181 result = fchownat(dir_fd, path->narrow, uid, gid,
3182 follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW);
3183 else
3184#endif
3185 result = chown(path->narrow, uid, gid);
3186 Py_END_ALLOW_THREADS
3187
3188 if (result)
3189 return path_error(path);
3190
3191 Py_RETURN_NONE;
3192}
3193#endif /* HAVE_CHOWN */
3194
3195
3196#ifdef HAVE_FCHOWN
3197/*[clinic input]
3198os.fchown
3199
3200 fd: int
3201 uid: uid_t
3202 gid: gid_t
3203
3204Change the owner and group id of the file specified by file descriptor.
3205
3206Equivalent to os.chown(fd, uid, gid).
3207
3208[clinic start generated code]*/
3209
3210static PyObject *
3211os_fchown_impl(PyObject *module, int fd, uid_t uid, gid_t gid)
3212/*[clinic end generated code: output=97d21cbd5a4350a6 input=3af544ba1b13a0d7]*/
3213{
3214 int res;
3215 int async_err = 0;
3216
3217 do {
3218 Py_BEGIN_ALLOW_THREADS
3219 res = fchown(fd, uid, gid);
3220 Py_END_ALLOW_THREADS
3221 } while (res != 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
3222 if (res != 0)
3223 return (!async_err) ? posix_error() : NULL;
3224
3225 Py_RETURN_NONE;
3226}
3227#endif /* HAVE_FCHOWN */
3228
3229
3230#ifdef HAVE_LCHOWN
3231/*[clinic input]
3232os.lchown
3233
3234 path : path_t
3235 uid: uid_t
3236 gid: gid_t
3237
3238Change the owner and group id of path to the numeric uid and gid.
3239
3240This function will not follow symbolic links.
3241Equivalent to os.chown(path, uid, gid, follow_symlinks=False).
3242[clinic start generated code]*/
3243
3244static PyObject *
3245os_lchown_impl(PyObject *module, path_t *path, uid_t uid, gid_t gid)
3246/*[clinic end generated code: output=25eaf6af412fdf2f input=b1c6014d563a7161]*/
3247{
3248 int res;
3249 Py_BEGIN_ALLOW_THREADS
3250 res = lchown(path->narrow, uid, gid);
3251 Py_END_ALLOW_THREADS
3252 if (res < 0) {
3253 return path_error(path);
3254 }
3255 Py_RETURN_NONE;
3256}
3257#endif /* HAVE_LCHOWN */
3258
3259
3260static PyObject *
3261posix_getcwd(int use_bytes)
3262{
3263 char *buf, *tmpbuf;
3264 char *cwd;
3265 const size_t chunk = 1024;
3266 size_t buflen = 0;
3267 PyObject *obj;
3268
3269#ifdef MS_WINDOWS
3270 if (!use_bytes) {
3271 wchar_t wbuf[MAXPATHLEN];
3272 wchar_t *wbuf2 = wbuf;
3273 PyObject *resobj;
3274 DWORD len;
3275 Py_BEGIN_ALLOW_THREADS
3276 len = GetCurrentDirectoryW(Py_ARRAY_LENGTH(wbuf), wbuf);
3277 /* If the buffer is large enough, len does not include the
3278 terminating \0. If the buffer is too small, len includes
3279 the space needed for the terminator. */
3280 if (len >= Py_ARRAY_LENGTH(wbuf)) {
3281 wbuf2 = PyMem_RawMalloc(len * sizeof(wchar_t));
3282 if (wbuf2)
3283 len = GetCurrentDirectoryW(len, wbuf2);
3284 }
3285 Py_END_ALLOW_THREADS
3286 if (!wbuf2) {
3287 PyErr_NoMemory();
3288 return NULL;
3289 }
3290 if (!len) {
3291 if (wbuf2 != wbuf)
3292 PyMem_RawFree(wbuf2);
3293 return PyErr_SetFromWindowsErr(0);
3294 }
3295 resobj = PyUnicode_FromWideChar(wbuf2, len);
3296 if (wbuf2 != wbuf)
3297 PyMem_RawFree(wbuf2);
3298 return resobj;
3299 }
3300
3301 if (win32_warn_bytes_api())
3302 return NULL;
3303#endif
3304
3305 buf = cwd = NULL;
3306 Py_BEGIN_ALLOW_THREADS
3307 do {
3308 buflen += chunk;
3309#ifdef MS_WINDOWS
3310 if (buflen > INT_MAX) {
3311 PyErr_NoMemory();
3312 break;
3313 }
3314#endif
3315 tmpbuf = PyMem_RawRealloc(buf, buflen);
3316 if (tmpbuf == NULL)
3317 break;
3318
3319 buf = tmpbuf;
3320#ifdef MS_WINDOWS
3321 cwd = getcwd(buf, (int)buflen);
3322#else
3323 cwd = getcwd(buf, buflen);
3324#endif
3325 } while (cwd == NULL && errno == ERANGE);
3326 Py_END_ALLOW_THREADS
3327
3328 if (cwd == NULL) {
3329 PyMem_RawFree(buf);
3330 return posix_error();
3331 }
3332
3333 if (use_bytes)
3334 obj = PyBytes_FromStringAndSize(buf, strlen(buf));
3335 else
3336 obj = PyUnicode_DecodeFSDefault(buf);
3337 PyMem_RawFree(buf);
3338
3339 return obj;
3340}
3341
3342
3343/*[clinic input]
3344os.getcwd
3345
3346Return a unicode string representing the current working directory.
3347[clinic start generated code]*/
3348
3349static PyObject *
3350os_getcwd_impl(PyObject *module)
3351/*[clinic end generated code: output=21badfae2ea99ddc input=f069211bb70e3d39]*/
3352{
3353 return posix_getcwd(0);
3354}
3355
3356
3357/*[clinic input]
3358os.getcwdb
3359
3360Return a bytes string representing the current working directory.
3361[clinic start generated code]*/
3362
3363static PyObject *
3364os_getcwdb_impl(PyObject *module)
3365/*[clinic end generated code: output=3dd47909480e4824 input=f6f6a378dad3d9cb]*/
3366{
3367 return posix_getcwd(1);
3368}
3369
3370
3371#if ((!defined(HAVE_LINK)) && defined(MS_WINDOWS))
3372#define HAVE_LINK 1
3373#endif
3374
3375#ifdef HAVE_LINK
3376/*[clinic input]
3377
3378os.link
3379
3380 src : path_t
3381 dst : path_t
3382 *
3383 src_dir_fd : dir_fd = None
3384 dst_dir_fd : dir_fd = None
3385 follow_symlinks: bool = True
3386
3387Create a hard link to a file.
3388
3389If either src_dir_fd or dst_dir_fd is not None, it should be a file
3390 descriptor open to a directory, and the respective path string (src or dst)
3391 should be relative; the path will then be relative to that directory.
3392If follow_symlinks is False, and the last element of src is a symbolic
3393 link, link will create a link to the symbolic link itself instead of the
3394 file the link points to.
3395src_dir_fd, dst_dir_fd, and follow_symlinks may not be implemented on your
3396 platform. If they are unavailable, using them will raise a
3397 NotImplementedError.
3398[clinic start generated code]*/
3399
3400static PyObject *
3401os_link_impl(PyObject *module, path_t *src, path_t *dst, int src_dir_fd,
3402 int dst_dir_fd, int follow_symlinks)
3403/*[clinic end generated code: output=7f00f6007fd5269a input=b0095ebbcbaa7e04]*/
3404{
3405#ifdef MS_WINDOWS
3406 BOOL result = FALSE;
3407#else
3408 int result;
3409#endif
3410
3411#ifndef HAVE_LINKAT
3412 if ((src_dir_fd != DEFAULT_DIR_FD) || (dst_dir_fd != DEFAULT_DIR_FD)) {
3413 argument_unavailable_error("link", "src_dir_fd and dst_dir_fd");
3414 return NULL;
3415 }
3416#endif
3417
3418#ifndef MS_WINDOWS
3419 if ((src->narrow && dst->wide) || (src->wide && dst->narrow)) {
3420 PyErr_SetString(PyExc_NotImplementedError,
3421 "link: src and dst must be the same type");
3422 return NULL;
3423 }
3424#endif
3425
3426#ifdef MS_WINDOWS
3427 Py_BEGIN_ALLOW_THREADS
3428 result = CreateHardLinkW(dst->wide, src->wide, NULL);
3429 Py_END_ALLOW_THREADS
3430
3431 if (!result)
3432 return path_error2(src, dst);
3433#else
3434 Py_BEGIN_ALLOW_THREADS
3435#ifdef HAVE_LINKAT
3436 if ((src_dir_fd != DEFAULT_DIR_FD) ||
3437 (dst_dir_fd != DEFAULT_DIR_FD) ||
3438 (!follow_symlinks))
3439 result = linkat(src_dir_fd, src->narrow,
3440 dst_dir_fd, dst->narrow,
3441 follow_symlinks ? AT_SYMLINK_FOLLOW : 0);
3442 else
3443#endif /* HAVE_LINKAT */
3444 result = link(src->narrow, dst->narrow);
3445 Py_END_ALLOW_THREADS
3446
3447 if (result)
3448 return path_error2(src, dst);
3449#endif /* MS_WINDOWS */
3450
3451 Py_RETURN_NONE;
3452}
3453#endif
3454
3455
3456#if defined(MS_WINDOWS) && !defined(HAVE_OPENDIR)
3457static PyObject *
3458_listdir_windows_no_opendir(path_t *path, PyObject *list)
3459{
3460 PyObject *v;
3461 HANDLE hFindFile = INVALID_HANDLE_VALUE;
3462 BOOL result;
3463 wchar_t namebuf[MAX_PATH+4]; /* Overallocate for "\*.*" */
3464 /* only claim to have space for MAX_PATH */
3465 Py_ssize_t len = Py_ARRAY_LENGTH(namebuf)-4;
3466 wchar_t *wnamebuf = NULL;
3467
3468 WIN32_FIND_DATAW wFileData;
3469 const wchar_t *po_wchars;
3470
3471 if (!path->wide) { /* Default arg: "." */
3472 po_wchars = L".";
3473 len = 1;
3474 } else {
3475 po_wchars = path->wide;
3476 len = wcslen(path->wide);
3477 }
3478 /* The +5 is so we can append "\\*.*\0" */
3479 wnamebuf = PyMem_New(wchar_t, len + 5);
3480 if (!wnamebuf) {
3481 PyErr_NoMemory();
3482 goto exit;
3483 }
3484 wcscpy(wnamebuf, po_wchars);
3485 if (len > 0) {
3486 wchar_t wch = wnamebuf[len-1];
3487 if (wch != SEP && wch != ALTSEP && wch != L':')
3488 wnamebuf[len++] = SEP;
3489 wcscpy(wnamebuf + len, L"*.*");
3490 }
3491 if ((list = PyList_New(0)) == NULL) {
3492 goto exit;
3493 }
3494 Py_BEGIN_ALLOW_THREADS
3495 hFindFile = FindFirstFileW(wnamebuf, &wFileData);
3496 Py_END_ALLOW_THREADS
3497 if (hFindFile == INVALID_HANDLE_VALUE) {
3498 int error = GetLastError();
3499 if (error == ERROR_FILE_NOT_FOUND)
3500 goto exit;
3501 Py_DECREF(list);
3502 list = path_error(path);
3503 goto exit;
3504 }
3505 do {
3506 /* Skip over . and .. */
3507 if (wcscmp(wFileData.cFileName, L".") != 0 &&
3508 wcscmp(wFileData.cFileName, L"..") != 0) {
3509 v = PyUnicode_FromWideChar(wFileData.cFileName,
3510 wcslen(wFileData.cFileName));
3511 if (path->narrow && v) {
3512 Py_SETREF(v, PyUnicode_EncodeFSDefault(v));
3513 }
3514 if (v == NULL) {
3515 Py_DECREF(list);
3516 list = NULL;
3517 break;
3518 }
3519 if (PyList_Append(list, v) != 0) {
3520 Py_DECREF(v);
3521 Py_DECREF(list);
3522 list = NULL;
3523 break;
3524 }
3525 Py_DECREF(v);
3526 }
3527 Py_BEGIN_ALLOW_THREADS
3528 result = FindNextFileW(hFindFile, &wFileData);
3529 Py_END_ALLOW_THREADS
3530 /* FindNextFile sets error to ERROR_NO_MORE_FILES if
3531 it got to the end of the directory. */
3532 if (!result && GetLastError() != ERROR_NO_MORE_FILES) {
3533 Py_DECREF(list);
3534 list = path_error(path);
3535 goto exit;
3536 }
3537 } while (result == TRUE);
3538
3539exit:
3540 if (hFindFile != INVALID_HANDLE_VALUE) {
3541 if (FindClose(hFindFile) == FALSE) {
3542 if (list != NULL) {
3543 Py_DECREF(list);
3544 list = path_error(path);
3545 }
3546 }
3547 }
3548 PyMem_Free(wnamebuf);
3549
3550 return list;
3551} /* end of _listdir_windows_no_opendir */
3552
3553#else /* thus POSIX, ie: not (MS_WINDOWS and not HAVE_OPENDIR) */
3554
3555static PyObject *
3556_posix_listdir(path_t *path, PyObject *list)
3557{
3558 PyObject *v;
3559 DIR *dirp = NULL;
3560 struct dirent *ep;
3561 int return_str; /* if false, return bytes */
3562#ifdef HAVE_FDOPENDIR
3563 int fd = -1;
3564#endif
3565
3566 errno = 0;
3567#ifdef HAVE_FDOPENDIR
3568 if (path->fd != -1) {
3569 /* closedir() closes the FD, so we duplicate it */
3570 fd = _Py_dup(path->fd);
3571 if (fd == -1)
3572 return NULL;
3573
3574 return_str = 1;
3575
3576 Py_BEGIN_ALLOW_THREADS
3577 dirp = fdopendir(fd);
3578 Py_END_ALLOW_THREADS
3579 }
3580 else
3581#endif
3582 {
3583 const char *name;
3584 if (path->narrow) {
3585 name = path->narrow;
3586 /* only return bytes if they specified a bytes-like object */
3587 return_str = !PyObject_CheckBuffer(path->object);
3588 }
3589 else {
3590 name = ".";
3591 return_str = 1;
3592 }
3593
3594 Py_BEGIN_ALLOW_THREADS
3595 dirp = opendir(name);
3596 Py_END_ALLOW_THREADS
3597 }
3598
3599 if (dirp == NULL) {
3600 list = path_error(path);
3601#ifdef HAVE_FDOPENDIR
3602 if (fd != -1) {
3603 Py_BEGIN_ALLOW_THREADS
3604 close(fd);
3605 Py_END_ALLOW_THREADS
3606 }
3607#endif
3608 goto exit;
3609 }
3610 if ((list = PyList_New(0)) == NULL) {
3611 goto exit;
3612 }
3613 for (;;) {
3614 errno = 0;
3615 Py_BEGIN_ALLOW_THREADS
3616 ep = readdir(dirp);
3617 Py_END_ALLOW_THREADS
3618 if (ep == NULL) {
3619 if (errno == 0) {
3620 break;
3621 } else {
3622 Py_DECREF(list);
3623 list = path_error(path);
3624 goto exit;
3625 }
3626 }
3627 if (ep->d_name[0] == '.' &&
3628 (NAMLEN(ep) == 1 ||
3629 (ep->d_name[1] == '.' && NAMLEN(ep) == 2)))
3630 continue;
3631 if (return_str)
3632 v = PyUnicode_DecodeFSDefaultAndSize(ep->d_name, NAMLEN(ep));
3633 else
3634 v = PyBytes_FromStringAndSize(ep->d_name, NAMLEN(ep));
3635 if (v == NULL) {
3636 Py_CLEAR(list);
3637 break;
3638 }
3639 if (PyList_Append(list, v) != 0) {
3640 Py_DECREF(v);
3641 Py_CLEAR(list);
3642 break;
3643 }
3644 Py_DECREF(v);
3645 }
3646
3647exit:
3648 if (dirp != NULL) {
3649 Py_BEGIN_ALLOW_THREADS
3650#ifdef HAVE_FDOPENDIR
3651 if (fd > -1)
3652 rewinddir(dirp);
3653#endif
3654 closedir(dirp);
3655 Py_END_ALLOW_THREADS
3656 }
3657
3658 return list;
3659} /* end of _posix_listdir */
3660#endif /* which OS */
3661
3662
3663/*[clinic input]
3664os.listdir
3665
3666 path : path_t(nullable=True, allow_fd='PATH_HAVE_FDOPENDIR') = None
3667
3668Return a list containing the names of the files in the directory.
3669
3670path can be specified as either str, bytes, or a path-like object. If path is bytes,
3671 the filenames returned will also be bytes; in all other circumstances
3672 the filenames returned will be str.
3673If path is None, uses the path='.'.
3674On some platforms, path may also be specified as an open file descriptor;\
3675 the file descriptor must refer to a directory.
3676 If this functionality is unavailable, using it raises NotImplementedError.
3677
3678The list is in arbitrary order. It does not include the special
3679entries '.' and '..' even if they are present in the directory.
3680
3681
3682[clinic start generated code]*/
3683
3684static PyObject *
3685os_listdir_impl(PyObject *module, path_t *path)
3686/*[clinic end generated code: output=293045673fcd1a75 input=e3f58030f538295d]*/
3687{
3688#if defined(MS_WINDOWS) && !defined(HAVE_OPENDIR)
3689 return _listdir_windows_no_opendir(path, NULL);
3690#else
3691 return _posix_listdir(path, NULL);
3692#endif
3693}
3694
3695#ifdef MS_WINDOWS
3696/* A helper function for abspath on win32 */
3697/*[clinic input]
3698os._getfullpathname
3699
3700 path: path_t
3701 /
3702
3703[clinic start generated code]*/
3704
3705static PyObject *
3706os__getfullpathname_impl(PyObject *module, path_t *path)
3707/*[clinic end generated code: output=bb8679d56845bc9b input=332ed537c29d0a3e]*/
3708{
3709 wchar_t woutbuf[MAX_PATH], *woutbufp = woutbuf;
3710 wchar_t *wtemp;
3711 DWORD result;
3712 PyObject *v;
3713
3714 result = GetFullPathNameW(path->wide,
3715 Py_ARRAY_LENGTH(woutbuf),
3716 woutbuf, &wtemp);
3717 if (result > Py_ARRAY_LENGTH(woutbuf)) {
3718 woutbufp = PyMem_New(wchar_t, result);
3719 if (!woutbufp)
3720 return PyErr_NoMemory();
3721 result = GetFullPathNameW(path->wide, result, woutbufp, &wtemp);
3722 }
3723 if (result) {
3724 v = PyUnicode_FromWideChar(woutbufp, wcslen(woutbufp));
3725 if (path->narrow)
3726 Py_SETREF(v, PyUnicode_EncodeFSDefault(v));
3727 } else
3728 v = win32_error_object("GetFullPathNameW", path->object);
3729 if (woutbufp != woutbuf)
3730 PyMem_Free(woutbufp);
3731 return v;
3732}
3733
3734
3735/*[clinic input]
3736os._getfinalpathname
3737
3738 path: path_t
3739 /
3740
3741A helper function for samepath on windows.
3742[clinic start generated code]*/
3743
3744static PyObject *
3745os__getfinalpathname_impl(PyObject *module, path_t *path)
3746/*[clinic end generated code: output=621a3c79bc29ebfa input=2b6b6c7cbad5fb84]*/
3747{
3748 HANDLE hFile;
3749 wchar_t buf[MAXPATHLEN], *target_path = buf;
3750 int buf_size = Py_ARRAY_LENGTH(buf);
3751 int result_length;
3752 PyObject *result;
3753
3754 Py_BEGIN_ALLOW_THREADS
3755 hFile = CreateFileW(
3756 path->wide,
3757 0, /* desired access */
3758 0, /* share mode */
3759 NULL, /* security attributes */
3760 OPEN_EXISTING,
3761 /* FILE_FLAG_BACKUP_SEMANTICS is required to open a directory */
3762 FILE_FLAG_BACKUP_SEMANTICS,
3763 NULL);
3764 Py_END_ALLOW_THREADS
3765
3766 if (hFile == INVALID_HANDLE_VALUE) {
3767 return win32_error_object("CreateFileW", path->object);
3768 }
3769
3770 /* We have a good handle to the target, use it to determine the
3771 target path name. */
3772 while (1) {
3773 Py_BEGIN_ALLOW_THREADS
3774 result_length = GetFinalPathNameByHandleW(hFile, target_path,
3775 buf_size, VOLUME_NAME_DOS);
3776 Py_END_ALLOW_THREADS
3777
3778 if (!result_length) {
3779 result = win32_error_object("GetFinalPathNameByHandleW",
3780 path->object);
3781 goto cleanup;
3782 }
3783
3784 if (result_length < buf_size) {
3785 break;
3786 }
3787
3788 wchar_t *tmp;
3789 tmp = PyMem_Realloc(target_path != buf ? target_path : NULL,
3790 result_length * sizeof(*tmp));
3791 if (!tmp) {
3792 result = PyErr_NoMemory();
3793 goto cleanup;
3794 }
3795
3796 buf_size = result_length;
3797 target_path = tmp;
3798 }
3799
3800 result = PyUnicode_FromWideChar(target_path, result_length);
3801 if (path->narrow)
3802 Py_SETREF(result, PyUnicode_EncodeFSDefault(result));
3803
3804cleanup:
3805 if (target_path != buf) {
3806 PyMem_Free(target_path);
3807 }
3808 CloseHandle(hFile);
3809 return result;
3810}
3811
3812/*[clinic input]
3813os._isdir
3814
3815 path: path_t
3816 /
3817
3818Return true if the pathname refers to an existing directory.
3819[clinic start generated code]*/
3820
3821static PyObject *
3822os__isdir_impl(PyObject *module, path_t *path)
3823/*[clinic end generated code: output=75f56f32720836cb input=5e0800149c0ad95f]*/
3824{
3825 DWORD attributes;
3826
3827 Py_BEGIN_ALLOW_THREADS
3828 attributes = GetFileAttributesW(path->wide);
3829 Py_END_ALLOW_THREADS
3830
3831 if (attributes == INVALID_FILE_ATTRIBUTES)
3832 Py_RETURN_FALSE;
3833
3834 if (attributes & FILE_ATTRIBUTE_DIRECTORY)
3835 Py_RETURN_TRUE;
3836 else
3837 Py_RETURN_FALSE;
3838}
3839
3840
3841/*[clinic input]
3842os._getvolumepathname
3843
3844 path: path_t
3845
3846A helper function for ismount on Win32.
3847[clinic start generated code]*/
3848
3849static PyObject *
3850os__getvolumepathname_impl(PyObject *module, path_t *path)
3851/*[clinic end generated code: output=804c63fd13a1330b input=722b40565fa21552]*/
3852{
3853 PyObject *result;
3854 wchar_t *mountpath=NULL;
3855 size_t buflen;
3856 BOOL ret;
3857
3858 /* Volume path should be shorter than entire path */
3859 buflen = Py_MAX(path->length, MAX_PATH);
3860
3861 if (buflen > PY_DWORD_MAX) {
3862 PyErr_SetString(PyExc_OverflowError, "path too long");
3863 return NULL;
3864 }
3865
3866 mountpath = PyMem_New(wchar_t, buflen);
3867 if (mountpath == NULL)
3868 return PyErr_NoMemory();
3869
3870 Py_BEGIN_ALLOW_THREADS
3871 ret = GetVolumePathNameW(path->wide, mountpath,
3872 Py_SAFE_DOWNCAST(buflen, size_t, DWORD));
3873 Py_END_ALLOW_THREADS
3874
3875 if (!ret) {
3876 result = win32_error_object("_getvolumepathname", path->object);
3877 goto exit;
3878 }
3879 result = PyUnicode_FromWideChar(mountpath, wcslen(mountpath));
3880 if (path->narrow)
3881 Py_SETREF(result, PyUnicode_EncodeFSDefault(result));
3882
3883exit:
3884 PyMem_Free(mountpath);
3885 return result;
3886}
3887
3888#endif /* MS_WINDOWS */
3889
3890
3891/*[clinic input]
3892os.mkdir
3893
3894 path : path_t
3895
3896 mode: int = 0o777
3897
3898 *
3899
3900 dir_fd : dir_fd(requires='mkdirat') = None
3901
3902# "mkdir(path, mode=0o777, *, dir_fd=None)\n\n\
3903
3904Create a directory.
3905
3906If dir_fd is not None, it should be a file descriptor open to a directory,
3907 and path should be relative; path will then be relative to that directory.
3908dir_fd may not be implemented on your platform.
3909 If it is unavailable, using it will raise a NotImplementedError.
3910
3911The mode argument is ignored on Windows.
3912[clinic start generated code]*/
3913
3914static PyObject *
3915os_mkdir_impl(PyObject *module, path_t *path, int mode, int dir_fd)
3916/*[clinic end generated code: output=a70446903abe821f input=e965f68377e9b1ce]*/
3917{
3918 int result;
3919
3920#ifdef MS_WINDOWS
3921 Py_BEGIN_ALLOW_THREADS
3922 result = CreateDirectoryW(path->wide, NULL);
3923 Py_END_ALLOW_THREADS
3924
3925 if (!result)
3926 return path_error(path);
3927#else
3928 Py_BEGIN_ALLOW_THREADS
3929#if HAVE_MKDIRAT
3930 if (dir_fd != DEFAULT_DIR_FD)
3931 result = mkdirat(dir_fd, path->narrow, mode);
3932 else
3933#endif
3934#if defined(__WATCOMC__) && !defined(__QNX__)
3935 result = mkdir(path->narrow);
3936#else
3937 result = mkdir(path->narrow, mode);
3938#endif
3939 Py_END_ALLOW_THREADS
3940 if (result < 0)
3941 return path_error(path);
3942#endif /* MS_WINDOWS */
3943 Py_RETURN_NONE;
3944}
3945
3946
3947/* sys/resource.h is needed for at least: wait3(), wait4(), broken nice. */
3948#if defined(HAVE_SYS_RESOURCE_H)
3949#include <sys/resource.h>
3950#endif
3951
3952
3953#ifdef HAVE_NICE
3954/*[clinic input]
3955os.nice
3956
3957 increment: int
3958 /
3959
3960Add increment to the priority of process and return the new priority.
3961[clinic start generated code]*/
3962
3963static PyObject *
3964os_nice_impl(PyObject *module, int increment)
3965/*[clinic end generated code: output=9dad8a9da8109943 input=864be2d402a21da2]*/
3966{
3967 int value;
3968
3969 /* There are two flavours of 'nice': one that returns the new
3970 priority (as required by almost all standards out there) and the
3971 Linux/FreeBSD one, which returns '0' on success and advices
3972 the use of getpriority() to get the new priority.
3973
3974 If we are of the nice family that returns the new priority, we
3975 need to clear errno before the call, and check if errno is filled
3976 before calling posix_error() on a returnvalue of -1, because the
3977 -1 may be the actual new priority! */
3978
3979 errno = 0;
3980 value = nice(increment);
3981#if defined(HAVE_BROKEN_NICE) && defined(HAVE_GETPRIORITY)
3982 if (value == 0)
3983 value = getpriority(PRIO_PROCESS, 0);
3984#endif
3985 if (value == -1 && errno != 0)
3986 /* either nice() or getpriority() returned an error */
3987 return posix_error();
3988 return PyLong_FromLong((long) value);
3989}
3990#endif /* HAVE_NICE */
3991
3992
3993#ifdef HAVE_GETPRIORITY
3994/*[clinic input]
3995os.getpriority
3996
3997 which: int
3998 who: int
3999
4000Return program scheduling priority.
4001[clinic start generated code]*/
4002
4003static PyObject *
4004os_getpriority_impl(PyObject *module, int which, int who)
4005/*[clinic end generated code: output=c41b7b63c7420228 input=9be615d40e2544ef]*/
4006{
4007 int retval;
4008
4009 errno = 0;
4010 retval = getpriority(which, who);
4011 if (errno != 0)
4012 return posix_error();
4013 return PyLong_FromLong((long)retval);
4014}
4015#endif /* HAVE_GETPRIORITY */
4016
4017
4018#ifdef HAVE_SETPRIORITY
4019/*[clinic input]
4020os.setpriority
4021
4022 which: int
4023 who: int
4024 priority: int
4025
4026Set program scheduling priority.
4027[clinic start generated code]*/
4028
4029static PyObject *
4030os_setpriority_impl(PyObject *module, int which, int who, int priority)
4031/*[clinic end generated code: output=3d910d95a7771eb2 input=710ccbf65b9dc513]*/
4032{
4033 int retval;
4034
4035 retval = setpriority(which, who, priority);
4036 if (retval == -1)
4037 return posix_error();
4038 Py_RETURN_NONE;
4039}
4040#endif /* HAVE_SETPRIORITY */
4041
4042
4043static PyObject *
4044internal_rename(path_t *src, path_t *dst, int src_dir_fd, int dst_dir_fd, int is_replace)
4045{
4046 const char *function_name = is_replace ? "replace" : "rename";
4047 int dir_fd_specified;
4048
4049#ifdef MS_WINDOWS
4050 BOOL result;
4051 int flags = is_replace ? MOVEFILE_REPLACE_EXISTING : 0;
4052#else
4053 int result;
4054#endif
4055
4056 dir_fd_specified = (src_dir_fd != DEFAULT_DIR_FD) ||
4057 (dst_dir_fd != DEFAULT_DIR_FD);
4058#ifndef HAVE_RENAMEAT
4059 if (dir_fd_specified) {
4060 argument_unavailable_error(function_name, "src_dir_fd and dst_dir_fd");
4061 return NULL;
4062 }
4063#endif
4064
4065#ifdef MS_WINDOWS
4066 Py_BEGIN_ALLOW_THREADS
4067 result = MoveFileExW(src->wide, dst->wide, flags);
4068 Py_END_ALLOW_THREADS
4069
4070 if (!result)
4071 return path_error2(src, dst);
4072
4073#else
4074 if ((src->narrow && dst->wide) || (src->wide && dst->narrow)) {
4075 PyErr_Format(PyExc_ValueError,
4076 "%s: src and dst must be the same type", function_name);
4077 return NULL;
4078 }
4079
4080 Py_BEGIN_ALLOW_THREADS
4081#ifdef HAVE_RENAMEAT
4082 if (dir_fd_specified)
4083 result = renameat(src_dir_fd, src->narrow, dst_dir_fd, dst->narrow);
4084 else
4085#endif
4086 result = rename(src->narrow, dst->narrow);
4087 Py_END_ALLOW_THREADS
4088
4089 if (result)
4090 return path_error2(src, dst);
4091#endif
4092 Py_RETURN_NONE;
4093}
4094
4095
4096/*[clinic input]
4097os.rename
4098
4099 src : path_t
4100 dst : path_t
4101 *
4102 src_dir_fd : dir_fd = None
4103 dst_dir_fd : dir_fd = None
4104
4105Rename a file or directory.
4106
4107If either src_dir_fd or dst_dir_fd is not None, it should be a file
4108 descriptor open to a directory, and the respective path string (src or dst)
4109 should be relative; the path will then be relative to that directory.
4110src_dir_fd and dst_dir_fd, may not be implemented on your platform.
4111 If they are unavailable, using them will raise a NotImplementedError.
4112[clinic start generated code]*/
4113
4114static PyObject *
4115os_rename_impl(PyObject *module, path_t *src, path_t *dst, int src_dir_fd,
4116 int dst_dir_fd)
4117/*[clinic end generated code: output=59e803072cf41230 input=faa61c847912c850]*/
4118{
4119 return internal_rename(src, dst, src_dir_fd, dst_dir_fd, 0);
4120}
4121
4122
4123/*[clinic input]
4124os.replace = os.rename
4125
4126Rename a file or directory, overwriting the destination.
4127
4128If either src_dir_fd or dst_dir_fd is not None, it should be a file
4129 descriptor open to a directory, and the respective path string (src or dst)
4130 should be relative; the path will then be relative to that directory.
4131src_dir_fd and dst_dir_fd, may not be implemented on your platform.
4132 If they are unavailable, using them will raise a NotImplementedError.
4133[clinic start generated code]*/
4134
4135static PyObject *
4136os_replace_impl(PyObject *module, path_t *src, path_t *dst, int src_dir_fd,
4137 int dst_dir_fd)
4138/*[clinic end generated code: output=1968c02e7857422b input=c003f0def43378ef]*/
4139{
4140 return internal_rename(src, dst, src_dir_fd, dst_dir_fd, 1);
4141}
4142
4143
4144/*[clinic input]
4145os.rmdir
4146
4147 path: path_t
4148 *
4149 dir_fd: dir_fd(requires='unlinkat') = None
4150
4151Remove a directory.
4152
4153If dir_fd is not None, it should be a file descriptor open to a directory,
4154 and path should be relative; path will then be relative to that directory.
4155dir_fd may not be implemented on your platform.
4156 If it is unavailable, using it will raise a NotImplementedError.
4157[clinic start generated code]*/
4158
4159static PyObject *
4160os_rmdir_impl(PyObject *module, path_t *path, int dir_fd)
4161/*[clinic end generated code: output=080eb54f506e8301 input=38c8b375ca34a7e2]*/
4162{
4163 int result;
4164
4165 Py_BEGIN_ALLOW_THREADS
4166#ifdef MS_WINDOWS
4167 /* Windows, success=1, UNIX, success=0 */
4168 result = !RemoveDirectoryW(path->wide);
4169#else
4170#ifdef HAVE_UNLINKAT
4171 if (dir_fd != DEFAULT_DIR_FD)
4172 result = unlinkat(dir_fd, path->narrow, AT_REMOVEDIR);
4173 else
4174#endif
4175 result = rmdir(path->narrow);
4176#endif
4177 Py_END_ALLOW_THREADS
4178
4179 if (result)
4180 return path_error(path);
4181
4182 Py_RETURN_NONE;
4183}
4184
4185
4186#ifdef HAVE_SYSTEM
4187#ifdef MS_WINDOWS
4188/*[clinic input]
4189os.system -> long
4190
4191 command: Py_UNICODE
4192
4193Execute the command in a subshell.
4194[clinic start generated code]*/
4195
4196static long
4197os_system_impl(PyObject *module, const Py_UNICODE *command)
4198/*[clinic end generated code: output=5b7c3599c068ca42 input=303f5ce97df606b0]*/
4199{
4200 long result;
4201 Py_BEGIN_ALLOW_THREADS
4202 _Py_BEGIN_SUPPRESS_IPH
4203 result = _wsystem(command);
4204 _Py_END_SUPPRESS_IPH
4205 Py_END_ALLOW_THREADS
4206 return result;
4207}
4208#else /* MS_WINDOWS */
4209/*[clinic input]
4210os.system -> long
4211
4212 command: FSConverter
4213
4214Execute the command in a subshell.
4215[clinic start generated code]*/
4216
4217static long
4218os_system_impl(PyObject *module, PyObject *command)
4219/*[clinic end generated code: output=290fc437dd4f33a0 input=86a58554ba6094af]*/
4220{
4221 long result;
4222 const char *bytes = PyBytes_AsString(command);
4223 Py_BEGIN_ALLOW_THREADS
4224 result = system(bytes);
4225 Py_END_ALLOW_THREADS
4226 return result;
4227}
4228#endif
4229#endif /* HAVE_SYSTEM */
4230
4231
4232/*[clinic input]
4233os.umask
4234
4235 mask: int
4236 /
4237
4238Set the current numeric umask and return the previous umask.
4239[clinic start generated code]*/
4240
4241static PyObject *
4242os_umask_impl(PyObject *module, int mask)
4243/*[clinic end generated code: output=a2e33ce3bc1a6e33 input=ab6bfd9b24d8a7e8]*/
4244{
4245 int i = (int)umask(mask);
4246 if (i < 0)
4247 return posix_error();
4248 return PyLong_FromLong((long)i);
4249}
4250
4251#ifdef MS_WINDOWS
4252
4253/* override the default DeleteFileW behavior so that directory
4254symlinks can be removed with this function, the same as with
4255Unix symlinks */
4256BOOL WINAPI Py_DeleteFileW(LPCWSTR lpFileName)
4257{
4258 WIN32_FILE_ATTRIBUTE_DATA info;
4259 WIN32_FIND_DATAW find_data;
4260 HANDLE find_data_handle;
4261 int is_directory = 0;
4262 int is_link = 0;
4263
4264 if (GetFileAttributesExW(lpFileName, GetFileExInfoStandard, &info)) {
4265 is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
4266
4267 /* Get WIN32_FIND_DATA structure for the path to determine if
4268 it is a symlink */
4269 if(is_directory &&
4270 info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
4271 find_data_handle = FindFirstFileW(lpFileName, &find_data);
4272
4273 if(find_data_handle != INVALID_HANDLE_VALUE) {
4274 /* IO_REPARSE_TAG_SYMLINK if it is a symlink and
4275 IO_REPARSE_TAG_MOUNT_POINT if it is a junction point. */
4276 is_link = find_data.dwReserved0 == IO_REPARSE_TAG_SYMLINK ||
4277 find_data.dwReserved0 == IO_REPARSE_TAG_MOUNT_POINT;
4278 FindClose(find_data_handle);
4279 }
4280 }
4281 }
4282
4283 if (is_directory && is_link)
4284 return RemoveDirectoryW(lpFileName);
4285
4286 return DeleteFileW(lpFileName);
4287}
4288#endif /* MS_WINDOWS */
4289
4290
4291/*[clinic input]
4292os.unlink
4293
4294 path: path_t
4295 *
4296 dir_fd: dir_fd(requires='unlinkat')=None
4297
4298Remove a file (same as remove()).
4299
4300If dir_fd is not None, it should be a file descriptor open to a directory,
4301 and path should be relative; path will then be relative to that directory.
4302dir_fd may not be implemented on your platform.
4303 If it is unavailable, using it will raise a NotImplementedError.
4304
4305[clinic start generated code]*/
4306
4307static PyObject *
4308os_unlink_impl(PyObject *module, path_t *path, int dir_fd)
4309/*[clinic end generated code: output=621797807b9963b1 input=d7bcde2b1b2a2552]*/
4310{
4311 int result;
4312
4313 Py_BEGIN_ALLOW_THREADS
4314 _Py_BEGIN_SUPPRESS_IPH
4315#ifdef MS_WINDOWS
4316 /* Windows, success=1, UNIX, success=0 */
4317 result = !Py_DeleteFileW(path->wide);
4318#else
4319#ifdef HAVE_UNLINKAT
4320 if (dir_fd != DEFAULT_DIR_FD)
4321 result = unlinkat(dir_fd, path->narrow, 0);
4322 else
4323#endif /* HAVE_UNLINKAT */
4324 result = unlink(path->narrow);
4325#endif
4326 _Py_END_SUPPRESS_IPH
4327 Py_END_ALLOW_THREADS
4328
4329 if (result)
4330 return path_error(path);
4331
4332 Py_RETURN_NONE;
4333}
4334
4335
4336/*[clinic input]
4337os.remove = os.unlink
4338
4339Remove a file (same as unlink()).
4340
4341If dir_fd is not None, it should be a file descriptor open to a directory,
4342 and path should be relative; path will then be relative to that directory.
4343dir_fd may not be implemented on your platform.
4344 If it is unavailable, using it will raise a NotImplementedError.
4345[clinic start generated code]*/
4346
4347static PyObject *
4348os_remove_impl(PyObject *module, path_t *path, int dir_fd)
4349/*[clinic end generated code: output=a8535b28f0068883 input=e05c5ab55cd30983]*/
4350{
4351 return os_unlink_impl(module, path, dir_fd);
4352}
4353
4354
4355static PyStructSequence_Field uname_result_fields[] = {
4356 {"sysname", "operating system name"},
4357 {"nodename", "name of machine on network (implementation-defined)"},
4358 {"release", "operating system release"},
4359 {"version", "operating system version"},
4360 {"machine", "hardware identifier"},
4361 {NULL}
4362};
4363
4364PyDoc_STRVAR(uname_result__doc__,
4365"uname_result: Result from os.uname().\n\n\
4366This object may be accessed either as a tuple of\n\
4367 (sysname, nodename, release, version, machine),\n\
4368or via the attributes sysname, nodename, release, version, and machine.\n\
4369\n\
4370See os.uname for more information.");
4371
4372static PyStructSequence_Desc uname_result_desc = {
4373 "uname_result", /* name */
4374 uname_result__doc__, /* doc */
4375 uname_result_fields,
4376 5
4377};
4378
4379static PyTypeObject UnameResultType;
4380
4381
4382#ifdef HAVE_UNAME
4383/*[clinic input]
4384os.uname
4385
4386Return an object identifying the current operating system.
4387
4388The object behaves like a named tuple with the following fields:
4389 (sysname, nodename, release, version, machine)
4390
4391[clinic start generated code]*/
4392
4393static PyObject *
4394os_uname_impl(PyObject *module)
4395/*[clinic end generated code: output=e6a49cf1a1508a19 input=e68bd246db3043ed]*/
4396{
4397 struct utsname u;
4398 int res;
4399 PyObject *value;
4400
4401 Py_BEGIN_ALLOW_THREADS
4402 res = uname(&u);
4403 Py_END_ALLOW_THREADS
4404 if (res < 0)
4405 return posix_error();
4406
4407 value = PyStructSequence_New(&UnameResultType);
4408 if (value == NULL)
4409 return NULL;
4410
4411#define SET(i, field) \
4412 { \
4413 PyObject *o = PyUnicode_DecodeFSDefault(field); \
4414 if (!o) { \
4415 Py_DECREF(value); \
4416 return NULL; \
4417 } \
4418 PyStructSequence_SET_ITEM(value, i, o); \
4419 } \
4420
4421 SET(0, u.sysname);
4422 SET(1, u.nodename);
4423 SET(2, u.release);
4424 SET(3, u.version);
4425 SET(4, u.machine);
4426
4427#undef SET
4428
4429 return value;
4430}
4431#endif /* HAVE_UNAME */
4432
4433
4434
4435typedef struct {
4436 int now;
4437 time_t atime_s;
4438 long atime_ns;
4439 time_t mtime_s;
4440 long mtime_ns;
4441} utime_t;
4442
4443/*
4444 * these macros assume that "ut" is a pointer to a utime_t
4445 * they also intentionally leak the declaration of a pointer named "time"
4446 */
4447#define UTIME_TO_TIMESPEC \
4448 struct timespec ts[2]; \
4449 struct timespec *time; \
4450 if (ut->now) \
4451 time = NULL; \
4452 else { \
4453 ts[0].tv_sec = ut->atime_s; \
4454 ts[0].tv_nsec = ut->atime_ns; \
4455 ts[1].tv_sec = ut->mtime_s; \
4456 ts[1].tv_nsec = ut->mtime_ns; \
4457 time = ts; \
4458 } \
4459
4460#define UTIME_TO_TIMEVAL \
4461 struct timeval tv[2]; \
4462 struct timeval *time; \
4463 if (ut->now) \
4464 time = NULL; \
4465 else { \
4466 tv[0].tv_sec = ut->atime_s; \
4467 tv[0].tv_usec = ut->atime_ns / 1000; \
4468 tv[1].tv_sec = ut->mtime_s; \
4469 tv[1].tv_usec = ut->mtime_ns / 1000; \
4470 time = tv; \
4471 } \
4472
4473#define UTIME_TO_UTIMBUF \
4474 struct utimbuf u; \
4475 struct utimbuf *time; \
4476 if (ut->now) \
4477 time = NULL; \
4478 else { \
4479 u.actime = ut->atime_s; \
4480 u.modtime = ut->mtime_s; \
4481 time = &u; \
4482 }
4483
4484#define UTIME_TO_TIME_T \
4485 time_t timet[2]; \
4486 time_t *time; \
4487 if (ut->now) \
4488 time = NULL; \
4489 else { \
4490 timet[0] = ut->atime_s; \
4491 timet[1] = ut->mtime_s; \
4492 time = timet; \
4493 } \
4494
4495
4496#if defined(HAVE_FUTIMESAT) || defined(HAVE_UTIMENSAT)
4497
4498static int
4499utime_dir_fd(utime_t *ut, int dir_fd, const char *path, int follow_symlinks)
4500{
4501#ifdef HAVE_UTIMENSAT
4502 int flags = follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW;
4503 UTIME_TO_TIMESPEC;
4504 return utimensat(dir_fd, path, time, flags);
4505#elif defined(HAVE_FUTIMESAT)
4506 UTIME_TO_TIMEVAL;
4507 /*
4508 * follow_symlinks will never be false here;
4509 * we only allow !follow_symlinks and dir_fd together
4510 * if we have utimensat()
4511 */
4512 assert(follow_symlinks);
4513 return futimesat(dir_fd, path, time);
4514#endif
4515}
4516
4517 #define FUTIMENSAT_DIR_FD_CONVERTER dir_fd_converter
4518#else
4519 #define FUTIMENSAT_DIR_FD_CONVERTER dir_fd_unavailable
4520#endif
4521
4522#if defined(HAVE_FUTIMES) || defined(HAVE_FUTIMENS)
4523
4524static int
4525utime_fd(utime_t *ut, int fd)
4526{
4527#ifdef HAVE_FUTIMENS
4528 UTIME_TO_TIMESPEC;
4529 return futimens(fd, time);
4530#else
4531 UTIME_TO_TIMEVAL;
4532 return futimes(fd, time);
4533#endif
4534}
4535
4536 #define PATH_UTIME_HAVE_FD 1
4537#else
4538 #define PATH_UTIME_HAVE_FD 0
4539#endif
4540
4541#if defined(HAVE_UTIMENSAT) || defined(HAVE_LUTIMES)
4542# define UTIME_HAVE_NOFOLLOW_SYMLINKS
4543#endif
4544
4545#ifdef UTIME_HAVE_NOFOLLOW_SYMLINKS
4546
4547static int
4548utime_nofollow_symlinks(utime_t *ut, const char *path)
4549{
4550#ifdef HAVE_UTIMENSAT
4551 UTIME_TO_TIMESPEC;
4552 return utimensat(DEFAULT_DIR_FD, path, time, AT_SYMLINK_NOFOLLOW);
4553#else
4554 UTIME_TO_TIMEVAL;
4555 return lutimes(path, time);
4556#endif
4557}
4558
4559#endif
4560
4561#ifndef MS_WINDOWS
4562
4563static int
4564utime_default(utime_t *ut, const char *path)
4565{
4566#ifdef HAVE_UTIMENSAT
4567 UTIME_TO_TIMESPEC;
4568 return utimensat(DEFAULT_DIR_FD, path, time, 0);
4569#elif defined(HAVE_UTIMES)
4570 UTIME_TO_TIMEVAL;
4571 return utimes(path, time);
4572#elif defined(HAVE_UTIME_H)
4573 UTIME_TO_UTIMBUF;
4574 return utime(path, time);
4575#else
4576 UTIME_TO_TIME_T;
4577 return utime(path, time);
4578#endif
4579}
4580
4581#endif
4582
4583static int
4584split_py_long_to_s_and_ns(PyObject *py_long, time_t *s, long *ns)
4585{
4586 int result = 0;
4587 PyObject *divmod;
4588 divmod = PyNumber_Divmod(py_long, billion);
4589 if (!divmod)
4590 goto exit;
4591 if (!PyTuple_Check(divmod) || PyTuple_GET_SIZE(divmod) != 2) {
4592 PyErr_Format(PyExc_TypeError,
4593 "%.200s.__divmod__() must return a 2-tuple, not %.200s",
4594 Py_TYPE(py_long)->tp_name, Py_TYPE(divmod)->tp_name);
4595 goto exit;
4596 }
4597 *s = _PyLong_AsTime_t(PyTuple_GET_ITEM(divmod, 0));
4598 if ((*s == -1) && PyErr_Occurred())
4599 goto exit;
4600 *ns = PyLong_AsLong(PyTuple_GET_ITEM(divmod, 1));
4601 if ((*ns == -1) && PyErr_Occurred())
4602 goto exit;
4603
4604 result = 1;
4605exit:
4606 Py_XDECREF(divmod);
4607 return result;
4608}
4609
4610
4611/*[clinic input]
4612os.utime
4613
4614 path: path_t(allow_fd='PATH_UTIME_HAVE_FD')
4615 times: object = NULL
4616 *
4617 ns: object = NULL
4618 dir_fd: dir_fd(requires='futimensat') = None
4619 follow_symlinks: bool=True
4620
4621# "utime(path, times=None, *[, ns], dir_fd=None, follow_symlinks=True)\n\
4622
4623Set the access and modified time of path.
4624
4625path may always be specified as a string.
4626On some platforms, path may also be specified as an open file descriptor.
4627 If this functionality is unavailable, using it raises an exception.
4628
4629If times is not None, it must be a tuple (atime, mtime);
4630 atime and mtime should be expressed as float seconds since the epoch.
4631If ns is specified, it must be a tuple (atime_ns, mtime_ns);
4632 atime_ns and mtime_ns should be expressed as integer nanoseconds
4633 since the epoch.
4634If times is None and ns is unspecified, utime uses the current time.
4635Specifying tuples for both times and ns is an error.
4636
4637If dir_fd is not None, it should be a file descriptor open to a directory,
4638 and path should be relative; path will then be relative to that directory.
4639If follow_symlinks is False, and the last element of the path is a symbolic
4640 link, utime will modify the symbolic link itself instead of the file the
4641 link points to.
4642It is an error to use dir_fd or follow_symlinks when specifying path
4643 as an open file descriptor.
4644dir_fd and follow_symlinks may not be available on your platform.
4645 If they are unavailable, using them will raise a NotImplementedError.
4646
4647[clinic start generated code]*/
4648
4649static PyObject *
4650os_utime_impl(PyObject *module, path_t *path, PyObject *times, PyObject *ns,
4651 int dir_fd, int follow_symlinks)
4652/*[clinic end generated code: output=cfcac69d027b82cf input=081cdc54ca685385]*/
4653{
4654#ifdef MS_WINDOWS
4655 HANDLE hFile;
4656 FILETIME atime, mtime;
4657#else
4658 int result;
4659#endif
4660
4661 utime_t utime;
4662
4663 memset(&utime, 0, sizeof(utime_t));
4664
4665 if (times && (times != Py_None) && ns) {
4666 PyErr_SetString(PyExc_ValueError,
4667 "utime: you may specify either 'times'"
4668 " or 'ns' but not both");
4669 return NULL;
4670 }
4671
4672 if (times && (times != Py_None)) {
4673 time_t a_sec, m_sec;
4674 long a_nsec, m_nsec;
4675 if (!PyTuple_CheckExact(times) || (PyTuple_Size(times) != 2)) {
4676 PyErr_SetString(PyExc_TypeError,
4677 "utime: 'times' must be either"
4678 " a tuple of two ints or None");
4679 return NULL;
4680 }
4681 utime.now = 0;
4682 if (_PyTime_ObjectToTimespec(PyTuple_GET_ITEM(times, 0),
4683 &a_sec, &a_nsec, _PyTime_ROUND_FLOOR) == -1 ||
4684 _PyTime_ObjectToTimespec(PyTuple_GET_ITEM(times, 1),
4685 &m_sec, &m_nsec, _PyTime_ROUND_FLOOR) == -1) {
4686 return NULL;
4687 }
4688 utime.atime_s = a_sec;
4689 utime.atime_ns = a_nsec;
4690 utime.mtime_s = m_sec;
4691 utime.mtime_ns = m_nsec;
4692 }
4693 else if (ns) {
4694 if (!PyTuple_CheckExact(ns) || (PyTuple_Size(ns) != 2)) {
4695 PyErr_SetString(PyExc_TypeError,
4696 "utime: 'ns' must be a tuple of two ints");
4697 return NULL;
4698 }
4699 utime.now = 0;
4700 if (!split_py_long_to_s_and_ns(PyTuple_GET_ITEM(ns, 0),
4701 &utime.atime_s, &utime.atime_ns) ||
4702 !split_py_long_to_s_and_ns(PyTuple_GET_ITEM(ns, 1),
4703 &utime.mtime_s, &utime.mtime_ns)) {
4704 return NULL;
4705 }
4706 }
4707 else {
4708 /* times and ns are both None/unspecified. use "now". */
4709 utime.now = 1;
4710 }
4711
4712#if !defined(UTIME_HAVE_NOFOLLOW_SYMLINKS)
4713 if (follow_symlinks_specified("utime", follow_symlinks))
4714 return NULL;
4715#endif
4716
4717 if (path_and_dir_fd_invalid("utime", path, dir_fd) ||
4718 dir_fd_and_fd_invalid("utime", dir_fd, path->fd) ||
4719 fd_and_follow_symlinks_invalid("utime", path->fd, follow_symlinks))
4720 return NULL;
4721
4722#if !defined(HAVE_UTIMENSAT)
4723 if ((dir_fd != DEFAULT_DIR_FD) && (!follow_symlinks)) {
4724 PyErr_SetString(PyExc_ValueError,
4725 "utime: cannot use dir_fd and follow_symlinks "
4726 "together on this platform");
4727 return NULL;
4728 }
4729#endif
4730
4731#ifdef MS_WINDOWS
4732 Py_BEGIN_ALLOW_THREADS
4733 hFile = CreateFileW(path->wide, FILE_WRITE_ATTRIBUTES, 0,
4734 NULL, OPEN_EXISTING,
4735 FILE_FLAG_BACKUP_SEMANTICS, NULL);
4736 Py_END_ALLOW_THREADS
4737 if (hFile == INVALID_HANDLE_VALUE) {
4738 path_error(path);
4739 return NULL;
4740 }
4741
4742 if (utime.now) {
4743 GetSystemTimeAsFileTime(&mtime);
4744 atime = mtime;
4745 }
4746 else {
4747 _Py_time_t_to_FILE_TIME(utime.atime_s, utime.atime_ns, &atime);
4748 _Py_time_t_to_FILE_TIME(utime.mtime_s, utime.mtime_ns, &mtime);
4749 }
4750 if (!SetFileTime(hFile, NULL, &atime, &mtime)) {
4751 /* Avoid putting the file name into the error here,
4752 as that may confuse the user into believing that
4753 something is wrong with the file, when it also
4754 could be the time stamp that gives a problem. */
4755 PyErr_SetFromWindowsErr(0);
4756 CloseHandle(hFile);
4757 return NULL;
4758 }
4759 CloseHandle(hFile);
4760#else /* MS_WINDOWS */
4761 Py_BEGIN_ALLOW_THREADS
4762
4763#ifdef UTIME_HAVE_NOFOLLOW_SYMLINKS
4764 if ((!follow_symlinks) && (dir_fd == DEFAULT_DIR_FD))
4765 result = utime_nofollow_symlinks(&utime, path->narrow);
4766 else
4767#endif
4768
4769#if defined(HAVE_FUTIMESAT) || defined(HAVE_UTIMENSAT)
4770 if ((dir_fd != DEFAULT_DIR_FD) || (!follow_symlinks))
4771 result = utime_dir_fd(&utime, dir_fd, path->narrow, follow_symlinks);
4772 else
4773#endif
4774
4775#if defined(HAVE_FUTIMES) || defined(HAVE_FUTIMENS)
4776 if (path->fd != -1)
4777 result = utime_fd(&utime, path->fd);
4778 else
4779#endif
4780
4781 result = utime_default(&utime, path->narrow);
4782
4783 Py_END_ALLOW_THREADS
4784
4785 if (result < 0) {
4786 /* see previous comment about not putting filename in error here */
4787 posix_error();
4788 return NULL;
4789 }
4790
4791#endif /* MS_WINDOWS */
4792
4793 Py_RETURN_NONE;
4794}
4795
4796/* Process operations */
4797
4798
4799/*[clinic input]
4800os._exit
4801
4802 status: int
4803
4804Exit to the system with specified status, without normal exit processing.
4805[clinic start generated code]*/
4806
4807static PyObject *
4808os__exit_impl(PyObject *module, int status)
4809/*[clinic end generated code: output=116e52d9c2260d54 input=5e6d57556b0c4a62]*/
4810{
4811 _exit(status);
4812 return NULL; /* Make gcc -Wall happy */
4813}
4814
4815#if defined(HAVE_WEXECV) || defined(HAVE_WSPAWNV)
4816#define EXECV_CHAR wchar_t
4817#else
4818#define EXECV_CHAR char
4819#endif
4820
4821#if defined(HAVE_EXECV) || defined(HAVE_SPAWNV)
4822static void
4823free_string_array(EXECV_CHAR **array, Py_ssize_t count)
4824{
4825 Py_ssize_t i;
4826 for (i = 0; i < count; i++)
4827 PyMem_Free(array[i]);
4828 PyMem_DEL(array);
4829}
4830
4831static int
4832fsconvert_strdup(PyObject *o, EXECV_CHAR **out)
4833{
4834 Py_ssize_t size;
4835 PyObject *ub;
4836 int result = 0;
4837#if defined(HAVE_WEXECV) || defined(HAVE_WSPAWNV)
4838 if (!PyUnicode_FSDecoder(o, &ub))
4839 return 0;
4840 *out = PyUnicode_AsWideCharString(ub, &size);
4841 if (*out)
4842 result = 1;
4843#else
4844 if (!PyUnicode_FSConverter(o, &ub))
4845 return 0;
4846 size = PyBytes_GET_SIZE(ub);
4847 *out = PyMem_Malloc(size + 1);
4848 if (*out) {
4849 memcpy(*out, PyBytes_AS_STRING(ub), size + 1);
4850 result = 1;
4851 } else
4852 PyErr_NoMemory();
4853#endif
4854 Py_DECREF(ub);
4855 return result;
4856}
4857#endif
4858
4859#if defined(HAVE_EXECV) || defined (HAVE_FEXECVE)
4860static EXECV_CHAR**
4861parse_envlist(PyObject* env, Py_ssize_t *envc_ptr)
4862{
4863 Py_ssize_t i, pos, envc;
4864 PyObject *keys=NULL, *vals=NULL;
4865 PyObject *key, *val, *key2, *val2, *keyval;
4866 EXECV_CHAR **envlist;
4867
4868 i = PyMapping_Size(env);
4869 if (i < 0)
4870 return NULL;
4871 envlist = PyMem_NEW(EXECV_CHAR *, i + 1);
4872 if (envlist == NULL) {
4873 PyErr_NoMemory();
4874 return NULL;
4875 }
4876 envc = 0;
4877 keys = PyMapping_Keys(env);
4878 if (!keys)
4879 goto error;
4880 vals = PyMapping_Values(env);
4881 if (!vals)
4882 goto error;
4883 if (!PyList_Check(keys) || !PyList_Check(vals)) {
4884 PyErr_Format(PyExc_TypeError,
4885 "env.keys() or env.values() is not a list");
4886 goto error;
4887 }
4888
4889 for (pos = 0; pos < i; pos++) {
4890 key = PyList_GetItem(keys, pos);
4891 val = PyList_GetItem(vals, pos);
4892 if (!key || !val)
4893 goto error;
4894
4895#if defined(HAVE_WEXECV) || defined(HAVE_WSPAWNV)
4896 if (!PyUnicode_FSDecoder(key, &key2))
4897 goto error;
4898 if (!PyUnicode_FSDecoder(val, &val2)) {
4899 Py_DECREF(key2);
4900 goto error;
4901 }
4902 /* Search from index 1 because on Windows starting '=' is allowed for
4903 defining hidden environment variables. */
4904 if (PyUnicode_GET_LENGTH(key2) == 0 ||
4905 PyUnicode_FindChar(key2, '=', 1, PyUnicode_GET_LENGTH(key2), 1) != -1)
4906 {
4907 PyErr_SetString(PyExc_ValueError, "illegal environment variable name");
4908 Py_DECREF(key2);
4909 Py_DECREF(val2);
4910 goto error;
4911 }
4912 keyval = PyUnicode_FromFormat("%U=%U", key2, val2);
4913#else
4914 if (!PyUnicode_FSConverter(key, &key2))
4915 goto error;
4916 if (!PyUnicode_FSConverter(val, &val2)) {
4917 Py_DECREF(key2);
4918 goto error;
4919 }
4920 if (PyBytes_GET_SIZE(key2) == 0 ||
4921 strchr(PyBytes_AS_STRING(key2) + 1, '=') != NULL)
4922 {
4923 PyErr_SetString(PyExc_ValueError, "illegal environment variable name");
4924 Py_DECREF(key2);
4925 Py_DECREF(val2);
4926 goto error;
4927 }
4928 keyval = PyBytes_FromFormat("%s=%s", PyBytes_AS_STRING(key2),
4929 PyBytes_AS_STRING(val2));
4930#endif
4931 Py_DECREF(key2);
4932 Py_DECREF(val2);
4933 if (!keyval)
4934 goto error;
4935
4936 if (!fsconvert_strdup(keyval, &envlist[envc++])) {
4937 Py_DECREF(keyval);
4938 goto error;
4939 }
4940
4941 Py_DECREF(keyval);
4942 }
4943 Py_DECREF(vals);
4944 Py_DECREF(keys);
4945
4946 envlist[envc] = 0;
4947 *envc_ptr = envc;
4948 return envlist;
4949
4950error:
4951 Py_XDECREF(keys);
4952 Py_XDECREF(vals);
4953 free_string_array(envlist, envc);
4954 return NULL;
4955}
4956
4957static EXECV_CHAR**
4958parse_arglist(PyObject* argv, Py_ssize_t *argc)
4959{
4960 int i;
4961 EXECV_CHAR **argvlist = PyMem_NEW(EXECV_CHAR *, *argc+1);
4962 if (argvlist == NULL) {
4963 PyErr_NoMemory();
4964 return NULL;
4965 }
4966 for (i = 0; i < *argc; i++) {
4967 PyObject* item = PySequence_ITEM(argv, i);
4968 if (item == NULL)
4969 goto fail;
4970 if (!fsconvert_strdup(item, &argvlist[i])) {
4971 Py_DECREF(item);
4972 goto fail;
4973 }
4974 Py_DECREF(item);
4975 }
4976 argvlist[*argc] = NULL;
4977 return argvlist;
4978fail:
4979 *argc = i;
4980 free_string_array(argvlist, *argc);
4981 return NULL;
4982}
4983
4984#endif
4985
4986
4987#ifdef HAVE_EXECV
4988/*[clinic input]
4989os.execv
4990
4991 path: path_t
4992 Path of executable file.
4993 argv: object
4994 Tuple or list of strings.
4995 /
4996
4997Execute an executable path with arguments, replacing current process.
4998[clinic start generated code]*/
4999
5000static PyObject *
5001os_execv_impl(PyObject *module, path_t *path, PyObject *argv)
5002/*[clinic end generated code: output=3b52fec34cd0dafd input=9bac31efae07dac7]*/
5003{
5004 EXECV_CHAR **argvlist;
5005 Py_ssize_t argc;
5006
5007 /* execv has two arguments: (path, argv), where
5008 argv is a list or tuple of strings. */
5009
5010 if (!PyList_Check(argv) && !PyTuple_Check(argv)) {
5011 PyErr_SetString(PyExc_TypeError,
5012 "execv() arg 2 must be a tuple or list");
5013 return NULL;
5014 }
5015 argc = PySequence_Size(argv);
5016 if (argc < 1) {
5017 PyErr_SetString(PyExc_ValueError, "execv() arg 2 must not be empty");
5018 return NULL;
5019 }
5020
5021 argvlist = parse_arglist(argv, &argc);
5022 if (argvlist == NULL) {
5023 return NULL;
5024 }
5025 if (!argvlist[0][0]) {
5026 PyErr_SetString(PyExc_ValueError,
5027 "execv() arg 2 first element cannot be empty");
5028 free_string_array(argvlist, argc);
5029 return NULL;
5030 }
5031
5032 _Py_BEGIN_SUPPRESS_IPH
5033#ifdef HAVE_WEXECV
5034 _wexecv(path->wide, argvlist);
5035#else
5036 execv(path->narrow, argvlist);
5037#endif
5038 _Py_END_SUPPRESS_IPH
5039
5040 /* If we get here it's definitely an error */
5041
5042 free_string_array(argvlist, argc);
5043 return posix_error();
5044}
5045
5046
5047/*[clinic input]
5048os.execve
5049
5050 path: path_t(allow_fd='PATH_HAVE_FEXECVE')
5051 Path of executable file.
5052 argv: object
5053 Tuple or list of strings.
5054 env: object
5055 Dictionary of strings mapping to strings.
5056
5057Execute an executable path with arguments, replacing current process.
5058[clinic start generated code]*/
5059
5060static PyObject *
5061os_execve_impl(PyObject *module, path_t *path, PyObject *argv, PyObject *env)
5062/*[clinic end generated code: output=ff9fa8e4da8bde58 input=626804fa092606d9]*/
5063{
5064 EXECV_CHAR **argvlist = NULL;
5065 EXECV_CHAR **envlist;
5066 Py_ssize_t argc, envc;
5067
5068 /* execve has three arguments: (path, argv, env), where
5069 argv is a list or tuple of strings and env is a dictionary
5070 like posix.environ. */
5071
5072 if (!PyList_Check(argv) && !PyTuple_Check(argv)) {
5073 PyErr_SetString(PyExc_TypeError,
5074 "execve: argv must be a tuple or list");
5075 goto fail;
5076 }
5077 argc = PySequence_Size(argv);
5078 if (argc < 1) {
5079 PyErr_SetString(PyExc_ValueError, "execve: argv must not be empty");
5080 return NULL;
5081 }
5082
5083 if (!PyMapping_Check(env)) {
5084 PyErr_SetString(PyExc_TypeError,
5085 "execve: environment must be a mapping object");
5086 goto fail;
5087 }
5088
5089 argvlist = parse_arglist(argv, &argc);
5090 if (argvlist == NULL) {
5091 goto fail;
5092 }
5093 if (!argvlist[0][0]) {
5094 PyErr_SetString(PyExc_ValueError,
5095 "execve: argv first element cannot be empty");
5096 goto fail;
5097 }
5098
5099 envlist = parse_envlist(env, &envc);
5100 if (envlist == NULL)
5101 goto fail;
5102
5103 _Py_BEGIN_SUPPRESS_IPH
5104#ifdef HAVE_FEXECVE
5105 if (path->fd > -1)
5106 fexecve(path->fd, argvlist, envlist);
5107 else
5108#endif
5109#ifdef HAVE_WEXECV
5110 _wexecve(path->wide, argvlist, envlist);
5111#else
5112 execve(path->narrow, argvlist, envlist);
5113#endif
5114 _Py_END_SUPPRESS_IPH
5115
5116 /* If we get here it's definitely an error */
5117
5118 posix_path_error(path);
5119
5120 free_string_array(envlist, envc);
5121 fail:
5122 if (argvlist)
5123 free_string_array(argvlist, argc);
5124 return NULL;
5125}
5126
5127#endif /* HAVE_EXECV */
5128
5129#if defined(HAVE_SPAWNV) || defined(HAVE_WSPAWNV)
5130/*[clinic input]
5131os.spawnv
5132
5133 mode: int
5134 Mode of process creation.
5135 path: path_t
5136 Path of executable file.
5137 argv: object
5138 Tuple or list of strings.
5139 /
5140
5141Execute the program specified by path in a new process.
5142[clinic start generated code]*/
5143
5144static PyObject *
5145os_spawnv_impl(PyObject *module, int mode, path_t *path, PyObject *argv)
5146/*[clinic end generated code: output=71cd037a9d96b816 input=43224242303291be]*/
5147{
5148 EXECV_CHAR **argvlist;
5149 int i;
5150 Py_ssize_t argc;
5151 intptr_t spawnval;
5152 PyObject *(*getitem)(PyObject *, Py_ssize_t);
5153
5154 /* spawnv has three arguments: (mode, path, argv), where
5155 argv is a list or tuple of strings. */
5156
5157 if (PyList_Check(argv)) {
5158 argc = PyList_Size(argv);
5159 getitem = PyList_GetItem;
5160 }
5161 else if (PyTuple_Check(argv)) {
5162 argc = PyTuple_Size(argv);
5163 getitem = PyTuple_GetItem;
5164 }
5165 else {
5166 PyErr_SetString(PyExc_TypeError,
5167 "spawnv() arg 2 must be a tuple or list");
5168 return NULL;
5169 }
5170 if (argc == 0) {
5171 PyErr_SetString(PyExc_ValueError,
5172 "spawnv() arg 2 cannot be empty");
5173 return NULL;
5174 }
5175
5176 argvlist = PyMem_NEW(EXECV_CHAR *, argc+1);
5177 if (argvlist == NULL) {
5178 return PyErr_NoMemory();
5179 }
5180 for (i = 0; i < argc; i++) {
5181 if (!fsconvert_strdup((*getitem)(argv, i),
5182 &argvlist[i])) {
5183 free_string_array(argvlist, i);
5184 PyErr_SetString(
5185 PyExc_TypeError,
5186 "spawnv() arg 2 must contain only strings");
5187 return NULL;
5188 }
5189 if (i == 0 && !argvlist[0][0]) {
5190 free_string_array(argvlist, i + 1);
5191 PyErr_SetString(
5192 PyExc_ValueError,
5193 "spawnv() arg 2 first element cannot be empty");
5194 return NULL;
5195 }
5196 }
5197 argvlist[argc] = NULL;
5198
5199 if (mode == _OLD_P_OVERLAY)
5200 mode = _P_OVERLAY;
5201
5202 Py_BEGIN_ALLOW_THREADS
5203 _Py_BEGIN_SUPPRESS_IPH
5204#ifdef HAVE_WSPAWNV
5205 spawnval = _wspawnv(mode, path->wide, argvlist);
5206#else
5207 spawnval = _spawnv(mode, path->narrow, argvlist);
5208#endif
5209 _Py_END_SUPPRESS_IPH
5210 Py_END_ALLOW_THREADS
5211
5212 free_string_array(argvlist, argc);
5213
5214 if (spawnval == -1)
5215 return posix_error();
5216 else
5217 return Py_BuildValue(_Py_PARSE_INTPTR, spawnval);
5218}
5219
5220/*[clinic input]
5221os.spawnve
5222
5223 mode: int
5224 Mode of process creation.
5225 path: path_t
5226 Path of executable file.
5227 argv: object
5228 Tuple or list of strings.
5229 env: object
5230 Dictionary of strings mapping to strings.
5231 /
5232
5233Execute the program specified by path in a new process.
5234[clinic start generated code]*/
5235
5236static PyObject *
5237os_spawnve_impl(PyObject *module, int mode, path_t *path, PyObject *argv,
5238 PyObject *env)
5239/*[clinic end generated code: output=30fe85be56fe37ad input=3e40803ee7c4c586]*/
5240{
5241 EXECV_CHAR **argvlist;
5242 EXECV_CHAR **envlist;
5243 PyObject *res = NULL;
5244 Py_ssize_t argc, i, envc;
5245 intptr_t spawnval;
5246 PyObject *(*getitem)(PyObject *, Py_ssize_t);
5247 Py_ssize_t lastarg = 0;
5248
5249 /* spawnve has four arguments: (mode, path, argv, env), where
5250 argv is a list or tuple of strings and env is a dictionary
5251 like posix.environ. */
5252
5253 if (PyList_Check(argv)) {
5254 argc = PyList_Size(argv);
5255 getitem = PyList_GetItem;
5256 }
5257 else if (PyTuple_Check(argv)) {
5258 argc = PyTuple_Size(argv);
5259 getitem = PyTuple_GetItem;
5260 }
5261 else {
5262 PyErr_SetString(PyExc_TypeError,
5263 "spawnve() arg 2 must be a tuple or list");
5264 goto fail_0;
5265 }
5266 if (argc == 0) {
5267 PyErr_SetString(PyExc_ValueError,
5268 "spawnve() arg 2 cannot be empty");
5269 goto fail_0;
5270 }
5271 if (!PyMapping_Check(env)) {
5272 PyErr_SetString(PyExc_TypeError,
5273 "spawnve() arg 3 must be a mapping object");
5274 goto fail_0;
5275 }
5276
5277 argvlist = PyMem_NEW(EXECV_CHAR *, argc+1);
5278 if (argvlist == NULL) {
5279 PyErr_NoMemory();
5280 goto fail_0;
5281 }
5282 for (i = 0; i < argc; i++) {
5283 if (!fsconvert_strdup((*getitem)(argv, i),
5284 &argvlist[i]))
5285 {
5286 lastarg = i;
5287 goto fail_1;
5288 }
5289 if (i == 0 && !argvlist[0][0]) {
5290 lastarg = i + 1;
5291 PyErr_SetString(
5292 PyExc_ValueError,
5293 "spawnv() arg 2 first element cannot be empty");
5294 goto fail_1;
5295 }
5296 }
5297 lastarg = argc;
5298 argvlist[argc] = NULL;
5299
5300 envlist = parse_envlist(env, &envc);
5301 if (envlist == NULL)
5302 goto fail_1;
5303
5304 if (mode == _OLD_P_OVERLAY)
5305 mode = _P_OVERLAY;
5306
5307 Py_BEGIN_ALLOW_THREADS
5308 _Py_BEGIN_SUPPRESS_IPH
5309#ifdef HAVE_WSPAWNV
5310 spawnval = _wspawnve(mode, path->wide, argvlist, envlist);
5311#else
5312 spawnval = _spawnve(mode, path->narrow, argvlist, envlist);
5313#endif
5314 _Py_END_SUPPRESS_IPH
5315 Py_END_ALLOW_THREADS
5316
5317 if (spawnval == -1)
5318 (void) posix_error();
5319 else
5320 res = Py_BuildValue(_Py_PARSE_INTPTR, spawnval);
5321
5322 while (--envc >= 0)
5323 PyMem_DEL(envlist[envc]);
5324 PyMem_DEL(envlist);
5325 fail_1:
5326 free_string_array(argvlist, lastarg);
5327 fail_0:
5328 return res;
5329}
5330
5331#endif /* HAVE_SPAWNV */
5332
5333
5334#ifdef HAVE_FORK
5335
5336/* Helper function to validate arguments.
5337 Returns 0 on success. non-zero on failure with a TypeError raised.
5338 If obj is non-NULL it must be callable. */
5339static int
5340check_null_or_callable(PyObject *obj, const char* obj_name)
5341{
5342 if (obj && !PyCallable_Check(obj)) {
5343 PyErr_Format(PyExc_TypeError, "'%s' must be callable, not %s",
5344 obj_name, Py_TYPE(obj)->tp_name);
5345 return -1;
5346 }
5347 return 0;
5348}
5349
5350/*[clinic input]
5351os.register_at_fork
5352
5353 *
5354 before: object=NULL
5355 A callable to be called in the parent before the fork() syscall.
5356 after_in_child: object=NULL
5357 A callable to be called in the child after fork().
5358 after_in_parent: object=NULL
5359 A callable to be called in the parent after fork().
5360
5361Register callables to be called when forking a new process.
5362
5363'before' callbacks are called in reverse order.
5364'after_in_child' and 'after_in_parent' callbacks are called in order.
5365
5366[clinic start generated code]*/
5367
5368static PyObject *
5369os_register_at_fork_impl(PyObject *module, PyObject *before,
5370 PyObject *after_in_child, PyObject *after_in_parent)
5371/*[clinic end generated code: output=5398ac75e8e97625 input=cd1187aa85d2312e]*/
5372{
5373 PyInterpreterState *interp;
5374
5375 if (!before && !after_in_child && !after_in_parent) {
5376 PyErr_SetString(PyExc_TypeError, "At least one argument is required.");
5377 return NULL;
5378 }
5379 if (check_null_or_callable(before, "before") ||
5380 check_null_or_callable(after_in_child, "after_in_child") ||
5381 check_null_or_callable(after_in_parent, "after_in_parent")) {
5382 return NULL;
5383 }
5384 interp = PyThreadState_Get()->interp;
5385
5386 if (register_at_forker(&interp->before_forkers, before)) {
5387 return NULL;
5388 }
5389 if (register_at_forker(&interp->after_forkers_child, after_in_child)) {
5390 return NULL;
5391 }
5392 if (register_at_forker(&interp->after_forkers_parent, after_in_parent)) {
5393 return NULL;
5394 }
5395 Py_RETURN_NONE;
5396}
5397#endif /* HAVE_FORK */
5398
5399
5400#ifdef HAVE_FORK1
5401/*[clinic input]
5402os.fork1
5403
5404Fork a child process with a single multiplexed (i.e., not bound) thread.
5405
5406Return 0 to child process and PID of child to parent process.
5407[clinic start generated code]*/
5408
5409static PyObject *
5410os_fork1_impl(PyObject *module)
5411/*[clinic end generated code: output=0de8e67ce2a310bc input=12db02167893926e]*/
5412{
5413 pid_t pid;
5414
5415 PyOS_BeforeFork();
5416 pid = fork1();
5417 if (pid == 0) {
5418 /* child: this clobbers and resets the import lock. */
5419 PyOS_AfterFork_Child();
5420 } else {
5421 /* parent: release the import lock. */
5422 PyOS_AfterFork_Parent();
5423 }
5424 if (pid == -1)
5425 return posix_error();
5426 return PyLong_FromPid(pid);
5427}
5428#endif /* HAVE_FORK1 */
5429
5430
5431#ifdef HAVE_FORK
5432/*[clinic input]
5433os.fork
5434
5435Fork a child process.
5436
5437Return 0 to child process and PID of child to parent process.
5438[clinic start generated code]*/
5439
5440static PyObject *
5441os_fork_impl(PyObject *module)
5442/*[clinic end generated code: output=3626c81f98985d49 input=13c956413110eeaa]*/
5443{
5444 pid_t pid;
5445
5446 PyOS_BeforeFork();
5447 pid = fork();
5448 if (pid == 0) {
5449 /* child: this clobbers and resets the import lock. */
5450 PyOS_AfterFork_Child();
5451 } else {
5452 /* parent: release the import lock. */
5453 PyOS_AfterFork_Parent();
5454 }
5455 if (pid == -1)
5456 return posix_error();
5457 return PyLong_FromPid(pid);
5458}
5459#endif /* HAVE_FORK */
5460
5461
5462#ifdef HAVE_SCHED_H
5463#ifdef HAVE_SCHED_GET_PRIORITY_MAX
5464/*[clinic input]
5465os.sched_get_priority_max
5466
5467 policy: int
5468
5469Get the maximum scheduling priority for policy.
5470[clinic start generated code]*/
5471
5472static PyObject *
5473os_sched_get_priority_max_impl(PyObject *module, int policy)
5474/*[clinic end generated code: output=9e465c6e43130521 input=2097b7998eca6874]*/
5475{
5476 int max;
5477
5478 max = sched_get_priority_max(policy);
5479 if (max < 0)
5480 return posix_error();
5481 return PyLong_FromLong(max);
5482}
5483
5484
5485/*[clinic input]
5486os.sched_get_priority_min
5487
5488 policy: int
5489
5490Get the minimum scheduling priority for policy.
5491[clinic start generated code]*/
5492
5493static PyObject *
5494os_sched_get_priority_min_impl(PyObject *module, int policy)
5495/*[clinic end generated code: output=7595c1138cc47a6d input=21bc8fa0d70983bf]*/
5496{
5497 int min = sched_get_priority_min(policy);
5498 if (min < 0)
5499 return posix_error();
5500 return PyLong_FromLong(min);
5501}
5502#endif /* HAVE_SCHED_GET_PRIORITY_MAX */
5503
5504
5505#ifdef HAVE_SCHED_SETSCHEDULER
5506/*[clinic input]
5507os.sched_getscheduler
5508 pid: pid_t
5509 /
5510
5511Get the scheduling policy for the process identifiedy by pid.
5512
5513Passing 0 for pid returns the scheduling policy for the calling process.
5514[clinic start generated code]*/
5515
5516static PyObject *
5517os_sched_getscheduler_impl(PyObject *module, pid_t pid)
5518/*[clinic end generated code: output=dce4c0bd3f1b34c8 input=5f14cfd1f189e1a0]*/
5519{
5520 int policy;
5521
5522 policy = sched_getscheduler(pid);
5523 if (policy < 0)
5524 return posix_error();
5525 return PyLong_FromLong(policy);
5526}
5527#endif /* HAVE_SCHED_SETSCHEDULER */
5528
5529
5530#if defined(HAVE_SCHED_SETSCHEDULER) || defined(HAVE_SCHED_SETPARAM)
5531/*[clinic input]
5532class os.sched_param "PyObject *" "&SchedParamType"
5533
5534@classmethod
5535os.sched_param.__new__
5536
5537 sched_priority: object
5538 A scheduling parameter.
5539
5540Current has only one field: sched_priority");
5541[clinic start generated code]*/
5542
5543static PyObject *
5544os_sched_param_impl(PyTypeObject *type, PyObject *sched_priority)
5545/*[clinic end generated code: output=48f4067d60f48c13 input=73a4c22f7071fc62]*/
5546{
5547 PyObject *res;
5548
5549 res = PyStructSequence_New(type);
5550 if (!res)
5551 return NULL;
5552 Py_INCREF(sched_priority);
5553 PyStructSequence_SET_ITEM(res, 0, sched_priority);
5554 return res;
5555}
5556
5557
5558PyDoc_VAR(os_sched_param__doc__);
5559
5560static PyStructSequence_Field sched_param_fields[] = {
5561 {"sched_priority", "the scheduling priority"},
5562 {0}
5563};
5564
5565static PyStructSequence_Desc sched_param_desc = {
5566 "sched_param", /* name */
5567 os_sched_param__doc__, /* doc */
5568 sched_param_fields,
5569 1
5570};
5571
5572static int
5573convert_sched_param(PyObject *param, struct sched_param *res)
5574{
5575 long priority;
5576
5577 if (Py_TYPE(param) != &SchedParamType) {
5578 PyErr_SetString(PyExc_TypeError, "must have a sched_param object");
5579 return 0;
5580 }
5581 priority = PyLong_AsLong(PyStructSequence_GET_ITEM(param, 0));
5582 if (priority == -1 && PyErr_Occurred())
5583 return 0;
5584 if (priority > INT_MAX || priority < INT_MIN) {
5585 PyErr_SetString(PyExc_OverflowError, "sched_priority out of range");
5586 return 0;
5587 }
5588 res->sched_priority = Py_SAFE_DOWNCAST(priority, long, int);
5589 return 1;
5590}
5591#endif /* defined(HAVE_SCHED_SETSCHEDULER) || defined(HAVE_SCHED_SETPARAM) */
5592
5593
5594#ifdef HAVE_SCHED_SETSCHEDULER
5595/*[clinic input]
5596os.sched_setscheduler
5597
5598 pid: pid_t
5599 policy: int
5600 param: sched_param
5601 /
5602
5603Set the scheduling policy for the process identified by pid.
5604
5605If pid is 0, the calling process is changed.
5606param is an instance of sched_param.
5607[clinic start generated code]*/
5608
5609static PyObject *
5610os_sched_setscheduler_impl(PyObject *module, pid_t pid, int policy,
5611 struct sched_param *param)
5612/*[clinic end generated code: output=b0ac0a70d3b1d705 input=c581f9469a5327dd]*/
5613{
5614 /*
5615 ** sched_setscheduler() returns 0 in Linux, but the previous
5616 ** scheduling policy under Solaris/Illumos, and others.
5617 ** On error, -1 is returned in all Operating Systems.
5618 */
5619 if (sched_setscheduler(pid, policy, param) == -1)
5620 return posix_error();
5621 Py_RETURN_NONE;
5622}
5623#endif /* HAVE_SCHED_SETSCHEDULER*/
5624
5625
5626#ifdef HAVE_SCHED_SETPARAM
5627/*[clinic input]
5628os.sched_getparam
5629 pid: pid_t
5630 /
5631
5632Returns scheduling parameters for the process identified by pid.
5633
5634If pid is 0, returns parameters for the calling process.
5635Return value is an instance of sched_param.
5636[clinic start generated code]*/
5637
5638static PyObject *
5639os_sched_getparam_impl(PyObject *module, pid_t pid)
5640/*[clinic end generated code: output=b194e8708dcf2db8 input=18a1ef9c2efae296]*/
5641{
5642 struct sched_param param;
5643 PyObject *result;
5644 PyObject *priority;
5645
5646 if (sched_getparam(pid, ¶m))
5647 return posix_error();
5648 result = PyStructSequence_New(&SchedParamType);
5649 if (!result)
5650 return NULL;
5651 priority = PyLong_FromLong(param.sched_priority);
5652 if (!priority) {
5653 Py_DECREF(result);
5654 return NULL;
5655 }
5656 PyStructSequence_SET_ITEM(result, 0, priority);
5657 return result;
5658}
5659
5660
5661/*[clinic input]
5662os.sched_setparam
5663 pid: pid_t
5664 param: sched_param
5665 /
5666
5667Set scheduling parameters for the process identified by pid.
5668
5669If pid is 0, sets parameters for the calling process.
5670param should be an instance of sched_param.
5671[clinic start generated code]*/
5672
5673static PyObject *
5674os_sched_setparam_impl(PyObject *module, pid_t pid,
5675 struct sched_param *param)
5676/*[clinic end generated code: output=8af013f78a32b591 input=6b8d6dfcecdc21bd]*/
5677{
5678 if (sched_setparam(pid, param))
5679 return posix_error();
5680 Py_RETURN_NONE;
5681}
5682#endif /* HAVE_SCHED_SETPARAM */
5683
5684
5685#ifdef HAVE_SCHED_RR_GET_INTERVAL
5686/*[clinic input]
5687os.sched_rr_get_interval -> double
5688 pid: pid_t
5689 /
5690
5691Return the round-robin quantum for the process identified by pid, in seconds.
5692
5693Value returned is a float.
5694[clinic start generated code]*/
5695
5696static double
5697os_sched_rr_get_interval_impl(PyObject *module, pid_t pid)
5698/*[clinic end generated code: output=7e2d935833ab47dc input=2a973da15cca6fae]*/
5699{
5700 struct timespec interval;
5701 if (sched_rr_get_interval(pid, &interval)) {
5702 posix_error();
5703 return -1.0;
5704 }
5705#ifdef _Py_MEMORY_SANITIZER
5706 __msan_unpoison(&interval, sizeof(interval));
5707#endif
5708 return (double)interval.tv_sec + 1e-9*interval.tv_nsec;
5709}
5710#endif /* HAVE_SCHED_RR_GET_INTERVAL */
5711
5712
5713/*[clinic input]
5714os.sched_yield
5715
5716Voluntarily relinquish the CPU.
5717[clinic start generated code]*/
5718
5719static PyObject *
5720os_sched_yield_impl(PyObject *module)
5721/*[clinic end generated code: output=902323500f222cac input=e54d6f98189391d4]*/
5722{
5723 if (sched_yield())
5724 return posix_error();
5725 Py_RETURN_NONE;
5726}
5727
5728#ifdef HAVE_SCHED_SETAFFINITY
5729/* The minimum number of CPUs allocated in a cpu_set_t */
5730static const int NCPUS_START = sizeof(unsigned long) * CHAR_BIT;
5731
5732/*[clinic input]
5733os.sched_setaffinity
5734 pid: pid_t
5735 mask : object
5736 /
5737
5738Set the CPU affinity of the process identified by pid to mask.
5739
5740mask should be an iterable of integers identifying CPUs.
5741[clinic start generated code]*/
5742
5743static PyObject *
5744os_sched_setaffinity_impl(PyObject *module, pid_t pid, PyObject *mask)
5745/*[clinic end generated code: output=882d7dd9a229335b input=a0791a597c7085ba]*/
5746{
5747 int ncpus;
5748 size_t setsize;
5749 cpu_set_t *cpu_set = NULL;
5750 PyObject *iterator = NULL, *item;
5751
5752 iterator = PyObject_GetIter(mask);
5753 if (iterator == NULL)
5754 return NULL;
5755
5756 ncpus = NCPUS_START;
5757 setsize = CPU_ALLOC_SIZE(ncpus);
5758 cpu_set = CPU_ALLOC(ncpus);
5759 if (cpu_set == NULL) {
5760 PyErr_NoMemory();
5761 goto error;
5762 }
5763 CPU_ZERO_S(setsize, cpu_set);
5764
5765 while ((item = PyIter_Next(iterator))) {
5766 long cpu;
5767 if (!PyLong_Check(item)) {
5768 PyErr_Format(PyExc_TypeError,
5769 "expected an iterator of ints, "
5770 "but iterator yielded %R",
5771 Py_TYPE(item));
5772 Py_DECREF(item);
5773 goto error;
5774 }
5775 cpu = PyLong_AsLong(item);
5776 Py_DECREF(item);
5777 if (cpu < 0) {
5778 if (!PyErr_Occurred())
5779 PyErr_SetString(PyExc_ValueError, "negative CPU number");
5780 goto error;
5781 }
5782 if (cpu > INT_MAX - 1) {
5783 PyErr_SetString(PyExc_OverflowError, "CPU number too large");
5784 goto error;
5785 }
5786 if (cpu >= ncpus) {
5787 /* Grow CPU mask to fit the CPU number */
5788 int newncpus = ncpus;
5789 cpu_set_t *newmask;
5790 size_t newsetsize;
5791 while (newncpus <= cpu) {
5792 if (newncpus > INT_MAX / 2)
5793 newncpus = cpu + 1;
5794 else
5795 newncpus = newncpus * 2;
5796 }
5797 newmask = CPU_ALLOC(newncpus);
5798 if (newmask == NULL) {
5799 PyErr_NoMemory();
5800 goto error;
5801 }
5802 newsetsize = CPU_ALLOC_SIZE(newncpus);
5803 CPU_ZERO_S(newsetsize, newmask);
5804 memcpy(newmask, cpu_set, setsize);
5805 CPU_FREE(cpu_set);
5806 setsize = newsetsize;
5807 cpu_set = newmask;
5808 ncpus = newncpus;
5809 }
5810 CPU_SET_S(cpu, setsize, cpu_set);
5811 }
5812 Py_CLEAR(iterator);
5813
5814 if (sched_setaffinity(pid, setsize, cpu_set)) {
5815 posix_error();
5816 goto error;
5817 }
5818 CPU_FREE(cpu_set);
5819 Py_RETURN_NONE;
5820
5821error:
5822 if (cpu_set)
5823 CPU_FREE(cpu_set);
5824 Py_XDECREF(iterator);
5825 return NULL;
5826}
5827
5828
5829/*[clinic input]
5830os.sched_getaffinity
5831 pid: pid_t
5832 /
5833
5834Return the affinity of the process identified by pid (or the current process if zero).
5835
5836The affinity is returned as a set of CPU identifiers.
5837[clinic start generated code]*/
5838
5839static PyObject *
5840os_sched_getaffinity_impl(PyObject *module, pid_t pid)
5841/*[clinic end generated code: output=f726f2c193c17a4f input=983ce7cb4a565980]*/
5842{
5843 int cpu, ncpus, count;
5844 size_t setsize;
5845 cpu_set_t *mask = NULL;
5846 PyObject *res = NULL;
5847
5848 ncpus = NCPUS_START;
5849 while (1) {
5850 setsize = CPU_ALLOC_SIZE(ncpus);
5851 mask = CPU_ALLOC(ncpus);
5852 if (mask == NULL)
5853 return PyErr_NoMemory();
5854 if (sched_getaffinity(pid, setsize, mask) == 0)
5855 break;
5856 CPU_FREE(mask);
5857 if (errno != EINVAL)
5858 return posix_error();
5859 if (ncpus > INT_MAX / 2) {
5860 PyErr_SetString(PyExc_OverflowError, "could not allocate "
5861 "a large enough CPU set");
5862 return NULL;
5863 }
5864 ncpus = ncpus * 2;
5865 }
5866
5867 res = PySet_New(NULL);
5868 if (res == NULL)
5869 goto error;
5870 for (cpu = 0, count = CPU_COUNT_S(setsize, mask); count; cpu++) {
5871 if (CPU_ISSET_S(cpu, setsize, mask)) {
5872 PyObject *cpu_num = PyLong_FromLong(cpu);
5873 --count;
5874 if (cpu_num == NULL)
5875 goto error;
5876 if (PySet_Add(res, cpu_num)) {
5877 Py_DECREF(cpu_num);
5878 goto error;
5879 }
5880 Py_DECREF(cpu_num);
5881 }
5882 }
5883 CPU_FREE(mask);
5884 return res;
5885
5886error:
5887 if (mask)
5888 CPU_FREE(mask);
5889 Py_XDECREF(res);
5890 return NULL;
5891}
5892
5893#endif /* HAVE_SCHED_SETAFFINITY */
5894
5895#endif /* HAVE_SCHED_H */
5896
5897
5898/* AIX uses /dev/ptc but is otherwise the same as /dev/ptmx */
5899/* IRIX has both /dev/ptc and /dev/ptmx, use ptmx */
5900#if defined(HAVE_DEV_PTC) && !defined(HAVE_DEV_PTMX)
5901#define DEV_PTY_FILE "/dev/ptc"
5902#define HAVE_DEV_PTMX
5903#else
5904#define DEV_PTY_FILE "/dev/ptmx"
5905#endif
5906
5907#if defined(HAVE_OPENPTY) || defined(HAVE_FORKPTY) || defined(HAVE_DEV_PTMX)
5908#ifdef HAVE_PTY_H
5909#include <pty.h>
5910#else
5911#ifdef HAVE_LIBUTIL_H
5912#include <libutil.h>
5913#else
5914#ifdef HAVE_UTIL_H
5915#include <util.h>
5916#endif /* HAVE_UTIL_H */
5917#endif /* HAVE_LIBUTIL_H */
5918#endif /* HAVE_PTY_H */
5919#ifdef HAVE_STROPTS_H
5920#include <stropts.h>
5921#endif
5922#endif /* defined(HAVE_OPENPTY) || defined(HAVE_FORKPTY) || defined(HAVE_DEV_PTMX) */
5923
5924
5925#if defined(HAVE_OPENPTY) || defined(HAVE__GETPTY) || defined(HAVE_DEV_PTMX)
5926/*[clinic input]
5927os.openpty
5928
5929Open a pseudo-terminal.
5930
5931Return a tuple of (master_fd, slave_fd) containing open file descriptors
5932for both the master and slave ends.
5933[clinic start generated code]*/
5934
5935static PyObject *
5936os_openpty_impl(PyObject *module)
5937/*[clinic end generated code: output=98841ce5ec9cef3c input=f3d99fd99e762907]*/
5938{
5939 int master_fd = -1, slave_fd = -1;
5940#ifndef HAVE_OPENPTY
5941 char * slave_name;
5942#endif
5943#if defined(HAVE_DEV_PTMX) && !defined(HAVE_OPENPTY) && !defined(HAVE__GETPTY)
5944 PyOS_sighandler_t sig_saved;
5945#if defined(__sun) && defined(__SVR4)
5946 extern char *ptsname(int fildes);
5947#endif
5948#endif
5949
5950#ifdef HAVE_OPENPTY
5951 if (openpty(&master_fd, &slave_fd, NULL, NULL, NULL) != 0)
5952 goto posix_error;
5953
5954 if (_Py_set_inheritable(master_fd, 0, NULL) < 0)
5955 goto error;
5956 if (_Py_set_inheritable(slave_fd, 0, NULL) < 0)
5957 goto error;
5958
5959#elif defined(HAVE__GETPTY)
5960 slave_name = _getpty(&master_fd, O_RDWR, 0666, 0);
5961 if (slave_name == NULL)
5962 goto posix_error;
5963 if (_Py_set_inheritable(master_fd, 0, NULL) < 0)
5964 goto error;
5965
5966 slave_fd = _Py_open(slave_name, O_RDWR);
5967 if (slave_fd < 0)
5968 goto error;
5969
5970#else
5971 master_fd = open(DEV_PTY_FILE, O_RDWR | O_NOCTTY); /* open master */
5972 if (master_fd < 0)
5973 goto posix_error;
5974
5975 sig_saved = PyOS_setsig(SIGCHLD, SIG_DFL);
5976
5977 /* change permission of slave */
5978 if (grantpt(master_fd) < 0) {
5979 PyOS_setsig(SIGCHLD, sig_saved);
5980 goto posix_error;
5981 }
5982
5983 /* unlock slave */
5984 if (unlockpt(master_fd) < 0) {
5985 PyOS_setsig(SIGCHLD, sig_saved);
5986 goto posix_error;
5987 }
5988
5989 PyOS_setsig(SIGCHLD, sig_saved);
5990
5991 slave_name = ptsname(master_fd); /* get name of slave */
5992 if (slave_name == NULL)
5993 goto posix_error;
5994
5995 slave_fd = _Py_open(slave_name, O_RDWR | O_NOCTTY); /* open slave */
5996 if (slave_fd == -1)
5997 goto error;
5998
5999 if (_Py_set_inheritable(master_fd, 0, NULL) < 0)
6000 goto posix_error;
6001
6002#if !defined(__CYGWIN__) && !defined(__ANDROID__) && !defined(HAVE_DEV_PTC)
6003 ioctl(slave_fd, I_PUSH, "ptem"); /* push ptem */
6004 ioctl(slave_fd, I_PUSH, "ldterm"); /* push ldterm */
6005#ifndef __hpux
6006 ioctl(slave_fd, I_PUSH, "ttcompat"); /* push ttcompat */
6007#endif /* __hpux */
6008#endif /* HAVE_CYGWIN */
6009#endif /* HAVE_OPENPTY */
6010
6011 return Py_BuildValue("(ii)", master_fd, slave_fd);
6012
6013posix_error:
6014 posix_error();
6015error:
6016 if (master_fd != -1)
6017 close(master_fd);
6018 if (slave_fd != -1)
6019 close(slave_fd);
6020 return NULL;
6021}
6022#endif /* defined(HAVE_OPENPTY) || defined(HAVE__GETPTY) || defined(HAVE_DEV_PTMX) */
6023
6024
6025#ifdef HAVE_FORKPTY
6026/*[clinic input]
6027os.forkpty
6028
6029Fork a new process with a new pseudo-terminal as controlling tty.
6030
6031Returns a tuple of (pid, master_fd).
6032Like fork(), return pid of 0 to the child process,
6033and pid of child to the parent process.
6034To both, return fd of newly opened pseudo-terminal.
6035[clinic start generated code]*/
6036
6037static PyObject *
6038os_forkpty_impl(PyObject *module)
6039/*[clinic end generated code: output=60d0a5c7512e4087 input=f1f7f4bae3966010]*/
6040{
6041 int master_fd = -1;
6042 pid_t pid;
6043
6044 PyOS_BeforeFork();
6045 pid = forkpty(&master_fd, NULL, NULL, NULL);
6046 if (pid == 0) {
6047 /* child: this clobbers and resets the import lock. */
6048 PyOS_AfterFork_Child();
6049 } else {
6050 /* parent: release the import lock. */
6051 PyOS_AfterFork_Parent();
6052 }
6053 if (pid == -1)
6054 return posix_error();
6055 return Py_BuildValue("(Ni)", PyLong_FromPid(pid), master_fd);
6056}
6057#endif /* HAVE_FORKPTY */
6058
6059
6060#ifdef HAVE_GETEGID
6061/*[clinic input]
6062os.getegid
6063
6064Return the current process's effective group id.
6065[clinic start generated code]*/
6066
6067static PyObject *
6068os_getegid_impl(PyObject *module)
6069/*[clinic end generated code: output=67d9be7ac68898a2 input=1596f79ad1107d5d]*/
6070{
6071 return _PyLong_FromGid(getegid());
6072}
6073#endif /* HAVE_GETEGID */
6074
6075
6076#ifdef HAVE_GETEUID
6077/*[clinic input]
6078os.geteuid
6079
6080Return the current process's effective user id.
6081[clinic start generated code]*/
6082
6083static PyObject *
6084os_geteuid_impl(PyObject *module)
6085/*[clinic end generated code: output=ea1b60f0d6abb66e input=4644c662d3bd9f19]*/
6086{
6087 return _PyLong_FromUid(geteuid());
6088}
6089#endif /* HAVE_GETEUID */
6090
6091
6092#ifdef HAVE_GETGID
6093/*[clinic input]
6094os.getgid
6095
6096Return the current process's group id.
6097[clinic start generated code]*/
6098
6099static PyObject *
6100os_getgid_impl(PyObject *module)
6101/*[clinic end generated code: output=4f28ebc9d3e5dfcf input=58796344cd87c0f6]*/
6102{
6103 return _PyLong_FromGid(getgid());
6104}
6105#endif /* HAVE_GETGID */
6106
6107
6108#ifdef HAVE_GETPID
6109/*[clinic input]
6110os.getpid
6111
6112Return the current process id.
6113[clinic start generated code]*/
6114
6115static PyObject *
6116os_getpid_impl(PyObject *module)
6117/*[clinic end generated code: output=9ea6fdac01ed2b3c input=5a9a00f0ab68aa00]*/
6118{
6119 return PyLong_FromPid(getpid());
6120}
6121#endif /* HAVE_GETPID */
6122
6123#ifdef NGROUPS_MAX
6124#define MAX_GROUPS NGROUPS_MAX
6125#else
6126 /* defined to be 16 on Solaris7, so this should be a small number */
6127#define MAX_GROUPS 64
6128#endif
6129
6130#ifdef HAVE_GETGROUPLIST
6131
6132/* AC 3.5: funny apple logic below */
6133PyDoc_STRVAR(posix_getgrouplist__doc__,
6134"getgrouplist(user, group) -> list of groups to which a user belongs\n\n\
6135Returns a list of groups to which a user belongs.\n\n\
6136 user: username to lookup\n\
6137 group: base group id of the user");
6138
6139static PyObject *
6140posix_getgrouplist(PyObject *self, PyObject *args)
6141{
6142 const char *user;
6143 int i, ngroups;
6144 PyObject *list;
6145#ifdef __APPLE__
6146 int *groups, basegid;
6147#else
6148 gid_t *groups, basegid;
6149#endif
6150
6151 /*
6152 * NGROUPS_MAX is defined by POSIX.1 as the maximum
6153 * number of supplimental groups a users can belong to.
6154 * We have to increment it by one because
6155 * getgrouplist() returns both the supplemental groups
6156 * and the primary group, i.e. all of the groups the
6157 * user belongs to.
6158 */
6159 ngroups = 1 + MAX_GROUPS;
6160
6161#ifdef __APPLE__
6162 if (!PyArg_ParseTuple(args, "si:getgrouplist", &user, &basegid))
6163 return NULL;
6164#else
6165 if (!PyArg_ParseTuple(args, "sO&:getgrouplist", &user,
6166 _Py_Gid_Converter, &basegid))
6167 return NULL;
6168#endif
6169
6170#ifdef __APPLE__
6171 groups = PyMem_New(int, ngroups);
6172#else
6173 groups = PyMem_New(gid_t, ngroups);
6174#endif
6175 if (groups == NULL)
6176 return PyErr_NoMemory();
6177
6178 if (getgrouplist(user, basegid, groups, &ngroups) == -1) {
6179 PyMem_Del(groups);
6180 return posix_error();
6181 }
6182
6183#ifdef _Py_MEMORY_SANITIZER
6184 /* Clang memory sanitizer libc intercepts don't know getgrouplist. */
6185 __msan_unpoison(&ngroups, sizeof(ngroups));
6186 __msan_unpoison(groups, ngroups*sizeof(*groups));
6187#endif
6188
6189 list = PyList_New(ngroups);
6190 if (list == NULL) {
6191 PyMem_Del(groups);
6192 return NULL;
6193 }
6194
6195 for (i = 0; i < ngroups; i++) {
6196#ifdef __APPLE__
6197 PyObject *o = PyLong_FromUnsignedLong((unsigned long)groups[i]);
6198#else
6199 PyObject *o = _PyLong_FromGid(groups[i]);
6200#endif
6201 if (o == NULL) {
6202 Py_DECREF(list);
6203 PyMem_Del(groups);
6204 return NULL;
6205 }
6206 PyList_SET_ITEM(list, i, o);
6207 }
6208
6209 PyMem_Del(groups);
6210
6211 return list;
6212}
6213#endif /* HAVE_GETGROUPLIST */
6214
6215
6216#ifdef HAVE_GETGROUPS
6217/*[clinic input]
6218os.getgroups
6219
6220Return list of supplemental group IDs for the process.
6221[clinic start generated code]*/
6222
6223static PyObject *
6224os_getgroups_impl(PyObject *module)
6225/*[clinic end generated code: output=42b0c17758561b56 input=d3f109412e6a155c]*/
6226{
6227 PyObject *result = NULL;
6228 gid_t grouplist[MAX_GROUPS];
6229
6230 /* On MacOSX getgroups(2) can return more than MAX_GROUPS results
6231 * This is a helper variable to store the intermediate result when
6232 * that happens.
6233 *
6234 * To keep the code readable the OSX behaviour is unconditional,
6235 * according to the POSIX spec this should be safe on all unix-y
6236 * systems.
6237 */
6238 gid_t* alt_grouplist = grouplist;
6239 int n;
6240
6241#ifdef __APPLE__
6242 /* Issue #17557: As of OS X 10.8, getgroups(2) no longer raises EINVAL if
6243 * there are more groups than can fit in grouplist. Therefore, on OS X
6244 * always first call getgroups with length 0 to get the actual number
6245 * of groups.
6246 */
6247 n = getgroups(0, NULL);
6248 if (n < 0) {
6249 return posix_error();
6250 } else if (n <= MAX_GROUPS) {
6251 /* groups will fit in existing array */
6252 alt_grouplist = grouplist;
6253 } else {
6254 alt_grouplist = PyMem_New(gid_t, n);
6255 if (alt_grouplist == NULL) {
6256 return PyErr_NoMemory();
6257 }
6258 }
6259
6260 n = getgroups(n, alt_grouplist);
6261 if (n == -1) {
6262 if (alt_grouplist != grouplist) {
6263 PyMem_Free(alt_grouplist);
6264 }
6265 return posix_error();
6266 }
6267#else
6268 n = getgroups(MAX_GROUPS, grouplist);
6269 if (n < 0) {
6270 if (errno == EINVAL) {
6271 n = getgroups(0, NULL);
6272 if (n == -1) {
6273 return posix_error();
6274 }
6275 if (n == 0) {
6276 /* Avoid malloc(0) */
6277 alt_grouplist = grouplist;
6278 } else {
6279 alt_grouplist = PyMem_New(gid_t, n);
6280 if (alt_grouplist == NULL) {
6281 return PyErr_NoMemory();
6282 }
6283 n = getgroups(n, alt_grouplist);
6284 if (n == -1) {
6285 PyMem_Free(alt_grouplist);
6286 return posix_error();
6287 }
6288 }
6289 } else {
6290 return posix_error();
6291 }
6292 }
6293#endif
6294
6295 result = PyList_New(n);
6296 if (result != NULL) {
6297 int i;
6298 for (i = 0; i < n; ++i) {
6299 PyObject *o = _PyLong_FromGid(alt_grouplist[i]);
6300 if (o == NULL) {
6301 Py_DECREF(result);
6302 result = NULL;
6303 break;
6304 }
6305 PyList_SET_ITEM(result, i, o);
6306 }
6307 }
6308
6309 if (alt_grouplist != grouplist) {
6310 PyMem_Free(alt_grouplist);
6311 }
6312
6313 return result;
6314}
6315#endif /* HAVE_GETGROUPS */
6316
6317#ifdef HAVE_INITGROUPS
6318PyDoc_STRVAR(posix_initgroups__doc__,
6319"initgroups(username, gid) -> None\n\n\
6320Call the system initgroups() to initialize the group access list with all of\n\
6321the groups of which the specified username is a member, plus the specified\n\
6322group id.");
6323
6324/* AC 3.5: funny apple logic */
6325static PyObject *
6326posix_initgroups(PyObject *self, PyObject *args)
6327{
6328 PyObject *oname;
6329 const char *username;
6330 int res;
6331#ifdef __APPLE__
6332 int gid;
6333#else
6334 gid_t gid;
6335#endif
6336
6337#ifdef __APPLE__
6338 if (!PyArg_ParseTuple(args, "O&i:initgroups",
6339 PyUnicode_FSConverter, &oname,
6340 &gid))
6341#else
6342 if (!PyArg_ParseTuple(args, "O&O&:initgroups",
6343 PyUnicode_FSConverter, &oname,
6344 _Py_Gid_Converter, &gid))
6345#endif
6346 return NULL;
6347 username = PyBytes_AS_STRING(oname);
6348
6349 res = initgroups(username, gid);
6350 Py_DECREF(oname);
6351 if (res == -1)
6352 return PyErr_SetFromErrno(PyExc_OSError);
6353
6354 Py_RETURN_NONE;
6355}
6356#endif /* HAVE_INITGROUPS */
6357
6358
6359#ifdef HAVE_GETPGID
6360/*[clinic input]
6361os.getpgid
6362
6363 pid: pid_t
6364
6365Call the system call getpgid(), and return the result.
6366[clinic start generated code]*/
6367
6368static PyObject *
6369os_getpgid_impl(PyObject *module, pid_t pid)
6370/*[clinic end generated code: output=1db95a97be205d18 input=39d710ae3baaf1c7]*/
6371{
6372 pid_t pgid = getpgid(pid);
6373 if (pgid < 0)
6374 return posix_error();
6375 return PyLong_FromPid(pgid);
6376}
6377#endif /* HAVE_GETPGID */
6378
6379
6380#ifdef HAVE_GETPGRP
6381/*[clinic input]
6382os.getpgrp
6383
6384Return the current process group id.
6385[clinic start generated code]*/
6386
6387static PyObject *
6388os_getpgrp_impl(PyObject *module)
6389/*[clinic end generated code: output=c4fc381e51103cf3 input=6846fb2bb9a3705e]*/
6390{
6391#ifdef GETPGRP_HAVE_ARG
6392 return PyLong_FromPid(getpgrp(0));
6393#else /* GETPGRP_HAVE_ARG */
6394 return PyLong_FromPid(getpgrp());
6395#endif /* GETPGRP_HAVE_ARG */
6396}
6397#endif /* HAVE_GETPGRP */
6398
6399
6400#ifdef HAVE_SETPGRP
6401/*[clinic input]
6402os.setpgrp
6403
6404Make the current process the leader of its process group.
6405[clinic start generated code]*/
6406
6407static PyObject *
6408os_setpgrp_impl(PyObject *module)
6409/*[clinic end generated code: output=2554735b0a60f0a0 input=1f0619fcb5731e7e]*/
6410{
6411#ifdef SETPGRP_HAVE_ARG
6412 if (setpgrp(0, 0) < 0)
6413#else /* SETPGRP_HAVE_ARG */
6414 if (setpgrp() < 0)
6415#endif /* SETPGRP_HAVE_ARG */
6416 return posix_error();
6417 Py_RETURN_NONE;
6418}
6419#endif /* HAVE_SETPGRP */
6420
6421#ifdef HAVE_GETPPID
6422
6423#ifdef MS_WINDOWS
6424#include <tlhelp32.h>
6425
6426static PyObject*
6427win32_getppid()
6428{
6429 HANDLE snapshot;
6430 pid_t mypid;
6431 PyObject* result = NULL;
6432 BOOL have_record;
6433 PROCESSENTRY32 pe;
6434
6435 mypid = getpid(); /* This function never fails */
6436
6437 snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
6438 if (snapshot == INVALID_HANDLE_VALUE)
6439 return PyErr_SetFromWindowsErr(GetLastError());
6440
6441 pe.dwSize = sizeof(pe);
6442 have_record = Process32First(snapshot, &pe);
6443 while (have_record) {
6444 if (mypid == (pid_t)pe.th32ProcessID) {
6445 /* We could cache the ulong value in a static variable. */
6446 result = PyLong_FromPid((pid_t)pe.th32ParentProcessID);
6447 break;
6448 }
6449
6450 have_record = Process32Next(snapshot, &pe);
6451 }
6452
6453 /* If our loop exits and our pid was not found (result will be NULL)
6454 * then GetLastError will return ERROR_NO_MORE_FILES. This is an
6455 * error anyway, so let's raise it. */
6456 if (!result)
6457 result = PyErr_SetFromWindowsErr(GetLastError());
6458
6459 CloseHandle(snapshot);
6460
6461 return result;
6462}
6463#endif /*MS_WINDOWS*/
6464
6465
6466/*[clinic input]
6467os.getppid
6468
6469Return the parent's process id.
6470
6471If the parent process has already exited, Windows machines will still
6472return its id; others systems will return the id of the 'init' process (1).
6473[clinic start generated code]*/
6474
6475static PyObject *
6476os_getppid_impl(PyObject *module)
6477/*[clinic end generated code: output=43b2a946a8c603b4 input=e637cb87539c030e]*/
6478{
6479#ifdef MS_WINDOWS
6480 return win32_getppid();
6481#else
6482 return PyLong_FromPid(getppid());
6483#endif
6484}
6485#endif /* HAVE_GETPPID */
6486
6487
6488#ifdef HAVE_GETLOGIN
6489/*[clinic input]
6490os.getlogin
6491
6492Return the actual login name.
6493[clinic start generated code]*/
6494
6495static PyObject *
6496os_getlogin_impl(PyObject *module)
6497/*[clinic end generated code: output=a32e66a7e5715dac input=2a21ab1e917163df]*/
6498{
6499 PyObject *result = NULL;
6500#ifdef MS_WINDOWS
6501 wchar_t user_name[UNLEN + 1];
6502 DWORD num_chars = Py_ARRAY_LENGTH(user_name);
6503
6504 if (GetUserNameW(user_name, &num_chars)) {
6505 /* num_chars is the number of unicode chars plus null terminator */
6506 result = PyUnicode_FromWideChar(user_name, num_chars - 1);
6507 }
6508 else
6509 result = PyErr_SetFromWindowsErr(GetLastError());
6510#else
6511 char *name;
6512 int old_errno = errno;
6513
6514 errno = 0;
6515 name = getlogin();
6516 if (name == NULL) {
6517 if (errno)
6518 posix_error();
6519 else
6520 PyErr_SetString(PyExc_OSError, "unable to determine login name");
6521 }
6522 else
6523 result = PyUnicode_DecodeFSDefault(name);
6524 errno = old_errno;
6525#endif
6526 return result;
6527}
6528#endif /* HAVE_GETLOGIN */
6529
6530
6531#ifdef HAVE_GETUID
6532/*[clinic input]
6533os.getuid
6534
6535Return the current process's user id.
6536[clinic start generated code]*/
6537
6538static PyObject *
6539os_getuid_impl(PyObject *module)
6540/*[clinic end generated code: output=415c0b401ebed11a input=b53c8b35f110a516]*/
6541{
6542 return _PyLong_FromUid(getuid());
6543}
6544#endif /* HAVE_GETUID */
6545
6546
6547#ifdef MS_WINDOWS
6548#define HAVE_KILL
6549#endif /* MS_WINDOWS */
6550
6551#ifdef HAVE_KILL
6552/*[clinic input]
6553os.kill
6554
6555 pid: pid_t
6556 signal: Py_ssize_t
6557 /
6558
6559Kill a process with a signal.
6560[clinic start generated code]*/
6561
6562static PyObject *
6563os_kill_impl(PyObject *module, pid_t pid, Py_ssize_t signal)
6564/*[clinic end generated code: output=8e346a6701c88568 input=61a36b86ca275ab9]*/
6565#ifndef MS_WINDOWS
6566{
6567 if (kill(pid, (int)signal) == -1)
6568 return posix_error();
6569 Py_RETURN_NONE;
6570}
6571#else /* !MS_WINDOWS */
6572{
6573 PyObject *result;
6574 DWORD sig = (DWORD)signal;
6575 DWORD err;
6576 HANDLE handle;
6577
6578 /* Console processes which share a common console can be sent CTRL+C or
6579 CTRL+BREAK events, provided they handle said events. */
6580 if (sig == CTRL_C_EVENT || sig == CTRL_BREAK_EVENT) {
6581 if (GenerateConsoleCtrlEvent(sig, (DWORD)pid) == 0) {
6582 err = GetLastError();
6583 PyErr_SetFromWindowsErr(err);
6584 }
6585 else
6586 Py_RETURN_NONE;
6587 }
6588
6589 /* If the signal is outside of what GenerateConsoleCtrlEvent can use,
6590 attempt to open and terminate the process. */
6591 handle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, (DWORD)pid);
6592 if (handle == NULL) {
6593 err = GetLastError();
6594 return PyErr_SetFromWindowsErr(err);
6595 }
6596
6597 if (TerminateProcess(handle, sig) == 0) {
6598 err = GetLastError();
6599 result = PyErr_SetFromWindowsErr(err);
6600 } else {
6601 Py_INCREF(Py_None);
6602 result = Py_None;
6603 }
6604
6605 CloseHandle(handle);
6606 return result;
6607}
6608#endif /* !MS_WINDOWS */
6609#endif /* HAVE_KILL */
6610
6611
6612#ifdef HAVE_KILLPG
6613/*[clinic input]
6614os.killpg
6615
6616 pgid: pid_t
6617 signal: int
6618 /
6619
6620Kill a process group with a signal.
6621[clinic start generated code]*/
6622
6623static PyObject *
6624os_killpg_impl(PyObject *module, pid_t pgid, int signal)
6625/*[clinic end generated code: output=6dbcd2f1fdf5fdba input=38b5449eb8faec19]*/
6626{
6627 /* XXX some man pages make the `pgid` parameter an int, others
6628 a pid_t. Since getpgrp() returns a pid_t, we assume killpg should
6629 take the same type. Moreover, pid_t is always at least as wide as
6630 int (else compilation of this module fails), which is safe. */
6631 if (killpg(pgid, signal) == -1)
6632 return posix_error();
6633 Py_RETURN_NONE;
6634}
6635#endif /* HAVE_KILLPG */
6636
6637
6638#ifdef HAVE_PLOCK
6639#ifdef HAVE_SYS_LOCK_H
6640#include <sys/lock.h>
6641#endif
6642
6643/*[clinic input]
6644os.plock
6645 op: int
6646 /
6647
6648Lock program segments into memory.");
6649[clinic start generated code]*/
6650
6651static PyObject *
6652os_plock_impl(PyObject *module, int op)
6653/*[clinic end generated code: output=81424167033b168e input=e6e5e348e1525f60]*/
6654{
6655 if (plock(op) == -1)
6656 return posix_error();
6657 Py_RETURN_NONE;
6658}
6659#endif /* HAVE_PLOCK */
6660
6661
6662#ifdef HAVE_SETUID
6663/*[clinic input]
6664os.setuid
6665
6666 uid: uid_t
6667 /
6668
6669Set the current process's user id.
6670[clinic start generated code]*/
6671
6672static PyObject *
6673os_setuid_impl(PyObject *module, uid_t uid)
6674/*[clinic end generated code: output=a0a41fd0d1ec555f input=c921a3285aa22256]*/
6675{
6676 if (setuid(uid) < 0)
6677 return posix_error();
6678 Py_RETURN_NONE;
6679}
6680#endif /* HAVE_SETUID */
6681
6682
6683#ifdef HAVE_SETEUID
6684/*[clinic input]
6685os.seteuid
6686
6687 euid: uid_t
6688 /
6689
6690Set the current process's effective user id.
6691[clinic start generated code]*/
6692
6693static PyObject *
6694os_seteuid_impl(PyObject *module, uid_t euid)
6695/*[clinic end generated code: output=102e3ad98361519a input=ba93d927e4781aa9]*/
6696{
6697 if (seteuid(euid) < 0)
6698 return posix_error();
6699 Py_RETURN_NONE;
6700}
6701#endif /* HAVE_SETEUID */
6702
6703
6704#ifdef HAVE_SETEGID
6705/*[clinic input]
6706os.setegid
6707
6708 egid: gid_t
6709 /
6710
6711Set the current process's effective group id.
6712[clinic start generated code]*/
6713
6714static PyObject *
6715os_setegid_impl(PyObject *module, gid_t egid)
6716/*[clinic end generated code: output=4e4b825a6a10258d input=4080526d0ccd6ce3]*/
6717{
6718 if (setegid(egid) < 0)
6719 return posix_error();
6720 Py_RETURN_NONE;
6721}
6722#endif /* HAVE_SETEGID */
6723
6724
6725#ifdef HAVE_SETREUID
6726/*[clinic input]
6727os.setreuid
6728
6729 ruid: uid_t
6730 euid: uid_t
6731 /
6732
6733Set the current process's real and effective user ids.
6734[clinic start generated code]*/
6735
6736static PyObject *
6737os_setreuid_impl(PyObject *module, uid_t ruid, uid_t euid)
6738/*[clinic end generated code: output=62d991210006530a input=0ca8978de663880c]*/
6739{
6740 if (setreuid(ruid, euid) < 0) {
6741 return posix_error();
6742 } else {
6743 Py_RETURN_NONE;
6744 }
6745}
6746#endif /* HAVE_SETREUID */
6747
6748
6749#ifdef HAVE_SETREGID
6750/*[clinic input]
6751os.setregid
6752
6753 rgid: gid_t
6754 egid: gid_t
6755 /
6756
6757Set the current process's real and effective group ids.
6758[clinic start generated code]*/
6759
6760static PyObject *
6761os_setregid_impl(PyObject *module, gid_t rgid, gid_t egid)
6762/*[clinic end generated code: output=aa803835cf5342f3 input=c59499f72846db78]*/
6763{
6764 if (setregid(rgid, egid) < 0)
6765 return posix_error();
6766 Py_RETURN_NONE;
6767}
6768#endif /* HAVE_SETREGID */
6769
6770
6771#ifdef HAVE_SETGID
6772/*[clinic input]
6773os.setgid
6774 gid: gid_t
6775 /
6776
6777Set the current process's group id.
6778[clinic start generated code]*/
6779
6780static PyObject *
6781os_setgid_impl(PyObject *module, gid_t gid)
6782/*[clinic end generated code: output=bdccd7403f6ad8c3 input=27d30c4059045dc6]*/
6783{
6784 if (setgid(gid) < 0)
6785 return posix_error();
6786 Py_RETURN_NONE;
6787}
6788#endif /* HAVE_SETGID */
6789
6790
6791#ifdef HAVE_SETGROUPS
6792/*[clinic input]
6793os.setgroups
6794
6795 groups: object
6796 /
6797
6798Set the groups of the current process to list.
6799[clinic start generated code]*/
6800
6801static PyObject *
6802os_setgroups(PyObject *module, PyObject *groups)
6803/*[clinic end generated code: output=3fcb32aad58c5ecd input=fa742ca3daf85a7e]*/
6804{
6805 Py_ssize_t i, len;
6806 gid_t grouplist[MAX_GROUPS];
6807
6808 if (!PySequence_Check(groups)) {
6809 PyErr_SetString(PyExc_TypeError, "setgroups argument must be a sequence");
6810 return NULL;
6811 }
6812 len = PySequence_Size(groups);
6813 if (len < 0) {
6814 return NULL;
6815 }
6816 if (len > MAX_GROUPS) {
6817 PyErr_SetString(PyExc_ValueError, "too many groups");
6818 return NULL;
6819 }
6820 for(i = 0; i < len; i++) {
6821 PyObject *elem;
6822 elem = PySequence_GetItem(groups, i);
6823 if (!elem)
6824 return NULL;
6825 if (!PyLong_Check(elem)) {
6826 PyErr_SetString(PyExc_TypeError,
6827 "groups must be integers");
6828 Py_DECREF(elem);
6829 return NULL;
6830 } else {
6831 if (!_Py_Gid_Converter(elem, &grouplist[i])) {
6832 Py_DECREF(elem);
6833 return NULL;
6834 }
6835 }
6836 Py_DECREF(elem);
6837 }
6838
6839 if (setgroups(len, grouplist) < 0)
6840 return posix_error();
6841 Py_RETURN_NONE;
6842}
6843#endif /* HAVE_SETGROUPS */
6844
6845#if defined(HAVE_WAIT3) || defined(HAVE_WAIT4)
6846static PyObject *
6847wait_helper(pid_t pid, int status, struct rusage *ru)
6848{
6849 PyObject *result;
6850 static PyObject *struct_rusage;
6851 _Py_IDENTIFIER(struct_rusage);
6852
6853 if (pid == -1)
6854 return posix_error();
6855
6856 if (struct_rusage == NULL) {
6857 PyObject *m = PyImport_ImportModuleNoBlock("resource");
6858 if (m == NULL)
6859 return NULL;
6860 struct_rusage = _PyObject_GetAttrId(m, &PyId_struct_rusage);
6861 Py_DECREF(m);
6862 if (struct_rusage == NULL)
6863 return NULL;
6864 }
6865
6866 /* XXX(nnorwitz): Copied (w/mods) from resource.c, there should be only one. */
6867 result = PyStructSequence_New((PyTypeObject*) struct_rusage);
6868 if (!result)
6869 return NULL;
6870
6871#ifndef doubletime
6872#define doubletime(TV) ((double)(TV).tv_sec + (TV).tv_usec * 0.000001)
6873#endif
6874
6875 PyStructSequence_SET_ITEM(result, 0,
6876 PyFloat_FromDouble(doubletime(ru->ru_utime)));
6877 PyStructSequence_SET_ITEM(result, 1,
6878 PyFloat_FromDouble(doubletime(ru->ru_stime)));
6879#define SET_INT(result, index, value)\
6880 PyStructSequence_SET_ITEM(result, index, PyLong_FromLong(value))
6881 SET_INT(result, 2, ru->ru_maxrss);
6882 SET_INT(result, 3, ru->ru_ixrss);
6883 SET_INT(result, 4, ru->ru_idrss);
6884 SET_INT(result, 5, ru->ru_isrss);
6885 SET_INT(result, 6, ru->ru_minflt);
6886 SET_INT(result, 7, ru->ru_majflt);
6887 SET_INT(result, 8, ru->ru_nswap);
6888 SET_INT(result, 9, ru->ru_inblock);
6889 SET_INT(result, 10, ru->ru_oublock);
6890 SET_INT(result, 11, ru->ru_msgsnd);
6891 SET_INT(result, 12, ru->ru_msgrcv);
6892 SET_INT(result, 13, ru->ru_nsignals);
6893 SET_INT(result, 14, ru->ru_nvcsw);
6894 SET_INT(result, 15, ru->ru_nivcsw);
6895#undef SET_INT
6896
6897 if (PyErr_Occurred()) {
6898 Py_DECREF(result);
6899 return NULL;
6900 }
6901
6902 return Py_BuildValue("NiN", PyLong_FromPid(pid), status, result);
6903}
6904#endif /* HAVE_WAIT3 || HAVE_WAIT4 */
6905
6906
6907#ifdef HAVE_WAIT3
6908/*[clinic input]
6909os.wait3
6910
6911 options: int
6912Wait for completion of a child process.
6913
6914Returns a tuple of information about the child process:
6915 (pid, status, rusage)
6916[clinic start generated code]*/
6917
6918static PyObject *
6919os_wait3_impl(PyObject *module, int options)
6920/*[clinic end generated code: output=92c3224e6f28217a input=8ac4c56956b61710]*/
6921{
6922 pid_t pid;
6923 struct rusage ru;
6924 int async_err = 0;
6925 WAIT_TYPE status;
6926 WAIT_STATUS_INT(status) = 0;
6927
6928 do {
6929 Py_BEGIN_ALLOW_THREADS
6930 pid = wait3(&status, options, &ru);
6931 Py_END_ALLOW_THREADS
6932 } while (pid < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
6933 if (pid < 0)
6934 return (!async_err) ? posix_error() : NULL;
6935
6936 return wait_helper(pid, WAIT_STATUS_INT(status), &ru);
6937}
6938#endif /* HAVE_WAIT3 */
6939
6940
6941#ifdef HAVE_WAIT4
6942/*[clinic input]
6943
6944os.wait4
6945
6946 pid: pid_t
6947 options: int
6948
6949Wait for completion of a specific child process.
6950
6951Returns a tuple of information about the child process:
6952 (pid, status, rusage)
6953[clinic start generated code]*/
6954
6955static PyObject *
6956os_wait4_impl(PyObject *module, pid_t pid, int options)
6957/*[clinic end generated code: output=66195aa507b35f70 input=d11deed0750600ba]*/
6958{
6959 pid_t res;
6960 struct rusage ru;
6961 int async_err = 0;
6962 WAIT_TYPE status;
6963 WAIT_STATUS_INT(status) = 0;
6964
6965 do {
6966 Py_BEGIN_ALLOW_THREADS
6967 res = wait4(pid, &status, options, &ru);
6968 Py_END_ALLOW_THREADS
6969 } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
6970 if (res < 0)
6971 return (!async_err) ? posix_error() : NULL;
6972
6973 return wait_helper(res, WAIT_STATUS_INT(status), &ru);
6974}
6975#endif /* HAVE_WAIT4 */
6976
6977
6978#if defined(HAVE_WAITID) && !defined(__APPLE__)
6979/*[clinic input]
6980os.waitid
6981
6982 idtype: idtype_t
6983 Must be one of be P_PID, P_PGID or P_ALL.
6984 id: id_t
6985 The id to wait on.
6986 options: int
6987 Constructed from the ORing of one or more of WEXITED, WSTOPPED
6988 or WCONTINUED and additionally may be ORed with WNOHANG or WNOWAIT.
6989 /
6990
6991Returns the result of waiting for a process or processes.
6992
6993Returns either waitid_result or None if WNOHANG is specified and there are
6994no children in a waitable state.
6995[clinic start generated code]*/
6996
6997static PyObject *
6998os_waitid_impl(PyObject *module, idtype_t idtype, id_t id, int options)
6999/*[clinic end generated code: output=5d2e1c0bde61f4d8 input=d8e7f76e052b7920]*/
7000{
7001 PyObject *result;
7002 int res;
7003 int async_err = 0;
7004 siginfo_t si;
7005 si.si_pid = 0;
7006
7007 do {
7008 Py_BEGIN_ALLOW_THREADS
7009 res = waitid(idtype, id, &si, options);
7010 Py_END_ALLOW_THREADS
7011 } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
7012 if (res < 0)
7013 return (!async_err) ? posix_error() : NULL;
7014
7015 if (si.si_pid == 0)
7016 Py_RETURN_NONE;
7017
7018 result = PyStructSequence_New(&WaitidResultType);
7019 if (!result)
7020 return NULL;
7021
7022 PyStructSequence_SET_ITEM(result, 0, PyLong_FromPid(si.si_pid));
7023 PyStructSequence_SET_ITEM(result, 1, _PyLong_FromUid(si.si_uid));
7024 PyStructSequence_SET_ITEM(result, 2, PyLong_FromLong((long)(si.si_signo)));
7025 PyStructSequence_SET_ITEM(result, 3, PyLong_FromLong((long)(si.si_status)));
7026 PyStructSequence_SET_ITEM(result, 4, PyLong_FromLong((long)(si.si_code)));
7027 if (PyErr_Occurred()) {
7028 Py_DECREF(result);
7029 return NULL;
7030 }
7031
7032 return result;
7033}
7034#endif /* defined(HAVE_WAITID) && !defined(__APPLE__) */
7035
7036
7037#if defined(HAVE_WAITPID)
7038/*[clinic input]
7039os.waitpid
7040 pid: pid_t
7041 options: int
7042 /
7043
7044Wait for completion of a given child process.
7045
7046Returns a tuple of information regarding the child process:
7047 (pid, status)
7048
7049The options argument is ignored on Windows.
7050[clinic start generated code]*/
7051
7052static PyObject *
7053os_waitpid_impl(PyObject *module, pid_t pid, int options)
7054/*[clinic end generated code: output=5c37c06887a20270 input=0bf1666b8758fda3]*/
7055{
7056 pid_t res;
7057 int async_err = 0;
7058 WAIT_TYPE status;
7059 WAIT_STATUS_INT(status) = 0;
7060
7061 do {
7062 Py_BEGIN_ALLOW_THREADS
7063 res = waitpid(pid, &status, options);
7064 Py_END_ALLOW_THREADS
7065 } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
7066 if (res < 0)
7067 return (!async_err) ? posix_error() : NULL;
7068
7069 return Py_BuildValue("Ni", PyLong_FromPid(res), WAIT_STATUS_INT(status));
7070}
7071#elif defined(HAVE_CWAIT)
7072/* MS C has a variant of waitpid() that's usable for most purposes. */
7073/*[clinic input]
7074os.waitpid
7075 pid: intptr_t
7076 options: int
7077 /
7078
7079Wait for completion of a given process.
7080
7081Returns a tuple of information regarding the process:
7082 (pid, status << 8)
7083
7084The options argument is ignored on Windows.
7085[clinic start generated code]*/
7086
7087static PyObject *
7088os_waitpid_impl(PyObject *module, intptr_t pid, int options)
7089/*[clinic end generated code: output=be836b221271d538 input=40f2440c515410f8]*/
7090{
7091 int status;
7092 intptr_t res;
7093 int async_err = 0;
7094
7095 do {
7096 Py_BEGIN_ALLOW_THREADS
7097 _Py_BEGIN_SUPPRESS_IPH
7098 res = _cwait(&status, pid, options);
7099 _Py_END_SUPPRESS_IPH
7100 Py_END_ALLOW_THREADS
7101 } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
7102 if (res < 0)
7103 return (!async_err) ? posix_error() : NULL;
7104
7105 /* shift the status left a byte so this is more like the POSIX waitpid */
7106 return Py_BuildValue(_Py_PARSE_INTPTR "i", res, status << 8);
7107}
7108#endif
7109
7110
7111#ifdef HAVE_WAIT
7112/*[clinic input]
7113os.wait
7114
7115Wait for completion of a child process.
7116
7117Returns a tuple of information about the child process:
7118 (pid, status)
7119[clinic start generated code]*/
7120
7121static PyObject *
7122os_wait_impl(PyObject *module)
7123/*[clinic end generated code: output=6bc419ac32fb364b input=03b0182d4a4700ce]*/
7124{
7125 pid_t pid;
7126 int async_err = 0;
7127 WAIT_TYPE status;
7128 WAIT_STATUS_INT(status) = 0;
7129
7130 do {
7131 Py_BEGIN_ALLOW_THREADS
7132 pid = wait(&status);
7133 Py_END_ALLOW_THREADS
7134 } while (pid < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
7135 if (pid < 0)
7136 return (!async_err) ? posix_error() : NULL;
7137
7138 return Py_BuildValue("Ni", PyLong_FromPid(pid), WAIT_STATUS_INT(status));
7139}
7140#endif /* HAVE_WAIT */
7141
7142
7143#if defined(HAVE_READLINK) || defined(MS_WINDOWS)
7144PyDoc_STRVAR(readlink__doc__,
7145"readlink(path, *, dir_fd=None) -> path\n\n\
7146Return a string representing the path to which the symbolic link points.\n\
7147\n\
7148If dir_fd is not None, it should be a file descriptor open to a directory,\n\
7149 and path should be relative; path will then be relative to that directory.\n\
7150dir_fd may not be implemented on your platform.\n\
7151 If it is unavailable, using it will raise a NotImplementedError.");
7152#endif
7153
7154#ifdef HAVE_READLINK
7155
7156/* AC 3.5: merge win32 and not together */
7157static PyObject *
7158posix_readlink(PyObject *self, PyObject *args, PyObject *kwargs)
7159{
7160 path_t path;
7161 int dir_fd = DEFAULT_DIR_FD;
7162 char buffer[MAXPATHLEN+1];
7163 ssize_t length;
7164 PyObject *return_value = NULL;
7165 static char *keywords[] = {"path", "dir_fd", NULL};
7166
7167 memset(&path, 0, sizeof(path));
7168 path.function_name = "readlink";
7169 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O&|$O&:readlink", keywords,
7170 path_converter, &path,
7171 READLINKAT_DIR_FD_CONVERTER, &dir_fd))
7172 return NULL;
7173
7174 Py_BEGIN_ALLOW_THREADS
7175#ifdef HAVE_READLINKAT
7176 if (dir_fd != DEFAULT_DIR_FD)
7177 length = readlinkat(dir_fd, path.narrow, buffer, MAXPATHLEN);
7178 else
7179#endif
7180 length = readlink(path.narrow, buffer, MAXPATHLEN);
7181 Py_END_ALLOW_THREADS
7182
7183 if (length < 0) {
7184 return_value = path_error(&path);
7185 goto exit;
7186 }
7187 buffer[length] = '\0';
7188
7189 if (PyUnicode_Check(path.object))
7190 return_value = PyUnicode_DecodeFSDefaultAndSize(buffer, length);
7191 else
7192 return_value = PyBytes_FromStringAndSize(buffer, length);
7193exit:
7194 path_cleanup(&path);
7195 return return_value;
7196}
7197
7198#endif /* HAVE_READLINK */
7199
7200#if !defined(HAVE_READLINK) && defined(MS_WINDOWS)
7201
7202static PyObject *
7203win_readlink(PyObject *self, PyObject *args, PyObject *kwargs)
7204{
7205 const wchar_t *path;
7206 DWORD n_bytes_returned;
7207 DWORD io_result;
7208 PyObject *po, *result;
7209 int dir_fd;
7210 HANDLE reparse_point_handle;
7211
7212 char target_buffer[_Py_MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
7213 _Py_REPARSE_DATA_BUFFER *rdb = (_Py_REPARSE_DATA_BUFFER *)target_buffer;
7214 const wchar_t *print_name;
7215
7216 static char *keywords[] = {"path", "dir_fd", NULL};
7217
7218 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "U|$O&:readlink", keywords,
7219 &po,
7220 dir_fd_unavailable, &dir_fd
7221 ))
7222 return NULL;
7223
7224 path = _PyUnicode_AsUnicode(po);
7225 if (path == NULL)
7226 return NULL;
7227
7228 /* First get a handle to the reparse point */
7229 Py_BEGIN_ALLOW_THREADS
7230 reparse_point_handle = CreateFileW(
7231 path,
7232 0,
7233 0,
7234 0,
7235 OPEN_EXISTING,
7236 FILE_FLAG_OPEN_REPARSE_POINT|FILE_FLAG_BACKUP_SEMANTICS,
7237 0);
7238 Py_END_ALLOW_THREADS
7239
7240 if (reparse_point_handle==INVALID_HANDLE_VALUE)
7241 return win32_error_object("readlink", po);
7242
7243 Py_BEGIN_ALLOW_THREADS
7244 /* New call DeviceIoControl to read the reparse point */
7245 io_result = DeviceIoControl(
7246 reparse_point_handle,
7247 FSCTL_GET_REPARSE_POINT,
7248 0, 0, /* in buffer */
7249 target_buffer, sizeof(target_buffer),
7250 &n_bytes_returned,
7251 0 /* we're not using OVERLAPPED_IO */
7252 );
7253 CloseHandle(reparse_point_handle);
7254 Py_END_ALLOW_THREADS
7255
7256 if (io_result==0)
7257 return win32_error_object("readlink", po);
7258
7259 if (rdb->ReparseTag != IO_REPARSE_TAG_SYMLINK)
7260 {
7261 PyErr_SetString(PyExc_ValueError,
7262 "not a symbolic link");
7263 return NULL;
7264 }
7265 print_name = (wchar_t *)((char*)rdb->SymbolicLinkReparseBuffer.PathBuffer +
7266 rdb->SymbolicLinkReparseBuffer.PrintNameOffset);
7267
7268 result = PyUnicode_FromWideChar(print_name,
7269 rdb->SymbolicLinkReparseBuffer.PrintNameLength / sizeof(wchar_t));
7270 return result;
7271}
7272
7273#endif /* !defined(HAVE_READLINK) && defined(MS_WINDOWS) */
7274
7275
7276
7277#ifdef HAVE_SYMLINK
7278
7279#if defined(MS_WINDOWS)
7280
7281/* Grab CreateSymbolicLinkW dynamically from kernel32 */
7282static BOOLEAN (CALLBACK *Py_CreateSymbolicLinkW)(LPCWSTR, LPCWSTR, DWORD) = NULL;
7283
7284static int
7285check_CreateSymbolicLink(void)
7286{
7287 HINSTANCE hKernel32;
7288 /* only recheck */
7289 if (Py_CreateSymbolicLinkW)
7290 return 1;
7291 hKernel32 = GetModuleHandleW(L"KERNEL32");
7292 *(FARPROC*)&Py_CreateSymbolicLinkW = GetProcAddress(hKernel32,
7293 "CreateSymbolicLinkW");
7294 return Py_CreateSymbolicLinkW != NULL;
7295}
7296
7297/* Remove the last portion of the path - return 0 on success */
7298static int
7299_dirnameW(WCHAR *path)
7300{
7301 WCHAR *ptr;
7302 size_t length = wcsnlen_s(path, MAX_PATH);
7303 if (length == MAX_PATH) {
7304 return -1;
7305 }
7306
7307 /* walk the path from the end until a backslash is encountered */
7308 for(ptr = path + length; ptr != path; ptr--) {
7309 if (*ptr == L'\\' || *ptr == L'/') {
7310 break;
7311 }
7312 }
7313 *ptr = 0;
7314 return 0;
7315}
7316
7317/* Is this path absolute? */
7318static int
7319_is_absW(const WCHAR *path)
7320{
7321 return path[0] == L'\\' || path[0] == L'/' ||
7322 (path[0] && path[1] == L':');
7323}
7324
7325/* join root and rest with a backslash - return 0 on success */
7326static int
7327_joinW(WCHAR *dest_path, const WCHAR *root, const WCHAR *rest)
7328{
7329 if (_is_absW(rest)) {
7330 return wcscpy_s(dest_path, MAX_PATH, rest);
7331 }
7332
7333 if (wcscpy_s(dest_path, MAX_PATH, root)) {
7334 return -1;
7335 }
7336
7337 if (dest_path[0] && wcscat_s(dest_path, MAX_PATH, L"\\")) {
7338 return -1;
7339 }
7340
7341 return wcscat_s(dest_path, MAX_PATH, rest);
7342}
7343
7344/* Return True if the path at src relative to dest is a directory */
7345static int
7346_check_dirW(LPCWSTR src, LPCWSTR dest)
7347{
7348 WIN32_FILE_ATTRIBUTE_DATA src_info;
7349 WCHAR dest_parent[MAX_PATH];
7350 WCHAR src_resolved[MAX_PATH] = L"";
7351
7352 /* dest_parent = os.path.dirname(dest) */
7353 if (wcscpy_s(dest_parent, MAX_PATH, dest) ||
7354 _dirnameW(dest_parent)) {
7355 return 0;
7356 }
7357 /* src_resolved = os.path.join(dest_parent, src) */
7358 if (_joinW(src_resolved, dest_parent, src)) {
7359 return 0;
7360 }
7361 return (
7362 GetFileAttributesExW(src_resolved, GetFileExInfoStandard, &src_info)
7363 && src_info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY
7364 );
7365}
7366#endif
7367
7368
7369/*[clinic input]
7370os.symlink
7371 src: path_t
7372 dst: path_t
7373 target_is_directory: bool = False
7374 *
7375 dir_fd: dir_fd(requires='symlinkat')=None
7376
7377# "symlink(src, dst, target_is_directory=False, *, dir_fd=None)\n\n\
7378
7379Create a symbolic link pointing to src named dst.
7380
7381target_is_directory is required on Windows if the target is to be
7382 interpreted as a directory. (On Windows, symlink requires
7383 Windows 6.0 or greater, and raises a NotImplementedError otherwise.)
7384 target_is_directory is ignored on non-Windows platforms.
7385
7386If dir_fd is not None, it should be a file descriptor open to a directory,
7387 and path should be relative; path will then be relative to that directory.
7388dir_fd may not be implemented on your platform.
7389 If it is unavailable, using it will raise a NotImplementedError.
7390
7391[clinic start generated code]*/
7392
7393static PyObject *
7394os_symlink_impl(PyObject *module, path_t *src, path_t *dst,
7395 int target_is_directory, int dir_fd)
7396/*[clinic end generated code: output=08ca9f3f3cf960f6 input=e820ec4472547bc3]*/
7397{
7398#ifdef MS_WINDOWS
7399 DWORD result;
7400#else
7401 int result;
7402#endif
7403
7404#ifdef MS_WINDOWS
7405 if (!check_CreateSymbolicLink()) {
7406 PyErr_SetString(PyExc_NotImplementedError,
7407 "CreateSymbolicLink functions not found");
7408 return NULL;
7409 }
7410 if (!win32_can_symlink) {
7411 PyErr_SetString(PyExc_OSError, "symbolic link privilege not held");
7412 return NULL;
7413 }
7414#endif
7415
7416#ifdef MS_WINDOWS
7417
7418 Py_BEGIN_ALLOW_THREADS
7419 _Py_BEGIN_SUPPRESS_IPH
7420 /* if src is a directory, ensure target_is_directory==1 */
7421 target_is_directory |= _check_dirW(src->wide, dst->wide);
7422 result = Py_CreateSymbolicLinkW(dst->wide, src->wide,
7423 target_is_directory);
7424 _Py_END_SUPPRESS_IPH
7425 Py_END_ALLOW_THREADS
7426
7427 if (!result)
7428 return path_error2(src, dst);
7429
7430#else
7431
7432 if ((src->narrow && dst->wide) || (src->wide && dst->narrow)) {
7433 PyErr_SetString(PyExc_ValueError,
7434 "symlink: src and dst must be the same type");
7435 return NULL;
7436 }
7437
7438 Py_BEGIN_ALLOW_THREADS
7439#if HAVE_SYMLINKAT
7440 if (dir_fd != DEFAULT_DIR_FD)
7441 result = symlinkat(src->narrow, dir_fd, dst->narrow);
7442 else
7443#endif
7444 result = symlink(src->narrow, dst->narrow);
7445 Py_END_ALLOW_THREADS
7446
7447 if (result)
7448 return path_error2(src, dst);
7449#endif
7450
7451 Py_RETURN_NONE;
7452}
7453#endif /* HAVE_SYMLINK */
7454
7455
7456
7457
7458static PyStructSequence_Field times_result_fields[] = {
7459 {"user", "user time"},
7460 {"system", "system time"},
7461 {"children_user", "user time of children"},
7462 {"children_system", "system time of children"},
7463 {"elapsed", "elapsed time since an arbitrary point in the past"},
7464 {NULL}
7465};
7466
7467PyDoc_STRVAR(times_result__doc__,
7468"times_result: Result from os.times().\n\n\
7469This object may be accessed either as a tuple of\n\
7470 (user, system, children_user, children_system, elapsed),\n\
7471or via the attributes user, system, children_user, children_system,\n\
7472and elapsed.\n\
7473\n\
7474See os.times for more information.");
7475
7476static PyStructSequence_Desc times_result_desc = {
7477 "times_result", /* name */
7478 times_result__doc__, /* doc */
7479 times_result_fields,
7480 5
7481};
7482
7483static PyTypeObject TimesResultType;
7484
7485#ifdef MS_WINDOWS
7486#define HAVE_TIMES /* mandatory, for the method table */
7487#endif
7488
7489#ifdef HAVE_TIMES
7490
7491static PyObject *
7492build_times_result(double user, double system,
7493 double children_user, double children_system,
7494 double elapsed)
7495{
7496 PyObject *value = PyStructSequence_New(&TimesResultType);
7497 if (value == NULL)
7498 return NULL;
7499
7500#define SET(i, field) \
7501 { \
7502 PyObject *o = PyFloat_FromDouble(field); \
7503 if (!o) { \
7504 Py_DECREF(value); \
7505 return NULL; \
7506 } \
7507 PyStructSequence_SET_ITEM(value, i, o); \
7508 } \
7509
7510 SET(0, user);
7511 SET(1, system);
7512 SET(2, children_user);
7513 SET(3, children_system);
7514 SET(4, elapsed);
7515
7516#undef SET
7517
7518 return value;
7519}
7520
7521
7522#ifndef MS_WINDOWS
7523#define NEED_TICKS_PER_SECOND
7524static long ticks_per_second = -1;
7525#endif /* MS_WINDOWS */
7526
7527/*[clinic input]
7528os.times
7529
7530Return a collection containing process timing information.
7531
7532The object returned behaves like a named tuple with these fields:
7533 (utime, stime, cutime, cstime, elapsed_time)
7534All fields are floating point numbers.
7535[clinic start generated code]*/
7536
7537static PyObject *
7538os_times_impl(PyObject *module)
7539/*[clinic end generated code: output=35f640503557d32a input=2bf9df3d6ab2e48b]*/
7540#ifdef MS_WINDOWS
7541{
7542 FILETIME create, exit, kernel, user;
7543 HANDLE hProc;
7544 hProc = GetCurrentProcess();
7545 GetProcessTimes(hProc, &create, &exit, &kernel, &user);
7546 /* The fields of a FILETIME structure are the hi and lo part
7547 of a 64-bit value expressed in 100 nanosecond units.
7548 1e7 is one second in such units; 1e-7 the inverse.
7549 429.4967296 is 2**32 / 1e7 or 2**32 * 1e-7.
7550 */
7551 return build_times_result(
7552 (double)(user.dwHighDateTime*429.4967296 +
7553 user.dwLowDateTime*1e-7),
7554 (double)(kernel.dwHighDateTime*429.4967296 +
7555 kernel.dwLowDateTime*1e-7),
7556 (double)0,
7557 (double)0,
7558 (double)0);
7559}
7560#else /* MS_WINDOWS */
7561{
7562
7563
7564 struct tms t;
7565 clock_t c;
7566 errno = 0;
7567 c = times(&t);
7568 if (c == (clock_t) -1)
7569 return posix_error();
7570 return build_times_result(
7571 (double)t.tms_utime / ticks_per_second,
7572 (double)t.tms_stime / ticks_per_second,
7573 (double)t.tms_cutime / ticks_per_second,
7574 (double)t.tms_cstime / ticks_per_second,
7575 (double)c / ticks_per_second);
7576}
7577#endif /* MS_WINDOWS */
7578#endif /* HAVE_TIMES */
7579
7580
7581#ifdef HAVE_GETSID
7582/*[clinic input]
7583os.getsid
7584
7585 pid: pid_t
7586 /
7587
7588Call the system call getsid(pid) and return the result.
7589[clinic start generated code]*/
7590
7591static PyObject *
7592os_getsid_impl(PyObject *module, pid_t pid)
7593/*[clinic end generated code: output=112deae56b306460 input=eeb2b923a30ce04e]*/
7594{
7595 int sid;
7596 sid = getsid(pid);
7597 if (sid < 0)
7598 return posix_error();
7599 return PyLong_FromLong((long)sid);
7600}
7601#endif /* HAVE_GETSID */
7602
7603
7604#ifdef HAVE_SETSID
7605/*[clinic input]
7606os.setsid
7607
7608Call the system call setsid().
7609[clinic start generated code]*/
7610
7611static PyObject *
7612os_setsid_impl(PyObject *module)
7613/*[clinic end generated code: output=e2ddedd517086d77 input=5fff45858e2f0776]*/
7614{
7615 if (setsid() < 0)
7616 return posix_error();
7617 Py_RETURN_NONE;
7618}
7619#endif /* HAVE_SETSID */
7620
7621
7622#ifdef HAVE_SETPGID
7623/*[clinic input]
7624os.setpgid
7625
7626 pid: pid_t
7627 pgrp: pid_t
7628 /
7629
7630Call the system call setpgid(pid, pgrp).
7631[clinic start generated code]*/
7632
7633static PyObject *
7634os_setpgid_impl(PyObject *module, pid_t pid, pid_t pgrp)
7635/*[clinic end generated code: output=6461160319a43d6a input=fceb395eca572e1a]*/
7636{
7637 if (setpgid(pid, pgrp) < 0)
7638 return posix_error();
7639 Py_RETURN_NONE;
7640}
7641#endif /* HAVE_SETPGID */
7642
7643
7644#ifdef HAVE_TCGETPGRP
7645/*[clinic input]
7646os.tcgetpgrp
7647
7648 fd: int
7649 /
7650
7651Return the process group associated with the terminal specified by fd.
7652[clinic start generated code]*/
7653
7654static PyObject *
7655os_tcgetpgrp_impl(PyObject *module, int fd)
7656/*[clinic end generated code: output=f865e88be86c272b input=7f6c18eac10ada86]*/
7657{
7658 pid_t pgid = tcgetpgrp(fd);
7659 if (pgid < 0)
7660 return posix_error();
7661 return PyLong_FromPid(pgid);
7662}
7663#endif /* HAVE_TCGETPGRP */
7664
7665
7666#ifdef HAVE_TCSETPGRP
7667/*[clinic input]
7668os.tcsetpgrp
7669
7670 fd: int
7671 pgid: pid_t
7672 /
7673
7674Set the process group associated with the terminal specified by fd.
7675[clinic start generated code]*/
7676
7677static PyObject *
7678os_tcsetpgrp_impl(PyObject *module, int fd, pid_t pgid)
7679/*[clinic end generated code: output=f1821a381b9daa39 input=5bdc997c6a619020]*/
7680{
7681 if (tcsetpgrp(fd, pgid) < 0)
7682 return posix_error();
7683 Py_RETURN_NONE;
7684}
7685#endif /* HAVE_TCSETPGRP */
7686
7687/* Functions acting on file descriptors */
7688
7689#ifdef O_CLOEXEC
7690extern int _Py_open_cloexec_works;
7691#endif
7692
7693
7694/*[clinic input]
7695os.open -> int
7696 path: path_t
7697 flags: int
7698 mode: int = 0o777
7699 *
7700 dir_fd: dir_fd(requires='openat') = None
7701
7702# "open(path, flags, mode=0o777, *, dir_fd=None)\n\n\
7703
7704Open a file for low level IO. Returns a file descriptor (integer).
7705
7706If dir_fd is not None, it should be a file descriptor open to a directory,
7707 and path should be relative; path will then be relative to that directory.
7708dir_fd may not be implemented on your platform.
7709 If it is unavailable, using it will raise a NotImplementedError.
7710[clinic start generated code]*/
7711
7712static int
7713os_open_impl(PyObject *module, path_t *path, int flags, int mode, int dir_fd)
7714/*[clinic end generated code: output=abc7227888c8bc73 input=ad8623b29acd2934]*/
7715{
7716 int fd;
7717 int async_err = 0;
7718
7719#ifdef O_CLOEXEC
7720 int *atomic_flag_works = &_Py_open_cloexec_works;
7721#elif !defined(MS_WINDOWS)
7722 int *atomic_flag_works = NULL;
7723#endif
7724
7725#ifdef MS_WINDOWS
7726 flags |= O_NOINHERIT;
7727#elif defined(O_CLOEXEC)
7728 flags |= O_CLOEXEC;
7729#endif
7730
7731 _Py_BEGIN_SUPPRESS_IPH
7732 do {
7733 Py_BEGIN_ALLOW_THREADS
7734#ifdef MS_WINDOWS
7735 fd = _wopen(path->wide, flags, mode);
7736#else
7737#ifdef HAVE_OPENAT
7738 if (dir_fd != DEFAULT_DIR_FD)
7739 fd = openat(dir_fd, path->narrow, flags, mode);
7740 else
7741#endif /* HAVE_OPENAT */
7742 fd = open(path->narrow, flags, mode);
7743#endif /* !MS_WINDOWS */
7744 Py_END_ALLOW_THREADS
7745 } while (fd < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
7746 _Py_END_SUPPRESS_IPH
7747
7748 if (fd < 0) {
7749 if (!async_err)
7750 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, path->object);
7751 return -1;
7752 }
7753
7754#ifndef MS_WINDOWS
7755 if (_Py_set_inheritable(fd, 0, atomic_flag_works) < 0) {
7756 close(fd);
7757 return -1;
7758 }
7759#endif
7760
7761 return fd;
7762}
7763
7764
7765/*[clinic input]
7766os.close
7767
7768 fd: int
7769
7770Close a file descriptor.
7771[clinic start generated code]*/
7772
7773static PyObject *
7774os_close_impl(PyObject *module, int fd)
7775/*[clinic end generated code: output=2fe4e93602822c14 input=2bc42451ca5c3223]*/
7776{
7777 int res;
7778 /* We do not want to retry upon EINTR: see http://lwn.net/Articles/576478/
7779 * and http://linux.derkeiler.com/Mailing-Lists/Kernel/2005-09/3000.html
7780 * for more details.
7781 */
7782 Py_BEGIN_ALLOW_THREADS
7783 _Py_BEGIN_SUPPRESS_IPH
7784 res = close(fd);
7785 _Py_END_SUPPRESS_IPH
7786 Py_END_ALLOW_THREADS
7787 if (res < 0)
7788 return posix_error();
7789 Py_RETURN_NONE;
7790}
7791
7792
7793/*[clinic input]
7794os.closerange
7795
7796 fd_low: int
7797 fd_high: int
7798 /
7799
7800Closes all file descriptors in [fd_low, fd_high), ignoring errors.
7801[clinic start generated code]*/
7802
7803static PyObject *
7804os_closerange_impl(PyObject *module, int fd_low, int fd_high)
7805/*[clinic end generated code: output=0ce5c20fcda681c2 input=5855a3d053ebd4ec]*/
7806{
7807 int i;
7808 Py_BEGIN_ALLOW_THREADS
7809 _Py_BEGIN_SUPPRESS_IPH
7810 for (i = Py_MAX(fd_low, 0); i < fd_high; i++)
7811 close(i);
7812 _Py_END_SUPPRESS_IPH
7813 Py_END_ALLOW_THREADS
7814 Py_RETURN_NONE;
7815}
7816
7817
7818/*[clinic input]
7819os.dup -> int
7820
7821 fd: int
7822 /
7823
7824Return a duplicate of a file descriptor.
7825[clinic start generated code]*/
7826
7827static int
7828os_dup_impl(PyObject *module, int fd)
7829/*[clinic end generated code: output=486f4860636b2a9f input=6f10f7ea97f7852a]*/
7830{
7831 return _Py_dup(fd);
7832}
7833
7834
7835/*[clinic input]
7836os.dup2 -> int
7837 fd: int
7838 fd2: int
7839 inheritable: bool=True
7840
7841Duplicate file descriptor.
7842[clinic start generated code]*/
7843
7844static int
7845os_dup2_impl(PyObject *module, int fd, int fd2, int inheritable)
7846/*[clinic end generated code: output=bc059d34a73404d1 input=c3cddda8922b038d]*/
7847{
7848 int res = 0;
7849#if defined(HAVE_DUP3) && \
7850 !(defined(HAVE_FCNTL_H) && defined(F_DUP2FD_CLOEXEC))
7851 /* dup3() is available on Linux 2.6.27+ and glibc 2.9 */
7852 static int dup3_works = -1;
7853#endif
7854
7855 if (fd < 0 || fd2 < 0) {
7856 posix_error();
7857 return -1;
7858 }
7859
7860 /* dup2() can fail with EINTR if the target FD is already open, because it
7861 * then has to be closed. See os_close_impl() for why we don't handle EINTR
7862 * upon close(), and therefore below.
7863 */
7864#ifdef MS_WINDOWS
7865 Py_BEGIN_ALLOW_THREADS
7866 _Py_BEGIN_SUPPRESS_IPH
7867 res = dup2(fd, fd2);
7868 _Py_END_SUPPRESS_IPH
7869 Py_END_ALLOW_THREADS
7870 if (res < 0) {
7871 posix_error();
7872 return -1;
7873 }
7874 res = fd2; // msvcrt dup2 returns 0 on success.
7875
7876 /* Character files like console cannot be make non-inheritable */
7877 if (!inheritable && _Py_set_inheritable(fd2, 0, NULL) < 0) {
7878 close(fd2);
7879 return -1;
7880 }
7881
7882#elif defined(HAVE_FCNTL_H) && defined(F_DUP2FD_CLOEXEC)
7883 Py_BEGIN_ALLOW_THREADS
7884 if (!inheritable)
7885 res = fcntl(fd, F_DUP2FD_CLOEXEC, fd2);
7886 else
7887 res = dup2(fd, fd2);
7888 Py_END_ALLOW_THREADS
7889 if (res < 0) {
7890 posix_error();
7891 return -1;
7892 }
7893
7894#else
7895
7896#ifdef HAVE_DUP3
7897 if (!inheritable && dup3_works != 0) {
7898 Py_BEGIN_ALLOW_THREADS
7899 res = dup3(fd, fd2, O_CLOEXEC);
7900 Py_END_ALLOW_THREADS
7901 if (res < 0) {
7902 if (dup3_works == -1)
7903 dup3_works = (errno != ENOSYS);
7904 if (dup3_works) {
7905 posix_error();
7906 return -1;
7907 }
7908 }
7909 }
7910
7911 if (inheritable || dup3_works == 0)
7912 {
7913#endif
7914 Py_BEGIN_ALLOW_THREADS
7915 res = dup2(fd, fd2);
7916 Py_END_ALLOW_THREADS
7917 if (res < 0) {
7918 posix_error();
7919 return -1;
7920 }
7921
7922 if (!inheritable && _Py_set_inheritable(fd2, 0, NULL) < 0) {
7923 close(fd2);
7924 return -1;
7925 }
7926#ifdef HAVE_DUP3
7927 }
7928#endif
7929
7930#endif
7931
7932 return res;
7933}
7934
7935
7936#ifdef HAVE_LOCKF
7937/*[clinic input]
7938os.lockf
7939
7940 fd: int
7941 An open file descriptor.
7942 command: int
7943 One of F_LOCK, F_TLOCK, F_ULOCK or F_TEST.
7944 length: Py_off_t
7945 The number of bytes to lock, starting at the current position.
7946 /
7947
7948Apply, test or remove a POSIX lock on an open file descriptor.
7949
7950[clinic start generated code]*/
7951
7952static PyObject *
7953os_lockf_impl(PyObject *module, int fd, int command, Py_off_t length)
7954/*[clinic end generated code: output=af7051f3e7c29651 input=65da41d2106e9b79]*/
7955{
7956 int res;
7957
7958 Py_BEGIN_ALLOW_THREADS
7959 res = lockf(fd, command, length);
7960 Py_END_ALLOW_THREADS
7961
7962 if (res < 0)
7963 return posix_error();
7964
7965 Py_RETURN_NONE;
7966}
7967#endif /* HAVE_LOCKF */
7968
7969
7970/*[clinic input]
7971os.lseek -> Py_off_t
7972
7973 fd: int
7974 position: Py_off_t
7975 how: int
7976 /
7977
7978Set the position of a file descriptor. Return the new position.
7979
7980Return the new cursor position in number of bytes
7981relative to the beginning of the file.
7982[clinic start generated code]*/
7983
7984static Py_off_t
7985os_lseek_impl(PyObject *module, int fd, Py_off_t position, int how)
7986/*[clinic end generated code: output=971e1efb6b30bd2f input=902654ad3f96a6d3]*/
7987{
7988 Py_off_t result;
7989
7990#ifdef SEEK_SET
7991 /* Turn 0, 1, 2 into SEEK_{SET,CUR,END} */
7992 switch (how) {
7993 case 0: how = SEEK_SET; break;
7994 case 1: how = SEEK_CUR; break;
7995 case 2: how = SEEK_END; break;
7996 }
7997#endif /* SEEK_END */
7998
7999 if (PyErr_Occurred())
8000 return -1;
8001
8002 Py_BEGIN_ALLOW_THREADS
8003 _Py_BEGIN_SUPPRESS_IPH
8004#ifdef MS_WINDOWS
8005 result = _lseeki64(fd, position, how);
8006#else
8007 result = lseek(fd, position, how);
8008#endif
8009 _Py_END_SUPPRESS_IPH
8010 Py_END_ALLOW_THREADS
8011 if (result < 0)
8012 posix_error();
8013
8014 return result;
8015}
8016
8017
8018/*[clinic input]
8019os.read
8020 fd: int
8021 length: Py_ssize_t
8022 /
8023
8024Read from a file descriptor. Returns a bytes object.
8025[clinic start generated code]*/
8026
8027static PyObject *
8028os_read_impl(PyObject *module, int fd, Py_ssize_t length)
8029/*[clinic end generated code: output=dafbe9a5cddb987b input=1df2eaa27c0bf1d3]*/
8030{
8031 Py_ssize_t n;
8032 PyObject *buffer;
8033
8034 if (length < 0) {
8035 errno = EINVAL;
8036 return posix_error();
8037 }
8038
8039 length = Py_MIN(length, _PY_READ_MAX);
8040
8041 buffer = PyBytes_FromStringAndSize((char *)NULL, length);
8042 if (buffer == NULL)
8043 return NULL;
8044
8045 n = _Py_read(fd, PyBytes_AS_STRING(buffer), length);
8046 if (n == -1) {
8047 Py_DECREF(buffer);
8048 return NULL;
8049 }
8050
8051 if (n != length)
8052 _PyBytes_Resize(&buffer, n);
8053
8054 return buffer;
8055}
8056
8057#if (defined(HAVE_SENDFILE) && (defined(__FreeBSD__) || defined(__DragonFly__) \
8058 || defined(__APPLE__))) \
8059 || defined(HAVE_READV) || defined(HAVE_PREADV) || defined (HAVE_PREADV2) \
8060 || defined(HAVE_WRITEV) || defined(HAVE_PWRITEV) || defined (HAVE_PWRITEV2)
8061static int
8062iov_setup(struct iovec **iov, Py_buffer **buf, PyObject *seq, Py_ssize_t cnt, int type)
8063{
8064 Py_ssize_t i, j;
8065
8066 *iov = PyMem_New(struct iovec, cnt);
8067 if (*iov == NULL) {
8068 PyErr_NoMemory();
8069 return -1;
8070 }
8071
8072 *buf = PyMem_New(Py_buffer, cnt);
8073 if (*buf == NULL) {
8074 PyMem_Del(*iov);
8075 PyErr_NoMemory();
8076 return -1;
8077 }
8078
8079 for (i = 0; i < cnt; i++) {
8080 PyObject *item = PySequence_GetItem(seq, i);
8081 if (item == NULL)
8082 goto fail;
8083 if (PyObject_GetBuffer(item, &(*buf)[i], type) == -1) {
8084 Py_DECREF(item);
8085 goto fail;
8086 }
8087 Py_DECREF(item);
8088 (*iov)[i].iov_base = (*buf)[i].buf;
8089 (*iov)[i].iov_len = (*buf)[i].len;
8090 }
8091 return 0;
8092
8093fail:
8094 PyMem_Del(*iov);
8095 for (j = 0; j < i; j++) {
8096 PyBuffer_Release(&(*buf)[j]);
8097 }
8098 PyMem_Del(*buf);
8099 return -1;
8100}
8101
8102static void
8103iov_cleanup(struct iovec *iov, Py_buffer *buf, int cnt)
8104{
8105 int i;
8106 PyMem_Del(iov);
8107 for (i = 0; i < cnt; i++) {
8108 PyBuffer_Release(&buf[i]);
8109 }
8110 PyMem_Del(buf);
8111}
8112#endif
8113
8114
8115#ifdef HAVE_READV
8116/*[clinic input]
8117os.readv -> Py_ssize_t
8118
8119 fd: int
8120 buffers: object
8121 /
8122
8123Read from a file descriptor fd into an iterable of buffers.
8124
8125The buffers should be mutable buffers accepting bytes.
8126readv will transfer data into each buffer until it is full
8127and then move on to the next buffer in the sequence to hold
8128the rest of the data.
8129
8130readv returns the total number of bytes read,
8131which may be less than the total capacity of all the buffers.
8132[clinic start generated code]*/
8133
8134static Py_ssize_t
8135os_readv_impl(PyObject *module, int fd, PyObject *buffers)
8136/*[clinic end generated code: output=792da062d3fcebdb input=e679eb5dbfa0357d]*/
8137{
8138 Py_ssize_t cnt, n;
8139 int async_err = 0;
8140 struct iovec *iov;
8141 Py_buffer *buf;
8142
8143 if (!PySequence_Check(buffers)) {
8144 PyErr_SetString(PyExc_TypeError,
8145 "readv() arg 2 must be a sequence");
8146 return -1;
8147 }
8148
8149 cnt = PySequence_Size(buffers);
8150 if (cnt < 0)
8151 return -1;
8152
8153 if (iov_setup(&iov, &buf, buffers, cnt, PyBUF_WRITABLE) < 0)
8154 return -1;
8155
8156 do {
8157 Py_BEGIN_ALLOW_THREADS
8158 n = readv(fd, iov, cnt);
8159 Py_END_ALLOW_THREADS
8160 } while (n < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
8161
8162 iov_cleanup(iov, buf, cnt);
8163 if (n < 0) {
8164 if (!async_err)
8165 posix_error();
8166 return -1;
8167 }
8168
8169 return n;
8170}
8171#endif /* HAVE_READV */
8172
8173
8174#ifdef HAVE_PREAD
8175/*[clinic input]
8176# TODO length should be size_t! but Python doesn't support parsing size_t yet.
8177os.pread
8178
8179 fd: int
8180 length: int
8181 offset: Py_off_t
8182 /
8183
8184Read a number of bytes from a file descriptor starting at a particular offset.
8185
8186Read length bytes from file descriptor fd, starting at offset bytes from
8187the beginning of the file. The file offset remains unchanged.
8188[clinic start generated code]*/
8189
8190static PyObject *
8191os_pread_impl(PyObject *module, int fd, int length, Py_off_t offset)
8192/*[clinic end generated code: output=435b29ee32b54a78 input=084948dcbaa35d4c]*/
8193{
8194 Py_ssize_t n;
8195 int async_err = 0;
8196 PyObject *buffer;
8197
8198 if (length < 0) {
8199 errno = EINVAL;
8200 return posix_error();
8201 }
8202 buffer = PyBytes_FromStringAndSize((char *)NULL, length);
8203 if (buffer == NULL)
8204 return NULL;
8205
8206 do {
8207 Py_BEGIN_ALLOW_THREADS
8208 _Py_BEGIN_SUPPRESS_IPH
8209 n = pread(fd, PyBytes_AS_STRING(buffer), length, offset);
8210 _Py_END_SUPPRESS_IPH
8211 Py_END_ALLOW_THREADS
8212 } while (n < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
8213
8214 if (n < 0) {
8215 Py_DECREF(buffer);
8216 return (!async_err) ? posix_error() : NULL;
8217 }
8218 if (n != length)
8219 _PyBytes_Resize(&buffer, n);
8220 return buffer;
8221}
8222#endif /* HAVE_PREAD */
8223
8224#if defined(HAVE_PREADV) || defined (HAVE_PREADV2)
8225/*[clinic input]
8226os.preadv -> Py_ssize_t
8227
8228 fd: int
8229 buffers: object
8230 offset: Py_off_t
8231 flags: int = 0
8232 /
8233
8234Reads from a file descriptor into a number of mutable bytes-like objects.
8235
8236Combines the functionality of readv() and pread(). As readv(), it will
8237transfer data into each buffer until it is full and then move on to the next
8238buffer in the sequence to hold the rest of the data. Its fourth argument,
8239specifies the file offset at which the input operation is to be performed. It
8240will return the total number of bytes read (which can be less than the total
8241capacity of all the objects).
8242
8243The flags argument contains a bitwise OR of zero or more of the following flags:
8244
8245- RWF_HIPRI
8246- RWF_NOWAIT
8247
8248Using non-zero flags requires Linux 4.6 or newer.
8249[clinic start generated code]*/
8250
8251static Py_ssize_t
8252os_preadv_impl(PyObject *module, int fd, PyObject *buffers, Py_off_t offset,
8253 int flags)
8254/*[clinic end generated code: output=26fc9c6e58e7ada5 input=4173919dc1f7ed99]*/
8255{
8256 Py_ssize_t cnt, n;
8257 int async_err = 0;
8258 struct iovec *iov;
8259 Py_buffer *buf;
8260
8261 if (!PySequence_Check(buffers)) {
8262 PyErr_SetString(PyExc_TypeError,
8263 "preadv2() arg 2 must be a sequence");
8264 return -1;
8265 }
8266
8267 cnt = PySequence_Size(buffers);
8268 if (cnt < 0) {
8269 return -1;
8270 }
8271
8272#ifndef HAVE_PREADV2
8273 if(flags != 0) {
8274 argument_unavailable_error("preadv2", "flags");
8275 return -1;
8276 }
8277#endif
8278
8279 if (iov_setup(&iov, &buf, buffers, cnt, PyBUF_WRITABLE) < 0) {
8280 return -1;
8281 }
8282#ifdef HAVE_PREADV2
8283 do {
8284 Py_BEGIN_ALLOW_THREADS
8285 _Py_BEGIN_SUPPRESS_IPH
8286 n = preadv2(fd, iov, cnt, offset, flags);
8287 _Py_END_SUPPRESS_IPH
8288 Py_END_ALLOW_THREADS
8289 } while (n < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
8290#else
8291 do {
8292 Py_BEGIN_ALLOW_THREADS
8293 _Py_BEGIN_SUPPRESS_IPH
8294 n = preadv(fd, iov, cnt, offset);
8295 _Py_END_SUPPRESS_IPH
8296 Py_END_ALLOW_THREADS
8297 } while (n < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
8298#endif
8299
8300 iov_cleanup(iov, buf, cnt);
8301 if (n < 0) {
8302 if (!async_err) {
8303 posix_error();
8304 }
8305 return -1;
8306 }
8307
8308 return n;
8309}
8310#endif /* HAVE_PREADV */
8311
8312
8313/*[clinic input]
8314os.write -> Py_ssize_t
8315
8316 fd: int
8317 data: Py_buffer
8318 /
8319
8320Write a bytes object to a file descriptor.
8321[clinic start generated code]*/
8322
8323static Py_ssize_t
8324os_write_impl(PyObject *module, int fd, Py_buffer *data)
8325/*[clinic end generated code: output=e4ef5bc904b58ef9 input=3207e28963234f3c]*/
8326{
8327 return _Py_write(fd, data->buf, data->len);
8328}
8329
8330#ifdef HAVE_SENDFILE
8331PyDoc_STRVAR(posix_sendfile__doc__,
8332"sendfile(out, in, offset, count) -> byteswritten\n\
8333sendfile(out, in, offset, count[, headers][, trailers], flags=0)\n\
8334 -> byteswritten\n\
8335Copy count bytes from file descriptor in to file descriptor out.");
8336
8337/* AC 3.5: don't bother converting, has optional group*/
8338static PyObject *
8339posix_sendfile(PyObject *self, PyObject *args, PyObject *kwdict)
8340{
8341 int in, out;
8342 Py_ssize_t ret;
8343 int async_err = 0;
8344 off_t offset;
8345
8346#if defined(__FreeBSD__) || defined(__DragonFly__) || defined(__APPLE__)
8347#ifndef __APPLE__
8348 Py_ssize_t len;
8349#endif
8350 PyObject *headers = NULL, *trailers = NULL;
8351 Py_buffer *hbuf, *tbuf;
8352 off_t sbytes;
8353 struct sf_hdtr sf;
8354 int flags = 0;
8355 /* Beware that "in" clashes with Python's own "in" operator keyword */
8356 static char *keywords[] = {"out", "in",
8357 "offset", "count",
8358 "headers", "trailers", "flags", NULL};
8359
8360 sf.headers = NULL;
8361 sf.trailers = NULL;
8362
8363#ifdef __APPLE__
8364 if (!PyArg_ParseTupleAndKeywords(args, kwdict, "iiO&O&|OOi:sendfile",
8365 keywords, &out, &in, Py_off_t_converter, &offset, Py_off_t_converter, &sbytes,
8366#else
8367 if (!PyArg_ParseTupleAndKeywords(args, kwdict, "iiO&n|OOi:sendfile",
8368 keywords, &out, &in, Py_off_t_converter, &offset, &len,
8369#endif
8370 &headers, &trailers, &flags))
8371 return NULL;
8372 if (headers != NULL) {
8373 if (!PySequence_Check(headers)) {
8374 PyErr_SetString(PyExc_TypeError,
8375 "sendfile() headers must be a sequence");
8376 return NULL;
8377 } else {
8378 Py_ssize_t i = PySequence_Size(headers);
8379 if (i < 0)
8380 return NULL;
8381 if (i > INT_MAX) {
8382 PyErr_SetString(PyExc_OverflowError,
8383 "sendfile() header is too large");
8384 return NULL;
8385 }
8386 if (i > 0) {
8387 sf.hdr_cnt = (int)i;
8388 if (iov_setup(&(sf.headers), &hbuf,
8389 headers, sf.hdr_cnt, PyBUF_SIMPLE) < 0)
8390 return NULL;
8391#ifdef __APPLE__
8392 for (i = 0; i < sf.hdr_cnt; i++) {
8393 Py_ssize_t blen = sf.headers[i].iov_len;
8394# define OFF_T_MAX 0x7fffffffffffffff
8395 if (sbytes >= OFF_T_MAX - blen) {
8396 PyErr_SetString(PyExc_OverflowError,
8397 "sendfile() header is too large");
8398 return NULL;
8399 }
8400 sbytes += blen;
8401 }
8402#endif
8403 }
8404 }
8405 }
8406 if (trailers != NULL) {
8407 if (!PySequence_Check(trailers)) {
8408 PyErr_SetString(PyExc_TypeError,
8409 "sendfile() trailers must be a sequence");
8410 return NULL;
8411 } else {
8412 Py_ssize_t i = PySequence_Size(trailers);
8413 if (i < 0)
8414 return NULL;
8415 if (i > INT_MAX) {
8416 PyErr_SetString(PyExc_OverflowError,
8417 "sendfile() trailer is too large");
8418 return NULL;
8419 }
8420 if (i > 0) {
8421 sf.trl_cnt = (int)i;
8422 if (iov_setup(&(sf.trailers), &tbuf,
8423 trailers, sf.trl_cnt, PyBUF_SIMPLE) < 0)
8424 return NULL;
8425 }
8426 }
8427 }
8428
8429 _Py_BEGIN_SUPPRESS_IPH
8430 do {
8431 Py_BEGIN_ALLOW_THREADS
8432#ifdef __APPLE__
8433 ret = sendfile(in, out, offset, &sbytes, &sf, flags);
8434#else
8435 ret = sendfile(in, out, offset, len, &sf, &sbytes, flags);
8436#endif
8437 Py_END_ALLOW_THREADS
8438 } while (ret < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
8439 _Py_END_SUPPRESS_IPH
8440
8441 if (sf.headers != NULL)
8442 iov_cleanup(sf.headers, hbuf, sf.hdr_cnt);
8443 if (sf.trailers != NULL)
8444 iov_cleanup(sf.trailers, tbuf, sf.trl_cnt);
8445
8446 if (ret < 0) {
8447 if ((errno == EAGAIN) || (errno == EBUSY)) {
8448 if (sbytes != 0) {
8449 // some data has been sent
8450 goto done;
8451 }
8452 else {
8453 // no data has been sent; upper application is supposed
8454 // to retry on EAGAIN or EBUSY
8455 return posix_error();
8456 }
8457 }
8458 return (!async_err) ? posix_error() : NULL;
8459 }
8460 goto done;
8461
8462done:
8463 #if !defined(HAVE_LARGEFILE_SUPPORT)
8464 return Py_BuildValue("l", sbytes);
8465 #else
8466 return Py_BuildValue("L", sbytes);
8467 #endif
8468
8469#else
8470 Py_ssize_t count;
8471 PyObject *offobj;
8472 static char *keywords[] = {"out", "in",
8473 "offset", "count", NULL};
8474 if (!PyArg_ParseTupleAndKeywords(args, kwdict, "iiOn:sendfile",
8475 keywords, &out, &in, &offobj, &count))
8476 return NULL;
8477#ifdef __linux__
8478 if (offobj == Py_None) {
8479 do {
8480 Py_BEGIN_ALLOW_THREADS
8481 ret = sendfile(out, in, NULL, count);
8482 Py_END_ALLOW_THREADS
8483 } while (ret < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
8484 if (ret < 0)
8485 return (!async_err) ? posix_error() : NULL;
8486 return Py_BuildValue("n", ret);
8487 }
8488#endif
8489 if (!Py_off_t_converter(offobj, &offset))
8490 return NULL;
8491
8492 do {
8493 Py_BEGIN_ALLOW_THREADS
8494 ret = sendfile(out, in, &offset, count);
8495 Py_END_ALLOW_THREADS
8496 } while (ret < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
8497 if (ret < 0)
8498 return (!async_err) ? posix_error() : NULL;
8499 return Py_BuildValue("n", ret);
8500#endif
8501}
8502#endif /* HAVE_SENDFILE */
8503
8504
8505/*[clinic input]
8506os.fstat
8507
8508 fd : int
8509
8510Perform a stat system call on the given file descriptor.
8511
8512Like stat(), but for an open file descriptor.
8513Equivalent to os.stat(fd).
8514[clinic start generated code]*/
8515
8516static PyObject *
8517os_fstat_impl(PyObject *module, int fd)
8518/*[clinic end generated code: output=efc038cb5f654492 input=27e0e0ebbe5600c9]*/
8519{
8520 STRUCT_STAT st;
8521 int res;
8522 int async_err = 0;
8523
8524 do {
8525 Py_BEGIN_ALLOW_THREADS
8526 res = FSTAT(fd, &st);
8527 Py_END_ALLOW_THREADS
8528 } while (res != 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
8529 if (res != 0) {
8530#ifdef MS_WINDOWS
8531 return PyErr_SetFromWindowsErr(0);
8532#else
8533 return (!async_err) ? posix_error() : NULL;
8534#endif
8535 }
8536
8537 return _pystat_fromstructstat(&st);
8538}
8539
8540
8541/*[clinic input]
8542os.isatty -> bool
8543 fd: int
8544 /
8545
8546Return True if the fd is connected to a terminal.
8547
8548Return True if the file descriptor is an open file descriptor
8549connected to the slave end of a terminal.
8550[clinic start generated code]*/
8551
8552static int
8553os_isatty_impl(PyObject *module, int fd)
8554/*[clinic end generated code: output=6a48c8b4e644ca00 input=08ce94aa1eaf7b5e]*/
8555{
8556 int return_value;
8557 _Py_BEGIN_SUPPRESS_IPH
8558 return_value = isatty(fd);
8559 _Py_END_SUPPRESS_IPH
8560 return return_value;
8561}
8562
8563
8564#ifdef HAVE_PIPE
8565/*[clinic input]
8566os.pipe
8567
8568Create a pipe.
8569
8570Returns a tuple of two file descriptors:
8571 (read_fd, write_fd)
8572[clinic start generated code]*/
8573
8574static PyObject *
8575os_pipe_impl(PyObject *module)
8576/*[clinic end generated code: output=ff9b76255793b440 input=02535e8c8fa6c4d4]*/
8577{
8578 int fds[2];
8579#ifdef MS_WINDOWS
8580 HANDLE read, write;
8581 SECURITY_ATTRIBUTES attr;
8582 BOOL ok;
8583#else
8584 int res;
8585#endif
8586
8587#ifdef MS_WINDOWS
8588 attr.nLength = sizeof(attr);
8589 attr.lpSecurityDescriptor = NULL;
8590 attr.bInheritHandle = FALSE;
8591
8592 Py_BEGIN_ALLOW_THREADS
8593 _Py_BEGIN_SUPPRESS_IPH
8594 ok = CreatePipe(&read, &write, &attr, 0);
8595 if (ok) {
8596 fds[0] = _open_osfhandle((intptr_t)read, _O_RDONLY);
8597 fds[1] = _open_osfhandle((intptr_t)write, _O_WRONLY);
8598 if (fds[0] == -1 || fds[1] == -1) {
8599 CloseHandle(read);
8600 CloseHandle(write);
8601 ok = 0;
8602 }
8603 }
8604 _Py_END_SUPPRESS_IPH
8605 Py_END_ALLOW_THREADS
8606
8607 if (!ok)
8608 return PyErr_SetFromWindowsErr(0);
8609#else
8610
8611#ifdef HAVE_PIPE2
8612 Py_BEGIN_ALLOW_THREADS
8613 res = pipe2(fds, O_CLOEXEC);
8614 Py_END_ALLOW_THREADS
8615
8616 if (res != 0 && errno == ENOSYS)
8617 {
8618#endif
8619 Py_BEGIN_ALLOW_THREADS
8620 res = pipe(fds);
8621 Py_END_ALLOW_THREADS
8622
8623 if (res == 0) {
8624 if (_Py_set_inheritable(fds[0], 0, NULL) < 0) {
8625 close(fds[0]);
8626 close(fds[1]);
8627 return NULL;
8628 }
8629 if (_Py_set_inheritable(fds[1], 0, NULL) < 0) {
8630 close(fds[0]);
8631 close(fds[1]);
8632 return NULL;
8633 }
8634 }
8635#ifdef HAVE_PIPE2
8636 }
8637#endif
8638
8639 if (res != 0)
8640 return PyErr_SetFromErrno(PyExc_OSError);
8641#endif /* !MS_WINDOWS */
8642 return Py_BuildValue("(ii)", fds[0], fds[1]);
8643}
8644#endif /* HAVE_PIPE */
8645
8646
8647#ifdef HAVE_PIPE2
8648/*[clinic input]
8649os.pipe2
8650
8651 flags: int
8652 /
8653
8654Create a pipe with flags set atomically.
8655
8656Returns a tuple of two file descriptors:
8657 (read_fd, write_fd)
8658
8659flags can be constructed by ORing together one or more of these values:
8660O_NONBLOCK, O_CLOEXEC.
8661[clinic start generated code]*/
8662
8663static PyObject *
8664os_pipe2_impl(PyObject *module, int flags)
8665/*[clinic end generated code: output=25751fb43a45540f input=f261b6e7e63c6817]*/
8666{
8667 int fds[2];
8668 int res;
8669
8670 res = pipe2(fds, flags);
8671 if (res != 0)
8672 return posix_error();
8673 return Py_BuildValue("(ii)", fds[0], fds[1]);
8674}
8675#endif /* HAVE_PIPE2 */
8676
8677
8678#ifdef HAVE_WRITEV
8679/*[clinic input]
8680os.writev -> Py_ssize_t
8681 fd: int
8682 buffers: object
8683 /
8684
8685Iterate over buffers, and write the contents of each to a file descriptor.
8686
8687Returns the total number of bytes written.
8688buffers must be a sequence of bytes-like objects.
8689[clinic start generated code]*/
8690
8691static Py_ssize_t
8692os_writev_impl(PyObject *module, int fd, PyObject *buffers)
8693/*[clinic end generated code: output=56565cfac3aac15b input=5b8d17fe4189d2fe]*/
8694{
8695 Py_ssize_t cnt;
8696 Py_ssize_t result;
8697 int async_err = 0;
8698 struct iovec *iov;
8699 Py_buffer *buf;
8700
8701 if (!PySequence_Check(buffers)) {
8702 PyErr_SetString(PyExc_TypeError,
8703 "writev() arg 2 must be a sequence");
8704 return -1;
8705 }
8706 cnt = PySequence_Size(buffers);
8707 if (cnt < 0)
8708 return -1;
8709
8710 if (iov_setup(&iov, &buf, buffers, cnt, PyBUF_SIMPLE) < 0) {
8711 return -1;
8712 }
8713
8714 do {
8715 Py_BEGIN_ALLOW_THREADS
8716 result = writev(fd, iov, cnt);
8717 Py_END_ALLOW_THREADS
8718 } while (result < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
8719
8720 iov_cleanup(iov, buf, cnt);
8721 if (result < 0 && !async_err)
8722 posix_error();
8723
8724 return result;
8725}
8726#endif /* HAVE_WRITEV */
8727
8728
8729#ifdef HAVE_PWRITE
8730/*[clinic input]
8731os.pwrite -> Py_ssize_t
8732
8733 fd: int
8734 buffer: Py_buffer
8735 offset: Py_off_t
8736 /
8737
8738Write bytes to a file descriptor starting at a particular offset.
8739
8740Write buffer to fd, starting at offset bytes from the beginning of
8741the file. Returns the number of bytes writte. Does not change the
8742current file offset.
8743[clinic start generated code]*/
8744
8745static Py_ssize_t
8746os_pwrite_impl(PyObject *module, int fd, Py_buffer *buffer, Py_off_t offset)
8747/*[clinic end generated code: output=c74da630758ee925 input=19903f1b3dd26377]*/
8748{
8749 Py_ssize_t size;
8750 int async_err = 0;
8751
8752 do {
8753 Py_BEGIN_ALLOW_THREADS
8754 _Py_BEGIN_SUPPRESS_IPH
8755 size = pwrite(fd, buffer->buf, (size_t)buffer->len, offset);
8756 _Py_END_SUPPRESS_IPH
8757 Py_END_ALLOW_THREADS
8758 } while (size < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
8759
8760 if (size < 0 && !async_err)
8761 posix_error();
8762 return size;
8763}
8764#endif /* HAVE_PWRITE */
8765
8766#if defined(HAVE_PWRITEV) || defined (HAVE_PWRITEV2)
8767/*[clinic input]
8768os.pwritev -> Py_ssize_t
8769
8770 fd: int
8771 buffers: object
8772 offset: Py_off_t
8773 flags: int = 0
8774 /
8775
8776Writes the contents of bytes-like objects to a file descriptor at a given offset.
8777
8778Combines the functionality of writev() and pwrite(). All buffers must be a sequence
8779of bytes-like objects. Buffers are processed in array order. Entire contents of first
8780buffer is written before proceeding to second, and so on. The operating system may
8781set a limit (sysconf() value SC_IOV_MAX) on the number of buffers that can be used.
8782This function writes the contents of each object to the file descriptor and returns
8783the total number of bytes written.
8784
8785The flags argument contains a bitwise OR of zero or more of the following flags:
8786
8787- RWF_DSYNC
8788- RWF_SYNC
8789
8790Using non-zero flags requires Linux 4.7 or newer.
8791[clinic start generated code]*/
8792
8793static Py_ssize_t
8794os_pwritev_impl(PyObject *module, int fd, PyObject *buffers, Py_off_t offset,
8795 int flags)
8796/*[clinic end generated code: output=e3dd3e9d11a6a5c7 input=803dc5ddbf0cfd3b]*/
8797{
8798 Py_ssize_t cnt;
8799 Py_ssize_t result;
8800 int async_err = 0;
8801 struct iovec *iov;
8802 Py_buffer *buf;
8803
8804 if (!PySequence_Check(buffers)) {
8805 PyErr_SetString(PyExc_TypeError,
8806 "pwritev() arg 2 must be a sequence");
8807 return -1;
8808 }
8809
8810 cnt = PySequence_Size(buffers);
8811 if (cnt < 0) {
8812 return -1;
8813 }
8814
8815#ifndef HAVE_PWRITEV2
8816 if(flags != 0) {
8817 argument_unavailable_error("pwritev2", "flags");
8818 return -1;
8819 }
8820#endif
8821
8822 if (iov_setup(&iov, &buf, buffers, cnt, PyBUF_SIMPLE) < 0) {
8823 return -1;
8824 }
8825#ifdef HAVE_PWRITEV2
8826 do {
8827 Py_BEGIN_ALLOW_THREADS
8828 _Py_BEGIN_SUPPRESS_IPH
8829 result = pwritev2(fd, iov, cnt, offset, flags);
8830 _Py_END_SUPPRESS_IPH
8831 Py_END_ALLOW_THREADS
8832 } while (result < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
8833#else
8834 do {
8835 Py_BEGIN_ALLOW_THREADS
8836 _Py_BEGIN_SUPPRESS_IPH
8837 result = pwritev(fd, iov, cnt, offset);
8838 _Py_END_SUPPRESS_IPH
8839 Py_END_ALLOW_THREADS
8840 } while (result < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
8841#endif
8842
8843 iov_cleanup(iov, buf, cnt);
8844 if (result < 0) {
8845 if (!async_err) {
8846 posix_error();
8847 }
8848 return -1;
8849 }
8850
8851 return result;
8852}
8853#endif /* HAVE_PWRITEV */
8854
8855
8856
8857
8858#ifdef HAVE_MKFIFO
8859/*[clinic input]
8860os.mkfifo
8861
8862 path: path_t
8863 mode: int=0o666
8864 *
8865 dir_fd: dir_fd(requires='mkfifoat')=None
8866
8867Create a "fifo" (a POSIX named pipe).
8868
8869If dir_fd is not None, it should be a file descriptor open to a directory,
8870 and path should be relative; path will then be relative to that directory.
8871dir_fd may not be implemented on your platform.
8872 If it is unavailable, using it will raise a NotImplementedError.
8873[clinic start generated code]*/
8874
8875static PyObject *
8876os_mkfifo_impl(PyObject *module, path_t *path, int mode, int dir_fd)
8877/*[clinic end generated code: output=ce41cfad0e68c940 input=73032e98a36e0e19]*/
8878{
8879 int result;
8880 int async_err = 0;
8881
8882 do {
8883 Py_BEGIN_ALLOW_THREADS
8884#ifdef HAVE_MKFIFOAT
8885 if (dir_fd != DEFAULT_DIR_FD)
8886 result = mkfifoat(dir_fd, path->narrow, mode);
8887 else
8888#endif
8889 result = mkfifo(path->narrow, mode);
8890 Py_END_ALLOW_THREADS
8891 } while (result != 0 && errno == EINTR &&
8892 !(async_err = PyErr_CheckSignals()));
8893 if (result != 0)
8894 return (!async_err) ? posix_error() : NULL;
8895
8896 Py_RETURN_NONE;
8897}
8898#endif /* HAVE_MKFIFO */
8899
8900
8901#if defined(HAVE_MKNOD) && defined(HAVE_MAKEDEV)
8902/*[clinic input]
8903os.mknod
8904
8905 path: path_t
8906 mode: int=0o600
8907 device: dev_t=0
8908 *
8909 dir_fd: dir_fd(requires='mknodat')=None
8910
8911Create a node in the file system.
8912
8913Create a node in the file system (file, device special file or named pipe)
8914at path. mode specifies both the permissions to use and the
8915type of node to be created, being combined (bitwise OR) with one of
8916S_IFREG, S_IFCHR, S_IFBLK, and S_IFIFO. If S_IFCHR or S_IFBLK is set on mode,
8917device defines the newly created device special file (probably using
8918os.makedev()). Otherwise device is ignored.
8919
8920If dir_fd is not None, it should be a file descriptor open to a directory,
8921 and path should be relative; path will then be relative to that directory.
8922dir_fd may not be implemented on your platform.
8923 If it is unavailable, using it will raise a NotImplementedError.
8924[clinic start generated code]*/
8925
8926static PyObject *
8927os_mknod_impl(PyObject *module, path_t *path, int mode, dev_t device,
8928 int dir_fd)
8929/*[clinic end generated code: output=92e55d3ca8917461 input=ee44531551a4d83b]*/
8930{
8931 int result;
8932 int async_err = 0;
8933
8934 do {
8935 Py_BEGIN_ALLOW_THREADS
8936#ifdef HAVE_MKNODAT
8937 if (dir_fd != DEFAULT_DIR_FD)
8938 result = mknodat(dir_fd, path->narrow, mode, device);
8939 else
8940#endif
8941 result = mknod(path->narrow, mode, device);
8942 Py_END_ALLOW_THREADS
8943 } while (result != 0 && errno == EINTR &&
8944 !(async_err = PyErr_CheckSignals()));
8945 if (result != 0)
8946 return (!async_err) ? posix_error() : NULL;
8947
8948 Py_RETURN_NONE;
8949}
8950#endif /* defined(HAVE_MKNOD) && defined(HAVE_MAKEDEV) */
8951
8952
8953#ifdef HAVE_DEVICE_MACROS
8954/*[clinic input]
8955os.major -> unsigned_int
8956
8957 device: dev_t
8958 /
8959
8960Extracts a device major number from a raw device number.
8961[clinic start generated code]*/
8962
8963static unsigned int
8964os_major_impl(PyObject *module, dev_t device)
8965/*[clinic end generated code: output=5b3b2589bafb498e input=1e16a4d30c4d4462]*/
8966{
8967 return major(device);
8968}
8969
8970
8971/*[clinic input]
8972os.minor -> unsigned_int
8973
8974 device: dev_t
8975 /
8976
8977Extracts a device minor number from a raw device number.
8978[clinic start generated code]*/
8979
8980static unsigned int
8981os_minor_impl(PyObject *module, dev_t device)
8982/*[clinic end generated code: output=5e1a25e630b0157d input=0842c6d23f24c65e]*/
8983{
8984 return minor(device);
8985}
8986
8987
8988/*[clinic input]
8989os.makedev -> dev_t
8990
8991 major: int
8992 minor: int
8993 /
8994
8995Composes a raw device number from the major and minor device numbers.
8996[clinic start generated code]*/
8997
8998static dev_t
8999os_makedev_impl(PyObject *module, int major, int minor)
9000/*[clinic end generated code: output=881aaa4aba6f6a52 input=4b9fd8fc73cbe48f]*/
9001{
9002 return makedev(major, minor);
9003}
9004#endif /* HAVE_DEVICE_MACROS */
9005
9006
9007#if defined HAVE_FTRUNCATE || defined MS_WINDOWS
9008/*[clinic input]
9009os.ftruncate
9010
9011 fd: int
9012 length: Py_off_t
9013 /
9014
9015Truncate a file, specified by file descriptor, to a specific length.
9016[clinic start generated code]*/
9017
9018static PyObject *
9019os_ftruncate_impl(PyObject *module, int fd, Py_off_t length)
9020/*[clinic end generated code: output=fba15523721be7e4 input=63b43641e52818f2]*/
9021{
9022 int result;
9023 int async_err = 0;
9024
9025 do {
9026 Py_BEGIN_ALLOW_THREADS
9027 _Py_BEGIN_SUPPRESS_IPH
9028#ifdef MS_WINDOWS
9029 result = _chsize_s(fd, length);
9030#else
9031 result = ftruncate(fd, length);
9032#endif
9033 _Py_END_SUPPRESS_IPH
9034 Py_END_ALLOW_THREADS
9035 } while (result != 0 && errno == EINTR &&
9036 !(async_err = PyErr_CheckSignals()));
9037 if (result != 0)
9038 return (!async_err) ? posix_error() : NULL;
9039 Py_RETURN_NONE;
9040}
9041#endif /* HAVE_FTRUNCATE || MS_WINDOWS */
9042
9043
9044#if defined HAVE_TRUNCATE || defined MS_WINDOWS
9045/*[clinic input]
9046os.truncate
9047 path: path_t(allow_fd='PATH_HAVE_FTRUNCATE')
9048 length: Py_off_t
9049
9050Truncate a file, specified by path, to a specific length.
9051
9052On some platforms, path may also be specified as an open file descriptor.
9053 If this functionality is unavailable, using it raises an exception.
9054[clinic start generated code]*/
9055
9056static PyObject *
9057os_truncate_impl(PyObject *module, path_t *path, Py_off_t length)
9058/*[clinic end generated code: output=43009c8df5c0a12b input=77229cf0b50a9b77]*/
9059{
9060 int result;
9061#ifdef MS_WINDOWS
9062 int fd;
9063#endif
9064
9065 if (path->fd != -1)
9066 return os_ftruncate_impl(module, path->fd, length);
9067
9068 Py_BEGIN_ALLOW_THREADS
9069 _Py_BEGIN_SUPPRESS_IPH
9070#ifdef MS_WINDOWS
9071 fd = _wopen(path->wide, _O_WRONLY | _O_BINARY | _O_NOINHERIT);
9072 if (fd < 0)
9073 result = -1;
9074 else {
9075 result = _chsize_s(fd, length);
9076 close(fd);
9077 if (result < 0)
9078 errno = result;
9079 }
9080#else
9081 result = truncate(path->narrow, length);
9082#endif
9083 _Py_END_SUPPRESS_IPH
9084 Py_END_ALLOW_THREADS
9085 if (result < 0)
9086 return posix_path_error(path);
9087
9088 Py_RETURN_NONE;
9089}
9090#endif /* HAVE_TRUNCATE || MS_WINDOWS */
9091
9092
9093/* Issue #22396: On 32-bit AIX platform, the prototypes of os.posix_fadvise()
9094 and os.posix_fallocate() in system headers are wrong if _LARGE_FILES is
9095 defined, which is the case in Python on AIX. AIX bug report:
9096 http://www-01.ibm.com/support/docview.wss?uid=isg1IV56170 */
9097#if defined(_AIX) && defined(_LARGE_FILES) && !defined(__64BIT__)
9098# define POSIX_FADVISE_AIX_BUG
9099#endif
9100
9101
9102#if defined(HAVE_POSIX_FALLOCATE) && !defined(POSIX_FADVISE_AIX_BUG)
9103/*[clinic input]
9104os.posix_fallocate
9105
9106 fd: int
9107 offset: Py_off_t
9108 length: Py_off_t
9109 /
9110
9111Ensure a file has allocated at least a particular number of bytes on disk.
9112
9113Ensure that the file specified by fd encompasses a range of bytes
9114starting at offset bytes from the beginning and continuing for length bytes.
9115[clinic start generated code]*/
9116
9117static PyObject *
9118os_posix_fallocate_impl(PyObject *module, int fd, Py_off_t offset,
9119 Py_off_t length)
9120/*[clinic end generated code: output=73f107139564aa9d input=d7a2ef0ab2ca52fb]*/
9121{
9122 int result;
9123 int async_err = 0;
9124
9125 do {
9126 Py_BEGIN_ALLOW_THREADS
9127 result = posix_fallocate(fd, offset, length);
9128 Py_END_ALLOW_THREADS
9129 } while (result == EINTR && !(async_err = PyErr_CheckSignals()));
9130
9131 if (result == 0)
9132 Py_RETURN_NONE;
9133
9134 if (async_err)
9135 return NULL;
9136
9137 errno = result;
9138 return posix_error();
9139}
9140#endif /* HAVE_POSIX_FALLOCATE) && !POSIX_FADVISE_AIX_BUG */
9141
9142
9143#if defined(HAVE_POSIX_FADVISE) && !defined(POSIX_FADVISE_AIX_BUG)
9144/*[clinic input]
9145os.posix_fadvise
9146
9147 fd: int
9148 offset: Py_off_t
9149 length: Py_off_t
9150 advice: int
9151 /
9152
9153Announce an intention to access data in a specific pattern.
9154
9155Announce an intention to access data in a specific pattern, thus allowing
9156the kernel to make optimizations.
9157The advice applies to the region of the file specified by fd starting at
9158offset and continuing for length bytes.
9159advice is one of POSIX_FADV_NORMAL, POSIX_FADV_SEQUENTIAL,
9160POSIX_FADV_RANDOM, POSIX_FADV_NOREUSE, POSIX_FADV_WILLNEED, or
9161POSIX_FADV_DONTNEED.
9162[clinic start generated code]*/
9163
9164static PyObject *
9165os_posix_fadvise_impl(PyObject *module, int fd, Py_off_t offset,
9166 Py_off_t length, int advice)
9167/*[clinic end generated code: output=412ef4aa70c98642 input=0fbe554edc2f04b5]*/
9168{
9169 int result;
9170 int async_err = 0;
9171
9172 do {
9173 Py_BEGIN_ALLOW_THREADS
9174 result = posix_fadvise(fd, offset, length, advice);
9175 Py_END_ALLOW_THREADS
9176 } while (result == EINTR && !(async_err = PyErr_CheckSignals()));
9177
9178 if (result == 0)
9179 Py_RETURN_NONE;
9180
9181 if (async_err)
9182 return NULL;
9183
9184 errno = result;
9185 return posix_error();
9186}
9187#endif /* HAVE_POSIX_FADVISE && !POSIX_FADVISE_AIX_BUG */
9188
9189#ifdef HAVE_PUTENV
9190
9191/* Save putenv() parameters as values here, so we can collect them when they
9192 * get re-set with another call for the same key. */
9193static PyObject *posix_putenv_garbage;
9194
9195static void
9196posix_putenv_garbage_setitem(PyObject *name, PyObject *value)
9197{
9198 /* Install the first arg and newstr in posix_putenv_garbage;
9199 * this will cause previous value to be collected. This has to
9200 * happen after the real putenv() call because the old value
9201 * was still accessible until then. */
9202 if (PyDict_SetItem(posix_putenv_garbage, name, value))
9203 /* really not much we can do; just leak */
9204 PyErr_Clear();
9205 else
9206 Py_DECREF(value);
9207}
9208
9209
9210#ifdef MS_WINDOWS
9211/*[clinic input]
9212os.putenv
9213
9214 name: unicode
9215 value: unicode
9216 /
9217
9218Change or add an environment variable.
9219[clinic start generated code]*/
9220
9221static PyObject *
9222os_putenv_impl(PyObject *module, PyObject *name, PyObject *value)
9223/*[clinic end generated code: output=d29a567d6b2327d2 input=ba586581c2e6105f]*/
9224{
9225 const wchar_t *env;
9226 Py_ssize_t size;
9227
9228 /* Search from index 1 because on Windows starting '=' is allowed for
9229 defining hidden environment variables. */
9230 if (PyUnicode_GET_LENGTH(name) == 0 ||
9231 PyUnicode_FindChar(name, '=', 1, PyUnicode_GET_LENGTH(name), 1) != -1)
9232 {
9233 PyErr_SetString(PyExc_ValueError, "illegal environment variable name");
9234 return NULL;
9235 }
9236 PyObject *unicode = PyUnicode_FromFormat("%U=%U", name, value);
9237 if (unicode == NULL) {
9238 return NULL;
9239 }
9240
9241 env = PyUnicode_AsUnicodeAndSize(unicode, &size);
9242 if (env == NULL)
9243 goto error;
9244 if (size > _MAX_ENV) {
9245 PyErr_Format(PyExc_ValueError,
9246 "the environment variable is longer than %u characters",
9247 _MAX_ENV);
9248 goto error;
9249 }
9250 if (wcslen(env) != (size_t)size) {
9251 PyErr_SetString(PyExc_ValueError, "embedded null character");
9252 goto error;
9253 }
9254
9255 if (_wputenv(env)) {
9256 posix_error();
9257 goto error;
9258 }
9259
9260 posix_putenv_garbage_setitem(name, unicode);
9261 Py_RETURN_NONE;
9262
9263error:
9264 Py_DECREF(unicode);
9265 return NULL;
9266}
9267#else /* MS_WINDOWS */
9268/*[clinic input]
9269os.putenv
9270
9271 name: FSConverter
9272 value: FSConverter
9273 /
9274
9275Change or add an environment variable.
9276[clinic start generated code]*/
9277
9278static PyObject *
9279os_putenv_impl(PyObject *module, PyObject *name, PyObject *value)
9280/*[clinic end generated code: output=d29a567d6b2327d2 input=a97bc6152f688d31]*/
9281{
9282 PyObject *bytes = NULL;
9283 char *env;
9284 const char *name_string = PyBytes_AS_STRING(name);
9285 const char *value_string = PyBytes_AS_STRING(value);
9286
9287 if (strchr(name_string, '=') != NULL) {
9288 PyErr_SetString(PyExc_ValueError, "illegal environment variable name");
9289 return NULL;
9290 }
9291 bytes = PyBytes_FromFormat("%s=%s", name_string, value_string);
9292 if (bytes == NULL) {
9293 return NULL;
9294 }
9295
9296 env = PyBytes_AS_STRING(bytes);
9297 if (putenv(env)) {
9298 Py_DECREF(bytes);
9299 return posix_error();
9300 }
9301
9302 posix_putenv_garbage_setitem(name, bytes);
9303 Py_RETURN_NONE;
9304}
9305#endif /* MS_WINDOWS */
9306#endif /* HAVE_PUTENV */
9307
9308
9309#ifdef HAVE_UNSETENV
9310/*[clinic input]
9311os.unsetenv
9312 name: FSConverter
9313 /
9314
9315Delete an environment variable.
9316[clinic start generated code]*/
9317
9318static PyObject *
9319os_unsetenv_impl(PyObject *module, PyObject *name)
9320/*[clinic end generated code: output=54c4137ab1834f02 input=2bb5288a599c7107]*/
9321{
9322#ifndef HAVE_BROKEN_UNSETENV
9323 int err;
9324#endif
9325
9326#ifdef HAVE_BROKEN_UNSETENV
9327 unsetenv(PyBytes_AS_STRING(name));
9328#else
9329 err = unsetenv(PyBytes_AS_STRING(name));
9330 if (err)
9331 return posix_error();
9332#endif
9333
9334 /* Remove the key from posix_putenv_garbage;
9335 * this will cause it to be collected. This has to
9336 * happen after the real unsetenv() call because the
9337 * old value was still accessible until then.
9338 */
9339 if (PyDict_DelItem(posix_putenv_garbage, name)) {
9340 /* really not much we can do; just leak */
9341 PyErr_Clear();
9342 }
9343 Py_RETURN_NONE;
9344}
9345#endif /* HAVE_UNSETENV */
9346
9347
9348/*[clinic input]
9349os.strerror
9350
9351 code: int
9352 /
9353
9354Translate an error code to a message string.
9355[clinic start generated code]*/
9356
9357static PyObject *
9358os_strerror_impl(PyObject *module, int code)
9359/*[clinic end generated code: output=baebf09fa02a78f2 input=75a8673d97915a91]*/
9360{
9361 char *message = strerror(code);
9362 if (message == NULL) {
9363 PyErr_SetString(PyExc_ValueError,
9364 "strerror() argument out of range");
9365 return NULL;
9366 }
9367 return PyUnicode_DecodeLocale(message, "surrogateescape");
9368}
9369
9370
9371#ifdef HAVE_SYS_WAIT_H
9372#ifdef WCOREDUMP
9373/*[clinic input]
9374os.WCOREDUMP -> bool
9375
9376 status: int
9377 /
9378
9379Return True if the process returning status was dumped to a core file.
9380[clinic start generated code]*/
9381
9382static int
9383os_WCOREDUMP_impl(PyObject *module, int status)
9384/*[clinic end generated code: output=1a584b147b16bd18 input=8b05e7ab38528d04]*/
9385{
9386 WAIT_TYPE wait_status;
9387 WAIT_STATUS_INT(wait_status) = status;
9388 return WCOREDUMP(wait_status);
9389}
9390#endif /* WCOREDUMP */
9391
9392
9393#ifdef WIFCONTINUED
9394/*[clinic input]
9395os.WIFCONTINUED -> bool
9396
9397 status: int
9398
9399Return True if a particular process was continued from a job control stop.
9400
9401Return True if the process returning status was continued from a
9402job control stop.
9403[clinic start generated code]*/
9404
9405static int
9406os_WIFCONTINUED_impl(PyObject *module, int status)
9407/*[clinic end generated code: output=1e35295d844364bd input=e777e7d38eb25bd9]*/
9408{
9409 WAIT_TYPE wait_status;
9410 WAIT_STATUS_INT(wait_status) = status;
9411 return WIFCONTINUED(wait_status);
9412}
9413#endif /* WIFCONTINUED */
9414
9415
9416#ifdef WIFSTOPPED
9417/*[clinic input]
9418os.WIFSTOPPED -> bool
9419
9420 status: int
9421
9422Return True if the process returning status was stopped.
9423[clinic start generated code]*/
9424
9425static int
9426os_WIFSTOPPED_impl(PyObject *module, int status)
9427/*[clinic end generated code: output=fdb57122a5c9b4cb input=043cb7f1289ef904]*/
9428{
9429 WAIT_TYPE wait_status;
9430 WAIT_STATUS_INT(wait_status) = status;
9431 return WIFSTOPPED(wait_status);
9432}
9433#endif /* WIFSTOPPED */
9434
9435
9436#ifdef WIFSIGNALED
9437/*[clinic input]
9438os.WIFSIGNALED -> bool
9439
9440 status: int
9441
9442Return True if the process returning status was terminated by a signal.
9443[clinic start generated code]*/
9444
9445static int
9446os_WIFSIGNALED_impl(PyObject *module, int status)
9447/*[clinic end generated code: output=d1dde4dcc819a5f5 input=d55ba7cc9ce5dc43]*/
9448{
9449 WAIT_TYPE wait_status;
9450 WAIT_STATUS_INT(wait_status) = status;
9451 return WIFSIGNALED(wait_status);
9452}
9453#endif /* WIFSIGNALED */
9454
9455
9456#ifdef WIFEXITED
9457/*[clinic input]
9458os.WIFEXITED -> bool
9459
9460 status: int
9461
9462Return True if the process returning status exited via the exit() system call.
9463[clinic start generated code]*/
9464
9465static int
9466os_WIFEXITED_impl(PyObject *module, int status)
9467/*[clinic end generated code: output=01c09d6ebfeea397 input=d63775a6791586c0]*/
9468{
9469 WAIT_TYPE wait_status;
9470 WAIT_STATUS_INT(wait_status) = status;
9471 return WIFEXITED(wait_status);
9472}
9473#endif /* WIFEXITED */
9474
9475
9476#ifdef WEXITSTATUS
9477/*[clinic input]
9478os.WEXITSTATUS -> int
9479
9480 status: int
9481
9482Return the process return code from status.
9483[clinic start generated code]*/
9484
9485static int
9486os_WEXITSTATUS_impl(PyObject *module, int status)
9487/*[clinic end generated code: output=6e3efbba11f6488d input=e1fb4944e377585b]*/
9488{
9489 WAIT_TYPE wait_status;
9490 WAIT_STATUS_INT(wait_status) = status;
9491 return WEXITSTATUS(wait_status);
9492}
9493#endif /* WEXITSTATUS */
9494
9495
9496#ifdef WTERMSIG
9497/*[clinic input]
9498os.WTERMSIG -> int
9499
9500 status: int
9501
9502Return the signal that terminated the process that provided the status value.
9503[clinic start generated code]*/
9504
9505static int
9506os_WTERMSIG_impl(PyObject *module, int status)
9507/*[clinic end generated code: output=172f7dfc8dcfc3ad input=727fd7f84ec3f243]*/
9508{
9509 WAIT_TYPE wait_status;
9510 WAIT_STATUS_INT(wait_status) = status;
9511 return WTERMSIG(wait_status);
9512}
9513#endif /* WTERMSIG */
9514
9515
9516#ifdef WSTOPSIG
9517/*[clinic input]
9518os.WSTOPSIG -> int
9519
9520 status: int
9521
9522Return the signal that stopped the process that provided the status value.
9523[clinic start generated code]*/
9524
9525static int
9526os_WSTOPSIG_impl(PyObject *module, int status)
9527/*[clinic end generated code: output=0ab7586396f5d82b input=46ebf1d1b293c5c1]*/
9528{
9529 WAIT_TYPE wait_status;
9530 WAIT_STATUS_INT(wait_status) = status;
9531 return WSTOPSIG(wait_status);
9532}
9533#endif /* WSTOPSIG */
9534#endif /* HAVE_SYS_WAIT_H */
9535
9536
9537#if defined(HAVE_FSTATVFS) && defined(HAVE_SYS_STATVFS_H)
9538#ifdef _SCO_DS
9539/* SCO OpenServer 5.0 and later requires _SVID3 before it reveals the
9540 needed definitions in sys/statvfs.h */
9541#define _SVID3
9542#endif
9543#include <sys/statvfs.h>
9544
9545static PyObject*
9546_pystatvfs_fromstructstatvfs(struct statvfs st) {
9547 PyObject *v = PyStructSequence_New(&StatVFSResultType);
9548 if (v == NULL)
9549 return NULL;
9550
9551#if !defined(HAVE_LARGEFILE_SUPPORT)
9552 PyStructSequence_SET_ITEM(v, 0, PyLong_FromLong((long) st.f_bsize));
9553 PyStructSequence_SET_ITEM(v, 1, PyLong_FromLong((long) st.f_frsize));
9554 PyStructSequence_SET_ITEM(v, 2, PyLong_FromLong((long) st.f_blocks));
9555 PyStructSequence_SET_ITEM(v, 3, PyLong_FromLong((long) st.f_bfree));
9556 PyStructSequence_SET_ITEM(v, 4, PyLong_FromLong((long) st.f_bavail));
9557 PyStructSequence_SET_ITEM(v, 5, PyLong_FromLong((long) st.f_files));
9558 PyStructSequence_SET_ITEM(v, 6, PyLong_FromLong((long) st.f_ffree));
9559 PyStructSequence_SET_ITEM(v, 7, PyLong_FromLong((long) st.f_favail));
9560 PyStructSequence_SET_ITEM(v, 8, PyLong_FromLong((long) st.f_flag));
9561 PyStructSequence_SET_ITEM(v, 9, PyLong_FromLong((long) st.f_namemax));
9562#else
9563 PyStructSequence_SET_ITEM(v, 0, PyLong_FromLong((long) st.f_bsize));
9564 PyStructSequence_SET_ITEM(v, 1, PyLong_FromLong((long) st.f_frsize));
9565 PyStructSequence_SET_ITEM(v, 2,
9566 PyLong_FromLongLong((long long) st.f_blocks));
9567 PyStructSequence_SET_ITEM(v, 3,
9568 PyLong_FromLongLong((long long) st.f_bfree));
9569 PyStructSequence_SET_ITEM(v, 4,
9570 PyLong_FromLongLong((long long) st.f_bavail));
9571 PyStructSequence_SET_ITEM(v, 5,
9572 PyLong_FromLongLong((long long) st.f_files));
9573 PyStructSequence_SET_ITEM(v, 6,
9574 PyLong_FromLongLong((long long) st.f_ffree));
9575 PyStructSequence_SET_ITEM(v, 7,
9576 PyLong_FromLongLong((long long) st.f_favail));
9577 PyStructSequence_SET_ITEM(v, 8, PyLong_FromLong((long) st.f_flag));
9578 PyStructSequence_SET_ITEM(v, 9, PyLong_FromLong((long) st.f_namemax));
9579#endif
9580/* The _ALL_SOURCE feature test macro defines f_fsid as a structure
9581 * (issue #32390). */
9582#if defined(_AIX) && defined(_ALL_SOURCE)
9583 PyStructSequence_SET_ITEM(v, 10, PyLong_FromUnsignedLong(st.f_fsid.val[0]));
9584#else
9585 PyStructSequence_SET_ITEM(v, 10, PyLong_FromUnsignedLong(st.f_fsid));
9586#endif
9587 if (PyErr_Occurred()) {
9588 Py_DECREF(v);
9589 return NULL;
9590 }
9591
9592 return v;
9593}
9594
9595
9596/*[clinic input]
9597os.fstatvfs
9598 fd: int
9599 /
9600
9601Perform an fstatvfs system call on the given fd.
9602
9603Equivalent to statvfs(fd).
9604[clinic start generated code]*/
9605
9606static PyObject *
9607os_fstatvfs_impl(PyObject *module, int fd)
9608/*[clinic end generated code: output=53547cf0cc55e6c5 input=d8122243ac50975e]*/
9609{
9610 int result;
9611 int async_err = 0;
9612 struct statvfs st;
9613
9614 do {
9615 Py_BEGIN_ALLOW_THREADS
9616 result = fstatvfs(fd, &st);
9617 Py_END_ALLOW_THREADS
9618 } while (result != 0 && errno == EINTR &&
9619 !(async_err = PyErr_CheckSignals()));
9620 if (result != 0)
9621 return (!async_err) ? posix_error() : NULL;
9622
9623 return _pystatvfs_fromstructstatvfs(st);
9624}
9625#endif /* defined(HAVE_FSTATVFS) && defined(HAVE_SYS_STATVFS_H) */
9626
9627
9628#if defined(HAVE_STATVFS) && defined(HAVE_SYS_STATVFS_H)
9629#include <sys/statvfs.h>
9630/*[clinic input]
9631os.statvfs
9632
9633 path: path_t(allow_fd='PATH_HAVE_FSTATVFS')
9634
9635Perform a statvfs system call on the given path.
9636
9637path may always be specified as a string.
9638On some platforms, path may also be specified as an open file descriptor.
9639 If this functionality is unavailable, using it raises an exception.
9640[clinic start generated code]*/
9641
9642static PyObject *
9643os_statvfs_impl(PyObject *module, path_t *path)
9644/*[clinic end generated code: output=87106dd1beb8556e input=3f5c35791c669bd9]*/
9645{
9646 int result;
9647 struct statvfs st;
9648
9649 Py_BEGIN_ALLOW_THREADS
9650#ifdef HAVE_FSTATVFS
9651 if (path->fd != -1) {
9652#ifdef __APPLE__
9653 /* handle weak-linking on Mac OS X 10.3 */
9654 if (fstatvfs == NULL) {
9655 fd_specified("statvfs", path->fd);
9656 return NULL;
9657 }
9658#endif
9659 result = fstatvfs(path->fd, &st);
9660 }
9661 else
9662#endif
9663 result = statvfs(path->narrow, &st);
9664 Py_END_ALLOW_THREADS
9665
9666 if (result) {
9667 return path_error(path);
9668 }
9669
9670 return _pystatvfs_fromstructstatvfs(st);
9671}
9672#endif /* defined(HAVE_STATVFS) && defined(HAVE_SYS_STATVFS_H) */
9673
9674
9675#ifdef MS_WINDOWS
9676/*[clinic input]
9677os._getdiskusage
9678
9679 path: path_t
9680
9681Return disk usage statistics about the given path as a (total, free) tuple.
9682[clinic start generated code]*/
9683
9684static PyObject *
9685os__getdiskusage_impl(PyObject *module, path_t *path)
9686/*[clinic end generated code: output=3bd3991f5e5c5dfb input=6af8d1b7781cc042]*/
9687{
9688 BOOL retval;
9689 ULARGE_INTEGER _, total, free;
9690
9691 Py_BEGIN_ALLOW_THREADS
9692 retval = GetDiskFreeSpaceExW(path->wide, &_, &total, &free);
9693 Py_END_ALLOW_THREADS
9694 if (retval == 0)
9695 return PyErr_SetFromWindowsErr(0);
9696
9697 return Py_BuildValue("(LL)", total.QuadPart, free.QuadPart);
9698}
9699#endif /* MS_WINDOWS */
9700
9701
9702/* This is used for fpathconf(), pathconf(), confstr() and sysconf().
9703 * It maps strings representing configuration variable names to
9704 * integer values, allowing those functions to be called with the
9705 * magic names instead of polluting the module's namespace with tons of
9706 * rarely-used constants. There are three separate tables that use
9707 * these definitions.
9708 *
9709 * This code is always included, even if none of the interfaces that
9710 * need it are included. The #if hackery needed to avoid it would be
9711 * sufficiently pervasive that it's not worth the loss of readability.
9712 */
9713struct constdef {
9714 const char *name;
9715 int value;
9716};
9717
9718static int
9719conv_confname(PyObject *arg, int *valuep, struct constdef *table,
9720 size_t tablesize)
9721{
9722 if (PyLong_Check(arg)) {
9723 int value = _PyLong_AsInt(arg);
9724 if (value == -1 && PyErr_Occurred())
9725 return 0;
9726 *valuep = value;
9727 return 1;
9728 }
9729 else {
9730 /* look up the value in the table using a binary search */
9731 size_t lo = 0;
9732 size_t mid;
9733 size_t hi = tablesize;
9734 int cmp;
9735 const char *confname;
9736 if (!PyUnicode_Check(arg)) {
9737 PyErr_SetString(PyExc_TypeError,
9738 "configuration names must be strings or integers");
9739 return 0;
9740 }
9741 confname = PyUnicode_AsUTF8(arg);
9742 if (confname == NULL)
9743 return 0;
9744 while (lo < hi) {
9745 mid = (lo + hi) / 2;
9746 cmp = strcmp(confname, table[mid].name);
9747 if (cmp < 0)
9748 hi = mid;
9749 else if (cmp > 0)
9750 lo = mid + 1;
9751 else {
9752 *valuep = table[mid].value;
9753 return 1;
9754 }
9755 }
9756 PyErr_SetString(PyExc_ValueError, "unrecognized configuration name");
9757 return 0;
9758 }
9759}
9760
9761
9762#if defined(HAVE_FPATHCONF) || defined(HAVE_PATHCONF)
9763static struct constdef posix_constants_pathconf[] = {
9764#ifdef _PC_ABI_AIO_XFER_MAX
9765 {"PC_ABI_AIO_XFER_MAX", _PC_ABI_AIO_XFER_MAX},
9766#endif
9767#ifdef _PC_ABI_ASYNC_IO
9768 {"PC_ABI_ASYNC_IO", _PC_ABI_ASYNC_IO},
9769#endif
9770#ifdef _PC_ASYNC_IO
9771 {"PC_ASYNC_IO", _PC_ASYNC_IO},
9772#endif
9773#ifdef _PC_CHOWN_RESTRICTED
9774 {"PC_CHOWN_RESTRICTED", _PC_CHOWN_RESTRICTED},
9775#endif
9776#ifdef _PC_FILESIZEBITS
9777 {"PC_FILESIZEBITS", _PC_FILESIZEBITS},
9778#endif
9779#ifdef _PC_LAST
9780 {"PC_LAST", _PC_LAST},
9781#endif
9782#ifdef _PC_LINK_MAX
9783 {"PC_LINK_MAX", _PC_LINK_MAX},
9784#endif
9785#ifdef _PC_MAX_CANON
9786 {"PC_MAX_CANON", _PC_MAX_CANON},
9787#endif
9788#ifdef _PC_MAX_INPUT
9789 {"PC_MAX_INPUT", _PC_MAX_INPUT},
9790#endif
9791#ifdef _PC_NAME_MAX
9792 {"PC_NAME_MAX", _PC_NAME_MAX},
9793#endif
9794#ifdef _PC_NO_TRUNC
9795 {"PC_NO_TRUNC", _PC_NO_TRUNC},
9796#endif
9797#ifdef _PC_PATH_MAX
9798 {"PC_PATH_MAX", _PC_PATH_MAX},
9799#endif
9800#ifdef _PC_PIPE_BUF
9801 {"PC_PIPE_BUF", _PC_PIPE_BUF},
9802#endif
9803#ifdef _PC_PRIO_IO
9804 {"PC_PRIO_IO", _PC_PRIO_IO},
9805#endif
9806#ifdef _PC_SOCK_MAXBUF
9807 {"PC_SOCK_MAXBUF", _PC_SOCK_MAXBUF},
9808#endif
9809#ifdef _PC_SYNC_IO
9810 {"PC_SYNC_IO", _PC_SYNC_IO},
9811#endif
9812#ifdef _PC_VDISABLE
9813 {"PC_VDISABLE", _PC_VDISABLE},
9814#endif
9815#ifdef _PC_ACL_ENABLED
9816 {"PC_ACL_ENABLED", _PC_ACL_ENABLED},
9817#endif
9818#ifdef _PC_MIN_HOLE_SIZE
9819 {"PC_MIN_HOLE_SIZE", _PC_MIN_HOLE_SIZE},
9820#endif
9821#ifdef _PC_ALLOC_SIZE_MIN
9822 {"PC_ALLOC_SIZE_MIN", _PC_ALLOC_SIZE_MIN},
9823#endif
9824#ifdef _PC_REC_INCR_XFER_SIZE
9825 {"PC_REC_INCR_XFER_SIZE", _PC_REC_INCR_XFER_SIZE},
9826#endif
9827#ifdef _PC_REC_MAX_XFER_SIZE
9828 {"PC_REC_MAX_XFER_SIZE", _PC_REC_MAX_XFER_SIZE},
9829#endif
9830#ifdef _PC_REC_MIN_XFER_SIZE
9831 {"PC_REC_MIN_XFER_SIZE", _PC_REC_MIN_XFER_SIZE},
9832#endif
9833#ifdef _PC_REC_XFER_ALIGN
9834 {"PC_REC_XFER_ALIGN", _PC_REC_XFER_ALIGN},
9835#endif
9836#ifdef _PC_SYMLINK_MAX
9837 {"PC_SYMLINK_MAX", _PC_SYMLINK_MAX},
9838#endif
9839#ifdef _PC_XATTR_ENABLED
9840 {"PC_XATTR_ENABLED", _PC_XATTR_ENABLED},
9841#endif
9842#ifdef _PC_XATTR_EXISTS
9843 {"PC_XATTR_EXISTS", _PC_XATTR_EXISTS},
9844#endif
9845#ifdef _PC_TIMESTAMP_RESOLUTION
9846 {"PC_TIMESTAMP_RESOLUTION", _PC_TIMESTAMP_RESOLUTION},
9847#endif
9848};
9849
9850static int
9851conv_path_confname(PyObject *arg, int *valuep)
9852{
9853 return conv_confname(arg, valuep, posix_constants_pathconf,
9854 sizeof(posix_constants_pathconf)
9855 / sizeof(struct constdef));
9856}
9857#endif
9858
9859
9860#ifdef HAVE_FPATHCONF
9861/*[clinic input]
9862os.fpathconf -> long
9863
9864 fd: int
9865 name: path_confname
9866 /
9867
9868Return the configuration limit name for the file descriptor fd.
9869
9870If there is no limit, return -1.
9871[clinic start generated code]*/
9872
9873static long
9874os_fpathconf_impl(PyObject *module, int fd, int name)
9875/*[clinic end generated code: output=d5b7042425fc3e21 input=5942a024d3777810]*/
9876{
9877 long limit;
9878
9879 errno = 0;
9880 limit = fpathconf(fd, name);
9881 if (limit == -1 && errno != 0)
9882 posix_error();
9883
9884 return limit;
9885}
9886#endif /* HAVE_FPATHCONF */
9887
9888
9889#ifdef HAVE_PATHCONF
9890/*[clinic input]
9891os.pathconf -> long
9892 path: path_t(allow_fd='PATH_HAVE_FPATHCONF')
9893 name: path_confname
9894
9895Return the configuration limit name for the file or directory path.
9896
9897If there is no limit, return -1.
9898On some platforms, path may also be specified as an open file descriptor.
9899 If this functionality is unavailable, using it raises an exception.
9900[clinic start generated code]*/
9901
9902static long
9903os_pathconf_impl(PyObject *module, path_t *path, int name)
9904/*[clinic end generated code: output=5bedee35b293a089 input=bc3e2a985af27e5e]*/
9905{
9906 long limit;
9907
9908 errno = 0;
9909#ifdef HAVE_FPATHCONF
9910 if (path->fd != -1)
9911 limit = fpathconf(path->fd, name);
9912 else
9913#endif
9914 limit = pathconf(path->narrow, name);
9915 if (limit == -1 && errno != 0) {
9916 if (errno == EINVAL)
9917 /* could be a path or name problem */
9918 posix_error();
9919 else
9920 path_error(path);
9921 }
9922
9923 return limit;
9924}
9925#endif /* HAVE_PATHCONF */
9926
9927#ifdef HAVE_CONFSTR
9928static struct constdef posix_constants_confstr[] = {
9929#ifdef _CS_ARCHITECTURE
9930 {"CS_ARCHITECTURE", _CS_ARCHITECTURE},
9931#endif
9932#ifdef _CS_GNU_LIBC_VERSION
9933 {"CS_GNU_LIBC_VERSION", _CS_GNU_LIBC_VERSION},
9934#endif
9935#ifdef _CS_GNU_LIBPTHREAD_VERSION
9936 {"CS_GNU_LIBPTHREAD_VERSION", _CS_GNU_LIBPTHREAD_VERSION},
9937#endif
9938#ifdef _CS_HOSTNAME
9939 {"CS_HOSTNAME", _CS_HOSTNAME},
9940#endif
9941#ifdef _CS_HW_PROVIDER
9942 {"CS_HW_PROVIDER", _CS_HW_PROVIDER},
9943#endif
9944#ifdef _CS_HW_SERIAL
9945 {"CS_HW_SERIAL", _CS_HW_SERIAL},
9946#endif
9947#ifdef _CS_INITTAB_NAME
9948 {"CS_INITTAB_NAME", _CS_INITTAB_NAME},
9949#endif
9950#ifdef _CS_LFS64_CFLAGS
9951 {"CS_LFS64_CFLAGS", _CS_LFS64_CFLAGS},
9952#endif
9953#ifdef _CS_LFS64_LDFLAGS
9954 {"CS_LFS64_LDFLAGS", _CS_LFS64_LDFLAGS},
9955#endif
9956#ifdef _CS_LFS64_LIBS
9957 {"CS_LFS64_LIBS", _CS_LFS64_LIBS},
9958#endif
9959#ifdef _CS_LFS64_LINTFLAGS
9960 {"CS_LFS64_LINTFLAGS", _CS_LFS64_LINTFLAGS},
9961#endif
9962#ifdef _CS_LFS_CFLAGS
9963 {"CS_LFS_CFLAGS", _CS_LFS_CFLAGS},
9964#endif
9965#ifdef _CS_LFS_LDFLAGS
9966 {"CS_LFS_LDFLAGS", _CS_LFS_LDFLAGS},
9967#endif
9968#ifdef _CS_LFS_LIBS
9969 {"CS_LFS_LIBS", _CS_LFS_LIBS},
9970#endif
9971#ifdef _CS_LFS_LINTFLAGS
9972 {"CS_LFS_LINTFLAGS", _CS_LFS_LINTFLAGS},
9973#endif
9974#ifdef _CS_MACHINE
9975 {"CS_MACHINE", _CS_MACHINE},
9976#endif
9977#ifdef _CS_PATH
9978 {"CS_PATH", _CS_PATH},
9979#endif
9980#ifdef _CS_RELEASE
9981 {"CS_RELEASE", _CS_RELEASE},
9982#endif
9983#ifdef _CS_SRPC_DOMAIN
9984 {"CS_SRPC_DOMAIN", _CS_SRPC_DOMAIN},
9985#endif
9986#ifdef _CS_SYSNAME
9987 {"CS_SYSNAME", _CS_SYSNAME},
9988#endif
9989#ifdef _CS_VERSION
9990 {"CS_VERSION", _CS_VERSION},
9991#endif
9992#ifdef _CS_XBS5_ILP32_OFF32_CFLAGS
9993 {"CS_XBS5_ILP32_OFF32_CFLAGS", _CS_XBS5_ILP32_OFF32_CFLAGS},
9994#endif
9995#ifdef _CS_XBS5_ILP32_OFF32_LDFLAGS
9996 {"CS_XBS5_ILP32_OFF32_LDFLAGS", _CS_XBS5_ILP32_OFF32_LDFLAGS},
9997#endif
9998#ifdef _CS_XBS5_ILP32_OFF32_LIBS
9999 {"CS_XBS5_ILP32_OFF32_LIBS", _CS_XBS5_ILP32_OFF32_LIBS},
10000#endif
10001#ifdef _CS_XBS5_ILP32_OFF32_LINTFLAGS
10002 {"CS_XBS5_ILP32_OFF32_LINTFLAGS", _CS_XBS5_ILP32_OFF32_LINTFLAGS},
10003#endif
10004#ifdef _CS_XBS5_ILP32_OFFBIG_CFLAGS
10005 {"CS_XBS5_ILP32_OFFBIG_CFLAGS", _CS_XBS5_ILP32_OFFBIG_CFLAGS},
10006#endif
10007#ifdef _CS_XBS5_ILP32_OFFBIG_LDFLAGS
10008 {"CS_XBS5_ILP32_OFFBIG_LDFLAGS", _CS_XBS5_ILP32_OFFBIG_LDFLAGS},
10009#endif
10010#ifdef _CS_XBS5_ILP32_OFFBIG_LIBS
10011 {"CS_XBS5_ILP32_OFFBIG_LIBS", _CS_XBS5_ILP32_OFFBIG_LIBS},
10012#endif
10013#ifdef _CS_XBS5_ILP32_OFFBIG_LINTFLAGS
10014 {"CS_XBS5_ILP32_OFFBIG_LINTFLAGS", _CS_XBS5_ILP32_OFFBIG_LINTFLAGS},
10015#endif
10016#ifdef _CS_XBS5_LP64_OFF64_CFLAGS
10017 {"CS_XBS5_LP64_OFF64_CFLAGS", _CS_XBS5_LP64_OFF64_CFLAGS},
10018#endif
10019#ifdef _CS_XBS5_LP64_OFF64_LDFLAGS
10020 {"CS_XBS5_LP64_OFF64_LDFLAGS", _CS_XBS5_LP64_OFF64_LDFLAGS},
10021#endif
10022#ifdef _CS_XBS5_LP64_OFF64_LIBS
10023 {"CS_XBS5_LP64_OFF64_LIBS", _CS_XBS5_LP64_OFF64_LIBS},
10024#endif
10025#ifdef _CS_XBS5_LP64_OFF64_LINTFLAGS
10026 {"CS_XBS5_LP64_OFF64_LINTFLAGS", _CS_XBS5_LP64_OFF64_LINTFLAGS},
10027#endif
10028#ifdef _CS_XBS5_LPBIG_OFFBIG_CFLAGS
10029 {"CS_XBS5_LPBIG_OFFBIG_CFLAGS", _CS_XBS5_LPBIG_OFFBIG_CFLAGS},
10030#endif
10031#ifdef _CS_XBS5_LPBIG_OFFBIG_LDFLAGS
10032 {"CS_XBS5_LPBIG_OFFBIG_LDFLAGS", _CS_XBS5_LPBIG_OFFBIG_LDFLAGS},
10033#endif
10034#ifdef _CS_XBS5_LPBIG_OFFBIG_LIBS
10035 {"CS_XBS5_LPBIG_OFFBIG_LIBS", _CS_XBS5_LPBIG_OFFBIG_LIBS},
10036#endif
10037#ifdef _CS_XBS5_LPBIG_OFFBIG_LINTFLAGS
10038 {"CS_XBS5_LPBIG_OFFBIG_LINTFLAGS", _CS_XBS5_LPBIG_OFFBIG_LINTFLAGS},
10039#endif
10040#ifdef _MIPS_CS_AVAIL_PROCESSORS
10041 {"MIPS_CS_AVAIL_PROCESSORS", _MIPS_CS_AVAIL_PROCESSORS},
10042#endif
10043#ifdef _MIPS_CS_BASE
10044 {"MIPS_CS_BASE", _MIPS_CS_BASE},
10045#endif
10046#ifdef _MIPS_CS_HOSTID
10047 {"MIPS_CS_HOSTID", _MIPS_CS_HOSTID},
10048#endif
10049#ifdef _MIPS_CS_HW_NAME
10050 {"MIPS_CS_HW_NAME", _MIPS_CS_HW_NAME},
10051#endif
10052#ifdef _MIPS_CS_NUM_PROCESSORS
10053 {"MIPS_CS_NUM_PROCESSORS", _MIPS_CS_NUM_PROCESSORS},
10054#endif
10055#ifdef _MIPS_CS_OSREL_MAJ
10056 {"MIPS_CS_OSREL_MAJ", _MIPS_CS_OSREL_MAJ},
10057#endif
10058#ifdef _MIPS_CS_OSREL_MIN
10059 {"MIPS_CS_OSREL_MIN", _MIPS_CS_OSREL_MIN},
10060#endif
10061#ifdef _MIPS_CS_OSREL_PATCH
10062 {"MIPS_CS_OSREL_PATCH", _MIPS_CS_OSREL_PATCH},
10063#endif
10064#ifdef _MIPS_CS_OS_NAME
10065 {"MIPS_CS_OS_NAME", _MIPS_CS_OS_NAME},
10066#endif
10067#ifdef _MIPS_CS_OS_PROVIDER
10068 {"MIPS_CS_OS_PROVIDER", _MIPS_CS_OS_PROVIDER},
10069#endif
10070#ifdef _MIPS_CS_PROCESSORS
10071 {"MIPS_CS_PROCESSORS", _MIPS_CS_PROCESSORS},
10072#endif
10073#ifdef _MIPS_CS_SERIAL
10074 {"MIPS_CS_SERIAL", _MIPS_CS_SERIAL},
10075#endif
10076#ifdef _MIPS_CS_VENDOR
10077 {"MIPS_CS_VENDOR", _MIPS_CS_VENDOR},
10078#endif
10079};
10080
10081static int
10082conv_confstr_confname(PyObject *arg, int *valuep)
10083{
10084 return conv_confname(arg, valuep, posix_constants_confstr,
10085 sizeof(posix_constants_confstr)
10086 / sizeof(struct constdef));
10087}
10088
10089
10090/*[clinic input]
10091os.confstr
10092
10093 name: confstr_confname
10094 /
10095
10096Return a string-valued system configuration variable.
10097[clinic start generated code]*/
10098
10099static PyObject *
10100os_confstr_impl(PyObject *module, int name)
10101/*[clinic end generated code: output=bfb0b1b1e49b9383 input=18fb4d0567242e65]*/
10102{
10103 PyObject *result = NULL;
10104 char buffer[255];
10105 size_t len;
10106
10107 errno = 0;
10108 len = confstr(name, buffer, sizeof(buffer));
10109 if (len == 0) {
10110 if (errno) {
10111 posix_error();
10112 return NULL;
10113 }
10114 else {
10115 Py_RETURN_NONE;
10116 }
10117 }
10118
10119 if (len >= sizeof(buffer)) {
10120 size_t len2;
10121 char *buf = PyMem_Malloc(len);
10122 if (buf == NULL)
10123 return PyErr_NoMemory();
10124 len2 = confstr(name, buf, len);
10125 assert(len == len2);
10126 result = PyUnicode_DecodeFSDefaultAndSize(buf, len2-1);
10127 PyMem_Free(buf);
10128 }
10129 else
10130 result = PyUnicode_DecodeFSDefaultAndSize(buffer, len-1);
10131 return result;
10132}
10133#endif /* HAVE_CONFSTR */
10134
10135
10136#ifdef HAVE_SYSCONF
10137static struct constdef posix_constants_sysconf[] = {
10138#ifdef _SC_2_CHAR_TERM
10139 {"SC_2_CHAR_TERM", _SC_2_CHAR_TERM},
10140#endif
10141#ifdef _SC_2_C_BIND
10142 {"SC_2_C_BIND", _SC_2_C_BIND},
10143#endif
10144#ifdef _SC_2_C_DEV
10145 {"SC_2_C_DEV", _SC_2_C_DEV},
10146#endif
10147#ifdef _SC_2_C_VERSION
10148 {"SC_2_C_VERSION", _SC_2_C_VERSION},
10149#endif
10150#ifdef _SC_2_FORT_DEV
10151 {"SC_2_FORT_DEV", _SC_2_FORT_DEV},
10152#endif
10153#ifdef _SC_2_FORT_RUN
10154 {"SC_2_FORT_RUN", _SC_2_FORT_RUN},
10155#endif
10156#ifdef _SC_2_LOCALEDEF
10157 {"SC_2_LOCALEDEF", _SC_2_LOCALEDEF},
10158#endif
10159#ifdef _SC_2_SW_DEV
10160 {"SC_2_SW_DEV", _SC_2_SW_DEV},
10161#endif
10162#ifdef _SC_2_UPE
10163 {"SC_2_UPE", _SC_2_UPE},
10164#endif
10165#ifdef _SC_2_VERSION
10166 {"SC_2_VERSION", _SC_2_VERSION},
10167#endif
10168#ifdef _SC_ABI_ASYNCHRONOUS_IO
10169 {"SC_ABI_ASYNCHRONOUS_IO", _SC_ABI_ASYNCHRONOUS_IO},
10170#endif
10171#ifdef _SC_ACL
10172 {"SC_ACL", _SC_ACL},
10173#endif
10174#ifdef _SC_AIO_LISTIO_MAX
10175 {"SC_AIO_LISTIO_MAX", _SC_AIO_LISTIO_MAX},
10176#endif
10177#ifdef _SC_AIO_MAX
10178 {"SC_AIO_MAX", _SC_AIO_MAX},
10179#endif
10180#ifdef _SC_AIO_PRIO_DELTA_MAX
10181 {"SC_AIO_PRIO_DELTA_MAX", _SC_AIO_PRIO_DELTA_MAX},
10182#endif
10183#ifdef _SC_ARG_MAX
10184 {"SC_ARG_MAX", _SC_ARG_MAX},
10185#endif
10186#ifdef _SC_ASYNCHRONOUS_IO
10187 {"SC_ASYNCHRONOUS_IO", _SC_ASYNCHRONOUS_IO},
10188#endif
10189#ifdef _SC_ATEXIT_MAX
10190 {"SC_ATEXIT_MAX", _SC_ATEXIT_MAX},
10191#endif
10192#ifdef _SC_AUDIT
10193 {"SC_AUDIT", _SC_AUDIT},
10194#endif
10195#ifdef _SC_AVPHYS_PAGES
10196 {"SC_AVPHYS_PAGES", _SC_AVPHYS_PAGES},
10197#endif
10198#ifdef _SC_BC_BASE_MAX
10199 {"SC_BC_BASE_MAX", _SC_BC_BASE_MAX},
10200#endif
10201#ifdef _SC_BC_DIM_MAX
10202 {"SC_BC_DIM_MAX", _SC_BC_DIM_MAX},
10203#endif
10204#ifdef _SC_BC_SCALE_MAX
10205 {"SC_BC_SCALE_MAX", _SC_BC_SCALE_MAX},
10206#endif
10207#ifdef _SC_BC_STRING_MAX
10208 {"SC_BC_STRING_MAX", _SC_BC_STRING_MAX},
10209#endif
10210#ifdef _SC_CAP
10211 {"SC_CAP", _SC_CAP},
10212#endif
10213#ifdef _SC_CHARCLASS_NAME_MAX
10214 {"SC_CHARCLASS_NAME_MAX", _SC_CHARCLASS_NAME_MAX},
10215#endif
10216#ifdef _SC_CHAR_BIT
10217 {"SC_CHAR_BIT", _SC_CHAR_BIT},
10218#endif
10219#ifdef _SC_CHAR_MAX
10220 {"SC_CHAR_MAX", _SC_CHAR_MAX},
10221#endif
10222#ifdef _SC_CHAR_MIN
10223 {"SC_CHAR_MIN", _SC_CHAR_MIN},
10224#endif
10225#ifdef _SC_CHILD_MAX
10226 {"SC_CHILD_MAX", _SC_CHILD_MAX},
10227#endif
10228#ifdef _SC_CLK_TCK
10229 {"SC_CLK_TCK", _SC_CLK_TCK},
10230#endif
10231#ifdef _SC_COHER_BLKSZ
10232 {"SC_COHER_BLKSZ", _SC_COHER_BLKSZ},
10233#endif
10234#ifdef _SC_COLL_WEIGHTS_MAX
10235 {"SC_COLL_WEIGHTS_MAX", _SC_COLL_WEIGHTS_MAX},
10236#endif
10237#ifdef _SC_DCACHE_ASSOC
10238 {"SC_DCACHE_ASSOC", _SC_DCACHE_ASSOC},
10239#endif
10240#ifdef _SC_DCACHE_BLKSZ
10241 {"SC_DCACHE_BLKSZ", _SC_DCACHE_BLKSZ},
10242#endif
10243#ifdef _SC_DCACHE_LINESZ
10244 {"SC_DCACHE_LINESZ", _SC_DCACHE_LINESZ},
10245#endif
10246#ifdef _SC_DCACHE_SZ
10247 {"SC_DCACHE_SZ", _SC_DCACHE_SZ},
10248#endif
10249#ifdef _SC_DCACHE_TBLKSZ
10250 {"SC_DCACHE_TBLKSZ", _SC_DCACHE_TBLKSZ},
10251#endif
10252#ifdef _SC_DELAYTIMER_MAX
10253 {"SC_DELAYTIMER_MAX", _SC_DELAYTIMER_MAX},
10254#endif
10255#ifdef _SC_EQUIV_CLASS_MAX
10256 {"SC_EQUIV_CLASS_MAX", _SC_EQUIV_CLASS_MAX},
10257#endif
10258#ifdef _SC_EXPR_NEST_MAX
10259 {"SC_EXPR_NEST_MAX", _SC_EXPR_NEST_MAX},
10260#endif
10261#ifdef _SC_FSYNC
10262 {"SC_FSYNC", _SC_FSYNC},
10263#endif
10264#ifdef _SC_GETGR_R_SIZE_MAX
10265 {"SC_GETGR_R_SIZE_MAX", _SC_GETGR_R_SIZE_MAX},
10266#endif
10267#ifdef _SC_GETPW_R_SIZE_MAX
10268 {"SC_GETPW_R_SIZE_MAX", _SC_GETPW_R_SIZE_MAX},
10269#endif
10270#ifdef _SC_ICACHE_ASSOC
10271 {"SC_ICACHE_ASSOC", _SC_ICACHE_ASSOC},
10272#endif
10273#ifdef _SC_ICACHE_BLKSZ
10274 {"SC_ICACHE_BLKSZ", _SC_ICACHE_BLKSZ},
10275#endif
10276#ifdef _SC_ICACHE_LINESZ
10277 {"SC_ICACHE_LINESZ", _SC_ICACHE_LINESZ},
10278#endif
10279#ifdef _SC_ICACHE_SZ
10280 {"SC_ICACHE_SZ", _SC_ICACHE_SZ},
10281#endif
10282#ifdef _SC_INF
10283 {"SC_INF", _SC_INF},
10284#endif
10285#ifdef _SC_INT_MAX
10286 {"SC_INT_MAX", _SC_INT_MAX},
10287#endif
10288#ifdef _SC_INT_MIN
10289 {"SC_INT_MIN", _SC_INT_MIN},
10290#endif
10291#ifdef _SC_IOV_MAX
10292 {"SC_IOV_MAX", _SC_IOV_MAX},
10293#endif
10294#ifdef _SC_IP_SECOPTS
10295 {"SC_IP_SECOPTS", _SC_IP_SECOPTS},
10296#endif
10297#ifdef _SC_JOB_CONTROL
10298 {"SC_JOB_CONTROL", _SC_JOB_CONTROL},
10299#endif
10300#ifdef _SC_KERN_POINTERS
10301 {"SC_KERN_POINTERS", _SC_KERN_POINTERS},
10302#endif
10303#ifdef _SC_KERN_SIM
10304 {"SC_KERN_SIM", _SC_KERN_SIM},
10305#endif
10306#ifdef _SC_LINE_MAX
10307 {"SC_LINE_MAX", _SC_LINE_MAX},
10308#endif
10309#ifdef _SC_LOGIN_NAME_MAX
10310 {"SC_LOGIN_NAME_MAX", _SC_LOGIN_NAME_MAX},
10311#endif
10312#ifdef _SC_LOGNAME_MAX
10313 {"SC_LOGNAME_MAX", _SC_LOGNAME_MAX},
10314#endif
10315#ifdef _SC_LONG_BIT
10316 {"SC_LONG_BIT", _SC_LONG_BIT},
10317#endif
10318#ifdef _SC_MAC
10319 {"SC_MAC", _SC_MAC},
10320#endif
10321#ifdef _SC_MAPPED_FILES
10322 {"SC_MAPPED_FILES", _SC_MAPPED_FILES},
10323#endif
10324#ifdef _SC_MAXPID
10325 {"SC_MAXPID", _SC_MAXPID},
10326#endif
10327#ifdef _SC_MB_LEN_MAX
10328 {"SC_MB_LEN_MAX", _SC_MB_LEN_MAX},
10329#endif
10330#ifdef _SC_MEMLOCK
10331 {"SC_MEMLOCK", _SC_MEMLOCK},
10332#endif
10333#ifdef _SC_MEMLOCK_RANGE
10334 {"SC_MEMLOCK_RANGE", _SC_MEMLOCK_RANGE},
10335#endif
10336#ifdef _SC_MEMORY_PROTECTION
10337 {"SC_MEMORY_PROTECTION", _SC_MEMORY_PROTECTION},
10338#endif
10339#ifdef _SC_MESSAGE_PASSING
10340 {"SC_MESSAGE_PASSING", _SC_MESSAGE_PASSING},
10341#endif
10342#ifdef _SC_MMAP_FIXED_ALIGNMENT
10343 {"SC_MMAP_FIXED_ALIGNMENT", _SC_MMAP_FIXED_ALIGNMENT},
10344#endif
10345#ifdef _SC_MQ_OPEN_MAX
10346 {"SC_MQ_OPEN_MAX", _SC_MQ_OPEN_MAX},
10347#endif
10348#ifdef _SC_MQ_PRIO_MAX
10349 {"SC_MQ_PRIO_MAX", _SC_MQ_PRIO_MAX},
10350#endif
10351#ifdef _SC_NACLS_MAX
10352 {"SC_NACLS_MAX", _SC_NACLS_MAX},
10353#endif
10354#ifdef _SC_NGROUPS_MAX
10355 {"SC_NGROUPS_MAX", _SC_NGROUPS_MAX},
10356#endif
10357#ifdef _SC_NL_ARGMAX
10358 {"SC_NL_ARGMAX", _SC_NL_ARGMAX},
10359#endif
10360#ifdef _SC_NL_LANGMAX
10361 {"SC_NL_LANGMAX", _SC_NL_LANGMAX},
10362#endif
10363#ifdef _SC_NL_MSGMAX
10364 {"SC_NL_MSGMAX", _SC_NL_MSGMAX},
10365#endif
10366#ifdef _SC_NL_NMAX
10367 {"SC_NL_NMAX", _SC_NL_NMAX},
10368#endif
10369#ifdef _SC_NL_SETMAX
10370 {"SC_NL_SETMAX", _SC_NL_SETMAX},
10371#endif
10372#ifdef _SC_NL_TEXTMAX
10373 {"SC_NL_TEXTMAX", _SC_NL_TEXTMAX},
10374#endif
10375#ifdef _SC_NPROCESSORS_CONF
10376 {"SC_NPROCESSORS_CONF", _SC_NPROCESSORS_CONF},
10377#endif
10378#ifdef _SC_NPROCESSORS_ONLN
10379 {"SC_NPROCESSORS_ONLN", _SC_NPROCESSORS_ONLN},
10380#endif
10381#ifdef _SC_NPROC_CONF
10382 {"SC_NPROC_CONF", _SC_NPROC_CONF},
10383#endif
10384#ifdef _SC_NPROC_ONLN
10385 {"SC_NPROC_ONLN", _SC_NPROC_ONLN},
10386#endif
10387#ifdef _SC_NZERO
10388 {"SC_NZERO", _SC_NZERO},
10389#endif
10390#ifdef _SC_OPEN_MAX
10391 {"SC_OPEN_MAX", _SC_OPEN_MAX},
10392#endif
10393#ifdef _SC_PAGESIZE
10394 {"SC_PAGESIZE", _SC_PAGESIZE},
10395#endif
10396#ifdef _SC_PAGE_SIZE
10397 {"SC_PAGE_SIZE", _SC_PAGE_SIZE},
10398#endif
10399#ifdef _SC_PASS_MAX
10400 {"SC_PASS_MAX", _SC_PASS_MAX},
10401#endif
10402#ifdef _SC_PHYS_PAGES
10403 {"SC_PHYS_PAGES", _SC_PHYS_PAGES},
10404#endif
10405#ifdef _SC_PII
10406 {"SC_PII", _SC_PII},
10407#endif
10408#ifdef _SC_PII_INTERNET
10409 {"SC_PII_INTERNET", _SC_PII_INTERNET},
10410#endif
10411#ifdef _SC_PII_INTERNET_DGRAM
10412 {"SC_PII_INTERNET_DGRAM", _SC_PII_INTERNET_DGRAM},
10413#endif
10414#ifdef _SC_PII_INTERNET_STREAM
10415 {"SC_PII_INTERNET_STREAM", _SC_PII_INTERNET_STREAM},
10416#endif
10417#ifdef _SC_PII_OSI
10418 {"SC_PII_OSI", _SC_PII_OSI},
10419#endif
10420#ifdef _SC_PII_OSI_CLTS
10421 {"SC_PII_OSI_CLTS", _SC_PII_OSI_CLTS},
10422#endif
10423#ifdef _SC_PII_OSI_COTS
10424 {"SC_PII_OSI_COTS", _SC_PII_OSI_COTS},
10425#endif
10426#ifdef _SC_PII_OSI_M
10427 {"SC_PII_OSI_M", _SC_PII_OSI_M},
10428#endif
10429#ifdef _SC_PII_SOCKET
10430 {"SC_PII_SOCKET", _SC_PII_SOCKET},
10431#endif
10432#ifdef _SC_PII_XTI
10433 {"SC_PII_XTI", _SC_PII_XTI},
10434#endif
10435#ifdef _SC_POLL
10436 {"SC_POLL", _SC_POLL},
10437#endif
10438#ifdef _SC_PRIORITIZED_IO
10439 {"SC_PRIORITIZED_IO", _SC_PRIORITIZED_IO},
10440#endif
10441#ifdef _SC_PRIORITY_SCHEDULING
10442 {"SC_PRIORITY_SCHEDULING", _SC_PRIORITY_SCHEDULING},
10443#endif
10444#ifdef _SC_REALTIME_SIGNALS
10445 {"SC_REALTIME_SIGNALS", _SC_REALTIME_SIGNALS},
10446#endif
10447#ifdef _SC_RE_DUP_MAX
10448 {"SC_RE_DUP_MAX", _SC_RE_DUP_MAX},
10449#endif
10450#ifdef _SC_RTSIG_MAX
10451 {"SC_RTSIG_MAX", _SC_RTSIG_MAX},
10452#endif
10453#ifdef _SC_SAVED_IDS
10454 {"SC_SAVED_IDS", _SC_SAVED_IDS},
10455#endif
10456#ifdef _SC_SCHAR_MAX
10457 {"SC_SCHAR_MAX", _SC_SCHAR_MAX},
10458#endif
10459#ifdef _SC_SCHAR_MIN
10460 {"SC_SCHAR_MIN", _SC_SCHAR_MIN},
10461#endif
10462#ifdef _SC_SELECT
10463 {"SC_SELECT", _SC_SELECT},
10464#endif
10465#ifdef _SC_SEMAPHORES
10466 {"SC_SEMAPHORES", _SC_SEMAPHORES},
10467#endif
10468#ifdef _SC_SEM_NSEMS_MAX
10469 {"SC_SEM_NSEMS_MAX", _SC_SEM_NSEMS_MAX},
10470#endif
10471#ifdef _SC_SEM_VALUE_MAX
10472 {"SC_SEM_VALUE_MAX", _SC_SEM_VALUE_MAX},
10473#endif
10474#ifdef _SC_SHARED_MEMORY_OBJECTS
10475 {"SC_SHARED_MEMORY_OBJECTS", _SC_SHARED_MEMORY_OBJECTS},
10476#endif
10477#ifdef _SC_SHRT_MAX
10478 {"SC_SHRT_MAX", _SC_SHRT_MAX},
10479#endif
10480#ifdef _SC_SHRT_MIN
10481 {"SC_SHRT_MIN", _SC_SHRT_MIN},
10482#endif
10483#ifdef _SC_SIGQUEUE_MAX
10484 {"SC_SIGQUEUE_MAX", _SC_SIGQUEUE_MAX},
10485#endif
10486#ifdef _SC_SIGRT_MAX
10487 {"SC_SIGRT_MAX", _SC_SIGRT_MAX},
10488#endif
10489#ifdef _SC_SIGRT_MIN
10490 {"SC_SIGRT_MIN", _SC_SIGRT_MIN},
10491#endif
10492#ifdef _SC_SOFTPOWER
10493 {"SC_SOFTPOWER", _SC_SOFTPOWER},
10494#endif
10495#ifdef _SC_SPLIT_CACHE
10496 {"SC_SPLIT_CACHE", _SC_SPLIT_CACHE},
10497#endif
10498#ifdef _SC_SSIZE_MAX
10499 {"SC_SSIZE_MAX", _SC_SSIZE_MAX},
10500#endif
10501#ifdef _SC_STACK_PROT
10502 {"SC_STACK_PROT", _SC_STACK_PROT},
10503#endif
10504#ifdef _SC_STREAM_MAX
10505 {"SC_STREAM_MAX", _SC_STREAM_MAX},
10506#endif
10507#ifdef _SC_SYNCHRONIZED_IO
10508 {"SC_SYNCHRONIZED_IO", _SC_SYNCHRONIZED_IO},
10509#endif
10510#ifdef _SC_THREADS
10511 {"SC_THREADS", _SC_THREADS},
10512#endif
10513#ifdef _SC_THREAD_ATTR_STACKADDR
10514 {"SC_THREAD_ATTR_STACKADDR", _SC_THREAD_ATTR_STACKADDR},
10515#endif
10516#ifdef _SC_THREAD_ATTR_STACKSIZE
10517 {"SC_THREAD_ATTR_STACKSIZE", _SC_THREAD_ATTR_STACKSIZE},
10518#endif
10519#ifdef _SC_THREAD_DESTRUCTOR_ITERATIONS
10520 {"SC_THREAD_DESTRUCTOR_ITERATIONS", _SC_THREAD_DESTRUCTOR_ITERATIONS},
10521#endif
10522#ifdef _SC_THREAD_KEYS_MAX
10523 {"SC_THREAD_KEYS_MAX", _SC_THREAD_KEYS_MAX},
10524#endif
10525#ifdef _SC_THREAD_PRIORITY_SCHEDULING
10526 {"SC_THREAD_PRIORITY_SCHEDULING", _SC_THREAD_PRIORITY_SCHEDULING},
10527#endif
10528#ifdef _SC_THREAD_PRIO_INHERIT
10529 {"SC_THREAD_PRIO_INHERIT", _SC_THREAD_PRIO_INHERIT},
10530#endif
10531#ifdef _SC_THREAD_PRIO_PROTECT
10532 {"SC_THREAD_PRIO_PROTECT", _SC_THREAD_PRIO_PROTECT},
10533#endif
10534#ifdef _SC_THREAD_PROCESS_SHARED
10535 {"SC_THREAD_PROCESS_SHARED", _SC_THREAD_PROCESS_SHARED},
10536#endif
10537#ifdef _SC_THREAD_SAFE_FUNCTIONS
10538 {"SC_THREAD_SAFE_FUNCTIONS", _SC_THREAD_SAFE_FUNCTIONS},
10539#endif
10540#ifdef _SC_THREAD_STACK_MIN
10541 {"SC_THREAD_STACK_MIN", _SC_THREAD_STACK_MIN},
10542#endif
10543#ifdef _SC_THREAD_THREADS_MAX
10544 {"SC_THREAD_THREADS_MAX", _SC_THREAD_THREADS_MAX},
10545#endif
10546#ifdef _SC_TIMERS
10547 {"SC_TIMERS", _SC_TIMERS},
10548#endif
10549#ifdef _SC_TIMER_MAX
10550 {"SC_TIMER_MAX", _SC_TIMER_MAX},
10551#endif
10552#ifdef _SC_TTY_NAME_MAX
10553 {"SC_TTY_NAME_MAX", _SC_TTY_NAME_MAX},
10554#endif
10555#ifdef _SC_TZNAME_MAX
10556 {"SC_TZNAME_MAX", _SC_TZNAME_MAX},
10557#endif
10558#ifdef _SC_T_IOV_MAX
10559 {"SC_T_IOV_MAX", _SC_T_IOV_MAX},
10560#endif
10561#ifdef _SC_UCHAR_MAX
10562 {"SC_UCHAR_MAX", _SC_UCHAR_MAX},
10563#endif
10564#ifdef _SC_UINT_MAX
10565 {"SC_UINT_MAX", _SC_UINT_MAX},
10566#endif
10567#ifdef _SC_UIO_MAXIOV
10568 {"SC_UIO_MAXIOV", _SC_UIO_MAXIOV},
10569#endif
10570#ifdef _SC_ULONG_MAX
10571 {"SC_ULONG_MAX", _SC_ULONG_MAX},
10572#endif
10573#ifdef _SC_USHRT_MAX
10574 {"SC_USHRT_MAX", _SC_USHRT_MAX},
10575#endif
10576#ifdef _SC_VERSION
10577 {"SC_VERSION", _SC_VERSION},
10578#endif
10579#ifdef _SC_WORD_BIT
10580 {"SC_WORD_BIT", _SC_WORD_BIT},
10581#endif
10582#ifdef _SC_XBS5_ILP32_OFF32
10583 {"SC_XBS5_ILP32_OFF32", _SC_XBS5_ILP32_OFF32},
10584#endif
10585#ifdef _SC_XBS5_ILP32_OFFBIG
10586 {"SC_XBS5_ILP32_OFFBIG", _SC_XBS5_ILP32_OFFBIG},
10587#endif
10588#ifdef _SC_XBS5_LP64_OFF64
10589 {"SC_XBS5_LP64_OFF64", _SC_XBS5_LP64_OFF64},
10590#endif
10591#ifdef _SC_XBS5_LPBIG_OFFBIG
10592 {"SC_XBS5_LPBIG_OFFBIG", _SC_XBS5_LPBIG_OFFBIG},
10593#endif
10594#ifdef _SC_XOPEN_CRYPT
10595 {"SC_XOPEN_CRYPT", _SC_XOPEN_CRYPT},
10596#endif
10597#ifdef _SC_XOPEN_ENH_I18N
10598 {"SC_XOPEN_ENH_I18N", _SC_XOPEN_ENH_I18N},
10599#endif
10600#ifdef _SC_XOPEN_LEGACY
10601 {"SC_XOPEN_LEGACY", _SC_XOPEN_LEGACY},
10602#endif
10603#ifdef _SC_XOPEN_REALTIME
10604 {"SC_XOPEN_REALTIME", _SC_XOPEN_REALTIME},
10605#endif
10606#ifdef _SC_XOPEN_REALTIME_THREADS
10607 {"SC_XOPEN_REALTIME_THREADS", _SC_XOPEN_REALTIME_THREADS},
10608#endif
10609#ifdef _SC_XOPEN_SHM
10610 {"SC_XOPEN_SHM", _SC_XOPEN_SHM},
10611#endif
10612#ifdef _SC_XOPEN_UNIX
10613 {"SC_XOPEN_UNIX", _SC_XOPEN_UNIX},
10614#endif
10615#ifdef _SC_XOPEN_VERSION
10616 {"SC_XOPEN_VERSION", _SC_XOPEN_VERSION},
10617#endif
10618#ifdef _SC_XOPEN_XCU_VERSION
10619 {"SC_XOPEN_XCU_VERSION", _SC_XOPEN_XCU_VERSION},
10620#endif
10621#ifdef _SC_XOPEN_XPG2
10622 {"SC_XOPEN_XPG2", _SC_XOPEN_XPG2},
10623#endif
10624#ifdef _SC_XOPEN_XPG3
10625 {"SC_XOPEN_XPG3", _SC_XOPEN_XPG3},
10626#endif
10627#ifdef _SC_XOPEN_XPG4
10628 {"SC_XOPEN_XPG4", _SC_XOPEN_XPG4},
10629#endif
10630};
10631
10632static int
10633conv_sysconf_confname(PyObject *arg, int *valuep)
10634{
10635 return conv_confname(arg, valuep, posix_constants_sysconf,
10636 sizeof(posix_constants_sysconf)
10637 / sizeof(struct constdef));
10638}
10639
10640
10641/*[clinic input]
10642os.sysconf -> long
10643 name: sysconf_confname
10644 /
10645
10646Return an integer-valued system configuration variable.
10647[clinic start generated code]*/
10648
10649static long
10650os_sysconf_impl(PyObject *module, int name)
10651/*[clinic end generated code: output=3662f945fc0cc756 input=279e3430a33f29e4]*/
10652{
10653 long value;
10654
10655 errno = 0;
10656 value = sysconf(name);
10657 if (value == -1 && errno != 0)
10658 posix_error();
10659 return value;
10660}
10661#endif /* HAVE_SYSCONF */
10662
10663
10664/* This code is used to ensure that the tables of configuration value names
10665 * are in sorted order as required by conv_confname(), and also to build
10666 * the exported dictionaries that are used to publish information about the
10667 * names available on the host platform.
10668 *
10669 * Sorting the table at runtime ensures that the table is properly ordered
10670 * when used, even for platforms we're not able to test on. It also makes
10671 * it easier to add additional entries to the tables.
10672 */
10673
10674static int
10675cmp_constdefs(const void *v1, const void *v2)
10676{
10677 const struct constdef *c1 =
10678 (const struct constdef *) v1;
10679 const struct constdef *c2 =
10680 (const struct constdef *) v2;
10681
10682 return strcmp(c1->name, c2->name);
10683}
10684
10685static int
10686setup_confname_table(struct constdef *table, size_t tablesize,
10687 const char *tablename, PyObject *module)
10688{
10689 PyObject *d = NULL;
10690 size_t i;
10691
10692 qsort(table, tablesize, sizeof(struct constdef), cmp_constdefs);
10693 d = PyDict_New();
10694 if (d == NULL)
10695 return -1;
10696
10697 for (i=0; i < tablesize; ++i) {
10698 PyObject *o = PyLong_FromLong(table[i].value);
10699 if (o == NULL || PyDict_SetItemString(d, table[i].name, o) == -1) {
10700 Py_XDECREF(o);
10701 Py_DECREF(d);
10702 return -1;
10703 }
10704 Py_DECREF(o);
10705 }
10706 return PyModule_AddObject(module, tablename, d);
10707}
10708
10709/* Return -1 on failure, 0 on success. */
10710static int
10711setup_confname_tables(PyObject *module)
10712{
10713#if defined(HAVE_FPATHCONF) || defined(HAVE_PATHCONF)
10714 if (setup_confname_table(posix_constants_pathconf,
10715 sizeof(posix_constants_pathconf)
10716 / sizeof(struct constdef),
10717 "pathconf_names", module))
10718 return -1;
10719#endif
10720#ifdef HAVE_CONFSTR
10721 if (setup_confname_table(posix_constants_confstr,
10722 sizeof(posix_constants_confstr)
10723 / sizeof(struct constdef),
10724 "confstr_names", module))
10725 return -1;
10726#endif
10727#ifdef HAVE_SYSCONF
10728 if (setup_confname_table(posix_constants_sysconf,
10729 sizeof(posix_constants_sysconf)
10730 / sizeof(struct constdef),
10731 "sysconf_names", module))
10732 return -1;
10733#endif
10734 return 0;
10735}
10736
10737
10738/*[clinic input]
10739os.abort
10740
10741Abort the interpreter immediately.
10742
10743This function 'dumps core' or otherwise fails in the hardest way possible
10744on the hosting operating system. This function never returns.
10745[clinic start generated code]*/
10746
10747static PyObject *
10748os_abort_impl(PyObject *module)
10749/*[clinic end generated code: output=dcf52586dad2467c input=cf2c7d98bc504047]*/
10750{
10751 abort();
10752 /*NOTREACHED*/
10753#ifndef __clang__
10754 /* Issue #28152: abort() is declared with __attribute__((__noreturn__)).
10755 GCC emits a warning without "return NULL;" (compiler bug?), but Clang
10756 is smarter and emits a warning on the return. */
10757 Py_FatalError("abort() called from Python code didn't abort!");
10758 return NULL;
10759#endif
10760}
10761
10762#ifdef MS_WINDOWS
10763/* Grab ShellExecute dynamically from shell32 */
10764static int has_ShellExecute = -1;
10765static HINSTANCE (CALLBACK *Py_ShellExecuteW)(HWND, LPCWSTR, LPCWSTR, LPCWSTR,
10766 LPCWSTR, INT);
10767static int
10768check_ShellExecute()
10769{
10770 HINSTANCE hShell32;
10771
10772 /* only recheck */
10773 if (-1 == has_ShellExecute) {
10774 Py_BEGIN_ALLOW_THREADS
10775 /* Security note: this call is not vulnerable to "DLL hijacking".
10776 SHELL32 is part of "KnownDLLs" and so Windows always load
10777 the system SHELL32.DLL, even if there is another SHELL32.DLL
10778 in the DLL search path. */
10779 hShell32 = LoadLibraryW(L"SHELL32");
10780 Py_END_ALLOW_THREADS
10781 if (hShell32) {
10782 *(FARPROC*)&Py_ShellExecuteW = GetProcAddress(hShell32,
10783 "ShellExecuteW");
10784 has_ShellExecute = Py_ShellExecuteW != NULL;
10785 } else {
10786 has_ShellExecute = 0;
10787 }
10788 }
10789 return has_ShellExecute;
10790}
10791
10792
10793/*[clinic input]
10794os.startfile
10795 filepath: path_t
10796 operation: Py_UNICODE = NULL
10797
10798startfile(filepath [, operation])
10799
10800Start a file with its associated application.
10801
10802When "operation" is not specified or "open", this acts like
10803double-clicking the file in Explorer, or giving the file name as an
10804argument to the DOS "start" command: the file is opened with whatever
10805application (if any) its extension is associated.
10806When another "operation" is given, it specifies what should be done with
10807the file. A typical operation is "print".
10808
10809startfile returns as soon as the associated application is launched.
10810There is no option to wait for the application to close, and no way
10811to retrieve the application's exit status.
10812
10813The filepath is relative to the current directory. If you want to use
10814an absolute path, make sure the first character is not a slash ("/");
10815the underlying Win32 ShellExecute function doesn't work if it is.
10816[clinic start generated code]*/
10817
10818static PyObject *
10819os_startfile_impl(PyObject *module, path_t *filepath,
10820 const Py_UNICODE *operation)
10821/*[clinic end generated code: output=66dc311c94d50797 input=63950bf2986380d0]*/
10822{
10823 HINSTANCE rc;
10824
10825 if(!check_ShellExecute()) {
10826 /* If the OS doesn't have ShellExecute, return a
10827 NotImplementedError. */
10828 return PyErr_Format(PyExc_NotImplementedError,
10829 "startfile not available on this platform");
10830 }
10831
10832 Py_BEGIN_ALLOW_THREADS
10833 rc = Py_ShellExecuteW((HWND)0, operation, filepath->wide,
10834 NULL, NULL, SW_SHOWNORMAL);
10835 Py_END_ALLOW_THREADS
10836
10837 if (rc <= (HINSTANCE)32) {
10838 win32_error_object("startfile", filepath->object);
10839 return NULL;
10840 }
10841 Py_RETURN_NONE;
10842}
10843#endif /* MS_WINDOWS */
10844
10845
10846#ifdef HAVE_GETLOADAVG
10847/*[clinic input]
10848os.getloadavg
10849
10850Return average recent system load information.
10851
10852Return the number of processes in the system run queue averaged over
10853the last 1, 5, and 15 minutes as a tuple of three floats.
10854Raises OSError if the load average was unobtainable.
10855[clinic start generated code]*/
10856
10857static PyObject *
10858os_getloadavg_impl(PyObject *module)
10859/*[clinic end generated code: output=9ad3a11bfb4f4bd2 input=3d6d826b76d8a34e]*/
10860{
10861 double loadavg[3];
10862 if (getloadavg(loadavg, 3)!=3) {
10863 PyErr_SetString(PyExc_OSError, "Load averages are unobtainable");
10864 return NULL;
10865 } else
10866 return Py_BuildValue("ddd", loadavg[0], loadavg[1], loadavg[2]);
10867}
10868#endif /* HAVE_GETLOADAVG */
10869
10870
10871/*[clinic input]
10872os.device_encoding
10873 fd: int
10874
10875Return a string describing the encoding of a terminal's file descriptor.
10876
10877The file descriptor must be attached to a terminal.
10878If the device is not a terminal, return None.
10879[clinic start generated code]*/
10880
10881static PyObject *
10882os_device_encoding_impl(PyObject *module, int fd)
10883/*[clinic end generated code: output=e0d294bbab7e8c2b input=9e1d4a42b66df312]*/
10884{
10885 return _Py_device_encoding(fd);
10886}
10887
10888
10889#ifdef HAVE_SETRESUID
10890/*[clinic input]
10891os.setresuid
10892
10893 ruid: uid_t
10894 euid: uid_t
10895 suid: uid_t
10896 /
10897
10898Set the current process's real, effective, and saved user ids.
10899[clinic start generated code]*/
10900
10901static PyObject *
10902os_setresuid_impl(PyObject *module, uid_t ruid, uid_t euid, uid_t suid)
10903/*[clinic end generated code: output=834a641e15373e97 input=9e33cb79a82792f3]*/
10904{
10905 if (setresuid(ruid, euid, suid) < 0)
10906 return posix_error();
10907 Py_RETURN_NONE;
10908}
10909#endif /* HAVE_SETRESUID */
10910
10911
10912#ifdef HAVE_SETRESGID
10913/*[clinic input]
10914os.setresgid
10915
10916 rgid: gid_t
10917 egid: gid_t
10918 sgid: gid_t
10919 /
10920
10921Set the current process's real, effective, and saved group ids.
10922[clinic start generated code]*/
10923
10924static PyObject *
10925os_setresgid_impl(PyObject *module, gid_t rgid, gid_t egid, gid_t sgid)
10926/*[clinic end generated code: output=6aa402f3d2e514a9 input=33e9e0785ef426b1]*/
10927{
10928 if (setresgid(rgid, egid, sgid) < 0)
10929 return posix_error();
10930 Py_RETURN_NONE;
10931}
10932#endif /* HAVE_SETRESGID */
10933
10934
10935#ifdef HAVE_GETRESUID
10936/*[clinic input]
10937os.getresuid
10938
10939Return a tuple of the current process's real, effective, and saved user ids.
10940[clinic start generated code]*/
10941
10942static PyObject *
10943os_getresuid_impl(PyObject *module)
10944/*[clinic end generated code: output=8e0becff5dece5bf input=41ccfa8e1f6517ad]*/
10945{
10946 uid_t ruid, euid, suid;
10947 if (getresuid(&ruid, &euid, &suid) < 0)
10948 return posix_error();
10949 return Py_BuildValue("(NNN)", _PyLong_FromUid(ruid),
10950 _PyLong_FromUid(euid),
10951 _PyLong_FromUid(suid));
10952}
10953#endif /* HAVE_GETRESUID */
10954
10955
10956#ifdef HAVE_GETRESGID
10957/*[clinic input]
10958os.getresgid
10959
10960Return a tuple of the current process's real, effective, and saved group ids.
10961[clinic start generated code]*/
10962
10963static PyObject *
10964os_getresgid_impl(PyObject *module)
10965/*[clinic end generated code: output=2719c4bfcf27fb9f input=517e68db9ca32df6]*/
10966{
10967 gid_t rgid, egid, sgid;
10968 if (getresgid(&rgid, &egid, &sgid) < 0)
10969 return posix_error();
10970 return Py_BuildValue("(NNN)", _PyLong_FromGid(rgid),
10971 _PyLong_FromGid(egid),
10972 _PyLong_FromGid(sgid));
10973}
10974#endif /* HAVE_GETRESGID */
10975
10976
10977#ifdef USE_XATTRS
10978/*[clinic input]
10979os.getxattr
10980
10981 path: path_t(allow_fd=True)
10982 attribute: path_t
10983 *
10984 follow_symlinks: bool = True
10985
10986Return the value of extended attribute attribute on path.
10987
10988path may be either a string, a path-like object, or an open file descriptor.
10989If follow_symlinks is False, and the last element of the path is a symbolic
10990 link, getxattr will examine the symbolic link itself instead of the file
10991 the link points to.
10992
10993[clinic start generated code]*/
10994
10995static PyObject *
10996os_getxattr_impl(PyObject *module, path_t *path, path_t *attribute,
10997 int follow_symlinks)
10998/*[clinic end generated code: output=5f2f44200a43cff2 input=025789491708f7eb]*/
10999{
11000 Py_ssize_t i;
11001 PyObject *buffer = NULL;
11002
11003 if (fd_and_follow_symlinks_invalid("getxattr", path->fd, follow_symlinks))
11004 return NULL;
11005
11006 for (i = 0; ; i++) {
11007 void *ptr;
11008 ssize_t result;
11009 static const Py_ssize_t buffer_sizes[] = {128, XATTR_SIZE_MAX, 0};
11010 Py_ssize_t buffer_size = buffer_sizes[i];
11011 if (!buffer_size) {
11012 path_error(path);
11013 return NULL;
11014 }
11015 buffer = PyBytes_FromStringAndSize(NULL, buffer_size);
11016 if (!buffer)
11017 return NULL;
11018 ptr = PyBytes_AS_STRING(buffer);
11019
11020 Py_BEGIN_ALLOW_THREADS;
11021 if (path->fd >= 0)
11022 result = fgetxattr(path->fd, attribute->narrow, ptr, buffer_size);
11023 else if (follow_symlinks)
11024 result = getxattr(path->narrow, attribute->narrow, ptr, buffer_size);
11025 else
11026 result = lgetxattr(path->narrow, attribute->narrow, ptr, buffer_size);
11027 Py_END_ALLOW_THREADS;
11028
11029 if (result < 0) {
11030 Py_DECREF(buffer);
11031 if (errno == ERANGE)
11032 continue;
11033 path_error(path);
11034 return NULL;
11035 }
11036
11037 if (result != buffer_size) {
11038 /* Can only shrink. */
11039 _PyBytes_Resize(&buffer, result);
11040 }
11041 break;
11042 }
11043
11044 return buffer;
11045}
11046
11047
11048/*[clinic input]
11049os.setxattr
11050
11051 path: path_t(allow_fd=True)
11052 attribute: path_t
11053 value: Py_buffer
11054 flags: int = 0
11055 *
11056 follow_symlinks: bool = True
11057
11058Set extended attribute attribute on path to value.
11059
11060path may be either a string, a path-like object, or an open file descriptor.
11061If follow_symlinks is False, and the last element of the path is a symbolic
11062 link, setxattr will modify the symbolic link itself instead of the file
11063 the link points to.
11064
11065[clinic start generated code]*/
11066
11067static PyObject *
11068os_setxattr_impl(PyObject *module, path_t *path, path_t *attribute,
11069 Py_buffer *value, int flags, int follow_symlinks)
11070/*[clinic end generated code: output=98b83f63fdde26bb input=c17c0103009042f0]*/
11071{
11072 ssize_t result;
11073
11074 if (fd_and_follow_symlinks_invalid("setxattr", path->fd, follow_symlinks))
11075 return NULL;
11076
11077 Py_BEGIN_ALLOW_THREADS;
11078 if (path->fd > -1)
11079 result = fsetxattr(path->fd, attribute->narrow,
11080 value->buf, value->len, flags);
11081 else if (follow_symlinks)
11082 result = setxattr(path->narrow, attribute->narrow,
11083 value->buf, value->len, flags);
11084 else
11085 result = lsetxattr(path->narrow, attribute->narrow,
11086 value->buf, value->len, flags);
11087 Py_END_ALLOW_THREADS;
11088
11089 if (result) {
11090 path_error(path);
11091 return NULL;
11092 }
11093
11094 Py_RETURN_NONE;
11095}
11096
11097
11098/*[clinic input]
11099os.removexattr
11100
11101 path: path_t(allow_fd=True)
11102 attribute: path_t
11103 *
11104 follow_symlinks: bool = True
11105
11106Remove extended attribute attribute on path.
11107
11108path may be either a string, a path-like object, or an open file descriptor.
11109If follow_symlinks is False, and the last element of the path is a symbolic
11110 link, removexattr will modify the symbolic link itself instead of the file
11111 the link points to.
11112
11113[clinic start generated code]*/
11114
11115static PyObject *
11116os_removexattr_impl(PyObject *module, path_t *path, path_t *attribute,
11117 int follow_symlinks)
11118/*[clinic end generated code: output=521a51817980cda6 input=3d9a7d36fe2f7c4e]*/
11119{
11120 ssize_t result;
11121
11122 if (fd_and_follow_symlinks_invalid("removexattr", path->fd, follow_symlinks))
11123 return NULL;
11124
11125 Py_BEGIN_ALLOW_THREADS;
11126 if (path->fd > -1)
11127 result = fremovexattr(path->fd, attribute->narrow);
11128 else if (follow_symlinks)
11129 result = removexattr(path->narrow, attribute->narrow);
11130 else
11131 result = lremovexattr(path->narrow, attribute->narrow);
11132 Py_END_ALLOW_THREADS;
11133
11134 if (result) {
11135 return path_error(path);
11136 }
11137
11138 Py_RETURN_NONE;
11139}
11140
11141
11142/*[clinic input]
11143os.listxattr
11144
11145 path: path_t(allow_fd=True, nullable=True) = None
11146 *
11147 follow_symlinks: bool = True
11148
11149Return a list of extended attributes on path.
11150
11151path may be either None, a string, a path-like object, or an open file descriptor.
11152if path is None, listxattr will examine the current directory.
11153If follow_symlinks is False, and the last element of the path is a symbolic
11154 link, listxattr will examine the symbolic link itself instead of the file
11155 the link points to.
11156[clinic start generated code]*/
11157
11158static PyObject *
11159os_listxattr_impl(PyObject *module, path_t *path, int follow_symlinks)
11160/*[clinic end generated code: output=bebdb4e2ad0ce435 input=9826edf9fdb90869]*/
11161{
11162 Py_ssize_t i;
11163 PyObject *result = NULL;
11164 const char *name;
11165 char *buffer = NULL;
11166
11167 if (fd_and_follow_symlinks_invalid("listxattr", path->fd, follow_symlinks))
11168 goto exit;
11169
11170 name = path->narrow ? path->narrow : ".";
11171
11172 for (i = 0; ; i++) {
11173 const char *start, *trace, *end;
11174 ssize_t length;
11175 static const Py_ssize_t buffer_sizes[] = { 256, XATTR_LIST_MAX, 0 };
11176 Py_ssize_t buffer_size = buffer_sizes[i];
11177 if (!buffer_size) {
11178 /* ERANGE */
11179 path_error(path);
11180 break;
11181 }
11182 buffer = PyMem_MALLOC(buffer_size);
11183 if (!buffer) {
11184 PyErr_NoMemory();
11185 break;
11186 }
11187
11188 Py_BEGIN_ALLOW_THREADS;
11189 if (path->fd > -1)
11190 length = flistxattr(path->fd, buffer, buffer_size);
11191 else if (follow_symlinks)
11192 length = listxattr(name, buffer, buffer_size);
11193 else
11194 length = llistxattr(name, buffer, buffer_size);
11195 Py_END_ALLOW_THREADS;
11196
11197 if (length < 0) {
11198 if (errno == ERANGE) {
11199 PyMem_FREE(buffer);
11200 buffer = NULL;
11201 continue;
11202 }
11203 path_error(path);
11204 break;
11205 }
11206
11207 result = PyList_New(0);
11208 if (!result) {
11209 goto exit;
11210 }
11211
11212 end = buffer + length;
11213 for (trace = start = buffer; trace != end; trace++) {
11214 if (!*trace) {
11215 int error;
11216 PyObject *attribute = PyUnicode_DecodeFSDefaultAndSize(start,
11217 trace - start);
11218 if (!attribute) {
11219 Py_DECREF(result);
11220 result = NULL;
11221 goto exit;
11222 }
11223 error = PyList_Append(result, attribute);
11224 Py_DECREF(attribute);
11225 if (error) {
11226 Py_DECREF(result);
11227 result = NULL;
11228 goto exit;
11229 }
11230 start = trace + 1;
11231 }
11232 }
11233 break;
11234 }
11235exit:
11236 if (buffer)
11237 PyMem_FREE(buffer);
11238 return result;
11239}
11240#endif /* USE_XATTRS */
11241
11242
11243/*[clinic input]
11244os.urandom
11245
11246 size: Py_ssize_t
11247 /
11248
11249Return a bytes object containing random bytes suitable for cryptographic use.
11250[clinic start generated code]*/
11251
11252static PyObject *
11253os_urandom_impl(PyObject *module, Py_ssize_t size)
11254/*[clinic end generated code: output=42c5cca9d18068e9 input=4067cdb1b6776c29]*/
11255{
11256 PyObject *bytes;
11257 int result;
11258
11259 if (size < 0)
11260 return PyErr_Format(PyExc_ValueError,
11261 "negative argument not allowed");
11262 bytes = PyBytes_FromStringAndSize(NULL, size);
11263 if (bytes == NULL)
11264 return NULL;
11265
11266 result = _PyOS_URandom(PyBytes_AS_STRING(bytes), PyBytes_GET_SIZE(bytes));
11267 if (result == -1) {
11268 Py_DECREF(bytes);
11269 return NULL;
11270 }
11271 return bytes;
11272}
11273
11274/* Terminal size querying */
11275
11276static PyTypeObject TerminalSizeType;
11277
11278PyDoc_STRVAR(TerminalSize_docstring,
11279 "A tuple of (columns, lines) for holding terminal window size");
11280
11281static PyStructSequence_Field TerminalSize_fields[] = {
11282 {"columns", "width of the terminal window in characters"},
11283 {"lines", "height of the terminal window in characters"},
11284 {NULL, NULL}
11285};
11286
11287static PyStructSequence_Desc TerminalSize_desc = {
11288 "os.terminal_size",
11289 TerminalSize_docstring,
11290 TerminalSize_fields,
11291 2,
11292};
11293
11294#if defined(TERMSIZE_USE_CONIO) || defined(TERMSIZE_USE_IOCTL)
11295/* AC 3.5: fd should accept None */
11296PyDoc_STRVAR(termsize__doc__,
11297 "Return the size of the terminal window as (columns, lines).\n" \
11298 "\n" \
11299 "The optional argument fd (default standard output) specifies\n" \
11300 "which file descriptor should be queried.\n" \
11301 "\n" \
11302 "If the file descriptor is not connected to a terminal, an OSError\n" \
11303 "is thrown.\n" \
11304 "\n" \
11305 "This function will only be defined if an implementation is\n" \
11306 "available for this system.\n" \
11307 "\n" \
11308 "shutil.get_terminal_size is the high-level function which should \n" \
11309 "normally be used, os.get_terminal_size is the low-level implementation.");
11310
11311static PyObject*
11312get_terminal_size(PyObject *self, PyObject *args)
11313{
11314 int columns, lines;
11315 PyObject *termsize;
11316
11317 int fd = fileno(stdout);
11318 /* Under some conditions stdout may not be connected and
11319 * fileno(stdout) may point to an invalid file descriptor. For example
11320 * GUI apps don't have valid standard streams by default.
11321 *
11322 * If this happens, and the optional fd argument is not present,
11323 * the ioctl below will fail returning EBADF. This is what we want.
11324 */
11325
11326 if (!PyArg_ParseTuple(args, "|i", &fd))
11327 return NULL;
11328
11329#ifdef TERMSIZE_USE_IOCTL
11330 {
11331 struct winsize w;
11332 if (ioctl(fd, TIOCGWINSZ, &w))
11333 return PyErr_SetFromErrno(PyExc_OSError);
11334 columns = w.ws_col;
11335 lines = w.ws_row;
11336 }
11337#endif /* TERMSIZE_USE_IOCTL */
11338
11339#ifdef TERMSIZE_USE_CONIO
11340 {
11341 DWORD nhandle;
11342 HANDLE handle;
11343 CONSOLE_SCREEN_BUFFER_INFO csbi;
11344 switch (fd) {
11345 case 0: nhandle = STD_INPUT_HANDLE;
11346 break;
11347 case 1: nhandle = STD_OUTPUT_HANDLE;
11348 break;
11349 case 2: nhandle = STD_ERROR_HANDLE;
11350 break;
11351 default:
11352 return PyErr_Format(PyExc_ValueError, "bad file descriptor");
11353 }
11354 handle = GetStdHandle(nhandle);
11355 if (handle == NULL)
11356 return PyErr_Format(PyExc_OSError, "handle cannot be retrieved");
11357 if (handle == INVALID_HANDLE_VALUE)
11358 return PyErr_SetFromWindowsErr(0);
11359
11360 if (!GetConsoleScreenBufferInfo(handle, &csbi))
11361 return PyErr_SetFromWindowsErr(0);
11362
11363 columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
11364 lines = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
11365 }
11366#endif /* TERMSIZE_USE_CONIO */
11367
11368 termsize = PyStructSequence_New(&TerminalSizeType);
11369 if (termsize == NULL)
11370 return NULL;
11371 PyStructSequence_SET_ITEM(termsize, 0, PyLong_FromLong(columns));
11372 PyStructSequence_SET_ITEM(termsize, 1, PyLong_FromLong(lines));
11373 if (PyErr_Occurred()) {
11374 Py_DECREF(termsize);
11375 return NULL;
11376 }
11377 return termsize;
11378}
11379#endif /* defined(TERMSIZE_USE_CONIO) || defined(TERMSIZE_USE_IOCTL) */
11380
11381
11382/*[clinic input]
11383os.cpu_count
11384
11385Return the number of CPUs in the system; return None if indeterminable.
11386
11387This number is not equivalent to the number of CPUs the current process can
11388use. The number of usable CPUs can be obtained with
11389``len(os.sched_getaffinity(0))``
11390[clinic start generated code]*/
11391
11392static PyObject *
11393os_cpu_count_impl(PyObject *module)
11394/*[clinic end generated code: output=5fc29463c3936a9c input=e7c8f4ba6dbbadd3]*/
11395{
11396 int ncpu = 0;
11397#ifdef MS_WINDOWS
11398 /* Vista is supported and the GetMaximumProcessorCount API is Win7+
11399 Need to fallback to Vista behavior if this call isn't present */
11400 HINSTANCE hKernel32;
11401 hKernel32 = GetModuleHandleW(L"KERNEL32");
11402
11403 static DWORD(CALLBACK *_GetMaximumProcessorCount)(WORD) = NULL;
11404 *(FARPROC*)&_GetMaximumProcessorCount = GetProcAddress(hKernel32,
11405 "GetMaximumProcessorCount");
11406 if (_GetMaximumProcessorCount != NULL) {
11407 ncpu = _GetMaximumProcessorCount(ALL_PROCESSOR_GROUPS);
11408 }
11409 else {
11410 SYSTEM_INFO sysinfo;
11411 GetSystemInfo(&sysinfo);
11412 ncpu = sysinfo.dwNumberOfProcessors;
11413 }
11414#elif defined(__hpux)
11415 ncpu = mpctl(MPC_GETNUMSPUS, NULL, NULL);
11416#elif defined(HAVE_SYSCONF) && defined(_SC_NPROCESSORS_ONLN)
11417 ncpu = sysconf(_SC_NPROCESSORS_ONLN);
11418#elif defined(__DragonFly__) || \
11419 defined(__OpenBSD__) || \
11420 defined(__FreeBSD__) || \
11421 defined(__NetBSD__) || \
11422 defined(__APPLE__)
11423 int mib[2];
11424 size_t len = sizeof(ncpu);
11425 mib[0] = CTL_HW;
11426 mib[1] = HW_NCPU;
11427 if (sysctl(mib, 2, &ncpu, &len, NULL, 0) != 0)
11428 ncpu = 0;
11429#endif
11430 if (ncpu >= 1)
11431 return PyLong_FromLong(ncpu);
11432 else
11433 Py_RETURN_NONE;
11434}
11435
11436
11437/*[clinic input]
11438os.get_inheritable -> bool
11439
11440 fd: int
11441 /
11442
11443Get the close-on-exe flag of the specified file descriptor.
11444[clinic start generated code]*/
11445
11446static int
11447os_get_inheritable_impl(PyObject *module, int fd)
11448/*[clinic end generated code: output=0445e20e149aa5b8 input=89ac008dc9ab6b95]*/
11449{
11450 int return_value;
11451 _Py_BEGIN_SUPPRESS_IPH
11452 return_value = _Py_get_inheritable(fd);
11453 _Py_END_SUPPRESS_IPH
11454 return return_value;
11455}
11456
11457
11458/*[clinic input]
11459os.set_inheritable
11460 fd: int
11461 inheritable: int
11462 /
11463
11464Set the inheritable flag of the specified file descriptor.
11465[clinic start generated code]*/
11466
11467static PyObject *
11468os_set_inheritable_impl(PyObject *module, int fd, int inheritable)
11469/*[clinic end generated code: output=f1b1918a2f3c38c2 input=9ceaead87a1e2402]*/
11470{
11471 int result;
11472
11473 _Py_BEGIN_SUPPRESS_IPH
11474 result = _Py_set_inheritable(fd, inheritable, NULL);
11475 _Py_END_SUPPRESS_IPH
11476 if (result < 0)
11477 return NULL;
11478 Py_RETURN_NONE;
11479}
11480
11481
11482#ifdef MS_WINDOWS
11483/*[clinic input]
11484os.get_handle_inheritable -> bool
11485 handle: intptr_t
11486 /
11487
11488Get the close-on-exe flag of the specified file descriptor.
11489[clinic start generated code]*/
11490
11491static int
11492os_get_handle_inheritable_impl(PyObject *module, intptr_t handle)
11493/*[clinic end generated code: output=36be5afca6ea84d8 input=cfe99f9c05c70ad1]*/
11494{
11495 DWORD flags;
11496
11497 if (!GetHandleInformation((HANDLE)handle, &flags)) {
11498 PyErr_SetFromWindowsErr(0);
11499 return -1;
11500 }
11501
11502 return flags & HANDLE_FLAG_INHERIT;
11503}
11504
11505
11506/*[clinic input]
11507os.set_handle_inheritable
11508 handle: intptr_t
11509 inheritable: bool
11510 /
11511
11512Set the inheritable flag of the specified handle.
11513[clinic start generated code]*/
11514
11515static PyObject *
11516os_set_handle_inheritable_impl(PyObject *module, intptr_t handle,
11517 int inheritable)
11518/*[clinic end generated code: output=021d74fe6c96baa3 input=7a7641390d8364fc]*/
11519{
11520 DWORD flags = inheritable ? HANDLE_FLAG_INHERIT : 0;
11521 if (!SetHandleInformation((HANDLE)handle, HANDLE_FLAG_INHERIT, flags)) {
11522 PyErr_SetFromWindowsErr(0);
11523 return NULL;
11524 }
11525 Py_RETURN_NONE;
11526}
11527#endif /* MS_WINDOWS */
11528
11529#ifndef MS_WINDOWS
11530PyDoc_STRVAR(get_blocking__doc__,
11531 "get_blocking(fd) -> bool\n" \
11532 "\n" \
11533 "Get the blocking mode of the file descriptor:\n" \
11534 "False if the O_NONBLOCK flag is set, True if the flag is cleared.");
11535
11536static PyObject*
11537posix_get_blocking(PyObject *self, PyObject *args)
11538{
11539 int fd;
11540 int blocking;
11541
11542 if (!PyArg_ParseTuple(args, "i:get_blocking", &fd))
11543 return NULL;
11544
11545 _Py_BEGIN_SUPPRESS_IPH
11546 blocking = _Py_get_blocking(fd);
11547 _Py_END_SUPPRESS_IPH
11548 if (blocking < 0)
11549 return NULL;
11550 return PyBool_FromLong(blocking);
11551}
11552
11553PyDoc_STRVAR(set_blocking__doc__,
11554 "set_blocking(fd, blocking)\n" \
11555 "\n" \
11556 "Set the blocking mode of the specified file descriptor.\n" \
11557 "Set the O_NONBLOCK flag if blocking is False,\n" \
11558 "clear the O_NONBLOCK flag otherwise.");
11559
11560static PyObject*
11561posix_set_blocking(PyObject *self, PyObject *args)
11562{
11563 int fd, blocking, result;
11564
11565 if (!PyArg_ParseTuple(args, "ii:set_blocking", &fd, &blocking))
11566 return NULL;
11567
11568 _Py_BEGIN_SUPPRESS_IPH
11569 result = _Py_set_blocking(fd, blocking);
11570 _Py_END_SUPPRESS_IPH
11571 if (result < 0)
11572 return NULL;
11573 Py_RETURN_NONE;
11574}
11575#endif /* !MS_WINDOWS */
11576
11577
11578/*[clinic input]
11579class os.DirEntry "DirEntry *" "&DirEntryType"
11580[clinic start generated code]*/
11581/*[clinic end generated code: output=da39a3ee5e6b4b0d input=3138f09f7c683f1d]*/
11582
11583typedef struct {
11584 PyObject_HEAD
11585 PyObject *name;
11586 PyObject *path;
11587 PyObject *stat;
11588 PyObject *lstat;
11589#ifdef MS_WINDOWS
11590 struct _Py_stat_struct win32_lstat;
11591 uint64_t win32_file_index;
11592 int got_file_index;
11593#else /* POSIX */
11594#ifdef HAVE_DIRENT_D_TYPE
11595 unsigned char d_type;
11596#endif
11597 ino_t d_ino;
11598 int dir_fd;
11599#endif
11600} DirEntry;
11601
11602static void
11603DirEntry_dealloc(DirEntry *entry)
11604{
11605 Py_XDECREF(entry->name);
11606 Py_XDECREF(entry->path);
11607 Py_XDECREF(entry->stat);
11608 Py_XDECREF(entry->lstat);
11609 Py_TYPE(entry)->tp_free((PyObject *)entry);
11610}
11611
11612/* Forward reference */
11613static int
11614DirEntry_test_mode(DirEntry *self, int follow_symlinks, unsigned short mode_bits);
11615
11616/*[clinic input]
11617os.DirEntry.is_symlink -> bool
11618
11619Return True if the entry is a symbolic link; cached per entry.
11620[clinic start generated code]*/
11621
11622static int
11623os_DirEntry_is_symlink_impl(DirEntry *self)
11624/*[clinic end generated code: output=42244667d7bcfc25 input=1605a1b4b96976c3]*/
11625{
11626#ifdef MS_WINDOWS
11627 return (self->win32_lstat.st_mode & S_IFMT) == S_IFLNK;
11628#elif defined(HAVE_DIRENT_D_TYPE)
11629 /* POSIX */
11630 if (self->d_type != DT_UNKNOWN)
11631 return self->d_type == DT_LNK;
11632 else
11633 return DirEntry_test_mode(self, 0, S_IFLNK);
11634#else
11635 /* POSIX without d_type */
11636 return DirEntry_test_mode(self, 0, S_IFLNK);
11637#endif
11638}
11639
11640static PyObject *
11641DirEntry_fetch_stat(DirEntry *self, int follow_symlinks)
11642{
11643 int result;
11644 STRUCT_STAT st;
11645 PyObject *ub;
11646
11647#ifdef MS_WINDOWS
11648 if (!PyUnicode_FSDecoder(self->path, &ub))
11649 return NULL;
11650 const wchar_t *path = PyUnicode_AsUnicode(ub);
11651#else /* POSIX */
11652 if (!PyUnicode_FSConverter(self->path, &ub))
11653 return NULL;
11654 const char *path = PyBytes_AS_STRING(ub);
11655 if (self->dir_fd != DEFAULT_DIR_FD) {
11656#ifdef HAVE_FSTATAT
11657 result = fstatat(self->dir_fd, path, &st,
11658 follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW);
11659#else
11660 PyErr_SetString(PyExc_NotImplementedError, "can't fetch stat");
11661 return NULL;
11662#endif /* HAVE_FSTATAT */
11663 }
11664 else
11665#endif
11666 {
11667 if (follow_symlinks)
11668 result = STAT(path, &st);
11669 else
11670 result = LSTAT(path, &st);
11671 }
11672 Py_DECREF(ub);
11673
11674 if (result != 0)
11675 return path_object_error(self->path);
11676
11677 return _pystat_fromstructstat(&st);
11678}
11679
11680static PyObject *
11681DirEntry_get_lstat(DirEntry *self)
11682{
11683 if (!self->lstat) {
11684#ifdef MS_WINDOWS
11685 self->lstat = _pystat_fromstructstat(&self->win32_lstat);
11686#else /* POSIX */
11687 self->lstat = DirEntry_fetch_stat(self, 0);
11688#endif
11689 }
11690 Py_XINCREF(self->lstat);
11691 return self->lstat;
11692}
11693
11694/*[clinic input]
11695os.DirEntry.stat
11696 *
11697 follow_symlinks: bool = True
11698
11699Return stat_result object for the entry; cached per entry.
11700[clinic start generated code]*/
11701
11702static PyObject *
11703os_DirEntry_stat_impl(DirEntry *self, int follow_symlinks)
11704/*[clinic end generated code: output=008593b3a6d01305 input=280d14c1d6f1d00d]*/
11705{
11706 if (!follow_symlinks)
11707 return DirEntry_get_lstat(self);
11708
11709 if (!self->stat) {
11710 int result = os_DirEntry_is_symlink_impl(self);
11711 if (result == -1)
11712 return NULL;
11713 else if (result)
11714 self->stat = DirEntry_fetch_stat(self, 1);
11715 else
11716 self->stat = DirEntry_get_lstat(self);
11717 }
11718
11719 Py_XINCREF(self->stat);
11720 return self->stat;
11721}
11722
11723/* Set exception and return -1 on error, 0 for False, 1 for True */
11724static int
11725DirEntry_test_mode(DirEntry *self, int follow_symlinks, unsigned short mode_bits)
11726{
11727 PyObject *stat = NULL;
11728 PyObject *st_mode = NULL;
11729 long mode;
11730 int result;
11731#if defined(MS_WINDOWS) || defined(HAVE_DIRENT_D_TYPE)
11732 int is_symlink;
11733 int need_stat;
11734#endif
11735#ifdef MS_WINDOWS
11736 unsigned long dir_bits;
11737#endif
11738 _Py_IDENTIFIER(st_mode);
11739
11740#ifdef MS_WINDOWS
11741 is_symlink = (self->win32_lstat.st_mode & S_IFMT) == S_IFLNK;
11742 need_stat = follow_symlinks && is_symlink;
11743#elif defined(HAVE_DIRENT_D_TYPE)
11744 is_symlink = self->d_type == DT_LNK;
11745 need_stat = self->d_type == DT_UNKNOWN || (follow_symlinks && is_symlink);
11746#endif
11747
11748#if defined(MS_WINDOWS) || defined(HAVE_DIRENT_D_TYPE)
11749 if (need_stat) {
11750#endif
11751 stat = os_DirEntry_stat_impl(self, follow_symlinks);
11752 if (!stat) {
11753 if (PyErr_ExceptionMatches(PyExc_FileNotFoundError)) {
11754 /* If file doesn't exist (anymore), then return False
11755 (i.e., say it's not a file/directory) */
11756 PyErr_Clear();
11757 return 0;
11758 }
11759 goto error;
11760 }
11761 st_mode = _PyObject_GetAttrId(stat, &PyId_st_mode);
11762 if (!st_mode)
11763 goto error;
11764
11765 mode = PyLong_AsLong(st_mode);
11766 if (mode == -1 && PyErr_Occurred())
11767 goto error;
11768 Py_CLEAR(st_mode);
11769 Py_CLEAR(stat);
11770 result = (mode & S_IFMT) == mode_bits;
11771#if defined(MS_WINDOWS) || defined(HAVE_DIRENT_D_TYPE)
11772 }
11773 else if (is_symlink) {
11774 assert(mode_bits != S_IFLNK);
11775 result = 0;
11776 }
11777 else {
11778 assert(mode_bits == S_IFDIR || mode_bits == S_IFREG);
11779#ifdef MS_WINDOWS
11780 dir_bits = self->win32_lstat.st_file_attributes & FILE_ATTRIBUTE_DIRECTORY;
11781 if (mode_bits == S_IFDIR)
11782 result = dir_bits != 0;
11783 else
11784 result = dir_bits == 0;
11785#else /* POSIX */
11786 if (mode_bits == S_IFDIR)
11787 result = self->d_type == DT_DIR;
11788 else
11789 result = self->d_type == DT_REG;
11790#endif
11791 }
11792#endif
11793
11794 return result;
11795
11796error:
11797 Py_XDECREF(st_mode);
11798 Py_XDECREF(stat);
11799 return -1;
11800}
11801
11802/*[clinic input]
11803os.DirEntry.is_dir -> bool
11804 *
11805 follow_symlinks: bool = True
11806
11807Return True if the entry is a directory; cached per entry.
11808[clinic start generated code]*/
11809
11810static int
11811os_DirEntry_is_dir_impl(DirEntry *self, int follow_symlinks)
11812/*[clinic end generated code: output=ad2e8d54365da287 input=0135232766f53f58]*/
11813{
11814 return DirEntry_test_mode(self, follow_symlinks, S_IFDIR);
11815}
11816
11817/*[clinic input]
11818os.DirEntry.is_file -> bool
11819 *
11820 follow_symlinks: bool = True
11821
11822Return True if the entry is a file; cached per entry.
11823[clinic start generated code]*/
11824
11825static int
11826os_DirEntry_is_file_impl(DirEntry *self, int follow_symlinks)
11827/*[clinic end generated code: output=8462ade481d8a476 input=0dc90be168b041ee]*/
11828{
11829 return DirEntry_test_mode(self, follow_symlinks, S_IFREG);
11830}
11831
11832/*[clinic input]
11833os.DirEntry.inode
11834
11835Return inode of the entry; cached per entry.
11836[clinic start generated code]*/
11837
11838static PyObject *
11839os_DirEntry_inode_impl(DirEntry *self)
11840/*[clinic end generated code: output=156bb3a72162440e input=3ee7b872ae8649f0]*/
11841{
11842#ifdef MS_WINDOWS
11843 if (!self->got_file_index) {
11844 PyObject *unicode;
11845 const wchar_t *path;
11846 STRUCT_STAT stat;
11847 int result;
11848
11849 if (!PyUnicode_FSDecoder(self->path, &unicode))
11850 return NULL;
11851 path = PyUnicode_AsUnicode(unicode);
11852 result = LSTAT(path, &stat);
11853 Py_DECREF(unicode);
11854
11855 if (result != 0)
11856 return path_object_error(self->path);
11857
11858 self->win32_file_index = stat.st_ino;
11859 self->got_file_index = 1;
11860 }
11861 Py_BUILD_ASSERT(sizeof(unsigned long long) >= sizeof(self->win32_file_index));
11862 return PyLong_FromUnsignedLongLong(self->win32_file_index);
11863#else /* POSIX */
11864 Py_BUILD_ASSERT(sizeof(unsigned long long) >= sizeof(self->d_ino));
11865 return PyLong_FromUnsignedLongLong(self->d_ino);
11866#endif
11867}
11868
11869static PyObject *
11870DirEntry_repr(DirEntry *self)
11871{
11872 return PyUnicode_FromFormat("<DirEntry %R>", self->name);
11873}
11874
11875/*[clinic input]
11876os.DirEntry.__fspath__
11877
11878Returns the path for the entry.
11879[clinic start generated code]*/
11880
11881static PyObject *
11882os_DirEntry___fspath___impl(DirEntry *self)
11883/*[clinic end generated code: output=6dd7f7ef752e6f4f input=3c49d0cf38df4fac]*/
11884{
11885 Py_INCREF(self->path);
11886 return self->path;
11887}
11888
11889static PyMemberDef DirEntry_members[] = {
11890 {"name", T_OBJECT_EX, offsetof(DirEntry, name), READONLY,
11891 "the entry's base filename, relative to scandir() \"path\" argument"},
11892 {"path", T_OBJECT_EX, offsetof(DirEntry, path), READONLY,
11893 "the entry's full path name; equivalent to os.path.join(scandir_path, entry.name)"},
11894 {NULL}
11895};
11896
11897#include "clinic/posixmodule.c.h"
11898
11899static PyMethodDef DirEntry_methods[] = {
11900 OS_DIRENTRY_IS_DIR_METHODDEF
11901 OS_DIRENTRY_IS_FILE_METHODDEF
11902 OS_DIRENTRY_IS_SYMLINK_METHODDEF
11903 OS_DIRENTRY_STAT_METHODDEF
11904 OS_DIRENTRY_INODE_METHODDEF
11905 OS_DIRENTRY___FSPATH___METHODDEF
11906 {NULL}
11907};
11908
11909static PyTypeObject DirEntryType = {
11910 PyVarObject_HEAD_INIT(NULL, 0)
11911 MODNAME ".DirEntry", /* tp_name */
11912 sizeof(DirEntry), /* tp_basicsize */
11913 0, /* tp_itemsize */
11914 /* methods */
11915 (destructor)DirEntry_dealloc, /* tp_dealloc */
11916 0, /* tp_print */
11917 0, /* tp_getattr */
11918 0, /* tp_setattr */
11919 0, /* tp_compare */
11920 (reprfunc)DirEntry_repr, /* tp_repr */
11921 0, /* tp_as_number */
11922 0, /* tp_as_sequence */
11923 0, /* tp_as_mapping */
11924 0, /* tp_hash */
11925 0, /* tp_call */
11926 0, /* tp_str */
11927 0, /* tp_getattro */
11928 0, /* tp_setattro */
11929 0, /* tp_as_buffer */
11930 Py_TPFLAGS_DEFAULT, /* tp_flags */
11931 0, /* tp_doc */
11932 0, /* tp_traverse */
11933 0, /* tp_clear */
11934 0, /* tp_richcompare */
11935 0, /* tp_weaklistoffset */
11936 0, /* tp_iter */
11937 0, /* tp_iternext */
11938 DirEntry_methods, /* tp_methods */
11939 DirEntry_members, /* tp_members */
11940};
11941
11942#ifdef MS_WINDOWS
11943
11944static wchar_t *
11945join_path_filenameW(const wchar_t *path_wide, const wchar_t *filename)
11946{
11947 Py_ssize_t path_len;
11948 Py_ssize_t size;
11949 wchar_t *result;
11950 wchar_t ch;
11951
11952 if (!path_wide) { /* Default arg: "." */
11953 path_wide = L".";
11954 path_len = 1;
11955 }
11956 else {
11957 path_len = wcslen(path_wide);
11958 }
11959
11960 /* The +1's are for the path separator and the NUL */
11961 size = path_len + 1 + wcslen(filename) + 1;
11962 result = PyMem_New(wchar_t, size);
11963 if (!result) {
11964 PyErr_NoMemory();
11965 return NULL;
11966 }
11967 wcscpy(result, path_wide);
11968 if (path_len > 0) {
11969 ch = result[path_len - 1];
11970 if (ch != SEP && ch != ALTSEP && ch != L':')
11971 result[path_len++] = SEP;
11972 wcscpy(result + path_len, filename);
11973 }
11974 return result;
11975}
11976
11977static PyObject *
11978DirEntry_from_find_data(path_t *path, WIN32_FIND_DATAW *dataW)
11979{
11980 DirEntry *entry;
11981 BY_HANDLE_FILE_INFORMATION file_info;
11982 ULONG reparse_tag;
11983 wchar_t *joined_path;
11984
11985 entry = PyObject_New(DirEntry, &DirEntryType);
11986 if (!entry)
11987 return NULL;
11988 entry->name = NULL;
11989 entry->path = NULL;
11990 entry->stat = NULL;
11991 entry->lstat = NULL;
11992 entry->got_file_index = 0;
11993
11994 entry->name = PyUnicode_FromWideChar(dataW->cFileName, -1);
11995 if (!entry->name)
11996 goto error;
11997 if (path->narrow) {
11998 Py_SETREF(entry->name, PyUnicode_EncodeFSDefault(entry->name));
11999 if (!entry->name)
12000 goto error;
12001 }
12002
12003 joined_path = join_path_filenameW(path->wide, dataW->cFileName);
12004 if (!joined_path)
12005 goto error;
12006
12007 entry->path = PyUnicode_FromWideChar(joined_path, -1);
12008 PyMem_Free(joined_path);
12009 if (!entry->path)
12010 goto error;
12011 if (path->narrow) {
12012 Py_SETREF(entry->path, PyUnicode_EncodeFSDefault(entry->path));
12013 if (!entry->path)
12014 goto error;
12015 }
12016
12017 find_data_to_file_info(dataW, &file_info, &reparse_tag);
12018 _Py_attribute_data_to_stat(&file_info, reparse_tag, &entry->win32_lstat);
12019
12020 return (PyObject *)entry;
12021
12022error:
12023 Py_DECREF(entry);
12024 return NULL;
12025}
12026
12027#else /* POSIX */
12028
12029static char *
12030join_path_filename(const char *path_narrow, const char* filename, Py_ssize_t filename_len)
12031{
12032 Py_ssize_t path_len;
12033 Py_ssize_t size;
12034 char *result;
12035
12036 if (!path_narrow) { /* Default arg: "." */
12037 path_narrow = ".";
12038 path_len = 1;
12039 }
12040 else {
12041 path_len = strlen(path_narrow);
12042 }
12043
12044 if (filename_len == -1)
12045 filename_len = strlen(filename);
12046
12047 /* The +1's are for the path separator and the NUL */
12048 size = path_len + 1 + filename_len + 1;
12049 result = PyMem_New(char, size);
12050 if (!result) {
12051 PyErr_NoMemory();
12052 return NULL;
12053 }
12054 strcpy(result, path_narrow);
12055 if (path_len > 0 && result[path_len - 1] != '/')
12056 result[path_len++] = '/';
12057 strcpy(result + path_len, filename);
12058 return result;
12059}
12060
12061static PyObject *
12062DirEntry_from_posix_info(path_t *path, const char *name, Py_ssize_t name_len,
12063 ino_t d_ino
12064#ifdef HAVE_DIRENT_D_TYPE
12065 , unsigned char d_type
12066#endif
12067 )
12068{
12069 DirEntry *entry;
12070 char *joined_path;
12071
12072 entry = PyObject_New(DirEntry, &DirEntryType);
12073 if (!entry)
12074 return NULL;
12075 entry->name = NULL;
12076 entry->path = NULL;
12077 entry->stat = NULL;
12078 entry->lstat = NULL;
12079
12080 if (path->fd != -1) {
12081 entry->dir_fd = path->fd;
12082 joined_path = NULL;
12083 }
12084 else {
12085 entry->dir_fd = DEFAULT_DIR_FD;
12086 joined_path = join_path_filename(path->narrow, name, name_len);
12087 if (!joined_path)
12088 goto error;
12089 }
12090
12091 if (!path->narrow || !PyObject_CheckBuffer(path->object)) {
12092 entry->name = PyUnicode_DecodeFSDefaultAndSize(name, name_len);
12093 if (joined_path)
12094 entry->path = PyUnicode_DecodeFSDefault(joined_path);
12095 }
12096 else {
12097 entry->name = PyBytes_FromStringAndSize(name, name_len);
12098 if (joined_path)
12099 entry->path = PyBytes_FromString(joined_path);
12100 }
12101 PyMem_Free(joined_path);
12102 if (!entry->name)
12103 goto error;
12104
12105 if (path->fd != -1) {
12106 entry->path = entry->name;
12107 Py_INCREF(entry->path);
12108 }
12109 else if (!entry->path)
12110 goto error;
12111
12112#ifdef HAVE_DIRENT_D_TYPE
12113 entry->d_type = d_type;
12114#endif
12115 entry->d_ino = d_ino;
12116
12117 return (PyObject *)entry;
12118
12119error:
12120 Py_XDECREF(entry);
12121 return NULL;
12122}
12123
12124#endif
12125
12126
12127typedef struct {
12128 PyObject_HEAD
12129 path_t path;
12130#ifdef MS_WINDOWS
12131 HANDLE handle;
12132 WIN32_FIND_DATAW file_data;
12133 int first_time;
12134#else /* POSIX */
12135 DIR *dirp;
12136#endif
12137#ifdef HAVE_FDOPENDIR
12138 int fd;
12139#endif
12140} ScandirIterator;
12141
12142#ifdef MS_WINDOWS
12143
12144static int
12145ScandirIterator_is_closed(ScandirIterator *iterator)
12146{
12147 return iterator->handle == INVALID_HANDLE_VALUE;
12148}
12149
12150static void
12151ScandirIterator_closedir(ScandirIterator *iterator)
12152{
12153 HANDLE handle = iterator->handle;
12154
12155 if (handle == INVALID_HANDLE_VALUE)
12156 return;
12157
12158 iterator->handle = INVALID_HANDLE_VALUE;
12159 Py_BEGIN_ALLOW_THREADS
12160 FindClose(handle);
12161 Py_END_ALLOW_THREADS
12162}
12163
12164static PyObject *
12165ScandirIterator_iternext(ScandirIterator *iterator)
12166{
12167 WIN32_FIND_DATAW *file_data = &iterator->file_data;
12168 BOOL success;
12169 PyObject *entry;
12170
12171 /* Happens if the iterator is iterated twice, or closed explicitly */
12172 if (iterator->handle == INVALID_HANDLE_VALUE)
12173 return NULL;
12174
12175 while (1) {
12176 if (!iterator->first_time) {
12177 Py_BEGIN_ALLOW_THREADS
12178 success = FindNextFileW(iterator->handle, file_data);
12179 Py_END_ALLOW_THREADS
12180 if (!success) {
12181 /* Error or no more files */
12182 if (GetLastError() != ERROR_NO_MORE_FILES)
12183 path_error(&iterator->path);
12184 break;
12185 }
12186 }
12187 iterator->first_time = 0;
12188
12189 /* Skip over . and .. */
12190 if (wcscmp(file_data->cFileName, L".") != 0 &&
12191 wcscmp(file_data->cFileName, L"..") != 0) {
12192 entry = DirEntry_from_find_data(&iterator->path, file_data);
12193 if (!entry)
12194 break;
12195 return entry;
12196 }
12197
12198 /* Loop till we get a non-dot directory or finish iterating */
12199 }
12200
12201 /* Error or no more files */
12202 ScandirIterator_closedir(iterator);
12203 return NULL;
12204}
12205
12206#else /* POSIX */
12207
12208static int
12209ScandirIterator_is_closed(ScandirIterator *iterator)
12210{
12211 return !iterator->dirp;
12212}
12213
12214static void
12215ScandirIterator_closedir(ScandirIterator *iterator)
12216{
12217 DIR *dirp = iterator->dirp;
12218
12219 if (!dirp)
12220 return;
12221
12222 iterator->dirp = NULL;
12223 Py_BEGIN_ALLOW_THREADS
12224#ifdef HAVE_FDOPENDIR
12225 if (iterator->path.fd != -1)
12226 rewinddir(dirp);
12227#endif
12228 closedir(dirp);
12229 Py_END_ALLOW_THREADS
12230 return;
12231}
12232
12233static PyObject *
12234ScandirIterator_iternext(ScandirIterator *iterator)
12235{
12236 struct dirent *direntp;
12237 Py_ssize_t name_len;
12238 int is_dot;
12239 PyObject *entry;
12240
12241 /* Happens if the iterator is iterated twice, or closed explicitly */
12242 if (!iterator->dirp)
12243 return NULL;
12244
12245 while (1) {
12246 errno = 0;
12247 Py_BEGIN_ALLOW_THREADS
12248 direntp = readdir(iterator->dirp);
12249 Py_END_ALLOW_THREADS
12250
12251 if (!direntp) {
12252 /* Error or no more files */
12253 if (errno != 0)
12254 path_error(&iterator->path);
12255 break;
12256 }
12257
12258 /* Skip over . and .. */
12259 name_len = NAMLEN(direntp);
12260 is_dot = direntp->d_name[0] == '.' &&
12261 (name_len == 1 || (direntp->d_name[1] == '.' && name_len == 2));
12262 if (!is_dot) {
12263 entry = DirEntry_from_posix_info(&iterator->path, direntp->d_name,
12264 name_len, direntp->d_ino
12265#ifdef HAVE_DIRENT_D_TYPE
12266 , direntp->d_type
12267#endif
12268 );
12269 if (!entry)
12270 break;
12271 return entry;
12272 }
12273
12274 /* Loop till we get a non-dot directory or finish iterating */
12275 }
12276
12277 /* Error or no more files */
12278 ScandirIterator_closedir(iterator);
12279 return NULL;
12280}
12281
12282#endif
12283
12284static PyObject *
12285ScandirIterator_close(ScandirIterator *self, PyObject *args)
12286{
12287 ScandirIterator_closedir(self);
12288 Py_RETURN_NONE;
12289}
12290
12291static PyObject *
12292ScandirIterator_enter(PyObject *self, PyObject *args)
12293{
12294 Py_INCREF(self);
12295 return self;
12296}
12297
12298static PyObject *
12299ScandirIterator_exit(ScandirIterator *self, PyObject *args)
12300{
12301 ScandirIterator_closedir(self);
12302 Py_RETURN_NONE;
12303}
12304
12305static void
12306ScandirIterator_finalize(ScandirIterator *iterator)
12307{
12308 PyObject *error_type, *error_value, *error_traceback;
12309
12310 /* Save the current exception, if any. */
12311 PyErr_Fetch(&error_type, &error_value, &error_traceback);
12312
12313 if (!ScandirIterator_is_closed(iterator)) {
12314 ScandirIterator_closedir(iterator);
12315
12316 if (PyErr_ResourceWarning((PyObject *)iterator, 1,
12317 "unclosed scandir iterator %R", iterator)) {
12318 /* Spurious errors can appear at shutdown */
12319 if (PyErr_ExceptionMatches(PyExc_Warning)) {
12320 PyErr_WriteUnraisable((PyObject *) iterator);
12321 }
12322 }
12323 }
12324
12325 path_cleanup(&iterator->path);
12326
12327 /* Restore the saved exception. */
12328 PyErr_Restore(error_type, error_value, error_traceback);
12329}
12330
12331static void
12332ScandirIterator_dealloc(ScandirIterator *iterator)
12333{
12334 if (PyObject_CallFinalizerFromDealloc((PyObject *)iterator) < 0)
12335 return;
12336
12337 Py_TYPE(iterator)->tp_free((PyObject *)iterator);
12338}
12339
12340static PyMethodDef ScandirIterator_methods[] = {
12341 {"__enter__", (PyCFunction)ScandirIterator_enter, METH_NOARGS},
12342 {"__exit__", (PyCFunction)ScandirIterator_exit, METH_VARARGS},
12343 {"close", (PyCFunction)ScandirIterator_close, METH_NOARGS},
12344 {NULL}
12345};
12346
12347static PyTypeObject ScandirIteratorType = {
12348 PyVarObject_HEAD_INIT(NULL, 0)
12349 MODNAME ".ScandirIterator", /* tp_name */
12350 sizeof(ScandirIterator), /* tp_basicsize */
12351 0, /* tp_itemsize */
12352 /* methods */
12353 (destructor)ScandirIterator_dealloc, /* tp_dealloc */
12354 0, /* tp_print */
12355 0, /* tp_getattr */
12356 0, /* tp_setattr */
12357 0, /* tp_compare */
12358 0, /* tp_repr */
12359 0, /* tp_as_number */
12360 0, /* tp_as_sequence */
12361 0, /* tp_as_mapping */
12362 0, /* tp_hash */
12363 0, /* tp_call */
12364 0, /* tp_str */
12365 0, /* tp_getattro */
12366 0, /* tp_setattro */
12367 0, /* tp_as_buffer */
12368 Py_TPFLAGS_DEFAULT
12369 | Py_TPFLAGS_HAVE_FINALIZE, /* tp_flags */
12370 0, /* tp_doc */
12371 0, /* tp_traverse */
12372 0, /* tp_clear */
12373 0, /* tp_richcompare */
12374 0, /* tp_weaklistoffset */
12375 PyObject_SelfIter, /* tp_iter */
12376 (iternextfunc)ScandirIterator_iternext, /* tp_iternext */
12377 ScandirIterator_methods, /* tp_methods */
12378 0, /* tp_members */
12379 0, /* tp_getset */
12380 0, /* tp_base */
12381 0, /* tp_dict */
12382 0, /* tp_descr_get */
12383 0, /* tp_descr_set */
12384 0, /* tp_dictoffset */
12385 0, /* tp_init */
12386 0, /* tp_alloc */
12387 0, /* tp_new */
12388 0, /* tp_free */
12389 0, /* tp_is_gc */
12390 0, /* tp_bases */
12391 0, /* tp_mro */
12392 0, /* tp_cache */
12393 0, /* tp_subclasses */
12394 0, /* tp_weaklist */
12395 0, /* tp_del */
12396 0, /* tp_version_tag */
12397 (destructor)ScandirIterator_finalize, /* tp_finalize */
12398};
12399
12400/*[clinic input]
12401os.scandir
12402
12403 path : path_t(nullable=True, allow_fd='PATH_HAVE_FDOPENDIR') = None
12404
12405Return an iterator of DirEntry objects for given path.
12406
12407path can be specified as either str, bytes, or a path-like object. If path
12408is bytes, the names of yielded DirEntry objects will also be bytes; in
12409all other circumstances they will be str.
12410
12411If path is None, uses the path='.'.
12412[clinic start generated code]*/
12413
12414static PyObject *
12415os_scandir_impl(PyObject *module, path_t *path)
12416/*[clinic end generated code: output=6eb2668b675ca89e input=6bdd312708fc3bb0]*/
12417{
12418 ScandirIterator *iterator;
12419#ifdef MS_WINDOWS
12420 wchar_t *path_strW;
12421#else
12422 const char *path_str;
12423#ifdef HAVE_FDOPENDIR
12424 int fd = -1;
12425#endif
12426#endif
12427
12428 iterator = PyObject_New(ScandirIterator, &ScandirIteratorType);
12429 if (!iterator)
12430 return NULL;
12431
12432#ifdef MS_WINDOWS
12433 iterator->handle = INVALID_HANDLE_VALUE;
12434#else
12435 iterator->dirp = NULL;
12436#endif
12437
12438 memcpy(&iterator->path, path, sizeof(path_t));
12439 /* Move the ownership to iterator->path */
12440 path->object = NULL;
12441 path->cleanup = NULL;
12442
12443#ifdef MS_WINDOWS
12444 iterator->first_time = 1;
12445
12446 path_strW = join_path_filenameW(iterator->path.wide, L"*.*");
12447 if (!path_strW)
12448 goto error;
12449
12450 Py_BEGIN_ALLOW_THREADS
12451 iterator->handle = FindFirstFileW(path_strW, &iterator->file_data);
12452 Py_END_ALLOW_THREADS
12453
12454 PyMem_Free(path_strW);
12455
12456 if (iterator->handle == INVALID_HANDLE_VALUE) {
12457 path_error(&iterator->path);
12458 goto error;
12459 }
12460#else /* POSIX */
12461 errno = 0;
12462#ifdef HAVE_FDOPENDIR
12463 if (path->fd != -1) {
12464 /* closedir() closes the FD, so we duplicate it */
12465 fd = _Py_dup(path->fd);
12466 if (fd == -1)
12467 goto error;
12468
12469 Py_BEGIN_ALLOW_THREADS
12470 iterator->dirp = fdopendir(fd);
12471 Py_END_ALLOW_THREADS
12472 }
12473 else
12474#endif
12475 {
12476 if (iterator->path.narrow)
12477 path_str = iterator->path.narrow;
12478 else
12479 path_str = ".";
12480
12481 Py_BEGIN_ALLOW_THREADS
12482 iterator->dirp = opendir(path_str);
12483 Py_END_ALLOW_THREADS
12484 }
12485
12486 if (!iterator->dirp) {
12487 path_error(&iterator->path);
12488#ifdef HAVE_FDOPENDIR
12489 if (fd != -1) {
12490 Py_BEGIN_ALLOW_THREADS
12491 close(fd);
12492 Py_END_ALLOW_THREADS
12493 }
12494#endif
12495 goto error;
12496 }
12497#endif
12498
12499 return (PyObject *)iterator;
12500
12501error:
12502 Py_DECREF(iterator);
12503 return NULL;
12504}
12505
12506/*
12507 Return the file system path representation of the object.
12508
12509 If the object is str or bytes, then allow it to pass through with
12510 an incremented refcount. If the object defines __fspath__(), then
12511 return the result of that method. All other types raise a TypeError.
12512*/
12513PyObject *
12514PyOS_FSPath(PyObject *path)
12515{
12516 /* For error message reasons, this function is manually inlined in
12517 path_converter(). */
12518 _Py_IDENTIFIER(__fspath__);
12519 PyObject *func = NULL;
12520 PyObject *path_repr = NULL;
12521
12522 if (PyUnicode_Check(path) || PyBytes_Check(path)) {
12523 Py_INCREF(path);
12524 return path;
12525 }
12526
12527 func = _PyObject_LookupSpecial(path, &PyId___fspath__);
12528 if (NULL == func) {
12529 return PyErr_Format(PyExc_TypeError,
12530 "expected str, bytes or os.PathLike object, "
12531 "not %.200s",
12532 Py_TYPE(path)->tp_name);
12533 }
12534
12535 path_repr = _PyObject_CallNoArg(func);
12536 Py_DECREF(func);
12537 if (NULL == path_repr) {
12538 return NULL;
12539 }
12540
12541 if (!(PyUnicode_Check(path_repr) || PyBytes_Check(path_repr))) {
12542 PyErr_Format(PyExc_TypeError,
12543 "expected %.200s.__fspath__() to return str or bytes, "
12544 "not %.200s", Py_TYPE(path)->tp_name,
12545 Py_TYPE(path_repr)->tp_name);
12546 Py_DECREF(path_repr);
12547 return NULL;
12548 }
12549
12550 return path_repr;
12551}
12552
12553/*[clinic input]
12554os.fspath
12555
12556 path: object
12557
12558Return the file system path representation of the object.
12559
12560If the object is str or bytes, then allow it to pass through as-is. If the
12561object defines __fspath__(), then return the result of that method. All other
12562types raise a TypeError.
12563[clinic start generated code]*/
12564
12565static PyObject *
12566os_fspath_impl(PyObject *module, PyObject *path)
12567/*[clinic end generated code: output=c3c3b78ecff2914f input=e357165f7b22490f]*/
12568{
12569 return PyOS_FSPath(path);
12570}
12571
12572#ifdef HAVE_GETRANDOM_SYSCALL
12573/*[clinic input]
12574os.getrandom
12575
12576 size: Py_ssize_t
12577 flags: int=0
12578
12579Obtain a series of random bytes.
12580[clinic start generated code]*/
12581
12582static PyObject *
12583os_getrandom_impl(PyObject *module, Py_ssize_t size, int flags)
12584/*[clinic end generated code: output=b3a618196a61409c input=59bafac39c594947]*/
12585{
12586 PyObject *bytes;
12587 Py_ssize_t n;
12588
12589 if (size < 0) {
12590 errno = EINVAL;
12591 return posix_error();
12592 }
12593
12594 bytes = PyBytes_FromStringAndSize(NULL, size);
12595 if (bytes == NULL) {
12596 PyErr_NoMemory();
12597 return NULL;
12598 }
12599
12600 while (1) {
12601 n = syscall(SYS_getrandom,
12602 PyBytes_AS_STRING(bytes),
12603 PyBytes_GET_SIZE(bytes),
12604 flags);
12605 if (n < 0 && errno == EINTR) {
12606 if (PyErr_CheckSignals() < 0) {
12607 goto error;
12608 }
12609
12610 /* getrandom() was interrupted by a signal: retry */
12611 continue;
12612 }
12613 break;
12614 }
12615
12616 if (n < 0) {
12617 PyErr_SetFromErrno(PyExc_OSError);
12618 goto error;
12619 }
12620
12621 if (n != size) {
12622 _PyBytes_Resize(&bytes, n);
12623 }
12624
12625 return bytes;
12626
12627error:
12628 Py_DECREF(bytes);
12629 return NULL;
12630}
12631#endif /* HAVE_GETRANDOM_SYSCALL */
12632
12633
12634static PyMethodDef posix_methods[] = {
12635
12636 OS_STAT_METHODDEF
12637 OS_ACCESS_METHODDEF
12638 OS_TTYNAME_METHODDEF
12639 OS_CHDIR_METHODDEF
12640 OS_CHFLAGS_METHODDEF
12641 OS_CHMOD_METHODDEF
12642 OS_FCHMOD_METHODDEF
12643 OS_LCHMOD_METHODDEF
12644 OS_CHOWN_METHODDEF
12645 OS_FCHOWN_METHODDEF
12646 OS_LCHOWN_METHODDEF
12647 OS_LCHFLAGS_METHODDEF
12648 OS_CHROOT_METHODDEF
12649 OS_CTERMID_METHODDEF
12650 OS_GETCWD_METHODDEF
12651 OS_GETCWDB_METHODDEF
12652 OS_LINK_METHODDEF
12653 OS_LISTDIR_METHODDEF
12654 OS_LSTAT_METHODDEF
12655 OS_MKDIR_METHODDEF
12656 OS_NICE_METHODDEF
12657 OS_GETPRIORITY_METHODDEF
12658 OS_SETPRIORITY_METHODDEF
12659#ifdef HAVE_READLINK
12660 {"readlink", (PyCFunction)posix_readlink,
12661 METH_VARARGS | METH_KEYWORDS,
12662 readlink__doc__},
12663#endif /* HAVE_READLINK */
12664#if !defined(HAVE_READLINK) && defined(MS_WINDOWS)
12665 {"readlink", (PyCFunction)win_readlink,
12666 METH_VARARGS | METH_KEYWORDS,
12667 readlink__doc__},
12668#endif /* !defined(HAVE_READLINK) && defined(MS_WINDOWS) */
12669 OS_RENAME_METHODDEF
12670 OS_REPLACE_METHODDEF
12671 OS_RMDIR_METHODDEF
12672 OS_SYMLINK_METHODDEF
12673 OS_SYSTEM_METHODDEF
12674 OS_UMASK_METHODDEF
12675 OS_UNAME_METHODDEF
12676 OS_UNLINK_METHODDEF
12677 OS_REMOVE_METHODDEF
12678 OS_UTIME_METHODDEF
12679 OS_TIMES_METHODDEF
12680 OS__EXIT_METHODDEF
12681 OS_EXECV_METHODDEF
12682 OS_EXECVE_METHODDEF
12683 OS_SPAWNV_METHODDEF
12684 OS_SPAWNVE_METHODDEF
12685 OS_FORK1_METHODDEF
12686 OS_FORK_METHODDEF
12687 OS_REGISTER_AT_FORK_METHODDEF
12688 OS_SCHED_GET_PRIORITY_MAX_METHODDEF
12689 OS_SCHED_GET_PRIORITY_MIN_METHODDEF
12690 OS_SCHED_GETPARAM_METHODDEF
12691 OS_SCHED_GETSCHEDULER_METHODDEF
12692 OS_SCHED_RR_GET_INTERVAL_METHODDEF
12693 OS_SCHED_SETPARAM_METHODDEF
12694 OS_SCHED_SETSCHEDULER_METHODDEF
12695 OS_SCHED_YIELD_METHODDEF
12696 OS_SCHED_SETAFFINITY_METHODDEF
12697 OS_SCHED_GETAFFINITY_METHODDEF
12698 OS_OPENPTY_METHODDEF
12699 OS_FORKPTY_METHODDEF
12700 OS_GETEGID_METHODDEF
12701 OS_GETEUID_METHODDEF
12702 OS_GETGID_METHODDEF
12703#ifdef HAVE_GETGROUPLIST
12704 {"getgrouplist", posix_getgrouplist, METH_VARARGS, posix_getgrouplist__doc__},
12705#endif
12706 OS_GETGROUPS_METHODDEF
12707 OS_GETPID_METHODDEF
12708 OS_GETPGRP_METHODDEF
12709 OS_GETPPID_METHODDEF
12710 OS_GETUID_METHODDEF
12711 OS_GETLOGIN_METHODDEF
12712 OS_KILL_METHODDEF
12713 OS_KILLPG_METHODDEF
12714 OS_PLOCK_METHODDEF
12715#ifdef MS_WINDOWS
12716 OS_STARTFILE_METHODDEF
12717#endif
12718 OS_SETUID_METHODDEF
12719 OS_SETEUID_METHODDEF
12720 OS_SETREUID_METHODDEF
12721 OS_SETGID_METHODDEF
12722 OS_SETEGID_METHODDEF
12723 OS_SETREGID_METHODDEF
12724 OS_SETGROUPS_METHODDEF
12725#ifdef HAVE_INITGROUPS
12726 {"initgroups", posix_initgroups, METH_VARARGS, posix_initgroups__doc__},
12727#endif /* HAVE_INITGROUPS */
12728 OS_GETPGID_METHODDEF
12729 OS_SETPGRP_METHODDEF
12730 OS_WAIT_METHODDEF
12731 OS_WAIT3_METHODDEF
12732 OS_WAIT4_METHODDEF
12733 OS_WAITID_METHODDEF
12734 OS_WAITPID_METHODDEF
12735 OS_GETSID_METHODDEF
12736 OS_SETSID_METHODDEF
12737 OS_SETPGID_METHODDEF
12738 OS_TCGETPGRP_METHODDEF
12739 OS_TCSETPGRP_METHODDEF
12740 OS_OPEN_METHODDEF
12741 OS_CLOSE_METHODDEF
12742 OS_CLOSERANGE_METHODDEF
12743 OS_DEVICE_ENCODING_METHODDEF
12744 OS_DUP_METHODDEF
12745 OS_DUP2_METHODDEF
12746 OS_LOCKF_METHODDEF
12747 OS_LSEEK_METHODDEF
12748 OS_READ_METHODDEF
12749 OS_READV_METHODDEF
12750 OS_PREAD_METHODDEF
12751 OS_PREADV_METHODDEF
12752 OS_WRITE_METHODDEF
12753 OS_WRITEV_METHODDEF
12754 OS_PWRITE_METHODDEF
12755 OS_PWRITEV_METHODDEF
12756#ifdef HAVE_SENDFILE
12757 {"sendfile", (PyCFunction)posix_sendfile, METH_VARARGS | METH_KEYWORDS,
12758 posix_sendfile__doc__},
12759#endif
12760 OS_FSTAT_METHODDEF
12761 OS_ISATTY_METHODDEF
12762 OS_PIPE_METHODDEF
12763 OS_PIPE2_METHODDEF
12764 OS_MKFIFO_METHODDEF
12765 OS_MKNOD_METHODDEF
12766 OS_MAJOR_METHODDEF
12767 OS_MINOR_METHODDEF
12768 OS_MAKEDEV_METHODDEF
12769 OS_FTRUNCATE_METHODDEF
12770 OS_TRUNCATE_METHODDEF
12771 OS_POSIX_FALLOCATE_METHODDEF
12772 OS_POSIX_FADVISE_METHODDEF
12773 OS_PUTENV_METHODDEF
12774 OS_UNSETENV_METHODDEF
12775 OS_STRERROR_METHODDEF
12776 OS_FCHDIR_METHODDEF
12777 OS_FSYNC_METHODDEF
12778 OS_SYNC_METHODDEF
12779 OS_FDATASYNC_METHODDEF
12780 OS_WCOREDUMP_METHODDEF
12781 OS_WIFCONTINUED_METHODDEF
12782 OS_WIFSTOPPED_METHODDEF
12783 OS_WIFSIGNALED_METHODDEF
12784 OS_WIFEXITED_METHODDEF
12785 OS_WEXITSTATUS_METHODDEF
12786 OS_WTERMSIG_METHODDEF
12787 OS_WSTOPSIG_METHODDEF
12788 OS_FSTATVFS_METHODDEF
12789 OS_STATVFS_METHODDEF
12790 OS_CONFSTR_METHODDEF
12791 OS_SYSCONF_METHODDEF
12792 OS_FPATHCONF_METHODDEF
12793 OS_PATHCONF_METHODDEF
12794 OS_ABORT_METHODDEF
12795 OS__GETFULLPATHNAME_METHODDEF
12796 OS__ISDIR_METHODDEF
12797 OS__GETDISKUSAGE_METHODDEF
12798 OS__GETFINALPATHNAME_METHODDEF
12799 OS__GETVOLUMEPATHNAME_METHODDEF
12800 OS_GETLOADAVG_METHODDEF
12801 OS_URANDOM_METHODDEF
12802 OS_SETRESUID_METHODDEF
12803 OS_SETRESGID_METHODDEF
12804 OS_GETRESUID_METHODDEF
12805 OS_GETRESGID_METHODDEF
12806
12807 OS_GETXATTR_METHODDEF
12808 OS_SETXATTR_METHODDEF
12809 OS_REMOVEXATTR_METHODDEF
12810 OS_LISTXATTR_METHODDEF
12811
12812#if defined(TERMSIZE_USE_CONIO) || defined(TERMSIZE_USE_IOCTL)
12813 {"get_terminal_size", get_terminal_size, METH_VARARGS, termsize__doc__},
12814#endif
12815 OS_CPU_COUNT_METHODDEF
12816 OS_GET_INHERITABLE_METHODDEF
12817 OS_SET_INHERITABLE_METHODDEF
12818 OS_GET_HANDLE_INHERITABLE_METHODDEF
12819 OS_SET_HANDLE_INHERITABLE_METHODDEF
12820#ifndef MS_WINDOWS
12821 {"get_blocking", posix_get_blocking, METH_VARARGS, get_blocking__doc__},
12822 {"set_blocking", posix_set_blocking, METH_VARARGS, set_blocking__doc__},
12823#endif
12824 OS_SCANDIR_METHODDEF
12825 OS_FSPATH_METHODDEF
12826 OS_GETRANDOM_METHODDEF
12827 {NULL, NULL} /* Sentinel */
12828};
12829
12830
12831#if defined(HAVE_SYMLINK) && defined(MS_WINDOWS)
12832static int
12833enable_symlink()
12834{
12835 HANDLE tok;
12836 TOKEN_PRIVILEGES tok_priv;
12837 LUID luid;
12838
12839 if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &tok))
12840 return 0;
12841
12842 if (!LookupPrivilegeValue(NULL, SE_CREATE_SYMBOLIC_LINK_NAME, &luid))
12843 return 0;
12844
12845 tok_priv.PrivilegeCount = 1;
12846 tok_priv.Privileges[0].Luid = luid;
12847 tok_priv.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
12848
12849 if (!AdjustTokenPrivileges(tok, FALSE, &tok_priv,
12850 sizeof(TOKEN_PRIVILEGES),
12851 (PTOKEN_PRIVILEGES) NULL, (PDWORD) NULL))
12852 return 0;
12853
12854 /* ERROR_NOT_ALL_ASSIGNED returned when the privilege can't be assigned. */
12855 return GetLastError() == ERROR_NOT_ALL_ASSIGNED ? 0 : 1;
12856}
12857#endif /* defined(HAVE_SYMLINK) && defined(MS_WINDOWS) */
12858
12859static int
12860all_ins(PyObject *m)
12861{
12862#ifdef F_OK
12863 if (PyModule_AddIntMacro(m, F_OK)) return -1;
12864#endif
12865#ifdef R_OK
12866 if (PyModule_AddIntMacro(m, R_OK)) return -1;
12867#endif
12868#ifdef W_OK
12869 if (PyModule_AddIntMacro(m, W_OK)) return -1;
12870#endif
12871#ifdef X_OK
12872 if (PyModule_AddIntMacro(m, X_OK)) return -1;
12873#endif
12874#ifdef NGROUPS_MAX
12875 if (PyModule_AddIntMacro(m, NGROUPS_MAX)) return -1;
12876#endif
12877#ifdef TMP_MAX
12878 if (PyModule_AddIntMacro(m, TMP_MAX)) return -1;
12879#endif
12880#ifdef WCONTINUED
12881 if (PyModule_AddIntMacro(m, WCONTINUED)) return -1;
12882#endif
12883#ifdef WNOHANG
12884 if (PyModule_AddIntMacro(m, WNOHANG)) return -1;
12885#endif
12886#ifdef WUNTRACED
12887 if (PyModule_AddIntMacro(m, WUNTRACED)) return -1;
12888#endif
12889#ifdef O_RDONLY
12890 if (PyModule_AddIntMacro(m, O_RDONLY)) return -1;
12891#endif
12892#ifdef O_WRONLY
12893 if (PyModule_AddIntMacro(m, O_WRONLY)) return -1;
12894#endif
12895#ifdef O_RDWR
12896 if (PyModule_AddIntMacro(m, O_RDWR)) return -1;
12897#endif
12898#ifdef O_NDELAY
12899 if (PyModule_AddIntMacro(m, O_NDELAY)) return -1;
12900#endif
12901#ifdef O_NONBLOCK
12902 if (PyModule_AddIntMacro(m, O_NONBLOCK)) return -1;
12903#endif
12904#ifdef O_APPEND
12905 if (PyModule_AddIntMacro(m, O_APPEND)) return -1;
12906#endif
12907#ifdef O_DSYNC
12908 if (PyModule_AddIntMacro(m, O_DSYNC)) return -1;
12909#endif
12910#ifdef O_RSYNC
12911 if (PyModule_AddIntMacro(m, O_RSYNC)) return -1;
12912#endif
12913#ifdef O_SYNC
12914 if (PyModule_AddIntMacro(m, O_SYNC)) return -1;
12915#endif
12916#ifdef O_NOCTTY
12917 if (PyModule_AddIntMacro(m, O_NOCTTY)) return -1;
12918#endif
12919#ifdef O_CREAT
12920 if (PyModule_AddIntMacro(m, O_CREAT)) return -1;
12921#endif
12922#ifdef O_EXCL
12923 if (PyModule_AddIntMacro(m, O_EXCL)) return -1;
12924#endif
12925#ifdef O_TRUNC
12926 if (PyModule_AddIntMacro(m, O_TRUNC)) return -1;
12927#endif
12928#ifdef O_BINARY
12929 if (PyModule_AddIntMacro(m, O_BINARY)) return -1;
12930#endif
12931#ifdef O_TEXT
12932 if (PyModule_AddIntMacro(m, O_TEXT)) return -1;
12933#endif
12934#ifdef O_XATTR
12935 if (PyModule_AddIntMacro(m, O_XATTR)) return -1;
12936#endif
12937#ifdef O_LARGEFILE
12938 if (PyModule_AddIntMacro(m, O_LARGEFILE)) return -1;
12939#endif
12940#ifndef __GNU__
12941#ifdef O_SHLOCK
12942 if (PyModule_AddIntMacro(m, O_SHLOCK)) return -1;
12943#endif
12944#ifdef O_EXLOCK
12945 if (PyModule_AddIntMacro(m, O_EXLOCK)) return -1;
12946#endif
12947#endif
12948#ifdef O_EXEC
12949 if (PyModule_AddIntMacro(m, O_EXEC)) return -1;
12950#endif
12951#ifdef O_SEARCH
12952 if (PyModule_AddIntMacro(m, O_SEARCH)) return -1;
12953#endif
12954#ifdef O_PATH
12955 if (PyModule_AddIntMacro(m, O_PATH)) return -1;
12956#endif
12957#ifdef O_TTY_INIT
12958 if (PyModule_AddIntMacro(m, O_TTY_INIT)) return -1;
12959#endif
12960#ifdef O_TMPFILE
12961 if (PyModule_AddIntMacro(m, O_TMPFILE)) return -1;
12962#endif
12963#ifdef PRIO_PROCESS
12964 if (PyModule_AddIntMacro(m, PRIO_PROCESS)) return -1;
12965#endif
12966#ifdef PRIO_PGRP
12967 if (PyModule_AddIntMacro(m, PRIO_PGRP)) return -1;
12968#endif
12969#ifdef PRIO_USER
12970 if (PyModule_AddIntMacro(m, PRIO_USER)) return -1;
12971#endif
12972#ifdef O_CLOEXEC
12973 if (PyModule_AddIntMacro(m, O_CLOEXEC)) return -1;
12974#endif
12975#ifdef O_ACCMODE
12976 if (PyModule_AddIntMacro(m, O_ACCMODE)) return -1;
12977#endif
12978
12979
12980#ifdef SEEK_HOLE
12981 if (PyModule_AddIntMacro(m, SEEK_HOLE)) return -1;
12982#endif
12983#ifdef SEEK_DATA
12984 if (PyModule_AddIntMacro(m, SEEK_DATA)) return -1;
12985#endif
12986
12987/* MS Windows */
12988#ifdef O_NOINHERIT
12989 /* Don't inherit in child processes. */
12990 if (PyModule_AddIntMacro(m, O_NOINHERIT)) return -1;
12991#endif
12992#ifdef _O_SHORT_LIVED
12993 /* Optimize for short life (keep in memory). */
12994 /* MS forgot to define this one with a non-underscore form too. */
12995 if (PyModule_AddIntConstant(m, "O_SHORT_LIVED", _O_SHORT_LIVED)) return -1;
12996#endif
12997#ifdef O_TEMPORARY
12998 /* Automatically delete when last handle is closed. */
12999 if (PyModule_AddIntMacro(m, O_TEMPORARY)) return -1;
13000#endif
13001#ifdef O_RANDOM
13002 /* Optimize for random access. */
13003 if (PyModule_AddIntMacro(m, O_RANDOM)) return -1;
13004#endif
13005#ifdef O_SEQUENTIAL
13006 /* Optimize for sequential access. */
13007 if (PyModule_AddIntMacro(m, O_SEQUENTIAL)) return -1;
13008#endif
13009
13010/* GNU extensions. */
13011#ifdef O_ASYNC
13012 /* Send a SIGIO signal whenever input or output
13013 becomes available on file descriptor */
13014 if (PyModule_AddIntMacro(m, O_ASYNC)) return -1;
13015#endif
13016#ifdef O_DIRECT
13017 /* Direct disk access. */
13018 if (PyModule_AddIntMacro(m, O_DIRECT)) return -1;
13019#endif
13020#ifdef O_DIRECTORY
13021 /* Must be a directory. */
13022 if (PyModule_AddIntMacro(m, O_DIRECTORY)) return -1;
13023#endif
13024#ifdef O_NOFOLLOW
13025 /* Do not follow links. */
13026 if (PyModule_AddIntMacro(m, O_NOFOLLOW)) return -1;
13027#endif
13028#ifdef O_NOLINKS
13029 /* Fails if link count of the named file is greater than 1 */
13030 if (PyModule_AddIntMacro(m, O_NOLINKS)) return -1;
13031#endif
13032#ifdef O_NOATIME
13033 /* Do not update the access time. */
13034 if (PyModule_AddIntMacro(m, O_NOATIME)) return -1;
13035#endif
13036
13037 /* These come from sysexits.h */
13038#ifdef EX_OK
13039 if (PyModule_AddIntMacro(m, EX_OK)) return -1;
13040#endif /* EX_OK */
13041#ifdef EX_USAGE
13042 if (PyModule_AddIntMacro(m, EX_USAGE)) return -1;
13043#endif /* EX_USAGE */
13044#ifdef EX_DATAERR
13045 if (PyModule_AddIntMacro(m, EX_DATAERR)) return -1;
13046#endif /* EX_DATAERR */
13047#ifdef EX_NOINPUT
13048 if (PyModule_AddIntMacro(m, EX_NOINPUT)) return -1;
13049#endif /* EX_NOINPUT */
13050#ifdef EX_NOUSER
13051 if (PyModule_AddIntMacro(m, EX_NOUSER)) return -1;
13052#endif /* EX_NOUSER */
13053#ifdef EX_NOHOST
13054 if (PyModule_AddIntMacro(m, EX_NOHOST)) return -1;
13055#endif /* EX_NOHOST */
13056#ifdef EX_UNAVAILABLE
13057 if (PyModule_AddIntMacro(m, EX_UNAVAILABLE)) return -1;
13058#endif /* EX_UNAVAILABLE */
13059#ifdef EX_SOFTWARE
13060 if (PyModule_AddIntMacro(m, EX_SOFTWARE)) return -1;
13061#endif /* EX_SOFTWARE */
13062#ifdef EX_OSERR
13063 if (PyModule_AddIntMacro(m, EX_OSERR)) return -1;
13064#endif /* EX_OSERR */
13065#ifdef EX_OSFILE
13066 if (PyModule_AddIntMacro(m, EX_OSFILE)) return -1;
13067#endif /* EX_OSFILE */
13068#ifdef EX_CANTCREAT
13069 if (PyModule_AddIntMacro(m, EX_CANTCREAT)) return -1;
13070#endif /* EX_CANTCREAT */
13071#ifdef EX_IOERR
13072 if (PyModule_AddIntMacro(m, EX_IOERR)) return -1;
13073#endif /* EX_IOERR */
13074#ifdef EX_TEMPFAIL
13075 if (PyModule_AddIntMacro(m, EX_TEMPFAIL)) return -1;
13076#endif /* EX_TEMPFAIL */
13077#ifdef EX_PROTOCOL
13078 if (PyModule_AddIntMacro(m, EX_PROTOCOL)) return -1;
13079#endif /* EX_PROTOCOL */
13080#ifdef EX_NOPERM
13081 if (PyModule_AddIntMacro(m, EX_NOPERM)) return -1;
13082#endif /* EX_NOPERM */
13083#ifdef EX_CONFIG
13084 if (PyModule_AddIntMacro(m, EX_CONFIG)) return -1;
13085#endif /* EX_CONFIG */
13086#ifdef EX_NOTFOUND
13087 if (PyModule_AddIntMacro(m, EX_NOTFOUND)) return -1;
13088#endif /* EX_NOTFOUND */
13089
13090 /* statvfs */
13091#ifdef ST_RDONLY
13092 if (PyModule_AddIntMacro(m, ST_RDONLY)) return -1;
13093#endif /* ST_RDONLY */
13094#ifdef ST_NOSUID
13095 if (PyModule_AddIntMacro(m, ST_NOSUID)) return -1;
13096#endif /* ST_NOSUID */
13097
13098 /* GNU extensions */
13099#ifdef ST_NODEV
13100 if (PyModule_AddIntMacro(m, ST_NODEV)) return -1;
13101#endif /* ST_NODEV */
13102#ifdef ST_NOEXEC
13103 if (PyModule_AddIntMacro(m, ST_NOEXEC)) return -1;
13104#endif /* ST_NOEXEC */
13105#ifdef ST_SYNCHRONOUS
13106 if (PyModule_AddIntMacro(m, ST_SYNCHRONOUS)) return -1;
13107#endif /* ST_SYNCHRONOUS */
13108#ifdef ST_MANDLOCK
13109 if (PyModule_AddIntMacro(m, ST_MANDLOCK)) return -1;
13110#endif /* ST_MANDLOCK */
13111#ifdef ST_WRITE
13112 if (PyModule_AddIntMacro(m, ST_WRITE)) return -1;
13113#endif /* ST_WRITE */
13114#ifdef ST_APPEND
13115 if (PyModule_AddIntMacro(m, ST_APPEND)) return -1;
13116#endif /* ST_APPEND */
13117#ifdef ST_NOATIME
13118 if (PyModule_AddIntMacro(m, ST_NOATIME)) return -1;
13119#endif /* ST_NOATIME */
13120#ifdef ST_NODIRATIME
13121 if (PyModule_AddIntMacro(m, ST_NODIRATIME)) return -1;
13122#endif /* ST_NODIRATIME */
13123#ifdef ST_RELATIME
13124 if (PyModule_AddIntMacro(m, ST_RELATIME)) return -1;
13125#endif /* ST_RELATIME */
13126
13127 /* FreeBSD sendfile() constants */
13128#ifdef SF_NODISKIO
13129 if (PyModule_AddIntMacro(m, SF_NODISKIO)) return -1;
13130#endif
13131#ifdef SF_MNOWAIT
13132 if (PyModule_AddIntMacro(m, SF_MNOWAIT)) return -1;
13133#endif
13134#ifdef SF_SYNC
13135 if (PyModule_AddIntMacro(m, SF_SYNC)) return -1;
13136#endif
13137
13138 /* constants for posix_fadvise */
13139#ifdef POSIX_FADV_NORMAL
13140 if (PyModule_AddIntMacro(m, POSIX_FADV_NORMAL)) return -1;
13141#endif
13142#ifdef POSIX_FADV_SEQUENTIAL
13143 if (PyModule_AddIntMacro(m, POSIX_FADV_SEQUENTIAL)) return -1;
13144#endif
13145#ifdef POSIX_FADV_RANDOM
13146 if (PyModule_AddIntMacro(m, POSIX_FADV_RANDOM)) return -1;
13147#endif
13148#ifdef POSIX_FADV_NOREUSE
13149 if (PyModule_AddIntMacro(m, POSIX_FADV_NOREUSE)) return -1;
13150#endif
13151#ifdef POSIX_FADV_WILLNEED
13152 if (PyModule_AddIntMacro(m, POSIX_FADV_WILLNEED)) return -1;
13153#endif
13154#ifdef POSIX_FADV_DONTNEED
13155 if (PyModule_AddIntMacro(m, POSIX_FADV_DONTNEED)) return -1;
13156#endif
13157
13158 /* constants for waitid */
13159#if defined(HAVE_SYS_WAIT_H) && defined(HAVE_WAITID)
13160 if (PyModule_AddIntMacro(m, P_PID)) return -1;
13161 if (PyModule_AddIntMacro(m, P_PGID)) return -1;
13162 if (PyModule_AddIntMacro(m, P_ALL)) return -1;
13163#endif
13164#ifdef WEXITED
13165 if (PyModule_AddIntMacro(m, WEXITED)) return -1;
13166#endif
13167#ifdef WNOWAIT
13168 if (PyModule_AddIntMacro(m, WNOWAIT)) return -1;
13169#endif
13170#ifdef WSTOPPED
13171 if (PyModule_AddIntMacro(m, WSTOPPED)) return -1;
13172#endif
13173#ifdef CLD_EXITED
13174 if (PyModule_AddIntMacro(m, CLD_EXITED)) return -1;
13175#endif
13176#ifdef CLD_DUMPED
13177 if (PyModule_AddIntMacro(m, CLD_DUMPED)) return -1;
13178#endif
13179#ifdef CLD_TRAPPED
13180 if (PyModule_AddIntMacro(m, CLD_TRAPPED)) return -1;
13181#endif
13182#ifdef CLD_CONTINUED
13183 if (PyModule_AddIntMacro(m, CLD_CONTINUED)) return -1;
13184#endif
13185
13186 /* constants for lockf */
13187#ifdef F_LOCK
13188 if (PyModule_AddIntMacro(m, F_LOCK)) return -1;
13189#endif
13190#ifdef F_TLOCK
13191 if (PyModule_AddIntMacro(m, F_TLOCK)) return -1;
13192#endif
13193#ifdef F_ULOCK
13194 if (PyModule_AddIntMacro(m, F_ULOCK)) return -1;
13195#endif
13196#ifdef F_TEST
13197 if (PyModule_AddIntMacro(m, F_TEST)) return -1;
13198#endif
13199
13200#ifdef RWF_DSYNC
13201 if (PyModule_AddIntConstant(m, "RWF_DSYNC", RWF_DSYNC)) return -1;
13202#endif
13203#ifdef RWF_HIPRI
13204 if (PyModule_AddIntConstant(m, "RWF_HIPRI", RWF_HIPRI)) return -1;
13205#endif
13206#ifdef RWF_SYNC
13207 if (PyModule_AddIntConstant(m, "RWF_SYNC", RWF_SYNC)) return -1;
13208#endif
13209#ifdef RWF_NOWAIT
13210 if (PyModule_AddIntConstant(m, "RWF_NOWAIT", RWF_NOWAIT)) return -1;
13211#endif
13212
13213#ifdef HAVE_SPAWNV
13214 if (PyModule_AddIntConstant(m, "P_WAIT", _P_WAIT)) return -1;
13215 if (PyModule_AddIntConstant(m, "P_NOWAIT", _P_NOWAIT)) return -1;
13216 if (PyModule_AddIntConstant(m, "P_OVERLAY", _OLD_P_OVERLAY)) return -1;
13217 if (PyModule_AddIntConstant(m, "P_NOWAITO", _P_NOWAITO)) return -1;
13218 if (PyModule_AddIntConstant(m, "P_DETACH", _P_DETACH)) return -1;
13219#endif
13220
13221#ifdef HAVE_SCHED_H
13222#ifdef SCHED_OTHER
13223 if (PyModule_AddIntMacro(m, SCHED_OTHER)) return -1;
13224#endif
13225#ifdef SCHED_FIFO
13226 if (PyModule_AddIntMacro(m, SCHED_FIFO)) return -1;
13227#endif
13228#ifdef SCHED_RR
13229 if (PyModule_AddIntMacro(m, SCHED_RR)) return -1;
13230#endif
13231#ifdef SCHED_SPORADIC
13232 if (PyModule_AddIntMacro(m, SCHED_SPORADIC)) return -1;
13233#endif
13234#ifdef SCHED_BATCH
13235 if (PyModule_AddIntMacro(m, SCHED_BATCH)) return -1;
13236#endif
13237#ifdef SCHED_IDLE
13238 if (PyModule_AddIntMacro(m, SCHED_IDLE)) return -1;
13239#endif
13240#ifdef SCHED_RESET_ON_FORK
13241 if (PyModule_AddIntMacro(m, SCHED_RESET_ON_FORK)) return -1;
13242#endif
13243#ifdef SCHED_SYS
13244 if (PyModule_AddIntMacro(m, SCHED_SYS)) return -1;
13245#endif
13246#ifdef SCHED_IA
13247 if (PyModule_AddIntMacro(m, SCHED_IA)) return -1;
13248#endif
13249#ifdef SCHED_FSS
13250 if (PyModule_AddIntMacro(m, SCHED_FSS)) return -1;
13251#endif
13252#ifdef SCHED_FX
13253 if (PyModule_AddIntConstant(m, "SCHED_FX", SCHED_FSS)) return -1;
13254#endif
13255#endif
13256
13257#ifdef USE_XATTRS
13258 if (PyModule_AddIntMacro(m, XATTR_CREATE)) return -1;
13259 if (PyModule_AddIntMacro(m, XATTR_REPLACE)) return -1;
13260 if (PyModule_AddIntMacro(m, XATTR_SIZE_MAX)) return -1;
13261#endif
13262
13263#if HAVE_DECL_RTLD_LAZY
13264 if (PyModule_AddIntMacro(m, RTLD_LAZY)) return -1;
13265#endif
13266#if HAVE_DECL_RTLD_NOW
13267 if (PyModule_AddIntMacro(m, RTLD_NOW)) return -1;
13268#endif
13269#if HAVE_DECL_RTLD_GLOBAL
13270 if (PyModule_AddIntMacro(m, RTLD_GLOBAL)) return -1;
13271#endif
13272#if HAVE_DECL_RTLD_LOCAL
13273 if (PyModule_AddIntMacro(m, RTLD_LOCAL)) return -1;
13274#endif
13275#if HAVE_DECL_RTLD_NODELETE
13276 if (PyModule_AddIntMacro(m, RTLD_NODELETE)) return -1;
13277#endif
13278#if HAVE_DECL_RTLD_NOLOAD
13279 if (PyModule_AddIntMacro(m, RTLD_NOLOAD)) return -1;
13280#endif
13281#if HAVE_DECL_RTLD_DEEPBIND
13282 if (PyModule_AddIntMacro(m, RTLD_DEEPBIND)) return -1;
13283#endif
13284#if HAVE_DECL_RTLD_MEMBER
13285 if (PyModule_AddIntMacro(m, RTLD_MEMBER)) return -1;
13286#endif
13287
13288#ifdef HAVE_GETRANDOM_SYSCALL
13289 if (PyModule_AddIntMacro(m, GRND_RANDOM)) return -1;
13290 if (PyModule_AddIntMacro(m, GRND_NONBLOCK)) return -1;
13291#endif
13292
13293 return 0;
13294}
13295
13296
13297static struct PyModuleDef posixmodule = {
13298 PyModuleDef_HEAD_INIT,
13299 MODNAME,
13300 posix__doc__,
13301 -1,
13302 posix_methods,
13303 NULL,
13304 NULL,
13305 NULL,
13306 NULL
13307};
13308
13309
13310static const char * const have_functions[] = {
13311
13312#ifdef HAVE_FACCESSAT
13313 "HAVE_FACCESSAT",
13314#endif
13315
13316#ifdef HAVE_FCHDIR
13317 "HAVE_FCHDIR",
13318#endif
13319
13320#ifdef HAVE_FCHMOD
13321 "HAVE_FCHMOD",
13322#endif
13323
13324#ifdef HAVE_FCHMODAT
13325 "HAVE_FCHMODAT",
13326#endif
13327
13328#ifdef HAVE_FCHOWN
13329 "HAVE_FCHOWN",
13330#endif
13331
13332#ifdef HAVE_FCHOWNAT
13333 "HAVE_FCHOWNAT",
13334#endif
13335
13336#ifdef HAVE_FEXECVE
13337 "HAVE_FEXECVE",
13338#endif
13339
13340#ifdef HAVE_FDOPENDIR
13341 "HAVE_FDOPENDIR",
13342#endif
13343
13344#ifdef HAVE_FPATHCONF
13345 "HAVE_FPATHCONF",
13346#endif
13347
13348#ifdef HAVE_FSTATAT
13349 "HAVE_FSTATAT",
13350#endif
13351
13352#ifdef HAVE_FSTATVFS
13353 "HAVE_FSTATVFS",
13354#endif
13355
13356#if defined HAVE_FTRUNCATE || defined MS_WINDOWS
13357 "HAVE_FTRUNCATE",
13358#endif
13359
13360#ifdef HAVE_FUTIMENS
13361 "HAVE_FUTIMENS",
13362#endif
13363
13364#ifdef HAVE_FUTIMES
13365 "HAVE_FUTIMES",
13366#endif
13367
13368#ifdef HAVE_FUTIMESAT
13369 "HAVE_FUTIMESAT",
13370#endif
13371
13372#ifdef HAVE_LINKAT
13373 "HAVE_LINKAT",
13374#endif
13375
13376#ifdef HAVE_LCHFLAGS
13377 "HAVE_LCHFLAGS",
13378#endif
13379
13380#ifdef HAVE_LCHMOD
13381 "HAVE_LCHMOD",
13382#endif
13383
13384#ifdef HAVE_LCHOWN
13385 "HAVE_LCHOWN",
13386#endif
13387
13388#ifdef HAVE_LSTAT
13389 "HAVE_LSTAT",
13390#endif
13391
13392#ifdef HAVE_LUTIMES
13393 "HAVE_LUTIMES",
13394#endif
13395
13396#ifdef HAVE_MKDIRAT
13397 "HAVE_MKDIRAT",
13398#endif
13399
13400#ifdef HAVE_MKFIFOAT
13401 "HAVE_MKFIFOAT",
13402#endif
13403
13404#ifdef HAVE_MKNODAT
13405 "HAVE_MKNODAT",
13406#endif
13407
13408#ifdef HAVE_OPENAT
13409 "HAVE_OPENAT",
13410#endif
13411
13412#ifdef HAVE_READLINKAT
13413 "HAVE_READLINKAT",
13414#endif
13415
13416#ifdef HAVE_RENAMEAT
13417 "HAVE_RENAMEAT",
13418#endif
13419
13420#ifdef HAVE_SYMLINKAT
13421 "HAVE_SYMLINKAT",
13422#endif
13423
13424#ifdef HAVE_UNLINKAT
13425 "HAVE_UNLINKAT",
13426#endif
13427
13428#ifdef HAVE_UTIMENSAT
13429 "HAVE_UTIMENSAT",
13430#endif
13431
13432#ifdef MS_WINDOWS
13433 "MS_WINDOWS",
13434#endif
13435
13436 NULL
13437};
13438
13439
13440PyMODINIT_FUNC
13441INITFUNC(void)
13442{
13443 PyObject *m, *v;
13444 PyObject *list;
13445 const char * const *trace;
13446
13447#if defined(HAVE_SYMLINK) && defined(MS_WINDOWS)
13448 win32_can_symlink = enable_symlink();
13449#endif
13450
13451 m = PyModule_Create(&posixmodule);
13452 if (m == NULL)
13453 return NULL;
13454
13455 /* Initialize environ dictionary */
13456 v = convertenviron();
13457 Py_XINCREF(v);
13458 if (v == NULL || PyModule_AddObject(m, "environ", v) != 0)
13459 return NULL;
13460 Py_DECREF(v);
13461
13462 if (all_ins(m))
13463 return NULL;
13464
13465 if (setup_confname_tables(m))
13466 return NULL;
13467
13468 Py_INCREF(PyExc_OSError);
13469 PyModule_AddObject(m, "error", PyExc_OSError);
13470
13471#ifdef HAVE_PUTENV
13472 if (posix_putenv_garbage == NULL)
13473 posix_putenv_garbage = PyDict_New();
13474#endif
13475
13476 if (!initialized) {
13477#if defined(HAVE_WAITID) && !defined(__APPLE__)
13478 waitid_result_desc.name = MODNAME ".waitid_result";
13479 if (PyStructSequence_InitType2(&WaitidResultType, &waitid_result_desc) < 0)
13480 return NULL;
13481#endif
13482
13483 stat_result_desc.name = "os.stat_result"; /* see issue #19209 */
13484 stat_result_desc.fields[7].name = PyStructSequence_UnnamedField;
13485 stat_result_desc.fields[8].name = PyStructSequence_UnnamedField;
13486 stat_result_desc.fields[9].name = PyStructSequence_UnnamedField;
13487 if (PyStructSequence_InitType2(&StatResultType, &stat_result_desc) < 0)
13488 return NULL;
13489 structseq_new = StatResultType.tp_new;
13490 StatResultType.tp_new = statresult_new;
13491
13492 statvfs_result_desc.name = "os.statvfs_result"; /* see issue #19209 */
13493 if (PyStructSequence_InitType2(&StatVFSResultType,
13494 &statvfs_result_desc) < 0)
13495 return NULL;
13496#ifdef NEED_TICKS_PER_SECOND
13497# if defined(HAVE_SYSCONF) && defined(_SC_CLK_TCK)
13498 ticks_per_second = sysconf(_SC_CLK_TCK);
13499# elif defined(HZ)
13500 ticks_per_second = HZ;
13501# else
13502 ticks_per_second = 60; /* magic fallback value; may be bogus */
13503# endif
13504#endif
13505
13506#if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER)
13507 sched_param_desc.name = MODNAME ".sched_param";
13508 if (PyStructSequence_InitType2(&SchedParamType, &sched_param_desc) < 0)
13509 return NULL;
13510 SchedParamType.tp_new = os_sched_param;
13511#endif
13512
13513 /* initialize TerminalSize_info */
13514 if (PyStructSequence_InitType2(&TerminalSizeType,
13515 &TerminalSize_desc) < 0)
13516 return NULL;
13517
13518 /* initialize scandir types */
13519 if (PyType_Ready(&ScandirIteratorType) < 0)
13520 return NULL;
13521 if (PyType_Ready(&DirEntryType) < 0)
13522 return NULL;
13523 }
13524#if defined(HAVE_WAITID) && !defined(__APPLE__)
13525 Py_INCREF((PyObject*) &WaitidResultType);
13526 PyModule_AddObject(m, "waitid_result", (PyObject*) &WaitidResultType);
13527#endif
13528 Py_INCREF((PyObject*) &StatResultType);
13529 PyModule_AddObject(m, "stat_result", (PyObject*) &StatResultType);
13530 Py_INCREF((PyObject*) &StatVFSResultType);
13531 PyModule_AddObject(m, "statvfs_result",
13532 (PyObject*) &StatVFSResultType);
13533
13534#if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER)
13535 Py_INCREF(&SchedParamType);
13536 PyModule_AddObject(m, "sched_param", (PyObject *)&SchedParamType);
13537#endif
13538
13539 times_result_desc.name = MODNAME ".times_result";
13540 if (PyStructSequence_InitType2(&TimesResultType, ×_result_desc) < 0)
13541 return NULL;
13542 PyModule_AddObject(m, "times_result", (PyObject *)&TimesResultType);
13543
13544 uname_result_desc.name = MODNAME ".uname_result";
13545 if (PyStructSequence_InitType2(&UnameResultType, &uname_result_desc) < 0)
13546 return NULL;
13547 PyModule_AddObject(m, "uname_result", (PyObject *)&UnameResultType);
13548
13549#ifdef __APPLE__
13550 /*
13551 * Step 2 of weak-linking support on Mac OS X.
13552 *
13553 * The code below removes functions that are not available on the
13554 * currently active platform.
13555 *
13556 * This block allow one to use a python binary that was build on
13557 * OSX 10.4 on OSX 10.3, without losing access to new APIs on
13558 * OSX 10.4.
13559 */
13560#ifdef HAVE_FSTATVFS
13561 if (fstatvfs == NULL) {
13562 if (PyObject_DelAttrString(m, "fstatvfs") == -1) {
13563 return NULL;
13564 }
13565 }
13566#endif /* HAVE_FSTATVFS */
13567
13568#ifdef HAVE_STATVFS
13569 if (statvfs == NULL) {
13570 if (PyObject_DelAttrString(m, "statvfs") == -1) {
13571 return NULL;
13572 }
13573 }
13574#endif /* HAVE_STATVFS */
13575
13576# ifdef HAVE_LCHOWN
13577 if (lchown == NULL) {
13578 if (PyObject_DelAttrString(m, "lchown") == -1) {
13579 return NULL;
13580 }
13581 }
13582#endif /* HAVE_LCHOWN */
13583
13584
13585#endif /* __APPLE__ */
13586
13587 Py_INCREF(&TerminalSizeType);
13588 PyModule_AddObject(m, "terminal_size", (PyObject*) &TerminalSizeType);
13589
13590 billion = PyLong_FromLong(1000000000);
13591 if (!billion)
13592 return NULL;
13593
13594 /* suppress "function not used" warnings */
13595 {
13596 int ignored;
13597 fd_specified("", -1);
13598 follow_symlinks_specified("", 1);
13599 dir_fd_and_follow_symlinks_invalid("chmod", DEFAULT_DIR_FD, 1);
13600 dir_fd_converter(Py_None, &ignored);
13601 dir_fd_unavailable(Py_None, &ignored);
13602 }
13603
13604 /*
13605 * provide list of locally available functions
13606 * so os.py can populate support_* lists
13607 */
13608 list = PyList_New(0);
13609 if (!list)
13610 return NULL;
13611 for (trace = have_functions; *trace; trace++) {
13612 PyObject *unicode = PyUnicode_DecodeASCII(*trace, strlen(*trace), NULL);
13613 if (!unicode)
13614 return NULL;
13615 if (PyList_Append(list, unicode))
13616 return NULL;
13617 Py_DECREF(unicode);
13618 }
13619 PyModule_AddObject(m, "_have_functions", list);
13620
13621 Py_INCREF((PyObject *) &DirEntryType);
13622 PyModule_AddObject(m, "DirEntry", (PyObject *)&DirEntryType);
13623
13624 initialized = 1;
13625
13626 return m;
13627}
13628
13629#ifdef __cplusplus
13630}
13631#endif