Coverage Report

Created: 2026-10-31 06:21

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.68k
{
94
1.68k
    void *state = _PyModule_GetState(module);
95
1.68k
    assert(state != NULL);
96
1.68k
    return (time_module_state *)state;
97
1.68k
}
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 && 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 && defined(__STDC_SECURE_LIB__)
864
        /* The secure CRT reports invalid format strings with EINVAL. */
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
    _PyTime_StrptimeFields fields;
1011
0
    if (PyTuple_GET_SIZE(args) == 2 &&
1012
0
        _PyTime_Strptime(PyTuple_GET_ITEM(args, 0),
1013
0
                         PyTuple_GET_ITEM(args, 1), &fields)) {
1014
0
        time_module_state *state = get_time_state(self);
1015
0
        PyObject *result = PyStructSequence_New(state->struct_time_type);
1016
0
        if (result == NULL) {
1017
0
            return NULL;
1018
0
        }
1019
0
        const int values[] = {
1020
0
            fields.year, fields.month, fields.day,
1021
0
            fields.hour, fields.minute, fields.second,
1022
0
            _PyTime_Weekday(fields.year, fields.yday), fields.yday, -1
1023
0
        };
1024
0
        for (size_t i = 0; i < Py_ARRAY_LENGTH(values); i++) {
1025
0
            PyObject *value = PyLong_FromLong(values[i]);
1026
0
            if (value == NULL) {
1027
0
                Py_DECREF(result);
1028
0
                return NULL;
1029
0
            }
1030
0
            PyStructSequence_SET_ITEM(result, i, value);
1031
0
        }
1032
        /* Numeric offsets don't supply a timezone name or DST information. */
1033
0
        PyStructSequence_SET_ITEM(result, 9, Py_NewRef(Py_None));
1034
0
        PyObject *offset = fields.gmtoff == INT_MIN
1035
0
                          ? Py_NewRef(Py_None)
1036
0
                          : PyLong_FromLong(fields.gmtoff);
1037
0
        if (offset == NULL) {
1038
0
            Py_DECREF(result);
1039
0
            return NULL;
1040
0
        }
1041
0
        PyStructSequence_SET_ITEM(result, 10, offset);
1042
0
        return result;
1043
0
    }
1044
0
    PyObject *func, *result;
1045
1046
0
    func = PyImport_ImportModuleAttrString("_strptime", "_strptime_time");
1047
0
    if (!func) {
1048
0
        return NULL;
1049
0
    }
1050
1051
0
    result = PyObject_Call(func, args, NULL);
1052
0
    Py_DECREF(func);
1053
0
    return result;
1054
0
}
1055
1056
1057
PyDoc_STRVAR(strptime_doc,
1058
"strptime(string[, format]) -> struct_time\n\
1059
\n\
1060
Parse a string to a time tuple according to a format specification.\n\
1061
See the library reference manual for formatting codes (same as\n\
1062
strftime()).\n\
1063
\n" STRFTIME_FORMAT_CODES);
1064
1065
static PyObject *
1066
_asctime(struct tm *timeptr)
1067
0
{
1068
    /* Inspired by Open Group reference implementation available at
1069
     * http://pubs.opengroup.org/onlinepubs/009695399/functions/asctime.html */
1070
0
    static const char wday_name[7][4] = {
1071
0
        "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
1072
0
    };
1073
0
    static const char mon_name[12][4] = {
1074
0
        "Jan", "Feb", "Mar", "Apr", "May", "Jun",
1075
0
        "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
1076
0
    };
1077
0
    return PyUnicode_FromFormat(
1078
0
        "%s %s%3d %.2d:%.2d:%.2d %d",
1079
0
        wday_name[timeptr->tm_wday],
1080
0
        mon_name[timeptr->tm_mon],
1081
0
        timeptr->tm_mday, timeptr->tm_hour,
1082
0
        timeptr->tm_min, timeptr->tm_sec,
1083
0
        1900 + timeptr->tm_year);
1084
0
}
1085
1086
/*[clinic input]
1087
time.asctime
1088
1089
    time_tuple as tup: object = NULL
1090
    /
1091
1092
Convert a time tuple to a string, e.g. 'Sat Jun 06 16:26:11 1998'.
1093
1094
When the time tuple is not present, current time as returned by
1095
localtime() is used.
1096
[clinic start generated code]*/
1097
1098
static PyObject *
1099
time_asctime_impl(PyObject *module, PyObject *tup)
1100
/*[clinic end generated code: output=a1bc45f84a00fb55 input=083c132f3cb23f1e]*/
1101
0
{
1102
0
    struct tm buf;
1103
1104
0
    time_module_state *state = get_time_state(module);
1105
0
    if (tup == NULL) {
1106
0
        time_t tt = time(NULL);
1107
0
        if (_PyTime_localtime(tt, &buf) != 0)
1108
0
            return NULL;
1109
0
    }
1110
0
    else if (!gettmarg(state, tup, &buf,
1111
0
                       "iiiiiiiii;asctime(): illegal time tuple argument") ||
1112
0
             !checktm(&buf))
1113
0
    {
1114
0
        return NULL;
1115
0
    }
1116
0
    return _asctime(&buf);
1117
0
}
1118
1119
/*[clinic input]
1120
time.ctime
1121
1122
    seconds as ot: object = None
1123
    /
1124
1125
Convert a time in seconds since the Epoch to a string in local time.
1126
1127
This is equivalent to asctime(localtime(seconds)).  When 'seconds' is
1128
not passed in, convert the current time instead.
1129
[clinic start generated code]*/
1130
1131
static PyObject *
1132
time_ctime_impl(PyObject *module, PyObject *ot)
1133
/*[clinic end generated code: output=c3a028f5c6931cbc input=ee744f25ce87d1ae]*/
1134
0
{
1135
0
    time_t tt;
1136
0
    struct tm buf;
1137
0
    if (!parse_time_t_arg(ot, &tt))
1138
0
        return NULL;
1139
0
    if (_PyTime_localtime(tt, &buf) != 0)
1140
0
        return NULL;
1141
0
    return _asctime(&buf);
1142
0
}
1143
1144
#ifdef HAVE_MKTIME
1145
/*[clinic input]
1146
time.mktime
1147
1148
    time_tuple as tm_tuple: object
1149
    /
1150
1151
Convert a time tuple in local time to seconds since the Epoch.
1152
1153
Note that mktime(gmtime(0)) will not generally return zero for most
1154
time zones; instead the returned value will either be equal to that of
1155
the timezone or altzone attributes on the time module.
1156
[clinic start generated code]*/
1157
1158
static PyObject *
1159
time_mktime(PyObject *module, PyObject *tm_tuple)
1160
/*[clinic end generated code: output=1b2a224cd309deb7 input=70b93e1c2e57e14e]*/
1161
0
{
1162
0
    struct tm tm;
1163
0
    time_t tt;
1164
1165
0
    time_module_state *state = get_time_state(module);
1166
0
    if (!gettmarg(state, tm_tuple, &tm,
1167
0
                  "iiiiiiiii;mktime(): illegal time tuple argument"))
1168
0
    {
1169
0
        return NULL;
1170
0
    }
1171
1172
#if defined(_AIX) || (defined(__VXWORKS__) && !defined(_WRS_CONFIG_LP64))
1173
    /* bpo-19748: AIX mktime() valid range is 00:00:00 UTC, January 1, 1970
1174
       to 03:14:07 UTC, January 19, 2038. Thanks to the workaround below,
1175
       it is possible to support years in range [1902; 2037] */
1176
    if (tm.tm_year < 2 || tm.tm_year > 137) {
1177
        /* bpo-19748: On AIX, mktime() does not report overflow error
1178
           for timestamp < -2^31 or timestamp > 2**31-1. VxWorks has the
1179
           same issue when working in 32 bit mode. */
1180
        PyErr_SetString(PyExc_OverflowError,
1181
                        "mktime argument out of range");
1182
        return NULL;
1183
    }
1184
#endif
1185
1186
#ifdef _AIX
1187
    /* bpo-34373: AIX mktime() has an integer overflow for years in range
1188
       [1902; 1969]. Workaround the issue by using a year greater or equal than
1189
       1970 (tm_year >= 70): mktime() behaves correctly in that case
1190
       (ex: properly report errors). tm_year and tm_wday are adjusted after
1191
       mktime() call. */
1192
    int orig_tm_year = tm.tm_year;
1193
    int delta_days = 0;
1194
    while (tm.tm_year < 70) {
1195
        /* Use 4 years to account properly leap years */
1196
        tm.tm_year += 4;
1197
        delta_days -= (366 + (365 * 3));
1198
    }
1199
#endif
1200
1201
0
    tm.tm_wday = -1;  /* sentinel; original value ignored */
1202
0
    tt = mktime(&tm);
1203
1204
    /* Return value of -1 does not necessarily mean an error, but tm_wday
1205
     * cannot remain set to -1 if mktime succeeded. */
1206
0
    if (tt == (time_t)(-1)
1207
        /* Return value of -1 does not necessarily mean an error, but
1208
         * tm_wday cannot remain set to -1 if mktime succeeded. */
1209
0
        && tm.tm_wday == -1)
1210
0
    {
1211
0
        PyErr_SetString(PyExc_OverflowError,
1212
0
                        "mktime argument out of range");
1213
0
        return NULL;
1214
0
    }
1215
1216
#ifdef _AIX
1217
    if (delta_days != 0) {
1218
        tm.tm_year = orig_tm_year;
1219
        if (tm.tm_wday != -1) {
1220
            tm.tm_wday = (tm.tm_wday + delta_days) % 7;
1221
        }
1222
        tt += delta_days * (24 * 3600);
1223
    }
1224
#endif
1225
1226
0
    return PyFloat_FromDouble((double)tt);
1227
0
}
1228
1229
#endif /* HAVE_MKTIME */
1230
1231
#ifdef HAVE_WORKING_TZSET
1232
static int init_timezone(PyObject *module);
1233
1234
/*[clinic input]
1235
time.tzset
1236
1237
Initialize, or reinitialize, the local timezone.
1238
1239
The local timezone is set to the value stored in os.environ['TZ'].  The
1240
TZ environment variable should be specified in standard Unix timezone
1241
format as documented in the tzset man page (eg. 'US/Eastern',
1242
'Europe/Amsterdam').  Unknown timezones will silently fall back to UTC.
1243
If the TZ environment variable is not set, the local timezone is set to
1244
the systems best guess of wallclock time.  Changing the TZ environment
1245
variable without calling tzset *may* change the local timezone used by
1246
methods such as localtime, but this behaviour should not be relied on.
1247
[clinic start generated code]*/
1248
1249
static PyObject *
1250
time_tzset_impl(PyObject *module)
1251
/*[clinic end generated code: output=d1564ac4d48d320b input=a4d11aab49badf88]*/
1252
0
{
1253
0
    PyObject* m;
1254
1255
0
    m = PyImport_ImportModule("time");
1256
0
    if (m == NULL) {
1257
0
        return NULL;
1258
0
    }
1259
1260
0
#if !defined(MS_WINDOWS) || defined(MS_WINDOWS_DESKTOP) || defined(MS_WINDOWS_SYSTEM)
1261
0
    tzset();
1262
0
#endif
1263
1264
    /* Reset timezone, altzone, daylight and tzname */
1265
0
    if (init_timezone(m) < 0) {
1266
0
        Py_DECREF(m);
1267
0
        return NULL;
1268
0
    }
1269
0
    Py_DECREF(m);
1270
0
    if (PyErr_Occurred())
1271
0
        return NULL;
1272
1273
0
    Py_RETURN_NONE;
1274
0
}
1275
1276
#endif /* HAVE_WORKING_TZSET */
1277
1278
1279
/*[clinic input]
1280
time.monotonic -> double
1281
1282
Monotonic clock, cannot go backward.
1283
[clinic start generated code]*/
1284
1285
static double
1286
time_monotonic_impl(PyObject *module)
1287
/*[clinic end generated code: output=ab51899a17e16542 input=059cb42b2bad6df0]*/
1288
0
{
1289
0
    PyTime_t t;
1290
0
    if (PyTime_Monotonic(&t) < 0) {
1291
0
        return -1.0;
1292
0
    }
1293
0
    return PyTime_AsSecondsDouble(t);
1294
0
}
1295
1296
/*[clinic input]
1297
time.monotonic_ns
1298
1299
Monotonic clock, cannot go backward, as nanoseconds.
1300
[clinic start generated code]*/
1301
1302
static PyObject *
1303
time_monotonic_ns_impl(PyObject *module)
1304
/*[clinic end generated code: output=57a9261f91740349 input=14032d6b1601a300]*/
1305
0
{
1306
0
    PyTime_t t;
1307
0
    if (PyTime_Monotonic(&t) < 0) {
1308
0
        return NULL;
1309
0
    }
1310
0
    return PyLong_FromInt64(t);
1311
0
}
1312
1313
/*[clinic input]
1314
time.perf_counter -> double
1315
1316
Performance counter for benchmarking.
1317
[clinic start generated code]*/
1318
1319
static double
1320
time_perf_counter_impl(PyObject *module)
1321
/*[clinic end generated code: output=6eee280ca7b73cb1 input=f786239c5015893b]*/
1322
25.6k
{
1323
25.6k
    PyTime_t t;
1324
25.6k
    if (PyTime_PerfCounter(&t) < 0) {
1325
0
        return -1.0;
1326
0
    }
1327
25.6k
    return PyTime_AsSecondsDouble(t);
1328
25.6k
}
1329
1330
/*[clinic input]
1331
time.perf_counter_ns
1332
1333
Performance counter for benchmarking as nanoseconds.
1334
[clinic start generated code]*/
1335
1336
static PyObject *
1337
time_perf_counter_ns_impl(PyObject *module)
1338
/*[clinic end generated code: output=e11a728338108d42 input=178bf260d7d48a02]*/
1339
0
{
1340
0
    PyTime_t t;
1341
0
    if (PyTime_PerfCounter(&t) < 0) {
1342
0
        return NULL;
1343
0
    }
1344
0
    return PyLong_FromInt64(t);
1345
0
}
1346
1347
// gh-115714: Don't use times() on WASI.
1348
#if defined(HAVE_TIMES) && !defined(__wasi__)
1349
static int
1350
process_time_times(time_module_state *state, PyTime_t *tp,
1351
                   _Py_clock_info_t *info)
1352
0
{
1353
0
    _PyTimeFraction *base = &state->times_base;
1354
1355
0
    struct tms process;
1356
0
    if (times(&process) == (clock_t)-1) {
1357
0
        return 0;
1358
0
    }
1359
1360
0
    if (info) {
1361
0
        info->implementation = "times()";
1362
0
        info->resolution = _PyTimeFraction_Resolution(base);
1363
0
        info->monotonic = 1;
1364
0
        info->adjustable = 0;
1365
0
    }
1366
1367
0
    PyTime_t ns;
1368
0
    ns = _PyTimeFraction_Mul(process.tms_utime, base);
1369
0
    ns += _PyTimeFraction_Mul(process.tms_stime, base);
1370
0
    *tp = ns;
1371
0
    return 1;
1372
0
}
1373
#endif
1374
1375
1376
static int
1377
py_process_time(time_module_state *state, PyTime_t *tp,
1378
                _Py_clock_info_t *info)
1379
0
{
1380
#if defined(MS_WINDOWS)
1381
    HANDLE process;
1382
    FILETIME creation_time, exit_time, kernel_time, user_time;
1383
    ULARGE_INTEGER large;
1384
    PyTime_t ktime, utime;
1385
    BOOL ok;
1386
1387
    process = GetCurrentProcess();
1388
    ok = GetProcessTimes(process, &creation_time, &exit_time,
1389
                         &kernel_time, &user_time);
1390
    if (!ok) {
1391
        PyErr_SetFromWindowsErr(0);
1392
        return -1;
1393
    }
1394
1395
    if (info) {
1396
        info->implementation = "GetProcessTimes()";
1397
        info->resolution = 1e-7;
1398
        info->monotonic = 1;
1399
        info->adjustable = 0;
1400
    }
1401
1402
    large.u.LowPart = kernel_time.dwLowDateTime;
1403
    large.u.HighPart = kernel_time.dwHighDateTime;
1404
    ktime = large.QuadPart;
1405
1406
    large.u.LowPart = user_time.dwLowDateTime;
1407
    large.u.HighPart = user_time.dwHighDateTime;
1408
    utime = large.QuadPart;
1409
1410
    /* ktime and utime have a resolution of 100 nanoseconds */
1411
    *tp = (ktime + utime) * 100;
1412
    return 0;
1413
#else
1414
1415
    /* clock_gettime */
1416
// gh-115714: Don't use CLOCK_PROCESS_CPUTIME_ID on WASI.
1417
/* CLOCK_PROF is defined on NetBSD, but not supported.
1418
 * CLOCK_PROCESS_CPUTIME_ID is broken on NetBSD for the same reason as
1419
 * CLOCK_THREAD_CPUTIME_ID (see comment below).
1420
 */
1421
0
#if defined(HAVE_CLOCK_GETTIME) \
1422
0
    && (defined(CLOCK_PROCESS_CPUTIME_ID) || defined(CLOCK_PROF)) \
1423
0
    && !defined(__wasi__) \
1424
0
    && !defined(__NetBSD__)
1425
0
    struct timespec ts;
1426
1427
0
    if (HAVE_CLOCK_GETTIME_RUNTIME) {
1428
1429
#ifdef CLOCK_PROF
1430
        const clockid_t clk_id = CLOCK_PROF;
1431
        const char *function = "clock_gettime(CLOCK_PROF)";
1432
#else
1433
0
        const clockid_t clk_id = CLOCK_PROCESS_CPUTIME_ID;
1434
0
        const char *function = "clock_gettime(CLOCK_PROCESS_CPUTIME_ID)";
1435
0
#endif
1436
1437
0
        if (clock_gettime(clk_id, &ts) == 0) {
1438
0
            if (info) {
1439
0
                struct timespec res;
1440
0
                info->implementation = function;
1441
0
                info->monotonic = 1;
1442
0
                info->adjustable = 0;
1443
0
                if (clock_getres(clk_id, &res)) {
1444
0
                    PyErr_SetFromErrno(PyExc_OSError);
1445
0
                    return -1;
1446
0
                }
1447
0
                info->resolution = res.tv_sec + res.tv_nsec * 1e-9;
1448
0
            }
1449
1450
0
            if (_PyTime_FromTimespec(tp, &ts) < 0) {
1451
0
                return -1;
1452
0
            }
1453
0
            return 0;
1454
0
        }
1455
0
    }
1456
0
#endif
1457
1458
    /* getrusage(RUSAGE_SELF) */
1459
0
#if defined(HAVE_SYS_RESOURCE_H) && defined(HAVE_GETRUSAGE)
1460
0
    struct rusage ru;
1461
1462
0
    if (getrusage(RUSAGE_SELF, &ru) == 0) {
1463
0
        PyTime_t utime, stime;
1464
1465
0
        if (info) {
1466
0
            info->implementation = "getrusage(RUSAGE_SELF)";
1467
0
            info->monotonic = 1;
1468
0
            info->adjustable = 0;
1469
0
            info->resolution = 1e-6;
1470
0
        }
1471
1472
0
        if (_PyTime_FromTimeval(&utime, &ru.ru_utime) < 0) {
1473
0
            return -1;
1474
0
        }
1475
0
        if (_PyTime_FromTimeval(&stime, &ru.ru_stime) < 0) {
1476
0
            return -1;
1477
0
        }
1478
1479
0
        PyTime_t total = utime + stime;
1480
0
        *tp = total;
1481
0
        return 0;
1482
0
    }
1483
0
#endif
1484
1485
    /* times() */
1486
// gh-115714: Don't use times() on WASI.
1487
0
#if defined(HAVE_TIMES) && !defined(__wasi__)
1488
0
    int res = process_time_times(state, tp, info);
1489
0
    if (res < 0) {
1490
0
        return -1;
1491
0
    }
1492
0
    if (res == 1) {
1493
0
        return 0;
1494
0
    }
1495
    // times() failed, ignore failure
1496
0
#endif
1497
1498
    /* clock(). Python 3 requires clock() to build (see gh-66814) */
1499
0
    return py_clock(state, tp, info);
1500
0
#endif
1501
0
}
1502
1503
/*[clinic input]
1504
time.process_time -> double
1505
1506
Process time for profiling.
1507
1508
That is the sum of the kernel and user-space CPU time.
1509
[clinic start generated code]*/
1510
1511
static double
1512
time_process_time_impl(PyObject *module)
1513
/*[clinic end generated code: output=13b593cb16d415a8 input=6d539ae686c37c06]*/
1514
0
{
1515
0
    time_module_state *state = get_time_state(module);
1516
0
    PyTime_t t;
1517
0
    if (py_process_time(state, &t, NULL) < 0) {
1518
0
        return -1.0;
1519
0
    }
1520
0
    return PyTime_AsSecondsDouble(t);
1521
0
}
1522
1523
/*[clinic input]
1524
time.process_time_ns
1525
1526
Process time for profiling as nanoseconds.
1527
1528
That is the sum of the kernel and user-space CPU time.
1529
[clinic start generated code]*/
1530
1531
static PyObject *
1532
time_process_time_ns_impl(PyObject *module)
1533
/*[clinic end generated code: output=857f0c20105c4d1a input=6d998fd7a213c0cd]*/
1534
0
{
1535
0
    time_module_state *state = get_time_state(module);
1536
0
    PyTime_t t;
1537
0
    if (py_process_time(state, &t, NULL) < 0) {
1538
0
        return NULL;
1539
0
    }
1540
0
    return PyLong_FromInt64(t);
1541
0
}
1542
1543
#if defined(MS_WINDOWS)
1544
#define HAVE_THREAD_TIME
1545
static int
1546
_PyTime_GetThreadTimeWithInfo(PyTime_t *tp, _Py_clock_info_t *info)
1547
{
1548
    HANDLE thread;
1549
    FILETIME creation_time, exit_time, kernel_time, user_time;
1550
    ULARGE_INTEGER large;
1551
    PyTime_t ktime, utime;
1552
    BOOL ok;
1553
1554
    thread =  GetCurrentThread();
1555
    ok = GetThreadTimes(thread, &creation_time, &exit_time,
1556
                        &kernel_time, &user_time);
1557
    if (!ok) {
1558
        PyErr_SetFromWindowsErr(0);
1559
        return -1;
1560
    }
1561
1562
    if (info) {
1563
        info->implementation = "GetThreadTimes()";
1564
        info->resolution = 1e-7;
1565
        info->monotonic = 1;
1566
        info->adjustable = 0;
1567
    }
1568
1569
    large.u.LowPart = kernel_time.dwLowDateTime;
1570
    large.u.HighPart = kernel_time.dwHighDateTime;
1571
    ktime = large.QuadPart;
1572
1573
    large.u.LowPart = user_time.dwLowDateTime;
1574
    large.u.HighPart = user_time.dwHighDateTime;
1575
    utime = large.QuadPart;
1576
1577
    /* ktime and utime have a resolution of 100 nanoseconds */
1578
    *tp = (ktime + utime) * 100;
1579
    return 0;
1580
}
1581
1582
#elif defined(_AIX)
1583
#define HAVE_THREAD_TIME
1584
static int
1585
_PyTime_GetThreadTimeWithInfo(PyTime_t *tp, _Py_clock_info_t *info)
1586
{
1587
    /* bpo-40192: On AIX, thread_cputime() is preferred: it has nanosecond
1588
       resolution, whereas clock_gettime(CLOCK_THREAD_CPUTIME_ID)
1589
       has a resolution of 10 ms. */
1590
    thread_cputime_t tc;
1591
    if (thread_cputime(-1, &tc) != 0) {
1592
        PyErr_SetFromErrno(PyExc_OSError);
1593
        return -1;
1594
    }
1595
1596
    if (info) {
1597
        info->implementation = "thread_cputime()";
1598
        info->monotonic = 1;
1599
        info->adjustable = 0;
1600
        info->resolution = 1e-9;
1601
    }
1602
    *tp = (tc.stime + tc.utime);
1603
    return 0;
1604
}
1605
1606
#elif defined(__sun) && defined(__SVR4)
1607
#define HAVE_THREAD_TIME
1608
static int
1609
_PyTime_GetThreadTimeWithInfo(PyTime_t *tp, _Py_clock_info_t *info)
1610
{
1611
    /* bpo-35455: On Solaris, CLOCK_THREAD_CPUTIME_ID clock is not always
1612
       available; use gethrvtime() to substitute this functionality. */
1613
    if (info) {
1614
        info->implementation = "gethrvtime()";
1615
        info->resolution = 1e-9;
1616
        info->monotonic = 1;
1617
        info->adjustable = 0;
1618
    }
1619
    *tp = gethrvtime();
1620
    return 0;
1621
}
1622
1623
/* CLOCK_THREAD_CPUTIME_ID is broken on NetBSD: the result of clock_gettime()
1624
 * includes the sleeping time, that defeats the purpose of the clock.
1625
 * Also, clock_getres() does not support it.
1626
 * https://github.com/python/cpython/issues/123978
1627
 * https://gnats.netbsd.org/57512
1628
 */
1629
#elif defined(HAVE_CLOCK_GETTIME) && \
1630
      defined(CLOCK_THREAD_CPUTIME_ID) && \
1631
      !defined(__EMSCRIPTEN__) && !defined(__wasi__) && \
1632
      !defined(__NetBSD__)
1633
#define HAVE_THREAD_TIME
1634
1635
#if defined(__APPLE__) && _Py__has_attribute(availability)
1636
static int
1637
_PyTime_GetThreadTimeWithInfo(PyTime_t *tp, _Py_clock_info_t *info)
1638
     __attribute__((availability(macos, introduced=10.12)))
1639
     __attribute__((availability(ios, introduced=10.0)))
1640
     __attribute__((availability(tvos, introduced=10.0)))
1641
     __attribute__((availability(watchos, introduced=3.0)));
1642
#endif
1643
1644
static int
1645
_PyTime_GetThreadTimeWithInfo(PyTime_t *tp, _Py_clock_info_t *info)
1646
0
{
1647
0
    struct timespec ts;
1648
0
    const clockid_t clk_id = CLOCK_THREAD_CPUTIME_ID;
1649
0
    const char *function = "clock_gettime(CLOCK_THREAD_CPUTIME_ID)";
1650
1651
0
    if (clock_gettime(clk_id, &ts)) {
1652
0
        PyErr_SetFromErrno(PyExc_OSError);
1653
0
        return -1;
1654
0
    }
1655
0
    if (info) {
1656
0
        struct timespec res;
1657
0
        info->implementation = function;
1658
0
        info->monotonic = 1;
1659
0
        info->adjustable = 0;
1660
0
        if (clock_getres(clk_id, &res)) {
1661
0
            PyErr_SetFromErrno(PyExc_OSError);
1662
0
            return -1;
1663
0
        }
1664
0
        info->resolution = res.tv_sec + res.tv_nsec * 1e-9;
1665
0
    }
1666
1667
0
    if (_PyTime_FromTimespec(tp, &ts) < 0) {
1668
0
        return -1;
1669
0
    }
1670
0
    return 0;
1671
0
}
1672
#endif
1673
1674
#ifdef HAVE_THREAD_TIME
1675
#ifdef __APPLE__
1676
/*
1677
 * The clock_* functions will be removed from the module
1678
 * dict entirely when the C API is not available.
1679
 */
1680
#pragma clang diagnostic push
1681
#pragma clang diagnostic ignored "-Wunguarded-availability"
1682
#endif
1683
1684
/*[clinic input]
1685
time.thread_time -> double
1686
1687
Thread time for profiling.
1688
1689
That is the sum of the kernel and user-space CPU time.
1690
[clinic start generated code]*/
1691
1692
static double
1693
time_thread_time_impl(PyObject *module)
1694
/*[clinic end generated code: output=33f6639edb42e8f5 input=cdf4621822b8ed60]*/
1695
0
{
1696
0
    PyTime_t t;
1697
0
    if (_PyTime_GetThreadTimeWithInfo(&t, NULL) < 0) {
1698
0
        return -1.0;
1699
0
    }
1700
0
    return PyTime_AsSecondsDouble(t);
1701
0
}
1702
1703
/*[clinic input]
1704
time.thread_time_ns
1705
1706
Thread time for profiling as nanoseconds.
1707
1708
That is the sum of the kernel and user-space CPU time.
1709
[clinic start generated code]*/
1710
1711
static PyObject *
1712
time_thread_time_ns_impl(PyObject *module)
1713
/*[clinic end generated code: output=2a1ac9cc3e1d4c37 input=a79b2b91f308277d]*/
1714
0
{
1715
0
    PyTime_t t;
1716
0
    if (_PyTime_GetThreadTimeWithInfo(&t, NULL) < 0) {
1717
0
        return NULL;
1718
0
    }
1719
0
    return PyLong_FromInt64(t);
1720
0
}
1721
1722
#ifdef __APPLE__
1723
#pragma clang diagnostic pop
1724
#endif
1725
1726
#endif
1727
1728
1729
/*[clinic input]
1730
time.get_clock_info
1731
1732
    name: str
1733
    /
1734
1735
Get information of the specified clock.
1736
[clinic start generated code]*/
1737
1738
static PyObject *
1739
time_get_clock_info_impl(PyObject *module, const char *name)
1740
/*[clinic end generated code: output=a77a07bdf3554bd6 input=6812ae049f1b1031]*/
1741
0
{
1742
0
    _Py_clock_info_t info;
1743
0
    PyObject *obj = NULL, *dict, *ns;
1744
0
    PyTime_t t;
1745
1746
#ifdef Py_DEBUG
1747
    info.implementation = NULL;
1748
    info.monotonic = -1;
1749
    info.adjustable = -1;
1750
    info.resolution = -1.0;
1751
#else
1752
0
    info.implementation = "";
1753
0
    info.monotonic = 0;
1754
0
    info.adjustable = 0;
1755
0
    info.resolution = 1.0;
1756
0
#endif
1757
1758
0
    if (strcmp(name, "time") == 0) {
1759
0
        if (_PyTime_TimeWithInfo(&t, &info) < 0) {
1760
0
            return NULL;
1761
0
        }
1762
0
    }
1763
0
    else if (strcmp(name, "monotonic") == 0) {
1764
0
        if (_PyTime_MonotonicWithInfo(&t, &info) < 0) {
1765
0
            return NULL;
1766
0
        }
1767
0
    }
1768
0
    else if (strcmp(name, "perf_counter") == 0) {
1769
0
        if (_PyTime_PerfCounterWithInfo(&t, &info) < 0) {
1770
0
            return NULL;
1771
0
        }
1772
0
    }
1773
0
    else if (strcmp(name, "process_time") == 0) {
1774
0
        time_module_state *state = get_time_state(module);
1775
0
        if (py_process_time(state, &t, &info) < 0) {
1776
0
            return NULL;
1777
0
        }
1778
0
    }
1779
0
#ifdef HAVE_THREAD_TIME
1780
0
    else if (strcmp(name, "thread_time") == 0) {
1781
1782
#ifdef __APPLE__
1783
        if (HAVE_CLOCK_GETTIME_RUNTIME) {
1784
#endif
1785
0
            if (_PyTime_GetThreadTimeWithInfo(&t, &info) < 0) {
1786
0
                return NULL;
1787
0
            }
1788
#ifdef __APPLE__
1789
        } else {
1790
            PyErr_SetString(PyExc_ValueError, "unknown clock");
1791
            return NULL;
1792
        }
1793
#endif
1794
0
    }
1795
0
#endif
1796
0
    else {
1797
0
        PyErr_SetString(PyExc_ValueError, "unknown clock");
1798
0
        return NULL;
1799
0
    }
1800
1801
0
    dict = PyDict_New();
1802
0
    if (dict == NULL) {
1803
0
        return NULL;
1804
0
    }
1805
1806
0
    assert(info.implementation != NULL);
1807
0
    obj = PyUnicode_FromString(info.implementation);
1808
0
    if (obj == NULL) {
1809
0
        goto error;
1810
0
    }
1811
0
    if (PyDict_SetItemString(dict, "implementation", obj) == -1) {
1812
0
        goto error;
1813
0
    }
1814
0
    Py_CLEAR(obj);
1815
1816
0
    assert(info.monotonic != -1);
1817
0
    obj = PyBool_FromLong(info.monotonic);
1818
0
    if (obj == NULL) {
1819
0
        goto error;
1820
0
    }
1821
0
    if (PyDict_SetItemString(dict, "monotonic", obj) == -1) {
1822
0
        goto error;
1823
0
    }
1824
0
    Py_CLEAR(obj);
1825
1826
0
    assert(info.adjustable != -1);
1827
0
    obj = PyBool_FromLong(info.adjustable);
1828
0
    if (obj == NULL) {
1829
0
        goto error;
1830
0
    }
1831
0
    if (PyDict_SetItemString(dict, "adjustable", obj) == -1) {
1832
0
        goto error;
1833
0
    }
1834
0
    Py_CLEAR(obj);
1835
1836
0
    assert(info.resolution > 0.0);
1837
0
    assert(info.resolution <= 1.0);
1838
0
    obj = PyFloat_FromDouble(info.resolution);
1839
0
    if (obj == NULL) {
1840
0
        goto error;
1841
0
    }
1842
0
    if (PyDict_SetItemString(dict, "resolution", obj) == -1) {
1843
0
        goto error;
1844
0
    }
1845
0
    Py_CLEAR(obj);
1846
1847
0
    ns = _PyNamespace_New(dict);
1848
0
    Py_DECREF(dict);
1849
0
    return ns;
1850
1851
0
error:
1852
0
    Py_DECREF(dict);
1853
0
    Py_XDECREF(obj);
1854
0
    return NULL;
1855
0
}
1856
1857
#ifndef HAVE_DECL_TZNAME
1858
static void
1859
get_zone(char *zone, int n, struct tm *p)
1860
74
{
1861
74
#ifdef HAVE_STRUCT_TM_TM_ZONE
1862
74
    strncpy(zone, p->tm_zone ? p->tm_zone : "   ", n);
1863
#else
1864
    tzset();
1865
    strftime(zone, n, "%Z", p);
1866
#endif
1867
74
}
1868
1869
static time_t
1870
get_gmtoff(time_t t, struct tm *p)
1871
74
{
1872
74
#ifdef HAVE_STRUCT_TM_TM_ZONE
1873
74
    return p->tm_gmtoff;
1874
#else
1875
    return timegm(p) - t;
1876
#endif
1877
74
}
1878
#endif // !HAVE_DECL_TZNAME
1879
1880
static int
1881
init_timezone(PyObject *m)
1882
37
{
1883
111
#define ADD_INT(NAME, VALUE) do {                       \
1884
111
    if (PyModule_AddIntConstant(m, NAME, VALUE) < 0) {  \
1885
0
        return -1;                                      \
1886
0
    }                                                   \
1887
111
} while (0)
1888
1889
37
    assert(!PyErr_Occurred());
1890
1891
    /* This code moved from PyInit_time wholesale to allow calling it from
1892
    time_tzset. In the future, some parts of it can be moved back
1893
    (for platforms that don't HAVE_WORKING_TZSET, when we know what they
1894
    are), and the extraneous calls to tzset(3) should be removed.
1895
    I haven't done this yet, as I don't want to change this code as
1896
    little as possible when introducing the time.tzset and time.tzsetwall
1897
    methods. This should simply be a method of doing the following once,
1898
    at the top of this function and removing the call to tzset() from
1899
    time_tzset():
1900
1901
        #ifdef HAVE_TZSET
1902
        tzset()
1903
        #endif
1904
1905
    And I'm lazy and hate C so nyer.
1906
     */
1907
#ifdef HAVE_DECL_TZNAME
1908
    PyObject *otz0, *otz1;
1909
#if !defined(MS_WINDOWS) || defined(MS_WINDOWS_DESKTOP) || defined(MS_WINDOWS_SYSTEM)
1910
    tzset();
1911
#endif
1912
    ADD_INT("timezone", _Py_timezone);
1913
#ifdef HAVE_ALTZONE
1914
    ADD_INT("altzone", altzone);
1915
#else
1916
    ADD_INT("altzone", _Py_timezone-3600);
1917
#endif
1918
    ADD_INT("daylight", _Py_daylight);
1919
#ifdef MS_WINDOWS
1920
    TIME_ZONE_INFORMATION tzinfo = {0};
1921
    GetTimeZoneInformation(&tzinfo);
1922
    otz0 = PyUnicode_FromWideChar(tzinfo.StandardName, -1);
1923
    if (otz0 == NULL) {
1924
        return -1;
1925
    }
1926
    otz1 = PyUnicode_FromWideChar(tzinfo.DaylightName, -1);
1927
    if (otz1 == NULL) {
1928
        Py_DECREF(otz0);
1929
        return -1;
1930
    }
1931
#else
1932
    otz0 = PyUnicode_DecodeLocale(_Py_tzname[0], "surrogateescape");
1933
    if (otz0 == NULL) {
1934
        return -1;
1935
    }
1936
    otz1 = PyUnicode_DecodeLocale(_Py_tzname[1], "surrogateescape");
1937
    if (otz1 == NULL) {
1938
        Py_DECREF(otz0);
1939
        return -1;
1940
    }
1941
#endif // MS_WINDOWS
1942
    if (PyModule_Add(m, "tzname", Py_BuildValue("(NN)", otz0, otz1)) < 0) {
1943
        return -1;
1944
    }
1945
#else // !HAVE_DECL_TZNAME
1946
37
    static const time_t YEAR = (365 * 24 + 6) * 3600;
1947
37
    time_t t;
1948
37
    struct tm p;
1949
37
    time_t janzone_t, julyzone_t;
1950
37
    char janname[10], julyname[10];
1951
37
    t = (time((time_t *)0) / YEAR) * YEAR;
1952
37
    _PyTime_localtime(t, &p);
1953
37
    get_zone(janname, 9, &p);
1954
37
    janzone_t = -get_gmtoff(t, &p);
1955
37
    janname[9] = '\0';
1956
37
    t += YEAR/2;
1957
37
    _PyTime_localtime(t, &p);
1958
37
    get_zone(julyname, 9, &p);
1959
37
    julyzone_t = -get_gmtoff(t, &p);
1960
37
    julyname[9] = '\0';
1961
1962
    /* Sanity check, don't check for the validity of timezones.
1963
       In practice, it should be more in range -12 hours .. +14 hours. */
1964
259
#define MAX_TIMEZONE (48 * 3600)
1965
37
    if (janzone_t < -MAX_TIMEZONE || janzone_t > MAX_TIMEZONE
1966
37
        || julyzone_t < -MAX_TIMEZONE || julyzone_t > MAX_TIMEZONE)
1967
0
    {
1968
0
        PyErr_SetString(PyExc_RuntimeError, "invalid GMT offset");
1969
0
        return -1;
1970
0
    }
1971
37
    int janzone = (int)janzone_t;
1972
37
    int julyzone = (int)julyzone_t;
1973
1974
37
    PyObject *tzname_obj;
1975
37
    if (janzone < julyzone) {
1976
        /* DST is reversed in the southern hemisphere */
1977
0
        ADD_INT("timezone", julyzone);
1978
0
        ADD_INT("altzone", janzone);
1979
0
        ADD_INT("daylight", janzone != julyzone);
1980
0
        tzname_obj = Py_BuildValue("(zz)", julyname, janname);
1981
37
    } else {
1982
37
        ADD_INT("timezone", janzone);
1983
37
        ADD_INT("altzone", julyzone);
1984
37
        ADD_INT("daylight", janzone != julyzone);
1985
37
        tzname_obj = Py_BuildValue("(zz)", janname, julyname);
1986
37
    }
1987
37
    if (PyModule_Add(m, "tzname", tzname_obj) < 0) {
1988
0
        return -1;
1989
0
    }
1990
37
#endif // !HAVE_DECL_TZNAME
1991
37
#undef ADD_INT
1992
1993
37
    if (PyErr_Occurred()) {
1994
0
        return -1;
1995
0
    }
1996
37
    return 0;
1997
37
}
1998
1999
2000
// Include Argument Clinic code after defining converters such as
2001
// time_clockid_converter().
2002
#include "clinic/timemodule.c.h"
2003
2004
static PyMethodDef time_methods[] = {
2005
    TIME_TIME_METHODDEF
2006
    TIME_TIME_NS_METHODDEF
2007
#ifdef HAVE_CLOCK_GETTIME
2008
    TIME_CLOCK_GETTIME_METHODDEF
2009
    TIME_CLOCK_GETTIME_NS_METHODDEF
2010
#endif
2011
#ifdef HAVE_CLOCK_SETTIME
2012
    TIME_CLOCK_SETTIME_METHODDEF
2013
    TIME_CLOCK_SETTIME_NS_METHODDEF
2014
#endif
2015
#ifdef HAVE_CLOCK_GETRES
2016
    TIME_CLOCK_GETRES_METHODDEF
2017
#endif
2018
#ifdef HAVE_PTHREAD_GETCPUCLOCKID
2019
    TIME_PTHREAD_GETCPUCLOCKID_METHODDEF
2020
#endif
2021
    TIME_SLEEP_METHODDEF
2022
    TIME_GMTIME_METHODDEF
2023
    TIME_LOCALTIME_METHODDEF
2024
    TIME_ASCTIME_METHODDEF
2025
    TIME_CTIME_METHODDEF
2026
#ifdef HAVE_MKTIME
2027
    TIME_MKTIME_METHODDEF
2028
#endif
2029
#ifdef HAVE_STRFTIME
2030
    {"strftime",        time_strftime, METH_VARARGS, strftime_doc},
2031
#endif
2032
    {"strptime",        time_strptime, METH_VARARGS, strptime_doc},
2033
#ifdef HAVE_WORKING_TZSET
2034
    TIME_TZSET_METHODDEF
2035
#endif
2036
    TIME_MONOTONIC_METHODDEF
2037
    TIME_MONOTONIC_NS_METHODDEF
2038
    TIME_PROCESS_TIME_METHODDEF
2039
    TIME_PROCESS_TIME_NS_METHODDEF
2040
#ifdef HAVE_THREAD_TIME
2041
    TIME_THREAD_TIME_METHODDEF
2042
    TIME_THREAD_TIME_NS_METHODDEF
2043
#endif
2044
    TIME_PERF_COUNTER_METHODDEF
2045
    TIME_PERF_COUNTER_NS_METHODDEF
2046
    TIME_GET_CLOCK_INFO_METHODDEF
2047
    {NULL,              NULL}           /* sentinel */
2048
};
2049
2050
2051
PyDoc_STRVAR(module_doc,
2052
"This module provides various functions to manipulate time values.\n\
2053
\n\
2054
There are two standard representations of time.  One is the number\n\
2055
of seconds since the Epoch, in UTC (a.k.a. GMT).  It may be an integer\n\
2056
or a floating-point number (to represent fractions of seconds).\n\
2057
The epoch is the point where the time starts, the return value of time.gmtime(0).\n\
2058
It is January 1, 1970, 00:00:00 (UTC) on all platforms.\n\
2059
\n\
2060
The other representation is a tuple of 9 integers giving local time.\n\
2061
The tuple items are:\n\
2062
  year (including century, e.g. 1998)\n\
2063
  month (1-12)\n\
2064
  day (1-31)\n\
2065
  hours (0-23)\n\
2066
  minutes (0-59)\n\
2067
  seconds (0-59)\n\
2068
  weekday (0-6, Monday is 0)\n\
2069
  Julian day (day in the year, 1-366)\n\
2070
  DST (Daylight Savings Time) flag (-1, 0 or 1)\n\
2071
If the DST flag is 0, the time is given in the regular time zone;\n\
2072
if it is 1, the time is given in the DST time zone;\n\
2073
if it is -1, mktime() should guess based on the date and time.\n");
2074
2075
2076
static int
2077
time_exec(PyObject *module)
2078
37
{
2079
37
    time_module_state *state = get_time_state(module);
2080
#if defined(__APPLE__) && defined(HAVE_CLOCK_GETTIME)
2081
    if (HAVE_CLOCK_GETTIME_RUNTIME) {
2082
        /* pass: ^^^ cannot use '!' here */
2083
    } else {
2084
        PyObject* dct = PyModule_GetDict(module);
2085
        if (dct == NULL) {
2086
            return -1;
2087
        }
2088
2089
        if (PyDict_PopString(dct, "clock_gettime", NULL) < 0) {
2090
            return -1;
2091
        }
2092
        if (PyDict_PopString(dct, "clock_gettime_ns", NULL) < 0) {
2093
            return -1;
2094
        }
2095
        if (PyDict_PopString(dct, "clock_settime", NULL) < 0) {
2096
            return -1;
2097
        }
2098
        if (PyDict_PopString(dct, "clock_settime_ns", NULL) < 0) {
2099
            return -1;
2100
        }
2101
        if (PyDict_PopString(dct, "clock_getres", NULL) < 0) {
2102
            return -1;
2103
        }
2104
    }
2105
#endif
2106
#if defined(__APPLE__) && defined(HAVE_THREAD_TIME)
2107
    if (HAVE_CLOCK_GETTIME_RUNTIME) {
2108
        /* pass: ^^^ cannot use '!' here */
2109
    } else {
2110
        PyObject* dct = PyModule_GetDict(module);
2111
2112
        if (PyDict_PopString(dct, "thread_time", NULL) < 0) {
2113
            return -1;
2114
        }
2115
        if (PyDict_PopString(dct, "thread_time_ns", NULL) < 0) {
2116
            return -1;
2117
        }
2118
    }
2119
#endif
2120
    /* Set, or reset, module variables like time.timezone */
2121
37
    if (init_timezone(module) < 0) {
2122
0
        return -1;
2123
0
    }
2124
2125
37
#if defined(HAVE_CLOCK_GETTIME) || defined(HAVE_CLOCK_SETTIME) || defined(HAVE_CLOCK_GETRES)
2126
37
    if (HAVE_CLOCK_GETTIME_RUNTIME) {
2127
2128
37
#ifdef CLOCK_REALTIME
2129
37
        if (PyModule_AddIntMacro(module, CLOCK_REALTIME) < 0) {
2130
0
            return -1;
2131
0
        }
2132
37
#endif
2133
37
#ifdef CLOCK_MONOTONIC
2134
37
        if (PyModule_AddIntMacro(module, CLOCK_MONOTONIC) < 0) {
2135
0
            return -1;
2136
0
        }
2137
37
#endif
2138
37
#ifdef CLOCK_MONOTONIC_RAW
2139
37
        if (PyModule_AddIntMacro(module, CLOCK_MONOTONIC_RAW) < 0) {
2140
0
            return -1;
2141
0
        }
2142
37
#endif
2143
#ifdef CLOCK_HIGHRES
2144
        if (PyModule_AddIntMacro(module, CLOCK_HIGHRES) < 0) {
2145
            return -1;
2146
        }
2147
#endif
2148
37
#ifdef CLOCK_PROCESS_CPUTIME_ID
2149
37
        if (PyModule_AddIntMacro(module, CLOCK_PROCESS_CPUTIME_ID) < 0) {
2150
0
            return -1;
2151
0
        }
2152
37
#endif
2153
37
#ifdef CLOCK_THREAD_CPUTIME_ID
2154
37
        if (PyModule_AddIntMacro(module, CLOCK_THREAD_CPUTIME_ID) < 0) {
2155
0
            return -1;
2156
0
        }
2157
37
#endif
2158
#ifdef CLOCK_PROF
2159
        if (PyModule_AddIntMacro(module, CLOCK_PROF) < 0) {
2160
            return -1;
2161
        }
2162
#endif
2163
37
#ifdef CLOCK_BOOTTIME
2164
37
        if (PyModule_AddIntMacro(module, CLOCK_BOOTTIME) < 0) {
2165
0
            return -1;
2166
0
        }
2167
37
#endif
2168
37
#ifdef CLOCK_TAI
2169
37
        if (PyModule_AddIntMacro(module, CLOCK_TAI) < 0) {
2170
0
            return -1;
2171
0
        }
2172
37
#endif
2173
#ifdef CLOCK_UPTIME
2174
        if (PyModule_AddIntMacro(module, CLOCK_UPTIME) < 0) {
2175
            return -1;
2176
        }
2177
#endif
2178
#ifdef CLOCK_UPTIME_RAW
2179
        if (PyModule_AddIntMacro(module, CLOCK_UPTIME_RAW) < 0) {
2180
            return -1;
2181
        }
2182
#endif
2183
#ifdef CLOCK_MONOTONIC_RAW_APPROX
2184
        if (PyModule_AddIntMacro(module, CLOCK_MONOTONIC_RAW_APPROX) < 0) {
2185
            return -1;
2186
        }
2187
#endif
2188
#ifdef CLOCK_UPTIME_RAW_APPROX
2189
        if (PyModule_AddIntMacro(module, CLOCK_UPTIME_RAW_APPROX) < 0) {
2190
            return -1;
2191
        }
2192
#endif
2193
37
    }
2194
2195
37
#endif  /* defined(HAVE_CLOCK_GETTIME) || defined(HAVE_CLOCK_SETTIME) || defined(HAVE_CLOCK_GETRES) */
2196
2197
37
    if (PyModule_AddIntConstant(module, "_STRUCT_TM_ITEMS", 11)) {
2198
0
        return -1;
2199
0
    }
2200
2201
    // struct_time type
2202
37
    state->struct_time_type = _PyStructSequence_NewType(
2203
37
        &struct_time_type_desc, Py_TPFLAGS_IMMUTABLETYPE);
2204
37
    if (state->struct_time_type == NULL) {
2205
0
        return -1;
2206
0
    }
2207
37
    if (PyModule_AddType(module, state->struct_time_type)) {
2208
0
        return -1;
2209
0
    }
2210
2211
#if defined(__linux__) && !defined(__GLIBC__)
2212
    struct tm tm;
2213
    const time_t zero = 0;
2214
    if (gmtime_r(&zero, &tm) != NULL)
2215
        utc_string = tm.tm_zone;
2216
#endif
2217
2218
#if defined(MS_WINDOWS)
2219
    if (timer_flags == (DWORD)-1) {
2220
        DWORD test_flags = CREATE_WAITABLE_TIMER_HIGH_RESOLUTION;
2221
        HANDLE timer = CreateWaitableTimerExW(NULL, NULL, test_flags,
2222
                                              TIMER_ALL_ACCESS);
2223
        if (timer == NULL) {
2224
            // CREATE_WAITABLE_TIMER_HIGH_RESOLUTION is not supported.
2225
            timer_flags = 0;
2226
        }
2227
        else {
2228
            // CREATE_WAITABLE_TIMER_HIGH_RESOLUTION is supported.
2229
            timer_flags = CREATE_WAITABLE_TIMER_HIGH_RESOLUTION;
2230
            CloseHandle(timer);
2231
        }
2232
    }
2233
#endif
2234
2235
// gh-115714: Don't use times() on WASI.
2236
37
#if defined(HAVE_TIMES) && !defined(__wasi__)
2237
37
    long ticks_per_second;
2238
37
    if (_Py_GetTicksPerSecond(&ticks_per_second) < 0) {
2239
0
        PyErr_SetString(PyExc_RuntimeError,
2240
0
                        "cannot read ticks_per_second");
2241
0
        return -1;
2242
0
    }
2243
37
    if (_PyTimeFraction_Set(&state->times_base, SEC_TO_NS,
2244
37
                            ticks_per_second) < 0) {
2245
0
        PyErr_Format(PyExc_OverflowError, "ticks_per_second is too large");
2246
0
        return -1;
2247
0
    }
2248
37
#endif
2249
2250
37
#ifdef HAVE_CLOCK
2251
37
    if (_PyTimeFraction_Set(&state->clock_base, SEC_TO_NS,
2252
37
                            CLOCKS_PER_SEC) < 0) {
2253
0
        PyErr_Format(PyExc_OverflowError, "CLOCKS_PER_SEC is too large");
2254
0
        return -1;
2255
0
    }
2256
37
#endif
2257
2258
37
    return 0;
2259
37
}
2260
2261
2262
static int
2263
time_module_traverse(PyObject *module, visitproc visit, void *arg)
2264
1.64k
{
2265
1.64k
    time_module_state *state = get_time_state(module);
2266
1.64k
    Py_VISIT(state->struct_time_type);
2267
1.64k
    return 0;
2268
1.64k
}
2269
2270
2271
static int
2272
time_module_clear(PyObject *module)
2273
0
{
2274
0
    time_module_state *state = get_time_state(module);
2275
0
    Py_CLEAR(state->struct_time_type);
2276
0
    return 0;
2277
0
}
2278
2279
2280
static void
2281
time_module_free(void *module)
2282
0
{
2283
0
    time_module_clear((PyObject *)module);
2284
0
}
2285
2286
2287
static struct PyModuleDef_Slot time_slots[] = {
2288
    _Py_ABI_SLOT,
2289
    {Py_mod_exec, time_exec},
2290
    {Py_mod_multiple_interpreters, Py_MOD_PER_INTERPRETER_GIL_SUPPORTED},
2291
    {Py_mod_gil, Py_MOD_GIL_NOT_USED},
2292
    {0, NULL}
2293
};
2294
2295
static struct PyModuleDef timemodule = {
2296
    PyModuleDef_HEAD_INIT,
2297
    .m_name = "time",
2298
    .m_doc = module_doc,
2299
    .m_size = sizeof(time_module_state),
2300
    .m_methods = time_methods,
2301
    .m_slots = time_slots,
2302
    .m_traverse = time_module_traverse,
2303
    .m_clear = time_module_clear,
2304
    .m_free = time_module_free,
2305
};
2306
2307
PyMODINIT_FUNC
2308
PyInit_time(void)
2309
37
{
2310
37
    return PyModuleDef_Init(&timemodule);
2311
37
}
2312
2313
2314
// time.sleep() implementation.
2315
// On error, raise an exception and return -1.
2316
// On success, return 0.
2317
static int
2318
pysleep(PyTime_t timeout)
2319
0
{
2320
0
    assert(timeout >= 0);
2321
2322
0
#ifndef MS_WINDOWS
2323
0
#ifdef HAVE_CLOCK_NANOSLEEP
2324
0
    struct timespec timeout_abs;
2325
#elif defined(HAVE_NANOSLEEP)
2326
    struct timespec timeout_ts;
2327
#else
2328
    struct timeval timeout_tv;
2329
#endif
2330
0
    PyTime_t deadline, monotonic;
2331
0
    int err = 0;
2332
2333
0
    if (PyTime_Monotonic(&monotonic) < 0) {
2334
0
        return -1;
2335
0
    }
2336
0
    deadline = monotonic + timeout;
2337
0
#ifdef HAVE_CLOCK_NANOSLEEP
2338
0
    if (_PyTime_AsTimespec(deadline, &timeout_abs) < 0) {
2339
0
        return -1;
2340
0
    }
2341
0
#endif
2342
2343
0
    do {
2344
0
#ifdef HAVE_CLOCK_NANOSLEEP
2345
        // use timeout_abs
2346
#elif defined(HAVE_NANOSLEEP)
2347
        if (_PyTime_AsTimespec(timeout, &timeout_ts) < 0) {
2348
            return -1;
2349
        }
2350
#else
2351
        if (_PyTime_AsTimeval(timeout, &timeout_tv, _PyTime_ROUND_CEILING) < 0) {
2352
            return -1;
2353
        }
2354
#endif
2355
2356
0
        int ret;
2357
0
        Py_BEGIN_ALLOW_THREADS
2358
0
#ifdef HAVE_CLOCK_NANOSLEEP
2359
0
        ret = clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &timeout_abs, NULL);
2360
0
        err = ret;
2361
#elif defined(HAVE_NANOSLEEP)
2362
        ret = nanosleep(&timeout_ts, NULL);
2363
        err = errno;
2364
#else
2365
        ret = select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &timeout_tv);
2366
        err = errno;
2367
#endif
2368
0
        Py_END_ALLOW_THREADS
2369
2370
0
        if (ret == 0) {
2371
0
            break;
2372
0
        }
2373
2374
0
        if (err != EINTR) {
2375
0
            errno = err;
2376
0
            PyErr_SetFromErrno(PyExc_OSError);
2377
0
            return -1;
2378
0
        }
2379
2380
        /* sleep was interrupted by SIGINT */
2381
0
        if (PyErr_CheckSignals()) {
2382
0
            return -1;
2383
0
        }
2384
2385
#ifndef HAVE_CLOCK_NANOSLEEP
2386
        if (PyTime_Monotonic(&monotonic) < 0) {
2387
            return -1;
2388
        }
2389
        timeout = deadline - monotonic;
2390
        if (timeout < 0) {
2391
            break;
2392
        }
2393
        /* retry with the recomputed delay */
2394
#endif
2395
0
    } while (1);
2396
2397
0
    return 0;
2398
#else  // MS_WINDOWS
2399
    PyTime_t timeout_100ns = _PyTime_As100Nanoseconds(timeout,
2400
                                                       _PyTime_ROUND_CEILING);
2401
2402
    // Maintain Windows Sleep() semantics for time.sleep(0)
2403
    if (timeout_100ns == 0) {
2404
        Py_BEGIN_ALLOW_THREADS
2405
        // A value of zero causes the thread to relinquish the remainder of its
2406
        // time slice to any other thread that is ready to run. If there are no
2407
        // other threads ready to run, the function returns immediately, and
2408
        // the thread continues execution.
2409
        Sleep(0);
2410
        Py_END_ALLOW_THREADS
2411
        return 0;
2412
    }
2413
2414
    LARGE_INTEGER relative_timeout;
2415
    // No need to check for integer overflow, both types are signed
2416
    assert(sizeof(relative_timeout) == sizeof(timeout_100ns));
2417
    // SetWaitableTimer(): a negative due time indicates relative time
2418
    relative_timeout.QuadPart = -timeout_100ns;
2419
2420
    HANDLE timer = CreateWaitableTimerExW(NULL, NULL, timer_flags,
2421
                                          TIMER_ALL_ACCESS);
2422
    if (timer == NULL) {
2423
        PyErr_SetFromWindowsErr(0);
2424
        return -1;
2425
    }
2426
2427
    if (!SetWaitableTimerEx(timer, &relative_timeout,
2428
                            0, // no period; the timer is signaled once
2429
                            NULL, NULL, // no completion routine
2430
                            NULL,  // no wake context; do not resume from suspend
2431
                            0)) // no tolerable delay for timer coalescing
2432
    {
2433
        PyErr_SetFromWindowsErr(0);
2434
        goto error;
2435
    }
2436
2437
    // Only the main thread can be interrupted by SIGINT.
2438
    // Signal handlers are only executed in the main thread.
2439
    if (_PyOS_IsMainThread()) {
2440
        HANDLE sigint_event = _PyOS_SigintEvent();
2441
2442
        while (1) {
2443
            // Check for pending SIGINT signal before resetting the event
2444
            if (PyErr_CheckSignals()) {
2445
                goto error;
2446
            }
2447
            ResetEvent(sigint_event);
2448
2449
            HANDLE events[] = {timer, sigint_event};
2450
            DWORD rc;
2451
2452
            Py_BEGIN_ALLOW_THREADS
2453
            rc = WaitForMultipleObjects(Py_ARRAY_LENGTH(events), events,
2454
                                        // bWaitAll
2455
                                        FALSE,
2456
                                        // No wait timeout
2457
                                        INFINITE);
2458
            Py_END_ALLOW_THREADS
2459
2460
            if (rc == WAIT_FAILED) {
2461
                PyErr_SetFromWindowsErr(0);
2462
                goto error;
2463
            }
2464
2465
            if (rc == WAIT_OBJECT_0) {
2466
                // Timer signaled: we are done
2467
                break;
2468
            }
2469
2470
            assert(rc == (WAIT_OBJECT_0 + 1));
2471
            // The sleep was interrupted by SIGINT: restart sleeping
2472
        }
2473
    }
2474
    else {
2475
        DWORD rc;
2476
2477
        Py_BEGIN_ALLOW_THREADS
2478
        rc = WaitForSingleObject(timer, INFINITE);
2479
        Py_END_ALLOW_THREADS
2480
2481
        if (rc == WAIT_FAILED) {
2482
            PyErr_SetFromWindowsErr(0);
2483
            goto error;
2484
        }
2485
2486
        assert(rc == WAIT_OBJECT_0);
2487
        // Timer signaled: we are done
2488
    }
2489
2490
    CloseHandle(timer);
2491
    return 0;
2492
2493
error:
2494
    CloseHandle(timer);
2495
    return -1;
2496
#endif
2497
0
}