File: fpdcommand.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 (925 lines) | stat: -rw-r--r-- 25,478 bytes parent folder | download | duplicates (2)
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
{ $Id: fpdcommand.pas 54031 2017-01-29 21:04:32Z joost $ }
{
 ---------------------------------------------------------------------------
 fpdcommand.pas  -  FP standalone debugger - Command interpreter
 ---------------------------------------------------------------------------

 This unit contains handles all debugger commands

 ---------------------------------------------------------------------------

 @created(Mon Apr 10th WET 2006)
 @lastmod($Date: 2017-01-29 22:04:32 +0100 (So, 29 Jan 2017) $)
 @author(Marc Weustink <marc@@dommelstein.nl>)

 ***************************************************************************
 *                                                                         *
 *   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 FPDCommand;
{$mode objfpc}{$H+}
interface

uses
  SysUtils, Classes,
{$ifdef windows}
  Windows,
{$endif}
  LCLProc, FpDbgInfo, FpDbgClasses, DbgIntfBaseTypes, FpDbgUtil, CustApp,
  FpPascalParser,
  FPDbgController,
  FpPascalBuilder,
  FpErrorMessages;

procedure HandleCommand(ACommand: String; out CallProcessLoop: boolean);

implementation

uses
  FPDGlobal
{$ifdef windows}
  , FPDPEImage
{$endif windows}
  ;

type
  TFPDCommandHandler = procedure(AParams: String; out CallProcessLoop: boolean);

  TFPDCommand = class
  private
    FCommand: String;
    FHandler: TFPDCommandHandler;
    FHelp: String;
  public
    constructor Create(const AHandler: TFPDCommandHandler; const ACommand, AHelp: String);
    property Command: String read FCommand;
    property Handler: TFPDCommandHandler read FHandler;
    property Help: String read FHelp;
  end;

  { TFPDCommandList }

  TFPDCommandList = class
  private
    FCommands: TStringList;
    function GetItem(const AIndex: Integer): TFPDCommand;
  public
    procedure AddCommand(const ACommands: array of String; const AHandler: TFPDCommandHandler; const AHelp: String);
    function Count: Integer;
    constructor Create;
    destructor Destroy; override;
    function FindCommand(const ACommand: String): TFPDCommand;
    procedure HandleCommand(ACommand: String; out CallProcessLoop: boolean);
    property Items[const AIndex: Integer]: TFPDCommand read GetItem; default;
  end;


var
  MCommands: TFPDCommandList;
  MShowCommands: TFPDCommandList;
  MSetCommands: TFPDCommandList;

resourcestring
  sAddBreakpoint = 'Breakpoint added at address %s.';
  sAddBreakpointFailed = 'Adding breakpoint at %s failed.';
  sRemoveBreakpoint = 'Breakpoint removed from address %s.';
  sRemoveBreakpointFailed = 'Removing breakpoint at %s failed.';

procedure HandleCommand(ACommand: String; out CallProcessLoop: boolean);
begin
  MCommands.HandleCommand(ACommand, CallProcessLoop);
end;


procedure HandleHelp(AParams: String; out CallProcessLoop: boolean);
var
  n: Integer;
  cmd: TFPDCommand;
begin
  CallProcessLoop:=false;
  if AParams = ''
  then begin
    WriteLN('Available commands:');
    for n := 0 to MCommands.Count - 1 do
      WriteLN(' ', MCommands[n].Command);
    end
  else begin
    cmd := MCommands.FindCommand(AParams);
    if cmd = nil
    then WriteLN('Unknown command: "', AParams, '"')
    else WriteLN(cmd.Help);
  end;
end;

procedure HandleFile(AParams: String; out CallProcessLoop: boolean);
begin
  if AParams <> ''
  then GController.ExecutableFilename := AParams;

  CallProcessLoop:=false;
  // TODO separate exec from args
end;

procedure HandleShow(AParams: String; out CallProcessLoop: boolean);
var
  cmd: TFPDCommand;
  S: String;
begin
  CallProcessLoop:=false;
  S := GetPart([], [' ', #9], AParams);
  if S = '' then S := 'help';
  cmd := MShowCommands.FindCommand(S);
  if cmd = nil
  then WriteLN('Unknown item: "', S, '"')
  else cmd.Handler(Trim(AParams), CallProcessLoop);
end;

procedure HandleSet(AParams: String; out CallProcessLoop: boolean);
var
  cmd: TFPDCommand;
  S: String;
begin
  S := GetPart([], [' ', #9], AParams);
  if S = '' then S := 'help';
  cmd := MSetCommands.FindCommand(S);
  if cmd = nil
  then WriteLN('Unknown param: "', S, '"')
  else cmd.Handler(Trim(AParams), CallProcessLoop);
end;

procedure HandleRun(AParams: String; out CallProcessLoop: boolean);
var
  AParamList: TStringList;
begin
  CallProcessLoop:=false;
  if Assigned(GController.MainProcess)
  then begin
    WriteLN('The debuggee is already running');
    Exit;
  end;

  if GController.ExecutableFilename = ''
  then begin
    WriteLN('No filename set');
    Exit;
  end;

  if AParams<>'' then begin
    AParamList := TStringList.Create;
    try
      AParamList.Text:=AParams;
      GController.Params.Assign(AParamList);
    finally
      AParamList.free;
    end;
  end;

  if not GController.Run then
    writeln('Failed to run '+GController.ExecutableFilename)
  else
    CallProcessLoop:=true;
end;

procedure HandleBreak(AParams: String; out CallProcessLoop: boolean);
var
  S, P: String;
  Remove: Boolean;
  Address: TDbgPtr;
  e: Integer;
  Line: Cardinal;
  bp: TDbgBreakpoint;

  AContext: TFpDbgInfoContext;
  AValue: TFpDbgValue;

begin
  CallProcessLoop:=false;
  if GController.MainProcess = nil
  then begin
    WriteLN('No Process');
    Exit;
  end;

  S := AParams;
  P := GetPart([], [' ', #9], S);
  Remove := P = '-d';
  if not Remove
  then S := P;
  
  if S = ''
  then begin
    // current addr
    P := '';
    Address := GController.CurrentProcess.GetInstructionPointerRegisterValue;
  end
  else begin
    P := GetPart([], [':'], S);
  end;
  
  if S = ''
  then begin
    if P <> ''
    then begin
      // address given
      Val(P, Address, e);
      if e <> 0
      then begin
        AContext := GController.CurrentProcess.SymbolTableInfo.FindContext(GController.CurrentProcess.GetInstructionPointerRegisterValue);
        if AContext = nil then begin
          Writeln('Invalid context');
          exit;
        end;
        AValue := AContext.FindSymbol(P);
        if not assigned(AValue) then begin
          WriteLN('Illegal address/unknown symbol: ', P);
          Exit;
        end;
        Address:=AValue.Address.Address;
      end;
    end;
    if Remove
    then begin
      if GController.CurrentProcess.RemoveBreak(Address)
      then WriteLn(format(sRemoveBreakpoint,[FormatAddress(Address)]))
      else WriteLn(Format(sRemoveBreakpointFailed, [FormatAddress(Address)]));
    end
    else begin
      if GController.CurrentProcess.AddBreak(Address) <> nil
      then WriteLn(format(sAddBreakpoint, [FormatAddress(Address)]))
      else WriteLn(Format(sAddBreakpointFailed, [FormatAddress(Address)]));
    end;
  end
  else begin
    S := GetPart([':'], [], S);
    Val(S, Line, e);
    if e <> 0
    then begin
      WriteLN('Illegal line: ', S);
      Exit;
    end;
    if Remove
    then begin
      if TDbgInstance(GController.CurrentProcess).RemoveBreak(P, Line)
      then WriteLn('breakpoint removed')
      else WriteLn('remove breakpoint failed');
      Exit;
    end;

    bp := TDbgInstance(GController.CurrentProcess).AddBreak(P, Line);
    if bp = nil
    then begin
      WriteLn(Format(sAddBreakpointFailed, [S]));
      Exit;
    end;
    
    WriteLn(format(sAddBreakpoint, [FormatAddress(bp.Location)]))
  end;
end;

procedure HandleContinue(AParams: String; out CallProcessLoop: boolean);
begin
  CallProcessLoop:=false;
  if not assigned(GController.MainProcess)
  then begin
    WriteLN('The process is not paused');
    Exit;
  end;

  CallProcessLoop:=true;
end;

procedure HandleKill(AParams: String; out CallProcessLoop: boolean);
begin
  CallProcessLoop:=false;
  if not assigned(GController.MainProcess)
  then begin
    WriteLN('No process');
    Exit;
  end;

  WriteLN('Terminating ...');
  GController.Stop;
  CallProcessLoop:=true;
end;

procedure HandleNextInst(AParams: String; out CallProcessLoop: boolean);
begin
  CallProcessLoop:=false;
  if not assigned(GController.MainProcess)
  then begin
    WriteLN('The process is not paused');
    Exit;
  end;
  GController.StepOverInstr;
  CallProcessLoop:=true;
end;

procedure HandleNext(AParams: String; out CallProcessLoop: boolean);
begin
  CallProcessLoop:=false;
  if not assigned(GController.MainProcess)
  then begin
    WriteLN('The process is not paused');
    Exit;
  end;
  GController.Next;
  CallProcessLoop:=true;
end;

procedure HandleStep(AParams: String; out CallProcessLoop: boolean);
begin
  CallProcessLoop:=false;
  if not assigned(GController.MainProcess)
  then begin
    WriteLN('The process is not paused');
    Exit;
  end;
  GController.Step;
  CallProcessLoop:=true;
end;

procedure HandleStepOut(AParams: String; out CallProcessLoop: boolean);
begin
  CallProcessLoop:=false;
  if not assigned(GController.MainProcess)
  then begin
    WriteLN('The process is not paused');
    Exit;
  end;
  GController.StepOut;
  CallProcessLoop:=true;
end;

procedure HandleStepInst(AParams: String; out CallProcessLoop: boolean);
begin
  CallProcessLoop:=false;
  if not assigned(GController.MainProcess)
  then begin
    WriteLN('The process is not paused');
    Exit;
  end;
  GController.StepIntoInstr;
  CallProcessLoop:=true;
end;

procedure HandleList(AParams: String; out CallProcessLoop: boolean);
begin
  WriteLN('not implemented: list');
  CallProcessLoop:=false;
end;

procedure HandleMemory(AParams: String; out CallProcessLoop: boolean);
// memory [-<size>] [<adress> <count>|<location> <count>]
var
  P: array[1..3] of String;
  Size, Count: Integer;
  Address: QWord;
  e, idx: Integer;
  buf: array[0..256*16 - 1] of Byte;
  BytesRead: Cardinal;
begin
  CallProcessLoop:=false;
  if GController.MainProcess = nil
  then begin
    WriteLN('No process');
    Exit;
  end;

  P[1] := GetPart([], [' ', #9], AParams);
  P[2] := GetPart([' ', #9], [' ', #9], AParams);
  P[3] := GetPart([' ', #9], [' ', #9], AParams);

  idx := 1;
  Count := 1;
  Size := 4;

  Address := GController.CurrentProcess.GetInstructionPointerRegisterValue;

  if P[idx] <> ''
  then begin
    if P[idx][1] = '-'
    then begin
      Size := -StrToIntDef(P[idx], -Size);
      if not (Size in [1,2,4,8,16])
      then begin
        WriteLN('Illegal size: "', P[idx], '"');
        Exit;
      end;
      Inc(idx);
    end;
    if P[idx] <> ''
    then begin
      if P[idx][1] = '%'
      then begin

      end
      else begin
        Val(P[idx], Address, e);
        if e <> 0
        then begin
          WriteLN('Location "',P[idx],'": Symbol resolving not implemented');
          Exit;
        end;
      end;
      Inc(idx);
    end;

    if P[idx] <> ''
    then begin
      Count := StrToIntDef(P[idx], Count);
      if Count > 256
      then begin
        WriteLN('Limiting count to 256');
        Count := 256;
      end;
      Inc(idx);
    end;
  end;


  BytesRead := Count * Size;
  if not GController.MainProcess.ReadData(Address, BytesRead, buf)
  then begin
    WriteLN('Could not read memory at: ', FormatAddress(Address));
    Exit;
  end;

  e := 0;
  while BytesRead >= size do
  begin
    if e and ((32 div Size) - 1) = 0
    then Write('[', FormatAddress(Address), '] ');

    for idx := Size - 1 downto 0 do Write(IntToHex(buf[e * size + idx], 2));

    Inc(e);
    if e = 32 div Size
    then WriteLn
    else Write(' ');
    Dec(BytesRead, Size);
    Inc(Address, Size);
  end;
  if e <> 32 div Size
  then WriteLn;
end;

procedure HandleWriteMemory(AParams: String; out CallProcessLoop: boolean);
// memory [<adress> <value>]
var
  P: array[1..2] of String;
  Size, Count: Integer;
  Address: QWord;
  Value: QWord;
  e, idx: Integer;
  buf: array[0..256*16 - 1] of Byte;
  BytesRead: Cardinal;
begin
  CallProcessLoop:=false;
  if GController.MainProcess = nil
  then begin
    WriteLN('No process');
    Exit;
  end;

  P[1] := GetPart([], [' ', #9], AParams);
  P[2] := GetPart([' ', #9], [' ', #9], AParams);

  idx := 1;
  Count := 1;
  Size := 4;

  if P[idx] <> ''
  then begin
    if P[idx] <> ''
    then begin
      Val(P[idx], Address, e);
      if e <> 0
      then begin
        WriteLN('Location "',P[idx],'": Symbol resolving not implemented');
        Exit;
      end;
      Inc(idx);
    end;

    if P[idx] <> ''
    then begin
      Val(P[idx], Value, e);
      if e <> 0
      then begin
        WriteLN('Value "',P[idx],'": Symbol resolving not implemented');
        Exit;
      end;
      Inc(idx);
    end;
  end;


  if not GController.MainProcess.WriteData(Address, 4, Value)
  then begin
    WriteLN('Could not write memory at: ', FormatAddress(Address));
    Exit;
  end;
end;


procedure HandleDisas(AParams: String; out CallProcessLoop: boolean);
begin
  CallProcessLoop:=false;
  WriteLN('not implemented: disassemble');
end;

procedure HandleEval(AParams: String; out CallProcessLoop: boolean);
var
  AContext: TFpDbgInfoContext;
  APasExpr: TFpPascalExpression;
  APrettyPrinter: TFpPascalPrettyPrinter;
  AVal: string;
  s,p: string;
begin
  if GController.MainProcess = nil
  then begin
    WriteLN('No Process');
    Exit;
  end;
  CallProcessLoop:=false;

  S := AParams;
  P := GetPart([], [' ', #9], S);

  AContext := GController.CurrentProcess.DbgInfo.FindContext(GController.CurrentProcess.GetInstructionPointerRegisterValue);
  if AContext = nil then begin
    Writeln('Invalid context');
    exit;
  end;

  APasExpr := TFpPascalExpression.Create(P, AContext);
  try
    APasExpr.ResultValue; // trigger full validation
    if not APasExpr.Valid then
      begin
      writeln(ErrorHandler.ErrorAsString(APasExpr.Error));
      end
    else
      begin
      APrettyPrinter := TFpPascalPrettyPrinter.Create(4);
      try
        APrettyPrinter.AddressSize:=AContext.SizeOfAddress;
        if APrettyPrinter.PrintValue(AVal, APasExpr.ResultValue) then
          begin
          Writeln(AVal)
          end
        else
          writeln('Invalid value');
      finally
        APrettyPrinter.Free;
      end;
      end;
  finally
    APasExpr.Free;
    AContext.ReleaseReference;
  end;
end;

procedure HandleQuit(AParams: String; out CallProcessLoop: boolean);
begin
  WriteLN('Quitting ...');
  if assigned(GController.MainProcess) then
  begin
    WriteLn('Killing application ...');
    GController.Stop;
    CallProcessLoop:=true;
  end
  else
    CallProcessLoop := false;
  CustomApplication.Terminate;
end;

//=================
// S H O W
//=================

procedure HandleShowHelp(AParams: String; out CallProcessLoop: boolean);
var
  n: Integer;
  cmd: TFPDCommand;
begin
  CallProcessLoop:=false;
  if AParams = ''
  then begin
    WriteLN('Available items:');
    for n := 0 to MShowCommands.Count - 1 do
      WriteLN(' ', MShowCommands[n].Command);
    end
  else begin
    cmd := MShowCommands.FindCommand(AParams);
    if cmd = nil
    then WriteLN('Unknown item: "', AParams, '"')
    else WriteLN(cmd.Help);
  end;
end;

procedure HandleShowFile(AParams: String; out CallProcessLoop: boolean);
var
  hFile, hMap: THandle;
  FilePtr: Pointer;
begin
  CallProcessLoop:=false;
  if GController.ExecutableFilename = ''
  then begin
    WriteLN('No filename set');
    Exit;
  end;
{$ifdef windows}
  hFile := CreateFile(PChar(GController.ExecutableFilename), GENERIC_READ, FILE_SHARE_READ, nil, OPEN_EXISTING, FILE_FLAG_RANDOM_ACCESS, 0);
  if hFile = INVALID_HANDLE_VALUE
  then begin
    WriteLN('File "', GController.ExecutableFilename, '" does not exist');
    Exit;
  end;

  hMap := 0;
  FilePtr := nil;
  try
    hMap := CreateFileMapping(hFile, nil, PAGE_READONLY{ or SEC_IMAGE}, 0, 0, nil);
    if hMap = 0
    then begin
      WriteLN('Map error');
      Exit;
    end;

    FilePtr := MapViewOfFile(hMap, FILE_MAP_READ, 0, 0, 0);
    DumpPEImage(GetCurrentProcess, TDbgPtr(FilePtr));
  finally
    UnmapViewOfFile(FilePtr);
    CloseHandle(hMap);
    CloseHandle(hFile);
  end;
{$endif windows}
end;

procedure HandleShowRegisters(AParams: String; out CallProcessLoop: boolean);
var
  ARegisterValue: TDbgRegisterValue;
  i: Integer;
begin
  CallProcessLoop:=false;
  if (GController.MainProcess = nil)
  then begin
    WriteLN('No process');
    Exit;
  end;

  for i := 0 to GController.CurrentThread.RegisterValueList.Count-1 do
  begin
    ARegisterValue := GController.CurrentThread.RegisterValueList[i];
    writeln(format('%7s: %s (%s)',[ARegisterValue.Name, FormatAddress(ARegisterValue.NumValue), ARegisterValue.StrValue]));
  end;
end;

procedure HandleShowCallStack(AParams: String; out CallProcessLoop: boolean);
var
  ACallStack: TDbgCallstackEntryList;
  i: Integer;
begin
  CallProcessLoop:=false;
  if (GController.MainProcess = nil)
  then begin
    WriteLN('No process');
    Exit;
  end;

  WriteLN('Callstack:');
  ACallStack := GController.CurrentProcess.MainThread.CreateCallStackEntryList;
  try
    for i := 0 to ACallStack.Count-1 do
    begin
      write(' ', FormatAddress(ACallStack.Items[i].AnAddress),' ');
      if ACallStack.Items[i].SourceFile<>'' then
        writeln(ACallStack.Items[i].SourceFile,':',ACallStack.Items[i].Line)
      else
        writeln('unknown');
    end;
  finally
    ACallStack.Free;
  end;
end;

//=================
// S E T
//=================

procedure HandleSetHelp(AParams: String; out CallProcessLoop: boolean);
var
  n: Integer;
  cmd: TFPDCommand;
begin
  CallProcessLoop:=false;
  if AParams = ''
  then begin
    WriteLN('Usage: set param [<value>] When no value is given, the current value is shown.');
    WriteLN('Available params:');
    for n := 0 to MSetCommands.Count - 1 do
      WriteLN(' ', MSetCommands[n].Command);
    end
  else begin
    cmd := MSetCommands.FindCommand(AParams);
    if cmd = nil
    then WriteLN('Unknown param: "', AParams, '"')
    else WriteLN(cmd.Help);
  end;
end;

procedure HandleSetMode(AParams: String; out CallProcessLoop: boolean);
const
  MODE: array[TFPDMode] of String = ('32', '64');
begin
  CallProcessLoop:=false;
  if AParams = ''
  then WriteLN(' Mode: ', MODE[GMode])
  else if AParams = '32'
  then GMode := dm32
  else if AParams = '64'
  then GMode := dm64
  else WriteLN('Unknown mode: "', AParams, '"')
end;

procedure HandleSetBoll(AParams: String; out CallProcessLoop: boolean);
const
  MODE: array[Boolean] of String = ('off', 'on');
begin
  CallProcessLoop:=false;
  if AParams = ''
  then WriteLN(' Break on library load: ', MODE[GBreakOnLibraryLoad])
  else GBreakOnLibraryLoad := (Length(Aparams) > 1) and (AParams[2] in ['n', 'N'])
end;

procedure HandleSetImageInfo(AParams: String; out CallProcessLoop: boolean);
const
  MODE: array[TFPDImageInfo] of String = ('none', 'name', 'detail');
begin
  CallProcessLoop:=false;
  if AParams = ''
  then WriteLN(' Imageinfo: ', MODE[GImageInfo])
  else begin
    case StringCase(AParams, MODE, True, False) of
      0: GImageInfo := iiNone;
      1: GImageInfo := iiName;
      2: GImageInfo := iiDetail;
    else
      WriteLN('Unknown type: "', AParams, '"')
    end;
  end;
end;


//=================
//=================
//=================

{ TFPDCommand }

constructor TFPDCommand.Create(const AHandler: TFPDCommandHandler; const ACommand, AHelp: String);
begin
  inherited Create;
  FCommand := ACommand;
  FHandler := AHandler;
  FHelp := AHelp;
end;

{ TFPDCommandList }

procedure TFPDCommandList.AddCommand(const ACommands: array of String; const AHandler: TFPDCommandHandler; const AHelp: String);
var
  n: Integer;
begin
  for n := Low(ACommands) to High(ACommands) do
    FCommands.AddObject(ACommands[n], TFPDCommand.Create(AHandler, ACommands[n], AHelp));
end;

function TFPDCommandList.Count: Integer;
begin
  Result := FCommands.Count;
end;

constructor TFPDCommandList.Create;
begin
  inherited;
  FCommands := TStringList.Create;
  FCommands.Duplicates := dupError;
  FCommands.Sorted := True;
end;

destructor TFPDCommandList.Destroy;
var
  n: integer;
begin
  for n := 0 to FCommands.Count - 1 do
    FCommands.Objects[n].Free;
  FreeAndNil(FCommands);
  inherited;
end;

function TFPDCommandList.FindCommand(const ACommand: String): TFPDCommand;
var
  idx: Integer;
begin
  idx := FCommands.IndexOf(ACommand);
  if idx = -1
  then Result := nil
  else Result := TFPDCommand(FCommands.Objects[idx]);
end;

function TFPDCommandList.GetItem(const AIndex: Integer): TFPDCommand;
begin
  Result := TFPDCommand(FCommands.Objects[AIndex]);
end;

procedure TFPDCommandList.HandleCommand(ACommand: String; out CallProcessLoop: boolean);
var
  cmd: TFPDCommand;
  S: String;
begin
  S := GetPart([], [' ', #9], ACommand);
  cmd := FindCommand(S);
  if cmd = nil
  then
  begin
    WriteLN('Unknown command: "', S, '"');
    CallProcessLoop:=false;
  end
  else cmd.Handler(Trim(ACommand), CallProcessLoop);
end;

//=================
//=================
//=================

procedure Initialize;
begin
  MCommands := TFPDCommandList.Create;

  MCommands.AddCommand(['help', 'h', '?'], @HandleHelp, 'help [<command>]: Shows help on a command, or this help if no command given');
  MCommands.AddCommand(['quit', 'q'], @HandleQuit,  'quit: Quits the debugger');
  MCommands.AddCommand(['file', 'f'], @HandleFile, 'file <filename>: Loads the debuggee <filename>');
  MCommands.AddCommand(['show', 's'], @HandleShow, 'show <info>: Enter show help for more info');
  MCommands.AddCommand(['set'], @HandleSet,  'set param: Enter set help for more info');
  MCommands.AddCommand(['run', 'r'], @HandleRun,  'run [params]: Starts the loaded debuggee');
  MCommands.AddCommand(['break', 'b'], @HandleBreak,  'break [-d] <adress>|<filename:line>: Set a breakpoint at <adress> or <filename:line>. -d removes');
  MCommands.AddCommand(['continue', 'cont', 'c'], @HandleContinue,  'continue: Continues execution');
  MCommands.AddCommand(['kill', 'k'], @HandleKill,  'kill: Stops execution of the debuggee');
  MCommands.AddCommand(['step-inst', 'si'], @HandleStepInst,  'step-inst: Steps-into one instruction');
  MCommands.AddCommand(['next-inst', 'ni'], @HandleNextInst,  'next-inst: Steps-over one instruction');
  MCommands.AddCommand(['next', 'n'], @HandleNext,  'next: Steps one line');
  MCommands.AddCommand(['step', 'st'], @HandleStep,  'step: Steps one line into procedure');
  MCommands.AddCommand(['step-out', 'so'], @HandleStepOut,  'step-out: Steps out of current procedure');
  MCommands.AddCommand(['list', 'l'], @HandleList,  'list [<adress>|<location>]: Lists the source for <adress> or <location>');
  MCommands.AddCommand(['memory', 'mem', 'm'], @HandleMemory,  'memory [-<size>] [<adress> <count>|<location> <count>]: Dump <count> (default: 1) from memory <adress> or <location> (default: current) of <size> (default: 4) bytes, where size is 1,2,4,8 or 16.');
  MCommands.AddCommand(['writememory', 'w'], @HandleWriteMemory,  'writememory [<adress> <value>]: Write <value> (with a length of 4 bytes) into memory at address <adress>.');
  MCommands.AddCommand(['disassemble', 'dis', 'd'], @HandleDisas,  'disassemble [<adress>|<location>] [<count>]: Disassemble <count> instructions from <adress> or <location> or current IP if none given');
  MCommands.AddCommand(['evaluate', 'eval', 'e'], @HandleEval,  'evaluate <symbol>: Evaluate <symbol>');


  MShowCommands := TFPDCommandList.Create;

  MShowCommands.AddCommand(['help', 'h', '?'], @HandleShowHelp, 'show help [<info>]: Shows help for info or this help if none given');
  MShowCommands.AddCommand(['file', 'f'], @HandleShowFile, 'show file: Shows the info for the current file');
  MShowCommands.AddCommand(['callstack', 'c'], @HandleShowCallStack,  'show callstack: Shows the callstack');
  MShowCommands.AddCommand(['registers', 'r'], @HandleShowRegisters,  'show registers: Show the values of all registers');

  MSetCommands := TFPDCommandList.Create;

  MSetCommands.AddCommand(['help', 'h', '?'], @HandleSetHelp, 'set help [<param>]: Shows help for param or this help if none given');
  MSetCommands.AddCommand(['mode', 'm'], @HandleSetMode, 'set mode 32|64: Set the mode for retrieving process info');
  MSetCommands.AddCommand(['break_on_library_load', 'boll'], @HandleSetBOLL, 'set break_on_library_load on|off: Pause running when a library is loaded (default off)');
  MSetCommands.AddCommand(['imageinfo', 'ii'], @HandleSetImageInfo, 'set imageinfo none|name|detail: When a library is loaded, show nothing, only its name or all details (default none)');
end;

procedure Finalize;
begin
  FreeAndNil(MCommands);
  FreeAndNil(MSetCommands);
  FreeAndNil(MShowCommands);
end;

initialization
  Initialize;

finalization
  Finalize;

end.