Coverage Report

Created: 2022-01-25 06:29

/Users/buildslave/jenkins/workspace/coverage/llvm-project/lldb/source/Host/common/NativeProcessProtocol.cpp
Line
Count
Source (jump to first uncovered line)
1
//===-- NativeProcessProtocol.cpp -----------------------------------------===//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
9
#include "lldb/Host/common/NativeProcessProtocol.h"
10
#include "lldb/Host/Host.h"
11
#include "lldb/Host/common/NativeBreakpointList.h"
12
#include "lldb/Host/common/NativeRegisterContext.h"
13
#include "lldb/Host/common/NativeThreadProtocol.h"
14
#include "lldb/Utility/LLDBAssert.h"
15
#include "lldb/Utility/Log.h"
16
#include "lldb/Utility/State.h"
17
#include "lldb/lldb-enumerations.h"
18
19
#include "llvm/Support/Process.h"
20
21
using namespace lldb;
22
using namespace lldb_private;
23
24
// NativeProcessProtocol Members
25
26
NativeProcessProtocol::NativeProcessProtocol(lldb::pid_t pid, int terminal_fd,
27
                                             NativeDelegate &delegate)
28
8
    : m_pid(pid), m_delegate(delegate), m_terminal_fd(terminal_fd) {
29
8
  delegate.InitializeDelegate(this);
30
8
}
31
32
0
lldb_private::Status NativeProcessProtocol::Interrupt() {
33
0
  Status error;
34
#if !defined(SIGSTOP)
35
  error.SetErrorString("local host does not support signaling");
36
  return error;
37
#else
38
0
  return Signal(SIGSTOP);
39
0
#endif
40
0
}
41
42
0
Status NativeProcessProtocol::IgnoreSignals(llvm::ArrayRef<int> signals) {
43
0
  m_signals_to_ignore.clear();
44
0
  m_signals_to_ignore.insert(signals.begin(), signals.end());
45
0
  return Status();
46
0
}
47
48
lldb_private::Status
49
NativeProcessProtocol::GetMemoryRegionInfo(lldb::addr_t load_addr,
50
0
                                           MemoryRegionInfo &range_info) {
51
  // Default: not implemented.
52
0
  return Status("not implemented");
53
0
}
54
55
lldb_private::Status
56
NativeProcessProtocol::ReadMemoryTags(int32_t type, lldb::addr_t addr,
57
0
                                      size_t len, std::vector<uint8_t> &tags) {
58
0
  return Status("not implemented");
59
0
}
60
61
lldb_private::Status
62
NativeProcessProtocol::WriteMemoryTags(int32_t type, lldb::addr_t addr,
63
                                       size_t len,
64
0
                                       const std::vector<uint8_t> &tags) {
65
0
  return Status("not implemented");
66
0
}
67
68
0
llvm::Optional<WaitStatus> NativeProcessProtocol::GetExitStatus() {
69
0
  if (m_state == lldb::eStateExited)
70
0
    return m_exit_status;
71
72
0
  return llvm::None;
73
0
}
74
75
bool NativeProcessProtocol::SetExitStatus(WaitStatus status,
76
0
                                          bool bNotifyStateChange) {
77
0
  Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
78
0
  LLDB_LOG(log, "status = {0}, notify = {1}", status, bNotifyStateChange);
79
80
  // Exit status already set
81
0
  if (m_state == lldb::eStateExited) {
82
0
    if (m_exit_status)
83
0
      LLDB_LOG(log, "exit status already set to {0}", *m_exit_status);
84
0
    else
85
0
      LLDB_LOG(log, "state is exited, but status not set");
86
0
    return false;
87
0
  }
88
89
0
  m_state = lldb::eStateExited;
90
0
  m_exit_status = status;
91
92
0
  if (bNotifyStateChange)
93
0
    SynchronouslyNotifyProcessStateChanged(lldb::eStateExited);
94
95
0
  return true;
96
0
}
97
98
0
NativeThreadProtocol *NativeProcessProtocol::GetThreadAtIndex(uint32_t idx) {
99
0
  std::lock_guard<std::recursive_mutex> guard(m_threads_mutex);
100
0
  if (idx < m_threads.size())
101
0
    return m_threads[idx].get();
102
0
  return nullptr;
103
0
}
104
105
NativeThreadProtocol *
106
0
NativeProcessProtocol::GetThreadByIDUnlocked(lldb::tid_t tid) {
107
0
  for (const auto &thread : m_threads) {
108
0
    if (thread->GetID() == tid)
109
0
      return thread.get();
110
0
  }
111
0
  return nullptr;
112
0
}
113
114
0
NativeThreadProtocol *NativeProcessProtocol::GetThreadByID(lldb::tid_t tid) {
115
0
  std::lock_guard<std::recursive_mutex> guard(m_threads_mutex);
116
0
  return GetThreadByIDUnlocked(tid);
117
0
}
118
119
0
bool NativeProcessProtocol::IsAlive() const {
120
0
  return m_state != eStateDetached && m_state != eStateExited &&
121
0
         m_state != eStateInvalid && m_state != eStateUnloaded;
122
0
}
123
124
const NativeWatchpointList::WatchpointMap &
125
0
NativeProcessProtocol::GetWatchpointMap() const {
126
0
  return m_watchpoint_list.GetWatchpointMap();
127
0
}
128
129
llvm::Optional<std::pair<uint32_t, uint32_t>>
130
0
NativeProcessProtocol::GetHardwareDebugSupportInfo() const {
131
0
  Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
132
133
  // get any thread
134
0
  NativeThreadProtocol *thread(
135
0
      const_cast<NativeProcessProtocol *>(this)->GetThreadAtIndex(0));
136
0
  if (!thread) {
137
0
    LLDB_LOG(log, "failed to find a thread to grab a NativeRegisterContext!");
138
0
    return llvm::None;
139
0
  }
140
141
0
  NativeRegisterContext &reg_ctx = thread->GetRegisterContext();
142
0
  return std::make_pair(reg_ctx.NumSupportedHardwareBreakpoints(),
143
0
                        reg_ctx.NumSupportedHardwareWatchpoints());
144
0
}
145
146
Status NativeProcessProtocol::SetWatchpoint(lldb::addr_t addr, size_t size,
147
                                            uint32_t watch_flags,
148
0
                                            bool hardware) {
149
  // This default implementation assumes setting the watchpoint for the process
150
  // will require setting the watchpoint for each of the threads.  Furthermore,
151
  // it will track watchpoints set for the process and will add them to each
152
  // thread that is attached to via the (FIXME implement) OnThreadAttached ()
153
  // method.
154
155
0
  Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
156
157
  // Update the thread list
158
0
  UpdateThreads();
159
160
  // Keep track of the threads we successfully set the watchpoint for.  If one
161
  // of the thread watchpoint setting operations fails, back off and remove the
162
  // watchpoint for all the threads that were successfully set so we get back
163
  // to a consistent state.
164
0
  std::vector<NativeThreadProtocol *> watchpoint_established_threads;
165
166
  // Tell each thread to set a watchpoint.  In the event that hardware
167
  // watchpoints are requested but the SetWatchpoint fails, try to set a
168
  // software watchpoint as a fallback.  It's conceivable that if there are
169
  // more threads than hardware watchpoints available, some of the threads will
170
  // fail to set hardware watchpoints while software ones may be available.
171
0
  std::lock_guard<std::recursive_mutex> guard(m_threads_mutex);
172
0
  for (const auto &thread : m_threads) {
173
0
    assert(thread && "thread list should not have a NULL thread!");
174
175
0
    Status thread_error =
176
0
        thread->SetWatchpoint(addr, size, watch_flags, hardware);
177
0
    if (thread_error.Fail() && hardware) {
178
      // Try software watchpoints since we failed on hardware watchpoint
179
      // setting and we may have just run out of hardware watchpoints.
180
0
      thread_error = thread->SetWatchpoint(addr, size, watch_flags, false);
181
0
      if (thread_error.Success())
182
0
        LLDB_LOG(log,
183
0
                 "hardware watchpoint requested but software watchpoint set");
184
0
    }
185
186
0
    if (thread_error.Success()) {
187
      // Remember that we set this watchpoint successfully in case we need to
188
      // clear it later.
189
0
      watchpoint_established_threads.push_back(thread.get());
190
0
    } else {
191
      // Unset the watchpoint for each thread we successfully set so that we
192
      // get back to a consistent state of "not set" for the watchpoint.
193
0
      for (auto unwatch_thread_sp : watchpoint_established_threads) {
194
0
        Status remove_error = unwatch_thread_sp->RemoveWatchpoint(addr);
195
0
        if (remove_error.Fail())
196
0
          LLDB_LOG(log, "RemoveWatchpoint failed for pid={0}, tid={1}: {2}",
197
0
                   GetID(), unwatch_thread_sp->GetID(), remove_error);
198
0
      }
199
200
0
      return thread_error;
201
0
    }
202
0
  }
203
0
  return m_watchpoint_list.Add(addr, size, watch_flags, hardware);
204
0
}
205
206
0
Status NativeProcessProtocol::RemoveWatchpoint(lldb::addr_t addr) {
207
  // Update the thread list
208
0
  UpdateThreads();
209
210
0
  Status overall_error;
211
212
0
  std::lock_guard<std::recursive_mutex> guard(m_threads_mutex);
213
0
  for (const auto &thread : m_threads) {
214
0
    assert(thread && "thread list should not have a NULL thread!");
215
216
0
    const Status thread_error = thread->RemoveWatchpoint(addr);
217
0
    if (thread_error.Fail()) {
218
      // Keep track of the first thread error if any threads fail. We want to
219
      // try to remove the watchpoint from every thread, though, even if one or
220
      // more have errors.
221
0
      if (!overall_error.Fail())
222
0
        overall_error = thread_error;
223
0
    }
224
0
  }
225
0
  const Status error = m_watchpoint_list.Remove(addr);
226
0
  return overall_error.Fail() ? overall_error : error;
227
0
}
228
229
const HardwareBreakpointMap &
230
0
NativeProcessProtocol::GetHardwareBreakpointMap() const {
231
0
  return m_hw_breakpoints_map;
232
0
}
233
234
Status NativeProcessProtocol::SetHardwareBreakpoint(lldb::addr_t addr,
235
0
                                                    size_t size) {
236
  // This default implementation assumes setting a hardware breakpoint for this
237
  // process will require setting same hardware breakpoint for each of its
238
  // existing threads. New thread will do the same once created.
239
0
  Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
240
241
  // Update the thread list
242
0
  UpdateThreads();
243
244
  // Exit here if target does not have required hardware breakpoint capability.
245
0
  auto hw_debug_cap = GetHardwareDebugSupportInfo();
246
247
0
  if (hw_debug_cap == llvm::None || hw_debug_cap->first == 0 ||
248
0
      hw_debug_cap->first <= m_hw_breakpoints_map.size())
249
0
    return Status("Target does not have required no of hardware breakpoints");
250
251
  // Vector below stores all thread pointer for which we have we successfully
252
  // set this hardware breakpoint. If any of the current process threads fails
253
  // to set this hardware breakpoint then roll back and remove this breakpoint
254
  // for all the threads that had already set it successfully.
255
0
  std::vector<NativeThreadProtocol *> breakpoint_established_threads;
256
257
  // Request to set a hardware breakpoint for each of current process threads.
258
0
  std::lock_guard<std::recursive_mutex> guard(m_threads_mutex);
259
0
  for (const auto &thread : m_threads) {
260
0
    assert(thread && "thread list should not have a NULL thread!");
261
262
0
    Status thread_error = thread->SetHardwareBreakpoint(addr, size);
263
0
    if (thread_error.Success()) {
264
      // Remember that we set this breakpoint successfully in case we need to
265
      // clear it later.
266
0
      breakpoint_established_threads.push_back(thread.get());
267
0
    } else {
268
      // Unset the breakpoint for each thread we successfully set so that we
269
      // get back to a consistent state of "not set" for this hardware
270
      // breakpoint.
271
0
      for (auto rollback_thread_sp : breakpoint_established_threads) {
272
0
        Status remove_error =
273
0
            rollback_thread_sp->RemoveHardwareBreakpoint(addr);
274
0
        if (remove_error.Fail())
275
0
          LLDB_LOG(log,
276
0
                   "RemoveHardwareBreakpoint failed for pid={0}, tid={1}: {2}",
277
0
                   GetID(), rollback_thread_sp->GetID(), remove_error);
278
0
      }
279
280
0
      return thread_error;
281
0
    }
282
0
  }
283
284
  // Register new hardware breakpoint into hardware breakpoints map of current
285
  // process.
286
0
  m_hw_breakpoints_map[addr] = {addr, size};
287
288
0
  return Status();
289
0
}
290
291
0
Status NativeProcessProtocol::RemoveHardwareBreakpoint(lldb::addr_t addr) {
292
  // Update the thread list
293
0
  UpdateThreads();
294
295
0
  Status error;
296
297
0
  std::lock_guard<std::recursive_mutex> guard(m_threads_mutex);
298
0
  for (const auto &thread : m_threads) {
299
0
    assert(thread && "thread list should not have a NULL thread!");
300
0
    error = thread->RemoveHardwareBreakpoint(addr);
301
0
  }
302
303
  // Also remove from hardware breakpoint map of current process.
304
0
  m_hw_breakpoints_map.erase(addr);
305
306
0
  return error;
307
0
}
308
309
void NativeProcessProtocol::SynchronouslyNotifyProcessStateChanged(
310
0
    lldb::StateType state) {
311
0
  Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
312
313
0
  m_delegate.ProcessStateChanged(this, state);
314
315
0
  LLDB_LOG(log, "sent state notification [{0}] from process {1}", state,
316
0
           GetID());
317
0
}
318
319
0
void NativeProcessProtocol::NotifyDidExec() {
320
0
  Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
321
0
  LLDB_LOG(log, "process {0} exec()ed", GetID());
322
323
0
  m_delegate.DidExec(this);
324
0
}
325
326
Status NativeProcessProtocol::SetSoftwareBreakpoint(lldb::addr_t addr,
327
5
                                                    uint32_t size_hint) {
328
5
  Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
329
5
  LLDB_LOG(log, "addr = {0:x}, size_hint = {1}", addr, size_hint);
330
331
5
  auto it = m_software_breakpoints.find(addr);
332
5
  if (it != m_software_breakpoints.end()) {
333
0
    ++it->second.ref_count;
334
0
    return Status();
335
0
  }
336
5
  auto expected_bkpt = EnableSoftwareBreakpoint(addr, size_hint);
337
5
  if (!expected_bkpt)
338
3
    return Status(expected_bkpt.takeError());
339
340
2
  m_software_breakpoints.emplace(addr, std::move(*expected_bkpt));
341
2
  return Status();
342
5
}
343
344
0
Status NativeProcessProtocol::RemoveSoftwareBreakpoint(lldb::addr_t addr) {
345
0
  Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
346
0
  LLDB_LOG(log, "addr = {0:x}", addr);
347
0
  auto it = m_software_breakpoints.find(addr);
348
0
  if (it == m_software_breakpoints.end())
349
0
    return Status("Breakpoint not found.");
350
0
  assert(it->second.ref_count > 0);
351
0
  if (--it->second.ref_count > 0)
352
0
    return Status();
353
354
  // This is the last reference. Let's remove the breakpoint.
355
0
  Status error;
356
357
  // Clear a software breakpoint instruction
358
0
  llvm::SmallVector<uint8_t, 4> curr_break_op(
359
0
      it->second.breakpoint_opcodes.size(), 0);
360
361
  // Read the breakpoint opcode
362
0
  size_t bytes_read = 0;
363
0
  error =
364
0
      ReadMemory(addr, curr_break_op.data(), curr_break_op.size(), bytes_read);
365
0
  if (error.Fail() || bytes_read < curr_break_op.size()) {
366
0
    return Status("addr=0x%" PRIx64
367
0
                  ": tried to read %zu bytes but only read %zu",
368
0
                  addr, curr_break_op.size(), bytes_read);
369
0
  }
370
0
  const auto &saved = it->second.saved_opcodes;
371
  // Make sure the breakpoint opcode exists at this address
372
0
  if (makeArrayRef(curr_break_op) != it->second.breakpoint_opcodes) {
373
0
    if (curr_break_op != it->second.saved_opcodes)
374
0
      return Status("Original breakpoint trap is no longer in memory.");
375
0
    LLDB_LOG(log,
376
0
             "Saved opcodes ({0:@[x]}) have already been restored at {1:x}.",
377
0
             llvm::make_range(saved.begin(), saved.end()), addr);
378
0
  } else {
379
    // We found a valid breakpoint opcode at this address, now restore the
380
    // saved opcode.
381
0
    size_t bytes_written = 0;
382
0
    error = WriteMemory(addr, saved.data(), saved.size(), bytes_written);
383
0
    if (error.Fail() || bytes_written < saved.size()) {
384
0
      return Status("addr=0x%" PRIx64
385
0
                    ": tried to write %zu bytes but only wrote %zu",
386
0
                    addr, saved.size(), bytes_written);
387
0
    }
388
389
    // Verify that our original opcode made it back to the inferior
390
0
    llvm::SmallVector<uint8_t, 4> verify_opcode(saved.size(), 0);
391
0
    size_t verify_bytes_read = 0;
392
0
    error = ReadMemory(addr, verify_opcode.data(), verify_opcode.size(),
393
0
                       verify_bytes_read);
394
0
    if (error.Fail() || verify_bytes_read < verify_opcode.size()) {
395
0
      return Status("addr=0x%" PRIx64
396
0
                    ": tried to read %zu verification bytes but only read %zu",
397
0
                    addr, verify_opcode.size(), verify_bytes_read);
398
0
    }
399
0
    if (verify_opcode != saved)
400
0
      LLDB_LOG(log, "Restoring bytes at {0:x}: {1:@[x]}", addr,
401
0
               llvm::make_range(saved.begin(), saved.end()));
402
0
  }
403
404
0
  m_software_breakpoints.erase(it);
405
0
  return Status();
406
0
}
407
408
llvm::Expected<NativeProcessProtocol::SoftwareBreakpoint>
409
NativeProcessProtocol::EnableSoftwareBreakpoint(lldb::addr_t addr,
410
5
                                                uint32_t size_hint) {
411
5
  Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
412
413
5
  auto expected_trap = GetSoftwareBreakpointTrapOpcode(size_hint);
414
5
  if (!expected_trap)
415
0
    return expected_trap.takeError();
416
417
5
  llvm::SmallVector<uint8_t, 4> saved_opcode_bytes(expected_trap->size(), 0);
418
  // Save the original opcodes by reading them so we can restore later.
419
5
  size_t bytes_read = 0;
420
5
  Status error = ReadMemory(addr, saved_opcode_bytes.data(),
421
5
                            saved_opcode_bytes.size(), bytes_read);
422
5
  if (error.Fail())
423
1
    return error.ToError();
424
425
  // Ensure we read as many bytes as we expected.
426
4
  if (bytes_read != saved_opcode_bytes.size()) {
427
0
    return llvm::createStringError(
428
0
        llvm::inconvertibleErrorCode(),
429
0
        "Failed to read memory while attempting to set breakpoint: attempted "
430
0
        "to read {0} bytes but only read {1}.",
431
0
        saved_opcode_bytes.size(), bytes_read);
432
0
  }
433
434
4
  LLDB_LOG(
435
4
      log, "Overwriting bytes at {0:x}: {1:@[x]}", addr,
436
4
      llvm::make_range(saved_opcode_bytes.begin(), saved_opcode_bytes.end()));
437
438
  // Write a software breakpoint in place of the original opcode.
439
4
  size_t bytes_written = 0;
440
4
  error = WriteMemory(addr, expected_trap->data(), expected_trap->size(),
441
4
                      bytes_written);
442
4
  if (error.Fail())
443
1
    return error.ToError();
444
445
  // Ensure we wrote as many bytes as we expected.
446
3
  if (bytes_written != expected_trap->size()) {
447
0
    return llvm::createStringError(
448
0
        llvm::inconvertibleErrorCode(),
449
0
        "Failed write memory while attempting to set "
450
0
        "breakpoint: attempted to write {0} bytes but only wrote {1}",
451
0
        expected_trap->size(), bytes_written);
452
0
  }
453
454
3
  llvm::SmallVector<uint8_t, 4> verify_bp_opcode_bytes(expected_trap->size(),
455
3
                                                       0);
456
3
  size_t verify_bytes_read = 0;
457
3
  error = ReadMemory(addr, verify_bp_opcode_bytes.data(),
458
3
                     verify_bp_opcode_bytes.size(), verify_bytes_read);
459
3
  if (error.Fail())
460
1
    return error.ToError();
461
462
  // Ensure we read as many verification bytes as we expected.
463
2
  if (verify_bytes_read != verify_bp_opcode_bytes.size()) {
464
0
    return llvm::createStringError(
465
0
        llvm::inconvertibleErrorCode(),
466
0
        "Failed to read memory while "
467
0
        "attempting to verify breakpoint: attempted to read {0} bytes "
468
0
        "but only read {1}",
469
0
        verify_bp_opcode_bytes.size(), verify_bytes_read);
470
0
  }
471
472
2
  if (llvm::makeArrayRef(verify_bp_opcode_bytes.data(), verify_bytes_read) !=
473
2
      *expected_trap) {
474
0
    return llvm::createStringError(
475
0
        llvm::inconvertibleErrorCode(),
476
0
        "Verification of software breakpoint "
477
0
        "writing failed - trap opcodes not successfully read back "
478
0
        "after writing when setting breakpoint at {0:x}",
479
0
        addr);
480
0
  }
481
482
2
  LLDB_LOG(log, "addr = {0:x}: SUCCESS", addr);
483
2
  return SoftwareBreakpoint{1, saved_opcode_bytes, *expected_trap};
484
2
}
485
486
llvm::Expected<llvm::ArrayRef<uint8_t>>
487
8
NativeProcessProtocol::GetSoftwareBreakpointTrapOpcode(size_t size_hint) {
488
8
  static const uint8_t g_aarch64_opcode[] = {0x00, 0x00, 0x20, 0xd4};
489
8
  static const uint8_t g_i386_opcode[] = {0xCC};
490
8
  static const uint8_t g_mips64_opcode[] = {0x00, 0x00, 0x00, 0x0d};
491
8
  static const uint8_t g_mips64el_opcode[] = {0x0d, 0x00, 0x00, 0x00};
492
8
  static const uint8_t g_s390x_opcode[] = {0x00, 0x01};
493
8
  static const uint8_t g_ppc_opcode[] = {0x7f, 0xe0, 0x00, 0x08}; // trap
494
8
  static const uint8_t g_ppcle_opcode[] = {0x08, 0x00, 0xe0, 0x7f}; // trap
495
496
8
  switch (GetArchitecture().GetMachine()) {
497
1
  case llvm::Triple::aarch64:
498
1
  case llvm::Triple::aarch64_32:
499
1
    return llvm::makeArrayRef(g_aarch64_opcode);
500
501
0
  case llvm::Triple::x86:
502
7
  case llvm::Triple::x86_64:
503
7
    return llvm::makeArrayRef(g_i386_opcode);
504
505
0
  case llvm::Triple::mips:
506
0
  case llvm::Triple::mips64:
507
0
    return llvm::makeArrayRef(g_mips64_opcode);
508
509
0
  case llvm::Triple::mipsel:
510
0
  case llvm::Triple::mips64el:
511
0
    return llvm::makeArrayRef(g_mips64el_opcode);
512
513
0
  case llvm::Triple::systemz:
514
0
    return llvm::makeArrayRef(g_s390x_opcode);
515
516
0
  case llvm::Triple::ppc:
517
0
  case llvm::Triple::ppc64:
518
0
    return llvm::makeArrayRef(g_ppc_opcode);
519
520
0
  case llvm::Triple::ppc64le:
521
0
    return llvm::makeArrayRef(g_ppcle_opcode);
522
523
0
  default:
524
0
    return llvm::createStringError(llvm::inconvertibleErrorCode(),
525
0
                                   "CPU type not supported!");
526
8
  }
527
8
}
528
529
0
size_t NativeProcessProtocol::GetSoftwareBreakpointPCOffset() {
530
0
  switch (GetArchitecture().GetMachine()) {
531
0
  case llvm::Triple::x86:
532
0
  case llvm::Triple::x86_64:
533
0
  case llvm::Triple::systemz:
534
    // These architectures report increment the PC after breakpoint is hit.
535
0
    return cantFail(GetSoftwareBreakpointTrapOpcode(0)).size();
536
537
0
  case llvm::Triple::arm:
538
0
  case llvm::Triple::aarch64:
539
0
  case llvm::Triple::aarch64_32:
540
0
  case llvm::Triple::mips64:
541
0
  case llvm::Triple::mips64el:
542
0
  case llvm::Triple::mips:
543
0
  case llvm::Triple::mipsel:
544
0
  case llvm::Triple::ppc:
545
0
  case llvm::Triple::ppc64:
546
0
  case llvm::Triple::ppc64le:
547
    // On these architectures the PC doesn't get updated for breakpoint hits.
548
0
    return 0;
549
550
0
  default:
551
0
    llvm_unreachable("CPU type not supported!");
552
0
  }
553
0
}
554
555
void NativeProcessProtocol::FixupBreakpointPCAsNeeded(
556
0
    NativeThreadProtocol &thread) {
557
0
  Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS);
558
559
0
  Status error;
560
561
  // Find out the size of a breakpoint (might depend on where we are in the
562
  // code).
563
0
  NativeRegisterContext &context = thread.GetRegisterContext();
564
565
0
  uint32_t breakpoint_size = GetSoftwareBreakpointPCOffset();
566
0
  LLDB_LOG(log, "breakpoint size: {0}", breakpoint_size);
567
0
  if (breakpoint_size == 0)
568
0
    return;
569
570
  // First try probing for a breakpoint at a software breakpoint location: PC -
571
  // breakpoint size.
572
0
  const lldb::addr_t initial_pc_addr = context.GetPCfromBreakpointLocation();
573
0
  lldb::addr_t breakpoint_addr = initial_pc_addr;
574
  // Do not allow breakpoint probe to wrap around.
575
0
  if (breakpoint_addr >= breakpoint_size)
576
0
    breakpoint_addr -= breakpoint_size;
577
578
0
  if (m_software_breakpoints.count(breakpoint_addr) == 0) {
579
    // We didn't find one at a software probe location.  Nothing to do.
580
0
    LLDB_LOG(log,
581
0
             "pid {0} no lldb software breakpoint found at current pc with "
582
0
             "adjustment: {1}",
583
0
             GetID(), breakpoint_addr);
584
0
    return;
585
0
  }
586
587
  //
588
  // We have a software breakpoint and need to adjust the PC.
589
  //
590
591
  // Change the program counter.
592
0
  LLDB_LOG(log, "pid {0} tid {1}: changing PC from {2:x} to {3:x}", GetID(),
593
0
           thread.GetID(), initial_pc_addr, breakpoint_addr);
594
595
0
  error = context.SetPC(breakpoint_addr);
596
0
  if (error.Fail()) {
597
    // This can happen in case the process was killed between the time we read
598
    // the PC and when we are updating it. There's nothing better to do than to
599
    // swallow the error.
600
0
    LLDB_LOG(log, "pid {0} tid {1}: failed to set PC: {2}", GetID(),
601
0
             thread.GetID(), error);
602
0
  }
603
0
}
604
605
Status NativeProcessProtocol::RemoveBreakpoint(lldb::addr_t addr,
606
0
                                               bool hardware) {
607
0
  if (hardware)
608
0
    return RemoveHardwareBreakpoint(addr);
609
0
  else
610
0
    return RemoveSoftwareBreakpoint(addr);
611
0
}
612
613
Status NativeProcessProtocol::ReadMemoryWithoutTrap(lldb::addr_t addr,
614
                                                    void *buf, size_t size,
615
5
                                                    size_t &bytes_read) {
616
5
  Status error = ReadMemory(addr, buf, size, bytes_read);
617
5
  if (error.Fail())
618
0
    return error;
619
620
5
  auto data =
621
5
      llvm::makeMutableArrayRef(static_cast<uint8_t *>(buf), bytes_read);
622
5
  for (const auto &pair : m_software_breakpoints) {
623
5
    lldb::addr_t bp_addr = pair.first;
624
5
    auto saved_opcodes = makeArrayRef(pair.second.saved_opcodes);
625
626
5
    if (bp_addr + saved_opcodes.size() < addr || addr + bytes_read <= bp_addr)
627
0
      continue; // Breakpoint not in range, ignore
628
629
5
    if (bp_addr < addr) {
630
2
      saved_opcodes = saved_opcodes.drop_front(addr - bp_addr);
631
2
      bp_addr = addr;
632
2
    }
633
5
    auto bp_data = data.drop_front(bp_addr - addr);
634
5
    std::copy_n(saved_opcodes.begin(),
635
5
                std::min(saved_opcodes.size(), bp_data.size()),
636
5
                bp_data.begin());
637
5
  }
638
5
  return Status();
639
5
}
640
641
llvm::Expected<llvm::StringRef>
642
NativeProcessProtocol::ReadCStringFromMemory(lldb::addr_t addr, char *buffer,
643
                                             size_t max_size,
644
3
                                             size_t &total_bytes_read) {
645
3
  static const size_t cache_line_size =
646
3
      llvm::sys::Process::getPageSizeEstimate();
647
3
  size_t bytes_read = 0;
648
3
  size_t bytes_left = max_size;
649
3
  addr_t curr_addr = addr;
650
3
  size_t string_size;
651
3
  char *curr_buffer = buffer;
652
3
  total_bytes_read = 0;
653
3
  Status status;
654
655
5
  while (bytes_left > 0 && 
status.Success()4
) {
656
4
    addr_t cache_line_bytes_left =
657
4
        cache_line_size - (curr_addr % cache_line_size);
658
4
    addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
659
4
    status = ReadMemory(curr_addr, static_cast<void *>(curr_buffer),
660
4
                        bytes_to_read, bytes_read);
661
662
4
    if (bytes_read == 0)
663
0
      break;
664
665
4
    void *str_end = std::memchr(curr_buffer, '\0', bytes_read);
666
4
    if (str_end != nullptr) {
667
2
      total_bytes_read =
668
2
          static_cast<size_t>((static_cast<char *>(str_end) - buffer + 1));
669
2
      status.Clear();
670
2
      break;
671
2
    }
672
673
2
    total_bytes_read += bytes_read;
674
2
    curr_buffer += bytes_read;
675
2
    curr_addr += bytes_read;
676
2
    bytes_left -= bytes_read;
677
2
  }
678
679
3
  string_size = total_bytes_read - 1;
680
681
  // Make sure we return a null terminated string.
682
3
  if (bytes_left == 0 && 
max_size > 01
&&
buffer[max_size - 1] != '\0'1
) {
683
1
    buffer[max_size - 1] = '\0';
684
1
    total_bytes_read--;
685
1
  }
686
687
3
  if (!status.Success())
688
0
    return status.ToError();
689
690
3
  return llvm::StringRef(buffer, string_size);
691
3
}
692
693
0
lldb::StateType NativeProcessProtocol::GetState() const {
694
0
  std::lock_guard<std::recursive_mutex> guard(m_state_mutex);
695
0
  return m_state;
696
0
}
697
698
void NativeProcessProtocol::SetState(lldb::StateType state,
699
0
                                     bool notify_delegates) {
700
0
  std::lock_guard<std::recursive_mutex> guard(m_state_mutex);
701
702
0
  if (state == m_state)
703
0
    return;
704
705
0
  m_state = state;
706
707
0
  if (StateIsStoppedState(state, false)) {
708
0
    ++m_stop_id;
709
710
    // Give process a chance to do any stop id bump processing, such as
711
    // clearing cached data that is invalidated each time the process runs.
712
    // Note if/when we support some threads running, we'll end up needing to
713
    // manage this per thread and per process.
714
0
    DoStopIDBumped(m_stop_id);
715
0
  }
716
717
  // Optionally notify delegates of the state change.
718
0
  if (notify_delegates)
719
0
    SynchronouslyNotifyProcessStateChanged(state);
720
0
}
721
722
0
uint32_t NativeProcessProtocol::GetStopID() const {
723
0
  std::lock_guard<std::recursive_mutex> guard(m_state_mutex);
724
0
  return m_stop_id;
725
0
}
726
727
0
void NativeProcessProtocol::DoStopIDBumped(uint32_t /* newBumpId */) {
728
  // Default implementation does nothing.
729
0
}
730
731
0
NativeProcessProtocol::Factory::~Factory() = default;