Coverage Report

Created: 2023-11-11 10:31

/Users/buildslave/jenkins/workspace/coverage/llvm-project/lldb/source/Commands/CommandObjectExpression.cpp
Line
Count
Source (jump to first uncovered line)
1
//===-- CommandObjectExpression.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 "llvm/ADT/StringRef.h"
10
11
#include "CommandObjectExpression.h"
12
#include "lldb/Core/Debugger.h"
13
#include "lldb/Expression/ExpressionVariable.h"
14
#include "lldb/Expression/REPL.h"
15
#include "lldb/Expression/UserExpression.h"
16
#include "lldb/Host/OptionParser.h"
17
#include "lldb/Interpreter/CommandInterpreter.h"
18
#include "lldb/Interpreter/CommandOptionArgumentTable.h"
19
#include "lldb/Interpreter/CommandReturnObject.h"
20
#include "lldb/Interpreter/OptionArgParser.h"
21
#include "lldb/Target/Language.h"
22
#include "lldb/Target/Process.h"
23
#include "lldb/Target/StackFrame.h"
24
#include "lldb/Target/Target.h"
25
#include "lldb/lldb-enumerations.h"
26
#include "lldb/lldb-private-enumerations.h"
27
28
using namespace lldb;
29
using namespace lldb_private;
30
31
12.2k
CommandObjectExpression::CommandOptions::CommandOptions() = default;
32
33
12.2k
CommandObjectExpression::CommandOptions::~CommandOptions() = default;
34
35
#define LLDB_OPTIONS_expression
36
#include "CommandOptions.inc"
37
38
Status CommandObjectExpression::CommandOptions::SetOptionValue(
39
    uint32_t option_idx, llvm::StringRef option_arg,
40
155
    ExecutionContext *execution_context) {
41
155
  Status error;
42
43
155
  const int short_option = GetDefinitions()[option_idx].short_option;
44
45
155
  switch (short_option) {
46
40
  case 'l':
47
40
    language = Language::GetLanguageTypeFromString(option_arg);
48
40
    if (language == eLanguageTypeUnknown) {
49
1
      StreamString sstr;
50
1
      sstr.Printf("unknown language type: '%s' for expression. "
51
1
                  "List of supported languages:\n",
52
1
                  option_arg.str().c_str());
53
54
1
      Language::PrintSupportedLanguagesForExpressions(sstr, "  ", "\n");
55
1
      error.SetErrorString(sstr.GetString());
56
1
    }
57
40
    break;
58
59
1
  case 'a': {
60
1
    bool success;
61
1
    bool result;
62
1
    result = OptionArgParser::ToBoolean(option_arg, true, &success);
63
1
    if (!success)
64
1
      error.SetErrorStringWithFormat(
65
1
          "invalid all-threads value setting: \"%s\"",
66
1
          option_arg.str().c_str());
67
0
    else
68
0
      try_all_threads = result;
69
1
  } break;
70
71
5
  case 'i': {
72
5
    bool success;
73
5
    bool tmp_value = OptionArgParser::ToBoolean(option_arg, true, &success);
74
5
    if (success)
75
4
      ignore_breakpoints = tmp_value;
76
1
    else
77
1
      error.SetErrorStringWithFormat(
78
1
          "could not convert \"%s\" to a boolean value.",
79
1
          option_arg.str().c_str());
80
5
    break;
81
0
  }
82
83
59
  case 'j': {
84
59
    bool success;
85
59
    bool tmp_value = OptionArgParser::ToBoolean(option_arg, true, &success);
86
59
    if (success)
87
58
      allow_jit = tmp_value;
88
1
    else
89
1
      error.SetErrorStringWithFormat(
90
1
          "could not convert \"%s\" to a boolean value.",
91
1
          option_arg.str().c_str());
92
59
    break;
93
0
  }
94
95
6
  case 't':
96
6
    if (option_arg.getAsInteger(0, timeout)) {
97
2
      timeout = 0;
98
2
      error.SetErrorStringWithFormat("invalid timeout setting \"%s\"",
99
2
                                     option_arg.str().c_str());
100
2
    }
101
6
    break;
102
103
5
  case 'u': {
104
5
    bool success;
105
5
    bool tmp_value = OptionArgParser::ToBoolean(option_arg, true, &success);
106
5
    if (success)
107
4
      unwind_on_error = tmp_value;
108
1
    else
109
1
      error.SetErrorStringWithFormat(
110
1
          "could not convert \"%s\" to a boolean value.",
111
1
          option_arg.str().c_str());
112
5
    break;
113
0
  }
114
115
14
  case 'v':
116
14
    if (option_arg.empty()) {
117
4
      m_verbosity = eLanguageRuntimeDescriptionDisplayVerbosityFull;
118
4
      break;
119
4
    }
120
10
    m_verbosity = (LanguageRuntimeDescriptionDisplayVerbosity)
121
10
        OptionArgParser::ToOptionEnum(
122
10
            option_arg, GetDefinitions()[option_idx].enum_values, 0, error);
123
10
    if (!error.Success())
124
0
      error.SetErrorStringWithFormat(
125
0
          "unrecognized value for description-verbosity '%s'",
126
0
          option_arg.str().c_str());
127
10
    break;
128
129
0
  case 'g':
130
0
    debug = true;
131
0
    unwind_on_error = false;
132
0
    ignore_breakpoints = false;
133
0
    break;
134
135
20
  case 'p':
136
20
    top_level = true;
137
20
    break;
138
139
1
  case 'X': {
140
1
    bool success;
141
1
    bool tmp_value = OptionArgParser::ToBoolean(option_arg, true, &success);
142
1
    if (success)
143
0
      auto_apply_fixits = tmp_value ? eLazyBoolYes : eLazyBoolNo;
144
1
    else
145
1
      error.SetErrorStringWithFormat(
146
1
          "could not convert \"%s\" to a boolean value.",
147
1
          option_arg.str().c_str());
148
1
    break;
149
14
  }
150
151
4
  case '\x01': {
152
4
    bool success;
153
4
    bool persist_result =
154
4
        OptionArgParser::ToBoolean(option_arg, true, &success);
155
4
    if (success)
156
4
      suppress_persistent_result = !persist_result ? 
eLazyBoolYes2
:
eLazyBoolNo2
;
157
0
    else
158
0
      error.SetErrorStringWithFormat(
159
0
          "could not convert \"%s\" to a boolean value.",
160
0
          option_arg.str().c_str());
161
4
    break;
162
14
  }
163
164
0
  default:
165
0
    llvm_unreachable("Unimplemented option");
166
155
  }
167
168
155
  return error;
169
155
}
170
171
void CommandObjectExpression::CommandOptions::OptionParsingStarting(
172
41.2k
    ExecutionContext *execution_context) {
173
41.2k
  auto process_sp =
174
41.2k
      execution_context ? execution_context->GetProcessSP() : 
ProcessSP()0
;
175
41.2k
  if (process_sp) {
176
4.26k
    ignore_breakpoints = process_sp->GetIgnoreBreakpointsInExpressions();
177
4.26k
    unwind_on_error = process_sp->GetUnwindOnErrorInExpressions();
178
36.9k
  } else {
179
36.9k
    ignore_breakpoints = true;
180
36.9k
    unwind_on_error = true;
181
36.9k
  }
182
183
41.2k
  show_summary = true;
184
41.2k
  try_all_threads = true;
185
41.2k
  timeout = 0;
186
41.2k
  debug = false;
187
41.2k
  language = eLanguageTypeUnknown;
188
41.2k
  m_verbosity = eLanguageRuntimeDescriptionDisplayVerbosityCompact;
189
41.2k
  auto_apply_fixits = eLazyBoolCalculate;
190
41.2k
  top_level = false;
191
41.2k
  allow_jit = true;
192
41.2k
  suppress_persistent_result = eLazyBoolCalculate;
193
41.2k
}
194
195
llvm::ArrayRef<OptionDefinition>
196
12.4k
CommandObjectExpression::CommandOptions::GetDefinitions() {
197
12.4k
  return llvm::ArrayRef(g_expression_options);
198
12.4k
}
199
200
EvaluateExpressionOptions
201
CommandObjectExpression::CommandOptions::GetEvaluateExpressionOptions(
202
3.83k
    const Target &target, const OptionGroupValueObjectDisplay &display_opts) {
203
3.83k
  EvaluateExpressionOptions options;
204
3.83k
  options.SetCoerceToId(display_opts.use_objc);
205
3.83k
  options.SetUnwindOnError(unwind_on_error);
206
3.83k
  options.SetIgnoreBreakpoints(ignore_breakpoints);
207
3.83k
  options.SetKeepInMemory(true);
208
3.83k
  options.SetUseDynamic(display_opts.use_dynamic);
209
3.83k
  options.SetTryAllThreads(try_all_threads);
210
3.83k
  options.SetDebug(debug);
211
3.83k
  options.SetLanguage(language);
212
3.83k
  options.SetExecutionPolicy(
213
3.83k
      allow_jit ? 
EvaluateExpressionOptions::default_execution_policy3.78k
214
3.83k
                : 
lldb_private::eExecutionPolicyNever55
);
215
216
3.83k
  bool auto_apply_fixits;
217
3.83k
  if (this->auto_apply_fixits == eLazyBoolCalculate)
218
3.83k
    auto_apply_fixits = target.GetEnableAutoApplyFixIts();
219
0
  else
220
0
    auto_apply_fixits = this->auto_apply_fixits == eLazyBoolYes;
221
222
3.83k
  options.SetAutoApplyFixIts(auto_apply_fixits);
223
3.83k
  options.SetRetriesWithFixIts(target.GetNumberOfRetriesWithFixits());
224
225
3.83k
  if (top_level)
226
19
    options.SetExecutionPolicy(eExecutionPolicyTopLevel);
227
228
  // If there is any chance we are going to stop and want to see what went
229
  // wrong with our expression, we should generate debug info
230
3.83k
  if (!ignore_breakpoints || 
!unwind_on_error3.83k
)
231
2
    options.SetGenerateDebugInfo(true);
232
233
3.83k
  if (timeout > 0)
234
4
    options.SetTimeout(std::chrono::microseconds(timeout));
235
3.83k
  else
236
3.83k
    options.SetTimeout(std::nullopt);
237
3.83k
  return options;
238
3.83k
}
239
240
bool CommandObjectExpression::CommandOptions::ShouldSuppressResult(
241
3.51k
    const OptionGroupValueObjectDisplay &display_opts) const {
242
  // Explicitly disabling persistent results takes precedence over the
243
  // m_verbosity/use_objc logic.
244
3.51k
  if (suppress_persistent_result != eLazyBoolCalculate)
245
80
    return suppress_persistent_result == eLazyBoolYes;
246
247
3.43k
  return display_opts.use_objc &&
248
3.43k
         
m_verbosity == eLanguageRuntimeDescriptionDisplayVerbosityCompact70
;
249
3.51k
}
250
251
CommandObjectExpression::CommandObjectExpression(
252
    CommandInterpreter &interpreter)
253
6.14k
    : CommandObjectRaw(interpreter, "expression",
254
6.14k
                       "Evaluate an expression on the current "
255
6.14k
                       "thread.  Displays any returned value "
256
6.14k
                       "with LLDB's default formatting.",
257
6.14k
                       "",
258
6.14k
                       eCommandProcessMustBePaused | eCommandTryTargetAPILock),
259
6.14k
      IOHandlerDelegate(IOHandlerDelegate::Completion::Expression),
260
6.14k
      m_format_options(eFormatDefault),
261
6.14k
      m_repl_option(LLDB_OPT_SET_1, false, "repl", 'r', "Drop into REPL", false,
262
6.14k
                    true),
263
6.14k
      m_expr_line_count(0) {
264
6.14k
  SetHelpLong(
265
6.14k
      R"(
266
6.14k
Single and multi-line expressions:
267
6.14k
268
6.14k
)"
269
6.14k
      "    The expression provided on the command line must be a complete expression \
270
6.14k
with no newlines.  To evaluate a multi-line expression, \
271
6.14k
hit a return after an empty expression, and lldb will enter the multi-line expression editor. \
272
6.14k
Hit return on an empty line to end the multi-line expression."
273
274
6.14k
      R"(
275
6.14k
276
6.14k
Timeouts:
277
6.14k
278
6.14k
)"
279
6.14k
      "    If the expression can be evaluated statically (without running code) then it will be.  \
280
6.14k
Otherwise, by default the expression will run on the current thread with a short timeout: \
281
6.14k
currently .25 seconds.  If it doesn't return in that time, the evaluation will be interrupted \
282
6.14k
and resumed with all threads running.  You can use the -a option to disable retrying on all \
283
6.14k
threads.  You can use the -t option to set a shorter timeout."
284
6.14k
      R"(
285
6.14k
286
6.14k
User defined variables:
287
6.14k
288
6.14k
)"
289
6.14k
      "    You can define your own variables for convenience or to be used in subsequent expressions.  \
290
6.14k
You define them the same way you would define variables in C.  If the first character of \
291
6.14k
your user defined variable is a $, then the variable's value will be available in future \
292
6.14k
expressions, otherwise it will just be available in the current expression."
293
6.14k
      R"(
294
6.14k
295
6.14k
Continuing evaluation after a breakpoint:
296
6.14k
297
6.14k
)"
298
6.14k
      "    If the \"-i false\" option is used, and execution is interrupted by a breakpoint hit, once \
299
6.14k
you are done with your investigation, you can either remove the expression execution frames \
300
6.14k
from the stack with \"thread return -x\" or if you are still interested in the expression result \
301
6.14k
you can issue the \"continue\" command and the expression evaluation will complete and the \
302
6.14k
expression result will be available using the \"thread.completed-expression\" key in the thread \
303
6.14k
format."
304
305
6.14k
      R"(
306
6.14k
307
6.14k
Examples:
308
6.14k
309
6.14k
    expr my_struct->a = my_array[3]
310
6.14k
    expr -f bin -- (index * 8) + 5
311
6.14k
    expr unsigned int $foo = 5
312
6.14k
    expr char c[] = \"foo\"; c[0])");
313
314
6.14k
  CommandArgumentEntry arg;
315
6.14k
  CommandArgumentData expression_arg;
316
317
  // Define the first (and only) variant of this arg.
318
6.14k
  expression_arg.arg_type = eArgTypeExpression;
319
6.14k
  expression_arg.arg_repetition = eArgRepeatPlain;
320
321
  // There is only one variant this argument could be; put it into the argument
322
  // entry.
323
6.14k
  arg.push_back(expression_arg);
324
325
  // Push the data for the first argument into the m_arguments vector.
326
6.14k
  m_arguments.push_back(arg);
327
328
  // Add the "--format" and "--gdb-format"
329
6.14k
  m_option_group.Append(&m_format_options,
330
6.14k
                        OptionGroupFormat::OPTION_GROUP_FORMAT |
331
6.14k
                            OptionGroupFormat::OPTION_GROUP_GDB_FMT,
332
6.14k
                        LLDB_OPT_SET_1);
333
6.14k
  m_option_group.Append(&m_command_options);
334
6.14k
  m_option_group.Append(&m_varobj_options, LLDB_OPT_SET_ALL,
335
6.14k
                        LLDB_OPT_SET_1 | LLDB_OPT_SET_2);
336
6.14k
  m_option_group.Append(&m_repl_option, LLDB_OPT_SET_ALL, LLDB_OPT_SET_3);
337
6.14k
  m_option_group.Finalize();
338
6.14k
}
339
340
6.13k
CommandObjectExpression::~CommandObjectExpression() = default;
341
342
18.9k
Options *CommandObjectExpression::GetOptions() { return &m_option_group; }
343
344
58
void CommandObjectExpression::HandleCompletion(CompletionRequest &request) {
345
58
  EvaluateExpressionOptions options;
346
58
  options.SetCoerceToId(m_varobj_options.use_objc);
347
58
  options.SetLanguage(m_command_options.language);
348
58
  options.SetExecutionPolicy(lldb_private::eExecutionPolicyNever);
349
58
  options.SetAutoApplyFixIts(false);
350
58
  options.SetGenerateDebugInfo(false);
351
352
58
  ExecutionContext exe_ctx(m_interpreter.GetExecutionContext());
353
354
  // Get out before we start doing things that expect a valid frame pointer.
355
58
  if (exe_ctx.GetFramePtr() == nullptr)
356
3
    return;
357
358
55
  Target *exe_target = exe_ctx.GetTargetPtr();
359
55
  Target &target = exe_target ? *exe_target : 
GetDummyTarget()0
;
360
361
55
  unsigned cursor_pos = request.GetRawCursorPos();
362
  // Get the full user input including the suffix. The suffix is necessary
363
  // as OptionsWithRaw will use it to detect if the cursor is cursor is in the
364
  // argument part of in the raw input part of the arguments. If we cut of
365
  // of the suffix then "expr -arg[cursor] --" would interpret the "-arg" as
366
  // the raw input (as the "--" is hidden in the suffix).
367
55
  llvm::StringRef code = request.GetRawLineWithUnusedSuffix();
368
369
55
  const std::size_t original_code_size = code.size();
370
371
  // Remove the first token which is 'expr' or some alias/abbreviation of that.
372
55
  code = llvm::getToken(code).second.ltrim();
373
55
  OptionsWithRaw args(code);
374
55
  code = args.GetRawPart();
375
376
  // The position where the expression starts in the command line.
377
55
  assert(original_code_size >= code.size());
378
55
  std::size_t raw_start = original_code_size - code.size();
379
380
  // Check if the cursor is actually in the expression string, and if not, we
381
  // exit.
382
  // FIXME: We should complete the options here.
383
55
  if (cursor_pos < raw_start)
384
2
    return;
385
386
  // Make the cursor_pos again relative to the start of the code string.
387
53
  assert(cursor_pos >= raw_start);
388
53
  cursor_pos -= raw_start;
389
390
53
  auto language = exe_ctx.GetFrameRef().GetLanguage();
391
392
53
  Status error;
393
53
  lldb::UserExpressionSP expr(target.GetUserExpressionForLanguage(
394
53
      code, llvm::StringRef(), language, UserExpression::eResultTypeAny,
395
53
      options, nullptr, error));
396
53
  if (error.Fail())
397
0
    return;
398
399
53
  expr->Complete(exe_ctx, request, cursor_pos);
400
53
}
401
402
static lldb_private::Status
403
47
CanBeUsedForElementCountPrinting(ValueObject &valobj) {
404
47
  CompilerType type(valobj.GetCompilerType());
405
47
  CompilerType pointee;
406
47
  if (!type.IsPointerType(&pointee))
407
3
    return Status("as it does not refer to a pointer");
408
44
  if (pointee.IsVoidType())
409
2
    return Status("as it refers to a pointer to void");
410
42
  return Status();
411
44
}
412
413
bool CommandObjectExpression::EvaluateExpression(llvm::StringRef expr,
414
                                                 Stream &output_stream,
415
                                                 Stream &error_stream,
416
3.76k
                                                 CommandReturnObject &result) {
417
  // Don't use m_exe_ctx as this might be called asynchronously after the
418
  // command object DoExecute has finished when doing multi-line expression
419
  // that use an input reader...
420
3.76k
  ExecutionContext exe_ctx(m_interpreter.GetExecutionContext());
421
3.76k
  Target *exe_target = exe_ctx.GetTargetPtr();
422
3.76k
  Target &target = exe_target ? 
*exe_target3.69k
:
GetDummyTarget()64
;
423
424
3.76k
  lldb::ValueObjectSP result_valobj_sp;
425
3.76k
  StackFrame *frame = exe_ctx.GetFramePtr();
426
427
3.76k
  if (m_command_options.top_level && 
!m_command_options.allow_jit20
) {
428
1
    result.AppendErrorWithFormat(
429
1
        "Can't disable JIT compilation for top-level expressions.\n");
430
1
    return false;
431
1
  }
432
433
3.75k
  EvaluateExpressionOptions eval_options =
434
3.75k
      m_command_options.GetEvaluateExpressionOptions(target, m_varobj_options);
435
  // This command manually removes the result variable, make sure expression
436
  // evaluation doesn't do it first.
437
3.75k
  eval_options.SetSuppressPersistentResult(false);
438
439
3.75k
  ExpressionResults success = target.EvaluateExpression(
440
3.75k
      expr, frame, result_valobj_sp, eval_options, &m_fixed_expression);
441
442
  // Only mention Fix-Its if the expression evaluator applied them.
443
  // Compiler errors refer to the final expression after applying Fix-It(s).
444
3.75k
  if (!m_fixed_expression.empty() && 
target.GetEnableNotifyAboutFixIts()6
) {
445
6
    error_stream << "  Evaluated this expression after applying Fix-It(s):\n";
446
6
    error_stream << "    " << m_fixed_expression << "\n";
447
6
  }
448
449
3.75k
  if (result_valobj_sp) {
450
3.75k
    Format format = m_format_options.GetFormat();
451
452
3.75k
    if (result_valobj_sp->GetError().Success()) {
453
3.44k
      if (format != eFormatVoid) {
454
3.44k
        if (format != eFormatDefault)
455
100
          result_valobj_sp->SetFormat(format);
456
457
3.44k
        if (m_varobj_options.elem_count > 0) {
458
47
          Status error(CanBeUsedForElementCountPrinting(*result_valobj_sp));
459
47
          if (error.Fail()) {
460
5
            result.AppendErrorWithFormat(
461
5
                "expression cannot be used with --element-count %s\n",
462
5
                error.AsCString(""));
463
5
            return false;
464
5
          }
465
47
        }
466
467
3.43k
        bool suppress_result =
468
3.43k
            m_command_options.ShouldSuppressResult(m_varobj_options);
469
470
3.43k
        DumpValueObjectOptions options(m_varobj_options.GetAsDumpOptions(
471
3.43k
            m_command_options.m_verbosity, format));
472
3.43k
        options.SetHideRootName(suppress_result);
473
3.43k
        options.SetVariableFormatDisplayLanguage(
474
3.43k
            result_valobj_sp->GetPreferredDisplayLanguage());
475
476
3.43k
        result_valobj_sp->Dump(output_stream, options);
477
478
3.43k
        if (suppress_result)
479
58
          if (auto result_var_sp =
480
58
                  target.GetPersistentVariable(result_valobj_sp->GetName())) {
481
58
            auto language = result_valobj_sp->GetPreferredDisplayLanguage();
482
58
            if (auto *persistent_state =
483
58
                    target.GetPersistentExpressionStateForLanguage(language))
484
58
              persistent_state->RemovePersistentVariable(result_var_sp);
485
58
          }
486
3.43k
        result.SetStatus(eReturnStatusSuccessFinishResult);
487
3.43k
      }
488
3.44k
    } else {
489
315
      if (result_valobj_sp->GetError().GetError() ==
490
315
          UserExpression::kNoResult) {
491
72
        if (format != eFormatVoid && GetDebugger().GetNotifyVoid()) {
492
0
          error_stream.PutCString("(void)\n");
493
0
        }
494
495
72
        result.SetStatus(eReturnStatusSuccessFinishResult);
496
243
      } else {
497
243
        const char *error_cstr = result_valobj_sp->GetError().AsCString();
498
243
        if (error_cstr && error_cstr[0]) {
499
243
          const size_t error_cstr_len = strlen(error_cstr);
500
243
          const bool ends_with_newline = error_cstr[error_cstr_len - 1] == '\n';
501
243
          if (strstr(error_cstr, "error:") != error_cstr)
502
7
            error_stream.PutCString("error: ");
503
243
          error_stream.Write(error_cstr, error_cstr_len);
504
243
          if (!ends_with_newline)
505
3
            error_stream.EOL();
506
243
        } else {
507
0
          error_stream.PutCString("error: unknown error\n");
508
0
        }
509
510
243
        result.SetStatus(eReturnStatusFailed);
511
243
      }
512
315
    }
513
3.75k
  } else {
514
0
    error_stream.Printf("error: unknown error\n");
515
0
  }
516
517
3.75k
  return (success != eExpressionSetupError &&
518
3.75k
          
success != eExpressionParseError3.74k
);
519
3.75k
}
520
521
void CommandObjectExpression::IOHandlerInputComplete(IOHandler &io_handler,
522
1
                                                     std::string &line) {
523
1
  io_handler.SetIsDone(true);
524
1
  StreamFileSP output_sp = io_handler.GetOutputStreamFileSP();
525
1
  StreamFileSP error_sp = io_handler.GetErrorStreamFileSP();
526
527
1
  CommandReturnObject return_obj(
528
1
      GetCommandInterpreter().GetDebugger().GetUseColor());
529
1
  EvaluateExpression(line.c_str(), *output_sp, *error_sp, return_obj);
530
1
  if (output_sp)
531
1
    output_sp->Flush();
532
1
  if (error_sp)
533
1
    error_sp->Flush();
534
1
}
535
536
bool CommandObjectExpression::IOHandlerIsInputComplete(IOHandler &io_handler,
537
3
                                                       StringList &lines) {
538
  // An empty lines is used to indicate the end of input
539
3
  const size_t num_lines = lines.GetSize();
540
3
  if (num_lines > 0 && lines[num_lines - 1].empty()) {
541
    // Remove the last empty line from "lines" so it doesn't appear in our
542
    // resulting input and return true to indicate we are done getting lines
543
1
    lines.PopBack();
544
1
    return true;
545
1
  }
546
2
  return false;
547
3
}
548
549
1
void CommandObjectExpression::GetMultilineExpression() {
550
1
  m_expr_lines.clear();
551
1
  m_expr_line_count = 0;
552
553
1
  Debugger &debugger = GetCommandInterpreter().GetDebugger();
554
1
  bool color_prompt = debugger.GetUseColor();
555
1
  const bool multiple_lines = true; // Get multiple lines
556
1
  IOHandlerSP io_handler_sp(
557
1
      new IOHandlerEditline(debugger, IOHandler::Type::Expression,
558
1
                            "lldb-expr", // Name of input reader for history
559
1
                            llvm::StringRef(), // No prompt
560
1
                            llvm::StringRef(), // Continuation prompt
561
1
                            multiple_lines, color_prompt,
562
1
                            1, // Show line numbers starting at 1
563
1
                            *this));
564
565
1
  StreamFileSP output_sp = io_handler_sp->GetOutputStreamFileSP();
566
1
  if (output_sp) {
567
1
    output_sp->PutCString(
568
1
        "Enter expressions, then terminate with an empty line to evaluate:\n");
569
1
    output_sp->Flush();
570
1
  }
571
1
  debugger.RunIOHandlerAsync(io_handler_sp);
572
1
}
573
574
static EvaluateExpressionOptions
575
GetExprOptions(ExecutionContext &ctx,
576
0
               CommandObjectExpression::CommandOptions command_options) {
577
0
  command_options.OptionParsingStarting(&ctx);
578
579
  // Default certain settings for REPL regardless of the global settings.
580
0
  command_options.unwind_on_error = false;
581
0
  command_options.ignore_breakpoints = false;
582
0
  command_options.debug = false;
583
584
0
  EvaluateExpressionOptions expr_options;
585
0
  expr_options.SetUnwindOnError(command_options.unwind_on_error);
586
0
  expr_options.SetIgnoreBreakpoints(command_options.ignore_breakpoints);
587
0
  expr_options.SetTryAllThreads(command_options.try_all_threads);
588
589
0
  if (command_options.timeout > 0)
590
0
    expr_options.SetTimeout(std::chrono::microseconds(command_options.timeout));
591
0
  else
592
0
    expr_options.SetTimeout(std::nullopt);
593
594
0
  return expr_options;
595
0
}
596
597
void CommandObjectExpression::DoExecute(llvm::StringRef command,
598
3.77k
                                        CommandReturnObject &result) {
599
3.77k
  m_fixed_expression.clear();
600
3.77k
  auto exe_ctx = GetCommandInterpreter().GetExecutionContext();
601
3.77k
  m_option_group.NotifyOptionParsingStarting(&exe_ctx);
602
603
3.77k
  if (command.empty()) {
604
1
    GetMultilineExpression();
605
1
    return;
606
1
  }
607
608
3.77k
  OptionsWithRaw args(command);
609
3.77k
  llvm::StringRef expr = args.GetRawPart();
610
611
3.77k
  if (args.HasArgs()) {
612
496
    if (!ParseOptionsAndNotify(args.GetArgs(), result, m_option_group, exe_ctx))
613
13
      return;
614
615
483
    if (m_repl_option.GetOptionValue().GetCurrentValue()) {
616
0
      Target &target = GetSelectedOrDummyTarget();
617
      // Drop into REPL
618
0
      m_expr_lines.clear();
619
0
      m_expr_line_count = 0;
620
621
0
      Debugger &debugger = target.GetDebugger();
622
623
      // Check if the LLDB command interpreter is sitting on top of a REPL
624
      // that launched it...
625
0
      if (debugger.CheckTopIOHandlerTypes(IOHandler::Type::CommandInterpreter,
626
0
                                          IOHandler::Type::REPL)) {
627
        // the LLDB command interpreter is sitting on top of a REPL that
628
        // launched it, so just say the command interpreter is done and
629
        // fall back to the existing REPL
630
0
        m_interpreter.GetIOHandler(false)->SetIsDone(true);
631
0
      } else {
632
        // We are launching the REPL on top of the current LLDB command
633
        // interpreter, so just push one
634
0
        bool initialize = false;
635
0
        Status repl_error;
636
0
        REPLSP repl_sp(target.GetREPL(repl_error, m_command_options.language,
637
0
                                       nullptr, false));
638
639
0
        if (!repl_sp) {
640
0
          initialize = true;
641
0
          repl_sp = target.GetREPL(repl_error, m_command_options.language,
642
0
                                    nullptr, true);
643
0
          if (!repl_error.Success()) {
644
0
            result.SetError(repl_error);
645
0
            return;
646
0
          }
647
0
        }
648
649
0
        if (repl_sp) {
650
0
          if (initialize) {
651
0
            repl_sp->SetEvaluateOptions(
652
0
                GetExprOptions(exe_ctx, m_command_options));
653
0
            repl_sp->SetFormatOptions(m_format_options);
654
0
            repl_sp->SetValueObjectDisplayOptions(m_varobj_options);
655
0
          }
656
657
0
          IOHandlerSP io_handler_sp(repl_sp->GetIOHandler());
658
0
          io_handler_sp->SetIsDone(false);
659
0
          debugger.RunIOHandlerAsync(io_handler_sp);
660
0
        } else {
661
0
          repl_error.SetErrorStringWithFormat(
662
0
              "Couldn't create a REPL for %s",
663
0
              Language::GetNameForLanguageType(m_command_options.language));
664
0
          result.SetError(repl_error);
665
0
          return;
666
0
        }
667
0
      }
668
0
    }
669
    // No expression following options
670
483
    else if (expr.empty()) {
671
0
      GetMultilineExpression();
672
0
      return;
673
0
    }
674
483
  }
675
676
3.75k
  Target &target = GetSelectedOrDummyTarget();
677
3.75k
  if (EvaluateExpression(expr, result.GetOutputStream(),
678
3.75k
                         result.GetErrorStream(), result)) {
679
680
3.52k
    if (!m_fixed_expression.empty() && 
target.GetEnableNotifyAboutFixIts()4
) {
681
4
      CommandHistory &history = m_interpreter.GetCommandHistory();
682
      // FIXME: Can we figure out what the user actually typed (e.g. some alias
683
      // for expr???)
684
      // If we can it would be nice to show that.
685
4
      std::string fixed_command("expression ");
686
4
      if (args.HasArgs()) {
687
        // Add in any options that might have been in the original command:
688
0
        fixed_command.append(std::string(args.GetArgStringWithDelimiter()));
689
0
        fixed_command.append(m_fixed_expression);
690
0
      } else
691
4
        fixed_command.append(m_fixed_expression);
692
4
      history.AppendString(fixed_command);
693
4
    }
694
3.52k
    return;
695
3.52k
  }
696
238
  result.SetStatus(eReturnStatusFailed);
697
238
}