/
Debugger.cpp
2894 lines (2499 loc) · 83.4 KB
/
Debugger.cpp
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
/*
Debugger.cpp - Main body of AutoHotkey debugger engine.
Original code by Steve Gray.
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, without restriction.
*/
#include "stdafx.h"
#include "defines.h"
#include "globaldata.h" // for access to many global vars
#include "script_object.h"
#include "script_com.h"
#include "TextIO.h"
//#include "Debugger.h" // included by globaldata.h
#ifdef CONFIG_DEBUGGER
// helper macro for WriteF()
#define U4T(s) CStringUTF8FromTChar(s).GetString()
#include <ws2tcpip.h>
#include <wspiapi.h> // for getaddrinfo() on versions of Windows earlier than XP.
#include <stdarg.h>
#include <typeinfo> // for typeid().
Debugger g_Debugger;
CStringA g_DebuggerHost;
CStringA g_DebuggerPort;
// The first breakpoint uses sMaxId + 1. Don't change this without also changing breakpoint_remove.
int Breakpoint::sMaxId = 0;
Debugger::CommandDef Debugger::sCommands[] =
{
{"run", &run},
{"step_into", &step_into},
{"step_over", &step_over},
{"step_out", &step_out},
{"break", &_break},
{"stop", &stop},
{"detach", &detach},
{"status", &status},
{"stack_get", &stack_get},
{"stack_depth", &stack_depth},
{"context_get", &context_get},
{"context_names", &context_names},
{"property_get", &property_get},
{"property_set", &property_set},
{"property_value", &property_value},
{"feature_get", &feature_get},
{"feature_set", &feature_set},
{"breakpoint_set", &breakpoint_set},
{"breakpoint_get", &breakpoint_get},
{"breakpoint_update", &breakpoint_update},
{"breakpoint_remove", &breakpoint_remove},
{"breakpoint_list", &breakpoint_list},
{"stdout", &redirect_stdout},
{"stderr", &redirect_stderr},
{"typemap_get", &typemap_get},
{"source", &source},
};
inline bool PreExecLineIsSlippery(Line *aLine)
{
ActionTypeType act = aLine->mActionType;
// TRY, CATCH, FINALLY: slippery.
// THROW, SWITCH: not slippery.
// CASE, BLOCK_BEGIN: slippery.
// BLOCK_END: slippery if !mAttribute (not a function-body).
return act <= ACT_BLOCK_END && act >= ACT_TRY
&& (
act <= ACT_FINALLY
|| act >= ACT_CASE && !(act == ACT_BLOCK_END && aLine->mAttribute)
);
}
inline bool BreakpointLineIsSlippery(Line *aLine)
{
ActionTypeType act = aLine->mActionType;
// ELSE: slippery.
// TRY, CATCH, FINALLY: slippery.
// THROW, SWITCH: not slippery.
// CASE, BLOCK_BEGIN: slippery.
// BLOCK_END: not slippery (can be used for "break-on-return"; also, doesn't make sense to slip to the next line?).
return (act >= ACT_TRY && act <= ACT_BLOCK_BEGIN
&& act != ACT_THROW && act != ACT_SWITCH)
|| act == ACT_ELSE;
}
// PreExecLine: aLine is about to execute; handle current line marker, breakpoints and step into/over/out.
int Debugger::PreExecLine(Line *aLine)
{
// Using this->mCurrLine might perform a little better than the alternative, at the expense of a
// small amount of complexity in stack_get (which is only called by request of the debugger client):
// mStack.mTop->line = aLine;
mCurrLine = aLine;
// Check for a breakpoint on the current line:
Breakpoint *bp = aLine->mBreakpoint;
if (bp && bp->state == BS_Enabled)
{
if (bp->temporary)
{
aLine->mBreakpoint = NULL;
delete bp;
}
return Break();
}
if ((mInternalState == DIS_StepInto
|| mInternalState == DIS_StepOver && mStack.Depth() <= mContinuationDepth
|| mInternalState == DIS_StepOut && mStack.Depth() < mContinuationDepth) // Due to short-circuit boolean evaluation, mStack.Depth() is only evaluated once and only if mInternalState is StepOver or StepOut.
// Although IF/ELSE/LOOP skips its block-begin, standalone/function-body block-begin still gets here; we want to skip it,
// unless it's the block-end of a function, to allow breaking there after a "return" to inspect variables while still in scope.
&& !PreExecLineIsSlippery(aLine)
&& aLine->mLineNumber) // Some scripts (i.e. LowLevel/code.ahk) use mLineNumber==0 to indicate the Line has been generated and injected by the script.
{
return Break();
}
// Check if a command was sent asynchronously (while the script was running).
// Such commands may also be detected via the AHK_CHECK_DEBUGGER message,
// but if the program is checking for messages infrequently or not at all,
// the check here is needed to ensure the debugger is responsive.
if (HasPendingCommand())
{
// A command was sent asynchronously.
return ProcessCommands();
}
return DEBUGGER_E_OK;
}
bool Debugger::PreThrow(ExprTokenType *aException)
{
if (!mBreakOnException)
return false;
if (mBreakOnExceptionIsTemporary)
mBreakOnException = mBreakOnExceptionWasSet = false;
mThrownToken = aException;
// The spec doesn't provide a way to differentiate between handled and unhandled exceptions,
// nor when to use the "exception" and "error" statuses, so we'll use them for that:
Break((g->ExcptMode & EXCPTMODE_CATCH) ? "exception" : "error");
bool suppress_default_handling = mThrownToken == NULL; // Signal from client via property_set.
mThrownToken = NULL;
return suppress_default_handling;
}
bool Debugger::HasPendingCommand()
// Returns true if there is data in the socket's receive buffer.
// This is used for receiving commands asynchronously.
{
u_long dataPending;
if (ioctlsocket(mSocket, FIONREAD, &dataPending) == 0)
return dataPending > 0;
return false;
}
int Debugger::EnterBreakState(char *aReason)
{
if (mInternalState != DIS_Break)
{
if (mInternalState != DIS_Starting)
// Send a response for the previous continuation command.
if (int err = SendContinuationResponse(nullptr, "break", aReason))
return err;
// Remove keyboard/mouse hooks.
if (mDisabledHooks = GetActiveHooks())
AddRemoveHooks(0, true);
// Set break state.
mInternalState = DIS_Break;
}
//else: no continuation command has been received so send no "response".
// Hooks were already removed and mDisabledHooks must not be overwritten.
return DEBUGGER_E_OK;
}
void Debugger::ExitBreakState()
{
// Restore keyboard/mouse hooks if they were previously removed.
if (mDisabledHooks)
{
AddRemoveHooks(mDisabledHooks, true);
mDisabledHooks = 0;
}
}
int Debugger::Break(char *aReason)
{
if (mInternalState == DIS_Break)
// Already in a break state, so it's likely that we are currently evaluating a
// DBGp command, such as when property_set releases an object which implements
// __delete and this causes a breakpoint to be hit. In that case we must not
// re-enter the command loop until the current command has completed.
return DEBUGGER_E_OK;
int err = EnterBreakState(aReason);
if (!err)
err = ProcessCommands();
return err;
}
const int MAX_DBGP_ARGS = 16; // More than currently necessary.
int Debugger::ProcessCommands()
{
// Disable notification of READ readiness and reset socket to synchronous mode.
u_long zero = 0;
WSAAsyncSelect(mSocket, g_hWnd, 0, 0);
ioctlsocket(mSocket, FIONBIO, &zero);
int err;
for (;;)
{
int command_length;
if (err = ReceiveCommand(&command_length))
break; // Already called FatalError().
char *command = mCommandBuf.mData;
char *args = strchr(command, ' ');
char *argv[MAX_DBGP_ARGS];
int arg_count = 0;
// transaction_id is considered optional for the following reasons:
// - The spec doesn't explicitly say it is mandatory (just "standard").
// - We don't actually need it for anything.
// - Rejecting the command doesn't seem useful.
// - It makes manually typing DBGp commands easier.
char *transaction_id = "";
if (args)
{
// Split command name and args.
*args++ = '\0';
// Split args into arg vector.
err = ParseArgs(args, argv, arg_count, transaction_id);
}
if (!err)
{
for (int i = 0; ; ++i)
{
if (i == _countof(sCommands))
{
err = DEBUGGER_E_UNIMPL_COMMAND;
break;
}
if (!strcmp(sCommands[i].mName, command))
{
// EXECUTE THE DBGP COMMAND.
err = (this->*sCommands[i].mFunc)(argv, arg_count, transaction_id);
break;
}
}
}
if (!err)
{
if (mResponseBuf.mDataUsed)
err = SendResponse();
else
err = SendStandardResponse(command, transaction_id);
if (err)
break; // Already called FatalError().
}
else if (err == DEBUGGER_E_CONTINUE)
{
ASSERT(mInternalState != DIS_Break);
// Response will be sent when the debugger breaks again.
err = DEBUGGER_E_OK;
}
else
{
// Clear the response buffer in case a response was partially written
// before the error was encountered (or the command failed because the
// response buffer is full and cannot be expanded).
mResponseBuf.Clear();
if (mSocket == INVALID_SOCKET) // Already disconnected; see FatalError().
break;
if (err = SendErrorResponse(command, transaction_id, err))
break; // Already called FatalError().
}
// Remove this command and its args from the buffer.
// (There may be additional commands following it.)
if (mCommandBuf.mDataUsed) // i.e. it hasn't been cleared as a result of disconnecting.
mCommandBuf.Remove(command_length + 1);
// If a command is received asynchronously, the debugger does not
// enter a break state. In that case, we need to return after each
// command to avoid blocking in recv().
if (mInternalState != DIS_Break)
{
// As ExitBreakState() can cause re-entry into ReceiveCommand() via the message pump,
// it is safe to call only now that the command has been removed from the buffer.
if (mInternalState != DIS_Starting) // i.e. it hasn't already been called by Disconnect().
ExitBreakState();
break;
}
}
ASSERT(mInternalState != DIS_Break);
// Register for message-based notification of data arrival. If a command
// is received asynchronously, control will be passed back to the debugger
// to process it. This allows the debugger engine to respond even if the
// script is sleeping or waiting for messages.
if (mSocket != INVALID_SOCKET)
WSAAsyncSelect(mSocket, g_hWnd, AHK_CHECK_DEBUGGER, FD_READ | FD_CLOSE);
return err;
}
int Debugger::ParseArgs(char *aArgs, char **aArgV, int &aArgCount, char *&aTransactionId)
{
aArgCount = 0;
while (*aArgs)
{
if (aArgCount == MAX_DBGP_ARGS)
return DEBUGGER_E_PARSE_ERROR;
if (*aArgs != '-')
return DEBUGGER_E_PARSE_ERROR;
++aArgs;
char arg_char = *aArgs;
if (!arg_char)
return DEBUGGER_E_PARSE_ERROR;
if (aArgs[1] == ' ' && aArgs[2] != '-')
{
// Move the arg letter onto the space.
*++aArgs = arg_char;
}
// Store a pointer to the arg letter, followed immediately by its value.
aArgV[aArgCount++] = aArgs;
if (arg_char == 'i')
{
// Handle transaction_id here to simplify many other sections.
aTransactionId = aArgs + 1;
--aArgCount;
}
if (arg_char == '-') // -- base64-encoded-data
break;
char *next_arg;
if (aArgs[1] == '"')
{
char *arg_end;
for (arg_end = aArgs + 1, next_arg = aArgs + 2; *next_arg != '"'; ++arg_end, ++next_arg)
{
if (*next_arg == '\\')
++next_arg; // Currently only \\ and \" are supported; i.e. mark next char as literal.
if (!*next_arg)
return DEBUGGER_E_PARSE_ERROR;
// Copy the value to eliminate the quotes and escape sequences.
*arg_end = *next_arg;
}
*arg_end = '\0'; // Terminate this arg.
++next_arg;
if (!*next_arg)
break;
if (strncmp(next_arg, " -", 2))
return DEBUGGER_E_PARSE_ERROR;
}
else
{
// Find where this arg's value ends and the next arg begins.
next_arg = strstr(aArgs + 1, " -");
if (!next_arg)
break;
*next_arg = '\0'; // Terminate this arg.
}
// Point aArgs to the next arg's hyphen.
aArgs = next_arg + 1;
}
return DEBUGGER_E_OK;
}
//
// DBGP COMMANDS
//
// Calculate base64-encoded size of data, including NULL terminator. org_size must be > 0 if unsigned.
#define DEBUGGER_BASE64_ENCODED_SIZE(org_size) ((((org_size)-1)/3+1)*4 +1)
DEBUGGER_COMMAND(Debugger::status)
{
if (aArgCount)
return DEBUGGER_E_INVALID_OPTIONS;
char *status;
switch (mInternalState)
{
case DIS_Starting: status = "starting"; break;
case DIS_Break: status = "break"; break;
default: status = "running";
}
return mResponseBuf.WriteF(
"<response command=\"status\" status=\"%s\" reason=\"ok\" transaction_id=\"%e\"/>"
, status, aTransactionId);
}
DEBUGGER_COMMAND(Debugger::feature_get)
{
// feature_get accepts exactly one arg: -n feature_name.
if (aArgCount != 1 || ArgChar(aArgV, 0) != 'n')
return DEBUGGER_E_INVALID_OPTIONS;
char *feature_name = ArgValue(aArgV, 0);
bool supported = false; // Is %feature_name% a supported feature string?
char *setting = "";
if (!strncmp(feature_name, "language_", 9)) {
if (!strcmp(feature_name + 9, "supports_threads"))
setting = "0";
else if (!strcmp(feature_name + 9, "name"))
setting = DEBUGGER_LANG_NAME;
else if (!strcmp(feature_name + 9, "version"))
#ifdef UNICODE
setting = AHK_VERSION " (Unicode)";
#else
setting = AHK_VERSION;
#endif
} else if (!strcmp(feature_name, "encoding"))
setting = "UTF-8";
else if (!strcmp(feature_name, "protocol_version")
|| !strcmp(feature_name, "supports_async"))
setting = "1";
// Not supported: data_encoding - assume base64.
// Not supported: breakpoint_languages - assume only %language_name% is supported.
else if (!strcmp(feature_name, "breakpoint_types"))
setting = "line exception";
else if (!strcmp(feature_name, "multiple_sessions"))
setting = "0";
else if (!strcmp(feature_name, "max_data"))
setting = _itoa(mMaxPropertyData, (char*)_alloca(MAX_INTEGER_SIZE), 10);
else if (!strcmp(feature_name, "max_children"))
setting = _ultoa(mMaxChildren, (char*)_alloca(MAX_INTEGER_SIZE), 10);
else if (!strcmp(feature_name, "max_depth"))
setting = _ultoa(mMaxDepth, (char*)_alloca(MAX_INTEGER_SIZE), 10);
// TODO: STOPPING state for retrieving variable values, etc. after the script finishes, then implement supports_postmortem feature name. Requires debugger client support.
else
{
for (int i = 0; i < _countof(sCommands); ++i)
{
if (!strcmp(sCommands[i].mName, feature_name))
{
supported = true;
break;
}
}
}
if (*setting)
supported = true;
return mResponseBuf.WriteF(
"<response command=\"feature_get\" feature_name=\"%e\" supported=\"%i\" transaction_id=\"%e\">%s</response>"
, feature_name, (int)supported, aTransactionId, setting);
}
DEBUGGER_COMMAND(Debugger::feature_set)
{
char arg, *value;
char *feature_name = NULL, *feature_value = NULL;
for (int i = 0; i < aArgCount; ++i)
{
arg = ArgChar(aArgV, i);
value = ArgValue(aArgV, i);
switch (arg)
{
case 'n': feature_name = value; break;
case 'v': feature_value = value; break;
default:
return DEBUGGER_E_INVALID_OPTIONS;
}
}
if (!feature_name || !feature_value)
return DEBUGGER_E_INVALID_OPTIONS;
bool success = false;
// Since all supported features are positive integers:
int ival = atoi(feature_value);
if (ival < 0)
{
// Since this value is invalid, return success="0" to indicate the error.
// Setting the feature to a negative value might cause instability elsewhere.
}
else if (success = !strcmp(feature_name, "max_data"))
{
if (ival == 0) // Although this isn't in the spec, at least one IDE relies on it.
ival = INT_MAX; // Strictly following the spec, we should probably return 0 bytes of data.
mMaxPropertyData = ival;
}
else if (success = !strcmp(feature_name, "max_children"))
mMaxChildren = ival;
else if (success = !strcmp(feature_name, "max_depth"))
mMaxDepth = ival;
return mResponseBuf.WriteF(
"<response command=\"feature_set\" feature=\"%e\" success=\"%i\" transaction_id=\"%e\"/>"
, feature_name, (int)success, aTransactionId);
}
DEBUGGER_COMMAND(Debugger::run)
{
return run_step(aArgV, aArgCount, aTransactionId, "run", DIS_Run);
}
DEBUGGER_COMMAND(Debugger::step_into)
{
return run_step(aArgV, aArgCount, aTransactionId, "step_into", DIS_StepInto);
}
DEBUGGER_COMMAND(Debugger::step_over)
{
return run_step(aArgV, aArgCount, aTransactionId, "step_over", DIS_StepOver);
}
DEBUGGER_COMMAND(Debugger::step_out)
{
return run_step(aArgV, aArgCount, aTransactionId, "step_out", DIS_StepOut);
}
int Debugger::run_step(char **aArgV, int aArgCount, char *aTransactionId, char *aCommandName, DebuggerInternalStateType aNewState)
{
if (aArgCount)
return DEBUGGER_E_INVALID_OPTIONS;
if (mInternalState != DIS_Break)
return DEBUGGER_E_COMMAND_UNAVAIL;
mInternalState = aNewState;
mContinuationDepth = mStack.Depth();
mContinuationTransactionId = aTransactionId;
// Response will be sent when the debugger breaks.
return DEBUGGER_E_CONTINUE;
}
DEBUGGER_COMMAND(Debugger::_break)
{
if (aArgCount)
return DEBUGGER_E_INVALID_OPTIONS;
if (int err = EnterBreakState())
return err;
return DEBUGGER_E_OK;
}
DEBUGGER_COMMAND(Debugger::stop)
{
mContinuationTransactionId = aTransactionId;
// Call g_script.TerminateApp instead of g_script.ExitApp to bypass OnExit subroutine.
g_script.TerminateApp(EXIT_EXIT, 0); // This also causes this->Exit() to be called.
// Should never be reached, but must be here to avoid a compile error:
return DEBUGGER_E_INTERNAL_ERROR;
}
DEBUGGER_COMMAND(Debugger::detach)
{
mContinuationTransactionId = aTransactionId; // Seems more appropriate than using the previous ID (if any).
// User wants to stop the debugger but let the script keep running.
Exit(EXIT_NONE, "detach"); // Anything but EXIT_ERROR. Sends "stopped" response, then disconnects.
return DEBUGGER_E_CONTINUE; // Response already sent.
}
DEBUGGER_COMMAND(Debugger::breakpoint_set)
{
char arg, *value;
char *type = NULL, state = BS_Enabled, *filename = NULL;
LineNumberType lineno = 0;
bool temporary = false;
for (int i = 0; i < aArgCount; ++i)
{
arg = ArgChar(aArgV, i);
value = ArgValue(aArgV, i);
switch (arg)
{
case 't': // type = line | call | return | exception | conditional | watch
type = value;
break;
case 's': // state = enabled | disabled
if (!strcmp(value, "enabled"))
state = BS_Enabled;
else if (!strcmp(value, "disabled"))
state = BS_Disabled;
else
return DEBUGGER_E_BREAKPOINT_STATE;
break;
case 'f': // filename
filename = value;
break;
case 'n': // lineno
lineno = strtoul(value, NULL, 10);
break;
case 'r': // temporary = 0 | 1
temporary = (*value != '0');
break;
case 'x': // exception
if (!stricmp(value, "Any")) // Require this or nothing, for now.
break;
return DEBUGGER_E_INVALID_OPTIONS;
case 'm': // function
case 'h': // hit_value
case 'o': // hit_condition = >= | == | %
case '-': // expression for conditional breakpoints
// These aren't used/supported.
default:
return DEBUGGER_E_INVALID_OPTIONS;
}
}
// Breakpoint type is required according to the spec, but allowing it to be omitted
// and defaulting to "line" is more convenient for debugging the debugger via console.
if (type && strcmp(type, "line")) // i.e. type was specified and is not "line".
{
if (!strcmp(type, "exception") && lineno == 0 && !filename)
{
mBreakOnException = state;
mBreakOnExceptionIsTemporary = temporary;
mBreakOnExceptionWasSet = true;
if (!mBreakOnExceptionID)
mBreakOnExceptionID = Breakpoint::AllocateID();
return mResponseBuf.WriteF(
"<response command=\"breakpoint_set\" transaction_id=\"%e\" state=\"%s\" id=\"%i\"/>"
, aTransactionId, state ? "enabled" : "disabled", mBreakOnExceptionID);
}
return DEBUGGER_E_BREAKPOINT_TYPE;
}
if (lineno < 1)
return DEBUGGER_E_BREAKPOINT_INVALID;
int file_index = 0;
if (filename)
{
// Decode filename URI -> path, in-place.
DecodeURI(filename);
CStringTCharFromUTF8 filename_t(filename);
// Find the specified source file.
for (file_index = 0; file_index < Line::sSourceFileCount; ++file_index)
if (!_tcsicmp(filename_t, Line::sSourceFile[file_index]))
break;
if (file_index >= Line::sSourceFileCount)
return DEBUGGER_E_BREAKPOINT_INVALID;
}
Line *line = NULL, *found_line = NULL;
// Due to the introduction of expressions in static initializers, lines aren't necessarily in
// line number order. First determine if any static initializers match the requested lineno.
// If not, use the first non-static line at or following that line number.
if (g_script.mFirstStaticLine)
for (line = g_script.mFirstStaticLine; ; line = line->mNextLine)
{
if (line->mFileIndex == file_index && line->mLineNumber == lineno) // Exact match, unlike normal lines.
{
found_line = line;
break;
}
if (line == g_script.mLastStaticLine)
break;
}
if (!found_line)
// If line is non-NULL, above has left it set to mLastStaticLine, which we want to exclude:
for (line = line ? line->mNextLine : g_script.mFirstLine; line; line = line->mNextLine)
if (line->mFileIndex == file_index && line->mLineNumber >= lineno)
{
// ACT_ELSE and ACT_BLOCK_BEGIN generally don't cause PreExecLine() to be called,
// so any breakpoint set on one of those lines would never be hit. Attempting to
// set a breakpoint on one of these should act like setting a breakpoint on a line
// which contains no code: put the breakpoint at the next line instead.
// Without this check, setting a breakpoint on a line like "else Exit" would not work.
// ACT_CASE executes when the *previous* case reaches its end, so for that case
// we want to shift the breakpoint to the first Line after the ACT_CASE.
if (BreakpointLineIsSlippery(line))
continue;
// Use the first line of code at or after lineno, like Visual Studio.
// To display the breakpoint correctly, an IDE should use breakpoint_get.
if (!found_line || found_line->mLineNumber > line->mLineNumber)
found_line = line;
// Must keep searching, since class var initializers can cause lines to be listed out of order.
//break;
}
if (found_line)
{
if (!found_line->mBreakpoint)
found_line->mBreakpoint = new Breakpoint();
found_line->mBreakpoint->state = state;
found_line->mBreakpoint->temporary = temporary;
return mResponseBuf.WriteF(
"<response command=\"breakpoint_set\" transaction_id=\"%e\" state=\"%s\" id=\"%i\"/>"
, aTransactionId, state ? "enabled" : "disabled", found_line->mBreakpoint->id);
}
// There are no lines of code beginning at or after lineno.
return DEBUGGER_E_BREAKPOINT_INVALID;
}
int Debugger::WriteBreakpointXml(Breakpoint *aBreakpoint, Line *aLine)
{
return mResponseBuf.WriteF("<breakpoint id=\"%i\" type=\"line\" state=\"%s\" filename=\"%r\" lineno=\"%u\"/>"
, aBreakpoint->id, aBreakpoint->state ? "enabled" : "disabled"
, Line::sSourceFile[aLine->mFileIndex], aLine->mLineNumber);
}
int Debugger::WriteExceptionBreakpointXml()
{
return mResponseBuf.WriteF("<breakpoint id=\"%i\" type=\"exception\" state=\"%s\" exception=\"Any\"/>"
, mBreakOnExceptionID, mBreakOnException ? "enabled" : "disabled");
}
DEBUGGER_COMMAND(Debugger::breakpoint_get)
{
// breakpoint_get accepts exactly one arg: -d breakpoint_id.
if (aArgCount != 1 || ArgChar(aArgV, 0) != 'd')
return DEBUGGER_E_INVALID_OPTIONS;
int breakpoint_id = atoi(ArgValue(aArgV, 0));
Line *line;
for (line = g_script.mFirstLine; line; line = line->mNextLine)
{
if (line->mBreakpoint && line->mBreakpoint->id == breakpoint_id)
{
mResponseBuf.WriteF("<response command=\"breakpoint_get\" transaction_id=\"%e\">", aTransactionId);
WriteBreakpointXml(line->mBreakpoint, line);
mResponseBuf.Write("</response>");
return DEBUGGER_E_OK;
}
}
if (breakpoint_id == mBreakOnExceptionID && mBreakOnExceptionWasSet)
{
mResponseBuf.WriteF("<response command=\"breakpoint_get\" transaction_id=\"%e\">", aTransactionId);
WriteExceptionBreakpointXml();
return mResponseBuf.Write("</response>");
}
return DEBUGGER_E_BREAKPOINT_NOT_FOUND;
}
DEBUGGER_COMMAND(Debugger::breakpoint_update)
{
char arg, *value;
int breakpoint_id = 0; // Breakpoint IDs begin at 1.
LineNumberType lineno = 0;
char state = -1;
for (int i = 0; i < aArgCount; ++i)
{
arg = ArgChar(aArgV, i);
value = ArgValue(aArgV, i);
switch (arg)
{
case 'd':
breakpoint_id = atoi(value);
break;
case 's':
if (!strcmp(value, "enabled"))
state = BS_Enabled;
else if (!strcmp(value, "disabled"))
state = BS_Disabled;
else
return DEBUGGER_E_BREAKPOINT_STATE;
break;
case 'n':
lineno = strtoul(value, NULL, 10);
break;
case 'h': // hit_value
case 'o': // hit_condition
// These aren't used/supported, but ignored for now.
break;
default:
return DEBUGGER_E_INVALID_OPTIONS;
}
}
if (!breakpoint_id)
return DEBUGGER_E_INVALID_OPTIONS;
Line *line;
for (line = g_script.mFirstLine; line; line = line->mNextLine)
{
Breakpoint *bp = line->mBreakpoint;
if (bp && bp->id == breakpoint_id)
{
if (lineno && line->mLineNumber != lineno)
{
// Move the breakpoint within its current file.
int file_index = line->mFileIndex;
Line *old_line = line;
for (line = g_script.mFirstLine; line; line = line->mNextLine)
{
if (line->mFileIndex == file_index && line->mLineNumber >= lineno)
{
line->mBreakpoint = bp;
break;
}
}
// If line is NULL, the line was not found.
if (!line)
return DEBUGGER_E_BREAKPOINT_INVALID;
// Seems best to only remove the breakpoint from its previous line
// once we know the breakpoint_update has succeeded.
old_line->mBreakpoint = NULL;
}
if (state != -1)
bp->state = state;
return DEBUGGER_E_OK;
}
}
if (breakpoint_id == mBreakOnExceptionID)
{
mBreakOnException = state;
return DEBUGGER_E_OK;
}
return DEBUGGER_E_BREAKPOINT_NOT_FOUND;
}
DEBUGGER_COMMAND(Debugger::breakpoint_remove)
{
// breakpoint_remove accepts exactly one arg: -d breakpoint_id.
if (aArgCount != 1 || ArgChar(aArgV, 0) != 'd')
return DEBUGGER_E_INVALID_OPTIONS;
int breakpoint_id = atoi(ArgValue(aArgV, 0));
Line *line;
for (line = g_script.mFirstLine; line; line = line->mNextLine)
{
if (line->mBreakpoint && line->mBreakpoint->id == breakpoint_id)
{
delete line->mBreakpoint;
line->mBreakpoint = NULL;
return DEBUGGER_E_OK;
}
}
if (breakpoint_id == mBreakOnExceptionID && mBreakOnExceptionWasSet)
{
mBreakOnException = false;
mBreakOnExceptionWasSet = false;
return DEBUGGER_E_OK;
}
return DEBUGGER_E_BREAKPOINT_NOT_FOUND;
}
DEBUGGER_COMMAND(Debugger::breakpoint_list)
{
if (aArgCount)
return DEBUGGER_E_INVALID_OPTIONS;
mResponseBuf.WriteF("<response command=\"breakpoint_list\" transaction_id=\"%e\">", aTransactionId);
Line *line;
for (line = g_script.mFirstLine; line; line = line->mNextLine)
{
if (line->mBreakpoint)
{
WriteBreakpointXml(line->mBreakpoint, line);
}
}
if (mBreakOnExceptionWasSet)
WriteExceptionBreakpointXml();
return mResponseBuf.Write("</response>");
}
DEBUGGER_COMMAND(Debugger::stack_depth)
{
if (aArgCount)
return DEBUGGER_E_INVALID_OPTIONS;
return mResponseBuf.WriteF(
"<response command=\"stack_depth\" depth=\"%i\" transaction_id=\"%e\"/>"
, mStack.Depth(), aTransactionId);
}
DEBUGGER_COMMAND(Debugger::stack_get)
{
int depth = -1;
if (aArgCount)
{
// stack_get accepts one optional arg: -d depth.
if (aArgCount > 1 || ArgChar(aArgV, 0) != 'd')
return DEBUGGER_E_INVALID_OPTIONS;
depth = atoi(ArgValue(aArgV, 0));
if (depth < 0 || depth >= mStack.Depth())
return DEBUGGER_E_INVALID_STACK_DEPTH;
}
mResponseBuf.WriteF("<response command=\"stack_get\" transaction_id=\"%e\">", aTransactionId);
int level = 0;
DbgStack::Entry *se;
for (se = mStack.mTop; se >= mStack.mBottom; --se)
{
if (depth == -1 || depth == level)
{
Line *line;
if (se == mStack.mTop)
{
ASSERT(mCurrLine); // Should always be valid.
line = mCurrLine; // See PreExecLine() for comments.
}
else if (se->type == DbgStack::SE_Thread)
{
// !se->line implies se->type == SE_Thread.
if (_tcscmp(se->desc, _T("Auto-execute")) && se[1].type == DbgStack::SE_UDF)
// Show the function's jump-to line since se->line is most likely whatever line
// this thread interrupted. Don't do it for the auto-execute thread since in
// that case the function doesn't represent the thread's overall execution.
line = se[1].udf->func->mJumpToLine;
else if (se[1].type == DbgStack::SE_Sub)
line = se[1].sub->mJumpToLine;
else
// The auto-execute thread is probably the only one that can exist without
// a Sub or Func entry immediately above it. As se != mStack.mTop, se->line
// has been set to a non-NULL by DbgStack::Push().
line = se->line;
}
else
{
line = se->line;
}
mResponseBuf.WriteF("<stack level=\"%i\" type=\"file\" filename=\"%r\" lineno=\"%u\" where=\""
, level, Line::sSourceFile[line->mFileIndex], line->mLineNumber);
switch (se->type)
{
case DbgStack::SE_Thread: