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