timemodule.c 65 KB

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