Coverage Report

Created: 2026-10-17 06:15

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