Bug 449474, Fx3.0.2 updates should force modules/distribution.js, and use the version...
[mozilla-1.9.git] / xpcom / base / nsMemoryImpl.cpp
blob8a838bc2cdb310665217edcfe25d5ed348782e35
1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2 /* ***** BEGIN LICENSE BLOCK *****
3 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
5 * The contents of this file are subject to the Mozilla Public License Version
6 * 1.1 (the "License"); you may not use this file except in compliance with
7 * the License. You may obtain a copy of the License at
8 * http://www.mozilla.org/MPL/
10 * Software distributed under the License is distributed on an "AS IS" basis,
11 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
12 * for the specific language governing rights and limitations under the
13 * License.
15 * The Original Code is mozilla.org code.
17 * The Initial Developer of the Original Code is
18 * Netscape Communications Corporation.
19 * Portions created by the Initial Developer are Copyright (C) 1998
20 * the Initial Developer. All Rights Reserved.
22 * Contributor(s):
24 * Alternatively, the contents of this file may be used under the terms of
25 * either of the GNU General Public License Version 2 or later (the "GPL"),
26 * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
27 * in which case the provisions of the GPL or the LGPL are applicable instead
28 * of those above. If you wish to allow use of your version of this file only
29 * under the terms of either the GPL or the LGPL, and not to allow others to
30 * use your version of this file under the terms of the MPL, indicate your
31 * decision by deleting the provisions above and replace them with the notice
32 * and other provisions required by the GPL or the LGPL. If you do not delete
33 * the provisions above, a recipient may use your version of this file under
34 * the terms of any one of the MPL, the GPL or the LGPL.
36 * ***** END LICENSE BLOCK ***** */
38 #include "nsXPCOM.h"
39 #include "nsMemoryImpl.h"
40 #include "nsThreadUtils.h"
42 #include "nsIObserverService.h"
43 #include "nsIServiceManager.h"
44 #include "nsISupportsArray.h"
46 #include "prmem.h"
47 #include "prcvar.h"
48 #include "pratom.h"
50 #include "nsAlgorithm.h"
51 #include "nsAutoLock.h"
52 #include "nsCOMPtr.h"
53 #include "nsString.h"
55 #if defined(XP_WIN)
56 #include <windows.h>
57 #define NS_MEMORY_FLUSHER
58 #else
59 // Need to implement the nsIMemory::IsLowMemory() predicate
60 #undef NS_MEMORY_FLUSHER
61 #endif
63 #ifdef NS_MEMORY_FLUSHER
64 #include "nsITimer.h"
65 #endif
67 ////////////////////////////////////////////////////////////////////////////////
68 // Define NS_OUT_OF_MEMORY_TESTER if you want to force memory failures
70 #ifdef DEBUG_xwarren
71 #define NS_OUT_OF_MEMORY_TESTER
72 #endif
74 #ifdef NS_OUT_OF_MEMORY_TESTER
76 // flush memory one in this number of times:
77 #define NS_FLUSH_FREQUENCY 100000
79 // fail allocation one in this number of flushes:
80 #define NS_FAIL_FREQUENCY 10
82 PRUint32 gFlushFreq = 0;
83 PRUint32 gFailFreq = 0;
85 static void*
86 mallocator(PRSize size, PRUint32& counter, PRUint32 max)
88 if (counter++ >= max) {
89 counter = 0;
90 NS_ASSERTION(0, "about to fail allocation... watch out");
91 return nsnull;
93 return PR_Malloc(size);
96 static void*
97 reallocator(void* ptr, PRSize size, PRUint32& counter, PRUint32 max)
99 if (counter++ >= max) {
100 counter = 0;
101 NS_ASSERTION(0, "about to fail reallocation... watch out");
102 return nsnull;
104 return PR_Realloc(ptr, size);
107 #define MALLOC1(s) mallocator(s, gFlushFreq, NS_FLUSH_FREQUENCY)
108 #define REALLOC1(p, s) reallocator(p, s, gFlushFreq, NS_FLUSH_FREQUENCY)
110 #else
112 #define MALLOC1(s) PR_Malloc(s)
113 #define REALLOC1(p, s) PR_Realloc(p, s)
115 #endif // NS_OUT_OF_MEMORY_TESTER
117 #if defined(XDEBUG_waterson)
118 #define NS_TEST_MEMORY_FLUSHER
119 #endif
121 #ifdef NS_MEMORY_FLUSHER
123 * A class that is used to periodically check the status of the system,
124 * determine if too much memory is in use, and if so, trigger a "memory flush".
126 class MemoryFlusher : public nsITimerCallback
128 public:
129 // We don't use the generic macros because we are a special static object
130 NS_IMETHOD QueryInterface(REFNSIID aIID, void** aResult);
131 NS_IMETHOD_(nsrefcnt) AddRef(void) { return 2; }
132 NS_IMETHOD_(nsrefcnt) Release(void) { return 1; }
134 NS_DECL_NSITIMERCALLBACK
136 nsresult Init();
137 void StopAndJoin();
139 private:
140 static PRIntervalTime sTimeout;
141 static PRLock* sLock;
142 static PRCondVar* sCVar;
144 enum {
145 kTimeout = 60000 // milliseconds
149 static MemoryFlusher sGlobalMemoryFlusher;
151 #endif // NS_MEMORY_FLUSHER
153 static nsMemoryImpl sGlobalMemory;
155 NS_IMPL_QUERY_INTERFACE1(nsMemoryImpl, nsIMemory)
157 NS_IMETHODIMP_(void*)
158 nsMemoryImpl::Alloc(PRSize size)
160 return NS_Alloc(size);
163 NS_IMETHODIMP_(void*)
164 nsMemoryImpl::Realloc(void* ptr, PRSize size)
166 return NS_Realloc(ptr, size);
169 NS_IMETHODIMP_(void)
170 nsMemoryImpl::Free(void* ptr)
172 NS_Free(ptr);
175 NS_IMETHODIMP
176 nsMemoryImpl::HeapMinimize(PRBool aImmediate)
178 return FlushMemory(NS_LITERAL_STRING("heap-minimize").get(), aImmediate);
181 NS_IMETHODIMP
182 nsMemoryImpl::IsLowMemory(PRBool *result)
184 #if defined(WINCE)
185 MEMORYSTATUS stat;
186 GlobalMemoryStatus(&stat);
187 *result = ((float)stat.dwAvailPhys / stat.dwTotalPhys) < 0.1;
188 #elif defined(XP_WIN)
189 MEMORYSTATUS stat;
190 GlobalMemoryStatus(&stat);
191 *result = ((float)stat.dwAvailPageFile / stat.dwTotalPageFile) < 0.1;
192 #else
193 *result = PR_FALSE;
194 #endif
195 return NS_OK;
199 /*static*/ nsresult
200 nsMemoryImpl::InitFlusher()
202 #ifdef NS_MEMORY_FLUSHER
203 return sGlobalMemoryFlusher.Init();
204 #else
205 return NS_OK;
206 #endif
209 /*static*/ nsresult
210 nsMemoryImpl::Create(nsISupports* outer, const nsIID& aIID, void **aResult)
212 NS_ENSURE_NO_AGGREGATION(outer);
213 return sGlobalMemory.QueryInterface(aIID, aResult);
216 nsresult
217 nsMemoryImpl::FlushMemory(const PRUnichar* aReason, PRBool aImmediate)
219 nsresult rv;
221 if (aImmediate) {
222 // They've asked us to run the flusher *immediately*. We've
223 // got to be on the UI main thread for us to be able to do
224 // that...are we?
225 if (!NS_IsMainThread()) {
226 NS_ERROR("can't synchronously flush memory: not on UI thread");
227 return NS_ERROR_FAILURE;
231 PRInt32 lastVal = PR_AtomicSet(&sIsFlushing, 1);
232 if (lastVal)
233 return NS_OK;
235 // Run the flushers immediately if we can; otherwise, proxy to the
236 // UI thread an run 'em asynchronously.
237 if (aImmediate) {
238 rv = RunFlushers(aReason);
240 else {
241 sFlushEvent.mReason = aReason;
242 rv = NS_DispatchToMainThread(&sFlushEvent, NS_DISPATCH_NORMAL);
245 return rv;
248 nsresult
249 nsMemoryImpl::RunFlushers(const PRUnichar* aReason)
251 nsCOMPtr<nsIObserverService> os = do_GetService("@mozilla.org/observer-service;1");
252 if (os) {
253 os->NotifyObservers(this, "memory-pressure", aReason);
256 sIsFlushing = 0;
257 return NS_OK;
260 // XXX need NS_IMPL_STATIC_ADDREF/RELEASE
261 NS_IMETHODIMP_(nsrefcnt) nsMemoryImpl::FlushEvent::AddRef() { return 2; }
262 NS_IMETHODIMP_(nsrefcnt) nsMemoryImpl::FlushEvent::Release() { return 1; }
263 NS_IMPL_QUERY_INTERFACE1(nsMemoryImpl::FlushEvent, nsIRunnable)
265 NS_IMETHODIMP
266 nsMemoryImpl::FlushEvent::Run()
268 sGlobalMemory.RunFlushers(mReason);
269 return NS_OK;
272 PRInt32
273 nsMemoryImpl::sIsFlushing = 0;
275 nsMemoryImpl::FlushEvent
276 nsMemoryImpl::sFlushEvent;
278 XPCOM_API(void*)
279 NS_Alloc(PRSize size)
281 void* result = MALLOC1(size);
282 if (! result) {
283 // Request an asynchronous flush
284 sGlobalMemory.FlushMemory(NS_LITERAL_STRING("alloc-failure").get(), PR_FALSE);
286 return result;
289 XPCOM_API(void*)
290 NS_Realloc(void* ptr, PRSize size)
292 void* result = REALLOC1(ptr, size);
293 if (! result && size != 0) {
294 // Request an asynchronous flush
295 sGlobalMemory.FlushMemory(NS_LITERAL_STRING("alloc-failure").get(), PR_FALSE);
297 return result;
300 XPCOM_API(void)
301 NS_Free(void* ptr)
303 PR_Free(ptr);
306 #ifdef NS_MEMORY_FLUSHER
308 NS_IMPL_QUERY_INTERFACE1(MemoryFlusher, nsITimerCallback)
310 NS_IMETHODIMP
311 MemoryFlusher::Notify(nsITimer *timer)
313 PRBool isLowMemory;
314 sGlobalMemory.IsLowMemory(&isLowMemory);
316 #ifdef NS_TEST_MEMORY_FLUSHER
317 // Fire the flusher *every* time
318 isLowMemory = PR_TRUE;
319 #endif
321 if (isLowMemory)
322 sGlobalMemory.FlushMemory(NS_LITERAL_STRING("low-memory").get(),
323 PR_FALSE);
324 return NS_OK;
327 nsresult
328 MemoryFlusher::Init()
330 nsCOMPtr<nsITimer> timer = do_CreateInstance(NS_TIMER_CONTRACTID);
331 NS_ENSURE_STATE(timer);
333 // There is no need to keep a reference to the timer object because we
334 // don't need to kill the timer. It will be killed automatically when
335 // XPCOM is shutdown.
337 return timer->InitWithCallback(this, kTimeout,
338 nsITimer::TYPE_REPEATING_SLACK);
341 #endif // NS_MEMORY_FLUSHER
343 nsresult
344 NS_GetMemoryManager(nsIMemory* *result)
346 return sGlobalMemory.QueryInterface(NS_GET_IID(nsIMemory), (void**) result);