-
-
Notifications
You must be signed in to change notification settings - Fork 122
/
mormot.core.os.posix.inc
4084 lines (3731 loc) · 113 KB
/
mormot.core.os.posix.inc
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
{
This file is a part of the Open Source Synopse mORMot framework 2,
licensed under a MPL/GPL/LGPL three license - see LICENSE.md
POSIX API calls for FPC, as used by mormot.core.os.pas
}
uses
baseunix,
unix,
unixcp,
unixtype,
unixutil, // for TZSeconds - used by sysutils anyway
{$ifdef OSBSDDARWIN}
sysctl,
{$else}
linux,
syscall,
{$endif OSBSDDARWIN}
{$ifdef FPCUSEVERSIONINFO} // to be enabled in mormot.defines.inc
fileinfo, // FPC 3.0 and up
{$ifdef OSDARWIN}
machoreader, // MACH-O executables
{$else}
elfreader, // ELF executables
{$endif OSDARWIN}
{$endif FPCUSEVERSIONINFO}
errors,
termio,
dl,
initc; // we statically link the libc for some raw calls
{$ifdef UNICODE}
'mORMot assumes no UNICODE on POSIX, i.e. as TFileName = PChar = PUtf8Char'
{$endif UNICODE}
// define some raw text functions, to avoid linking mormot.core.text
function IdemPChar(p, up: PUtf8Char): boolean; inline;
var
c, u: AnsiChar;
begin
// we know that p<>nil and up<>nil within this unit
result := false;
repeat
u := up^;
if u = #0 then
break;
inc(up);
c := p^;
inc(p);
if c <> u then
if (c >= 'a') and
(c <= 'z') then
begin
dec(c, 32);
if c <> u then
exit;
end
else
exit;
until false;
result := true;
end;
function IdemPChars(const s: RawUtf8; const up: array of PUtf8Char): boolean;
var
i: PtrInt;
begin
if s <> '' then
begin
result := true;
for i := 0 to high(up) do
if IdemPChar(pointer(s), up[i]) then
exit;
end;
result := false;
end;
procedure FindNameValue(const s, up: RawUtf8; var res: RawUtf8);
var
p: PUtf8Char;
L: PtrInt;
begin
p := pointer(s);
while p <> nil do
begin
if IdemPChar(p, pointer(up)) then
begin
inc(p, length(up));
while (p^ <= ' ') and
(p^ <> #0) do
inc(p); // trim left
L := 0;
while p[L] > #13 do
inc(L);
while p[L - 1] = ' ' do
dec(L); // trim right
FastSetString(res, p, L);
exit;
end;
p := GotoNextLine(p);
end;
res := '';
end;
function GetNextCardinal(var P: PAnsiChar): PtrUInt;
var
c: cardinal;
begin
result := 0;
while not (P^ in ['0'..'9']) do
if P^ = #0 then
exit
else
inc(P);
repeat
c := ord(P^) - 48;
if c > 9 then
break;
result := result * 10 + c;
inc(P);
until false;
end;
function GetNextItem(var P: PAnsiChar): RawUtf8;
var
S: PAnsiChar;
begin
result := '';
while P^ <= ' ' do
if P^ = #0 then
exit
else
inc(P);
S := P;
repeat
inc(P);
until P^ <= ' ';
FastSetString(result, S, P - S);
end;
procedure RawUtf8Append(var s: RawUtf8; p: PUtf8Char; l: PtrInt);
var
n: PtrInt;
begin
if l = 0 then
exit;
n := length(s);
SetLength(s, n + l);
MoveFast(p^, PByteArray(s)[n], l);
end;
function _fmt(const Fmt: string; const Args: array of const): RawUtf8; overload;
begin
result := RawUtf8(format(Fmt, Args)); // good enough (seldom called)
end;
procedure _fmt(const Fmt: string; const Args: array of const;
var result: RawUtf8); overload;
begin
result := RawUtf8(format(Fmt, Args)); // good enough (seldom called)
end;
{ ****************** Unicode, Time, File process }
function LibraryOpen(const LibraryName: TFileName): TLibHandle;
begin
result := TLibHandle(dlopen(pointer(LibraryName), RTLD_LAZY));
end;
procedure LibraryClose(Lib: TLibHandle);
begin
dlclose(pointer(Lib));
end;
function LibraryResolve(Lib: TLibHandle; ProcName: PAnsiChar): pointer;
begin
result := dlsym(pointer(Lib), ProcName);
end;
function LibraryError: string;
begin
result := dlerror;
end;
{ TIcuLibrary }
procedure TIcuLibrary.Done;
begin
if icui18n <> nil then
dlclose(icui18n);
if icu <> nil then
dlclose(icu);
if icudata <> nil then
dlclose(icudata);
icu := nil;
icudata := nil;
icui18n := nil;
@ucnv_open := nil;
end;
function TIcuLibrary.IsAvailable: boolean;
begin
if not Loaded then
DoLoad;
result := Assigned(ucnv_open);
end;
function IsWideStringManagerProperlyInstalled: boolean;
const
u: WideChar = #$2020; // should convert to dagger glyph #134 in CP 1252
var
d: RawByteString;
begin
try
widestringmanager.Unicode2AnsiMoveProc(@u, d, 1252, 1);
result := (length(d) = 1) and
(d[1] = #134);
// the default RTL handler would just return '?'
except
result := false;
end;
end;
procedure TIcuLibrary.DoLoad(const LibName: TFileName; Version: string);
const
NAMES: array[0..12] of string = (
'ucnv_open',
'ucnv_close',
'ucnv_setSubstChars',
'ucnv_setFallback',
'ucnv_fromUChars',
'ucnv_toUChars',
'u_strToUpper',
'u_strToLower',
'u_strCompare',
'u_strCaseCompare',
'u_getDataDirectory',
'u_setDataDirectory',
'u_init');
{$ifdef OSANDROID}
// https://developer.android.com/guide/topics/resources/internationalization
ICU_VER: array[1..15] of string = (
'_3_8', '_4_2', '_44', '_46', '_48', '_50', '_51', '_53', '_55',
'_56', '_58', '_60', '_63', '_66', '_68');
ICU_MAX = 80;
ICU_MIN = 69; // previous versions are known and listed within ICU_VER[]
SYSDATA: PAnsiChar = '/system/usr/icu';
{$else}
ICU_MAX = 80;
ICU_MIN = 44;
SYSDATA: PAnsiChar = '';
{$endif OSANDROID}
var
i: integer;
err: SizeInt;
P: PPointer;
{$ifndef OSDARWIN}
so: string;
{$endif OSDARWIN}
v, vers: string;
data: PAnsiChar;
begin
GlobalLock;
try
if Loaded then
exit;
Loaded := true;
if LibName <> '' then
begin
icu := dlopen(pointer(LibName), RTLD_LAZY);
if icu = nil then
exit;
end
else
begin
{$ifdef OSDARWIN}
// Mach OS has its own ICU set of libraries
icu := dlopen('libicuuc.dylib', RTLD_LAZY);
if icu <> nil then
icui18n := dlopen('libicui18n.dylib', RTLD_LAZY);
{$else}
// libicudata should be loaded first because other two depend on it
icudata := dlopen('libicudata.so', RTLD_LAZY);
{$ifndef OSANDROID}
if icudata = nil then
begin
// there is no link to the library -> try e.g. 'libicudata.so.67'
if Version <> '' then
icudata := dlopen(pointer('libicudata.so.' + Version), RTLD_LAZY);
if icudata = nil then
for i := ICU_MAX downto ICU_MIN do
begin
str(i, v);
icudata := dlopen(pointer('libicudata.so.' + v), RTLD_LAZY);
if icudata <> nil then
begin
Version := v;
break;
end;
end;
if icudata <> nil then
so := '.' + Version;
end;
{$endif OSANDROID}
if icudata <> nil then
begin
icu := dlopen(pointer('libicuuc.so' + so), RTLD_LAZY);
if icu <> nil then
icui18n := dlopen(pointer('libicui18n.so' + so), RTLD_LAZY);
end;
{$endif OSDARWIN}
if icui18n = nil then
begin
// we did not find any ICU installed -> ensure iconv/RTL fallback is ok
if not IsWideStringManagerProperlyInstalled then
DisplayFatalError('ICU ' + CPU_ARCH_TEXT + ' is not available',
'Either install it or put cwstring in your uses clause as fallback');
Done;
exit;
end
end;
// ICU append a version prefix to all its functions e.g. ucnv_open_66
if (Version <> '') and
(dlsym(icu, pointer('ucnv_open_' + Version)) <> nil) then
vers := '_' + Version // matched the explicit version
else
begin
{$ifdef OSANDROID}
for i := high(ICU_VER) downto 1 do
begin
if dlsym(icu, pointer(NAMES[0] + ICU_VER[i])) <> nil then
begin
vers := ICU_VER[i];
break;
end;
end;
if vers <> '' then
{$endif OSANDROID}
if dlsym(icu, 'ucnv_open') = nil then
for i := ICU_MAX downto ICU_MIN do
begin
str(i, v);
if dlsym(icu, pointer('ucnv_open_' + v)) <> nil then
begin
vers := '_' + v;
break;
end;
end;
end;
P := @@ucnv_open;
for i := 0 to high(NAMES) do
begin
P[i] := dlsym(icu, pointer(NAMES[i] + vers));
if P[i] = nil then
begin
@ucnv_open := nil;
exit;
end;
end;
data := u_getDataDirectory;
if (data = nil) or
(data^ = #0) then
if SYSDATA <> '' then
u_setDataDirectory(SYSDATA);
err := 0;
u_init(err);
finally
GlobalUnLock;
end;
end;
function TIcuLibrary.ForceLoad(const LibName: TFileName; const Version: string): boolean;
begin
Done;
Loaded := false;
DoLoad(LibName, Version);
result := Assigned(ucnv_open);
end;
function TIcuLibrary.ucnv(codepage: cardinal): pointer;
var
s: ShortString;
err: SizeInt;
{$ifdef CPUINTEL}
mask: cardinal;
{$endif CPUINTEL}
begin
if not IsAvailable then
exit(nil);
str(codepage, s);
MoveFast(s[1], s[3], ord(s[0]));
PWord(@s[1])^ := ord('c') + ord('p') shl 8;
inc(s[0], 3);
s[ord(s[0])] := #0;
{$ifdef CPUINTEL}
mask := GetMXCSR;
SetMXCSR(mask or $0080 {MM_MaskInvalidOp} or $1000 {MM_MaskPrecision});
{$endif CPUINTEL}
err := 0;
result := ucnv_open(@s[1], err);
if result <> nil then
begin
err := 0;
ucnv_setSubstChars(result, '?', 1, err);
ucnv_setFallback(result, true);
end;
{$ifdef CPUINTEL}
SetMXCSR(mask);
{$endif CPUINTEL}
end;
const
// for CompareStringW()
LOCALE_USER_DEFAULT = $400;
NORM_IGNORECASE = 1 shl ord(coIgnoreCase); // [widestringmanager.coIgnoreCase]
function CompareStringRTL(A, B: PWideChar; AL, BL, flags: integer): integer;
var
U1, U2: UnicodeString; // allocate two temporary strings
begin
// cwstring as fallback, using iconv on systems where ICU is not available
SetString(U1, A, AL);
SetString(U2, B, BL);
result := widestringmanager.CompareUnicodeStringProc(
U1, U2, TCompareOptions(flags));
end;
function CompareStringW(locale, flags: DWORD;
A: PWideChar; AL: integer; B: PWideChar; BL: integer): PtrInt;
const
CODE_POINT_ORDER = $8000;
var
err: SizeInt;
begin
if AL < 0 then
AL := StrLenW(A);
if BL < 0 then
BL := StrLenW(B);
err := 0;
if icu.IsAvailable then
if flags and NORM_IGNORECASE <> 0 then
result := icu.u_strCaseCompare(A, AL, B, BL, CODE_POINT_ORDER, err)
else
result := icu.u_strCompare(A, AL, B, BL, true)
else
result := CompareStringRTL(A, B, AL, BL, flags);
inc(result, 2); // caller would make -2 to get regular -1/0/1 comparison values
end;
function AnsiToWideRTL(CodePage: cardinal; A: PAnsiChar; W: PWideChar;
AL, WL: PtrInt): PtrInt;
var
tmp: UnicodeString;
begin
// cwstring as fallback, using iconv on systems where ICU is not available
widestringmanager.Ansi2UnicodeMoveProc(A, CodePage, tmp, AL);
result := length(tmp);
if result > WL then
result := WL;
MoveFast(pointer(tmp)^, W^, result * 2);
end;
function Unicode_AnsiToWide(A: PAnsiChar; W: PWideChar;
LA, LW, CodePage: PtrInt): integer;
var
cnv: pointer;
err: SizeInt;
begin
if CodePage = CP_UTF8 then
exit(Utf8ToUnicode(W, A, LA));
cnv := icu.ucnv(CodePage);
if cnv = nil then
exit(AnsiToWideRTL(CodePage, A, W, LA, LW)); // fallback to cwstring/iconv
err := 0;
result := icu.ucnv_toUChars(cnv, W, LW, A, LA, err);
if result < 0 then
result := 0;
icu.ucnv_close(cnv);
end;
function WideToAnsiRTL(CodePage: cardinal; W: PWideChar; A: PAnsiChar;
WL, AL: PtrInt): PtrInt;
var
tmp: RawByteString;
begin
// cwstring as fallback, using iconv on systems where ICU is not available
widestringmanager.Unicode2AnsiMoveProc(W, tmp, CodePage, WL);
result := length(tmp);
if result > AL then
result := AL;
MoveFast(pointer(tmp)^, A^, result);
end;
function Unicode_WideToAnsi(W: PWideChar; A: PAnsiChar;
LW, LA, CodePage: PtrInt): integer;
var
cnv: pointer;
err: SizeInt;
begin
if CodePage = CP_UTF8 then
exit(UnicodeToUtf8(A, W, LW));
cnv := icu.ucnv(CodePage);
if cnv = nil then
exit(WideToAnsiRTL(CodePage, W, A, LW, LA)); // fallback to cwstring/iconv
err := 0;
result := icu.ucnv_fromUChars(cnv, A, LA, W, LW, err);
if result < 0 then
result := 0;
icu.ucnv_close(cnv);
end;
function Unicode_InPlaceUpper(W: PWideChar; WLen: integer): integer;
var
err, i: SizeInt;
begin
if icu.IsAvailable then
begin
// call the accurate ICU library
err := 0;
result := icu.u_strToUpper(W, WLen, W, WLen, nil, err);
end
else
begin
// simple fallback code only handling 'a'..'z' -> 'A'..'Z' basic conversion
for i := 0 to WLen - 1 do
if ord(W[i]) in [ord('a')..ord('z')] then
dec(W[i], 32);
result := WLen;
end;
end;
function Unicode_InPlaceLower(W: PWideChar; WLen: integer): integer;
var
err, i: SizeInt;
begin
if icu.IsAvailable then
begin
// call the accurate ICU library
err := 0;
result := icu.u_strToLower(W, WLen, W, WLen, nil, err);
end
else
begin
// simple fallback code only handling 'A'..'Z' -> 'a'..'z' basic conversion
for i := 0 to WLen - 1 do
if ord(W[i]) in [ord('A')..ord('Z')] then
inc(W[i], 32);
result := WLen;
end;
end;
function GetDesktopWindow: PtrInt;
begin
result := 0; // fixed result on a window-abstracted system
end;
{$ifdef NODIRECTTHREADMANAGER} // try to stabilize MacOS/BSD pthreads API calls
function GetCurrentThreadId: TThreadID;
begin
result := system.GetCurrentThreadID();
end;
function TryEnterCriticalSection(var cs: TRTLCriticalSection): integer;
begin
result := system.TryEnterCriticalSection(cs);
end;
procedure EnterCriticalSection(var cs: TRTLCriticalSection);
begin
system.EnterCriticalSection(cs);
end;
procedure LeaveCriticalSection(var cs: TRTLCriticalSection);
begin
system.LeaveCriticalSection(cs);
end;
{$endif NODIRECTTHREADMANAGER}
const // Date Translation - see http://en.wikipedia.org/wiki/Julian_day
HoursPerDay = 24;
MinsPerHour = 60;
SecsPerMin = 60;
MinsPerDay = HoursPerDay * MinsPerHour;
SecsPerDay = MinsPerDay * SecsPerMin;
SecsPerHour = MinsPerHour * SecsPerMin;
MilliSecsPerSec = 1000;
MicroSecsPerSec = 1000000;
MicroSecsPerMilliSec = 1000;
NanoSecsPerMicroSec = 1000;
NanoSecsPerMilliSec = 1000000;
C1970 = 2440588;
D0 = 1461;
D1 = 146097;
D2 = 1721119;
procedure JulianToGregorian(JulianDN: PtrUInt; out result: TSystemTime);
{$ifdef HASINLINE}inline;{$endif}
var
YYear, XYear, Temp, TempMonth: PtrUInt;
begin
Temp := ((JulianDN - D2) * 4) - 1;
JulianDN := Temp div D1;
XYear := (Temp - (JulianDN * D1)) or 3;
YYear := XYear div D0;
Temp := (((XYear - (YYear * D0) + 4) shr 2) * 5) - 3;
TempMonth := Temp div 153;
result.Day := ((Temp - (TempMonth * 153)) + 5) div 5;
if TempMonth >= 10 then
begin
inc(YYear);
dec(TempMonth, 12 - 3);
end
else
inc(TempMonth, 3);
result.Month := TempMonth;
result.Year := YYear + (JulianDN * 100);
// initialize fake dayOfWeek - as used by FromGlobalTime Rcu128
result.DayOfWeek := 0;
end;
procedure EpochToSystemTime(epoch: PtrUInt; out result: TSystemTime);
var
t: PtrUInt;
begin
t := epoch div SecsPerDay;
JulianToGregorian(t + C1970, result);
dec(epoch, t * SecsPerDay);
t := epoch div SecsPerHour;
result.Hour := t;
dec(epoch, t * SecsPerHour);
t := epoch div SecsPerMin;
result.Minute := t;
result.Second := epoch - t * SecsPerMin;
end;
{$ifdef OSDARWIN} // OSX has no clock_gettime() API
type
TTimebaseInfoData = record
Numer: cardinal;
Denom: cardinal;
end;
function mach_absolute_time: UInt64;
cdecl external clib name 'mach_absolute_time';
function mach_timebase_info(var TimebaseInfoData: TTimebaseInfoData): integer;
cdecl external clib name 'mach_timebase_info';
var
mach_timeinfo: TTimebaseInfoData;
mach_timecoeff: double;
mach_timenanosecond: boolean; // very likely to be TRUE on Intel CPUs
procedure QueryPerformanceNanosec(out Value: Int64);
begin
// Win32-API like function which returns time in nano second resolution
Value := mach_absolute_time;
if mach_timeinfo.Denom = 1 then
if mach_timeinfo.Numer = 1 then
// seems to be the case on Intel CPUs
exit
else
Value := Value * mach_timeinfo.Numer
else
// use floating point to avoid potential overflow
Value := round(Value * mach_timecoeff);
end;
procedure QueryPerformanceMicroSeconds(out Value: Int64);
begin
if mach_timenanosecond then
Value := mach_absolute_time
else
QueryPerformanceNanosec(Value);
Value := Value div NanoSecsPerMicroSec; // ns to us
end;
function GetTickCount64: Int64;
begin
if mach_timenanosecond then
result := mach_absolute_time
else
QueryPerformanceNanosec(result);
result := result div NanoSecsPerMilliSec; // ns to ms
end;
function UnixTimeUtc: TUnixTime;
var
tz: timeval;
begin
fpgettimeofday(@tz, nil); // from libc
result := tz.tv_sec;
end;
function UnixMSTimeUtc: TUnixMSTime;
var
tz: timeval;
begin
fpgettimeofday(@tz, nil);
result := (Int64(tz.tv_sec) * MilliSecsPerSec) +
tz.tv_usec div MicroSecsPerMilliSec; // in milliseconds
end;
procedure GetSystemTime(out result: TSystemTime);
var
tz: timeval;
begin
fpgettimeofday(@tz, nil);
EpochToSystemTime(tz.tv_sec, result);
result.MilliSecond := tz.tv_usec div MicroSecsPerMilliSec;
end;
{$else}
{$ifdef OSBSD}
const
// see https://github.com/freebsd/freebsd/blob/master/sys/sys/time.h
CLOCK_REALTIME = 0;
CLOCK_MONOTONIC = 4;
CLOCK_REALTIME_COARSE = 10; // named CLOCK_REALTIME_FAST in FreeBSD 8.1+
CLOCK_MONOTONIC_COARSE = 12;
function clock_gettime(clk_id: cardinal; tp: ptimespec): integer;
cdecl external clib name 'clock_gettime';
function clock_getres(clk_id: cardinal; tp: ptimespec): integer;
cdecl external clib name 'clock_getres';
{$else}
const
CLOCK_REALTIME = 0;
CLOCK_MONOTONIC = 1;
CLOCK_REALTIME_COARSE = 5; // see http://lwn.net/Articles/347811
CLOCK_MONOTONIC_COARSE = 6;
// libc's clock_gettime function uses vDSO (avoid syscall) while FPC by default
// is compiled without FPC_USE_LIBC defined and do a syscall each time
// GetTickCount64 fpc 2 494 563 op/sec
// GetTickCount64 libc 119 919 893 op/sec
function clock_gettime(clk_id: clockid_t; tp: ptimespec): cint;
cdecl external clib name 'clock_gettime'; // LIBC_SUFFIX fails on CentOS 7
function gettimeofday(tp: ptimeval; tzp: ptimezone): cint;
cdecl external clib name 'gettimeofday' + LIBC_SUFFIX;
{$endif OSBSD}
var
// contains CLOCK_REALTIME_COARSE since kernel 2.6.32
CLOCK_REALTIME_FAST: integer = CLOCK_REALTIME;
// contains CLOCK_MONOTONIC_COARSE since kernel 2.6.32
CLOCK_MONOTONIC_FAST: integer = CLOCK_MONOTONIC;
// contains CLOCK_MONOTONIC_RAW since kernel 2.6.28
// - so that QueryPerformanceMicroSeconds() is not subject to NTP adjustments
CLOCK_MONOTONIC_HIRES: integer = CLOCK_MONOTONIC;
function UnixMSTimeUtc: TUnixMSTime;
var
r: timespec;
begin
clock_gettime(CLOCK_REALTIME_FAST, @r); // likely = CLOCK_REALTIME_COARSE
// convert from nanoseconds into milliseconds
result := QWord(PtrUInt(r.tv_nsec) div PtrUInt(NanoSecsPerMilliSec)) +
QWord(r.tv_sec) * MilliSecsPerSec;
end;
function UnixTimeUtc: TUnixTime;
var
r: timespec;
begin
clock_gettime(CLOCK_REALTIME_FAST, @r);
result := r.tv_sec;
end;
procedure QueryPerformanceMicroSeconds(out Value: Int64);
var
r : TTimeSpec;
begin
clock_gettime(CLOCK_MONOTONIC_HIRES, @r);
// convert from nanoseconds into microseconds
Value := QWord(PtrUInt(r.tv_nsec) div PtrUInt(NanoSecsPerMicroSec)) +
QWord(r.tv_sec) * MicroSecsPerSec;
end;
procedure GetSystemTime(out result: TSystemTime);
var
r: timespec;
begin
// faster than fpgettimeofday() which makes a syscall and don't use vDSO
clock_gettime(CLOCK_REALTIME_FAST, @r);
EpochToSystemTime(r.tv_sec, result);
result.MilliSecond := PtrUInt(r.tv_nsec) div PtrUInt(NanoSecsPerMilliSec);
end;
function GetTickCount64: Int64;
var
tp: timespec;
begin
clock_gettime(CLOCK_MONOTONIC_FAST, @tp); // likely = CLOCK_MONOTONIC_COARSE
// convert from nanoseconds into milliseconds
result := QWord(PtrUInt(tp.tv_nsec) div PtrUInt(NanoSecsPerMilliSec)) +
QWord(tp.tv_sec) * MilliSecsPerSec;
end;
{$endif OSDARWIN}
function UnixMSTimeUtcFast: TUnixMSTime;
begin
result := UnixMSTimeUtc;
end;
{$undef OSPTHREADS}
{$undef HAS_PTHREADSETNAMENP}
{$undef HAS_PTHREADSETAFFINITY}
{$ifdef OSPTHREADSLIB}
{$define OSPTHREADS}
var
{$ifdef OSLINUX}
// pthread_setname_np for Linux https://stackoverflow.com/a/7989973/458259
{$define HAS_PTHREADSETNAMENP}
pthread_setname_np: function(thread: pointer; name: PAnsiChar): integer; cdecl;
// pthread_setaffinity_np has been tested on Linux only
{$define HAS_PTHREADSETAFFINITY}
pthread_setaffinity_np: function(thread: pointer;
cpusetsize: SizeUInt; cpuset: pointer): integer; cdecl;
{$endif OSLINUX}
pthread_cancel: function(thread: pointer): integer; cdecl;
pthread_mutex_init: function(mutex, attr: pointer): integer; cdecl;
pthread_mutex_destroy: function(mutex: pointer): integer; cdecl;
{$endif OSPTHREADSLIB}
{$ifdef OSPTHREADSSTATIC}
{$define OSPTHREADS}
// note: pthread_setname_np() has no single API across POSIX systems
function pthread_cancel(thread: pointer): integer;
cdecl external clib name 'pthread_cancel';
function pthread_mutex_init(mutex, attr: pointer): integer;
cdecl external clib name 'pthread_mutex_init';
function pthread_mutex_destroy(mutex: pointer): integer;
cdecl external clib name 'pthread_mutex_destroy';
function pthread_mutex_lock(mutex: pointer): integer;
cdecl external clib name 'pthread_mutex_lock';
function pthread_mutex_trylock(mutex: pointer): integer;
cdecl external clib name 'pthread_mutex_trylock';
function pthread_mutex_unlock(mutex: pointer): integer;
cdecl external clib name 'pthread_mutex_unlock';
{$endif OSPTHREADSSTATIC}
function IsInitializedCriticalSection(var cs: TRTLCriticalSection): boolean;
begin
{$ifdef OSLINUX}
result := cs.__m_kind <> 0;
{$else}
result := not IsZero(@cs, SizeOf(cs));
{$endif OSLINUX}
end;
{$ifdef OSPTHREADS}
{ TOSLightLock }
procedure TOSLightLock.Init;
begin
FillCharFast(fMutex, SizeOf(fMutex), 0); // may be bigger than pthread struct
{$ifdef OSPTHREADSLIB}
if not Assigned(pthread_mutex_init) then
EOSException.Create('TOSLightLock.Init: no pthread_mutex_init')
else // no recursive attribute -> fast mutex
{$endif OSPTHREADSLIB}
pthread_mutex_init(@fMutex, nil);
end;
procedure TOSLightLock.Done;
begin
if IsInitializedCriticalSection(fMutex) then
pthread_mutex_destroy(@fMutex);
end;
procedure TOSLightLock.Lock;
begin
pthread_mutex_lock(@fMutex);
end;
function TOSLightLock.TryLock: boolean;
begin
result := pthread_mutex_trylock(@fMutex) = 0;
end;
procedure TOSLightLock.UnLock;
begin
pthread_mutex_unlock(@fMutex);
end;
{$else} // fallback to plain recursive TRTLCriticalSection
{ TOSLightLock }
procedure TOSLightLock.Init;
begin
InitCriticalSection(fMutex);
end;
procedure TOSLightLock.Done;
begin
DeleteCriticalSectionIfNeeded(fMutex);
end;
procedure TOSLightLock.Lock;
begin
EnterCriticalSection(fMutex);
end;
function TOSLightLock.TryLock: boolean;
begin
result := TryEnterCriticalSection(fMutex) <> 0;
end;
procedure TOSLightLock.UnLock;
begin
LeaveCriticalSection(fMutex);
end;
{$endif OSPTHREADS}
procedure SetUnixThreadName(ThreadID: TThreadID; const Name: RawByteString);
var
// truncated to 16 non space chars (including #0)
{%H-}trunc: array[0..15] of AnsiChar;
i, L, c4: integer;
begin
if Name = '' then
exit;
L := 0; // trim unrelevant spaces and prefixes when filling the 16 chars
i := 1;
if Name[1] = 'T' then
begin
c4 := PCardinal(Name)^ and $dfdfdfdf;
if (c4 = ord('T') + ord('S') shl 8 + ord('Q') shl 16 + ord('L') shl 24) or
(c4 = ord('T') + ord('O') shl 8 + ord('R') shl 16 + ord('M') shl 24) then
i := 5
else
i := 2;
end;
while i <= length(Name) do
begin
if Name[i] > ' ' then
begin
trunc[L] := Name[i];
inc(L);
if L = high(trunc) then
break;
end;
inc(i);
end;
if L = 0 then
exit;
trunc[L] := #0;
{$ifdef HAS_PTHREADSETNAMENP} // see https://stackoverflow.com/a/7989973
{$ifdef OSPTHREADSLIB}
if Assigned(pthread_setname_np) then
try
pthread_setname_np(pointer(ThreadID), @trunc[0]);
except
// ignore any exception (pthread confusion with its static version?)
@pthread_setname_np := nil; // don't continue that way
end;
{$endif OSPTHREADSLIB}
{$endif HAS_PTHREADSETNAMENP}
end;
procedure RawSetThreadName(ThreadID: TThreadID; const Name: RawUtf8);
begin
if ThreadID <> MainThreadID then // don't change the main process name
SetUnixThreadName(ThreadID, Name); // call pthread_setname_np()
end;
function RawKillThread(Thread: TThread): boolean;
begin
result := false;
{$ifdef OSPTHREADSLIB}
if Assigned(pthread_cancel) then