1 //===-- ABISysV_arm64.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_arm64.h"
10 
11 #include <vector>
12 
13 #include "llvm/ADT/STLExtras.h"
14 #include "llvm/ADT/Triple.h"
15 
16 #include "lldb/Core/Module.h"
17 #include "lldb/Core/PluginManager.h"
18 #include "lldb/Core/Value.h"
19 #include "lldb/Core/ValueObjectConstResult.h"
20 #include "lldb/Symbol/UnwindPlan.h"
21 #include "lldb/Target/Process.h"
22 #include "lldb/Target/RegisterContext.h"
23 #include "lldb/Target/Target.h"
24 #include "lldb/Target/Thread.h"
25 #include "lldb/Utility/ConstString.h"
26 #include "lldb/Utility/LLDBLog.h"
27 #include "lldb/Utility/Log.h"
28 #include "lldb/Utility/RegisterValue.h"
29 #include "lldb/Utility/Scalar.h"
30 #include "lldb/Utility/Status.h"
31 
32 #include "Utility/ARM64_DWARF_Registers.h"
33 
34 using namespace lldb;
35 using namespace lldb_private;
36 
37 bool ABISysV_arm64::GetPointerReturnRegister(const char *&name) {
38   name = "x0";
39   return true;
40 }
41 
42 size_t ABISysV_arm64::GetRedZoneSize() const { return 128; }
43 
44 // Static Functions
45 
46 ABISP
47 ABISysV_arm64::CreateInstance(lldb::ProcessSP process_sp, const ArchSpec &arch) {
48   const llvm::Triple::ArchType arch_type = arch.GetTriple().getArch();
49   const llvm::Triple::VendorType vendor_type = arch.GetTriple().getVendor();
50 
51   if (vendor_type != llvm::Triple::Apple) {
52     if (arch_type == llvm::Triple::aarch64 ||
53         arch_type == llvm::Triple::aarch64_32) {
54       return ABISP(
55           new ABISysV_arm64(std::move(process_sp), MakeMCRegisterInfo(arch)));
56     }
57   }
58 
59   return ABISP();
60 }
61 
62 bool ABISysV_arm64::PrepareTrivialCall(Thread &thread, addr_t sp,
63                                        addr_t func_addr, addr_t return_addr,
64                                        llvm::ArrayRef<addr_t> args) const {
65   RegisterContext *reg_ctx = thread.GetRegisterContext().get();
66   if (!reg_ctx)
67     return false;
68 
69   Log *log = GetLog(LLDBLog::Expressions);
70 
71   if (log) {
72     StreamString s;
73     s.Printf("ABISysV_arm64::PrepareTrivialCall (tid = 0x%" PRIx64
74              ", sp = 0x%" PRIx64 ", func_addr = 0x%" PRIx64
75              ", return_addr = 0x%" PRIx64,
76              thread.GetID(), (uint64_t)sp, (uint64_t)func_addr,
77              (uint64_t)return_addr);
78 
79     for (size_t i = 0; i < args.size(); ++i)
80       s.Printf(", arg%d = 0x%" PRIx64, static_cast<int>(i + 1), args[i]);
81     s.PutCString(")");
82     log->PutString(s.GetString());
83   }
84 
85   // x0 - x7 contain first 8 simple args
86   if (args.size() > 8)
87     return false;
88 
89   for (size_t i = 0; i < args.size(); ++i) {
90     const RegisterInfo *reg_info = reg_ctx->GetRegisterInfo(
91         eRegisterKindGeneric, LLDB_REGNUM_GENERIC_ARG1 + i);
92     LLDB_LOGF(log, "About to write arg%d (0x%" PRIx64 ") into %s",
93               static_cast<int>(i + 1), args[i], reg_info->name);
94     if (!reg_ctx->WriteRegisterFromUnsigned(reg_info, args[i]))
95       return false;
96   }
97 
98   // Set "lr" to the return address
99   if (!reg_ctx->WriteRegisterFromUnsigned(
100           reg_ctx->GetRegisterInfo(eRegisterKindGeneric,
101                                    LLDB_REGNUM_GENERIC_RA),
102           return_addr))
103     return false;
104 
105   // Set "sp" to the requested value
106   if (!reg_ctx->WriteRegisterFromUnsigned(
107           reg_ctx->GetRegisterInfo(eRegisterKindGeneric,
108                                    LLDB_REGNUM_GENERIC_SP),
109           sp))
110     return false;
111 
112   // Set "pc" to the address requested
113   if (!reg_ctx->WriteRegisterFromUnsigned(
114           reg_ctx->GetRegisterInfo(eRegisterKindGeneric,
115                                    LLDB_REGNUM_GENERIC_PC),
116           func_addr))
117     return false;
118 
119   return true;
120 }
121 
122 // TODO: We dont support fp/SIMD arguments in v0-v7
123 bool ABISysV_arm64::GetArgumentValues(Thread &thread, ValueList &values) const {
124   uint32_t num_values = values.GetSize();
125 
126   ExecutionContext exe_ctx(thread.shared_from_this());
127 
128   // Extract the register context so we can read arguments from registers
129 
130   RegisterContext *reg_ctx = thread.GetRegisterContext().get();
131 
132   if (!reg_ctx)
133     return false;
134 
135   addr_t sp = 0;
136 
137   for (uint32_t value_idx = 0; value_idx < num_values; ++value_idx) {
138     // We currently only support extracting values with Clang QualTypes. Do we
139     // care about others?
140     Value *value = values.GetValueAtIndex(value_idx);
141 
142     if (!value)
143       return false;
144 
145     CompilerType value_type = value->GetCompilerType();
146     if (value_type) {
147       bool is_signed = false;
148       size_t bit_width = 0;
149       llvm::Optional<uint64_t> bit_size = value_type.GetBitSize(&thread);
150       if (!bit_size)
151         return false;
152       if (value_type.IsIntegerOrEnumerationType(is_signed)) {
153         bit_width = *bit_size;
154       } else if (value_type.IsPointerOrReferenceType()) {
155         bit_width = *bit_size;
156       } else {
157         // We only handle integer, pointer and reference types currently...
158         return false;
159       }
160 
161       if (bit_width <= (exe_ctx.GetProcessRef().GetAddressByteSize() * 8)) {
162         if (value_idx < 8) {
163           // Arguments 1-8 are in x0-x7...
164           const RegisterInfo *reg_info = nullptr;
165           reg_info = reg_ctx->GetRegisterInfo(
166               eRegisterKindGeneric, LLDB_REGNUM_GENERIC_ARG1 + value_idx);
167 
168           if (reg_info) {
169             RegisterValue reg_value;
170 
171             if (reg_ctx->ReadRegister(reg_info, reg_value)) {
172               if (is_signed)
173                 reg_value.SignExtend(bit_width);
174               if (!reg_value.GetScalarValue(value->GetScalar()))
175                 return false;
176               continue;
177             }
178           }
179           return false;
180         } else {
181           // TODO: Verify for stack layout for SysV
182           if (sp == 0) {
183             // Read the stack pointer if we already haven't read it
184             sp = reg_ctx->GetSP(0);
185             if (sp == 0)
186               return false;
187           }
188 
189           // Arguments 5 on up are on the stack
190           const uint32_t arg_byte_size = (bit_width + (8 - 1)) / 8;
191           Status error;
192           if (!exe_ctx.GetProcessRef().ReadScalarIntegerFromMemory(
193                   sp, arg_byte_size, is_signed, value->GetScalar(), error))
194             return false;
195 
196           sp += arg_byte_size;
197           // Align up to the next 8 byte boundary if needed
198           if (sp % 8) {
199             sp >>= 3;
200             sp += 1;
201             sp <<= 3;
202           }
203         }
204       }
205     }
206   }
207   return true;
208 }
209 
210 Status ABISysV_arm64::SetReturnValueObject(lldb::StackFrameSP &frame_sp,
211                                            lldb::ValueObjectSP &new_value_sp) {
212   Status error;
213   if (!new_value_sp) {
214     error.SetErrorString("Empty value object for return value.");
215     return error;
216   }
217 
218   CompilerType return_value_type = new_value_sp->GetCompilerType();
219   if (!return_value_type) {
220     error.SetErrorString("Null clang type for return value.");
221     return error;
222   }
223 
224   Thread *thread = frame_sp->GetThread().get();
225 
226   RegisterContext *reg_ctx = thread->GetRegisterContext().get();
227 
228   if (reg_ctx) {
229     DataExtractor data;
230     Status data_error;
231     const uint64_t byte_size = new_value_sp->GetData(data, data_error);
232     if (data_error.Fail()) {
233       error.SetErrorStringWithFormat(
234           "Couldn't convert return value to raw data: %s",
235           data_error.AsCString());
236       return error;
237     }
238 
239     const uint32_t type_flags = return_value_type.GetTypeInfo(nullptr);
240     if (type_flags & eTypeIsScalar || type_flags & eTypeIsPointer) {
241       if (type_flags & eTypeIsInteger || type_flags & eTypeIsPointer) {
242         // Extract the register context so we can read arguments from registers
243         lldb::offset_t offset = 0;
244         if (byte_size <= 16) {
245           const RegisterInfo *x0_info = reg_ctx->GetRegisterInfo(
246               eRegisterKindGeneric, LLDB_REGNUM_GENERIC_ARG1);
247           if (byte_size <= 8) {
248             uint64_t raw_value = data.GetMaxU64(&offset, byte_size);
249 
250             if (!reg_ctx->WriteRegisterFromUnsigned(x0_info, raw_value))
251               error.SetErrorString("failed to write register x0");
252           } else {
253             uint64_t raw_value = data.GetMaxU64(&offset, 8);
254 
255             if (reg_ctx->WriteRegisterFromUnsigned(x0_info, raw_value)) {
256               const RegisterInfo *x1_info = reg_ctx->GetRegisterInfo(
257                   eRegisterKindGeneric, LLDB_REGNUM_GENERIC_ARG2);
258               raw_value = data.GetMaxU64(&offset, byte_size - offset);
259 
260               if (!reg_ctx->WriteRegisterFromUnsigned(x1_info, raw_value))
261                 error.SetErrorString("failed to write register x1");
262             }
263           }
264         } else {
265           error.SetErrorString("We don't support returning longer than 128 bit "
266                                "integer values at present.");
267         }
268       } else if (type_flags & eTypeIsFloat) {
269         if (type_flags & eTypeIsComplex) {
270           // Don't handle complex yet.
271           error.SetErrorString(
272               "returning complex float values are not supported");
273         } else {
274           const RegisterInfo *v0_info = reg_ctx->GetRegisterInfoByName("v0", 0);
275 
276           if (v0_info) {
277             if (byte_size <= 16) {
278               if (byte_size <= RegisterValue::GetMaxByteSize()) {
279                 RegisterValue reg_value;
280                 error = reg_value.SetValueFromData(v0_info, data, 0, true);
281                 if (error.Success()) {
282                   if (!reg_ctx->WriteRegister(v0_info, reg_value))
283                     error.SetErrorString("failed to write register v0");
284                 }
285               } else {
286                 error.SetErrorStringWithFormat(
287                     "returning float values with a byte size of %" PRIu64
288                     " are not supported",
289                     byte_size);
290               }
291             } else {
292               error.SetErrorString("returning float values longer than 128 "
293                                    "bits are not supported");
294             }
295           } else {
296             error.SetErrorString("v0 register is not available on this target");
297           }
298         }
299       }
300     } else if (type_flags & eTypeIsVector) {
301       if (byte_size > 0) {
302         const RegisterInfo *v0_info = reg_ctx->GetRegisterInfoByName("v0", 0);
303 
304         if (v0_info) {
305           if (byte_size <= v0_info->byte_size) {
306             RegisterValue reg_value;
307             error = reg_value.SetValueFromData(v0_info, data, 0, true);
308             if (error.Success()) {
309               if (!reg_ctx->WriteRegister(v0_info, reg_value))
310                 error.SetErrorString("failed to write register v0");
311             }
312           }
313         }
314       }
315     }
316   } else {
317     error.SetErrorString("no registers are available");
318   }
319 
320   return error;
321 }
322 
323 bool ABISysV_arm64::CreateFunctionEntryUnwindPlan(UnwindPlan &unwind_plan) {
324   unwind_plan.Clear();
325   unwind_plan.SetRegisterKind(eRegisterKindDWARF);
326 
327   uint32_t lr_reg_num = arm64_dwarf::lr;
328   uint32_t sp_reg_num = arm64_dwarf::sp;
329 
330   UnwindPlan::RowSP row(new UnwindPlan::Row);
331 
332   // Our previous Call Frame Address is the stack pointer
333   row->GetCFAValue().SetIsRegisterPlusOffset(sp_reg_num, 0);
334 
335   unwind_plan.AppendRow(row);
336   unwind_plan.SetReturnAddressRegister(lr_reg_num);
337 
338   // All other registers are the same.
339 
340   unwind_plan.SetSourceName("arm64 at-func-entry default");
341   unwind_plan.SetSourcedFromCompiler(eLazyBoolNo);
342   unwind_plan.SetUnwindPlanValidAtAllInstructions(eLazyBoolNo);
343   unwind_plan.SetUnwindPlanForSignalTrap(eLazyBoolNo);
344 
345   return true;
346 }
347 
348 bool ABISysV_arm64::CreateDefaultUnwindPlan(UnwindPlan &unwind_plan) {
349   unwind_plan.Clear();
350   unwind_plan.SetRegisterKind(eRegisterKindDWARF);
351 
352   uint32_t fp_reg_num = arm64_dwarf::fp;
353   uint32_t pc_reg_num = arm64_dwarf::pc;
354 
355   UnwindPlan::RowSP row(new UnwindPlan::Row);
356   const int32_t ptr_size = 8;
357 
358   row->GetCFAValue().SetIsRegisterPlusOffset(fp_reg_num, 2 * ptr_size);
359   row->SetOffset(0);
360   row->SetUnspecifiedRegistersAreUndefined(true);
361 
362   row->SetRegisterLocationToAtCFAPlusOffset(fp_reg_num, ptr_size * -2, true);
363   row->SetRegisterLocationToAtCFAPlusOffset(pc_reg_num, ptr_size * -1, true);
364 
365   unwind_plan.AppendRow(row);
366   unwind_plan.SetSourceName("arm64 default unwind plan");
367   unwind_plan.SetSourcedFromCompiler(eLazyBoolNo);
368   unwind_plan.SetUnwindPlanValidAtAllInstructions(eLazyBoolNo);
369   unwind_plan.SetUnwindPlanForSignalTrap(eLazyBoolNo);
370 
371   return true;
372 }
373 
374 // AAPCS64 (Procedure Call Standard for the ARM 64-bit Architecture) says
375 // registers x19 through x28 and sp are callee preserved. v8-v15 are non-
376 // volatile (and specifically only the lower 8 bytes of these regs), the rest
377 // of the fp/SIMD registers are volatile.
378 
379 // We treat x29 as callee preserved also, else the unwinder won't try to
380 // retrieve fp saves.
381 
382 bool ABISysV_arm64::RegisterIsVolatile(const RegisterInfo *reg_info) {
383   if (reg_info) {
384     const char *name = reg_info->name;
385 
386     // Sometimes we'll be called with the "alternate" name for these registers;
387     // recognize them as non-volatile.
388 
389     if (name[0] == 'p' && name[1] == 'c') // pc
390       return false;
391     if (name[0] == 'f' && name[1] == 'p') // fp
392       return false;
393     if (name[0] == 's' && name[1] == 'p') // sp
394       return false;
395     if (name[0] == 'l' && name[1] == 'r') // lr
396       return false;
397 
398     if (name[0] == 'x' || name[0] == 'r') {
399       // Volatile registers: x0-x18
400       // Although documentation says only x19-28 + sp are callee saved We ll
401       // also have to treat x30 as non-volatile. Each dwarf frame has its own
402       // value of lr. Return false for the non-volatile gpr regs, true for
403       // everything else
404       switch (name[1]) {
405       case '1':
406         switch (name[2]) {
407         case '9':
408           return false; // x19 is non-volatile
409         default:
410           return true;
411         }
412         break;
413       case '2':
414         switch (name[2]) {
415         case '0':
416         case '1':
417         case '2':
418         case '3':
419         case '4':
420         case '5':
421         case '6':
422         case '7':
423         case '8':
424           return false; // x20 - 28 are non-volatile
425         case '9':
426           return false; // x29 aka fp treat as non-volatile
427         default:
428           return true;
429         }
430       case '3': // x30 (lr) and x31 (sp) treat as non-volatile
431         if (name[2] == '0' || name[2] == '1')
432           return false;
433         break;
434       default:
435         return true; // all volatile cases not handled above fall here.
436       }
437     } else if (name[0] == 'v' || name[0] == 's' || name[0] == 'd') {
438       // Volatile registers: v0-7, v16-v31
439       // Return false for non-volatile fp/SIMD regs, true for everything else
440       switch (name[1]) {
441       case '8':
442       case '9':
443         return false; // v8-v9 are non-volatile
444       case '1':
445         switch (name[2]) {
446         case '0':
447         case '1':
448         case '2':
449         case '3':
450         case '4':
451         case '5':
452           return false; // v10-v15 are non-volatile
453         default:
454           return true;
455         }
456       default:
457         return true;
458       }
459     }
460   }
461   return true;
462 }
463 
464 static bool LoadValueFromConsecutiveGPRRegisters(
465     ExecutionContext &exe_ctx, RegisterContext *reg_ctx,
466     const CompilerType &value_type,
467     bool is_return_value, // false => parameter, true => return value
468     uint32_t &NGRN,       // NGRN (see ABI documentation)
469     uint32_t &NSRN,       // NSRN (see ABI documentation)
470     DataExtractor &data) {
471   llvm::Optional<uint64_t> byte_size =
472       value_type.GetByteSize(exe_ctx.GetBestExecutionContextScope());
473 
474   if (byte_size || *byte_size == 0)
475     return false;
476 
477   std::unique_ptr<DataBufferHeap> heap_data_up(
478       new DataBufferHeap(*byte_size, 0));
479   const ByteOrder byte_order = exe_ctx.GetProcessRef().GetByteOrder();
480   Status error;
481 
482   CompilerType base_type;
483   const uint32_t homogeneous_count =
484       value_type.IsHomogeneousAggregate(&base_type);
485   if (homogeneous_count > 0 && homogeneous_count <= 8) {
486     // Make sure we have enough registers
487     if (NSRN < 8 && (8 - NSRN) >= homogeneous_count) {
488       if (!base_type)
489         return false;
490       llvm::Optional<uint64_t> base_byte_size =
491           base_type.GetByteSize(exe_ctx.GetBestExecutionContextScope());
492       if (!base_byte_size)
493         return false;
494       uint32_t data_offset = 0;
495 
496       for (uint32_t i = 0; i < homogeneous_count; ++i) {
497         char v_name[8];
498         ::snprintf(v_name, sizeof(v_name), "v%u", NSRN);
499         const RegisterInfo *reg_info =
500             reg_ctx->GetRegisterInfoByName(v_name, 0);
501         if (reg_info == nullptr)
502           return false;
503 
504         if (*base_byte_size > reg_info->byte_size)
505           return false;
506 
507         RegisterValue reg_value;
508 
509         if (!reg_ctx->ReadRegister(reg_info, reg_value))
510           return false;
511 
512         // Make sure we have enough room in "heap_data_up"
513         if ((data_offset + *base_byte_size) <= heap_data_up->GetByteSize()) {
514           const size_t bytes_copied = reg_value.GetAsMemoryData(
515               reg_info, heap_data_up->GetBytes() + data_offset, *base_byte_size,
516               byte_order, error);
517           if (bytes_copied != *base_byte_size)
518             return false;
519           data_offset += bytes_copied;
520           ++NSRN;
521         } else
522           return false;
523       }
524       data.SetByteOrder(byte_order);
525       data.SetAddressByteSize(exe_ctx.GetProcessRef().GetAddressByteSize());
526       data.SetData(DataBufferSP(heap_data_up.release()));
527       return true;
528     }
529   }
530 
531   const size_t max_reg_byte_size = 16;
532   if (*byte_size <= max_reg_byte_size) {
533     size_t bytes_left = *byte_size;
534     uint32_t data_offset = 0;
535     while (data_offset < *byte_size) {
536       if (NGRN >= 8)
537         return false;
538 
539       const RegisterInfo *reg_info = reg_ctx->GetRegisterInfo(
540           eRegisterKindGeneric, LLDB_REGNUM_GENERIC_ARG1 + NGRN);
541       if (reg_info == nullptr)
542         return false;
543 
544       RegisterValue reg_value;
545 
546       if (!reg_ctx->ReadRegister(reg_info, reg_value))
547         return false;
548 
549       const size_t curr_byte_size = std::min<size_t>(8, bytes_left);
550       const size_t bytes_copied = reg_value.GetAsMemoryData(
551           reg_info, heap_data_up->GetBytes() + data_offset, curr_byte_size,
552           byte_order, error);
553       if (bytes_copied == 0)
554         return false;
555       if (bytes_copied >= bytes_left)
556         break;
557       data_offset += bytes_copied;
558       bytes_left -= bytes_copied;
559       ++NGRN;
560     }
561   } else {
562     const RegisterInfo *reg_info = nullptr;
563     if (is_return_value) {
564       // The SysV arm64 ABI doesn't require you to write the return location
565       // back to x8 before returning from the function the way the x86_64 ABI
566       // does.  It looks like all the users of this ABI currently choose not to
567       // do that, and so we can't reconstruct stack based returns on exit
568       // from the function.
569       return false;
570     } else {
571       // We are assuming we are stopped at the first instruction in a function
572       // and that the ABI is being respected so all parameters appear where
573       // they should be (functions with no external linkage can legally violate
574       // the ABI).
575       if (NGRN >= 8)
576         return false;
577 
578       reg_info = reg_ctx->GetRegisterInfo(eRegisterKindGeneric,
579                                           LLDB_REGNUM_GENERIC_ARG1 + NGRN);
580       if (reg_info == nullptr)
581         return false;
582       ++NGRN;
583     }
584 
585     if (reg_info == nullptr)
586       return false;
587 
588     const lldb::addr_t value_addr =
589         reg_ctx->ReadRegisterAsUnsigned(reg_info, LLDB_INVALID_ADDRESS);
590 
591     if (value_addr == LLDB_INVALID_ADDRESS)
592       return false;
593 
594     if (exe_ctx.GetProcessRef().ReadMemory(
595             value_addr, heap_data_up->GetBytes(), heap_data_up->GetByteSize(),
596             error) != heap_data_up->GetByteSize()) {
597       return false;
598     }
599   }
600 
601   data.SetByteOrder(byte_order);
602   data.SetAddressByteSize(exe_ctx.GetProcessRef().GetAddressByteSize());
603   data.SetData(DataBufferSP(heap_data_up.release()));
604   return true;
605 }
606 
607 ValueObjectSP ABISysV_arm64::GetReturnValueObjectImpl(
608     Thread &thread, CompilerType &return_compiler_type) const {
609   ValueObjectSP return_valobj_sp;
610   Value value;
611 
612   ExecutionContext exe_ctx(thread.shared_from_this());
613   if (exe_ctx.GetTargetPtr() == nullptr || exe_ctx.GetProcessPtr() == nullptr)
614     return return_valobj_sp;
615 
616   // value.SetContext (Value::eContextTypeClangType, return_compiler_type);
617   value.SetCompilerType(return_compiler_type);
618 
619   RegisterContext *reg_ctx = thread.GetRegisterContext().get();
620   if (!reg_ctx)
621     return return_valobj_sp;
622 
623   llvm::Optional<uint64_t> byte_size =
624       return_compiler_type.GetByteSize(&thread);
625   if (!byte_size)
626     return return_valobj_sp;
627 
628   const uint32_t type_flags = return_compiler_type.GetTypeInfo(nullptr);
629   if (type_flags & eTypeIsScalar || type_flags & eTypeIsPointer) {
630     value.SetValueType(Value::ValueType::Scalar);
631 
632     bool success = false;
633     if (type_flags & eTypeIsInteger || type_flags & eTypeIsPointer) {
634       // Extract the register context so we can read arguments from registers
635       if (*byte_size <= 8) {
636         const RegisterInfo *x0_reg_info = nullptr;
637         x0_reg_info = reg_ctx->GetRegisterInfo(eRegisterKindGeneric,
638                                                LLDB_REGNUM_GENERIC_ARG1);
639         if (x0_reg_info) {
640           uint64_t raw_value =
641               thread.GetRegisterContext()->ReadRegisterAsUnsigned(x0_reg_info,
642                                                                   0);
643           const bool is_signed = (type_flags & eTypeIsSigned) != 0;
644           switch (*byte_size) {
645           default:
646             break;
647           case 16: // uint128_t
648             // In register x0 and x1
649             {
650               const RegisterInfo *x1_reg_info = nullptr;
651               x1_reg_info = reg_ctx->GetRegisterInfo(eRegisterKindGeneric,
652                                                      LLDB_REGNUM_GENERIC_ARG2);
653 
654               if (x1_reg_info) {
655                 if (*byte_size <=
656                     x0_reg_info->byte_size + x1_reg_info->byte_size) {
657                   std::unique_ptr<DataBufferHeap> heap_data_up(
658                       new DataBufferHeap(*byte_size, 0));
659                   const ByteOrder byte_order =
660                       exe_ctx.GetProcessRef().GetByteOrder();
661                   RegisterValue x0_reg_value;
662                   RegisterValue x1_reg_value;
663                   if (reg_ctx->ReadRegister(x0_reg_info, x0_reg_value) &&
664                       reg_ctx->ReadRegister(x1_reg_info, x1_reg_value)) {
665                     Status error;
666                     if (x0_reg_value.GetAsMemoryData(
667                             x0_reg_info, heap_data_up->GetBytes() + 0, 8,
668                             byte_order, error) &&
669                         x1_reg_value.GetAsMemoryData(
670                             x1_reg_info, heap_data_up->GetBytes() + 8, 8,
671                             byte_order, error)) {
672                       DataExtractor data(
673                           DataBufferSP(heap_data_up.release()), byte_order,
674                           exe_ctx.GetProcessRef().GetAddressByteSize());
675 
676                       return_valobj_sp = ValueObjectConstResult::Create(
677                           &thread, return_compiler_type, ConstString(""), data);
678                       return return_valobj_sp;
679                     }
680                   }
681                 }
682               }
683             }
684             break;
685           case sizeof(uint64_t):
686             if (is_signed)
687               value.GetScalar() = (int64_t)(raw_value);
688             else
689               value.GetScalar() = (uint64_t)(raw_value);
690             success = true;
691             break;
692 
693           case sizeof(uint32_t):
694             if (is_signed)
695               value.GetScalar() = (int32_t)(raw_value & UINT32_MAX);
696             else
697               value.GetScalar() = (uint32_t)(raw_value & UINT32_MAX);
698             success = true;
699             break;
700 
701           case sizeof(uint16_t):
702             if (is_signed)
703               value.GetScalar() = (int16_t)(raw_value & UINT16_MAX);
704             else
705               value.GetScalar() = (uint16_t)(raw_value & UINT16_MAX);
706             success = true;
707             break;
708 
709           case sizeof(uint8_t):
710             if (is_signed)
711               value.GetScalar() = (int8_t)(raw_value & UINT8_MAX);
712             else
713               value.GetScalar() = (uint8_t)(raw_value & UINT8_MAX);
714             success = true;
715             break;
716           }
717         }
718       }
719     } else if (type_flags & eTypeIsFloat) {
720       if (type_flags & eTypeIsComplex) {
721         // Don't handle complex yet.
722       } else {
723         if (*byte_size <= sizeof(long double)) {
724           const RegisterInfo *v0_reg_info =
725               reg_ctx->GetRegisterInfoByName("v0", 0);
726           RegisterValue v0_value;
727           if (reg_ctx->ReadRegister(v0_reg_info, v0_value)) {
728             DataExtractor data;
729             if (v0_value.GetData(data)) {
730               lldb::offset_t offset = 0;
731               if (*byte_size == sizeof(float)) {
732                 value.GetScalar() = data.GetFloat(&offset);
733                 success = true;
734               } else if (*byte_size == sizeof(double)) {
735                 value.GetScalar() = data.GetDouble(&offset);
736                 success = true;
737               } else if (*byte_size == sizeof(long double)) {
738                 value.GetScalar() = data.GetLongDouble(&offset);
739                 success = true;
740               }
741             }
742           }
743         }
744       }
745     }
746 
747     if (success)
748       return_valobj_sp = ValueObjectConstResult::Create(
749           thread.GetStackFrameAtIndex(0).get(), value, ConstString(""));
750   } else if (type_flags & eTypeIsVector && *byte_size <= 16) {
751     if (*byte_size > 0) {
752       const RegisterInfo *v0_info = reg_ctx->GetRegisterInfoByName("v0", 0);
753 
754       if (v0_info) {
755         std::unique_ptr<DataBufferHeap> heap_data_up(
756             new DataBufferHeap(*byte_size, 0));
757         const ByteOrder byte_order = exe_ctx.GetProcessRef().GetByteOrder();
758         RegisterValue reg_value;
759         if (reg_ctx->ReadRegister(v0_info, reg_value)) {
760           Status error;
761           if (reg_value.GetAsMemoryData(v0_info, heap_data_up->GetBytes(),
762                                         heap_data_up->GetByteSize(), byte_order,
763                                         error)) {
764             DataExtractor data(DataBufferSP(heap_data_up.release()), byte_order,
765                                exe_ctx.GetProcessRef().GetAddressByteSize());
766             return_valobj_sp = ValueObjectConstResult::Create(
767                 &thread, return_compiler_type, ConstString(""), data);
768           }
769         }
770       }
771     }
772   } else if (type_flags & eTypeIsStructUnion || type_flags & eTypeIsClass ||
773              (type_flags & eTypeIsVector && *byte_size > 16)) {
774     DataExtractor data;
775 
776     uint32_t NGRN = 0; // Search ABI docs for NGRN
777     uint32_t NSRN = 0; // Search ABI docs for NSRN
778     const bool is_return_value = true;
779     if (LoadValueFromConsecutiveGPRRegisters(
780             exe_ctx, reg_ctx, return_compiler_type, is_return_value, NGRN, NSRN,
781             data)) {
782       return_valobj_sp = ValueObjectConstResult::Create(
783           &thread, return_compiler_type, ConstString(""), data);
784     }
785   }
786   return return_valobj_sp;
787 }
788 
789 lldb::addr_t ABISysV_arm64::FixAddress(addr_t pc, addr_t mask) {
790   lldb::addr_t pac_sign_extension = 0x0080000000000000ULL;
791   return (pc & pac_sign_extension) ? pc | mask : pc & (~mask);
792 }
793 
794 // Reads code or data address mask for the current Linux process.
795 static lldb::addr_t ReadLinuxProcessAddressMask(lldb::ProcessSP process_sp,
796                                                 llvm::StringRef reg_name) {
797   // 0 means there isn't a mask or it has not been read yet.
798   // We do not return the top byte mask unless thread_sp is valid.
799   // This prevents calls to this function before the thread is setup locking
800   // in the value to just the top byte mask, in cases where pointer
801   // authentication might also be active.
802   uint64_t address_mask = 0;
803   lldb::ThreadSP thread_sp = process_sp->GetThreadList().GetSelectedThread();
804   if (thread_sp) {
805     // Linux configures user-space virtual addresses with top byte ignored.
806     // We set default value of mask such that top byte is masked out.
807     address_mask = ~((1ULL << 56) - 1);
808     // If Pointer Authentication feature is enabled then Linux exposes
809     // PAC data and code mask register. Try reading relevant register
810     // below and merge it with default address mask calculated above.
811     lldb::RegisterContextSP reg_ctx_sp = thread_sp->GetRegisterContext();
812     if (reg_ctx_sp) {
813       const RegisterInfo *reg_info =
814           reg_ctx_sp->GetRegisterInfoByName(reg_name, 0);
815       if (reg_info) {
816         lldb::addr_t mask_reg_val = reg_ctx_sp->ReadRegisterAsUnsigned(
817             reg_info->kinds[eRegisterKindLLDB], LLDB_INVALID_ADDRESS);
818         if (mask_reg_val != LLDB_INVALID_ADDRESS)
819           address_mask |= mask_reg_val;
820       }
821     }
822   }
823   return address_mask;
824 }
825 
826 lldb::addr_t ABISysV_arm64::FixCodeAddress(lldb::addr_t pc) {
827   if (lldb::ProcessSP process_sp = GetProcessSP()) {
828     if (process_sp->GetTarget().GetArchitecture().GetTriple().isOSLinux() &&
829         !process_sp->GetCodeAddressMask())
830       process_sp->SetCodeAddressMask(
831           ReadLinuxProcessAddressMask(process_sp, "code_mask"));
832 
833     return FixAddress(pc, process_sp->GetCodeAddressMask());
834   }
835   return pc;
836 }
837 
838 lldb::addr_t ABISysV_arm64::FixDataAddress(lldb::addr_t pc) {
839   if (lldb::ProcessSP process_sp = GetProcessSP()) {
840     if (process_sp->GetTarget().GetArchitecture().GetTriple().isOSLinux() &&
841         !process_sp->GetDataAddressMask())
842       process_sp->SetDataAddressMask(
843           ReadLinuxProcessAddressMask(process_sp, "data_mask"));
844 
845     return FixAddress(pc, process_sp->GetDataAddressMask());
846   }
847   return pc;
848 }
849 
850 void ABISysV_arm64::Initialize() {
851   PluginManager::RegisterPlugin(GetPluginNameStatic(),
852                                 "SysV ABI for AArch64 targets", CreateInstance);
853 }
854 
855 void ABISysV_arm64::Terminate() {
856   PluginManager::UnregisterPlugin(CreateInstance);
857 }
858