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