gc_callback.h 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. // Copyright 2015 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #ifndef EXTENSIONS_RENDERER_GC_CALLBACK_H_
  5. #define EXTENSIONS_RENDERER_GC_CALLBACK_H_
  6. #include "base/callback.h"
  7. #include "base/memory/ref_counted.h"
  8. #include "base/memory/weak_ptr.h"
  9. #include "base/task/single_thread_task_runner.h"
  10. #include "v8/include/v8-forward.h"
  11. #include "v8/include/v8-persistent-handle.h"
  12. namespace extensions {
  13. class ScriptContext;
  14. // Runs |callback| when v8 garbage collects |object|, or |fallback| if
  15. // |context| is invalidated first. Exactly one of |callback| or |fallback| will
  16. // be called, after which it deletes itself.
  17. // This object manages its own lifetime.
  18. // TODO(devlin): Cleanup. "callback" and "fallback" are odd names here, and
  19. // we should use OnceCallbacks.
  20. class GCCallback {
  21. public:
  22. GCCallback(ScriptContext* context,
  23. const v8::Local<v8::Object>& object,
  24. const v8::Local<v8::Function>& callback,
  25. base::OnceClosure fallback);
  26. GCCallback(ScriptContext* context,
  27. const v8::Local<v8::Object>& object,
  28. base::OnceClosure callback,
  29. base::OnceClosure fallback);
  30. GCCallback(const GCCallback&) = delete;
  31. GCCallback& operator=(const GCCallback&) = delete;
  32. private:
  33. GCCallback(ScriptContext* context,
  34. const v8::Local<v8::Object>& object,
  35. const v8::Local<v8::Function> v8_callback,
  36. base::OnceClosure closure_callback,
  37. base::OnceClosure fallback);
  38. ~GCCallback();
  39. static void OnObjectGC(const v8::WeakCallbackInfo<GCCallback>& data);
  40. void RunCallback();
  41. void OnContextInvalidated();
  42. // The context which owns |object_|.
  43. ScriptContext* context_;
  44. // A task runner associated with the frame for the context.
  45. scoped_refptr<base::SingleThreadTaskRunner> task_runner_;
  46. // The object this GCCallback is bound to.
  47. v8::Global<v8::Object> object_;
  48. // The function to run when |object_| is garbage collected. Can be either a
  49. // JS or native function (only one will be set).
  50. v8::Global<v8::Function> v8_callback_;
  51. base::OnceClosure closure_callback_;
  52. // The function to run if |context_| is invalidated before we have a chance
  53. // to execute |callback_|.
  54. base::OnceClosure fallback_;
  55. base::WeakPtrFactory<GCCallback> weak_ptr_factory_{this};
  56. };
  57. } // namespace extensions
  58. #endif // EXTENSIONS_RENDERER_GC_CALLBACK_H_