File: ReflectionContext.cpp

package info (click to toggle)
swiftlang 6.0.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,519,992 kB
  • sloc: cpp: 9,107,863; ansic: 2,040,022; asm: 1,135,751; python: 296,500; objc: 82,456; f90: 60,502; lisp: 34,951; pascal: 19,946; sh: 18,133; perl: 7,482; ml: 4,937; javascript: 4,117; makefile: 3,840; awk: 3,535; xml: 914; fortran: 619; cs: 573; ruby: 573
file content (428 lines) | stat: -rw-r--r-- 17,163 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
//===-- ReflectionContext.cpp --------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

#include "ReflectionContextInterface.h"
#include "SwiftLanguageRuntimeImpl.h"
#include "lldb/Utility/LLDBLog.h"
#include "lldb/Utility/Log.h"
#include "swift/Demangling/Demangle.h"
#include "swift/RemoteInspection/DescriptorFinder.h"

using namespace lldb;
using namespace lldb_private;

namespace {

/// The descriptor finder needs to be an instance variable of the
/// TypeRefBuilder, but we would still want to swap out the descriptor finder,
/// as they are tied to each type system typeref's symbol file. This class's
/// only purpose is to allow this swapping.
struct DescriptorFinderForwarder : public swift::reflection::DescriptorFinder {
  DescriptorFinderForwarder() = default;
  ~DescriptorFinderForwarder() override = default;

  std::unique_ptr<swift::reflection::BuiltinTypeDescriptorBase>
  getBuiltinTypeDescriptor(const swift::reflection::TypeRef *TR) override {
    if (!m_descriptor_finders.empty() && shouldConsultDescriptorFinder())
      return m_descriptor_finders.back()->getBuiltinTypeDescriptor(TR);
    return nullptr;
  }

  std::unique_ptr<swift::reflection::FieldDescriptorBase>
  getFieldDescriptor(const swift::reflection::TypeRef *TR) override {
    if (!m_descriptor_finders.empty() && shouldConsultDescriptorFinder())
      return m_descriptor_finders.back()->getFieldDescriptor(TR);
    return nullptr;
  }

  std::unique_ptr<swift::reflection::MultiPayloadEnumDescriptorBase>
  getMultiPayloadEnumDescriptor(const swift::reflection::TypeRef *TR) override {
    if (!m_descriptor_finders.empty() && shouldConsultDescriptorFinder())
      return m_descriptor_finders.back()->getMultiPayloadEnumDescriptor(TR);
    return nullptr;
  }

  void PushExternalDescriptorFinder(
      swift::reflection::DescriptorFinder *descriptor_finder) {
    m_descriptor_finders.push_back(descriptor_finder);
  }

  void PopExternalDescriptorFinder() {
    assert(!m_descriptor_finders.empty() && "m_descriptor_finders is empty!");
    m_descriptor_finders.pop_back();
  }

  void SetImageAdded(bool image_added) {
    m_image_added |= image_added;
  }

private:
  bool shouldConsultDescriptorFinder() {
    switch (ModuleList::GetGlobalModuleListProperties()
                .GetSwiftEnableFullDwarfDebugging()) {
    case lldb_private::AutoBool::True:
      return true;
    case lldb_private::AutoBool::False:
      return false;
    case lldb_private::AutoBool::Auto:
      // Full DWARF debugging is auto-enabled if there is no reflection metadata
      // to read from.
      return !m_image_added;
    }
  }

  llvm::SmallVector<swift::reflection::DescriptorFinder *, 1>
      m_descriptor_finders;
  bool m_image_added = false;
};

/// An implementation of the generic ReflectionContextInterface that
/// is templatized on target pointer width and specialized to either
/// 32-bit or 64-bit pointers, with and without ObjC interoperability.
template <typename ReflectionContext>
class TargetReflectionContext : public ReflectionContextInterface {
  DescriptorFinderForwarder m_forwader;
  ReflectionContext m_reflection_ctx;
  swift::reflection::TypeConverter m_type_converter;

public:
  TargetReflectionContext(
      std::shared_ptr<swift::reflection::MemoryReader> reader,
      SwiftMetadataCache *swift_metadata_cache)
      : m_reflection_ctx(reader, swift_metadata_cache, &m_forwader),
        m_type_converter(m_reflection_ctx.getBuilder()) {}

  std::optional<uint32_t> AddImage(
      llvm::function_ref<std::pair<swift::remote::RemoteRef<void>, uint64_t>(
          swift::ReflectionSectionKind)>
          find_section,
      llvm::SmallVector<llvm::StringRef, 1> likely_module_names) override {
    auto id = m_reflection_ctx.addImage(find_section, likely_module_names);
    m_forwader.SetImageAdded(id.has_value());
    return id;
  }

  std::optional<uint32_t>
  AddImage(swift::remote::RemoteAddress image_start,
           llvm::SmallVector<llvm::StringRef, 1> likely_module_names) override {
    auto id = m_reflection_ctx.addImage(image_start, likely_module_names);
    m_forwader.SetImageAdded(id.has_value());
    return id;
  }

  std::optional<uint32_t> ReadELF(
      swift::remote::RemoteAddress ImageStart,
      std::optional<llvm::sys::MemoryBlock> FileBuffer,
      llvm::SmallVector<llvm::StringRef, 1> likely_module_names = {}) override {
    auto id = m_reflection_ctx.readELF(ImageStart, FileBuffer,
                                    likely_module_names);
    m_forwader.SetImageAdded(id.has_value());
    return id;
  }

  const swift::reflection::TypeRef *GetTypeRefOrNull(
      StringRef mangled_type_name,
      swift::reflection::DescriptorFinder *descriptor_finder) override {
    swift::Demangle::Demangler dem;
    swift::Demangle::NodePointer node = dem.demangleSymbol(mangled_type_name);
    const swift::reflection::TypeRef *type_ref =
        GetTypeRefOrNull(dem, node, descriptor_finder);
    if (!type_ref)
      LLDB_LOG(GetLog(LLDBLog::Types), "Could not find typeref for type {0}",
               mangled_type_name);
    return type_ref;
  }

  /// Sets the descriptor finder, and on scope exit clears it out.
  auto PushDescriptorFinderAndPopOnExit(
      swift::reflection::DescriptorFinder *descriptor_finder) {
    m_forwader.PushExternalDescriptorFinder(descriptor_finder);
    return llvm::make_scope_exit(
        [&]() { m_forwader.PopExternalDescriptorFinder(); });
  }

  const swift::reflection::TypeRef *GetTypeRefOrNull(
      swift::Demangle::Demangler &dem, swift::Demangle::NodePointer node,
      swift::reflection::DescriptorFinder *descriptor_finder) override {
    auto on_exit = PushDescriptorFinderAndPopOnExit(descriptor_finder);
    auto type_ref_or_err =
        swift::Demangle::decodeMangledType(m_reflection_ctx.getBuilder(), node);
    if (type_ref_or_err.isError()) {
      LLDB_LOG(GetLog(LLDBLog::Types),
               "Could not find typeref: decode mangled type failed. Error: {0}",
               type_ref_or_err.getError()->copyErrorString());
      return nullptr;
    }
    return type_ref_or_err.getType();
  }

  const swift::reflection::RecordTypeInfo *GetClassInstanceTypeInfo(
      const swift::reflection::TypeRef *type_ref,
      swift::remote::TypeInfoProvider *provider,
      swift::reflection::DescriptorFinder *descriptor_finder) override {
    auto on_exit = PushDescriptorFinderAndPopOnExit(descriptor_finder);
    if (!type_ref)
      return nullptr;

    auto start =
        m_reflection_ctx.computeUnalignedFieldStartOffset(type_ref, provider);
    if (!start) {
      if (auto *log = GetLog(LLDBLog::Types)) {
        std::stringstream ss;
        type_ref->dump(ss);
        LLDB_LOG(log, "Could not compute start field offset for typeref: ",
                 ss.str());
      }
      return nullptr;
    }

    return m_type_converter.getClassInstanceTypeInfo(type_ref, *start,
                                                     provider);
  }

  const swift::reflection::TypeInfo *
  GetTypeInfo(const swift::reflection::TypeRef *type_ref,
              swift::remote::TypeInfoProvider *provider,
              swift::reflection::DescriptorFinder *descriptor_finder) override {
    auto on_exit = PushDescriptorFinderAndPopOnExit(descriptor_finder);
    if (!type_ref)
      return nullptr;

    Log *log(GetLog(LLDBLog::Types));
    if (log && log->GetVerbose()) {
      std::stringstream ss;
      type_ref->dump(ss);
      LLDB_LOG(log,
               "[TargetReflectionContext[{0:x}]::getTypeInfo] Getting type "
               "info for typeref {1}",
               provider ? provider->getId() : 0, ss.str());
    }

    auto type_info = m_reflection_ctx.getTypeInfo(type_ref, provider);
    if (log && !type_info) {
      std::stringstream ss;
      type_ref->dump(ss);
      LLDB_LOG(log,
               "[TargetReflectionContext::getTypeInfo] Could not get "
               "type info for typeref {0}",
               ss.str());
    }

    if (type_info && log && log->GetVerbose()) {
      std::stringstream ss;
      type_info->dump(ss);
      LLDB_LOG(log,
               "[TargetReflectionContext::getTypeInfo] Found "
               "type info {0}",
               ss.str());
    }
    return type_info;
  }

  const swift::reflection::TypeInfo *GetTypeInfoFromInstance(
      lldb::addr_t instance, swift::remote::TypeInfoProvider *provider,
      swift::reflection::DescriptorFinder *descriptor_finder) override {
    auto on_exit = PushDescriptorFinderAndPopOnExit(descriptor_finder);
    return m_reflection_ctx.getInstanceTypeInfo(instance, provider);
  }

  swift::reflection::MemoryReader &GetReader() override {
    return m_reflection_ctx.getReader();
  }

  const swift::reflection::TypeRef *LookupSuperclass(
      const swift::reflection::TypeRef *tr,
      swift::reflection::DescriptorFinder *descriptor_finder) override {
    auto on_exit = PushDescriptorFinderAndPopOnExit(descriptor_finder);
    return m_reflection_ctx.getBuilder().lookupSuperclass(tr);
  }

  bool
  ForEachSuperClassType(swift::remote::TypeInfoProvider *tip,
                        swift::reflection::DescriptorFinder *descriptor_finder,
                        const swift::reflection::TypeRef *tr,
                        std::function<bool(SuperClassType)> fn) override {
    while (tr) {
      if (fn({[=]() -> const swift::reflection::RecordTypeInfo * {
                return GetRecordTypeInfo(tr, tip, descriptor_finder);
              },
              [=]() -> const swift::reflection::TypeRef * { return tr; }}))
        return true;

      tr = LookupSuperclass(tr, descriptor_finder);
    }
    return false;
  }

  bool
  ForEachSuperClassType(swift::remote::TypeInfoProvider *tip,
                        swift::reflection::DescriptorFinder *descriptor_finder,
                        lldb::addr_t pointer,
                        std::function<bool(SuperClassType)> fn) override {
    auto on_exit = PushDescriptorFinderAndPopOnExit(descriptor_finder);
    // Guard against faulty self-referential metadata.
    unsigned limit = 256;
    auto md_ptr = m_reflection_ctx.readMetadataFromInstance(pointer);
    if (!md_ptr)
      return false;

    // Class object.
    while (md_ptr && *md_ptr && --limit) {
      // Reading metadata is potentially expensive since (in a remote
      // debugging scenario it may even incur network traffic) so we
      // just return closures that the caller can use to query details
      // if they need them.'
      auto metadata = *md_ptr;
      if (fn({[=]() -> const swift::reflection::RecordTypeInfo * {
                auto *ti = m_reflection_ctx.getMetadataTypeInfo(metadata, tip);
                return llvm::dyn_cast_or_null<
                    swift::reflection::RecordTypeInfo>(ti);
              },
              [=]() -> const swift::reflection::TypeRef * {
                return m_reflection_ctx.readTypeFromMetadata(metadata);
              }}))
        return true;

      // Continue with the base class.
      md_ptr = m_reflection_ctx.readSuperClassFromClassMetadata(metadata);
    }
    return false;
  }

  std::optional<int32_t> ProjectEnumValue(
      swift::remote::RemoteAddress enum_addr,
      const swift::reflection::TypeRef *enum_type_ref,
      swift::remote::TypeInfoProvider *provider,
      swift::reflection::DescriptorFinder *descriptor_finder) override {
    auto on_exit = PushDescriptorFinderAndPopOnExit(descriptor_finder);
    int32_t case_idx;
    if (m_reflection_ctx.projectEnumValue(enum_addr, enum_type_ref, &case_idx,
                                          provider))
      return case_idx;
    return {};
  }

  std::optional<std::pair<const swift::reflection::TypeRef *,
                           swift::reflection::RemoteAddress>>
  ProjectExistentialAndUnwrapClass(
      swift::reflection::RemoteAddress existential_address,
      const swift::reflection::TypeRef &existential_tr,
      swift::reflection::DescriptorFinder *descriptor_finder) override {
    auto on_exit = PushDescriptorFinderAndPopOnExit(descriptor_finder);
    return m_reflection_ctx.projectExistentialAndUnwrapClass(
        existential_address, existential_tr);
  }

  const swift::reflection::TypeRef *
  ReadTypeFromMetadata(lldb::addr_t metadata_address,
                       swift::reflection::DescriptorFinder *descriptor_finder,
                       bool skip_artificial_subclasses) override {
    auto on_exit = PushDescriptorFinderAndPopOnExit(descriptor_finder);
    return m_reflection_ctx.readTypeFromMetadata(metadata_address,
                                                 skip_artificial_subclasses);
  }

  const swift::reflection::TypeRef *
  ReadTypeFromInstance(lldb::addr_t instance_address,
                       swift::reflection::DescriptorFinder *descriptor_finder,
                       bool skip_artificial_subclasses) override {
    auto on_exit = PushDescriptorFinderAndPopOnExit(descriptor_finder);
    auto metadata_address =
        m_reflection_ctx.readMetadataFromInstance(instance_address);
    if (!metadata_address) {
      LLDB_LOG(GetLog(LLDBLog::Types),
               "could not read heap metadata for object at {0:x}",
               instance_address);
      return nullptr;
    }

    return m_reflection_ctx.readTypeFromMetadata(*metadata_address,
                                                 skip_artificial_subclasses);
  }

  std::optional<bool> IsValueInlinedInExistentialContainer(
      swift::remote::RemoteAddress existential_address) override {
    return m_reflection_ctx.isValueInlinedInExistentialContainer(
        existential_address);
  }

  const swift::reflection::TypeRef *ApplySubstitutions(
      const swift::reflection::TypeRef *type_ref,
      swift::reflection::GenericArgumentMap substitutions,
      swift::reflection::DescriptorFinder *descriptor_finder) override {
    auto on_exit = PushDescriptorFinderAndPopOnExit(descriptor_finder);
    return type_ref->subst(m_reflection_ctx.getBuilder(), substitutions);
  }

  swift::remote::RemoteAbsolutePointer
  StripSignedPointer(swift::remote::RemoteAbsolutePointer pointer) override {
    return m_reflection_ctx.stripSignedPointer(pointer);
  }

private:
  /// Return a description of the layout of the record (classes, structs and
  /// tuples) type given its typeref.
  const swift::reflection::RecordTypeInfo *
  GetRecordTypeInfo(const swift::reflection::TypeRef *type_ref,
                    swift::remote::TypeInfoProvider *tip,
                    swift::reflection::DescriptorFinder *descriptor_finder) {
    auto *type_info = GetTypeInfo(type_ref, tip, descriptor_finder);
    if (auto record_type_info =
            llvm::dyn_cast_or_null<swift::reflection::RecordTypeInfo>(
                type_info))
      return record_type_info;
    if (llvm::isa_and_nonnull<swift::reflection::ReferenceTypeInfo>(type_info))
      return GetClassInstanceTypeInfo(type_ref, tip, descriptor_finder);
    if (auto *log = GetLog(LLDBLog::Types)) {
      std::stringstream ss;
      type_ref->dump(ss);
      LLDB_LOG(log, "Could not get record type info for typeref: ", ss.str());
    }
    return nullptr;
  }
};
} // namespace

namespace lldb_private {
std::unique_ptr<ReflectionContextInterface>
ReflectionContextInterface::CreateReflectionContext(
    uint8_t ptr_size, std::shared_ptr<swift::remote::MemoryReader> reader,
    bool ObjCInterop, SwiftMetadataCache *swift_metadata_cache) {
  using ReflectionContext32ObjCInterop =
      TargetReflectionContext<swift::reflection::ReflectionContext<
          swift::External<swift::WithObjCInterop<swift::RuntimeTarget<4>>>>>;
  using ReflectionContext32NoObjCInterop =
      TargetReflectionContext<swift::reflection::ReflectionContext<
          swift::External<swift::NoObjCInterop<swift::RuntimeTarget<4>>>>>;
  using ReflectionContext64ObjCInterop =
      TargetReflectionContext<swift::reflection::ReflectionContext<
          swift::External<swift::WithObjCInterop<swift::RuntimeTarget<8>>>>>;
  using ReflectionContext64NoObjCInterop =
      TargetReflectionContext<swift::reflection::ReflectionContext<
          swift::External<swift::NoObjCInterop<swift::RuntimeTarget<8>>>>>;
  if (ptr_size == 4) {
    if (ObjCInterop)
      return std::make_unique<ReflectionContext32ObjCInterop>(
          reader, swift_metadata_cache);
    return std::make_unique<ReflectionContext32NoObjCInterop>(
        reader, swift_metadata_cache);
  }
  if (ptr_size == 8) {
    if (ObjCInterop)
      return std::make_unique<ReflectionContext64ObjCInterop>(
          reader, swift_metadata_cache);
    return std::make_unique<ReflectionContext64NoObjCInterop>(
        reader, swift_metadata_cache);
  }
  return {};
}
} // namespace lldb_private