1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4  * License, v. 2.0. If a copy of the MPL was not distributed with this file,
5  * You can obtain one at http://mozilla.org/MPL/2.0/. */
6 
7 /* This Source Code Form is subject to the terms of the Mozilla Public
8  * License, v. 2.0. If a copy of the MPL was not distributed with this file,
9  * You can obtain one at http://mozilla.org/MPL/2.0/. */
10 
11 // Original code by: ekr@rtfm.com
12 
13 // Implementation of the NR timer interface
14 
15 // Some code here copied from nrappkit. The license was.
16 
17 /**
18    Copyright (C) 2004, Network Resonance, Inc.
19    Copyright (C) 2006, Network Resonance, Inc.
20    All Rights Reserved
21 
22    Redistribution and use in source and binary forms, with or without
23    modification, are permitted provided that the following conditions
24    are met:
25 
26    1. Redistributions of source code must retain the above copyright
27       notice, this list of conditions and the following disclaimer.
28    2. Redistributions in binary form must reproduce the above copyright
29       notice, this list of conditions and the following disclaimer in the
30       documentation and/or other materials provided with the distribution.
31    3. Neither the name of Network Resonance, Inc. nor the name of any
32       contributors to this software may be used to endorse or promote
33       products derived from this software without specific prior written
34       permission.
35 
36    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS''
37    AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
38    IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
39    ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
40    LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
41    CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
42    SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
43    INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
44    CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
45    ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
46    POSSIBILITY OF SUCH DAMAGE.
47 
48 
49    ekr@rtfm.com  Sun Feb 22 19:35:24 2004
50  */
51 
52 #include <string>
53 
54 #include "nsCOMPtr.h"
55 #include "nsComponentManagerUtils.h"
56 #include "nsServiceManagerUtils.h"
57 #include "nsIEventTarget.h"
58 #include "nsINamed.h"
59 #include "nsITimer.h"
60 #include "nsNetCID.h"
61 #include "runnable_utils.h"
62 #include "mozilla/DebugOnly.h"
63 #include "mozilla/UniquePtr.h"
64 
65 extern "C" {
66 #include "nr_api.h"
67 #include "async_timer.h"
68 }
69 
70 namespace mozilla {
71 
72 class nrappkitCallback {
73  public:
nrappkitCallback(NR_async_cb cb,void * cb_arg,const char * function,int line)74   nrappkitCallback(NR_async_cb cb, void* cb_arg, const char* function, int line)
75       : cb_(cb), cb_arg_(cb_arg), function_(function), line_(line) {}
76   virtual ~nrappkitCallback() = default;
77 
78   virtual void Cancel() = 0;
79 
80  protected:
81   /* additional members */
82   NR_async_cb cb_;
83   void* cb_arg_;
84   std::string function_;
85   int line_;
86 };
87 
88 class nrappkitTimerCallback : public nrappkitCallback,
89                               public nsITimerCallback,
90                               public nsINamed {
91  public:
92   // We're going to release ourself in the callback, so we need to be threadsafe
93   NS_DECL_THREADSAFE_ISUPPORTS
94   NS_DECL_NSITIMERCALLBACK
95 
nrappkitTimerCallback(NR_async_cb cb,void * cb_arg,const char * function,int line)96   nrappkitTimerCallback(NR_async_cb cb, void* cb_arg, const char* function,
97                         int line)
98       : nrappkitCallback(cb, cb_arg, function, line), timer_(nullptr) {}
99 
SetTimer(already_AddRefed<nsITimer> && timer)100   void SetTimer(already_AddRefed<nsITimer>&& timer) { timer_ = timer; }
101 
Cancel()102   virtual void Cancel() override {
103     AddRef();  // Cancelling the timer causes the callback it holds to
104                // be released. AddRef() keeps us alive.
105     timer_->Cancel();
106     timer_ = nullptr;
107     Release();  // Will cause deletion of this object.
108   }
109 
110   NS_IMETHOD
GetName(nsACString & aName)111   GetName(nsACString& aName) override {
112     aName.AssignLiteral("nrappkitTimerCallback");
113     return NS_OK;
114   }
115 
116  private:
117   nsCOMPtr<nsITimer> timer_;
118   virtual ~nrappkitTimerCallback() = default;
119 };
120 
NS_IMPL_ISUPPORTS(nrappkitTimerCallback,nsITimerCallback,nsINamed)121 NS_IMPL_ISUPPORTS(nrappkitTimerCallback, nsITimerCallback, nsINamed)
122 
123 NS_IMETHODIMP nrappkitTimerCallback::Notify(nsITimer* timer) {
124   r_log(LOG_GENERIC, LOG_DEBUG, "Timer callback fired (set in %s:%d)",
125         function_.c_str(), line_);
126   MOZ_RELEASE_ASSERT(timer == timer_);
127   cb_(nullptr, 0, cb_arg_);
128 
129   // Allow the timer to go away.
130   timer_ = nullptr;
131   return NS_OK;
132 }
133 
134 class nrappkitScheduledCallback : public nrappkitCallback {
135  public:
nrappkitScheduledCallback(NR_async_cb cb,void * cb_arg,const char * function,int line)136   nrappkitScheduledCallback(NR_async_cb cb, void* cb_arg, const char* function,
137                             int line)
138       : nrappkitCallback(cb, cb_arg, function, line) {}
139 
Run()140   void Run() {
141     if (cb_) {
142       cb_(nullptr, 0, cb_arg_);
143     }
144   }
145 
Cancel()146   virtual void Cancel() override { cb_ = nullptr; }
147 
148   ~nrappkitScheduledCallback() = default;
149 };
150 
151 }  // namespace mozilla
152 
153 using namespace mozilla;
154 
GetSTSThread()155 static nsCOMPtr<nsIEventTarget> GetSTSThread() {
156   nsresult rv;
157 
158   nsCOMPtr<nsIEventTarget> sts_thread;
159 
160   sts_thread = do_GetService(NS_SOCKETTRANSPORTSERVICE_CONTRACTID, &rv);
161   MOZ_ASSERT(NS_SUCCEEDED(rv));
162 
163   return sts_thread;
164 }
165 
166 // These timers must only be used from the STS thread.
167 // This function is a helper that enforces that.
CheckSTSThread()168 static void CheckSTSThread() {
169   DebugOnly<nsCOMPtr<nsIEventTarget>> sts_thread = GetSTSThread();
170 
171   ASSERT_ON_THREAD(sts_thread.value);
172 }
173 
nr_async_timer_set_zero(NR_async_cb cb,void * arg,char * func,int l,nrappkitCallback ** handle)174 static int nr_async_timer_set_zero(NR_async_cb cb, void* arg, char* func, int l,
175                                    nrappkitCallback** handle) {
176   nrappkitScheduledCallback* callback(
177       new nrappkitScheduledCallback(cb, arg, func, l));
178 
179   nsresult rv = GetSTSThread()->Dispatch(
180       WrapRunnable(UniquePtr<nrappkitScheduledCallback>(callback),
181                    &nrappkitScheduledCallback::Run),
182       NS_DISPATCH_NORMAL);
183   if (NS_FAILED(rv)) return R_FAILED;
184 
185   *handle = callback;
186 
187   // On exit to this function, the only strong reference to callback is in
188   // the Runnable. Because we are redispatching to the same thread,
189   // this is always safe.
190   return 0;
191 }
192 
nr_async_timer_set_nonzero(int timeout,NR_async_cb cb,void * arg,char * func,int l,nrappkitCallback ** handle)193 static int nr_async_timer_set_nonzero(int timeout, NR_async_cb cb, void* arg,
194                                       char* func, int l,
195                                       nrappkitCallback** handle) {
196   nsresult rv;
197   CheckSTSThread();
198 
199   nrappkitTimerCallback* callback = new nrappkitTimerCallback(cb, arg, func, l);
200 
201   nsCOMPtr<nsITimer> timer;
202   rv = NS_NewTimerWithCallback(getter_AddRefs(timer), callback, timeout,
203                                nsITimer::TYPE_ONE_SHOT);
204   if (NS_FAILED(rv)) {
205     return R_FAILED;
206   }
207 
208   // Move the ownership of the timer to the callback object, which holds the
209   // timer alive per spec.
210   callback->SetTimer(timer.forget());
211 
212   *handle = callback;
213 
214   return 0;
215 }
216 
NR_async_timer_set(int timeout,NR_async_cb cb,void * arg,char * func,int l,void ** handle)217 int NR_async_timer_set(int timeout, NR_async_cb cb, void* arg, char* func,
218                        int l, void** handle) {
219   CheckSTSThread();
220 
221   nrappkitCallback* callback;
222   int r;
223 
224   if (!timeout) {
225     r = nr_async_timer_set_zero(cb, arg, func, l, &callback);
226   } else {
227     r = nr_async_timer_set_nonzero(timeout, cb, arg, func, l, &callback);
228   }
229 
230   if (r) return r;
231 
232   if (handle) *handle = callback;
233 
234   return 0;
235 }
236 
NR_async_schedule(NR_async_cb cb,void * arg,char * func,int l)237 int NR_async_schedule(NR_async_cb cb, void* arg, char* func, int l) {
238   // No need to check the thread because we check it next in the
239   // timer set.
240   return NR_async_timer_set(0, cb, arg, func, l, nullptr);
241 }
242 
NR_async_timer_cancel(void * handle)243 int NR_async_timer_cancel(void* handle) {
244   // Check for the handle being nonzero because sometimes we get
245   // no-op cancels that aren't on the STS thread. This can be
246   // non-racy as long as the upper-level code is careful.
247   if (!handle) return 0;
248 
249   CheckSTSThread();
250 
251   nrappkitCallback* callback = static_cast<nrappkitCallback*>(handle);
252   callback->Cancel();
253 
254   return 0;
255 }
256