update_engine: Add WeakPtrFactory to UpdateAttempter

BUG=b:179419726
TEST=cros_workon_make --board reef --test update_engine

Change-Id: Iba2a5c6d5eeb2d2c3df159a41e785bac3088239b
Reviewed-on: https://chromium-review.googlesource.com/c/aosp/platform/system/update_engine/+/2719101
Commit-Queue: Amin Hassani <ahassani@chromium.org>
Tested-by: Amin Hassani <ahassani@chromium.org>
Reviewed-by: Jae Hoon Kim <kimjae@chromium.org>
Reviewed-by: Vyshu Khota <vyshu@chromium.org>
diff --git a/cros/update_attempter.cc b/cros/update_attempter.cc
index 4f1ddff..67f36ce 100644
--- a/cros/update_attempter.cc
+++ b/cros/update_attempter.cc
@@ -128,7 +128,8 @@
 UpdateAttempter::UpdateAttempter(CertificateChecker* cert_checker)
     : processor_(new ActionProcessor()),
       cert_checker_(cert_checker),
-      is_install_(false) {}
+      is_install_(false),
+      weak_ptr_factory_(this) {}
 
 UpdateAttempter::~UpdateAttempter() {
   // Prevent any DBus communication from UpdateAttempter when shutting down the
@@ -173,7 +174,8 @@
   SystemState::Get()->update_manager()->PolicyRequest2(
       std::make_unique<UpdateCheckAllowedPolicy>(),
       policy_data_,  // Do not move because we don't want transfer of ownership.
-      base::Bind(&UpdateAttempter::OnUpdateScheduled, base::Unretained(this)));
+      base::Bind(&UpdateAttempter::OnUpdateScheduled,
+                 weak_ptr_factory_.GetWeakPtr()));
 
   waiting_for_scheduled_check_ = true;
   return true;
@@ -195,14 +197,14 @@
 
   // Broadcast the update engine status on startup to ensure consistent system
   // state on crashes.
-  MessageLoop::current()->PostTask(
-      FROM_HERE,
-      base::Bind(&UpdateAttempter::BroadcastStatus, base::Unretained(this)));
+  MessageLoop::current()->PostTask(FROM_HERE,
+                                   base::Bind(&UpdateAttempter::BroadcastStatus,
+                                              weak_ptr_factory_.GetWeakPtr()));
 
   MessageLoop::current()->PostTask(
       FROM_HERE,
       base::Bind(&UpdateAttempter::UpdateEngineStarted,
-                 base::Unretained(this)));
+                 weak_ptr_factory_.GetWeakPtr()));
   return true;
 }
 
diff --git a/cros/update_attempter.h b/cros/update_attempter.h
index ecd96c3..5360568 100644
--- a/cros/update_attempter.h
+++ b/cros/update_attempter.h
@@ -580,6 +580,8 @@
   std::shared_ptr<chromeos_update_manager::UpdateCheckAllowedPolicyData>
       policy_data_;
 
+  base::WeakPtrFactory<UpdateAttempter> weak_ptr_factory_;
+
   DISALLOW_COPY_AND_ASSIGN(UpdateAttempter);
 };