1 //===-- NativeRegisterContext.cpp -------------------------*- 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 #include "lldb/Host/common/NativeRegisterContext.h"
10 
11 #include "lldb/Utility/Log.h"
12 #include "lldb/Utility/RegisterValue.h"
13 
14 #include "lldb/Host/PosixApi.h"
15 #include "lldb/Host/common/NativeProcessProtocol.h"
16 #include "lldb/Host/common/NativeThreadProtocol.h"
17 
18 using namespace lldb;
19 using namespace lldb_private;
20 
21 NativeRegisterContext::NativeRegisterContext(NativeThreadProtocol &thread)
22     : m_thread(thread) {}
23 
24 //----------------------------------------------------------------------
25 // Destructor
26 //----------------------------------------------------------------------
27 NativeRegisterContext::~NativeRegisterContext() {}
28 
29 // FIXME revisit invalidation, process stop ids, etc.  Right now we don't
30 // support caching in NativeRegisterContext.  We can do this later by utilizing
31 // NativeProcessProtocol::GetStopID () and adding a stop id to
32 // NativeRegisterContext.
33 
34 // void
35 // NativeRegisterContext::InvalidateIfNeeded (bool force) {
36 //     ProcessSP process_sp (m_thread.GetProcess());
37 //     bool invalidate = force;
38 //     uint32_t process_stop_id = UINT32_MAX;
39 
40 //     if (process_sp)
41 //         process_stop_id = process_sp->GetStopID();
42 //     else
43 //         invalidate = true;
44 
45 //     if (!invalidate)
46 //         invalidate = process_stop_id != GetStopID();
47 
48 //     if (invalidate)
49 //     {
50 //         InvalidateAllRegisters ();
51 //         SetStopID (process_stop_id);
52 //     }
53 // }
54 
55 const RegisterInfo *
56 NativeRegisterContext::GetRegisterInfoByName(llvm::StringRef reg_name,
57                                              uint32_t start_idx) {
58   if (reg_name.empty())
59     return nullptr;
60 
61   const uint32_t num_registers = GetRegisterCount();
62   for (uint32_t reg = start_idx; reg < num_registers; ++reg) {
63     const RegisterInfo *reg_info = GetRegisterInfoAtIndex(reg);
64 
65     if (reg_name.equals_lower(reg_info->name) ||
66         reg_name.equals_lower(reg_info->alt_name))
67       return reg_info;
68   }
69   return nullptr;
70 }
71 
72 const RegisterInfo *NativeRegisterContext::GetRegisterInfo(uint32_t kind,
73                                                            uint32_t num) {
74   const uint32_t reg_num = ConvertRegisterKindToRegisterNumber(kind, num);
75   if (reg_num == LLDB_INVALID_REGNUM)
76     return nullptr;
77   return GetRegisterInfoAtIndex(reg_num);
78 }
79 
80 const char *NativeRegisterContext::GetRegisterName(uint32_t reg) {
81   const RegisterInfo *reg_info = GetRegisterInfoAtIndex(reg);
82   if (reg_info)
83     return reg_info->name;
84   return nullptr;
85 }
86 
87 const char *NativeRegisterContext::GetRegisterSetNameForRegisterAtIndex(
88     uint32_t reg_index) const {
89   const RegisterInfo *const reg_info = GetRegisterInfoAtIndex(reg_index);
90   if (!reg_info)
91     return nullptr;
92 
93   for (uint32_t set_index = 0; set_index < GetRegisterSetCount(); ++set_index) {
94     const RegisterSet *const reg_set = GetRegisterSet(set_index);
95     if (!reg_set)
96       continue;
97 
98     for (uint32_t reg_num_index = 0; reg_num_index < reg_set->num_registers;
99          ++reg_num_index) {
100       const uint32_t reg_num = reg_set->registers[reg_num_index];
101       // FIXME double check we're checking the right register kind here.
102       if (reg_info->kinds[RegisterKind::eRegisterKindLLDB] == reg_num) {
103         // The given register is a member of this register set.  Return the
104         // register set name.
105         return reg_set->name;
106       }
107     }
108   }
109 
110   // Didn't find it.
111   return nullptr;
112 }
113 
114 lldb::addr_t NativeRegisterContext::GetPC(lldb::addr_t fail_value) {
115   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_THREAD));
116 
117   uint32_t reg = ConvertRegisterKindToRegisterNumber(eRegisterKindGeneric,
118                                                      LLDB_REGNUM_GENERIC_PC);
119   if (log)
120     log->Printf("NativeRegisterContext::%s using reg index %" PRIu32
121                 " (default %" PRIu64 ")",
122                 __FUNCTION__, reg, fail_value);
123 
124   const uint64_t retval = ReadRegisterAsUnsigned(reg, fail_value);
125 
126   if (log)
127     log->Printf("NativeRegisterContext::%s " PRIu32 " retval %" PRIu64,
128                 __FUNCTION__, retval);
129 
130   return retval;
131 }
132 
133 lldb::addr_t
134 NativeRegisterContext::GetPCfromBreakpointLocation(lldb::addr_t fail_value) {
135   return GetPC(fail_value);
136 }
137 
138 Status NativeRegisterContext::SetPC(lldb::addr_t pc) {
139   uint32_t reg = ConvertRegisterKindToRegisterNumber(eRegisterKindGeneric,
140                                                      LLDB_REGNUM_GENERIC_PC);
141   return WriteRegisterFromUnsigned(reg, pc);
142 }
143 
144 lldb::addr_t NativeRegisterContext::GetSP(lldb::addr_t fail_value) {
145   uint32_t reg = ConvertRegisterKindToRegisterNumber(eRegisterKindGeneric,
146                                                      LLDB_REGNUM_GENERIC_SP);
147   return ReadRegisterAsUnsigned(reg, fail_value);
148 }
149 
150 Status NativeRegisterContext::SetSP(lldb::addr_t sp) {
151   uint32_t reg = ConvertRegisterKindToRegisterNumber(eRegisterKindGeneric,
152                                                      LLDB_REGNUM_GENERIC_SP);
153   return WriteRegisterFromUnsigned(reg, sp);
154 }
155 
156 lldb::addr_t NativeRegisterContext::GetFP(lldb::addr_t fail_value) {
157   uint32_t reg = ConvertRegisterKindToRegisterNumber(eRegisterKindGeneric,
158                                                      LLDB_REGNUM_GENERIC_FP);
159   return ReadRegisterAsUnsigned(reg, fail_value);
160 }
161 
162 Status NativeRegisterContext::SetFP(lldb::addr_t fp) {
163   uint32_t reg = ConvertRegisterKindToRegisterNumber(eRegisterKindGeneric,
164                                                      LLDB_REGNUM_GENERIC_FP);
165   return WriteRegisterFromUnsigned(reg, fp);
166 }
167 
168 lldb::addr_t NativeRegisterContext::GetReturnAddress(lldb::addr_t fail_value) {
169   uint32_t reg = ConvertRegisterKindToRegisterNumber(eRegisterKindGeneric,
170                                                      LLDB_REGNUM_GENERIC_RA);
171   return ReadRegisterAsUnsigned(reg, fail_value);
172 }
173 
174 lldb::addr_t NativeRegisterContext::GetFlags(lldb::addr_t fail_value) {
175   uint32_t reg = ConvertRegisterKindToRegisterNumber(eRegisterKindGeneric,
176                                                      LLDB_REGNUM_GENERIC_FLAGS);
177   return ReadRegisterAsUnsigned(reg, fail_value);
178 }
179 
180 lldb::addr_t
181 NativeRegisterContext::ReadRegisterAsUnsigned(uint32_t reg,
182                                               lldb::addr_t fail_value) {
183   if (reg != LLDB_INVALID_REGNUM)
184     return ReadRegisterAsUnsigned(GetRegisterInfoAtIndex(reg), fail_value);
185   return fail_value;
186 }
187 
188 uint64_t
189 NativeRegisterContext::ReadRegisterAsUnsigned(const RegisterInfo *reg_info,
190                                               lldb::addr_t fail_value) {
191   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_THREAD));
192 
193   if (reg_info) {
194     RegisterValue value;
195     Status error = ReadRegister(reg_info, value);
196     if (error.Success()) {
197       if (log)
198         log->Printf("NativeRegisterContext::%s ReadRegister() succeeded, value "
199                     "%" PRIu64,
200                     __FUNCTION__, value.GetAsUInt64());
201       return value.GetAsUInt64();
202     } else {
203       if (log)
204         log->Printf("NativeRegisterContext::%s ReadRegister() failed, error %s",
205                     __FUNCTION__, error.AsCString());
206     }
207   } else {
208     if (log)
209       log->Printf("NativeRegisterContext::%s ReadRegister() null reg_info",
210                   __FUNCTION__);
211   }
212   return fail_value;
213 }
214 
215 Status NativeRegisterContext::WriteRegisterFromUnsigned(uint32_t reg,
216                                                         uint64_t uval) {
217   if (reg == LLDB_INVALID_REGNUM)
218     return Status("NativeRegisterContext::%s (): reg is invalid", __FUNCTION__);
219   return WriteRegisterFromUnsigned(GetRegisterInfoAtIndex(reg), uval);
220 }
221 
222 Status
223 NativeRegisterContext::WriteRegisterFromUnsigned(const RegisterInfo *reg_info,
224                                                  uint64_t uval) {
225   assert(reg_info);
226   if (!reg_info)
227     return Status("reg_info is nullptr");
228 
229   RegisterValue value;
230   if (!value.SetUInt(uval, reg_info->byte_size))
231     return Status("RegisterValue::SetUInt () failed");
232 
233   return WriteRegister(reg_info, value);
234 }
235 
236 lldb::tid_t NativeRegisterContext::GetThreadID() const {
237   return m_thread.GetID();
238 }
239 
240 uint32_t NativeRegisterContext::NumSupportedHardwareBreakpoints() { return 0; }
241 
242 uint32_t NativeRegisterContext::SetHardwareBreakpoint(lldb::addr_t addr,
243                                                       size_t size) {
244   return LLDB_INVALID_INDEX32;
245 }
246 
247 Status NativeRegisterContext::ClearAllHardwareBreakpoints() {
248   return Status("not implemented");
249 }
250 
251 bool NativeRegisterContext::ClearHardwareBreakpoint(uint32_t hw_idx) {
252   return false;
253 }
254 
255 Status NativeRegisterContext::GetHardwareBreakHitIndex(uint32_t &bp_index,
256                                                        lldb::addr_t trap_addr) {
257   bp_index = LLDB_INVALID_INDEX32;
258   return Status("not implemented");
259 }
260 
261 uint32_t NativeRegisterContext::NumSupportedHardwareWatchpoints() { return 0; }
262 
263 uint32_t NativeRegisterContext::SetHardwareWatchpoint(lldb::addr_t addr,
264                                                       size_t size,
265                                                       uint32_t watch_flags) {
266   return LLDB_INVALID_INDEX32;
267 }
268 
269 bool NativeRegisterContext::ClearHardwareWatchpoint(uint32_t hw_index) {
270   return false;
271 }
272 
273 Status NativeRegisterContext::ClearAllHardwareWatchpoints() {
274   return Status("not implemented");
275 }
276 
277 Status NativeRegisterContext::IsWatchpointHit(uint32_t wp_index, bool &is_hit) {
278   is_hit = false;
279   return Status("not implemented");
280 }
281 
282 Status NativeRegisterContext::GetWatchpointHitIndex(uint32_t &wp_index,
283                                                     lldb::addr_t trap_addr) {
284   wp_index = LLDB_INVALID_INDEX32;
285   return Status("not implemented");
286 }
287 
288 Status NativeRegisterContext::IsWatchpointVacant(uint32_t wp_index,
289                                                  bool &is_vacant) {
290   is_vacant = false;
291   return Status("not implemented");
292 }
293 
294 lldb::addr_t NativeRegisterContext::GetWatchpointAddress(uint32_t wp_index) {
295   return LLDB_INVALID_ADDRESS;
296 }
297 
298 lldb::addr_t NativeRegisterContext::GetWatchpointHitAddress(uint32_t wp_index) {
299   return LLDB_INVALID_ADDRESS;
300 }
301 
302 bool NativeRegisterContext::HardwareSingleStep(bool enable) { return false; }
303 
304 Status NativeRegisterContext::ReadRegisterValueFromMemory(
305     const RegisterInfo *reg_info, lldb::addr_t src_addr, size_t src_len,
306     RegisterValue &reg_value) {
307   Status error;
308   if (reg_info == nullptr) {
309     error.SetErrorString("invalid register info argument.");
310     return error;
311   }
312 
313   // Moving from addr into a register
314   //
315   // Case 1: src_len == dst_len
316   //
317   //   |AABBCCDD| Address contents
318   //   |AABBCCDD| Register contents
319   //
320   // Case 2: src_len > dst_len
321   //
322   //   Status!  (The register should always be big enough to hold the data)
323   //
324   // Case 3: src_len < dst_len
325   //
326   //   |AABB| Address contents
327   //   |AABB0000| Register contents [on little-endian hardware]
328   //   |0000AABB| Register contents [on big-endian hardware]
329   if (src_len > RegisterValue::kMaxRegisterByteSize) {
330     error.SetErrorString("register too small to receive memory data");
331     return error;
332   }
333 
334   const size_t dst_len = reg_info->byte_size;
335 
336   if (src_len > dst_len) {
337     error.SetErrorStringWithFormat(
338         "%" PRIu64 " bytes is too big to store in register %s (%" PRIu64
339         " bytes)",
340         static_cast<uint64_t>(src_len), reg_info->name,
341         static_cast<uint64_t>(dst_len));
342     return error;
343   }
344 
345   NativeProcessProtocol &process = m_thread.GetProcess();
346   uint8_t src[RegisterValue::kMaxRegisterByteSize];
347 
348   // Read the memory
349   size_t bytes_read;
350   error = process.ReadMemory(src_addr, src, src_len, bytes_read);
351   if (error.Fail())
352     return error;
353 
354   // Make sure the memory read succeeded...
355   if (bytes_read != src_len) {
356     // This might happen if we read _some_ bytes but not all
357     error.SetErrorStringWithFormat("read %" PRIu64 " of %" PRIu64 " bytes",
358                                    static_cast<uint64_t>(bytes_read),
359                                    static_cast<uint64_t>(src_len));
360     return error;
361   }
362 
363   // We now have a memory buffer that contains the part or all of the register
364   // value. Set the register value using this memory data.
365   // TODO: we might need to add a parameter to this function in case the byte
366   // order of the memory data doesn't match the process. For now we are
367   // assuming they are the same.
368   reg_value.SetFromMemoryData(reg_info, src, src_len, process.GetByteOrder(),
369                               error);
370 
371   return error;
372 }
373 
374 Status NativeRegisterContext::WriteRegisterValueToMemory(
375     const RegisterInfo *reg_info, lldb::addr_t dst_addr, size_t dst_len,
376     const RegisterValue &reg_value) {
377 
378   uint8_t dst[RegisterValue::kMaxRegisterByteSize];
379 
380   Status error;
381 
382   NativeProcessProtocol &process = m_thread.GetProcess();
383 
384   // TODO: we might need to add a parameter to this function in case the byte
385   // order of the memory data doesn't match the process. For now we are
386   // assuming they are the same.
387   const size_t bytes_copied = reg_value.GetAsMemoryData(
388       reg_info, dst, dst_len, process.GetByteOrder(), error);
389 
390   if (error.Success()) {
391     if (bytes_copied == 0) {
392       error.SetErrorString("byte copy failed.");
393     } else {
394       size_t bytes_written;
395       error = process.WriteMemory(dst_addr, dst, bytes_copied, bytes_written);
396       if (error.Fail())
397         return error;
398 
399       if (bytes_written != bytes_copied) {
400         // This might happen if we read _some_ bytes but not all
401         error.SetErrorStringWithFormat("only wrote %" PRIu64 " of %" PRIu64
402                                        " bytes",
403                                        static_cast<uint64_t>(bytes_written),
404                                        static_cast<uint64_t>(bytes_copied));
405       }
406     }
407   }
408 
409   return error;
410 }
411 
412 uint32_t
413 NativeRegisterContext::ConvertRegisterKindToRegisterNumber(uint32_t kind,
414                                                            uint32_t num) const {
415   const uint32_t num_regs = GetRegisterCount();
416 
417   assert(kind < kNumRegisterKinds);
418   for (uint32_t reg_idx = 0; reg_idx < num_regs; ++reg_idx) {
419     const RegisterInfo *reg_info = GetRegisterInfoAtIndex(reg_idx);
420 
421     if (reg_info->kinds[kind] == num)
422       return reg_idx;
423   }
424 
425   return LLDB_INVALID_REGNUM;
426 }
427