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