Skip to content

Commit c885dbf

Browse files
author
git apple-llvm automerger
committed
Merge commit 'e1abf42c7b0c' from swift/release/5.3 into swift/master
2 parents f59ef87 + e1abf42 commit c885dbf

File tree

8 files changed

+217
-30
lines changed

8 files changed

+217
-30
lines changed

lldb/include/lldb/lldb-enumerations.h

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -269,7 +269,8 @@ enum ExpressionResults {
269269
eExpressionHitBreakpoint,
270270
eExpressionTimedOut,
271271
eExpressionResultUnavailable,
272-
eExpressionStoppedForDebug
272+
eExpressionStoppedForDebug,
273+
eExpressionThreadVanished
273274
};
274275

275276
enum SearchDepth {

lldb/source/Expression/FunctionCaller.cpp

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -364,8 +364,9 @@ lldb::ExpressionResults FunctionCaller::ExecuteFunction(
364364
if (return_value != lldb::eExpressionCompleted) {
365365
LLDB_LOGF(log,
366366
"== [FunctionCaller::ExecuteFunction] Execution of \"%s\" "
367-
"completed abnormally ==",
368-
m_name.c_str());
367+
"completed abnormally: %s ==",
368+
m_name.c_str(),
369+
Process::ExecutionResultAsCString(return_value));
369370
} else {
370371
LLDB_LOGF(log,
371372
"== [FunctionCaller::ExecuteFunction] Execution of \"%s\" "

lldb/source/Expression/LLVMUserExpression.cpp

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -136,6 +136,10 @@ LLVMUserExpression::DoExecute(DiagnosticManager &diagnostic_manager,
136136
return lldb::eExpressionSetupError;
137137
}
138138

139+
// Store away the thread ID for error reporting, in case it exits
140+
// during execution:
141+
lldb::tid_t expr_thread_id = exe_ctx.GetThreadRef().GetID();
142+
139143
Address wrapper_address(m_jit_start_addr);
140144

141145
std::vector<lldb::addr_t> args;
@@ -241,6 +245,14 @@ LLVMUserExpression::DoExecute(DiagnosticManager &diagnostic_manager,
241245
user_expression_plan->GetReturnValueObject();
242246
}
243247
}
248+
} else if (execution_result == lldb::eExpressionThreadVanished) {
249+
diagnostic_manager.Printf(
250+
eDiagnosticSeverityError,
251+
"Couldn't complete execution; the thread "
252+
"on which the expression was being run: 0x%" PRIx64
253+
" exited during its execution.",
254+
expr_thread_id);
255+
return execution_result;
244256
} else {
245257
diagnostic_manager.Printf(
246258
eDiagnosticSeverityError, "Couldn't execute function; result was %s",

lldb/source/Interpreter/CommandInterpreter.cpp

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1606,6 +1606,11 @@ Status CommandInterpreter::PreprocessCommand(std::string &command) {
16061606
"expression '%s'",
16071607
expr_str.c_str());
16081608
break;
1609+
case eExpressionThreadVanished:
1610+
error.SetErrorStringWithFormat(
1611+
"expression thread vanished for the expression '%s'",
1612+
expr_str.c_str());
1613+
break;
16091614
}
16101615
}
16111616
}

lldb/source/Target/Process.cpp

Lines changed: 45 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -4771,13 +4771,27 @@ GetExpressionTimeout(const EvaluateExpressionOptions &options,
47714771
}
47724772

47734773
static llvm::Optional<ExpressionResults>
4774-
HandleStoppedEvent(Thread &thread, const ThreadPlanSP &thread_plan_sp,
4774+
HandleStoppedEvent(lldb::tid_t thread_id, const ThreadPlanSP &thread_plan_sp,
47754775
RestorePlanState &restorer, const EventSP &event_sp,
47764776
EventSP &event_to_broadcast_sp,
4777-
const EvaluateExpressionOptions &options, bool handle_interrupts) {
4777+
const EvaluateExpressionOptions &options,
4778+
bool handle_interrupts) {
47784779
Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS);
47794780

4780-
ThreadPlanSP plan = thread.GetCompletedPlan();
4781+
ThreadSP thread_sp = thread_plan_sp->GetTarget()
4782+
.GetProcessSP()
4783+
->GetThreadList()
4784+
.FindThreadByID(thread_id);
4785+
if (!thread_sp) {
4786+
LLDB_LOG(log,
4787+
"The thread on which we were running the "
4788+
"expression: tid = {0}, exited while "
4789+
"the expression was running.",
4790+
thread_id);
4791+
return eExpressionThreadVanished;
4792+
}
4793+
4794+
ThreadPlanSP plan = thread_sp->GetCompletedPlan();
47814795
if (plan == thread_plan_sp && plan->PlanSucceeded()) {
47824796
LLDB_LOG(log, "execution completed successfully");
47834797

@@ -4787,7 +4801,7 @@ HandleStoppedEvent(Thread &thread, const ThreadPlanSP &thread_plan_sp,
47874801
return eExpressionCompleted;
47884802
}
47894803

4790-
StopInfoSP stop_info_sp = thread.GetStopInfo();
4804+
StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
47914805
if (stop_info_sp && stop_info_sp->GetStopReason() == eStopReasonBreakpoint &&
47924806
stop_info_sp->ShouldNotify(event_sp.get())) {
47934807
LLDB_LOG(log, "stopped for breakpoint: {0}.", stop_info_sp->GetDescription());
@@ -4862,6 +4876,10 @@ Process::RunThreadPlan(ExecutionContext &exe_ctx,
48624876
return eExpressionSetupError;
48634877
}
48644878

4879+
// Record the thread's id so we can tell when a thread we were using
4880+
// to run the expression exits during the expression evaluation.
4881+
lldb::tid_t expr_thread_id = thread->GetID();
4882+
48654883
// We need to change some of the thread plan attributes for the thread plan
48664884
// runner. This will restore them when we are done:
48674885

@@ -5006,7 +5024,7 @@ Process::RunThreadPlan(ExecutionContext &exe_ctx,
50065024
LLDB_LOGF(log,
50075025
"Process::RunThreadPlan(): Resuming thread %u - 0x%4.4" PRIx64
50085026
" to run thread plan \"%s\".",
5009-
thread->GetIndexID(), thread->GetID(), s.GetData());
5027+
thread_idx_id, expr_thread_id, s.GetData());
50105028
}
50115029

50125030
bool got_event;
@@ -5206,33 +5224,23 @@ Process::RunThreadPlan(ExecutionContext &exe_ctx,
52065224

52075225
switch (stop_state) {
52085226
case lldb::eStateStopped: {
5209-
// We stopped, figure out what we are going to do now.
5210-
ThreadSP thread_sp =
5211-
GetThreadList().FindThreadByIndexID(thread_idx_id);
5212-
if (!thread_sp) {
5213-
// Ooh, our thread has vanished. Unlikely that this was
5214-
// successful execution...
5215-
LLDB_LOGF(log,
5216-
"Process::RunThreadPlan(): execution completed "
5217-
"but our thread (index-id=%u) has vanished.",
5218-
thread_idx_id);
5219-
return_value = eExpressionInterrupted;
5220-
} else if (Process::ProcessEventData::GetRestartedFromEvent(
5221-
event_sp.get())) {
5227+
if (Process::ProcessEventData::GetRestartedFromEvent(
5228+
event_sp.get())) {
52225229
// If we were restarted, we just need to go back up to fetch
52235230
// another event.
5224-
if (log) {
5225-
LLDB_LOGF(log, "Process::RunThreadPlan(): Got a stop and "
5226-
"restart, so we'll continue waiting.");
5227-
}
5231+
LLDB_LOGF(log, "Process::RunThreadPlan(): Got a stop and "
5232+
"restart, so we'll continue waiting.");
52285233
keep_going = true;
52295234
do_resume = false;
52305235
handle_running_event = true;
52315236
} else {
52325237
const bool handle_interrupts = true;
52335238
return_value = *HandleStoppedEvent(
5234-
*thread, thread_plan_sp, thread_plan_restorer, event_sp,
5235-
event_to_broadcast_sp, options, handle_interrupts);
5239+
expr_thread_id, thread_plan_sp, thread_plan_restorer,
5240+
event_sp, event_to_broadcast_sp, options,
5241+
handle_interrupts);
5242+
if (return_value == eExpressionThreadVanished)
5243+
keep_going = false;
52365244
}
52375245
} break;
52385246

@@ -5354,8 +5362,9 @@ Process::RunThreadPlan(ExecutionContext &exe_ctx,
53545362
// job. Check that here:
53555363
const bool handle_interrupts = false;
53565364
if (auto result = HandleStoppedEvent(
5357-
*thread, thread_plan_sp, thread_plan_restorer, event_sp,
5358-
event_to_broadcast_sp, options, handle_interrupts)) {
5365+
expr_thread_id, thread_plan_sp, thread_plan_restorer,
5366+
event_sp, event_to_broadcast_sp, options,
5367+
handle_interrupts)) {
53595368
return_value = *result;
53605369
back_to_top = false;
53615370
break;
@@ -5427,6 +5436,13 @@ Process::RunThreadPlan(ExecutionContext &exe_ctx,
54275436
m_public_state.SetValueNoLock(old_state);
54285437
}
54295438

5439+
// If our thread went away on us, we need to get out of here without
5440+
// doing any more work. We don't have to clean up the thread plan, that
5441+
// will have happened when the Thread was destroyed.
5442+
if (return_value == eExpressionThreadVanished) {
5443+
return return_value;
5444+
}
5445+
54305446
if (return_value != eExpressionCompleted && log) {
54315447
// Print a backtrace into the log so we can figure out where we are:
54325448
StreamString s;
@@ -5615,7 +5631,7 @@ Process::RunThreadPlan(ExecutionContext &exe_ctx,
56155631
}
56165632

56175633
const char *Process::ExecutionResultAsCString(ExpressionResults result) {
5618-
const char *result_name;
5634+
const char *result_name = "<unknown>";
56195635

56205636
switch (result) {
56215637
case eExpressionCompleted:
@@ -5645,6 +5661,8 @@ const char *Process::ExecutionResultAsCString(ExpressionResults result) {
56455661
case eExpressionStoppedForDebug:
56465662
result_name = "eExpressionStoppedForDebug";
56475663
break;
5664+
case eExpressionThreadVanished:
5665+
result_name = "eExpressionThreadVanished";
56485666
}
56495667
return result_name;
56505668
}
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
C_SOURCES := main.c
2+
CFLAGS_EXTRAS := -std=c99
3+
4+
ENABLE_THREADS := YES
5+
6+
include Makefile.rules
Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
1+
"""
2+
Make sure that we handle an expression on a thread, if
3+
the thread exits while the expression is running.
4+
"""
5+
6+
import lldb
7+
from lldbsuite.test.decorators import *
8+
import lldbsuite.test.lldbutil as lldbutil
9+
from lldbsuite.test.lldbtest import *
10+
11+
class TestExitDuringExpression(TestBase):
12+
13+
mydir = TestBase.compute_mydir(__file__)
14+
15+
NO_DEBUG_INFO_TESTCASE = True
16+
17+
@skipIfWindows
18+
def test_exit_before_one_thread_unwind(self):
19+
"""Test the case where we exit within the one thread timeout"""
20+
self.exiting_expression_test(True, True)
21+
22+
@skipIfWindows
23+
def test_exit_before_one_thread_no_unwind(self):
24+
"""Test the case where we exit within the one thread timeout"""
25+
self.exiting_expression_test(True, False)
26+
27+
@skipIfWindows
28+
def test_exit_after_one_thread_unwind(self):
29+
"""Test the case where we exit within the one thread timeout"""
30+
self.exiting_expression_test(False, True)
31+
32+
@skipIfWindows
33+
def test_exit_after_one_thread_no_unwind(self):
34+
"""Test the case where we exit within the one thread timeout"""
35+
self.exiting_expression_test(False, False)
36+
37+
def setUp(self):
38+
TestBase.setUp(self)
39+
self.main_source_file = lldb.SBFileSpec("main.c")
40+
self.build()
41+
42+
def exiting_expression_test(self, before_one_thread_timeout , unwind):
43+
"""function_to_call sleeps for g_timeout microseconds, then calls pthread_exit.
44+
This test calls function_to_call with an overall timeout of 500
45+
microseconds, and a one_thread_timeout as passed in.
46+
It also sets unwind_on_exit for the call to the unwind passed in.
47+
This allows you to have the thread exit either before the one thread
48+
timeout is passed. """
49+
50+
(target, process, thread, bkpt) = lldbutil.run_to_source_breakpoint(self,
51+
"Break here and cause the thread to exit", self.main_source_file)
52+
53+
# We'll continue to this breakpoint after running our expression:
54+
return_bkpt = target.BreakpointCreateBySourceRegex("Break here to make sure the thread exited", self.main_source_file)
55+
frame = thread.frames[0]
56+
tid = thread.GetThreadID()
57+
# Find the timeout:
58+
var_options = lldb.SBVariablesOptions()
59+
var_options.SetIncludeArguments(False)
60+
var_options.SetIncludeLocals(False)
61+
var_options.SetIncludeStatics(True)
62+
63+
value_list = frame.GetVariables(var_options)
64+
g_timeout = value_list.GetFirstValueByName("g_timeout")
65+
self.assertTrue(g_timeout.IsValid(), "Found g_timeout")
66+
67+
error = lldb.SBError()
68+
timeout_value = g_timeout.GetValueAsUnsigned(error)
69+
self.assertTrue(error.Success(), "Couldn't get timeout value: %s"%(error.GetCString()))
70+
71+
one_thread_timeout = 0
72+
if (before_one_thread_timeout):
73+
one_thread_timeout = timeout_value * 2
74+
else:
75+
one_thread_timeout = int(timeout_value / 2)
76+
77+
options = lldb.SBExpressionOptions()
78+
options.SetUnwindOnError(unwind)
79+
options.SetOneThreadTimeoutInMicroSeconds(one_thread_timeout)
80+
options.SetTimeoutInMicroSeconds(4 * timeout_value)
81+
82+
result = frame.EvaluateExpression("function_to_call()", options)
83+
84+
# Make sure the thread actually exited:
85+
thread = process.GetThreadByID(tid)
86+
self.assertFalse(thread.IsValid(), "The thread exited")
87+
88+
# Make sure the expression failed:
89+
self.assertFalse(result.GetError().Success(), "Expression failed.")
90+
91+
# Make sure we can keep going:
92+
threads = lldbutil.continue_to_breakpoint(process, return_bkpt)
93+
if not threads:
94+
self.fail("didn't get any threads back after continuing")
95+
96+
self.assertEqual(len(threads), 1, "One thread hit our breakpoint")
97+
thread = threads[0]
98+
frame = thread.frames[0]
99+
# Now get the return value, if we successfully caused the thread to exit
100+
# it should be 10, not 20.
101+
ret_val = frame.FindVariable("ret_val")
102+
self.assertTrue(ret_val.GetError().Success(), "Found ret_val")
103+
ret_val_value = ret_val.GetValueAsSigned(error)
104+
self.assertTrue(error.Success(), "Got ret_val's value")
105+
self.assertEqual(ret_val_value, 10, "We put the right value in ret_val")
106+
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
#include <errno.h>
2+
#include <pthread.h>
3+
#include <stdio.h>
4+
#include <unistd.h>
5+
6+
static unsigned int g_timeout = 100000;
7+
8+
int function_to_call() {
9+
10+
errno = 0;
11+
while (1) {
12+
int result = usleep(g_timeout);
13+
if (errno != EINTR)
14+
break;
15+
}
16+
17+
pthread_exit((void *)10);
18+
19+
return 20; // Prevent warning
20+
}
21+
22+
void *exiting_thread_func(void *unused) {
23+
function_to_call(); // Break here and cause the thread to exit
24+
return NULL;
25+
}
26+
27+
int main() {
28+
char *exit_ptr;
29+
pthread_t exiting_thread;
30+
31+
pthread_create(&exiting_thread, NULL, exiting_thread_func, NULL);
32+
33+
pthread_join(exiting_thread, &exit_ptr);
34+
int ret_val = (int)exit_ptr;
35+
usleep(g_timeout * 4); // Make sure in the "run all threads" case
36+
// that we don't run past our breakpoint.
37+
return ret_val; // Break here to make sure the thread exited.
38+
}

0 commit comments

Comments
 (0)