-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathJclSysUtils.pas
4540 lines (4041 loc) · 132 KB
/
JclSysUtils.pas
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
{**************************************************************************************************}
{ }
{ Project JEDI Code Library (JCL) }
{ }
{ The contents of this file are subject to the Mozilla Public License Version 1.1 (the "License"); }
{ you may not use this file except in compliance with the License. You may obtain a copy of the }
{ License at http://www.mozilla.org/MPL/ }
{ }
{ Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF }
{ ANY KIND, either express or implied. See the License for the specific language governing rights }
{ and limitations under the License. }
{ }
{ The Original Code is JclSysUtils.pas. }
{ }
{ The Initial Developer of the Original Code is Marcel van Brakel. }
{ Portions created by Marcel van Brakel are Copyright (C) Marcel van Brakel. All rights reserved. }
{ }
{ Contributors: }
{ Alexander Radchenko, }
{ Andreas Hausladen (ahuser) }
{ Anthony Steele }
{ Bernhard Berger }
{ Heri Bender }
{ Jean-Fabien Connault (cycocrew) }
{ Jens Fudickar }
{ Jeroen Speldekamp }
{ Marcel van Brakel }
{ Peter Friese }
{ Petr Vones (pvones) }
{ Python }
{ Robert Marquardt (marquardt) }
{ Robert R. Marsh }
{ Robert Rossmair (rrossmair) }
{ Rudy Velthuis }
{ Uwe Schuster (uschuster) }
{ Wayne Sherman }
{ }
{**************************************************************************************************}
{ }
{ Description: Various pointer and class related routines. }
{ }
{**************************************************************************************************}
{ }
{ Last modified: $Date:: $ }
{ Revision: $Rev:: $ }
{ Author: $Author:: $ }
{ }
{**************************************************************************************************}
unit JclSysUtils;
{$I jcl.inc}
interface
uses
{$IFDEF UNITVERSIONING}
JclUnitVersioning,
{$ENDIF UNITVERSIONING}
{$IFDEF HAS_UNITSCOPE}
{$IFDEF MSWINDOWS}
Winapi.Windows,
{$ENDIF MSWINDOWS}
System.SysUtils, System.Classes, System.TypInfo, System.SyncObjs,
{$ELSE ~HAS_UNITSCOPE}
{$IFDEF MSWINDOWS}
Windows,
{$ENDIF MSWINDOWS}
SysUtils, Classes, TypInfo, SyncObjs,
{$ENDIF ~HAS_UNITSCOPE}
JclBase, JclSynch;
// memory initialization
// first parameter is "out" to make FPC happy with uninitialized values
procedure ResetMemory(out P; Size: Longint);
// Pointer manipulation
procedure GetAndFillMem(var P: Pointer; const Size: Integer; const Value: Byte);
procedure FreeMemAndNil(var P: Pointer);
function PCharOrNil(const S: string): PChar;
function PAnsiCharOrNil(const S: AnsiString): PAnsiChar;
{$IFDEF SUPPORTS_WIDESTRING}
function PWideCharOrNil(const W: WideString): PWideChar;
{$ENDIF SUPPORTS_WIDESTRING}
function SizeOfMem(const APointer: Pointer): Integer;
function WriteProtectedMemory(BaseAddress, Buffer: Pointer; Size: Cardinal;
out WrittenBytes: Cardinal): Boolean;
// Guards
type
ISafeGuard = interface
function ReleaseItem: Pointer;
function GetItem: Pointer;
procedure FreeItem;
property Item: Pointer read GetItem;
end;
IMultiSafeGuard = interface (IInterface)
function AddItem(Item: Pointer): Pointer;
procedure FreeItem(Index: Integer);
function GetCount: Integer;
function GetItem(Index: Integer): Pointer;
function ReleaseItem(Index: Integer): Pointer;
property Count: Integer read GetCount;
property Items[Index: Integer]: Pointer read GetItem;
end;
TJclSafeGuard = class(TInterfacedObject, ISafeGuard)
private
FItem: Pointer;
public
constructor Create(Mem: Pointer);
destructor Destroy; override;
{ ISafeGuard }
function ReleaseItem: Pointer;
function GetItem: Pointer;
procedure FreeItem; virtual;
property Item: Pointer read GetItem;
end;
TJclObjSafeGuard = class(TJclSafeGuard, ISafeGuard)
public
constructor Create(Obj: TObject);
{ ISafeGuard }
procedure FreeItem; override;
end;
TJclMultiSafeGuard = class(TInterfacedObject, IMultiSafeGuard)
private
FItems: TList;
public
constructor Create;
destructor Destroy; override;
{ IMultiSafeGuard }
function AddItem(Item: Pointer): Pointer;
procedure FreeItem(Index: Integer); virtual;
function GetCount: Integer;
function GetItem(Index: Integer): Pointer;
function ReleaseItem(Index: Integer): Pointer;
property Count: Integer read GetCount;
property Items[Index: Integer]: Pointer read GetItem;
end;
TJclObjMultiSafeGuard = class(TJclMultiSafeGuard, IMultiSafeGuard)
public
{ IMultiSafeGuard }
procedure FreeItem(Index: Integer); override;
end;
function Guard(Mem: Pointer; out SafeGuard: ISafeGuard): Pointer; overload;
function Guard(Obj: TObject; out SafeGuard: ISafeGuard): TObject; overload;
function Guard(Mem: Pointer; var SafeGuard: IMultiSafeGuard): Pointer; overload;
function Guard(Obj: TObject; var SafeGuard: IMultiSafeGuard): TObject; overload;
function GuardGetMem(Size: Cardinal; out SafeGuard: ISafeGuard): Pointer;
function GuardAllocMem(Size: Cardinal; out SafeGuard: ISafeGuard): Pointer;
(*
{$IFDEF SUPPORTS_GENERICS}
type
ISafeGuard<T: class> = interface
function ReleaseItem: T;
function GetItem: T;
procedure FreeItem;
property Item: T read GetItem;
end;
TSafeGuard<T: class> = class(TObject, ISafeGuard<T>)
private
FItem: T;
function ReleaseItem: T;
function GetItem: T;
procedure FreeItem;
constructor Create(Instance: T);
destructor Destroy; override;
public
class function New(Instance: T): ISafeGuard<T>; static;
end;
{$ENDIF SUPPORTS_GENERICS}
*)
{ Shared memory between processes functions }
// Functions for the shared memory owner
type
ESharedMemError = class(EJclError);
{$IFDEF MSWINDOWS}
{ SharedGetMem return ERROR_ALREADY_EXISTS if the shared memory is already
allocated, otherwise it returns 0.
Throws ESharedMemError if the Name is invalid. }
function SharedGetMem(var P{: Pointer}; const Name: string; Size: Cardinal;
DesiredAccess: Cardinal = FILE_MAP_ALL_ACCESS): Integer;
{ SharedAllocMem calls SharedGetMem and then fills the memory with zero if
it was not already allocated.
Throws ESharedMemError if the Name is invalid. }
function SharedAllocMem(const Name: string; Size: Cardinal;
DesiredAccess: Cardinal = FILE_MAP_ALL_ACCESS): Pointer;
{ SharedFreeMem releases the shared memory if it was the last reference. }
function SharedFreeMem(var P{: Pointer}): Boolean;
// Functions for the shared memory user
{ SharedOpenMem returns True if the shared memory was already allocated by
SharedGetMem or SharedAllocMem. Otherwise it returns False.
Throws ESharedMemError if the Name is invalid. }
function SharedOpenMem(var P{: Pointer}; const Name: string;
DesiredAccess: Cardinal = FILE_MAP_ALL_ACCESS): Boolean; overload;
{ SharedOpenMem return nil if the shared memory was not already allocated
by SharedGetMem or SharedAllocMem.
Throws ESharedMemError if the Name is invalid. }
function SharedOpenMem(const Name: string;
DesiredAccess: Cardinal = FILE_MAP_ALL_ACCESS): Pointer; overload;
{ SharedCloseMem releases the shared memory if it was the last reference. }
function SharedCloseMem(var P{: Pointer}): Boolean;
{$ENDIF MSWINDOWS}
// Binary search
function SearchSortedList(List: TList; SortFunc: TListSortCompare; Item: Pointer;
Nearest: Boolean = False): Integer;
type
TUntypedSearchCompare = function(Param: Pointer; ItemIndex: Integer; const Value): Integer;
function SearchSortedUntyped(Param: Pointer; ItemCount: Integer; SearchFunc: TUntypedSearchCompare;
const Value; Nearest: Boolean = False): Integer;
// Dynamic array sort and search routines
type
TDynArraySortCompare = function (Item1, Item2: Pointer): Integer;
procedure SortDynArray(const ArrayPtr: Pointer; ElementSize: Cardinal; SortFunc: TDynArraySortCompare);
// Usage: SortDynArray(Array, SizeOf(Array[0]), SortFunction);
function SearchDynArray(const ArrayPtr: Pointer; ElementSize: Cardinal; SortFunc: TDynArraySortCompare;
ValuePtr: Pointer; Nearest: Boolean = False): SizeInt;
// Usage: SearchDynArray(Array, SizeOf(Array[0]), SortFunction, @SearchedValue);
{ Various compare functions for basic types }
function DynArrayCompareByte(Item1, Item2: Pointer): Integer;
function DynArrayCompareShortInt(Item1, Item2: Pointer): Integer;
function DynArrayCompareWord(Item1, Item2: Pointer): Integer;
function DynArrayCompareSmallInt(Item1, Item2: Pointer): Integer;
function DynArrayCompareInteger(Item1, Item2: Pointer): Integer;
function DynArrayCompareCardinal(Item1, Item2: Pointer): Integer;
function DynArrayCompareInt64(Item1, Item2: Pointer): Integer;
function DynArrayCompareSingle(Item1, Item2: Pointer): Integer;
function DynArrayCompareDouble(Item1, Item2: Pointer): Integer;
function DynArrayCompareExtended(Item1, Item2: Pointer): Integer;
function DynArrayCompareFloat(Item1, Item2: Pointer): Integer;
function DynArrayCompareAnsiString(Item1, Item2: Pointer): Integer;
function DynArrayCompareAnsiText(Item1, Item2: Pointer): Integer;
function DynArrayCompareWideString(Item1, Item2: Pointer): Integer;
function DynArrayCompareWideText(Item1, Item2: Pointer): Integer;
function DynArrayCompareString(Item1, Item2: Pointer): Integer;
function DynArrayCompareText(Item1, Item2: Pointer): Integer;
// Object lists
procedure ClearObjectList(List: TList);
procedure FreeObjectList(var List: TList);
// Reference memory stream
type
TJclReferenceMemoryStream = class(TCustomMemoryStream)
public
constructor Create(const Ptr: Pointer; Size: Longint);
function Write(const Buffer; Count: Longint): Longint; override;
end;
// AutoPtr
type
IAutoPtr = interface
{ Returns the object as pointer, so it is easier to assign it to a variable }
function AsPointer: Pointer;
{ Returns the AutoPtr handled object }
function AsObject: TObject;
{ Releases the object from the AutoPtr. The AutoPtr looses the control over
the object. }
function ReleaseObject: TObject;
end;
TJclAutoPtr = class(TInterfacedObject, IAutoPtr)
private
FValue: TObject;
public
constructor Create(AValue: TObject);
destructor Destroy; override;
{ IAutoPtr }
function AsPointer: Pointer;
function AsObject: TObject;
function ReleaseObject: TObject;
end;
function CreateAutoPtr(Value: TObject): IAutoPtr;
// Replacement for the C ternary conditional operator ? :
function Iff(const Condition: Boolean; const TruePart, FalsePart: string): string; overload;
function Iff(const Condition: Boolean; const TruePart, FalsePart: Char): Char; overload;
function Iff(const Condition: Boolean; const TruePart, FalsePart: Byte): Byte; overload;
function Iff(const Condition: Boolean; const TruePart, FalsePart: Integer): Integer; overload;
function Iff(const Condition: Boolean; const TruePart, FalsePart: Cardinal): Cardinal; overload;
function Iff(const Condition: Boolean; const TruePart, FalsePart: Float): Float; overload;
function Iff(const Condition: Boolean; const TruePart, FalsePart: Boolean): Boolean; overload;
function Iff(const Condition: Boolean; const TruePart, FalsePart: Pointer): Pointer; overload;
function Iff(const Condition: Boolean; const TruePart, FalsePart: Int64): Int64; overload;
{$IFDEF SUPPORTS_VARIANT}
function Iff(const Condition: Boolean; const TruePart, FalsePart: Variant): Variant; overload;
{$ENDIF SUPPORTS_VARIANT}
// Classes information and manipulation
type
EJclVMTError = class(EJclError);
// Virtual Methods
{$IFNDEF FPC}
function GetVirtualMethodCount(AClass: TClass): Integer;
{$ENDIF ~FPC}
function GetVirtualMethod(AClass: TClass; const Index: Integer): Pointer;
procedure SetVirtualMethod(AClass: TClass; const Index: Integer; const Method: Pointer);
// Dynamic Methods
type
TDynamicIndexList = array [0..MaxInt div 16] of Word;
PDynamicIndexList = ^TDynamicIndexList;
TDynamicAddressList = array [0..MaxInt div 16] of Pointer;
PDynamicAddressList = ^TDynamicAddressList;
function GetDynamicMethodCount(AClass: TClass): Integer;
function GetDynamicIndexList(AClass: TClass): PDynamicIndexList;
function GetDynamicAddressList(AClass: TClass): PDynamicAddressList;
function HasDynamicMethod(AClass: TClass; Index: Integer): Boolean;
{$IFNDEF FPC}
function GetDynamicMethod(AClass: TClass; Index: Integer): Pointer;
{$ENDIF ~FPC}
{ init table methods }
function GetInitTable(AClass: TClass): PTypeInfo;
{ field table methods }
type
PFieldEntry = ^TFieldEntry;
TFieldEntry = packed record
OffSet: Integer;
IDX: Word;
Name: ShortString;
end;
PFieldClassTable = ^TFieldClassTable;
TFieldClassTable = packed record
Count: Smallint;
Classes: array [0..8191] of ^TPersistentClass;
end;
PFieldTable = ^TFieldTable;
TFieldTable = packed record
EntryCount: Word;
FieldClassTable: PFieldClassTable;
FirstEntry: TFieldEntry;
{Entries: array [1..65534] of TFieldEntry;}
end;
function GetFieldTable(AClass: TClass): PFieldTable;
{ method table }
type
PMethodEntry = ^TMethodEntry;
TMethodEntry = packed record
EntrySize: Word;
Address: Pointer;
Name: ShortString;
end;
PMethodTable = ^TMethodTable;
TMethodTable = packed record
Count: Word;
FirstEntry: TMethodEntry;
{Entries: array [1..65534] of TMethodEntry;}
end;
function GetMethodTable(AClass: TClass): PMethodTable;
function GetMethodEntry(MethodTable: PMethodTable; Index: Integer): PMethodEntry;
// Function to compare if two methods/event handlers are equal
function MethodEquals(aMethod1, aMethod2: TMethod): boolean;
function NotifyEventEquals(aMethod1, aMethod2: TNotifyEvent): boolean;
// Class Parent
procedure SetClassParent(AClass: TClass; NewClassParent: TClass);
function GetClassParent(AClass: TClass): TClass;
{$IFNDEF FPC}
function IsClass(Address: Pointer): Boolean;
function IsObject(Address: Pointer): Boolean;
{$ENDIF ~FPC}
function InheritsFromByName(AClass: TClass; const AClassName: string): Boolean;
// Interface information
function GetImplementorOfInterface(const I: IInterface): TObject;
// interfaced persistent
type
TJclInterfacedPersistent = class(TInterfacedPersistent, IInterface)
protected
FOwnerInterface: IInterface;
FRefCount: Integer;
public
procedure AfterConstruction; override;
{ IInterface }
// function QueryInterface(const IID: TGUID; out Obj): HRESULT; virtual; stdcall;
function _AddRef: Integer; stdcall;
function _Release: Integer; stdcall;
end;
// Numeric formatting routines
type
TDigitCount = 0..255;
TDigitValue = -1..35; // invalid, '0'..'9', 'A'..'Z'
TNumericSystemBase = 2..Succ(High(TDigitValue));
TJclNumericFormat = class(TObject)
private
FWantedPrecision: TDigitCount;
FPrecision: TDigitCount;
FNumberOfFractionalDigits: TDigitCount;
FExpDivision: Integer;
FDigitBlockSize: TDigitCount;
FWidth: TDigitCount;
FSignChars: array [Boolean] of Char;
FBase: TNumericSystemBase;
FFractionalPartSeparator: Char;
FDigitBlockSeparator: Char;
FShowPositiveSign: Boolean;
FPaddingChar: Char;
FMultiplier: string;
function GetDigitValue(Digit: Char): Integer;
function GetNegativeSign: Char;
function GetPositiveSign: Char;
procedure InvalidDigit(Digit: Char);
procedure SetPrecision(const Value: TDigitCount);
procedure SetBase(const Value: TNumericSystemBase);
procedure SetNegativeSign(const Value: Char);
procedure SetPositiveSign(const Value: Char);
procedure SetExpDivision(const Value: Integer);
protected
function IntToStr(const Value: Int64; out FirstDigitPos: Integer): string; overload;
function ShowSign(const Value: Float): Boolean; overload;
function ShowSign(const Value: Int64): Boolean; overload;
function SignChar(const Value: Float): Char; overload;
function SignChar(const Value: Int64): Char; overload;
property WantedPrecision: TDigitCount read FWantedPrecision;
public
constructor Create;
function Digit(DigitValue: TDigitValue): Char;
function DigitValue(Digit: Char): TDigitValue;
function IsDigit(Value: Char): Boolean;
function Sign(Value: Char): Integer;
procedure GetMantissaExp(const Value: Float; out Mantissa: string; out Exponent: Integer);
function FloatToHTML(const Value: Float): string;
function IntToStr(const Value: Int64): string; overload;
function FloatToStr(const Value: Float): string; overload;
function StrToInt(const Value: string): Int64;
property Base: TNumericSystemBase read FBase write SetBase;
property Precision: TDigitCount read FPrecision write SetPrecision;
property NumberOfFractionalDigits: TDigitCount read FNumberOfFractionalDigits write FNumberOfFractionalDigits;
property ExponentDivision: Integer read FExpDivision write SetExpDivision;
property DigitBlockSize: TDigitCount read FDigitBlockSize write FDigitBlockSize;
property DigitBlockSeparator: Char read FDigitBlockSeparator write FDigitBlockSeparator;
property FractionalPartSeparator: Char read FFractionalPartSeparator write FFractionalPartSeparator;
property Multiplier: string read FMultiplier write FMultiplier;
property PaddingChar: Char read FPaddingChar write FPaddingChar;
property ShowPositiveSign: Boolean read FShowPositiveSign write FShowPositiveSign;
property Width: TDigitCount read FWidth write FWidth;
property NegativeSign: Char read GetNegativeSign write SetNegativeSign;
property PositiveSign: Char read GetPositiveSign write SetPositiveSign;
end;
function IntToStrZeroPad(Value, Count: Integer): string;
// Child processes
type
// e.g. TStrings.Append
TTextHandler = procedure(const Text: string) of object;
TJclProcessPriority = (ppIdle, ppNormal, ppHigh, ppRealTime, ppBelowNormal, ppAboveNormal);
const
ABORT_EXIT_CODE = {$IFDEF MSWINDOWS} ERROR_CANCELLED {$ELSE} 1223 {$ENDIF};
function Execute(const CommandLine: string; OutputLineCallback: TTextHandler; RawOutput: Boolean = False;
AbortPtr: PBoolean = nil; ProcessPriority: TJclProcessPriority = ppNormal;
AutoConvertOem: Boolean = False): Cardinal; overload;
function Execute(const CommandLine: string; AbortEvent: TJclEvent;
OutputLineCallback: TTextHandler; RawOutput: Boolean = False; ProcessPriority: TJclProcessPriority = ppNormal;
AutoConvertOem: Boolean = False): Cardinal; overload;
function Execute(const CommandLine: string; var Output: string; RawOutput: Boolean = False;
AbortPtr: PBoolean = nil; ProcessPriority: TJclProcessPriority = ppNormal;
AutoConvertOem: Boolean = False): Cardinal; overload;
function Execute(const CommandLine: string; AbortEvent: TJclEvent;
var Output: string; RawOutput: Boolean = False; ProcessPriority: TJclProcessPriority = ppNormal;
AutoConvertOem: Boolean = False): Cardinal; overload;
function Execute(const CommandLine: string; OutputLineCallback, ErrorLineCallback: TTextHandler;
RawOutput: Boolean = False; RawError: Boolean = False; AbortPtr: PBoolean = nil;
ProcessPriority: TJclProcessPriority = ppNormal; AutoConvertOem: Boolean = False): Cardinal; overload;
function Execute(const CommandLine: string; AbortEvent: TJclEvent;
OutputLineCallback, ErrorLineCallback: TTextHandler; RawOutput: Boolean = False; RawError: Boolean = False;
ProcessPriority: TJclProcessPriority = ppNormal; AutoConvertOem: Boolean = False): Cardinal; overload;
function Execute(const CommandLine: string; var Output, Error: string;
RawOutput: Boolean = False; RawError: Boolean = False; AbortPtr: PBoolean = nil;
ProcessPriority: TJclProcessPriority = ppNormal; AutoConvertOem: Boolean = False): Cardinal; overload;
function Execute(const CommandLine: string; AbortEvent: TJclEvent;
var Output, Error: string; RawOutput: Boolean = False; RawError: Boolean = False;
ProcessPriority: TJclProcessPriority = ppNormal; AutoConvertOem: Boolean = False): Cardinal; overload;
type
{$IFDEF MSWINDOWS}
TJclExecuteCmdProcessOptionBeforeResumeEvent = procedure(const ProcessInfo: TProcessInformation) of object;
TStartupVisibility = (svHide, svShow, svNotSet);
{$ENDIF MSWINDOWS}
TJclExecuteCmdProcessOptions = {record} class(TObject)
private
FCommandLine: string;
FAbortPtr: PBoolean;
FAbortEvent: TJclEvent;
FOutputLineCallback: TTextHandler;
FRawOutput: Boolean;
FMergeError: Boolean;
FErrorLineCallback: TTextHandler;
FRawError: Boolean;
FProcessPriority: TJclProcessPriority;
FAutoConvertOem: Boolean;
{$IFDEF MSWINDOWS}
FCreateProcessFlags: DWORD;
FStartupVisibility: TStartupVisibility;
FBeforeResume: TJclExecuteCmdProcessOptionBeforeResumeEvent;
{$ENDIF MSWINDOWS}
FExitCode: Cardinal;
FOutput: string;
FError: string;
public
// in:
property CommandLine: string read FCommandLine write FCommandLine;
property AbortPtr: PBoolean read FAbortPtr write FAbortPtr;
property AbortEvent: TJclEvent read FAbortEvent write FAbortEvent;
property OutputLineCallback: TTextHandler read FOutputLineCallback write FOutputLineCallback;
property RawOutput: Boolean read FRawOutput write FRawOutput default False;
property MergeError: Boolean read FMergeError write FMergeError default False;
property ErrorLineCallback: TTextHandler read FErrorLineCallback write FErrorLineCallback;
property RawError: Boolean read FRawError write FRawError default False;
property ProcessPriority: TJclProcessPriority read FProcessPriority write FProcessPriority default ppNormal;
// AutoConvertOem assumes the process outputs OEM encoded strings and converts them to the
// default string encoding.
property AutoConvertOem: Boolean read FAutoConvertOem write FAutoConvertOem default True;
{$IFDEF MSWINDOWS}
property CreateProcessFlags: DWORD read FCreateProcessFlags write FCreateProcessFlags;
property StartupVisibility: TStartupVisibility read FStartupVisibility write FStartupVisibility;
property BeforeResume: TJclExecuteCmdProcessOptionBeforeResumeEvent read FBeforeResume write FBeforeResume;
{$ENDIF MSWINDOWS}
// out:
property ExitCode: Cardinal read FExitCode;
property Output: string read FOutput;
property Error: string read FError;
public
constructor Create(const ACommandLine: string);
end;
function ExecuteCmdProcess(Options: TJclExecuteCmdProcessOptions): Boolean;
type
{$HPPEMIT 'namespace Jclsysutils'}
{$HPPEMIT '{'}
{$HPPEMIT ' // For some reason, the generator puts this interface after its first'}
{$HPPEMIT ' // usage, resulting in an unusable header file. We fix this by forward'}
{$HPPEMIT ' // declaring the interface.'}
{$HPPEMIT ' __interface IJclCommandLineTool;'}
(*$HPPEMIT '}'*)
IJclCommandLineTool = interface
['{A0034B09-A074-D811-847D-0030849E4592}']
function GetExeName: string;
function GetOptions: TStrings;
function GetOutput: string;
function GetOutputCallback: TTextHandler;
procedure AddPathOption(const Option, Path: string);
function Execute(const CommandLine: string): Boolean;
procedure SetOutputCallback(const CallbackMethod: TTextHandler);
property ExeName: string read GetExeName;
property Options: TStrings read GetOptions;
property OutputCallback: TTextHandler read GetOutputCallback write SetOutputCallback;
property Output: string read GetOutput;
end;
EJclCommandLineToolError = class(EJclError);
TJclCommandLineTool = class(TInterfacedObject, IJclCommandLineTool)
private
FExeName: string;
FOptions: TStringList;
FOutput: string;
FOutputCallback: TTextHandler;
public
constructor Create(const AExeName: string);
destructor Destroy; override;
{ IJclCommandLineTool }
function GetExeName: string;
function GetOptions: TStrings;
function GetOutput: string;
function GetOutputCallback: TTextHandler;
procedure AddPathOption(const Option, Path: string);
function Execute(const CommandLine: string): Boolean;
procedure SetOutputCallback(const CallbackMethod: TTextHandler);
property ExeName: string read GetExeName;
property Options: TStrings read GetOptions;
property OutputCallback: TTextHandler read GetOutputCallback write SetOutputCallback;
property Output: string read GetOutput;
end;
// Console Utilities
function ReadKey: Char;
// Loading of modules (DLLs)
type
{$IFDEF MSWINDOWS}
TModuleHandle = HINST;
{$ENDIF MSWINDOWS}
{$IFDEF LINUX}
TModuleHandle = Pointer;
{$ENDIF LINUX}
const
INVALID_MODULEHANDLE_VALUE = TModuleHandle(0);
function LoadModule(var Module: TModuleHandle; FileName: string): Boolean;
function LoadModuleEx(var Module: TModuleHandle; FileName: string; Flags: Cardinal): Boolean;
procedure UnloadModule(var Module: TModuleHandle);
function GetModuleSymbol(Module: TModuleHandle; SymbolName: string): Pointer;
function GetModuleSymbolEx(Module: TModuleHandle; SymbolName: string; var Accu: Boolean): Pointer;
function ReadModuleData(Module: TModuleHandle; SymbolName: string; var Buffer; Size: Cardinal): Boolean;
function WriteModuleData(Module: TModuleHandle; SymbolName: string; var Buffer; Size: Cardinal): Boolean;
// Conversion Utilities
type
EJclConversionError = class(EJclError);
function StrToBoolean(const S: string): Boolean;
function BooleanToStr(B: Boolean): string;
function IntToBool(I: Integer): Boolean;
function BoolToInt(B: Boolean): Integer;
function TryStrToUInt(const Value: string; out Res: Cardinal): Boolean;
function StrToUIntDef(const Value: string; const Default: Cardinal): Cardinal;
function StrToUInt(const Value: string): Cardinal;
const
{$IFDEF MSWINDOWS}
ListSeparator = ';';
{$ENDIF MSWINDOWS}
{$IFDEF LINUX}
ListSeparator = ':';
{$ENDIF LINUX}
// functions to handle items in a separated list of items
// add items at the end
procedure ListAddItems(var List: string; const Separator, Items: string);
// add items at the end if they are not present
procedure ListIncludeItems(var List: string; const Separator, Items: string);
// delete multiple items
procedure ListRemoveItems(var List: string; const Separator, Items: string);
// delete one item
procedure ListDelItem(var List: string; const Separator: string;
const Index: Integer);
// return the number of item
function ListItemCount(const List, Separator: string): Integer;
// return the Nth item
function ListGetItem(const List, Separator: string;
const Index: Integer): string;
// set the Nth item
procedure ListSetItem(var List: string; const Separator: string;
const Index: Integer; const Value: string);
// return the index of an item
function ListItemIndex(const List, Separator, Item: string): Integer;
// RTL package information
function SystemTObjectInstance: TJclAddr;
function IsCompiledWithPackages: Boolean;
// GUID
function JclGUIDToString(const GUID: TGUID): string;
function JclStringToGUID(const S: string): TGUID;
function GUIDEquals(const GUID1, GUID2: TGUID): Boolean;
// thread safe support
type
TJclIntfCriticalSection = class(TInterfacedObject, IInterface)
private
FCriticalSection: TCriticalSection;
public
constructor Create;
destructor Destroy; override;
{ IInterface }
// function QueryInterface(const IID: TGUID; out Obj): HRESULT; stdcall;
function _AddRef: Integer; stdcall;
function _Release: Integer; stdcall;
end;
type
{$IFDEF BORLAND}
{$IFDEF COMPILER16_UP}
TFileHandle = THandle;
{$ELSE ~COMPILER16_UP}
TFileHandle = Integer;
{$ENDIF ~COMPILER16_UP}
{$ELSE ~BORLAND}
TFileHandle = THandle;
{$ENDIF ~BORLAND}
TJclSimpleLog = class (TObject)
private
FDateTimeFormatStr: String;
FLogFileHandle: TFileHandle;
FLogFileName: string;
FLoggingActive: Boolean;
FLogWasEmpty: Boolean;
function GetLogOpen: Boolean;
protected
function CreateDefaultFileName: string;
public
constructor Create(const ALogFileName: string = '');
destructor Destroy; override;
procedure ClearLog;
procedure CloseLog;
procedure OpenLog;
procedure Write(const Text: string; Indent: Integer = 0; KeepOpen: Boolean = true); overload;
procedure Write(Strings: TStrings; Indent: Integer = 0; KeepOpen: Boolean = true); overload;
//Writes a line to the log file. The current timestamp is written before the line.
procedure TimeWrite(const Text: string; Indent: Integer = 0; KeepOpen: Boolean = true); overload;
procedure TimeWrite(Strings: TStrings; Indent: Integer = 0; KeepOpen: Boolean = true); overload;
procedure WriteStamp(SeparatorLen: Integer = 0; KeepOpen: Boolean = true);
// DateTimeFormatStr property assumes the values described in "FormatDateTime Function" in Delphi Help
property DateTimeFormatStr: String read FDateTimeFormatStr write FDateTimeFormatStr;
property LogFileName: string read FLogFileName;
//1 Property to activate / deactivate the logging
property LoggingActive: Boolean read FLoggingActive write FLoggingActive default True;
property LogOpen: Boolean read GetLogOpen;
end;
type
TJclFormatSettings = class
private
function GetCurrencyDecimals: Byte; {$IFDEF SUPPORTS_INLINE} inline; {$ENDIF}
function GetCurrencyFormat: Byte; {$IFDEF SUPPORTS_INLINE} inline; {$ENDIF}
function GetCurrencyString: string; {$IFDEF SUPPORTS_INLINE} inline; {$ENDIF}
function GetDateSeparator: Char; {$IFDEF SUPPORTS_INLINE} inline; {$ENDIF}
function GetDayNamesHighIndex: Integer; {$IFDEF SUPPORTS_INLINE} inline; {$ENDIF}
function GetDayNamesLowIndex: Integer; {$IFDEF SUPPORTS_INLINE} inline; {$ENDIF}
function GetDecimalSeparator: Char; {$IFDEF SUPPORTS_INLINE} inline; {$ENDIF}
function GetListSeparator: Char; {$IFDEF SUPPORTS_INLINE} inline; {$ENDIF}
function GetLongDateFormat: string; {$IFDEF SUPPORTS_INLINE} inline; {$ENDIF}
function GetLongDayNames(AIndex: Integer): string; {$IFDEF SUPPORTS_INLINE} inline; {$ENDIF}
function GetLongMonthNames(AIndex: Integer): string; {$IFDEF SUPPORTS_INLINE} inline; {$ENDIF}
function GetLongTimeFormat: string; {$IFDEF SUPPORTS_INLINE} inline; {$ENDIF}
function GetMonthNamesHighIndex: Integer; {$IFDEF SUPPORTS_INLINE} inline; {$ENDIF}
function GetMonthNamesLowIndex: Integer; {$IFDEF SUPPORTS_INLINE} inline; {$ENDIF}
function GetNegCurrFormat: Byte; {$IFDEF SUPPORTS_INLINE} inline; {$ENDIF}
function GetShortDateFormat: string; {$IFDEF SUPPORTS_INLINE} inline; {$ENDIF}
function GetShortDayNames(AIndex: Integer): string; {$IFDEF SUPPORTS_INLINE} inline; {$ENDIF}
function GetShortMonthNames(AIndex: Integer): string; {$IFDEF SUPPORTS_INLINE} inline; {$ENDIF}
function GetShortTimeFormat: string; {$IFDEF SUPPORTS_INLINE} inline; {$ENDIF}
function GetThousandSeparator: Char; {$IFDEF SUPPORTS_INLINE} inline; {$ENDIF}
function GetTimeAMString: string; {$IFDEF SUPPORTS_INLINE} inline; {$ENDIF}
function GetTimePMString: string; {$IFDEF SUPPORTS_INLINE} inline; {$ENDIF}
function GetTimeSeparator: Char; {$IFDEF SUPPORTS_INLINE} inline; {$ENDIF}
function GetTwoDigitYearCenturyWindow: Word; {$IFDEF SUPPORTS_INLINE} inline; {$ENDIF}
procedure SetCurrencyDecimals(AValue: Byte); {$IFDEF SUPPORTS_INLINE} inline; {$ENDIF}
procedure SetCurrencyFormat(const AValue: Byte); {$IFDEF SUPPORTS_INLINE} inline; {$ENDIF}
procedure SetCurrencyString(AValue: string); {$IFDEF SUPPORTS_INLINE} inline; {$ENDIF}
procedure SetDateSeparator(const AValue: Char); {$IFDEF SUPPORTS_INLINE} inline; {$ENDIF}
procedure SetDecimalSeparator(AValue: Char); {$IFDEF SUPPORTS_INLINE} inline; {$ENDIF}
procedure SetListSeparator(const AValue: Char); {$IFDEF SUPPORTS_INLINE} inline; {$ENDIF}
procedure SetLongDateFormat(const AValue: string); {$IFDEF SUPPORTS_INLINE} inline; {$ENDIF}
procedure SetLongTimeFormat(const AValue: string); {$IFDEF SUPPORTS_INLINE} inline; {$ENDIF}
procedure SetNegCurrFormat(const AValue: Byte); {$IFDEF SUPPORTS_INLINE} inline; {$ENDIF}
procedure SetShortDateFormat(AValue: string); {$IFDEF SUPPORTS_INLINE} inline; {$ENDIF}
procedure SetShortTimeFormat(const AValue: string); {$IFDEF SUPPORTS_INLINE} inline; {$ENDIF}
procedure SetThousandSeparator(AValue: Char); {$IFDEF SUPPORTS_INLINE} inline; {$ENDIF}
procedure SetTimeAMString(const AValue: string); {$IFDEF SUPPORTS_INLINE} inline; {$ENDIF}
procedure SetTimePMString(const AValue: string); {$IFDEF SUPPORTS_INLINE} inline; {$ENDIF}
procedure SetTimeSeparator(const AValue: Char); {$IFDEF SUPPORTS_INLINE} inline; {$ENDIF}
procedure SetTwoDigitYearCenturyWindow(const AValue: Word); {$IFDEF SUPPORTS_INLINE} inline; {$ENDIF}
public
property CurrencyDecimals: Byte read GetCurrencyDecimals write SetCurrencyDecimals;
property CurrencyFormat: Byte read GetCurrencyFormat write SetCurrencyFormat;
property CurrencyString: string read GetCurrencyString write SetCurrencyString;
property DateSeparator: Char read GetDateSeparator write SetDateSeparator;
property DayNamesHighIndex: Integer read GetDayNamesHighIndex;
property DayNamesLowIndex: Integer read GetDayNamesLowIndex;
property DecimalSeparator: Char read GetDecimalSeparator write SetDecimalSeparator;
property ListSeparator: Char read GetListSeparator write SetListSeparator;
property LongDateFormat: string read GetLongDateFormat write SetLongDateFormat;
property LongDayNames[AIndex: Integer]: string read GetLongDayNames;
property LongMonthNames[AIndex: Integer]: string read GetLongMonthNames;
property LongTimeFormat: string read GetLongTimeFormat write SetLongTimeFormat;
property MonthNamesHighIndex: Integer read GetMonthNamesHighIndex;
property MonthNamesLowIndex: Integer read GetMonthNamesLowIndex;
property NegCurrFormat: Byte read GetNegCurrFormat write SetNegCurrFormat;
property ShortDateFormat: string read GetShortDateFormat write SetShortDateFormat;
property ShortDayNames[AIndex: Integer]: string read GetShortDayNames;
property ShortMonthNames[AIndex: Integer]: string read GetShortMonthNames;
property ShortTimeFormat: string read GetShortTimeFormat write SetShortTimeFormat;
property ThousandSeparator: Char read GetThousandSeparator write SetThousandSeparator;
property TimeAMString: string read GetTimeAMString write SetTimeAMString;
property TimePMString: string read GetTimePMString write SetTimePMString;
property TimeSeparator: Char read GetTimeSeparator write SetTimeSeparator;
property TwoDigitYearCenturyWindow: Word read GetTwoDigitYearCenturyWindow write SetTwoDigitYearCenturyWindow;
end;
var
JclFormatSettings: TJclFormatSettings;
// Procedure to initialize the SimpleLog Variable
procedure InitSimpleLog(const ALogFileName: string = ''; AOpenLog: Boolean = true);
// Global Variable to make it easier for an application wide log handling.
// Must be initialized with InitSimpleLog before using
var
SimpleLog : TJclSimpleLog;
// Validates if then variant value is null or is empty
function VarIsNullEmpty(const V: Variant): Boolean;
// Validates if then variant value is null or is empty or VarToStr is a blank string
function VarIsNullEmptyBlank(const V: Variant): Boolean;
{$IFDEF UNITVERSIONING}
const
UnitVersioning: TUnitVersionInfo = (
RCSfile: '$URL$';
Revision: '$Revision$';
Date: '$Date$';
LogPath: 'JCL\source\common';
Extra: '';
Data: nil
);
{$ENDIF UNITVERSIONING}
implementation
uses
{$IFDEF HAS_UNIT_LIBC}
Libc,
{$ENDIF HAS_UNIT_LIBC}
{$IFDEF MSWINDOWS}
JclConsole,
{$ENDIF MSWINDOWS}
{$IFDEF HAS_UNITSCOPE}
System.Variants, System.Types, System.Contnrs,
{$IFDEF HAS_UNIT_ANSISTRINGS}
System.AnsiStrings,
{$ENDIF HAS_UNIT_ANSISTRINGS}
{$ELSE ~HAS_UNITSCOPE}
Variants, Types, Contnrs,
{$IFDEF HAS_UNIT_ANSISTRINGS}
AnsiStrings,
{$ENDIF HAS_UNIT_ANSISTRINGS}
{$ENDIF ~HAS_UNITSCOPE}
JclFileUtils, JclMath, JclResources, JclStrings,
JclStringConversions, JclSysInfo, JclWin32;
// memory initialization
procedure ResetMemory(out P; Size: Longint);
begin
if Size > 0 then
begin
Byte(P) := 0;
FillChar(P, Size, 0);
end;
end;
// Pointer manipulation
procedure GetAndFillMem(var P: Pointer; const Size: Integer; const Value: Byte);
begin
GetMem(P, Size);
FillChar(P^, Size, Value);
end;
procedure FreeMemAndNil(var P: Pointer);
var
Q: Pointer;
begin
Q := P;
P := nil;
FreeMem(Q);
end;
function PCharOrNil(const S: string): PChar;
begin
Result := Pointer(S);
end;
function PAnsiCharOrNil(const S: AnsiString): PAnsiChar;
begin
Result := Pointer(S);
end;
{$IFDEF SUPPORTS_WIDESTRING}
function PWideCharOrNil(const W: WideString): PWideChar;
begin
Result := Pointer(W);
end;
{$ENDIF SUPPORTS_WIDESTRING}
{$IFDEF MSWINDOWS}
type
PUsed = ^TUsed;
TUsed = record
SizeFlags: Integer;
end;
const
cThisUsedFlag = 2;
cPrevFreeFlag = 1;
cFillerFlag = Integer($80000000);
cFlags = cThisUsedFlag or cPrevFreeFlag or cFillerFlag;
function SizeOfMem(const APointer: Pointer): Integer;
var
U: PUsed;
begin
if IsMemoryManagerSet then
Result:= -1
else
begin
Result := 0;
if APointer <> nil then
begin
U := APointer;
U := PUsed(TJclAddr(U) - SizeOf(TUsed));
if (U.SizeFlags and cThisUsedFlag) <> 0 then
Result := (U.SizeFlags) and (not cFlags - SizeOf(TUsed));
end;
end;
end;
{$ENDIF MSWINDOWS}
{$IFDEF LINUX}
function SizeOfMem(const APointer: Pointer): Integer;
begin
if IsMemoryManagerSet then
Result:= -1
else
begin
if APointer <> nil then
Result := malloc_usable_size(APointer)
else
Result := 0;
end;
end;
{$ENDIF LINUX}
function WriteProtectedMemory(BaseAddress, Buffer: Pointer;
Size: Cardinal; out WrittenBytes: Cardinal): Boolean;
{$IFDEF MSWINDOWS}
var
OldProtect, Dummy: Cardinal;
begin
WrittenBytes := 0;
if Size > 0 then
begin
// (outchy) VirtualProtect for DEP issues
OldProtect := 0;
Result := VirtualProtect(BaseAddress, Size, PAGE_EXECUTE_READWRITE, OldProtect);
if Result then
try