LLDB  mainline
ABISysV_ppc64.cpp
Go to the documentation of this file.
1 //===-- ABISysV_ppc64.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 "ABISysV_ppc64.h"
10 
11 #include "llvm/ADT/STLExtras.h"
12 #include "llvm/ADT/Triple.h"
13 
16 #include "lldb/Core/Module.h"
18 #include "lldb/Core/Value.h"
23 #include "lldb/Symbol/UnwindPlan.h"
24 #include "lldb/Target/Process.h"
26 #include "lldb/Target/StackFrame.h"
27 #include "lldb/Target/Target.h"
28 #include "lldb/Target/Thread.h"
31 #include "lldb/Utility/Log.h"
33 #include "lldb/Utility/Status.h"
34 
35 #include "clang/AST/ASTContext.h"
36 #include "clang/AST/Attr.h"
37 #include "clang/AST/Decl.h"
38 
39 #define DECLARE_REGISTER_INFOS_PPC64_STRUCT
41 #undef DECLARE_REGISTER_INFOS_PPC64_STRUCT
42 
43 #define DECLARE_REGISTER_INFOS_PPC64LE_STRUCT
45 #undef DECLARE_REGISTER_INFOS_PPC64LE_STRUCT
46 
47 using namespace lldb;
48 using namespace lldb_private;
49 
50 const lldb_private::RegisterInfo *
52  if (GetByteOrder() == lldb::eByteOrderLittle) {
53  count = llvm::array_lengthof(g_register_infos_ppc64le);
54  return g_register_infos_ppc64le;
55  } else {
56  count = llvm::array_lengthof(g_register_infos_ppc64);
57  return g_register_infos_ppc64;
58  }
59 }
60 
61 size_t ABISysV_ppc64::GetRedZoneSize() const { return 224; }
62 
63 lldb::ByteOrder ABISysV_ppc64::GetByteOrder() const {
64  return GetProcessSP()->GetByteOrder();
65 }
66 
67 // Static Functions
68 
69 ABISP
70 ABISysV_ppc64::CreateInstance(lldb::ProcessSP process_sp,
71  const ArchSpec &arch) {
72  if (arch.GetTriple().getArch() == llvm::Triple::ppc64 ||
73  arch.GetTriple().getArch() == llvm::Triple::ppc64le) {
74  return ABISP(new ABISysV_ppc64(process_sp));
75  }
76  return ABISP();
77 }
78 
80  addr_t func_addr, addr_t return_addr,
81  llvm::ArrayRef<addr_t> args) const {
83 
84  if (log) {
85  StreamString s;
86  s.Printf("ABISysV_ppc64::PrepareTrivialCall (tid = 0x%" PRIx64
87  ", sp = 0x%" PRIx64 ", func_addr = 0x%" PRIx64
88  ", return_addr = 0x%" PRIx64,
89  thread.GetID(), (uint64_t)sp, (uint64_t)func_addr,
90  (uint64_t)return_addr);
91 
92  for (size_t i = 0; i < args.size(); ++i)
93  s.Printf(", arg%" PRIu64 " = 0x%" PRIx64, static_cast<uint64_t>(i + 1),
94  args[i]);
95  s.PutCString(")");
96  log->PutString(s.GetString());
97  }
98 
99  RegisterContext *reg_ctx = thread.GetRegisterContext().get();
100  if (!reg_ctx)
101  return false;
102 
103  const RegisterInfo *reg_info = nullptr;
104 
105  if (args.size() > 8) // TODO handle more than 8 arguments
106  return false;
107 
108  for (size_t i = 0; i < args.size(); ++i) {
109  reg_info = reg_ctx->GetRegisterInfo(eRegisterKindGeneric,
111  if (log)
112  log->Printf("About to write arg%" PRIu64 " (0x%" PRIx64 ") into %s",
113  static_cast<uint64_t>(i + 1), args[i], reg_info->name);
114  if (!reg_ctx->WriteRegisterFromUnsigned(reg_info, args[i]))
115  return false;
116  }
117 
118  // First, align the SP
119 
120  if (log)
121  log->Printf("16-byte aligning SP: 0x%" PRIx64 " to 0x%" PRIx64,
122  (uint64_t)sp, (uint64_t)(sp & ~0xfull));
123 
124  sp &= ~(0xfull); // 16-byte alignment
125 
126  sp -= 544; // allocate frame to save TOC, RA and SP.
127 
128  Status error;
129  uint64_t reg_value;
130  const RegisterInfo *pc_reg_info =
132  const RegisterInfo *sp_reg_info =
134  ProcessSP process_sp(thread.GetProcess());
135  const RegisterInfo *lr_reg_info =
137  const RegisterInfo *r2_reg_info = reg_ctx->GetRegisterInfoAtIndex(2);
138  const RegisterInfo *r12_reg_info = reg_ctx->GetRegisterInfoAtIndex(12);
139 
140  // Save return address onto the stack.
141  if (log)
142  log->Printf("Pushing the return address onto the stack: 0x%" PRIx64
143  "(+16): 0x%" PRIx64,
144  (uint64_t)sp, (uint64_t)return_addr);
145  if (!process_sp->WritePointerToMemory(sp + 16, return_addr, error))
146  return false;
147 
148  // Write the return address to link register.
149  if (log)
150  log->Printf("Writing LR: 0x%" PRIx64, (uint64_t)return_addr);
151  if (!reg_ctx->WriteRegisterFromUnsigned(lr_reg_info, return_addr))
152  return false;
153 
154  // Write target address to %r12 register.
155  if (log)
156  log->Printf("Writing R12: 0x%" PRIx64, (uint64_t)func_addr);
157  if (!reg_ctx->WriteRegisterFromUnsigned(r12_reg_info, func_addr))
158  return false;
159 
160  // Read TOC pointer value.
161  reg_value = reg_ctx->ReadRegisterAsUnsigned(r2_reg_info, 0);
162 
163  // Write TOC pointer onto the stack.
164  uint64_t stack_offset;
165  if (GetByteOrder() == lldb::eByteOrderLittle)
166  stack_offset = 24;
167  else
168  stack_offset = 40;
169 
170  if (log)
171  log->Printf("Writing R2 (TOC) at SP(0x%" PRIx64 ")+%d: 0x%" PRIx64,
172  (uint64_t)(sp + stack_offset), (int)stack_offset,
173  (uint64_t)reg_value);
174  if (!process_sp->WritePointerToMemory(sp + stack_offset, reg_value, error))
175  return false;
176 
177  // Read the current SP value.
178  reg_value = reg_ctx->ReadRegisterAsUnsigned(sp_reg_info, 0);
179 
180  // Save current SP onto the stack.
181  if (log)
182  log->Printf("Writing SP at SP(0x%" PRIx64 ")+0: 0x%" PRIx64, (uint64_t)sp,
183  (uint64_t)reg_value);
184  if (!process_sp->WritePointerToMemory(sp, reg_value, error))
185  return false;
186 
187  // %r1 is set to the actual stack value.
188  if (log)
189  log->Printf("Writing SP: 0x%" PRIx64, (uint64_t)sp);
190 
191  if (!reg_ctx->WriteRegisterFromUnsigned(sp_reg_info, sp))
192  return false;
193 
194  // %pc is set to the address of the called function.
195 
196  if (log)
197  log->Printf("Writing IP: 0x%" PRIx64, (uint64_t)func_addr);
198 
199  if (!reg_ctx->WriteRegisterFromUnsigned(pc_reg_info, func_addr))
200  return false;
201 
202  return true;
203 }
204 
205 static bool ReadIntegerArgument(Scalar &scalar, unsigned int bit_width,
206  bool is_signed, Thread &thread,
207  uint32_t *argument_register_ids,
208  unsigned int &current_argument_register,
209  addr_t &current_stack_argument) {
210  if (bit_width > 64)
211  return false; // Scalar can't hold large integer arguments
212 
213  if (current_argument_register < 6) {
214  scalar = thread.GetRegisterContext()->ReadRegisterAsUnsigned(
215  argument_register_ids[current_argument_register], 0);
216  current_argument_register++;
217  if (is_signed)
218  scalar.SignExtend(bit_width);
219  } else {
220  uint32_t byte_size = (bit_width + (8 - 1)) / 8;
221  Status error;
222  if (thread.GetProcess()->ReadScalarIntegerFromMemory(
223  current_stack_argument, byte_size, is_signed, scalar, error)) {
224  current_stack_argument += byte_size;
225  return true;
226  }
227  return false;
228  }
229  return true;
230 }
231 
232 bool ABISysV_ppc64::GetArgumentValues(Thread &thread, ValueList &values) const {
233  unsigned int num_values = values.GetSize();
234  unsigned int value_index;
235 
236  // Extract the register context so we can read arguments from registers
237 
238  RegisterContext *reg_ctx = thread.GetRegisterContext().get();
239 
240  if (!reg_ctx)
241  return false;
242 
243  // Get the pointer to the first stack argument so we have a place to start
244  // when reading data
245 
246  addr_t sp = reg_ctx->GetSP(0);
247 
248  if (!sp)
249  return false;
250 
251  uint64_t stack_offset;
252  if (GetByteOrder() == lldb::eByteOrderLittle)
253  stack_offset = 32;
254  else
255  stack_offset = 48;
256 
257  // jump over return address.
258  addr_t current_stack_argument = sp + stack_offset;
259  uint32_t argument_register_ids[8];
260 
261  for (size_t i = 0; i < 8; ++i) {
262  argument_register_ids[i] =
263  reg_ctx
266  ->kinds[eRegisterKindLLDB];
267  }
268 
269  unsigned int current_argument_register = 0;
270 
271  for (value_index = 0; value_index < num_values; ++value_index) {
272  Value *value = values.GetValueAtIndex(value_index);
273 
274  if (!value)
275  return false;
276 
277  // We currently only support extracting values with Clang QualTypes. Do we
278  // care about others?
279  CompilerType compiler_type = value->GetCompilerType();
280  llvm::Optional<uint64_t> bit_size = compiler_type.GetBitSize(&thread);
281  if (!bit_size)
282  return false;
283  bool is_signed;
284 
285  if (compiler_type.IsIntegerOrEnumerationType(is_signed)) {
286  ReadIntegerArgument(value->GetScalar(), *bit_size, is_signed, thread,
287  argument_register_ids, current_argument_register,
288  current_stack_argument);
289  } else if (compiler_type.IsPointerType()) {
290  ReadIntegerArgument(value->GetScalar(), *bit_size, false, thread,
291  argument_register_ids, current_argument_register,
292  current_stack_argument);
293  }
294  }
295 
296  return true;
297 }
298 
299 Status ABISysV_ppc64::SetReturnValueObject(lldb::StackFrameSP &frame_sp,
300  lldb::ValueObjectSP &new_value_sp) {
301  Status error;
302  if (!new_value_sp) {
303  error.SetErrorString("Empty value object for return value.");
304  return error;
305  }
306 
307  CompilerType compiler_type = new_value_sp->GetCompilerType();
308  if (!compiler_type) {
309  error.SetErrorString("Null clang type for return value.");
310  return error;
311  }
312 
313  Thread *thread = frame_sp->GetThread().get();
314 
315  bool is_signed;
316  uint32_t count;
317  bool is_complex;
318 
319  RegisterContext *reg_ctx = thread->GetRegisterContext().get();
320 
321  bool set_it_simple = false;
322  if (compiler_type.IsIntegerOrEnumerationType(is_signed) ||
323  compiler_type.IsPointerType()) {
324  const RegisterInfo *reg_info = reg_ctx->GetRegisterInfoByName("r3", 0);
325 
326  DataExtractor data;
327  Status data_error;
328  size_t num_bytes = new_value_sp->GetData(data, data_error);
329  if (data_error.Fail()) {
331  "Couldn't convert return value to raw data: %s",
332  data_error.AsCString());
333  return error;
334  }
335  lldb::offset_t offset = 0;
336  if (num_bytes <= 8) {
337  uint64_t raw_value = data.GetMaxU64(&offset, num_bytes);
338 
339  if (reg_ctx->WriteRegisterFromUnsigned(reg_info, raw_value))
340  set_it_simple = true;
341  } else {
342  error.SetErrorString("We don't support returning longer than 64 bit "
343  "integer values at present.");
344  }
345  } else if (compiler_type.IsFloatingPointType(count, is_complex)) {
346  if (is_complex)
347  error.SetErrorString(
348  "We don't support returning complex values at present");
349  else {
350  llvm::Optional<uint64_t> bit_width =
351  compiler_type.GetBitSize(frame_sp.get());
352  if (!bit_width) {
353  error.SetErrorString("can't get size of type");
354  return error;
355  }
356  if (*bit_width <= 64) {
357  DataExtractor data;
358  Status data_error;
359  size_t num_bytes = new_value_sp->GetData(data, data_error);
360  if (data_error.Fail()) {
362  "Couldn't convert return value to raw data: %s",
363  data_error.AsCString());
364  return error;
365  }
366 
367  unsigned char buffer[16];
368  ByteOrder byte_order = data.GetByteOrder();
369 
370  data.CopyByteOrderedData(0, num_bytes, buffer, 16, byte_order);
371  set_it_simple = true;
372  } else {
373  // FIXME - don't know how to do 80 bit long doubles yet.
374  error.SetErrorString(
375  "We don't support returning float values > 64 bits at present");
376  }
377  }
378  }
379 
380  if (!set_it_simple) {
381  // Okay we've got a structure or something that doesn't fit in a simple
382  // register. We should figure out where it really goes, but we don't
383  // support this yet.
384  error.SetErrorString("We only support setting simple integer and float "
385  "return types at present.");
386  }
387 
388  return error;
389 }
390 
391 //
392 // ReturnValueExtractor
393 //
394 
395 namespace {
396 
397 #define LOG_PREFIX "ReturnValueExtractor: "
398 
399 class ReturnValueExtractor {
400  // This class represents a register, from which data may be extracted.
401  //
402  // It may be constructed by directly specifying its index (where 0 is the
403  // first register used to return values) or by specifying the offset of a
404  // given struct field, in which case the appropriated register index will be
405  // calculated.
406  class Register {
407  public:
408  enum Type {
409  GPR, // General Purpose Register
410  FPR // Floating Point Register
411  };
412 
413  // main constructor
414  //
415  // offs - field offset in struct
416  Register(Type ty, uint32_t index, uint32_t offs, RegisterContext *reg_ctx,
417  ByteOrder byte_order)
418  : m_index(index), m_offs(offs % sizeof(uint64_t)),
419  m_avail(sizeof(uint64_t) - m_offs), m_type(ty), m_reg_ctx(reg_ctx),
420  m_byte_order(byte_order) {}
421 
422  // explicit index, no offset
423  Register(Type ty, uint32_t index, RegisterContext *reg_ctx,
424  ByteOrder byte_order)
425  : Register(ty, index, 0, reg_ctx, byte_order) {}
426 
427  // GPR, calculate index from offs
428  Register(uint32_t offs, RegisterContext *reg_ctx, ByteOrder byte_order)
429  : Register(GPR, offs / sizeof(uint64_t), offs, reg_ctx, byte_order) {}
430 
431  uint32_t Index() const { return m_index; }
432 
433  // register offset where data is located
434  uint32_t Offs() const { return m_offs; }
435 
436  // available bytes in this register
437  uint32_t Avail() const { return m_avail; }
438 
439  bool IsValid() const {
440  if (m_index > 7) {
441  LLDB_LOG(m_log, LOG_PREFIX
442  "No more than 8 registers should be used to return values");
443  return false;
444  }
445  return true;
446  }
447 
448  std::string GetName() const {
449  if (m_type == GPR)
450  return ("r" + llvm::Twine(m_index + 3)).str();
451  else
452  return ("f" + llvm::Twine(m_index + 1)).str();
453  }
454 
455  // get raw register data
456  bool GetRawData(uint64_t &raw_data) {
457  const RegisterInfo *reg_info =
458  m_reg_ctx->GetRegisterInfoByName(GetName());
459  if (!reg_info) {
460  LLDB_LOG(m_log, LOG_PREFIX "Failed to get RegisterInfo");
461  return false;
462  }
463 
464  RegisterValue reg_val;
465  if (!m_reg_ctx->ReadRegister(reg_info, reg_val)) {
466  LLDB_LOG(m_log, LOG_PREFIX "ReadRegister() failed");
467  return false;
468  }
469 
470  Status error;
471  uint32_t rc = reg_val.GetAsMemoryData(
472  reg_info, &raw_data, sizeof(raw_data), m_byte_order, error);
473  if (rc != sizeof(raw_data)) {
474  LLDB_LOG(m_log, LOG_PREFIX "GetAsMemoryData() failed");
475  return false;
476  }
477 
478  return true;
479  }
480 
481  private:
482  uint32_t m_index;
483  uint32_t m_offs;
484  uint32_t m_avail;
485  Type m_type;
486  RegisterContext *m_reg_ctx;
487  ByteOrder m_byte_order;
488  Log *m_log =
490  };
491 
492  Register GetGPR(uint32_t index) const {
493  return Register(Register::GPR, index, m_reg_ctx, m_byte_order);
494  }
495 
496  Register GetFPR(uint32_t index) const {
497  return Register(Register::FPR, index, m_reg_ctx, m_byte_order);
498  }
499 
500  Register GetGPRByOffs(uint32_t offs) const {
501  return Register(offs, m_reg_ctx, m_byte_order);
502  }
503 
504 public:
505  // factory
506  static llvm::Expected<ReturnValueExtractor> Create(Thread &thread,
507  CompilerType &type) {
508  RegisterContext *reg_ctx = thread.GetRegisterContext().get();
509  if (!reg_ctx)
510  return llvm::make_error<llvm::StringError>(
511  LOG_PREFIX "Failed to get RegisterContext",
512  llvm::inconvertibleErrorCode());
513 
514  ProcessSP process_sp = thread.GetProcess();
515  if (!process_sp)
516  return llvm::make_error<llvm::StringError>(
517  LOG_PREFIX "GetProcess() failed", llvm::inconvertibleErrorCode());
518 
519  return ReturnValueExtractor(thread, type, reg_ctx, process_sp);
520  }
521 
522  // main method: get value of the type specified at construction time
523  ValueObjectSP GetValue() {
524  const uint32_t type_flags = m_type.GetTypeInfo();
525 
526  // call the appropriate type handler
527  ValueSP value_sp;
528  ValueObjectSP valobj_sp;
529  if (type_flags & eTypeIsScalar) {
530  if (type_flags & eTypeIsInteger) {
531  value_sp = GetIntegerValue(0);
532  } else if (type_flags & eTypeIsFloat) {
533  if (type_flags & eTypeIsComplex) {
534  LLDB_LOG(m_log, LOG_PREFIX "Complex numbers are not supported yet");
535  return ValueObjectSP();
536  } else {
537  value_sp = GetFloatValue(m_type, 0);
538  }
539  }
540  } else if (type_flags & eTypeIsPointer) {
541  value_sp = GetPointerValue(0);
542  }
543 
544  if (value_sp) {
545  valobj_sp = ValueObjectConstResult::Create(
546  m_thread.GetStackFrameAtIndex(0).get(), *value_sp, ConstString(""));
547  } else if (type_flags & eTypeIsVector) {
548  valobj_sp = GetVectorValueObject();
549  } else if (type_flags & eTypeIsStructUnion || type_flags & eTypeIsClass) {
550  valobj_sp = GetStructValueObject();
551  }
552 
553  return valobj_sp;
554  }
555 
556 private:
557  // data
558  Thread &m_thread;
559  CompilerType &m_type;
560  uint64_t m_byte_size;
561  std::unique_ptr<DataBufferHeap> m_data_up;
562  int32_t m_src_offs = 0;
563  int32_t m_dst_offs = 0;
564  bool m_packed = false;
566  RegisterContext *m_reg_ctx;
567  ProcessSP m_process_sp;
568  ByteOrder m_byte_order;
569  uint32_t m_addr_size;
570 
571  // methods
572 
573  // constructor
574  ReturnValueExtractor(Thread &thread, CompilerType &type,
575  RegisterContext *reg_ctx, ProcessSP process_sp)
576  : m_thread(thread), m_type(type),
577  m_byte_size(m_type.GetByteSize(nullptr).getValueOr(0)),
578  m_data_up(new DataBufferHeap(m_byte_size, 0)), m_reg_ctx(reg_ctx),
579  m_process_sp(process_sp), m_byte_order(process_sp->GetByteOrder()),
580  m_addr_size(
581  process_sp->GetTarget().GetArchitecture().GetAddressByteSize()) {}
582 
583  // build a new scalar value
584  ValueSP NewScalarValue(CompilerType &type) {
585  ValueSP value_sp(new Value);
586  value_sp->SetCompilerType(type);
587  value_sp->SetValueType(Value::eValueTypeScalar);
588  return value_sp;
589  }
590 
591  // get an integer value in the specified register
592  ValueSP GetIntegerValue(uint32_t reg_index) {
593  uint64_t raw_value;
594  auto reg = GetGPR(reg_index);
595  if (!reg.GetRawData(raw_value))
596  return ValueSP();
597 
598  // build value from data
599  ValueSP value_sp(NewScalarValue(m_type));
600 
601  uint32_t type_flags = m_type.GetTypeInfo();
602  bool is_signed = (type_flags & eTypeIsSigned) != 0;
603 
604  switch (m_byte_size) {
605  case sizeof(uint64_t):
606  if (is_signed)
607  value_sp->GetScalar() = (int64_t)(raw_value);
608  else
609  value_sp->GetScalar() = (uint64_t)(raw_value);
610  break;
611 
612  case sizeof(uint32_t):
613  if (is_signed)
614  value_sp->GetScalar() = (int32_t)(raw_value & UINT32_MAX);
615  else
616  value_sp->GetScalar() = (uint32_t)(raw_value & UINT32_MAX);
617  break;
618 
619  case sizeof(uint16_t):
620  if (is_signed)
621  value_sp->GetScalar() = (int16_t)(raw_value & UINT16_MAX);
622  else
623  value_sp->GetScalar() = (uint16_t)(raw_value & UINT16_MAX);
624  break;
625 
626  case sizeof(uint8_t):
627  if (is_signed)
628  value_sp->GetScalar() = (int8_t)(raw_value & UINT8_MAX);
629  else
630  value_sp->GetScalar() = (uint8_t)(raw_value & UINT8_MAX);
631  break;
632 
633  default:
634  llvm_unreachable("Invalid integer size");
635  }
636 
637  return value_sp;
638  }
639 
640  // get a floating point value on the specified register
641  ValueSP GetFloatValue(CompilerType &type, uint32_t reg_index) {
642  uint64_t raw_data;
643  auto reg = GetFPR(reg_index);
644  if (!reg.GetRawData(raw_data))
645  return {};
646 
647  // build value from data
648  ValueSP value_sp(NewScalarValue(type));
649 
650  DataExtractor de(&raw_data, sizeof(raw_data), m_byte_order, m_addr_size);
651 
652  offset_t offset = 0;
653  llvm::Optional<uint64_t> byte_size = type.GetByteSize(nullptr);
654  if (!byte_size)
655  return {};
656  switch (*byte_size) {
657  case sizeof(float):
658  value_sp->GetScalar() = (float)de.GetDouble(&offset);
659  break;
660 
661  case sizeof(double):
662  value_sp->GetScalar() = de.GetDouble(&offset);
663  break;
664 
665  default:
666  llvm_unreachable("Invalid floating point size");
667  }
668 
669  return value_sp;
670  }
671 
672  // get pointer value from register
673  ValueSP GetPointerValue(uint32_t reg_index) {
674  uint64_t raw_data;
675  auto reg = GetGPR(reg_index);
676  if (!reg.GetRawData(raw_data))
677  return ValueSP();
678 
679  // build value from raw data
680  ValueSP value_sp(NewScalarValue(m_type));
681  value_sp->GetScalar() = raw_data;
682  return value_sp;
683  }
684 
685  // build the ValueObject from our data buffer
686  ValueObjectSP BuildValueObject() {
687  DataExtractor de(DataBufferSP(m_data_up.release()), m_byte_order,
688  m_addr_size);
689  return ValueObjectConstResult::Create(&m_thread, m_type, ConstString(""),
690  de);
691  }
692 
693  // get a vector return value
694  ValueObjectSP GetVectorValueObject() {
695  const uint32_t MAX_VRS = 2;
696 
697  // get first V register used to return values
698  const RegisterInfo *vr[MAX_VRS];
699  vr[0] = m_reg_ctx->GetRegisterInfoByName("vr2");
700  if (!vr[0]) {
701  LLDB_LOG(m_log, LOG_PREFIX "Failed to get vr2 RegisterInfo");
702  return ValueObjectSP();
703  }
704 
705  const uint32_t vr_size = vr[0]->byte_size;
706  size_t vrs = 1;
707  if (m_byte_size > 2 * vr_size) {
708  LLDB_LOG(
709  m_log, LOG_PREFIX
710  "Returning vectors that don't fit in 2 VR regs is not supported");
711  return ValueObjectSP();
712  }
713 
714  // load vr3, if needed
715  if (m_byte_size > vr_size) {
716  vrs++;
717  vr[1] = m_reg_ctx->GetRegisterInfoByName("vr3");
718  if (!vr[1]) {
719  LLDB_LOG(m_log, LOG_PREFIX "Failed to get vr3 RegisterInfo");
720  return ValueObjectSP();
721  }
722  }
723 
724  // Get the whole contents of vector registers and let the logic here
725  // arrange the data properly.
726 
727  RegisterValue vr_val[MAX_VRS];
728  Status error;
729  std::unique_ptr<DataBufferHeap> vr_data(
730  new DataBufferHeap(vrs * vr_size, 0));
731 
732  for (uint32_t i = 0; i < vrs; i++) {
733  if (!m_reg_ctx->ReadRegister(vr[i], vr_val[i])) {
734  LLDB_LOG(m_log, LOG_PREFIX "Failed to read vector register contents");
735  return ValueObjectSP();
736  }
737  if (!vr_val[i].GetAsMemoryData(vr[i], vr_data->GetBytes() + i * vr_size,
738  vr_size, m_byte_order, error)) {
739  LLDB_LOG(m_log, LOG_PREFIX "Failed to extract vector register bytes");
740  return ValueObjectSP();
741  }
742  }
743 
744  // The compiler generated code seems to always put the vector elements at
745  // the end of the vector register, in case they don't occupy all of it.
746  // This offset variable handles this.
747  uint32_t offs = 0;
748  if (m_byte_size < vr_size)
749  offs = vr_size - m_byte_size;
750 
751  // copy extracted data to our buffer
752  memcpy(m_data_up->GetBytes(), vr_data->GetBytes() + offs, m_byte_size);
753  return BuildValueObject();
754  }
755 
756  // get a struct return value
757  ValueObjectSP GetStructValueObject() {
758  // case 1: get from stack
759  if (m_byte_size > 2 * sizeof(uint64_t)) {
760  uint64_t addr;
761  auto reg = GetGPR(0);
762  if (!reg.GetRawData(addr))
763  return {};
764 
765  Status error;
766  size_t rc = m_process_sp->ReadMemory(addr, m_data_up->GetBytes(),
767  m_byte_size, error);
768  if (rc != m_byte_size) {
769  LLDB_LOG(m_log, LOG_PREFIX "Failed to read memory pointed by r3");
770  return ValueObjectSP();
771  }
772  return BuildValueObject();
773  }
774 
775  // get number of children
776  const bool omit_empty_base_classes = true;
777  uint32_t n = m_type.GetNumChildren(omit_empty_base_classes, nullptr);
778  if (!n) {
779  LLDB_LOG(m_log, LOG_PREFIX "No children found in struct");
780  return {};
781  }
782 
783  // case 2: homogeneous double or float aggregate
784  CompilerType elem_type;
785  if (m_type.IsHomogeneousAggregate(&elem_type)) {
786  uint32_t type_flags = elem_type.GetTypeInfo();
787  llvm::Optional<uint64_t> elem_size = elem_type.GetByteSize(nullptr);
788  if (!elem_size)
789  return {};
790  if (type_flags & eTypeIsComplex || !(type_flags & eTypeIsFloat)) {
791  LLDB_LOG(m_log,
792  LOG_PREFIX "Unexpected type found in homogeneous aggregate");
793  return {};
794  }
795 
796  for (uint32_t i = 0; i < n; i++) {
797  ValueSP val_sp = GetFloatValue(elem_type, i);
798  if (!val_sp)
799  return {};
800 
801  // copy to buffer
802  Status error;
803  size_t rc = val_sp->GetScalar().GetAsMemoryData(
804  m_data_up->GetBytes() + m_dst_offs, *elem_size, m_byte_order,
805  error);
806  if (rc != *elem_size) {
807  LLDB_LOG(m_log, LOG_PREFIX "Failed to get float data");
808  return {};
809  }
810  m_dst_offs += *elem_size;
811  }
812  return BuildValueObject();
813  }
814 
815  // case 3: get from GPRs
816 
817  // first, check if this is a packed struct or not
818  ClangASTContext *ast =
819  llvm::dyn_cast<ClangASTContext>(m_type.GetTypeSystem());
820  if (ast) {
821  clang::RecordDecl *record_decl = ClangASTContext::GetAsRecordDecl(m_type);
822 
823  if (record_decl) {
824  auto attrs = record_decl->attrs();
825  for (const auto &attr : attrs) {
826  if (attr->getKind() == clang::attr::Packed) {
827  m_packed = true;
828  break;
829  }
830  }
831  }
832  }
833 
834  LLDB_LOG(m_log, LOG_PREFIX "{0} struct",
835  m_packed ? "packed" : "not packed");
836 
837  for (uint32_t i = 0; i < n; i++) {
838  std::string name;
839  uint32_t size;
840  GetChildType(i, name, size);
841  // NOTE: the offset returned by GetChildCompilerTypeAtIndex()
842  // can't be used because it never considers alignment bytes
843  // between struct fields.
844  LLDB_LOG(m_log, LOG_PREFIX "field={0}, size={1}", name, size);
845  if (!ExtractField(size))
846  return ValueObjectSP();
847  }
848 
849  return BuildValueObject();
850  }
851 
852  // extract 'size' bytes at 'offs' from GPRs
853  bool ExtractFromRegs(int32_t offs, uint32_t size, void *buf) {
854  while (size) {
855  auto reg = GetGPRByOffs(offs);
856  if (!reg.IsValid())
857  return false;
858 
859  uint32_t n = std::min(reg.Avail(), size);
860  uint64_t raw_data;
861 
862  if (!reg.GetRawData(raw_data))
863  return false;
864 
865  memcpy(buf, (char *)&raw_data + reg.Offs(), n);
866  offs += n;
867  size -= n;
868  buf = (char *)buf + n;
869  }
870  return true;
871  }
872 
873  // extract one field from GPRs and put it in our buffer
874  bool ExtractField(uint32_t size) {
875  auto reg = GetGPRByOffs(m_src_offs);
876  if (!reg.IsValid())
877  return false;
878 
879  // handle padding
880  if (!m_packed) {
881  uint32_t n = m_src_offs % size;
882 
883  // not 'size' bytes aligned
884  if (n) {
885  LLDB_LOG(m_log,
886  LOG_PREFIX "Extracting {0} alignment bytes at offset {1}", n,
887  m_src_offs);
888  // get alignment bytes
889  if (!ExtractFromRegs(m_src_offs, n, m_data_up->GetBytes() + m_dst_offs))
890  return false;
891  m_src_offs += n;
892  m_dst_offs += n;
893  }
894  }
895 
896  // get field
897  LLDB_LOG(m_log, LOG_PREFIX "Extracting {0} field bytes at offset {1}", size,
898  m_src_offs);
899  if (!ExtractFromRegs(m_src_offs, size, m_data_up->GetBytes() + m_dst_offs))
900  return false;
901  m_src_offs += size;
902  m_dst_offs += size;
903  return true;
904  }
905 
906  // get child
907  CompilerType GetChildType(uint32_t i, std::string &name, uint32_t &size) {
908  // GetChild constant inputs
909  const bool transparent_pointers = false;
910  const bool omit_empty_base_classes = true;
911  const bool ignore_array_bounds = false;
912  // GetChild output params
913  int32_t child_offs;
914  uint32_t child_bitfield_bit_size;
915  uint32_t child_bitfield_bit_offset;
916  bool child_is_base_class;
917  bool child_is_deref_of_parent;
918  ValueObject *valobj = nullptr;
919  uint64_t language_flags;
920  ExecutionContext exe_ctx;
921  m_thread.CalculateExecutionContext(exe_ctx);
922 
923  return m_type.GetChildCompilerTypeAtIndex(
924  &exe_ctx, i, transparent_pointers, omit_empty_base_classes,
925  ignore_array_bounds, name, size, child_offs, child_bitfield_bit_size,
926  child_bitfield_bit_offset, child_is_base_class,
927  child_is_deref_of_parent, valobj, language_flags);
928  }
929 };
930 
931 #undef LOG_PREFIX
932 
933 } // anonymous namespace
934 
935 ValueObjectSP
937  CompilerType &type) const {
938  if (!type)
939  return ValueObjectSP();
940 
941  auto exp_extractor = ReturnValueExtractor::Create(thread, type);
942  if (!exp_extractor) {
944  LLDB_LOG_ERROR(log, exp_extractor.takeError(),
945  "Extracting return value failed: {0}");
946  return ValueObjectSP();
947  }
948 
949  return exp_extractor.get().GetValue();
950 }
951 
953  Thread &thread, CompilerType &return_compiler_type) const {
954  return GetReturnValueObjectSimple(thread, return_compiler_type);
955 }
956 
958  unwind_plan.Clear();
959  unwind_plan.SetRegisterKind(eRegisterKindDWARF);
960 
961  uint32_t lr_reg_num;
962  uint32_t sp_reg_num;
963  uint32_t pc_reg_num;
964 
965  if (GetByteOrder() == lldb::eByteOrderLittle) {
966  lr_reg_num = ppc64le_dwarf::dwarf_lr_ppc64le;
967  sp_reg_num = ppc64le_dwarf::dwarf_r1_ppc64le;
968  pc_reg_num = ppc64le_dwarf::dwarf_pc_ppc64le;
969  } else {
970  lr_reg_num = ppc64_dwarf::dwarf_lr_ppc64;
971  sp_reg_num = ppc64_dwarf::dwarf_r1_ppc64;
972  pc_reg_num = ppc64_dwarf::dwarf_pc_ppc64;
973  }
974 
976 
977  // Our Call Frame Address is the stack pointer value
978  row->GetCFAValue().SetIsRegisterPlusOffset(sp_reg_num, 0);
979 
980  // The previous PC is in the LR
981  row->SetRegisterLocationToRegister(pc_reg_num, lr_reg_num, true);
982  unwind_plan.AppendRow(row);
983 
984  // All other registers are the same.
985 
986  unwind_plan.SetSourceName("ppc64 at-func-entry default");
987  unwind_plan.SetSourcedFromCompiler(eLazyBoolNo);
988 
989  return true;
990 }
991 
993  unwind_plan.Clear();
994  unwind_plan.SetRegisterKind(eRegisterKindDWARF);
995 
996  uint32_t sp_reg_num;
997  uint32_t pc_reg_num;
998  uint32_t cr_reg_num;
999 
1000  if (GetByteOrder() == lldb::eByteOrderLittle) {
1001  sp_reg_num = ppc64le_dwarf::dwarf_r1_ppc64le;
1002  pc_reg_num = ppc64le_dwarf::dwarf_lr_ppc64le;
1003  cr_reg_num = ppc64le_dwarf::dwarf_cr_ppc64le;
1004  } else {
1005  sp_reg_num = ppc64_dwarf::dwarf_r1_ppc64;
1006  pc_reg_num = ppc64_dwarf::dwarf_lr_ppc64;
1007  cr_reg_num = ppc64_dwarf::dwarf_cr_ppc64;
1008  }
1009 
1011  const int32_t ptr_size = 8;
1012  row->GetCFAValue().SetIsRegisterDereferenced(sp_reg_num);
1013 
1014  row->SetRegisterLocationToAtCFAPlusOffset(pc_reg_num, ptr_size * 2, true);
1015  row->SetRegisterLocationToIsCFAPlusOffset(sp_reg_num, 0, true);
1016  row->SetRegisterLocationToAtCFAPlusOffset(cr_reg_num, ptr_size, true);
1017 
1018  unwind_plan.AppendRow(row);
1019  unwind_plan.SetSourceName("ppc64 default unwind plan");
1020  unwind_plan.SetSourcedFromCompiler(eLazyBoolNo);
1022  unwind_plan.SetReturnAddressRegister(pc_reg_num);
1023  return true;
1024 }
1025 
1026 bool ABISysV_ppc64::RegisterIsVolatile(const RegisterInfo *reg_info) {
1027  return !RegisterIsCalleeSaved(reg_info);
1028 }
1029 
1030 // See "Register Usage" in the
1031 // "System V Application Binary Interface"
1032 // "64-bit PowerPC ELF Application Binary Interface Supplement" current version
1033 // is 2 released 2015 at
1034 // https://members.openpowerfoundation.org/document/dl/576
1035 bool ABISysV_ppc64::RegisterIsCalleeSaved(const RegisterInfo *reg_info) {
1036  if (reg_info) {
1037  // Preserved registers are :
1038  // r1,r2,r13-r31
1039  // cr2-cr4 (partially preserved)
1040  // f14-f31 (not yet)
1041  // v20-v31 (not yet)
1042  // vrsave (not yet)
1043 
1044  const char *name = reg_info->name;
1045  if (name[0] == 'r') {
1046  if ((name[1] == '1' || name[1] == '2') && name[2] == '\0')
1047  return true;
1048  if (name[1] == '1' && name[2] > '2')
1049  return true;
1050  if ((name[1] == '2' || name[1] == '3') && name[2] != '\0')
1051  return true;
1052  }
1053 
1054  if (name[0] == 'f' && name[1] >= '0' && name[2] <= '9') {
1055  if (name[2] == '\0')
1056  return false;
1057  if (name[1] == '1' && name[2] >= '4')
1058  return true;
1059  if ((name[1] == '2' || name[1] == '3') && name[2] != '\0')
1060  return true;
1061  }
1062 
1063  if (name[0] == 's' && name[1] == 'p' && name[2] == '\0') // sp
1064  return true;
1065  if (name[0] == 'f' && name[1] == 'p' && name[2] == '\0') // fp
1066  return false;
1067  if (name[0] == 'p' && name[1] == 'c' && name[2] == '\0') // pc
1068  return true;
1069  }
1070  return false;
1071 }
1072 
1074  PluginManager::RegisterPlugin(
1075  GetPluginNameStatic(), "System V ABI for ppc64 targets", CreateInstance);
1076 }
1077 
1079  PluginManager::UnregisterPlugin(CreateInstance);
1080 }
1081 
1083  static ConstString g_name("sysv-ppc64");
1084  return g_name;
1085 }
1086 
1087 // PluginInterface protocol
1088 
1090  return GetPluginNameStatic();
1091 }
1092 
size_t PutCString(llvm::StringRef cstr)
Output a C string to the stream.
Definition: Stream.cpp:61
#define LLDB_REGNUM_GENERIC_PC
Definition: lldb-defines.h:63
An data extractor class.
Definition: DataExtractor.h:47
void SetSourceName(const char *)
Definition: UnwindPlan.cpp:542
Enumerations for broadcasting.
Definition: SBLaunchInfo.h:14
#define LLDB_REGNUM_GENERIC_RA
Definition: lldb-defines.h:66
uint64_t ReadRegisterAsUnsigned(uint32_t reg, uint64_t fail_value)
static bool ReadIntegerArgument(Scalar &scalar, unsigned int bit_width, bool is_signed, Thread &thread, uint32_t *argument_register_ids, unsigned int &current_argument_register, addr_t &current_stack_argument)
uint32_t GetAsMemoryData(const RegisterInfo *reg_info, void *dst, uint32_t dst_len, lldb::ByteOrder dst_byte_order, Status &error) const
bool IsIntegerOrEnumerationType(bool &is_signed) const
uint64_t GetSP(uint64_t fail_value=LLDB_INVALID_ADDRESS)
void PutString(llvm::StringRef str)
Definition: Log.cpp:110
lldb::user_id_t GetID() const
Get accessor for the user ID.
Definition: UserID.h:49
An architecture specification class.
Definition: ArchSpec.h:32
uint32_t IsHomogeneousAggregate(CompilerType *base_type_ptr) const
void CalculateExecutionContext(ExecutionContext &exe_ctx) override
Reconstruct the object&#39;s execution context into sc.
Definition: Thread.cpp:1598
lldb_private::Status SetReturnValueObject(lldb::StackFrameSP &frame_sp, lldb::ValueObjectSP &new_value) override
uint32_t GetTypeInfo(CompilerType *pointee_or_element_compiler_type=nullptr) const
Value * GetValueAtIndex(size_t idx)
Definition: Value.cpp:701
"lldb/Target/ExecutionContext.h" A class that contains an execution context.
#define LLDB_REGNUM_GENERIC_SP
Definition: lldb-defines.h:64
size_t GetRedZoneSize() const override
#define LLDB_LOG(log,...)
Definition: Log.h:209
llvm::Optional< uint64_t > GetByteSize(ExecutionContextScope *exe_scope) const
Return the size of the type in bytes.
uint32_t GetNumChildren(bool omit_empty_base_classes, const ExecutionContext *exe_ctx) const
#define LLDB_LOG_ERROR(log, error,...)
Definition: Log.h:225
A subclass of DataBuffer that stores a data buffer on the heap.
#define LLDB_REGNUM_GENERIC_ARG1
Definition: lldb-defines.h:68
bool IsPointerType(CompilerType *pointee_type=nullptr) const
llvm::Triple & GetTriple()
Architecture triple accessor.
Definition: ArchSpec.h:431
static lldb::ABISP CreateInstance(lldb::ProcessSP process_sp, const lldb_private::ArchSpec &arch)
bool SignExtend(uint32_t bit_pos)
Definition: Scalar.cpp:2609
#define UINT32_MAX
Definition: lldb-defines.h:31
bool PrepareTrivialCall(lldb_private::Thread &thread, lldb::addr_t sp, lldb::addr_t functionAddress, lldb::addr_t returnAddress, llvm::ArrayRef< lldb::addr_t > args) const override
bool IsFloatingPointType(uint32_t &count, bool &is_complex) const
bool CreateFunctionEntryUnwindPlan(lldb_private::UnwindPlan &unwind_plan) override
static void Terminate()
uint64_t offset_t
Definition: lldb-types.h:87
Log * GetLogIfAllCategoriesSet(uint32_t mask)
Definition: Logging.cpp:57
TypeSystem * GetTypeSystem() const
Definition: CompilerType.h:150
std::shared_ptr< Row > RowSP
Definition: UnwindPlan.h:366
void AppendRow(const RowSP &row_sp)
Definition: UnwindPlan.cpp:355
lldb::ByteOrder GetByteOrder() const
Get the current byte order value.
llvm::StringRef GetString() const
virtual lldb::RegisterContextSP GetRegisterContext()=0
#define LOG_PREFIX
void SetErrorString(llvm::StringRef err_str)
Set the current error string to err_str.
Definition: Status.cpp:241
virtual const RegisterInfo * GetRegisterInfoAtIndex(size_t reg)=0
uint32_t GetPluginVersion() override
virtual bool ReadRegister(const RegisterInfo *reg_info, RegisterValue &reg_value)=0
bool RegisterIsCalleeSaved(const lldb_private::RegisterInfo *reg_info)
static void Initialize()
double GetDouble(lldb::offset_t *offset_ptr) const
struct _GPR GPR
const RegisterInfo * GetRegisterInfoByName(llvm::StringRef reg_name, uint32_t start_idx=0)
size_t Printf(const char *format,...) __attribute__((format(printf
Output printf formatted output to the stream.
Definition: Stream.cpp:106
const CompilerType & GetCompilerType()
Definition: Value.cpp:239
lldb::ValueObjectSP GetReturnValueObjectImpl(lldb_private::Thread &thread, lldb_private::CompilerType &type) const override
void SetRegisterKind(lldb::RegisterKind kind)
Definition: UnwindPlan.h:408
bool WriteRegisterFromUnsigned(uint32_t reg, uint64_t uval)
lldb::ProcessSP GetProcess() const
Definition: Thread.h:154
CompilerType GetChildCompilerTypeAtIndex(ExecutionContext *exe_ctx, size_t idx, bool transparent_pointers, bool omit_empty_base_classes, bool ignore_array_bounds, std::string &child_name, uint32_t &child_byte_size, int32_t &child_byte_offset, uint32_t &child_bitfield_bit_size, uint32_t &child_bitfield_bit_offset, bool &child_is_base_class, bool &child_is_deref_of_parent, ValueObject *valobj, uint64_t &language_flags) const
uint64_t GetMaxU64(lldb::offset_t *offset_ptr, size_t byte_size) const
Extract an unsigned integer of size byte_size from *offset_ptr.
bool CreateDefaultUnwindPlan(lldb_private::UnwindPlan &unwind_plan) override
const RegisterInfo * GetRegisterInfo(lldb::RegisterKind reg_kind, uint32_t reg_num)
void SetUnwindPlanValidAtAllInstructions(lldb_private::LazyBool valid_at_all_insn)
Definition: UnwindPlan.h:461
lldb::offset_t CopyByteOrderedData(lldb::offset_t src_offset, lldb::offset_t src_len, void *dst, lldb::offset_t dst_len, lldb::ByteOrder dst_byte_order) const
Copy dst_len bytes from *offset_ptr and ensure the copied data is treated as a value that can be swap...
static lldb_private::ConstString GetPluginNameStatic()
uint64_t addr_t
Definition: lldb-types.h:83
A uniqued constant string class.
Definition: ConstString.h:38
lldb_private::ConstString GetPluginName() override
bool Fail() const
Test for error condition.
Definition: Status.cpp:181
bool RegisterIsVolatile(const lldb_private::RegisterInfo *reg_info) override
llvm::Optional< uint64_t > GetBitSize(ExecutionContextScope *exe_scope) const
Return the size of the type in bits.
Definition: SBAddress.h:15
int SetErrorStringWithFormat(const char *format,...) __attribute__((format(printf
Set the current error string to a formatted error string.
Definition: Status.cpp:255
#define LIBLLDB_LOG_EXPRESSIONS
Definition: Logging.h:22
const Scalar & GetScalar() const
Definition: Value.h:178
const char * AsCString(const char *default_error_str="unknown error") const
Get the error string associated with the current error.
Definition: Status.cpp:130
lldb::ValueObjectSP GetReturnValueObjectSimple(lldb_private::Thread &thread, lldb_private::CompilerType &ast_type) const
const lldb_private::RegisterInfo * GetRegisterInfoArray(uint32_t &count) override
void Printf(const char *format,...) __attribute__((format(printf
Definition: Log.cpp:113
bool GetArgumentValues(lldb_private::Thread &thread, lldb_private::ValueList &values) const override
void SetSourcedFromCompiler(lldb_private::LazyBool from_compiler)
Definition: UnwindPlan.h:449
void SetReturnAddressRegister(uint32_t regnum)
Definition: UnwindPlan.h:410
An error handling class.
Definition: Status.h:44
struct _FPR FPR