aboutsummaryrefslogtreecommitdiff
path: root/source/Host/common/NativeProcessProtocol.cpp
blob: 6f1a9f895b6182f7f31286291ba5ab7ef2adbf64 (plain) (blame)
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
//===-- NativeProcessProtocol.cpp -------------------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "lldb/Host/common/NativeProcessProtocol.h"

#include "lldb/Core/ArchSpec.h"
#include "lldb/Core/ModuleSpec.h"
#include "lldb/Core/State.h"
#include "lldb/Host/Host.h"
#include "lldb/Host/common/NativeRegisterContext.h"
#include "lldb/Host/common/NativeThreadProtocol.h"
#include "lldb/Host/common/SoftwareBreakpoint.h"
#include "lldb/Symbol/ObjectFile.h"
#include "lldb/Target/Process.h"
#include "lldb/Utility/LLDBAssert.h"
#include "lldb/Utility/Log.h"
#include "lldb/lldb-enumerations.h"

using namespace lldb;
using namespace lldb_private;

// -----------------------------------------------------------------------------
// NativeProcessProtocol Members
// -----------------------------------------------------------------------------

NativeProcessProtocol::NativeProcessProtocol(lldb::pid_t pid)
    : m_pid(pid), m_threads(), m_current_thread_id(LLDB_INVALID_THREAD_ID),
      m_threads_mutex(), m_state(lldb::eStateInvalid), m_state_mutex(),
      m_exit_type(eExitTypeInvalid), m_exit_status(0), m_exit_description(),
      m_delegates_mutex(), m_delegates(), m_breakpoint_list(),
      m_watchpoint_list(), m_terminal_fd(-1), m_stop_id(0) {}

lldb_private::Status NativeProcessProtocol::Interrupt() {
  Status error;
#if !defined(SIGSTOP)
  error.SetErrorString("local host does not support signaling");
  return error;
#else
  return Signal(SIGSTOP);
#endif
}

Status NativeProcessProtocol::IgnoreSignals(llvm::ArrayRef<int> signals) {
  m_signals_to_ignore.clear();
  m_signals_to_ignore.insert(signals.begin(), signals.end());
  return Status();
}

lldb_private::Status
NativeProcessProtocol::GetMemoryRegionInfo(lldb::addr_t load_addr,
                                           MemoryRegionInfo &range_info) {
  // Default: not implemented.
  return Status("not implemented");
}

bool NativeProcessProtocol::GetExitStatus(ExitType *exit_type, int *status,
                                          std::string &exit_description) {
  if (m_state == lldb::eStateExited) {
    *exit_type = m_exit_type;
    *status = m_exit_status;
    exit_description = m_exit_description;
    return true;
  }

  *status = 0;
  return false;
}

bool NativeProcessProtocol::SetExitStatus(ExitType exit_type, int status,
                                          const char *exit_description,
                                          bool bNotifyStateChange) {
  Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
  if (log)
    log->Printf("NativeProcessProtocol::%s(%d, %d, %s, %s) called",
                __FUNCTION__, exit_type, status,
                exit_description ? exit_description : "nullptr",
                bNotifyStateChange ? "true" : "false");

  // Exit status already set
  if (m_state == lldb::eStateExited) {
    if (log)
      log->Printf("NativeProcessProtocol::%s exit status already set to %d, "
                  "ignoring new set to %d",
                  __FUNCTION__, m_exit_status, status);
    return false;
  }

  m_state = lldb::eStateExited;

  m_exit_type = exit_type;
  m_exit_status = status;
  if (exit_description && exit_description[0])
    m_exit_description = exit_description;
  else
    m_exit_description.clear();

  if (bNotifyStateChange)
    SynchronouslyNotifyProcessStateChanged(lldb::eStateExited);

  return true;
}

NativeThreadProtocolSP NativeProcessProtocol::GetThreadAtIndex(uint32_t idx) {
  std::lock_guard<std::recursive_mutex> guard(m_threads_mutex);
  if (idx < m_threads.size())
    return m_threads[idx];
  return NativeThreadProtocolSP();
}

NativeThreadProtocolSP
NativeProcessProtocol::GetThreadByIDUnlocked(lldb::tid_t tid) {
  for (auto thread_sp : m_threads) {
    if (thread_sp->GetID() == tid)
      return thread_sp;
  }
  return NativeThreadProtocolSP();
}

NativeThreadProtocolSP NativeProcessProtocol::GetThreadByID(lldb::tid_t tid) {
  std::lock_guard<std::recursive_mutex> guard(m_threads_mutex);
  return GetThreadByIDUnlocked(tid);
}

bool NativeProcessProtocol::IsAlive() const {
  return m_state != eStateDetached && m_state != eStateExited &&
         m_state != eStateInvalid && m_state != eStateUnloaded;
}

bool NativeProcessProtocol::GetByteOrder(lldb::ByteOrder &byte_order) const {
  ArchSpec process_arch;
  if (!GetArchitecture(process_arch))
    return false;
  byte_order = process_arch.GetByteOrder();
  return true;
}

const NativeWatchpointList::WatchpointMap &
NativeProcessProtocol::GetWatchpointMap() const {
  return m_watchpoint_list.GetWatchpointMap();
}

llvm::Optional<std::pair<uint32_t, uint32_t>>
NativeProcessProtocol::GetHardwareDebugSupportInfo() const {
  Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));

  // get any thread
  NativeThreadProtocolSP thread_sp(
      const_cast<NativeProcessProtocol *>(this)->GetThreadAtIndex(0));
  if (!thread_sp) {
    if (log)
      log->Warning("NativeProcessProtocol::%s (): failed to find a thread to "
                   "grab a NativeRegisterContext!",
                   __FUNCTION__);
    return llvm::None;
  }

  NativeRegisterContextSP reg_ctx_sp(thread_sp->GetRegisterContext());
  if (!reg_ctx_sp) {
    if (log)
      log->Warning("NativeProcessProtocol::%s (): failed to get a "
                   "RegisterContextNativeProcess from the first thread!",
                   __FUNCTION__);
    return llvm::None;
  }

  return std::make_pair(reg_ctx_sp->NumSupportedHardwareBreakpoints(),
                        reg_ctx_sp->NumSupportedHardwareWatchpoints());
}

Status NativeProcessProtocol::SetWatchpoint(lldb::addr_t addr, size_t size,
                                            uint32_t watch_flags,
                                            bool hardware) {
  // This default implementation assumes setting the watchpoint for
  // the process will require setting the watchpoint for each of the
  // threads.  Furthermore, it will track watchpoints set for the
  // process and will add them to each thread that is attached to
  // via the (FIXME implement) OnThreadAttached () method.

  Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));

  // Update the thread list
  UpdateThreads();

  // Keep track of the threads we successfully set the watchpoint
  // for.  If one of the thread watchpoint setting operations fails,
  // back off and remove the watchpoint for all the threads that
  // were successfully set so we get back to a consistent state.
  std::vector<NativeThreadProtocolSP> watchpoint_established_threads;

  // Tell each thread to set a watchpoint.  In the event that
  // hardware watchpoints are requested but the SetWatchpoint fails,
  // try to set a software watchpoint as a fallback.  It's
  // conceivable that if there are more threads than hardware
  // watchpoints available, some of the threads will fail to set
  // hardware watchpoints while software ones may be available.
  std::lock_guard<std::recursive_mutex> guard(m_threads_mutex);
  for (auto thread_sp : m_threads) {
    assert(thread_sp && "thread list should not have a NULL thread!");
    if (!thread_sp)
      continue;

    Status thread_error =
        thread_sp->SetWatchpoint(addr, size, watch_flags, hardware);
    if (thread_error.Fail() && hardware) {
      // Try software watchpoints since we failed on hardware watchpoint setting
      // and we may have just run out of hardware watchpoints.
      thread_error = thread_sp->SetWatchpoint(addr, size, watch_flags, false);
      if (thread_error.Success()) {
        if (log)
          log->Warning(
              "hardware watchpoint requested but software watchpoint set");
      }
    }

    if (thread_error.Success()) {
      // Remember that we set this watchpoint successfully in
      // case we need to clear it later.
      watchpoint_established_threads.push_back(thread_sp);
    } else {
      // Unset the watchpoint for each thread we successfully
      // set so that we get back to a consistent state of "not
      // set" for the watchpoint.
      for (auto unwatch_thread_sp : watchpoint_established_threads) {
        Status remove_error = unwatch_thread_sp->RemoveWatchpoint(addr);
        if (remove_error.Fail() && log) {
          log->Warning("NativeProcessProtocol::%s (): RemoveWatchpoint failed "
                       "for pid=%" PRIu64 ", tid=%" PRIu64 ": %s",
                       __FUNCTION__, GetID(), unwatch_thread_sp->GetID(),
                       remove_error.AsCString());
        }
      }

      return thread_error;
    }
  }
  return m_watchpoint_list.Add(addr, size, watch_flags, hardware);
}

Status NativeProcessProtocol::RemoveWatchpoint(lldb::addr_t addr) {
  // Update the thread list
  UpdateThreads();

  Status overall_error;

  std::lock_guard<std::recursive_mutex> guard(m_threads_mutex);
  for (auto thread_sp : m_threads) {
    assert(thread_sp && "thread list should not have a NULL thread!");
    if (!thread_sp)
      continue;

    const Status thread_error = thread_sp->RemoveWatchpoint(addr);
    if (thread_error.Fail()) {
      // Keep track of the first thread error if any threads
      // fail. We want to try to remove the watchpoint from
      // every thread, though, even if one or more have errors.
      if (!overall_error.Fail())
        overall_error = thread_error;
    }
  }
  const Status error = m_watchpoint_list.Remove(addr);
  return overall_error.Fail() ? overall_error : error;
}

const HardwareBreakpointMap &
NativeProcessProtocol::GetHardwareBreakpointMap() const {
  return m_hw_breakpoints_map;
}

Status NativeProcessProtocol::SetHardwareBreakpoint(lldb::addr_t addr,
                                                    size_t size) {
  // This default implementation assumes setting a hardware breakpoint for
  // this process will require setting same hardware breakpoint for each
  // of its existing threads. New thread will do the same once created.
  Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));

  // Update the thread list
  UpdateThreads();

  // Exit here if target does not have required hardware breakpoint capability.
  auto hw_debug_cap = GetHardwareDebugSupportInfo();

  if (hw_debug_cap == llvm::None || hw_debug_cap->first == 0 ||
      hw_debug_cap->first <= m_hw_breakpoints_map.size())
    return Status("Target does not have required no of hardware breakpoints");

  // Vector below stores all thread pointer for which we have we successfully
  // set this hardware breakpoint. If any of the current process threads fails
  // to set this hardware breakpoint then roll back and remove this breakpoint
  // for all the threads that had already set it successfully.
  std::vector<NativeThreadProtocolSP> breakpoint_established_threads;

  // Request to set a hardware breakpoint for each of current process threads.
  std::lock_guard<std::recursive_mutex> guard(m_threads_mutex);
  for (auto thread_sp : m_threads) {
    assert(thread_sp && "thread list should not have a NULL thread!");
    if (!thread_sp)
      continue;

    Status thread_error = thread_sp->SetHardwareBreakpoint(addr, size);
    if (thread_error.Success()) {
      // Remember that we set this breakpoint successfully in
      // case we need to clear it later.
      breakpoint_established_threads.push_back(thread_sp);
    } else {
      // Unset the breakpoint for each thread we successfully
      // set so that we get back to a consistent state of "not
      // set" for this hardware breakpoint.
      for (auto rollback_thread_sp : breakpoint_established_threads) {
        Status remove_error =
            rollback_thread_sp->RemoveHardwareBreakpoint(addr);
        if (remove_error.Fail() && log) {
          log->Warning("NativeProcessProtocol::%s (): RemoveHardwareBreakpoint"
                       " failed for pid=%" PRIu64 ", tid=%" PRIu64 ": %s",
                       __FUNCTION__, GetID(), rollback_thread_sp->GetID(),
                       remove_error.AsCString());
        }
      }

      return thread_error;
    }
  }

  // Register new hardware breakpoint into hardware breakpoints map of current
  // process.
  m_hw_breakpoints_map[addr] = {addr, size};

  return Status();
}

Status NativeProcessProtocol::RemoveHardwareBreakpoint(lldb::addr_t addr) {
  // Update the thread list
  UpdateThreads();

  Status error;

  std::lock_guard<std::recursive_mutex> guard(m_threads_mutex);
  for (auto thread_sp : m_threads) {
    assert(thread_sp && "thread list should not have a NULL thread!");
    if (!thread_sp)
      continue;

    error = thread_sp->RemoveHardwareBreakpoint(addr);
  }

  // Also remove from hardware breakpoint map of current process.
  m_hw_breakpoints_map.erase(addr);

  return error;
}

bool NativeProcessProtocol::RegisterNativeDelegate(
    NativeDelegate &native_delegate) {
  std::lock_guard<std::recursive_mutex> guard(m_delegates_mutex);
  if (std::find(m_delegates.begin(), m_delegates.end(), &native_delegate) !=
      m_delegates.end())
    return false;

  m_delegates.push_back(&native_delegate);
  native_delegate.InitializeDelegate(this);
  return true;
}

bool NativeProcessProtocol::UnregisterNativeDelegate(
    NativeDelegate &native_delegate) {
  std::lock_guard<std::recursive_mutex> guard(m_delegates_mutex);

  const auto initial_size = m_delegates.size();
  m_delegates.erase(
      remove(m_delegates.begin(), m_delegates.end(), &native_delegate),
      m_delegates.end());

  // We removed the delegate if the count of delegates shrank after
  // removing all copies of the given native_delegate from the vector.
  return m_delegates.size() < initial_size;
}

void NativeProcessProtocol::SynchronouslyNotifyProcessStateChanged(
    lldb::StateType state) {
  Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));

  std::lock_guard<std::recursive_mutex> guard(m_delegates_mutex);
  for (auto native_delegate : m_delegates)
    native_delegate->ProcessStateChanged(this, state);

  if (log) {
    if (!m_delegates.empty()) {
      log->Printf("NativeProcessProtocol::%s: sent state notification [%s] "
                  "from process %" PRIu64,
                  __FUNCTION__, lldb_private::StateAsCString(state), GetID());
    } else {
      log->Printf("NativeProcessProtocol::%s: would send state notification "
                  "[%s] from process %" PRIu64 ", but no delegates",
                  __FUNCTION__, lldb_private::StateAsCString(state), GetID());
    }
  }
}

void NativeProcessProtocol::NotifyDidExec() {
  Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
  if (log)
    log->Printf("NativeProcessProtocol::%s - preparing to call delegates",
                __FUNCTION__);

  {
    std::lock_guard<std::recursive_mutex> guard(m_delegates_mutex);
    for (auto native_delegate : m_delegates)
      native_delegate->DidExec(this);
  }
}

Status NativeProcessProtocol::SetSoftwareBreakpoint(lldb::addr_t addr,
                                                    uint32_t size_hint) {
  Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
  if (log)
    log->Printf("NativeProcessProtocol::%s addr = 0x%" PRIx64, __FUNCTION__,
                addr);

  return m_breakpoint_list.AddRef(
      addr, size_hint, false,
      [this](lldb::addr_t addr, size_t size_hint, bool /* hardware */,
             NativeBreakpointSP &breakpoint_sp) -> Status {
        return SoftwareBreakpoint::CreateSoftwareBreakpoint(
            *this, addr, size_hint, breakpoint_sp);
      });
}

Status NativeProcessProtocol::RemoveBreakpoint(lldb::addr_t addr,
                                               bool hardware) {
  if (hardware)
    return RemoveHardwareBreakpoint(addr);
  else
    return m_breakpoint_list.DecRef(addr);
}

Status NativeProcessProtocol::EnableBreakpoint(lldb::addr_t addr) {
  return m_breakpoint_list.EnableBreakpoint(addr);
}

Status NativeProcessProtocol::DisableBreakpoint(lldb::addr_t addr) {
  return m_breakpoint_list.DisableBreakpoint(addr);
}

lldb::StateType NativeProcessProtocol::GetState() const {
  std::lock_guard<std::recursive_mutex> guard(m_state_mutex);
  return m_state;
}

void NativeProcessProtocol::SetState(lldb::StateType state,
                                     bool notify_delegates) {
  std::lock_guard<std::recursive_mutex> guard(m_state_mutex);

  if (state == m_state)
    return;

  m_state = state;

  if (StateIsStoppedState(state, false)) {
    ++m_stop_id;

    // Give process a chance to do any stop id bump processing, such as
    // clearing cached data that is invalidated each time the process runs.
    // Note if/when we support some threads running, we'll end up needing
    // to manage this per thread and per process.
    DoStopIDBumped(m_stop_id);
  }

  // Optionally notify delegates of the state change.
  if (notify_delegates)
    SynchronouslyNotifyProcessStateChanged(state);
}

uint32_t NativeProcessProtocol::GetStopID() const {
  std::lock_guard<std::recursive_mutex> guard(m_state_mutex);
  return m_stop_id;
}

void NativeProcessProtocol::DoStopIDBumped(uint32_t /* newBumpId */) {
  // Default implementation does nothing.
}

Status NativeProcessProtocol::ResolveProcessArchitecture(lldb::pid_t pid,
                                                         ArchSpec &arch) {
  // Grab process info for the running process.
  ProcessInstanceInfo process_info;
  if (!Host::GetProcessInfo(pid, process_info))
    return Status("failed to get process info");

  // Resolve the executable module.
  ModuleSpecList module_specs;
  if (!ObjectFile::GetModuleSpecifications(process_info.GetExecutableFile(), 0,
                                           0, module_specs))
    return Status("failed to get module specifications");
  lldbassert(module_specs.GetSize() == 1);

  arch = module_specs.GetModuleSpecRefAtIndex(0).GetArchitecture();
  if (arch.IsValid())
    return Status();
  else
    return Status(
        "failed to retrieve a valid architecture from the exe module");
}

#if !defined(__linux__) && !defined(__NetBSD__)
// These need to be implemented to support lldb-gdb-server on a given platform.
// Stubs are
// provided to make the rest of the code link on non-supported platforms.

Status NativeProcessProtocol::Launch(ProcessLaunchInfo &launch_info,
                                     NativeDelegate &native_delegate,
                                     MainLoop &mainloop,
                                     NativeProcessProtocolSP &process_sp) {
  llvm_unreachable("Platform has no NativeProcessProtocol support");
}

Status NativeProcessProtocol::Attach(lldb::pid_t pid,
                                     NativeDelegate &native_delegate,
                                     MainLoop &mainloop,
                                     NativeProcessProtocolSP &process_sp) {
  llvm_unreachable("Platform has no NativeProcessProtocol support");
}

#endif