-
-
Notifications
You must be signed in to change notification settings - Fork 719
/
putil.cpp
2477 lines (2191 loc) · 78 KB
/
putil.cpp
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
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*
******************************************************************************
*
* Copyright (C) 1997-2016, International Business Machines
* Corporation and others. All Rights Reserved.
*
******************************************************************************
*
* FILE NAME : putil.c (previously putil.cpp and ptypes.cpp)
*
* Date Name Description
* 04/14/97 aliu Creation.
* 04/24/97 aliu Added getDefaultDataDirectory() and
* getDefaultLocaleID().
* 04/28/97 aliu Rewritten to assume Unix and apply general methods
* for assumed case. Non-UNIX platforms must be
* special-cased. Rewrote numeric methods dealing
* with NaN and Infinity to be platform independent
* over all IEEE 754 platforms.
* 05/13/97 aliu Restored sign of timezone
* (semantics are hours West of GMT)
* 06/16/98 erm Added IEEE_754 stuff, cleaned up isInfinite, isNan,
* nextDouble..
* 07/22/98 stephen Added remainder, max, min, trunc
* 08/13/98 stephen Added isNegativeInfinity, isPositiveInfinity
* 08/24/98 stephen Added longBitsFromDouble
* 09/08/98 stephen Minor changes for Mac Port
* 03/02/99 stephen Removed openFile(). Added AS400 support.
* Fixed EBCDIC tables
* 04/15/99 stephen Converted to C.
* 06/28/99 stephen Removed mutex locking in u_isBigEndian().
* 08/04/99 jeffrey R. Added OS/2 changes
* 11/15/99 helena Integrated S/390 IEEE support.
* 04/26/01 Barry N. OS/400 support for uprv_getDefaultLocaleID
* 08/15/01 Steven H. OS/400 support for uprv_getDefaultCodepage
* 01/03/08 Steven L. Fake Time Support
******************************************************************************
*/
// Defines _XOPEN_SOURCE for access to POSIX functions.
// Must be before any other #includes.
#include "uposixdefs.h"
// First, the platform type. Need this for U_PLATFORM.
#include "unicode/platform.h"
#if U_PLATFORM == U_PF_MINGW && defined __STRICT_ANSI__
/* tzset isn't defined in strict ANSI on MinGW. */
#undef __STRICT_ANSI__
#endif
/*
* Cygwin with GCC requires inclusion of time.h after the above disabling strict asci mode statement.
*/
#include <time.h>
#if !U_PLATFORM_USES_ONLY_WIN32_API
#include <sys/time.h>
#endif
/* include the rest of the ICU headers */
#include "unicode/putil.h"
#include "unicode/ustring.h"
#include "putilimp.h"
#include "uassert.h"
#include "umutex.h"
#include "cmemory.h"
#include "cstring.h"
#include "locmap.h"
#include "ucln_cmn.h"
#include "charstr.h"
/* Include standard headers. */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <locale.h>
#include <float.h>
#ifndef U_COMMON_IMPLEMENTATION
#error U_COMMON_IMPLEMENTATION not set - must be set for all ICU source files in common/ - see http://userguide.icu-project.org/howtouseicu
#endif
/* include system headers */
#if U_PLATFORM_USES_ONLY_WIN32_API
/*
* TODO: U_PLATFORM_USES_ONLY_WIN32_API includes MinGW.
* Should Cygwin be included as well (U_PLATFORM_HAS_WIN32_API)
* to use native APIs as much as possible?
*/
#ifndef WIN32_LEAN_AND_MEAN
# define WIN32_LEAN_AND_MEAN
#endif
# define VC_EXTRALEAN
# define NOUSER
# define NOSERVICE
# define NOIME
# define NOMCX
# include <windows.h>
# include "unicode/uloc.h"
#if U_PLATFORM_HAS_WINUWP_API == 0
# include "wintz.h"
#else // U_PLATFORM_HAS_WINUWP_API
typedef PVOID LPMSG; // TODO: figure out how to get rid of this typedef
#include <Windows.Globalization.h>
#include <windows.system.userprofile.h>
#include <wrl/wrappers/corewrappers.h>
#include <wrl/client.h>
using namespace ABI::Windows::Foundation;
using namespace Microsoft::WRL;
using namespace Microsoft::WRL::Wrappers;
#endif
#elif U_PLATFORM == U_PF_OS400
# include <float.h>
# include <qusec.h> /* error code structure */
# include <qusrjobi.h>
# include <qliept.h> /* EPT_CALL macro - this include must be after all other "QSYSINCs" */
# include <mih/testptr.h> /* For uprv_maximumPtr */
#elif U_PLATFORM == U_PF_OS390
# include "unicode/ucnv.h" /* Needed for UCNV_SWAP_LFNL_OPTION_STRING */
#elif U_PLATFORM_IS_DARWIN_BASED || U_PLATFORM_IS_LINUX_BASED || U_PLATFORM == U_PF_BSD || U_PLATFORM == U_PF_SOLARIS
# include <limits.h>
# include <unistd.h>
# if U_PLATFORM == U_PF_SOLARIS
# ifndef _XPG4_2
# define _XPG4_2
# endif
# endif
#elif U_PLATFORM == U_PF_QNX
# include <sys/neutrino.h>
#endif
/*
* Only include langinfo.h if we have a way to get the codeset. If we later
* depend on more feature, we can test on U_HAVE_NL_LANGINFO.
*
*/
#if U_HAVE_NL_LANGINFO_CODESET
#include <langinfo.h>
#endif
/**
* Simple things (presence of functions, etc) should just go in configure.in and be added to
* icucfg.h via autoheader.
*/
#if U_PLATFORM_IMPLEMENTS_POSIX
# if U_PLATFORM == U_PF_OS400
# define HAVE_DLFCN_H 0
# define HAVE_DLOPEN 0
# else
# ifndef HAVE_DLFCN_H
# define HAVE_DLFCN_H 1
# endif
# ifndef HAVE_DLOPEN
# define HAVE_DLOPEN 1
# endif
# endif
# ifndef HAVE_GETTIMEOFDAY
# define HAVE_GETTIMEOFDAY 1
# endif
#else
# define HAVE_DLFCN_H 0
# define HAVE_DLOPEN 0
# define HAVE_GETTIMEOFDAY 0
#endif
U_NAMESPACE_USE
/* Define the extension for data files, again... */
#define DATA_TYPE "dat"
/* Leave this copyright notice here! */
static const char copyright[] = U_COPYRIGHT_STRING;
/* floating point implementations ------------------------------------------- */
/* We return QNAN rather than SNAN*/
#define SIGN 0x80000000U
/* Make it easy to define certain types of constants */
typedef union {
int64_t i64; /* This must be defined first in order to allow the initialization to work. This is a C89 feature. */
double d64;
} BitPatternConversion;
static const BitPatternConversion gNan = { (int64_t) INT64_C(0x7FF8000000000000) };
static const BitPatternConversion gInf = { (int64_t) INT64_C(0x7FF0000000000000) };
/*---------------------------------------------------------------------------
Platform utilities
Our general strategy is to assume we're on a POSIX platform. Platforms which
are non-POSIX must declare themselves so. The default POSIX implementation
will sometimes work for non-POSIX platforms as well (e.g., the NaN-related
functions).
---------------------------------------------------------------------------*/
#if U_PLATFORM_USES_ONLY_WIN32_API || U_PLATFORM == U_PF_OS400
# undef U_POSIX_LOCALE
#else
# define U_POSIX_LOCALE 1
#endif
/*
WARNING! u_topNBytesOfDouble and u_bottomNBytesOfDouble
can't be properly optimized by the gcc compiler sometimes (i.e. gcc 3.2).
*/
#if !IEEE_754
static char*
u_topNBytesOfDouble(double* d, int n)
{
#if U_IS_BIG_ENDIAN
return (char*)d;
#else
return (char*)(d + 1) - n;
#endif
}
static char*
u_bottomNBytesOfDouble(double* d, int n)
{
#if U_IS_BIG_ENDIAN
return (char*)(d + 1) - n;
#else
return (char*)d;
#endif
}
#endif /* !IEEE_754 */
#if IEEE_754
static UBool
u_signBit(double d) {
uint8_t hiByte;
#if U_IS_BIG_ENDIAN
hiByte = *(uint8_t *)&d;
#else
hiByte = *(((uint8_t *)&d) + sizeof(double) - 1);
#endif
return (hiByte & 0x80) != 0;
}
#endif
#if defined (U_DEBUG_FAKETIME)
/* Override the clock to test things without having to move the system clock.
* Assumes POSIX gettimeofday() will function
*/
UDate fakeClock_t0 = 0; /** Time to start the clock from **/
UDate fakeClock_dt = 0; /** Offset (fake time - real time) **/
UBool fakeClock_set = FALSE; /** True if fake clock has spun up **/
static UMutex fakeClockMutex = U_MUTEX_INTIALIZER;
static UDate getUTCtime_real() {
struct timeval posixTime;
gettimeofday(&posixTime, NULL);
return (UDate)(((int64_t)posixTime.tv_sec * U_MILLIS_PER_SECOND) + (posixTime.tv_usec/1000));
}
static UDate getUTCtime_fake() {
umtx_lock(&fakeClockMutex);
if(!fakeClock_set) {
UDate real = getUTCtime_real();
const char *fake_start = getenv("U_FAKETIME_START");
if((fake_start!=NULL) && (fake_start[0]!=0)) {
sscanf(fake_start,"%lf",&fakeClock_t0);
fakeClock_dt = fakeClock_t0 - real;
fprintf(stderr,"U_DEBUG_FAKETIME was set at compile time, so the ICU clock will start at a preset value\n"
"env variable U_FAKETIME_START=%.0f (%s) for an offset of %.0f ms from the current time %.0f\n",
fakeClock_t0, fake_start, fakeClock_dt, real);
} else {
fakeClock_dt = 0;
fprintf(stderr,"U_DEBUG_FAKETIME was set at compile time, but U_FAKETIME_START was not set.\n"
"Set U_FAKETIME_START to the number of milliseconds since 1/1/1970 to set the ICU clock.\n");
}
fakeClock_set = TRUE;
}
umtx_unlock(&fakeClockMutex);
return getUTCtime_real() + fakeClock_dt;
}
#endif
#if U_PLATFORM_USES_ONLY_WIN32_API
typedef union {
int64_t int64;
FILETIME fileTime;
} FileTimeConversion; /* This is like a ULARGE_INTEGER */
/* Number of 100 nanoseconds from 1/1/1601 to 1/1/1970 */
#define EPOCH_BIAS INT64_C(116444736000000000)
#define HECTONANOSECOND_PER_MILLISECOND 10000
#endif
/*---------------------------------------------------------------------------
Universal Implementations
These are designed to work on all platforms. Try these, and if they
don't work on your platform, then special case your platform with new
implementations.
---------------------------------------------------------------------------*/
U_CAPI UDate U_EXPORT2
uprv_getUTCtime()
{
#if defined(U_DEBUG_FAKETIME)
return getUTCtime_fake(); /* Hook for overriding the clock */
#else
return uprv_getRawUTCtime();
#endif
}
/* Return UTC (GMT) time measured in milliseconds since 0:00 on 1/1/70.*/
U_CAPI UDate U_EXPORT2
uprv_getRawUTCtime()
{
#if U_PLATFORM_USES_ONLY_WIN32_API
FileTimeConversion winTime;
GetSystemTimeAsFileTime(&winTime.fileTime);
return (UDate)((winTime.int64 - EPOCH_BIAS) / HECTONANOSECOND_PER_MILLISECOND);
#else
#if HAVE_GETTIMEOFDAY
struct timeval posixTime;
gettimeofday(&posixTime, NULL);
return (UDate)(((int64_t)posixTime.tv_sec * U_MILLIS_PER_SECOND) + (posixTime.tv_usec/1000));
#else
time_t epochtime;
time(&epochtime);
return (UDate)epochtime * U_MILLIS_PER_SECOND;
#endif
#endif
}
/*-----------------------------------------------------------------------------
IEEE 754
These methods detect and return NaN and infinity values for doubles
conforming to IEEE 754. Platforms which support this standard include X86,
Mac 680x0, Mac PowerPC, AIX RS/6000, and most others.
If this doesn't work on your platform, you have non-IEEE floating-point, and
will need to code your own versions. A naive implementation is to return 0.0
for getNaN and getInfinity, and false for isNaN and isInfinite.
---------------------------------------------------------------------------*/
U_CAPI UBool U_EXPORT2
uprv_isNaN(double number)
{
#if IEEE_754
BitPatternConversion convertedNumber;
convertedNumber.d64 = number;
/* Infinity is 0x7FF0000000000000U. Anything greater than that is a NaN */
return (UBool)((convertedNumber.i64 & U_INT64_MAX) > gInf.i64);
#elif U_PLATFORM == U_PF_OS390
uint32_t highBits = *(uint32_t*)u_topNBytesOfDouble(&number,
sizeof(uint32_t));
uint32_t lowBits = *(uint32_t*)u_bottomNBytesOfDouble(&number,
sizeof(uint32_t));
return ((highBits & 0x7F080000L) == 0x7F080000L) &&
(lowBits == 0x00000000L);
#else
/* If your platform doesn't support IEEE 754 but *does* have an NaN value,*/
/* you'll need to replace this default implementation with what's correct*/
/* for your platform.*/
return number != number;
#endif
}
U_CAPI UBool U_EXPORT2
uprv_isInfinite(double number)
{
#if IEEE_754
BitPatternConversion convertedNumber;
convertedNumber.d64 = number;
/* Infinity is exactly 0x7FF0000000000000U. */
return (UBool)((convertedNumber.i64 & U_INT64_MAX) == gInf.i64);
#elif U_PLATFORM == U_PF_OS390
uint32_t highBits = *(uint32_t*)u_topNBytesOfDouble(&number,
sizeof(uint32_t));
uint32_t lowBits = *(uint32_t*)u_bottomNBytesOfDouble(&number,
sizeof(uint32_t));
return ((highBits & ~SIGN) == 0x70FF0000L) && (lowBits == 0x00000000L);
#else
/* If your platform doesn't support IEEE 754 but *does* have an infinity*/
/* value, you'll need to replace this default implementation with what's*/
/* correct for your platform.*/
return number == (2.0 * number);
#endif
}
U_CAPI UBool U_EXPORT2
uprv_isPositiveInfinity(double number)
{
#if IEEE_754 || U_PLATFORM == U_PF_OS390
return (UBool)(number > 0 && uprv_isInfinite(number));
#else
return uprv_isInfinite(number);
#endif
}
U_CAPI UBool U_EXPORT2
uprv_isNegativeInfinity(double number)
{
#if IEEE_754 || U_PLATFORM == U_PF_OS390
return (UBool)(number < 0 && uprv_isInfinite(number));
#else
uint32_t highBits = *(uint32_t*)u_topNBytesOfDouble(&number,
sizeof(uint32_t));
return((highBits & SIGN) && uprv_isInfinite(number));
#endif
}
U_CAPI double U_EXPORT2
uprv_getNaN()
{
#if IEEE_754 || U_PLATFORM == U_PF_OS390
return gNan.d64;
#else
/* If your platform doesn't support IEEE 754 but *does* have an NaN value,*/
/* you'll need to replace this default implementation with what's correct*/
/* for your platform.*/
return 0.0;
#endif
}
U_CAPI double U_EXPORT2
uprv_getInfinity()
{
#if IEEE_754 || U_PLATFORM == U_PF_OS390
return gInf.d64;
#else
/* If your platform doesn't support IEEE 754 but *does* have an infinity*/
/* value, you'll need to replace this default implementation with what's*/
/* correct for your platform.*/
return 0.0;
#endif
}
U_CAPI double U_EXPORT2
uprv_floor(double x)
{
return floor(x);
}
U_CAPI double U_EXPORT2
uprv_ceil(double x)
{
return ceil(x);
}
U_CAPI double U_EXPORT2
uprv_round(double x)
{
return uprv_floor(x + 0.5);
}
U_CAPI double U_EXPORT2
uprv_fabs(double x)
{
return fabs(x);
}
U_CAPI double U_EXPORT2
uprv_modf(double x, double* y)
{
return modf(x, y);
}
U_CAPI double U_EXPORT2
uprv_fmod(double x, double y)
{
return fmod(x, y);
}
U_CAPI double U_EXPORT2
uprv_pow(double x, double y)
{
/* This is declared as "double pow(double x, double y)" */
return pow(x, y);
}
U_CAPI double U_EXPORT2
uprv_pow10(int32_t x)
{
return pow(10.0, (double)x);
}
U_CAPI double U_EXPORT2
uprv_fmax(double x, double y)
{
#if IEEE_754
/* first handle NaN*/
if(uprv_isNaN(x) || uprv_isNaN(y))
return uprv_getNaN();
/* check for -0 and 0*/
if(x == 0.0 && y == 0.0 && u_signBit(x))
return y;
#endif
/* this should work for all flt point w/o NaN and Inf special cases */
return (x > y ? x : y);
}
U_CAPI double U_EXPORT2
uprv_fmin(double x, double y)
{
#if IEEE_754
/* first handle NaN*/
if(uprv_isNaN(x) || uprv_isNaN(y))
return uprv_getNaN();
/* check for -0 and 0*/
if(x == 0.0 && y == 0.0 && u_signBit(y))
return y;
#endif
/* this should work for all flt point w/o NaN and Inf special cases */
return (x > y ? y : x);
}
/**
* Truncates the given double.
* trunc(3.3) = 3.0, trunc (-3.3) = -3.0
* This is different than calling floor() or ceil():
* floor(3.3) = 3, floor(-3.3) = -4
* ceil(3.3) = 4, ceil(-3.3) = -3
*/
U_CAPI double U_EXPORT2
uprv_trunc(double d)
{
#if IEEE_754
/* handle error cases*/
if(uprv_isNaN(d))
return uprv_getNaN();
if(uprv_isInfinite(d))
return uprv_getInfinity();
if(u_signBit(d)) /* Signbit() picks up -0.0; d<0 does not. */
return ceil(d);
else
return floor(d);
#else
return d >= 0 ? floor(d) : ceil(d);
#endif
}
/**
* Return the largest positive number that can be represented by an integer
* type of arbitrary bit length.
*/
U_CAPI double U_EXPORT2
uprv_maxMantissa(void)
{
return pow(2.0, DBL_MANT_DIG + 1.0) - 1.0;
}
U_CAPI double U_EXPORT2
uprv_log(double d)
{
return log(d);
}
U_CAPI void * U_EXPORT2
uprv_maximumPtr(void * base)
{
#if U_PLATFORM == U_PF_OS400
/*
* With the provided function we should never be out of range of a given segment
* (a traditional/typical segment that is). Our segments have 5 bytes for the
* id and 3 bytes for the offset. The key is that the casting takes care of
* only retrieving the offset portion minus x1000. Hence, the smallest offset
* seen in a program is x001000 and when casted to an int would be 0.
* That's why we can only add 0xffefff. Otherwise, we would exceed the segment.
*
* Currently, 16MB is the current addressing limitation on i5/OS if the activation is
* non-TERASPACE. If it is TERASPACE it is 2GB - 4k(header information).
* This function determines the activation based on the pointer that is passed in and
* calculates the appropriate maximum available size for
* each pointer type (TERASPACE and non-TERASPACE)
*
* Unlike other operating systems, the pointer model isn't determined at
* compile time on i5/OS.
*/
if ((base != NULL) && (_TESTPTR(base, _C_TERASPACE_CHECK))) {
/* if it is a TERASPACE pointer the max is 2GB - 4k */
return ((void *)(((char *)base)-((uint32_t)(base))+((uint32_t)0x7fffefff)));
}
/* otherwise 16MB since NULL ptr is not checkable or the ptr is not TERASPACE */
return ((void *)(((char *)base)-((uint32_t)(base))+((uint32_t)0xffefff)));
#else
return U_MAX_PTR(base);
#endif
}
/*---------------------------------------------------------------------------
Platform-specific Implementations
Try these, and if they don't work on your platform, then special case your
platform with new implementations.
---------------------------------------------------------------------------*/
/* Generic time zone layer -------------------------------------------------- */
/* Time zone utilities */
U_CAPI void U_EXPORT2
uprv_tzset()
{
#if defined(U_TZSET)
U_TZSET();
#else
/* no initialization*/
#endif
}
U_CAPI int32_t U_EXPORT2
uprv_timezone()
{
#ifdef U_TIMEZONE
return U_TIMEZONE;
#else
time_t t, t1, t2;
struct tm tmrec;
int32_t tdiff = 0;
time(&t);
uprv_memcpy( &tmrec, localtime(&t), sizeof(tmrec) );
#if U_PLATFORM != U_PF_IPHONE
UBool dst_checked = (tmrec.tm_isdst != 0); /* daylight savings time is checked*/
#endif
t1 = mktime(&tmrec); /* local time in seconds*/
uprv_memcpy( &tmrec, gmtime(&t), sizeof(tmrec) );
t2 = mktime(&tmrec); /* GMT (or UTC) in seconds*/
tdiff = t2 - t1;
#if U_PLATFORM != U_PF_IPHONE
/* imitate NT behaviour, which returns same timezone offset to GMT for
winter and summer.
This does not work on all platforms. For instance, on glibc on Linux
and on Mac OS 10.5, tdiff calculated above remains the same
regardless of whether DST is in effect or not. iOS is another
platform where this does not work. Linux + glibc and Mac OS 10.5
have U_TIMEZONE defined so that this code is not reached.
*/
if (dst_checked)
tdiff += 3600;
#endif
return tdiff;
#endif
}
/* Note that U_TZNAME does *not* have to be tzname, but if it is,
some platforms need to have it declared here. */
#if defined(U_TZNAME) && (U_PLATFORM == U_PF_IRIX || U_PLATFORM_IS_DARWIN_BASED)
/* RS6000 and others reject char **tzname. */
extern U_IMPORT char *U_TZNAME[];
#endif
#if !UCONFIG_NO_FILE_IO && ((U_PLATFORM_IS_DARWIN_BASED && (U_PLATFORM != U_PF_IPHONE || defined(U_TIMEZONE))) || U_PLATFORM_IS_LINUX_BASED || U_PLATFORM == U_PF_BSD || U_PLATFORM == U_PF_SOLARIS)
/* These platforms are likely to use Olson timezone IDs. */
/* common targets of the symbolic link at TZDEFAULT are:
* "/usr/share/zoneinfo/<olsonID>" default, older Linux distros, macOS to 10.12
* "../usr/share/zoneinfo/<olsonID>" newer Linux distros: Red Hat Enterprise Linux 7, Ubuntu 16, SuSe Linux 12
* "/usr/share/lib/zoneinfo/<olsonID>" Solaris
* "../usr/share/lib/zoneinfo/<olsonID>" Solaris
* "/var/db/timezone/zoneinfo/<olsonID>" macOS 10.13
* To avoid checking lots of paths, just check that the target path
* before the <olsonID> ends with "/zoneinfo/", and the <olsonID> is valid.
*/
#define CHECK_LOCALTIME_LINK 1
#if U_PLATFORM_IS_DARWIN_BASED
#include <tzfile.h>
#define TZZONEINFO (TZDIR "/")
#elif U_PLATFORM == U_PF_SOLARIS
#define TZDEFAULT "/etc/localtime"
#define TZZONEINFO "/usr/share/lib/zoneinfo/"
#define TZ_ENV_CHECK "localtime"
#else
#define TZDEFAULT "/etc/localtime"
#define TZZONEINFO "/usr/share/zoneinfo/"
#endif
#define TZZONEINFOTAIL "/zoneinfo/"
#if U_HAVE_DIRENT_H
#define TZFILE_SKIP "posixrules" /* tz file to skip when searching. */
/* Some Linux distributions have 'localtime' in /usr/share/zoneinfo
symlinked to /etc/localtime, which makes searchForTZFile return
'localtime' when it's the first match. */
#define TZFILE_SKIP2 "localtime"
#define SEARCH_TZFILE
#include <dirent.h> /* Needed to search through system timezone files */
#endif
static char gTimeZoneBuffer[PATH_MAX];
static char *gTimeZoneBufferPtr = NULL;
#endif
#if !U_PLATFORM_USES_ONLY_WIN32_API
#define isNonDigit(ch) (ch < '0' || '9' < ch)
static UBool isValidOlsonID(const char *id) {
int32_t idx = 0;
/* Determine if this is something like Iceland (Olson ID)
or AST4ADT (non-Olson ID) */
while (id[idx] && isNonDigit(id[idx]) && id[idx] != ',') {
idx++;
}
/* If we went through the whole string, then it might be okay.
The timezone is sometimes set to "CST-7CDT", "CST6CDT5,J129,J131/19:30",
"GRNLNDST3GRNLNDDT" or similar, so we cannot use it.
The rest of the time it could be an Olson ID. George */
return (UBool)(id[idx] == 0
|| uprv_strcmp(id, "PST8PDT") == 0
|| uprv_strcmp(id, "MST7MDT") == 0
|| uprv_strcmp(id, "CST6CDT") == 0
|| uprv_strcmp(id, "EST5EDT") == 0);
}
/* On some Unix-like OS, 'posix' subdirectory in
/usr/share/zoneinfo replicates the top-level contents. 'right'
subdirectory has the same set of files, but individual files
are different from those in the top-level directory or 'posix'
because 'right' has files for TAI (Int'l Atomic Time) while 'posix'
has files for UTC.
When the first match for /etc/localtime is in either of them
(usually in posix because 'right' has different file contents),
or TZ environment variable points to one of them, createTimeZone
fails because, say, 'posix/America/New_York' is not an Olson
timezone id ('America/New_York' is). So, we have to skip
'posix/' and 'right/' at the beginning. */
static void skipZoneIDPrefix(const char** id) {
if (uprv_strncmp(*id, "posix/", 6) == 0
|| uprv_strncmp(*id, "right/", 6) == 0)
{
*id += 6;
}
}
#endif
#if defined(U_TZNAME) && !U_PLATFORM_USES_ONLY_WIN32_API
#define CONVERT_HOURS_TO_SECONDS(offset) (int32_t)(offset*3600)
typedef struct OffsetZoneMapping {
int32_t offsetSeconds;
int32_t daylightType; /* 0=U_DAYLIGHT_NONE, 1=daylight in June-U_DAYLIGHT_JUNE, 2=daylight in December=U_DAYLIGHT_DECEMBER*/
const char *stdID;
const char *dstID;
const char *olsonID;
} OffsetZoneMapping;
enum { U_DAYLIGHT_NONE=0,U_DAYLIGHT_JUNE=1,U_DAYLIGHT_DECEMBER=2 };
/*
This list tries to disambiguate a set of abbreviated timezone IDs and offsets
and maps it to an Olson ID.
Before adding anything to this list, take a look at
icu/source/tools/tzcode/tz.alias
Sometimes no daylight savings (0) is important to define due to aliases.
This list can be tested with icu/source/test/compat/tzone.pl
More values could be added to daylightType to increase precision.
*/
static const struct OffsetZoneMapping OFFSET_ZONE_MAPPINGS[] = {
{-45900, 2, "CHAST", "CHADT", "Pacific/Chatham"},
{-43200, 1, "PETT", "PETST", "Asia/Kamchatka"},
{-43200, 2, "NZST", "NZDT", "Pacific/Auckland"},
{-43200, 1, "ANAT", "ANAST", "Asia/Anadyr"},
{-39600, 1, "MAGT", "MAGST", "Asia/Magadan"},
{-37800, 2, "LHST", "LHST", "Australia/Lord_Howe"},
{-36000, 2, "EST", "EST", "Australia/Sydney"},
{-36000, 1, "SAKT", "SAKST", "Asia/Sakhalin"},
{-36000, 1, "VLAT", "VLAST", "Asia/Vladivostok"},
{-34200, 2, "CST", "CST", "Australia/South"},
{-32400, 1, "YAKT", "YAKST", "Asia/Yakutsk"},
{-32400, 1, "CHOT", "CHOST", "Asia/Choibalsan"},
{-31500, 2, "CWST", "CWST", "Australia/Eucla"},
{-28800, 1, "IRKT", "IRKST", "Asia/Irkutsk"},
{-28800, 1, "ULAT", "ULAST", "Asia/Ulaanbaatar"},
{-28800, 2, "WST", "WST", "Australia/West"},
{-25200, 1, "HOVT", "HOVST", "Asia/Hovd"},
{-25200, 1, "KRAT", "KRAST", "Asia/Krasnoyarsk"},
{-21600, 1, "NOVT", "NOVST", "Asia/Novosibirsk"},
{-21600, 1, "OMST", "OMSST", "Asia/Omsk"},
{-18000, 1, "YEKT", "YEKST", "Asia/Yekaterinburg"},
{-14400, 1, "SAMT", "SAMST", "Europe/Samara"},
{-14400, 1, "AMT", "AMST", "Asia/Yerevan"},
{-14400, 1, "AZT", "AZST", "Asia/Baku"},
{-10800, 1, "AST", "ADT", "Asia/Baghdad"},
{-10800, 1, "MSK", "MSD", "Europe/Moscow"},
{-10800, 1, "VOLT", "VOLST", "Europe/Volgograd"},
{-7200, 0, "EET", "CEST", "Africa/Tripoli"},
{-7200, 1, "EET", "EEST", "Europe/Athens"}, /* Conflicts with Africa/Cairo */
{-7200, 1, "IST", "IDT", "Asia/Jerusalem"},
{-3600, 0, "CET", "WEST", "Africa/Algiers"},
{-3600, 2, "WAT", "WAST", "Africa/Windhoek"},
{0, 1, "GMT", "IST", "Europe/Dublin"},
{0, 1, "GMT", "BST", "Europe/London"},
{0, 0, "WET", "WEST", "Africa/Casablanca"},
{0, 0, "WET", "WET", "Africa/El_Aaiun"},
{3600, 1, "AZOT", "AZOST", "Atlantic/Azores"},
{3600, 1, "EGT", "EGST", "America/Scoresbysund"},
{10800, 1, "PMST", "PMDT", "America/Miquelon"},
{10800, 2, "UYT", "UYST", "America/Montevideo"},
{10800, 1, "WGT", "WGST", "America/Godthab"},
{10800, 2, "BRT", "BRST", "Brazil/East"},
{12600, 1, "NST", "NDT", "America/St_Johns"},
{14400, 1, "AST", "ADT", "Canada/Atlantic"},
{14400, 2, "AMT", "AMST", "America/Cuiaba"},
{14400, 2, "CLT", "CLST", "Chile/Continental"},
{14400, 2, "FKT", "FKST", "Atlantic/Stanley"},
{14400, 2, "PYT", "PYST", "America/Asuncion"},
{18000, 1, "CST", "CDT", "America/Havana"},
{18000, 1, "EST", "EDT", "US/Eastern"}, /* Conflicts with America/Grand_Turk */
{21600, 2, "EAST", "EASST", "Chile/EasterIsland"},
{21600, 0, "CST", "MDT", "Canada/Saskatchewan"},
{21600, 0, "CST", "CDT", "America/Guatemala"},
{21600, 1, "CST", "CDT", "US/Central"}, /* Conflicts with Mexico/General */
{25200, 1, "MST", "MDT", "US/Mountain"}, /* Conflicts with Mexico/BajaSur */
{28800, 0, "PST", "PST", "Pacific/Pitcairn"},
{28800, 1, "PST", "PDT", "US/Pacific"}, /* Conflicts with Mexico/BajaNorte */
{32400, 1, "AKST", "AKDT", "US/Alaska"},
{36000, 1, "HAST", "HADT", "US/Aleutian"}
};
/*#define DEBUG_TZNAME*/
static const char* remapShortTimeZone(const char *stdID, const char *dstID, int32_t daylightType, int32_t offset)
{
int32_t idx;
#ifdef DEBUG_TZNAME
fprintf(stderr, "TZ=%s std=%s dst=%s daylight=%d offset=%d\n", getenv("TZ"), stdID, dstID, daylightType, offset);
#endif
for (idx = 0; idx < UPRV_LENGTHOF(OFFSET_ZONE_MAPPINGS); idx++)
{
if (offset == OFFSET_ZONE_MAPPINGS[idx].offsetSeconds
&& daylightType == OFFSET_ZONE_MAPPINGS[idx].daylightType
&& strcmp(OFFSET_ZONE_MAPPINGS[idx].stdID, stdID) == 0
&& strcmp(OFFSET_ZONE_MAPPINGS[idx].dstID, dstID) == 0)
{
return OFFSET_ZONE_MAPPINGS[idx].olsonID;
}
}
return NULL;
}
#endif
#ifdef SEARCH_TZFILE
#define MAX_READ_SIZE 512
typedef struct DefaultTZInfo {
char* defaultTZBuffer;
int64_t defaultTZFileSize;
FILE* defaultTZFilePtr;
UBool defaultTZstatus;
int32_t defaultTZPosition;
} DefaultTZInfo;
/*
* This method compares the two files given to see if they are a match.
* It is currently use to compare two TZ files.
*/
static UBool compareBinaryFiles(const char* defaultTZFileName, const char* TZFileName, DefaultTZInfo* tzInfo) {
FILE* file;
int64_t sizeFile;
int64_t sizeFileLeft;
int32_t sizeFileRead;
int32_t sizeFileToRead;
char bufferFile[MAX_READ_SIZE];
UBool result = TRUE;
if (tzInfo->defaultTZFilePtr == NULL) {
tzInfo->defaultTZFilePtr = fopen(defaultTZFileName, "r");
}
file = fopen(TZFileName, "r");
tzInfo->defaultTZPosition = 0; /* reset position to begin search */
if (file != NULL && tzInfo->defaultTZFilePtr != NULL) {
/* First check that the file size are equal. */
if (tzInfo->defaultTZFileSize == 0) {
fseek(tzInfo->defaultTZFilePtr, 0, SEEK_END);
tzInfo->defaultTZFileSize = ftell(tzInfo->defaultTZFilePtr);
}
fseek(file, 0, SEEK_END);
sizeFile = ftell(file);
sizeFileLeft = sizeFile;
if (sizeFile != tzInfo->defaultTZFileSize) {
result = FALSE;
} else {
/* Store the data from the files in seperate buffers and
* compare each byte to determine equality.
*/
if (tzInfo->defaultTZBuffer == NULL) {
rewind(tzInfo->defaultTZFilePtr);
tzInfo->defaultTZBuffer = (char*)uprv_malloc(sizeof(char) * tzInfo->defaultTZFileSize);
sizeFileRead = fread(tzInfo->defaultTZBuffer, 1, tzInfo->defaultTZFileSize, tzInfo->defaultTZFilePtr);
}
rewind(file);
while(sizeFileLeft > 0) {
uprv_memset(bufferFile, 0, MAX_READ_SIZE);
sizeFileToRead = sizeFileLeft < MAX_READ_SIZE ? sizeFileLeft : MAX_READ_SIZE;
sizeFileRead = fread(bufferFile, 1, sizeFileToRead, file);
if (memcmp(tzInfo->defaultTZBuffer + tzInfo->defaultTZPosition, bufferFile, sizeFileRead) != 0) {
result = FALSE;
break;
}
sizeFileLeft -= sizeFileRead;
tzInfo->defaultTZPosition += sizeFileRead;
}
}
} else {
result = FALSE;
}
if (file != NULL) {
fclose(file);
}
return result;
}
/* dirent also lists two entries: "." and ".." that we can safely ignore. */
#define SKIP1 "."
#define SKIP2 ".."
static UBool U_CALLCONV putil_cleanup(void);
static CharString *gSearchTZFileResult = NULL;
/*
* This method recursively traverses the directory given for a matching TZ file and returns the first match.
* This function is not thread safe - it uses a global, gSearchTZFileResult, to hold its results.
*/
static char* searchForTZFile(const char* path, DefaultTZInfo* tzInfo) {
DIR* dirp = NULL;
struct dirent* dirEntry = NULL;
char* result = NULL;
UErrorCode status = U_ZERO_ERROR;
/* Save the current path */
CharString curpath(path, -1, status);
if (U_FAILURE(status)) {
goto cleanupAndReturn;
}
dirp = opendir(path);
if (dirp == NULL) {
goto cleanupAndReturn;
}
if (gSearchTZFileResult == NULL) {
gSearchTZFileResult = new CharString;
if (gSearchTZFileResult == NULL) {
goto cleanupAndReturn;
}
ucln_common_registerCleanup(UCLN_COMMON_PUTIL, putil_cleanup);
}
/* Check each entry in the directory. */
while((dirEntry = readdir(dirp)) != NULL) {
const char* dirName = dirEntry->d_name;
if (uprv_strcmp(dirName, SKIP1) != 0 && uprv_strcmp(dirName, SKIP2) != 0) {
/* Create a newpath with the new entry to test each entry in the directory. */
CharString newpath(curpath, status);
newpath.append(dirName, -1, status);
if (U_FAILURE(status)) {
break;
}
DIR* subDirp = NULL;
if ((subDirp = opendir(newpath.data())) != NULL) {
/* If this new path is a directory, make a recursive call with the newpath. */
closedir(subDirp);
newpath.append('/', status);
if (U_FAILURE(status)) {
break;
}
result = searchForTZFile(newpath.data(), tzInfo);
/*
Have to get out here. Otherwise, we'd keep looking
and return the first match in the top-level directory
if there's a match in the top-level. If not, this function
would return NULL and set gTimeZoneBufferPtr to NULL in initDefault().