Coverage Report

Created: 2022-01-18 06:27

/Users/buildslave/jenkins/workspace/coverage/llvm-project/lldb/include/lldb/Host/common/NativeProcessProtocol.h
Line
Count
Source (jump to first uncovered line)
1
//===-- NativeProcessProtocol.h ---------------------------------*- C++ -*-===//
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
#ifndef LLDB_HOST_COMMON_NATIVEPROCESSPROTOCOL_H
10
#define LLDB_HOST_COMMON_NATIVEPROCESSPROTOCOL_H
11
12
#include "NativeBreakpointList.h"
13
#include "NativeThreadProtocol.h"
14
#include "NativeWatchpointList.h"
15
#include "lldb/Host/Host.h"
16
#include "lldb/Host/MainLoop.h"
17
#include "lldb/Utility/ArchSpec.h"
18
#include "lldb/Utility/Status.h"
19
#include "lldb/Utility/TraceGDBRemotePackets.h"
20
#include "lldb/Utility/UnimplementedError.h"
21
#include "lldb/lldb-private-forward.h"
22
#include "lldb/lldb-types.h"
23
#include "llvm/ADT/ArrayRef.h"
24
#include "llvm/ADT/DenseSet.h"
25
#include "llvm/ADT/StringRef.h"
26
#include "llvm/Support/Error.h"
27
#include "llvm/Support/MemoryBuffer.h"
28
#include <mutex>
29
#include <unordered_map>
30
#include <vector>
31
32
namespace lldb_private {
33
LLVM_ENABLE_BITMASK_ENUMS_IN_NAMESPACE();
34
35
class MemoryRegionInfo;
36
class ResumeActionList;
37
38
struct SVR4LibraryInfo {
39
  std::string name;
40
  lldb::addr_t link_map;
41
  lldb::addr_t base_addr;
42
  lldb::addr_t ld_addr;
43
  lldb::addr_t next;
44
};
45
46
// NativeProcessProtocol
47
class NativeProcessProtocol {
48
public:
49
  virtual ~NativeProcessProtocol() = default;
50
51
  virtual Status Resume(const ResumeActionList &resume_actions) = 0;
52
53
  virtual Status Halt() = 0;
54
55
  virtual Status Detach() = 0;
56
57
  /// Sends a process a UNIX signal \a signal.
58
  ///
59
  /// \return
60
  ///     Returns an error object.
61
  virtual Status Signal(int signo) = 0;
62
63
  /// Tells a process to interrupt all operations as if by a Ctrl-C.
64
  ///
65
  /// The default implementation will send a local host's equivalent of
66
  /// a SIGSTOP to the process via the NativeProcessProtocol::Signal()
67
  /// operation.
68
  ///
69
  /// \return
70
  ///     Returns an error object.
71
  virtual Status Interrupt();
72
73
  virtual Status Kill() = 0;
74
75
  // Tells a process not to stop the inferior on given signals and just
76
  // reinject them back.
77
  virtual Status IgnoreSignals(llvm::ArrayRef<int> signals);
78
79
  // Memory and memory region functions
80
81
  virtual Status GetMemoryRegionInfo(lldb::addr_t load_addr,
82
                                     MemoryRegionInfo &range_info);
83
84
  virtual Status ReadMemory(lldb::addr_t addr, void *buf, size_t size,
85
                            size_t &bytes_read) = 0;
86
87
  Status ReadMemoryWithoutTrap(lldb::addr_t addr, void *buf, size_t size,
88
                               size_t &bytes_read);
89
90
  virtual Status ReadMemoryTags(int32_t type, lldb::addr_t addr, size_t len,
91
                                std::vector<uint8_t> &tags);
92
93
  virtual Status WriteMemoryTags(int32_t type, lldb::addr_t addr, size_t len,
94
                                 const std::vector<uint8_t> &tags);
95
96
  /// Reads a null terminated string from memory.
97
  ///
98
  /// Reads up to \p max_size bytes of memory until it finds a '\0'.
99
  /// If a '\0' is not found then it reads max_size-1 bytes as a string and a
100
  /// '\0' is added as the last character of the \p buffer.
101
  ///
102
  /// \param[in] addr
103
  ///     The address in memory to read from.
104
  ///
105
  /// \param[in] buffer
106
  ///     An allocated buffer with at least \p max_size size.
107
  ///
108
  /// \param[in] max_size
109
  ///     The maximum number of bytes to read from memory until it reads the
110
  ///     string.
111
  ///
112
  /// \param[out] total_bytes_read
113
  ///     The number of bytes read from memory into \p buffer.
114
  ///
115
  /// \return
116
  ///     Returns a StringRef backed up by the \p buffer passed in.
117
  llvm::Expected<llvm::StringRef>
118
  ReadCStringFromMemory(lldb::addr_t addr, char *buffer, size_t max_size,
119
                        size_t &total_bytes_read);
120
121
  virtual Status WriteMemory(lldb::addr_t addr, const void *buf, size_t size,
122
                             size_t &bytes_written) = 0;
123
124
  virtual llvm::Expected<lldb::addr_t> AllocateMemory(size_t size,
125
0
                                                      uint32_t permissions) {
126
0
    return llvm::make_error<UnimplementedError>();
127
0
  }
128
129
0
  virtual llvm::Error DeallocateMemory(lldb::addr_t addr) {
130
0
    return llvm::make_error<UnimplementedError>();
131
0
  }
132
133
  virtual lldb::addr_t GetSharedLibraryInfoAddress() = 0;
134
135
  virtual llvm::Expected<std::vector<SVR4LibraryInfo>>
136
0
  GetLoadedSVR4Libraries() {
137
0
    return llvm::createStringError(llvm::inconvertibleErrorCode(),
138
0
                                   "Not implemented");
139
0
  }
140
141
  virtual bool IsAlive() const;
142
143
  virtual size_t UpdateThreads() = 0;
144
145
  virtual const ArchSpec &GetArchitecture() const = 0;
146
147
  // Breakpoint functions
148
  virtual Status SetBreakpoint(lldb::addr_t addr, uint32_t size,
149
                               bool hardware) = 0;
150
151
  virtual Status RemoveBreakpoint(lldb::addr_t addr, bool hardware = false);
152
153
  // Hardware Breakpoint functions
154
  virtual const HardwareBreakpointMap &GetHardwareBreakpointMap() const;
155
156
  virtual Status SetHardwareBreakpoint(lldb::addr_t addr, size_t size);
157
158
  virtual Status RemoveHardwareBreakpoint(lldb::addr_t addr);
159
160
  // Watchpoint functions
161
  virtual const NativeWatchpointList::WatchpointMap &GetWatchpointMap() const;
162
163
  virtual llvm::Optional<std::pair<uint32_t, uint32_t>>
164
  GetHardwareDebugSupportInfo() const;
165
166
  virtual Status SetWatchpoint(lldb::addr_t addr, size_t size,
167
                               uint32_t watch_flags, bool hardware);
168
169
  virtual Status RemoveWatchpoint(lldb::addr_t addr);
170
171
  // Accessors
172
0
  lldb::pid_t GetID() const { return m_pid; }
173
174
  lldb::StateType GetState() const;
175
176
0
  bool IsRunning() const {
177
0
    return m_state == lldb::eStateRunning || IsStepping();
178
0
  }
179
180
0
  bool IsStepping() const { return m_state == lldb::eStateStepping; }
181
182
0
  bool CanResume() const { return m_state == lldb::eStateStopped; }
183
184
0
  lldb::ByteOrder GetByteOrder() const {
185
0
    return GetArchitecture().GetByteOrder();
186
0
  }
187
188
0
  uint32_t GetAddressByteSize() const {
189
0
    return GetArchitecture().GetAddressByteSize();
190
0
  }
191
192
  virtual llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
193
  GetAuxvData() const = 0;
194
195
  // Exit Status
196
  virtual llvm::Optional<WaitStatus> GetExitStatus();
197
198
  virtual bool SetExitStatus(WaitStatus status, bool bNotifyStateChange);
199
200
  // Access to threads
201
  NativeThreadProtocol *GetThreadAtIndex(uint32_t idx);
202
203
  NativeThreadProtocol *GetThreadByID(lldb::tid_t tid);
204
205
0
  void SetCurrentThreadID(lldb::tid_t tid) { m_current_thread_id = tid; }
206
207
0
  lldb::tid_t GetCurrentThreadID() const { return m_current_thread_id; }
208
209
0
  NativeThreadProtocol *GetCurrentThread() {
210
0
    return GetThreadByID(m_current_thread_id);
211
0
  }
212
213
  // Access to inferior stdio
214
0
  virtual int GetTerminalFileDescriptor() { return m_terminal_fd; }
215
216
  // Stop id interface
217
218
  uint32_t GetStopID() const;
219
220
  // Callbacks for low-level process state changes
221
  class NativeDelegate {
222
  public:
223
8
    virtual ~NativeDelegate() = default;
224
225
    virtual void InitializeDelegate(NativeProcessProtocol *process) = 0;
226
227
    virtual void ProcessStateChanged(NativeProcessProtocol *process,
228
                                     lldb::StateType state) = 0;
229
230
    virtual void DidExec(NativeProcessProtocol *process) = 0;
231
232
    virtual void
233
    NewSubprocess(NativeProcessProtocol *parent_process,
234
                  std::unique_ptr<NativeProcessProtocol> child_process) = 0;
235
  };
236
237
  virtual Status GetLoadedModuleFileSpec(const char *module_path,
238
                                         FileSpec &file_spec) = 0;
239
240
  virtual Status GetFileLoadAddress(const llvm::StringRef &file_name,
241
                                    lldb::addr_t &load_addr) = 0;
242
243
  /// Extension flag constants, returned by Factory::GetSupportedExtensions()
244
  /// and passed to SetEnabledExtension()
245
  enum class Extension {
246
    multiprocess = (1u << 0),
247
    fork = (1u << 1),
248
    vfork = (1u << 2),
249
    pass_signals = (1u << 3),
250
    auxv = (1u << 4),
251
    libraries_svr4 = (1u << 5),
252
    memory_tagging = (1u << 6),
253
    savecore = (1u << 7),
254
    siginfo_read = (1u << 8),
255
256
    LLVM_MARK_AS_BITMASK_ENUM(siginfo_read)
257
  };
258
259
  class Factory {
260
  public:
261
    virtual ~Factory();
262
    /// Launch a process for debugging.
263
    ///
264
    /// \param[in] launch_info
265
    ///     Information required to launch the process.
266
    ///
267
    /// \param[in] native_delegate
268
    ///     The delegate that will receive messages regarding the
269
    ///     inferior.  Must outlive the NativeProcessProtocol
270
    ///     instance.
271
    ///
272
    /// \param[in] mainloop
273
    ///     The mainloop instance with which the process can register
274
    ///     callbacks. Must outlive the NativeProcessProtocol
275
    ///     instance.
276
    ///
277
    /// \return
278
    ///     A NativeProcessProtocol shared pointer if the operation succeeded or
279
    ///     an error object if it failed.
280
    virtual llvm::Expected<std::unique_ptr<NativeProcessProtocol>>
281
    Launch(ProcessLaunchInfo &launch_info, NativeDelegate &native_delegate,
282
           MainLoop &mainloop) const = 0;
283
284
    /// Attach to an existing process.
285
    ///
286
    /// \param[in] pid
287
    ///     pid of the process locatable
288
    ///
289
    /// \param[in] native_delegate
290
    ///     The delegate that will receive messages regarding the
291
    ///     inferior.  Must outlive the NativeProcessProtocol
292
    ///     instance.
293
    ///
294
    /// \param[in] mainloop
295
    ///     The mainloop instance with which the process can register
296
    ///     callbacks. Must outlive the NativeProcessProtocol
297
    ///     instance.
298
    ///
299
    /// \return
300
    ///     A NativeProcessProtocol shared pointer if the operation succeeded or
301
    ///     an error object if it failed.
302
    virtual llvm::Expected<std::unique_ptr<NativeProcessProtocol>>
303
    Attach(lldb::pid_t pid, NativeDelegate &native_delegate,
304
           MainLoop &mainloop) const = 0;
305
306
    /// Get the bitmask of extensions supported by this process plugin.
307
    ///
308
    /// \return
309
    ///     A NativeProcessProtocol::Extension bitmask.
310
0
    virtual Extension GetSupportedExtensions() const { return {}; }
311
  };
312
313
  /// Start tracing a process or its threads.
314
  ///
315
  /// \param[in] json_params
316
  ///     JSON object with the information of what and how to trace.
317
  ///     In the case of gdb-remote, this object should conform to the
318
  ///     jLLDBTraceStart packet.
319
  ///
320
  ///     This object should have a string entry called "type", which is the
321
  ///     tracing technology name.
322
  ///
323
  /// \param[in] type
324
  ///     Tracing technology type, as described in the \a json_params.
325
  ///
326
  /// \return
327
  ///     \a llvm::Error::success if the operation was successful, or an
328
  ///     \a llvm::Error otherwise.
329
  virtual llvm::Error TraceStart(llvm::StringRef json_params,
330
0
                                 llvm::StringRef type) {
331
0
    return llvm::createStringError(llvm::inconvertibleErrorCode(),
332
0
                                   "Unsupported tracing type '%s'",
333
0
                                   type.data());
334
0
  }
335
336
  /// \copydoc Process::TraceStop(const TraceStopRequest &)
337
0
  virtual llvm::Error TraceStop(const TraceStopRequest &request) {
338
0
    return llvm::createStringError(llvm::inconvertibleErrorCode(),
339
0
                                   "Unsupported tracing type '%s'",
340
0
                                   request.type.data());
341
0
  }
342
343
  /// \copydoc Process::TraceGetState(llvm::StringRef type)
344
  virtual llvm::Expected<llvm::json::Value>
345
0
  TraceGetState(llvm::StringRef type) {
346
0
    return llvm::createStringError(llvm::inconvertibleErrorCode(),
347
0
                                   "Unsupported tracing type '%s'",
348
0
                                   type.data());
349
0
  }
350
351
  /// \copydoc Process::TraceGetBinaryData(const TraceGetBinaryDataRequest &)
352
  virtual llvm::Expected<std::vector<uint8_t>>
353
0
  TraceGetBinaryData(const TraceGetBinaryDataRequest &request) {
354
0
    return llvm::createStringError(
355
0
        llvm::inconvertibleErrorCode(),
356
0
        "Unsupported data kind '%s' for the '%s' tracing technology",
357
0
        request.kind.c_str(), request.type.c_str());
358
0
  }
359
360
  /// \copydoc Process::TraceSupported()
361
0
  virtual llvm::Expected<TraceSupportedResponse> TraceSupported() {
362
0
    return llvm::make_error<UnimplementedError>();
363
0
  }
364
365
  /// Method called in order to propagate the bitmap of protocol
366
  /// extensions supported by the client.
367
  ///
368
  /// \param[in] flags
369
  ///     The bitmap of enabled extensions.
370
0
  virtual void SetEnabledExtensions(Extension flags) {
371
0
    m_enabled_extensions = flags;
372
0
  }
373
374
  /// Write a core dump (without crashing the program).
375
  ///
376
  /// \param[in] path_hint
377
  ///     Suggested core dump path (optional, can be empty).
378
  ///
379
  /// \return
380
  ///     Path to the core dump if successfully written, an error
381
  ///     otherwise.
382
0
  virtual llvm::Expected<std::string> SaveCore(llvm::StringRef path_hint) {
383
0
    return llvm::createStringError(llvm::inconvertibleErrorCode(),
384
0
                                   "Not implemented");
385
0
  }
386
387
protected:
388
  struct SoftwareBreakpoint {
389
    uint32_t ref_count;
390
    llvm::SmallVector<uint8_t, 4> saved_opcodes;
391
    llvm::ArrayRef<uint8_t> breakpoint_opcodes;
392
  };
393
394
  std::unordered_map<lldb::addr_t, SoftwareBreakpoint> m_software_breakpoints;
395
  lldb::pid_t m_pid;
396
397
  std::vector<std::unique_ptr<NativeThreadProtocol>> m_threads;
398
  lldb::tid_t m_current_thread_id = LLDB_INVALID_THREAD_ID;
399
  mutable std::recursive_mutex m_threads_mutex;
400
401
  lldb::StateType m_state = lldb::eStateInvalid;
402
  mutable std::recursive_mutex m_state_mutex;
403
404
  llvm::Optional<WaitStatus> m_exit_status;
405
406
  NativeDelegate &m_delegate;
407
  NativeWatchpointList m_watchpoint_list;
408
  HardwareBreakpointMap m_hw_breakpoints_map;
409
  int m_terminal_fd;
410
  uint32_t m_stop_id = 0;
411
412
  // Set of signal numbers that LLDB directly injects back to inferior without
413
  // stopping it.
414
  llvm::DenseSet<int> m_signals_to_ignore;
415
416
  // Extensions enabled per the last SetEnabledExtensions() call.
417
  Extension m_enabled_extensions;
418
419
  // lldb_private::Host calls should be used to launch a process for debugging,
420
  // and then the process should be attached to. When attaching to a process
421
  // lldb_private::Host calls should be used to locate the process to attach
422
  // to, and then this function should be called.
423
  NativeProcessProtocol(lldb::pid_t pid, int terminal_fd,
424
                        NativeDelegate &delegate);
425
426
0
  void SetID(lldb::pid_t pid) { m_pid = pid; }
427
428
  // interface for state handling
429
  void SetState(lldb::StateType state, bool notify_delegates = true);
430
431
  // Derived classes need not implement this.  It can be used as a hook to
432
  // clear internal caches that should be invalidated when stop ids change.
433
  //
434
  // Note this function is called with the state mutex obtained by the caller.
435
  virtual void DoStopIDBumped(uint32_t newBumpId);
436
437
  // interface for software breakpoints
438
439
  Status SetSoftwareBreakpoint(lldb::addr_t addr, uint32_t size_hint);
440
  Status RemoveSoftwareBreakpoint(lldb::addr_t addr);
441
442
  virtual llvm::Expected<llvm::ArrayRef<uint8_t>>
443
  GetSoftwareBreakpointTrapOpcode(size_t size_hint);
444
445
  /// Return the offset of the PC relative to the software breakpoint that was hit. If an
446
  /// architecture (e.g. arm) reports breakpoint hits before incrementing the PC, this offset
447
  /// will be 0. If an architecture (e.g. intel) reports breakpoints hits after incrementing the
448
  /// PC, this offset will be the size of the breakpoint opcode.
449
  virtual size_t GetSoftwareBreakpointPCOffset();
450
451
  // Adjust the thread's PC after hitting a software breakpoint. On
452
  // architectures where the PC points after the breakpoint instruction, this
453
  // resets it to point to the breakpoint itself.
454
  void FixupBreakpointPCAsNeeded(NativeThreadProtocol &thread);
455
456
  /// Notify the delegate that an exec occurred.
457
  ///
458
  /// Provide a mechanism for a delegate to clear out any exec-
459
  /// sensitive data.
460
  void NotifyDidExec();
461
462
  NativeThreadProtocol *GetThreadByIDUnlocked(lldb::tid_t tid);
463
464
private:
465
  void SynchronouslyNotifyProcessStateChanged(lldb::StateType state);
466
  llvm::Expected<SoftwareBreakpoint>
467
  EnableSoftwareBreakpoint(lldb::addr_t addr, uint32_t size_hint);
468
};
469
} // namespace lldb_private
470
471
#endif // LLDB_HOST_COMMON_NATIVEPROCESSPROTOCOL_H