blob: 80eab30c95d6f034356970569cd795d613055277 [file] [log] [blame]
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001/* Time module */
2
Barry Warsaw9a2a8a81996-12-06 23:32:14 +00003#include "Python.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +00004
Guido van Rossum87ce7bb1998-06-09 16:30:31 +00005#include <ctype.h>
6
Victor Stinnerec895392012-04-29 02:41:27 +02007#ifdef HAVE_SYS_TIMES_H
8#include <sys/times.h>
9#endif
10
Thomas Wouters0e3f5912006-08-11 14:57:12 +000011#ifdef HAVE_SYS_TYPES_H
Guido van Rossumb6775db1994-08-01 11:34:53 +000012#include <sys/types.h>
Victor Stinnerec895392012-04-29 02:41:27 +020013#endif
14
15#if defined(HAVE_SYS_RESOURCE_H)
16#include <sys/resource.h>
17#endif
Guido van Rossum6d946f91992-08-14 13:49:30 +000018
Guido van Rossumb6775db1994-08-01 11:34:53 +000019#ifdef QUICKWIN
20#include <io.h>
21#endif
22
pdoxe14679c2017-10-05 00:01:56 -070023#if defined(HAVE_PTHREAD_H)
24# include <pthread.h>
25#endif
26
Batuhan Taskaya45410862020-05-16 12:39:09 +030027#if defined(_AIX)
28# include <sys/thread.h>
29#endif
30
Guido van Rossum7bf22de1997-12-02 20:34:19 +000031#if defined(__WATCOMC__) && !defined(__QNX__)
Victor Stinner62183b82020-04-15 02:04:42 +020032# include <i86.h>
Guido van Rossumbceeac81996-05-23 22:53:47 +000033#else
Victor Stinner62183b82020-04-15 02:04:42 +020034# ifdef MS_WINDOWS
35# define WIN32_LEAN_AND_MEAN
36# include <windows.h>
37# endif /* MS_WINDOWS */
Guido van Rossum7bf22de1997-12-02 20:34:19 +000038#endif /* !__WATCOMC__ || __QNX__ */
Guido van Rossum234f9421993-06-17 12:35:49 +000039
Gregory P. Smithb474e672018-12-30 17:05:36 -080040#ifdef _Py_MEMORY_SANITIZER
41# include <sanitizer/msan_interface.h>
42#endif
43
Zackery Spytz6673dec2019-02-25 16:56:44 -070044#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
Ronald Oussorene8b1c032020-11-22 11:18:40 +010054#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
Victor Stinnerc29b5852017-11-02 07:28:27 -070063#define SEC_TO_NS (1000 * 1000 * 1000)
64
Guido van Rossum234f9421993-06-17 12:35:49 +000065/* Forward declarations */
Victor Stinnercb29f012015-03-27 13:31:18 +010066static int pysleep(_PyTime_t);
Victor Stinnerec895392012-04-29 02:41:27 +020067
Victor Stinner85fdfa82012-01-27 00:38:48 +010068
Victor Stinnera997c7b2017-10-10 02:51:50 -070069static PyObject*
70_PyFloat_FromPyTime(_PyTime_t t)
71{
72 double d = _PyTime_AsSecondsDouble(t);
73 return PyFloat_FromDouble(d);
74}
75
Victor Stinnerc29b5852017-11-02 07:28:27 -070076
Victor Stinner4195b5c2012-02-08 23:03:19 +010077static PyObject *
Victor Stinnerc29b5852017-11-02 07:28:27 -070078time_time(PyObject *self, PyObject *unused)
Victor Stinner85fdfa82012-01-27 00:38:48 +010079{
Victor Stinnerc29b5852017-11-02 07:28:27 -070080 _PyTime_t t = _PyTime_GetSystemClock();
81 return _PyFloat_FromPyTime(t);
82}
83
84
85PyDoc_STRVAR(time_doc,
86"time() -> floating point number\n\
87\n\
88Return the current time in seconds since the Epoch.\n\
89Fractions of a second may be present if the system clock provides them.");
90
91static PyObject *
92time_time_ns(PyObject *self, PyObject *unused)
93{
94 _PyTime_t t = _PyTime_GetSystemClock();
95 return _PyTime_AsNanosecondsObject(t);
96}
97
98PyDoc_STRVAR(time_ns_doc,
99"time_ns() -> int\n\
100\n\
101Return 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
113static int
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 }
Victor Stinner85fdfa82012-01-27 00:38:48 +0100129 }
Victor Stinnerc29b5852017-11-02 07:28:27 -0700130
Victor Stinnerec895392012-04-29 02:41:27 +0200131 if (info) {
132 info->implementation = "clock()";
133 info->resolution = 1.0 / (double)CLOCKS_PER_SEC;
Benjamin Peterson49a69e42012-05-01 09:38:34 -0400134 info->monotonic = 1;
Victor Stinner2b89fdf2012-06-12 22:46:37 +0200135 info->adjustable = 0;
Victor Stinnerec895392012-04-29 02:41:27 +0200136 }
Victor Stinnerc29b5852017-11-02 07:28:27 -0700137
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;
Victor Stinner85fdfa82012-01-27 00:38:48 +0100147}
148#endif /* HAVE_CLOCK */
149
Victor Stinnercba9a0c2017-10-12 08:51:56 -0700150static PyObject*
151perf_counter(_Py_clock_info_t *info)
152{
Victor Stinnerbdaeb7d2017-10-16 08:44:31 -0700153 _PyTime_t t;
154 if (_PyTime_GetPerfCounterWithInfo(&t, info) < 0) {
Victor Stinnercba9a0c2017-10-12 08:51:56 -0700155 return NULL;
156 }
Victor Stinnerc29b5852017-11-02 07:28:27 -0700157 return _PyFloat_FromPyTime(t);
Victor Stinnercba9a0c2017-10-12 08:51:56 -0700158}
159
Victor Stinnere0be4232011-10-25 13:06:09 +0200160#ifdef HAVE_CLOCK_GETTIME
Ronald Oussorene8b1c032020-11-22 11:18:40 +0100161
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
Victor Stinnere0be4232011-10-25 13:06:09 +0200171static PyObject *
Victor Stinner4195b5c2012-02-08 23:03:19 +0100172time_clock_gettime(PyObject *self, PyObject *args)
Victor Stinnere0be4232011-10-25 13:06:09 +0200173{
174 int ret;
Victor Stinnere0be4232011-10-25 13:06:09 +0200175 struct timespec tp;
176
Michael Felte2926b72018-12-28 14:57:37 +0100177#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;
Victor Stinnerc29b5852017-11-02 07:28:27 -0700182 if (!PyArg_ParseTuple(args, "i:clock_gettime", &clk_id)) {
Michael Felte2926b72018-12-28 14:57:37 +0100183#endif
Victor Stinnere0be4232011-10-25 13:06:09 +0200184 return NULL;
Victor Stinnerc29b5852017-11-02 07:28:27 -0700185 }
Victor Stinnere0be4232011-10-25 13:06:09 +0200186
187 ret = clock_gettime((clockid_t)clk_id, &tp);
Antoine Pitrou2c085602012-01-18 01:41:44 +0100188 if (ret != 0) {
Victor Stinnera734af32014-07-31 13:07:17 +0200189 PyErr_SetFromErrno(PyExc_OSError);
Antoine Pitrou2c085602012-01-18 01:41:44 +0100190 return NULL;
191 }
Victor Stinner4195b5c2012-02-08 23:03:19 +0100192 return PyFloat_FromDouble(tp.tv_sec + tp.tv_nsec * 1e-9);
Victor Stinnere0be4232011-10-25 13:06:09 +0200193}
194
195PyDoc_STRVAR(clock_gettime_doc,
Victor Stinnerc29b5852017-11-02 07:28:27 -0700196"clock_gettime(clk_id) -> float\n\
Victor Stinnere0be4232011-10-25 13:06:09 +0200197\n\
198Return the time of the specified clock clk_id.");
Victor Stinnerc29b5852017-11-02 07:28:27 -0700199
200static PyObject *
201time_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
223PyDoc_STRVAR(clock_gettime_ns_doc,
224"clock_gettime_ns(clk_id) -> int\n\
225\n\
226Return the time of the specified clock clk_id as nanoseconds.");
Benjamin Peterson37098cd2016-09-13 22:55:09 -0700227#endif /* HAVE_CLOCK_GETTIME */
Victor Stinner30d79472012-04-03 00:45:07 +0200228
Benjamin Peterson37098cd2016-09-13 22:55:09 -0700229#ifdef HAVE_CLOCK_SETTIME
Victor Stinner30d79472012-04-03 00:45:07 +0200230static PyObject *
231time_clock_settime(PyObject *self, PyObject *args)
232{
Victor Stinnerb8d01692012-04-13 23:44:05 +0200233 int clk_id;
Victor Stinner30d79472012-04-03 00:45:07 +0200234 PyObject *obj;
Victor Stinnerb3b45442015-03-28 04:09:41 +0100235 _PyTime_t t;
Victor Stinner30d79472012-04-03 00:45:07 +0200236 struct timespec tp;
237 int ret;
238
239 if (!PyArg_ParseTuple(args, "iO:clock_settime", &clk_id, &obj))
240 return NULL;
241
Victor Stinner02937aa2015-03-28 05:02:39 +0100242 if (_PyTime_FromSecondsObject(&t, obj, _PyTime_ROUND_FLOOR) < 0)
Victor Stinner30d79472012-04-03 00:45:07 +0200243 return NULL;
Victor Stinnerb3b45442015-03-28 04:09:41 +0100244
245 if (_PyTime_AsTimespec(t, &tp) == -1)
246 return NULL;
Victor Stinner30d79472012-04-03 00:45:07 +0200247
248 ret = clock_settime((clockid_t)clk_id, &tp);
249 if (ret != 0) {
Victor Stinnera734af32014-07-31 13:07:17 +0200250 PyErr_SetFromErrno(PyExc_OSError);
Victor Stinner30d79472012-04-03 00:45:07 +0200251 return NULL;
252 }
253 Py_RETURN_NONE;
254}
255
256PyDoc_STRVAR(clock_settime_doc,
257"clock_settime(clk_id, time)\n\
258\n\
259Set the time of the specified clock clk_id.");
Victor Stinnerc29b5852017-11-02 07:28:27 -0700260
261static PyObject *
262time_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
289PyDoc_STRVAR(clock_settime_ns_doc,
290"clock_settime_ns(clk_id, time)\n\
291\n\
292Set the time of the specified clock clk_id with nanoseconds.");
Benjamin Peterson37098cd2016-09-13 22:55:09 -0700293#endif /* HAVE_CLOCK_SETTIME */
Victor Stinnere0be4232011-10-25 13:06:09 +0200294
Benjamin Peterson37098cd2016-09-13 22:55:09 -0700295#ifdef HAVE_CLOCK_GETRES
Victor Stinnere0be4232011-10-25 13:06:09 +0200296static PyObject *
Victor Stinner4195b5c2012-02-08 23:03:19 +0100297time_clock_getres(PyObject *self, PyObject *args)
Victor Stinnere0be4232011-10-25 13:06:09 +0200298{
299 int ret;
Victor Stinnerb8d01692012-04-13 23:44:05 +0200300 int clk_id;
Victor Stinnere0be4232011-10-25 13:06:09 +0200301 struct timespec tp;
302
Victor Stinner4195b5c2012-02-08 23:03:19 +0100303 if (!PyArg_ParseTuple(args, "i:clock_getres", &clk_id))
Victor Stinnere0be4232011-10-25 13:06:09 +0200304 return NULL;
305
306 ret = clock_getres((clockid_t)clk_id, &tp);
Antoine Pitrou2c085602012-01-18 01:41:44 +0100307 if (ret != 0) {
Victor Stinnera734af32014-07-31 13:07:17 +0200308 PyErr_SetFromErrno(PyExc_OSError);
Antoine Pitrou2c085602012-01-18 01:41:44 +0100309 return NULL;
310 }
Victor Stinner4195b5c2012-02-08 23:03:19 +0100311
312 return PyFloat_FromDouble(tp.tv_sec + tp.tv_nsec * 1e-9);
Victor Stinnere0be4232011-10-25 13:06:09 +0200313}
314
315PyDoc_STRVAR(clock_getres_doc,
Victor Stinner4195b5c2012-02-08 23:03:19 +0100316"clock_getres(clk_id) -> floating point number\n\
Victor Stinnere0be4232011-10-25 13:06:09 +0200317\n\
318Return the resolution (precision) of the specified clock clk_id.");
Ronald Oussorene8b1c032020-11-22 11:18:40 +0100319
320#ifdef __APPLE__
321#pragma clang diagnostic pop
322#endif
323
Benjamin Peterson37098cd2016-09-13 22:55:09 -0700324#endif /* HAVE_CLOCK_GETRES */
Victor Stinnere0be4232011-10-25 13:06:09 +0200325
pdoxe14679c2017-10-05 00:01:56 -0700326#ifdef HAVE_PTHREAD_GETCPUCLOCKID
327static PyObject *
328time_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 }
Gregory P. Smithb474e672018-12-30 17:05:36 -0800342#ifdef _Py_MEMORY_SANITIZER
343 __msan_unpoison(&clk_id, sizeof(clk_id));
344#endif
pdoxe14679c2017-10-05 00:01:56 -0700345 return PyLong_FromLong(clk_id);
346}
347
348PyDoc_STRVAR(pthread_getcpuclockid_doc,
349"pthread_getcpuclockid(thread_id) -> int\n\
350\n\
351Return the clk_id of a thread's CPU time clock.");
352#endif /* HAVE_PTHREAD_GETCPUCLOCKID */
353
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000354static PyObject *
Victor Stinnercb29f012015-03-27 13:31:18 +0100355time_sleep(PyObject *self, PyObject *obj)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000356{
Victor Stinnercb29f012015-03-27 13:31:18 +0100357 _PyTime_t secs;
Pablo Galindo59af94f2017-10-18 08:13:09 +0100358 if (_PyTime_FromSecondsObject(&secs, obj, _PyTime_ROUND_TIMEOUT))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000359 return NULL;
Victor Stinner7f53a502011-07-05 22:00:25 +0200360 if (secs < 0) {
361 PyErr_SetString(PyExc_ValueError,
362 "sleep length must be non-negative");
363 return NULL;
364 }
Victor Stinnercb29f012015-03-27 13:31:18 +0100365 if (pysleep(secs) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000366 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200367 Py_RETURN_NONE;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000368}
369
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000370PyDoc_STRVAR(sleep_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000371"sleep(seconds)\n\
372\n\
373Delay execution for a given number of seconds. The argument may be\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000374a floating point number for subsecond precision.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000375
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000376static PyStructSequence_Field struct_time_type_fields[] = {
Alexander Belopolsky69f3fd02010-06-05 15:04:51 +0000377 {"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"},
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400386 {"tm_zone", "abbreviation of timezone name"},
387 {"tm_gmtoff", "offset from UTC in seconds"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000388 {0}
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000389};
390
391static PyStructSequence_Desc struct_time_type_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000392 "time.struct_time",
Alexander Belopolsky69f3fd02010-06-05 15:04:51 +0000393 "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.",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000400 struct_time_type_fields,
401 9,
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000402};
Tim Peters9ad4b682002-02-13 05:14:18 +0000403
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000404static int initialized;
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000405static PyTypeObject StructTimeType;
406
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400407
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000408static PyObject *
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -0400409tmtotuple(struct tm *p
410#ifndef HAVE_STRUCT_TM_TM_ZONE
Victor Stinner0d659e52017-04-25 01:22:42 +0200411 , const char *zone, time_t gmtoff
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -0400412#endif
413)
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000414{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000415 PyObject *v = PyStructSequence_New(&StructTimeType);
416 if (v == NULL)
417 return NULL;
Tim Peters9ad4b682002-02-13 05:14:18 +0000418
Christian Heimes217cfd12007-12-02 14:31:20 +0000419#define SET(i,val) PyStructSequence_SET_ITEM(v, i, PyLong_FromLong((long) val))
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000420
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000421 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);
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400430#ifdef HAVE_STRUCT_TM_TM_ZONE
431 PyStructSequence_SET_ITEM(v, 9,
Victor Stinner7ed7aea2018-01-15 10:45:49 +0100432 PyUnicode_DecodeLocale(p->tm_zone, "surrogateescape"));
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400433 SET(10, p->tm_gmtoff);
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -0400434#else
435 PyStructSequence_SET_ITEM(v, 9,
Victor Stinner7ed7aea2018-01-15 10:45:49 +0100436 PyUnicode_DecodeLocale(zone, "surrogateescape"));
Victor Stinner0d659e52017-04-25 01:22:42 +0200437 PyStructSequence_SET_ITEM(v, 10, _PyLong_FromTime_t(gmtoff));
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400438#endif /* HAVE_STRUCT_TM_TM_ZONE */
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000439#undef SET
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000440 if (PyErr_Occurred()) {
441 Py_XDECREF(v);
442 return NULL;
443 }
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000444
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000445 return v;
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000446}
447
Fred Drakef901abd2004-08-03 17:58:55 +0000448/* 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*/
452static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +0200453parse_time_t_args(PyObject *args, const char *format, time_t *pwhen)
Fred Drakef901abd2004-08-03 17:58:55 +0000454{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000455 PyObject *ot = NULL;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100456 time_t whent;
Fred Drakef901abd2004-08-03 17:58:55 +0000457
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000458 if (!PyArg_ParseTuple(args, format, &ot))
459 return 0;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100460 if (ot == NULL || ot == Py_None) {
461 whent = time(NULL);
462 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000463 else {
Victor Stinner02937aa2015-03-28 05:02:39 +0100464 if (_PyTime_ObjectToTime_t(ot, &whent, _PyTime_ROUND_FLOOR) == -1)
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100465 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000466 }
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100467 *pwhen = whent;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000468 return 1;
Fred Drakef901abd2004-08-03 17:58:55 +0000469}
470
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000471static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000472time_gmtime(PyObject *self, PyObject *args)
Guido van Rossum234f9421993-06-17 12:35:49 +0000473{
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100474 time_t when;
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -0400475 struct tm buf;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100476
477 if (!parse_time_t_args(args, "|O:gmtime", &when))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000478 return NULL;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100479
480 errno = 0;
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -0400481 if (_PyTime_gmtime(when, &buf) != 0)
482 return NULL;
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -0400483#ifdef HAVE_STRUCT_TM_TM_ZONE
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100484 return tmtotuple(&buf);
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -0400485#else
486 return tmtotuple(&buf, "UTC", 0);
487#endif
Guido van Rossum234f9421993-06-17 12:35:49 +0000488}
489
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -0400490#ifndef HAVE_TIMEGM
491static time_t
492timegm(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
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000503PyDoc_STRVAR(gmtime_doc,
Christian Heimes9a371592007-12-28 14:08:13 +0000504"gmtime([seconds]) -> (tm_year, tm_mon, tm_mday, tm_hour, tm_min,\n\
Fred Drake193a3f62002-03-12 21:38:49 +0000505 tm_sec, tm_wday, tm_yday, tm_isdst)\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000506\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000507Convert seconds since the Epoch to a time tuple expressing UTC (a.k.a.\n\
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400508GMT). When 'seconds' is not passed in, convert the current time instead.\n\
509\n\
510If the platform supports the tm_gmtoff and tm_zone, they are available as\n\
511attributes only.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000512
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000513static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000514time_localtime(PyObject *self, PyObject *args)
Guido van Rossum234f9421993-06-17 12:35:49 +0000515{
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100516 time_t when;
517 struct tm buf;
518
519 if (!parse_time_t_args(args, "|O:localtime", &when))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000520 return NULL;
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -0400521 if (_PyTime_localtime(when, &buf) != 0)
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100522 return NULL;
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -0400523#ifdef HAVE_STRUCT_TM_TM_ZONE
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100524 return tmtotuple(&buf);
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -0400525#else
526 {
527 struct tm local = buf;
528 char zone[100];
Victor Stinner0d659e52017-04-25 01:22:42 +0200529 time_t gmtoff;
Steve Dowerc3c6f712016-12-14 11:22:05 -0800530 strftime(zone, sizeof(zone), "%Z", &buf);
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -0400531 gmtoff = timegm(&buf) - when;
532 return tmtotuple(&local, zone, gmtoff);
533 }
534#endif
Guido van Rossum234f9421993-06-17 12:35:49 +0000535}
536
Benjamin Peterson5633c4f2018-09-14 09:09:04 -0700537#if defined(__linux__) && !defined(__GLIBC__)
538static const char *utc_string = NULL;
539#endif
540
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000541PyDoc_STRVAR(localtime_doc,
Christian Heimes9a371592007-12-28 14:08:13 +0000542"localtime([seconds]) -> (tm_year,tm_mon,tm_mday,tm_hour,tm_min,\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000543 tm_sec,tm_wday,tm_yday,tm_isdst)\n\
Martin v. Löwisb3cfc1d2001-12-02 12:27:43 +0000544\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000545Convert seconds since the Epoch to a time tuple expressing local time.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000546When 'seconds' is not passed in, convert the current time instead.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000547
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000548/* Convert 9-item tuple to tm structure. Return 1 on success, set
549 * an exception and return 0 on error.
550 */
Guido van Rossum9e90a671993-06-24 11:10:19 +0000551static int
Oren Milman1d1d3e92017-08-20 18:35:36 +0300552gettmarg(PyObject *args, struct tm *p, const char *format)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000553{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000554 int y;
Guido van Rossumcfbaecc1998-08-25 14:51:12 +0000555
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000556 memset((void *) p, '\0', sizeof(struct tm));
Guido van Rossumb9081262007-08-25 03:14:09 +0000557
Alexander Belopolsky610e5442011-01-06 21:57:06 +0000558 if (!PyTuple_Check(args)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000559 PyErr_SetString(PyExc_TypeError,
560 "Tuple or struct_time argument required");
561 return 0;
562 }
Skip Montanaro41cfce92007-08-24 21:11:00 +0000563
Oren Milman1d1d3e92017-08-20 18:35:36 +0300564 if (!PyArg_ParseTuple(args, format,
Alexander Belopolsky610e5442011-01-06 21:57:06 +0000565 &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))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000568 return 0;
Gregory P. Smith76be0ff2018-08-24 18:08:50 -0700569
570 if (y < INT_MIN + 1900) {
571 PyErr_SetString(PyExc_OverflowError, "year out of range");
572 return 0;
573 }
574
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000575 p->tm_year = y - 1900;
576 p->tm_mon--;
577 p->tm_wday = (p->tm_wday + 1) % 7;
578 p->tm_yday--;
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400579#ifdef HAVE_STRUCT_TM_TM_ZONE
Dong-hee Na1b55b652020-02-17 19:09:15 +0900580 if (Py_IS_TYPE(args, &StructTimeType)) {
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400581 PyObject *item;
Victor Stinner1cdfcfc2018-11-28 15:19:51 +0100582 item = PyStructSequence_GET_ITEM(args, 9);
Benjamin Peterson5633c4f2018-09-14 09:09:04 -0700583 if (item != Py_None) {
Xiang Zhang163eca32018-10-28 23:58:42 +0800584 p->tm_zone = (char *)PyUnicode_AsUTF8(item);
Benjamin Peterson5633c4f2018-09-14 09:09:04 -0700585 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 }
Victor Stinner1cdfcfc2018-11-28 15:19:51 +0100603 item = PyStructSequence_GET_ITEM(args, 10);
Benjamin Peterson5633c4f2018-09-14 09:09:04 -0700604 if (item != Py_None) {
605 p->tm_gmtoff = PyLong_AsLong(item);
606 if (PyErr_Occurred())
607 return 0;
608 }
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400609 }
610#endif /* HAVE_STRUCT_TM_TM_ZONE */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000611 return 1;
Guido van Rossum9e90a671993-06-24 11:10:19 +0000612}
613
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000614/* 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 */
Victor Stinneref128102010-10-07 01:00:52 +0000618static int
619checktm(struct tm* buf)
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000620{
Victor Stinneref128102010-10-07 01:00:52 +0000621 /* 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,
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000643 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
Victor Stinnerc1f32ca2011-10-14 02:36:13 +0200684#ifdef MS_WINDOWS
685 /* wcsftime() doesn't format correctly time zones, see issue #10653 */
686# undef HAVE_WCSFTIME
687#endif
Alexander Belopolskycf774542012-10-02 18:39:16 -0400688#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\
706Other codes may be available on your platform. See documentation for\n\
707the C library strftime function.\n"
Victor Stinnerc1f32ca2011-10-14 02:36:13 +0200708
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000709#ifdef HAVE_STRFTIME
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000710#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
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000720static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000721time_strftime(PyObject *self, PyObject *args)
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000722{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000723 PyObject *tup = NULL;
724 struct tm buf;
725 const time_char *fmt;
Victor Stinnerb2904782010-09-29 10:34:19 +0000726#ifdef HAVE_WCSFTIME
727 wchar_t *format;
728#else
729 PyObject *format;
730#endif
Victor Stinneref128102010-10-07 01:00:52 +0000731 PyObject *format_arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000732 size_t fmtlen, buflen;
Victor Stinnerb2904782010-09-29 10:34:19 +0000733 time_char *outbuf = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000734 size_t i;
Victor Stinnerb2904782010-09-29 10:34:19 +0000735 PyObject *ret = NULL;
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000736
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000737 memset((void *) &buf, '\0', sizeof(buf));
Guido van Rossum1f41f841998-04-27 19:04:26 +0000738
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000739 /* 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 */
Victor Stinneref128102010-10-07 01:00:52 +0000742 if (!PyArg_ParseTuple(args, "U|O:strftime", &format_arg, &tup))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000743 return NULL;
Thomas Woutersfe385252001-01-19 23:16:56 +0000744
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000745 if (tup == NULL) {
746 time_t tt = time(NULL);
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -0400747 if (_PyTime_localtime(tt, &buf) != 0)
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100748 return NULL;
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000749 }
Oren Milman1d1d3e92017-08-20 18:35:36 +0300750 else if (!gettmarg(tup, &buf,
751 "iiiiiiiii;strftime(): illegal time tuple argument") ||
752 !checktm(&buf))
753 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000754 return NULL;
Oren Milman1d1d3e92017-08-20 18:35:36 +0300755 }
Guido van Rossum10b164a2001-09-25 13:59:01 +0000756
pxinwrf1464f42019-04-15 17:06:21 +0800757#if defined(_MSC_VER) || (defined(__sun) && defined(__SVR4)) || defined(_AIX) || defined(__VXWORKS__)
Victor Stinner73ea29c2011-01-08 01:56:31 +0000758 if (buf.tm_year + 1900 < 1 || 9999 < buf.tm_year + 1900) {
Victor Stinner6f0e4f92011-03-21 02:14:53 +0100759 PyErr_SetString(PyExc_ValueError,
760 "strftime() requires year in [1; 9999]");
Alexander Belopolsky0dd06f42011-01-08 01:23:02 +0000761 return NULL;
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000762 }
Victor Stinner73ea29c2011-01-08 01:56:31 +0000763#endif
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000764
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000765 /* 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;
Brett Cannond1080a32004-03-02 04:38:10 +0000772
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000773#ifdef HAVE_WCSFTIME
Victor Stinnerbeb4135b2010-10-07 01:02:42 +0000774 format = PyUnicode_AsWideCharString(format_arg, NULL);
Victor Stinnerb2904782010-09-29 10:34:19 +0000775 if (format == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000776 return NULL;
Victor Stinnerb2904782010-09-29 10:34:19 +0000777 fmt = format;
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000778#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000779 /* Convert the unicode string to an ascii one */
Victor Stinner1b579672011-12-17 05:47:23 +0100780 format = PyUnicode_EncodeLocale(format_arg, "surrogateescape");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000781 if (format == NULL)
782 return NULL;
783 fmt = PyBytes_AS_STRING(format);
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000784#endif
Amaury Forgeot d'Arcb5be6d42009-03-02 23:52:57 +0000785
Stefan Krah4aea7d32012-02-27 16:30:26 +0100786#if defined(MS_WINDOWS) && !defined(HAVE_WCSFTIME)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000787 /* check that the format string contains only valid directives */
Steve Dowere5b58952015-09-06 19:20:51 -0700788 for (outbuf = strchr(fmt, '%');
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000789 outbuf != NULL;
Victor Stinner5a3ff792011-10-16 19:08:23 +0200790 outbuf = strchr(outbuf+2, '%'))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000791 {
Steve Dowere5b58952015-09-06 19:20:51 -0700792 if (outbuf[1] == '#')
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000793 ++outbuf; /* not documented by python, */
Steve Dowere5b58952015-09-06 19:20:51 -0700794 if (outbuf[1] == '\0')
795 break;
796 if ((outbuf[1] == 'y') && buf.tm_year < 0) {
Tim Golden6e51b8f2013-11-12 12:36:54 +0000797 PyErr_SetString(PyExc_ValueError,
798 "format %y requires year >= 1900 on Windows");
799 Py_DECREF(format);
800 return NULL;
801 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000802 }
Jakub Kulík6f9bc722018-12-31 03:16:40 +0100803#elif (defined(_AIX) || (defined(__sun) && defined(__SVR4))) && defined(HAVE_WCSFTIME)
Steve Dowere5b58952015-09-06 19:20:51 -0700804 for (outbuf = wcschr(fmt, '%');
Victor Stinner55329f82013-11-17 23:39:21 +0100805 outbuf != NULL;
806 outbuf = wcschr(outbuf+2, '%'))
807 {
Steve Dowere5b58952015-09-06 19:20:51 -0700808 if (outbuf[1] == L'\0')
809 break;
Victor Stinner55329f82013-11-17 23:39:21 +0100810 /* 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");
Zackery Spytz91e6c872018-09-21 00:09:48 -0600815 PyMem_Free(format);
Victor Stinner55329f82013-11-17 23:39:21 +0100816 return NULL;
817 }
818 }
Amaury Forgeot d'Arcb5be6d42009-03-02 23:52:57 +0000819#endif
820
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000821 fmtlen = time_strlen(fmt);
Guido van Rossumc222ec21999-02-23 00:00:10 +0000822
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000823 /* 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) {
Victor Stinnerb2904782010-09-29 10:34:19 +0000829 PyErr_NoMemory();
830 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000831 }
Steve Dower57ab1cd2015-09-22 14:51:42 -0700832#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
833 errno = 0;
834#endif
Steve Dowerd9ef74e2015-05-22 15:08:34 -0700835 _Py_BEGIN_SUPPRESS_IPH
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000836 buflen = format_time(outbuf, i, fmt, &buf);
Steve Dowerd9ef74e2015-05-22 15:08:34 -0700837 _Py_END_SUPPRESS_IPH
Victor Stinner136ea492011-12-17 22:37:18 +0100838#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
Steve Dower97cded92015-09-08 19:12:51 -0700839 /* 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 }
Victor Stinner136ea492011-12-17 22:37:18 +0100845#endif
Steve Dower97cded92015-09-08 19:12:51 -0700846 if (buflen > 0 || i >= 256 * fmtlen) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000847 /* 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. */
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000852#ifdef HAVE_WCSFTIME
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000853 ret = PyUnicode_FromWideChar(outbuf, buflen);
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000854#else
Victor Stinner7ed7aea2018-01-15 10:45:49 +0100855 ret = PyUnicode_DecodeLocaleAndSize(outbuf, buflen, "surrogateescape");
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000856#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000857 PyMem_Free(outbuf);
Victor Stinnerb2904782010-09-29 10:34:19 +0000858 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000859 }
860 PyMem_Free(outbuf);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000861 }
Victor Stinnerb2904782010-09-29 10:34:19 +0000862#ifdef HAVE_WCSFTIME
863 PyMem_Free(format);
864#else
865 Py_DECREF(format);
866#endif
867 return ret;
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000868}
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000869
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000870#undef time_char
871#undef format_time
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000872PyDoc_STRVAR(strftime_doc,
Thomas Woutersfe385252001-01-19 23:16:56 +0000873"strftime(format[, tuple]) -> string\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000874\n\
875Convert a time tuple to a string according to a format specification.\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000876See the library reference manual for formatting codes. When the time tuple\n\
Alexander Belopolskycf774542012-10-02 18:39:16 -0400877is not present, current time as returned by localtime() is used.\n\
878\n" STRFTIME_FORMAT_CODES);
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000879#endif /* HAVE_STRFTIME */
880
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000881static PyObject *
882time_strptime(PyObject *self, PyObject *args)
883{
Victor Stinnerdbe28d22016-12-09 00:38:53 +0100884 PyObject *module, *func, *result;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200885 _Py_IDENTIFIER(_strptime_time);
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000886
Victor Stinnerdbe28d22016-12-09 00:38:53 +0100887 module = PyImport_ImportModuleNoBlock("_strptime");
888 if (!module)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000889 return NULL;
Victor Stinnerdbe28d22016-12-09 00:38:53 +0100890
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;
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000900}
901
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000902
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000903PyDoc_STRVAR(strptime_doc,
Brett Cannon20def8b2003-07-01 05:16:08 +0000904"strptime(string, format) -> struct_time\n\
Martin v. Löwisb3cfc1d2001-12-02 12:27:43 +0000905\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000906Parse a string to a time tuple according to a format specification.\n\
Alexander Belopolskycf774542012-10-02 18:39:16 -0400907See the library reference manual for formatting codes (same as\n\
908strftime()).\n\
909\n" STRFTIME_FORMAT_CODES);
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000910
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000911static 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 */
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200916 static const char wday_name[7][4] = {
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000917 "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
918 };
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200919 static const char mon_name[12][4] = {
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000920 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
921 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
922 };
Victor Stinner499dfcf2011-03-21 13:26:24 +0100923 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);
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000930}
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000931
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000932static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000933time_asctime(PyObject *self, PyObject *args)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000934{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000935 PyObject *tup = NULL;
936 struct tm buf;
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000937
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000938 if (!PyArg_UnpackTuple(args, "asctime", 0, 1, &tup))
939 return NULL;
940 if (tup == NULL) {
941 time_t tt = time(NULL);
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -0400942 if (_PyTime_localtime(tt, &buf) != 0)
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100943 return NULL;
Oren Milman1d1d3e92017-08-20 18:35:36 +0300944 }
945 else if (!gettmarg(tup, &buf,
946 "iiiiiiiii;asctime(): illegal time tuple argument") ||
947 !checktm(&buf))
948 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000949 return NULL;
Oren Milman1d1d3e92017-08-20 18:35:36 +0300950 }
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000951 return _asctime(&buf);
Guido van Rossum9e90a671993-06-24 11:10:19 +0000952}
953
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000954PyDoc_STRVAR(asctime_doc,
Thomas Woutersfe385252001-01-19 23:16:56 +0000955"asctime([tuple]) -> string\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000956\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000957Convert a time tuple to a string, e.g. 'Sat Jun 06 16:26:11 1998'.\n\
958When the time tuple is not present, current time as returned by localtime()\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000959is used.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000960
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000961static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000962time_ctime(PyObject *self, PyObject *args)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000963{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000964 time_t tt;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100965 struct tm buf;
966 if (!parse_time_t_args(args, "|O:ctime", &tt))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000967 return NULL;
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -0400968 if (_PyTime_localtime(tt, &buf) != 0)
Alexander Belopolsky5da468f2011-01-04 17:15:52 +0000969 return NULL;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100970 return _asctime(&buf);
Guido van Rossum9e90a671993-06-24 11:10:19 +0000971}
972
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000973PyDoc_STRVAR(ctime_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000974"ctime(seconds) -> string\n\
975\n\
976Convert a time in seconds since the Epoch to a string in local time.\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000977This is equivalent to asctime(localtime(seconds)). When the time tuple is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000978not present, current time as returned by localtime() is used.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000979
Guido van Rossum60cd8131998-03-06 17:16:21 +0000980#ifdef HAVE_MKTIME
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000981static PyObject *
Victor Stinner87094902019-04-09 19:12:26 +0200982time_mktime(PyObject *self, PyObject *tm_tuple)
Guido van Rossum234f9421993-06-17 12:35:49 +0000983{
Victor Stinner87094902019-04-09 19:12:26 +0200984 struct tm tm;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000985 time_t tt;
Michael Felte2926b72018-12-28 14:57:37 +0100986
Victor Stinner87094902019-04-09 19:12:26 +0200987 if (!gettmarg(tm_tuple, &tm,
Oren Milman1d1d3e92017-08-20 18:35:36 +0300988 "iiiiiiiii;mktime(): illegal time tuple argument"))
989 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000990 return NULL;
Oren Milman1d1d3e92017-08-20 18:35:36 +0300991 }
Victor Stinner87094902019-04-09 19:12:26 +0200992
pxinwrf1464f42019-04-15 17:06:21 +0800993#if defined(_AIX) || (defined(__VXWORKS__) && !defined(_WRS_CONFIG_LP64))
Victor Stinner87094902019-04-09 19:12:26 +0200994 /* 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
pxinwrf1464f42019-04-15 17:06:21 +0800999 for timestamp < -2^31 or timestamp > 2**31-1. VxWorks has the
1000 same issue when working in 32 bit mode. */
Victor Stinner1ac42612014-02-21 09:27:17 +01001001 PyErr_SetString(PyExc_OverflowError,
1002 "mktime argument out of range");
1003 return NULL;
1004 }
pxinwrf1464f42019-04-15 17:06:21 +08001005#endif
Victor Stinner87094902019-04-09 19:12:26 +02001006
pxinwrf1464f42019-04-15 17:06:21 +08001007#ifdef _AIX
Victor Stinner87094902019-04-09 19:12:26 +02001008 /* 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;
Michael Felte2926b72018-12-28 14:57:37 +01001018 delta_days -= (366 + (365 * 3));
1019 }
Victor Stinner1ac42612014-02-21 09:27:17 +01001020#endif
Victor Stinner87094902019-04-09 19:12:26 +02001021
1022 tm.tm_wday = -1; /* sentinel; original value ignored */
1023 tt = mktime(&tm);
1024
Alexander Belopolskyb7d40d12011-01-11 01:21:25 +00001025 /* Return value of -1 does not necessarily mean an error, but tm_wday
Ezio Melotti13925002011-03-16 11:05:33 +02001026 * cannot remain set to -1 if mktime succeeded. */
Victor Stinner93037492013-06-25 22:54:35 +02001027 if (tt == (time_t)(-1)
Victor Stinner93037492013-06-25 22:54:35 +02001028 /* Return value of -1 does not necessarily mean an error, but
1029 * tm_wday cannot remain set to -1 if mktime succeeded. */
Victor Stinner87094902019-04-09 19:12:26 +02001030 && tm.tm_wday == -1)
Victor Stinner93037492013-06-25 22:54:35 +02001031 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001032 PyErr_SetString(PyExc_OverflowError,
1033 "mktime argument out of range");
1034 return NULL;
1035 }
Victor Stinner87094902019-04-09 19:12:26 +02001036
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
Victor Stinner4195b5c2012-02-08 23:03:19 +01001047 return PyFloat_FromDouble((double)tt);
Guido van Rossum234f9421993-06-17 12:35:49 +00001048}
Guido van Rossum0ef577b1998-06-27 20:38:36 +00001049
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001050PyDoc_STRVAR(mktime_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +00001051"mktime(tuple) -> floating point number\n\
1052\n\
Alexander Belopolskyc142bba2012-06-13 22:15:26 -04001053Convert a time tuple in local time to seconds since the Epoch.\n\
1054Note that mktime(gmtime(0)) will not generally return zero for most\n\
1055time zones; instead the returned value will either be equal to that\n\
1056of the timezone or altzone attributes on the time module.");
Guido van Rossum60cd8131998-03-06 17:16:21 +00001057#endif /* HAVE_MKTIME */
Guido van Rossum234f9421993-06-17 12:35:49 +00001058
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001059#ifdef HAVE_WORKING_TZSET
Victor Stinner3bb150d2018-12-03 13:45:38 +01001060static int init_timezone(PyObject *module);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001061
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001062static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001063time_tzset(PyObject *self, PyObject *unused)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001064{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001065 PyObject* m;
Fred Drake9bb74322002-04-01 14:49:59 +00001066
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001067 m = PyImport_ImportModuleNoBlock("time");
1068 if (m == NULL) {
1069 return NULL;
1070 }
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001071
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001072 tzset();
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001073
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001074 /* Reset timezone, altzone, daylight and tzname */
Victor Stinner3bb150d2018-12-03 13:45:38 +01001075 if (init_timezone(m) < 0) {
Victor Stinner503ce5c2018-12-01 00:39:36 +01001076 return NULL;
1077 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001078 Py_DECREF(m);
Victor Stinner2ff51b82013-07-17 21:42:45 +02001079 if (PyErr_Occurred())
1080 return NULL;
Tim Peters1b6f7a92004-06-20 02:50:16 +00001081
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001082 Py_RETURN_NONE;
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001083}
1084
1085PyDoc_STRVAR(tzset_doc,
R. David Murray4d55bf92010-12-14 00:55:46 +00001086"tzset()\n\
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001087\n\
1088Initialize, or reinitialize, the local timezone to the value stored in\n\
1089os.environ['TZ']. The TZ environment variable should be specified in\n\
Neal Norwitzdc8e1942004-07-20 22:34:37 +00001090standard Unix timezone format as documented in the tzset man page\n\
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001091(eg. 'US/Eastern', 'Europe/Amsterdam'). Unknown timezones will silently\n\
1092fall back to UTC. If the TZ environment variable is not set, the local\n\
1093timezone is set to the systems best guess of wallclock time.\n\
1094Changing the TZ environment variable without calling tzset *may* change\n\
1095the local timezone used by methods such as localtime, but this behaviour\n\
1096should not be relied on.");
1097#endif /* HAVE_WORKING_TZSET */
1098
Victor Stinnerae586492014-09-02 23:18:25 +02001099static PyObject *
Victor Stinnerec895392012-04-29 02:41:27 +02001100time_monotonic(PyObject *self, PyObject *unused)
Victor Stinner071eca32012-03-15 01:17:09 +01001101{
Victor Stinnerc29b5852017-11-02 07:28:27 -07001102 _PyTime_t t = _PyTime_GetMonotonicClock();
1103 return _PyFloat_FromPyTime(t);
Victor Stinner071eca32012-03-15 01:17:09 +01001104}
1105
Victor Stinnerec895392012-04-29 02:41:27 +02001106PyDoc_STRVAR(monotonic_doc,
1107"monotonic() -> float\n\
Victor Stinner8b302012012-02-07 23:29:46 +01001108\n\
Victor Stinnerec895392012-04-29 02:41:27 +02001109Monotonic clock, cannot go backward.");
Victor Stinnerec919cc2012-03-15 00:58:32 +01001110
Victor Stinnerec895392012-04-29 02:41:27 +02001111static PyObject *
Victor Stinnerc29b5852017-11-02 07:28:27 -07001112time_monotonic_ns(PyObject *self, PyObject *unused)
1113{
1114 _PyTime_t t = _PyTime_GetMonotonicClock();
1115 return _PyTime_AsNanosecondsObject(t);
1116}
1117
1118PyDoc_STRVAR(monotonic_ns_doc,
1119"monotonic_ns() -> int\n\
1120\n\
1121Monotonic clock, cannot go backward, as nanoseconds.");
1122
1123static PyObject *
Victor Stinnerec895392012-04-29 02:41:27 +02001124time_perf_counter(PyObject *self, PyObject *unused)
1125{
1126 return perf_counter(NULL);
1127}
1128
1129PyDoc_STRVAR(perf_counter_doc,
1130"perf_counter() -> float\n\
1131\n\
1132Performance counter for benchmarking.");
1133
Victor Stinnerc29b5852017-11-02 07:28:27 -07001134static PyObject *
1135time_perf_counter_ns(PyObject *self, PyObject *unused)
1136{
1137 _PyTime_t t = _PyTime_GetPerfCounter();
1138 return _PyTime_AsNanosecondsObject(t);
1139}
1140
1141PyDoc_STRVAR(perf_counter_ns_doc,
1142"perf_counter_ns() -> int\n\
1143\n\
1144Performance counter for benchmarking as nanoseconds.");
1145
1146static int
1147_PyTime_GetProcessTimeWithInfo(_PyTime_t *tp, _Py_clock_info_t *info)
Victor Stinnerec895392012-04-29 02:41:27 +02001148{
1149#if defined(MS_WINDOWS)
1150 HANDLE process;
1151 FILETIME creation_time, exit_time, kernel_time, user_time;
1152 ULARGE_INTEGER large;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001153 _PyTime_t ktime, utime, t;
Victor Stinnerec895392012-04-29 02:41:27 +02001154 BOOL ok;
1155
1156 process = GetCurrentProcess();
Victor Stinnerc29b5852017-11-02 07:28:27 -07001157 ok = GetProcessTimes(process, &creation_time, &exit_time,
1158 &kernel_time, &user_time);
1159 if (!ok) {
1160 PyErr_SetFromWindowsErr(0);
1161 return -1;
1162 }
Victor Stinnerec895392012-04-29 02:41:27 +02001163
Victor Stinnerec895392012-04-29 02:41:27 +02001164 if (info) {
1165 info->implementation = "GetProcessTimes()";
1166 info->resolution = 1e-7;
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001167 info->monotonic = 1;
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001168 info->adjustable = 0;
Victor Stinnerec895392012-04-29 02:41:27 +02001169 }
Victor Stinnerc29b5852017-11-02 07:28:27 -07001170
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;
Victor Stinnerec895392012-04-29 02:41:27 +02001183#else
1184
Victor Stinnerc29b5852017-11-02 07:28:27 -07001185 /* clock_gettime */
Victor Stinnerec895392012-04-29 02:41:27 +02001186#if defined(HAVE_CLOCK_GETTIME) \
1187 && (defined(CLOCK_PROCESS_CPUTIME_ID) || defined(CLOCK_PROF))
Victor Stinnerc29b5852017-11-02 07:28:27 -07001188 struct timespec ts;
Ronald Oussorene8b1c032020-11-22 11:18:40 +01001189
1190 if (HAVE_CLOCK_GETTIME_RUNTIME) {
1191
Victor Stinnerec895392012-04-29 02:41:27 +02001192#ifdef CLOCK_PROF
Ronald Oussorene8b1c032020-11-22 11:18:40 +01001193 const clockid_t clk_id = CLOCK_PROF;
1194 const char *function = "clock_gettime(CLOCK_PROF)";
Victor Stinnerec895392012-04-29 02:41:27 +02001195#else
Ronald Oussorene8b1c032020-11-22 11:18:40 +01001196 const clockid_t clk_id = CLOCK_PROCESS_CPUTIME_ID;
1197 const char *function = "clock_gettime(CLOCK_PROCESS_CPUTIME_ID)";
Victor Stinnerec895392012-04-29 02:41:27 +02001198#endif
1199
Ronald Oussorene8b1c032020-11-22 11:18:40 +01001200 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) {
Victor Stinnerc29b5852017-11-02 07:28:27 -07001214 return -1;
1215 }
Ronald Oussorene8b1c032020-11-22 11:18:40 +01001216 return 0;
Victor Stinnerec895392012-04-29 02:41:27 +02001217 }
Victor Stinnerec895392012-04-29 02:41:27 +02001218 }
1219#endif
1220
Victor Stinnerc29b5852017-11-02 07:28:27 -07001221 /* getrusage(RUSAGE_SELF) */
Victor Stinnerec895392012-04-29 02:41:27 +02001222#if defined(HAVE_SYS_RESOURCE_H)
Victor Stinnerc29b5852017-11-02 07:28:27 -07001223 struct rusage ru;
1224
Victor Stinnerec895392012-04-29 02:41:27 +02001225 if (getrusage(RUSAGE_SELF, &ru) == 0) {
Victor Stinnerc29b5852017-11-02 07:28:27 -07001226 _PyTime_t utime, stime;
1227
Victor Stinnerec895392012-04-29 02:41:27 +02001228 if (info) {
1229 info->implementation = "getrusage(RUSAGE_SELF)";
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001230 info->monotonic = 1;
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001231 info->adjustable = 0;
Victor Stinnerec895392012-04-29 02:41:27 +02001232 info->resolution = 1e-6;
1233 }
Victor Stinnerc29b5852017-11-02 07:28:27 -07001234
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
vrajivk8bf5fef2019-08-26 21:13:12 -07001242 _PyTime_t total = utime + stime;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001243 *tp = total;
1244 return 0;
Victor Stinnerec895392012-04-29 02:41:27 +02001245 }
1246#endif
1247
Victor Stinnerc29b5852017-11-02 07:28:27 -07001248 /* times() */
Victor Stinnerec895392012-04-29 02:41:27 +02001249#ifdef HAVE_TIMES
Victor Stinnerc29b5852017-11-02 07:28:27 -07001250 struct tms t;
1251
Victor Stinnerec895392012-04-29 02:41:27 +02001252 if (times(&t) != (clock_t)-1) {
Victor Stinnerc29b5852017-11-02 07:28:27 -07001253 static long ticks_per_second = -1;
Victor Stinnerec895392012-04-29 02:41:27 +02001254
1255 if (ticks_per_second == -1) {
Victor Stinnerc29b5852017-11-02 07:28:27 -07001256 long freq;
Victor Stinnerec895392012-04-29 02:41:27 +02001257#if defined(HAVE_SYSCONF) && defined(_SC_CLK_TCK)
Victor Stinnerc29b5852017-11-02 07:28:27 -07001258 freq = sysconf(_SC_CLK_TCK);
1259 if (freq < 1) {
1260 freq = -1;
1261 }
Victor Stinnerec895392012-04-29 02:41:27 +02001262#elif defined(HZ)
Victor Stinnerc29b5852017-11-02 07:28:27 -07001263 freq = HZ;
Victor Stinnerec895392012-04-29 02:41:27 +02001264#else
Victor Stinnerc29b5852017-11-02 07:28:27 -07001265 freq = 60; /* magic fallback value; may be bogus */
Victor Stinnerec895392012-04-29 02:41:27 +02001266#endif
Victor Stinnerc29b5852017-11-02 07:28:27 -07001267
1268 if (freq != -1) {
1269 /* check that _PyTime_MulDiv(t, SEC_TO_NS, ticks_per_second)
1270 cannot overflow below */
Serhiy Storchakabfe4fd52018-02-09 17:31:26 +02001271#if LONG_MAX > _PyTime_MAX / SEC_TO_NS
Victor Stinnerc29b5852017-11-02 07:28:27 -07001272 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 }
Serhiy Storchakabfe4fd52018-02-09 17:31:26 +02001277#endif
Victor Stinnerc29b5852017-11-02 07:28:27 -07001278
1279 ticks_per_second = freq;
1280 }
Victor Stinnerec895392012-04-29 02:41:27 +02001281 }
1282
1283 if (ticks_per_second != -1) {
Victor Stinnerec895392012-04-29 02:41:27 +02001284 if (info) {
1285 info->implementation = "times()";
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001286 info->monotonic = 1;
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001287 info->adjustable = 0;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001288 info->resolution = 1.0 / (double)ticks_per_second;
Victor Stinnerec895392012-04-29 02:41:27 +02001289 }
Victor Stinnerc29b5852017-11-02 07:28:27 -07001290
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;
Victor Stinnerec895392012-04-29 02:41:27 +02001296 }
1297 }
1298#endif
1299
Victor Stinnerc29b5852017-11-02 07:28:27 -07001300 /* clock */
Victor Stinner53e22bf2016-07-08 17:55:01 +02001301 /* Currently, Python 3 requires clock() to build: see issue #22624 */
Victor Stinnerc29b5852017-11-02 07:28:27 -07001302 return _PyTime_GetClockWithInfo(tp, info);
Victor Stinnerec895392012-04-29 02:41:27 +02001303#endif
1304}
1305
1306static PyObject *
1307time_process_time(PyObject *self, PyObject *unused)
1308{
Victor Stinnerc29b5852017-11-02 07:28:27 -07001309 _PyTime_t t;
1310 if (_PyTime_GetProcessTimeWithInfo(&t, NULL) < 0) {
1311 return NULL;
1312 }
1313 return _PyFloat_FromPyTime(t);
Victor Stinnerec895392012-04-29 02:41:27 +02001314}
1315
1316PyDoc_STRVAR(process_time_doc,
1317"process_time() -> float\n\
1318\n\
1319Process time for profiling: sum of the kernel and user-space CPU time.");
1320
Victor Stinnerc29b5852017-11-02 07:28:27 -07001321static PyObject *
1322time_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
1331PyDoc_STRVAR(process_time_ns_doc,
1332"process_time() -> int\n\
1333\n\
1334Process time for profiling as nanoseconds:\n\
1335sum of the kernel and user-space CPU time.");
1336
Victor Stinnerec895392012-04-29 02:41:27 +02001337
Antoine Pitrou4bd41c92017-11-15 22:52:21 +01001338#if defined(MS_WINDOWS)
1339#define HAVE_THREAD_TIME
1340static 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
Batuhan Taskaya45410862020-05-16 12:39:09 +03001378#elif defined(_AIX)
1379#define HAVE_THREAD_TIME
1380static 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
Miss Skeleton (bot)72bb4c62020-11-04 05:16:28 -08001402#elif defined(__sun) && defined(__SVR4)
1403#define HAVE_THREAD_TIME
1404static 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
Antoine Pitrou4bd41c92017-11-15 22:52:21 +01001419#elif defined(HAVE_CLOCK_GETTIME) && defined(CLOCK_PROCESS_CPUTIME_ID)
1420#define HAVE_THREAD_TIME
Ronald Oussorene8b1c032020-11-22 11:18:40 +01001421
1422#if defined(__APPLE__) && defined(__has_attribute) && __has_attribute(availability)
1423static 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
Antoine Pitrou4bd41c92017-11-15 22:52:21 +01001431static 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
Ronald Oussorene8b1c032020-11-22 11:18:40 +01001462#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
Antoine Pitrou4bd41c92017-11-15 22:52:21 +01001471static PyObject *
1472time_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
1481PyDoc_STRVAR(thread_time_doc,
1482"thread_time() -> float\n\
1483\n\
1484Thread time for profiling: sum of the kernel and user-space CPU time.");
1485
1486static PyObject *
1487time_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
1496PyDoc_STRVAR(thread_time_ns_doc,
1497"thread_time() -> int\n\
1498\n\
1499Thread time for profiling as nanoseconds:\n\
1500sum of the kernel and user-space CPU time.");
Ronald Oussorene8b1c032020-11-22 11:18:40 +01001501
1502#ifdef __APPLE__
1503#pragma clang diagnostic pop
1504#endif
1505
Antoine Pitrou4bd41c92017-11-15 22:52:21 +01001506#endif
1507
1508
Victor Stinnerec895392012-04-29 02:41:27 +02001509static PyObject *
1510time_get_clock_info(PyObject *self, PyObject *args)
1511{
1512 char *name;
Victor Stinnerec895392012-04-29 02:41:27 +02001513 _Py_clock_info_t info;
Victor Stinnerbda4b882012-06-12 22:11:44 +02001514 PyObject *obj = NULL, *dict, *ns;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001515 _PyTime_t t;
Victor Stinnerec895392012-04-29 02:41:27 +02001516
Victor Stinnerc29b5852017-11-02 07:28:27 -07001517 if (!PyArg_ParseTuple(args, "s:get_clock_info", &name)) {
Victor Stinnerec895392012-04-29 02:41:27 +02001518 return NULL;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001519 }
Victor Stinnerec895392012-04-29 02:41:27 +02001520
1521#ifdef Py_DEBUG
1522 info.implementation = NULL;
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001523 info.monotonic = -1;
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001524 info.adjustable = -1;
Victor Stinnerec895392012-04-29 02:41:27 +02001525 info.resolution = -1.0;
1526#else
1527 info.implementation = "";
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001528 info.monotonic = 0;
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001529 info.adjustable = 0;
Victor Stinnerec895392012-04-29 02:41:27 +02001530 info.resolution = 1.0;
1531#endif
1532
Victor Stinnerc29b5852017-11-02 07:28:27 -07001533 if (strcmp(name, "time") == 0) {
1534 if (_PyTime_GetSystemClockWithInfo(&t, &info) < 0) {
1535 return NULL;
1536 }
1537 }
Victor Stinnerc29b5852017-11-02 07:28:27 -07001538 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 }
Antoine Pitrou4bd41c92017-11-15 22:52:21 +01001553#ifdef HAVE_THREAD_TIME
1554 else if (strcmp(name, "thread_time") == 0) {
Ronald Oussorene8b1c032020-11-22 11:18:40 +01001555
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");
Antoine Pitrou4bd41c92017-11-15 22:52:21 +01001565 return NULL;
1566 }
Ronald Oussorene8b1c032020-11-22 11:18:40 +01001567#endif
Antoine Pitrou4bd41c92017-11-15 22:52:21 +01001568 }
1569#endif
Victor Stinnerec895392012-04-29 02:41:27 +02001570 else {
1571 PyErr_SetString(PyExc_ValueError, "unknown clock");
1572 return NULL;
1573 }
Victor Stinnerec895392012-04-29 02:41:27 +02001574
Victor Stinnerbda4b882012-06-12 22:11:44 +02001575 dict = PyDict_New();
Victor Stinnerc29b5852017-11-02 07:28:27 -07001576 if (dict == NULL) {
Victor Stinnerec895392012-04-29 02:41:27 +02001577 return NULL;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001578 }
Victor Stinnerec895392012-04-29 02:41:27 +02001579
1580 assert(info.implementation != NULL);
1581 obj = PyUnicode_FromString(info.implementation);
Victor Stinnerc29b5852017-11-02 07:28:27 -07001582 if (obj == NULL) {
Victor Stinnerec895392012-04-29 02:41:27 +02001583 goto error;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001584 }
1585 if (PyDict_SetItemString(dict, "implementation", obj) == -1) {
Victor Stinnerbda4b882012-06-12 22:11:44 +02001586 goto error;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001587 }
Victor Stinnerbda4b882012-06-12 22:11:44 +02001588 Py_CLEAR(obj);
Victor Stinnerec895392012-04-29 02:41:27 +02001589
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001590 assert(info.monotonic != -1);
1591 obj = PyBool_FromLong(info.monotonic);
Victor Stinnerc29b5852017-11-02 07:28:27 -07001592 if (obj == NULL) {
Victor Stinnerec895392012-04-29 02:41:27 +02001593 goto error;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001594 }
1595 if (PyDict_SetItemString(dict, "monotonic", obj) == -1) {
Victor Stinnerbda4b882012-06-12 22:11:44 +02001596 goto error;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001597 }
Victor Stinnerbda4b882012-06-12 22:11:44 +02001598 Py_CLEAR(obj);
Victor Stinnerec895392012-04-29 02:41:27 +02001599
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001600 assert(info.adjustable != -1);
1601 obj = PyBool_FromLong(info.adjustable);
Victor Stinnerc29b5852017-11-02 07:28:27 -07001602 if (obj == NULL) {
Victor Stinnerec895392012-04-29 02:41:27 +02001603 goto error;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001604 }
1605 if (PyDict_SetItemString(dict, "adjustable", obj) == -1) {
Victor Stinnerbda4b882012-06-12 22:11:44 +02001606 goto error;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001607 }
Victor Stinnerbda4b882012-06-12 22:11:44 +02001608 Py_CLEAR(obj);
Victor Stinnerec895392012-04-29 02:41:27 +02001609
1610 assert(info.resolution > 0.0);
1611 assert(info.resolution <= 1.0);
1612 obj = PyFloat_FromDouble(info.resolution);
Victor Stinnerc29b5852017-11-02 07:28:27 -07001613 if (obj == NULL) {
Victor Stinnerec895392012-04-29 02:41:27 +02001614 goto error;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001615 }
1616 if (PyDict_SetItemString(dict, "resolution", obj) == -1) {
Victor Stinnerbda4b882012-06-12 22:11:44 +02001617 goto error;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001618 }
Victor Stinnerbda4b882012-06-12 22:11:44 +02001619 Py_CLEAR(obj);
Victor Stinnerec895392012-04-29 02:41:27 +02001620
Victor Stinnerbda4b882012-06-12 22:11:44 +02001621 ns = _PyNamespace_New(dict);
1622 Py_DECREF(dict);
1623 return ns;
Victor Stinnerec895392012-04-29 02:41:27 +02001624
1625error:
Victor Stinnerbda4b882012-06-12 22:11:44 +02001626 Py_DECREF(dict);
1627 Py_XDECREF(obj);
Victor Stinnerec895392012-04-29 02:41:27 +02001628 return NULL;
1629}
1630
1631PyDoc_STRVAR(get_clock_info_doc,
1632"get_clock_info(name: str) -> dict\n\
1633\n\
1634Get information of the specified clock.");
Victor Stinner8b302012012-02-07 23:29:46 +01001635
Benjamin Petersonc510c6b2018-09-20 19:52:18 -07001636#ifndef HAVE_DECL_TZNAME
Victor Stinner1fb399b2018-09-17 13:56:17 -07001637static void
1638get_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
Victor Stinner503ce5c2018-12-01 00:39:36 +01001648static time_t
Victor Stinner1fb399b2018-09-17 13:56:17 -07001649get_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}
Benjamin Petersonc510c6b2018-09-20 19:52:18 -07001657#endif // !HAVE_DECL_TZNAME
Victor Stinner1fb399b2018-09-17 13:56:17 -07001658
Victor Stinner503ce5c2018-12-01 00:39:36 +01001659static int
Victor Stinner3bb150d2018-12-03 13:45:38 +01001660init_timezone(PyObject *m)
Victor Stinner503ce5c2018-12-01 00:39:36 +01001661{
1662 assert(!PyErr_Occurred());
1663
Martin v. Löwis1a214512008-06-11 05:26:20 +00001664 /* This code moved from PyInit_time wholesale to allow calling it from
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001665 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():
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001673
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001674 #ifdef HAVE_TZSET
1675 tzset()
1676 #endif
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001677
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001678 And I'm lazy and hate C so nyer.
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001679 */
Benjamin Petersonc510c6b2018-09-20 19:52:18 -07001680#ifdef HAVE_DECL_TZNAME
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001681 PyObject *otz0, *otz1;
1682 tzset();
Zackery Spytz6673dec2019-02-25 16:56:44 -07001683 PyModule_AddIntConstant(m, "timezone", _Py_timezone);
Guido van Rossumb6775db1994-08-01 11:34:53 +00001684#ifdef HAVE_ALTZONE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001685 PyModule_AddIntConstant(m, "altzone", altzone);
Guido van Rossumb6775db1994-08-01 11:34:53 +00001686#else
Zackery Spytz6673dec2019-02-25 16:56:44 -07001687 PyModule_AddIntConstant(m, "altzone", _Py_timezone-3600);
Guido van Rossumb6775db1994-08-01 11:34:53 +00001688#endif
Zackery Spytz6673dec2019-02-25 16:56:44 -07001689 PyModule_AddIntConstant(m, "daylight", _Py_daylight);
Paul Monsonb4c7def2019-06-12 16:13:27 -07001690#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
Zackery Spytz6673dec2019-02-25 16:56:44 -07001703 otz0 = PyUnicode_DecodeLocale(_Py_tzname[0], "surrogateescape");
Benjamin Petersonc510c6b2018-09-20 19:52:18 -07001704 if (otz0 == NULL) {
Victor Stinnerab661492018-12-03 12:02:43 +01001705 return -1;
Victor Stinner1fb399b2018-09-17 13:56:17 -07001706 }
Zackery Spytz6673dec2019-02-25 16:56:44 -07001707 otz1 = PyUnicode_DecodeLocale(_Py_tzname[1], "surrogateescape");
Benjamin Petersonc510c6b2018-09-20 19:52:18 -07001708 if (otz1 == NULL) {
1709 Py_DECREF(otz0);
Victor Stinnerab661492018-12-03 12:02:43 +01001710 return -1;
Benjamin Petersonc510c6b2018-09-20 19:52:18 -07001711 }
Paul Monsonb4c7def2019-06-12 16:13:27 -07001712#endif // MS_WINDOWS
Benjamin Petersonc510c6b2018-09-20 19:52:18 -07001713 PyObject *tzname_obj = Py_BuildValue("(NN)", otz0, otz1);
Victor Stinnerab661492018-12-03 12:02:43 +01001714 if (tzname_obj == NULL) {
1715 return -1;
1716 }
Benjamin Petersonc510c6b2018-09-20 19:52:18 -07001717 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;
Victor Stinner503ce5c2018-12-01 00:39:36 +01001722 time_t janzone_t, julyzone_t;
Benjamin Petersonc510c6b2018-09-20 19:52:18 -07001723 char janname[10], julyname[10];
1724 t = (time((time_t *)0) / YEAR) * YEAR;
1725 _PyTime_localtime(t, &p);
1726 get_zone(janname, 9, &p);
Victor Stinner503ce5c2018-12-01 00:39:36 +01001727 janzone_t = -get_gmtoff(t, &p);
Benjamin Petersonc510c6b2018-09-20 19:52:18 -07001728 janname[9] = '\0';
1729 t += YEAR/2;
1730 _PyTime_localtime(t, &p);
1731 get_zone(julyname, 9, &p);
Victor Stinner503ce5c2018-12-01 00:39:36 +01001732 julyzone_t = -get_gmtoff(t, &p);
Benjamin Petersonc510c6b2018-09-20 19:52:18 -07001733 julyname[9] = '\0';
1734
Victor Stinner503ce5c2018-12-01 00:39:36 +01001735 /* 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
Benjamin Petersonc510c6b2018-09-20 19:52:18 -07001747 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 }
Victor Stinner503ce5c2018-12-01 00:39:36 +01001760 if (tzname_obj == NULL) {
1761 return -1;
1762 }
Benjamin Petersonc510c6b2018-09-20 19:52:18 -07001763 PyModule_AddObject(m, "tzname", tzname_obj);
1764#endif // !HAVE_DECL_TZNAME
Victor Stinner503ce5c2018-12-01 00:39:36 +01001765
1766 if (PyErr_Occurred()) {
1767 return -1;
1768 }
1769 return 0;
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001770}
1771
1772
1773static PyMethodDef time_methods[] = {
Victor Stinner4195b5c2012-02-08 23:03:19 +01001774 {"time", time_time, METH_NOARGS, time_doc},
Victor Stinnerc29b5852017-11-02 07:28:27 -07001775 {"time_ns", time_time_ns, METH_NOARGS, time_ns_doc},
Victor Stinnere0be4232011-10-25 13:06:09 +02001776#ifdef HAVE_CLOCK_GETTIME
Victor Stinner4195b5c2012-02-08 23:03:19 +01001777 {"clock_gettime", time_clock_gettime, METH_VARARGS, clock_gettime_doc},
Victor Stinnerc29b5852017-11-02 07:28:27 -07001778 {"clock_gettime_ns",time_clock_gettime_ns, METH_VARARGS, clock_gettime_ns_doc},
Benjamin Peterson37098cd2016-09-13 22:55:09 -07001779#endif
1780#ifdef HAVE_CLOCK_SETTIME
Victor Stinner30d79472012-04-03 00:45:07 +02001781 {"clock_settime", time_clock_settime, METH_VARARGS, clock_settime_doc},
Victor Stinnerc29b5852017-11-02 07:28:27 -07001782 {"clock_settime_ns",time_clock_settime_ns, METH_VARARGS, clock_settime_ns_doc},
Benjamin Peterson37098cd2016-09-13 22:55:09 -07001783#endif
1784#ifdef HAVE_CLOCK_GETRES
Victor Stinner4195b5c2012-02-08 23:03:19 +01001785 {"clock_getres", time_clock_getres, METH_VARARGS, clock_getres_doc},
Victor Stinnere0be4232011-10-25 13:06:09 +02001786#endif
pdoxe14679c2017-10-05 00:01:56 -07001787#ifdef HAVE_PTHREAD_GETCPUCLOCKID
1788 {"pthread_getcpuclockid", time_pthread_getcpuclockid, METH_VARARGS, pthread_getcpuclockid_doc},
1789#endif
Victor Stinnercb29f012015-03-27 13:31:18 +01001790 {"sleep", time_sleep, METH_O, sleep_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001791 {"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},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001795#ifdef HAVE_MKTIME
Victor Stinner4195b5c2012-02-08 23:03:19 +01001796 {"mktime", time_mktime, METH_O, mktime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001797#endif
1798#ifdef HAVE_STRFTIME
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001799 {"strftime", time_strftime, METH_VARARGS, strftime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001800#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001801 {"strptime", time_strptime, METH_VARARGS, strptime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001802#ifdef HAVE_WORKING_TZSET
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001803 {"tzset", time_tzset, METH_NOARGS, tzset_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001804#endif
Victor Stinnerec895392012-04-29 02:41:27 +02001805 {"monotonic", time_monotonic, METH_NOARGS, monotonic_doc},
Victor Stinnerc29b5852017-11-02 07:28:27 -07001806 {"monotonic_ns", time_monotonic_ns, METH_NOARGS, monotonic_ns_doc},
Victor Stinnerec895392012-04-29 02:41:27 +02001807 {"process_time", time_process_time, METH_NOARGS, process_time_doc},
Victor Stinnerc29b5852017-11-02 07:28:27 -07001808 {"process_time_ns", time_process_time_ns, METH_NOARGS, process_time_ns_doc},
Antoine Pitrou4bd41c92017-11-15 22:52:21 +01001809#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
Victor Stinnerec895392012-04-29 02:41:27 +02001813 {"perf_counter", time_perf_counter, METH_NOARGS, perf_counter_doc},
Victor Stinnerc29b5852017-11-02 07:28:27 -07001814 {"perf_counter_ns", time_perf_counter_ns, METH_NOARGS, perf_counter_ns_doc},
Victor Stinnerec895392012-04-29 02:41:27 +02001815 {"get_clock_info", time_get_clock_info, METH_VARARGS, get_clock_info_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001816 {NULL, NULL} /* sentinel */
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001817};
1818
1819
1820PyDoc_STRVAR(module_doc,
1821"This module provides various functions to manipulate time values.\n\
1822\n\
1823There are two standard representations of time. One is the number\n\
1824of seconds since the Epoch, in UTC (a.k.a. GMT). It may be an integer\n\
1825or a floating point number (to represent fractions of seconds).\n\
1826The Epoch is system-defined; on Unix, it is generally January 1st, 1970.\n\
1827The actual value can be retrieved by calling gmtime(0).\n\
1828\n\
1829The other representation is a tuple of 9 integers giving local time.\n\
1830The tuple items are:\n\
Alexander Belopolsky03163ac2011-05-02 12:20:52 -04001831 year (including century, e.g. 1998)\n\
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001832 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\
1840If the DST flag is 0, the time is given in the regular time zone;\n\
1841if it is 1, the time is given in the DST time zone;\n\
Cheryl Sabella703ff382017-10-11 09:29:14 -04001842if it is -1, mktime() should guess based on the date and time.\n");
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001843
1844
Paulo Henrique Silvabd409bb2020-03-23 15:58:23 -03001845static int
1846time_exec(PyObject *module)
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001847{
Ronald Oussorene8b1c032020-11-22 11:18:40 +01001848#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
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001888 /* Set, or reset, module variables like time.timezone */
Paulo Henrique Silvabd409bb2020-03-23 15:58:23 -03001889 if (init_timezone(module) < 0) {
1890 return -1;
Victor Stinner503ce5c2018-12-01 00:39:36 +01001891 }
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001892
Max Bélanger94451182018-10-20 17:07:54 -07001893#if defined(HAVE_CLOCK_GETTIME) || defined(HAVE_CLOCK_SETTIME) || defined(HAVE_CLOCK_GETRES)
Ronald Oussorene8b1c032020-11-22 11:18:40 +01001894 if (HAVE_CLOCK_GETTIME_RUNTIME) {
Max Bélanger94451182018-10-20 17:07:54 -07001895
Benjamin Peterson37098cd2016-09-13 22:55:09 -07001896#ifdef CLOCK_REALTIME
Ronald Oussorene8b1c032020-11-22 11:18:40 +01001897 if (PyModule_AddIntMacro(module, CLOCK_REALTIME) < 0) {
1898 return -1;
1899 }
Benjamin Peterson37098cd2016-09-13 22:55:09 -07001900#endif
Ronald Oussorene8b1c032020-11-22 11:18:40 +01001901
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -04001902#ifdef CLOCK_MONOTONIC
Ronald Oussorene8b1c032020-11-22 11:18:40 +01001903
1904 if (PyModule_AddIntMacro(module, CLOCK_MONOTONIC) < 0) {
1905 return -1;
1906 }
1907
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -04001908#endif
1909#ifdef CLOCK_MONOTONIC_RAW
Ronald Oussorene8b1c032020-11-22 11:18:40 +01001910 if (PyModule_AddIntMacro(module, CLOCK_MONOTONIC_RAW) < 0) {
1911 return -1;
1912 }
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -04001913#endif
Ronald Oussorene8b1c032020-11-22 11:18:40 +01001914
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -04001915#ifdef CLOCK_HIGHRES
Ronald Oussorene8b1c032020-11-22 11:18:40 +01001916 if (PyModule_AddIntMacro(module, CLOCK_HIGHRES) < 0) {
1917 return -1;
1918 }
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -04001919#endif
1920#ifdef CLOCK_PROCESS_CPUTIME_ID
Ronald Oussorene8b1c032020-11-22 11:18:40 +01001921 if (PyModule_AddIntMacro(module, CLOCK_PROCESS_CPUTIME_ID) < 0) {
1922 return -1;
1923 }
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -04001924#endif
Ronald Oussorene8b1c032020-11-22 11:18:40 +01001925
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -04001926#ifdef CLOCK_THREAD_CPUTIME_ID
Ronald Oussorene8b1c032020-11-22 11:18:40 +01001927 if (PyModule_AddIntMacro(module, CLOCK_THREAD_CPUTIME_ID) < 0) {
1928 return -1;
1929 }
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -04001930#endif
Victor Stinnera64ce972017-11-02 04:19:19 -07001931#ifdef CLOCK_PROF
Ronald Oussorene8b1c032020-11-22 11:18:40 +01001932 if (PyModule_AddIntMacro(module, CLOCK_PROF) < 0) {
1933 return -1;
1934 }
Victor Stinnera64ce972017-11-02 04:19:19 -07001935#endif
1936#ifdef CLOCK_BOOTTIME
Ronald Oussorene8b1c032020-11-22 11:18:40 +01001937 if (PyModule_AddIntMacro(module, CLOCK_BOOTTIME) < 0) {
1938 return -1;
1939 }
Victor Stinnera64ce972017-11-02 04:19:19 -07001940#endif
Russell Owen60000872020-03-23 20:41:40 -07001941#ifdef CLOCK_TAI
Ronald Oussorene8b1c032020-11-22 11:18:40 +01001942 if (PyModule_AddIntMacro(module, CLOCK_TAI) < 0) {
1943 return -1;
1944 }
Russell Owen60000872020-03-23 20:41:40 -07001945#endif
Victor Stinnera64ce972017-11-02 04:19:19 -07001946#ifdef CLOCK_UPTIME
Ronald Oussorene8b1c032020-11-22 11:18:40 +01001947 if (PyModule_AddIntMacro(module, CLOCK_UPTIME) < 0) {
1948 return -1;
1949 }
Victor Stinnera64ce972017-11-02 04:19:19 -07001950#endif
Joannah Nanjekye572168a2019-01-10 19:56:38 +03001951#ifdef CLOCK_UPTIME_RAW
Ronald Oussorene8b1c032020-11-22 11:18:40 +01001952
1953 if (PyModule_AddIntMacro(module, CLOCK_UPTIME_RAW) < 0) {
1954 return -1;
1955 }
Joannah Nanjekye572168a2019-01-10 19:56:38 +03001956#endif
Ronald Oussorene8b1c032020-11-22 11:18:40 +01001957 }
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -04001958
Max Bélanger94451182018-10-20 17:07:54 -07001959#endif /* defined(HAVE_CLOCK_GETTIME) || defined(HAVE_CLOCK_SETTIME) || defined(HAVE_CLOCK_GETRES) */
1960
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001961 if (!initialized) {
Victor Stinner1c8f0592013-07-22 22:24:54 +02001962 if (PyStructSequence_InitType2(&StructTimeType,
Hai Shi196f1eb2020-03-12 00:56:08 +08001963 &struct_time_type_desc) < 0) {
Paulo Henrique Silvabd409bb2020-03-23 15:58:23 -03001964 return -1;
Hai Shi196f1eb2020-03-12 00:56:08 +08001965 }
1966 }
Paulo Henrique Silvabd409bb2020-03-23 15:58:23 -03001967 if (PyModule_AddIntConstant(module, "_STRUCT_TM_ITEMS", 11)) {
1968 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001969 }
1970 Py_INCREF(&StructTimeType);
Paulo Henrique Silvabd409bb2020-03-23 15:58:23 -03001971 if (PyModule_AddObject(module, "struct_time", (PyObject*) &StructTimeType)) {
Hai Shi196f1eb2020-03-12 00:56:08 +08001972 Py_DECREF(&StructTimeType);
Paulo Henrique Silvabd409bb2020-03-23 15:58:23 -03001973 return -1;
Hai Shi196f1eb2020-03-12 00:56:08 +08001974 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001975 initialized = 1;
Benjamin Peterson5633c4f2018-09-14 09:09:04 -07001976
1977#if defined(__linux__) && !defined(__GLIBC__)
1978 struct tm tm;
Benjamin Petersonb93062b2018-09-14 10:39:13 -07001979 const time_t zero = 0;
1980 if (gmtime_r(&zero, &tm) != NULL)
Benjamin Peterson5633c4f2018-09-14 09:09:04 -07001981 utc_string = tm.tm_zone;
1982#endif
1983
Paulo Henrique Silvabd409bb2020-03-23 15:58:23 -03001984 return 0;
1985}
Hai Shi196f1eb2020-03-12 00:56:08 +08001986
Paulo Henrique Silvabd409bb2020-03-23 15:58:23 -03001987static struct PyModuleDef_Slot time_slots[] = {
1988 {Py_mod_exec, time_exec},
1989 {0, NULL}
1990};
1991
1992static 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
2004PyMODINIT_FUNC
2005PyInit_time(void)
2006{
2007 return PyModuleDef_Init(&timemodule);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002008}
2009
Victor Stinnercb29f012015-03-27 13:31:18 +01002010/* Implement pysleep() for various platforms.
Guido van Rossumb6775db1994-08-01 11:34:53 +00002011 When interrupted (or when another error occurs), return -1 and
2012 set an exception; else return 0. */
2013
2014static int
Victor Stinnercb29f012015-03-27 13:31:18 +01002015pysleep(_PyTime_t secs)
Guido van Rossum426035c1991-02-19 12:27:35 +00002016{
Victor Stinnercb29f012015-03-27 13:31:18 +01002017 _PyTime_t deadline, monotonic;
Victor Stinner79d68f92015-03-19 21:54:09 +01002018#ifndef MS_WINDOWS
2019 struct timeval timeout;
Victor Stinner79d68f92015-03-19 21:54:09 +01002020 int err = 0;
2021#else
Victor Stinnercb29f012015-03-27 13:31:18 +01002022 _PyTime_t millisecs;
Victor Stinner79d68f92015-03-19 21:54:09 +01002023 unsigned long ul_millis;
2024 DWORD rc;
2025 HANDLE hInterruptEvent;
Victor Stinner0c2fd892015-03-17 10:49:17 +01002026#endif
Victor Stinner79d68f92015-03-19 21:54:09 +01002027
Victor Stinnercb29f012015-03-27 13:31:18 +01002028 deadline = _PyTime_GetMonotonicClock() + secs;
Victor Stinner79d68f92015-03-19 21:54:09 +01002029
2030 do {
2031#ifndef MS_WINDOWS
Victor Stinner869e1772015-03-30 03:49:14 +02002032 if (_PyTime_AsTimeval(secs, &timeout, _PyTime_ROUND_CEILING) < 0)
Victor Stinnercb29f012015-03-27 13:31:18 +01002033 return -1;
Victor Stinner79d68f92015-03-19 21:54:09 +01002034
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) {
Victor Stinner0c2fd892015-03-17 10:49:17 +01002043 PyErr_SetFromErrno(PyExc_OSError);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002044 return -1;
2045 }
Victor Stinner79d68f92015-03-19 21:54:09 +01002046#else
Victor Stinner869e1772015-03-30 03:49:14 +02002047 millisecs = _PyTime_AsMilliseconds(secs, _PyTime_ROUND_CEILING);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002048 if (millisecs > (double)ULONG_MAX) {
2049 PyErr_SetString(PyExc_OverflowError,
2050 "sleep length is too large");
2051 return -1;
2052 }
Victor Stinner79d68f92015-03-19 21:54:09 +01002053
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002054 /* 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;
Victor Stinner79d68f92015-03-19 21:54:09 +01002058 if (ul_millis == 0 || !_PyOS_IsMainThread()) {
2059 Py_BEGIN_ALLOW_THREADS
Victor Stinner0eac1302015-03-20 03:06:12 +01002060 Sleep(ul_millis);
Victor Stinner79d68f92015-03-19 21:54:09 +01002061 Py_END_ALLOW_THREADS
2062 break;
Victor Stinner945c82e2015-03-12 16:19:01 +01002063 }
Victor Stinner79d68f92015-03-19 21:54:09 +01002064
2065 hInterruptEvent = _PyOS_SigintEvent();
2066 ResetEvent(hInterruptEvent);
2067
2068 Py_BEGIN_ALLOW_THREADS
2069 rc = WaitForSingleObjectEx(hInterruptEvent, ul_millis, FALSE);
Victor Stinner0c2fd892015-03-17 10:49:17 +01002070 Py_END_ALLOW_THREADS
Victor Stinner79d68f92015-03-19 21:54:09 +01002071
2072 if (rc != WAIT_OBJECT_0)
2073 break;
Victor Stinner945c82e2015-03-12 16:19:01 +01002074#endif
Victor Stinner0c2fd892015-03-17 10:49:17 +01002075
Victor Stinner79d68f92015-03-19 21:54:09 +01002076 /* sleep was interrupted by SIGINT */
2077 if (PyErr_CheckSignals())
2078 return -1;
2079
Victor Stinnercb29f012015-03-27 13:31:18 +01002080 monotonic = _PyTime_GetMonotonicClock();
2081 secs = deadline - monotonic;
Victor Stinner6aa446c2015-03-30 21:33:51 +02002082 if (secs < 0)
Victor Stinner79d68f92015-03-19 21:54:09 +01002083 break;
2084 /* retry with the recomputed delay */
2085 } while (1);
2086
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002087 return 0;
Guido van Rossum80c9d881991-04-16 08:47:51 +00002088}