Coverage Report

Created: 2026-08-28 06:28

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