File: LLDBConnector.cpp

package info (click to toggle)
codelite 6.1.1%2Bdfsg-4
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 48,992 kB
  • ctags: 43,502
  • sloc: cpp: 334,263; ansic: 18,441; xml: 4,713; yacc: 2,653; lex: 2,449; python: 1,188; sh: 385; makefile: 40
file content (673 lines) | stat: -rw-r--r-- 18,833 bytes parent folder | download
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
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//
// copyright            : (C) 2014 The CodeLite Team
// file name            : LLDBConnector.cpp
//
// -------------------------------------------------------------------------
// A
//              _____           _      _     _ _
//             /  __ \         | |    | |   (_) |
//             | /  \/ ___   __| | ___| |    _| |_ ___
//             | |    / _ \ / _  |/ _ \ |   | | __/ _ )
//             | \__/\ (_) | (_| |  __/ |___| | ||  __/
//              \____/\___/ \__,_|\___\_____/_|\__\___|
//
//                                                  F i l e
//
//    This program is free software; you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation; either version 2 of the License, or
//    (at your option) any later version.
//
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////

#include "LLDBConnector.h"
#include "LLDBNetworkListenerThread.h"
#include "LLDBEvent.h"
#include "file_logger.h"
#include "processreaderthread.h"
#include <wx/tokenzr.h>
#include "file_logger.h"
#include <wx/filefn.h>
#include <wx/log.h>
#include "environmentconfig.h"
#include "json_node.h"
#include <wx/msgdlg.h>
#include "LLDBSettings.h"
#include "globals.h"
#include "LLDBRemoteHandshakePacket.h"
#include "cl_standard_paths.h"

#ifndef __WXMSW__
#include <sys/wait.h>
#include <unistd.h>
#endif

wxBEGIN_EVENT_TABLE(LLDBConnector, wxEvtHandler)
    EVT_COMMAND(wxID_ANY, wxEVT_PROC_DATA_READ, LLDBConnector::OnProcessOutput)
    EVT_COMMAND(wxID_ANY, wxEVT_PROC_TERMINATED, LLDBConnector::OnProcessTerminated) wxEND_EVENT_TABLE()

    LLDBConnector::LLDBConnector()
    : m_thread(NULL)
    , m_process(NULL)
    , m_isRunning(false)
    , m_canInteract(false)
    , m_goingDown(false)
{
    Bind(wxEVT_LLDB_EXITED, &LLDBConnector::OnLLDBExited, this);
    Bind(wxEVT_LLDB_STARTED, &LLDBConnector::OnLLDBStarted, this);
}

LLDBConnector::~LLDBConnector()
{
    StopDebugServer();
    Unbind(wxEVT_LLDB_EXITED, &LLDBConnector::OnLLDBExited, this);
    Unbind(wxEVT_LLDB_STARTED, &LLDBConnector::OnLLDBStarted, this);
    Cleanup();
}

bool LLDBConnector::ConnectToLocalDebugger(LLDBConnectReturnObject& ret, int timeout)
{

#ifndef __WXMSW__
    clSocketClient* client = new clSocketClient();
    m_socket.reset(client);
    CL_DEBUG("Connecting to codelite-lldb on %s", GetDebugServerPath());

    long msTimeout = timeout * 1000;
    long retriesCount = msTimeout / 250; // We try every 250 ms to connect
    bool connected = false;
    for(long i = 0; i < retriesCount; ++i) {
        if(!client->ConnectLocal(GetDebugServerPath())) {
            wxThread::Sleep(250);
            continue;
        }
        connected = true;
        break;
    }

    if(!connected) {
        return false;
    }

    // Start the lldb event thread
    // and start a listener thread which will read replies
    // from codelite-lldb and convert them into LLDBEvent
    socket_t fd = m_socket->GetSocket();
    m_pivot.Clear();
    m_thread = new LLDBNetworkListenerThread(this, m_pivot, fd);
    m_thread->Start();
    CL_DEBUG("Successfully connected to codelite-lldb");
    return true;
#else
    CL_WARNING("LLDB Debugger: can't connect to local debugger - this is not support on MSW");
    return false;
#endif
}

bool LLDBConnector::ConnectToRemoteDebugger(const wxString& ip, int port, LLDBConnectReturnObject& ret, int timeout)
{
    m_socket.reset(NULL);
    clSocketClient* client = new clSocketClient();
    m_socket.reset(client);
    CL_DEBUG("Connecting to codelite-lldb on %s:%d", ip, port);

    try {
        bool would_block = false;
        if(!client->ConnectRemote(ip, port, would_block, true)) {
            // select the socket
            if(!would_block) {
                m_socket.reset(NULL);
                return false;
            }

            try {
                if(client->SelectWrite(timeout) == clSocketBase::kTimeout) {
                    m_socket.reset(NULL);
                    return false;
                }
            } catch(clSocketException& e) {
                CL_DEBUG("SelectWrite error: %s", e.what());
            }
        }

        // Connected!
        // Read the negotiation packet (part of the protocol only when doing remote connection)
        wxString message;
        if(m_socket->ReadMessage(message, 2) != clSocketBase::kSuccess) {
            m_socket.reset(NULL);
            return false;
        }

        LLDBRemoteHandshakePacket handshake(message);
        ret.SetRemoteHostName(handshake.GetHost());
        ret.SetPivotNeeded(handshake.GetHost() != ::wxGetHostName());

    } catch(clSocketException& e) {
        CL_WARNING("LLDBConnector::ConnectToRemoteDebugger: %s", e.what());
        m_socket.reset(NULL);
        return false;
    }
    CL_DEBUG("Successfully connected to codelite-lldb");
    return true;
}

void LLDBConnector::SendCommand(const LLDBCommand& command)
{
    try {
        if(m_socket) {
            // Convert local paths to remote paths if needed
            LLDBCommand updatedCommand = command;
            updatedCommand.UpdatePaths(m_pivot);
            m_socket->WriteMessage(updatedCommand.ToJSON().format());
        }

    } catch(clSocketException& e) {
        wxUnusedVar(e);
    }
}

void LLDBConnector::InvalidateBreakpoints()
{
    // mark all the breakpoints as "not-applied" (id=-1)
    LLDBBreakpoint::Vec_t updatedList;

    for(size_t i = 0; i < m_breakpoints.size(); ++i) {
        m_breakpoints.at(i)->Invalidate();
        if(wxFileName::Exists(m_breakpoints.at(i)->GetFilename())) {
            updatedList.push_back(m_breakpoints.at(i));
        }
    }
    // we keep only breakpoints with valid filename
    m_breakpoints.swap(updatedList);
    ClearBreakpointDeletionQueue();

    CL_DEBUG("codelite: InvalidateBreakpoints called");
    m_pendingDeletionBreakpoints.clear();
}

bool LLDBConnector::IsBreakpointExists(LLDBBreakpoint::Ptr_t bp) const
{
    return FindBreakpoint(bp) != m_breakpoints.end();
}

LLDBBreakpoint::Vec_t::iterator LLDBConnector::FindBreakpoint(LLDBBreakpoint::Ptr_t bp)
{
    LLDBBreakpoint::Vec_t::iterator iter = m_breakpoints.begin();
    for(; iter != m_breakpoints.end(); ++iter) {
        if((*iter)->SameAs(bp)) {
            return iter;
        }
    }
    return m_breakpoints.end();
}

LLDBBreakpoint::Vec_t::const_iterator LLDBConnector::FindBreakpoint(LLDBBreakpoint::Ptr_t bp) const
{
    LLDBBreakpoint::Vec_t::const_iterator iter = m_breakpoints.begin();
    for(; iter != m_breakpoints.end(); ++iter) {
        if((*iter)->SameAs(bp)) {
            return iter;
        }
    }
    return m_breakpoints.end();
}

void LLDBConnector::AddBreakpoint(LLDBBreakpoint::Ptr_t breakpoint, bool notify)
{
    if(!IsBreakpointExists(breakpoint)) {
        m_breakpoints.push_back(breakpoint);

        if(notify) {
            LLDBEvent event(wxEVT_LLDB_BREAKPOINTS_UPDATED);
            event.SetBreakpoints(GetAllBreakpoints());
            ProcessEvent(event);
        }
    }
}

void LLDBConnector::ApplyBreakpoints()
{
    if(!m_breakpoints.empty()) {

        if(IsCanInteract()) {
            LLDBCommand command;
            command.SetCommandType(kCommandApplyBreakpoints);
            command.SetBreakpoints(GetUnappliedBreakpoints());
            SendCommand(command);
            m_breakpoints.clear();

        } else {
            Interrupt(kInterruptReasonApplyBreakpoints);
        }
    }
}

void LLDBConnector::Continue()
{
    LLDBCommand command;
    command.SetCommandType(kCommandContinue);
    SendCommand(command);
}

void LLDBConnector::Stop()
{
    if(IsAttachedToProcess()) {
        Detach();

    } else {
        LLDBCommand command;
        command.SetCommandType(kCommandStop);
        SendCommand(command);
    }
}

void LLDBConnector::Detach()
{
    if(IsCanInteract()) {
        CL_DEBUG("Sending 'Detach' command");
        LLDBCommand command;
        command.SetCommandType(kCommandDetach);
        SendCommand(command);

    } else {
        Interrupt(kInterruptReasonDetaching);
    }
}

void LLDBConnector::MarkBreakpointForDeletion(LLDBBreakpoint::Ptr_t bp)
{
    if(!IsBreakpointExists(bp)) {
        return;
    }

    LLDBBreakpoint::Vec_t::iterator iter = FindBreakpoint(bp);

    // add the breakpoint to the pending deletion breakpoints
    bp->SetId((*iter)->GetId());
    m_pendingDeletionBreakpoints.push_back(bp);
    m_breakpoints.erase(iter);
}

void LLDBConnector::DeleteBreakpoints()
{
    if(IsCanInteract()) {
        CL_DEBUGS(wxString() << "codelite: deleting breakpoints (total of " << m_pendingDeletionBreakpoints.size()
                             << " breakpoints)");
        LLDBCommand command;
        command.SetCommandType(kCommandDeleteBreakpoint);
        command.SetBreakpoints(m_pendingDeletionBreakpoints);
        SendCommand(command);
        CL_DEBUGS(wxString() << "codelite: DeleteBreakpoints celar pending deletionbreakpoints queue");
        m_pendingDeletionBreakpoints.clear();

    } else {
        CL_DEBUG("codelite: interrupting codelite-lldb for kInterruptReasonDeleteBreakpoint");
        Interrupt(kInterruptReasonDeleteBreakpoint);
    }
}

void LLDBConnector::ClearBreakpointDeletionQueue()
{
    CL_DEBUGS(wxString() << "codelite: ClearBreakpointDeletionQueue called");
    m_pendingDeletionBreakpoints.clear();
}

void LLDBConnector::Next()
{
    LLDBCommand command;
    command.SetCommandType(kCommandNext);
    SendCommand(command);
}

void LLDBConnector::StepIn()
{
    LLDBCommand command;
    command.SetCommandType(kCommandStepIn);
    SendCommand(command);
}

void LLDBConnector::StepOut()
{
    LLDBCommand command;
    command.SetCommandType(kCommandStepOut);
    SendCommand(command);
}

void LLDBConnector::DeleteAllBreakpoints()
{
    if(!IsRunning()) {
        m_pendingDeletionBreakpoints.clear();
        m_breakpoints.clear();

        LLDBEvent event(wxEVT_LLDB_BREAKPOINTS_UPDATED);
        event.SetBreakpoints(GetAllBreakpoints());
        ProcessEvent(event);
        return;
    }

    // mark all breakpoints for deletion
    CL_DEBUGS(wxString() << "codelite: DeleteAllBreakpoints called");
    m_pendingDeletionBreakpoints.swap(m_breakpoints);

    if(!IsCanInteract()) {
        Interrupt(kInterruptReasonDeleteAllBreakpoints);

    } else {
        LLDBCommand command;
        command.SetCommandType(kCommandDeleteAllBreakpoints);
        SendCommand(command);
        m_pendingDeletionBreakpoints.clear();
    }
}

void LLDBConnector::AddBreakpoints(const BreakpointInfo::Vec_t& breakpoints)
{
    LLDBBreakpoint::Vec_t bps = LLDBBreakpoint::FromBreakpointInfoVector(breakpoints);
    AddBreakpoints(bps);
}

void LLDBConnector::AddBreakpoints(const LLDBBreakpoint::Vec_t& breakpoints)
{
    for(size_t i = 0; i < breakpoints.size(); ++i) {
        AddBreakpoint(breakpoints.at(i), false);
    }
}

void LLDBConnector::Cleanup()
{
    // the order matters here, since both are using the same file descriptor
    // but only m_socket does the actual socket shutdown
    wxDELETE(m_thread);
    m_socket.reset(NULL);
    InvalidateBreakpoints();
    m_isRunning = false;
    m_canInteract = false;
    m_runCommand.Clear();
    m_attachedToProcess = false;
    StopDebugServer();
    m_pivot.Clear();
}

void LLDBConnector::OnLLDBExited(LLDBEvent& event)
{
    event.Skip();
    m_isRunning = false;
}

void LLDBConnector::OnLLDBStarted(LLDBEvent& event)
{
    event.Skip();
    m_isRunning = true;
}

void LLDBConnector::Start(const LLDBCommand& runCommand)
{
    LLDBCommand startCommand;
    startCommand.SetExecutable(runCommand.GetExecutable());
    startCommand.SetCommandType(kCommandStart);
    startCommand.SetWorkingDirectory(runCommand.GetWorkingDirectory());

    // send the settings as well
    LLDBSettings settings;
    settings.Load();
    startCommand.SetSettings(settings);
    SendCommand(startCommand);

    // stash the runCommand for the future 'Run()' call
    m_runCommand.Clear();
    m_runCommand = runCommand;
    m_runCommand.SetCommandType(kCommandRun);
}

void LLDBConnector::Run()
{
    if(m_runCommand.GetCommandType() == kCommandRun) {
        SendCommand(m_runCommand);
        m_runCommand.Clear();
    }
}

void LLDBConnector::UpdateAppliedBreakpoints(const LLDBBreakpoint::Vec_t& breakpoints) { m_breakpoints = breakpoints; }

const LLDBBreakpoint::Vec_t& LLDBConnector::GetAllBreakpoints() const { return m_breakpoints; }

void LLDBConnector::OnProcessOutput(wxCommandEvent& event)
{
    ProcessEventData* ped = (ProcessEventData*)event.GetClientData();
    wxString output = ped->GetData();
    wxDELETE(ped);

    wxArrayString lines = ::wxStringTokenize(output, "\n", wxTOKEN_STRTOK);
    for(size_t i = 0; i < lines.GetCount(); ++i) {
        CL_DEBUG("%s", lines.Item(i).Trim());
    }
}

void LLDBConnector::OnProcessTerminated(wxCommandEvent& event)
{
    ProcessEventData* ped = (ProcessEventData*)event.GetClientData();
    if(ped) {
        wxDELETE(ped);
    }
    wxDELETE(m_process);
    Cleanup();
}

void LLDBConnector::Interrupt(eInterruptReason reason)
{
    LLDBCommand command;
    command.SetCommandType(kCommandInterrupt);
    command.SetInterruptReason(reason);
    SendCommand(command);
}

bool LLDBConnector::LaunchLocalDebugServer()
{
#ifdef __WXMSW__
    // Not supported :(
    ::wxMessageBox(_("Locally debugging with LLDB on Windows is not supported by LLDB"),
                   "CodeLite",
                   wxICON_WARNING | wxOK | wxCENTER);
    return false;
#endif

    CL_DEBUG("Launching codelite-lldb");
    // Start the debugger
    if(m_process) {
        // another debugger process is already running
        return false;
    }

    // Apply the environment before we start
    wxStringMap_t om;

#ifdef __WXMAC__
    // set the LLDB_DEBUGSERVER_PATH env variable
    wxFileName debugserver(clStandardPaths::Get().GetBinaryFullPath("debugserver"));
    om["LLDB_DEBUGSERVER_PATH"] = debugserver.GetFullPath();
#endif

    EnvSetter es(NULL, &om);

    wxFileName fnCodeLiteLLDB(clStandardPaths::Get().GetBinaryFullPath("codelite-lldb"));

    wxString command;
    command << fnCodeLiteLLDB.GetFullPath() << " -s " << GetDebugServerPath();

    m_process = ::CreateAsyncProcess(this, command);
    if(!m_process) {
        CL_ERROR("LLDBConnector: failed to launch codelite-lldb: %s", fnCodeLiteLLDB.GetFullPath());
        return false;

    } else {
        CL_DEBUG("codelite-lldb launched successfully. PID=%d\n", m_process->GetPid());
    }
    return true;
}

void LLDBConnector::StopDebugServer()
{
    if(m_process) {
        m_process->SetHardKill(true); // kill -9
        m_process->Terminate();
        m_process = NULL;
    }

    wxLogNull noLog;
    wxRemoveFile(GetDebugServerPath());
}

LLDBBreakpoint::Vec_t LLDBConnector::GetUnappliedBreakpoints()
{
    LLDBBreakpoint::Vec_t unappliedBreakpoints;
    for(size_t i = 0; i < m_breakpoints.size(); ++i) {
        if(!m_breakpoints.at(i)->IsApplied()) {
            unappliedBreakpoints.push_back(m_breakpoints.at(i));
        }
    }
    return unappliedBreakpoints;
}

void LLDBConnector::RequestLocals()
{
    if(IsCanInteract()) {
        LLDBCommand command;
        command.SetCommandType(kCommandGetLocals);
        SendCommand(command);
    }
}

void LLDBConnector::RequestVariableChildren(int lldbId)
{
    if(IsCanInteract()) {
        LLDBCommand command;
        command.SetCommandType(kCommandExpandVariable);
        command.SetLldbId(lldbId);
        SendCommand(command);
    }
}

wxString LLDBConnector::GetDebugServerPath() const
{
    wxString path;
    path << "/tmp/codelite-lldb.";
    path << ::wxGetProcessId() << ".sock";
    return path;
}

void LLDBConnector::SelectFrame(int frameID)
{
    if(IsCanInteract()) {
        LLDBCommand command;
        command.SetCommandType(kCommandSelectFrame);
        command.SetFrameId(frameID);
        SendCommand(command);
    }
}

void LLDBConnector::SelectThread(int threadID)
{
    if(IsCanInteract()) {
        LLDBCommand command;
        command.SetCommandType(kCommandSelectThread);
        command.SetThreadId(threadID);
        SendCommand(command);
    }
}

void LLDBConnector::EvaluateExpression(const wxString& expression)
{
    if(IsCanInteract()) {
        LLDBCommand command;
        command.SetCommandType(kCommandEvalExpression);
        command.SetExpression(expression);
        SendCommand(command);
    }
}

void LLDBConnector::OpenCoreFile(const LLDBCommand& runCommand) { SendCommand(runCommand); }

void LLDBConnector::AttachProcessWithPID(const LLDBCommand& runCommand)
{
    m_attachedToProcess = true;
    SendCommand(runCommand);
}

void LLDBConnector::NextInstruction()
{
    if(IsCanInteract()) {
        LLDBCommand command;
        command.SetCommandType(kCommandNextInstruction);
        SendCommand(command);
    }
}

void LLDBConnector::ShowCurrentFileLine()
{
    if(IsCanInteract()) {
        LLDBCommand command;
        command.SetCommandType(kCommandCurrentFileLine);
        SendCommand(command);
    }
}

wxString LLDBConnector::GetConnectString() const
{
    wxString connectString;
    LLDBSettings settings;
    bool useTcp = settings.Load().IsUsingRemoteProxy();
    if(useTcp) {
        connectString << settings.GetProxyIp() << ":" << settings.GetProxyPort();
    } else {
        connectString << GetDebugServerPath();
    }
    return connectString;
}

bool LLDBConnector::Connect(LLDBConnectReturnObject& ret, const LLDBSettings& settings, int timeout)
{
    ret.Clear();
    if(settings.IsUsingRemoteProxy()) {
        return ConnectToRemoteDebugger(settings.GetProxyIp(), settings.GetProxyPort(), ret, timeout);

    } else {
        return ConnectToLocalDebugger(ret, timeout);
    }
}

void LLDBConnector::StartNetworkThread()
{
    if(!m_thread && m_socket) {
        socket_t fd = m_socket->GetSocket();
        m_thread = new LLDBNetworkListenerThread(this, m_pivot, fd);
        m_thread->Start();
    }
}

void LLDBConnector::AddWatch(const wxString& watch)
{
    LLDBCommand command;
    command.SetCommandType(kCommandAddWatch);
    command.SetExpression(watch);
    SendCommand(command);
}

void LLDBConnector::DeleteWatch(int lldbId)
{
    LLDBCommand command;
    command.SetCommandType(kCommandDeleteWatch);
    command.SetLldbId(lldbId);
    SendCommand(command);
}

void LLDBTerminalCallback::OnProcessOutput(const wxString& str) { wxUnusedVar(str); }

void LLDBTerminalCallback::OnProcessTerminated()
{
    wxDELETE(m_process);
    delete this;
    CL_DEBUG("LLDB terminal process terminated. Cleaning up");
}