forked from cyrus-and/gdb-dashboard
-
Notifications
You must be signed in to change notification settings - Fork 0
/
.gdbinit
1302 lines (1180 loc) · 48.4 KB
/
.gdbinit
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
python
# GDB dashboard - Modular visual interface for GDB in Python.
#
# https://github.com/cyrus-and/gdb-dashboard
import ast
import fcntl
import os
import re
import struct
import termios
# Common attributes ------------------------------------------------------------
class R():
@staticmethod
def attributes():
return {
# miscellaneous
'ansi': {
'doc': 'Control the ANSI output of the dashboard.',
'default': True,
'type': bool
},
'syntax_highlighting': {
'doc': """Pygments style to use for syntax highlighting.
Using an empty string (or a name not in the list) disables this feature.
The list of all the available styles can be obtained with (from GDB itself):
python from pygments.styles import get_all_styles as styles
python for s in styles(): print(s)
""",
'default': 'vim',
'type': str
},
# prompt
'prompt': {
'doc': """Command prompt.
This value is parsed as a Python format string in which `{status}` is expanded
with the substitution of either `prompt_running` or `prompt_not_running`
attributes, according to the target program status. The resulting string must be
a valid GDB prompt, see the command `python print(gdb.prompt.prompt_help())`""",
'default': '{status}'
},
'prompt_running': {
'doc': """`{status}` when the target program is running.
See the `prompt` attribute. This value is parsed as a Python format string in
which `{pid}` is expanded with the process identifier of the target program.""",
'default': '\[\e[1;35m\]>>>\[\e[0m\]'
},
'prompt_not_running': {
'doc': '`{status}` when the target program is not running.',
'default': '\[\e[1;30m\]>>>\[\e[0m\]'
},
# divider
'divider_fill_char_primary': {
'doc': 'Filler around the label for primary dividers',
'default': '─'
},
'divider_fill_char_secondary': {
'doc': 'Filler around the label for secondary dividers',
'default': '─'
},
'divider_fill_style_primary': {
'doc': 'Style for `divider_fill_char_primary`',
'default': '36'
},
'divider_fill_style_secondary': {
'doc': 'Style for `divider_fill_char_secondary`',
'default': '1;30'
},
'divider_label_style_on_primary': {
'doc': 'Label style for non-empty primary dividers',
'default': '1;33'
},
'divider_label_style_on_secondary': {
'doc': 'Label style for non-empty secondary dividers',
'default': '0'
},
'divider_label_style_off_primary': {
'doc': 'Label style for empty primary dividers',
'default': '33'
},
'divider_label_style_off_secondary': {
'doc': 'Label style for empty secondary dividers',
'default': '1;30'
},
'divider_label_skip': {
'doc': 'Gap between the aligning border and the label.',
'default': 3,
'type': int,
'check': check_ge_zero
},
'divider_label_margin': {
'doc': 'Number of spaces around the label.',
'default': 1,
'type': int,
'check': check_ge_zero
},
'divider_label_align_right': {
'doc': 'Label alignment flag.',
'default': False,
'type': bool
},
# common styles
'style_selected_1': {
'default': '1;32'
},
'style_selected_2': {
'default': '32'
},
'style_low': {
'default': '1;30'
},
'style_high': {
'default': '1;37'
},
'style_error': {
'default': '31'
}
}
# Common -----------------------------------------------------------------------
def run(command):
return gdb.execute(command, to_string=True)
def ansi(string, style):
if R.ansi:
return '\x1b[{}m{}\x1b[0m'.format(style, string)
else:
return string
def divider(label='', primary=False, active=True):
width = Dashboard.term_width
if primary:
divider_fill_style = R.divider_fill_style_primary
divider_fill_char = R.divider_fill_char_primary
divider_label_style_on = R.divider_label_style_on_primary
divider_label_style_off = R.divider_label_style_off_primary
else:
divider_fill_style = R.divider_fill_style_secondary
divider_fill_char = R.divider_fill_char_secondary
divider_label_style_on = R.divider_label_style_on_secondary
divider_label_style_off = R.divider_label_style_off_secondary
if label:
if active:
divider_label_style = divider_label_style_on
else:
divider_label_style = divider_label_style_off
skip = R.divider_label_skip
margin = R.divider_label_margin
before = ansi(divider_fill_char * skip, divider_fill_style)
middle = ansi(label, divider_label_style)
after_length = width - len(label) - skip - 2 * margin
after = ansi(divider_fill_char * after_length, divider_fill_style)
if R.divider_label_align_right:
before, after = after, before
return ''.join([before, ' ' * margin, middle, ' ' * margin, after])
else:
return ansi(divider_fill_char * width, divider_fill_style)
def check_gt_zero(x):
return x > 0
def check_ge_zero(x):
return x >= 0
def to_unsigned(value, size=8):
# values from GDB can be used transparently but are not suitable for
# being printed as unsigned integers, so a conversion is needed
return int(value.cast(gdb.Value(0).type)) % (2 ** (size * 8))
def to_string(value):
# attempt to convert an inferior value to string; OK when (Python 3 ||
# simple ASCII); otherwise (Python 2.7 && not ASCII) encode the string as
# utf8
try:
value_string = str(value)
except UnicodeEncodeError:
value_string = unicode(value).encode('utf8')
return value_string
def format_address(address):
pointer_size = gdb.parse_and_eval('$pc').type.sizeof
return ('0x{{:0{}x}}').format(pointer_size * 2).format(address)
def highlight(source, filename):
if not R.ansi:
highlighted = False
else:
try:
import pygments.lexers
import pygments.formatters
formatter_class = pygments.formatters.Terminal256Formatter
formatter = formatter_class(style=R.syntax_highlighting)
lexer = pygments.lexers.get_lexer_for_filename(filename)
source = pygments.highlight(source, lexer, formatter)
highlighted = True
except ImportError:
# Pygments not available
highlighted = False
except pygments.util.ClassNotFound:
# no lexer for this file or invalid style
highlighted = False
return highlighted, source.rstrip('\n')
# Dashboard --------------------------------------------------------------------
class Dashboard(gdb.Command):
"""Redisplay the dashboard."""
def __init__(self):
gdb.Command.__init__(self, 'dashboard',
gdb.COMMAND_USER, gdb.COMPLETE_NONE, True)
self.output = None # main terminal
# setup subcommands
Dashboard.OutputCommand(self)
Dashboard.EnabledCommand(self)
Dashboard.LayoutCommand(self)
# setup style commands
Dashboard.StyleCommand(self, 'dashboard', R, R.attributes())
# enable by default
self.enable()
def on_continue(self, _):
# try to contain the GDB messages in a specified area unless the
# dashboard is printed to a separate file
if self.is_running() and not self.output:
Dashboard.update_term_width()
gdb.write(Dashboard.clear_screen())
gdb.write(divider('Output/messages', True))
gdb.write('\n')
gdb.flush()
def on_stop(self, _):
# redisplay the dashboard when the target program stops (the screen is
# cleared by on_continue when the dashboard is printed to a separate
# file)
if self.is_running():
clear = Dashboard.clear_screen() if self.output else ''
self.display(clear, self.build(), '\n')
def on_exit(self, _):
pass
def enable(self):
self.enabled = True
# setup events
gdb.events.cont.connect(self.on_continue)
gdb.events.stop.connect(self.on_stop)
gdb.events.exited.connect(self.on_exit)
def disable(self):
self.enabled = False
# setup events
gdb.events.cont.disconnect(self.on_continue)
gdb.events.stop.disconnect(self.on_stop)
gdb.events.exited.disconnect(self.on_exit)
def load_modules(self, modules):
self.modules = []
for module in modules:
info = Dashboard.ModuleInfo(self, module)
self.modules.append(info)
def redisplay(self, style_changed=False):
# manually redisplay the dashboard
if self.is_running():
self.display(Dashboard.clear_screen(), self.build(style_changed))
def inferior_pid(self):
return gdb.selected_inferior().pid
def is_running(self):
return self.inferior_pid() != 0
def build(self, style_changed=False):
# fetch the output width
try:
fd = self.output.fileno() if self.output else 1 # main terminal
Dashboard.update_term_width(fd)
except:
# fall back to the main terminal
Dashboard.update_term_width()
# fetch lines
lines = []
for module in self.modules:
if not module.enabled:
continue
module = module.instance
# active if more than zero lines
module_lines = module.lines(style_changed)
lines.append(divider(module.label(), True, module_lines))
lines.extend(module_lines)
if len(lines) == 0:
lines.append(divider('Error', True))
if len(self.modules) == 0:
lines.append('No module loaded')
else:
lines.append('No module to display (see `help dashboard`)')
lines.append(divider(primary=True))
# print the dashboard
return '\n'.join(lines)
def display(self, *data):
# gdb module has both write() and flush()
try:
output = self.output or gdb
for string in data:
output.write(string)
output.flush()
except:
Dashboard.err('Cannot write the dashboard')
# Utility methods --------------------------------------------------------------
@staticmethod
def start():
# initialize the dashboard
dashboard = Dashboard()
Dashboard.set_custom_prompt(dashboard)
# parse Python inits, load modules then parse GDB inits
Dashboard.parse_inits(True)
modules = Dashboard.get_modules()
dashboard.load_modules(modules)
Dashboard.parse_inits(False)
# GDB overrides
run('set pagination off')
run('alias -a db = dashboard')
@staticmethod
def update_term_width(fd=1): # defaults to the main terminal
# first 2 shorts (4 byte) of struct winsize
raw = fcntl.ioctl(fd, termios.TIOCGWINSZ, ' ' * 4)
height, width = struct.unpack('hh', raw)
Dashboard.term_width = int(width)
@staticmethod
def set_custom_prompt(dashboard):
def custom_prompt(_):
# render thread status indicator
if dashboard.is_running():
pid = dashboard.inferior_pid()
status = R.prompt_running.format(pid=pid)
else:
status = R.prompt_not_running
# build prompt
prompt = R.prompt.format(status=status)
prompt = gdb.prompt.substitute_prompt(prompt)
return prompt + ' ' # force trailing space
gdb.prompt_hook = custom_prompt
@staticmethod
def parse_inits(python):
for root, dirs, files in os.walk(os.path.expanduser('~/.gdbinit.d/')):
dirs.sort()
for init in sorted(files):
path = os.path.join(root, init)
_, ext = os.path.splitext(path)
# either load Python files or GDB
if python ^ (ext != '.py'):
gdb.execute('source ' + path)
@staticmethod
def get_modules():
# scan the scope for modules
modules = []
for name in globals():
obj = globals()[name]
try:
if issubclass(obj, Dashboard.Module):
modules.append(obj)
except TypeError:
continue
# sort modules alphabetically
modules.sort(key=lambda x: x.__name__)
return modules
@staticmethod
def create_command(name, invoke, doc, is_prefix, complete=None):
Class = type('', (gdb.Command,), {'invoke': invoke, '__doc__': doc})
Class(name, gdb.COMMAND_USER, complete or gdb.COMPLETE_NONE, is_prefix)
@staticmethod
def err(string):
print(ansi(string, R.style_error))
@staticmethod
def complete(word, candidates):
matching = []
for candidate in candidates:
if candidate.startswith(word):
matching.append(candidate)
return matching
@staticmethod
def parse_arg(arg):
# encode unicode GDB command arguments as utf8 in Python 2.7
if type(arg) is not str:
arg = arg.encode('utf8')
return arg
@staticmethod
def clear_screen():
# ANSI: move the cursor to top-left corner and clear the screen
return '\x1b[H\x1b[J'
# Module descriptor ------------------------------------------------------------
class ModuleInfo:
def __init__(self, dashboard, module):
self.name = module.__name__.lower() # from class to module name
self.enabled = True
self.instance = module()
self.doc = self.instance.__doc__ or '(no documentation)'
self.prefix = 'dashboard {}'.format(self.name)
# add GDB commands
self.add_main_command(dashboard)
self.add_style_command(dashboard)
self.add_subcommands(dashboard)
def add_main_command(self, dashboard):
module = self
def invoke(self, arg, from_tty, info=self):
arg = Dashboard.parse_arg(arg)
if arg == '':
info.enabled ^= True
if dashboard.is_running():
dashboard.redisplay()
else:
status = 'enabled' if info.enabled else 'disabled'
print('{} module {}'.format(module.name, status))
else:
Dashboard.err('Wrong argument "{}"'.format(arg))
doc_brief = 'Configure the {} module.'.format(self.name)
doc_extended = 'Toggle the module visibility.'
doc = '{}\n{}\n\n{}'.format(doc_brief, doc_extended, self.doc)
Dashboard.create_command(self.prefix, invoke, doc, True)
def add_style_command(self, dashboard):
if 'attributes' in dir(self.instance):
Dashboard.StyleCommand(dashboard, self.prefix, self.instance,
self.instance.attributes())
def add_subcommands(self, dashboard):
if 'commands' in dir(self.instance):
for name, command in self.instance.commands().items():
self.add_subcommand(dashboard, name, command)
def add_subcommand(self, dashboard, name, command):
action = command['action']
doc = command['doc']
complete = command.get('complete')
def invoke(self, arg, from_tty, info=self):
arg = Dashboard.parse_arg(arg)
if info.enabled:
try:
action(arg)
except Exception as e:
Dashboard.err(e)
return
# don't catch redisplay errors
dashboard.redisplay()
else:
Dashboard.err('Module disabled')
prefix = '{} {}'.format(self.prefix, name)
Dashboard.create_command(prefix, invoke, doc, False, complete)
# GDB commands -----------------------------------------------------------------
def invoke(self, arg, from_tty):
arg = Dashboard.parse_arg(arg)
if arg == '':
if self.is_running():
self.redisplay()
else:
Dashboard.err('Is the target program running?')
else:
Dashboard.err('Wrong argument "{}"'.format(arg))
class OutputCommand(gdb.Command):
"""Set the dashboard output file/TTY.
The dashboard will be appended to the specified file, which will be created if
it does not exist. If the specified file identifies a terminal then its width
will be used to format the dashboard, otherwise falls back to the width of the
main GDB terminal. Without argument the dashboard will be printed on standard
output (default)."""
def __init__(self, dashboard):
gdb.Command.__init__(self, 'dashboard -output',
gdb.COMMAND_USER, gdb.COMPLETE_FILENAME)
self.dashboard = dashboard
def invoke(self, arg, from_tty):
arg = Dashboard.parse_arg(arg)
# close the previous output file, if any
if self.dashboard.output:
self.dashboard.output.close()
# set or open the output file
if arg == '':
self.dashboard.output = None
else:
try:
self.dashboard.output = open(arg, 'w')
except:
Dashboard.err('Cannot open "{}"'.format(arg))
# redisplay the dashboard in the new output
self.dashboard.redisplay()
class EnabledCommand(gdb.Command):
"""Enable or disable the dashboard [on|off].
The current status is printed if no argument is present."""
def __init__(self, dashboard):
gdb.Command.__init__(self, 'dashboard -enabled', gdb.COMMAND_USER)
self.dashboard = dashboard
def invoke(self, arg, from_tty):
arg = Dashboard.parse_arg(arg)
if arg == '':
status = 'enabled' if self.dashboard.enabled else 'disabled'
print('The dashboard is {}'.format(status))
elif arg == 'on':
self.dashboard.enable()
self.dashboard.redisplay()
elif arg == 'off':
self.dashboard.disable()
else:
msg = 'Wrong argument "{}"; expecting "on" or "off"'
Dashboard.err(msg.format(arg))
def complete(self, text, word):
return Dashboard.complete(word, ['on', 'off'])
class LayoutCommand(gdb.Command):
"""Set or show the dashboard layout.
Accepts a space-separated list of directive. Each directive is in the form
"[!]<module>". Modules in the list are placed in the dashboard in the same order
as they appear and those prefixed by "!" are disabled by default. Omitted
modules are hidden and placed at the bottom in alphabetical order. Without
arguments the current layout is shown; enabled and disabled modules are properly
marked."""
def __init__(self, dashboard):
gdb.Command.__init__(self, 'dashboard -layout', gdb.COMMAND_USER)
self.dashboard = dashboard
def invoke(self, arg, from_tty):
arg = Dashboard.parse_arg(arg)
directives = str(arg).split()
if directives:
self.layout(directives)
if from_tty and not self.dashboard.is_running():
self.show()
else:
self.show()
def show(self):
for module in self.dashboard.modules:
style = R.style_high if module.enabled else R.style_low
print(ansi(module.name, style))
def layout(self, directives):
modules = self.dashboard.modules
# reset visibility
for module in modules:
module.enabled = False
# move and enable the selected modules on top
last = 0
n_enabled = 0
for directive in directives:
# parse next directive
enabled = (directive[0] != '!')
name = directive[not enabled:]
try:
# it may actually start from last, but in this way repeated
# modules can be handler transparently and without error
todo = enumerate(modules[last:], start=last)
index = next(i for i, m in todo if name == m.name)
modules[index].enabled = enabled
modules.insert(last, modules.pop(index))
last += 1
n_enabled += enabled
except StopIteration:
def find_module(x):
return x.name == name
first_part = modules[:last]
if len(filter(find_module, first_part)) == 0:
Dashboard.err('Cannot find module "{}"'.format(name))
else:
Dashboard.err('Module "{}" already set'.format(name))
continue
# redisplay the dashboard
if n_enabled:
self.dashboard.redisplay()
def complete(self, text, word):
all_modules = (m.name for m in self.dashboard.modules)
return Dashboard.complete(word, all_modules)
class StyleCommand(gdb.Command):
"""Access the stylable attributes.
Without arguments print all the stylable attributes. Subcommands are used to set
or print (when the value is omitted) individual attributes."""
def __init__(self, dashboard, prefix, obj, attributes):
self.prefix = prefix + ' -style'
gdb.Command.__init__(self, self.prefix,
gdb.COMMAND_USER, gdb.COMPLETE_NONE, True)
self.dashboard = dashboard
self.obj = obj
self.attributes = attributes
self.add_styles()
def add_styles(self):
this = self
for name, attribute in self.attributes.items():
# fetch fields
attr_name = attribute.get('name', name)
attr_type = attribute.get('type', str)
attr_check = attribute.get('check', lambda _: True)
attr_default = attribute['default']
# set the default value (coerced to the type)
value = attr_type(attr_default)
setattr(self.obj, attr_name, value)
# create the command
def invoke(self, arg, from_tty, name=name, attr_name=attr_name,
attr_type=attr_type, attr_check=attr_check):
new_value = Dashboard.parse_arg(arg)
if new_value == '':
# print the current value
value = getattr(this.obj, attr_name)
print('{} = {!r}'.format(name, value))
else:
try:
# convert and check the new value
parsed = ast.literal_eval(new_value)
value = attr_type(parsed)
if not attr_check(value):
msg = 'Invalid value "{}" for "{}"'
raise Exception(msg.format(new_value, name))
except Exception as e:
Dashboard.err(e)
else:
# set and redisplay
setattr(this.obj, attr_name, value)
this.dashboard.redisplay(True)
prefix = self.prefix + ' ' + name
doc = attribute.get('doc', 'This style is self-documenting')
Dashboard.create_command(prefix, invoke, doc, False)
def invoke(self, arg, from_tty):
# an argument here means that the provided attribute is invalid
if arg:
Dashboard.err('Invalid argument "{}"'.format(arg))
return
# print all the pairs
for name, attribute in self.attributes.items():
attr_name = attribute.get('name', name)
value = getattr(self.obj, attr_name)
print('{} = {!r}'.format(name, value))
# Base module ------------------------------------------------------------------
# just a tag
class Module():
pass
# Default modules --------------------------------------------------------------
class Source(Dashboard.Module):
"""Show the program source code, if available."""
def __init__(self):
self.file_name = None
self.source_lines = []
self.ts = None
self.highlighted = False
def label(self):
return 'Source'
def lines(self, style_changed):
# try to fetch the current line (skip if no line information)
sal = gdb.selected_frame().find_sal()
current_line = sal.line
if current_line == 0:
return []
# reload the source file if changed
file_name = sal.symtab.fullname()
ts = None
try:
ts = os.path.getmtime(file_name)
except:
pass # delay error check to open()
if (style_changed or
file_name != self.file_name or # different file name
ts and ts > self.ts): # file modified in the meanwhile
self.file_name = file_name
self.ts = ts
try:
with open(self.file_name) as source_file:
self.highlighted, source = highlight(source_file.read(),
self.file_name)
self.source_lines = source.split('\n')
except Exception as e:
msg = 'Cannot display "{}" ({})'.format(self.file_name, e)
return [ansi(msg, R.style_error)]
# compute the line range
start = max(current_line - 1 - self.context, 0)
end = min(current_line - 1 + self.context + 1, len(self.source_lines))
# return the source code listing
out = []
number_format = '{{:>{}}}'.format(len(str(end)))
for number, line in enumerate(self.source_lines[start:end], start + 1):
if int(number) == current_line:
# the current line has a different style without ANSI
if R.ansi:
if self.highlighted:
line_format = ansi(number_format,
R.style_selected_1) + ' {}'
else:
line_format = ansi(number_format + ' {}',
R.style_selected_1)
else:
# just show a plain text indicator
line_format = number_format + '>{}'
else:
line_format = ansi(number_format, R.style_low) + ' {}'
out.append(line_format.format(number, line.rstrip('\n')))
return out
def attributes(self):
return {
'context': {
'doc': 'Number of context lines.',
'default': 5,
'type': int,
'check': check_ge_zero
}
}
class Assembly(Dashboard.Module):
"""Show the disassembled code surrounding the program counter. The
instructions constituting the current statement are marked, if available."""
def label(self):
return 'Assembly'
def lines(self, style_changed):
line_info = None
frame = gdb.selected_frame() # PC is here
disassemble = frame.architecture().disassemble
try:
# try to fetch the function boundaries using the disassemble command
output = run('disassemble').split('\n')
start = int(re.split('[ :]', output[1][3:], 1)[0], 16)
end = int(re.split('[ :]', output[-3][3:], 1)[0], 16)
asm = disassemble(start, end_pc=end)
# find the location of the PC
pc_index = next(index for index, instr in enumerate(asm)
if instr['addr'] == frame.pc())
start = max(pc_index - self.context, 0)
end = pc_index + self.context + 1
asm = asm[start:end]
# if there are line information then use it, it may be that
# line_info is not None but line_info.last is None
line_info = gdb.find_pc_line(frame.pc())
line_info = line_info if line_info.last else None
except (gdb.error, StopIteration):
# if it is not possible (stripped binary or the PC is not present in
# the output of `disassemble` as per issue #31) start from PC and
# end after twice the context
asm = disassemble(frame.pc(), count=2 * self.context + 1)
# fetch function start if available
func_start = None
if self.show_function and frame.name():
try:
value = gdb.parse_and_eval(frame.name()).address
func_start = to_unsigned(value)
except gdb.error:
pass # e.g., @plt
# fetch the assembly flavor and the extension used by Pygments
# TODO save the lexer and reuse it if performance becomes a problem
try:
flavor = gdb.parameter('disassembly-flavor')
except:
flavor = None # not always defined (see #36)
filename = {
'att': '.s',
'intel': '.asm'
}.get(flavor, '.s')
# return the machine code
max_length = max(instr['length'] for instr in asm)
inferior = gdb.selected_inferior()
out = []
for index, instr in enumerate(asm):
addr = instr['addr']
length = instr['length']
text = instr['asm']
addr_str = format_address(addr)
if self.show_opcodes:
# fetch and format opcode
region = inferior.read_memory(addr, length)
opcodes = (' '.join('{:02x}'.format(ord(byte))
for byte in region))
opcodes += (max_length - len(region)) * 3 * ' ' + ' '
else:
opcodes = ''
# compute the offset if available
if self.show_function:
if func_start:
max_offset = len(str(asm[-1]['addr'] - func_start))
offset = str(addr - func_start).ljust(max_offset)
func_info = '{}+{} '.format(frame.name(), offset)
else:
func_info = '? '
else:
func_info = ''
format_string = '{}{}{}{}{}'
indicator = ' '
highlighted, text = highlight(text, filename)
if addr == frame.pc():
if not R.ansi:
indicator = '>'
addr_str = ansi(addr_str, R.style_selected_1)
opcodes = ansi(opcodes, R.style_selected_1)
func_info = ansi(func_info, R.style_selected_1)
if not highlighted:
text = ansi(text, R.style_selected_1)
elif line_info and line_info.pc <= addr < line_info.last:
if not R.ansi:
indicator = ':'
addr_str = ansi(addr_str, R.style_selected_2)
opcodes = ansi(opcodes, R.style_selected_2)
func_info = ansi(func_info, R.style_selected_2)
if not highlighted:
text = ansi(text, R.style_selected_2)
else:
addr_str = ansi(addr_str, R.style_low)
func_info = ansi(func_info, R.style_low)
out.append(format_string.format(addr_str, indicator,
opcodes, func_info, text))
return out
def attributes(self):
return {
'context': {
'doc': 'Number of context instructions.',
'default': 3,
'type': int,
'check': check_ge_zero
},
'opcodes': {
'doc': 'Opcodes visibility flag.',
'default': False,
'name': 'show_opcodes',
'type': bool
},
'function': {
'doc': 'Function information visibility flag.',
'default': True,
'name': 'show_function',
'type': bool
}
}
class Stack(Dashboard.Module):
"""Show the current stack trace including the function name and the file
location, if available. Optionally list the frame arguments and locals too."""
def label(self):
return 'Stack'
def lines(self, style_changed):
frames = []
number = 0
selected_index = 0
frame = gdb.newest_frame()
while frame:
frame_lines = []
# fetch frame info
selected = (frame == gdb.selected_frame())
if selected:
selected_index = number
style = R.style_selected_1 if selected else R.style_selected_2
frame_id = ansi(str(number), style)
info = Stack.get_pc_line(frame, style)
frame_lines.append('[{}] {}'.format(frame_id, info))
# fetch frame arguments and locals
decorator = gdb.FrameDecorator.FrameDecorator(frame)
if self.show_arguments:
frame_args = decorator.frame_args()
args_lines = self.fetch_frame_info(frame, frame_args, 'arg')
if args_lines:
frame_lines.extend(args_lines)
else:
frame_lines.append(ansi('(no arguments)', R.style_low))
if self.show_locals:
frame_locals = decorator.frame_locals()
locals_lines = self.fetch_frame_info(frame, frame_locals, 'loc')
if locals_lines:
frame_lines.extend(locals_lines)
else:
frame_lines.append(ansi('(no locals)', R.style_low))
# add frame
frames.append(frame_lines)
# next
frame = frame.older()
number += 1
# format the output
if not self.limit or self.limit >= len(frames):
start = 0
end = len(frames)
more = False
else:
start = selected_index
end = min(len(frames), start + self.limit)
more = (len(frames) - start > self.limit)
lines = []
for frame_lines in frames[start:end]:
lines.extend(frame_lines)
# add the placeholder
if more:
lines.append('[{}]'.format(ansi('+', R.style_selected_2)))
return lines
def fetch_frame_info(self, frame, data, prefix):
prefix = ansi(prefix, R.style_low)
lines = []
for elem in data or []:
name = elem.sym
value = to_string(elem.sym.value(frame))
lines.append('{} {} = {}'.format(prefix, name, value))
return lines
@staticmethod
def get_pc_line(frame, style):
frame_pc = ansi(format_address(frame.pc()), style)
info = 'from {}'.format(frame_pc)
if frame.name():
frame_name = ansi(frame.name(), style)
try:
# try to compute the offset relative to the current function
value = gdb.parse_and_eval(frame.name()).address
# it can be None even if it is part of the "stack" (C++)
if value:
func_start = to_unsigned(value)
offset = frame.pc() - func_start
frame_name += '+' + ansi(str(offset), style)
except gdb.error:
pass # e.g., @plt
info += ' in {}'.format(frame_name)
sal = frame.find_sal()
if sal.symtab:
file_name = ansi(sal.symtab.filename, style)
file_line = ansi(str(sal.line), style)
info += ' at {}:{}'.format(file_name, file_line)
return info
def attributes(self):
return {
'limit': {
'doc': 'Maximum number of displayed frames (0 means no limit).',
'default': 2,
'type': int,
'check': check_ge_zero
},
'arguments': {
'doc': 'Frame arguments visibility flag.',
'default': True,
'name': 'show_arguments',
'type': bool
},
'locals': {
'doc': 'Frame locals visibility flag.',
'default': False,
'name': 'show_locals',
'type': bool
}
}
class History(Dashboard.Module):
"""List the last entries of the value history."""
def label(self):
return 'History'
def lines(self, style_changed):
out = []
# fetch last entries
for i in range(-self.limit + 1, 1):
try:
value = to_string(gdb.history(i))
value_id = ansi('$${}', R.style_low).format(abs(i))
line = '{} = {}'.format(value_id, value)