Open Bug 1791110 Opened 4 years ago Updated 3 years ago

Task queue crashes if released with active shutdown tasks

Categories

(Core :: XPCOM, defect)

defect

Tracking

()

People

(Reporter: rkraesig, Unassigned)

Details

If a background task queue is created with NS_CreateBackgroundTaskQueue() and has an nsITargetShutdownTask task assigned to it, that task will never run, and the destructor of TaskQueue will assert, instead.

(This appears to be avoidable when the TaskQueue is created directly, by calling BeginShutdown() on it before releasing it -- but NS_CreateBackgroundTaskQueue() only returns an nsISerialEventTarget, which doesn't expose any shutdown methods.)

 

Test case, suitable for GTest inclusion:

class DummyShutdownTask final : public nsITargetShutdownTask {
  virtual ~DummyShutdownTask() = default;
  NS_DECL_THREADSAFE_ISUPPORTS
  virtual void TargetShutdown() override final {};
};

NS_IMPL_ISUPPORTS(DummyShutdownTask, nsITargetShutdownTask);

TEST(TaskQueue_, ShutdownTask)
{
  nsCOMPtr<nsISerialEventTarget> target;
  nsresult rv =
      NS_CreateBackgroundTaskQueue("task queue", getter_AddRefs(target));
  ASSERT_NSRESULT_OK(rv);

  {
    auto task = mozilla::MakeRefPtr<DummyShutdownTask>();
    rv = target->RegisterShutdownTask(task.get());
    ASSERT_NSRESULT_OK(rv);
  }  // release the task queue...

  PR_Sleep(PR_SecondsToInterval(1));  // ... and wait for the kaboom:  
  // "Assertion failure: mShutdownTasks.IsEmpty(), at C:/mozilla-source/mozilla-unified/xpcom/threads/TaskQueue.cpp:80"
}

All current uses of nsITargetShutdownTask also hold a reference to the TaskQueue, and thus keep the queue alive until shutdown when it will be automatically shutdown during thread shutdown. This was the expected behaviour for this sort of method.

Unfortunately automatically running the shutdown tasks when refcount reaches zero is very difficult, as the TaskQueue itself needs to stay alive in order to run the shutdown tasks against it, but the refcount is atomic, and so drops to zero. Doing something else would be somewhat of a pain, which is why this wasn't handled. For now, making sure that nsITargetShutdownTask instances keep their TaskQueue targets alive is probably our best approach.

Severity: -- → S4
You need to log in before you can comment on or make changes to this bug.