File: LLDBMemoryReader.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 (731 lines) | stat: -rw-r--r-- 26,493 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
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
//===-- LLDBMemoryReader.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 "LLDBMemoryReader.h"
#include "lldb/Core/Address.h"
#include "lldb/Core/Section.h"
#include "lldb/Utility/LLDBLog.h"
#include "lldb/Utility/Log.h"

#include "llvm/Support/MathExtras.h"
#include "swift/Demangling/Demangle.h"

using namespace lldb;
using namespace lldb_private;

namespace lldb_private {
bool LLDBMemoryReader::queryDataLayout(DataLayoutQueryType type, void *inBuffer,
                                       void *outBuffer) {
  switch (type) {
  case DLQ_GetPtrAuthMask: {
    lldb::addr_t ptrauth_mask = m_process.GetDataAddressMask();
    if (ptrauth_mask == LLDB_INVALID_ADDRESS_MASK)
      return false;
    // The mask returned by the process masks out the non-addressable bits.
    uint64_t mask_pattern = ~ptrauth_mask;
    // LLDBMemoryReader sets LLDB_FILE_ADDRESS_BIT to distinguish process
    // addresses and file addresses that point into a reflection section on
    // disk. Setting the bit in the mask ensures it isn't accidentally cleared
    // by ptrauth stripping.
    mask_pattern |= LLDB_FILE_ADDRESS_BIT;
    memcpy(outBuffer, &mask_pattern, m_process.GetAddressByteSize());
    return true;
  }
  case DLQ_GetObjCReservedLowBits: {
    auto *result = static_cast<uint8_t *>(outBuffer);
    auto &triple = m_process.GetTarget().GetArchitecture().GetTriple();
    if (triple.isMacOSX() && triple.getArch() == llvm::Triple::x86_64) {
      // Obj-C reserves low bit on 64-bit Intel macOS only.
      // Other Apple platforms don't reserve this bit (even when
      // running on x86_64-based simulators).
      *result = 1;
    } else {
      *result = 0;
    }
    return true;
  }
  case DLQ_GetPointerSize: {
    auto *result = static_cast<uint8_t *>(outBuffer);
    *result = m_process.GetAddressByteSize();
    return true;
  }
  case DLQ_GetSizeSize: {
    auto *result = static_cast<uint8_t *>(outBuffer);
    *result = m_process.GetAddressByteSize(); // FIXME: sizeof(size_t)
    return true;
  }
  case DLQ_GetLeastValidPointerValue: {
    auto *result = (uint64_t *)outBuffer;
    auto &triple = m_process.GetTarget().GetArchitecture().GetTriple();
    if (triple.isOSDarwin() && triple.isArch64Bit())
      *result = 0x100000000;
    else
      *result = 0x1000;
    return true;
  }
  case DLQ_GetObjCInteropIsEnabled: {
    auto *result = (bool *)outBuffer;
    *result = SwiftLanguageRuntime::GetObjCRuntime(m_process) != nullptr;
    return true;
  }
  }
}

swift::remote::RemoteAddress
LLDBMemoryReader::getSymbolAddress(const std::string &name) {
  lldbassert(!name.empty());
  if (name.empty())
    return swift::remote::RemoteAddress(nullptr);

  Log *log = GetLog(LLDBLog::Types);

  LLDB_LOGV(log, "[MemoryReader] asked to retrieve the address of symbol {0}",
            name);

  ConstString name_cs(name.c_str(), name.size());
  SymbolContextList sc_list;
  m_process.GetTarget().GetImages().FindSymbolsWithNameAndType(
      name_cs, lldb::eSymbolTypeAny, sc_list);
  if (!sc_list.GetSize()) {
    LLDB_LOGV(log, "[MemoryReader] symbol resolution failed {0}", name);
    return swift::remote::RemoteAddress(nullptr);
  }

  SymbolContext sym_ctx;
  // Remove undefined symbols from the list.
  size_t num_sc_matches = sc_list.GetSize();
  if (num_sc_matches > 1) {
    SymbolContextList tmp_sc_list(sc_list);
    sc_list.Clear();
    for (size_t idx = 0; idx < num_sc_matches; idx++) {
      tmp_sc_list.GetContextAtIndex(idx, sym_ctx);
      if (sym_ctx.symbol &&
          sym_ctx.symbol->GetType() != lldb::eSymbolTypeUndefined) {
        sc_list.Append(sym_ctx);
      }
    }
  }
  if (sc_list.GetSize() == 1 && sc_list.GetContextAtIndex(0, sym_ctx)) {
    if (sym_ctx.symbol) {
      auto load_addr = sym_ctx.symbol->GetLoadAddress(&m_process.GetTarget());
      LLDB_LOGV(log, "[MemoryReader] symbol resolved to {0:x}", load_addr);
      return swift::remote::RemoteAddress(load_addr);
    }
  }

  // Empty list, resolution failed.
  if (sc_list.GetSize() == 0) {
    LLDB_LOGV(log, "[MemoryReader] symbol resolution failed {0}", name);
    return swift::remote::RemoteAddress(nullptr);
  }

  // If there's a single symbol, then we're golden. If there's more than
  // a symbol, then just make sure all of them agree on the value.
  Status error;
  auto load_addr = sym_ctx.symbol->GetLoadAddress(&m_process.GetTarget());
  uint64_t sym_value = m_process.GetTarget().ReadUnsignedIntegerFromMemory(
      load_addr, m_process.GetAddressByteSize(), 0, error, true);
  for (unsigned i = 1; i < sc_list.GetSize(); ++i) {
    uint64_t other_sym_value =
        m_process.GetTarget().ReadUnsignedIntegerFromMemory(
            load_addr, m_process.GetAddressByteSize(), 0, error, true);
    if (sym_value != other_sym_value) {
      LLDB_LOGV(log, "[MemoryReader] symbol resolution failed {0}", name);
      return swift::remote::RemoteAddress(nullptr);
    }
  }
  LLDB_LOGV(log, "[MemoryReader] symbol resolved to {0}", load_addr);
  return swift::remote::RemoteAddress(load_addr);
}

static std::unique_ptr<swift::SwiftObjectFileFormat>
GetSwiftObjectFileFormat(llvm::Triple::ObjectFormatType obj_format_type) {
  std::unique_ptr<swift::SwiftObjectFileFormat> obj_file_format;
  switch (obj_format_type) {
  case llvm::Triple::MachO:
    obj_file_format = std::make_unique<swift::SwiftObjectFileFormatMachO>();
    break;
  case llvm::Triple::ELF:
    obj_file_format = std::make_unique<swift::SwiftObjectFileFormatELF>();
    break;
  case llvm::Triple::COFF:
    obj_file_format = std::make_unique<swift::SwiftObjectFileFormatCOFF>();
    break;
  default:
    LLDB_LOG(GetLog(LLDBLog::Types), "Could not determine swift reflection "
                                     "section names for object format type");
    break;
  }
  return obj_file_format;
}

std::optional<swift::remote::RemoteAbsolutePointer>
LLDBMemoryReader::resolvePointerAsSymbol(swift::remote::RemoteAddress address) {
  // If an address has a symbol, that symbol provides additional useful data to
  // MetadataReader. Without the symbol, MetadataReader can derive the symbol
  // by loading other parts of reflection metadata, but that work has a cost.
  // For lldb, that data loading can be a significant performance hit. Providing
  // a symbol greatly reduces memory read traffic to the process.
  auto &target = m_process.GetTarget();
  if (!target.GetSwiftUseReflectionSymbols())
    return {};

  std::optional<Address> maybeAddr =
      resolveRemoteAddress(address.getAddressData());
  // This is not an assert, but should never happen.
  if (!maybeAddr)
    return {};

  Address addr;
  if (maybeAddr->IsSectionOffset()) {
    // `address` was tagged, and then successfully mapped (resolved).
    addr = *maybeAddr;
  } else {
    // `address` is a real load address.
    if (!target.ResolveLoadAddress(address.getAddressData(), addr))
      return {};
  }

  if (auto section_sp = addr.GetSection()) {
    if (auto *obj_file = section_sp->GetObjectFile()) {
      auto obj_file_format_type =
          obj_file->GetArchitecture().GetTriple().getObjectFormat();
      if (auto swift_obj_file_format =
              GetSwiftObjectFileFormat(obj_file_format_type)) {
        if (!swift_obj_file_format->sectionContainsReflectionData(
                section_sp->GetName().GetStringRef()))
          return {};
      }
    }
  }

  if (auto *symbol = addr.CalculateSymbolContextSymbol()) {
    auto mangledName = symbol->GetMangled().GetMangledName().GetStringRef();
    // MemoryReader requires this to be a Swift symbol. LLDB can also be
    // aware of local symbols, so avoid returning those.
    using namespace swift::Demangle;
    if (isSwiftSymbol(mangledName) && !isOldFunctionTypeMangling(mangledName))
      return {{mangledName, 0}};
  }

  return {};
}

swift::remote::RemoteAbsolutePointer
LLDBMemoryReader::resolvePointer(swift::remote::RemoteAddress address,
                                 uint64_t readValue) {
  Log *log = GetLog(LLDBLog::Types);

  // We may have gotten a pointer to a process address, try to map it back
  // to a tagged address so further memory reads originating from it benefit
  // from the file-cache optimization.
  swift::remote::RemoteAbsolutePointer process_pointer("", readValue);

  if (!readMetadataFromFileCacheEnabled())
    return process_pointer;

  // Try to strip the pointer before checking if we have it mapped.
  auto strippedPointer = signedPointerStripper(process_pointer);
  if (strippedPointer.isResolved())
    readValue = strippedPointer.getOffset();

  auto &target = m_process.GetTarget();
  Address addr;
  if (!target.ResolveLoadAddress(readValue, addr)) {
    LLDB_LOGV(log,
              "[MemoryReader] Could not resolve load address of pointer {0:x} "
              "read from {1:x}.",
              readValue, address.getAddressData());
    return process_pointer;
  }

  auto module_containing_pointer = addr.GetSection()->GetModule();

  // Check if the module containing the pointer is registered with
  // LLDBMemoryReader.
  auto pair_iterator = std::find_if(
      m_range_module_map.begin(), m_range_module_map.end(), [&](auto pair) {
        return std::get<ModuleSP>(pair) == module_containing_pointer;
      });

  // We haven't registered the image that contains the pointer.
  if (pair_iterator == m_range_module_map.end()) {
    LLDB_LOG(log,
             "[MemoryReader] Could not resolve find module containing pointer "
             "{0:x} read from {1:x}.",
             readValue, address.getAddressData());
    return process_pointer;
  }

  // If the containing image is the first registered one, the image's tagged
  // start address for it is the first tagged address. Otherwise, the previous
  // pair's address is the start tagged address.
  uint64_t start_tagged_address = pair_iterator == m_range_module_map.begin()
                                      ? LLDB_FILE_ADDRESS_BIT
                                      : std::prev(pair_iterator)->first;

  auto *section_list = module_containing_pointer->GetSectionList();
  if (section_list->GetSize() == 0) {
    LLDB_LOG(log,
             "[MemoryReader] Module with empty section list.");
    return {};
  }

  uint64_t tagged_address =
      start_tagged_address + addr.GetFileAddress() -
      section_list->GetSectionAtIndex(0)->GetFileAddress();

  if (tagged_address >= std::get<uint64_t>(*pair_iterator)) {
    // If the tagged address invades the next image's tagged address space,
    // something went wrong. Log it and just return the process address.
    LLDB_LOG(log,
             "[MemoryReader] Pointer {0:x} read from {1:x} resolved to tagged "
             "address {2:x}, which is outside its image address space.",
             readValue, address.getAddressData(), tagged_address);
    return process_pointer;
  }

  swift::remote::RemoteAbsolutePointer tagged_pointer("", tagged_address);
  if (tagged_address !=
      (uint64_t)signedPointerStripper(tagged_pointer).getOffset()) {
    lldb_assert(false, "Tagged pointer runs into pointer authentication mask!",
                __FUNCTION__, __FILE__, __LINE__);
    return process_pointer;
  }

  LLDB_LOGV(log,
            "[MemoryReader] Successfully resolved pointer {0:x} read from "
            "{1:x} to tagged address {2:x}.",
            readValue, address.getAddressData(), tagged_address);
  return tagged_pointer;
}

bool LLDBMemoryReader::readBytes(swift::remote::RemoteAddress address,
                                 uint8_t *dest, uint64_t size) {
  Log *log = GetLog(LLDBLog::Types);
  if (m_local_buffer) {
    bool overflow = false;
    auto addr = address.getAddressData();
    auto end = llvm::SaturatingAdd(addr, size, &overflow);
    if (overflow) {
      LLDB_LOGV(log, "[MemoryReader] address {0:x} + size {1} overflows", addr,
                size);
      return false;
    }
    if (addr >= *m_local_buffer &&
        end <= *m_local_buffer + m_local_buffer_size) {
      // If this crashes, the assumptions stated in
      // GetDynamicTypeAndAddress_Protocol() most likely no longer
      // hold.
      memcpy(dest, (void *)addr, size);
      return true;
    }
  }

  LLDB_LOGV(log, "[MemoryReader] asked to read {0} bytes at address {1:x}",
            size, address.getAddressData());
  std::optional<Address> maybeAddr =
      resolveRemoteAddressFromSymbolObjectFile(address.getAddressData());

  if (!maybeAddr)
    maybeAddr = resolveRemoteAddress(address.getAddressData());

  if (!maybeAddr) {
    LLDB_LOGV(log, "[MemoryReader] could not resolve address {0:x}",
              address.getAddressData());
    return false;
  }
  auto addr = *maybeAddr;
  if (addr.IsSectionOffset()) {
    auto section = addr.GetSection();
    auto *object_file = section->GetObjectFile();
    if (object_file->GetType() == ObjectFile::Type::eTypeDebugInfo) {
      LLDB_LOGV(log, "[MemoryReader] Reading memory from symbol rich binary");

      return object_file->ReadSectionData(section.get(), addr.GetOffset(), dest,
                                          size);
    }
  }

  if (size > m_max_read_amount) {
    LLDB_LOGV(log, "[MemoryReader] memory read exceeds maximum allowed size");
    return false;
  }
  Target &target(m_process.GetTarget());
  Status error;
  // We only want to allow the file-cache optimization if we resolved the
  // address to section + offset.
  const bool force_live_memory =
      !readMetadataFromFileCacheEnabled() || !addr.IsSectionOffset();
  if (size > target.ReadMemory(addr, dest, size, error, force_live_memory)) {
    LLDB_LOGV(log,
              "[MemoryReader] memory read returned fewer bytes than asked for");
    return false;
  }
  if (error.Fail()) {
    LLDB_LOGV(log, "[MemoryReader] memory read returned error: {0}",
              error.AsCString());
    return false;
  }

  auto format_data = [](auto dest, auto size) {
    StreamString stream;
    for (uint64_t i = 0; i < size; i++) {
      stream.PutHex8(dest[i]);
      stream.PutChar(' ');
    }
    return std::string(stream.GetData());
  };
  LLDB_LOGV(log, "[MemoryReader] memory read returned data: {0}",
            format_data(dest, size));

  return true;
}

bool LLDBMemoryReader::readString(swift::remote::RemoteAddress address,
                                  std::string &dest) {
  Log *log = GetLog(LLDBLog::Types);

  auto format_string = [](const std::string &dest) {
    StreamString stream;
    for (auto c : dest) {
      if (c >= 32 && c <= 127) {
        stream << c;
      } else {
        stream << "\\0";
        stream.PutHex8(c);
      }
    }
    return std::string(stream.GetData());
  };
  LLDB_LOGV(log, "[MemoryReader] asked to read string data at address {0:x}",
            address.getAddressData());

  std::optional<Address> maybeAddr =
      resolveRemoteAddressFromSymbolObjectFile(address.getAddressData());

  if (!maybeAddr)
    maybeAddr = resolveRemoteAddress(address.getAddressData());

  if (!maybeAddr) {
    LLDB_LOGV(log, "[MemoryReader] could not resolve address {0:x}",
              address.getAddressData());
    return false;
  }
  auto addr = *maybeAddr;
  if (addr.IsSectionOffset()) {
    auto section = addr.GetSection();
    auto *object_file = section->GetObjectFile();
    if (object_file->GetType() == ObjectFile::Type::eTypeDebugInfo) {
      LLDB_LOGV(log, "[MemoryReader] Reading memory from symbol rich binary");

      dest = object_file->GetCStrFromSection(section.get(), addr.GetOffset());
      LLDB_LOGV(log, "[MemoryReader] memory read returned string: \"{0}\"",
                format_string(dest));
      return true;
    }
  }

  Target &target(m_process.GetTarget());
  Status error;
  // We only want to allow the file-cache optimization if we resolved the
  // address to section + offset.
  const bool force_live_memory =
      !readMetadataFromFileCacheEnabled() || !addr.IsSectionOffset();
  target.ReadCStringFromMemory(addr, dest, error, force_live_memory);
  if (error.Success()) {
    LLDB_LOGV(log, "[MemoryReader] memory read returned string: \"{0}\"",
              format_string(dest));
    return true;
  }
  LLDB_LOGV(log, "[MemoryReader] memory read returned error: {0}",
            error.AsCString());
  return false;
}

void LLDBMemoryReader::pushLocalBuffer(uint64_t local_buffer,
                                       uint64_t local_buffer_size) {
  lldbassert(!m_local_buffer);
  m_local_buffer = local_buffer;
  m_local_buffer_size = local_buffer_size;
}

void LLDBMemoryReader::popLocalBuffer() {
  lldbassert(m_local_buffer);
  m_local_buffer.reset();
  m_local_buffer_size = 0;
}

std::optional<std::pair<uint64_t, uint64_t>>
LLDBMemoryReader::addModuleToAddressMap(ModuleSP module,
                                        bool register_symbol_obj_file) {
  if (!readMetadataFromFileCacheEnabled())
    return {};

  assert(register_symbol_obj_file <=
             m_process.GetTarget().GetSwiftReadMetadataFromDSYM() &&
         "Trying to register symbol object file, but reading from it is "
         "disabled!");

  // The first available address is the mask, since subsequent images are mapped
  // in ascending order, all of them will contain this mask.
  uint64_t module_start_address = LLDB_FILE_ADDRESS_BIT;
  if (!m_range_module_map.empty())
    // We map the images contiguously one after the other, all with the tag bit
    // set.
    // The address that maps the last module is exactly the address the new
    // module should start at.
    module_start_address = m_range_module_map.back().first;

#ifndef NDEBUG
  static std::initializer_list<uint64_t> objc_bits = {
      SWIFT_ABI_ARM_IS_OBJC_BIT, SWIFT_ABI_X86_64_IS_OBJC_BIT,
      SWIFT_ABI_ARM64_IS_OBJC_BIT};

  for (auto objc_bit : objc_bits)
    assert((module_start_address & objc_bit) != objc_bit &&
           "LLDB file address bit clashes with an obj-c bit!");
#endif

  ObjectFile *object_file;
  if (register_symbol_obj_file) {
    auto *symbol_file = module->GetSymbolFile();
    if (!symbol_file)
      return {};
    object_file = symbol_file->GetObjectFile();
  } else {
    object_file = module->GetObjectFile();
  }

  if (!object_file)
    return {};

  SectionList *section_list = object_file->GetSectionList();

  auto section_list_size = section_list->GetSize();
  if (section_list_size == 0)
    return {};

  auto first_section = section_list->GetSectionAtIndex(0);
  auto last_section =
      section_list->GetSectionAtIndex(section_list->GetSize() - 1);

  // The total size is the last section's file address plus size, subtracting
  // the first section's file address.
  auto start_file_address = first_section->GetFileAddress();
  uint64_t end_file_address =
      last_section->GetFileAddress() + last_section->GetByteSize();
  auto size = end_file_address - start_file_address;
  auto module_end_address = module_start_address + size;

  if (module_end_address !=
      (uint64_t)signedPointerStripper(
          swift::remote::RemoteAbsolutePointer("", module_end_address))
          .getOffset()) {
    lldb_assert(false,
                "LLDBMemoryReader module to address map ran into pointer "
                "authentication mask!",
                __FUNCTION__, __FILE__, __LINE__);
    return {};
  }
  // The address for the next image is the next pointer aligned address
  // available after the end of the current image.
  uint64_t next_module_start_address = llvm::alignTo(module_end_address, 8);
  m_range_module_map.emplace_back(next_module_start_address, module);

  if (register_symbol_obj_file)
    m_modules_with_metadata_in_symbol_obj_file.insert(module);

  return {{module_start_address, module_end_address}};
}

std::optional<std::pair<uint64_t, lldb::ModuleSP>>
LLDBMemoryReader::getFileAddressAndModuleForTaggedAddress(
    uint64_t tagged_address) const {
  Log *log(GetLog(LLDBLog::Types));

  if (!readMetadataFromFileCacheEnabled())
    return {};

  // If the address contains our mask, this is an image we registered.
  if (!(tagged_address & LLDB_FILE_ADDRESS_BIT))
    return {};

  // Dummy pair with the address we're looking for.
  auto comparison_pair = std::make_pair(tagged_address, ModuleSP());

  // Explicitly compare only the addresses, never the modules in the pairs.
  auto pair_iterator = std::lower_bound(
      m_range_module_map.begin(), m_range_module_map.end(), comparison_pair,
      [](auto &a, auto &b) { return a.first < b.first; });

  // If the address is larger than anything we have mapped the address is out
  if (pair_iterator == m_range_module_map.end()) {
    LLDB_LOG(log,
             "[MemoryReader] Address {0:x} is larger than the upper bound "
             "address of the mapped in modules",
             tagged_address);
    return {};
  }

  ModuleSP module = pair_iterator->second;
  auto *section_list = module->GetSectionList();
  if (section_list->GetSize() == 0) {
    LLDB_LOG(log,
             "[MemoryReader] Module with empty section list.");
    return {};
  }
  uint64_t file_address;
  if (pair_iterator == m_range_module_map.begin())
    // Since this is the first registered module,
    // clearing the tag bit will give the virtual file address.
    file_address = tagged_address & ~LLDB_FILE_ADDRESS_BIT;
  else
    // The end of the previous section is the start of the current one.
    // We also need to add the first section's file address since we remove it
    // when constructing the range to module map.
    file_address = tagged_address - std::prev(pair_iterator)->first;

  // We also need to add the module's file address, since we subtract it when
  // building the range to module map.
  file_address += section_list->GetSectionAtIndex(0)->GetFileAddress();
  return {{file_address, module}};
}

std::optional<Address>
LLDBMemoryReader::resolveRemoteAddress(uint64_t address) const {
  Log *log(GetLog(LLDBLog::Types));
  auto maybe_pair = getFileAddressAndModuleForTaggedAddress(address);
  if (!maybe_pair)
    return Address(address);

  uint64_t file_address = maybe_pair->first;
  ModuleSP module = maybe_pair->second;

  if (m_modules_with_metadata_in_symbol_obj_file.count(module))
    return Address(address);

  auto *object_file = module->GetObjectFile();
  if (!object_file)
    return {};

  Address resolved(file_address, object_file->GetSectionList());

  // If the address doesn't have a section it means we couldn't find a section
  // that contains that file address, and the "resolved" instance is wrong. 
  // Calculate the virtual address by finding out the slide of the associated 
  // module, and adding that to the file address.
  if (resolved.GetSection()) {
    LLDB_LOGV(log,
              "[MemoryReader] Successfully resolved mapped address {0:x} into "
              "file address {1:x}",
              address, resolved.GetFileAddress());
    return resolved;
  }
  auto *sec_list = module->GetSectionList();
  if (sec_list->GetSize() == 0) {
    LLDB_LOG(log,
             "[MemoryReader] Could not calculate virtual address from file "
             "address {0:x}, no sections in {1}",
             file_address, object_file->GetFileSpec().GetFilename());
    return {};
  }
  SectionSP sec = sec_list->GetSectionAtIndex(0);
  addr_t sec_file_address = sec->GetFileAddress();
  addr_t sec_load_address = sec->GetLoadBaseAddress(&m_process.GetTarget());

  if (sec_load_address < sec_file_address) {
    LLDB_LOG(log,
             "[MemoryReader] section load address {0:x} is smaller than "
             "section file address {1:x}",
             sec_load_address, sec_file_address);
    return {};
  }

  addr_t slide = sec_load_address - sec_file_address;

  bool overflow = false;
  addr_t virtual_address = llvm::SaturatingAdd(file_address, slide, &overflow);
  if (overflow) {
    LLDB_LOG(log, "[MemoryReader] file address {0:x} + slide {1:x} overflows",
             sec_load_address, sec_file_address);
    return {};
  }

  resolved = Address(virtual_address);
  LLDB_LOGV(log,
            "[MemoryReader] Could not find section with file address {0:x} "
            "and file {1}, resolved it into virtual address {2:x}",
            file_address, object_file->GetFileSpec().GetFilename(),
            virtual_address);
  return resolved;
}

std::optional<Address>
LLDBMemoryReader::resolveRemoteAddressFromSymbolObjectFile(
    uint64_t address) const {
  Log *log(GetLog(LLDBLog::Types));

  if (!m_process.GetTarget().GetSwiftReadMetadataFromDSYM())
    return {};

  auto maybe_pair = getFileAddressAndModuleForTaggedAddress(address);
  if (!maybe_pair)
    return {};

  uint64_t file_address = maybe_pair->first;
  ModuleSP module = maybe_pair->second;

  if (!m_modules_with_metadata_in_symbol_obj_file.count(module))
    return {};

  auto *symbol_file = module->GetSymbolFile();
  if (!symbol_file)
    return {};

  auto *object_file = symbol_file->GetObjectFile();
  if (!object_file)
    return {};

  Address resolved(file_address, object_file->GetSectionList());
  if (!resolved.IsSectionOffset()) {
    LLDB_LOG(log,
             "[MemoryReader] Could not make a real address out of file address "
             "{0:x} and object file {1}",
             file_address, object_file->GetFileSpec().GetFilename());
    return {};
  }

  if (!resolved.GetSection()
           ->GetParent()
           ->GetName()
           .GetStringRef()
           .contains_insensitive("DWARF")) {
    auto *main_object_file = module->GetObjectFile();
    resolved = Address(file_address, main_object_file->GetSectionList());
  }
  LLDB_LOGV(log,
            "[MemoryReader] Successfully resolved mapped address {0:x} into "
            "file address {1:x} from symbol object file.",
            address, file_address);
  return resolved;
}

bool LLDBMemoryReader::readMetadataFromFileCacheEnabled() const {
  auto &triple = m_process.GetTarget().GetArchitecture().GetTriple();

  // 32 doesn't have a flag bit we can reliably use, so reading from filecache
  // is disabled on it.
  return m_process.GetTarget().GetSwiftReadMetadataFromFileCache() &&
         triple.isArch64Bit();
}
} // namespace lldb_private