Backout 30bfb150da06 (bug 449315) due to unit test timeouts.
[wine-gecko.git] / xpcom / base / nsMemoryImpl.cpp
blob559706ebd3bbe10da623ce3d8e91d95fd7de14b3
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 #include <fcntl.h>
61 #include <unistd.h>
62 const char* kHighMark = "/sys/kernel/high_watermark";
63 #else
64 // Need to implement the nsIMemory::IsLowMemory() predicate
65 #undef NS_MEMORY_FLUSHER
66 #endif
68 #ifdef NS_MEMORY_FLUSHER
69 #include "nsITimer.h"
70 #endif
72 ////////////////////////////////////////////////////////////////////////////////
73 // Define NS_OUT_OF_MEMORY_TESTER if you want to force memory failures
75 #ifdef DEBUG_xwarren
76 #define NS_OUT_OF_MEMORY_TESTER
77 #endif
79 #ifdef NS_OUT_OF_MEMORY_TESTER
81 // flush memory one in this number of times:
82 #define NS_FLUSH_FREQUENCY 100000
84 // fail allocation one in this number of flushes:
85 #define NS_FAIL_FREQUENCY 10
87 PRUint32 gFlushFreq = 0;
88 PRUint32 gFailFreq = 0;
90 static void*
91 mallocator(PRSize size, PRUint32& counter, PRUint32 max)
93 if (counter++ >= max) {
94 counter = 0;
95 NS_ASSERTION(0, "about to fail allocation... watch out");
96 return nsnull;
98 return PR_Malloc(size);
101 static void*
102 reallocator(void* ptr, PRSize size, PRUint32& counter, PRUint32 max)
104 if (counter++ >= max) {
105 counter = 0;
106 NS_ASSERTION(0, "about to fail reallocation... watch out");
107 return nsnull;
109 return PR_Realloc(ptr, size);
112 #define MALLOC1(s) mallocator(s, gFlushFreq, NS_FLUSH_FREQUENCY)
113 #define REALLOC1(p, s) reallocator(p, s, gFlushFreq, NS_FLUSH_FREQUENCY)
115 #else
117 #define MALLOC1(s) PR_Malloc(s)
118 #define REALLOC1(p, s) PR_Realloc(p, s)
120 #endif // NS_OUT_OF_MEMORY_TESTER
122 #if defined(XDEBUG_waterson)
123 #define NS_TEST_MEMORY_FLUSHER
124 #endif
126 #ifdef NS_MEMORY_FLUSHER
128 * A class that is used to periodically check the status of the system,
129 * determine if too much memory is in use, and if so, trigger a "memory flush".
131 class MemoryFlusher : public nsITimerCallback
133 public:
134 // We don't use the generic macros because we are a special static object
135 NS_IMETHOD QueryInterface(REFNSIID aIID, void** aResult);
136 NS_IMETHOD_(nsrefcnt) AddRef(void) { return 2; }
137 NS_IMETHOD_(nsrefcnt) Release(void) { return 1; }
139 NS_DECL_NSITIMERCALLBACK
141 nsresult Init();
142 void StopAndJoin();
144 private:
145 static PRIntervalTime sTimeout;
146 static PRLock* sLock;
147 static PRCondVar* sCVar;
149 enum {
150 kTimeout = 60000 // milliseconds
154 static MemoryFlusher sGlobalMemoryFlusher;
156 #endif // NS_MEMORY_FLUSHER
158 static nsMemoryImpl sGlobalMemory;
160 NS_IMPL_QUERY_INTERFACE1(nsMemoryImpl, nsIMemory)
162 NS_IMETHODIMP_(void*)
163 nsMemoryImpl::Alloc(PRSize size)
165 return NS_Alloc(size);
168 NS_IMETHODIMP_(void*)
169 nsMemoryImpl::Realloc(void* ptr, PRSize size)
171 return NS_Realloc(ptr, size);
174 NS_IMETHODIMP_(void)
175 nsMemoryImpl::Free(void* ptr)
177 NS_Free(ptr);
180 NS_IMETHODIMP
181 nsMemoryImpl::HeapMinimize(PRBool aImmediate)
183 return FlushMemory(NS_LITERAL_STRING("heap-minimize").get(), aImmediate);
186 NS_IMETHODIMP
187 nsMemoryImpl::IsLowMemory(PRBool *result)
189 #if defined(WINCE)
190 MEMORYSTATUS stat;
191 GlobalMemoryStatus(&stat);
192 *result = ((float)stat.dwAvailPhys / stat.dwTotalPhys) < 0.1;
193 #elif defined(XP_WIN)
194 MEMORYSTATUS stat;
195 GlobalMemoryStatus(&stat);
196 *result = ((float)stat.dwAvailPageFile / stat.dwTotalPageFile) < 0.1;
197 #elif defined(NS_OSSO)
198 int fd = open (kHighMark, O_RDONLY);
199 if (fd == -1) {
200 *result = PR_FALSE;
201 return NS_OK;
203 int c = 0;
204 read (fd, &c, 1);
205 close(fd);
206 *result = (c == '1');
207 #else
208 *result = PR_FALSE;
209 #endif
210 return NS_OK;
214 /*static*/ nsresult
215 nsMemoryImpl::InitFlusher()
217 #ifdef NS_MEMORY_FLUSHER
218 return sGlobalMemoryFlusher.Init();
219 #else
220 return NS_OK;
221 #endif
224 /*static*/ nsresult
225 nsMemoryImpl::Create(nsISupports* outer, const nsIID& aIID, void **aResult)
227 NS_ENSURE_NO_AGGREGATION(outer);
228 return sGlobalMemory.QueryInterface(aIID, aResult);
231 nsresult
232 nsMemoryImpl::FlushMemory(const PRUnichar* aReason, PRBool aImmediate)
234 nsresult rv;
236 if (aImmediate) {
237 // They've asked us to run the flusher *immediately*. We've
238 // got to be on the UI main thread for us to be able to do
239 // that...are we?
240 if (!NS_IsMainThread()) {
241 NS_ERROR("can't synchronously flush memory: not on UI thread");
242 return NS_ERROR_FAILURE;
246 PRInt32 lastVal = PR_AtomicSet(&sIsFlushing, 1);
247 if (lastVal)
248 return NS_OK;
250 // Run the flushers immediately if we can; otherwise, proxy to the
251 // UI thread an run 'em asynchronously.
252 if (aImmediate) {
253 rv = RunFlushers(aReason);
255 else {
256 sFlushEvent.mReason = aReason;
257 rv = NS_DispatchToMainThread(&sFlushEvent, NS_DISPATCH_NORMAL);
260 return rv;
263 nsresult
264 nsMemoryImpl::RunFlushers(const PRUnichar* aReason)
266 nsCOMPtr<nsIObserverService> os = do_GetService("@mozilla.org/observer-service;1");
267 if (os) {
268 os->NotifyObservers(this, "memory-pressure", aReason);
271 sIsFlushing = 0;
272 return NS_OK;
275 // XXX need NS_IMPL_STATIC_ADDREF/RELEASE
276 NS_IMETHODIMP_(nsrefcnt) nsMemoryImpl::FlushEvent::AddRef() { return 2; }
277 NS_IMETHODIMP_(nsrefcnt) nsMemoryImpl::FlushEvent::Release() { return 1; }
278 NS_IMPL_QUERY_INTERFACE1(nsMemoryImpl::FlushEvent, nsIRunnable)
280 NS_IMETHODIMP
281 nsMemoryImpl::FlushEvent::Run()
283 sGlobalMemory.RunFlushers(mReason);
284 return NS_OK;
287 PRInt32
288 nsMemoryImpl::sIsFlushing = 0;
290 nsMemoryImpl::FlushEvent
291 nsMemoryImpl::sFlushEvent;
293 XPCOM_API(void*)
294 NS_Alloc(PRSize size)
296 void* result = MALLOC1(size);
297 if (! result) {
298 // Request an asynchronous flush
299 sGlobalMemory.FlushMemory(NS_LITERAL_STRING("alloc-failure").get(), PR_FALSE);
301 return result;
304 XPCOM_API(void*)
305 NS_Realloc(void* ptr, PRSize size)
307 void* result = REALLOC1(ptr, size);
308 if (! result && size != 0) {
309 // Request an asynchronous flush
310 sGlobalMemory.FlushMemory(NS_LITERAL_STRING("alloc-failure").get(), PR_FALSE);
312 return result;
315 XPCOM_API(void)
316 NS_Free(void* ptr)
318 PR_Free(ptr);
321 #ifdef NS_MEMORY_FLUSHER
323 NS_IMPL_QUERY_INTERFACE1(MemoryFlusher, nsITimerCallback)
325 NS_IMETHODIMP
326 MemoryFlusher::Notify(nsITimer *timer)
328 PRBool isLowMemory;
329 sGlobalMemory.IsLowMemory(&isLowMemory);
331 #ifdef NS_TEST_MEMORY_FLUSHER
332 // Fire the flusher *every* time
333 isLowMemory = PR_TRUE;
334 #endif
336 if (isLowMemory)
337 sGlobalMemory.FlushMemory(NS_LITERAL_STRING("low-memory").get(),
338 PR_FALSE);
339 return NS_OK;
342 nsresult
343 MemoryFlusher::Init()
345 nsCOMPtr<nsITimer> timer = do_CreateInstance(NS_TIMER_CONTRACTID);
346 NS_ENSURE_STATE(timer);
348 // There is no need to keep a reference to the timer object because we
349 // don't need to kill the timer. It will be killed automatically when
350 // XPCOM is shutdown.
352 return timer->InitWithCallback(this, kTimeout,
353 nsITimer::TYPE_REPEATING_SLACK);
356 #endif // NS_MEMORY_FLUSHER
358 nsresult
359 NS_GetMemoryManager(nsIMemory* *result)
361 return sGlobalMemory.QueryInterface(NS_GET_IID(nsIMemory), (void**) result);