Bug 496271, automation config for Tb2.0.0.22 build1, p=joduinn, r=me
[mozilla-1.9.git] / xpcom / base / nsMemoryImpl.cpp
blob7c009bc311e825259dd78bf83ce077d37071f1cf
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 if (size > PR_INT32_MAX)
282 return nsnull;
284 void* result = MALLOC1(size);
285 if (! result) {
286 // Request an asynchronous flush
287 sGlobalMemory.FlushMemory(NS_LITERAL_STRING("alloc-failure").get(), PR_FALSE);
289 return result;
292 XPCOM_API(void*)
293 NS_Realloc(void* ptr, PRSize size)
295 if (size > PR_INT32_MAX)
296 return nsnull;
298 void* result = REALLOC1(ptr, size);
299 if (! result && size != 0) {
300 // Request an asynchronous flush
301 sGlobalMemory.FlushMemory(NS_LITERAL_STRING("alloc-failure").get(), PR_FALSE);
303 return result;
306 XPCOM_API(void)
307 NS_Free(void* ptr)
309 PR_Free(ptr);
312 #ifdef NS_MEMORY_FLUSHER
314 NS_IMPL_QUERY_INTERFACE1(MemoryFlusher, nsITimerCallback)
316 NS_IMETHODIMP
317 MemoryFlusher::Notify(nsITimer *timer)
319 PRBool isLowMemory;
320 sGlobalMemory.IsLowMemory(&isLowMemory);
322 #ifdef NS_TEST_MEMORY_FLUSHER
323 // Fire the flusher *every* time
324 isLowMemory = PR_TRUE;
325 #endif
327 if (isLowMemory)
328 sGlobalMemory.FlushMemory(NS_LITERAL_STRING("low-memory").get(),
329 PR_FALSE);
330 return NS_OK;
333 nsresult
334 MemoryFlusher::Init()
336 nsCOMPtr<nsITimer> timer = do_CreateInstance(NS_TIMER_CONTRACTID);
337 NS_ENSURE_STATE(timer);
339 // There is no need to keep a reference to the timer object because we
340 // don't need to kill the timer. It will be killed automatically when
341 // XPCOM is shutdown.
343 return timer->InitWithCallback(this, kTimeout,
344 nsITimer::TYPE_REPEATING_SLACK);
347 #endif // NS_MEMORY_FLUSHER
349 nsresult
350 NS_GetMemoryManager(nsIMemory* *result)
352 return sGlobalMemory.QueryInterface(NS_GET_IID(nsIMemory), (void**) result);