1 /* Time module */
2 
3 #include "Python.h"
4 
5 #include <ctype.h>
6 
7 #ifdef HAVE_SYS_TIMES_H
8 #include <sys/times.h>
9 #endif
10 
11 #ifdef HAVE_SYS_TYPES_H
12 #include <sys/types.h>
13 #endif
14 
15 #if defined(HAVE_SYS_RESOURCE_H)
16 #include <sys/resource.h>
17 #endif
18 
19 #ifdef QUICKWIN
20 #include <io.h>
21 #endif
22 
23 #if defined(HAVE_PTHREAD_H)
24 #  include <pthread.h>
25 #endif
26 
27 #if defined(__WATCOMC__) && !defined(__QNX__)
28 #include <i86.h>
29 #else
30 #ifdef MS_WINDOWS
31 #define WIN32_LEAN_AND_MEAN
32 #include <windows.h>
33 #include "pythread.h"
34 #endif /* MS_WINDOWS */
35 #endif /* !__WATCOMC__ || __QNX__ */
36 
37 #ifdef _Py_MEMORY_SANITIZER
38 # include <sanitizer/msan_interface.h>
39 #endif
40 
41 #ifdef _MSC_VER
42 #define _Py_timezone _timezone
43 #define _Py_daylight _daylight
44 #define _Py_tzname _tzname
45 #else
46 #define _Py_timezone timezone
47 #define _Py_daylight daylight
48 #define _Py_tzname tzname
49 #endif
50 
51 #define SEC_TO_NS (1000 * 1000 * 1000)
52 
53 /* Forward declarations */
54 static int pysleep(_PyTime_t);
55 
56 
57 static PyObject*
_PyFloat_FromPyTime(_PyTime_t t)58 _PyFloat_FromPyTime(_PyTime_t t)
59 {
60     double d = _PyTime_AsSecondsDouble(t);
61     return PyFloat_FromDouble(d);
62 }
63 
64 
65 static PyObject *
time_time(PyObject * self,PyObject * unused)66 time_time(PyObject *self, PyObject *unused)
67 {
68     _PyTime_t t = _PyTime_GetSystemClock();
69     return _PyFloat_FromPyTime(t);
70 }
71 
72 
73 PyDoc_STRVAR(time_doc,
74 "time() -> floating point number\n\
75 \n\
76 Return the current time in seconds since the Epoch.\n\
77 Fractions of a second may be present if the system clock provides them.");
78 
79 static PyObject *
time_time_ns(PyObject * self,PyObject * unused)80 time_time_ns(PyObject *self, PyObject *unused)
81 {
82     _PyTime_t t = _PyTime_GetSystemClock();
83     return _PyTime_AsNanosecondsObject(t);
84 }
85 
86 PyDoc_STRVAR(time_ns_doc,
87 "time_ns() -> int\n\
88 \n\
89 Return the current time in nanoseconds since the Epoch.");
90 
91 #if defined(HAVE_CLOCK)
92 
93 #ifndef CLOCKS_PER_SEC
94 #  ifdef CLK_TCK
95 #    define CLOCKS_PER_SEC CLK_TCK
96 #  else
97 #    define CLOCKS_PER_SEC 1000000
98 #  endif
99 #endif
100 
101 static int
_PyTime_GetClockWithInfo(_PyTime_t * tp,_Py_clock_info_t * info)102 _PyTime_GetClockWithInfo(_PyTime_t *tp, _Py_clock_info_t *info)
103 {
104     static int initialized = 0;
105     clock_t ticks;
106 
107     if (!initialized) {
108         initialized = 1;
109 
110         /* must sure that _PyTime_MulDiv(ticks, SEC_TO_NS, CLOCKS_PER_SEC)
111            above cannot overflow */
112         if ((_PyTime_t)CLOCKS_PER_SEC > _PyTime_MAX / SEC_TO_NS) {
113             PyErr_SetString(PyExc_OverflowError,
114                             "CLOCKS_PER_SEC is too large");
115             return -1;
116         }
117     }
118 
119     if (info) {
120         info->implementation = "clock()";
121         info->resolution = 1.0 / (double)CLOCKS_PER_SEC;
122         info->monotonic = 1;
123         info->adjustable = 0;
124     }
125 
126     ticks = clock();
127     if (ticks == (clock_t)-1) {
128         PyErr_SetString(PyExc_RuntimeError,
129                         "the processor time used is not available "
130                         "or its value cannot be represented");
131         return -1;
132     }
133     *tp = _PyTime_MulDiv(ticks, SEC_TO_NS, (_PyTime_t)CLOCKS_PER_SEC);
134     return 0;
135 }
136 #endif /* HAVE_CLOCK */
137 
138 static PyObject*
perf_counter(_Py_clock_info_t * info)139 perf_counter(_Py_clock_info_t *info)
140 {
141     _PyTime_t t;
142     if (_PyTime_GetPerfCounterWithInfo(&t, info) < 0) {
143         return NULL;
144     }
145     return _PyFloat_FromPyTime(t);
146 }
147 
148 #ifdef HAVE_CLOCK_GETTIME
149 static PyObject *
time_clock_gettime(PyObject * self,PyObject * args)150 time_clock_gettime(PyObject *self, PyObject *args)
151 {
152     int ret;
153     struct timespec tp;
154 
155 #if defined(_AIX) && (SIZEOF_LONG == 8)
156     long clk_id;
157     if (!PyArg_ParseTuple(args, "l:clock_gettime", &clk_id)) {
158 #else
159     int clk_id;
160     if (!PyArg_ParseTuple(args, "i:clock_gettime", &clk_id)) {
161 #endif
162         return NULL;
163     }
164 
165     ret = clock_gettime((clockid_t)clk_id, &tp);
166     if (ret != 0) {
167         PyErr_SetFromErrno(PyExc_OSError);
168         return NULL;
169     }
170     return PyFloat_FromDouble(tp.tv_sec + tp.tv_nsec * 1e-9);
171 }
172 
173 PyDoc_STRVAR(clock_gettime_doc,
174 "clock_gettime(clk_id) -> float\n\
175 \n\
176 Return the time of the specified clock clk_id.");
177 
178 static PyObject *
179 time_clock_gettime_ns(PyObject *self, PyObject *args)
180 {
181     int ret;
182     int clk_id;
183     struct timespec ts;
184     _PyTime_t t;
185 
186     if (!PyArg_ParseTuple(args, "i:clock_gettime", &clk_id)) {
187         return NULL;
188     }
189 
190     ret = clock_gettime((clockid_t)clk_id, &ts);
191     if (ret != 0) {
192         PyErr_SetFromErrno(PyExc_OSError);
193         return NULL;
194     }
195     if (_PyTime_FromTimespec(&t, &ts) < 0) {
196         return NULL;
197     }
198     return _PyTime_AsNanosecondsObject(t);
199 }
200 
201 PyDoc_STRVAR(clock_gettime_ns_doc,
202 "clock_gettime_ns(clk_id) -> int\n\
203 \n\
204 Return the time of the specified clock clk_id as nanoseconds.");
205 #endif   /* HAVE_CLOCK_GETTIME */
206 
207 #ifdef HAVE_CLOCK_SETTIME
208 static PyObject *
209 time_clock_settime(PyObject *self, PyObject *args)
210 {
211     int clk_id;
212     PyObject *obj;
213     _PyTime_t t;
214     struct timespec tp;
215     int ret;
216 
217     if (!PyArg_ParseTuple(args, "iO:clock_settime", &clk_id, &obj))
218         return NULL;
219 
220     if (_PyTime_FromSecondsObject(&t, obj, _PyTime_ROUND_FLOOR) < 0)
221         return NULL;
222 
223     if (_PyTime_AsTimespec(t, &tp) == -1)
224         return NULL;
225 
226     ret = clock_settime((clockid_t)clk_id, &tp);
227     if (ret != 0) {
228         PyErr_SetFromErrno(PyExc_OSError);
229         return NULL;
230     }
231     Py_RETURN_NONE;
232 }
233 
234 PyDoc_STRVAR(clock_settime_doc,
235 "clock_settime(clk_id, time)\n\
236 \n\
237 Set the time of the specified clock clk_id.");
238 
239 static PyObject *
240 time_clock_settime_ns(PyObject *self, PyObject *args)
241 {
242     int clk_id;
243     PyObject *obj;
244     _PyTime_t t;
245     struct timespec ts;
246     int ret;
247 
248     if (!PyArg_ParseTuple(args, "iO:clock_settime", &clk_id, &obj)) {
249         return NULL;
250     }
251 
252     if (_PyTime_FromNanosecondsObject(&t, obj) < 0) {
253         return NULL;
254     }
255     if (_PyTime_AsTimespec(t, &ts) == -1) {
256         return NULL;
257     }
258 
259     ret = clock_settime((clockid_t)clk_id, &ts);
260     if (ret != 0) {
261         PyErr_SetFromErrno(PyExc_OSError);
262         return NULL;
263     }
264     Py_RETURN_NONE;
265 }
266 
267 PyDoc_STRVAR(clock_settime_ns_doc,
268 "clock_settime_ns(clk_id, time)\n\
269 \n\
270 Set the time of the specified clock clk_id with nanoseconds.");
271 #endif   /* HAVE_CLOCK_SETTIME */
272 
273 #ifdef HAVE_CLOCK_GETRES
274 static PyObject *
275 time_clock_getres(PyObject *self, PyObject *args)
276 {
277     int ret;
278     int clk_id;
279     struct timespec tp;
280 
281     if (!PyArg_ParseTuple(args, "i:clock_getres", &clk_id))
282         return NULL;
283 
284     ret = clock_getres((clockid_t)clk_id, &tp);
285     if (ret != 0) {
286         PyErr_SetFromErrno(PyExc_OSError);
287         return NULL;
288     }
289 
290     return PyFloat_FromDouble(tp.tv_sec + tp.tv_nsec * 1e-9);
291 }
292 
293 PyDoc_STRVAR(clock_getres_doc,
294 "clock_getres(clk_id) -> floating point number\n\
295 \n\
296 Return the resolution (precision) of the specified clock clk_id.");
297 #endif   /* HAVE_CLOCK_GETRES */
298 
299 #ifdef HAVE_PTHREAD_GETCPUCLOCKID
300 static PyObject *
301 time_pthread_getcpuclockid(PyObject *self, PyObject *args)
302 {
303     unsigned long thread_id;
304     int err;
305     clockid_t clk_id;
306     if (!PyArg_ParseTuple(args, "k:pthread_getcpuclockid", &thread_id)) {
307         return NULL;
308     }
309     err = pthread_getcpuclockid((pthread_t)thread_id, &clk_id);
310     if (err) {
311         errno = err;
312         PyErr_SetFromErrno(PyExc_OSError);
313         return NULL;
314     }
315 #ifdef _Py_MEMORY_SANITIZER
316     __msan_unpoison(&clk_id, sizeof(clk_id));
317 #endif
318     return PyLong_FromLong(clk_id);
319 }
320 
321 PyDoc_STRVAR(pthread_getcpuclockid_doc,
322 "pthread_getcpuclockid(thread_id) -> int\n\
323 \n\
324 Return the clk_id of a thread's CPU time clock.");
325 #endif /* HAVE_PTHREAD_GETCPUCLOCKID */
326 
327 static PyObject *
328 time_sleep(PyObject *self, PyObject *obj)
329 {
330     _PyTime_t secs;
331     if (_PyTime_FromSecondsObject(&secs, obj, _PyTime_ROUND_TIMEOUT))
332         return NULL;
333     if (secs < 0) {
334         PyErr_SetString(PyExc_ValueError,
335                         "sleep length must be non-negative");
336         return NULL;
337     }
338     if (pysleep(secs) != 0)
339         return NULL;
340     Py_RETURN_NONE;
341 }
342 
343 PyDoc_STRVAR(sleep_doc,
344 "sleep(seconds)\n\
345 \n\
346 Delay execution for a given number of seconds.  The argument may be\n\
347 a floating point number for subsecond precision.");
348 
349 static PyStructSequence_Field struct_time_type_fields[] = {
350     {"tm_year", "year, for example, 1993"},
351     {"tm_mon", "month of year, range [1, 12]"},
352     {"tm_mday", "day of month, range [1, 31]"},
353     {"tm_hour", "hours, range [0, 23]"},
354     {"tm_min", "minutes, range [0, 59]"},
355     {"tm_sec", "seconds, range [0, 61])"},
356     {"tm_wday", "day of week, range [0, 6], Monday is 0"},
357     {"tm_yday", "day of year, range [1, 366]"},
358     {"tm_isdst", "1 if summer time is in effect, 0 if not, and -1 if unknown"},
359     {"tm_zone", "abbreviation of timezone name"},
360     {"tm_gmtoff", "offset from UTC in seconds"},
361     {0}
362 };
363 
364 static PyStructSequence_Desc struct_time_type_desc = {
365     "time.struct_time",
366     "The time value as returned by gmtime(), localtime(), and strptime(), and\n"
367     " accepted by asctime(), mktime() and strftime().  May be considered as a\n"
368     " sequence of 9 integers.\n\n"
369     " Note that several fields' values are not the same as those defined by\n"
370     " the C language standard for struct tm.  For example, the value of the\n"
371     " field tm_year is the actual year, not year - 1900.  See individual\n"
372     " fields' descriptions for details.",
373     struct_time_type_fields,
374     9,
375 };
376 
377 static int initialized;
378 static PyTypeObject StructTimeType;
379 
380 
381 static PyObject *
382 tmtotuple(struct tm *p
383 #ifndef HAVE_STRUCT_TM_TM_ZONE
384         , const char *zone, time_t gmtoff
385 #endif
386 )
387 {
388     PyObject *v = PyStructSequence_New(&StructTimeType);
389     if (v == NULL)
390         return NULL;
391 
392 #define SET(i,val) PyStructSequence_SET_ITEM(v, i, PyLong_FromLong((long) val))
393 
394     SET(0, p->tm_year + 1900);
395     SET(1, p->tm_mon + 1);         /* Want January == 1 */
396     SET(2, p->tm_mday);
397     SET(3, p->tm_hour);
398     SET(4, p->tm_min);
399     SET(5, p->tm_sec);
400     SET(6, (p->tm_wday + 6) % 7); /* Want Monday == 0 */
401     SET(7, p->tm_yday + 1);        /* Want January, 1 == 1 */
402     SET(8, p->tm_isdst);
403 #ifdef HAVE_STRUCT_TM_TM_ZONE
404     PyStructSequence_SET_ITEM(v, 9,
405         PyUnicode_DecodeLocale(p->tm_zone, "surrogateescape"));
406     SET(10, p->tm_gmtoff);
407 #else
408     PyStructSequence_SET_ITEM(v, 9,
409         PyUnicode_DecodeLocale(zone, "surrogateescape"));
410     PyStructSequence_SET_ITEM(v, 10, _PyLong_FromTime_t(gmtoff));
411 #endif /* HAVE_STRUCT_TM_TM_ZONE */
412 #undef SET
413     if (PyErr_Occurred()) {
414         Py_XDECREF(v);
415         return NULL;
416     }
417 
418     return v;
419 }
420 
421 /* Parse arg tuple that can contain an optional float-or-None value;
422    format needs to be "|O:name".
423    Returns non-zero on success (parallels PyArg_ParseTuple).
424 */
425 static int
426 parse_time_t_args(PyObject *args, const char *format, time_t *pwhen)
427 {
428     PyObject *ot = NULL;
429     time_t whent;
430 
431     if (!PyArg_ParseTuple(args, format, &ot))
432         return 0;
433     if (ot == NULL || ot == Py_None) {
434         whent = time(NULL);
435     }
436     else {
437         if (_PyTime_ObjectToTime_t(ot, &whent, _PyTime_ROUND_FLOOR) == -1)
438             return 0;
439     }
440     *pwhen = whent;
441     return 1;
442 }
443 
444 static PyObject *
445 time_gmtime(PyObject *self, PyObject *args)
446 {
447     time_t when;
448     struct tm buf;
449 
450     if (!parse_time_t_args(args, "|O:gmtime", &when))
451         return NULL;
452 
453     errno = 0;
454     if (_PyTime_gmtime(when, &buf) != 0)
455         return NULL;
456 #ifdef HAVE_STRUCT_TM_TM_ZONE
457     return tmtotuple(&buf);
458 #else
459     return tmtotuple(&buf, "UTC", 0);
460 #endif
461 }
462 
463 #ifndef HAVE_TIMEGM
464 static time_t
465 timegm(struct tm *p)
466 {
467     /* XXX: the following implementation will not work for tm_year < 1970.
468        but it is likely that platforms that don't have timegm do not support
469        negative timestamps anyways. */
470     return p->tm_sec + p->tm_min*60 + p->tm_hour*3600 + p->tm_yday*86400 +
471         (p->tm_year-70)*31536000 + ((p->tm_year-69)/4)*86400 -
472         ((p->tm_year-1)/100)*86400 + ((p->tm_year+299)/400)*86400;
473 }
474 #endif
475 
476 PyDoc_STRVAR(gmtime_doc,
477 "gmtime([seconds]) -> (tm_year, tm_mon, tm_mday, tm_hour, tm_min,\n\
478                        tm_sec, tm_wday, tm_yday, tm_isdst)\n\
479 \n\
480 Convert seconds since the Epoch to a time tuple expressing UTC (a.k.a.\n\
481 GMT).  When 'seconds' is not passed in, convert the current time instead.\n\
482 \n\
483 If the platform supports the tm_gmtoff and tm_zone, they are available as\n\
484 attributes only.");
485 
486 static PyObject *
487 time_localtime(PyObject *self, PyObject *args)
488 {
489     time_t when;
490     struct tm buf;
491 
492     if (!parse_time_t_args(args, "|O:localtime", &when))
493         return NULL;
494     if (_PyTime_localtime(when, &buf) != 0)
495         return NULL;
496 #ifdef HAVE_STRUCT_TM_TM_ZONE
497     return tmtotuple(&buf);
498 #else
499     {
500         struct tm local = buf;
501         char zone[100];
502         time_t gmtoff;
503         strftime(zone, sizeof(zone), "%Z", &buf);
504         gmtoff = timegm(&buf) - when;
505         return tmtotuple(&local, zone, gmtoff);
506     }
507 #endif
508 }
509 
510 #if defined(__linux__) && !defined(__GLIBC__)
511 static const char *utc_string = NULL;
512 #endif
513 
514 PyDoc_STRVAR(localtime_doc,
515 "localtime([seconds]) -> (tm_year,tm_mon,tm_mday,tm_hour,tm_min,\n\
516                           tm_sec,tm_wday,tm_yday,tm_isdst)\n\
517 \n\
518 Convert seconds since the Epoch to a time tuple expressing local time.\n\
519 When 'seconds' is not passed in, convert the current time instead.");
520 
521 /* Convert 9-item tuple to tm structure.  Return 1 on success, set
522  * an exception and return 0 on error.
523  */
524 static int
525 gettmarg(PyObject *args, struct tm *p, const char *format)
526 {
527     int y;
528 
529     memset((void *) p, '\0', sizeof(struct tm));
530 
531     if (!PyTuple_Check(args)) {
532         PyErr_SetString(PyExc_TypeError,
533                         "Tuple or struct_time argument required");
534         return 0;
535     }
536 
537     if (!PyArg_ParseTuple(args, format,
538                           &y, &p->tm_mon, &p->tm_mday,
539                           &p->tm_hour, &p->tm_min, &p->tm_sec,
540                           &p->tm_wday, &p->tm_yday, &p->tm_isdst))
541         return 0;
542 
543     if (y < INT_MIN + 1900) {
544         PyErr_SetString(PyExc_OverflowError, "year out of range");
545         return 0;
546     }
547 
548     p->tm_year = y - 1900;
549     p->tm_mon--;
550     p->tm_wday = (p->tm_wday + 1) % 7;
551     p->tm_yday--;
552 #ifdef HAVE_STRUCT_TM_TM_ZONE
553     if (Py_TYPE(args) == &StructTimeType) {
554         PyObject *item;
555         item = PyStructSequence_GET_ITEM(args, 9);
556         if (item != Py_None) {
557             p->tm_zone = (char *)PyUnicode_AsUTF8(item);
558             if (p->tm_zone == NULL) {
559                 return 0;
560             }
561 #if defined(__linux__) && !defined(__GLIBC__)
562             // Make an attempt to return the C library's own timezone strings to
563             // it. musl refuses to process a tm_zone field unless it produced
564             // it. See issue #34672.
565             if (utc_string && strcmp(p->tm_zone, utc_string) == 0) {
566                 p->tm_zone = utc_string;
567             }
568             else if (tzname[0] && strcmp(p->tm_zone, tzname[0]) == 0) {
569                 p->tm_zone = tzname[0];
570             }
571             else if (tzname[1] && strcmp(p->tm_zone, tzname[1]) == 0) {
572                 p->tm_zone = tzname[1];
573             }
574 #endif
575         }
576         item = PyStructSequence_GET_ITEM(args, 10);
577         if (item != Py_None) {
578             p->tm_gmtoff = PyLong_AsLong(item);
579             if (PyErr_Occurred())
580                 return 0;
581         }
582     }
583 #endif /* HAVE_STRUCT_TM_TM_ZONE */
584     return 1;
585 }
586 
587 /* Check values of the struct tm fields before it is passed to strftime() and
588  * asctime().  Return 1 if all values are valid, otherwise set an exception
589  * and returns 0.
590  */
591 static int
592 checktm(struct tm* buf)
593 {
594     /* Checks added to make sure strftime() and asctime() does not crash Python by
595        indexing blindly into some array for a textual representation
596        by some bad index (fixes bug #897625 and #6608).
597 
598        Also support values of zero from Python code for arguments in which
599        that is out of range by forcing that value to the lowest value that
600        is valid (fixed bug #1520914).
601 
602        Valid ranges based on what is allowed in struct tm:
603 
604        - tm_year: [0, max(int)] (1)
605        - tm_mon: [0, 11] (2)
606        - tm_mday: [1, 31]
607        - tm_hour: [0, 23]
608        - tm_min: [0, 59]
609        - tm_sec: [0, 60]
610        - tm_wday: [0, 6] (1)
611        - tm_yday: [0, 365] (2)
612        - tm_isdst: [-max(int), max(int)]
613 
614        (1) gettmarg() handles bounds-checking.
615        (2) Python's acceptable range is one greater than the range in C,
616        thus need to check against automatic decrement by gettmarg().
617     */
618     if (buf->tm_mon == -1)
619         buf->tm_mon = 0;
620     else if (buf->tm_mon < 0 || buf->tm_mon > 11) {
621         PyErr_SetString(PyExc_ValueError, "month out of range");
622         return 0;
623     }
624     if (buf->tm_mday == 0)
625         buf->tm_mday = 1;
626     else if (buf->tm_mday < 0 || buf->tm_mday > 31) {
627         PyErr_SetString(PyExc_ValueError, "day of month out of range");
628         return 0;
629     }
630     if (buf->tm_hour < 0 || buf->tm_hour > 23) {
631         PyErr_SetString(PyExc_ValueError, "hour out of range");
632         return 0;
633     }
634     if (buf->tm_min < 0 || buf->tm_min > 59) {
635         PyErr_SetString(PyExc_ValueError, "minute out of range");
636         return 0;
637     }
638     if (buf->tm_sec < 0 || buf->tm_sec > 61) {
639         PyErr_SetString(PyExc_ValueError, "seconds out of range");
640         return 0;
641     }
642     /* tm_wday does not need checking of its upper-bound since taking
643     ``% 7`` in gettmarg() automatically restricts the range. */
644     if (buf->tm_wday < 0) {
645         PyErr_SetString(PyExc_ValueError, "day of week out of range");
646         return 0;
647     }
648     if (buf->tm_yday == -1)
649         buf->tm_yday = 0;
650     else if (buf->tm_yday < 0 || buf->tm_yday > 365) {
651         PyErr_SetString(PyExc_ValueError, "day of year out of range");
652         return 0;
653     }
654     return 1;
655 }
656 
657 #ifdef MS_WINDOWS
658    /* wcsftime() doesn't format correctly time zones, see issue #10653 */
659 #  undef HAVE_WCSFTIME
660 #endif
661 #define STRFTIME_FORMAT_CODES \
662 "Commonly used format codes:\n\
663 \n\
664 %Y  Year with century as a decimal number.\n\
665 %m  Month as a decimal number [01,12].\n\
666 %d  Day of the month as a decimal number [01,31].\n\
667 %H  Hour (24-hour clock) as a decimal number [00,23].\n\
668 %M  Minute as a decimal number [00,59].\n\
669 %S  Second as a decimal number [00,61].\n\
670 %z  Time zone offset from UTC.\n\
671 %a  Locale's abbreviated weekday name.\n\
672 %A  Locale's full weekday name.\n\
673 %b  Locale's abbreviated month name.\n\
674 %B  Locale's full month name.\n\
675 %c  Locale's appropriate date and time representation.\n\
676 %I  Hour (12-hour clock) as a decimal number [01,12].\n\
677 %p  Locale's equivalent of either AM or PM.\n\
678 \n\
679 Other codes may be available on your platform.  See documentation for\n\
680 the C library strftime function.\n"
681 
682 #ifdef HAVE_STRFTIME
683 #ifdef HAVE_WCSFTIME
684 #define time_char wchar_t
685 #define format_time wcsftime
686 #define time_strlen wcslen
687 #else
688 #define time_char char
689 #define format_time strftime
690 #define time_strlen strlen
691 #endif
692 
693 static PyObject *
694 time_strftime(PyObject *self, PyObject *args)
695 {
696     PyObject *tup = NULL;
697     struct tm buf;
698     const time_char *fmt;
699 #ifdef HAVE_WCSFTIME
700     wchar_t *format;
701 #else
702     PyObject *format;
703 #endif
704     PyObject *format_arg;
705     size_t fmtlen, buflen;
706     time_char *outbuf = NULL;
707     size_t i;
708     PyObject *ret = NULL;
709 
710     memset((void *) &buf, '\0', sizeof(buf));
711 
712     /* Will always expect a unicode string to be passed as format.
713        Given that there's no str type anymore in py3k this seems safe.
714     */
715     if (!PyArg_ParseTuple(args, "U|O:strftime", &format_arg, &tup))
716         return NULL;
717 
718     if (tup == NULL) {
719         time_t tt = time(NULL);
720         if (_PyTime_localtime(tt, &buf) != 0)
721             return NULL;
722     }
723     else if (!gettmarg(tup, &buf,
724                        "iiiiiiiii;strftime(): illegal time tuple argument") ||
725              !checktm(&buf))
726     {
727         return NULL;
728     }
729 
730 #if defined(_MSC_VER) || (defined(__sun) && defined(__SVR4)) || defined(_AIX) || defined(__VXWORKS__)
731     if (buf.tm_year + 1900 < 1 || 9999 < buf.tm_year + 1900) {
732         PyErr_SetString(PyExc_ValueError,
733                         "strftime() requires year in [1; 9999]");
734         return NULL;
735     }
736 #endif
737 
738     /* Normalize tm_isdst just in case someone foolishly implements %Z
739        based on the assumption that tm_isdst falls within the range of
740        [-1, 1] */
741     if (buf.tm_isdst < -1)
742         buf.tm_isdst = -1;
743     else if (buf.tm_isdst > 1)
744         buf.tm_isdst = 1;
745 
746 #ifdef HAVE_WCSFTIME
747     format = PyUnicode_AsWideCharString(format_arg, NULL);
748     if (format == NULL)
749         return NULL;
750     fmt = format;
751 #else
752     /* Convert the unicode string to an ascii one */
753     format = PyUnicode_EncodeLocale(format_arg, "surrogateescape");
754     if (format == NULL)
755         return NULL;
756     fmt = PyBytes_AS_STRING(format);
757 #endif
758 
759 #if defined(MS_WINDOWS) && !defined(HAVE_WCSFTIME)
760     /* check that the format string contains only valid directives */
761     for (outbuf = strchr(fmt, '%');
762         outbuf != NULL;
763         outbuf = strchr(outbuf+2, '%'))
764     {
765         if (outbuf[1] == '#')
766             ++outbuf; /* not documented by python, */
767         if (outbuf[1] == '\0')
768             break;
769         if ((outbuf[1] == 'y') && buf.tm_year < 0) {
770             PyErr_SetString(PyExc_ValueError,
771                         "format %y requires year >= 1900 on Windows");
772             Py_DECREF(format);
773             return NULL;
774         }
775     }
776 #elif (defined(_AIX) || (defined(__sun) && defined(__SVR4))) && defined(HAVE_WCSFTIME)
777     for (outbuf = wcschr(fmt, '%');
778         outbuf != NULL;
779         outbuf = wcschr(outbuf+2, '%'))
780     {
781         if (outbuf[1] == L'\0')
782             break;
783         /* Issue #19634: On AIX, wcsftime("y", (1899, 1, 1, 0, 0, 0, 0, 0, 0))
784            returns "0/" instead of "99" */
785         if (outbuf[1] == L'y' && buf.tm_year < 0) {
786             PyErr_SetString(PyExc_ValueError,
787                             "format %y requires year >= 1900 on AIX");
788             PyMem_Free(format);
789             return NULL;
790         }
791     }
792 #endif
793 
794     fmtlen = time_strlen(fmt);
795 
796     /* I hate these functions that presume you know how big the output
797      * will be ahead of time...
798      */
799     for (i = 1024; ; i += i) {
800         outbuf = (time_char *)PyMem_Malloc(i*sizeof(time_char));
801         if (outbuf == NULL) {
802             PyErr_NoMemory();
803             break;
804         }
805 #if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
806         errno = 0;
807 #endif
808         _Py_BEGIN_SUPPRESS_IPH
809         buflen = format_time(outbuf, i, fmt, &buf);
810         _Py_END_SUPPRESS_IPH
811 #if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
812         /* VisualStudio .NET 2005 does this properly */
813         if (buflen == 0 && errno == EINVAL) {
814             PyErr_SetString(PyExc_ValueError, "Invalid format string");
815             PyMem_Free(outbuf);
816             break;
817         }
818 #endif
819         if (buflen > 0 || i >= 256 * fmtlen) {
820             /* If the buffer is 256 times as long as the format,
821                it's probably not failing for lack of room!
822                More likely, the format yields an empty result,
823                e.g. an empty format, or %Z when the timezone
824                is unknown. */
825 #ifdef HAVE_WCSFTIME
826             ret = PyUnicode_FromWideChar(outbuf, buflen);
827 #else
828             ret = PyUnicode_DecodeLocaleAndSize(outbuf, buflen, "surrogateescape");
829 #endif
830             PyMem_Free(outbuf);
831             break;
832         }
833         PyMem_Free(outbuf);
834     }
835 #ifdef HAVE_WCSFTIME
836     PyMem_Free(format);
837 #else
838     Py_DECREF(format);
839 #endif
840     return ret;
841 }
842 
843 #undef time_char
844 #undef format_time
845 PyDoc_STRVAR(strftime_doc,
846 "strftime(format[, tuple]) -> string\n\
847 \n\
848 Convert a time tuple to a string according to a format specification.\n\
849 See the library reference manual for formatting codes. When the time tuple\n\
850 is not present, current time as returned by localtime() is used.\n\
851 \n" STRFTIME_FORMAT_CODES);
852 #endif /* HAVE_STRFTIME */
853 
854 static PyObject *
855 time_strptime(PyObject *self, PyObject *args)
856 {
857     PyObject *module, *func, *result;
858     _Py_IDENTIFIER(_strptime_time);
859 
860     module = PyImport_ImportModuleNoBlock("_strptime");
861     if (!module)
862         return NULL;
863 
864     func = _PyObject_GetAttrId(module, &PyId__strptime_time);
865     Py_DECREF(module);
866     if (!func) {
867         return NULL;
868     }
869 
870     result = PyObject_Call(func, args, NULL);
871     Py_DECREF(func);
872     return result;
873 }
874 
875 
876 PyDoc_STRVAR(strptime_doc,
877 "strptime(string, format) -> struct_time\n\
878 \n\
879 Parse a string to a time tuple according to a format specification.\n\
880 See the library reference manual for formatting codes (same as\n\
881 strftime()).\n\
882 \n" STRFTIME_FORMAT_CODES);
883 
884 static PyObject *
885 _asctime(struct tm *timeptr)
886 {
887     /* Inspired by Open Group reference implementation available at
888      * http://pubs.opengroup.org/onlinepubs/009695399/functions/asctime.html */
889     static const char wday_name[7][4] = {
890         "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
891     };
892     static const char mon_name[12][4] = {
893         "Jan", "Feb", "Mar", "Apr", "May", "Jun",
894         "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
895     };
896     return PyUnicode_FromFormat(
897         "%s %s%3d %.2d:%.2d:%.2d %d",
898         wday_name[timeptr->tm_wday],
899         mon_name[timeptr->tm_mon],
900         timeptr->tm_mday, timeptr->tm_hour,
901         timeptr->tm_min, timeptr->tm_sec,
902         1900 + timeptr->tm_year);
903 }
904 
905 static PyObject *
906 time_asctime(PyObject *self, PyObject *args)
907 {
908     PyObject *tup = NULL;
909     struct tm buf;
910 
911     if (!PyArg_UnpackTuple(args, "asctime", 0, 1, &tup))
912         return NULL;
913     if (tup == NULL) {
914         time_t tt = time(NULL);
915         if (_PyTime_localtime(tt, &buf) != 0)
916             return NULL;
917     }
918     else if (!gettmarg(tup, &buf,
919                        "iiiiiiiii;asctime(): illegal time tuple argument") ||
920              !checktm(&buf))
921     {
922         return NULL;
923     }
924     return _asctime(&buf);
925 }
926 
927 PyDoc_STRVAR(asctime_doc,
928 "asctime([tuple]) -> string\n\
929 \n\
930 Convert a time tuple to a string, e.g. 'Sat Jun 06 16:26:11 1998'.\n\
931 When the time tuple is not present, current time as returned by localtime()\n\
932 is used.");
933 
934 static PyObject *
935 time_ctime(PyObject *self, PyObject *args)
936 {
937     time_t tt;
938     struct tm buf;
939     if (!parse_time_t_args(args, "|O:ctime", &tt))
940         return NULL;
941     if (_PyTime_localtime(tt, &buf) != 0)
942         return NULL;
943     return _asctime(&buf);
944 }
945 
946 PyDoc_STRVAR(ctime_doc,
947 "ctime(seconds) -> string\n\
948 \n\
949 Convert a time in seconds since the Epoch to a string in local time.\n\
950 This is equivalent to asctime(localtime(seconds)). When the time tuple is\n\
951 not present, current time as returned by localtime() is used.");
952 
953 #ifdef HAVE_MKTIME
954 static PyObject *
955 time_mktime(PyObject *self, PyObject *tm_tuple)
956 {
957     struct tm tm;
958     time_t tt;
959 
960     if (!gettmarg(tm_tuple, &tm,
961                   "iiiiiiiii;mktime(): illegal time tuple argument"))
962     {
963         return NULL;
964     }
965 
966 #if defined(_AIX) || (defined(__VXWORKS__) && !defined(_WRS_CONFIG_LP64))
967     /* bpo-19748: AIX mktime() valid range is 00:00:00 UTC, January 1, 1970
968        to 03:14:07 UTC, January 19, 2038. Thanks to the workaround below,
969        it is possible to support years in range [1902; 2037] */
970     if (tm.tm_year < 2 || tm.tm_year > 137) {
971         /* bpo-19748: On AIX, mktime() does not report overflow error
972            for timestamp < -2^31 or timestamp > 2**31-1. VxWorks has the
973            same issue when working in 32 bit mode. */
974         PyErr_SetString(PyExc_OverflowError,
975                         "mktime argument out of range");
976         return NULL;
977     }
978 #endif
979 
980 #ifdef _AIX
981     /* bpo-34373: AIX mktime() has an integer overflow for years in range
982        [1902; 1969]. Workaround the issue by using a year greater or equal than
983        1970 (tm_year >= 70): mktime() behaves correctly in that case
984        (ex: properly report errors). tm_year and tm_wday are adjusted after
985        mktime() call. */
986     int orig_tm_year = tm.tm_year;
987     int delta_days = 0;
988     while (tm.tm_year < 70) {
989         /* Use 4 years to account properly leap years */
990         tm.tm_year += 4;
991         delta_days -= (366 + (365 * 3));
992     }
993 #endif
994 
995     tm.tm_wday = -1;  /* sentinel; original value ignored */
996     tt = mktime(&tm);
997 
998     /* Return value of -1 does not necessarily mean an error, but tm_wday
999      * cannot remain set to -1 if mktime succeeded. */
1000     if (tt == (time_t)(-1)
1001         /* Return value of -1 does not necessarily mean an error, but
1002          * tm_wday cannot remain set to -1 if mktime succeeded. */
1003         && tm.tm_wday == -1)
1004     {
1005         PyErr_SetString(PyExc_OverflowError,
1006                         "mktime argument out of range");
1007         return NULL;
1008     }
1009 
1010 #ifdef _AIX
1011     if (delta_days != 0) {
1012         tm.tm_year = orig_tm_year;
1013         if (tm.tm_wday != -1) {
1014             tm.tm_wday = (tm.tm_wday + delta_days) % 7;
1015         }
1016         tt += delta_days * (24 * 3600);
1017     }
1018 #endif
1019 
1020     return PyFloat_FromDouble((double)tt);
1021 }
1022 
1023 PyDoc_STRVAR(mktime_doc,
1024 "mktime(tuple) -> floating point number\n\
1025 \n\
1026 Convert a time tuple in local time to seconds since the Epoch.\n\
1027 Note that mktime(gmtime(0)) will not generally return zero for most\n\
1028 time zones; instead the returned value will either be equal to that\n\
1029 of the timezone or altzone attributes on the time module.");
1030 #endif /* HAVE_MKTIME */
1031 
1032 #ifdef HAVE_WORKING_TZSET
1033 static int init_timezone(PyObject *module);
1034 
1035 static PyObject *
1036 time_tzset(PyObject *self, PyObject *unused)
1037 {
1038     PyObject* m;
1039 
1040     m = PyImport_ImportModuleNoBlock("time");
1041     if (m == NULL) {
1042         return NULL;
1043     }
1044 
1045     tzset();
1046 
1047     /* Reset timezone, altzone, daylight and tzname */
1048     if (init_timezone(m) < 0) {
1049          return NULL;
1050     }
1051     Py_DECREF(m);
1052     if (PyErr_Occurred())
1053         return NULL;
1054 
1055     Py_RETURN_NONE;
1056 }
1057 
1058 PyDoc_STRVAR(tzset_doc,
1059 "tzset()\n\
1060 \n\
1061 Initialize, or reinitialize, the local timezone to the value stored in\n\
1062 os.environ['TZ']. The TZ environment variable should be specified in\n\
1063 standard Unix timezone format as documented in the tzset man page\n\
1064 (eg. 'US/Eastern', 'Europe/Amsterdam'). Unknown timezones will silently\n\
1065 fall back to UTC. If the TZ environment variable is not set, the local\n\
1066 timezone is set to the systems best guess of wallclock time.\n\
1067 Changing the TZ environment variable without calling tzset *may* change\n\
1068 the local timezone used by methods such as localtime, but this behaviour\n\
1069 should not be relied on.");
1070 #endif /* HAVE_WORKING_TZSET */
1071 
1072 static PyObject *
1073 time_monotonic(PyObject *self, PyObject *unused)
1074 {
1075     _PyTime_t t = _PyTime_GetMonotonicClock();
1076     return _PyFloat_FromPyTime(t);
1077 }
1078 
1079 PyDoc_STRVAR(monotonic_doc,
1080 "monotonic() -> float\n\
1081 \n\
1082 Monotonic clock, cannot go backward.");
1083 
1084 static PyObject *
1085 time_monotonic_ns(PyObject *self, PyObject *unused)
1086 {
1087     _PyTime_t t = _PyTime_GetMonotonicClock();
1088     return _PyTime_AsNanosecondsObject(t);
1089 }
1090 
1091 PyDoc_STRVAR(monotonic_ns_doc,
1092 "monotonic_ns() -> int\n\
1093 \n\
1094 Monotonic clock, cannot go backward, as nanoseconds.");
1095 
1096 static PyObject *
1097 time_perf_counter(PyObject *self, PyObject *unused)
1098 {
1099     return perf_counter(NULL);
1100 }
1101 
1102 PyDoc_STRVAR(perf_counter_doc,
1103 "perf_counter() -> float\n\
1104 \n\
1105 Performance counter for benchmarking.");
1106 
1107 static PyObject *
1108 time_perf_counter_ns(PyObject *self, PyObject *unused)
1109 {
1110     _PyTime_t t = _PyTime_GetPerfCounter();
1111     return _PyTime_AsNanosecondsObject(t);
1112 }
1113 
1114 PyDoc_STRVAR(perf_counter_ns_doc,
1115 "perf_counter_ns() -> int\n\
1116 \n\
1117 Performance counter for benchmarking as nanoseconds.");
1118 
1119 static int
1120 _PyTime_GetProcessTimeWithInfo(_PyTime_t *tp, _Py_clock_info_t *info)
1121 {
1122 #if defined(MS_WINDOWS)
1123     HANDLE process;
1124     FILETIME creation_time, exit_time, kernel_time, user_time;
1125     ULARGE_INTEGER large;
1126     _PyTime_t ktime, utime, t;
1127     BOOL ok;
1128 
1129     process = GetCurrentProcess();
1130     ok = GetProcessTimes(process, &creation_time, &exit_time,
1131                          &kernel_time, &user_time);
1132     if (!ok) {
1133         PyErr_SetFromWindowsErr(0);
1134         return -1;
1135     }
1136 
1137     if (info) {
1138         info->implementation = "GetProcessTimes()";
1139         info->resolution = 1e-7;
1140         info->monotonic = 1;
1141         info->adjustable = 0;
1142     }
1143 
1144     large.u.LowPart = kernel_time.dwLowDateTime;
1145     large.u.HighPart = kernel_time.dwHighDateTime;
1146     ktime = large.QuadPart;
1147 
1148     large.u.LowPart = user_time.dwLowDateTime;
1149     large.u.HighPart = user_time.dwHighDateTime;
1150     utime = large.QuadPart;
1151 
1152     /* ktime and utime have a resolution of 100 nanoseconds */
1153     t = _PyTime_FromNanoseconds((ktime + utime) * 100);
1154     *tp = t;
1155     return 0;
1156 #else
1157 
1158     /* clock_gettime */
1159 #if defined(HAVE_CLOCK_GETTIME) \
1160     && (defined(CLOCK_PROCESS_CPUTIME_ID) || defined(CLOCK_PROF))
1161     struct timespec ts;
1162 #ifdef CLOCK_PROF
1163     const clockid_t clk_id = CLOCK_PROF;
1164     const char *function = "clock_gettime(CLOCK_PROF)";
1165 #else
1166     const clockid_t clk_id = CLOCK_PROCESS_CPUTIME_ID;
1167     const char *function = "clock_gettime(CLOCK_PROCESS_CPUTIME_ID)";
1168 #endif
1169 
1170     if (clock_gettime(clk_id, &ts) == 0) {
1171         if (info) {
1172             struct timespec res;
1173             info->implementation = function;
1174             info->monotonic = 1;
1175             info->adjustable = 0;
1176             if (clock_getres(clk_id, &res)) {
1177                 PyErr_SetFromErrno(PyExc_OSError);
1178                 return -1;
1179             }
1180             info->resolution = res.tv_sec + res.tv_nsec * 1e-9;
1181         }
1182 
1183         if (_PyTime_FromTimespec(tp, &ts) < 0) {
1184             return -1;
1185         }
1186         return 0;
1187     }
1188 #endif
1189 
1190     /* getrusage(RUSAGE_SELF) */
1191 #if defined(HAVE_SYS_RESOURCE_H)
1192     struct rusage ru;
1193 
1194     if (getrusage(RUSAGE_SELF, &ru) == 0) {
1195         _PyTime_t utime, stime;
1196 
1197         if (info) {
1198             info->implementation = "getrusage(RUSAGE_SELF)";
1199             info->monotonic = 1;
1200             info->adjustable = 0;
1201             info->resolution = 1e-6;
1202         }
1203 
1204         if (_PyTime_FromTimeval(&utime, &ru.ru_utime) < 0) {
1205             return -1;
1206         }
1207         if (_PyTime_FromTimeval(&stime, &ru.ru_stime) < 0) {
1208             return -1;
1209         }
1210 
1211         _PyTime_t total = utime + stime;
1212         *tp = total;
1213         return 0;
1214     }
1215 #endif
1216 
1217     /* times() */
1218 #ifdef HAVE_TIMES
1219     struct tms t;
1220 
1221     if (times(&t) != (clock_t)-1) {
1222         static long ticks_per_second = -1;
1223 
1224         if (ticks_per_second == -1) {
1225             long freq;
1226 #if defined(HAVE_SYSCONF) && defined(_SC_CLK_TCK)
1227             freq = sysconf(_SC_CLK_TCK);
1228             if (freq < 1) {
1229                 freq = -1;
1230             }
1231 #elif defined(HZ)
1232             freq = HZ;
1233 #else
1234             freq = 60; /* magic fallback value; may be bogus */
1235 #endif
1236 
1237             if (freq != -1) {
1238                 /* check that _PyTime_MulDiv(t, SEC_TO_NS, ticks_per_second)
1239                    cannot overflow below */
1240 #if LONG_MAX > _PyTime_MAX / SEC_TO_NS
1241                 if ((_PyTime_t)freq > _PyTime_MAX / SEC_TO_NS) {
1242                     PyErr_SetString(PyExc_OverflowError,
1243                                     "_SC_CLK_TCK is too large");
1244                     return -1;
1245                 }
1246 #endif
1247 
1248                 ticks_per_second = freq;
1249             }
1250         }
1251 
1252         if (ticks_per_second != -1) {
1253             if (info) {
1254                 info->implementation = "times()";
1255                 info->monotonic = 1;
1256                 info->adjustable = 0;
1257                 info->resolution = 1.0 / (double)ticks_per_second;
1258             }
1259 
1260             _PyTime_t total;
1261             total = _PyTime_MulDiv(t.tms_utime, SEC_TO_NS, ticks_per_second);
1262             total += _PyTime_MulDiv(t.tms_stime, SEC_TO_NS, ticks_per_second);
1263             *tp = total;
1264             return 0;
1265         }
1266     }
1267 #endif
1268 
1269     /* clock */
1270     /* Currently, Python 3 requires clock() to build: see issue #22624 */
1271     return _PyTime_GetClockWithInfo(tp, info);
1272 #endif
1273 }
1274 
1275 static PyObject *
1276 time_process_time(PyObject *self, PyObject *unused)
1277 {
1278     _PyTime_t t;
1279     if (_PyTime_GetProcessTimeWithInfo(&t, NULL) < 0) {
1280         return NULL;
1281     }
1282     return _PyFloat_FromPyTime(t);
1283 }
1284 
1285 PyDoc_STRVAR(process_time_doc,
1286 "process_time() -> float\n\
1287 \n\
1288 Process time for profiling: sum of the kernel and user-space CPU time.");
1289 
1290 static PyObject *
1291 time_process_time_ns(PyObject *self, PyObject *unused)
1292 {
1293     _PyTime_t t;
1294     if (_PyTime_GetProcessTimeWithInfo(&t, NULL) < 0) {
1295         return NULL;
1296     }
1297     return _PyTime_AsNanosecondsObject(t);
1298 }
1299 
1300 PyDoc_STRVAR(process_time_ns_doc,
1301 "process_time() -> int\n\
1302 \n\
1303 Process time for profiling as nanoseconds:\n\
1304 sum of the kernel and user-space CPU time.");
1305 
1306 
1307 #if defined(MS_WINDOWS)
1308 #define HAVE_THREAD_TIME
1309 static int
1310 _PyTime_GetThreadTimeWithInfo(_PyTime_t *tp, _Py_clock_info_t *info)
1311 {
1312     HANDLE thread;
1313     FILETIME creation_time, exit_time, kernel_time, user_time;
1314     ULARGE_INTEGER large;
1315     _PyTime_t ktime, utime, t;
1316     BOOL ok;
1317 
1318     thread =  GetCurrentThread();
1319     ok = GetThreadTimes(thread, &creation_time, &exit_time,
1320                         &kernel_time, &user_time);
1321     if (!ok) {
1322         PyErr_SetFromWindowsErr(0);
1323         return -1;
1324     }
1325 
1326     if (info) {
1327         info->implementation = "GetThreadTimes()";
1328         info->resolution = 1e-7;
1329         info->monotonic = 1;
1330         info->adjustable = 0;
1331     }
1332 
1333     large.u.LowPart = kernel_time.dwLowDateTime;
1334     large.u.HighPart = kernel_time.dwHighDateTime;
1335     ktime = large.QuadPart;
1336 
1337     large.u.LowPart = user_time.dwLowDateTime;
1338     large.u.HighPart = user_time.dwHighDateTime;
1339     utime = large.QuadPart;
1340 
1341     /* ktime and utime have a resolution of 100 nanoseconds */
1342     t = _PyTime_FromNanoseconds((ktime + utime) * 100);
1343     *tp = t;
1344     return 0;
1345 }
1346 
1347 #elif defined(__sun) && defined(__SVR4)
1348 #define HAVE_THREAD_TIME
1349 static int
1350 _PyTime_GetThreadTimeWithInfo(_PyTime_t *tp, _Py_clock_info_t *info)
1351 {
1352     /* bpo-35455: On Solaris, CLOCK_THREAD_CPUTIME_ID clock is not always
1353        available; use gethrvtime() to substitute this functionality. */
1354     if (info) {
1355         info->implementation = "gethrvtime()";
1356         info->resolution = 1e-9;
1357         info->monotonic = 1;
1358         info->adjustable = 0;
1359     }
1360     *tp = _PyTime_FromNanoseconds(gethrvtime());
1361     return 0;
1362 }
1363 
1364 #elif defined(HAVE_CLOCK_GETTIME) && defined(CLOCK_PROCESS_CPUTIME_ID)
1365 #define HAVE_THREAD_TIME
1366 static int
1367 _PyTime_GetThreadTimeWithInfo(_PyTime_t *tp, _Py_clock_info_t *info)
1368 {
1369     struct timespec ts;
1370     const clockid_t clk_id = CLOCK_THREAD_CPUTIME_ID;
1371     const char *function = "clock_gettime(CLOCK_THREAD_CPUTIME_ID)";
1372 
1373     if (clock_gettime(clk_id, &ts)) {
1374         PyErr_SetFromErrno(PyExc_OSError);
1375         return -1;
1376     }
1377     if (info) {
1378         struct timespec res;
1379         info->implementation = function;
1380         info->monotonic = 1;
1381         info->adjustable = 0;
1382         if (clock_getres(clk_id, &res)) {
1383             PyErr_SetFromErrno(PyExc_OSError);
1384             return -1;
1385         }
1386         info->resolution = res.tv_sec + res.tv_nsec * 1e-9;
1387     }
1388 
1389     if (_PyTime_FromTimespec(tp, &ts) < 0) {
1390         return -1;
1391     }
1392     return 0;
1393 }
1394 #endif
1395 
1396 #ifdef HAVE_THREAD_TIME
1397 static PyObject *
1398 time_thread_time(PyObject *self, PyObject *unused)
1399 {
1400     _PyTime_t t;
1401     if (_PyTime_GetThreadTimeWithInfo(&t, NULL) < 0) {
1402         return NULL;
1403     }
1404     return _PyFloat_FromPyTime(t);
1405 }
1406 
1407 PyDoc_STRVAR(thread_time_doc,
1408 "thread_time() -> float\n\
1409 \n\
1410 Thread time for profiling: sum of the kernel and user-space CPU time.");
1411 
1412 static PyObject *
1413 time_thread_time_ns(PyObject *self, PyObject *unused)
1414 {
1415     _PyTime_t t;
1416     if (_PyTime_GetThreadTimeWithInfo(&t, NULL) < 0) {
1417         return NULL;
1418     }
1419     return _PyTime_AsNanosecondsObject(t);
1420 }
1421 
1422 PyDoc_STRVAR(thread_time_ns_doc,
1423 "thread_time() -> int\n\
1424 \n\
1425 Thread time for profiling as nanoseconds:\n\
1426 sum of the kernel and user-space CPU time.");
1427 #endif
1428 
1429 
1430 static PyObject *
1431 time_get_clock_info(PyObject *self, PyObject *args)
1432 {
1433     char *name;
1434     _Py_clock_info_t info;
1435     PyObject *obj = NULL, *dict, *ns;
1436     _PyTime_t t;
1437 
1438     if (!PyArg_ParseTuple(args, "s:get_clock_info", &name)) {
1439         return NULL;
1440     }
1441 
1442 #ifdef Py_DEBUG
1443     info.implementation = NULL;
1444     info.monotonic = -1;
1445     info.adjustable = -1;
1446     info.resolution = -1.0;
1447 #else
1448     info.implementation = "";
1449     info.monotonic = 0;
1450     info.adjustable = 0;
1451     info.resolution = 1.0;
1452 #endif
1453 
1454     if (strcmp(name, "time") == 0) {
1455         if (_PyTime_GetSystemClockWithInfo(&t, &info) < 0) {
1456             return NULL;
1457         }
1458     }
1459     else if (strcmp(name, "monotonic") == 0) {
1460         if (_PyTime_GetMonotonicClockWithInfo(&t, &info) < 0) {
1461             return NULL;
1462         }
1463     }
1464     else if (strcmp(name, "perf_counter") == 0) {
1465         if (_PyTime_GetPerfCounterWithInfo(&t, &info) < 0) {
1466             return NULL;
1467         }
1468     }
1469     else if (strcmp(name, "process_time") == 0) {
1470         if (_PyTime_GetProcessTimeWithInfo(&t, &info) < 0) {
1471             return NULL;
1472         }
1473     }
1474 #ifdef HAVE_THREAD_TIME
1475     else if (strcmp(name, "thread_time") == 0) {
1476         if (_PyTime_GetThreadTimeWithInfo(&t, &info) < 0) {
1477             return NULL;
1478         }
1479     }
1480 #endif
1481     else {
1482         PyErr_SetString(PyExc_ValueError, "unknown clock");
1483         return NULL;
1484     }
1485 
1486     dict = PyDict_New();
1487     if (dict == NULL) {
1488         return NULL;
1489     }
1490 
1491     assert(info.implementation != NULL);
1492     obj = PyUnicode_FromString(info.implementation);
1493     if (obj == NULL) {
1494         goto error;
1495     }
1496     if (PyDict_SetItemString(dict, "implementation", obj) == -1) {
1497         goto error;
1498     }
1499     Py_CLEAR(obj);
1500 
1501     assert(info.monotonic != -1);
1502     obj = PyBool_FromLong(info.monotonic);
1503     if (obj == NULL) {
1504         goto error;
1505     }
1506     if (PyDict_SetItemString(dict, "monotonic", obj) == -1) {
1507         goto error;
1508     }
1509     Py_CLEAR(obj);
1510 
1511     assert(info.adjustable != -1);
1512     obj = PyBool_FromLong(info.adjustable);
1513     if (obj == NULL) {
1514         goto error;
1515     }
1516     if (PyDict_SetItemString(dict, "adjustable", obj) == -1) {
1517         goto error;
1518     }
1519     Py_CLEAR(obj);
1520 
1521     assert(info.resolution > 0.0);
1522     assert(info.resolution <= 1.0);
1523     obj = PyFloat_FromDouble(info.resolution);
1524     if (obj == NULL) {
1525         goto error;
1526     }
1527     if (PyDict_SetItemString(dict, "resolution", obj) == -1) {
1528         goto error;
1529     }
1530     Py_CLEAR(obj);
1531 
1532     ns = _PyNamespace_New(dict);
1533     Py_DECREF(dict);
1534     return ns;
1535 
1536 error:
1537     Py_DECREF(dict);
1538     Py_XDECREF(obj);
1539     return NULL;
1540 }
1541 
1542 PyDoc_STRVAR(get_clock_info_doc,
1543 "get_clock_info(name: str) -> dict\n\
1544 \n\
1545 Get information of the specified clock.");
1546 
1547 #ifndef HAVE_DECL_TZNAME
1548 static void
1549 get_zone(char *zone, int n, struct tm *p)
1550 {
1551 #ifdef HAVE_STRUCT_TM_TM_ZONE
1552     strncpy(zone, p->tm_zone ? p->tm_zone : "   ", n);
1553 #else
1554     tzset();
1555     strftime(zone, n, "%Z", p);
1556 #endif
1557 }
1558 
1559 static time_t
1560 get_gmtoff(time_t t, struct tm *p)
1561 {
1562 #ifdef HAVE_STRUCT_TM_TM_ZONE
1563     return p->tm_gmtoff;
1564 #else
1565     return timegm(p) - t;
1566 #endif
1567 }
1568 #endif // !HAVE_DECL_TZNAME
1569 
1570 static int
1571 init_timezone(PyObject *m)
1572 {
1573     assert(!PyErr_Occurred());
1574 
1575     /* This code moved from PyInit_time wholesale to allow calling it from
1576     time_tzset. In the future, some parts of it can be moved back
1577     (for platforms that don't HAVE_WORKING_TZSET, when we know what they
1578     are), and the extraneous calls to tzset(3) should be removed.
1579     I haven't done this yet, as I don't want to change this code as
1580     little as possible when introducing the time.tzset and time.tzsetwall
1581     methods. This should simply be a method of doing the following once,
1582     at the top of this function and removing the call to tzset() from
1583     time_tzset():
1584 
1585         #ifdef HAVE_TZSET
1586         tzset()
1587         #endif
1588 
1589     And I'm lazy and hate C so nyer.
1590      */
1591 #ifdef HAVE_DECL_TZNAME
1592     PyObject *otz0, *otz1;
1593     tzset();
1594     PyModule_AddIntConstant(m, "timezone", _Py_timezone);
1595 #ifdef HAVE_ALTZONE
1596     PyModule_AddIntConstant(m, "altzone", altzone);
1597 #else
1598     PyModule_AddIntConstant(m, "altzone", _Py_timezone-3600);
1599 #endif
1600     PyModule_AddIntConstant(m, "daylight", _Py_daylight);
1601 #ifdef MS_WINDOWS
1602     TIME_ZONE_INFORMATION tzinfo = {0};
1603     GetTimeZoneInformation(&tzinfo);
1604     otz0 = PyUnicode_FromWideChar(tzinfo.StandardName, -1);
1605     if (otz0 == NULL) {
1606         return -1;
1607     }
1608     otz1 = PyUnicode_FromWideChar(tzinfo.DaylightName, -1);
1609     if (otz1 == NULL) {
1610         Py_DECREF(otz0);
1611         return -1;
1612     }
1613 #else
1614     otz0 = PyUnicode_DecodeLocale(_Py_tzname[0], "surrogateescape");
1615     if (otz0 == NULL) {
1616         return -1;
1617     }
1618     otz1 = PyUnicode_DecodeLocale(_Py_tzname[1], "surrogateescape");
1619     if (otz1 == NULL) {
1620         Py_DECREF(otz0);
1621         return -1;
1622     }
1623 #endif // MS_WINDOWS
1624     PyObject *tzname_obj = Py_BuildValue("(NN)", otz0, otz1);
1625     if (tzname_obj == NULL) {
1626         return -1;
1627     }
1628     PyModule_AddObject(m, "tzname", tzname_obj);
1629 #else // !HAVE_DECL_TZNAME
1630     static const time_t YEAR = (365 * 24 + 6) * 3600;
1631     time_t t;
1632     struct tm p;
1633     time_t janzone_t, julyzone_t;
1634     char janname[10], julyname[10];
1635     t = (time((time_t *)0) / YEAR) * YEAR;
1636     _PyTime_localtime(t, &p);
1637     get_zone(janname, 9, &p);
1638     janzone_t = -get_gmtoff(t, &p);
1639     janname[9] = '\0';
1640     t += YEAR/2;
1641     _PyTime_localtime(t, &p);
1642     get_zone(julyname, 9, &p);
1643     julyzone_t = -get_gmtoff(t, &p);
1644     julyname[9] = '\0';
1645 
1646     /* Sanity check, don't check for the validity of timezones.
1647        In practice, it should be more in range -12 hours .. +14 hours. */
1648 #define MAX_TIMEZONE (48 * 3600)
1649     if (janzone_t < -MAX_TIMEZONE || janzone_t > MAX_TIMEZONE
1650         || julyzone_t < -MAX_TIMEZONE || julyzone_t > MAX_TIMEZONE)
1651     {
1652         PyErr_SetString(PyExc_RuntimeError, "invalid GMT offset");
1653         return -1;
1654     }
1655     int janzone = (int)janzone_t;
1656     int julyzone = (int)julyzone_t;
1657 
1658     PyObject *tzname_obj;
1659     if (janzone < julyzone) {
1660         /* DST is reversed in the southern hemisphere */
1661         PyModule_AddIntConstant(m, "timezone", julyzone);
1662         PyModule_AddIntConstant(m, "altzone", janzone);
1663         PyModule_AddIntConstant(m, "daylight", janzone != julyzone);
1664         tzname_obj = Py_BuildValue("(zz)", julyname, janname);
1665     } else {
1666         PyModule_AddIntConstant(m, "timezone", janzone);
1667         PyModule_AddIntConstant(m, "altzone", julyzone);
1668         PyModule_AddIntConstant(m, "daylight", janzone != julyzone);
1669         tzname_obj = Py_BuildValue("(zz)", janname, julyname);
1670     }
1671     if (tzname_obj == NULL) {
1672         return -1;
1673     }
1674     PyModule_AddObject(m, "tzname", tzname_obj);
1675 #endif // !HAVE_DECL_TZNAME
1676 
1677     if (PyErr_Occurred()) {
1678         return -1;
1679     }
1680     return 0;
1681 }
1682 
1683 
1684 static PyMethodDef time_methods[] = {
1685     {"time",            time_time, METH_NOARGS, time_doc},
1686     {"time_ns",         time_time_ns, METH_NOARGS, time_ns_doc},
1687 #ifdef HAVE_CLOCK_GETTIME
1688     {"clock_gettime",   time_clock_gettime, METH_VARARGS, clock_gettime_doc},
1689     {"clock_gettime_ns",time_clock_gettime_ns, METH_VARARGS, clock_gettime_ns_doc},
1690 #endif
1691 #ifdef HAVE_CLOCK_SETTIME
1692     {"clock_settime",   time_clock_settime, METH_VARARGS, clock_settime_doc},
1693     {"clock_settime_ns",time_clock_settime_ns, METH_VARARGS, clock_settime_ns_doc},
1694 #endif
1695 #ifdef HAVE_CLOCK_GETRES
1696     {"clock_getres",    time_clock_getres, METH_VARARGS, clock_getres_doc},
1697 #endif
1698 #ifdef HAVE_PTHREAD_GETCPUCLOCKID
1699     {"pthread_getcpuclockid", time_pthread_getcpuclockid, METH_VARARGS, pthread_getcpuclockid_doc},
1700 #endif
1701     {"sleep",           time_sleep, METH_O, sleep_doc},
1702     {"gmtime",          time_gmtime, METH_VARARGS, gmtime_doc},
1703     {"localtime",       time_localtime, METH_VARARGS, localtime_doc},
1704     {"asctime",         time_asctime, METH_VARARGS, asctime_doc},
1705     {"ctime",           time_ctime, METH_VARARGS, ctime_doc},
1706 #ifdef HAVE_MKTIME
1707     {"mktime",          time_mktime, METH_O, mktime_doc},
1708 #endif
1709 #ifdef HAVE_STRFTIME
1710     {"strftime",        time_strftime, METH_VARARGS, strftime_doc},
1711 #endif
1712     {"strptime",        time_strptime, METH_VARARGS, strptime_doc},
1713 #ifdef HAVE_WORKING_TZSET
1714     {"tzset",           time_tzset, METH_NOARGS, tzset_doc},
1715 #endif
1716     {"monotonic",       time_monotonic, METH_NOARGS, monotonic_doc},
1717     {"monotonic_ns",    time_monotonic_ns, METH_NOARGS, monotonic_ns_doc},
1718     {"process_time",    time_process_time, METH_NOARGS, process_time_doc},
1719     {"process_time_ns", time_process_time_ns, METH_NOARGS, process_time_ns_doc},
1720 #ifdef HAVE_THREAD_TIME
1721     {"thread_time",     time_thread_time, METH_NOARGS, thread_time_doc},
1722     {"thread_time_ns",  time_thread_time_ns, METH_NOARGS, thread_time_ns_doc},
1723 #endif
1724     {"perf_counter",    time_perf_counter, METH_NOARGS, perf_counter_doc},
1725     {"perf_counter_ns", time_perf_counter_ns, METH_NOARGS, perf_counter_ns_doc},
1726     {"get_clock_info",  time_get_clock_info, METH_VARARGS, get_clock_info_doc},
1727     {NULL,              NULL}           /* sentinel */
1728 };
1729 
1730 
1731 PyDoc_STRVAR(module_doc,
1732 "This module provides various functions to manipulate time values.\n\
1733 \n\
1734 There are two standard representations of time.  One is the number\n\
1735 of seconds since the Epoch, in UTC (a.k.a. GMT).  It may be an integer\n\
1736 or a floating point number (to represent fractions of seconds).\n\
1737 The Epoch is system-defined; on Unix, it is generally January 1st, 1970.\n\
1738 The actual value can be retrieved by calling gmtime(0).\n\
1739 \n\
1740 The other representation is a tuple of 9 integers giving local time.\n\
1741 The tuple items are:\n\
1742   year (including century, e.g. 1998)\n\
1743   month (1-12)\n\
1744   day (1-31)\n\
1745   hours (0-23)\n\
1746   minutes (0-59)\n\
1747   seconds (0-59)\n\
1748   weekday (0-6, Monday is 0)\n\
1749   Julian day (day in the year, 1-366)\n\
1750   DST (Daylight Savings Time) flag (-1, 0 or 1)\n\
1751 If the DST flag is 0, the time is given in the regular time zone;\n\
1752 if it is 1, the time is given in the DST time zone;\n\
1753 if it is -1, mktime() should guess based on the date and time.\n");
1754 
1755 
1756 
1757 static struct PyModuleDef timemodule = {
1758     PyModuleDef_HEAD_INIT,
1759     "time",
1760     module_doc,
1761     -1,
1762     time_methods,
1763     NULL,
1764     NULL,
1765     NULL,
1766     NULL
1767 };
1768 
1769 PyMODINIT_FUNC
1770 PyInit_time(void)
1771 {
1772     PyObject *m;
1773     m = PyModule_Create(&timemodule);
1774     if (m == NULL)
1775         return NULL;
1776 
1777     /* Set, or reset, module variables like time.timezone */
1778     if (init_timezone(m) < 0) {
1779         return NULL;
1780     }
1781 
1782 #if defined(HAVE_CLOCK_GETTIME) || defined(HAVE_CLOCK_SETTIME) || defined(HAVE_CLOCK_GETRES)
1783 
1784 #ifdef CLOCK_REALTIME
1785     PyModule_AddIntMacro(m, CLOCK_REALTIME);
1786 #endif
1787 #ifdef CLOCK_MONOTONIC
1788     PyModule_AddIntMacro(m, CLOCK_MONOTONIC);
1789 #endif
1790 #ifdef CLOCK_MONOTONIC_RAW
1791     PyModule_AddIntMacro(m, CLOCK_MONOTONIC_RAW);
1792 #endif
1793 #ifdef CLOCK_HIGHRES
1794     PyModule_AddIntMacro(m, CLOCK_HIGHRES);
1795 #endif
1796 #ifdef CLOCK_PROCESS_CPUTIME_ID
1797     PyModule_AddIntMacro(m, CLOCK_PROCESS_CPUTIME_ID);
1798 #endif
1799 #ifdef CLOCK_THREAD_CPUTIME_ID
1800     PyModule_AddIntMacro(m, CLOCK_THREAD_CPUTIME_ID);
1801 #endif
1802 #ifdef CLOCK_PROF
1803     PyModule_AddIntMacro(m, CLOCK_PROF);
1804 #endif
1805 #ifdef CLOCK_BOOTTIME
1806     PyModule_AddIntMacro(m, CLOCK_BOOTTIME);
1807 #endif
1808 #ifdef CLOCK_UPTIME
1809     PyModule_AddIntMacro(m, CLOCK_UPTIME);
1810 #endif
1811 #ifdef CLOCK_UPTIME_RAW
1812     PyModule_AddIntMacro(m, CLOCK_UPTIME_RAW);
1813 #endif
1814 
1815 #endif  /* defined(HAVE_CLOCK_GETTIME) || defined(HAVE_CLOCK_SETTIME) || defined(HAVE_CLOCK_GETRES) */
1816 
1817     if (!initialized) {
1818         if (PyStructSequence_InitType2(&StructTimeType,
1819                                        &struct_time_type_desc) < 0)
1820             return NULL;
1821     }
1822     Py_INCREF(&StructTimeType);
1823     PyModule_AddIntConstant(m, "_STRUCT_TM_ITEMS", 11);
1824     PyModule_AddObject(m, "struct_time", (PyObject*) &StructTimeType);
1825     initialized = 1;
1826 
1827 #if defined(__linux__) && !defined(__GLIBC__)
1828     struct tm tm;
1829     const time_t zero = 0;
1830     if (gmtime_r(&zero, &tm) != NULL)
1831         utc_string = tm.tm_zone;
1832 #endif
1833 
1834     if (PyErr_Occurred()) {
1835         return NULL;
1836     }
1837     return m;
1838 }
1839 
1840 /* Implement pysleep() for various platforms.
1841    When interrupted (or when another error occurs), return -1 and
1842    set an exception; else return 0. */
1843 
1844 static int
1845 pysleep(_PyTime_t secs)
1846 {
1847     _PyTime_t deadline, monotonic;
1848 #ifndef MS_WINDOWS
1849     struct timeval timeout;
1850     int err = 0;
1851 #else
1852     _PyTime_t millisecs;
1853     unsigned long ul_millis;
1854     DWORD rc;
1855     HANDLE hInterruptEvent;
1856 #endif
1857 
1858     deadline = _PyTime_GetMonotonicClock() + secs;
1859 
1860     do {
1861 #ifndef MS_WINDOWS
1862         if (_PyTime_AsTimeval(secs, &timeout, _PyTime_ROUND_CEILING) < 0)
1863             return -1;
1864 
1865         Py_BEGIN_ALLOW_THREADS
1866         err = select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &timeout);
1867         Py_END_ALLOW_THREADS
1868 
1869         if (err == 0)
1870             break;
1871 
1872         if (errno != EINTR) {
1873             PyErr_SetFromErrno(PyExc_OSError);
1874             return -1;
1875         }
1876 #else
1877         millisecs = _PyTime_AsMilliseconds(secs, _PyTime_ROUND_CEILING);
1878         if (millisecs > (double)ULONG_MAX) {
1879             PyErr_SetString(PyExc_OverflowError,
1880                             "sleep length is too large");
1881             return -1;
1882         }
1883 
1884         /* Allow sleep(0) to maintain win32 semantics, and as decreed
1885          * by Guido, only the main thread can be interrupted.
1886          */
1887         ul_millis = (unsigned long)millisecs;
1888         if (ul_millis == 0 || !_PyOS_IsMainThread()) {
1889             Py_BEGIN_ALLOW_THREADS
1890             Sleep(ul_millis);
1891             Py_END_ALLOW_THREADS
1892             break;
1893         }
1894 
1895         hInterruptEvent = _PyOS_SigintEvent();
1896         ResetEvent(hInterruptEvent);
1897 
1898         Py_BEGIN_ALLOW_THREADS
1899         rc = WaitForSingleObjectEx(hInterruptEvent, ul_millis, FALSE);
1900         Py_END_ALLOW_THREADS
1901 
1902         if (rc != WAIT_OBJECT_0)
1903             break;
1904 #endif
1905 
1906         /* sleep was interrupted by SIGINT */
1907         if (PyErr_CheckSignals())
1908             return -1;
1909 
1910         monotonic = _PyTime_GetMonotonicClock();
1911         secs = deadline - monotonic;
1912         if (secs < 0)
1913             break;
1914         /* retry with the recomputed delay */
1915     } while (1);
1916 
1917     return 0;
1918 }
1919