Fix crash in ExtensionFunctionDispatcher due to invalid Profile/BrowserContext

The Profile may be closed (and hence the BrowserContext becomes invalid) after
the LogSuccess task is posted to the UI thread. We don't care about logging
function call activity for a profile that just closed, so skip the logging.

BUG=341195
TEST=existing extensions browser_tests
[email protected]

Review URL: https://codereview.chromium.org/151003008

git-svn-id: svn://svn.chromium.org/chrome/trunk/src@249470 0039d316-1c4b-4281-b951-d872f2087c98
diff --git a/chrome/browser/extensions/extension_function_dispatcher.cc b/chrome/browser/extensions/extension_function_dispatcher.cc
index 77ba907..944763f5 100644
--- a/chrome/browser/extensions/extension_function_dispatcher.cc
+++ b/chrome/browser/extensions/extension_function_dispatcher.cc
@@ -42,6 +42,7 @@
 
 using extensions::Extension;
 using extensions::ExtensionAPI;
+using extensions::ExtensionsBrowserClient;
 using extensions::ExtensionSystem;
 using extensions::Feature;
 using content::BrowserThread;
@@ -55,7 +56,7 @@
                              const std::string& api_name,
                              scoped_ptr<base::ListValue> args,
                              content::BrowserContext* browser_context) {
-  // The ApiActivityLogger can only be accessed from the main (UI) thread. If
+  // The ApiActivityMonitor can only be accessed from the main (UI) thread. If
   // we're running on the wrong thread, re-dispatch from the main thread.
   if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) {
     BrowserThread::PostTask(BrowserThread::UI,
@@ -67,9 +68,12 @@
                                        browser_context));
     return;
   }
+  // The BrowserContext may become invalid after the task above is posted.
+  if (!ExtensionsBrowserClient::Get()->IsValidContext(browser_context))
+    return;
+
   extensions::ApiActivityMonitor* monitor =
-      extensions::ExtensionsBrowserClient::Get()->GetApiActivityMonitor(
-          browser_context);
+      ExtensionsBrowserClient::Get()->GetApiActivityMonitor(browser_context);
   if (monitor)
     monitor->OnApiFunctionCalled(extension_id, api_name, args.Pass());
 }