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