timemodule.c 63 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327
  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_strftime(PyObject *module, PyObject *args)
  693. {
  694. PyObject *tup = NULL;
  695. struct tm buf;
  696. const time_char *fmt;
  697. #ifdef HAVE_WCSFTIME
  698. wchar_t *format;
  699. #else
  700. PyObject *format;
  701. #endif
  702. PyObject *format_arg;
  703. size_t fmtlen, buflen;
  704. time_char *outbuf = NULL;
  705. size_t i;
  706. PyObject *ret = NULL;
  707. memset((void *) &buf, '\0', sizeof(buf));
  708. /* Will always expect a unicode string to be passed as format.
  709. Given that there's no str type anymore in py3k this seems safe.
  710. */
  711. if (!PyArg_ParseTuple(args, "U|O:strftime", &format_arg, &tup))
  712. return NULL;
  713. time_module_state *state = get_time_state(module);
  714. if (tup == NULL) {
  715. time_t tt = time(NULL);
  716. if (_PyTime_localtime(tt, &buf) != 0)
  717. return NULL;
  718. }
  719. else if (!gettmarg(state, tup, &buf,
  720. "iiiiiiiii;strftime(): illegal time tuple argument") ||
  721. !checktm(&buf))
  722. {
  723. return NULL;
  724. }
  725. #if defined(_MSC_VER) || (defined(__sun) && defined(__SVR4)) || defined(_AIX) || defined(__VXWORKS__)
  726. if (buf.tm_year + 1900 < 1 || 9999 < buf.tm_year + 1900) {
  727. PyErr_SetString(PyExc_ValueError,
  728. "strftime() requires year in [1; 9999]");
  729. return NULL;
  730. }
  731. #endif
  732. /* Normalize tm_isdst just in case someone foolishly implements %Z
  733. based on the assumption that tm_isdst falls within the range of
  734. [-1, 1] */
  735. if (buf.tm_isdst < -1)
  736. buf.tm_isdst = -1;
  737. else if (buf.tm_isdst > 1)
  738. buf.tm_isdst = 1;
  739. #ifdef HAVE_WCSFTIME
  740. format = PyUnicode_AsWideCharString(format_arg, NULL);
  741. if (format == NULL)
  742. return NULL;
  743. fmt = format;
  744. #else
  745. /* Convert the unicode string to an ascii one */
  746. format = PyUnicode_EncodeLocale(format_arg, "surrogateescape");
  747. if (format == NULL)
  748. return NULL;
  749. fmt = PyBytes_AS_STRING(format);
  750. #endif
  751. #if defined(MS_WINDOWS) && !defined(HAVE_WCSFTIME)
  752. /* check that the format string contains only valid directives */
  753. for (outbuf = strchr(fmt, '%');
  754. outbuf != NULL;
  755. outbuf = strchr(outbuf+2, '%'))
  756. {
  757. if (outbuf[1] == '#')
  758. ++outbuf; /* not documented by python, */
  759. if (outbuf[1] == '\0')
  760. break;
  761. if ((outbuf[1] == 'y') && buf.tm_year < 0) {
  762. PyErr_SetString(PyExc_ValueError,
  763. "format %y requires year >= 1900 on Windows");
  764. Py_DECREF(format);
  765. return NULL;
  766. }
  767. }
  768. #elif (defined(_AIX) || (defined(__sun) && defined(__SVR4))) && defined(HAVE_WCSFTIME)
  769. for (outbuf = wcschr(fmt, '%');
  770. outbuf != NULL;
  771. outbuf = wcschr(outbuf+2, '%'))
  772. {
  773. if (outbuf[1] == L'\0')
  774. break;
  775. /* Issue #19634: On AIX, wcsftime("y", (1899, 1, 1, 0, 0, 0, 0, 0, 0))
  776. returns "0/" instead of "99" */
  777. if (outbuf[1] == L'y' && buf.tm_year < 0) {
  778. PyErr_SetString(PyExc_ValueError,
  779. "format %y requires year >= 1900 on AIX");
  780. PyMem_Free(format);
  781. return NULL;
  782. }
  783. }
  784. #endif
  785. fmtlen = time_strlen(fmt);
  786. /* I hate these functions that presume you know how big the output
  787. * will be ahead of time...
  788. */
  789. for (i = 1024; ; i += i) {
  790. outbuf = (time_char *)PyMem_Malloc(i*sizeof(time_char));
  791. if (outbuf == NULL) {
  792. PyErr_NoMemory();
  793. break;
  794. }
  795. #if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
  796. errno = 0;
  797. #endif
  798. _Py_BEGIN_SUPPRESS_IPH
  799. buflen = format_time(outbuf, i, fmt, &buf);
  800. _Py_END_SUPPRESS_IPH
  801. #if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
  802. /* VisualStudio .NET 2005 does this properly */
  803. if (buflen == 0 && errno == EINVAL) {
  804. PyErr_SetString(PyExc_ValueError, "Invalid format string");
  805. PyMem_Free(outbuf);
  806. break;
  807. }
  808. #endif
  809. if (buflen > 0 || i >= 256 * fmtlen) {
  810. /* If the buffer is 256 times as long as the format,
  811. it's probably not failing for lack of room!
  812. More likely, the format yields an empty result,
  813. e.g. an empty format, or %Z when the timezone
  814. is unknown. */
  815. #ifdef HAVE_WCSFTIME
  816. ret = PyUnicode_FromWideChar(outbuf, buflen);
  817. #else
  818. ret = PyUnicode_DecodeLocaleAndSize(outbuf, buflen, "surrogateescape");
  819. #endif
  820. PyMem_Free(outbuf);
  821. break;
  822. }
  823. PyMem_Free(outbuf);
  824. }
  825. #ifdef HAVE_WCSFTIME
  826. PyMem_Free(format);
  827. #else
  828. Py_DECREF(format);
  829. #endif
  830. return ret;
  831. }
  832. #undef time_char
  833. #undef format_time
  834. PyDoc_STRVAR(strftime_doc,
  835. "strftime(format[, tuple]) -> string\n\
  836. \n\
  837. Convert a time tuple to a string according to a format specification.\n\
  838. See the library reference manual for formatting codes. When the time tuple\n\
  839. is not present, current time as returned by localtime() is used.\n\
  840. \n" STRFTIME_FORMAT_CODES);
  841. #endif /* HAVE_STRFTIME */
  842. static PyObject *
  843. time_strptime(PyObject *self, PyObject *args)
  844. {
  845. PyObject *func, *result;
  846. func = _PyImport_GetModuleAttrString("_strptime", "_strptime_time");
  847. if (!func) {
  848. return NULL;
  849. }
  850. result = PyObject_Call(func, args, NULL);
  851. Py_DECREF(func);
  852. return result;
  853. }
  854. PyDoc_STRVAR(strptime_doc,
  855. "strptime(string, format) -> struct_time\n\
  856. \n\
  857. Parse a string to a time tuple according to a format specification.\n\
  858. See the library reference manual for formatting codes (same as\n\
  859. strftime()).\n\
  860. \n" STRFTIME_FORMAT_CODES);
  861. static PyObject *
  862. _asctime(struct tm *timeptr)
  863. {
  864. /* Inspired by Open Group reference implementation available at
  865. * http://pubs.opengroup.org/onlinepubs/009695399/functions/asctime.html */
  866. static const char wday_name[7][4] = {
  867. "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
  868. };
  869. static const char mon_name[12][4] = {
  870. "Jan", "Feb", "Mar", "Apr", "May", "Jun",
  871. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
  872. };
  873. return PyUnicode_FromFormat(
  874. "%s %s%3d %.2d:%.2d:%.2d %d",
  875. wday_name[timeptr->tm_wday],
  876. mon_name[timeptr->tm_mon],
  877. timeptr->tm_mday, timeptr->tm_hour,
  878. timeptr->tm_min, timeptr->tm_sec,
  879. 1900 + timeptr->tm_year);
  880. }
  881. static PyObject *
  882. time_asctime(PyObject *module, PyObject *args)
  883. {
  884. PyObject *tup = NULL;
  885. struct tm buf;
  886. if (!PyArg_UnpackTuple(args, "asctime", 0, 1, &tup))
  887. return NULL;
  888. time_module_state *state = get_time_state(module);
  889. if (tup == NULL) {
  890. time_t tt = time(NULL);
  891. if (_PyTime_localtime(tt, &buf) != 0)
  892. return NULL;
  893. }
  894. else if (!gettmarg(state, tup, &buf,
  895. "iiiiiiiii;asctime(): illegal time tuple argument") ||
  896. !checktm(&buf))
  897. {
  898. return NULL;
  899. }
  900. return _asctime(&buf);
  901. }
  902. PyDoc_STRVAR(asctime_doc,
  903. "asctime([tuple]) -> string\n\
  904. \n\
  905. Convert a time tuple to a string, e.g. 'Sat Jun 06 16:26:11 1998'.\n\
  906. When the time tuple is not present, current time as returned by localtime()\n\
  907. is used.");
  908. static PyObject *
  909. time_ctime(PyObject *self, PyObject *args)
  910. {
  911. time_t tt;
  912. struct tm buf;
  913. if (!parse_time_t_args(args, "|O:ctime", &tt))
  914. return NULL;
  915. if (_PyTime_localtime(tt, &buf) != 0)
  916. return NULL;
  917. return _asctime(&buf);
  918. }
  919. PyDoc_STRVAR(ctime_doc,
  920. "ctime(seconds) -> string\n\
  921. \n\
  922. Convert a time in seconds since the Epoch to a string in local time.\n\
  923. This is equivalent to asctime(localtime(seconds)). When the time tuple is\n\
  924. not present, current time as returned by localtime() is used.");
  925. #ifdef HAVE_MKTIME
  926. static PyObject *
  927. time_mktime(PyObject *module, PyObject *tm_tuple)
  928. {
  929. struct tm tm;
  930. time_t tt;
  931. time_module_state *state = get_time_state(module);
  932. if (!gettmarg(state, tm_tuple, &tm,
  933. "iiiiiiiii;mktime(): illegal time tuple argument"))
  934. {
  935. return NULL;
  936. }
  937. #if defined(_AIX) || (defined(__VXWORKS__) && !defined(_WRS_CONFIG_LP64))
  938. /* bpo-19748: AIX mktime() valid range is 00:00:00 UTC, January 1, 1970
  939. to 03:14:07 UTC, January 19, 2038. Thanks to the workaround below,
  940. it is possible to support years in range [1902; 2037] */
  941. if (tm.tm_year < 2 || tm.tm_year > 137) {
  942. /* bpo-19748: On AIX, mktime() does not report overflow error
  943. for timestamp < -2^31 or timestamp > 2**31-1. VxWorks has the
  944. same issue when working in 32 bit mode. */
  945. PyErr_SetString(PyExc_OverflowError,
  946. "mktime argument out of range");
  947. return NULL;
  948. }
  949. #endif
  950. #ifdef _AIX
  951. /* bpo-34373: AIX mktime() has an integer overflow for years in range
  952. [1902; 1969]. Workaround the issue by using a year greater or equal than
  953. 1970 (tm_year >= 70): mktime() behaves correctly in that case
  954. (ex: properly report errors). tm_year and tm_wday are adjusted after
  955. mktime() call. */
  956. int orig_tm_year = tm.tm_year;
  957. int delta_days = 0;
  958. while (tm.tm_year < 70) {
  959. /* Use 4 years to account properly leap years */
  960. tm.tm_year += 4;
  961. delta_days -= (366 + (365 * 3));
  962. }
  963. #endif
  964. tm.tm_wday = -1; /* sentinel; original value ignored */
  965. tt = mktime(&tm);
  966. /* Return value of -1 does not necessarily mean an error, but tm_wday
  967. * cannot remain set to -1 if mktime succeeded. */
  968. if (tt == (time_t)(-1)
  969. /* Return value of -1 does not necessarily mean an error, but
  970. * tm_wday cannot remain set to -1 if mktime succeeded. */
  971. && tm.tm_wday == -1)
  972. {
  973. PyErr_SetString(PyExc_OverflowError,
  974. "mktime argument out of range");
  975. return NULL;
  976. }
  977. #ifdef _AIX
  978. if (delta_days != 0) {
  979. tm.tm_year = orig_tm_year;
  980. if (tm.tm_wday != -1) {
  981. tm.tm_wday = (tm.tm_wday + delta_days) % 7;
  982. }
  983. tt += delta_days * (24 * 3600);
  984. }
  985. #endif
  986. return PyFloat_FromDouble((double)tt);
  987. }
  988. PyDoc_STRVAR(mktime_doc,
  989. "mktime(tuple) -> floating-point number\n\
  990. \n\
  991. Convert a time tuple in local time to seconds since the Epoch.\n\
  992. Note that mktime(gmtime(0)) will not generally return zero for most\n\
  993. time zones; instead the returned value will either be equal to that\n\
  994. of the timezone or altzone attributes on the time module.");
  995. #endif /* HAVE_MKTIME */
  996. #ifdef HAVE_WORKING_TZSET
  997. static int init_timezone(PyObject *module);
  998. static PyObject *
  999. time_tzset(PyObject *self, PyObject *unused)
  1000. {
  1001. PyObject* m;
  1002. m = PyImport_ImportModule("time");
  1003. if (m == NULL) {
  1004. return NULL;
  1005. }
  1006. #if !defined(MS_WINDOWS) || defined(MS_WINDOWS_DESKTOP) || defined(MS_WINDOWS_SYSTEM)
  1007. tzset();
  1008. #endif
  1009. /* Reset timezone, altzone, daylight and tzname */
  1010. if (init_timezone(m) < 0) {
  1011. return NULL;
  1012. }
  1013. Py_DECREF(m);
  1014. if (PyErr_Occurred())
  1015. return NULL;
  1016. Py_RETURN_NONE;
  1017. }
  1018. PyDoc_STRVAR(tzset_doc,
  1019. "tzset()\n\
  1020. \n\
  1021. Initialize, or reinitialize, the local timezone to the value stored in\n\
  1022. os.environ['TZ']. The TZ environment variable should be specified in\n\
  1023. standard Unix timezone format as documented in the tzset man page\n\
  1024. (eg. 'US/Eastern', 'Europe/Amsterdam'). Unknown timezones will silently\n\
  1025. fall back to UTC. If the TZ environment variable is not set, the local\n\
  1026. timezone is set to the systems best guess of wallclock time.\n\
  1027. Changing the TZ environment variable without calling tzset *may* change\n\
  1028. the local timezone used by methods such as localtime, but this behaviour\n\
  1029. should not be relied on.");
  1030. #endif /* HAVE_WORKING_TZSET */
  1031. static int
  1032. get_monotonic(_PyTime_t *t)
  1033. {
  1034. // Avoid _PyTime_GetMonotonicClock() which silently ignores errors.
  1035. return _PyTime_GetMonotonicClockWithInfo(t, NULL);
  1036. }
  1037. static PyObject *
  1038. time_monotonic(PyObject *self, PyObject *unused)
  1039. {
  1040. _PyTime_t t;
  1041. if (get_monotonic(&t) < 0) {
  1042. return NULL;
  1043. }
  1044. return _PyFloat_FromPyTime(t);
  1045. }
  1046. PyDoc_STRVAR(monotonic_doc,
  1047. "monotonic() -> float\n\
  1048. \n\
  1049. Monotonic clock, cannot go backward.");
  1050. static PyObject *
  1051. time_monotonic_ns(PyObject *self, PyObject *unused)
  1052. {
  1053. _PyTime_t t;
  1054. if (get_monotonic(&t) < 0) {
  1055. return NULL;
  1056. }
  1057. return _PyTime_AsNanosecondsObject(t);
  1058. }
  1059. PyDoc_STRVAR(monotonic_ns_doc,
  1060. "monotonic_ns() -> int\n\
  1061. \n\
  1062. Monotonic clock, cannot go backward, as nanoseconds.");
  1063. static int
  1064. get_perf_counter(_PyTime_t *t)
  1065. {
  1066. // Avoid _PyTime_GetPerfCounter() which silently ignores errors.
  1067. return _PyTime_GetPerfCounterWithInfo(t, NULL);
  1068. }
  1069. static PyObject *
  1070. time_perf_counter(PyObject *self, PyObject *unused)
  1071. {
  1072. _PyTime_t t;
  1073. if (get_perf_counter(&t) < 0) {
  1074. return NULL;
  1075. }
  1076. return _PyFloat_FromPyTime(t);
  1077. }
  1078. PyDoc_STRVAR(perf_counter_doc,
  1079. "perf_counter() -> float\n\
  1080. \n\
  1081. Performance counter for benchmarking.");
  1082. static PyObject *
  1083. time_perf_counter_ns(PyObject *self, PyObject *unused)
  1084. {
  1085. _PyTime_t t;
  1086. if (get_perf_counter(&t) < 0) {
  1087. return NULL;
  1088. }
  1089. return _PyTime_AsNanosecondsObject(t);
  1090. }
  1091. PyDoc_STRVAR(perf_counter_ns_doc,
  1092. "perf_counter_ns() -> int\n\
  1093. \n\
  1094. Performance counter for benchmarking as nanoseconds.");
  1095. static int
  1096. _PyTime_GetProcessTimeWithInfo(_PyTime_t *tp, _Py_clock_info_t *info)
  1097. {
  1098. #if defined(MS_WINDOWS)
  1099. HANDLE process;
  1100. FILETIME creation_time, exit_time, kernel_time, user_time;
  1101. ULARGE_INTEGER large;
  1102. _PyTime_t ktime, utime, t;
  1103. BOOL ok;
  1104. process = GetCurrentProcess();
  1105. ok = GetProcessTimes(process, &creation_time, &exit_time,
  1106. &kernel_time, &user_time);
  1107. if (!ok) {
  1108. PyErr_SetFromWindowsErr(0);
  1109. return -1;
  1110. }
  1111. if (info) {
  1112. info->implementation = "GetProcessTimes()";
  1113. info->resolution = 1e-7;
  1114. info->monotonic = 1;
  1115. info->adjustable = 0;
  1116. }
  1117. large.u.LowPart = kernel_time.dwLowDateTime;
  1118. large.u.HighPart = kernel_time.dwHighDateTime;
  1119. ktime = large.QuadPart;
  1120. large.u.LowPart = user_time.dwLowDateTime;
  1121. large.u.HighPart = user_time.dwHighDateTime;
  1122. utime = large.QuadPart;
  1123. /* ktime and utime have a resolution of 100 nanoseconds */
  1124. t = _PyTime_FromNanoseconds((ktime + utime) * 100);
  1125. *tp = t;
  1126. return 0;
  1127. #else
  1128. /* clock_gettime */
  1129. #if defined(HAVE_CLOCK_GETTIME) \
  1130. && (defined(CLOCK_PROCESS_CPUTIME_ID) || defined(CLOCK_PROF))
  1131. struct timespec ts;
  1132. if (HAVE_CLOCK_GETTIME_RUNTIME) {
  1133. #ifdef CLOCK_PROF
  1134. const clockid_t clk_id = CLOCK_PROF;
  1135. const char *function = "clock_gettime(CLOCK_PROF)";
  1136. #else
  1137. const clockid_t clk_id = CLOCK_PROCESS_CPUTIME_ID;
  1138. const char *function = "clock_gettime(CLOCK_PROCESS_CPUTIME_ID)";
  1139. #endif
  1140. if (clock_gettime(clk_id, &ts) == 0) {
  1141. if (info) {
  1142. struct timespec res;
  1143. info->implementation = function;
  1144. info->monotonic = 1;
  1145. info->adjustable = 0;
  1146. if (clock_getres(clk_id, &res)) {
  1147. PyErr_SetFromErrno(PyExc_OSError);
  1148. return -1;
  1149. }
  1150. info->resolution = res.tv_sec + res.tv_nsec * 1e-9;
  1151. }
  1152. if (_PyTime_FromTimespec(tp, &ts) < 0) {
  1153. return -1;
  1154. }
  1155. return 0;
  1156. }
  1157. }
  1158. #endif
  1159. /* getrusage(RUSAGE_SELF) */
  1160. #if defined(HAVE_SYS_RESOURCE_H) && defined(HAVE_GETRUSAGE)
  1161. struct rusage ru;
  1162. if (getrusage(RUSAGE_SELF, &ru) == 0) {
  1163. _PyTime_t utime, stime;
  1164. if (info) {
  1165. info->implementation = "getrusage(RUSAGE_SELF)";
  1166. info->monotonic = 1;
  1167. info->adjustable = 0;
  1168. info->resolution = 1e-6;
  1169. }
  1170. if (_PyTime_FromTimeval(&utime, &ru.ru_utime) < 0) {
  1171. return -1;
  1172. }
  1173. if (_PyTime_FromTimeval(&stime, &ru.ru_stime) < 0) {
  1174. return -1;
  1175. }
  1176. _PyTime_t total = utime + stime;
  1177. *tp = total;
  1178. return 0;
  1179. }
  1180. #endif
  1181. /* times() */
  1182. #ifdef HAVE_TIMES
  1183. struct tms t;
  1184. if (times(&t) != (clock_t)-1) {
  1185. assert(_PyRuntime.time.ticks_per_second_initialized);
  1186. if (check_ticks_per_second(ticks_per_second, "_SC_CLK_TCK") < 0) {
  1187. return -1;
  1188. }
  1189. if (ticks_per_second != -1) {
  1190. if (info) {
  1191. info->implementation = "times()";
  1192. info->monotonic = 1;
  1193. info->adjustable = 0;
  1194. info->resolution = 1.0 / (double)ticks_per_second;
  1195. }
  1196. _PyTime_t ns;
  1197. ns = _PyTime_MulDiv(t.tms_utime, SEC_TO_NS, ticks_per_second);
  1198. ns += _PyTime_MulDiv(t.tms_stime, SEC_TO_NS, ticks_per_second);
  1199. *tp = _PyTime_FromNanoseconds(ns);
  1200. return 0;
  1201. }
  1202. }
  1203. #endif
  1204. /* clock */
  1205. /* Currently, Python 3 requires clock() to build: see issue #22624 */
  1206. return _PyTime_GetClockWithInfo(tp, info);
  1207. #endif
  1208. }
  1209. static PyObject *
  1210. time_process_time(PyObject *self, PyObject *unused)
  1211. {
  1212. _PyTime_t t;
  1213. if (_PyTime_GetProcessTimeWithInfo(&t, NULL) < 0) {
  1214. return NULL;
  1215. }
  1216. return _PyFloat_FromPyTime(t);
  1217. }
  1218. PyDoc_STRVAR(process_time_doc,
  1219. "process_time() -> float\n\
  1220. \n\
  1221. Process time for profiling: sum of the kernel and user-space CPU time.");
  1222. static PyObject *
  1223. time_process_time_ns(PyObject *self, PyObject *unused)
  1224. {
  1225. _PyTime_t t;
  1226. if (_PyTime_GetProcessTimeWithInfo(&t, NULL) < 0) {
  1227. return NULL;
  1228. }
  1229. return _PyTime_AsNanosecondsObject(t);
  1230. }
  1231. PyDoc_STRVAR(process_time_ns_doc,
  1232. "process_time() -> int\n\
  1233. \n\
  1234. Process time for profiling as nanoseconds:\n\
  1235. sum of the kernel and user-space CPU time.");
  1236. #if defined(MS_WINDOWS)
  1237. #define HAVE_THREAD_TIME
  1238. static int
  1239. _PyTime_GetThreadTimeWithInfo(_PyTime_t *tp, _Py_clock_info_t *info)
  1240. {
  1241. HANDLE thread;
  1242. FILETIME creation_time, exit_time, kernel_time, user_time;
  1243. ULARGE_INTEGER large;
  1244. _PyTime_t ktime, utime, t;
  1245. BOOL ok;
  1246. thread = GetCurrentThread();
  1247. ok = GetThreadTimes(thread, &creation_time, &exit_time,
  1248. &kernel_time, &user_time);
  1249. if (!ok) {
  1250. PyErr_SetFromWindowsErr(0);
  1251. return -1;
  1252. }
  1253. if (info) {
  1254. info->implementation = "GetThreadTimes()";
  1255. info->resolution = 1e-7;
  1256. info->monotonic = 1;
  1257. info->adjustable = 0;
  1258. }
  1259. large.u.LowPart = kernel_time.dwLowDateTime;
  1260. large.u.HighPart = kernel_time.dwHighDateTime;
  1261. ktime = large.QuadPart;
  1262. large.u.LowPart = user_time.dwLowDateTime;
  1263. large.u.HighPart = user_time.dwHighDateTime;
  1264. utime = large.QuadPart;
  1265. /* ktime and utime have a resolution of 100 nanoseconds */
  1266. t = _PyTime_FromNanoseconds((ktime + utime) * 100);
  1267. *tp = t;
  1268. return 0;
  1269. }
  1270. #elif defined(_AIX)
  1271. #define HAVE_THREAD_TIME
  1272. static int
  1273. _PyTime_GetThreadTimeWithInfo(_PyTime_t *tp, _Py_clock_info_t *info)
  1274. {
  1275. /* bpo-40192: On AIX, thread_cputime() is preferred: it has nanosecond
  1276. resolution, whereas clock_gettime(CLOCK_THREAD_CPUTIME_ID)
  1277. has a resolution of 10 ms. */
  1278. thread_cputime_t tc;
  1279. if (thread_cputime(-1, &tc) != 0) {
  1280. PyErr_SetFromErrno(PyExc_OSError);
  1281. return -1;
  1282. }
  1283. if (info) {
  1284. info->implementation = "thread_cputime()";
  1285. info->monotonic = 1;
  1286. info->adjustable = 0;
  1287. info->resolution = 1e-9;
  1288. }
  1289. *tp = _PyTime_FromNanoseconds(tc.stime + tc.utime);
  1290. return 0;
  1291. }
  1292. #elif defined(__sun) && defined(__SVR4)
  1293. #define HAVE_THREAD_TIME
  1294. static int
  1295. _PyTime_GetThreadTimeWithInfo(_PyTime_t *tp, _Py_clock_info_t *info)
  1296. {
  1297. /* bpo-35455: On Solaris, CLOCK_THREAD_CPUTIME_ID clock is not always
  1298. available; use gethrvtime() to substitute this functionality. */
  1299. if (info) {
  1300. info->implementation = "gethrvtime()";
  1301. info->resolution = 1e-9;
  1302. info->monotonic = 1;
  1303. info->adjustable = 0;
  1304. }
  1305. *tp = _PyTime_FromNanoseconds(gethrvtime());
  1306. return 0;
  1307. }
  1308. #elif defined(HAVE_CLOCK_GETTIME) && \
  1309. defined(CLOCK_PROCESS_CPUTIME_ID) && \
  1310. !defined(__EMSCRIPTEN__) && !defined(__wasi__)
  1311. #define HAVE_THREAD_TIME
  1312. #if defined(__APPLE__) && defined(__has_attribute) && __has_attribute(availability)
  1313. static int
  1314. _PyTime_GetThreadTimeWithInfo(_PyTime_t *tp, _Py_clock_info_t *info)
  1315. __attribute__((availability(macos, introduced=10.12)))
  1316. __attribute__((availability(ios, introduced=10.0)))
  1317. __attribute__((availability(tvos, introduced=10.0)))
  1318. __attribute__((availability(watchos, introduced=3.0)));
  1319. #endif
  1320. static int
  1321. _PyTime_GetThreadTimeWithInfo(_PyTime_t *tp, _Py_clock_info_t *info)
  1322. {
  1323. struct timespec ts;
  1324. const clockid_t clk_id = CLOCK_THREAD_CPUTIME_ID;
  1325. const char *function = "clock_gettime(CLOCK_THREAD_CPUTIME_ID)";
  1326. if (clock_gettime(clk_id, &ts)) {
  1327. PyErr_SetFromErrno(PyExc_OSError);
  1328. return -1;
  1329. }
  1330. if (info) {
  1331. struct timespec res;
  1332. info->implementation = function;
  1333. info->monotonic = 1;
  1334. info->adjustable = 0;
  1335. if (clock_getres(clk_id, &res)) {
  1336. PyErr_SetFromErrno(PyExc_OSError);
  1337. return -1;
  1338. }
  1339. info->resolution = res.tv_sec + res.tv_nsec * 1e-9;
  1340. }
  1341. if (_PyTime_FromTimespec(tp, &ts) < 0) {
  1342. return -1;
  1343. }
  1344. return 0;
  1345. }
  1346. #endif
  1347. #ifdef HAVE_THREAD_TIME
  1348. #ifdef __APPLE__
  1349. /*
  1350. * The clock_* functions will be removed from the module
  1351. * dict entirely when the C API is not available.
  1352. */
  1353. #pragma clang diagnostic push
  1354. #pragma clang diagnostic ignored "-Wunguarded-availability"
  1355. #endif
  1356. static PyObject *
  1357. time_thread_time(PyObject *self, PyObject *unused)
  1358. {
  1359. _PyTime_t t;
  1360. if (_PyTime_GetThreadTimeWithInfo(&t, NULL) < 0) {
  1361. return NULL;
  1362. }
  1363. return _PyFloat_FromPyTime(t);
  1364. }
  1365. PyDoc_STRVAR(thread_time_doc,
  1366. "thread_time() -> float\n\
  1367. \n\
  1368. Thread time for profiling: sum of the kernel and user-space CPU time.");
  1369. static PyObject *
  1370. time_thread_time_ns(PyObject *self, PyObject *unused)
  1371. {
  1372. _PyTime_t t;
  1373. if (_PyTime_GetThreadTimeWithInfo(&t, NULL) < 0) {
  1374. return NULL;
  1375. }
  1376. return _PyTime_AsNanosecondsObject(t);
  1377. }
  1378. PyDoc_STRVAR(thread_time_ns_doc,
  1379. "thread_time() -> int\n\
  1380. \n\
  1381. Thread time for profiling as nanoseconds:\n\
  1382. sum of the kernel and user-space CPU time.");
  1383. #ifdef __APPLE__
  1384. #pragma clang diagnostic pop
  1385. #endif
  1386. #endif
  1387. static PyObject *
  1388. time_get_clock_info(PyObject *self, PyObject *args)
  1389. {
  1390. char *name;
  1391. _Py_clock_info_t info;
  1392. PyObject *obj = NULL, *dict, *ns;
  1393. _PyTime_t t;
  1394. if (!PyArg_ParseTuple(args, "s:get_clock_info", &name)) {
  1395. return NULL;
  1396. }
  1397. #ifdef Py_DEBUG
  1398. info.implementation = NULL;
  1399. info.monotonic = -1;
  1400. info.adjustable = -1;
  1401. info.resolution = -1.0;
  1402. #else
  1403. info.implementation = "";
  1404. info.monotonic = 0;
  1405. info.adjustable = 0;
  1406. info.resolution = 1.0;
  1407. #endif
  1408. if (strcmp(name, "time") == 0) {
  1409. if (_PyTime_GetSystemClockWithInfo(&t, &info) < 0) {
  1410. return NULL;
  1411. }
  1412. }
  1413. else if (strcmp(name, "monotonic") == 0) {
  1414. if (_PyTime_GetMonotonicClockWithInfo(&t, &info) < 0) {
  1415. return NULL;
  1416. }
  1417. }
  1418. else if (strcmp(name, "perf_counter") == 0) {
  1419. if (_PyTime_GetPerfCounterWithInfo(&t, &info) < 0) {
  1420. return NULL;
  1421. }
  1422. }
  1423. else if (strcmp(name, "process_time") == 0) {
  1424. if (_PyTime_GetProcessTimeWithInfo(&t, &info) < 0) {
  1425. return NULL;
  1426. }
  1427. }
  1428. #ifdef HAVE_THREAD_TIME
  1429. else if (strcmp(name, "thread_time") == 0) {
  1430. #ifdef __APPLE__
  1431. if (HAVE_CLOCK_GETTIME_RUNTIME) {
  1432. #endif
  1433. if (_PyTime_GetThreadTimeWithInfo(&t, &info) < 0) {
  1434. return NULL;
  1435. }
  1436. #ifdef __APPLE__
  1437. } else {
  1438. PyErr_SetString(PyExc_ValueError, "unknown clock");
  1439. return NULL;
  1440. }
  1441. #endif
  1442. }
  1443. #endif
  1444. else {
  1445. PyErr_SetString(PyExc_ValueError, "unknown clock");
  1446. return NULL;
  1447. }
  1448. dict = PyDict_New();
  1449. if (dict == NULL) {
  1450. return NULL;
  1451. }
  1452. assert(info.implementation != NULL);
  1453. obj = PyUnicode_FromString(info.implementation);
  1454. if (obj == NULL) {
  1455. goto error;
  1456. }
  1457. if (PyDict_SetItemString(dict, "implementation", obj) == -1) {
  1458. goto error;
  1459. }
  1460. Py_CLEAR(obj);
  1461. assert(info.monotonic != -1);
  1462. obj = PyBool_FromLong(info.monotonic);
  1463. if (obj == NULL) {
  1464. goto error;
  1465. }
  1466. if (PyDict_SetItemString(dict, "monotonic", obj) == -1) {
  1467. goto error;
  1468. }
  1469. Py_CLEAR(obj);
  1470. assert(info.adjustable != -1);
  1471. obj = PyBool_FromLong(info.adjustable);
  1472. if (obj == NULL) {
  1473. goto error;
  1474. }
  1475. if (PyDict_SetItemString(dict, "adjustable", obj) == -1) {
  1476. goto error;
  1477. }
  1478. Py_CLEAR(obj);
  1479. assert(info.resolution > 0.0);
  1480. assert(info.resolution <= 1.0);
  1481. obj = PyFloat_FromDouble(info.resolution);
  1482. if (obj == NULL) {
  1483. goto error;
  1484. }
  1485. if (PyDict_SetItemString(dict, "resolution", obj) == -1) {
  1486. goto error;
  1487. }
  1488. Py_CLEAR(obj);
  1489. ns = _PyNamespace_New(dict);
  1490. Py_DECREF(dict);
  1491. return ns;
  1492. error:
  1493. Py_DECREF(dict);
  1494. Py_XDECREF(obj);
  1495. return NULL;
  1496. }
  1497. PyDoc_STRVAR(get_clock_info_doc,
  1498. "get_clock_info(name: str) -> dict\n\
  1499. \n\
  1500. Get information of the specified clock.");
  1501. #ifndef HAVE_DECL_TZNAME
  1502. static void
  1503. get_zone(char *zone, int n, struct tm *p)
  1504. {
  1505. #ifdef HAVE_STRUCT_TM_TM_ZONE
  1506. strncpy(zone, p->tm_zone ? p->tm_zone : " ", n);
  1507. #else
  1508. tzset();
  1509. strftime(zone, n, "%Z", p);
  1510. #endif
  1511. }
  1512. static time_t
  1513. get_gmtoff(time_t t, struct tm *p)
  1514. {
  1515. #ifdef HAVE_STRUCT_TM_TM_ZONE
  1516. return p->tm_gmtoff;
  1517. #else
  1518. return timegm(p) - t;
  1519. #endif
  1520. }
  1521. #endif // !HAVE_DECL_TZNAME
  1522. static int
  1523. init_timezone(PyObject *m)
  1524. {
  1525. #define ADD_INT(NAME, VALUE) do { \
  1526. if (PyModule_AddIntConstant(m, NAME, VALUE) < 0) { \
  1527. return -1; \
  1528. } \
  1529. } while (0)
  1530. assert(!PyErr_Occurred());
  1531. /* This code moved from PyInit_time wholesale to allow calling it from
  1532. time_tzset. In the future, some parts of it can be moved back
  1533. (for platforms that don't HAVE_WORKING_TZSET, when we know what they
  1534. are), and the extraneous calls to tzset(3) should be removed.
  1535. I haven't done this yet, as I don't want to change this code as
  1536. little as possible when introducing the time.tzset and time.tzsetwall
  1537. methods. This should simply be a method of doing the following once,
  1538. at the top of this function and removing the call to tzset() from
  1539. time_tzset():
  1540. #ifdef HAVE_TZSET
  1541. tzset()
  1542. #endif
  1543. And I'm lazy and hate C so nyer.
  1544. */
  1545. #ifdef HAVE_DECL_TZNAME
  1546. PyObject *otz0, *otz1;
  1547. #if !defined(MS_WINDOWS) || defined(MS_WINDOWS_DESKTOP) || defined(MS_WINDOWS_SYSTEM)
  1548. tzset();
  1549. #endif
  1550. ADD_INT("timezone", _Py_timezone);
  1551. #ifdef HAVE_ALTZONE
  1552. ADD_INT("altzone", altzone);
  1553. #else
  1554. ADD_INT("altzone", _Py_timezone-3600);
  1555. #endif
  1556. ADD_INT("daylight", _Py_daylight);
  1557. #ifdef MS_WINDOWS
  1558. TIME_ZONE_INFORMATION tzinfo = {0};
  1559. GetTimeZoneInformation(&tzinfo);
  1560. otz0 = PyUnicode_FromWideChar(tzinfo.StandardName, -1);
  1561. if (otz0 == NULL) {
  1562. return -1;
  1563. }
  1564. otz1 = PyUnicode_FromWideChar(tzinfo.DaylightName, -1);
  1565. if (otz1 == NULL) {
  1566. Py_DECREF(otz0);
  1567. return -1;
  1568. }
  1569. #else
  1570. otz0 = PyUnicode_DecodeLocale(_Py_tzname[0], "surrogateescape");
  1571. if (otz0 == NULL) {
  1572. return -1;
  1573. }
  1574. otz1 = PyUnicode_DecodeLocale(_Py_tzname[1], "surrogateescape");
  1575. if (otz1 == NULL) {
  1576. Py_DECREF(otz0);
  1577. return -1;
  1578. }
  1579. #endif // MS_WINDOWS
  1580. if (_PyModule_Add(m, "tzname", Py_BuildValue("(NN)", otz0, otz1)) < 0) {
  1581. return -1;
  1582. }
  1583. #else // !HAVE_DECL_TZNAME
  1584. static const time_t YEAR = (365 * 24 + 6) * 3600;
  1585. time_t t;
  1586. struct tm p;
  1587. time_t janzone_t, julyzone_t;
  1588. char janname[10], julyname[10];
  1589. t = (time((time_t *)0) / YEAR) * YEAR;
  1590. _PyTime_localtime(t, &p);
  1591. get_zone(janname, 9, &p);
  1592. janzone_t = -get_gmtoff(t, &p);
  1593. janname[9] = '\0';
  1594. t += YEAR/2;
  1595. _PyTime_localtime(t, &p);
  1596. get_zone(julyname, 9, &p);
  1597. julyzone_t = -get_gmtoff(t, &p);
  1598. julyname[9] = '\0';
  1599. /* Sanity check, don't check for the validity of timezones.
  1600. In practice, it should be more in range -12 hours .. +14 hours. */
  1601. #define MAX_TIMEZONE (48 * 3600)
  1602. if (janzone_t < -MAX_TIMEZONE || janzone_t > MAX_TIMEZONE
  1603. || julyzone_t < -MAX_TIMEZONE || julyzone_t > MAX_TIMEZONE)
  1604. {
  1605. PyErr_SetString(PyExc_RuntimeError, "invalid GMT offset");
  1606. return -1;
  1607. }
  1608. int janzone = (int)janzone_t;
  1609. int julyzone = (int)julyzone_t;
  1610. PyObject *tzname_obj;
  1611. if (janzone < julyzone) {
  1612. /* DST is reversed in the southern hemisphere */
  1613. ADD_INT("timezone", julyzone);
  1614. ADD_INT("altzone", janzone);
  1615. ADD_INT("daylight", janzone != julyzone);
  1616. tzname_obj = Py_BuildValue("(zz)", julyname, janname);
  1617. } else {
  1618. ADD_INT("timezone", janzone);
  1619. ADD_INT("altzone", julyzone);
  1620. ADD_INT("daylight", janzone != julyzone);
  1621. tzname_obj = Py_BuildValue("(zz)", janname, julyname);
  1622. }
  1623. if (_PyModule_Add(m, "tzname", tzname_obj) < 0) {
  1624. return -1;
  1625. }
  1626. #endif // !HAVE_DECL_TZNAME
  1627. #undef ADD_INT
  1628. if (PyErr_Occurred()) {
  1629. return -1;
  1630. }
  1631. return 0;
  1632. }
  1633. static PyMethodDef time_methods[] = {
  1634. {"time", time_time, METH_NOARGS, time_doc},
  1635. {"time_ns", time_time_ns, METH_NOARGS, time_ns_doc},
  1636. #ifdef HAVE_CLOCK_GETTIME
  1637. {"clock_gettime", time_clock_gettime, METH_VARARGS, clock_gettime_doc},
  1638. {"clock_gettime_ns",time_clock_gettime_ns, METH_VARARGS, clock_gettime_ns_doc},
  1639. #endif
  1640. #ifdef HAVE_CLOCK_SETTIME
  1641. {"clock_settime", time_clock_settime, METH_VARARGS, clock_settime_doc},
  1642. {"clock_settime_ns",time_clock_settime_ns, METH_VARARGS, clock_settime_ns_doc},
  1643. #endif
  1644. #ifdef HAVE_CLOCK_GETRES
  1645. {"clock_getres", time_clock_getres, METH_VARARGS, clock_getres_doc},
  1646. #endif
  1647. #ifdef HAVE_PTHREAD_GETCPUCLOCKID
  1648. {"pthread_getcpuclockid", time_pthread_getcpuclockid, METH_VARARGS, pthread_getcpuclockid_doc},
  1649. #endif
  1650. {"sleep", time_sleep, METH_O, sleep_doc},
  1651. {"gmtime", time_gmtime, METH_VARARGS, gmtime_doc},
  1652. {"localtime", time_localtime, METH_VARARGS, localtime_doc},
  1653. {"asctime", time_asctime, METH_VARARGS, asctime_doc},
  1654. {"ctime", time_ctime, METH_VARARGS, ctime_doc},
  1655. #ifdef HAVE_MKTIME
  1656. {"mktime", time_mktime, METH_O, mktime_doc},
  1657. #endif
  1658. #ifdef HAVE_STRFTIME
  1659. {"strftime", time_strftime, METH_VARARGS, strftime_doc},
  1660. #endif
  1661. {"strptime", time_strptime, METH_VARARGS, strptime_doc},
  1662. #ifdef HAVE_WORKING_TZSET
  1663. {"tzset", time_tzset, METH_NOARGS, tzset_doc},
  1664. #endif
  1665. {"monotonic", time_monotonic, METH_NOARGS, monotonic_doc},
  1666. {"monotonic_ns", time_monotonic_ns, METH_NOARGS, monotonic_ns_doc},
  1667. {"process_time", time_process_time, METH_NOARGS, process_time_doc},
  1668. {"process_time_ns", time_process_time_ns, METH_NOARGS, process_time_ns_doc},
  1669. #ifdef HAVE_THREAD_TIME
  1670. {"thread_time", time_thread_time, METH_NOARGS, thread_time_doc},
  1671. {"thread_time_ns", time_thread_time_ns, METH_NOARGS, thread_time_ns_doc},
  1672. #endif
  1673. {"perf_counter", time_perf_counter, METH_NOARGS, perf_counter_doc},
  1674. {"perf_counter_ns", time_perf_counter_ns, METH_NOARGS, perf_counter_ns_doc},
  1675. {"get_clock_info", time_get_clock_info, METH_VARARGS, get_clock_info_doc},
  1676. {NULL, NULL} /* sentinel */
  1677. };
  1678. PyDoc_STRVAR(module_doc,
  1679. "This module provides various functions to manipulate time values.\n\
  1680. \n\
  1681. There are two standard representations of time. One is the number\n\
  1682. of seconds since the Epoch, in UTC (a.k.a. GMT). It may be an integer\n\
  1683. or a floating-point number (to represent fractions of seconds).\n\
  1684. The epoch is the point where the time starts, the return value of time.gmtime(0).\n\
  1685. It is January 1, 1970, 00:00:00 (UTC) on all platforms.\n\
  1686. \n\
  1687. The other representation is a tuple of 9 integers giving local time.\n\
  1688. The tuple items are:\n\
  1689. year (including century, e.g. 1998)\n\
  1690. month (1-12)\n\
  1691. day (1-31)\n\
  1692. hours (0-23)\n\
  1693. minutes (0-59)\n\
  1694. seconds (0-59)\n\
  1695. weekday (0-6, Monday is 0)\n\
  1696. Julian day (day in the year, 1-366)\n\
  1697. DST (Daylight Savings Time) flag (-1, 0 or 1)\n\
  1698. If the DST flag is 0, the time is given in the regular time zone;\n\
  1699. if it is 1, the time is given in the DST time zone;\n\
  1700. if it is -1, mktime() should guess based on the date and time.\n");
  1701. static int
  1702. time_exec(PyObject *module)
  1703. {
  1704. time_module_state *state = get_time_state(module);
  1705. #if defined(__APPLE__) && defined(HAVE_CLOCK_GETTIME)
  1706. if (HAVE_CLOCK_GETTIME_RUNTIME) {
  1707. /* pass: ^^^ cannot use '!' here */
  1708. } else {
  1709. PyObject* dct = PyModule_GetDict(module);
  1710. if (dct == NULL) {
  1711. return -1;
  1712. }
  1713. if (PyDict_DelItemString(dct, "clock_gettime") == -1) {
  1714. PyErr_Clear();
  1715. }
  1716. if (PyDict_DelItemString(dct, "clock_gettime_ns") == -1) {
  1717. PyErr_Clear();
  1718. }
  1719. if (PyDict_DelItemString(dct, "clock_settime") == -1) {
  1720. PyErr_Clear();
  1721. }
  1722. if (PyDict_DelItemString(dct, "clock_settime_ns") == -1) {
  1723. PyErr_Clear();
  1724. }
  1725. if (PyDict_DelItemString(dct, "clock_getres") == -1) {
  1726. PyErr_Clear();
  1727. }
  1728. }
  1729. #endif
  1730. #if defined(__APPLE__) && defined(HAVE_THREAD_TIME)
  1731. if (HAVE_CLOCK_GETTIME_RUNTIME) {
  1732. /* pass: ^^^ cannot use '!' here */
  1733. } else {
  1734. PyObject* dct = PyModule_GetDict(module);
  1735. if (PyDict_DelItemString(dct, "thread_time") == -1) {
  1736. PyErr_Clear();
  1737. }
  1738. if (PyDict_DelItemString(dct, "thread_time_ns") == -1) {
  1739. PyErr_Clear();
  1740. }
  1741. }
  1742. #endif
  1743. /* Set, or reset, module variables like time.timezone */
  1744. if (init_timezone(module) < 0) {
  1745. return -1;
  1746. }
  1747. #if defined(HAVE_CLOCK_GETTIME) || defined(HAVE_CLOCK_SETTIME) || defined(HAVE_CLOCK_GETRES)
  1748. if (HAVE_CLOCK_GETTIME_RUNTIME) {
  1749. #ifdef CLOCK_REALTIME
  1750. if (PyModule_AddIntMacro(module, CLOCK_REALTIME) < 0) {
  1751. return -1;
  1752. }
  1753. #endif
  1754. #ifdef CLOCK_MONOTONIC
  1755. if (PyModule_AddIntMacro(module, CLOCK_MONOTONIC) < 0) {
  1756. return -1;
  1757. }
  1758. #endif
  1759. #ifdef CLOCK_MONOTONIC_RAW
  1760. if (PyModule_AddIntMacro(module, CLOCK_MONOTONIC_RAW) < 0) {
  1761. return -1;
  1762. }
  1763. #endif
  1764. #ifdef CLOCK_HIGHRES
  1765. if (PyModule_AddIntMacro(module, CLOCK_HIGHRES) < 0) {
  1766. return -1;
  1767. }
  1768. #endif
  1769. #ifdef CLOCK_PROCESS_CPUTIME_ID
  1770. if (PyModule_AddIntMacro(module, CLOCK_PROCESS_CPUTIME_ID) < 0) {
  1771. return -1;
  1772. }
  1773. #endif
  1774. #ifdef CLOCK_THREAD_CPUTIME_ID
  1775. if (PyModule_AddIntMacro(module, CLOCK_THREAD_CPUTIME_ID) < 0) {
  1776. return -1;
  1777. }
  1778. #endif
  1779. #ifdef CLOCK_PROF
  1780. if (PyModule_AddIntMacro(module, CLOCK_PROF) < 0) {
  1781. return -1;
  1782. }
  1783. #endif
  1784. #ifdef CLOCK_BOOTTIME
  1785. if (PyModule_AddIntMacro(module, CLOCK_BOOTTIME) < 0) {
  1786. return -1;
  1787. }
  1788. #endif
  1789. #ifdef CLOCK_TAI
  1790. if (PyModule_AddIntMacro(module, CLOCK_TAI) < 0) {
  1791. return -1;
  1792. }
  1793. #endif
  1794. #ifdef CLOCK_UPTIME
  1795. if (PyModule_AddIntMacro(module, CLOCK_UPTIME) < 0) {
  1796. return -1;
  1797. }
  1798. #endif
  1799. #ifdef CLOCK_UPTIME_RAW
  1800. if (PyModule_AddIntMacro(module, CLOCK_UPTIME_RAW) < 0) {
  1801. return -1;
  1802. }
  1803. #endif
  1804. }
  1805. #endif /* defined(HAVE_CLOCK_GETTIME) || defined(HAVE_CLOCK_SETTIME) || defined(HAVE_CLOCK_GETRES) */
  1806. if (PyModule_AddIntConstant(module, "_STRUCT_TM_ITEMS", 11)) {
  1807. return -1;
  1808. }
  1809. // struct_time type
  1810. state->struct_time_type = PyStructSequence_NewType(&struct_time_type_desc);
  1811. if (state->struct_time_type == NULL) {
  1812. return -1;
  1813. }
  1814. if (PyModule_AddType(module, state->struct_time_type)) {
  1815. return -1;
  1816. }
  1817. #if defined(__linux__) && !defined(__GLIBC__)
  1818. struct tm tm;
  1819. const time_t zero = 0;
  1820. if (gmtime_r(&zero, &tm) != NULL)
  1821. utc_string = tm.tm_zone;
  1822. #endif
  1823. #if defined(MS_WINDOWS)
  1824. if (timer_flags == (DWORD)-1) {
  1825. DWORD test_flags = CREATE_WAITABLE_TIMER_HIGH_RESOLUTION;
  1826. HANDLE timer = CreateWaitableTimerExW(NULL, NULL, test_flags,
  1827. TIMER_ALL_ACCESS);
  1828. if (timer == NULL) {
  1829. // CREATE_WAITABLE_TIMER_HIGH_RESOLUTION is not supported.
  1830. timer_flags = 0;
  1831. }
  1832. else {
  1833. // CREATE_WAITABLE_TIMER_HIGH_RESOLUTION is supported.
  1834. timer_flags = CREATE_WAITABLE_TIMER_HIGH_RESOLUTION;
  1835. CloseHandle(timer);
  1836. }
  1837. }
  1838. #endif
  1839. return 0;
  1840. }
  1841. static int
  1842. time_module_traverse(PyObject *module, visitproc visit, void *arg)
  1843. {
  1844. time_module_state *state = get_time_state(module);
  1845. Py_VISIT(state->struct_time_type);
  1846. return 0;
  1847. }
  1848. static int
  1849. time_module_clear(PyObject *module)
  1850. {
  1851. time_module_state *state = get_time_state(module);
  1852. Py_CLEAR(state->struct_time_type);
  1853. return 0;
  1854. }
  1855. static void
  1856. time_module_free(void *module)
  1857. {
  1858. time_module_clear((PyObject *)module);
  1859. }
  1860. static struct PyModuleDef_Slot time_slots[] = {
  1861. {Py_mod_exec, time_exec},
  1862. {Py_mod_multiple_interpreters, Py_MOD_PER_INTERPRETER_GIL_SUPPORTED},
  1863. {0, NULL}
  1864. };
  1865. static struct PyModuleDef timemodule = {
  1866. PyModuleDef_HEAD_INIT,
  1867. .m_name = "time",
  1868. .m_doc = module_doc,
  1869. .m_size = sizeof(time_module_state),
  1870. .m_methods = time_methods,
  1871. .m_slots = time_slots,
  1872. .m_traverse = time_module_traverse,
  1873. .m_clear = time_module_clear,
  1874. .m_free = time_module_free,
  1875. };
  1876. PyMODINIT_FUNC
  1877. PyInit_time(void)
  1878. {
  1879. return PyModuleDef_Init(&timemodule);
  1880. }
  1881. // time.sleep() implementation.
  1882. // On error, raise an exception and return -1.
  1883. // On success, return 0.
  1884. static int
  1885. pysleep(_PyTime_t timeout)
  1886. {
  1887. assert(timeout >= 0);
  1888. #ifndef MS_WINDOWS
  1889. #ifdef HAVE_CLOCK_NANOSLEEP
  1890. struct timespec timeout_abs;
  1891. #elif defined(HAVE_NANOSLEEP)
  1892. struct timespec timeout_ts;
  1893. #else
  1894. struct timeval timeout_tv;
  1895. #endif
  1896. _PyTime_t deadline, monotonic;
  1897. int err = 0;
  1898. if (get_monotonic(&monotonic) < 0) {
  1899. return -1;
  1900. }
  1901. deadline = monotonic + timeout;
  1902. #ifdef HAVE_CLOCK_NANOSLEEP
  1903. if (_PyTime_AsTimespec(deadline, &timeout_abs) < 0) {
  1904. return -1;
  1905. }
  1906. #endif
  1907. do {
  1908. #ifdef HAVE_CLOCK_NANOSLEEP
  1909. // use timeout_abs
  1910. #elif defined(HAVE_NANOSLEEP)
  1911. if (_PyTime_AsTimespec(timeout, &timeout_ts) < 0) {
  1912. return -1;
  1913. }
  1914. #else
  1915. if (_PyTime_AsTimeval(timeout, &timeout_tv, _PyTime_ROUND_CEILING) < 0) {
  1916. return -1;
  1917. }
  1918. #endif
  1919. int ret;
  1920. Py_BEGIN_ALLOW_THREADS
  1921. #ifdef HAVE_CLOCK_NANOSLEEP
  1922. ret = clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &timeout_abs, NULL);
  1923. err = ret;
  1924. #elif defined(HAVE_NANOSLEEP)
  1925. ret = nanosleep(&timeout_ts, NULL);
  1926. err = errno;
  1927. #else
  1928. ret = select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &timeout_tv);
  1929. err = errno;
  1930. #endif
  1931. Py_END_ALLOW_THREADS
  1932. if (ret == 0) {
  1933. break;
  1934. }
  1935. if (err != EINTR) {
  1936. errno = err;
  1937. PyErr_SetFromErrno(PyExc_OSError);
  1938. return -1;
  1939. }
  1940. /* sleep was interrupted by SIGINT */
  1941. if (PyErr_CheckSignals()) {
  1942. return -1;
  1943. }
  1944. #ifndef HAVE_CLOCK_NANOSLEEP
  1945. if (get_monotonic(&monotonic) < 0) {
  1946. return -1;
  1947. }
  1948. timeout = deadline - monotonic;
  1949. if (timeout < 0) {
  1950. break;
  1951. }
  1952. /* retry with the recomputed delay */
  1953. #endif
  1954. } while (1);
  1955. return 0;
  1956. #else // MS_WINDOWS
  1957. _PyTime_t timeout_100ns = _PyTime_As100Nanoseconds(timeout,
  1958. _PyTime_ROUND_CEILING);
  1959. // Maintain Windows Sleep() semantics for time.sleep(0)
  1960. if (timeout_100ns == 0) {
  1961. Py_BEGIN_ALLOW_THREADS
  1962. // A value of zero causes the thread to relinquish the remainder of its
  1963. // time slice to any other thread that is ready to run. If there are no
  1964. // other threads ready to run, the function returns immediately, and
  1965. // the thread continues execution.
  1966. Sleep(0);
  1967. Py_END_ALLOW_THREADS
  1968. return 0;
  1969. }
  1970. LARGE_INTEGER relative_timeout;
  1971. // No need to check for integer overflow, both types are signed
  1972. assert(sizeof(relative_timeout) == sizeof(timeout_100ns));
  1973. // SetWaitableTimer(): a negative due time indicates relative time
  1974. relative_timeout.QuadPart = -timeout_100ns;
  1975. HANDLE timer = CreateWaitableTimerExW(NULL, NULL, timer_flags,
  1976. TIMER_ALL_ACCESS);
  1977. if (timer == NULL) {
  1978. PyErr_SetFromWindowsErr(0);
  1979. return -1;
  1980. }
  1981. if (!SetWaitableTimerEx(timer, &relative_timeout,
  1982. 0, // no period; the timer is signaled once
  1983. NULL, NULL, // no completion routine
  1984. NULL, // no wake context; do not resume from suspend
  1985. 0)) // no tolerable delay for timer coalescing
  1986. {
  1987. PyErr_SetFromWindowsErr(0);
  1988. goto error;
  1989. }
  1990. // Only the main thread can be interrupted by SIGINT.
  1991. // Signal handlers are only executed in the main thread.
  1992. if (_PyOS_IsMainThread()) {
  1993. HANDLE sigint_event = _PyOS_SigintEvent();
  1994. while (1) {
  1995. // Check for pending SIGINT signal before resetting the event
  1996. if (PyErr_CheckSignals()) {
  1997. goto error;
  1998. }
  1999. ResetEvent(sigint_event);
  2000. HANDLE events[] = {timer, sigint_event};
  2001. DWORD rc;
  2002. Py_BEGIN_ALLOW_THREADS
  2003. rc = WaitForMultipleObjects(Py_ARRAY_LENGTH(events), events,
  2004. // bWaitAll
  2005. FALSE,
  2006. // No wait timeout
  2007. INFINITE);
  2008. Py_END_ALLOW_THREADS
  2009. if (rc == WAIT_FAILED) {
  2010. PyErr_SetFromWindowsErr(0);
  2011. goto error;
  2012. }
  2013. if (rc == WAIT_OBJECT_0) {
  2014. // Timer signaled: we are done
  2015. break;
  2016. }
  2017. assert(rc == (WAIT_OBJECT_0 + 1));
  2018. // The sleep was interrupted by SIGINT: restart sleeping
  2019. }
  2020. }
  2021. else {
  2022. DWORD rc;
  2023. Py_BEGIN_ALLOW_THREADS
  2024. rc = WaitForSingleObject(timer, INFINITE);
  2025. Py_END_ALLOW_THREADS
  2026. if (rc == WAIT_FAILED) {
  2027. PyErr_SetFromWindowsErr(0);
  2028. goto error;
  2029. }
  2030. assert(rc == WAIT_OBJECT_0);
  2031. // Timer signaled: we are done
  2032. }
  2033. CloseHandle(timer);
  2034. return 0;
  2035. error:
  2036. CloseHandle(timer);
  2037. return -1;
  2038. #endif
  2039. }