• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2013 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 CONTENT_BROWSER_RENDERER_DATA_MEMOIZING_STORE_H_
6 #define CONTENT_BROWSER_RENDERER_DATA_MEMOIZING_STORE_H_
7 
8 #include <map>
9 
10 #include "base/bind.h"
11 #include "base/synchronization/lock.h"
12 #include "content/browser/renderer_host/render_view_host_impl.h"
13 #include "content/public/browser/browser_thread.h"
14 #include "content/public/browser/render_process_host_observer.h"
15 
16 namespace content {
17 
18 // RendererDataMemoizingStore is a thread-safe container that retains reference
19 // counted objects that are associated with one or more render processes.
20 // Objects are identified by an int and only a single reference to a given
21 // object is retained. RendererDataMemoizingStore watches for render process
22 // termination and releases objects that are no longer associated with any
23 // render process.
24 //
25 // TODO(jcampan): Rather than watching for render process termination, we should
26 //                instead be listening to events such as resource cached/
27 //                removed from cache, and remove the items when we know they
28 //                are not used anymore.
29 template <typename T>
30 class RendererDataMemoizingStore : public RenderProcessHostObserver {
31  public:
RendererDataMemoizingStore()32   RendererDataMemoizingStore() : next_item_id_(1) {
33   }
34 
~RendererDataMemoizingStore()35   ~RendererDataMemoizingStore() {
36     DCHECK_EQ(0U, id_to_item_.size()) << "Failed to outlive render processes";
37   }
38 
39   // Store adds |item| to this collection, associates it with the given render
40   // process id and returns an opaque identifier for it. If |item| is already
41   // known, the same identifier will be returned.
Store(T * item,int process_id)42   int Store(T* item, int process_id) {
43     DCHECK(item);
44     base::AutoLock auto_lock(lock_);
45 
46     int item_id;
47 
48     // Do we already know this item?
49     typename ReverseItemMap::iterator item_iter = item_to_id_.find(item);
50     if (item_iter == item_to_id_.end()) {
51       item_id = next_item_id_++;
52       // We use 0 as an invalid item_id value.  In the unlikely event that
53       // next_item_id_ wraps around, we reset it to 1.
54       if (next_item_id_ == 0)
55         next_item_id_ = 1;
56       id_to_item_[item_id] = item;
57       item_to_id_[item] = item_id;
58     } else {
59       item_id = item_iter->second;
60     }
61 
62     // Let's update process_id_to_item_id_.
63     std::pair<IDMap::iterator, IDMap::iterator> process_ids =
64         process_id_to_item_id_.equal_range(process_id);
65     bool already_watching_process = (process_ids.first != process_ids.second);
66     if (std::find_if(process_ids.first, process_ids.second,
67                      MatchSecond<int>(item_id)) == process_ids.second) {
68       process_id_to_item_id_.insert(std::make_pair(process_id, item_id));
69     }
70 
71     // And item_id_to_process_id_.
72     std::pair<IDMap::iterator, IDMap::iterator> item_ids =
73         item_id_to_process_id_.equal_range(item_id);
74     if (std::find_if(item_ids.first, item_ids.second,
75                      MatchSecond<int>(process_id)) == item_ids.second) {
76       item_id_to_process_id_.insert(std::make_pair(item_id, process_id));
77     }
78 
79     // If we're not doing so already, keep an eye for the process host deletion.
80     if (!already_watching_process) {
81       if (BrowserThread::CurrentlyOn(BrowserThread::UI)) {
82         StartObservingProcess(process_id);
83       } else {
84         BrowserThread::PostTask(
85             BrowserThread::UI,
86             FROM_HERE,
87             base::Bind(&RendererDataMemoizingStore::StartObservingProcess,
88                        base::Unretained(this),
89                        process_id));
90       }
91     }
92 
93     return item_id;
94   }
95 
96   // Retrieve fetches a previously Stored() item, identified by |item_id|.
97   // If |item_id| is recognized, |item| will be updated and Retrieve() will
98   // return true, it will otherwise return false.
Retrieve(int item_id,scoped_refptr<T> * item)99   bool Retrieve(int item_id, scoped_refptr<T>* item) {
100     base::AutoLock auto_lock(lock_);
101 
102     typename ItemMap::iterator iter = id_to_item_.find(item_id);
103     if (iter == id_to_item_.end())
104       return false;
105     if (item)
106       *item = iter->second;
107     return true;
108   }
109 
110  private:
111   typedef std::multimap<int, int> IDMap;
112   typedef std::map<int, scoped_refptr<T> > ItemMap;
113   typedef std::map<T*, int, typename T::LessThan> ReverseItemMap;
114 
115   template <typename M>
116   struct MatchSecond {
MatchSecondMatchSecond117     explicit MatchSecond(const M& t) : value(t) {}
118 
119     template <typename Pair>
operatorMatchSecond120     bool operator()(const Pair& p) const {
121       return (value == p.second);
122     }
123 
124     M value;
125   };
126 
StartObservingProcess(int process_id)127   void StartObservingProcess(int process_id) {
128     DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
129     RenderProcessHost* host = RenderProcessHost::FromID(process_id);
130     if (!host) {
131       // We lost the race to observe the host before it was destroyed. Since
132       // this function was called because we're managing objects tied to that
133       // (now destroyed) RenderProcessHost, let's clean up.
134       RemoveRenderProcessItems(process_id);
135       return;
136     }
137 
138     host->AddObserver(this);
139   }
140 
141   // Remove the item specified by |item_id| from id_to_item_ and item_to_id_.
142   // NOTE: the caller (RemoveRenderProcessItems) must hold lock_.
RemoveInternal(int item_id)143   void RemoveInternal(int item_id) {
144     typename ItemMap::iterator item_iter = id_to_item_.find(item_id);
145     DCHECK(item_iter != id_to_item_.end());
146 
147     typename ReverseItemMap::iterator id_iter =
148         item_to_id_.find(item_iter->second.get());
149     DCHECK(id_iter != item_to_id_.end());
150     item_to_id_.erase(id_iter);
151 
152     id_to_item_.erase(item_iter);
153   }
154 
RenderProcessHostDestroyed(RenderProcessHost * host)155   void RenderProcessHostDestroyed(RenderProcessHost* host) {
156     DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
157     RemoveRenderProcessItems(host->GetID());
158   }
159 
160   // Removes all the items associated with the specified process from the store.
RemoveRenderProcessItems(int process_id)161   void RemoveRenderProcessItems(int process_id) {
162     base::AutoLock auto_lock(lock_);
163 
164     // We iterate through all the item ids for that process.
165     std::pair<IDMap::iterator, IDMap::iterator> process_ids =
166         process_id_to_item_id_.equal_range(process_id);
167     for (IDMap::iterator ids_iter = process_ids.first;
168          ids_iter != process_ids.second; ++ids_iter) {
169       int item_id = ids_iter->second;
170       // Find all the processes referring to this item id in
171       // item_id_to_process_id_, then locate the process being removed within
172       // that range.
173       std::pair<IDMap::iterator, IDMap::iterator> item_ids =
174           item_id_to_process_id_.equal_range(item_id);
175       IDMap::iterator proc_iter = std::find_if(
176           item_ids.first, item_ids.second, MatchSecond<int>(process_id));
177       DCHECK(proc_iter != item_ids.second);
178 
179       // Before removing, determine if no other processes refer to the current
180       // item id. If |proc_iter| (the current process) is the lower bound of
181       // processes containing the current item id and if |next_proc_iter| is the
182       // upper bound (the first process that does not), then only one process,
183       // the one being removed, refers to the item id.
184       IDMap::iterator next_proc_iter = proc_iter;
185       ++next_proc_iter;
186       bool last_process_for_item_id =
187           (proc_iter == item_ids.first && next_proc_iter == item_ids.second);
188       item_id_to_process_id_.erase(proc_iter);
189 
190       if (last_process_for_item_id) {
191         // The current item id is not referenced by any other processes, so
192         // remove it from id_to_item_ and item_to_id_.
193         RemoveInternal(item_id);
194       }
195     }
196     if (process_ids.first != process_ids.second)
197       process_id_to_item_id_.erase(process_ids.first, process_ids.second);
198   }
199 
200   IDMap process_id_to_item_id_;
201   IDMap item_id_to_process_id_;
202   ItemMap id_to_item_;
203   ReverseItemMap item_to_id_;
204 
205   int next_item_id_;
206 
207   // This lock protects: process_id_to_item_id_, item_id_to_process_id_,
208   //                     id_to_item_, and item_to_id_.
209   base::Lock lock_;
210 };
211 
212 }  // namespace content
213 
214 #endif  // CONTENT_BROWSER_RENDERER_DATA_MEMOIZING_STORE_H_
215