Coverage Report

Created: 2026-12-01 06:09

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/cpython/Modules/posixmodule.c
Line
Count
Source
1
/* POSIX module implementation */
2
3
/* This file is also used for Windows NT/MS-Win.  In that case the
4
   module actually calls itself 'nt', not 'posix', and a few
5
   functions are either unimplemented or implemented differently.  The source
6
   assumes that for Windows NT, the macro 'MS_WINDOWS' is defined independent
7
   of the compiler used.  Different compilers define their own feature
8
   test macro, e.g. '_MSC_VER'. */
9
10
// --- Python includes ------------------------------------------------------
11
12
#include "Python.h"
13
14
#ifdef __VXWORKS__
15
#  include "pycore_bitutils.h"    // _Py_popcount32()
16
#endif
17
#include "pycore_abstract.h"      // _PyNumber_Index()
18
#include "pycore_call.h"          // _PyObject_CallNoArgs()
19
#include "pycore_ceval.h"         // _PyEval_ReInitThreads()
20
#include "pycore_fileutils.h"     // _Py_closerange()
21
#include "pycore_import.h"        // _PyImport_AcquireLock()
22
#include "pycore_initconfig.h"    // _PyStatus_EXCEPTION()
23
#include "pycore_jit_unwind.h"    // _Py_jit_debug_mutex
24
#include "pycore_lock.h"          // PyMutex_LockFast()
25
#include "pycore_long.h"          // _PyLong_IsNegative()
26
#include "pycore_moduleobject.h"  // _PyModule_GetState()
27
#include "pycore_object.h"        // _PyObject_LookupSpecial()
28
#include "pycore_pylifecycle.h"   // _PyOS_URandom()
29
#include "pycore_pystate.h"       // _PyInterpreterState_GET()
30
#include "pycore_signal.h"        // Py_NSIG
31
#include "pycore_time.h"          // _PyLong_FromTime_t()
32
#include "pycore_tuple.h"         // _PyTuple_FromPairSteal
33
#include "pycore_typeobject.h"    // _PyType_AddMethod()
34
#include "pycore_warnings.h"      // _PyWarnings_AfterFork()
35
36
#ifndef MS_WINDOWS
37
#  include "posixmodule.h"        // _PyLong_FromUid()
38
#else
39
#  include "pycore_fileutils_windows.h" // _Py_GetFileInformationByName()
40
#  include "osdefs.h"             // SEP
41
#  include "winreparse.h"         // _Py_REPARSE_DATA_BUFFER
42
#endif
43
44
45
// --- System includes ------------------------------------------------------
46
47
#include <stddef.h>               // offsetof()
48
#include <stdio.h>                // ctermid()
49
#include <stdlib.h>               // system()
50
51
#ifdef HAVE_UNISTD_H
52
#  include <unistd.h>             // symlink()
53
#endif
54
55
#ifdef __APPLE__
56
   /* Needed for the implementation of os.statvfs */
57
#  include <sys/param.h>
58
#  include <sys/mount.h>
59
#endif
60
61
#ifdef HAVE_SYS_TIME_H
62
#  include <sys/time.h>           // futimes()
63
#endif
64
65
#ifdef HAVE_SYS_PIDFD_H
66
#  include <sys/pidfd.h>          // PIDFD_NONBLOCK
67
#endif
68
69
#ifdef __EMSCRIPTEN__
70
#  include "emscripten.h"         // emscripten_debugger()
71
#endif
72
73
#ifdef HAVE_SYS_RANDOM_H
74
#  include <sys/random.h>         // getrandom()
75
#endif
76
77
#ifdef HAVE_SYS_UIO_H
78
#  include <sys/uio.h>
79
#endif
80
81
#ifdef HAVE_SYS_TYPES_H
82
   /* Should be included before <sys/sysmacros.h> on HP-UX v3 */
83
#  include <sys/types.h>
84
#endif
85
#ifdef HAVE_SYS_SYSMACROS_H
86
   /* GNU C Library: major(), minor(), makedev() */
87
#  include <sys/sysmacros.h>
88
#endif
89
90
#ifdef HAVE_SYS_STAT_H
91
#  include <sys/stat.h>
92
#endif
93
94
#ifdef HAVE_SYS_WAIT_H
95
#  include <sys/wait.h>           // WNOHANG
96
#endif
97
98
#ifdef HAVE_LINUX_WAIT_H
99
#  include <linux/wait.h>         // P_PIDFD
100
#endif
101
102
#ifdef HAVE_SIGNAL_H
103
#  include <signal.h>
104
#endif
105
106
#ifdef HAVE_FCNTL_H
107
#  include <fcntl.h>              // fcntl()
108
#endif
109
110
#ifdef HAVE_GRP_H
111
#  include <grp.h>                // setgroups()
112
#endif
113
114
#ifdef HAVE_SYSEXITS_H
115
#  include <sysexits.h>           // EX_OK
116
#endif
117
118
#ifdef HAVE_SYS_LOADAVG_H
119
#  include <sys/loadavg.h>        // getloadavg()
120
#endif
121
122
#ifdef HAVE_SYS_SENDFILE_H
123
#  include <sys/sendfile.h>       // sendfile()
124
#endif
125
126
#if defined(__APPLE__)
127
#  include <copyfile.h>           // fcopyfile()
128
#endif
129
130
#ifdef HAVE_SCHED_H
131
#  include <sched.h>              // sched_setscheduler()
132
#endif
133
#ifdef HAVE_LINUX_SCHED_H
134
#  include <linux/sched.h>        // SCHED_IDLE, SCHED_RR
135
#endif
136
137
#if defined(__FreeBSD__) || defined(__DragonFly__) || defined(__APPLE__)
138
#  ifdef HAVE_SYS_SOCKET_H
139
#    include <sys/socket.h>
140
#  endif
141
#endif
142
143
#ifdef HAVE_DLFCN_H
144
#  include <dlfcn.h>
145
#endif
146
147
#ifdef __hpux
148
#  include <sys/mpctl.h>
149
#endif
150
151
#if defined(__DragonFly__) || \
152
    defined(__OpenBSD__)   || \
153
    defined(__FreeBSD__)   || \
154
    defined(__NetBSD__)    || \
155
    defined(__APPLE__)
156
#  include <sys/sysctl.h>
157
#endif
158
159
#ifdef HAVE_LINUX_RANDOM_H
160
#  include <linux/random.h>       // GRND_RANDOM
161
#endif
162
#ifdef HAVE_SYS_SYSCALL_H
163
#  include <sys/syscall.h>        // syscall(), __NR_xxx syscall numbers
164
#endif
165
#if !defined(SYS_getrandom) && defined(__NR_getrandom)
166
#  define SYS_getrandom __NR_getrandom
167
#endif
168
169
#ifdef HAVE_POSIX_SPAWN
170
#  include <spawn.h>              // posix_spawn()
171
#endif
172
173
#ifdef HAVE_UTIME_H
174
#  include <utime.h>              // utime()
175
#endif
176
177
#ifdef HAVE_SYS_UTIME_H
178
#  include <sys/utime.h>
179
#  define HAVE_UTIME_H /* pretend we do for the rest of this file */
180
#endif
181
182
#ifdef HAVE_SYS_TIMES_H
183
#  include <sys/times.h>          // times()
184
#endif
185
186
#ifdef HAVE_SYS_PARAM_H
187
#  include <sys/param.h>
188
#endif
189
190
#ifdef HAVE_SYS_UTSNAME_H
191
#  include <sys/utsname.h>        // uname()
192
#endif
193
194
/* memfd_create is either defined in sys/mman.h or sys/memfd.h
195
 * linux/memfd.h defines additional flags
196
 */
197
#ifdef HAVE_SYS_MMAN_H
198
#  include <sys/mman.h>           // memfd_create()
199
#endif
200
#ifdef HAVE_SYS_MEMFD_H
201
#  include <sys/memfd.h>          // memfd_create()
202
#endif
203
#ifdef HAVE_LINUX_MEMFD_H
204
#  include <linux/memfd.h>        // memfd_create(), MFD_CLOEXEC
205
#endif
206
207
#ifdef HAVE_SYS_EVENTFD_H
208
#  include <sys/eventfd.h>        // eventfd()
209
#endif
210
211
#ifdef HAVE_SYS_TIMERFD_H
212
#  include <sys/timerfd.h>        // timerfd_create()
213
#endif
214
215
#ifdef _Py_MEMORY_SANITIZER
216
#  include <sanitizer/msan_interface.h> // __msan_unpoison()
217
#endif
218
219
220
// --- More complex system includes -----------------------------------------
221
222
#ifdef MS_WINDOWS
223
#  include <windows.h>
224
#  if !defined(MS_WINDOWS_GAMES) || defined(MS_WINDOWS_DESKTOP)
225
#    include <pathcch.h>          // PathCchSkipRoot()
226
#  endif
227
#  include <aclapi.h>             // SetEntriesInAcl
228
#  include <lmcons.h>             // UNLEN
229
#  include <sddl.h>               // SDDL_REVISION_1
230
#  include <winioctl.h>           // FSCTL_GET_REPARSE_POINT
231
#  if defined(MS_WINDOWS_DESKTOP) || defined(MS_WINDOWS_SYSTEM)
232
#    define HAVE_SYMLINK
233
#  endif /* MS_WINDOWS_DESKTOP | MS_WINDOWS_SYSTEM */
234
#endif
235
236
237
#ifdef _MSC_VER
238
#  ifdef HAVE_DIRECT_H
239
#    include <direct.h>
240
#  endif
241
#  ifdef HAVE_IO_H
242
#    include <io.h>
243
#  endif
244
#  ifdef HAVE_PROCESS_H
245
#    include <process.h>          // getpid(), _cwait()
246
#  endif
247
#  include <malloc.h>
248
#endif /* _MSC_VER */
249
250
251
#ifdef HAVE__GETPTY
252
#  include <sys/types.h>          // mode_t
253
   // SGI apparently needs this forward declaration
254
   extern char * _getpty(int *, int, mode_t, int);
255
#endif
256
257
258
#if defined(HAVE_SYS_XATTR_H)
259
#  if defined(HAVE_LINUX_LIMITS_H) && !defined(__FreeBSD_kernel__) && !defined(__GNU__)
260
#    define USE_XATTRS
261
#    include <linux/limits.h>  // Needed for XATTR_SIZE_MAX on musl libc.
262
#  endif
263
#  if defined(__CYGWIN__)
264
#    define USE_XATTRS
265
#    include <cygwin/limits.h>  // Needed for XATTR_SIZE_MAX and XATTR_LIST_MAX.
266
#  endif
267
#endif
268
#ifdef USE_XATTRS
269
#  include <sys/xattr.h>          // fgetxattr()
270
#endif
271
272
273
#ifdef HAVE_WINDOWS_CONSOLE_IO
274
#  define TERMSIZE_USE_CONIO
275
#elif defined(HAVE_SYS_IOCTL_H)
276
#  include <sys/ioctl.h>          // ioctl(), TIOCGWINSZ
277
#  if defined(HAVE_TERMIOS_H)
278
#    include <termios.h>
279
#  endif
280
#  if defined(TIOCGWINSZ)
281
#    define TERMSIZE_USE_IOCTL
282
#  endif
283
#endif
284
285
286
/* Various compilers have only certain posix functions */
287
/* XXX Gosh I wish these were all moved into pyconfig.h */
288
#if defined(__WATCOMC__) && !defined(__QNX__)           /* Watcom compiler */
289
#  define HAVE_OPENDIR    1
290
#  define HAVE_SYSTEM     1
291
#  include <process.h>
292
#elif defined( _MSC_VER)
293
  /* Microsoft compiler */
294
#  if defined(MS_WINDOWS_DESKTOP) || defined(MS_WINDOWS_APP) || defined(MS_WINDOWS_SYSTEM)
295
#    define HAVE_GETPPID    1
296
#  endif /* MS_WINDOWS_DESKTOP | MS_WINDOWS_APP | MS_WINDOWS_SYSTEM */
297
#  if defined(MS_WINDOWS_DESKTOP)
298
#    define HAVE_GETLOGIN   1
299
#  endif /* MS_WINDOWS_DESKTOP */
300
#  if defined(MS_WINDOWS_DESKTOP) || defined(MS_WINDOWS_SYSTEM)
301
#    define HAVE_SPAWNV     1
302
#    define HAVE_EXECV      1
303
#    define HAVE_WSPAWNV    1
304
#    define HAVE_WEXECV     1
305
#    define HAVE_SYSTEM     1
306
#    define HAVE_CWAIT      1
307
#  endif /* MS_WINDOWS_DESKTOP | MS_WINDOWS_SYSTEM */
308
#  define HAVE_PIPE       1
309
#  define HAVE_FSYNC      1
310
#  define fsync _commit
311
#endif
312
313
314
#if defined(__VXWORKS__)
315
#  include <vxCpuLib.h>
316
#  include <rtpLib.h>
317
#  include <wait.h>
318
#  include <taskLib.h>
319
#  ifndef _P_WAIT
320
#    define _P_WAIT          0
321
#    define _P_NOWAIT        1
322
#    define _P_NOWAITO       1
323
#  endif
324
#endif /* __VXWORKS__ */
325
326
327
#ifdef HAVE_DIRENT_H
328
#  include <dirent.h>             // opendir()
329
341k
#  define NAMLEN(dirent) strlen((dirent)->d_name)
330
#else
331
#  if defined(__WATCOMC__) && !defined(__QNX__)
332
#    include <direct.h>
333
#    define NAMLEN(dirent) strlen((dirent)->d_name)
334
#  else
335
#    define dirent direct
336
#    define NAMLEN(dirent) (dirent)->d_namlen
337
#  endif
338
#  ifdef HAVE_SYS_NDIR_H
339
#    include <sys/ndir.h>
340
#  endif
341
#  ifdef HAVE_SYS_DIR_H
342
#    include <sys/dir.h>
343
#  endif
344
#  ifdef HAVE_NDIR_H
345
#    include <ndir.h>
346
#  endif
347
#endif
348
349
350
#if defined(MAJOR_IN_MKDEV)
351
#  include <sys/mkdev.h>
352
#else
353
#  if defined(MAJOR_IN_SYSMACROS)
354
#    include <sys/sysmacros.h>
355
#  endif
356
#  if defined(HAVE_MKNOD) && defined(HAVE_SYS_MKDEV_H)
357
#    include <sys/mkdev.h>
358
#  endif
359
#endif
360
361
362
// --- Macros ---------------------------------------------------------------
363
364
#ifndef MAXPATHLEN
365
#  if defined(PATH_MAX) && PATH_MAX > 1024
366
#    define MAXPATHLEN PATH_MAX
367
#  else
368
#    define MAXPATHLEN 1024
369
#  endif
370
#endif /* MAXPATHLEN */
371
372
373
#ifdef UNION_WAIT
374
   /* Emulate some macros on systems that have a union instead of macros */
375
#  ifndef WIFEXITED
376
#    define WIFEXITED(u_wait) (!(u_wait).w_termsig && !(u_wait).w_coredump)
377
#  endif
378
#  ifndef WEXITSTATUS
379
#    define WEXITSTATUS(u_wait) (WIFEXITED(u_wait)?((u_wait).w_retcode):-1)
380
#  endif
381
#  ifndef WTERMSIG
382
#    define WTERMSIG(u_wait) ((u_wait).w_termsig)
383
#  endif
384
#  define WAIT_TYPE union wait
385
#  define WAIT_STATUS_INT(s) (s.w_status)
386
#else
387
   /* !UNION_WAIT */
388
0
#  define WAIT_TYPE int
389
0
#  define WAIT_STATUS_INT(s) (s)
390
#endif /* UNION_WAIT */
391
392
393
/* Don't use the "_r" form if we don't need it (also, won't have a
394
   prototype for it, at least on Solaris -- maybe others as well?). */
395
#if defined(HAVE_CTERMID_R)
396
#  define USE_CTERMID_R
397
#endif
398
399
400
/* choose the appropriate stat and fstat functions and return structs */
401
#undef STAT
402
#undef FSTAT
403
#undef STRUCT_STAT
404
#ifdef MS_WINDOWS
405
#  define STAT win32_stat
406
#  define LSTAT win32_lstat
407
#  define FSTAT _Py_fstat_noraise
408
#  define STRUCT_STAT struct _Py_stat_struct
409
#else
410
207k
#  define STAT stat
411
11.5k
#  define LSTAT lstat
412
101k
#  define FSTAT fstat
413
417k
#  define STRUCT_STAT struct stat
414
#endif
415
416
#ifdef HAVE_STATX
417
/* until we can assume glibc 2.28 at runtime, we must weakly link */
418
#  pragma weak statx
419
static const unsigned int _Py_STATX_KNOWN = (STATX_BASIC_STATS | STATX_BTIME
420
#ifdef STATX_MNT_ID
421
                                             | STATX_MNT_ID
422
#endif
423
#ifdef STATX_DIOALIGN
424
                                             | STATX_DIOALIGN
425
#endif
426
#ifdef STATX_MNT_ID_UNIQUE
427
                                             | STATX_MNT_ID_UNIQUE
428
#endif
429
#ifdef STATX_SUBVOL
430
                                             | STATX_SUBVOL
431
#endif
432
#ifdef STATX_WRITE_ATOMIC
433
                                             | STATX_WRITE_ATOMIC
434
#endif
435
#ifdef STATX_DIO_READ_ALIGN
436
                                             | STATX_DIO_READ_ALIGN
437
#endif
438
                                            );
439
#endif /* HAVE_STATX */
440
441
442
#if !defined(EX_OK) && defined(EXIT_SUCCESS)
443
#  define EX_OK EXIT_SUCCESS
444
#endif
445
446
#if !defined(CPU_ALLOC) && defined(HAVE_SCHED_SETAFFINITY)
447
#  undef HAVE_SCHED_SETAFFINITY
448
#endif
449
450
/* On android API level 21, 'AT_EACCESS' is not declared although
451
 * HAVE_FACCESSAT is defined. */
452
#ifdef __ANDROID__
453
#  undef HAVE_FACCESSAT
454
#endif
455
456
#if defined(__sun)
457
/* Something to implement in autoconf, not present in autoconf 2.69 */
458
#  define HAVE_STRUCT_STAT_ST_FSTYPE 1
459
#endif
460
461
462
// --- Apple __builtin_available() macros -----------------------------------
463
464
/*
465
 * A number of APIs are available on macOS from a certain macOS version.
466
 * To support building with a new SDK while deploying to older versions
467
 * the availability test is split into two:
468
 *   - HAVE_<FUNCTION>:  The configure check for compile time availability
469
 *   - HAVE_<FUNCTION>_RUNTIME: Runtime check for availability
470
 *
471
 * The latter is always true when not on macOS, or when using a compiler
472
 * that does not support __has_builtin (older versions of Xcode).
473
 *
474
 * Due to compiler restrictions there is one valid use of HAVE_<FUNCTION>_RUNTIME:
475
 *    if (HAVE_<FUNCTION>_RUNTIME) { ... }
476
 *
477
 * In mixing the test with other tests or using negations will result in compile
478
 * errors.
479
 */
480
#if defined(__APPLE__)
481
482
#include <mach/mach.h>
483
484
#if defined(__has_builtin)
485
#if __has_builtin(__builtin_available)
486
#define HAVE_BUILTIN_AVAILABLE 1
487
#endif
488
#endif
489
490
#ifdef HAVE_BUILTIN_AVAILABLE
491
#  define HAVE_FSTATAT_RUNTIME __builtin_available(macOS 10.10, iOS 8.0, *)
492
#  define HAVE_FACCESSAT_RUNTIME __builtin_available(macOS 10.10, iOS 8.0, *)
493
#  define HAVE_FCHMODAT_RUNTIME __builtin_available(macOS 10.10, iOS 8.0, *)
494
#  define HAVE_FCHOWNAT_RUNTIME __builtin_available(macOS 10.10, iOS 8.0, *)
495
#  define HAVE_LINKAT_RUNTIME __builtin_available(macOS 10.10, iOS 8.0, *)
496
#  define HAVE_FDOPENDIR_RUNTIME __builtin_available(macOS 10.10, iOS 8.0, *)
497
#  define HAVE_MKDIRAT_RUNTIME __builtin_available(macOS 10.10, iOS 8.0, *)
498
#  define HAVE_RENAMEAT_RUNTIME __builtin_available(macOS 10.10, iOS 8.0, *)
499
#  define HAVE_UNLINKAT_RUNTIME __builtin_available(macOS 10.10, iOS 8.0, *)
500
#  define HAVE_OPENAT_RUNTIME __builtin_available(macOS 10.10, iOS 8.0, *)
501
#  define HAVE_READLINKAT_RUNTIME __builtin_available(macOS 10.10, iOS 8.0, *)
502
#  define HAVE_FREADLINK_RUNTIME __builtin_available(macOS 13.0, iOS 16.0, *)
503
#  define HAVE_SYMLINKAT_RUNTIME __builtin_available(macOS 10.10, iOS 8.0, *)
504
#  define HAVE_FUTIMENS_RUNTIME __builtin_available(macOS 10.13, iOS 11.0, tvOS 11.0, watchOS 4.0, *)
505
#  define HAVE_UTIMENSAT_RUNTIME __builtin_available(macOS 10.13, iOS 11.0, tvOS 11.0, watchOS 4.0, *)
506
#  define HAVE_PWRITEV_RUNTIME __builtin_available(macOS 11.0, iOS 14.0, tvOS 14.0, watchOS 7.0, *)
507
#  define HAVE_MKFIFOAT_RUNTIME __builtin_available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *)
508
#  define HAVE_MKNODAT_RUNTIME __builtin_available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *)
509
#  define HAVE_PTSNAME_R_RUNTIME __builtin_available(macOS 10.13.4, iOS 11.3, tvOS 11.3, watchOS 4.3, *)
510
#  define HAVE_DUP3_RUNTIME __builtin_available(macOS 27.0, iOS 27.0, tvOS 27.0, watchOS 27.0, visionOS 27.0, *)
511
#  define HAVE_PIPE2_RUNTIME __builtin_available(macOS 27.0, iOS 27.0, tvOS 27.0, watchOS 27.0, visionOS 27.0, *)
512
513
#  define HAVE_POSIX_SPAWN_SETSID_RUNTIME __builtin_available(macOS 10.15, *)
514
515
#else /* Xcode 8 or earlier */
516
517
   /* __builtin_available is not present in these compilers, but
518
    * some of the symbols might be weak linked (10.10 SDK or later
519
    * deploying on 10.9.
520
    *
521
    * Fall back to the older style of availability checking for
522
    * symbols introduced in macOS 10.10.
523
    */
524
525
#  ifdef HAVE_FSTATAT
526
#    define HAVE_FSTATAT_RUNTIME (fstatat != NULL)
527
#  endif
528
529
#  ifdef HAVE_FACCESSAT
530
#    define HAVE_FACCESSAT_RUNTIME (faccessat != NULL)
531
#  endif
532
533
#  ifdef HAVE_FCHMODAT
534
#    define HAVE_FCHMODAT_RUNTIME (fchmodat != NULL)
535
#  endif
536
537
#  ifdef HAVE_FCHOWNAT
538
#    define HAVE_FCHOWNAT_RUNTIME (fchownat != NULL)
539
#  endif
540
541
#  ifdef HAVE_LINKAT
542
#    define HAVE_LINKAT_RUNTIME (linkat != NULL)
543
#  endif
544
545
#  ifdef HAVE_FDOPENDIR
546
#    define HAVE_FDOPENDIR_RUNTIME (fdopendir != NULL)
547
#  endif
548
549
#  ifdef HAVE_MKDIRAT
550
#    define HAVE_MKDIRAT_RUNTIME (mkdirat != NULL)
551
#  endif
552
553
#  ifdef HAVE_RENAMEAT
554
#    define HAVE_RENAMEAT_RUNTIME (renameat != NULL)
555
#  endif
556
557
#  ifdef HAVE_UNLINKAT
558
#    define HAVE_UNLINKAT_RUNTIME (unlinkat != NULL)
559
#  endif
560
561
#  ifdef HAVE_OPENAT
562
#    define HAVE_OPENAT_RUNTIME (openat != NULL)
563
#  endif
564
565
#  ifdef HAVE_READLINKAT
566
#    define HAVE_READLINKAT_RUNTIME (readlinkat != NULL)
567
#  endif
568
569
#  ifdef _Py_HAVE_FREADLINK
570
#    define HAVE_FREADLINK_RUNTIME (freadlink != NULL)
571
#  endif
572
573
#  ifdef HAVE_SYMLINKAT
574
#    define HAVE_SYMLINKAT_RUNTIME (symlinkat != NULL)
575
#  endif
576
577
#  ifdef HAVE_UTIMENSAT
578
#    define HAVE_UTIMENSAT_RUNTIME (utimensat != NULL)
579
#  endif
580
581
#  ifdef HAVE_FUTIMENS
582
#    define HAVE_FUTIMENS_RUNTIME (futimens != NULL)
583
#  endif
584
585
#  ifdef HAVE_PWRITEV
586
#    define HAVE_PWRITEV_RUNTIME (pwritev != NULL)
587
#  endif
588
589
#  ifdef HAVE_MKFIFOAT
590
#    define HAVE_MKFIFOAT_RUNTIME (mkfifoat != NULL)
591
#  endif
592
593
#  ifdef HAVE_MKNODAT
594
#    define HAVE_MKNODAT_RUNTIME (mknodat != NULL)
595
#  endif
596
597
#  ifdef HAVE_PTSNAME_R
598
#    define HAVE_PTSNAME_R_RUNTIME (ptsname_r != NULL)
599
#  endif
600
601
#  ifdef HAVE_DUP3
602
#    define HAVE_DUP3_RUNTIME (dup3 != NULL)
603
#  endif
604
605
#  ifdef HAVE_PIPE2
606
#    define HAVE_PIPE2_RUNTIME (pipe2 != NULL)
607
#  endif
608
609
#endif
610
611
#ifdef HAVE_FUTIMESAT
612
/* Some of the logic for weak linking depends on this assertion */
613
# error "HAVE_FUTIMESAT unexpectedly defined"
614
#endif
615
616
#else
617
97.0k
#  define HAVE_FSTATAT_RUNTIME 1
618
0
#  define HAVE_FACCESSAT_RUNTIME 1
619
0
#  define HAVE_FCHMODAT_RUNTIME 1
620
0
#  define HAVE_FCHOWNAT_RUNTIME 1
621
#ifdef __wasi__
622
#  define HAVE_LINKAT_RUNTIME 0
623
# else
624
0
#  define HAVE_LINKAT_RUNTIME 1
625
# endif
626
101k
#  define HAVE_FDOPENDIR_RUNTIME 1
627
0
#  define HAVE_MKDIRAT_RUNTIME 1
628
0
#  define HAVE_RENAMEAT_RUNTIME 1
629
116k
#  define HAVE_UNLINKAT_RUNTIME 1
630
97.0k
#  define HAVE_OPENAT_RUNTIME 1
631
0
#  define HAVE_READLINKAT_RUNTIME 1
632
0
#  define HAVE_SYMLINKAT_RUNTIME 1
633
0
#  define HAVE_FUTIMENS_RUNTIME 1
634
0
#  define HAVE_UTIMENSAT_RUNTIME 1
635
37
#  define HAVE_PWRITEV_RUNTIME 1
636
0
#  define HAVE_MKFIFOAT_RUNTIME 1
637
0
#  define HAVE_MKNODAT_RUNTIME 1
638
0
#  define HAVE_PTSNAME_R_RUNTIME 1
639
0
#  define HAVE_DUP3_RUNTIME 1
640
37
#  define HAVE_PIPE2_RUNTIME 1
641
#  define HAVE_FREADLINK_RUNTIME 1
642
#endif
643
644
645
// --- os module ------------------------------------------------------------
646
647
#ifdef MS_WINDOWS
648
#  define INITFUNC PyInit_nt
649
#  define MODNAME "nt"
650
#  define MODNAME_OBJ &_Py_ID(nt)
651
#else
652
#  define INITFUNC PyInit_posix
653
#  define MODNAME "posix"
654
0
#  define MODNAME_OBJ &_Py_ID(posix)
655
#endif
656
657
/*[clinic input]
658
# one of the few times we lie about this name!
659
module os
660
[clinic start generated code]*/
661
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=94a0f0f978acae17]*/
662
663
PyDoc_STRVAR(posix__doc__,
664
"This module provides access to operating system functionality that is\n\
665
standardized by the C Standard and the POSIX standard (a thinly\n\
666
disguised Unix interface).  Refer to the library manual and\n\
667
corresponding Unix manual entries for more information on calls.");
668
669
670
// --- Functions ------------------------------------------------------------
671
672
#ifdef HAVE_FORK
673
static void
674
run_at_forkers(PyObject *lst, int reverse)
675
0
{
676
0
    Py_ssize_t i;
677
0
    PyObject *cpy;
678
679
0
    if (lst != NULL) {
680
0
        assert(PyList_CheckExact(lst));
681
682
        /* Use a list copy in case register_at_fork() is called from
683
         * one of the callbacks.
684
         */
685
0
        cpy = PyList_GetSlice(lst, 0, PyList_GET_SIZE(lst));
686
0
        if (cpy == NULL) {
687
0
            PyErr_FormatUnraisable("Exception ignored in atfork callback "
688
0
                                   "while copying list %R", lst);
689
0
        }
690
0
        else {
691
0
            if (reverse)
692
0
                PyList_Reverse(cpy);
693
0
            for (i = 0; i < PyList_GET_SIZE(cpy); i++) {
694
0
                PyObject *func, *res;
695
0
                func = PyList_GET_ITEM(cpy, i);
696
0
                res = _PyObject_CallNoArgs(func);
697
0
                if (res == NULL) {
698
0
                    PyErr_FormatUnraisable("Exception ignored "
699
0
                                           "in atfork callback %R", func);
700
0
                }
701
0
                else {
702
0
                    Py_DECREF(res);
703
0
                }
704
0
            }
705
0
            Py_DECREF(cpy);
706
0
        }
707
0
    }
708
0
}
709
710
void
711
PyOS_BeforeFork(void)
712
0
{
713
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
714
0
    run_at_forkers(interp->before_forkers, 1);
715
716
0
    _PyImport_AcquireLock(interp);
717
0
    _PyEval_StopTheWorldAll(&_PyRuntime);
718
0
    HEAD_LOCK(&_PyRuntime);
719
0
    _PyWarnings_BeforeFork(interp);
720
0
}
721
722
void
723
PyOS_AfterFork_Parent(void)
724
0
{
725
0
    HEAD_UNLOCK(&_PyRuntime);
726
0
    _PyEval_StartTheWorldAll(&_PyRuntime);
727
728
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
729
0
    _PyImport_ReleaseLock(interp);
730
0
    run_at_forkers(interp->after_forkers_parent, 0);
731
0
}
732
733
static void
734
reset_remotedebug_data(PyThreadState *tstate)
735
0
{
736
0
    tstate->remote_debugger_support.debugger_pending_call = 0;
737
0
    memset(tstate->remote_debugger_support.debugger_script_path, 0,
738
0
           _Py_MAX_SCRIPT_PATH_SIZE);
739
0
}
740
741
static void
742
reset_asyncio_state(_PyThreadStateImpl *tstate)
743
0
{
744
0
    llist_init(&tstate->asyncio_tasks_head);
745
0
    tstate->asyncio_running_loop = NULL;
746
0
    tstate->asyncio_running_task = NULL;
747
0
}
748
749
750
void
751
PyOS_AfterFork_Child(void)
752
0
{
753
0
    PyStatus status;
754
0
    _PyRuntimeState *runtime = &_PyRuntime;
755
756
    // re-creates runtime->interpreters.mutex (HEAD_UNLOCK)
757
0
    status = _PyRuntimeState_ReInitThreads(runtime);
758
0
    if (_PyStatus_EXCEPTION(status)) {
759
0
        goto fatal_error;
760
0
    }
761
762
0
    PyThreadState *tstate = _PyThreadState_GET();
763
0
    _Py_EnsureTstateNotNULL(tstate);
764
765
0
    assert(tstate->thread_id == PyThread_get_thread_ident());
766
0
#ifdef PY_HAVE_THREAD_NATIVE_ID
767
0
    tstate->native_thread_id = PyThread_get_thread_native_id();
768
0
#endif
769
770
#ifdef Py_GIL_DISABLED
771
    _Py_brc_after_fork(tstate->interp);
772
    _Py_qsbr_after_fork((_PyThreadStateImpl *)tstate);
773
#endif
774
775
    // Ideally we could guarantee tstate is running main.
776
0
    _PyInterpreterState_ReinitRunningMain(tstate);
777
778
0
    status = _PyEval_ReInitThreads(tstate);
779
0
    if (_PyStatus_EXCEPTION(status)) {
780
0
        goto fatal_error;
781
0
    }
782
783
#if defined(PY_HAVE_JIT_GDB_UNWIND)
784
    // The child can inherit this mutex locked if another thread held it at
785
    // fork(), but the child itself cannot be inside gdb_jit_register_code().
786
    // Reinitialize it before any executor cleanup can unregister JIT code.
787
    _Py_jit_debug_mutex = (PyMutex){0};
788
#endif
789
790
    // Thread-state cleanup can run finalizers that issue warnings.
791
0
    _PyWarnings_AfterFork(tstate->interp);
792
793
0
    reset_remotedebug_data(tstate);
794
795
0
    reset_asyncio_state((_PyThreadStateImpl *)tstate);
796
797
    // Remove the dead thread states. We "start the world" once we are the only
798
    // thread state left to undo the stop the world call in `PyOS_BeforeFork`.
799
    // That needs to happen before `_PyThreadState_DeleteList`, because that
800
    // may call destructors.
801
0
    PyThreadState *list = _PyThreadState_RemoveExcept(tstate);
802
0
    _PyEval_StartTheWorldAll(&_PyRuntime);
803
0
    _PyThreadState_DeleteList(list, /*is_after_fork=*/1);
804
805
0
    _PyImport_ReInitLock(tstate->interp);
806
0
    _PyImport_ReleaseLock(tstate->interp);
807
808
0
    _PySignal_AfterFork();
809
810
0
    status = _PyInterpreterState_DeleteExceptMain(runtime);
811
0
    if (_PyStatus_EXCEPTION(status)) {
812
0
        goto fatal_error;
813
0
    }
814
0
    assert(_PyThreadState_GET() == tstate);
815
816
0
    status = _PyPerfTrampoline_AfterFork_Child();
817
0
    if (_PyStatus_EXCEPTION(status)) {
818
0
        goto fatal_error;
819
0
    }
820
821
0
    run_at_forkers(tstate->interp->after_forkers_child, 0);
822
0
    return;
823
824
0
fatal_error:
825
0
    Py_ExitStatusException(status);
826
0
}
827
828
static int
829
register_at_forker(PyObject **lst, PyObject *func)
830
60
{
831
60
    if (func == NULL)  /* nothing to register? do nothing. */
832
40
        return 0;
833
20
    if (*lst == NULL) {
834
10
        *lst = PyList_New(0);
835
10
        if (*lst == NULL)
836
0
            return -1;
837
10
    }
838
20
    return PyList_Append(*lst, func);
839
20
}
840
#endif  /* HAVE_FORK */
841
842
843
/* Legacy wrapper */
844
void
845
PyOS_AfterFork(void)
846
0
{
847
0
#ifdef HAVE_FORK
848
0
    PyOS_AfterFork_Child();
849
0
#endif
850
0
}
851
852
853
#ifdef MS_WINDOWS
854
/* defined in fileutils.c */
855
void _Py_time_t_to_FILE_TIME(time_t, int, FILETIME *);
856
void _Py_attribute_data_to_stat(FILE_STANDARD_INFO*, ULONG,
857
                                FILE_BASIC_INFO*, FILE_ID_INFO*,
858
                                struct _Py_stat_struct*);
859
void _Py_stat_basic_info_to_stat(FILE_STAT_BASIC_INFORMATION *,
860
                                 struct _Py_stat_struct *);
861
#endif
862
863
864
#ifndef MS_WINDOWS
865
PyObject *
866
_PyLong_FromUid(uid_t uid)
867
239k
{
868
239k
    if (uid == (uid_t)-1)
869
0
        return PyLong_FromLong(-1);
870
239k
    return PyLong_FromUnsignedLong(uid);
871
239k
}
872
873
PyObject *
874
_PyLong_FromGid(gid_t gid)
875
239k
{
876
239k
    if (gid == (gid_t)-1)
877
0
        return PyLong_FromLong(-1);
878
239k
    return PyLong_FromUnsignedLong(gid);
879
239k
}
880
881
int
882
_Py_Uid_Converter(PyObject *obj, uid_t *p)
883
0
{
884
0
    uid_t uid;
885
0
    PyObject *index;
886
0
    int overflow;
887
0
    long result;
888
0
    unsigned long uresult;
889
890
0
    index = _PyNumber_Index(obj);
891
0
    if (index == NULL) {
892
0
        PyErr_Format(PyExc_TypeError,
893
0
                     "uid should be integer, not %.200s",
894
0
                     _PyType_Name(Py_TYPE(obj)));
895
0
        return 0;
896
0
    }
897
898
    /*
899
     * Handling uid_t is complicated for two reasons:
900
     *  * Although uid_t is (always?) unsigned, it still
901
     *    accepts -1.
902
     *  * We don't know its size in advance--it may be
903
     *    bigger than an int, or it may be smaller than
904
     *    a long.
905
     *
906
     * So a bit of defensive programming is in order.
907
     * Start with interpreting the value passed
908
     * in as a signed long and see if it works.
909
     */
910
911
0
    result = PyLong_AsLongAndOverflow(index, &overflow);
912
913
0
    if (!overflow) {
914
0
        uid = (uid_t)result;
915
916
0
        if (result == -1) {
917
0
            if (PyErr_Occurred())
918
0
                goto fail;
919
            /* It's a legitimate -1, we're done. */
920
0
            goto success;
921
0
        }
922
923
        /* Any other negative number is disallowed. */
924
0
        if (result < 0)
925
0
            goto underflow;
926
927
        /* Ensure the value wasn't truncated. */
928
0
        if (sizeof(uid_t) < sizeof(long) &&
929
0
            (long)uid != result)
930
0
            goto underflow;
931
0
        goto success;
932
0
    }
933
934
0
    if (overflow < 0)
935
0
        goto underflow;
936
937
    /*
938
     * Okay, the value overflowed a signed long.  If it
939
     * fits in an *unsigned* long, it may still be okay,
940
     * as uid_t may be unsigned long on this platform.
941
     */
942
0
    uresult = PyLong_AsUnsignedLong(index);
943
0
    if (PyErr_Occurred()) {
944
0
        if (PyErr_ExceptionMatches(PyExc_OverflowError))
945
0
            goto overflow;
946
0
        goto fail;
947
0
    }
948
949
0
    uid = (uid_t)uresult;
950
951
    /*
952
     * If uid == (uid_t)-1, the user actually passed in ULONG_MAX,
953
     * but this value would get interpreted as (uid_t)-1  by chown
954
     * and its siblings.   That's not what the user meant!  So we
955
     * throw an overflow exception instead.   (We already
956
     * handled a real -1 with PyLong_AsLongAndOverflow() above.)
957
     */
958
0
    if (uid == (uid_t)-1)
959
0
        goto overflow;
960
961
    /* Ensure the value wasn't truncated. */
962
0
    if (sizeof(uid_t) < sizeof(long) &&
963
0
        (unsigned long)uid != uresult)
964
0
        goto overflow;
965
    /* fallthrough */
966
967
0
success:
968
0
    Py_DECREF(index);
969
0
    *p = uid;
970
0
    return 1;
971
972
0
underflow:
973
0
    PyErr_SetString(PyExc_OverflowError,
974
0
                    "uid is less than minimum");
975
0
    goto fail;
976
977
0
overflow:
978
0
    PyErr_SetString(PyExc_OverflowError,
979
0
                    "uid is greater than maximum");
980
    /* fallthrough */
981
982
0
fail:
983
0
    Py_DECREF(index);
984
0
    return 0;
985
0
}
986
987
int
988
_Py_Gid_Converter(PyObject *obj, gid_t *p)
989
0
{
990
0
    gid_t gid;
991
0
    PyObject *index;
992
0
    int overflow;
993
0
    long result;
994
0
    unsigned long uresult;
995
996
0
    index = _PyNumber_Index(obj);
997
0
    if (index == NULL) {
998
0
        PyErr_Format(PyExc_TypeError,
999
0
                     "gid should be integer, not %.200s",
1000
0
                     _PyType_Name(Py_TYPE(obj)));
1001
0
        return 0;
1002
0
    }
1003
1004
    /*
1005
     * Handling gid_t is complicated for two reasons:
1006
     *  * Although gid_t is (always?) unsigned, it still
1007
     *    accepts -1.
1008
     *  * We don't know its size in advance--it may be
1009
     *    bigger than an int, or it may be smaller than
1010
     *    a long.
1011
     *
1012
     * So a bit of defensive programming is in order.
1013
     * Start with interpreting the value passed
1014
     * in as a signed long and see if it works.
1015
     */
1016
1017
0
    result = PyLong_AsLongAndOverflow(index, &overflow);
1018
1019
0
    if (!overflow) {
1020
0
        gid = (gid_t)result;
1021
1022
0
        if (result == -1) {
1023
0
            if (PyErr_Occurred())
1024
0
                goto fail;
1025
            /* It's a legitimate -1, we're done. */
1026
0
            goto success;
1027
0
        }
1028
1029
        /* Any other negative number is disallowed. */
1030
0
        if (result < 0) {
1031
0
            goto underflow;
1032
0
        }
1033
1034
        /* Ensure the value wasn't truncated. */
1035
0
        if (sizeof(gid_t) < sizeof(long) &&
1036
0
            (long)gid != result)
1037
0
            goto underflow;
1038
0
        goto success;
1039
0
    }
1040
1041
0
    if (overflow < 0)
1042
0
        goto underflow;
1043
1044
    /*
1045
     * Okay, the value overflowed a signed long.  If it
1046
     * fits in an *unsigned* long, it may still be okay,
1047
     * as gid_t may be unsigned long on this platform.
1048
     */
1049
0
    uresult = PyLong_AsUnsignedLong(index);
1050
0
    if (PyErr_Occurred()) {
1051
0
        if (PyErr_ExceptionMatches(PyExc_OverflowError))
1052
0
            goto overflow;
1053
0
        goto fail;
1054
0
    }
1055
1056
0
    gid = (gid_t)uresult;
1057
1058
    /*
1059
     * If gid == (gid_t)-1, the user actually passed in ULONG_MAX,
1060
     * but this value would get interpreted as (gid_t)-1  by chown
1061
     * and its siblings.   That's not what the user meant!  So we
1062
     * throw an overflow exception instead.   (We already
1063
     * handled a real -1 with PyLong_AsLongAndOverflow() above.)
1064
     */
1065
0
    if (gid == (gid_t)-1)
1066
0
        goto overflow;
1067
1068
    /* Ensure the value wasn't truncated. */
1069
0
    if (sizeof(gid_t) < sizeof(long) &&
1070
0
        (unsigned long)gid != uresult)
1071
0
        goto overflow;
1072
    /* fallthrough */
1073
1074
0
success:
1075
0
    Py_DECREF(index);
1076
0
    *p = gid;
1077
0
    return 1;
1078
1079
0
underflow:
1080
0
    PyErr_SetString(PyExc_OverflowError,
1081
0
                    "gid is less than minimum");
1082
0
    goto fail;
1083
1084
0
overflow:
1085
0
    PyErr_SetString(PyExc_OverflowError,
1086
0
                    "gid is greater than maximum");
1087
    /* fallthrough */
1088
1089
0
fail:
1090
0
    Py_DECREF(index);
1091
0
    return 0;
1092
0
}
1093
#endif /* MS_WINDOWS */
1094
1095
1096
static PyObject *
1097
_PyLong_FromDev(dev_t dev)
1098
479k
{
1099
479k
#ifdef NODEV
1100
479k
    if (dev == NODEV) {
1101
37
        return PyLong_FromLongLong((long long)dev);
1102
37
    }
1103
479k
#endif
1104
479k
    return PyLong_FromUnsignedLongLong((unsigned long long)dev);
1105
479k
}
1106
1107
1108
#if (defined(HAVE_MKNOD) && defined(HAVE_MAKEDEV)) || defined(HAVE_DEVICE_MACROS)
1109
static int
1110
_Py_Dev_Converter(PyObject *obj, void *p)
1111
0
{
1112
0
    if (!PyLong_Check(obj)) {
1113
0
        obj = _PyNumber_Index(obj);
1114
0
        if (obj == NULL) {
1115
0
            return 0;
1116
0
        }
1117
0
    }
1118
0
    else {
1119
0
        Py_INCREF(obj);
1120
0
    }
1121
0
    assert(PyLong_Check(obj));
1122
0
#ifdef NODEV
1123
0
    if (_PyLong_IsNegative((PyLongObject *)obj)) {
1124
0
        int overflow;
1125
0
        long long result = PyLong_AsLongLongAndOverflow(obj, &overflow);
1126
0
        if (result == -1 && PyErr_Occurred()) {
1127
0
            Py_DECREF(obj);
1128
0
            return 0;
1129
0
        }
1130
0
        if (!overflow && result == (long long)NODEV) {
1131
0
            *((dev_t *)p) = NODEV;
1132
0
            Py_DECREF(obj);
1133
0
            return 1;
1134
0
        }
1135
0
    }
1136
0
#endif
1137
1138
0
    unsigned long long result = PyLong_AsUnsignedLongLong(obj);
1139
0
    Py_DECREF(obj);
1140
0
    if (result == (unsigned long long)-1 && PyErr_Occurred()) {
1141
0
        return 0;
1142
0
    }
1143
0
    if ((unsigned long long)(dev_t)result != result) {
1144
0
        PyErr_SetString(PyExc_OverflowError,
1145
0
                        "Python int too large to convert to C dev_t");
1146
0
        return 0;
1147
0
    }
1148
0
    *((dev_t *)p) = (dev_t)result;
1149
0
    return 1;
1150
0
}
1151
#endif /* (HAVE_MKNOD && HAVE_MAKEDEV) || HAVE_DEVICE_MACROS */
1152
1153
1154
#ifdef AT_FDCWD
1155
/*
1156
 * Why the (int) cast?  Solaris 10 defines AT_FDCWD as 0xffd19553 (-3041965);
1157
 * without the int cast, the value gets interpreted as uint (4291925331),
1158
 * which doesn't play nicely with all the initializer lines in this file that
1159
 * look like this:
1160
 *      int dir_fd = DEFAULT_DIR_FD;
1161
 */
1162
1.86M
#define DEFAULT_DIR_FD (int)AT_FDCWD
1163
#else
1164
#define DEFAULT_DIR_FD (-100)
1165
#endif
1166
1167
static int
1168
_fd_converter(PyObject *o, int *p)
1169
315k
{
1170
315k
    int overflow;
1171
315k
    long long_value;
1172
1173
315k
    if (PyBool_Check(o)) {
1174
0
        if (PyErr_WarnEx(PyExc_RuntimeWarning,
1175
0
                "bool is used as a file descriptor", 1))
1176
0
        {
1177
0
            return 0;
1178
0
        }
1179
0
    }
1180
315k
    PyObject *index = _PyNumber_Index(o);
1181
315k
    if (index == NULL) {
1182
0
        return 0;
1183
0
    }
1184
1185
315k
    assert(PyLong_Check(index));
1186
315k
    long_value = PyLong_AsLongAndOverflow(index, &overflow);
1187
315k
    Py_DECREF(index);
1188
315k
    assert(!PyErr_Occurred());
1189
315k
    if (overflow > 0 || long_value > INT_MAX) {
1190
0
        PyErr_SetString(PyExc_OverflowError,
1191
0
                        "fd is greater than maximum");
1192
0
        return 0;
1193
0
    }
1194
315k
    if (overflow < 0 || long_value < INT_MIN) {
1195
0
        PyErr_SetString(PyExc_OverflowError,
1196
0
                        "fd is less than minimum");
1197
0
        return 0;
1198
0
    }
1199
1200
315k
    *p = (int)long_value;
1201
315k
    return 1;
1202
315k
}
1203
1204
static int
1205
dir_fd_converter(PyObject *o, void *p)
1206
231k
{
1207
231k
    if (o == Py_None) {
1208
18.0k
        *(int *)p = DEFAULT_DIR_FD;
1209
18.0k
        return 1;
1210
18.0k
    }
1211
213k
    else if (PyIndex_Check(o)) {
1212
213k
        return _fd_converter(o, (int *)p);
1213
213k
    }
1214
0
    else {
1215
0
        PyErr_Format(PyExc_TypeError,
1216
0
                     "argument should be integer or None, not %.200s",
1217
0
                     _PyType_Name(Py_TYPE(o)));
1218
0
        return 0;
1219
0
    }
1220
231k
}
1221
1222
typedef struct {
1223
    PyObject *billion;
1224
    PyObject *DirEntryType;
1225
    PyObject *ScandirIteratorType;
1226
#if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
1227
    PyObject *SchedParamType;
1228
#endif
1229
    newfunc statresult_new_orig;
1230
    PyObject *StatResultType;
1231
#ifdef HAVE_STATX
1232
    PyObject *StatxResultType;
1233
#endif
1234
    PyObject *StatVFSResultType;
1235
    PyObject *TerminalSizeType;
1236
    PyObject *TimesResultType;
1237
    PyObject *UnameResultType;
1238
#if defined(HAVE_WAITID)
1239
    PyObject *WaitidResultType;
1240
#endif
1241
#if defined(HAVE_WAIT3) || defined(HAVE_WAIT4)
1242
    PyObject *struct_rusage;
1243
#endif
1244
    PyObject *st_mode;
1245
#ifndef MS_WINDOWS
1246
    // times() clock frequency in hertz; used by os.times()
1247
    long ticks_per_second;
1248
#endif
1249
} _posixstate;
1250
1251
1252
static inline _posixstate*
1253
get_posix_state(PyObject *module)
1254
460k
{
1255
460k
    void *state = _PyModule_GetState(module);
1256
460k
    assert(state != NULL);
1257
460k
    return (_posixstate *)state;
1258
460k
}
1259
1260
/*
1261
 * A PyArg_ParseTuple "converter" function
1262
 * that handles filesystem paths in the manner
1263
 * preferred by the os module.
1264
 *
1265
 * path_converter accepts (Unicode) strings and their
1266
 * subclasses, and bytes and their subclasses.  What
1267
 * it does with the argument depends on path.make_wide:
1268
 *
1269
 *   * If path.make_wide is nonzero, if we get a (Unicode)
1270
 *     string we extract the wchar_t * and return it; if we
1271
 *     get bytes we decode to wchar_t * and return that.
1272
 *
1273
 *   * If path.make_wide is zero, if we get bytes we extract
1274
 *     the char_t * and return it; if we get a (Unicode)
1275
 *     string we encode to char_t * and return that.
1276
 *
1277
 * path_converter also optionally accepts signed
1278
 * integers (representing open file descriptors) instead
1279
 * of path strings.
1280
 *
1281
 * Input fields:
1282
 *   path.nullable
1283
 *     If nonzero, the path is permitted to be None.
1284
 *   path.nonstrict
1285
 *     If nonzero, the path is permitted to contain
1286
 *     embedded null characters and have any length.
1287
 *   path.make_wide
1288
 *     If nonzero, the converter always uses wide, decoding if necessary, else
1289
 *     it always uses narrow, encoding if necessary. The default value is
1290
 *     nonzero on Windows, else zero.
1291
 *   path.suppress_value_error
1292
 *     If nonzero, raising ValueError is suppressed.
1293
 *   path.allow_fd
1294
 *     If nonzero, the path is permitted to be a file handle
1295
 *     (a signed int) instead of a string.
1296
 *   path.function_name
1297
 *     If non-NULL, path_converter will use that as the name
1298
 *     of the function in error messages.
1299
 *     (If path.function_name is NULL it omits the function name.)
1300
 *   path.argument_name
1301
 *     If non-NULL, path_converter will use that as the name
1302
 *     of the parameter in error messages.
1303
 *     (If path.argument_name is NULL it uses "path".)
1304
 *
1305
 * Output fields:
1306
 *   path.wide
1307
 *     Points to the path if it was expressed as Unicode
1308
 *     or if it was bytes and decoded to Unicode.
1309
 *   path.narrow
1310
 *     Points to the path if it was expressed as bytes,
1311
 *     or if it was Unicode and encoded to bytes.
1312
 *   path.fd
1313
 *     Contains a file descriptor if path.accept_fd was true
1314
 *     and the caller provided a signed integer instead of any
1315
 *     sort of string.
1316
 *   path.is_fd
1317
 *     True if path was provided as a file descriptor.
1318
 *
1319
 *     WARNING: if your "path" parameter is optional, and is
1320
 *     unspecified, path_converter will never get called.
1321
 *     So if you set allow_fd, you *MUST* initialize path.fd = -1
1322
 *     yourself!
1323
 *   path.value_error
1324
 *     If nonzero, then suppress_value_error was specified and a ValueError
1325
 *     occurred.
1326
 *   path.length
1327
 *     The length of the path in characters, if specified as
1328
 *     a string.
1329
 *   path.object
1330
 *     The original object passed in (if get a PathLike object,
1331
 *     the result of PyOS_FSPath() is treated as the original object).
1332
 *     Own a reference to the object.
1333
 *   path.cleanup
1334
 *     For internal use only.  May point to a temporary object.
1335
 *     (Pay no attention to the man behind the curtain.)
1336
 *
1337
 *   At most one of path.wide or path.narrow will be non-NULL.
1338
 *   If path was None and path.nullable was set,
1339
 *     or if path was an integer and path.allow_fd was set,
1340
 *     both path.wide and path.narrow will be NULL
1341
 *     and path.length will be 0.
1342
 *
1343
 *   path_converter takes care to not write to the path_t
1344
 *   unless it's successful.  However it must reset the
1345
 *   "cleanup" field each time it's called.
1346
 *
1347
 * Use as follows:
1348
 *      path_t path;
1349
 *      memset(&path, 0, sizeof(path));
1350
 *      PyArg_ParseTuple(args, "O&", path_converter, &path);
1351
 *      // ... use values from path ...
1352
 *      path_cleanup(&path);
1353
 *
1354
 * (Note that if PyArg_Parse fails you don't need to call
1355
 * path_cleanup().  However it is safe to do so.)
1356
 */
1357
typedef struct {
1358
    // Input fields
1359
    const char *function_name;
1360
    const char *argument_name;
1361
    int nullable;
1362
    int nonstrict;
1363
    int make_wide;
1364
    int suppress_value_error;
1365
    int allow_fd;
1366
    // Output fields
1367
    const wchar_t *wide;
1368
    const char *narrow;
1369
    int fd;
1370
    bool is_fd;
1371
    int value_error;
1372
    Py_ssize_t length;
1373
    PyObject *object;
1374
    PyObject *cleanup;
1375
} path_t;
1376
1377
#define PATH_T_INITIALIZE(function_name, argument_name, nullable, nonstrict, \
1378
                          make_wide, suppress_value_error, allow_fd) \
1379
821k
    {function_name, argument_name, nullable, nonstrict, make_wide, \
1380
821k
     suppress_value_error, allow_fd, NULL, NULL, -1, false, 0, 0, NULL, NULL}
1381
#ifdef MS_WINDOWS
1382
#define PATH_T_INITIALIZE_P(function_name, argument_name, nullable, \
1383
                            nonstrict, suppress_value_error, allow_fd) \
1384
    PATH_T_INITIALIZE(function_name, argument_name, nullable, nonstrict, 1, \
1385
                      suppress_value_error, allow_fd)
1386
#else
1387
#define PATH_T_INITIALIZE_P(function_name, argument_name, nullable, \
1388
                            nonstrict, suppress_value_error, allow_fd) \
1389
646k
    PATH_T_INITIALIZE(function_name, argument_name, nullable, nonstrict, 0, \
1390
646k
                      suppress_value_error, allow_fd)
1391
#endif
1392
1393
static void
1394
path_cleanup(path_t *path)
1395
923k
{
1396
923k
    wchar_t *wide = (wchar_t *)path->wide;
1397
923k
    path->wide = NULL;
1398
923k
    PyMem_Free(wide);
1399
923k
    Py_CLEAR(path->object);
1400
923k
    Py_CLEAR(path->cleanup);
1401
923k
}
1402
1403
static int
1404
path_converter(PyObject *o, void *p)
1405
821k
{
1406
821k
    path_t *path = (path_t *)p;
1407
821k
    PyObject *bytes = NULL;
1408
821k
    Py_ssize_t length = 0;
1409
821k
    int is_index, is_bytes, is_unicode;
1410
821k
    const char *narrow;
1411
821k
    PyObject *wo = NULL;
1412
821k
    wchar_t *wide = NULL;
1413
1414
821k
#define FORMAT_EXCEPTION(exc, fmt) \
1415
821k
    PyErr_Format(exc, "%s%s" fmt, \
1416
0
        path->function_name ? path->function_name : "", \
1417
0
        path->function_name ? ": "                : "", \
1418
0
        path->argument_name ? path->argument_name : "path")
1419
1420
    /* Py_CLEANUP_SUPPORTED support */
1421
821k
    if (o == NULL) {
1422
0
        path_cleanup(path);
1423
0
        return 1;
1424
0
    }
1425
1426
    /* Ensure it's always safe to call path_cleanup(). */
1427
821k
    path->object = path->cleanup = NULL;
1428
    /* path->object owns a reference to the original object */
1429
821k
    Py_INCREF(o);
1430
1431
821k
    if ((o == Py_None) && path->nullable) {
1432
0
        path->wide = NULL;
1433
0
        path->narrow = NULL;
1434
0
        path->fd = -1;
1435
0
        goto success_exit;
1436
0
    }
1437
1438
    /* Only call this here so that we don't treat the return value of
1439
       os.fspath() as an fd or buffer. */
1440
821k
    is_index = path->allow_fd && PyIndex_Check(o);
1441
821k
    is_bytes = PyBytes_Check(o);
1442
821k
    is_unicode = PyUnicode_Check(o);
1443
1444
821k
    if (!is_index && !is_unicode && !is_bytes) {
1445
        /* Inline PyOS_FSPath() for better error messages. */
1446
17
        PyObject *func, *res;
1447
1448
17
        func = _PyObject_LookupSpecial(o, &_Py_ID(__fspath__));
1449
17
        if ((NULL == func) || (func == Py_None)) {
1450
0
            goto error_format;
1451
0
        }
1452
17
        res = _PyObject_CallNoArgs(func);
1453
17
        Py_DECREF(func);
1454
17
        if (NULL == res) {
1455
0
            goto error_exit;
1456
0
        }
1457
17
        else if (PyUnicode_Check(res)) {
1458
17
            is_unicode = 1;
1459
17
        }
1460
0
        else if (PyBytes_Check(res)) {
1461
0
            is_bytes = 1;
1462
0
        }
1463
0
        else {
1464
0
            PyErr_Format(PyExc_TypeError,
1465
0
                 "expected %.200s.__fspath__() to return str or bytes, "
1466
0
                 "not %.200s", _PyType_Name(Py_TYPE(o)),
1467
0
                 _PyType_Name(Py_TYPE(res)));
1468
0
            Py_DECREF(res);
1469
0
            goto error_exit;
1470
0
        }
1471
1472
        /* still owns a reference to the original object */
1473
17
        Py_SETREF(o, res);
1474
17
    }
1475
1476
821k
    if (is_unicode) {
1477
720k
        if (path->make_wide) {
1478
175k
            wide = PyUnicode_AsWideCharString(o, &length);
1479
175k
            if (!wide) {
1480
0
                goto error_exit;
1481
0
            }
1482
#ifdef MS_WINDOWS
1483
            if (!path->nonstrict && length > 32767) {
1484
                FORMAT_EXCEPTION(PyExc_ValueError, "%s too long for Windows");
1485
                goto error_exit;
1486
            }
1487
#endif
1488
175k
            if (!path->nonstrict && wcslen(wide) != (size_t)length) {
1489
0
                FORMAT_EXCEPTION(PyExc_ValueError,
1490
0
                                 "embedded null character in %s");
1491
0
                goto error_exit;
1492
0
            }
1493
1494
175k
            path->wide = wide;
1495
175k
            path->narrow = NULL;
1496
175k
            path->fd = -1;
1497
175k
            wide = NULL;
1498
175k
            goto success_exit;
1499
175k
        }
1500
544k
        bytes = PyUnicode_EncodeFSDefault(o);
1501
544k
        if (!bytes) {
1502
0
            goto error_exit;
1503
0
        }
1504
544k
    }
1505
101k
    else if (is_bytes) {
1506
0
        bytes = Py_NewRef(o);
1507
0
    }
1508
101k
    else if (is_index) {
1509
101k
        if (!_fd_converter(o, &path->fd)) {
1510
0
            goto error_exit;
1511
0
        }
1512
101k
        path->wide = NULL;
1513
101k
        path->narrow = NULL;
1514
101k
        path->is_fd = true;
1515
101k
        goto success_exit;
1516
101k
    }
1517
0
    else {
1518
0
 error_format:
1519
0
        PyErr_Format(PyExc_TypeError, "%s%s%s should be %s, not %.200s",
1520
0
            path->function_name ? path->function_name : "",
1521
0
            path->function_name ? ": "                : "",
1522
0
            path->argument_name ? path->argument_name : "path",
1523
0
            path->allow_fd && path->nullable ? "string, bytes, os.PathLike, "
1524
0
                                               "integer or None" :
1525
0
            path->allow_fd ? "string, bytes, os.PathLike or integer" :
1526
0
            path->nullable ? "string, bytes, os.PathLike or None" :
1527
0
                             "string, bytes or os.PathLike",
1528
0
            _PyType_Name(Py_TYPE(o)));
1529
0
        goto error_exit;
1530
0
    }
1531
1532
544k
    length = PyBytes_GET_SIZE(bytes);
1533
544k
    narrow = PyBytes_AS_STRING(bytes);
1534
544k
    if (!path->nonstrict && strlen(narrow) != (size_t)length) {
1535
0
        FORMAT_EXCEPTION(PyExc_ValueError, "embedded null character in %s");
1536
0
        goto error_exit;
1537
0
    }
1538
1539
544k
    if (path->make_wide) {
1540
0
        wo = PyUnicode_DecodeFSDefaultAndSize(narrow, length);
1541
0
        if (!wo) {
1542
0
            goto error_exit;
1543
0
        }
1544
1545
0
        wide = PyUnicode_AsWideCharString(wo, &length);
1546
0
        Py_DECREF(wo);
1547
0
        if (!wide) {
1548
0
            goto error_exit;
1549
0
        }
1550
#ifdef MS_WINDOWS
1551
        if (!path->nonstrict && length > 32767) {
1552
            FORMAT_EXCEPTION(PyExc_ValueError, "%s too long for Windows");
1553
            goto error_exit;
1554
        }
1555
#endif
1556
0
        if (!path->nonstrict && wcslen(wide) != (size_t)length) {
1557
0
            FORMAT_EXCEPTION(PyExc_ValueError,
1558
0
                             "embedded null character in %s");
1559
0
            goto error_exit;
1560
0
        }
1561
0
        path->wide = wide;
1562
0
        path->narrow = NULL;
1563
0
        Py_DECREF(bytes);
1564
0
        wide = NULL;
1565
0
    }
1566
544k
    else {
1567
544k
        path->wide = NULL;
1568
544k
        path->narrow = narrow;
1569
544k
        if (bytes == o) {
1570
            /* Still a reference owned by path->object, don't have to
1571
            worry about path->narrow is used after free. */
1572
0
            Py_DECREF(bytes);
1573
0
        }
1574
544k
        else {
1575
544k
            path->cleanup = bytes;
1576
544k
        }
1577
544k
    }
1578
544k
    path->fd = -1;
1579
1580
821k
 success_exit:
1581
821k
    path->value_error = 0;
1582
821k
    path->length = length;
1583
821k
    path->object = o;
1584
821k
    return Py_CLEANUP_SUPPORTED;
1585
1586
0
 error_exit:
1587
0
    Py_XDECREF(o);
1588
0
    Py_XDECREF(bytes);
1589
0
    PyMem_Free(wide);
1590
0
    if (!path->suppress_value_error ||
1591
0
        !PyErr_ExceptionMatches(PyExc_ValueError))
1592
0
    {
1593
0
        return 0;
1594
0
    }
1595
0
    PyErr_Clear();
1596
0
    path->wide = NULL;
1597
0
    path->narrow = NULL;
1598
0
    path->fd = -1;
1599
0
    path->value_error = 1;
1600
0
    path->length = 0;
1601
0
    path->object = NULL;
1602
0
    return Py_CLEANUP_SUPPORTED;
1603
0
}
1604
1605
static void
1606
argument_unavailable_error(const char *function_name, const char *argument_name)
1607
0
{
1608
0
    PyErr_Format(PyExc_NotImplementedError,
1609
0
        "%s%s%s unavailable on this platform",
1610
0
        (function_name != NULL) ? function_name : "",
1611
0
        (function_name != NULL) ? ": ": "",
1612
0
        argument_name);
1613
0
}
1614
1615
static int
1616
dir_fd_unavailable(PyObject *o, void *p)
1617
37
{
1618
37
    int dir_fd;
1619
37
    if (!dir_fd_converter(o, &dir_fd))
1620
0
        return 0;
1621
37
    if (dir_fd != DEFAULT_DIR_FD) {
1622
0
        argument_unavailable_error(NULL, "dir_fd");
1623
0
        return 0;
1624
0
    }
1625
37
    *(int *)p = dir_fd;
1626
37
    return 1;
1627
37
}
1628
1629
static int
1630
fd_specified(const char *function_name, int fd)
1631
37
{
1632
37
    if (fd == -1)
1633
37
        return 0;
1634
1635
0
    argument_unavailable_error(function_name, "fd");
1636
0
    return 1;
1637
37
}
1638
1639
static int
1640
follow_symlinks_specified(const char *function_name, int follow_symlinks)
1641
37
{
1642
37
    if (follow_symlinks)
1643
37
        return 0;
1644
1645
0
    argument_unavailable_error(function_name, "follow_symlinks");
1646
0
    return 1;
1647
37
}
1648
1649
static int
1650
path_and_dir_fd_invalid(const char *function_name, path_t *path, int dir_fd)
1651
219k
{
1652
219k
    if (!path->wide && (dir_fd != DEFAULT_DIR_FD) && !path->narrow) {
1653
0
        PyErr_Format(PyExc_ValueError,
1654
0
                     "%s: can't specify dir_fd without matching path",
1655
0
                     function_name);
1656
0
        return 1;
1657
0
    }
1658
219k
    return 0;
1659
219k
}
1660
1661
static int
1662
dir_fd_and_fd_invalid(const char *function_name, int dir_fd, int fd)
1663
219k
{
1664
219k
    if ((dir_fd != DEFAULT_DIR_FD) && (fd != -1)) {
1665
0
        PyErr_Format(PyExc_ValueError,
1666
0
                     "%s: can't specify both dir_fd and fd",
1667
0
                     function_name);
1668
0
        return 1;
1669
0
    }
1670
219k
    return 0;
1671
219k
}
1672
1673
static int
1674
fd_and_follow_symlinks_invalid(const char *function_name, int is_fd,
1675
                               int follow_symlinks)
1676
219k
{
1677
219k
    if (is_fd && (!follow_symlinks)) {
1678
0
        PyErr_Format(PyExc_ValueError,
1679
0
                     "%s: cannot use fd and follow_symlinks together",
1680
0
                     function_name);
1681
0
        return 1;
1682
0
    }
1683
219k
    return 0;
1684
219k
}
1685
1686
static int
1687
dir_fd_and_follow_symlinks_invalid(const char *function_name, int dir_fd,
1688
                                   int follow_symlinks)
1689
37
{
1690
37
    if ((dir_fd != DEFAULT_DIR_FD) && (!follow_symlinks)) {
1691
0
        PyErr_Format(PyExc_ValueError,
1692
0
                     "%s: cannot use dir_fd and follow_symlinks together",
1693
0
                     function_name);
1694
0
        return 1;
1695
0
    }
1696
37
    return 0;
1697
37
}
1698
1699
#if defined(HAVE_WAITID)
1700
static int
1701
idtype_t_converter(PyObject *arg, void *addr)
1702
0
{
1703
0
    int value = PyLong_AsInt(arg);
1704
0
    if (value == -1 && PyErr_Occurred()) {
1705
0
        return 0;
1706
0
    }
1707
0
    *((idtype_t *)addr) = (idtype_t)(value);
1708
0
    return 1;
1709
0
}
1710
#endif
1711
1712
static PyObject *
1713
PyLong_FromPy_off_t(Py_off_t offset)
1714
0
{
1715
#ifdef HAVE_LARGEFILE_SUPPORT
1716
    return PyLong_FromLongLong(offset);
1717
#else
1718
0
    return PyLong_FromLong(offset);
1719
0
#endif
1720
0
}
1721
1722
#ifdef HAVE_SIGSET_T
1723
/* Convert an iterable of integers to a sigset.
1724
   Return 1 on success, return 0 and raise an exception on error. */
1725
int
1726
_Py_Sigset_Converter(PyObject *obj, void *addr)
1727
0
{
1728
0
    sigset_t *mask = (sigset_t *)addr;
1729
0
    PyObject *iterator, *item;
1730
0
    long signum;
1731
0
    int overflow;
1732
1733
    // The extra parens suppress the unreachable-code warning with clang on MacOS
1734
0
    if (sigemptyset(mask) < (0)) {
1735
        /* Probably only if mask == NULL. */
1736
0
        PyErr_SetFromErrno(PyExc_OSError);
1737
0
        return 0;
1738
0
    }
1739
1740
0
    iterator = PyObject_GetIter(obj);
1741
0
    if (iterator == NULL) {
1742
0
        return 0;
1743
0
    }
1744
1745
0
    while ((item = PyIter_Next(iterator)) != NULL) {
1746
0
        signum = PyLong_AsLongAndOverflow(item, &overflow);
1747
0
        Py_DECREF(item);
1748
0
        if (signum <= 0 || signum >= Py_NSIG) {
1749
0
            if (overflow || signum != -1 || !PyErr_Occurred()) {
1750
0
                PyErr_Format(PyExc_ValueError,
1751
0
                             "signal number %ld out of range [1; %i]",
1752
0
                             signum, Py_NSIG - 1);
1753
0
            }
1754
0
            goto error;
1755
0
        }
1756
0
        if (sigaddset(mask, (int)signum)) {
1757
0
            if (errno != EINVAL) {
1758
                /* Probably impossible */
1759
0
                PyErr_SetFromErrno(PyExc_OSError);
1760
0
                goto error;
1761
0
            }
1762
            /* For backwards compatibility, allow idioms such as
1763
             * `range(1, NSIG)` but warn about invalid signal numbers
1764
             */
1765
0
            const char msg[] =
1766
0
                "invalid signal number %ld, please use valid_signals()";
1767
0
            if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1, msg, signum)) {
1768
0
                goto error;
1769
0
            }
1770
0
        }
1771
0
    }
1772
0
    if (!PyErr_Occurred()) {
1773
0
        Py_DECREF(iterator);
1774
0
        return 1;
1775
0
    }
1776
1777
0
error:
1778
0
    Py_DECREF(iterator);
1779
0
    return 0;
1780
0
}
1781
#endif /* HAVE_SIGSET_T */
1782
1783
/* Return a dictionary corresponding to the POSIX environment table */
1784
#if defined(WITH_NEXT_FRAMEWORK) || (defined(__APPLE__) && defined(Py_ENABLE_SHARED))
1785
/* On Darwin/MacOSX a shared library or framework has no access to
1786
** environ directly, we must obtain it with _NSGetEnviron(). See also
1787
** man environ(7).
1788
*/
1789
#include <crt_externs.h>
1790
#define USE_DARWIN_NS_GET_ENVIRON 1
1791
#elif !defined(_MSC_VER) && (!defined(__WATCOMC__) || defined(__QNX__) || defined(__VXWORKS__))
1792
extern char **environ;
1793
#endif /* !_MSC_VER */
1794
1795
static PyObject *
1796
convertenviron(void)
1797
37
{
1798
37
    PyObject *d;
1799
#ifdef MS_WINDOWS
1800
    wchar_t **e;
1801
#else
1802
37
    char **e;
1803
37
#endif
1804
1805
37
    d = PyDict_New();
1806
37
    if (d == NULL)
1807
0
        return NULL;
1808
#ifdef MS_WINDOWS
1809
    /* _wenviron must be initialized in this way if the program is started
1810
       through main() instead of wmain(). */
1811
    (void)_wgetenv(L"");
1812
    e = _wenviron;
1813
#elif defined(USE_DARWIN_NS_GET_ENVIRON)
1814
    /* environ is not accessible as an extern in a shared object on OSX; use
1815
       _NSGetEnviron to resolve it. The value changes if you add environment
1816
       variables between calls to Py_Initialize, so don't cache the value. */
1817
    e = *_NSGetEnviron();
1818
#else
1819
37
    e = environ;
1820
37
#endif
1821
37
    if (e == NULL)
1822
0
        return d;
1823
1.29k
    for (; *e != NULL; e++) {
1824
1.25k
        PyObject *k;
1825
1.25k
        PyObject *v;
1826
#ifdef MS_WINDOWS
1827
        const wchar_t *p = wcschr(*e, L'=');
1828
#else
1829
1.25k
        const char *p = strchr(*e, '=');
1830
1.25k
#endif
1831
1.25k
        if (p == NULL)
1832
0
            continue;
1833
#ifdef MS_WINDOWS
1834
        k = PyUnicode_FromWideChar(*e, (Py_ssize_t)(p-*e));
1835
#else
1836
1.25k
        k = PyBytes_FromStringAndSize(*e, (Py_ssize_t)(p-*e));
1837
1.25k
#endif
1838
1.25k
        if (k == NULL) {
1839
0
            Py_DECREF(d);
1840
0
            return NULL;
1841
0
        }
1842
#ifdef MS_WINDOWS
1843
        v = PyUnicode_FromWideChar(p+1, -1);
1844
#else
1845
1.25k
        v = PyBytes_FromStringAndSize(p+1, strlen(p+1));
1846
1.25k
#endif
1847
1.25k
        if (v == NULL) {
1848
0
            Py_DECREF(k);
1849
0
            Py_DECREF(d);
1850
0
            return NULL;
1851
0
        }
1852
1.25k
        if (PyDict_SetDefaultRef(d, k, v, NULL) < 0) {
1853
0
            Py_DECREF(v);
1854
0
            Py_DECREF(k);
1855
0
            Py_DECREF(d);
1856
0
            return NULL;
1857
0
        }
1858
1.25k
        Py_DECREF(k);
1859
1.25k
        Py_DECREF(v);
1860
1.25k
    }
1861
37
    return d;
1862
37
}
1863
1864
/* Set a POSIX-specific error from errno, and return NULL */
1865
1866
static PyObject *
1867
posix_error(void)
1868
0
{
1869
0
    return PyErr_SetFromErrno(PyExc_OSError);
1870
0
}
1871
1872
#ifdef MS_WINDOWS
1873
static PyObject *
1874
win32_error(const char* function, const char* filename)
1875
{
1876
    /* XXX We should pass the function name along in the future.
1877
       (winreg.c also wants to pass the function name.)
1878
       This would however require an additional param to the
1879
       Windows error object, which is non-trivial.
1880
    */
1881
    errno = GetLastError();
1882
    if (filename)
1883
        return PyErr_SetFromWindowsErrWithFilename(errno, filename);
1884
    else
1885
        return PyErr_SetFromWindowsErr(errno);
1886
}
1887
1888
static PyObject *
1889
win32_error_object_err(const char* function, PyObject* filename, DWORD err)
1890
{
1891
    /* XXX - see win32_error for comments on 'function' */
1892
    if (filename)
1893
        return PyErr_SetExcFromWindowsErrWithFilenameObject(
1894
                    PyExc_OSError,
1895
                    err,
1896
                    filename);
1897
    else
1898
        return PyErr_SetFromWindowsErr(err);
1899
}
1900
1901
static PyObject *
1902
win32_error_object(const char* function, PyObject* filename)
1903
{
1904
    errno = GetLastError();
1905
    return win32_error_object_err(function, filename, errno);
1906
}
1907
1908
#endif /* MS_WINDOWS */
1909
1910
static PyObject *
1911
posix_path_object_error(PyObject *path)
1912
178k
{
1913
178k
    return PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, path);
1914
178k
}
1915
1916
static PyObject *
1917
path_object_error(PyObject *path)
1918
178k
{
1919
#ifdef MS_WINDOWS
1920
    return PyErr_SetExcFromWindowsErrWithFilenameObject(
1921
                PyExc_OSError, 0, path);
1922
#else
1923
178k
    return posix_path_object_error(path);
1924
178k
#endif
1925
178k
}
1926
1927
static PyObject *
1928
path_object_error2(PyObject *path, PyObject *path2)
1929
0
{
1930
#ifdef MS_WINDOWS
1931
    return PyErr_SetExcFromWindowsErrWithFilenameObjects(
1932
                PyExc_OSError, 0, path, path2);
1933
#else
1934
0
    return PyErr_SetFromErrnoWithFilenameObjects(PyExc_OSError, path, path2);
1935
0
#endif
1936
0
}
1937
1938
static PyObject *
1939
path_error(path_t *path)
1940
178k
{
1941
178k
    return path_object_error(path->object);
1942
178k
}
1943
1944
static PyObject *
1945
posix_path_error(path_t *path)
1946
0
{
1947
0
    return posix_path_object_error(path->object);
1948
0
}
1949
1950
static PyObject *
1951
path_error2(path_t *path, path_t *path2)
1952
0
{
1953
0
    return path_object_error2(path->object, path2->object);
1954
0
}
1955
1956
1957
/* POSIX generic methods */
1958
1959
static PyObject *
1960
posix_fildes_fd(int fd, int (*func)(int))
1961
0
{
1962
0
    int res;
1963
0
    int async_err = 0;
1964
1965
0
    do {
1966
0
        Py_BEGIN_ALLOW_THREADS
1967
0
        _Py_BEGIN_SUPPRESS_IPH
1968
0
        res = (*func)(fd);
1969
0
        _Py_END_SUPPRESS_IPH
1970
0
        Py_END_ALLOW_THREADS
1971
0
    } while (res != 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
1972
0
    if (res != 0)
1973
0
        return (!async_err) ? posix_error() : NULL;
1974
0
    Py_RETURN_NONE;
1975
0
}
1976
1977
1978
#ifdef MS_WINDOWS
1979
/* This is a reimplementation of the C library's chdir function,
1980
   but one that produces Win32 errors instead of DOS error codes.
1981
   chdir is essentially a wrapper around SetCurrentDirectory; however,
1982
   it also needs to set "magic" environment variables indicating
1983
   the per-drive current directory, which are of the form =<drive>: */
1984
static BOOL __stdcall
1985
win32_wchdir(LPCWSTR path)
1986
{
1987
    wchar_t path_buf[MAX_PATH], *new_path = path_buf;
1988
    int result;
1989
    wchar_t env[4] = L"=x:";
1990
1991
    if(!SetCurrentDirectoryW(path))
1992
        return FALSE;
1993
    result = GetCurrentDirectoryW(Py_ARRAY_LENGTH(path_buf), new_path);
1994
    if (!result)
1995
        return FALSE;
1996
    if (result > Py_ARRAY_LENGTH(path_buf)) {
1997
        new_path = PyMem_RawMalloc(result * sizeof(wchar_t));
1998
        if (!new_path) {
1999
            SetLastError(ERROR_OUTOFMEMORY);
2000
            return FALSE;
2001
        }
2002
        result = GetCurrentDirectoryW(result, new_path);
2003
        if (!result) {
2004
            PyMem_RawFree(new_path);
2005
            return FALSE;
2006
        }
2007
    }
2008
    int is_unc_like_path = (wcsncmp(new_path, L"\\\\", 2) == 0 ||
2009
                            wcsncmp(new_path, L"//", 2) == 0);
2010
    if (!is_unc_like_path) {
2011
        env[1] = new_path[0];
2012
        result = SetEnvironmentVariableW(env, new_path);
2013
    }
2014
    if (new_path != path_buf)
2015
        PyMem_RawFree(new_path);
2016
    return result ? TRUE : FALSE;
2017
}
2018
#endif
2019
2020
#ifdef MS_WINDOWS
2021
/* The CRT of Windows has a number of flaws wrt. its stat() implementation:
2022
   - time stamps are restricted to second resolution
2023
   - file modification times suffer from forth-and-back conversions between
2024
     UTC and local time
2025
   Therefore, we implement our own stat, based on the Win32 API directly.
2026
*/
2027
#define HAVE_STAT_NSEC 1
2028
#define HAVE_STRUCT_STAT_ST_FILE_ATTRIBUTES 1
2029
#define HAVE_STRUCT_STAT_ST_REPARSE_TAG 1
2030
2031
/* The \\?\ prefix disables the path normalization, in particular
2032
   stripping of trailing dots and spaces. */
2033
static int
2034
is_extended_path(const wchar_t *path)
2035
{
2036
    return wcsncmp(path, L"\\\\?\\", 4) == 0;
2037
}
2038
2039
static void
2040
find_data_to_file_info(WIN32_FIND_DATAW *pFileData,
2041
                       FILE_BASIC_INFO* basic_info,
2042
                       FILE_STANDARD_INFO* standard_info,
2043
                       ULONG *reparse_tag)
2044
{
2045
    memset(basic_info, 0, sizeof(*basic_info));
2046
    memset(standard_info, 0, sizeof(*standard_info));
2047
2048
    basic_info->FileAttributes = pFileData->dwFileAttributes;
2049
    basic_info->CreationTime.HighPart = pFileData->ftCreationTime.dwHighDateTime;
2050
    basic_info->CreationTime.LowPart = pFileData->ftCreationTime.dwLowDateTime;
2051
    basic_info->LastAccessTime.HighPart = pFileData->ftLastAccessTime.dwHighDateTime;
2052
    basic_info->LastAccessTime.LowPart = pFileData->ftLastAccessTime.dwLowDateTime;
2053
    basic_info->LastWriteTime.HighPart = pFileData->ftLastWriteTime.dwHighDateTime;
2054
    basic_info->LastWriteTime.LowPart = pFileData->ftLastWriteTime.dwLowDateTime;
2055
    standard_info->EndOfFile.HighPart = pFileData->nFileSizeHigh;
2056
    standard_info->EndOfFile.LowPart = pFileData->nFileSizeLow;
2057
2058
    if (pFileData->dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT)
2059
        *reparse_tag = pFileData->dwReserved0;
2060
    else
2061
        *reparse_tag = 0;
2062
}
2063
2064
static BOOL
2065
attributes_from_dir(LPCWSTR pszFile, FILE_BASIC_INFO* basic_info, FILE_STANDARD_INFO* standard_info, ULONG* reparse_tag)
2066
{
2067
    HANDLE hFindFile;
2068
    WIN32_FIND_DATAW FileData;
2069
    LPCWSTR filename = pszFile;
2070
    size_t n = wcslen(pszFile);
2071
    if (n && (pszFile[n - 1] == L'\\' || pszFile[n - 1] == L'/')) {
2072
        // cannot use PyMem_Malloc here because we do not hold the GIL
2073
        filename = (LPCWSTR)malloc((n + 1) * sizeof(filename[0]));
2074
        if(!filename) {
2075
            SetLastError(ERROR_NOT_ENOUGH_MEMORY);
2076
            return FALSE;
2077
        }
2078
        wcsncpy_s((LPWSTR)filename, n + 1, pszFile, n);
2079
        while (--n > 0 && (filename[n] == L'\\' || filename[n] == L'/')) {
2080
            ((LPWSTR)filename)[n] = L'\0';
2081
        }
2082
        if (!n || (n == 1 && filename[1] == L':')) {
2083
            // Nothing left to query
2084
            free((void *)filename);
2085
            return FALSE;
2086
        }
2087
    }
2088
    hFindFile = FindFirstFileW(filename, &FileData);
2089
    if (pszFile != filename) {
2090
        free((void *)filename);
2091
    }
2092
    if (hFindFile == INVALID_HANDLE_VALUE) {
2093
        return FALSE;
2094
    }
2095
    FindClose(hFindFile);
2096
    find_data_to_file_info(&FileData, basic_info, standard_info, reparse_tag);
2097
    return TRUE;
2098
}
2099
2100
2101
static void
2102
update_st_mode_from_path(const wchar_t *path, DWORD attr,
2103
                         struct _Py_stat_struct *result)
2104
{
2105
    if (!(attr & FILE_ATTRIBUTE_DIRECTORY)) {
2106
        /* Fix the file execute permissions. This hack sets S_IEXEC if
2107
           the filename has an extension that is commonly used by files
2108
           that CreateProcessW can execute. A real implementation calls
2109
           GetSecurityInfo, OpenThreadToken/OpenProcessToken, and
2110
           AccessCheck to check for generic read, write, and execute
2111
           access. */
2112
        size_t len = wcslen(path);
2113
        if (!is_extended_path(path)) {
2114
            /* Trailing dots and spaces are stripped from the last component
2115
               of the path. */
2116
            while (len > 0 && (path[len - 1] == L'.' || path[len - 1] == L' ')) {
2117
                len--;
2118
            }
2119
        }
2120
        if (len >= 4) {
2121
            const wchar_t *fileExtension = path + len - 4;
2122
            if (_wcsnicmp(fileExtension, L".exe", 4) == 0 ||
2123
                _wcsnicmp(fileExtension, L".bat", 4) == 0 ||
2124
                _wcsnicmp(fileExtension, L".cmd", 4) == 0 ||
2125
                _wcsnicmp(fileExtension, L".com", 4) == 0) {
2126
                result->st_mode |= 0111;
2127
            }
2128
        }
2129
    }
2130
}
2131
2132
2133
static int
2134
win32_xstat_slow_impl(const wchar_t *path, struct _Py_stat_struct *result,
2135
                      BOOL traverse)
2136
{
2137
    HANDLE hFile;
2138
    FILE_STANDARD_INFO standardInfo = {0};
2139
    FILE_BASIC_INFO basicInfo = {0};
2140
    FILE_ID_INFO idInfo = {0};
2141
    FILE_ID_INFO *pIdInfo = NULL;
2142
    FILE_ATTRIBUTE_TAG_INFO tagInfo = { 0 };
2143
    DWORD fileType, error;
2144
    BOOL isUnhandledTag = FALSE;
2145
    int retval = 0;
2146
2147
    DWORD access = FILE_READ_ATTRIBUTES;
2148
    DWORD flags = FILE_FLAG_BACKUP_SEMANTICS; /* Allow opening directories. */
2149
    if (!traverse) {
2150
        flags |= FILE_FLAG_OPEN_REPARSE_POINT;
2151
    }
2152
2153
    hFile = CreateFileW(path, access, 0, NULL, OPEN_EXISTING, flags, NULL);
2154
    if (hFile == INVALID_HANDLE_VALUE) {
2155
        /* Either the path doesn't exist, or the caller lacks access. */
2156
        error = GetLastError();
2157
        switch (error) {
2158
        case ERROR_ACCESS_DENIED:     /* Cannot sync or read attributes. */
2159
        case ERROR_SHARING_VIOLATION: /* It's a paging file. */
2160
            /* Try reading the parent directory. */
2161
            if (!attributes_from_dir(path, &basicInfo, &standardInfo, &tagInfo.ReparseTag)) {
2162
                /* Cannot read the parent directory. */
2163
                switch (GetLastError()) {
2164
                case ERROR_FILE_NOT_FOUND: /* File cannot be found */
2165
                case ERROR_PATH_NOT_FOUND: /* File parent directory cannot be found */
2166
                case ERROR_NOT_READY: /* Drive exists but unavailable */
2167
                case ERROR_BAD_NET_NAME: /* Remote drive unavailable */
2168
                    break;
2169
                /* Restore the error from CreateFileW(). */
2170
                default:
2171
                    SetLastError(error);
2172
                }
2173
2174
                return -1;
2175
            }
2176
            if (basicInfo.FileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
2177
                if (traverse ||
2178
                    !IsReparseTagNameSurrogate(tagInfo.ReparseTag)) {
2179
                    /* The stat call has to traverse but cannot, so fail. */
2180
                    SetLastError(error);
2181
                    return -1;
2182
                }
2183
            }
2184
            break;
2185
2186
        case ERROR_INVALID_PARAMETER:
2187
            /* \\.\con requires read or write access. */
2188
            hFile = CreateFileW(path, access | GENERIC_READ,
2189
                        FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
2190
                        OPEN_EXISTING, flags, NULL);
2191
            if (hFile == INVALID_HANDLE_VALUE) {
2192
                SetLastError(error);
2193
                return -1;
2194
            }
2195
            break;
2196
2197
        case ERROR_CANT_ACCESS_FILE:
2198
            /* bpo37834: open unhandled reparse points if traverse fails. */
2199
            if (traverse) {
2200
                traverse = FALSE;
2201
                isUnhandledTag = TRUE;
2202
                hFile = CreateFileW(path, access, 0, NULL, OPEN_EXISTING,
2203
                            flags | FILE_FLAG_OPEN_REPARSE_POINT, NULL);
2204
            }
2205
            if (hFile == INVALID_HANDLE_VALUE) {
2206
                SetLastError(error);
2207
                return -1;
2208
            }
2209
            break;
2210
2211
        default:
2212
            return -1;
2213
        }
2214
    }
2215
2216
    if (hFile != INVALID_HANDLE_VALUE) {
2217
        /* Handle types other than files on disk. */
2218
        fileType = GetFileType(hFile);
2219
        if (fileType != FILE_TYPE_DISK) {
2220
            if (fileType == FILE_TYPE_UNKNOWN && GetLastError() != 0) {
2221
                retval = -1;
2222
                goto cleanup;
2223
            }
2224
            DWORD fileAttributes = GetFileAttributesW(path);
2225
            memset(result, 0, sizeof(*result));
2226
            if (fileAttributes != INVALID_FILE_ATTRIBUTES &&
2227
                fileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
2228
                /* \\.\pipe\ or \\.\mailslot\ */
2229
                result->st_mode = _S_IFDIR;
2230
            } else if (fileType == FILE_TYPE_CHAR) {
2231
                /* \\.\nul */
2232
                result->st_mode = _S_IFCHR;
2233
            } else if (fileType == FILE_TYPE_PIPE) {
2234
                /* \\.\pipe\spam */
2235
                result->st_mode = _S_IFIFO;
2236
            }
2237
            /* FILE_TYPE_UNKNOWN, e.g. \\.\mailslot\waitfor.exe\spam */
2238
            goto cleanup;
2239
        }
2240
2241
        /* Query the reparse tag, and traverse a non-link. */
2242
        if (!traverse) {
2243
            if (!GetFileInformationByHandleEx(hFile, FileAttributeTagInfo,
2244
                    &tagInfo, sizeof(tagInfo))) {
2245
                /* Allow devices that do not support FileAttributeTagInfo. */
2246
                switch (GetLastError()) {
2247
                case ERROR_INVALID_PARAMETER:
2248
                case ERROR_INVALID_FUNCTION:
2249
                case ERROR_NOT_SUPPORTED:
2250
                    tagInfo.FileAttributes = FILE_ATTRIBUTE_NORMAL;
2251
                    tagInfo.ReparseTag = 0;
2252
                    break;
2253
                default:
2254
                    retval = -1;
2255
                    goto cleanup;
2256
                }
2257
            } else if (tagInfo.FileAttributes &
2258
                         FILE_ATTRIBUTE_REPARSE_POINT) {
2259
                if (IsReparseTagNameSurrogate(tagInfo.ReparseTag)) {
2260
                    if (isUnhandledTag) {
2261
                        /* Traversing previously failed for either this link
2262
                           or its target. */
2263
                        SetLastError(ERROR_CANT_ACCESS_FILE);
2264
                        retval = -1;
2265
                        goto cleanup;
2266
                    }
2267
                /* Traverse a non-link, but not if traversing already failed
2268
                   for an unhandled tag. */
2269
                } else if (!isUnhandledTag) {
2270
                    CloseHandle(hFile);
2271
                    return win32_xstat_slow_impl(path, result, TRUE);
2272
                }
2273
            }
2274
        }
2275
2276
        if (!GetFileInformationByHandleEx(hFile, FileStandardInfo, &standardInfo, sizeof(standardInfo)) ||
2277
            !GetFileInformationByHandleEx(hFile, FileBasicInfo, &basicInfo, sizeof(basicInfo))) {
2278
            switch (GetLastError()) {
2279
            case ERROR_INVALID_PARAMETER:
2280
            case ERROR_INVALID_FUNCTION:
2281
            case ERROR_NOT_SUPPORTED:
2282
                /* Volumes and physical disks are block devices, e.g.
2283
                   \\.\C: and \\.\PhysicalDrive0. */
2284
                memset(result, 0, sizeof(*result));
2285
                result->st_mode = 0x6000; /* S_IFBLK */
2286
                goto cleanup;
2287
            }
2288
            retval = -1;
2289
            goto cleanup;
2290
        }
2291
2292
        if (GetFileInformationByHandleEx(hFile, FileIdInfo, &idInfo, sizeof(idInfo))) {
2293
            /* Successfully got FileIdInfo, so pass it along */
2294
            pIdInfo = &idInfo;
2295
        }
2296
    }
2297
2298
    _Py_attribute_data_to_stat(&standardInfo, tagInfo.ReparseTag, &basicInfo, pIdInfo, result);
2299
    update_st_mode_from_path(path, basicInfo.FileAttributes, result);
2300
2301
cleanup:
2302
    if (hFile != INVALID_HANDLE_VALUE) {
2303
        /* Preserve last error if we are failing */
2304
        error = retval ? GetLastError() : 0;
2305
        if (!CloseHandle(hFile)) {
2306
            retval = -1;
2307
        } else if (retval) {
2308
            /* Restore last error */
2309
            SetLastError(error);
2310
        }
2311
    }
2312
2313
    return retval;
2314
}
2315
2316
static int
2317
win32_xstat_impl(const wchar_t *path, struct _Py_stat_struct *result,
2318
                 BOOL traverse)
2319
{
2320
    FILE_STAT_BASIC_INFORMATION statInfo;
2321
    if (_Py_GetFileInformationByName(path, FileStatBasicByNameInfo,
2322
                                     &statInfo, sizeof(statInfo))) {
2323
        if (// Cannot use fast path for reparse points ...
2324
            !(statInfo.FileAttributes & FILE_ATTRIBUTE_REPARSE_POINT)
2325
            // ... unless it's a name surrogate (symlink) and we're not following
2326
            || (!traverse && IsReparseTagNameSurrogate(statInfo.ReparseTag))
2327
        ) {
2328
            _Py_stat_basic_info_to_stat(&statInfo, result);
2329
            update_st_mode_from_path(path, statInfo.FileAttributes, result);
2330
            return 0;
2331
        }
2332
    } else {
2333
        switch(GetLastError()) {
2334
        case ERROR_FILE_NOT_FOUND:
2335
        case ERROR_PATH_NOT_FOUND:
2336
        case ERROR_NOT_READY:
2337
        case ERROR_BAD_NET_NAME:
2338
            /* These errors aren't worth retrying with the slow path */
2339
            return -1;
2340
        case ERROR_NOT_SUPPORTED:
2341
            /* indicates the API couldn't be loaded */
2342
            break;
2343
        }
2344
    }
2345
2346
    return win32_xstat_slow_impl(path, result, traverse);
2347
}
2348
2349
static int
2350
win32_xstat(const wchar_t *path, struct _Py_stat_struct *result, BOOL traverse)
2351
{
2352
    /* Protocol violation: we explicitly clear errno, instead of
2353
       setting it to a POSIX error. Callers should use GetLastError. */
2354
    int code = win32_xstat_impl(path, result, traverse);
2355
    errno = 0;
2356
2357
    /* ctime is only deprecated from 3.12, so we copy birthtime across */
2358
    result->st_ctime = result->st_birthtime;
2359
    result->st_ctime_nsec = result->st_birthtime_nsec;
2360
    return code;
2361
}
2362
/* About the following functions: win32_lstat_w, win32_stat, win32_stat_w
2363
2364
   In Posix, stat automatically traverses symlinks and returns the stat
2365
   structure for the target.  In Windows, the equivalent GetFileAttributes by
2366
   default does not traverse symlinks and instead returns attributes for
2367
   the symlink.
2368
2369
   Instead, we will open the file (which *does* traverse symlinks by default)
2370
   and GetFileInformationByHandle(). */
2371
2372
static int
2373
win32_lstat(const wchar_t* path, struct _Py_stat_struct *result)
2374
{
2375
    return win32_xstat(path, result, FALSE);
2376
}
2377
2378
static int
2379
win32_stat(const wchar_t* path, struct _Py_stat_struct *result)
2380
{
2381
    return win32_xstat(path, result, TRUE);
2382
}
2383
2384
#endif /* MS_WINDOWS */
2385
2386
PyDoc_STRVAR(stat_result__doc__,
2387
"stat_result: Result from stat, fstat, or lstat.\n\n\
2388
This object may be accessed either as a tuple of\n\
2389
  (mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime)\n\
2390
or via the attributes st_mode, st_ino, st_dev, st_nlink, and so on.\n\
2391
\n\
2392
Posix/windows: If your platform supports st_blksize, st_blocks, st_rdev,\n\
2393
or st_flags, they are available as attributes only.\n\
2394
\n\
2395
See os.stat for more information.");
2396
2397
static PyStructSequence_Field stat_result_fields[] = {
2398
    {"st_mode",    "protection bits"},
2399
    {"st_ino",     "inode"},
2400
    {"st_dev",     "device"},
2401
    {"st_nlink",   "number of hard links"},
2402
    {"st_uid",     "user ID of owner"},
2403
    {"st_gid",     "group ID of owner"},
2404
    {"st_size",    "total size, in bytes"},
2405
    /* The NULL is replaced with PyStructSequence_UnnamedField later. */
2406
    {NULL,   "integer time of last access"},
2407
    {NULL,   "integer time of last modification"},
2408
    {NULL,   "integer time of last change"},
2409
    {"st_atime",   "time of last access"},
2410
    {"st_mtime",   "time of last modification"},
2411
    {"st_ctime",   "time of last change"},
2412
    {"st_atime_ns",   "time of last access in nanoseconds"},
2413
    {"st_mtime_ns",   "time of last modification in nanoseconds"},
2414
    {"st_ctime_ns",   "time of last change in nanoseconds"},
2415
#ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
2416
    {"st_blksize", "blocksize for filesystem I/O"},
2417
#endif
2418
#ifdef HAVE_STRUCT_STAT_ST_BLOCKS
2419
    {"st_blocks",  "number of blocks allocated"},
2420
#endif
2421
#ifdef HAVE_STRUCT_STAT_ST_RDEV
2422
    {"st_rdev",    "device type (if inode device)"},
2423
#endif
2424
#ifdef HAVE_STRUCT_STAT_ST_FLAGS
2425
    {"st_flags",   "user defined flags for file"},
2426
#endif
2427
#ifdef HAVE_STRUCT_STAT_ST_GEN
2428
    {"st_gen",    "generation number"},
2429
#endif
2430
#if defined(HAVE_STRUCT_STAT_ST_BIRTHTIME) || defined(MS_WINDOWS)
2431
    {"st_birthtime",   "time of creation"},
2432
#endif
2433
#ifdef MS_WINDOWS
2434
    {"st_birthtime_ns", "time of creation in nanoseconds"},
2435
#endif
2436
#ifdef HAVE_STRUCT_STAT_ST_FILE_ATTRIBUTES
2437
    {"st_file_attributes", "Windows file attribute bits"},
2438
#endif
2439
#ifdef HAVE_STRUCT_STAT_ST_FSTYPE
2440
    {"st_fstype",  "Type of filesystem"},
2441
#endif
2442
#ifdef HAVE_STRUCT_STAT_ST_REPARSE_TAG
2443
    {"st_reparse_tag", "Windows reparse tag"},
2444
#endif
2445
    {0}
2446
};
2447
2448
#ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
2449
#define ST_BLKSIZE_IDX 16
2450
#else
2451
#define ST_BLKSIZE_IDX 15
2452
#endif
2453
2454
#ifdef HAVE_STRUCT_STAT_ST_BLOCKS
2455
#define ST_BLOCKS_IDX (ST_BLKSIZE_IDX+1)
2456
#else
2457
#define ST_BLOCKS_IDX ST_BLKSIZE_IDX
2458
#endif
2459
2460
#ifdef HAVE_STRUCT_STAT_ST_RDEV
2461
#define ST_RDEV_IDX (ST_BLOCKS_IDX+1)
2462
#else
2463
#define ST_RDEV_IDX ST_BLOCKS_IDX
2464
#endif
2465
2466
#ifdef HAVE_STRUCT_STAT_ST_FLAGS
2467
#define ST_FLAGS_IDX (ST_RDEV_IDX+1)
2468
#else
2469
#define ST_FLAGS_IDX ST_RDEV_IDX
2470
#endif
2471
2472
#ifdef HAVE_STRUCT_STAT_ST_GEN
2473
#define ST_GEN_IDX (ST_FLAGS_IDX+1)
2474
#else
2475
#define ST_GEN_IDX ST_FLAGS_IDX
2476
#endif
2477
2478
#if defined(HAVE_STRUCT_STAT_ST_BIRTHTIME) || defined(MS_WINDOWS)
2479
#define ST_BIRTHTIME_IDX (ST_GEN_IDX+1)
2480
#else
2481
#define ST_BIRTHTIME_IDX ST_GEN_IDX
2482
#endif
2483
2484
#ifdef MS_WINDOWS
2485
#define ST_BIRTHTIME_NS_IDX (ST_BIRTHTIME_IDX+1)
2486
#else
2487
#define ST_BIRTHTIME_NS_IDX ST_BIRTHTIME_IDX
2488
#endif
2489
2490
#if defined(HAVE_STRUCT_STAT_ST_FILE_ATTRIBUTES) || defined(MS_WINDOWS)
2491
#define ST_FILE_ATTRIBUTES_IDX (ST_BIRTHTIME_NS_IDX+1)
2492
#else
2493
#define ST_FILE_ATTRIBUTES_IDX ST_BIRTHTIME_NS_IDX
2494
#endif
2495
2496
#ifdef HAVE_STRUCT_STAT_ST_FSTYPE
2497
#define ST_FSTYPE_IDX (ST_FILE_ATTRIBUTES_IDX+1)
2498
#else
2499
#define ST_FSTYPE_IDX ST_FILE_ATTRIBUTES_IDX
2500
#endif
2501
2502
#ifdef HAVE_STRUCT_STAT_ST_REPARSE_TAG
2503
#define ST_REPARSE_TAG_IDX (ST_FSTYPE_IDX+1)
2504
#else
2505
#define ST_REPARSE_TAG_IDX ST_FSTYPE_IDX
2506
#endif
2507
2508
static PyStructSequence_Desc stat_result_desc = {
2509
    "os.stat_result", /* name; see issue gh-63408 */
2510
    stat_result__doc__, /* doc */
2511
    stat_result_fields,
2512
    10
2513
};
2514
2515
PyDoc_STRVAR(statvfs_result__doc__,
2516
"statvfs_result: Result from statvfs or fstatvfs.\n\n\
2517
This object may be accessed either as a tuple of\n\
2518
  (bsize, frsize, blocks, bfree, bavail, files, ffree, favail, flag, namemax),\n\
2519
or via the attributes f_bsize, f_frsize, f_blocks, f_bfree, and so on.\n\
2520
\n\
2521
See os.statvfs for more information.");
2522
2523
static PyStructSequence_Field statvfs_result_fields[] = {
2524
    {"f_bsize",  },
2525
    {"f_frsize", },
2526
    {"f_blocks", },
2527
    {"f_bfree",  },
2528
    {"f_bavail", },
2529
    {"f_files",  },
2530
    {"f_ffree",  },
2531
    {"f_favail", },
2532
    {"f_flag",   },
2533
    {"f_namemax",},
2534
    {"f_fsid",   },
2535
    {0}
2536
};
2537
2538
static PyStructSequence_Desc statvfs_result_desc = {
2539
    "os.statvfs_result", /* name; see issue gh-63408 */
2540
    statvfs_result__doc__, /* doc */
2541
    statvfs_result_fields,
2542
    10
2543
};
2544
2545
#if defined(HAVE_WAITID)
2546
PyDoc_STRVAR(waitid_result__doc__,
2547
"waitid_result: Result from waitid.\n\n\
2548
This object may be accessed either as a tuple of\n\
2549
  (si_pid, si_uid, si_signo, si_status, si_code),\n\
2550
or via the attributes si_pid, si_uid, and so on.\n\
2551
\n\
2552
See os.waitid for more information.");
2553
2554
static PyStructSequence_Field waitid_result_fields[] = {
2555
    {"si_pid",  },
2556
    {"si_uid", },
2557
    {"si_signo", },
2558
    {"si_status",  },
2559
    {"si_code", },
2560
    {0}
2561
};
2562
2563
static PyStructSequence_Desc waitid_result_desc = {
2564
    "os.waitid_result", /* name */
2565
    waitid_result__doc__, /* doc */
2566
    waitid_result_fields,
2567
    5
2568
};
2569
#endif
2570
2571
static PyObject *
2572
statresult_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
2573
0
{
2574
0
    PyStructSequence *result;
2575
0
    int i;
2576
2577
    // ht_module doesn't get set in PyStructSequence_NewType(),
2578
    // so we can't use PyType_GetModule().
2579
0
    PyObject *mod = PyImport_GetModule(MODNAME_OBJ);
2580
0
    if (mod == NULL) {
2581
0
        return NULL;
2582
0
    }
2583
0
    _posixstate *state = get_posix_state(mod);
2584
0
    Py_DECREF(mod);
2585
0
    if (state == NULL) {
2586
0
        return NULL;
2587
0
    }
2588
0
#define structseq_new state->statresult_new_orig
2589
2590
0
    result = (PyStructSequence*)structseq_new(type, args, kwds);
2591
0
    if (!result)
2592
0
        return NULL;
2593
    /* If we have been initialized from a tuple,
2594
       st_?time might be set to None. Initialize it
2595
       from the int slots.  */
2596
0
    for (i = 7; i <= 9; i++) {
2597
0
        if (result->ob_item[i+3] == Py_None) {
2598
0
            Py_DECREF(Py_None);
2599
0
            result->ob_item[i+3] = Py_NewRef(result->ob_item[i]);
2600
0
        }
2601
0
    }
2602
0
    return (PyObject*)result;
2603
0
}
2604
2605
static int
2606
_posix_clear(PyObject *module)
2607
0
{
2608
0
    _posixstate *state = get_posix_state(module);
2609
0
    Py_CLEAR(state->billion);
2610
0
    Py_CLEAR(state->DirEntryType);
2611
0
    Py_CLEAR(state->ScandirIteratorType);
2612
0
#if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
2613
0
    Py_CLEAR(state->SchedParamType);
2614
0
#endif
2615
0
    Py_CLEAR(state->StatResultType);
2616
0
#ifdef HAVE_STATX
2617
0
    Py_CLEAR(state->StatxResultType);
2618
0
#endif
2619
0
    Py_CLEAR(state->StatVFSResultType);
2620
0
    Py_CLEAR(state->TerminalSizeType);
2621
0
    Py_CLEAR(state->TimesResultType);
2622
0
    Py_CLEAR(state->UnameResultType);
2623
0
#if defined(HAVE_WAITID)
2624
0
    Py_CLEAR(state->WaitidResultType);
2625
0
#endif
2626
0
#if defined(HAVE_WAIT3) || defined(HAVE_WAIT4)
2627
0
    Py_CLEAR(state->struct_rusage);
2628
0
#endif
2629
0
    Py_CLEAR(state->st_mode);
2630
0
    return 0;
2631
0
}
2632
2633
static int
2634
_posix_traverse(PyObject *module, visitproc visit, void *arg)
2635
2.03k
{
2636
2.03k
    _posixstate *state = get_posix_state(module);
2637
2.03k
    Py_VISIT(state->billion);
2638
2.03k
    Py_VISIT(state->DirEntryType);
2639
2.03k
    Py_VISIT(state->ScandirIteratorType);
2640
2.03k
#if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
2641
2.03k
    Py_VISIT(state->SchedParamType);
2642
2.03k
#endif
2643
2.03k
    Py_VISIT(state->StatResultType);
2644
2.03k
#ifdef HAVE_STATX
2645
2.03k
    Py_VISIT(state->StatxResultType);
2646
2.03k
#endif
2647
2.03k
    Py_VISIT(state->StatVFSResultType);
2648
2.03k
    Py_VISIT(state->TerminalSizeType);
2649
2.03k
    Py_VISIT(state->TimesResultType);
2650
2.03k
    Py_VISIT(state->UnameResultType);
2651
2.03k
#if defined(HAVE_WAITID)
2652
2.03k
    Py_VISIT(state->WaitidResultType);
2653
2.03k
#endif
2654
2.03k
#if defined(HAVE_WAIT3) || defined(HAVE_WAIT4)
2655
2.03k
    Py_VISIT(state->struct_rusage);
2656
2.03k
#endif
2657
2.03k
    Py_VISIT(state->st_mode);
2658
2.03k
    return 0;
2659
2.03k
}
2660
2661
static void
2662
_posix_free(void *module)
2663
0
{
2664
0
   _posix_clear((PyObject *)module);
2665
0
}
2666
2667
2668
2.15M
#define SEC_TO_NS (1000000000LL)
2669
static PyObject *
2670
stat_nanosecond_timestamp(_posixstate *state, time_t sec, unsigned long nsec)
2671
718k
{
2672
#if SIZEOF_TIME_T == 4
2673
    return PyLong_FromLongLong(sec * SEC_TO_NS + nsec);
2674
#else
2675
    /* 1677-09-21 00:12:44 to 2262-04-11 23:47:15 UTC inclusive */
2676
718k
    if ((LLONG_MIN/SEC_TO_NS) <= sec && sec <= (LLONG_MAX/SEC_TO_NS - 1)) {
2677
718k
        return PyLong_FromLongLong(sec * SEC_TO_NS + nsec);
2678
718k
    }
2679
0
    else
2680
0
    {
2681
0
        PyObject *ns_total = NULL;
2682
0
        PyObject *s_in_ns = NULL;
2683
0
        PyObject *s = _PyLong_FromTime_t(sec);
2684
0
        PyObject *ns_fractional = PyLong_FromUnsignedLong(nsec);
2685
0
        if (s == NULL || ns_fractional == NULL) {
2686
0
            goto exit;
2687
0
        }
2688
2689
0
        s_in_ns = PyNumber_Multiply(s, state->billion);
2690
0
        if (s_in_ns == NULL) {
2691
0
            goto exit;
2692
0
        }
2693
2694
0
        ns_total = PyNumber_Add(s_in_ns, ns_fractional);
2695
2696
0
    exit:
2697
0
        Py_XDECREF(s);
2698
0
        Py_XDECREF(ns_fractional);
2699
0
        Py_XDECREF(s_in_ns);
2700
0
        return ns_total;
2701
0
    }
2702
718k
#endif
2703
718k
}
2704
2705
static int
2706
fill_time(_posixstate *state, PyObject *v, int s_index, int f_index,
2707
          int ns_index, time_t sec, unsigned long nsec)
2708
718k
{
2709
718k
    assert(!PyErr_Occurred());
2710
718k
    assert(nsec < SEC_TO_NS);
2711
2712
718k
    if (s_index >= 0) {
2713
718k
        PyObject *s = _PyLong_FromTime_t(sec);
2714
718k
        if (s == NULL) {
2715
0
            return -1;
2716
0
        }
2717
718k
        PyStructSequence_SET_ITEM(v, s_index, s);
2718
718k
    }
2719
2720
718k
    if (f_index >= 0) {
2721
718k
        PyObject *float_s = PyFloat_FromDouble((double)sec + 1e-9 * nsec);
2722
718k
        if (float_s == NULL) {
2723
0
            return -1;
2724
0
        }
2725
718k
        PyStructSequence_SET_ITEM(v, f_index, float_s);
2726
718k
    }
2727
2728
718k
    if (ns_index >= 0) {
2729
718k
        PyObject *ns_total = stat_nanosecond_timestamp(state, sec, nsec);
2730
718k
        if (ns_total == NULL) {
2731
0
            return -1;
2732
0
        }
2733
718k
        PyStructSequence_SET_ITEM(v, ns_index, ns_total);
2734
718k
    }
2735
2736
718k
    assert(!PyErr_Occurred());
2737
718k
    return 0;
2738
718k
}
2739
#undef SEC_TO_NS
2740
2741
#ifdef MS_WINDOWS
2742
static PyObject*
2743
_pystat_l128_from_l64_l64(uint64_t low, uint64_t high)
2744
{
2745
    PyObject *o_low = PyLong_FromUnsignedLongLong(low);
2746
    if (!o_low || !high) {
2747
        return o_low;
2748
    }
2749
    PyObject *o_high = PyLong_FromUnsignedLongLong(high);
2750
    PyObject *l64 = o_high ? PyLong_FromLong(64) : NULL;
2751
    if (!l64) {
2752
        Py_XDECREF(o_high);
2753
        Py_DECREF(o_low);
2754
        return NULL;
2755
    }
2756
    Py_SETREF(o_high, PyNumber_Lshift(o_high, l64));
2757
    Py_DECREF(l64);
2758
    if (!o_high) {
2759
        Py_DECREF(o_low);
2760
        return NULL;
2761
    }
2762
    Py_SETREF(o_low, PyNumber_Add(o_low, o_high));
2763
    Py_DECREF(o_high);
2764
    return o_low;
2765
}
2766
#endif
2767
2768
/* pack a system stat C structure into the Python stat tuple
2769
   (used by posix_stat() and posix_fstat()) */
2770
static PyObject*
2771
_pystat_fromstructstat(PyObject *module, STRUCT_STAT *st)
2772
239k
{
2773
239k
    assert(!PyErr_Occurred());
2774
2775
239k
    _posixstate *state = get_posix_state(module);
2776
239k
    PyObject *StatResultType = state->StatResultType;
2777
239k
    PyObject *v = PyStructSequence_New((PyTypeObject *)StatResultType);
2778
239k
    if (v == NULL) {
2779
0
        return NULL;
2780
0
    }
2781
2782
239k
#define SET_ITEM(pos, expr) \
2783
2.39M
    do { \
2784
2.39M
        PyObject *obj = (expr); \
2785
2.39M
        if (obj == NULL) { \
2786
0
            goto error; \
2787
0
        } \
2788
2.39M
        PyStructSequence_SET_ITEM(v, (pos), obj); \
2789
2.39M
    } while (0)
2790
2791
239k
    SET_ITEM(0, PyLong_FromLong((long)st->st_mode));
2792
#ifdef MS_WINDOWS
2793
    SET_ITEM(1, _pystat_l128_from_l64_l64(st->st_ino, st->st_ino_high));
2794
    SET_ITEM(2, PyLong_FromUnsignedLongLong(st->st_dev));
2795
#else
2796
239k
    static_assert(sizeof(unsigned long long) >= sizeof(st->st_ino),
2797
239k
                  "stat.st_ino is larger than unsigned long long");
2798
239k
    SET_ITEM(1, PyLong_FromUnsignedLongLong(st->st_ino));
2799
239k
    SET_ITEM(2, _PyLong_FromDev(st->st_dev));
2800
239k
#endif
2801
239k
    SET_ITEM(3, PyLong_FromLong((long)st->st_nlink));
2802
#if defined(MS_WINDOWS)
2803
    SET_ITEM(4, PyLong_FromLong(0));
2804
    SET_ITEM(5, PyLong_FromLong(0));
2805
#else
2806
239k
    SET_ITEM(4, _PyLong_FromUid(st->st_uid));
2807
239k
    SET_ITEM(5, _PyLong_FromGid(st->st_gid));
2808
239k
#endif
2809
239k
    static_assert(sizeof(long long) >= sizeof(st->st_size),
2810
239k
                  "stat.st_size is larger than long long");
2811
239k
    SET_ITEM(6, PyLong_FromLongLong(st->st_size));
2812
2813
    // Set st_atime, st_mtime and st_ctime
2814
239k
    unsigned long ansec, mnsec, cnsec;
2815
239k
#if defined(HAVE_STAT_TV_NSEC)
2816
239k
    ansec = st->st_atim.tv_nsec;
2817
239k
    mnsec = st->st_mtim.tv_nsec;
2818
239k
    cnsec = st->st_ctim.tv_nsec;
2819
#elif defined(HAVE_STAT_TV_NSEC2)
2820
    ansec = st->st_atimespec.tv_nsec;
2821
    mnsec = st->st_mtimespec.tv_nsec;
2822
    cnsec = st->st_ctimespec.tv_nsec;
2823
#elif defined(HAVE_STAT_NSEC)
2824
    ansec = st->st_atime_nsec;
2825
    mnsec = st->st_mtime_nsec;
2826
    cnsec = st->st_ctime_nsec;
2827
#else
2828
    ansec = mnsec = cnsec = 0;
2829
#endif
2830
239k
    if (fill_time(state, v, 7, 10, 13, st->st_atime, ansec) < 0) {
2831
0
        goto error;
2832
0
    }
2833
239k
    if (fill_time(state, v, 8, 11, 14, st->st_mtime, mnsec) < 0) {
2834
0
        goto error;
2835
0
    }
2836
239k
    if (fill_time(state, v, 9, 12, 15, st->st_ctime, cnsec) < 0) {
2837
0
        goto error;
2838
0
    }
2839
2840
239k
#ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
2841
239k
    SET_ITEM(ST_BLKSIZE_IDX, PyLong_FromLong((long)st->st_blksize));
2842
239k
#endif
2843
239k
#ifdef HAVE_STRUCT_STAT_ST_BLOCKS
2844
239k
    SET_ITEM(ST_BLOCKS_IDX, PyLong_FromLong((long)st->st_blocks));
2845
239k
#endif
2846
239k
#ifdef HAVE_STRUCT_STAT_ST_RDEV
2847
239k
    SET_ITEM(ST_RDEV_IDX, _PyLong_FromDev(st->st_rdev));
2848
239k
#endif
2849
#ifdef HAVE_STRUCT_STAT_ST_GEN
2850
    SET_ITEM(ST_GEN_IDX, PyLong_FromLong((long)st->st_gen));
2851
#endif
2852
#if defined(HAVE_STRUCT_STAT_ST_BIRTHTIME)
2853
    {
2854
      unsigned long bsec, bnsec;
2855
      bsec = (long)st->st_birthtime;
2856
#ifdef HAVE_STAT_TV_NSEC2
2857
      bnsec = st->st_birthtimespec.tv_nsec;
2858
#else
2859
      bnsec = 0;
2860
#endif
2861
      SET_ITEM(ST_BIRTHTIME_IDX, PyFloat_FromDouble(bsec + bnsec * 1e-9));
2862
    }
2863
#elif defined(MS_WINDOWS)
2864
    if (fill_time(state, v, -1, ST_BIRTHTIME_IDX, ST_BIRTHTIME_NS_IDX,
2865
                  st->st_birthtime, st->st_birthtime_nsec) < 0) {
2866
        goto error;
2867
    }
2868
#endif
2869
#ifdef HAVE_STRUCT_STAT_ST_FLAGS
2870
    SET_ITEM(ST_FLAGS_IDX, PyLong_FromLong((long)st->st_flags));
2871
#endif
2872
#ifdef HAVE_STRUCT_STAT_ST_FILE_ATTRIBUTES
2873
    SET_ITEM(ST_FILE_ATTRIBUTES_IDX,
2874
             PyLong_FromUnsignedLong(st->st_file_attributes));
2875
#endif
2876
#ifdef HAVE_STRUCT_STAT_ST_FSTYPE
2877
   SET_ITEM(ST_FSTYPE_IDX, PyUnicode_FromString(st->st_fstype));
2878
#endif
2879
#ifdef HAVE_STRUCT_STAT_ST_REPARSE_TAG
2880
    SET_ITEM(ST_REPARSE_TAG_IDX, PyLong_FromUnsignedLong(st->st_reparse_tag));
2881
#endif
2882
2883
239k
    assert(!PyErr_Occurred());
2884
239k
    return v;
2885
2886
0
error:
2887
0
    Py_DECREF(v);
2888
0
    return NULL;
2889
2890
239k
#undef SET_ITEM
2891
239k
}
2892
2893
/* POSIX methods */
2894
2895
2896
static PyObject *
2897
posix_do_stat(PyObject *module, const char *function_name, path_t *path,
2898
              int dir_fd, int follow_symlinks)
2899
219k
{
2900
219k
    STRUCT_STAT st;
2901
219k
    int result;
2902
2903
219k
#ifdef HAVE_FSTATAT
2904
219k
    int fstatat_unavailable = 0;
2905
219k
#endif
2906
2907
#if !defined(MS_WINDOWS) && !defined(HAVE_FSTATAT) && !defined(HAVE_LSTAT)
2908
    if (follow_symlinks_specified(function_name, follow_symlinks))
2909
        return NULL;
2910
#endif
2911
2912
219k
    if (path_and_dir_fd_invalid("stat", path, dir_fd) ||
2913
219k
        dir_fd_and_fd_invalid("stat", dir_fd, path->fd) ||
2914
219k
        fd_and_follow_symlinks_invalid("stat", path->is_fd, follow_symlinks))
2915
0
        return NULL;
2916
2917
219k
    Py_BEGIN_ALLOW_THREADS
2918
219k
    if (path->is_fd) {
2919
0
        result = FSTAT(path->fd, &st);
2920
0
    }
2921
#ifdef MS_WINDOWS
2922
    else if (follow_symlinks)
2923
        result = win32_stat(path->wide, &st);
2924
    else
2925
        result = win32_lstat(path->wide, &st);
2926
#else
2927
219k
    else
2928
219k
#if defined(HAVE_LSTAT)
2929
219k
    if ((!follow_symlinks) && (dir_fd == DEFAULT_DIR_FD))
2930
11.5k
        result = LSTAT(path->narrow, &st);
2931
207k
    else
2932
207k
#endif /* HAVE_LSTAT */
2933
207k
#ifdef HAVE_FSTATAT
2934
207k
    if ((dir_fd != DEFAULT_DIR_FD) || !follow_symlinks) {
2935
0
        if (HAVE_FSTATAT_RUNTIME) {
2936
0
            result = fstatat(dir_fd, path->narrow, &st,
2937
0
                         follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW);
2938
2939
0
        } else {
2940
0
            fstatat_unavailable = 1;
2941
0
        }
2942
0
    } else
2943
207k
#endif /* HAVE_FSTATAT */
2944
207k
        result = STAT(path->narrow, &st);
2945
219k
#endif /* MS_WINDOWS */
2946
219k
    Py_END_ALLOW_THREADS
2947
2948
219k
#ifdef HAVE_FSTATAT
2949
219k
    if (fstatat_unavailable) {
2950
0
        argument_unavailable_error("stat", "dir_fd");
2951
0
        return NULL;
2952
0
    }
2953
219k
#endif
2954
2955
219k
    if (result != 0) {
2956
178k
        return path_error(path);
2957
178k
    }
2958
2959
40.8k
    return _pystat_fromstructstat(module, &st);
2960
219k
}
2961
2962
/*[python input]
2963
2964
for s in """
2965
2966
FACCESSAT
2967
FCHMODAT
2968
FCHOWNAT
2969
FSTATAT
2970
LINKAT
2971
MKDIRAT
2972
MKFIFOAT
2973
MKNODAT
2974
OPENAT
2975
READLINKAT
2976
SYMLINKAT
2977
UNLINKAT
2978
2979
""".strip().split():
2980
    s = s.strip()
2981
    print("""
2982
#ifdef HAVE_{s}
2983
    #define {s}_DIR_FD_CONVERTER dir_fd_converter
2984
#else
2985
    #define {s}_DIR_FD_CONVERTER dir_fd_unavailable
2986
#endif
2987
""".rstrip().format(s=s))
2988
2989
for s in """
2990
2991
FCHDIR
2992
FCHMOD
2993
FCHOWN
2994
FDOPENDIR
2995
FEXECVE
2996
FPATHCONF
2997
FSTATVFS
2998
FTRUNCATE
2999
3000
""".strip().split():
3001
    s = s.strip()
3002
    print("""
3003
#ifdef HAVE_{s}
3004
    #define PATH_HAVE_{s} 1
3005
#else
3006
    #define PATH_HAVE_{s} 0
3007
#endif
3008
3009
""".rstrip().format(s=s))
3010
[python start generated code]*/
3011
3012
#ifdef HAVE_FACCESSAT
3013
0
    #define FACCESSAT_DIR_FD_CONVERTER dir_fd_converter
3014
#else
3015
    #define FACCESSAT_DIR_FD_CONVERTER dir_fd_unavailable
3016
#endif
3017
3018
#ifdef HAVE_FCHMODAT
3019
0
    #define FCHMODAT_DIR_FD_CONVERTER dir_fd_converter
3020
#else
3021
    #define FCHMODAT_DIR_FD_CONVERTER dir_fd_unavailable
3022
#endif
3023
3024
#ifdef HAVE_FCHOWNAT
3025
0
    #define FCHOWNAT_DIR_FD_CONVERTER dir_fd_converter
3026
#else
3027
    #define FCHOWNAT_DIR_FD_CONVERTER dir_fd_unavailable
3028
#endif
3029
3030
#ifdef HAVE_FSTATAT
3031
9.00k
    #define FSTATAT_DIR_FD_CONVERTER dir_fd_converter
3032
#else
3033
    #define FSTATAT_DIR_FD_CONVERTER dir_fd_unavailable
3034
#endif
3035
3036
#ifdef HAVE_LINKAT
3037
    #define LINKAT_DIR_FD_CONVERTER dir_fd_converter
3038
#else
3039
    #define LINKAT_DIR_FD_CONVERTER dir_fd_unavailable
3040
#endif
3041
3042
#ifdef HAVE_MKDIRAT
3043
0
    #define MKDIRAT_DIR_FD_CONVERTER dir_fd_converter
3044
#else
3045
    #define MKDIRAT_DIR_FD_CONVERTER dir_fd_unavailable
3046
#endif
3047
3048
#ifdef HAVE_MKFIFOAT
3049
0
    #define MKFIFOAT_DIR_FD_CONVERTER dir_fd_converter
3050
#else
3051
    #define MKFIFOAT_DIR_FD_CONVERTER dir_fd_unavailable
3052
#endif
3053
3054
#ifdef HAVE_MKNODAT
3055
0
    #define MKNODAT_DIR_FD_CONVERTER dir_fd_converter
3056
#else
3057
    #define MKNODAT_DIR_FD_CONVERTER dir_fd_unavailable
3058
#endif
3059
3060
#ifdef HAVE_OPENAT
3061
101k
    #define OPENAT_DIR_FD_CONVERTER dir_fd_converter
3062
#else
3063
    #define OPENAT_DIR_FD_CONVERTER dir_fd_unavailable
3064
#endif
3065
3066
#ifdef HAVE_READLINKAT
3067
0
    #define READLINKAT_DIR_FD_CONVERTER dir_fd_converter
3068
#else
3069
    #define READLINKAT_DIR_FD_CONVERTER dir_fd_unavailable
3070
#endif
3071
3072
#ifdef HAVE_SYMLINKAT
3073
0
    #define SYMLINKAT_DIR_FD_CONVERTER dir_fd_converter
3074
#else
3075
    #define SYMLINKAT_DIR_FD_CONVERTER dir_fd_unavailable
3076
#endif
3077
3078
#ifdef HAVE_UNLINKAT
3079
121k
    #define UNLINKAT_DIR_FD_CONVERTER dir_fd_converter
3080
#else
3081
    #define UNLINKAT_DIR_FD_CONVERTER dir_fd_unavailable
3082
#endif
3083
3084
#ifdef HAVE_FCHDIR
3085
    #define PATH_HAVE_FCHDIR 1
3086
#else
3087
    #define PATH_HAVE_FCHDIR 0
3088
#endif
3089
3090
#ifdef HAVE_FCHMOD
3091
    #define PATH_HAVE_FCHMOD 1
3092
#else
3093
    #define PATH_HAVE_FCHMOD 0
3094
#endif
3095
3096
#ifdef HAVE_FCHOWN
3097
    #define PATH_HAVE_FCHOWN 1
3098
#else
3099
    #define PATH_HAVE_FCHOWN 0
3100
#endif
3101
3102
#ifdef HAVE_FDOPENDIR
3103
    #define PATH_HAVE_FDOPENDIR 1
3104
#else
3105
    #define PATH_HAVE_FDOPENDIR 0
3106
#endif
3107
3108
#ifdef HAVE_FEXECVE
3109
    #define PATH_HAVE_FEXECVE 1
3110
#else
3111
    #define PATH_HAVE_FEXECVE 0
3112
#endif
3113
3114
#ifdef HAVE_FPATHCONF
3115
    #define PATH_HAVE_FPATHCONF 1
3116
#else
3117
    #define PATH_HAVE_FPATHCONF 0
3118
#endif
3119
3120
#ifdef HAVE_FSTATVFS
3121
    #define PATH_HAVE_FSTATVFS 1
3122
#else
3123
    #define PATH_HAVE_FSTATVFS 0
3124
#endif
3125
3126
#ifdef HAVE_FTRUNCATE
3127
    #define PATH_HAVE_FTRUNCATE 1
3128
#else
3129
    #define PATH_HAVE_FTRUNCATE 0
3130
#endif
3131
/*[python end generated code: output=4bd4f6f7d41267f1 input=80b4c890b6774ea5]*/
3132
3133
#ifdef MS_WINDOWS
3134
    #undef PATH_HAVE_FTRUNCATE
3135
    #define PATH_HAVE_FTRUNCATE 1
3136
    #undef PATH_HAVE_FCHMOD
3137
    #define PATH_HAVE_FCHMOD 1
3138
#endif
3139
3140
/*[python input]
3141
3142
class path_t_converter(CConverter):
3143
3144
    type = "path_t"
3145
    impl_by_reference = True
3146
    parse_by_reference = True
3147
    default_type = ()
3148
    c_init_default = "<placeholder>"  # overridden in pre_render()
3149
3150
    converter = 'path_converter'
3151
3152
    def converter_init(self, *, allow_fd=False, make_wide=None,
3153
                       nonstrict=False, nullable=False,
3154
                       suppress_value_error=False):
3155
3156
        self.nullable = nullable
3157
        self.nonstrict = nonstrict
3158
        self.make_wide = make_wide
3159
        self.suppress_value_error = suppress_value_error
3160
        self.allow_fd = allow_fd
3161
        if nullable:
3162
            self.default_type = NoneType
3163
3164
    def pre_render(self):
3165
        def strify(value):
3166
            if isinstance(value, str):
3167
                return value
3168
            return str(int(bool(value)))
3169
3170
        # add self.py_name here when merging with posixmodule conversion
3171
        if self.make_wide is None:
3172
            self.c_default = 'PATH_T_INITIALIZE_P("{}", "{}", {}, {}, {}, {})'.format(
3173
                self.function.name,
3174
                self.name,
3175
                strify(self.nullable),
3176
                strify(self.nonstrict),
3177
                strify(self.suppress_value_error),
3178
                strify(self.allow_fd),
3179
            )
3180
        else:
3181
            self.c_default = 'PATH_T_INITIALIZE("{}", "{}", {}, {}, {}, {}, {})'.format(
3182
                self.function.name,
3183
                self.name,
3184
                strify(self.nullable),
3185
                strify(self.nonstrict),
3186
                strify(self.make_wide),
3187
                strify(self.suppress_value_error),
3188
                strify(self.allow_fd),
3189
            )
3190
3191
    def cleanup(self):
3192
        return "path_cleanup(&" + self.name + ");\n"
3193
3194
3195
class dir_fd_converter(CConverter):
3196
    type = 'int'
3197
    default_type = NoneType
3198
    c_init_default = 'DEFAULT_DIR_FD'
3199
3200
    def converter_init(self, requires=None):
3201
        if self.default in (unspecified, None):
3202
            self.c_default = 'DEFAULT_DIR_FD'
3203
        if isinstance(requires, str):
3204
            self.converter = requires.upper() + '_DIR_FD_CONVERTER'
3205
        else:
3206
            self.converter = 'dir_fd_converter'
3207
3208
    def c_default_init(self):
3209
        self.c_default = 'DEFAULT_DIR_FD'
3210
3211
class dev_t_converter(CConverter):
3212
    type = 'dev_t'
3213
    converter = '_Py_Dev_Converter'
3214
3215
class dev_t_return_converter(unsigned_long_return_converter):
3216
    type = 'dev_t'
3217
    conversion_fn = '_PyLong_FromDev'
3218
    unsigned_cast = '(dev_t)'
3219
3220
class idtype_t_converter(CConverter):
3221
    type = 'idtype_t'
3222
    converter = 'idtype_t_converter'
3223
3224
class id_t_converter(CConverter):
3225
    type = 'id_t'
3226
    format_unit = '" _Py_PARSE_PID "'
3227
3228
    def parse_arg(self, argname, displayname, *, limited_capi):
3229
        return self.format_code("""
3230
            {paramname} = (id_t)PyLong_AsPid({argname});
3231
            if ({paramname} == (id_t)(-1) && PyErr_Occurred()) {{{{
3232
                goto exit;
3233
            }}}}
3234
            """, argname=argname)
3235
3236
class intptr_t_converter(CConverter):
3237
    type = 'intptr_t'
3238
    format_unit = '" _Py_PARSE_INTPTR "'
3239
3240
    def parse_arg(self, argname, displayname, *, limited_capi):
3241
        return self.format_code("""
3242
            {paramname} = (intptr_t)PyLong_AsVoidPtr({argname});
3243
            if (!{paramname} && PyErr_Occurred()) {{{{
3244
                goto exit;
3245
            }}}}
3246
            """, argname=argname)
3247
3248
class Py_off_t_return_converter(long_return_converter):
3249
    type = 'Py_off_t'
3250
    conversion_fn = 'PyLong_FromPy_off_t'
3251
3252
class confname_converter(CConverter):
3253
    type="int"
3254
    converter="conv_confname"
3255
3256
    def converter_init(self, *, table):
3257
        self.table = table
3258
3259
    def parse_arg(self, argname, displayname, *, limited_capi):
3260
        return self.format_code("""
3261
            if (!{converter}(module, {argname}, &{paramname}, "{table}")) {{{{
3262
                goto exit;
3263
            }}}}
3264
        """, argname=argname, converter=self.converter, table=self.table)
3265
3266
[python start generated code]*/
3267
/*[python end generated code: output=da39a3ee5e6b4b0d input=7ceccf55bb600f61]*/
3268
3269
/*[clinic input]
3270
3271
os.stat
3272
3273
    path : path_t(allow_fd=True)
3274
        Path to be examined; can be string, bytes, a path-like object or
3275
        open-file-descriptor int.
3276
3277
    *
3278
3279
    dir_fd : dir_fd(requires='fstatat') = None
3280
        If not None, it should be a file descriptor open to a directory,
3281
        and path should be a relative string; path will then be relative to
3282
        that directory.
3283
3284
    follow_symlinks: bool = True
3285
        If False, and the last element of the path is a symbolic link,
3286
        stat will examine the symbolic link itself instead of the file
3287
        the link points to.
3288
3289
Perform a stat system call on the given path.
3290
3291
dir_fd and follow_symlinks may not be implemented
3292
  on your platform.  If they are unavailable, using them will raise a
3293
  NotImplementedError.
3294
3295
It's an error to use dir_fd or follow_symlinks when specifying path as
3296
  an open file descriptor.
3297
3298
[clinic start generated code]*/
3299
3300
static PyObject *
3301
os_stat_impl(PyObject *module, path_t *path, int dir_fd, int follow_symlinks)
3302
/*[clinic end generated code: output=7d4976e6f18a59c5 input=01d362ebcc06996b]*/
3303
207k
{
3304
207k
    return posix_do_stat(module, "stat", path, dir_fd, follow_symlinks);
3305
207k
}
3306
3307
3308
/*[clinic input]
3309
@permit_long_summary
3310
os.lstat
3311
3312
    path : path_t
3313
3314
    *
3315
3316
    dir_fd : dir_fd(requires='fstatat') = None
3317
3318
Perform a stat system call on the given path, without following symbolic links.
3319
3320
Like stat(), but do not follow symbolic links.
3321
Equivalent to stat(path, follow_symlinks=False).
3322
[clinic start generated code]*/
3323
3324
static PyObject *
3325
os_lstat_impl(PyObject *module, path_t *path, int dir_fd)
3326
/*[clinic end generated code: output=ef82a5d35ce8ab37 input=024102124f88e743]*/
3327
11.5k
{
3328
11.5k
    int follow_symlinks = 0;
3329
11.5k
    return posix_do_stat(module, "lstat", path, dir_fd, follow_symlinks);
3330
11.5k
}
3331
3332
3333
#ifdef HAVE_STATX
3334
typedef struct {
3335
    PyObject_HEAD
3336
    dev_t rdev, dev;
3337
    struct statx stx;
3338
} Py_statx_result;
3339
3340
0
#define Py_statx_result_CAST(op) _Py_CAST(Py_statx_result*, (op))
3341
3342
#define M(attr, type, offset, doc) \
3343
    {attr, type, offset, Py_READONLY, PyDoc_STR(doc)}
3344
#define MM(attr, type, member, doc) \
3345
    M(#attr, type, offsetof(Py_statx_result, stx.stx_##member), doc)
3346
#define MX(attr, type, member, doc) \
3347
    M(#attr, type, offsetof(Py_statx_result, member), doc)
3348
3349
static PyMemberDef pystatx_result_members[] = {
3350
    MM(stx_mask, Py_T_UINT, mask, "member validity mask"),
3351
    MM(stx_blksize, Py_T_UINT, blksize, "blocksize for filesystem I/O"),
3352
    MM(stx_attributes, Py_T_ULONGLONG, attributes, "Linux inode attribute bits"),
3353
    MM(stx_attributes_mask, Py_T_ULONGLONG, attributes_mask,
3354
        "Mask of supported bits in stx_attributes"),
3355
    MM(stx_rdev_major, Py_T_UINT, rdev_major, "represented device major number"),
3356
    MM(stx_rdev_minor, Py_T_UINT, rdev_minor, "represented device minor number"),
3357
    MX(stx_rdev, Py_T_ULONGLONG, rdev, "device type (if inode device)"),
3358
    MM(stx_dev_major, Py_T_UINT, dev_major, "containing device major number"),
3359
    MM(stx_dev_minor, Py_T_UINT, dev_minor, "containing device minor number"),
3360
    MX(stx_dev, Py_T_ULONGLONG, dev, "device"),
3361
    {NULL},
3362
};
3363
3364
#undef MX
3365
#undef MM
3366
#undef M
3367
3368
3369
#define STATX_GET_UINT(ATTR, MASK) \
3370
    static PyObject* \
3371
    pystatx_result_get_##ATTR(PyObject *op, void *Py_UNUSED(context)) \
3372
0
    { \
3373
0
        Py_statx_result *self = Py_statx_result_CAST(op); \
3374
0
        if (!(self->stx.stx_mask & MASK)) { \
3375
0
            Py_RETURN_NONE; \
3376
0
        } \
3377
0
        unsigned long value = self->stx.ATTR; \
3378
0
        return PyLong_FromUnsignedLong(value); \
3379
0
    }
Unexecuted instantiation: posixmodule.c:pystatx_result_get_stx_nlink
Unexecuted instantiation: posixmodule.c:pystatx_result_get_stx_uid
Unexecuted instantiation: posixmodule.c:pystatx_result_get_stx_gid
Unexecuted instantiation: posixmodule.c:pystatx_result_get_stx_dio_mem_align
Unexecuted instantiation: posixmodule.c:pystatx_result_get_stx_dio_offset_align
3380
3381
STATX_GET_UINT(stx_uid, STATX_UID)
3382
STATX_GET_UINT(stx_gid, STATX_GID)
3383
STATX_GET_UINT(stx_nlink, STATX_NLINK)
3384
#ifdef HAVE_STRUCT_STATX_STX_DIO_MEM_ALIGN
3385
STATX_GET_UINT(stx_dio_mem_align, STATX_DIOALIGN)
3386
STATX_GET_UINT(stx_dio_offset_align, STATX_DIOALIGN)
3387
#endif
3388
#ifdef HAVE_STRUCT_STATX_STX_DIO_READ_OFFSET_ALIGN
3389
STATX_GET_UINT(stx_dio_read_offset_align, STATX_DIO_READ_ALIGN)
3390
#endif
3391
#ifdef HAVE_STRUCT_STATX_STX_ATOMIC_WRITE_UNIT_MIN
3392
STATX_GET_UINT(stx_atomic_write_unit_min, STATX_WRITE_ATOMIC)
3393
STATX_GET_UINT(stx_atomic_write_unit_max, STATX_WRITE_ATOMIC)
3394
STATX_GET_UINT(stx_atomic_write_segments_max, STATX_WRITE_ATOMIC)
3395
#endif
3396
#ifdef HAVE_STRUCT_STATX_STX_ATOMIC_WRITE_UNIT_MAX_OPT
3397
STATX_GET_UINT(stx_atomic_write_unit_max_opt, STATX_WRITE_ATOMIC)
3398
#endif
3399
3400
3401
static PyObject*
3402
pystatx_result_get_stx_mode(PyObject *op, void *Py_UNUSED(context))
3403
0
{
3404
0
    Py_statx_result *self = Py_statx_result_CAST(op);
3405
0
    if (!(self->stx.stx_mask & (STATX_TYPE | STATX_MODE))) {
3406
0
        Py_RETURN_NONE;
3407
0
    }
3408
0
    return PyLong_FromUnsignedLong(self->stx.stx_mode);
3409
0
}
3410
3411
3412
#define STATX_GET_ULONGLONG(ATTR, MASK) \
3413
    static PyObject* \
3414
    pystatx_result_get_##ATTR(PyObject *op, void *Py_UNUSED(context)) \
3415
0
    { \
3416
0
        Py_statx_result *self = Py_statx_result_CAST(op); \
3417
0
        if (!(self->stx.stx_mask & MASK)) { \
3418
0
            Py_RETURN_NONE; \
3419
0
        } \
3420
0
        unsigned long long value = self->stx.ATTR; \
3421
0
        return PyLong_FromUnsignedLongLong(value); \
3422
0
    }
Unexecuted instantiation: posixmodule.c:pystatx_result_get_stx_ino
Unexecuted instantiation: posixmodule.c:pystatx_result_get_stx_size
Unexecuted instantiation: posixmodule.c:pystatx_result_get_stx_blocks
Unexecuted instantiation: posixmodule.c:pystatx_result_get_stx_mnt_id
3423
3424
STATX_GET_ULONGLONG(stx_blocks, STATX_BLOCKS)
3425
STATX_GET_ULONGLONG(stx_ino, STATX_INO)
3426
STATX_GET_ULONGLONG(stx_size, STATX_SIZE)
3427
#if defined(STATX_MNT_ID) && defined(HAVE_STRUCT_STATX_STX_MNT_ID)
3428
STATX_GET_ULONGLONG(stx_mnt_id, STATX_MNT_ID)
3429
#endif
3430
#if defined(STATX_SUBVOL) && defined(HAVE_STRUCT_STATX_STX_SUBVOL)
3431
STATX_GET_ULONGLONG(stx_subvol, STATX_SUBVOL)
3432
#endif
3433
3434
3435
#define STATX_GET_DOUBLE(ATTR, MASK) \
3436
    static PyObject* \
3437
    pystatx_result_get_##ATTR(PyObject *op, void *Py_UNUSED(context)) \
3438
0
    { \
3439
0
        Py_statx_result *self = Py_statx_result_CAST(op); \
3440
0
        if (!(self->stx.stx_mask & MASK)) { \
3441
0
            Py_RETURN_NONE; \
3442
0
        } \
3443
0
        struct statx_timestamp *ts = &self->stx.ATTR; \
3444
0
        double sec = ((double)ts->tv_sec + ts->tv_nsec * 1e-9); \
3445
0
        return PyFloat_FromDouble(sec); \
3446
0
    }
Unexecuted instantiation: posixmodule.c:pystatx_result_get_stx_atime
Unexecuted instantiation: posixmodule.c:pystatx_result_get_stx_btime
Unexecuted instantiation: posixmodule.c:pystatx_result_get_stx_ctime
Unexecuted instantiation: posixmodule.c:pystatx_result_get_stx_mtime
3447
3448
STATX_GET_DOUBLE(stx_atime, STATX_ATIME)
3449
STATX_GET_DOUBLE(stx_btime, STATX_BTIME)
3450
STATX_GET_DOUBLE(stx_ctime, STATX_CTIME)
3451
STATX_GET_DOUBLE(stx_mtime, STATX_MTIME)
3452
3453
#define STATX_GET_NSEC(ATTR, MEMBER, MASK) \
3454
    static PyObject* \
3455
    pystatx_result_get_##ATTR(PyObject *op, void *context) \
3456
0
    { \
3457
0
        Py_statx_result *self = Py_statx_result_CAST(op); \
3458
0
        if (!(self->stx.stx_mask & MASK)) { \
3459
0
            Py_RETURN_NONE; \
3460
0
        } \
3461
0
        struct statx_timestamp *ts = &self->stx.MEMBER; \
3462
0
        _posixstate *state = PyType_GetModuleState(Py_TYPE(op)); \
3463
0
        assert(state != NULL); \
3464
0
        return stat_nanosecond_timestamp(state, ts->tv_sec, ts->tv_nsec); \
3465
0
    }
3466
3467
0
STATX_GET_NSEC(stx_atime_ns, stx_atime, STATX_ATIME)
3468
0
STATX_GET_NSEC(stx_btime_ns, stx_btime, STATX_BTIME)
3469
0
STATX_GET_NSEC(stx_ctime_ns, stx_ctime, STATX_CTIME)
3470
0
STATX_GET_NSEC(stx_mtime_ns, stx_mtime, STATX_MTIME)
3471
3472
#define G(attr, doc) \
3473
    {#attr, pystatx_result_get_##attr, NULL, PyDoc_STR(doc), NULL}
3474
3475
static PyGetSetDef pystatx_result_getset[] = {
3476
    G(stx_mode, "protection bits"),
3477
    G(stx_nlink, "number of hard links"),
3478
    G(stx_uid, "user ID of owner"),
3479
    G(stx_gid, "group ID of owner"),
3480
    G(stx_ino, "inode"),
3481
    G(stx_size, "total size, in bytes"),
3482
    G(stx_blocks, "number of blocks allocated"),
3483
    G(stx_atime, "time of last access"),
3484
    G(stx_atime_ns, "time of last access in nanoseconds"),
3485
    G(stx_btime, "time of creation"),
3486
    G(stx_btime_ns, "time of creation in nanoseconds"),
3487
    G(stx_ctime, "time of last change"),
3488
    G(stx_ctime_ns, "time of last change in nanoseconds"),
3489
    G(stx_mtime, "time of last modification"),
3490
    G(stx_mtime_ns, "time of last modification in nanoseconds"),
3491
#if defined(STATX_MNT_ID) && defined(HAVE_STRUCT_STATX_STX_MNT_ID)
3492
    G(stx_mnt_id, "mount ID"),
3493
#endif
3494
#ifdef HAVE_STRUCT_STATX_STX_DIO_MEM_ALIGN
3495
    G(stx_dio_mem_align, "direct I/O memory buffer alignment"),
3496
    G(stx_dio_offset_align, "direct I/O file offset alignment"),
3497
#endif
3498
#if defined(STATX_SUBVOL) && defined(HAVE_STRUCT_STATX_STX_SUBVOL)
3499
    G(stx_subvol, "subvolume ID"),
3500
#endif
3501
#ifdef HAVE_STRUCT_STATX_STX_ATOMIC_WRITE_UNIT_MIN
3502
    G(stx_atomic_write_unit_min,
3503
      "minimum size for direct I/O with torn-write protection"),
3504
    G(stx_atomic_write_unit_max,
3505
        "maximum size for direct I/O with torn-write protection"),
3506
    G(stx_atomic_write_segments_max,
3507
        "maximum iovecs for direct I/O with torn-write protection"),
3508
#endif
3509
#ifdef HAVE_STRUCT_STATX_STX_DIO_READ_OFFSET_ALIGN
3510
    G(stx_dio_read_offset_align, "direct I/O file offset alignment for reads"),
3511
#endif
3512
#ifdef HAVE_STRUCT_STATX_STX_ATOMIC_WRITE_UNIT_MAX_OPT
3513
    G(stx_atomic_write_unit_max_opt,
3514
        "maximum optimized size for direct I/O with torn-write protection"),
3515
#endif
3516
    {NULL},
3517
};
3518
3519
#undef G
3520
3521
static PyObject *
3522
pystatx_result_repr(PyObject *op)
3523
0
{
3524
0
    PyUnicodeWriter *writer = PyUnicodeWriter_Create(0);
3525
0
    if (writer == NULL) {
3526
0
        return NULL;
3527
0
    }
3528
0
#define WRITE_ASCII(s) \
3529
0
    do { \
3530
0
        if (PyUnicodeWriter_WriteASCII(writer, s, strlen(s)) < 0) { \
3531
0
            goto error; \
3532
0
        } \
3533
0
    } while (0)
3534
3535
0
    WRITE_ASCII("os.statx_result(");
3536
3537
0
    for (size_t i = 0; i < Py_ARRAY_LENGTH(pystatx_result_members) - 1; ++i) {
3538
0
        if (i > 0) {
3539
0
            WRITE_ASCII(", ");
3540
0
        }
3541
3542
0
        PyMemberDef *d = &pystatx_result_members[i];
3543
0
        WRITE_ASCII(d->name);
3544
0
        WRITE_ASCII("=");
3545
3546
0
        PyObject *o = PyMember_GetOne((const char *)op, d);
3547
0
        if (o == NULL) {
3548
0
            goto error;
3549
0
        }
3550
0
        if (PyUnicodeWriter_WriteRepr(writer, o) < 0) {
3551
0
            Py_DECREF(o);
3552
0
            goto error;
3553
0
        }
3554
0
        Py_DECREF(o);
3555
0
    }
3556
3557
0
    for (size_t i = 0; i < Py_ARRAY_LENGTH(pystatx_result_getset) - 1; ++i) {
3558
0
        PyGetSetDef *d = &pystatx_result_getset[i];
3559
0
        PyObject *o = d->get(op, d->closure);
3560
0
        if (o == NULL) {
3561
0
            goto error;
3562
0
        }
3563
0
        if (o == Py_None) {
3564
0
            continue;
3565
0
        }
3566
3567
0
        WRITE_ASCII(", ");
3568
0
        WRITE_ASCII(d->name);
3569
0
        WRITE_ASCII("=");
3570
0
        if (PyUnicodeWriter_WriteRepr(writer, o) < 0) {
3571
0
            Py_DECREF(o);
3572
0
            goto error;
3573
0
        }
3574
0
        Py_DECREF(o);
3575
0
    }
3576
3577
0
    WRITE_ASCII(")");
3578
0
    return PyUnicodeWriter_Finish(writer);
3579
0
#undef WRITE_ASCII
3580
3581
0
error:
3582
0
    PyUnicodeWriter_Discard(writer);
3583
0
    return NULL;
3584
0
}
3585
3586
static int
3587
pystatx_result_traverse(PyObject *self, visitproc visit, void *arg)
3588
0
{
3589
0
    Py_VISIT(Py_TYPE(self));
3590
0
    return 0;
3591
0
}
3592
3593
static void
3594
pystatx_result_dealloc(PyObject *op)
3595
0
{
3596
0
    Py_statx_result *self = (Py_statx_result *) op;
3597
0
    PyTypeObject *tp = Py_TYPE(self);
3598
0
    PyObject_GC_UnTrack(self);
3599
0
    tp->tp_free(self);
3600
0
    Py_DECREF(tp);
3601
0
}
3602
3603
static PyType_Slot pystatx_result_slots[] = {
3604
    {Py_tp_repr, pystatx_result_repr},
3605
    {Py_tp_traverse, pystatx_result_traverse},
3606
    {Py_tp_dealloc, pystatx_result_dealloc},
3607
    {Py_tp_members, pystatx_result_members},
3608
    {Py_tp_getset, pystatx_result_getset},
3609
    {0, NULL},
3610
};
3611
3612
static PyType_Spec pystatx_result_spec = {
3613
    .name = "os.statx_result",
3614
    .basicsize = sizeof(Py_statx_result),
3615
    .flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE | Py_TPFLAGS_HAVE_GC |
3616
             Py_TPFLAGS_IMMUTABLETYPE | Py_TPFLAGS_DISALLOW_INSTANTIATION,
3617
    .slots = pystatx_result_slots,
3618
};
3619
3620
/*[clinic input]
3621
3622
os.statx
3623
3624
    path : path_t(allow_fd=True)
3625
        Path to be examined; can be string, bytes, a path-like object or
3626
        open-file-descriptor int.
3627
3628
    mask: unsigned_int(bitwise=True)
3629
        A bitmask of STATX_* constants defining the requested information.
3630
3631
    *
3632
3633
    flags: int = 0
3634
        A bitmask of AT_NO_AUTOMOUNT and/or AT_STATX_* flags.
3635
3636
    dir_fd : dir_fd = None
3637
        If not None, it should be a file descriptor open to a directory,
3638
        and path should be a relative string; path will then be relative to
3639
        that directory.
3640
3641
    follow_symlinks: bool = True
3642
        If False, and the last element of the path is a symbolic link,
3643
        statx will examine the symbolic link itself instead of the file
3644
        the link points to.
3645
3646
Perform a statx system call on the given path.
3647
3648
It's an error to use dir_fd or follow_symlinks when specifying path as
3649
  an open file descriptor.
3650
3651
[clinic start generated code]*/
3652
3653
static PyObject *
3654
os_statx_impl(PyObject *module, path_t *path, unsigned int mask, int flags,
3655
              int dir_fd, int follow_symlinks)
3656
/*[clinic end generated code: output=e3765979ac6fe15b input=f0116380c5dc4f2f]*/
3657
0
{
3658
0
    if (path_and_dir_fd_invalid("statx", path, dir_fd) ||
3659
0
        dir_fd_and_fd_invalid("statx", dir_fd, path->fd) ||
3660
0
        fd_and_follow_symlinks_invalid("statx", path->is_fd, follow_symlinks)) {
3661
0
        return NULL;
3662
0
    }
3663
3664
    /* reject flags covered by kwargs, but allow unknown flags that may be
3665
       future AT_STATX_* extensions */
3666
0
    if (flags & (AT_SYMLINK_NOFOLLOW | AT_SYMLINK_FOLLOW)) {
3667
0
        PyErr_Format(PyExc_ValueError,
3668
0
                     "use follow_symlinks kwarg instead of AT_SYMLINK_* flag");
3669
0
        return NULL;
3670
0
    }
3671
0
    if (flags & AT_EMPTY_PATH) {
3672
0
        PyErr_Format(PyExc_ValueError,
3673
0
                     "use dir_fd kwarg instead of AT_EMPTY_PATH flag");
3674
0
        return NULL;
3675
0
    }
3676
0
    if (!follow_symlinks) {
3677
0
        flags |= AT_SYMLINK_NOFOLLOW;
3678
0
    }
3679
3680
    /* Future bits may refer to members beyond the current size of struct
3681
       statx, so we need to mask them off to prevent memory corruption. */
3682
0
    mask &= _Py_STATX_KNOWN;
3683
3684
0
    _posixstate *state = get_posix_state(module);
3685
0
    PyTypeObject *tp = (PyTypeObject *)state->StatxResultType;
3686
0
    Py_statx_result *v = (Py_statx_result *)tp->tp_alloc(tp, 0);
3687
0
    if (v == NULL) {
3688
0
        return NULL;
3689
0
    }
3690
3691
0
    int result;
3692
0
    Py_BEGIN_ALLOW_THREADS
3693
0
    if (path->is_fd) {
3694
0
        result = statx(path->fd, "", flags | AT_EMPTY_PATH, mask, &v->stx);
3695
0
    }
3696
0
    else {
3697
0
        result = statx(dir_fd, path->narrow, flags, mask, &v->stx);
3698
0
    }
3699
0
    Py_END_ALLOW_THREADS
3700
3701
0
    if (result != 0) {
3702
0
        Py_DECREF(v);
3703
0
        return path_error(path);
3704
0
    }
3705
3706
0
    v->rdev = makedev(v->stx.stx_rdev_major, v->stx.stx_rdev_minor);
3707
0
    v->dev = makedev(v->stx.stx_dev_major, v->stx.stx_dev_minor);
3708
3709
0
    assert(!PyErr_Occurred());
3710
0
    return (PyObject *)v;
3711
0
}
3712
#endif /* HAVE_STATX */
3713
3714
3715
/*[clinic input]
3716
os.access -> bool
3717
3718
    path: path_t
3719
        Path to be tested; can be string, bytes, or a path-like object.
3720
3721
    mode: int
3722
        Operating-system mode bitfield.  Can be F_OK to test existence,
3723
        or the inclusive-OR of R_OK, W_OK, and X_OK.
3724
3725
    *
3726
3727
    dir_fd : dir_fd(requires='faccessat') = None
3728
        If not None, it should be a file descriptor open to a directory,
3729
        and path should be relative; path will then be relative to that
3730
        directory.
3731
3732
    effective_ids: bool = False
3733
        If True, access will use the effective uid/gid instead of
3734
        the real uid/gid.
3735
3736
    follow_symlinks: bool = True
3737
        If False, and the last element of the path is a symbolic link,
3738
        access will examine the symbolic link itself instead of the file
3739
        the link points to.
3740
3741
Use the real uid/gid to test for access to a path.
3742
3743
{parameters}
3744
dir_fd, effective_ids, and follow_symlinks may not be implemented
3745
  on your platform.  If they are unavailable, using them will raise a
3746
  NotImplementedError.
3747
3748
Note that most operations will use the effective uid/gid, therefore this
3749
  routine can be used in a suid/sgid environment to test if the invoking
3750
  user has the specified access to the path.
3751
3752
[clinic start generated code]*/
3753
3754
static int
3755
os_access_impl(PyObject *module, path_t *path, int mode, int dir_fd,
3756
               int effective_ids, int follow_symlinks)
3757
/*[clinic end generated code: output=cf84158bc90b1a77 input=c33565f7584b99e4]*/
3758
0
{
3759
0
    int return_value;
3760
3761
#ifdef MS_WINDOWS
3762
    DWORD attr;
3763
#else
3764
0
    int result;
3765
0
#endif
3766
3767
0
#ifdef HAVE_FACCESSAT
3768
0
    int faccessat_unavailable = 0;
3769
0
#endif
3770
3771
#ifndef HAVE_FACCESSAT
3772
    if (follow_symlinks_specified("access", follow_symlinks))
3773
        return -1;
3774
3775
    if (effective_ids) {
3776
        argument_unavailable_error("access", "effective_ids");
3777
        return -1;
3778
    }
3779
#endif
3780
3781
#ifdef MS_WINDOWS
3782
    Py_BEGIN_ALLOW_THREADS
3783
    attr = GetFileAttributesW(path->wide);
3784
    Py_END_ALLOW_THREADS
3785
3786
    /*
3787
     * Access is possible if
3788
     *   * we didn't get a -1, and
3789
     *     * write access wasn't requested,
3790
     *     * or the file isn't read-only,
3791
     *     * or it's a directory.
3792
     * (Directories cannot be read-only on Windows.)
3793
    */
3794
    return_value = (attr != INVALID_FILE_ATTRIBUTES) &&
3795
            (!(mode & 2) ||
3796
            !(attr & FILE_ATTRIBUTE_READONLY) ||
3797
            (attr & FILE_ATTRIBUTE_DIRECTORY));
3798
#else
3799
3800
0
    Py_BEGIN_ALLOW_THREADS
3801
0
#ifdef HAVE_FACCESSAT
3802
0
    if ((dir_fd != DEFAULT_DIR_FD) ||
3803
0
        effective_ids ||
3804
0
        !follow_symlinks) {
3805
3806
0
        if (HAVE_FACCESSAT_RUNTIME) {
3807
0
            int flags = 0;
3808
0
            if (!follow_symlinks)
3809
0
                flags |= AT_SYMLINK_NOFOLLOW;
3810
0
            if (effective_ids)
3811
0
                flags |= AT_EACCESS;
3812
0
            result = faccessat(dir_fd, path->narrow, mode, flags);
3813
0
        } else {
3814
0
            faccessat_unavailable = 1;
3815
0
        }
3816
0
    }
3817
0
    else
3818
0
#endif
3819
0
        result = access(path->narrow, mode);
3820
0
    Py_END_ALLOW_THREADS
3821
3822
0
#ifdef HAVE_FACCESSAT
3823
0
    if (faccessat_unavailable) {
3824
0
        if (dir_fd != DEFAULT_DIR_FD) {
3825
0
            argument_unavailable_error("access", "dir_fd");
3826
0
            return -1;
3827
0
        }
3828
0
        if (follow_symlinks_specified("access", follow_symlinks))
3829
0
            return -1;
3830
3831
0
        if (effective_ids) {
3832
0
            argument_unavailable_error("access", "effective_ids");
3833
0
            return -1;
3834
0
        }
3835
        /* should be unreachable */
3836
0
        return -1;
3837
0
    }
3838
0
#endif
3839
0
    return_value = !result;
3840
0
#endif
3841
3842
0
    return return_value;
3843
0
}
3844
3845
#ifndef F_OK
3846
#define F_OK 0
3847
#endif
3848
#ifndef R_OK
3849
#define R_OK 4
3850
#endif
3851
#ifndef W_OK
3852
#define W_OK 2
3853
#endif
3854
#ifndef X_OK
3855
#define X_OK 1
3856
#endif
3857
3858
3859
#ifdef HAVE_TTYNAME_R
3860
/*[clinic input]
3861
os.ttyname
3862
3863
    fd: int
3864
        Integer file descriptor handle.
3865
3866
    /
3867
3868
Return the name of the terminal device connected to 'fd'.
3869
[clinic start generated code]*/
3870
3871
static PyObject *
3872
os_ttyname_impl(PyObject *module, int fd)
3873
/*[clinic end generated code: output=c424d2e9d1cd636a input=9ff5a58b08115c55]*/
3874
0
{
3875
3876
0
    long size = sysconf(_SC_TTY_NAME_MAX);
3877
0
    if (size == -1) {
3878
0
        return posix_error();
3879
0
    }
3880
0
    char *buffer = (char *)PyMem_RawMalloc(size);
3881
0
    if (buffer == NULL) {
3882
0
        return PyErr_NoMemory();
3883
0
    }
3884
0
    int ret = ttyname_r(fd, buffer, size);
3885
0
    if (ret != 0) {
3886
0
        PyMem_RawFree(buffer);
3887
0
        errno = ret;
3888
0
        return posix_error();
3889
0
    }
3890
0
    PyObject *res = PyUnicode_DecodeFSDefault(buffer);
3891
0
    PyMem_RawFree(buffer);
3892
0
    return res;
3893
0
}
3894
#endif
3895
3896
#ifdef HAVE_CTERMID
3897
/*[clinic input]
3898
os.ctermid
3899
3900
Return the name of the controlling terminal for this process.
3901
[clinic start generated code]*/
3902
3903
static PyObject *
3904
os_ctermid_impl(PyObject *module)
3905
/*[clinic end generated code: output=02f017e6c9e620db input=3b87fdd52556382d]*/
3906
0
{
3907
0
    char *ret;
3908
0
    char buffer[L_ctermid];
3909
3910
#ifdef USE_CTERMID_R
3911
    ret = ctermid_r(buffer);
3912
#else
3913
0
    ret = ctermid(buffer);
3914
0
#endif
3915
0
    if (ret == NULL)
3916
0
        return posix_error();
3917
0
    return PyUnicode_DecodeFSDefault(buffer);
3918
0
}
3919
#endif /* HAVE_CTERMID */
3920
3921
3922
/*[clinic input]
3923
os.chdir
3924
3925
    path: path_t(allow_fd='PATH_HAVE_FCHDIR')
3926
3927
Change the current working directory to the specified path.
3928
3929
path may always be specified as a string.  On some platforms, path may
3930
also be specified as an open file descriptor.  If this functionality is
3931
unavailable, using it raises an exception.
3932
[clinic start generated code]*/
3933
3934
static PyObject *
3935
os_chdir_impl(PyObject *module, path_t *path)
3936
/*[clinic end generated code: output=3be6400eee26eaae input=64673c342e4369f1]*/
3937
0
{
3938
0
    int result;
3939
3940
0
    if (PySys_Audit("os.chdir", "(O)", path->object) < 0) {
3941
0
        return NULL;
3942
0
    }
3943
3944
0
    Py_BEGIN_ALLOW_THREADS
3945
#ifdef MS_WINDOWS
3946
    /* on unix, success = 0, on windows, success = !0 */
3947
    result = !win32_wchdir(path->wide);
3948
#else
3949
0
#ifdef HAVE_FCHDIR
3950
0
    if (path->is_fd)
3951
0
        result = fchdir(path->fd);
3952
0
    else
3953
0
#endif
3954
0
        result = chdir(path->narrow);
3955
0
#endif
3956
0
    Py_END_ALLOW_THREADS
3957
3958
0
    if (result) {
3959
0
        return path_error(path);
3960
0
    }
3961
3962
0
    Py_RETURN_NONE;
3963
0
}
3964
3965
3966
#ifdef HAVE_FCHDIR
3967
/*[clinic input]
3968
os.fchdir
3969
3970
    fd: fildes
3971
3972
Change to the directory of the given file descriptor.
3973
3974
fd must be opened on a directory, not a file.
3975
Equivalent to os.chdir(fd).
3976
3977
[clinic start generated code]*/
3978
3979
static PyObject *
3980
os_fchdir_impl(PyObject *module, int fd)
3981
/*[clinic end generated code: output=42e064ec4dc00ab0 input=18e816479a2fa985]*/
3982
0
{
3983
0
    if (PySys_Audit("os.chdir", "(i)", fd) < 0) {
3984
0
        return NULL;
3985
0
    }
3986
0
    return posix_fildes_fd(fd, fchdir);
3987
0
}
3988
#endif /* HAVE_FCHDIR */
3989
3990
#ifdef MS_WINDOWS
3991
# define CHMOD_DEFAULT_FOLLOW_SYMLINKS 0
3992
#else
3993
0
# define CHMOD_DEFAULT_FOLLOW_SYMLINKS 1
3994
#endif
3995
3996
#ifdef MS_WINDOWS
3997
static int
3998
win32_lchmod(LPCWSTR path, int mode)
3999
{
4000
    DWORD attr = GetFileAttributesW(path);
4001
    if (attr == INVALID_FILE_ATTRIBUTES) {
4002
        return 0;
4003
    }
4004
    if (mode & _S_IWRITE) {
4005
        attr &= ~FILE_ATTRIBUTE_READONLY;
4006
    }
4007
    else {
4008
        attr |= FILE_ATTRIBUTE_READONLY;
4009
    }
4010
    return SetFileAttributesW(path, attr);
4011
}
4012
4013
static int
4014
win32_hchmod(HANDLE hfile, int mode)
4015
{
4016
    FILE_BASIC_INFO info;
4017
    if (!GetFileInformationByHandleEx(hfile, FileBasicInfo,
4018
                                      &info, sizeof(info)))
4019
    {
4020
        return 0;
4021
    }
4022
    if (mode & _S_IWRITE) {
4023
        info.FileAttributes &= ~FILE_ATTRIBUTE_READONLY;
4024
        if (info.FileAttributes == 0) {
4025
            /* SetFileInformationByHandle() interprets FileAttributes == 0
4026
               as "leave the attributes unchanged"; FILE_ATTRIBUTE_NORMAL
4027
               is the documented way to clear all attributes. */
4028
            info.FileAttributes = FILE_ATTRIBUTE_NORMAL;
4029
        }
4030
    }
4031
    else {
4032
        info.FileAttributes |= FILE_ATTRIBUTE_READONLY;
4033
    }
4034
    return SetFileInformationByHandle(hfile, FileBasicInfo,
4035
                                      &info, sizeof(info));
4036
}
4037
4038
static int
4039
win32_fchmod(int fd, int mode)
4040
{
4041
    HANDLE hfile = _Py_get_osfhandle_noraise(fd);
4042
    if (hfile == INVALID_HANDLE_VALUE) {
4043
        SetLastError(ERROR_INVALID_HANDLE);
4044
        return 0;
4045
    }
4046
    return win32_hchmod(hfile, mode);
4047
}
4048
4049
#endif /* MS_WINDOWS */
4050
4051
/*[clinic input]
4052
os.chmod
4053
4054
    path: path_t(allow_fd='PATH_HAVE_FCHMOD')
4055
        Path to be modified.  May always be specified as a str, bytes, or
4056
        a path-like object.  On some platforms, path may also be specified
4057
        as an open file descriptor.  If this functionality is unavailable,
4058
        using it raises an exception.
4059
4060
    mode: int
4061
        Operating-system mode bitfield.
4062
        Be careful when using number literals for *mode*. The conventional
4063
        UNIX notation for numeric modes uses an octal base, which needs to
4064
        be indicated with a ``0o`` prefix in Python.
4065
4066
    *
4067
4068
    dir_fd : dir_fd(requires='fchmodat') = None
4069
        If not None, it should be a file descriptor open to a directory,
4070
        and path should be relative; path will then be relative to that
4071
        directory.
4072
4073
    follow_symlinks: bool(c_default="CHMOD_DEFAULT_FOLLOW_SYMLINKS", \
4074
                          py_default="(os.name != 'nt')") = CHMOD_DEFAULT_FOLLOW_SYMLINKS
4075
        If False, and the last element of the path is a symbolic link,
4076
        chmod will modify the symbolic link itself instead of the file
4077
        the link points to.
4078
4079
Change the access permissions of a file.
4080
4081
It is an error to use dir_fd or follow_symlinks when specifying path as
4082
  an open file descriptor.
4083
dir_fd and follow_symlinks may not be implemented on your platform.
4084
  If they are unavailable, using them will raise a NotImplementedError.
4085
4086
[clinic start generated code]*/
4087
4088
static PyObject *
4089
os_chmod_impl(PyObject *module, path_t *path, int mode, int dir_fd,
4090
              int follow_symlinks)
4091
/*[clinic end generated code: output=5cf6a94915cc7bff input=7b6e2eeadd8bf199]*/
4092
0
{
4093
0
    int result;
4094
4095
0
#ifdef HAVE_FCHMODAT
4096
0
    int fchmodat_nofollow_unsupported = 0;
4097
0
    int fchmodat_unsupported = 0;
4098
0
#endif
4099
4100
#if !(defined(HAVE_FCHMODAT) || defined(HAVE_LCHMOD) || defined(MS_WINDOWS))
4101
    if (follow_symlinks_specified("chmod", follow_symlinks))
4102
        return NULL;
4103
#endif
4104
4105
0
    if (PySys_Audit("os.chmod", "Oii", path->object, mode,
4106
0
                    dir_fd == DEFAULT_DIR_FD ? -1 : dir_fd) < 0) {
4107
0
        return NULL;
4108
0
    }
4109
4110
#ifdef MS_WINDOWS
4111
    result = 0;
4112
    Py_BEGIN_ALLOW_THREADS
4113
    if (path->is_fd) {
4114
        result = win32_fchmod(path->fd, mode);
4115
    }
4116
    else if (follow_symlinks) {
4117
        HANDLE hfile = CreateFileW(path->wide,
4118
                                   FILE_READ_ATTRIBUTES|FILE_WRITE_ATTRIBUTES,
4119
                                   0, NULL,
4120
                                   OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
4121
        if (hfile != INVALID_HANDLE_VALUE) {
4122
            result = win32_hchmod(hfile, mode);
4123
            (void)CloseHandle(hfile);
4124
        }
4125
    }
4126
    else {
4127
        result = win32_lchmod(path->wide, mode);
4128
    }
4129
    Py_END_ALLOW_THREADS
4130
    if (!result) {
4131
        return path_error(path);
4132
    }
4133
#else /* MS_WINDOWS */
4134
0
    Py_BEGIN_ALLOW_THREADS
4135
0
#ifdef HAVE_FCHMOD
4136
0
    if (path->is_fd) {
4137
0
        result = fchmod(path->fd, mode);
4138
0
    }
4139
0
    else
4140
0
#endif /* HAVE_CHMOD */
4141
#ifdef HAVE_LCHMOD
4142
    if ((!follow_symlinks) && (dir_fd == DEFAULT_DIR_FD))
4143
        result = lchmod(path->narrow, mode);
4144
    else
4145
#endif /* HAVE_LCHMOD */
4146
0
#ifdef HAVE_FCHMODAT
4147
0
    if ((dir_fd != DEFAULT_DIR_FD) || !follow_symlinks) {
4148
0
        if (HAVE_FCHMODAT_RUNTIME) {
4149
            /*
4150
             * fchmodat() doesn't currently support AT_SYMLINK_NOFOLLOW!
4151
             * The documentation specifically shows how to use it,
4152
             * and then says it isn't implemented yet.
4153
             * (true on linux with glibc 2.15, and openindiana 3.x)
4154
             *
4155
             * Once it is supported, os.chmod will automatically
4156
             * support dir_fd and follow_symlinks=False.  (Hopefully.)
4157
             * Until then, we need to be careful what exception we raise.
4158
             */
4159
0
            result = fchmodat(dir_fd, path->narrow, mode,
4160
0
                              follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW);
4161
            /*
4162
             * But wait!  We can't throw the exception without allowing threads,
4163
             * and we can't do that in this nested scope.  (Macro trickery, sigh.)
4164
             */
4165
0
            fchmodat_nofollow_unsupported =
4166
0
                             result &&
4167
0
                             ((errno == ENOTSUP) || (errno == EOPNOTSUPP)) &&
4168
0
                             !follow_symlinks;
4169
0
        } else {
4170
0
            fchmodat_unsupported = 1;
4171
0
            fchmodat_nofollow_unsupported = 1;
4172
4173
0
            result = -1;
4174
0
        }
4175
0
    }
4176
0
    else
4177
0
#endif /* HAVE_FHCMODAT */
4178
0
    {
4179
0
#ifdef HAVE_CHMOD
4180
0
        result = chmod(path->narrow, mode);
4181
#elif defined(__wasi__)
4182
        // WASI SDK 15.0 does not support chmod.
4183
        // Ignore missing syscall for now.
4184
        result = 0;
4185
#else
4186
        result = -1;
4187
        errno = ENOSYS;
4188
#endif
4189
0
    }
4190
0
    Py_END_ALLOW_THREADS
4191
4192
0
    if (result) {
4193
0
#ifdef HAVE_FCHMODAT
4194
0
        if (fchmodat_unsupported) {
4195
0
            if (dir_fd != DEFAULT_DIR_FD) {
4196
0
                argument_unavailable_error("chmod", "dir_fd");
4197
0
                return NULL;
4198
0
            }
4199
0
        }
4200
4201
0
        if (fchmodat_nofollow_unsupported) {
4202
0
            if (dir_fd != DEFAULT_DIR_FD)
4203
0
                dir_fd_and_follow_symlinks_invalid("chmod",
4204
0
                                                   dir_fd, follow_symlinks);
4205
0
            else
4206
0
                follow_symlinks_specified("chmod", follow_symlinks);
4207
0
            return NULL;
4208
0
        }
4209
0
        else
4210
0
#endif /* HAVE_FCHMODAT */
4211
0
        return path_error(path);
4212
0
    }
4213
0
#endif /* MS_WINDOWS */
4214
4215
0
    Py_RETURN_NONE;
4216
0
}
4217
4218
4219
#if defined(HAVE_FCHMOD) || defined(MS_WINDOWS)
4220
/*[clinic input]
4221
os.fchmod
4222
4223
    fd: int
4224
        The file descriptor of the file to be modified.
4225
    mode: int
4226
        Operating-system mode bitfield.
4227
        Be careful when using number literals for *mode*.  The conventional
4228
        UNIX notation for numeric modes uses an octal base, which needs to
4229
        be indicated with a ``0o`` prefix in Python.
4230
4231
Change the access permissions of the file given by file descriptor fd.
4232
4233
Equivalent to os.chmod(fd, mode).
4234
[clinic start generated code]*/
4235
4236
static PyObject *
4237
os_fchmod_impl(PyObject *module, int fd, int mode)
4238
/*[clinic end generated code: output=afd9bc05b4e426b3 input=d24331f9fdc17f49]*/
4239
0
{
4240
0
    int res;
4241
4242
0
    if (PySys_Audit("os.chmod", "iii", fd, mode, -1) < 0) {
4243
0
        return NULL;
4244
0
    }
4245
4246
#ifdef MS_WINDOWS
4247
    res = 0;
4248
    Py_BEGIN_ALLOW_THREADS
4249
    res = win32_fchmod(fd, mode);
4250
    Py_END_ALLOW_THREADS
4251
    if (!res) {
4252
        return PyErr_SetFromWindowsErr(0);
4253
    }
4254
#else /* MS_WINDOWS */
4255
0
    int async_err = 0;
4256
0
    do {
4257
0
        Py_BEGIN_ALLOW_THREADS
4258
0
        res = fchmod(fd, mode);
4259
0
        Py_END_ALLOW_THREADS
4260
0
    } while (res != 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
4261
0
    if (res != 0)
4262
0
        return (!async_err) ? posix_error() : NULL;
4263
0
#endif /* MS_WINDOWS */
4264
4265
0
    Py_RETURN_NONE;
4266
0
}
4267
#endif /* HAVE_FCHMOD || MS_WINDOWS */
4268
4269
4270
#if defined(HAVE_LCHMOD) || defined(MS_WINDOWS)
4271
/*[clinic input]
4272
@permit_long_summary
4273
os.lchmod
4274
4275
    path: path_t
4276
    mode: int
4277
4278
Change the access permissions of a file, without following symbolic links.
4279
4280
If path is a symlink, this affects the link itself rather than the
4281
target.  Equivalent to chmod(path, mode, follow_symlinks=False).
4282
[clinic start generated code]*/
4283
4284
static PyObject *
4285
os_lchmod_impl(PyObject *module, path_t *path, int mode)
4286
/*[clinic end generated code: output=082344022b51a1d5 input=13110fb62911b015]*/
4287
{
4288
    int res;
4289
    if (PySys_Audit("os.chmod", "Oii", path->object, mode, -1) < 0) {
4290
        return NULL;
4291
    }
4292
#ifdef MS_WINDOWS
4293
    Py_BEGIN_ALLOW_THREADS
4294
    res = win32_lchmod(path->wide, mode);
4295
    Py_END_ALLOW_THREADS
4296
    if (!res) {
4297
        path_error(path);
4298
        return NULL;
4299
    }
4300
#else /* MS_WINDOWS */
4301
    Py_BEGIN_ALLOW_THREADS
4302
    res = lchmod(path->narrow, mode);
4303
    Py_END_ALLOW_THREADS
4304
    if (res < 0) {
4305
        path_error(path);
4306
        return NULL;
4307
    }
4308
#endif /* MS_WINDOWS */
4309
    Py_RETURN_NONE;
4310
}
4311
#endif /* HAVE_LCHMOD || MS_WINDOWS */
4312
4313
4314
#ifdef HAVE_CHFLAGS
4315
/*[clinic input]
4316
os.chflags
4317
4318
    path: path_t
4319
    flags: unsigned_long(bitwise=True)
4320
    follow_symlinks: bool=True
4321
4322
Set file flags.
4323
4324
If follow_symlinks is False, and the last element of the path is
4325
a symbolic link, chflags() will change flags on the symbolic link itself
4326
instead of the file the link points to.
4327
follow_symlinks may not be implemented on your platform.  If it is
4328
unavailable, using it will raise a NotImplementedError.
4329
4330
[clinic start generated code]*/
4331
4332
static PyObject *
4333
os_chflags_impl(PyObject *module, path_t *path, unsigned long flags,
4334
                int follow_symlinks)
4335
/*[clinic end generated code: output=85571c6737661ce9 input=31391927707be1de]*/
4336
{
4337
    int result;
4338
4339
#ifndef HAVE_LCHFLAGS
4340
    if (follow_symlinks_specified("chflags", follow_symlinks))
4341
        return NULL;
4342
#endif
4343
4344
    if (PySys_Audit("os.chflags", "Ok", path->object, flags) < 0) {
4345
        return NULL;
4346
    }
4347
4348
    Py_BEGIN_ALLOW_THREADS
4349
#ifdef HAVE_LCHFLAGS
4350
    if (!follow_symlinks)
4351
        result = lchflags(path->narrow, flags);
4352
    else
4353
#endif
4354
        result = chflags(path->narrow, flags);
4355
    Py_END_ALLOW_THREADS
4356
4357
    if (result)
4358
        return path_error(path);
4359
4360
    Py_RETURN_NONE;
4361
}
4362
#endif /* HAVE_CHFLAGS */
4363
4364
4365
#ifdef HAVE_LCHFLAGS
4366
/*[clinic input]
4367
os.lchflags
4368
4369
    path: path_t
4370
    flags: unsigned_long(bitwise=True)
4371
4372
Set file flags.
4373
4374
This function will not follow symbolic links.
4375
Equivalent to chflags(path, flags, follow_symlinks=False).
4376
[clinic start generated code]*/
4377
4378
static PyObject *
4379
os_lchflags_impl(PyObject *module, path_t *path, unsigned long flags)
4380
/*[clinic end generated code: output=30ae958695c07316 input=f9f82ea8b585ca9d]*/
4381
{
4382
    int res;
4383
    if (PySys_Audit("os.chflags", "Ok", path->object, flags) < 0) {
4384
        return NULL;
4385
    }
4386
    Py_BEGIN_ALLOW_THREADS
4387
    res = lchflags(path->narrow, flags);
4388
    Py_END_ALLOW_THREADS
4389
    if (res < 0) {
4390
        return path_error(path);
4391
    }
4392
    Py_RETURN_NONE;
4393
}
4394
#endif /* HAVE_LCHFLAGS */
4395
4396
4397
#ifdef HAVE_CHROOT
4398
/*[clinic input]
4399
os.chroot
4400
    path: path_t
4401
4402
Change root directory to path.
4403
4404
[clinic start generated code]*/
4405
4406
static PyObject *
4407
os_chroot_impl(PyObject *module, path_t *path)
4408
/*[clinic end generated code: output=de80befc763a4475 input=14822965652c3dc3]*/
4409
0
{
4410
#ifdef __ANDROID__
4411
    // On Android, calling this function as a non-root user leads to a process crash
4412
    // rather than returning a permission error.
4413
    if (getuid() != 0) {
4414
        errno = EPERM;
4415
        return path_error(path);
4416
    }
4417
#endif
4418
0
    int res;
4419
0
    Py_BEGIN_ALLOW_THREADS
4420
0
    res = chroot(path->narrow);
4421
0
    Py_END_ALLOW_THREADS
4422
0
    if (res < 0)
4423
0
        return path_error(path);
4424
0
    Py_RETURN_NONE;
4425
0
}
4426
#endif /* HAVE_CHROOT */
4427
4428
4429
#ifdef HAVE_FSYNC
4430
/*[clinic input]
4431
os.fsync
4432
4433
    fd: fildes
4434
4435
Force write of fd to disk.
4436
[clinic start generated code]*/
4437
4438
static PyObject *
4439
os_fsync_impl(PyObject *module, int fd)
4440
/*[clinic end generated code: output=4a10d773f52b3584 input=21c3645c056967f2]*/
4441
0
{
4442
0
    return posix_fildes_fd(fd, fsync);
4443
0
}
4444
#endif /* HAVE_FSYNC */
4445
4446
4447
#ifdef HAVE_SYNC
4448
/*[clinic input]
4449
os.sync
4450
4451
Force write of everything to disk.
4452
[clinic start generated code]*/
4453
4454
static PyObject *
4455
os_sync_impl(PyObject *module)
4456
/*[clinic end generated code: output=2796b1f0818cd71c input=84749fe5e9b404ff]*/
4457
0
{
4458
0
    Py_BEGIN_ALLOW_THREADS
4459
0
    sync();
4460
0
    Py_END_ALLOW_THREADS
4461
0
    Py_RETURN_NONE;
4462
0
}
4463
#endif /* HAVE_SYNC */
4464
4465
4466
#ifdef HAVE_FDATASYNC
4467
#ifdef __hpux
4468
extern int fdatasync(int); /* On HP-UX, in libc but not in unistd.h */
4469
#endif
4470
4471
/*[clinic input]
4472
os.fdatasync
4473
4474
    fd: fildes
4475
4476
Force write of fd to disk without forcing update of metadata.
4477
[clinic start generated code]*/
4478
4479
static PyObject *
4480
os_fdatasync_impl(PyObject *module, int fd)
4481
/*[clinic end generated code: output=b4b9698b5d7e26dd input=bc74791ee54dd291]*/
4482
0
{
4483
0
    return posix_fildes_fd(fd, fdatasync);
4484
0
}
4485
#endif /* HAVE_FDATASYNC */
4486
4487
4488
#ifdef HAVE_CHOWN
4489
/*[clinic input]
4490
os.chown
4491
4492
    path : path_t(allow_fd='PATH_HAVE_FCHOWN')
4493
        Path to be examined; can be string, bytes, a path-like object, or
4494
        open-file-descriptor int.
4495
4496
    uid: uid_t
4497
4498
    gid: gid_t
4499
4500
    *
4501
4502
    dir_fd: dir_fd(requires='fchownat') = None
4503
        If not None, it should be a file descriptor open to a directory,
4504
        and path should be relative; path will then be relative to that
4505
        directory.
4506
4507
    follow_symlinks: bool = True
4508
        If False, and the last element of the path is a symbolic link,
4509
        stat will examine the symbolic link itself instead of the file
4510
        the link points to.
4511
4512
Change the owner and group id of path to the numeric uid and gid.
4513
4514
path may always be specified as a string.  On some platforms, path may
4515
also be specified as an open file descriptor.  If this functionality is
4516
unavailable, using it raises an exception.
4517
If dir_fd is not None, it should be a file descriptor open to
4518
a directory, and path should be relative; path will then be relative to
4519
that directory.
4520
If follow_symlinks is False, and the last element of the path is
4521
a symbolic link, chown will modify the symbolic link itself instead of
4522
the file the link points to.
4523
It is an error to use dir_fd or follow_symlinks when specifying path as
4524
an open file descriptor.
4525
dir_fd and follow_symlinks may not be implemented on your platform.  If
4526
they are unavailable, using them will raise a NotImplementedError.
4527
4528
[clinic start generated code]*/
4529
4530
static PyObject *
4531
os_chown_impl(PyObject *module, path_t *path, uid_t uid, gid_t gid,
4532
              int dir_fd, int follow_symlinks)
4533
/*[clinic end generated code: output=4beadab0db5f70cd input=509c91b7a0e72f52]*/
4534
0
{
4535
0
    int result;
4536
4537
0
#if defined(HAVE_FCHOWNAT)
4538
0
    int fchownat_unsupported = 0;
4539
0
#endif
4540
4541
#if !(defined(HAVE_LCHOWN) || defined(HAVE_FCHOWNAT))
4542
    if (follow_symlinks_specified("chown", follow_symlinks))
4543
        return NULL;
4544
#endif
4545
0
    if (dir_fd_and_fd_invalid("chown", dir_fd, path->fd) ||
4546
0
        fd_and_follow_symlinks_invalid("chown", path->is_fd, follow_symlinks))
4547
0
        return NULL;
4548
4549
0
    if (PySys_Audit("os.chown", "OIIi", path->object, uid, gid,
4550
0
                    dir_fd == DEFAULT_DIR_FD ? -1 : dir_fd) < 0) {
4551
0
        return NULL;
4552
0
    }
4553
4554
0
    Py_BEGIN_ALLOW_THREADS
4555
0
#ifdef HAVE_FCHOWN
4556
0
    if (path->is_fd)
4557
0
        result = fchown(path->fd, uid, gid);
4558
0
    else
4559
0
#endif
4560
0
#ifdef HAVE_LCHOWN
4561
0
    if ((!follow_symlinks) && (dir_fd == DEFAULT_DIR_FD))
4562
0
        result = lchown(path->narrow, uid, gid);
4563
0
    else
4564
0
#endif
4565
0
#ifdef HAVE_FCHOWNAT
4566
0
    if ((dir_fd != DEFAULT_DIR_FD) || (!follow_symlinks)) {
4567
0
      if (HAVE_FCHOWNAT_RUNTIME) {
4568
0
        result = fchownat(dir_fd, path->narrow, uid, gid,
4569
0
                          follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW);
4570
0
      } else {
4571
0
         fchownat_unsupported = 1;
4572
0
      }
4573
0
    } else
4574
0
#endif
4575
0
        result = chown(path->narrow, uid, gid);
4576
0
    Py_END_ALLOW_THREADS
4577
4578
0
#ifdef HAVE_FCHOWNAT
4579
0
    if (fchownat_unsupported) {
4580
        /* This would be incorrect if the current platform
4581
         * doesn't support lchown.
4582
         */
4583
0
        argument_unavailable_error(NULL, "dir_fd");
4584
0
        return NULL;
4585
0
    }
4586
0
#endif
4587
4588
0
    if (result)
4589
0
        return path_error(path);
4590
4591
0
    Py_RETURN_NONE;
4592
0
}
4593
#endif /* HAVE_CHOWN */
4594
4595
4596
#ifdef HAVE_FCHOWN
4597
/*[clinic input]
4598
os.fchown
4599
4600
    fd: int
4601
    uid: uid_t
4602
    gid: gid_t
4603
4604
Change the owner and group id of the file specified by file descriptor.
4605
4606
Equivalent to os.chown(fd, uid, gid).
4607
4608
[clinic start generated code]*/
4609
4610
static PyObject *
4611
os_fchown_impl(PyObject *module, int fd, uid_t uid, gid_t gid)
4612
/*[clinic end generated code: output=97d21cbd5a4350a6 input=3af544ba1b13a0d7]*/
4613
0
{
4614
0
    int res;
4615
0
    int async_err = 0;
4616
4617
0
    if (PySys_Audit("os.chown", "iIIi", fd, uid, gid, -1) < 0) {
4618
0
        return NULL;
4619
0
    }
4620
4621
0
    do {
4622
0
        Py_BEGIN_ALLOW_THREADS
4623
0
        res = fchown(fd, uid, gid);
4624
0
        Py_END_ALLOW_THREADS
4625
0
    } while (res != 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
4626
0
    if (res != 0)
4627
0
        return (!async_err) ? posix_error() : NULL;
4628
4629
0
    Py_RETURN_NONE;
4630
0
}
4631
#endif /* HAVE_FCHOWN */
4632
4633
4634
#ifdef HAVE_LCHOWN
4635
/*[clinic input]
4636
os.lchown
4637
4638
    path : path_t
4639
    uid: uid_t
4640
    gid: gid_t
4641
4642
Change the owner and group id of path to the numeric uid and gid.
4643
4644
This function will not follow symbolic links.
4645
Equivalent to os.chown(path, uid, gid, follow_symlinks=False).
4646
[clinic start generated code]*/
4647
4648
static PyObject *
4649
os_lchown_impl(PyObject *module, path_t *path, uid_t uid, gid_t gid)
4650
/*[clinic end generated code: output=25eaf6af412fdf2f input=b1c6014d563a7161]*/
4651
0
{
4652
0
    int res;
4653
0
    if (PySys_Audit("os.chown", "OIIi", path->object, uid, gid, -1) < 0) {
4654
0
        return NULL;
4655
0
    }
4656
0
    Py_BEGIN_ALLOW_THREADS
4657
0
    res = lchown(path->narrow, uid, gid);
4658
0
    Py_END_ALLOW_THREADS
4659
0
    if (res < 0) {
4660
0
        return path_error(path);
4661
0
    }
4662
0
    Py_RETURN_NONE;
4663
0
}
4664
#endif /* HAVE_LCHOWN */
4665
4666
4667
static PyObject *
4668
posix_getcwd(int use_bytes)
4669
8
{
4670
#ifdef MS_WINDOWS
4671
    wchar_t wbuf[MAXPATHLEN];
4672
    wchar_t *wbuf2 = wbuf;
4673
    DWORD len;
4674
4675
    Py_BEGIN_ALLOW_THREADS
4676
    len = GetCurrentDirectoryW(Py_ARRAY_LENGTH(wbuf), wbuf);
4677
    /* If the buffer is large enough, len does not include the
4678
       terminating \0. If the buffer is too small, len includes
4679
       the space needed for the terminator. */
4680
    if (len >= Py_ARRAY_LENGTH(wbuf)) {
4681
        if ((Py_ssize_t)len <= PY_SSIZE_T_MAX / sizeof(wchar_t)) {
4682
            wbuf2 = PyMem_RawMalloc(len * sizeof(wchar_t));
4683
        }
4684
        else {
4685
            wbuf2 = NULL;
4686
        }
4687
        if (wbuf2) {
4688
            len = GetCurrentDirectoryW(len, wbuf2);
4689
        }
4690
    }
4691
    Py_END_ALLOW_THREADS
4692
4693
    if (!wbuf2) {
4694
        PyErr_NoMemory();
4695
        return NULL;
4696
    }
4697
    if (!len) {
4698
        PyErr_SetFromWindowsErr(0);
4699
        if (wbuf2 != wbuf)
4700
            PyMem_RawFree(wbuf2);
4701
        return NULL;
4702
    }
4703
4704
    PyObject *resobj = PyUnicode_FromWideChar(wbuf2, len);
4705
    if (wbuf2 != wbuf) {
4706
        PyMem_RawFree(wbuf2);
4707
    }
4708
4709
    if (use_bytes) {
4710
        if (resobj == NULL) {
4711
            return NULL;
4712
        }
4713
        Py_SETREF(resobj, PyUnicode_EncodeFSDefault(resobj));
4714
    }
4715
4716
    return resobj;
4717
#else
4718
8
    const size_t chunk = 1024;
4719
4720
8
    char *buf = NULL;
4721
8
    char *cwd = NULL;
4722
8
    size_t buflen = 0;
4723
4724
8
    Py_BEGIN_ALLOW_THREADS
4725
8
    do {
4726
8
        char *newbuf;
4727
8
        if (buflen <= PY_SSIZE_T_MAX - chunk) {
4728
8
            buflen += chunk;
4729
8
            newbuf = PyMem_RawRealloc(buf, buflen);
4730
8
        }
4731
0
        else {
4732
0
            newbuf = NULL;
4733
0
        }
4734
8
        if (newbuf == NULL) {
4735
0
            PyMem_RawFree(buf);
4736
0
            buf = NULL;
4737
0
            break;
4738
0
        }
4739
8
        buf = newbuf;
4740
4741
8
        cwd = getcwd(buf, buflen);
4742
8
    } while (cwd == NULL && errno == ERANGE);
4743
8
    Py_END_ALLOW_THREADS
4744
4745
8
    if (buf == NULL) {
4746
0
        return PyErr_NoMemory();
4747
0
    }
4748
8
    if (cwd == NULL) {
4749
0
        posix_error();
4750
0
        PyMem_RawFree(buf);
4751
0
        return NULL;
4752
0
    }
4753
4754
8
    PyObject *obj;
4755
8
    if (use_bytes) {
4756
0
        obj = PyBytes_FromStringAndSize(buf, strlen(buf));
4757
0
    }
4758
8
    else {
4759
8
        obj = PyUnicode_DecodeFSDefault(buf);
4760
8
    }
4761
8
#ifdef __linux__
4762
8
    if (buf[0] != '/') {
4763
        /*
4764
         * On Linux >= 2.6.36 with glibc < 2.27, getcwd() can return a
4765
         * relative pathname starting with '(unreachable)'. We detect this
4766
         * and fail with ENOENT, matching newer glibc behaviour.
4767
         */
4768
0
        errno = ENOENT;
4769
0
        path_object_error(obj);
4770
0
        PyMem_RawFree(buf);
4771
0
        return NULL;
4772
0
    }
4773
8
#endif
4774
8
    assert(buf[0] == '/');
4775
8
    PyMem_RawFree(buf);
4776
4777
8
    return obj;
4778
8
#endif   /* !MS_WINDOWS */
4779
8
}
4780
4781
4782
/*[clinic input]
4783
os.getcwd
4784
4785
Return a unicode string representing the current working directory.
4786
[clinic start generated code]*/
4787
4788
static PyObject *
4789
os_getcwd_impl(PyObject *module)
4790
/*[clinic end generated code: output=21badfae2ea99ddc input=f069211bb70e3d39]*/
4791
8
{
4792
8
    return posix_getcwd(0);
4793
8
}
4794
4795
4796
/*[clinic input]
4797
os.getcwdb
4798
4799
Return a bytes string representing the current working directory.
4800
[clinic start generated code]*/
4801
4802
static PyObject *
4803
os_getcwdb_impl(PyObject *module)
4804
/*[clinic end generated code: output=3dd47909480e4824 input=f6f6a378dad3d9cb]*/
4805
0
{
4806
0
    return posix_getcwd(1);
4807
0
}
4808
4809
4810
#if ((!defined(HAVE_LINK)) && defined(MS_WINDOWS))
4811
#define HAVE_LINK 1
4812
#endif
4813
4814
#ifdef HAVE_LINK
4815
/*[clinic input]
4816
4817
os.link
4818
4819
    src : path_t
4820
    dst : path_t
4821
    *
4822
    src_dir_fd : dir_fd = None
4823
    dst_dir_fd : dir_fd = None
4824
    follow_symlinks: bool(c_default="-1", py_default="(os.name != 'nt')") = PLACEHOLDER
4825
4826
Create a hard link to a file.
4827
4828
If either src_dir_fd or dst_dir_fd is not None, it should be a file
4829
descriptor open to a directory, and the respective path string (src or
4830
dst) should be relative; the path will then be relative to that
4831
directory.
4832
If follow_symlinks is False, and the last element of src is a symbolic
4833
link, link will create a link to the symbolic link itself instead of the
4834
file the link points to.
4835
src_dir_fd, dst_dir_fd, and follow_symlinks may not be implemented on
4836
your platform.  If they are unavailable, using them will raise
4837
a NotImplementedError.
4838
[clinic start generated code]*/
4839
4840
static PyObject *
4841
os_link_impl(PyObject *module, path_t *src, path_t *dst, int src_dir_fd,
4842
             int dst_dir_fd, int follow_symlinks)
4843
/*[clinic end generated code: output=7f00f6007fd5269a input=a28e6866fbd20a01]*/
4844
0
{
4845
#ifdef MS_WINDOWS
4846
    BOOL result = FALSE;
4847
#else
4848
0
    int result;
4849
0
#endif
4850
4851
0
#ifdef HAVE_LINKAT
4852
0
    if (HAVE_LINKAT_RUNTIME) {
4853
0
        if (follow_symlinks < 0) {
4854
0
            follow_symlinks = 1;
4855
0
        }
4856
0
    }
4857
0
    else
4858
0
#endif
4859
0
    {
4860
0
        if ((src_dir_fd != DEFAULT_DIR_FD) || (dst_dir_fd != DEFAULT_DIR_FD)) {
4861
0
            argument_unavailable_error("link", "src_dir_fd and dst_dir_fd");
4862
0
            return NULL;
4863
0
        }
4864
/* See issue 85527: link() on Linux works like linkat without AT_SYMLINK_FOLLOW,
4865
   but on Mac it works like linkat *with* AT_SYMLINK_FOLLOW. */
4866
0
#if defined(MS_WINDOWS) || defined(__linux__)
4867
0
        if (follow_symlinks == 1) {
4868
0
            argument_unavailable_error("link", "follow_symlinks=True");
4869
0
            return NULL;
4870
0
        }
4871
#elif defined(__APPLE__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) || (defined(__sun) && defined(__SVR4))
4872
        if (follow_symlinks == 0) {
4873
            argument_unavailable_error("link", "follow_symlinks=False");
4874
            return NULL;
4875
        }
4876
#else
4877
        if (follow_symlinks >= 0) {
4878
            argument_unavailable_error("link", "follow_symlinks");
4879
            return NULL;
4880
        }
4881
#endif
4882
0
    }
4883
4884
0
    if (PySys_Audit("os.link", "OOii", src->object, dst->object,
4885
0
                    src_dir_fd == DEFAULT_DIR_FD ? -1 : src_dir_fd,
4886
0
                    dst_dir_fd == DEFAULT_DIR_FD ? -1 : dst_dir_fd) < 0) {
4887
0
        return NULL;
4888
0
    }
4889
4890
#ifdef MS_WINDOWS
4891
    Py_BEGIN_ALLOW_THREADS
4892
    result = CreateHardLinkW(dst->wide, src->wide, NULL);
4893
    Py_END_ALLOW_THREADS
4894
4895
    if (!result)
4896
        return path_error2(src, dst);
4897
#else
4898
0
    Py_BEGIN_ALLOW_THREADS
4899
0
#ifdef HAVE_LINKAT
4900
0
    if (HAVE_LINKAT_RUNTIME) {
4901
0
        result = linkat(src_dir_fd, src->narrow,
4902
0
            dst_dir_fd, dst->narrow,
4903
0
            follow_symlinks ? AT_SYMLINK_FOLLOW : 0);
4904
0
    }
4905
0
    else
4906
0
#endif
4907
0
    {
4908
        /* linkat not available */
4909
0
        result = link(src->narrow, dst->narrow);
4910
0
    }
4911
0
    Py_END_ALLOW_THREADS
4912
4913
0
    if (result)
4914
0
        return path_error2(src, dst);
4915
0
#endif /* MS_WINDOWS */
4916
4917
0
    Py_RETURN_NONE;
4918
0
}
4919
#endif
4920
4921
4922
#if defined(MS_WINDOWS) && !defined(HAVE_OPENDIR)
4923
static wchar_t *
4924
join_path_filenameW(const wchar_t *path_wide, const wchar_t *filename,
4925
                    int normalize);
4926
4927
static PyObject *
4928
_listdir_windows_no_opendir(path_t *path, PyObject *list)
4929
{
4930
    PyObject *v;
4931
    HANDLE hFindFile = INVALID_HANDLE_VALUE;
4932
    BOOL result, return_bytes;
4933
    wchar_t *wnamebuf = NULL;
4934
4935
    WIN32_FIND_DATAW wFileData;
4936
    const wchar_t *po_wchars;
4937
4938
    if (!path->wide) { /* Default arg: "." */
4939
        po_wchars = L".";
4940
        return_bytes = 0;
4941
    } else {
4942
        po_wchars = path->wide;
4943
        return_bytes = PyBytes_Check(path->object);
4944
    }
4945
4946
    wnamebuf = join_path_filenameW(po_wchars, L"*.*", 1);
4947
    if (wnamebuf == NULL) {
4948
        goto exit;
4949
    }
4950
4951
    if ((list = PyList_New(0)) == NULL) {
4952
        goto exit;
4953
    }
4954
    Py_BEGIN_ALLOW_THREADS
4955
    hFindFile = FindFirstFileW(wnamebuf, &wFileData);
4956
    Py_END_ALLOW_THREADS
4957
    if (hFindFile == INVALID_HANDLE_VALUE) {
4958
        int error = GetLastError();
4959
        if (error == ERROR_FILE_NOT_FOUND)
4960
            goto exit;
4961
        path_error(path);
4962
        Py_CLEAR(list);
4963
        goto exit;
4964
    }
4965
    do {
4966
        /* Skip over . and .. */
4967
        if (wcscmp(wFileData.cFileName, L".") != 0 &&
4968
            wcscmp(wFileData.cFileName, L"..") != 0) {
4969
            v = PyUnicode_FromWideChar(wFileData.cFileName,
4970
                                       wcslen(wFileData.cFileName));
4971
            if (return_bytes && v) {
4972
                Py_SETREF(v, PyUnicode_EncodeFSDefault(v));
4973
            }
4974
            if (v == NULL) {
4975
                Py_CLEAR(list);
4976
                break;
4977
            }
4978
            if (PyList_Append(list, v) != 0) {
4979
                Py_DECREF(v);
4980
                Py_CLEAR(list);
4981
                break;
4982
            }
4983
            Py_DECREF(v);
4984
        }
4985
        Py_BEGIN_ALLOW_THREADS
4986
        result = FindNextFileW(hFindFile, &wFileData);
4987
        Py_END_ALLOW_THREADS
4988
        /* FindNextFile sets error to ERROR_NO_MORE_FILES if
4989
           it got to the end of the directory. */
4990
        if (!result && GetLastError() != ERROR_NO_MORE_FILES) {
4991
            path_error(path);
4992
            Py_CLEAR(list);
4993
            goto exit;
4994
        }
4995
    } while (result == TRUE);
4996
4997
exit:
4998
    if (hFindFile != INVALID_HANDLE_VALUE) {
4999
        if (FindClose(hFindFile) == FALSE) {
5000
            if (list != NULL) {
5001
                path_error(path);
5002
                Py_CLEAR(list);
5003
            }
5004
        }
5005
    }
5006
    PyMem_Free(wnamebuf);
5007
5008
    return list;
5009
}  /* end of _listdir_windows_no_opendir */
5010
5011
#else  /* thus POSIX, ie: not (MS_WINDOWS and not HAVE_OPENDIR) */
5012
5013
static PyObject *
5014
_posix_listdir(path_t *path, PyObject *list)
5015
382
{
5016
382
    PyObject *v;
5017
382
    DIR *dirp = NULL;
5018
382
    struct dirent *ep;
5019
382
    int return_str; /* if false, return bytes */
5020
382
#ifdef HAVE_FDOPENDIR
5021
382
    int fd = -1;
5022
382
#endif
5023
5024
382
    errno = 0;
5025
382
#ifdef HAVE_FDOPENDIR
5026
382
    if (path->is_fd) {
5027
0
      if (HAVE_FDOPENDIR_RUNTIME) {
5028
        /* closedir() closes the FD, so we duplicate it */
5029
0
        fd = _Py_dup(path->fd);
5030
0
        if (fd == -1)
5031
0
            return NULL;
5032
5033
0
        return_str = 1;
5034
5035
0
        Py_BEGIN_ALLOW_THREADS
5036
0
        dirp = fdopendir(fd);
5037
0
        Py_END_ALLOW_THREADS
5038
0
      } else {
5039
0
        PyErr_SetString(PyExc_TypeError,
5040
0
            "listdir: path should be string, bytes, os.PathLike or None, not int");
5041
0
        return NULL;
5042
0
      }
5043
0
    }
5044
382
    else
5045
382
#endif
5046
382
    {
5047
382
        const char *name;
5048
382
        if (path->narrow) {
5049
382
            name = path->narrow;
5050
            /* only return bytes if they specified a bytes object */
5051
382
            return_str = !PyBytes_Check(path->object);
5052
382
        }
5053
0
        else {
5054
0
            name = ".";
5055
0
            return_str = 1;
5056
0
        }
5057
5058
382
        Py_BEGIN_ALLOW_THREADS
5059
382
        dirp = opendir(name);
5060
382
        Py_END_ALLOW_THREADS
5061
382
    }
5062
5063
382
    if (dirp == NULL) {
5064
4
        path_error(path);
5065
4
        list = NULL;
5066
4
#ifdef HAVE_FDOPENDIR
5067
4
        if (fd != -1) {
5068
0
            Py_BEGIN_ALLOW_THREADS
5069
0
            close(fd);
5070
0
            Py_END_ALLOW_THREADS
5071
0
        }
5072
4
#endif
5073
4
        goto exit;
5074
4
    }
5075
378
    if ((list = PyList_New(0)) == NULL) {
5076
0
        goto exit;
5077
0
    }
5078
21.7k
    for (;;) {
5079
21.7k
        errno = 0;
5080
21.7k
        Py_BEGIN_ALLOW_THREADS
5081
21.7k
        ep = readdir(dirp);
5082
21.7k
        Py_END_ALLOW_THREADS
5083
21.7k
        if (ep == NULL) {
5084
378
            if (errno == 0) {
5085
378
                break;
5086
378
            } else {
5087
0
                path_error(path);
5088
0
                Py_CLEAR(list);
5089
0
                goto exit;
5090
0
            }
5091
378
        }
5092
21.4k
        if (ep->d_name[0] == '.' &&
5093
769
            (NAMLEN(ep) == 1 ||
5094
391
             (ep->d_name[1] == '.' && NAMLEN(ep) == 2)))
5095
756
            continue;
5096
20.6k
        if (return_str)
5097
20.6k
            v = PyUnicode_DecodeFSDefaultAndSize(ep->d_name, NAMLEN(ep));
5098
0
        else
5099
0
            v = PyBytes_FromStringAndSize(ep->d_name, NAMLEN(ep));
5100
20.6k
        if (v == NULL) {
5101
0
            Py_CLEAR(list);
5102
0
            break;
5103
0
        }
5104
20.6k
        if (PyList_Append(list, v) != 0) {
5105
0
            Py_DECREF(v);
5106
0
            Py_CLEAR(list);
5107
0
            break;
5108
0
        }
5109
20.6k
        Py_DECREF(v);
5110
20.6k
    }
5111
5112
382
exit:
5113
382
    if (dirp != NULL) {
5114
378
        Py_BEGIN_ALLOW_THREADS
5115
378
#ifdef HAVE_FDOPENDIR
5116
378
        if (fd > -1)
5117
0
            rewinddir(dirp);
5118
378
#endif
5119
378
        closedir(dirp);
5120
378
        Py_END_ALLOW_THREADS
5121
378
    }
5122
5123
382
    return list;
5124
378
}  /* end of _posix_listdir */
5125
#endif  /* which OS */
5126
5127
5128
/*[clinic input]
5129
os.listdir
5130
5131
    path : path_t(nullable=True, allow_fd='PATH_HAVE_FDOPENDIR') = None
5132
5133
Return a list containing the names of the files in the directory.
5134
5135
path can be specified as either str, bytes, or a path-like object.  If
5136
path is bytes, the filenames returned will also be bytes; in all other
5137
circumstances the filenames returned will be str.
5138
If path is None, uses the path='.'.
5139
On some platforms, path may also be specified as an open file
5140
descriptor; the file descriptor must refer to a directory.  If this
5141
functionality is unavailable, using it raises NotImplementedError.
5142
5143
The list is in arbitrary order.  It does not include the special
5144
entries '.' and '..' even if they are present in the directory.
5145
5146
[clinic start generated code]*/
5147
5148
static PyObject *
5149
os_listdir_impl(PyObject *module, path_t *path)
5150
/*[clinic end generated code: output=293045673fcd1a75 input=4eefe7c6a42ec9b2]*/
5151
382
{
5152
382
    if (PySys_Audit("os.listdir", "O",
5153
382
                    path->object ? path->object : Py_None) < 0) {
5154
0
        return NULL;
5155
0
    }
5156
#if defined(MS_WINDOWS) && !defined(HAVE_OPENDIR)
5157
    return _listdir_windows_no_opendir(path, NULL);
5158
#else
5159
382
    return _posix_listdir(path, NULL);
5160
382
#endif
5161
382
}
5162
5163
5164
#if defined(MS_WINDOWS_DESKTOP) || defined(MS_WINDOWS_SYSTEM)
5165
5166
/*[clinic input]
5167
os.listdrives
5168
5169
Return a list containing the names of drives in the system.
5170
5171
A drive name typically looks like 'C:\\'.
5172
5173
[clinic start generated code]*/
5174
5175
static PyObject *
5176
os_listdrives_impl(PyObject *module)
5177
/*[clinic end generated code: output=aaece9dacdf682b5 input=1af9ccc9e583798e]*/
5178
{
5179
    /* Number of possible drives is limited, so 256 should always be enough.
5180
       On the day when it is not, listmounts() will have to be used. */
5181
    wchar_t buffer[256];
5182
    DWORD buflen = Py_ARRAY_LENGTH(buffer);
5183
    PyObject *result = NULL;
5184
    if (PySys_Audit("os.listdrives", NULL) < 0) {
5185
        return NULL;
5186
    }
5187
5188
    Py_BEGIN_ALLOW_THREADS;
5189
    buflen = GetLogicalDriveStringsW(buflen, buffer);
5190
    Py_END_ALLOW_THREADS;
5191
5192
    if (!buflen) {
5193
        PyErr_SetFromWindowsErr(0);
5194
        return NULL;
5195
    } else if (buflen >= Py_ARRAY_LENGTH(buffer)) {
5196
        PyErr_SetFromWindowsErr(ERROR_MORE_DATA);
5197
        return NULL;
5198
    }
5199
5200
    /* buflen includes a null terminator, so remove it */
5201
    PyObject *str = PyUnicode_FromWideChar(buffer, buflen - 1);
5202
    if (str) {
5203
        PyObject *nullchar = PyUnicode_FromStringAndSize("\0", 1);
5204
        if (nullchar) {
5205
            result = PyUnicode_Split(str, nullchar, -1);
5206
            Py_DECREF(nullchar);
5207
        }
5208
        Py_DECREF(str);
5209
    }
5210
    return result;
5211
}
5212
5213
#endif /* MS_WINDOWS_DESKTOP || MS_WINDOWS_SYSTEM */
5214
5215
#if defined(MS_WINDOWS_DESKTOP) || defined(MS_WINDOWS_SYSTEM)
5216
5217
/*[clinic input]
5218
os.listvolumes
5219
5220
Return a list containing the volumes in the system.
5221
5222
Volumes are typically represented as a GUID path.
5223
5224
[clinic start generated code]*/
5225
5226
static PyObject *
5227
os_listvolumes_impl(PyObject *module)
5228
/*[clinic end generated code: output=534e10ea2bf9d386 input=f6e4e70371f11e99]*/
5229
{
5230
    PyObject *result = PyList_New(0);
5231
    HANDLE find = INVALID_HANDLE_VALUE;
5232
    wchar_t buffer[MAX_PATH + 1];
5233
    if (!result) {
5234
        return NULL;
5235
    }
5236
    if (PySys_Audit("os.listvolumes", NULL) < 0) {
5237
        Py_DECREF(result);
5238
        return NULL;
5239
    }
5240
5241
    int err = 0;
5242
    Py_BEGIN_ALLOW_THREADS;
5243
    find = FindFirstVolumeW(buffer, Py_ARRAY_LENGTH(buffer));
5244
    if (find == INVALID_HANDLE_VALUE) {
5245
        err = GetLastError();
5246
    }
5247
    Py_END_ALLOW_THREADS;
5248
5249
    while (!err) {
5250
        PyObject *s = PyUnicode_FromWideChar(buffer, -1);
5251
        if (!s || PyList_Append(result, s) < 0) {
5252
            Py_XDECREF(s);
5253
            Py_CLEAR(result);
5254
            break;
5255
        }
5256
        Py_DECREF(s);
5257
5258
        Py_BEGIN_ALLOW_THREADS;
5259
        if (!FindNextVolumeW(find, buffer, Py_ARRAY_LENGTH(buffer))) {
5260
            err = GetLastError();
5261
        }
5262
        Py_END_ALLOW_THREADS;
5263
    }
5264
5265
    if (find != INVALID_HANDLE_VALUE) {
5266
        Py_BEGIN_ALLOW_THREADS;
5267
        FindVolumeClose(find);
5268
        Py_END_ALLOW_THREADS;
5269
    }
5270
    if (err && err != ERROR_NO_MORE_FILES) {
5271
        PyErr_SetFromWindowsErr(err);
5272
        Py_XDECREF(result);
5273
        result = NULL;
5274
    }
5275
    return result;
5276
}
5277
5278
#endif /* MS_WINDOWS_DESKTOP || MS_WINDOWS_SYSTEM */
5279
5280
#if defined(MS_WINDOWS_DESKTOP) || defined(MS_WINDOWS_SYSTEM)
5281
5282
/*[clinic input]
5283
os.listmounts
5284
5285
    volume: path_t
5286
5287
Return a list containing mount points for a particular volume.
5288
5289
'volume' should be a GUID path as returned from os.listvolumes.
5290
5291
[clinic start generated code]*/
5292
5293
static PyObject *
5294
os_listmounts_impl(PyObject *module, path_t *volume)
5295
/*[clinic end generated code: output=06da49679de4512e input=a8a27178e3f67845]*/
5296
{
5297
    wchar_t default_buffer[MAX_PATH + 1];
5298
    DWORD buflen = Py_ARRAY_LENGTH(default_buffer);
5299
    LPWSTR buffer = default_buffer;
5300
    DWORD attributes;
5301
    PyObject *str = NULL;
5302
    PyObject *nullchar = NULL;
5303
    PyObject *result = NULL;
5304
5305
    /* Ensure we have a valid volume path before continuing */
5306
    Py_BEGIN_ALLOW_THREADS
5307
    attributes = GetFileAttributesW(volume->wide);
5308
    Py_END_ALLOW_THREADS
5309
    if (attributes == INVALID_FILE_ATTRIBUTES &&
5310
        GetLastError() == ERROR_UNRECOGNIZED_VOLUME)
5311
    {
5312
        return PyErr_SetFromWindowsErr(ERROR_UNRECOGNIZED_VOLUME);
5313
    }
5314
5315
    if (PySys_Audit("os.listmounts", "O", volume->object) < 0) {
5316
        return NULL;
5317
    }
5318
5319
    while (1) {
5320
        BOOL success;
5321
        Py_BEGIN_ALLOW_THREADS
5322
        success = GetVolumePathNamesForVolumeNameW(volume->wide, buffer,
5323
                                                   buflen, &buflen);
5324
        Py_END_ALLOW_THREADS
5325
        if (success) {
5326
            break;
5327
        }
5328
        if (GetLastError() != ERROR_MORE_DATA) {
5329
            PyErr_SetFromWindowsErr(0);
5330
            goto exit;
5331
        }
5332
        if (buffer != default_buffer) {
5333
            PyMem_Free((void *)buffer);
5334
        }
5335
        buffer = (wchar_t*)PyMem_Malloc(sizeof(wchar_t) * buflen);
5336
        if (!buffer) {
5337
            PyErr_NoMemory();
5338
            goto exit;
5339
        }
5340
    }
5341
    if (buflen < 2) {
5342
        result = PyList_New(0);
5343
        goto exit;
5344
    }
5345
    // buflen includes two null terminators, one for the last string
5346
    // and one for the array of strings.
5347
    str = PyUnicode_FromWideChar(buffer, buflen - 2);
5348
    nullchar = PyUnicode_FromStringAndSize("\0", 1);
5349
    if (str && nullchar) {
5350
        result = PyUnicode_Split(str, nullchar, -1);
5351
    }
5352
exit:
5353
    if (buffer != default_buffer) {
5354
        PyMem_Free(buffer);
5355
    }
5356
    Py_XDECREF(nullchar);
5357
    Py_XDECREF(str);
5358
    return result;
5359
}
5360
5361
#endif /* MS_WINDOWS_DESKTOP || MS_WINDOWS_SYSTEM */
5362
5363
#ifdef MS_WINDOWS
5364
5365
/*[clinic input]
5366
os._path_isdevdrive
5367
5368
    path: path_t
5369
5370
Determines whether the specified path is on a Windows Dev Drive.
5371
5372
[clinic start generated code]*/
5373
5374
static PyObject *
5375
os__path_isdevdrive_impl(PyObject *module, path_t *path)
5376
/*[clinic end generated code: output=1f437ea6677433a2 input=ee83e4996a48e23d]*/
5377
{
5378
#ifndef PERSISTENT_VOLUME_STATE_DEV_VOLUME
5379
    /* This flag will be documented at
5380
       https://learn.microsoft.com/windows-hardware/drivers/ddi/ntifs/ns-ntifs-_file_fs_persistent_volume_information
5381
       after release, and will be available in the latest WinSDK.
5382
       We include the flag to avoid a specific version dependency
5383
       on the latest WinSDK. */
5384
    const int PERSISTENT_VOLUME_STATE_DEV_VOLUME = 0x00002000;
5385
#endif
5386
    int err = 0;
5387
    PyObject *r = NULL;
5388
    wchar_t volume[MAX_PATH];
5389
5390
    Py_BEGIN_ALLOW_THREADS
5391
    if (!GetVolumePathNameW(path->wide, volume, MAX_PATH)) {
5392
        /* invalid path of some kind */
5393
        /* Note that this also includes the case where a volume is mounted
5394
           in a path longer than 260 characters. This is likely to be rare
5395
           and problematic for other reasons, so a (soft) failure in this
5396
           check seems okay. */
5397
        err = GetLastError();
5398
    } else if (GetDriveTypeW(volume) != DRIVE_FIXED) {
5399
        /* only care about local dev drives */
5400
        r = Py_False;
5401
    } else {
5402
        HANDLE hVolume = CreateFileW(
5403
            volume,
5404
            FILE_READ_ATTRIBUTES,
5405
            FILE_SHARE_READ | FILE_SHARE_WRITE,
5406
            NULL,
5407
            OPEN_EXISTING,
5408
            FILE_FLAG_BACKUP_SEMANTICS,
5409
            NULL
5410
        );
5411
        if (hVolume == INVALID_HANDLE_VALUE) {
5412
            err = GetLastError();
5413
        } else {
5414
            FILE_FS_PERSISTENT_VOLUME_INFORMATION volumeState = {0};
5415
            volumeState.Version = 1;
5416
            volumeState.FlagMask = PERSISTENT_VOLUME_STATE_DEV_VOLUME;
5417
            if (!DeviceIoControl(
5418
                hVolume,
5419
                FSCTL_QUERY_PERSISTENT_VOLUME_STATE,
5420
                &volumeState,
5421
                sizeof(volumeState),
5422
                &volumeState,
5423
                sizeof(volumeState),
5424
                NULL,
5425
                NULL
5426
            )) {
5427
                err = GetLastError();
5428
            }
5429
            CloseHandle(hVolume);
5430
            if (err == ERROR_INVALID_PARAMETER) {
5431
                /* not supported on this platform */
5432
                r = Py_False;
5433
            } else if (!err) {
5434
                r = (volumeState.VolumeFlags & PERSISTENT_VOLUME_STATE_DEV_VOLUME)
5435
                    ? Py_True : Py_False;
5436
            }
5437
        }
5438
    }
5439
    Py_END_ALLOW_THREADS
5440
5441
    if (err) {
5442
        PyErr_SetFromWindowsErr(err);
5443
        return NULL;
5444
    }
5445
5446
    if (r) {
5447
        return Py_NewRef(r);
5448
    }
5449
5450
    return NULL;
5451
}
5452
5453
5454
int
5455
_PyOS_getfullpathname(const wchar_t *path, wchar_t **abspath_p)
5456
{
5457
    wchar_t woutbuf[MAX_PATH], *woutbufp = woutbuf;
5458
    DWORD result;
5459
5460
    result = GetFullPathNameW(path,
5461
                              Py_ARRAY_LENGTH(woutbuf), woutbuf,
5462
                              NULL);
5463
    if (!result) {
5464
        return -1;
5465
    }
5466
5467
    if (result >= Py_ARRAY_LENGTH(woutbuf)) {
5468
        if ((size_t)result <= (size_t)PY_SSIZE_T_MAX / sizeof(wchar_t)) {
5469
            woutbufp = PyMem_RawMalloc((size_t)result * sizeof(wchar_t));
5470
        }
5471
        else {
5472
            woutbufp = NULL;
5473
        }
5474
        if (!woutbufp) {
5475
            *abspath_p = NULL;
5476
            return 0;
5477
        }
5478
5479
        result = GetFullPathNameW(path, result, woutbufp, NULL);
5480
        if (!result) {
5481
            PyMem_RawFree(woutbufp);
5482
            return -1;
5483
        }
5484
    }
5485
5486
    if (woutbufp != woutbuf) {
5487
        *abspath_p = woutbufp;
5488
        return 0;
5489
    }
5490
5491
    *abspath_p = _PyMem_RawWcsdup(woutbufp);
5492
    return 0;
5493
}
5494
5495
5496
/* A helper function for abspath on win32 */
5497
/*[clinic input]
5498
os._getfullpathname
5499
5500
    path: path_t
5501
    /
5502
5503
[clinic start generated code]*/
5504
5505
static PyObject *
5506
os__getfullpathname_impl(PyObject *module, path_t *path)
5507
/*[clinic end generated code: output=bb8679d56845bc9b input=332ed537c29d0a3e]*/
5508
{
5509
    wchar_t *abspath;
5510
5511
    if (_PyOS_getfullpathname(path->wide, &abspath) < 0) {
5512
        return win32_error_object("GetFullPathNameW", path->object);
5513
    }
5514
    if (abspath == NULL) {
5515
        return PyErr_NoMemory();
5516
    }
5517
5518
    PyObject *str = PyUnicode_FromWideChar(abspath, -1);
5519
    PyMem_RawFree(abspath);
5520
    if (str == NULL) {
5521
        return NULL;
5522
    }
5523
    if (PyBytes_Check(path->object)) {
5524
        Py_SETREF(str, PyUnicode_EncodeFSDefault(str));
5525
    }
5526
    return str;
5527
}
5528
5529
5530
/*[clinic input]
5531
os._getfinalpathname
5532
5533
    path: path_t
5534
    /
5535
5536
A helper function for samepath on windows.
5537
[clinic start generated code]*/
5538
5539
static PyObject *
5540
os__getfinalpathname_impl(PyObject *module, path_t *path)
5541
/*[clinic end generated code: output=621a3c79bc29ebfa input=2b6b6c7cbad5fb84]*/
5542
{
5543
    HANDLE hFile;
5544
    wchar_t buf[MAXPATHLEN], *target_path = buf;
5545
    int buf_size = Py_ARRAY_LENGTH(buf);
5546
    int result_length;
5547
    PyObject *result;
5548
5549
    Py_BEGIN_ALLOW_THREADS
5550
    hFile = CreateFileW(
5551
        path->wide,
5552
        0, /* desired access */
5553
        0, /* share mode */
5554
        NULL, /* security attributes */
5555
        OPEN_EXISTING,
5556
        /* FILE_FLAG_BACKUP_SEMANTICS is required to open a directory */
5557
        FILE_FLAG_BACKUP_SEMANTICS,
5558
        NULL);
5559
    Py_END_ALLOW_THREADS
5560
5561
    if (hFile == INVALID_HANDLE_VALUE) {
5562
        return win32_error_object("CreateFileW", path->object);
5563
    }
5564
5565
    /* We have a good handle to the target, use it to determine the
5566
       target path name. */
5567
    while (1) {
5568
        Py_BEGIN_ALLOW_THREADS
5569
        result_length = GetFinalPathNameByHandleW(hFile, target_path,
5570
                                                  buf_size, VOLUME_NAME_DOS);
5571
        Py_END_ALLOW_THREADS
5572
5573
        if (!result_length) {
5574
            result = win32_error_object("GetFinalPathNameByHandleW",
5575
                                         path->object);
5576
            goto cleanup;
5577
        }
5578
5579
        if (result_length < buf_size) {
5580
            break;
5581
        }
5582
5583
        wchar_t *tmp;
5584
        tmp = PyMem_Realloc(target_path != buf ? target_path : NULL,
5585
                            result_length * sizeof(*tmp));
5586
        if (!tmp) {
5587
            result = PyErr_NoMemory();
5588
            goto cleanup;
5589
        }
5590
5591
        buf_size = result_length;
5592
        target_path = tmp;
5593
    }
5594
5595
    result = PyUnicode_FromWideChar(target_path, result_length);
5596
    if (result && PyBytes_Check(path->object)) {
5597
        Py_SETREF(result, PyUnicode_EncodeFSDefault(result));
5598
    }
5599
5600
cleanup:
5601
    if (target_path != buf) {
5602
        PyMem_Free(target_path);
5603
    }
5604
    CloseHandle(hFile);
5605
    return result;
5606
}
5607
5608
/*[clinic input]
5609
@permit_long_summary
5610
os._findfirstfile
5611
    path: path_t
5612
    /
5613
A function to get the real file name without accessing the file in Windows.
5614
[clinic start generated code]*/
5615
5616
static PyObject *
5617
os__findfirstfile_impl(PyObject *module, path_t *path)
5618
/*[clinic end generated code: output=106dd3f0779c83dd input=48c319aaa48d05d4]*/
5619
{
5620
    PyObject *result;
5621
    HANDLE hFindFile;
5622
    WIN32_FIND_DATAW wFileData;
5623
    WCHAR *wRealFileName;
5624
5625
    Py_BEGIN_ALLOW_THREADS
5626
    hFindFile = FindFirstFileW(path->wide, &wFileData);
5627
    Py_END_ALLOW_THREADS
5628
5629
    if (hFindFile == INVALID_HANDLE_VALUE) {
5630
        path_error(path);
5631
        return NULL;
5632
    }
5633
5634
    wRealFileName = wFileData.cFileName;
5635
    result = PyUnicode_FromWideChar(wRealFileName, -1);
5636
    FindClose(hFindFile);
5637
    return result;
5638
}
5639
5640
5641
/*[clinic input]
5642
os._getvolumepathname
5643
5644
    path: path_t
5645
5646
A helper function for ismount on Win32.
5647
[clinic start generated code]*/
5648
5649
static PyObject *
5650
os__getvolumepathname_impl(PyObject *module, path_t *path)
5651
/*[clinic end generated code: output=804c63fd13a1330b input=722b40565fa21552]*/
5652
{
5653
    PyObject *result;
5654
    wchar_t *mountpath=NULL;
5655
    size_t buflen;
5656
    BOOL ret;
5657
5658
    /* Volume path should be shorter than entire path */
5659
    buflen = Py_MAX(path->length, MAX_PATH);
5660
5661
    if (buflen > PY_DWORD_MAX) {
5662
        PyErr_SetString(PyExc_OverflowError, "path too long");
5663
        return NULL;
5664
    }
5665
5666
    mountpath = PyMem_New(wchar_t, buflen);
5667
    if (mountpath == NULL)
5668
        return PyErr_NoMemory();
5669
5670
    Py_BEGIN_ALLOW_THREADS
5671
    ret = GetVolumePathNameW(path->wide, mountpath,
5672
                             Py_SAFE_DOWNCAST(buflen, size_t, DWORD));
5673
    Py_END_ALLOW_THREADS
5674
5675
    if (!ret) {
5676
        result = win32_error_object("_getvolumepathname", path->object);
5677
        goto exit;
5678
    }
5679
    result = PyUnicode_FromWideChar(mountpath, -1);
5680
    if (result != NULL && PyBytes_Check(path->object)) {
5681
        Py_SETREF(result, PyUnicode_EncodeFSDefault(result));
5682
    }
5683
5684
exit:
5685
    PyMem_Free(mountpath);
5686
    return result;
5687
}
5688
5689
5690
/*[clinic input]
5691
os._path_splitroot
5692
5693
    path: path_t
5694
    /
5695
5696
Removes everything after the root on Win32.
5697
[clinic start generated code]*/
5698
5699
static PyObject *
5700
os__path_splitroot_impl(PyObject *module, path_t *path)
5701
/*[clinic end generated code: output=ab7f1a88b654581c input=d356de1edb6050a2]*/
5702
{
5703
    wchar_t *buffer;
5704
    wchar_t *end;
5705
    PyObject *result = NULL;
5706
    HRESULT ret;
5707
5708
    buffer = (wchar_t*)PyMem_Malloc(sizeof(wchar_t) * (wcslen(path->wide) + 1));
5709
    if (!buffer) {
5710
        return PyErr_NoMemory();
5711
    }
5712
    wcscpy(buffer, path->wide);
5713
    for (wchar_t *p = wcschr(buffer, L'/'); p; p = wcschr(p, L'/')) {
5714
        *p = L'\\';
5715
    }
5716
5717
    Py_BEGIN_ALLOW_THREADS
5718
    ret = PathCchSkipRoot(buffer, &end);
5719
    Py_END_ALLOW_THREADS
5720
    if (FAILED(ret)) {
5721
        result = Py_BuildValue("sO", "", path->object);
5722
    } else if (end != buffer) {
5723
        size_t rootLen = (size_t)(end - buffer);
5724
        result = Py_BuildValue("NN",
5725
            PyUnicode_FromWideChar(path->wide, rootLen),
5726
            PyUnicode_FromWideChar(path->wide + rootLen, -1)
5727
        );
5728
    } else {
5729
        result = Py_BuildValue("Os", path->object, "");
5730
    }
5731
    PyMem_Free(buffer);
5732
5733
    return result;
5734
}
5735
5736
5737
#define PY_IFREG  1 // Regular file
5738
#define PY_IFDIR  2 // Directory
5739
#define PY_IFLNK  4 // Symlink
5740
#define PY_IFMNT  8 // Mount Point (junction)
5741
#define PY_IFLRP 16 // Link Reparse Point (name-surrogate, symlink, junction)
5742
#define PY_IFRRP 32 // Regular Reparse Point
5743
5744
static inline BOOL
5745
_testInfo(DWORD attributes, DWORD reparseTag, BOOL diskDevice, int testedType)
5746
{
5747
    switch (testedType) {
5748
    case PY_IFREG:
5749
        return diskDevice && attributes &&
5750
               !(attributes & FILE_ATTRIBUTE_DIRECTORY);
5751
    case PY_IFDIR:
5752
        return attributes & FILE_ATTRIBUTE_DIRECTORY;
5753
    case PY_IFLNK:
5754
        return (attributes & FILE_ATTRIBUTE_REPARSE_POINT) &&
5755
               reparseTag == IO_REPARSE_TAG_SYMLINK;
5756
    case PY_IFMNT:
5757
        return (attributes & FILE_ATTRIBUTE_REPARSE_POINT) &&
5758
               reparseTag == IO_REPARSE_TAG_MOUNT_POINT;
5759
    case PY_IFLRP:
5760
        return (attributes & FILE_ATTRIBUTE_REPARSE_POINT) &&
5761
               IsReparseTagNameSurrogate(reparseTag);
5762
    case PY_IFRRP:
5763
        return (attributes & FILE_ATTRIBUTE_REPARSE_POINT) &&
5764
               reparseTag && !IsReparseTagNameSurrogate(reparseTag);
5765
    }
5766
5767
    return FALSE;
5768
}
5769
5770
static BOOL
5771
_testFileTypeByHandle(HANDLE hfile, int testedType, BOOL diskOnly)
5772
{
5773
    assert(testedType == PY_IFREG || testedType == PY_IFDIR ||
5774
           testedType == PY_IFLNK || testedType == PY_IFMNT ||
5775
           testedType == PY_IFLRP || testedType == PY_IFRRP);
5776
5777
    BOOL diskDevice = GetFileType(hfile) == FILE_TYPE_DISK;
5778
    if (diskOnly && !diskDevice) {
5779
        return FALSE;
5780
    }
5781
    if (testedType != PY_IFREG && testedType != PY_IFDIR) {
5782
        FILE_ATTRIBUTE_TAG_INFO info;
5783
        return GetFileInformationByHandleEx(hfile, FileAttributeTagInfo, &info,
5784
                                            sizeof(info)) &&
5785
               _testInfo(info.FileAttributes, info.ReparseTag, diskDevice,
5786
                         testedType);
5787
    }
5788
    FILE_BASIC_INFO info;
5789
    return GetFileInformationByHandleEx(hfile, FileBasicInfo, &info,
5790
                                        sizeof(info)) &&
5791
           _testInfo(info.FileAttributes, 0, diskDevice, testedType);
5792
}
5793
5794
static BOOL
5795
_testFileTypeByName(LPCWSTR path, int testedType)
5796
{
5797
    assert(testedType == PY_IFREG || testedType == PY_IFDIR ||
5798
           testedType == PY_IFLNK || testedType == PY_IFMNT ||
5799
           testedType == PY_IFLRP || testedType == PY_IFRRP);
5800
5801
    FILE_STAT_BASIC_INFORMATION info;
5802
    if (_Py_GetFileInformationByName(path, FileStatBasicByNameInfo, &info,
5803
                                     sizeof(info)))
5804
    {
5805
        BOOL diskDevice = info.DeviceType == FILE_DEVICE_DISK ||
5806
                          info.DeviceType == FILE_DEVICE_VIRTUAL_DISK ||
5807
                          info.DeviceType == FILE_DEVICE_CD_ROM;
5808
        BOOL result = _testInfo(info.FileAttributes, info.ReparseTag,
5809
                                diskDevice, testedType);
5810
        if (!result || (testedType != PY_IFREG && testedType != PY_IFDIR) ||
5811
            !(info.FileAttributes & FILE_ATTRIBUTE_REPARSE_POINT))
5812
        {
5813
            return result;
5814
        }
5815
    }
5816
    else if (_Py_GetFileInformationByName_ErrorIsTrustworthy(
5817
                GetLastError()))
5818
    {
5819
        return FALSE;
5820
    }
5821
5822
    DWORD flags = FILE_FLAG_BACKUP_SEMANTICS;
5823
    if (testedType != PY_IFREG && testedType != PY_IFDIR) {
5824
        flags |= FILE_FLAG_OPEN_REPARSE_POINT;
5825
    }
5826
    HANDLE hfile = CreateFileW(path, FILE_READ_ATTRIBUTES, 0, NULL,
5827
                               OPEN_EXISTING, flags, NULL);
5828
    if (hfile != INVALID_HANDLE_VALUE) {
5829
        BOOL result = _testFileTypeByHandle(hfile, testedType, FALSE);
5830
        CloseHandle(hfile);
5831
        return result;
5832
    }
5833
5834
    switch (GetLastError()) {
5835
    case ERROR_ACCESS_DENIED:
5836
    case ERROR_SHARING_VIOLATION:
5837
    case ERROR_CANT_ACCESS_FILE:
5838
    case ERROR_INVALID_PARAMETER:
5839
        int rc;
5840
        STRUCT_STAT st;
5841
        if (testedType == PY_IFREG || testedType == PY_IFDIR) {
5842
            rc = STAT(path, &st);
5843
        }
5844
        else {
5845
            // PY_IFRRP is not generally supported in this case, except for
5846
            // unhandled reparse points such as IO_REPARSE_TAG_APPEXECLINK.
5847
            rc = LSTAT(path, &st);
5848
        }
5849
        if (!rc) {
5850
            return _testInfo(st.st_file_attributes, st.st_reparse_tag,
5851
                             st.st_mode & S_IFREG, testedType);
5852
        }
5853
    }
5854
5855
    return FALSE;
5856
}
5857
5858
5859
static BOOL
5860
_testFileExistsByName(LPCWSTR path, BOOL followLinks)
5861
{
5862
    FILE_STAT_BASIC_INFORMATION info;
5863
    if (_Py_GetFileInformationByName(path, FileStatBasicByNameInfo, &info,
5864
                                     sizeof(info)))
5865
    {
5866
        if (!(info.FileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) ||
5867
            (!followLinks && IsReparseTagNameSurrogate(info.ReparseTag)))
5868
        {
5869
            return TRUE;
5870
        }
5871
    }
5872
    else if (_Py_GetFileInformationByName_ErrorIsTrustworthy(
5873
                    GetLastError()))
5874
    {
5875
        return FALSE;
5876
    }
5877
5878
    DWORD flags = FILE_FLAG_BACKUP_SEMANTICS;
5879
    if (!followLinks) {
5880
        flags |= FILE_FLAG_OPEN_REPARSE_POINT;
5881
    }
5882
    HANDLE hfile = CreateFileW(path, FILE_READ_ATTRIBUTES, 0, NULL,
5883
                               OPEN_EXISTING, flags, NULL);
5884
    if (hfile != INVALID_HANDLE_VALUE) {
5885
        if (followLinks) {
5886
            CloseHandle(hfile);
5887
            return TRUE;
5888
        }
5889
        // Regular Reparse Points (PY_IFRRP) have to be traversed.
5890
        BOOL result = _testFileTypeByHandle(hfile, PY_IFRRP, FALSE);
5891
        CloseHandle(hfile);
5892
        if (!result) {
5893
            return TRUE;
5894
        }
5895
        hfile = CreateFileW(path, FILE_READ_ATTRIBUTES, 0, NULL, OPEN_EXISTING,
5896
                            FILE_FLAG_BACKUP_SEMANTICS, NULL);
5897
        if (hfile != INVALID_HANDLE_VALUE) {
5898
            CloseHandle(hfile);
5899
            return TRUE;
5900
        }
5901
    }
5902
5903
    switch (GetLastError()) {
5904
    case ERROR_ACCESS_DENIED:
5905
    case ERROR_SHARING_VIOLATION:
5906
    case ERROR_CANT_ACCESS_FILE:
5907
    case ERROR_INVALID_PARAMETER:
5908
        STRUCT_STAT _st;
5909
        return followLinks ? !STAT(path, &_st): !LSTAT(path, &_st);
5910
    }
5911
5912
    return FALSE;
5913
}
5914
5915
5916
static BOOL
5917
_testFileExists(path_t *path, BOOL followLinks)
5918
{
5919
    BOOL result = FALSE;
5920
    if (path->value_error) {
5921
        return FALSE;
5922
    }
5923
5924
    Py_BEGIN_ALLOW_THREADS
5925
    if (path->is_fd) {
5926
        HANDLE hfile = _Py_get_osfhandle_noraise(path->fd);
5927
        if (hfile != INVALID_HANDLE_VALUE) {
5928
            if (GetFileType(hfile) != FILE_TYPE_UNKNOWN || !GetLastError()) {
5929
                result = TRUE;
5930
            }
5931
        }
5932
    }
5933
    else if (path->wide) {
5934
        result = _testFileExistsByName(path->wide, followLinks);
5935
    }
5936
    Py_END_ALLOW_THREADS
5937
5938
    return result;
5939
}
5940
5941
5942
static BOOL
5943
_testFileType(path_t *path, int testedType)
5944
{
5945
    BOOL result = FALSE;
5946
    if (path->value_error) {
5947
        return FALSE;
5948
    }
5949
5950
    Py_BEGIN_ALLOW_THREADS
5951
    if (path->is_fd) {
5952
        HANDLE hfile = _Py_get_osfhandle_noraise(path->fd);
5953
        if (hfile != INVALID_HANDLE_VALUE) {
5954
            result = _testFileTypeByHandle(hfile, testedType, TRUE);
5955
        }
5956
    }
5957
    else if (path->wide) {
5958
        result = _testFileTypeByName(path->wide, testedType);
5959
    }
5960
    Py_END_ALLOW_THREADS
5961
5962
    return result;
5963
}
5964
5965
5966
/*[clinic input]
5967
os._path_exists -> bool
5968
5969
    path: path_t(allow_fd=True, suppress_value_error=True)
5970
5971
Test whether a path exists.  Returns False for broken symbolic links.
5972
5973
[clinic start generated code]*/
5974
5975
static int
5976
os__path_exists_impl(PyObject *module, path_t *path)
5977
/*[clinic end generated code: output=8da13acf666e16ba input=142beabfc66783eb]*/
5978
{
5979
    return _testFileExists(path, TRUE);
5980
}
5981
5982
5983
/*[clinic input]
5984
os._path_lexists -> bool
5985
5986
    path: path_t(allow_fd=True, suppress_value_error=True)
5987
5988
Test whether a path exists.  Returns True for broken symbolic links.
5989
5990
[clinic start generated code]*/
5991
5992
static int
5993
os__path_lexists_impl(PyObject *module, path_t *path)
5994
/*[clinic end generated code: output=e7240ed5fc45bff3 input=208205112a3cc1ed]*/
5995
{
5996
    return _testFileExists(path, FALSE);
5997
}
5998
5999
6000
/*[clinic input]
6001
os._path_isdir -> bool
6002
6003
    path: path_t(allow_fd=True, suppress_value_error=True)
6004
    /
6005
6006
Return true if the pathname refers to an existing directory.
6007
6008
[clinic start generated code]*/
6009
6010
static int
6011
os__path_isdir_impl(PyObject *module, path_t *path)
6012
/*[clinic end generated code: output=d5786196f9e2fa7a input=b15f9b697a7a759f]*/
6013
{
6014
    return _testFileType(path, PY_IFDIR);
6015
}
6016
6017
6018
/*[clinic input]
6019
os._path_isfile -> bool
6020
6021
    path: path_t(allow_fd=True, suppress_value_error=True)
6022
6023
Test whether a path is a regular file
6024
6025
[clinic start generated code]*/
6026
6027
static int
6028
os__path_isfile_impl(PyObject *module, path_t *path)
6029
/*[clinic end generated code: output=5c3073bc212b9863 input=4ac1fd350b30a39e]*/
6030
{
6031
    return _testFileType(path, PY_IFREG);
6032
}
6033
6034
6035
/*[clinic input]
6036
os._path_islink -> bool
6037
6038
    path: path_t(allow_fd=True, suppress_value_error=True)
6039
6040
Test whether a path is a symbolic link
6041
6042
[clinic start generated code]*/
6043
6044
static int
6045
os__path_islink_impl(PyObject *module, path_t *path)
6046
/*[clinic end generated code: output=30da7bda8296adcc input=7510ce05b547debb]*/
6047
{
6048
    return _testFileType(path, PY_IFLNK);
6049
}
6050
6051
6052
/*[clinic input]
6053
os._path_isjunction -> bool
6054
6055
    path: path_t(allow_fd=True, suppress_value_error=True)
6056
6057
Test whether a path is a junction
6058
6059
[clinic start generated code]*/
6060
6061
static int
6062
os__path_isjunction_impl(PyObject *module, path_t *path)
6063
/*[clinic end generated code: output=e1d17a9dd18a9945 input=7dcb8bc4e972fcaf]*/
6064
{
6065
    return _testFileType(path, PY_IFMNT);
6066
}
6067
6068
#undef PY_IFREG
6069
#undef PY_IFDIR
6070
#undef PY_IFLNK
6071
#undef PY_IFMNT
6072
#undef PY_IFLRP
6073
#undef PY_IFRRP
6074
6075
#endif /* MS_WINDOWS */
6076
6077
6078
/*[clinic input]
6079
os._path_splitroot_ex
6080
6081
    path: path_t(make_wide=True, nonstrict=True)
6082
    /
6083
6084
Split a pathname into drive, root and tail.
6085
6086
The tail contains anything after the root.
6087
[clinic start generated code]*/
6088
6089
static PyObject *
6090
os__path_splitroot_ex_impl(PyObject *module, path_t *path)
6091
/*[clinic end generated code: output=4b0072b6cdf4b611 input=012fbfad14888b2b]*/
6092
146k
{
6093
146k
    Py_ssize_t drvsize, rootsize;
6094
146k
    PyObject *drv = NULL, *root = NULL, *tail = NULL, *result = NULL;
6095
6096
146k
    const wchar_t *buffer = path->wide;
6097
146k
    _Py_skiproot(buffer, path->length, &drvsize, &rootsize);
6098
146k
    drv = PyUnicode_FromWideChar(buffer, drvsize);
6099
146k
    if (drv == NULL) {
6100
0
        goto exit;
6101
0
    }
6102
146k
    root = PyUnicode_FromWideChar(&buffer[drvsize], rootsize);
6103
146k
    if (root == NULL) {
6104
0
        goto exit;
6105
0
    }
6106
146k
    tail = PyUnicode_FromWideChar(&buffer[drvsize + rootsize],
6107
146k
                                  path->length - drvsize - rootsize);
6108
146k
    if (tail == NULL) {
6109
0
        goto exit;
6110
0
    }
6111
146k
    if (PyBytes_Check(path->object)) {
6112
0
        Py_SETREF(drv, PyUnicode_EncodeFSDefault(drv));
6113
0
        if (drv == NULL) {
6114
0
            goto exit;
6115
0
        }
6116
0
        Py_SETREF(root, PyUnicode_EncodeFSDefault(root));
6117
0
        if (root == NULL) {
6118
0
            goto exit;
6119
0
        }
6120
0
        Py_SETREF(tail, PyUnicode_EncodeFSDefault(tail));
6121
0
        if (tail == NULL) {
6122
0
            goto exit;
6123
0
        }
6124
0
    }
6125
146k
    result = PyTuple_Pack(3, drv, root, tail);
6126
146k
exit:
6127
146k
    Py_XDECREF(drv);
6128
146k
    Py_XDECREF(root);
6129
146k
    Py_XDECREF(tail);
6130
146k
    return result;
6131
146k
}
6132
6133
6134
/*[clinic input]
6135
os._path_normpath
6136
6137
    path: path_t(make_wide=True, nonstrict=True)
6138
6139
Normalize path, eliminating double slashes, etc.
6140
[clinic start generated code]*/
6141
6142
static PyObject *
6143
os__path_normpath_impl(PyObject *module, path_t *path)
6144
/*[clinic end generated code: output=d353e7ed9410c044 input=3d4ac23b06332dcb]*/
6145
28.8k
{
6146
28.8k
    PyObject *result;
6147
28.8k
    Py_ssize_t norm_len;
6148
28.8k
    wchar_t *norm_path = _Py_normpath_and_size((wchar_t *)path->wide,
6149
28.8k
                                               path->length, &norm_len);
6150
28.8k
    if (!norm_len) {
6151
0
        result = PyUnicode_FromOrdinal('.');
6152
0
    }
6153
28.8k
    else {
6154
28.8k
        result = PyUnicode_FromWideChar(norm_path, norm_len);
6155
28.8k
    }
6156
28.8k
    if (result == NULL) {
6157
0
        return NULL;
6158
0
    }
6159
28.8k
    if (PyBytes_Check(path->object)) {
6160
0
        Py_SETREF(result, PyUnicode_EncodeFSDefault(result));
6161
0
    }
6162
28.8k
    return result;
6163
28.8k
}
6164
6165
/*[clinic input]
6166
os.mkdir
6167
6168
    path : path_t
6169
6170
    mode: int = 0o777
6171
6172
    *
6173
6174
    dir_fd : dir_fd(requires='mkdirat') = None
6175
6176
Create a directory.
6177
6178
If dir_fd is not None, it should be a file descriptor open to
6179
a directory, and path should be relative; path will then be relative to
6180
that directory.
6181
dir_fd may not be implemented on your platform.  If it is unavailable,
6182
using it will raise a NotImplementedError.
6183
6184
The mode argument is ignored on Windows.  Where it is used, the current
6185
umask value is first masked out.
6186
[clinic start generated code]*/
6187
6188
static PyObject *
6189
os_mkdir_impl(PyObject *module, path_t *path, int mode, int dir_fd)
6190
/*[clinic end generated code: output=a70446903abe821f input=30270d369599634b]*/
6191
102k
{
6192
102k
    int result;
6193
#ifdef MS_WINDOWS
6194
    int error = 0;
6195
    SECURITY_ATTRIBUTES secAttr = { sizeof(secAttr) };
6196
    SECURITY_ATTRIBUTES *pSecAttr = NULL;
6197
#endif
6198
102k
#ifdef HAVE_MKDIRAT
6199
102k
    int mkdirat_unavailable = 0;
6200
102k
#endif
6201
6202
102k
    if (PySys_Audit("os.mkdir", "Oii", path->object, mode,
6203
102k
                    dir_fd == DEFAULT_DIR_FD ? -1 : dir_fd) < 0) {
6204
0
        return NULL;
6205
0
    }
6206
6207
#ifdef MS_WINDOWS
6208
    Py_BEGIN_ALLOW_THREADS
6209
    // For API sets that don't support these APIs, we have no choice
6210
    // but to silently create a directory with default ACL.
6211
#if defined(MS_WINDOWS_APP) || defined(MS_WINDOWS_SYSTEM)
6212
    if (mode == 0700 /* 0o700 */) {
6213
        ULONG sdSize;
6214
        pSecAttr = &secAttr;
6215
        // Set a discretionary ACL (D) that is protected (P) and includes
6216
        // inheritable (OICI) entries that allow (A) full control (FA) to
6217
        // SYSTEM (SY), Administrators (BA), and the owner (OW).
6218
        if (!ConvertStringSecurityDescriptorToSecurityDescriptorW(
6219
            L"D:P(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)(A;OICI;FA;;;OW)",
6220
            SDDL_REVISION_1,
6221
            &secAttr.lpSecurityDescriptor,
6222
            &sdSize
6223
        )) {
6224
            error = GetLastError();
6225
        }
6226
    }
6227
#endif
6228
    if (!error) {
6229
        result = CreateDirectoryW(path->wide, pSecAttr);
6230
        if (secAttr.lpSecurityDescriptor &&
6231
            // uncommonly, LocalFree returns non-zero on error, but still uses
6232
            // GetLastError() to see what the error code is
6233
            LocalFree(secAttr.lpSecurityDescriptor)) {
6234
            error = GetLastError();
6235
        }
6236
    }
6237
    Py_END_ALLOW_THREADS
6238
6239
    if (error) {
6240
        return PyErr_SetFromWindowsErr(error);
6241
    }
6242
    if (!result) {
6243
        return path_error(path);
6244
    }
6245
#else
6246
102k
    Py_BEGIN_ALLOW_THREADS
6247
102k
#if HAVE_MKDIRAT
6248
102k
    if (dir_fd != DEFAULT_DIR_FD) {
6249
0
      if (HAVE_MKDIRAT_RUNTIME) {
6250
0
        result = mkdirat(dir_fd, path->narrow, mode);
6251
6252
0
      } else {
6253
0
        mkdirat_unavailable = 1;
6254
0
      }
6255
0
    } else
6256
102k
#endif
6257
#if defined(__WATCOMC__) && !defined(__QNX__)
6258
        result = mkdir(path->narrow);
6259
#else
6260
102k
        result = mkdir(path->narrow, mode);
6261
102k
#endif
6262
102k
    Py_END_ALLOW_THREADS
6263
6264
102k
#if HAVE_MKDIRAT
6265
102k
    if (mkdirat_unavailable) {
6266
0
        argument_unavailable_error(NULL, "dir_fd");
6267
0
        return NULL;
6268
0
    }
6269
102k
#endif
6270
6271
102k
    if (result < 0)
6272
413
        return path_error(path);
6273
101k
#endif /* MS_WINDOWS */
6274
102k
    Py_RETURN_NONE;
6275
102k
}
6276
6277
6278
/* sys/resource.h is needed for at least: wait3(), wait4(), broken nice. */
6279
#if defined(HAVE_SYS_RESOURCE_H)
6280
#include <sys/resource.h>
6281
#endif
6282
6283
6284
#ifdef HAVE_NICE
6285
/*[clinic input]
6286
os.nice
6287
6288
    increment: int
6289
    /
6290
6291
Add increment to the priority of process and return the new priority.
6292
[clinic start generated code]*/
6293
6294
static PyObject *
6295
os_nice_impl(PyObject *module, int increment)
6296
/*[clinic end generated code: output=9dad8a9da8109943 input=864be2d402a21da2]*/
6297
0
{
6298
0
    int value;
6299
6300
    /* There are two flavours of 'nice': one that returns the new
6301
       priority (as required by almost all standards out there) and the
6302
       Linux/FreeBSD one, which returns '0' on success and advices
6303
       the use of getpriority() to get the new priority.
6304
6305
       If we are of the nice family that returns the new priority, we
6306
       need to clear errno before the call, and check if errno is filled
6307
       before calling posix_error() on a returnvalue of -1, because the
6308
       -1 may be the actual new priority! */
6309
6310
0
    errno = 0;
6311
0
    value = nice(increment);
6312
#if defined(HAVE_BROKEN_NICE) && defined(HAVE_GETPRIORITY)
6313
    if (value == 0)
6314
        value = getpriority(PRIO_PROCESS, 0);
6315
#endif
6316
0
    if (value == -1 && errno != 0)
6317
        /* either nice() or getpriority() returned an error */
6318
0
        return posix_error();
6319
0
    return PyLong_FromLong((long) value);
6320
0
}
6321
#endif /* HAVE_NICE */
6322
6323
6324
#ifdef HAVE_GETPRIORITY
6325
/*[clinic input]
6326
os.getpriority
6327
6328
    which: int
6329
    who: int
6330
6331
Return program scheduling priority.
6332
[clinic start generated code]*/
6333
6334
static PyObject *
6335
os_getpriority_impl(PyObject *module, int which, int who)
6336
/*[clinic end generated code: output=c41b7b63c7420228 input=9be615d40e2544ef]*/
6337
0
{
6338
0
    int retval;
6339
6340
0
    errno = 0;
6341
0
    retval = getpriority(which, who);
6342
0
    if (errno != 0)
6343
0
        return posix_error();
6344
0
    return PyLong_FromLong((long)retval);
6345
0
}
6346
#endif /* HAVE_GETPRIORITY */
6347
6348
6349
#ifdef HAVE_SETPRIORITY
6350
/*[clinic input]
6351
os.setpriority
6352
6353
    which: int
6354
    who: int
6355
    priority: int
6356
6357
Set program scheduling priority.
6358
[clinic start generated code]*/
6359
6360
static PyObject *
6361
os_setpriority_impl(PyObject *module, int which, int who, int priority)
6362
/*[clinic end generated code: output=3d910d95a7771eb2 input=710ccbf65b9dc513]*/
6363
0
{
6364
0
    int retval;
6365
6366
0
    retval = setpriority(which, who, priority);
6367
0
    if (retval == -1)
6368
0
        return posix_error();
6369
0
    Py_RETURN_NONE;
6370
0
}
6371
#endif /* HAVE_SETPRIORITY */
6372
6373
6374
static PyObject *
6375
internal_rename(path_t *src, path_t *dst, int src_dir_fd, int dst_dir_fd, int is_replace)
6376
141
{
6377
141
    const char *function_name = is_replace ? "replace" : "rename";
6378
141
    int dir_fd_specified;
6379
6380
141
#ifdef HAVE_RENAMEAT
6381
141
    int renameat_unavailable = 0;
6382
141
#endif
6383
6384
#ifdef MS_WINDOWS
6385
    BOOL result;
6386
    int flags = is_replace ? MOVEFILE_REPLACE_EXISTING : 0;
6387
#else
6388
141
    int result;
6389
141
#endif
6390
6391
141
    dir_fd_specified = (src_dir_fd != DEFAULT_DIR_FD) ||
6392
141
                       (dst_dir_fd != DEFAULT_DIR_FD);
6393
#ifndef HAVE_RENAMEAT
6394
    if (dir_fd_specified) {
6395
        argument_unavailable_error(function_name, "src_dir_fd and dst_dir_fd");
6396
        return NULL;
6397
    }
6398
#endif
6399
6400
141
    if (PySys_Audit("os.rename", "OOii", src->object, dst->object,
6401
141
                    src_dir_fd == DEFAULT_DIR_FD ? -1 : src_dir_fd,
6402
141
                    dst_dir_fd == DEFAULT_DIR_FD ? -1 : dst_dir_fd) < 0) {
6403
0
        return NULL;
6404
0
    }
6405
6406
#ifdef MS_WINDOWS
6407
    Py_BEGIN_ALLOW_THREADS
6408
    result = MoveFileExW(src->wide, dst->wide, flags);
6409
    Py_END_ALLOW_THREADS
6410
6411
    if (!result)
6412
        return path_error2(src, dst);
6413
6414
#else
6415
141
    Py_BEGIN_ALLOW_THREADS
6416
141
#ifdef HAVE_RENAMEAT
6417
141
    if (dir_fd_specified) {
6418
0
        if (HAVE_RENAMEAT_RUNTIME) {
6419
0
            result = renameat(src_dir_fd, src->narrow, dst_dir_fd, dst->narrow);
6420
0
        } else {
6421
0
            renameat_unavailable = 1;
6422
0
        }
6423
0
    } else
6424
141
#endif
6425
141
    result = rename(src->narrow, dst->narrow);
6426
141
    Py_END_ALLOW_THREADS
6427
6428
6429
141
#ifdef HAVE_RENAMEAT
6430
141
    if (renameat_unavailable) {
6431
0
        argument_unavailable_error(function_name, "src_dir_fd and dst_dir_fd");
6432
0
        return NULL;
6433
0
    }
6434
141
#endif
6435
6436
141
    if (result)
6437
0
        return path_error2(src, dst);
6438
141
#endif
6439
141
    Py_RETURN_NONE;
6440
141
}
6441
6442
6443
/*[clinic input]
6444
os.rename
6445
6446
    src : path_t
6447
    dst : path_t
6448
    *
6449
    src_dir_fd : dir_fd = None
6450
    dst_dir_fd : dir_fd = None
6451
6452
Rename a file or directory.
6453
6454
If either src_dir_fd or dst_dir_fd is not None, it should be a file
6455
descriptor open to a directory, and the respective path string (src or
6456
dst) should be relative; the path will then be relative to that
6457
directory.
6458
src_dir_fd and dst_dir_fd, may not be implemented on your platform.
6459
If they are unavailable, using them will raise a NotImplementedError.
6460
[clinic start generated code]*/
6461
6462
static PyObject *
6463
os_rename_impl(PyObject *module, path_t *src, path_t *dst, int src_dir_fd,
6464
               int dst_dir_fd)
6465
/*[clinic end generated code: output=59e803072cf41230 input=7d320d687c715fd6]*/
6466
5
{
6467
5
    return internal_rename(src, dst, src_dir_fd, dst_dir_fd, 0);
6468
5
}
6469
6470
6471
/*[clinic input]
6472
os.replace = os.rename
6473
6474
Rename a file or directory, overwriting the destination.
6475
6476
If either src_dir_fd or dst_dir_fd is not None, it should be a file
6477
descriptor open to a directory, and the respective path string (src or
6478
dst) should be relative; the path will then be relative to that
6479
directory.
6480
src_dir_fd and dst_dir_fd, may not be implemented on your platform.
6481
If they are unavailable, using them will raise a NotImplementedError.
6482
[clinic start generated code]*/
6483
6484
static PyObject *
6485
os_replace_impl(PyObject *module, path_t *src, path_t *dst, int src_dir_fd,
6486
                int dst_dir_fd)
6487
/*[clinic end generated code: output=1968c02e7857422b input=44ed6b762d5953fc]*/
6488
136
{
6489
136
    return internal_rename(src, dst, src_dir_fd, dst_dir_fd, 1);
6490
136
}
6491
6492
6493
/*[clinic input]
6494
os.rmdir
6495
6496
    path: path_t
6497
    *
6498
    dir_fd: dir_fd(requires='unlinkat') = None
6499
6500
Remove a directory.
6501
6502
If dir_fd is not None, it should be a file descriptor open to
6503
a directory, and path should be relative; path will then be relative
6504
to that directory.
6505
dir_fd may not be implemented on your platform.
6506
If it is unavailable, using it will raise a NotImplementedError.
6507
[clinic start generated code]*/
6508
6509
static PyObject *
6510
os_rmdir_impl(PyObject *module, path_t *path, int dir_fd)
6511
/*[clinic end generated code: output=080eb54f506e8301 input=84325211e33a98e0]*/
6512
101k
{
6513
101k
    int result;
6514
101k
#ifdef HAVE_UNLINKAT
6515
101k
    int unlinkat_unavailable = 0;
6516
101k
#endif
6517
6518
101k
    if (PySys_Audit("os.rmdir", "Oi", path->object,
6519
101k
                    dir_fd == DEFAULT_DIR_FD ? -1 : dir_fd) < 0) {
6520
0
        return NULL;
6521
0
    }
6522
6523
101k
    Py_BEGIN_ALLOW_THREADS
6524
#ifdef MS_WINDOWS
6525
    /* Windows, success=1, UNIX, success=0 */
6526
    result = !RemoveDirectoryW(path->wide);
6527
#else
6528
101k
#ifdef HAVE_UNLINKAT
6529
101k
    if (dir_fd != DEFAULT_DIR_FD) {
6530
97.0k
      if (HAVE_UNLINKAT_RUNTIME) {
6531
97.0k
        result = unlinkat(dir_fd, path->narrow, AT_REMOVEDIR);
6532
97.0k
      } else {
6533
0
        unlinkat_unavailable = 1;
6534
0
        result = -1;
6535
0
      }
6536
97.0k
    } else
6537
4.51k
#endif
6538
4.51k
        result = rmdir(path->narrow);
6539
101k
#endif
6540
101k
    Py_END_ALLOW_THREADS
6541
6542
101k
#ifdef HAVE_UNLINKAT
6543
101k
    if (unlinkat_unavailable) {
6544
0
        argument_unavailable_error("rmdir", "dir_fd");
6545
0
        return NULL;
6546
0
    }
6547
101k
#endif
6548
6549
101k
    if (result)
6550
5
        return path_error(path);
6551
6552
101k
    Py_RETURN_NONE;
6553
101k
}
6554
6555
6556
#ifdef HAVE_SYSTEM
6557
#ifdef MS_WINDOWS
6558
/*[clinic input]
6559
os.system -> long
6560
6561
    command: Py_UNICODE
6562
6563
Execute the command in a subshell.
6564
[clinic start generated code]*/
6565
6566
static long
6567
os_system_impl(PyObject *module, const wchar_t *command)
6568
/*[clinic end generated code: output=dd528cbd5943a679 input=303f5ce97df606b0]*/
6569
{
6570
    long result;
6571
6572
    if (PySys_Audit("os.system", "(u)", command) < 0) {
6573
        return -1;
6574
    }
6575
6576
    Py_BEGIN_ALLOW_THREADS
6577
    _Py_BEGIN_SUPPRESS_IPH
6578
    result = _wsystem(command);
6579
    _Py_END_SUPPRESS_IPH
6580
    Py_END_ALLOW_THREADS
6581
    return result;
6582
}
6583
#else /* MS_WINDOWS */
6584
/*[clinic input]
6585
os.system -> long
6586
6587
    command: unicode_fs_encoded
6588
6589
Execute the command in a subshell.
6590
[clinic start generated code]*/
6591
6592
static long
6593
os_system_impl(PyObject *module, PyObject *command)
6594
/*[clinic end generated code: output=290fc437dd4f33a0 input=47c6f24b6dc92881]*/
6595
0
{
6596
0
    long result;
6597
0
    const char *bytes = PyBytes_AsString(command);
6598
6599
0
    if (PySys_Audit("os.system", "(O)", command) < 0) {
6600
0
        return -1;
6601
0
    }
6602
6603
0
    Py_BEGIN_ALLOW_THREADS
6604
0
    result = system(bytes);
6605
0
    Py_END_ALLOW_THREADS
6606
0
    return result;
6607
0
}
6608
#endif
6609
#endif /* HAVE_SYSTEM */
6610
6611
6612
#ifdef HAVE_UMASK
6613
/*[clinic input]
6614
os.umask
6615
6616
    mask: int
6617
    /
6618
6619
Set the current numeric umask and return the previous umask.
6620
[clinic start generated code]*/
6621
6622
static PyObject *
6623
os_umask_impl(PyObject *module, int mask)
6624
/*[clinic end generated code: output=a2e33ce3bc1a6e33 input=ab6bfd9b24d8a7e8]*/
6625
0
{
6626
0
    int i = (int)umask(mask);
6627
0
    if (i < 0)
6628
0
        return posix_error();
6629
0
    return PyLong_FromLong((long)i);
6630
0
}
6631
#endif
6632
6633
#ifdef MS_WINDOWS
6634
6635
/* override the default DeleteFileW behavior so that directory
6636
symlinks can be removed with this function, the same as with
6637
Unix symlinks */
6638
BOOL WINAPI Py_DeleteFileW(LPCWSTR lpFileName)
6639
{
6640
    WIN32_FILE_ATTRIBUTE_DATA info;
6641
    WIN32_FIND_DATAW find_data;
6642
    HANDLE find_data_handle;
6643
    int is_directory = 0;
6644
    int is_link = 0;
6645
6646
    if (GetFileAttributesExW(lpFileName, GetFileExInfoStandard, &info)) {
6647
        is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
6648
6649
        /* Get WIN32_FIND_DATA structure for the path to determine if
6650
           it is a symlink */
6651
        if(is_directory &&
6652
           info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
6653
            find_data_handle = FindFirstFileW(lpFileName, &find_data);
6654
6655
            if(find_data_handle != INVALID_HANDLE_VALUE) {
6656
                /* IO_REPARSE_TAG_SYMLINK if it is a symlink and
6657
                   IO_REPARSE_TAG_MOUNT_POINT if it is a junction point. */
6658
                is_link = find_data.dwReserved0 == IO_REPARSE_TAG_SYMLINK ||
6659
                          find_data.dwReserved0 == IO_REPARSE_TAG_MOUNT_POINT;
6660
                FindClose(find_data_handle);
6661
            }
6662
        }
6663
    }
6664
6665
    if (is_directory && is_link)
6666
        return RemoveDirectoryW(lpFileName);
6667
6668
    return DeleteFileW(lpFileName);
6669
}
6670
#endif /* MS_WINDOWS */
6671
6672
6673
/*[clinic input]
6674
os.unlink
6675
6676
    path: path_t
6677
    *
6678
    dir_fd: dir_fd(requires='unlinkat')=None
6679
6680
Remove a file (same as remove()).
6681
6682
If dir_fd is not None, it should be a file descriptor open to
6683
a directory, and path should be relative; path will then be relative to
6684
that directory.
6685
dir_fd may not be implemented on your platform.
6686
If it is unavailable, using it will raise a NotImplementedError.
6687
6688
[clinic start generated code]*/
6689
6690
static PyObject *
6691
os_unlink_impl(PyObject *module, path_t *path, int dir_fd)
6692
/*[clinic end generated code: output=621797807b9963b1 input=1a2ef2579207eab1]*/
6693
19.7k
{
6694
19.7k
    int result;
6695
19.7k
#ifdef HAVE_UNLINKAT
6696
19.7k
    int unlinkat_unavailable = 0;
6697
19.7k
#endif
6698
6699
19.7k
    if (PySys_Audit("os.remove", "Oi", path->object,
6700
19.7k
                    dir_fd == DEFAULT_DIR_FD ? -1 : dir_fd) < 0) {
6701
0
        return NULL;
6702
0
    }
6703
6704
19.7k
    Py_BEGIN_ALLOW_THREADS
6705
19.7k
    _Py_BEGIN_SUPPRESS_IPH
6706
#ifdef MS_WINDOWS
6707
    /* Windows, success=1, UNIX, success=0 */
6708
    result = !Py_DeleteFileW(path->wide);
6709
#else
6710
19.7k
#ifdef HAVE_UNLINKAT
6711
19.7k
    if (dir_fd != DEFAULT_DIR_FD) {
6712
19.7k
      if (HAVE_UNLINKAT_RUNTIME) {
6713
6714
19.7k
        result = unlinkat(dir_fd, path->narrow, 0);
6715
19.7k
      } else {
6716
0
        unlinkat_unavailable = 1;
6717
0
      }
6718
19.7k
    } else
6719
2
#endif /* HAVE_UNLINKAT */
6720
2
        result = unlink(path->narrow);
6721
19.7k
#endif
6722
19.7k
    _Py_END_SUPPRESS_IPH
6723
19.7k
    Py_END_ALLOW_THREADS
6724
6725
19.7k
#ifdef HAVE_UNLINKAT
6726
19.7k
    if (unlinkat_unavailable) {
6727
0
        argument_unavailable_error(NULL, "dir_fd");
6728
0
        return NULL;
6729
0
    }
6730
19.7k
#endif
6731
6732
19.7k
    if (result)
6733
0
        return path_error(path);
6734
6735
19.7k
    Py_RETURN_NONE;
6736
19.7k
}
6737
6738
6739
/*[clinic input]
6740
os.remove = os.unlink
6741
6742
Remove a file (same as unlink()).
6743
6744
If dir_fd is not None, it should be a file descriptor open to
6745
a directory, and path should be relative; path will then be relative
6746
to that directory.
6747
dir_fd may not be implemented on your platform.
6748
If it is unavailable, using it will raise a NotImplementedError.
6749
[clinic start generated code]*/
6750
6751
static PyObject *
6752
os_remove_impl(PyObject *module, path_t *path, int dir_fd)
6753
/*[clinic end generated code: output=a8535b28f0068883 input=9f6e66912126bd56]*/
6754
0
{
6755
0
    return os_unlink_impl(module, path, dir_fd);
6756
0
}
6757
6758
6759
static PyStructSequence_Field uname_result_fields[] = {
6760
    {"sysname",    "operating system name"},
6761
    {"nodename",   "name of machine on network (implementation-defined)"},
6762
    {"release",    "operating system release"},
6763
    {"version",    "operating system version"},
6764
    {"machine",    "hardware identifier"},
6765
    {NULL}
6766
};
6767
6768
PyDoc_STRVAR(uname_result__doc__,
6769
"uname_result: Result from os.uname().\n\n\
6770
This object may be accessed either as a tuple of\n\
6771
  (sysname, nodename, release, version, machine),\n\
6772
or via the attributes sysname, nodename, release, version, and machine.\n\
6773
\n\
6774
See os.uname for more information.");
6775
6776
static PyStructSequence_Desc uname_result_desc = {
6777
    "os.uname_result", /* name */
6778
    uname_result__doc__, /* doc */
6779
    uname_result_fields,
6780
    5
6781
};
6782
6783
#ifdef HAVE_UNAME
6784
/*[clinic input]
6785
os.uname
6786
6787
Return an object identifying the current operating system.
6788
6789
The object behaves like a named tuple with the following fields:
6790
  (sysname, nodename, release, version, machine)
6791
6792
[clinic start generated code]*/
6793
6794
static PyObject *
6795
os_uname_impl(PyObject *module)
6796
/*[clinic end generated code: output=e6a49cf1a1508a19 input=e68bd246db3043ed]*/
6797
4
{
6798
4
    struct utsname u;
6799
4
    int res;
6800
4
    PyObject *value;
6801
6802
4
    Py_BEGIN_ALLOW_THREADS
6803
4
    res = uname(&u);
6804
4
    Py_END_ALLOW_THREADS
6805
4
    if (res < 0)
6806
0
        return posix_error();
6807
6808
4
    PyObject *UnameResultType = get_posix_state(module)->UnameResultType;
6809
4
    value = PyStructSequence_New((PyTypeObject *)UnameResultType);
6810
4
    if (value == NULL)
6811
0
        return NULL;
6812
6813
4
#define SET(i, field) \
6814
20
    { \
6815
20
    PyObject *o = PyUnicode_DecodeFSDefault(field); \
6816
20
    if (!o) { \
6817
0
        Py_DECREF(value); \
6818
0
        return NULL; \
6819
0
    } \
6820
20
    PyStructSequence_SET_ITEM(value, i, o); \
6821
20
    } \
6822
4
6823
8
    SET(0, u.sysname);
6824
8
    SET(1, u.nodename);
6825
4
    SET(2, u.release);
6826
4
    SET(3, u.version);
6827
4
    SET(4, u.machine);
6828
6829
4
#undef SET
6830
6831
4
    return value;
6832
4
}
6833
#endif /* HAVE_UNAME */
6834
6835
6836
6837
typedef struct {
6838
    int    now;
6839
    time_t atime_s;
6840
    long   atime_ns;
6841
    time_t mtime_s;
6842
    long   mtime_ns;
6843
} utime_t;
6844
6845
/*
6846
 * these macros assume that "ut" is a pointer to a utime_t
6847
 * they also intentionally leak the declaration of a pointer named "time"
6848
 */
6849
#define UTIME_TO_TIMESPEC \
6850
0
    struct timespec ts[2]; \
6851
0
    struct timespec *time; \
6852
0
    if (ut->now) \
6853
0
        time = NULL; \
6854
0
    else { \
6855
0
        ts[0].tv_sec = ut->atime_s; \
6856
0
        ts[0].tv_nsec = ut->atime_ns; \
6857
0
        ts[1].tv_sec = ut->mtime_s; \
6858
0
        ts[1].tv_nsec = ut->mtime_ns; \
6859
0
        time = ts; \
6860
0
    } \
6861
6862
#define UTIME_TO_TIMEVAL \
6863
0
    struct timeval tv[2]; \
6864
0
    struct timeval *time; \
6865
0
    if (ut->now) \
6866
0
        time = NULL; \
6867
0
    else { \
6868
0
        tv[0].tv_sec = ut->atime_s; \
6869
0
        tv[0].tv_usec = ut->atime_ns / 1000; \
6870
0
        tv[1].tv_sec = ut->mtime_s; \
6871
0
        tv[1].tv_usec = ut->mtime_ns / 1000; \
6872
0
        time = tv; \
6873
0
    } \
6874
6875
#define UTIME_TO_UTIMBUF \
6876
    struct utimbuf u; \
6877
    struct utimbuf *time; \
6878
    if (ut->now) \
6879
        time = NULL; \
6880
    else { \
6881
        u.actime = ut->atime_s; \
6882
        u.modtime = ut->mtime_s; \
6883
        time = &u; \
6884
    }
6885
6886
#define UTIME_TO_TIME_T \
6887
    time_t timet[2]; \
6888
    time_t *time; \
6889
    if (ut->now) \
6890
        time = NULL; \
6891
    else { \
6892
        timet[0] = ut->atime_s; \
6893
        timet[1] = ut->mtime_s; \
6894
        time = timet; \
6895
    } \
6896
6897
6898
#if defined(HAVE_FUTIMESAT) || defined(HAVE_UTIMENSAT)
6899
6900
static int
6901
utime_dir_fd(utime_t *ut, int dir_fd, const char *path, int follow_symlinks)
6902
0
{
6903
#if defined(__APPLE__) &&  defined(HAVE_UTIMENSAT)
6904
    if (HAVE_UTIMENSAT_RUNTIME) {
6905
        int flags = follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW;
6906
        UTIME_TO_TIMESPEC;
6907
        return utimensat(dir_fd, path, time, flags);
6908
    }  else {
6909
        errno = ENOSYS;
6910
        return -1;
6911
    }
6912
#elif defined(HAVE_UTIMENSAT)
6913
0
    int flags = follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW;
6914
0
    UTIME_TO_TIMESPEC;
6915
0
    return utimensat(dir_fd, path, time, flags);
6916
#elif defined(HAVE_FUTIMESAT)
6917
    UTIME_TO_TIMEVAL;
6918
    /*
6919
     * follow_symlinks will never be false here;
6920
     * we only allow !follow_symlinks and dir_fd together
6921
     * if we have utimensat()
6922
     */
6923
    assert(follow_symlinks);
6924
    return futimesat(dir_fd, path, time);
6925
#endif
6926
0
}
6927
6928
0
    #define FUTIMENSAT_DIR_FD_CONVERTER dir_fd_converter
6929
#else
6930
    #define FUTIMENSAT_DIR_FD_CONVERTER dir_fd_unavailable
6931
#endif
6932
6933
#if defined(HAVE_FUTIMES) || defined(HAVE_FUTIMENS)
6934
6935
static int
6936
utime_fd(utime_t *ut, int fd)
6937
0
{
6938
0
#ifdef HAVE_FUTIMENS
6939
6940
0
    if (HAVE_FUTIMENS_RUNTIME) {
6941
6942
0
    UTIME_TO_TIMESPEC;
6943
0
    return futimens(fd, time);
6944
6945
0
    } else
6946
#ifndef HAVE_FUTIMES
6947
    {
6948
        /* Not sure if this can happen */
6949
        PyErr_SetString(
6950
            PyExc_RuntimeError,
6951
            "neither futimens nor futimes are supported"
6952
            " on this system");
6953
        return -1;
6954
    }
6955
#endif
6956
6957
0
#endif
6958
0
#ifdef HAVE_FUTIMES
6959
0
    {
6960
0
    UTIME_TO_TIMEVAL;
6961
0
    return futimes(fd, time);
6962
0
    }
6963
0
#endif
6964
0
}
6965
6966
    #define PATH_UTIME_HAVE_FD 1
6967
#else
6968
    #define PATH_UTIME_HAVE_FD 0
6969
#endif
6970
6971
#if defined(HAVE_UTIMENSAT) || defined(HAVE_LUTIMES)
6972
#  define UTIME_HAVE_NOFOLLOW_SYMLINKS
6973
#endif
6974
6975
#ifdef UTIME_HAVE_NOFOLLOW_SYMLINKS
6976
6977
static int
6978
utime_nofollow_symlinks(utime_t *ut, const char *path)
6979
0
{
6980
0
#ifdef HAVE_UTIMENSAT
6981
0
    if (HAVE_UTIMENSAT_RUNTIME) {
6982
0
        UTIME_TO_TIMESPEC;
6983
0
        return utimensat(DEFAULT_DIR_FD, path, time, AT_SYMLINK_NOFOLLOW);
6984
0
    } else
6985
#ifndef HAVE_LUTIMES
6986
    {
6987
        /* Not sure if this can happen */
6988
        PyErr_SetString(
6989
            PyExc_RuntimeError,
6990
            "neither utimensat nor lutimes are supported"
6991
            " on this system");
6992
        return -1;
6993
    }
6994
#endif
6995
0
#endif
6996
6997
0
#ifdef HAVE_LUTIMES
6998
0
    {
6999
0
    UTIME_TO_TIMEVAL;
7000
0
    return lutimes(path, time);
7001
0
    }
7002
0
#endif
7003
0
}
7004
7005
#endif
7006
7007
#ifndef MS_WINDOWS
7008
7009
static int
7010
utime_default(utime_t *ut, const char *path)
7011
0
{
7012
#if defined(__APPLE__) && defined(HAVE_UTIMENSAT)
7013
    if (HAVE_UTIMENSAT_RUNTIME) {
7014
        UTIME_TO_TIMESPEC;
7015
        return utimensat(DEFAULT_DIR_FD, path, time, 0);
7016
    } else {
7017
        UTIME_TO_TIMEVAL;
7018
        return utimes(path, time);
7019
    }
7020
#elif defined(HAVE_UTIMENSAT)
7021
0
    UTIME_TO_TIMESPEC;
7022
0
    return utimensat(DEFAULT_DIR_FD, path, time, 0);
7023
#elif defined(HAVE_UTIMES)
7024
    UTIME_TO_TIMEVAL;
7025
    return utimes(path, time);
7026
#elif defined(HAVE_UTIME_H)
7027
    UTIME_TO_UTIMBUF;
7028
    return utime(path, time);
7029
#else
7030
    UTIME_TO_TIME_T;
7031
    return utime(path, time);
7032
#endif
7033
0
}
7034
7035
#endif
7036
7037
static int
7038
split_py_long_to_s_and_ns(PyObject *module, PyObject *py_long, time_t *s, long *ns)
7039
0
{
7040
0
    int result = 0;
7041
0
    PyObject *divmod;
7042
0
    divmod = PyNumber_Divmod(py_long, get_posix_state(module)->billion);
7043
0
    if (!divmod)
7044
0
        goto exit;
7045
0
    if (!PyTuple_Check(divmod) || PyTuple_GET_SIZE(divmod) != 2) {
7046
0
        PyErr_Format(PyExc_TypeError,
7047
0
                     "%.200s.__divmod__() must return a 2-tuple, not %.200s",
7048
0
                     _PyType_Name(Py_TYPE(py_long)), _PyType_Name(Py_TYPE(divmod)));
7049
0
        goto exit;
7050
0
    }
7051
0
    *s = _PyLong_AsTime_t(PyTuple_GET_ITEM(divmod, 0));
7052
0
    if ((*s == -1) && PyErr_Occurred())
7053
0
        goto exit;
7054
0
    *ns = PyLong_AsLong(PyTuple_GET_ITEM(divmod, 1));
7055
0
    if ((*ns == -1) && PyErr_Occurred())
7056
0
        goto exit;
7057
7058
0
    result = 1;
7059
0
exit:
7060
0
    Py_XDECREF(divmod);
7061
0
    return result;
7062
0
}
7063
7064
7065
/*[clinic input]
7066
os.utime
7067
7068
    path: path_t(allow_fd='PATH_UTIME_HAVE_FD')
7069
    times: object = None
7070
    *
7071
    ns: object = NULL
7072
    dir_fd: dir_fd(requires='futimensat') = None
7073
    follow_symlinks: bool=True
7074
7075
Set the access and modified time of path.
7076
7077
path may always be specified as a string.  On some platforms, path may
7078
also be specified as an open file descriptor.  If this functionality is
7079
unavailable, using it raises an exception.
7080
7081
If times is not None, it must be a tuple (atime, mtime);
7082
atime and mtime should be expressed as float seconds since the epoch.
7083
If ns is specified, it must be a tuple (atime_ns, mtime_ns);
7084
atime_ns and mtime_ns should be expressed as integer nanoseconds
7085
since the epoch.
7086
If times is None and ns is unspecified, utime uses the current time.
7087
Specifying tuples for both times and ns is an error.
7088
7089
If dir_fd is not None, it should be a file descriptor open to
7090
a directory, and path should be relative; path will then be relative to
7091
that directory.
7092
If follow_symlinks is False, and the last element of the path is
7093
a symbolic link, utime will modify the symbolic link itself instead of
7094
the file the link points to.
7095
It is an error to use dir_fd or follow_symlinks when specifying path as
7096
an open file descriptor.
7097
dir_fd and follow_symlinks may not be available on your platform.
7098
If they are unavailable, using them will raise a NotImplementedError.
7099
7100
[clinic start generated code]*/
7101
7102
static PyObject *
7103
os_utime_impl(PyObject *module, path_t *path, PyObject *times, PyObject *ns,
7104
              int dir_fd, int follow_symlinks)
7105
/*[clinic end generated code: output=cfcac69d027b82cf input=5ab470b2bc250788]*/
7106
0
{
7107
#ifdef MS_WINDOWS
7108
    HANDLE hFile;
7109
    FILETIME atime, mtime;
7110
#else
7111
0
    int result;
7112
0
#endif
7113
7114
0
    utime_t utime;
7115
7116
0
    memset(&utime, 0, sizeof(utime_t));
7117
7118
0
    if (times != Py_None && ns) {
7119
0
        PyErr_SetString(PyExc_ValueError,
7120
0
                     "utime: you may specify either 'times'"
7121
0
                     " or 'ns' but not both");
7122
0
        return NULL;
7123
0
    }
7124
7125
0
    if (times != Py_None) {
7126
0
        time_t a_sec, m_sec;
7127
0
        long a_nsec, m_nsec;
7128
0
        if (!PyTuple_CheckExact(times) || (PyTuple_Size(times) != 2)) {
7129
0
            PyErr_SetString(PyExc_TypeError,
7130
0
                         "utime: 'times' must be either"
7131
0
                         " a tuple of two numbers or None");
7132
0
            return NULL;
7133
0
        }
7134
0
        utime.now = 0;
7135
0
        if (_PyTime_ObjectToTimespec(PyTuple_GET_ITEM(times, 0),
7136
0
                                     &a_sec, &a_nsec, _PyTime_ROUND_FLOOR) == -1 ||
7137
0
            _PyTime_ObjectToTimespec(PyTuple_GET_ITEM(times, 1),
7138
0
                                     &m_sec, &m_nsec, _PyTime_ROUND_FLOOR) == -1) {
7139
0
            return NULL;
7140
0
        }
7141
0
        utime.atime_s = a_sec;
7142
0
        utime.atime_ns = a_nsec;
7143
0
        utime.mtime_s = m_sec;
7144
0
        utime.mtime_ns = m_nsec;
7145
0
    }
7146
0
    else if (ns) {
7147
0
        if (!PyTuple_CheckExact(ns) || (PyTuple_Size(ns) != 2)) {
7148
0
            PyErr_SetString(PyExc_TypeError,
7149
0
                         "utime: 'ns' must be a tuple of two ints");
7150
0
            return NULL;
7151
0
        }
7152
0
        utime.now = 0;
7153
0
        if (!split_py_long_to_s_and_ns(module, PyTuple_GET_ITEM(ns, 0),
7154
0
                                      &utime.atime_s, &utime.atime_ns) ||
7155
0
            !split_py_long_to_s_and_ns(module, PyTuple_GET_ITEM(ns, 1),
7156
0
                                       &utime.mtime_s, &utime.mtime_ns)) {
7157
0
            return NULL;
7158
0
        }
7159
0
    }
7160
0
    else {
7161
        /* times and ns are both None/unspecified. use "now". */
7162
0
        utime.now = 1;
7163
0
    }
7164
7165
#if !defined(UTIME_HAVE_NOFOLLOW_SYMLINKS)
7166
    if (follow_symlinks_specified("utime", follow_symlinks))
7167
        return NULL;
7168
#endif
7169
7170
0
    if (path_and_dir_fd_invalid("utime", path, dir_fd) ||
7171
0
        dir_fd_and_fd_invalid("utime", dir_fd, path->fd) ||
7172
0
        fd_and_follow_symlinks_invalid("utime", path->is_fd, follow_symlinks))
7173
0
        return NULL;
7174
7175
#if !defined(HAVE_UTIMENSAT)
7176
    if ((dir_fd != DEFAULT_DIR_FD) && (!follow_symlinks)) {
7177
        PyErr_SetString(PyExc_ValueError,
7178
                     "utime: cannot use dir_fd and follow_symlinks "
7179
                     "together on this platform");
7180
        return NULL;
7181
    }
7182
#endif
7183
7184
0
    if (PySys_Audit("os.utime", "OOOi", path->object, times, ns ? ns : Py_None,
7185
0
                    dir_fd == DEFAULT_DIR_FD ? -1 : dir_fd) < 0) {
7186
0
        return NULL;
7187
0
    }
7188
7189
#ifdef MS_WINDOWS
7190
    Py_BEGIN_ALLOW_THREADS
7191
    hFile = CreateFileW(path->wide, FILE_WRITE_ATTRIBUTES, 0,
7192
                        NULL, OPEN_EXISTING,
7193
                        FILE_FLAG_BACKUP_SEMANTICS, NULL);
7194
    Py_END_ALLOW_THREADS
7195
    if (hFile == INVALID_HANDLE_VALUE) {
7196
        path_error(path);
7197
        return NULL;
7198
    }
7199
7200
    if (utime.now) {
7201
        GetSystemTimeAsFileTime(&mtime);
7202
        atime = mtime;
7203
    }
7204
    else {
7205
        _Py_time_t_to_FILE_TIME(utime.atime_s, utime.atime_ns, &atime);
7206
        _Py_time_t_to_FILE_TIME(utime.mtime_s, utime.mtime_ns, &mtime);
7207
    }
7208
    if (!SetFileTime(hFile, NULL, &atime, &mtime)) {
7209
        path_error(path);
7210
        CloseHandle(hFile);
7211
        return NULL;
7212
    }
7213
    CloseHandle(hFile);
7214
#else /* MS_WINDOWS */
7215
0
    Py_BEGIN_ALLOW_THREADS
7216
7217
0
#ifdef UTIME_HAVE_NOFOLLOW_SYMLINKS
7218
0
    if ((!follow_symlinks) && (dir_fd == DEFAULT_DIR_FD))
7219
0
        result = utime_nofollow_symlinks(&utime, path->narrow);
7220
0
    else
7221
0
#endif
7222
7223
0
#if defined(HAVE_FUTIMESAT) || defined(HAVE_UTIMENSAT)
7224
0
    if ((dir_fd != DEFAULT_DIR_FD) || (!follow_symlinks)) {
7225
0
        result = utime_dir_fd(&utime, dir_fd, path->narrow, follow_symlinks);
7226
7227
0
    } else
7228
0
#endif
7229
7230
0
#if defined(HAVE_FUTIMES) || defined(HAVE_FUTIMENS)
7231
0
    if (path->is_fd)
7232
0
        result = utime_fd(&utime, path->fd);
7233
0
    else
7234
0
#endif
7235
7236
0
    result = utime_default(&utime, path->narrow);
7237
7238
0
    Py_END_ALLOW_THREADS
7239
7240
#if defined(__APPLE__) && defined(HAVE_UTIMENSAT)
7241
    /* See utime_dir_fd implementation */
7242
    if (result == -1 && errno == ENOSYS) {
7243
        argument_unavailable_error(NULL, "dir_fd");
7244
        return NULL;
7245
    }
7246
#endif
7247
7248
0
    if (result < 0) {
7249
0
        path_error(path);
7250
0
        return NULL;
7251
0
    }
7252
7253
0
#endif /* MS_WINDOWS */
7254
7255
0
    Py_RETURN_NONE;
7256
0
}
7257
7258
/* Process operations */
7259
7260
7261
/*[clinic input]
7262
@permit_long_summary
7263
os._exit
7264
7265
    status: int
7266
7267
Exit to the system with specified status, without normal exit processing.
7268
[clinic start generated code]*/
7269
7270
static PyObject *
7271
os__exit_impl(PyObject *module, int status)
7272
/*[clinic end generated code: output=116e52d9c2260d54 input=c35d282acfebe8fd]*/
7273
0
{
7274
0
    _exit(status);
7275
0
    return NULL; /* Make gcc -Wall happy */
7276
0
}
7277
7278
#if defined(HAVE_WEXECV) || defined(HAVE_WSPAWNV)
7279
#define EXECV_CHAR wchar_t
7280
#else
7281
0
#define EXECV_CHAR char
7282
#endif
7283
7284
#if defined(HAVE_EXECV) || defined(HAVE_SPAWNV) || defined(HAVE_RTPSPAWN)
7285
static void
7286
free_string_array(EXECV_CHAR **array, Py_ssize_t count)
7287
0
{
7288
0
    Py_ssize_t i;
7289
0
    for (i = 0; i < count; i++)
7290
0
        PyMem_Free(array[i]);
7291
0
    PyMem_Free(array);
7292
0
}
7293
7294
static int
7295
fsconvert_strdup(PyObject *o, EXECV_CHAR **out)
7296
0
{
7297
0
    Py_ssize_t size;
7298
0
    PyObject *ub;
7299
0
    int result = 0;
7300
#if defined(HAVE_WEXECV) || defined(HAVE_WSPAWNV)
7301
    if (!PyUnicode_FSDecoder(o, &ub))
7302
        return 0;
7303
    *out = PyUnicode_AsWideCharString(ub, &size);
7304
    if (*out)
7305
        result = 1;
7306
#else
7307
0
    if (!PyUnicode_FSConverter(o, &ub))
7308
0
        return 0;
7309
0
    size = PyBytes_GET_SIZE(ub);
7310
0
    *out = PyMem_Malloc(size + 1);
7311
0
    if (*out) {
7312
0
        memcpy(*out, PyBytes_AS_STRING(ub), size + 1);
7313
0
        result = 1;
7314
0
    } else
7315
0
        PyErr_NoMemory();
7316
0
#endif
7317
0
    Py_DECREF(ub);
7318
0
    return result;
7319
0
}
7320
#endif
7321
7322
#if defined(HAVE_EXECV) || defined (HAVE_FEXECVE) || defined(HAVE_RTPSPAWN)
7323
static EXECV_CHAR**
7324
parse_envlist(PyObject* env, Py_ssize_t *envc_ptr)
7325
0
{
7326
0
    Py_ssize_t i, pos, envc;
7327
0
    PyObject *keys = NULL, *vals = NULL;
7328
0
    PyObject *key = NULL, *val = NULL, *key2 = NULL, *val2 = NULL;
7329
0
    EXECV_CHAR **envlist;
7330
7331
0
    i = PyMapping_Size(env);
7332
0
    if (i < 0)
7333
0
        return NULL;
7334
0
    envlist = PyMem_NEW(EXECV_CHAR *, i + 1);
7335
0
    if (envlist == NULL) {
7336
0
        PyErr_NoMemory();
7337
0
        return NULL;
7338
0
    }
7339
0
    envc = 0;
7340
0
    keys = PyMapping_Keys(env);
7341
0
    if (!keys)
7342
0
        goto error;
7343
0
    vals = PyMapping_Values(env);
7344
0
    if (!vals)
7345
0
        goto error;
7346
0
    if (!PyList_Check(keys) || !PyList_Check(vals)) {
7347
0
        PyErr_Format(PyExc_TypeError,
7348
0
                     "env.keys() or env.values() is not a list");
7349
0
        goto error;
7350
0
    }
7351
7352
0
    for (pos = 0; pos < i; pos++) {
7353
        // The 'key' and 'val' must be strong references because of
7354
        // possible side-effects by PyUnicode_FS{Converter,Decoder}().
7355
0
        key = PyList_GetItemRef(keys, pos);
7356
0
        if (key == NULL) {
7357
0
            goto error;
7358
0
        }
7359
0
        val = PyList_GetItemRef(vals, pos);
7360
0
        if (val == NULL) {
7361
0
            goto error;
7362
0
        }
7363
7364
#if defined(HAVE_WEXECV) || defined(HAVE_WSPAWNV)
7365
        if (!PyUnicode_FSDecoder(key, &key2)) {
7366
            goto error;
7367
        }
7368
        if (!PyUnicode_FSDecoder(val, &val2)) {
7369
            goto error;
7370
        }
7371
        /* Search from index 1 because on Windows starting '=' is allowed for
7372
           defining hidden environment variables. */
7373
        if (PyUnicode_GET_LENGTH(key2) == 0 ||
7374
            PyUnicode_FindChar(key2, '=', 1, PyUnicode_GET_LENGTH(key2), 1) != -1)
7375
        {
7376
            PyErr_SetString(PyExc_ValueError, "illegal environment variable name");
7377
            goto error;
7378
        }
7379
        PyObject *keyval = PyUnicode_FromFormat("%U=%U", key2, val2);
7380
#else
7381
0
        if (!PyUnicode_FSConverter(key, &key2)) {
7382
0
            goto error;
7383
0
        }
7384
0
        if (!PyUnicode_FSConverter(val, &val2)) {
7385
0
            goto error;
7386
0
        }
7387
0
        if (PyBytes_GET_SIZE(key2) == 0 ||
7388
0
            strchr(PyBytes_AS_STRING(key2) + 1, '=') != NULL)
7389
0
        {
7390
0
            PyErr_SetString(PyExc_ValueError, "illegal environment variable name");
7391
0
            goto error;
7392
0
        }
7393
0
        PyObject *keyval = PyBytes_FromFormat("%s=%s", PyBytes_AS_STRING(key2),
7394
0
                                              PyBytes_AS_STRING(val2));
7395
0
#endif
7396
0
        if (!keyval) {
7397
0
            goto error;
7398
0
        }
7399
7400
0
        if (!fsconvert_strdup(keyval, &envlist[envc++])) {
7401
0
            Py_DECREF(keyval);
7402
0
            goto error;
7403
0
        }
7404
7405
0
        Py_CLEAR(key);
7406
0
        Py_CLEAR(val);
7407
0
        Py_CLEAR(key2);
7408
0
        Py_CLEAR(val2);
7409
0
        Py_DECREF(keyval);
7410
0
    }
7411
0
    Py_DECREF(vals);
7412
0
    Py_DECREF(keys);
7413
7414
0
    envlist[envc] = 0;
7415
0
    *envc_ptr = envc;
7416
0
    return envlist;
7417
7418
0
error:
7419
0
    Py_XDECREF(key);
7420
0
    Py_XDECREF(val);
7421
0
    Py_XDECREF(key2);
7422
0
    Py_XDECREF(val2);
7423
0
    Py_XDECREF(keys);
7424
0
    Py_XDECREF(vals);
7425
0
    free_string_array(envlist, envc);
7426
0
    return NULL;
7427
0
}
7428
7429
static EXECV_CHAR**
7430
parse_arglist(PyObject* argv, Py_ssize_t *argc)
7431
0
{
7432
0
    int i;
7433
0
    EXECV_CHAR **argvlist = PyMem_NEW(EXECV_CHAR *, *argc+1);
7434
0
    if (argvlist == NULL) {
7435
0
        PyErr_NoMemory();
7436
0
        return NULL;
7437
0
    }
7438
0
    for (i = 0; i < *argc; i++) {
7439
0
        PyObject* item = PySequence_ITEM(argv, i);
7440
0
        if (item == NULL)
7441
0
            goto fail;
7442
0
        if (!fsconvert_strdup(item, &argvlist[i])) {
7443
0
            Py_DECREF(item);
7444
0
            goto fail;
7445
0
        }
7446
0
        Py_DECREF(item);
7447
0
    }
7448
0
    argvlist[*argc] = NULL;
7449
0
    return argvlist;
7450
0
fail:
7451
0
    *argc = i;
7452
0
    free_string_array(argvlist, *argc);
7453
0
    return NULL;
7454
0
}
7455
7456
#endif
7457
7458
7459
#ifdef HAVE_EXECV
7460
/*[clinic input]
7461
os.execv
7462
7463
    path: path_t
7464
        Path of executable file.
7465
    argv: object
7466
        Tuple or list of strings.
7467
    /
7468
7469
Execute an executable path with arguments, replacing current process.
7470
[clinic start generated code]*/
7471
7472
static PyObject *
7473
os_execv_impl(PyObject *module, path_t *path, PyObject *argv)
7474
/*[clinic end generated code: output=3b52fec34cd0dafd input=9bac31efae07dac7]*/
7475
0
{
7476
0
    EXECV_CHAR **argvlist;
7477
0
    Py_ssize_t argc;
7478
7479
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
7480
0
    if (!_PyInterpreterState_HasFeature(interp, Py_RTFLAGS_EXEC)) {
7481
0
        PyErr_SetString(PyExc_RuntimeError,
7482
0
                        "exec not supported for isolated subinterpreters");
7483
0
        return NULL;
7484
0
    }
7485
7486
    /* execv has two arguments: (path, argv), where
7487
       argv is a list or tuple of strings. */
7488
7489
0
    if (!PyList_Check(argv) && !PyTuple_Check(argv)) {
7490
0
        PyErr_SetString(PyExc_TypeError,
7491
0
                        "execv() arg 2 must be a tuple or list");
7492
0
        return NULL;
7493
0
    }
7494
0
    argc = PySequence_Size(argv);
7495
0
    if (argc < 1) {
7496
0
        PyErr_SetString(PyExc_ValueError, "execv() arg 2 must not be empty");
7497
0
        return NULL;
7498
0
    }
7499
7500
0
    argvlist = parse_arglist(argv, &argc);
7501
0
    if (argvlist == NULL) {
7502
0
        return NULL;
7503
0
    }
7504
0
    if (!argvlist[0][0]) {
7505
0
        PyErr_SetString(PyExc_ValueError,
7506
0
            "execv() arg 2 first element cannot be empty");
7507
0
        free_string_array(argvlist, argc);
7508
0
        return NULL;
7509
0
    }
7510
7511
0
    if (PySys_Audit("os.exec", "OOO", path->object, argv, Py_None) < 0) {
7512
0
        free_string_array(argvlist, argc);
7513
0
        return NULL;
7514
0
    }
7515
7516
0
    _Py_BEGIN_SUPPRESS_IPH
7517
#ifdef HAVE_WEXECV
7518
    _wexecv(path->wide, argvlist);
7519
#else
7520
0
    execv(path->narrow, argvlist);
7521
0
#endif
7522
0
    _Py_END_SUPPRESS_IPH
7523
7524
    /* If we get here it's definitely an error */
7525
7526
0
    posix_path_error(path);
7527
0
    free_string_array(argvlist, argc);
7528
0
    return NULL;
7529
0
}
7530
7531
7532
/*[clinic input]
7533
os.execve
7534
7535
    path: path_t(allow_fd='PATH_HAVE_FEXECVE')
7536
        Path of executable file.
7537
    argv: object
7538
        Tuple or list of strings.
7539
    env: object
7540
        Dictionary of strings mapping to strings.
7541
7542
Execute an executable path with arguments, replacing current process.
7543
[clinic start generated code]*/
7544
7545
static PyObject *
7546
os_execve_impl(PyObject *module, path_t *path, PyObject *argv, PyObject *env)
7547
/*[clinic end generated code: output=ff9fa8e4da8bde58 input=626804fa092606d9]*/
7548
0
{
7549
0
    EXECV_CHAR **argvlist = NULL;
7550
0
    EXECV_CHAR **envlist;
7551
0
    Py_ssize_t argc, envc;
7552
7553
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
7554
0
    if (!_PyInterpreterState_HasFeature(interp, Py_RTFLAGS_EXEC)) {
7555
0
        PyErr_SetString(PyExc_RuntimeError,
7556
0
                        "exec not supported for isolated subinterpreters");
7557
0
        return NULL;
7558
0
    }
7559
7560
    /* execve has three arguments: (path, argv, env), where
7561
       argv is a list or tuple of strings and env is a dictionary
7562
       like posix.environ. */
7563
7564
0
    if (!PyList_Check(argv) && !PyTuple_Check(argv)) {
7565
0
        PyErr_SetString(PyExc_TypeError,
7566
0
                        "execve: argv must be a tuple or list");
7567
0
        goto fail_0;
7568
0
    }
7569
0
    argc = PySequence_Size(argv);
7570
0
    if (argc < 1) {
7571
0
        PyErr_SetString(PyExc_ValueError, "execve: argv must not be empty");
7572
0
        return NULL;
7573
0
    }
7574
7575
0
    if (!PyMapping_Check(env)) {
7576
0
        PyErr_SetString(PyExc_TypeError,
7577
0
                        "execve: environment must be a mapping object");
7578
0
        goto fail_0;
7579
0
    }
7580
7581
0
    argvlist = parse_arglist(argv, &argc);
7582
0
    if (argvlist == NULL) {
7583
0
        goto fail_0;
7584
0
    }
7585
0
    if (!argvlist[0][0]) {
7586
0
        PyErr_SetString(PyExc_ValueError,
7587
0
            "execve: argv first element cannot be empty");
7588
0
        goto fail_0;
7589
0
    }
7590
7591
0
    envlist = parse_envlist(env, &envc);
7592
0
    if (envlist == NULL)
7593
0
        goto fail_0;
7594
7595
0
    if (PySys_Audit("os.exec", "OOO", path->object, argv, env) < 0) {
7596
0
        goto fail_1;
7597
0
    }
7598
7599
0
    _Py_BEGIN_SUPPRESS_IPH
7600
0
#ifdef HAVE_FEXECVE
7601
0
    if (path->is_fd)
7602
0
        fexecve(path->fd, argvlist, envlist);
7603
0
    else
7604
0
#endif
7605
#ifdef HAVE_WEXECV
7606
        _wexecve(path->wide, argvlist, envlist);
7607
#else
7608
0
        execve(path->narrow, argvlist, envlist);
7609
0
#endif
7610
0
    _Py_END_SUPPRESS_IPH
7611
7612
    /* If we get here it's definitely an error */
7613
7614
0
    posix_path_error(path);
7615
0
  fail_1:
7616
0
    free_string_array(envlist, envc);
7617
0
  fail_0:
7618
0
    if (argvlist)
7619
0
        free_string_array(argvlist, argc);
7620
0
    return NULL;
7621
0
}
7622
7623
#endif /* HAVE_EXECV */
7624
7625
#ifdef HAVE_POSIX_SPAWN
7626
7627
enum posix_spawn_file_actions_identifier {
7628
    POSIX_SPAWN_OPEN,
7629
    POSIX_SPAWN_CLOSE,
7630
    POSIX_SPAWN_DUP2
7631
#ifdef HAVE_POSIX_SPAWN_FILE_ACTIONS_ADDCLOSEFROM_NP
7632
    ,POSIX_SPAWN_CLOSEFROM
7633
#endif
7634
};
7635
7636
#if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
7637
static int
7638
convert_sched_param(PyObject *module, PyObject *param, struct sched_param *res);
7639
#endif
7640
7641
static int
7642
parse_posix_spawn_flags(PyObject *module, const char *func_name, PyObject *setpgroup,
7643
                        int resetids, int setsid, PyObject *setsigmask,
7644
                        PyObject *setsigdef, PyObject *scheduler,
7645
                        posix_spawnattr_t *attrp)
7646
0
{
7647
0
    assert(scheduler == NULL || scheduler == Py_None || PyTuple_Check(scheduler));
7648
0
    long all_flags = 0;
7649
7650
0
    errno = posix_spawnattr_init(attrp);
7651
0
    if (errno) {
7652
0
        posix_error();
7653
0
        return -1;
7654
0
    }
7655
7656
0
    if (setpgroup && setpgroup != Py_None) {
7657
0
        pid_t pgid = PyLong_AsPid(setpgroup);
7658
0
        if (pgid == (pid_t)-1 && PyErr_Occurred()) {
7659
0
            goto fail;
7660
0
        }
7661
0
        errno = posix_spawnattr_setpgroup(attrp, pgid);
7662
0
        if (errno) {
7663
0
            posix_error();
7664
0
            goto fail;
7665
0
        }
7666
0
        all_flags |= POSIX_SPAWN_SETPGROUP;
7667
0
    }
7668
7669
0
    if (resetids) {
7670
0
        all_flags |= POSIX_SPAWN_RESETIDS;
7671
0
    }
7672
7673
0
    if (setsid) {
7674
#ifdef HAVE_POSIX_SPAWN_SETSID_RUNTIME
7675
        if (HAVE_POSIX_SPAWN_SETSID_RUNTIME) {
7676
#endif
7677
0
#ifdef POSIX_SPAWN_SETSID
7678
0
        all_flags |= POSIX_SPAWN_SETSID;
7679
#elif defined(POSIX_SPAWN_SETSID_NP)
7680
        all_flags |= POSIX_SPAWN_SETSID_NP;
7681
#else
7682
        argument_unavailable_error(func_name, "setsid");
7683
        return -1;
7684
#endif
7685
7686
#ifdef HAVE_POSIX_SPAWN_SETSID_RUNTIME
7687
        } else {
7688
            argument_unavailable_error(func_name, "setsid");
7689
            return -1;
7690
        }
7691
#endif /* HAVE_POSIX_SPAWN_SETSID_RUNTIME */
7692
7693
0
    }
7694
7695
0
#ifdef HAVE_SIGSET_T
7696
0
   if (setsigmask) {
7697
0
        sigset_t set;
7698
0
        if (!_Py_Sigset_Converter(setsigmask, &set)) {
7699
0
            goto fail;
7700
0
        }
7701
0
        errno = posix_spawnattr_setsigmask(attrp, &set);
7702
0
        if (errno) {
7703
0
            posix_error();
7704
0
            goto fail;
7705
0
        }
7706
0
        all_flags |= POSIX_SPAWN_SETSIGMASK;
7707
0
    }
7708
7709
0
    if (setsigdef) {
7710
0
        sigset_t set;
7711
0
        if (!_Py_Sigset_Converter(setsigdef, &set)) {
7712
0
            goto fail;
7713
0
        }
7714
0
        errno = posix_spawnattr_setsigdefault(attrp, &set);
7715
0
        if (errno) {
7716
0
            posix_error();
7717
0
            goto fail;
7718
0
        }
7719
0
        all_flags |= POSIX_SPAWN_SETSIGDEF;
7720
0
    }
7721
#else
7722
    if (setsigmask || setsigdef) {
7723
        PyErr_SetString(PyExc_NotImplementedError,
7724
                        "sigset is not supported on this platform");
7725
        goto fail;
7726
    }
7727
#endif
7728
7729
0
    if (scheduler && scheduler != Py_None) {
7730
0
#ifdef POSIX_SPAWN_SETSCHEDULER
7731
0
        PyObject *py_schedpolicy;
7732
0
        PyObject *schedparam_obj;
7733
0
        struct sched_param schedparam;
7734
7735
0
        if (!PyArg_ParseTuple(scheduler, "OO"
7736
0
                        ";A scheduler tuple must have two elements",
7737
0
                        &py_schedpolicy, &schedparam_obj)) {
7738
0
            goto fail;
7739
0
        }
7740
0
        if (!convert_sched_param(module, schedparam_obj, &schedparam)) {
7741
0
            goto fail;
7742
0
        }
7743
0
        if (py_schedpolicy != Py_None) {
7744
0
            int schedpolicy = PyLong_AsInt(py_schedpolicy);
7745
7746
0
            if (schedpolicy == -1 && PyErr_Occurred()) {
7747
0
                goto fail;
7748
0
            }
7749
0
            errno = posix_spawnattr_setschedpolicy(attrp, schedpolicy);
7750
0
            if (errno) {
7751
0
                posix_error();
7752
0
                goto fail;
7753
0
            }
7754
0
            all_flags |= POSIX_SPAWN_SETSCHEDULER;
7755
0
        }
7756
0
        errno = posix_spawnattr_setschedparam(attrp, &schedparam);
7757
0
        if (errno) {
7758
0
            posix_error();
7759
0
            goto fail;
7760
0
        }
7761
0
        all_flags |= POSIX_SPAWN_SETSCHEDPARAM;
7762
#else
7763
        PyErr_SetString(PyExc_NotImplementedError,
7764
                "The scheduler option is not supported in this system.");
7765
        goto fail;
7766
#endif
7767
0
    }
7768
7769
0
    errno = posix_spawnattr_setflags(attrp, all_flags);
7770
0
    if (errno) {
7771
0
        posix_error();
7772
0
        goto fail;
7773
0
    }
7774
7775
0
    return 0;
7776
7777
0
fail:
7778
0
    (void)posix_spawnattr_destroy(attrp);
7779
0
    return -1;
7780
0
}
7781
7782
static int
7783
parse_file_actions(PyObject *file_actions,
7784
                   posix_spawn_file_actions_t *file_actionsp,
7785
                   PyObject *temp_buffer)
7786
0
{
7787
0
    PyObject *seq;
7788
0
    PyObject *file_action = NULL;
7789
0
    PyObject *tag_obj;
7790
7791
0
    seq = PySequence_Fast(file_actions,
7792
0
                          "file_actions must be a sequence or None");
7793
0
    if (seq == NULL) {
7794
0
        return -1;
7795
0
    }
7796
7797
0
    errno = posix_spawn_file_actions_init(file_actionsp);
7798
0
    if (errno) {
7799
0
        posix_error();
7800
0
        Py_DECREF(seq);
7801
0
        return -1;
7802
0
    }
7803
7804
0
    for (Py_ssize_t i = 0; i < PySequence_Fast_GET_SIZE(seq); ++i) {
7805
0
        file_action = PySequence_Fast_GET_ITEM(seq, i);
7806
0
        Py_INCREF(file_action);
7807
0
        if (!PyTuple_Check(file_action) || !PyTuple_GET_SIZE(file_action)) {
7808
0
            PyErr_SetString(PyExc_TypeError,
7809
0
                "Each file_actions element must be a non-empty tuple");
7810
0
            goto fail;
7811
0
        }
7812
0
        long tag = PyLong_AsLong(PyTuple_GET_ITEM(file_action, 0));
7813
0
        if (tag == -1 && PyErr_Occurred()) {
7814
0
            goto fail;
7815
0
        }
7816
7817
        /* Populate the file_actions object */
7818
0
        switch (tag) {
7819
0
            case POSIX_SPAWN_OPEN: {
7820
0
                int fd, oflag;
7821
0
                PyObject *path;
7822
0
                unsigned long mode;
7823
0
                if (!PyArg_ParseTuple(file_action, "OiO&ik"
7824
0
                        ";A open file_action tuple must have 5 elements",
7825
0
                        &tag_obj, &fd, PyUnicode_FSConverter, &path,
7826
0
                        &oflag, &mode))
7827
0
                {
7828
0
                    goto fail;
7829
0
                }
7830
0
                if (PyList_Append(temp_buffer, path)) {
7831
0
                    Py_DECREF(path);
7832
0
                    goto fail;
7833
0
                }
7834
0
                errno = posix_spawn_file_actions_addopen(file_actionsp,
7835
0
                        fd, PyBytes_AS_STRING(path), oflag, (mode_t)mode);
7836
0
                if (errno) {
7837
0
                    posix_error();
7838
0
                    Py_DECREF(path);
7839
0
                    goto fail;
7840
0
                }
7841
0
                Py_DECREF(path);
7842
0
                break;
7843
0
            }
7844
0
            case POSIX_SPAWN_CLOSE: {
7845
0
                int fd;
7846
0
                if (!PyArg_ParseTuple(file_action, "Oi"
7847
0
                        ";A close file_action tuple must have 2 elements",
7848
0
                        &tag_obj, &fd))
7849
0
                {
7850
0
                    goto fail;
7851
0
                }
7852
0
                errno = posix_spawn_file_actions_addclose(file_actionsp, fd);
7853
0
                if (errno) {
7854
0
                    posix_error();
7855
0
                    goto fail;
7856
0
                }
7857
0
                break;
7858
0
            }
7859
0
            case POSIX_SPAWN_DUP2: {
7860
0
                int fd1, fd2;
7861
0
                if (!PyArg_ParseTuple(file_action, "Oii"
7862
0
                        ";A dup2 file_action tuple must have 3 elements",
7863
0
                        &tag_obj, &fd1, &fd2))
7864
0
                {
7865
0
                    goto fail;
7866
0
                }
7867
0
                errno = posix_spawn_file_actions_adddup2(file_actionsp,
7868
0
                                                         fd1, fd2);
7869
0
                if (errno) {
7870
0
                    posix_error();
7871
0
                    goto fail;
7872
0
                }
7873
0
                break;
7874
0
            }
7875
0
#ifdef HAVE_POSIX_SPAWN_FILE_ACTIONS_ADDCLOSEFROM_NP
7876
0
            case POSIX_SPAWN_CLOSEFROM: {
7877
0
                int fd;
7878
0
                if (!PyArg_ParseTuple(file_action, "Oi"
7879
0
                        ";A closefrom file_action tuple must have 2 elements",
7880
0
                        &tag_obj, &fd))
7881
0
                {
7882
0
                    goto fail;
7883
0
                }
7884
0
                errno = posix_spawn_file_actions_addclosefrom_np(file_actionsp,
7885
0
                                                                 fd);
7886
0
                if (errno) {
7887
0
                    posix_error();
7888
0
                    goto fail;
7889
0
                }
7890
0
                break;
7891
0
            }
7892
0
#endif
7893
0
            default: {
7894
0
                PyErr_SetString(PyExc_TypeError,
7895
0
                                "Unknown file_actions identifier");
7896
0
                goto fail;
7897
0
            }
7898
0
        }
7899
0
        Py_DECREF(file_action);
7900
0
    }
7901
7902
0
    Py_DECREF(seq);
7903
0
    return 0;
7904
7905
0
fail:
7906
0
    Py_DECREF(seq);
7907
0
    Py_DECREF(file_action);
7908
0
    (void)posix_spawn_file_actions_destroy(file_actionsp);
7909
0
    return -1;
7910
0
}
7911
7912
7913
static PyObject *
7914
py_posix_spawn(int use_posix_spawnp, PyObject *module, path_t *path, PyObject *argv,
7915
               PyObject *env, PyObject *file_actions,
7916
               PyObject *setpgroup, int resetids, int setsid, PyObject *setsigmask,
7917
               PyObject *setsigdef, PyObject *scheduler)
7918
0
{
7919
0
    const char *func_name = use_posix_spawnp ? "posix_spawnp" : "posix_spawn";
7920
0
    EXECV_CHAR **argvlist = NULL;
7921
0
    EXECV_CHAR **envlist = NULL;
7922
0
    posix_spawn_file_actions_t file_actions_buf;
7923
0
    posix_spawn_file_actions_t *file_actionsp = NULL;
7924
0
    posix_spawnattr_t attr;
7925
0
    posix_spawnattr_t *attrp = NULL;
7926
0
    Py_ssize_t argc, envc;
7927
0
    PyObject *result = NULL;
7928
0
    PyObject *temp_buffer = NULL;
7929
0
    pid_t pid;
7930
0
    int err_code;
7931
7932
    /* posix_spawn and posix_spawnp have three arguments: (path, argv, env), where
7933
       argv is a list or tuple of strings and env is a dictionary
7934
       like posix.environ. */
7935
7936
0
    if (!PyList_Check(argv) && !PyTuple_Check(argv)) {
7937
0
        PyErr_Format(PyExc_TypeError,
7938
0
                     "%s: argv must be a tuple or list", func_name);
7939
0
        goto exit;
7940
0
    }
7941
0
    argc = PySequence_Size(argv);
7942
0
    if (argc < 1) {
7943
0
        PyErr_Format(PyExc_ValueError,
7944
0
                     "%s: argv must not be empty", func_name);
7945
0
        goto exit;
7946
0
    }
7947
7948
0
    if (!PyMapping_Check(env) && env != Py_None) {
7949
0
        PyErr_Format(PyExc_TypeError,
7950
0
                     "%s: environment must be a mapping object or None", func_name);
7951
0
        goto exit;
7952
0
    }
7953
7954
0
    if (scheduler && !PyTuple_Check(scheduler) && scheduler != Py_None) {
7955
0
        PyErr_Format(PyExc_TypeError,
7956
0
                     "%s: scheduler must be a tuple or None", func_name);
7957
0
        goto exit;
7958
0
    }
7959
7960
0
    argvlist = parse_arglist(argv, &argc);
7961
0
    if (argvlist == NULL) {
7962
0
        goto exit;
7963
0
    }
7964
0
    if (!argvlist[0][0]) {
7965
0
        PyErr_Format(PyExc_ValueError,
7966
0
                     "%s: argv first element cannot be empty", func_name);
7967
0
        goto exit;
7968
0
    }
7969
7970
#ifdef USE_DARWIN_NS_GET_ENVIRON
7971
    // There is no environ global in this situation.
7972
    char **environ = NULL;
7973
#endif
7974
7975
0
    if (env == Py_None) {
7976
#ifdef USE_DARWIN_NS_GET_ENVIRON
7977
        environ = *_NSGetEnviron();
7978
#endif
7979
0
        envlist = environ;
7980
0
    } else {
7981
0
        envlist = parse_envlist(env, &envc);
7982
0
        if (envlist == NULL) {
7983
0
            goto exit;
7984
0
        }
7985
0
    }
7986
7987
0
    if (file_actions != NULL && file_actions != Py_None) {
7988
        /* There is a bug in old versions of glibc that makes some of the
7989
         * helper functions for manipulating file actions not copy the provided
7990
         * buffers. The problem is that posix_spawn_file_actions_addopen does not
7991
         * copy the value of path for some old versions of glibc (<2.20).
7992
         * The use of temp_buffer here is a workaround that keeps the
7993
         * python objects that own the buffers alive until posix_spawn gets called.
7994
         * Check https://bugs.python.org/issue33630 and
7995
         * https://sourceware.org/bugzilla/show_bug.cgi?id=17048 for more info.*/
7996
0
        temp_buffer = PyList_New(0);
7997
0
        if (!temp_buffer) {
7998
0
            goto exit;
7999
0
        }
8000
0
        if (parse_file_actions(file_actions, &file_actions_buf, temp_buffer)) {
8001
0
            goto exit;
8002
0
        }
8003
0
        file_actionsp = &file_actions_buf;
8004
0
    }
8005
8006
0
    if (parse_posix_spawn_flags(module, func_name, setpgroup, resetids, setsid,
8007
0
                                setsigmask, setsigdef, scheduler, &attr)) {
8008
0
        goto exit;
8009
0
    }
8010
0
    attrp = &attr;
8011
8012
0
    if (PySys_Audit("os.posix_spawn", "OOO", path->object, argv, env) < 0) {
8013
0
        goto exit;
8014
0
    }
8015
8016
0
    _Py_BEGIN_SUPPRESS_IPH
8017
0
#ifdef HAVE_POSIX_SPAWNP
8018
0
    if (use_posix_spawnp) {
8019
0
        err_code = posix_spawnp(&pid, path->narrow,
8020
0
                                file_actionsp, attrp, argvlist, envlist);
8021
0
    }
8022
0
    else
8023
0
#endif /* HAVE_POSIX_SPAWNP */
8024
0
    {
8025
0
        err_code = posix_spawn(&pid, path->narrow,
8026
0
                               file_actionsp, attrp, argvlist, envlist);
8027
0
    }
8028
0
    _Py_END_SUPPRESS_IPH
8029
8030
0
    if (err_code) {
8031
0
        errno = err_code;
8032
0
        PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, path->object);
8033
0
        goto exit;
8034
0
    }
8035
#ifdef _Py_MEMORY_SANITIZER
8036
    __msan_unpoison(&pid, sizeof(pid));
8037
#endif
8038
0
    result = PyLong_FromPid(pid);
8039
8040
0
exit:
8041
0
    if (file_actionsp) {
8042
0
        (void)posix_spawn_file_actions_destroy(file_actionsp);
8043
0
    }
8044
0
    if (attrp) {
8045
0
        (void)posix_spawnattr_destroy(attrp);
8046
0
    }
8047
0
    if (envlist && envlist != environ) {
8048
0
        free_string_array(envlist, envc);
8049
0
    }
8050
0
    if (argvlist) {
8051
0
        free_string_array(argvlist, argc);
8052
0
    }
8053
0
    Py_XDECREF(temp_buffer);
8054
0
    return result;
8055
0
}
8056
8057
8058
/*[clinic input]
8059
8060
os.posix_spawn
8061
    path: path_t
8062
        Path of executable file.
8063
    argv: object
8064
        Tuple or list of strings.
8065
    env: object
8066
        Dictionary of strings mapping to strings.
8067
    /
8068
    *
8069
    file_actions: object(c_default='NULL') = ()
8070
        A sequence of file action tuples.
8071
    setpgroup: object(c_default='NULL') = None
8072
        The pgroup to use with the POSIX_SPAWN_SETPGROUP flag.
8073
    resetids: bool = False
8074
        If the value is `true` the POSIX_SPAWN_RESETIDS will be activated.
8075
    setsid: bool = False
8076
        If the value is `true` the POSIX_SPAWN_SETSID or POSIX_SPAWN_SETSID_NP
8077
        will be activated.
8078
    setsigmask: object(c_default='NULL') = ()
8079
        The sigmask to use with the POSIX_SPAWN_SETSIGMASK flag.
8080
    setsigdef: object(c_default='NULL') = ()
8081
        The sigmask to use with the POSIX_SPAWN_SETSIGDEF flag.
8082
    scheduler: object(c_default='NULL') = None
8083
        A tuple with the scheduler policy (optional) and parameters.
8084
8085
Execute the program specified by path in a new process.
8086
[clinic start generated code]*/
8087
8088
static PyObject *
8089
os_posix_spawn_impl(PyObject *module, path_t *path, PyObject *argv,
8090
                    PyObject *env, PyObject *file_actions,
8091
                    PyObject *setpgroup, int resetids, int setsid,
8092
                    PyObject *setsigmask, PyObject *setsigdef,
8093
                    PyObject *scheduler)
8094
/*[clinic end generated code: output=14a1098c566bc675 input=c7592dcbc96e8114]*/
8095
0
{
8096
0
    return py_posix_spawn(0, module, path, argv, env, file_actions,
8097
0
                          setpgroup, resetids, setsid, setsigmask, setsigdef,
8098
0
                          scheduler);
8099
0
}
8100
 #endif /* HAVE_POSIX_SPAWN */
8101
8102
8103
8104
#ifdef HAVE_POSIX_SPAWNP
8105
/*[clinic input]
8106
8107
os.posix_spawnp
8108
    path: path_t
8109
        Path of executable file.
8110
    argv: object
8111
        Tuple or list of strings.
8112
    env: object
8113
        Dictionary of strings mapping to strings.
8114
    /
8115
    *
8116
    file_actions: object(c_default='NULL') = ()
8117
        A sequence of file action tuples.
8118
    setpgroup: object(c_default='NULL') = None
8119
        The pgroup to use with the POSIX_SPAWN_SETPGROUP flag.
8120
    resetids: bool = False
8121
        If the value is `True` the POSIX_SPAWN_RESETIDS will be activated.
8122
    setsid: bool = False
8123
        If the value is `True` the POSIX_SPAWN_SETSID or POSIX_SPAWN_SETSID_NP
8124
        will be activated.
8125
    setsigmask: object(c_default='NULL') = ()
8126
        The sigmask to use with the POSIX_SPAWN_SETSIGMASK flag.
8127
    setsigdef: object(c_default='NULL') = ()
8128
        The sigmask to use with the POSIX_SPAWN_SETSIGDEF flag.
8129
    scheduler: object(c_default='NULL') = None
8130
        A tuple with the scheduler policy (optional) and parameters.
8131
8132
Execute the program specified by path in a new process.
8133
[clinic start generated code]*/
8134
8135
static PyObject *
8136
os_posix_spawnp_impl(PyObject *module, path_t *path, PyObject *argv,
8137
                     PyObject *env, PyObject *file_actions,
8138
                     PyObject *setpgroup, int resetids, int setsid,
8139
                     PyObject *setsigmask, PyObject *setsigdef,
8140
                     PyObject *scheduler)
8141
/*[clinic end generated code: output=7b9aaefe3031238d input=43ccc1452cae2be3]*/
8142
0
{
8143
0
    return py_posix_spawn(1, module, path, argv, env, file_actions,
8144
0
                          setpgroup, resetids, setsid, setsigmask, setsigdef,
8145
0
                          scheduler);
8146
0
}
8147
#endif /* HAVE_POSIX_SPAWNP */
8148
8149
#ifdef HAVE_RTPSPAWN
8150
static intptr_t
8151
_rtp_spawn(int mode, const char *rtpFileName, const char *argv[],
8152
               const char  *envp[])
8153
{
8154
     RTP_ID rtpid;
8155
     int status;
8156
     pid_t res;
8157
     int async_err = 0;
8158
8159
     /* Set priority=100 and uStackSize=16 MiB (0x1000000) for new processes.
8160
        uStackSize=0 cannot be used, the default stack size is too small for
8161
        Python. */
8162
     if (envp) {
8163
         rtpid = rtpSpawn(rtpFileName, argv, envp,
8164
                          100, 0x1000000, 0, VX_FP_TASK);
8165
     }
8166
     else {
8167
         rtpid = rtpSpawn(rtpFileName, argv, (const char **)environ,
8168
                          100, 0x1000000, 0, VX_FP_TASK);
8169
     }
8170
     if ((rtpid != RTP_ID_ERROR) && (mode == _P_WAIT)) {
8171
         do {
8172
             res = waitpid((pid_t)rtpid, &status, 0);
8173
         } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
8174
8175
         if (res < 0)
8176
             return RTP_ID_ERROR;
8177
         return ((intptr_t)status);
8178
     }
8179
     return ((intptr_t)rtpid);
8180
}
8181
#endif
8182
8183
#if defined(HAVE_SPAWNV) || defined(HAVE_WSPAWNV) || defined(HAVE_RTPSPAWN)
8184
/*[clinic input]
8185
os.spawnv
8186
8187
    mode: int
8188
        Mode of process creation.
8189
    path: path_t
8190
        Path of executable file.
8191
    argv: object
8192
        Tuple or list of strings.
8193
    /
8194
8195
Execute the program specified by path in a new process.
8196
[clinic start generated code]*/
8197
8198
static PyObject *
8199
os_spawnv_impl(PyObject *module, int mode, path_t *path, PyObject *argv)
8200
/*[clinic end generated code: output=71cd037a9d96b816 input=43224242303291be]*/
8201
{
8202
    EXECV_CHAR **argvlist;
8203
    int i;
8204
    Py_ssize_t argc;
8205
    intptr_t spawnval;
8206
8207
    /* spawnv has three arguments: (mode, path, argv), where
8208
       argv is a list or tuple of strings. */
8209
8210
    if (PyList_Check(argv)) {
8211
        argc = PyList_Size(argv);
8212
    }
8213
    else if (PyTuple_Check(argv)) {
8214
        argc = PyTuple_Size(argv);
8215
    }
8216
    else {
8217
        PyErr_SetString(PyExc_TypeError,
8218
                        "spawnv() arg 2 must be a tuple or list");
8219
        return NULL;
8220
    }
8221
    if (argc == 0) {
8222
        PyErr_SetString(PyExc_ValueError,
8223
            "spawnv() arg 2 cannot be empty");
8224
        return NULL;
8225
    }
8226
8227
    argvlist = PyMem_NEW(EXECV_CHAR *, argc+1);
8228
    if (argvlist == NULL) {
8229
        return PyErr_NoMemory();
8230
    }
8231
    for (i = 0; i < argc; i++) {
8232
        // The item must be a strong reference because of possible
8233
        // side-effects of PyUnicode_FS{Converter,Decoder}() in
8234
        // fsconvert_strdup(): an item's __fspath__() can mutate a list
8235
        // *argv*, releasing the list's reference to the item (gh-151416).
8236
        PyObject *item = PySequence_ITEM(argv, i);
8237
        if (item == NULL) {
8238
            free_string_array(argvlist, i);
8239
            return NULL;
8240
        }
8241
        if (!fsconvert_strdup(item, &argvlist[i])) {
8242
            Py_DECREF(item);
8243
            free_string_array(argvlist, i);
8244
            // Add argument context to the converter's terse TypeError, but
8245
            // let MemoryError, codec errors, embedded-null ValueError, etc.
8246
            // propagate unmasked.
8247
            if (PyErr_ExceptionMatches(PyExc_TypeError)) {
8248
                PyErr_SetString(
8249
                    PyExc_TypeError,
8250
                    "spawnv() arg 2 must contain only strings");
8251
            }
8252
            return NULL;
8253
        }
8254
        Py_DECREF(item);
8255
        if (i == 0 && !argvlist[0][0]) {
8256
            free_string_array(argvlist, i + 1);
8257
            PyErr_SetString(
8258
                PyExc_ValueError,
8259
                "spawnv() arg 2 first element cannot be empty");
8260
            return NULL;
8261
        }
8262
    }
8263
    argvlist[argc] = NULL;
8264
8265
#if !defined(HAVE_RTPSPAWN)
8266
    if (mode == _OLD_P_OVERLAY)
8267
        mode = _P_OVERLAY;
8268
#endif
8269
8270
    if (PySys_Audit("os.spawn", "iOOO", mode, path->object, argv,
8271
                    Py_None) < 0) {
8272
        free_string_array(argvlist, argc);
8273
        return NULL;
8274
    }
8275
8276
    Py_BEGIN_ALLOW_THREADS
8277
    _Py_BEGIN_SUPPRESS_IPH
8278
#ifdef HAVE_WSPAWNV
8279
    spawnval = _wspawnv(mode, path->wide, argvlist);
8280
#elif defined(HAVE_RTPSPAWN)
8281
    spawnval = _rtp_spawn(mode, path->narrow, (const char **)argvlist, NULL);
8282
#else
8283
    spawnval = _spawnv(mode, path->narrow, argvlist);
8284
#endif
8285
    _Py_END_SUPPRESS_IPH
8286
    Py_END_ALLOW_THREADS
8287
8288
    int saved_errno = errno;
8289
    free_string_array(argvlist, argc);
8290
8291
    if (spawnval == -1) {
8292
        errno = saved_errno;
8293
        posix_error();
8294
        return NULL;
8295
    }
8296
    return Py_BuildValue(_Py_PARSE_INTPTR, spawnval);
8297
}
8298
8299
/*[clinic input]
8300
os.spawnve
8301
8302
    mode: int
8303
        Mode of process creation.
8304
    path: path_t
8305
        Path of executable file.
8306
    argv: object
8307
        Tuple or list of strings.
8308
    env: object
8309
        Dictionary of strings mapping to strings.
8310
    /
8311
8312
Execute the program specified by path in a new process.
8313
[clinic start generated code]*/
8314
8315
static PyObject *
8316
os_spawnve_impl(PyObject *module, int mode, path_t *path, PyObject *argv,
8317
                PyObject *env)
8318
/*[clinic end generated code: output=30fe85be56fe37ad input=3e40803ee7c4c586]*/
8319
{
8320
    EXECV_CHAR **argvlist;
8321
    EXECV_CHAR **envlist;
8322
    PyObject *res = NULL;
8323
    Py_ssize_t argc, i, envc;
8324
    intptr_t spawnval;
8325
    Py_ssize_t lastarg = 0;
8326
8327
    /* spawnve has four arguments: (mode, path, argv, env), where
8328
       argv is a list or tuple of strings and env is a dictionary
8329
       like posix.environ. */
8330
8331
    if (PyList_Check(argv)) {
8332
        argc = PyList_Size(argv);
8333
    }
8334
    else if (PyTuple_Check(argv)) {
8335
        argc = PyTuple_Size(argv);
8336
    }
8337
    else {
8338
        PyErr_SetString(PyExc_TypeError,
8339
                        "spawnve() arg 2 must be a tuple or list");
8340
        goto fail_0;
8341
    }
8342
    if (argc == 0) {
8343
        PyErr_SetString(PyExc_ValueError,
8344
            "spawnve() arg 2 cannot be empty");
8345
        goto fail_0;
8346
    }
8347
    if (!PyMapping_Check(env)) {
8348
        PyErr_SetString(PyExc_TypeError,
8349
                        "spawnve() arg 3 must be a mapping object");
8350
        goto fail_0;
8351
    }
8352
8353
    argvlist = PyMem_NEW(EXECV_CHAR *, argc+1);
8354
    if (argvlist == NULL) {
8355
        PyErr_NoMemory();
8356
        goto fail_0;
8357
    }
8358
    for (i = 0; i < argc; i++) {
8359
        // The item must be a strong reference because of possible
8360
        // side-effects of PyUnicode_FS{Converter,Decoder}() in
8361
        // fsconvert_strdup(): an item's __fspath__() can mutate a list
8362
        // *argv*, releasing the list's reference to the item (gh-151416).
8363
        PyObject *item = PySequence_ITEM(argv, i);
8364
        if (item == NULL) {
8365
            lastarg = i;
8366
            goto fail_1;
8367
        }
8368
        if (!fsconvert_strdup(item, &argvlist[i])) {
8369
            Py_DECREF(item);
8370
            lastarg = i;
8371
            goto fail_1;
8372
        }
8373
        Py_DECREF(item);
8374
        if (i == 0 && !argvlist[0][0]) {
8375
            lastarg = i + 1;
8376
            PyErr_SetString(
8377
                PyExc_ValueError,
8378
                "spawnve() arg 2 first element cannot be empty");
8379
            goto fail_1;
8380
        }
8381
    }
8382
    lastarg = argc;
8383
    argvlist[argc] = NULL;
8384
8385
    envlist = parse_envlist(env, &envc);
8386
    if (envlist == NULL)
8387
        goto fail_1;
8388
8389
#if !defined(HAVE_RTPSPAWN)
8390
    if (mode == _OLD_P_OVERLAY)
8391
        mode = _P_OVERLAY;
8392
#endif
8393
8394
    if (PySys_Audit("os.spawn", "iOOO", mode, path->object, argv, env) < 0) {
8395
        goto fail_2;
8396
    }
8397
8398
    Py_BEGIN_ALLOW_THREADS
8399
    _Py_BEGIN_SUPPRESS_IPH
8400
#ifdef HAVE_WSPAWNV
8401
    spawnval = _wspawnve(mode, path->wide, argvlist, envlist);
8402
#elif defined(HAVE_RTPSPAWN)
8403
    spawnval = _rtp_spawn(mode, path->narrow, (const char **)argvlist,
8404
                           (const char **)envlist);
8405
#else
8406
    spawnval = _spawnve(mode, path->narrow, argvlist, envlist);
8407
#endif
8408
    _Py_END_SUPPRESS_IPH
8409
    Py_END_ALLOW_THREADS
8410
8411
    if (spawnval == -1)
8412
        (void) posix_error();
8413
    else
8414
        res = Py_BuildValue(_Py_PARSE_INTPTR, spawnval);
8415
8416
  fail_2:
8417
    while (--envc >= 0) {
8418
        PyMem_Free(envlist[envc]);
8419
    }
8420
    PyMem_Free(envlist);
8421
  fail_1:
8422
    free_string_array(argvlist, lastarg);
8423
  fail_0:
8424
    return res;
8425
}
8426
8427
#endif /* HAVE_SPAWNV */
8428
8429
#ifdef HAVE_FORK
8430
8431
/* Helper function to validate arguments.
8432
   Returns 0 on success.  non-zero on failure with a TypeError raised.
8433
   If obj is non-NULL it must be callable.  */
8434
static int
8435
check_null_or_callable(PyObject *obj, const char* obj_name)
8436
60
{
8437
60
    if (obj && !PyCallable_Check(obj)) {
8438
0
        PyErr_Format(PyExc_TypeError, "'%s' must be callable, not %s",
8439
0
                     obj_name, _PyType_Name(Py_TYPE(obj)));
8440
0
        return -1;
8441
0
    }
8442
60
    return 0;
8443
60
}
8444
8445
/*[clinic input]
8446
os.register_at_fork
8447
8448
    *
8449
    before: object=NULL
8450
        A callable to be called in the parent before the fork() syscall.
8451
    after_in_child: object=NULL
8452
        A callable to be called in the child after fork().
8453
    after_in_parent: object=NULL
8454
        A callable to be called in the parent after fork().
8455
8456
Register callables to be called when forking a new process.
8457
8458
'before' callbacks are called in reverse order.
8459
'after_in_child' and 'after_in_parent' callbacks are called in order.
8460
8461
[clinic start generated code]*/
8462
8463
static PyObject *
8464
os_register_at_fork_impl(PyObject *module, PyObject *before,
8465
                         PyObject *after_in_child, PyObject *after_in_parent)
8466
/*[clinic end generated code: output=5398ac75e8e97625 input=cd1187aa85d2312e]*/
8467
20
{
8468
20
    PyInterpreterState *interp;
8469
8470
20
    if (!before && !after_in_child && !after_in_parent) {
8471
0
        PyErr_SetString(PyExc_TypeError, "At least one argument is required.");
8472
0
        return NULL;
8473
0
    }
8474
20
    if (check_null_or_callable(before, "before") ||
8475
20
        check_null_or_callable(after_in_child, "after_in_child") ||
8476
20
        check_null_or_callable(after_in_parent, "after_in_parent")) {
8477
0
        return NULL;
8478
0
    }
8479
20
    interp = _PyInterpreterState_GET();
8480
8481
20
    if (register_at_forker(&interp->before_forkers, before)) {
8482
0
        return NULL;
8483
0
    }
8484
20
    if (register_at_forker(&interp->after_forkers_child, after_in_child)) {
8485
0
        return NULL;
8486
0
    }
8487
20
    if (register_at_forker(&interp->after_forkers_parent, after_in_parent)) {
8488
0
        return NULL;
8489
0
    }
8490
20
    Py_RETURN_NONE;
8491
20
}
8492
#endif /* HAVE_FORK */
8493
8494
#if defined(HAVE_FORK1) || defined(HAVE_FORKPTY) || defined(HAVE_FORK)
8495
// Common code to raise a warning if we detect there is more than one thread
8496
// running in the process. Best effort, silent if unable to count threads.
8497
// Constraint: Quick. Never overcounts. Never leaves an error set.
8498
//
8499
// This MUST only be called from the parent process after
8500
// PyOS_AfterFork_Parent().
8501
static int
8502
warn_about_fork_with_threads(
8503
    const char* name,  // Name of the API to use in the warning message.
8504
    const Py_ssize_t num_os_threads  // Only trusted when >= 1.
8505
)
8506
0
{
8507
    // It's not safe to issue the warning while the world is stopped, because
8508
    // other threads might be holding locks that we need, which would deadlock.
8509
0
    assert(!_PyRuntime.stoptheworld.world_stopped);
8510
8511
0
    Py_ssize_t num_python_threads = num_os_threads;
8512
0
    if (num_python_threads <= 0) {
8513
        // Fall back to just the number our threading module knows about.
8514
        // An incomplete view of the world, but better than nothing.
8515
0
        PyObject *threading = PyImport_GetModule(&_Py_ID(threading));
8516
0
        if (!threading) {
8517
0
            PyErr_Clear();
8518
0
            return 0;
8519
0
        }
8520
0
        PyObject *threading_active =
8521
0
                PyObject_GetAttr(threading, &_Py_ID(_active));
8522
0
        if (!threading_active) {
8523
0
            PyErr_Clear();
8524
0
            Py_DECREF(threading);
8525
0
            return 0;
8526
0
        }
8527
0
        PyObject *threading_limbo =
8528
0
                PyObject_GetAttr(threading, &_Py_ID(_limbo));
8529
0
        if (!threading_limbo) {
8530
0
            PyErr_Clear();
8531
0
            Py_DECREF(threading);
8532
0
            Py_DECREF(threading_active);
8533
0
            return 0;
8534
0
        }
8535
0
        Py_DECREF(threading);
8536
        // Duplicating what threading.active_count() does but without holding
8537
        // threading._active_limbo_lock so our count could be inaccurate if
8538
        // these dicts are mid-update from another thread.  Not a big deal.
8539
        // Worst case if someone replaced threading._active or threading._limbo
8540
        // with non-dicts, we get -1 from *Length() below and undercount.
8541
        // Nobody should, but we're best effort so we clear errors and move on.
8542
0
        num_python_threads = (PyMapping_Length(threading_active)
8543
0
                              + PyMapping_Length(threading_limbo));
8544
0
        PyErr_Clear();
8545
0
        Py_DECREF(threading_active);
8546
0
        Py_DECREF(threading_limbo);
8547
0
    }
8548
0
    if (num_python_threads > 1) {
8549
0
        return PyErr_WarnFormat(
8550
0
                PyExc_DeprecationWarning, 1,
8551
0
#ifdef HAVE_GETPID
8552
0
                "This process (pid=%d) is multi-threaded, "
8553
#else
8554
                "This process is multi-threaded, "
8555
#endif
8556
0
                "use of %s() may lead to deadlocks in the child.",
8557
0
#ifdef HAVE_GETPID
8558
0
                getpid(),
8559
0
#endif
8560
0
                name);
8561
0
    }
8562
0
    return 0;
8563
0
}
8564
8565
// If this returns <= 0, we were unable to successfully use any OS APIs.
8566
// Returns a positive number of threads otherwise.
8567
static Py_ssize_t get_number_of_os_threads(void)
8568
0
{
8569
    // TODO: Consider making an `os` module API to return the current number
8570
    // of threads in the process. That'd presumably use this platform code but
8571
    // raise an error rather than using the inaccurate fallback.
8572
0
    Py_ssize_t num_python_threads = 0;
8573
#if defined(__APPLE__) && defined(HAVE_GETPID)
8574
    mach_port_t macos_self = mach_task_self();
8575
    mach_port_t macos_task;
8576
    if (task_for_pid(macos_self, getpid(), &macos_task) == KERN_SUCCESS) {
8577
        thread_array_t macos_threads;
8578
        mach_msg_type_number_t macos_n_threads;
8579
        if (task_threads(macos_task, &macos_threads,
8580
                         &macos_n_threads) == KERN_SUCCESS) {
8581
            num_python_threads = macos_n_threads;
8582
        }
8583
    }
8584
#elif defined(__linux__)
8585
    // Linux /proc/self/stat 20th field is the number of threads.
8586
0
    FILE* proc_stat = fopen("/proc/self/stat", "r");
8587
0
    if (proc_stat) {
8588
0
        size_t n;
8589
        // Size chosen arbitrarily. ~60% more bytes than a 20th column index
8590
        // observed on the author's workstation.
8591
0
        char stat_line[160];
8592
0
        n = fread(&stat_line, 1, 159, proc_stat);
8593
0
        stat_line[n] = '\0';
8594
0
        fclose(proc_stat);
8595
8596
0
        char *saveptr = NULL;
8597
0
        char *field = strtok_r(stat_line, " ", &saveptr);
8598
0
        unsigned int idx;
8599
0
        for (idx = 19; idx && field; --idx) {
8600
0
            field = strtok_r(NULL, " ", &saveptr);
8601
0
        }
8602
0
        if (idx == 0 && field) {  // found the 20th field
8603
0
            num_python_threads = atoi(field);  // 0 on error
8604
0
        }
8605
0
    }
8606
0
#endif
8607
0
    return num_python_threads;
8608
0
}
8609
#endif  // HAVE_FORK1 || HAVE_FORKPTY || HAVE_FORK
8610
8611
#ifdef HAVE_FORK1
8612
/*[clinic input]
8613
os.fork1
8614
8615
Fork a child process with a single multiplexed (i.e., not bound) thread.
8616
8617
Return 0 to child process and PID of child to parent process.
8618
[clinic start generated code]*/
8619
8620
static PyObject *
8621
os_fork1_impl(PyObject *module)
8622
/*[clinic end generated code: output=0de8e67ce2a310bc input=12db02167893926e]*/
8623
{
8624
    pid_t pid;
8625
8626
    PyInterpreterState *interp = _PyInterpreterState_GET();
8627
    if (_PyInterpreterState_GetFinalizing(interp) != NULL) {
8628
        PyErr_SetString(PyExc_PythonFinalizationError,
8629
                        "can't fork at interpreter shutdown");
8630
        return NULL;
8631
    }
8632
    if (!_Py_IsMainInterpreter(interp)) {
8633
        PyErr_SetString(PyExc_RuntimeError, "fork not supported for subinterpreters");
8634
        return NULL;
8635
    }
8636
    PyOS_BeforeFork();
8637
    pid = fork1();
8638
    int saved_errno = errno;
8639
    if (pid == 0) {
8640
        /* child: this clobbers and resets the import lock. */
8641
        PyOS_AfterFork_Child();
8642
    } else {
8643
        // Called before AfterFork_Parent in case those hooks start threads.
8644
        Py_ssize_t num_os_threads = get_number_of_os_threads();
8645
        /* parent: release the import lock. */
8646
        PyOS_AfterFork_Parent();
8647
        // After PyOS_AfterFork_Parent() starts the world to avoid deadlock.
8648
        if (warn_about_fork_with_threads("fork1", num_os_threads) < 0) {
8649
            return NULL;
8650
        }
8651
    }
8652
    if (pid == -1) {
8653
        errno = saved_errno;
8654
        return posix_error();
8655
    }
8656
    return PyLong_FromPid(pid);
8657
}
8658
#endif /* HAVE_FORK1 */
8659
8660
8661
#ifdef HAVE_FORK
8662
/*[clinic input]
8663
os.fork
8664
8665
Fork a child process.
8666
8667
Return 0 to child process and PID of child to parent process.
8668
[clinic start generated code]*/
8669
8670
static PyObject *
8671
os_fork_impl(PyObject *module)
8672
/*[clinic end generated code: output=3626c81f98985d49 input=13c956413110eeaa]*/
8673
0
{
8674
0
    pid_t pid;
8675
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
8676
0
    if (_PyInterpreterState_GetFinalizing(interp) != NULL) {
8677
0
        PyErr_SetString(PyExc_PythonFinalizationError,
8678
0
                        "can't fork at interpreter shutdown");
8679
0
        return NULL;
8680
0
    }
8681
0
    if (!_PyInterpreterState_HasFeature(interp, Py_RTFLAGS_FORK)) {
8682
0
        PyErr_SetString(PyExc_RuntimeError,
8683
0
                        "fork not supported for isolated subinterpreters");
8684
0
        return NULL;
8685
0
    }
8686
0
    if (PySys_Audit("os.fork", NULL) < 0) {
8687
0
        return NULL;
8688
0
    }
8689
0
    PyOS_BeforeFork();
8690
0
    pid = fork();
8691
0
    int saved_errno = errno;
8692
0
    if (pid == 0) {
8693
        /* child: this clobbers and resets the import lock. */
8694
0
        PyOS_AfterFork_Child();
8695
0
    } else {
8696
        // Called before AfterFork_Parent in case those hooks start threads.
8697
0
        Py_ssize_t num_os_threads = get_number_of_os_threads();
8698
        /* parent: release the import lock. */
8699
0
        PyOS_AfterFork_Parent();
8700
        // After PyOS_AfterFork_Parent() starts the world to avoid deadlock.
8701
0
        if (warn_about_fork_with_threads("fork", num_os_threads) < 0)
8702
0
            return NULL;
8703
0
    }
8704
0
    if (pid == -1) {
8705
0
        errno = saved_errno;
8706
0
        return posix_error();
8707
0
    }
8708
0
    return PyLong_FromPid(pid);
8709
0
}
8710
#endif /* HAVE_FORK */
8711
8712
8713
#ifdef HAVE_SCHED_H
8714
#ifdef HAVE_SCHED_GET_PRIORITY_MAX
8715
/*[clinic input]
8716
os.sched_get_priority_max
8717
8718
    policy: int
8719
8720
Get the maximum scheduling priority for policy.
8721
[clinic start generated code]*/
8722
8723
static PyObject *
8724
os_sched_get_priority_max_impl(PyObject *module, int policy)
8725
/*[clinic end generated code: output=9e465c6e43130521 input=2097b7998eca6874]*/
8726
0
{
8727
    /* make sure that errno is cleared before the call */
8728
0
    errno = 0;
8729
0
    int max = sched_get_priority_max(policy);
8730
0
    if (max == -1 && errno)
8731
0
        return posix_error();
8732
0
    return PyLong_FromLong(max);
8733
0
}
8734
8735
8736
/*[clinic input]
8737
os.sched_get_priority_min
8738
8739
    policy: int
8740
8741
Get the minimum scheduling priority for policy.
8742
[clinic start generated code]*/
8743
8744
static PyObject *
8745
os_sched_get_priority_min_impl(PyObject *module, int policy)
8746
/*[clinic end generated code: output=7595c1138cc47a6d input=21bc8fa0d70983bf]*/
8747
0
{
8748
    /* make sure that errno is cleared before the call */
8749
0
    errno = 0;
8750
0
    int min = sched_get_priority_min(policy);
8751
0
    if (min == -1 && errno)
8752
0
        return posix_error();
8753
0
    return PyLong_FromLong(min);
8754
0
}
8755
#endif /* HAVE_SCHED_GET_PRIORITY_MAX */
8756
8757
8758
#ifdef HAVE_SCHED_SETSCHEDULER
8759
/*[clinic input]
8760
os.sched_getscheduler
8761
    pid: pid_t
8762
    /
8763
8764
Get the scheduling policy for the process identified by pid.
8765
8766
Passing 0 for pid returns the scheduling policy for the calling process.
8767
[clinic start generated code]*/
8768
8769
static PyObject *
8770
os_sched_getscheduler_impl(PyObject *module, pid_t pid)
8771
/*[clinic end generated code: output=dce4c0bd3f1b34c8 input=8d99dac505485ac8]*/
8772
0
{
8773
0
    int policy;
8774
8775
0
    policy = sched_getscheduler(pid);
8776
0
    if (policy < 0)
8777
0
        return posix_error();
8778
0
    return PyLong_FromLong(policy);
8779
0
}
8780
#endif /* HAVE_SCHED_SETSCHEDULER */
8781
8782
8783
#if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
8784
/*[clinic input]
8785
class os.sched_param "PyObject *" "SchedParamType"
8786
8787
@classmethod
8788
os.sched_param.__new__
8789
8790
    sched_priority: object
8791
        A scheduling parameter.
8792
8793
Currently has only one field: sched_priority
8794
[clinic start generated code]*/
8795
8796
static PyObject *
8797
os_sched_param_impl(PyTypeObject *type, PyObject *sched_priority)
8798
/*[clinic end generated code: output=48f4067d60f48c13 input=eb42909a2c0e3e6c]*/
8799
0
{
8800
0
    PyObject *res;
8801
8802
0
    res = PyStructSequence_New(type);
8803
0
    if (!res)
8804
0
        return NULL;
8805
0
    PyStructSequence_SET_ITEM(res, 0, Py_NewRef(sched_priority));
8806
0
    return res;
8807
0
}
8808
8809
static PyObject *
8810
os_sched_param_reduce(PyObject *self, PyObject *Py_UNUSED(dummy))
8811
0
{
8812
0
    return Py_BuildValue("(O(O))", Py_TYPE(self), PyStructSequence_GetItem(self, 0));
8813
0
}
8814
8815
static PyMethodDef os_sched_param_reduce_method = {
8816
    "__reduce__", os_sched_param_reduce, METH_NOARGS | METH_COEXIST, NULL,
8817
};
8818
8819
PyDoc_VAR(os_sched_param__doc__);
8820
8821
static PyStructSequence_Field sched_param_fields[] = {
8822
    {"sched_priority", "the scheduling priority"},
8823
    {0}
8824
};
8825
8826
static PyStructSequence_Desc sched_param_desc = {
8827
    "os.sched_param", /* name */
8828
    os_sched_param__doc__, /* doc */
8829
    sched_param_fields,
8830
    1
8831
};
8832
8833
static int
8834
convert_sched_param(PyObject *module, PyObject *param, struct sched_param *res)
8835
0
{
8836
0
    long priority;
8837
8838
0
    if (!Py_IS_TYPE(param, (PyTypeObject *)get_posix_state(module)->SchedParamType)) {
8839
0
        PyErr_SetString(PyExc_TypeError, "must have a sched_param object");
8840
0
        return 0;
8841
0
    }
8842
0
    priority = PyLong_AsLong(PyStructSequence_GET_ITEM(param, 0));
8843
0
    if (priority == -1 && PyErr_Occurred())
8844
0
        return 0;
8845
0
    if (priority > INT_MAX || priority < INT_MIN) {
8846
0
        PyErr_SetString(PyExc_OverflowError, "sched_priority out of range");
8847
0
        return 0;
8848
0
    }
8849
0
    res->sched_priority = Py_SAFE_DOWNCAST(priority, long, int);
8850
0
    return 1;
8851
0
}
8852
#endif /* defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM) */
8853
8854
8855
#ifdef HAVE_SCHED_SETSCHEDULER
8856
/*[clinic input]
8857
os.sched_setscheduler
8858
8859
    pid: pid_t
8860
    policy: int
8861
    param as param_obj: object
8862
    /
8863
8864
Set the scheduling policy for the process identified by pid.
8865
8866
If pid is 0, the calling process is changed.
8867
param is an instance of sched_param.
8868
[clinic start generated code]*/
8869
8870
static PyObject *
8871
os_sched_setscheduler_impl(PyObject *module, pid_t pid, int policy,
8872
                           PyObject *param_obj)
8873
/*[clinic end generated code: output=cde27faa55dc993e input=73013d731bd8fbe9]*/
8874
0
{
8875
0
    struct sched_param param;
8876
0
    if (!convert_sched_param(module, param_obj, &param)) {
8877
0
        return NULL;
8878
0
    }
8879
8880
    /*
8881
    ** sched_setscheduler() returns 0 in Linux, but the previous
8882
    ** scheduling policy under Solaris/Illumos, and others.
8883
    ** On error, -1 is returned in all Operating Systems.
8884
    */
8885
0
    if (sched_setscheduler(pid, policy, &param) == -1)
8886
0
        return posix_error();
8887
0
    Py_RETURN_NONE;
8888
0
}
8889
#endif  /* HAVE_SCHED_SETSCHEDULER*/
8890
8891
8892
#ifdef HAVE_SCHED_SETPARAM
8893
/*[clinic input]
8894
os.sched_getparam
8895
    pid: pid_t
8896
    /
8897
8898
Returns scheduling parameters for the process identified by pid.
8899
8900
If pid is 0, returns parameters for the calling process.
8901
Return value is an instance of sched_param.
8902
[clinic start generated code]*/
8903
8904
static PyObject *
8905
os_sched_getparam_impl(PyObject *module, pid_t pid)
8906
/*[clinic end generated code: output=b194e8708dcf2db8 input=18a1ef9c2efae296]*/
8907
0
{
8908
0
    struct sched_param param;
8909
0
    PyObject *result;
8910
0
    PyObject *priority;
8911
8912
0
    if (sched_getparam(pid, &param))
8913
0
        return posix_error();
8914
0
    PyObject *SchedParamType = get_posix_state(module)->SchedParamType;
8915
0
    result = PyStructSequence_New((PyTypeObject *)SchedParamType);
8916
0
    if (!result)
8917
0
        return NULL;
8918
0
    priority = PyLong_FromLong(param.sched_priority);
8919
0
    if (!priority) {
8920
0
        Py_DECREF(result);
8921
0
        return NULL;
8922
0
    }
8923
0
    PyStructSequence_SET_ITEM(result, 0, priority);
8924
0
    return result;
8925
0
}
8926
8927
8928
/*[clinic input]
8929
os.sched_setparam
8930
    pid: pid_t
8931
    param as param_obj: object
8932
    /
8933
8934
Set scheduling parameters for the process identified by pid.
8935
8936
If pid is 0, sets parameters for the calling process.
8937
param should be an instance of sched_param.
8938
[clinic start generated code]*/
8939
8940
static PyObject *
8941
os_sched_setparam_impl(PyObject *module, pid_t pid, PyObject *param_obj)
8942
/*[clinic end generated code: output=f19fe020a53741c1 input=27b98337c8b2dcc7]*/
8943
0
{
8944
0
    struct sched_param param;
8945
0
    if (!convert_sched_param(module, param_obj, &param)) {
8946
0
        return NULL;
8947
0
    }
8948
8949
0
    if (sched_setparam(pid, &param))
8950
0
        return posix_error();
8951
0
    Py_RETURN_NONE;
8952
0
}
8953
#endif /* HAVE_SCHED_SETPARAM */
8954
8955
8956
#ifdef HAVE_SCHED_RR_GET_INTERVAL
8957
/*[clinic input]
8958
@permit_long_summary
8959
os.sched_rr_get_interval -> double
8960
    pid: pid_t
8961
    /
8962
8963
Return the round-robin quantum for the process identified by pid, in seconds.
8964
8965
Value returned is a float.
8966
[clinic start generated code]*/
8967
8968
static double
8969
os_sched_rr_get_interval_impl(PyObject *module, pid_t pid)
8970
/*[clinic end generated code: output=7e2d935833ab47dc input=cab0b83586776b10]*/
8971
0
{
8972
0
    struct timespec interval;
8973
0
    if (sched_rr_get_interval(pid, &interval)) {
8974
0
        posix_error();
8975
0
        return -1.0;
8976
0
    }
8977
#ifdef _Py_MEMORY_SANITIZER
8978
    __msan_unpoison(&interval, sizeof(interval));
8979
#endif
8980
0
    return (double)interval.tv_sec + 1e-9*interval.tv_nsec;
8981
0
}
8982
#endif /* HAVE_SCHED_RR_GET_INTERVAL */
8983
8984
8985
/*[clinic input]
8986
os.sched_yield
8987
8988
Voluntarily relinquish the CPU.
8989
[clinic start generated code]*/
8990
8991
static PyObject *
8992
os_sched_yield_impl(PyObject *module)
8993
/*[clinic end generated code: output=902323500f222cac input=e54d6f98189391d4]*/
8994
0
{
8995
0
    int result;
8996
0
    Py_BEGIN_ALLOW_THREADS
8997
0
    result = sched_yield();
8998
0
    Py_END_ALLOW_THREADS
8999
0
    if (result < 0) {
9000
0
        return posix_error();
9001
0
    }
9002
0
    Py_RETURN_NONE;
9003
0
}
9004
9005
#ifdef HAVE_SCHED_SETAFFINITY
9006
/* The minimum number of CPUs allocated in a cpu_set_t */
9007
static const int NCPUS_START = sizeof(unsigned long) * CHAR_BIT;
9008
9009
/*[clinic input]
9010
os.sched_setaffinity
9011
    pid: pid_t
9012
    mask : object
9013
    /
9014
9015
Set the CPU affinity of the process identified by pid to mask.
9016
9017
mask should be an iterable of integers identifying CPUs.
9018
[clinic start generated code]*/
9019
9020
static PyObject *
9021
os_sched_setaffinity_impl(PyObject *module, pid_t pid, PyObject *mask)
9022
/*[clinic end generated code: output=882d7dd9a229335b input=a0791a597c7085ba]*/
9023
0
{
9024
0
    int ncpus;
9025
0
    size_t setsize;
9026
0
    cpu_set_t *cpu_set = NULL;
9027
0
    PyObject *iterator = NULL, *item;
9028
9029
0
    iterator = PyObject_GetIter(mask);
9030
0
    if (iterator == NULL)
9031
0
        return NULL;
9032
9033
0
    ncpus = NCPUS_START;
9034
0
    setsize = CPU_ALLOC_SIZE(ncpus);
9035
0
    cpu_set = CPU_ALLOC(ncpus);
9036
0
    if (cpu_set == NULL) {
9037
0
        PyErr_NoMemory();
9038
0
        goto error;
9039
0
    }
9040
0
    CPU_ZERO_S(setsize, cpu_set);
9041
9042
0
    while ((item = PyIter_Next(iterator))) {
9043
0
        long cpu;
9044
0
        if (!PyIndex_Check(item)) {
9045
0
            PyErr_Format(PyExc_TypeError,
9046
0
                        "expected an iterator of ints, "
9047
0
                        "but iterator yielded %R",
9048
0
                        Py_TYPE(item));
9049
0
            Py_DECREF(item);
9050
0
            goto error;
9051
0
        }
9052
0
        cpu = PyLong_AsLong(item);
9053
0
        Py_DECREF(item);
9054
0
        if (cpu < 0) {
9055
0
            if (!PyErr_Occurred())
9056
0
                PyErr_SetString(PyExc_ValueError, "negative CPU number");
9057
0
            goto error;
9058
0
        }
9059
0
        if (cpu > INT_MAX - 1) {
9060
0
            PyErr_SetString(PyExc_OverflowError, "CPU number too large");
9061
0
            goto error;
9062
0
        }
9063
0
        if (cpu >= ncpus) {
9064
            /* Grow CPU mask to fit the CPU number */
9065
0
            int newncpus = ncpus;
9066
0
            cpu_set_t *newmask;
9067
0
            size_t newsetsize;
9068
0
            while (newncpus <= cpu) {
9069
0
                if (newncpus > INT_MAX / 2)
9070
0
                    newncpus = cpu + 1;
9071
0
                else
9072
0
                    newncpus = newncpus * 2;
9073
0
            }
9074
0
            newmask = CPU_ALLOC(newncpus);
9075
0
            if (newmask == NULL) {
9076
0
                PyErr_NoMemory();
9077
0
                goto error;
9078
0
            }
9079
0
            newsetsize = CPU_ALLOC_SIZE(newncpus);
9080
0
            CPU_ZERO_S(newsetsize, newmask);
9081
0
            memcpy(newmask, cpu_set, setsize);
9082
0
            CPU_FREE(cpu_set);
9083
0
            setsize = newsetsize;
9084
0
            cpu_set = newmask;
9085
0
            ncpus = newncpus;
9086
0
        }
9087
0
        CPU_SET_S(cpu, setsize, cpu_set);
9088
0
    }
9089
0
    if (PyErr_Occurred()) {
9090
0
        goto error;
9091
0
    }
9092
0
    Py_CLEAR(iterator);
9093
9094
0
    if (sched_setaffinity(pid, setsize, cpu_set)) {
9095
0
        posix_error();
9096
0
        goto error;
9097
0
    }
9098
0
    CPU_FREE(cpu_set);
9099
0
    Py_RETURN_NONE;
9100
9101
0
error:
9102
0
    if (cpu_set)
9103
0
        CPU_FREE(cpu_set);
9104
0
    Py_XDECREF(iterator);
9105
0
    return NULL;
9106
0
}
9107
9108
9109
/*[clinic input]
9110
@permit_long_summary
9111
os.sched_getaffinity
9112
    pid: pid_t
9113
    /
9114
9115
Return the affinity of the process identified by pid (or the current process if zero).
9116
9117
The affinity is returned as a set of CPU identifiers.
9118
[clinic start generated code]*/
9119
9120
static PyObject *
9121
os_sched_getaffinity_impl(PyObject *module, pid_t pid)
9122
/*[clinic end generated code: output=f726f2c193c17a4f input=cb79ff13579ef091]*/
9123
0
{
9124
0
    int ncpus = NCPUS_START;
9125
0
    size_t setsize;
9126
0
    cpu_set_t *mask;
9127
9128
0
    while (1) {
9129
0
        setsize = CPU_ALLOC_SIZE(ncpus);
9130
0
        mask = CPU_ALLOC(ncpus);
9131
0
        if (mask == NULL) {
9132
0
            return PyErr_NoMemory();
9133
0
        }
9134
0
        if (sched_getaffinity(pid, setsize, mask) == 0) {
9135
0
            break;
9136
0
        }
9137
0
        CPU_FREE(mask);
9138
0
        if (errno != EINVAL) {
9139
0
            return posix_error();
9140
0
        }
9141
0
        if (ncpus > INT_MAX / 2) {
9142
0
            PyErr_SetString(PyExc_OverflowError,
9143
0
                            "could not allocate a large enough CPU set");
9144
0
            return NULL;
9145
0
        }
9146
0
        ncpus *= 2;
9147
0
    }
9148
9149
0
    PyObject *res = PySet_New(NULL);
9150
0
    if (res == NULL) {
9151
0
        goto error;
9152
0
    }
9153
9154
0
    int cpu = 0;
9155
0
    int count = CPU_COUNT_S(setsize, mask);
9156
0
    for (; count; cpu++) {
9157
0
        if (CPU_ISSET_S(cpu, setsize, mask)) {
9158
0
            PyObject *cpu_num = PyLong_FromLong(cpu);
9159
0
            --count;
9160
0
            if (cpu_num == NULL) {
9161
0
                goto error;
9162
0
            }
9163
0
            if (PySet_Add(res, cpu_num)) {
9164
0
                Py_DECREF(cpu_num);
9165
0
                goto error;
9166
0
            }
9167
0
            Py_DECREF(cpu_num);
9168
0
        }
9169
0
    }
9170
0
    CPU_FREE(mask);
9171
0
    return res;
9172
9173
0
error:
9174
0
    if (mask) {
9175
0
        CPU_FREE(mask);
9176
0
    }
9177
0
    Py_XDECREF(res);
9178
0
    return NULL;
9179
0
}
9180
#endif /* HAVE_SCHED_SETAFFINITY */
9181
9182
#endif /* HAVE_SCHED_H */
9183
9184
9185
#ifdef HAVE_POSIX_OPENPT
9186
/*[clinic input]
9187
os.posix_openpt -> int
9188
9189
    oflag: int
9190
    /
9191
9192
Open and return a file descriptor for a master pseudo-terminal device.
9193
9194
Performs a posix_openpt() C function call. The oflag argument is used to
9195
set file status flags and file access modes as specified in the manual
9196
page of posix_openpt() of your system.
9197
[clinic start generated code]*/
9198
9199
static int
9200
os_posix_openpt_impl(PyObject *module, int oflag)
9201
/*[clinic end generated code: output=ee0bc2624305fc79 input=3ce4eb297fa64307]*/
9202
0
{
9203
0
    int fd;
9204
9205
    // OpenBSD posix_openpt() rejects any flag other than O_RDWR and
9206
    // O_NOCTTY; the fd is made non-inheritable below in any case.
9207
0
#if defined(O_CLOEXEC) && !defined(__OpenBSD__)
9208
0
    oflag |= O_CLOEXEC;
9209
0
#endif
9210
9211
0
    fd = posix_openpt(oflag);
9212
0
    if (fd == -1) {
9213
0
        posix_error();
9214
0
        return -1;
9215
0
    }
9216
9217
    // Just in case, likely a no-op given O_CLOEXEC above.
9218
0
    if (_Py_set_inheritable(fd, 0, NULL) < 0) {
9219
0
        close(fd);
9220
0
        return -1;
9221
0
    }
9222
9223
0
    return fd;
9224
0
}
9225
#endif /* HAVE_POSIX_OPENPT */
9226
9227
#ifdef HAVE_GRANTPT
9228
/*[clinic input]
9229
os.grantpt
9230
9231
    fd: fildes
9232
        File descriptor of a master pseudo-terminal device.
9233
    /
9234
9235
Grant access to the slave pseudo-terminal device.
9236
9237
Performs a grantpt() C function call.
9238
[clinic start generated code]*/
9239
9240
static PyObject *
9241
os_grantpt_impl(PyObject *module, int fd)
9242
/*[clinic end generated code: output=dfd580015cf548ab input=0668e3b96760e849]*/
9243
0
{
9244
0
    int ret;
9245
0
    int saved_errno;
9246
0
    PyOS_sighandler_t sig_saved;
9247
9248
0
    sig_saved = PyOS_setsig(SIGCHLD, SIG_DFL);
9249
9250
0
    ret = grantpt(fd);
9251
0
    if (ret == -1)
9252
0
        saved_errno = errno;
9253
9254
0
    PyOS_setsig(SIGCHLD, sig_saved);
9255
9256
0
    if (ret == -1) {
9257
0
        errno = saved_errno;
9258
0
        return posix_error();
9259
0
    }
9260
9261
0
    Py_RETURN_NONE;
9262
0
}
9263
#endif /* HAVE_GRANTPT */
9264
9265
#ifdef HAVE_UNLOCKPT
9266
/*[clinic input]
9267
os.unlockpt
9268
9269
    fd: fildes
9270
        File descriptor of a master pseudo-terminal device.
9271
    /
9272
9273
Unlock a pseudo-terminal master/slave pair.
9274
9275
Performs an unlockpt() C function call.
9276
[clinic start generated code]*/
9277
9278
static PyObject *
9279
os_unlockpt_impl(PyObject *module, int fd)
9280
/*[clinic end generated code: output=e08d354dec12d30c input=de7ab1f59f69a2b4]*/
9281
0
{
9282
0
    if (unlockpt(fd) == -1)
9283
0
        return posix_error();
9284
9285
0
    Py_RETURN_NONE;
9286
0
}
9287
#endif /* HAVE_UNLOCKPT */
9288
9289
#if defined(HAVE_PTSNAME) || defined(HAVE_PTSNAME_R)
9290
static PyObject *
9291
py_ptsname(int fd)
9292
0
{
9293
0
    // POSIX manpage: Upon failure, ptsname() shall return a null pointer
9294
0
    // and may set errno. Always initialize errno to avoid undefined behavior.
9295
0
    errno = 0;
9296
0
    char *name = ptsname(fd);
9297
0
    if (name == NULL) {
9298
0
        return posix_error();
9299
0
    }
9300
0
    return PyUnicode_DecodeFSDefault(name);
9301
0
}
9302
9303
/*[clinic input]
9304
os.ptsname
9305
9306
    fd: fildes
9307
        File descriptor of a master pseudo-terminal device.
9308
    /
9309
9310
Return the name of the slave pseudo-terminal device.
9311
9312
If the ptsname_r() C function is available, it is called;
9313
otherwise, performs a ptsname() C function call.
9314
[clinic start generated code]*/
9315
9316
static PyObject *
9317
os_ptsname_impl(PyObject *module, int fd)
9318
/*[clinic end generated code: output=ef300fadc5675872 input=1369ccc0546f3130]*/
9319
0
{
9320
0
#ifdef HAVE_PTSNAME_R
9321
0
    int ret;
9322
0
    char name[MAXPATHLEN+1];
9323
9324
0
    if (HAVE_PTSNAME_R_RUNTIME) {
9325
0
        ret = ptsname_r(fd, name, sizeof(name));
9326
0
    }
9327
0
    else {
9328
        // fallback to ptsname() if ptsname_r() is not available in runtime.
9329
0
        return py_ptsname(fd);
9330
0
    }
9331
0
    if (ret != 0) {
9332
0
        errno = ret;
9333
0
        return posix_error();
9334
0
    }
9335
9336
0
    return PyUnicode_DecodeFSDefault(name);
9337
#else
9338
    return py_ptsname(fd);
9339
#endif /* HAVE_PTSNAME_R */
9340
0
}
9341
#endif /* defined(HAVE_PTSNAME) || defined(HAVE_PTSNAME_R) */
9342
9343
/* AIX uses /dev/ptc but is otherwise the same as /dev/ptmx */
9344
#if defined(HAVE_DEV_PTC) && !defined(HAVE_DEV_PTMX)
9345
#  define DEV_PTY_FILE "/dev/ptc"
9346
#  define HAVE_DEV_PTMX
9347
#else
9348
#  define DEV_PTY_FILE "/dev/ptmx"
9349
#endif
9350
9351
#if defined(HAVE_OPENPTY) || defined(HAVE_FORKPTY) || defined(HAVE_LOGIN_TTY) || defined(HAVE_DEV_PTMX)
9352
#ifdef HAVE_PTY_H
9353
#include <pty.h>
9354
#elif defined(HAVE_LIBUTIL_H)
9355
#include <libutil.h>
9356
#elif defined(HAVE_UTIL_H)
9357
#include <util.h>
9358
#endif /* HAVE_PTY_H */
9359
#ifdef HAVE_UTMP_H
9360
#include <utmp.h>
9361
#endif /* HAVE_UTMP_H */
9362
#ifdef HAVE_STROPTS_H
9363
#include <stropts.h>
9364
#endif
9365
#endif /* defined(HAVE_OPENPTY) || defined(HAVE_FORKPTY) || defined(HAVE_LOGIN_TTY) || defined(HAVE_DEV_PTMX) */
9366
9367
9368
#if defined(HAVE_OPENPTY) || defined(HAVE__GETPTY) || defined(HAVE_DEV_PTMX)
9369
/*[clinic input]
9370
os.openpty
9371
9372
Open a pseudo-terminal.
9373
9374
Return a tuple of (master_fd, slave_fd) containing open file descriptors
9375
for both the master and slave ends.
9376
[clinic start generated code]*/
9377
9378
static PyObject *
9379
os_openpty_impl(PyObject *module)
9380
/*[clinic end generated code: output=98841ce5ec9cef3c input=f3d99fd99e762907]*/
9381
0
{
9382
0
    int master_fd = -1, slave_fd = -1;
9383
#ifndef HAVE_OPENPTY
9384
    char * slave_name;
9385
#endif
9386
#if defined(HAVE_DEV_PTMX) && !defined(HAVE_OPENPTY) && !defined(HAVE__GETPTY)
9387
    PyOS_sighandler_t sig_saved;
9388
#if defined(__sun) && defined(__SVR4)
9389
    extern char *ptsname(int fildes);
9390
#endif
9391
#endif
9392
9393
0
#ifdef HAVE_OPENPTY
9394
0
    if (openpty(&master_fd, &slave_fd, NULL, NULL, NULL) != 0)
9395
0
        goto posix_error;
9396
9397
0
    if (_Py_set_inheritable(master_fd, 0, NULL) < 0)
9398
0
        goto error;
9399
0
    if (_Py_set_inheritable(slave_fd, 0, NULL) < 0)
9400
0
        goto error;
9401
9402
#elif defined(HAVE__GETPTY)
9403
    slave_name = _getpty(&master_fd, O_RDWR, 0666, 0);
9404
    if (slave_name == NULL)
9405
        goto posix_error;
9406
    if (_Py_set_inheritable(master_fd, 0, NULL) < 0)
9407
        goto error;
9408
9409
    slave_fd = _Py_open(slave_name, O_RDWR);
9410
    if (slave_fd < 0)
9411
        goto error;
9412
9413
#else
9414
    master_fd = open(DEV_PTY_FILE, O_RDWR | O_NOCTTY); /* open master */
9415
    if (master_fd < 0)
9416
        goto posix_error;
9417
9418
    sig_saved = PyOS_setsig(SIGCHLD, SIG_DFL);
9419
9420
    /* change permission of slave */
9421
    if (grantpt(master_fd) < 0) {
9422
        int saved_errno = errno;
9423
        PyOS_setsig(SIGCHLD, sig_saved);
9424
        errno = saved_errno;
9425
        goto posix_error;
9426
    }
9427
9428
    /* unlock slave */
9429
    if (unlockpt(master_fd) < 0) {
9430
        int saved_errno = errno;
9431
        PyOS_setsig(SIGCHLD, sig_saved);
9432
        errno = saved_errno;
9433
        goto posix_error;
9434
    }
9435
9436
    PyOS_setsig(SIGCHLD, sig_saved);
9437
9438
    slave_name = ptsname(master_fd); /* get name of slave */
9439
    if (slave_name == NULL)
9440
        goto posix_error;
9441
9442
    slave_fd = _Py_open(slave_name, O_RDWR | O_NOCTTY); /* open slave */
9443
    if (slave_fd == -1)
9444
        goto error;
9445
9446
    if (_Py_set_inheritable(master_fd, 0, NULL) < 0)
9447
        goto posix_error;
9448
9449
#if defined(HAVE_STROPTS_H) && !defined(HAVE_DEV_PTC)
9450
    // Pushing "ptem" makes the slave a terminal, which a session leader
9451
    // without a controlling terminal then acquires as one despite O_NOCTTY.
9452
    // Note whether we already had one, so a new one can be disowned below.
9453
    int had_ctty = 0;
9454
#ifdef TIOCNOTTY
9455
    int tty_fd = open("/dev/tty", O_RDONLY | O_NOCTTY);
9456
    if (tty_fd >= 0) {
9457
        had_ctty = 1;
9458
        close(tty_fd);
9459
    }
9460
#endif
9461
    ioctl(slave_fd, I_PUSH, "ptem"); /* push ptem */
9462
    ioctl(slave_fd, I_PUSH, "ldterm"); /* push ldterm */
9463
#ifndef __hpux
9464
    ioctl(slave_fd, I_PUSH, "ttcompat"); /* push ttcompat */
9465
#endif /* __hpux */
9466
#ifdef TIOCNOTTY
9467
    if (!had_ctty && getsid(0) == getpid()) {
9468
        // Disown it; TIOCNOTTY sends SIGHUP to the session leader.
9469
        PyOS_sighandler_t sig_saved = PyOS_setsig(SIGHUP, SIG_IGN);
9470
        ioctl(slave_fd, TIOCNOTTY);
9471
        PyOS_setsig(SIGHUP, sig_saved);
9472
    }
9473
#endif
9474
#endif /* defined(HAVE_STROPTS_H) && !defined(HAVE_DEV_PTC) */
9475
#endif /* HAVE_OPENPTY */
9476
9477
0
    return Py_BuildValue("(ii)", master_fd, slave_fd);
9478
9479
0
posix_error:
9480
0
    posix_error();
9481
0
error:
9482
0
    if (master_fd != -1)
9483
0
        close(master_fd);
9484
0
    if (slave_fd != -1)
9485
0
        close(slave_fd);
9486
0
    return NULL;
9487
0
}
9488
#endif /* defined(HAVE_OPENPTY) || defined(HAVE__GETPTY) || defined(HAVE_DEV_PTMX) */
9489
9490
9491
#if defined(HAVE_SETSID) && defined(TIOCSCTTY)
9492
#define HAVE_FALLBACK_LOGIN_TTY 1
9493
#endif /* defined(HAVE_SETSID) && defined(TIOCSCTTY) */
9494
9495
#if defined(HAVE_LOGIN_TTY) || defined(HAVE_FALLBACK_LOGIN_TTY)
9496
/*[clinic input]
9497
@permit_long_summary
9498
os.login_tty
9499
9500
    fd: fildes
9501
    /
9502
9503
Prepare the tty of which fd is a file descriptor for a new login session.
9504
9505
Make the calling process a session leader; make the tty the
9506
controlling tty, the stdin, the stdout, and the stderr of the
9507
calling process; close fd.
9508
[clinic start generated code]*/
9509
9510
static PyObject *
9511
os_login_tty_impl(PyObject *module, int fd)
9512
/*[clinic end generated code: output=495a79911b4cc1bc input=b102a7c36e8baf00]*/
9513
0
{
9514
0
#ifdef HAVE_LOGIN_TTY
9515
0
    if (login_tty(fd) == -1) {
9516
0
        return posix_error();
9517
0
    }
9518
#else /* defined(HAVE_FALLBACK_LOGIN_TTY) */
9519
    /* Establish a new session. */
9520
    if (setsid() == -1) {
9521
        return posix_error();
9522
    }
9523
9524
    /* The tty becomes the controlling terminal. */
9525
    if (ioctl(fd, TIOCSCTTY, (char *)NULL) == -1) {
9526
        return posix_error();
9527
    }
9528
9529
    /* The tty becomes stdin/stdout/stderr */
9530
    if (dup2(fd, 0) == -1 || dup2(fd, 1) == -1 || dup2(fd, 2) == -1) {
9531
        return posix_error();
9532
    }
9533
    if (fd > 2) {
9534
        close(fd);
9535
    }
9536
#endif /* HAVE_LOGIN_TTY */
9537
0
    Py_RETURN_NONE;
9538
0
}
9539
#endif /* defined(HAVE_LOGIN_TTY) || defined(HAVE_FALLBACK_LOGIN_TTY) */
9540
9541
9542
#ifdef HAVE_FORKPTY
9543
/*[clinic input]
9544
os.forkpty
9545
9546
Fork a new process with a new pseudo-terminal as controlling tty.
9547
9548
Returns a tuple of (pid, master_fd).
9549
Like fork(), return pid of 0 to the child process,
9550
and pid of child to the parent process.
9551
To both, return fd of newly opened pseudo-terminal.
9552
The master_fd is non-inheritable.
9553
[clinic start generated code]*/
9554
9555
static PyObject *
9556
os_forkpty_impl(PyObject *module)
9557
/*[clinic end generated code: output=60d0a5c7512e4087 input=24765e0f33275b3b]*/
9558
0
{
9559
0
    int master_fd = -1;
9560
0
    pid_t pid;
9561
9562
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
9563
0
    if (_PyInterpreterState_GetFinalizing(interp) != NULL) {
9564
0
        PyErr_SetString(PyExc_PythonFinalizationError,
9565
0
                        "can't fork at interpreter shutdown");
9566
0
        return NULL;
9567
0
    }
9568
0
    if (!_Py_IsMainInterpreter(interp)) {
9569
0
        PyErr_SetString(PyExc_RuntimeError, "fork not supported for subinterpreters");
9570
0
        return NULL;
9571
0
    }
9572
0
    if (PySys_Audit("os.forkpty", NULL) < 0) {
9573
0
        return NULL;
9574
0
    }
9575
0
    PyOS_BeforeFork();
9576
0
    pid = forkpty(&master_fd, NULL, NULL, NULL);
9577
0
    if (pid == 0) {
9578
        /* child: this clobbers and resets the import lock. */
9579
0
        PyOS_AfterFork_Child();
9580
0
    } else {
9581
        // Called before AfterFork_Parent in case those hooks start threads.
9582
0
        Py_ssize_t num_os_threads = get_number_of_os_threads();
9583
        /* parent: release the import lock. */
9584
0
        PyOS_AfterFork_Parent();
9585
        /* set O_CLOEXEC on master_fd */
9586
0
        if (_Py_set_inheritable(master_fd, 0, NULL) < 0) {
9587
0
            PyErr_FormatUnraisable("Exception ignored when setting master_fd "
9588
0
                                   "non-inheritable in forkpty()");
9589
0
        }
9590
9591
        // After PyOS_AfterFork_Parent() starts the world to avoid deadlock.
9592
0
        if (warn_about_fork_with_threads("forkpty", num_os_threads) < 0)
9593
0
            return NULL;
9594
0
    }
9595
0
    if (pid == -1) {
9596
0
        return posix_error();
9597
0
    }
9598
9599
0
    return Py_BuildValue("(Ni)", PyLong_FromPid(pid), master_fd);
9600
0
}
9601
#endif /* HAVE_FORKPTY */
9602
9603
9604
#ifdef HAVE_GETEGID
9605
/*[clinic input]
9606
os.getegid
9607
9608
Return the current process's effective group id.
9609
[clinic start generated code]*/
9610
9611
static PyObject *
9612
os_getegid_impl(PyObject *module)
9613
/*[clinic end generated code: output=67d9be7ac68898a2 input=1596f79ad1107d5d]*/
9614
37
{
9615
37
    return _PyLong_FromGid(getegid());
9616
37
}
9617
#endif /* HAVE_GETEGID */
9618
9619
9620
#ifdef HAVE_GETEUID
9621
/*[clinic input]
9622
os.geteuid
9623
9624
Return the current process's effective user id.
9625
[clinic start generated code]*/
9626
9627
static PyObject *
9628
os_geteuid_impl(PyObject *module)
9629
/*[clinic end generated code: output=ea1b60f0d6abb66e input=4644c662d3bd9f19]*/
9630
37
{
9631
37
    return _PyLong_FromUid(geteuid());
9632
37
}
9633
#endif /* HAVE_GETEUID */
9634
9635
9636
#ifdef HAVE_GETGID
9637
/*[clinic input]
9638
os.getgid
9639
9640
Return the current process's group id.
9641
[clinic start generated code]*/
9642
9643
static PyObject *
9644
os_getgid_impl(PyObject *module)
9645
/*[clinic end generated code: output=4f28ebc9d3e5dfcf input=58796344cd87c0f6]*/
9646
37
{
9647
37
    return _PyLong_FromGid(getgid());
9648
37
}
9649
#endif /* HAVE_GETGID */
9650
9651
9652
#if defined(HAVE_GETPID)
9653
/*[clinic input]
9654
os.getpid
9655
9656
Return the current process id.
9657
[clinic start generated code]*/
9658
9659
static PyObject *
9660
os_getpid_impl(PyObject *module)
9661
/*[clinic end generated code: output=9ea6fdac01ed2b3c input=5a9a00f0ab68aa00]*/
9662
4.51k
{
9663
4.51k
#if !defined(MS_WINDOWS) || defined(MS_WINDOWS_DESKTOP) || defined(MS_WINDOWS_SYSTEM)
9664
4.51k
    return PyLong_FromPid(getpid());
9665
#else
9666
    return PyLong_FromUnsignedLong(GetCurrentProcessId());
9667
#endif
9668
4.51k
}
9669
#endif /* defined(HAVE_GETPID) */
9670
9671
#ifdef NGROUPS_MAX
9672
0
#define MAX_GROUPS NGROUPS_MAX
9673
#else
9674
    /* defined to be 16 on Solaris7, so this should be a small number */
9675
#define MAX_GROUPS 64
9676
#endif
9677
9678
#ifdef HAVE_GETGROUPLIST
9679
9680
#ifdef __APPLE__
9681
/*[clinic input]
9682
os.getgrouplist
9683
9684
    user: str
9685
        username to lookup
9686
    group as basegid: int
9687
        base group id of the user
9688
    /
9689
9690
Returns a list of groups to which a user belongs.
9691
[clinic start generated code]*/
9692
9693
static PyObject *
9694
os_getgrouplist_impl(PyObject *module, const char *user, int basegid)
9695
/*[clinic end generated code: output=6e734697b8c26de0 input=f8d870374b09a490]*/
9696
#else
9697
/*[clinic input]
9698
os.getgrouplist
9699
9700
    user: str
9701
        username to lookup
9702
    group as basegid: gid_t
9703
        base group id of the user
9704
    /
9705
9706
Returns a list of groups to which a user belongs.
9707
[clinic start generated code]*/
9708
9709
static PyObject *
9710
os_getgrouplist_impl(PyObject *module, const char *user, gid_t basegid)
9711
/*[clinic end generated code: output=0ebd7fb70115575b input=cc61d5c20b08958d]*/
9712
#endif
9713
0
{
9714
0
    int i, ngroups;
9715
0
    PyObject *list;
9716
#ifdef __APPLE__
9717
    int *groups;
9718
#else
9719
0
    gid_t *groups;
9720
0
#endif
9721
9722
    /*
9723
     * NGROUPS_MAX is defined by POSIX.1 as the maximum
9724
     * number of supplemental groups a users can belong to.
9725
     * We have to increment it by one because
9726
     * getgrouplist() returns both the supplemental groups
9727
     * and the primary group, i.e. all of the groups the
9728
     * user belongs to.
9729
     */
9730
0
    ngroups = 1 + MAX_GROUPS;
9731
9732
0
    while (1) {
9733
#ifdef __APPLE__
9734
        groups = PyMem_New(int, ngroups);
9735
#else
9736
0
        groups = PyMem_New(gid_t, ngroups);
9737
0
#endif
9738
0
        if (groups == NULL) {
9739
0
            return PyErr_NoMemory();
9740
0
        }
9741
9742
0
        int old_ngroups = ngroups;
9743
0
        if (getgrouplist(user, basegid, groups, &ngroups) != -1) {
9744
            /* Success */
9745
0
            break;
9746
0
        }
9747
9748
        /* getgrouplist() fails if the group list is too small */
9749
0
        PyMem_Free(groups);
9750
9751
0
        if (ngroups > old_ngroups) {
9752
            /* If the group list is too small, the glibc implementation of
9753
               getgrouplist() sets ngroups to the total number of groups and
9754
               returns -1. */
9755
0
        }
9756
0
        else {
9757
            /* Double the group list size */
9758
0
            if (ngroups > INT_MAX / 2) {
9759
0
                return PyErr_NoMemory();
9760
0
            }
9761
0
            ngroups *= 2;
9762
0
        }
9763
9764
        /* Retry getgrouplist() with a larger group list */
9765
0
    }
9766
9767
#ifdef _Py_MEMORY_SANITIZER
9768
    /* Clang memory sanitizer libc intercepts don't know getgrouplist. */
9769
    __msan_unpoison(&ngroups, sizeof(ngroups));
9770
    __msan_unpoison(groups, ngroups*sizeof(*groups));
9771
#endif
9772
9773
0
    list = PyList_New(ngroups);
9774
0
    if (list == NULL) {
9775
0
        PyMem_Free(groups);
9776
0
        return NULL;
9777
0
    }
9778
9779
0
    for (i = 0; i < ngroups; i++) {
9780
#ifdef __APPLE__
9781
        PyObject *o = PyLong_FromUnsignedLong((unsigned long)groups[i]);
9782
#else
9783
0
        PyObject *o = _PyLong_FromGid(groups[i]);
9784
0
#endif
9785
0
        if (o == NULL) {
9786
0
            Py_DECREF(list);
9787
0
            PyMem_Free(groups);
9788
0
            return NULL;
9789
0
        }
9790
0
        PyList_SET_ITEM(list, i, o);
9791
0
    }
9792
9793
0
    PyMem_Free(groups);
9794
9795
0
    return list;
9796
0
}
9797
#endif /* HAVE_GETGROUPLIST */
9798
9799
9800
#ifdef HAVE_GETGROUPS
9801
/*[clinic input]
9802
os.getgroups
9803
9804
Return list of supplemental group IDs for the process.
9805
[clinic start generated code]*/
9806
9807
static PyObject *
9808
os_getgroups_impl(PyObject *module)
9809
/*[clinic end generated code: output=42b0c17758561b56 input=d3f109412e6a155c]*/
9810
0
{
9811
    // Call getgroups with length 0 to get the actual number of groups
9812
0
    int n = getgroups(0, NULL);
9813
0
    if (n < 0) {
9814
0
        return posix_error();
9815
0
    }
9816
9817
0
    if (n == 0) {
9818
0
        return PyList_New(0);
9819
0
    }
9820
9821
0
    gid_t *grouplist = PyMem_New(gid_t, n);
9822
0
    if (grouplist == NULL) {
9823
0
        return PyErr_NoMemory();
9824
0
    }
9825
9826
0
    n = getgroups(n, grouplist);
9827
0
    if (n == -1) {
9828
0
        posix_error();
9829
0
        PyMem_Free(grouplist);
9830
0
        return NULL;
9831
0
    }
9832
9833
0
    PyObject *result = PyList_New(n);
9834
0
    if (result == NULL) {
9835
0
        goto error;
9836
0
    }
9837
9838
0
    for (int i = 0; i < n; ++i) {
9839
0
        PyObject *group = _PyLong_FromGid(grouplist[i]);
9840
0
        if (group == NULL) {
9841
0
            goto error;
9842
0
        }
9843
0
        PyList_SET_ITEM(result, i, group);
9844
0
    }
9845
0
    PyMem_Free(grouplist);
9846
9847
0
    return result;
9848
9849
0
error:
9850
0
    PyMem_Free(grouplist);
9851
0
    Py_XDECREF(result);
9852
0
    return NULL;
9853
0
}
9854
#endif /* HAVE_GETGROUPS */
9855
9856
#ifdef HAVE_INITGROUPS
9857
#ifdef __APPLE__
9858
/*[clinic input]
9859
os.initgroups
9860
9861
    username as oname: unicode_fs_encoded
9862
    gid: int
9863
    /
9864
9865
Initialize the group access list.
9866
9867
Call the system initgroups() to initialize the group access list with
9868
all of the groups of which the specified username is a member, plus the
9869
specified group id.
9870
[clinic start generated code]*/
9871
9872
static PyObject *
9873
os_initgroups_impl(PyObject *module, PyObject *oname, int gid)
9874
/*[clinic end generated code: output=7f074d30a425fd3a input=35f2d4fb7fcc0bdf]*/
9875
#else
9876
/*[clinic input]
9877
os.initgroups
9878
9879
    username as oname: unicode_fs_encoded
9880
    gid: gid_t
9881
    /
9882
9883
Initialize the group access list.
9884
9885
Call the system initgroups() to initialize the group access list with
9886
all of the groups of which the specified username is a member, plus the
9887
specified group id.
9888
[clinic start generated code]*/
9889
9890
static PyObject *
9891
os_initgroups_impl(PyObject *module, PyObject *oname, gid_t gid)
9892
/*[clinic end generated code: output=59341244521a9e3f input=7e4514dff4526a95]*/
9893
#endif
9894
0
{
9895
#ifdef __ANDROID__
9896
    // On Android, calling this function as a non-root user leads to a process crash
9897
    // rather than returning a permission error.
9898
    if (getuid() != 0) {
9899
        errno = EPERM;
9900
        return posix_error();
9901
    }
9902
#endif
9903
0
    const char *username = PyBytes_AS_STRING(oname);
9904
9905
0
    if (initgroups(username, gid) == -1)
9906
0
        return PyErr_SetFromErrno(PyExc_OSError);
9907
9908
0
    Py_RETURN_NONE;
9909
0
}
9910
#endif /* HAVE_INITGROUPS */
9911
9912
9913
#ifdef HAVE_GETPGID
9914
/*[clinic input]
9915
os.getpgid
9916
9917
    pid: pid_t
9918
9919
Call the system call getpgid(), and return the result.
9920
[clinic start generated code]*/
9921
9922
static PyObject *
9923
os_getpgid_impl(PyObject *module, pid_t pid)
9924
/*[clinic end generated code: output=1db95a97be205d18 input=39d710ae3baaf1c7]*/
9925
0
{
9926
0
    pid_t pgid = getpgid(pid);
9927
0
    if (pgid < 0)
9928
0
        return posix_error();
9929
0
    return PyLong_FromPid(pgid);
9930
0
}
9931
#endif /* HAVE_GETPGID */
9932
9933
9934
#ifdef HAVE_GETPGRP
9935
/*[clinic input]
9936
os.getpgrp
9937
9938
Return the current process group id.
9939
[clinic start generated code]*/
9940
9941
static PyObject *
9942
os_getpgrp_impl(PyObject *module)
9943
/*[clinic end generated code: output=c4fc381e51103cf3 input=6846fb2bb9a3705e]*/
9944
0
{
9945
#ifdef GETPGRP_HAVE_ARG
9946
    return PyLong_FromPid(getpgrp(0));
9947
#else /* GETPGRP_HAVE_ARG */
9948
0
    return PyLong_FromPid(getpgrp());
9949
0
#endif /* GETPGRP_HAVE_ARG */
9950
0
}
9951
#endif /* HAVE_GETPGRP */
9952
9953
9954
#ifdef HAVE_SETPGRP
9955
/*[clinic input]
9956
os.setpgrp
9957
9958
Make the current process the leader of its process group.
9959
[clinic start generated code]*/
9960
9961
static PyObject *
9962
os_setpgrp_impl(PyObject *module)
9963
/*[clinic end generated code: output=2554735b0a60f0a0 input=1f0619fcb5731e7e]*/
9964
0
{
9965
#ifdef SETPGRP_HAVE_ARG
9966
    if (setpgrp(0, 0) < 0)
9967
#else /* SETPGRP_HAVE_ARG */
9968
0
    if (setpgrp() < 0)
9969
0
#endif /* SETPGRP_HAVE_ARG */
9970
0
        return posix_error();
9971
0
    Py_RETURN_NONE;
9972
0
}
9973
#endif /* HAVE_SETPGRP */
9974
9975
#ifdef HAVE_GETPPID
9976
9977
#ifdef MS_WINDOWS
9978
#include <winternl.h>
9979
#include <ProcessSnapshot.h>
9980
9981
#ifdef MS_WINDOWS_DESKTOP
9982
// The structure definition in winternl.h may be incomplete.
9983
// This structure is the full version from the MSDN documentation.
9984
typedef struct _PROCESS_BASIC_INFORMATION_FULL {
9985
    NTSTATUS ExitStatus;
9986
    PVOID PebBaseAddress;
9987
    ULONG_PTR AffinityMask;
9988
    LONG BasePriority;
9989
    ULONG_PTR UniqueProcessId;
9990
    ULONG_PTR InheritedFromUniqueProcessId;
9991
} PROCESS_BASIC_INFORMATION_FULL;
9992
9993
typedef NTSTATUS (NTAPI *PNT_QUERY_INFORMATION_PROCESS) (
9994
    IN    HANDLE           ProcessHandle,
9995
    IN    PROCESSINFOCLASS ProcessInformationClass,
9996
    OUT   PVOID            ProcessInformation,
9997
    IN    ULONG            ProcessInformationLength,
9998
    OUT   PULONG           ReturnLength OPTIONAL);
9999
10000
// This function returns the process ID of the parent process.
10001
// Returns 0 on failure.
10002
static ULONG
10003
win32_getppid_fast(void)
10004
{
10005
    NTSTATUS status;
10006
    HMODULE ntdll;
10007
    PNT_QUERY_INFORMATION_PROCESS pNtQueryInformationProcess;
10008
    PROCESS_BASIC_INFORMATION_FULL basic_information;
10009
    static ULONG cached_ppid = 0;
10010
10011
    if (cached_ppid) {
10012
        // No need to query the kernel again.
10013
        return cached_ppid;
10014
    }
10015
10016
    ntdll = GetModuleHandleW(L"ntdll.dll");
10017
    if (!ntdll) {
10018
        return 0;
10019
    }
10020
10021
    pNtQueryInformationProcess = (PNT_QUERY_INFORMATION_PROCESS) GetProcAddress(ntdll, "NtQueryInformationProcess");
10022
    if (!pNtQueryInformationProcess) {
10023
        return 0;
10024
    }
10025
10026
    status = pNtQueryInformationProcess(GetCurrentProcess(),
10027
                                        ProcessBasicInformation,
10028
                                        &basic_information,
10029
                                        sizeof(basic_information),
10030
                                        NULL);
10031
10032
    if (!NT_SUCCESS(status)) {
10033
        return 0;
10034
    }
10035
10036
    // Perform sanity check on the parent process ID we received from NtQueryInformationProcess.
10037
    // The check covers values which exceed the 32-bit range (if running on x64) as well as
10038
    // zero and (ULONG) -1.
10039
10040
    if (basic_information.InheritedFromUniqueProcessId == 0 ||
10041
        basic_information.InheritedFromUniqueProcessId >= ULONG_MAX)
10042
    {
10043
        return 0;
10044
    }
10045
10046
    // Now that we have reached this point, the BasicInformation.InheritedFromUniqueProcessId
10047
    // structure member contains a ULONG_PTR which represents the process ID of our parent
10048
    // process. This process ID will be correctly returned even if the parent process has
10049
    // exited or been terminated.
10050
10051
    cached_ppid = (ULONG) basic_information.InheritedFromUniqueProcessId;
10052
    return cached_ppid;
10053
}
10054
#endif // MS_WINDOWS_DESKTOP
10055
10056
static PyObject*
10057
win32_getppid(void)
10058
{
10059
    DWORD error;
10060
    PyObject* result = NULL;
10061
    HANDLE process = GetCurrentProcess();
10062
    HPSS snapshot = NULL;
10063
10064
#ifdef MS_WINDOWS_DESKTOP
10065
    ULONG pid = win32_getppid_fast();
10066
    if (pid != 0) {
10067
        return PyLong_FromUnsignedLong(pid);
10068
    }
10069
#endif
10070
10071
    // If failure occurs in win32_getppid_fast(), fall back to using the PSS API.
10072
10073
    error = PssCaptureSnapshot(process, PSS_CAPTURE_NONE, 0, &snapshot);
10074
    if (error != ERROR_SUCCESS) {
10075
        return PyErr_SetFromWindowsErr(error);
10076
    }
10077
10078
    PSS_PROCESS_INFORMATION info;
10079
    error = PssQuerySnapshot(snapshot, PSS_QUERY_PROCESS_INFORMATION, &info,
10080
                             sizeof(info));
10081
    if (error == ERROR_SUCCESS) {
10082
        result = PyLong_FromUnsignedLong(info.ParentProcessId);
10083
    }
10084
    else {
10085
        result = PyErr_SetFromWindowsErr(error);
10086
    }
10087
10088
    PssFreeSnapshot(process, snapshot);
10089
    return result;
10090
}
10091
#endif /*MS_WINDOWS*/
10092
10093
10094
/*[clinic input]
10095
os.getppid
10096
10097
Return the parent's process id.
10098
10099
If the parent process has already exited, Windows machines will still
10100
return its id; other systems will return the id of the 'init' process
10101
(1).
10102
[clinic start generated code]*/
10103
10104
static PyObject *
10105
os_getppid_impl(PyObject *module)
10106
/*[clinic end generated code: output=43b2a946a8c603b4 input=158cc6dd661d54d9]*/
10107
0
{
10108
#ifdef MS_WINDOWS
10109
    return win32_getppid();
10110
#else
10111
0
    return PyLong_FromPid(getppid());
10112
0
#endif
10113
0
}
10114
#endif /* HAVE_GETPPID */
10115
10116
10117
#ifdef HAVE_GETLOGIN
10118
/*[clinic input]
10119
os.getlogin
10120
10121
Return the actual login name.
10122
[clinic start generated code]*/
10123
10124
static PyObject *
10125
os_getlogin_impl(PyObject *module)
10126
/*[clinic end generated code: output=a32e66a7e5715dac input=2a21ab1e917163df]*/
10127
0
{
10128
0
    PyObject *result = NULL;
10129
#ifdef MS_WINDOWS
10130
    wchar_t user_name[UNLEN + 1];
10131
    DWORD num_chars = Py_ARRAY_LENGTH(user_name);
10132
10133
    if (GetUserNameW(user_name, &num_chars)) {
10134
        /* num_chars is the number of unicode chars plus null terminator */
10135
        result = PyUnicode_FromWideChar(user_name, num_chars - 1);
10136
    }
10137
    else
10138
        result = PyErr_SetFromWindowsErr(GetLastError());
10139
#elif defined (HAVE_GETLOGIN_R)
10140
# if defined (HAVE_MAXLOGNAME)
10141
    char name[MAXLOGNAME + 1];
10142
# elif defined (HAVE_UT_NAMESIZE)
10143
    char name[UT_NAMESIZE + 1];
10144
# else
10145
    char name[256];
10146
# endif
10147
0
    int err = getlogin_r(name, sizeof(name));
10148
0
    if (err) {
10149
0
        int old_errno = errno;
10150
0
        errno = err;
10151
0
        posix_error();
10152
0
        errno = old_errno;
10153
0
    }
10154
0
    else {
10155
0
        _Py_MSAN_UNPOISON(name, sizeof(name));
10156
0
        result = PyUnicode_DecodeFSDefault(name);
10157
0
    }
10158
#else
10159
    char *name;
10160
    int old_errno = errno;
10161
10162
    errno = 0;
10163
    name = getlogin();
10164
    if (name == NULL) {
10165
        if (errno)
10166
            posix_error();
10167
        else
10168
            PyErr_SetString(PyExc_OSError, "unable to determine login name");
10169
    }
10170
    else
10171
        result = PyUnicode_DecodeFSDefault(name);
10172
    errno = old_errno;
10173
#endif
10174
0
    return result;
10175
0
}
10176
#endif /* HAVE_GETLOGIN */
10177
10178
10179
#ifdef HAVE_GETUID
10180
/*[clinic input]
10181
os.getuid
10182
10183
Return the current process's user id.
10184
[clinic start generated code]*/
10185
10186
static PyObject *
10187
os_getuid_impl(PyObject *module)
10188
/*[clinic end generated code: output=415c0b401ebed11a input=b53c8b35f110a516]*/
10189
37
{
10190
37
    return _PyLong_FromUid(getuid());
10191
37
}
10192
#endif /* HAVE_GETUID */
10193
10194
10195
#ifdef MS_WINDOWS
10196
#define HAVE_KILL
10197
#endif /* MS_WINDOWS */
10198
10199
#ifdef HAVE_KILL
10200
/*[clinic input]
10201
os.kill
10202
10203
    pid: pid_t
10204
    signal: Py_ssize_t
10205
    /
10206
10207
Kill a process with a signal.
10208
[clinic start generated code]*/
10209
10210
static PyObject *
10211
os_kill_impl(PyObject *module, pid_t pid, Py_ssize_t signal)
10212
/*[clinic end generated code: output=8e346a6701c88568 input=61a36b86ca275ab9]*/
10213
0
{
10214
0
    if (PySys_Audit("os.kill", "in", pid, signal) < 0) {
10215
0
        return NULL;
10216
0
    }
10217
0
#ifndef MS_WINDOWS
10218
0
    if (kill(pid, (int)signal) == -1) {
10219
0
        return posix_error();
10220
0
    }
10221
10222
    // Check immediately if the signal was sent to the current process.
10223
    // Don't micro-optimize pid == getpid(), since PyErr_SetString() check
10224
    // is cheap.
10225
0
    if (PyErr_CheckSignals()) {
10226
0
        return NULL;
10227
0
    }
10228
10229
0
    Py_RETURN_NONE;
10230
#else /* !MS_WINDOWS */
10231
    DWORD sig = (DWORD)signal;
10232
10233
#ifdef HAVE_WINDOWS_CONSOLE_IO
10234
    /* Console processes which share a common console can be sent CTRL+C or
10235
       CTRL+BREAK events, provided they handle said events. */
10236
    if (sig == CTRL_C_EVENT || sig == CTRL_BREAK_EVENT) {
10237
        if (GenerateConsoleCtrlEvent(sig, (DWORD)pid) == 0) {
10238
            return PyErr_SetFromWindowsErr(0);
10239
        }
10240
        Py_RETURN_NONE;
10241
    }
10242
#endif /* HAVE_WINDOWS_CONSOLE_IO */
10243
10244
    /* If the signal is outside of what GenerateConsoleCtrlEvent can use,
10245
       attempt to open and terminate the process. */
10246
    HANDLE handle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, (DWORD)pid);
10247
    if (handle == NULL) {
10248
        return PyErr_SetFromWindowsErr(0);
10249
    }
10250
10251
    BOOL res = TerminateProcess(handle, sig);
10252
    CloseHandle(handle);
10253
    if (res == 0) {
10254
        return PyErr_SetFromWindowsErr(0);
10255
    }
10256
10257
    Py_RETURN_NONE;
10258
#endif /* !MS_WINDOWS */
10259
0
}
10260
#endif /* HAVE_KILL */
10261
10262
10263
#ifdef HAVE_KILLPG
10264
/*[clinic input]
10265
os.killpg
10266
10267
    pgid: pid_t
10268
    signal: int
10269
    /
10270
10271
Kill a process group with a signal.
10272
[clinic start generated code]*/
10273
10274
static PyObject *
10275
os_killpg_impl(PyObject *module, pid_t pgid, int signal)
10276
/*[clinic end generated code: output=6dbcd2f1fdf5fdba input=38b5449eb8faec19]*/
10277
0
{
10278
0
    if (PySys_Audit("os.killpg", "ii", pgid, signal) < 0) {
10279
0
        return NULL;
10280
0
    }
10281
    /* XXX some man pages make the `pgid` parameter an int, others
10282
       a pid_t. Since getpgrp() returns a pid_t, we assume killpg should
10283
       take the same type. Moreover, pid_t is always at least as wide as
10284
       int (else compilation of this module fails), which is safe. */
10285
0
    if (killpg(pgid, signal) == -1)
10286
0
        return posix_error();
10287
0
    Py_RETURN_NONE;
10288
0
}
10289
#endif /* HAVE_KILLPG */
10290
10291
10292
#ifdef HAVE_PLOCK
10293
#ifdef HAVE_SYS_LOCK_H
10294
#include <sys/lock.h>
10295
#endif
10296
10297
/*[clinic input]
10298
os.plock
10299
    op: int
10300
    /
10301
10302
Lock program segments into memory.");
10303
[clinic start generated code]*/
10304
10305
static PyObject *
10306
os_plock_impl(PyObject *module, int op)
10307
/*[clinic end generated code: output=81424167033b168e input=e6e5e348e1525f60]*/
10308
{
10309
    if (plock(op) == -1)
10310
        return posix_error();
10311
    Py_RETURN_NONE;
10312
}
10313
#endif /* HAVE_PLOCK */
10314
10315
10316
#ifdef HAVE_SETUID
10317
/*[clinic input]
10318
os.setuid
10319
10320
    uid: uid_t
10321
    /
10322
10323
Set the current process's user id.
10324
[clinic start generated code]*/
10325
10326
static PyObject *
10327
os_setuid_impl(PyObject *module, uid_t uid)
10328
/*[clinic end generated code: output=a0a41fd0d1ec555f input=c921a3285aa22256]*/
10329
0
{
10330
#ifdef __ANDROID__
10331
    // On Android, calling this function as a non-root user leads to a process crash
10332
    // rather than returning a permission error.
10333
    if (getuid() != 0) {
10334
        errno = EPERM;
10335
        return posix_error();
10336
    }
10337
#endif
10338
0
    if (setuid(uid) < 0)
10339
0
        return posix_error();
10340
0
    Py_RETURN_NONE;
10341
0
}
10342
#endif /* HAVE_SETUID */
10343
10344
10345
#ifdef HAVE_SETEUID
10346
/*[clinic input]
10347
os.seteuid
10348
10349
    euid: uid_t
10350
    /
10351
10352
Set the current process's effective user id.
10353
[clinic start generated code]*/
10354
10355
static PyObject *
10356
os_seteuid_impl(PyObject *module, uid_t euid)
10357
/*[clinic end generated code: output=102e3ad98361519a input=ba93d927e4781aa9]*/
10358
0
{
10359
#ifdef __ANDROID__
10360
    // On Android, calling this function as a non-root user leads to a process crash
10361
    // rather than returning a permission error.
10362
    if (getuid() != 0) {
10363
        errno = EPERM;
10364
        return posix_error();
10365
    }
10366
#endif
10367
0
    if (seteuid(euid) < 0)
10368
0
        return posix_error();
10369
0
    Py_RETURN_NONE;
10370
0
}
10371
#endif /* HAVE_SETEUID */
10372
10373
10374
#ifdef HAVE_SETEGID
10375
/*[clinic input]
10376
os.setegid
10377
10378
    egid: gid_t
10379
    /
10380
10381
Set the current process's effective group id.
10382
[clinic start generated code]*/
10383
10384
static PyObject *
10385
os_setegid_impl(PyObject *module, gid_t egid)
10386
/*[clinic end generated code: output=4e4b825a6a10258d input=4080526d0ccd6ce3]*/
10387
0
{
10388
#ifdef __ANDROID__
10389
    // On Android, calling this function as a non-root user leads to a process crash
10390
    // rather than returning a permission error.
10391
    if (getuid() != 0) {
10392
        errno = EPERM;
10393
        return posix_error();
10394
    }
10395
#endif
10396
0
    if (setegid(egid) < 0)
10397
0
        return posix_error();
10398
0
    Py_RETURN_NONE;
10399
0
}
10400
#endif /* HAVE_SETEGID */
10401
10402
10403
#ifdef HAVE_SETREUID
10404
/*[clinic input]
10405
os.setreuid
10406
10407
    ruid: uid_t
10408
    euid: uid_t
10409
    /
10410
10411
Set the current process's real and effective user ids.
10412
[clinic start generated code]*/
10413
10414
static PyObject *
10415
os_setreuid_impl(PyObject *module, uid_t ruid, uid_t euid)
10416
/*[clinic end generated code: output=62d991210006530a input=0ca8978de663880c]*/
10417
0
{
10418
#ifdef __ANDROID__
10419
    // On Android, calling this function as a non-root user leads to a process crash
10420
    // rather than returning a permission error.
10421
    if (getuid() != 0) {
10422
        errno = EPERM;
10423
        return posix_error();
10424
    }
10425
#endif
10426
0
    if (setreuid(ruid, euid) < 0) {
10427
0
        return posix_error();
10428
0
    } else {
10429
0
        Py_RETURN_NONE;
10430
0
    }
10431
0
}
10432
#endif /* HAVE_SETREUID */
10433
10434
10435
#ifdef HAVE_SETREGID
10436
/*[clinic input]
10437
os.setregid
10438
10439
    rgid: gid_t
10440
    egid: gid_t
10441
    /
10442
10443
Set the current process's real and effective group ids.
10444
[clinic start generated code]*/
10445
10446
static PyObject *
10447
os_setregid_impl(PyObject *module, gid_t rgid, gid_t egid)
10448
/*[clinic end generated code: output=aa803835cf5342f3 input=c59499f72846db78]*/
10449
0
{
10450
#ifdef __ANDROID__
10451
    // On Android, calling this function as a non-root user leads to a process crash
10452
    // rather than returning a permission error.
10453
    if (getuid() != 0) {
10454
        errno = EPERM;
10455
        return posix_error();
10456
    }
10457
#endif
10458
0
    if (setregid(rgid, egid) < 0)
10459
0
        return posix_error();
10460
0
    Py_RETURN_NONE;
10461
0
}
10462
#endif /* HAVE_SETREGID */
10463
10464
10465
#ifdef HAVE_SETGID
10466
/*[clinic input]
10467
os.setgid
10468
    gid: gid_t
10469
    /
10470
10471
Set the current process's group id.
10472
[clinic start generated code]*/
10473
10474
static PyObject *
10475
os_setgid_impl(PyObject *module, gid_t gid)
10476
/*[clinic end generated code: output=bdccd7403f6ad8c3 input=27d30c4059045dc6]*/
10477
0
{
10478
#ifdef __ANDROID__
10479
    // On Android, calling this function as a non-root user leads to a process crash
10480
    // rather than returning a permission error.
10481
    if (getuid() != 0) {
10482
        errno = EPERM;
10483
        return posix_error();
10484
    }
10485
#endif
10486
0
    if (setgid(gid) < 0)
10487
0
        return posix_error();
10488
0
    Py_RETURN_NONE;
10489
0
}
10490
#endif /* HAVE_SETGID */
10491
10492
10493
#ifdef HAVE_SETGROUPS
10494
/*[clinic input]
10495
os.setgroups
10496
10497
    groups: object
10498
    /
10499
10500
Set the groups of the current process to list.
10501
[clinic start generated code]*/
10502
10503
static PyObject *
10504
os_setgroups(PyObject *module, PyObject *groups)
10505
/*[clinic end generated code: output=3fcb32aad58c5ecd input=fa742ca3daf85a7e]*/
10506
0
{
10507
0
    if (!PySequence_Check(groups)) {
10508
0
        PyErr_SetString(PyExc_TypeError, "setgroups argument must be a sequence");
10509
0
        return NULL;
10510
0
    }
10511
0
    Py_ssize_t len = PySequence_Size(groups);
10512
0
    if (len < 0) {
10513
0
        return NULL;
10514
0
    }
10515
0
    if (len > MAX_GROUPS) {
10516
0
        PyErr_SetString(PyExc_ValueError, "too many groups");
10517
0
        return NULL;
10518
0
    }
10519
10520
0
    gid_t *grouplist = PyMem_New(gid_t, len);
10521
0
    if (grouplist == NULL) {
10522
0
        PyErr_NoMemory();
10523
0
        return NULL;
10524
0
    }
10525
0
    for (Py_ssize_t i = 0; i < len; i++) {
10526
0
        PyObject *elem;
10527
0
        elem = PySequence_GetItem(groups, i);
10528
0
        if (!elem) {
10529
0
            PyMem_Free(grouplist);
10530
0
            return NULL;
10531
0
        }
10532
0
        if (!PyIndex_Check(elem)) {
10533
0
            PyErr_SetString(PyExc_TypeError,
10534
0
                            "groups must be integers");
10535
0
            Py_DECREF(elem);
10536
0
            PyMem_Free(grouplist);
10537
0
            return NULL;
10538
0
        } else {
10539
0
            if (!_Py_Gid_Converter(elem, &grouplist[i])) {
10540
0
                Py_DECREF(elem);
10541
0
                PyMem_Free(grouplist);
10542
0
                return NULL;
10543
0
            }
10544
0
        }
10545
0
        Py_DECREF(elem);
10546
0
    }
10547
10548
0
    if (setgroups(len, grouplist) < 0) {
10549
0
        posix_error();
10550
0
        PyMem_Free(grouplist);
10551
0
        return NULL;
10552
0
    }
10553
0
    PyMem_Free(grouplist);
10554
0
    Py_RETURN_NONE;
10555
0
}
10556
#endif /* HAVE_SETGROUPS */
10557
10558
#if defined(HAVE_WAIT3) || defined(HAVE_WAIT4)
10559
static PyObject *
10560
wait_helper(PyObject *module, pid_t pid, int status, struct rusage *ru)
10561
0
{
10562
0
    PyObject *result;
10563
0
    PyObject *struct_rusage;
10564
10565
0
    if (pid == -1)
10566
0
        return posix_error();
10567
10568
    // If wait succeeded but no child was ready to report status, ru will not
10569
    // have been populated.
10570
0
    if (pid == 0) {
10571
0
        memset(ru, 0, sizeof(*ru));
10572
0
    }
10573
10574
0
    struct_rusage = PyImport_ImportModuleAttrString("resource", "struct_rusage");
10575
0
    if (struct_rusage == NULL)
10576
0
        return NULL;
10577
10578
    /* XXX(nnorwitz): Copied (w/mods) from resource.c, there should be only one. */
10579
0
    result = PyStructSequence_New((PyTypeObject*) struct_rusage);
10580
0
    Py_DECREF(struct_rusage);
10581
0
    if (!result)
10582
0
        return NULL;
10583
10584
0
    int pos = 0;
10585
10586
0
#ifndef doubletime
10587
0
#define doubletime(TV) ((double)(TV).tv_sec + (TV).tv_usec * 0.000001)
10588
0
#endif
10589
10590
0
#define SET_RESULT(CALL)                                     \
10591
0
    do {                                                     \
10592
0
        PyObject *item = (CALL);                             \
10593
0
        if (item == NULL) {                                  \
10594
0
            Py_DECREF(result);                               \
10595
0
            return NULL;                                     \
10596
0
        }                                                    \
10597
0
        PyStructSequence_SET_ITEM(result, pos++, item);      \
10598
0
    } while(0)
10599
10600
0
    SET_RESULT(PyFloat_FromDouble(doubletime(ru->ru_utime)));
10601
0
    SET_RESULT(PyFloat_FromDouble(doubletime(ru->ru_stime)));
10602
0
    SET_RESULT(PyLong_FromLong(ru->ru_maxrss));
10603
0
    SET_RESULT(PyLong_FromLong(ru->ru_ixrss));
10604
0
    SET_RESULT(PyLong_FromLong(ru->ru_idrss));
10605
0
    SET_RESULT(PyLong_FromLong(ru->ru_isrss));
10606
0
    SET_RESULT(PyLong_FromLong(ru->ru_minflt));
10607
0
    SET_RESULT(PyLong_FromLong(ru->ru_majflt));
10608
0
    SET_RESULT(PyLong_FromLong(ru->ru_nswap));
10609
0
    SET_RESULT(PyLong_FromLong(ru->ru_inblock));
10610
0
    SET_RESULT(PyLong_FromLong(ru->ru_oublock));
10611
0
    SET_RESULT(PyLong_FromLong(ru->ru_msgsnd));
10612
0
    SET_RESULT(PyLong_FromLong(ru->ru_msgrcv));
10613
0
    SET_RESULT(PyLong_FromLong(ru->ru_nsignals));
10614
0
    SET_RESULT(PyLong_FromLong(ru->ru_nvcsw));
10615
0
    SET_RESULT(PyLong_FromLong(ru->ru_nivcsw));
10616
0
#undef SET_RESULT
10617
10618
0
    return Py_BuildValue("NiN", PyLong_FromPid(pid), status, result);
10619
0
}
10620
#endif /* HAVE_WAIT3 || HAVE_WAIT4 */
10621
10622
10623
#ifdef HAVE_WAIT3
10624
/*[clinic input]
10625
os.wait3
10626
10627
    options: int
10628
Wait for completion of a child process.
10629
10630
Returns a tuple of information about the child process:
10631
  (pid, status, rusage)
10632
[clinic start generated code]*/
10633
10634
static PyObject *
10635
os_wait3_impl(PyObject *module, int options)
10636
/*[clinic end generated code: output=92c3224e6f28217a input=8ac4c56956b61710]*/
10637
0
{
10638
0
    pid_t pid;
10639
0
    struct rusage ru;
10640
0
    int async_err = 0;
10641
0
    WAIT_TYPE status;
10642
0
    WAIT_STATUS_INT(status) = 0;
10643
10644
0
    do {
10645
0
        Py_BEGIN_ALLOW_THREADS
10646
0
        pid = wait3(&status, options, &ru);
10647
0
        Py_END_ALLOW_THREADS
10648
0
    } while (pid < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
10649
0
    if (pid < 0)
10650
0
        return (!async_err) ? posix_error() : NULL;
10651
10652
0
    return wait_helper(module, pid, WAIT_STATUS_INT(status), &ru);
10653
0
}
10654
#endif /* HAVE_WAIT3 */
10655
10656
10657
#ifdef HAVE_WAIT4
10658
/*[clinic input]
10659
10660
os.wait4
10661
10662
    pid: pid_t
10663
    options: int
10664
10665
Wait for completion of a specific child process.
10666
10667
Returns a tuple of information about the child process:
10668
  (pid, status, rusage)
10669
[clinic start generated code]*/
10670
10671
static PyObject *
10672
os_wait4_impl(PyObject *module, pid_t pid, int options)
10673
/*[clinic end generated code: output=66195aa507b35f70 input=d11deed0750600ba]*/
10674
0
{
10675
0
    pid_t res;
10676
0
    struct rusage ru;
10677
0
    int async_err = 0;
10678
0
    WAIT_TYPE status;
10679
0
    WAIT_STATUS_INT(status) = 0;
10680
10681
0
    do {
10682
0
        Py_BEGIN_ALLOW_THREADS
10683
0
        res = wait4(pid, &status, options, &ru);
10684
0
        Py_END_ALLOW_THREADS
10685
0
    } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
10686
0
    if (res < 0)
10687
0
        return (!async_err) ? posix_error() : NULL;
10688
10689
0
    return wait_helper(module, res, WAIT_STATUS_INT(status), &ru);
10690
0
}
10691
#endif /* HAVE_WAIT4 */
10692
10693
10694
#if defined(HAVE_WAITID)
10695
/*[clinic input]
10696
os.waitid
10697
10698
    idtype: idtype_t
10699
        Must be one of be P_PID, P_PGID or P_ALL.
10700
    id: id_t
10701
        The id to wait on.
10702
    options: int
10703
        Constructed from the ORing of one or more of WEXITED, WSTOPPED
10704
        or WCONTINUED and additionally may be ORed with WNOHANG or WNOWAIT.
10705
    /
10706
10707
Returns the result of waiting for a process or processes.
10708
10709
Returns either waitid_result or None if WNOHANG is specified and there
10710
are no children in a waitable state.
10711
[clinic start generated code]*/
10712
10713
static PyObject *
10714
os_waitid_impl(PyObject *module, idtype_t idtype, id_t id, int options)
10715
/*[clinic end generated code: output=5d2e1c0bde61f4d8 input=14956bc8d102b5db]*/
10716
0
{
10717
0
    PyObject *result;
10718
0
    int res;
10719
0
    int async_err = 0;
10720
0
    siginfo_t si;
10721
0
    si.si_pid = 0;
10722
10723
0
    do {
10724
0
        Py_BEGIN_ALLOW_THREADS
10725
0
        res = waitid(idtype, id, &si, options);
10726
0
        Py_END_ALLOW_THREADS
10727
0
    } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
10728
0
    if (res < 0)
10729
0
        return (!async_err) ? posix_error() : NULL;
10730
10731
0
    if (si.si_pid == 0)
10732
0
        Py_RETURN_NONE;
10733
10734
0
    PyObject *WaitidResultType = get_posix_state(module)->WaitidResultType;
10735
0
    result = PyStructSequence_New((PyTypeObject *)WaitidResultType);
10736
0
    if (!result)
10737
0
        return NULL;
10738
10739
0
    int pos = 0;
10740
10741
0
#define SET_RESULT(CALL)                                     \
10742
0
    do {                                                     \
10743
0
        PyObject *item = (CALL);                             \
10744
0
        if (item == NULL) {                                  \
10745
0
            Py_DECREF(result);                               \
10746
0
            return NULL;                                     \
10747
0
        }                                                    \
10748
0
        PyStructSequence_SET_ITEM(result, pos++, item);      \
10749
0
    } while(0)
10750
10751
0
    SET_RESULT(PyLong_FromPid(si.si_pid));
10752
0
    SET_RESULT(_PyLong_FromUid(si.si_uid));
10753
0
    SET_RESULT(PyLong_FromLong((long)(si.si_signo)));
10754
0
    SET_RESULT(PyLong_FromLong((long)(si.si_status)));
10755
0
    SET_RESULT(PyLong_FromLong((long)(si.si_code)));
10756
10757
0
#undef SET_RESULT
10758
10759
0
    return result;
10760
0
}
10761
#endif /* defined(HAVE_WAITID) */
10762
10763
10764
#if defined(HAVE_WAITPID)
10765
/*[clinic input]
10766
os.waitpid
10767
    pid: pid_t
10768
    options: int
10769
    /
10770
10771
Wait for completion of a given child process.
10772
10773
Returns a tuple of information regarding the child process:
10774
    (pid, status)
10775
10776
The options argument is ignored on Windows.
10777
[clinic start generated code]*/
10778
10779
static PyObject *
10780
os_waitpid_impl(PyObject *module, pid_t pid, int options)
10781
/*[clinic end generated code: output=5c37c06887a20270 input=0bf1666b8758fda3]*/
10782
0
{
10783
0
    pid_t res;
10784
0
    int async_err = 0;
10785
0
    WAIT_TYPE status;
10786
0
    WAIT_STATUS_INT(status) = 0;
10787
10788
0
    do {
10789
0
        Py_BEGIN_ALLOW_THREADS
10790
0
        res = waitpid(pid, &status, options);
10791
0
        Py_END_ALLOW_THREADS
10792
0
    } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
10793
0
    if (res < 0)
10794
0
        return (!async_err) ? posix_error() : NULL;
10795
10796
0
    return Py_BuildValue("Ni", PyLong_FromPid(res), WAIT_STATUS_INT(status));
10797
0
}
10798
#elif defined(HAVE_CWAIT)
10799
/* MS C has a variant of waitpid() that's usable for most purposes. */
10800
/*[clinic input]
10801
os.waitpid
10802
    pid: intptr_t
10803
    options: int
10804
    /
10805
10806
Wait for completion of a given process.
10807
10808
Returns a tuple of information regarding the process:
10809
    (pid, status << 8)
10810
10811
The options argument is ignored on Windows.
10812
[clinic start generated code]*/
10813
10814
static PyObject *
10815
os_waitpid_impl(PyObject *module, intptr_t pid, int options)
10816
/*[clinic end generated code: output=be836b221271d538 input=40f2440c515410f8]*/
10817
{
10818
    int status;
10819
    intptr_t res;
10820
    int async_err = 0;
10821
10822
    do {
10823
        Py_BEGIN_ALLOW_THREADS
10824
        _Py_BEGIN_SUPPRESS_IPH
10825
        res = _cwait(&status, pid, options);
10826
        _Py_END_SUPPRESS_IPH
10827
        Py_END_ALLOW_THREADS
10828
    } while (res < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
10829
    if (res < 0)
10830
        return (!async_err) ? posix_error() : NULL;
10831
10832
    unsigned long long ustatus = (unsigned int)status;
10833
10834
    /* shift the status left a byte so this is more like the POSIX waitpid */
10835
    return Py_BuildValue(_Py_PARSE_INTPTR "K", res, ustatus << 8);
10836
}
10837
#endif
10838
10839
10840
#ifdef HAVE_WAIT
10841
/*[clinic input]
10842
os.wait
10843
10844
Wait for completion of a child process.
10845
10846
Returns a tuple of information about the child process:
10847
    (pid, status)
10848
[clinic start generated code]*/
10849
10850
static PyObject *
10851
os_wait_impl(PyObject *module)
10852
/*[clinic end generated code: output=6bc419ac32fb364b input=03b0182d4a4700ce]*/
10853
0
{
10854
0
    pid_t pid;
10855
0
    int async_err = 0;
10856
0
    WAIT_TYPE status;
10857
0
    WAIT_STATUS_INT(status) = 0;
10858
10859
0
    do {
10860
0
        Py_BEGIN_ALLOW_THREADS
10861
0
        pid = wait(&status);
10862
0
        Py_END_ALLOW_THREADS
10863
0
    } while (pid < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
10864
0
    if (pid < 0)
10865
0
        return (!async_err) ? posix_error() : NULL;
10866
10867
0
    return Py_BuildValue("Ni", PyLong_FromPid(pid), WAIT_STATUS_INT(status));
10868
0
}
10869
#endif /* HAVE_WAIT */
10870
10871
10872
// This system call always crashes on older Android versions.
10873
#if defined(_Py_HAVE_PIDFD_OPEN) \
10874
    || (defined(__linux__) && defined(__NR_pidfd_open) \
10875
        && !(defined(__ANDROID__) && __ANDROID_API__ < 31))
10876
/*[clinic input]
10877
os.pidfd_open
10878
  pid: pid_t
10879
  flags: unsigned_int = 0
10880
10881
Return a file descriptor referring to the process *pid*.
10882
10883
The descriptor can be used to perform process management without races
10884
and signals.
10885
[clinic start generated code]*/
10886
10887
static PyObject *
10888
os_pidfd_open_impl(PyObject *module, pid_t pid, unsigned int flags)
10889
/*[clinic end generated code: output=5c7252698947dc41 input=03058b32c389f874]*/
10890
4
{
10891
4
#ifdef _Py_HAVE_PIDFD_OPEN
10892
4
    int fd = pidfd_open(pid, flags);
10893
#else
10894
    int fd = syscall(__NR_pidfd_open, pid, flags);
10895
#endif
10896
4
    if (fd < 0) {
10897
0
        return posix_error();
10898
0
    }
10899
4
    return PyLong_FromLong(fd);
10900
4
}
10901
#endif
10902
10903
10904
#if defined(_Py_HAVE_PIDFD_GETFD) \
10905
    || (defined(__linux__) && defined(__NR_pidfd_getfd) \
10906
        && !(defined(__ANDROID__) && __ANDROID_API__ < 31))
10907
/*[clinic input]
10908
os.pidfd_getfd
10909
  pidfd: int
10910
    A process file descriptor.
10911
  targetfd: int
10912
    The file descriptor to duplicate from the target process.
10913
  *
10914
  flags: unsigned_int = 0
10915
    Reserved, must be 0.
10916
10917
Duplicate a file descriptor from the process referred to by *pidfd*.
10918
[clinic start generated code]*/
10919
10920
static PyObject *
10921
os_pidfd_getfd_impl(PyObject *module, int pidfd, int targetfd,
10922
                    unsigned int flags)
10923
/*[clinic end generated code: output=e1a1415a13c7137f input=ef6417fb10deb1cc]*/
10924
0
{
10925
0
#ifdef _Py_HAVE_PIDFD_GETFD
10926
0
    int fd = pidfd_getfd(pidfd, targetfd, flags);
10927
#else
10928
    int fd = syscall(__NR_pidfd_getfd, pidfd, targetfd, flags);
10929
#endif
10930
0
    if (fd < 0) {
10931
0
        return posix_error();
10932
0
    }
10933
0
    return PyLong_FromLong(fd);
10934
0
}
10935
#endif
10936
10937
10938
#ifdef HAVE_SETNS
10939
/*[clinic input]
10940
os.setns
10941
  fd: fildes
10942
    A file descriptor to a namespace.
10943
  nstype: int = 0
10944
    Type of namespace.
10945
10946
Move the calling thread into different namespaces.
10947
[clinic start generated code]*/
10948
10949
static PyObject *
10950
os_setns_impl(PyObject *module, int fd, int nstype)
10951
/*[clinic end generated code: output=5dbd055bfb66ecd0 input=42787871226bf3ee]*/
10952
0
{
10953
0
    int res;
10954
10955
0
    Py_BEGIN_ALLOW_THREADS
10956
0
    res = setns(fd, nstype);
10957
0
    Py_END_ALLOW_THREADS
10958
10959
0
    if (res != 0) {
10960
0
        return posix_error();
10961
0
    }
10962
10963
0
    Py_RETURN_NONE;
10964
0
}
10965
#endif
10966
10967
10968
#ifdef HAVE_UNSHARE
10969
/*[clinic input]
10970
os.unshare
10971
  flags: int
10972
    Namespaces to be unshared.
10973
10974
Disassociate parts of a process (or thread) execution context.
10975
[clinic start generated code]*/
10976
10977
static PyObject *
10978
os_unshare_impl(PyObject *module, int flags)
10979
/*[clinic end generated code: output=1b3177906dd237ee input=9e065db3232b8b1b]*/
10980
0
{
10981
0
    int res;
10982
10983
0
    Py_BEGIN_ALLOW_THREADS
10984
0
    res = unshare(flags);
10985
0
    Py_END_ALLOW_THREADS
10986
10987
0
    if (res != 0) {
10988
0
        return posix_error();
10989
0
    }
10990
10991
0
    Py_RETURN_NONE;
10992
0
}
10993
#endif
10994
10995
10996
10997
#if defined(HAVE_READLINK) || defined(MS_WINDOWS)
10998
10999
#if (defined(__linux__) || defined(__ANDROID__)) && defined(O_PATH)
11000
// readlinkat(fd, "", ...) reads the symlink that fd refers to.
11001
// supported since Linux 2.6.39 (same version that O_PATH was introduced).
11002
#define _Py_READLINKAT_SUPPORTS_EMPTY_PATH
11003
#endif
11004
11005
/*[clinic input]
11006
os.readlink
11007
11008
    path: path_t(allow_fd=True)
11009
    *
11010
    dir_fd: dir_fd(requires='readlinkat') = None
11011
11012
Return a string representing the path to which the symbolic link points.
11013
11014
If dir_fd is not None, it should be a file descriptor open to
11015
a directory, and path should be relative; path will then be relative to
11016
that directory.
11017
11018
dir_fd may not be implemented on your platform.  If it is unavailable,
11019
using it will raise a NotImplementedError.
11020
11021
On Linux, Android, macOS and iOS, path may be a file descriptor
11022
referring to a symlink. If it is, dir_fd must be None.
11023
[clinic start generated code]*/
11024
11025
static PyObject *
11026
os_readlink_impl(PyObject *module, path_t *path, int dir_fd)
11027
/*[clinic end generated code: output=d21b732a2e814030 input=d90bddfeee86f673]*/
11028
6
{
11029
6
#if defined(HAVE_READLINK)
11030
6
    char buffer[MAXPATHLEN+1];
11031
6
    ssize_t length;
11032
11033
6
    if (path_and_dir_fd_invalid("readlink", path, dir_fd)) {
11034
0
        return NULL;
11035
0
    }
11036
11037
6
    if (path->is_fd) {
11038
#if defined(_Py_HAVE_FREADLINK)
11039
        if (HAVE_FREADLINK_RUNTIME) {
11040
            Py_BEGIN_ALLOW_THREADS
11041
            length = freadlink(path->fd, buffer, MAXPATHLEN);
11042
            Py_END_ALLOW_THREADS
11043
        } else
11044
#elif defined(HAVE_READLINKAT) && defined(_Py_READLINKAT_SUPPORTS_EMPTY_PATH)
11045
        // linux/android:
11046
        // readlinkat(fd, "", ...) reads the link that fd refers to.
11047
0
        if (HAVE_READLINKAT_RUNTIME) {
11048
0
            Py_BEGIN_ALLOW_THREADS
11049
0
            length = readlinkat(path->fd, "", buffer, MAXPATHLEN);
11050
0
            Py_END_ALLOW_THREADS
11051
0
        } else
11052
0
#endif
11053
0
        {
11054
0
            PyErr_SetString(PyExc_NotImplementedError,
11055
0
                "readlink cannot read file descriptors on this platform");
11056
0
            return NULL;
11057
0
        }
11058
0
    } else
11059
6
#ifdef HAVE_READLINKAT
11060
6
    if (dir_fd != DEFAULT_DIR_FD) {
11061
0
        if (HAVE_READLINKAT_RUNTIME) {
11062
0
            Py_BEGIN_ALLOW_THREADS
11063
0
            length = readlinkat(dir_fd, path->narrow, buffer, MAXPATHLEN);
11064
0
            Py_END_ALLOW_THREADS
11065
0
        } else {
11066
0
            argument_unavailable_error(NULL, "dir_fd");
11067
0
            return NULL;
11068
0
        }
11069
0
    } else
11070
6
#endif
11071
6
    {
11072
6
        Py_BEGIN_ALLOW_THREADS
11073
6
        length = readlink(path->narrow, buffer, MAXPATHLEN);
11074
6
        Py_END_ALLOW_THREADS
11075
6
    }
11076
11077
6
    if (length < 0) {
11078
0
        return path_error(path);
11079
0
    }
11080
6
    buffer[length] = '\0';
11081
11082
6
    if (path->is_fd || PyUnicode_Check(path->object)) {
11083
6
        return PyUnicode_DecodeFSDefaultAndSize(buffer, length);
11084
6
    }
11085
0
    else {
11086
0
        return PyBytes_FromStringAndSize(buffer, length);
11087
0
    }
11088
#elif defined(MS_WINDOWS)
11089
    DWORD n_bytes_returned;
11090
    DWORD io_result = 0;
11091
    HANDLE reparse_point_handle;
11092
    char target_buffer[_Py_MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
11093
    _Py_REPARSE_DATA_BUFFER *rdb = (_Py_REPARSE_DATA_BUFFER *)target_buffer;
11094
    PyObject *result = NULL;
11095
11096
    if (path->is_fd) {
11097
        PyErr_SetString(PyExc_NotImplementedError,
11098
            "readlink cannot read file descriptors on this platform");
11099
        return NULL;
11100
    }
11101
11102
    /* First get a handle to the reparse point */
11103
    Py_BEGIN_ALLOW_THREADS
11104
    reparse_point_handle = CreateFileW(
11105
        path->wide,
11106
        0,
11107
        0,
11108
        0,
11109
        OPEN_EXISTING,
11110
        FILE_FLAG_OPEN_REPARSE_POINT|FILE_FLAG_BACKUP_SEMANTICS,
11111
        0);
11112
    if (reparse_point_handle != INVALID_HANDLE_VALUE) {
11113
        /* New call DeviceIoControl to read the reparse point */
11114
        io_result = DeviceIoControl(
11115
            reparse_point_handle,
11116
            FSCTL_GET_REPARSE_POINT,
11117
            0, 0, /* in buffer */
11118
            target_buffer, sizeof(target_buffer),
11119
            &n_bytes_returned,
11120
            0 /* we're not using OVERLAPPED_IO */
11121
            );
11122
        CloseHandle(reparse_point_handle);
11123
    }
11124
    Py_END_ALLOW_THREADS
11125
11126
    if (io_result == 0) {
11127
        return path_error(path);
11128
    }
11129
11130
    wchar_t *name = NULL;
11131
    Py_ssize_t nameLen = 0;
11132
    if (rdb->ReparseTag == IO_REPARSE_TAG_SYMLINK)
11133
    {
11134
        name = (wchar_t *)((char*)rdb->SymbolicLinkReparseBuffer.PathBuffer +
11135
                           rdb->SymbolicLinkReparseBuffer.SubstituteNameOffset);
11136
        nameLen = rdb->SymbolicLinkReparseBuffer.SubstituteNameLength / sizeof(wchar_t);
11137
    }
11138
    else if (rdb->ReparseTag == IO_REPARSE_TAG_MOUNT_POINT)
11139
    {
11140
        name = (wchar_t *)((char*)rdb->MountPointReparseBuffer.PathBuffer +
11141
                           rdb->MountPointReparseBuffer.SubstituteNameOffset);
11142
        nameLen = rdb->MountPointReparseBuffer.SubstituteNameLength / sizeof(wchar_t);
11143
    }
11144
    else
11145
    {
11146
        PyErr_SetString(PyExc_ValueError, "not a symbolic link");
11147
    }
11148
    if (name) {
11149
        if (nameLen > 4 && wcsncmp(name, L"\\??\\", 4) == 0) {
11150
            /* Our buffer is mutable, so this is okay */
11151
            name[1] = L'\\';
11152
        }
11153
        result = PyUnicode_FromWideChar(name, nameLen);
11154
        if (result && PyBytes_Check(path->object)) {
11155
            Py_SETREF(result, PyUnicode_EncodeFSDefault(result));
11156
        }
11157
    }
11158
    return result;
11159
#endif
11160
6
}
11161
#endif /* defined(HAVE_READLINK) || defined(MS_WINDOWS) */
11162
11163
#if defined(MS_WINDOWS)
11164
11165
/* Remove the last portion of the path - return 0 on success */
11166
static int
11167
_dirnameW(WCHAR *path)
11168
{
11169
    WCHAR *ptr;
11170
    size_t length = wcsnlen_s(path, MAX_PATH);
11171
    if (length == MAX_PATH) {
11172
        return -1;
11173
    }
11174
11175
    /* walk the path from the end until a backslash is encountered */
11176
    for(ptr = path + length; ptr != path; ptr--) {
11177
        if (*ptr == L'\\' || *ptr == L'/') {
11178
            break;
11179
        }
11180
    }
11181
    *ptr = 0;
11182
    return 0;
11183
}
11184
11185
#endif
11186
11187
#ifdef HAVE_SYMLINK
11188
11189
#if defined(MS_WINDOWS)
11190
11191
/* Is this path absolute? */
11192
static int
11193
_is_absW(const WCHAR *path)
11194
{
11195
    return path[0] == L'\\' || path[0] == L'/' ||
11196
        (path[0] && path[1] == L':');
11197
}
11198
11199
/* join root and rest with a backslash - return 0 on success */
11200
static int
11201
_joinW(WCHAR *dest_path, const WCHAR *root, const WCHAR *rest)
11202
{
11203
    if (_is_absW(rest)) {
11204
        return wcscpy_s(dest_path, MAX_PATH, rest);
11205
    }
11206
11207
    if (wcscpy_s(dest_path, MAX_PATH, root)) {
11208
        return -1;
11209
    }
11210
11211
    if (dest_path[0] && wcscat_s(dest_path, MAX_PATH, L"\\")) {
11212
        return -1;
11213
    }
11214
11215
    return wcscat_s(dest_path, MAX_PATH, rest);
11216
}
11217
11218
/* Return True if the path at src relative to dest is a directory */
11219
static int
11220
_check_dirW(LPCWSTR src, LPCWSTR dest)
11221
{
11222
    WIN32_FILE_ATTRIBUTE_DATA src_info;
11223
    WCHAR dest_parent[MAX_PATH];
11224
    WCHAR src_resolved[MAX_PATH] = L"";
11225
11226
    /* dest_parent = os.path.dirname(dest) */
11227
    if (wcscpy_s(dest_parent, MAX_PATH, dest) ||
11228
        _dirnameW(dest_parent)) {
11229
        return 0;
11230
    }
11231
    /* src_resolved = os.path.join(dest_parent, src) */
11232
    if (_joinW(src_resolved, dest_parent, src)) {
11233
        return 0;
11234
    }
11235
    return (
11236
        GetFileAttributesExW(src_resolved, GetFileExInfoStandard, &src_info)
11237
        && src_info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY
11238
    );
11239
}
11240
#endif
11241
11242
11243
/*[clinic input]
11244
os.symlink
11245
    src: path_t
11246
    dst: path_t
11247
    target_is_directory: bool = False
11248
    *
11249
    dir_fd: dir_fd(requires='symlinkat')=None
11250
11251
Create a symbolic link pointing to src named dst.
11252
11253
target_is_directory is required on Windows if the target is to be
11254
interpreted as a directory.  (On Windows, symlink requires Windows 6.0
11255
or greater, and raises a NotImplementedError otherwise.)
11256
target_is_directory is ignored on non-Windows platforms.
11257
11258
If dir_fd is not None, it should be a file descriptor open to
11259
a directory, and path should be relative; path will then be relative
11260
to that directory.
11261
dir_fd may not be implemented on your platform.  If it is unavailable,
11262
using it will raise a NotImplementedError.
11263
11264
[clinic start generated code]*/
11265
11266
static PyObject *
11267
os_symlink_impl(PyObject *module, path_t *src, path_t *dst,
11268
                int target_is_directory, int dir_fd)
11269
/*[clinic end generated code: output=08ca9f3f3cf960f6 input=71b75467b31c45f7]*/
11270
0
{
11271
#ifdef MS_WINDOWS
11272
    DWORD result;
11273
    DWORD flags = 0;
11274
11275
    /* Assumed true, set to false if detected to not be available. */
11276
    static int windows_has_symlink_unprivileged_flag = TRUE;
11277
#else
11278
0
    int result;
11279
0
#ifdef HAVE_SYMLINKAT
11280
0
    int symlinkat_unavailable = 0;
11281
0
#endif
11282
0
#endif
11283
11284
0
    if (PySys_Audit("os.symlink", "OOi", src->object, dst->object,
11285
0
                    dir_fd == DEFAULT_DIR_FD ? -1 : dir_fd) < 0) {
11286
0
        return NULL;
11287
0
    }
11288
11289
#ifdef MS_WINDOWS
11290
11291
    if (windows_has_symlink_unprivileged_flag) {
11292
        /* Allow non-admin symlinks if system allows it. */
11293
        flags |= SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE;
11294
    }
11295
11296
    Py_BEGIN_ALLOW_THREADS
11297
    _Py_BEGIN_SUPPRESS_IPH
11298
    /* if src is a directory, ensure flags==1 (target_is_directory bit) */
11299
    if (target_is_directory || _check_dirW(src->wide, dst->wide)) {
11300
        flags |= SYMBOLIC_LINK_FLAG_DIRECTORY;
11301
    }
11302
11303
    result = CreateSymbolicLinkW(dst->wide, src->wide, flags);
11304
    _Py_END_SUPPRESS_IPH
11305
    Py_END_ALLOW_THREADS
11306
11307
    if (windows_has_symlink_unprivileged_flag && !result &&
11308
        ERROR_INVALID_PARAMETER == GetLastError()) {
11309
11310
        Py_BEGIN_ALLOW_THREADS
11311
        _Py_BEGIN_SUPPRESS_IPH
11312
        /* This error might be caused by
11313
        SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE not being supported.
11314
        Try again, and update windows_has_symlink_unprivileged_flag if we
11315
        are successful this time.
11316
11317
        NOTE: There is a risk of a race condition here if there are other
11318
        conditions than the flag causing ERROR_INVALID_PARAMETER, and
11319
        another process (or thread) changes that condition in between our
11320
        calls to CreateSymbolicLink.
11321
        */
11322
        flags &= ~(SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE);
11323
        result = CreateSymbolicLinkW(dst->wide, src->wide, flags);
11324
        _Py_END_SUPPRESS_IPH
11325
        Py_END_ALLOW_THREADS
11326
11327
        if (result || ERROR_INVALID_PARAMETER != GetLastError()) {
11328
            windows_has_symlink_unprivileged_flag = FALSE;
11329
        }
11330
    }
11331
11332
    if (!result)
11333
        return path_error2(src, dst);
11334
11335
#else
11336
11337
0
    Py_BEGIN_ALLOW_THREADS
11338
0
#ifdef HAVE_SYMLINKAT
11339
0
    if (dir_fd != DEFAULT_DIR_FD) {
11340
0
        if (HAVE_SYMLINKAT_RUNTIME) {
11341
0
            result = symlinkat(src->narrow, dir_fd, dst->narrow);
11342
0
        } else {
11343
0
            symlinkat_unavailable = 1;
11344
0
        }
11345
0
    } else
11346
0
#endif
11347
0
        result = symlink(src->narrow, dst->narrow);
11348
0
    Py_END_ALLOW_THREADS
11349
11350
0
#ifdef HAVE_SYMLINKAT
11351
0
    if (symlinkat_unavailable) {
11352
0
          argument_unavailable_error(NULL, "dir_fd");
11353
0
          return NULL;
11354
0
    }
11355
0
#endif
11356
11357
0
    if (result)
11358
0
        return path_error2(src, dst);
11359
0
#endif
11360
11361
0
    Py_RETURN_NONE;
11362
0
}
11363
#endif /* HAVE_SYMLINK */
11364
11365
11366
static PyStructSequence_Field times_result_fields[] = {
11367
    {"user",    "user time"},
11368
    {"system",   "system time"},
11369
    {"children_user",    "user time of children"},
11370
    {"children_system",    "system time of children"},
11371
    {"elapsed",    "elapsed time since an arbitrary point in the past"},
11372
    {NULL}
11373
};
11374
11375
PyDoc_STRVAR(times_result__doc__,
11376
"times_result: Result from os.times().\n\n\
11377
This object may be accessed either as a tuple of\n\
11378
  (user, system, children_user, children_system, elapsed),\n\
11379
or via the attributes user, system, children_user, children_system,\n\
11380
and elapsed.\n\
11381
\n\
11382
See os.times for more information.");
11383
11384
static PyStructSequence_Desc times_result_desc = {
11385
    "os.times_result", /* name */
11386
    times_result__doc__, /* doc */
11387
    times_result_fields,
11388
    5
11389
};
11390
11391
static PyObject *
11392
build_times_result(PyObject *module, double user, double system,
11393
    double children_user, double children_system,
11394
    double elapsed)
11395
0
{
11396
0
    PyObject *TimesResultType = get_posix_state(module)->TimesResultType;
11397
0
    PyObject *value = PyStructSequence_New((PyTypeObject *)TimesResultType);
11398
0
    if (value == NULL)
11399
0
        return NULL;
11400
11401
0
#define SET(i, field) \
11402
0
    { \
11403
0
    PyObject *o = PyFloat_FromDouble(field); \
11404
0
    if (!o) { \
11405
0
        Py_DECREF(value); \
11406
0
        return NULL; \
11407
0
    } \
11408
0
    PyStructSequence_SET_ITEM(value, i, o); \
11409
0
    } \
11410
0
11411
0
    SET(0, user);
11412
0
    SET(1, system);
11413
0
    SET(2, children_user);
11414
0
    SET(3, children_system);
11415
0
    SET(4, elapsed);
11416
11417
0
#undef SET
11418
11419
0
    return value;
11420
0
}
11421
11422
11423
/*[clinic input]
11424
os.times
11425
11426
Return a collection containing process timing information.
11427
11428
The object returned behaves like a named tuple with these fields:
11429
  (utime, stime, cutime, cstime, elapsed_time)
11430
All fields are floating-point numbers.
11431
[clinic start generated code]*/
11432
11433
static PyObject *
11434
os_times_impl(PyObject *module)
11435
/*[clinic end generated code: output=35f640503557d32a input=8dbfe33a2dcc3df3]*/
11436
0
{
11437
#ifdef MS_WINDOWS
11438
    FILETIME create, exit, kernel, user;
11439
    HANDLE hProc;
11440
    hProc = GetCurrentProcess();
11441
    GetProcessTimes(hProc, &create, &exit, &kernel, &user);
11442
    /* The fields of a FILETIME structure are the hi and lo part
11443
       of a 64-bit value expressed in 100 nanosecond units.
11444
       1e7 is one second in such units; 1e-7 the inverse.
11445
       429.4967296 is 2**32 / 1e7 or 2**32 * 1e-7.
11446
    */
11447
    return build_times_result(module,
11448
        (double)(user.dwHighDateTime*429.4967296 +
11449
                 user.dwLowDateTime*1e-7),
11450
        (double)(kernel.dwHighDateTime*429.4967296 +
11451
                 kernel.dwLowDateTime*1e-7),
11452
        (double)0,
11453
        (double)0,
11454
        (double)0);
11455
#else /* MS_WINDOWS */
11456
0
    _posixstate *state = get_posix_state(module);
11457
0
    long ticks_per_second = state->ticks_per_second;
11458
11459
0
    struct tms process;
11460
0
    clock_t elapsed;
11461
0
    errno = 0;
11462
0
    elapsed = times(&process);
11463
0
    if (elapsed == (clock_t) -1) {
11464
0
        return posix_error();
11465
0
    }
11466
11467
0
    return build_times_result(module,
11468
0
        (double)process.tms_utime / ticks_per_second,
11469
0
        (double)process.tms_stime / ticks_per_second,
11470
0
        (double)process.tms_cutime / ticks_per_second,
11471
0
        (double)process.tms_cstime / ticks_per_second,
11472
0
        (double)elapsed / ticks_per_second);
11473
0
#endif /* MS_WINDOWS */
11474
0
}
11475
11476
11477
#if defined(HAVE_TIMERFD_CREATE)
11478
#define ONE_SECOND_IN_NS (1000 * 1000 * 1000)
11479
#define EXTRACT_NSEC(value)  (long)( ( (double)(value) - (time_t)(value) ) * 1e9)
11480
0
#define CONVERT_SEC_AND_NSEC_TO_DOUBLE(sec, nsec) ( (double)(sec) + (double)(nsec) * 1e-9 )
11481
11482
static PyObject *
11483
build_itimerspec(const struct itimerspec* curr_value)
11484
0
{
11485
0
    double _value = CONVERT_SEC_AND_NSEC_TO_DOUBLE(curr_value->it_value.tv_sec,
11486
0
                                                          curr_value->it_value.tv_nsec);
11487
0
    PyObject *value = PyFloat_FromDouble(_value);
11488
0
    if (value == NULL) {
11489
0
        return NULL;
11490
0
    }
11491
0
    double _interval = CONVERT_SEC_AND_NSEC_TO_DOUBLE(curr_value->it_interval.tv_sec,
11492
0
                                                   curr_value->it_interval.tv_nsec);
11493
0
    PyObject *interval = PyFloat_FromDouble(_interval);
11494
0
    if (interval == NULL) {
11495
0
        Py_DECREF(value);
11496
0
        return NULL;
11497
0
    }
11498
0
    return _PyTuple_FromPairSteal(value, interval);
11499
0
}
11500
11501
static PyObject *
11502
build_itimerspec_ns(const struct itimerspec* curr_value)
11503
0
{
11504
0
    PyTime_t value, interval;
11505
0
    if (_PyTime_FromTimespec(&value, &curr_value->it_value) < 0) {
11506
0
        return NULL;
11507
0
    }
11508
0
    if (_PyTime_FromTimespec(&interval, &curr_value->it_interval) < 0) {
11509
0
        return NULL;
11510
0
    }
11511
0
    return Py_BuildValue("LL", value, interval);
11512
0
}
11513
11514
/*[clinic input]
11515
os.timerfd_create
11516
11517
    clockid: int
11518
        A valid clock ID constant as timer file descriptor.
11519
11520
        time.CLOCK_REALTIME
11521
        time.CLOCK_MONOTONIC
11522
        time.CLOCK_BOOTTIME
11523
    /
11524
    *
11525
    flags: int = 0
11526
        0 or a bit mask of os.TFD_NONBLOCK or os.TFD_CLOEXEC.
11527
11528
        os.TFD_NONBLOCK
11529
            If *TFD_NONBLOCK* is set as a flag, read doesn't blocks.
11530
            If *TFD_NONBLOCK* is not set as a flag, read block until the timer fires.
11531
11532
        os.TFD_CLOEXEC
11533
            If *TFD_CLOEXEC* is set as a flag, enable the close-on-exec flag
11534
11535
Create and return a timer file descriptor.
11536
[clinic start generated code]*/
11537
11538
static PyObject *
11539
os_timerfd_create_impl(PyObject *module, int clockid, int flags)
11540
/*[clinic end generated code: output=1caae80fb168004a input=64b7020c5ac0b8f4]*/
11541
11542
0
{
11543
0
    int fd;
11544
0
    Py_BEGIN_ALLOW_THREADS
11545
0
    flags |= TFD_CLOEXEC;  // PEP 446: always create non-inheritable FD
11546
0
    fd = timerfd_create(clockid, flags);
11547
0
    Py_END_ALLOW_THREADS
11548
0
    if (fd == -1) {
11549
0
        return PyErr_SetFromErrno(PyExc_OSError);
11550
0
    }
11551
0
    return PyLong_FromLong(fd);
11552
0
}
11553
11554
/*[clinic input]
11555
os.timerfd_settime
11556
11557
    fd: fildes
11558
        A timer file descriptor.
11559
    /
11560
    *
11561
    flags: int = 0
11562
        0 or a bit mask of TFD_TIMER_ABSTIME or TFD_TIMER_CANCEL_ON_SET.
11563
    initial as initial_double: double = 0.0
11564
        The initial expiration time, in seconds.
11565
    interval as interval_double: double = 0.0
11566
        The timer's interval, in seconds.
11567
11568
Alter a timer file descriptor's internal timer in seconds.
11569
[clinic start generated code]*/
11570
11571
static PyObject *
11572
os_timerfd_settime_impl(PyObject *module, int fd, int flags,
11573
                        double initial_double, double interval_double)
11574
/*[clinic end generated code: output=df4c1bce6859224e input=81d2c0d7e936e8a7]*/
11575
0
{
11576
0
    PyTime_t initial, interval;
11577
0
    if (_PyTime_FromSecondsDouble(initial_double, _PyTime_ROUND_FLOOR,
11578
0
                                  &initial) < 0) {
11579
0
        return NULL;
11580
0
    }
11581
0
    if (_PyTime_FromSecondsDouble(interval_double, _PyTime_ROUND_FLOOR,
11582
0
                                  &interval) < 0) {
11583
0
        return NULL;
11584
0
    }
11585
11586
0
    struct itimerspec new_value, old_value;
11587
0
    if (_PyTime_AsTimespec(initial, &new_value.it_value) < 0) {
11588
0
        PyErr_SetString(PyExc_ValueError, "invalid initial value");
11589
0
        return NULL;
11590
0
    }
11591
0
    if (_PyTime_AsTimespec(interval, &new_value.it_interval) < 0) {
11592
0
        PyErr_SetString(PyExc_ValueError, "invalid interval value");
11593
0
        return NULL;
11594
0
    }
11595
11596
0
    int result;
11597
0
    Py_BEGIN_ALLOW_THREADS
11598
0
    result = timerfd_settime(fd, flags, &new_value, &old_value);
11599
0
    Py_END_ALLOW_THREADS
11600
0
    if (result == -1) {
11601
0
        return PyErr_SetFromErrno(PyExc_OSError);
11602
0
    }
11603
0
    return build_itimerspec(&old_value);
11604
0
}
11605
11606
11607
/*[clinic input]
11608
os.timerfd_settime_ns
11609
11610
    fd: fildes
11611
        A timer file descriptor.
11612
    /
11613
    *
11614
    flags: int = 0
11615
        0 or a bit mask of TFD_TIMER_ABSTIME or TFD_TIMER_CANCEL_ON_SET.
11616
    initial: long_long = 0
11617
        initial expiration timing in nanoseconds.
11618
    interval: long_long = 0
11619
        interval for the timer in nanoseconds.
11620
11621
Alter a timer file descriptor's internal timer in nanoseconds.
11622
[clinic start generated code]*/
11623
11624
static PyObject *
11625
os_timerfd_settime_ns_impl(PyObject *module, int fd, int flags,
11626
                           long long initial, long long interval)
11627
/*[clinic end generated code: output=6273ec7d7b4cc0b3 input=94bdcea7292157eb]*/
11628
0
{
11629
0
    struct itimerspec new_value;
11630
0
    struct itimerspec old_value;
11631
0
    int result;
11632
0
    if (_PyTime_AsTimespec(initial, &new_value.it_value) < 0) {
11633
0
        PyErr_SetString(PyExc_ValueError, "invalid initial value");
11634
0
        return NULL;
11635
0
    }
11636
0
    if (_PyTime_AsTimespec(interval, &new_value.it_interval) < 0) {
11637
0
        PyErr_SetString(PyExc_ValueError, "invalid interval value");
11638
0
        return NULL;
11639
0
    }
11640
0
    Py_BEGIN_ALLOW_THREADS
11641
0
    result = timerfd_settime(fd, flags, &new_value, &old_value);
11642
0
    Py_END_ALLOW_THREADS
11643
0
    if (result == -1) {
11644
0
        return PyErr_SetFromErrno(PyExc_OSError);
11645
0
    }
11646
0
    return build_itimerspec_ns(&old_value);
11647
0
}
11648
11649
/*[clinic input]
11650
@permit_long_summary
11651
os.timerfd_gettime
11652
11653
    fd: fildes
11654
        A timer file descriptor.
11655
    /
11656
11657
Return a tuple of a timer file descriptor's (next expiration, interval) in float seconds.
11658
[clinic start generated code]*/
11659
11660
static PyObject *
11661
os_timerfd_gettime_impl(PyObject *module, int fd)
11662
/*[clinic end generated code: output=ec5a94a66cfe6ab4 input=7b0a7cc61ea9e31a]*/
11663
0
{
11664
0
    struct itimerspec curr_value;
11665
0
    int result;
11666
0
    Py_BEGIN_ALLOW_THREADS
11667
0
    result = timerfd_gettime(fd, &curr_value);
11668
0
    Py_END_ALLOW_THREADS
11669
0
    if (result == -1) {
11670
0
        return PyErr_SetFromErrno(PyExc_OSError);
11671
0
    }
11672
0
    return build_itimerspec(&curr_value);
11673
0
}
11674
11675
11676
/*[clinic input]
11677
@permit_long_summary
11678
os.timerfd_gettime_ns
11679
11680
    fd: fildes
11681
        A timer file descriptor.
11682
    /
11683
11684
Return a tuple of a timer file descriptor's (next expiration, interval) in nanoseconds.
11685
[clinic start generated code]*/
11686
11687
static PyObject *
11688
os_timerfd_gettime_ns_impl(PyObject *module, int fd)
11689
/*[clinic end generated code: output=580633a4465f39fe input=89702268455fa93b]*/
11690
0
{
11691
0
    struct itimerspec curr_value;
11692
0
    int result;
11693
0
    Py_BEGIN_ALLOW_THREADS
11694
0
    result = timerfd_gettime(fd, &curr_value);
11695
0
    Py_END_ALLOW_THREADS
11696
0
    if (result == -1) {
11697
0
        return PyErr_SetFromErrno(PyExc_OSError);
11698
0
    }
11699
0
    return build_itimerspec_ns(&curr_value);
11700
0
}
11701
11702
#undef ONE_SECOND_IN_NS
11703
#undef EXTRACT_NSEC
11704
11705
#endif  /* HAVE_TIMERFD_CREATE */
11706
11707
#ifdef HAVE_GETSID
11708
/*[clinic input]
11709
os.getsid
11710
11711
    pid: pid_t
11712
    /
11713
11714
Call the system call getsid(pid) and return the result.
11715
[clinic start generated code]*/
11716
11717
static PyObject *
11718
os_getsid_impl(PyObject *module, pid_t pid)
11719
/*[clinic end generated code: output=112deae56b306460 input=eeb2b923a30ce04e]*/
11720
0
{
11721
0
    int sid;
11722
0
    sid = getsid(pid);
11723
0
    if (sid < 0)
11724
0
        return posix_error();
11725
0
    return PyLong_FromLong((long)sid);
11726
0
}
11727
#endif /* HAVE_GETSID */
11728
11729
11730
#ifdef HAVE_SETSID
11731
/*[clinic input]
11732
os.setsid
11733
11734
Call the system call setsid().
11735
[clinic start generated code]*/
11736
11737
static PyObject *
11738
os_setsid_impl(PyObject *module)
11739
/*[clinic end generated code: output=e2ddedd517086d77 input=5fff45858e2f0776]*/
11740
0
{
11741
0
    if (setsid() < 0)
11742
0
        return posix_error();
11743
0
    Py_RETURN_NONE;
11744
0
}
11745
#endif /* HAVE_SETSID */
11746
11747
11748
#ifdef HAVE_SETPGID
11749
/*[clinic input]
11750
os.setpgid
11751
11752
    pid: pid_t
11753
    pgrp: pid_t
11754
    /
11755
11756
Call the system call setpgid(pid, pgrp).
11757
[clinic start generated code]*/
11758
11759
static PyObject *
11760
os_setpgid_impl(PyObject *module, pid_t pid, pid_t pgrp)
11761
/*[clinic end generated code: output=6461160319a43d6a input=fceb395eca572e1a]*/
11762
0
{
11763
0
    if (setpgid(pid, pgrp) < 0)
11764
0
        return posix_error();
11765
0
    Py_RETURN_NONE;
11766
0
}
11767
#endif /* HAVE_SETPGID */
11768
11769
11770
#ifdef HAVE_TCGETPGRP
11771
/*[clinic input]
11772
os.tcgetpgrp
11773
11774
    fd: int
11775
    /
11776
11777
Return the process group associated with the terminal specified by fd.
11778
[clinic start generated code]*/
11779
11780
static PyObject *
11781
os_tcgetpgrp_impl(PyObject *module, int fd)
11782
/*[clinic end generated code: output=f865e88be86c272b input=7f6c18eac10ada86]*/
11783
0
{
11784
0
    pid_t pgid = tcgetpgrp(fd);
11785
0
    if (pgid < 0)
11786
0
        return posix_error();
11787
0
    return PyLong_FromPid(pgid);
11788
0
}
11789
#endif /* HAVE_TCGETPGRP */
11790
11791
11792
#ifdef HAVE_TCSETPGRP
11793
/*[clinic input]
11794
os.tcsetpgrp
11795
11796
    fd: int
11797
    pgid: pid_t
11798
    /
11799
11800
Set the process group associated with the terminal specified by fd.
11801
[clinic start generated code]*/
11802
11803
static PyObject *
11804
os_tcsetpgrp_impl(PyObject *module, int fd, pid_t pgid)
11805
/*[clinic end generated code: output=f1821a381b9daa39 input=5bdc997c6a619020]*/
11806
0
{
11807
0
    if (tcsetpgrp(fd, pgid) < 0)
11808
0
        return posix_error();
11809
0
    Py_RETURN_NONE;
11810
0
}
11811
#endif /* HAVE_TCSETPGRP */
11812
11813
/* Functions acting on file descriptors */
11814
11815
#ifdef O_CLOEXEC
11816
extern int _Py_open_cloexec_works;
11817
#endif
11818
11819
11820
/*[clinic input]
11821
os.open -> int
11822
    path: path_t
11823
    flags: int
11824
    mode: int = 0o777
11825
    *
11826
    dir_fd: dir_fd(requires='openat') = None
11827
11828
Open a file for low level IO.  Returns a file descriptor (integer).
11829
11830
If dir_fd is not None, it should be a file descriptor open to
11831
a directory, and path should be relative; path will then be relative to
11832
that directory.
11833
dir_fd may not be implemented on your platform.  If it is unavailable,
11834
using it will raise a NotImplementedError.
11835
[clinic start generated code]*/
11836
11837
static int
11838
os_open_impl(PyObject *module, path_t *path, int flags, int mode, int dir_fd)
11839
/*[clinic end generated code: output=abc7227888c8bc73 input=75f7b4eaf92f2225]*/
11840
101k
{
11841
101k
    int fd;
11842
101k
    int async_err = 0;
11843
101k
#ifdef HAVE_OPENAT
11844
101k
    int openat_unavailable = 0;
11845
101k
#endif
11846
11847
101k
#ifdef O_CLOEXEC
11848
101k
    int *atomic_flag_works = &_Py_open_cloexec_works;
11849
#elif !defined(MS_WINDOWS)
11850
    int *atomic_flag_works = NULL;
11851
#endif
11852
11853
#ifdef MS_WINDOWS
11854
    flags |= O_NOINHERIT;
11855
#elif defined(O_CLOEXEC)
11856
101k
    flags |= O_CLOEXEC;
11857
101k
#endif
11858
11859
101k
    if (PySys_Audit("open", "OOi", path->object, Py_None, flags) < 0) {
11860
0
        return -1;
11861
0
    }
11862
11863
101k
    _Py_BEGIN_SUPPRESS_IPH
11864
101k
    do {
11865
101k
        Py_BEGIN_ALLOW_THREADS
11866
#ifdef MS_WINDOWS
11867
        fd = _wopen(path->wide, flags, mode);
11868
#else
11869
101k
#ifdef HAVE_OPENAT
11870
101k
        if (dir_fd != DEFAULT_DIR_FD) {
11871
97.0k
            if (HAVE_OPENAT_RUNTIME) {
11872
97.0k
                fd = openat(dir_fd, path->narrow, flags, mode);
11873
11874
97.0k
            } else {
11875
0
                openat_unavailable = 1;
11876
0
                fd = -1;
11877
0
            }
11878
97.0k
        } else
11879
4.64k
#endif /* HAVE_OPENAT */
11880
4.64k
            fd = open(path->narrow, flags, mode);
11881
101k
#endif /* !MS_WINDOWS */
11882
101k
        Py_END_ALLOW_THREADS
11883
101k
    } while (fd < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
11884
101k
    _Py_END_SUPPRESS_IPH
11885
11886
101k
#ifdef HAVE_OPENAT
11887
101k
    if (openat_unavailable) {
11888
0
        argument_unavailable_error(NULL, "dir_fd");
11889
0
        return -1;
11890
0
    }
11891
101k
#endif
11892
11893
101k
    if (fd < 0) {
11894
0
        if (!async_err)
11895
0
            PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, path->object);
11896
0
        return -1;
11897
0
    }
11898
11899
101k
#ifndef MS_WINDOWS
11900
101k
    if (_Py_set_inheritable(fd, 0, atomic_flag_works) < 0) {
11901
0
        close(fd);
11902
0
        return -1;
11903
0
    }
11904
101k
#endif
11905
11906
101k
    return fd;
11907
101k
}
11908
11909
11910
/*[clinic input]
11911
os.close
11912
11913
    fd: int
11914
11915
Close a file descriptor.
11916
[clinic start generated code]*/
11917
11918
static PyObject *
11919
os_close_impl(PyObject *module, int fd)
11920
/*[clinic end generated code: output=2fe4e93602822c14 input=2bc42451ca5c3223]*/
11921
101k
{
11922
101k
    int res;
11923
    /* We do not want to retry upon EINTR: see http://lwn.net/Articles/576478/
11924
     * and http://linux.derkeiler.com/Mailing-Lists/Kernel/2005-09/3000.html
11925
     * for more details.
11926
     */
11927
101k
    Py_BEGIN_ALLOW_THREADS
11928
101k
    _Py_BEGIN_SUPPRESS_IPH
11929
101k
    res = close(fd);
11930
101k
    _Py_END_SUPPRESS_IPH
11931
101k
    Py_END_ALLOW_THREADS
11932
101k
    if (res < 0)
11933
0
        return posix_error();
11934
101k
    Py_RETURN_NONE;
11935
101k
}
11936
11937
/*[clinic input]
11938
os.closerange
11939
11940
    fd_low: int
11941
    fd_high: int
11942
    /
11943
11944
Closes all file descriptors in [fd_low, fd_high), ignoring errors.
11945
[clinic start generated code]*/
11946
11947
static PyObject *
11948
os_closerange_impl(PyObject *module, int fd_low, int fd_high)
11949
/*[clinic end generated code: output=0ce5c20fcda681c2 input=5855a3d053ebd4ec]*/
11950
0
{
11951
0
    Py_BEGIN_ALLOW_THREADS
11952
0
    _Py_closerange(fd_low, fd_high - 1);
11953
0
    Py_END_ALLOW_THREADS
11954
0
    Py_RETURN_NONE;
11955
0
}
11956
11957
11958
/*[clinic input]
11959
os.dup -> int
11960
11961
    fd: int
11962
    /
11963
11964
Return a duplicate of a file descriptor.
11965
[clinic start generated code]*/
11966
11967
static int
11968
os_dup_impl(PyObject *module, int fd)
11969
/*[clinic end generated code: output=486f4860636b2a9f input=6f10f7ea97f7852a]*/
11970
0
{
11971
0
    return _Py_dup(fd);
11972
0
}
11973
11974
// dup2() is either provided by libc or dup2.c with AC_REPLACE_FUNCS().
11975
// dup2.c provides working dup2() if and only if F_DUPFD is available.
11976
#if (defined(HAVE_DUP3) || defined(F_DUPFD) || defined(MS_WINDOWS))
11977
/*[clinic input]
11978
os.dup2 -> int
11979
    fd: int
11980
    fd2: int
11981
    inheritable: bool=True
11982
11983
Duplicate file descriptor.
11984
[clinic start generated code]*/
11985
11986
static int
11987
os_dup2_impl(PyObject *module, int fd, int fd2, int inheritable)
11988
/*[clinic end generated code: output=bc059d34a73404d1 input=c3cddda8922b038d]*/
11989
0
{
11990
0
    int res = 0;
11991
11992
    /* dup3() is available on Linux 2.6.27+ and glibc 2.9 and macOS 27.0;
11993
     * it needs runtime detection for the case of running on older kernels.
11994
     * Values: -1: unknown; 0: doesn't work; 1: works
11995
     * For thread safety, use a process-global with one read & one store,
11996
     * both relaxed. (It's fine if two threads race and do the detection
11997
     * simultaneously; they should get the same result.)
11998
     */
11999
0
    static int dup3_works_atomic = -1;
12000
0
    (void) dup3_works_atomic;  // unused on some platforms
12001
12002
    /* dup2() can fail with EINTR if the target FD is already open, because it
12003
     * then has to be closed. See os_close_impl() for why we don't handle EINTR
12004
     * upon close(), and therefore below.
12005
     */
12006
#ifdef MS_WINDOWS
12007
    Py_BEGIN_ALLOW_THREADS
12008
    _Py_BEGIN_SUPPRESS_IPH
12009
    res = dup2(fd, fd2);
12010
    _Py_END_SUPPRESS_IPH
12011
    Py_END_ALLOW_THREADS
12012
    if (res < 0) {
12013
        posix_error();
12014
        return -1;
12015
    }
12016
    res = fd2; // msvcrt dup2 returns 0 on success.
12017
12018
    /* Character files like console cannot be make non-inheritable */
12019
    if (!inheritable && _Py_set_inheritable(fd2, 0, NULL) < 0) {
12020
        close(fd2);
12021
        return -1;
12022
    }
12023
12024
#elif defined(HAVE_FCNTL_H) && defined(F_DUP2FD_CLOEXEC)
12025
    Py_BEGIN_ALLOW_THREADS
12026
    if (!inheritable)
12027
        res = fcntl(fd, F_DUP2FD_CLOEXEC, fd2);
12028
    else
12029
        res = dup2(fd, fd2);
12030
    Py_END_ALLOW_THREADS
12031
    if (res < 0) {
12032
        posix_error();
12033
        return -1;
12034
    }
12035
12036
#else
12037
12038
0
#ifdef HAVE_DUP3
12039
0
    int dup3_works = FT_ATOMIC_LOAD_INT_RELAXED(dup3_works_atomic);
12040
0
    if (!inheritable && dup3_works != 0) {
12041
0
        if (HAVE_DUP3_RUNTIME) {
12042
0
            Py_BEGIN_ALLOW_THREADS
12043
0
            res = dup3(fd, fd2, O_CLOEXEC);
12044
0
            Py_END_ALLOW_THREADS
12045
0
            if (res < 0) {
12046
0
                if (dup3_works == -1) {
12047
0
                    dup3_works = (errno != ENOSYS);
12048
0
                    FT_ATOMIC_STORE_INT_RELAXED(dup3_works_atomic, dup3_works);
12049
0
                }
12050
0
                if (dup3_works) {
12051
0
                    posix_error();
12052
0
                    return -1;
12053
0
                }
12054
0
            }
12055
0
        }
12056
0
        else {
12057
0
            dup3_works = 0;
12058
0
            FT_ATOMIC_STORE_INT_RELAXED(dup3_works_atomic, dup3_works);
12059
0
        }
12060
0
    }
12061
12062
0
    if (inheritable || dup3_works == 0)
12063
0
    {
12064
0
#endif
12065
0
        Py_BEGIN_ALLOW_THREADS
12066
0
        res = dup2(fd, fd2);
12067
0
        Py_END_ALLOW_THREADS
12068
0
        if (res < 0) {
12069
0
            posix_error();
12070
0
            return -1;
12071
0
        }
12072
12073
0
        if (!inheritable && _Py_set_inheritable(fd2, 0, NULL) < 0) {
12074
0
            close(fd2);
12075
0
            return -1;
12076
0
        }
12077
0
#ifdef HAVE_DUP3
12078
0
    }
12079
0
#endif
12080
12081
0
#endif
12082
12083
0
    return res;
12084
0
}
12085
#endif
12086
12087
12088
#ifdef HAVE_LOCKF
12089
/*[clinic input]
12090
os.lockf
12091
12092
    fd: int
12093
        An open file descriptor.
12094
    command: int
12095
        One of F_LOCK, F_TLOCK, F_ULOCK or F_TEST.
12096
    length: Py_off_t
12097
        The number of bytes to lock, starting at the current position.
12098
    /
12099
12100
Apply, test or remove a POSIX lock on an open file descriptor.
12101
12102
[clinic start generated code]*/
12103
12104
static PyObject *
12105
os_lockf_impl(PyObject *module, int fd, int command, Py_off_t length)
12106
/*[clinic end generated code: output=af7051f3e7c29651 input=65da41d2106e9b79]*/
12107
0
{
12108
0
    int res;
12109
12110
0
    if (PySys_Audit("os.lockf", "iiL", fd, command, length) < 0) {
12111
0
        return NULL;
12112
0
    }
12113
12114
0
    Py_BEGIN_ALLOW_THREADS
12115
0
    res = lockf(fd, command, length);
12116
0
    Py_END_ALLOW_THREADS
12117
12118
0
    if (res < 0)
12119
0
        return posix_error();
12120
12121
0
    Py_RETURN_NONE;
12122
0
}
12123
#endif /* HAVE_LOCKF */
12124
12125
12126
/*[clinic input]
12127
os.lseek -> Py_off_t
12128
12129
    fd: int
12130
        An open file descriptor, as returned by os.open().
12131
    position: Py_off_t
12132
        Position, interpreted relative to 'whence'.
12133
    whence as how: int
12134
        The relative position to seek from. Valid values are:
12135
        - SEEK_SET: seek from the start of the file.
12136
        - SEEK_CUR: seek from the current file position.
12137
        - SEEK_END: seek from the end of the file.
12138
    /
12139
12140
Set the position of a file descriptor.  Return the new position.
12141
12142
The return value is the number of bytes relative to the beginning of
12143
the file.
12144
[clinic start generated code]*/
12145
12146
static Py_off_t
12147
os_lseek_impl(PyObject *module, int fd, Py_off_t position, int how)
12148
/*[clinic end generated code: output=971e1efb6b30bd2f input=32ea0788da7cb44b]*/
12149
0
{
12150
0
    Py_off_t result = -1;
12151
12152
0
#ifdef SEEK_SET
12153
    /* Turn 0, 1, 2 into SEEK_{SET,CUR,END} */
12154
0
    switch (how) {
12155
0
        case 0: how = SEEK_SET; break;
12156
0
        case 1: how = SEEK_CUR; break;
12157
0
        case 2: how = SEEK_END; break;
12158
0
    }
12159
0
#endif /* SEEK_END */
12160
12161
0
    Py_BEGIN_ALLOW_THREADS
12162
0
    _Py_BEGIN_SUPPRESS_IPH
12163
#ifdef MS_WINDOWS
12164
    HANDLE h = (HANDLE)_get_osfhandle(fd);
12165
    if (h != INVALID_HANDLE_VALUE && GetFileType(h) == FILE_TYPE_PIPE) {
12166
        errno = ESPIPE;
12167
    }
12168
    else {
12169
        result = _lseeki64(fd, position, how);
12170
    }
12171
#else
12172
0
    result = lseek(fd, position, how);
12173
0
#endif
12174
0
    _Py_END_SUPPRESS_IPH
12175
0
    Py_END_ALLOW_THREADS
12176
0
    if (result < 0) {
12177
0
        posix_error();
12178
0
    }
12179
12180
0
    return result;
12181
0
}
12182
12183
12184
/*[clinic input]
12185
os.read
12186
    fd: int
12187
    length: Py_ssize_t
12188
    /
12189
12190
Read from a file descriptor.  Returns a bytes object.
12191
[clinic start generated code]*/
12192
12193
static PyObject *
12194
os_read_impl(PyObject *module, int fd, Py_ssize_t length)
12195
/*[clinic end generated code: output=dafbe9a5cddb987b input=1df2eaa27c0bf1d3]*/
12196
0
{
12197
0
    if (length < 0) {
12198
0
        errno = EINVAL;
12199
0
        return posix_error();
12200
0
    }
12201
12202
0
    length = Py_MIN(length, _PY_READ_MAX);
12203
12204
0
    PyBytesWriter *writer = PyBytesWriter_Create(length);
12205
0
    if (writer == NULL) {
12206
0
        return NULL;
12207
0
    }
12208
12209
0
    Py_ssize_t n = _Py_read(fd, PyBytesWriter_GetData(writer), length);
12210
0
    if (n == -1) {
12211
0
        PyBytesWriter_Discard(writer);
12212
0
        return NULL;
12213
0
    }
12214
12215
0
    return PyBytesWriter_FinishWithSize(writer, n);
12216
0
}
12217
12218
/*[clinic input]
12219
os.readinto -> Py_ssize_t
12220
    fd: int
12221
    buffer: Py_buffer(accept={rwbuffer})
12222
    /
12223
12224
Read into a buffer object from a file descriptor.
12225
12226
The buffer should be mutable and bytes-like.  On success, returns the
12227
number of bytes read.  Less bytes may be read than the size of the
12228
buffer.  The underlying system call will be retried when interrupted by
12229
a signal, unless the signal handler raises an exception.  Other errors
12230
will not be retried and an error will be raised.
12231
12232
Returns 0 if *fd* is at end of file or if the provided *buffer* has
12233
length 0 (which can be used to check for errors without reading data).
12234
Never returns negative.
12235
[clinic start generated code]*/
12236
12237
static Py_ssize_t
12238
os_readinto_impl(PyObject *module, int fd, Py_buffer *buffer)
12239
/*[clinic end generated code: output=8091a3513c683a80 input=2a5f8b212cb5730c]*/
12240
0
{
12241
0
    assert(buffer->len >= 0);
12242
0
    Py_ssize_t result = _Py_read(fd, buffer->buf, buffer->len);
12243
    /* Ensure negative is never returned without an error. Simplifies calling
12244
        code. _Py_read should succeed, possibly reading 0 bytes, _or_ set an
12245
        error. */
12246
0
    assert(result >= 0 || (result == -1 && PyErr_Occurred()));
12247
0
    return result;
12248
0
}
12249
12250
#if (defined(HAVE_SENDFILE) && (defined(__FreeBSD__) || defined(__DragonFly__) \
12251
                                || defined(__APPLE__))) \
12252
    || defined(HAVE_READV) || defined(HAVE_PREADV) || defined (HAVE_PREADV2) \
12253
    || defined(HAVE_WRITEV) || defined(HAVE_PWRITEV) || defined (HAVE_PWRITEV2)
12254
static int
12255
iov_setup(struct iovec **iov, Py_buffer **buf, PyObject *seq, Py_ssize_t cnt, int type)
12256
0
{
12257
0
    Py_ssize_t i, j;
12258
12259
0
    *iov = PyMem_New(struct iovec, cnt);
12260
0
    if (*iov == NULL) {
12261
0
        PyErr_NoMemory();
12262
0
        return -1;
12263
0
    }
12264
12265
0
    *buf = PyMem_New(Py_buffer, cnt);
12266
0
    if (*buf == NULL) {
12267
0
        PyMem_Free(*iov);
12268
0
        PyErr_NoMemory();
12269
0
        return -1;
12270
0
    }
12271
12272
0
    for (i = 0; i < cnt; i++) {
12273
0
        PyObject *item = PySequence_GetItem(seq, i);
12274
0
        if (item == NULL)
12275
0
            goto fail;
12276
0
        if (PyObject_GetBuffer(item, &(*buf)[i], type) == -1) {
12277
0
            Py_DECREF(item);
12278
0
            goto fail;
12279
0
        }
12280
0
        Py_DECREF(item);
12281
0
        (*iov)[i].iov_base = (*buf)[i].buf;
12282
0
        (*iov)[i].iov_len = (*buf)[i].len;
12283
0
    }
12284
0
    return 0;
12285
12286
0
fail:
12287
0
    PyMem_Free(*iov);
12288
0
    for (j = 0; j < i; j++) {
12289
0
        PyBuffer_Release(&(*buf)[j]);
12290
0
    }
12291
0
    PyMem_Free(*buf);
12292
0
    return -1;
12293
0
}
12294
12295
static void
12296
iov_cleanup(struct iovec *iov, Py_buffer *buf, int cnt)
12297
0
{
12298
0
    int i;
12299
0
    PyMem_Free(iov);
12300
0
    for (i = 0; i < cnt; i++) {
12301
0
        PyBuffer_Release(&buf[i]);
12302
0
    }
12303
0
    PyMem_Free(buf);
12304
0
}
12305
#endif
12306
12307
12308
#ifdef HAVE_READV
12309
/*[clinic input]
12310
os.readv -> Py_ssize_t
12311
12312
    fd: int
12313
    buffers: object
12314
    /
12315
12316
Read from a file descriptor fd into an iterable of buffers.
12317
12318
The buffers should be mutable buffers accepting bytes.
12319
readv will transfer data into each buffer until it is full
12320
and then move on to the next buffer in the sequence to hold
12321
the rest of the data.
12322
12323
readv returns the total number of bytes read,
12324
which may be less than the total capacity of all the buffers.
12325
[clinic start generated code]*/
12326
12327
static Py_ssize_t
12328
os_readv_impl(PyObject *module, int fd, PyObject *buffers)
12329
/*[clinic end generated code: output=792da062d3fcebdb input=e679eb5dbfa0357d]*/
12330
0
{
12331
0
    Py_ssize_t cnt, n;
12332
0
    int async_err = 0;
12333
0
    struct iovec *iov;
12334
0
    Py_buffer *buf;
12335
12336
0
    if (!PySequence_Check(buffers)) {
12337
0
        PyErr_SetString(PyExc_TypeError,
12338
0
            "readv() arg 2 must be a sequence");
12339
0
        return -1;
12340
0
    }
12341
12342
0
    cnt = PySequence_Size(buffers);
12343
0
    if (cnt < 0)
12344
0
        return -1;
12345
12346
0
    if (iov_setup(&iov, &buf, buffers, cnt, PyBUF_WRITABLE) < 0)
12347
0
        return -1;
12348
12349
0
    do {
12350
0
        Py_BEGIN_ALLOW_THREADS
12351
0
        n = readv(fd, iov, cnt);
12352
0
        Py_END_ALLOW_THREADS
12353
0
    } while (n < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
12354
12355
0
    int saved_errno = errno;
12356
0
    iov_cleanup(iov, buf, cnt);
12357
0
    if (n < 0) {
12358
0
        if (!async_err) {
12359
0
            errno = saved_errno;
12360
0
            posix_error();
12361
0
        }
12362
0
        return -1;
12363
0
    }
12364
12365
0
    return n;
12366
0
}
12367
#endif /* HAVE_READV */
12368
12369
12370
#ifdef HAVE_PREAD
12371
/*[clinic input]
12372
@permit_long_summary
12373
os.pread
12374
12375
    fd: int
12376
    length: Py_ssize_t
12377
    offset: Py_off_t
12378
    /
12379
12380
Read a number of bytes from a file descriptor starting at a particular offset.
12381
12382
Read length bytes from file descriptor fd, starting at offset bytes from
12383
the beginning of the file.  The file offset remains unchanged.
12384
[clinic start generated code]*/
12385
12386
static PyObject *
12387
os_pread_impl(PyObject *module, int fd, Py_ssize_t length, Py_off_t offset)
12388
/*[clinic end generated code: output=3f875c1eef82e32f input=5943beb009d3da04]*/
12389
0
{
12390
0
    Py_ssize_t n;
12391
0
    int async_err = 0;
12392
12393
0
    if (length < 0) {
12394
0
        errno = EINVAL;
12395
0
        return posix_error();
12396
0
    }
12397
0
    PyBytesWriter *writer = PyBytesWriter_Create(length);
12398
0
    if (writer == NULL) {
12399
0
        return NULL;
12400
0
    }
12401
12402
0
    do {
12403
0
        Py_BEGIN_ALLOW_THREADS
12404
0
        _Py_BEGIN_SUPPRESS_IPH
12405
0
        n = pread(fd, PyBytesWriter_GetData(writer), length, offset);
12406
0
        _Py_END_SUPPRESS_IPH
12407
0
        Py_END_ALLOW_THREADS
12408
0
    } while (n < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
12409
12410
0
    if (n < 0) {
12411
0
        if (!async_err) {
12412
0
            posix_error();
12413
0
        }
12414
0
        PyBytesWriter_Discard(writer);
12415
0
        return NULL;
12416
0
    }
12417
0
    return PyBytesWriter_FinishWithSize(writer, n);
12418
0
}
12419
#endif /* HAVE_PREAD */
12420
12421
#if defined(HAVE_PREADV) || defined (HAVE_PREADV2)
12422
/*[clinic input]
12423
@permit_long_summary
12424
os.preadv -> Py_ssize_t
12425
12426
    fd: int
12427
    buffers: object
12428
    offset: Py_off_t
12429
    flags: int = 0
12430
    /
12431
12432
Reads from a file descriptor into a number of mutable bytes-like objects.
12433
12434
Combines the functionality of readv() and pread().  As readv(), it will
12435
transfer data into each buffer until it is full and then move on to the
12436
next buffer in the sequence to hold the rest of the data.  Its fourth
12437
argument, specifies the file offset at which the input operation is to
12438
be performed.  It will return the total number of bytes read (which can
12439
be less than the total capacity of all the objects).
12440
12441
The flags argument contains a bitwise OR of zero or more of the
12442
following flags:
12443
12444
- RWF_HIPRI
12445
- RWF_NOWAIT
12446
- RWF_DONTCACHE
12447
12448
Using non-zero flags requires Linux 4.6 or newer.
12449
[clinic start generated code]*/
12450
12451
static Py_ssize_t
12452
os_preadv_impl(PyObject *module, int fd, PyObject *buffers, Py_off_t offset,
12453
               int flags)
12454
/*[clinic end generated code: output=26fc9c6e58e7ada5 input=bbc70c63b4f4e877]*/
12455
0
{
12456
0
    Py_ssize_t cnt, n;
12457
0
    int async_err = 0;
12458
0
    struct iovec *iov;
12459
0
    Py_buffer *buf;
12460
12461
0
    if (!PySequence_Check(buffers)) {
12462
0
        PyErr_SetString(PyExc_TypeError,
12463
0
            "preadv() arg 2 must be a sequence");
12464
0
        return -1;
12465
0
    }
12466
12467
0
    cnt = PySequence_Size(buffers);
12468
0
    if (cnt < 0) {
12469
0
        return -1;
12470
0
    }
12471
12472
#ifndef HAVE_PREADV2
12473
    if(flags != 0) {
12474
        argument_unavailable_error("preadv2", "flags");
12475
        return -1;
12476
    }
12477
#endif
12478
12479
0
    if (iov_setup(&iov, &buf, buffers, cnt, PyBUF_WRITABLE) < 0) {
12480
0
        return -1;
12481
0
    }
12482
0
#ifdef HAVE_PREADV2
12483
0
    do {
12484
0
        Py_BEGIN_ALLOW_THREADS
12485
0
        _Py_BEGIN_SUPPRESS_IPH
12486
0
        n = preadv2(fd, iov, cnt, offset, flags);
12487
0
        _Py_END_SUPPRESS_IPH
12488
0
        Py_END_ALLOW_THREADS
12489
0
    } while (n < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
12490
#else
12491
    do {
12492
#if defined(__APPLE__) && defined(__clang__)
12493
/* This entire function will be removed from the module dict when the API
12494
 * is not available.
12495
 */
12496
#pragma clang diagnostic push
12497
#pragma clang diagnostic ignored "-Wunguarded-availability"
12498
#pragma clang diagnostic ignored "-Wunguarded-availability-new"
12499
#endif
12500
        Py_BEGIN_ALLOW_THREADS
12501
        _Py_BEGIN_SUPPRESS_IPH
12502
        n = preadv(fd, iov, cnt, offset);
12503
        _Py_END_SUPPRESS_IPH
12504
        Py_END_ALLOW_THREADS
12505
    } while (n < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
12506
12507
#if defined(__APPLE__) && defined(__clang__)
12508
#pragma clang diagnostic pop
12509
#endif
12510
12511
#endif
12512
12513
0
    int saved_errno = errno;
12514
0
    iov_cleanup(iov, buf, cnt);
12515
0
    if (n < 0) {
12516
0
        if (!async_err) {
12517
0
            errno = saved_errno;
12518
0
            posix_error();
12519
0
        }
12520
0
        return -1;
12521
0
    }
12522
12523
0
    return n;
12524
0
}
12525
#endif /* HAVE_PREADV */
12526
12527
12528
/*[clinic input]
12529
os.write -> Py_ssize_t
12530
12531
    fd: int
12532
    data: Py_buffer
12533
    /
12534
12535
Write a bytes object to a file descriptor.
12536
[clinic start generated code]*/
12537
12538
static Py_ssize_t
12539
os_write_impl(PyObject *module, int fd, Py_buffer *data)
12540
/*[clinic end generated code: output=e4ef5bc904b58ef9 input=3207e28963234f3c]*/
12541
2
{
12542
2
    return _Py_write(fd, data->buf, data->len);
12543
2
}
12544
12545
#ifdef HAVE_SENDFILE
12546
#ifdef __APPLE__
12547
/*[clinic input]
12548
os.sendfile
12549
12550
    out_fd: int
12551
    in_fd: int
12552
    offset: Py_off_t
12553
    count as sbytes: Py_off_t
12554
    headers: object(c_default="NULL") = ()
12555
    trailers: object(c_default="NULL") = ()
12556
    flags: int = 0
12557
12558
Copy count bytes from file descriptor in_fd to file descriptor out_fd.
12559
[clinic start generated code]*/
12560
12561
static PyObject *
12562
os_sendfile_impl(PyObject *module, int out_fd, int in_fd, Py_off_t offset,
12563
                 Py_off_t sbytes, PyObject *headers, PyObject *trailers,
12564
                 int flags)
12565
/*[clinic end generated code: output=81c4bcd143f5c82b input=b0d72579d4c69afa]*/
12566
#elif defined(__FreeBSD__) || defined(__DragonFly__)
12567
/*[clinic input]
12568
os.sendfile
12569
12570
    out_fd: int
12571
    in_fd: int
12572
    offset: Py_off_t
12573
    count: Py_ssize_t(allow_negative=False)
12574
    headers: object(c_default="NULL") = ()
12575
    trailers: object(c_default="NULL") = ()
12576
    flags: int = 0
12577
12578
Copy count bytes from file descriptor in_fd to file descriptor out_fd.
12579
[clinic start generated code]*/
12580
12581
static PyObject *
12582
os_sendfile_impl(PyObject *module, int out_fd, int in_fd, Py_off_t offset,
12583
                 Py_ssize_t count, PyObject *headers, PyObject *trailers,
12584
                 int flags)
12585
/*[clinic end generated code: output=329ea009bdd55afc input=dcb026b94effa922]*/
12586
#else
12587
/*[clinic input]
12588
os.sendfile
12589
12590
    out_fd: int
12591
    in_fd: int
12592
    offset as offobj: object
12593
    count: Py_ssize_t(allow_negative=False)
12594
12595
Copy count bytes from file descriptor in_fd to file descriptor out_fd.
12596
[clinic start generated code]*/
12597
12598
static PyObject *
12599
os_sendfile_impl(PyObject *module, int out_fd, int in_fd, PyObject *offobj,
12600
                 Py_ssize_t count)
12601
/*[clinic end generated code: output=ae81216e40f167d8 input=424df0949059ea5b]*/
12602
#endif
12603
0
{
12604
0
    Py_ssize_t ret;
12605
0
    int async_err = 0;
12606
12607
#ifdef __APPLE__
12608
    if(sbytes < 0) {
12609
        PyErr_SetString(PyExc_ValueError,
12610
                        "count cannot be negative");
12611
        return NULL;
12612
    }
12613
#else
12614
0
    assert(count >= 0);
12615
0
#endif
12616
12617
#if defined(__FreeBSD__) || defined(__DragonFly__) || defined(__APPLE__)
12618
#ifndef __APPLE__
12619
    off_t sbytes;
12620
#endif
12621
    Py_buffer *hbuf, *tbuf;
12622
    struct sf_hdtr sf;
12623
12624
    sf.headers = NULL;
12625
    sf.trailers = NULL;
12626
12627
    if (headers != NULL) {
12628
        if (!PySequence_Check(headers)) {
12629
            PyErr_SetString(PyExc_TypeError,
12630
                "sendfile() headers must be a sequence");
12631
            return NULL;
12632
        } else {
12633
            Py_ssize_t i = PySequence_Size(headers);
12634
            if (i < 0)
12635
                return NULL;
12636
            if (i > INT_MAX) {
12637
                PyErr_SetString(PyExc_OverflowError,
12638
                    "sendfile() header is too large");
12639
                return NULL;
12640
            }
12641
            if (i > 0) {
12642
                sf.hdr_cnt = (int)i;
12643
                if (iov_setup(&(sf.headers), &hbuf,
12644
                              headers, sf.hdr_cnt, PyBUF_SIMPLE) < 0)
12645
                    return NULL;
12646
#ifdef __APPLE__
12647
                for (i = 0; i < sf.hdr_cnt; i++) {
12648
                    Py_ssize_t blen = sf.headers[i].iov_len;
12649
# define OFF_T_MAX 0x7fffffffffffffff
12650
                    if (sbytes >= OFF_T_MAX - blen) {
12651
                        PyErr_SetString(PyExc_OverflowError,
12652
                            "sendfile() header is too large");
12653
                        return NULL;
12654
                    }
12655
                    sbytes += blen;
12656
                }
12657
#endif
12658
            }
12659
        }
12660
    }
12661
    if (trailers != NULL) {
12662
        if (!PySequence_Check(trailers)) {
12663
            PyErr_SetString(PyExc_TypeError,
12664
                "sendfile() trailers must be a sequence");
12665
            return NULL;
12666
        } else {
12667
            Py_ssize_t i = PySequence_Size(trailers);
12668
            if (i < 0)
12669
                return NULL;
12670
            if (i > INT_MAX) {
12671
                PyErr_SetString(PyExc_OverflowError,
12672
                    "sendfile() trailer is too large");
12673
                return NULL;
12674
            }
12675
            if (i > 0) {
12676
                sf.trl_cnt = (int)i;
12677
                if (iov_setup(&(sf.trailers), &tbuf,
12678
                              trailers, sf.trl_cnt, PyBUF_SIMPLE) < 0)
12679
                    return NULL;
12680
            }
12681
        }
12682
    }
12683
12684
    _Py_BEGIN_SUPPRESS_IPH
12685
    do {
12686
        Py_BEGIN_ALLOW_THREADS
12687
#ifdef __APPLE__
12688
        ret = sendfile(in_fd, out_fd, offset, &sbytes, &sf, flags);
12689
#else
12690
        ret = sendfile(in_fd, out_fd, offset, count, &sf, &sbytes, flags);
12691
#endif
12692
        Py_END_ALLOW_THREADS
12693
    } while (ret < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
12694
    _Py_END_SUPPRESS_IPH
12695
12696
    int saved_errno = errno;
12697
    if (sf.headers != NULL)
12698
        iov_cleanup(sf.headers, hbuf, sf.hdr_cnt);
12699
    if (sf.trailers != NULL)
12700
        iov_cleanup(sf.trailers, tbuf, sf.trl_cnt);
12701
12702
    if (ret < 0) {
12703
        if ((saved_errno == EAGAIN) || (saved_errno == EBUSY)) {
12704
            if (sbytes != 0) {
12705
                // some data has been sent
12706
                goto done;
12707
            }
12708
            // no data has been sent; upper application is supposed
12709
            // to retry on EAGAIN or EBUSY
12710
        }
12711
        if (!async_err) {
12712
            errno = saved_errno;
12713
            posix_error();
12714
        }
12715
        return NULL;
12716
    }
12717
    goto done;
12718
12719
done:
12720
    #if !defined(HAVE_LARGEFILE_SUPPORT)
12721
        return PyLong_FromLong(sbytes);
12722
    #else
12723
        return PyLong_FromLongLong(sbytes);
12724
    #endif
12725
12726
#else
12727
0
#ifdef __linux__
12728
0
    if (offobj == Py_None) {
12729
0
        do {
12730
0
            Py_BEGIN_ALLOW_THREADS
12731
0
            ret = sendfile(out_fd, in_fd, NULL, count);
12732
0
            Py_END_ALLOW_THREADS
12733
0
        } while (ret < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
12734
0
        if (ret < 0)
12735
0
            return (!async_err) ? posix_error() : NULL;
12736
0
        return PyLong_FromSsize_t(ret);
12737
0
    }
12738
0
#endif
12739
0
    off_t offset;
12740
0
    if (!_Py_Off_t_Converter(offobj, &offset))
12741
0
        return NULL;
12742
12743
#if defined(__sun) && defined(__SVR4)
12744
    // On Solaris, sendfile raises EINVAL rather than returning 0
12745
    // when the offset is equal or bigger than the in_fd size.
12746
    struct stat st;
12747
12748
    do {
12749
        Py_BEGIN_ALLOW_THREADS
12750
        ret = fstat(in_fd, &st);
12751
        Py_END_ALLOW_THREADS
12752
    } while (ret != 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
12753
    if (ret < 0)
12754
        return (!async_err) ? posix_error() : NULL;
12755
12756
    if (offset >= st.st_size) {
12757
        return PyLong_FromLong(0);
12758
    }
12759
12760
    // sendfile() may perform a partial write and still return -1, so the
12761
    // number of transferred bytes must be taken from the out parameter.
12762
    // sendfile() reports it by adding it to the offset, but does not
12763
    // initialize it when the transfer fails before writing any data, so use
12764
    // sendfilev(), which reports it explicitly.
12765
    sendfilevec_t vec;
12766
    size_t xferred;
12767
12768
    vec.sfv_fd = in_fd;
12769
    vec.sfv_flag = 0;
12770
    vec.sfv_off = offset;
12771
    vec.sfv_len = count;
12772
12773
    do {
12774
        Py_BEGIN_ALLOW_THREADS
12775
        xferred = 0;
12776
        ret = sendfilev(out_fd, &vec, 1, &xferred);
12777
        if (ret < 0 && xferred != 0) {
12778
            ret = (Py_ssize_t)xferred;
12779
        }
12780
        Py_END_ALLOW_THREADS
12781
    } while (ret < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
12782
#else
12783
0
    do {
12784
0
        Py_BEGIN_ALLOW_THREADS
12785
0
        ret = sendfile(out_fd, in_fd, &offset, count);
12786
0
        Py_END_ALLOW_THREADS
12787
0
    } while (ret < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
12788
0
#endif
12789
0
    if (ret < 0)
12790
0
        return (!async_err) ? posix_error() : NULL;
12791
0
    return PyLong_FromSsize_t(ret);
12792
0
#endif
12793
0
}
12794
#endif /* HAVE_SENDFILE */
12795
12796
12797
#if defined(__APPLE__)
12798
/*[clinic input]
12799
@permit_long_summary
12800
os._fcopyfile
12801
12802
    in_fd: int
12803
    out_fd: int
12804
    flags: int
12805
    /
12806
12807
Efficiently copy content or metadata of 2 regular file descriptors (macOS).
12808
[clinic start generated code]*/
12809
12810
static PyObject *
12811
os__fcopyfile_impl(PyObject *module, int in_fd, int out_fd, int flags)
12812
/*[clinic end generated code: output=c9d1a35a992e401b input=80b53ad8863c9101]*/
12813
{
12814
    int ret;
12815
12816
    Py_BEGIN_ALLOW_THREADS
12817
    ret = fcopyfile(in_fd, out_fd, NULL, flags);
12818
    Py_END_ALLOW_THREADS
12819
    if (ret < 0)
12820
        return posix_error();
12821
    Py_RETURN_NONE;
12822
}
12823
#endif
12824
12825
12826
/*[clinic input]
12827
os.fstat
12828
12829
    fd : int
12830
12831
Perform a stat system call on the given file descriptor.
12832
12833
Like stat(), but for an open file descriptor.
12834
Equivalent to os.stat(fd).
12835
[clinic start generated code]*/
12836
12837
static PyObject *
12838
os_fstat_impl(PyObject *module, int fd)
12839
/*[clinic end generated code: output=efc038cb5f654492 input=27e0e0ebbe5600c9]*/
12840
101k
{
12841
101k
    STRUCT_STAT st;
12842
101k
    int res;
12843
101k
    int async_err = 0;
12844
12845
101k
    do {
12846
101k
        Py_BEGIN_ALLOW_THREADS
12847
101k
        res = FSTAT(fd, &st);
12848
101k
        Py_END_ALLOW_THREADS
12849
101k
    } while (res != 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
12850
101k
    if (res != 0) {
12851
#ifdef MS_WINDOWS
12852
        return PyErr_SetFromWindowsErr(0);
12853
#else
12854
0
        return (!async_err) ? posix_error() : NULL;
12855
0
#endif
12856
0
    }
12857
12858
101k
    return _pystat_fromstructstat(module, &st);
12859
101k
}
12860
12861
12862
/*[clinic input]
12863
os.isatty -> bool
12864
    fd: int
12865
    /
12866
12867
Return True if the fd is connected to a terminal.
12868
12869
Return True if the file descriptor is an open file descriptor
12870
connected to the slave end of a terminal.
12871
[clinic start generated code]*/
12872
12873
static int
12874
os_isatty_impl(PyObject *module, int fd)
12875
/*[clinic end generated code: output=6a48c8b4e644ca00 input=08ce94aa1eaf7b5e]*/
12876
0
{
12877
0
    int return_value;
12878
0
    Py_BEGIN_ALLOW_THREADS
12879
0
    _Py_BEGIN_SUPPRESS_IPH
12880
0
    return_value = isatty(fd);
12881
0
    _Py_END_SUPPRESS_IPH
12882
0
    Py_END_ALLOW_THREADS
12883
0
    return return_value;
12884
0
}
12885
12886
12887
#ifdef HAVE_PIPE
12888
/*[clinic input]
12889
os.pipe
12890
12891
Create a pipe.
12892
12893
Returns a tuple of two file descriptors:
12894
  (read_fd, write_fd)
12895
[clinic start generated code]*/
12896
12897
static PyObject *
12898
os_pipe_impl(PyObject *module)
12899
/*[clinic end generated code: output=ff9b76255793b440 input=02535e8c8fa6c4d4]*/
12900
0
{
12901
0
    int fds[2];
12902
#ifdef MS_WINDOWS
12903
    HANDLE read, write;
12904
    SECURITY_ATTRIBUTES attr;
12905
    BOOL ok;
12906
#else
12907
0
    int res = -1;
12908
12909
    /* pipe2() is available on some newer linux/glibc & macOS;
12910
     * use the same runtime detection as for dup3 above.
12911
     */
12912
0
    static int pipe2_works_atomic = -1;
12913
0
    (void) pipe2_works_atomic;  // unused on some platforms
12914
0
#endif
12915
12916
#ifdef MS_WINDOWS
12917
    attr.nLength = sizeof(attr);
12918
    attr.lpSecurityDescriptor = NULL;
12919
    attr.bInheritHandle = FALSE;
12920
12921
    Py_BEGIN_ALLOW_THREADS
12922
    ok = CreatePipe(&read, &write, &attr, 0);
12923
    if (ok) {
12924
        fds[0] = _Py_open_osfhandle_noraise(read, _O_RDONLY | _O_NOINHERIT);
12925
        fds[1] = _Py_open_osfhandle_noraise(write, _O_WRONLY | _O_NOINHERIT);
12926
        if (fds[0] == -1 || fds[1] == -1) {
12927
            CloseHandle(read);
12928
            CloseHandle(write);
12929
            ok = 0;
12930
        }
12931
    }
12932
    Py_END_ALLOW_THREADS
12933
12934
    if (!ok)
12935
        return PyErr_SetFromWindowsErr(0);
12936
#else
12937
12938
0
#ifdef HAVE_PIPE2
12939
0
    int pipe2_works = FT_ATOMIC_LOAD_INT_RELAXED(pipe2_works_atomic);
12940
0
    if (pipe2_works != 0) {
12941
0
        if (HAVE_PIPE2_RUNTIME) {
12942
0
            Py_BEGIN_ALLOW_THREADS
12943
0
            res = pipe2(fds, O_CLOEXEC);
12944
0
            Py_END_ALLOW_THREADS
12945
0
            if (pipe2_works == -1) {
12946
0
                if (res != 0 && errno == ENOSYS) {
12947
0
                    pipe2_works = 0;
12948
0
                }
12949
0
                else {
12950
                    // pipe2 is present but this call failed
12951
0
                    pipe2_works = 1;
12952
0
                }
12953
0
                FT_ATOMIC_STORE_INT_RELAXED(pipe2_works_atomic, pipe2_works);
12954
0
            }
12955
0
        }
12956
0
        else {
12957
0
            pipe2_works = 0;
12958
0
            FT_ATOMIC_STORE_INT_RELAXED(pipe2_works_atomic, pipe2_works);
12959
0
        }
12960
0
    }
12961
12962
0
    if (pipe2_works == 0)
12963
0
    {
12964
0
#endif
12965
0
        Py_BEGIN_ALLOW_THREADS
12966
0
        res = pipe(fds);
12967
0
        Py_END_ALLOW_THREADS
12968
12969
0
        if (res == 0) {
12970
0
            if (_Py_set_inheritable(fds[0], 0, NULL) < 0) {
12971
0
                close(fds[0]);
12972
0
                close(fds[1]);
12973
0
                return NULL;
12974
0
            }
12975
0
            if (_Py_set_inheritable(fds[1], 0, NULL) < 0) {
12976
0
                close(fds[0]);
12977
0
                close(fds[1]);
12978
0
                return NULL;
12979
0
            }
12980
0
        }
12981
0
#ifdef HAVE_PIPE2
12982
0
    }
12983
0
#endif
12984
12985
0
    if (res != 0) {
12986
0
        return PyErr_SetFromErrno(PyExc_OSError);
12987
0
    }
12988
0
#endif /* !MS_WINDOWS */
12989
0
    return Py_BuildValue("(ii)", fds[0], fds[1]);
12990
0
}
12991
#endif  /* HAVE_PIPE */
12992
12993
12994
#ifdef HAVE_PIPE2
12995
/*[clinic input]
12996
os.pipe2
12997
12998
    flags: int
12999
    /
13000
13001
Create a pipe with flags set atomically.
13002
13003
Returns a tuple of two file descriptors:
13004
  (read_fd, write_fd)
13005
13006
flags can be constructed by ORing together one or more of these values:
13007
O_NONBLOCK, O_CLOEXEC.
13008
[clinic start generated code]*/
13009
13010
static PyObject *
13011
os_pipe2_impl(PyObject *module, int flags)
13012
/*[clinic end generated code: output=25751fb43a45540f input=f261b6e7e63c6817]*/
13013
0
{
13014
0
    int fds[2];
13015
0
    int res;
13016
13017
0
    if (HAVE_PIPE2_RUNTIME) {
13018
0
        res = pipe2(fds, flags);
13019
0
    }
13020
0
    else {
13021
0
        res = -1;
13022
0
        errno = ENOSYS;
13023
0
    }
13024
0
    if (res != 0) {
13025
0
        return posix_error();
13026
0
    }
13027
13028
0
    return Py_BuildValue("(ii)", fds[0], fds[1]);
13029
0
}
13030
#endif /* HAVE_PIPE2 */
13031
13032
13033
#ifdef HAVE_WRITEV
13034
/*[clinic input]
13035
@permit_long_summary
13036
os.writev -> Py_ssize_t
13037
    fd: int
13038
    buffers: object
13039
    /
13040
13041
Iterate over buffers, and write the contents of each to a file descriptor.
13042
13043
Returns the total number of bytes written.
13044
buffers must be a sequence of bytes-like objects.
13045
[clinic start generated code]*/
13046
13047
static Py_ssize_t
13048
os_writev_impl(PyObject *module, int fd, PyObject *buffers)
13049
/*[clinic end generated code: output=56565cfac3aac15b input=5771a0f0c2b326f2]*/
13050
0
{
13051
0
    Py_ssize_t cnt;
13052
0
    Py_ssize_t result;
13053
0
    int async_err = 0;
13054
0
    struct iovec *iov;
13055
0
    Py_buffer *buf;
13056
13057
0
    if (!PySequence_Check(buffers)) {
13058
0
        PyErr_SetString(PyExc_TypeError,
13059
0
            "writev() arg 2 must be a sequence");
13060
0
        return -1;
13061
0
    }
13062
0
    cnt = PySequence_Size(buffers);
13063
0
    if (cnt < 0)
13064
0
        return -1;
13065
13066
0
    if (iov_setup(&iov, &buf, buffers, cnt, PyBUF_SIMPLE) < 0) {
13067
0
        return -1;
13068
0
    }
13069
13070
0
    do {
13071
0
        Py_BEGIN_ALLOW_THREADS
13072
0
        result = writev(fd, iov, cnt);
13073
0
        Py_END_ALLOW_THREADS
13074
0
    } while (result < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
13075
13076
0
    if (result < 0 && !async_err)
13077
0
        posix_error();
13078
13079
0
    iov_cleanup(iov, buf, cnt);
13080
0
    return result;
13081
0
}
13082
#endif /* HAVE_WRITEV */
13083
13084
13085
#ifdef HAVE_PWRITE
13086
/*[clinic input]
13087
os.pwrite -> Py_ssize_t
13088
13089
    fd: int
13090
    buffer: Py_buffer
13091
    offset: Py_off_t
13092
    /
13093
13094
Write bytes to a file descriptor starting at a particular offset.
13095
13096
Write buffer to fd, starting at offset bytes from the beginning of
13097
the file.  Returns the number of bytes written.  Does not change the
13098
current file offset.
13099
[clinic start generated code]*/
13100
13101
static Py_ssize_t
13102
os_pwrite_impl(PyObject *module, int fd, Py_buffer *buffer, Py_off_t offset)
13103
/*[clinic end generated code: output=c74da630758ee925 input=614acbc7e5a0339a]*/
13104
0
{
13105
0
    Py_ssize_t size;
13106
0
    int async_err = 0;
13107
13108
0
    do {
13109
0
        Py_BEGIN_ALLOW_THREADS
13110
0
        _Py_BEGIN_SUPPRESS_IPH
13111
0
        size = pwrite(fd, buffer->buf, (size_t)buffer->len, offset);
13112
0
        _Py_END_SUPPRESS_IPH
13113
0
        Py_END_ALLOW_THREADS
13114
0
    } while (size < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
13115
13116
0
    if (size < 0 && !async_err)
13117
0
        posix_error();
13118
0
    return size;
13119
0
}
13120
#endif /* HAVE_PWRITE */
13121
13122
#if defined(HAVE_PWRITEV) || defined (HAVE_PWRITEV2)
13123
/*[clinic input]
13124
@permit_long_summary
13125
os.pwritev -> Py_ssize_t
13126
13127
    fd: int
13128
    buffers: object
13129
    offset: Py_off_t
13130
    flags: int = 0
13131
    /
13132
13133
Writes the contents of bytes-like objects to a file descriptor at a given offset.
13134
13135
Combines the functionality of writev() and pwrite(). All buffers must be
13136
a sequence of bytes-like objects.  Buffers are processed in array order.
13137
Entire contents of first buffer is written before proceeding to second,
13138
and so on. The operating system may set a limit (sysconf() value
13139
SC_IOV_MAX) on the number of buffers that can be used.
13140
This function writes the contents of each object to the file descriptor
13141
and returns the total number of bytes written.
13142
13143
The flags argument contains a bitwise OR of zero or more of the
13144
following flags:
13145
13146
- RWF_DSYNC
13147
- RWF_SYNC
13148
- RWF_APPEND
13149
- RWF_DONTCACHE
13150
- RWF_ATOMIC
13151
- RWF_NOSIGNAL
13152
13153
Using non-zero flags requires Linux 4.7 or newer.
13154
[clinic start generated code]*/
13155
13156
static Py_ssize_t
13157
os_pwritev_impl(PyObject *module, int fd, PyObject *buffers, Py_off_t offset,
13158
                int flags)
13159
/*[clinic end generated code: output=e3dd3e9d11a6a5c7 input=c202f24f01fa66c9]*/
13160
0
{
13161
0
    Py_ssize_t cnt;
13162
0
    Py_ssize_t result;
13163
0
    int async_err = 0;
13164
0
    struct iovec *iov;
13165
0
    Py_buffer *buf;
13166
13167
0
    if (!PySequence_Check(buffers)) {
13168
0
        PyErr_SetString(PyExc_TypeError,
13169
0
            "pwritev() arg 2 must be a sequence");
13170
0
        return -1;
13171
0
    }
13172
13173
0
    cnt = PySequence_Size(buffers);
13174
0
    if (cnt < 0) {
13175
0
        return -1;
13176
0
    }
13177
13178
#ifndef HAVE_PWRITEV2
13179
    if(flags != 0) {
13180
        argument_unavailable_error("pwritev2", "flags");
13181
        return -1;
13182
    }
13183
#endif
13184
13185
0
    if (iov_setup(&iov, &buf, buffers, cnt, PyBUF_SIMPLE) < 0) {
13186
0
        return -1;
13187
0
    }
13188
0
#ifdef HAVE_PWRITEV2
13189
0
    do {
13190
0
        Py_BEGIN_ALLOW_THREADS
13191
0
        _Py_BEGIN_SUPPRESS_IPH
13192
0
        result = pwritev2(fd, iov, cnt, offset, flags);
13193
0
        _Py_END_SUPPRESS_IPH
13194
0
        Py_END_ALLOW_THREADS
13195
0
    } while (result < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
13196
#else
13197
13198
#if defined(__APPLE__) && defined(__clang__)
13199
/* This entire function will be removed from the module dict when the API
13200
 * is not available.
13201
 */
13202
#pragma clang diagnostic push
13203
#pragma clang diagnostic ignored "-Wunguarded-availability"
13204
#pragma clang diagnostic ignored "-Wunguarded-availability-new"
13205
#endif
13206
    do {
13207
        Py_BEGIN_ALLOW_THREADS
13208
        _Py_BEGIN_SUPPRESS_IPH
13209
        result = pwritev(fd, iov, cnt, offset);
13210
        _Py_END_SUPPRESS_IPH
13211
        Py_END_ALLOW_THREADS
13212
    } while (result < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
13213
13214
#if defined(__APPLE__) && defined(__clang__)
13215
#pragma clang diagnostic pop
13216
#endif
13217
13218
#endif
13219
13220
0
    if (result < 0) {
13221
0
        if (!async_err) {
13222
0
            posix_error();
13223
0
        }
13224
0
        result = -1;
13225
0
    }
13226
0
    iov_cleanup(iov, buf, cnt);
13227
13228
0
    return result;
13229
0
}
13230
#endif /* HAVE_PWRITEV */
13231
13232
#if defined(HAVE_COPY_FILE_RANGE) || \
13233
    (defined(__linux__) && defined(__NR_copy_file_range))
13234
#  define _Py_HAVE_COPY_FILE_RANGE
13235
#endif
13236
13237
#ifdef _Py_HAVE_COPY_FILE_RANGE
13238
/*[clinic input]
13239
13240
os.copy_file_range
13241
    src: int
13242
        Source file descriptor.
13243
    dst: int
13244
        Destination file descriptor.
13245
    count: Py_ssize_t(allow_negative=False)
13246
        Number of bytes to copy.
13247
    offset_src: object = None
13248
        Starting offset in src.
13249
    offset_dst: object = None
13250
        Starting offset in dst.
13251
13252
Copy count bytes from one file descriptor to another.
13253
13254
If offset_src is None, then src is read from the current position;
13255
respectively for offset_dst.
13256
[clinic start generated code]*/
13257
13258
static PyObject *
13259
os_copy_file_range_impl(PyObject *module, int src, int dst, Py_ssize_t count,
13260
                        PyObject *offset_src, PyObject *offset_dst)
13261
/*[clinic end generated code: output=1a91713a1d99fc7a input=08dacb760869b87c]*/
13262
0
{
13263
0
    off_t offset_src_val, offset_dst_val;
13264
0
    off_t *p_offset_src = NULL;
13265
0
    off_t *p_offset_dst = NULL;
13266
0
    Py_ssize_t ret;
13267
0
    int async_err = 0;
13268
    /* The flags argument is provided to allow
13269
     * for future extensions and currently must be to 0. */
13270
0
    int flags = 0;
13271
13272
13273
0
    if (offset_src != Py_None) {
13274
0
        if (!_Py_Off_t_Converter(offset_src, &offset_src_val)) {
13275
0
            return NULL;
13276
0
        }
13277
0
        p_offset_src = &offset_src_val;
13278
0
    }
13279
13280
0
    if (offset_dst != Py_None) {
13281
0
        if (!_Py_Off_t_Converter(offset_dst, &offset_dst_val)) {
13282
0
            return NULL;
13283
0
        }
13284
0
        p_offset_dst = &offset_dst_val;
13285
0
    }
13286
13287
0
    do {
13288
0
        Py_BEGIN_ALLOW_THREADS
13289
0
#ifdef HAVE_COPY_FILE_RANGE
13290
0
        ret = copy_file_range(src, p_offset_src, dst, p_offset_dst, count, flags);
13291
#else
13292
        /* Largefile support makes off_t 64-bit, as the kernel expects. */
13293
        ret = syscall(__NR_copy_file_range, src, p_offset_src, dst, p_offset_dst,
13294
                      count, flags);
13295
#endif
13296
0
        Py_END_ALLOW_THREADS
13297
0
    } while (ret < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
13298
13299
0
    if (ret < 0) {
13300
0
        return (!async_err) ? posix_error() : NULL;
13301
0
    }
13302
13303
0
    return PyLong_FromSsize_t(ret);
13304
0
}
13305
#endif /* _Py_HAVE_COPY_FILE_RANGE */
13306
13307
#if (defined(HAVE_SPLICE) && !defined(_AIX))
13308
/*[clinic input]
13309
13310
os.splice
13311
    src: int
13312
        Source file descriptor.
13313
    dst: int
13314
        Destination file descriptor.
13315
    count: Py_ssize_t(allow_negative=False)
13316
        Number of bytes to copy.
13317
    offset_src: object = None
13318
        Starting offset in src.
13319
    offset_dst: object = None
13320
        Starting offset in dst.
13321
    flags: unsigned_int = 0
13322
        Flags to modify the semantics of the call.
13323
13324
Transfer count bytes from one pipe to a descriptor or vice versa.
13325
13326
If offset_src is None, then src is read from the current position;
13327
respectively for offset_dst. The offset associated to the file
13328
descriptor that refers to a pipe must be None.
13329
[clinic start generated code]*/
13330
13331
static PyObject *
13332
os_splice_impl(PyObject *module, int src, int dst, Py_ssize_t count,
13333
               PyObject *offset_src, PyObject *offset_dst,
13334
               unsigned int flags)
13335
/*[clinic end generated code: output=d0386f25a8519dc5 input=034852a7b2e7af35]*/
13336
0
{
13337
0
    off_t offset_src_val, offset_dst_val;
13338
0
    off_t *p_offset_src = NULL;
13339
0
    off_t *p_offset_dst = NULL;
13340
0
    Py_ssize_t ret;
13341
0
    int async_err = 0;
13342
13343
13344
0
    if (offset_src != Py_None) {
13345
0
        if (!_Py_Off_t_Converter(offset_src, &offset_src_val)) {
13346
0
            return NULL;
13347
0
        }
13348
0
        p_offset_src = &offset_src_val;
13349
0
    }
13350
13351
0
    if (offset_dst != Py_None) {
13352
0
        if (!_Py_Off_t_Converter(offset_dst, &offset_dst_val)) {
13353
0
            return NULL;
13354
0
        }
13355
0
        p_offset_dst = &offset_dst_val;
13356
0
    }
13357
13358
0
    do {
13359
0
        Py_BEGIN_ALLOW_THREADS
13360
0
        ret = splice(src, p_offset_src, dst, p_offset_dst, count, flags);
13361
0
        Py_END_ALLOW_THREADS
13362
0
    } while (ret < 0 && errno == EINTR && !(async_err = PyErr_CheckSignals()));
13363
13364
0
    if (ret < 0) {
13365
0
        return (!async_err) ? posix_error() : NULL;
13366
0
    }
13367
13368
0
    return PyLong_FromSsize_t(ret);
13369
0
}
13370
#endif /* HAVE_SPLICE*/
13371
13372
#ifdef HAVE_MKFIFO
13373
/*[clinic input]
13374
os.mkfifo
13375
13376
    path: path_t
13377
    mode: int=0o666
13378
    *
13379
    dir_fd: dir_fd(requires='mkfifoat')=None
13380
13381
Create a "fifo" (a POSIX named pipe).
13382
13383
If dir_fd is not None, it should be a file descriptor open to
13384
a directory, and path should be relative; path will then be relative to
13385
that directory.
13386
dir_fd may not be implemented on your platform.  If it is unavailable,
13387
using it will raise a NotImplementedError.
13388
[clinic start generated code]*/
13389
13390
static PyObject *
13391
os_mkfifo_impl(PyObject *module, path_t *path, int mode, int dir_fd)
13392
/*[clinic end generated code: output=ce41cfad0e68c940 input=d2fb917c01e888d6]*/
13393
0
{
13394
0
    int result;
13395
0
    int async_err = 0;
13396
0
#ifdef HAVE_MKFIFOAT
13397
0
    int mkfifoat_unavailable = 0;
13398
0
#endif
13399
13400
0
    do {
13401
0
        Py_BEGIN_ALLOW_THREADS
13402
0
#ifdef HAVE_MKFIFOAT
13403
0
        if (dir_fd != DEFAULT_DIR_FD) {
13404
0
            if (HAVE_MKFIFOAT_RUNTIME) {
13405
0
                result = mkfifoat(dir_fd, path->narrow, mode);
13406
13407
0
            } else {
13408
0
                mkfifoat_unavailable = 1;
13409
0
                result = 0;
13410
0
            }
13411
0
        } else
13412
0
#endif
13413
0
            result = mkfifo(path->narrow, mode);
13414
0
        Py_END_ALLOW_THREADS
13415
0
    } while (result != 0 && errno == EINTR &&
13416
0
             !(async_err = PyErr_CheckSignals()));
13417
13418
0
#ifdef HAVE_MKFIFOAT
13419
0
    if (mkfifoat_unavailable) {
13420
0
        argument_unavailable_error(NULL, "dir_fd");
13421
0
        return NULL;
13422
0
    }
13423
0
#endif
13424
13425
0
    if (result != 0)
13426
0
        return (!async_err) ? posix_error() : NULL;
13427
13428
0
    Py_RETURN_NONE;
13429
0
}
13430
#endif /* HAVE_MKFIFO */
13431
13432
13433
#if defined(HAVE_MKNOD) && defined(HAVE_MAKEDEV)
13434
/*[clinic input]
13435
os.mknod
13436
13437
    path: path_t
13438
    mode: int=0o600
13439
    device: dev_t=0
13440
    *
13441
    dir_fd: dir_fd(requires='mknodat')=None
13442
13443
Create a node in the file system.
13444
13445
Create a node in the file system (file, device special file or named
13446
pipe) at path.  mode specifies both the permissions to use and the
13447
type of node to be created, being combined (bitwise OR) with one of
13448
S_IFREG, S_IFCHR, S_IFBLK, and S_IFIFO.  If S_IFCHR or S_IFBLK is set
13449
on mode, device defines the newly created device special file (probably
13450
using os.makedev()).  Otherwise device is ignored.
13451
13452
If dir_fd is not None, it should be a file descriptor open to
13453
a directory, and path should be relative; path will then be relative
13454
to that directory.
13455
dir_fd may not be implemented on your platform.  If it is unavailable,
13456
using it will raise a NotImplementedError.
13457
[clinic start generated code]*/
13458
13459
static PyObject *
13460
os_mknod_impl(PyObject *module, path_t *path, int mode, dev_t device,
13461
              int dir_fd)
13462
/*[clinic end generated code: output=92e55d3ca8917461 input=7d0099e85c6b4cba]*/
13463
0
{
13464
0
    int result;
13465
0
    int async_err = 0;
13466
0
#ifdef HAVE_MKNODAT
13467
0
    int mknodat_unavailable = 0;
13468
0
#endif
13469
13470
0
    do {
13471
0
        Py_BEGIN_ALLOW_THREADS
13472
0
#ifdef HAVE_MKNODAT
13473
0
        if (dir_fd != DEFAULT_DIR_FD) {
13474
0
            if (HAVE_MKNODAT_RUNTIME) {
13475
0
                result = mknodat(dir_fd, path->narrow, mode, device);
13476
13477
0
            } else {
13478
0
                mknodat_unavailable = 1;
13479
0
                result = 0;
13480
0
            }
13481
0
        } else
13482
0
#endif
13483
0
            result = mknod(path->narrow, mode, device);
13484
0
        Py_END_ALLOW_THREADS
13485
0
    } while (result != 0 && errno == EINTR &&
13486
0
             !(async_err = PyErr_CheckSignals()));
13487
0
#ifdef HAVE_MKNODAT
13488
0
    if (mknodat_unavailable) {
13489
0
        argument_unavailable_error(NULL, "dir_fd");
13490
0
        return NULL;
13491
0
    }
13492
0
#endif
13493
0
    if (result != 0)
13494
0
        return (!async_err) ? posix_error() : NULL;
13495
13496
0
    Py_RETURN_NONE;
13497
0
}
13498
#endif /* defined(HAVE_MKNOD) && defined(HAVE_MAKEDEV) */
13499
13500
13501
#ifdef HAVE_DEVICE_MACROS
13502
static PyObject *
13503
major_minor_conv(unsigned int value)
13504
0
{
13505
0
#ifdef NODEV
13506
0
    if (value == (unsigned int)NODEV) {
13507
0
        return PyLong_FromLong((int)NODEV);
13508
0
    }
13509
0
#endif
13510
0
    return PyLong_FromUnsignedLong(value);
13511
0
}
13512
13513
static int
13514
major_minor_check(dev_t value)
13515
0
{
13516
0
#ifdef NODEV
13517
0
    if (value == NODEV) {
13518
0
        return 1;
13519
0
    }
13520
0
#endif
13521
0
    return (dev_t)(unsigned int)value == value;
13522
0
}
13523
13524
/*[clinic input]
13525
os.major
13526
13527
    device: dev_t
13528
    /
13529
13530
Extracts a device major number from a raw device number.
13531
[clinic start generated code]*/
13532
13533
static PyObject *
13534
os_major_impl(PyObject *module, dev_t device)
13535
/*[clinic end generated code: output=4071ffee17647891 input=b1a0a14ec9448229]*/
13536
0
{
13537
0
    return major_minor_conv(major(device));
13538
0
}
13539
13540
13541
/*[clinic input]
13542
os.minor
13543
13544
    device: dev_t
13545
    /
13546
13547
Extracts a device minor number from a raw device number.
13548
[clinic start generated code]*/
13549
13550
static PyObject *
13551
os_minor_impl(PyObject *module, dev_t device)
13552
/*[clinic end generated code: output=306cb78e3bc5004f input=2f686e463682a9da]*/
13553
0
{
13554
0
    return major_minor_conv(minor(device));
13555
0
}
13556
13557
13558
/*[clinic input]
13559
os.makedev -> dev_t
13560
13561
    major: dev_t
13562
    minor: dev_t
13563
    /
13564
13565
Composes a raw device number from the major and minor device numbers.
13566
[clinic start generated code]*/
13567
13568
static dev_t
13569
os_makedev_impl(PyObject *module, dev_t major, dev_t minor)
13570
/*[clinic end generated code: output=cad6125c51f5af80 input=2146126ec02e55c1]*/
13571
0
{
13572
0
    if (!major_minor_check(major) || !major_minor_check(minor)) {
13573
0
        PyErr_SetString(PyExc_OverflowError,
13574
0
                        "Python int too large to convert to C unsigned int");
13575
0
        return (dev_t)-1;
13576
0
    }
13577
0
    return makedev(major, minor);
13578
0
}
13579
#endif /* HAVE_DEVICE_MACROS */
13580
13581
13582
#if defined HAVE_FTRUNCATE || defined MS_WINDOWS
13583
/*[clinic input]
13584
os.ftruncate
13585
13586
    fd: int
13587
    length: Py_off_t
13588
    /
13589
13590
Truncate a file, specified by file descriptor, to a specific length.
13591
[clinic start generated code]*/
13592
13593
static PyObject *
13594
os_ftruncate_impl(PyObject *module, int fd, Py_off_t length)
13595
/*[clinic end generated code: output=fba15523721be7e4 input=63b43641e52818f2]*/
13596
0
{
13597
0
    int result;
13598
0
    int async_err = 0;
13599
13600
0
    if (PySys_Audit("os.truncate", "in", fd, length) < 0) {
13601
0
        return NULL;
13602
0
    }
13603
13604
0
    do {
13605
0
        Py_BEGIN_ALLOW_THREADS
13606
0
        _Py_BEGIN_SUPPRESS_IPH
13607
#ifdef MS_WINDOWS
13608
        result = _chsize_s(fd, length);
13609
#else
13610
0
        result = ftruncate(fd, length);
13611
0
#endif
13612
0
        _Py_END_SUPPRESS_IPH
13613
0
        Py_END_ALLOW_THREADS
13614
0
    } while (result != 0 && errno == EINTR &&
13615
0
             !(async_err = PyErr_CheckSignals()));
13616
0
    if (result != 0)
13617
0
        return (!async_err) ? posix_error() : NULL;
13618
0
    Py_RETURN_NONE;
13619
0
}
13620
#endif /* HAVE_FTRUNCATE || MS_WINDOWS */
13621
13622
13623
#if defined HAVE_TRUNCATE || defined MS_WINDOWS
13624
/*[clinic input]
13625
os.truncate
13626
    path: path_t(allow_fd='PATH_HAVE_FTRUNCATE')
13627
    length: Py_off_t
13628
13629
Truncate a file, specified by path, to a specific length.
13630
13631
On some platforms, path may also be specified as an open file
13632
descriptor.  If this functionality is unavailable, using it raises
13633
an exception.
13634
[clinic start generated code]*/
13635
13636
static PyObject *
13637
os_truncate_impl(PyObject *module, path_t *path, Py_off_t length)
13638
/*[clinic end generated code: output=43009c8df5c0a12b input=ce33fd7808a511c4]*/
13639
0
{
13640
0
    int result;
13641
#ifdef MS_WINDOWS
13642
    int fd;
13643
#endif
13644
13645
0
    if (path->is_fd)
13646
0
        return os_ftruncate_impl(module, path->fd, length);
13647
13648
0
    if (PySys_Audit("os.truncate", "On", path->object, length) < 0) {
13649
0
        return NULL;
13650
0
    }
13651
13652
0
    Py_BEGIN_ALLOW_THREADS
13653
0
    _Py_BEGIN_SUPPRESS_IPH
13654
#ifdef MS_WINDOWS
13655
    fd = _wopen(path->wide, _O_WRONLY | _O_BINARY | _O_NOINHERIT);
13656
    if (fd < 0)
13657
        result = -1;
13658
    else {
13659
        result = _chsize_s(fd, length);
13660
        close(fd);
13661
        if (result < 0)
13662
            errno = result;
13663
    }
13664
#else
13665
0
    result = truncate(path->narrow, length);
13666
0
#endif
13667
0
    _Py_END_SUPPRESS_IPH
13668
0
    Py_END_ALLOW_THREADS
13669
0
    if (result < 0)
13670
0
        return posix_path_error(path);
13671
13672
0
    Py_RETURN_NONE;
13673
0
}
13674
#endif /* HAVE_TRUNCATE || MS_WINDOWS */
13675
13676
13677
/* GH-111804: Due to posix_fallocate() not having consistent semantics across
13678
   OSs, support was dropped in WASI preview2. */
13679
#if defined(HAVE_POSIX_FALLOCATE) && !defined(__wasi__)
13680
/*[clinic input]
13681
@permit_long_summary
13682
os.posix_fallocate
13683
13684
    fd: int
13685
    offset: Py_off_t
13686
    length: Py_off_t
13687
    /
13688
13689
Ensure a file has allocated at least a particular number of bytes on disk.
13690
13691
Ensure that the file specified by fd encompasses a range of bytes
13692
starting at offset bytes from the beginning and continuing for length
13693
bytes.
13694
[clinic start generated code]*/
13695
13696
static PyObject *
13697
os_posix_fallocate_impl(PyObject *module, int fd, Py_off_t offset,
13698
                        Py_off_t length)
13699
/*[clinic end generated code: output=73f107139564aa9d input=c718971d18b96896]*/
13700
0
{
13701
0
    int result;
13702
0
    int async_err = 0;
13703
13704
0
    do {
13705
0
        Py_BEGIN_ALLOW_THREADS
13706
0
        result = posix_fallocate(fd, offset, length);
13707
0
        Py_END_ALLOW_THREADS
13708
        // DragonFly BSD returns -1 and sets errno.
13709
0
        if (result == -1) {
13710
0
            result = errno;
13711
0
        }
13712
0
    } while (result == EINTR && !(async_err = PyErr_CheckSignals()));
13713
13714
0
    if (result == 0)
13715
0
        Py_RETURN_NONE;
13716
13717
0
    if (async_err)
13718
0
        return NULL;
13719
13720
0
    errno = result;
13721
0
    return posix_error();
13722
0
}
13723
#endif /* HAVE_POSIX_FALLOCATE && !defined(__wasi__) */
13724
13725
13726
#if defined(HAVE_POSIX_FADVISE)
13727
/*[clinic input]
13728
os.posix_fadvise
13729
13730
    fd: int
13731
    offset: Py_off_t
13732
    length: Py_off_t
13733
    advice: int
13734
    /
13735
13736
Announce an intention to access data in a specific pattern.
13737
13738
Announce an intention to access data in a specific pattern, thus
13739
allowing the kernel to make optimizations.
13740
The advice applies to the region of the file specified by fd starting at
13741
offset and continuing for length bytes.
13742
advice is one of POSIX_FADV_NORMAL, POSIX_FADV_SEQUENTIAL,
13743
POSIX_FADV_RANDOM, POSIX_FADV_NOREUSE, POSIX_FADV_WILLNEED, or
13744
POSIX_FADV_DONTNEED.
13745
[clinic start generated code]*/
13746
13747
static PyObject *
13748
os_posix_fadvise_impl(PyObject *module, int fd, Py_off_t offset,
13749
                      Py_off_t length, int advice)
13750
/*[clinic end generated code: output=412ef4aa70c98642 input=961b01a4518ef727]*/
13751
0
{
13752
0
    int result;
13753
0
    int async_err = 0;
13754
13755
0
    do {
13756
0
        Py_BEGIN_ALLOW_THREADS
13757
0
        result = posix_fadvise(fd, offset, length, advice);
13758
0
        Py_END_ALLOW_THREADS
13759
        // DragonFly BSD returns -1 and sets errno.
13760
0
        if (result == -1) {
13761
0
            result = errno;
13762
0
        }
13763
0
    } while (result == EINTR && !(async_err = PyErr_CheckSignals()));
13764
13765
0
    if (result == 0)
13766
0
        Py_RETURN_NONE;
13767
13768
0
    if (async_err)
13769
0
        return NULL;
13770
13771
0
    errno = result;
13772
0
    return posix_error();
13773
0
}
13774
#endif /* HAVE_POSIX_FADVISE */
13775
13776
13777
#ifdef MS_WINDOWS
13778
static PyObject*
13779
win32_putenv(PyObject *name, PyObject *value)
13780
{
13781
    /* Search from index 1 because on Windows starting '=' is allowed for
13782
       defining hidden environment variables. */
13783
    if (PyUnicode_GET_LENGTH(name) == 0 ||
13784
        PyUnicode_FindChar(name, '=', 1, PyUnicode_GET_LENGTH(name), 1) != -1)
13785
    {
13786
        PyErr_SetString(PyExc_ValueError, "illegal environment variable name");
13787
        return NULL;
13788
    }
13789
    PyObject *unicode;
13790
    if (value != NULL) {
13791
        unicode = PyUnicode_FromFormat("%U=%U", name, value);
13792
    }
13793
    else {
13794
        unicode = PyUnicode_FromFormat("%U=", name);
13795
    }
13796
    if (unicode == NULL) {
13797
        return NULL;
13798
    }
13799
13800
    Py_ssize_t size;
13801
    wchar_t *env = PyUnicode_AsWideCharString(unicode, &size);
13802
    Py_DECREF(unicode);
13803
13804
    if (env == NULL) {
13805
        return NULL;
13806
    }
13807
    if (size > _MAX_ENV) {
13808
        PyErr_Format(PyExc_ValueError,
13809
                     "the environment variable is longer than %u characters",
13810
                     _MAX_ENV);
13811
        PyMem_Free(env);
13812
        return NULL;
13813
    }
13814
    if (wcslen(env) != (size_t)size) {
13815
        PyErr_SetString(PyExc_ValueError,
13816
                        "embedded null character");
13817
        PyMem_Free(env);
13818
        return NULL;
13819
    }
13820
13821
    /* _wputenv() and SetEnvironmentVariableW() update the environment in the
13822
       Process Environment Block (PEB). _wputenv() also updates CRT 'environ'
13823
       and '_wenviron' variables, whereas SetEnvironmentVariableW() does not.
13824
13825
       Prefer _wputenv() to be compatible with C libraries using CRT
13826
       variables and CRT functions using these variables (ex: getenv()). */
13827
    int err = _wputenv(env);
13828
13829
    if (err) {
13830
        posix_error();
13831
        PyMem_Free(env);
13832
        return NULL;
13833
    }
13834
    PyMem_Free(env);
13835
13836
    Py_RETURN_NONE;
13837
}
13838
#endif
13839
13840
13841
#ifdef MS_WINDOWS
13842
/*[clinic input]
13843
os.putenv
13844
13845
    name: unicode
13846
    value: unicode
13847
    /
13848
13849
Change or add an environment variable.
13850
[clinic start generated code]*/
13851
13852
static PyObject *
13853
os_putenv_impl(PyObject *module, PyObject *name, PyObject *value)
13854
/*[clinic end generated code: output=d29a567d6b2327d2 input=ba586581c2e6105f]*/
13855
{
13856
    if (PySys_Audit("os.putenv", "OO", name, value) < 0) {
13857
        return NULL;
13858
    }
13859
    return win32_putenv(name, value);
13860
}
13861
#else
13862
/*[clinic input]
13863
os.putenv
13864
13865
    name: unicode_fs_encoded
13866
    value: unicode_fs_encoded
13867
    /
13868
13869
Change or add an environment variable.
13870
[clinic start generated code]*/
13871
13872
static PyObject *
13873
os_putenv_impl(PyObject *module, PyObject *name, PyObject *value)
13874
/*[clinic end generated code: output=d29a567d6b2327d2 input=84fcd30f873c8c45]*/
13875
0
{
13876
0
    const char *name_string = PyBytes_AS_STRING(name);
13877
0
    const char *value_string = PyBytes_AS_STRING(value);
13878
13879
0
    if (strchr(name_string, '=') != NULL) {
13880
0
        PyErr_SetString(PyExc_ValueError, "illegal environment variable name");
13881
0
        return NULL;
13882
0
    }
13883
13884
0
    if (PySys_Audit("os.putenv", "OO", name, value) < 0) {
13885
0
        return NULL;
13886
0
    }
13887
13888
0
    if (setenv(name_string, value_string, 1)) {
13889
0
        return posix_error();
13890
0
    }
13891
0
    Py_RETURN_NONE;
13892
0
}
13893
#endif  /* !defined(MS_WINDOWS) */
13894
13895
13896
#ifdef MS_WINDOWS
13897
/*[clinic input]
13898
os.unsetenv
13899
    name: unicode
13900
    /
13901
13902
Delete an environment variable.
13903
[clinic start generated code]*/
13904
13905
static PyObject *
13906
os_unsetenv_impl(PyObject *module, PyObject *name)
13907
/*[clinic end generated code: output=54c4137ab1834f02 input=4d6a1747cc526d2f]*/
13908
{
13909
    if (PySys_Audit("os.unsetenv", "(O)", name) < 0) {
13910
        return NULL;
13911
    }
13912
    return win32_putenv(name, NULL);
13913
}
13914
#else
13915
/*[clinic input]
13916
os.unsetenv
13917
    name: unicode_fs_encoded
13918
    /
13919
13920
Delete an environment variable.
13921
[clinic start generated code]*/
13922
13923
static PyObject *
13924
os_unsetenv_impl(PyObject *module, PyObject *name)
13925
/*[clinic end generated code: output=54c4137ab1834f02 input=78ff12e505ade80a]*/
13926
0
{
13927
0
    if (PySys_Audit("os.unsetenv", "(O)", name) < 0) {
13928
0
        return NULL;
13929
0
    }
13930
#ifdef HAVE_BROKEN_UNSETENV
13931
    unsetenv(PyBytes_AS_STRING(name));
13932
#else
13933
0
    int err = unsetenv(PyBytes_AS_STRING(name));
13934
0
    if (err) {
13935
0
        return posix_error();
13936
0
    }
13937
0
#endif
13938
13939
0
    Py_RETURN_NONE;
13940
0
}
13941
#endif /* !MS_WINDOWS */
13942
13943
13944
#ifdef HAVE_CLEARENV
13945
/*[clinic input]
13946
os._clearenv
13947
[clinic start generated code]*/
13948
13949
static PyObject *
13950
os__clearenv_impl(PyObject *module)
13951
/*[clinic end generated code: output=2d6705d62c014b51 input=47d2fa7f323c43ca]*/
13952
0
{
13953
0
    if (PySys_Audit("os._clearenv", NULL) < 0) {
13954
0
        return NULL;
13955
0
    }
13956
13957
0
    errno = 0;
13958
0
    int err = clearenv();
13959
0
    if (err) {
13960
0
        return posix_error();
13961
0
    }
13962
0
    Py_RETURN_NONE;
13963
0
}
13964
#endif
13965
13966
13967
/*[clinic input]
13968
os.strerror
13969
13970
    code: int
13971
    /
13972
13973
Translate an error code to a message string.
13974
[clinic start generated code]*/
13975
13976
static PyObject *
13977
os_strerror_impl(PyObject *module, int code)
13978
/*[clinic end generated code: output=baebf09fa02a78f2 input=75a8673d97915a91]*/
13979
0
{
13980
0
    return _Py_strerror(code);
13981
0
}
13982
13983
13984
#ifdef HAVE_SYS_WAIT_H
13985
#ifdef WCOREDUMP
13986
/*[clinic input]
13987
os.WCOREDUMP -> bool
13988
13989
    status: int
13990
    /
13991
13992
Return True if the process returning status was dumped to a core file.
13993
[clinic start generated code]*/
13994
13995
static int
13996
os_WCOREDUMP_impl(PyObject *module, int status)
13997
/*[clinic end generated code: output=1a584b147b16bd18 input=8b05e7ab38528d04]*/
13998
0
{
13999
0
    WAIT_TYPE wait_status;
14000
0
    WAIT_STATUS_INT(wait_status) = status;
14001
0
    return WCOREDUMP(wait_status);
14002
0
}
14003
#endif /* WCOREDUMP */
14004
14005
14006
#ifdef WIFCONTINUED
14007
/*[clinic input]
14008
@permit_long_summary
14009
os.WIFCONTINUED -> bool
14010
14011
    status: int
14012
14013
Return True if a particular process was continued from a job control stop.
14014
14015
Return True if the process returning status was continued from a
14016
job control stop.
14017
[clinic start generated code]*/
14018
14019
static int
14020
os_WIFCONTINUED_impl(PyObject *module, int status)
14021
/*[clinic end generated code: output=1e35295d844364bd input=7b577845a0f8b12f]*/
14022
0
{
14023
0
    WAIT_TYPE wait_status;
14024
0
    WAIT_STATUS_INT(wait_status) = status;
14025
0
    return WIFCONTINUED(wait_status);
14026
0
}
14027
#endif /* WIFCONTINUED */
14028
14029
14030
#ifdef WIFSTOPPED
14031
/*[clinic input]
14032
os.WIFSTOPPED -> bool
14033
14034
    status: int
14035
14036
Return True if the process returning status was stopped.
14037
[clinic start generated code]*/
14038
14039
static int
14040
os_WIFSTOPPED_impl(PyObject *module, int status)
14041
/*[clinic end generated code: output=fdb57122a5c9b4cb input=043cb7f1289ef904]*/
14042
0
{
14043
0
    WAIT_TYPE wait_status;
14044
0
    WAIT_STATUS_INT(wait_status) = status;
14045
0
    return WIFSTOPPED(wait_status);
14046
0
}
14047
#endif /* WIFSTOPPED */
14048
14049
14050
#ifdef WIFSIGNALED
14051
/*[clinic input]
14052
os.WIFSIGNALED -> bool
14053
14054
    status: int
14055
14056
Return True if the process returning status was terminated by a signal.
14057
[clinic start generated code]*/
14058
14059
static int
14060
os_WIFSIGNALED_impl(PyObject *module, int status)
14061
/*[clinic end generated code: output=d1dde4dcc819a5f5 input=d55ba7cc9ce5dc43]*/
14062
0
{
14063
0
    WAIT_TYPE wait_status;
14064
0
    WAIT_STATUS_INT(wait_status) = status;
14065
0
    return WIFSIGNALED(wait_status);
14066
0
}
14067
#endif /* WIFSIGNALED */
14068
14069
14070
#ifdef WIFEXITED
14071
/*[clinic input]
14072
@permit_long_summary
14073
os.WIFEXITED -> bool
14074
14075
    status: int
14076
14077
Return True if the process returning status exited via the exit() system call.
14078
[clinic start generated code]*/
14079
14080
static int
14081
os_WIFEXITED_impl(PyObject *module, int status)
14082
/*[clinic end generated code: output=01c09d6ebfeea397 input=8c24a82148709b30]*/
14083
0
{
14084
0
    WAIT_TYPE wait_status;
14085
0
    WAIT_STATUS_INT(wait_status) = status;
14086
0
    return WIFEXITED(wait_status);
14087
0
}
14088
#endif /* WIFEXITED */
14089
14090
14091
#ifdef WEXITSTATUS
14092
/*[clinic input]
14093
os.WEXITSTATUS -> int
14094
14095
    status: int
14096
14097
Return the process return code from status.
14098
[clinic start generated code]*/
14099
14100
static int
14101
os_WEXITSTATUS_impl(PyObject *module, int status)
14102
/*[clinic end generated code: output=6e3efbba11f6488d input=e1fb4944e377585b]*/
14103
0
{
14104
0
    WAIT_TYPE wait_status;
14105
0
    WAIT_STATUS_INT(wait_status) = status;
14106
0
    return WEXITSTATUS(wait_status);
14107
0
}
14108
#endif /* WEXITSTATUS */
14109
14110
14111
#ifdef WTERMSIG
14112
/*[clinic input]
14113
@permit_long_summary
14114
os.WTERMSIG -> int
14115
14116
    status: int
14117
14118
Return the signal that terminated the process that provided the status value.
14119
[clinic start generated code]*/
14120
14121
static int
14122
os_WTERMSIG_impl(PyObject *module, int status)
14123
/*[clinic end generated code: output=172f7dfc8dcfc3ad input=89072f6cbf3f8050]*/
14124
0
{
14125
0
    WAIT_TYPE wait_status;
14126
0
    WAIT_STATUS_INT(wait_status) = status;
14127
0
    return WTERMSIG(wait_status);
14128
0
}
14129
#endif /* WTERMSIG */
14130
14131
14132
#ifdef WSTOPSIG
14133
/*[clinic input]
14134
@permit_long_summary
14135
os.WSTOPSIG -> int
14136
14137
    status: int
14138
14139
Return the signal that stopped the process that provided the status value.
14140
[clinic start generated code]*/
14141
14142
static int
14143
os_WSTOPSIG_impl(PyObject *module, int status)
14144
/*[clinic end generated code: output=0ab7586396f5d82b input=4698db1a6a320433]*/
14145
0
{
14146
0
    WAIT_TYPE wait_status;
14147
0
    WAIT_STATUS_INT(wait_status) = status;
14148
0
    return WSTOPSIG(wait_status);
14149
0
}
14150
#endif /* WSTOPSIG */
14151
#endif /* HAVE_SYS_WAIT_H */
14152
14153
14154
#if defined(HAVE_FSTATVFS) && defined(HAVE_SYS_STATVFS_H)
14155
#include <sys/statvfs.h>
14156
14157
#ifdef __APPLE__
14158
/* On macOS struct statvfs uses 32-bit integers for block counts,
14159
 * resulting in overflow when filesystems are larger than 4TB. Therefore
14160
 * os.statvfs is implemented in terms of statfs(2).
14161
 */
14162
14163
static PyObject*
14164
_pystatvfs_fromstructstatfs(PyObject *module, struct statfs st) {
14165
    PyObject *StatVFSResultType = get_posix_state(module)->StatVFSResultType;
14166
    PyObject *v = PyStructSequence_New((PyTypeObject *)StatVFSResultType);
14167
    if (v == NULL) {
14168
        return NULL;
14169
    }
14170
14171
    long flags = 0;
14172
    if (st.f_flags & MNT_RDONLY) {
14173
        flags |= ST_RDONLY;
14174
    }
14175
    if (st.f_flags & MNT_NOSUID) {
14176
        flags |= ST_NOSUID;
14177
    }
14178
14179
    _Static_assert(sizeof(st.f_blocks) == sizeof(long long), "assuming large file");
14180
14181
#define SET_ITEM(SEQ, INDEX, EXPR)                       \
14182
    do {                                                 \
14183
        PyObject *obj = (EXPR);                          \
14184
        if (obj == NULL) {                               \
14185
            Py_DECREF((SEQ));                            \
14186
            return NULL;                                 \
14187
        }                                                \
14188
        PyStructSequence_SET_ITEM((SEQ), (INDEX), obj);  \
14189
    } while (0)
14190
14191
    SET_ITEM(v, 0, PyLong_FromLong((long) st.f_iosize));
14192
    SET_ITEM(v, 1, PyLong_FromLong((long) st.f_bsize));
14193
    SET_ITEM(v, 2, PyLong_FromLongLong((long long) st.f_blocks));
14194
    SET_ITEM(v, 3, PyLong_FromLongLong((long long) st.f_bfree));
14195
    SET_ITEM(v, 4, PyLong_FromLongLong((long long) st.f_bavail));
14196
    SET_ITEM(v, 5, PyLong_FromLongLong((long long) st.f_files));
14197
    SET_ITEM(v, 6, PyLong_FromLongLong((long long) st.f_ffree));
14198
    SET_ITEM(v, 7, PyLong_FromLongLong((long long) st.f_ffree));
14199
    SET_ITEM(v, 8, PyLong_FromLong((long) flags));
14200
14201
    SET_ITEM(v, 9, PyLong_FromLong((long) NAME_MAX));
14202
    SET_ITEM(v, 10, PyLong_FromUnsignedLong(st.f_fsid.val[0]));
14203
14204
#undef SET_ITEM
14205
14206
    return v;
14207
}
14208
14209
#else
14210
14211
14212
14213
static PyObject*
14214
0
_pystatvfs_fromstructstatvfs(PyObject *module, struct statvfs st) {
14215
0
    PyObject *StatVFSResultType = get_posix_state(module)->StatVFSResultType;
14216
0
    PyObject *v = PyStructSequence_New((PyTypeObject *)StatVFSResultType);
14217
0
    if (v == NULL)
14218
0
        return NULL;
14219
14220
0
    int pos = 0;
14221
14222
0
#define SET_RESULT(CALL)                                     \
14223
0
    do {                                                     \
14224
0
        PyObject *item = (CALL);                             \
14225
0
        if (item == NULL) {                                  \
14226
0
            Py_DECREF(v);                                    \
14227
0
            return NULL;                                     \
14228
0
        }                                                    \
14229
0
        PyStructSequence_SET_ITEM(v, pos++, item);           \
14230
0
    } while(0)
14231
14232
0
#if !defined(HAVE_LARGEFILE_SUPPORT)
14233
0
    SET_RESULT(PyLong_FromLong((long) st.f_bsize));
14234
0
    SET_RESULT(PyLong_FromLong((long) st.f_frsize));
14235
0
    SET_RESULT(PyLong_FromLong((long) st.f_blocks));
14236
0
    SET_RESULT(PyLong_FromLong((long) st.f_bfree));
14237
0
    SET_RESULT(PyLong_FromLong((long) st.f_bavail));
14238
0
    SET_RESULT(PyLong_FromLong((long) st.f_files));
14239
0
    SET_RESULT(PyLong_FromLong((long) st.f_ffree));
14240
0
    SET_RESULT(PyLong_FromLong((long) st.f_favail));
14241
0
    SET_RESULT(PyLong_FromLong((long) st.f_flag));
14242
0
    SET_RESULT(PyLong_FromLong((long) st.f_namemax));
14243
#else
14244
    SET_RESULT(PyLong_FromLong((long) st.f_bsize));
14245
    SET_RESULT(PyLong_FromLong((long) st.f_frsize));
14246
    SET_RESULT(PyLong_FromLongLong((long long) st.f_blocks));
14247
    SET_RESULT(PyLong_FromLongLong((long long) st.f_bfree));
14248
    SET_RESULT(PyLong_FromLongLong((long long) st.f_bavail));
14249
    SET_RESULT(PyLong_FromLongLong((long long) st.f_files));
14250
    SET_RESULT(PyLong_FromLongLong((long long) st.f_ffree));
14251
    SET_RESULT(PyLong_FromLongLong((long long) st.f_favail));
14252
    SET_RESULT(PyLong_FromLong((long) st.f_flag));
14253
    SET_RESULT(PyLong_FromLong((long) st.f_namemax));
14254
#endif
14255
/* The _ALL_SOURCE feature test macro defines f_fsid as a structure
14256
 * (issue #32390). */
14257
#if defined(_AIX) && defined(_ALL_SOURCE)
14258
    SET_RESULT(PyLong_FromUnsignedLong(st.f_fsid.val[0]));
14259
#else
14260
0
    SET_RESULT(PyLong_FromUnsignedLong(st.f_fsid));
14261
0
#endif
14262
14263
0
#undef SET_RESULT
14264
14265
0
    return v;
14266
0
}
14267
14268
#endif
14269
14270
14271
/*[clinic input]
14272
os.fstatvfs
14273
    fd: int
14274
    /
14275
14276
Perform an fstatvfs system call on the given fd.
14277
14278
Equivalent to statvfs(fd).
14279
[clinic start generated code]*/
14280
14281
static PyObject *
14282
os_fstatvfs_impl(PyObject *module, int fd)
14283
/*[clinic end generated code: output=53547cf0cc55e6c5 input=d8122243ac50975e]*/
14284
0
{
14285
0
    int result;
14286
0
    int async_err = 0;
14287
#ifdef __APPLE__
14288
    struct statfs st;
14289
    /* On macOS os.fstatvfs is implemented using fstatfs(2) because
14290
     * the former uses 32-bit values for block counts.
14291
     */
14292
    do {
14293
        Py_BEGIN_ALLOW_THREADS
14294
        result = fstatfs(fd, &st);
14295
        Py_END_ALLOW_THREADS
14296
    } while (result != 0 && errno == EINTR &&
14297
             !(async_err = PyErr_CheckSignals()));
14298
    if (result != 0)
14299
        return (!async_err) ? posix_error() : NULL;
14300
14301
    return _pystatvfs_fromstructstatfs(module, st);
14302
#else
14303
0
    struct statvfs st;
14304
14305
0
    do {
14306
0
        Py_BEGIN_ALLOW_THREADS
14307
0
        result = fstatvfs(fd, &st);
14308
0
        Py_END_ALLOW_THREADS
14309
0
    } while (result != 0 && errno == EINTR &&
14310
0
             !(async_err = PyErr_CheckSignals()));
14311
0
    if (result != 0)
14312
0
        return (!async_err) ? posix_error() : NULL;
14313
14314
0
    return _pystatvfs_fromstructstatvfs(module, st);
14315
0
#endif
14316
0
}
14317
#endif /* defined(HAVE_FSTATVFS) && defined(HAVE_SYS_STATVFS_H) */
14318
14319
14320
#if defined(HAVE_STATVFS) && defined(HAVE_SYS_STATVFS_H)
14321
#include <sys/statvfs.h>
14322
/*[clinic input]
14323
os.statvfs
14324
14325
    path: path_t(allow_fd='PATH_HAVE_FSTATVFS')
14326
14327
Perform a statvfs system call on the given path.
14328
14329
path may always be specified as a string.
14330
On some platforms, path may also be specified as an open file
14331
descriptor.  If this functionality is unavailable, using it raises
14332
an exception.
14333
[clinic start generated code]*/
14334
14335
static PyObject *
14336
os_statvfs_impl(PyObject *module, path_t *path)
14337
/*[clinic end generated code: output=87106dd1beb8556e input=1cfd9a4fd36f7425]*/
14338
0
{
14339
0
    int result;
14340
14341
#ifdef __APPLE__
14342
    /* On macOS os.statvfs is implemented using statfs(2)/fstatfs(2) because
14343
     * the former uses 32-bit values for block counts.
14344
     */
14345
    struct statfs st;
14346
14347
    Py_BEGIN_ALLOW_THREADS
14348
    if (path->is_fd) {
14349
        result = fstatfs(path->fd, &st);
14350
    }
14351
    else
14352
        result = statfs(path->narrow, &st);
14353
    Py_END_ALLOW_THREADS
14354
14355
    if (result) {
14356
        return path_error(path);
14357
    }
14358
14359
    return _pystatvfs_fromstructstatfs(module, st);
14360
14361
#else
14362
0
    struct statvfs st;
14363
14364
0
    Py_BEGIN_ALLOW_THREADS
14365
0
#ifdef HAVE_FSTATVFS
14366
0
    if (path->is_fd) {
14367
0
        result = fstatvfs(path->fd, &st);
14368
0
    }
14369
0
    else
14370
0
#endif
14371
0
        result = statvfs(path->narrow, &st);
14372
0
    Py_END_ALLOW_THREADS
14373
14374
0
    if (result) {
14375
0
        return path_error(path);
14376
0
    }
14377
14378
0
    return _pystatvfs_fromstructstatvfs(module, st);
14379
0
#endif
14380
0
}
14381
#endif /* defined(HAVE_STATVFS) && defined(HAVE_SYS_STATVFS_H) */
14382
14383
14384
#ifdef MS_WINDOWS
14385
/*[clinic input]
14386
@permit_long_summary
14387
os._getdiskusage
14388
14389
    path: path_t
14390
14391
Return disk usage statistics about the given path as a (total, free) tuple.
14392
[clinic start generated code]*/
14393
14394
static PyObject *
14395
os__getdiskusage_impl(PyObject *module, path_t *path)
14396
/*[clinic end generated code: output=3bd3991f5e5c5dfb input=aee7e38bc3e7fb08]*/
14397
{
14398
    BOOL retval;
14399
    ULARGE_INTEGER _, total, free;
14400
    DWORD err = 0;
14401
14402
    Py_BEGIN_ALLOW_THREADS
14403
    retval = GetDiskFreeSpaceExW(path->wide, &_, &total, &free);
14404
    Py_END_ALLOW_THREADS
14405
    if (retval == 0) {
14406
        if (GetLastError() == ERROR_DIRECTORY) {
14407
            wchar_t *dir_path = NULL;
14408
14409
            dir_path = PyMem_New(wchar_t, path->length + 1);
14410
            if (dir_path == NULL) {
14411
                return PyErr_NoMemory();
14412
            }
14413
14414
            wcscpy_s(dir_path, path->length + 1, path->wide);
14415
14416
            if (_dirnameW(dir_path) != -1) {
14417
                Py_BEGIN_ALLOW_THREADS
14418
                retval = GetDiskFreeSpaceExW(dir_path, &_, &total, &free);
14419
                Py_END_ALLOW_THREADS
14420
            }
14421
            /* Record the last error in case it's modified by PyMem_Free. */
14422
            err = GetLastError();
14423
            PyMem_Free(dir_path);
14424
            if (retval) {
14425
                goto success;
14426
            }
14427
        }
14428
        return PyErr_SetFromWindowsErr(err);
14429
    }
14430
14431
success:
14432
    return Py_BuildValue("(LL)", total.QuadPart, free.QuadPart);
14433
}
14434
#endif /* MS_WINDOWS */
14435
14436
14437
/* This is used for fpathconf(), pathconf(), confstr() and sysconf().
14438
 * It maps strings representing configuration variable names to
14439
 * integer values, allowing those functions to be called with the
14440
 * magic names instead of polluting the module's namespace with tons of
14441
 * rarely-used constants.  There are three separate tables that use
14442
 * these definitions.
14443
 *
14444
 * This code is always included, even if none of the interfaces that
14445
 * need it are included.  The #if hackery needed to avoid it would be
14446
 * sufficiently pervasive that it's not worth the loss of readability.
14447
 */
14448
struct constdef {
14449
    const char *name;
14450
    int value;
14451
};
14452
14453
static int
14454
conv_confname(PyObject *module, PyObject *arg, int *valuep, const char *tablename)
14455
4
{
14456
4
    if (PyUnicode_Check(arg)) {
14457
4
        PyObject *table = PyObject_GetAttrString(module, tablename);
14458
4
        if (table == NULL) {
14459
0
            return 0;
14460
0
        }
14461
14462
4
        arg = PyObject_GetItem(table, arg);
14463
4
        Py_DECREF(table);
14464
4
        if (arg == NULL) {
14465
0
            PyErr_SetString(
14466
0
                PyExc_ValueError, "unrecognized configuration name");
14467
0
            return 0;
14468
0
        }
14469
4
    } else {
14470
0
        Py_INCREF(arg);  // Match the Py_DECREF below.
14471
0
    }
14472
14473
4
    int success = 0;
14474
4
    if (!PyIndex_Check(arg)) {
14475
0
        PyErr_SetString(PyExc_TypeError,
14476
0
            "configuration names must be strings or integers");
14477
4
    } else {
14478
4
        int value = PyLong_AsInt(arg);
14479
4
        if (!(value == -1 && PyErr_Occurred())) {
14480
4
            *valuep = value;
14481
4
            success = 1;
14482
4
        }
14483
4
    }
14484
4
    Py_DECREF(arg);
14485
4
    return success;
14486
4
}
14487
14488
14489
#if defined(HAVE_FPATHCONF) || defined(HAVE_PATHCONF)
14490
static struct constdef  posix_constants_pathconf[] = {
14491
#ifdef _PC_ABI_AIO_XFER_MAX
14492
    {"PC_ABI_AIO_XFER_MAX",     _PC_ABI_AIO_XFER_MAX},
14493
#endif
14494
#ifdef _PC_ABI_ASYNC_IO
14495
    {"PC_ABI_ASYNC_IO", _PC_ABI_ASYNC_IO},
14496
#endif
14497
#ifdef _PC_ASYNC_IO
14498
    {"PC_ASYNC_IO",     _PC_ASYNC_IO},
14499
#endif
14500
#ifdef _PC_CHOWN_RESTRICTED
14501
    {"PC_CHOWN_RESTRICTED",     _PC_CHOWN_RESTRICTED},
14502
#endif
14503
#ifdef _PC_FILESIZEBITS
14504
    {"PC_FILESIZEBITS", _PC_FILESIZEBITS},
14505
#endif
14506
#ifdef _PC_LAST
14507
    {"PC_LAST", _PC_LAST},
14508
#endif
14509
#ifdef _PC_LINK_MAX
14510
    {"PC_LINK_MAX",     _PC_LINK_MAX},
14511
#endif
14512
#ifdef _PC_MAX_CANON
14513
    {"PC_MAX_CANON",    _PC_MAX_CANON},
14514
#endif
14515
#ifdef _PC_MAX_INPUT
14516
    {"PC_MAX_INPUT",    _PC_MAX_INPUT},
14517
#endif
14518
#ifdef _PC_NAME_MAX
14519
    {"PC_NAME_MAX",     _PC_NAME_MAX},
14520
#endif
14521
#ifdef _PC_NO_TRUNC
14522
    {"PC_NO_TRUNC",     _PC_NO_TRUNC},
14523
#endif
14524
#ifdef _PC_PATH_MAX
14525
    {"PC_PATH_MAX",     _PC_PATH_MAX},
14526
#endif
14527
#ifdef _PC_PIPE_BUF
14528
    {"PC_PIPE_BUF",     _PC_PIPE_BUF},
14529
#endif
14530
#ifdef _PC_PRIO_IO
14531
    {"PC_PRIO_IO",      _PC_PRIO_IO},
14532
#endif
14533
#ifdef _PC_SOCK_MAXBUF
14534
    {"PC_SOCK_MAXBUF",  _PC_SOCK_MAXBUF},
14535
#endif
14536
#ifdef _PC_SYNC_IO
14537
    {"PC_SYNC_IO",      _PC_SYNC_IO},
14538
#endif
14539
#ifdef _PC_VDISABLE
14540
    {"PC_VDISABLE",     _PC_VDISABLE},
14541
#endif
14542
#ifdef _PC_ACL_ENABLED
14543
    {"PC_ACL_ENABLED",  _PC_ACL_ENABLED},
14544
#endif
14545
#ifdef _PC_MIN_HOLE_SIZE
14546
    {"PC_MIN_HOLE_SIZE",    _PC_MIN_HOLE_SIZE},
14547
#endif
14548
#ifdef _PC_ALLOC_SIZE_MIN
14549
    {"PC_ALLOC_SIZE_MIN",   _PC_ALLOC_SIZE_MIN},
14550
#endif
14551
#ifdef _PC_REC_INCR_XFER_SIZE
14552
    {"PC_REC_INCR_XFER_SIZE",   _PC_REC_INCR_XFER_SIZE},
14553
#endif
14554
#ifdef _PC_REC_MAX_XFER_SIZE
14555
    {"PC_REC_MAX_XFER_SIZE",    _PC_REC_MAX_XFER_SIZE},
14556
#endif
14557
#ifdef _PC_REC_MIN_XFER_SIZE
14558
    {"PC_REC_MIN_XFER_SIZE",    _PC_REC_MIN_XFER_SIZE},
14559
#endif
14560
#ifdef _PC_REC_XFER_ALIGN
14561
    {"PC_REC_XFER_ALIGN",   _PC_REC_XFER_ALIGN},
14562
#endif
14563
#ifdef _PC_SYMLINK_MAX
14564
    {"PC_SYMLINK_MAX",  _PC_SYMLINK_MAX},
14565
#endif
14566
#ifdef _PC_XATTR_ENABLED
14567
    {"PC_XATTR_ENABLED",    _PC_XATTR_ENABLED},
14568
#endif
14569
#ifdef _PC_XATTR_EXISTS
14570
    {"PC_XATTR_EXISTS", _PC_XATTR_EXISTS},
14571
#endif
14572
#ifdef _PC_TIMESTAMP_RESOLUTION
14573
    {"PC_TIMESTAMP_RESOLUTION", _PC_TIMESTAMP_RESOLUTION},
14574
#endif
14575
};
14576
#endif
14577
14578
14579
#ifdef HAVE_FPATHCONF
14580
/*[clinic input]
14581
os.fpathconf -> long
14582
14583
    fd: fildes
14584
    name: confname(table="pathconf_names")
14585
    /
14586
14587
Return the configuration limit name for the file descriptor fd.
14588
14589
If there is no limit, return -1.
14590
[clinic start generated code]*/
14591
14592
static long
14593
os_fpathconf_impl(PyObject *module, int fd, int name)
14594
/*[clinic end generated code: output=d5b7042425fc3e21 input=023d44589c9ed6aa]*/
14595
0
{
14596
0
    long limit;
14597
14598
0
    errno = 0;
14599
0
    limit = fpathconf(fd, name);
14600
0
    if (limit == -1 && errno != 0)
14601
0
        posix_error();
14602
14603
0
    return limit;
14604
0
}
14605
#endif /* HAVE_FPATHCONF */
14606
14607
14608
#ifdef HAVE_PATHCONF
14609
/*[clinic input]
14610
os.pathconf -> long
14611
    path: path_t(allow_fd='PATH_HAVE_FPATHCONF')
14612
    name: confname(table="pathconf_names")
14613
14614
Return the configuration limit name for the file or directory path.
14615
14616
If there is no limit, return -1.
14617
On some platforms, path may also be specified as an open file
14618
descriptor.  If this functionality is unavailable, using it raises
14619
an exception.
14620
[clinic start generated code]*/
14621
14622
static long
14623
os_pathconf_impl(PyObject *module, path_t *path, int name)
14624
/*[clinic end generated code: output=5bedee35b293a089 input=e86f6eacfa006426]*/
14625
0
{
14626
0
    long limit;
14627
14628
0
    errno = 0;
14629
0
#ifdef HAVE_FPATHCONF
14630
0
    if (path->is_fd) {
14631
0
        limit = fpathconf(path->fd, name);
14632
0
    }
14633
0
    else
14634
0
#endif
14635
0
        limit = pathconf(path->narrow, name);
14636
0
    if (limit == -1 && errno != 0) {
14637
0
        if (errno == EINVAL)
14638
            /* could be a path or name problem */
14639
0
            posix_error();
14640
0
        else
14641
0
            path_error(path);
14642
0
    }
14643
14644
0
    return limit;
14645
0
}
14646
#endif /* HAVE_PATHCONF */
14647
14648
#ifdef HAVE_CONFSTR
14649
static struct constdef posix_constants_confstr[] = {
14650
#ifdef _CS_ARCHITECTURE
14651
    {"CS_ARCHITECTURE", _CS_ARCHITECTURE},
14652
#endif
14653
#ifdef _CS_GNU_LIBC_VERSION
14654
    {"CS_GNU_LIBC_VERSION",     _CS_GNU_LIBC_VERSION},
14655
#endif
14656
#ifdef _CS_GNU_LIBPTHREAD_VERSION
14657
    {"CS_GNU_LIBPTHREAD_VERSION",       _CS_GNU_LIBPTHREAD_VERSION},
14658
#endif
14659
#ifdef _CS_HOSTNAME
14660
    {"CS_HOSTNAME",     _CS_HOSTNAME},
14661
#endif
14662
#ifdef _CS_HW_PROVIDER
14663
    {"CS_HW_PROVIDER",  _CS_HW_PROVIDER},
14664
#endif
14665
#ifdef _CS_HW_SERIAL
14666
    {"CS_HW_SERIAL",    _CS_HW_SERIAL},
14667
#endif
14668
#ifdef _CS_INITTAB_NAME
14669
    {"CS_INITTAB_NAME", _CS_INITTAB_NAME},
14670
#endif
14671
#ifdef _CS_LFS64_CFLAGS
14672
    {"CS_LFS64_CFLAGS", _CS_LFS64_CFLAGS},
14673
#endif
14674
#ifdef _CS_LFS64_LDFLAGS
14675
    {"CS_LFS64_LDFLAGS",        _CS_LFS64_LDFLAGS},
14676
#endif
14677
#ifdef _CS_LFS64_LIBS
14678
    {"CS_LFS64_LIBS",   _CS_LFS64_LIBS},
14679
#endif
14680
#ifdef _CS_LFS64_LINTFLAGS
14681
    {"CS_LFS64_LINTFLAGS",      _CS_LFS64_LINTFLAGS},
14682
#endif
14683
#ifdef _CS_LFS_CFLAGS
14684
    {"CS_LFS_CFLAGS",   _CS_LFS_CFLAGS},
14685
#endif
14686
#ifdef _CS_LFS_LDFLAGS
14687
    {"CS_LFS_LDFLAGS",  _CS_LFS_LDFLAGS},
14688
#endif
14689
#ifdef _CS_LFS_LIBS
14690
    {"CS_LFS_LIBS",     _CS_LFS_LIBS},
14691
#endif
14692
#ifdef _CS_LFS_LINTFLAGS
14693
    {"CS_LFS_LINTFLAGS",        _CS_LFS_LINTFLAGS},
14694
#endif
14695
#ifdef _CS_MACHINE
14696
    {"CS_MACHINE",      _CS_MACHINE},
14697
#endif
14698
#ifdef _CS_PATH
14699
    {"CS_PATH", _CS_PATH},
14700
#endif
14701
#ifdef _CS_RELEASE
14702
    {"CS_RELEASE",      _CS_RELEASE},
14703
#endif
14704
#ifdef _CS_SRPC_DOMAIN
14705
    {"CS_SRPC_DOMAIN",  _CS_SRPC_DOMAIN},
14706
#endif
14707
#ifdef _CS_SYSNAME
14708
    {"CS_SYSNAME",      _CS_SYSNAME},
14709
#endif
14710
#ifdef _CS_VERSION
14711
    {"CS_VERSION",      _CS_VERSION},
14712
#endif
14713
#ifdef _CS_XBS5_ILP32_OFF32_CFLAGS
14714
    {"CS_XBS5_ILP32_OFF32_CFLAGS",      _CS_XBS5_ILP32_OFF32_CFLAGS},
14715
#endif
14716
#ifdef _CS_XBS5_ILP32_OFF32_LDFLAGS
14717
    {"CS_XBS5_ILP32_OFF32_LDFLAGS",     _CS_XBS5_ILP32_OFF32_LDFLAGS},
14718
#endif
14719
#ifdef _CS_XBS5_ILP32_OFF32_LIBS
14720
    {"CS_XBS5_ILP32_OFF32_LIBS",        _CS_XBS5_ILP32_OFF32_LIBS},
14721
#endif
14722
#ifdef _CS_XBS5_ILP32_OFF32_LINTFLAGS
14723
    {"CS_XBS5_ILP32_OFF32_LINTFLAGS",   _CS_XBS5_ILP32_OFF32_LINTFLAGS},
14724
#endif
14725
#ifdef _CS_XBS5_ILP32_OFFBIG_CFLAGS
14726
    {"CS_XBS5_ILP32_OFFBIG_CFLAGS",     _CS_XBS5_ILP32_OFFBIG_CFLAGS},
14727
#endif
14728
#ifdef _CS_XBS5_ILP32_OFFBIG_LDFLAGS
14729
    {"CS_XBS5_ILP32_OFFBIG_LDFLAGS",    _CS_XBS5_ILP32_OFFBIG_LDFLAGS},
14730
#endif
14731
#ifdef _CS_XBS5_ILP32_OFFBIG_LIBS
14732
    {"CS_XBS5_ILP32_OFFBIG_LIBS",       _CS_XBS5_ILP32_OFFBIG_LIBS},
14733
#endif
14734
#ifdef _CS_XBS5_ILP32_OFFBIG_LINTFLAGS
14735
    {"CS_XBS5_ILP32_OFFBIG_LINTFLAGS",  _CS_XBS5_ILP32_OFFBIG_LINTFLAGS},
14736
#endif
14737
#ifdef _CS_XBS5_LP64_OFF64_CFLAGS
14738
    {"CS_XBS5_LP64_OFF64_CFLAGS",       _CS_XBS5_LP64_OFF64_CFLAGS},
14739
#endif
14740
#ifdef _CS_XBS5_LP64_OFF64_LDFLAGS
14741
    {"CS_XBS5_LP64_OFF64_LDFLAGS",      _CS_XBS5_LP64_OFF64_LDFLAGS},
14742
#endif
14743
#ifdef _CS_XBS5_LP64_OFF64_LIBS
14744
    {"CS_XBS5_LP64_OFF64_LIBS", _CS_XBS5_LP64_OFF64_LIBS},
14745
#endif
14746
#ifdef _CS_XBS5_LP64_OFF64_LINTFLAGS
14747
    {"CS_XBS5_LP64_OFF64_LINTFLAGS",    _CS_XBS5_LP64_OFF64_LINTFLAGS},
14748
#endif
14749
#ifdef _CS_XBS5_LPBIG_OFFBIG_CFLAGS
14750
    {"CS_XBS5_LPBIG_OFFBIG_CFLAGS",     _CS_XBS5_LPBIG_OFFBIG_CFLAGS},
14751
#endif
14752
#ifdef _CS_XBS5_LPBIG_OFFBIG_LDFLAGS
14753
    {"CS_XBS5_LPBIG_OFFBIG_LDFLAGS",    _CS_XBS5_LPBIG_OFFBIG_LDFLAGS},
14754
#endif
14755
#ifdef _CS_XBS5_LPBIG_OFFBIG_LIBS
14756
    {"CS_XBS5_LPBIG_OFFBIG_LIBS",       _CS_XBS5_LPBIG_OFFBIG_LIBS},
14757
#endif
14758
#ifdef _CS_XBS5_LPBIG_OFFBIG_LINTFLAGS
14759
    {"CS_XBS5_LPBIG_OFFBIG_LINTFLAGS",  _CS_XBS5_LPBIG_OFFBIG_LINTFLAGS},
14760
#endif
14761
#ifdef _MIPS_CS_AVAIL_PROCESSORS
14762
    {"MIPS_CS_AVAIL_PROCESSORS",        _MIPS_CS_AVAIL_PROCESSORS},
14763
#endif
14764
#ifdef _MIPS_CS_BASE
14765
    {"MIPS_CS_BASE",    _MIPS_CS_BASE},
14766
#endif
14767
#ifdef _MIPS_CS_HOSTID
14768
    {"MIPS_CS_HOSTID",  _MIPS_CS_HOSTID},
14769
#endif
14770
#ifdef _MIPS_CS_HW_NAME
14771
    {"MIPS_CS_HW_NAME", _MIPS_CS_HW_NAME},
14772
#endif
14773
#ifdef _MIPS_CS_NUM_PROCESSORS
14774
    {"MIPS_CS_NUM_PROCESSORS",  _MIPS_CS_NUM_PROCESSORS},
14775
#endif
14776
#ifdef _MIPS_CS_OSREL_MAJ
14777
    {"MIPS_CS_OSREL_MAJ",       _MIPS_CS_OSREL_MAJ},
14778
#endif
14779
#ifdef _MIPS_CS_OSREL_MIN
14780
    {"MIPS_CS_OSREL_MIN",       _MIPS_CS_OSREL_MIN},
14781
#endif
14782
#ifdef _MIPS_CS_OSREL_PATCH
14783
    {"MIPS_CS_OSREL_PATCH",     _MIPS_CS_OSREL_PATCH},
14784
#endif
14785
#ifdef _MIPS_CS_OS_NAME
14786
    {"MIPS_CS_OS_NAME", _MIPS_CS_OS_NAME},
14787
#endif
14788
#ifdef _MIPS_CS_OS_PROVIDER
14789
    {"MIPS_CS_OS_PROVIDER",     _MIPS_CS_OS_PROVIDER},
14790
#endif
14791
#ifdef _MIPS_CS_PROCESSORS
14792
    {"MIPS_CS_PROCESSORS",      _MIPS_CS_PROCESSORS},
14793
#endif
14794
#ifdef _MIPS_CS_SERIAL
14795
    {"MIPS_CS_SERIAL",  _MIPS_CS_SERIAL},
14796
#endif
14797
#ifdef _MIPS_CS_VENDOR
14798
    {"MIPS_CS_VENDOR",  _MIPS_CS_VENDOR},
14799
#endif
14800
};
14801
14802
14803
/*[clinic input]
14804
os.confstr
14805
14806
    name: confname(table="confstr_names")
14807
    /
14808
14809
Return a string-valued system configuration variable.
14810
[clinic start generated code]*/
14811
14812
static PyObject *
14813
os_confstr_impl(PyObject *module, int name)
14814
/*[clinic end generated code: output=bfb0b1b1e49b9383 input=4c6ffca2837ec959]*/
14815
4
{
14816
4
    PyObject *result = NULL;
14817
4
    char buffer[255];
14818
4
    size_t len;
14819
14820
4
    errno = 0;
14821
4
    len = confstr(name, buffer, sizeof(buffer));
14822
4
    if (len == 0) {
14823
0
        if (errno) {
14824
0
            posix_error();
14825
0
            return NULL;
14826
0
        }
14827
0
        else {
14828
0
            Py_RETURN_NONE;
14829
0
        }
14830
0
    }
14831
14832
4
    if (len >= sizeof(buffer)) {
14833
0
        size_t len2;
14834
0
        char *buf = PyMem_Malloc(len);
14835
0
        if (buf == NULL)
14836
0
            return PyErr_NoMemory();
14837
0
        len2 = confstr(name, buf, len);
14838
0
        assert(len == len2);
14839
0
        result = PyUnicode_DecodeFSDefaultAndSize(buf, len2-1);
14840
0
        PyMem_Free(buf);
14841
0
    }
14842
4
    else
14843
4
        result = PyUnicode_DecodeFSDefaultAndSize(buffer, len-1);
14844
4
    return result;
14845
4
}
14846
#endif /* HAVE_CONFSTR */
14847
14848
14849
#ifdef HAVE_SYSCONF
14850
static struct constdef posix_constants_sysconf[] = {
14851
#ifdef _SC_2_CHAR_TERM
14852
    {"SC_2_CHAR_TERM",  _SC_2_CHAR_TERM},
14853
#endif
14854
#ifdef _SC_2_C_BIND
14855
    {"SC_2_C_BIND",     _SC_2_C_BIND},
14856
#endif
14857
#ifdef _SC_2_C_DEV
14858
    {"SC_2_C_DEV",      _SC_2_C_DEV},
14859
#endif
14860
#ifdef _SC_2_C_VERSION
14861
    {"SC_2_C_VERSION",  _SC_2_C_VERSION},
14862
#endif
14863
#ifdef _SC_2_FORT_DEV
14864
    {"SC_2_FORT_DEV",   _SC_2_FORT_DEV},
14865
#endif
14866
#ifdef _SC_2_FORT_RUN
14867
    {"SC_2_FORT_RUN",   _SC_2_FORT_RUN},
14868
#endif
14869
#ifdef _SC_2_LOCALEDEF
14870
    {"SC_2_LOCALEDEF",  _SC_2_LOCALEDEF},
14871
#endif
14872
#ifdef _SC_2_SW_DEV
14873
    {"SC_2_SW_DEV",     _SC_2_SW_DEV},
14874
#endif
14875
#ifdef _SC_2_UPE
14876
    {"SC_2_UPE",        _SC_2_UPE},
14877
#endif
14878
#ifdef _SC_2_VERSION
14879
    {"SC_2_VERSION",    _SC_2_VERSION},
14880
#endif
14881
#ifdef _SC_ABI_ASYNCHRONOUS_IO
14882
    {"SC_ABI_ASYNCHRONOUS_IO",  _SC_ABI_ASYNCHRONOUS_IO},
14883
#endif
14884
#ifdef _SC_ACL
14885
    {"SC_ACL",  _SC_ACL},
14886
#endif
14887
#ifdef _SC_AIO_LISTIO_MAX
14888
    {"SC_AIO_LISTIO_MAX",       _SC_AIO_LISTIO_MAX},
14889
#endif
14890
#ifdef _SC_AIO_MAX
14891
    {"SC_AIO_MAX",      _SC_AIO_MAX},
14892
#endif
14893
#ifdef _SC_AIO_PRIO_DELTA_MAX
14894
    {"SC_AIO_PRIO_DELTA_MAX",   _SC_AIO_PRIO_DELTA_MAX},
14895
#endif
14896
#ifdef _SC_ARG_MAX
14897
    {"SC_ARG_MAX",      _SC_ARG_MAX},
14898
#endif
14899
#ifdef _SC_ASYNCHRONOUS_IO
14900
    {"SC_ASYNCHRONOUS_IO",      _SC_ASYNCHRONOUS_IO},
14901
#endif
14902
#ifdef _SC_ATEXIT_MAX
14903
    {"SC_ATEXIT_MAX",   _SC_ATEXIT_MAX},
14904
#endif
14905
#ifdef _SC_AUDIT
14906
    {"SC_AUDIT",        _SC_AUDIT},
14907
#endif
14908
#ifdef _SC_AVPHYS_PAGES
14909
    {"SC_AVPHYS_PAGES", _SC_AVPHYS_PAGES},
14910
#endif
14911
#ifdef _SC_BC_BASE_MAX
14912
    {"SC_BC_BASE_MAX",  _SC_BC_BASE_MAX},
14913
#endif
14914
#ifdef _SC_BC_DIM_MAX
14915
    {"SC_BC_DIM_MAX",   _SC_BC_DIM_MAX},
14916
#endif
14917
#ifdef _SC_BC_SCALE_MAX
14918
    {"SC_BC_SCALE_MAX", _SC_BC_SCALE_MAX},
14919
#endif
14920
#ifdef _SC_BC_STRING_MAX
14921
    {"SC_BC_STRING_MAX",        _SC_BC_STRING_MAX},
14922
#endif
14923
#ifdef _SC_CAP
14924
    {"SC_CAP",  _SC_CAP},
14925
#endif
14926
#ifdef _SC_CHARCLASS_NAME_MAX
14927
    {"SC_CHARCLASS_NAME_MAX",   _SC_CHARCLASS_NAME_MAX},
14928
#endif
14929
#ifdef _SC_CHAR_BIT
14930
    {"SC_CHAR_BIT",     _SC_CHAR_BIT},
14931
#endif
14932
#ifdef _SC_CHAR_MAX
14933
    {"SC_CHAR_MAX",     _SC_CHAR_MAX},
14934
#endif
14935
#ifdef _SC_CHAR_MIN
14936
    {"SC_CHAR_MIN",     _SC_CHAR_MIN},
14937
#endif
14938
#ifdef _SC_CHILD_MAX
14939
    {"SC_CHILD_MAX",    _SC_CHILD_MAX},
14940
#endif
14941
#ifdef _SC_CLK_TCK
14942
    {"SC_CLK_TCK",      _SC_CLK_TCK},
14943
#endif
14944
#ifdef _SC_COHER_BLKSZ
14945
    {"SC_COHER_BLKSZ",  _SC_COHER_BLKSZ},
14946
#endif
14947
#ifdef _SC_COLL_WEIGHTS_MAX
14948
    {"SC_COLL_WEIGHTS_MAX",     _SC_COLL_WEIGHTS_MAX},
14949
#endif
14950
#ifdef _SC_DCACHE_ASSOC
14951
    {"SC_DCACHE_ASSOC", _SC_DCACHE_ASSOC},
14952
#endif
14953
#ifdef _SC_DCACHE_BLKSZ
14954
    {"SC_DCACHE_BLKSZ", _SC_DCACHE_BLKSZ},
14955
#endif
14956
#ifdef _SC_DCACHE_LINESZ
14957
    {"SC_DCACHE_LINESZ",        _SC_DCACHE_LINESZ},
14958
#endif
14959
#ifdef _SC_DCACHE_SZ
14960
    {"SC_DCACHE_SZ",    _SC_DCACHE_SZ},
14961
#endif
14962
#ifdef _SC_DCACHE_TBLKSZ
14963
    {"SC_DCACHE_TBLKSZ",        _SC_DCACHE_TBLKSZ},
14964
#endif
14965
#ifdef _SC_DELAYTIMER_MAX
14966
    {"SC_DELAYTIMER_MAX",       _SC_DELAYTIMER_MAX},
14967
#endif
14968
#ifdef _SC_EQUIV_CLASS_MAX
14969
    {"SC_EQUIV_CLASS_MAX",      _SC_EQUIV_CLASS_MAX},
14970
#endif
14971
#ifdef _SC_EXPR_NEST_MAX
14972
    {"SC_EXPR_NEST_MAX",        _SC_EXPR_NEST_MAX},
14973
#endif
14974
#ifdef _SC_FSYNC
14975
    {"SC_FSYNC",        _SC_FSYNC},
14976
#endif
14977
#ifdef _SC_GETGR_R_SIZE_MAX
14978
    {"SC_GETGR_R_SIZE_MAX",     _SC_GETGR_R_SIZE_MAX},
14979
#endif
14980
#ifdef _SC_GETPW_R_SIZE_MAX
14981
    {"SC_GETPW_R_SIZE_MAX",     _SC_GETPW_R_SIZE_MAX},
14982
#endif
14983
#ifdef _SC_ICACHE_ASSOC
14984
    {"SC_ICACHE_ASSOC", _SC_ICACHE_ASSOC},
14985
#endif
14986
#ifdef _SC_ICACHE_BLKSZ
14987
    {"SC_ICACHE_BLKSZ", _SC_ICACHE_BLKSZ},
14988
#endif
14989
#ifdef _SC_ICACHE_LINESZ
14990
    {"SC_ICACHE_LINESZ",        _SC_ICACHE_LINESZ},
14991
#endif
14992
#ifdef _SC_ICACHE_SZ
14993
    {"SC_ICACHE_SZ",    _SC_ICACHE_SZ},
14994
#endif
14995
#ifdef _SC_INF
14996
    {"SC_INF",  _SC_INF},
14997
#endif
14998
#ifdef _SC_INT_MAX
14999
    {"SC_INT_MAX",      _SC_INT_MAX},
15000
#endif
15001
#ifdef _SC_INT_MIN
15002
    {"SC_INT_MIN",      _SC_INT_MIN},
15003
#endif
15004
#ifdef _SC_IOV_MAX
15005
    {"SC_IOV_MAX",      _SC_IOV_MAX},
15006
#endif
15007
#ifdef _SC_IP_SECOPTS
15008
    {"SC_IP_SECOPTS",   _SC_IP_SECOPTS},
15009
#endif
15010
#ifdef _SC_JOB_CONTROL
15011
    {"SC_JOB_CONTROL",  _SC_JOB_CONTROL},
15012
#endif
15013
#ifdef _SC_KERN_POINTERS
15014
    {"SC_KERN_POINTERS",        _SC_KERN_POINTERS},
15015
#endif
15016
#ifdef _SC_KERN_SIM
15017
    {"SC_KERN_SIM",     _SC_KERN_SIM},
15018
#endif
15019
#ifdef _SC_LINE_MAX
15020
    {"SC_LINE_MAX",     _SC_LINE_MAX},
15021
#endif
15022
#ifdef _SC_LOGIN_NAME_MAX
15023
    {"SC_LOGIN_NAME_MAX",       _SC_LOGIN_NAME_MAX},
15024
#endif
15025
#ifdef _SC_LOGNAME_MAX
15026
    {"SC_LOGNAME_MAX",  _SC_LOGNAME_MAX},
15027
#endif
15028
#ifdef _SC_LONG_BIT
15029
    {"SC_LONG_BIT",     _SC_LONG_BIT},
15030
#endif
15031
#ifdef _SC_MAC
15032
    {"SC_MAC",  _SC_MAC},
15033
#endif
15034
#ifdef _SC_MAPPED_FILES
15035
    {"SC_MAPPED_FILES", _SC_MAPPED_FILES},
15036
#endif
15037
#ifdef _SC_MAXPID
15038
    {"SC_MAXPID",       _SC_MAXPID},
15039
#endif
15040
#ifdef _SC_MB_LEN_MAX
15041
    {"SC_MB_LEN_MAX",   _SC_MB_LEN_MAX},
15042
#endif
15043
#ifdef _SC_MEMLOCK
15044
    {"SC_MEMLOCK",      _SC_MEMLOCK},
15045
#endif
15046
#ifdef _SC_MEMLOCK_RANGE
15047
    {"SC_MEMLOCK_RANGE",        _SC_MEMLOCK_RANGE},
15048
#endif
15049
#ifdef _SC_MEMORY_PROTECTION
15050
    {"SC_MEMORY_PROTECTION",    _SC_MEMORY_PROTECTION},
15051
#endif
15052
#ifdef _SC_MESSAGE_PASSING
15053
    {"SC_MESSAGE_PASSING",      _SC_MESSAGE_PASSING},
15054
#endif
15055
#ifdef _SC_MMAP_FIXED_ALIGNMENT
15056
    {"SC_MMAP_FIXED_ALIGNMENT", _SC_MMAP_FIXED_ALIGNMENT},
15057
#endif
15058
#ifdef _SC_MQ_OPEN_MAX
15059
    {"SC_MQ_OPEN_MAX",  _SC_MQ_OPEN_MAX},
15060
#endif
15061
#ifdef _SC_MQ_PRIO_MAX
15062
    {"SC_MQ_PRIO_MAX",  _SC_MQ_PRIO_MAX},
15063
#endif
15064
#ifdef _SC_NACLS_MAX
15065
    {"SC_NACLS_MAX",    _SC_NACLS_MAX},
15066
#endif
15067
#ifdef _SC_NGROUPS_MAX
15068
    {"SC_NGROUPS_MAX",  _SC_NGROUPS_MAX},
15069
#endif
15070
#ifdef _SC_NL_ARGMAX
15071
    {"SC_NL_ARGMAX",    _SC_NL_ARGMAX},
15072
#endif
15073
#ifdef _SC_NL_LANGMAX
15074
    {"SC_NL_LANGMAX",   _SC_NL_LANGMAX},
15075
#endif
15076
#ifdef _SC_NL_MSGMAX
15077
    {"SC_NL_MSGMAX",    _SC_NL_MSGMAX},
15078
#endif
15079
#ifdef _SC_NL_NMAX
15080
    {"SC_NL_NMAX",      _SC_NL_NMAX},
15081
#endif
15082
#ifdef _SC_NL_SETMAX
15083
    {"SC_NL_SETMAX",    _SC_NL_SETMAX},
15084
#endif
15085
#ifdef _SC_NL_TEXTMAX
15086
    {"SC_NL_TEXTMAX",   _SC_NL_TEXTMAX},
15087
#endif
15088
#ifdef _SC_NPROCESSORS_CONF
15089
    {"SC_NPROCESSORS_CONF",     _SC_NPROCESSORS_CONF},
15090
#endif
15091
#ifdef _SC_NPROCESSORS_ONLN
15092
    {"SC_NPROCESSORS_ONLN",     _SC_NPROCESSORS_ONLN},
15093
#endif
15094
#ifdef _SC_NPROC_CONF
15095
    {"SC_NPROC_CONF",   _SC_NPROC_CONF},
15096
#endif
15097
#ifdef _SC_NPROC_ONLN
15098
    {"SC_NPROC_ONLN",   _SC_NPROC_ONLN},
15099
#endif
15100
#ifdef _SC_NZERO
15101
    {"SC_NZERO",        _SC_NZERO},
15102
#endif
15103
#ifdef _SC_OPEN_MAX
15104
    {"SC_OPEN_MAX",     _SC_OPEN_MAX},
15105
#endif
15106
#ifdef _SC_PAGESIZE
15107
    {"SC_PAGESIZE",     _SC_PAGESIZE},
15108
#endif
15109
#ifdef _SC_PAGE_SIZE
15110
    {"SC_PAGE_SIZE",    _SC_PAGE_SIZE},
15111
#endif
15112
#ifdef _SC_AIX_REALMEM
15113
    {"SC_AIX_REALMEM", _SC_AIX_REALMEM},
15114
#endif
15115
#ifdef _SC_PASS_MAX
15116
    {"SC_PASS_MAX",     _SC_PASS_MAX},
15117
#endif
15118
#ifdef _SC_PHYS_PAGES
15119
    {"SC_PHYS_PAGES",   _SC_PHYS_PAGES},
15120
#endif
15121
#ifdef _SC_PII
15122
    {"SC_PII",  _SC_PII},
15123
#endif
15124
#ifdef _SC_PII_INTERNET
15125
    {"SC_PII_INTERNET", _SC_PII_INTERNET},
15126
#endif
15127
#ifdef _SC_PII_INTERNET_DGRAM
15128
    {"SC_PII_INTERNET_DGRAM",   _SC_PII_INTERNET_DGRAM},
15129
#endif
15130
#ifdef _SC_PII_INTERNET_STREAM
15131
    {"SC_PII_INTERNET_STREAM",  _SC_PII_INTERNET_STREAM},
15132
#endif
15133
#ifdef _SC_PII_OSI
15134
    {"SC_PII_OSI",      _SC_PII_OSI},
15135
#endif
15136
#ifdef _SC_PII_OSI_CLTS
15137
    {"SC_PII_OSI_CLTS", _SC_PII_OSI_CLTS},
15138
#endif
15139
#ifdef _SC_PII_OSI_COTS
15140
    {"SC_PII_OSI_COTS", _SC_PII_OSI_COTS},
15141
#endif
15142
#ifdef _SC_PII_OSI_M
15143
    {"SC_PII_OSI_M",    _SC_PII_OSI_M},
15144
#endif
15145
#ifdef _SC_PII_SOCKET
15146
    {"SC_PII_SOCKET",   _SC_PII_SOCKET},
15147
#endif
15148
#ifdef _SC_PII_XTI
15149
    {"SC_PII_XTI",      _SC_PII_XTI},
15150
#endif
15151
#ifdef _SC_POLL
15152
    {"SC_POLL", _SC_POLL},
15153
#endif
15154
#ifdef _SC_PRIORITIZED_IO
15155
    {"SC_PRIORITIZED_IO",       _SC_PRIORITIZED_IO},
15156
#endif
15157
#ifdef _SC_PRIORITY_SCHEDULING
15158
    {"SC_PRIORITY_SCHEDULING",  _SC_PRIORITY_SCHEDULING},
15159
#endif
15160
#ifdef _SC_REALTIME_SIGNALS
15161
    {"SC_REALTIME_SIGNALS",     _SC_REALTIME_SIGNALS},
15162
#endif
15163
#ifdef _SC_RE_DUP_MAX
15164
    {"SC_RE_DUP_MAX",   _SC_RE_DUP_MAX},
15165
#endif
15166
#ifdef _SC_RTSIG_MAX
15167
    {"SC_RTSIG_MAX",    _SC_RTSIG_MAX},
15168
#endif
15169
#ifdef _SC_SAVED_IDS
15170
    {"SC_SAVED_IDS",    _SC_SAVED_IDS},
15171
#endif
15172
#ifdef _SC_SCHAR_MAX
15173
    {"SC_SCHAR_MAX",    _SC_SCHAR_MAX},
15174
#endif
15175
#ifdef _SC_SCHAR_MIN
15176
    {"SC_SCHAR_MIN",    _SC_SCHAR_MIN},
15177
#endif
15178
#ifdef _SC_SELECT
15179
    {"SC_SELECT",       _SC_SELECT},
15180
#endif
15181
#ifdef _SC_SEMAPHORES
15182
    {"SC_SEMAPHORES",   _SC_SEMAPHORES},
15183
#endif
15184
#ifdef _SC_SEM_NSEMS_MAX
15185
    {"SC_SEM_NSEMS_MAX",        _SC_SEM_NSEMS_MAX},
15186
#endif
15187
#ifdef _SC_SEM_VALUE_MAX
15188
    {"SC_SEM_VALUE_MAX",        _SC_SEM_VALUE_MAX},
15189
#endif
15190
#ifdef _SC_SHARED_MEMORY_OBJECTS
15191
    {"SC_SHARED_MEMORY_OBJECTS",        _SC_SHARED_MEMORY_OBJECTS},
15192
#endif
15193
#ifdef _SC_SHRT_MAX
15194
    {"SC_SHRT_MAX",     _SC_SHRT_MAX},
15195
#endif
15196
#ifdef _SC_SHRT_MIN
15197
    {"SC_SHRT_MIN",     _SC_SHRT_MIN},
15198
#endif
15199
#ifdef _SC_SIGQUEUE_MAX
15200
    {"SC_SIGQUEUE_MAX", _SC_SIGQUEUE_MAX},
15201
#endif
15202
#ifdef _SC_SIGRT_MAX
15203
    {"SC_SIGRT_MAX",    _SC_SIGRT_MAX},
15204
#endif
15205
#ifdef _SC_SIGRT_MIN
15206
    {"SC_SIGRT_MIN",    _SC_SIGRT_MIN},
15207
#endif
15208
#ifdef _SC_SOFTPOWER
15209
    {"SC_SOFTPOWER",    _SC_SOFTPOWER},
15210
#endif
15211
#ifdef _SC_SPLIT_CACHE
15212
    {"SC_SPLIT_CACHE",  _SC_SPLIT_CACHE},
15213
#endif
15214
#ifdef _SC_SSIZE_MAX
15215
    {"SC_SSIZE_MAX",    _SC_SSIZE_MAX},
15216
#endif
15217
#ifdef _SC_STACK_PROT
15218
    {"SC_STACK_PROT",   _SC_STACK_PROT},
15219
#endif
15220
#ifdef _SC_STREAM_MAX
15221
    {"SC_STREAM_MAX",   _SC_STREAM_MAX},
15222
#endif
15223
#ifdef _SC_SYNCHRONIZED_IO
15224
    {"SC_SYNCHRONIZED_IO",      _SC_SYNCHRONIZED_IO},
15225
#endif
15226
#ifdef _SC_THREADS
15227
    {"SC_THREADS",      _SC_THREADS},
15228
#endif
15229
#ifdef _SC_THREAD_ATTR_STACKADDR
15230
    {"SC_THREAD_ATTR_STACKADDR",        _SC_THREAD_ATTR_STACKADDR},
15231
#endif
15232
#ifdef _SC_THREAD_ATTR_STACKSIZE
15233
    {"SC_THREAD_ATTR_STACKSIZE",        _SC_THREAD_ATTR_STACKSIZE},
15234
#endif
15235
#ifdef _SC_THREAD_DESTRUCTOR_ITERATIONS
15236
    {"SC_THREAD_DESTRUCTOR_ITERATIONS", _SC_THREAD_DESTRUCTOR_ITERATIONS},
15237
#endif
15238
#ifdef _SC_THREAD_KEYS_MAX
15239
    {"SC_THREAD_KEYS_MAX",      _SC_THREAD_KEYS_MAX},
15240
#endif
15241
#ifdef _SC_THREAD_PRIORITY_SCHEDULING
15242
    {"SC_THREAD_PRIORITY_SCHEDULING",   _SC_THREAD_PRIORITY_SCHEDULING},
15243
#endif
15244
#ifdef _SC_THREAD_PRIO_INHERIT
15245
    {"SC_THREAD_PRIO_INHERIT",  _SC_THREAD_PRIO_INHERIT},
15246
#endif
15247
#ifdef _SC_THREAD_PRIO_PROTECT
15248
    {"SC_THREAD_PRIO_PROTECT",  _SC_THREAD_PRIO_PROTECT},
15249
#endif
15250
#ifdef _SC_THREAD_PROCESS_SHARED
15251
    {"SC_THREAD_PROCESS_SHARED",        _SC_THREAD_PROCESS_SHARED},
15252
#endif
15253
#ifdef _SC_THREAD_SAFE_FUNCTIONS
15254
    {"SC_THREAD_SAFE_FUNCTIONS",        _SC_THREAD_SAFE_FUNCTIONS},
15255
#endif
15256
#ifdef _SC_THREAD_STACK_MIN
15257
    {"SC_THREAD_STACK_MIN",     _SC_THREAD_STACK_MIN},
15258
#endif
15259
#ifdef _SC_THREAD_THREADS_MAX
15260
    {"SC_THREAD_THREADS_MAX",   _SC_THREAD_THREADS_MAX},
15261
#endif
15262
#ifdef _SC_TIMERS
15263
    {"SC_TIMERS",       _SC_TIMERS},
15264
#endif
15265
#ifdef _SC_TIMER_MAX
15266
    {"SC_TIMER_MAX",    _SC_TIMER_MAX},
15267
#endif
15268
#ifdef _SC_TTY_NAME_MAX
15269
    {"SC_TTY_NAME_MAX", _SC_TTY_NAME_MAX},
15270
#endif
15271
#ifdef _SC_TZNAME_MAX
15272
    {"SC_TZNAME_MAX",   _SC_TZNAME_MAX},
15273
#endif
15274
#ifdef _SC_T_IOV_MAX
15275
    {"SC_T_IOV_MAX",    _SC_T_IOV_MAX},
15276
#endif
15277
#ifdef _SC_UCHAR_MAX
15278
    {"SC_UCHAR_MAX",    _SC_UCHAR_MAX},
15279
#endif
15280
#ifdef _SC_UINT_MAX
15281
    {"SC_UINT_MAX",     _SC_UINT_MAX},
15282
#endif
15283
#ifdef _SC_UIO_MAXIOV
15284
    {"SC_UIO_MAXIOV",   _SC_UIO_MAXIOV},
15285
#endif
15286
#ifdef _SC_ULONG_MAX
15287
    {"SC_ULONG_MAX",    _SC_ULONG_MAX},
15288
#endif
15289
#ifdef _SC_USHRT_MAX
15290
    {"SC_USHRT_MAX",    _SC_USHRT_MAX},
15291
#endif
15292
#ifdef _SC_VERSION
15293
    {"SC_VERSION",      _SC_VERSION},
15294
#endif
15295
#ifdef _SC_WORD_BIT
15296
    {"SC_WORD_BIT",     _SC_WORD_BIT},
15297
#endif
15298
#ifdef _SC_XBS5_ILP32_OFF32
15299
    {"SC_XBS5_ILP32_OFF32",     _SC_XBS5_ILP32_OFF32},
15300
#endif
15301
#ifdef _SC_XBS5_ILP32_OFFBIG
15302
    {"SC_XBS5_ILP32_OFFBIG",    _SC_XBS5_ILP32_OFFBIG},
15303
#endif
15304
#ifdef _SC_XBS5_LP64_OFF64
15305
    {"SC_XBS5_LP64_OFF64",      _SC_XBS5_LP64_OFF64},
15306
#endif
15307
#ifdef _SC_XBS5_LPBIG_OFFBIG
15308
    {"SC_XBS5_LPBIG_OFFBIG",    _SC_XBS5_LPBIG_OFFBIG},
15309
#endif
15310
#ifdef _SC_XOPEN_CRYPT
15311
    {"SC_XOPEN_CRYPT",  _SC_XOPEN_CRYPT},
15312
#endif
15313
#ifdef _SC_XOPEN_ENH_I18N
15314
    {"SC_XOPEN_ENH_I18N",       _SC_XOPEN_ENH_I18N},
15315
#endif
15316
#ifdef _SC_XOPEN_LEGACY
15317
    {"SC_XOPEN_LEGACY", _SC_XOPEN_LEGACY},
15318
#endif
15319
#ifdef _SC_XOPEN_REALTIME
15320
    {"SC_XOPEN_REALTIME",       _SC_XOPEN_REALTIME},
15321
#endif
15322
#ifdef _SC_XOPEN_REALTIME_THREADS
15323
    {"SC_XOPEN_REALTIME_THREADS",       _SC_XOPEN_REALTIME_THREADS},
15324
#endif
15325
#ifdef _SC_XOPEN_SHM
15326
    {"SC_XOPEN_SHM",    _SC_XOPEN_SHM},
15327
#endif
15328
#ifdef _SC_XOPEN_UNIX
15329
    {"SC_XOPEN_UNIX",   _SC_XOPEN_UNIX},
15330
#endif
15331
#ifdef _SC_XOPEN_VERSION
15332
    {"SC_XOPEN_VERSION",        _SC_XOPEN_VERSION},
15333
#endif
15334
#ifdef _SC_XOPEN_XCU_VERSION
15335
    {"SC_XOPEN_XCU_VERSION",    _SC_XOPEN_XCU_VERSION},
15336
#endif
15337
#ifdef _SC_XOPEN_XPG2
15338
    {"SC_XOPEN_XPG2",   _SC_XOPEN_XPG2},
15339
#endif
15340
#ifdef _SC_XOPEN_XPG3
15341
    {"SC_XOPEN_XPG3",   _SC_XOPEN_XPG3},
15342
#endif
15343
#ifdef _SC_XOPEN_XPG4
15344
    {"SC_XOPEN_XPG4",   _SC_XOPEN_XPG4},
15345
#endif
15346
#ifdef _SC_MINSIGSTKSZ
15347
    {"SC_MINSIGSTKSZ",   _SC_MINSIGSTKSZ},
15348
#endif
15349
};
15350
15351
15352
/*[clinic input]
15353
os.sysconf -> long
15354
    name: confname(table="sysconf_names")
15355
    /
15356
15357
Return an integer-valued system configuration variable.
15358
[clinic start generated code]*/
15359
15360
static long
15361
os_sysconf_impl(PyObject *module, int name)
15362
/*[clinic end generated code: output=3662f945fc0cc756 input=930b8f23b5d15086]*/
15363
0
{
15364
0
    long value;
15365
15366
0
    errno = 0;
15367
0
    value = sysconf(name);
15368
0
    if (value == -1 && errno != 0)
15369
0
        posix_error();
15370
0
    return value;
15371
0
}
15372
#endif /* HAVE_SYSCONF */
15373
15374
15375
static int
15376
setup_confname_table(struct constdef *table, size_t tablesize,
15377
                     const char *tablename, PyObject *module)
15378
111
{
15379
111
    PyObject *d = PyDict_New();
15380
111
    if (d == NULL)
15381
0
        return -1;
15382
15383
6.84k
    for (size_t i=0; i < tablesize; ++i) {
15384
6.73k
        PyObject *o = PyLong_FromLong(table[i].value);
15385
6.73k
        if (o == NULL || PyDict_SetItemString(d, table[i].name, o) == -1) {
15386
0
            Py_XDECREF(o);
15387
0
            Py_DECREF(d);
15388
0
            return -1;
15389
0
        }
15390
6.73k
        Py_DECREF(o);
15391
6.73k
    }
15392
111
    return PyModule_Add(module, tablename, d);
15393
111
}
15394
15395
/* Return -1 on failure, 0 on success. */
15396
static int
15397
setup_confname_tables(PyObject *module)
15398
37
{
15399
37
#if defined(HAVE_FPATHCONF) || defined(HAVE_PATHCONF)
15400
37
    if (setup_confname_table(posix_constants_pathconf,
15401
37
                             sizeof(posix_constants_pathconf)
15402
37
                               / sizeof(struct constdef),
15403
37
                             "pathconf_names", module))
15404
0
        return -1;
15405
37
#endif
15406
37
#ifdef HAVE_CONFSTR
15407
37
    if (setup_confname_table(posix_constants_confstr,
15408
37
                             sizeof(posix_constants_confstr)
15409
37
                               / sizeof(struct constdef),
15410
37
                             "confstr_names", module))
15411
0
        return -1;
15412
37
#endif
15413
37
#ifdef HAVE_SYSCONF
15414
37
    if (setup_confname_table(posix_constants_sysconf,
15415
37
                             sizeof(posix_constants_sysconf)
15416
37
                               / sizeof(struct constdef),
15417
37
                             "sysconf_names", module))
15418
0
        return -1;
15419
37
#endif
15420
37
    return 0;
15421
37
}
15422
15423
15424
/*[clinic input]
15425
os.abort
15426
15427
Abort the interpreter immediately.
15428
15429
This function 'dumps core' or otherwise fails in the hardest way
15430
possible on the hosting operating system.  This function never returns.
15431
[clinic start generated code]*/
15432
15433
static PyObject *
15434
os_abort_impl(PyObject *module)
15435
/*[clinic end generated code: output=dcf52586dad2467c input=ee8bd0ed690440ab]*/
15436
0
{
15437
0
    abort();
15438
    /*NOTREACHED*/
15439
#ifndef __clang__
15440
    /* Issue #28152: abort() is declared with __attribute__((__noreturn__)).
15441
       GCC emits a warning without "return NULL;" (compiler bug?), but Clang
15442
       is smarter and emits a warning on the return. */
15443
    Py_FatalError("abort() called from Python code didn't abort!");
15444
    return NULL;
15445
#endif
15446
0
}
15447
15448
#ifdef MS_WINDOWS
15449
/* Grab ShellExecute dynamically from shell32 */
15450
static int has_ShellExecute = -1;
15451
static HINSTANCE (CALLBACK *Py_ShellExecuteW)(HWND, LPCWSTR, LPCWSTR, LPCWSTR,
15452
                                              LPCWSTR, INT);
15453
static int
15454
check_ShellExecute(void)
15455
{
15456
    HINSTANCE hShell32;
15457
15458
    /* only recheck */
15459
    if (-1 == has_ShellExecute) {
15460
        Py_BEGIN_ALLOW_THREADS
15461
        /* Security note: this call is not vulnerable to "DLL hijacking".
15462
           SHELL32 is part of "KnownDLLs" and so Windows always load
15463
           the system SHELL32.DLL, even if there is another SHELL32.DLL
15464
           in the DLL search path. */
15465
        hShell32 = LoadLibraryW(L"SHELL32");
15466
        if (hShell32) {
15467
            *(FARPROC*)&Py_ShellExecuteW = GetProcAddress(hShell32,
15468
                                            "ShellExecuteW");
15469
            has_ShellExecute = Py_ShellExecuteW != NULL;
15470
        } else {
15471
            has_ShellExecute = 0;
15472
        }
15473
        Py_END_ALLOW_THREADS
15474
    }
15475
    return has_ShellExecute;
15476
}
15477
15478
15479
/*[clinic input]
15480
os.startfile
15481
    filepath: path_t
15482
    operation: Py_UNICODE = NULL
15483
    arguments: Py_UNICODE = NULL
15484
    cwd: path_t(nullable=True) = None
15485
    show_cmd: int = 1
15486
15487
Start a file with its associated application.
15488
15489
When "operation" is not specified or "open", this acts like
15490
double-clicking the file in Explorer, or giving the file name as an
15491
argument to the DOS "start" command: the file is opened with whatever
15492
application (if any) its extension is associated.
15493
When another "operation" is given, it specifies what should be done with
15494
the file.  A typical operation is "print".
15495
15496
"arguments" is passed to the application, but should be omitted if the
15497
file is a document.
15498
15499
"cwd" is the working directory for the operation. If "filepath" is
15500
relative, it will be resolved against this directory. This argument
15501
should usually be an absolute path.
15502
15503
"show_cmd" can be used to override the recommended visibility option.
15504
See the Windows ShellExecute documentation for values.
15505
15506
startfile returns as soon as the associated application is launched.
15507
There is no option to wait for the application to close, and no way
15508
to retrieve the application's exit status.
15509
15510
The filepath is relative to the current directory.  If you want to use
15511
an absolute path, make sure the first character is not a slash ("/");
15512
the underlying Win32 ShellExecute function doesn't work if it is.
15513
[clinic start generated code]*/
15514
15515
static PyObject *
15516
os_startfile_impl(PyObject *module, path_t *filepath,
15517
                  const wchar_t *operation, const wchar_t *arguments,
15518
                  path_t *cwd, int show_cmd)
15519
/*[clinic end generated code: output=1c6f2f3340e31ffa input=8248997b80669622]*/
15520
{
15521
    HINSTANCE rc;
15522
15523
    if(!check_ShellExecute()) {
15524
        /* If the OS doesn't have ShellExecute, return a
15525
           NotImplementedError. */
15526
        return PyErr_Format(PyExc_NotImplementedError,
15527
            "startfile not available on this platform");
15528
    }
15529
15530
    if (PySys_Audit("os.startfile", "Ou", filepath->object, operation) < 0) {
15531
        return NULL;
15532
    }
15533
    if (PySys_Audit("os.startfile/2", "OuuOi", filepath->object, operation,
15534
                    arguments, cwd->object ? cwd->object : Py_None,
15535
                    show_cmd) < 0) {
15536
        return NULL;
15537
    }
15538
15539
    Py_BEGIN_ALLOW_THREADS
15540
    rc = Py_ShellExecuteW((HWND)0, operation, filepath->wide,
15541
                          arguments, cwd->wide, show_cmd);
15542
    Py_END_ALLOW_THREADS
15543
15544
    if (rc <= (HINSTANCE)32) {
15545
        win32_error_object("startfile", filepath->object);
15546
        return NULL;
15547
    }
15548
    Py_RETURN_NONE;
15549
}
15550
#endif /* MS_WINDOWS */
15551
15552
15553
#ifdef HAVE_GETLOADAVG
15554
/*[clinic input]
15555
os.getloadavg
15556
15557
Return average recent system load information.
15558
15559
Return the number of processes in the system run queue averaged over
15560
the last 1, 5, and 15 minutes as a tuple of three floats.
15561
Raises OSError if the load average was unobtainable.
15562
[clinic start generated code]*/
15563
15564
static PyObject *
15565
os_getloadavg_impl(PyObject *module)
15566
/*[clinic end generated code: output=9ad3a11bfb4f4bd2 input=3d6d826b76d8a34e]*/
15567
0
{
15568
0
    double loadavg[3];
15569
0
    if (getloadavg(loadavg, 3)!=3) {
15570
0
        PyErr_SetString(PyExc_OSError, "Load averages are unobtainable");
15571
0
        return NULL;
15572
0
    } else
15573
0
        return Py_BuildValue("ddd", loadavg[0], loadavg[1], loadavg[2]);
15574
0
}
15575
#endif /* HAVE_GETLOADAVG */
15576
15577
15578
/*[clinic input]
15579
os.device_encoding
15580
    fd: int
15581
15582
Return a string describing the encoding of a terminal's file descriptor.
15583
15584
The file descriptor must be attached to a terminal.
15585
If the device is not a terminal, return None.
15586
[clinic start generated code]*/
15587
15588
static PyObject *
15589
os_device_encoding_impl(PyObject *module, int fd)
15590
/*[clinic end generated code: output=e0d294bbab7e8c2b input=9e1d4a42b66df312]*/
15591
0
{
15592
0
    return _Py_device_encoding(fd);
15593
0
}
15594
15595
15596
#ifdef HAVE_SETRESUID
15597
/*[clinic input]
15598
os.setresuid
15599
15600
    ruid: uid_t
15601
    euid: uid_t
15602
    suid: uid_t
15603
    /
15604
15605
Set the current process's real, effective, and saved user ids.
15606
[clinic start generated code]*/
15607
15608
static PyObject *
15609
os_setresuid_impl(PyObject *module, uid_t ruid, uid_t euid, uid_t suid)
15610
/*[clinic end generated code: output=834a641e15373e97 input=9e33cb79a82792f3]*/
15611
0
{
15612
#ifdef __ANDROID__
15613
    // On Android, calling this function as a non-root user leads to a process crash
15614
    // rather than returning a permission error.
15615
    if (getuid() != 0) {
15616
        errno = EPERM;
15617
        return posix_error();
15618
    }
15619
#endif
15620
0
    if (setresuid(ruid, euid, suid) < 0)
15621
0
        return posix_error();
15622
0
    Py_RETURN_NONE;
15623
0
}
15624
#endif /* HAVE_SETRESUID */
15625
15626
15627
#ifdef HAVE_SETRESGID
15628
/*[clinic input]
15629
os.setresgid
15630
15631
    rgid: gid_t
15632
    egid: gid_t
15633
    sgid: gid_t
15634
    /
15635
15636
Set the current process's real, effective, and saved group ids.
15637
[clinic start generated code]*/
15638
15639
static PyObject *
15640
os_setresgid_impl(PyObject *module, gid_t rgid, gid_t egid, gid_t sgid)
15641
/*[clinic end generated code: output=6aa402f3d2e514a9 input=33e9e0785ef426b1]*/
15642
0
{
15643
#ifdef __ANDROID__
15644
    // On Android, calling this function as a non-root user leads to a process crash
15645
    // rather than returning a permission error.
15646
    if (getuid() != 0) {
15647
        errno = EPERM;
15648
        return posix_error();
15649
    }
15650
#endif
15651
0
    if (setresgid(rgid, egid, sgid) < 0)
15652
0
        return posix_error();
15653
0
    Py_RETURN_NONE;
15654
0
}
15655
#endif /* HAVE_SETRESGID */
15656
15657
15658
#ifdef HAVE_GETRESUID
15659
/*[clinic input]
15660
@permit_long_summary
15661
os.getresuid
15662
15663
Return a tuple of the current process's real, effective, and saved user ids.
15664
[clinic start generated code]*/
15665
15666
static PyObject *
15667
os_getresuid_impl(PyObject *module)
15668
/*[clinic end generated code: output=8e0becff5dece5bf input=ddf95881f492cb97]*/
15669
0
{
15670
0
    uid_t ruid, euid, suid;
15671
0
    if (getresuid(&ruid, &euid, &suid) < 0)
15672
0
        return posix_error();
15673
0
    return Py_BuildValue("(NNN)", _PyLong_FromUid(ruid),
15674
0
                                  _PyLong_FromUid(euid),
15675
0
                                  _PyLong_FromUid(suid));
15676
0
}
15677
#endif /* HAVE_GETRESUID */
15678
15679
15680
#ifdef HAVE_GETRESGID
15681
/*[clinic input]
15682
@permit_long_summary
15683
os.getresgid
15684
15685
Return a tuple of the current process's real, effective, and saved group ids.
15686
[clinic start generated code]*/
15687
15688
static PyObject *
15689
os_getresgid_impl(PyObject *module)
15690
/*[clinic end generated code: output=2719c4bfcf27fb9f input=ad9adadc86fbdb17]*/
15691
0
{
15692
0
    gid_t rgid, egid, sgid;
15693
0
    if (getresgid(&rgid, &egid, &sgid) < 0)
15694
0
        return posix_error();
15695
0
    return Py_BuildValue("(NNN)", _PyLong_FromGid(rgid),
15696
0
                                  _PyLong_FromGid(egid),
15697
0
                                  _PyLong_FromGid(sgid));
15698
0
}
15699
#endif /* HAVE_GETRESGID */
15700
15701
15702
#ifdef USE_XATTRS
15703
/*[clinic input]
15704
os.getxattr
15705
15706
    path: path_t(allow_fd=True)
15707
    attribute: path_t
15708
    *
15709
    follow_symlinks: bool = True
15710
15711
Return the value of extended attribute attribute on path.
15712
15713
path may be either a string, a path-like object, or an open file
15714
descriptor.
15715
If follow_symlinks is False, and the last element of the path is
15716
a symbolic link, getxattr will examine the symbolic link itself
15717
instead of the file the link points to.
15718
15719
[clinic start generated code]*/
15720
15721
static PyObject *
15722
os_getxattr_impl(PyObject *module, path_t *path, path_t *attribute,
15723
                 int follow_symlinks)
15724
/*[clinic end generated code: output=5f2f44200a43cff2 input=db1021ed738d9754]*/
15725
0
{
15726
0
    if (fd_and_follow_symlinks_invalid("getxattr", path->is_fd, follow_symlinks))
15727
0
        return NULL;
15728
15729
0
    if (PySys_Audit("os.getxattr", "OO", path->object, attribute->object) < 0) {
15730
0
        return NULL;
15731
0
    }
15732
15733
0
    for (Py_ssize_t i = 0; ; i++) {
15734
0
        ssize_t result;
15735
0
        static const Py_ssize_t buffer_sizes[] = {128, XATTR_SIZE_MAX, 0};
15736
0
        Py_ssize_t buffer_size = buffer_sizes[i];
15737
0
        if (!buffer_size) {
15738
0
            path_error(path);
15739
0
            return NULL;
15740
0
        }
15741
0
        PyBytesWriter *writer = PyBytesWriter_Create(buffer_size);
15742
0
        if (writer == NULL) {
15743
0
            return NULL;
15744
0
        }
15745
0
        void *ptr = PyBytesWriter_GetData(writer);
15746
15747
0
        Py_BEGIN_ALLOW_THREADS;
15748
0
        if (path->is_fd)
15749
0
            result = fgetxattr(path->fd, attribute->narrow, ptr, buffer_size);
15750
0
        else if (follow_symlinks)
15751
0
            result = getxattr(path->narrow, attribute->narrow, ptr, buffer_size);
15752
0
        else
15753
0
            result = lgetxattr(path->narrow, attribute->narrow, ptr, buffer_size);
15754
0
        Py_END_ALLOW_THREADS;
15755
15756
0
        if (result < 0) {
15757
0
            PyBytesWriter_Discard(writer);
15758
0
            if (errno == ERANGE) {
15759
0
                continue;
15760
0
            }
15761
0
            path_error(path);
15762
0
            return NULL;
15763
0
        }
15764
15765
0
        return PyBytesWriter_FinishWithSize(writer, result);
15766
0
    }
15767
0
}
15768
15769
15770
/*[clinic input]
15771
os.setxattr
15772
15773
    path: path_t(allow_fd=True)
15774
    attribute: path_t
15775
    value: Py_buffer
15776
    flags: int = 0
15777
    *
15778
    follow_symlinks: bool = True
15779
15780
Set extended attribute attribute on path to value.
15781
15782
path may be either a string, a path-like object,  or an open file
15783
descriptor.
15784
If follow_symlinks is False, and the last element of the path is
15785
a symbolic link, setxattr will modify the symbolic link itself instead
15786
of the file the link points to.
15787
15788
[clinic start generated code]*/
15789
15790
static PyObject *
15791
os_setxattr_impl(PyObject *module, path_t *path, path_t *attribute,
15792
                 Py_buffer *value, int flags, int follow_symlinks)
15793
/*[clinic end generated code: output=98b83f63fdde26bb input=6c4ee6724e8947a4]*/
15794
0
{
15795
0
    ssize_t result;
15796
15797
0
    if (fd_and_follow_symlinks_invalid("setxattr", path->is_fd, follow_symlinks))
15798
0
        return NULL;
15799
15800
0
    if (PySys_Audit("os.setxattr", "OOy#i", path->object, attribute->object,
15801
0
                    value->buf, value->len, flags) < 0) {
15802
0
        return NULL;
15803
0
    }
15804
15805
0
    Py_BEGIN_ALLOW_THREADS;
15806
0
    if (path->is_fd)
15807
0
        result = fsetxattr(path->fd, attribute->narrow,
15808
0
                           value->buf, value->len, flags);
15809
0
    else if (follow_symlinks)
15810
0
        result = setxattr(path->narrow, attribute->narrow,
15811
0
                           value->buf, value->len, flags);
15812
0
    else
15813
0
        result = lsetxattr(path->narrow, attribute->narrow,
15814
0
                           value->buf, value->len, flags);
15815
0
    Py_END_ALLOW_THREADS;
15816
15817
0
    if (result) {
15818
0
        path_error(path);
15819
0
        return NULL;
15820
0
    }
15821
15822
0
    Py_RETURN_NONE;
15823
0
}
15824
15825
15826
/*[clinic input]
15827
os.removexattr
15828
15829
    path: path_t(allow_fd=True)
15830
    attribute: path_t
15831
    *
15832
    follow_symlinks: bool = True
15833
15834
Remove extended attribute attribute on path.
15835
15836
path may be either a string, a path-like object, or an open file
15837
descriptor.
15838
If follow_symlinks is False, and the last element of the path is
15839
a symbolic link, removexattr will modify the symbolic link itself
15840
instead of the file the link points to.
15841
15842
[clinic start generated code]*/
15843
15844
static PyObject *
15845
os_removexattr_impl(PyObject *module, path_t *path, path_t *attribute,
15846
                    int follow_symlinks)
15847
/*[clinic end generated code: output=521a51817980cda6 input=a7ec62a86aa83f01]*/
15848
0
{
15849
0
    ssize_t result;
15850
15851
0
    if (fd_and_follow_symlinks_invalid("removexattr", path->is_fd, follow_symlinks))
15852
0
        return NULL;
15853
15854
0
    if (PySys_Audit("os.removexattr", "OO", path->object, attribute->object) < 0) {
15855
0
        return NULL;
15856
0
    }
15857
15858
0
    Py_BEGIN_ALLOW_THREADS;
15859
0
    if (path->is_fd)
15860
0
        result = fremovexattr(path->fd, attribute->narrow);
15861
0
    else if (follow_symlinks)
15862
0
        result = removexattr(path->narrow, attribute->narrow);
15863
0
    else
15864
0
        result = lremovexattr(path->narrow, attribute->narrow);
15865
0
    Py_END_ALLOW_THREADS;
15866
15867
0
    if (result) {
15868
0
        return path_error(path);
15869
0
    }
15870
15871
0
    Py_RETURN_NONE;
15872
0
}
15873
15874
15875
/*[clinic input]
15876
os.listxattr
15877
15878
    path: path_t(allow_fd=True, nullable=True) = None
15879
    *
15880
    follow_symlinks: bool = True
15881
15882
Return a list of extended attributes on path.
15883
15884
path may be either None, a string, a path-like object, or an open file
15885
descriptor.  If path is None, listxattr will examine the current
15886
directory.
15887
If follow_symlinks is False, and the last element of the path is
15888
a symbolic link, listxattr will examine the symbolic link itself instead
15889
of the file the link points to.
15890
[clinic start generated code]*/
15891
15892
static PyObject *
15893
os_listxattr_impl(PyObject *module, path_t *path, int follow_symlinks)
15894
/*[clinic end generated code: output=bebdb4e2ad0ce435 input=cb4a6414afaa99bd]*/
15895
0
{
15896
0
    Py_ssize_t i;
15897
0
    PyObject *result = NULL;
15898
0
    const char *name;
15899
0
    char *buffer = NULL;
15900
15901
0
    if (fd_and_follow_symlinks_invalid("listxattr", path->is_fd, follow_symlinks))
15902
0
        goto exit;
15903
15904
0
    if (PySys_Audit("os.listxattr", "(O)",
15905
0
                    path->object ? path->object : Py_None) < 0) {
15906
0
        return NULL;
15907
0
    }
15908
15909
0
    name = path->narrow ? path->narrow : ".";
15910
15911
0
    for (i = 0; ; i++) {
15912
0
        const char *start, *trace, *end;
15913
0
        ssize_t length;
15914
0
        static const Py_ssize_t buffer_sizes[] = { 256, XATTR_LIST_MAX, 0 };
15915
0
        Py_ssize_t buffer_size = buffer_sizes[i];
15916
0
        if (!buffer_size) {
15917
            /* ERANGE */
15918
0
            path_error(path);
15919
0
            break;
15920
0
        }
15921
0
        buffer = PyMem_Malloc(buffer_size);
15922
0
        if (!buffer) {
15923
0
            PyErr_NoMemory();
15924
0
            break;
15925
0
        }
15926
15927
0
        Py_BEGIN_ALLOW_THREADS;
15928
0
        if (path->is_fd)
15929
0
            length = flistxattr(path->fd, buffer, buffer_size);
15930
0
        else if (follow_symlinks)
15931
0
            length = listxattr(name, buffer, buffer_size);
15932
0
        else
15933
0
            length = llistxattr(name, buffer, buffer_size);
15934
0
        Py_END_ALLOW_THREADS;
15935
15936
0
        if (length < 0) {
15937
0
            if (errno == ERANGE) {
15938
0
                PyMem_Free(buffer);
15939
0
                buffer = NULL;
15940
0
                continue;
15941
0
            }
15942
0
            path_error(path);
15943
0
            break;
15944
0
        }
15945
15946
0
        result = PyList_New(0);
15947
0
        if (!result) {
15948
0
            goto exit;
15949
0
        }
15950
15951
0
        end = buffer + length;
15952
0
        for (trace = start = buffer; trace != end; trace++) {
15953
0
            if (!*trace) {
15954
0
                int error;
15955
0
                PyObject *attribute = PyUnicode_DecodeFSDefaultAndSize(start,
15956
0
                                                                 trace - start);
15957
0
                if (!attribute) {
15958
0
                    Py_SETREF(result, NULL);
15959
0
                    goto exit;
15960
0
                }
15961
0
                error = PyList_Append(result, attribute);
15962
0
                Py_DECREF(attribute);
15963
0
                if (error) {
15964
0
                    Py_SETREF(result, NULL);
15965
0
                    goto exit;
15966
0
                }
15967
0
                start = trace + 1;
15968
0
            }
15969
0
        }
15970
0
    break;
15971
0
    }
15972
0
exit:
15973
0
    if (buffer)
15974
0
        PyMem_Free(buffer);
15975
0
    return result;
15976
0
}
15977
#endif /* USE_XATTRS */
15978
15979
15980
/*[clinic input]
15981
@permit_long_summary
15982
os.urandom
15983
15984
    size: Py_ssize_t(allow_negative=False)
15985
    /
15986
15987
Return a bytes object containing random bytes suitable for cryptographic use.
15988
[clinic start generated code]*/
15989
15990
static PyObject *
15991
os_urandom_impl(PyObject *module, Py_ssize_t size)
15992
/*[clinic end generated code: output=42c5cca9d18068e9 input=58a0def87dbc2c22]*/
15993
0
{
15994
0
    if (size < 0) {
15995
0
        return PyErr_Format(PyExc_ValueError,
15996
0
                            "negative argument not allowed");
15997
0
    }
15998
15999
0
    PyBytesWriter *writer = PyBytesWriter_Create(size);
16000
0
    if (writer == NULL) {
16001
0
        return NULL;
16002
0
    }
16003
16004
0
    int result = _PyOS_URandom(PyBytesWriter_GetData(writer), size);
16005
0
    if (result == -1) {
16006
0
        PyBytesWriter_Discard(writer);
16007
0
        return NULL;
16008
0
    }
16009
0
    return PyBytesWriter_Finish(writer);
16010
0
}
16011
16012
#if defined(HAVE_MEMFD_CREATE) || \
16013
    (defined(__linux__) && defined(__NR_memfd_create) && defined(MFD_CLOEXEC))
16014
#  define _Py_HAVE_MEMFD_CREATE
16015
#endif
16016
16017
#ifdef _Py_HAVE_MEMFD_CREATE
16018
/*[clinic input]
16019
os.memfd_create
16020
16021
    name: unicode_fs_encoded
16022
    flags: unsigned_int(bitwise=True, c_default="MFD_CLOEXEC") = MFD_CLOEXEC
16023
16024
[clinic start generated code]*/
16025
16026
static PyObject *
16027
os_memfd_create_impl(PyObject *module, PyObject *name, unsigned int flags)
16028
/*[clinic end generated code: output=6681ede983bdb9a6 input=cd0eb092cfac474b]*/
16029
0
{
16030
0
    int fd;
16031
0
    const char *bytes = PyBytes_AS_STRING(name);
16032
0
    Py_BEGIN_ALLOW_THREADS
16033
0
#ifdef HAVE_MEMFD_CREATE
16034
0
    fd = memfd_create(bytes, flags);
16035
#else
16036
    fd = syscall(__NR_memfd_create, bytes, flags);
16037
#endif
16038
0
    Py_END_ALLOW_THREADS
16039
0
    if (fd == -1) {
16040
0
        return PyErr_SetFromErrno(PyExc_OSError);
16041
0
    }
16042
0
    return PyLong_FromLong(fd);
16043
0
}
16044
#endif
16045
16046
#if defined(HAVE_EVENTFD) && defined(EFD_CLOEXEC)
16047
/*[clinic input]
16048
os.eventfd
16049
16050
    initval: unsigned_int
16051
    flags: int(c_default="EFD_CLOEXEC") = EFD_CLOEXEC
16052
16053
Creates and returns an event notification file descriptor.
16054
[clinic start generated code]*/
16055
16056
static PyObject *
16057
os_eventfd_impl(PyObject *module, unsigned int initval, int flags)
16058
/*[clinic end generated code: output=ce9c9bbd1446f2de input=66203e3c50c4028b]*/
16059
16060
0
{
16061
    /* initval is limited to uint32_t, internal counter is uint64_t */
16062
0
    int fd;
16063
0
    Py_BEGIN_ALLOW_THREADS
16064
0
    fd = eventfd(initval, flags);
16065
0
    Py_END_ALLOW_THREADS
16066
0
    if (fd == -1) {
16067
0
        return PyErr_SetFromErrno(PyExc_OSError);
16068
0
    }
16069
0
    return PyLong_FromLong(fd);
16070
0
}
16071
16072
/*[clinic input]
16073
os.eventfd_read
16074
16075
    fd: fildes
16076
16077
Read eventfd value
16078
[clinic start generated code]*/
16079
16080
static PyObject *
16081
os_eventfd_read_impl(PyObject *module, int fd)
16082
/*[clinic end generated code: output=8f2c7b59a3521fd1 input=110f8b57fa596afe]*/
16083
0
{
16084
0
    eventfd_t value;
16085
0
    int result;
16086
0
    Py_BEGIN_ALLOW_THREADS
16087
0
    result = eventfd_read(fd, &value);
16088
0
    Py_END_ALLOW_THREADS
16089
0
    if (result == -1) {
16090
0
        return PyErr_SetFromErrno(PyExc_OSError);
16091
0
    }
16092
0
    return PyLong_FromUnsignedLongLong(value);
16093
0
}
16094
16095
/*[clinic input]
16096
os.eventfd_write
16097
16098
    fd: fildes
16099
    value: unsigned_long_long
16100
16101
Write eventfd value.
16102
[clinic start generated code]*/
16103
16104
static PyObject *
16105
os_eventfd_write_impl(PyObject *module, int fd, unsigned long long value)
16106
/*[clinic end generated code: output=bebd9040bbf987f5 input=156de8555be5a949]*/
16107
0
{
16108
0
    int result;
16109
0
    Py_BEGIN_ALLOW_THREADS
16110
0
    result = eventfd_write(fd, value);
16111
0
    Py_END_ALLOW_THREADS
16112
0
    if (result == -1) {
16113
0
        return PyErr_SetFromErrno(PyExc_OSError);
16114
0
    }
16115
0
    Py_RETURN_NONE;
16116
0
}
16117
#endif  /* HAVE_EVENTFD && EFD_CLOEXEC */
16118
16119
/* Terminal size querying */
16120
16121
PyDoc_STRVAR(TerminalSize_docstring,
16122
    "A tuple of (columns, lines) for holding terminal window size");
16123
16124
static PyStructSequence_Field TerminalSize_fields[] = {
16125
    {"columns", "width of the terminal window in characters"},
16126
    {"lines", "height of the terminal window in characters"},
16127
    {NULL, NULL}
16128
};
16129
16130
static PyStructSequence_Desc TerminalSize_desc = {
16131
    "os.terminal_size",
16132
    TerminalSize_docstring,
16133
    TerminalSize_fields,
16134
    2,
16135
};
16136
16137
#if defined(TERMSIZE_USE_CONIO) || defined(TERMSIZE_USE_IOCTL)
16138
/*[clinic input]
16139
os.get_terminal_size
16140
16141
    fd: int(c_default="fileno(stdout)", py_default="<unrepresentable>") = -1
16142
    /
16143
16144
Return the size of the terminal window as (columns, lines).
16145
16146
The optional argument fd (default standard output) specifies
16147
which file descriptor should be queried.
16148
16149
If the file descriptor is not connected to a terminal, an OSError
16150
is thrown.
16151
16152
This function will only be defined if an implementation is
16153
available for this system.
16154
16155
shutil.get_terminal_size is the high-level function which should
16156
normally be used, os.get_terminal_size is the low-level implementation.
16157
[clinic start generated code]*/
16158
16159
static PyObject *
16160
os_get_terminal_size_impl(PyObject *module, int fd)
16161
/*[clinic end generated code: output=fbab93acef980508 input=ead5679b82ddb920]*/
16162
0
{
16163
0
    int columns, lines;
16164
0
    PyObject *termsize;
16165
16166
    /* Under some conditions stdout may not be connected and
16167
     * fileno(stdout) may point to an invalid file descriptor. For example
16168
     * GUI apps don't have valid standard streams by default.
16169
     *
16170
     * If this happens, and the optional fd argument is not present,
16171
     * the ioctl below will fail returning EBADF. This is what we want.
16172
     */
16173
16174
0
#ifdef TERMSIZE_USE_IOCTL
16175
0
    {
16176
        // On Android, stdout is probably not connected, and calling TIOCGWINSZ
16177
        // on an invalid file descriptor causes a log message "avc:  denied  {
16178
        // ioctl }". Some common tools such as pytest call get_terminal_size
16179
        // very often, so check it's a TTY first to avoid cluttering the log.
16180
0
        if (!isatty(fd))
16181
0
            return PyErr_SetFromErrno(PyExc_OSError);
16182
16183
0
        struct winsize w;
16184
0
        if (ioctl(fd, TIOCGWINSZ, &w))
16185
0
            return PyErr_SetFromErrno(PyExc_OSError);
16186
0
        columns = w.ws_col;
16187
0
        lines = w.ws_row;
16188
0
    }
16189
0
#endif /* TERMSIZE_USE_IOCTL */
16190
16191
#ifdef TERMSIZE_USE_CONIO
16192
    {
16193
        HANDLE handle;
16194
        CONSOLE_SCREEN_BUFFER_INFO csbi;
16195
        handle = _Py_get_osfhandle(fd);
16196
        if (handle == INVALID_HANDLE_VALUE)
16197
            return NULL;
16198
16199
        if (!GetConsoleScreenBufferInfo(handle, &csbi))
16200
            return PyErr_SetFromWindowsErr(0);
16201
16202
        columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
16203
        lines = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
16204
    }
16205
#endif /* TERMSIZE_USE_CONIO */
16206
16207
0
    PyObject *TerminalSizeType = get_posix_state(module)->TerminalSizeType;
16208
0
    termsize = PyStructSequence_New((PyTypeObject *)TerminalSizeType);
16209
0
    if (termsize == NULL)
16210
0
        return NULL;
16211
16212
0
    int pos = 0;
16213
16214
0
#define SET_TERMSIZE(CALL)                                   \
16215
0
    do {                                                     \
16216
0
        PyObject *item = (CALL);                             \
16217
0
        if (item == NULL) {                                  \
16218
0
            Py_DECREF(termsize);                             \
16219
0
            return NULL;                                     \
16220
0
        }                                                    \
16221
0
        PyStructSequence_SET_ITEM(termsize, pos++, item);    \
16222
0
    } while(0)
16223
16224
0
    SET_TERMSIZE(PyLong_FromLong(columns));
16225
0
    SET_TERMSIZE(PyLong_FromLong(lines));
16226
0
#undef SET_TERMSIZE
16227
16228
0
    return termsize;
16229
0
}
16230
#endif /* defined(TERMSIZE_USE_CONIO) || defined(TERMSIZE_USE_IOCTL) */
16231
16232
/*[clinic input]
16233
os.cpu_count
16234
16235
Return the number of logical CPUs in the system.
16236
16237
Return None if indeterminable.
16238
[clinic start generated code]*/
16239
16240
static PyObject *
16241
os_cpu_count_impl(PyObject *module)
16242
/*[clinic end generated code: output=5fc29463c3936a9c input=ba2f6f8980a0e2eb]*/
16243
0
{
16244
0
    const PyConfig *config = _Py_GetConfig();
16245
0
    if (config->cpu_count > 0) {
16246
0
        return PyLong_FromLong(config->cpu_count);
16247
0
    }
16248
16249
0
    int ncpu = 0;
16250
#ifdef MS_WINDOWS
16251
# ifdef MS_WINDOWS_DESKTOP
16252
    ncpu = GetActiveProcessorCount(ALL_PROCESSOR_GROUPS);
16253
# else
16254
    SYSTEM_INFO sysinfo;
16255
    GetSystemInfo(&sysinfo);
16256
    ncpu = sysinfo.dwNumberOfProcessors;
16257
# endif
16258
16259
#elif defined(__hpux)
16260
    ncpu = mpctl(MPC_GETNUMSPUS, NULL, NULL);
16261
16262
#elif defined(HAVE_SYSCONF) && defined(_SC_NPROCESSORS_ONLN)
16263
0
    ncpu = sysconf(_SC_NPROCESSORS_ONLN);
16264
16265
#elif defined(__VXWORKS__)
16266
    ncpu = _Py_popcount32(vxCpuEnabledGet());
16267
16268
#elif defined(__DragonFly__) || \
16269
      defined(__OpenBSD__)   || \
16270
      defined(__FreeBSD__)   || \
16271
      defined(__NetBSD__)    || \
16272
      defined(__APPLE__)
16273
    ncpu = 0;
16274
    size_t len = sizeof(ncpu);
16275
    int mib[2] = {CTL_HW, HW_NCPU};
16276
    if (sysctl(mib, 2, &ncpu, &len, NULL, 0) != 0) {
16277
        ncpu = 0;
16278
    }
16279
#endif
16280
16281
0
    if (ncpu < 1) {
16282
0
        Py_RETURN_NONE;
16283
0
    }
16284
0
    return PyLong_FromLong(ncpu);
16285
0
}
16286
16287
16288
/*[clinic input]
16289
os.get_inheritable -> bool
16290
16291
    fd: int
16292
    /
16293
16294
Get the close-on-exe flag of the specified file descriptor.
16295
[clinic start generated code]*/
16296
16297
static int
16298
os_get_inheritable_impl(PyObject *module, int fd)
16299
/*[clinic end generated code: output=0445e20e149aa5b8 input=89ac008dc9ab6b95]*/
16300
0
{
16301
0
    int return_value;
16302
0
    _Py_BEGIN_SUPPRESS_IPH
16303
0
    return_value = _Py_get_inheritable(fd);
16304
0
    _Py_END_SUPPRESS_IPH
16305
0
    return return_value;
16306
0
}
16307
16308
16309
/*[clinic input]
16310
os.set_inheritable
16311
    fd: int
16312
    inheritable: int
16313
    /
16314
16315
Set the inheritable flag of the specified file descriptor.
16316
[clinic start generated code]*/
16317
16318
static PyObject *
16319
os_set_inheritable_impl(PyObject *module, int fd, int inheritable)
16320
/*[clinic end generated code: output=f1b1918a2f3c38c2 input=9ceaead87a1e2402]*/
16321
0
{
16322
0
    int result;
16323
16324
0
    _Py_BEGIN_SUPPRESS_IPH
16325
0
    result = _Py_set_inheritable(fd, inheritable, NULL);
16326
0
    _Py_END_SUPPRESS_IPH
16327
0
    if (result < 0)
16328
0
        return NULL;
16329
0
    Py_RETURN_NONE;
16330
0
}
16331
16332
16333
#ifdef MS_WINDOWS
16334
#ifndef HANDLE_FLAG_INHERIT
16335
#define HANDLE_FLAG_INHERIT 0x00000001
16336
#endif
16337
16338
/*[clinic input]
16339
os.get_handle_inheritable -> bool
16340
    handle: intptr_t
16341
    /
16342
16343
Get the close-on-exe flag of the specified file descriptor.
16344
[clinic start generated code]*/
16345
16346
static int
16347
os_get_handle_inheritable_impl(PyObject *module, intptr_t handle)
16348
/*[clinic end generated code: output=36be5afca6ea84d8 input=cfe99f9c05c70ad1]*/
16349
{
16350
    DWORD flags;
16351
16352
    if (!GetHandleInformation((HANDLE)handle, &flags)) {
16353
        PyErr_SetFromWindowsErr(0);
16354
        return -1;
16355
    }
16356
16357
    return flags & HANDLE_FLAG_INHERIT;
16358
}
16359
16360
16361
/*[clinic input]
16362
os.set_handle_inheritable
16363
    handle: intptr_t
16364
    inheritable: bool
16365
    /
16366
16367
Set the inheritable flag of the specified handle.
16368
[clinic start generated code]*/
16369
16370
static PyObject *
16371
os_set_handle_inheritable_impl(PyObject *module, intptr_t handle,
16372
                               int inheritable)
16373
/*[clinic end generated code: output=021d74fe6c96baa3 input=7a7641390d8364fc]*/
16374
{
16375
    DWORD flags = inheritable ? HANDLE_FLAG_INHERIT : 0;
16376
    if (!SetHandleInformation((HANDLE)handle, HANDLE_FLAG_INHERIT, flags)) {
16377
        PyErr_SetFromWindowsErr(0);
16378
        return NULL;
16379
    }
16380
    Py_RETURN_NONE;
16381
}
16382
#endif /* MS_WINDOWS */
16383
16384
/*[clinic input]
16385
os.get_blocking -> bool
16386
    fd: int
16387
    /
16388
16389
Get the blocking mode of the file descriptor.
16390
16391
Return False if the O_NONBLOCK flag is set, True if the flag is cleared.
16392
[clinic start generated code]*/
16393
16394
static int
16395
os_get_blocking_impl(PyObject *module, int fd)
16396
/*[clinic end generated code: output=336a12ad76a61482 input=f4afb59d51560179]*/
16397
0
{
16398
0
    int blocking;
16399
16400
0
    _Py_BEGIN_SUPPRESS_IPH
16401
0
    blocking = _Py_get_blocking(fd);
16402
0
    _Py_END_SUPPRESS_IPH
16403
0
    return blocking;
16404
0
}
16405
16406
/*[clinic input]
16407
os.set_blocking
16408
    fd: int
16409
    blocking: bool
16410
    /
16411
16412
Set the blocking mode of the specified file descriptor.
16413
16414
Set the O_NONBLOCK flag if blocking is False,
16415
clear the O_NONBLOCK flag otherwise.
16416
[clinic start generated code]*/
16417
16418
static PyObject *
16419
os_set_blocking_impl(PyObject *module, int fd, int blocking)
16420
/*[clinic end generated code: output=384eb43aa0762a9d input=7e9dfc9b14804dd4]*/
16421
0
{
16422
0
    int result;
16423
16424
0
    _Py_BEGIN_SUPPRESS_IPH
16425
0
    result = _Py_set_blocking(fd, blocking);
16426
0
    _Py_END_SUPPRESS_IPH
16427
0
    if (result < 0)
16428
0
        return NULL;
16429
0
    Py_RETURN_NONE;
16430
0
}
16431
16432
16433
/*[clinic input]
16434
class os.DirEntry "DirEntry *" "DirEntryType"
16435
class os.ScandirIterator "PyObject *" "ScandirIteratorType"
16436
[clinic start generated code]*/
16437
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=b845e502eb4a0406]*/
16438
16439
typedef struct {
16440
    PyObject_HEAD
16441
    PyObject *name;
16442
    PyObject *path;
16443
    PyObject *stat;
16444
    PyObject *lstat;
16445
#ifdef MS_WINDOWS
16446
    struct _Py_stat_struct win32_lstat;
16447
    uint64_t win32_file_index;
16448
    uint64_t win32_file_index_high;
16449
    int got_file_index;
16450
#else /* POSIX */
16451
#ifdef HAVE_DIRENT_D_TYPE
16452
    unsigned char d_type;
16453
#endif
16454
    ino_t d_ino;
16455
    int dir_fd;
16456
#endif
16457
} DirEntry;
16458
16459
116k
#define DirEntry_CAST(op)   ((DirEntry *)(op))
16460
16461
static void
16462
DirEntry_dealloc(PyObject *op)
16463
116k
{
16464
116k
    DirEntry *entry = DirEntry_CAST(op);
16465
116k
    PyTypeObject *tp = Py_TYPE(entry);
16466
116k
    Py_XDECREF(entry->name);
16467
116k
    Py_XDECREF(entry->path);
16468
116k
    Py_XDECREF(entry->stat);
16469
116k
    Py_XDECREF(entry->lstat);
16470
116k
    freefunc free_func = PyType_GetSlot(tp, Py_tp_free);
16471
116k
    free_func(entry);
16472
116k
    Py_DECREF(tp);
16473
116k
}
16474
16475
/* Forward reference */
16476
static int
16477
DirEntry_test_mode(PyTypeObject *defining_class, DirEntry *self,
16478
                   int follow_symlinks, unsigned short mode_bits);
16479
16480
/*[clinic input]
16481
os.DirEntry.is_symlink -> bool
16482
    defining_class: defining_class
16483
    /
16484
16485
Return True if the entry is a symbolic link; cached per entry.
16486
[clinic start generated code]*/
16487
16488
static int
16489
os_DirEntry_is_symlink_impl(DirEntry *self, PyTypeObject *defining_class)
16490
/*[clinic end generated code: output=293096d589b6d47c input=e9acc5ee4d511113]*/
16491
0
{
16492
#ifdef MS_WINDOWS
16493
    return (self->win32_lstat.st_mode & S_IFMT) == S_IFLNK;
16494
#elif defined(HAVE_DIRENT_D_TYPE)
16495
    /* POSIX */
16496
0
    if (self->d_type != DT_UNKNOWN)
16497
0
        return self->d_type == DT_LNK;
16498
0
    else
16499
0
        return DirEntry_test_mode(defining_class, self, 0, S_IFLNK);
16500
#else
16501
    /* POSIX without d_type */
16502
    return DirEntry_test_mode(defining_class, self, 0, S_IFLNK);
16503
#endif
16504
0
}
16505
16506
/*[clinic input]
16507
os.DirEntry.is_junction -> bool
16508
16509
Return True if the entry is a junction; cached per entry.
16510
[clinic start generated code]*/
16511
16512
static int
16513
os_DirEntry_is_junction_impl(DirEntry *self)
16514
/*[clinic end generated code: output=97f64d5d99eeccb5 input=4fc8e701eea118a1]*/
16515
0
{
16516
#ifdef MS_WINDOWS
16517
    return self->win32_lstat.st_reparse_tag == IO_REPARSE_TAG_MOUNT_POINT;
16518
#else
16519
0
    return 0;
16520
0
#endif
16521
0
}
16522
16523
static PyObject *
16524
DirEntry_fetch_stat(PyObject *module, DirEntry *self, int follow_symlinks)
16525
97.0k
{
16526
97.0k
    int result;
16527
97.0k
    STRUCT_STAT st;
16528
97.0k
    PyObject *ub;
16529
16530
#ifdef MS_WINDOWS
16531
    if (!PyUnicode_FSDecoder(self->path, &ub))
16532
        return NULL;
16533
    wchar_t *path = PyUnicode_AsWideCharString(ub, NULL);
16534
    Py_DECREF(ub);
16535
#else /* POSIX */
16536
97.0k
    if (!PyUnicode_FSConverter(self->path, &ub))
16537
0
        return NULL;
16538
97.0k
    const char *path = PyBytes_AS_STRING(ub);
16539
97.0k
    if (self->dir_fd != DEFAULT_DIR_FD) {
16540
97.0k
#ifdef HAVE_FSTATAT
16541
97.0k
      if (HAVE_FSTATAT_RUNTIME) {
16542
97.0k
        Py_BEGIN_ALLOW_THREADS
16543
97.0k
        result = fstatat(self->dir_fd, path, &st,
16544
97.0k
                         follow_symlinks ? 0 : AT_SYMLINK_NOFOLLOW);
16545
97.0k
        Py_END_ALLOW_THREADS
16546
97.0k
      } else
16547
16548
0
#endif /* HAVE_FSTATAT */
16549
0
      {
16550
0
        Py_DECREF(ub);
16551
0
        PyErr_SetString(PyExc_NotImplementedError, "can't fetch stat");
16552
0
        return NULL;
16553
0
      }
16554
97.0k
    }
16555
0
    else
16556
0
#endif
16557
0
    {
16558
0
        Py_BEGIN_ALLOW_THREADS
16559
0
        if (follow_symlinks) {
16560
0
            result = STAT(path, &st);
16561
0
        }
16562
0
        else {
16563
0
            result = LSTAT(path, &st);
16564
0
        }
16565
0
        Py_END_ALLOW_THREADS
16566
0
    }
16567
16568
97.0k
    int saved_errno = errno;
16569
#if defined(MS_WINDOWS)
16570
    PyMem_Free(path);
16571
#else
16572
97.0k
    Py_DECREF(ub);
16573
97.0k
#endif
16574
16575
97.0k
    if (result != 0) {
16576
0
        errno = saved_errno;
16577
0
        path_object_error(self->path);
16578
0
        return NULL;
16579
0
    }
16580
16581
97.0k
    return _pystat_fromstructstat(module, &st);
16582
97.0k
}
16583
16584
static PyObject *
16585
DirEntry_get_lstat(PyTypeObject *defining_class, DirEntry *self)
16586
97.0k
{
16587
97.0k
    if (!self->lstat) {
16588
97.0k
        PyObject *module = PyType_GetModule(defining_class);
16589
#ifdef MS_WINDOWS
16590
        self->lstat = _pystat_fromstructstat(module, &self->win32_lstat);
16591
#else /* POSIX */
16592
97.0k
        self->lstat = DirEntry_fetch_stat(module, self, 0);
16593
97.0k
#endif
16594
97.0k
    }
16595
97.0k
    return Py_XNewRef(self->lstat);
16596
97.0k
}
16597
16598
/*[clinic input]
16599
os.DirEntry.stat
16600
    defining_class: defining_class
16601
    /
16602
    *
16603
    follow_symlinks: bool = True
16604
16605
Return stat_result object for the entry; cached per entry.
16606
[clinic start generated code]*/
16607
16608
static PyObject *
16609
os_DirEntry_stat_impl(DirEntry *self, PyTypeObject *defining_class,
16610
                      int follow_symlinks)
16611
/*[clinic end generated code: output=23f803e19c3e780e input=e816273c4e67ee98]*/
16612
97.0k
{
16613
97.0k
    if (!follow_symlinks) {
16614
97.0k
        return DirEntry_get_lstat(defining_class, self);
16615
97.0k
    }
16616
16617
0
    if (!self->stat) {
16618
0
        int result = os_DirEntry_is_symlink_impl(self, defining_class);
16619
0
        if (result == -1) {
16620
0
            return NULL;
16621
0
        }
16622
0
        if (result) {
16623
0
            PyObject *module = PyType_GetModule(defining_class);
16624
0
            self->stat = DirEntry_fetch_stat(module, self, 1);
16625
0
        }
16626
0
        else {
16627
0
            self->stat = DirEntry_get_lstat(defining_class, self);
16628
0
        }
16629
0
    }
16630
16631
0
    return Py_XNewRef(self->stat);
16632
0
}
16633
16634
/* Set exception and return -1 on error, 0 for False, 1 for True */
16635
static int
16636
DirEntry_test_mode(PyTypeObject *defining_class, DirEntry *self,
16637
                   int follow_symlinks, unsigned short mode_bits)
16638
116k
{
16639
116k
    PyObject *stat = NULL;
16640
116k
    PyObject *st_mode = NULL;
16641
116k
    long mode;
16642
116k
    int result;
16643
116k
#if defined(MS_WINDOWS) || defined(HAVE_DIRENT_D_TYPE)
16644
116k
    int is_symlink;
16645
116k
    int need_stat;
16646
116k
#endif
16647
#ifdef MS_WINDOWS
16648
    unsigned long dir_bits;
16649
#endif
16650
16651
#ifdef MS_WINDOWS
16652
    is_symlink = (self->win32_lstat.st_mode & S_IFMT) == S_IFLNK;
16653
    need_stat = follow_symlinks && is_symlink;
16654
#elif defined(HAVE_DIRENT_D_TYPE)
16655
116k
    is_symlink = self->d_type == DT_LNK;
16656
116k
    need_stat = self->d_type == DT_UNKNOWN || (follow_symlinks && is_symlink);
16657
116k
#endif
16658
16659
116k
#if defined(MS_WINDOWS) || defined(HAVE_DIRENT_D_TYPE)
16660
116k
    if (need_stat) {
16661
0
#endif
16662
0
        stat = os_DirEntry_stat_impl(self, defining_class, follow_symlinks);
16663
0
        if (!stat) {
16664
0
            if (PyErr_ExceptionMatches(PyExc_FileNotFoundError)) {
16665
                /* If file doesn't exist (anymore), then return False
16666
                   (i.e., say it's not a file/directory) */
16667
0
                PyErr_Clear();
16668
0
                return 0;
16669
0
            }
16670
0
            goto error;
16671
0
        }
16672
0
        _posixstate* state = get_posix_state(PyType_GetModule(defining_class));
16673
0
        st_mode = PyObject_GetAttr(stat, state->st_mode);
16674
0
        if (!st_mode)
16675
0
            goto error;
16676
16677
0
        mode = PyLong_AsLong(st_mode);
16678
0
        if (mode == -1 && PyErr_Occurred())
16679
0
            goto error;
16680
0
        Py_CLEAR(st_mode);
16681
0
        Py_CLEAR(stat);
16682
0
        result = (mode & S_IFMT) == mode_bits;
16683
0
#if defined(MS_WINDOWS) || defined(HAVE_DIRENT_D_TYPE)
16684
0
    }
16685
116k
    else if (is_symlink) {
16686
0
        assert(mode_bits != S_IFLNK);
16687
0
        result = 0;
16688
0
    }
16689
116k
    else {
16690
116k
        assert(mode_bits == S_IFDIR || mode_bits == S_IFREG);
16691
#ifdef MS_WINDOWS
16692
        dir_bits = self->win32_lstat.st_file_attributes & FILE_ATTRIBUTE_DIRECTORY;
16693
        if (mode_bits == S_IFDIR)
16694
            result = dir_bits != 0;
16695
        else
16696
            result = dir_bits == 0;
16697
#else /* POSIX */
16698
116k
        if (mode_bits == S_IFDIR)
16699
116k
            result = self->d_type == DT_DIR;
16700
0
        else
16701
0
            result = self->d_type == DT_REG;
16702
116k
#endif
16703
116k
    }
16704
116k
#endif
16705
16706
116k
    return result;
16707
16708
0
error:
16709
0
    Py_XDECREF(st_mode);
16710
0
    Py_XDECREF(stat);
16711
0
    return -1;
16712
116k
}
16713
16714
/*[clinic input]
16715
os.DirEntry.is_dir -> bool
16716
    defining_class: defining_class
16717
    /
16718
    *
16719
    follow_symlinks: bool = True
16720
16721
Return True if the entry is a directory; cached per entry.
16722
[clinic start generated code]*/
16723
16724
static int
16725
os_DirEntry_is_dir_impl(DirEntry *self, PyTypeObject *defining_class,
16726
                        int follow_symlinks)
16727
/*[clinic end generated code: output=0cd453b9c0987fdf input=1a4ffd6dec9920cb]*/
16728
116k
{
16729
116k
    return DirEntry_test_mode(defining_class, self, follow_symlinks, S_IFDIR);
16730
116k
}
16731
16732
/*[clinic input]
16733
os.DirEntry.is_file -> bool
16734
    defining_class: defining_class
16735
    /
16736
    *
16737
    follow_symlinks: bool = True
16738
16739
Return True if the entry is a file; cached per entry.
16740
[clinic start generated code]*/
16741
16742
static int
16743
os_DirEntry_is_file_impl(DirEntry *self, PyTypeObject *defining_class,
16744
                         int follow_symlinks)
16745
/*[clinic end generated code: output=f7c277ab5ba80908 input=0a64c5a12e802e3b]*/
16746
0
{
16747
0
    return DirEntry_test_mode(defining_class, self, follow_symlinks, S_IFREG);
16748
0
}
16749
16750
/*[clinic input]
16751
os.DirEntry.inode
16752
16753
Return inode of the entry; cached per entry.
16754
[clinic start generated code]*/
16755
16756
static PyObject *
16757
os_DirEntry_inode_impl(DirEntry *self)
16758
/*[clinic end generated code: output=156bb3a72162440e input=3ee7b872ae8649f0]*/
16759
0
{
16760
#ifdef MS_WINDOWS
16761
    if (!self->got_file_index) {
16762
        PyObject *unicode;
16763
        STRUCT_STAT stat;
16764
        int result;
16765
16766
        if (!PyUnicode_FSDecoder(self->path, &unicode))
16767
            return NULL;
16768
        wchar_t *path = PyUnicode_AsWideCharString(unicode, NULL);
16769
        Py_DECREF(unicode);
16770
        result = LSTAT(path, &stat);
16771
16772
        int saved_errno = errno;
16773
        PyMem_Free(path);
16774
16775
        if (result != 0) {
16776
            errno = saved_errno;
16777
            return path_object_error(self->path);
16778
        }
16779
16780
        self->win32_file_index = stat.st_ino;
16781
        self->win32_file_index_high = stat.st_ino_high;
16782
        self->got_file_index = 1;
16783
    }
16784
    return _pystat_l128_from_l64_l64(self->win32_file_index, self->win32_file_index_high);
16785
#else /* POSIX */
16786
0
    static_assert(sizeof(unsigned long long) >= sizeof(self->d_ino),
16787
0
                  "DirEntry.d_ino is larger than unsigned long long");
16788
0
    return PyLong_FromUnsignedLongLong(self->d_ino);
16789
0
#endif
16790
0
}
16791
16792
static PyObject *
16793
DirEntry_repr(PyObject *op)
16794
0
{
16795
0
    DirEntry *self = DirEntry_CAST(op);
16796
0
    return PyUnicode_FromFormat("<DirEntry %R>", self->name);
16797
0
}
16798
16799
/*[clinic input]
16800
os.DirEntry.__fspath__
16801
16802
Returns the path for the entry.
16803
[clinic start generated code]*/
16804
16805
static PyObject *
16806
os_DirEntry___fspath___impl(DirEntry *self)
16807
/*[clinic end generated code: output=6dd7f7ef752e6f4f input=3c49d0cf38df4fac]*/
16808
0
{
16809
0
    return Py_NewRef(self->path);
16810
0
}
16811
16812
static PyMemberDef DirEntry_members[] = {
16813
    {"name", Py_T_OBJECT_EX, offsetof(DirEntry, name), Py_READONLY,
16814
     "the entry's base filename, relative to scandir() \"path\" argument"},
16815
    {"path", Py_T_OBJECT_EX, offsetof(DirEntry, path), Py_READONLY,
16816
     "the entry's full path name; equivalent to\nos.path.join(scandir_path, entry.name)"},
16817
    {NULL}
16818
};
16819
16820
#include "clinic/posixmodule.c.h"
16821
16822
static PyMethodDef DirEntry_methods[] = {
16823
    OS_DIRENTRY_IS_DIR_METHODDEF
16824
    OS_DIRENTRY_IS_FILE_METHODDEF
16825
    OS_DIRENTRY_IS_SYMLINK_METHODDEF
16826
    OS_DIRENTRY_IS_JUNCTION_METHODDEF
16827
    OS_DIRENTRY_STAT_METHODDEF
16828
    OS_DIRENTRY_INODE_METHODDEF
16829
    OS_DIRENTRY___FSPATH___METHODDEF
16830
    {"__class_getitem__",       Py_GenericAlias,
16831
    METH_O|METH_CLASS,          PyDoc_STR("DirEntry is generic over the type of the path (str or bytes)")},
16832
    {NULL}
16833
};
16834
16835
static PyType_Slot DirEntryType_slots[] = {
16836
    {Py_tp_dealloc, DirEntry_dealloc},
16837
    {Py_tp_repr, DirEntry_repr},
16838
    {Py_tp_methods, DirEntry_methods},
16839
    {Py_tp_members, DirEntry_members},
16840
    {0, 0},
16841
};
16842
16843
static PyType_Spec DirEntryType_spec = {
16844
    .name = "os.DirEntry",
16845
    .basicsize = sizeof(DirEntry),
16846
    .flags = (
16847
        Py_TPFLAGS_DEFAULT
16848
        | Py_TPFLAGS_DISALLOW_INSTANTIATION
16849
        | Py_TPFLAGS_IMMUTABLETYPE
16850
    ),
16851
    .slots = DirEntryType_slots
16852
};
16853
16854
16855
#ifdef MS_WINDOWS
16856
16857
static wchar_t *
16858
join_path_filenameW(const wchar_t *path_wide, const wchar_t *filename,
16859
                    int normalize)
16860
{
16861
    Py_ssize_t path_len;
16862
    wchar_t *result;
16863
    wchar_t *path_allocated = NULL;
16864
16865
    if (!path_wide) { /* Default arg: "." */
16866
        path_wide = L".";
16867
        path_len = 1;
16868
    }
16869
    else {
16870
        path_len = wcslen(path_wide);
16871
    }
16872
16873
    if (path_len == 0) {
16874
        result = PyMem_New(wchar_t, 1);
16875
        if (result == NULL) {
16876
            PyErr_NoMemory();
16877
            return NULL;
16878
        }
16879
        result[0] = L'\0';
16880
        return result;
16881
    }
16882
16883
    if (normalize && !is_extended_path(path_wide)) {
16884
        int err = _PyOS_getfullpathname(path_wide, &path_allocated);
16885
        if (err < 0) {
16886
            PyErr_SetFromWindowsErr(0);
16887
            return NULL;
16888
        }
16889
        if (path_allocated == NULL) {
16890
            PyErr_NoMemory();
16891
            return NULL;
16892
        }
16893
        path_wide = path_allocated;
16894
        path_len = wcslen(path_wide);
16895
    }
16896
16897
    size_t size = (size_t)path_len + 1 + wcslen(filename) + 1;
16898
    result = PyMem_New(wchar_t, size);
16899
    if (result == NULL) {
16900
        PyMem_RawFree(path_allocated);
16901
        PyErr_NoMemory();
16902
        return NULL;
16903
    }
16904
    wcscpy(result, path_wide);
16905
    wchar_t ch = result[path_len - 1];
16906
    if (ch != SEP && ch != ALTSEP && ch != L':') {
16907
        result[path_len++] = SEP;
16908
    }
16909
    wcscpy(result + path_len, filename);
16910
    PyMem_RawFree(path_allocated);
16911
    return result;
16912
}
16913
16914
static PyObject *
16915
DirEntry_from_find_data(PyObject *module, path_t *path, WIN32_FIND_DATAW *dataW)
16916
{
16917
    DirEntry *entry;
16918
    FILE_BASIC_INFO basic_info;
16919
    FILE_STANDARD_INFO standard_info;
16920
    ULONG reparse_tag;
16921
    wchar_t *joined_path;
16922
16923
    PyObject *DirEntryType = get_posix_state(module)->DirEntryType;
16924
    entry = PyObject_New(DirEntry, (PyTypeObject *)DirEntryType);
16925
    if (!entry)
16926
        return NULL;
16927
    entry->name = NULL;
16928
    entry->path = NULL;
16929
    entry->stat = NULL;
16930
    entry->lstat = NULL;
16931
    entry->got_file_index = 0;
16932
16933
    entry->name = PyUnicode_FromWideChar(dataW->cFileName, -1);
16934
    if (!entry->name)
16935
        goto error;
16936
    int return_bytes = path->wide && PyBytes_Check(path->object);
16937
    if (return_bytes) {
16938
        Py_SETREF(entry->name, PyUnicode_EncodeFSDefault(entry->name));
16939
        if (!entry->name)
16940
            goto error;
16941
    }
16942
16943
    joined_path = join_path_filenameW(path->wide, dataW->cFileName, 0);
16944
    if (!joined_path)
16945
        goto error;
16946
16947
    entry->path = PyUnicode_FromWideChar(joined_path, -1);
16948
    PyMem_Free(joined_path);
16949
    if (!entry->path)
16950
        goto error;
16951
    if (return_bytes) {
16952
        Py_SETREF(entry->path, PyUnicode_EncodeFSDefault(entry->path));
16953
        if (!entry->path)
16954
            goto error;
16955
    }
16956
16957
    find_data_to_file_info(dataW, &basic_info, &standard_info, &reparse_tag);
16958
    _Py_attribute_data_to_stat(&standard_info, reparse_tag, &basic_info, NULL, &entry->win32_lstat);
16959
16960
    /* ctime is only deprecated from 3.12, so we copy birthtime across */
16961
    entry->win32_lstat.st_ctime = entry->win32_lstat.st_birthtime;
16962
    entry->win32_lstat.st_ctime_nsec = entry->win32_lstat.st_birthtime_nsec;
16963
16964
    return (PyObject *)entry;
16965
16966
error:
16967
    Py_DECREF(entry);
16968
    return NULL;
16969
}
16970
16971
#else /* POSIX */
16972
16973
static char *
16974
join_path_filename(const char *path_narrow, const char* filename, Py_ssize_t filename_len)
16975
0
{
16976
0
    Py_ssize_t path_len;
16977
0
    Py_ssize_t size;
16978
0
    char *result;
16979
16980
0
    if (!path_narrow) { /* Default arg: "." */
16981
0
        path_narrow = ".";
16982
0
        path_len = 1;
16983
0
    }
16984
0
    else {
16985
0
        path_len = strlen(path_narrow);
16986
0
    }
16987
16988
0
    if (filename_len == -1)
16989
0
        filename_len = strlen(filename);
16990
16991
    /* The +1's are for the path separator and the NUL */
16992
0
    size = path_len + 1 + filename_len + 1;
16993
0
    result = PyMem_New(char, size);
16994
0
    if (!result) {
16995
0
        PyErr_NoMemory();
16996
0
        return NULL;
16997
0
    }
16998
0
    strcpy(result, path_narrow);
16999
0
    if (path_len > 0 && result[path_len - 1] != '/')
17000
0
        result[path_len++] = '/';
17001
0
    strcpy(result + path_len, filename);
17002
0
    return result;
17003
0
}
17004
17005
static PyObject *
17006
DirEntry_from_posix_info(PyObject *module, path_t *path, const char *name,
17007
                         Py_ssize_t name_len, ino_t d_ino
17008
#ifdef HAVE_DIRENT_D_TYPE
17009
                         , unsigned char d_type
17010
#endif
17011
                         )
17012
116k
{
17013
116k
    DirEntry *entry;
17014
116k
    char *joined_path;
17015
17016
116k
    PyObject *DirEntryType = get_posix_state(module)->DirEntryType;
17017
116k
    entry = PyObject_New(DirEntry, (PyTypeObject *)DirEntryType);
17018
116k
    if (!entry)
17019
0
        return NULL;
17020
116k
    entry->name = NULL;
17021
116k
    entry->path = NULL;
17022
116k
    entry->stat = NULL;
17023
116k
    entry->lstat = NULL;
17024
17025
116k
    if (path->is_fd) {
17026
116k
        entry->dir_fd = path->fd;
17027
116k
        joined_path = NULL;
17028
116k
    }
17029
0
    else {
17030
0
        entry->dir_fd = DEFAULT_DIR_FD;
17031
0
        joined_path = join_path_filename(path->narrow, name, name_len);
17032
0
        if (!joined_path)
17033
0
            goto error;
17034
0
    }
17035
17036
116k
    if (!path->narrow || !PyBytes_Check(path->object)) {
17037
116k
        entry->name = PyUnicode_DecodeFSDefaultAndSize(name, name_len);
17038
116k
        if (joined_path)
17039
0
            entry->path = PyUnicode_DecodeFSDefault(joined_path);
17040
116k
    }
17041
0
    else {
17042
0
        entry->name = PyBytes_FromStringAndSize(name, name_len);
17043
0
        if (joined_path)
17044
0
            entry->path = PyBytes_FromString(joined_path);
17045
0
    }
17046
116k
    PyMem_Free(joined_path);
17047
116k
    if (!entry->name)
17048
0
        goto error;
17049
17050
116k
    if (path->is_fd) {
17051
116k
        entry->path = Py_NewRef(entry->name);
17052
116k
    }
17053
0
    else if (!entry->path)
17054
0
        goto error;
17055
17056
116k
#ifdef HAVE_DIRENT_D_TYPE
17057
116k
    entry->d_type = d_type;
17058
116k
#endif
17059
116k
    entry->d_ino = d_ino;
17060
17061
116k
    return (PyObject *)entry;
17062
17063
0
error:
17064
0
    Py_XDECREF(entry);
17065
0
    return NULL;
17066
116k
}
17067
17068
#endif
17069
17070
17071
typedef struct {
17072
    PyObject_HEAD
17073
    path_t path;
17074
#ifdef MS_WINDOWS
17075
    HANDLE handle;
17076
    WIN32_FIND_DATAW file_data;
17077
    int first_time;
17078
#else /* POSIX */
17079
    DIR *dirp;
17080
#endif
17081
#ifdef HAVE_FDOPENDIR
17082
    int fd;
17083
#endif
17084
    // Sharing the iterator between threads is subject to race conditions:
17085
    // which entries each thread receives is unspecified.  It must not
17086
    // corrupt the iterator or crash.  Since we don't want close() to be
17087
    // held up by a blocking directory read, we set the 'closed' flag if
17088
    // there are reads in progress.
17089
    PyMutex read_mutex;
17090
    uint8_t closed;
17091
} ScandirIterator;
17092
17093
421k
#define ScandirIterator_CAST(op)    ((ScandirIterator *)(op))
17094
17095
#ifdef MS_WINDOWS
17096
17097
static int
17098
ScandirIterator_is_closed(ScandirIterator *iterator)
17099
{
17100
    return _Py_atomic_load_uint8(&iterator->closed);
17101
}
17102
17103
static void
17104
ScandirIterator_closedir(ScandirIterator *iterator)
17105
{
17106
    HANDLE handle = INVALID_HANDLE_VALUE;
17107
17108
    _Py_atomic_store_uint8(&iterator->closed, 1);
17109
    if (PyMutex_LockFast(&iterator->read_mutex)) {
17110
        // no reads in progress, we can close the handle
17111
        handle = iterator->handle;
17112
        iterator->handle = INVALID_HANDLE_VALUE;
17113
        PyMutex_Unlock(&iterator->read_mutex);
17114
    }
17115
17116
    if (handle != INVALID_HANDLE_VALUE) {
17117
        Py_BEGIN_ALLOW_THREADS
17118
        FindClose(handle);
17119
        Py_END_ALLOW_THREADS
17120
    }
17121
}
17122
17123
static PyObject *
17124
ScandirIterator_iternext(PyObject *op)
17125
{
17126
    ScandirIterator *iterator = ScandirIterator_CAST(op);
17127
    WIN32_FIND_DATAW file_data;
17128
    BOOL success;
17129
    DWORD error = ERROR_SUCCESS;
17130
    int found = 0;
17131
17132
    PyMutex_Lock(&iterator->read_mutex);
17133
    /* Happens if the iterator is iterated twice, or closed explicitly */
17134
    while (iterator->handle != INVALID_HANDLE_VALUE &&
17135
           !_Py_atomic_load_uint8_relaxed(&iterator->closed))
17136
    {
17137
        if (!iterator->first_time) {
17138
            Py_BEGIN_ALLOW_THREADS
17139
            success = FindNextFileW(iterator->handle, &iterator->file_data);
17140
            if (!success) {
17141
                error = GetLastError();
17142
            }
17143
            Py_END_ALLOW_THREADS
17144
            if (!success) {
17145
                break;
17146
            }
17147
        }
17148
        iterator->first_time = 0;
17149
17150
        /* Skip over . and .. */
17151
        if (wcscmp(iterator->file_data.cFileName, L".") != 0 &&
17152
            wcscmp(iterator->file_data.cFileName, L"..") != 0)
17153
        {
17154
            file_data = iterator->file_data;
17155
            found = 1;
17156
            break;
17157
        }
17158
17159
        /* Loop till we get a non-dot directory or finish iterating */
17160
    }
17161
    PyMutex_Unlock(&iterator->read_mutex);
17162
17163
    if (found && ScandirIterator_is_closed(iterator)) {
17164
        ScandirIterator_closedir(iterator); // deferred close
17165
    }
17166
17167
    if (found) {
17168
        PyObject *module = PyType_GetModule(Py_TYPE(iterator));
17169
        PyObject *entry = DirEntry_from_find_data(module, &iterator->path, &file_data);
17170
        if (entry != NULL) {
17171
            return entry;
17172
        }
17173
    }
17174
    else if (error != ERROR_SUCCESS && error != ERROR_NO_MORE_FILES) {
17175
        SetLastError(error);
17176
        path_error(&iterator->path);
17177
    }
17178
17179
    /* Error or no more files */
17180
    ScandirIterator_closedir(iterator);
17181
    return NULL;
17182
}
17183
17184
#else /* POSIX */
17185
17186
static int
17187
ScandirIterator_is_closed(ScandirIterator *iterator)
17188
218k
{
17189
218k
    return _Py_atomic_load_uint8(&iterator->closed);
17190
218k
}
17191
17192
static void
17193
ScandirIterator_closedir(ScandirIterator *iterator)
17194
304k
{
17195
304k
    DIR *dirp = NULL;
17196
17197
304k
    _Py_atomic_store_uint8(&iterator->closed, 1);
17198
304k
    if (PyMutex_LockFast(&iterator->read_mutex)) {
17199
        // no reads in progress, we can close dirp
17200
304k
        dirp = iterator->dirp;
17201
304k
        iterator->dirp = NULL;
17202
304k
        PyMutex_Unlock(&iterator->read_mutex);
17203
304k
    }
17204
17205
304k
    if (dirp != NULL) {
17206
101k
        Py_BEGIN_ALLOW_THREADS
17207
101k
#ifdef HAVE_FDOPENDIR
17208
101k
        if (iterator->path.is_fd) {
17209
101k
            rewinddir(dirp);
17210
101k
        }
17211
101k
#endif
17212
101k
        closedir(dirp);
17213
101k
        Py_END_ALLOW_THREADS
17214
101k
    }
17215
304k
}
17216
17217
static PyObject *
17218
ScandirIterator_iternext(PyObject *op)
17219
218k
{
17220
218k
    ScandirIterator *iterator = ScandirIterator_CAST(op);
17221
218k
    struct dirent *direntp;
17222
218k
    Py_ssize_t name_len = 0;
17223
218k
    int is_dot;
17224
218k
    int found = 0;
17225
218k
    int error = 0;
17226
218k
    int no_memory = 0;
17227
218k
    char namebuf[256];
17228
218k
    char *name = namebuf;
17229
218k
    ino_t d_ino = 0;
17230
218k
#ifdef HAVE_DIRENT_D_TYPE
17231
218k
    unsigned char d_type = 0;
17232
218k
#endif
17233
17234
218k
    PyMutex_Lock(&iterator->read_mutex);
17235
    /* Happens if the iterator is iterated twice, or closed explicitly */
17236
421k
    while (iterator->dirp != NULL &&
17237
421k
           !_Py_atomic_load_uint8_relaxed(&iterator->closed))
17238
421k
    {
17239
421k
        Py_BEGIN_ALLOW_THREADS
17240
421k
        errno = 0;
17241
421k
        direntp = readdir(iterator->dirp);
17242
421k
        if (direntp == NULL) {
17243
101k
            error = errno;
17244
101k
        }
17245
421k
        Py_END_ALLOW_THREADS
17246
17247
421k
        if (!direntp) {
17248
101k
            break;
17249
101k
        }
17250
17251
        /* Skip over . and .. */
17252
319k
        name_len = NAMLEN(direntp);
17253
319k
        is_dot = direntp->d_name[0] == '.' &&
17254
203k
                 (name_len == 1 || (direntp->d_name[1] == '.' && name_len == 2));
17255
319k
        if (!is_dot) {
17256
116k
            if ((size_t)name_len >= sizeof(namebuf)) {
17257
0
                name = PyMem_RawMalloc(name_len + 1);
17258
0
                if (name == NULL) {
17259
0
                    no_memory = 1;
17260
0
                    break;
17261
0
                }
17262
0
            }
17263
116k
            memcpy(name, direntp->d_name, name_len);
17264
116k
            name[name_len] = '\0';
17265
116k
            d_ino = direntp->d_ino;
17266
116k
#ifdef HAVE_DIRENT_D_TYPE
17267
116k
            d_type = direntp->d_type;
17268
116k
#endif
17269
116k
            found = 1;
17270
116k
            break;
17271
116k
        }
17272
17273
        /* Loop till we get a non-dot directory or finish iterating */
17274
319k
    }
17275
218k
    PyMutex_Unlock(&iterator->read_mutex);
17276
17277
218k
    if (found && ScandirIterator_is_closed(iterator)) {
17278
0
        ScandirIterator_closedir(iterator); // deferred close
17279
0
    }
17280
17281
218k
    if (found) {
17282
116k
        PyObject *module = PyType_GetModule(Py_TYPE(iterator));
17283
116k
        PyObject *entry = DirEntry_from_posix_info(module,
17284
116k
                                                   &iterator->path, name,
17285
116k
                                                   name_len, d_ino
17286
116k
#ifdef HAVE_DIRENT_D_TYPE
17287
116k
                                                   , d_type
17288
116k
#endif
17289
116k
                                                  );
17290
116k
        if (name != namebuf) {
17291
0
            PyMem_RawFree(name);
17292
0
        }
17293
116k
        if (entry != NULL) {
17294
116k
            return entry;
17295
116k
        }
17296
116k
    }
17297
101k
    else if (no_memory) {
17298
0
        PyErr_NoMemory();
17299
0
    }
17300
101k
    else if (error != 0) {
17301
0
        errno = error;
17302
0
        path_error(&iterator->path);
17303
0
    }
17304
17305
    /* Error or no more files */
17306
101k
    ScandirIterator_closedir(iterator);
17307
101k
    return NULL;
17308
218k
}
17309
17310
#endif
17311
17312
static PyObject *
17313
ScandirIterator_close(PyObject *op, PyObject *Py_UNUSED(dummy))
17314
0
{
17315
0
    ScandirIterator *self = ScandirIterator_CAST(op);
17316
0
    ScandirIterator_closedir(self);
17317
0
    Py_RETURN_NONE;
17318
0
}
17319
17320
static PyObject *
17321
ScandirIterator_enter(PyObject *self, PyObject *Py_UNUSED(dummy))
17322
101k
{
17323
101k
    return Py_NewRef(self);
17324
101k
}
17325
17326
/*[clinic input]
17327
os.ScandirIterator.__exit__
17328
17329
    *exc_info: array
17330
17331
Close the scandir iterator.
17332
[clinic start generated code]*/
17333
17334
static PyObject *
17335
os_ScandirIterator___exit___impl(PyObject *self, PyObject * const *exc_info,
17336
                                 Py_ssize_t exc_info_length)
17337
/*[clinic end generated code: output=5d3941725a7c97c7 input=ff3ffe83ae605a36]*/
17338
101k
{
17339
101k
    ScandirIterator_closedir(ScandirIterator_CAST(self));
17340
101k
    Py_RETURN_NONE;
17341
101k
}
17342
17343
static void
17344
ScandirIterator_finalize(PyObject *op)
17345
101k
{
17346
101k
    ScandirIterator *iterator = ScandirIterator_CAST(op);
17347
    /* Save the current exception, if any. */
17348
101k
    PyObject *exc = PyErr_GetRaisedException();
17349
17350
101k
    int was_closed = ScandirIterator_is_closed(iterator);
17351
17352
101k
    ScandirIterator_closedir(iterator);
17353
17354
101k
    if (!was_closed) {
17355
0
        if (PyErr_ResourceWarning(op, 1,
17356
0
                                  "unclosed scandir iterator %R", iterator))
17357
0
        {
17358
            /* Spurious errors can appear at shutdown */
17359
0
            if (PyErr_ExceptionMatches(PyExc_Warning)) {
17360
0
                PyErr_FormatUnraisable("Exception ignored while finalizing "
17361
0
                                       "scandir iterator %R", iterator);
17362
0
            }
17363
0
        }
17364
0
    }
17365
17366
101k
    path_cleanup(&iterator->path);
17367
17368
    /* Restore the saved exception. */
17369
101k
    PyErr_SetRaisedException(exc);
17370
101k
}
17371
17372
static void
17373
ScandirIterator_dealloc(PyObject *op)
17374
101k
{
17375
101k
    PyTypeObject *tp = Py_TYPE(op);
17376
101k
    if (PyObject_CallFinalizerFromDealloc(op) < 0)
17377
0
        return;
17378
17379
101k
    freefunc free_func = PyType_GetSlot(tp, Py_tp_free);
17380
101k
    free_func(op);
17381
101k
    Py_DECREF(tp);
17382
101k
}
17383
17384
static PyMethodDef ScandirIterator_methods[] = {
17385
    {"__enter__", ScandirIterator_enter, METH_NOARGS},
17386
    OS_SCANDIRITERATOR___EXIT___METHODDEF
17387
    {"close", ScandirIterator_close, METH_NOARGS},
17388
    {NULL}
17389
};
17390
17391
static PyType_Slot ScandirIteratorType_slots[] = {
17392
    {Py_tp_dealloc, ScandirIterator_dealloc},
17393
    {Py_tp_finalize, ScandirIterator_finalize},
17394
    {Py_tp_iter, PyObject_SelfIter},
17395
    {Py_tp_iternext, ScandirIterator_iternext},
17396
    {Py_tp_methods, ScandirIterator_methods},
17397
    {0, 0},
17398
};
17399
17400
static PyType_Spec ScandirIteratorType_spec = {
17401
    .name = "os.ScandirIterator",
17402
    .basicsize = sizeof(ScandirIterator),
17403
    // bpo-40549: Py_TPFLAGS_BASETYPE should not be used, since
17404
    // PyType_GetModule(Py_TYPE(self)) doesn't work on a subclass instance.
17405
    .flags = (
17406
        Py_TPFLAGS_DEFAULT
17407
        | Py_TPFLAGS_HAVE_FINALIZE
17408
        | Py_TPFLAGS_DISALLOW_INSTANTIATION
17409
        | Py_TPFLAGS_IMMUTABLETYPE
17410
    ),
17411
    .slots = ScandirIteratorType_slots
17412
};
17413
17414
/*[clinic input]
17415
os.scandir
17416
17417
    path : path_t(nullable=True, allow_fd='PATH_HAVE_FDOPENDIR') = None
17418
17419
Return an iterator of DirEntry objects for given path.
17420
17421
path can be specified as either str, bytes, or a path-like object.  If
17422
path is bytes, the names of yielded DirEntry objects will also be bytes;
17423
in all other circumstances they will be str.
17424
17425
If path is None, uses the path='.'.
17426
[clinic start generated code]*/
17427
17428
static PyObject *
17429
os_scandir_impl(PyObject *module, path_t *path)
17430
/*[clinic end generated code: output=6eb2668b675ca89e input=6ab9600993f51577]*/
17431
101k
{
17432
101k
    ScandirIterator *iterator;
17433
#ifdef MS_WINDOWS
17434
    wchar_t *path_strW;
17435
#else
17436
101k
    const char *path_str;
17437
101k
#ifdef HAVE_FDOPENDIR
17438
101k
    int fd = -1;
17439
101k
#endif
17440
101k
#endif
17441
17442
101k
    if (PySys_Audit("os.scandir", "O",
17443
101k
                    path->object ? path->object : Py_None) < 0) {
17444
0
        return NULL;
17445
0
    }
17446
17447
101k
    PyObject *ScandirIteratorType = get_posix_state(module)->ScandirIteratorType;
17448
101k
    iterator = PyObject_New(ScandirIterator, (PyTypeObject *)ScandirIteratorType);
17449
101k
    if (!iterator)
17450
0
        return NULL;
17451
17452
101k
    iterator->read_mutex = (PyMutex){0};
17453
101k
    iterator->closed = 1;
17454
#ifdef MS_WINDOWS
17455
    iterator->handle = INVALID_HANDLE_VALUE;
17456
#else
17457
101k
    iterator->dirp = NULL;
17458
101k
#endif
17459
17460
    /* Move the ownership to iterator->path */
17461
101k
    memcpy(&iterator->path, path, sizeof(path_t));
17462
101k
    memset(path, 0, sizeof(path_t));
17463
17464
#ifdef MS_WINDOWS
17465
    iterator->first_time = 1;
17466
17467
    path_strW = join_path_filenameW(iterator->path.wide, L"*.*", 1);
17468
    if (!path_strW)
17469
        goto error;
17470
17471
    Py_BEGIN_ALLOW_THREADS
17472
    iterator->handle = FindFirstFileW(path_strW, &iterator->file_data);
17473
    Py_END_ALLOW_THREADS
17474
17475
    if (iterator->handle == INVALID_HANDLE_VALUE) {
17476
        path_error(&iterator->path);
17477
        PyMem_Free(path_strW);
17478
        goto error;
17479
    }
17480
    PyMem_Free(path_strW);
17481
#else /* POSIX */
17482
101k
    errno = 0;
17483
101k
#ifdef HAVE_FDOPENDIR
17484
101k
    if (iterator->path.is_fd) {
17485
101k
      if (HAVE_FDOPENDIR_RUNTIME) {
17486
        /* closedir() closes the FD, so we duplicate it */
17487
101k
        fd = _Py_dup(iterator->path.fd);
17488
101k
        if (fd == -1)
17489
0
            goto error;
17490
17491
101k
        Py_BEGIN_ALLOW_THREADS
17492
101k
        iterator->dirp = fdopendir(fd);
17493
101k
        Py_END_ALLOW_THREADS
17494
101k
      } else {
17495
0
        PyErr_SetString(PyExc_TypeError,
17496
0
            "scandir: path should be string, bytes, os.PathLike or None, not int");
17497
0
        return NULL;
17498
0
      }
17499
101k
    }
17500
0
    else
17501
0
#endif
17502
0
    {
17503
0
        if (iterator->path.narrow)
17504
0
            path_str = iterator->path.narrow;
17505
0
        else
17506
0
            path_str = ".";
17507
17508
0
        Py_BEGIN_ALLOW_THREADS
17509
0
        iterator->dirp = opendir(path_str);
17510
0
        Py_END_ALLOW_THREADS
17511
0
    }
17512
17513
101k
    if (!iterator->dirp) {
17514
0
        path_error(&iterator->path);
17515
0
#ifdef HAVE_FDOPENDIR
17516
0
        if (fd != -1) {
17517
0
            Py_BEGIN_ALLOW_THREADS
17518
0
            close(fd);
17519
0
            Py_END_ALLOW_THREADS
17520
0
        }
17521
0
#endif
17522
0
        goto error;
17523
0
    }
17524
101k
#endif
17525
17526
101k
    iterator->closed = 0;
17527
101k
    return (PyObject *)iterator;
17528
17529
0
error:
17530
0
    Py_DECREF(iterator);
17531
0
    return NULL;
17532
101k
}
17533
17534
/*
17535
    Return the file system path representation of the object.
17536
17537
    If the object is str or bytes, then allow it to pass through with
17538
    an incremented refcount. If the object defines __fspath__(), then
17539
    return the result of that method. All other types raise a TypeError.
17540
*/
17541
PyObject *
17542
PyOS_FSPath(PyObject *path)
17543
1.00M
{
17544
    /* For error message reasons, this function is manually inlined in
17545
       path_converter(). */
17546
1.00M
    PyObject *func = NULL;
17547
1.00M
    PyObject *path_repr = NULL;
17548
17549
1.00M
    if (PyUnicode_Check(path) || PyBytes_Check(path)) {
17550
1.00M
        return Py_NewRef(path);
17551
1.00M
    }
17552
17553
371
    func = _PyObject_LookupSpecial(path, &_Py_ID(__fspath__));
17554
371
    if ((NULL == func) || (func == Py_None)) {
17555
0
        return PyErr_Format(PyExc_TypeError,
17556
0
                            "expected str, bytes or os.PathLike object, "
17557
0
                            "not %.200s",
17558
0
                            _PyType_Name(Py_TYPE(path)));
17559
0
    }
17560
17561
371
    path_repr = _PyObject_CallNoArgs(func);
17562
371
    Py_DECREF(func);
17563
371
    if (NULL == path_repr) {
17564
0
        return NULL;
17565
0
    }
17566
17567
371
    if (!(PyUnicode_Check(path_repr) || PyBytes_Check(path_repr))) {
17568
0
        PyErr_Format(PyExc_TypeError,
17569
0
                     "expected %.200s.__fspath__() to return str or bytes, "
17570
0
                     "not %.200s", _PyType_Name(Py_TYPE(path)),
17571
0
                     _PyType_Name(Py_TYPE(path_repr)));
17572
0
        Py_DECREF(path_repr);
17573
0
        return NULL;
17574
0
    }
17575
17576
371
    return path_repr;
17577
371
}
17578
17579
/*[clinic input]
17580
os.fspath
17581
17582
    path: object
17583
17584
Return the file system path representation of the object.
17585
17586
If the object is str or bytes, then allow it to pass through as-is.  If
17587
the object defines __fspath__(), then return the result of that method.
17588
All other types raise a TypeError.
17589
[clinic start generated code]*/
17590
17591
static PyObject *
17592
os_fspath_impl(PyObject *module, PyObject *path)
17593
/*[clinic end generated code: output=c3c3b78ecff2914f input=d3c54404240d5da0]*/
17594
747k
{
17595
747k
    return PyOS_FSPath(path);
17596
747k
}
17597
17598
#if defined(HAVE_GETRANDOM) || defined(HAVE_GETRANDOM_SYSCALL)
17599
/*[clinic input]
17600
os.getrandom
17601
17602
    size: Py_ssize_t
17603
    flags: unsigned_int(bitwise=True) = 0
17604
17605
Obtain a series of random bytes.
17606
[clinic start generated code]*/
17607
17608
static PyObject *
17609
os_getrandom_impl(PyObject *module, Py_ssize_t size, unsigned int flags)
17610
/*[clinic end generated code: output=c2163c05f0e1d0a1 input=e0174983f5703f82]*/
17611
0
{
17612
0
    if (size < 0) {
17613
0
        errno = EINVAL;
17614
0
        return posix_error();
17615
0
    }
17616
17617
0
    PyBytesWriter *writer = PyBytesWriter_Create(size);
17618
0
    if (writer == NULL) {
17619
0
        return NULL;
17620
0
    }
17621
0
    void *data = PyBytesWriter_GetData(writer);
17622
17623
0
    Py_ssize_t n;
17624
0
    while (1) {
17625
0
#ifdef HAVE_GETRANDOM
17626
0
        n = getrandom(data, size, flags);
17627
#else
17628
        n = syscall(SYS_getrandom, data, size, flags);
17629
#endif
17630
0
        if (n < 0 && errno == EINTR) {
17631
0
            if (PyErr_CheckSignals() < 0) {
17632
0
                goto error;
17633
0
            }
17634
17635
            /* getrandom() was interrupted by a signal: retry */
17636
0
            continue;
17637
0
        }
17638
0
        break;
17639
0
    }
17640
17641
0
    if (n < 0) {
17642
0
        PyErr_SetFromErrno(PyExc_OSError);
17643
0
        goto error;
17644
0
    }
17645
17646
0
    _Py_MSAN_UNPOISON(data, size);
17647
17648
0
    return PyBytesWriter_FinishWithSize(writer, n);
17649
17650
0
error:
17651
0
    PyBytesWriter_Discard(writer);
17652
0
    return NULL;
17653
0
}
17654
#endif   /* HAVE_GETRANDOM_SYSCALL */
17655
17656
#if defined(MS_WINDOWS_DESKTOP) || defined(MS_WINDOWS_APP) || defined(MS_WINDOWS_SYSTEM)
17657
17658
/* bpo-36085: Helper functions for managing DLL search directories
17659
 * on win32
17660
 */
17661
17662
/*[clinic input]
17663
os._add_dll_directory
17664
17665
    path: path_t
17666
17667
Add a path to the DLL search path.
17668
17669
This search path is used when resolving dependencies for imported
17670
extension modules (the module itself is resolved through sys.path),
17671
and also by ctypes.
17672
17673
Returns an opaque value that may be passed to os.remove_dll_directory
17674
to remove this directory from the search path.
17675
[clinic start generated code]*/
17676
17677
static PyObject *
17678
os__add_dll_directory_impl(PyObject *module, path_t *path)
17679
/*[clinic end generated code: output=80b025daebb5d683 input=1de3e6c13a5808c8]*/
17680
{
17681
    DLL_DIRECTORY_COOKIE cookie = 0;
17682
    DWORD err = 0;
17683
17684
    if (PySys_Audit("os.add_dll_directory", "(O)", path->object) < 0) {
17685
        return NULL;
17686
    }
17687
17688
    Py_BEGIN_ALLOW_THREADS
17689
    if (!(cookie = AddDllDirectory(path->wide))) {
17690
        err = GetLastError();
17691
    }
17692
    Py_END_ALLOW_THREADS
17693
17694
    if (err) {
17695
        return win32_error_object_err("add_dll_directory",
17696
                                      path->object, err);
17697
    }
17698
17699
    return PyCapsule_New(cookie, "DLL directory cookie", NULL);
17700
}
17701
17702
/*[clinic input]
17703
os._remove_dll_directory
17704
17705
    cookie: object
17706
17707
Removes a path from the DLL search path.
17708
17709
The parameter is an opaque value that was returned from
17710
os.add_dll_directory. You can only remove directories that you added
17711
yourself.
17712
[clinic start generated code]*/
17713
17714
static PyObject *
17715
os__remove_dll_directory_impl(PyObject *module, PyObject *cookie)
17716
/*[clinic end generated code: output=594350433ae535bc input=c1d16a7e7d9dc5dc]*/
17717
{
17718
    DLL_DIRECTORY_COOKIE cookieValue;
17719
    DWORD err = 0;
17720
17721
    if (!PyCapsule_IsValid(cookie, "DLL directory cookie")) {
17722
        PyErr_SetString(PyExc_TypeError,
17723
            "Provided cookie was not returned from os.add_dll_directory");
17724
        return NULL;
17725
    }
17726
17727
    cookieValue = (DLL_DIRECTORY_COOKIE)PyCapsule_GetPointer(
17728
        cookie, "DLL directory cookie");
17729
17730
    Py_BEGIN_ALLOW_THREADS
17731
    if (!RemoveDllDirectory(cookieValue)) {
17732
        err = GetLastError();
17733
    }
17734
    Py_END_ALLOW_THREADS
17735
17736
    if (err) {
17737
        return win32_error_object_err("remove_dll_directory",
17738
                                      NULL, err);
17739
    }
17740
17741
    if (PyCapsule_SetName(cookie, NULL)) {
17742
        return NULL;
17743
    }
17744
17745
    Py_RETURN_NONE;
17746
}
17747
17748
#endif /* MS_WINDOWS_APP || MS_WINDOWS_SYSTEM */
17749
17750
17751
/* Only check if WIFEXITED is available: expect that it comes
17752
   with WEXITSTATUS, WIFSIGNALED, etc.
17753
17754
   os.waitstatus_to_exitcode() is implemented in C and not in Python, so
17755
   subprocess can safely call it during late Python finalization without
17756
   risking that used os attributes were set to None by finalize_modules(). */
17757
#if defined(WIFEXITED) || defined(MS_WINDOWS)
17758
/*[clinic input]
17759
os.waitstatus_to_exitcode
17760
17761
    status as status_obj: object
17762
17763
Convert a wait status to an exit code.
17764
17765
On Unix:
17766
17767
* If WIFEXITED(status) is true, return WEXITSTATUS(status).
17768
* If WIFSIGNALED(status) is true, return -WTERMSIG(status).
17769
* Otherwise, raise a ValueError.
17770
17771
On Windows, return status shifted right by 8 bits.
17772
17773
On Unix, if the process is being traced or if waitpid() was called with
17774
WUNTRACED option, the caller must first check if WIFSTOPPED(status) is
17775
true.  This function must not be called if WIFSTOPPED(status) is true.
17776
[clinic start generated code]*/
17777
17778
static PyObject *
17779
os_waitstatus_to_exitcode_impl(PyObject *module, PyObject *status_obj)
17780
/*[clinic end generated code: output=db50b1b0ba3c7153 input=3b44a23f5090006c]*/
17781
0
{
17782
0
#ifndef MS_WINDOWS
17783
0
    int status = PyLong_AsInt(status_obj);
17784
0
    if (status == -1 && PyErr_Occurred()) {
17785
0
        return NULL;
17786
0
    }
17787
17788
0
    WAIT_TYPE wait_status;
17789
0
    WAIT_STATUS_INT(wait_status) = status;
17790
0
    int exitcode;
17791
0
    if (WIFEXITED(wait_status)) {
17792
0
        exitcode = WEXITSTATUS(wait_status);
17793
        /* Sanity check to provide warranty on the function behavior.
17794
           It should not occur in practice */
17795
0
        if (exitcode < 0) {
17796
0
            PyErr_Format(PyExc_ValueError, "invalid WEXITSTATUS: %i", exitcode);
17797
0
            return NULL;
17798
0
        }
17799
0
    }
17800
0
    else if (WIFSIGNALED(wait_status)) {
17801
0
        int signum = WTERMSIG(wait_status);
17802
        /* Sanity check to provide warranty on the function behavior.
17803
           It should not occurs in practice */
17804
0
        if (signum <= 0) {
17805
0
            PyErr_Format(PyExc_ValueError, "invalid WTERMSIG: %i", signum);
17806
0
            return NULL;
17807
0
        }
17808
0
        exitcode = -signum;
17809
0
    } else if (WIFSTOPPED(wait_status)) {
17810
        /* Status only received if the process is being traced
17811
           or if waitpid() was called with WUNTRACED option. */
17812
0
        int signum = WSTOPSIG(wait_status);
17813
0
        PyErr_Format(PyExc_ValueError,
17814
0
                     "process stopped by delivery of signal %i",
17815
0
                     signum);
17816
0
        return NULL;
17817
0
    }
17818
0
    else {
17819
0
        PyErr_Format(PyExc_ValueError, "invalid wait status: %i", status);
17820
0
        return NULL;
17821
0
    }
17822
0
    return PyLong_FromLong(exitcode);
17823
#else
17824
    /* Windows implementation: see os.waitpid() implementation
17825
       which uses _cwait(). */
17826
    unsigned long long status = PyLong_AsUnsignedLongLong(status_obj);
17827
    if (status == (unsigned long long)-1 && PyErr_Occurred()) {
17828
        return NULL;
17829
    }
17830
17831
    unsigned long long exitcode = (status >> 8);
17832
    /* ExitProcess() accepts an UINT type:
17833
       reject exit code which doesn't fit in an UINT */
17834
    if (exitcode > UINT_MAX) {
17835
        PyErr_Format(PyExc_ValueError, "invalid exit code: %llu", exitcode);
17836
        return NULL;
17837
    }
17838
    return PyLong_FromUnsignedLong((unsigned long)exitcode);
17839
#endif
17840
0
}
17841
#endif
17842
17843
#if defined(MS_WINDOWS)
17844
/*[clinic input]
17845
os._supports_virtual_terminal
17846
17847
Checks if virtual terminal is supported in windows
17848
[clinic start generated code]*/
17849
17850
static PyObject *
17851
os__supports_virtual_terminal_impl(PyObject *module)
17852
/*[clinic end generated code: output=bd0556a6d9d99fe6 input=0752c98e5d321542]*/
17853
{
17854
#ifdef HAVE_WINDOWS_CONSOLE_IO
17855
    DWORD mode = 0;
17856
    HANDLE handle = GetStdHandle(STD_ERROR_HANDLE);
17857
    if (!GetConsoleMode(handle, &mode)) {
17858
        Py_RETURN_FALSE;
17859
    }
17860
    return PyBool_FromLong(mode & ENABLE_VIRTUAL_TERMINAL_PROCESSING);
17861
#else
17862
    Py_RETURN_FALSE;
17863
#endif /* HAVE_WINDOWS_CONSOLE_IO */
17864
}
17865
#endif
17866
17867
/*[clinic input]
17868
os._inputhook
17869
17870
Calls PyOS_InputHook dropping the GIL first
17871
[clinic start generated code]*/
17872
17873
static PyObject *
17874
os__inputhook_impl(PyObject *module)
17875
/*[clinic end generated code: output=525aca4ef3c6149f input=b5018fa1ec3aa440]*/
17876
0
{
17877
0
     int result = 0;
17878
0
     if (PyOS_InputHook) {
17879
0
         Py_BEGIN_ALLOW_THREADS;
17880
0
         result = PyOS_InputHook();
17881
0
         Py_END_ALLOW_THREADS;
17882
0
     }
17883
0
     return PyLong_FromLong(result);
17884
0
}
17885
17886
/*[clinic input]
17887
os._is_inputhook_installed
17888
17889
Checks if PyOS_InputHook is set
17890
[clinic start generated code]*/
17891
17892
static PyObject *
17893
os__is_inputhook_installed_impl(PyObject *module)
17894
/*[clinic end generated code: output=3b3eab4f672c689a input=757820f79f48820c]*/
17895
0
{
17896
0
    return PyBool_FromLong(PyOS_InputHook != NULL);
17897
0
}
17898
17899
/*[clinic input]
17900
os._create_environ
17901
17902
Create the environment dictionary.
17903
[clinic start generated code]*/
17904
17905
static PyObject *
17906
os__create_environ_impl(PyObject *module)
17907
/*[clinic end generated code: output=19d9039ab14f8ad4 input=a4c05686b34635e8]*/
17908
0
{
17909
0
    return convertenviron();
17910
0
}
17911
17912
17913
#ifdef __EMSCRIPTEN__
17914
/*[clinic input]
17915
os._emscripten_debugger
17916
17917
Create a breakpoint for the JavaScript debugger. Emscripten only.
17918
[clinic start generated code]*/
17919
17920
static PyObject *
17921
os__emscripten_debugger_impl(PyObject *module)
17922
/*[clinic end generated code: output=ad47dc3bf0661343 input=d814b1877fb6083a]*/
17923
{
17924
    emscripten_debugger();
17925
    Py_RETURN_NONE;
17926
}
17927
17928
EM_JS(void, emscripten_log_impl_js, (const char* arg), {
17929
    console.warn(UTF8ToString(arg));
17930
});
17931
17932
/*[clinic input]
17933
os._emscripten_log
17934
   arg: str
17935
17936
Log something to the JS console. Emscripten only.
17937
[clinic start generated code]*/
17938
17939
static PyObject *
17940
os__emscripten_log_impl(PyObject *module, const char *arg)
17941
/*[clinic end generated code: output=9749e5e293c42784 input=350aa1f70bc1e905]*/
17942
{
17943
    emscripten_log_impl_js(arg);
17944
    Py_RETURN_NONE;
17945
}
17946
#endif /* __EMSCRIPTEN__ */
17947
17948
17949
static PyMethodDef posix_methods[] = {
17950
    OS_STAT_METHODDEF
17951
    OS_STATX_METHODDEF
17952
    OS_ACCESS_METHODDEF
17953
    OS_TTYNAME_METHODDEF
17954
    OS_CHDIR_METHODDEF
17955
    OS_CHFLAGS_METHODDEF
17956
    OS_CHMOD_METHODDEF
17957
    OS_FCHMOD_METHODDEF
17958
    OS_LCHMOD_METHODDEF
17959
    OS_CHOWN_METHODDEF
17960
    OS_FCHOWN_METHODDEF
17961
    OS_LCHOWN_METHODDEF
17962
    OS_LCHFLAGS_METHODDEF
17963
    OS_CHROOT_METHODDEF
17964
    OS_CTERMID_METHODDEF
17965
    OS_GETCWD_METHODDEF
17966
    OS_GETCWDB_METHODDEF
17967
    OS_LINK_METHODDEF
17968
    OS_LISTDIR_METHODDEF
17969
    OS_LISTDRIVES_METHODDEF
17970
    OS_LISTMOUNTS_METHODDEF
17971
    OS_LISTVOLUMES_METHODDEF
17972
    OS_LSTAT_METHODDEF
17973
    OS_MKDIR_METHODDEF
17974
    OS_NICE_METHODDEF
17975
    OS_GETPRIORITY_METHODDEF
17976
    OS_SETPRIORITY_METHODDEF
17977
    OS_POSIX_SPAWN_METHODDEF
17978
    OS_POSIX_SPAWNP_METHODDEF
17979
    OS_READLINK_METHODDEF
17980
    OS_COPY_FILE_RANGE_METHODDEF
17981
    OS_SPLICE_METHODDEF
17982
    OS_RENAME_METHODDEF
17983
    OS_REPLACE_METHODDEF
17984
    OS_RMDIR_METHODDEF
17985
    OS_SYMLINK_METHODDEF
17986
    OS_SYSTEM_METHODDEF
17987
    OS_UMASK_METHODDEF
17988
    OS_UNAME_METHODDEF
17989
    OS_UNLINK_METHODDEF
17990
    OS_REMOVE_METHODDEF
17991
    OS_UTIME_METHODDEF
17992
    OS_TIMES_METHODDEF
17993
    OS__EXIT_METHODDEF
17994
    OS__FCOPYFILE_METHODDEF
17995
    OS_EXECV_METHODDEF
17996
    OS_EXECVE_METHODDEF
17997
    OS_SPAWNV_METHODDEF
17998
    OS_SPAWNVE_METHODDEF
17999
    OS_FORK1_METHODDEF
18000
    OS_FORK_METHODDEF
18001
    OS_REGISTER_AT_FORK_METHODDEF
18002
    OS_SCHED_GET_PRIORITY_MAX_METHODDEF
18003
    OS_SCHED_GET_PRIORITY_MIN_METHODDEF
18004
    OS_SCHED_GETPARAM_METHODDEF
18005
    OS_SCHED_GETSCHEDULER_METHODDEF
18006
    OS_SCHED_RR_GET_INTERVAL_METHODDEF
18007
    OS_SCHED_SETPARAM_METHODDEF
18008
    OS_SCHED_SETSCHEDULER_METHODDEF
18009
    OS_SCHED_YIELD_METHODDEF
18010
    OS_SCHED_SETAFFINITY_METHODDEF
18011
    OS_SCHED_GETAFFINITY_METHODDEF
18012
    OS_POSIX_OPENPT_METHODDEF
18013
    OS_GRANTPT_METHODDEF
18014
    OS_UNLOCKPT_METHODDEF
18015
    OS_PTSNAME_METHODDEF
18016
    OS_OPENPTY_METHODDEF
18017
    OS_LOGIN_TTY_METHODDEF
18018
    OS_FORKPTY_METHODDEF
18019
    OS_GETEGID_METHODDEF
18020
    OS_GETEUID_METHODDEF
18021
    OS_GETGID_METHODDEF
18022
    OS_GETGROUPLIST_METHODDEF
18023
    OS_GETGROUPS_METHODDEF
18024
    OS_GETPID_METHODDEF
18025
    OS_GETPGRP_METHODDEF
18026
    OS_GETPPID_METHODDEF
18027
    OS_GETUID_METHODDEF
18028
    OS_GETLOGIN_METHODDEF
18029
    OS_KILL_METHODDEF
18030
    OS_KILLPG_METHODDEF
18031
    OS_PLOCK_METHODDEF
18032
    OS_STARTFILE_METHODDEF
18033
    OS_SETUID_METHODDEF
18034
    OS_SETEUID_METHODDEF
18035
    OS_SETREUID_METHODDEF
18036
    OS_SETGID_METHODDEF
18037
    OS_SETEGID_METHODDEF
18038
    OS_SETREGID_METHODDEF
18039
    OS_SETGROUPS_METHODDEF
18040
    OS_INITGROUPS_METHODDEF
18041
    OS_GETPGID_METHODDEF
18042
    OS_SETPGRP_METHODDEF
18043
    OS_WAIT_METHODDEF
18044
    OS_WAIT3_METHODDEF
18045
    OS_WAIT4_METHODDEF
18046
    OS_WAITID_METHODDEF
18047
    OS_WAITPID_METHODDEF
18048
    OS_PIDFD_OPEN_METHODDEF
18049
    OS_PIDFD_GETFD_METHODDEF
18050
    OS_GETSID_METHODDEF
18051
    OS_SETSID_METHODDEF
18052
    OS_SETPGID_METHODDEF
18053
    OS_TCGETPGRP_METHODDEF
18054
    OS_TCSETPGRP_METHODDEF
18055
    OS_OPEN_METHODDEF
18056
    OS_CLOSE_METHODDEF
18057
    OS_CLOSERANGE_METHODDEF
18058
    OS_DEVICE_ENCODING_METHODDEF
18059
    OS_DUP_METHODDEF
18060
    OS_DUP2_METHODDEF
18061
    OS_LOCKF_METHODDEF
18062
    OS_LSEEK_METHODDEF
18063
    OS_READ_METHODDEF
18064
    OS_READINTO_METHODDEF
18065
    OS_READV_METHODDEF
18066
    OS_PREAD_METHODDEF
18067
    OS_PREADV_METHODDEF
18068
    OS_WRITE_METHODDEF
18069
    OS_WRITEV_METHODDEF
18070
    OS_PWRITE_METHODDEF
18071
    OS_PWRITEV_METHODDEF
18072
    OS_SENDFILE_METHODDEF
18073
    OS_FSTAT_METHODDEF
18074
    OS_ISATTY_METHODDEF
18075
    OS_PIPE_METHODDEF
18076
    OS_PIPE2_METHODDEF
18077
    OS_MKFIFO_METHODDEF
18078
    OS_MKNOD_METHODDEF
18079
    OS_MAJOR_METHODDEF
18080
    OS_MINOR_METHODDEF
18081
    OS_MAKEDEV_METHODDEF
18082
    OS_FTRUNCATE_METHODDEF
18083
    OS_TRUNCATE_METHODDEF
18084
    OS_POSIX_FALLOCATE_METHODDEF
18085
    OS_POSIX_FADVISE_METHODDEF
18086
    OS_PUTENV_METHODDEF
18087
    OS_UNSETENV_METHODDEF
18088
    OS__CLEARENV_METHODDEF
18089
    OS_STRERROR_METHODDEF
18090
    OS_FCHDIR_METHODDEF
18091
    OS_FSYNC_METHODDEF
18092
    OS_SYNC_METHODDEF
18093
    OS_FDATASYNC_METHODDEF
18094
    OS_WCOREDUMP_METHODDEF
18095
    OS_WIFCONTINUED_METHODDEF
18096
    OS_WIFSTOPPED_METHODDEF
18097
    OS_WIFSIGNALED_METHODDEF
18098
    OS_WIFEXITED_METHODDEF
18099
    OS_WEXITSTATUS_METHODDEF
18100
    OS_WTERMSIG_METHODDEF
18101
    OS_WSTOPSIG_METHODDEF
18102
    OS_FSTATVFS_METHODDEF
18103
    OS_STATVFS_METHODDEF
18104
    OS_CONFSTR_METHODDEF
18105
    OS_SYSCONF_METHODDEF
18106
    OS_FPATHCONF_METHODDEF
18107
    OS_PATHCONF_METHODDEF
18108
    OS_ABORT_METHODDEF
18109
    OS__GETFULLPATHNAME_METHODDEF
18110
    OS__GETDISKUSAGE_METHODDEF
18111
    OS__GETFINALPATHNAME_METHODDEF
18112
    OS__FINDFIRSTFILE_METHODDEF
18113
    OS__GETVOLUMEPATHNAME_METHODDEF
18114
    OS__PATH_SPLITROOT_METHODDEF
18115
    OS__PATH_SPLITROOT_EX_METHODDEF
18116
    OS__PATH_NORMPATH_METHODDEF
18117
    OS_GETLOADAVG_METHODDEF
18118
    OS_URANDOM_METHODDEF
18119
    OS_SETRESUID_METHODDEF
18120
    OS_SETRESGID_METHODDEF
18121
    OS_GETRESUID_METHODDEF
18122
    OS_GETRESGID_METHODDEF
18123
18124
    OS_GETXATTR_METHODDEF
18125
    OS_SETXATTR_METHODDEF
18126
    OS_REMOVEXATTR_METHODDEF
18127
    OS_LISTXATTR_METHODDEF
18128
18129
    OS_GET_TERMINAL_SIZE_METHODDEF
18130
    OS_CPU_COUNT_METHODDEF
18131
    OS_GET_INHERITABLE_METHODDEF
18132
    OS_SET_INHERITABLE_METHODDEF
18133
    OS_GET_HANDLE_INHERITABLE_METHODDEF
18134
    OS_SET_HANDLE_INHERITABLE_METHODDEF
18135
    OS_GET_BLOCKING_METHODDEF
18136
    OS_SET_BLOCKING_METHODDEF
18137
    OS_SCANDIR_METHODDEF
18138
    OS_FSPATH_METHODDEF
18139
    OS_GETRANDOM_METHODDEF
18140
    OS_MEMFD_CREATE_METHODDEF
18141
    OS_EVENTFD_METHODDEF
18142
    OS_EVENTFD_READ_METHODDEF
18143
    OS_EVENTFD_WRITE_METHODDEF
18144
    OS__ADD_DLL_DIRECTORY_METHODDEF
18145
    OS__REMOVE_DLL_DIRECTORY_METHODDEF
18146
    OS_WAITSTATUS_TO_EXITCODE_METHODDEF
18147
    OS_SETNS_METHODDEF
18148
    OS_UNSHARE_METHODDEF
18149
    OS_TIMERFD_CREATE_METHODDEF
18150
    OS_TIMERFD_SETTIME_METHODDEF
18151
    OS_TIMERFD_SETTIME_NS_METHODDEF
18152
    OS_TIMERFD_GETTIME_METHODDEF
18153
    OS_TIMERFD_GETTIME_NS_METHODDEF
18154
18155
    OS__PATH_ISDEVDRIVE_METHODDEF
18156
    OS__PATH_ISDIR_METHODDEF
18157
    OS__PATH_ISFILE_METHODDEF
18158
    OS__PATH_ISLINK_METHODDEF
18159
    OS__PATH_ISJUNCTION_METHODDEF
18160
    OS__PATH_EXISTS_METHODDEF
18161
    OS__PATH_LEXISTS_METHODDEF
18162
18163
    OS__SUPPORTS_VIRTUAL_TERMINAL_METHODDEF
18164
    OS__INPUTHOOK_METHODDEF
18165
    OS__IS_INPUTHOOK_INSTALLED_METHODDEF
18166
    OS__CREATE_ENVIRON_METHODDEF
18167
    OS__EMSCRIPTEN_DEBUGGER_METHODDEF
18168
    OS__EMSCRIPTEN_LOG_METHODDEF
18169
    {NULL,              NULL}            /* Sentinel */
18170
};
18171
18172
static int
18173
all_ins(PyObject *m)
18174
37
{
18175
37
#ifdef F_OK
18176
37
    if (PyModule_AddIntMacro(m, F_OK)) return -1;
18177
37
#endif
18178
37
#ifdef R_OK
18179
37
    if (PyModule_AddIntMacro(m, R_OK)) return -1;
18180
37
#endif
18181
37
#ifdef W_OK
18182
37
    if (PyModule_AddIntMacro(m, W_OK)) return -1;
18183
37
#endif
18184
37
#ifdef X_OK
18185
37
    if (PyModule_AddIntMacro(m, X_OK)) return -1;
18186
37
#endif
18187
37
#ifdef NGROUPS_MAX
18188
37
    if (PyModule_AddIntMacro(m, NGROUPS_MAX)) return -1;
18189
37
#endif
18190
37
#ifdef TMP_MAX
18191
37
    if (PyModule_AddIntMacro(m, TMP_MAX)) return -1;
18192
37
#endif
18193
37
#ifdef WCONTINUED
18194
37
    if (PyModule_AddIntMacro(m, WCONTINUED)) return -1;
18195
37
#endif
18196
37
#ifdef WNOHANG
18197
37
    if (PyModule_AddIntMacro(m, WNOHANG)) return -1;
18198
37
#endif
18199
37
#ifdef WUNTRACED
18200
37
    if (PyModule_AddIntMacro(m, WUNTRACED)) return -1;
18201
37
#endif
18202
37
#ifdef O_RDONLY
18203
37
    if (PyModule_AddIntMacro(m, O_RDONLY)) return -1;
18204
37
#endif
18205
37
#ifdef O_WRONLY
18206
37
    if (PyModule_AddIntMacro(m, O_WRONLY)) return -1;
18207
37
#endif
18208
37
#ifdef O_RDWR
18209
37
    if (PyModule_AddIntMacro(m, O_RDWR)) return -1;
18210
37
#endif
18211
37
#ifdef O_NDELAY
18212
37
    if (PyModule_AddIntMacro(m, O_NDELAY)) return -1;
18213
37
#endif
18214
37
#ifdef O_NONBLOCK
18215
37
    if (PyModule_AddIntMacro(m, O_NONBLOCK)) return -1;
18216
37
#endif
18217
37
#ifdef O_APPEND
18218
37
    if (PyModule_AddIntMacro(m, O_APPEND)) return -1;
18219
37
#endif
18220
37
#ifdef O_DSYNC
18221
37
    if (PyModule_AddIntMacro(m, O_DSYNC)) return -1;
18222
37
#endif
18223
37
#ifdef O_RSYNC
18224
37
    if (PyModule_AddIntMacro(m, O_RSYNC)) return -1;
18225
37
#endif
18226
37
#ifdef O_SYNC
18227
37
    if (PyModule_AddIntMacro(m, O_SYNC)) return -1;
18228
37
#endif
18229
37
#ifdef O_NOCTTY
18230
37
    if (PyModule_AddIntMacro(m, O_NOCTTY)) return -1;
18231
37
#endif
18232
37
#ifdef O_CREAT
18233
37
    if (PyModule_AddIntMacro(m, O_CREAT)) return -1;
18234
37
#endif
18235
37
#ifdef O_EXCL
18236
37
    if (PyModule_AddIntMacro(m, O_EXCL)) return -1;
18237
37
#endif
18238
37
#ifdef O_TRUNC
18239
37
    if (PyModule_AddIntMacro(m, O_TRUNC)) return -1;
18240
37
#endif
18241
#ifdef O_BINARY
18242
    if (PyModule_AddIntMacro(m, O_BINARY)) return -1;
18243
#endif
18244
#ifdef O_TEXT
18245
    if (PyModule_AddIntMacro(m, O_TEXT)) return -1;
18246
#endif
18247
#ifdef O_XATTR
18248
    if (PyModule_AddIntMacro(m, O_XATTR)) return -1;
18249
#endif
18250
37
#ifdef O_LARGEFILE
18251
37
    if (PyModule_AddIntMacro(m, O_LARGEFILE)) return -1;
18252
37
#endif
18253
37
#ifndef __GNU__
18254
#ifdef O_SHLOCK
18255
    if (PyModule_AddIntMacro(m, O_SHLOCK)) return -1;
18256
#endif
18257
#ifdef O_EXLOCK
18258
    if (PyModule_AddIntMacro(m, O_EXLOCK)) return -1;
18259
#endif
18260
37
#endif
18261
#ifdef O_EXEC
18262
    if (PyModule_AddIntMacro(m, O_EXEC)) return -1;
18263
#endif
18264
#ifdef O_SEARCH
18265
    if (PyModule_AddIntMacro(m, O_SEARCH)) return -1;
18266
#endif
18267
37
#ifdef O_PATH
18268
37
    if (PyModule_AddIntMacro(m, O_PATH)) return -1;
18269
37
#endif
18270
#ifdef O_TTY_INIT
18271
    if (PyModule_AddIntMacro(m, O_TTY_INIT)) return -1;
18272
#endif
18273
37
#ifdef O_TMPFILE
18274
37
    if (PyModule_AddIntMacro(m, O_TMPFILE)) return -1;
18275
37
#endif
18276
37
#ifdef PRIO_PROCESS
18277
37
    if (PyModule_AddIntMacro(m, PRIO_PROCESS)) return -1;
18278
37
#endif
18279
37
#ifdef PRIO_PGRP
18280
37
    if (PyModule_AddIntMacro(m, PRIO_PGRP)) return -1;
18281
37
#endif
18282
37
#ifdef PRIO_USER
18283
37
    if (PyModule_AddIntMacro(m, PRIO_USER)) return -1;
18284
37
#endif
18285
#ifdef PRIO_DARWIN_THREAD
18286
    if (PyModule_AddIntMacro(m, PRIO_DARWIN_THREAD)) return -1;
18287
#endif
18288
#ifdef PRIO_DARWIN_PROCESS
18289
    if (PyModule_AddIntMacro(m, PRIO_DARWIN_PROCESS)) return -1;
18290
#endif
18291
#ifdef PRIO_DARWIN_BG
18292
    if (PyModule_AddIntMacro(m, PRIO_DARWIN_BG)) return -1;
18293
#endif
18294
#ifdef PRIO_DARWIN_NONUI
18295
    if (PyModule_AddIntMacro(m, PRIO_DARWIN_NONUI)) return -1;
18296
#endif
18297
37
#ifdef O_CLOEXEC
18298
37
    if (PyModule_AddIntMacro(m, O_CLOEXEC)) return -1;
18299
37
#endif
18300
37
#ifdef O_ACCMODE
18301
37
    if (PyModule_AddIntMacro(m, O_ACCMODE)) return -1;
18302
37
#endif
18303
#ifdef O_EVTONLY
18304
    if (PyModule_AddIntMacro(m, O_EVTONLY)) return -1;
18305
#endif
18306
37
#ifdef O_FSYNC
18307
37
    if (PyModule_AddIntMacro(m, O_FSYNC)) return -1;
18308
37
#endif
18309
#ifdef O_SYMLINK
18310
    if (PyModule_AddIntMacro(m, O_SYMLINK)) return -1;
18311
#endif
18312
18313
37
#ifdef SEEK_HOLE
18314
37
    if (PyModule_AddIntMacro(m, SEEK_HOLE)) return -1;
18315
37
#endif
18316
37
#ifdef SEEK_DATA
18317
37
    if (PyModule_AddIntMacro(m, SEEK_DATA)) return -1;
18318
37
#endif
18319
18320
/* MS Windows */
18321
#ifdef O_NOINHERIT
18322
    /* Don't inherit in child processes. */
18323
    if (PyModule_AddIntMacro(m, O_NOINHERIT)) return -1;
18324
#endif
18325
#ifdef _O_SHORT_LIVED
18326
    /* Optimize for short life (keep in memory). */
18327
    /* MS forgot to define this one with a non-underscore form too. */
18328
    if (PyModule_AddIntConstant(m, "O_SHORT_LIVED", _O_SHORT_LIVED)) return -1;
18329
#endif
18330
#ifdef O_TEMPORARY
18331
    /* Automatically delete when last handle is closed. */
18332
    if (PyModule_AddIntMacro(m, O_TEMPORARY)) return -1;
18333
#endif
18334
#ifdef O_RANDOM
18335
    /* Optimize for random access. */
18336
    if (PyModule_AddIntMacro(m, O_RANDOM)) return -1;
18337
#endif
18338
#ifdef O_SEQUENTIAL
18339
    /* Optimize for sequential access. */
18340
    if (PyModule_AddIntMacro(m, O_SEQUENTIAL)) return -1;
18341
#endif
18342
18343
/* GNU extensions. */
18344
37
#ifdef O_ASYNC
18345
    /* Send a SIGIO signal whenever input or output
18346
       becomes available on file descriptor */
18347
37
    if (PyModule_AddIntMacro(m, O_ASYNC)) return -1;
18348
37
#endif
18349
37
#ifdef O_DIRECT
18350
    /* Direct disk access. */
18351
37
    if (PyModule_AddIntMacro(m, O_DIRECT)) return -1;
18352
37
#endif
18353
37
#ifdef O_DIRECTORY
18354
    /* Must be a directory.      */
18355
37
    if (PyModule_AddIntMacro(m, O_DIRECTORY)) return -1;
18356
37
#endif
18357
37
#ifdef O_NOFOLLOW
18358
    /* Do not follow links.      */
18359
37
    if (PyModule_AddIntMacro(m, O_NOFOLLOW)) return -1;
18360
37
#endif
18361
#ifdef O_NOFOLLOW_ANY
18362
    if (PyModule_AddIntMacro(m, O_NOFOLLOW_ANY)) return -1;
18363
#endif
18364
#ifdef O_NOLINKS
18365
    /* Fails if link count of the named file is greater than 1 */
18366
    if (PyModule_AddIntMacro(m, O_NOLINKS)) return -1;
18367
#endif
18368
37
#ifdef O_NOATIME
18369
    /* Do not update the access time. */
18370
37
    if (PyModule_AddIntMacro(m, O_NOATIME)) return -1;
18371
37
#endif
18372
18373
    /* These come from sysexits.h */
18374
37
#ifdef EX_OK
18375
37
    if (PyModule_AddIntMacro(m, EX_OK)) return -1;
18376
37
#endif /* EX_OK */
18377
37
#ifdef EX_USAGE
18378
37
    if (PyModule_AddIntMacro(m, EX_USAGE)) return -1;
18379
37
#endif /* EX_USAGE */
18380
37
#ifdef EX_DATAERR
18381
37
    if (PyModule_AddIntMacro(m, EX_DATAERR)) return -1;
18382
37
#endif /* EX_DATAERR */
18383
37
#ifdef EX_NOINPUT
18384
37
    if (PyModule_AddIntMacro(m, EX_NOINPUT)) return -1;
18385
37
#endif /* EX_NOINPUT */
18386
37
#ifdef EX_NOUSER
18387
37
    if (PyModule_AddIntMacro(m, EX_NOUSER)) return -1;
18388
37
#endif /* EX_NOUSER */
18389
37
#ifdef EX_NOHOST
18390
37
    if (PyModule_AddIntMacro(m, EX_NOHOST)) return -1;
18391
37
#endif /* EX_NOHOST */
18392
37
#ifdef EX_UNAVAILABLE
18393
37
    if (PyModule_AddIntMacro(m, EX_UNAVAILABLE)) return -1;
18394
37
#endif /* EX_UNAVAILABLE */
18395
37
#ifdef EX_SOFTWARE
18396
37
    if (PyModule_AddIntMacro(m, EX_SOFTWARE)) return -1;
18397
37
#endif /* EX_SOFTWARE */
18398
37
#ifdef EX_OSERR
18399
37
    if (PyModule_AddIntMacro(m, EX_OSERR)) return -1;
18400
37
#endif /* EX_OSERR */
18401
37
#ifdef EX_OSFILE
18402
37
    if (PyModule_AddIntMacro(m, EX_OSFILE)) return -1;
18403
37
#endif /* EX_OSFILE */
18404
37
#ifdef EX_CANTCREAT
18405
37
    if (PyModule_AddIntMacro(m, EX_CANTCREAT)) return -1;
18406
37
#endif /* EX_CANTCREAT */
18407
37
#ifdef EX_IOERR
18408
37
    if (PyModule_AddIntMacro(m, EX_IOERR)) return -1;
18409
37
#endif /* EX_IOERR */
18410
37
#ifdef EX_TEMPFAIL
18411
37
    if (PyModule_AddIntMacro(m, EX_TEMPFAIL)) return -1;
18412
37
#endif /* EX_TEMPFAIL */
18413
37
#ifdef EX_PROTOCOL
18414
37
    if (PyModule_AddIntMacro(m, EX_PROTOCOL)) return -1;
18415
37
#endif /* EX_PROTOCOL */
18416
37
#ifdef EX_NOPERM
18417
37
    if (PyModule_AddIntMacro(m, EX_NOPERM)) return -1;
18418
37
#endif /* EX_NOPERM */
18419
37
#ifdef EX_CONFIG
18420
37
    if (PyModule_AddIntMacro(m, EX_CONFIG)) return -1;
18421
37
#endif /* EX_CONFIG */
18422
#ifdef EX_NOTFOUND
18423
    if (PyModule_AddIntMacro(m, EX_NOTFOUND)) return -1;
18424
#endif /* EX_NOTFOUND */
18425
18426
    /* statvfs */
18427
37
#ifdef ST_RDONLY
18428
37
    if (PyModule_AddIntMacro(m, ST_RDONLY)) return -1;
18429
37
#endif /* ST_RDONLY */
18430
37
#ifdef ST_NOSUID
18431
37
    if (PyModule_AddIntMacro(m, ST_NOSUID)) return -1;
18432
37
#endif /* ST_NOSUID */
18433
18434
       /* GNU extensions */
18435
37
#ifdef ST_NODEV
18436
37
    if (PyModule_AddIntMacro(m, ST_NODEV)) return -1;
18437
37
#endif /* ST_NODEV */
18438
37
#ifdef ST_NOEXEC
18439
37
    if (PyModule_AddIntMacro(m, ST_NOEXEC)) return -1;
18440
37
#endif /* ST_NOEXEC */
18441
37
#ifdef ST_SYNCHRONOUS
18442
37
    if (PyModule_AddIntMacro(m, ST_SYNCHRONOUS)) return -1;
18443
37
#endif /* ST_SYNCHRONOUS */
18444
37
#ifdef ST_MANDLOCK
18445
37
    if (PyModule_AddIntMacro(m, ST_MANDLOCK)) return -1;
18446
37
#endif /* ST_MANDLOCK */
18447
37
#ifdef ST_WRITE
18448
37
    if (PyModule_AddIntMacro(m, ST_WRITE)) return -1;
18449
37
#endif /* ST_WRITE */
18450
37
#ifdef ST_APPEND
18451
37
    if (PyModule_AddIntMacro(m, ST_APPEND)) return -1;
18452
37
#endif /* ST_APPEND */
18453
37
#ifdef ST_NOATIME
18454
37
    if (PyModule_AddIntMacro(m, ST_NOATIME)) return -1;
18455
37
#endif /* ST_NOATIME */
18456
37
#ifdef ST_NODIRATIME
18457
37
    if (PyModule_AddIntMacro(m, ST_NODIRATIME)) return -1;
18458
37
#endif /* ST_NODIRATIME */
18459
37
#ifdef ST_RELATIME
18460
37
    if (PyModule_AddIntMacro(m, ST_RELATIME)) return -1;
18461
37
#endif /* ST_RELATIME */
18462
18463
    /* FreeBSD sendfile() constants */
18464
#ifdef SF_NODISKIO
18465
    if (PyModule_AddIntMacro(m, SF_NODISKIO)) return -1;
18466
#endif
18467
    /* is obsolete since the 11.x release */
18468
#ifdef SF_MNOWAIT
18469
    if (PyModule_AddIntMacro(m, SF_MNOWAIT)) return -1;
18470
#endif
18471
#ifdef SF_SYNC
18472
    if (PyModule_AddIntMacro(m, SF_SYNC)) return -1;
18473
#endif
18474
#ifdef SF_NOCACHE
18475
    if (PyModule_AddIntMacro(m, SF_NOCACHE)) return -1;
18476
#endif
18477
18478
37
#ifdef TFD_NONBLOCK
18479
37
    if (PyModule_AddIntMacro(m, TFD_NONBLOCK)) return -1;
18480
37
#endif
18481
37
#ifdef TFD_CLOEXEC
18482
37
    if (PyModule_AddIntMacro(m, TFD_CLOEXEC)) return -1;
18483
37
#endif
18484
37
#ifdef TFD_TIMER_ABSTIME
18485
37
    if (PyModule_AddIntMacro(m, TFD_TIMER_ABSTIME)) return -1;
18486
37
#endif
18487
37
#ifdef TFD_TIMER_CANCEL_ON_SET
18488
37
    if (PyModule_AddIntMacro(m, TFD_TIMER_CANCEL_ON_SET)) return -1;
18489
37
#endif
18490
18491
    /* constants for posix_fadvise */
18492
37
#ifdef POSIX_FADV_NORMAL
18493
37
    if (PyModule_AddIntMacro(m, POSIX_FADV_NORMAL)) return -1;
18494
37
#endif
18495
37
#ifdef POSIX_FADV_SEQUENTIAL
18496
37
    if (PyModule_AddIntMacro(m, POSIX_FADV_SEQUENTIAL)) return -1;
18497
37
#endif
18498
37
#ifdef POSIX_FADV_RANDOM
18499
37
    if (PyModule_AddIntMacro(m, POSIX_FADV_RANDOM)) return -1;
18500
37
#endif
18501
37
#ifdef POSIX_FADV_NOREUSE
18502
37
    if (PyModule_AddIntMacro(m, POSIX_FADV_NOREUSE)) return -1;
18503
37
#endif
18504
37
#ifdef POSIX_FADV_WILLNEED
18505
37
    if (PyModule_AddIntMacro(m, POSIX_FADV_WILLNEED)) return -1;
18506
37
#endif
18507
37
#ifdef POSIX_FADV_DONTNEED
18508
37
    if (PyModule_AddIntMacro(m, POSIX_FADV_DONTNEED)) return -1;
18509
37
#endif
18510
18511
    /* constants for waitid */
18512
37
#if defined(HAVE_SYS_WAIT_H) && defined(HAVE_WAITID)
18513
37
    if (PyModule_AddIntMacro(m, P_PID)) return -1;
18514
37
    if (PyModule_AddIntMacro(m, P_PGID)) return -1;
18515
37
    if (PyModule_AddIntMacro(m, P_ALL)) return -1;
18516
37
#ifdef P_PIDFD
18517
37
    if (PyModule_AddIntMacro(m, P_PIDFD)) return -1;
18518
37
#endif
18519
37
#ifdef PIDFD_NONBLOCK
18520
37
    if (PyModule_AddIntMacro(m, PIDFD_NONBLOCK)) return -1;
18521
37
#endif
18522
37
#endif
18523
37
#ifdef WEXITED
18524
37
    if (PyModule_AddIntMacro(m, WEXITED)) return -1;
18525
37
#endif
18526
37
#ifdef WNOWAIT
18527
37
    if (PyModule_AddIntMacro(m, WNOWAIT)) return -1;
18528
37
#endif
18529
37
#ifdef WSTOPPED
18530
37
    if (PyModule_AddIntMacro(m, WSTOPPED)) return -1;
18531
37
#endif
18532
37
#ifdef CLD_EXITED
18533
37
    if (PyModule_AddIntMacro(m, CLD_EXITED)) return -1;
18534
37
#endif
18535
37
#ifdef CLD_KILLED
18536
37
    if (PyModule_AddIntMacro(m, CLD_KILLED)) return -1;
18537
37
#endif
18538
37
#ifdef CLD_DUMPED
18539
37
    if (PyModule_AddIntMacro(m, CLD_DUMPED)) return -1;
18540
37
#endif
18541
37
#ifdef CLD_TRAPPED
18542
37
    if (PyModule_AddIntMacro(m, CLD_TRAPPED)) return -1;
18543
37
#endif
18544
37
#ifdef CLD_STOPPED
18545
37
    if (PyModule_AddIntMacro(m, CLD_STOPPED)) return -1;
18546
37
#endif
18547
37
#ifdef CLD_CONTINUED
18548
37
    if (PyModule_AddIntMacro(m, CLD_CONTINUED)) return -1;
18549
37
#endif
18550
18551
    /* constants for lockf */
18552
37
#ifdef F_LOCK
18553
37
    if (PyModule_AddIntMacro(m, F_LOCK)) return -1;
18554
37
#endif
18555
37
#ifdef F_TLOCK
18556
37
    if (PyModule_AddIntMacro(m, F_TLOCK)) return -1;
18557
37
#endif
18558
37
#ifdef F_ULOCK
18559
37
    if (PyModule_AddIntMacro(m, F_ULOCK)) return -1;
18560
37
#endif
18561
37
#ifdef F_TEST
18562
37
    if (PyModule_AddIntMacro(m, F_TEST)) return -1;
18563
37
#endif
18564
18565
37
#ifdef RWF_DSYNC
18566
37
    if (PyModule_AddIntConstant(m, "RWF_DSYNC", RWF_DSYNC)) return -1;
18567
37
#endif
18568
37
#ifdef RWF_HIPRI
18569
37
    if (PyModule_AddIntConstant(m, "RWF_HIPRI", RWF_HIPRI)) return -1;
18570
37
#endif
18571
37
#ifdef RWF_SYNC
18572
37
    if (PyModule_AddIntConstant(m, "RWF_SYNC", RWF_SYNC)) return -1;
18573
37
#endif
18574
37
#ifdef RWF_NOWAIT
18575
37
    if (PyModule_AddIntConstant(m, "RWF_NOWAIT", RWF_NOWAIT)) return -1;
18576
37
#endif
18577
#ifdef RWF_DONTCACHE
18578
    if (PyModule_AddIntConstant(m, "RWF_DONTCACHE", RWF_DONTCACHE)) return -1;
18579
#endif
18580
#ifdef RWF_ATOMIC
18581
    if (PyModule_AddIntConstant(m, "RWF_ATOMIC", RWF_ATOMIC)) return -1;
18582
#endif
18583
37
#ifdef RWF_APPEND
18584
37
    if (PyModule_AddIntConstant(m, "RWF_APPEND", RWF_APPEND)) return -1;
18585
37
#endif
18586
#ifdef RWF_NOSIGNAL
18587
    if (PyModule_AddIntConstant(m, "RWF_NOSIGNAL", RWF_NOSIGNAL)) return -1;
18588
#endif
18589
18590
/* constants for splice */
18591
37
#if defined(HAVE_SPLICE) && defined(__linux__)
18592
37
    if (PyModule_AddIntConstant(m, "SPLICE_F_MOVE", SPLICE_F_MOVE)) return -1;
18593
37
    if (PyModule_AddIntConstant(m, "SPLICE_F_NONBLOCK", SPLICE_F_NONBLOCK)) return -1;
18594
37
    if (PyModule_AddIntConstant(m, "SPLICE_F_MORE", SPLICE_F_MORE)) return -1;
18595
37
#endif
18596
18597
/* constants for posix_spawn */
18598
37
#ifdef HAVE_POSIX_SPAWN
18599
37
    if (PyModule_AddIntConstant(m, "POSIX_SPAWN_OPEN", POSIX_SPAWN_OPEN)) return -1;
18600
37
    if (PyModule_AddIntConstant(m, "POSIX_SPAWN_CLOSE", POSIX_SPAWN_CLOSE)) return -1;
18601
37
    if (PyModule_AddIntConstant(m, "POSIX_SPAWN_DUP2", POSIX_SPAWN_DUP2)) return -1;
18602
37
#ifdef HAVE_POSIX_SPAWN_FILE_ACTIONS_ADDCLOSEFROM_NP
18603
37
    if (PyModule_AddIntMacro(m, POSIX_SPAWN_CLOSEFROM)) return -1;
18604
37
#endif
18605
37
#endif
18606
18607
#if defined(HAVE_SPAWNV) || defined (HAVE_RTPSPAWN)
18608
    if (PyModule_AddIntConstant(m, "P_WAIT", _P_WAIT)) return -1;
18609
    if (PyModule_AddIntConstant(m, "P_NOWAIT", _P_NOWAIT)) return -1;
18610
    if (PyModule_AddIntConstant(m, "P_NOWAITO", _P_NOWAITO)) return -1;
18611
#endif
18612
#ifdef HAVE_SPAWNV
18613
    if (PyModule_AddIntConstant(m, "P_OVERLAY", _OLD_P_OVERLAY)) return -1;
18614
    if (PyModule_AddIntConstant(m, "P_DETACH", _P_DETACH)) return -1;
18615
#endif
18616
18617
37
#ifdef HAVE_SCHED_H
18618
37
#ifdef SCHED_OTHER
18619
37
    if (PyModule_AddIntMacro(m, SCHED_OTHER)) return -1;
18620
37
#endif
18621
37
#ifdef SCHED_DEADLINE
18622
37
    if (PyModule_AddIntMacro(m, SCHED_DEADLINE)) return -1;
18623
37
#endif
18624
37
#ifdef SCHED_FIFO
18625
37
    if (PyModule_AddIntMacro(m, SCHED_FIFO)) return -1;
18626
37
#endif
18627
37
#ifdef SCHED_NORMAL
18628
37
    if (PyModule_AddIntMacro(m, SCHED_NORMAL)) return -1;
18629
37
#endif
18630
37
#ifdef SCHED_RR
18631
37
    if (PyModule_AddIntMacro(m, SCHED_RR)) return -1;
18632
37
#endif
18633
#ifdef SCHED_SPORADIC
18634
    if (PyModule_AddIntMacro(m, SCHED_SPORADIC)) return -1;
18635
#endif
18636
37
#ifdef SCHED_BATCH
18637
37
    if (PyModule_AddIntMacro(m, SCHED_BATCH)) return -1;
18638
37
#endif
18639
37
#ifdef SCHED_IDLE
18640
37
    if (PyModule_AddIntMacro(m, SCHED_IDLE)) return -1;
18641
37
#endif
18642
37
#ifdef SCHED_RESET_ON_FORK
18643
37
    if (PyModule_AddIntMacro(m, SCHED_RESET_ON_FORK)) return -1;
18644
37
#endif
18645
#ifdef SCHED_SYS
18646
    if (PyModule_AddIntMacro(m, SCHED_SYS)) return -1;
18647
#endif
18648
#ifdef SCHED_IA
18649
    if (PyModule_AddIntMacro(m, SCHED_IA)) return -1;
18650
#endif
18651
#ifdef SCHED_FSS
18652
    if (PyModule_AddIntMacro(m, SCHED_FSS)) return -1;
18653
#endif
18654
#ifdef SCHED_FX
18655
    if (PyModule_AddIntConstant(m, "SCHED_FX", SCHED_FSS)) return -1;
18656
#endif
18657
18658
/* constants for namespaces */
18659
37
#if defined(HAVE_SETNS) || defined(HAVE_UNSHARE)
18660
37
#ifdef CLONE_FS
18661
37
    if (PyModule_AddIntMacro(m, CLONE_FS)) return -1;
18662
37
#endif
18663
37
#ifdef CLONE_FILES
18664
37
    if (PyModule_AddIntMacro(m, CLONE_FILES)) return -1;
18665
37
#endif
18666
37
#ifdef CLONE_NEWNS
18667
37
    if (PyModule_AddIntMacro(m, CLONE_NEWNS)) return -1;
18668
37
#endif
18669
37
#ifdef CLONE_NEWCGROUP
18670
37
    if (PyModule_AddIntMacro(m, CLONE_NEWCGROUP)) return -1;
18671
37
#endif
18672
37
#ifdef CLONE_NEWUTS
18673
37
    if (PyModule_AddIntMacro(m, CLONE_NEWUTS)) return -1;
18674
37
#endif
18675
37
#ifdef CLONE_NEWIPC
18676
37
    if (PyModule_AddIntMacro(m, CLONE_NEWIPC)) return -1;
18677
37
#endif
18678
37
#ifdef CLONE_NEWUSER
18679
37
    if (PyModule_AddIntMacro(m, CLONE_NEWUSER)) return -1;
18680
37
#endif
18681
37
#ifdef CLONE_NEWPID
18682
37
    if (PyModule_AddIntMacro(m, CLONE_NEWPID)) return -1;
18683
37
#endif
18684
37
#ifdef CLONE_NEWNET
18685
37
    if (PyModule_AddIntMacro(m, CLONE_NEWNET)) return -1;
18686
37
#endif
18687
37
#ifdef CLONE_NEWTIME
18688
37
    if (PyModule_AddIntMacro(m, CLONE_NEWTIME)) return -1;
18689
37
#endif
18690
37
#ifdef CLONE_SYSVSEM
18691
37
    if (PyModule_AddIntMacro(m, CLONE_SYSVSEM)) return -1;
18692
37
#endif
18693
37
#ifdef CLONE_THREAD
18694
37
    if (PyModule_AddIntMacro(m, CLONE_THREAD)) return -1;
18695
37
#endif
18696
37
#ifdef CLONE_SIGHAND
18697
37
    if (PyModule_AddIntMacro(m, CLONE_SIGHAND)) return -1;
18698
37
#endif
18699
37
#ifdef CLONE_VM
18700
37
    if (PyModule_AddIntMacro(m, CLONE_VM)) return -1;
18701
37
#endif
18702
37
#endif
18703
18704
37
#endif
18705
18706
37
#ifdef USE_XATTRS
18707
37
    if (PyModule_AddIntMacro(m, XATTR_CREATE)) return -1;
18708
37
    if (PyModule_AddIntMacro(m, XATTR_REPLACE)) return -1;
18709
37
    if (PyModule_AddIntMacro(m, XATTR_SIZE_MAX)) return -1;
18710
37
#endif
18711
18712
37
#if HAVE_DECL_RTLD_LAZY
18713
37
    if (PyModule_AddIntMacro(m, RTLD_LAZY)) return -1;
18714
37
#endif
18715
37
#if HAVE_DECL_RTLD_NOW
18716
37
    if (PyModule_AddIntMacro(m, RTLD_NOW)) return -1;
18717
37
#endif
18718
37
#if HAVE_DECL_RTLD_GLOBAL
18719
37
    if (PyModule_AddIntMacro(m, RTLD_GLOBAL)) return -1;
18720
37
#endif
18721
37
#if HAVE_DECL_RTLD_LOCAL
18722
37
    if (PyModule_AddIntMacro(m, RTLD_LOCAL)) return -1;
18723
37
#endif
18724
37
#if HAVE_DECL_RTLD_NODELETE
18725
37
    if (PyModule_AddIntMacro(m, RTLD_NODELETE)) return -1;
18726
37
#endif
18727
37
#if HAVE_DECL_RTLD_NOLOAD
18728
37
    if (PyModule_AddIntMacro(m, RTLD_NOLOAD)) return -1;
18729
37
#endif
18730
37
#if HAVE_DECL_RTLD_DEEPBIND
18731
37
    if (PyModule_AddIntMacro(m, RTLD_DEEPBIND)) return -1;
18732
37
#endif
18733
#if HAVE_DECL_RTLD_MEMBER
18734
    if (PyModule_AddIntMacro(m, RTLD_MEMBER)) return -1;
18735
#endif
18736
18737
37
#if defined(HAVE_GETRANDOM) || defined(HAVE_GETRANDOM_SYSCALL)
18738
37
    if (PyModule_AddIntMacro(m, GRND_RANDOM)) return -1;
18739
37
    if (PyModule_AddIntMacro(m, GRND_NONBLOCK)) return -1;
18740
37
#endif
18741
37
#ifdef _Py_HAVE_MEMFD_CREATE
18742
37
    if (PyModule_AddIntMacro(m, MFD_CLOEXEC)) return -1;
18743
37
    if (PyModule_AddIntMacro(m, MFD_ALLOW_SEALING)) return -1;
18744
37
#ifdef MFD_HUGETLB
18745
37
    if (PyModule_AddIntMacro(m, MFD_HUGETLB)) return -1;
18746
37
#endif
18747
37
#ifdef MFD_HUGE_SHIFT
18748
37
    if (PyModule_AddIntMacro(m, MFD_HUGE_SHIFT)) return -1;
18749
37
#endif
18750
37
#ifdef MFD_HUGE_MASK
18751
37
    if (PyModule_AddIntMacro(m, MFD_HUGE_MASK)) return -1;
18752
37
#endif
18753
37
#ifdef MFD_HUGE_64KB
18754
37
    if (PyModule_AddIntMacro(m, MFD_HUGE_64KB)) return -1;
18755
37
#endif
18756
37
#ifdef MFD_HUGE_512KB
18757
37
    if (PyModule_AddIntMacro(m, MFD_HUGE_512KB)) return -1;
18758
37
#endif
18759
37
#ifdef MFD_HUGE_1MB
18760
37
    if (PyModule_AddIntMacro(m, MFD_HUGE_1MB)) return -1;
18761
37
#endif
18762
37
#ifdef MFD_HUGE_2MB
18763
37
    if (PyModule_AddIntMacro(m, MFD_HUGE_2MB)) return -1;
18764
37
#endif
18765
37
#ifdef MFD_HUGE_8MB
18766
37
    if (PyModule_AddIntMacro(m, MFD_HUGE_8MB)) return -1;
18767
37
#endif
18768
37
#ifdef MFD_HUGE_16MB
18769
37
    if (PyModule_AddIntMacro(m, MFD_HUGE_16MB)) return -1;
18770
37
#endif
18771
37
#ifdef MFD_HUGE_32MB
18772
37
    if (PyModule_AddIntMacro(m, MFD_HUGE_32MB)) return -1;
18773
37
#endif
18774
37
#ifdef MFD_HUGE_256MB
18775
37
    if (PyModule_AddIntMacro(m, MFD_HUGE_256MB)) return -1;
18776
37
#endif
18777
37
#ifdef MFD_HUGE_512MB
18778
37
    if (PyModule_AddIntMacro(m, MFD_HUGE_512MB)) return -1;
18779
37
#endif
18780
37
#ifdef MFD_HUGE_1GB
18781
37
    if (PyModule_AddIntMacro(m, MFD_HUGE_1GB)) return -1;
18782
37
#endif
18783
37
#ifdef MFD_HUGE_2GB
18784
37
    if (PyModule_AddIntMacro(m, MFD_HUGE_2GB)) return -1;
18785
37
#endif
18786
37
#ifdef MFD_HUGE_16GB
18787
37
    if (PyModule_AddIntMacro(m, MFD_HUGE_16GB)) return -1;
18788
37
#endif
18789
37
#endif /* _Py_HAVE_MEMFD_CREATE */
18790
18791
37
#if defined(HAVE_EVENTFD) && defined(EFD_CLOEXEC)
18792
37
    if (PyModule_AddIntMacro(m, EFD_CLOEXEC)) return -1;
18793
37
#ifdef EFD_NONBLOCK
18794
37
    if (PyModule_AddIntMacro(m, EFD_NONBLOCK)) return -1;
18795
37
#endif
18796
37
#ifdef EFD_SEMAPHORE
18797
37
    if (PyModule_AddIntMacro(m, EFD_SEMAPHORE)) return -1;
18798
37
#endif
18799
37
#endif  /* HAVE_EVENTFD && EFD_CLOEXEC */
18800
18801
37
#ifdef NODEV
18802
37
    if (PyModule_Add(m, "NODEV", _PyLong_FromDev(NODEV))) return -1;
18803
37
#endif
18804
18805
37
#ifdef AT_NO_AUTOMOUNT
18806
37
    if (PyModule_AddIntMacro(m, AT_NO_AUTOMOUNT)) return -1;
18807
37
#endif
18808
18809
37
#ifdef HAVE_STATX
18810
37
    if (PyModule_AddIntMacro(m, STATX_TYPE)) return -1;
18811
37
    if (PyModule_AddIntMacro(m, STATX_MODE)) return -1;
18812
37
    if (PyModule_AddIntMacro(m, STATX_NLINK)) return -1;
18813
37
    if (PyModule_AddIntMacro(m, STATX_UID)) return -1;
18814
37
    if (PyModule_AddIntMacro(m, STATX_GID)) return -1;
18815
37
    if (PyModule_AddIntMacro(m, STATX_ATIME)) return -1;
18816
37
    if (PyModule_AddIntMacro(m, STATX_MTIME)) return -1;
18817
37
    if (PyModule_AddIntMacro(m, STATX_CTIME)) return -1;
18818
37
    if (PyModule_AddIntMacro(m, STATX_INO)) return -1;
18819
37
    if (PyModule_AddIntMacro(m, STATX_SIZE)) return -1;
18820
37
    if (PyModule_AddIntMacro(m, STATX_BLOCKS)) return -1;
18821
37
    if (PyModule_AddIntMacro(m, STATX_BASIC_STATS)) return -1;
18822
37
    if (PyModule_AddIntMacro(m, STATX_BTIME)) return -1;
18823
37
#ifdef STATX_MNT_ID
18824
37
    if (PyModule_AddIntMacro(m, STATX_MNT_ID)) return -1;
18825
37
#endif
18826
37
#ifdef STATX_DIOALIGN
18827
37
    if (PyModule_AddIntMacro(m, STATX_DIOALIGN)) return -1;
18828
37
#endif
18829
37
#ifdef STATX_MNT_ID_UNIQUE
18830
37
    if (PyModule_AddIntMacro(m, STATX_MNT_ID_UNIQUE)) return -1;
18831
37
#endif
18832
#ifdef STATX_SUBVOL
18833
    if (PyModule_AddIntMacro(m, STATX_SUBVOL)) return -1;
18834
#endif
18835
#ifdef STATX_WRITE_ATOMIC
18836
    if (PyModule_AddIntMacro(m, STATX_WRITE_ATOMIC)) return -1;
18837
#endif
18838
#ifdef STATX_DIO_READ_ALIGN
18839
    if (PyModule_AddIntMacro(m, STATX_DIO_READ_ALIGN)) return -1;
18840
#endif
18841
    /* STATX_ALL intentionally omitted because it is deprecated */
18842
37
    if (PyModule_AddIntMacro(m, AT_STATX_SYNC_AS_STAT)) return -1;
18843
37
    if (PyModule_AddIntMacro(m, AT_STATX_FORCE_SYNC)) return -1;
18844
37
    if (PyModule_AddIntMacro(m, AT_STATX_DONT_SYNC)) return -1;
18845
    /* STATX_ATTR_* constants are in the stat module */
18846
37
#endif /* HAVE_STATX */
18847
18848
#if defined(__APPLE__)
18849
    if (PyModule_AddIntConstant(m, "_COPYFILE_DATA", COPYFILE_DATA)) return -1;
18850
    if (PyModule_AddIntConstant(m, "_COPYFILE_STAT", COPYFILE_STAT)) return -1;
18851
    if (PyModule_AddIntConstant(m, "_COPYFILE_ACL", COPYFILE_ACL)) return -1;
18852
    if (PyModule_AddIntConstant(m, "_COPYFILE_XATTR", COPYFILE_XATTR)) return -1;
18853
#endif
18854
18855
#ifdef MS_WINDOWS
18856
    if (PyModule_AddIntConstant(m, "_LOAD_LIBRARY_SEARCH_DEFAULT_DIRS", LOAD_LIBRARY_SEARCH_DEFAULT_DIRS)) return -1;
18857
    if (PyModule_AddIntConstant(m, "_LOAD_LIBRARY_SEARCH_APPLICATION_DIR", LOAD_LIBRARY_SEARCH_APPLICATION_DIR)) return -1;
18858
    if (PyModule_AddIntConstant(m, "_LOAD_LIBRARY_SEARCH_SYSTEM32", LOAD_LIBRARY_SEARCH_SYSTEM32)) return -1;
18859
    if (PyModule_AddIntConstant(m, "_LOAD_LIBRARY_SEARCH_USER_DIRS", LOAD_LIBRARY_SEARCH_USER_DIRS)) return -1;
18860
    if (PyModule_AddIntConstant(m, "_LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR", LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR)) return -1;
18861
#endif
18862
18863
37
    return 0;
18864
37
}
18865
18866
18867
18868
#define PROBE(name, test) \
18869
   static int name(void)  \
18870
629
   {                      \
18871
629
      if (test) {        \
18872
629
          return 1;       \
18873
629
      } else {            \
18874
0
          return 0;       \
18875
0
      }                   \
18876
629
   }
posixmodule.c:probe_faccessat
Line
Count
Source
18870
37
   {                      \
18871
37
      if (test) {        \
18872
37
          return 1;       \
18873
37
      } else {            \
18874
0
          return 0;       \
18875
0
      }                   \
18876
37
   }
posixmodule.c:probe_fchmodat
Line
Count
Source
18870
37
   {                      \
18871
37
      if (test) {        \
18872
37
          return 1;       \
18873
37
      } else {            \
18874
0
          return 0;       \
18875
0
      }                   \
18876
37
   }
posixmodule.c:probe_fchownat
Line
Count
Source
18870
37
   {                      \
18871
37
      if (test) {        \
18872
37
          return 1;       \
18873
37
      } else {            \
18874
0
          return 0;       \
18875
0
      }                   \
18876
37
   }
posixmodule.c:probe_fdopendir
Line
Count
Source
18870
37
   {                      \
18871
37
      if (test) {        \
18872
37
          return 1;       \
18873
37
      } else {            \
18874
0
          return 0;       \
18875
0
      }                   \
18876
37
   }
posixmodule.c:probe_fstatat
Line
Count
Source
18870
37
   {                      \
18871
37
      if (test) {        \
18872
37
          return 1;       \
18873
37
      } else {            \
18874
0
          return 0;       \
18875
0
      }                   \
18876
37
   }
posixmodule.c:probe_futimens
Line
Count
Source
18870
37
   {                      \
18871
37
      if (test) {        \
18872
37
          return 1;       \
18873
37
      } else {            \
18874
0
          return 0;       \
18875
0
      }                   \
18876
37
   }
posixmodule.c:probe_linkat
Line
Count
Source
18870
37
   {                      \
18871
37
      if (test) {        \
18872
37
          return 1;       \
18873
37
      } else {            \
18874
0
          return 0;       \
18875
0
      }                   \
18876
37
   }
posixmodule.c:probe_mkdirat
Line
Count
Source
18870
37
   {                      \
18871
37
      if (test) {        \
18872
37
          return 1;       \
18873
37
      } else {            \
18874
0
          return 0;       \
18875
0
      }                   \
18876
37
   }
posixmodule.c:probe_mkfifoat
Line
Count
Source
18870
37
   {                      \
18871
37
      if (test) {        \
18872
37
          return 1;       \
18873
37
      } else {            \
18874
0
          return 0;       \
18875
0
      }                   \
18876
37
   }
posixmodule.c:probe_mknodat
Line
Count
Source
18870
37
   {                      \
18871
37
      if (test) {        \
18872
37
          return 1;       \
18873
37
      } else {            \
18874
0
          return 0;       \
18875
0
      }                   \
18876
37
   }
posixmodule.c:probe_openat
Line
Count
Source
18870
37
   {                      \
18871
37
      if (test) {        \
18872
37
          return 1;       \
18873
37
      } else {            \
18874
0
          return 0;       \
18875
0
      }                   \
18876
37
   }
posixmodule.c:probe_readlinkat
Line
Count
Source
18870
37
   {                      \
18871
37
      if (test) {        \
18872
37
          return 1;       \
18873
37
      } else {            \
18874
0
          return 0;       \
18875
0
      }                   \
18876
37
   }
posixmodule.c:probe_renameat
Line
Count
Source
18870
37
   {                      \
18871
37
      if (test) {        \
18872
37
          return 1;       \
18873
37
      } else {            \
18874
0
          return 0;       \
18875
0
      }                   \
18876
37
   }
posixmodule.c:probe_symlinkat
Line
Count
Source
18870
37
   {                      \
18871
37
      if (test) {        \
18872
37
          return 1;       \
18873
37
      } else {            \
18874
0
          return 0;       \
18875
0
      }                   \
18876
37
   }
posixmodule.c:probe_unlinkat
Line
Count
Source
18870
37
   {                      \
18871
37
      if (test) {        \
18872
37
          return 1;       \
18873
37
      } else {            \
18874
0
          return 0;       \
18875
0
      }                   \
18876
37
   }
posixmodule.c:probe_utimensat
Line
Count
Source
18870
37
   {                      \
18871
37
      if (test) {        \
18872
37
          return 1;       \
18873
37
      } else {            \
18874
0
          return 0;       \
18875
0
      }                   \
18876
37
   }
posixmodule.c:probe_ptsname_r
Line
Count
Source
18870
37
   {                      \
18871
37
      if (test) {        \
18872
37
          return 1;       \
18873
37
      } else {            \
18874
0
          return 0;       \
18875
0
      }                   \
18876
37
   }
18877
18878
#ifdef HAVE_FSTATAT
18879
PROBE(probe_fstatat, HAVE_FSTATAT_RUNTIME)
18880
#endif
18881
18882
#ifdef HAVE_FACCESSAT
18883
PROBE(probe_faccessat, HAVE_FACCESSAT_RUNTIME)
18884
#endif
18885
18886
#ifdef HAVE_FCHMODAT
18887
PROBE(probe_fchmodat, HAVE_FCHMODAT_RUNTIME)
18888
#endif
18889
18890
#ifdef HAVE_FCHOWNAT
18891
PROBE(probe_fchownat, HAVE_FCHOWNAT_RUNTIME)
18892
#endif
18893
18894
#ifdef HAVE_LINKAT
18895
PROBE(probe_linkat, HAVE_LINKAT_RUNTIME)
18896
#endif
18897
18898
#ifdef HAVE_FDOPENDIR
18899
PROBE(probe_fdopendir, HAVE_FDOPENDIR_RUNTIME)
18900
#endif
18901
18902
#ifdef HAVE_MKDIRAT
18903
PROBE(probe_mkdirat, HAVE_MKDIRAT_RUNTIME)
18904
#endif
18905
18906
#ifdef HAVE_MKFIFOAT
18907
PROBE(probe_mkfifoat, HAVE_MKFIFOAT_RUNTIME)
18908
#endif
18909
18910
#ifdef HAVE_MKNODAT
18911
PROBE(probe_mknodat, HAVE_MKNODAT_RUNTIME)
18912
#endif
18913
18914
#ifdef HAVE_RENAMEAT
18915
PROBE(probe_renameat, HAVE_RENAMEAT_RUNTIME)
18916
#endif
18917
18918
#ifdef HAVE_UNLINKAT
18919
PROBE(probe_unlinkat, HAVE_UNLINKAT_RUNTIME)
18920
#endif
18921
18922
#ifdef HAVE_OPENAT
18923
PROBE(probe_openat, HAVE_OPENAT_RUNTIME)
18924
#endif
18925
18926
#ifdef HAVE_READLINKAT
18927
PROBE(probe_readlinkat, HAVE_READLINKAT_RUNTIME)
18928
#endif
18929
18930
#ifdef _Py_HAVE_FREADLINK
18931
PROBE(probe_freadlink, HAVE_FREADLINK_RUNTIME)
18932
#endif
18933
18934
#ifdef HAVE_SYMLINKAT
18935
PROBE(probe_symlinkat, HAVE_SYMLINKAT_RUNTIME)
18936
#endif
18937
18938
#ifdef HAVE_FUTIMENS
18939
PROBE(probe_futimens, HAVE_FUTIMENS_RUNTIME)
18940
#endif
18941
18942
#ifdef HAVE_UTIMENSAT
18943
PROBE(probe_utimensat, HAVE_UTIMENSAT_RUNTIME)
18944
#endif
18945
18946
#ifdef HAVE_PTSNAME_R
18947
PROBE(probe_ptsname_r, HAVE_PTSNAME_R_RUNTIME)
18948
#endif
18949
18950
18951
18952
static const struct have_function {
18953
    const char * const label;
18954
    int (*probe)(void);
18955
} have_functions[] = {
18956
18957
#ifdef HAVE_EVENTFD
18958
    {"HAVE_EVENTFD", NULL},
18959
#endif
18960
18961
#ifdef HAVE_TIMERFD_CREATE
18962
    {"HAVE_TIMERFD_CREATE", NULL},
18963
#endif
18964
18965
#ifdef HAVE_FACCESSAT
18966
    { "HAVE_FACCESSAT", probe_faccessat },
18967
#endif
18968
18969
#ifdef HAVE_FCHDIR
18970
    { "HAVE_FCHDIR", NULL },
18971
#endif
18972
18973
#ifdef HAVE_FCHMOD
18974
    { "HAVE_FCHMOD", NULL },
18975
#endif
18976
18977
#ifdef HAVE_FCHMODAT
18978
    { "HAVE_FCHMODAT", probe_fchmodat },
18979
#endif
18980
18981
#ifdef HAVE_FCHOWN
18982
    { "HAVE_FCHOWN", NULL },
18983
#endif
18984
18985
#ifdef HAVE_FCHOWNAT
18986
    { "HAVE_FCHOWNAT", probe_fchownat },
18987
#endif
18988
18989
#ifdef HAVE_FEXECVE
18990
    { "HAVE_FEXECVE", NULL },
18991
#endif
18992
18993
#ifdef HAVE_FDOPENDIR
18994
    { "HAVE_FDOPENDIR", probe_fdopendir },
18995
#endif
18996
18997
#ifdef HAVE_FPATHCONF
18998
    { "HAVE_FPATHCONF", NULL },
18999
#endif
19000
19001
#ifdef _Py_HAVE_FREADLINK
19002
    { "HAVE_FREADLINK", probe_freadlink },
19003
#endif
19004
19005
#ifdef HAVE_FSTATAT
19006
    { "HAVE_FSTATAT", probe_fstatat },
19007
#endif
19008
19009
#ifdef HAVE_FSTATVFS
19010
    { "HAVE_FSTATVFS", NULL },
19011
#endif
19012
19013
#if defined HAVE_FTRUNCATE || defined MS_WINDOWS
19014
    { "HAVE_FTRUNCATE", NULL },
19015
#endif
19016
19017
#ifdef HAVE_FUTIMENS
19018
    { "HAVE_FUTIMENS", probe_futimens },
19019
#endif
19020
19021
#ifdef HAVE_FUTIMES
19022
    { "HAVE_FUTIMES", NULL },
19023
#endif
19024
19025
#ifdef HAVE_FUTIMESAT
19026
    { "HAVE_FUTIMESAT", NULL },
19027
#endif
19028
19029
#ifdef HAVE_LINKAT
19030
    { "HAVE_LINKAT", probe_linkat },
19031
#endif
19032
19033
#ifdef HAVE_LCHFLAGS
19034
    { "HAVE_LCHFLAGS", NULL },
19035
#endif
19036
19037
#ifdef HAVE_LCHMOD
19038
    { "HAVE_LCHMOD", NULL },
19039
#endif
19040
19041
#ifdef HAVE_LCHOWN
19042
    { "HAVE_LCHOWN", NULL },
19043
#endif
19044
19045
#ifdef HAVE_LSTAT
19046
    { "HAVE_LSTAT", NULL },
19047
#endif
19048
19049
#ifdef HAVE_LUTIMES
19050
    { "HAVE_LUTIMES", NULL },
19051
#endif
19052
19053
#ifdef _Py_HAVE_MEMFD_CREATE
19054
    { "HAVE_MEMFD_CREATE", NULL },
19055
#endif
19056
19057
#ifdef HAVE_MKDIRAT
19058
    { "HAVE_MKDIRAT", probe_mkdirat },
19059
#endif
19060
19061
#ifdef HAVE_MKFIFOAT
19062
    { "HAVE_MKFIFOAT", probe_mkfifoat },
19063
#endif
19064
19065
#ifdef HAVE_MKNODAT
19066
    { "HAVE_MKNODAT", probe_mknodat },
19067
#endif
19068
19069
#ifdef HAVE_OPENAT
19070
    { "HAVE_OPENAT", probe_openat },
19071
#endif
19072
19073
#ifdef HAVE_READLINKAT
19074
    { "HAVE_READLINKAT", probe_readlinkat },
19075
#endif
19076
19077
#ifdef HAVE_RENAMEAT
19078
    { "HAVE_RENAMEAT", probe_renameat },
19079
#endif
19080
19081
#ifdef HAVE_SYMLINKAT
19082
    { "HAVE_SYMLINKAT", probe_symlinkat },
19083
#endif
19084
19085
#ifdef HAVE_UNLINKAT
19086
    { "HAVE_UNLINKAT", probe_unlinkat },
19087
#endif
19088
19089
#ifdef HAVE_UTIMENSAT
19090
    { "HAVE_UTIMENSAT", probe_utimensat },
19091
#endif
19092
19093
#ifdef HAVE_PTSNAME_R
19094
    { "HAVE_PTSNAME_R", probe_ptsname_r },
19095
#endif
19096
19097
#ifdef MS_WINDOWS
19098
    { "MS_WINDOWS", NULL },
19099
#endif
19100
19101
    { NULL, NULL }
19102
};
19103
19104
19105
static int
19106
posixmodule_exec(PyObject *m)
19107
37
{
19108
37
    _posixstate *state = get_posix_state(m);
19109
19110
37
#if defined(HAVE_PWRITEV)
19111
37
    if (HAVE_PWRITEV_RUNTIME) {} else {
19112
0
        PyObject* dct = PyModule_GetDict(m);
19113
19114
0
        if (dct == NULL) {
19115
0
            return -1;
19116
0
        }
19117
19118
0
        if (PyDict_PopString(dct, "pwritev", NULL) < 0) {
19119
0
            return -1;
19120
0
        }
19121
0
        if (PyDict_PopString(dct, "preadv", NULL) < 0) {
19122
0
            return -1;
19123
0
        }
19124
0
    }
19125
37
#endif
19126
19127
37
#ifdef HAVE_STATX
19128
37
    if (statx == NULL) {
19129
0
        PyObject* dct = PyModule_GetDict(m);
19130
0
        if (dct == NULL) {
19131
0
            return -1;
19132
0
        }
19133
0
        if (PyDict_PopString(dct, "statx", NULL) < 0) {
19134
0
            return -1;
19135
0
        }
19136
0
    }
19137
37
    else {
19138
37
        state->StatxResultType = PyType_FromModuleAndSpec(m, &pystatx_result_spec, NULL);
19139
37
        if (PyModule_AddObjectRef(m, "statx_result", state->StatxResultType) < 0) {
19140
0
            return -1;
19141
0
        }
19142
37
    }
19143
37
#endif
19144
19145
37
#if HAVE_PIPE2
19146
37
    if (HAVE_PIPE2_RUNTIME) {
19147
        // Do nothing. (`__builtin_available` doesn't allow `!`; see
19148
        // "using negations" in a comment above.)
19149
37
    }
19150
0
    else {
19151
0
        PyObject* dct = PyModule_GetDict(m);
19152
0
        if (dct == NULL) {
19153
0
            return -1;
19154
0
        }
19155
0
        if (PyDict_PopString(dct, "pipe2", NULL) < 0) {
19156
0
            return -1;
19157
0
        }
19158
0
    }
19159
37
#endif
19160
19161
    /* Initialize environ dictionary */
19162
37
    if (PyModule_Add(m, "environ", convertenviron()) != 0) {
19163
0
        return -1;
19164
0
    }
19165
19166
37
    if (all_ins(m))
19167
0
        return -1;
19168
19169
37
    if (setup_confname_tables(m))
19170
0
        return -1;
19171
19172
37
    if (PyModule_AddObjectRef(m, "error", PyExc_OSError) < 0) {
19173
0
        return -1;
19174
0
    }
19175
19176
37
#if defined(HAVE_WAITID)
19177
37
    state->WaitidResultType = (PyObject *)PyStructSequence_NewType(&waitid_result_desc);
19178
37
    if (PyModule_AddObjectRef(m, "waitid_result", state->WaitidResultType) < 0) {
19179
0
        return -1;
19180
0
    }
19181
37
#endif
19182
19183
37
    stat_result_desc.fields[7].name = PyStructSequence_UnnamedField;
19184
37
    stat_result_desc.fields[8].name = PyStructSequence_UnnamedField;
19185
37
    stat_result_desc.fields[9].name = PyStructSequence_UnnamedField;
19186
37
    state->StatResultType = (PyObject *)PyStructSequence_NewType(&stat_result_desc);
19187
37
    if (PyModule_AddObjectRef(m, "stat_result", state->StatResultType) < 0) {
19188
0
        return -1;
19189
0
    }
19190
37
    state->statresult_new_orig = ((PyTypeObject *)state->StatResultType)->tp_new;
19191
37
    ((PyTypeObject *)state->StatResultType)->tp_new = statresult_new;
19192
19193
37
    state->StatVFSResultType = (PyObject *)PyStructSequence_NewType(&statvfs_result_desc);
19194
37
    if (PyModule_AddObjectRef(m, "statvfs_result", state->StatVFSResultType) < 0) {
19195
0
        return -1;
19196
0
    }
19197
19198
37
#if defined(HAVE_SCHED_SETPARAM) || defined(HAVE_SCHED_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDULER) || defined(POSIX_SPAWN_SETSCHEDPARAM)
19199
37
    state->SchedParamType = (PyObject *)PyStructSequence_NewType(&sched_param_desc);
19200
37
    if (PyModule_AddObjectRef(m, "sched_param", state->SchedParamType) < 0) {
19201
0
        return -1;
19202
0
    }
19203
37
    ((PyTypeObject *)state->SchedParamType)->tp_new = os_sched_param;
19204
37
    if (_PyType_AddMethod((PyTypeObject *)state->SchedParamType,
19205
37
                          &os_sched_param_reduce_method) < 0)
19206
0
    {
19207
0
        return -1;
19208
0
    }
19209
37
    PyType_Modified((PyTypeObject *)state->SchedParamType);
19210
37
#endif
19211
19212
    /* initialize TerminalSize_info */
19213
37
    state->TerminalSizeType = (PyObject *)PyStructSequence_NewType(&TerminalSize_desc);
19214
37
    if (PyModule_AddObjectRef(m, "terminal_size", state->TerminalSizeType) < 0) {
19215
0
        return -1;
19216
0
    }
19217
19218
    /* initialize scandir types */
19219
37
    PyObject *ScandirIteratorType = PyType_FromModuleAndSpec(m, &ScandirIteratorType_spec, NULL);
19220
37
    if (ScandirIteratorType == NULL) {
19221
0
        return -1;
19222
0
    }
19223
37
    state->ScandirIteratorType = ScandirIteratorType;
19224
19225
37
    state->DirEntryType = PyType_FromModuleAndSpec(m, &DirEntryType_spec, NULL);
19226
37
    if (PyModule_AddObjectRef(m, "DirEntry", state->DirEntryType) < 0) {
19227
0
        return -1;
19228
0
    }
19229
19230
37
    state->TimesResultType = (PyObject *)PyStructSequence_NewType(&times_result_desc);
19231
37
    if (PyModule_AddObjectRef(m, "times_result", state->TimesResultType) < 0) {
19232
0
        return -1;
19233
0
    }
19234
19235
37
    state->UnameResultType = (PyObject *)PyStructSequence_NewType(&uname_result_desc);
19236
37
    if (PyModule_AddObjectRef(m, "uname_result", state->UnameResultType) < 0) {
19237
0
        return -1;
19238
0
    }
19239
19240
37
    if ((state->billion = PyLong_FromLong(1000000000)) == NULL)
19241
0
        return -1;
19242
37
#if defined(HAVE_WAIT3) || defined(HAVE_WAIT4)
19243
37
    state->struct_rusage = PyUnicode_InternFromString("struct_rusage");
19244
37
    if (state->struct_rusage == NULL)
19245
0
        return -1;
19246
37
#endif
19247
37
    state->st_mode = PyUnicode_InternFromString("st_mode");
19248
37
    if (state->st_mode == NULL)
19249
0
        return -1;
19250
19251
    /* suppress "function not used" warnings */
19252
37
    {
19253
37
    int ignored;
19254
37
    fd_specified("", -1);
19255
37
    follow_symlinks_specified("", 1);
19256
37
    dir_fd_and_follow_symlinks_invalid("chmod", DEFAULT_DIR_FD, 1);
19257
37
    dir_fd_converter(Py_None, &ignored);
19258
37
    dir_fd_unavailable(Py_None, &ignored);
19259
37
    }
19260
19261
    /*
19262
     * provide list of locally available functions
19263
     * so os.py can populate support_* lists
19264
     */
19265
37
    PyObject *list = PyList_New(0);
19266
37
    if (!list) {
19267
0
        return -1;
19268
0
    }
19269
1.22k
    for (const struct have_function *trace = have_functions; trace->label; trace++) {
19270
1.18k
        PyObject *unicode;
19271
1.18k
        if (trace->probe && !trace->probe()) continue;
19272
1.18k
        unicode = PyUnicode_DecodeASCII(trace->label, strlen(trace->label), NULL);
19273
1.18k
        if (!unicode)
19274
0
            return -1;
19275
1.18k
        if (PyList_Append(list, unicode))
19276
0
            return -1;
19277
1.18k
        Py_DECREF(unicode);
19278
1.18k
    }
19279
19280
37
#ifndef MS_WINDOWS
19281
37
    if (_Py_GetTicksPerSecond(&state->ticks_per_second) < 0) {
19282
0
        PyErr_SetString(PyExc_RuntimeError,
19283
0
                        "cannot read ticks_per_second");
19284
0
        return -1;
19285
0
    }
19286
37
    assert(state->ticks_per_second >= 1);
19287
37
#endif
19288
19289
37
    return PyModule_Add(m, "_have_functions", list);
19290
37
}
19291
19292
19293
static PyModuleDef_Slot posixmodile_slots[] = {
19294
    _Py_ABI_SLOT,
19295
    {Py_mod_exec, posixmodule_exec},
19296
    {Py_mod_multiple_interpreters, Py_MOD_PER_INTERPRETER_GIL_SUPPORTED},
19297
    {Py_mod_gil, Py_MOD_GIL_NOT_USED},
19298
    {0, NULL}
19299
};
19300
19301
static struct PyModuleDef posixmodule = {
19302
    PyModuleDef_HEAD_INIT,
19303
    .m_name = MODNAME,
19304
    .m_doc = posix__doc__,
19305
    .m_size = sizeof(_posixstate),
19306
    .m_methods = posix_methods,
19307
    .m_slots = posixmodile_slots,
19308
    .m_traverse = _posix_traverse,
19309
    .m_clear = _posix_clear,
19310
    .m_free = _posix_free,
19311
};
19312
19313
PyMODINIT_FUNC
19314
INITFUNC(void)
19315
37
{
19316
37
    return PyModuleDef_Init(&posixmodule);
19317
37
}