Debian Codegraph @

DebugAdapterClient/DebugAdapterClient.cpp

raw
1 //////////////////////////////////////////////////////////////////////////////
2 //////////////////////////////////////////////////////////////////////////////
3 //
4 // copyright : (C) 2014 Eran Ifrah
5 // file name : LLDBPlugin.cpp
6 //
7 // -------------------------------------------------------------------------
8 // A
9 // _____ _ _ _ _
10 // / __ \ | | | | (_) |
11 // | / \/ ___ __| | ___| | _| |_ ___
12 // | | / _ \ / _ |/ _ \ | | | __/ _ )
13 // | \__/\ (_) | (_| | __/ |___| | || __/
14 // \____/\___/ \__,_|\___\_____/_|\__\___|
15 //
16 // F i l e
17 //
18 // This program is free software; you can redistribute it and/or modify
19 // it under the terms of the GNU General Public License as published by
20 // the Free Software Foundation; either version 2 of the License, or
21 // (at your option) any later version.
22 //
23 //////////////////////////////////////////////////////////////////////////////
24 //////////////////////////////////////////////////////////////////////////////
25
26 #include "DebugAdapterClient.hpp"
27
28 #include "DAPBreakpointsView.h"
29 #include "DAPConsoleOutput.hpp"
30 #include "DAPMainView.h"
31 #include "DAPModuleView.h"
32 #include "DAPTextView.h"
33 #include "DAPTooltip.hpp"
34 #include "DAPWatchesView.h"
35 #include "DapDebuggerSettingsDlg.h"
36 #include "DapLocator.hpp"
37 #include "DapLoggingHelper.hpp"
38 #include "StringUtils.h"
39 #include "asyncprocess.h"
40 #include "bookmark_manager.h"
41 #include "clFileSystemWorkspace.hpp"
42 #include "clResizableTooltip.h"
43 #include "clWorkspaceManager.h"
44 #include "clcommandlineparser.h"
45 #include "console_frame.h"
46 #include "debuggermanager.h"
47 #include "dirsaver.h"
48 #include "environmentconfig.h"
49 #include "event_notifier.h"
50 #include "file_logger.h"
51 #include "globals.h"
52 #include "macromanager.h"
53 #include "processreaderthread.h"
54
55 #include <wx/aui/framemanager.h>
56 #include <wx/filename.h>
57 #include <wx/msgdlg.h>
58 #include <wx/platinfo.h>
59 #include <wx/stc/stc.h>
60 #include <wx/xrc/xmlres.h>
61
62 #if USE_SFTP
63 #include "sftp_settings.h"
64 #endif
65
66 static DebugAdapterClient* thePlugin = NULL;
67
68 namespace
69 {
70 clModuleLogger LOG;
71 #ifdef __WXMSW__
72 constexpr bool IS_WINDOWS = true;
73 #else
74 constexpr bool IS_WINDOWS = false;
75 #endif
76
77 const wxString DAP_MAIN_VIEW = _("Thread, stacks & variables");
78 const wxString DAP_BREAKPOINTS_VIEW = _("Breakpoints");
79 const wxString DAP_OUTPUT_VIEW = _("Output");
80 const wxString DAP_WATCHES_VIEW = _("Watches");
81
82 const wxString DAP_MESSAGE_BOX_TITLE = "CodeLite - Debug Adapter Client";
83
84 // Reusing gdb ids so global debugger menu and accelerators work.
85 const int lldbRunToCursorContextMenuId = XRCID("dbg_run_to_cursor");
86 const int lldbJumpToCursorContextMenuId = XRCID("dbg_jump_cursor");
87 const int lldbAddWatchContextMenuId = XRCID("lldb_add_watch");
88
89 wxString GetWatchWord(IEditor* editor)
90 {
91 CHECK_PTR_RET_EMPTY_STRING(editor);
92 auto word = editor->GetSelection();
93 if(word.IsEmpty()) {
94 word = editor->GetWordAtCaret();
95 }
96
97 // Remove leading and trailing whitespace.
98 word.Trim(true).Trim(false);
99 return word;
100 }
101
102 std::vector<wxString> to_string_array(const clEnvList_t& env_list)
103 {
104 std::vector<wxString> arr;
105 arr.reserve(env_list.size());
106 for(const auto& vt : env_list) {
107 arr.emplace_back(vt.first + "=" + vt.second);
108 }
109 return arr;
110 }
111
112 wxString get_dap_settings_file()
113 {
114 wxFileName fn(clStandardPaths::Get().GetUserDataDir(), "debug-adapter-client.conf");
115 fn.AppendDir("config");
116 return fn.GetFullPath();
117 }
118
119 } // namespace
120
121 #define CHECK_IS_DAP_CONNECTED() \
122 if(!m_client.IsConnected()) { \
123 event.Skip(); \
124 return; \
125 }
126
127 // Define the plugin entry point
128 CL_PLUGIN_API IPlugin* CreatePlugin(IManager* manager)
129 {
130 if(thePlugin == 0) {
131 thePlugin = new DebugAdapterClient(manager);
132 }
133 return thePlugin;
134 }
135
136 CL_PLUGIN_API PluginInfo* GetPluginInfo()
137 {
138 static PluginInfo info;
139 info.SetAuthor(wxT("eran"));
140 info.SetName(wxT("DebugAdapterClient"));
141 info.SetDescription(_("Debug Adapter Client"));
142 info.SetVersion(wxT("v1.0"));
143 return &info;
144 }
145
146 CL_PLUGIN_API int GetPluginInterfaceVersion() { return PLUGIN_INTERFACE_VERSION; }
147
148 DebugAdapterClient::DebugAdapterClient(IManager* manager)
149 : IPlugin(manager)
150 , m_terminal_helper(LOG)
151 , m_isPerspectiveLoaded(false)
152 {
153 // setup custom logger for this module
154 wxFileName logfile(clStandardPaths::Get().GetUserDataDir(), "debug-adapter-client.log");
155
156 LOG.Open(logfile);
157 LOG.SetCurrentLogLevel(FileLogger::Dbg);
158 LOG_DEBUG(LOG) << "Debug Adapter Client startd" << endl;
159 m_longName = _("Debug Adapter Client");
160 m_shortName = wxT("DebugAdapterClient");
161
162 // load settings
163 m_dap_store.Load(get_dap_settings_file());
164
165 RegisterDebuggers();
166
167 Bind(wxEVT_ASYNC_PROCESS_OUTPUT, &DebugAdapterClient::OnProcessOutput, this);
168 Bind(wxEVT_ASYNC_PROCESS_TERMINATED, &DebugAdapterClient::OnProcessTerminated, this);
169
170 // UI events
171 EventNotifier::Get()->Bind(wxEVT_FILE_LOADED, &DebugAdapterClient::OnFileLoaded, this);
172 EventNotifier::Get()->Bind(wxEVT_WORKSPACE_LOADED, &DebugAdapterClient::OnWorkspaceLoaded, this);
173 EventNotifier::Get()->Bind(wxEVT_WORKSPACE_CLOSED, &DebugAdapterClient::OnWorkspaceClosed, this);
174
175 EventNotifier::Get()->Bind(wxEVT_DBG_UI_START, &DebugAdapterClient::OnDebugStart, this);
176 EventNotifier::Get()->Bind(wxEVT_DBG_UI_CONTINUE, &DebugAdapterClient::OnDebugContinue, this);
177 EventNotifier::Get()->Bind(wxEVT_DBG_UI_NEXT, &DebugAdapterClient::OnDebugNext, this);
178 EventNotifier::Get()->Bind(wxEVT_DBG_UI_STEP_IN, &DebugAdapterClient::OnDebugStepIn, this);
179 EventNotifier::Get()->Bind(wxEVT_DBG_UI_STEP_OUT, &DebugAdapterClient::OnDebugStepOut, this);
180 EventNotifier::Get()->Bind(wxEVT_DBG_UI_STOP, &DebugAdapterClient::OnDebugStop, this);
181 EventNotifier::Get()->Bind(wxEVT_DBG_IS_RUNNING, &DebugAdapterClient::OnDebugIsRunning, this);
182 EventNotifier::Get()->Bind(wxEVT_DBG_CAN_INTERACT, &DebugAdapterClient::OnDebugCanInteract, this);
183 EventNotifier::Get()->Bind(wxEVT_DBG_UI_INTERRUPT, &DebugAdapterClient::OnToggleInterrupt, this);
184 EventNotifier::Get()->Bind(wxEVT_BUILD_STARTING, &DebugAdapterClient::OnBuildStarting, this);
185 EventNotifier::Get()->Bind(wxEVT_INIT_DONE, &DebugAdapterClient::OnInitDone, this);
186 EventNotifier::Get()->Bind(wxEVT_DBG_EXPR_TOOLTIP, &DebugAdapterClient::OnDebugTooltip, this);
187 EventNotifier::Get()->Bind(wxEVT_QUICK_DEBUG, &DebugAdapterClient::OnDebugQuickDebug, this);
188 EventNotifier::Get()->Bind(wxEVT_TOOLTIP_DESTROY, &DebugAdapterClient::OnDestroyTip, this);
189 EventNotifier::Get()->Bind(wxEVT_DBG_UI_CORE_FILE, &DebugAdapterClient::OnDebugCoreFile, this);
190 EventNotifier::Get()->Bind(wxEVT_DBG_UI_DELETE_ALL_BREAKPOINTS, &DebugAdapterClient::OnDebugDeleteAllBreakpoints,
191 this);
192 EventNotifier::Get()->Bind(wxEVT_DBG_UI_ATTACH_TO_PROCESS, &DebugAdapterClient::OnDebugAttachToProcess, this);
193 EventNotifier::Get()->Bind(wxEVT_DBG_UI_ENABLE_ALL_BREAKPOINTS, &DebugAdapterClient::OnDebugEnableAllBreakpoints,
194 this);
195 EventNotifier::Get()->Bind(wxEVT_DBG_UI_DISABLE_ALL_BREAKPOINTS, &DebugAdapterClient::OnDebugDisableAllBreakpoints,
196 this);
197 EventNotifier::Get()->Bind(wxEVT_DBG_UI_NEXT_INST, &DebugAdapterClient::OnDebugNextInst, this);
198 EventNotifier::Get()->Bind(wxEVT_DBG_UI_STEP_I, &DebugAdapterClient::OnDebugVOID, this); // not supported
199
200 EventNotifier::Get()->Bind(wxEVT_DBG_UI_SHOW_CURSOR, &DebugAdapterClient::OnDebugShowCursor, this);
201 wxTheApp->Bind(wxEVT_MENU, &DebugAdapterClient::OnSettings, this, XRCID("lldb_settings"));
202
203 wxTheApp->Bind(wxEVT_COMMAND_MENU_SELECTED, &DebugAdapterClient::OnAddWatch, this, lldbAddWatchContextMenuId);
204 wxTheApp->Bind(wxEVT_IDLE, &DebugAdapterClient::OnIdle, this);
205 dap::Initialize(); // register all dap objects
206
207 m_client.SetWantsLogEvents(true);
208 m_client.Bind(wxEVT_DAP_INITIALIZE_RESPONSE, &DebugAdapterClient::OnDapInitializeResponse, this);
209 m_client.Bind(wxEVT_DAP_INITIALIZED_EVENT, &DebugAdapterClient::OnDapInitializedEvent, this);
210 m_client.Bind(wxEVT_DAP_RUN_IN_TERMINAL_REQUEST, &DebugAdapterClient::OnDapRunInTerminal, this);
211 m_client.Bind(wxEVT_DAP_EXITED_EVENT, &DebugAdapterClient::OnDapExited, this);
212 m_client.Bind(wxEVT_DAP_TERMINATED_EVENT, &DebugAdapterClient::OnDapExited, this);
213 m_client.Bind(wxEVT_DAP_LAUNCH_RESPONSE, &DebugAdapterClient::OnDapLaunchResponse, this);
214 m_client.Bind(wxEVT_DAP_STOPPED_EVENT, &DebugAdapterClient::OnDapStoppedEvent, this);
215 m_client.Bind(wxEVT_DAP_THREADS_RESPONSE, &DebugAdapterClient::OnDapThreadsResponse, this);
216 m_client.Bind(wxEVT_DAP_STACKTRACE_RESPONSE, &DebugAdapterClient::OnDapStackTraceResponse, this);
217 m_client.Bind(wxEVT_DAP_SCOPES_RESPONSE, &DebugAdapterClient::OnDapScopesResponse, this);
218 m_client.Bind(wxEVT_DAP_VARIABLES_RESPONSE, &DebugAdapterClient::OnDapVariablesResponse, this);
219 m_client.Bind(wxEVT_DAP_SET_FUNCTION_BREAKPOINT_RESPONSE, &DebugAdapterClient::OnDapSetFunctionBreakpointResponse,
220 this);
221 m_client.Bind(wxEVT_DAP_SET_SOURCE_BREAKPOINT_RESPONSE, &DebugAdapterClient::OnDapSetSourceBreakpointResponse,
222 this);
223 m_client.Bind(wxEVT_DAP_LOG_EVENT, &DebugAdapterClient::OnDapLog, this);
224 m_client.Bind(wxEVT_DAP_BREAKPOINT_EVENT, &DebugAdapterClient::OnDapBreakpointEvent, this);
225 m_client.Bind(wxEVT_DAP_OUTPUT_EVENT, &DebugAdapterClient::OnDapOutputEvent, this);
226 m_client.Bind(wxEVT_DAP_MODULE_EVENT, &DebugAdapterClient::OnDapModuleEvent, this);
227 EventNotifier::Get()->Bind(wxEVT_NOTIFY_PAGE_CLOSING, &DebugAdapterClient::OnPageClosing, this);
228 }
229
230 void DebugAdapterClient::UnPlug()
231 {
232 wxDELETE(m_breakpointsHelper);
233 wxTheApp->Unbind(wxEVT_IDLE, &DebugAdapterClient::OnIdle, this);
234 // DestroyUI();
235 DebuggerMgr::Get().UnregisterDebuggers(m_shortName);
236
237 // UI events
238 EventNotifier::Get()->Unbind(wxEVT_FILE_LOADED, &DebugAdapterClient::OnFileLoaded, this);
239 EventNotifier::Get()->Unbind(wxEVT_WORKSPACE_LOADED, &DebugAdapterClient::OnWorkspaceLoaded, this);
240 EventNotifier::Get()->Unbind(wxEVT_WORKSPACE_CLOSED, &DebugAdapterClient::OnWorkspaceClosed, this);
241
242 EventNotifier::Get()->Unbind(wxEVT_DBG_UI_START, &DebugAdapterClient::OnDebugStart, this);
243 EventNotifier::Get()->Unbind(wxEVT_DBG_UI_CONTINUE, &DebugAdapterClient::OnDebugContinue, this);
244 EventNotifier::Get()->Unbind(wxEVT_DBG_UI_NEXT, &DebugAdapterClient::OnDebugNext, this);
245 EventNotifier::Get()->Unbind(wxEVT_DBG_UI_STOP, &DebugAdapterClient::OnDebugStop, this);
246 EventNotifier::Get()->Unbind(wxEVT_DBG_IS_RUNNING, &DebugAdapterClient::OnDebugIsRunning, this);
247 EventNotifier::Get()->Unbind(wxEVT_DBG_CAN_INTERACT, &DebugAdapterClient::OnDebugCanInteract, this);
248 EventNotifier::Get()->Unbind(wxEVT_DBG_UI_STEP_IN, &DebugAdapterClient::OnDebugStepIn, this);
249 EventNotifier::Get()->Unbind(wxEVT_DBG_UI_STEP_OUT, &DebugAdapterClient::OnDebugStepOut, this);
250 EventNotifier::Get()->Unbind(wxEVT_DBG_UI_INTERRUPT, &DebugAdapterClient::OnToggleInterrupt, this);
251 EventNotifier::Get()->Unbind(wxEVT_BUILD_STARTING, &DebugAdapterClient::OnBuildStarting, this);
252 EventNotifier::Get()->Unbind(wxEVT_INIT_DONE, &DebugAdapterClient::OnInitDone, this);
253 EventNotifier::Get()->Unbind(wxEVT_DBG_EXPR_TOOLTIP, &DebugAdapterClient::OnDebugTooltip, this);
254 EventNotifier::Get()->Unbind(wxEVT_QUICK_DEBUG, &DebugAdapterClient::OnDebugQuickDebug, this);
255 EventNotifier::Get()->Unbind(wxEVT_TOOLTIP_DESTROY, &DebugAdapterClient::OnDestroyTip, this);
256 EventNotifier::Get()->Unbind(wxEVT_DBG_UI_CORE_FILE, &DebugAdapterClient::OnDebugCoreFile, this);
257 EventNotifier::Get()->Unbind(wxEVT_DBG_UI_DELETE_ALL_BREAKPOINTS, &DebugAdapterClient::OnDebugDeleteAllBreakpoints,
258 this);
259 EventNotifier::Get()->Unbind(wxEVT_DBG_UI_ATTACH_TO_PROCESS, &DebugAdapterClient::OnDebugAttachToProcess, this);
260 EventNotifier::Get()->Unbind(wxEVT_DBG_UI_ENABLE_ALL_BREAKPOINTS, &DebugAdapterClient::OnDebugEnableAllBreakpoints,
261 this);
262 EventNotifier::Get()->Unbind(wxEVT_DBG_UI_DISABLE_ALL_BREAKPOINTS,
263 &DebugAdapterClient::OnDebugDisableAllBreakpoints, this);
264 EventNotifier::Get()->Unbind(wxEVT_DBG_UI_STEP_I, &DebugAdapterClient::OnDebugVOID, this); // Not supported
265 EventNotifier::Get()->Unbind(wxEVT_DBG_UI_NEXT_INST, &DebugAdapterClient::OnDebugNextInst, this);
266 EventNotifier::Get()->Unbind(wxEVT_DBG_UI_SHOW_CURSOR, &DebugAdapterClient::OnDebugShowCursor, this);
267 wxTheApp->Unbind(wxEVT_MENU, &DebugAdapterClient::OnSettings, this, XRCID("lldb_settings"));
268
269 // Dap events
270 m_client.Unbind(wxEVT_DAP_INITIALIZE_RESPONSE, &DebugAdapterClient::OnDapInitializeResponse, this);
271 m_client.Unbind(wxEVT_DAP_INITIALIZED_EVENT, &DebugAdapterClient::OnDapInitializedEvent, this);
272 m_client.Unbind(wxEVT_DAP_RUN_IN_TERMINAL_REQUEST, &DebugAdapterClient::OnDapRunInTerminal, this);
273 m_client.Unbind(wxEVT_DAP_EXITED_EVENT, &DebugAdapterClient::OnDapExited, this);
274 m_client.Unbind(wxEVT_DAP_TERMINATED_EVENT, &DebugAdapterClient::OnDapExited, this);
275 m_client.Unbind(wxEVT_DAP_LAUNCH_RESPONSE, &DebugAdapterClient::OnDapLaunchResponse, this);
276 m_client.Unbind(wxEVT_DAP_STOPPED_EVENT, &DebugAdapterClient::OnDapStoppedEvent, this);
277 m_client.Unbind(wxEVT_DAP_THREADS_RESPONSE, &DebugAdapterClient::OnDapThreadsResponse, this);
278 m_client.Unbind(wxEVT_DAP_STACKTRACE_RESPONSE, &DebugAdapterClient::OnDapStackTraceResponse, this);
279 m_client.Unbind(wxEVT_DAP_SCOPES_RESPONSE, &DebugAdapterClient::OnDapScopesResponse, this);
280 m_client.Unbind(wxEVT_DAP_VARIABLES_RESPONSE, &DebugAdapterClient::OnDapVariablesResponse, this);
281 m_client.Unbind(wxEVT_DAP_SET_FUNCTION_BREAKPOINT_RESPONSE, &DebugAdapterClient::OnDapSetFunctionBreakpointResponse,
282 this);
283 m_client.Unbind(wxEVT_DAP_SET_SOURCE_BREAKPOINT_RESPONSE, &DebugAdapterClient::OnDapSetSourceBreakpointResponse,
284 this);
285 m_client.Unbind(wxEVT_DAP_LOG_EVENT, &DebugAdapterClient::OnDapLog, this);
286 m_client.Unbind(wxEVT_DAP_BREAKPOINT_EVENT, &DebugAdapterClient::OnDapBreakpointEvent, this);
287 m_client.Unbind(wxEVT_DAP_OUTPUT_EVENT, &DebugAdapterClient::OnDapOutputEvent, this);
288 m_client.Unbind(wxEVT_DAP_MODULE_EVENT, &DebugAdapterClient::OnDapModuleEvent, this);
289 EventNotifier::Get()->Unbind(wxEVT_NOTIFY_PAGE_CLOSING, &DebugAdapterClient::OnPageClosing, this);
290 }
291
292 DebugAdapterClient::~DebugAdapterClient() {}
293
294 void DebugAdapterClient::RegisterDebuggers()
295 {
296 wxArrayString debuggers;
297 debuggers.reserve(m_dap_store.GetEntries().size());
298 for(const auto& entry : m_dap_store.GetEntries()) {
299 debuggers.Add(entry.first);
300 }
301 DebuggerMgr::Get().RegisterDebuggers(m_shortName, debuggers);
302 }
303
304 bool DebugAdapterClient::ShowThreadNames() const { return m_showThreadNames; }
305
306 wxString DebugAdapterClient::GetFilenameForDisplay(const wxString& fileName) const
307 {
308 if(m_showFileNamesOnly) {
309 return wxFileName(fileName).GetFullName();
310 } else {
311 return fileName;
312 }
313 }
314
315 void DebugAdapterClient::CreateToolBar(clToolBarGeneric* toolbar) { wxUnusedVar(toolbar); }
316
317 void DebugAdapterClient::CreatePluginMenu(wxMenu* pluginsMenu)
318 {
319 // We want to add an entry in the global settings menu
320 // Menu Bar > Settings > LLDB Settings
321
322 // Get the main frame's menubar
323 auto mb = clGetManager()->GetMenuBar();
324 if(mb) {
325 wxMenu* settingsMenu(NULL);
326 int menuPos = mb->FindMenu(_("Settings"));
327 if(menuPos != wxNOT_FOUND) {
328 settingsMenu = mb->GetMenu(menuPos);
329 if(settingsMenu) {
330 settingsMenu->Append(XRCID("lldb_settings"), _("Debug Adapter Client..."));
331 }
332 }
333 }
334 }
335
336 void DebugAdapterClient::HookPopupMenu(wxMenu* menu, MenuType type)
337 {
338 wxUnusedVar(type);
339 wxUnusedVar(menu);
340 }
341
342 void DebugAdapterClient::ClearDebuggerMarker()
343 {
344 IEditor::List_t editors;
345 clGetManager()->GetAllEditors(editors);
346
347 for(auto editor : editors) {
348 DAPTextView::ClearMarker(editor->GetCtrl());
349 }
350 }
351
352 void DebugAdapterClient::RefreshBreakpointsView()
353 {
354 if(m_breakpointsView) {
355 m_breakpointsView->RefreshView(m_sessionBreakpoints);
356 }
357
358 // clear all breakpoint markers
359 IEditor::List_t editors;
360 clGetManager()->GetAllEditors(editors);
361 for(auto editor : editors) {
362 editor->DeleteBreakpointMarkers();
363 }
364
365 // update the open editors with breakpoint markers
366 for(const auto& bp : m_sessionBreakpoints.get_breakpoints()) {
367 wxString path = NormaliseReceivedPath(bp.source.path);
368 auto editor = clGetManager()->FindEditor(path);
369 if(!editor) {
370 continue;
371 }
372 editor->SetBreakpointMarker(bp.line - 1);
373 }
374 }
375
376 void DebugAdapterClient::OnDebugContinue(clDebugEvent& event)
377 {
378 CHECK_IS_DAP_CONNECTED();
379 // call continue
380 m_client.Continue();
381 LOG_DEBUG(LOG) << "Sending 'continue' command" << endl;
382 }
383
384 void DebugAdapterClient::OnDebugStart(clDebugEvent& event)
385 {
386 if(m_client.IsConnected()) {
387 // already running - assume "continue"
388 OnDebugContinue(event);
389 return;
390 }
391
392 LOG_DEBUG(LOG) << "debug-start event is called for debugger:" << event.GetDebuggerName() << endl;
393
394 if(!IsDebuggerOwnedByPlugin(event.GetDebuggerName())) {
395 event.Skip();
396 LOG_DEBUG(LOG) << "Not a dap debugger (" << event.GetDebuggerName() << ")" << endl;
397 return;
398 }
399
400 // fetch the requested debugger details
401 DapEntry dap_server;
402 m_dap_store.Get(event.GetDebuggerName(), &dap_server);
403
404 LOG_DEBUG(LOG) << "working directory is:" << ::wxGetCwd() << endl;
405
406 // the following 4 variables are used for launching the debugger
407 wxString working_directory;
408 wxString exepath;
409 wxString args;
410 clEnvList_t env;
411 wxString ssh_account;
412
413 if(clCxxWorkspaceST::Get()->IsOpen()) {
414 //
415 // standard C++ workspace
416 //
417 ProjectPtr project = clCxxWorkspaceST::Get()->GetActiveProject();
418 if(!project) {
419 ::wxMessageBox(wxString() << _("Could not locate project: ")
420 << clCxxWorkspaceST::Get()->GetActiveProjectName(),
421 DAP_MESSAGE_BOX_TITLE, wxICON_ERROR | wxOK | wxCENTER);
422 LOG_ERROR(LOG) << "unable to locate project:" << clCxxWorkspaceST::Get()->GetActiveProjectName() << endl;
423 return;
424 }
425
426 BuildConfigPtr bldConf = project->GetBuildConfiguration();
427 if(!bldConf) {
428 ::wxMessageBox(wxString() << _("Could not locate the requested build configuration"), DAP_MESSAGE_BOX_TITLE,
429 wxICON_ERROR | wxOK | wxCENTER);
430 return;
431 }
432
433 // Determine the executable to debug, working directory and arguments
434 LOG_DEBUG(LOG) << "Preparing environment variables.." << endl;
435 env = bldConf->GetEnvironment(project.Get());
436 LOG_DEBUG(LOG) << "Success" << endl;
437 exepath = bldConf->GetCommand();
438
439 // Get the debugging arguments.
440 if(bldConf->GetUseSeparateDebugArgs()) {
441 args = bldConf->GetDebugArgs();
442 } else {
443 args = bldConf->GetCommandArguments();
444 }
445
446 working_directory = MacroManager::Instance()->Expand(bldConf->GetWorkingDirectory(), m_mgr, project->GetName());
447 exepath = MacroManager::Instance()->Expand(exepath, m_mgr, project->GetName());
448
449 if(working_directory.empty()) {
450 working_directory = wxGetCwd();
451 }
452 wxFileName fn(exepath);
453 if(fn.IsRelative()) {
454 fn.MakeAbsolute(working_directory);
455 }
456 exepath = fn.GetFullPath();
457 } else if(clFileSystemWorkspace::Get().IsOpen()) {
458 //
459 // Handle file system workspace
460 //
461 auto conf = clFileSystemWorkspace::Get().GetSettings().GetSelectedConfig();
462 if(!conf) {
463 LOG_ERROR(LOG) << "No active configuration found!" << endl;
464 return;
465 }
466
467 auto workspace = clWorkspaceManager::Get().GetWorkspace();
468 bool is_remote = workspace->IsRemote();
469 ssh_account = workspace->GetSshAccount();
470
471 clFileSystemWorkspace::Get().GetExecutable(exepath, args, working_directory);
472 if(is_remote) {
473 env = StringUtils::BuildEnvFromString(conf->GetEnvironment());
474 } else {
475 env = StringUtils::ResolveEnvList(conf->GetEnvironment());
476 wxFileName fnExepath(exepath);
477 if(fnExepath.IsRelative()) {
478 fnExepath.MakeAbsolute(workspace->GetDir());
479 }
480 exepath = fnExepath.GetFullPath();
481 }
482 }
483
484 // start the debugger
485 if(!InitialiseSession(dap_server, exepath, args, working_directory, ssh_account, env)) {
486 return;
487 }
488 StartAndConnectToDapServer();
489 }
490
491 void DebugAdapterClient::OnDebugNext(clDebugEvent& event)
492 {
493 CHECK_IS_DAP_CONNECTED();
494 LOG_DEBUG(LOG) << "-> Next" << endl;
495 m_client.Next();
496 }
497
498 void DebugAdapterClient::OnDebugStop(clDebugEvent& event)
499 {
500 CHECK_IS_DAP_CONNECTED();
501 LOG_DEBUG(LOG) << "-> Stop" << endl;
502 DoCleanup();
503 }
504
505 void DebugAdapterClient::OnDebugIsRunning(clDebugEvent& event)
506 {
507 CHECK_IS_DAP_CONNECTED();
508 event.SetAnswer(m_client.IsConnected());
509 }
510
511 void DebugAdapterClient::OnDebugCanInteract(clDebugEvent& event)
512 {
513 CHECK_IS_DAP_CONNECTED();
514 event.SetAnswer(m_client.IsConnected() && m_client.CanInteract());
515 }
516
517 void DebugAdapterClient::OnDebugStepIn(clDebugEvent& event)
518 {
519 CHECK_IS_DAP_CONNECTED();
520 m_client.StepIn();
521 LOG_DEBUG(LOG) << "-> StopIn" << endl;
522 }
523
524 void DebugAdapterClient::OnDebugStepOut(clDebugEvent& event)
525 {
526 CHECK_IS_DAP_CONNECTED();
527 m_client.StepOut();
528 LOG_DEBUG(LOG) << "-> StopOut" << endl;
529 }
530
531 void DebugAdapterClient::RestoreUI()
532 {
533 // Save current perspective before destroying the session
534 if(m_isPerspectiveLoaded) {
535 m_mgr->SavePerspective("DAP");
536
537 // Restore the old perspective
538 m_mgr->LoadPerspective("Default");
539 m_isPerspectiveLoaded = false;
540 }
541
542 DestroyUI();
543 }
544
545 void DebugAdapterClient::LoadPerspective()
546 {
547 // Save the current persepctive we start debguging
548 m_mgr->SavePerspective("Default");
549
550 // Hide all the panes
551 const auto& panes = m_mgr->GetDockingManager()->GetAllPanes();
552 for(size_t i = 0; i < panes.size(); ++i) {
553 if(panes[i].dock_direction != wxAUI_DOCK_CENTER) {
554 panes[i].Hide();
555 }
556 }
557
558 m_mgr->LoadPerspective("DAP");
559 m_isPerspectiveLoaded = true;
560
561 // Make sure that all the panes are visible
562 ShowPane(DAP_MAIN_VIEW, true);
563 ShowPane(DAP_BREAKPOINTS_VIEW, true);
564 ShowPane(DAP_OUTPUT_VIEW, true);
565 ShowPane(DAP_WATCHES_VIEW, true);
566
567 // Hide the output pane
568 wxAuiPaneInfo& pi = m_mgr->GetDockingManager()->GetPane("Output View");
569 if(pi.IsOk() && pi.IsShown()) {
570 pi.Hide();
571 }
572 m_mgr->GetDockingManager()->Update();
573 }
574
575 void DebugAdapterClient::ShowPane(const wxString& paneName, bool show)
576 {
577 wxAuiPaneInfo& pi = m_mgr->GetDockingManager()->GetPane(paneName);
578 if(pi.IsOk()) {
579 if(show) {
580 if(!pi.IsShown()) {
581 pi.Show();
582 }
583 } else {
584 if(pi.IsShown()) {
585 pi.Hide();
586 }
587 }
588 }
589 }
590
591 void DebugAdapterClient::DestroyUI()
592 {
593 // Destroy the callstack window
594 if(m_threadsView) {
595 wxAuiPaneInfo& pi = m_mgr->GetDockingManager()->GetPane(DAP_MAIN_VIEW);
596 if(pi.IsOk()) {
597 m_mgr->GetDockingManager()->DetachPane(m_threadsView);
598 }
599 m_threadsView->Destroy();
600 m_threadsView = nullptr;
601 }
602
603 if(m_watchesView) {
604 wxAuiPaneInfo& pi = m_mgr->GetDockingManager()->GetPane(DAP_WATCHES_VIEW);
605 if(pi.IsOk()) {
606 m_mgr->GetDockingManager()->DetachPane(m_watchesView);
607 }
608 m_watchesView->Destroy();
609 m_watchesView = nullptr;
610 }
611
612 if(m_breakpointsView) {
613 wxAuiPaneInfo& pi = m_mgr->GetDockingManager()->GetPane(DAP_BREAKPOINTS_VIEW);
614 if(pi.IsOk()) {
615 m_mgr->GetDockingManager()->DetachPane(m_breakpointsView);
616 }
617 m_breakpointsView->Destroy();
618 m_breakpointsView = nullptr;
619 }
620
621 if(m_outputView) {
622 wxAuiPaneInfo& pi = m_mgr->GetDockingManager()->GetPane(DAP_OUTPUT_VIEW);
623 if(pi.IsOk()) {
624 m_mgr->GetDockingManager()->DetachPane(m_outputView);
625 }
626 m_outputView->Destroy();
627 m_outputView = nullptr;
628 }
629
630 if(m_textView) {
631 int index = clGetManager()->GetMainNotebook()->FindPage(m_textView);
632 if(index != wxNOT_FOUND) {
633 clGetManager()->GetMainNotebook()->RemovePage(index, true);
634 }
635 m_textView->Destroy();
636 m_textView = nullptr;
637 }
638
639 DestroyTooltip();
640 ClearDebuggerMarker();
641 m_mgr->GetDockingManager()->Update();
642 }
643
644 void DebugAdapterClient::InitializeUI()
645 {
646 wxWindow* parent = m_mgr->GetDockingManager()->GetManagedWindow();
647 if(!m_threadsView) {
648 m_threadsView = new DAPMainView(parent, this, LOG);
649 m_mgr->GetDockingManager()->AddPane(m_threadsView, wxAuiPaneInfo()
650 .MinSize(300, 300)
651 .Layer(10)
652 .Bottom()
653 .Position(1)
654 .CloseButton(false)
655 .Caption(DAP_MAIN_VIEW)
656 .Name(DAP_MAIN_VIEW));
657 }
658
659 if(!m_watchesView) {
660 m_watchesView = new DAPWatchesView(parent, this, LOG);
661 m_mgr->GetDockingManager()->AddPane(m_watchesView, wxAuiPaneInfo()
662 .MinSize(300, 300)
663 .Layer(10)
664 .Left()
665 .Position(1)
666 .CloseButton(false)
667 .Caption(DAP_WATCHES_VIEW)
668 .Name(DAP_WATCHES_VIEW));
669 }
670
671 if(!m_breakpointsView) {
672 m_breakpointsView = new DAPBreakpointsView(parent, this, LOG);
673 m_mgr->GetDockingManager()->AddPane(m_breakpointsView, wxAuiPaneInfo()
674 .MinSize(300, 300)
675 .Layer(5)
676 .Right()
677 .Position(2)
678 .CloseButton(false)
679 .Caption(DAP_BREAKPOINTS_VIEW)
680 .Name(DAP_BREAKPOINTS_VIEW));
681 }
682 if(!m_outputView) {
683 m_outputView = new DAPOutputPane(parent, LOG);
684 m_mgr->GetDockingManager()->AddPane(m_outputView, wxAuiPaneInfo()
685 .MinSize(300, 300)
686 .Layer(5)
687 .Left()
688 .Position(2)
689 .CloseButton(false)
690 .Caption(DAP_OUTPUT_VIEW)
691 .Name(DAP_OUTPUT_VIEW));
692 }
693
694 if(!m_textView) {
695 m_textView = new DAPTextView(clGetManager()->GetMainNotebook());
696 clGetManager()->GetMainNotebook()->AddPage(m_textView, _("Debug Adapter Client"), true);
697 }
698 }
699
700 void DebugAdapterClient::DoCleanup()
701 {
702 m_client.Reset();
703 ClearDebuggerMarker();
704 m_raisOnBpHit = false;
705 StopProcess();
706 m_session.Clear();
707 m_terminal_helper.Terminate();
708 m_sessionBreakpoints.clear();
709 wxDELETE(m_breakpointsHelper);
710
711 // clear all breakpoint markers
712 IEditor::List_t editors;
713 clGetManager()->GetAllEditors(editors);
714 for(auto editor : editors) {
715 editor->DeleteBreakpointMarkers();
716 }
717
718 clDebuggerBreakpoint::Vec_t all_bps;
719 clGetManager()->GetAllBreakpoints(all_bps);
720
721 for(const auto& bp : all_bps) {
722 if(bp.file.empty()) {
723 continue;
724 }
725
726 auto editor = clGetManager()->FindEditor(bp.file);
727 if(!editor) {
728 continue;
729 }
730 editor->SetBreakpointMarker(bp.lineno - 1);
731 }
732 }
733
734 void DebugAdapterClient::OnWorkspaceClosed(clWorkspaceEvent& event)
735 {
736 event.Skip();
737 DoCleanup();
738 }
739
740 void DebugAdapterClient::OnWorkspaceLoaded(clWorkspaceEvent& event) { event.Skip(); }
741
742 void DebugAdapterClient::OnToggleInterrupt(clDebugEvent& event)
743 {
744 CHECK_IS_DAP_CONNECTED();
745 event.Skip();
746 m_client.Pause();
747 }
748
749 void DebugAdapterClient::OnBuildStarting(clBuildEvent& event)
750 {
751 if(m_client.IsConnected()) {
752 // lldb session is active, prompt the user
753 if(::wxMessageBox(_("A debug session is running\nCancel debug session and continue building?"),
754 DAP_MESSAGE_BOX_TITLE, wxICON_QUESTION | wxYES_NO | wxNO_DEFAULT | wxCENTER) == wxYES) {
755 clDebugEvent dummy;
756 OnDebugStop(dummy);
757 event.Skip();
758 } else {
759 // do nothing - this will cancel the build
760 }
761
762 } else {
763 event.Skip();
764 }
765 }
766
767 void DebugAdapterClient::OnAddWatch(wxCommandEvent& event)
768 {
769 CHECK_IS_DAP_CONNECTED();
770 // FIXME
771 }
772
773 void DebugAdapterClient::OnSettings(wxCommandEvent& event)
774 {
775 event.Skip();
776 clDapSettingsStore store = m_dap_store;
777 DapDebuggerSettingsDlg dlg(EventNotifier::Get()->TopFrame(), store);
778 if(dlg.ShowModal() != wxID_OK) {
779 return;
780 }
781 m_dap_store = store;
782 m_dap_store.Save(get_dap_settings_file());
783
784 // refresh the list of debuggers we are registering by this plugin
785 RegisterDebuggers();
786 }
787
788 void DebugAdapterClient::OnInitDone(wxCommandEvent& event)
789 {
790 event.Skip();
791 if(!m_dap_store.empty()) {
792 return;
793 }
794 // this seems like a good time to scan for available debuggers
795 DapLocator locator;
796 std::vector<DapEntry> entries;
797 if(locator.Locate(&entries) > 0) {
798 m_dap_store.Set(entries);
799 m_dap_store.Save(get_dap_settings_file());
800 LOG_SYSTEM(LOG) << "Found and configured" << entries.size() << "dap servers" << endl;
801 RegisterDebuggers();
802 }
803 }
804
805 void DebugAdapterClient::OnDebugTooltip(clDebugEvent& event)
806 {
807 CHECK_IS_DAP_CONNECTED();
808 DestroyTooltip();
809
810 wxString word = event.GetString();
811 int frame_id = m_threadsView->GetCurrentFrameId();
812
813 m_client.EvaluateExpression(
814 word, frame_id, dap::EvaluateContext::HOVER,
815 [this, word](bool success, const wxString& result, const wxString& type, int variablesReference) {
816 if(!success) {
817 clGetManager()->SetStatusMessage(_("Failed to evaluate expression: ") + word);
818 return;
819 }
820
821 auto editor = clGetManager()->GetActiveEditor();
822 CHECK_PTR_RET(editor);
823 m_tooltip = new DAPTooltip(&m_client, word, result, type, variablesReference);
824 m_tooltip->Move(::wxGetMousePosition());
825 m_tooltip->Show();
826 });
827 }
828
829 void DebugAdapterClient::OnDestroyTip(clCommandEvent& event)
830 {
831 event.Skip();
832 DestroyTooltip();
833 }
834
835 void DebugAdapterClient::OnDebugQuickDebug(clDebugEvent& event)
836 {
837 if(!IsDebuggerOwnedByPlugin(event.GetDebuggerName())) {
838 event.Skip();
839 return;
840 }
841
842 // ours to handle
843 event.Skip(false);
844 wxString exe_to_debug = event.GetExecutableName();
845 const wxString& working_dir = event.GetWorkingDirectory();
846 const wxString& args = event.GetArguments();
847
848 wxFileName fnExepath(exe_to_debug);
849 if(fnExepath.IsRelative()) {
850 wxString cwd;
851 if(clFileSystemWorkspace::Get().IsOpen()) {
852 cwd = clFileSystemWorkspace::Get().GetDir();
853 }
854 fnExepath.MakeAbsolute(cwd);
855 }
856
857 #ifdef __WXMSW__
858 fnExepath.SetExt("exe");
859 #endif
860
861 exe_to_debug = fnExepath.GetFullPath();
862
863 // fetch the requested debugger details
864 DapEntry dap_server;
865 m_dap_store.Get(event.GetDebuggerName(), &dap_server);
866
867 auto env = PrepareEnvForFileSystemWorkspace(dap_server, !event.IsSSHDebugging());
868 if(!InitialiseSession(dap_server, exe_to_debug, args, working_dir, event.GetSshAccount(), env)) {
869 return;
870 }
871 StartAndConnectToDapServer();
872 }
873
874 void DebugAdapterClient::OnDebugCoreFile(clDebugEvent& event)
875 {
876 // FIXME
877 event.Skip();
878 }
879
880 void DebugAdapterClient::OnDebugAttachToProcess(clDebugEvent& event)
881 {
882 // FIXME
883 event.Skip();
884 }
885
886 void DebugAdapterClient::OnDebugDeleteAllBreakpoints(clDebugEvent& event)
887 {
888 event.Skip();
889 // FIXME
890 }
891
892 void DebugAdapterClient::OnDebugDisableAllBreakpoints(clDebugEvent& event) { event.Skip(); }
893
894 void DebugAdapterClient::OnDebugEnableAllBreakpoints(clDebugEvent& event) { event.Skip(); }
895
896 void DebugAdapterClient::OnDebugVOID(clDebugEvent& event) { CHECK_IS_DAP_CONNECTED(); }
897
898 void DebugAdapterClient::OnDebugNextInst(clDebugEvent& event)
899 {
900 CHECK_IS_DAP_CONNECTED();
901 m_client.Next(wxNOT_FOUND, true, dap::SteppingGranularity::INSTRUCTION);
902 }
903
904 void DebugAdapterClient::OnDebugShowCursor(clDebugEvent& event)
905 {
906 CHECK_IS_DAP_CONNECTED();
907 // FIXME
908 }
909
910 /// --------------------------------------------------------------------------
911 /// dap events starting here
912 /// --------------------------------------------------------------------------
913
914 void DebugAdapterClient::OnDapExited(DAPEvent& event)
915 {
916 event.Skip();
917 LOG_DEBUG(LOG) << "dap-server exited" << endl;
918 DoCleanup();
919 }
920
921 void DebugAdapterClient::OnDapLog(DAPEvent& event)
922 {
923 event.Skip();
924 LOG_DEBUG(LOG) << event.GetString() << endl;
925 }
926
927 void DebugAdapterClient::OnDapOutputEvent(DAPEvent& event)
928 {
929 LOG_DEBUG(LOG) << "Received output event" << endl;
930 if(m_outputView) {
931 m_outputView->AddEvent(event.GetDapEvent()->As<dap::OutputEvent>());
932 }
933 }
934
935 void DebugAdapterClient::OnDapModuleEvent(DAPEvent& event)
936 {
937 LOG_DEBUG(LOG) << "Received module event" << endl;
938 CHECK_IS_DAP_CONNECTED();
939 if(m_outputView) {
940 m_outputView->AddEvent(event.GetDapEvent()->As<dap::ModuleEvent>());
941 }
942 }
943
944 void DebugAdapterClient::OnDapLaunchResponse(DAPEvent& event)
945 {
946 // Check that the debugee was started successfully
947 dap::LaunchResponse* resp = event.GetDapResponse()->As<dap::LaunchResponse>();
948
949 if(resp && !resp->success) {
950 // launch failed!
951 wxMessageBox("Failed to launch debuggee: " + resp->message, DAP_MESSAGE_BOX_TITLE,
952 wxICON_ERROR | wxOK | wxOK_DEFAULT | wxCENTRE);
953 CallAfter(&DebugAdapterClient::DoCleanup);
954 }
955 }
956
957 void DebugAdapterClient::OnDapInitializeResponse(DAPEvent& event)
958 {
959 LOG_DEBUG(LOG) << "got initialize response" << endl;
960 LOG_DEBUG(LOG) << "Starting debugger for command:" << endl;
961 LOG_DEBUG(LOG) << m_session.command << endl;
962 LOG_DEBUG(LOG) << "working directory:" << m_session.working_directory << endl;
963
964 // FIXME: apply the environment here
965 auto v = m_session.command;
966 LOG_DEBUG(LOG) << "Calling Launch() with command:" << v << endl;
967 if(m_session.dap_server.GetLaunchType() == DapLaunchType::LAUNCH) {
968 m_client.Launch(std::move(v), m_session.working_directory, m_session.MakeEnvironment());
969
970 } else {
971 auto v = m_session.command;
972 v.erase(v.begin()); // remove the exe and pass just the arguments
973 m_client.Attach(m_session.m_pid, v);
974 }
975 }
976
977 /// DAP server responded to our `initialize` request
978 void DebugAdapterClient::OnDapInitializedEvent(DAPEvent& event)
979 {
980 // place a single breakpoint on main
981 dap::FunctionBreakpoint main_bp{ "main" };
982 m_session.need_to_set_breakpoints = true;
983 m_client.SetFunctionBreakpoints({ main_bp });
984
985 if(m_breakpointsHelper) {
986 m_breakpointsHelper->ApplyBreakpoints(wxEmptyString);
987 }
988 // place all breakpoints
989 m_client.ConfigurationDone();
990 }
991
992 void DebugAdapterClient::OnDapStoppedEvent(DAPEvent& event)
993 {
994 // raise CodeLite
995 EventNotifier::Get()->TopFrame()->Raise();
996
997 // got stopped event
998 if(m_session.need_to_set_breakpoints) {
999 if(m_breakpointsHelper) {
1000 m_breakpointsHelper->ApplyBreakpoints(wxEmptyString);
1001 }
1002 m_session.need_to_set_breakpoints = false;
1003 }
1004
1005 LOG_DEBUG(LOG) << " *** DAP Stopped Event *** " << endl;
1006 dap::StoppedEvent* stopped_data = event.GetDapEvent()->As<dap::StoppedEvent>();
1007 if(stopped_data) {
1008 m_client.GetThreads();
1009 }
1010
1011 // update watches if needed
1012 UpdateWatches();
1013 }
1014
1015 void DebugAdapterClient::OnDapThreadsResponse(DAPEvent& event)
1016 {
1017 CHECK_PTR_RET(m_threadsView);
1018
1019 auto response = event.GetDapResponse()->As<dap::ThreadsResponse>();
1020 CHECK_PTR_RET(response);
1021
1022 m_threadsView->UpdateThreads(m_client.GetActiveThreadId(), response);
1023
1024 // get the frames for the active thread
1025 m_client.GetFrames();
1026 }
1027
1028 void DebugAdapterClient::OnDapStackTraceResponse(DAPEvent& event)
1029 {
1030 CHECK_PTR_RET(m_threadsView);
1031
1032 auto response = event.GetDapResponse()->As<dap::StackTraceResponse>();
1033 CHECK_PTR_RET(response);
1034
1035 m_threadsView->UpdateFrames(response->refId, response);
1036 if(!response->stackFrames.empty()) {
1037 auto frame = response->stackFrames[0];
1038 LoadFile(frame.source, frame.line - 1);
1039
1040 // ask the scopes for the first frame
1041 m_client.GetScopes(frame.id);
1042 }
1043 }
1044
1045 void DebugAdapterClient::OnDapScopesResponse(DAPEvent& event)
1046 {
1047 auto response = event.GetDapResponse()->As<dap::ScopesResponse>();
1048 CHECK_PTR_RET(response);
1049 CHECK_PTR_RET(m_threadsView);
1050
1051 if(!response->success) {
1052 LOG_DEBUG(LOG) << "failed to retrieve scopes." << response->message << endl;
1053 return;
1054 }
1055 m_threadsView->UpdateScopes(response->refId, response);
1056 }
1057
1058 void DebugAdapterClient::OnDapVariablesResponse(DAPEvent& event)
1059 {
1060 auto response = event.GetDapResponse()->As<dap::VariablesResponse>();
1061 CHECK_PTR_RET(response);
1062 CHECK_PTR_RET(m_threadsView);
1063 switch(response->context) {
1064 case dap::EvaluateContext::HOVER:
1065 if(m_tooltip) {
1066 m_tooltip->UpdateChildren(response->refId, response);
1067 }
1068 break;
1069 case dap::EvaluateContext::WATCH:
1070 // update the watches view
1071 if(m_watchesView) {
1072 m_watchesView->UpdateChildren(response->refId, response);
1073 }
1074 break;
1075 default:
1076 // assume its the variables view
1077 m_threadsView->UpdateVariables(response->refId, response);
1078 break;
1079 }
1080 }
1081
1082 void DebugAdapterClient::OnDapSetFunctionBreakpointResponse(DAPEvent& event)
1083 {
1084 auto resp = event.GetDapResponse()->As<dap::SetFunctionBreakpointsResponse>();
1085 CHECK_PTR_RET(resp);
1086
1087 // delete all breakpoints associated with the reported file
1088 m_sessionBreakpoints.delete_by_paths(resp->breakpoints);
1089
1090 for(const auto& bp : resp->breakpoints) {
1091 m_sessionBreakpoints.update_or_insert(bp);
1092 }
1093 RefreshBreakpointsView();
1094 }
1095
1096 void DebugAdapterClient::OnDapSetSourceBreakpointResponse(DAPEvent& event)
1097 {
1098 auto resp = event.GetDapResponse()->As<dap::SetBreakpointsResponse>();
1099 CHECK_PTR_RET(resp);
1100
1101 // delete all breakpoints associated with the reported file
1102 LOG_DEBUG(LOG) << "Deleting session breakpoints for file:" << resp->originSource << endl;
1103 m_sessionBreakpoints.delete_by_path(resp->originSource);
1104
1105 for(const auto& bp : resp->breakpoints) {
1106 m_sessionBreakpoints.update_or_insert(bp);
1107 }
1108 RefreshBreakpointsView();
1109 }
1110
1111 void DebugAdapterClient::OnDapBreakpointEvent(DAPEvent& event)
1112 {
1113 auto event_data = event.GetDapEvent()->As<dap::BreakpointEvent>();
1114 CHECK_PTR_RET(event_data);
1115 CHECK_PTR_RET(m_breakpointsView);
1116 // check the event reason
1117 const auto& bp = event_data->breakpoint;
1118 m_sessionBreakpoints.delete_by_id(bp.id);
1119 if(event_data->reason != "removed") {
1120 m_sessionBreakpoints.update_or_insert(bp);
1121 }
1122 RefreshBreakpointsView();
1123 }
1124
1125 void DebugAdapterClient::OnDapRunInTerminal(DAPEvent& event)
1126 {
1127 auto request = event.GetDapRequest()->As<dap::RunInTerminalRequest>();
1128 CHECK_PTR_RET(request);
1129
1130 int process_id = m_terminal_helper.RunProcess(request->arguments.args, wxEmptyString, {});
1131 // send the response back to the dap server
1132 auto response = m_client.MakeRequest<dap::RunInTerminalResponse>();
1133 LOG_DEBUG(LOG) << "RunInTerminal process ID:" << process_id << endl;
1134 response.request_seq = request->seq;
1135 if(process_id == wxNOT_FOUND) {
1136 response.success = false;
1137 response.processId = 0;
1138 } else {
1139 response.success = true;
1140 response.processId = process_id;
1141 }
1142 m_client.SendResponse(response);
1143 }
1144
1145 /// --------------------------------------------------------------------------
1146 /// dap events stops here
1147 /// --------------------------------------------------------------------------
1148
1149 void DebugAdapterClient::UpdateWatches()
1150 {
1151 if(!m_client.IsConnected()) {
1152 return;
1153 }
1154
1155 CHECK_PTR_RET(m_watchesView);
1156 m_watchesView->Update(m_threadsView->GetCurrentFrameId());
1157 }
1158
1159 void DebugAdapterClient::RefreshBreakpointsMarkersForEditor(IEditor* editor) { CHECK_PTR_RET(editor); }
1160
1161 bool DebugAdapterClient::LaunchDAPServer()
1162 {
1163 wxDELETE(m_dap_server);
1164 const DapEntry& dap_server = m_session.dap_server;
1165 wxString command = ReplacePlaceholders(dap_server.GetCommand());
1166
1167 LOG_DEBUG(LOG) << "starting dap with command:" << command << endl;
1168 if(m_session.debug_over_ssh) {
1169 // launch ssh process
1170 auto env_list = StringUtils::BuildEnvFromString(dap_server.GetEnvironment());
1171 m_dap_server =
1172 ::CreateAsyncProcess(this, command, IProcessCreateDefault | IProcessCreateSSH | IProcessWrapInShell,
1173 wxEmptyString, &env_list, m_session.ssh_acount.GetAccountName());
1174 } else {
1175 // launch local process
1176 auto env_list = StringUtils::ResolveEnvList(dap_server.GetEnvironment());
1177 m_dap_server = ::CreateAsyncProcess(this, command,
1178 IProcessNoRedirect | IProcessWrapInShell | IProcessCreateWithHiddenConsole,
1179 wxEmptyString, &env_list);
1180 }
1181 m_dap_server->SetHardKill(true);
1182 return m_dap_server;
1183 }
1184
1185 bool DebugAdapterClient::InitialiseSession(const DapEntry& dap_server, const wxString& exepath, const wxString& args,
1186 const wxString& working_directory, const wxString& ssh_account,
1187 const clEnvList_t& env)
1188 {
1189 m_session.Clear();
1190 m_session.dap_server = dap_server;
1191 wxArrayString command_array = StringUtils::BuildArgv(args);
1192 command_array.Insert(exepath, 0);
1193 m_session.command = { command_array.begin(), command_array.end() };
1194 m_session.debug_over_ssh = !ssh_account.empty();
1195
1196 if(!m_session.debug_over_ssh) {
1197 // only add the working directory if it exists
1198 if(wxFileName::DirExists(working_directory)) {
1199 m_session.working_directory = working_directory;
1200 }
1201 } else {
1202 m_session.working_directory = working_directory;
1203 }
1204 m_session.environment = env;
1205
1206 #if USE_SFTP
1207 if(m_session.debug_over_ssh) {
1208 m_session.ssh_acount = SSHAccountInfo::LoadAccount(ssh_account);
1209 if(m_session.ssh_acount.GetAccountName().empty()) {
1210 LOG_ERROR(LOG) << "failed to load ssh account:" << ssh_account << endl;
1211 m_session.Clear();
1212 return false;
1213 }
1214 }
1215 #endif
1216
1217 return true;
1218 }
1219
1220 void DebugAdapterClient::StartAndConnectToDapServer()
1221 {
1222 m_client.Reset();
1223 LOG_DEBUG(LOG) << "Connecting to dap-server:" << m_session.dap_server.GetName() << endl;
1224 LOG_DEBUG(LOG) << "exepath:" << m_session.command << endl;
1225 LOG_DEBUG(LOG) << "working_directory:" << m_session.working_directory << endl;
1226 LOG_DEBUG(LOG) << "env:" << to_string_array(m_session.environment) << endl;
1227
1228 // start the dap server (for the current session)
1229 if(!LaunchDAPServer()) {
1230 return;
1231 }
1232
1233 wxBusyCursor cursor;
1234 // For this demo, we use socket transport. But you may choose
1235 // to write your own transport that implements the dap::Transport interface
1236 // This is useful when the user wishes to use stdin/out for communicating with
1237 // the dap and not over socket
1238 dap::SocketTransport* transport = new dap::SocketTransport();
1239 if(!transport->Connect(m_session.dap_server.GetConnectionString(), 10)) {
1240 wxMessageBox("Failed to connect to DAP server", DAP_MESSAGE_BOX_TITLE, wxICON_ERROR | wxOK | wxCENTRE);
1241 wxDELETE(transport);
1242 m_client.Reset();
1243 return;
1244 }
1245 wxDELETE(m_breakpointsHelper);
1246 m_breakpointsHelper = new BreakpointsHelper(m_client, m_session, LOG);
1247
1248 // Notify about debug start event
1249 // + load the UI
1250 InitializeUI();
1251 LoadPerspective();
1252
1253 // Fire CodeLite IDE event indicating that a debug session started
1254 clDebugEvent cl_event{ wxEVT_DEBUG_STARTED };
1255 cl_event.SetDebuggerName(m_session.dap_server.GetName());
1256 EventNotifier::Get()->AddPendingEvent(cl_event);
1257
1258 // construct new client with the transport
1259 m_client.SetTransport(transport);
1260 m_client.Initialize(); // send protocol Initialize request
1261 }
1262
1263 void DebugAdapterClient::OnFileLoaded(clCommandEvent& event) { event.Skip(); }
1264
1265 bool DebugAdapterClient::IsDebuggerOwnedByPlugin(const wxString& name) const
1266 {
1267 return m_dap_store.GetEntries().count(name) != 0;
1268 }
1269
1270 void DebugAdapterClient::OnProcessOutput(clProcessEvent& event)
1271 {
1272 wxUnusedVar(event);
1273 LOG_DEBUG(LOG) << "server output:" << event.GetOutput() << endl;
1274 }
1275
1276 void DebugAdapterClient::OnProcessTerminated(clProcessEvent& event)
1277 {
1278 wxUnusedVar(event);
1279 wxDELETE(m_dap_server);
1280
1281 m_client.Reset();
1282
1283 RestoreUI();
1284 LOG_DEBUG(LOG) << "dap-server terminated" << endl;
1285
1286 clDebugEvent e(wxEVT_DEBUG_ENDED);
1287 EventNotifier::Get()->AddPendingEvent(e);
1288 }
1289
1290 void DebugAdapterClient::StopProcess()
1291 {
1292 if(m_dap_server) {
1293 // wxEVT_DEBUG_ENDED is sent in OnProcessTerminated() handler
1294 LOG_DEBUG(LOG) << "Terminating dap-server..." << endl;
1295 m_dap_server->Terminate();
1296
1297 } else {
1298 clDebugEvent e(wxEVT_DEBUG_ENDED);
1299 EventNotifier::Get()->AddPendingEvent(e);
1300 }
1301 }
1302
1303 wxString DebugAdapterClient::NormaliseReceivedPath(const wxString& path) const
1304 {
1305 wxFileName fn(path);
1306 if(m_session.debug_over_ssh) {
1307 if(fn.IsRelative()) {
1308 fn.MakeAbsolute(m_session.working_directory, wxPATH_UNIX);
1309 }
1310 return fn.GetFullPath(wxPATH_UNIX);
1311 } else {
1312 if(fn.IsRelative()) {
1313 fn.MakeAbsolute(m_session.working_directory);
1314 }
1315 #ifdef __WXMSW__
1316 if(!fn.HasVolume()) {
1317 // try to fix path volume issue (lldb-vscode)
1318 fn.SetVolume("C");
1319 }
1320 #endif
1321 wxString fullpath = fn.GetFullPath();
1322 return fullpath;
1323 }
1324 }
1325
1326 void DebugAdapterClient::LoadFile(const dap::Source& sourceId, int line_number)
1327 {
1328 if(sourceId.sourceReference <= 0) {
1329 // use local file system
1330 // not a server file, load it locally
1331 wxFileName fp(sourceId.path);
1332
1333 // the is already loaded
1334 wxString file_to_load = fp.GetFullPath();
1335 LOG_DEBUG(LOG) << "Loading file.." << file_to_load << endl;
1336 file_to_load = NormaliseReceivedPath(file_to_load);
1337 LOG_DEBUG(LOG) << "Normalised form:" << file_to_load << endl;
1338
1339 if(m_session.debug_over_ssh) {
1340 clGetManager()->SetStatusMessage(_("ERROR: (dap) loading remote file over SSH is not supported yet"));
1341 return;
1342 } else {
1343 wxFileName fn(file_to_load);
1344 if(!fn.FileExists()) {
1345 clGetManager()->SetStatusMessage(_("ERROR: (dap) file:") + file_to_load + _(" does not exist"));
1346 return;
1347 }
1348
1349 auto callback = [line_number](IEditor* editor) {
1350 DAPTextView::ClearMarker(editor->GetCtrl());
1351 DAPTextView::SetMarker(editor->GetCtrl(), line_number);
1352 };
1353 clGetManager()->OpenFileAndAsyncExecute(fn.GetFullPath(), callback);
1354 if(m_textView) {
1355 m_textView->ClearMarker();
1356 }
1357 }
1358
1359 } else {
1360 // reference file, load it into the editor
1361
1362 // easy path
1363 CHECK_PTR_RET(m_textView);
1364 if(m_textView->IsSame(sourceId)) {
1365 clGetManager()->SelectPage(m_textView);
1366 m_textView->SetMarker(line_number);
1367 return;
1368 }
1369
1370 m_client.LoadSource(sourceId, [this, sourceId, line_number](bool success, const wxString& content,
1371 const wxString& mimeType) {
1372 if(!success) {
1373 return;
1374 }
1375 LOG_DEBUG(LOG) << "mimeType:" << mimeType << endl;
1376 clGetManager()->SelectPage(m_textView);
1377 m_textView->SetText(sourceId, content,
1378 wxString() << sourceId.name << " (ref: " << sourceId.sourceReference << ")", mimeType);
1379 m_textView->SetMarker(line_number);
1380 });
1381 }
1382 }
1383
1384 clEnvList_t DebugAdapterClient::PrepareEnvForFileSystemWorkspace(const DapEntry& dap_server, bool resolve_vars)
1385 {
1386 clEnvList_t envlist = StringUtils::BuildEnvFromString(dap_server.GetEnvironment());
1387 if(clFileSystemWorkspace::Get().IsOpen()) {
1388 auto conf = clFileSystemWorkspace::Get().GetSettings().GetSelectedConfig();
1389 if(conf) {
1390 auto workspace_env = StringUtils::BuildEnvFromString(conf->GetEnvironment());
1391 envlist.insert(envlist.end(), workspace_env.begin(), workspace_env.end());
1392 }
1393 }
1394
1395 if(resolve_vars) {
1396 EnvSetter setter; // apply global variables
1397 envlist = StringUtils::ResolveEnvList(envlist);
1398 }
1399 return envlist;
1400 }
1401
1402 void DebugAdapterClient::OnIdle(wxIdleEvent& event)
1403 {
1404 event.Skip();
1405 CHECK_PTR_RET(m_client.IsConnected());
1406
1407 if(!m_client.CanInteract()) {
1408 ClearDebuggerMarker();
1409 }
1410 }
1411
1412 void DebugAdapterClient::DestroyTooltip()
1413 {
1414 CHECK_PTR_RET(m_tooltip);
1415 wxDELETE(m_tooltip);
1416 }
1417
1418 void DebugAdapterClient::OnPageClosing(wxNotifyEvent& event)
1419 {
1420 event.Skip();
1421 if(!m_client.IsConnected())
1422 return;
1423 // do not allow the user to close our text view control while debugging is active
1424 if(m_textView && m_textView == event.GetClientData()) {
1425 event.Veto();
1426 }
1427 }
1428
1429 wxString DebugAdapterClient::ReplacePlaceholders(const wxString& str) const
1430 {
1431 wxString project_name;
1432 if(clWorkspaceManager::Get().IsWorkspaceOpened()) {
1433 project_name = clWorkspaceManager::Get().GetWorkspace()->GetActiveProjectName();
1434 }
1435
1436 wxString command = MacroManager::Instance()->Expand(str, clGetManager(), project_name);
1437 return command;
1438 }
1439
1440 int DebugAdapterClient::GetCurrentFrameId() const
1441 {
1442 if(!m_threadsView) {
1443 return wxNOT_FOUND;
1444 }
1445 return m_threadsView->GetCurrentFrameId();
1446 }