Coverage Report

Created: 2023-09-21 18:56

/Users/buildslave/jenkins/workspace/coverage/llvm-project/lldb/source/Core/SourceManager.cpp
Line
Count
Source (jump to first uncovered line)
1
//===-- SourceManager.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 "lldb/Core/SourceManager.h"
10
11
#include "lldb/Core/Address.h"
12
#include "lldb/Core/AddressRange.h"
13
#include "lldb/Core/Debugger.h"
14
#include "lldb/Core/FormatEntity.h"
15
#include "lldb/Core/Highlighter.h"
16
#include "lldb/Core/Module.h"
17
#include "lldb/Core/ModuleList.h"
18
#include "lldb/Host/FileSystem.h"
19
#include "lldb/Symbol/CompileUnit.h"
20
#include "lldb/Symbol/Function.h"
21
#include "lldb/Symbol/LineEntry.h"
22
#include "lldb/Symbol/SymbolContext.h"
23
#include "lldb/Target/PathMappingList.h"
24
#include "lldb/Target/Process.h"
25
#include "lldb/Target/Target.h"
26
#include "lldb/Utility/AnsiTerminal.h"
27
#include "lldb/Utility/ConstString.h"
28
#include "lldb/Utility/DataBuffer.h"
29
#include "lldb/Utility/LLDBLog.h"
30
#include "lldb/Utility/Log.h"
31
#include "lldb/Utility/RegularExpression.h"
32
#include "lldb/Utility/Stream.h"
33
#include "lldb/lldb-enumerations.h"
34
35
#include "llvm/ADT/Twine.h"
36
37
#include <memory>
38
#include <optional>
39
#include <utility>
40
41
#include <cassert>
42
#include <cstdio>
43
44
namespace lldb_private {
45
class ExecutionContext;
46
}
47
namespace lldb_private {
48
class ValueObject;
49
}
50
51
using namespace lldb;
52
using namespace lldb_private;
53
54
3.43M
static inline bool is_newline_char(char ch) { return ch == '\n' || 
ch == '\r'3.30M
; }
55
56
1.68k
static void resolve_tilde(FileSpec &file_spec) {
57
1.68k
  if (!FileSystem::Instance().Exists(file_spec) &&
58
1.68k
      
file_spec.GetDirectory()20
&&
59
1.68k
      
file_spec.GetDirectory().GetCString()[0] == '~'18
) {
60
0
    FileSystem::Instance().Resolve(file_spec);
61
0
  }
62
1.68k
}
63
64
// SourceManager constructor
65
SourceManager::SourceManager(const TargetSP &target_sp)
66
1.68k
    : m_last_line(0), m_last_count(0), m_default_set(false),
67
1.68k
      m_target_wp(target_sp),
68
1.68k
      m_debugger_wp(target_sp->GetDebugger().shared_from_this()) {}
69
70
SourceManager::SourceManager(const DebuggerSP &debugger_sp)
71
8
    : m_last_line(0), m_last_count(0), m_default_set(false), m_target_wp(),
72
8
      m_debugger_wp(debugger_sp) {}
73
74
// Destructor
75
1.63k
SourceManager::~SourceManager() = default;
76
77
14.4k
SourceManager::FileSP SourceManager::GetFile(const FileSpec &file_spec) {
78
14.4k
  if (!file_spec)
79
609
    return {};
80
81
13.8k
  Log *log = GetLog(LLDBLog::Source);
82
83
13.8k
  DebuggerSP debugger_sp(m_debugger_wp.lock());
84
13.8k
  TargetSP target_sp(m_target_wp.lock());
85
86
13.8k
  if (!debugger_sp || !debugger_sp->GetUseSourceCache()) {
87
1
    LLDB_LOG(log, "Source file caching disabled: creating new source file: {0}",
88
1
             file_spec);
89
1
    if (target_sp)
90
1
      return std::make_shared<File>(file_spec, target_sp);
91
0
    return std::make_shared<File>(file_spec, debugger_sp);
92
1
  }
93
94
13.8k
  ProcessSP process_sp = target_sp ? 
target_sp->GetProcessSP()13.7k
:
ProcessSP()76
;
95
96
  // Check the process source cache first. This is the fast path which avoids
97
  // touching the file system unless the path remapping has changed.
98
13.8k
  if (process_sp) {
99
12.7k
    if (FileSP file_sp =
100
12.7k
            process_sp->GetSourceFileCache().FindSourceFile(file_spec)) {
101
6.89k
      LLDB_LOG(log, "Found source file in the process cache: {0}", file_spec);
102
6.89k
      if (file_sp->PathRemappingIsStale()) {
103
0
        LLDB_LOG(log, "Path remapping is stale: removing file from caches: {0}",
104
0
                 file_spec);
105
106
        // Remove the file from the debugger and process cache. Otherwise we'll
107
        // hit the same issue again below when querying the debugger cache.
108
0
        debugger_sp->GetSourceFileCache().RemoveSourceFile(file_sp);
109
0
        process_sp->GetSourceFileCache().RemoveSourceFile(file_sp);
110
111
0
        file_sp.reset();
112
6.89k
      } else {
113
6.89k
        return file_sp;
114
6.89k
      }
115
6.89k
    }
116
12.7k
  }
117
118
  // Cache miss in the process cache. Check the debugger source cache.
119
6.94k
  FileSP file_sp = debugger_sp->GetSourceFileCache().FindSourceFile(file_spec);
120
121
  // We found the file in the debugger cache. Check if anything invalidated our
122
  // cache result.
123
6.94k
  if (file_sp)
124
5.26k
    LLDB_LOG(log, "Found source file in the debugger cache: {0}", file_spec);
125
126
  // Check if the path remapping has changed.
127
6.94k
  if (file_sp && 
file_sp->PathRemappingIsStale()5.26k
) {
128
2
    LLDB_LOG(log, "Path remapping is stale: {0}", file_spec);
129
2
    file_sp.reset();
130
2
  }
131
132
  // Check if the modification time has changed.
133
6.94k
  if (file_sp && 
file_sp->ModificationTimeIsStale()5.25k
) {
134
0
    LLDB_LOG(log, "Modification time is stale: {0}", file_spec);
135
0
    file_sp.reset();
136
0
  }
137
138
  // Check if the file exists on disk.
139
6.94k
  if (file_sp && 
!FileSystem::Instance().Exists(file_sp->GetFileSpec())5.25k
) {
140
0
    LLDB_LOG(log, "File doesn't exist on disk: {0}", file_spec);
141
0
    file_sp.reset();
142
0
  }
143
144
  // If at this point we don't have a valid file, it means we either didn't find
145
  // it in the debugger cache or something caused it to be invalidated.
146
6.94k
  if (!file_sp) {
147
1.68k
    LLDB_LOG(log, "Creating and caching new source file: {0}", file_spec);
148
149
    // (Re)create the file.
150
1.68k
    if (target_sp)
151
1.67k
      file_sp = std::make_shared<File>(file_spec, target_sp);
152
8
    else
153
8
      file_sp = std::make_shared<File>(file_spec, debugger_sp);
154
155
    // Add the file to the debugger and process cache. If the file was
156
    // invalidated, this will overwrite it.
157
1.68k
    debugger_sp->GetSourceFileCache().AddSourceFile(file_spec, file_sp);
158
1.68k
    if (process_sp)
159
804
      process_sp->GetSourceFileCache().AddSourceFile(file_spec, file_sp);
160
1.68k
  }
161
162
6.94k
  return file_sp;
163
13.8k
}
164
165
9.97k
static bool should_highlight_source(DebuggerSP debugger_sp) {
166
9.97k
  if (!debugger_sp)
167
0
    return false;
168
169
  // We don't use ANSI stop column formatting if the debugger doesn't think it
170
  // should be using color.
171
9.97k
  if (!debugger_sp->GetUseColor())
172
9.94k
    return false;
173
174
31
  return debugger_sp->GetHighlightSource();
175
9.97k
}
176
177
9.97k
static bool should_show_stop_column_with_ansi(DebuggerSP debugger_sp) {
178
  // We don't use ANSI stop column formatting if we can't lookup values from
179
  // the debugger.
180
9.97k
  if (!debugger_sp)
181
0
    return false;
182
183
  // We don't use ANSI stop column formatting if the debugger doesn't think it
184
  // should be using color.
185
9.97k
  if (!debugger_sp->GetUseColor())
186
9.94k
    return false;
187
188
  // We only use ANSI stop column formatting if we're either supposed to show
189
  // ANSI where available (which we know we have when we get to this point), or
190
  // if we're only supposed to use ANSI.
191
31
  const auto value = debugger_sp->GetStopShowColumn();
192
31
  return ((value == eStopShowColumnAnsiOrCaret) ||
193
31
          
(value == eStopShowColumnAnsi)0
);
194
9.97k
}
195
196
1.48k
static bool should_show_stop_column_with_caret(DebuggerSP debugger_sp) {
197
  // We don't use text-based stop column formatting if we can't lookup values
198
  // from the debugger.
199
1.48k
  if (!debugger_sp)
200
0
    return false;
201
202
  // If we're asked to show the first available of ANSI or caret, then we do
203
  // show the caret when ANSI is not available.
204
1.48k
  const auto value = debugger_sp->GetStopShowColumn();
205
1.48k
  if ((value == eStopShowColumnAnsiOrCaret) && !debugger_sp->GetUseColor())
206
1.47k
    return true;
207
208
  // The only other time we use caret is if we're explicitly asked to show
209
  // caret.
210
8
  return value == eStopShowColumnCaret;
211
1.48k
}
212
213
9.97k
static bool should_show_stop_line_with_ansi(DebuggerSP debugger_sp) {
214
9.97k
  return debugger_sp && debugger_sp->GetUseColor();
215
9.97k
}
216
217
size_t SourceManager::DisplaySourceLinesWithLineNumbersUsingLastFile(
218
    uint32_t start_line, uint32_t count, uint32_t curr_line, uint32_t column,
219
    const char *current_line_cstr, Stream *s,
220
1.52k
    const SymbolContextList *bp_locs) {
221
1.52k
  if (count == 0)
222
0
    return 0;
223
224
1.52k
  Stream::ByteDelta delta(*s);
225
226
1.52k
  if (start_line == 0) {
227
0
    if (m_last_line != 0 && m_last_line != UINT32_MAX)
228
0
      start_line = m_last_line + m_last_count;
229
0
    else
230
0
      start_line = 1;
231
0
  }
232
233
1.52k
  if (!m_default_set) {
234
787
    FileSpec tmp_spec;
235
787
    uint32_t tmp_line;
236
787
    GetDefaultFileAndLine(tmp_spec, tmp_line);
237
787
  }
238
239
1.52k
  m_last_line = start_line;
240
1.52k
  m_last_count = count;
241
242
1.52k
  if (FileSP last_file_sp = GetLastFile()) {
243
1.52k
    const uint32_t end_line = start_line + count - 1;
244
11.4k
    for (uint32_t line = start_line; line <= end_line; 
++line9.97k
) {
245
10.3k
      if (!last_file_sp->LineIsValid(line)) {
246
351
        m_last_line = UINT32_MAX;
247
351
        break;
248
351
      }
249
250
9.97k
      std::string prefix;
251
9.97k
      if (bp_locs) {
252
3
        uint32_t bp_count = bp_locs->NumLineEntriesWithLine(line);
253
254
3
        if (bp_count > 0)
255
2
          prefix = llvm::formatv("[{0}]", bp_count);
256
1
        else
257
1
          prefix = "    ";
258
3
      }
259
260
9.97k
      char buffer[3];
261
9.97k
      snprintf(buffer, sizeof(buffer), "%2.2s",
262
9.97k
               (line == curr_line) ? 
current_line_cstr1.52k
:
""8.44k
);
263
9.97k
      std::string current_line_highlight(buffer);
264
265
9.97k
      auto debugger_sp = m_debugger_wp.lock();
266
9.97k
      if (should_show_stop_line_with_ansi(debugger_sp)) {
267
31
        current_line_highlight = ansi::FormatAnsiTerminalCodes(
268
31
            (debugger_sp->GetStopShowLineMarkerAnsiPrefix() +
269
31
             current_line_highlight +
270
31
             debugger_sp->GetStopShowLineMarkerAnsiSuffix())
271
31
                .str());
272
31
      }
273
274
9.97k
      s->Printf("%s%s %-4u\t", prefix.c_str(), current_line_highlight.c_str(),
275
9.97k
                line);
276
277
      // So far we treated column 0 as a special 'no column value', but
278
      // DisplaySourceLines starts counting columns from 0 (and no column is
279
      // expressed by passing an empty optional).
280
9.97k
      std::optional<size_t> columnToHighlight;
281
9.97k
      if (line == curr_line && 
column1.52k
)
282
1.48k
        columnToHighlight = column - 1;
283
284
9.97k
      size_t this_line_size =
285
9.97k
          last_file_sp->DisplaySourceLines(line, columnToHighlight, 0, 0, s);
286
9.97k
      if (column != 0 && 
line == curr_line9.77k
&&
287
9.97k
          
should_show_stop_column_with_caret(debugger_sp)1.48k
) {
288
        // Display caret cursor.
289
1.47k
        std::string src_line;
290
1.47k
        last_file_sp->GetLine(line, src_line);
291
1.47k
        s->Printf("    \t");
292
        // Insert a space for every non-tab character in the source line.
293
21.1k
        for (size_t i = 0; i + 1 < column && 
i < src_line.length()19.6k
;
++i19.6k
)
294
19.6k
          s->PutChar(src_line[i] == '\t' ? 
'\t'58
:
' '19.6k
);
295
        // Now add the caret.
296
1.47k
        s->Printf("^\n");
297
1.47k
      }
298
9.97k
      if (this_line_size == 0) {
299
0
        m_last_line = UINT32_MAX;
300
0
        break;
301
0
      }
302
9.97k
    }
303
1.52k
  }
304
1.52k
  return *delta;
305
1.52k
}
306
307
size_t SourceManager::DisplaySourceLinesWithLineNumbers(
308
    const FileSpec &file_spec, uint32_t line, uint32_t column,
309
    uint32_t context_before, uint32_t context_after,
310
    const char *current_line_cstr, Stream *s,
311
1.52k
    const SymbolContextList *bp_locs) {
312
1.52k
  FileSP file_sp(GetFile(file_spec));
313
314
1.52k
  uint32_t start_line;
315
1.52k
  uint32_t count = context_before + context_after + 1;
316
1.52k
  if (line > context_before)
317
1.46k
    start_line = line - context_before;
318
62
  else
319
62
    start_line = 1;
320
321
1.52k
  FileSP last_file_sp(GetLastFile());
322
1.52k
  if (last_file_sp.get() != file_sp.get()) {
323
565
    if (line == 0)
324
0
      m_last_line = 0;
325
565
    m_last_file_spec = file_spec;
326
565
  }
327
1.52k
  return DisplaySourceLinesWithLineNumbersUsingLastFile(
328
1.52k
      start_line, count, line, column, current_line_cstr, s, bp_locs);
329
1.52k
}
330
331
size_t SourceManager::DisplayMoreWithLineNumbers(
332
1
    Stream *s, uint32_t count, bool reverse, const SymbolContextList *bp_locs) {
333
  // If we get called before anybody has set a default file and line, then try
334
  // to figure it out here.
335
1
  FileSP last_file_sp(GetLastFile());
336
1
  const bool have_default_file_line = last_file_sp && 
m_last_line > 00
;
337
1
  if (!m_default_set) {
338
1
    FileSpec tmp_spec;
339
1
    uint32_t tmp_line;
340
1
    GetDefaultFileAndLine(tmp_spec, tmp_line);
341
1
  }
342
343
1
  if (last_file_sp) {
344
0
    if (m_last_line == UINT32_MAX)
345
0
      return 0;
346
347
0
    if (reverse && m_last_line == 1)
348
0
      return 0;
349
350
0
    if (count > 0)
351
0
      m_last_count = count;
352
0
    else if (m_last_count == 0)
353
0
      m_last_count = 10;
354
355
0
    if (m_last_line > 0) {
356
0
      if (reverse) {
357
        // If this is the first time we've done a reverse, then back up one
358
        // more time so we end up showing the chunk before the last one we've
359
        // shown:
360
0
        if (m_last_line > m_last_count)
361
0
          m_last_line -= m_last_count;
362
0
        else
363
0
          m_last_line = 1;
364
0
      } else if (have_default_file_line)
365
0
        m_last_line += m_last_count;
366
0
    } else
367
0
      m_last_line = 1;
368
369
0
    const uint32_t column = 0;
370
0
    return DisplaySourceLinesWithLineNumbersUsingLastFile(
371
0
        m_last_line, m_last_count, UINT32_MAX, column, "", s, bp_locs);
372
0
  }
373
1
  return 0;
374
1
}
375
376
bool SourceManager::SetDefaultFileAndLine(const FileSpec &file_spec,
377
7.96k
                                          uint32_t line) {
378
7.96k
  m_default_set = true;
379
7.96k
  FileSP file_sp(GetFile(file_spec));
380
381
7.96k
  if (file_sp) {
382
7.96k
    m_last_line = line;
383
7.96k
    m_last_file_spec = file_spec;
384
7.96k
    return true;
385
7.96k
  } else {
386
0
    return false;
387
0
  }
388
7.96k
}
389
390
853
bool SourceManager::GetDefaultFileAndLine(FileSpec &file_spec, uint32_t &line) {
391
853
  if (FileSP last_file_sp = GetLastFile()) {
392
792
    file_spec = m_last_file_spec;
393
792
    line = m_last_line;
394
792
    return true;
395
792
  } else 
if (61
!m_default_set61
) {
396
61
    TargetSP target_sp(m_target_wp.lock());
397
398
61
    if (target_sp) {
399
      // If nobody has set the default file and line then try here.  If there's
400
      // no executable, then we will try again later when there is one.
401
      // Otherwise, if we can't find it we won't look again, somebody will have
402
      // to set it (for instance when we stop somewhere...)
403
61
      Module *executable_ptr = target_sp->GetExecutableModulePointer();
404
61
      if (executable_ptr) {
405
61
        SymbolContextList sc_list;
406
61
        ConstString main_name("main");
407
408
61
        ModuleFunctionSearchOptions function_options;
409
61
        function_options.include_symbols =
410
61
            false; // Force it to be a debug symbol.
411
61
        function_options.include_inlines = true;
412
61
        executable_ptr->FindFunctions(main_name, CompilerDeclContext(),
413
61
                                      lldb::eFunctionNameTypeBase,
414
61
                                      function_options, sc_list);
415
61
        for (const SymbolContext &sc : sc_list) {
416
61
          if (sc.function) {
417
61
            lldb_private::LineEntry line_entry;
418
61
            if (sc.function->GetAddressRange()
419
61
                    .GetBaseAddress()
420
61
                    .CalculateSymbolContextLineEntry(line_entry)) {
421
61
              SetDefaultFileAndLine(line_entry.file, line_entry.line);
422
61
              file_spec = m_last_file_spec;
423
61
              line = m_last_line;
424
61
              return true;
425
61
            }
426
61
          }
427
61
        }
428
61
      }
429
61
    }
430
61
  }
431
0
  return false;
432
853
}
433
434
void SourceManager::FindLinesMatchingRegex(FileSpec &file_spec,
435
                                           RegularExpression &regex,
436
                                           uint32_t start_line,
437
                                           uint32_t end_line,
438
1.04k
                                           std::vector<uint32_t> &match_lines) {
439
1.04k
  match_lines.clear();
440
1.04k
  FileSP file_sp = GetFile(file_spec);
441
1.04k
  if (!file_sp)
442
0
    return;
443
1.04k
  return file_sp->FindLinesMatchingRegex(regex, start_line, end_line,
444
1.04k
                                         match_lines);
445
1.04k
}
446
447
SourceManager::File::File(const FileSpec &file_spec,
448
                          lldb::DebuggerSP debugger_sp)
449
11
    : m_file_spec_orig(file_spec), m_file_spec(), m_mod_time(),
450
11
      m_debugger_wp(debugger_sp), m_target_wp(TargetSP()) {
451
11
  CommonInitializer(file_spec, {});
452
11
}
453
454
SourceManager::File::File(const FileSpec &file_spec, TargetSP target_sp)
455
1.67k
    : m_file_spec_orig(file_spec), m_file_spec(), m_mod_time(),
456
1.67k
      m_debugger_wp(target_sp ? target_sp->GetDebugger().shared_from_this()
457
1.67k
                              : 
DebuggerSP()0
),
458
1.67k
      m_target_wp(target_sp) {
459
1.67k
  CommonInitializer(file_spec, target_sp);
460
1.67k
}
461
462
void SourceManager::File::CommonInitializer(const FileSpec &file_spec,
463
1.68k
                                            TargetSP target_sp) {
464
  // Set the file and update the modification time.
465
1.68k
  SetFileSpec(file_spec);
466
467
  // Always update the source map modification ID if we have a target.
468
1.68k
  if (target_sp)
469
1.67k
    m_source_map_mod_id = target_sp->GetSourcePathMap().GetModificationID();
470
471
  // File doesn't exist.
472
1.68k
  if (m_mod_time == llvm::sys::TimePoint<>()) {
473
20
    if (target_sp) {
474
      // If this is just a file name, try finding it in the target.
475
17
      if (!file_spec.GetDirectory() && 
file_spec.GetFilename()0
) {
476
0
        bool check_inlines = false;
477
0
        SymbolContextList sc_list;
478
0
        size_t num_matches =
479
0
            target_sp->GetImages().ResolveSymbolContextForFilePath(
480
0
                file_spec.GetFilename().AsCString(), 0, check_inlines,
481
0
                SymbolContextItem(eSymbolContextModule |
482
0
                                  eSymbolContextCompUnit),
483
0
                sc_list);
484
0
        bool got_multiple = false;
485
0
        if (num_matches != 0) {
486
0
          if (num_matches > 1) {
487
0
            CompileUnit *test_cu = nullptr;
488
0
            for (const SymbolContext &sc : sc_list) {
489
0
              if (sc.comp_unit) {
490
0
                if (test_cu) {
491
0
                  if (test_cu != sc.comp_unit)
492
0
                    got_multiple = true;
493
0
                  break;
494
0
                } else
495
0
                  test_cu = sc.comp_unit;
496
0
              }
497
0
            }
498
0
          }
499
0
          if (!got_multiple) {
500
0
            SymbolContext sc;
501
0
            sc_list.GetContextAtIndex(0, sc);
502
0
            if (sc.comp_unit)
503
0
              SetFileSpec(sc.comp_unit->GetPrimaryFile());
504
0
          }
505
0
        }
506
0
      }
507
508
      // Try remapping the file if it doesn't exist.
509
17
      if (!FileSystem::Instance().Exists(m_file_spec)) {
510
        // Check target specific source remappings (i.e., the
511
        // target.source-map setting), then fall back to the module
512
        // specific remapping (i.e., the .dSYM remapping dictionary).
513
17
        auto remapped = target_sp->GetSourcePathMap().FindFile(m_file_spec);
514
17
        if (!remapped) {
515
16
          FileSpec new_spec;
516
16
          if (target_sp->GetImages().FindSourceFile(m_file_spec, new_spec))
517
0
            remapped = new_spec;
518
16
        }
519
17
        if (remapped)
520
1
          SetFileSpec(*remapped);
521
17
      }
522
17
    }
523
20
  }
524
525
  // If the file exists, read in the data.
526
1.68k
  if (m_mod_time != llvm::sys::TimePoint<>())
527
1.66k
    m_data_sp = FileSystem::Instance().CreateDataBuffer(m_file_spec);
528
1.68k
}
529
530
1.68k
void SourceManager::File::SetFileSpec(FileSpec file_spec) {
531
1.68k
  resolve_tilde(file_spec);
532
1.68k
  m_file_spec = std::move(file_spec);
533
1.68k
  m_mod_time = FileSystem::Instance().GetModificationTime(m_file_spec);
534
1.68k
}
535
536
149k
uint32_t SourceManager::File::GetLineOffset(uint32_t line) {
537
149k
  if (line == 0)
538
0
    return UINT32_MAX;
539
540
149k
  if (line == 1)
541
1.15k
    return 0;
542
543
148k
  if (CalculateLineOffsets(line)) {
544
148k
    if (line < m_offsets.size())
545
146k
      return m_offsets[line - 1]; // yes we want "line - 1" in the index
546
148k
  }
547
1.53k
  return UINT32_MAX;
548
148k
}
549
550
2
uint32_t SourceManager::File::GetNumLines() {
551
2
  CalculateLineOffsets();
552
2
  return m_offsets.size();
553
2
}
554
555
0
const char *SourceManager::File::PeekLineData(uint32_t line) {
556
0
  if (!LineIsValid(line))
557
0
    return nullptr;
558
559
0
  size_t line_offset = GetLineOffset(line);
560
0
  if (line_offset < m_data_sp->GetByteSize())
561
0
    return (const char *)m_data_sp->GetBytes() + line_offset;
562
0
  return nullptr;
563
0
}
564
565
uint32_t SourceManager::File::GetLineLength(uint32_t line,
566
0
                                            bool include_newline_chars) {
567
0
  if (!LineIsValid(line))
568
0
    return false;
569
570
0
  size_t start_offset = GetLineOffset(line);
571
0
  size_t end_offset = GetLineOffset(line + 1);
572
0
  if (end_offset == UINT32_MAX)
573
0
    end_offset = m_data_sp->GetByteSize();
574
575
0
  if (end_offset > start_offset) {
576
0
    uint32_t length = end_offset - start_offset;
577
0
    if (!include_newline_chars) {
578
0
      const char *line_start =
579
0
          (const char *)m_data_sp->GetBytes() + start_offset;
580
0
      while (length > 0) {
581
0
        const char last_char = line_start[length - 1];
582
0
        if ((last_char == '\r') || (last_char == '\n'))
583
0
          --length;
584
0
        else
585
0
          break;
586
0
      }
587
0
    }
588
0
    return length;
589
0
  }
590
0
  return 0;
591
0
}
592
593
77.2k
bool SourceManager::File::LineIsValid(uint32_t line) {
594
77.2k
  if (line == 0)
595
0
    return false;
596
597
77.2k
  if (CalculateLineOffsets(line))
598
77.2k
    return line < m_offsets.size();
599
0
  return false;
600
77.2k
}
601
602
5.25k
bool SourceManager::File::ModificationTimeIsStale() const {
603
  // TODO: use host API to sign up for file modifications to anything in our
604
  // source cache and only update when we determine a file has been updated.
605
  // For now we check each time we want to display info for the file.
606
5.25k
  auto curr_mod_time = FileSystem::Instance().GetModificationTime(m_file_spec);
607
5.25k
  return curr_mod_time != llvm::sys::TimePoint<>() &&
608
5.25k
         m_mod_time != curr_mod_time;
609
5.25k
}
610
611
12.1k
bool SourceManager::File::PathRemappingIsStale() const {
612
12.1k
  if (TargetSP target_sp = m_target_wp.lock())
613
12.0k
    return GetSourceMapModificationID() !=
614
12.0k
           target_sp->GetSourcePathMap().GetModificationID();
615
71
  return false;
616
12.1k
}
617
618
size_t SourceManager::File::DisplaySourceLines(uint32_t line,
619
                                               std::optional<size_t> column,
620
                                               uint32_t context_before,
621
                                               uint32_t context_after,
622
9.97k
                                               Stream *s) {
623
  // Nothing to write if there's no stream.
624
9.97k
  if (!s)
625
0
    return 0;
626
627
  // Sanity check m_data_sp before proceeding.
628
9.97k
  if (!m_data_sp)
629
0
    return 0;
630
631
9.97k
  size_t bytes_written = s->GetWrittenBytes();
632
633
9.97k
  auto debugger_sp = m_debugger_wp.lock();
634
635
9.97k
  HighlightStyle style;
636
  // Use the default Vim style if source highlighting is enabled.
637
9.97k
  if (should_highlight_source(debugger_sp))
638
26
    style = HighlightStyle::MakeVimStyle();
639
640
  // If we should mark the stop column with color codes, then copy the prefix
641
  // and suffix to our color style.
642
9.97k
  if (should_show_stop_column_with_ansi(debugger_sp))
643
31
    style.selected.Set(debugger_sp->GetStopShowColumnAnsiPrefix(),
644
31
                       debugger_sp->GetStopShowColumnAnsiSuffix());
645
646
9.97k
  HighlighterManager mgr;
647
9.97k
  std::string path = GetFileSpec().GetPath(/*denormalize*/ false);
648
  // FIXME: Find a way to get the definitive language this file was written in
649
  // and pass it to the highlighter.
650
9.97k
  const auto &h = mgr.getHighlighterFor(lldb::eLanguageTypeUnknown, path);
651
652
9.97k
  const uint32_t start_line =
653
9.97k
      line <= context_before ? 
10
: line - context_before;
654
9.97k
  const uint32_t start_line_offset = GetLineOffset(start_line);
655
9.97k
  if (start_line_offset != UINT32_MAX) {
656
9.97k
    const uint32_t end_line = line + context_after;
657
9.97k
    uint32_t end_line_offset = GetLineOffset(end_line + 1);
658
9.97k
    if (end_line_offset == UINT32_MAX)
659
474
      end_line_offset = m_data_sp->GetByteSize();
660
661
9.97k
    assert(start_line_offset <= end_line_offset);
662
9.97k
    if (start_line_offset < end_line_offset) {
663
9.97k
      size_t count = end_line_offset - start_line_offset;
664
9.97k
      const uint8_t *cstr = m_data_sp->GetBytes() + start_line_offset;
665
666
9.97k
      auto ref = llvm::StringRef(reinterpret_cast<const char *>(cstr), count);
667
668
9.97k
      h.Highlight(style, ref, column, "", *s);
669
670
      // Ensure we get an end of line character one way or another.
671
9.97k
      if (!is_newline_char(ref.back()))
672
0
        s->EOL();
673
9.97k
    }
674
9.97k
  }
675
9.97k
  return s->GetWrittenBytes() - bytes_written;
676
9.97k
}
677
678
void SourceManager::File::FindLinesMatchingRegex(
679
    RegularExpression &regex, uint32_t start_line, uint32_t end_line,
680
1.04k
    std::vector<uint32_t> &match_lines) {
681
1.04k
  match_lines.clear();
682
683
1.04k
  if (!LineIsValid(start_line) ||
684
1.04k
      (end_line != UINT32_MAX && 
!LineIsValid(end_line)0
))
685
0
    return;
686
1.04k
  if (start_line > end_line)
687
0
    return;
688
689
64.3k
  
for (uint32_t line_no = start_line; 1.04k
line_no < end_line;
line_no++63.3k
) {
690
64.3k
    std::string buffer;
691
64.3k
    if (!GetLine(line_no, buffer))
692
1.04k
      break;
693
63.3k
    if (regex.Execute(buffer)) {
694
1.23k
      match_lines.push_back(line_no);
695
1.23k
    }
696
63.3k
  }
697
1.04k
}
698
699
bool lldb_private::operator==(const SourceManager::File &lhs,
700
0
                              const SourceManager::File &rhs) {
701
0
  if (lhs.m_file_spec != rhs.m_file_spec)
702
0
    return false;
703
0
  return lhs.m_mod_time == rhs.m_mod_time;
704
0
}
705
706
225k
bool SourceManager::File::CalculateLineOffsets(uint32_t line) {
707
225k
  line =
708
225k
      UINT32_MAX; // TODO: take this line out when we support partial indexing
709
225k
  if (line == UINT32_MAX) {
710
    // Already done?
711
225k
    if (!m_offsets.empty() && 
m_offsets[0] == UINT32_MAX224k
)
712
224k
      return true;
713
714
1.51k
    if (m_offsets.empty()) {
715
1.51k
      if (m_data_sp.get() == nullptr)
716
0
        return false;
717
718
1.51k
      const char *start = (const char *)m_data_sp->GetBytes();
719
1.51k
      if (start) {
720
1.51k
        const char *end = start + m_data_sp->GetByteSize();
721
722
        // Calculate all line offsets from scratch
723
724
        // Push a 1 at index zero to indicate the file has been completely
725
        // indexed.
726
1.51k
        m_offsets.push_back(UINT32_MAX);
727
1.51k
        const char *s;
728
3.32M
        for (s = start; s < end; 
++s3.32M
) {
729
3.32M
          char curr_ch = *s;
730
3.32M
          if (is_newline_char(curr_ch)) {
731
100k
            if (s + 1 < end) {
732
98.7k
              char next_ch = s[1];
733
98.7k
              if (is_newline_char(next_ch)) {
734
17.2k
                if (curr_ch != next_ch)
735
0
                  ++s;
736
17.2k
              }
737
98.7k
            }
738
100k
            m_offsets.push_back(s + 1 - start);
739
100k
          }
740
3.32M
        }
741
1.51k
        if (!m_offsets.empty()) {
742
1.51k
          if (m_offsets.back() < size_t(end - start))
743
0
            m_offsets.push_back(end - start);
744
1.51k
        }
745
1.51k
        return true;
746
1.51k
      }
747
1.51k
    } else {
748
      // Some lines have been populated, start where we last left off
749
0
      assert("Not implemented yet" && false);
750
0
    }
751
752
1.51k
  } else {
753
    // Calculate all line offsets up to "line"
754
0
    assert("Not implemented yet" && false);
755
0
  }
756
0
  return false;
757
225k
}
758
759
65.8k
bool SourceManager::File::GetLine(uint32_t line_no, std::string &buffer) {
760
65.8k
  if (!LineIsValid(line_no))
761
1.04k
    return false;
762
763
64.8k
  size_t start_offset = GetLineOffset(line_no);
764
64.8k
  size_t end_offset = GetLineOffset(line_no + 1);
765
64.8k
  if (end_offset == UINT32_MAX) {
766
1.05k
    end_offset = m_data_sp->GetByteSize();
767
1.05k
  }
768
64.8k
  buffer.assign((const char *)m_data_sp->GetBytes() + start_offset,
769
64.8k
                end_offset - start_offset);
770
771
64.8k
  return true;
772
65.8k
}
773
774
void SourceManager::SourceFileCache::AddSourceFile(const FileSpec &file_spec,
775
2.48k
                                                   FileSP file_sp) {
776
2.48k
  llvm::sys::ScopedWriter guard(m_mutex);
777
778
2.48k
  assert(file_sp && "invalid FileSP");
779
780
2.48k
  AddSourceFileImpl(file_spec, file_sp);
781
2.48k
  const FileSpec &resolved_file_spec = file_sp->GetFileSpec();
782
2.48k
  if (file_spec != resolved_file_spec)
783
2
    AddSourceFileImpl(file_sp->GetFileSpec(), file_sp);
784
2.48k
}
785
786
0
void SourceManager::SourceFileCache::RemoveSourceFile(const FileSP &file_sp) {
787
0
  llvm::sys::ScopedWriter guard(m_mutex);
788
789
0
  assert(file_sp && "invalid FileSP");
790
791
  // Iterate over all the elements in the cache.
792
  // This is expensive but a relatively uncommon operation.
793
0
  auto it = m_file_cache.begin();
794
0
  while (it != m_file_cache.end()) {
795
0
    if (it->second == file_sp)
796
0
      it = m_file_cache.erase(it);
797
0
    else
798
0
      it++;
799
0
  }
800
0
}
801
802
void SourceManager::SourceFileCache::AddSourceFileImpl(
803
2.49k
    const FileSpec &file_spec, FileSP file_sp) {
804
2.49k
  FileCache::iterator pos = m_file_cache.find(file_spec);
805
2.49k
  if (pos == m_file_cache.end()) {
806
2.48k
    m_file_cache[file_spec] = file_sp;
807
2.48k
  } else {
808
2
    if (file_sp != pos->second)
809
2
      m_file_cache[file_spec] = file_sp;
810
2
  }
811
2.49k
}
812
813
SourceManager::FileSP SourceManager::SourceFileCache::FindSourceFile(
814
19.6k
    const FileSpec &file_spec) const {
815
19.6k
  llvm::sys::ScopedReader guard(m_mutex);
816
817
19.6k
  FileCache::const_iterator pos = m_file_cache.find(file_spec);
818
19.6k
  if (pos != m_file_cache.end())
819
12.1k
    return pos->second;
820
7.49k
  return {};
821
19.6k
}
822
823
4
void SourceManager::SourceFileCache::Dump(Stream &stream) const {
824
4
  stream << "Modification time   Lines    Path\n";
825
4
  stream << "------------------- -------- --------------------------------\n";
826
4
  for (auto &entry : m_file_cache) {
827
2
    if (!entry.second)
828
0
      continue;
829
2
    FileSP file = entry.second;
830
2
    stream.Format("{0:%Y-%m-%d %H:%M:%S} {1,8:d} {2}\n", file->GetTimestamp(),
831
2
                  file->GetNumLines(), entry.first.GetPath());
832
2
  }
833
4
}