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/Log.h"
13 #include "lldb/Core/RegisterValue.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 Error 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 Error 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 Error 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     Error 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 Error NativeRegisterContext::WriteRegisterFromUnsigned(uint32_t reg,
219                                                        uint64_t uval) {
220   if (reg == LLDB_INVALID_REGNUM)
221     return Error("NativeRegisterContext::%s (): reg is invalid", __FUNCTION__);
222   return WriteRegisterFromUnsigned(GetRegisterInfoAtIndex(reg), uval);
223 }
224 
225 Error NativeRegisterContext::WriteRegisterFromUnsigned(
226     const RegisterInfo *reg_info, uint64_t uval) {
227   assert(reg_info);
228   if (!reg_info)
229     return Error("reg_info is nullptr");
230 
231   RegisterValue value;
232   if (!value.SetUInt(uval, reg_info->byte_size))
233     return Error("RegisterValue::SetUInt () failed");
234 
235   return WriteRegister(reg_info, value);
236 }
237 
238 lldb::tid_t NativeRegisterContext::GetThreadID() const {
239   return m_thread.GetID();
240 }
241 
242 uint32_t NativeRegisterContext::NumSupportedHardwareBreakpoints() { return 0; }
243 
244 uint32_t NativeRegisterContext::SetHardwareBreakpoint(lldb::addr_t addr,
245                                                       size_t size) {
246   return LLDB_INVALID_INDEX32;
247 }
248 
249 Error NativeRegisterContext::ClearAllHardwareBreakpoints() {
250   return Error("not implemented");
251 }
252 
253 bool NativeRegisterContext::ClearHardwareBreakpoint(uint32_t hw_idx) {
254   return false;
255 }
256 
257 Error NativeRegisterContext::GetHardwareBreakHitIndex(uint32_t &bp_index,
258                                                       lldb::addr_t trap_addr) {
259   bp_index = LLDB_INVALID_INDEX32;
260   return Error("not implemented");
261 }
262 
263 uint32_t NativeRegisterContext::NumSupportedHardwareWatchpoints() { return 0; }
264 
265 uint32_t NativeRegisterContext::SetHardwareWatchpoint(lldb::addr_t addr,
266                                                       size_t size,
267                                                       uint32_t watch_flags) {
268   return LLDB_INVALID_INDEX32;
269 }
270 
271 bool NativeRegisterContext::ClearHardwareWatchpoint(uint32_t hw_index) {
272   return false;
273 }
274 
275 Error NativeRegisterContext::ClearAllHardwareWatchpoints() {
276   return Error("not implemented");
277 }
278 
279 Error NativeRegisterContext::IsWatchpointHit(uint32_t wp_index, bool &is_hit) {
280   is_hit = false;
281   return Error("not implemented");
282 }
283 
284 Error NativeRegisterContext::GetWatchpointHitIndex(uint32_t &wp_index,
285                                                    lldb::addr_t trap_addr) {
286   wp_index = LLDB_INVALID_INDEX32;
287   return Error("not implemented");
288 }
289 
290 Error NativeRegisterContext::IsWatchpointVacant(uint32_t wp_index,
291                                                 bool &is_vacant) {
292   is_vacant = false;
293   return Error("not implemented");
294 }
295 
296 lldb::addr_t NativeRegisterContext::GetWatchpointAddress(uint32_t wp_index) {
297   return LLDB_INVALID_ADDRESS;
298 }
299 
300 lldb::addr_t NativeRegisterContext::GetWatchpointHitAddress(uint32_t wp_index) {
301   return LLDB_INVALID_ADDRESS;
302 }
303 
304 bool NativeRegisterContext::HardwareSingleStep(bool enable) { return false; }
305 
306 Error NativeRegisterContext::ReadRegisterValueFromMemory(
307     const RegisterInfo *reg_info, lldb::addr_t src_addr, size_t src_len,
308     RegisterValue &reg_value) {
309   Error error;
310   if (reg_info == nullptr) {
311     error.SetErrorString("invalid register info argument.");
312     return error;
313   }
314 
315   // Moving from addr into a register
316   //
317   // Case 1: src_len == dst_len
318   //
319   //   |AABBCCDD| Address contents
320   //   |AABBCCDD| Register contents
321   //
322   // Case 2: src_len > dst_len
323   //
324   //   Error!  (The register should always be big enough to hold the data)
325   //
326   // Case 3: src_len < dst_len
327   //
328   //   |AABB| Address contents
329   //   |AABB0000| Register contents [on little-endian hardware]
330   //   |0000AABB| Register contents [on big-endian hardware]
331   if (src_len > RegisterValue::kMaxRegisterByteSize) {
332     error.SetErrorString("register too small to receive memory data");
333     return error;
334   }
335 
336   const size_t dst_len = reg_info->byte_size;
337 
338   if (src_len > dst_len) {
339     error.SetErrorStringWithFormat(
340         "%" PRIu64 " bytes is too big to store in register %s (%" PRIu64
341         " bytes)",
342         static_cast<uint64_t>(src_len), reg_info->name,
343         static_cast<uint64_t>(dst_len));
344     return error;
345   }
346 
347   NativeProcessProtocolSP process_sp(m_thread.GetProcess());
348   if (!process_sp) {
349     error.SetErrorString("invalid process");
350     return error;
351   }
352 
353   uint8_t src[RegisterValue::kMaxRegisterByteSize];
354 
355   // Read the memory
356   size_t bytes_read;
357   error = process_sp->ReadMemory(src_addr, src, src_len, bytes_read);
358   if (error.Fail())
359     return error;
360 
361   // Make sure the memory read succeeded...
362   if (bytes_read != src_len) {
363     // This might happen if we read _some_ bytes but not all
364     error.SetErrorStringWithFormat("read %" PRIu64 " of %" PRIu64 " bytes",
365                                    static_cast<uint64_t>(bytes_read),
366                                    static_cast<uint64_t>(src_len));
367     return error;
368   }
369 
370   // We now have a memory buffer that contains the part or all of the register
371   // value. Set the register value using this memory data.
372   // TODO: we might need to add a parameter to this function in case the byte
373   // order of the memory data doesn't match the process. For now we are assuming
374   // they are the same.
375   lldb::ByteOrder byte_order;
376   if (!process_sp->GetByteOrder(byte_order)) {
377     error.SetErrorString("NativeProcessProtocol::GetByteOrder () failed");
378     return error;
379   }
380 
381   reg_value.SetFromMemoryData(reg_info, src, src_len, byte_order, error);
382 
383   return error;
384 }
385 
386 Error NativeRegisterContext::WriteRegisterValueToMemory(
387     const RegisterInfo *reg_info, lldb::addr_t dst_addr, size_t dst_len,
388     const RegisterValue &reg_value) {
389 
390   uint8_t dst[RegisterValue::kMaxRegisterByteSize];
391 
392   Error error;
393 
394   NativeProcessProtocolSP process_sp(m_thread.GetProcess());
395   if (process_sp) {
396 
397     // TODO: we might need to add a parameter to this function in case the byte
398     // order of the memory data doesn't match the process. For now we are
399     // assuming
400     // they are the same.
401     lldb::ByteOrder byte_order;
402     if (!process_sp->GetByteOrder(byte_order))
403       return Error("NativeProcessProtocol::GetByteOrder () failed");
404 
405     const size_t bytes_copied =
406         reg_value.GetAsMemoryData(reg_info, dst, dst_len, byte_order, error);
407 
408     if (error.Success()) {
409       if (bytes_copied == 0) {
410         error.SetErrorString("byte copy failed.");
411       } else {
412         size_t bytes_written;
413         error =
414             process_sp->WriteMemory(dst_addr, dst, bytes_copied, bytes_written);
415         if (error.Fail())
416           return error;
417 
418         if (bytes_written != bytes_copied) {
419           // This might happen if we read _some_ bytes but not all
420           error.SetErrorStringWithFormat("only wrote %" PRIu64 " of %" PRIu64
421                                          " bytes",
422                                          static_cast<uint64_t>(bytes_written),
423                                          static_cast<uint64_t>(bytes_copied));
424         }
425       }
426     }
427   } else
428     error.SetErrorString("invalid process");
429 
430   return error;
431 }
432 
433 uint32_t
434 NativeRegisterContext::ConvertRegisterKindToRegisterNumber(uint32_t kind,
435                                                            uint32_t num) const {
436   const uint32_t num_regs = GetRegisterCount();
437 
438   assert(kind < kNumRegisterKinds);
439   for (uint32_t reg_idx = 0; reg_idx < num_regs; ++reg_idx) {
440     const RegisterInfo *reg_info = GetRegisterInfoAtIndex(reg_idx);
441 
442     if (reg_info->kinds[kind] == num)
443       return reg_idx;
444   }
445 
446   return LLDB_INVALID_REGNUM;
447 }
448