Skip to content

Commit

Permalink
Fix potential deadlock in TestMdns (#6721)
Browse files Browse the repository at this point in the history
* Fix locking scope for MDNS test.

std::condition_variable is supposed to be able to hold the lock mutex
when exiting after wait_for. If the lock on the mutex is held throughout
the 'RunMainLoop', the condition variable can never exit.

Updated the scope of the locks.

* Update the locking logic to make the test not racy at startup

* Fix unterminated comment
  • Loading branch information
andy31415 authored and pull[bot] committed Jun 22, 2021
1 parent a7403c9 commit cd579de
Showing 1 changed file with 43 additions and 11 deletions.
54 changes: 43 additions & 11 deletions src/platform/tests/TestMdns.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -95,25 +95,57 @@ static const nlTest sTests[] = { NL_TEST_DEF("Test Mdns::PubSub", TestMdnsPubSub
int TestMdns()
{
std::mutex mtx;
std::unique_lock<std::mutex> lock(mtx);
std::condition_variable done;

std::condition_variable readyCondition;
bool ready = false;

std::condition_variable doneCondition;
bool done = false;

int retVal = EXIT_FAILURE;

std::thread t([&mtx, &done, &retVal]() {
std::thread t([&]() {
{
std::lock_guard<std::mutex> localLock(mtx);
nlTestSuite theSuite = { "CHIP DeviceLayer mdns tests", &sTests[0], nullptr, nullptr };
std::lock_guard<std::mutex> lock(mtx);
ready = true;
readyCondition.notify_one();
}

nlTestSuite theSuite = { "CHIP DeviceLayer mdns tests", &sTests[0], nullptr, nullptr };

nlTestRunner(&theSuite, nullptr);
retVal = nlTestRunnerStats(&theSuite);
nlTestRunner(&theSuite, nullptr);
retVal = nlTestRunnerStats(&theSuite);

{
std::lock_guard<std::mutex> lock(mtx);
done = true;
doneCondition.notify_all();
}
done.notify_all();
});

if (done.wait_for(lock, std::chrono::seconds(5)) == std::cv_status::timeout)
{
fprintf(stderr, "mDNS test timeout, is avahi daemon running?");
retVal = EXIT_FAILURE;
std::unique_lock<std::mutex> lock(mtx);
readyCondition.wait(lock, [&] { return ready; });

doneCondition.wait_for(lock, std::chrono::seconds(5));
if (!done)
{
fprintf(stderr, "mDNS test timeout, is avahi daemon running?\n");

chip::DeviceLayer::PlatformMgr().LockChipStack();
chip::DeviceLayer::PlatformMgr().Shutdown();
chip::DeviceLayer::SystemLayer.WakeSelect();
chip::DeviceLayer::PlatformMgr().UnlockChipStack();

// TODO: the above does not seem to actually reliably shut down the chip stack.
// Program will abort with core because chip thread will still run.
doneCondition.wait_for(lock, std::chrono::seconds(1));
if (!done)
{
fprintf(stderr, "Orderly shutdown of the platform main loop failed as well.\n");
}
retVal = EXIT_FAILURE;
}
}
return retVal;
}
Expand Down

0 comments on commit cd579de

Please sign in to comment.