[Extensions Bindings] Add a thread-friendly ScriptContext getter

Add a common ScriptContext getter to retrieve a ScriptContext from a
given v8::Context that works across threads. This previously existed,
but only in native_extension_bindings_system.cc. Pull it out to a common
file to a) make it reusable from other consumers (custom hooks will need
to use this) and b) remove (direct) threading knowledge from the bindings
system.

Bug: 653596

Change-Id: I09a0e4ea76bb891ab1871ca1deb0d315e6e9789d
Reviewed-on: https://chromium-review.googlesource.com/812173
Reviewed-by: Istiaque Ahmed <[email protected]>
Commit-Queue: Devlin <[email protected]>
Cr-Commit-Position: refs/heads/master@{#522243}
diff --git a/extensions/renderer/get_script_context.cc b/extensions/renderer/get_script_context.cc
new file mode 100644
index 0000000..0b4ba826
--- /dev/null
+++ b/extensions/renderer/get_script_context.cc
@@ -0,0 +1,31 @@
+// Copyright 2017 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "extensions/renderer/get_script_context.h"
+
+#include "base/logging.h"
+#include "content/public/renderer/worker_thread.h"
+#include "extensions/renderer/script_context.h"
+#include "extensions/renderer/script_context_set.h"
+#include "extensions/renderer/worker_thread_dispatcher.h"
+
+namespace extensions {
+
+ScriptContext* GetScriptContextFromV8Context(v8::Local<v8::Context> context) {
+  ScriptContext* script_context =
+      content::WorkerThread::GetCurrentId() > 0
+          ? WorkerThreadDispatcher::GetScriptContext()
+          : ScriptContextSet::GetContextByV8Context(context);
+  DCHECK(!script_context || script_context->v8_context() == context);
+  return script_context;
+}
+
+ScriptContext* GetScriptContextFromV8ContextChecked(
+    v8::Local<v8::Context> context) {
+  ScriptContext* script_context = GetScriptContextFromV8Context(context);
+  CHECK(script_context);
+  return script_context;
+}
+
+}  // namespace extensions