forked from quarnster/SublimeGDB
-
Notifications
You must be signed in to change notification settings - Fork 1
/
sublimegdb.py
2381 lines (1969 loc) · 80.7 KB
/
sublimegdb.py
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
"""
Copyright (c) 2012 Fredrik Ehnbom
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, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
"""
import sublime
import sublime_plugin
import subprocess
import struct
import tempfile
import threading
import time
import traceback
import os
import sys
import re
from datetime import datetime
from functools import partial
try:
import Queue
from resultparser import parse_result_line
def sencode(s):
return s.encode("utf-8")
def sdecode(s):
return s
def bencode(s):
return s
def bdecode(s):
return s
except:
def sencode(s):
return s
def sdecode(s):
return s
def bencode(s):
return s.encode("utf-8")
def bdecode(s):
return s.decode("utf-8")
import queue as Queue
from SublimeGDB.resultparser import parse_result_line
exec_settings = {}
def get_setting(key, default=None, view=None):
try:
if view is None:
view = sublime.active_window().active_view()
s = view.settings()
# Try executable specific settings first
if exec_settings and key in exec_settings:
return exec_settings[key]
# Then try user settings
if s.has("sublimegdb_%s" % key):
return s.get("sublimegdb_%s" % key)
except:
pass
# Default settings
return sublime.load_settings("SublimeGDB.sublime-settings").get(key, default)
def expand_path(value, window):
if window is None:
# Views can apparently be window less, in most instances getting
# the active_window will be the right choice (for example when
# previewing a file), but the one instance this is incorrect
# is during Sublime Text 2 session restore. Apparently it's
# possible for views to be windowless then too and since it's
# possible that multiple windows are to be restored, the
# "wrong" one for this view might be the active one and thus
# ${project_path} will not be expanded correctly.
#
# This will have to remain a known documented issue unless
# someone can think of something that should be done plugin
# side to fix this.
window = sublime.active_window()
get_existing_files = \
lambda m: [ path \
for f in window.folders() \
for path in [os.path.join(f, m.group('file'))] \
if os.path.exists(path) \
]
view = window.active_view()
file_name = view.file_name();
# replace variable with values
if file_name:
value = re.sub(r'\${file}', lambda m: file_name, value)
value = re.sub(r'\${file_base_name}', lambda m: os.path.splitext(os.path.basename(file_name))[0], value)
if os.getenv("HOME"):
value = re.sub(r'\${home}', re.escape(os.getenv('HOME')), value)
value = re.sub(r'\${env:(?P<variable>.*)}', lambda m: os.getenv(m.group('variable')), value)
# search in projekt for path and get folder from path
value = re.sub(r'\${project_path:(?P<file>[^}]+)}', lambda m: len(get_existing_files(m)) > 0 and get_existing_files(m)[0] or m.group('file'), value)
value = re.sub(r'\${folder:(?P<file>.*)}', lambda m: os.path.dirname(m.group('file')), value)
value = value.replace('\\', os.sep)
value = value.replace('/', os.sep)
return value
DEBUG = None
DEBUG_FILE = None
__debug_file_handle = None
gdb_lastresult = ""
gdb_lastline = ""
gdb_last_console_line = ""
gdb_cursor = ""
gdb_cursor_position = 0
gdb_last_cursor_view = None
gdb_bkp_layout = {}
gdb_bkp_window = None
gdb_bkp_view = None
gdb_python_command_running = False
gdb_shutting_down = False
gdb_process = None
gdb_server_process = None
gdb_threads = []
gdb_stack_frame = None
gdb_stack_index = 0
gdb_nonstop = False
if os.name == 'nt':
gdb_nonstop = False
gdb_run_status = None
result_regex = re.compile("(?<=\^)[^,\"]*")
collapse_regex = re.compile("{.*}", re.DOTALL)
def normalize(filename):
if filename is None:
return None
return os.path.abspath(os.path.normcase(filename))
def log_debug(line):
global __debug_file_handle
global DEBUG
if DEBUG:
try:
if __debug_file_handle is None:
if DEBUG_FILE == "stdout":
__debug_file_handle = sys.stdout
else:
__debug_file_handle = open(DEBUG_FILE, 'a')
__debug_file_handle.write(line)
except:
sublime.error_message("Couldn't write to the debug file. Debug writes will be disabled for this session.\n\nDebug file name used:\n%s\n\nError message\n:%s" % (DEBUG_FILE, traceback.format_exc()))
DEBUG = False
class GDBView(object):
def __init__(self, name, s=True, settingsprefix=None):
self.queue = Queue.Queue()
self.name = name
self.closed = True
self.doScroll = s
self.view = None
self.settingsprefix = settingsprefix
self.timer = None
self.lines = ""
self.lock = threading.RLock()
def is_open(self):
return not self.closed
def open_at_start(self):
if self.settingsprefix is not None:
return get_setting("%s_open" % self.settingsprefix, False)
return False
def open(self):
if self.view is None or self.view.window() is None:
if self.settingsprefix is not None:
sublime.active_window().focus_group(get_setting("%s_group" % self.settingsprefix, 0))
self.create_view()
def close(self):
if self.view is not None:
if self.settingsprefix is not None:
sublime.active_window().focus_group(get_setting("%s_group" % self.settingsprefix, 0))
self.destroy_view()
def should_update(self):
return self.is_open() and is_running() and gdb_run_status == "stopped"
def set_syntax(self, syntax):
if self.is_open():
self.get_view().set_syntax_file(syntax)
def timed_add(self):
try:
self.lock.acquire()
lines = self.lines
self.lines = ""
self.timer = None
self.queue.put((self.do_add_line, lines))
sublime.set_timeout(self.update, 0)
finally:
self.lock.release()
def add_line(self, line, now=True):
if self.is_open():
try:
self.lock.acquire()
self.lines += line
if self.timer:
self.timer.cancel()
if self.lines.count("\n") > 10 or now:
self.timed_add()
else:
self.timer = threading.Timer(0.1, self.timed_add)
self.timer.start()
finally:
self.lock.release()
def scroll(self, line):
if self.is_open():
self.queue.put((self.do_scroll, line))
sublime.set_timeout(self.update, 0)
def set_viewport_position(self, pos):
if self.is_open():
self.queue.put((self.do_set_viewport_position, pos))
sublime.set_timeout(self.update, 0)
def clear(self, now=False):
if self.is_open():
if not now:
self.queue.put((self.do_clear, None))
sublime.set_timeout(self.update, 0)
else:
self.do_clear(None)
def create_view(self):
self.view = sublime.active_window().new_file()
self.view.set_name(self.name)
self.view.set_scratch(True)
self.view.set_read_only(True)
self.view.settings().set("scroll_past_end", False)
# Setting command_mode to false so that vintage
# does not eat the "enter" keybinding
self.view.settings().set('command_mode', False)
self.closed = False
def destroy_view(self):
sublime.active_window().focus_view(self.view)
sublime.active_window().run_command("close")
self.view = None
self.closed = True
def is_closed(self):
return self.closed
def was_closed(self):
self.closed = True
def fold_all(self):
if self.is_open():
self.queue.put((self.do_fold_all, None))
def get_view(self):
return self.view
def do_add_line(self, line):
self.view.run_command("gdb_view_add_line", {"line": line, "doScroll": self.doScroll})
def do_fold_all(self, data):
self.view.run_command("fold_all")
def do_clear(self, data):
self.view.run_command("gdb_view_clear")
def do_scroll(self, data):
self.view.run_command("goto_line", {"line": data + 1})
def do_move_to_eof(self):
if self.view:
self.view.run_command("move_to", { "to": "eof", "extend": False })
def do_set_viewport_position(self, data):
# Shouldn't have to call viewport_extent, but it
# seems to flush whatever value is stale so that
# the following set_viewport_position works.
# Keeping it around as a WAR until it's fixed
# in Sublime Text 2.
self.view.viewport_extent()
self.view.set_viewport_position(data, False)
def update(self):
if not self.is_open():
return
try:
while not self.queue.empty():
cmd, data = self.queue.get()
try:
cmd(data)
finally:
self.queue.task_done()
except:
traceback.print_exc()
def on_activated(self):
# scroll to the end of the view on first activation
if self.doScroll and self.view.visible_region().empty():
# need a timeout because apparently a view can't be scrolled until
# it has been fully activated once
sublime.set_timeout(self.do_move_to_eof, 20)
def on_session_ended(self):
if get_setting("%s_clear_on_end" % self.settingsprefix, True):
self.clear()
class GdbViewClear(sublime_plugin.TextCommand):
def run(self, edit):
self.view.set_read_only(False)
self.view.erase(edit, sublime.Region(0, self.view.size()))
self.view.set_read_only(True)
class GdbViewAddLine(sublime_plugin.TextCommand):
def run(self, edit, line, doScroll):
# force a scroll to the end if the last line is currently visible
force_scroll = False
if doScroll and self.view.visible_region().contains(self.view.size()):
force_scroll = True
self.view.run_command("append", { "characters": line, "force": True })
if force_scroll:
self.view.run_command("move_to", { "to": "eof", "extend": False })
class GDBVariable:
def __init__(self, vp=None, parent=None):
self.parent = parent
self.valuepair = vp
self.children = []
self.line = 0
self.is_expanded = False
if "value" not in vp:
self.update_value()
self.dirty = False
self.deleted = False
def delete(self):
run_cmd("-var-delete %s" % self.get_name())
self.deleted = True
def update_value(self):
line = run_cmd("-var-evaluate-expression %s" % self["name"], True)
if get_result(line) == "done":
self['value'] = parse_result_line(line)["value"]
def update(self, d):
for key in d:
if key.startswith("new_"):
if key == "new_num_children":
self["numchild"] = d[key]
else:
self[key[4:]] = d[key]
else:
self[key] = d[key]
if (('dynamic' in self) and ('dynamic' not in d)):
del self['dynamic']
def is_existing(self):
# if there is a parent this variable should be existing
if self.parent:
return True
# try to find the line where this variable was declared
output = run_python_cmd("python print(gdb.lookup_symbol(\"%s\")[0].line)" % self["exp"], True)
try:
line = int(output)
# if the cursor is after this position the variable should be
# existing
if gdb_cursor_position > line:
return True
except:
pass
return False
def get_expression(self):
expression = ""
parent = self.parent
while parent is not None:
ispointer = "typecode" in parent and parent["typecode"] == "PTR"
expression = "%s%s%s" % (parent["exp"], "->" if ispointer else ".", expression)
parent = parent.parent
expression += self["exp"]
return expression
def add_children(self, name):
children = listify(parse_result_line(run_cmd("-var-list-children 1 \"%s\"" % name, True))["children"]["child"])
for child in children:
child = GDBVariable(child, parent=self)
if child.get_name().endswith(".private") or \
child.get_name().endswith(".protected") or \
child.get_name().endswith(".public"):
if child.has_children():
self.add_children(child.get_name())
else:
self.children.append(child)
def is_editable(self):
line = run_cmd("-var-show-attributes %s" % (self.get_name()), True)
return "editable" in re.findall("(?<=attr=\")[a-z]+(?=\")", line)
def edit_on_done(self, val):
line = run_cmd("-var-assign %s \"%s\"" % (self.get_name(), val), True)
if get_result(line) == "done":
self.valuepair["value"] = parse_result_line(line)["value"]
gdb_variables_view.update_variables(True)
else:
err = line[line.find("msg=") + 4:]
sublime.status_message("Error: %s" % err)
def find(self, name):
if self.deleted:
return None
if name == self.get_name():
return self
elif name.startswith(self.get_name()):
for child in self.children:
ret = child.find(name)
if ret is not None:
return ret
return None
def edit(self):
sublime.active_window().show_input_panel("%s =" % self["exp"], self.valuepair["value"], self.edit_on_done, None, None)
def get_name(self):
return self.valuepair["name"]
def expand(self):
if not self.is_existing():
return
self.is_expanded = True
if ((not self.children) and self.has_children()):
self.add_children(self.get_name())
def has_children(self):
if (int(self["numchild"]) > 0 or
(self.is_dynamic and int(self.valuepair.get("has_more", 0)) > 0)):
return True
# for dynamic child variables the has_more field is not available so we
# have to actually list the children to find out if there are any
if self.is_dynamic and self.is_existing():
children = parse_result_line(run_cmd("-var-list-children \"%s\"" % self.get_name(), True))
return int(children["numchild"]) > 0
return False
def collapse(self):
self.is_expanded = False
def __str__(self):
# apply the user-defined filters to the type
type = self.filter_type(self['type'])
if not "dynamic_type" in self or len(self['dynamic_type']) == 0 or self['dynamic_type'] == self['type']:
return "%s %s = %s" % (type, self['exp'], self['value'])
else:
return "%s %s = (%s) %s" % (type, self['exp'], self['dynamic_type'], self['value'])
def __iter__(self):
return self.valuepair.__iter__()
def __getitem__(self, key):
return self.valuepair[key]
def __setitem__(self, key, value):
self.valuepair[key] = value
if key == "value":
self.dirty = True
@property
def is_dynamic(self):
return ('dynamic' in self)
def update_from(self, var):
if (var.is_expanded):
self.expand()
for child in self.children:
otherChild = var.find_child_expression(child["exp"])
if (otherChild):
child.update_from(otherChild)
else:
child.dirty = True
self.dirty = (self["value"] != var["value"])
def find_child_expression(self, exp):
for child in self.children:
if (child["exp"] == exp):
return child
return None
def clear_dirty(self):
self.dirty = False
for child in self.children:
child.clear_dirty()
def is_dirty(self):
dirt = self.dirty
if not dirt and not self.is_expanded:
for child in self.children:
if child.is_dirty():
dirt = True
break
return dirt
def format(self, indent="", output="", line=0, dirty=[]):
icon = " "
if self.has_children():
if self.is_expanded:
icon = "-"
else:
icon = "+"
output += "%s%s%s\n" % (indent, icon, self)
self.line = line
line = line + 1
indent += " "
if self.is_expanded:
for child in self.children:
output, line = child.format(indent, output, line, dirty)
if self.is_dirty():
dirty.append(self)
return (output, line)
@staticmethod
def filter_type(type):
# use the regex module instead of re if available
sub = re.sub
try:
import regex
sub = regex.sub
except:
pass
# apply all user-defined filters
filters = get_setting("type_filters", [], gdb_variables_view)
for f in filters:
type = sub(f["pattern"], f["replace"], type)
return type
def qtod(q):
val = struct.pack("Q", q)
return struct.unpack("d", val)[0]
def itof(i):
val = struct.pack("I", i)
return struct.unpack("f", val)[0]
class GDBRegister:
def __init__(self, name, index, val):
self.name = name
self.index = index
self.value = val
self.line = 0
self.lines = 0
def format(self, line=0):
val = self.value
if "{" not in val and re.match(r"[\da-yA-Fx]+", val):
valh = int(val, 16)&0xffffffffffffffffffffffffffffffff
six4 = False
if valh > 0xffffffff:
six4 = True
val = struct.pack("Q" if six4 else "I", valh)
valf = struct.unpack("d" if six4 else "f", val)[0]
valI = struct.unpack("Q" if six4 else "I", val)[0]
vali = struct.unpack("q" if six4 else "i", val)[0]
val = "0x%016x %16.8f %020d %020d" % (valh, valf, valI, vali)
elif "{" in val:
match = re.search(r"(.*v4_float\s*=\s*\{)([^}]+)(\}.*v4_int32\s*=\s*\{([^\}]+)\}.*)", val)
if match:
floats = re.findall(r"0x[^,\}]+", match.group(4))
if len(floats) == 4:
floats = [str(itof(int(f, 16))) for f in floats]
val = match.expand(r"\g<1>%s\g<3>" % ", ".join(floats))
match = re.search(r"(.*v2_double\s*=\s*\{)([^}]+)(\}.*v2_int64\s*=\s*\{([^\}]+)\}.*)", val)
if match:
doubles = re.findall(r"0x[^,\}]+", match.group(4))
if len(doubles) == 2:
doubles = [str(qtod(int(f, 16))) for f in doubles]
val = match.expand(r"\g<1>%s\g<3>" % ", ".join(doubles))
output = "%8s: %s\n" % (self.name, val)
self.line = line
line += output.count("\n")
self.lines = line - self.line
return (output, line)
def set_value(self, val):
self.value = val
def set_gdb_value(self, val):
if "." in val:
if val.endswith("f"):
val = struct.unpack("I", struct.pack("f", float(val[:-1])))[0]
else:
val = struct.unpack("Q", struct.pack("d", float(val)))[0]
run_cmd("-data-evaluate-expression $%s=%s" % (self.name, val))
def edit_on_done(self, val):
self.set_gdb_value(val)
gdb_register_view.update_values()
def edit(self):
sublime.active_window().show_input_panel("$%s =" % self.name, self.value, self.edit_on_done, None, None)
class GDBRegisterView(GDBView):
def __init__(self):
super(GDBRegisterView, self).__init__("GDB Registers", s=False, settingsprefix="registers")
self.values = None
def open(self):
super(GDBRegisterView, self).open()
self.set_syntax("Packages/SublimeGDB/gdb_registers.tmLanguage")
self.get_view().settings().set("word_wrap", False)
if self.is_open() and gdb_run_status == "stopped":
self.update_values()
def get_names(self):
line = run_cmd("-data-list-register-names", True)
return parse_result_line(line)["register-names"]
def get_values(self):
line = run_cmd("-data-list-register-values x", True)
if get_result(line) != "done":
return []
return parse_result_line(line)["register-values"]
def update_values(self):
if not self.should_update():
return
dirtylist = []
if self.values is None:
names = self.get_names()
vals = self.get_values()
self.values = []
for i in range(len(vals)):
idx = int(vals[i]["number"])
self.values.append(GDBRegister(names[idx], idx, vals[i]["value"]))
else:
dirtylist = regs = parse_result_line(run_cmd("-data-list-changed-registers", True))["changed-registers"]
regvals = parse_result_line(run_cmd("-data-list-register-values x %s" % " ".join(regs), True))["register-values"]
for i in range(len(regs)):
reg = int(regvals[i]["number"])
if reg < len(self.values):
self.values[reg].set_value(regvals[i]["value"])
pos = self.get_view().viewport_position()
self.clear()
line = 0
for item in self.values:
output, line = item.format(line)
self.add_line(output)
self.set_viewport_position(pos)
self.update()
regions = []
v = self.get_view()
for dirty in dirtylist:
i = int(dirty)
if i >= len(self.values):
continue
region = v.full_line(v.text_point(self.values[i].line, 0))
if self.values[i].lines > 1:
region = region.cover(v.full_line(v.text_point(self.values[i].line + self.values[i].lines - 1, 0)))
regions.append(region)
v.add_regions("sublimegdb.dirtyregisters", regions,
get_setting("changed_variable_scope", "entity.name.class"),
get_setting("changed_variable_icon", ""),
sublime.DRAW_OUTLINED)
def get_register_at_line(self, line):
if self.values is None:
return None
for i in range(len(self.values)):
if self.values[i].line == line:
return self.values[i]
elif self.values[i].line > line:
return self.values[i - 1]
return None
class GDBVariablesView(GDBView):
def __init__(self):
super(GDBVariablesView, self).__init__("GDB Variables", False, settingsprefix="variables")
self.variables = []
def open(self):
super(GDBVariablesView, self).open()
self.set_syntax("Packages/C++/C++.tmLanguage")
if self.is_open() and gdb_run_status == "stopped":
self.update_variables(False)
def update_view(self):
self.clear()
output = ""
line = 0
dirtylist = []
for local in self.variables:
output, line = local.format(line=line, dirty=dirtylist)
self.add_line(output)
self.update()
regions = []
v = self.get_view()
for dirty in dirtylist:
regions.append(v.full_line(v.text_point(dirty.line, 0)))
v.add_regions("sublimegdb.dirtyvariables", regions,
get_setting("changed_variable_scope", "entity.name.class"),
get_setting("changed_variable_icon", ""),
sublime.DRAW_OUTLINED)
def extract_varnames(self, res):
if "name" in res:
return listify(res["name"])
elif len(res) > 0 and isinstance(res, list):
if "name" in res[0]:
return [x["name"] for x in res]
return []
def add_variable(self, exp):
v = self.create_variable(exp)
if v:
self.variables.append(v)
def create_variable(self, exp, show_error = True):
line = run_cmd("-var-create - * %s" % exp, True)
if get_result(line, False) == "error" and "&" in exp:
line = run_cmd("-var-create - * %s" % exp.replace("&", ""), True)
if get_result(line, show_error) == "error":
return None
var = parse_result_line(line)
var['exp'] = exp
return GDBVariable(var)
def update_variables(self, sameFrame):
if not self.should_update():
return
if sameFrame:
variables = []
for var in self.variables: # completely replace dynamic variables because we don't always get proper update notifications
if (var.is_dynamic):
var.delete()
newVar = self.create_variable(var['exp'], False)
if (newVar): # may have gone out of scope without notification
newVar.update_from(var)
variables.append(newVar)
else:
var.clear_dirty()
variables.append(var)
self.variables = variables
ret = parse_result_line(run_cmd("-var-update --all-values *", True))["changelist"]
if "varobj" in ret:
ret = listify(ret["varobj"])
dellist = []
for value in ret:
name = value["name"]
for var in self.variables:
real = var.find(name)
if (real is not None):
if "in_scope" in value and value["in_scope"] == "false":
real.delete()
dellist.append(real)
continue
if (not real.is_dynamic):
real.update(value)
if not "value" in value and not "new_value" in value:
real.update_value()
break
for item in dellist:
self.variables.remove(item)
if len(self.variables) == 0:
# Is it really the same frame? Seems everything was removed, so might as well pull all data again
sameFrame = False
else:
loc = self.extract_varnames(parse_result_line(run_cmd("-stack-list-locals 0", True))["locals"])
tracked = []
for var in loc:
create = True
for var2 in self.variables:
if var2['exp'] == var and var2 not in tracked:
tracked.append(var2)
create = False
break
if create:
self.add_variable(var)
if not sameFrame:
for var in self.variables:
var.delete()
args = self.extract_varnames(parse_result_line(run_cmd("-stack-list-arguments 0 %d %d" % (gdb_stack_index, gdb_stack_index), True))["stack-args"]["frame"]["args"])
self.variables = []
for arg in args:
self.add_variable(arg)
loc = self.extract_varnames(parse_result_line(run_cmd("-stack-list-locals 0", True))["locals"])
for var in loc:
self.add_variable(var)
self.update_view()
def get_variable_at_line(self, line, var_list=None):
if var_list is None:
var_list = self.variables
if len(var_list) == 0:
return None
for i in range(len(var_list)):
if var_list[i].line == line:
return var_list[i]
elif var_list[i].line > line:
return self.get_variable_at_line(line, var_list[i - 1].children)
return self.get_variable_at_line(line, var_list[len(var_list) - 1].children)
def expand_collapse_variable(self, view, expand=True, toggle=False):
row, col = view.rowcol(view.sel()[0].a)
if self.is_open() and view.id() == self.get_view().id():
var = self.get_variable_at_line(row)
if var and var.has_children():
if toggle:
if var.is_expanded:
var.collapse()
else:
var.expand()
elif expand:
var.expand()
else:
var.collapse()
pos = view.viewport_position()
self.update_view()
self.set_viewport_position(pos)
self.update()
class GDBCallstackFrame:
def __init__(self, func, args):
self.func = func
self.args = args
self.lines = 0
def format(self):
output = "%s(" % self.func
for arg in self.args:
if "name" in arg:
output += arg["name"]
if "value" in arg:
val = arg["value"]
val = collapse_regex.sub("{...}", val)
output += " = %s" % val
output += ","
output += ");\n"
self.lines = output.count("\n")
return output
class GDBCallstackView(GDBView):
def __init__(self):
super(GDBCallstackView, self).__init__("GDB Callstack", settingsprefix="callstack")
self.frames = []
def open(self):
super(GDBCallstackView, self).open()
self.set_syntax("Packages/C++/C++.tmLanguage")
if self.is_open() and gdb_run_status == "stopped":
self.update_callstack()
def update_callstack(self):
if not self.should_update():
return
global gdb_cursor_position
line = run_cmd("-stack-list-frames", True)
if get_result(line) == "error":
gdb_cursor_position = 0
update_view_markers()
return
frames = listify(parse_result_line(line)["stack"]["frame"])
args = listify(parse_result_line(run_cmd("-stack-list-arguments 1", True))["stack-args"]["frame"])
pos = self.get_view().viewport_position()
self.clear()
self.frames = []
for i in range(len(frames)):
arg = {}
if len(args) > i:
arg = args[i]["args"]
f = GDBCallstackFrame(frames[i]["func"], arg)
self.frames.append(f)
self.add_line(f.format())
self.set_viewport_position(pos)
self.update()
def update_marker(self, pos_scope, pos_icon):
if self.is_open():
view = self.get_view()
if gdb_stack_index != -1:
line = 0
for i in range(gdb_stack_index):
line += self.frames[i].lines
view.add_regions("sublimegdb.stackframe",
[view.line(view.text_point(line, 0))],
pos_scope, pos_icon, sublime.HIDDEN)
else:
view.erase_regions("sublimegdb.stackframe")
def select(self, row):
line = 0
for i in range(len(self.frames)):
fl = self.frames[i].lines
if row <= line + fl - 1:
run_cmd("-stack-select-frame %d" % i)
update_cursor()
break
line += fl
class GDBThread:
def __init__(self, id, state="UNKNOWN", func="???()", details=None):
self.id = id
self.state = state
self.func = func
self.details = details
def format(self):
if self.details:
return "%03d - %10s - %s - %s\n" % (self.id, self.state, self.details, self.func)
else:
return "%03d - %10s - %s\n" % (self.id, self.state, self.func)
class GDBThreadsView(GDBView):
def __init__(self):
super(GDBThreadsView, self).__init__("GDB Threads", s=False, settingsprefix="threads")
self.threads = []
self.current_thread = 0
def open(self):
super(GDBThreadsView, self).open()
self.set_syntax("Packages/C++/C++.tmLanguage")
if self.is_open() and gdb_run_status == "stopped":
self.update_threads()
def update_threads(self):
if not self.should_update():
return
res = run_cmd("-thread-info", True)
ids = parse_result_line(run_cmd("-thread-list-ids", True))
if get_result(res) == "error":
if "thread-ids" in ids and "thread-id" in ids["thread-ids"]:
self.threads = [GDBThread(int(id)) for id in ids["thread-ids"]["thread-id"]]
if "threads" in ids and "thread" in ids["threads"]:
for thread in ids["threads"]["thread"]:
if "thread-id" in thread and "state" in thread:
tid = int(thread["thread-id"])
for t2 in self.threads:
if t2.id == tid:
t2.state = thread["state"]