File: debugprocess.pas

package info (click to toggle)
lazarus 2.0.0%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 214,460 kB
  • sloc: pascal: 1,862,622; xml: 265,709; cpp: 56,595; sh: 3,008; java: 609; makefile: 535; perl: 297; sql: 222; ansic: 137
file content (593 lines) | stat: -rw-r--r-- 17,668 bytes parent folder | download | duplicates (3)
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
{
 This unit contains the Commandline debugger class for external commandline
 debuggers.

 ***************************************************************************
 *                                                                         *
 *   This source 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 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This code 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.                              *
 *                                                                         *
 *   A copy of the GNU General Public License is available on the World    *
 *   Wide Web at <http://www.gnu.org/copyleft/gpl.html>. You can also      *
 *   obtain it by writing to the Free Software Foundation,                 *
 *   Inc., 51 Franklin Street - Fifth Floor, Boston, MA 02110-1335, USA.   *
 *                                                                         *
 ***************************************************************************
}
unit DebugProcess;

{$mode objfpc}{$H+}

{ $DEFINE DBG_VERBOSE}
{ $DEFINE DBG_VERBOSE_FULL_DATA}

{$IFDEF MSWindows} // optional gtk
  {$DEFINE NATIVE_ASYNC_PROCESS}
{$ELSE}
  {$UNDEF NATIVE_ASYNC_PROCESS}
{$ENDIF}

interface

uses
  Classes, sysutils, AsyncProcess, LCLIntf, InterfaceBase, process,
  Pipes, LazLoggerBase, UTF8Process;

type

  TDebugProcessNotification = procedure(Sender: TObject; ALine: String) of object;

  { TDebugProcessReadThread }

  {$IFnDEF NATIVE_ASYNC_PROCESS}
  TDebugProcessReadThread = class(TThread)
  private
    FAsyncLoopWaitEvent: PRTLEvent;
  protected
    FStream: TInputPipeStream;
    FOnDataAvail: TThreadMethod;
    FOnPipeError: TThreadMethod;
    procedure Execute; override;
  public
    constructor Create(CreateSuspended: Boolean; const StackSize: SizeUInt =
      DefaultStackSize);
    destructor Destroy; override;
    property AsyncLoopWaitEvent: PRTLEvent read FAsyncLoopWaitEvent;
  end;
  {$ENDIF}

  { TDebugAsyncProcess }

  TDebugAsyncProcess = class(TProcessUTF8) // TAsyncProcess
  private
    {$IFdef NATIVE_ASYNC_PROCESS}
    FPipeHandler: PPipeEventHandler;
    FProcessHandler: PProcessEventHandler;
    {$ELSE}
    FReadThread: TDebugProcessReadThread;
    {$ENDIF}
    FOnReadData: TNotifyEvent;
    FOnTerminate: TNotifyEvent;
    {$ifNdef NATIVE_ASYNC_PROCESS}
    procedure ThreadDataAvail;
    procedure ThreadPipeError;
    procedure TerminataThread;
    {$ENDIF}
    procedure FinishedReadingOutput;
  protected
    procedure HandlePipeInput(AData: PtrInt; AReasons: TPipeReasons);
    procedure HandleProcessTermination(AData: PtrInt; AReason: TChildExitReason; AInfo: dword);
    procedure UnhookPipeHandle;
    procedure UnhookProcessHandle;
  public
    procedure Execute; override;
    destructor Destroy; override;
    function Terminate(AExitCode: Integer): Boolean; override;
  published
    property OnReadData: TNotifyEvent read FOnReadData write FOnReadData;// You must read all the data in this event. Otherwise it is called again.
    property OnTerminate: TNotifyEvent read FOnTerminate write FOnTerminate;
  end;

  { TDebugProcess }

  TDebugProcess = class
  private const
    DBG_STREAM_READ_LEN = 8192;
  private
    FExternalDebugger: String;
    FDbgProcess: TDebugAsyncProcess;
    FOnLineReceived: TDebugProcessNotification;
    FOnBeginLinesReceived: TNotifyEvent;
    FOnEndLinesReceived: TNotifyEvent;
    FOnLineSent: TDebugProcessNotification;
    FOnSendError: TDebugProcessNotification;
    FOnTerminate: TNotifyEvent;
    FTmpBuffer: String;
    FOutputBuf: String;
    FLockReadData: Boolean;
    procedure DoReadData(Sender: TObject);
    procedure DoTerminate(Sender: TObject);
    function  GetDbgProcess: TProcessUTF8;
    function HandleHasData(const AHandle: Integer): Boolean;
  protected
    function GetDebugProcessRunning: Boolean;
  public
    constructor Create(const AExternalDebugger: String);
    destructor Destroy; override;
    function  CreateDebugProcess(const AOptions: String; AnEnvironment: TStrings): Boolean;
    procedure StopDebugProcess;
    procedure SendCmdLn(const ACommand: String); overload;
    procedure SendCmdLn(const ACommand: String; Values: array of const); overload;
  public
    property DebugProcess: TProcessUTF8 read GetDbgProcess;
    property DebugProcessRunning: Boolean read GetDebugProcessRunning;
    property OnLineReceived: TDebugProcessNotification read FOnLineReceived write FOnLineReceived;
    property OnBeginLinesReceived: TNotifyEvent read FOnBeginLinesReceived write FOnBeginLinesReceived;
    property OnEndLinesReceived: TNotifyEvent read FOnEndLinesReceived write FOnEndLinesReceived;
    property OnLineSent: TDebugProcessNotification read FOnLineSent write FOnLineSent;
    property OnSendError: TDebugProcessNotification read FOnSendError write FOnSendError;
//    property OnTimeOut: TDebugProcessNotification read FOnTimeOut write FOnTimeOut;
    property OnTerminate: TNotifyEvent read FOnTerminate write FOnTerminate;
  end;

implementation

uses
  {$IFdef MSWindows} Windows {$ENDIF}
  {$IFDEF UNIX} Unix, BaseUnix {$ENDIF}
  ;

var
  DBG_CMD_ECHO, DBG_CMD_ECHO_FULL, DBG_VERBOSE, DBG_WARNINGS: PLazLoggerLogGroup;

{ TDebugProcessReadThread }

{$IFnDEF NATIVE_ASYNC_PROCESS}
procedure TDebugProcessReadThread.Execute;
var
  R: Integer;
  FDS: TFDSet;
begin
  while (not Terminated) and (FStream.Handle >= 0) do begin
    FpFD_ZERO(FDS);
    FpFD_Set(FStream.Handle, FDS);
    // R = -1 on error, 0 on timeout, >0 on success and is number of handles
    // FDS is changed, and indicates what descriptors have changed
    R := FpSelect(FStream.Handle + 1, @FDS, nil, nil, 50);

    if Terminated then
      break;

    if r < 0 then begin
DebugLn('TTTTT pipe err');
      Queue(FOnPipeError);
      exit;
    end;

    if (R > 0) and (FpFD_ISSET(FStream.Handle,FDS)=1) then begin
DebugLn('TTTTT data avail');
      Queue(FOnDataAvail);
      RTLeventWaitFor(FAsyncLoopWaitEvent);
DebugLn('TTTTT data avail continue');
    end;

  end;
DebugLn(['TTTTT loop end ', Terminated]);
  RemoveQueuedEvents(Self, FOnDataAvail);
  RemoveQueuedEvents(Self, FOnPipeError);
end;

constructor TDebugProcessReadThread.Create(CreateSuspended: Boolean;
  const StackSize: SizeUInt);
begin
  FAsyncLoopWaitEvent := RTLEventCreate;
  inherited;
end;

destructor TDebugProcessReadThread.Destroy;
begin
  inherited Destroy;
  RTLeventdestroy(FAsyncLoopWaitEvent);
end;

{$ENDIF}

{ TDebugAsyncProcess }

procedure TDebugAsyncProcess.FinishedReadingOutput;
begin
{$ifNdef NATIVE_ASYNC_PROCESS}
  // Either finished reading, or TThread.Terminate was called
  if FReadThread <> nil then
    RTLeventSetEvent(FReadThread.AsyncLoopWaitEvent);
{$ENDIF}
end;

{$ifNdef NATIVE_ASYNC_PROCESS}
procedure TDebugAsyncProcess.ThreadDataAvail;
begin
  if not Running then begin
    //HandlePipeInput(0, [prBroken]);
    HandleProcessTermination(0, cerExit, 0);
    exit;
  end;

  HandlePipeInput(0, [prDataAvailable]);
  // SELF may have been destroyed, during read or handle-termination
end;

procedure TDebugAsyncProcess.ThreadPipeError;
begin
DebugLn(['got pipe err / is running ', Running]);
  Terminate(0);
  HandleProcessTermination(0, cerExit, 0);
end;

procedure TDebugAsyncProcess.TerminataThread;
begin
  FReadThread.Terminate;
  FinishedReadingOutput;
  TThread.RemoveQueuedEvents(FReadThread, @ThreadDataAvail);
  TThread.RemoveQueuedEvents(FReadThread, @ThreadPipeError);
end;

{$ENDIF}

procedure TDebugAsyncProcess.HandlePipeInput(AData: PtrInt;
  AReasons: TPipeReasons);
begin
  if prBroken in AReasons then
    UnhookPipeHandle;
  if prDataAvailable in AReasons then
    if FOnReadData <> nil then
      FOnReadData(Self);
end;

procedure TDebugAsyncProcess.HandleProcessTermination(AData: PtrInt;
  AReason: TChildExitReason; AInfo: dword);
begin
DebugLn('HandleProcessTermination');
  UnhookProcessHandle;
  UnhookPipeHandle;
  if FOnTerminate <> nil then
    FOnTerminate(Self);
end;

procedure TDebugAsyncProcess.UnhookPipeHandle;
begin
  {$IFdef NATIVE_ASYNC_PROCESS}
  if FPipeHandler <> nil then
    RemovePipeEventHandler(FPipeHandler);
  {$ELSE}
  if FReadThread <> nil then begin
    TerminataThread;
  end;
  {$ENDIF}
end;

procedure TDebugAsyncProcess.UnhookProcessHandle;
begin
  {$IFdef NATIVE_ASYNC_PROCESS}
  if FProcessHandler <> nil then
    RemoveProcessEventHandler(FProcessHandler);
  {$ELSE} // should be enough in UnhookPipeHandle;
  if FReadThread <> nil then begin
    TerminataThread;
  end;
  {$ENDIF}
end;

procedure TDebugAsyncProcess.Execute;
begin
  inherited Execute;

  {$IFdef NATIVE_ASYNC_PROCESS}
  if poUsePipes in Options then
    FPipeHandler := AddPipeEventHandler(Output.Handle, @HandlePipeInput, 0);
  FProcessHandler := AddProcessEventHandler(ProcessHandle, @HandleProcessTermination, 0);
  {$ELSE}
  if FReadThread = nil then
    FReadThread := TDebugProcessReadThread.Create(false);
  FReadThread.FStream := Output;
  FReadThread.FOnDataAvail := @ThreadDataAvail;
  FReadThread.FOnPipeError := @ThreadPipeError;
  FReadThread.Start;
  {$ENDIF}
end;

destructor TDebugAsyncProcess.Destroy;
begin
  {$IFdef NATIVE_ASYNC_PROCESS}
  UnhookProcessHandle;
  UnhookPipeHandle;
  {$ELSE}
  if FReadThread <> nil then begin
    TerminataThread;
    FReadThread.WaitFor;
debugln(['DESTROY thread destroying']);
    FreeAndNil(FReadThread);
debugln(['DESTROY thread destroyed']);
  end;
  {$ENDIF}
  inherited;
end;

function TDebugAsyncProcess.Terminate(AExitCode: Integer): Boolean;
begin
  {$ifdef NATIVE_ASYNC_PROCESS}
  UnhookProcessHandle;
  UnhookPipeHandle;
  {$ELSE}
  if FReadThread <> nil then begin
    TerminataThread;
    FReadThread.WaitFor;
debugln(['DESTROY thread destroying']);
    FreeAndNil(FReadThread);
debugln(['DESTROY thread destroyed']);
  end;
  {$ENDIF}
  Result := inherited Terminate(AExitCode);
end;

{ TDebugProcess }

procedure TDebugProcess.DoReadData(Sender: TObject);
  function ReadData(const AStream: TInputPipeStream; var ABuffer: String): Integer;
  var
    c: LongInt;
  begin
    Result := 0;
    c := AStream.Read(FTmpBuffer[1], DBG_STREAM_READ_LEN);
    while c > 0 do begin
      SetLength(ABuffer, Length(ABuffer)+c);
      Move(FTmpBuffer[1], ABuffer[1 + Result], c);
      Result := Result + c;
      if (c = DBG_STREAM_READ_LEN) and HandleHasData(AStream.Handle) then begin
        c := AStream.Read(FTmpBuffer[1], DBG_STREAM_READ_LEN);
      end
      else
        c := 0;
    end;
  end;
  function LineEndPos(const s: string; out LineEndLen: integer): integer;
  var
    n, idx: Integer;
  begin
    LineEndLen := 0;
    Result := pos(#10, s);
    n := pos(#13, s);
    if (n > 0) and (n < Result) then
      Result := n;

    if Result = 0 then exit;
    LineEndLen := 1;
    if Result < Length(s) then begin
      if (s[Result+1] in [#10,#13]) and (s[Result+1] <> s[Result]) then
        LineEndLen := 2;
    end;
  end;

var
  LineEndIdx, LineEndLen: Integer;
  Line: String;
begin
  if not DebugProcessRunning then begin
    StopDebugProcess;
    exit;
  end;

  if (FDbgProcess.Output <> nil) then
    ReadData(FDbgProcess.Output, Line);
  FOutputBuf := FOutputBuf + Line;

  FDbgProcess.FinishedReadingOutput; // Allow new reads, while we are processing

  if FLockReadData or (FOutputBuf = '') then
    exit;

  try
    FLockReadData := True;
    if FOnBeginLinesReceived <> nil then  // use to UnlockRelease
      FOnBeginLinesReceived(Self);

    LineEndIdx := LineEndPos(FOutputBuf, LineEndLen);
    while (LineEndIdx > 0) do begin
      Dec(LineEndIdx);
      Line := Copy(FOutputBuf, 1, LineEndIdx);
      Delete(FOutputBuf, 1, LineEndIdx + LineEndLen);

      if ((DBG_CMD_ECHO_FULL <> nil) and (DBG_CMD_ECHO_FULL^. Enabled))
      then debugln(DBG_CMD_ECHO_FULL, '<< << TCmdLineDebugger.ReadLn "',Line,'"')
      else if (length(Line) < 300)
      then debugln(DBG_CMD_ECHO, '<< << TCmdLineDebugger.ReadLn "',Line,'"')
      else debugln(DBG_CMD_ECHO, ['<< << TCmdLineDebugger.ReadLn "',copy(Line, 1, 200), '" ..(',length(Line)-300,').. "',copy(Line, length(Line)-99, 100),'"']);

      if FOnLineReceived <> nil then
        FOnLineReceived(Self, Line);

      LineEndIdx := LineEndPos(FOutputBuf, LineEndLen);
    end;

  finally
    FLockReadData := False;
    if FOnEndLinesReceived <> nil then  // use to LockRelease
      FOnEndLinesReceived(Self);
    // Debugger and Self may get destroyed at this point
  end;
end;

procedure TDebugProcess.DoTerminate(Sender: TObject);
begin
  if FOnTerminate <> nil then
    FOnTerminate(Self);
end;

function TDebugProcess.GetDbgProcess: TProcessUTF8;
begin
  Result := FDbgProcess;
end;

function TDebugProcess.HandleHasData(const AHandle: Integer): Boolean;
{$IFDEF UNIX}
var
  R: Integer;
  FDS: TFDSet;
begin
  Result := False;
  if AHandle < 0 then
    exit;

  FpFD_ZERO(FDS);
  FpFD_Set(AHandle, FDS);
  // R = -1 on error, 0 on timeout, >0 on success and is number of handles
  // FDS is changed, and indicates what descriptors have changed
  R := FpSelect(AHandle + 1, @FDS, nil, nil, 1);

  Result := (R > 0) and (FpFD_ISSET(AHandle,FDS)=1);
end;
{$ELSE linux}
{$IFdef MSWindows}
var
  TotalBytesAvailable: dword;
  R: LongBool;
begin
  R := Windows.PeekNamedPipe(AHandle, nil, 0, nil, @TotalBytesAvailable, nil);
  if not R then begin
    // PeekNamedPipe failed
    DebugLn(DBG_WARNINGS, ['PeekNamedPipe failed, GetLastError is ', GetLastError]);
    Exit;
  end;
  Result := TotalBytesAvailable > 0;
end;
{$ELSE win32}
begin
  DebugLn('ToDo: implement WaitForHandles for this OS');
  Result := 0;
end;
{$ENDIF win32}
{$ENDIF linux}


function TDebugProcess.GetDebugProcessRunning: Boolean;
begin
  Result := (FDbgProcess <> nil) and FDbgProcess.Running;
end;

constructor TDebugProcess.Create(const AExternalDebugger: String);
begin
  FDbgProcess := nil;
  FExternalDebugger := AExternalDebugger;
  SetLength(FTmpBuffer, DBG_STREAM_READ_LEN);
  inherited Create;
end;

destructor TDebugProcess.Destroy;
begin
  if DebugProcessRunning then
    StopDebugProcess;  // calls  FDbgProcess.Release;

  try
    FDbgProcess.Destroy;
  except
    on E: Exception do DebugLn(DBG_WARNINGS, 'Exception while freeing debugger: ', E.Message);
  end;
  inherited Destroy;
end;

function TDebugProcess.CreateDebugProcess(const AOptions: String;
  AnEnvironment: TStrings): Boolean;
begin
  Result := False;

  if FDbgProcess = nil
  then begin
    FDbgProcess := TDebugAsyncProcess.Create(nil);
    try
      FDbgProcess.Options:= [poUsePipes, poNoConsole, poStdErrToOutPut, poNewProcessGroup];
      {$if defined(windows) and not defined(wince)}
      // under win9x and winMe should be created with console,
      // otherwise no break can be send.
      if Win32MajorVersion <= 4 then
        FDbgProcess.Options:= [poUsePipes, poNewConsole, poStdErrToOutPut, poNewProcessGroup];
      {$endif windows}
      FDbgProcess.ShowWindow := swoNone;
    except
      FreeAndNil(FDbgProcess);
    end;
  end;
  if FDbgProcess = nil then exit;

  FDbgProcess.ParseCmdLine(FExternalDebugger + ' ' + AOptions);
  FDbgProcess.Environment:= AnEnvironment;
  FDbgProcess.OnReadData := @DoReadData;
  FDbgProcess.OnTerminate := @DoTerminate;

  if not FDbgProcess.Running
  then begin
    try
      FDbgProcess.Execute;
      DebugLn(DBG_VERBOSE, '[TDebugProcess] Debug PID: ', IntToStr(FDbgProcess.Handle));
      Result := FDbgProcess.Running;
    except
      on E: Exception do begin
        FOutputBuf := E.Message;
        DebugLn(DBG_WARNINGS, 'Exception while executing debugger: ', FOutputBuf);
      end;
    end;
  end;

end;

procedure TDebugProcess.StopDebugProcess;
begin
debugln(['TDebugProcess.StopDebugProcess FDbgProcess = nil ',FDbgProcess = nil]);
  if FDbgProcess = nil then exit;

  FDbgProcess.Terminate(0);
end;

procedure TDebugProcess.SendCmdLn(const ACommand: String);
const
  LE: string = LineEnding;
begin
  if (DBG_CMD_ECHO_FULL <> nil) and (DBG_CMD_ECHO_FULL^.Enabled)
  then debugln(DBG_CMD_ECHO_FULL, '>> >> TDebugProcess.SendCmdLn "',ACommand,'"')
  else debugln(DBG_CMD_ECHO,      '>> >> TDebugProcess.SendCmdLn "',ACommand,'"');

  if DebugProcessRunning
  then begin
    if FOnLineSent <> nil then
      FOnLineSent(Self, ACommand);

    if ACommand <> ''
    then FDbgProcess.Input.Write(ACommand[1], Length(ACommand));
    FDbgProcess.Input.Write(LE[1], Length(LE));
  end
  else begin
    DebugLn(DBG_WARNINGS, '[TDebugProcess.SendCmdLn] Unable to send <', ACommand, '>. No process running.');
    if FOnSendError <> nil then
      FOnSendError(Self, ACommand);
  end;
end;

procedure TDebugProcess.SendCmdLn(const ACommand: String;
  Values: array of const);
begin
  SendCmdLn(Format(ACommand, Values));
end;

initialization
  DBG_CMD_ECHO      := DebugLogger.FindOrRegisterLogGroup('DBG_CMD_ECHO' {$IF defined(DBG_VERBOSE) or defined(DBG_CMD_ECHO)} , True {$ENDIF} );
  DBG_CMD_ECHO_FULL := DebugLogger.FindOrRegisterLogGroup('DBG_CMD_ECHO_FULL' {$IF defined(DBG_VERBOSE_FULL_DATA) or defined(DBG_CMD_ECHO_FULL)} , True {$ENDIF} );
  DBG_VERBOSE := DebugLogger.FindOrRegisterLogGroup('DBG_VERBOSE' {$IFDEF DBG_VERBOSE} , True {$ENDIF} );
  DBG_WARNINGS := DebugLogger.FindOrRegisterLogGroup('DBG_WARNINGS' {$IFDEF DBG_WARNINGS} , True {$ENDIF} );

end.