1// Copyright (c) 2012 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
5#ifndef PPAPI_SHARED_IMPL_VAR_TRACKER_H_
6#define PPAPI_SHARED_IMPL_VAR_TRACKER_H_
7
8#include <vector>
9
10#include "base/basictypes.h"
11#include "base/containers/hash_tables.h"
12#include "base/memory/ref_counted.h"
13#include "base/memory/scoped_ptr.h"
14#include "base/memory/shared_memory.h"
15#include "base/threading/thread_checker.h"
16#include "ppapi/c/pp_instance.h"
17#include "ppapi/c/pp_module.h"
18#include "ppapi/c/pp_resource.h"
19#include "ppapi/c/pp_var.h"
20#include "ppapi/shared_impl/host_resource.h"
21#include "ppapi/shared_impl/ppapi_shared_export.h"
22#include "ppapi/shared_impl/var.h"
23
24namespace ppapi {
25
26class ArrayBufferVar;
27
28// Tracks non-POD (refcounted) var objects held by a plugin.
29//
30// The tricky part is the concept of a "tracked object". These are only
31// necessary in the plugin side of the proxy when running out of process. A
32// tracked object is one that the plugin is aware of, but doesn't hold a
33// reference to. This will happen when the plugin is passed an object as an
34// argument from the host (renderer) as an input argument to a sync function,
35// but where ownership is not passed.
36//
37// This class maintains the "track_with_no_reference_count" but doesn't do
38// anything with it other than call virtual functions. The interesting parts
39// are added by the PluginObjectVar derived from this class.
40class PPAPI_SHARED_EXPORT VarTracker {
41 public:
42  // A SINGLE_THREADED VarTracker will use a thread-checker to make sure it's
43  // always invoked on the same thread on which it was constructed. A
44  // THREAD_SAFE VarTracker will check that the ProxyLock is held. See
45  // CheckThreadingPreconditions() for more details.
46  enum ThreadMode { SINGLE_THREADED, THREAD_SAFE };
47  explicit VarTracker(ThreadMode thread_mode);
48  virtual ~VarTracker();
49
50  // Called by the Var object to add a new var to the tracker.
51  int32 AddVar(Var* var);
52
53  // Looks up a given var and returns a reference to the Var if it exists.
54  // Returns NULL if the var type is not an object we track (POD) or is
55  // invalid.
56  Var* GetVar(int32 var_id) const;
57  Var* GetVar(const PP_Var& var) const;
58
59  // Increases a previously-known Var ID's refcount, returning true on success,
60  // false if the ID is invalid. The PP_Var version returns true and does
61  // nothing for non-refcounted type vars.
62  bool AddRefVar(int32 var_id);
63  bool AddRefVar(const PP_Var& var);
64
65  // Decreases the given Var ID's refcount, returning true on success, false if
66  // the ID is invalid or if the refcount was already 0. The PP_Var version
67  // returns true and does nothing for non-refcounted type vars. The var will
68  // be deleted if there are no more refs to it.
69  bool ReleaseVar(int32 var_id);
70  bool ReleaseVar(const PP_Var& var);
71
72  // Create a new array buffer of size |size_in_bytes|. Return a PP_Var that
73  // that references it and has an initial reference-count of 1.
74  PP_Var MakeArrayBufferPPVar(uint32 size_in_bytes);
75  // Same as above, but copy the contents of |data| in to the new array buffer.
76  PP_Var MakeArrayBufferPPVar(uint32 size_in_bytes, const void* data);
77  // Same as above, but copy the contents of the shared memory in |h|
78  // into the new array buffer.
79  PP_Var MakeArrayBufferPPVar(uint32 size_in_bytes,
80                              base::SharedMemoryHandle h);
81
82  // Create an ArrayBuffer and copy the contents of |data| in to it. The
83  // returned object has 0 reference count in the tracker, and like all
84  // RefCounted objects, has a 0 initial internal reference count. (You should
85  // usually immediately put this in a scoped_refptr).
86  ArrayBufferVar* MakeArrayBufferVar(uint32 size_in_bytes, const void* data);
87
88  // Return a vector containing all PP_Vars that are in the tracker. This is
89  // to help implement PPB_Testing_Dev.GetLiveVars and should generally not be
90  // used in production code. The PP_Vars are returned in no particular order,
91  // and their reference counts are unaffected.
92  std::vector<PP_Var> GetLiveVars();
93
94  // Retrieves the internal reference counts for testing. Returns 0 if we
95  // know about the object but the corresponding value is 0, or -1 if the
96  // given object ID isn't in our map.
97  int GetRefCountForObject(const PP_Var& object);
98  int GetTrackedWithNoReferenceCountForObject(const PP_Var& object);
99
100  // Returns true if the given vartype is refcounted and has associated objects
101  // (it's not POD).
102  static bool IsVarTypeRefcounted(PP_VarType type);
103
104  // Called after an instance is deleted to do var cleanup.
105  virtual void DidDeleteInstance(PP_Instance instance) = 0;
106
107  // Returns an "id" for a shared memory handle that can be safely sent between
108  // the host and plugin, and resolved back into the original handle on the
109  // host. Not implemented on the plugin side.
110  virtual int TrackSharedMemoryHandle(PP_Instance instance,
111                                      base::SharedMemoryHandle handle,
112                                      uint32 size_in_bytes) = 0;
113
114  // Resolves an "id" generated by TrackSharedMemoryHandle back into
115  // a SharedMemory handle and its size on the host.
116  // Not implemented on the plugin side.
117  virtual bool StopTrackingSharedMemoryHandle(
118      int id,
119      PP_Instance instance,
120      base::SharedMemoryHandle *handle,
121      uint32* size_in_bytes) = 0;
122
123 protected:
124  struct PPAPI_SHARED_EXPORT VarInfo {
125    VarInfo();
126    VarInfo(Var* v, int input_ref_count);
127
128    scoped_refptr<Var> var;
129
130    // Explicit reference count. This value is affected by the renderer calling
131    // AddRef and Release. A nonzero value here is represented by a single
132    // reference in the host on our behalf (this reduces IPC traffic).
133    int ref_count;
134
135    // Tracked object count (see class comment above).
136    //
137    // "TrackObjectWithNoReference" might be called recursively in rare cases.
138    // For example, say the host calls a plugin function with an object as an
139    // argument, and in response, the plugin calls a host function that then
140    // calls another (or the same) plugin function with the same object.
141    //
142    // This value tracks the number of calls to TrackObjectWithNoReference so
143    // we know when we can stop tracking this object.
144    int track_with_no_reference_count;
145  };
146  typedef base::hash_map<int32, VarInfo> VarMap;
147
148  // Specifies what should happen with the refcount when calling AddVarInternal.
149  enum AddVarRefMode {
150    ADD_VAR_TAKE_ONE_REFERENCE,
151    ADD_VAR_CREATE_WITH_NO_REFERENCE
152  };
153
154  // On the host-side, make sure we are called on the right thread. On the
155  // plugin side, make sure we have the proxy lock.
156  void CheckThreadingPreconditions() const;
157
158  // Implementation of AddVar that allows the caller to specify whether the
159  // initial refcount of the added object will be 0 or 1.
160  //
161  // Overridden in the plugin proxy to do additional object tracking.
162  virtual int32 AddVarInternal(Var* var, AddVarRefMode mode);
163
164  // Convenience functions for doing lookups into the live_vars_ map.
165  VarMap::iterator GetLiveVar(int32 id);
166  VarMap::iterator GetLiveVar(const PP_Var& var);
167  VarMap::const_iterator GetLiveVar(const PP_Var& var) const;
168
169  // Called when AddRefVar increases a "tracked" ProxyObject's refcount from
170  // zero to one. In the plugin side of the proxy, we need to send some
171  // messages to the host. In the host side, this should never be called since
172  // there are no proxy objects.
173  virtual void TrackedObjectGettingOneRef(VarMap::const_iterator iter);
174
175  // Called when ReleaseVar decreases a object's refcount from one to zero. It
176  // may still be "tracked" (has a "track_with_no_reference_count") value. In
177  // the plugin side of the proxy, we need to tell the host that we no longer
178  // have a reference. In the host side, this should never be called since
179  // there are no proxy objects.
180  virtual void ObjectGettingZeroRef(VarMap::iterator iter);
181
182  // Called when an object may have had its refcount or
183  // track_with_no_reference_count value decreased. If the object has neither
184  // refs anymore, this will remove it and return true. Returns false if it's
185  // still alive.
186  //
187  // Overridden by the PluginVarTracker to also clean up the host info map.
188  virtual bool DeleteObjectInfoIfNecessary(VarMap::iterator iter);
189
190  VarMap live_vars_;
191
192  // Last assigned var ID.
193  int32 last_var_id_;
194
195 private:
196  // Create and return a new ArrayBufferVar size_in_bytes bytes long. This is
197  // implemented by the Host and Plugin tracker separately, so that it can be
198  // a real WebKit ArrayBuffer on the host side.
199  virtual ArrayBufferVar* CreateArrayBuffer(uint32 size_in_bytes) = 0;
200  virtual ArrayBufferVar* CreateShmArrayBuffer(
201      uint32 size_in_bytes,
202      base::SharedMemoryHandle handle) = 0;
203
204  // On the host side, we want to check that we are only called on the main
205  // thread. This is to protect us from accidentally using the tracker from
206  // other threads (especially the IO thread). On the plugin side, the tracker
207  // is protected by the proxy lock and is thread-safe, so this will be NULL.
208  scoped_ptr<base::ThreadChecker> thread_checker_;
209
210  DISALLOW_COPY_AND_ASSIGN(VarTracker);
211};
212
213}  // namespace ppapi
214
215#endif  // PPAPI_SHARED_IMPL_VAR_TRACKER_H_
216