forked from ppv/NPPFSIPlugin
-
Notifications
You must be signed in to change notification settings - Fork 1
/
FpcPipes.pas
4999 lines (4573 loc) · 143 KB
/
FpcPipes.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
{
Ported to Free Pascal by Robert Di Pardo, Copyright 2022, 2023
This program is free software: you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation, either version
3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied
warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General
Public License along with this program. If not, see
<https://www.gnu.org/licenses/>.
This software incorporates work covered by the following copyright and permission notice:
}
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
Author: Russell Libby, updated by François PIETTE @ OverByte
Creation: Mar 30, 2003
Last update: Sep 30, 2023
Description: Pipe components by Russell Libby
See blog article at http://francois-piette.blogspot.be
Version: 1.02
History: See below in the original comments
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
{ avoid name collision with the Pipes unit in Free Pascal's fcl-process package }
unit FpcPipes;
{$IFDEF FPC}
{$MODE Delphi}
{$ASMMODE Intel}
{$IFDEF CPUx64}
{$WARN 4056 OFF}
{$ENDIF}
{$WARN 4055 OFF}
{$WARN 4082 OFF}
{$WARN SYMBOL_DEPRECATED OFF}
{$ENDIF}
////////////////////////////////////////////////////////////////////////////////
//
// Unit : FpcPipes
// Author : rllibby
// Date : 01.30.2003 - Original code
// URL: : http://home.roadrunner.com/~rllibby/source.html
//
// 01.19.2006 - Code overhauled to allow for usage in dll's
// when compiled with Delphi 6 and up.
//
// 04.03.2008 - Second overhaul after finding that memory leaks
// in the server thread handling when run under
// load. Also found cases where messages were missed
// using PeekMessage due to the queue being full. The
// default limit for the Windows message queue is 10000.
//
// 04.04.2008 - (1) Better memory handling for messages.
// (2) Smart reallocation for overlapped reads
// (3) Message chunking is handled, which alleviates
// the developer from manually splitting data writes
// over the network when the data is > 65K.
// (4) Temp file backed streams for multi packet
// messages.
// (5) Added the ability to throttle down client
// based on memory consumption in the write queue.
//
// 05.30.2008 - Updated the client / server components to allow
// the Active (server) and Disconnect (client) calls
// to be made while processing an event from the
// component.
//
// 06.05.2008 - Wrapped up the TPipeConsole component, which
// handles redirection from console processes.
// Also provides a means of synchronous execution
// by way of the Execute(...) function.
//
// 10.20.2008 - Added remote code threading for obtaining the
// console handle directly. If this fails, the
// code will revert to enumerating the windows
// of the console process. Also added priority
// setting for the process.
//
// 12.01.2010 - Fix to "constructor TPipeListenThread.Create()"
// where "FPipeServer.FThreadCount.Increment" was being
// called before the property was set from the incoming
// parameters
//
// 04.03.2013 - francois.piette@overbyte.be updated the code for Delphi XE3
// Started from sources downloaded from Mick Grove blog
// http://micksmix.wordpress.com/2011/06/27/named-pipes-unit-for-delphi/
// I made a runttime package and a designtime package. For that purpose,
// I moved the register procedure to a separate source "PipesReg.pas".
// I made simple icons for the components.
// The components are registered in the "Pipes" tab in the IDE.
//
// 04.10.2013 - arno.garrels@gmx.de added 64-bit support and fixed code to
// compile with Delphi 7 to XE5 (earlier versions may compile however untested).
// Made event parameter HPIPE a type THandle otherwise there type mismatches
// in event handler signatures.
//
// 11.26.2022 - Robert Di Pardo <dipardo.r@gmail.com>
// Adapted unit for Free Pascal.
//
// 09.30.2023 - *idem*
// Added the GPLv3 license header.
//
// Description : Set of client and server named pipe components for Delphi & Free Pascal, as
// well a console pipe redirection component.
//
// Notes:
//
// TPipeClient
//
// - The worker thread coordinates events with the component by way of
// SendMessage. This means the thread that the component lives on has
// to have a message loop. Also, it means that the developer needs
// to watch what is done in the TPipeClient events. Do not expect the
// following calls to work from within the events:
//
// - FlushPipeBuffers
// - WaitForReply
// - Write (works, but no memory throttling)
//
// The reason these calls do not work is that they are expecting
// interaction from the worker thread, which is currently stalled while
// waiting on the event handler to finish (and the SendMessage call to
// complete). I have coded these routines so that they will NOT deadlock,
// but again, don't expect them to ever return success if called from
// within one of TPipeClient events. The one exception to this is the
// call to Disconnect, which can be called from within an event. If
// called from within an event, the component will PostMessage to itself
// and will perform the true disconnect when the message is handled.
//
// TPipeServer
//
// - The worker threads coordinate events with the component by way of
// SendMessage. This means the thread that the component lives on has
// to have a message loop. No special restrictions for what is done in
// the event handlers.
//
// TPipeConsole
//
// - The worker thread coordinates events with the component by way of
// SendMessage. This means the thread that the component lives on has
// to have a message loop. No special restrictions for what is done in
// the event handlers.
//
////////////////////////////////////////////////////////////////////////////////
interface
{$DEFINE DELPHI_6_ABOVE}
{$IFDEF CONDITIONALEXPRESSIONS}
{$IF COMPILERVERSION > 22}
{$DEFINE DELPHI_XE2_ABOVE} // has 64-bit compiler
{$IFEND}
{$ENDIF}
{$IF NOT DEFINED(DELPHI_XE2_ABOVE) AND NOT DEFINED(FPC)}
{$DEFINE CPUX86}
{$ENDIF}
{$WARN SYMBOL_PLATFORM OFF} // TThreadPriority is specific to Windows
////////////////////////////////////////////////////////////////////////////////
// Include units
////////////////////////////////////////////////////////////////////////////////
uses
Windows,
Types,
SysUtils,
Classes,
Messages;
////////////////////////////////////////////////////////////////////////////////
// Resource strings
////////////////////////////////////////////////////////////////////////////////
resourcestring
resThreadCtx =
'The notify window and the component window do not exist in the same thread!';
resPipeActive = 'Cannot change property while server is active!';
resPipeConnected = 'Cannot change property when client is connected!';
resBadPipeName = 'Invalid pipe name specified!';
resPipeBaseName = '\\.\pipe\';
resPipeBaseFmtName = '\\%s\pipe\';
resPipeName = 'PipeServer';
resConClass = 'ConsoleWindowClass';
resComSpec = 'ComSpec';
////////////////////////////////////////////////////////////////////////////////
// Min, max and default constants
////////////////////////////////////////////////////////////////////////////////
const
MAX_NAME = 256;
MAX_WAIT = 1000;
MAX_BUFFER = Pred(MaxWord);
DEF_SLEEP = 100;
DEF_MEMTHROTTLE = 10240000;
PIPE_UNLIMITED_INSTANCES = 255;
////////////////////////////////////////////////////////////////////////////////
// Pipe mode constants
////////////////////////////////////////////////////////////////////////////////
const
PIPE_MODE = PIPE_TYPE_MESSAGE or PIPE_READMODE_MESSAGE or PIPE_WAIT;
PIPE_OPENMODE = PIPE_ACCESS_DUPLEX or FILE_FLAG_OVERLAPPED;
PIPE_INSTANCES = PIPE_UNLIMITED_INSTANCES;
////////////////////////////////////////////////////////////////////////////////
// Pipe handle constants
////////////////////////////////////////////////////////////////////////////////
const
STD_PIPE_INPUT = 0;
STD_PIPE_OUTPUT = 1;
STD_PIPE_ERROR = 2;
////////////////////////////////////////////////////////////////////////////////
// Mutliblock message constants
////////////////////////////////////////////////////////////////////////////////
const
MB_MAGIC = $4347414D; // MAGC
MB_START = $424D5453; // STMB
MB_END = $424D5445; // ETMB
MB_PREFIX = 'PMM';
////////////////////////////////////////////////////////////////////////////////
// Pipe window message constants
////////////////////////////////////////////////////////////////////////////////
const
WM_PIPEERROR_L = WM_USER + 100;
WM_PIPEERROR_W = WM_USER + 101;
WM_PIPECONNECT = WM_USER + 102;
WM_PIPESEND = WM_USER + 103;
WM_PIPEMESSAGE = WM_USER + 104;
WM_PIPE_CON_OUT = WM_USER + 105;
WM_PIPE_CON_ERR = WM_USER + 106;
WM_PIPEMINMSG = WM_PIPEERROR_L;
WM_PIPEMAXMSG = WM_PIPE_CON_ERR;
////////////////////////////////////////////////////////////////////////////////
// Posted (deferred) window messages
////////////////////////////////////////////////////////////////////////////////
const
WM_THREADCTX = WM_USER + 200;
WM_DOSHUTDOWN = WM_USER + 300;
////////////////////////////////////////////////////////////////////////////////
// Thread window message constants
////////////////////////////////////////////////////////////////////////////////
const
CM_EXECPROC = $8FFD;
CM_DESTROYWINDOW = $8FFC;
////////////////////////////////////////////////////////////////////////////////
// Pipe exception type
////////////////////////////////////////////////////////////////////////////////
type
EPipeException = class(Exception);
////////////////////////////////////////////////////////////////////////////////
// Pipe data type
////////////////////////////////////////////////////////////////////////////////
type
HPIPE = type THandle;
////////////////////////////////////////////////////////////////////////////////
// Record and class types
////////////////////////////////////////////////////////////////////////////////
type
// Forward declarations
TPipeServer = class;
TPipeClient = class;
TWriteQueue = class;
// Std handles for console redirection
TPipeStdHandles = array [STD_PIPE_INPUT .. STD_PIPE_ERROR] of THandle;
// Process window info
PPipeConsoleInfo = ^TPipeConsoleInfo;
TPipeConsoleInfo = packed record
ProcessID : DWORD;
ThreadID : DWORD;
Window : HWND;
end;
// Data write record
PPipeWrite = ^TPipeWrite;
TPipeWrite = packed record
Buffer : PChar;
Count : Integer;
end;
// Data write message block
PPipeMsgBlock = ^TPipeMsgBlock;
TPipeMsgBlock = packed record
Size : DWORD;
MagicStart : DWORD;
ControlCode : DWORD;
MagicEnd : DWORD;
end;
// Data writer list record
PWriteNode = ^TWriteNode;
TWriteNode = packed record
PipeWrite : PPipeWrite;
NextNode : PWriteNode;
end;
// Server pipe info record
PPipeInfo = ^TPipeInfo;
TPipeInfo = packed record
Pipe : HPIPE;
KillEvent : THandle;
WriteQueue : TWriteQueue;
end;
// Thread sync info
TSyncInfo = class
FSyncBaseTID : THandle;
FThreadWindow : HWND;
FThreadCount : Integer;
end;
// Exception frame
PRaiseFrame = ^TRaiseFrame;
TRaiseFrame = record
NextRaise : PRaiseFrame;
ExceptAddr : Pointer;
ExceptObject : TObject;
ExceptionRecord : PExceptionRecord;
end;
// Pipe context for error messages
TPipeContext = (pcListener, pcWorker);
// Pipe Events
TOnConsole = procedure(Sender : TObject; Stream : TStream) of object;
TOnConsoleStop = procedure(Sender : TObject; ExitValue : LongWord) of object;
TOnPipeConnect = procedure(Sender : TObject; Pipe : HPIPE) of object;
TOnPipeDisconnect = procedure(Sender : TObject; Pipe : HPIPE) of object;
TOnPipeMessage = procedure(Sender : TObject; Pipe : HPIPE; Stream : TStream) of object;
TOnPipeSent = procedure(Sender : TObject; Pipe : HPIPE; Size : DWORD) of object;
TOnPipeError = procedure(Sender : TObject; Pipe : HPIPE; PipeContext : TPipeContext; ErrorCode : Integer) of object;
// TWriteQueue class
TWriteQueue = class(TObject)
private
// Private declarations
FMutex : THandle;
FDataEv : THandle;
FEmptyEv : THandle;
FDataSize : LongWord;
FHead : PWriteNode;
FTail : PWriteNode;
procedure UpdateState;
function NodeSize(Node : PWriteNode) : LongWord;
protected
// Protected declarations
procedure Clear;
procedure EnqueueControlPacket(ControlCode : DWORD);
procedure EnqueueMultiPacket(PipeWrite : PPipeWrite);
function GetEmpty : Boolean;
function NewNode(PipeWrite : PPipeWrite) : PWriteNode;
public
// Public declarations
constructor Create;
destructor Destroy; override;
procedure Enqueue(PipeWrite : PPipeWrite);
procedure EnqueueEndPacket;
procedure EnqueueStartPacket;
function Dequeue : PPipeWrite;
property DataEvent : THandle read FDataEv;
property DataSize : LongWord read FDataSize;
property Empty : Boolean read GetEmpty;
property EmptyEvent : THandle read FEmptyEv;
end;
// TThreadSync class
TThreadSync = class
private
// Private declarations
FSyncRaise : TObject;
FMethod : TThreadMethod;
FSyncBaseTID : THandle;
public
// Public declarations
constructor Create;
destructor Destroy; override;
procedure Synchronize(Method : TThreadMethod);
property SyncBaseTID : THandle read FSyncBaseTID;
end;
// TThreadEx class
TThreadEx = class(TThread)
private
// Private declarations
FSync : TThreadSync;
procedure HandleTerminate;
protected
// Protected declarations
procedure SafeSynchronize(Method : TThreadMethod);
procedure Synchronize(Method : TThreadMethod);
procedure DoTerminate; override;
public
// Public declarations
constructor Create(CreateSuspended : Boolean);
destructor Destroy; override;
procedure Run;
procedure Wait;
property Sync : TThreadSync read FSync;
end;
// TSyncManager class
TSyncManager = class(TObject)
private
// Private declarations
FThreadLock : TRTLCriticalSection;
FList : TList;
protected
// Protected declarations
procedure DoDestroyWindow(Info : TSyncInfo);
procedure FreeSyncInfo(Info : TSyncInfo);
function AllocateWindow : HWND;
function FindSyncInfo(SyncBaseTID : LongWord) : TSyncInfo;
public
// Public declarations
class function Instance : TSyncManager;
constructor Create;
destructor Destroy; override;
procedure AddThread(ThreadSync : TThreadSync);
procedure RemoveThread(ThreadSync : TThreadSync);
procedure Synchronize(ThreadSync : TThreadSync);
end;
// TThreadCounter class
TThreadCounter = class(TObject)
private
// Private declarations
FLock : TRTLCriticalSection;
FEmpty : THandle;
FCount : Integer;
protected
// Protected declarations
function GetCount : Integer;
public
// Public declarations
constructor Create;
destructor Destroy; override;
procedure Increment;
procedure Decrement;
procedure WaitForEmpty;
property Count : Integer read GetCount;
end;
// TFastMemStream class
TFastMemStream = class(TMemoryStream)
protected
// Protected declarations
function Realloc(var NewCapacity : Longint) : Pointer; {$IFDEF FPC}reintroduce{$ELSE}override{$ENDIF};
end;
// Multipacket message handler
TPipeMultiMsg = class(TObject)
private
// Private declarations
FHandle : THandle;
FStream : TStream;
protected
// Protected declarations
procedure CreateTempBacking;
public
// Public declarations
constructor Create;
destructor Destroy; override;
property Stream : TStream read FStream;
end;
// TPipeListenThread class
TPipeListenThread = class(TThreadEx)
private
// Private declarations
FNotify : HWND;
FNotifyThread : THandle;
FErrorCode : Integer;
FPipe : HPIPE;
FPipeName : string;
FConnected : Boolean;
FEvents : array [0 .. 1] of THandle;
FOlapConnect : TOverlapped;
FPipeServer : TPipeServer;
FSA : TSecurityAttributes;
protected
// Protected declarations
function CreateServerPipe : Boolean;
procedure DoWorker;
procedure Execute; override;
function SafeSendMessage(AMsg : UINT; AWParam: WPARAM; ALParam: LPARAM): LRESULT;
public
// Public declarations
constructor Create(PipeServer : TPipeServer; KillEvent : THandle);
destructor Destroy; override;
end;
// TPipeThread class
TPipeThread = class(TThreadEx)
private
// Private declarations
FServer : Boolean;
FNotify : HWND;
FNotifyThread : THandle;
FPipe : HPIPE;
FErrorCode : Integer;
FCounter : TThreadCounter;
FWrite : DWORD;
FWriteQueue : TWriteQueue;
FPipeWrite : PPipeWrite;
FRcvRead : DWORD;
FPendingRead : Boolean;
FPendingWrite : Boolean;
FMultiMsg : TPipeMultiMsg;
FRcvStream : TFastMemStream;
FRcvBuffer : PChar;
FRcvAlloc : DWORD;
FRcvSize : DWORD;
FEvents : array [0 .. 3] of THandle;
FOlapRead : TOverlapped;
FOlapWrite : TOverlapped;
protected
// Protected declarations
function QueuedRead : Boolean;
function CompleteRead : Boolean;
function QueuedWrite : Boolean;
function CompleteWrite : Boolean;
procedure DoMessage;
procedure Execute; override;
function SafeSendMessage(AMsg : UINT; AWParam : WPARAM; ALParam : LPARAM): LRESULT;
public
// Public declarations
constructor Create(Server : Boolean; NotifyWindow : HWND;
NotifyThread : THandle; WriteQueue : TWriteQueue;
Counter : TThreadCounter; Pipe : HPIPE; KillEvent : THandle);
destructor Destroy; override;
property Pipe : HPIPE read FPipe;
end;
// TPipeServer component class
TPipeServer = class(TComponent)
private
// Private declarations
FBaseThread : THandle;
FHwnd : HWND;
FPipeName : string;
FDeferActive : Boolean;
FActive : Boolean;
FInShutDown : Boolean;
FKillEv : THandle;
FClients : TList;
FThreadCount : TThreadCounter;
FListener : TPipeListenThread;
FSA : TSecurityAttributes;
FOPS : TOnPipeSent;
FOPC : TOnPipeConnect;
FOPD : TOnPipeDisconnect;
FOPM : TOnPipeMessage;
FOPE : TOnPipeError;
procedure DoStartup;
procedure DoShutdown;
protected
// Protected declarations
function AllocPipeInfo(Pipe : HPIPE) : PPipeInfo;
function GetClient(Index : Integer) : HPIPE;
function GetClientCount : Integer;
function GetClientInfo(Pipe : HPIPE; out PipeInfo : PPipeInfo): Boolean;
procedure WndMethod(var Message : TMessage);
procedure RemoveClient(Pipe : HPIPE);
procedure SetActive(Value : Boolean);
procedure SetPipeName(Value : string);
procedure AddWorkerThread(Pipe : HPIPE);
procedure RemoveWorkerThread(Sender : TObject);
procedure RemoveListenerThread(Sender : TObject);
procedure Loaded; override;
public
// Public declarations
constructor Create(AOwner : TComponent); override;
constructor CreateUnowned;
destructor Destroy; override;
function Broadcast(var Buffer; Count : Integer) : Boolean; overload;
function Broadcast(var Prefix; PrefixCount : Integer; var Buffer; Count : Integer) : Boolean; overload;
function Disconnect(Pipe : HPIPE) : Boolean;
function Write(Pipe : HPIPE; var Prefix; PrefixCount : Integer; var Buffer; Count : Integer) : Boolean; overload;
function Write(Pipe : HPIPE; var Buffer; Count : Integer): Boolean; overload;
function SendStream(Pipe : HPIPE; Stream : TStream) : Boolean;
property WindowHandle : HWND read FHwnd;
property ClientCount : Integer read GetClientCount;
property Clients[index : Integer] : HPIPE read GetClient;
published
// Published declarations
property Active : Boolean read FActive write SetActive;
property OnPipeSent : TOnPipeSent read FOPS write FOPS;
property OnPipeConnect : TOnPipeConnect read FOPC write FOPC;
property OnPipeDisconnect : TOnPipeDisconnect read FOPD write FOPD;
property OnPipeMessage : TOnPipeMessage read FOPM write FOPM;
property OnPipeError : TOnPipeError read FOPE write FOPE;
property PipeName : string read FPipeName write SetPipeName;
end;
// TPipeClient component class
TPipeClient = class(TComponent)
private
// Private declarations
FBaseThread : THandle;
FHwnd : HWND;
FPipe : HPIPE;
FPipeName : string;
FServerName : string;
FDisconnecting : Boolean;
FReply : Boolean;
FThrottle : LongWord;
FWriteQueue : TWriteQueue;
FWorker : TPipeThread;
FKillEv : THandle;
FSA : TSecurityAttributes;
FOPE : TOnPipeError;
FOPD : TOnPipeDisconnect;
FOPM : TOnPipeMessage;
FOPS : TOnPipeSent;
protected
// Protected declarations
function GetConnected : Boolean;
procedure SetPipeName(Value : string);
procedure SetServerName(Value : string);
procedure RemoveWorkerThread(Sender : TObject);
procedure WndMethod(var AMsg : TMessage);
public
// Public declarations
constructor Create(AOwner : TComponent); override;
constructor CreateUnowned;
destructor Destroy; override;
function Connect(WaitTime : DWORD = NMPWAIT_USE_DEFAULT_WAIT; Start : Boolean = TRUE) : Boolean;
function WaitForReply(TimeOut : Cardinal = INFINITE) : Boolean;
procedure Disconnect;
procedure FlushPipeBuffers;
function SendStream(Stream : TStream) : Boolean;
function Write(var Prefix; PrefixCount : Integer; var Buffer; Count : Integer) : Boolean; overload;
function Write(var Buffer; Count : Integer) : Boolean; overload;
property Connected : Boolean read GetConnected;
property WindowHandle : HWND read FHwnd;
property Pipe : HPIPE read FPipe;
published
// Published declarations
property MemoryThrottle : LongWord read FThrottle write FThrottle;
property PipeName : string read FPipeName write SetPipeName;
property ServerName : string read FServerName write SetServerName;
property OnPipeDisconnect : TOnPipeDisconnect read FOPD write FOPD;
property OnPipeMessage : TOnPipeMessage read FOPM write FOPM;
property OnPipeSent : TOnPipeSent read FOPS write FOPS;
property OnPipeError : TOnPipeError read FOPE write FOPE;
end;
// TPipeConsoleThread class
TPipeConsoleThread = class(TThreadEx)
private
// Private declarations
FNotify : HWND;
FStream : TFastMemStream;
FProcess : THandle;
FOutput : THandle;
FError : THandle;
procedure ProcessPipe(Handle : THandle; AMsg : UINT);
protected
// Protected declarations
procedure Execute; override;
procedure ProcessPipes;
function SafeSendMessage(AMsg : UINT; AWParam: WParam; ALParam : LPARAM): LRESULT;
public
// Public declarations
constructor Create(NotifyWindow : HWND; ProcessHandle, OutputPipe, ErrorPipe : THandle);
destructor Destroy; override;
end;
// TPipeConsole component class
TPipeConsole = class(TComponent)
private
// Private declarations
FRead : TPipeStdHandles;
FWrite : TPipeStdHandles;
FWorker : TPipeConsoleThread;
FPriority : TThreadPriority;
FPI : TProcessInformation;
FSI : TStartupInfo;
FLastErr : Integer;
FVisible : Boolean;
FStopping : Boolean;
FHwnd : HWND;
FOnStop : TOnConsoleStop;
FOnOutput : TOnConsole;
FOnError : TOnConsole;
FApplication : string;
FCommandLine : string;
procedure ProcessPipe(Handle : THandle; Stream : TStream);
function SynchronousRun(OutputStream, ErrorStream : TStream; TimeOut : DWORD) : DWORD;
protected
// Protected declarations
function GetConsoleHandle : HWND;
function GetRunning : Boolean;
function GetVisible : Boolean;
function OpenStdPipes : Boolean;
procedure CloseStdPipes;
procedure ForcePriority(Value : TThreadPriority);
procedure RemoveWorkerThread(Sender : TObject);
procedure SetLastErr(Value : Integer);
procedure SetPriority(Value : TThreadPriority);
procedure SetVisible(Value : Boolean);
procedure WndMethod(var Message : TMessage);
public
// Public declarations
constructor Create(AOwner : TComponent); override;
constructor CreateUnowned;
destructor Destroy; override;
function ComSpec : string;
function Execute(Application, CommandLine : string;
OutputStream, ErrorStream : TStream;
TimeOut : DWORD = INFINITE) : DWORD;
procedure SendCtrlBreak;
procedure SendCtrlC;
function Start(Application, CommandLine : string) : Boolean;
procedure Stop(ExitValue : DWORD);
procedure Write(const Buffer; Length : Integer);
property Application : string read FApplication;
property CommandLine : string read FCommandLine;
property ConsoleHandle : HWND read GetConsoleHandle;
property Running : Boolean read GetRunning;
published
// Published declarations
property LastError : Integer read FLastErr write SetLastErr;
property OnError : TOnConsole read FOnError write FOnError;
property OnOutput : TOnConsole read FOnOutput write FOnOutput;
property OnStop : TOnConsoleStop read FOnStop write FOnStop;
property Priority : TThreadPriority read FPriority write SetPriority;
property Visible : Boolean read GetVisible write SetVisible;
end;
////////////////////////////////////////////////////////////////////////////////
// Console helper functions
////////////////////////////////////////////////////////////////////////////////
function ExecConsoleEvent(ProcessHandle : THandle; Event : DWORD) : Boolean;
procedure ExitProcessEx(ProcessHandle : THandle; ExitCode : DWORD);
function GetConsoleWindowEx(ProcessHandle : THandle; ProcessID, ThreadID : DWORD) : HWND;
////////////////////////////////////////////////////////////////////////////////
// Pipe helper functions
////////////////////////////////////////////////////////////////////////////////
function AllocPipeWrite(const Buffer; Count : Integer) : PPipeWrite;
function AllocPipeWriteWithPrefix(const Prefix; PrefixCount : Integer;
const Buffer; Count : Integer) : PPipeWrite;
procedure CheckPipeName(Value : string);
procedure ClearOverlapped(var Overlapped : TOverlapped;
ClearEvent : Boolean = FALSE);
procedure CloseHandleClear(var Handle : THandle); overload;
procedure CloseHandleClear(var Handle : HPIPE); overload;
function ComputerName : string;
procedure DisconnectAndClose(Pipe : HPIPE; IsServer : Boolean = TRUE);
procedure DisposePipeWrite(var PipeWrite : PPipeWrite);
function EnumConsoleWindows(Window : HWND; lParam : Integer) : BOOL; stdcall;
procedure FlushMessages;
function IsHandle(Handle : THandle) : Boolean;
procedure RaiseWindowsError;
////////////////////////////////////////////////////////////////////////////////
// Security helper functions
////////////////////////////////////////////////////////////////////////////////
procedure InitializeSecurity(var SA : TSecurityAttributes);
procedure FinalizeSecurity(var SA : TSecurityAttributes);
////////////////////////////////////////////////////////////////////////////////
// Object instance functions
////////////////////////////////////////////////////////////////////////////////
function AllocateHWnd(Method : TWndMethod) : HWND;
procedure DeallocateHWnd(Wnd : HWND);
procedure FreeObjectInstance(ObjectInstance : Pointer);
function MakeObjectInstance(Method : TWndMethod) : Pointer;
implementation
{$IF NOT DEFINED(DELPHI_XE2_ABOVE) AND NOT DEFINED(FPC)}
type
NativeUInt = LongWord;
NativeInt = LongInt;
SIZE_T = NativeUInt; // SIZE_T since XE2 available
{$ENDIF}
type
// Object instance structure
PObjectInstance = ^TObjectInstance;
TObjectInstance = packed record
Code : Byte;
Offset : Integer;
case Integer of
0 : (Next : PObjectInstance);
1 : (Method : TWndMethod);
end;
const
{$IFDEF CPUX86}
CodeBytes = 2;
{$ENDIF}
{$IFDEF CPUX64}
CodeBytes = 8;
{$ENDIF}
INSTANCE_COUNT = (4096 - SizeOf(Pointer) * 2 - CodeBytes) div SizeOf(TObjectInstance) - 1;//313;
type
// Object instance page block
PInstanceBlock = ^TInstanceBlock;
TInstanceBlock = packed record
Next : PInstanceBlock;
Counter : Word;
Code : array [1 .. CodeBytes] of Byte;
WndProcPtr : Pointer;
Instances : array [0 .. INSTANCE_COUNT] of TObjectInstance;
end;
////////////////////////////////////////////////////////////////////////////////
// Global protected variables
////////////////////////////////////////////////////////////////////////////////
var
InstBlockList : PInstanceBlock = nil;
InstFreeList : PObjectInstance = nil;
SyncManager : TSyncManager = nil;
InstCritSect : TRTLCriticalSection;
ThreadWndClass : TWndClass = (style : 0; lpfnWndProc : nil; cbClsExtra : 0;
cbWndExtra : 0; hInstance : 0; hIcon : 0; hCursor : 0;
hbrBackground : 0; lpszMenuName : nil;
lpszClassName : 'ThreadSyncWindow');
ObjWndClass : TWndClass = (style : 0; lpfnWndProc : @DefWindowProc;
cbClsExtra : 0; cbWndExtra : 0; hInstance : 0; hIcon : 0; hCursor : 0;
hbrBackground : 0; lpszMenuName : nil; lpszClassName : 'ObjWndWindow');
////////////////////////////////////////////////////////////////////////////////
// TPipeConsoleThread
////////////////////////////////////////////////////////////////////////////////
constructor TPipeConsoleThread.Create(NotifyWindow: HWND; ProcessHandle, OutputPipe, ErrorPipe: THandle);
begin
// Perform inherited create (suspended)
inherited Create(TRUE);
// Resource protection
try
// Set initial state
FProcess := 0;
FNotify := NotifyWindow;
FOutput := OutputPipe;
FError := ErrorPipe;
FStream := TFastMemStream.Create;
finally
// Duplicate the process handle
DuplicateHandle(GetCurrentProcess, ProcessHandle, GetCurrentProcess, @FProcess, 0, TRUE, DUPLICATE_SAME_ACCESS);
end;
// Set thread parameters
FreeOnTerminate := TRUE;
Priority := tpLower;
end;
destructor TPipeConsoleThread.Destroy;
begin
// Resource protection
try
// Close the process handle
CloseHandleClear(FProcess);
// Free the memory stream
FStream.Free;
finally
// Perform inherited
inherited Destroy;
end;
end;
procedure TPipeConsoleThread.Execute;
var
dwExitCode : DWORD;
begin
// Set default return value
ReturnValue := ERROR_SUCCESS;
// Keep looping until the process terminates
while TRUE do
begin
// Wait for specified amount of time
case WaitForSingleObject(FProcess, DEF_SLEEP) of
// Object is signaled (process is finished)
WAIT_OBJECT_0 :
begin
// Process the output pipes one last time
ProcessPipes;
// Get the process exit code
if GetExitCodeProcess(FProcess, dwExitCode) then ReturnValue := dwExitCode;
// Break the loop
break;
end;
// Timeout, check the output pipes for data
WAIT_TIMEOUT :
ProcessPipes;
else
// Failure, set return code
ReturnValue := GetLastError;
// Done processing
break;
end;
end;
end;
procedure TPipeConsoleThread.ProcessPipes;
begin
// Process the output pipe
ProcessPipe(FOutput, WM_PIPE_CON_OUT);
// Process the error pipe
ProcessPipe(FError, WM_PIPE_CON_ERR);
end;
procedure TPipeConsoleThread.ProcessPipe(Handle: THandle; AMsg: UINT);
var
dwRead : DWORD;
dwSize : DWORD;
begin
// Check the pipe for available data
if PeekNamedPipe(Handle, nil, 0, nil, @dwSize, nil) and (dwSize > 0) then
begin
// Set the stream size
FStream.Size := dwSize;
// Resource protection
try
// Read from the pipe
if ReadFile(Handle, FStream.Memory^, dwSize, dwRead, nil) then
begin
// Make sure we read the number of bytes specified by size
if not(dwRead = dwSize) then
FStream.Size := dwRead;
// Rewind the stream
FStream.Position := 0;
// Send the message to the component
SafeSendMessage(AMsg, 0, LPARAM(FStream));
// Sleep
Sleep(0);
end;
finally
// Clear the stream
FStream.Clear;
end;
end;
end;
function TPipeConsoleThread.SafeSendMessage(AMsg : UINT; AWParam : WPARAM; ALParam : LPARAM) : LRESULT;
begin
// Check window handle
if IsWindow(FNotify) then
// Send the message
Result := SendMessage(FNotify, AMsg, AWParam, ALParam)
else
// Failure
Result := 0;
end;
////////////////////////////////////////////////////////////////////////////////
// TPipeConsole
////////////////////////////////////////////////////////////////////////////////
constructor TPipeConsole.Create(AOwner: TComponent);
begin
// Perform inherited create
inherited Create(AOwner);
// Private declarations
FHwnd := AllocateHWnd(WndMethod);
FillChar(FRead, SizeOf(FRead), 0);
FillChar(FWrite, SizeOf(FWrite), 0);
FillChar(FPI, SizeOf(FPI), 0);
FillChar(FSI, SizeOf(FSI), 0);
FLastErr := ERROR_SUCCESS;
FPriority := tpNormal;
SetLength(FApplication, 0);
SetLength(FCommandLine, 0);
FStopping := FALSE;
FVisible := FALSE;
FWorker := nil;
end;