-
Notifications
You must be signed in to change notification settings - Fork 71
/
Copy pathw32util.c
4755 lines (3823 loc) · 164 KB
/
w32util.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* W32UTIL.C (c) Copyright "Fish" (David B. Trout), 2005-2012 */
/* (c) Copyright TurboHercules, SAS 2010-2011 */
/* Windows porting functions */
/* */
/* Released under "The Q Public License Version 1" */
/* (http://www.hercules-390.org/herclic.html) as modifications to */
/* Hercules. */
//////////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT PROGRAMMING NOTE!
//
// Please see the "VERY IMPORTANT SPECIAL NOTE" comments accompanying the
// select, fdopen, etc, #undef's in the Windows Socket Handling section!!
//
//////////////////////////////////////////////////////////////////////////////////////////
#include "hstdinc.h"
#define _W32UTIL_C_
#define _HUTIL_DLL_
#include "hercules.h"
//#define W32UTIL_DEBUG
#if defined(DEBUG) && !defined(W32UTIL_DEBUG)
#define W32UTIL_DEBUG
#endif
#if defined(W32UTIL_DEBUG)
#define ENABLE_TRACING_STMTS 1
#include "dbgtrace.h"
#endif
#if defined( _MSVC_ )
///////////////////////////////////////////////////////////////////////////////
// Support for disabling of CRT Invalid Parameter Handler...
#if defined( _MSC_VER ) && ( _MSC_VER >= VS2005 )
static void DummyCRTInvalidParameterHandler
(
const wchar_t* expression,
const wchar_t* function,
const wchar_t* file,
unsigned int line,
uintptr_t pReserved
)
{
// Do nothing to cause CRT to simply ignore the invalid parameter
// and to instead just pass back the return code to the caller.
}
static _invalid_parameter_handler old_iph = NULL;
static int prev_rm = 0;
// This function's sole purpose is to bypass Microsoft's default handling of
// invalid parameters being passed to CRT functions, which ends up causing
// two completely different assertion dialogs to appear for each problem
DLL_EXPORT void DisableInvalidParameterHandling()
{
if ( old_iph ) return;
old_iph = _set_invalid_parameter_handler( DummyCRTInvalidParameterHandler );
#if defined(DEBUG) || defined(_DEBUG)
prev_rm = _CrtSetReportMode( _CRT_ASSERT, 0 );
#endif
}
DLL_EXPORT void EnableInvalidParameterHandling()
{
if ( !old_iph ) return;
_set_invalid_parameter_handler( old_iph ); old_iph = NULL;
#if defined(DEBUG) || defined(_DEBUG)
_CrtSetReportMode( _CRT_ASSERT, prev_rm );
#endif
}
#endif // defined( _MSC_VER ) && ( _MSC_VER >= VS2005 )
//////////////////////////////////////////////////////////////////////////////////////////
struct ERRNOTAB
{
DWORD dwLastError; // Win32 error from GetLastError()
int nErrNo; // corresponding 'errno' value
};
typedef struct ERRNOTAB ERRNOTAB;
// PROGRAMMING NOTE: we only need to translate values which
// are in the same range as existing defined errno values. If
// the Win32 GetLastError() value is outside the defined errno
// value range, then we just use the raw GetLastError() value.
// The current 'errno' value range is 0 - 43, so only those
// GetLastError() values (defined in winerror.h) which are 43
// or less need to be remapped.
ERRNOTAB w32_errno_tab[] =
{
{ ERROR_TOO_MANY_OPEN_FILES, EMFILE },
{ ERROR_ACCESS_DENIED, EACCES },
{ ERROR_INVALID_HANDLE, EBADF },
{ ERROR_NOT_ENOUGH_MEMORY, ENOMEM },
{ ERROR_OUTOFMEMORY, ENOMEM },
{ ERROR_INVALID_DRIVE, ENOENT },
{ ERROR_WRITE_PROTECT, EACCES },
{ ERROR_NOT_READY, EIO },
{ ERROR_CRC, EIO },
{ ERROR_WRITE_FAULT, EIO },
{ ERROR_READ_FAULT, EIO },
{ ERROR_GEN_FAILURE, EIO },
{ ERROR_SHARING_VIOLATION, EACCES },
};
#define NUM_ERRNOTAB_ENTRIES (sizeof(w32_errno_tab)/sizeof(w32_errno_tab[0]))
//////////////////////////////////////////////////////////////////////////////////////////
// Translates a Win32 '[WSA]GetLastError()' value into a 'errno' value (if possible
// and/or if needed) that can then be used in the below 'w32_strerror' string function...
DLL_EXPORT int w32_trans_w32error( const DWORD dwLastError )
{
int i; for ( i=0; i < NUM_ERRNOTAB_ENTRIES; i++ )
if ( dwLastError == w32_errno_tab[i].dwLastError )
return w32_errno_tab[i].nErrNo;
return (int) dwLastError;
}
//////////////////////////////////////////////////////////////////////////////////////////
// ("unsafe" version -- use "safer" 'w32_strerror_r' instead if possible)
DLL_EXPORT char* w32_strerror( int errnum )
{
static char szMsgBuff[ 256 ]; // (s/b plenty big enough)
w32_strerror_r( errnum, szMsgBuff, sizeof(szMsgBuff) );
return szMsgBuff;
}
//////////////////////////////////////////////////////////////////////////////////////////
// Handles both regular 'errno' values as well as [WSA]GetLastError() values too...
DLL_EXPORT int w32_strerror_r( int errnum, char* buffer, size_t buffsize )
{
// Route all 'errno' values outside the normal CRT (C Runtime) error
// message table range to the Win32 'w32_w32errmsg' function instead.
// Otherwise simply use the CRT's error message table directly...
if ( !buffer || !buffsize ) return -1;
if ( errnum >= 0 && errnum < _sys_nerr )
{
// Use CRT's error message table directly...
strlcpy( buffer, _sys_errlist[ errnum ], buffsize );
}
else
{
// 'errno' value is actually a Win32 [WSA]GetLastError value...
w32_w32errmsg( errnum, buffer, buffsize );
}
return 0;
}
//////////////////////////////////////////////////////////////////////////////////////////
// Return Win32 error message text associated with an error number value
// as returned by a call to either GetLastError() or WSAGetLastError()...
DLL_EXPORT char* w32_w32errmsg( int errnum, char* pszBuffer, size_t nBuffSize )
{
DWORD dwBytesReturned = 0;
DWORD dwBuffSize = (DWORD)nBuffSize;
ASSERT( pszBuffer && nBuffSize );
dwBytesReturned = FormatMessageA
(
0
| FORMAT_MESSAGE_FROM_SYSTEM
| FORMAT_MESSAGE_IGNORE_INSERTS
,
NULL,
errnum,
MAKELANGID( LANG_NEUTRAL, SUBLANG_DEFAULT ),
pszBuffer,
dwBuffSize,
NULL
);
// (remove trailing whitespace)
{
char* p = pszBuffer + dwBytesReturned - 1;
while ( p >= pszBuffer && isspace(*p) ) p--;
*++p = 0;
}
return pszBuffer;
}
//////////////////////////////////////////////////////////////////////////////////////////
// Large File Support...
#if (_MSC_VER < VS2005)
//----------------------------------------------------------------------------------------
#if defined( _POSIX_ )
// (promote/demote long to/from __int64)
#define FPOS_T_TO_INT64(pos) ((__int64)(pos))
#define INT64_TO_FPOS_T(i64,pos) ((pos) = (long)(i64))
#if _INTEGRAL_MAX_BITS < 64
WARNING( "fseek/ftell use offset arguments of insufficient size" )
#endif
#else
#if !__STDC__ && _INTEGRAL_MAX_BITS >= 64
// (already __int64!)
#define FPOS_T_TO_INT64(pos) (pos)
#define INT64_TO_FPOS_T(i64,pos) ((pos) = (i64))
#else
// (construct an __int64 from fpos_t structure members and vice-versa)
#define FPOS_T_TO_INT64(pos) ((__int64)(((unsigned __int64)(pos).hipart << 32) | \
(unsigned __int64)(pos).lopart))
#define INT64_TO_FPOS_T(i64,pos) ((pos).hipart = (int)((i64) >> 32), \
(pos).lopart = (unsigned int)(i64))
#endif
#endif
//----------------------------------------------------------------------------------------
DLL_EXPORT __int64 w32_ftelli64 ( FILE* stream )
{
fpos_t pos; if ( fgetpos( stream, &pos ) != 0 )
return -1; else return FPOS_T_TO_INT64( pos );
}
//----------------------------------------------------------------------------------------
DLL_EXPORT int w32_fseeki64 ( FILE* stream, __int64 offset, int origin )
{
__int64 offset_from_beg;
fpos_t pos;
if (SEEK_CUR == origin)
{
if ( (offset_from_beg = w32_ftelli64( stream )) < 0 )
return -1;
offset_from_beg += offset;
}
else if (SEEK_END == origin)
{
struct stat fst;
if ( fstat( fileno( stream ), &fst ) != 0 )
return -1;
offset_from_beg = (__int64)fst.st_size + offset;
}
else if (SEEK_SET == origin)
{
offset_from_beg = offset;
}
else
{
errno = EINVAL;
return -1;
}
INT64_TO_FPOS_T( offset_from_beg, pos );
return fsetpos( stream, &pos );
}
//----------------------------------------------------------------------------------------
DLL_EXPORT int w32_ftrunc64 ( int fd, __int64 new_size )
{
HANDLE hFile;
int rc = 0, save_errno;
__int64 old_pos, old_size;
if ( new_size < 0 )
{
errno = EINVAL;
return -1;
}
hFile = (HANDLE) _get_osfhandle( fd );
if ( (HANDLE) -1 == hFile )
{
errno = EBADF; // (probably not a valid opened file descriptor)
return -1;
}
// The value of the seek pointer shall not be modified by a call to ftruncate().
if ( ( old_pos = _telli64( fd ) ) < 0 )
return -1;
// PROGRAMMING NOTE: from here on, all errors
// need to goto error_return to restore the original
// seek pointer...
if ( ( old_size = _lseeki64( fd, 0, SEEK_END ) ) < 0 )
{
rc = -1;
goto error_return;
}
// pad with zeros out to new_size if needed
rc = 0; // (think positively)
if ( new_size > old_size )
{
#define ZEROPAD_BUFFSIZE ( 128 * 1024 )
BYTE zeros[ZEROPAD_BUFFSIZE];
size_t write_amount = sizeof(zeros);
memset( zeros, 0, sizeof(zeros) );
do
{
write_amount = min( sizeof(zeros), ( new_size - old_size ) );
if ( !WriteFile( hFile, zeros, write_amount, NULL, NULL ) )
{
errno = (int) GetLastError();
rc = -1;
break;
}
}
while ( ( old_size += write_amount ) < new_size );
save_errno = errno;
ASSERT( old_size == new_size || rc < 0 );
errno = save_errno;
}
if ( rc < 0 )
goto error_return;
// set the new file size (eof)
if ( _lseeki64( fd, new_size, SEEK_SET ) < 0 )
{
rc = -1;
goto error_return;
}
if ( !SetEndOfFile( hFile ) )
{
errno = (int) GetLastError();
rc = -1;
goto error_return;
}
rc = 0; // success!
error_return:
// restore the original seek pointer and return
save_errno = errno;
_lseeki64( fd, old_pos, SEEK_SET );
errno = save_errno;
return rc;
}
#endif // (_MSC_VER < VS2005)
//////////////////////////////////////////////////////////////////////////////////////////
#if !defined( HAVE_FORK )
DLL_EXPORT pid_t fork( void )
{
errno = ENOTSUP;
return -1; // *** NOT SUPPORTED ***
}
#endif
//////////////////////////////////////////////////////////////////////////////////////////
#if !defined( HAVE_SCHED_YIELD )
DLL_EXPORT int sched_yield ( void )
{
if (!SwitchToThread())
Sleep(0);
return 0;
}
#endif
//////////////////////////////////////////////////////////////////////////////////////////
// Win32's runtime library functions are reentrant as long as you link
// with one of the multi-threaded libraries (i.e. LIBCMT, MSVCRT, etc.)
#if !defined( HAVE_STRTOK_R )
DLL_EXPORT char* strtok_r ( char* s, const char* sep, char** lasts )
{
return strtok_s( s, sep, lasts );
}
#endif
//////////////////////////////////////////////////////////////////////////////////////////
// nanosleep, usleep and gettimeofday
#if !defined( HAVE_NANOSLEEP ) || !defined( HAVE_USLEEP )
#if !defined( HAVE_GETTIMEOFDAY )
// (INTERNAL) Convert Windows SystemTime value to #of nanoseconds since 1/1/1970...
static ULARGE_INTEGER FileTimeTo1970Nanoseconds( const FILETIME* pFT )
{
ULARGE_INTEGER uliRetVal;
ASSERT( pFT );
// Convert FILETIME to ULARGE_INTEGER
uliRetVal.HighPart = pFT->dwHighDateTime;
uliRetVal.LowPart = pFT->dwLowDateTime;
// Convert from 100-nsec units since 1/1/1601
// to number of 100-nsec units since 1/1/1970
uliRetVal.QuadPart -= 116444736000000000ULL;
// Convert from 100-nsec units to just nsecs
uliRetVal.QuadPart *= 100;
return uliRetVal;
}
//////////////////////////////////////////////////////////////////////////////////////////
// (PUBLIC) Nanosecond resolution (not quite but almost!) TOD clock (clock_gettime)
//
// ** CRITICAL PROGRAMMING NOTE! **
//
// Because the new hthreads design calls gettimeofday to save the time when a lock is
// initialized or obtained, etc, the below function nor any of the functions it calls
// may call logmsg either directly or indirectly (such as using the 'TRACE' macro) or
// else an infinite loop will occur since our logger design uses locks! hthreads will
// call gettimeofday which issues a message which calls logger which uses a lock and
// hthreads calls gettimeofday again, etc.
//
DLL_EXPORT int clock_gettime ( clockid_t clk_id, struct timespec *tp )
{
ULARGE_INTEGER uliWork; // (current HPC tick count and work)
static ULARGE_INTEGER uliHPCTicksPerSec = {0}; // (HPC ticks per second)
static ULARGE_INTEGER uliStartingHPCTick; // (HPC tick count @ start of interval)
static ULARGE_INTEGER uliMaxElapsedHPCTicks; // (HPC tick count resync threshold)
static ULARGE_INTEGER uliStartingNanoTime; // (time of last resync in nanoseconds)
static struct timespec tsPrevRetVal = {0}; // (previously returned timespec value)
static U64 u64ClockResolution = MAX_GTOD_RESOLUTION; // (max emulated TOD clock resolution)
static U64 u64ClockNanoScale; // (elapsed nanoseconds scale factor)
static UINT uiResyncSecs = DEF_GTOD_RESYNC_SECS; // (host TOD clock resync interval)
static BOOL bInSync = FALSE; // (host TOD clock resync flag)
// Validate parameters...
ASSERT( tp );
if (unlikely( clk_id > CLOCK_MONOTONIC || !tp ))
{
errno = EINVAL;
return -1;
}
// Simulate clock_gettime with a clk_id as set by pthread_getcpuclockid,
// which is simply mines the thread_id, i.e. clk_id = -tid. (PJJ Jan-2018)
if ( clk_id < 0 )
{
struct rusage r_usage;
int result;
result = getrusage( -clk_id, &r_usage );
tp->tv_sec = r_usage.ru_utime.tv_sec;
tp->tv_nsec = r_usage.ru_utime.tv_usec;
tp->tv_sec += r_usage.ru_stime.tv_sec;
tp->tv_nsec += r_usage.ru_stime.tv_usec;
if (tp->tv_nsec > 1000000)
{
tp->tv_sec += tp->tv_nsec / 1000000;
tp->tv_nsec = tp->tv_nsec % 1000000;
}
tp->tv_nsec *= 1000;
return result;
}
while (1) { // (for easy backward branching)
// Query current high-performance counter value...
VERIFY( QueryPerformanceCounter( (LARGE_INTEGER*)&uliWork ) );
// Perform (re-)initialization...
if (unlikely( !bInSync )) // (do this once per resync interval)
{
FILETIME ftStartingSystemTime;
// The "GetSystemTimeAsFileTime" function obtains the current system date
// and time. The information is in Coordinated Universal Time (UTC) format.
GetSystemTimeAsFileTime( &ftStartingSystemTime );
uliStartingHPCTick.QuadPart = uliWork.QuadPart;
// PROGRAMMING NOTE: According to Microsoft Desktop Dev Center (MSDN):
// http://msdn.microsoft.com/en-us/library/windows/desktop/ms644905(v=vs.85).aspx
// "The [HPC] frequency cannot change while the system is running."
if (!uliHPCTicksPerSec.QuadPart) // (we only need to do this once)
{
VERIFY( QueryPerformanceFrequency( (LARGE_INTEGER*)&uliHPCTicksPerSec ));
// Verify the length of time between host TOD clock resyncs isn't
// so very long that the number of High Performance Counter ticks
// times our resync interval would then overflow 64-bits. If so,
// we need to decrease our interval until we're certain it won't.
while (uliHPCTicksPerSec.QuadPart > (_UI64_MAX / (uiResyncSecs + 1)))
uiResyncSecs--;
uliMaxElapsedHPCTicks.QuadPart =
uliHPCTicksPerSec.QuadPart * uiResyncSecs;
// Calculate the maximum supported clock resolution such that we don't
// resync with the host TOD clock more than once every resync interval.
while (u64ClockResolution >= MIN_GTOD_RESOLUTION &&
(uliHPCTicksPerSec.QuadPart * (uiResyncSecs + 1)) >= (_UI64_MAX / u64ClockResolution))
{
u64ClockResolution /= 10; // (decrease TOD clock resolution)
}
// (check for error condition...)
if (u64ClockResolution < MIN_GTOD_RESOLUTION)
{
// "Cannot provide minimum emulated TOD clock resolution"
WRMSG( HHC04112, "S" );
exit(1);
}
u64ClockNanoScale = (MAX_GTOD_RESOLUTION / u64ClockResolution);
}
uliStartingNanoTime = FileTimeTo1970Nanoseconds( &ftStartingSystemTime );
bInSync = TRUE;
}
// Calculate elapsed HPC ticks...
if (likely( uliWork.QuadPart >= uliStartingHPCTick.QuadPart ))
{
uliWork.QuadPart -= uliStartingHPCTick.QuadPart;
}
else // (counter wrapped)
{
uliWork.QuadPart += _UI64_MAX - uliStartingHPCTick.QuadPart + 1;
}
// Re-sync to system clock every so often to prevent clock drift
// since high-performance timer updated independently from clock.
if (unlikely( uliWork.QuadPart >= uliMaxElapsedHPCTicks.QuadPart ))
{
bInSync = FALSE; // (force resync)
continue; // (start over)
}
// Convert elapsed HPC ticks to elapsed nanoseconds...
uliWork.QuadPart *= u64ClockResolution;
uliWork.QuadPart /= uliHPCTicksPerSec.QuadPart;
uliWork.QuadPart *= u64ClockNanoScale;
// Add starting time to yield current TOD in nanoseconds...
uliWork.QuadPart += uliStartingNanoTime.QuadPart;
// Build results...
tp->tv_sec = (time_t) (uliWork.QuadPart / BILLION);
tp->tv_nsec = (long) (uliWork.QuadPart % BILLION);
break; } // end while(1)
// If monotonic request, ensure each call returns a unique, ever-increasing value...
if (unlikely( clk_id == CLOCK_MONOTONIC ))
{
if (unlikely( !tsPrevRetVal.tv_sec ))
{
tsPrevRetVal.tv_sec = tp->tv_sec;
tsPrevRetVal.tv_nsec = tp->tv_nsec;
}
if (unlikely
(0
|| tp->tv_sec < tsPrevRetVal.tv_sec
|| (1
&& tp->tv_sec == tsPrevRetVal.tv_sec
&& tp->tv_nsec <= tsPrevRetVal.tv_nsec
)
))
{
tp->tv_sec = tsPrevRetVal.tv_sec;
tp->tv_nsec = tsPrevRetVal.tv_nsec + 1;
if (unlikely(tp->tv_nsec >= BILLION))
{
tp->tv_sec += tp->tv_nsec / BILLION;
tp->tv_nsec = tp->tv_nsec % BILLION;
}
}
}
// Save previously returned high clock value for next MONOTONIC clock time...
if (likely( tp->tv_sec > tsPrevRetVal.tv_sec ||
(tp->tv_sec == tsPrevRetVal.tv_sec &&
tp->tv_nsec > tsPrevRetVal.tv_nsec)))
{
tsPrevRetVal.tv_sec = tp->tv_sec;
tsPrevRetVal.tv_nsec = tp->tv_nsec;
}
// Done!
return 0; // (always, unless user error)
}
//////////////////////////////////////////////////////////////////////////////////////////
// In Windows, thread specific timings can be obtained directly from the thread_id (tid),
// but under Linux etc. a clock_id must be derived first from that thread_id. Having
// observed that such clock_id's are negative, we just simulate the clock_id as -tid.
// (PJJ Jan-2018)
DLL_EXPORT int pthread_getcpuclockid ( TID tid, clockid_t* clk_id )
{
*clk_id = -tid;
return 0;
}
//////////////////////////////////////////////////////////////////////////////////////////
// (PUBLIC) Microsecond resolution GTOD (getimeofday)...
//
// ** CRITICAL PROGRAMMING NOTE! **
//
// Because the new hthreads design calls gettimeofday to save the time when a lock is
// initialized or obtained, etc, the below function nor any of the functions it calls
// may call logmsg either directly or indirectly (such as using the 'TRACE' macro) or
// else an infinite loop will occur since our logger design uses locks! hthreads will
// call gettimeofday which issues a message which calls logger which uses a lock and
// hthreads calls gettimeofday again, etc.
//
DLL_EXPORT int gettimeofday ( struct timeval* pTV, void* pTZ )
{
static struct timeval tvPrevRetVal = {0};
struct timespec ts = {0};
// Validate parameters...
UNREFERENCED( pTZ );
ASSERT( pTV );
if (unlikely( !pTV ))
{
errno = EINVAL;
return -1;
}
// Get nanosecond resolution TOD...
VERIFY( clock_gettime( CLOCK_REALTIME, &ts ) == 0 );
// Convert to microsecond resolution...
pTV->tv_sec = (long) (ts.tv_sec);
pTV->tv_usec = (long) ((ts.tv_nsec + 500) / 1000);
if (unlikely( pTV->tv_usec >= MILLION ))
{
pTV->tv_sec += 1;
pTV->tv_usec -= MILLION;
}
return 0;
}
#endif // !defined( HAVE_GETTIMEOFDAY )
//////////////////////////////////////////////////////////////////////////////////////////
// (INTERNAL) Sleep for specified number of nanoseconds...
static int w32_nanosleep ( const struct timespec* rqtp )
{
/**************************************************************************
NANOSLEEP
DESCRIPTION
The nanosleep() function shall cause the current thread
to be suspended from execution until either the time interval
specified by the rqtp argument has elapsed or a signal is
delivered to the calling thread, and its action is to invoke
a signal-catching function or to terminate the process. The
suspension time may be longer than requested because the argument
value is rounded up to an integer multiple of the sleep resolution
or because of the scheduling of other activity by the system.
But, except for the case of being interrupted by a signal, the
suspension time shall not be less than the time specified by rqtp,
as measured by the system clock CLOCK_REALTIME.
The use of the nanosleep() function has no effect on the action
or blockage of any signal.
RETURN VALUE
If the nanosleep() function returns because the requested time
has elapsed, its return value shall be zero.
If the nanosleep() function returns because it has been interrupted
by a signal, it shall return a value of -1 and set errno to indicate
the interruption. If the rmtp argument is non-NULL, the timespec
structure referenced by it is updated to contain the amount of time
remaining in the interval (the requested time minus the time actually
slept). If the rmtp argument is NULL, the remaining time is not
returned.
If nanosleep() fails, it shall return a value of -1 and set errno
to indicate the error.
ERRORS
The nanosleep() function shall fail if:
[EINTR] The nanosleep() function was interrupted by a signal.
[EINVAL] The rqtp argument specified a nanosecond value less than
zero or greater than or equal to 1000 million.
**************************************************************************/
// IMPLEMENTATION NOTE
//
// The following code of course does not actually implement true nano-
// second resolution sleep functionality since Windows does not support
// such finely grained timers (yet). It is however coded in such a way
// that should Windows ever begin providing such support in the future,
// the changes needed to support such high precisions should be trivial.
static LONGLONG timerint = 0; // TOD clock interval
static HANDLE hTimer = NULL; // Waitable timer handle
static LARGE_INTEGER liWaitAmt = {0}; // Amount of time to wait
static CRITICAL_SECTION waitlock = {0}; // Multi-threading lock
static struct timespec tsCurrTime = {0}; // Current Time-of-Day
static struct timespec tsWakeTime = {0}; // Current wakeup time
struct timespec tsSaveWake = {0}; // Saved wakeup time
struct timespec tsOurWake = {0}; // Our wakeup time
// Check passed parameters...
ASSERT( rqtp );
if (unlikely
(0
|| !rqtp
|| rqtp->tv_nsec < 0
|| rqtp->tv_nsec >= BILLION
))
{
errno = EINVAL;
return -1;
}
// Perform first time initialization...
if (unlikely( !hTimer ))
{
InitializeCriticalSectionAndSpinCount( &waitlock, 4000 );
VERIFY(( hTimer = CreateWaitableTimer( NULL, TRUE, NULL ) ) != NULL );
}
EnterCriticalSection( &waitlock );
do
{
// Calculate our wakeup time if we haven't done so yet...
if (unlikely( !tsOurWake.tv_sec ))
{
VERIFY( clock_gettime( CLOCK_REALTIME, &tsCurrTime ) == 0);
tsOurWake = tsCurrTime;
tsOurWake.tv_sec += rqtp->tv_sec;
tsOurWake.tv_nsec += rqtp->tv_nsec;
if (unlikely( tsOurWake.tv_nsec >= BILLION ))
{
tsOurWake.tv_sec += 1;
tsOurWake.tv_nsec -= BILLION;
}
}
// (CRTICIAL TEST)
//
// If our wakeup time is earlier than the current alarm time,
// then set the timer again with our new earlier wakeup time.
//
// Otherwise (our wakeup time comes later than the currently
// set wakeup/alarm time) we proceed directly to waiting for
// the existing currently set alarm to expire first...
if (0
|| !tsWakeTime.tv_sec
|| tsOurWake.tv_sec < tsWakeTime.tv_sec
|| (1
&& tsOurWake.tv_sec == tsWakeTime.tv_sec
&& tsOurWake.tv_nsec < tsWakeTime.tv_nsec
)
)
{
// Calculate how long to wait in 100-nanosecond units...
liWaitAmt.QuadPart =
(
( (LONGLONG)(tsOurWake.tv_sec - tsCurrTime.tv_sec) * 10000000 )
+
(((LONGLONG)(tsOurWake.tv_nsec - tsCurrTime.tv_nsec) + 50) / 100)
);
// For efficiency don't allow any wait interval shorter
// than our currently defined TOD clock update interval...
timerint = sysblk.timerint; // (copy volatile value)
if (unlikely( liWaitAmt.QuadPart < (timerint * 10) ))
{
// (adjust wakeup time to respect imposed minimum)
tsOurWake.tv_nsec += (long) ((timerint * 10) - liWaitAmt.QuadPart) * 100;
liWaitAmt.QuadPart = (timerint * 10);
if (unlikely( tsOurWake.tv_nsec >= BILLION ))
{
tsOurWake.tv_sec += (tsOurWake.tv_nsec / BILLION);
tsOurWake.tv_nsec %= BILLION;
}
}
liWaitAmt.QuadPart = -liWaitAmt.QuadPart; // (negative == relative)
VERIFY( SetWaitableTimer( hTimer, &liWaitAmt, 0, NULL, NULL, FALSE ) );
tsWakeTime = tsOurWake; // (use our wakeup time)
}
tsSaveWake = tsWakeTime; // (save the wakeup time)
// Wait for the currently calculated wakeup time to arrive...
LeaveCriticalSection( &waitlock );
{
VERIFY( WaitForSingleObject( hTimer, INFINITE ) == WAIT_OBJECT_0 );
}
EnterCriticalSection( &waitlock );
// Reset the wakeup time (if the previously awakened thread
// hasn't done that yet) and get a new updated current TOD.
// (CRTICIAL TEST)
if (1
&& tsWakeTime.tv_sec == tsSaveWake.tv_sec
&& tsWakeTime.tv_nsec == tsSaveWake.tv_nsec
&& WaitForSingleObject( hTimer, 0 ) == WAIT_OBJECT_0
)
{
// The wakeup time hasn't been changed and the timer
// is still signaled so we must be the first thread
// to be woken up (otherwise the previously awakened
// thread would have set a new wakeup time and the
// timer thus wouldn't still be signaled). We clear
// the wakeup time too (since it's now known to be
// obsolete) which forces us to calculate a new one
// further above.
tsWakeTime.tv_sec = 0; // (needs recalculated)
tsWakeTime.tv_nsec = 0; // (needs recalculated)
}
// PROGRAMMING NOTE: I thought about simply using either
// 'tsWakeTime' or 'tsSaveWake' (depending on the above
// condition) as our new current TOD value, but doing so
// does not yield the desired behavior, since the system
// does not always wake us at our exact requested time.
// Thus obtaining a fresh/current TOD value each time we
// are awakened yields more precise/desireable behavior.
VERIFY( clock_gettime( CLOCK_REALTIME, &tsCurrTime ) == 0);
}
while // (has our wakeup time arrived yet?)
(0
|| tsCurrTime.tv_sec < tsOurWake.tv_sec
|| (1
&& tsCurrTime.tv_sec == tsOurWake.tv_sec
&& tsCurrTime.tv_nsec < tsOurWake.tv_nsec
)
);
// Our wakeup time has arrived...
LeaveCriticalSection( &waitlock );
return 0;
}
//////////////////////////////////////////////////////////////////////////////////////////
// nanosleep - high resolution sleep
#if !defined( HAVE_NANOSLEEP )
DLL_EXPORT int nanosleep ( const struct timespec* rqtp, struct timespec* rmtp )
{
if (unlikely( rmtp ))
{
rmtp->tv_sec = 0;
rmtp->tv_nsec = 0;
}
return w32_nanosleep ( rqtp );
}
#endif // !defined( HAVE_NANOSLEEP )
//////////////////////////////////////////////////////////////////////////////////////////
// usleep - suspend execution for an interval
#if !defined( HAVE_USLEEP )
DLL_EXPORT int usleep ( useconds_t useconds )
{
// "The useconds argument shall be less than one million. If the value of
// useconds is 0, then the call has no effect."
// "Implementations may place limitations on the granularity of timer values.
// For each interval timer, if the requested timer value requires a finer
// granularity than the implementation supports, the actual timer value shall
// be rounded up to the next supported value."
// "Upon successful completion, usleep() shall return 0; otherwise, it shall
// return -1 and set errno to indicate the error."
// "The usleep() function may fail if:
//
// [EINVAL] The time interval specified
// one million or more microseconds"
struct timespec rqtp;
if (unlikely( useconds < 0 || useconds >= MILLION ))
{
errno = EINVAL;
return -1;
}
rqtp.tv_sec = 0;
rqtp.tv_nsec = useconds * 1000;
return w32_nanosleep ( &rqtp );
}
#endif // !defined( HAVE_USLEEP )
#endif // !defined( HAVE_NANOSLEEP ) || !defined( HAVE_USLEEP )
//////////////////////////////////////////////////////////////////////////////////////////
// Can't use "HAVE_SLEEP" since Win32's "Sleep" causes HAVE_SLEEP to
// be erroneously #defined due to autoconf AC_CHECK_FUNCS case issues...
//#if !defined( HAVE_SLEEP )
DLL_EXPORT unsigned sleep ( unsigned seconds )
{
Sleep( seconds * 1000 );