File: SwiftREPLMaterializer.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 (517 lines) | stat: -rw-r--r-- 17,317 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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
//===-- SwiftREPLMaterializer.cpp -------------------------------*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 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 "SwiftREPLMaterializer.h"
#include "SwiftASTManipulator.h"
#include "SwiftPersistentExpressionState.h"

#include "Plugins/LanguageRuntime/Swift/SwiftLanguageRuntime.h"
#include "lldb/Core/DumpDataExtractor.h"
#include "lldb/Core/ValueObjectConstResult.h"
#include "lldb/Expression/IRExecutionUnit.h"
#include "lldb/Expression/IRMemoryMap.h"
#include "lldb/Target/Target.h"
#include "lldb/Utility/Log.h"

#include "swift/Demangling/Demangle.h"

using namespace lldb_private;

static llvm::StringRef
GetNameOfDemangledVariable(swift::Demangle::NodePointer node_pointer) {
  if (!node_pointer ||
      node_pointer->getKind() != swift::Demangle::Node::Kind::Global)
    return llvm::StringRef();

  swift::Demangle::NodePointer variable_pointer =
      node_pointer->getFirstChild();

  if (!variable_pointer ||
      variable_pointer->getKind() != swift::Demangle::Node::Kind::Variable)
    return llvm::StringRef();

  for (swift::Demangle::NodePointer child : *variable_pointer) {
    if (child &&
        child->getKind() == swift::Demangle::Node::Kind::Identifier &&
        child->hasText()) {
      return child->getText();
    }
  }
  return llvm::StringRef();
}

/// Dereference global resilient values that are store in fixed-size
/// buffers, if the runtime says it's necessary.
static lldb::addr_t FixupResilientGlobal(lldb::addr_t var_addr,
                                         CompilerType compiler_type,
                                         IRExecutionUnit &execution_unit,
                                         lldb::ProcessSP process_sp,
                                         Status &error) {
  if (process_sp)
    if (auto *runtime = SwiftLanguageRuntime::Get(process_sp)) {
      if (!runtime->IsStoredInlineInBuffer(compiler_type)) {
        if (var_addr != LLDB_INVALID_ADDRESS) {
          size_t ptr_size = process_sp->GetAddressByteSize();
          llvm::SmallVector<uint8_t, 8> bytes;
          bytes.reserve(ptr_size);
          execution_unit.ReadMemory(bytes.data(), var_addr, ptr_size, error);
          if (error.Success())
            memcpy(&var_addr, bytes.data(), sizeof(var_addr));
        }
      }
    }
  return var_addr;
}

class EntityREPLResultVariable : public Materializer::Entity {
public:
  EntityREPLResultVariable(const CompilerType &type,
                           swift::ValueDecl *swift_decl,
                           SwiftREPLMaterializer *parent,
                           Materializer::PersistentVariableDelegate *delegate)
      : Entity(), m_type(type), m_parent(parent), m_swift_decl(swift_decl),
        m_temporary_allocation(LLDB_INVALID_ADDRESS),
        m_temporary_allocation_size(0), m_delegate(delegate) {
    // Hard-coding to maximum size of a pointer since all results are
    // materialized by reference
    m_size = 8;
    m_alignment = 8;
  }

  void Materialize(lldb::StackFrameSP &frame_sp, IRMemoryMap &map,
                   lldb::addr_t process_address, Status &err) override {
    // no action required
  }

  void MakeREPLResult(IRExecutionUnit &execution_unit, Status &err,
                      const IRExecutionUnit::JittedGlobalVariable *variable) {
    err.Clear();

    ExecutionContextScope *exe_scope =
        execution_unit.GetBestExecutionContextScope();

    if (!exe_scope) {
      err.SetErrorString("Couldn't dematerialize a result variable: invalid "
                         "execution context scope");
      return;
    }

    lldb::TargetSP target_sp = exe_scope->CalculateTarget();

    if (!target_sp) {
      err.SetErrorString("Couldn't dematerialize a result variable: no target");
      return;
    }

    lldb::LanguageType lang =
        (m_type.GetMinimumLanguage() == lldb::eLanguageTypeSwift)
            ? lldb::eLanguageTypeSwift
            : lldb::eLanguageTypeObjC_plus_plus;

    PersistentExpressionState *persistent_state =
        target_sp->GetPersistentExpressionStateForLanguage(lang);

    if (!persistent_state) {
      err.SetErrorString("Couldn't dematerialize a result variable: language "
                         "doesn't have persistent state");
      return;
    }

    ConstString name = m_delegate
                           ? m_delegate->GetName()
                           : persistent_state->GetNextPersistentVariableName();

    lldb::ExpressionVariableSP ret;

    ret = persistent_state
              ->CreatePersistentVariable(exe_scope, name, m_type,
                                         execution_unit.GetByteOrder(),
                                         execution_unit.GetAddressByteSize())
              ->shared_from_this();

    if (!ret) {
      err.SetErrorStringWithFormat("couldn't dematerialize a result variable: "
                                   "failed to make persistent variable %s",
                                   name.AsCString());
      return;
    }

    lldb::ProcessSP process_sp =
        execution_unit.GetBestExecutionContextScope()->CalculateProcess();

    ret->m_live_sp = ValueObjectConstResult::Create(
        exe_scope, m_type, name,
        variable ? variable->m_remote_addr : LLDB_INVALID_ADDRESS,
        eAddressTypeLoad, execution_unit.GetAddressByteSize());

    ret->ValueUpdated();

    if (variable) {
      const size_t pvar_byte_size = ret->GetByteSize().value_or(0);
      uint8_t *pvar_data = ret->GetValueBytes();

      Status read_error;
      // Handle resilient globals in fixed-size buffers.
      lldb::addr_t var_addr = variable->m_remote_addr;
      if (auto ast_ctx = m_type.GetTypeSystem()
                             .dyn_cast_or_null<SwiftASTContextForExpressions>())
        if (!ast_ctx->IsFixedSize(m_type))
          var_addr = FixupResilientGlobal(var_addr, m_type, execution_unit,
                                          process_sp, read_error);

      execution_unit.ReadMemory(pvar_data, var_addr, pvar_byte_size,
                                read_error);

      if (!read_error.Success()) {
        err.SetErrorString("Couldn't dematerialize a result variable: couldn't "
                           "read its memory");
        return;
      }
    }

    if (m_delegate) {
      m_delegate->DidDematerialize(ret);
    }

    // Register the variable with the persistent decls under the assumed,
    // just-generated name so it can be reused.

    if (m_swift_decl) {
      llvm::cast<SwiftPersistentExpressionState>(persistent_state)
          ->RegisterSwiftPersistentDeclAlias(
              {SwiftASTContext::GetSwiftASTContext(
                   &m_swift_decl->getASTContext()),
               m_swift_decl},
              name.GetStringRef());
    }

    return;
  }

  void Dematerialize(lldb::StackFrameSP &frame_sp, IRMemoryMap &map,
                     lldb::addr_t process_address, lldb::addr_t frame_top,
                     lldb::addr_t frame_bottom, Status &err) override {
    IRExecutionUnit *execution_unit =
        llvm::cast<SwiftREPLMaterializer>(m_parent)->GetExecutionUnit();

    if (!execution_unit) {
      return;
    }

    swift::Demangle::Context demangle_ctx;
    llvm::StringRef result_name = SwiftASTManipulator::GetResultName();

    for (const IRExecutionUnit::JittedGlobalVariable &variable :
         execution_unit->GetJittedGlobalVariables()) {
      auto *node_pointer = SwiftLanguageRuntime::DemangleSymbolAsNode(
          variable.m_name.GetStringRef(), demangle_ctx);

      llvm::StringRef variable_name = GetNameOfDemangledVariable(node_pointer);
      if (variable_name == result_name) {
        MakeREPLResult(*execution_unit, err, &variable);
        return;
      }

      demangle_ctx.clear();
    }

    std::optional<uint64_t> size =
        m_type.GetByteSize(execution_unit->GetBestExecutionContextScope());
    if (size && *size == 0) {
      MakeREPLResult(*execution_unit, err, nullptr);
      return;
    }

    err.SetErrorToGenericError();
    err.SetErrorStringWithFormat(
        "Couldn't dematerialize result: corresponding symbol wasn't found");
  }

  void DumpToLog(IRMemoryMap &map, lldb::addr_t process_address,
                 Log *log) override {
    StreamString dump_stream;

    const lldb::addr_t load_addr = process_address + m_offset;

    dump_stream.Printf("0x%" PRIx64 ": EntityResultVariable\n", load_addr);

    Status err;

    lldb::addr_t ptr = LLDB_INVALID_ADDRESS;

    {
      dump_stream.Printf("Pointer:\n");

      DataBufferHeap data(m_size, 0);

      map.ReadMemory(data.GetBytes(), load_addr, m_size, err);

      if (!err.Success()) {
        dump_stream.Printf("  <could not be read>\n");
      } else {
        DataExtractor extractor(data.GetBytes(), data.GetByteSize(),
                                map.GetByteOrder(), map.GetAddressByteSize());

        DumpHexBytes(&dump_stream, data.GetBytes(),
                               data.GetByteSize(), 16, load_addr);

        lldb::offset_t offset;

        ptr = extractor.GetAddress(&offset);

        dump_stream.PutChar('\n');
      }
    }

    if (m_temporary_allocation == LLDB_INVALID_ADDRESS) {
      dump_stream.Printf("Points to process memory:\n");
    } else {
      dump_stream.Printf("Temporary allocation:\n");
    }

    if (ptr == LLDB_INVALID_ADDRESS) {
      dump_stream.Printf("  <could not be be found>\n");
    } else {
      DataBufferHeap data(m_temporary_allocation_size, 0);

      map.ReadMemory(data.GetBytes(), m_temporary_allocation,
                     m_temporary_allocation_size, err);

      if (!err.Success()) {
        dump_stream.Printf("  <could not be read>\n");
      } else {
        DumpHexBytes(&dump_stream, data.GetBytes(),
                               data.GetByteSize(), 16, m_temporary_allocation);

        dump_stream.PutChar('\n');
      }
    }

    log->PutCString(dump_stream.GetData());
  }

  void Wipe(IRMemoryMap &map, lldb::addr_t process_address) override {
    m_temporary_allocation = LLDB_INVALID_ADDRESS;
    m_temporary_allocation_size = 0;
  }

private:
  CompilerType m_type;

  SwiftREPLMaterializer *m_parent;
  swift::ValueDecl *m_swift_decl; // only used for the REPL; nullptr otherwise

  lldb::addr_t m_temporary_allocation;
  size_t m_temporary_allocation_size;

  Materializer::PersistentVariableDelegate *m_delegate;
};

uint32_t SwiftREPLMaterializer::AddREPLResultVariable(
    const CompilerType &type, swift::ValueDecl *decl,
    PersistentVariableDelegate *delegate, Status &err) {
  EntityVector::iterator iter = m_entities.insert(m_entities.end(), EntityUP());

  iter->reset(new EntityREPLResultVariable(type, decl, this, delegate));
  uint32_t ret = AddStructMember(**iter);
  (*iter)->SetOffset(ret);

  return ret;
}

class EntityREPLPersistentVariable : public Materializer::Entity {
public:
  EntityREPLPersistentVariable(
      lldb::ExpressionVariableSP &persistent_variable_sp,
      SwiftREPLMaterializer *parent,
      Materializer::PersistentVariableDelegate *)
      : Entity(), m_persistent_variable_sp(persistent_variable_sp),
        m_parent(parent) {
    // Hard-coding to maximum size of a pointer since persistent variables are
    // materialized by reference
    m_size = 8;
    m_alignment = 8;
  }

  void Materialize(lldb::StackFrameSP &frame_sp, IRMemoryMap &map,
                   lldb::addr_t process_address, Status &err) override {
    // no action required
  }

  void Dematerialize(lldb::StackFrameSP &frame_sp, IRMemoryMap &map,
                     lldb::addr_t process_address, lldb::addr_t frame_top,
                     lldb::addr_t frame_bottom, Status &err) override {
    if (llvm::cast<SwiftExpressionVariable>(m_persistent_variable_sp.get())
            ->GetIsComputed())
      return;

    IRExecutionUnit *execution_unit = m_parent->GetExecutionUnit();

    if (!execution_unit) {
      return;
    }

    swift::Demangle::Context demangle_ctx;

    for (const IRExecutionUnit::JittedGlobalVariable &variable :
         execution_unit->GetJittedGlobalVariables()) {
      // e.g.
      // kind=Global
      //   kind=Variable
      //     kind=Module, text="lldb_expr_0"
      //     kind=Identifier, text="a"

      auto *node_pointer = SwiftLanguageRuntime::DemangleSymbolAsNode(
          variable.m_name.GetStringRef(), demangle_ctx);

      llvm::StringRef last_component = GetNameOfDemangledVariable(node_pointer);

      if (last_component.empty())
        continue;

      if (m_persistent_variable_sp->GetName().GetStringRef().equals(
              last_component)) {
        ExecutionContextScope *exe_scope =
            execution_unit->GetBestExecutionContextScope();

        if (!exe_scope) {
          err.SetErrorString("Couldn't dematerialize a persistent variable: "
                             "invalid execution context scope");
          return;
        }

        CompilerType compiler_type =
            m_persistent_variable_sp->GetCompilerType();

        m_persistent_variable_sp->m_live_sp = ValueObjectConstResult::Create(
            exe_scope, compiler_type, m_persistent_variable_sp->GetName(),
            variable.m_remote_addr, eAddressTypeLoad,
            execution_unit->GetAddressByteSize());

        // Read the contents of the spare memory area

        m_persistent_variable_sp->ValueUpdated();

        Status read_error;
        lldb::addr_t var_addr = variable.m_remote_addr;

        // Handle resilient globals in fixed-size buffers.
        if (Flags(m_persistent_variable_sp->m_flags)
            .Test(ExpressionVariable::EVIsSwiftFixedBuffer))
          var_addr =
              FixupResilientGlobal(var_addr, compiler_type, *execution_unit,
                                   exe_scope->CalculateProcess(), read_error);

        // FIXME: This may not work if the value is not bitwise-takable.
        execution_unit->ReadMemory(
            m_persistent_variable_sp->GetValueBytes(), var_addr,
            m_persistent_variable_sp->GetByteSize().value_or(0), read_error);

        if (!read_error.Success()) {
          err.SetErrorStringWithFormat(
              "couldn't read the contents of %s from memory: %s",
              m_persistent_variable_sp->GetName().GetCString(),
              read_error.AsCString());
          return;
        }

        m_persistent_variable_sp->m_flags &=
            ~ExpressionVariable::EVNeedsFreezeDry;

        return;
      }
      demangle_ctx.clear();
    }

    err.SetErrorToGenericError();
    err.SetErrorStringWithFormat(
        "Couldn't dematerialize %s: corresponding symbol wasn't found",
        m_persistent_variable_sp->GetName().GetCString());
  }

  void DumpToLog(IRMemoryMap &map, lldb::addr_t process_address,
                 Log *log) override {
    StreamString dump_stream;

    Status err;

    const lldb::addr_t load_addr = process_address + m_offset;

    dump_stream.Printf("0x%" PRIx64 ": EntityPersistentVariable (%s)\n",
                       load_addr,
                       m_persistent_variable_sp->GetName().AsCString());

    {
      dump_stream.Printf("Pointer:\n");

      DataBufferHeap data(m_size, 0);

      map.ReadMemory(data.GetBytes(), load_addr, m_size, err);

      if (!err.Success()) {
        dump_stream.Printf("  <could not be read>\n");
      } else {
        DumpHexBytes(&dump_stream, data.GetBytes(), data.GetByteSize(), 16,
                     load_addr);

        dump_stream.PutChar('\n');
      }
    }

    {
      dump_stream.Printf("Target:\n");

      lldb::addr_t target_address = LLDB_INVALID_ADDRESS;

      map.ReadPointerFromMemory(&target_address, load_addr, err);

      if (!err.Success()) {
        dump_stream.Printf("  <could not be read>\n");
      } else {
        DataBufferHeap data(m_persistent_variable_sp->GetByteSize().value_or(0),
                            0);

        map.ReadMemory(data.GetBytes(), target_address,
                       m_persistent_variable_sp->GetByteSize().value_or(0),
                       err);

        if (!err.Success()) {
          dump_stream.Printf("  <could not be read>\n");
        } else {
          DumpHexBytes(&dump_stream, data.GetBytes(), data.GetByteSize(), 16,
                       target_address);

          dump_stream.PutChar('\n');
        }
      }
    }

    log->PutCString(dump_stream.GetData());
  }

  void Wipe(IRMemoryMap &map, lldb::addr_t process_address) override {}

private:
  lldb::ExpressionVariableSP m_persistent_variable_sp;
  SwiftREPLMaterializer *m_parent;
};

uint32_t SwiftREPLMaterializer::AddPersistentVariable(
    lldb::ExpressionVariableSP &persistent_variable_sp,
    PersistentVariableDelegate *delegate, Status &err) {
  EntityVector::iterator iter = m_entities.insert(m_entities.end(), EntityUP());
  iter->reset(
      new EntityREPLPersistentVariable(persistent_variable_sp, this, delegate));
  uint32_t ret = AddStructMember(**iter);
  (*iter)->SetOffset(ret);
  return ret;
}