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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
|
//===-- CommandInterpreter.cpp ----------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include <string>
#include <vector>
#include <getopt.h>
#include <stdlib.h>
#include "../Commands/CommandObjectApropos.h"
#include "../Commands/CommandObjectArgs.h"
#include "../Commands/CommandObjectBreakpoint.h"
//#include "../Commands/CommandObjectCall.h"
#include "../Commands/CommandObjectDisassemble.h"
#include "../Commands/CommandObjectExpression.h"
#include "../Commands/CommandObjectFile.h"
#include "../Commands/CommandObjectFrame.h"
#include "../Commands/CommandObjectHelp.h"
#include "../Commands/CommandObjectImage.h"
#include "../Commands/CommandObjectLog.h"
#include "../Commands/CommandObjectMemory.h"
#include "../Commands/CommandObjectProcess.h"
#include "../Commands/CommandObjectQuit.h"
#include "lldb/Interpreter/CommandObjectRegexCommand.h"
#include "../Commands/CommandObjectRegister.h"
#include "CommandObjectScript.h"
#include "../Commands/CommandObjectSettings.h"
#include "../Commands/CommandObjectSource.h"
#include "../Commands/CommandObjectCommands.h"
#include "../Commands/CommandObjectSyntax.h"
#include "../Commands/CommandObjectTarget.h"
#include "../Commands/CommandObjectThread.h"
#include "../Commands/CommandObjectVersion.h"
#include "lldb/Interpreter/Args.h"
#include "lldb/Core/Debugger.h"
#include "lldb/Core/InputReader.h"
#include "lldb/Core/Stream.h"
#include "lldb/Core/Timer.h"
#include "lldb/Target/Process.h"
#include "lldb/Target/Thread.h"
#include "lldb/Target/TargetList.h"
#include "lldb/Utility/CleanUp.h"
#include "lldb/Interpreter/CommandReturnObject.h"
#include "lldb/Interpreter/CommandInterpreter.h"
#include "lldb/Interpreter/ScriptInterpreterNone.h"
#include "lldb/Interpreter/ScriptInterpreterPython.h"
using namespace lldb;
using namespace lldb_private;
CommandInterpreter::CommandInterpreter
(
Debugger &debugger,
ScriptLanguage script_language,
bool synchronous_execution
) :
Broadcaster ("lldb.command-interpreter"),
m_debugger (debugger),
m_synchronous_execution (synchronous_execution),
m_skip_lldbinit_files (false),
m_script_interpreter_ap ()
{
const char *dbg_name = debugger.GetInstanceName().AsCString();
std::string lang_name = ScriptInterpreter::LanguageToString (script_language);
StreamString var_name;
var_name.Printf ("[%s].script-lang", dbg_name);
debugger.GetSettingsController()->SetVariable (var_name.GetData(), lang_name.c_str(),
lldb::eVarSetOperationAssign, false,
m_debugger.GetInstanceName().AsCString());
SetEventName (eBroadcastBitThreadShouldExit, "thread-should-exit");
SetEventName (eBroadcastBitResetPrompt, "reset-prompt");
SetEventName (eBroadcastBitQuitCommandReceived, "quit");
}
void
CommandInterpreter::Initialize ()
{
Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
CommandReturnObject result;
LoadCommandDictionary ();
// Set up some initial aliases.
result.Clear(); HandleCommand ("command alias q quit", false, result);
result.Clear(); HandleCommand ("command alias run process launch --", false, result);
result.Clear(); HandleCommand ("command alias r process launch --", false, result);
result.Clear(); HandleCommand ("command alias c process continue", false, result);
result.Clear(); HandleCommand ("command alias continue process continue", false, result);
result.Clear(); HandleCommand ("command alias expr expression", false, result);
result.Clear(); HandleCommand ("command alias exit quit", false, result);
result.Clear(); HandleCommand ("command alias b regexp-break", false, result);
result.Clear(); HandleCommand ("command alias bt thread backtrace", false, result);
result.Clear(); HandleCommand ("command alias si thread step-inst", false, result);
result.Clear(); HandleCommand ("command alias step thread step-in", false, result);
result.Clear(); HandleCommand ("command alias s thread step-in", false, result);
result.Clear(); HandleCommand ("command alias next thread step-over", false, result);
result.Clear(); HandleCommand ("command alias n thread step-over", false, result);
result.Clear(); HandleCommand ("command alias finish thread step-out", false, result);
result.Clear(); HandleCommand ("command alias x memory read", false, result);
result.Clear(); HandleCommand ("command alias l source list", false, result);
result.Clear(); HandleCommand ("command alias list source list", false, result);
result.Clear(); HandleCommand ("command alias p frame variable", false, result);
result.Clear(); HandleCommand ("command alias print frame variable", false, result);
result.Clear(); HandleCommand ("command alias po expression -o --", false, result);
}
const char *
CommandInterpreter::ProcessEmbeddedScriptCommands (const char *arg)
{
// This function has not yet been implemented.
// Look for any embedded script command
// If found,
// get interpreter object from the command dictionary,
// call execute_one_command on it,
// get the results as a string,
// substitute that string for current stuff.
return arg;
}
void
CommandInterpreter::LoadCommandDictionary ()
{
Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
// **** IMPORTANT **** IMPORTANT *** IMPORTANT *** **** IMPORTANT **** IMPORTANT *** IMPORTANT ***
//
// Command objects that are used as cross reference objects (i.e. they inherit from CommandObjectCrossref)
// *MUST* be created and put into the command dictionary *BEFORE* any multi-word commands (which may use
// the cross-referencing stuff) are created!!!
//
// **** IMPORTANT **** IMPORTANT *** IMPORTANT *** **** IMPORTANT **** IMPORTANT *** IMPORTANT ***
// Command objects that inherit from CommandObjectCrossref must be created before other command objects
// are created. This is so that when another command is created that needs to go into a crossref object,
// the crossref object exists and is ready to take the cross reference. Put the cross referencing command
// objects into the CommandDictionary now, so they are ready for use when the other commands get created.
// Non-CommandObjectCrossref commands can now be created.
lldb::ScriptLanguage script_language = m_debugger.GetScriptLanguage();
m_command_dict["apropos"] = CommandObjectSP (new CommandObjectApropos (*this));
m_command_dict["breakpoint"]= CommandObjectSP (new CommandObjectMultiwordBreakpoint (*this));
//m_command_dict["call"] = CommandObjectSP (new CommandObjectCall (*this));
m_command_dict["commands"] = CommandObjectSP (new CommandObjectMultiwordCommands (*this));
m_command_dict["disassemble"] = CommandObjectSP (new CommandObjectDisassemble (*this));
m_command_dict["expression"]= CommandObjectSP (new CommandObjectExpression (*this));
m_command_dict["file"] = CommandObjectSP (new CommandObjectFile (*this));
m_command_dict["frame"] = CommandObjectSP (new CommandObjectMultiwordFrame (*this));
m_command_dict["help"] = CommandObjectSP (new CommandObjectHelp (*this));
m_command_dict["image"] = CommandObjectSP (new CommandObjectImage (*this));
m_command_dict["log"] = CommandObjectSP (new CommandObjectLog (*this));
m_command_dict["memory"] = CommandObjectSP (new CommandObjectMemory (*this));
m_command_dict["process"] = CommandObjectSP (new CommandObjectMultiwordProcess (*this));
m_command_dict["quit"] = CommandObjectSP (new CommandObjectQuit (*this));
m_command_dict["register"] = CommandObjectSP (new CommandObjectRegister (*this));
m_command_dict["script"] = CommandObjectSP (new CommandObjectScript (*this, script_language));
m_command_dict["settings"] = CommandObjectSP (new CommandObjectMultiwordSettings (*this));
m_command_dict["source"] = CommandObjectSP (new CommandObjectMultiwordSource (*this));
m_command_dict["target"] = CommandObjectSP (new CommandObjectMultiwordTarget (*this));
m_command_dict["thread"] = CommandObjectSP (new CommandObjectMultiwordThread (*this));
m_command_dict["version"] = CommandObjectSP (new CommandObjectVersion (*this));
std::auto_ptr<CommandObjectRegexCommand>
break_regex_cmd_ap(new CommandObjectRegexCommand (*this,
"regexp-break",
"Set a breakpoint using a regular expression to specify the location.",
"regexp-break [<filename>:<linenum>]\nregexp-break [<address>]\nregexp-break <...>", 2));
if (break_regex_cmd_ap.get())
{
if (break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]]*$", "breakpoint set --file '%1' --line %2") &&
break_regex_cmd_ap->AddRegexCommand("^(0x[[:xdigit:]]+)[[:space:]]*$", "breakpoint set --address %1") &&
break_regex_cmd_ap->AddRegexCommand("^[\"']?([-+]\\[.*\\])[\"']?[[:space:]]*$", "breakpoint set --name '%1'") &&
break_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list") &&
break_regex_cmd_ap->AddRegexCommand("^(-.*)$", "breakpoint set %1") &&
break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%1'"))
{
CommandObjectSP break_regex_cmd_sp(break_regex_cmd_ap.release());
m_command_dict[break_regex_cmd_sp->GetCommandName ()] = break_regex_cmd_sp;
}
}
}
int
CommandInterpreter::GetCommandNamesMatchingPartialString (const char *cmd_str, bool include_aliases,
StringList &matches)
{
CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_str, matches);
if (include_aliases)
{
CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_str, matches);
}
return matches.GetSize();
}
CommandObjectSP
CommandInterpreter::GetCommandSP (const char *cmd_cstr, bool include_aliases, bool exact, StringList *matches)
{
CommandObject::CommandMap::iterator pos;
CommandObjectSP ret_val;
std::string cmd(cmd_cstr);
if (HasCommands())
{
pos = m_command_dict.find(cmd);
if (pos != m_command_dict.end())
ret_val = pos->second;
}
if (include_aliases && HasAliases())
{
pos = m_alias_dict.find(cmd);
if (pos != m_alias_dict.end())
ret_val = pos->second;
}
if (HasUserCommands())
{
pos = m_user_dict.find(cmd);
if (pos != m_user_dict.end())
ret_val = pos->second;
}
if (!exact && ret_val == NULL)
{
// We will only get into here if we didn't find any exact matches.
CommandObjectSP user_match_sp, alias_match_sp, real_match_sp;
StringList local_matches;
if (matches == NULL)
matches = &local_matches;
unsigned int num_cmd_matches = 0;
unsigned int num_alias_matches = 0;
unsigned int num_user_matches = 0;
// Look through the command dictionaries one by one, and if we get only one match from any of
// them in toto, then return that, otherwise return an empty CommandObjectSP and the list of matches.
if (HasCommands())
{
num_cmd_matches = CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_cstr, *matches);
}
if (num_cmd_matches == 1)
{
cmd.assign(matches->GetStringAtIndex(0));
pos = m_command_dict.find(cmd);
if (pos != m_command_dict.end())
real_match_sp = pos->second;
}
if (include_aliases && HasAliases())
{
num_alias_matches = CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_cstr, *matches);
}
if (num_alias_matches == 1)
{
cmd.assign(matches->GetStringAtIndex (num_cmd_matches));
pos = m_alias_dict.find(cmd);
if (pos != m_alias_dict.end())
alias_match_sp = pos->second;
}
if (HasUserCommands())
{
num_user_matches = CommandObject::AddNamesMatchingPartialString (m_user_dict, cmd_cstr, *matches);
}
if (num_user_matches == 1)
{
cmd.assign (matches->GetStringAtIndex (num_cmd_matches + num_alias_matches));
pos = m_user_dict.find (cmd);
if (pos != m_user_dict.end())
user_match_sp = pos->second;
}
// If we got exactly one match, return that, otherwise return the match list.
if (num_user_matches + num_cmd_matches + num_alias_matches == 1)
{
if (num_cmd_matches)
return real_match_sp;
else if (num_alias_matches)
return alias_match_sp;
else
return user_match_sp;
}
}
else if (matches && ret_val != NULL)
{
matches->AppendString (cmd_cstr);
}
return ret_val;
}
CommandObjectSP
CommandInterpreter::GetCommandSPExact (const char *cmd_cstr, bool include_aliases)
{
Args cmd_words (cmd_cstr); // Break up the command string into words, in case it's a multi-word command.
CommandObjectSP ret_val; // Possibly empty return value.
if (cmd_cstr == NULL)
return ret_val;
if (cmd_words.GetArgumentCount() == 1)
return GetCommandSP(cmd_cstr, include_aliases, true, NULL);
else
{
// We have a multi-word command (seemingly), so we need to do more work.
// First, get the cmd_obj_sp for the first word in the command.
CommandObjectSP cmd_obj_sp = GetCommandSP (cmd_words.GetArgumentAtIndex (0), include_aliases, true, NULL);
if (cmd_obj_sp.get() != NULL)
{
// Loop through the rest of the words in the command (everything passed in was supposed to be part of a
// command name), and find the appropriate sub-command SP for each command word....
size_t end = cmd_words.GetArgumentCount();
for (size_t j= 1; j < end; ++j)
{
if (cmd_obj_sp->IsMultiwordObject())
{
cmd_obj_sp = ((CommandObjectMultiword *) cmd_obj_sp.get())->GetSubcommandSP
(cmd_words.GetArgumentAtIndex (j));
if (cmd_obj_sp.get() == NULL)
// The sub-command name was invalid. Fail and return the empty 'ret_val'.
return ret_val;
}
else
// We have more words in the command name, but we don't have a multiword object. Fail and return
// empty 'ret_val'.
return ret_val;
}
// We successfully looped through all the command words and got valid command objects for them. Assign the
// last object retrieved to 'ret_val'.
ret_val = cmd_obj_sp;
}
}
return ret_val;
}
CommandObject *
CommandInterpreter::GetCommandObjectExact (const char *cmd_cstr, bool include_aliases)
{
return GetCommandSPExact (cmd_cstr, include_aliases).get();
}
CommandObject *
CommandInterpreter::GetCommandObject (const char *cmd_cstr, StringList *matches)
{
CommandObject *command_obj = GetCommandSP (cmd_cstr, false, true, matches).get();
// If we didn't find an exact match to the command string in the commands, look in
// the aliases.
if (command_obj == NULL)
{
command_obj = GetCommandSP (cmd_cstr, true, true, matches).get();
}
// Finally, if there wasn't an exact match among the aliases, look for an inexact match
// in both the commands and the aliases.
if (command_obj == NULL)
command_obj = GetCommandSP(cmd_cstr, true, false, matches).get();
return command_obj;
}
bool
CommandInterpreter::CommandExists (const char *cmd)
{
return m_command_dict.find(cmd) != m_command_dict.end();
}
bool
CommandInterpreter::AliasExists (const char *cmd)
{
return m_alias_dict.find(cmd) != m_alias_dict.end();
}
bool
CommandInterpreter::UserCommandExists (const char *cmd)
{
return m_user_dict.find(cmd) != m_user_dict.end();
}
void
CommandInterpreter::AddAlias (const char *alias_name, CommandObjectSP& command_obj_sp)
{
command_obj_sp->SetIsAlias (true);
m_alias_dict[alias_name] = command_obj_sp;
}
bool
CommandInterpreter::RemoveAlias (const char *alias_name)
{
CommandObject::CommandMap::iterator pos = m_alias_dict.find(alias_name);
if (pos != m_alias_dict.end())
{
m_alias_dict.erase(pos);
return true;
}
return false;
}
bool
CommandInterpreter::RemoveUser (const char *alias_name)
{
CommandObject::CommandMap::iterator pos = m_user_dict.find(alias_name);
if (pos != m_user_dict.end())
{
m_user_dict.erase(pos);
return true;
}
return false;
}
void
CommandInterpreter::GetAliasHelp (const char *alias_name, const char *command_name, StreamString &help_string)
{
help_string.Printf ("'%s", command_name);
OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
if (option_arg_vector_sp != NULL)
{
OptionArgVector *options = option_arg_vector_sp.get();
for (int i = 0; i < options->size(); ++i)
{
OptionArgPair cur_option = (*options)[i];
std::string opt = cur_option.first;
OptionArgValue value_pair = cur_option.second;
std::string value = value_pair.second;
if (opt.compare("<argument>") == 0)
{
help_string.Printf (" %s", value.c_str());
}
else
{
help_string.Printf (" %s", opt.c_str());
if ((value.compare ("<no-argument>") != 0)
&& (value.compare ("<need-argument") != 0))
{
help_string.Printf (" %s", value.c_str());
}
}
}
}
help_string.Printf ("'");
}
size_t
CommandInterpreter::FindLongestCommandWord (CommandObject::CommandMap &dict)
{
CommandObject::CommandMap::const_iterator pos;
CommandObject::CommandMap::const_iterator end = dict.end();
size_t max_len = 0;
for (pos = dict.begin(); pos != end; ++pos)
{
size_t len = pos->first.size();
if (max_len < len)
max_len = len;
}
return max_len;
}
void
CommandInterpreter::GetHelp (CommandReturnObject &result)
{
CommandObject::CommandMap::const_iterator pos;
result.AppendMessage("The following is a list of built-in, permanent debugger commands:");
result.AppendMessage("");
uint32_t max_len = FindLongestCommandWord (m_command_dict);
for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
{
OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(),
max_len);
}
result.AppendMessage("");
if (m_alias_dict.size() > 0)
{
result.AppendMessage("The following is a list of your current command abbreviations "
"(see 'help commands alias' for more info):");
result.AppendMessage("");
max_len = FindLongestCommandWord (m_alias_dict);
for (pos = m_alias_dict.begin(); pos != m_alias_dict.end(); ++pos)
{
StreamString sstr;
StreamString translation_and_help;
std::string entry_name = pos->first;
std::string second_entry = pos->second.get()->GetCommandName();
GetAliasHelp (pos->first.c_str(), pos->second->GetCommandName(), sstr);
translation_and_help.Printf ("(%s) %s", sstr.GetData(), pos->second->GetHelp());
OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--",
translation_and_help.GetData(), max_len);
}
result.AppendMessage("");
}
if (m_user_dict.size() > 0)
{
result.AppendMessage ("The following is a list of your current user-defined commands:");
result.AppendMessage("");
for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos)
{
result.AppendMessageWithFormat ("%s -- %s\n", pos->first.c_str(), pos->second->GetHelp());
}
result.AppendMessage("");
}
result.AppendMessage("For more information on any particular command, try 'help <command-name>'.");
}
CommandObject *
CommandInterpreter::GetCommandObjectForCommand (std::string &command_string)
{
// This function finds the final, lowest-level, alias-resolved command object whose 'Execute' function will
// eventually be invoked by the given command line.
CommandObject *cmd_obj = NULL;
std::string white_space (" \t\v");
size_t start = command_string.find_first_not_of (white_space);
size_t end = 0;
bool done = false;
while (!done)
{
if (start != std::string::npos)
{
// Get the next word from command_string.
end = command_string.find_first_of (white_space, start);
if (end == std::string::npos)
end = command_string.size();
std::string cmd_word = command_string.substr (start, end - start);
if (cmd_obj == NULL)
// Since cmd_obj is NULL we are on our first time through this loop. Check to see if cmd_word is a valid
// command or alias.
cmd_obj = GetCommandObject (cmd_word.c_str());
else if (cmd_obj->IsMultiwordObject ())
{
// Our current object is a multi-word object; see if the cmd_word is a valid sub-command for our object.
CommandObject *sub_cmd_obj =
((CommandObjectMultiword *) cmd_obj)->GetSubcommandObject (cmd_word.c_str());
if (sub_cmd_obj)
cmd_obj = sub_cmd_obj;
else // cmd_word was not a valid sub-command word, so we are donee
done = true;
}
else
// We have a cmd_obj and it is not a multi-word object, so we are done.
done = true;
// If we didn't find a valid command object, or our command object is not a multi-word object, or
// we are at the end of the command_string, then we are done. Otherwise, find the start of the
// next word.
if (!cmd_obj || !cmd_obj->IsMultiwordObject() || end >= command_string.size())
done = true;
else
start = command_string.find_first_not_of (white_space, end);
}
else
// Unable to find any more words.
done = true;
}
if (end == command_string.size())
command_string.clear();
else
command_string = command_string.substr(end);
return cmd_obj;
}
bool
CommandInterpreter::StripFirstWord (std::string &command_string, std::string &word)
{
std::string white_space (" \t\v");
size_t start;
size_t end;
start = command_string.find_first_not_of (white_space);
if (start != std::string::npos)
{
end = command_string.find_first_of (white_space, start);
if (end != std::string::npos)
{
word = command_string.substr (start, end - start);
command_string = command_string.substr (end);
size_t pos = command_string.find_first_not_of (white_space);
if ((pos != 0) && (pos != std::string::npos))
command_string = command_string.substr (pos);
}
else
{
word = command_string.substr (start);
command_string.erase();
}
}
return true;
}
void
CommandInterpreter::BuildAliasResult (const char *alias_name, std::string &raw_input_string, std::string &alias_result,
CommandObject *&alias_cmd_obj, CommandReturnObject &result)
{
Args cmd_args (raw_input_string.c_str());
alias_cmd_obj = GetCommandObject (alias_name);
StreamString result_str;
if (alias_cmd_obj)
{
std::string alias_name_str = alias_name;
if ((cmd_args.GetArgumentCount() == 0)
|| (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0))
cmd_args.Unshift (alias_name);
result_str.Printf ("%s", alias_cmd_obj->GetCommandName ());
OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
if (option_arg_vector_sp.get())
{
OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
for (int i = 0; i < option_arg_vector->size(); ++i)
{
OptionArgPair option_pair = (*option_arg_vector)[i];
OptionArgValue value_pair = option_pair.second;
int value_type = value_pair.first;
std::string option = option_pair.first;
std::string value = value_pair.second;
if (option.compare ("<argument>") == 0)
result_str.Printf (" %s", value.c_str());
else
{
result_str.Printf (" %s", option.c_str());
if (value_type != optional_argument)
result_str.Printf (" ");
if (value.compare ("<no_argument>") != 0)
{
int index = GetOptionArgumentPosition (value.c_str());
if (index == 0)
result_str.Printf ("%s", value.c_str());
else if (index >= cmd_args.GetArgumentCount())
{
result.AppendErrorWithFormat
("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
index);
result.SetStatus (eReturnStatusFailed);
return;
}
else
{
size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
if (strpos != std::string::npos)
raw_input_string = raw_input_string.erase (strpos,
strlen (cmd_args.GetArgumentAtIndex (index)));
result_str.Printf ("%s", cmd_args.GetArgumentAtIndex (index));
}
}
}
}
}
alias_result = result_str.GetData();
}
}
bool
CommandInterpreter::HandleCommand (const char *command_line,
bool add_to_history,
CommandReturnObject &result,
ExecutionContext *override_context)
{
bool done = false;
CommandObject *cmd_obj = NULL;
std::string next_word;
bool wants_raw_input = false;
std::string command_string (command_line);
LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_COMMANDS));
Host::SetCrashDescriptionWithFormat ("HandleCommand(command = \"%s\")", command_line);
// Make a scoped cleanup object that will clear the crash description string
// on exit of this function.
lldb_utility::CleanUp <const char *, void> crash_description_cleanup(NULL, Host::SetCrashDescription);
if (log)
log->Printf ("Processing command: %s", command_line);
Timer scoped_timer (__PRETTY_FUNCTION__, "Handling command: %s.", command_line);
m_debugger.UpdateExecutionContext (override_context);
if (command_line == NULL || command_line[0] == '\0')
{
if (m_command_history.empty())
{
result.AppendError ("empty command");
result.SetStatus(eReturnStatusFailed);
return false;
}
else
{
command_line = m_repeat_command.c_str();
command_string = command_line;
if (m_repeat_command.empty())
{
result.AppendErrorWithFormat("No auto repeat.\n");
result.SetStatus (eReturnStatusFailed);
return false;
}
}
add_to_history = false;
}
// Phase 1.
// Before we do ANY kind of argument processing, etc. we need to figure out what the real/final command object
// is for the specified command, and whether or not it wants raw input. This gets complicated by the fact that
// the user could have specified an alias, and in translating the alias there may also be command options and/or
// even data (including raw text strings) that need to be found and inserted into the command line as part of
// the translation. So this first step is plain look-up & replacement, resulting in three things: 1). the command
// object whose Execute method will actually be called; 2). a revised command string, with all substitutions &
// replacements taken care of; 3). whether or not the Execute function wants raw input or not.
StreamString revised_command_line;
size_t actual_cmd_name_len = 0;
while (!done)
{
StripFirstWord (command_string, next_word);
if (!cmd_obj && AliasExists (next_word.c_str()))
{
std::string alias_result;
BuildAliasResult (next_word.c_str(), command_string, alias_result, cmd_obj, result);
revised_command_line.Printf ("%s", alias_result.c_str());
if (cmd_obj)
{
wants_raw_input = cmd_obj->WantsRawCommandString ();
actual_cmd_name_len = strlen (cmd_obj->GetCommandName());
}
}
else if (!cmd_obj)
{
cmd_obj = GetCommandObject (next_word.c_str());
if (cmd_obj)
{
actual_cmd_name_len += next_word.length();
revised_command_line.Printf ("%s", next_word.c_str());
wants_raw_input = cmd_obj->WantsRawCommandString ();
}
else
{
revised_command_line.Printf ("%s", next_word.c_str());
}
}
else if (cmd_obj->IsMultiwordObject ())
{
CommandObject *sub_cmd_obj = ((CommandObjectMultiword *) cmd_obj)->GetSubcommandObject (next_word.c_str());
if (sub_cmd_obj)
{
actual_cmd_name_len += next_word.length() + 1;
revised_command_line.Printf (" %s", next_word.c_str());
cmd_obj = sub_cmd_obj;
wants_raw_input = cmd_obj->WantsRawCommandString ();
}
else
{
revised_command_line.Printf (" %s", next_word.c_str());
done = true;
}
}
else
{
revised_command_line.Printf (" %s", next_word.c_str());
done = true;
}
if (cmd_obj == NULL)
{
result.AppendErrorWithFormat ("'%s' is not a valid command.\n", next_word.c_str());
result.SetStatus (eReturnStatusFailed);
return false;
}
next_word.erase ();
if (command_string.length() == 0)
done = true;
}
if (command_string.size() > 0)
revised_command_line.Printf (" %s", command_string.c_str());
// End of Phase 1.
// At this point cmd_obj should contain the CommandObject whose Execute method will be called, if the command
// specified was valid; revised_command_line contains the complete command line (including command name(s)),
// fully translated with all substitutions & translations taken care of (still in raw text format); and
// wants_raw_input specifies whether the Execute method expects raw input or not.
if (log)
{
log->Printf ("HandleCommand, cmd_obj : '%s'", cmd_obj ? cmd_obj->GetCommandName() : "<not found>");
log->Printf ("HandleCommand, revised_command_line: '%s'", revised_command_line.GetData());
log->Printf ("HandleCommand, wants_raw_input:'%s'", wants_raw_input ? "True" : "False");
}
// Phase 2.
// Take care of things like setting up the history command & calling the appropriate Execute method on the
// CommandObject, with the appropriate arguments.
if (cmd_obj != NULL)
{
if (add_to_history)
{
Args command_args (revised_command_line.GetData());
const char *repeat_command = cmd_obj->GetRepeatCommand(command_args, 0);
if (repeat_command != NULL)
m_repeat_command.assign(repeat_command);
else
m_repeat_command.assign(command_line);
m_command_history.push_back (command_line);
}
command_string = revised_command_line.GetData();
std::string command_name (cmd_obj->GetCommandName());
std::string remainder;
if (actual_cmd_name_len < command_string.length())
remainder = command_string.substr (actual_cmd_name_len); // Note: 'actual_cmd_name_len' may be considerably shorter
// than cmd_obj->GetCommandName(), because name completion
// allows users to enter short versions of the names,
// e.g. 'br s' for 'breakpoint set'.
// Remove any initial spaces
std::string white_space (" \t\v");
size_t pos = remainder.find_first_not_of (white_space);
if (pos != 0 && pos != std::string::npos)
remainder = remainder.substr (pos);
if (log)
log->Printf ("HandleCommand, command line after removing command name(s): '%s'\n", remainder.c_str());
if (wants_raw_input)
cmd_obj->ExecuteRawCommandString (remainder.c_str(), result);
else
{
Args cmd_args (remainder.c_str());
cmd_obj->ExecuteWithOptions (cmd_args, result);
}
}
else
{
// We didn't find the first command object, so complete the first argument.
Args command_args (revised_command_line.GetData());
StringList matches;
int num_matches;
int cursor_index = 0;
int cursor_char_position = strlen (command_args.GetArgumentAtIndex(0));
bool word_complete;
num_matches = HandleCompletionMatches (command_args,
cursor_index,
cursor_char_position,
0,
-1,
word_complete,
matches);
if (num_matches > 0)
{
std::string error_msg;
error_msg.assign ("ambiguous command '");
error_msg.append(command_args.GetArgumentAtIndex(0));
error_msg.append ("'.");
error_msg.append (" Possible completions:");
for (int i = 0; i < num_matches; i++)
{
error_msg.append ("\n\t");
error_msg.append (matches.GetStringAtIndex (i));
}
error_msg.append ("\n");
result.AppendRawError (error_msg.c_str(), error_msg.size());
}
else
result.AppendErrorWithFormat ("Unrecognized command '%s'.\n", command_args.GetArgumentAtIndex (0));
result.SetStatus (eReturnStatusFailed);
}
return result.Succeeded();
}
int
CommandInterpreter::HandleCompletionMatches (Args &parsed_line,
int &cursor_index,
int &cursor_char_position,
int match_start_point,
int max_return_elements,
bool &word_complete,
StringList &matches)
{
int num_command_matches = 0;
bool look_for_subcommand = false;
// For any of the command completions a unique match will be a complete word.
word_complete = true;
if (cursor_index == -1)
{
// We got nothing on the command line, so return the list of commands
bool include_aliases = true;
num_command_matches = GetCommandNamesMatchingPartialString ("", include_aliases, matches);
}
else if (cursor_index == 0)
{
// The cursor is in the first argument, so just do a lookup in the dictionary.
CommandObject *cmd_obj = GetCommandObject (parsed_line.GetArgumentAtIndex(0), &matches);
num_command_matches = matches.GetSize();
if (num_command_matches == 1
&& cmd_obj && cmd_obj->IsMultiwordObject()
&& matches.GetStringAtIndex(0) != NULL
&& strcmp (parsed_line.GetArgumentAtIndex(0), matches.GetStringAtIndex(0)) == 0)
{
look_for_subcommand = true;
num_command_matches = 0;
matches.DeleteStringAtIndex(0);
parsed_line.AppendArgument ("");
cursor_index++;
cursor_char_position = 0;
}
}
if (cursor_index > 0 || look_for_subcommand)
{
// We are completing further on into a commands arguments, so find the command and tell it
// to complete the command.
// First see if there is a matching initial command:
CommandObject *command_object = GetCommandObject (parsed_line.GetArgumentAtIndex(0));
if (command_object == NULL)
{
return 0;
}
else
{
parsed_line.Shift();
cursor_index--;
num_command_matches = command_object->HandleCompletion (parsed_line,
cursor_index,
cursor_char_position,
match_start_point,
max_return_elements,
word_complete,
matches);
}
}
return num_command_matches;
}
int
CommandInterpreter::HandleCompletion (const char *current_line,
const char *cursor,
const char *last_char,
int match_start_point,
int max_return_elements,
StringList &matches)
{
// We parse the argument up to the cursor, so the last argument in parsed_line is
// the one containing the cursor, and the cursor is after the last character.
Args parsed_line(current_line, last_char - current_line);
Args partial_parsed_line(current_line, cursor - current_line);
int num_args = partial_parsed_line.GetArgumentCount();
int cursor_index = partial_parsed_line.GetArgumentCount() - 1;
int cursor_char_position;
if (cursor_index == -1)
cursor_char_position = 0;
else
cursor_char_position = strlen (partial_parsed_line.GetArgumentAtIndex(cursor_index));
if (cursor > current_line && cursor[-1] == ' ')
{
// We are just after a space. If we are in an argument, then we will continue
// parsing, but if we are between arguments, then we have to complete whatever the next
// element would be.
// We can distinguish the two cases because if we are in an argument (e.g. because the space is
// protected by a quote) then the space will also be in the parsed argument...
const char *current_elem = partial_parsed_line.GetArgumentAtIndex(cursor_index);
if (cursor_char_position == 0 || current_elem[cursor_char_position - 1] != ' ')
{
parsed_line.InsertArgumentAtIndex(cursor_index + 1, "", '"');
cursor_index++;
cursor_char_position = 0;
}
}
int num_command_matches;
matches.Clear();
// Only max_return_elements == -1 is supported at present:
assert (max_return_elements == -1);
bool word_complete;
num_command_matches = HandleCompletionMatches (parsed_line,
cursor_index,
cursor_char_position,
match_start_point,
max_return_elements,
word_complete,
matches);
if (num_command_matches <= 0)
return num_command_matches;
if (num_args == 0)
{
// If we got an empty string, insert nothing.
matches.InsertStringAtIndex(0, "");
}
else
{
// Now figure out if there is a common substring, and if so put that in element 0, otherwise
// put an empty string in element 0.
std::string command_partial_str;
if (cursor_index >= 0)
command_partial_str.assign(parsed_line.GetArgumentAtIndex(cursor_index),
parsed_line.GetArgumentAtIndex(cursor_index) + cursor_char_position);
std::string common_prefix;
matches.LongestCommonPrefix (common_prefix);
int partial_name_len = command_partial_str.size();
// If we matched a unique single command, add a space...
// Only do this if the completer told us this was a complete word, however...
if (num_command_matches == 1 && word_complete)
{
char quote_char = parsed_line.GetArgumentQuoteCharAtIndex(cursor_index);
if (quote_char != '\0')
common_prefix.push_back(quote_char);
common_prefix.push_back(' ');
}
common_prefix.erase (0, partial_name_len);
matches.InsertStringAtIndex(0, common_prefix.c_str());
}
return num_command_matches;
}
CommandInterpreter::~CommandInterpreter ()
{
}
const char *
CommandInterpreter::GetPrompt ()
{
return m_debugger.GetPrompt();
}
void
CommandInterpreter::SetPrompt (const char *new_prompt)
{
m_debugger.SetPrompt (new_prompt);
}
size_t
CommandInterpreter::GetConfirmationInputReaderCallback (void *baton,
InputReader &reader,
lldb::InputReaderAction action,
const char *bytes,
size_t bytes_len)
{
FILE *out_fh = reader.GetDebugger().GetOutputFileHandle();
bool *response_ptr = (bool *) baton;
switch (action)
{
case eInputReaderActivate:
if (out_fh)
{
if (reader.GetPrompt())
::fprintf (out_fh, "%s", reader.GetPrompt());
}
break;
case eInputReaderDeactivate:
break;
case eInputReaderReactivate:
if (out_fh && reader.GetPrompt())
::fprintf (out_fh, "%s", reader.GetPrompt());
break;
case eInputReaderGotToken:
if (bytes_len == 0)
{
reader.SetIsDone(true);
}
else if (bytes[0] == 'y')
{
*response_ptr = true;
reader.SetIsDone(true);
}
else if (bytes[0] == 'n')
{
*response_ptr = false;
reader.SetIsDone(true);
}
else
{
if (out_fh && !reader.IsDone() && reader.GetPrompt())
{
::fprintf (out_fh, "Please answer \"y\" or \"n\"\n");
::fprintf (out_fh, "%s", reader.GetPrompt());
}
}
break;
case eInputReaderInterrupt:
case eInputReaderEndOfFile:
*response_ptr = false; // Assume ^C or ^D means cancel the proposed action
reader.SetIsDone (true);
break;
case eInputReaderDone:
break;
}
return bytes_len;
}
bool
CommandInterpreter::Confirm (const char *message, bool default_answer)
{
// Check AutoConfirm first:
if (m_debugger.GetAutoConfirm())
return default_answer;
InputReaderSP reader_sp (new InputReader(GetDebugger()));
bool response = default_answer;
if (reader_sp)
{
std::string prompt(message);
prompt.append(": [");
if (default_answer)
prompt.append ("Y/n] ");
else
prompt.append ("y/N] ");
Error err (reader_sp->Initialize (CommandInterpreter::GetConfirmationInputReaderCallback,
&response, // baton
eInputReaderGranularityLine, // token size, to pass to callback function
NULL, // end token
prompt.c_str(), // prompt
true)); // echo input
if (err.Success())
{
GetDebugger().PushInputReader (reader_sp);
}
reader_sp->WaitOnReaderIsDone();
}
return response;
}
void
CommandInterpreter::CrossRegisterCommand (const char * dest_cmd, const char * object_type)
{
CommandObjectSP cmd_obj_sp = GetCommandSPExact (dest_cmd, true);
if (cmd_obj_sp != NULL)
{
CommandObject *cmd_obj = cmd_obj_sp.get();
if (cmd_obj->IsCrossRefObject ())
cmd_obj->AddObject (object_type);
}
}
OptionArgVectorSP
CommandInterpreter::GetAliasOptions (const char *alias_name)
{
OptionArgMap::iterator pos;
OptionArgVectorSP ret_val;
std::string alias (alias_name);
if (HasAliasOptions())
{
pos = m_alias_options.find (alias);
if (pos != m_alias_options.end())
ret_val = pos->second;
}
return ret_val;
}
void
CommandInterpreter::RemoveAliasOptions (const char *alias_name)
{
OptionArgMap::iterator pos = m_alias_options.find(alias_name);
if (pos != m_alias_options.end())
{
m_alias_options.erase (pos);
}
}
void
CommandInterpreter::AddOrReplaceAliasOptions (const char *alias_name, OptionArgVectorSP &option_arg_vector_sp)
{
m_alias_options[alias_name] = option_arg_vector_sp;
}
bool
CommandInterpreter::HasCommands ()
{
return (!m_command_dict.empty());
}
bool
CommandInterpreter::HasAliases ()
{
return (!m_alias_dict.empty());
}
bool
CommandInterpreter::HasUserCommands ()
{
return (!m_user_dict.empty());
}
bool
CommandInterpreter::HasAliasOptions ()
{
return (!m_alias_options.empty());
}
void
CommandInterpreter::BuildAliasCommandArgs (CommandObject *alias_cmd_obj,
const char *alias_name,
Args &cmd_args,
std::string &raw_input_string,
CommandReturnObject &result)
{
OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
bool wants_raw_input = alias_cmd_obj->WantsRawCommandString();
// Make sure that the alias name is the 0th element in cmd_args
std::string alias_name_str = alias_name;
if (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0)
cmd_args.Unshift (alias_name);
Args new_args (alias_cmd_obj->GetCommandName());
if (new_args.GetArgumentCount() == 2)
new_args.Shift();
if (option_arg_vector_sp.get())
{
if (wants_raw_input)
{
// We have a command that both has command options and takes raw input. Make *sure* it has a
// " -- " in the right place in the raw_input_string.
size_t pos = raw_input_string.find(" -- ");
if (pos == std::string::npos)
{
// None found; assume it goes at the beginning of the raw input string
raw_input_string.insert (0, " -- ");
}
}
OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
int old_size = cmd_args.GetArgumentCount();
std::vector<bool> used (old_size + 1, false);
used[0] = true;
for (int i = 0; i < option_arg_vector->size(); ++i)
{
OptionArgPair option_pair = (*option_arg_vector)[i];
OptionArgValue value_pair = option_pair.second;
int value_type = value_pair.first;
std::string option = option_pair.first;
std::string value = value_pair.second;
if (option.compare ("<argument>") == 0)
{
if (!wants_raw_input
|| (value.compare("--") != 0)) // Since we inserted this above, make sure we don't insert it twice
new_args.AppendArgument (value.c_str());
}
else
{
if (value_type != optional_argument)
new_args.AppendArgument (option.c_str());
if (value.compare ("<no-argument>") != 0)
{
int index = GetOptionArgumentPosition (value.c_str());
if (index == 0)
{
// value was NOT a positional argument; must be a real value
if (value_type != optional_argument)
new_args.AppendArgument (value.c_str());
else
{
char buffer[255];
::snprintf (buffer, sizeof (buffer), "%s%s", option.c_str(), value.c_str());
new_args.AppendArgument (buffer);
}
}
else if (index >= cmd_args.GetArgumentCount())
{
result.AppendErrorWithFormat
("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
index);
result.SetStatus (eReturnStatusFailed);
return;
}
else
{
// Find and remove cmd_args.GetArgumentAtIndex(i) from raw_input_string
size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
if (strpos != std::string::npos)
{
raw_input_string = raw_input_string.erase (strpos, strlen (cmd_args.GetArgumentAtIndex (index)));
}
if (value_type != optional_argument)
new_args.AppendArgument (cmd_args.GetArgumentAtIndex (index));
else
{
char buffer[255];
::snprintf (buffer, sizeof(buffer), "%s%s", option.c_str(),
cmd_args.GetArgumentAtIndex (index));
new_args.AppendArgument (buffer);
}
used[index] = true;
}
}
}
}
for (int j = 0; j < cmd_args.GetArgumentCount(); ++j)
{
if (!used[j] && !wants_raw_input)
new_args.AppendArgument (cmd_args.GetArgumentAtIndex (j));
}
cmd_args.Clear();
cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
}
else
{
result.SetStatus (eReturnStatusSuccessFinishNoResult);
// This alias was not created with any options; nothing further needs to be done, unless it is a command that
// wants raw input, in which case we need to clear the rest of the data from cmd_args, since its in the raw
// input string.
if (wants_raw_input)
{
cmd_args.Clear();
cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
}
return;
}
result.SetStatus (eReturnStatusSuccessFinishNoResult);
return;
}
int
CommandInterpreter::GetOptionArgumentPosition (const char *in_string)
{
int position = 0; // Any string that isn't an argument position, i.e. '%' followed by an integer, gets a position
// of zero.
char *cptr = (char *) in_string;
// Does it start with '%'
if (cptr[0] == '%')
{
++cptr;
// Is the rest of it entirely digits?
if (isdigit (cptr[0]))
{
const char *start = cptr;
while (isdigit (cptr[0]))
++cptr;
// We've gotten to the end of the digits; are we at the end of the string?
if (cptr[0] == '\0')
position = atoi (start);
}
}
return position;
}
void
CommandInterpreter::SourceInitFile (bool in_cwd, CommandReturnObject &result)
{
// Don't parse any .lldbinit files if we were asked not to
if (m_skip_lldbinit_files)
return;
const char *init_file_path = in_cwd ? "./.lldbinit" : "~/.lldbinit";
FileSpec init_file (init_file_path, true);
// If the file exists, tell HandleCommand to 'source' it; this will do the actual broadcasting
// of the commands back to any appropriate listener (see CommandObjectSource::Execute for more details).
if (init_file.Exists())
{
char path[PATH_MAX];
init_file.GetPath(path, sizeof(path));
StreamString source_command;
source_command.Printf ("command source '%s'", path);
HandleCommand (source_command.GetData(), false, result);
}
else
{
// nothing to be done if the file doesn't exist
result.SetStatus(eReturnStatusSuccessFinishNoResult);
}
}
ScriptInterpreter *
CommandInterpreter::GetScriptInterpreter ()
{
if (m_script_interpreter_ap.get() != NULL)
return m_script_interpreter_ap.get();
lldb::ScriptLanguage script_lang = GetDebugger().GetScriptLanguage();
switch (script_lang)
{
case eScriptLanguageNone:
m_script_interpreter_ap.reset (new ScriptInterpreterNone (*this));
break;
case eScriptLanguagePython:
m_script_interpreter_ap.reset (new ScriptInterpreterPython (*this));
break;
default:
break;
};
return m_script_interpreter_ap.get();
}
bool
CommandInterpreter::GetSynchronous ()
{
return m_synchronous_execution;
}
void
CommandInterpreter::SetSynchronous (bool value)
{
m_synchronous_execution = value;
}
void
CommandInterpreter::OutputFormattedHelpText (Stream &strm,
const char *word_text,
const char *separator,
const char *help_text,
uint32_t max_word_len)
{
const uint32_t max_columns = m_debugger.GetTerminalWidth();
int indent_size = max_word_len + strlen (separator) + 2;
strm.IndentMore (indent_size);
int len = indent_size + strlen (help_text) + 1;
char *text = (char *) malloc (len);
sprintf (text, "%-*s %s %s", max_word_len, word_text, separator, help_text);
if (text[len - 1] == '\n')
text[--len] = '\0';
if (len < max_columns)
{
// Output it as a single line.
strm.Printf ("%s", text);
}
else
{
// We need to break it up into multiple lines.
bool first_line = true;
int text_width;
int start = 0;
int end = start;
int final_end = strlen (text);
int sub_len;
while (end < final_end)
{
if (first_line)
text_width = max_columns - 1;
else
text_width = max_columns - indent_size - 1;
// Don't start the 'text' on a space, since we're already outputting the indentation.
if (!first_line)
{
while ((start < final_end) && (text[start] == ' '))
start++;
}
end = start + text_width;
if (end > final_end)
end = final_end;
else
{
// If we're not at the end of the text, make sure we break the line on white space.
while (end > start
&& text[end] != ' ' && text[end] != '\t' && text[end] != '\n')
end--;
}
sub_len = end - start;
if (start != 0)
strm.EOL();
if (!first_line)
strm.Indent();
else
first_line = false;
assert (start <= final_end);
assert (start + sub_len <= final_end);
if (sub_len > 0)
strm.Write (text + start, sub_len);
start = end + 1;
}
}
strm.EOL();
strm.IndentLess(indent_size);
free (text);
}
void
CommandInterpreter::AproposAllSubCommands (CommandObject *cmd_obj, const char *prefix, const char *search_word,
StringList &commands_found, StringList &commands_help)
{
CommandObject::CommandMap::const_iterator pos;
CommandObject::CommandMap sub_cmd_dict = ((CommandObjectMultiword *) cmd_obj)->m_subcommand_dict;
CommandObject *sub_cmd_obj;
for (pos = sub_cmd_dict.begin(); pos != sub_cmd_dict.end(); ++pos)
{
const char * command_name = pos->first.c_str();
sub_cmd_obj = pos->second.get();
StreamString complete_command_name;
complete_command_name.Printf ("%s %s", prefix, command_name);
if (sub_cmd_obj->HelpTextContainsWord (search_word))
{
commands_found.AppendString (complete_command_name.GetData());
commands_help.AppendString (sub_cmd_obj->GetHelp());
}
if (sub_cmd_obj->IsMultiwordObject())
AproposAllSubCommands (sub_cmd_obj, complete_command_name.GetData(), search_word, commands_found,
commands_help);
}
}
void
CommandInterpreter::FindCommandsForApropos (const char *search_word, StringList &commands_found,
StringList &commands_help)
{
CommandObject::CommandMap::const_iterator pos;
for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
{
const char *command_name = pos->first.c_str();
CommandObject *cmd_obj = pos->second.get();
if (cmd_obj->HelpTextContainsWord (search_word))
{
commands_found.AppendString (command_name);
commands_help.AppendString (cmd_obj->GetHelp());
}
if (cmd_obj->IsMultiwordObject())
AproposAllSubCommands (cmd_obj, command_name, search_word, commands_found, commands_help);
}
}
|