On x86 compilers without fastcall, simulate it when invoking traces and un-simulate...
[wine-gecko.git] / xpcom / base / nsMemoryImpl.cpp
blob1038a160660d03a0feaaeb27d65e962beda2d319
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 #elif defined (NS_OSSO)
59 #include <osso-mem.h>
60 #else
61 // Need to implement the nsIMemory::IsLowMemory() predicate
62 #undef NS_MEMORY_FLUSHER
63 #endif
65 #ifdef NS_MEMORY_FLUSHER
66 #include "nsITimer.h"
67 #endif
69 ////////////////////////////////////////////////////////////////////////////////
70 // Define NS_OUT_OF_MEMORY_TESTER if you want to force memory failures
72 #ifdef DEBUG_xwarren
73 #define NS_OUT_OF_MEMORY_TESTER
74 #endif
76 #ifdef NS_OUT_OF_MEMORY_TESTER
78 // flush memory one in this number of times:
79 #define NS_FLUSH_FREQUENCY 100000
81 // fail allocation one in this number of flushes:
82 #define NS_FAIL_FREQUENCY 10
84 PRUint32 gFlushFreq = 0;
85 PRUint32 gFailFreq = 0;
87 static void*
88 mallocator(PRSize size, PRUint32& counter, PRUint32 max)
90 if (counter++ >= max) {
91 counter = 0;
92 NS_ASSERTION(0, "about to fail allocation... watch out");
93 return nsnull;
95 return PR_Malloc(size);
98 static void*
99 reallocator(void* ptr, PRSize size, PRUint32& counter, PRUint32 max)
101 if (counter++ >= max) {
102 counter = 0;
103 NS_ASSERTION(0, "about to fail reallocation... watch out");
104 return nsnull;
106 return PR_Realloc(ptr, size);
109 #define MALLOC1(s) mallocator(s, gFlushFreq, NS_FLUSH_FREQUENCY)
110 #define REALLOC1(p, s) reallocator(p, s, gFlushFreq, NS_FLUSH_FREQUENCY)
112 #else
114 #define MALLOC1(s) PR_Malloc(s)
115 #define REALLOC1(p, s) PR_Realloc(p, s)
117 #endif // NS_OUT_OF_MEMORY_TESTER
119 #if defined(XDEBUG_waterson)
120 #define NS_TEST_MEMORY_FLUSHER
121 #endif
123 #ifdef NS_MEMORY_FLUSHER
125 * A class that is used to periodically check the status of the system,
126 * determine if too much memory is in use, and if so, trigger a "memory flush".
128 class MemoryFlusher : public nsITimerCallback
130 public:
131 // We don't use the generic macros because we are a special static object
132 NS_IMETHOD QueryInterface(REFNSIID aIID, void** aResult);
133 NS_IMETHOD_(nsrefcnt) AddRef(void) { return 2; }
134 NS_IMETHOD_(nsrefcnt) Release(void) { return 1; }
136 NS_DECL_NSITIMERCALLBACK
138 nsresult Init();
139 void StopAndJoin();
141 private:
142 static PRIntervalTime sTimeout;
143 static PRLock* sLock;
144 static PRCondVar* sCVar;
146 enum {
147 kTimeout = 60000 // milliseconds
151 static MemoryFlusher sGlobalMemoryFlusher;
153 #endif // NS_MEMORY_FLUSHER
155 static nsMemoryImpl sGlobalMemory;
157 NS_IMPL_QUERY_INTERFACE1(nsMemoryImpl, nsIMemory)
159 NS_IMETHODIMP_(void*)
160 nsMemoryImpl::Alloc(PRSize size)
162 return NS_Alloc(size);
165 NS_IMETHODIMP_(void*)
166 nsMemoryImpl::Realloc(void* ptr, PRSize size)
168 return NS_Realloc(ptr, size);
171 NS_IMETHODIMP_(void)
172 nsMemoryImpl::Free(void* ptr)
174 NS_Free(ptr);
177 NS_IMETHODIMP
178 nsMemoryImpl::HeapMinimize(PRBool aImmediate)
180 return FlushMemory(NS_LITERAL_STRING("heap-minimize").get(), aImmediate);
183 NS_IMETHODIMP
184 nsMemoryImpl::IsLowMemory(PRBool *result)
186 #if defined(WINCE)
187 MEMORYSTATUS stat;
188 GlobalMemoryStatus(&stat);
189 *result = ((float)stat.dwAvailPhys / stat.dwTotalPhys) < 0.1;
190 #elif defined(XP_WIN)
191 MEMORYSTATUS stat;
192 GlobalMemoryStatus(&stat);
193 *result = ((float)stat.dwAvailPageFile / stat.dwTotalPageFile) < 0.1;
194 #elif defined(NS_OSSO)
195 osso_mem_usage_t usage;
196 osso_mem_get_usage(&usage);
198 // According to the docs, low memory limit isn't set if it is
199 // zero, or if it is greater than 100%.
200 if (usage.low == 0 || usage.low > usage.total)
201 *result = PR_FALSE;
202 else
203 *result = (PRBool) usage.low <= usage.used;
204 #else
205 *result = PR_FALSE;
206 #endif
207 return NS_OK;
211 /*static*/ nsresult
212 nsMemoryImpl::InitFlusher()
214 #ifdef NS_MEMORY_FLUSHER
215 return sGlobalMemoryFlusher.Init();
216 #else
217 return NS_OK;
218 #endif
221 /*static*/ nsresult
222 nsMemoryImpl::Create(nsISupports* outer, const nsIID& aIID, void **aResult)
224 NS_ENSURE_NO_AGGREGATION(outer);
225 return sGlobalMemory.QueryInterface(aIID, aResult);
228 nsresult
229 nsMemoryImpl::FlushMemory(const PRUnichar* aReason, PRBool aImmediate)
231 nsresult rv;
233 if (aImmediate) {
234 // They've asked us to run the flusher *immediately*. We've
235 // got to be on the UI main thread for us to be able to do
236 // that...are we?
237 if (!NS_IsMainThread()) {
238 NS_ERROR("can't synchronously flush memory: not on UI thread");
239 return NS_ERROR_FAILURE;
243 PRInt32 lastVal = PR_AtomicSet(&sIsFlushing, 1);
244 if (lastVal)
245 return NS_OK;
247 // Run the flushers immediately if we can; otherwise, proxy to the
248 // UI thread an run 'em asynchronously.
249 if (aImmediate) {
250 rv = RunFlushers(aReason);
252 else {
253 sFlushEvent.mReason = aReason;
254 rv = NS_DispatchToMainThread(&sFlushEvent, NS_DISPATCH_NORMAL);
257 return rv;
260 nsresult
261 nsMemoryImpl::RunFlushers(const PRUnichar* aReason)
263 nsCOMPtr<nsIObserverService> os = do_GetService("@mozilla.org/observer-service;1");
264 if (os) {
265 os->NotifyObservers(this, "memory-pressure", aReason);
268 sIsFlushing = 0;
269 return NS_OK;
272 // XXX need NS_IMPL_STATIC_ADDREF/RELEASE
273 NS_IMETHODIMP_(nsrefcnt) nsMemoryImpl::FlushEvent::AddRef() { return 2; }
274 NS_IMETHODIMP_(nsrefcnt) nsMemoryImpl::FlushEvent::Release() { return 1; }
275 NS_IMPL_QUERY_INTERFACE1(nsMemoryImpl::FlushEvent, nsIRunnable)
277 NS_IMETHODIMP
278 nsMemoryImpl::FlushEvent::Run()
280 sGlobalMemory.RunFlushers(mReason);
281 return NS_OK;
284 PRInt32
285 nsMemoryImpl::sIsFlushing = 0;
287 nsMemoryImpl::FlushEvent
288 nsMemoryImpl::sFlushEvent;
290 XPCOM_API(void*)
291 NS_Alloc(PRSize size)
293 void* result = MALLOC1(size);
294 if (! result) {
295 // Request an asynchronous flush
296 sGlobalMemory.FlushMemory(NS_LITERAL_STRING("alloc-failure").get(), PR_FALSE);
298 return result;
301 XPCOM_API(void*)
302 NS_Realloc(void* ptr, PRSize size)
304 void* result = REALLOC1(ptr, size);
305 if (! result && size != 0) {
306 // Request an asynchronous flush
307 sGlobalMemory.FlushMemory(NS_LITERAL_STRING("alloc-failure").get(), PR_FALSE);
309 return result;
312 XPCOM_API(void)
313 NS_Free(void* ptr)
315 PR_Free(ptr);
318 #ifdef NS_MEMORY_FLUSHER
320 NS_IMPL_QUERY_INTERFACE1(MemoryFlusher, nsITimerCallback)
322 NS_IMETHODIMP
323 MemoryFlusher::Notify(nsITimer *timer)
325 PRBool isLowMemory;
326 sGlobalMemory.IsLowMemory(&isLowMemory);
328 #ifdef NS_TEST_MEMORY_FLUSHER
329 // Fire the flusher *every* time
330 isLowMemory = PR_TRUE;
331 #endif
333 if (isLowMemory)
334 sGlobalMemory.FlushMemory(NS_LITERAL_STRING("low-memory").get(),
335 PR_FALSE);
336 return NS_OK;
339 nsresult
340 MemoryFlusher::Init()
342 nsCOMPtr<nsITimer> timer = do_CreateInstance(NS_TIMER_CONTRACTID);
343 NS_ENSURE_STATE(timer);
345 // There is no need to keep a reference to the timer object because we
346 // don't need to kill the timer. It will be killed automatically when
347 // XPCOM is shutdown.
349 return timer->InitWithCallback(this, kTimeout,
350 nsITimer::TYPE_REPEATING_SLACK);
353 #endif // NS_MEMORY_FLUSHER
355 nsresult
356 NS_GetMemoryManager(nsIMemory* *result)
358 return sGlobalMemory.QueryInterface(NS_GET_IID(nsIMemory), (void**) result);