update_engine: UM: UpdateManager removes EvaluationContext objects.

This fixes a situation where the destruction of an UpdateManager object
may leave a bunch of dangling main loop events due to delayed
evaluation, whose presence prevents the destruction of their
corresponding EvaluationContext objects. We solve this by registering
each EvaluationContext that's created for an async evaluation with the
UpdateManager, and storing a (weak) reverse callback in each
EvaluationContext for unregistering itself upon destruction. The
UpdateManager itself cares to unregister (i.e. remove any pending
events) for any outstanding EvaluationContexts that are still present
during its destruction. This also ensures that these objects are
properly destructed right after the destruction of the UpdateManager.

This CL also fixes a bug whereas removal of pending events might have
left a "live" callback handle inside the EvaluationContext, thus
creating a reference-count cycle and preventing the object from being
deallocated.

BUG=None
TEST=Unit tests.

Change-Id: I5b7f4b740241ed3a5f1831ae41fead0fc1481071
Reviewed-on: https://chromium-review.googlesource.com/211720
Tested-by: Gilad Arnold <garnold@chromium.org>
Reviewed-by: Alex Vakulenko <avakulenko@chromium.org>
Commit-Queue: Gilad Arnold <garnold@chromium.org>
diff --git a/update_manager/update_manager-inl.h b/update_manager/update_manager-inl.h
index 649dcff..a9f051f 100644
--- a/update_manager/update_manager-inl.h
+++ b/update_manager/update_manager-inl.h
@@ -127,7 +127,16 @@
                                         ExpectedArgs...) const,
     ActualArgs... args) {
   scoped_refptr<EvaluationContext> ec =
-      new EvaluationContext(clock_, evaluation_timeout_, expiration_timeout_);
+      new EvaluationContext(
+          clock_, evaluation_timeout_, expiration_timeout_,
+          scoped_ptr<base::Callback<void(EvaluationContext*)>>(
+              new base::Callback<void(EvaluationContext*)>(
+                  base::Bind(&UpdateManager::UnregisterEvalContext,
+                             weak_ptr_factory_.GetWeakPtr()))));
+  if (!ec_repo_.insert(ec.get()).second) {
+    LOG(ERROR) << "Failed to register evaluation context; this is a bug.";
+  }
+
   // IMPORTANT: To ensure that ActualArgs can be converted to ExpectedArgs, we
   // explicitly instantiate UpdateManager::OnPolicyReadyToEvaluate with the
   // latter in lieu of the former.