1 //===-- ABISysV_x86_64.cpp ------------------------------------------------===//
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_x86_64.h"
10 
11 #include "llvm/ADT/STLExtras.h"
12 #include "llvm/ADT/StringSwitch.h"
13 #include "llvm/ADT/Triple.h"
14 
15 #include "lldb/Core/Module.h"
16 #include "lldb/Core/PluginManager.h"
17 #include "lldb/Core/Value.h"
18 #include "lldb/Core/ValueObjectConstResult.h"
19 #include "lldb/Core/ValueObjectMemory.h"
20 #include "lldb/Core/ValueObjectRegister.h"
21 #include "lldb/Symbol/UnwindPlan.h"
22 #include "lldb/Target/Process.h"
23 #include "lldb/Target/RegisterContext.h"
24 #include "lldb/Target/StackFrame.h"
25 #include "lldb/Target/Target.h"
26 #include "lldb/Target/Thread.h"
27 #include "lldb/Utility/ConstString.h"
28 #include "lldb/Utility/DataExtractor.h"
29 #include "lldb/Utility/LLDBLog.h"
30 #include "lldb/Utility/Log.h"
31 #include "lldb/Utility/RegisterValue.h"
32 #include "lldb/Utility/Status.h"
33 
34 #include <vector>
35 
36 using namespace lldb;
37 using namespace lldb_private;
38 
39 LLDB_PLUGIN_DEFINE(ABISysV_x86_64)
40 
41 enum dwarf_regnums {
42   dwarf_rax = 0,
43   dwarf_rdx,
44   dwarf_rcx,
45   dwarf_rbx,
46   dwarf_rsi,
47   dwarf_rdi,
48   dwarf_rbp,
49   dwarf_rsp,
50   dwarf_r8,
51   dwarf_r9,
52   dwarf_r10,
53   dwarf_r11,
54   dwarf_r12,
55   dwarf_r13,
56   dwarf_r14,
57   dwarf_r15,
58   dwarf_rip,
59 };
60 
61 bool ABISysV_x86_64::GetPointerReturnRegister(const char *&name) {
62   name = "rax";
63   return true;
64 }
65 
66 size_t ABISysV_x86_64::GetRedZoneSize() const { return 128; }
67 
68 // Static Functions
69 
70 ABISP
71 ABISysV_x86_64::CreateInstance(lldb::ProcessSP process_sp, const ArchSpec &arch) {
72   const llvm::Triple::ArchType arch_type = arch.GetTriple().getArch();
73   const llvm::Triple::OSType os_type = arch.GetTriple().getOS();
74   const llvm::Triple::EnvironmentType os_env =
75       arch.GetTriple().getEnvironment();
76   if (arch_type == llvm::Triple::x86_64) {
77     switch(os_type) {
78     case llvm::Triple::OSType::IOS:
79     case llvm::Triple::OSType::TvOS:
80     case llvm::Triple::OSType::WatchOS:
81       switch (os_env) {
82       case llvm::Triple::EnvironmentType::MacABI:
83       case llvm::Triple::EnvironmentType::Simulator:
84       case llvm::Triple::EnvironmentType::UnknownEnvironment:
85         // UnknownEnvironment is needed for older compilers that don't
86         // support the simulator environment.
87         return ABISP(new ABISysV_x86_64(std::move(process_sp),
88                                         MakeMCRegisterInfo(arch)));
89       default:
90         return ABISP();
91       }
92     case llvm::Triple::OSType::Darwin:
93     case llvm::Triple::OSType::FreeBSD:
94     case llvm::Triple::OSType::Linux:
95     case llvm::Triple::OSType::MacOSX:
96     case llvm::Triple::OSType::NetBSD:
97     case llvm::Triple::OSType::Solaris:
98     case llvm::Triple::OSType::UnknownOS:
99       return ABISP(
100           new ABISysV_x86_64(std::move(process_sp), MakeMCRegisterInfo(arch)));
101     default:
102       return ABISP();
103     }
104   }
105   return ABISP();
106 }
107 
108 bool ABISysV_x86_64::PrepareTrivialCall(Thread &thread, addr_t sp,
109                                         addr_t func_addr, addr_t return_addr,
110                                         llvm::ArrayRef<addr_t> args) const {
111   Log *log = GetLog(LLDBLog::Expressions);
112 
113   if (log) {
114     StreamString s;
115     s.Printf("ABISysV_x86_64::PrepareTrivialCall (tid = 0x%" PRIx64
116              ", sp = 0x%" PRIx64 ", func_addr = 0x%" PRIx64
117              ", return_addr = 0x%" PRIx64,
118              thread.GetID(), (uint64_t)sp, (uint64_t)func_addr,
119              (uint64_t)return_addr);
120 
121     for (size_t i = 0; i < args.size(); ++i)
122       s.Printf(", arg%" PRIu64 " = 0x%" PRIx64, static_cast<uint64_t>(i + 1),
123                args[i]);
124     s.PutCString(")");
125     log->PutString(s.GetString());
126   }
127 
128   RegisterContext *reg_ctx = thread.GetRegisterContext().get();
129   if (!reg_ctx)
130     return false;
131 
132   const RegisterInfo *reg_info = nullptr;
133 
134   if (args.size() > 6) // TODO handle more than 6 arguments
135     return false;
136 
137   for (size_t i = 0; i < args.size(); ++i) {
138     reg_info = reg_ctx->GetRegisterInfo(eRegisterKindGeneric,
139                                         LLDB_REGNUM_GENERIC_ARG1 + i);
140     LLDB_LOGF(log, "About to write arg%" PRIu64 " (0x%" PRIx64 ") into %s",
141               static_cast<uint64_t>(i + 1), args[i], reg_info->name);
142     if (!reg_ctx->WriteRegisterFromUnsigned(reg_info, args[i]))
143       return false;
144   }
145 
146   // First, align the SP
147 
148   LLDB_LOGF(log, "16-byte aligning SP: 0x%" PRIx64 " to 0x%" PRIx64,
149             (uint64_t)sp, (uint64_t)(sp & ~0xfull));
150 
151   sp &= ~(0xfull); // 16-byte alignment
152 
153   sp -= 8;
154 
155   Status error;
156   const RegisterInfo *pc_reg_info =
157       reg_ctx->GetRegisterInfo(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
158   const RegisterInfo *sp_reg_info =
159       reg_ctx->GetRegisterInfo(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_SP);
160   ProcessSP process_sp(thread.GetProcess());
161 
162   RegisterValue reg_value;
163   LLDB_LOGF(log,
164             "Pushing the return address onto the stack: 0x%" PRIx64
165             ": 0x%" PRIx64,
166             (uint64_t)sp, (uint64_t)return_addr);
167 
168   // Save return address onto the stack
169   if (!process_sp->WritePointerToMemory(sp, return_addr, error))
170     return false;
171 
172   // %rsp is set to the actual stack value.
173 
174   LLDB_LOGF(log, "Writing SP: 0x%" PRIx64, (uint64_t)sp);
175 
176   if (!reg_ctx->WriteRegisterFromUnsigned(sp_reg_info, sp))
177     return false;
178 
179   // %rip is set to the address of the called function.
180 
181   LLDB_LOGF(log, "Writing IP: 0x%" PRIx64, (uint64_t)func_addr);
182 
183   if (!reg_ctx->WriteRegisterFromUnsigned(pc_reg_info, func_addr))
184     return false;
185 
186   return true;
187 }
188 
189 static bool ReadIntegerArgument(Scalar &scalar, unsigned int bit_width,
190                                 bool is_signed, Thread &thread,
191                                 uint32_t *argument_register_ids,
192                                 unsigned int &current_argument_register,
193                                 addr_t &current_stack_argument) {
194   if (bit_width > 64)
195     return false; // Scalar can't hold large integer arguments
196 
197   if (current_argument_register < 6) {
198     scalar = thread.GetRegisterContext()->ReadRegisterAsUnsigned(
199         argument_register_ids[current_argument_register], 0);
200     current_argument_register++;
201     if (is_signed)
202       scalar.SignExtend(bit_width);
203   } else {
204     uint32_t byte_size = (bit_width + (8 - 1)) / 8;
205     Status error;
206     if (thread.GetProcess()->ReadScalarIntegerFromMemory(
207             current_stack_argument, byte_size, is_signed, scalar, error)) {
208       current_stack_argument += byte_size;
209       return true;
210     }
211     return false;
212   }
213   return true;
214 }
215 
216 bool ABISysV_x86_64::GetArgumentValues(Thread &thread,
217                                        ValueList &values) const {
218   unsigned int num_values = values.GetSize();
219   unsigned int value_index;
220 
221   // Extract the register context so we can read arguments from registers
222 
223   RegisterContext *reg_ctx = thread.GetRegisterContext().get();
224 
225   if (!reg_ctx)
226     return false;
227 
228   // Get the pointer to the first stack argument so we have a place to start
229   // when reading data
230 
231   addr_t sp = reg_ctx->GetSP(0);
232 
233   if (!sp)
234     return false;
235 
236   addr_t current_stack_argument = sp + 8; // jump over return address
237 
238   uint32_t argument_register_ids[6];
239 
240   argument_register_ids[0] =
241       reg_ctx->GetRegisterInfo(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_ARG1)
242           ->kinds[eRegisterKindLLDB];
243   argument_register_ids[1] =
244       reg_ctx->GetRegisterInfo(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_ARG2)
245           ->kinds[eRegisterKindLLDB];
246   argument_register_ids[2] =
247       reg_ctx->GetRegisterInfo(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_ARG3)
248           ->kinds[eRegisterKindLLDB];
249   argument_register_ids[3] =
250       reg_ctx->GetRegisterInfo(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_ARG4)
251           ->kinds[eRegisterKindLLDB];
252   argument_register_ids[4] =
253       reg_ctx->GetRegisterInfo(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_ARG5)
254           ->kinds[eRegisterKindLLDB];
255   argument_register_ids[5] =
256       reg_ctx->GetRegisterInfo(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_ARG6)
257           ->kinds[eRegisterKindLLDB];
258 
259   unsigned int current_argument_register = 0;
260 
261   for (value_index = 0; value_index < num_values; ++value_index) {
262     Value *value = values.GetValueAtIndex(value_index);
263 
264     if (!value)
265       return false;
266 
267     // We currently only support extracting values with Clang QualTypes. Do we
268     // care about others?
269     CompilerType compiler_type = value->GetCompilerType();
270     llvm::Optional<uint64_t> bit_size = compiler_type.GetBitSize(&thread);
271     if (!bit_size)
272       return false;
273     bool is_signed;
274 
275     if (compiler_type.IsIntegerOrEnumerationType(is_signed)) {
276       ReadIntegerArgument(value->GetScalar(), *bit_size, is_signed, thread,
277                           argument_register_ids, current_argument_register,
278                           current_stack_argument);
279     } else if (compiler_type.IsPointerType()) {
280       ReadIntegerArgument(value->GetScalar(), *bit_size, false, thread,
281                           argument_register_ids, current_argument_register,
282                           current_stack_argument);
283     }
284   }
285 
286   return true;
287 }
288 
289 Status ABISysV_x86_64::SetReturnValueObject(lldb::StackFrameSP &frame_sp,
290                                             lldb::ValueObjectSP &new_value_sp) {
291   Status error;
292   if (!new_value_sp) {
293     error.SetErrorString("Empty value object for return value.");
294     return error;
295   }
296 
297   CompilerType compiler_type = new_value_sp->GetCompilerType();
298   if (!compiler_type) {
299     error.SetErrorString("Null clang type for return value.");
300     return error;
301   }
302 
303   Thread *thread = frame_sp->GetThread().get();
304 
305   bool is_signed;
306   uint32_t count;
307   bool is_complex;
308 
309   RegisterContext *reg_ctx = thread->GetRegisterContext().get();
310 
311   bool set_it_simple = false;
312   if (compiler_type.IsIntegerOrEnumerationType(is_signed) ||
313       compiler_type.IsPointerType()) {
314     const RegisterInfo *reg_info = reg_ctx->GetRegisterInfoByName("rax", 0);
315 
316     DataExtractor data;
317     Status data_error;
318     size_t num_bytes = new_value_sp->GetData(data, data_error);
319     if (data_error.Fail()) {
320       error.SetErrorStringWithFormat(
321           "Couldn't convert return value to raw data: %s",
322           data_error.AsCString());
323       return error;
324     }
325     lldb::offset_t offset = 0;
326     if (num_bytes <= 8) {
327       uint64_t raw_value = data.GetMaxU64(&offset, num_bytes);
328 
329       if (reg_ctx->WriteRegisterFromUnsigned(reg_info, raw_value))
330         set_it_simple = true;
331     } else {
332       error.SetErrorString("We don't support returning longer than 64 bit "
333                            "integer values at present.");
334     }
335   } else if (compiler_type.IsFloatingPointType(count, is_complex)) {
336     if (is_complex)
337       error.SetErrorString(
338           "We don't support returning complex values at present");
339     else {
340       llvm::Optional<uint64_t> bit_width =
341           compiler_type.GetBitSize(frame_sp.get());
342       if (!bit_width) {
343         error.SetErrorString("can't get type size");
344         return error;
345       }
346       if (*bit_width <= 64) {
347         const RegisterInfo *xmm0_info =
348             reg_ctx->GetRegisterInfoByName("xmm0", 0);
349         RegisterValue xmm0_value;
350         DataExtractor data;
351         Status data_error;
352         size_t num_bytes = new_value_sp->GetData(data, data_error);
353         if (data_error.Fail()) {
354           error.SetErrorStringWithFormat(
355               "Couldn't convert return value to raw data: %s",
356               data_error.AsCString());
357           return error;
358         }
359 
360         unsigned char buffer[16];
361         ByteOrder byte_order = data.GetByteOrder();
362 
363         data.CopyByteOrderedData(0, num_bytes, buffer, 16, byte_order);
364         xmm0_value.SetBytes(buffer, 16, byte_order);
365         reg_ctx->WriteRegister(xmm0_info, xmm0_value);
366         set_it_simple = true;
367       } else {
368         // FIXME - don't know how to do 80 bit long doubles yet.
369         error.SetErrorString(
370             "We don't support returning float values > 64 bits at present");
371       }
372     }
373   }
374 
375   if (!set_it_simple) {
376     // Okay we've got a structure or something that doesn't fit in a simple
377     // register. We should figure out where it really goes, but we don't
378     // support this yet.
379     error.SetErrorString("We only support setting simple integer and float "
380                          "return types at present.");
381   }
382 
383   return error;
384 }
385 
386 ValueObjectSP ABISysV_x86_64::GetReturnValueObjectSimple(
387     Thread &thread, CompilerType &return_compiler_type) const {
388   ValueObjectSP return_valobj_sp;
389   Value value;
390 
391   if (!return_compiler_type)
392     return return_valobj_sp;
393 
394   // value.SetContext (Value::eContextTypeClangType, return_value_type);
395   value.SetCompilerType(return_compiler_type);
396 
397   RegisterContext *reg_ctx = thread.GetRegisterContext().get();
398   if (!reg_ctx)
399     return return_valobj_sp;
400 
401   const uint32_t type_flags = return_compiler_type.GetTypeInfo();
402   if (type_flags & eTypeIsScalar) {
403     value.SetValueType(Value::ValueType::Scalar);
404 
405     bool success = false;
406     if (type_flags & eTypeIsInteger) {
407       // Extract the register context so we can read arguments from registers
408 
409       llvm::Optional<uint64_t> byte_size =
410           return_compiler_type.GetByteSize(&thread);
411       if (!byte_size)
412         return return_valobj_sp;
413       uint64_t raw_value = thread.GetRegisterContext()->ReadRegisterAsUnsigned(
414           reg_ctx->GetRegisterInfoByName("rax", 0), 0);
415       const bool is_signed = (type_flags & eTypeIsSigned) != 0;
416       switch (*byte_size) {
417       default:
418         break;
419 
420       case sizeof(uint64_t):
421         if (is_signed)
422           value.GetScalar() = (int64_t)(raw_value);
423         else
424           value.GetScalar() = (uint64_t)(raw_value);
425         success = true;
426         break;
427 
428       case sizeof(uint32_t):
429         if (is_signed)
430           value.GetScalar() = (int32_t)(raw_value & UINT32_MAX);
431         else
432           value.GetScalar() = (uint32_t)(raw_value & UINT32_MAX);
433         success = true;
434         break;
435 
436       case sizeof(uint16_t):
437         if (is_signed)
438           value.GetScalar() = (int16_t)(raw_value & UINT16_MAX);
439         else
440           value.GetScalar() = (uint16_t)(raw_value & UINT16_MAX);
441         success = true;
442         break;
443 
444       case sizeof(uint8_t):
445         if (is_signed)
446           value.GetScalar() = (int8_t)(raw_value & UINT8_MAX);
447         else
448           value.GetScalar() = (uint8_t)(raw_value & UINT8_MAX);
449         success = true;
450         break;
451       }
452     } else if (type_flags & eTypeIsFloat) {
453       if (type_flags & eTypeIsComplex) {
454         // Don't handle complex yet.
455       } else {
456         llvm::Optional<uint64_t> byte_size =
457             return_compiler_type.GetByteSize(&thread);
458         if (byte_size && *byte_size <= sizeof(long double)) {
459           const RegisterInfo *xmm0_info =
460               reg_ctx->GetRegisterInfoByName("xmm0", 0);
461           RegisterValue xmm0_value;
462           if (reg_ctx->ReadRegister(xmm0_info, xmm0_value)) {
463             DataExtractor data;
464             if (xmm0_value.GetData(data)) {
465               lldb::offset_t offset = 0;
466               if (*byte_size == sizeof(float)) {
467                 value.GetScalar() = (float)data.GetFloat(&offset);
468                 success = true;
469               } else if (*byte_size == sizeof(double)) {
470                 value.GetScalar() = (double)data.GetDouble(&offset);
471                 success = true;
472               } else if (*byte_size == sizeof(long double)) {
473                 // Don't handle long double since that can be encoded as 80 bit
474                 // floats...
475               }
476             }
477           }
478         }
479       }
480     }
481 
482     if (success)
483       return_valobj_sp = ValueObjectConstResult::Create(
484           thread.GetStackFrameAtIndex(0).get(), value, ConstString(""));
485   } else if (type_flags & eTypeIsPointer) {
486     unsigned rax_id =
487         reg_ctx->GetRegisterInfoByName("rax", 0)->kinds[eRegisterKindLLDB];
488     value.GetScalar() =
489         (uint64_t)thread.GetRegisterContext()->ReadRegisterAsUnsigned(rax_id,
490                                                                       0);
491     value.SetValueType(Value::ValueType::Scalar);
492     return_valobj_sp = ValueObjectConstResult::Create(
493         thread.GetStackFrameAtIndex(0).get(), value, ConstString(""));
494   } else if (type_flags & eTypeIsVector) {
495     llvm::Optional<uint64_t> byte_size =
496         return_compiler_type.GetByteSize(&thread);
497     if (byte_size && *byte_size > 0) {
498       const RegisterInfo *altivec_reg =
499           reg_ctx->GetRegisterInfoByName("xmm0", 0);
500       if (altivec_reg == nullptr)
501         altivec_reg = reg_ctx->GetRegisterInfoByName("mm0", 0);
502 
503       if (altivec_reg) {
504         if (*byte_size <= altivec_reg->byte_size) {
505           ProcessSP process_sp(thread.GetProcess());
506           if (process_sp) {
507             std::unique_ptr<DataBufferHeap> heap_data_up(
508                 new DataBufferHeap(*byte_size, 0));
509             const ByteOrder byte_order = process_sp->GetByteOrder();
510             RegisterValue reg_value;
511             if (reg_ctx->ReadRegister(altivec_reg, reg_value)) {
512               Status error;
513               if (reg_value.GetAsMemoryData(
514                       altivec_reg, heap_data_up->GetBytes(),
515                       heap_data_up->GetByteSize(), byte_order, error)) {
516                 DataExtractor data(DataBufferSP(heap_data_up.release()),
517                                    byte_order,
518                                    process_sp->GetTarget()
519                                        .GetArchitecture()
520                                        .GetAddressByteSize());
521                 return_valobj_sp = ValueObjectConstResult::Create(
522                     &thread, return_compiler_type, ConstString(""), data);
523               }
524             }
525           }
526         } else if (*byte_size <= altivec_reg->byte_size * 2) {
527           const RegisterInfo *altivec_reg2 =
528               reg_ctx->GetRegisterInfoByName("xmm1", 0);
529           if (altivec_reg2) {
530             ProcessSP process_sp(thread.GetProcess());
531             if (process_sp) {
532               std::unique_ptr<DataBufferHeap> heap_data_up(
533                   new DataBufferHeap(*byte_size, 0));
534               const ByteOrder byte_order = process_sp->GetByteOrder();
535               RegisterValue reg_value;
536               RegisterValue reg_value2;
537               if (reg_ctx->ReadRegister(altivec_reg, reg_value) &&
538                   reg_ctx->ReadRegister(altivec_reg2, reg_value2)) {
539 
540                 Status error;
541                 if (reg_value.GetAsMemoryData(
542                         altivec_reg, heap_data_up->GetBytes(),
543                         altivec_reg->byte_size, byte_order, error) &&
544                     reg_value2.GetAsMemoryData(
545                         altivec_reg2,
546                         heap_data_up->GetBytes() + altivec_reg->byte_size,
547                         heap_data_up->GetByteSize() - altivec_reg->byte_size,
548                         byte_order, error)) {
549                   DataExtractor data(DataBufferSP(heap_data_up.release()),
550                                      byte_order,
551                                      process_sp->GetTarget()
552                                          .GetArchitecture()
553                                          .GetAddressByteSize());
554                   return_valobj_sp = ValueObjectConstResult::Create(
555                       &thread, return_compiler_type, ConstString(""), data);
556                 }
557               }
558             }
559           }
560         }
561       }
562     }
563   }
564 
565   return return_valobj_sp;
566 }
567 
568 // The compiler will flatten the nested aggregate type into single
569 // layer and push the value to stack
570 // This helper function will flatten an aggregate type
571 // and return true if it can be returned in register(s) by value
572 // return false if the aggregate is in memory
573 static bool FlattenAggregateType(
574     Thread &thread, ExecutionContext &exe_ctx,
575     CompilerType &return_compiler_type,
576     uint32_t data_byte_offset,
577     std::vector<uint32_t> &aggregate_field_offsets,
578     std::vector<CompilerType> &aggregate_compiler_types) {
579 
580   const uint32_t num_children = return_compiler_type.GetNumFields();
581   for (uint32_t idx = 0; idx < num_children; ++idx) {
582     std::string name;
583     bool is_signed;
584     uint32_t count;
585     bool is_complex;
586 
587     uint64_t field_bit_offset = 0;
588     CompilerType field_compiler_type = return_compiler_type.GetFieldAtIndex(
589         idx, name, &field_bit_offset, nullptr, nullptr);
590     llvm::Optional<uint64_t> field_bit_width =
591           field_compiler_type.GetBitSize(&thread);
592 
593     // if we don't know the size of the field (e.g. invalid type), exit
594     if (!field_bit_width || *field_bit_width == 0) {
595       return false;
596     }
597 
598     uint32_t field_byte_offset = field_bit_offset / 8 + data_byte_offset;
599 
600     const uint32_t field_type_flags = field_compiler_type.GetTypeInfo();
601     if (field_compiler_type.IsIntegerOrEnumerationType(is_signed) ||
602         field_compiler_type.IsPointerType() ||
603         field_compiler_type.IsFloatingPointType(count, is_complex)) {
604       aggregate_field_offsets.push_back(field_byte_offset);
605       aggregate_compiler_types.push_back(field_compiler_type);
606     } else if (field_type_flags & eTypeHasChildren) {
607       if (!FlattenAggregateType(thread, exe_ctx, field_compiler_type,
608                                 field_byte_offset, aggregate_field_offsets,
609                                 aggregate_compiler_types)) {
610         return false;
611       }
612     }
613   }
614   return true;
615 }
616 
617 ValueObjectSP ABISysV_x86_64::GetReturnValueObjectImpl(
618     Thread &thread, CompilerType &return_compiler_type) const {
619   ValueObjectSP return_valobj_sp;
620 
621   if (!return_compiler_type)
622     return return_valobj_sp;
623 
624   ExecutionContext exe_ctx(thread.shared_from_this());
625   return_valobj_sp = GetReturnValueObjectSimple(thread, return_compiler_type);
626   if (return_valobj_sp)
627     return return_valobj_sp;
628 
629   RegisterContextSP reg_ctx_sp = thread.GetRegisterContext();
630   if (!reg_ctx_sp)
631     return return_valobj_sp;
632 
633   llvm::Optional<uint64_t> bit_width = return_compiler_type.GetBitSize(&thread);
634   if (!bit_width)
635     return return_valobj_sp;
636   if (return_compiler_type.IsAggregateType()) {
637     Target *target = exe_ctx.GetTargetPtr();
638     bool is_memory = true;
639     std::vector<uint32_t> aggregate_field_offsets;
640     std::vector<CompilerType> aggregate_compiler_types;
641     if (return_compiler_type.GetTypeSystem()->CanPassInRegisters(
642           return_compiler_type) &&
643       *bit_width <= 128 &&
644       FlattenAggregateType(thread, exe_ctx, return_compiler_type,
645                           0, aggregate_field_offsets,
646                           aggregate_compiler_types)) {
647       ByteOrder byte_order = target->GetArchitecture().GetByteOrder();
648       WritableDataBufferSP data_sp(new DataBufferHeap(16, 0));
649       DataExtractor return_ext(data_sp, byte_order,
650                                target->GetArchitecture().GetAddressByteSize());
651 
652       const RegisterInfo *rax_info =
653           reg_ctx_sp->GetRegisterInfoByName("rax", 0);
654       const RegisterInfo *rdx_info =
655           reg_ctx_sp->GetRegisterInfoByName("rdx", 0);
656       const RegisterInfo *xmm0_info =
657           reg_ctx_sp->GetRegisterInfoByName("xmm0", 0);
658       const RegisterInfo *xmm1_info =
659           reg_ctx_sp->GetRegisterInfoByName("xmm1", 0);
660 
661       RegisterValue rax_value, rdx_value, xmm0_value, xmm1_value;
662       reg_ctx_sp->ReadRegister(rax_info, rax_value);
663       reg_ctx_sp->ReadRegister(rdx_info, rdx_value);
664       reg_ctx_sp->ReadRegister(xmm0_info, xmm0_value);
665       reg_ctx_sp->ReadRegister(xmm1_info, xmm1_value);
666 
667       DataExtractor rax_data, rdx_data, xmm0_data, xmm1_data;
668 
669       rax_value.GetData(rax_data);
670       rdx_value.GetData(rdx_data);
671       xmm0_value.GetData(xmm0_data);
672       xmm1_value.GetData(xmm1_data);
673 
674       uint32_t fp_bytes =
675           0; // Tracks how much of the xmm registers we've consumed so far
676       uint32_t integer_bytes =
677           0; // Tracks how much of the rax/rds registers we've consumed so far
678 
679       // in case of the returned type is a subclass of non-abstract-base class
680       // it will have a padding to skip the base content
681       if (aggregate_field_offsets.size()) {
682         fp_bytes = aggregate_field_offsets[0];
683         integer_bytes = aggregate_field_offsets[0];
684       }
685 
686       const uint32_t num_children = aggregate_compiler_types.size();
687 
688       // Since we are in the small struct regime, assume we are not in memory.
689       is_memory = false;
690       for (uint32_t idx = 0; idx < num_children; idx++) {
691         bool is_signed;
692         uint32_t count;
693         bool is_complex;
694 
695         CompilerType field_compiler_type = aggregate_compiler_types[idx];
696         uint32_t field_byte_width = (uint32_t) (*field_compiler_type.GetByteSize(&thread));
697         uint32_t field_byte_offset = aggregate_field_offsets[idx];
698 
699         uint32_t field_bit_width = field_byte_width * 8;
700 
701         DataExtractor *copy_from_extractor = nullptr;
702         uint32_t copy_from_offset = 0;
703 
704         if (field_compiler_type.IsIntegerOrEnumerationType(is_signed) ||
705             field_compiler_type.IsPointerType()) {
706           if (integer_bytes < 8) {
707             if (integer_bytes + field_byte_width <= 8) {
708               // This is in RAX, copy from register to our result structure:
709               copy_from_extractor = &rax_data;
710               copy_from_offset = integer_bytes;
711               integer_bytes += field_byte_width;
712             } else {
713               // The next field wouldn't fit in the remaining space, so we
714               // pushed it to rdx.
715               copy_from_extractor = &rdx_data;
716               copy_from_offset = 0;
717               integer_bytes = 8 + field_byte_width;
718             }
719           } else if (integer_bytes + field_byte_width <= 16) {
720             copy_from_extractor = &rdx_data;
721             copy_from_offset = integer_bytes - 8;
722             integer_bytes += field_byte_width;
723           } else {
724             // The last field didn't fit.  I can't see how that would happen
725             // w/o the overall size being greater than 16 bytes.  For now,
726             // return a nullptr return value object.
727             return return_valobj_sp;
728           }
729         } else if (field_compiler_type.IsFloatingPointType(count, is_complex)) {
730           // Structs with long doubles are always passed in memory.
731           if (field_bit_width == 128) {
732             is_memory = true;
733             break;
734           } else if (field_bit_width == 64) {
735             // These have to be in a single xmm register.
736             if (fp_bytes == 0)
737               copy_from_extractor = &xmm0_data;
738             else
739               copy_from_extractor = &xmm1_data;
740 
741             copy_from_offset = 0;
742             fp_bytes += field_byte_width;
743           } else if (field_bit_width == 32) {
744             // This one is kind of complicated.  If we are in an "eightbyte"
745             // with another float, we'll be stuffed into an xmm register with
746             // it.  If we are in an "eightbyte" with one or more ints, then we
747             // will be stuffed into the appropriate GPR with them.
748             bool in_gpr;
749             if (field_byte_offset % 8 == 0) {
750               // We are at the beginning of one of the eightbytes, so check the
751               // next element (if any)
752               if (idx == num_children - 1) {
753                 in_gpr = false;
754               } else {
755                 CompilerType next_field_compiler_type =
756                     aggregate_compiler_types[idx + 1];
757                 if (next_field_compiler_type.IsIntegerOrEnumerationType(
758                         is_signed)) {
759                   in_gpr = true;
760                 } else {
761                   copy_from_offset = 0;
762                   in_gpr = false;
763                 }
764               }
765             } else if (field_byte_offset % 4 == 0) {
766               // We are inside of an eightbyte, so see if the field before us
767               // is floating point: This could happen if somebody put padding
768               // in the structure.
769               if (idx == 0) {
770                 in_gpr = false;
771               } else {
772                 CompilerType prev_field_compiler_type =
773                     aggregate_compiler_types[idx - 1];
774                 if (prev_field_compiler_type.IsIntegerOrEnumerationType(
775                         is_signed)) {
776                   in_gpr = true;
777                 } else {
778                   copy_from_offset = 4;
779                   in_gpr = false;
780                 }
781               }
782             } else {
783               is_memory = true;
784               continue;
785             }
786 
787             // Okay, we've figured out whether we are in GPR or XMM, now figure
788             // out which one.
789             if (in_gpr) {
790               if (integer_bytes < 8) {
791                 // This is in RAX, copy from register to our result structure:
792                 copy_from_extractor = &rax_data;
793                 copy_from_offset = integer_bytes;
794                 integer_bytes += field_byte_width;
795               } else {
796                 copy_from_extractor = &rdx_data;
797                 copy_from_offset = integer_bytes - 8;
798                 integer_bytes += field_byte_width;
799               }
800             } else {
801               if (fp_bytes < 8)
802                 copy_from_extractor = &xmm0_data;
803               else
804                 copy_from_extractor = &xmm1_data;
805 
806               fp_bytes += field_byte_width;
807             }
808           }
809         }
810         // These two tests are just sanity checks.  If I somehow get the type
811         // calculation wrong above it is better to just return nothing than to
812         // assert or crash.
813         if (!copy_from_extractor)
814           return return_valobj_sp;
815         if (copy_from_offset + field_byte_width >
816             copy_from_extractor->GetByteSize())
817           return return_valobj_sp;
818         copy_from_extractor->CopyByteOrderedData(
819             copy_from_offset, field_byte_width,
820             data_sp->GetBytes() + field_byte_offset, field_byte_width,
821             byte_order);
822       }
823       if (!is_memory) {
824         // The result is in our data buffer.  Let's make a variable object out
825         // of it:
826         return_valobj_sp = ValueObjectConstResult::Create(
827             &thread, return_compiler_type, ConstString(""), return_ext);
828       }
829     }
830 
831     // FIXME: This is just taking a guess, rax may very well no longer hold the
832     // return storage location.
833     // If we are going to do this right, when we make a new frame we should
834     // check to see if it uses a memory return, and if we are at the first
835     // instruction and if so stash away the return location.  Then we would
836     // only return the memory return value if we know it is valid.
837 
838     if (is_memory) {
839       unsigned rax_id =
840           reg_ctx_sp->GetRegisterInfoByName("rax", 0)->kinds[eRegisterKindLLDB];
841       lldb::addr_t storage_addr =
842           (uint64_t)thread.GetRegisterContext()->ReadRegisterAsUnsigned(rax_id,
843                                                                         0);
844       return_valobj_sp = ValueObjectMemory::Create(
845           &thread, "", Address(storage_addr, nullptr), return_compiler_type);
846     }
847   }
848 
849   return return_valobj_sp;
850 }
851 
852 // This defines the CFA as rsp+8
853 // the saved pc is at CFA-8 (i.e. rsp+0)
854 // The saved rsp is CFA+0
855 
856 bool ABISysV_x86_64::CreateFunctionEntryUnwindPlan(UnwindPlan &unwind_plan) {
857   unwind_plan.Clear();
858   unwind_plan.SetRegisterKind(eRegisterKindDWARF);
859 
860   uint32_t sp_reg_num = dwarf_rsp;
861   uint32_t pc_reg_num = dwarf_rip;
862 
863   UnwindPlan::RowSP row(new UnwindPlan::Row);
864   row->GetCFAValue().SetIsRegisterPlusOffset(sp_reg_num, 8);
865   row->SetRegisterLocationToAtCFAPlusOffset(pc_reg_num, -8, false);
866   row->SetRegisterLocationToIsCFAPlusOffset(sp_reg_num, 0, true);
867   unwind_plan.AppendRow(row);
868   unwind_plan.SetSourceName("x86_64 at-func-entry default");
869   unwind_plan.SetSourcedFromCompiler(eLazyBoolNo);
870   return true;
871 }
872 
873 // This defines the CFA as rbp+16
874 // The saved pc is at CFA-8 (i.e. rbp+8)
875 // The saved rbp is at CFA-16 (i.e. rbp+0)
876 // The saved rsp is CFA+0
877 
878 bool ABISysV_x86_64::CreateDefaultUnwindPlan(UnwindPlan &unwind_plan) {
879   unwind_plan.Clear();
880   unwind_plan.SetRegisterKind(eRegisterKindDWARF);
881 
882   uint32_t fp_reg_num = dwarf_rbp;
883   uint32_t sp_reg_num = dwarf_rsp;
884   uint32_t pc_reg_num = dwarf_rip;
885 
886   UnwindPlan::RowSP row(new UnwindPlan::Row);
887 
888   const int32_t ptr_size = 8;
889   row->GetCFAValue().SetIsRegisterPlusOffset(dwarf_rbp, 2 * ptr_size);
890   row->SetOffset(0);
891   row->SetUnspecifiedRegistersAreUndefined(true);
892 
893   row->SetRegisterLocationToAtCFAPlusOffset(fp_reg_num, ptr_size * -2, true);
894   row->SetRegisterLocationToAtCFAPlusOffset(pc_reg_num, ptr_size * -1, true);
895   row->SetRegisterLocationToIsCFAPlusOffset(sp_reg_num, 0, true);
896 
897   unwind_plan.AppendRow(row);
898   unwind_plan.SetSourceName("x86_64 default unwind plan");
899   unwind_plan.SetSourcedFromCompiler(eLazyBoolNo);
900   unwind_plan.SetUnwindPlanValidAtAllInstructions(eLazyBoolNo);
901   unwind_plan.SetUnwindPlanForSignalTrap(eLazyBoolNo);
902   return true;
903 }
904 
905 bool ABISysV_x86_64::RegisterIsVolatile(const RegisterInfo *reg_info) {
906   return !RegisterIsCalleeSaved(reg_info);
907 }
908 
909 // See "Register Usage" in the
910 // "System V Application Binary Interface"
911 // "AMD64 Architecture Processor Supplement" (or "x86-64(tm) Architecture
912 // Processor Supplement" in earlier revisions) (this doc is also commonly
913 // referred to as the x86-64/AMD64 psABI) Edited by Michael Matz, Jan Hubicka,
914 // Andreas Jaeger, and Mark Mitchell current version is 0.99.6 released
915 // 2012-07-02 at http://refspecs.linuxfoundation.org/elf/x86-64-abi-0.99.pdf
916 // It's being revised & updated at https://github.com/hjl-tools/x86-psABI/
917 
918 bool ABISysV_x86_64::RegisterIsCalleeSaved(const RegisterInfo *reg_info) {
919   if (!reg_info)
920     return false;
921   assert(reg_info->name != nullptr && "unnamed register?");
922   std::string Name = std::string(reg_info->name);
923   bool IsCalleeSaved =
924       llvm::StringSwitch<bool>(Name)
925           .Cases("r12", "r13", "r14", "r15", "rbp", "ebp", "rbx", "ebx", true)
926           .Cases("rip", "eip", "rsp", "esp", "sp", "fp", "pc", true)
927           .Default(false);
928   return IsCalleeSaved;
929 }
930 
931 uint32_t ABISysV_x86_64::GetGenericNum(llvm::StringRef name) {
932   return llvm::StringSwitch<uint32_t>(name)
933       .Case("rip", LLDB_REGNUM_GENERIC_PC)
934       .Case("rsp", LLDB_REGNUM_GENERIC_SP)
935       .Case("rbp", LLDB_REGNUM_GENERIC_FP)
936       .Case("rflags", LLDB_REGNUM_GENERIC_FLAGS)
937       // gdbserver uses eflags
938       .Case("eflags", LLDB_REGNUM_GENERIC_FLAGS)
939       .Case("rdi", LLDB_REGNUM_GENERIC_ARG1)
940       .Case("rsi", LLDB_REGNUM_GENERIC_ARG2)
941       .Case("rdx", LLDB_REGNUM_GENERIC_ARG3)
942       .Case("rcx", LLDB_REGNUM_GENERIC_ARG4)
943       .Case("r8", LLDB_REGNUM_GENERIC_ARG5)
944       .Case("r9", LLDB_REGNUM_GENERIC_ARG6)
945       .Default(LLDB_INVALID_REGNUM);
946 }
947 
948 void ABISysV_x86_64::Initialize() {
949   PluginManager::RegisterPlugin(
950       GetPluginNameStatic(), "System V ABI for x86_64 targets", CreateInstance);
951 }
952 
953 void ABISysV_x86_64::Terminate() {
954   PluginManager::UnregisterPlugin(CreateInstance);
955 }
956