blob: 4caacc3b64d7c87a575002b1a0cb220afec73f01 [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
Victor Stinnerae6cd7c2020-11-16 16:08:05 +010054#if defined(__APPLE__ ) && defined(__has_builtin)
Ronald Oussoren41761932020-11-08 10:05:27 +010055# 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 Stinnerae6cd7c2020-11-16 16:08:05 +010077static int
78get_system_time(_PyTime_t *t)
79{
80 // Avoid _PyTime_GetSystemClock() which silently ignores errors.
81 return _PyTime_GetSystemClockWithInfo(t, NULL);
82}
83
84
Victor Stinner4195b5c2012-02-08 23:03:19 +010085static PyObject *
Victor Stinnerc29b5852017-11-02 07:28:27 -070086time_time(PyObject *self, PyObject *unused)
Victor Stinner85fdfa82012-01-27 00:38:48 +010087{
Victor Stinnerae6cd7c2020-11-16 16:08:05 +010088 _PyTime_t t;
89 if (get_system_time(&t) < 0) {
90 return NULL;
91 }
Victor Stinnerc29b5852017-11-02 07:28:27 -070092 return _PyFloat_FromPyTime(t);
93}
94
95
96PyDoc_STRVAR(time_doc,
97"time() -> floating point number\n\
98\n\
99Return the current time in seconds since the Epoch.\n\
100Fractions of a second may be present if the system clock provides them.");
101
102static PyObject *
103time_time_ns(PyObject *self, PyObject *unused)
104{
Victor Stinnerae6cd7c2020-11-16 16:08:05 +0100105 _PyTime_t t;
106 if (get_system_time(&t) < 0) {
107 return NULL;
108 }
Victor Stinnerc29b5852017-11-02 07:28:27 -0700109 return _PyTime_AsNanosecondsObject(t);
110}
111
112PyDoc_STRVAR(time_ns_doc,
113"time_ns() -> int\n\
114\n\
115Return the current time in nanoseconds since the Epoch.");
116
117#if defined(HAVE_CLOCK)
118
119#ifndef CLOCKS_PER_SEC
120# ifdef CLK_TCK
121# define CLOCKS_PER_SEC CLK_TCK
122# else
123# define CLOCKS_PER_SEC 1000000
124# endif
125#endif
126
127static int
128_PyTime_GetClockWithInfo(_PyTime_t *tp, _Py_clock_info_t *info)
129{
130 static int initialized = 0;
131 clock_t ticks;
132
133 if (!initialized) {
134 initialized = 1;
135
136 /* must sure that _PyTime_MulDiv(ticks, SEC_TO_NS, CLOCKS_PER_SEC)
137 above cannot overflow */
138 if ((_PyTime_t)CLOCKS_PER_SEC > _PyTime_MAX / SEC_TO_NS) {
139 PyErr_SetString(PyExc_OverflowError,
140 "CLOCKS_PER_SEC is too large");
141 return -1;
142 }
Victor Stinner85fdfa82012-01-27 00:38:48 +0100143 }
Victor Stinnerc29b5852017-11-02 07:28:27 -0700144
Victor Stinnerec895392012-04-29 02:41:27 +0200145 if (info) {
146 info->implementation = "clock()";
147 info->resolution = 1.0 / (double)CLOCKS_PER_SEC;
Benjamin Peterson49a69e42012-05-01 09:38:34 -0400148 info->monotonic = 1;
Victor Stinner2b89fdf2012-06-12 22:46:37 +0200149 info->adjustable = 0;
Victor Stinnerec895392012-04-29 02:41:27 +0200150 }
Victor Stinnerc29b5852017-11-02 07:28:27 -0700151
152 ticks = clock();
153 if (ticks == (clock_t)-1) {
154 PyErr_SetString(PyExc_RuntimeError,
155 "the processor time used is not available "
156 "or its value cannot be represented");
157 return -1;
158 }
159 *tp = _PyTime_MulDiv(ticks, SEC_TO_NS, (_PyTime_t)CLOCKS_PER_SEC);
160 return 0;
Victor Stinner85fdfa82012-01-27 00:38:48 +0100161}
162#endif /* HAVE_CLOCK */
163
Victor Stinnercba9a0c2017-10-12 08:51:56 -0700164
Victor Stinnere0be4232011-10-25 13:06:09 +0200165#ifdef HAVE_CLOCK_GETTIME
Ronald Oussoren41761932020-11-08 10:05:27 +0100166
167#ifdef __APPLE__
Victor Stinnerae6cd7c2020-11-16 16:08:05 +0100168/*
Ronald Oussoren41761932020-11-08 10:05:27 +0100169 * The clock_* functions will be removed from the module
170 * dict entirely when the C API is not available.
171 */
172#pragma clang diagnostic push
173#pragma clang diagnostic ignored "-Wunguarded-availability"
174#endif
175
Victor Stinnere0be4232011-10-25 13:06:09 +0200176static PyObject *
Victor Stinner4195b5c2012-02-08 23:03:19 +0100177time_clock_gettime(PyObject *self, PyObject *args)
Victor Stinnere0be4232011-10-25 13:06:09 +0200178{
179 int ret;
Victor Stinnere0be4232011-10-25 13:06:09 +0200180 struct timespec tp;
181
Michael Felte2926b72018-12-28 14:57:37 +0100182#if defined(_AIX) && (SIZEOF_LONG == 8)
183 long clk_id;
184 if (!PyArg_ParseTuple(args, "l:clock_gettime", &clk_id)) {
185#else
186 int clk_id;
Victor Stinnerc29b5852017-11-02 07:28:27 -0700187 if (!PyArg_ParseTuple(args, "i:clock_gettime", &clk_id)) {
Michael Felte2926b72018-12-28 14:57:37 +0100188#endif
Victor Stinnere0be4232011-10-25 13:06:09 +0200189 return NULL;
Victor Stinnerc29b5852017-11-02 07:28:27 -0700190 }
Victor Stinnere0be4232011-10-25 13:06:09 +0200191
192 ret = clock_gettime((clockid_t)clk_id, &tp);
Antoine Pitrou2c085602012-01-18 01:41:44 +0100193 if (ret != 0) {
Victor Stinnera734af32014-07-31 13:07:17 +0200194 PyErr_SetFromErrno(PyExc_OSError);
Antoine Pitrou2c085602012-01-18 01:41:44 +0100195 return NULL;
196 }
Victor Stinner4195b5c2012-02-08 23:03:19 +0100197 return PyFloat_FromDouble(tp.tv_sec + tp.tv_nsec * 1e-9);
Victor Stinnere0be4232011-10-25 13:06:09 +0200198}
199
200PyDoc_STRVAR(clock_gettime_doc,
Victor Stinnerc29b5852017-11-02 07:28:27 -0700201"clock_gettime(clk_id) -> float\n\
Victor Stinnere0be4232011-10-25 13:06:09 +0200202\n\
203Return the time of the specified clock clk_id.");
Victor Stinnerc29b5852017-11-02 07:28:27 -0700204
205static PyObject *
206time_clock_gettime_ns(PyObject *self, PyObject *args)
207{
208 int ret;
209 int clk_id;
210 struct timespec ts;
211 _PyTime_t t;
212
213 if (!PyArg_ParseTuple(args, "i:clock_gettime", &clk_id)) {
214 return NULL;
215 }
216
217 ret = clock_gettime((clockid_t)clk_id, &ts);
218 if (ret != 0) {
219 PyErr_SetFromErrno(PyExc_OSError);
220 return NULL;
221 }
222 if (_PyTime_FromTimespec(&t, &ts) < 0) {
223 return NULL;
224 }
225 return _PyTime_AsNanosecondsObject(t);
226}
227
228PyDoc_STRVAR(clock_gettime_ns_doc,
229"clock_gettime_ns(clk_id) -> int\n\
230\n\
231Return the time of the specified clock clk_id as nanoseconds.");
Benjamin Peterson37098cd2016-09-13 22:55:09 -0700232#endif /* HAVE_CLOCK_GETTIME */
Victor Stinner30d79472012-04-03 00:45:07 +0200233
Benjamin Peterson37098cd2016-09-13 22:55:09 -0700234#ifdef HAVE_CLOCK_SETTIME
Victor Stinner30d79472012-04-03 00:45:07 +0200235static PyObject *
236time_clock_settime(PyObject *self, PyObject *args)
237{
Victor Stinnerb8d01692012-04-13 23:44:05 +0200238 int clk_id;
Victor Stinner30d79472012-04-03 00:45:07 +0200239 PyObject *obj;
Victor Stinnerb3b45442015-03-28 04:09:41 +0100240 _PyTime_t t;
Victor Stinner30d79472012-04-03 00:45:07 +0200241 struct timespec tp;
242 int ret;
243
244 if (!PyArg_ParseTuple(args, "iO:clock_settime", &clk_id, &obj))
245 return NULL;
246
Victor Stinner02937aa2015-03-28 05:02:39 +0100247 if (_PyTime_FromSecondsObject(&t, obj, _PyTime_ROUND_FLOOR) < 0)
Victor Stinner30d79472012-04-03 00:45:07 +0200248 return NULL;
Victor Stinnerb3b45442015-03-28 04:09:41 +0100249
250 if (_PyTime_AsTimespec(t, &tp) == -1)
251 return NULL;
Victor Stinner30d79472012-04-03 00:45:07 +0200252
253 ret = clock_settime((clockid_t)clk_id, &tp);
254 if (ret != 0) {
Victor Stinnera734af32014-07-31 13:07:17 +0200255 PyErr_SetFromErrno(PyExc_OSError);
Victor Stinner30d79472012-04-03 00:45:07 +0200256 return NULL;
257 }
258 Py_RETURN_NONE;
259}
260
261PyDoc_STRVAR(clock_settime_doc,
262"clock_settime(clk_id, time)\n\
263\n\
264Set the time of the specified clock clk_id.");
Victor Stinnerc29b5852017-11-02 07:28:27 -0700265
266static PyObject *
267time_clock_settime_ns(PyObject *self, PyObject *args)
268{
269 int clk_id;
270 PyObject *obj;
271 _PyTime_t t;
272 struct timespec ts;
273 int ret;
274
275 if (!PyArg_ParseTuple(args, "iO:clock_settime", &clk_id, &obj)) {
276 return NULL;
277 }
278
279 if (_PyTime_FromNanosecondsObject(&t, obj) < 0) {
280 return NULL;
281 }
282 if (_PyTime_AsTimespec(t, &ts) == -1) {
283 return NULL;
284 }
285
286 ret = clock_settime((clockid_t)clk_id, &ts);
287 if (ret != 0) {
288 PyErr_SetFromErrno(PyExc_OSError);
289 return NULL;
290 }
291 Py_RETURN_NONE;
292}
293
294PyDoc_STRVAR(clock_settime_ns_doc,
295"clock_settime_ns(clk_id, time)\n\
296\n\
297Set the time of the specified clock clk_id with nanoseconds.");
Benjamin Peterson37098cd2016-09-13 22:55:09 -0700298#endif /* HAVE_CLOCK_SETTIME */
Victor Stinnere0be4232011-10-25 13:06:09 +0200299
Benjamin Peterson37098cd2016-09-13 22:55:09 -0700300#ifdef HAVE_CLOCK_GETRES
Victor Stinnere0be4232011-10-25 13:06:09 +0200301static PyObject *
Victor Stinner4195b5c2012-02-08 23:03:19 +0100302time_clock_getres(PyObject *self, PyObject *args)
Victor Stinnere0be4232011-10-25 13:06:09 +0200303{
304 int ret;
Victor Stinnerb8d01692012-04-13 23:44:05 +0200305 int clk_id;
Victor Stinnere0be4232011-10-25 13:06:09 +0200306 struct timespec tp;
307
Victor Stinner4195b5c2012-02-08 23:03:19 +0100308 if (!PyArg_ParseTuple(args, "i:clock_getres", &clk_id))
Victor Stinnere0be4232011-10-25 13:06:09 +0200309 return NULL;
310
311 ret = clock_getres((clockid_t)clk_id, &tp);
Antoine Pitrou2c085602012-01-18 01:41:44 +0100312 if (ret != 0) {
Victor Stinnera734af32014-07-31 13:07:17 +0200313 PyErr_SetFromErrno(PyExc_OSError);
Antoine Pitrou2c085602012-01-18 01:41:44 +0100314 return NULL;
315 }
Victor Stinner4195b5c2012-02-08 23:03:19 +0100316
317 return PyFloat_FromDouble(tp.tv_sec + tp.tv_nsec * 1e-9);
Victor Stinnere0be4232011-10-25 13:06:09 +0200318}
319
320PyDoc_STRVAR(clock_getres_doc,
Victor Stinner4195b5c2012-02-08 23:03:19 +0100321"clock_getres(clk_id) -> floating point number\n\
Victor Stinnere0be4232011-10-25 13:06:09 +0200322\n\
323Return the resolution (precision) of the specified clock clk_id.");
Ronald Oussoren41761932020-11-08 10:05:27 +0100324
325#ifdef __APPLE__
326#pragma clang diagnostic pop
327#endif
328
Benjamin Peterson37098cd2016-09-13 22:55:09 -0700329#endif /* HAVE_CLOCK_GETRES */
Victor Stinnere0be4232011-10-25 13:06:09 +0200330
pdoxe14679c2017-10-05 00:01:56 -0700331#ifdef HAVE_PTHREAD_GETCPUCLOCKID
332static PyObject *
333time_pthread_getcpuclockid(PyObject *self, PyObject *args)
334{
335 unsigned long thread_id;
336 int err;
337 clockid_t clk_id;
338 if (!PyArg_ParseTuple(args, "k:pthread_getcpuclockid", &thread_id)) {
339 return NULL;
340 }
341 err = pthread_getcpuclockid((pthread_t)thread_id, &clk_id);
342 if (err) {
343 errno = err;
344 PyErr_SetFromErrno(PyExc_OSError);
345 return NULL;
346 }
Gregory P. Smithb474e672018-12-30 17:05:36 -0800347#ifdef _Py_MEMORY_SANITIZER
348 __msan_unpoison(&clk_id, sizeof(clk_id));
349#endif
pdoxe14679c2017-10-05 00:01:56 -0700350 return PyLong_FromLong(clk_id);
351}
352
353PyDoc_STRVAR(pthread_getcpuclockid_doc,
354"pthread_getcpuclockid(thread_id) -> int\n\
355\n\
356Return the clk_id of a thread's CPU time clock.");
357#endif /* HAVE_PTHREAD_GETCPUCLOCKID */
358
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000359static PyObject *
Victor Stinnercb29f012015-03-27 13:31:18 +0100360time_sleep(PyObject *self, PyObject *obj)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000361{
Victor Stinnercb29f012015-03-27 13:31:18 +0100362 _PyTime_t secs;
Pablo Galindo59af94f2017-10-18 08:13:09 +0100363 if (_PyTime_FromSecondsObject(&secs, obj, _PyTime_ROUND_TIMEOUT))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000364 return NULL;
Victor Stinner7f53a502011-07-05 22:00:25 +0200365 if (secs < 0) {
366 PyErr_SetString(PyExc_ValueError,
367 "sleep length must be non-negative");
368 return NULL;
369 }
Victor Stinnercb29f012015-03-27 13:31:18 +0100370 if (pysleep(secs) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000371 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200372 Py_RETURN_NONE;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000373}
374
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000375PyDoc_STRVAR(sleep_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000376"sleep(seconds)\n\
377\n\
378Delay execution for a given number of seconds. The argument may be\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000379a floating point number for subsecond precision.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000380
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000381static PyStructSequence_Field struct_time_type_fields[] = {
Alexander Belopolsky69f3fd02010-06-05 15:04:51 +0000382 {"tm_year", "year, for example, 1993"},
383 {"tm_mon", "month of year, range [1, 12]"},
384 {"tm_mday", "day of month, range [1, 31]"},
385 {"tm_hour", "hours, range [0, 23]"},
386 {"tm_min", "minutes, range [0, 59]"},
387 {"tm_sec", "seconds, range [0, 61])"},
388 {"tm_wday", "day of week, range [0, 6], Monday is 0"},
389 {"tm_yday", "day of year, range [1, 366]"},
390 {"tm_isdst", "1 if summer time is in effect, 0 if not, and -1 if unknown"},
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400391 {"tm_zone", "abbreviation of timezone name"},
392 {"tm_gmtoff", "offset from UTC in seconds"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000393 {0}
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000394};
395
396static PyStructSequence_Desc struct_time_type_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000397 "time.struct_time",
Alexander Belopolsky69f3fd02010-06-05 15:04:51 +0000398 "The time value as returned by gmtime(), localtime(), and strptime(), and\n"
399 " accepted by asctime(), mktime() and strftime(). May be considered as a\n"
400 " sequence of 9 integers.\n\n"
401 " Note that several fields' values are not the same as those defined by\n"
402 " the C language standard for struct tm. For example, the value of the\n"
403 " field tm_year is the actual year, not year - 1900. See individual\n"
404 " fields' descriptions for details.",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000405 struct_time_type_fields,
406 9,
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000407};
Tim Peters9ad4b682002-02-13 05:14:18 +0000408
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000409static int initialized;
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000410static PyTypeObject StructTimeType;
411
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400412
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000413static PyObject *
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -0400414tmtotuple(struct tm *p
415#ifndef HAVE_STRUCT_TM_TM_ZONE
Victor Stinner0d659e52017-04-25 01:22:42 +0200416 , const char *zone, time_t gmtoff
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -0400417#endif
418)
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000419{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000420 PyObject *v = PyStructSequence_New(&StructTimeType);
421 if (v == NULL)
422 return NULL;
Tim Peters9ad4b682002-02-13 05:14:18 +0000423
Christian Heimes217cfd12007-12-02 14:31:20 +0000424#define SET(i,val) PyStructSequence_SET_ITEM(v, i, PyLong_FromLong((long) val))
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000425
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000426 SET(0, p->tm_year + 1900);
427 SET(1, p->tm_mon + 1); /* Want January == 1 */
428 SET(2, p->tm_mday);
429 SET(3, p->tm_hour);
430 SET(4, p->tm_min);
431 SET(5, p->tm_sec);
432 SET(6, (p->tm_wday + 6) % 7); /* Want Monday == 0 */
433 SET(7, p->tm_yday + 1); /* Want January, 1 == 1 */
434 SET(8, p->tm_isdst);
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400435#ifdef HAVE_STRUCT_TM_TM_ZONE
436 PyStructSequence_SET_ITEM(v, 9,
Victor Stinner7ed7aea2018-01-15 10:45:49 +0100437 PyUnicode_DecodeLocale(p->tm_zone, "surrogateescape"));
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400438 SET(10, p->tm_gmtoff);
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -0400439#else
440 PyStructSequence_SET_ITEM(v, 9,
Victor Stinner7ed7aea2018-01-15 10:45:49 +0100441 PyUnicode_DecodeLocale(zone, "surrogateescape"));
Victor Stinner0d659e52017-04-25 01:22:42 +0200442 PyStructSequence_SET_ITEM(v, 10, _PyLong_FromTime_t(gmtoff));
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400443#endif /* HAVE_STRUCT_TM_TM_ZONE */
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000444#undef SET
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000445 if (PyErr_Occurred()) {
446 Py_XDECREF(v);
447 return NULL;
448 }
Guido van Rossum98bf58f2001-10-18 20:34:25 +0000449
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000450 return v;
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000451}
452
Fred Drakef901abd2004-08-03 17:58:55 +0000453/* Parse arg tuple that can contain an optional float-or-None value;
454 format needs to be "|O:name".
455 Returns non-zero on success (parallels PyArg_ParseTuple).
456*/
457static int
Serhiy Storchakaef1585e2015-12-25 20:01:53 +0200458parse_time_t_args(PyObject *args, const char *format, time_t *pwhen)
Fred Drakef901abd2004-08-03 17:58:55 +0000459{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000460 PyObject *ot = NULL;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100461 time_t whent;
Fred Drakef901abd2004-08-03 17:58:55 +0000462
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000463 if (!PyArg_ParseTuple(args, format, &ot))
464 return 0;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100465 if (ot == NULL || ot == Py_None) {
466 whent = time(NULL);
467 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000468 else {
Victor Stinner02937aa2015-03-28 05:02:39 +0100469 if (_PyTime_ObjectToTime_t(ot, &whent, _PyTime_ROUND_FLOOR) == -1)
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100470 return 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000471 }
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100472 *pwhen = whent;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000473 return 1;
Fred Drakef901abd2004-08-03 17:58:55 +0000474}
475
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000476static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000477time_gmtime(PyObject *self, PyObject *args)
Guido van Rossum234f9421993-06-17 12:35:49 +0000478{
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100479 time_t when;
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -0400480 struct tm buf;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100481
482 if (!parse_time_t_args(args, "|O:gmtime", &when))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000483 return NULL;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100484
485 errno = 0;
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -0400486 if (_PyTime_gmtime(when, &buf) != 0)
487 return NULL;
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -0400488#ifdef HAVE_STRUCT_TM_TM_ZONE
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100489 return tmtotuple(&buf);
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -0400490#else
491 return tmtotuple(&buf, "UTC", 0);
492#endif
Guido van Rossum234f9421993-06-17 12:35:49 +0000493}
494
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -0400495#ifndef HAVE_TIMEGM
496static time_t
497timegm(struct tm *p)
498{
499 /* XXX: the following implementation will not work for tm_year < 1970.
500 but it is likely that platforms that don't have timegm do not support
501 negative timestamps anyways. */
502 return p->tm_sec + p->tm_min*60 + p->tm_hour*3600 + p->tm_yday*86400 +
503 (p->tm_year-70)*31536000 + ((p->tm_year-69)/4)*86400 -
504 ((p->tm_year-1)/100)*86400 + ((p->tm_year+299)/400)*86400;
505}
506#endif
507
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000508PyDoc_STRVAR(gmtime_doc,
Christian Heimes9a371592007-12-28 14:08:13 +0000509"gmtime([seconds]) -> (tm_year, tm_mon, tm_mday, tm_hour, tm_min,\n\
Fred Drake193a3f62002-03-12 21:38:49 +0000510 tm_sec, tm_wday, tm_yday, tm_isdst)\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000511\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000512Convert seconds since the Epoch to a time tuple expressing UTC (a.k.a.\n\
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400513GMT). When 'seconds' is not passed in, convert the current time instead.\n\
514\n\
515If the platform supports the tm_gmtoff and tm_zone, they are available as\n\
516attributes only.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000517
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000518static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000519time_localtime(PyObject *self, PyObject *args)
Guido van Rossum234f9421993-06-17 12:35:49 +0000520{
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100521 time_t when;
522 struct tm buf;
523
524 if (!parse_time_t_args(args, "|O:localtime", &when))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000525 return NULL;
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -0400526 if (_PyTime_localtime(when, &buf) != 0)
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100527 return NULL;
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -0400528#ifdef HAVE_STRUCT_TM_TM_ZONE
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100529 return tmtotuple(&buf);
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -0400530#else
531 {
532 struct tm local = buf;
533 char zone[100];
Victor Stinner0d659e52017-04-25 01:22:42 +0200534 time_t gmtoff;
Steve Dowerc3c6f712016-12-14 11:22:05 -0800535 strftime(zone, sizeof(zone), "%Z", &buf);
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -0400536 gmtoff = timegm(&buf) - when;
537 return tmtotuple(&local, zone, gmtoff);
538 }
539#endif
Guido van Rossum234f9421993-06-17 12:35:49 +0000540}
541
Benjamin Peterson5633c4f2018-09-14 09:09:04 -0700542#if defined(__linux__) && !defined(__GLIBC__)
543static const char *utc_string = NULL;
544#endif
545
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000546PyDoc_STRVAR(localtime_doc,
Christian Heimes9a371592007-12-28 14:08:13 +0000547"localtime([seconds]) -> (tm_year,tm_mon,tm_mday,tm_hour,tm_min,\n\
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000548 tm_sec,tm_wday,tm_yday,tm_isdst)\n\
Martin v. Löwisb3cfc1d2001-12-02 12:27:43 +0000549\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000550Convert seconds since the Epoch to a time tuple expressing local time.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000551When 'seconds' is not passed in, convert the current time instead.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000552
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000553/* Convert 9-item tuple to tm structure. Return 1 on success, set
554 * an exception and return 0 on error.
555 */
Guido van Rossum9e90a671993-06-24 11:10:19 +0000556static int
Oren Milman1d1d3e92017-08-20 18:35:36 +0300557gettmarg(PyObject *args, struct tm *p, const char *format)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000558{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000559 int y;
Guido van Rossumcfbaecc1998-08-25 14:51:12 +0000560
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000561 memset((void *) p, '\0', sizeof(struct tm));
Guido van Rossumb9081262007-08-25 03:14:09 +0000562
Alexander Belopolsky610e5442011-01-06 21:57:06 +0000563 if (!PyTuple_Check(args)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000564 PyErr_SetString(PyExc_TypeError,
565 "Tuple or struct_time argument required");
566 return 0;
567 }
Skip Montanaro41cfce92007-08-24 21:11:00 +0000568
Oren Milman1d1d3e92017-08-20 18:35:36 +0300569 if (!PyArg_ParseTuple(args, format,
Alexander Belopolsky610e5442011-01-06 21:57:06 +0000570 &y, &p->tm_mon, &p->tm_mday,
571 &p->tm_hour, &p->tm_min, &p->tm_sec,
572 &p->tm_wday, &p->tm_yday, &p->tm_isdst))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000573 return 0;
Gregory P. Smith76be0ff2018-08-24 18:08:50 -0700574
575 if (y < INT_MIN + 1900) {
576 PyErr_SetString(PyExc_OverflowError, "year out of range");
577 return 0;
578 }
579
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000580 p->tm_year = y - 1900;
581 p->tm_mon--;
582 p->tm_wday = (p->tm_wday + 1) % 7;
583 p->tm_yday--;
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400584#ifdef HAVE_STRUCT_TM_TM_ZONE
Dong-hee Na1b55b652020-02-17 19:09:15 +0900585 if (Py_IS_TYPE(args, &StructTimeType)) {
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400586 PyObject *item;
Victor Stinner1cdfcfc2018-11-28 15:19:51 +0100587 item = PyStructSequence_GET_ITEM(args, 9);
Benjamin Peterson5633c4f2018-09-14 09:09:04 -0700588 if (item != Py_None) {
Xiang Zhang163eca32018-10-28 23:58:42 +0800589 p->tm_zone = (char *)PyUnicode_AsUTF8(item);
Benjamin Peterson5633c4f2018-09-14 09:09:04 -0700590 if (p->tm_zone == NULL) {
591 return 0;
592 }
593#if defined(__linux__) && !defined(__GLIBC__)
594 // Make an attempt to return the C library's own timezone strings to
595 // it. musl refuses to process a tm_zone field unless it produced
596 // it. See issue #34672.
597 if (utc_string && strcmp(p->tm_zone, utc_string) == 0) {
598 p->tm_zone = utc_string;
599 }
600 else if (tzname[0] && strcmp(p->tm_zone, tzname[0]) == 0) {
601 p->tm_zone = tzname[0];
602 }
603 else if (tzname[1] && strcmp(p->tm_zone, tzname[1]) == 0) {
604 p->tm_zone = tzname[1];
605 }
606#endif
607 }
Victor Stinner1cdfcfc2018-11-28 15:19:51 +0100608 item = PyStructSequence_GET_ITEM(args, 10);
Benjamin Peterson5633c4f2018-09-14 09:09:04 -0700609 if (item != Py_None) {
610 p->tm_gmtoff = PyLong_AsLong(item);
611 if (PyErr_Occurred())
612 return 0;
613 }
Alexander Belopolskyc142bba2012-06-13 22:15:26 -0400614 }
615#endif /* HAVE_STRUCT_TM_TM_ZONE */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000616 return 1;
Guido van Rossum9e90a671993-06-24 11:10:19 +0000617}
618
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000619/* Check values of the struct tm fields before it is passed to strftime() and
620 * asctime(). Return 1 if all values are valid, otherwise set an exception
621 * and returns 0.
622 */
Victor Stinneref128102010-10-07 01:00:52 +0000623static int
624checktm(struct tm* buf)
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000625{
Victor Stinneref128102010-10-07 01:00:52 +0000626 /* Checks added to make sure strftime() and asctime() does not crash Python by
627 indexing blindly into some array for a textual representation
628 by some bad index (fixes bug #897625 and #6608).
629
630 Also support values of zero from Python code for arguments in which
631 that is out of range by forcing that value to the lowest value that
632 is valid (fixed bug #1520914).
633
634 Valid ranges based on what is allowed in struct tm:
635
636 - tm_year: [0, max(int)] (1)
637 - tm_mon: [0, 11] (2)
638 - tm_mday: [1, 31]
639 - tm_hour: [0, 23]
640 - tm_min: [0, 59]
641 - tm_sec: [0, 60]
642 - tm_wday: [0, 6] (1)
643 - tm_yday: [0, 365] (2)
644 - tm_isdst: [-max(int), max(int)]
645
646 (1) gettmarg() handles bounds-checking.
647 (2) Python's acceptable range is one greater than the range in C,
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000648 thus need to check against automatic decrement by gettmarg().
649 */
650 if (buf->tm_mon == -1)
651 buf->tm_mon = 0;
652 else if (buf->tm_mon < 0 || buf->tm_mon > 11) {
653 PyErr_SetString(PyExc_ValueError, "month out of range");
654 return 0;
655 }
656 if (buf->tm_mday == 0)
657 buf->tm_mday = 1;
658 else if (buf->tm_mday < 0 || buf->tm_mday > 31) {
659 PyErr_SetString(PyExc_ValueError, "day of month out of range");
660 return 0;
661 }
662 if (buf->tm_hour < 0 || buf->tm_hour > 23) {
663 PyErr_SetString(PyExc_ValueError, "hour out of range");
664 return 0;
665 }
666 if (buf->tm_min < 0 || buf->tm_min > 59) {
667 PyErr_SetString(PyExc_ValueError, "minute out of range");
668 return 0;
669 }
670 if (buf->tm_sec < 0 || buf->tm_sec > 61) {
671 PyErr_SetString(PyExc_ValueError, "seconds out of range");
672 return 0;
673 }
674 /* tm_wday does not need checking of its upper-bound since taking
675 ``% 7`` in gettmarg() automatically restricts the range. */
676 if (buf->tm_wday < 0) {
677 PyErr_SetString(PyExc_ValueError, "day of week out of range");
678 return 0;
679 }
680 if (buf->tm_yday == -1)
681 buf->tm_yday = 0;
682 else if (buf->tm_yday < 0 || buf->tm_yday > 365) {
683 PyErr_SetString(PyExc_ValueError, "day of year out of range");
684 return 0;
685 }
686 return 1;
687}
688
Victor Stinnerc1f32ca2011-10-14 02:36:13 +0200689#ifdef MS_WINDOWS
690 /* wcsftime() doesn't format correctly time zones, see issue #10653 */
691# undef HAVE_WCSFTIME
692#endif
Alexander Belopolskycf774542012-10-02 18:39:16 -0400693#define STRFTIME_FORMAT_CODES \
694"Commonly used format codes:\n\
695\n\
696%Y Year with century as a decimal number.\n\
697%m Month as a decimal number [01,12].\n\
698%d Day of the month as a decimal number [01,31].\n\
699%H Hour (24-hour clock) as a decimal number [00,23].\n\
700%M Minute as a decimal number [00,59].\n\
701%S Second as a decimal number [00,61].\n\
702%z Time zone offset from UTC.\n\
703%a Locale's abbreviated weekday name.\n\
704%A Locale's full weekday name.\n\
705%b Locale's abbreviated month name.\n\
706%B Locale's full month name.\n\
707%c Locale's appropriate date and time representation.\n\
708%I Hour (12-hour clock) as a decimal number [01,12].\n\
709%p Locale's equivalent of either AM or PM.\n\
710\n\
711Other codes may be available on your platform. See documentation for\n\
712the C library strftime function.\n"
Victor Stinnerc1f32ca2011-10-14 02:36:13 +0200713
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000714#ifdef HAVE_STRFTIME
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000715#ifdef HAVE_WCSFTIME
716#define time_char wchar_t
717#define format_time wcsftime
718#define time_strlen wcslen
719#else
720#define time_char char
721#define format_time strftime
722#define time_strlen strlen
723#endif
724
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000725static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000726time_strftime(PyObject *self, PyObject *args)
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000727{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000728 PyObject *tup = NULL;
729 struct tm buf;
730 const time_char *fmt;
Victor Stinnerb2904782010-09-29 10:34:19 +0000731#ifdef HAVE_WCSFTIME
732 wchar_t *format;
733#else
734 PyObject *format;
735#endif
Victor Stinneref128102010-10-07 01:00:52 +0000736 PyObject *format_arg;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000737 size_t fmtlen, buflen;
Victor Stinnerb2904782010-09-29 10:34:19 +0000738 time_char *outbuf = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000739 size_t i;
Victor Stinnerb2904782010-09-29 10:34:19 +0000740 PyObject *ret = NULL;
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000741
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000742 memset((void *) &buf, '\0', sizeof(buf));
Guido van Rossum1f41f841998-04-27 19:04:26 +0000743
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000744 /* Will always expect a unicode string to be passed as format.
745 Given that there's no str type anymore in py3k this seems safe.
746 */
Victor Stinneref128102010-10-07 01:00:52 +0000747 if (!PyArg_ParseTuple(args, "U|O:strftime", &format_arg, &tup))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000748 return NULL;
Thomas Woutersfe385252001-01-19 23:16:56 +0000749
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000750 if (tup == NULL) {
751 time_t tt = time(NULL);
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -0400752 if (_PyTime_localtime(tt, &buf) != 0)
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100753 return NULL;
Alexander Belopolsky38e29962010-10-01 14:18:49 +0000754 }
Oren Milman1d1d3e92017-08-20 18:35:36 +0300755 else if (!gettmarg(tup, &buf,
756 "iiiiiiiii;strftime(): illegal time tuple argument") ||
757 !checktm(&buf))
758 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000759 return NULL;
Oren Milman1d1d3e92017-08-20 18:35:36 +0300760 }
Guido van Rossum10b164a2001-09-25 13:59:01 +0000761
pxinwrf1464f42019-04-15 17:06:21 +0800762#if defined(_MSC_VER) || (defined(__sun) && defined(__SVR4)) || defined(_AIX) || defined(__VXWORKS__)
Victor Stinner73ea29c2011-01-08 01:56:31 +0000763 if (buf.tm_year + 1900 < 1 || 9999 < buf.tm_year + 1900) {
Victor Stinner6f0e4f92011-03-21 02:14:53 +0100764 PyErr_SetString(PyExc_ValueError,
765 "strftime() requires year in [1; 9999]");
Alexander Belopolsky0dd06f42011-01-08 01:23:02 +0000766 return NULL;
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000767 }
Victor Stinner73ea29c2011-01-08 01:56:31 +0000768#endif
Alexander Belopolskyc64708a2011-01-07 19:59:19 +0000769
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000770 /* Normalize tm_isdst just in case someone foolishly implements %Z
771 based on the assumption that tm_isdst falls within the range of
772 [-1, 1] */
773 if (buf.tm_isdst < -1)
774 buf.tm_isdst = -1;
775 else if (buf.tm_isdst > 1)
776 buf.tm_isdst = 1;
Brett Cannond1080a32004-03-02 04:38:10 +0000777
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000778#ifdef HAVE_WCSFTIME
Victor Stinnerbeb4135b2010-10-07 01:02:42 +0000779 format = PyUnicode_AsWideCharString(format_arg, NULL);
Victor Stinnerb2904782010-09-29 10:34:19 +0000780 if (format == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000781 return NULL;
Victor Stinnerb2904782010-09-29 10:34:19 +0000782 fmt = format;
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000783#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000784 /* Convert the unicode string to an ascii one */
Victor Stinner1b579672011-12-17 05:47:23 +0100785 format = PyUnicode_EncodeLocale(format_arg, "surrogateescape");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000786 if (format == NULL)
787 return NULL;
788 fmt = PyBytes_AS_STRING(format);
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000789#endif
Amaury Forgeot d'Arcb5be6d42009-03-02 23:52:57 +0000790
Stefan Krah4aea7d32012-02-27 16:30:26 +0100791#if defined(MS_WINDOWS) && !defined(HAVE_WCSFTIME)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000792 /* check that the format string contains only valid directives */
Steve Dowere5b58952015-09-06 19:20:51 -0700793 for (outbuf = strchr(fmt, '%');
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000794 outbuf != NULL;
Victor Stinner5a3ff792011-10-16 19:08:23 +0200795 outbuf = strchr(outbuf+2, '%'))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000796 {
Steve Dowere5b58952015-09-06 19:20:51 -0700797 if (outbuf[1] == '#')
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000798 ++outbuf; /* not documented by python, */
Steve Dowere5b58952015-09-06 19:20:51 -0700799 if (outbuf[1] == '\0')
800 break;
801 if ((outbuf[1] == 'y') && buf.tm_year < 0) {
Tim Golden6e51b8f2013-11-12 12:36:54 +0000802 PyErr_SetString(PyExc_ValueError,
803 "format %y requires year >= 1900 on Windows");
804 Py_DECREF(format);
805 return NULL;
806 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000807 }
Jakub Kulík6f9bc722018-12-31 03:16:40 +0100808#elif (defined(_AIX) || (defined(__sun) && defined(__SVR4))) && defined(HAVE_WCSFTIME)
Steve Dowere5b58952015-09-06 19:20:51 -0700809 for (outbuf = wcschr(fmt, '%');
Victor Stinner55329f82013-11-17 23:39:21 +0100810 outbuf != NULL;
811 outbuf = wcschr(outbuf+2, '%'))
812 {
Steve Dowere5b58952015-09-06 19:20:51 -0700813 if (outbuf[1] == L'\0')
814 break;
Victor Stinner55329f82013-11-17 23:39:21 +0100815 /* Issue #19634: On AIX, wcsftime("y", (1899, 1, 1, 0, 0, 0, 0, 0, 0))
816 returns "0/" instead of "99" */
817 if (outbuf[1] == L'y' && buf.tm_year < 0) {
818 PyErr_SetString(PyExc_ValueError,
819 "format %y requires year >= 1900 on AIX");
Zackery Spytz91e6c872018-09-21 00:09:48 -0600820 PyMem_Free(format);
Victor Stinner55329f82013-11-17 23:39:21 +0100821 return NULL;
822 }
823 }
Amaury Forgeot d'Arcb5be6d42009-03-02 23:52:57 +0000824#endif
825
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000826 fmtlen = time_strlen(fmt);
Guido van Rossumc222ec21999-02-23 00:00:10 +0000827
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000828 /* I hate these functions that presume you know how big the output
829 * will be ahead of time...
830 */
831 for (i = 1024; ; i += i) {
832 outbuf = (time_char *)PyMem_Malloc(i*sizeof(time_char));
833 if (outbuf == NULL) {
Victor Stinnerb2904782010-09-29 10:34:19 +0000834 PyErr_NoMemory();
835 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000836 }
Steve Dower57ab1cd2015-09-22 14:51:42 -0700837#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
838 errno = 0;
839#endif
Steve Dowerd9ef74e2015-05-22 15:08:34 -0700840 _Py_BEGIN_SUPPRESS_IPH
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000841 buflen = format_time(outbuf, i, fmt, &buf);
Steve Dowerd9ef74e2015-05-22 15:08:34 -0700842 _Py_END_SUPPRESS_IPH
Victor Stinner136ea492011-12-17 22:37:18 +0100843#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
Steve Dower97cded92015-09-08 19:12:51 -0700844 /* VisualStudio .NET 2005 does this properly */
845 if (buflen == 0 && errno == EINVAL) {
846 PyErr_SetString(PyExc_ValueError, "Invalid format string");
847 PyMem_Free(outbuf);
848 break;
849 }
Victor Stinner136ea492011-12-17 22:37:18 +0100850#endif
Steve Dower97cded92015-09-08 19:12:51 -0700851 if (buflen > 0 || i >= 256 * fmtlen) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000852 /* If the buffer is 256 times as long as the format,
853 it's probably not failing for lack of room!
854 More likely, the format yields an empty result,
855 e.g. an empty format, or %Z when the timezone
856 is unknown. */
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000857#ifdef HAVE_WCSFTIME
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000858 ret = PyUnicode_FromWideChar(outbuf, buflen);
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000859#else
Victor Stinner7ed7aea2018-01-15 10:45:49 +0100860 ret = PyUnicode_DecodeLocaleAndSize(outbuf, buflen, "surrogateescape");
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000861#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000862 PyMem_Free(outbuf);
Victor Stinnerb2904782010-09-29 10:34:19 +0000863 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000864 }
865 PyMem_Free(outbuf);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000866 }
Victor Stinnerb2904782010-09-29 10:34:19 +0000867#ifdef HAVE_WCSFTIME
868 PyMem_Free(format);
869#else
870 Py_DECREF(format);
871#endif
872 return ret;
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000873}
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000874
Martin v. Löwis1b01ccd2009-05-30 06:13:40 +0000875#undef time_char
876#undef format_time
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000877PyDoc_STRVAR(strftime_doc,
Thomas Woutersfe385252001-01-19 23:16:56 +0000878"strftime(format[, tuple]) -> string\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000879\n\
880Convert a time tuple to a string according to a format specification.\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000881See the library reference manual for formatting codes. When the time tuple\n\
Alexander Belopolskycf774542012-10-02 18:39:16 -0400882is not present, current time as returned by localtime() is used.\n\
883\n" STRFTIME_FORMAT_CODES);
Guido van Rossum8d8c1ee1995-09-13 17:38:35 +0000884#endif /* HAVE_STRFTIME */
885
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000886static PyObject *
887time_strptime(PyObject *self, PyObject *args)
888{
Victor Stinnerdbe28d22016-12-09 00:38:53 +0100889 PyObject *module, *func, *result;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200890 _Py_IDENTIFIER(_strptime_time);
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000891
Victor Stinnerdbe28d22016-12-09 00:38:53 +0100892 module = PyImport_ImportModuleNoBlock("_strptime");
893 if (!module)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000894 return NULL;
Victor Stinnerdbe28d22016-12-09 00:38:53 +0100895
896 func = _PyObject_GetAttrId(module, &PyId__strptime_time);
897 Py_DECREF(module);
898 if (!func) {
899 return NULL;
900 }
901
902 result = PyObject_Call(func, args, NULL);
903 Py_DECREF(func);
904 return result;
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000905}
906
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000907
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000908PyDoc_STRVAR(strptime_doc,
Brett Cannon20def8b2003-07-01 05:16:08 +0000909"strptime(string, format) -> struct_time\n\
Martin v. Löwisb3cfc1d2001-12-02 12:27:43 +0000910\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000911Parse a string to a time tuple according to a format specification.\n\
Alexander Belopolskycf774542012-10-02 18:39:16 -0400912See the library reference manual for formatting codes (same as\n\
913strftime()).\n\
914\n" STRFTIME_FORMAT_CODES);
Guido van Rossumd3c46d52002-07-19 17:06:47 +0000915
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000916static PyObject *
917_asctime(struct tm *timeptr)
918{
919 /* Inspired by Open Group reference implementation available at
920 * http://pubs.opengroup.org/onlinepubs/009695399/functions/asctime.html */
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200921 static const char wday_name[7][4] = {
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000922 "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
923 };
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200924 static const char mon_name[12][4] = {
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000925 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
926 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
927 };
Victor Stinner499dfcf2011-03-21 13:26:24 +0100928 return PyUnicode_FromFormat(
929 "%s %s%3d %.2d:%.2d:%.2d %d",
930 wday_name[timeptr->tm_wday],
931 mon_name[timeptr->tm_mon],
932 timeptr->tm_mday, timeptr->tm_hour,
933 timeptr->tm_min, timeptr->tm_sec,
934 1900 + timeptr->tm_year);
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000935}
Guido van Rossum87ce7bb1998-06-09 16:30:31 +0000936
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000937static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000938time_asctime(PyObject *self, PyObject *args)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000939{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000940 PyObject *tup = NULL;
941 struct tm buf;
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000942
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000943 if (!PyArg_UnpackTuple(args, "asctime", 0, 1, &tup))
944 return NULL;
945 if (tup == NULL) {
946 time_t tt = time(NULL);
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -0400947 if (_PyTime_localtime(tt, &buf) != 0)
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100948 return NULL;
Oren Milman1d1d3e92017-08-20 18:35:36 +0300949 }
950 else if (!gettmarg(tup, &buf,
951 "iiiiiiiii;asctime(): illegal time tuple argument") ||
952 !checktm(&buf))
953 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000954 return NULL;
Oren Milman1d1d3e92017-08-20 18:35:36 +0300955 }
Alexander Belopolskyb9588b52011-01-04 16:34:30 +0000956 return _asctime(&buf);
Guido van Rossum9e90a671993-06-24 11:10:19 +0000957}
958
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000959PyDoc_STRVAR(asctime_doc,
Thomas Woutersfe385252001-01-19 23:16:56 +0000960"asctime([tuple]) -> string\n\
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000961\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000962Convert a time tuple to a string, e.g. 'Sat Jun 06 16:26:11 1998'.\n\
963When the time tuple is not present, current time as returned by localtime()\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000964is used.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000965
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000966static PyObject *
Peter Schneider-Kamp416d4132000-07-10 12:15:54 +0000967time_ctime(PyObject *self, PyObject *args)
Guido van Rossum9e90a671993-06-24 11:10:19 +0000968{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000969 time_t tt;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100970 struct tm buf;
971 if (!parse_time_t_args(args, "|O:ctime", &tt))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000972 return NULL;
Alexander Belopolsky3e7a3cb2016-09-28 17:31:35 -0400973 if (_PyTime_localtime(tt, &buf) != 0)
Alexander Belopolsky5da468f2011-01-04 17:15:52 +0000974 return NULL;
Victor Stinnerc1b5d342012-01-27 00:08:48 +0100975 return _asctime(&buf);
Guido van Rossum9e90a671993-06-24 11:10:19 +0000976}
977
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000978PyDoc_STRVAR(ctime_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000979"ctime(seconds) -> string\n\
980\n\
981Convert a time in seconds since the Epoch to a string in local time.\n\
Thomas Woutersfe385252001-01-19 23:16:56 +0000982This is equivalent to asctime(localtime(seconds)). When the time tuple is\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000983not present, current time as returned by localtime() is used.");
Guido van Rossum0ef577b1998-06-27 20:38:36 +0000984
Guido van Rossum60cd8131998-03-06 17:16:21 +0000985#ifdef HAVE_MKTIME
Barry Warsaw9a2a8a81996-12-06 23:32:14 +0000986static PyObject *
Victor Stinner87094902019-04-09 19:12:26 +0200987time_mktime(PyObject *self, PyObject *tm_tuple)
Guido van Rossum234f9421993-06-17 12:35:49 +0000988{
Victor Stinner87094902019-04-09 19:12:26 +0200989 struct tm tm;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000990 time_t tt;
Michael Felte2926b72018-12-28 14:57:37 +0100991
Victor Stinner87094902019-04-09 19:12:26 +0200992 if (!gettmarg(tm_tuple, &tm,
Oren Milman1d1d3e92017-08-20 18:35:36 +0300993 "iiiiiiiii;mktime(): illegal time tuple argument"))
994 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000995 return NULL;
Oren Milman1d1d3e92017-08-20 18:35:36 +0300996 }
Victor Stinner87094902019-04-09 19:12:26 +0200997
pxinwrf1464f42019-04-15 17:06:21 +0800998#if defined(_AIX) || (defined(__VXWORKS__) && !defined(_WRS_CONFIG_LP64))
Victor Stinner87094902019-04-09 19:12:26 +0200999 /* bpo-19748: AIX mktime() valid range is 00:00:00 UTC, January 1, 1970
1000 to 03:14:07 UTC, January 19, 2038. Thanks to the workaround below,
1001 it is possible to support years in range [1902; 2037] */
1002 if (tm.tm_year < 2 || tm.tm_year > 137) {
1003 /* bpo-19748: On AIX, mktime() does not report overflow error
pxinwrf1464f42019-04-15 17:06:21 +08001004 for timestamp < -2^31 or timestamp > 2**31-1. VxWorks has the
1005 same issue when working in 32 bit mode. */
Victor Stinner1ac42612014-02-21 09:27:17 +01001006 PyErr_SetString(PyExc_OverflowError,
1007 "mktime argument out of range");
1008 return NULL;
1009 }
pxinwrf1464f42019-04-15 17:06:21 +08001010#endif
Victor Stinner87094902019-04-09 19:12:26 +02001011
pxinwrf1464f42019-04-15 17:06:21 +08001012#ifdef _AIX
Victor Stinner87094902019-04-09 19:12:26 +02001013 /* bpo-34373: AIX mktime() has an integer overflow for years in range
1014 [1902; 1969]. Workaround the issue by using a year greater or equal than
1015 1970 (tm_year >= 70): mktime() behaves correctly in that case
1016 (ex: properly report errors). tm_year and tm_wday are adjusted after
1017 mktime() call. */
1018 int orig_tm_year = tm.tm_year;
1019 int delta_days = 0;
1020 while (tm.tm_year < 70) {
1021 /* Use 4 years to account properly leap years */
1022 tm.tm_year += 4;
Michael Felte2926b72018-12-28 14:57:37 +01001023 delta_days -= (366 + (365 * 3));
1024 }
Victor Stinner1ac42612014-02-21 09:27:17 +01001025#endif
Victor Stinner87094902019-04-09 19:12:26 +02001026
1027 tm.tm_wday = -1; /* sentinel; original value ignored */
1028 tt = mktime(&tm);
1029
Alexander Belopolskyb7d40d12011-01-11 01:21:25 +00001030 /* Return value of -1 does not necessarily mean an error, but tm_wday
Ezio Melotti13925002011-03-16 11:05:33 +02001031 * cannot remain set to -1 if mktime succeeded. */
Victor Stinner93037492013-06-25 22:54:35 +02001032 if (tt == (time_t)(-1)
Victor Stinner93037492013-06-25 22:54:35 +02001033 /* Return value of -1 does not necessarily mean an error, but
1034 * tm_wday cannot remain set to -1 if mktime succeeded. */
Victor Stinner87094902019-04-09 19:12:26 +02001035 && tm.tm_wday == -1)
Victor Stinner93037492013-06-25 22:54:35 +02001036 {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001037 PyErr_SetString(PyExc_OverflowError,
1038 "mktime argument out of range");
1039 return NULL;
1040 }
Victor Stinner87094902019-04-09 19:12:26 +02001041
1042#ifdef _AIX
1043 if (delta_days != 0) {
1044 tm.tm_year = orig_tm_year;
1045 if (tm.tm_wday != -1) {
1046 tm.tm_wday = (tm.tm_wday + delta_days) % 7;
1047 }
1048 tt += delta_days * (24 * 3600);
1049 }
1050#endif
1051
Victor Stinner4195b5c2012-02-08 23:03:19 +01001052 return PyFloat_FromDouble((double)tt);
Guido van Rossum234f9421993-06-17 12:35:49 +00001053}
Guido van Rossum0ef577b1998-06-27 20:38:36 +00001054
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001055PyDoc_STRVAR(mktime_doc,
Guido van Rossum0ef577b1998-06-27 20:38:36 +00001056"mktime(tuple) -> floating point number\n\
1057\n\
Alexander Belopolskyc142bba2012-06-13 22:15:26 -04001058Convert a time tuple in local time to seconds since the Epoch.\n\
1059Note that mktime(gmtime(0)) will not generally return zero for most\n\
1060time zones; instead the returned value will either be equal to that\n\
1061of the timezone or altzone attributes on the time module.");
Guido van Rossum60cd8131998-03-06 17:16:21 +00001062#endif /* HAVE_MKTIME */
Guido van Rossum234f9421993-06-17 12:35:49 +00001063
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001064#ifdef HAVE_WORKING_TZSET
Victor Stinner3bb150d2018-12-03 13:45:38 +01001065static int init_timezone(PyObject *module);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001066
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001067static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001068time_tzset(PyObject *self, PyObject *unused)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001069{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001070 PyObject* m;
Fred Drake9bb74322002-04-01 14:49:59 +00001071
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001072 m = PyImport_ImportModuleNoBlock("time");
1073 if (m == NULL) {
1074 return NULL;
1075 }
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001076
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001077 tzset();
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001078
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001079 /* Reset timezone, altzone, daylight and tzname */
Victor Stinner3bb150d2018-12-03 13:45:38 +01001080 if (init_timezone(m) < 0) {
Victor Stinner503ce5c2018-12-01 00:39:36 +01001081 return NULL;
1082 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001083 Py_DECREF(m);
Victor Stinner2ff51b82013-07-17 21:42:45 +02001084 if (PyErr_Occurred())
1085 return NULL;
Tim Peters1b6f7a92004-06-20 02:50:16 +00001086
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001087 Py_RETURN_NONE;
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001088}
1089
1090PyDoc_STRVAR(tzset_doc,
R. David Murray4d55bf92010-12-14 00:55:46 +00001091"tzset()\n\
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001092\n\
1093Initialize, or reinitialize, the local timezone to the value stored in\n\
1094os.environ['TZ']. The TZ environment variable should be specified in\n\
Neal Norwitzdc8e1942004-07-20 22:34:37 +00001095standard Unix timezone format as documented in the tzset man page\n\
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001096(eg. 'US/Eastern', 'Europe/Amsterdam'). Unknown timezones will silently\n\
1097fall back to UTC. If the TZ environment variable is not set, the local\n\
1098timezone is set to the systems best guess of wallclock time.\n\
1099Changing the TZ environment variable without calling tzset *may* change\n\
1100the local timezone used by methods such as localtime, but this behaviour\n\
1101should not be relied on.");
1102#endif /* HAVE_WORKING_TZSET */
1103
Victor Stinnerae6cd7c2020-11-16 16:08:05 +01001104
1105static int
1106get_monotonic(_PyTime_t *t)
1107{
1108 // Avoid _PyTime_GetMonotonicClock() which silently ignores errors.
1109 return _PyTime_GetMonotonicClockWithInfo(t, NULL);
1110}
1111
1112
Victor Stinnerae586492014-09-02 23:18:25 +02001113static PyObject *
Victor Stinnerec895392012-04-29 02:41:27 +02001114time_monotonic(PyObject *self, PyObject *unused)
Victor Stinner071eca32012-03-15 01:17:09 +01001115{
Victor Stinnerae6cd7c2020-11-16 16:08:05 +01001116 _PyTime_t t;
1117 if (get_monotonic(&t) < 0) {
1118 return NULL;
1119 }
Victor Stinnerc29b5852017-11-02 07:28:27 -07001120 return _PyFloat_FromPyTime(t);
Victor Stinner071eca32012-03-15 01:17:09 +01001121}
1122
Victor Stinnerec895392012-04-29 02:41:27 +02001123PyDoc_STRVAR(monotonic_doc,
1124"monotonic() -> float\n\
Victor Stinner8b302012012-02-07 23:29:46 +01001125\n\
Victor Stinnerec895392012-04-29 02:41:27 +02001126Monotonic clock, cannot go backward.");
Victor Stinnerec919cc2012-03-15 00:58:32 +01001127
Victor Stinnerec895392012-04-29 02:41:27 +02001128static PyObject *
Victor Stinnerc29b5852017-11-02 07:28:27 -07001129time_monotonic_ns(PyObject *self, PyObject *unused)
1130{
Victor Stinnerae6cd7c2020-11-16 16:08:05 +01001131 _PyTime_t t;
1132 if (get_monotonic(&t) < 0) {
1133 return NULL;
1134 }
Victor Stinnerc29b5852017-11-02 07:28:27 -07001135 return _PyTime_AsNanosecondsObject(t);
1136}
1137
1138PyDoc_STRVAR(monotonic_ns_doc,
1139"monotonic_ns() -> int\n\
1140\n\
1141Monotonic clock, cannot go backward, as nanoseconds.");
1142
Victor Stinnerae6cd7c2020-11-16 16:08:05 +01001143
1144static int
1145get_perf_counter(_PyTime_t *t)
1146{
1147 // Avoid _PyTime_GetPerfCounter() which silently ignores errors.
1148 return _PyTime_GetPerfCounterWithInfo(t, NULL);
1149}
1150
1151
Victor Stinnerc29b5852017-11-02 07:28:27 -07001152static PyObject *
Victor Stinnerec895392012-04-29 02:41:27 +02001153time_perf_counter(PyObject *self, PyObject *unused)
1154{
Victor Stinnerae6cd7c2020-11-16 16:08:05 +01001155 _PyTime_t t;
1156 if (get_perf_counter(&t) < 0) {
1157 return NULL;
1158 }
1159 return _PyFloat_FromPyTime(t);
Victor Stinnerec895392012-04-29 02:41:27 +02001160}
1161
1162PyDoc_STRVAR(perf_counter_doc,
1163"perf_counter() -> float\n\
1164\n\
1165Performance counter for benchmarking.");
1166
Victor Stinnerae6cd7c2020-11-16 16:08:05 +01001167
Victor Stinnerc29b5852017-11-02 07:28:27 -07001168static PyObject *
1169time_perf_counter_ns(PyObject *self, PyObject *unused)
1170{
Victor Stinnerae6cd7c2020-11-16 16:08:05 +01001171 _PyTime_t t;
1172 if (get_perf_counter(&t) < 0) {
1173 return NULL;
1174 }
Victor Stinnerc29b5852017-11-02 07:28:27 -07001175 return _PyTime_AsNanosecondsObject(t);
1176}
1177
1178PyDoc_STRVAR(perf_counter_ns_doc,
1179"perf_counter_ns() -> int\n\
1180\n\
1181Performance counter for benchmarking as nanoseconds.");
1182
1183static int
1184_PyTime_GetProcessTimeWithInfo(_PyTime_t *tp, _Py_clock_info_t *info)
Victor Stinnerec895392012-04-29 02:41:27 +02001185{
1186#if defined(MS_WINDOWS)
1187 HANDLE process;
1188 FILETIME creation_time, exit_time, kernel_time, user_time;
1189 ULARGE_INTEGER large;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001190 _PyTime_t ktime, utime, t;
Victor Stinnerec895392012-04-29 02:41:27 +02001191 BOOL ok;
1192
1193 process = GetCurrentProcess();
Victor Stinnerc29b5852017-11-02 07:28:27 -07001194 ok = GetProcessTimes(process, &creation_time, &exit_time,
1195 &kernel_time, &user_time);
1196 if (!ok) {
1197 PyErr_SetFromWindowsErr(0);
1198 return -1;
1199 }
Victor Stinnerec895392012-04-29 02:41:27 +02001200
Victor Stinnerec895392012-04-29 02:41:27 +02001201 if (info) {
1202 info->implementation = "GetProcessTimes()";
1203 info->resolution = 1e-7;
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001204 info->monotonic = 1;
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001205 info->adjustable = 0;
Victor Stinnerec895392012-04-29 02:41:27 +02001206 }
Victor Stinnerc29b5852017-11-02 07:28:27 -07001207
1208 large.u.LowPart = kernel_time.dwLowDateTime;
1209 large.u.HighPart = kernel_time.dwHighDateTime;
1210 ktime = large.QuadPart;
1211
1212 large.u.LowPart = user_time.dwLowDateTime;
1213 large.u.HighPart = user_time.dwHighDateTime;
1214 utime = large.QuadPart;
1215
1216 /* ktime and utime have a resolution of 100 nanoseconds */
1217 t = _PyTime_FromNanoseconds((ktime + utime) * 100);
1218 *tp = t;
1219 return 0;
Victor Stinnerec895392012-04-29 02:41:27 +02001220#else
1221
Victor Stinnerc29b5852017-11-02 07:28:27 -07001222 /* clock_gettime */
Victor Stinnerec895392012-04-29 02:41:27 +02001223#if defined(HAVE_CLOCK_GETTIME) \
1224 && (defined(CLOCK_PROCESS_CPUTIME_ID) || defined(CLOCK_PROF))
Victor Stinnerc29b5852017-11-02 07:28:27 -07001225 struct timespec ts;
Ronald Oussoren41761932020-11-08 10:05:27 +01001226
1227 if (HAVE_CLOCK_GETTIME_RUNTIME) {
1228
Victor Stinnerec895392012-04-29 02:41:27 +02001229#ifdef CLOCK_PROF
Ronald Oussoren41761932020-11-08 10:05:27 +01001230 const clockid_t clk_id = CLOCK_PROF;
1231 const char *function = "clock_gettime(CLOCK_PROF)";
Victor Stinnerec895392012-04-29 02:41:27 +02001232#else
Ronald Oussoren41761932020-11-08 10:05:27 +01001233 const clockid_t clk_id = CLOCK_PROCESS_CPUTIME_ID;
1234 const char *function = "clock_gettime(CLOCK_PROCESS_CPUTIME_ID)";
Victor Stinnerec895392012-04-29 02:41:27 +02001235#endif
1236
Ronald Oussoren41761932020-11-08 10:05:27 +01001237 if (clock_gettime(clk_id, &ts) == 0) {
1238 if (info) {
1239 struct timespec res;
1240 info->implementation = function;
1241 info->monotonic = 1;
1242 info->adjustable = 0;
1243 if (clock_getres(clk_id, &res)) {
1244 PyErr_SetFromErrno(PyExc_OSError);
1245 return -1;
1246 }
1247 info->resolution = res.tv_sec + res.tv_nsec * 1e-9;
1248 }
1249
1250 if (_PyTime_FromTimespec(tp, &ts) < 0) {
Victor Stinnerc29b5852017-11-02 07:28:27 -07001251 return -1;
1252 }
Ronald Oussoren41761932020-11-08 10:05:27 +01001253 return 0;
Victor Stinnerec895392012-04-29 02:41:27 +02001254 }
Victor Stinnerec895392012-04-29 02:41:27 +02001255 }
1256#endif
1257
Victor Stinnerc29b5852017-11-02 07:28:27 -07001258 /* getrusage(RUSAGE_SELF) */
Victor Stinnerec895392012-04-29 02:41:27 +02001259#if defined(HAVE_SYS_RESOURCE_H)
Victor Stinnerc29b5852017-11-02 07:28:27 -07001260 struct rusage ru;
1261
Victor Stinnerec895392012-04-29 02:41:27 +02001262 if (getrusage(RUSAGE_SELF, &ru) == 0) {
Victor Stinnerc29b5852017-11-02 07:28:27 -07001263 _PyTime_t utime, stime;
1264
Victor Stinnerec895392012-04-29 02:41:27 +02001265 if (info) {
1266 info->implementation = "getrusage(RUSAGE_SELF)";
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001267 info->monotonic = 1;
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001268 info->adjustable = 0;
Victor Stinnerec895392012-04-29 02:41:27 +02001269 info->resolution = 1e-6;
1270 }
Victor Stinnerc29b5852017-11-02 07:28:27 -07001271
1272 if (_PyTime_FromTimeval(&utime, &ru.ru_utime) < 0) {
1273 return -1;
1274 }
1275 if (_PyTime_FromTimeval(&stime, &ru.ru_stime) < 0) {
1276 return -1;
1277 }
1278
vrajivk8bf5fef2019-08-26 21:13:12 -07001279 _PyTime_t total = utime + stime;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001280 *tp = total;
1281 return 0;
Victor Stinnerec895392012-04-29 02:41:27 +02001282 }
1283#endif
1284
Victor Stinnerc29b5852017-11-02 07:28:27 -07001285 /* times() */
Victor Stinnerec895392012-04-29 02:41:27 +02001286#ifdef HAVE_TIMES
Victor Stinnerc29b5852017-11-02 07:28:27 -07001287 struct tms t;
1288
Victor Stinnerec895392012-04-29 02:41:27 +02001289 if (times(&t) != (clock_t)-1) {
Victor Stinnerc29b5852017-11-02 07:28:27 -07001290 static long ticks_per_second = -1;
Victor Stinnerec895392012-04-29 02:41:27 +02001291
1292 if (ticks_per_second == -1) {
Victor Stinnerc29b5852017-11-02 07:28:27 -07001293 long freq;
Victor Stinnerec895392012-04-29 02:41:27 +02001294#if defined(HAVE_SYSCONF) && defined(_SC_CLK_TCK)
Victor Stinnerc29b5852017-11-02 07:28:27 -07001295 freq = sysconf(_SC_CLK_TCK);
1296 if (freq < 1) {
1297 freq = -1;
1298 }
Victor Stinnerec895392012-04-29 02:41:27 +02001299#elif defined(HZ)
Victor Stinnerc29b5852017-11-02 07:28:27 -07001300 freq = HZ;
Victor Stinnerec895392012-04-29 02:41:27 +02001301#else
Victor Stinnerc29b5852017-11-02 07:28:27 -07001302 freq = 60; /* magic fallback value; may be bogus */
Victor Stinnerec895392012-04-29 02:41:27 +02001303#endif
Victor Stinnerc29b5852017-11-02 07:28:27 -07001304
1305 if (freq != -1) {
1306 /* check that _PyTime_MulDiv(t, SEC_TO_NS, ticks_per_second)
1307 cannot overflow below */
Serhiy Storchakabfe4fd52018-02-09 17:31:26 +02001308#if LONG_MAX > _PyTime_MAX / SEC_TO_NS
Victor Stinnerc29b5852017-11-02 07:28:27 -07001309 if ((_PyTime_t)freq > _PyTime_MAX / SEC_TO_NS) {
1310 PyErr_SetString(PyExc_OverflowError,
1311 "_SC_CLK_TCK is too large");
1312 return -1;
1313 }
Serhiy Storchakabfe4fd52018-02-09 17:31:26 +02001314#endif
Victor Stinnerc29b5852017-11-02 07:28:27 -07001315
1316 ticks_per_second = freq;
1317 }
Victor Stinnerec895392012-04-29 02:41:27 +02001318 }
1319
1320 if (ticks_per_second != -1) {
Victor Stinnerec895392012-04-29 02:41:27 +02001321 if (info) {
1322 info->implementation = "times()";
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001323 info->monotonic = 1;
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001324 info->adjustable = 0;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001325 info->resolution = 1.0 / (double)ticks_per_second;
Victor Stinnerec895392012-04-29 02:41:27 +02001326 }
Victor Stinnerc29b5852017-11-02 07:28:27 -07001327
1328 _PyTime_t total;
1329 total = _PyTime_MulDiv(t.tms_utime, SEC_TO_NS, ticks_per_second);
1330 total += _PyTime_MulDiv(t.tms_stime, SEC_TO_NS, ticks_per_second);
1331 *tp = total;
1332 return 0;
Victor Stinnerec895392012-04-29 02:41:27 +02001333 }
1334 }
1335#endif
1336
Victor Stinnerc29b5852017-11-02 07:28:27 -07001337 /* clock */
Victor Stinner53e22bf2016-07-08 17:55:01 +02001338 /* Currently, Python 3 requires clock() to build: see issue #22624 */
Victor Stinnerc29b5852017-11-02 07:28:27 -07001339 return _PyTime_GetClockWithInfo(tp, info);
Victor Stinnerec895392012-04-29 02:41:27 +02001340#endif
1341}
1342
1343static PyObject *
1344time_process_time(PyObject *self, PyObject *unused)
1345{
Victor Stinnerc29b5852017-11-02 07:28:27 -07001346 _PyTime_t t;
1347 if (_PyTime_GetProcessTimeWithInfo(&t, NULL) < 0) {
1348 return NULL;
1349 }
1350 return _PyFloat_FromPyTime(t);
Victor Stinnerec895392012-04-29 02:41:27 +02001351}
1352
1353PyDoc_STRVAR(process_time_doc,
1354"process_time() -> float\n\
1355\n\
1356Process time for profiling: sum of the kernel and user-space CPU time.");
1357
Victor Stinnerc29b5852017-11-02 07:28:27 -07001358static PyObject *
1359time_process_time_ns(PyObject *self, PyObject *unused)
1360{
1361 _PyTime_t t;
1362 if (_PyTime_GetProcessTimeWithInfo(&t, NULL) < 0) {
1363 return NULL;
1364 }
1365 return _PyTime_AsNanosecondsObject(t);
1366}
1367
1368PyDoc_STRVAR(process_time_ns_doc,
1369"process_time() -> int\n\
1370\n\
1371Process time for profiling as nanoseconds:\n\
1372sum of the kernel and user-space CPU time.");
1373
Victor Stinnerec895392012-04-29 02:41:27 +02001374
Antoine Pitrou4bd41c92017-11-15 22:52:21 +01001375#if defined(MS_WINDOWS)
1376#define HAVE_THREAD_TIME
1377static int
1378_PyTime_GetThreadTimeWithInfo(_PyTime_t *tp, _Py_clock_info_t *info)
1379{
1380 HANDLE thread;
1381 FILETIME creation_time, exit_time, kernel_time, user_time;
1382 ULARGE_INTEGER large;
1383 _PyTime_t ktime, utime, t;
1384 BOOL ok;
1385
1386 thread = GetCurrentThread();
1387 ok = GetThreadTimes(thread, &creation_time, &exit_time,
1388 &kernel_time, &user_time);
1389 if (!ok) {
1390 PyErr_SetFromWindowsErr(0);
1391 return -1;
1392 }
1393
1394 if (info) {
1395 info->implementation = "GetThreadTimes()";
1396 info->resolution = 1e-7;
1397 info->monotonic = 1;
1398 info->adjustable = 0;
1399 }
1400
1401 large.u.LowPart = kernel_time.dwLowDateTime;
1402 large.u.HighPart = kernel_time.dwHighDateTime;
1403 ktime = large.QuadPart;
1404
1405 large.u.LowPart = user_time.dwLowDateTime;
1406 large.u.HighPart = user_time.dwHighDateTime;
1407 utime = large.QuadPart;
1408
1409 /* ktime and utime have a resolution of 100 nanoseconds */
1410 t = _PyTime_FromNanoseconds((ktime + utime) * 100);
1411 *tp = t;
1412 return 0;
1413}
1414
Batuhan Taskaya45410862020-05-16 12:39:09 +03001415#elif defined(_AIX)
1416#define HAVE_THREAD_TIME
1417static int
1418_PyTime_GetThreadTimeWithInfo(_PyTime_t *tp, _Py_clock_info_t *info)
1419{
1420 /* bpo-40192: On AIX, thread_cputime() is preferred: it has nanosecond
1421 resolution, whereas clock_gettime(CLOCK_THREAD_CPUTIME_ID)
1422 has a resolution of 10 ms. */
1423 thread_cputime_t tc;
1424 if (thread_cputime(-1, &tc) != 0) {
1425 PyErr_SetFromErrno(PyExc_OSError);
1426 return -1;
1427 }
1428
1429 if (info) {
1430 info->implementation = "thread_cputime()";
1431 info->monotonic = 1;
1432 info->adjustable = 0;
1433 info->resolution = 1e-9;
1434 }
1435 *tp = _PyTime_FromNanoseconds(tc.stime + tc.utime);
1436 return 0;
1437}
1438
Jakub Kulík95686222020-11-03 00:10:01 +01001439#elif defined(__sun) && defined(__SVR4)
1440#define HAVE_THREAD_TIME
1441static int
1442_PyTime_GetThreadTimeWithInfo(_PyTime_t *tp, _Py_clock_info_t *info)
1443{
1444 /* bpo-35455: On Solaris, CLOCK_THREAD_CPUTIME_ID clock is not always
1445 available; use gethrvtime() to substitute this functionality. */
1446 if (info) {
1447 info->implementation = "gethrvtime()";
1448 info->resolution = 1e-9;
1449 info->monotonic = 1;
1450 info->adjustable = 0;
1451 }
1452 *tp = _PyTime_FromNanoseconds(gethrvtime());
1453 return 0;
1454}
1455
Antoine Pitrou4bd41c92017-11-15 22:52:21 +01001456#elif defined(HAVE_CLOCK_GETTIME) && defined(CLOCK_PROCESS_CPUTIME_ID)
1457#define HAVE_THREAD_TIME
Ronald Oussoren41761932020-11-08 10:05:27 +01001458
1459#if defined(__APPLE__) && defined(__has_attribute) && __has_attribute(availability)
1460static int
Victor Stinnerae6cd7c2020-11-16 16:08:05 +01001461_PyTime_GetThreadTimeWithInfo(_PyTime_t *tp, _Py_clock_info_t *info)
Ronald Oussoren41761932020-11-08 10:05:27 +01001462 __attribute__((availability(macos, introduced=10.12)))
1463 __attribute__((availability(ios, introduced=10.0)))
1464 __attribute__((availability(tvos, introduced=10.0)))
1465 __attribute__((availability(watchos, introduced=3.0)));
1466#endif
1467
Antoine Pitrou4bd41c92017-11-15 22:52:21 +01001468static int
1469_PyTime_GetThreadTimeWithInfo(_PyTime_t *tp, _Py_clock_info_t *info)
1470{
1471 struct timespec ts;
1472 const clockid_t clk_id = CLOCK_THREAD_CPUTIME_ID;
1473 const char *function = "clock_gettime(CLOCK_THREAD_CPUTIME_ID)";
1474
1475 if (clock_gettime(clk_id, &ts)) {
1476 PyErr_SetFromErrno(PyExc_OSError);
1477 return -1;
1478 }
1479 if (info) {
1480 struct timespec res;
1481 info->implementation = function;
1482 info->monotonic = 1;
1483 info->adjustable = 0;
1484 if (clock_getres(clk_id, &res)) {
1485 PyErr_SetFromErrno(PyExc_OSError);
1486 return -1;
1487 }
1488 info->resolution = res.tv_sec + res.tv_nsec * 1e-9;
1489 }
1490
1491 if (_PyTime_FromTimespec(tp, &ts) < 0) {
1492 return -1;
1493 }
1494 return 0;
1495}
1496#endif
1497
1498#ifdef HAVE_THREAD_TIME
Ronald Oussoren41761932020-11-08 10:05:27 +01001499#ifdef __APPLE__
Victor Stinnerae6cd7c2020-11-16 16:08:05 +01001500/*
Ronald Oussoren41761932020-11-08 10:05:27 +01001501 * The clock_* functions will be removed from the module
1502 * dict entirely when the C API is not available.
1503 */
1504#pragma clang diagnostic push
1505#pragma clang diagnostic ignored "-Wunguarded-availability"
1506#endif
1507
Antoine Pitrou4bd41c92017-11-15 22:52:21 +01001508static PyObject *
1509time_thread_time(PyObject *self, PyObject *unused)
1510{
1511 _PyTime_t t;
1512 if (_PyTime_GetThreadTimeWithInfo(&t, NULL) < 0) {
1513 return NULL;
1514 }
1515 return _PyFloat_FromPyTime(t);
1516}
1517
1518PyDoc_STRVAR(thread_time_doc,
1519"thread_time() -> float\n\
1520\n\
1521Thread time for profiling: sum of the kernel and user-space CPU time.");
1522
1523static PyObject *
1524time_thread_time_ns(PyObject *self, PyObject *unused)
1525{
1526 _PyTime_t t;
1527 if (_PyTime_GetThreadTimeWithInfo(&t, NULL) < 0) {
1528 return NULL;
1529 }
1530 return _PyTime_AsNanosecondsObject(t);
1531}
1532
1533PyDoc_STRVAR(thread_time_ns_doc,
1534"thread_time() -> int\n\
1535\n\
1536Thread time for profiling as nanoseconds:\n\
1537sum of the kernel and user-space CPU time.");
Ronald Oussoren41761932020-11-08 10:05:27 +01001538
1539#ifdef __APPLE__
1540#pragma clang diagnostic pop
1541#endif
1542
Antoine Pitrou4bd41c92017-11-15 22:52:21 +01001543#endif
1544
1545
Victor Stinnerec895392012-04-29 02:41:27 +02001546static PyObject *
1547time_get_clock_info(PyObject *self, PyObject *args)
1548{
1549 char *name;
Victor Stinnerec895392012-04-29 02:41:27 +02001550 _Py_clock_info_t info;
Victor Stinnerbda4b882012-06-12 22:11:44 +02001551 PyObject *obj = NULL, *dict, *ns;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001552 _PyTime_t t;
Victor Stinnerec895392012-04-29 02:41:27 +02001553
Victor Stinnerc29b5852017-11-02 07:28:27 -07001554 if (!PyArg_ParseTuple(args, "s:get_clock_info", &name)) {
Victor Stinnerec895392012-04-29 02:41:27 +02001555 return NULL;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001556 }
Victor Stinnerec895392012-04-29 02:41:27 +02001557
1558#ifdef Py_DEBUG
1559 info.implementation = NULL;
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001560 info.monotonic = -1;
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001561 info.adjustable = -1;
Victor Stinnerec895392012-04-29 02:41:27 +02001562 info.resolution = -1.0;
1563#else
1564 info.implementation = "";
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001565 info.monotonic = 0;
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001566 info.adjustable = 0;
Victor Stinnerec895392012-04-29 02:41:27 +02001567 info.resolution = 1.0;
1568#endif
1569
Victor Stinnerc29b5852017-11-02 07:28:27 -07001570 if (strcmp(name, "time") == 0) {
1571 if (_PyTime_GetSystemClockWithInfo(&t, &info) < 0) {
1572 return NULL;
1573 }
1574 }
Victor Stinnerc29b5852017-11-02 07:28:27 -07001575 else if (strcmp(name, "monotonic") == 0) {
1576 if (_PyTime_GetMonotonicClockWithInfo(&t, &info) < 0) {
1577 return NULL;
1578 }
1579 }
1580 else if (strcmp(name, "perf_counter") == 0) {
1581 if (_PyTime_GetPerfCounterWithInfo(&t, &info) < 0) {
1582 return NULL;
1583 }
1584 }
1585 else if (strcmp(name, "process_time") == 0) {
1586 if (_PyTime_GetProcessTimeWithInfo(&t, &info) < 0) {
1587 return NULL;
1588 }
1589 }
Antoine Pitrou4bd41c92017-11-15 22:52:21 +01001590#ifdef HAVE_THREAD_TIME
1591 else if (strcmp(name, "thread_time") == 0) {
Ronald Oussoren41761932020-11-08 10:05:27 +01001592
1593#ifdef __APPLE__
1594 if (HAVE_CLOCK_GETTIME_RUNTIME) {
1595#endif
1596 if (_PyTime_GetThreadTimeWithInfo(&t, &info) < 0) {
1597 return NULL;
1598 }
1599#ifdef __APPLE__
1600 } else {
1601 PyErr_SetString(PyExc_ValueError, "unknown clock");
Antoine Pitrou4bd41c92017-11-15 22:52:21 +01001602 return NULL;
1603 }
Ronald Oussoren41761932020-11-08 10:05:27 +01001604#endif
Antoine Pitrou4bd41c92017-11-15 22:52:21 +01001605 }
1606#endif
Victor Stinnerec895392012-04-29 02:41:27 +02001607 else {
1608 PyErr_SetString(PyExc_ValueError, "unknown clock");
1609 return NULL;
1610 }
Victor Stinnerec895392012-04-29 02:41:27 +02001611
Victor Stinnerbda4b882012-06-12 22:11:44 +02001612 dict = PyDict_New();
Victor Stinnerc29b5852017-11-02 07:28:27 -07001613 if (dict == NULL) {
Victor Stinnerec895392012-04-29 02:41:27 +02001614 return NULL;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001615 }
Victor Stinnerec895392012-04-29 02:41:27 +02001616
1617 assert(info.implementation != NULL);
1618 obj = PyUnicode_FromString(info.implementation);
Victor Stinnerc29b5852017-11-02 07:28:27 -07001619 if (obj == NULL) {
Victor Stinnerec895392012-04-29 02:41:27 +02001620 goto error;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001621 }
1622 if (PyDict_SetItemString(dict, "implementation", obj) == -1) {
Victor Stinnerbda4b882012-06-12 22:11:44 +02001623 goto error;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001624 }
Victor Stinnerbda4b882012-06-12 22:11:44 +02001625 Py_CLEAR(obj);
Victor Stinnerec895392012-04-29 02:41:27 +02001626
Benjamin Peterson49a69e42012-05-01 09:38:34 -04001627 assert(info.monotonic != -1);
1628 obj = PyBool_FromLong(info.monotonic);
Victor Stinnerc29b5852017-11-02 07:28:27 -07001629 if (obj == NULL) {
Victor Stinnerec895392012-04-29 02:41:27 +02001630 goto error;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001631 }
1632 if (PyDict_SetItemString(dict, "monotonic", obj) == -1) {
Victor Stinnerbda4b882012-06-12 22:11:44 +02001633 goto error;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001634 }
Victor Stinnerbda4b882012-06-12 22:11:44 +02001635 Py_CLEAR(obj);
Victor Stinnerec895392012-04-29 02:41:27 +02001636
Victor Stinner2b89fdf2012-06-12 22:46:37 +02001637 assert(info.adjustable != -1);
1638 obj = PyBool_FromLong(info.adjustable);
Victor Stinnerc29b5852017-11-02 07:28:27 -07001639 if (obj == NULL) {
Victor Stinnerec895392012-04-29 02:41:27 +02001640 goto error;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001641 }
1642 if (PyDict_SetItemString(dict, "adjustable", obj) == -1) {
Victor Stinnerbda4b882012-06-12 22:11:44 +02001643 goto error;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001644 }
Victor Stinnerbda4b882012-06-12 22:11:44 +02001645 Py_CLEAR(obj);
Victor Stinnerec895392012-04-29 02:41:27 +02001646
1647 assert(info.resolution > 0.0);
1648 assert(info.resolution <= 1.0);
1649 obj = PyFloat_FromDouble(info.resolution);
Victor Stinnerc29b5852017-11-02 07:28:27 -07001650 if (obj == NULL) {
Victor Stinnerec895392012-04-29 02:41:27 +02001651 goto error;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001652 }
1653 if (PyDict_SetItemString(dict, "resolution", obj) == -1) {
Victor Stinnerbda4b882012-06-12 22:11:44 +02001654 goto error;
Victor Stinnerc29b5852017-11-02 07:28:27 -07001655 }
Victor Stinnerbda4b882012-06-12 22:11:44 +02001656 Py_CLEAR(obj);
Victor Stinnerec895392012-04-29 02:41:27 +02001657
Victor Stinnerbda4b882012-06-12 22:11:44 +02001658 ns = _PyNamespace_New(dict);
1659 Py_DECREF(dict);
1660 return ns;
Victor Stinnerec895392012-04-29 02:41:27 +02001661
1662error:
Victor Stinnerbda4b882012-06-12 22:11:44 +02001663 Py_DECREF(dict);
1664 Py_XDECREF(obj);
Victor Stinnerec895392012-04-29 02:41:27 +02001665 return NULL;
1666}
1667
1668PyDoc_STRVAR(get_clock_info_doc,
1669"get_clock_info(name: str) -> dict\n\
1670\n\
1671Get information of the specified clock.");
Victor Stinner8b302012012-02-07 23:29:46 +01001672
Benjamin Petersonc510c6b2018-09-20 19:52:18 -07001673#ifndef HAVE_DECL_TZNAME
Victor Stinner1fb399b2018-09-17 13:56:17 -07001674static void
1675get_zone(char *zone, int n, struct tm *p)
1676{
1677#ifdef HAVE_STRUCT_TM_TM_ZONE
1678 strncpy(zone, p->tm_zone ? p->tm_zone : " ", n);
1679#else
1680 tzset();
1681 strftime(zone, n, "%Z", p);
1682#endif
1683}
1684
Victor Stinner503ce5c2018-12-01 00:39:36 +01001685static time_t
Victor Stinner1fb399b2018-09-17 13:56:17 -07001686get_gmtoff(time_t t, struct tm *p)
1687{
1688#ifdef HAVE_STRUCT_TM_TM_ZONE
1689 return p->tm_gmtoff;
1690#else
1691 return timegm(p) - t;
1692#endif
1693}
Benjamin Petersonc510c6b2018-09-20 19:52:18 -07001694#endif // !HAVE_DECL_TZNAME
Victor Stinner1fb399b2018-09-17 13:56:17 -07001695
Victor Stinner503ce5c2018-12-01 00:39:36 +01001696static int
Victor Stinner3bb150d2018-12-03 13:45:38 +01001697init_timezone(PyObject *m)
Victor Stinner503ce5c2018-12-01 00:39:36 +01001698{
1699 assert(!PyErr_Occurred());
1700
Martin v. Löwis1a214512008-06-11 05:26:20 +00001701 /* This code moved from PyInit_time wholesale to allow calling it from
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001702 time_tzset. In the future, some parts of it can be moved back
1703 (for platforms that don't HAVE_WORKING_TZSET, when we know what they
1704 are), and the extraneous calls to tzset(3) should be removed.
1705 I haven't done this yet, as I don't want to change this code as
1706 little as possible when introducing the time.tzset and time.tzsetwall
1707 methods. This should simply be a method of doing the following once,
1708 at the top of this function and removing the call to tzset() from
1709 time_tzset():
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001710
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001711 #ifdef HAVE_TZSET
1712 tzset()
1713 #endif
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001714
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001715 And I'm lazy and hate C so nyer.
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001716 */
Benjamin Petersonc510c6b2018-09-20 19:52:18 -07001717#ifdef HAVE_DECL_TZNAME
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001718 PyObject *otz0, *otz1;
1719 tzset();
Zackery Spytz6673dec2019-02-25 16:56:44 -07001720 PyModule_AddIntConstant(m, "timezone", _Py_timezone);
Guido van Rossumb6775db1994-08-01 11:34:53 +00001721#ifdef HAVE_ALTZONE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001722 PyModule_AddIntConstant(m, "altzone", altzone);
Guido van Rossumb6775db1994-08-01 11:34:53 +00001723#else
Zackery Spytz6673dec2019-02-25 16:56:44 -07001724 PyModule_AddIntConstant(m, "altzone", _Py_timezone-3600);
Guido van Rossumb6775db1994-08-01 11:34:53 +00001725#endif
Zackery Spytz6673dec2019-02-25 16:56:44 -07001726 PyModule_AddIntConstant(m, "daylight", _Py_daylight);
Paul Monsonb4c7def2019-06-12 16:13:27 -07001727#ifdef MS_WINDOWS
1728 TIME_ZONE_INFORMATION tzinfo = {0};
1729 GetTimeZoneInformation(&tzinfo);
1730 otz0 = PyUnicode_FromWideChar(tzinfo.StandardName, -1);
1731 if (otz0 == NULL) {
1732 return -1;
1733 }
1734 otz1 = PyUnicode_FromWideChar(tzinfo.DaylightName, -1);
1735 if (otz1 == NULL) {
1736 Py_DECREF(otz0);
1737 return -1;
1738 }
1739#else
Zackery Spytz6673dec2019-02-25 16:56:44 -07001740 otz0 = PyUnicode_DecodeLocale(_Py_tzname[0], "surrogateescape");
Benjamin Petersonc510c6b2018-09-20 19:52:18 -07001741 if (otz0 == NULL) {
Victor Stinnerab661492018-12-03 12:02:43 +01001742 return -1;
Victor Stinner1fb399b2018-09-17 13:56:17 -07001743 }
Zackery Spytz6673dec2019-02-25 16:56:44 -07001744 otz1 = PyUnicode_DecodeLocale(_Py_tzname[1], "surrogateescape");
Benjamin Petersonc510c6b2018-09-20 19:52:18 -07001745 if (otz1 == NULL) {
1746 Py_DECREF(otz0);
Victor Stinnerab661492018-12-03 12:02:43 +01001747 return -1;
Benjamin Petersonc510c6b2018-09-20 19:52:18 -07001748 }
Paul Monsonb4c7def2019-06-12 16:13:27 -07001749#endif // MS_WINDOWS
Benjamin Petersonc510c6b2018-09-20 19:52:18 -07001750 PyObject *tzname_obj = Py_BuildValue("(NN)", otz0, otz1);
Victor Stinnerab661492018-12-03 12:02:43 +01001751 if (tzname_obj == NULL) {
1752 return -1;
1753 }
Benjamin Petersonc510c6b2018-09-20 19:52:18 -07001754 PyModule_AddObject(m, "tzname", tzname_obj);
1755#else // !HAVE_DECL_TZNAME
1756 static const time_t YEAR = (365 * 24 + 6) * 3600;
1757 time_t t;
1758 struct tm p;
Victor Stinner503ce5c2018-12-01 00:39:36 +01001759 time_t janzone_t, julyzone_t;
Benjamin Petersonc510c6b2018-09-20 19:52:18 -07001760 char janname[10], julyname[10];
1761 t = (time((time_t *)0) / YEAR) * YEAR;
1762 _PyTime_localtime(t, &p);
1763 get_zone(janname, 9, &p);
Victor Stinner503ce5c2018-12-01 00:39:36 +01001764 janzone_t = -get_gmtoff(t, &p);
Benjamin Petersonc510c6b2018-09-20 19:52:18 -07001765 janname[9] = '\0';
1766 t += YEAR/2;
1767 _PyTime_localtime(t, &p);
1768 get_zone(julyname, 9, &p);
Victor Stinner503ce5c2018-12-01 00:39:36 +01001769 julyzone_t = -get_gmtoff(t, &p);
Benjamin Petersonc510c6b2018-09-20 19:52:18 -07001770 julyname[9] = '\0';
1771
Victor Stinner503ce5c2018-12-01 00:39:36 +01001772 /* Sanity check, don't check for the validity of timezones.
1773 In practice, it should be more in range -12 hours .. +14 hours. */
1774#define MAX_TIMEZONE (48 * 3600)
1775 if (janzone_t < -MAX_TIMEZONE || janzone_t > MAX_TIMEZONE
1776 || julyzone_t < -MAX_TIMEZONE || julyzone_t > MAX_TIMEZONE)
1777 {
1778 PyErr_SetString(PyExc_RuntimeError, "invalid GMT offset");
1779 return -1;
1780 }
1781 int janzone = (int)janzone_t;
1782 int julyzone = (int)julyzone_t;
1783
Benjamin Petersonc510c6b2018-09-20 19:52:18 -07001784 PyObject *tzname_obj;
1785 if (janzone < julyzone) {
1786 /* DST is reversed in the southern hemisphere */
1787 PyModule_AddIntConstant(m, "timezone", julyzone);
1788 PyModule_AddIntConstant(m, "altzone", janzone);
1789 PyModule_AddIntConstant(m, "daylight", janzone != julyzone);
1790 tzname_obj = Py_BuildValue("(zz)", julyname, janname);
1791 } else {
1792 PyModule_AddIntConstant(m, "timezone", janzone);
1793 PyModule_AddIntConstant(m, "altzone", julyzone);
1794 PyModule_AddIntConstant(m, "daylight", janzone != julyzone);
1795 tzname_obj = Py_BuildValue("(zz)", janname, julyname);
1796 }
Victor Stinner503ce5c2018-12-01 00:39:36 +01001797 if (tzname_obj == NULL) {
1798 return -1;
1799 }
Benjamin Petersonc510c6b2018-09-20 19:52:18 -07001800 PyModule_AddObject(m, "tzname", tzname_obj);
1801#endif // !HAVE_DECL_TZNAME
Victor Stinner503ce5c2018-12-01 00:39:36 +01001802
1803 if (PyErr_Occurred()) {
1804 return -1;
1805 }
1806 return 0;
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001807}
1808
1809
1810static PyMethodDef time_methods[] = {
Victor Stinner4195b5c2012-02-08 23:03:19 +01001811 {"time", time_time, METH_NOARGS, time_doc},
Victor Stinnerc29b5852017-11-02 07:28:27 -07001812 {"time_ns", time_time_ns, METH_NOARGS, time_ns_doc},
Victor Stinnere0be4232011-10-25 13:06:09 +02001813#ifdef HAVE_CLOCK_GETTIME
Victor Stinner4195b5c2012-02-08 23:03:19 +01001814 {"clock_gettime", time_clock_gettime, METH_VARARGS, clock_gettime_doc},
Victor Stinnerc29b5852017-11-02 07:28:27 -07001815 {"clock_gettime_ns",time_clock_gettime_ns, METH_VARARGS, clock_gettime_ns_doc},
Benjamin Peterson37098cd2016-09-13 22:55:09 -07001816#endif
1817#ifdef HAVE_CLOCK_SETTIME
Victor Stinner30d79472012-04-03 00:45:07 +02001818 {"clock_settime", time_clock_settime, METH_VARARGS, clock_settime_doc},
Victor Stinnerc29b5852017-11-02 07:28:27 -07001819 {"clock_settime_ns",time_clock_settime_ns, METH_VARARGS, clock_settime_ns_doc},
Benjamin Peterson37098cd2016-09-13 22:55:09 -07001820#endif
1821#ifdef HAVE_CLOCK_GETRES
Victor Stinner4195b5c2012-02-08 23:03:19 +01001822 {"clock_getres", time_clock_getres, METH_VARARGS, clock_getres_doc},
Victor Stinnere0be4232011-10-25 13:06:09 +02001823#endif
pdoxe14679c2017-10-05 00:01:56 -07001824#ifdef HAVE_PTHREAD_GETCPUCLOCKID
1825 {"pthread_getcpuclockid", time_pthread_getcpuclockid, METH_VARARGS, pthread_getcpuclockid_doc},
1826#endif
Victor Stinnercb29f012015-03-27 13:31:18 +01001827 {"sleep", time_sleep, METH_O, sleep_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001828 {"gmtime", time_gmtime, METH_VARARGS, gmtime_doc},
1829 {"localtime", time_localtime, METH_VARARGS, localtime_doc},
1830 {"asctime", time_asctime, METH_VARARGS, asctime_doc},
1831 {"ctime", time_ctime, METH_VARARGS, ctime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001832#ifdef HAVE_MKTIME
Victor Stinner4195b5c2012-02-08 23:03:19 +01001833 {"mktime", time_mktime, METH_O, mktime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001834#endif
1835#ifdef HAVE_STRFTIME
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001836 {"strftime", time_strftime, METH_VARARGS, strftime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001837#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001838 {"strptime", time_strptime, METH_VARARGS, strptime_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001839#ifdef HAVE_WORKING_TZSET
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001840 {"tzset", time_tzset, METH_NOARGS, tzset_doc},
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001841#endif
Victor Stinnerec895392012-04-29 02:41:27 +02001842 {"monotonic", time_monotonic, METH_NOARGS, monotonic_doc},
Victor Stinnerc29b5852017-11-02 07:28:27 -07001843 {"monotonic_ns", time_monotonic_ns, METH_NOARGS, monotonic_ns_doc},
Victor Stinnerec895392012-04-29 02:41:27 +02001844 {"process_time", time_process_time, METH_NOARGS, process_time_doc},
Victor Stinnerc29b5852017-11-02 07:28:27 -07001845 {"process_time_ns", time_process_time_ns, METH_NOARGS, process_time_ns_doc},
Antoine Pitrou4bd41c92017-11-15 22:52:21 +01001846#ifdef HAVE_THREAD_TIME
1847 {"thread_time", time_thread_time, METH_NOARGS, thread_time_doc},
1848 {"thread_time_ns", time_thread_time_ns, METH_NOARGS, thread_time_ns_doc},
1849#endif
Victor Stinnerec895392012-04-29 02:41:27 +02001850 {"perf_counter", time_perf_counter, METH_NOARGS, perf_counter_doc},
Victor Stinnerc29b5852017-11-02 07:28:27 -07001851 {"perf_counter_ns", time_perf_counter_ns, METH_NOARGS, perf_counter_ns_doc},
Victor Stinnerec895392012-04-29 02:41:27 +02001852 {"get_clock_info", time_get_clock_info, METH_VARARGS, get_clock_info_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001853 {NULL, NULL} /* sentinel */
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001854};
1855
1856
1857PyDoc_STRVAR(module_doc,
1858"This module provides various functions to manipulate time values.\n\
1859\n\
1860There are two standard representations of time. One is the number\n\
1861of seconds since the Epoch, in UTC (a.k.a. GMT). It may be an integer\n\
1862or a floating point number (to represent fractions of seconds).\n\
1863The Epoch is system-defined; on Unix, it is generally January 1st, 1970.\n\
1864The actual value can be retrieved by calling gmtime(0).\n\
1865\n\
1866The other representation is a tuple of 9 integers giving local time.\n\
1867The tuple items are:\n\
Alexander Belopolsky03163ac2011-05-02 12:20:52 -04001868 year (including century, e.g. 1998)\n\
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001869 month (1-12)\n\
1870 day (1-31)\n\
1871 hours (0-23)\n\
1872 minutes (0-59)\n\
1873 seconds (0-59)\n\
1874 weekday (0-6, Monday is 0)\n\
1875 Julian day (day in the year, 1-366)\n\
1876 DST (Daylight Savings Time) flag (-1, 0 or 1)\n\
1877If the DST flag is 0, the time is given in the regular time zone;\n\
1878if it is 1, the time is given in the DST time zone;\n\
Cheryl Sabella703ff382017-10-11 09:29:14 -04001879if it is -1, mktime() should guess based on the date and time.\n");
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001880
1881
Paulo Henrique Silvabd409bb2020-03-23 15:58:23 -03001882static int
1883time_exec(PyObject *module)
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001884{
Ronald Oussoren41761932020-11-08 10:05:27 +01001885#if defined(__APPLE__) && defined(HAVE_CLOCK_GETTIME)
1886 if (HAVE_CLOCK_GETTIME_RUNTIME) {
1887 /* pass: ^^^ cannot use '!' here */
1888 } else {
1889 PyObject* dct = PyModule_GetDict(module);
1890 if (dct == NULL) {
1891 return -1;
1892 }
1893
1894 if (PyDict_DelItemString(dct, "clock_gettime") == -1) {
1895 PyErr_Clear();
1896 }
1897 if (PyDict_DelItemString(dct, "clock_gettime_ns") == -1) {
1898 PyErr_Clear();
1899 }
1900 if (PyDict_DelItemString(dct, "clock_settime") == -1) {
1901 PyErr_Clear();
1902 }
1903 if (PyDict_DelItemString(dct, "clock_settime_ns") == -1) {
1904 PyErr_Clear();
1905 }
1906 if (PyDict_DelItemString(dct, "clock_getres") == -1) {
1907 PyErr_Clear();
1908 }
1909 }
1910#endif
1911#if defined(__APPLE__) && defined(HAVE_THREAD_TIME)
1912 if (HAVE_CLOCK_GETTIME_RUNTIME) {
1913 /* pass: ^^^ cannot use '!' here */
1914 } else {
1915 PyObject* dct = PyModule_GetDict(module);
1916
1917 if (PyDict_DelItemString(dct, "thread_time") == -1) {
1918 PyErr_Clear();
1919 }
1920 if (PyDict_DelItemString(dct, "thread_time_ns") == -1) {
1921 PyErr_Clear();
1922 }
1923 }
1924#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001925 /* Set, or reset, module variables like time.timezone */
Paulo Henrique Silvabd409bb2020-03-23 15:58:23 -03001926 if (init_timezone(module) < 0) {
1927 return -1;
Victor Stinner503ce5c2018-12-01 00:39:36 +01001928 }
Guido van Rossumd11b62e2003-03-14 21:51:36 +00001929
Max Bélanger94451182018-10-20 17:07:54 -07001930#if defined(HAVE_CLOCK_GETTIME) || defined(HAVE_CLOCK_SETTIME) || defined(HAVE_CLOCK_GETRES)
Ronald Oussoren41761932020-11-08 10:05:27 +01001931 if (HAVE_CLOCK_GETTIME_RUNTIME) {
Max Bélanger94451182018-10-20 17:07:54 -07001932
Benjamin Peterson37098cd2016-09-13 22:55:09 -07001933#ifdef CLOCK_REALTIME
Ronald Oussoren41761932020-11-08 10:05:27 +01001934 if (PyModule_AddIntMacro(module, CLOCK_REALTIME) < 0) {
1935 return -1;
1936 }
Benjamin Peterson37098cd2016-09-13 22:55:09 -07001937#endif
Ronald Oussoren41761932020-11-08 10:05:27 +01001938
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -04001939#ifdef CLOCK_MONOTONIC
Ronald Oussoren41761932020-11-08 10:05:27 +01001940
1941 if (PyModule_AddIntMacro(module, CLOCK_MONOTONIC) < 0) {
1942 return -1;
1943 }
1944
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -04001945#endif
1946#ifdef CLOCK_MONOTONIC_RAW
Ronald Oussoren41761932020-11-08 10:05:27 +01001947 if (PyModule_AddIntMacro(module, CLOCK_MONOTONIC_RAW) < 0) {
1948 return -1;
1949 }
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -04001950#endif
Ronald Oussoren41761932020-11-08 10:05:27 +01001951
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -04001952#ifdef CLOCK_HIGHRES
Ronald Oussoren41761932020-11-08 10:05:27 +01001953 if (PyModule_AddIntMacro(module, CLOCK_HIGHRES) < 0) {
1954 return -1;
1955 }
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -04001956#endif
1957#ifdef CLOCK_PROCESS_CPUTIME_ID
Ronald Oussoren41761932020-11-08 10:05:27 +01001958 if (PyModule_AddIntMacro(module, CLOCK_PROCESS_CPUTIME_ID) < 0) {
1959 return -1;
1960 }
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -04001961#endif
Ronald Oussoren41761932020-11-08 10:05:27 +01001962
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -04001963#ifdef CLOCK_THREAD_CPUTIME_ID
Ronald Oussoren41761932020-11-08 10:05:27 +01001964 if (PyModule_AddIntMacro(module, CLOCK_THREAD_CPUTIME_ID) < 0) {
1965 return -1;
1966 }
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -04001967#endif
Victor Stinnera64ce972017-11-02 04:19:19 -07001968#ifdef CLOCK_PROF
Ronald Oussoren41761932020-11-08 10:05:27 +01001969 if (PyModule_AddIntMacro(module, CLOCK_PROF) < 0) {
1970 return -1;
1971 }
Victor Stinnera64ce972017-11-02 04:19:19 -07001972#endif
1973#ifdef CLOCK_BOOTTIME
Ronald Oussoren41761932020-11-08 10:05:27 +01001974 if (PyModule_AddIntMacro(module, CLOCK_BOOTTIME) < 0) {
1975 return -1;
1976 }
Victor Stinnera64ce972017-11-02 04:19:19 -07001977#endif
Russell Owen60000872020-03-23 20:41:40 -07001978#ifdef CLOCK_TAI
Ronald Oussoren41761932020-11-08 10:05:27 +01001979 if (PyModule_AddIntMacro(module, CLOCK_TAI) < 0) {
1980 return -1;
1981 }
Russell Owen60000872020-03-23 20:41:40 -07001982#endif
Victor Stinnera64ce972017-11-02 04:19:19 -07001983#ifdef CLOCK_UPTIME
Ronald Oussoren41761932020-11-08 10:05:27 +01001984 if (PyModule_AddIntMacro(module, CLOCK_UPTIME) < 0) {
1985 return -1;
1986 }
Victor Stinnera64ce972017-11-02 04:19:19 -07001987#endif
Joannah Nanjekye572168a2019-01-10 19:56:38 +03001988#ifdef CLOCK_UPTIME_RAW
Ronald Oussoren41761932020-11-08 10:05:27 +01001989
1990 if (PyModule_AddIntMacro(module, CLOCK_UPTIME_RAW) < 0) {
1991 return -1;
1992 }
Joannah Nanjekye572168a2019-01-10 19:56:38 +03001993#endif
Ronald Oussoren41761932020-11-08 10:05:27 +01001994 }
Alexander Belopolsky18f3a9b2016-09-11 22:55:16 -04001995
Max Bélanger94451182018-10-20 17:07:54 -07001996#endif /* defined(HAVE_CLOCK_GETTIME) || defined(HAVE_CLOCK_SETTIME) || defined(HAVE_CLOCK_GETRES) */
1997
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001998 if (!initialized) {
Victor Stinner1c8f0592013-07-22 22:24:54 +02001999 if (PyStructSequence_InitType2(&StructTimeType,
Hai Shi196f1eb2020-03-12 00:56:08 +08002000 &struct_time_type_desc) < 0) {
Paulo Henrique Silvabd409bb2020-03-23 15:58:23 -03002001 return -1;
Hai Shi196f1eb2020-03-12 00:56:08 +08002002 }
2003 }
Paulo Henrique Silvabd409bb2020-03-23 15:58:23 -03002004 if (PyModule_AddIntConstant(module, "_STRUCT_TM_ITEMS", 11)) {
2005 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002006 }
2007 Py_INCREF(&StructTimeType);
Paulo Henrique Silvabd409bb2020-03-23 15:58:23 -03002008 if (PyModule_AddObject(module, "struct_time", (PyObject*) &StructTimeType)) {
Hai Shi196f1eb2020-03-12 00:56:08 +08002009 Py_DECREF(&StructTimeType);
Paulo Henrique Silvabd409bb2020-03-23 15:58:23 -03002010 return -1;
Hai Shi196f1eb2020-03-12 00:56:08 +08002011 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002012 initialized = 1;
Benjamin Peterson5633c4f2018-09-14 09:09:04 -07002013
2014#if defined(__linux__) && !defined(__GLIBC__)
2015 struct tm tm;
Benjamin Petersonb93062b2018-09-14 10:39:13 -07002016 const time_t zero = 0;
2017 if (gmtime_r(&zero, &tm) != NULL)
Benjamin Peterson5633c4f2018-09-14 09:09:04 -07002018 utc_string = tm.tm_zone;
2019#endif
2020
Paulo Henrique Silvabd409bb2020-03-23 15:58:23 -03002021 return 0;
2022}
Hai Shi196f1eb2020-03-12 00:56:08 +08002023
Paulo Henrique Silvabd409bb2020-03-23 15:58:23 -03002024static struct PyModuleDef_Slot time_slots[] = {
2025 {Py_mod_exec, time_exec},
2026 {0, NULL}
2027};
2028
2029static struct PyModuleDef timemodule = {
2030 PyModuleDef_HEAD_INIT,
2031 "time",
2032 module_doc,
2033 0,
2034 time_methods,
2035 time_slots,
2036 NULL,
2037 NULL,
2038 NULL
2039};
2040
2041PyMODINIT_FUNC
2042PyInit_time(void)
2043{
2044 return PyModuleDef_Init(&timemodule);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002045}
2046
Victor Stinnercb29f012015-03-27 13:31:18 +01002047/* Implement pysleep() for various platforms.
Guido van Rossumb6775db1994-08-01 11:34:53 +00002048 When interrupted (or when another error occurs), return -1 and
2049 set an exception; else return 0. */
2050
2051static int
Victor Stinnercb29f012015-03-27 13:31:18 +01002052pysleep(_PyTime_t secs)
Guido van Rossum426035c1991-02-19 12:27:35 +00002053{
Victor Stinnercb29f012015-03-27 13:31:18 +01002054 _PyTime_t deadline, monotonic;
Victor Stinner79d68f92015-03-19 21:54:09 +01002055#ifndef MS_WINDOWS
2056 struct timeval timeout;
Victor Stinner79d68f92015-03-19 21:54:09 +01002057 int err = 0;
2058#else
Victor Stinnercb29f012015-03-27 13:31:18 +01002059 _PyTime_t millisecs;
Victor Stinner79d68f92015-03-19 21:54:09 +01002060 unsigned long ul_millis;
2061 DWORD rc;
2062 HANDLE hInterruptEvent;
Victor Stinner0c2fd892015-03-17 10:49:17 +01002063#endif
Victor Stinner79d68f92015-03-19 21:54:09 +01002064
Victor Stinnerae6cd7c2020-11-16 16:08:05 +01002065 if (get_monotonic(&monotonic) < 0) {
2066 return -1;
2067 }
2068 deadline = monotonic + secs;
Victor Stinner79d68f92015-03-19 21:54:09 +01002069
2070 do {
2071#ifndef MS_WINDOWS
Victor Stinner869e1772015-03-30 03:49:14 +02002072 if (_PyTime_AsTimeval(secs, &timeout, _PyTime_ROUND_CEILING) < 0)
Victor Stinnercb29f012015-03-27 13:31:18 +01002073 return -1;
Victor Stinner79d68f92015-03-19 21:54:09 +01002074
2075 Py_BEGIN_ALLOW_THREADS
2076 err = select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &timeout);
2077 Py_END_ALLOW_THREADS
2078
2079 if (err == 0)
2080 break;
2081
2082 if (errno != EINTR) {
Victor Stinner0c2fd892015-03-17 10:49:17 +01002083 PyErr_SetFromErrno(PyExc_OSError);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002084 return -1;
2085 }
Victor Stinner79d68f92015-03-19 21:54:09 +01002086#else
Victor Stinner869e1772015-03-30 03:49:14 +02002087 millisecs = _PyTime_AsMilliseconds(secs, _PyTime_ROUND_CEILING);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002088 if (millisecs > (double)ULONG_MAX) {
2089 PyErr_SetString(PyExc_OverflowError,
2090 "sleep length is too large");
2091 return -1;
2092 }
Victor Stinner79d68f92015-03-19 21:54:09 +01002093
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002094 /* Allow sleep(0) to maintain win32 semantics, and as decreed
2095 * by Guido, only the main thread can be interrupted.
2096 */
2097 ul_millis = (unsigned long)millisecs;
Victor Stinner79d68f92015-03-19 21:54:09 +01002098 if (ul_millis == 0 || !_PyOS_IsMainThread()) {
2099 Py_BEGIN_ALLOW_THREADS
Victor Stinner0eac1302015-03-20 03:06:12 +01002100 Sleep(ul_millis);
Victor Stinner79d68f92015-03-19 21:54:09 +01002101 Py_END_ALLOW_THREADS
2102 break;
Victor Stinner945c82e2015-03-12 16:19:01 +01002103 }
Victor Stinner79d68f92015-03-19 21:54:09 +01002104
2105 hInterruptEvent = _PyOS_SigintEvent();
2106 ResetEvent(hInterruptEvent);
2107
2108 Py_BEGIN_ALLOW_THREADS
2109 rc = WaitForSingleObjectEx(hInterruptEvent, ul_millis, FALSE);
Victor Stinner0c2fd892015-03-17 10:49:17 +01002110 Py_END_ALLOW_THREADS
Victor Stinner79d68f92015-03-19 21:54:09 +01002111
2112 if (rc != WAIT_OBJECT_0)
2113 break;
Victor Stinner945c82e2015-03-12 16:19:01 +01002114#endif
Victor Stinner0c2fd892015-03-17 10:49:17 +01002115
Victor Stinner79d68f92015-03-19 21:54:09 +01002116 /* sleep was interrupted by SIGINT */
2117 if (PyErr_CheckSignals())
2118 return -1;
2119
Victor Stinnerae6cd7c2020-11-16 16:08:05 +01002120 if (get_monotonic(&monotonic) < 0) {
2121 return -1;
2122 }
Victor Stinnercb29f012015-03-27 13:31:18 +01002123 secs = deadline - monotonic;
Victor Stinnerae6cd7c2020-11-16 16:08:05 +01002124 if (secs < 0) {
Victor Stinner79d68f92015-03-19 21:54:09 +01002125 break;
Victor Stinnerae6cd7c2020-11-16 16:08:05 +01002126 }
Victor Stinner79d68f92015-03-19 21:54:09 +01002127 /* retry with the recomputed delay */
2128 } while (1);
2129
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002130 return 0;
Guido van Rossum80c9d881991-04-16 08:47:51 +00002131}