Coverage Report

Created: 2026-09-27 06:15

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/cpython3/Modules/timemodule.c
Line
Count
Source
1
/* Time module */
2
3
#include "Python.h"
4
#include "pycore_fileutils.h"     // _Py_BEGIN_SUPPRESS_IPH
5
#include "pycore_moduleobject.h"  // _PyModule_GetState()
6
#include "pycore_namespace.h"     // _PyNamespace_New()
7
#include "pycore_runtime.h"       // _Py_ID()
8
#include "pycore_time.h"          // _PyTimeFraction
9
10
#include <time.h>                 // clock()
11
#ifdef HAVE_SYS_TIMES_H
12
#  include <sys/times.h>          // times()
13
#endif
14
#ifdef HAVE_SYS_TYPES_H
15
#  include <sys/types.h>
16
#endif
17
#if defined(HAVE_SYS_RESOURCE_H)
18
#  include <sys/resource.h>       // getrusage(RUSAGE_SELF)
19
#endif
20
#ifdef QUICKWIN
21
# include <io.h>
22
#endif
23
#if defined(HAVE_PTHREAD_H)
24
#  include <pthread.h>            // pthread_getcpuclockid()
25
#endif
26
#if defined(_AIX)
27
#   include <sys/thread.h>
28
#endif
29
#if defined(__WATCOMC__) && !defined(__QNX__)
30
#  include <i86.h>
31
#else
32
#  ifdef MS_WINDOWS
33
#    ifndef WIN32_LEAN_AND_MEAN
34
#      define WIN32_LEAN_AND_MEAN
35
#    endif
36
#    include <windows.h>
37
#  endif /* MS_WINDOWS */
38
#endif /* !__WATCOMC__ || __QNX__ */
39
40
#ifdef _Py_MEMORY_SANITIZER
41
#  include <sanitizer/msan_interface.h>
42
#endif
43
44
#ifdef _MSC_VER
45
#  define _Py_timezone _timezone
46
#  define _Py_daylight _daylight
47
#  define _Py_tzname _tzname
48
#else
49
#  define _Py_timezone timezone
50
#  define _Py_daylight daylight
51
#  define _Py_tzname tzname
52
#endif
53
54
#if defined(__APPLE__ ) && defined(__has_builtin)
55
#  if __has_builtin(__builtin_available)
56
#    define HAVE_CLOCK_GETTIME_RUNTIME __builtin_available(macOS 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *)
57
#  endif
58
#endif
59
#ifndef HAVE_CLOCK_GETTIME_RUNTIME
60
21
#  define HAVE_CLOCK_GETTIME_RUNTIME 1
61
#endif
62
63
64
42
#define SEC_TO_NS (1000 * 1000 * 1000)
65
66
67
/*[clinic input]
68
module time
69
[clinic start generated code]*/
70
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=a668a08771581f36]*/
71
72
73
/* Forward declarations */
74
static int pysleep(PyTime_t timeout);
75
76
77
typedef struct {
78
    PyTypeObject *struct_time_type;
79
// gh-115714: Don't use times() on WASI.
80
#if defined(HAVE_TIMES) && !defined(__wasi__)
81
    // times() clock frequency in hertz
82
    _PyTimeFraction times_base;
83
#endif
84
#ifdef HAVE_CLOCK
85
    // clock() frequency in hertz
86
    _PyTimeFraction clock_base;
87
#endif
88
} time_module_state;
89
90
static inline time_module_state*
91
get_time_state(PyObject *module)
92
413
{
93
413
    void *state = _PyModule_GetState(module);
94
413
    assert(state != NULL);
95
413
    return (time_module_state *)state;
96
413
}
97
98
99
/*[clinic input]
100
time.time -> double
101
102
Return the current time in seconds since the Epoch.
103
104
Fractions of a second may be present if the system clock provides
105
them.
106
[clinic start generated code]*/
107
108
static double
109
time_time_impl(PyObject *module)
110
/*[clinic end generated code: output=4adfc457b48923ca input=eea2e80c63bbcaad]*/
111
0
{
112
0
    PyTime_t t;
113
0
    if (PyTime_Time(&t) < 0) {
114
0
        return -1.0;
115
0
    }
116
0
    return PyTime_AsSecondsDouble(t);
117
0
}
118
119
120
/*[clinic input]
121
time.time_ns
122
123
Return the current time in nanoseconds since the Epoch.
124
[clinic start generated code]*/
125
126
static PyObject *
127
time_time_ns_impl(PyObject *module)
128
/*[clinic end generated code: output=f5f1924ebdcf1cf3 input=3acccd9786731be4]*/
129
0
{
130
0
    PyTime_t t;
131
0
    if (PyTime_Time(&t) < 0) {
132
0
        return NULL;
133
0
    }
134
0
    return PyLong_FromInt64(t);
135
0
}
136
137
#ifdef HAVE_CLOCK
138
139
#ifndef CLOCKS_PER_SEC
140
#  ifdef CLK_TCK
141
#    define CLOCKS_PER_SEC CLK_TCK
142
#  else
143
#    define CLOCKS_PER_SEC 1000000
144
#  endif
145
#endif
146
147
static int
148
py_clock(time_module_state *state, PyTime_t *tp, _Py_clock_info_t *info)
149
0
{
150
0
    _PyTimeFraction *base = &state->clock_base;
151
152
0
    if (info) {
153
0
        info->implementation = "clock()";
154
0
        info->resolution = _PyTimeFraction_Resolution(base);
155
0
        info->monotonic = 1;
156
0
        info->adjustable = 0;
157
0
    }
158
159
0
    clock_t ticks = clock();
160
0
    if (ticks == (clock_t)-1) {
161
0
        PyErr_SetString(PyExc_RuntimeError,
162
0
                        "the processor time used is not available "
163
0
                        "or its value cannot be represented");
164
0
        return -1;
165
0
    }
166
0
    *tp = _PyTimeFraction_Mul(ticks, base);
167
0
    return 0;
168
0
}
169
#endif /* HAVE_CLOCK */
170
171
172
#ifdef HAVE_CLOCK_GETTIME
173
174
#ifdef __APPLE__
175
/*
176
 * The clock_* functions will be removed from the module
177
 * dict entirely when the C API is not available.
178
 */
179
#pragma clang diagnostic push
180
#pragma clang diagnostic ignored "-Wunguarded-availability"
181
#endif
182
183
static int
184
time_clockid_converter(PyObject *obj, clockid_t *p)
185
0
{
186
#ifdef _AIX
187
    long long clk_id = PyLong_AsLongLong(obj);
188
#elif defined(__DragonFly__) || defined(__CYGWIN__)
189
    long clk_id = PyLong_AsLong(obj);
190
#else
191
0
    int clk_id = PyLong_AsInt(obj);
192
0
#endif
193
0
    if (clk_id == -1 && PyErr_Occurred()) {
194
0
        PyErr_Format(PyExc_TypeError,
195
0
                     "clk_id should be integer, not %s",
196
0
                     _PyType_Name(Py_TYPE(obj)));
197
0
        return 0;
198
0
    }
199
200
    // Make sure that we picked the right type (check sizes type)
201
0
    Py_BUILD_ASSERT(sizeof(clk_id) == sizeof(*p));
202
0
    *p = (clockid_t)clk_id;
203
0
    return 1;
204
0
}
205
206
/*[python input]
207
208
class clockid_t_converter(CConverter):
209
    type = "clockid_t"
210
    converter = 'time_clockid_converter'
211
212
[python start generated code]*/
213
/*[python end generated code: output=da39a3ee5e6b4b0d input=53867111501f46c8]*/
214
215
216
/*[clinic input]
217
time.clock_gettime
218
219
    clk_id: clockid_t
220
    /
221
222
Return the time of the specified clock clk_id as a float.
223
[clinic start generated code]*/
224
225
static PyObject *
226
time_clock_gettime_impl(PyObject *module, clockid_t clk_id)
227
/*[clinic end generated code: output=832b9ebc03328020 input=7e89fcc42ca15e5d]*/
228
0
{
229
0
    struct timespec tp;
230
0
    int ret = clock_gettime(clk_id, &tp);
231
0
    if (ret != 0) {
232
0
        PyErr_SetFromErrno(PyExc_OSError);
233
0
        return NULL;
234
0
    }
235
0
    return PyFloat_FromDouble(tp.tv_sec + tp.tv_nsec * 1e-9);
236
0
}
237
238
/*[clinic input]
239
time.clock_gettime_ns
240
241
    clk_id: clockid_t
242
    /
243
244
Return the time of the specified clock clk_id as nanoseconds (int).
245
[clinic start generated code]*/
246
247
static PyObject *
248
time_clock_gettime_ns_impl(PyObject *module, clockid_t clk_id)
249
/*[clinic end generated code: output=4a045c3a36e60044 input=aabc248db8c8e3e5]*/
250
0
{
251
0
    struct timespec ts;
252
0
    int ret = clock_gettime(clk_id, &ts);
253
0
    if (ret != 0) {
254
0
        PyErr_SetFromErrno(PyExc_OSError);
255
0
        return NULL;
256
0
    }
257
258
0
    PyTime_t t;
259
0
    if (_PyTime_FromTimespec(&t, &ts) < 0) {
260
0
        return NULL;
261
0
    }
262
0
    return PyLong_FromInt64(t);
263
0
}
264
#endif   /* HAVE_CLOCK_GETTIME */
265
266
#ifdef HAVE_CLOCK_SETTIME
267
/*[clinic input]
268
time.clock_settime
269
270
    clk_id: int
271
    time as obj: object
272
    /
273
274
Set the time of the specified clock clk_id.
275
[clinic start generated code]*/
276
277
static PyObject *
278
time_clock_settime_impl(PyObject *module, int clk_id, PyObject *obj)
279
/*[clinic end generated code: output=ff2fc2e129f5fdea input=0e71daa237ff6edc]*/
280
0
{
281
0
    PyTime_t t;
282
0
    struct timespec tp;
283
0
    int ret;
284
285
0
    if (_PyTime_FromSecondsObject(&t, obj, _PyTime_ROUND_FLOOR) < 0)
286
0
        return NULL;
287
288
0
    if (_PyTime_AsTimespec(t, &tp) == -1)
289
0
        return NULL;
290
291
0
    ret = clock_settime((clockid_t)clk_id, &tp);
292
0
    if (ret != 0) {
293
0
        PyErr_SetFromErrno(PyExc_OSError);
294
0
        return NULL;
295
0
    }
296
0
    Py_RETURN_NONE;
297
0
}
298
299
/*[clinic input]
300
time.clock_settime_ns
301
302
    clk_id: int
303
    time as obj: object
304
    /
305
306
Set the time of the specified clock clk_id with nanoseconds.
307
[clinic start generated code]*/
308
309
static PyObject *
310
time_clock_settime_ns_impl(PyObject *module, int clk_id, PyObject *obj)
311
/*[clinic end generated code: output=5d40ca0217bfe058 input=f2333aae32a7f441]*/
312
0
{
313
0
    PyTime_t t;
314
0
    struct timespec ts;
315
0
    int ret;
316
317
0
    if (PyLong_AsInt64(obj, &t) < 0) {
318
0
        return NULL;
319
0
    }
320
0
    if (_PyTime_AsTimespec(t, &ts) == -1) {
321
0
        return NULL;
322
0
    }
323
324
0
    ret = clock_settime((clockid_t)clk_id, &ts);
325
0
    if (ret != 0) {
326
0
        PyErr_SetFromErrno(PyExc_OSError);
327
0
        return NULL;
328
0
    }
329
0
    Py_RETURN_NONE;
330
0
}
331
332
#endif   /* HAVE_CLOCK_SETTIME */
333
334
#ifdef HAVE_CLOCK_GETRES
335
/*[clinic input]
336
time.clock_getres -> double
337
338
    clk_id: int
339
    /
340
341
Return the resolution (precision) of the specified clock clk_id.
342
[clinic start generated code]*/
343
344
static double
345
time_clock_getres_impl(PyObject *module, int clk_id)
346
/*[clinic end generated code: output=94c4fb7df9f0c2f2 input=d1409a8b5b3be180]*/
347
0
{
348
0
    int ret;
349
0
    struct timespec tp;
350
351
0
    ret = clock_getres((clockid_t)clk_id, &tp);
352
0
    if (ret != 0) {
353
0
        PyErr_SetFromErrno(PyExc_OSError);
354
0
        return -1.0;
355
0
    }
356
357
0
    return tp.tv_sec + tp.tv_nsec * 1e-9;
358
0
}
359
360
#ifdef __APPLE__
361
#pragma clang diagnostic pop
362
#endif
363
364
#endif   /* HAVE_CLOCK_GETRES */
365
366
#ifdef HAVE_PTHREAD_GETCPUCLOCKID
367
/*[clinic input]
368
time.pthread_getcpuclockid
369
370
    thread_id: unsigned_long(bitwise=True)
371
    /
372
373
Return the clk_id of a thread's CPU time clock.
374
[clinic start generated code]*/
375
376
static PyObject *
377
time_pthread_getcpuclockid_impl(PyObject *module, unsigned long thread_id)
378
/*[clinic end generated code: output=4fc7d4cb73d2e894 input=eb8af7bbcf189270]*/
379
0
{
380
0
    int err;
381
0
    clockid_t clk_id;
382
0
    err = pthread_getcpuclockid((pthread_t)thread_id, &clk_id);
383
0
    if (err) {
384
0
        errno = err;
385
0
        PyErr_SetFromErrno(PyExc_OSError);
386
0
        return NULL;
387
0
    }
388
#ifdef _Py_MEMORY_SANITIZER
389
    __msan_unpoison(&clk_id, sizeof(clk_id));
390
#endif
391
0
    return PyLong_FromLong(clk_id);
392
0
}
393
394
#endif /* HAVE_PTHREAD_GETCPUCLOCKID */
395
396
/*[clinic input]
397
time.sleep
398
399
    seconds as timeout_obj: object
400
    /
401
402
Delay execution for a given number of seconds.
403
404
The argument may be a floating-point number for subsecond precision.
405
[clinic start generated code]*/
406
407
static PyObject *
408
time_sleep(PyObject *module, PyObject *timeout_obj)
409
/*[clinic end generated code: output=f46e88f5f5756f65 input=3928b1704a2faa12]*/
410
0
{
411
0
    if (PySys_Audit("time.sleep", "O", timeout_obj) < 0) {
412
0
        return NULL;
413
0
    }
414
415
0
    PyTime_t timeout;
416
0
    if (_PyTime_FromSecondsObject(&timeout, timeout_obj, _PyTime_ROUND_TIMEOUT))
417
0
        return NULL;
418
0
    if (timeout < 0) {
419
0
        PyErr_SetString(PyExc_ValueError,
420
0
                        "sleep length must be non-negative");
421
0
        return NULL;
422
0
    }
423
0
    if (pysleep(timeout) != 0) {
424
0
        return NULL;
425
0
    }
426
0
    Py_RETURN_NONE;
427
0
}
428
429
static PyStructSequence_Field struct_time_type_fields[] = {
430
    {"tm_year", "year, for example, 1993"},
431
    {"tm_mon", "month of year, range [1, 12]"},
432
    {"tm_mday", "day of month, range [1, 31]"},
433
    {"tm_hour", "hours, range [0, 23]"},
434
    {"tm_min", "minutes, range [0, 59]"},
435
    {"tm_sec", "seconds, range [0, 61])"},
436
    {"tm_wday", "day of week, range [0, 6], Monday is 0"},
437
    {"tm_yday", "day of year, range [1, 366]"},
438
    {"tm_isdst", "1 if summer time is in effect, 0 if not, and -1 if unknown"},
439
    {"tm_zone", "abbreviation of timezone name"},
440
    {"tm_gmtoff", "offset from UTC in seconds"},
441
    {0}
442
};
443
444
static PyStructSequence_Desc struct_time_type_desc = {
445
    "time.struct_time",
446
    "The time value as returned by gmtime(), localtime(), and strptime(), and\n"
447
    " accepted by asctime(), mktime() and strftime().  May be considered as a\n"
448
    " sequence of 9 integers.\n\n"
449
    " Note that several fields' values are not the same as those defined by\n"
450
    " the C language standard for struct tm.  For example, the value of the\n"
451
    " field tm_year is the actual year, not year - 1900.  See individual\n"
452
    " fields' descriptions for details.",
453
    struct_time_type_fields,
454
    9,
455
};
456
457
#if defined(MS_WINDOWS)
458
#ifndef CREATE_WAITABLE_TIMER_HIGH_RESOLUTION
459
  #define CREATE_WAITABLE_TIMER_HIGH_RESOLUTION 0x00000002
460
#endif
461
462
static DWORD timer_flags = (DWORD)-1;
463
#endif
464
465
static PyObject *
466
tmtotuple(time_module_state *state, struct tm *p
467
#ifndef HAVE_STRUCT_TM_TM_ZONE
468
        , const char *zone, time_t gmtoff
469
#endif
470
)
471
0
{
472
0
    PyObject *v = PyStructSequence_New(state->struct_time_type);
473
0
    if (v == NULL)
474
0
        return NULL;
475
476
0
#define SET_ITEM(INDEX, CALL)                       \
477
0
    do {                                            \
478
0
        PyObject *obj = (CALL);                     \
479
0
        if (obj == NULL) {                          \
480
0
            Py_DECREF(v);                           \
481
0
            return NULL;                            \
482
0
        }                                           \
483
0
        PyStructSequence_SET_ITEM(v, (INDEX), obj); \
484
0
    } while (0)
485
486
0
#define SET(INDEX, VAL) \
487
0
    SET_ITEM((INDEX), PyLong_FromLong((long) (VAL)))
488
489
0
    SET(0, p->tm_year + 1900);
490
0
    SET(1, p->tm_mon + 1);         /* Want January == 1 */
491
0
    SET(2, p->tm_mday);
492
0
    SET(3, p->tm_hour);
493
0
    SET(4, p->tm_min);
494
0
    SET(5, p->tm_sec);
495
0
    SET(6, (p->tm_wday + 6) % 7); /* Want Monday == 0 */
496
0
    SET(7, p->tm_yday + 1);        /* Want January, 1 == 1 */
497
0
    SET(8, p->tm_isdst);
498
0
#ifdef HAVE_STRUCT_TM_TM_ZONE
499
0
    SET_ITEM(9, PyUnicode_DecodeLocale(p->tm_zone, "surrogateescape"));
500
0
    SET(10, p->tm_gmtoff);
501
#else
502
    SET_ITEM(9, PyUnicode_DecodeLocale(zone, "surrogateescape"));
503
    SET_ITEM(10, _PyLong_FromTime_t(gmtoff));
504
#endif /* HAVE_STRUCT_TM_TM_ZONE */
505
506
0
#undef SET
507
0
#undef SET_ITEM
508
509
0
    return v;
510
0
}
511
512
/* Convert a number of seconds since the Epoch, or None which means the
513
   current time, to time_t.
514
   Returns non-zero on success (parallels PyArg_ParseTuple).
515
*/
516
static int
517
parse_time_t_arg(PyObject *ot, time_t *pwhen)
518
0
{
519
0
    time_t whent;
520
521
0
    if (ot == Py_None) {
522
0
        whent = time(NULL);
523
0
    }
524
0
    else {
525
0
        if (_PyTime_ObjectToTime_t(ot, &whent, _PyTime_ROUND_FLOOR) == -1)
526
0
            return 0;
527
0
    }
528
0
    *pwhen = whent;
529
0
    return 1;
530
0
}
531
532
/*[clinic input]
533
time.gmtime
534
535
    seconds as ot: object = None
536
    /
537
538
Convert seconds since the Epoch to a time tuple expressing UTC.
539
540
That is, Greenwich Mean Time.  When 'seconds' is not passed in, convert
541
the current time instead.
542
543
If the platform supports the tm_gmtoff and tm_zone, they are available
544
as attributes only.
545
[clinic start generated code]*/
546
547
static PyObject *
548
time_gmtime_impl(PyObject *module, PyObject *ot)
549
/*[clinic end generated code: output=375372dd236a6ed6 input=784de5b57649d4d7]*/
550
0
{
551
0
    time_t when;
552
0
    struct tm buf;
553
554
0
    if (!parse_time_t_arg(ot, &when))
555
0
        return NULL;
556
557
0
    errno = 0;
558
0
    if (_PyTime_gmtime(when, &buf) != 0)
559
0
        return NULL;
560
561
0
    time_module_state *state = get_time_state(module);
562
0
#ifdef HAVE_STRUCT_TM_TM_ZONE
563
0
    return tmtotuple(state, &buf);
564
#else
565
    return tmtotuple(state, &buf, "UTC", 0);
566
#endif
567
0
}
568
569
#ifndef HAVE_TIMEGM
570
static time_t
571
timegm(struct tm *p)
572
{
573
    /* XXX: the following implementation will not work for tm_year < 1970.
574
       but it is likely that platforms that don't have timegm do not support
575
       negative timestamps anyways. */
576
    return p->tm_sec + p->tm_min*60 + p->tm_hour*3600 + p->tm_yday*86400 +
577
        (p->tm_year-70)*31536000 + ((p->tm_year-69)/4)*86400 -
578
        ((p->tm_year-1)/100)*86400 + ((p->tm_year+299)/400)*86400;
579
}
580
#endif
581
582
/*[clinic input]
583
time.localtime
584
585
    seconds as ot: object = None
586
    /
587
588
Convert seconds since the Epoch to a time tuple expressing local time.
589
590
When 'seconds' is not passed in, convert the current time instead.
591
[clinic start generated code]*/
592
593
static PyObject *
594
time_localtime_impl(PyObject *module, PyObject *ot)
595
/*[clinic end generated code: output=d3c1c6818abd34a1 input=43b4e8bf4914300e]*/
596
0
{
597
0
    time_t when;
598
0
    struct tm buf;
599
600
0
    if (!parse_time_t_arg(ot, &when))
601
0
        return NULL;
602
0
    if (_PyTime_localtime(when, &buf) != 0)
603
0
        return NULL;
604
605
0
    time_module_state *state = get_time_state(module);
606
0
#ifdef HAVE_STRUCT_TM_TM_ZONE
607
0
    return tmtotuple(state, &buf);
608
#else
609
    {
610
        struct tm local = buf;
611
        char zone[100];
612
        time_t gmtoff;
613
        strftime(zone, sizeof(zone), "%Z", &buf);
614
        gmtoff = timegm(&buf) - when;
615
        return tmtotuple(state, &local, zone, gmtoff);
616
    }
617
#endif
618
0
}
619
620
#if defined(__linux__) && !defined(__GLIBC__)
621
static const char *utc_string = NULL;
622
#endif
623
624
/* Convert 9-item tuple to tm structure.  Return 1 on success, set
625
 * an exception and return 0 on error.
626
 */
627
static int
628
gettmarg(time_module_state *state, PyObject *args,
629
         struct tm *p, const char *format)
630
0
{
631
0
    int y;
632
633
0
    memset((void *) p, '\0', sizeof(struct tm));
634
635
0
    if (!PyTuple_Check(args)) {
636
0
        PyErr_SetString(PyExc_TypeError,
637
0
                        "Tuple or struct_time argument required");
638
0
        return 0;
639
0
    }
640
641
0
    if (!PyArg_ParseTuple(args, format,
642
0
                          &y, &p->tm_mon, &p->tm_mday,
643
0
                          &p->tm_hour, &p->tm_min, &p->tm_sec,
644
0
                          &p->tm_wday, &p->tm_yday, &p->tm_isdst))
645
0
        return 0;
646
647
0
    if (y < INT_MIN + 1900) {
648
0
        PyErr_SetString(PyExc_OverflowError, "year out of range");
649
0
        return 0;
650
0
    }
651
652
0
    p->tm_year = y - 1900;
653
0
    p->tm_mon--;
654
0
    p->tm_wday = (p->tm_wday + 1) % 7;
655
0
    p->tm_yday--;
656
0
#ifdef HAVE_STRUCT_TM_TM_ZONE
657
0
    if (Py_IS_TYPE(args, state->struct_time_type)) {
658
0
        PyObject *item;
659
0
        item = PyStructSequence_GET_ITEM(args, 9);
660
0
        if (item != Py_None) {
661
0
            p->tm_zone = (char *)PyUnicode_AsUTF8(item);
662
0
            if (p->tm_zone == NULL) {
663
0
                return 0;
664
0
            }
665
#if defined(__linux__) && !defined(__GLIBC__)
666
            // Make an attempt to return the C library's own timezone strings to
667
            // it. musl refuses to process a tm_zone field unless it produced
668
            // it. See issue #34672.
669
            if (utc_string && strcmp(p->tm_zone, utc_string) == 0) {
670
                p->tm_zone = utc_string;
671
            }
672
            else if (tzname[0] && strcmp(p->tm_zone, tzname[0]) == 0) {
673
                p->tm_zone = tzname[0];
674
            }
675
            else if (tzname[1] && strcmp(p->tm_zone, tzname[1]) == 0) {
676
                p->tm_zone = tzname[1];
677
            }
678
#endif
679
0
        }
680
0
        item = PyStructSequence_GET_ITEM(args, 10);
681
0
        if (item != Py_None) {
682
0
            p->tm_gmtoff = PyLong_AsLong(item);
683
0
            if (PyErr_Occurred())
684
0
                return 0;
685
0
        }
686
0
    }
687
0
#endif /* HAVE_STRUCT_TM_TM_ZONE */
688
0
    return 1;
689
0
}
690
691
/* Check values of the struct tm fields before it is passed to strftime() and
692
 * asctime().  Return 1 if all values are valid, otherwise set an exception
693
 * and returns 0.
694
 */
695
static int
696
checktm(struct tm* buf)
697
0
{
698
    /* Checks added to make sure strftime() and asctime() does not crash Python by
699
       indexing blindly into some array for a textual representation
700
       by some bad index (fixes bug #897625 and #6608).
701
702
       Also support values of zero from Python code for arguments in which
703
       that is out of range by forcing that value to the lowest value that
704
       is valid (fixed bug #1520914).
705
706
       Valid ranges based on what is allowed in struct tm:
707
708
       - tm_year: [0, max(int)] (1)
709
       - tm_mon: [0, 11] (2)
710
       - tm_mday: [1, 31]
711
       - tm_hour: [0, 23]
712
       - tm_min: [0, 59]
713
       - tm_sec: [0, 60]
714
       - tm_wday: [0, 6] (1)
715
       - tm_yday: [0, 365] (2)
716
       - tm_isdst: [-max(int), max(int)]
717
718
       (1) gettmarg() handles bounds-checking.
719
       (2) Python's acceptable range is one greater than the range in C,
720
       thus need to check against automatic decrement by gettmarg().
721
    */
722
0
    if (buf->tm_mon == -1)
723
0
        buf->tm_mon = 0;
724
0
    else if (buf->tm_mon < 0 || buf->tm_mon > 11) {
725
0
        PyErr_SetString(PyExc_ValueError, "month out of range");
726
0
        return 0;
727
0
    }
728
0
    if (buf->tm_mday == 0)
729
0
        buf->tm_mday = 1;
730
0
    else if (buf->tm_mday < 0 || buf->tm_mday > 31) {
731
0
        PyErr_SetString(PyExc_ValueError, "day of month out of range");
732
0
        return 0;
733
0
    }
734
0
    if (buf->tm_hour < 0 || buf->tm_hour > 23) {
735
0
        PyErr_SetString(PyExc_ValueError, "hour out of range");
736
0
        return 0;
737
0
    }
738
0
    if (buf->tm_min < 0 || buf->tm_min > 59) {
739
0
        PyErr_SetString(PyExc_ValueError, "minute out of range");
740
0
        return 0;
741
0
    }
742
0
    if (buf->tm_sec < 0 || buf->tm_sec > 61) {
743
0
        PyErr_SetString(PyExc_ValueError, "seconds out of range");
744
0
        return 0;
745
0
    }
746
    /* tm_wday does not need checking of its upper-bound since taking
747
    ``% 7`` in gettmarg() automatically restricts the range. */
748
0
    if (buf->tm_wday < 0) {
749
0
        PyErr_SetString(PyExc_ValueError, "day of week out of range");
750
0
        return 0;
751
0
    }
752
0
    if (buf->tm_yday == -1)
753
0
        buf->tm_yday = 0;
754
0
    else if (buf->tm_yday < 0 || buf->tm_yday > 365) {
755
0
        PyErr_SetString(PyExc_ValueError, "day of year out of range");
756
0
        return 0;
757
0
    }
758
0
    return 1;
759
0
}
760
761
#define STRFTIME_FORMAT_CODES \
762
"Commonly used format codes:\n\
763
\n\
764
%Y  Year with century as a decimal number.\n\
765
%m  Month as a decimal number [01,12].\n\
766
%d  Day of the month as a decimal number [01,31].\n\
767
%H  Hour (24-hour clock) as a decimal number [00,23].\n\
768
%M  Minute as a decimal number [00,59].\n\
769
%S  Second as a decimal number [00,61].\n\
770
%z  Time zone offset from UTC.\n\
771
%a  Locale's abbreviated weekday name.\n\
772
%A  Locale's full weekday name.\n\
773
%b  Locale's abbreviated month name.\n\
774
%B  Locale's full month name.\n\
775
%c  Locale's appropriate date and time representation.\n\
776
%I  Hour (12-hour clock) as a decimal number [01,12].\n\
777
%p  Locale's equivalent of either AM or PM.\n\
778
\n\
779
Other codes may be available on your platform.  See documentation for\n\
780
the C library strftime function.\n"
781
782
#ifdef HAVE_STRFTIME
783
// gh-154460: OpenBSD's wcsftime() computes %V incorrectly: it returns 53
784
// whenever the ISO 8601 week belongs to a different year than tm_year.
785
// strftime() is not affected.
786
#ifdef __OpenBSD__
787
#  undef HAVE_WCSFTIME
788
#endif
789
790
#ifdef HAVE_WCSFTIME
791
0
#define time_char wchar_t
792
0
#define format_time wcsftime
793
#define time_strlen wcslen
794
#else
795
#define time_char char
796
#define format_time strftime
797
#define time_strlen strlen
798
#endif
799
800
static PyObject *
801
time_strftime1(time_char **outbuf, size_t *bufsize,
802
               time_char *format, size_t fmtlen,
803
               struct tm *tm)
804
0
{
805
0
    size_t buflen;
806
#if defined(MS_WINDOWS) && !defined(HAVE_WCSFTIME)
807
    /* check that the format string contains only valid directives */
808
    for (const time_char *f = strchr(format, '%');
809
        f != NULL;
810
        f = strchr(f + 2, '%'))
811
    {
812
        if (f[1] == '#')
813
            ++f; /* not documented by python, */
814
        if (f[1] == '\0')
815
            break;
816
        if ((f[1] == 'y') && tm->tm_year < 0) {
817
            PyErr_SetString(PyExc_ValueError,
818
                            "format %y requires year >= 1900 on Windows");
819
            return NULL;
820
        }
821
    }
822
#elif (defined(_AIX) || (defined(__sun) && defined(__SVR4))) && defined(HAVE_WCSFTIME)
823
    for (const time_char *f = wcschr(format, '%');
824
        f != NULL;
825
        f = wcschr(f + 2, '%'))
826
    {
827
        if (f[1] == L'\0')
828
            break;
829
        /* Issue #19634: On AIX, wcsftime("y", (1899, 1, 1, 0, 0, 0, 0, 0, 0))
830
           returns "0/" instead of "99" */
831
        if (f[1] == L'y' && tm->tm_year < 0) {
832
            PyErr_SetString(PyExc_ValueError,
833
                            "format %y requires year >= 1900 on AIX");
834
            return NULL;
835
        }
836
    }
837
#endif
838
839
    /* I hate these functions that presume you know how big the output
840
     * will be ahead of time...
841
     */
842
0
    while (1) {
843
0
        if (*bufsize > PY_SSIZE_T_MAX/sizeof(time_char)) {
844
0
            PyErr_NoMemory();
845
0
            return NULL;
846
0
        }
847
0
        time_char *tmp = (time_char *)PyMem_Realloc(*outbuf,
848
0
                                                    *bufsize*sizeof(time_char));
849
0
        if (tmp == NULL) {
850
0
            PyMem_Free(*outbuf);
851
0
            *outbuf = NULL;
852
0
            PyErr_NoMemory();
853
0
            return NULL;
854
0
        }
855
0
        *outbuf = tmp;
856
#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
857
        errno = 0;
858
#endif
859
0
        _Py_BEGIN_SUPPRESS_IPH
860
0
        buflen = format_time(*outbuf, *bufsize, format, tm);
861
0
        _Py_END_SUPPRESS_IPH
862
#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
863
        /* VisualStudio .NET 2005 does this properly */
864
        if (buflen == 0 && errno == EINVAL) {
865
            PyErr_SetString(PyExc_ValueError, "Invalid format string");
866
            return NULL;
867
        }
868
#endif
869
0
        if (buflen == 0 && *bufsize < 256 * fmtlen) {
870
0
            *bufsize += *bufsize;
871
0
            continue;
872
0
        }
873
        /* If the buffer is 256 times as long as the format,
874
           it's probably not failing for lack of room!
875
           More likely, the format yields an empty result,
876
           e.g. an empty format, or %Z when the timezone
877
           is unknown. */
878
0
#ifdef HAVE_WCSFTIME
879
0
        return PyUnicode_FromWideChar(*outbuf, buflen);
880
#else
881
        return PyUnicode_DecodeLocaleAndSize(*outbuf, buflen, "surrogateescape");
882
#endif
883
0
    }
884
0
}
885
886
static PyObject *
887
time_strftime(PyObject *module, PyObject *args)
888
0
{
889
0
    PyObject *tup = NULL;
890
0
    struct tm buf;
891
0
    PyObject *format_arg;
892
0
    Py_ssize_t format_size;
893
0
    time_char *format, *outbuf = NULL;
894
0
    size_t fmtlen, bufsize = 1024;
895
896
0
    memset((void *) &buf, '\0', sizeof(buf));
897
898
0
    if (!PyArg_ParseTuple(args, "U|O:strftime", &format_arg, &tup))
899
0
        return NULL;
900
901
0
    time_module_state *state = get_time_state(module);
902
0
    if (tup == NULL) {
903
0
        time_t tt = time(NULL);
904
0
        if (_PyTime_localtime(tt, &buf) != 0)
905
0
            return NULL;
906
0
    }
907
0
    else if (!gettmarg(state, tup, &buf,
908
0
                       "iiiiiiiii;strftime(): illegal time tuple argument") ||
909
0
             !checktm(&buf))
910
0
    {
911
0
        return NULL;
912
0
    }
913
914
// Some platforms only support a limited range of years.
915
//
916
// Android works with negative years on the emulator, but fails on some
917
// physical devices (#123017).
918
#if defined(_MSC_VER) || (defined(__sun) && defined(__SVR4)) || defined(_AIX) \
919
    || defined(__VXWORKS__) || defined(__ANDROID__)
920
    if (buf.tm_year + 1900 < 1 || 9999 < buf.tm_year + 1900) {
921
        PyErr_SetString(PyExc_ValueError,
922
                        "strftime() requires year in [1; 9999]");
923
        return NULL;
924
    }
925
#endif
926
927
    /* Normalize tm_isdst just in case someone foolishly implements %Z
928
       based on the assumption that tm_isdst falls within the range of
929
       [-1, 1] */
930
0
    if (buf.tm_isdst < -1)
931
0
        buf.tm_isdst = -1;
932
0
    else if (buf.tm_isdst > 1)
933
0
        buf.tm_isdst = 1;
934
935
0
    format_size = PyUnicode_GET_LENGTH(format_arg);
936
0
    if ((size_t)format_size > PY_SSIZE_T_MAX/sizeof(time_char) - 1) {
937
0
        PyErr_NoMemory();
938
0
        return NULL;
939
0
    }
940
0
    format = PyMem_Malloc((format_size + 1)*sizeof(time_char));
941
0
    if (format == NULL) {
942
0
        PyErr_NoMemory();
943
0
        return NULL;
944
0
    }
945
0
    PyUnicodeWriter *writer = PyUnicodeWriter_Create(0);
946
0
    if (writer == NULL) {
947
0
        goto error;
948
0
    }
949
0
    Py_ssize_t i = 0;
950
0
    while (i < format_size) {
951
0
        fmtlen = 0;
952
0
        for (; i < format_size; i++) {
953
0
            Py_UCS4 c = PyUnicode_READ_CHAR(format_arg, i);
954
0
            if (!c || c > 127) {
955
0
                break;
956
0
            }
957
0
            format[fmtlen++] = (char)c;
958
0
        }
959
0
        if (fmtlen) {
960
0
            format[fmtlen] = 0;
961
0
            PyObject *unicode = time_strftime1(&outbuf, &bufsize,
962
0
                                               format, fmtlen, &buf);
963
0
            if (unicode == NULL) {
964
0
                goto error;
965
0
            }
966
0
            if (PyUnicodeWriter_WriteStr(writer, unicode) < 0) {
967
0
                Py_DECREF(unicode);
968
0
                goto error;
969
0
            }
970
0
            Py_DECREF(unicode);
971
0
        }
972
973
0
        Py_ssize_t start = i;
974
0
        for (; i < format_size; i++) {
975
0
            Py_UCS4 c = PyUnicode_READ_CHAR(format_arg, i);
976
0
            if (c == '%') {
977
0
                break;
978
0
            }
979
0
        }
980
0
        if (PyUnicodeWriter_WriteSubstring(writer, format_arg, start, i) < 0) {
981
0
            goto error;
982
0
        }
983
0
    }
984
985
0
    PyMem_Free(outbuf);
986
0
    PyMem_Free(format);
987
0
    return PyUnicodeWriter_Finish(writer);
988
0
error:
989
0
    PyMem_Free(outbuf);
990
0
    PyMem_Free(format);
991
0
    PyUnicodeWriter_Discard(writer);
992
0
    return NULL;
993
0
}
994
995
#undef time_char
996
#undef format_time
997
PyDoc_STRVAR(strftime_doc,
998
"strftime(format[, time_tuple]) -> string\n\
999
\n\
1000
Convert a time tuple to a string according to a format specification.\n\
1001
See the library reference manual for formatting codes. When the time tuple\n\
1002
is not present, current time as returned by localtime() is used.\n\
1003
\n" STRFTIME_FORMAT_CODES);
1004
#endif /* HAVE_STRFTIME */
1005
1006
static PyObject *
1007
time_strptime(PyObject *self, PyObject *args)
1008
0
{
1009
0
    PyObject *func, *result;
1010
1011
0
    func = PyImport_ImportModuleAttrString("_strptime", "_strptime_time");
1012
0
    if (!func) {
1013
0
        return NULL;
1014
0
    }
1015
1016
0
    result = PyObject_Call(func, args, NULL);
1017
0
    Py_DECREF(func);
1018
0
    return result;
1019
0
}
1020
1021
1022
PyDoc_STRVAR(strptime_doc,
1023
"strptime(string[, format]) -> struct_time\n\
1024
\n\
1025
Parse a string to a time tuple according to a format specification.\n\
1026
See the library reference manual for formatting codes (same as\n\
1027
strftime()).\n\
1028
\n" STRFTIME_FORMAT_CODES);
1029
1030
static PyObject *
1031
_asctime(struct tm *timeptr)
1032
0
{
1033
    /* Inspired by Open Group reference implementation available at
1034
     * http://pubs.opengroup.org/onlinepubs/009695399/functions/asctime.html */
1035
0
    static const char wday_name[7][4] = {
1036
0
        "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
1037
0
    };
1038
0
    static const char mon_name[12][4] = {
1039
0
        "Jan", "Feb", "Mar", "Apr", "May", "Jun",
1040
0
        "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
1041
0
    };
1042
0
    return PyUnicode_FromFormat(
1043
0
        "%s %s%3d %.2d:%.2d:%.2d %d",
1044
0
        wday_name[timeptr->tm_wday],
1045
0
        mon_name[timeptr->tm_mon],
1046
0
        timeptr->tm_mday, timeptr->tm_hour,
1047
0
        timeptr->tm_min, timeptr->tm_sec,
1048
0
        1900 + timeptr->tm_year);
1049
0
}
1050
1051
/*[clinic input]
1052
time.asctime
1053
1054
    time_tuple as tup: object = NULL
1055
    /
1056
1057
Convert a time tuple to a string, e.g. 'Sat Jun 06 16:26:11 1998'.
1058
1059
When the time tuple is not present, current time as returned by
1060
localtime() is used.
1061
[clinic start generated code]*/
1062
1063
static PyObject *
1064
time_asctime_impl(PyObject *module, PyObject *tup)
1065
/*[clinic end generated code: output=a1bc45f84a00fb55 input=083c132f3cb23f1e]*/
1066
0
{
1067
0
    struct tm buf;
1068
1069
0
    time_module_state *state = get_time_state(module);
1070
0
    if (tup == NULL) {
1071
0
        time_t tt = time(NULL);
1072
0
        if (_PyTime_localtime(tt, &buf) != 0)
1073
0
            return NULL;
1074
0
    }
1075
0
    else if (!gettmarg(state, tup, &buf,
1076
0
                       "iiiiiiiii;asctime(): illegal time tuple argument") ||
1077
0
             !checktm(&buf))
1078
0
    {
1079
0
        return NULL;
1080
0
    }
1081
0
    return _asctime(&buf);
1082
0
}
1083
1084
/*[clinic input]
1085
time.ctime
1086
1087
    seconds as ot: object = None
1088
    /
1089
1090
Convert a time in seconds since the Epoch to a string in local time.
1091
1092
This is equivalent to asctime(localtime(seconds)).  When 'seconds' is
1093
not passed in, convert the current time instead.
1094
[clinic start generated code]*/
1095
1096
static PyObject *
1097
time_ctime_impl(PyObject *module, PyObject *ot)
1098
/*[clinic end generated code: output=c3a028f5c6931cbc input=ee744f25ce87d1ae]*/
1099
0
{
1100
0
    time_t tt;
1101
0
    struct tm buf;
1102
0
    if (!parse_time_t_arg(ot, &tt))
1103
0
        return NULL;
1104
0
    if (_PyTime_localtime(tt, &buf) != 0)
1105
0
        return NULL;
1106
0
    return _asctime(&buf);
1107
0
}
1108
1109
#ifdef HAVE_MKTIME
1110
/*[clinic input]
1111
time.mktime
1112
1113
    time_tuple as tm_tuple: object
1114
    /
1115
1116
Convert a time tuple in local time to seconds since the Epoch.
1117
1118
Note that mktime(gmtime(0)) will not generally return zero for most
1119
time zones; instead the returned value will either be equal to that of
1120
the timezone or altzone attributes on the time module.
1121
[clinic start generated code]*/
1122
1123
static PyObject *
1124
time_mktime(PyObject *module, PyObject *tm_tuple)
1125
/*[clinic end generated code: output=1b2a224cd309deb7 input=70b93e1c2e57e14e]*/
1126
0
{
1127
0
    struct tm tm;
1128
0
    time_t tt;
1129
1130
0
    time_module_state *state = get_time_state(module);
1131
0
    if (!gettmarg(state, tm_tuple, &tm,
1132
0
                  "iiiiiiiii;mktime(): illegal time tuple argument"))
1133
0
    {
1134
0
        return NULL;
1135
0
    }
1136
1137
#if defined(_AIX) || (defined(__VXWORKS__) && !defined(_WRS_CONFIG_LP64))
1138
    /* bpo-19748: AIX mktime() valid range is 00:00:00 UTC, January 1, 1970
1139
       to 03:14:07 UTC, January 19, 2038. Thanks to the workaround below,
1140
       it is possible to support years in range [1902; 2037] */
1141
    if (tm.tm_year < 2 || tm.tm_year > 137) {
1142
        /* bpo-19748: On AIX, mktime() does not report overflow error
1143
           for timestamp < -2^31 or timestamp > 2**31-1. VxWorks has the
1144
           same issue when working in 32 bit mode. */
1145
        PyErr_SetString(PyExc_OverflowError,
1146
                        "mktime argument out of range");
1147
        return NULL;
1148
    }
1149
#endif
1150
1151
#ifdef _AIX
1152
    /* bpo-34373: AIX mktime() has an integer overflow for years in range
1153
       [1902; 1969]. Workaround the issue by using a year greater or equal than
1154
       1970 (tm_year >= 70): mktime() behaves correctly in that case
1155
       (ex: properly report errors). tm_year and tm_wday are adjusted after
1156
       mktime() call. */
1157
    int orig_tm_year = tm.tm_year;
1158
    int delta_days = 0;
1159
    while (tm.tm_year < 70) {
1160
        /* Use 4 years to account properly leap years */
1161
        tm.tm_year += 4;
1162
        delta_days -= (366 + (365 * 3));
1163
    }
1164
#endif
1165
1166
0
    tm.tm_wday = -1;  /* sentinel; original value ignored */
1167
0
    tt = mktime(&tm);
1168
1169
    /* Return value of -1 does not necessarily mean an error, but tm_wday
1170
     * cannot remain set to -1 if mktime succeeded. */
1171
0
    if (tt == (time_t)(-1)
1172
        /* Return value of -1 does not necessarily mean an error, but
1173
         * tm_wday cannot remain set to -1 if mktime succeeded. */
1174
0
        && tm.tm_wday == -1)
1175
0
    {
1176
0
        PyErr_SetString(PyExc_OverflowError,
1177
0
                        "mktime argument out of range");
1178
0
        return NULL;
1179
0
    }
1180
1181
#ifdef _AIX
1182
    if (delta_days != 0) {
1183
        tm.tm_year = orig_tm_year;
1184
        if (tm.tm_wday != -1) {
1185
            tm.tm_wday = (tm.tm_wday + delta_days) % 7;
1186
        }
1187
        tt += delta_days * (24 * 3600);
1188
    }
1189
#endif
1190
1191
0
    return PyFloat_FromDouble((double)tt);
1192
0
}
1193
1194
#endif /* HAVE_MKTIME */
1195
1196
#ifdef HAVE_WORKING_TZSET
1197
static int init_timezone(PyObject *module);
1198
1199
/*[clinic input]
1200
time.tzset
1201
1202
Initialize, or reinitialize, the local timezone.
1203
1204
The local timezone is set to the value stored in os.environ['TZ'].  The
1205
TZ environment variable should be specified in standard Unix timezone
1206
format as documented in the tzset man page (eg. 'US/Eastern',
1207
'Europe/Amsterdam').  Unknown timezones will silently fall back to UTC.
1208
If the TZ environment variable is not set, the local timezone is set to
1209
the systems best guess of wallclock time.  Changing the TZ environment
1210
variable without calling tzset *may* change the local timezone used by
1211
methods such as localtime, but this behaviour should not be relied on.
1212
[clinic start generated code]*/
1213
1214
static PyObject *
1215
time_tzset_impl(PyObject *module)
1216
/*[clinic end generated code: output=d1564ac4d48d320b input=a4d11aab49badf88]*/
1217
0
{
1218
0
    PyObject* m;
1219
1220
0
    m = PyImport_ImportModule("time");
1221
0
    if (m == NULL) {
1222
0
        return NULL;
1223
0
    }
1224
1225
0
#if !defined(MS_WINDOWS) || defined(MS_WINDOWS_DESKTOP) || defined(MS_WINDOWS_SYSTEM)
1226
0
    tzset();
1227
0
#endif
1228
1229
    /* Reset timezone, altzone, daylight and tzname */
1230
0
    if (init_timezone(m) < 0) {
1231
0
        Py_DECREF(m);
1232
0
        return NULL;
1233
0
    }
1234
0
    Py_DECREF(m);
1235
0
    if (PyErr_Occurred())
1236
0
        return NULL;
1237
1238
0
    Py_RETURN_NONE;
1239
0
}
1240
1241
#endif /* HAVE_WORKING_TZSET */
1242
1243
1244
/*[clinic input]
1245
time.monotonic -> double
1246
1247
Monotonic clock, cannot go backward.
1248
[clinic start generated code]*/
1249
1250
static double
1251
time_monotonic_impl(PyObject *module)
1252
/*[clinic end generated code: output=ab51899a17e16542 input=059cb42b2bad6df0]*/
1253
0
{
1254
0
    PyTime_t t;
1255
0
    if (PyTime_Monotonic(&t) < 0) {
1256
0
        return -1.0;
1257
0
    }
1258
0
    return PyTime_AsSecondsDouble(t);
1259
0
}
1260
1261
/*[clinic input]
1262
time.monotonic_ns
1263
1264
Monotonic clock, cannot go backward, as nanoseconds.
1265
[clinic start generated code]*/
1266
1267
static PyObject *
1268
time_monotonic_ns_impl(PyObject *module)
1269
/*[clinic end generated code: output=57a9261f91740349 input=14032d6b1601a300]*/
1270
0
{
1271
0
    PyTime_t t;
1272
0
    if (PyTime_Monotonic(&t) < 0) {
1273
0
        return NULL;
1274
0
    }
1275
0
    return PyLong_FromInt64(t);
1276
0
}
1277
1278
/*[clinic input]
1279
time.perf_counter -> double
1280
1281
Performance counter for benchmarking.
1282
[clinic start generated code]*/
1283
1284
static double
1285
time_perf_counter_impl(PyObject *module)
1286
/*[clinic end generated code: output=6eee280ca7b73cb1 input=f786239c5015893b]*/
1287
0
{
1288
0
    PyTime_t t;
1289
0
    if (PyTime_PerfCounter(&t) < 0) {
1290
0
        return -1.0;
1291
0
    }
1292
0
    return PyTime_AsSecondsDouble(t);
1293
0
}
1294
1295
/*[clinic input]
1296
time.perf_counter_ns
1297
1298
Performance counter for benchmarking as nanoseconds.
1299
[clinic start generated code]*/
1300
1301
static PyObject *
1302
time_perf_counter_ns_impl(PyObject *module)
1303
/*[clinic end generated code: output=e11a728338108d42 input=178bf260d7d48a02]*/
1304
0
{
1305
0
    PyTime_t t;
1306
0
    if (PyTime_PerfCounter(&t) < 0) {
1307
0
        return NULL;
1308
0
    }
1309
0
    return PyLong_FromInt64(t);
1310
0
}
1311
1312
// gh-115714: Don't use times() on WASI.
1313
#if defined(HAVE_TIMES) && !defined(__wasi__)
1314
static int
1315
process_time_times(time_module_state *state, PyTime_t *tp,
1316
                   _Py_clock_info_t *info)
1317
0
{
1318
0
    _PyTimeFraction *base = &state->times_base;
1319
1320
0
    struct tms process;
1321
0
    if (times(&process) == (clock_t)-1) {
1322
0
        return 0;
1323
0
    }
1324
1325
0
    if (info) {
1326
0
        info->implementation = "times()";
1327
0
        info->resolution = _PyTimeFraction_Resolution(base);
1328
0
        info->monotonic = 1;
1329
0
        info->adjustable = 0;
1330
0
    }
1331
1332
0
    PyTime_t ns;
1333
0
    ns = _PyTimeFraction_Mul(process.tms_utime, base);
1334
0
    ns += _PyTimeFraction_Mul(process.tms_stime, base);
1335
0
    *tp = ns;
1336
0
    return 1;
1337
0
}
1338
#endif
1339
1340
1341
static int
1342
py_process_time(time_module_state *state, PyTime_t *tp,
1343
                _Py_clock_info_t *info)
1344
0
{
1345
#if defined(MS_WINDOWS)
1346
    HANDLE process;
1347
    FILETIME creation_time, exit_time, kernel_time, user_time;
1348
    ULARGE_INTEGER large;
1349
    PyTime_t ktime, utime;
1350
    BOOL ok;
1351
1352
    process = GetCurrentProcess();
1353
    ok = GetProcessTimes(process, &creation_time, &exit_time,
1354
                         &kernel_time, &user_time);
1355
    if (!ok) {
1356
        PyErr_SetFromWindowsErr(0);
1357
        return -1;
1358
    }
1359
1360
    if (info) {
1361
        info->implementation = "GetProcessTimes()";
1362
        info->resolution = 1e-7;
1363
        info->monotonic = 1;
1364
        info->adjustable = 0;
1365
    }
1366
1367
    large.u.LowPart = kernel_time.dwLowDateTime;
1368
    large.u.HighPart = kernel_time.dwHighDateTime;
1369
    ktime = large.QuadPart;
1370
1371
    large.u.LowPart = user_time.dwLowDateTime;
1372
    large.u.HighPart = user_time.dwHighDateTime;
1373
    utime = large.QuadPart;
1374
1375
    /* ktime and utime have a resolution of 100 nanoseconds */
1376
    *tp = (ktime + utime) * 100;
1377
    return 0;
1378
#else
1379
1380
    /* clock_gettime */
1381
// gh-115714: Don't use CLOCK_PROCESS_CPUTIME_ID on WASI.
1382
/* CLOCK_PROF is defined on NetBSD, but not supported.
1383
 * CLOCK_PROCESS_CPUTIME_ID is broken on NetBSD for the same reason as
1384
 * CLOCK_THREAD_CPUTIME_ID (see comment below).
1385
 */
1386
0
#if defined(HAVE_CLOCK_GETTIME) \
1387
0
    && (defined(CLOCK_PROCESS_CPUTIME_ID) || defined(CLOCK_PROF)) \
1388
0
    && !defined(__wasi__) \
1389
0
    && !defined(__NetBSD__)
1390
0
    struct timespec ts;
1391
1392
0
    if (HAVE_CLOCK_GETTIME_RUNTIME) {
1393
1394
#ifdef CLOCK_PROF
1395
        const clockid_t clk_id = CLOCK_PROF;
1396
        const char *function = "clock_gettime(CLOCK_PROF)";
1397
#else
1398
0
        const clockid_t clk_id = CLOCK_PROCESS_CPUTIME_ID;
1399
0
        const char *function = "clock_gettime(CLOCK_PROCESS_CPUTIME_ID)";
1400
0
#endif
1401
1402
0
        if (clock_gettime(clk_id, &ts) == 0) {
1403
0
            if (info) {
1404
0
                struct timespec res;
1405
0
                info->implementation = function;
1406
0
                info->monotonic = 1;
1407
0
                info->adjustable = 0;
1408
0
                if (clock_getres(clk_id, &res)) {
1409
0
                    PyErr_SetFromErrno(PyExc_OSError);
1410
0
                    return -1;
1411
0
                }
1412
0
                info->resolution = res.tv_sec + res.tv_nsec * 1e-9;
1413
0
            }
1414
1415
0
            if (_PyTime_FromTimespec(tp, &ts) < 0) {
1416
0
                return -1;
1417
0
            }
1418
0
            return 0;
1419
0
        }
1420
0
    }
1421
0
#endif
1422
1423
    /* getrusage(RUSAGE_SELF) */
1424
0
#if defined(HAVE_SYS_RESOURCE_H) && defined(HAVE_GETRUSAGE)
1425
0
    struct rusage ru;
1426
1427
0
    if (getrusage(RUSAGE_SELF, &ru) == 0) {
1428
0
        PyTime_t utime, stime;
1429
1430
0
        if (info) {
1431
0
            info->implementation = "getrusage(RUSAGE_SELF)";
1432
0
            info->monotonic = 1;
1433
0
            info->adjustable = 0;
1434
0
            info->resolution = 1e-6;
1435
0
        }
1436
1437
0
        if (_PyTime_FromTimeval(&utime, &ru.ru_utime) < 0) {
1438
0
            return -1;
1439
0
        }
1440
0
        if (_PyTime_FromTimeval(&stime, &ru.ru_stime) < 0) {
1441
0
            return -1;
1442
0
        }
1443
1444
0
        PyTime_t total = utime + stime;
1445
0
        *tp = total;
1446
0
        return 0;
1447
0
    }
1448
0
#endif
1449
1450
    /* times() */
1451
// gh-115714: Don't use times() on WASI.
1452
0
#if defined(HAVE_TIMES) && !defined(__wasi__)
1453
0
    int res = process_time_times(state, tp, info);
1454
0
    if (res < 0) {
1455
0
        return -1;
1456
0
    }
1457
0
    if (res == 1) {
1458
0
        return 0;
1459
0
    }
1460
    // times() failed, ignore failure
1461
0
#endif
1462
1463
    /* clock(). Python 3 requires clock() to build (see gh-66814) */
1464
0
    return py_clock(state, tp, info);
1465
0
#endif
1466
0
}
1467
1468
/*[clinic input]
1469
time.process_time -> double
1470
1471
Process time for profiling.
1472
1473
That is the sum of the kernel and user-space CPU time.
1474
[clinic start generated code]*/
1475
1476
static double
1477
time_process_time_impl(PyObject *module)
1478
/*[clinic end generated code: output=13b593cb16d415a8 input=6d539ae686c37c06]*/
1479
0
{
1480
0
    time_module_state *state = get_time_state(module);
1481
0
    PyTime_t t;
1482
0
    if (py_process_time(state, &t, NULL) < 0) {
1483
0
        return -1.0;
1484
0
    }
1485
0
    return PyTime_AsSecondsDouble(t);
1486
0
}
1487
1488
/*[clinic input]
1489
time.process_time_ns
1490
1491
Process time for profiling as nanoseconds.
1492
1493
That is the sum of the kernel and user-space CPU time.
1494
[clinic start generated code]*/
1495
1496
static PyObject *
1497
time_process_time_ns_impl(PyObject *module)
1498
/*[clinic end generated code: output=857f0c20105c4d1a input=6d998fd7a213c0cd]*/
1499
0
{
1500
0
    time_module_state *state = get_time_state(module);
1501
0
    PyTime_t t;
1502
0
    if (py_process_time(state, &t, NULL) < 0) {
1503
0
        return NULL;
1504
0
    }
1505
0
    return PyLong_FromInt64(t);
1506
0
}
1507
1508
#if defined(MS_WINDOWS)
1509
#define HAVE_THREAD_TIME
1510
static int
1511
_PyTime_GetThreadTimeWithInfo(PyTime_t *tp, _Py_clock_info_t *info)
1512
{
1513
    HANDLE thread;
1514
    FILETIME creation_time, exit_time, kernel_time, user_time;
1515
    ULARGE_INTEGER large;
1516
    PyTime_t ktime, utime;
1517
    BOOL ok;
1518
1519
    thread =  GetCurrentThread();
1520
    ok = GetThreadTimes(thread, &creation_time, &exit_time,
1521
                        &kernel_time, &user_time);
1522
    if (!ok) {
1523
        PyErr_SetFromWindowsErr(0);
1524
        return -1;
1525
    }
1526
1527
    if (info) {
1528
        info->implementation = "GetThreadTimes()";
1529
        info->resolution = 1e-7;
1530
        info->monotonic = 1;
1531
        info->adjustable = 0;
1532
    }
1533
1534
    large.u.LowPart = kernel_time.dwLowDateTime;
1535
    large.u.HighPart = kernel_time.dwHighDateTime;
1536
    ktime = large.QuadPart;
1537
1538
    large.u.LowPart = user_time.dwLowDateTime;
1539
    large.u.HighPart = user_time.dwHighDateTime;
1540
    utime = large.QuadPart;
1541
1542
    /* ktime and utime have a resolution of 100 nanoseconds */
1543
    *tp = (ktime + utime) * 100;
1544
    return 0;
1545
}
1546
1547
#elif defined(_AIX)
1548
#define HAVE_THREAD_TIME
1549
static int
1550
_PyTime_GetThreadTimeWithInfo(PyTime_t *tp, _Py_clock_info_t *info)
1551
{
1552
    /* bpo-40192: On AIX, thread_cputime() is preferred: it has nanosecond
1553
       resolution, whereas clock_gettime(CLOCK_THREAD_CPUTIME_ID)
1554
       has a resolution of 10 ms. */
1555
    thread_cputime_t tc;
1556
    if (thread_cputime(-1, &tc) != 0) {
1557
        PyErr_SetFromErrno(PyExc_OSError);
1558
        return -1;
1559
    }
1560
1561
    if (info) {
1562
        info->implementation = "thread_cputime()";
1563
        info->monotonic = 1;
1564
        info->adjustable = 0;
1565
        info->resolution = 1e-9;
1566
    }
1567
    *tp = (tc.stime + tc.utime);
1568
    return 0;
1569
}
1570
1571
#elif defined(__sun) && defined(__SVR4)
1572
#define HAVE_THREAD_TIME
1573
static int
1574
_PyTime_GetThreadTimeWithInfo(PyTime_t *tp, _Py_clock_info_t *info)
1575
{
1576
    /* bpo-35455: On Solaris, CLOCK_THREAD_CPUTIME_ID clock is not always
1577
       available; use gethrvtime() to substitute this functionality. */
1578
    if (info) {
1579
        info->implementation = "gethrvtime()";
1580
        info->resolution = 1e-9;
1581
        info->monotonic = 1;
1582
        info->adjustable = 0;
1583
    }
1584
    *tp = gethrvtime();
1585
    return 0;
1586
}
1587
1588
/* CLOCK_THREAD_CPUTIME_ID is broken on NetBSD: the result of clock_gettime()
1589
 * includes the sleeping time, that defeats the purpose of the clock.
1590
 * Also, clock_getres() does not support it.
1591
 * https://github.com/python/cpython/issues/123978
1592
 * https://gnats.netbsd.org/57512
1593
 */
1594
#elif defined(HAVE_CLOCK_GETTIME) && \
1595
      defined(CLOCK_THREAD_CPUTIME_ID) && \
1596
      !defined(__EMSCRIPTEN__) && !defined(__wasi__) && \
1597
      !defined(__NetBSD__)
1598
#define HAVE_THREAD_TIME
1599
1600
#if defined(__APPLE__) && _Py__has_attribute(availability)
1601
static int
1602
_PyTime_GetThreadTimeWithInfo(PyTime_t *tp, _Py_clock_info_t *info)
1603
     __attribute__((availability(macos, introduced=10.12)))
1604
     __attribute__((availability(ios, introduced=10.0)))
1605
     __attribute__((availability(tvos, introduced=10.0)))
1606
     __attribute__((availability(watchos, introduced=3.0)));
1607
#endif
1608
1609
static int
1610
_PyTime_GetThreadTimeWithInfo(PyTime_t *tp, _Py_clock_info_t *info)
1611
0
{
1612
0
    struct timespec ts;
1613
0
    const clockid_t clk_id = CLOCK_THREAD_CPUTIME_ID;
1614
0
    const char *function = "clock_gettime(CLOCK_THREAD_CPUTIME_ID)";
1615
1616
0
    if (clock_gettime(clk_id, &ts)) {
1617
0
        PyErr_SetFromErrno(PyExc_OSError);
1618
0
        return -1;
1619
0
    }
1620
0
    if (info) {
1621
0
        struct timespec res;
1622
0
        info->implementation = function;
1623
0
        info->monotonic = 1;
1624
0
        info->adjustable = 0;
1625
0
        if (clock_getres(clk_id, &res)) {
1626
0
            PyErr_SetFromErrno(PyExc_OSError);
1627
0
            return -1;
1628
0
        }
1629
0
        info->resolution = res.tv_sec + res.tv_nsec * 1e-9;
1630
0
    }
1631
1632
0
    if (_PyTime_FromTimespec(tp, &ts) < 0) {
1633
0
        return -1;
1634
0
    }
1635
0
    return 0;
1636
0
}
1637
#endif
1638
1639
#ifdef HAVE_THREAD_TIME
1640
#ifdef __APPLE__
1641
/*
1642
 * The clock_* functions will be removed from the module
1643
 * dict entirely when the C API is not available.
1644
 */
1645
#pragma clang diagnostic push
1646
#pragma clang diagnostic ignored "-Wunguarded-availability"
1647
#endif
1648
1649
/*[clinic input]
1650
time.thread_time -> double
1651
1652
Thread time for profiling.
1653
1654
That is the sum of the kernel and user-space CPU time.
1655
[clinic start generated code]*/
1656
1657
static double
1658
time_thread_time_impl(PyObject *module)
1659
/*[clinic end generated code: output=33f6639edb42e8f5 input=cdf4621822b8ed60]*/
1660
0
{
1661
0
    PyTime_t t;
1662
0
    if (_PyTime_GetThreadTimeWithInfo(&t, NULL) < 0) {
1663
0
        return -1.0;
1664
0
    }
1665
0
    return PyTime_AsSecondsDouble(t);
1666
0
}
1667
1668
/*[clinic input]
1669
time.thread_time_ns
1670
1671
Thread time for profiling as nanoseconds.
1672
1673
That is the sum of the kernel and user-space CPU time.
1674
[clinic start generated code]*/
1675
1676
static PyObject *
1677
time_thread_time_ns_impl(PyObject *module)
1678
/*[clinic end generated code: output=2a1ac9cc3e1d4c37 input=a79b2b91f308277d]*/
1679
0
{
1680
0
    PyTime_t t;
1681
0
    if (_PyTime_GetThreadTimeWithInfo(&t, NULL) < 0) {
1682
0
        return NULL;
1683
0
    }
1684
0
    return PyLong_FromInt64(t);
1685
0
}
1686
1687
#ifdef __APPLE__
1688
#pragma clang diagnostic pop
1689
#endif
1690
1691
#endif
1692
1693
1694
/*[clinic input]
1695
time.get_clock_info
1696
1697
    name: str
1698
    /
1699
1700
Get information of the specified clock.
1701
[clinic start generated code]*/
1702
1703
static PyObject *
1704
time_get_clock_info_impl(PyObject *module, const char *name)
1705
/*[clinic end generated code: output=a77a07bdf3554bd6 input=6812ae049f1b1031]*/
1706
0
{
1707
0
    _Py_clock_info_t info;
1708
0
    PyObject *obj = NULL, *dict, *ns;
1709
0
    PyTime_t t;
1710
1711
#ifdef Py_DEBUG
1712
    info.implementation = NULL;
1713
    info.monotonic = -1;
1714
    info.adjustable = -1;
1715
    info.resolution = -1.0;
1716
#else
1717
0
    info.implementation = "";
1718
0
    info.monotonic = 0;
1719
0
    info.adjustable = 0;
1720
0
    info.resolution = 1.0;
1721
0
#endif
1722
1723
0
    if (strcmp(name, "time") == 0) {
1724
0
        if (_PyTime_TimeWithInfo(&t, &info) < 0) {
1725
0
            return NULL;
1726
0
        }
1727
0
    }
1728
0
    else if (strcmp(name, "monotonic") == 0) {
1729
0
        if (_PyTime_MonotonicWithInfo(&t, &info) < 0) {
1730
0
            return NULL;
1731
0
        }
1732
0
    }
1733
0
    else if (strcmp(name, "perf_counter") == 0) {
1734
0
        if (_PyTime_PerfCounterWithInfo(&t, &info) < 0) {
1735
0
            return NULL;
1736
0
        }
1737
0
    }
1738
0
    else if (strcmp(name, "process_time") == 0) {
1739
0
        time_module_state *state = get_time_state(module);
1740
0
        if (py_process_time(state, &t, &info) < 0) {
1741
0
            return NULL;
1742
0
        }
1743
0
    }
1744
0
#ifdef HAVE_THREAD_TIME
1745
0
    else if (strcmp(name, "thread_time") == 0) {
1746
1747
#ifdef __APPLE__
1748
        if (HAVE_CLOCK_GETTIME_RUNTIME) {
1749
#endif
1750
0
            if (_PyTime_GetThreadTimeWithInfo(&t, &info) < 0) {
1751
0
                return NULL;
1752
0
            }
1753
#ifdef __APPLE__
1754
        } else {
1755
            PyErr_SetString(PyExc_ValueError, "unknown clock");
1756
            return NULL;
1757
        }
1758
#endif
1759
0
    }
1760
0
#endif
1761
0
    else {
1762
0
        PyErr_SetString(PyExc_ValueError, "unknown clock");
1763
0
        return NULL;
1764
0
    }
1765
1766
0
    dict = PyDict_New();
1767
0
    if (dict == NULL) {
1768
0
        return NULL;
1769
0
    }
1770
1771
0
    assert(info.implementation != NULL);
1772
0
    obj = PyUnicode_FromString(info.implementation);
1773
0
    if (obj == NULL) {
1774
0
        goto error;
1775
0
    }
1776
0
    if (PyDict_SetItemString(dict, "implementation", obj) == -1) {
1777
0
        goto error;
1778
0
    }
1779
0
    Py_CLEAR(obj);
1780
1781
0
    assert(info.monotonic != -1);
1782
0
    obj = PyBool_FromLong(info.monotonic);
1783
0
    if (obj == NULL) {
1784
0
        goto error;
1785
0
    }
1786
0
    if (PyDict_SetItemString(dict, "monotonic", obj) == -1) {
1787
0
        goto error;
1788
0
    }
1789
0
    Py_CLEAR(obj);
1790
1791
0
    assert(info.adjustable != -1);
1792
0
    obj = PyBool_FromLong(info.adjustable);
1793
0
    if (obj == NULL) {
1794
0
        goto error;
1795
0
    }
1796
0
    if (PyDict_SetItemString(dict, "adjustable", obj) == -1) {
1797
0
        goto error;
1798
0
    }
1799
0
    Py_CLEAR(obj);
1800
1801
0
    assert(info.resolution > 0.0);
1802
0
    assert(info.resolution <= 1.0);
1803
0
    obj = PyFloat_FromDouble(info.resolution);
1804
0
    if (obj == NULL) {
1805
0
        goto error;
1806
0
    }
1807
0
    if (PyDict_SetItemString(dict, "resolution", obj) == -1) {
1808
0
        goto error;
1809
0
    }
1810
0
    Py_CLEAR(obj);
1811
1812
0
    ns = _PyNamespace_New(dict);
1813
0
    Py_DECREF(dict);
1814
0
    return ns;
1815
1816
0
error:
1817
0
    Py_DECREF(dict);
1818
0
    Py_XDECREF(obj);
1819
0
    return NULL;
1820
0
}
1821
1822
#ifndef HAVE_DECL_TZNAME
1823
static void
1824
get_zone(char *zone, int n, struct tm *p)
1825
42
{
1826
42
#ifdef HAVE_STRUCT_TM_TM_ZONE
1827
42
    strncpy(zone, p->tm_zone ? p->tm_zone : "   ", n);
1828
#else
1829
    tzset();
1830
    strftime(zone, n, "%Z", p);
1831
#endif
1832
42
}
1833
1834
static time_t
1835
get_gmtoff(time_t t, struct tm *p)
1836
42
{
1837
42
#ifdef HAVE_STRUCT_TM_TM_ZONE
1838
42
    return p->tm_gmtoff;
1839
#else
1840
    return timegm(p) - t;
1841
#endif
1842
42
}
1843
#endif // !HAVE_DECL_TZNAME
1844
1845
static int
1846
init_timezone(PyObject *m)
1847
21
{
1848
63
#define ADD_INT(NAME, VALUE) do {                       \
1849
63
    if (PyModule_AddIntConstant(m, NAME, VALUE) < 0) {  \
1850
0
        return -1;                                      \
1851
0
    }                                                   \
1852
63
} while (0)
1853
1854
21
    assert(!PyErr_Occurred());
1855
1856
    /* This code moved from PyInit_time wholesale to allow calling it from
1857
    time_tzset. In the future, some parts of it can be moved back
1858
    (for platforms that don't HAVE_WORKING_TZSET, when we know what they
1859
    are), and the extraneous calls to tzset(3) should be removed.
1860
    I haven't done this yet, as I don't want to change this code as
1861
    little as possible when introducing the time.tzset and time.tzsetwall
1862
    methods. This should simply be a method of doing the following once,
1863
    at the top of this function and removing the call to tzset() from
1864
    time_tzset():
1865
1866
        #ifdef HAVE_TZSET
1867
        tzset()
1868
        #endif
1869
1870
    And I'm lazy and hate C so nyer.
1871
     */
1872
#ifdef HAVE_DECL_TZNAME
1873
    PyObject *otz0, *otz1;
1874
#if !defined(MS_WINDOWS) || defined(MS_WINDOWS_DESKTOP) || defined(MS_WINDOWS_SYSTEM)
1875
    tzset();
1876
#endif
1877
    ADD_INT("timezone", _Py_timezone);
1878
#ifdef HAVE_ALTZONE
1879
    ADD_INT("altzone", altzone);
1880
#else
1881
    ADD_INT("altzone", _Py_timezone-3600);
1882
#endif
1883
    ADD_INT("daylight", _Py_daylight);
1884
#ifdef MS_WINDOWS
1885
    TIME_ZONE_INFORMATION tzinfo = {0};
1886
    GetTimeZoneInformation(&tzinfo);
1887
    otz0 = PyUnicode_FromWideChar(tzinfo.StandardName, -1);
1888
    if (otz0 == NULL) {
1889
        return -1;
1890
    }
1891
    otz1 = PyUnicode_FromWideChar(tzinfo.DaylightName, -1);
1892
    if (otz1 == NULL) {
1893
        Py_DECREF(otz0);
1894
        return -1;
1895
    }
1896
#else
1897
    otz0 = PyUnicode_DecodeLocale(_Py_tzname[0], "surrogateescape");
1898
    if (otz0 == NULL) {
1899
        return -1;
1900
    }
1901
    otz1 = PyUnicode_DecodeLocale(_Py_tzname[1], "surrogateescape");
1902
    if (otz1 == NULL) {
1903
        Py_DECREF(otz0);
1904
        return -1;
1905
    }
1906
#endif // MS_WINDOWS
1907
    if (PyModule_Add(m, "tzname", Py_BuildValue("(NN)", otz0, otz1)) < 0) {
1908
        return -1;
1909
    }
1910
#else // !HAVE_DECL_TZNAME
1911
21
    static const time_t YEAR = (365 * 24 + 6) * 3600;
1912
21
    time_t t;
1913
21
    struct tm p;
1914
21
    time_t janzone_t, julyzone_t;
1915
21
    char janname[10], julyname[10];
1916
21
    t = (time((time_t *)0) / YEAR) * YEAR;
1917
21
    _PyTime_localtime(t, &p);
1918
21
    get_zone(janname, 9, &p);
1919
21
    janzone_t = -get_gmtoff(t, &p);
1920
21
    janname[9] = '\0';
1921
21
    t += YEAR/2;
1922
21
    _PyTime_localtime(t, &p);
1923
21
    get_zone(julyname, 9, &p);
1924
21
    julyzone_t = -get_gmtoff(t, &p);
1925
21
    julyname[9] = '\0';
1926
1927
    /* Sanity check, don't check for the validity of timezones.
1928
       In practice, it should be more in range -12 hours .. +14 hours. */
1929
147
#define MAX_TIMEZONE (48 * 3600)
1930
21
    if (janzone_t < -MAX_TIMEZONE || janzone_t > MAX_TIMEZONE
1931
21
        || julyzone_t < -MAX_TIMEZONE || julyzone_t > MAX_TIMEZONE)
1932
0
    {
1933
0
        PyErr_SetString(PyExc_RuntimeError, "invalid GMT offset");
1934
0
        return -1;
1935
0
    }
1936
21
    int janzone = (int)janzone_t;
1937
21
    int julyzone = (int)julyzone_t;
1938
1939
21
    PyObject *tzname_obj;
1940
21
    if (janzone < julyzone) {
1941
        /* DST is reversed in the southern hemisphere */
1942
0
        ADD_INT("timezone", julyzone);
1943
0
        ADD_INT("altzone", janzone);
1944
0
        ADD_INT("daylight", janzone != julyzone);
1945
0
        tzname_obj = Py_BuildValue("(zz)", julyname, janname);
1946
21
    } else {
1947
21
        ADD_INT("timezone", janzone);
1948
21
        ADD_INT("altzone", julyzone);
1949
21
        ADD_INT("daylight", janzone != julyzone);
1950
21
        tzname_obj = Py_BuildValue("(zz)", janname, julyname);
1951
21
    }
1952
21
    if (PyModule_Add(m, "tzname", tzname_obj) < 0) {
1953
0
        return -1;
1954
0
    }
1955
21
#endif // !HAVE_DECL_TZNAME
1956
21
#undef ADD_INT
1957
1958
21
    if (PyErr_Occurred()) {
1959
0
        return -1;
1960
0
    }
1961
21
    return 0;
1962
21
}
1963
1964
1965
// Include Argument Clinic code after defining converters such as
1966
// time_clockid_converter().
1967
#include "clinic/timemodule.c.h"
1968
1969
static PyMethodDef time_methods[] = {
1970
    TIME_TIME_METHODDEF
1971
    TIME_TIME_NS_METHODDEF
1972
#ifdef HAVE_CLOCK_GETTIME
1973
    TIME_CLOCK_GETTIME_METHODDEF
1974
    TIME_CLOCK_GETTIME_NS_METHODDEF
1975
#endif
1976
#ifdef HAVE_CLOCK_SETTIME
1977
    TIME_CLOCK_SETTIME_METHODDEF
1978
    TIME_CLOCK_SETTIME_NS_METHODDEF
1979
#endif
1980
#ifdef HAVE_CLOCK_GETRES
1981
    TIME_CLOCK_GETRES_METHODDEF
1982
#endif
1983
#ifdef HAVE_PTHREAD_GETCPUCLOCKID
1984
    TIME_PTHREAD_GETCPUCLOCKID_METHODDEF
1985
#endif
1986
    TIME_SLEEP_METHODDEF
1987
    TIME_GMTIME_METHODDEF
1988
    TIME_LOCALTIME_METHODDEF
1989
    TIME_ASCTIME_METHODDEF
1990
    TIME_CTIME_METHODDEF
1991
#ifdef HAVE_MKTIME
1992
    TIME_MKTIME_METHODDEF
1993
#endif
1994
#ifdef HAVE_STRFTIME
1995
    {"strftime",        time_strftime, METH_VARARGS, strftime_doc},
1996
#endif
1997
    {"strptime",        time_strptime, METH_VARARGS, strptime_doc},
1998
#ifdef HAVE_WORKING_TZSET
1999
    TIME_TZSET_METHODDEF
2000
#endif
2001
    TIME_MONOTONIC_METHODDEF
2002
    TIME_MONOTONIC_NS_METHODDEF
2003
    TIME_PROCESS_TIME_METHODDEF
2004
    TIME_PROCESS_TIME_NS_METHODDEF
2005
#ifdef HAVE_THREAD_TIME
2006
    TIME_THREAD_TIME_METHODDEF
2007
    TIME_THREAD_TIME_NS_METHODDEF
2008
#endif
2009
    TIME_PERF_COUNTER_METHODDEF
2010
    TIME_PERF_COUNTER_NS_METHODDEF
2011
    TIME_GET_CLOCK_INFO_METHODDEF
2012
    {NULL,              NULL}           /* sentinel */
2013
};
2014
2015
2016
PyDoc_STRVAR(module_doc,
2017
"This module provides various functions to manipulate time values.\n\
2018
\n\
2019
There are two standard representations of time.  One is the number\n\
2020
of seconds since the Epoch, in UTC (a.k.a. GMT).  It may be an integer\n\
2021
or a floating-point number (to represent fractions of seconds).\n\
2022
The epoch is the point where the time starts, the return value of time.gmtime(0).\n\
2023
It is January 1, 1970, 00:00:00 (UTC) on all platforms.\n\
2024
\n\
2025
The other representation is a tuple of 9 integers giving local time.\n\
2026
The tuple items are:\n\
2027
  year (including century, e.g. 1998)\n\
2028
  month (1-12)\n\
2029
  day (1-31)\n\
2030
  hours (0-23)\n\
2031
  minutes (0-59)\n\
2032
  seconds (0-59)\n\
2033
  weekday (0-6, Monday is 0)\n\
2034
  Julian day (day in the year, 1-366)\n\
2035
  DST (Daylight Savings Time) flag (-1, 0 or 1)\n\
2036
If the DST flag is 0, the time is given in the regular time zone;\n\
2037
if it is 1, the time is given in the DST time zone;\n\
2038
if it is -1, mktime() should guess based on the date and time.\n");
2039
2040
2041
static int
2042
time_exec(PyObject *module)
2043
21
{
2044
21
    time_module_state *state = get_time_state(module);
2045
#if defined(__APPLE__) && defined(HAVE_CLOCK_GETTIME)
2046
    if (HAVE_CLOCK_GETTIME_RUNTIME) {
2047
        /* pass: ^^^ cannot use '!' here */
2048
    } else {
2049
        PyObject* dct = PyModule_GetDict(module);
2050
        if (dct == NULL) {
2051
            return -1;
2052
        }
2053
2054
        if (PyDict_PopString(dct, "clock_gettime", NULL) < 0) {
2055
            return -1;
2056
        }
2057
        if (PyDict_PopString(dct, "clock_gettime_ns", NULL) < 0) {
2058
            return -1;
2059
        }
2060
        if (PyDict_PopString(dct, "clock_settime", NULL) < 0) {
2061
            return -1;
2062
        }
2063
        if (PyDict_PopString(dct, "clock_settime_ns", NULL) < 0) {
2064
            return -1;
2065
        }
2066
        if (PyDict_PopString(dct, "clock_getres", NULL) < 0) {
2067
            return -1;
2068
        }
2069
    }
2070
#endif
2071
#if defined(__APPLE__) && defined(HAVE_THREAD_TIME)
2072
    if (HAVE_CLOCK_GETTIME_RUNTIME) {
2073
        /* pass: ^^^ cannot use '!' here */
2074
    } else {
2075
        PyObject* dct = PyModule_GetDict(module);
2076
2077
        if (PyDict_PopString(dct, "thread_time", NULL) < 0) {
2078
            return -1;
2079
        }
2080
        if (PyDict_PopString(dct, "thread_time_ns", NULL) < 0) {
2081
            return -1;
2082
        }
2083
    }
2084
#endif
2085
    /* Set, or reset, module variables like time.timezone */
2086
21
    if (init_timezone(module) < 0) {
2087
0
        return -1;
2088
0
    }
2089
2090
21
#if defined(HAVE_CLOCK_GETTIME) || defined(HAVE_CLOCK_SETTIME) || defined(HAVE_CLOCK_GETRES)
2091
21
    if (HAVE_CLOCK_GETTIME_RUNTIME) {
2092
2093
21
#ifdef CLOCK_REALTIME
2094
21
        if (PyModule_AddIntMacro(module, CLOCK_REALTIME) < 0) {
2095
0
            return -1;
2096
0
        }
2097
21
#endif
2098
21
#ifdef CLOCK_MONOTONIC
2099
21
        if (PyModule_AddIntMacro(module, CLOCK_MONOTONIC) < 0) {
2100
0
            return -1;
2101
0
        }
2102
21
#endif
2103
21
#ifdef CLOCK_MONOTONIC_RAW
2104
21
        if (PyModule_AddIntMacro(module, CLOCK_MONOTONIC_RAW) < 0) {
2105
0
            return -1;
2106
0
        }
2107
21
#endif
2108
#ifdef CLOCK_HIGHRES
2109
        if (PyModule_AddIntMacro(module, CLOCK_HIGHRES) < 0) {
2110
            return -1;
2111
        }
2112
#endif
2113
21
#ifdef CLOCK_PROCESS_CPUTIME_ID
2114
21
        if (PyModule_AddIntMacro(module, CLOCK_PROCESS_CPUTIME_ID) < 0) {
2115
0
            return -1;
2116
0
        }
2117
21
#endif
2118
21
#ifdef CLOCK_THREAD_CPUTIME_ID
2119
21
        if (PyModule_AddIntMacro(module, CLOCK_THREAD_CPUTIME_ID) < 0) {
2120
0
            return -1;
2121
0
        }
2122
21
#endif
2123
#ifdef CLOCK_PROF
2124
        if (PyModule_AddIntMacro(module, CLOCK_PROF) < 0) {
2125
            return -1;
2126
        }
2127
#endif
2128
21
#ifdef CLOCK_BOOTTIME
2129
21
        if (PyModule_AddIntMacro(module, CLOCK_BOOTTIME) < 0) {
2130
0
            return -1;
2131
0
        }
2132
21
#endif
2133
21
#ifdef CLOCK_TAI
2134
21
        if (PyModule_AddIntMacro(module, CLOCK_TAI) < 0) {
2135
0
            return -1;
2136
0
        }
2137
21
#endif
2138
#ifdef CLOCK_UPTIME
2139
        if (PyModule_AddIntMacro(module, CLOCK_UPTIME) < 0) {
2140
            return -1;
2141
        }
2142
#endif
2143
#ifdef CLOCK_UPTIME_RAW
2144
        if (PyModule_AddIntMacro(module, CLOCK_UPTIME_RAW) < 0) {
2145
            return -1;
2146
        }
2147
#endif
2148
#ifdef CLOCK_MONOTONIC_RAW_APPROX
2149
        if (PyModule_AddIntMacro(module, CLOCK_MONOTONIC_RAW_APPROX) < 0) {
2150
            return -1;
2151
        }
2152
#endif
2153
#ifdef CLOCK_UPTIME_RAW_APPROX
2154
        if (PyModule_AddIntMacro(module, CLOCK_UPTIME_RAW_APPROX) < 0) {
2155
            return -1;
2156
        }
2157
#endif
2158
21
    }
2159
2160
21
#endif  /* defined(HAVE_CLOCK_GETTIME) || defined(HAVE_CLOCK_SETTIME) || defined(HAVE_CLOCK_GETRES) */
2161
2162
21
    if (PyModule_AddIntConstant(module, "_STRUCT_TM_ITEMS", 11)) {
2163
0
        return -1;
2164
0
    }
2165
2166
    // struct_time type
2167
21
    state->struct_time_type = PyStructSequence_NewType(&struct_time_type_desc);
2168
21
    if (state->struct_time_type == NULL) {
2169
0
        return -1;
2170
0
    }
2171
21
    if (PyModule_AddType(module, state->struct_time_type)) {
2172
0
        return -1;
2173
0
    }
2174
2175
#if defined(__linux__) && !defined(__GLIBC__)
2176
    struct tm tm;
2177
    const time_t zero = 0;
2178
    if (gmtime_r(&zero, &tm) != NULL)
2179
        utc_string = tm.tm_zone;
2180
#endif
2181
2182
#if defined(MS_WINDOWS)
2183
    if (timer_flags == (DWORD)-1) {
2184
        DWORD test_flags = CREATE_WAITABLE_TIMER_HIGH_RESOLUTION;
2185
        HANDLE timer = CreateWaitableTimerExW(NULL, NULL, test_flags,
2186
                                              TIMER_ALL_ACCESS);
2187
        if (timer == NULL) {
2188
            // CREATE_WAITABLE_TIMER_HIGH_RESOLUTION is not supported.
2189
            timer_flags = 0;
2190
        }
2191
        else {
2192
            // CREATE_WAITABLE_TIMER_HIGH_RESOLUTION is supported.
2193
            timer_flags = CREATE_WAITABLE_TIMER_HIGH_RESOLUTION;
2194
            CloseHandle(timer);
2195
        }
2196
    }
2197
#endif
2198
2199
// gh-115714: Don't use times() on WASI.
2200
21
#if defined(HAVE_TIMES) && !defined(__wasi__)
2201
21
    long ticks_per_second;
2202
21
    if (_Py_GetTicksPerSecond(&ticks_per_second) < 0) {
2203
0
        PyErr_SetString(PyExc_RuntimeError,
2204
0
                        "cannot read ticks_per_second");
2205
0
        return -1;
2206
0
    }
2207
21
    if (_PyTimeFraction_Set(&state->times_base, SEC_TO_NS,
2208
21
                            ticks_per_second) < 0) {
2209
0
        PyErr_Format(PyExc_OverflowError, "ticks_per_second is too large");
2210
0
        return -1;
2211
0
    }
2212
21
#endif
2213
2214
21
#ifdef HAVE_CLOCK
2215
21
    if (_PyTimeFraction_Set(&state->clock_base, SEC_TO_NS,
2216
21
                            CLOCKS_PER_SEC) < 0) {
2217
0
        PyErr_Format(PyExc_OverflowError, "CLOCKS_PER_SEC is too large");
2218
0
        return -1;
2219
0
    }
2220
21
#endif
2221
2222
21
    return 0;
2223
21
}
2224
2225
2226
static int
2227
time_module_traverse(PyObject *module, visitproc visit, void *arg)
2228
392
{
2229
392
    time_module_state *state = get_time_state(module);
2230
392
    Py_VISIT(state->struct_time_type);
2231
392
    return 0;
2232
392
}
2233
2234
2235
static int
2236
time_module_clear(PyObject *module)
2237
0
{
2238
0
    time_module_state *state = get_time_state(module);
2239
0
    Py_CLEAR(state->struct_time_type);
2240
0
    return 0;
2241
0
}
2242
2243
2244
static void
2245
time_module_free(void *module)
2246
0
{
2247
0
    time_module_clear((PyObject *)module);
2248
0
}
2249
2250
2251
static struct PyModuleDef_Slot time_slots[] = {
2252
    _Py_ABI_SLOT,
2253
    {Py_mod_exec, time_exec},
2254
    {Py_mod_multiple_interpreters, Py_MOD_PER_INTERPRETER_GIL_SUPPORTED},
2255
    {Py_mod_gil, Py_MOD_GIL_NOT_USED},
2256
    {0, NULL}
2257
};
2258
2259
static struct PyModuleDef timemodule = {
2260
    PyModuleDef_HEAD_INIT,
2261
    .m_name = "time",
2262
    .m_doc = module_doc,
2263
    .m_size = sizeof(time_module_state),
2264
    .m_methods = time_methods,
2265
    .m_slots = time_slots,
2266
    .m_traverse = time_module_traverse,
2267
    .m_clear = time_module_clear,
2268
    .m_free = time_module_free,
2269
};
2270
2271
PyMODINIT_FUNC
2272
PyInit_time(void)
2273
21
{
2274
21
    return PyModuleDef_Init(&timemodule);
2275
21
}
2276
2277
2278
// time.sleep() implementation.
2279
// On error, raise an exception and return -1.
2280
// On success, return 0.
2281
static int
2282
pysleep(PyTime_t timeout)
2283
0
{
2284
0
    assert(timeout >= 0);
2285
2286
0
#ifndef MS_WINDOWS
2287
0
#ifdef HAVE_CLOCK_NANOSLEEP
2288
0
    struct timespec timeout_abs;
2289
#elif defined(HAVE_NANOSLEEP)
2290
    struct timespec timeout_ts;
2291
#else
2292
    struct timeval timeout_tv;
2293
#endif
2294
0
    PyTime_t deadline, monotonic;
2295
0
    int err = 0;
2296
2297
0
    if (PyTime_Monotonic(&monotonic) < 0) {
2298
0
        return -1;
2299
0
    }
2300
0
    deadline = monotonic + timeout;
2301
0
#ifdef HAVE_CLOCK_NANOSLEEP
2302
0
    if (_PyTime_AsTimespec(deadline, &timeout_abs) < 0) {
2303
0
        return -1;
2304
0
    }
2305
0
#endif
2306
2307
0
    do {
2308
0
#ifdef HAVE_CLOCK_NANOSLEEP
2309
        // use timeout_abs
2310
#elif defined(HAVE_NANOSLEEP)
2311
        if (_PyTime_AsTimespec(timeout, &timeout_ts) < 0) {
2312
            return -1;
2313
        }
2314
#else
2315
        if (_PyTime_AsTimeval(timeout, &timeout_tv, _PyTime_ROUND_CEILING) < 0) {
2316
            return -1;
2317
        }
2318
#endif
2319
2320
0
        int ret;
2321
0
        Py_BEGIN_ALLOW_THREADS
2322
0
#ifdef HAVE_CLOCK_NANOSLEEP
2323
0
        ret = clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &timeout_abs, NULL);
2324
0
        err = ret;
2325
#elif defined(HAVE_NANOSLEEP)
2326
        ret = nanosleep(&timeout_ts, NULL);
2327
        err = errno;
2328
#else
2329
        ret = select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &timeout_tv);
2330
        err = errno;
2331
#endif
2332
0
        Py_END_ALLOW_THREADS
2333
2334
0
        if (ret == 0) {
2335
0
            break;
2336
0
        }
2337
2338
0
        if (err != EINTR) {
2339
0
            errno = err;
2340
0
            PyErr_SetFromErrno(PyExc_OSError);
2341
0
            return -1;
2342
0
        }
2343
2344
        /* sleep was interrupted by SIGINT */
2345
0
        if (PyErr_CheckSignals()) {
2346
0
            return -1;
2347
0
        }
2348
2349
#ifndef HAVE_CLOCK_NANOSLEEP
2350
        if (PyTime_Monotonic(&monotonic) < 0) {
2351
            return -1;
2352
        }
2353
        timeout = deadline - monotonic;
2354
        if (timeout < 0) {
2355
            break;
2356
        }
2357
        /* retry with the recomputed delay */
2358
#endif
2359
0
    } while (1);
2360
2361
0
    return 0;
2362
#else  // MS_WINDOWS
2363
    PyTime_t timeout_100ns = _PyTime_As100Nanoseconds(timeout,
2364
                                                       _PyTime_ROUND_CEILING);
2365
2366
    // Maintain Windows Sleep() semantics for time.sleep(0)
2367
    if (timeout_100ns == 0) {
2368
        Py_BEGIN_ALLOW_THREADS
2369
        // A value of zero causes the thread to relinquish the remainder of its
2370
        // time slice to any other thread that is ready to run. If there are no
2371
        // other threads ready to run, the function returns immediately, and
2372
        // the thread continues execution.
2373
        Sleep(0);
2374
        Py_END_ALLOW_THREADS
2375
        return 0;
2376
    }
2377
2378
    LARGE_INTEGER relative_timeout;
2379
    // No need to check for integer overflow, both types are signed
2380
    assert(sizeof(relative_timeout) == sizeof(timeout_100ns));
2381
    // SetWaitableTimer(): a negative due time indicates relative time
2382
    relative_timeout.QuadPart = -timeout_100ns;
2383
2384
    HANDLE timer = CreateWaitableTimerExW(NULL, NULL, timer_flags,
2385
                                          TIMER_ALL_ACCESS);
2386
    if (timer == NULL) {
2387
        PyErr_SetFromWindowsErr(0);
2388
        return -1;
2389
    }
2390
2391
    if (!SetWaitableTimerEx(timer, &relative_timeout,
2392
                            0, // no period; the timer is signaled once
2393
                            NULL, NULL, // no completion routine
2394
                            NULL,  // no wake context; do not resume from suspend
2395
                            0)) // no tolerable delay for timer coalescing
2396
    {
2397
        PyErr_SetFromWindowsErr(0);
2398
        goto error;
2399
    }
2400
2401
    // Only the main thread can be interrupted by SIGINT.
2402
    // Signal handlers are only executed in the main thread.
2403
    if (_PyOS_IsMainThread()) {
2404
        HANDLE sigint_event = _PyOS_SigintEvent();
2405
2406
        while (1) {
2407
            // Check for pending SIGINT signal before resetting the event
2408
            if (PyErr_CheckSignals()) {
2409
                goto error;
2410
            }
2411
            ResetEvent(sigint_event);
2412
2413
            HANDLE events[] = {timer, sigint_event};
2414
            DWORD rc;
2415
2416
            Py_BEGIN_ALLOW_THREADS
2417
            rc = WaitForMultipleObjects(Py_ARRAY_LENGTH(events), events,
2418
                                        // bWaitAll
2419
                                        FALSE,
2420
                                        // No wait timeout
2421
                                        INFINITE);
2422
            Py_END_ALLOW_THREADS
2423
2424
            if (rc == WAIT_FAILED) {
2425
                PyErr_SetFromWindowsErr(0);
2426
                goto error;
2427
            }
2428
2429
            if (rc == WAIT_OBJECT_0) {
2430
                // Timer signaled: we are done
2431
                break;
2432
            }
2433
2434
            assert(rc == (WAIT_OBJECT_0 + 1));
2435
            // The sleep was interrupted by SIGINT: restart sleeping
2436
        }
2437
    }
2438
    else {
2439
        DWORD rc;
2440
2441
        Py_BEGIN_ALLOW_THREADS
2442
        rc = WaitForSingleObject(timer, INFINITE);
2443
        Py_END_ALLOW_THREADS
2444
2445
        if (rc == WAIT_FAILED) {
2446
            PyErr_SetFromWindowsErr(0);
2447
            goto error;
2448
        }
2449
2450
        assert(rc == WAIT_OBJECT_0);
2451
        // Timer signaled: we are done
2452
    }
2453
2454
    CloseHandle(timer);
2455
    return 0;
2456
2457
error:
2458
    CloseHandle(timer);
2459
    return -1;
2460
#endif
2461
0
}