This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
perlapi: Document __ASSERT_
[perl5.git] / dist / Time-HiRes / HiRes.xs
1 /*
2  *
3  * Copyright (c) 1996-2002 Douglas E. Wegscheid.  All rights reserved.
4  *
5  * Copyright (c) 2002-2010 Jarkko Hietaniemi.
6  * All rights reserved.
7  *
8  * Copyright (C) 2011, 2012, 2013 Andrew Main (Zefram) <zefram@fysh.org>
9  *
10  * This program is free software; you can redistribute it and/or modify
11  * it under the same terms as Perl itself.
12  */
13
14 #ifdef __cplusplus
15 extern "C" {
16 #endif
17 #define PERL_NO_GET_CONTEXT
18 #include "EXTERN.h"
19 #include "perl.h"
20 #include "XSUB.h"
21 #ifdef USE_PPPORT_H
22 #  include "ppport.h"
23 #endif
24 #if defined(__CYGWIN__) && defined(HAS_W32API_WINDOWS_H)
25 #  include <w32api/windows.h>
26 #  define CYGWIN_WITH_W32API
27 #endif
28 #ifdef WIN32
29 #  include <time.h>
30 #else
31 #  include <sys/time.h>
32 #endif
33 #ifdef HAS_SELECT
34 #  ifdef I_SYS_SELECT
35 #    include <sys/select.h>
36 #  endif
37 #endif
38 #if defined(TIME_HIRES_CLOCK_GETTIME_SYSCALL) || defined(TIME_HIRES_CLOCK_GETRES_SYSCALL)
39 #  include <syscall.h>
40 #endif
41 #ifdef __cplusplus
42 }
43 #endif
44
45 #define PERL_VERSION_DECIMAL(r,v,s) (r*1000000 + v*1000 + s)
46 #define PERL_DECIMAL_VERSION \
47         PERL_VERSION_DECIMAL(PERL_REVISION,PERL_VERSION,PERL_SUBVERSION)
48 #define PERL_VERSION_GE(r,v,s) \
49         (PERL_DECIMAL_VERSION >= PERL_VERSION_DECIMAL(r,v,s))
50
51 #ifndef GCC_DIAG_IGNORE
52 #  define GCC_DIAG_IGNORE(x)
53 #  define GCC_DIAG_RESTORE
54 #endif
55 #ifndef GCC_DIAG_IGNORE_STMT
56 #  define GCC_DIAG_IGNORE_STMT(x) GCC_DIAG_IGNORE(x) NOOP
57 #  define GCC_DIAG_RESTORE_STMT GCC_DIAG_RESTORE NOOP
58 #endif
59
60 #if PERL_VERSION_GE(5,7,3) && !PERL_VERSION_GE(5,10,1)
61 #  undef SAVEOP
62 #  define SAVEOP() SAVEVPTR(PL_op)
63 #endif
64
65 #define IV_1E6 1000000
66 #define IV_1E7 10000000
67 #define IV_1E9 1000000000
68
69 #define NV_1E6 1000000.0
70 #define NV_1E7 10000000.0
71 #define NV_1E9 1000000000.0
72
73 #ifndef PerlProc_pause
74 #  define PerlProc_pause() Pause()
75 #endif
76
77 #ifdef HAS_PAUSE
78 #  define Pause   pause
79 #else
80 #  undef Pause /* In case perl.h did it already. */
81 #  define Pause() sleep(~0) /* Zzz for a long time. */
82 #endif
83
84 /* Though the cpp define ITIMER_VIRTUAL is available the functionality
85  * is not supported in Cygwin as of August 2004, ditto for Win32.
86  * Neither are ITIMER_PROF or ITIMER_REALPROF implemented.  --jhi
87  */
88 #if defined(__CYGWIN__) || defined(WIN32)
89 #  undef ITIMER_VIRTUAL
90 #  undef ITIMER_PROF
91 #  undef ITIMER_REALPROF
92 #endif
93
94 #ifndef TIME_HIRES_CLOCKID_T
95 typedef int clockid_t;
96 #endif
97
98 #if defined(TIME_HIRES_CLOCK_GETTIME) && defined(_STRUCT_ITIMERSPEC)
99
100 /* HP-UX has CLOCK_XXX values but as enums, not as defines.
101  * The only way to detect these would be to test compile for each. */
102 #  ifdef __hpux
103 /* However, it seems that at least in HP-UX 11.31 ia64 there *are*
104  * defines for these, so let's try detecting them. */
105 #    ifndef CLOCK_REALTIME
106 #      define CLOCK_REALTIME CLOCK_REALTIME
107 #      define CLOCK_VIRTUAL  CLOCK_VIRTUAL
108 #      define CLOCK_PROFILE  CLOCK_PROFILE
109 #    endif
110 #  endif /* # ifdef __hpux */
111
112 #endif /* #if defined(TIME_HIRES_CLOCK_GETTIME) && defined(_STRUCT_ITIMERSPEC) */
113
114 #if defined(WIN32) || defined(CYGWIN_WITH_W32API)
115
116 #  ifndef HAS_GETTIMEOFDAY
117 #    define HAS_GETTIMEOFDAY
118 #  endif
119
120 /* shows up in winsock.h?
121 struct timeval {
122     long tv_sec;
123     long tv_usec;
124 }
125 */
126
127 typedef union {
128     unsigned __int64    ft_i64;
129     FILETIME            ft_val;
130 } FT_t;
131
132 #  define MY_CXT_KEY "Time::HiRes_" XS_VERSION
133
134 typedef struct {
135     unsigned long run_count;
136     unsigned __int64 base_ticks;
137     unsigned __int64 tick_frequency;
138     FT_t base_systime_as_filetime;
139     unsigned __int64 reset_time;
140 } my_cxt_t;
141
142 START_MY_CXT
143
144 /* Number of 100 nanosecond units from 1/1/1601 to 1/1/1970 */
145 #  ifdef __GNUC__
146 #    define Const64(x) x##LL
147 #  else
148 #    define Const64(x) x##i64
149 #  endif
150 #  define EPOCH_BIAS  Const64(116444736000000000)
151
152 #  ifdef Const64
153 #    ifdef __GNUC__
154 #      define IV_1E6LL  1000000LL /* Needed because of Const64() ##-appends LL (or i64). */
155 #      define IV_1E7LL  10000000LL
156 #      define IV_1E9LL  1000000000LL
157 #    else
158 #      define IV_1E6i64 1000000i64
159 #      define IV_1E7i64 10000000i64
160 #      define IV_1E9i64 1000000000i64
161 #    endif
162 #  endif
163
164 /* NOTE: This does not compute the timezone info (doing so can be expensive,
165  * and appears to be unsupported even by glibc) */
166
167 /* dMY_CXT needs a Perl context and we don't want to call PERL_GET_CONTEXT
168    for performance reasons */
169
170 #  undef gettimeofday
171 #  define gettimeofday(tp, not_used) _gettimeofday(aTHX_ tp, not_used)
172
173 /* If the performance counter delta drifts more than 0.5 seconds from the
174  * system time then we recalibrate to the system time.  This means we may
175  * move *backwards* in time! */
176 #  define MAX_PERF_COUNTER_SKEW Const64(5000000) /* 0.5 seconds */
177
178 /* Reset reading from the performance counter every five minutes.
179  * Many PC clocks just seem to be so bad. */
180 #  define MAX_PERF_COUNTER_TICKS Const64(300000000) /* 300 seconds */
181
182 static int
183 _gettimeofday(pTHX_ struct timeval *tp, void *not_used)
184 {
185     dMY_CXT;
186
187     unsigned __int64 ticks;
188     FT_t ft;
189
190     PERL_UNUSED_ARG(not_used);
191     if (MY_CXT.run_count++ == 0 ||
192         MY_CXT.base_systime_as_filetime.ft_i64 > MY_CXT.reset_time) {
193
194         QueryPerformanceFrequency((LARGE_INTEGER*)&MY_CXT.tick_frequency);
195         QueryPerformanceCounter((LARGE_INTEGER*)&MY_CXT.base_ticks);
196         GetSystemTimeAsFileTime(&MY_CXT.base_systime_as_filetime.ft_val);
197         ft.ft_i64 = MY_CXT.base_systime_as_filetime.ft_i64;
198         MY_CXT.reset_time = ft.ft_i64 + MAX_PERF_COUNTER_TICKS;
199     }
200     else {
201         __int64 diff;
202         QueryPerformanceCounter((LARGE_INTEGER*)&ticks);
203         ticks -= MY_CXT.base_ticks;
204         ft.ft_i64 = MY_CXT.base_systime_as_filetime.ft_i64
205                     + Const64(IV_1E7) * (ticks / MY_CXT.tick_frequency)
206                     +(Const64(IV_1E7) * (ticks % MY_CXT.tick_frequency)) / MY_CXT.tick_frequency;
207         diff = ft.ft_i64 - MY_CXT.base_systime_as_filetime.ft_i64;
208         if (diff < -MAX_PERF_COUNTER_SKEW || diff > MAX_PERF_COUNTER_SKEW) {
209             MY_CXT.base_ticks += ticks;
210             GetSystemTimeAsFileTime(&MY_CXT.base_systime_as_filetime.ft_val);
211             ft.ft_i64 = MY_CXT.base_systime_as_filetime.ft_i64;
212         }
213     }
214
215     /* seconds since epoch */
216     tp->tv_sec = (long)((ft.ft_i64 - EPOCH_BIAS) / Const64(IV_1E7));
217
218     /* microseconds remaining */
219     tp->tv_usec = (long)((ft.ft_i64 / Const64(10)) % Const64(IV_1E6));
220
221     return 0;
222 }
223 #endif /* #if defined(WIN32) || defined(CYGWIN_WITH_W32API) */
224
225 #if !defined(HAS_GETTIMEOFDAY) && defined(VMS)
226 #  define HAS_GETTIMEOFDAY
227
228 #  include <lnmdef.h>
229 #  include <time.h> /* gettimeofday */
230 #  include <stdlib.h> /* qdiv */
231 #  include <starlet.h> /* sys$gettim */
232 #  include <descrip.h>
233 #  ifdef __VAX
234 #    include <lib$routines.h> /* lib$ediv() */
235 #  endif
236
237 /*
238         VMS binary time is expressed in 100 nano-seconds since
239         system base time which is 17-NOV-1858 00:00:00.00
240 */
241
242 #  define DIV_100NS_TO_SECS  10000000L
243 #  define DIV_100NS_TO_USECS 10L
244
245 /*
246         gettimeofday is supposed to return times since the epoch
247         so need to determine this in terms of VMS base time
248 */
249 static $DESCRIPTOR(dscepoch,"01-JAN-1970 00:00:00.00");
250
251 #  ifdef __VAX
252 static long base_adjust[2]={0L,0L};
253 #  else
254 static __int64 base_adjust=0;
255 #  endif
256
257 /*
258
259    If we don't have gettimeofday, then likely we are on a VMS machine that
260    operates on local time rather than UTC...so we have to zone-adjust.
261    This code gleefully swiped from VMS.C
262
263 */
264 /* method used to handle UTC conversions:
265  *   1 == CRTL gmtime();  2 == SYS$TIMEZONE_DIFFERENTIAL;  3 == no correction
266  */
267 static int gmtime_emulation_type;
268 /* number of secs to add to UTC POSIX-style time to get local time */
269 static long int utc_offset_secs;
270 static struct dsc$descriptor_s fildevdsc =
271     { 12, DSC$K_DTYPE_T, DSC$K_CLASS_S, "LNM$FILE_DEV" };
272 static struct dsc$descriptor_s *fildev[] = { &fildevdsc, NULL };
273
274 static time_t toutc_dst(time_t loc) {
275     struct tm *rsltmp;
276
277     if ((rsltmp = localtime(&loc)) == NULL) return -1;
278     loc -= utc_offset_secs;
279     if (rsltmp->tm_isdst) loc -= 3600;
280     return loc;
281 }
282
283 static time_t toloc_dst(time_t utc) {
284     struct tm *rsltmp;
285
286     utc += utc_offset_secs;
287     if ((rsltmp = localtime(&utc)) == NULL) return -1;
288     if (rsltmp->tm_isdst) utc += 3600;
289     return utc;
290 }
291
292 #  define _toutc(secs)  ((secs) == (time_t) -1 ? (time_t) -1 : \
293           ((gmtime_emulation_type || timezone_setup()), \
294           (gmtime_emulation_type == 1 ? toutc_dst(secs) : \
295           ((secs) - utc_offset_secs))))
296
297 #  define _toloc(secs)  ((secs) == (time_t) -1 ? (time_t) -1 : \
298           ((gmtime_emulation_type || timezone_setup()), \
299           (gmtime_emulation_type == 1 ? toloc_dst(secs) : \
300           ((secs) + utc_offset_secs))))
301
302 static int
303 timezone_setup(void)
304 {
305     struct tm *tm_p;
306
307     if (gmtime_emulation_type == 0) {
308         int dstnow;
309         time_t base = 15 * 86400; /* 15jan71; to avoid month/year ends between    */
310                                   /* results of calls to gmtime() and localtime() */
311                                   /* for same &base */
312
313         gmtime_emulation_type++;
314         if ((tm_p = gmtime(&base)) == NULL) { /* CRTL gmtime() is a fake */
315             char off[LNM$C_NAMLENGTH+1];;
316
317             gmtime_emulation_type++;
318             if (!Perl_vmstrnenv("SYS$TIMEZONE_DIFFERENTIAL",off,0,fildev,0)) {
319                 gmtime_emulation_type++;
320                 utc_offset_secs = 0;
321                 Perl_warn(aTHX_ "no UTC offset information; assuming local time is UTC");
322             }
323             else { utc_offset_secs = atol(off); }
324         }
325         else { /* We've got a working gmtime() */
326             struct tm gmt, local;
327
328             gmt = *tm_p;
329             tm_p = localtime(&base);
330             local = *tm_p;
331             utc_offset_secs  = (local.tm_mday - gmt.tm_mday) * 86400;
332             utc_offset_secs += (local.tm_hour - gmt.tm_hour) * 3600;
333             utc_offset_secs += (local.tm_min  - gmt.tm_min)  * 60;
334             utc_offset_secs += (local.tm_sec  - gmt.tm_sec);
335         }
336     }
337     return 1;
338 }
339
340
341 int
342 gettimeofday (struct timeval *tp, void *tpz)
343 {
344     long ret;
345 #  ifdef __VAX
346     long quad[2];
347     long quad1[2];
348     long div_100ns_to_secs;
349     long div_100ns_to_usecs;
350     long quo,rem;
351     long quo1,rem1;
352 #  else
353     __int64 quad;
354     __qdiv_t ans1,ans2;
355 #  endif
356     /*
357         In case of error, tv_usec = 0 and tv_sec = VMS condition code.
358         The return from function is also set to -1.
359         This is not exactly as per the manual page.
360     */
361
362     tp->tv_usec = 0;
363
364 #  ifdef __VAX
365     if (base_adjust[0]==0 && base_adjust[1]==0) {
366 #  else
367     if (base_adjust==0) { /* Need to determine epoch adjustment */
368 #  endif
369         ret=sys$bintim(&dscepoch,&base_adjust);
370         if (1 != (ret &&1)) {
371             tp->tv_sec = ret;
372             return -1;
373         }
374     }
375
376     ret=sys$gettim(&quad); /* Get VMS system time */
377     if ((1 && ret) == 1) {
378 #  ifdef __VAX
379         quad[0] -= base_adjust[0]; /* convert to epoch offset */
380         quad[1] -= base_adjust[1]; /* convert 2nd half of quadword */
381         div_100ns_to_secs = DIV_100NS_TO_SECS;
382         div_100ns_to_usecs = DIV_100NS_TO_USECS;
383         lib$ediv(&div_100ns_to_secs,&quad,&quo,&rem);
384         quad1[0] = rem;
385         quad1[1] = 0L;
386         lib$ediv(&div_100ns_to_usecs,&quad1,&quo1,&rem1);
387         tp->tv_sec = quo; /* Whole seconds */
388         tp->tv_usec = quo1; /* Micro-seconds */
389 #  else
390         quad -= base_adjust; /* convert to epoch offset */
391         ans1=qdiv(quad,DIV_100NS_TO_SECS);
392         ans2=qdiv(ans1.rem,DIV_100NS_TO_USECS);
393         tp->tv_sec = ans1.quot; /* Whole seconds */
394         tp->tv_usec = ans2.quot; /* Micro-seconds */
395 #  endif
396     } else {
397         tp->tv_sec = ret;
398         return -1;
399     }
400 #  ifdef VMSISH_TIME
401 #    ifdef RTL_USES_UTC
402     if (VMSISH_TIME) tp->tv_sec = _toloc(tp->tv_sec);
403 #    else
404     if (!VMSISH_TIME) tp->tv_sec = _toutc(tp->tv_sec);
405 #    endif
406 #  endif
407     return 0;
408 }
409 #endif /* #if !defined(HAS_GETTIMEOFDAY) && defined(VMS) */
410
411
412  /* Do not use H A S _ N A N O S L E E P
413   * so that Perl Configure doesn't scan for it (and pull in -lrt and
414   * the like which are not usually good ideas for the default Perl).
415   * (We are part of the core perl now.)
416   * The TIME_HIRES_NANOSLEEP is set by Makefile.PL. */
417 #if !defined(HAS_USLEEP) && defined(TIME_HIRES_NANOSLEEP)
418 #  define HAS_USLEEP
419 #  define usleep hrt_usleep  /* could conflict with ncurses for static build */
420
421 static void
422 hrt_usleep(unsigned long usec) /* This is used to emulate usleep. */
423 {
424     struct timespec res;
425     res.tv_sec = usec / IV_1E6;
426     res.tv_nsec = ( usec - res.tv_sec * IV_1E6 ) * 1000;
427     nanosleep(&res, NULL);
428 }
429
430 #endif /* #if !defined(HAS_USLEEP) && defined(TIME_HIRES_NANOSLEEP) */
431
432 #if !defined(HAS_USLEEP) && defined(HAS_SELECT)
433 #  ifndef SELECT_IS_BROKEN
434 #    define HAS_USLEEP
435 #    define usleep hrt_usleep  /* could conflict with ncurses for static build */
436
437 static void
438 hrt_usleep(unsigned long usec)
439 {
440     struct timeval tv;
441     tv.tv_sec = 0;
442     tv.tv_usec = usec;
443     select(0, (Select_fd_set_t)NULL, (Select_fd_set_t)NULL,
444         (Select_fd_set_t)NULL, &tv);
445 }
446 #  endif
447 #endif /* #if !defined(HAS_USLEEP) && defined(HAS_SELECT) */
448
449 #if !defined(HAS_USLEEP) && defined(WIN32)
450 #  define HAS_USLEEP
451 #  define usleep hrt_usleep  /* could conflict with ncurses for static build */
452
453 static void
454 hrt_usleep(unsigned long usec)
455 {
456     long msec;
457     msec = usec / 1000;
458     Sleep (msec);
459 }
460 #endif /* #if !defined(HAS_USLEEP) && defined(WIN32) */
461
462 #if !defined(HAS_USLEEP) && defined(HAS_POLL)
463 #  define HAS_USLEEP
464 #  define usleep hrt_usleep  /* could conflict with ncurses for static build */
465
466 static void
467 hrt_usleep(unsigned long usec)
468 {
469     int msec = usec / 1000;
470     poll(0, 0, msec);
471 }
472
473 #endif /* #if !defined(HAS_USLEEP) && defined(HAS_POLL) */
474
475 #if defined(HAS_SETITIMER) && defined(ITIMER_REAL)
476
477 static int
478 hrt_ualarm_itimero(struct itimerval *oitv, int usec, int uinterval)
479 {
480     struct itimerval itv;
481     itv.it_value.tv_sec = usec / IV_1E6;
482     itv.it_value.tv_usec = usec % IV_1E6;
483     itv.it_interval.tv_sec = uinterval / IV_1E6;
484     itv.it_interval.tv_usec = uinterval % IV_1E6;
485     return setitimer(ITIMER_REAL, &itv, oitv);
486 }
487
488 #endif /* #if !defined(HAS_UALARM) && defined(HAS_SETITIMER) */
489
490 #if !defined(HAS_UALARM) && defined(HAS_SETITIMER)
491 #  define HAS_UALARM
492 #  define ualarm hrt_ualarm_itimer  /* could conflict with ncurses for static build */
493 #endif
494
495 #if !defined(HAS_UALARM) && defined(VMS)
496 #  define HAS_UALARM
497 #  define ualarm vms_ualarm
498
499 #  include <lib$routines.h>
500 #  include <ssdef.h>
501 #  include <starlet.h>
502 #  include <descrip.h>
503 #  include <signal.h>
504 #  include <jpidef.h>
505 #  include <psldef.h>
506
507 #  define VMSERR(s)   (!((s)&1))
508
509 static void
510 us_to_VMS(useconds_t mseconds, unsigned long v[])
511 {
512     int iss;
513     unsigned long qq[2];
514
515     qq[0] = mseconds;
516     qq[1] = 0;
517     v[0] = v[1] = 0;
518
519     iss = lib$addx(qq,qq,qq);
520     if (VMSERR(iss)) lib$signal(iss);
521     iss = lib$subx(v,qq,v);
522     if (VMSERR(iss)) lib$signal(iss);
523     iss = lib$addx(qq,qq,qq);
524     if (VMSERR(iss)) lib$signal(iss);
525     iss = lib$subx(v,qq,v);
526     if (VMSERR(iss)) lib$signal(iss);
527     iss = lib$subx(v,qq,v);
528     if (VMSERR(iss)) lib$signal(iss);
529 }
530
531 static int
532 VMS_to_us(unsigned long v[])
533 {
534     int iss;
535     unsigned long div=10,quot, rem;
536
537     iss = lib$ediv(&div,v,&quot,&rem);
538     if (VMSERR(iss)) lib$signal(iss);
539
540     return quot;
541 }
542
543 typedef unsigned short word;
544 typedef struct _ualarm {
545     int function;
546     int repeat;
547     unsigned long delay[2];
548     unsigned long interval[2];
549     unsigned long remain[2];
550 } Alarm;
551
552
553 static int alarm_ef;
554 static Alarm *a0, alarm_base;
555 #  define UAL_NULL   0
556 #  define UAL_SET    1
557 #  define UAL_CLEAR  2
558 #  define UAL_ACTIVE 4
559 static void ualarm_AST(Alarm *a);
560
561 static int
562 vms_ualarm(int mseconds, int interval)
563 {
564     Alarm *a, abase;
565     struct item_list3 {
566         word length;
567         word code;
568         void *bufaddr;
569         void *retlenaddr;
570     } ;
571     static struct item_list3 itmlst[2];
572     static int first = 1;
573     unsigned long asten;
574     int iss, enabled;
575
576     if (first) {
577         first = 0;
578         itmlst[0].code       = JPI$_ASTEN;
579         itmlst[0].length     = sizeof(asten);
580         itmlst[0].retlenaddr = NULL;
581         itmlst[1].code       = 0;
582         itmlst[1].length     = 0;
583         itmlst[1].bufaddr    = NULL;
584         itmlst[1].retlenaddr = NULL;
585
586         iss = lib$get_ef(&alarm_ef);
587         if (VMSERR(iss)) lib$signal(iss);
588
589         a0 = &alarm_base;
590         a0->function = UAL_NULL;
591     }
592     itmlst[0].bufaddr    = &asten;
593
594     iss = sys$getjpiw(0,0,0,itmlst,0,0,0);
595     if (VMSERR(iss)) lib$signal(iss);
596     if (!(asten&0x08)) return -1;
597
598     a = &abase;
599     if (mseconds) {
600         a->function = UAL_SET;
601     } else {
602         a->function = UAL_CLEAR;
603     }
604
605     us_to_VMS(mseconds, a->delay);
606     if (interval) {
607         us_to_VMS(interval, a->interval);
608         a->repeat = 1;
609     } else
610         a->repeat = 0;
611
612     iss = sys$clref(alarm_ef);
613     if (VMSERR(iss)) lib$signal(iss);
614
615     iss = sys$dclast(ualarm_AST,a,0);
616     if (VMSERR(iss)) lib$signal(iss);
617
618     iss = sys$waitfr(alarm_ef);
619     if (VMSERR(iss)) lib$signal(iss);
620
621     if (a->function == UAL_ACTIVE)
622         return VMS_to_us(a->remain);
623     else
624         return 0;
625 }
626
627
628
629 static void
630 ualarm_AST(Alarm *a)
631 {
632     int iss;
633     unsigned long now[2];
634
635     iss = sys$gettim(now);
636     if (VMSERR(iss)) lib$signal(iss);
637
638     if (a->function == UAL_SET || a->function == UAL_CLEAR) {
639         if (a0->function == UAL_ACTIVE) {
640             iss = sys$cantim(a0,PSL$C_USER);
641             if (VMSERR(iss)) lib$signal(iss);
642
643             iss = lib$subx(a0->remain, now, a->remain);
644             if (VMSERR(iss)) lib$signal(iss);
645
646             if (a->remain[1] & 0x80000000)
647                 a->remain[0] = a->remain[1] = 0;
648         }
649
650         if (a->function == UAL_SET) {
651             a->function = a0->function;
652             a0->function = UAL_ACTIVE;
653             a0->repeat = a->repeat;
654             if (a0->repeat) {
655                 a0->interval[0] = a->interval[0];
656                 a0->interval[1] = a->interval[1];
657             }
658             a0->delay[0] = a->delay[0];
659             a0->delay[1] = a->delay[1];
660
661             iss = lib$subx(now, a0->delay, a0->remain);
662             if (VMSERR(iss)) lib$signal(iss);
663
664             iss = sys$setimr(0,a0->delay,ualarm_AST,a0);
665             if (VMSERR(iss)) lib$signal(iss);
666         } else {
667             a->function = a0->function;
668             a0->function = UAL_NULL;
669         }
670         iss = sys$setef(alarm_ef);
671         if (VMSERR(iss)) lib$signal(iss);
672     } else if (a->function == UAL_ACTIVE) {
673         if (a->repeat) {
674             iss = lib$subx(now, a->interval, a->remain);
675             if (VMSERR(iss)) lib$signal(iss);
676
677             iss = sys$setimr(0,a->interval,ualarm_AST,a);
678             if (VMSERR(iss)) lib$signal(iss);
679         } else {
680             a->function = UAL_NULL;
681         }
682         iss = sys$wake(0,0);
683         if (VMSERR(iss)) lib$signal(iss);
684         lib$signal(SS$_ASTFLT);
685     } else {
686         lib$signal(SS$_BADPARAM);
687     }
688 }
689
690 #endif /* #if !defined(HAS_UALARM) && defined(VMS) */
691
692 #ifdef HAS_GETTIMEOFDAY
693
694 static int
695 myU2time(pTHX_ UV *ret)
696 {
697     struct timeval Tp;
698     int status;
699     status = gettimeofday (&Tp, NULL);
700     ret[0] = Tp.tv_sec;
701     ret[1] = Tp.tv_usec;
702     return status;
703 }
704
705 static NV
706 myNVtime()
707 {
708 #  ifdef WIN32
709     dTHX;
710 #  endif
711     struct timeval Tp;
712     int status;
713     status = gettimeofday (&Tp, NULL);
714     return status == 0 ? Tp.tv_sec + (Tp.tv_usec / NV_1E6) : -1.0;
715 }
716
717 #endif /* #ifdef HAS_GETTIMEOFDAY */
718
719 static void
720 hrstatns(UV *atime_nsec, UV *mtime_nsec, UV *ctime_nsec)
721 {
722     dTHX;
723 #if TIME_HIRES_STAT == 1
724     *atime_nsec = PL_statcache.st_atimespec.tv_nsec;
725     *mtime_nsec = PL_statcache.st_mtimespec.tv_nsec;
726     *ctime_nsec = PL_statcache.st_ctimespec.tv_nsec;
727 #elif TIME_HIRES_STAT == 2
728     *atime_nsec = PL_statcache.st_atimensec;
729     *mtime_nsec = PL_statcache.st_mtimensec;
730     *ctime_nsec = PL_statcache.st_ctimensec;
731 #elif TIME_HIRES_STAT == 3
732     *atime_nsec = PL_statcache.st_atime_n;
733     *mtime_nsec = PL_statcache.st_mtime_n;
734     *ctime_nsec = PL_statcache.st_ctime_n;
735 #elif TIME_HIRES_STAT == 4
736     *atime_nsec = PL_statcache.st_atim.tv_nsec;
737     *mtime_nsec = PL_statcache.st_mtim.tv_nsec;
738     *ctime_nsec = PL_statcache.st_ctim.tv_nsec;
739 #elif TIME_HIRES_STAT == 5
740     *atime_nsec = PL_statcache.st_uatime * 1000;
741     *mtime_nsec = PL_statcache.st_umtime * 1000;
742     *ctime_nsec = PL_statcache.st_uctime * 1000;
743 #else /* !TIME_HIRES_STAT */
744     *atime_nsec = 0;
745     *mtime_nsec = 0;
746     *ctime_nsec = 0;
747 #endif /* !TIME_HIRES_STAT */
748 }
749
750 /* Until Apple implements clock_gettime()
751  * (ditto clock_getres() and clock_nanosleep())
752  * we will emulate them using the Mach kernel interfaces. */
753 #if defined(PERL_DARWIN) && \
754   (defined(TIME_HIRES_CLOCK_GETTIME_EMULATION)   || \
755    defined(TIME_HIRES_CLOCK_GETRES_EMULATION)    || \
756    defined(TIME_HIRES_CLOCK_NANOSLEEP_EMULATION))
757
758 #  ifndef CLOCK_REALTIME
759 #    define CLOCK_REALTIME  0x01
760 #    define CLOCK_MONOTONIC 0x02
761 #  endif
762
763 #  ifndef TIMER_ABSTIME
764 #    define TIMER_ABSTIME   0x01
765 #  endif
766
767 #  ifdef USE_ITHREADS
768 #    define PERL_DARWIN_MUTEX
769 #  endif
770
771 #  ifdef PERL_DARWIN_MUTEX
772 STATIC perl_mutex darwin_time_mutex;
773 #  endif
774
775 #  include <mach/mach_time.h>
776
777 static uint64_t absolute_time_init;
778 static mach_timebase_info_data_t timebase_info;
779 static struct timespec timespec_init;
780
781 static int darwin_time_init() {
782     struct timeval tv;
783     int success = 1;
784 #  ifdef PERL_DARWIN_MUTEX
785     MUTEX_LOCK(&darwin_time_mutex);
786 #  endif
787     if (absolute_time_init == 0) {
788         /* mach_absolute_time() cannot fail */
789         absolute_time_init = mach_absolute_time();
790         success = mach_timebase_info(&timebase_info) == KERN_SUCCESS;
791         if (success) {
792             success = gettimeofday(&tv, NULL) == 0;
793             if (success) {
794                 timespec_init.tv_sec  = tv.tv_sec;
795                 timespec_init.tv_nsec = tv.tv_usec * 1000;
796             }
797         }
798     }
799 #  ifdef PERL_DARWIN_MUTEX
800     MUTEX_UNLOCK(&darwin_time_mutex);
801 #  endif
802     return success;
803 }
804
805 #  ifdef TIME_HIRES_CLOCK_GETTIME_EMULATION
806 static int th_clock_gettime(clockid_t clock_id, struct timespec *ts) {
807     if (darwin_time_init() && timebase_info.denom) {
808         switch (clock_id) {
809         case CLOCK_REALTIME:
810             {
811                 uint64_t nanos =
812                     ((mach_absolute_time() - absolute_time_init) *
813                     (uint64_t)timebase_info.numer) / (uint64_t)timebase_info.denom;
814                 ts->tv_sec  = timespec_init.tv_sec  + nanos / IV_1E9;
815                 ts->tv_nsec = timespec_init.tv_nsec + nanos % IV_1E9;
816                 return 0;
817             }
818
819         case CLOCK_MONOTONIC:
820             {
821                 uint64_t nanos =
822                     (mach_absolute_time() *
823                     (uint64_t)timebase_info.numer) / (uint64_t)timebase_info.denom;
824                 ts->tv_sec  = nanos / IV_1E9;
825                 ts->tv_nsec = nanos - ts->tv_sec * IV_1E9;
826                 return 0;
827             }
828
829         default:
830             break;
831         }
832     }
833
834     SETERRNO(EINVAL, LIB_INVARG);
835     return -1;
836 }
837
838 #    define clock_gettime(clock_id, ts) th_clock_gettime((clock_id), (ts))
839
840 #  endif /* TIME_HIRES_CLOCK_GETTIME_EMULATION */
841
842 #  ifdef TIME_HIRES_CLOCK_GETRES_EMULATION
843 static int th_clock_getres(clockid_t clock_id, struct timespec *ts) {
844     if (darwin_time_init() && timebase_info.denom) {
845         switch (clock_id) {
846         case CLOCK_REALTIME:
847         case CLOCK_MONOTONIC:
848             ts->tv_sec  = 0;
849             /* In newer kernels both the numer and denom are one,
850              * resulting in conversion factor of one, which is of
851              * course unrealistic. */
852             ts->tv_nsec = timebase_info.numer / timebase_info.denom;
853             return 0;
854         default:
855             break;
856         }
857     }
858
859     SETERRNO(EINVAL, LIB_INVARG);
860     return -1;
861 }
862
863 #    define clock_getres(clock_id, ts) th_clock_getres((clock_id), (ts))
864 #  endif /* TIME_HIRES_CLOCK_GETRES_EMULATION */
865
866 #  ifdef TIME_HIRES_CLOCK_NANOSLEEP_EMULATION
867 static int th_clock_nanosleep(clockid_t clock_id, int flags,
868                            const struct timespec *rqtp,
869                            struct timespec *rmtp) {
870     if (darwin_time_init()) {
871         switch (clock_id) {
872         case CLOCK_REALTIME:
873         case CLOCK_MONOTONIC:
874             {
875                 uint64_t nanos = rqtp->tv_sec * IV_1E9 + rqtp->tv_nsec;
876                 int success;
877                 if ((flags & TIMER_ABSTIME)) {
878                     uint64_t back =
879                         timespec_init.tv_sec * IV_1E9 + timespec_init.tv_nsec;
880                     nanos = nanos > back ? nanos - back : 0;
881                 }
882                 success =
883                     mach_wait_until(mach_absolute_time() + nanos) == KERN_SUCCESS;
884
885                 /* In the relative sleep, the rmtp should be filled in with
886                  * the 'unused' part of the rqtp in case the sleep gets
887                  * interrupted by a signal.  But it is unknown how signals
888                  * interact with mach_wait_until().  In the absolute sleep,
889                  * the rmtp should stay untouched. */
890                 rmtp->tv_sec  = 0;
891                 rmtp->tv_nsec = 0;
892
893                 return success;
894             }
895
896         default:
897             break;
898         }
899     }
900
901     SETERRNO(EINVAL, LIB_INVARG);
902     return -1;
903 }
904
905 #    define clock_nanosleep(clock_id, flags, rqtp, rmtp) \
906   th_clock_nanosleep((clock_id), (flags), (rqtp), (rmtp))
907
908 #  endif /* TIME_HIRES_CLOCK_NANOSLEEP_EMULATION */
909
910 #endif /* PERL_DARWIN */
911
912 /* The macOS headers warn about using certain interfaces in
913  * OS-release-ignorant manner, for example:
914  *
915  * warning: 'futimens' is only available on macOS 10.13 or newer
916  *       [-Wunguarded-availability-new]
917  *
918  * (ditto for utimensat)
919  *
920  * There is clang __builtin_available() *runtime* check for this.
921  * The gotchas are that neither __builtin_available() nor __has_builtin()
922  * are always available.
923  */
924 #ifndef __has_builtin
925 #  define __has_builtin(x) 0 /* non-clang */
926 #endif
927 #ifdef HAS_FUTIMENS
928 #  if defined(PERL_DARWIN) && __has_builtin(__builtin_available)
929 #    define FUTIMENS_AVAILABLE __builtin_available(macOS 10.13, *)
930 #  else
931 #    define FUTIMENS_AVAILABLE 1
932 #  endif
933 #else
934 #  define FUTIMENS_AVAILABLE 0
935 #endif
936 #ifdef HAS_UTIMENSAT
937 #  if defined(PERL_DARWIN) && __has_builtin(__builtin_available)
938 #    define UTIMENSAT_AVAILABLE __builtin_available(macOS 10.13, *)
939 #  else
940 #    define UTIMENSAT_AVAILABLE 1
941 #  endif
942 #else
943 #  define UTIMENSAT_AVAILABLE 0
944 #endif
945
946 #include "const-c.inc"
947
948 #if (defined(TIME_HIRES_NANOSLEEP)) || \
949     (defined(TIME_HIRES_CLOCK_NANOSLEEP) && defined(TIMER_ABSTIME))
950
951 static void
952 nanosleep_init(NV nsec,
953                     struct timespec *sleepfor,
954                     struct timespec *unslept) {
955   sleepfor->tv_sec = (Time_t)(nsec / NV_1E9);
956   sleepfor->tv_nsec = (long)(nsec - ((NV)sleepfor->tv_sec) * NV_1E9);
957   unslept->tv_sec = 0;
958   unslept->tv_nsec = 0;
959 }
960
961 static NV
962 nsec_without_unslept(struct timespec *sleepfor,
963                      const struct timespec *unslept) {
964     if (sleepfor->tv_sec >= unslept->tv_sec) {
965         sleepfor->tv_sec -= unslept->tv_sec;
966         if (sleepfor->tv_nsec >= unslept->tv_nsec) {
967             sleepfor->tv_nsec -= unslept->tv_nsec;
968         } else if (sleepfor->tv_sec > 0) {
969             sleepfor->tv_sec--;
970             sleepfor->tv_nsec += IV_1E9;
971             sleepfor->tv_nsec -= unslept->tv_nsec;
972         } else {
973             sleepfor->tv_sec = 0;
974             sleepfor->tv_nsec = 0;
975         }
976     } else {
977         sleepfor->tv_sec = 0;
978         sleepfor->tv_nsec = 0;
979     }
980     return ((NV)sleepfor->tv_sec) * NV_1E9 + ((NV)sleepfor->tv_nsec);
981 }
982
983 #endif
984
985 /* In case Perl and/or Devel::PPPort are too old, minimally emulate
986  * IS_SAFE_PATHNAME() (which looks for zero bytes in the pathname). */
987 #ifndef IS_SAFE_PATHNAME
988 #  if PERL_VERSION >= 12 /* Perl_ck_warner is 5.10.0 -> */
989 #    ifdef WARN_SYSCALLS
990 #      define WARNEMUCAT WARN_SYSCALLS /* 5.22.0 -> */
991 #    else
992 #      define WARNEMUCAT WARN_MISC
993 #    endif
994 #    define WARNEMU(opname) Perl_ck_warner(aTHX_ packWARN(WARNEMUCAT), "Invalid \\0 character in pathname for %s",opname)
995 #  else
996 #    define WARNEMU(opname) Perl_warn(aTHX_ "Invalid \\0 character in pathname for %s",opname)
997 #  endif
998 #  define IS_SAFE_PATHNAME(pv, len, opname) (((len)>1)&&memchr((pv), 0, (len)-1)?(SETERRNO(ENOENT, LIB_INVARG),WARNEMU(opname),FALSE):(TRUE))
999 #endif
1000
1001 MODULE = Time::HiRes            PACKAGE = Time::HiRes
1002
1003 PROTOTYPES: ENABLE
1004
1005 BOOT:
1006     {
1007 #ifdef MY_CXT_KEY
1008         MY_CXT_INIT;
1009 #endif
1010 #ifdef HAS_GETTIMEOFDAY
1011         {
1012             (void) hv_store(PL_modglobal, "Time::NVtime", 12,
1013                             newSViv(PTR2IV(myNVtime)), 0);
1014             (void) hv_store(PL_modglobal, "Time::U2time", 12,
1015                             newSViv(PTR2IV(myU2time)), 0);
1016         }
1017 #endif
1018 #if defined(PERL_DARWIN)
1019 #  if defined(USE_ITHREADS) && defined(PERL_DARWIN_MUTEX)
1020         MUTEX_INIT(&darwin_time_mutex);
1021 #  endif
1022 #endif
1023     }
1024
1025 #if defined(USE_ITHREADS) && defined(MY_CXT_KEY)
1026
1027 void
1028 CLONE(...)
1029     CODE:
1030         MY_CXT_CLONE;
1031
1032 #endif
1033
1034 INCLUDE: const-xs.inc
1035
1036 #if defined(HAS_USLEEP) && defined(HAS_GETTIMEOFDAY)
1037
1038 NV
1039 usleep(useconds)
1040     NV useconds
1041     PREINIT:
1042         struct timeval Ta, Tb;
1043     CODE:
1044         gettimeofday(&Ta, NULL);
1045         if (items > 0) {
1046             if (useconds >= NV_1E6) {
1047                 IV seconds = (IV) (useconds / NV_1E6);
1048                 /* If usleep() has been implemented using setitimer()
1049                  * then this contortion is unnecessary-- but usleep()
1050                  * may be implemented in some other way, so let's contort. */
1051                 if (seconds) {
1052                     sleep(seconds);
1053                     useconds -= NV_1E6 * seconds;
1054                 }
1055             } else if (useconds < 0.0)
1056                 croak("Time::HiRes::usleep(%" NVgf
1057                       "): negative time not invented yet", useconds);
1058
1059             usleep((U32)useconds);
1060         } else
1061             PerlProc_pause();
1062
1063         gettimeofday(&Tb, NULL);
1064 #  if 0
1065         printf("[%ld %ld] [%ld %ld]\n", Tb.tv_sec, Tb.tv_usec, Ta.tv_sec, Ta.tv_usec);
1066 #  endif
1067         RETVAL = NV_1E6*(Tb.tv_sec-Ta.tv_sec)+(NV)((IV)Tb.tv_usec-(IV)Ta.tv_usec);
1068
1069     OUTPUT:
1070         RETVAL
1071
1072 #  if defined(TIME_HIRES_NANOSLEEP)
1073
1074 NV
1075 nanosleep(nsec)
1076     NV nsec
1077     PREINIT:
1078         struct timespec sleepfor, unslept;
1079     CODE:
1080         if (nsec < 0.0)
1081             croak("Time::HiRes::nanosleep(%" NVgf
1082                   "): negative time not invented yet", nsec);
1083         nanosleep_init(nsec, &sleepfor, &unslept);
1084         if (nanosleep(&sleepfor, &unslept) == 0) {
1085             RETVAL = nsec;
1086         } else {
1087             RETVAL = nsec_without_unslept(&sleepfor, &unslept);
1088         }
1089     OUTPUT:
1090         RETVAL
1091
1092 #  else  /* #if defined(TIME_HIRES_NANOSLEEP) */
1093
1094 NV
1095 nanosleep(nsec)
1096     NV nsec
1097     CODE:
1098         PERL_UNUSED_ARG(nsec);
1099         croak("Time::HiRes::nanosleep(): unimplemented in this platform");
1100         RETVAL = 0.0;
1101     OUTPUT:
1102         RETVAL
1103
1104 #  endif /* #if defined(TIME_HIRES_NANOSLEEP) */
1105
1106 NV
1107 sleep(...)
1108     PREINIT:
1109         struct timeval Ta, Tb;
1110     CODE:
1111         gettimeofday(&Ta, NULL);
1112         if (items > 0) {
1113             NV seconds  = SvNV(ST(0));
1114             if (seconds >= 0.0) {
1115                 UV useconds = (UV)(1E6 * (seconds - (UV)seconds));
1116                 if (seconds >= 1.0)
1117                     sleep((U32)seconds);
1118                 if ((IV)useconds < 0) {
1119 #  if defined(__sparc64__) && defined(__GNUC__)
1120                     /* Sparc64 gcc 2.95.3 (e.g. on NetBSD) has a bug
1121                      * where (0.5 - (UV)(0.5)) will under certain
1122                      * circumstances (if the double is cast to UV more
1123                      * than once?) evaluate to -0.5, instead of 0.5. */
1124                     useconds = -(IV)useconds;
1125 #  endif /* #if defined(__sparc64__) && defined(__GNUC__) */
1126                     if ((IV)useconds < 0)
1127                         croak("Time::HiRes::sleep(%" NVgf
1128                               "): internal error: useconds < 0 (unsigned %" UVuf
1129                               " signed %" IVdf ")",
1130                               seconds, useconds, (IV)useconds);
1131                 }
1132                 usleep(useconds);
1133             } else
1134                 croak("Time::HiRes::sleep(%" NVgf
1135                       "): negative time not invented yet", seconds);
1136         } else
1137             PerlProc_pause();
1138
1139         gettimeofday(&Tb, NULL);
1140 #  if 0
1141         printf("[%ld %ld] [%ld %ld]\n", Tb.tv_sec, Tb.tv_usec, Ta.tv_sec, Ta.tv_usec);
1142 #  endif
1143         RETVAL = (NV)(Tb.tv_sec-Ta.tv_sec)+0.000001*(NV)(Tb.tv_usec-Ta.tv_usec);
1144
1145     OUTPUT:
1146         RETVAL
1147
1148 #else  /* #if defined(HAS_USLEEP) && defined(HAS_GETTIMEOFDAY) */
1149
1150 NV
1151 usleep(useconds)
1152     NV useconds
1153     CODE:
1154         PERL_UNUSED_ARG(useconds);
1155         croak("Time::HiRes::usleep(): unimplemented in this platform");
1156         RETVAL = 0.0;
1157     OUTPUT:
1158         RETVAL
1159
1160 #endif /* #if defined(HAS_USLEEP) && defined(HAS_GETTIMEOFDAY) */
1161
1162 #ifdef HAS_UALARM
1163
1164 IV
1165 ualarm(useconds,uinterval=0)
1166     int useconds
1167     int uinterval
1168     CODE:
1169         if (useconds < 0 || uinterval < 0)
1170             croak("Time::HiRes::ualarm(%d, %d): negative time not invented yet", useconds, uinterval);
1171 #  if defined(HAS_SETITIMER) && defined(ITIMER_REAL)
1172         {
1173             struct itimerval itv;
1174             if (hrt_ualarm_itimero(&itv, useconds, uinterval)) {
1175                 /* To conform to ualarm's interface, we're actually ignoring
1176                    an error here.  */
1177                 RETVAL = 0;
1178             } else {
1179                 RETVAL = itv.it_value.tv_sec * IV_1E6 + itv.it_value.tv_usec;
1180             }
1181         }
1182 #  else
1183         if (useconds >= IV_1E6 || uinterval >= IV_1E6)
1184             croak("Time::HiRes::ualarm(%d, %d): useconds or uinterval"
1185                   " equal to or more than %" IVdf,
1186                   useconds, uinterval, IV_1E6);
1187
1188         RETVAL = ualarm(useconds, uinterval);
1189 #  endif
1190
1191     OUTPUT:
1192         RETVAL
1193
1194 NV
1195 alarm(seconds,interval=0)
1196     NV seconds
1197     NV interval
1198     CODE:
1199         if (seconds < 0.0 || interval < 0.0)
1200             croak("Time::HiRes::alarm(%" NVgf ", %" NVgf
1201                   "): negative time not invented yet", seconds, interval);
1202
1203         {
1204             IV iseconds = (IV)seconds;
1205             IV iinterval = (IV)interval;
1206             NV fseconds = seconds - iseconds;
1207             NV finterval = interval - iinterval;
1208             IV useconds, uinterval;
1209             if (fseconds >= 1.0 || finterval >= 1.0)
1210                 croak("Time::HiRes::alarm(%" NVgf ", %" NVgf
1211                       "): seconds or interval too large to split correctly",
1212                       seconds, interval);
1213
1214             useconds = IV_1E6 * fseconds;
1215             uinterval = IV_1E6 * finterval;
1216 #  if defined(HAS_SETITIMER) && defined(ITIMER_REAL)
1217             {
1218                 struct itimerval nitv, oitv;
1219                 nitv.it_value.tv_sec = iseconds;
1220                 nitv.it_value.tv_usec = useconds;
1221                 nitv.it_interval.tv_sec = iinterval;
1222                 nitv.it_interval.tv_usec = uinterval;
1223                 if (setitimer(ITIMER_REAL, &nitv, &oitv)) {
1224                     /* To conform to alarm's interface, we're actually ignoring
1225                        an error here.  */
1226                     RETVAL = 0;
1227                 } else {
1228                     RETVAL = oitv.it_value.tv_sec + ((NV)oitv.it_value.tv_usec) / NV_1E6;
1229                 }
1230             }
1231 #  else
1232             if (iseconds || iinterval)
1233                 croak("Time::HiRes::alarm(%" NVgf ", %" NVgf
1234                       "): seconds or interval equal to or more than 1.0 ",
1235                       seconds, interval);
1236
1237             RETVAL = (NV)ualarm( useconds, uinterval ) / NV_1E6;
1238 #  endif
1239         }
1240
1241     OUTPUT:
1242         RETVAL
1243
1244 #else /* #ifdef HAS_UALARM */
1245
1246 int
1247 ualarm(useconds,interval=0)
1248     int useconds
1249     int interval
1250     CODE:
1251         PERL_UNUSED_ARG(useconds);
1252         PERL_UNUSED_ARG(interval);
1253         croak("Time::HiRes::ualarm(): unimplemented in this platform");
1254         RETVAL = -1;
1255     OUTPUT:
1256         RETVAL
1257
1258 NV
1259 alarm(seconds,interval=0)
1260     NV seconds
1261     NV interval
1262     CODE:
1263         PERL_UNUSED_ARG(seconds);
1264         PERL_UNUSED_ARG(interval);
1265         croak("Time::HiRes::alarm(): unimplemented in this platform");
1266         RETVAL = 0.0;
1267     OUTPUT:
1268         RETVAL
1269
1270 #endif /* #ifdef HAS_UALARM */
1271
1272 #ifdef HAS_GETTIMEOFDAY
1273
1274 void
1275 gettimeofday()
1276     PREINIT:
1277         struct timeval Tp;
1278     PPCODE:
1279         int status;
1280         status = gettimeofday (&Tp, NULL);
1281         if (status == 0) {
1282             if (GIMME == G_ARRAY) {
1283                 EXTEND(sp, 2);
1284                 PUSHs(sv_2mortal(newSViv(Tp.tv_sec)));
1285                 PUSHs(sv_2mortal(newSViv(Tp.tv_usec)));
1286             } else {
1287                 EXTEND(sp, 1);
1288                 PUSHs(sv_2mortal(newSVnv(Tp.tv_sec + (Tp.tv_usec / NV_1E6))));
1289             }
1290         }
1291
1292 NV
1293 time()
1294     PREINIT:
1295         struct timeval Tp;
1296     CODE:
1297         int status;
1298         status = gettimeofday (&Tp, NULL);
1299         if (status == 0) {
1300             RETVAL = Tp.tv_sec + (Tp.tv_usec / NV_1E6);
1301         } else {
1302             RETVAL = -1.0;
1303         }
1304     OUTPUT:
1305         RETVAL
1306
1307 #endif /* #ifdef HAS_GETTIMEOFDAY */
1308
1309 #if defined(HAS_GETITIMER) && defined(HAS_SETITIMER)
1310
1311 #  define TV2NV(tv) ((NV)((tv).tv_sec) + 0.000001 * (NV)((tv).tv_usec))
1312
1313 void
1314 setitimer(which, seconds, interval = 0)
1315     int which
1316     NV seconds
1317     NV interval
1318     PREINIT:
1319         struct itimerval newit;
1320         struct itimerval oldit;
1321     PPCODE:
1322         if (seconds < 0.0 || interval < 0.0)
1323             croak("Time::HiRes::setitimer(%" IVdf ", %" NVgf ", %" NVgf
1324                   "): negative time not invented yet",
1325                   (IV)which, seconds, interval);
1326         newit.it_value.tv_sec  = (IV)seconds;
1327         newit.it_value.tv_usec =
1328           (IV)((seconds  - (NV)newit.it_value.tv_sec)    * NV_1E6);
1329         newit.it_interval.tv_sec  = (IV)interval;
1330         newit.it_interval.tv_usec =
1331           (IV)((interval - (NV)newit.it_interval.tv_sec) * NV_1E6);
1332         /* on some platforms the 1st arg to setitimer is an enum, which
1333          * causes -Wc++-compat to complain about passing an int instead
1334          */
1335         GCC_DIAG_IGNORE_STMT(-Wc++-compat);
1336         if (setitimer(which, &newit, &oldit) == 0) {
1337             EXTEND(sp, 1);
1338             PUSHs(sv_2mortal(newSVnv(TV2NV(oldit.it_value))));
1339             if (GIMME == G_ARRAY) {
1340                 EXTEND(sp, 1);
1341                 PUSHs(sv_2mortal(newSVnv(TV2NV(oldit.it_interval))));
1342             }
1343         }
1344         GCC_DIAG_RESTORE_STMT;
1345
1346 void
1347 getitimer(which)
1348     int which
1349     PREINIT:
1350         struct itimerval nowit;
1351     PPCODE:
1352         /* on some platforms the 1st arg to getitimer is an enum, which
1353          * causes -Wc++-compat to complain about passing an int instead
1354          */
1355         GCC_DIAG_IGNORE_STMT(-Wc++-compat);
1356         if (getitimer(which, &nowit) == 0) {
1357             EXTEND(sp, 1);
1358             PUSHs(sv_2mortal(newSVnv(TV2NV(nowit.it_value))));
1359             if (GIMME == G_ARRAY) {
1360                 EXTEND(sp, 1);
1361                 PUSHs(sv_2mortal(newSVnv(TV2NV(nowit.it_interval))));
1362             }
1363         }
1364         GCC_DIAG_RESTORE_STMT;
1365
1366 #endif /* #if defined(HAS_GETITIMER) && defined(HAS_SETITIMER) */
1367
1368 #if defined(TIME_HIRES_UTIME)
1369
1370 I32
1371 utime(accessed, modified, ...)
1372 PROTOTYPE: $$@
1373     PREINIT:
1374         SV* accessed;
1375         SV* modified;
1376         SV* file;
1377
1378         struct timespec utbuf[2];
1379         struct timespec *utbufp = utbuf;
1380         int tot;
1381
1382     CODE:
1383         accessed = ST(0);
1384         modified = ST(1);
1385         items -= 2;
1386         tot = 0;
1387
1388         if ( accessed == &PL_sv_undef && modified == &PL_sv_undef )
1389             utbufp = NULL;
1390         else {
1391             if (SvNV(accessed) < 0.0 || SvNV(modified) < 0.0)
1392                 croak("Time::HiRes::utime(%" NVgf ", %" NVgf
1393                       "): negative time not invented yet",
1394                           SvNV(accessed), SvNV(modified));
1395             Zero(&utbuf, sizeof utbuf, char);
1396
1397             utbuf[0].tv_sec = (Time_t)SvNV(accessed);  /* time accessed */
1398             utbuf[0].tv_nsec = (long)(
1399                 (SvNV(accessed) - (NV)utbuf[0].tv_sec)
1400                 * NV_1E9 + (NV)0.5);
1401
1402             utbuf[1].tv_sec = (Time_t)SvNV(modified);  /* time modified */
1403             utbuf[1].tv_nsec = (long)(
1404                 (SvNV(modified) - (NV)utbuf[1].tv_sec)
1405                 * NV_1E9 + (NV)0.5);
1406         }
1407
1408         while (items > 0) {
1409             file = POPs; items--;
1410
1411             if (SvROK(file) && GvIO(SvRV(file)) && IoIFP(sv_2io(SvRV(file)))) {
1412                 int fd =  PerlIO_fileno(IoIFP(sv_2io(file)));
1413                 if (fd < 0) {
1414                     SETERRNO(EBADF,RMS_IFI);
1415                 } else {
1416 #  ifdef HAS_FUTIMENS
1417                     if (FUTIMENS_AVAILABLE) {
1418                         if (futimens(fd, utbufp) == 0) {
1419                             tot++;
1420                         }
1421                     } else {
1422                         croak("futimens unimplemented in this platform");
1423                     }
1424 #  else  /* HAS_FUTIMENS */
1425                     croak("futimens unimplemented in this platform");
1426 #  endif /* HAS_FUTIMENS */
1427                 }
1428             }
1429             else {
1430 #  ifdef HAS_UTIMENSAT
1431                 if (UTIMENSAT_AVAILABLE) {
1432                     STRLEN len;
1433                     char * name = SvPV(file, len);
1434                     if (IS_SAFE_PATHNAME(name, len, "utime") &&
1435                         utimensat(AT_FDCWD, name, utbufp, 0) == 0) {
1436
1437                         tot++;
1438                     }
1439                 } else {
1440                     croak("utimensat unimplemented in this platform");
1441                 }
1442 #  else  /* HAS_UTIMENSAT */
1443                 croak("utimensat unimplemented in this platform");
1444 #  endif /* HAS_UTIMENSAT */
1445             }
1446         } /* while items */
1447         RETVAL = tot;
1448
1449     OUTPUT:
1450         RETVAL
1451
1452 #else  /* #if defined(TIME_HIRES_UTIME) */
1453
1454 I32
1455 utime(accessed, modified, ...)
1456     CODE:
1457         croak("Time::HiRes::utime(): unimplemented in this platform");
1458         RETVAL = 0;
1459     OUTPUT:
1460         RETVAL
1461
1462 #endif /* #if defined(TIME_HIRES_UTIME) */
1463
1464 #if defined(TIME_HIRES_CLOCK_GETTIME)
1465
1466 NV
1467 clock_gettime(clock_id = CLOCK_REALTIME)
1468     clockid_t clock_id
1469     PREINIT:
1470         struct timespec ts;
1471         int status = -1;
1472     CODE:
1473 #  ifdef TIME_HIRES_CLOCK_GETTIME_SYSCALL
1474         status = syscall(SYS_clock_gettime, clock_id, &ts);
1475 #  else
1476         status = clock_gettime(clock_id, &ts);
1477 #  endif
1478         RETVAL = status == 0 ? ts.tv_sec + (NV) ts.tv_nsec / NV_1E9 : -1;
1479
1480     OUTPUT:
1481         RETVAL
1482
1483 #else  /* if defined(TIME_HIRES_CLOCK_GETTIME) */
1484
1485 NV
1486 clock_gettime(clock_id = 0)
1487     clockid_t clock_id
1488     CODE:
1489         PERL_UNUSED_ARG(clock_id);
1490         croak("Time::HiRes::clock_gettime(): unimplemented in this platform");
1491         RETVAL = 0.0;
1492     OUTPUT:
1493         RETVAL
1494
1495 #endif /*  #if defined(TIME_HIRES_CLOCK_GETTIME) */
1496
1497 #if defined(TIME_HIRES_CLOCK_GETRES)
1498
1499 NV
1500 clock_getres(clock_id = CLOCK_REALTIME)
1501     clockid_t clock_id
1502     PREINIT:
1503         int status = -1;
1504         struct timespec ts;
1505     CODE:
1506 #  ifdef TIME_HIRES_CLOCK_GETRES_SYSCALL
1507         status = syscall(SYS_clock_getres, clock_id, &ts);
1508 #  else
1509         status = clock_getres(clock_id, &ts);
1510 #  endif
1511         RETVAL = status == 0 ? ts.tv_sec + (NV) ts.tv_nsec / NV_1E9 : -1;
1512
1513     OUTPUT:
1514         RETVAL
1515
1516 #else  /* if defined(TIME_HIRES_CLOCK_GETRES) */
1517
1518 NV
1519 clock_getres(clock_id = 0)
1520     clockid_t clock_id
1521     CODE:
1522         PERL_UNUSED_ARG(clock_id);
1523         croak("Time::HiRes::clock_getres(): unimplemented in this platform");
1524         RETVAL = 0.0;
1525     OUTPUT:
1526         RETVAL
1527
1528 #endif /*  #if defined(TIME_HIRES_CLOCK_GETRES) */
1529
1530 #if defined(TIME_HIRES_CLOCK_NANOSLEEP) && defined(TIMER_ABSTIME)
1531
1532 NV
1533 clock_nanosleep(clock_id, nsec, flags = 0)
1534     clockid_t clock_id
1535     NV  nsec
1536     int flags
1537     PREINIT:
1538         struct timespec sleepfor, unslept;
1539     CODE:
1540         if (nsec < 0.0)
1541             croak("Time::HiRes::clock_nanosleep(..., %" NVgf
1542                   "): negative time not invented yet", nsec);
1543         nanosleep_init(nsec, &sleepfor, &unslept);
1544         if (clock_nanosleep(clock_id, flags, &sleepfor, &unslept) == 0) {
1545             RETVAL = nsec;
1546         } else {
1547             RETVAL = nsec_without_unslept(&sleepfor, &unslept);
1548         }
1549     OUTPUT:
1550         RETVAL
1551
1552 #else  /* if defined(TIME_HIRES_CLOCK_NANOSLEEP) && defined(TIMER_ABSTIME) */
1553
1554 NV
1555 clock_nanosleep(clock_id, nsec, flags = 0)
1556     clockid_t clock_id
1557     NV  nsec
1558     int flags
1559     CODE:
1560         PERL_UNUSED_ARG(clock_id);
1561         PERL_UNUSED_ARG(nsec);
1562         PERL_UNUSED_ARG(flags);
1563         croak("Time::HiRes::clock_nanosleep(): unimplemented in this platform");
1564         RETVAL = 0.0;
1565     OUTPUT:
1566         RETVAL
1567
1568 #endif /*  #if defined(TIME_HIRES_CLOCK_NANOSLEEP) && defined(TIMER_ABSTIME) */
1569
1570 #if defined(TIME_HIRES_CLOCK) && defined(CLOCKS_PER_SEC)
1571
1572 NV
1573 clock()
1574     PREINIT:
1575         clock_t clocks;
1576     CODE:
1577         clocks = clock();
1578         RETVAL = clocks == (clock_t) -1 ? (clock_t) -1 : (NV)clocks / (NV)CLOCKS_PER_SEC;
1579
1580     OUTPUT:
1581         RETVAL
1582
1583 #else  /* if defined(TIME_HIRES_CLOCK) && defined(CLOCKS_PER_SEC) */
1584
1585 NV
1586 clock()
1587     CODE:
1588         croak("Time::HiRes::clock(): unimplemented in this platform");
1589         RETVAL = 0.0;
1590     OUTPUT:
1591         RETVAL
1592
1593 #endif /*  #if defined(TIME_HIRES_CLOCK) && defined(CLOCKS_PER_SEC) */
1594
1595 void
1596 stat(...)
1597 PROTOTYPE: ;$
1598     PREINIT:
1599         OP fakeop;
1600         int nret;
1601     ALIAS:
1602         Time::HiRes::lstat = 1
1603     PPCODE:
1604         XPUSHs(sv_2mortal(newSVsv(items == 1 ? ST(0) : DEFSV)));
1605         PUTBACK;
1606         ENTER;
1607         PL_laststatval = -1;
1608         SAVEOP();
1609         Zero(&fakeop, 1, OP);
1610         fakeop.op_type = ix ? OP_LSTAT : OP_STAT;
1611         fakeop.op_ppaddr = PL_ppaddr[fakeop.op_type];
1612         fakeop.op_flags = GIMME_V == G_ARRAY ? OPf_WANT_LIST :
1613             GIMME_V == G_SCALAR ? OPf_WANT_SCALAR : OPf_WANT_VOID;
1614         PL_op = &fakeop;
1615         (void)fakeop.op_ppaddr(aTHX);
1616         SPAGAIN;
1617         LEAVE;
1618         nret = SP+1 - &ST(0);
1619         if (nret == 13) {
1620             UV atime = SvUV(ST( 8));
1621             UV mtime = SvUV(ST( 9));
1622             UV ctime = SvUV(ST(10));
1623             UV atime_nsec;
1624             UV mtime_nsec;
1625             UV ctime_nsec;
1626             hrstatns(&atime_nsec, &mtime_nsec, &ctime_nsec);
1627             if (atime_nsec)
1628                 ST( 8) = sv_2mortal(newSVnv(atime + (NV) atime_nsec / NV_1E9));
1629             if (mtime_nsec)
1630                 ST( 9) = sv_2mortal(newSVnv(mtime + (NV) mtime_nsec / NV_1E9));
1631             if (ctime_nsec)
1632                 ST(10) = sv_2mortal(newSVnv(ctime + (NV) ctime_nsec / NV_1E9));
1633         }
1634         XSRETURN(nret);