Coverage Report

Created: 2023-09-21 18:56

/Users/buildslave/jenkins/workspace/coverage/llvm-project/lldb/source/Host/common/Editline.cpp
Line
Count
Source (jump to first uncovered line)
1
//===-- Editline.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 <climits>
10
#include <iomanip>
11
#include <optional>
12
13
#include "lldb/Host/Editline.h"
14
15
#include "lldb/Host/ConnectionFileDescriptor.h"
16
#include "lldb/Host/FileSystem.h"
17
#include "lldb/Host/Host.h"
18
#include "lldb/Utility/CompletionRequest.h"
19
#include "lldb/Utility/FileSpec.h"
20
#include "lldb/Utility/LLDBAssert.h"
21
#include "lldb/Utility/SelectHelper.h"
22
#include "lldb/Utility/Status.h"
23
#include "lldb/Utility/StreamString.h"
24
#include "lldb/Utility/StringList.h"
25
#include "lldb/Utility/Timeout.h"
26
27
#include "llvm/Support/FileSystem.h"
28
#include "llvm/Support/Locale.h"
29
#include "llvm/Support/Threading.h"
30
31
using namespace lldb_private;
32
using namespace lldb_private::line_editor;
33
34
// Workaround for what looks like an OS X-specific issue, but other platforms
35
// may benefit from something similar if issues arise.  The libedit library
36
// doesn't explicitly initialize the curses termcap library, which it gets away
37
// with until TERM is set to VT100 where it stumbles over an implementation
38
// assumption that may not exist on other platforms.  The setupterm() function
39
// would normally require headers that don't work gracefully in this context,
40
// so the function declaration has been hoisted here.
41
#if defined(__APPLE__)
42
extern "C" {
43
int setupterm(char *term, int fildes, int *errret);
44
}
45
#define USE_SETUPTERM_WORKAROUND
46
#endif
47
48
// Editline uses careful cursor management to achieve the illusion of editing a
49
// multi-line block of text with a single line editor.  Preserving this
50
// illusion requires fairly careful management of cursor state.  Read and
51
// understand the relationship between DisplayInput(), MoveCursor(),
52
// SetCurrentLine(), and SaveEditedLine() before making changes.
53
54
/// https://www.ecma-international.org/publications/files/ECMA-ST/Ecma-048.pdf
55
189
#define ESCAPE "\x1b"
56
1
#define ANSI_CLEAR_BELOW ESCAPE "[J"
57
#define ANSI_CLEAR_RIGHT ESCAPE "[K"
58
75
#define ANSI_SET_COLUMN_N ESCAPE "[%dG"
59
5
#define ANSI_UP_N_ROWS ESCAPE "[%dA"
60
0
#define ANSI_DOWN_N_ROWS ESCAPE "[%dB"
61
62
#if LLDB_EDITLINE_USE_WCHAR
63
64
5
#define EditLineConstString(str) L##str
65
#define EditLineStringFormatSpec "%ls"
66
67
#else
68
69
#define EditLineConstString(str) str
70
#define EditLineStringFormatSpec "%s"
71
72
// use #defines so wide version functions and structs will resolve to old
73
// versions for case of libedit not built with wide char support
74
#define history_w history
75
#define history_winit history_init
76
#define history_wend history_end
77
#define HistoryW History
78
#define HistEventW HistEvent
79
#define LineInfoW LineInfo
80
81
#define el_wgets el_gets
82
#define el_wgetc el_getc
83
#define el_wpush el_push
84
#define el_wparse el_parse
85
#define el_wset el_set
86
#define el_wget el_get
87
#define el_wline el_line
88
#define el_winsertstr el_insertstr
89
#define el_wdeletestr el_deletestr
90
91
#endif // #if LLDB_EDITLINE_USE_WCHAR
92
93
5
bool IsOnlySpaces(const EditLineStringType &content) {
94
5
  for (wchar_t ch : content) {
95
0
    if (ch != EditLineCharType(' '))
96
0
      return false;
97
0
  }
98
5
  return true;
99
5
}
100
101
409
static size_t ColumnWidth(llvm::StringRef str) {
102
409
  return llvm::sys::locale::columnWidth(str);
103
409
}
104
105
0
static int GetOperation(HistoryOperation op) {
106
  // The naming used by editline for the history operations is counter
107
  // intuitive to how it's used in LLDB's editline implementation.
108
  //
109
  //  - The H_LAST returns the oldest entry in the history.
110
  //
111
  //  - The H_PREV operation returns the previous element in the history, which
112
  //    is newer than the current one.
113
  //
114
  //  - The H_CURR returns the current entry in the history.
115
  //
116
  //  - The H_NEXT operation returns the next element in the history, which is
117
  //    older than the current one.
118
  //
119
  //  - The H_FIRST returns the most recent entry in the history.
120
  //
121
  // The naming of the enum entries match the semantic meaning.
122
0
  switch(op) {
123
0
    case HistoryOperation::Oldest:
124
0
      return H_LAST;
125
0
    case HistoryOperation::Older:
126
0
      return H_NEXT;
127
0
    case HistoryOperation::Current:
128
0
      return H_CURR;
129
0
    case HistoryOperation::Newer:
130
0
      return H_PREV;
131
0
    case HistoryOperation::Newest:
132
0
      return H_FIRST;
133
0
  }
134
0
  llvm_unreachable("Fully covered switch!");
135
0
}
136
137
138
2
EditLineStringType CombineLines(const std::vector<EditLineStringType> &lines) {
139
2
  EditLineStringStreamType combined_stream;
140
6
  for (EditLineStringType line : lines) {
141
6
    combined_stream << line.c_str() << "\n";
142
6
  }
143
2
  return combined_stream.str();
144
2
}
145
146
50
std::vector<EditLineStringType> SplitLines(const EditLineStringType &input) {
147
50
  std::vector<EditLineStringType> result;
148
50
  size_t start = 0;
149
100
  while (start < input.length()) {
150
50
    size_t end = input.find('\n', start);
151
50
    if (end == std::string::npos) {
152
0
      result.push_back(input.substr(start));
153
0
      break;
154
0
    }
155
50
    result.push_back(input.substr(start, end - start));
156
50
    start = end + 1;
157
50
  }
158
  // Treat an empty history session as a single command of zero-length instead
159
  // of returning an empty vector.
160
50
  if (result.empty()) {
161
0
    result.emplace_back();
162
0
  }
163
50
  return result;
164
50
}
165
166
EditLineStringType FixIndentation(const EditLineStringType &line,
167
0
                                  int indent_correction) {
168
0
  if (indent_correction == 0)
169
0
    return line;
170
0
  if (indent_correction < 0)
171
0
    return line.substr(-indent_correction);
172
0
  return EditLineStringType(indent_correction, EditLineCharType(' ')) + line;
173
0
}
174
175
0
int GetIndentation(const EditLineStringType &line) {
176
0
  int space_count = 0;
177
0
  for (EditLineCharType ch : line) {
178
0
    if (ch != EditLineCharType(' '))
179
0
      break;
180
0
    ++space_count;
181
0
  }
182
0
  return space_count;
183
0
}
184
185
12
bool IsInputPending(FILE *file) {
186
  // FIXME: This will be broken on Windows if we ever re-enable Editline.  You
187
  // can't use select
188
  // on something that isn't a socket.  This will have to be re-written to not
189
  // use a FILE*, but instead use some kind of yet-to-be-created abstraction
190
  // that select-like functionality on non-socket objects.
191
12
  const int fd = fileno(file);
192
12
  SelectHelper select_helper;
193
12
  select_helper.SetTimeout(std::chrono::microseconds(0));
194
12
  select_helper.FDSetRead(fd);
195
12
  return select_helper.Select().Success();
196
12
}
197
198
namespace lldb_private {
199
namespace line_editor {
200
typedef std::weak_ptr<EditlineHistory> EditlineHistoryWP;
201
202
// EditlineHistory objects are sometimes shared between multiple Editline
203
// instances with the same program name.
204
205
class EditlineHistory {
206
private:
207
  // Use static GetHistory() function to get a EditlineHistorySP to one of
208
  // these objects
209
  EditlineHistory(const std::string &prefix, uint32_t size, bool unique_entries)
210
14
      : m_prefix(prefix) {
211
14
    m_history = history_winit();
212
14
    history_w(m_history, &m_event, H_SETSIZE, size);
213
14
    if (unique_entries)
214
14
      history_w(m_history, &m_event, H_SETUNIQUE, 1);
215
14
  }
216
217
28
  const char *GetHistoryFilePath() {
218
    // Compute the history path lazily.
219
28
    if (m_path.empty() && 
m_history14
&&
!m_prefix.empty()14
) {
220
14
      llvm::SmallString<128> lldb_history_file;
221
14
      FileSystem::Instance().GetHomeDirectory(lldb_history_file);
222
14
      llvm::sys::path::append(lldb_history_file, ".lldb");
223
224
      // LLDB stores its history in ~/.lldb/. If for some reason this directory
225
      // isn't writable or cannot be created, history won't be available.
226
14
      if (!llvm::sys::fs::create_directory(lldb_history_file)) {
227
14
#if LLDB_EDITLINE_USE_WCHAR
228
14
        std::string filename = m_prefix + "-widehistory";
229
#else
230
        std::string filename = m_prefix + "-history";
231
#endif
232
14
        llvm::sys::path::append(lldb_history_file, filename);
233
14
        m_path = std::string(lldb_history_file.str());
234
14
      }
235
14
    }
236
237
28
    if (m_path.empty())
238
0
      return nullptr;
239
240
28
    return m_path.c_str();
241
28
  }
242
243
public:
244
14
  ~EditlineHistory() {
245
14
    Save();
246
247
14
    if (m_history) {
248
14
      history_wend(m_history);
249
14
      m_history = nullptr;
250
14
    }
251
14
  }
252
253
14
  static EditlineHistorySP GetHistory(const std::string &prefix) {
254
14
    typedef std::map<std::string, EditlineHistoryWP> WeakHistoryMap;
255
14
    static std::recursive_mutex g_mutex;
256
14
    static WeakHistoryMap g_weak_map;
257
14
    std::lock_guard<std::recursive_mutex> guard(g_mutex);
258
14
    WeakHistoryMap::const_iterator pos = g_weak_map.find(prefix);
259
14
    EditlineHistorySP history_sp;
260
14
    if (pos != g_weak_map.end()) {
261
0
      history_sp = pos->second.lock();
262
0
      if (history_sp)
263
0
        return history_sp;
264
0
      g_weak_map.erase(pos);
265
0
    }
266
14
    history_sp.reset(new EditlineHistory(prefix, 800, true));
267
14
    g_weak_map[prefix] = history_sp;
268
14
    return history_sp;
269
14
  }
270
271
14
  bool IsValid() const { return m_history != nullptr; }
272
273
14
  HistoryW *GetHistoryPtr() { return m_history; }
274
275
52
  void Enter(const EditLineCharType *line_cstr) {
276
52
    if (m_history)
277
52
      history_w(m_history, &m_event, H_ENTER, line_cstr);
278
52
  }
279
280
14
  bool Load() {
281
14
    if (m_history) {
282
14
      const char *path = GetHistoryFilePath();
283
14
      if (path) {
284
14
        history_w(m_history, &m_event, H_LOAD, path);
285
14
        return true;
286
14
      }
287
14
    }
288
0
    return false;
289
14
  }
290
291
14
  bool Save() {
292
14
    if (m_history) {
293
14
      const char *path = GetHistoryFilePath();
294
14
      if (path) {
295
14
        history_w(m_history, &m_event, H_SAVE, path);
296
14
        return true;
297
14
      }
298
14
    }
299
0
    return false;
300
14
  }
301
302
protected:
303
  /// The history object.
304
  HistoryW *m_history = nullptr;
305
  /// The history event needed to contain all history events.
306
  HistEventW m_event;
307
  /// The prefix name (usually the editline program name) to use when
308
  /// loading/saving history.
309
  std::string m_prefix;
310
  /// Path to the history file.
311
  std::string m_path;
312
};
313
}
314
}
315
316
// Editline private methods
317
318
2
void Editline::SetBaseLineNumber(int line_number) {
319
2
  m_base_line_number = line_number;
320
2
  m_line_number_digits =
321
2
      std::max<int>(3, std::to_string(line_number).length() + 1);
322
2
}
323
324
482
std::string Editline::PromptForIndex(int line_index) {
325
482
  bool use_line_numbers = m_multiline_enabled && 
m_base_line_number > 0386
;
326
482
  std::string prompt = m_set_prompt;
327
482
  if (use_line_numbers && 
prompt.length() == 0110
)
328
0
    prompt = ": ";
329
482
  std::string continuation_prompt = prompt;
330
482
  if (m_set_continuation_prompt.length() > 0) {
331
0
    continuation_prompt = m_set_continuation_prompt;
332
    // Ensure that both prompts are the same length through space padding
333
0
    const size_t prompt_width = ColumnWidth(prompt);
334
0
    const size_t cont_prompt_width = ColumnWidth(continuation_prompt);
335
0
    const size_t padded_prompt_width =
336
0
        std::max(prompt_width, cont_prompt_width);
337
0
    if (prompt_width < padded_prompt_width)
338
0
      prompt += std::string(padded_prompt_width - prompt_width, ' ');
339
0
    else if (cont_prompt_width < padded_prompt_width)
340
0
      continuation_prompt +=
341
0
          std::string(padded_prompt_width - cont_prompt_width, ' ');
342
0
  }
343
344
482
  if (use_line_numbers) {
345
110
    StreamString prompt_stream;
346
110
    prompt_stream.Printf(
347
110
        "%*d%s", m_line_number_digits, m_base_line_number + line_index,
348
110
        (line_index == 0) ? 
prompt.c_str()99
:
continuation_prompt.c_str()11
);
349
110
    return std::string(std::move(prompt_stream.GetString()));
350
110
  }
351
372
  return (line_index == 0) ? 
prompt370
:
continuation_prompt2
;
352
482
}
353
354
57
void Editline::SetCurrentLine(int line_index) {
355
57
  m_current_line_index = line_index;
356
57
  m_current_prompt = PromptForIndex(line_index);
357
57
}
358
359
353
size_t Editline::GetPromptWidth() { return ColumnWidth(PromptForIndex(0)); }
360
361
2
bool Editline::IsEmacs() {
362
2
  const char *editor;
363
2
  el_get(m_editline, EL_EDITOR, &editor);
364
2
  return editor[0] == 'e';
365
2
}
366
367
0
bool Editline::IsOnlySpaces() {
368
0
  const LineInfoW *info = el_wline(m_editline);
369
0
  for (const EditLineCharType *character = info->buffer;
370
0
       character < info->lastchar; character++) {
371
0
    if (*character != ' ')
372
0
      return false;
373
0
  }
374
0
  return true;
375
0
}
376
377
128
int Editline::GetLineIndexForLocation(CursorLocation location, int cursor_row) {
378
128
  int line = 0;
379
128
  if (location == CursorLocation::EditingPrompt ||
380
128
      
location == CursorLocation::BlockEnd73
||
381
128
      
location == CursorLocation::EditingCursor60
) {
382
169
    for (unsigned index = 0; index < m_current_line_index; 
index++44
) {
383
44
      line += CountRowsForLine(m_input_lines[index]);
384
44
    }
385
125
    if (location == CursorLocation::EditingCursor) {
386
57
      line += cursor_row;
387
68
    } else if (location == CursorLocation::BlockEnd) {
388
25
      for (unsigned index = m_current_line_index; index < m_input_lines.size();
389
13
           
index++12
) {
390
12
        line += CountRowsForLine(m_input_lines[index]);
391
12
      }
392
13
      --line;
393
13
    }
394
125
  }
395
128
  return line;
396
128
}
397
398
64
void Editline::MoveCursor(CursorLocation from, CursorLocation to) {
399
64
  const LineInfoW *info = el_wline(m_editline);
400
64
  int editline_cursor_position =
401
64
      (int)((info->cursor - info->buffer) + GetPromptWidth());
402
64
  int editline_cursor_row = editline_cursor_position / m_terminal_width;
403
404
  // Determine relative starting and ending lines
405
64
  int fromLine = GetLineIndexForLocation(from, editline_cursor_row);
406
64
  int toLine = GetLineIndexForLocation(to, editline_cursor_row);
407
64
  if (toLine != fromLine) {
408
5
    fprintf(m_output_file,
409
5
            (toLine > fromLine) ? ANSI_DOWN_N_ROWS : ANSI_UP_N_ROWS,
410
5
            std::abs(toLine - fromLine));
411
5
  }
412
413
  // Determine target column
414
64
  int toColumn = 1;
415
64
  if (to == CursorLocation::EditingCursor) {
416
25
    toColumn =
417
25
        editline_cursor_position - (editline_cursor_row * m_terminal_width) + 1;
418
39
  } else if (to == CursorLocation::BlockEnd && 
!m_input_lines.empty()2
) {
419
2
    toColumn =
420
2
        ((m_input_lines[m_input_lines.size() - 1].length() + GetPromptWidth()) %
421
2
         80) +
422
2
        1;
423
2
  }
424
64
  fprintf(m_output_file, ANSI_SET_COLUMN_N, toColumn);
425
64
}
426
427
11
void Editline::DisplayInput(int firstIndex) {
428
11
  fprintf(m_output_file, ANSI_SET_COLUMN_N ANSI_CLEAR_BELOW, 1);
429
11
  int line_count = (int)m_input_lines.size();
430
27
  for (int index = firstIndex; index < line_count; 
index++16
) {
431
16
    fprintf(m_output_file,
432
16
            "%s"
433
16
            "%s"
434
16
            "%s" EditLineStringFormatSpec " ",
435
16
            m_prompt_ansi_prefix.c_str(), PromptForIndex(index).c_str(),
436
16
            m_prompt_ansi_suffix.c_str(), m_input_lines[index].c_str());
437
16
    if (index < line_count - 1)
438
5
      fprintf(m_output_file, "\n");
439
16
  }
440
11
}
441
442
56
int Editline::CountRowsForLine(const EditLineStringType &content) {
443
56
  std::string prompt =
444
56
      PromptForIndex(0); // Prompt width is constant during an edit session
445
56
  int line_length = (int)(content.length() + ColumnWidth(prompt));
446
56
  return (line_length / m_terminal_width) + 1;
447
56
}
448
449
5
void Editline::SaveEditedLine() {
450
5
  const LineInfoW *info = el_wline(m_editline);
451
5
  m_input_lines[m_current_line_index] =
452
5
      EditLineStringType(info->buffer, info->lastchar - info->buffer);
453
5
}
454
455
4
StringList Editline::GetInputAsStringList(int line_count) {
456
4
  StringList lines;
457
13
  for (EditLineStringType line : m_input_lines) {
458
13
    if (line_count == 0)
459
0
      break;
460
13
#if LLDB_EDITLINE_USE_WCHAR
461
13
    lines.AppendString(m_utf8conv.to_bytes(line));
462
#else
463
    lines.AppendString(line);
464
#endif
465
13
    --line_count;
466
13
  }
467
4
  return lines;
468
4
}
469
470
0
unsigned char Editline::RecallHistory(HistoryOperation op) {
471
0
  assert(op == HistoryOperation::Older || op == HistoryOperation::Newer);
472
0
  if (!m_history_sp || !m_history_sp->IsValid())
473
0
    return CC_ERROR;
474
475
0
  HistoryW *pHistory = m_history_sp->GetHistoryPtr();
476
0
  HistEventW history_event;
477
0
  std::vector<EditLineStringType> new_input_lines;
478
479
  // Treat moving from the "live" entry differently
480
0
  if (!m_in_history) {
481
0
    switch (op) {
482
0
    case HistoryOperation::Newer:
483
0
      return CC_ERROR; // Can't go newer than the "live" entry
484
0
    case HistoryOperation::Older: {
485
0
      if (history_w(pHistory, &history_event,
486
0
                    GetOperation(HistoryOperation::Newest)) == -1)
487
0
        return CC_ERROR;
488
      // Save any edits to the "live" entry in case we return by moving forward
489
      // in history (it would be more bash-like to save over any current entry,
490
      // but libedit doesn't offer the ability to add entries anywhere except
491
      // the end.)
492
0
      SaveEditedLine();
493
0
      m_live_history_lines = m_input_lines;
494
0
      m_in_history = true;
495
0
    } break;
496
0
    default:
497
0
      llvm_unreachable("unsupported history direction");
498
0
    }
499
0
  } else {
500
0
    if (history_w(pHistory, &history_event, GetOperation(op)) == -1) {
501
0
      switch (op) {
502
0
      case HistoryOperation::Older:
503
        // Can't move earlier than the earliest entry.
504
0
        return CC_ERROR;
505
0
      case HistoryOperation::Newer:
506
        // Moving to newer-than-the-newest entry yields the "live" entry.
507
0
        new_input_lines = m_live_history_lines;
508
0
        m_in_history = false;
509
0
        break;
510
0
      default:
511
0
        llvm_unreachable("unsupported history direction");
512
0
      }
513
0
    }
514
0
  }
515
516
  // If we're pulling the lines from history, split them apart
517
0
  if (m_in_history)
518
0
    new_input_lines = SplitLines(history_event.str);
519
520
  // Erase the current edit session and replace it with a new one
521
0
  MoveCursor(CursorLocation::EditingCursor, CursorLocation::BlockStart);
522
0
  m_input_lines = new_input_lines;
523
0
  DisplayInput();
524
525
  // Prepare to edit the last line when moving to previous entry, or the first
526
  // line when moving to next entry
527
0
  switch (op) {
528
0
  case HistoryOperation::Older:
529
0
    m_current_line_index = (int)m_input_lines.size() - 1;
530
0
    break;
531
0
  case HistoryOperation::Newer:
532
0
    m_current_line_index = 0;
533
0
    break;
534
0
  default:
535
0
    llvm_unreachable("unsupported history direction");
536
0
  }
537
0
  SetCurrentLine(m_current_line_index);
538
0
  MoveCursor(CursorLocation::BlockEnd, CursorLocation::EditingPrompt);
539
0
  return CC_NEWLINE;
540
0
}
541
542
1.78k
int Editline::GetCharacter(EditLineGetCharType *c) {
543
1.78k
  const LineInfoW *info = el_wline(m_editline);
544
545
  // Paint a ANSI formatted version of the desired prompt over the version
546
  // libedit draws. (will only be requested if colors are supported)
547
1.78k
  if (m_needs_prompt_repaint) {
548
21
    MoveCursor(CursorLocation::EditingCursor, CursorLocation::EditingPrompt);
549
21
    fprintf(m_output_file,
550
21
            "%s"
551
21
            "%s"
552
21
            "%s",
553
21
            m_prompt_ansi_prefix.c_str(), Prompt(),
554
21
            m_prompt_ansi_suffix.c_str());
555
21
    MoveCursor(CursorLocation::EditingPrompt, CursorLocation::EditingCursor);
556
21
    m_needs_prompt_repaint = false;
557
21
  }
558
559
1.78k
  if (m_multiline_enabled) {
560
    // Detect when the number of rows used for this input line changes due to
561
    // an edit
562
287
    int lineLength = (int)((info->lastchar - info->buffer) + GetPromptWidth());
563
287
    int new_line_rows = (lineLength / m_terminal_width) + 1;
564
287
    if (m_current_line_rows != -1 && 
new_line_rows != m_current_line_rows280
) {
565
      // Respond by repainting the current state from this line on
566
3
      MoveCursor(CursorLocation::EditingCursor, CursorLocation::EditingPrompt);
567
3
      SaveEditedLine();
568
3
      DisplayInput(m_current_line_index);
569
3
      MoveCursor(CursorLocation::BlockEnd, CursorLocation::EditingCursor);
570
3
    }
571
287
    m_current_line_rows = new_line_rows;
572
287
  }
573
574
  // Read an actual character
575
1.78k
  while (true) {
576
1.78k
    lldb::ConnectionStatus status = lldb::eConnectionStatusSuccess;
577
1.78k
    char ch = 0;
578
579
1.78k
    if (m_terminal_size_has_changed)
580
0
      ApplyTerminalSizeChange();
581
582
    // This mutex is locked by our caller (GetLine). Unlock it while we read a
583
    // character (blocking operation), so we do not hold the mutex
584
    // indefinitely. This gives a chance for someone to interrupt us. After
585
    // Read returns, immediately lock the mutex again and check if we were
586
    // interrupted.
587
1.78k
    m_output_mutex.unlock();
588
1.78k
    int read_count =
589
1.78k
        m_input_connection.Read(&ch, 1, std::nullopt, status, nullptr);
590
1.78k
    m_output_mutex.lock();
591
1.78k
    if (m_editor_status == EditorStatus::Interrupted) {
592
0
      while (read_count > 0 && status == lldb::eConnectionStatusSuccess)
593
0
        read_count =
594
0
            m_input_connection.Read(&ch, 1, std::nullopt, status, nullptr);
595
0
      lldbassert(status == lldb::eConnectionStatusInterrupted);
596
0
      return 0;
597
0
    }
598
599
1.78k
    if (read_count) {
600
1.78k
      if (CompleteCharacter(ch, *c))
601
1.78k
        return 1;
602
1.78k
    } else {
603
0
      switch (status) {
604
0
      case lldb::eConnectionStatusSuccess: // Success
605
0
        break;
606
607
0
      case lldb::eConnectionStatusInterrupted:
608
0
        llvm_unreachable("Interrupts should have been handled above.");
609
610
0
      case lldb::eConnectionStatusError:        // Check GetError() for details
611
0
      case lldb::eConnectionStatusTimedOut:     // Request timed out
612
0
      case lldb::eConnectionStatusEndOfFile:    // End-of-file encountered
613
0
      case lldb::eConnectionStatusNoConnection: // No connection
614
0
      case lldb::eConnectionStatusLostConnection: // Lost connection while
615
                                                  // connected to a valid
616
                                                  // connection
617
0
        m_editor_status = EditorStatus::EndOfInput;
618
0
        return 0;
619
0
      }
620
0
    }
621
1.78k
  }
622
1.78k
}
623
624
85
const char *Editline::Prompt() {
625
85
  if (!m_prompt_ansi_prefix.empty() || 
!m_prompt_ansi_suffix.empty()43
)
626
42
    m_needs_prompt_repaint = true;
627
85
  return m_current_prompt.c_str();
628
85
}
629
630
5
unsigned char Editline::BreakLineCommand(int ch) {
631
  // Preserve any content beyond the cursor, truncate and save the current line
632
5
  const LineInfoW *info = el_wline(m_editline);
633
5
  auto current_line =
634
5
      EditLineStringType(info->buffer, info->cursor - info->buffer);
635
5
  auto new_line_fragment =
636
5
      EditLineStringType(info->cursor, info->lastchar - info->cursor);
637
5
  m_input_lines[m_current_line_index] = current_line;
638
639
  // Ignore whitespace-only extra fragments when breaking a line
640
5
  if (::IsOnlySpaces(new_line_fragment))
641
5
    new_line_fragment = EditLineConstString("");
642
643
  // Establish the new cursor position at the start of a line when inserting a
644
  // line break
645
5
  m_revert_cursor_index = 0;
646
647
  // Don't perform automatic formatting when pasting
648
5
  if (!IsInputPending(m_input_file)) {
649
    // Apply smart indentation
650
0
    if (m_fix_indentation_callback) {
651
0
      StringList lines = GetInputAsStringList(m_current_line_index + 1);
652
0
#if LLDB_EDITLINE_USE_WCHAR
653
0
      lines.AppendString(m_utf8conv.to_bytes(new_line_fragment));
654
#else
655
      lines.AppendString(new_line_fragment);
656
#endif
657
658
0
      int indent_correction = m_fix_indentation_callback(this, lines, 0);
659
0
      new_line_fragment = FixIndentation(new_line_fragment, indent_correction);
660
0
      m_revert_cursor_index = GetIndentation(new_line_fragment);
661
0
    }
662
0
  }
663
664
  // Insert the new line and repaint everything from the split line on down
665
5
  m_input_lines.insert(m_input_lines.begin() + m_current_line_index + 1,
666
5
                       new_line_fragment);
667
5
  MoveCursor(CursorLocation::EditingCursor, CursorLocation::EditingPrompt);
668
5
  DisplayInput(m_current_line_index);
669
670
  // Reposition the cursor to the right line and prepare to edit the new line
671
5
  SetCurrentLine(m_current_line_index + 1);
672
5
  MoveCursor(CursorLocation::BlockEnd, CursorLocation::EditingPrompt);
673
5
  return CC_NEWLINE;
674
5
}
675
676
7
unsigned char Editline::EndOrAddLineCommand(int ch) {
677
  // Don't perform end of input detection when pasting, always treat this as a
678
  // line break
679
7
  if (IsInputPending(m_input_file)) {
680
5
    return BreakLineCommand(ch);
681
5
  }
682
683
  // Save any edits to this line
684
2
  SaveEditedLine();
685
686
  // If this is the end of the last line, consider whether to add a line
687
  // instead
688
2
  const LineInfoW *info = el_wline(m_editline);
689
2
  if (m_current_line_index == m_input_lines.size() - 1 &&
690
2
      info->cursor == info->lastchar) {
691
2
    if (m_is_input_complete_callback) {
692
2
      auto lines = GetInputAsStringList();
693
2
      if (!m_is_input_complete_callback(this, lines)) {
694
0
        return BreakLineCommand(ch);
695
0
      }
696
697
      // The completion test is allowed to change the input lines when complete
698
2
      m_input_lines.clear();
699
8
      for (unsigned index = 0; index < lines.GetSize(); 
index++6
) {
700
6
#if LLDB_EDITLINE_USE_WCHAR
701
6
        m_input_lines.insert(m_input_lines.end(),
702
6
                             m_utf8conv.from_bytes(lines[index]));
703
#else
704
        m_input_lines.insert(m_input_lines.end(), lines[index]);
705
#endif
706
6
      }
707
2
    }
708
2
  }
709
2
  MoveCursor(CursorLocation::EditingCursor, CursorLocation::BlockEnd);
710
2
  fprintf(m_output_file, "\n");
711
2
  m_editor_status = EditorStatus::Complete;
712
2
  return CC_NEWLINE;
713
2
}
714
715
0
unsigned char Editline::DeleteNextCharCommand(int ch) {
716
0
  LineInfoW *info = const_cast<LineInfoW *>(el_wline(m_editline));
717
718
  // Just delete the next character normally if possible
719
0
  if (info->cursor < info->lastchar) {
720
0
    info->cursor++;
721
0
    el_deletestr(m_editline, 1);
722
0
    return CC_REFRESH;
723
0
  }
724
725
  // Fail when at the end of the last line, except when ^D is pressed on the
726
  // line is empty, in which case it is treated as EOF
727
0
  if (m_current_line_index == m_input_lines.size() - 1) {
728
0
    if (ch == 4 && info->buffer == info->lastchar) {
729
0
      fprintf(m_output_file, "^D\n");
730
0
      m_editor_status = EditorStatus::EndOfInput;
731
0
      return CC_EOF;
732
0
    }
733
0
    return CC_ERROR;
734
0
  }
735
736
  // Prepare to combine this line with the one below
737
0
  MoveCursor(CursorLocation::EditingCursor, CursorLocation::EditingPrompt);
738
739
  // Insert the next line of text at the cursor and restore the cursor position
740
0
  const EditLineCharType *cursor = info->cursor;
741
0
  el_winsertstr(m_editline, m_input_lines[m_current_line_index + 1].c_str());
742
0
  info->cursor = cursor;
743
0
  SaveEditedLine();
744
745
  // Delete the extra line
746
0
  m_input_lines.erase(m_input_lines.begin() + m_current_line_index + 1);
747
748
  // Clear and repaint from this line on down
749
0
  DisplayInput(m_current_line_index);
750
0
  MoveCursor(CursorLocation::BlockEnd, CursorLocation::EditingCursor);
751
0
  return CC_REFRESH;
752
0
}
753
754
0
unsigned char Editline::DeletePreviousCharCommand(int ch) {
755
0
  LineInfoW *info = const_cast<LineInfoW *>(el_wline(m_editline));
756
757
  // Just delete the previous character normally when not at the start of a
758
  // line
759
0
  if (info->cursor > info->buffer) {
760
0
    el_deletestr(m_editline, 1);
761
0
    return CC_REFRESH;
762
0
  }
763
764
  // No prior line and no prior character?  Let the user know
765
0
  if (m_current_line_index == 0)
766
0
    return CC_ERROR;
767
768
  // No prior character, but prior line?  Combine with the line above
769
0
  SaveEditedLine();
770
0
  SetCurrentLine(m_current_line_index - 1);
771
0
  auto priorLine = m_input_lines[m_current_line_index];
772
0
  m_input_lines.erase(m_input_lines.begin() + m_current_line_index);
773
0
  m_input_lines[m_current_line_index] =
774
0
      priorLine + m_input_lines[m_current_line_index];
775
776
  // Repaint from the new line down
777
0
  fprintf(m_output_file, ANSI_UP_N_ROWS ANSI_SET_COLUMN_N,
778
0
          CountRowsForLine(priorLine), 1);
779
0
  DisplayInput(m_current_line_index);
780
781
  // Put the cursor back where libedit expects it to be before returning to
782
  // editing by telling libedit about the newly inserted text
783
0
  MoveCursor(CursorLocation::BlockEnd, CursorLocation::EditingPrompt);
784
0
  el_winsertstr(m_editline, priorLine.c_str());
785
0
  return CC_REDISPLAY;
786
0
}
787
788
0
unsigned char Editline::PreviousLineCommand(int ch) {
789
0
  SaveEditedLine();
790
791
0
  if (m_current_line_index == 0) {
792
0
    return RecallHistory(HistoryOperation::Older);
793
0
  }
794
795
  // Start from a known location
796
0
  MoveCursor(CursorLocation::EditingCursor, CursorLocation::EditingPrompt);
797
798
  // Treat moving up from a blank last line as a deletion of that line
799
0
  if (m_current_line_index == m_input_lines.size() - 1 && IsOnlySpaces()) {
800
0
    m_input_lines.erase(m_input_lines.begin() + m_current_line_index);
801
0
    fprintf(m_output_file, ANSI_CLEAR_BELOW);
802
0
  }
803
804
0
  SetCurrentLine(m_current_line_index - 1);
805
0
  fprintf(m_output_file, ANSI_UP_N_ROWS ANSI_SET_COLUMN_N,
806
0
          CountRowsForLine(m_input_lines[m_current_line_index]), 1);
807
0
  return CC_NEWLINE;
808
0
}
809
810
0
unsigned char Editline::NextLineCommand(int ch) {
811
0
  SaveEditedLine();
812
813
  // Handle attempts to move down from the last line
814
0
  if (m_current_line_index == m_input_lines.size() - 1) {
815
    // Don't add an extra line if the existing last line is blank, move through
816
    // history instead
817
0
    if (IsOnlySpaces()) {
818
0
      return RecallHistory(HistoryOperation::Newer);
819
0
    }
820
821
    // Determine indentation for the new line
822
0
    int indentation = 0;
823
0
    if (m_fix_indentation_callback) {
824
0
      StringList lines = GetInputAsStringList();
825
0
      lines.AppendString("");
826
0
      indentation = m_fix_indentation_callback(this, lines, 0);
827
0
    }
828
0
    m_input_lines.insert(
829
0
        m_input_lines.end(),
830
0
        EditLineStringType(indentation, EditLineCharType(' ')));
831
0
  }
832
833
  // Move down past the current line using newlines to force scrolling if
834
  // needed
835
0
  SetCurrentLine(m_current_line_index + 1);
836
0
  const LineInfoW *info = el_wline(m_editline);
837
0
  int cursor_position = (int)((info->cursor - info->buffer) + GetPromptWidth());
838
0
  int cursor_row = cursor_position / m_terminal_width;
839
0
  for (int line_count = 0; line_count < m_current_line_rows - cursor_row;
840
0
       line_count++) {
841
0
    fprintf(m_output_file, "\n");
842
0
  }
843
0
  return CC_NEWLINE;
844
0
}
845
846
0
unsigned char Editline::PreviousHistoryCommand(int ch) {
847
0
  SaveEditedLine();
848
849
0
  return RecallHistory(HistoryOperation::Older);
850
0
}
851
852
0
unsigned char Editline::NextHistoryCommand(int ch) {
853
0
  SaveEditedLine();
854
855
0
  return RecallHistory(HistoryOperation::Newer);
856
0
}
857
858
0
unsigned char Editline::FixIndentationCommand(int ch) {
859
0
  if (!m_fix_indentation_callback)
860
0
    return CC_NORM;
861
862
  // Insert the character typed before proceeding
863
0
  EditLineCharType inserted[] = {(EditLineCharType)ch, 0};
864
0
  el_winsertstr(m_editline, inserted);
865
0
  LineInfoW *info = const_cast<LineInfoW *>(el_wline(m_editline));
866
0
  int cursor_position = info->cursor - info->buffer;
867
868
  // Save the edits and determine the correct indentation level
869
0
  SaveEditedLine();
870
0
  StringList lines = GetInputAsStringList(m_current_line_index + 1);
871
0
  int indent_correction =
872
0
      m_fix_indentation_callback(this, lines, cursor_position);
873
874
  // If it is already correct no special work is needed
875
0
  if (indent_correction == 0)
876
0
    return CC_REFRESH;
877
878
  // Change the indentation level of the line
879
0
  std::string currentLine = lines.GetStringAtIndex(m_current_line_index);
880
0
  if (indent_correction > 0) {
881
0
    currentLine = currentLine.insert(0, indent_correction, ' ');
882
0
  } else {
883
0
    currentLine = currentLine.erase(0, -indent_correction);
884
0
  }
885
0
#if LLDB_EDITLINE_USE_WCHAR
886
0
  m_input_lines[m_current_line_index] = m_utf8conv.from_bytes(currentLine);
887
#else
888
  m_input_lines[m_current_line_index] = currentLine;
889
#endif
890
891
  // Update the display to reflect the change
892
0
  MoveCursor(CursorLocation::EditingCursor, CursorLocation::EditingPrompt);
893
0
  DisplayInput(m_current_line_index);
894
895
  // Reposition the cursor back on the original line and prepare to restart
896
  // editing with a new cursor position
897
0
  SetCurrentLine(m_current_line_index);
898
0
  MoveCursor(CursorLocation::BlockEnd, CursorLocation::EditingPrompt);
899
0
  m_revert_cursor_index = cursor_position + indent_correction;
900
0
  return CC_NEWLINE;
901
0
}
902
903
7
unsigned char Editline::RevertLineCommand(int ch) {
904
7
  el_winsertstr(m_editline, m_input_lines[m_current_line_index].c_str());
905
7
  if (m_revert_cursor_index >= 0) {
906
5
    LineInfoW *info = const_cast<LineInfoW *>(el_wline(m_editline));
907
5
    info->cursor = info->buffer + m_revert_cursor_index;
908
5
    if (info->cursor > info->lastchar) {
909
0
      info->cursor = info->lastchar;
910
0
    }
911
5
    m_revert_cursor_index = -1;
912
5
  }
913
7
  return CC_REFRESH;
914
7
}
915
916
0
unsigned char Editline::BufferStartCommand(int ch) {
917
0
  SaveEditedLine();
918
0
  MoveCursor(CursorLocation::EditingCursor, CursorLocation::BlockStart);
919
0
  SetCurrentLine(0);
920
0
  m_revert_cursor_index = 0;
921
0
  return CC_NEWLINE;
922
0
}
923
924
0
unsigned char Editline::BufferEndCommand(int ch) {
925
0
  SaveEditedLine();
926
0
  MoveCursor(CursorLocation::EditingCursor, CursorLocation::BlockEnd);
927
0
  SetCurrentLine((int)m_input_lines.size() - 1);
928
0
  MoveCursor(CursorLocation::BlockEnd, CursorLocation::EditingPrompt);
929
0
  return CC_NEWLINE;
930
0
}
931
932
/// Prints completions and their descriptions to the given file. Only the
933
/// completions in the interval [start, end) are printed.
934
static void
935
PrintCompletion(FILE *output_file,
936
                llvm::ArrayRef<CompletionResult::Completion> results,
937
0
                size_t max_len) {
938
0
  for (const CompletionResult::Completion &c : results) {
939
0
    fprintf(output_file, "\t%-*s", (int)max_len, c.GetCompletion().c_str());
940
0
    if (!c.GetDescription().empty())
941
0
      fprintf(output_file, " -- %s", c.GetDescription().c_str());
942
0
    fprintf(output_file, "\n");
943
0
  }
944
0
}
945
946
static void
947
DisplayCompletions(::EditLine *editline, FILE *output_file,
948
0
                   llvm::ArrayRef<CompletionResult::Completion> results) {
949
0
  assert(!results.empty());
950
951
0
  fprintf(output_file, "\n" ANSI_CLEAR_BELOW "Available completions:\n");
952
0
  const size_t page_size = 40;
953
0
  bool all = false;
954
955
0
  auto longest =
956
0
      std::max_element(results.begin(), results.end(), [](auto &c1, auto &c2) {
957
0
        return c1.GetCompletion().size() < c2.GetCompletion().size();
958
0
      });
959
960
0
  const size_t max_len = longest->GetCompletion().size();
961
962
0
  if (results.size() < page_size) {
963
0
    PrintCompletion(output_file, results, max_len);
964
0
    return;
965
0
  }
966
967
0
  size_t cur_pos = 0;
968
0
  while (cur_pos < results.size()) {
969
0
    size_t remaining = results.size() - cur_pos;
970
0
    size_t next_size = all ? remaining : std::min(page_size, remaining);
971
972
0
    PrintCompletion(output_file, results.slice(cur_pos, next_size), max_len);
973
974
0
    cur_pos += next_size;
975
976
0
    if (cur_pos >= results.size())
977
0
      break;
978
979
0
    fprintf(output_file, "More (Y/n/a): ");
980
0
    char reply = 'n';
981
0
    int got_char = el_getc(editline, &reply);
982
0
    fprintf(output_file, "\n");
983
0
    if (got_char == -1 || reply == 'n')
984
0
      break;
985
0
    if (reply == 'a')
986
0
      all = true;
987
0
  }
988
0
}
989
990
0
unsigned char Editline::TabCommand(int ch) {
991
0
  if (!m_completion_callback)
992
0
    return CC_ERROR;
993
994
0
  const LineInfo *line_info = el_line(m_editline);
995
996
0
  llvm::StringRef line(line_info->buffer,
997
0
                       line_info->lastchar - line_info->buffer);
998
0
  unsigned cursor_index = line_info->cursor - line_info->buffer;
999
0
  CompletionResult result;
1000
0
  CompletionRequest request(line, cursor_index, result);
1001
1002
0
  m_completion_callback(request);
1003
1004
0
  llvm::ArrayRef<CompletionResult::Completion> results = result.GetResults();
1005
1006
0
  StringList completions;
1007
0
  result.GetMatches(completions);
1008
1009
0
  if (results.size() == 0)
1010
0
    return CC_ERROR;
1011
1012
0
  if (results.size() == 1) {
1013
0
    CompletionResult::Completion completion = results.front();
1014
0
    switch (completion.GetMode()) {
1015
0
    case CompletionMode::Normal: {
1016
0
      std::string to_add = completion.GetCompletion();
1017
      // Terminate the current argument with a quote if it started with a quote.
1018
0
      if (!request.GetParsedLine().empty() && request.GetParsedArg().IsQuoted())
1019
0
        to_add.push_back(request.GetParsedArg().GetQuoteChar());
1020
0
      to_add.push_back(' ');
1021
0
      el_deletestr(m_editline, request.GetCursorArgumentPrefix().size());
1022
0
      el_insertstr(m_editline, to_add.c_str());
1023
      // Clear all the autosuggestion parts if the only single space can be completed.
1024
0
      if (to_add == " ")
1025
0
        return CC_REDISPLAY;
1026
0
      return CC_REFRESH;
1027
0
    }
1028
0
    case CompletionMode::Partial: {
1029
0
      std::string to_add = completion.GetCompletion();
1030
0
      to_add = to_add.substr(request.GetCursorArgumentPrefix().size());
1031
0
      el_insertstr(m_editline, to_add.c_str());
1032
0
      break;
1033
0
    }
1034
0
    case CompletionMode::RewriteLine: {
1035
0
      el_deletestr(m_editline, line_info->cursor - line_info->buffer);
1036
0
      el_insertstr(m_editline, completion.GetCompletion().c_str());
1037
0
      break;
1038
0
    }
1039
0
    }
1040
0
    return CC_REDISPLAY;
1041
0
  }
1042
1043
  // If we get a longer match display that first.
1044
0
  std::string longest_prefix = completions.LongestCommonPrefix();
1045
0
  if (!longest_prefix.empty())
1046
0
    longest_prefix =
1047
0
        longest_prefix.substr(request.GetCursorArgumentPrefix().size());
1048
0
  if (!longest_prefix.empty()) {
1049
0
    el_insertstr(m_editline, longest_prefix.c_str());
1050
0
    return CC_REDISPLAY;
1051
0
  }
1052
1053
0
  DisplayCompletions(m_editline, m_output_file, results);
1054
1055
0
  DisplayInput();
1056
0
  MoveCursor(CursorLocation::BlockEnd, CursorLocation::EditingCursor);
1057
0
  return CC_REDISPLAY;
1058
0
}
1059
1060
0
unsigned char Editline::ApplyAutosuggestCommand(int ch) {
1061
0
  if (!m_suggestion_callback) {
1062
0
    return CC_REDISPLAY;
1063
0
  }
1064
1065
0
  const LineInfo *line_info = el_line(m_editline);
1066
0
  llvm::StringRef line(line_info->buffer,
1067
0
                       line_info->lastchar - line_info->buffer);
1068
1069
0
  if (std::optional<std::string> to_add = m_suggestion_callback(line))
1070
0
    el_insertstr(m_editline, to_add->c_str());
1071
1072
0
  return CC_REDISPLAY;
1073
0
}
1074
1075
0
unsigned char Editline::TypedCharacter(int ch) {
1076
0
  std::string typed = std::string(1, ch);
1077
0
  el_insertstr(m_editline, typed.c_str());
1078
1079
0
  if (!m_suggestion_callback) {
1080
0
    return CC_REDISPLAY;
1081
0
  }
1082
1083
0
  const LineInfo *line_info = el_line(m_editline);
1084
0
  llvm::StringRef line(line_info->buffer,
1085
0
                       line_info->lastchar - line_info->buffer);
1086
1087
0
  if (std::optional<std::string> to_add = m_suggestion_callback(line)) {
1088
0
    std::string to_add_color =
1089
0
        m_suggestion_ansi_prefix + to_add.value() + m_suggestion_ansi_suffix;
1090
0
    fputs(typed.c_str(), m_output_file);
1091
0
    fputs(to_add_color.c_str(), m_output_file);
1092
0
    size_t new_autosuggestion_size = line.size() + to_add->length();
1093
    // Print spaces to hide any remains of a previous longer autosuggestion.
1094
0
    if (new_autosuggestion_size < m_previous_autosuggestion_size) {
1095
0
      size_t spaces_to_print =
1096
0
          m_previous_autosuggestion_size - new_autosuggestion_size;
1097
0
      std::string spaces = std::string(spaces_to_print, ' ');
1098
0
      fputs(spaces.c_str(), m_output_file);
1099
0
    }
1100
0
    m_previous_autosuggestion_size = new_autosuggestion_size;
1101
1102
0
    int editline_cursor_position =
1103
0
        (int)((line_info->cursor - line_info->buffer) + GetPromptWidth());
1104
0
    int editline_cursor_row = editline_cursor_position / m_terminal_width;
1105
0
    int toColumn =
1106
0
        editline_cursor_position - (editline_cursor_row * m_terminal_width);
1107
0
    fprintf(m_output_file, ANSI_SET_COLUMN_N, toColumn);
1108
0
    return CC_REFRESH;
1109
0
  }
1110
1111
0
  return CC_REDISPLAY;
1112
0
}
1113
1114
void Editline::AddFunctionToEditLine(const EditLineCharType *command,
1115
                                     const EditLineCharType *helptext,
1116
196
                                     EditlineCommandCallbackType callbackFn) {
1117
196
  el_wset(m_editline, EL_ADDFN, command, helptext, callbackFn);
1118
196
}
1119
1120
void Editline::SetEditLinePromptCallback(
1121
14
    EditlinePromptCallbackType callbackFn) {
1122
14
  el_set(m_editline, EL_PROMPT, callbackFn);
1123
14
}
1124
1125
14
void Editline::SetGetCharacterFunction(EditlineGetCharCallbackType callbackFn) {
1126
14
  el_wset(m_editline, EL_GETCFN, callbackFn);
1127
14
}
1128
1129
58
void Editline::ConfigureEditor(bool multiline) {
1130
58
  if (m_editline && 
m_multiline_enabled == multiline44
)
1131
44
    return;
1132
14
  m_multiline_enabled = multiline;
1133
1134
14
  if (m_editline) {
1135
    // Disable edit mode to stop the terminal from flushing all input during
1136
    // the call to el_end() since we expect to have multiple editline instances
1137
    // in this program.
1138
0
    el_set(m_editline, EL_EDITMODE, 0);
1139
0
    el_end(m_editline);
1140
0
  }
1141
1142
14
  m_editline =
1143
14
      el_init(m_editor_name.c_str(), m_input_file, m_output_file, m_error_file);
1144
14
  ApplyTerminalSizeChange();
1145
1146
14
  if (m_history_sp && m_history_sp->IsValid()) {
1147
14
    if (!m_history_sp->Load()) {
1148
0
        fputs("Could not load history file\n.", m_output_file);
1149
0
    }
1150
14
    el_wset(m_editline, EL_HIST, history, m_history_sp->GetHistoryPtr());
1151
14
  }
1152
14
  el_set(m_editline, EL_CLIENTDATA, this);
1153
14
  el_set(m_editline, EL_SIGNAL, 0);
1154
14
  el_set(m_editline, EL_EDITOR, "emacs");
1155
1156
1.78k
  SetGetCharacterFunction([](EditLine *editline, EditLineGetCharType *c) {
1157
1.78k
    return Editline::InstanceFor(editline)->GetCharacter(c);
1158
1.78k
  });
1159
1160
64
  SetEditLinePromptCallback([](EditLine *editline) {
1161
64
    return Editline::InstanceFor(editline)->Prompt();
1162
64
  });
1163
1164
  // Commands used for multiline support, registered whether or not they're
1165
  // used
1166
14
  AddFunctionToEditLine(
1167
14
      EditLineConstString("lldb-break-line"),
1168
14
      EditLineConstString("Insert a line break"),
1169
14
      [](EditLine *editline, int ch) {
1170
0
        return Editline::InstanceFor(editline)->BreakLineCommand(ch);
1171
0
      });
1172
1173
14
  AddFunctionToEditLine(
1174
14
      EditLineConstString("lldb-end-or-add-line"),
1175
14
      EditLineConstString("End editing or continue when incomplete"),
1176
14
      [](EditLine *editline, int ch) {
1177
7
        return Editline::InstanceFor(editline)->EndOrAddLineCommand(ch);
1178
7
      });
1179
14
  AddFunctionToEditLine(
1180
14
      EditLineConstString("lldb-delete-next-char"),
1181
14
      EditLineConstString("Delete next character"),
1182
14
      [](EditLine *editline, int ch) {
1183
0
        return Editline::InstanceFor(editline)->DeleteNextCharCommand(ch);
1184
0
      });
1185
14
  AddFunctionToEditLine(
1186
14
      EditLineConstString("lldb-delete-previous-char"),
1187
14
      EditLineConstString("Delete previous character"),
1188
14
      [](EditLine *editline, int ch) {
1189
0
        return Editline::InstanceFor(editline)->DeletePreviousCharCommand(ch);
1190
0
      });
1191
14
  AddFunctionToEditLine(
1192
14
      EditLineConstString("lldb-previous-line"),
1193
14
      EditLineConstString("Move to previous line"),
1194
14
      [](EditLine *editline, int ch) {
1195
0
        return Editline::InstanceFor(editline)->PreviousLineCommand(ch);
1196
0
      });
1197
14
  AddFunctionToEditLine(
1198
14
      EditLineConstString("lldb-next-line"),
1199
14
      EditLineConstString("Move to next line"), [](EditLine *editline, int ch) {
1200
0
        return Editline::InstanceFor(editline)->NextLineCommand(ch);
1201
0
      });
1202
14
  AddFunctionToEditLine(
1203
14
      EditLineConstString("lldb-previous-history"),
1204
14
      EditLineConstString("Move to previous history"),
1205
14
      [](EditLine *editline, int ch) {
1206
0
        return Editline::InstanceFor(editline)->PreviousHistoryCommand(ch);
1207
0
      });
1208
14
  AddFunctionToEditLine(
1209
14
      EditLineConstString("lldb-next-history"),
1210
14
      EditLineConstString("Move to next history"),
1211
14
      [](EditLine *editline, int ch) {
1212
0
        return Editline::InstanceFor(editline)->NextHistoryCommand(ch);
1213
0
      });
1214
14
  AddFunctionToEditLine(
1215
14
      EditLineConstString("lldb-buffer-start"),
1216
14
      EditLineConstString("Move to start of buffer"),
1217
14
      [](EditLine *editline, int ch) {
1218
0
        return Editline::InstanceFor(editline)->BufferStartCommand(ch);
1219
0
      });
1220
14
  AddFunctionToEditLine(
1221
14
      EditLineConstString("lldb-buffer-end"),
1222
14
      EditLineConstString("Move to end of buffer"),
1223
14
      [](EditLine *editline, int ch) {
1224
0
        return Editline::InstanceFor(editline)->BufferEndCommand(ch);
1225
0
      });
1226
14
  AddFunctionToEditLine(
1227
14
      EditLineConstString("lldb-fix-indentation"),
1228
14
      EditLineConstString("Fix line indentation"),
1229
14
      [](EditLine *editline, int ch) {
1230
0
        return Editline::InstanceFor(editline)->FixIndentationCommand(ch);
1231
0
      });
1232
1233
  // Register the complete callback under two names for compatibility with
1234
  // older clients using custom .editrc files (largely because libedit has a
1235
  // bad bug where if you have a bind command that tries to bind to a function
1236
  // name that doesn't exist, it can corrupt the heap and crash your process
1237
  // later.)
1238
14
  EditlineCommandCallbackType complete_callback = [](EditLine *editline,
1239
14
                                                     int ch) {
1240
0
    return Editline::InstanceFor(editline)->TabCommand(ch);
1241
0
  };
1242
14
  AddFunctionToEditLine(EditLineConstString("lldb-complete"),
1243
14
                        EditLineConstString("Invoke completion"),
1244
14
                        complete_callback);
1245
14
  AddFunctionToEditLine(EditLineConstString("lldb_complete"),
1246
14
                        EditLineConstString("Invoke completion"),
1247
14
                        complete_callback);
1248
1249
  // General bindings we don't mind being overridden
1250
14
  if (!multiline) {
1251
12
    el_set(m_editline, EL_BIND, "^r", "em-inc-search-prev",
1252
12
           NULL); // Cycle through backwards search, entering string
1253
1254
12
    if (m_suggestion_callback) {
1255
0
      AddFunctionToEditLine(
1256
0
          EditLineConstString("lldb-apply-complete"),
1257
0
          EditLineConstString("Adopt autocompletion"),
1258
0
          [](EditLine *editline, int ch) {
1259
0
            return Editline::InstanceFor(editline)->ApplyAutosuggestCommand(ch);
1260
0
          });
1261
1262
0
      el_set(m_editline, EL_BIND, "^f", "lldb-apply-complete",
1263
0
             NULL); // Apply a part that is suggested automatically
1264
1265
0
      AddFunctionToEditLine(
1266
0
          EditLineConstString("lldb-typed-character"),
1267
0
          EditLineConstString("Typed character"),
1268
0
          [](EditLine *editline, int ch) {
1269
0
            return Editline::InstanceFor(editline)->TypedCharacter(ch);
1270
0
          });
1271
1272
0
      char bind_key[2] = {0, 0};
1273
0
      llvm::StringRef ascii_chars =
1274
0
          "abcdefghijklmnopqrstuvwxzyABCDEFGHIJKLMNOPQRSTUVWXZY1234567890!\"#$%"
1275
0
          "&'()*+,./:;<=>?@[]_`{|}~ ";
1276
0
      for (char c : ascii_chars) {
1277
0
        bind_key[0] = c;
1278
0
        el_set(m_editline, EL_BIND, bind_key, "lldb-typed-character", NULL);
1279
0
      }
1280
0
      el_set(m_editline, EL_BIND, "\\-", "lldb-typed-character", NULL);
1281
0
      el_set(m_editline, EL_BIND, "\\^", "lldb-typed-character", NULL);
1282
0
      el_set(m_editline, EL_BIND, "\\\\", "lldb-typed-character", NULL);
1283
0
    }
1284
12
  }
1285
1286
14
  el_set(m_editline, EL_BIND, "^w", "ed-delete-prev-word",
1287
14
         NULL); // Delete previous word, behave like bash in emacs mode
1288
14
  el_set(m_editline, EL_BIND, "\t", "lldb-complete",
1289
14
         NULL); // Bind TAB to auto complete
1290
1291
  // Allow ctrl-left-arrow and ctrl-right-arrow for navigation, behave like
1292
  // bash in emacs mode.
1293
14
  el_set(m_editline, EL_BIND, ESCAPE "[1;5C", "em-next-word", NULL);
1294
14
  el_set(m_editline, EL_BIND, ESCAPE "[1;5D", "ed-prev-word", NULL);
1295
14
  el_set(m_editline, EL_BIND, ESCAPE "[5C", "em-next-word", NULL);
1296
14
  el_set(m_editline, EL_BIND, ESCAPE "[5D", "ed-prev-word", NULL);
1297
14
  el_set(m_editline, EL_BIND, ESCAPE ESCAPE "[C", "em-next-word", NULL);
1298
14
  el_set(m_editline, EL_BIND, ESCAPE ESCAPE "[D", "ed-prev-word", NULL);
1299
1300
  // Allow user-specific customization prior to registering bindings we
1301
  // absolutely require
1302
14
  el_source(m_editline, nullptr);
1303
1304
  // Register an internal binding that external developers shouldn't use
1305
14
  AddFunctionToEditLine(
1306
14
      EditLineConstString("lldb-revert-line"),
1307
14
      EditLineConstString("Revert line to saved state"),
1308
14
      [](EditLine *editline, int ch) {
1309
7
        return Editline::InstanceFor(editline)->RevertLineCommand(ch);
1310
7
      });
1311
1312
  // Register keys that perform auto-indent correction
1313
14
  if (m_fix_indentation_callback && 
m_fix_indentation_callback_chars0
) {
1314
0
    char bind_key[2] = {0, 0};
1315
0
    const char *indent_chars = m_fix_indentation_callback_chars;
1316
0
    while (*indent_chars) {
1317
0
      bind_key[0] = *indent_chars;
1318
0
      el_set(m_editline, EL_BIND, bind_key, "lldb-fix-indentation", NULL);
1319
0
      ++indent_chars;
1320
0
    }
1321
0
  }
1322
1323
  // Multi-line editor bindings
1324
14
  if (multiline) {
1325
2
    el_set(m_editline, EL_BIND, "\n", "lldb-end-or-add-line", NULL);
1326
2
    el_set(m_editline, EL_BIND, "\r", "lldb-end-or-add-line", NULL);
1327
2
    el_set(m_editline, EL_BIND, ESCAPE "\n", "lldb-break-line", NULL);
1328
2
    el_set(m_editline, EL_BIND, ESCAPE "\r", "lldb-break-line", NULL);
1329
2
    el_set(m_editline, EL_BIND, "^p", "lldb-previous-line", NULL);
1330
2
    el_set(m_editline, EL_BIND, "^n", "lldb-next-line", NULL);
1331
2
    el_set(m_editline, EL_BIND, "^?", "lldb-delete-previous-char", NULL);
1332
2
    el_set(m_editline, EL_BIND, "^d", "lldb-delete-next-char", NULL);
1333
2
    el_set(m_editline, EL_BIND, ESCAPE "[3~", "lldb-delete-next-char", NULL);
1334
2
    el_set(m_editline, EL_BIND, ESCAPE "[\\^", "lldb-revert-line", NULL);
1335
1336
    // Editor-specific bindings
1337
2
    if (IsEmacs()) {
1338
2
      el_set(m_editline, EL_BIND, ESCAPE "<", "lldb-buffer-start", NULL);
1339
2
      el_set(m_editline, EL_BIND, ESCAPE ">", "lldb-buffer-end", NULL);
1340
2
      el_set(m_editline, EL_BIND, ESCAPE "[A", "lldb-previous-line", NULL);
1341
2
      el_set(m_editline, EL_BIND, ESCAPE "[B", "lldb-next-line", NULL);
1342
2
      el_set(m_editline, EL_BIND, ESCAPE ESCAPE "[A", "lldb-previous-history",
1343
2
             NULL);
1344
2
      el_set(m_editline, EL_BIND, ESCAPE ESCAPE "[B", "lldb-next-history",
1345
2
             NULL);
1346
2
      el_set(m_editline, EL_BIND, ESCAPE "[1;3A", "lldb-previous-history",
1347
2
             NULL);
1348
2
      el_set(m_editline, EL_BIND, ESCAPE "[1;3B", "lldb-next-history", NULL);
1349
2
    } else {
1350
0
      el_set(m_editline, EL_BIND, "^H", "lldb-delete-previous-char", NULL);
1351
1352
0
      el_set(m_editline, EL_BIND, "-a", ESCAPE "[A", "lldb-previous-line",
1353
0
             NULL);
1354
0
      el_set(m_editline, EL_BIND, "-a", ESCAPE "[B", "lldb-next-line", NULL);
1355
0
      el_set(m_editline, EL_BIND, "-a", "x", "lldb-delete-next-char", NULL);
1356
0
      el_set(m_editline, EL_BIND, "-a", "^H", "lldb-delete-previous-char",
1357
0
             NULL);
1358
0
      el_set(m_editline, EL_BIND, "-a", "^?", "lldb-delete-previous-char",
1359
0
             NULL);
1360
1361
      // Escape is absorbed exiting edit mode, so re-register important
1362
      // sequences without the prefix
1363
0
      el_set(m_editline, EL_BIND, "-a", "[A", "lldb-previous-line", NULL);
1364
0
      el_set(m_editline, EL_BIND, "-a", "[B", "lldb-next-line", NULL);
1365
0
      el_set(m_editline, EL_BIND, "-a", "[\\^", "lldb-revert-line", NULL);
1366
0
    }
1367
2
  }
1368
14
}
1369
1370
// Editline public methods
1371
1372
1.86k
Editline *Editline::InstanceFor(EditLine *editline) {
1373
1.86k
  Editline *editor;
1374
1.86k
  el_get(editline, EL_CLIENTDATA, &editor);
1375
1.86k
  return editor;
1376
1.86k
}
1377
1378
Editline::Editline(const char *editline_name, FILE *input_file,
1379
                   FILE *output_file, FILE *error_file,
1380
                   std::recursive_mutex &output_mutex)
1381
14
    : m_editor_status(EditorStatus::Complete), m_input_file(input_file),
1382
14
      m_output_file(output_file), m_error_file(error_file),
1383
14
      m_input_connection(fileno(input_file), false),
1384
14
      m_output_mutex(output_mutex) {
1385
  // Get a shared history instance
1386
14
  m_editor_name = (editline_name == nullptr) ? 
"lldb-tmp"0
: editline_name;
1387
14
  m_history_sp = EditlineHistory::GetHistory(m_editor_name);
1388
1389
14
#ifdef USE_SETUPTERM_WORKAROUND
1390
14
  if (m_output_file) {
1391
14
    const int term_fd = fileno(m_output_file);
1392
14
    if (term_fd != -1) {
1393
14
      static std::recursive_mutex *g_init_terminal_fds_mutex_ptr = nullptr;
1394
14
      static std::set<int> *g_init_terminal_fds_ptr = nullptr;
1395
14
      static llvm::once_flag g_once_flag;
1396
14
      llvm::call_once(g_once_flag, [&]() {
1397
13
        g_init_terminal_fds_mutex_ptr =
1398
13
            new std::recursive_mutex(); // NOTE: Leak to avoid C++ destructor
1399
                                        // chain issues
1400
13
        g_init_terminal_fds_ptr = new std::set<int>(); // NOTE: Leak to avoid
1401
                                                       // C++ destructor chain
1402
                                                       // issues
1403
13
      });
1404
1405
      // We must make sure to initialize the terminal a given file descriptor
1406
      // only once. If we do this multiple times, we start leaking memory.
1407
14
      std::lock_guard<std::recursive_mutex> guard(
1408
14
          *g_init_terminal_fds_mutex_ptr);
1409
14
      if (g_init_terminal_fds_ptr->find(term_fd) ==
1410
14
          g_init_terminal_fds_ptr->end()) {
1411
13
        g_init_terminal_fds_ptr->insert(term_fd);
1412
13
        setupterm((char *)0, term_fd, (int *)0);
1413
13
      }
1414
14
    }
1415
14
  }
1416
14
#endif
1417
14
}
1418
1419
14
Editline::~Editline() {
1420
14
  if (m_editline) {
1421
    // Disable edit mode to stop the terminal from flushing all input during
1422
    // the call to el_end() since we expect to have multiple editline instances
1423
    // in this program.
1424
14
    el_set(m_editline, EL_EDITMODE, 0);
1425
14
    el_end(m_editline);
1426
14
    m_editline = nullptr;
1427
14
  }
1428
1429
  // EditlineHistory objects are sometimes shared between multiple Editline
1430
  // instances with the same program name. So just release our shared pointer
1431
  // and if we are the last owner, it will save the history to the history save
1432
  // file automatically.
1433
14
  m_history_sp.reset();
1434
14
}
1435
1436
17
void Editline::SetPrompt(const char *prompt) {
1437
17
  m_set_prompt = prompt == nullptr ? 
""0
: prompt;
1438
17
}
1439
1440
12
void Editline::SetContinuationPrompt(const char *continuation_prompt) {
1441
12
  m_set_continuation_prompt =
1442
12
      continuation_prompt == nullptr ? "" : 
continuation_prompt0
;
1443
12
}
1444
1445
0
void Editline::TerminalSizeChanged() { m_terminal_size_has_changed = 1; }
1446
1447
14
void Editline::ApplyTerminalSizeChange() {
1448
14
  if (!m_editline)
1449
0
    return;
1450
1451
14
  m_terminal_size_has_changed = 0;
1452
14
  el_resize(m_editline);
1453
14
  int columns;
1454
  // This function is documenting as taking (const char *, void *) for the
1455
  // vararg part, but in reality in was consuming arguments until the first
1456
  // null pointer. This was fixed in libedit in April 2019
1457
  // <http://mail-index.netbsd.org/source-changes/2019/04/26/msg105454.html>,
1458
  // but we're keeping the workaround until a version with that fix is more
1459
  // widely available.
1460
14
  if (el_get(m_editline, EL_GETTC, "co", &columns, nullptr) == 0) {
1461
14
    m_terminal_width = columns;
1462
14
    if (m_current_line_rows != -1) {
1463
0
      const LineInfoW *info = el_wline(m_editline);
1464
0
      int lineLength =
1465
0
          (int)((info->lastchar - info->buffer) + GetPromptWidth());
1466
0
      m_current_line_rows = (lineLength / columns) + 1;
1467
0
    }
1468
14
  } else {
1469
0
    m_terminal_width = INT_MAX;
1470
0
    m_current_line_rows = 1;
1471
0
  }
1472
14
}
1473
1474
0
const char *Editline::GetPrompt() { return m_set_prompt.c_str(); }
1475
1476
0
uint32_t Editline::GetCurrentLine() { return m_current_line_index; }
1477
1478
0
bool Editline::Interrupt() {
1479
0
  bool result = true;
1480
0
  std::lock_guard<std::recursive_mutex> guard(m_output_mutex);
1481
0
  if (m_editor_status == EditorStatus::Editing) {
1482
0
    fprintf(m_output_file, "^C\n");
1483
0
    result = m_input_connection.InterruptRead();
1484
0
  }
1485
0
  m_editor_status = EditorStatus::Interrupted;
1486
0
  return result;
1487
0
}
1488
1489
18
bool Editline::Cancel() {
1490
18
  bool result = true;
1491
18
  std::lock_guard<std::recursive_mutex> guard(m_output_mutex);
1492
18
  if (m_editor_status == EditorStatus::Editing) {
1493
0
    MoveCursor(CursorLocation::EditingCursor, CursorLocation::BlockStart);
1494
0
    fprintf(m_output_file, ANSI_CLEAR_BELOW);
1495
0
    result = m_input_connection.InterruptRead();
1496
0
  }
1497
18
  m_editor_status = EditorStatus::Interrupted;
1498
18
  return result;
1499
18
}
1500
1501
56
bool Editline::GetLine(std::string &line, bool &interrupted) {
1502
56
  ConfigureEditor(false);
1503
56
  m_input_lines = std::vector<EditLineStringType>();
1504
56
  m_input_lines.insert(m_input_lines.begin(), EditLineConstString(""));
1505
1506
56
  std::lock_guard<std::recursive_mutex> guard(m_output_mutex);
1507
1508
56
  lldbassert(m_editor_status != EditorStatus::Editing);
1509
56
  if (m_editor_status == EditorStatus::Interrupted) {
1510
6
    m_editor_status = EditorStatus::Complete;
1511
6
    interrupted = true;
1512
6
    return true;
1513
6
  }
1514
1515
50
  SetCurrentLine(0);
1516
50
  m_in_history = false;
1517
50
  m_editor_status = EditorStatus::Editing;
1518
50
  m_revert_cursor_index = -1;
1519
1520
50
  int count;
1521
50
  auto input = el_wgets(m_editline, &count);
1522
1523
50
  interrupted = m_editor_status == EditorStatus::Interrupted;
1524
50
  if (!interrupted) {
1525
50
    if (input == nullptr) {
1526
0
      fprintf(m_output_file, "\n");
1527
0
      m_editor_status = EditorStatus::EndOfInput;
1528
50
    } else {
1529
50
      m_history_sp->Enter(input);
1530
50
#if LLDB_EDITLINE_USE_WCHAR
1531
50
      line = m_utf8conv.to_bytes(SplitLines(input)[0]);
1532
#else
1533
      line = SplitLines(input)[0];
1534
#endif
1535
50
      m_editor_status = EditorStatus::Complete;
1536
50
    }
1537
50
  }
1538
50
  return m_editor_status != EditorStatus::EndOfInput;
1539
56
}
1540
1541
bool Editline::GetLines(int first_line_number, StringList &lines,
1542
2
                        bool &interrupted) {
1543
2
  ConfigureEditor(true);
1544
1545
  // Print the initial input lines, then move the cursor back up to the start
1546
  // of input
1547
2
  SetBaseLineNumber(first_line_number);
1548
2
  m_input_lines = std::vector<EditLineStringType>();
1549
2
  m_input_lines.insert(m_input_lines.begin(), EditLineConstString(""));
1550
1551
2
  std::lock_guard<std::recursive_mutex> guard(m_output_mutex);
1552
  // Begin the line editing loop
1553
2
  DisplayInput();
1554
2
  SetCurrentLine(0);
1555
2
  MoveCursor(CursorLocation::BlockEnd, CursorLocation::BlockStart);
1556
2
  m_editor_status = EditorStatus::Editing;
1557
2
  m_in_history = false;
1558
1559
2
  m_revert_cursor_index = -1;
1560
9
  while (m_editor_status == EditorStatus::Editing) {
1561
7
    int count;
1562
7
    m_current_line_rows = -1;
1563
7
    el_wpush(m_editline, EditLineConstString(
1564
7
                             "\x1b[^")); // Revert to the existing line content
1565
7
    el_wgets(m_editline, &count);
1566
7
  }
1567
1568
2
  interrupted = m_editor_status == EditorStatus::Interrupted;
1569
2
  if (!interrupted) {
1570
    // Save the completed entry in history before returning. Don't save empty
1571
    // input as that just clutters the command history.
1572
2
    if (!m_input_lines.empty())
1573
2
      m_history_sp->Enter(CombineLines(m_input_lines).c_str());
1574
1575
2
    lines = GetInputAsStringList();
1576
2
  }
1577
2
  return m_editor_status != EditorStatus::EndOfInput;
1578
2
}
1579
1580
341
void Editline::PrintAsync(Stream *stream, const char *s, size_t len) {
1581
341
  std::lock_guard<std::recursive_mutex> guard(m_output_mutex);
1582
341
  if (m_editor_status == EditorStatus::Editing) {
1583
1
    MoveCursor(CursorLocation::EditingCursor, CursorLocation::BlockStart);
1584
1
    fprintf(m_output_file, ANSI_CLEAR_BELOW);
1585
1
  }
1586
341
  stream->Write(s, len);
1587
341
  stream->Flush();
1588
341
  if (m_editor_status == EditorStatus::Editing) {
1589
1
    DisplayInput();
1590
1
    MoveCursor(CursorLocation::BlockEnd, CursorLocation::EditingCursor);
1591
1
  }
1592
341
}
1593
1594
1.78k
bool Editline::CompleteCharacter(char ch, EditLineGetCharType &out) {
1595
#if !LLDB_EDITLINE_USE_WCHAR
1596
  if (ch == (char)EOF)
1597
    return false;
1598
1599
  out = (unsigned char)ch;
1600
  return true;
1601
#else
1602
1.78k
  std::codecvt_utf8<wchar_t> cvt;
1603
1.78k
  llvm::SmallString<4> input;
1604
1.79k
  for (;;) {
1605
1.79k
    const char *from_next;
1606
1.79k
    wchar_t *to_next;
1607
1.79k
    std::mbstate_t state = std::mbstate_t();
1608
1.79k
    input.push_back(ch);
1609
1.79k
    switch (cvt.in(state, input.begin(), input.end(), from_next, &out, &out + 1,
1610
1.79k
                   to_next)) {
1611
1.78k
    case std::codecvt_base::ok:
1612
1.78k
      return out != (EditLineGetCharType)WEOF;
1613
1614
0
    case std::codecvt_base::error:
1615
0
    case std::codecvt_base::noconv:
1616
0
      return false;
1617
1618
3
    case std::codecvt_base::partial:
1619
3
      lldb::ConnectionStatus status;
1620
3
      size_t read_count = m_input_connection.Read(
1621
3
          &ch, 1, std::chrono::seconds(0), status, nullptr);
1622
3
      if (read_count == 0)
1623
0
        return false;
1624
3
      break;
1625
1.79k
    }
1626
1.79k
  }
1627
1.78k
#endif
1628
1.78k
}