-
Notifications
You must be signed in to change notification settings - Fork 168
/
debug_session.py
2276 lines (1840 loc) · 75.5 KB
/
debug_session.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
# vimspector - A multi-language debugging system for Vim
# Copyright 2018 Ben Jackson
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import glob
import json
import logging
import os
import shlex
import subprocess
import functools
import vim
import importlib
import typing
from vimspector import ( breakpoints,
code,
core_utils,
debug_adapter_connection,
disassembly,
install,
output,
stack_trace,
utils,
variables,
settings,
terminal,
installer )
from vimspector.vendor.json_minify import minify
# We cache this once, and don't allow it to change (FIXME?)
VIMSPECTOR_HOME = utils.GetVimspectorBase()
# cache of what the user entered for any option we ask them
USER_CHOICES = {}
class DebugSession( object ):
child_sessions: typing.List[ "DebugSession" ]
def CurrentSession():
def decorator( fct ):
@functools.wraps( fct )
def wrapper( self: "DebugSession", *args, **kwargs ):
active_session = self
if self._stackTraceView:
active_session = self._stackTraceView.GetCurrentSession()
if active_session is not None:
return fct( active_session, *args, **kwargs )
return fct( self, *args, **kwargs )
return wrapper
return decorator
def ParentOnly( otherwise=None ):
def decorator( fct ):
@functools.wraps( fct )
def wrapper( self: "DebugSession", *args, **kwargs ):
if self.parent_session:
return otherwise
return fct( self, *args, **kwargs )
return wrapper
return decorator
def IfConnected( otherwise=None ):
def decorator( fct ):
"""Decorator, call fct if self._connected else echo warning"""
@functools.wraps( fct )
def wrapper( self: "DebugSession", *args, **kwargs ):
if not self._connection:
utils.UserMessage(
'Vimspector not connected, start a debug session first',
persist=False,
error=True )
return otherwise
return fct( self, *args, **kwargs )
return wrapper
return decorator
def RequiresUI( otherwise=None ):
"""Decorator, call fct if self._connected else echo warning"""
def decorator( fct ):
@functools.wraps( fct )
def wrapper( self, *args, **kwargs ):
if not self.HasUI():
utils.UserMessage(
'Vimspector is not active',
persist=False,
error=True )
return otherwise
return fct( self, *args, **kwargs )
return wrapper
return decorator
def __init__( self,
session_id,
session_manager,
api_prefix,
session_name = None,
parent_session: "DebugSession" = None ):
self.session_id = session_id
self.manager = session_manager
self.name = session_name
self.parent_session = parent_session
self.child_sessions = []
if parent_session:
parent_session.child_sessions.append( self )
self._logger = logging.getLogger( __name__ + '.' + str( session_id ) )
utils.SetUpLogging( self._logger, session_id )
self._api_prefix = api_prefix
self._render_emitter = utils.EventEmitter()
self._logger.info( "**** INITIALISING NEW VIMSPECTOR SESSION FOR ID "
f"{session_id } ****" )
self._logger.info( "API is: {}".format( api_prefix ) )
self._logger.info( 'VIMSPECTOR_HOME = %s', VIMSPECTOR_HOME )
self._logger.info( 'gadgetDir = %s',
install.GetGadgetDir( VIMSPECTOR_HOME ) )
self._uiTab = None
self._logView: output.OutputView = None
self._stackTraceView: stack_trace.StackTraceView = None
self._variablesView: variables.VariablesView = None
self._outputView: output.DAPOutputView = None
self._codeView: code.CodeView = None
self._disassemblyView: disassembly.DisassemblyView = None
if parent_session:
self._breakpoints = parent_session._breakpoints
else:
self._breakpoints = breakpoints.ProjectBreakpoints(
session_id,
self._render_emitter,
self._IsPCPresentAt,
self._disassemblyView )
utils.SetSessionWindows( {} )
self._saved_variables_data = None
self._splash_screen = None
self._remote_term = None
self._adapter_term = None
self._run_on_server_exit = None
self._configuration = None
self._adapter = None
self._launch_config = None
self._ResetServerState()
def _ResetServerState( self ):
self._connection = None
self._init_complete = False
self._launch_complete = False
self._on_init_complete_handlers = []
self._server_capabilities = {}
self._breakpoints.ClearTemporaryBreakpoints()
def GetConfigurations( self, adapters ):
current_file = utils.GetBufferFilepath( vim.current.buffer )
filetypes = utils.GetBufferFiletypes( vim.current.buffer )
configurations = settings.Dict( 'configurations' )
for launch_config_file in PathsToAllConfigFiles( VIMSPECTOR_HOME,
current_file,
filetypes ):
self._logger.debug( f'Reading configurations from: {launch_config_file}' )
if not launch_config_file or not os.path.exists( launch_config_file ):
continue
with open( launch_config_file, 'r' ) as f:
database = json.loads( minify( f.read() ) )
configurations.update( database.get( 'configurations' ) or {} )
adapters.update( database.get( 'adapters' ) or {} )
filetype_configurations = configurations
if filetypes:
# filter out any configurations that have a 'filetypes' list set and it
# doesn't contain one of the current filetypes
filetype_configurations = {
k: c for k, c in configurations.items() if 'filetypes' not in c or any(
ft in c[ 'filetypes' ] for ft in filetypes
)
}
return launch_config_file, filetype_configurations, configurations
def Name( self ):
return self.name if self.name else "Unnamed-" + str( self.session_id )
def DisplayName( self ):
return self.Name() + ' (' + str( self.session_id ) + ')'
@ParentOnly()
def Start( self,
force_choose = False,
launch_variables = None,
adhoc_configurations = None ):
# We mutate launch_variables, so don't mutate the default argument.
# https://docs.python-guide.org/writing/gotchas/#mutable-default-arguments
if launch_variables is None:
launch_variables = {}
self._logger.info( "User requested start debug session with %s",
launch_variables )
current_file = utils.GetBufferFilepath( vim.current.buffer )
adapters = settings.Dict( 'adapters' )
launch_config_file = None
configurations = None
if adhoc_configurations:
configurations = adhoc_configurations
else:
( launch_config_file,
configurations,
all_configurations ) = self.GetConfigurations( adapters )
if not configurations:
utils.UserMessage( 'Unable to find any debug configurations. '
'You need to tell vimspector how to launch your '
'application.' )
return
glob.glob( install.GetGadgetDir( VIMSPECTOR_HOME ) )
for gadget_config_file in PathsToAllGadgetConfigs( VIMSPECTOR_HOME,
current_file ):
self._logger.debug( f'Reading gadget config: {gadget_config_file}' )
if not gadget_config_file or not os.path.exists( gadget_config_file ):
continue
with open( gadget_config_file, 'r' ) as f:
a = json.loads( minify( f.read() ) ).get( 'adapters' ) or {}
adapters.update( a )
if 'configuration' in launch_variables:
configuration_name = launch_variables.pop( 'configuration' )
elif force_choose:
# Always display the menu
configuration_name = utils.SelectFromList(
'Which launch configuration?',
sorted( configurations.keys() ) )
elif ( len( configurations ) == 1 and
next( iter( configurations.values() ) ).get( "autoselect", True ) ):
configuration_name = next( iter( configurations.keys() ) )
else:
# Find a single configuration with 'default' True and autoselect not False
defaults = { n: c for n, c in configurations.items()
if c.get( 'default', False )
and c.get( 'autoselect', True ) }
if len( defaults ) == 1:
configuration_name = next( iter( defaults.keys() ) )
else:
configuration_name = utils.SelectFromList(
'Which launch configuration?',
sorted( configurations.keys() ) )
if not configuration_name or configuration_name not in configurations:
return
if self.name is None:
self.name = configuration_name
if launch_config_file:
self._workspace_root = os.path.dirname( launch_config_file )
else:
self._workspace_root = os.path.dirname( current_file )
try:
configuration = configurations[ configuration_name ]
except KeyError:
# Maybe the specified one by name that's not for this filetype? Let's try
# that one...
configuration = all_configurations[ configuration_name ]
current_configuration_name = configuration_name
while 'extends' in configuration:
base_configuration_name = configuration.pop( 'extends' )
base_configuration = all_configurations.get( base_configuration_name )
if base_configuration is None:
raise RuntimeError( f"The adapter { current_configuration_name } "
f"extends configuration { base_configuration_name }"
", but this does not exist" )
core_utils.override( base_configuration, configuration )
current_configuration_name = base_configuration_name
configuration = base_configuration
adapter = configuration.get( 'adapter' )
if isinstance( adapter, str ):
adapter_dict = adapters.get( adapter )
if adapter_dict is None:
suggested_gadgets = installer.FindGadgetForAdapter( adapter )
if suggested_gadgets:
response = utils.AskForInput(
f"The specified adapter '{adapter}' is not "
"installed. Would you like to install the following gadgets? ",
' '.join( suggested_gadgets ) )
if response:
new_launch_variables = dict( launch_variables )
new_launch_variables[ 'configuration' ] = configuration_name
installer.RunInstaller(
self._api_prefix,
False, # Don't leave open
*shlex.split( response ),
then = lambda: self.Start(
launch_variables = new_launch_variables ) )
return
elif response is None:
return
utils.UserMessage( f"The specified adapter '{adapter}' is not "
"available. Did you forget to run "
"'VimspectorInstall'?",
persist = True,
error = True )
return
adapter = adapter_dict
if not adapter:
utils.UserMessage( 'No adapter configured for {}'.format(
configuration_name ),
persist=True )
return
# Pull in anything from the base(s)
# FIXME: this is copypasta from above, but sharing the code is a little icky
# due to the way it returns from this method (maybe use an exception?)
while 'extends' in adapter:
base_adapter_name = adapter.pop( 'extends' )
base_adapter = adapters.get( base_adapter_name )
if base_adapter is None:
suggested_gadgets = installer.FindGadgetForAdapter( base_adapter_name )
if suggested_gadgets:
response = utils.AskForInput(
f"The specified base adapter '{base_adapter_name}' is not "
"installed. Would you like to install the following gadgets? ",
' '.join( suggested_gadgets ) )
if response:
new_launch_variables = dict( launch_variables )
new_launch_variables[ 'configuration' ] = configuration_name
installer.RunInstaller(
self._api_prefix,
False, # Don't leave open
*shlex.split( response ),
then = lambda: self.Start(
launch_variables = new_launch_variables ) )
return
elif response is None:
return
utils.UserMessage( f"The specified base adapter '{base_adapter_name}' "
"is not available. Did you forget to run "
"'VimspectorInstall'?",
persist = True,
error = True )
return
core_utils.override( base_adapter, adapter )
adapter = base_adapter
# Additional vars as defined by VSCode:
#
# ${workspaceFolder} - the path of the folder opened in VS Code
# ${workspaceFolderBasename} - the name of the folder opened in VS Code
# without any slashes (/)
# ${file} - the current opened file
# ${relativeFile} - the current opened file relative to workspaceFolder
# ${fileBasename} - the current opened file's basename
# ${fileBasenameNoExtension} - the current opened file's basename with no
# file extension
# ${fileDirname} - the current opened file's dirname
# ${fileExtname} - the current opened file's extension
# ${cwd} - the task runner's current working directory on startup
# ${lineNumber} - the current selected line number in the active file
# ${selectedText} - the current selected text in the active file
# ${execPath} - the path to the running VS Code executable
def relpath( p, relative_to ):
if not p:
return ''
return os.path.relpath( p, relative_to )
def splitext( p ):
if not p:
return [ '', '' ]
return os.path.splitext( p )
variables = {
'dollar': '$', # HACK. Hote '$$' also works.
'workspaceRoot': self._workspace_root,
'workspaceFolder': self._workspace_root,
'gadgetDir': install.GetGadgetDir( VIMSPECTOR_HOME ),
'file': current_file,
}
calculus = {
'relativeFileDirname': lambda: os.path.dirname( relpath( current_file,
self._workspace_root ) ),
'relativeFile': lambda: relpath( current_file,
self._workspace_root ),
'fileBasename': lambda: os.path.basename( current_file ),
'fileBasenameNoExtension':
lambda: splitext( os.path.basename( current_file ) )[ 0 ],
'fileDirname': lambda: os.path.dirname( current_file ),
'fileExtname': lambda: splitext( os.path.basename( current_file ) )[ 1 ],
# NOTE: this is the window-local cwd for the current window, *not* Vim's
# working directory.
'cwd': os.getcwd,
'unusedLocalPort': utils.GetUnusedLocalPort,
# The following, starting with uppercase letters, are 'functions' taking
# arguments.
'SelectProcess': _SelectProcess,
'PickProcess': _SelectProcess,
}
# Pretend that vars passed to the launch command were typed in by the user
# (they may have been in theory)
USER_CHOICES.update( launch_variables )
variables.update( launch_variables )
try:
variables.update(
utils.ParseVariables( adapter.pop( 'variables', {} ),
variables,
calculus,
USER_CHOICES ) )
variables.update(
utils.ParseVariables( configuration.pop( 'variables', {} ),
variables,
calculus,
USER_CHOICES ) )
utils.ExpandReferencesInDict( configuration,
variables,
calculus,
USER_CHOICES )
utils.ExpandReferencesInDict( adapter,
variables,
calculus,
USER_CHOICES )
except KeyboardInterrupt:
self._Reset()
return
self._StartWithConfiguration( configuration, adapter )
def _StartWithConfiguration( self, configuration, adapter ):
def start():
self._configuration = configuration
self._adapter = adapter
self._launch_config = None
self._logger.info( 'Configuration: %s',
json.dumps( self._configuration ) )
self._logger.info( 'Adapter: %s',
json.dumps( self._adapter ) )
if self.parent_session:
# use the parent session's stuff
self._uiTab = self.parent_session._uiTab
self._stackTraceView = self.parent_session._stackTraceView
self._variablesView = self.parent_session._variablesView
self._outputView = self.parent_session._outputView
self._disassemblyView = self.parent_session._disassemblyView
self._codeView = self.parent_session._codeView
elif not self._uiTab:
self._SetUpUI()
else:
with utils.NoAutocommands():
vim.current.tabpage = self._uiTab
self._stackTraceView.AddSession( self )
self._Prepare()
if not self._StartDebugAdapter():
self._logger.info( "Failed to launch or attach to the debug adapter" )
return
self._Initialise()
if self._saved_variables_data:
self._variablesView.Load( self._saved_variables_data )
if self._connection:
self._logger.debug( "Stop debug adapter with callback: start" )
self.StopAllSessions( interactive = False, then = start )
return
start()
@ParentOnly()
def Restart( self ):
if self._configuration is None or self._adapter is None:
return self.Start()
self._StartWithConfiguration( self._configuration, self._adapter )
def Connection( self ):
return self._connection
def HasUI( self ):
return self._uiTab and self._uiTab.valid
def IsUITab( self, tab_number ):
return self.HasUI() and self._uiTab.number == tab_number
@ParentOnly()
def SwitchTo( self ):
if self.HasUI():
vim.current.tabpage = self._uiTab
self._breakpoints.UpdateUI()
@ParentOnly()
def SwitchFrom( self ):
self._breakpoints.ClearUI()
def OnChannelData( self, data ):
if self._connection is None:
# Should _not_ happen, but maybe possible due to races or vim bufs?
return
self._connection.OnData( data )
def OnServerStderr( self, data ):
if self._outputView:
self._outputView.Print( 'server', data )
def OnRequestTimeout( self, timer_id ):
self._connection.OnRequestTimeout( timer_id )
def OnChannelClosed( self ):
# TODO: Not called
self._connection = None
def _StopNextSession( self, terminateDebuggee, then ):
if self.child_sessions:
c = self.child_sessions.pop()
c._StopNextSession( terminateDebuggee,
then = lambda: self._StopNextSession(
terminateDebuggee,
then ) )
elif self._connection:
self._StopDebugAdapter( terminateDebuggee, callback = then )
elif then:
then()
def StopAllSessions( self, interactive = False, then = None ):
if not interactive:
self._StopNextSession( None, then )
elif not self._server_capabilities.get( 'supportTerminateDebuggee' ):
self._StopNextSession( None, then )
elif not self._stackTraceView.AnyThreadsRunning():
self._StopNextSession( None, then )
else:
self._ConfirmTerminateDebugee(
lambda terminateDebuggee: self._StopNextSession( terminateDebuggee,
then ) )
@ParentOnly()
@IfConnected()
def Stop( self, interactive = False ):
self._logger.debug( "Stop debug adapter with no callback" )
self.StopAllSessions( interactive = False )
@ParentOnly()
def Destroy( self ):
"""Call when the vimspector session will be removed and never used again"""
if self._connection is not None:
raise RuntimeError( "Can't destroy a session with a live connection" )
if self.HasUI():
raise RuntimeError( "Can't destroy a session with an active UI" )
self.ClearBreakpoints()
self._ResetUI()
@ParentOnly()
def Reset( self, interactive = False ):
# We reset all of the child sessions in turn
self._logger.debug( "Stop debug adapter with callback: _Reset" )
self.StopAllSessions( interactive, self._Reset )
def _IsPCPresentAt( self, file_path, line ):
return self._codeView and self._codeView.IsPCPresentAt( file_path, line )
def _ResetUI( self ):
if not self.parent_session:
if self._stackTraceView:
self._stackTraceView.Reset()
if self._variablesView:
self._variablesView.Reset()
if self._outputView:
self._outputView.Reset()
if self._logView:
self._logView.Reset()
if self._codeView:
self._codeView.Reset()
if self._disassemblyView:
self._disassemblyView.Reset()
self._breakpoints.RemoveConnection( self._connection )
self._stackTraceView = None
self._variablesView = None
self._outputView = None
self._codeView = None
self._disassemblyView = None
self._remote_term = None
self._uiTab = None
if self.parent_session:
self.manager.DestroySession( self )
def _Reset( self ):
if self.parent_session:
self._ResetUI()
return
vim.vars[ 'vimspector_resetting' ] = 1
self._logger.info( "Debugging complete." )
if self.HasUI():
self._logger.debug( "Clearing down UI" )
with utils.NoAutocommands():
vim.current.tabpage = self._uiTab
self._splash_screen = utils.HideSplash( self._api_prefix,
self._splash_screen )
self._ResetUI()
vim.command( 'tabclose!' )
else:
self._ResetUI()
self._breakpoints.SetDisassemblyManager( None )
utils.SetSessionWindows( {
'breakpoints': vim.vars[ 'vimspector_session_windows' ].get(
'breakpoints' )
} )
vim.command( 'doautocmd <nomodeline> User VimspectorDebugEnded' )
vim.vars[ 'vimspector_resetting' ] = 0
# make sure that we're displaying signs in any still-open buffers
self._breakpoints.UpdateUI()
@ParentOnly( False )
def ReadSessionFile( self, session_file: str = None ):
if session_file is None:
session_file = self._DetectSessionFile( invent_one_if_not_found = False )
if session_file is None:
utils.UserMessage( f"No { settings.Get( 'session_file_name' ) } file "
"found. Specify a file with :VimspectorLoadSession "
"<filename>",
persist = True,
error = True )
return False
try:
with open( session_file, 'r' ) as f:
session_data = json.load( f )
USER_CHOICES.update(
session_data.get( 'session', {} ).get( 'user_choices', {} ) )
self._breakpoints.Load( session_data.get( 'breakpoints' ) )
# We might not _have_ a self._variablesView yet so we need a
# mechanism where we save this for later and reload when it's ready
variables_data = session_data.get( 'variables', {} )
if self._variablesView:
self._variablesView.Load( variables_data )
else:
self._saved_variables_data = variables_data
utils.UserMessage( f"Loaded session file { session_file }",
persist=True )
return True
except OSError:
self._logger.exception( f"Invalid session file { session_file }" )
utils.UserMessage( f"Session file { session_file } not found",
persist=True,
error=True )
return False
except json.JSONDecodeError:
self._logger.exception( f"Invalid session file { session_file }" )
utils.UserMessage( "The session file could not be read",
persist = True,
error = True )
return False
@ParentOnly( False )
def WriteSessionFile( self, session_file: str = None ):
if session_file is None:
session_file = self._DetectSessionFile( invent_one_if_not_found = True )
elif os.path.isdir( session_file ):
session_file = self._DetectSessionFile( invent_one_if_not_found = True,
in_directory = session_file )
try:
with open( session_file, 'w' ) as f:
f.write( json.dumps( {
'breakpoints': self._breakpoints.Save(),
'session': {
'user_choices': USER_CHOICES,
},
'variables': self._variablesView.Save() if self._variablesView else {}
} ) )
utils.UserMessage( f"Wrote { session_file }" )
return True
except OSError:
self._logger.exception( f"Unable to write session file { session_file }" )
utils.UserMessage( "The session file could not be read",
persist = True,
error = True )
return False
def _DetectSessionFile( self,
invent_one_if_not_found: bool,
in_directory: str = None ):
session_file_name = settings.Get( 'session_file_name' )
if in_directory:
# If a dir was supplied, read from there
write_directory = in_directory
file_path = os.path.join( in_directory, session_file_name )
if not os.path.exists( file_path ):
file_path = None
else:
# Otherwise, search based on the current file, and write based on CWD
current_file = utils.GetBufferFilepath( vim.current.buffer )
write_directory = os.getcwd()
# Search from the path of the file we're editing. But note that if we
# invent a file, we always use CWD as that's more like what would be
# expected.
file_path = utils.PathToConfigFile( session_file_name,
os.path.dirname( current_file ) )
if file_path:
return file_path
if invent_one_if_not_found:
return os.path.join( write_directory, session_file_name )
return None
@CurrentSession()
@IfConnected()
def StepOver( self, **kwargs ):
if self._stackTraceView.GetCurrentThreadId() is None:
return
arguments = {
'threadId': self._stackTraceView.GetCurrentThreadId(),
'granularity': self._CurrentSteppingGranularity(),
}
arguments.update( kwargs )
if not self._server_capabilities.get( 'supportsSteppingGranularity' ):
arguments.pop( 'granularity' )
self._connection.DoRequest( None, {
'command': 'next',
'arguments': arguments,
} )
# TODO: WHy is this different from StepInto and StepOut
self._stackTraceView.OnContinued( self )
self.ClearCurrentPC()
@CurrentSession()
@IfConnected()
def StepInto( self, **kwargs ):
threadId = self._stackTraceView.GetCurrentThreadId()
if threadId is None:
return
def handler( *_ ):
self._stackTraceView.OnContinued( self, { 'threadId': threadId } )
self.ClearCurrentPC()
arguments = {
'threadId': threadId,
'granularity': self._CurrentSteppingGranularity(),
}
arguments.update( kwargs )
self._connection.DoRequest( handler, {
'command': 'stepIn',
'arguments': arguments,
} )
@CurrentSession()
@IfConnected()
def StepOut( self, **kwargs ):
threadId = self._stackTraceView.GetCurrentThreadId()
if threadId is None:
return
def handler( *_ ):
self._stackTraceView.OnContinued( self, { 'threadId': threadId } )
self.ClearCurrentPC()
arguments = {
'threadId': threadId,
'granularity': self._CurrentSteppingGranularity(),
}
arguments.update( kwargs )
self._connection.DoRequest( handler, {
'command': 'stepOut',
'arguments': arguments,
} )
def _CurrentSteppingGranularity( self ):
if self._disassemblyView and self._disassemblyView.IsCurrent():
return 'instruction'
return 'statement'
@CurrentSession()
def Continue( self ):
if not self._connection:
self.Start()
return
threadId = self._stackTraceView.GetCurrentThreadId()
if threadId is None:
utils.UserMessage( 'No current thread', persist = True )
return
def handler( msg ):
self._stackTraceView.OnContinued( self, {
'threadId': threadId,
'allThreadsContinued': ( msg.get( 'body' ) or {} ).get(
'allThreadsContinued',
True )
} )
self.ClearCurrentPC()
self._connection.DoRequest( handler, {
'command': 'continue',
'arguments': {
'threadId': threadId,
},
} )
@CurrentSession()
@IfConnected()
def Pause( self ):
if self._stackTraceView.GetCurrentThreadId() is None:
utils.UserMessage( 'No current thread', persist = True )
return
self._connection.DoRequest( None, {
'command': 'pause',
'arguments': {
'threadId': self._stackTraceView.GetCurrentThreadId(),
},
} )
@IfConnected()
def PauseContinueThread( self ):
self._stackTraceView.PauseContinueThread()
@CurrentSession()
@IfConnected()
def SetCurrentThread( self ):
self._stackTraceView.SetCurrentThread()
@CurrentSession()
@IfConnected()
def ExpandVariable( self, buf = None, line_num = None ):
self._variablesView.ExpandVariable( buf, line_num )
@CurrentSession()
@IfConnected()
def SetVariableValue( self, new_value = None, buf = None, line_num = None ):
if not self._server_capabilities.get( 'supportsSetVariable' ):
return
self._variablesView.SetVariableValue( new_value, buf, line_num )
@ParentOnly()
def ReadMemory( self, length = None, offset = None ):
# We use the parent session because the actual connection is returned from
# the variables view (and might not be our self._connection) at least in
# theory.
if not self._server_capabilities.get( 'supportsReadMemoryRequest' ):
utils.UserMessage( "Server does not support memory request",
error = True )
return
connection: debug_adapter_connection.DebugAdapterConnection
connection, memoryReference = self._variablesView.GetMemoryReference()
if memoryReference is None or connection is None:
utils.UserMessage( "Cannot find memory reference for that",
error = True )
return
if length is None:
length = utils.AskForInput( 'How much data to display? ',
default_value = '1024' )
try:
length = int( length )
except ValueError:
return
if offset is None:
offset = utils.AskForInput( 'Location offset? ',
default_value = '0' )
try:
offset = int( offset )
except ValueError:
return
def handler( msg ):
self._codeView.ShowMemory( connection.GetSessionId(),
memoryReference,
length,
offset,
msg )
connection.DoRequest( handler, {
'command': 'readMemory',
'arguments': {
'memoryReference': memoryReference,
'count': int( length ),
'offset': int( offset )
}
} )
@CurrentSession()
@IfConnected()
@RequiresUI()
def ShowDisassembly( self ):
if self._disassemblyView and self._disassemblyView.WindowIsValid():
return
if not self._codeView or not self._codeView._window.valid:
return
if not self._stackTraceView:
return
if not self._server_capabilities.get( 'supportsDisassembleRequest', False ):
utils.UserMessage( "Sorry, server doesn't support that" )
return
with utils.LetCurrentWindow( self._codeView._window ):
vim.command( f'rightbelow { settings.Int( "disassembly_height" ) }new' )
self._disassemblyView = disassembly.DisassemblyView(