Coverage Report

Created: 2022-01-18 06:27

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