diff --git a/xpcom/base/AvailableMemoryTracker.cpp b/xpcom/base/AvailableMemoryTracker.cpp index c21d89cea22e..248b1b9fe186 100644 --- a/xpcom/base/AvailableMemoryTracker.cpp +++ b/xpcom/base/AvailableMemoryTracker.cpp @@ -490,15 +490,15 @@ void Activate() } else { Preferences::AddUintVarCache(&sLowVirtualMemoryThreshold, - "memory.low_virtual_mem_threshold_mb", 128); + "memory.low_virtual_mem_threshold_mb", 128); } Preferences::AddUintVarCache(&sLowPhysicalMemoryThreshold, - "memory.low_physical_memory_threshold_mb", 0); + "memory.low_physical_memory_threshold_mb", 0); Preferences::AddUintVarCache(&sLowCommitSpaceThreshold, - "memory.low_commit_space_threshold_mb", 128); + "memory.low_commit_space_threshold_mb", 128); Preferences::AddUintVarCache(&sLowMemoryNotificationIntervalMS, - "memory.low_memory_notification_interval_ms", 10000); + "memory.low_memory_notification_interval_ms", 10000); RegisterStrongMemoryReporter(new LowEventsReporter()); RegisterLowMemoryEventsVirtualDistinguishedAmount(LowMemoryEventsVirtualDistinguishedAmount); @@ -530,16 +530,16 @@ void Init() if (!PR_GetEnv("MOZ_PGO_INSTRUMENTED")) { sKernel32Intercept.Init("Kernel32.dll"); sKernel32Intercept.AddHook("VirtualAlloc", - reinterpret_cast(VirtualAllocHook), - (void**) &sVirtualAllocOrig); + reinterpret_cast(VirtualAllocHook), + (void**) &sVirtualAllocOrig); sKernel32Intercept.AddHook("MapViewOfFile", - reinterpret_cast(MapViewOfFileHook), - (void**) &sMapViewOfFileOrig); + reinterpret_cast(MapViewOfFileHook), + (void**) &sMapViewOfFileOrig); sGdi32Intercept.Init("Gdi32.dll"); sGdi32Intercept.AddHook("CreateDIBSection", - reinterpret_cast(CreateDIBSectionHook), - (void**) &sCreateDIBSectionOrig); + reinterpret_cast(CreateDIBSectionHook), + (void**) &sCreateDIBSectionOrig); } sInitialized = true; diff --git a/xpcom/base/CycleCollectedJSRuntime.cpp b/xpcom/base/CycleCollectedJSRuntime.cpp index aac8c69e7a3d..b05dad4969c5 100644 --- a/xpcom/base/CycleCollectedJSRuntime.cpp +++ b/xpcom/base/CycleCollectedJSRuntime.cpp @@ -123,7 +123,7 @@ TraceWeakMappingChild(JSTracer* trc, void** thingp, JSGCTraceKind kind); struct NoteWeakMapChildrenTracer : public JSTracer { NoteWeakMapChildrenTracer(JSRuntime *rt, nsCycleCollectionNoteRootCallback& cb) - : JSTracer(rt, TraceWeakMappingChild), mCb(cb) + : JSTracer(rt, TraceWeakMappingChild), mCb(cb) { } nsCycleCollectionNoteRootCallback& mCb; @@ -161,7 +161,7 @@ struct NoteWeakMapsTracer : public js::WeakMapTracer { NoteWeakMapsTracer(JSRuntime* rt, js::WeakMapTraceCallback cb, nsCycleCollectionNoteRootCallback& cccb) - : js::WeakMapTracer(rt, cb), mCb(cccb), mChildTracer(rt, cccb) + : js::WeakMapTracer(rt, cb), mCb(cccb), mChildTracer(rt, cccb) { } nsCycleCollectionNoteRootCallback& mCb; @@ -170,8 +170,8 @@ struct NoteWeakMapsTracer : public js::WeakMapTracer static void TraceWeakMapping(js::WeakMapTracer* trc, JSObject* m, - void* k, JSGCTraceKind kkind, - void* v, JSGCTraceKind vkind) + void* k, JSGCTraceKind kkind, + void* v, JSGCTraceKind vkind) { MOZ_ASSERT(trc->callback == TraceWeakMapping); NoteWeakMapsTracer* tracer = static_cast(trc); @@ -691,7 +691,7 @@ CycleCollectedJSRuntime::TraverseZone(JS::Zone* aZone, CycleCollectedJSRuntime::TraverseObjectShim(void* aData, void* aThing) { TraverseObjectShimClosure* closure = - static_cast(aData); + static_cast(aData); MOZ_ASSERT(js::GCThingTraceKind(aThing) == JSTRACE_OBJECT); closure->self->TraverseGCThing(CycleCollectedJSRuntime::TRAVERSE_CPP, aThing, @@ -887,13 +887,13 @@ CycleCollectedJSRuntime::SetPendingException(nsIException* aException) nsCycleCollectionParticipant* CycleCollectedJSRuntime::GCThingParticipant() { - return &mGCThingCycleCollectorGlobal; + return &mGCThingCycleCollectorGlobal; } nsCycleCollectionParticipant* CycleCollectedJSRuntime::ZoneParticipant() { - return &mJSZoneCycleCollectorGlobal; + return &mJSZoneCycleCollectorGlobal; } nsresult diff --git a/xpcom/base/CycleCollectedJSRuntime.h b/xpcom/base/CycleCollectedJSRuntime.h index e7c36fd414cd..8092a0fc904a 100644 --- a/xpcom/base/CycleCollectedJSRuntime.h +++ b/xpcom/base/CycleCollectedJSRuntime.h @@ -146,8 +146,8 @@ private: } enum TraverseSelect { - TRAVERSE_CPP, - TRAVERSE_FULL + TRAVERSE_CPP, + TRAVERSE_FULL }; void diff --git a/xpcom/base/StaticPtr.h b/xpcom/base/StaticPtr.h index 865606702f3e..b14396044753 100644 --- a/xpcom/base/StaticPtr.h +++ b/xpcom/base/StaticPtr.h @@ -1,5 +1,5 @@ /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim: set sw=2 ts=8 et ft=cpp : */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ @@ -37,62 +37,62 @@ namespace mozilla { template class StaticAutoPtr { - public: - // In debug builds, check that mRawPtr is initialized for us as we expect - // by the compiler. In non-debug builds, don't declare a constructor - // so that the compiler can see that the constructor is trivial. +public: + // In debug builds, check that mRawPtr is initialized for us as we expect + // by the compiler. In non-debug builds, don't declare a constructor + // so that the compiler can see that the constructor is trivial. #ifdef DEBUG - StaticAutoPtr() - { - MOZ_ASSERT(!mRawPtr); - } + StaticAutoPtr() + { + MOZ_ASSERT(!mRawPtr); + } #endif - StaticAutoPtr& operator=(T* rhs) - { - Assign(rhs); - return *this; - } + StaticAutoPtr& operator=(T* rhs) + { + Assign(rhs); + return *this; + } - T* get() const - { - return mRawPtr; - } + T* get() const + { + return mRawPtr; + } - operator T*() const - { - return get(); - } + operator T*() const + { + return get(); + } - T* operator->() const - { - MOZ_ASSERT(mRawPtr); - return get(); - } + T* operator->() const + { + MOZ_ASSERT(mRawPtr); + return get(); + } - T& operator*() const - { - return *get(); - } + T& operator*() const + { + return *get(); + } - private: - // Disallow copy constructor, but only in debug mode. We only define - // a default constructor in debug mode (see above); if we declared - // this constructor always, the compiler wouldn't generate a trivial - // default constructor for us in non-debug mode. +private: + // Disallow copy constructor, but only in debug mode. We only define + // a default constructor in debug mode (see above); if we declared + // this constructor always, the compiler wouldn't generate a trivial + // default constructor for us in non-debug mode. #ifdef DEBUG - StaticAutoPtr(StaticAutoPtr &other); + StaticAutoPtr(StaticAutoPtr &other); #endif - void Assign(T* newPtr) - { - MOZ_ASSERT(!newPtr || mRawPtr != newPtr); - T* oldPtr = mRawPtr; - mRawPtr = newPtr; - delete oldPtr; - } + void Assign(T* newPtr) + { + MOZ_ASSERT(!newPtr || mRawPtr != newPtr); + T* oldPtr = mRawPtr; + mRawPtr = newPtr; + delete oldPtr; + } - T* mRawPtr; + T* mRawPtr; }; template diff --git a/xpcom/base/SystemMemoryReporter.cpp b/xpcom/base/SystemMemoryReporter.cpp index 8676e923ee41..81292aeb8d15 100644 --- a/xpcom/base/SystemMemoryReporter.cpp +++ b/xpcom/base/SystemMemoryReporter.cpp @@ -130,7 +130,7 @@ public: } while (0) #define REPORT(_path, _amount, _desc) \ - REPORT_WITH_CLEANUP(_path, UNITS_BYTES, _amount, _desc, (void)0) + REPORT_WITH_CLEANUP(_path, UNITS_BYTES, _amount, _desc, (void)0) NS_IMETHOD CollectReports(nsIHandleReportCallback* aHandleReport, nsISupports* aData) @@ -626,16 +626,16 @@ private: uint64_t ReadSizeFromFile(const char* aFilename) { - FILE* sizeFile = fopen(aFilename, "r"); - if (NS_WARN_IF(!sizeFile)) { - return 0; - } + FILE* sizeFile = fopen(aFilename, "r"); + if (NS_WARN_IF(!sizeFile)) { + return 0; + } - uint64_t size = 0; - fscanf(sizeFile, "%" SCNu64, &size); - fclose(sizeFile); + uint64_t size = 0; + fscanf(sizeFile, "%" SCNu64, &size); + fclose(sizeFile); - return size; + return size; } nsresult @@ -681,16 +681,16 @@ private: nsPrintfCString diskUsedPath("zram-disksize/%s/used", name); nsPrintfCString diskUsedDesc( - "The uncompressed size of data stored in \"%s.\" " - "This excludes zero-filled pages since " - "no memory is allocated for them.", name); + "The uncompressed size of data stored in \"%s.\" " + "This excludes zero-filled pages since " + "no memory is allocated for them.", name); REPORT_WITH_CLEANUP(diskUsedPath, UNITS_BYTES, origSize, diskUsedDesc, closedir(d)); nsPrintfCString diskUnusedPath("zram-disksize/%s/unused", name); nsPrintfCString diskUnusedDesc( - "The amount of uncompressed data that can still be " - "be stored in \"%s\"", name); + "The amount of uncompressed data that can still be " + "be stored in \"%s\"", name); REPORT_WITH_CLEANUP(diskUnusedPath, UNITS_BYTES, unusedSize, diskUnusedDesc, closedir(d)); @@ -702,15 +702,15 @@ private: uint64_t writes = ReadSizeFromFile(writesFile.get()); nsPrintfCString readsDesc( - "The number of reads (failed or successful) done on " - "\"%s\"", name); + "The number of reads (failed or successful) done on " + "\"%s\"", name); nsPrintfCString readsPath("zram-accesses/%s/reads", name); REPORT_WITH_CLEANUP(readsPath, UNITS_COUNT_CUMULATIVE, reads, readsDesc, closedir(d)); nsPrintfCString writesDesc( - "The number of writes (failed or successful) done " - "on \"%s\"", name); + "The number of writes (failed or successful) done " + "on \"%s\"", name); nsPrintfCString writesPath("zram-accesses/%s/writes", name); REPORT_WITH_CLEANUP(writesPath, UNITS_COUNT_CUMULATIVE, writes, writesDesc, closedir(d)); @@ -720,8 +720,8 @@ private: uint64_t comprSize = ReadSizeFromFile(comprSizeFile.get()); nsPrintfCString comprSizeDesc( - "The compressed size of data stored in \"%s\"", - name); + "The compressed size of data stored in \"%s\"", + name); nsPrintfCString comprSizePath("zram-compr-data-size/%s", name); REPORT_WITH_CLEANUP(comprSizePath, UNITS_BYTES, comprSize, comprSizeDesc, closedir(d)); @@ -816,15 +816,15 @@ NS_IMPL_ISUPPORTS(SystemReporter, nsIMemoryReporter) // Keep this in sync with SystemReporter::ProcessSizeKind! const char* SystemReporter::kindPathSuffixes[] = { - "anonymous/outside-brk", - "anonymous/brk-heap", - "shared-libraries/read-executable", - "shared-libraries/read-write", - "shared-libraries/read-only", - "shared-libraries/other", - "other-files", - "main-thread-stack", - "vdso" + "anonymous/outside-brk", + "anonymous/brk-heap", + "shared-libraries/read-executable", + "shared-libraries/read-write", + "shared-libraries/read-only", + "shared-libraries/other", + "other-files", + "main-thread-stack", + "vdso" }; void Init() diff --git a/xpcom/base/SystemMemoryReporter.h b/xpcom/base/SystemMemoryReporter.h index f8ee74b95227..7e44e92226cc 100644 --- a/xpcom/base/SystemMemoryReporter.h +++ b/xpcom/base/SystemMemoryReporter.h @@ -1,5 +1,5 @@ -/* -*- Mode: C++; tab-width: 50; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ -/* vim:set ts=2 sw=2 sts=2 ci et: */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ @@ -14,9 +14,9 @@ namespace SystemMemoryReporter { // empty functions on other platforms. #if defined(XP_LINUX) - void Init(); +void Init(); #else - void Init() {} +void Init() {} #endif } // namespace SystemMemoryReporter diff --git a/xpcom/base/VisualEventTracer.cpp b/xpcom/base/VisualEventTracer.cpp index 8debcd9ca4e3..c71c95821b99 100644 --- a/xpcom/base/VisualEventTracer.cpp +++ b/xpcom/base/VisualEventTracer.cpp @@ -43,14 +43,14 @@ mozilla::TimeDuration * gMaxBacklogTime; // Record of a single event class Record { public: - Record() + Record() : mType(::mozilla::eventtracer::eNone) , mItem(nullptr) , mText(nullptr) - , mText2(nullptr) + , mText2(nullptr) { MOZ_COUNT_CTOR(Record); - } + } Record& operator=(const Record & aOther) { @@ -62,10 +62,10 @@ public: return *this; } - ~Record() + ~Record() { PL_strfree(mText2); - PL_strfree(mText); + PL_strfree(mText); MOZ_COUNT_DTOR(Record); } @@ -354,7 +354,7 @@ EventFilter::Build(const char * filterVar) // Read up to a comma or EOF -> get name of an event first in the list count = sscanf(filterVar, "%63[^,]%n", eventName, &delta); - if (count == 0) + if (count == 0) return nullptr; pos = delta; @@ -382,7 +382,7 @@ EventFilter::EventPasses(const char * eventName) return false; } -// State and control variables, initialized in Init() method, after it +// State and control variables, initialized in Init() method, after it // immutable and read concurently. EventFilter * gEventFilter = nullptr; unsigned gThreadPrivateIndex; @@ -403,7 +403,7 @@ bool CheckEventFilters(uint32_t aType, void * aItem, const char * aText) #endif //MOZ_VISUAL_EVENT_TRACER -// static +// static void Init() { #ifdef MOZ_VISUAL_EVENT_TRACER @@ -426,7 +426,7 @@ void Init() #endif } -// static +// static void Shutdown() { #ifdef MOZ_VISUAL_EVENT_TRACER @@ -457,7 +457,7 @@ void Shutdown() #endif } -// static +// static void Mark(uint32_t aType, void * aItem, const char * aText, const char * aText2) { #ifdef MOZ_VISUAL_EVENT_TRACER @@ -471,7 +471,7 @@ void Mark(uint32_t aType, void * aItem, const char * aText, const char * aText2) return; RecordBatch * threadLogPrivate = static_cast( - PR_GetThreadPrivate(gThreadPrivateIndex)); + PR_GetThreadPrivate(gThreadPrivateIndex)); if (!threadLogPrivate) { threadLogPrivate = RecordBatch::Register(); if (!threadLogPrivate) @@ -589,7 +589,7 @@ VisualEventTracerLog::WriteToProfilingFile() } PRFileDesc* fd = PR_Open(filename, PR_WRONLY | PR_CREATE_FILE | PR_TRUNCATE, - 0644); + 0644); if (!fd) { return NS_ERROR_FILE_ACCESS_DENIED; } diff --git a/xpcom/base/VisualEventTracer.h b/xpcom/base/VisualEventTracer.h index fb1c1e3444a2..3ff09d24b00a 100644 --- a/xpcom/base/VisualEventTracer.h +++ b/xpcom/base/VisualEventTracer.h @@ -7,7 +7,7 @@ /** * The event tracer code is by default disabled in both build and run time. * - * To enable this code at build time, add --enable-visual-profiling to your + * To enable this code at build time, add --enable-visual-profiling to your * configure options. * * To enable this code at run time, export MOZ_TRACE_FILE env var with a @@ -15,8 +15,8 @@ * the log of all events instrumentation in the mozilla code. Check * MOZ_EVENT_TRACER_* macros below to add your own. * - * To let the event tracer log only some events to save disk space, export - * MOZ_PROFILING_EVENTS with comma separated list of event names you want + * To let the event tracer log only some events to save disk space, export + * MOZ_PROFILING_EVENTS with comma separated list of event names you want * to record in the log. */ @@ -30,8 +30,8 @@ #ifdef MOZ_VISUAL_EVENT_TRACER #include "nsIVisualEventTracer.h" -// Bind an object instance, usually |this|, to a name, usually URL or -// host name, the instance deals with for its lifetime. The name string +// Bind an object instance, usually |this|, to a name, usually URL or +// host name, the instance deals with for its lifetime. The name string // is duplicated. // IMPORTANT: it is up to the caller to pass the correct static_cast // of the |instance| pointer to all these macros ; otherwise the linking @@ -47,19 +47,19 @@ mozilla::eventtracer::Mark(mozilla::eventtracer::eName, instance, name, name2) -// Call the followings with the same |instance| reference as you have +// Call the followings with the same |instance| reference as you have // previously called MOZ_EVENT_TRACER_NAME_OBJECT. -// Let |name| be the name of the event happening, like "resolving", +// Let |name| be the name of the event happening, like "resolving", // "connecting", "loading" etc. -// This will crate a single-point-in-time event marked with an arrow +// This will crate a single-point-in-time event marked with an arrow // on the timeline, this is a way to indicate an event without a duration. #define MOZ_EVENT_TRACER_MARK(instance, name) \ mozilla::eventtracer::Mark(mozilla::eventtracer::eShot, instance, name) // Following macros are used to log events with duration. -// There always has to be complete WAIT,EXEC,DONE or EXEC,DONE -// uninterrupted and non-interferring tuple(s) for an event to be correctly +// There always has to be complete WAIT,EXEC,DONE or EXEC,DONE +// uninterrupted and non-interferring tuple(s) for an event to be correctly // shown on the timeline. Each can be called on any thread, the event tape is // finally displayed on the thread where it has been EXECuted. @@ -71,7 +71,7 @@ // DONE: we've just got OnStopRequest call that indicates the content // has been completely delivered and the request is now finished -// Indicate an event pending start, on the timeline this will +// Indicate an event pending start, on the timeline this will // start the event's interval tape with a pale color, the time will // show in details. Usually used when an event is being posted or // we wait for a lock acquisition. @@ -79,7 +79,7 @@ #define MOZ_EVENT_TRACER_WAIT(instance, name) \ mozilla::eventtracer::Mark(mozilla::eventtracer::eWait, instance, name) -// Indicate start of an event actual execution, on the timeline this will +// Indicate start of an event actual execution, on the timeline this will // change the event's tape to a deeper color, the time will show in details. #define MOZ_EVENT_TRACER_EXEC(instance, name) \ mozilla::eventtracer::Mark(mozilla::eventtracer::eExec, instance, name) @@ -94,7 +94,7 @@ // The same meaning as the above macros, just for concurent events. // Concurent event means it can happen for the same instance on more -// then just a single thread, e.g. a service method call, a global lock +// then just a single thread, e.g. a service method call, a global lock // acquisition, enter and release. #define MOZ_EVENT_TRACER_WAIT_THREADSAFE(instance, name) \ mozilla::eventtracer::Mark(mozilla::eventtracer::eWait | mozilla::eventtracer::eThreadConcurrent, instance, name) @@ -103,7 +103,7 @@ #define MOZ_EVENT_TRACER_DONE_THREASAFE(instance, name) \ mozilla::eventtracer::Mark(mozilla::eventtracer::eDone | mozilla::eventtracer::eThreadConcurrent, instance, name) -#else +#else // MOZ_VISUAL_EVENT_TRACER disabled @@ -126,7 +126,7 @@ namespace eventtracer { // Initialize the event tracer engine, called automatically on XPCOM startup. void Init(); -// Shuts the event tracer engine down and closes the log file, called +// Shuts the event tracer engine down and closes the log file, called // automatically during XPCOM shutdown. void Shutdown(); @@ -146,8 +146,8 @@ enum MarkType { eThreadConcurrent = 0x10000 }; -// Records an event on the calling thread. -// @param aType +// Records an event on the calling thread. +// @param aType // One of MarkType fields, can be bitwise or'ed with the flags. // @param aItem // Reference to the object we want to bind a name to or the event is @@ -159,7 +159,7 @@ enum MarkType { // @param aText2 // Optional second part of the instnace name, or event name. // Event filtering does apply only to the first part (aText). -void Mark(uint32_t aType, void * aItem, +void Mark(uint32_t aType, void * aItem, const char * aText, const char * aText2 = 0); @@ -176,12 +176,12 @@ void Mark(uint32_t aType, void * aItem, class MOZ_STACK_CLASS AutoEventTracer { public: - AutoEventTracer(void * aInstance, - uint32_t aTypeOn, // MarkType marked in constructor - uint32_t aTypeOff, // MarkType marked in destructor - const char * aName, - const char * aName2 = 0 - MOZ_GUARD_OBJECT_NOTIFIER_PARAM) + AutoEventTracer(void * aInstance, + uint32_t aTypeOn, // MarkType marked in constructor + uint32_t aTypeOff, // MarkType marked in destructor + const char * aName, + const char * aName2 = 0 + MOZ_GUARD_OBJECT_NOTIFIER_PARAM) : mInstance(aInstance) , mName(aName) , mName2(aName2) diff --git a/xpcom/base/nsAgg.h b/xpcom/base/nsAgg.h index d0988cf8485f..a29879ef3539 100644 --- a/xpcom/base/nsAgg.h +++ b/xpcom/base/nsAgg.h @@ -1,4 +1,5 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ @@ -15,12 +16,12 @@ // Put NS_DECL_AGGREGATED or NS_DECL_CYCLE_COLLECTING_AGGREGATED in your class's // declaration. #define NS_DECL_AGGREGATED \ - NS_DECL_ISUPPORTS \ - NS_DECL_AGGREGATED_HELPER + NS_DECL_ISUPPORTS \ + NS_DECL_AGGREGATED_HELPER #define NS_DECL_CYCLE_COLLECTING_AGGREGATED \ - NS_DECL_CYCLE_COLLECTING_ISUPPORTS \ - NS_DECL_AGGREGATED_HELPER + NS_DECL_CYCLE_COLLECTING_ISUPPORTS \ + NS_DECL_AGGREGATED_HELPER #define NS_DECL_AGGREGATED_HELPER \ public: \ @@ -230,10 +231,10 @@ _class::Internal::QueryInterface(const nsIID& aIID, void** aInstancePtr) \ class nsAggregatedCycleCollectionParticipant { public: - NS_DECLARE_STATIC_IID_ACCESSOR(NS_AGGREGATED_CYCLECOLLECTIONPARTICIPANT_IID) + NS_DECLARE_STATIC_IID_ACCESSOR(NS_AGGREGATED_CYCLECOLLECTIONPARTICIPANT_IID) }; -NS_DEFINE_STATIC_IID_ACCESSOR(nsAggregatedCycleCollectionParticipant, +NS_DEFINE_STATIC_IID_ACCESSOR(nsAggregatedCycleCollectionParticipant, NS_AGGREGATED_CYCLECOLLECTIONPARTICIPANT_IID) // for use with QI macros in nsISupportsUtils.h: diff --git a/xpcom/base/nsAutoPtr.h b/xpcom/base/nsAutoPtr.h index f8778554a6a2..b1489f7b627f 100644 --- a/xpcom/base/nsAutoPtr.h +++ b/xpcom/base/nsAutoPtr.h @@ -1,4 +1,5 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ @@ -17,433 +18,433 @@ template class nsAutoPtr +{ +private: + void** + begin_assignment() { - private: - void** - begin_assignment() - { - assign(0); - return reinterpret_cast(&mRawPtr); - } + assign(0); + return reinterpret_cast(&mRawPtr); + } - void - assign( T* newPtr ) - { - T* oldPtr = mRawPtr; + void + assign( T* newPtr ) + { + T* oldPtr = mRawPtr; - if (newPtr != nullptr && newPtr == oldPtr) { - NS_RUNTIMEABORT("Logic flaw in the caller"); - } + if (newPtr != nullptr && newPtr == oldPtr) { + NS_RUNTIMEABORT("Logic flaw in the caller"); + } - mRawPtr = newPtr; - delete oldPtr; - } + mRawPtr = newPtr; + delete oldPtr; + } - // |class Ptr| helps us prevent implicit "copy construction" - // through |operator T*() const| from a |const nsAutoPtr| - // because two implicit conversions in a row aren't allowed. - // It still allows assignment from T* through implicit conversion - // from |T*| to |nsAutoPtr::Ptr| - class Ptr - { - public: - Ptr( T* aPtr ) - : mPtr(aPtr) - { - } + // |class Ptr| helps us prevent implicit "copy construction" + // through |operator T*() const| from a |const nsAutoPtr| + // because two implicit conversions in a row aren't allowed. + // It still allows assignment from T* through implicit conversion + // from |T*| to |nsAutoPtr::Ptr| + class Ptr + { + public: + Ptr( T* aPtr ) + : mPtr(aPtr) + { + } - operator T*() const - { - return mPtr; - } + operator T*() const + { + return mPtr; + } - private: - T* mPtr; - }; - - private: - T* mRawPtr; - - public: - typedef T element_type; - - ~nsAutoPtr() - { - delete mRawPtr; - } - - // Constructors - - nsAutoPtr() - : mRawPtr(0) - // default constructor - { - } - - nsAutoPtr( Ptr aRawPtr ) - : mRawPtr(aRawPtr) - // construct from a raw pointer (of the right type) - { - } - - // This constructor shouldn't exist; we should just use the && - // constructor. - nsAutoPtr( nsAutoPtr& aSmartPtr ) - : mRawPtr( aSmartPtr.forget() ) - // Construct by transferring ownership from another smart pointer. - { - } - - nsAutoPtr( nsAutoPtr&& aSmartPtr ) - : mRawPtr( aSmartPtr.forget() ) - // Construct by transferring ownership from another smart pointer. - { - } - - // Assignment operators - - nsAutoPtr& - operator=( T* rhs ) - // assign from a raw pointer (of the right type) - { - assign(rhs); - return *this; - } - - nsAutoPtr& operator=( nsAutoPtr& rhs ) - // assign by transferring ownership from another smart pointer. - { - assign(rhs.forget()); - return *this; - } - - // Other pointer operators - - T* - get() const - /* - Prefer the implicit conversion provided automatically by - |operator T*() const|. Use |get()| _only_ to resolve - ambiguity. - */ - { - return mRawPtr; - } - - operator T*() const - /* - ...makes an |nsAutoPtr| act like its underlying raw pointer - type whenever it is used in a context where a raw pointer - is expected. It is this operator that makes an |nsAutoPtr| - substitutable for a raw pointer. - - Prefer the implicit use of this operator to calling |get()|, - except where necessary to resolve ambiguity. - */ - { - return get(); - } - - T* - forget() - { - T* temp = mRawPtr; - mRawPtr = 0; - return temp; - } - - T* - operator->() const - { - NS_PRECONDITION(mRawPtr != 0, "You can't dereference a NULL nsAutoPtr with operator->()."); - return get(); - } - - // This operator is needed for gcc <= 4.0.* and for Sun Studio; it - // causes internal compiler errors for some MSVC versions. (It's not - // clear to me whether it should be needed.) -#ifndef _MSC_VER - template - U& - operator->*(U V::* aMember) - { - NS_PRECONDITION(mRawPtr != 0, "You can't dereference a NULL nsAutoPtr with operator->*()."); - return get()->*aMember; - } -#endif - - nsAutoPtr* - get_address() - // This is not intended to be used by clients. See |address_of| - // below. - { - return this; - } - - const nsAutoPtr* - get_address() const - // This is not intended to be used by clients. See |address_of| - // below. - { - return this; - } - - public: - T& - operator*() const - { - NS_PRECONDITION(mRawPtr != 0, "You can't dereference a NULL nsAutoPtr with operator*()."); - return *get(); - } - - T** - StartAssignment() - { -#ifndef NSCAP_FEATURE_INLINE_STARTASSIGNMENT - return reinterpret_cast(begin_assignment()); -#else - assign(0); - return reinterpret_cast(&mRawPtr); -#endif - } + private: + T* mPtr; }; +private: + T* mRawPtr; + +public: + typedef T element_type; + + ~nsAutoPtr() + { + delete mRawPtr; + } + + // Constructors + + nsAutoPtr() + : mRawPtr(0) + // default constructor + { + } + + nsAutoPtr( Ptr aRawPtr ) + : mRawPtr(aRawPtr) + // construct from a raw pointer (of the right type) + { + } + + // This constructor shouldn't exist; we should just use the && + // constructor. + nsAutoPtr( nsAutoPtr& aSmartPtr ) + : mRawPtr( aSmartPtr.forget() ) + // Construct by transferring ownership from another smart pointer. + { + } + + nsAutoPtr( nsAutoPtr&& aSmartPtr ) + : mRawPtr( aSmartPtr.forget() ) + // Construct by transferring ownership from another smart pointer. + { + } + + // Assignment operators + + nsAutoPtr& + operator=( T* rhs ) + // assign from a raw pointer (of the right type) + { + assign(rhs); + return *this; + } + + nsAutoPtr& operator=( nsAutoPtr& rhs ) + // assign by transferring ownership from another smart pointer. + { + assign(rhs.forget()); + return *this; + } + + // Other pointer operators + + T* + get() const + /* + Prefer the implicit conversion provided automatically by + |operator T*() const|. Use |get()| _only_ to resolve + ambiguity. + */ + { + return mRawPtr; + } + + operator T*() const + /* + ...makes an |nsAutoPtr| act like its underlying raw pointer + type whenever it is used in a context where a raw pointer + is expected. It is this operator that makes an |nsAutoPtr| + substitutable for a raw pointer. + + Prefer the implicit use of this operator to calling |get()|, + except where necessary to resolve ambiguity. + */ + { + return get(); + } + + T* + forget() + { + T* temp = mRawPtr; + mRawPtr = 0; + return temp; + } + + T* + operator->() const + { + NS_PRECONDITION(mRawPtr != 0, "You can't dereference a NULL nsAutoPtr with operator->()."); + return get(); + } + + // This operator is needed for gcc <= 4.0.* and for Sun Studio; it + // causes internal compiler errors for some MSVC versions. (It's not + // clear to me whether it should be needed.) +#ifndef _MSC_VER + template + U& + operator->*(U V::* aMember) + { + NS_PRECONDITION(mRawPtr != 0, "You can't dereference a NULL nsAutoPtr with operator->*()."); + return get()->*aMember; + } +#endif + + nsAutoPtr* + get_address() + // This is not intended to be used by clients. See |address_of| + // below. + { + return this; + } + + const nsAutoPtr* + get_address() const + // This is not intended to be used by clients. See |address_of| + // below. + { + return this; + } + +public: + T& + operator*() const + { + NS_PRECONDITION(mRawPtr != 0, "You can't dereference a NULL nsAutoPtr with operator*()."); + return *get(); + } + + T** + StartAssignment() + { +#ifndef NSCAP_FEATURE_INLINE_STARTASSIGNMENT + return reinterpret_cast(begin_assignment()); +#else + assign(0); + return reinterpret_cast(&mRawPtr); +#endif + } +}; + template inline nsAutoPtr* address_of( nsAutoPtr& aPtr ) - { - return aPtr.get_address(); - } +{ + return aPtr.get_address(); +} template inline const nsAutoPtr* address_of( const nsAutoPtr& aPtr ) - { - return aPtr.get_address(); - } +{ + return aPtr.get_address(); +} template class nsAutoPtrGetterTransfers - /* - ... +/* + ... - This class is designed to be used for anonymous temporary objects in the - argument list of calls that return COM interface pointers, e.g., + This class is designed to be used for anonymous temporary objects in the + argument list of calls that return COM interface pointers, e.g., - nsAutoPtr fooP; - ...->GetTransferedPointer(getter_Transfers(fooP)) + nsAutoPtr fooP; + ...->GetTransferedPointer(getter_Transfers(fooP)) - DO NOT USE THIS TYPE DIRECTLY IN YOUR CODE. Use |getter_Transfers()| instead. + DO NOT USE THIS TYPE DIRECTLY IN YOUR CODE. Use |getter_Transfers()| instead. - When initialized with a |nsAutoPtr|, as in the example above, it returns - a |void**|, a |T**|, or an |nsISupports**| as needed, that the - outer call (|GetTransferedPointer| in this case) can fill in. + When initialized with a |nsAutoPtr|, as in the example above, it returns + a |void**|, a |T**|, or an |nsISupports**| as needed, that the + outer call (|GetTransferedPointer| in this case) can fill in. - This type should be a nested class inside |nsAutoPtr|. - */ + This type should be a nested class inside |nsAutoPtr|. +*/ +{ +public: + explicit + nsAutoPtrGetterTransfers( nsAutoPtr& aSmartPtr ) + : mTargetSmartPtr(aSmartPtr) { - public: - explicit - nsAutoPtrGetterTransfers( nsAutoPtr& aSmartPtr ) - : mTargetSmartPtr(aSmartPtr) - { - // nothing else to do - } + // nothing else to do + } - operator void**() - { - return reinterpret_cast(mTargetSmartPtr.StartAssignment()); - } + operator void**() + { + return reinterpret_cast(mTargetSmartPtr.StartAssignment()); + } - operator T**() - { - return mTargetSmartPtr.StartAssignment(); - } + operator T**() + { + return mTargetSmartPtr.StartAssignment(); + } - T*& - operator*() - { - return *(mTargetSmartPtr.StartAssignment()); - } + T*& + operator*() + { + return *(mTargetSmartPtr.StartAssignment()); + } - private: - nsAutoPtr& mTargetSmartPtr; - }; +private: + nsAutoPtr& mTargetSmartPtr; +}; template inline nsAutoPtrGetterTransfers getter_Transfers( nsAutoPtr& aSmartPtr ) - /* - Used around a |nsAutoPtr| when - ...makes the class |nsAutoPtrGetterTransfers| invisible. - */ - { - return nsAutoPtrGetterTransfers(aSmartPtr); - } +/* + Used around a |nsAutoPtr| when + ...makes the class |nsAutoPtrGetterTransfers| invisible. +*/ +{ + return nsAutoPtrGetterTransfers(aSmartPtr); +} - // Comparing two |nsAutoPtr|s +// Comparing two |nsAutoPtr|s template inline bool operator==( const nsAutoPtr& lhs, const nsAutoPtr& rhs ) - { - return static_cast(lhs.get()) == static_cast(rhs.get()); - } +{ + return static_cast(lhs.get()) == static_cast(rhs.get()); +} template inline bool operator!=( const nsAutoPtr& lhs, const nsAutoPtr& rhs ) - { - return static_cast(lhs.get()) != static_cast(rhs.get()); - } +{ + return static_cast(lhs.get()) != static_cast(rhs.get()); +} - // Comparing an |nsAutoPtr| to a raw pointer +// Comparing an |nsAutoPtr| to a raw pointer template inline bool operator==( const nsAutoPtr& lhs, const U* rhs ) - { - return static_cast(lhs.get()) == static_cast(rhs); - } +{ + return static_cast(lhs.get()) == static_cast(rhs); +} template inline bool operator==( const U* lhs, const nsAutoPtr& rhs ) - { - return static_cast(lhs) == static_cast(rhs.get()); - } +{ + return static_cast(lhs) == static_cast(rhs.get()); +} template inline bool operator!=( const nsAutoPtr& lhs, const U* rhs ) - { - return static_cast(lhs.get()) != static_cast(rhs); - } +{ + return static_cast(lhs.get()) != static_cast(rhs); +} template inline bool operator!=( const U* lhs, const nsAutoPtr& rhs ) - { - return static_cast(lhs) != static_cast(rhs.get()); - } +{ + return static_cast(lhs) != static_cast(rhs.get()); +} - // To avoid ambiguities caused by the presence of builtin |operator==|s - // creating a situation where one of the |operator==| defined above - // has a better conversion for one argument and the builtin has a - // better conversion for the other argument, define additional - // |operator==| without the |const| on the raw pointer. - // See bug 65664 for details. +// To avoid ambiguities caused by the presence of builtin |operator==|s +// creating a situation where one of the |operator==| defined above +// has a better conversion for one argument and the builtin has a +// better conversion for the other argument, define additional +// |operator==| without the |const| on the raw pointer. +// See bug 65664 for details. #ifndef NSCAP_DONT_PROVIDE_NONCONST_OPEQ template inline bool operator==( const nsAutoPtr& lhs, U* rhs ) - { - return static_cast(lhs.get()) == const_cast(rhs); - } +{ + return static_cast(lhs.get()) == const_cast(rhs); +} template inline bool operator==( U* lhs, const nsAutoPtr& rhs ) - { - return const_cast(lhs) == static_cast(rhs.get()); - } +{ + return const_cast(lhs) == static_cast(rhs.get()); +} template inline bool operator!=( const nsAutoPtr& lhs, U* rhs ) - { - return static_cast(lhs.get()) != const_cast(rhs); - } +{ + return static_cast(lhs.get()) != const_cast(rhs); +} template inline bool operator!=( U* lhs, const nsAutoPtr& rhs ) - { - return const_cast(lhs) != static_cast(rhs.get()); - } +{ + return const_cast(lhs) != static_cast(rhs.get()); +} #endif - // Comparing an |nsAutoPtr| to |0| +// Comparing an |nsAutoPtr| to |0| template inline bool operator==( const nsAutoPtr& lhs, NSCAP_Zero* rhs ) - // specifically to allow |smartPtr == 0| - { - return static_cast(lhs.get()) == reinterpret_cast(rhs); - } +// specifically to allow |smartPtr == 0| +{ + return static_cast(lhs.get()) == reinterpret_cast(rhs); +} template inline bool operator==( NSCAP_Zero* lhs, const nsAutoPtr& rhs ) - // specifically to allow |0 == smartPtr| - { - return reinterpret_cast(lhs) == static_cast(rhs.get()); - } +// specifically to allow |0 == smartPtr| +{ + return reinterpret_cast(lhs) == static_cast(rhs.get()); +} template inline bool operator!=( const nsAutoPtr& lhs, NSCAP_Zero* rhs ) - // specifically to allow |smartPtr != 0| - { - return static_cast(lhs.get()) != reinterpret_cast(rhs); - } +// specifically to allow |smartPtr != 0| +{ + return static_cast(lhs.get()) != reinterpret_cast(rhs); +} template inline bool operator!=( NSCAP_Zero* lhs, const nsAutoPtr& rhs ) - // specifically to allow |0 != smartPtr| - { - return reinterpret_cast(lhs) != static_cast(rhs.get()); - } +// specifically to allow |0 != smartPtr| +{ + return reinterpret_cast(lhs) != static_cast(rhs.get()); +} #ifdef HAVE_CPP_TROUBLE_COMPARING_TO_ZERO - // We need to explicitly define comparison operators for `int' - // because the compiler is lame. +// We need to explicitly define comparison operators for `int' +// because the compiler is lame. template inline bool operator==( const nsAutoPtr& lhs, int rhs ) - // specifically to allow |smartPtr == 0| - { - return static_cast(lhs.get()) == reinterpret_cast(rhs); - } +// specifically to allow |smartPtr == 0| +{ + return static_cast(lhs.get()) == reinterpret_cast(rhs); +} template inline bool operator==( int lhs, const nsAutoPtr& rhs ) - // specifically to allow |0 == smartPtr| - { - return reinterpret_cast(lhs) == static_cast(rhs.get()); - } +// specifically to allow |0 == smartPtr| +{ + return reinterpret_cast(lhs) == static_cast(rhs.get()); +} #endif // !defined(HAVE_CPP_TROUBLE_COMPARING_TO_ZERO) @@ -453,398 +454,398 @@ operator==( int lhs, const nsAutoPtr& rhs ) template class nsAutoArrayPtr +{ +private: + void** + begin_assignment() { - private: - void** - begin_assignment() - { - assign(0); - return reinterpret_cast(&mRawPtr); - } + assign(0); + return reinterpret_cast(&mRawPtr); + } - void - assign( T* newPtr ) - { - T* oldPtr = mRawPtr; - mRawPtr = newPtr; - delete [] oldPtr; - } + void + assign( T* newPtr ) + { + T* oldPtr = mRawPtr; + mRawPtr = newPtr; + delete [] oldPtr; + } - private: - T* mRawPtr; +private: + T* mRawPtr; - public: - typedef T element_type; - - ~nsAutoArrayPtr() - { - delete [] mRawPtr; - } +public: + typedef T element_type; - // Constructors + ~nsAutoArrayPtr() + { + delete [] mRawPtr; + } - nsAutoArrayPtr() - : mRawPtr(0) - // default constructor - { - } + // Constructors - nsAutoArrayPtr( T* aRawPtr ) - : mRawPtr(aRawPtr) - // construct from a raw pointer (of the right type) - { - } + nsAutoArrayPtr() + : mRawPtr(0) + // default constructor + { + } - nsAutoArrayPtr( nsAutoArrayPtr& aSmartPtr ) - : mRawPtr( aSmartPtr.forget() ) - // Construct by transferring ownership from another smart pointer. - { - } + nsAutoArrayPtr( T* aRawPtr ) + : mRawPtr(aRawPtr) + // construct from a raw pointer (of the right type) + { + } + + nsAutoArrayPtr( nsAutoArrayPtr& aSmartPtr ) + : mRawPtr( aSmartPtr.forget() ) + // Construct by transferring ownership from another smart pointer. + { + } - // Assignment operators + // Assignment operators - nsAutoArrayPtr& - operator=( T* rhs ) - // assign from a raw pointer (of the right type) - { - assign(rhs); - return *this; - } + nsAutoArrayPtr& + operator=( T* rhs ) + // assign from a raw pointer (of the right type) + { + assign(rhs); + return *this; + } - nsAutoArrayPtr& operator=( nsAutoArrayPtr& rhs ) - // assign by transferring ownership from another smart pointer. - { - assign(rhs.forget()); - return *this; - } + nsAutoArrayPtr& operator=( nsAutoArrayPtr& rhs ) + // assign by transferring ownership from another smart pointer. + { + assign(rhs.forget()); + return *this; + } - // Other pointer operators + // Other pointer operators - T* - get() const - /* - Prefer the implicit conversion provided automatically by - |operator T*() const|. Use |get()| _only_ to resolve - ambiguity. - */ - { - return mRawPtr; - } + T* + get() const + /* + Prefer the implicit conversion provided automatically by + |operator T*() const|. Use |get()| _only_ to resolve + ambiguity. + */ + { + return mRawPtr; + } - operator T*() const - /* - ...makes an |nsAutoArrayPtr| act like its underlying raw pointer - type whenever it is used in a context where a raw pointer - is expected. It is this operator that makes an |nsAutoArrayPtr| - substitutable for a raw pointer. + operator T*() const + /* + ...makes an |nsAutoArrayPtr| act like its underlying raw pointer + type whenever it is used in a context where a raw pointer + is expected. It is this operator that makes an |nsAutoArrayPtr| + substitutable for a raw pointer. - Prefer the implicit use of this operator to calling |get()|, - except where necessary to resolve ambiguity. - */ - { - return get(); - } + Prefer the implicit use of this operator to calling |get()|, + except where necessary to resolve ambiguity. + */ + { + return get(); + } - T* - forget() - { - T* temp = mRawPtr; - mRawPtr = 0; - return temp; - } + T* + forget() + { + T* temp = mRawPtr; + mRawPtr = 0; + return temp; + } - T* - operator->() const - { - NS_PRECONDITION(mRawPtr != 0, "You can't dereference a NULL nsAutoArrayPtr with operator->()."); - return get(); - } + T* + operator->() const + { + NS_PRECONDITION(mRawPtr != 0, "You can't dereference a NULL nsAutoArrayPtr with operator->()."); + return get(); + } - nsAutoArrayPtr* - get_address() - // This is not intended to be used by clients. See |address_of| - // below. - { - return this; - } + nsAutoArrayPtr* + get_address() + // This is not intended to be used by clients. See |address_of| + // below. + { + return this; + } - const nsAutoArrayPtr* - get_address() const - // This is not intended to be used by clients. See |address_of| - // below. - { - return this; - } + const nsAutoArrayPtr* + get_address() const + // This is not intended to be used by clients. See |address_of| + // below. + { + return this; + } - public: - T& - operator*() const - { - NS_PRECONDITION(mRawPtr != 0, "You can't dereference a NULL nsAutoArrayPtr with operator*()."); - return *get(); - } +public: + T& + operator*() const + { + NS_PRECONDITION(mRawPtr != 0, "You can't dereference a NULL nsAutoArrayPtr with operator*()."); + return *get(); + } - T** - StartAssignment() - { + T** + StartAssignment() + { #ifndef NSCAP_FEATURE_INLINE_STARTASSIGNMENT - return reinterpret_cast(begin_assignment()); + return reinterpret_cast(begin_assignment()); #else - assign(0); - return reinterpret_cast(&mRawPtr); + assign(0); + return reinterpret_cast(&mRawPtr); #endif - } + } - size_t - SizeOfExcludingThis(mozilla::MallocSizeOf aMallocSizeOf) const - { - return aMallocSizeOf(mRawPtr); - } + size_t + SizeOfExcludingThis(mozilla::MallocSizeOf aMallocSizeOf) const + { + return aMallocSizeOf(mRawPtr); + } - size_t - SizeOfIncludingThis(mozilla::MallocSizeOf aMallocSizeOf) const - { - return aMallocSizeOf(this) + SizeOfExcludingThis(aMallocSizeOf); - } - }; + size_t + SizeOfIncludingThis(mozilla::MallocSizeOf aMallocSizeOf) const + { + return aMallocSizeOf(this) + SizeOfExcludingThis(aMallocSizeOf); + } +}; template inline nsAutoArrayPtr* address_of( nsAutoArrayPtr& aPtr ) - { - return aPtr.get_address(); - } +{ + return aPtr.get_address(); +} template inline const nsAutoArrayPtr* address_of( const nsAutoArrayPtr& aPtr ) - { - return aPtr.get_address(); - } +{ + return aPtr.get_address(); +} template class nsAutoArrayPtrGetterTransfers - /* - ... +/* + ... - This class is designed to be used for anonymous temporary objects in the - argument list of calls that return COM interface pointers, e.g., + This class is designed to be used for anonymous temporary objects in the + argument list of calls that return COM interface pointers, e.g., - nsAutoArrayPtr fooP; - ...->GetTransferedPointer(getter_Transfers(fooP)) + nsAutoArrayPtr fooP; + ...->GetTransferedPointer(getter_Transfers(fooP)) - DO NOT USE THIS TYPE DIRECTLY IN YOUR CODE. Use |getter_Transfers()| instead. + DO NOT USE THIS TYPE DIRECTLY IN YOUR CODE. Use |getter_Transfers()| instead. - When initialized with a |nsAutoArrayPtr|, as in the example above, it returns - a |void**|, a |T**|, or an |nsISupports**| as needed, that the - outer call (|GetTransferedPointer| in this case) can fill in. + When initialized with a |nsAutoArrayPtr|, as in the example above, it returns + a |void**|, a |T**|, or an |nsISupports**| as needed, that the + outer call (|GetTransferedPointer| in this case) can fill in. - This type should be a nested class inside |nsAutoArrayPtr|. - */ + This type should be a nested class inside |nsAutoArrayPtr|. +*/ +{ +public: + explicit + nsAutoArrayPtrGetterTransfers( nsAutoArrayPtr& aSmartPtr ) + : mTargetSmartPtr(aSmartPtr) { - public: - explicit - nsAutoArrayPtrGetterTransfers( nsAutoArrayPtr& aSmartPtr ) - : mTargetSmartPtr(aSmartPtr) - { - // nothing else to do - } + // nothing else to do + } - operator void**() - { - return reinterpret_cast(mTargetSmartPtr.StartAssignment()); - } + operator void**() + { + return reinterpret_cast(mTargetSmartPtr.StartAssignment()); + } - operator T**() - { - return mTargetSmartPtr.StartAssignment(); - } + operator T**() + { + return mTargetSmartPtr.StartAssignment(); + } - T*& - operator*() - { - return *(mTargetSmartPtr.StartAssignment()); - } + T*& + operator*() + { + return *(mTargetSmartPtr.StartAssignment()); + } - private: - nsAutoArrayPtr& mTargetSmartPtr; - }; +private: + nsAutoArrayPtr& mTargetSmartPtr; +}; template inline nsAutoArrayPtrGetterTransfers getter_Transfers( nsAutoArrayPtr& aSmartPtr ) - /* - Used around a |nsAutoArrayPtr| when - ...makes the class |nsAutoArrayPtrGetterTransfers| invisible. - */ - { - return nsAutoArrayPtrGetterTransfers(aSmartPtr); - } +/* + Used around a |nsAutoArrayPtr| when + ...makes the class |nsAutoArrayPtrGetterTransfers| invisible. +*/ +{ + return nsAutoArrayPtrGetterTransfers(aSmartPtr); +} - // Comparing two |nsAutoArrayPtr|s +// Comparing two |nsAutoArrayPtr|s template inline bool operator==( const nsAutoArrayPtr& lhs, const nsAutoArrayPtr& rhs ) - { - return static_cast(lhs.get()) == static_cast(rhs.get()); - } +{ + return static_cast(lhs.get()) == static_cast(rhs.get()); +} template inline bool operator!=( const nsAutoArrayPtr& lhs, const nsAutoArrayPtr& rhs ) - { - return static_cast(lhs.get()) != static_cast(rhs.get()); - } +{ + return static_cast(lhs.get()) != static_cast(rhs.get()); +} - // Comparing an |nsAutoArrayPtr| to a raw pointer +// Comparing an |nsAutoArrayPtr| to a raw pointer template inline bool operator==( const nsAutoArrayPtr& lhs, const U* rhs ) - { - return static_cast(lhs.get()) == static_cast(rhs); - } +{ + return static_cast(lhs.get()) == static_cast(rhs); +} template inline bool operator==( const U* lhs, const nsAutoArrayPtr& rhs ) - { - return static_cast(lhs) == static_cast(rhs.get()); - } +{ + return static_cast(lhs) == static_cast(rhs.get()); +} template inline bool operator!=( const nsAutoArrayPtr& lhs, const U* rhs ) - { - return static_cast(lhs.get()) != static_cast(rhs); - } +{ + return static_cast(lhs.get()) != static_cast(rhs); +} template inline bool operator!=( const U* lhs, const nsAutoArrayPtr& rhs ) - { - return static_cast(lhs) != static_cast(rhs.get()); - } +{ + return static_cast(lhs) != static_cast(rhs.get()); +} - // To avoid ambiguities caused by the presence of builtin |operator==|s - // creating a situation where one of the |operator==| defined above - // has a better conversion for one argument and the builtin has a - // better conversion for the other argument, define additional - // |operator==| without the |const| on the raw pointer. - // See bug 65664 for details. +// To avoid ambiguities caused by the presence of builtin |operator==|s +// creating a situation where one of the |operator==| defined above +// has a better conversion for one argument and the builtin has a +// better conversion for the other argument, define additional +// |operator==| without the |const| on the raw pointer. +// See bug 65664 for details. #ifndef NSCAP_DONT_PROVIDE_NONCONST_OPEQ template inline bool operator==( const nsAutoArrayPtr& lhs, U* rhs ) - { - return static_cast(lhs.get()) == const_cast(rhs); - } +{ + return static_cast(lhs.get()) == const_cast(rhs); +} template inline bool operator==( U* lhs, const nsAutoArrayPtr& rhs ) - { - return const_cast(lhs) == static_cast(rhs.get()); - } +{ + return const_cast(lhs) == static_cast(rhs.get()); +} template inline bool operator!=( const nsAutoArrayPtr& lhs, U* rhs ) - { - return static_cast(lhs.get()) != const_cast(rhs); - } +{ + return static_cast(lhs.get()) != const_cast(rhs); +} template inline bool operator!=( U* lhs, const nsAutoArrayPtr& rhs ) - { - return const_cast(lhs) != static_cast(rhs.get()); - } +{ + return const_cast(lhs) != static_cast(rhs.get()); +} #endif - // Comparing an |nsAutoArrayPtr| to |0| +// Comparing an |nsAutoArrayPtr| to |0| template inline bool operator==( const nsAutoArrayPtr& lhs, NSCAP_Zero* rhs ) - // specifically to allow |smartPtr == 0| - { - return static_cast(lhs.get()) == reinterpret_cast(rhs); - } +// specifically to allow |smartPtr == 0| +{ + return static_cast(lhs.get()) == reinterpret_cast(rhs); +} template inline bool operator==( NSCAP_Zero* lhs, const nsAutoArrayPtr& rhs ) - // specifically to allow |0 == smartPtr| - { - return reinterpret_cast(lhs) == static_cast(rhs.get()); - } +// specifically to allow |0 == smartPtr| +{ + return reinterpret_cast(lhs) == static_cast(rhs.get()); +} template inline bool operator!=( const nsAutoArrayPtr& lhs, NSCAP_Zero* rhs ) - // specifically to allow |smartPtr != 0| - { - return static_cast(lhs.get()) != reinterpret_cast(rhs); - } +// specifically to allow |smartPtr != 0| +{ + return static_cast(lhs.get()) != reinterpret_cast(rhs); +} template inline bool operator!=( NSCAP_Zero* lhs, const nsAutoArrayPtr& rhs ) - // specifically to allow |0 != smartPtr| - { - return reinterpret_cast(lhs) != static_cast(rhs.get()); - } +// specifically to allow |0 != smartPtr| +{ + return reinterpret_cast(lhs) != static_cast(rhs.get()); +} #ifdef HAVE_CPP_TROUBLE_COMPARING_TO_ZERO - // We need to explicitly define comparison operators for `int' - // because the compiler is lame. +// We need to explicitly define comparison operators for `int' +// because the compiler is lame. template inline bool operator==( const nsAutoArrayPtr& lhs, int rhs ) - // specifically to allow |smartPtr == 0| - { - return static_cast(lhs.get()) == reinterpret_cast(rhs); - } +// specifically to allow |smartPtr == 0| +{ + return static_cast(lhs.get()) == reinterpret_cast(rhs); +} template inline bool operator==( int lhs, const nsAutoArrayPtr& rhs ) - // specifically to allow |0 == smartPtr| - { - return reinterpret_cast(lhs) == static_cast(rhs.get()); - } +// specifically to allow |0 == smartPtr| +{ + return reinterpret_cast(lhs) == static_cast(rhs.get()); +} #endif // !defined(HAVE_CPP_TROUBLE_COMPARING_TO_ZERO) @@ -855,273 +856,273 @@ operator==( int lhs, const nsAutoArrayPtr& rhs ) template class nsRefPtr +{ +private: + + void + assign_with_AddRef( T* rawPtr ) { - private: + if ( rawPtr ) + rawPtr->AddRef(); + assign_assuming_AddRef(rawPtr); + } - void - assign_with_AddRef( T* rawPtr ) - { - if ( rawPtr ) - rawPtr->AddRef(); - assign_assuming_AddRef(rawPtr); - } + void** + begin_assignment() + { + assign_assuming_AddRef(0); + return reinterpret_cast(&mRawPtr); + } - void** - begin_assignment() - { - assign_assuming_AddRef(0); - return reinterpret_cast(&mRawPtr); - } + void + assign_assuming_AddRef( T* newPtr ) + { + T* oldPtr = mRawPtr; + mRawPtr = newPtr; + if ( oldPtr ) + oldPtr->Release(); + } - void - assign_assuming_AddRef( T* newPtr ) - { - T* oldPtr = mRawPtr; - mRawPtr = newPtr; - if ( oldPtr ) - oldPtr->Release(); - } +private: + T* mRawPtr; - private: - T* mRawPtr; +public: + typedef T element_type; - public: - typedef T element_type; - - ~nsRefPtr() - { - if ( mRawPtr ) - mRawPtr->Release(); - } + ~nsRefPtr() + { + if ( mRawPtr ) + mRawPtr->Release(); + } - // Constructors + // Constructors - nsRefPtr() - : mRawPtr(0) - // default constructor - { - } + nsRefPtr() + : mRawPtr(0) + // default constructor + { + } - nsRefPtr(const nsRefPtr& aSmartPtr) - : mRawPtr(aSmartPtr.mRawPtr) - // copy-constructor - { - if ( mRawPtr ) - mRawPtr->AddRef(); - } + nsRefPtr(const nsRefPtr& aSmartPtr) + : mRawPtr(aSmartPtr.mRawPtr) + // copy-constructor + { + if ( mRawPtr ) + mRawPtr->AddRef(); + } - nsRefPtr(nsRefPtr&& aRefPtr) - : mRawPtr(aRefPtr.mRawPtr) - { - aRefPtr.mRawPtr = nullptr; - } + nsRefPtr(nsRefPtr&& aRefPtr) + : mRawPtr(aRefPtr.mRawPtr) + { + aRefPtr.mRawPtr = nullptr; + } - // construct from a raw pointer (of the right type) + // construct from a raw pointer (of the right type) - nsRefPtr(T* aRawPtr) - : mRawPtr(aRawPtr) - { - if ( mRawPtr ) - mRawPtr->AddRef(); - } + nsRefPtr(T* aRawPtr) + : mRawPtr(aRawPtr) + { + if ( mRawPtr ) + mRawPtr->AddRef(); + } - template - nsRefPtr( already_AddRefed& aSmartPtr ) - : mRawPtr(aSmartPtr.take()) - // construct from |already_AddRefed| - { - } + template + nsRefPtr( already_AddRefed& aSmartPtr ) + : mRawPtr(aSmartPtr.take()) + // construct from |already_AddRefed| + { + } - template - nsRefPtr( already_AddRefed&& aSmartPtr ) - : mRawPtr(aSmartPtr.take()) - // construct from |otherRefPtr.forget()| - { - } + template + nsRefPtr( already_AddRefed&& aSmartPtr ) + : mRawPtr(aSmartPtr.take()) + // construct from |otherRefPtr.forget()| + { + } - nsRefPtr( const nsCOMPtr_helper& helper ) - { - void* newRawPtr; - if (NS_FAILED(helper(NS_GET_TEMPLATE_IID(T), &newRawPtr))) - newRawPtr = 0; - mRawPtr = static_cast(newRawPtr); - } + nsRefPtr( const nsCOMPtr_helper& helper ) + { + void* newRawPtr; + if (NS_FAILED(helper(NS_GET_TEMPLATE_IID(T), &newRawPtr))) + newRawPtr = 0; + mRawPtr = static_cast(newRawPtr); + } - // Assignment operators + // Assignment operators - nsRefPtr& - operator=(const nsRefPtr& rhs) - // copy assignment operator - { - assign_with_AddRef(rhs.mRawPtr); - return *this; - } + nsRefPtr& + operator=(const nsRefPtr& rhs) + // copy assignment operator + { + assign_with_AddRef(rhs.mRawPtr); + return *this; + } - nsRefPtr& - operator=( T* rhs ) - // assign from a raw pointer (of the right type) - { - assign_with_AddRef(rhs); - return *this; - } + nsRefPtr& + operator=( T* rhs ) + // assign from a raw pointer (of the right type) + { + assign_with_AddRef(rhs); + return *this; + } - template - nsRefPtr& - operator=( already_AddRefed& rhs ) - // assign from |already_AddRefed| - { - assign_assuming_AddRef(rhs.take()); - return *this; - } + template + nsRefPtr& + operator=( already_AddRefed& rhs ) + // assign from |already_AddRefed| + { + assign_assuming_AddRef(rhs.take()); + return *this; + } - template - nsRefPtr& - operator=( already_AddRefed&& rhs ) - // assign from |otherRefPtr.forget()| - { - assign_assuming_AddRef(rhs.take()); - return *this; - } + template + nsRefPtr& + operator=( already_AddRefed&& rhs ) + // assign from |otherRefPtr.forget()| + { + assign_assuming_AddRef(rhs.take()); + return *this; + } - nsRefPtr& - operator=( const nsCOMPtr_helper& helper ) - { - void* newRawPtr; - if (NS_FAILED(helper(NS_GET_TEMPLATE_IID(T), &newRawPtr))) - newRawPtr = 0; - assign_assuming_AddRef(static_cast(newRawPtr)); - return *this; - } + nsRefPtr& + operator=( const nsCOMPtr_helper& helper ) + { + void* newRawPtr; + if (NS_FAILED(helper(NS_GET_TEMPLATE_IID(T), &newRawPtr))) + newRawPtr = 0; + assign_assuming_AddRef(static_cast(newRawPtr)); + return *this; + } - nsRefPtr& - operator=(nsRefPtr&& aRefPtr) - { - assign_assuming_AddRef(aRefPtr.mRawPtr); - aRefPtr.mRawPtr = nullptr; - return *this; - } + nsRefPtr& + operator=(nsRefPtr&& aRefPtr) + { + assign_assuming_AddRef(aRefPtr.mRawPtr); + aRefPtr.mRawPtr = nullptr; + return *this; + } - // Other pointer operators + // Other pointer operators - void - swap( nsRefPtr& rhs ) - // ...exchange ownership with |rhs|; can save a pair of refcount operations - { - T* temp = rhs.mRawPtr; - rhs.mRawPtr = mRawPtr; - mRawPtr = temp; - } + void + swap( nsRefPtr& rhs ) + // ...exchange ownership with |rhs|; can save a pair of refcount operations + { + T* temp = rhs.mRawPtr; + rhs.mRawPtr = mRawPtr; + mRawPtr = temp; + } - void - swap( T*& rhs ) - // ...exchange ownership with |rhs|; can save a pair of refcount operations - { - T* temp = rhs; - rhs = mRawPtr; - mRawPtr = temp; - } + void + swap( T*& rhs ) + // ...exchange ownership with |rhs|; can save a pair of refcount operations + { + T* temp = rhs; + rhs = mRawPtr; + mRawPtr = temp; + } - already_AddRefed - forget() - // return the value of mRawPtr and null out mRawPtr. Useful for - // already_AddRefed return values. - { - T* temp = 0; - swap(temp); - return already_AddRefed(temp); - } + already_AddRefed + forget() + // return the value of mRawPtr and null out mRawPtr. Useful for + // already_AddRefed return values. + { + T* temp = 0; + swap(temp); + return already_AddRefed(temp); + } - template - void - forget( I** rhs) - // Set the target of rhs to the value of mRawPtr and null out mRawPtr. - // Useful to avoid unnecessary AddRef/Release pairs with "out" - // parameters where rhs bay be a T** or an I** where I is a base class - // of T. - { - NS_ASSERTION(rhs, "Null pointer passed to forget!"); - *rhs = mRawPtr; - mRawPtr = 0; - } + template + void + forget( I** rhs) + // Set the target of rhs to the value of mRawPtr and null out mRawPtr. + // Useful to avoid unnecessary AddRef/Release pairs with "out" + // parameters where rhs bay be a T** or an I** where I is a base class + // of T. + { + NS_ASSERTION(rhs, "Null pointer passed to forget!"); + *rhs = mRawPtr; + mRawPtr = 0; + } - T* - get() const - /* - Prefer the implicit conversion provided automatically by |operator T*() const|. - Use |get()| to resolve ambiguity or to get a castable pointer. - */ - { - return const_cast(mRawPtr); - } + T* + get() const + /* + Prefer the implicit conversion provided automatically by |operator T*() const|. + Use |get()| to resolve ambiguity or to get a castable pointer. + */ + { + return const_cast(mRawPtr); + } - operator T*() const - /* - ...makes an |nsRefPtr| act like its underlying raw pointer type whenever it - is used in a context where a raw pointer is expected. It is this operator - that makes an |nsRefPtr| substitutable for a raw pointer. + operator T*() const + /* + ...makes an |nsRefPtr| act like its underlying raw pointer type whenever it + is used in a context where a raw pointer is expected. It is this operator + that makes an |nsRefPtr| substitutable for a raw pointer. - Prefer the implicit use of this operator to calling |get()|, except where - necessary to resolve ambiguity. - */ - { - return get(); - } + Prefer the implicit use of this operator to calling |get()|, except where + necessary to resolve ambiguity. + */ + { + return get(); + } - T* - operator->() const - { - NS_PRECONDITION(mRawPtr != 0, "You can't dereference a NULL nsRefPtr with operator->()."); - return get(); - } + T* + operator->() const + { + NS_PRECONDITION(mRawPtr != 0, "You can't dereference a NULL nsRefPtr with operator->()."); + return get(); + } - // This operator is needed for gcc <= 4.0.* and for Sun Studio; it - // causes internal compiler errors for some MSVC versions. (It's not - // clear to me whether it should be needed.) + // This operator is needed for gcc <= 4.0.* and for Sun Studio; it + // causes internal compiler errors for some MSVC versions. (It's not + // clear to me whether it should be needed.) #ifndef _MSC_VER - template - U& - operator->*(U V::* aMember) - { - NS_PRECONDITION(mRawPtr != 0, "You can't dereference a NULL nsRefPtr with operator->*()."); - return get()->*aMember; - } + template + U& + operator->*(U V::* aMember) + { + NS_PRECONDITION(mRawPtr != 0, "You can't dereference a NULL nsRefPtr with operator->*()."); + return get()->*aMember; + } #endif - nsRefPtr* - get_address() - // This is not intended to be used by clients. See |address_of| - // below. - { - return this; - } + nsRefPtr* + get_address() + // This is not intended to be used by clients. See |address_of| + // below. + { + return this; + } - const nsRefPtr* - get_address() const - // This is not intended to be used by clients. See |address_of| - // below. - { - return this; - } + const nsRefPtr* + get_address() const + // This is not intended to be used by clients. See |address_of| + // below. + { + return this; + } - public: - T& - operator*() const - { - NS_PRECONDITION(mRawPtr != 0, "You can't dereference a NULL nsRefPtr with operator*()."); - return *get(); - } +public: + T& + operator*() const + { + NS_PRECONDITION(mRawPtr != 0, "You can't dereference a NULL nsRefPtr with operator*()."); + return *get(); + } - T** - StartAssignment() - { + T** + StartAssignment() + { #ifndef NSCAP_FEATURE_INLINE_STARTASSIGNMENT - return reinterpret_cast(begin_assignment()); + return reinterpret_cast(begin_assignment()); #else - assign_assuming_AddRef(0); - return reinterpret_cast(&mRawPtr); + assign_assuming_AddRef(0); + return reinterpret_cast(&mRawPtr); #endif - } - }; + } +}; template inline void @@ -1144,238 +1145,238 @@ template inline nsRefPtr* address_of( nsRefPtr& aPtr ) - { - return aPtr.get_address(); - } +{ + return aPtr.get_address(); +} template inline const nsRefPtr* address_of( const nsRefPtr& aPtr ) - { - return aPtr.get_address(); - } +{ + return aPtr.get_address(); +} template class nsRefPtrGetterAddRefs - /* - ... +/* + ... - This class is designed to be used for anonymous temporary objects in the - argument list of calls that return COM interface pointers, e.g., + This class is designed to be used for anonymous temporary objects in the + argument list of calls that return COM interface pointers, e.g., - nsRefPtr fooP; - ...->GetAddRefedPointer(getter_AddRefs(fooP)) + nsRefPtr fooP; + ...->GetAddRefedPointer(getter_AddRefs(fooP)) - DO NOT USE THIS TYPE DIRECTLY IN YOUR CODE. Use |getter_AddRefs()| instead. + DO NOT USE THIS TYPE DIRECTLY IN YOUR CODE. Use |getter_AddRefs()| instead. - When initialized with a |nsRefPtr|, as in the example above, it returns - a |void**|, a |T**|, or an |nsISupports**| as needed, that the - outer call (|GetAddRefedPointer| in this case) can fill in. + When initialized with a |nsRefPtr|, as in the example above, it returns + a |void**|, a |T**|, or an |nsISupports**| as needed, that the + outer call (|GetAddRefedPointer| in this case) can fill in. - This type should be a nested class inside |nsRefPtr|. - */ + This type should be a nested class inside |nsRefPtr|. +*/ +{ +public: + explicit + nsRefPtrGetterAddRefs( nsRefPtr& aSmartPtr ) + : mTargetSmartPtr(aSmartPtr) { - public: - explicit - nsRefPtrGetterAddRefs( nsRefPtr& aSmartPtr ) - : mTargetSmartPtr(aSmartPtr) - { - // nothing else to do - } + // nothing else to do + } - operator void**() - { - return reinterpret_cast(mTargetSmartPtr.StartAssignment()); - } + operator void**() + { + return reinterpret_cast(mTargetSmartPtr.StartAssignment()); + } - operator T**() - { - return mTargetSmartPtr.StartAssignment(); - } + operator T**() + { + return mTargetSmartPtr.StartAssignment(); + } - T*& - operator*() - { - return *(mTargetSmartPtr.StartAssignment()); - } + T*& + operator*() + { + return *(mTargetSmartPtr.StartAssignment()); + } - private: - nsRefPtr& mTargetSmartPtr; - }; +private: + nsRefPtr& mTargetSmartPtr; +}; template inline nsRefPtrGetterAddRefs getter_AddRefs( nsRefPtr& aSmartPtr ) - /* - Used around a |nsRefPtr| when - ...makes the class |nsRefPtrGetterAddRefs| invisible. - */ - { - return nsRefPtrGetterAddRefs(aSmartPtr); - } +/* + Used around a |nsRefPtr| when + ...makes the class |nsRefPtrGetterAddRefs| invisible. +*/ +{ + return nsRefPtrGetterAddRefs(aSmartPtr); +} - // Comparing two |nsRefPtr|s +// Comparing two |nsRefPtr|s template inline bool operator==( const nsRefPtr& lhs, const nsRefPtr& rhs ) - { - return static_cast(lhs.get()) == static_cast(rhs.get()); - } +{ + return static_cast(lhs.get()) == static_cast(rhs.get()); +} template inline bool operator!=( const nsRefPtr& lhs, const nsRefPtr& rhs ) - { - return static_cast(lhs.get()) != static_cast(rhs.get()); - } +{ + return static_cast(lhs.get()) != static_cast(rhs.get()); +} - // Comparing an |nsRefPtr| to a raw pointer +// Comparing an |nsRefPtr| to a raw pointer template inline bool operator==( const nsRefPtr& lhs, const U* rhs ) - { - return static_cast(lhs.get()) == static_cast(rhs); - } +{ + return static_cast(lhs.get()) == static_cast(rhs); +} template inline bool operator==( const U* lhs, const nsRefPtr& rhs ) - { - return static_cast(lhs) == static_cast(rhs.get()); - } +{ + return static_cast(lhs) == static_cast(rhs.get()); +} template inline bool operator!=( const nsRefPtr& lhs, const U* rhs ) - { - return static_cast(lhs.get()) != static_cast(rhs); - } +{ + return static_cast(lhs.get()) != static_cast(rhs); +} template inline bool operator!=( const U* lhs, const nsRefPtr& rhs ) - { - return static_cast(lhs) != static_cast(rhs.get()); - } +{ + return static_cast(lhs) != static_cast(rhs.get()); +} - // To avoid ambiguities caused by the presence of builtin |operator==|s - // creating a situation where one of the |operator==| defined above - // has a better conversion for one argument and the builtin has a - // better conversion for the other argument, define additional - // |operator==| without the |const| on the raw pointer. - // See bug 65664 for details. +// To avoid ambiguities caused by the presence of builtin |operator==|s +// creating a situation where one of the |operator==| defined above +// has a better conversion for one argument and the builtin has a +// better conversion for the other argument, define additional +// |operator==| without the |const| on the raw pointer. +// See bug 65664 for details. #ifndef NSCAP_DONT_PROVIDE_NONCONST_OPEQ template inline bool operator==( const nsRefPtr& lhs, U* rhs ) - { - return static_cast(lhs.get()) == const_cast(rhs); - } +{ + return static_cast(lhs.get()) == const_cast(rhs); +} template inline bool operator==( U* lhs, const nsRefPtr& rhs ) - { - return const_cast(lhs) == static_cast(rhs.get()); - } +{ + return const_cast(lhs) == static_cast(rhs.get()); +} template inline bool operator!=( const nsRefPtr& lhs, U* rhs ) - { - return static_cast(lhs.get()) != const_cast(rhs); - } +{ + return static_cast(lhs.get()) != const_cast(rhs); +} template inline bool operator!=( U* lhs, const nsRefPtr& rhs ) - { - return const_cast(lhs) != static_cast(rhs.get()); - } +{ + return const_cast(lhs) != static_cast(rhs.get()); +} #endif - // Comparing an |nsRefPtr| to |0| +// Comparing an |nsRefPtr| to |0| template inline bool operator==( const nsRefPtr& lhs, NSCAP_Zero* rhs ) - // specifically to allow |smartPtr == 0| - { - return static_cast(lhs.get()) == reinterpret_cast(rhs); - } +// specifically to allow |smartPtr == 0| +{ + return static_cast(lhs.get()) == reinterpret_cast(rhs); +} template inline bool operator==( NSCAP_Zero* lhs, const nsRefPtr& rhs ) - // specifically to allow |0 == smartPtr| - { - return reinterpret_cast(lhs) == static_cast(rhs.get()); - } +// specifically to allow |0 == smartPtr| +{ + return reinterpret_cast(lhs) == static_cast(rhs.get()); +} template inline bool operator!=( const nsRefPtr& lhs, NSCAP_Zero* rhs ) - // specifically to allow |smartPtr != 0| - { - return static_cast(lhs.get()) != reinterpret_cast(rhs); - } +// specifically to allow |smartPtr != 0| +{ + return static_cast(lhs.get()) != reinterpret_cast(rhs); +} template inline bool operator!=( NSCAP_Zero* lhs, const nsRefPtr& rhs ) - // specifically to allow |0 != smartPtr| - { - return reinterpret_cast(lhs) != static_cast(rhs.get()); - } +// specifically to allow |0 != smartPtr| +{ + return reinterpret_cast(lhs) != static_cast(rhs.get()); +} #ifdef HAVE_CPP_TROUBLE_COMPARING_TO_ZERO - // We need to explicitly define comparison operators for `int' - // because the compiler is lame. +// We need to explicitly define comparison operators for `int' +// because the compiler is lame. template inline bool operator==( const nsRefPtr& lhs, int rhs ) - // specifically to allow |smartPtr == 0| - { - return static_cast(lhs.get()) == reinterpret_cast(rhs); - } +// specifically to allow |smartPtr == 0| +{ + return static_cast(lhs.get()) == reinterpret_cast(rhs); +} template inline bool operator==( int lhs, const nsRefPtr& rhs ) - // specifically to allow |0 == smartPtr| - { - return reinterpret_cast(lhs) == static_cast(rhs.get()); - } +// specifically to allow |0 == smartPtr| +{ + return reinterpret_cast(lhs) == static_cast(rhs.get()); +} #endif // !defined(HAVE_CPP_TROUBLE_COMPARING_TO_ZERO) @@ -1383,9 +1384,9 @@ template inline nsresult CallQueryInterface( nsRefPtr& aSourcePtr, DestinationType** aDestPtr ) - { - return CallQueryInterface(aSourcePtr.get(), aDestPtr); - } +{ + return CallQueryInterface(aSourcePtr.get(), aDestPtr); +} /*****************************************************************************/ diff --git a/xpcom/base/nsAutoRef.h b/xpcom/base/nsAutoRef.h index 9013fd2e8086..495569b36c49 100644 --- a/xpcom/base/nsAutoRef.h +++ b/xpcom/base/nsAutoRef.h @@ -1,5 +1,5 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set shiftwidth=4 tabstop=8 autoindent cindent expandtab: */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ @@ -108,109 +108,109 @@ template class nsAutoRef : public nsAutoRefBase { protected: - typedef nsAutoRef ThisClass; - typedef nsAutoRefBase BaseClass; - typedef nsSimpleRef SimpleRef; - typedef typename BaseClass::RawRefOnly RawRefOnly; - typedef typename BaseClass::LocalSimpleRef LocalSimpleRef; + typedef nsAutoRef ThisClass; + typedef nsAutoRefBase BaseClass; + typedef nsSimpleRef SimpleRef; + typedef typename BaseClass::RawRefOnly RawRefOnly; + typedef typename BaseClass::LocalSimpleRef LocalSimpleRef; public: - nsAutoRef() - { - } + nsAutoRef() + { + } - // Explicit construction is required so as not to risk unintentionally - // releasing the resource associated with a raw ref. - explicit nsAutoRef(RawRefOnly aRefToRelease) - : BaseClass(aRefToRelease) - { - } + // Explicit construction is required so as not to risk unintentionally + // releasing the resource associated with a raw ref. + explicit nsAutoRef(RawRefOnly aRefToRelease) + : BaseClass(aRefToRelease) + { + } - // Construction from a nsReturnRef function return value, which expects - // to give up ownership, transfers ownership. - // (nsReturnRef is converted to const nsReturningRef.) - explicit nsAutoRef(const nsReturningRef& aReturning) - : BaseClass(aReturning) - { - } + // Construction from a nsReturnRef function return value, which expects + // to give up ownership, transfers ownership. + // (nsReturnRef is converted to const nsReturningRef.) + explicit nsAutoRef(const nsReturningRef& aReturning) + : BaseClass(aReturning) + { + } - // The only assignment operator provided is for transferring from an - // nsReturnRef smart reference, which expects to pass its ownership to - // another object. - // - // With raw references and other smart references, the type of the lhs and - // its taking and releasing nature is often not obvious from an assignment - // statement. Assignment from a raw ptr especially is not normally - // expected to release the reference. - // - // Use |steal| for taking ownership from other smart refs. - // - // For raw references, use |own| to indicate intention to have the - // resource released. - // - // Or, to create another owner of the same reference, use an nsCountedRef. + // The only assignment operator provided is for transferring from an + // nsReturnRef smart reference, which expects to pass its ownership to + // another object. + // + // With raw references and other smart references, the type of the lhs and + // its taking and releasing nature is often not obvious from an assignment + // statement. Assignment from a raw ptr especially is not normally + // expected to release the reference. + // + // Use |steal| for taking ownership from other smart refs. + // + // For raw references, use |own| to indicate intention to have the + // resource released. + // + // Or, to create another owner of the same reference, use an nsCountedRef. - ThisClass& operator=(const nsReturningRef& aReturning) - { - BaseClass::steal(aReturning.mReturnRef); - return *this; - } + ThisClass& operator=(const nsReturningRef& aReturning) + { + BaseClass::steal(aReturning.mReturnRef); + return *this; + } - // Conversion to a raw reference allow the nsAutoRef to often be used - // like a raw reference. - operator typename SimpleRef::RawRef() const - { - return this->get(); - } + // Conversion to a raw reference allow the nsAutoRef to often be used + // like a raw reference. + operator typename SimpleRef::RawRef() const + { + return this->get(); + } - // Transfer ownership from another smart reference. - void steal(ThisClass& aOtherRef) - { - BaseClass::steal(aOtherRef); - } + // Transfer ownership from another smart reference. + void steal(ThisClass& aOtherRef) + { + BaseClass::steal(aOtherRef); + } - // Assume ownership of a raw ref. - // - // |own| has similar function to |steal|, and is useful for receiving - // ownership from a return value of a function. It is named differently - // because |own| requires more care to ensure that the function intends to - // give away ownership, and so that |steal| can be safely used, knowing - // that it won't steal ownership from any methods returning raw ptrs to - // data owned by a foreign object. - void own(RawRefOnly aRefToRelease) - { - BaseClass::own(aRefToRelease); - } + // Assume ownership of a raw ref. + // + // |own| has similar function to |steal|, and is useful for receiving + // ownership from a return value of a function. It is named differently + // because |own| requires more care to ensure that the function intends to + // give away ownership, and so that |steal| can be safely used, knowing + // that it won't steal ownership from any methods returning raw ptrs to + // data owned by a foreign object. + void own(RawRefOnly aRefToRelease) + { + BaseClass::own(aRefToRelease); + } - // Exchange ownership with |aOther| - void swap(ThisClass& aOther) - { - LocalSimpleRef temp; - temp.SimpleRef::operator=(*this); - SimpleRef::operator=(aOther); - aOther.SimpleRef::operator=(temp); - } + // Exchange ownership with |aOther| + void swap(ThisClass& aOther) + { + LocalSimpleRef temp; + temp.SimpleRef::operator=(*this); + SimpleRef::operator=(aOther); + aOther.SimpleRef::operator=(temp); + } - // Release the reference now. - void reset() - { - this->SafeRelease(); - LocalSimpleRef empty; - SimpleRef::operator=(empty); - } + // Release the reference now. + void reset() + { + this->SafeRelease(); + LocalSimpleRef empty; + SimpleRef::operator=(empty); + } - // Pass out the reference for a function return values. - nsReturnRef out() - { - return nsReturnRef(this->disown()); - } + // Pass out the reference for a function return values. + nsReturnRef out() + { + return nsReturnRef(this->disown()); + } - // operator->() and disown() are provided by nsAutoRefBase. - // The default nsSimpleRef provides get(). + // operator->() and disown() are provided by nsAutoRefBase. + // The default nsSimpleRef provides get(). private: - // No copy constructor - explicit nsAutoRef(ThisClass& aRefToSteal); + // No copy constructor + explicit nsAutoRef(ThisClass& aRefToSteal); }; /** @@ -232,68 +232,68 @@ template class nsCountedRef : public nsAutoRef { protected: - typedef nsCountedRef ThisClass; - typedef nsAutoRef BaseClass; - typedef nsSimpleRef SimpleRef; - typedef typename BaseClass::RawRef RawRef; + typedef nsCountedRef ThisClass; + typedef nsAutoRef BaseClass; + typedef nsSimpleRef SimpleRef; + typedef typename BaseClass::RawRef RawRef; public: - nsCountedRef() - { - } + nsCountedRef() + { + } - // Construction and assignment from a another nsCountedRef - // or a raw ref copies and increments the ref count. - nsCountedRef(const ThisClass& aRefToCopy) - { - SimpleRef::operator=(aRefToCopy); - SafeAddRef(); - } - ThisClass& operator=(const ThisClass& aRefToCopy) - { - if (this == &aRefToCopy) - return *this; + // Construction and assignment from a another nsCountedRef + // or a raw ref copies and increments the ref count. + nsCountedRef(const ThisClass& aRefToCopy) + { + SimpleRef::operator=(aRefToCopy); + SafeAddRef(); + } + ThisClass& operator=(const ThisClass& aRefToCopy) + { + if (this == &aRefToCopy) + return *this; - this->SafeRelease(); - SimpleRef::operator=(aRefToCopy); - SafeAddRef(); - return *this; - } + this->SafeRelease(); + SimpleRef::operator=(aRefToCopy); + SafeAddRef(); + return *this; + } - // Implicit conversion from another smart ref argument (to a raw ref) is - // accepted here because construction and assignment safely creates a new - // reference without interfering with the reference to copy. - explicit nsCountedRef(RawRef aRefToCopy) - : BaseClass(aRefToCopy) - { - SafeAddRef(); - } - ThisClass& operator=(RawRef aRefToCopy) - { - this->own(aRefToCopy); - SafeAddRef(); - return *this; - } + // Implicit conversion from another smart ref argument (to a raw ref) is + // accepted here because construction and assignment safely creates a new + // reference without interfering with the reference to copy. + explicit nsCountedRef(RawRef aRefToCopy) + : BaseClass(aRefToCopy) + { + SafeAddRef(); + } + ThisClass& operator=(RawRef aRefToCopy) + { + this->own(aRefToCopy); + SafeAddRef(); + return *this; + } - // Construction and assignment from an nsReturnRef function return value, - // which expects to give up ownership, transfers ownership. - explicit nsCountedRef(const nsReturningRef& aReturning) - : BaseClass(aReturning) - { - } - ThisClass& operator=(const nsReturningRef& aReturning) - { - BaseClass::operator=(aReturning); - return *this; - } + // Construction and assignment from an nsReturnRef function return value, + // which expects to give up ownership, transfers ownership. + explicit nsCountedRef(const nsReturningRef& aReturning) + : BaseClass(aReturning) + { + } + ThisClass& operator=(const nsReturningRef& aReturning) + { + BaseClass::operator=(aReturning); + return *this; + } protected: - // Increase the reference count if there is a resource. - void SafeAddRef() - { - if (this->HaveResource()) - this->AddRef(this->get()); - } + // Increase the reference count if there is a resource. + void SafeAddRef() + { + if (this->HaveResource()) + this->AddRef(this->get()); + } }; /** @@ -307,48 +307,48 @@ template class nsReturnRef : public nsAutoRefBase { protected: - typedef nsAutoRefBase BaseClass; - typedef typename BaseClass::RawRefOnly RawRefOnly; + typedef nsAutoRefBase BaseClass; + typedef typename BaseClass::RawRefOnly RawRefOnly; public: - // For constructing a return value with no resource - nsReturnRef() - { - } + // For constructing a return value with no resource + nsReturnRef() + { + } - // For returning a smart reference from a raw reference that must be - // released. Explicit construction is required so as not to risk - // unintentionally releasing the resource associated with a raw ref. - explicit nsReturnRef(RawRefOnly aRefToRelease) - : BaseClass(aRefToRelease) - { - } + // For returning a smart reference from a raw reference that must be + // released. Explicit construction is required so as not to risk + // unintentionally releasing the resource associated with a raw ref. + explicit nsReturnRef(RawRefOnly aRefToRelease) + : BaseClass(aRefToRelease) + { + } - // Copy construction transfers ownership - nsReturnRef(nsReturnRef& aRefToSteal) - : BaseClass(aRefToSteal) - { - } + // Copy construction transfers ownership + nsReturnRef(nsReturnRef& aRefToSteal) + : BaseClass(aRefToSteal) + { + } - nsReturnRef(const nsReturningRef& aReturning) - : BaseClass(aReturning) - { - } + nsReturnRef(const nsReturningRef& aReturning) + : BaseClass(aReturning) + { + } - // Conversion to a temporary (const) object referring to this object so - // that the reference may be passed from a function return value - // (temporary) to another smart reference. There is no need to use this - // explicitly. Simply assign a nsReturnRef function return value to a - // smart reference. - operator nsReturningRef() - { - return nsReturningRef(*this); - } + // Conversion to a temporary (const) object referring to this object so + // that the reference may be passed from a function return value + // (temporary) to another smart reference. There is no need to use this + // explicitly. Simply assign a nsReturnRef function return value to a + // smart reference. + operator nsReturningRef() + { + return nsReturningRef(*this); + } - // No conversion to RawRef operator is provided on nsReturnRef, to ensure - // that the return value is not carelessly assigned to a raw ptr (and the - // resource then released). If passing to a function that takes a raw - // ptr, use get or disown as appropriate. + // No conversion to RawRef operator is provided on nsReturnRef, to ensure + // that the return value is not carelessly assigned to a raw ptr (and the + // resource then released). If passing to a function that takes a raw + // ptr, use get or disown as appropriate. }; /** @@ -370,14 +370,14 @@ template class nsReturningRef { private: - friend class nsReturnRef; + friend class nsReturnRef; - explicit nsReturningRef(nsReturnRef& aReturnRef) - : mReturnRef(aReturnRef) - { - } + explicit nsReturningRef(nsReturnRef& aReturnRef) + : mReturnRef(aReturnRef) + { + } public: - nsReturnRef& mReturnRef; + nsReturnRef& mReturnRef; }; /** @@ -464,10 +464,10 @@ template class nsPointerRefTraits { public: - // The handle is a pointer to T. - typedef T* RawRef; - // A nullptr does not have a resource. - static RawRef Void() { return nullptr; } + // The handle is a pointer to T. + typedef T* RawRef; + // A nullptr does not have a resource. + static RawRef Void() { return nullptr; } }; /** @@ -490,49 +490,49 @@ template class nsSimpleRef : protected nsAutoRefTraits { protected: - // The default implementation uses nsAutoRefTrait. - // Specializations need not define this typedef. - typedef nsAutoRefTraits Traits; - // The type of the handle to the resource. - // A specialization must provide a typedef for RawRef. - typedef typename Traits::RawRef RawRef; + // The default implementation uses nsAutoRefTrait. + // Specializations need not define this typedef. + typedef nsAutoRefTraits Traits; + // The type of the handle to the resource. + // A specialization must provide a typedef for RawRef. + typedef typename Traits::RawRef RawRef; - // Construct with no resource. - // - // If this constructor is not accessible then some limited nsAutoRef - // functionality will still be available, but the default constructor, - // |reset|, and most transfer of ownership methods will not be available. - nsSimpleRef() - : mRawRef(Traits::Void()) - { - } - // Construct with a handle to a resource. - // A specialization must provide this. - nsSimpleRef(RawRef aRawRef) - : mRawRef(aRawRef) - { - } + // Construct with no resource. + // + // If this constructor is not accessible then some limited nsAutoRef + // functionality will still be available, but the default constructor, + // |reset|, and most transfer of ownership methods will not be available. + nsSimpleRef() + : mRawRef(Traits::Void()) + { + } + // Construct with a handle to a resource. + // A specialization must provide this. + nsSimpleRef(RawRef aRawRef) + : mRawRef(aRawRef) + { + } - // Test whether there is an associated resource. A specialization must - // provide this. The function is permitted to always return true if the - // default constructor is not accessible, or if Release (and AddRef) can - // deal with void handles. - bool HaveResource() const - { - return mRawRef != Traits::Void(); - } + // Test whether there is an associated resource. A specialization must + // provide this. The function is permitted to always return true if the + // default constructor is not accessible, or if Release (and AddRef) can + // deal with void handles. + bool HaveResource() const + { + return mRawRef != Traits::Void(); + } public: - // A specialization must provide get() or loose some functionality. This - // is inherited by derived classes and the specialization may choose - // whether it is public or protected. - RawRef get() const - { - return mRawRef; - } + // A specialization must provide get() or loose some functionality. This + // is inherited by derived classes and the specialization may choose + // whether it is public or protected. + RawRef get() const + { + return mRawRef; + } private: - RawRef mRawRef; + RawRef mRawRef; }; @@ -547,120 +547,120 @@ template class nsAutoRefBase : public nsSimpleRef { protected: - typedef nsAutoRefBase ThisClass; - typedef nsSimpleRef SimpleRef; - typedef typename SimpleRef::RawRef RawRef; + typedef nsAutoRefBase ThisClass; + typedef nsSimpleRef SimpleRef; + typedef typename SimpleRef::RawRef RawRef; - nsAutoRefBase() + nsAutoRefBase() + { + } + + // A type for parameters that should be passed a raw ref but should not + // accept implicit conversions (from another smart ref). (The only + // conversion to this type is from a raw ref so only raw refs will be + // accepted.) + class RawRefOnly + { + public: + RawRefOnly(RawRef aRawRef) + : mRawRef(aRawRef) { } - - // A type for parameters that should be passed a raw ref but should not - // accept implicit conversions (from another smart ref). (The only - // conversion to this type is from a raw ref so only raw refs will be - // accepted.) - class RawRefOnly + operator RawRef() const { - public: - RawRefOnly(RawRef aRawRef) - : mRawRef(aRawRef) - { - } - operator RawRef() const - { - return mRawRef; - } - private: - RawRef mRawRef; - }; + return mRawRef; + } + private: + RawRef mRawRef; + }; - // Construction from a raw ref assumes ownership - explicit nsAutoRefBase(RawRefOnly aRefToRelease) - : SimpleRef(aRefToRelease) + // Construction from a raw ref assumes ownership + explicit nsAutoRefBase(RawRefOnly aRefToRelease) + : SimpleRef(aRefToRelease) + { + } + + // Constructors that steal ownership + explicit nsAutoRefBase(ThisClass& aRefToSteal) + : SimpleRef(aRefToSteal.disown()) + { + } + explicit nsAutoRefBase(const nsReturningRef& aReturning) + : SimpleRef(aReturning.mReturnRef.disown()) + { + } + + ~nsAutoRefBase() + { + SafeRelease(); + } + + // An internal class providing access to protected nsSimpleRef + // constructors for construction of temporary simple references (that are + // not ThisClass). + class LocalSimpleRef : public SimpleRef + { + public: + LocalSimpleRef() { } - - // Constructors that steal ownership - explicit nsAutoRefBase(ThisClass& aRefToSteal) - : SimpleRef(aRefToSteal.disown()) + explicit LocalSimpleRef(RawRef aRawRef) + : SimpleRef(aRawRef) { } - explicit nsAutoRefBase(const nsReturningRef& aReturning) - : SimpleRef(aReturning.mReturnRef.disown()) - { - } - - ~nsAutoRefBase() - { - SafeRelease(); - } - - // An internal class providing access to protected nsSimpleRef - // constructors for construction of temporary simple references (that are - // not ThisClass). - class LocalSimpleRef : public SimpleRef - { - public: - LocalSimpleRef() - { - } - explicit LocalSimpleRef(RawRef aRawRef) - : SimpleRef(aRawRef) - { - } - }; + }; private: - ThisClass& operator=(const ThisClass& aSmartRef) MOZ_DELETE; - -public: - RawRef operator->() const - { - return this->get(); - } + ThisClass& operator=(const ThisClass& aSmartRef) MOZ_DELETE; - // Transfer ownership to a raw reference. - // - // THE CALLER MUST ENSURE THAT THE REFERENCE IS EXPLICITLY RELEASED. - // - // Is this really what you want to use? Using this removes any guarantee - // of release. Use nsAutoRef::out() for return values, or an - // nsAutoRef modifiable lvalue for an out parameter. Use disown() when - // the reference must be stored in a POD type object, such as may be - // preferred for a namespace-scope object with static storage duration, - // for example. - RawRef disown() - { - RawRef temp = this->get(); - LocalSimpleRef empty; - SimpleRef::operator=(empty); - return temp; - } +public: + RawRef operator->() const + { + return this->get(); + } + + // Transfer ownership to a raw reference. + // + // THE CALLER MUST ENSURE THAT THE REFERENCE IS EXPLICITLY RELEASED. + // + // Is this really what you want to use? Using this removes any guarantee + // of release. Use nsAutoRef::out() for return values, or an + // nsAutoRef modifiable lvalue for an out parameter. Use disown() when + // the reference must be stored in a POD type object, such as may be + // preferred for a namespace-scope object with static storage duration, + // for example. + RawRef disown() + { + RawRef temp = this->get(); + LocalSimpleRef empty; + SimpleRef::operator=(empty); + return temp; + } protected: - // steal and own are protected because they make no sense on nsReturnRef, - // but steal is implemented on this class for access to aOtherRef.disown() - // when aOtherRef is an nsReturnRef; + // steal and own are protected because they make no sense on nsReturnRef, + // but steal is implemented on this class for access to aOtherRef.disown() + // when aOtherRef is an nsReturnRef; - // Transfer ownership from another smart reference. - void steal(ThisClass& aOtherRef) - { - own(aOtherRef.disown()); - } - // Assume ownership of a raw ref. - void own(RawRefOnly aRefToRelease) - { - SafeRelease(); - LocalSimpleRef ref(aRefToRelease); - SimpleRef::operator=(ref); - } + // Transfer ownership from another smart reference. + void steal(ThisClass& aOtherRef) + { + own(aOtherRef.disown()); + } + // Assume ownership of a raw ref. + void own(RawRefOnly aRefToRelease) + { + SafeRelease(); + LocalSimpleRef ref(aRefToRelease); + SimpleRef::operator=(ref); + } - // Release a resource if there is one. - void SafeRelease() - { - if (this->HaveResource()) - this->Release(this->get()); - } + // Release a resource if there is one. + void SafeRelease() + { + if (this->HaveResource()) + this->Release(this->get()); + } }; #endif // !defined(nsAutoRef_h_) diff --git a/xpcom/base/nsConsoleMessage.cpp b/xpcom/base/nsConsoleMessage.cpp index ca9d728105e5..4cbc6843bfe5 100644 --- a/xpcom/base/nsConsoleMessage.cpp +++ b/xpcom/base/nsConsoleMessage.cpp @@ -1,4 +1,5 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ @@ -13,8 +14,8 @@ NS_IMPL_ISUPPORTS(nsConsoleMessage, nsIConsoleMessage) nsConsoleMessage::nsConsoleMessage() - : mTimeStamp(0), - mMessage() + : mTimeStamp(0), + mMessage() { } diff --git a/xpcom/base/nsConsoleMessage.h b/xpcom/base/nsConsoleMessage.h index 9f92771489a2..d8aa803ca7ea 100644 --- a/xpcom/base/nsConsoleMessage.h +++ b/xpcom/base/nsConsoleMessage.h @@ -1,4 +1,5 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ @@ -13,17 +14,17 @@ class nsConsoleMessage MOZ_FINAL : public nsIConsoleMessage { public: - nsConsoleMessage(); - nsConsoleMessage(const char16_t *message); + nsConsoleMessage(); + nsConsoleMessage(const char16_t *message); - NS_DECL_THREADSAFE_ISUPPORTS - NS_DECL_NSICONSOLEMESSAGE + NS_DECL_THREADSAFE_ISUPPORTS + NS_DECL_NSICONSOLEMESSAGE private: - ~nsConsoleMessage() {} + ~nsConsoleMessage() {} - int64_t mTimeStamp; - nsString mMessage; + int64_t mTimeStamp; + nsString mMessage; }; #endif /* __nsconsolemessage_h__ */ diff --git a/xpcom/base/nsConsoleService.cpp b/xpcom/base/nsConsoleService.cpp index a86f08d77690..1908a0ba5577 100644 --- a/xpcom/base/nsConsoleService.cpp +++ b/xpcom/base/nsConsoleService.cpp @@ -1,4 +1,5 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ @@ -41,63 +42,63 @@ static bool sLoggingEnabled = true; static bool sLoggingBuffered = true; nsConsoleService::nsConsoleService() - : mMessages(nullptr) - , mCurrent(0) - , mFull(false) - , mDeliveringMessage(false) - , mLock("nsConsoleService.mLock") + : mMessages(nullptr) + , mCurrent(0) + , mFull(false) + , mDeliveringMessage(false) + , mLock("nsConsoleService.mLock") { - // XXX grab this from a pref! - // hm, but worry about circularity, bc we want to be able to report - // prefs errs... - mBufferSize = 250; + // XXX grab this from a pref! + // hm, but worry about circularity, bc we want to be able to report + // prefs errs... + mBufferSize = 250; } nsConsoleService::~nsConsoleService() { - uint32_t i = 0; - while (i < mBufferSize && mMessages[i] != nullptr) { - NS_RELEASE(mMessages[i]); - i++; - } + uint32_t i = 0; + while (i < mBufferSize && mMessages[i] != nullptr) { + NS_RELEASE(mMessages[i]); + i++; + } - if (mMessages) - nsMemory::Free(mMessages); + if (mMessages) + nsMemory::Free(mMessages); } class AddConsolePrefWatchers : public nsRunnable { public: - AddConsolePrefWatchers(nsConsoleService* aConsole) : mConsole(aConsole) {} + AddConsolePrefWatchers(nsConsoleService* aConsole) : mConsole(aConsole) {} - NS_IMETHOD Run() - { - Preferences::AddBoolVarCache(&sLoggingEnabled, "consoleservice.enabled", true); - Preferences::AddBoolVarCache(&sLoggingBuffered, "consoleservice.buffered", true); - if (!sLoggingBuffered) { - mConsole->Reset(); - } - return NS_OK; + NS_IMETHOD Run() + { + Preferences::AddBoolVarCache(&sLoggingEnabled, "consoleservice.enabled", true); + Preferences::AddBoolVarCache(&sLoggingBuffered, "consoleservice.buffered", true); + if (!sLoggingBuffered) { + mConsole->Reset(); } + return NS_OK; + } private: - nsRefPtr mConsole; + nsRefPtr mConsole; }; nsresult nsConsoleService::Init() { - mMessages = (nsIConsoleMessage **) - nsMemory::Alloc(mBufferSize * sizeof(nsIConsoleMessage *)); - if (!mMessages) - return NS_ERROR_OUT_OF_MEMORY; + mMessages = (nsIConsoleMessage **) + nsMemory::Alloc(mBufferSize * sizeof(nsIConsoleMessage *)); + if (!mMessages) + return NS_ERROR_OUT_OF_MEMORY; - // Array elements should be 0 initially for circular buffer algorithm. - memset(mMessages, 0, mBufferSize * sizeof(nsIConsoleMessage *)); + // Array elements should be 0 initially for circular buffer algorithm. + memset(mMessages, 0, mBufferSize * sizeof(nsIConsoleMessage *)); - NS_DispatchToMainThread(new AddConsolePrefWatchers(this)); + NS_DispatchToMainThread(new AddConsolePrefWatchers(this)); - return NS_OK; + return NS_OK; } namespace { @@ -105,16 +106,16 @@ namespace { class LogMessageRunnable : public nsRunnable { public: - LogMessageRunnable(nsIConsoleMessage* message, nsConsoleService* service) - : mMessage(message) - , mService(service) - { } + LogMessageRunnable(nsIConsoleMessage* message, nsConsoleService* service) + : mMessage(message) + , mService(service) + { } - NS_DECL_NSIRUNNABLE + NS_DECL_NSIRUNNABLE private: - nsCOMPtr mMessage; - nsRefPtr mService; + nsCOMPtr mMessage; + nsRefPtr mService; }; typedef nsCOMArray ListenerArrayType; @@ -123,29 +124,29 @@ PLDHashOperator CollectCurrentListeners(nsISupports* aKey, nsIConsoleListener* aValue, void* closure) { - ListenerArrayType* listeners = static_cast(closure); - listeners->AppendObject(aValue); - return PL_DHASH_NEXT; + ListenerArrayType* listeners = static_cast(closure); + listeners->AppendObject(aValue); + return PL_DHASH_NEXT; } NS_IMETHODIMP LogMessageRunnable::Run() { - MOZ_ASSERT(NS_IsMainThread()); + MOZ_ASSERT(NS_IsMainThread()); - // Snapshot of listeners so that we don't reenter this hash during - // enumeration. - nsCOMArray listeners; - mService->EnumerateListeners(CollectCurrentListeners, &listeners); + // Snapshot of listeners so that we don't reenter this hash during + // enumeration. + nsCOMArray listeners; + mService->EnumerateListeners(CollectCurrentListeners, &listeners); - mService->SetIsDelivering(); + mService->SetIsDelivering(); - for (int32_t i = 0; i < listeners.Count(); ++i) - listeners[i]->Observe(mMessage); + for (int32_t i = 0; i < listeners.Count(); ++i) + listeners[i]->Observe(mMessage); - mService->SetDoneDelivering(); + mService->SetDoneDelivering(); - return NS_OK; + return NS_OK; } } // anonymous namespace @@ -154,220 +155,220 @@ LogMessageRunnable::Run() NS_IMETHODIMP nsConsoleService::LogMessage(nsIConsoleMessage *message) { - return LogMessageWithMode(message, OutputToLog); + return LogMessageWithMode(message, OutputToLog); } nsresult nsConsoleService::LogMessageWithMode(nsIConsoleMessage *message, nsConsoleService::OutputMode outputMode) { - if (message == nullptr) - return NS_ERROR_INVALID_ARG; + if (message == nullptr) + return NS_ERROR_INVALID_ARG; - if (!sLoggingEnabled) { - return NS_OK; - } + if (!sLoggingEnabled) { + return NS_OK; + } - if (NS_IsMainThread() && mDeliveringMessage) { - nsCString msg; - message->ToString(msg); - NS_WARNING(nsPrintfCString("Reentrancy error: some client attempted " - "to display a message to the console while in a console listener. " - "The following message was discarded: \"%s\"", msg.get()).get()); - return NS_ERROR_FAILURE; - } + if (NS_IsMainThread() && mDeliveringMessage) { + nsCString msg; + message->ToString(msg); + NS_WARNING(nsPrintfCString("Reentrancy error: some client attempted " + "to display a message to the console while in a console listener. " + "The following message was discarded: \"%s\"", msg.get()).get()); + return NS_ERROR_FAILURE; + } - nsRefPtr r; - nsIConsoleMessage *retiredMessage; + nsRefPtr r; + nsIConsoleMessage *retiredMessage; - if (sLoggingBuffered) { - NS_ADDREF(message); // early, in case it's same as replaced below. - } + if (sLoggingBuffered) { + NS_ADDREF(message); // early, in case it's same as replaced below. + } - /* - * Lock while updating buffer, and while taking snapshot of - * listeners array. - */ - { - MutexAutoLock lock(mLock); + /* + * Lock while updating buffer, and while taking snapshot of + * listeners array. + */ + { + MutexAutoLock lock(mLock); #if defined(ANDROID) - if (outputMode == OutputToLog) - { - nsCString msg; - message->ToString(msg); - __android_log_print(ANDROID_LOG_ERROR, "GeckoConsole", - "%s", msg.get()); - } + if (outputMode == OutputToLog) + { + nsCString msg; + message->ToString(msg); + __android_log_print(ANDROID_LOG_ERROR, "GeckoConsole", + "%s", msg.get()); + } #endif #ifdef XP_WIN - if (IsDebuggerPresent()) { - nsString msg; - message->GetMessageMoz(getter_Copies(msg)); - msg.AppendLiteral("\n"); - OutputDebugStringW(msg.get()); - } + if (IsDebuggerPresent()) { + nsString msg; + message->GetMessageMoz(getter_Copies(msg)); + msg.AppendLiteral("\n"); + OutputDebugStringW(msg.get()); + } #endif - /* - * If there's already a message in the slot we're about to replace, - * we've wrapped around, and we need to release the old message. We - * save a pointer to it, so we can release below outside the lock. - */ - retiredMessage = mMessages[mCurrent]; + /* + * If there's already a message in the slot we're about to replace, + * we've wrapped around, and we need to release the old message. We + * save a pointer to it, so we can release below outside the lock. + */ + retiredMessage = mMessages[mCurrent]; - if (sLoggingBuffered) { - mMessages[mCurrent++] = message; - if (mCurrent == mBufferSize) { - mCurrent = 0; // wrap around. - mFull = true; - } - } - - if (mListeners.Count() > 0) { - r = new LogMessageRunnable(message, this); - } + if (sLoggingBuffered) { + mMessages[mCurrent++] = message; + if (mCurrent == mBufferSize) { + mCurrent = 0; // wrap around. + mFull = true; + } } - if (retiredMessage != nullptr) - NS_RELEASE(retiredMessage); + if (mListeners.Count() > 0) { + r = new LogMessageRunnable(message, this); + } + } - if (r) - NS_DispatchToMainThread(r); + if (retiredMessage != nullptr) + NS_RELEASE(retiredMessage); - return NS_OK; + if (r) + NS_DispatchToMainThread(r); + + return NS_OK; } void nsConsoleService::EnumerateListeners(ListenerHash::EnumReadFunction aFunction, void* aClosure) { - MutexAutoLock lock(mLock); - mListeners.EnumerateRead(aFunction, aClosure); + MutexAutoLock lock(mLock); + mListeners.EnumerateRead(aFunction, aClosure); } NS_IMETHODIMP nsConsoleService::LogStringMessage(const char16_t *message) { - if (!sLoggingEnabled) { - return NS_OK; - } + if (!sLoggingEnabled) { + return NS_OK; + } - nsRefPtr msg(new nsConsoleMessage(message)); - return this->LogMessage(msg); + nsRefPtr msg(new nsConsoleMessage(message)); + return this->LogMessage(msg); } NS_IMETHODIMP nsConsoleService::GetMessageArray(uint32_t *count, nsIConsoleMessage ***messages) { - nsIConsoleMessage **messageArray; + nsIConsoleMessage **messageArray; + /* + * Lock the whole method, as we don't want anyone mucking with mCurrent or + * mFull while we're copying out the buffer. + */ + MutexAutoLock lock(mLock); + + if (mCurrent == 0 && !mFull) { /* - * Lock the whole method, as we don't want anyone mucking with mCurrent or - * mFull while we're copying out the buffer. + * Make a 1-length output array so that nobody gets confused, + * and return a count of 0. This should result in a 0-length + * array object when called from script. */ - MutexAutoLock lock(mLock); - - if (mCurrent == 0 && !mFull) { - /* - * Make a 1-length output array so that nobody gets confused, - * and return a count of 0. This should result in a 0-length - * array object when called from script. - */ - messageArray = (nsIConsoleMessage **) - nsMemory::Alloc(sizeof (nsIConsoleMessage *)); - *messageArray = nullptr; - *messages = messageArray; - *count = 0; - - return NS_OK; - } - - uint32_t resultSize = mFull ? mBufferSize : mCurrent; - messageArray = - (nsIConsoleMessage **)nsMemory::Alloc((sizeof (nsIConsoleMessage *)) - * resultSize); - - if (messageArray == nullptr) { - *messages = nullptr; - *count = 0; - return NS_ERROR_FAILURE; - } - - uint32_t i; - if (mFull) { - for (i = 0; i < mBufferSize; i++) { - // if full, fill the buffer starting from mCurrent (which'll be - // oldest) wrapping around the buffer to the most recent. - messageArray[i] = mMessages[(mCurrent + i) % mBufferSize]; - NS_ADDREF(messageArray[i]); - } - } else { - for (i = 0; i < mCurrent; i++) { - messageArray[i] = mMessages[i]; - NS_ADDREF(messageArray[i]); - } - } - *count = resultSize; + messageArray = (nsIConsoleMessage **) + nsMemory::Alloc(sizeof (nsIConsoleMessage *)); + *messageArray = nullptr; *messages = messageArray; + *count = 0; return NS_OK; + } + + uint32_t resultSize = mFull ? mBufferSize : mCurrent; + messageArray = + (nsIConsoleMessage **)nsMemory::Alloc((sizeof (nsIConsoleMessage *)) + * resultSize); + + if (messageArray == nullptr) { + *messages = nullptr; + *count = 0; + return NS_ERROR_FAILURE; + } + + uint32_t i; + if (mFull) { + for (i = 0; i < mBufferSize; i++) { + // if full, fill the buffer starting from mCurrent (which'll be + // oldest) wrapping around the buffer to the most recent. + messageArray[i] = mMessages[(mCurrent + i) % mBufferSize]; + NS_ADDREF(messageArray[i]); + } + } else { + for (i = 0; i < mCurrent; i++) { + messageArray[i] = mMessages[i]; + NS_ADDREF(messageArray[i]); + } + } + *count = resultSize; + *messages = messageArray; + + return NS_OK; } NS_IMETHODIMP nsConsoleService::RegisterListener(nsIConsoleListener *listener) { - if (!NS_IsMainThread()) { - NS_ERROR("nsConsoleService::RegisterListener is main thread only."); - return NS_ERROR_NOT_SAME_THREAD; - } + if (!NS_IsMainThread()) { + NS_ERROR("nsConsoleService::RegisterListener is main thread only."); + return NS_ERROR_NOT_SAME_THREAD; + } - nsCOMPtr canonical = do_QueryInterface(listener); + nsCOMPtr canonical = do_QueryInterface(listener); - MutexAutoLock lock(mLock); - if (mListeners.GetWeak(canonical)) { - // Reregistering a listener isn't good - return NS_ERROR_FAILURE; - } - mListeners.Put(canonical, listener); - return NS_OK; + MutexAutoLock lock(mLock); + if (mListeners.GetWeak(canonical)) { + // Reregistering a listener isn't good + return NS_ERROR_FAILURE; + } + mListeners.Put(canonical, listener); + return NS_OK; } NS_IMETHODIMP nsConsoleService::UnregisterListener(nsIConsoleListener *listener) { - if (!NS_IsMainThread()) { - NS_ERROR("nsConsoleService::UnregisterListener is main thread only."); - return NS_ERROR_NOT_SAME_THREAD; - } + if (!NS_IsMainThread()) { + NS_ERROR("nsConsoleService::UnregisterListener is main thread only."); + return NS_ERROR_NOT_SAME_THREAD; + } - nsCOMPtr canonical = do_QueryInterface(listener); + nsCOMPtr canonical = do_QueryInterface(listener); - MutexAutoLock lock(mLock); + MutexAutoLock lock(mLock); - if (!mListeners.GetWeak(canonical)) { - // Unregistering a listener that was never registered? - return NS_ERROR_FAILURE; - } - mListeners.Remove(canonical); - return NS_OK; + if (!mListeners.GetWeak(canonical)) { + // Unregistering a listener that was never registered? + return NS_ERROR_FAILURE; + } + mListeners.Remove(canonical); + return NS_OK; } NS_IMETHODIMP nsConsoleService::Reset() { - /* - * Make sure nobody trips into the buffer while it's being reset - */ - MutexAutoLock lock(mLock); + /* + * Make sure nobody trips into the buffer while it's being reset + */ + MutexAutoLock lock(mLock); - mCurrent = 0; - mFull = false; + mCurrent = 0; + mFull = false; - /* - * Free all messages stored so far (cf. destructor) - */ - for (uint32_t i = 0; i < mBufferSize && mMessages[i] != nullptr; i++) - NS_RELEASE(mMessages[i]); + /* + * Free all messages stored so far (cf. destructor) + */ + for (uint32_t i = 0; i < mBufferSize && mMessages[i] != nullptr; i++) + NS_RELEASE(mMessages[i]); - return NS_OK; + return NS_OK; } diff --git a/xpcom/base/nsConsoleService.h b/xpcom/base/nsConsoleService.h index ef373fc4e6b4..f2125dd65ce8 100644 --- a/xpcom/base/nsConsoleService.h +++ b/xpcom/base/nsConsoleService.h @@ -1,4 +1,5 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ @@ -21,62 +22,62 @@ class nsConsoleService MOZ_FINAL : public nsIConsoleService { public: - nsConsoleService(); - nsresult Init(); + nsConsoleService(); + nsresult Init(); - NS_DECL_THREADSAFE_ISUPPORTS - NS_DECL_NSICONSOLESERVICE + NS_DECL_THREADSAFE_ISUPPORTS + NS_DECL_NSICONSOLESERVICE - void SetIsDelivering() { - MOZ_ASSERT(NS_IsMainThread()); - MOZ_ASSERT(!mDeliveringMessage); - mDeliveringMessage = true; - } + void SetIsDelivering() { + MOZ_ASSERT(NS_IsMainThread()); + MOZ_ASSERT(!mDeliveringMessage); + mDeliveringMessage = true; + } - void SetDoneDelivering() { - MOZ_ASSERT(NS_IsMainThread()); - MOZ_ASSERT(mDeliveringMessage); - mDeliveringMessage = false; - } + void SetDoneDelivering() { + MOZ_ASSERT(NS_IsMainThread()); + MOZ_ASSERT(mDeliveringMessage); + mDeliveringMessage = false; + } - // This is a variant of LogMessage which allows the caller to determine - // if the message should be output to an OS-specific log. This is used on - // B2G to control whether the message is logged to the android log or not. + // This is a variant of LogMessage which allows the caller to determine + // if the message should be output to an OS-specific log. This is used on + // B2G to control whether the message is logged to the android log or not. - enum OutputMode { - SuppressLog, - OutputToLog - }; - virtual nsresult LogMessageWithMode(nsIConsoleMessage *message, OutputMode outputMode); + enum OutputMode { + SuppressLog, + OutputToLog + }; + virtual nsresult LogMessageWithMode(nsIConsoleMessage *message, OutputMode outputMode); - typedef nsInterfaceHashtable ListenerHash; - void EnumerateListeners(ListenerHash::EnumReadFunction aFunction, void* aClosure); + typedef nsInterfaceHashtable ListenerHash; + void EnumerateListeners(ListenerHash::EnumReadFunction aFunction, void* aClosure); private: - ~nsConsoleService(); + ~nsConsoleService(); - // Circular buffer of saved messages - nsIConsoleMessage **mMessages; + // Circular buffer of saved messages + nsIConsoleMessage **mMessages; - // How big? - uint32_t mBufferSize; + // How big? + uint32_t mBufferSize; - // Index of slot in mMessages that'll be filled by *next* log message - uint32_t mCurrent; + // Index of slot in mMessages that'll be filled by *next* log message + uint32_t mCurrent; - // Is the buffer full? (Has mCurrent wrapped around at least once?) - bool mFull; + // Is the buffer full? (Has mCurrent wrapped around at least once?) + bool mFull; - // Are we currently delivering a console message on the main thread? If - // so, we suppress incoming messages on the main thread only, to avoid - // infinite repitition. - bool mDeliveringMessage; + // Are we currently delivering a console message on the main thread? If + // so, we suppress incoming messages on the main thread only, to avoid + // infinite repitition. + bool mDeliveringMessage; - // Listeners to notify whenever a new message is logged. - ListenerHash mListeners; + // Listeners to notify whenever a new message is logged. + ListenerHash mListeners; - // To serialize interesting methods. - mozilla::Mutex mLock; + // To serialize interesting methods. + mozilla::Mutex mLock; }; #endif /* __nsconsoleservice_h__ */ diff --git a/xpcom/base/nsCrashOnException.cpp b/xpcom/base/nsCrashOnException.cpp index bff88bbfb412..37627b89b975 100644 --- a/xpcom/base/nsCrashOnException.cpp +++ b/xpcom/base/nsCrashOnException.cpp @@ -1,4 +1,5 @@ /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ @@ -26,7 +27,7 @@ static int ReportException(EXCEPTION_POINTERS *aExceptionInfo) XPCOM_API(LRESULT) CallWindowProcCrashProtected(WNDPROC wndProc, HWND hWnd, UINT msg, - WPARAM wParam, LPARAM lParam) + WPARAM wParam, LPARAM lParam) { MOZ_SEH_TRY { return wndProc(hWnd, msg, wParam, lParam); diff --git a/xpcom/base/nsCrashOnException.h b/xpcom/base/nsCrashOnException.h index 1c3b0a9ca5c7..5f100b40dfd9 100644 --- a/xpcom/base/nsCrashOnException.h +++ b/xpcom/base/nsCrashOnException.h @@ -1,4 +1,5 @@ /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ @@ -14,7 +15,7 @@ namespace mozilla { // Call a given window procedure, and catch any Win32 exceptions raised from it, // and report them as crashes. XPCOM_API(LRESULT) CallWindowProcCrashProtected(WNDPROC wndProc, HWND hWnd, UINT msg, - WPARAM wParam, LPARAM lParam); + WPARAM wParam, LPARAM lParam); } diff --git a/xpcom/base/nsCycleCollector.cpp b/xpcom/base/nsCycleCollector.cpp index 7549ab972c7b..8a9d26214ed7 100644 --- a/xpcom/base/nsCycleCollector.cpp +++ b/xpcom/base/nsCycleCollector.cpp @@ -1,5 +1,5 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ -/* vim: set ts=8 sts=4 et sw=4 tw=80: */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ @@ -233,95 +233,95 @@ using namespace mozilla; struct nsCycleCollectorParams { - bool mLogAll; - bool mLogShutdown; - bool mAllTracesAll; - bool mAllTracesShutdown; - bool mLogThisThread; + bool mLogAll; + bool mLogShutdown; + bool mAllTracesAll; + bool mAllTracesShutdown; + bool mLogThisThread; - nsCycleCollectorParams() : - mLogAll (PR_GetEnv("MOZ_CC_LOG_ALL") != nullptr), - mLogShutdown (PR_GetEnv("MOZ_CC_LOG_SHUTDOWN") != nullptr), - mAllTracesAll(false), - mAllTracesShutdown(false) - { - const char* logThreadEnv = PR_GetEnv("MOZ_CC_LOG_THREAD"); - bool threadLogging = true; - if (logThreadEnv && !!strcmp(logThreadEnv, "all")) { - if (NS_IsMainThread()) { - threadLogging = !strcmp(logThreadEnv, "main"); - } else { - threadLogging = !strcmp(logThreadEnv, "worker"); - } - } - - const char* logProcessEnv = PR_GetEnv("MOZ_CC_LOG_PROCESS"); - bool processLogging = true; - if (logProcessEnv && !!strcmp(logProcessEnv, "all")) { - switch (XRE_GetProcessType()) { - case GeckoProcessType_Default: - processLogging = !strcmp(logProcessEnv, "main"); - break; - case GeckoProcessType_Plugin: - processLogging = !strcmp(logProcessEnv, "plugins"); - break; - case GeckoProcessType_Content: - processLogging = !strcmp(logProcessEnv, "content"); - break; - default: - processLogging = false; - break; - } - } - mLogThisThread = threadLogging && processLogging; - - const char* allTracesEnv = PR_GetEnv("MOZ_CC_ALL_TRACES"); - if (allTracesEnv) { - if (!strcmp(allTracesEnv, "all")) { - mAllTracesAll = true; - } else if (!strcmp(allTracesEnv, "shutdown")) { - mAllTracesShutdown = true; - } - } + nsCycleCollectorParams() : + mLogAll (PR_GetEnv("MOZ_CC_LOG_ALL") != nullptr), + mLogShutdown (PR_GetEnv("MOZ_CC_LOG_SHUTDOWN") != nullptr), + mAllTracesAll(false), + mAllTracesShutdown(false) + { + const char* logThreadEnv = PR_GetEnv("MOZ_CC_LOG_THREAD"); + bool threadLogging = true; + if (logThreadEnv && !!strcmp(logThreadEnv, "all")) { + if (NS_IsMainThread()) { + threadLogging = !strcmp(logThreadEnv, "main"); + } else { + threadLogging = !strcmp(logThreadEnv, "worker"); + } } - bool LogThisCC(bool aIsShutdown) - { - return (mLogAll || (aIsShutdown && mLogShutdown)) && mLogThisThread; + const char* logProcessEnv = PR_GetEnv("MOZ_CC_LOG_PROCESS"); + bool processLogging = true; + if (logProcessEnv && !!strcmp(logProcessEnv, "all")) { + switch (XRE_GetProcessType()) { + case GeckoProcessType_Default: + processLogging = !strcmp(logProcessEnv, "main"); + break; + case GeckoProcessType_Plugin: + processLogging = !strcmp(logProcessEnv, "plugins"); + break; + case GeckoProcessType_Content: + processLogging = !strcmp(logProcessEnv, "content"); + break; + default: + processLogging = false; + break; + } } + mLogThisThread = threadLogging && processLogging; - bool AllTracesThisCC(bool aIsShutdown) - { - return mAllTracesAll || (aIsShutdown && mAllTracesShutdown); + const char* allTracesEnv = PR_GetEnv("MOZ_CC_ALL_TRACES"); + if (allTracesEnv) { + if (!strcmp(allTracesEnv, "all")) { + mAllTracesAll = true; + } else if (!strcmp(allTracesEnv, "shutdown")) { + mAllTracesShutdown = true; + } } + } + + bool LogThisCC(bool aIsShutdown) + { + return (mLogAll || (aIsShutdown && mLogShutdown)) && mLogThisThread; + } + + bool AllTracesThisCC(bool aIsShutdown) + { + return mAllTracesAll || (aIsShutdown && mAllTracesShutdown); + } }; #ifdef COLLECT_TIME_DEBUG class TimeLog { public: - TimeLog() : mLastCheckpoint(TimeStamp::Now()) {} + TimeLog() : mLastCheckpoint(TimeStamp::Now()) {} - void - Checkpoint(const char* aEvent) - { - TimeStamp now = TimeStamp::Now(); - uint32_t dur = (uint32_t) ((now - mLastCheckpoint).ToMilliseconds()); - if (dur > 0) { - printf("cc: %s took %dms\n", aEvent, dur); - } - mLastCheckpoint = now; + void + Checkpoint(const char* aEvent) + { + TimeStamp now = TimeStamp::Now(); + uint32_t dur = (uint32_t) ((now - mLastCheckpoint).ToMilliseconds()); + if (dur > 0) { + printf("cc: %s took %dms\n", aEvent, dur); } + mLastCheckpoint = now; + } private: - TimeStamp mLastCheckpoint; + TimeStamp mLastCheckpoint; }; #else class TimeLog { public: - TimeLog() {} - void Checkpoint(const char* aEvent) {} + TimeLog() {} + void Checkpoint(const char* aEvent) {} }; #endif @@ -335,154 +335,154 @@ struct PtrInfo; class EdgePool { public: - // EdgePool allocates arrays of void*, primarily to hold PtrInfo*. - // However, at the end of a block, the last two pointers are a null - // and then a void** pointing to the next block. This allows - // EdgePool::Iterators to be a single word but still capable of crossing - // block boundaries. + // EdgePool allocates arrays of void*, primarily to hold PtrInfo*. + // However, at the end of a block, the last two pointers are a null + // and then a void** pointing to the next block. This allows + // EdgePool::Iterators to be a single word but still capable of crossing + // block boundaries. - EdgePool() - { - mSentinelAndBlocks[0].block = nullptr; - mSentinelAndBlocks[1].block = nullptr; + EdgePool() + { + mSentinelAndBlocks[0].block = nullptr; + mSentinelAndBlocks[1].block = nullptr; + } + + ~EdgePool() + { + MOZ_ASSERT(!mSentinelAndBlocks[0].block && + !mSentinelAndBlocks[1].block, + "Didn't call Clear()?"); + } + + void Clear() + { + Block *b = Blocks(); + while (b) { + Block *next = b->Next(); + delete b; + b = next; } - ~EdgePool() - { - MOZ_ASSERT(!mSentinelAndBlocks[0].block && - !mSentinelAndBlocks[1].block, - "Didn't call Clear()?"); - } - - void Clear() - { - Block *b = Blocks(); - while (b) { - Block *next = b->Next(); - delete b; - b = next; - } - - mSentinelAndBlocks[0].block = nullptr; - mSentinelAndBlocks[1].block = nullptr; - } + mSentinelAndBlocks[0].block = nullptr; + mSentinelAndBlocks[1].block = nullptr; + } #ifdef DEBUG - bool IsEmpty() - { - return !mSentinelAndBlocks[0].block && - !mSentinelAndBlocks[1].block; - } + bool IsEmpty() + { + return !mSentinelAndBlocks[0].block && + !mSentinelAndBlocks[1].block; + } #endif private: - struct Block; - union PtrInfoOrBlock { - // Use a union to avoid reinterpret_cast and the ensuing - // potential aliasing bugs. - PtrInfo *ptrInfo; - Block *block; - }; - struct Block { - enum { BlockSize = 16 * 1024 }; + struct Block; + union PtrInfoOrBlock { + // Use a union to avoid reinterpret_cast and the ensuing + // potential aliasing bugs. + PtrInfo *ptrInfo; + Block *block; + }; + struct Block { + enum { BlockSize = 16 * 1024 }; - PtrInfoOrBlock mPointers[BlockSize]; - Block() { - mPointers[BlockSize - 2].block = nullptr; // sentinel - mPointers[BlockSize - 1].block = nullptr; // next block pointer - } - Block*& Next() { return mPointers[BlockSize - 1].block; } - PtrInfoOrBlock* Start() { return &mPointers[0]; } - PtrInfoOrBlock* End() { return &mPointers[BlockSize - 2]; } - }; + PtrInfoOrBlock mPointers[BlockSize]; + Block() { + mPointers[BlockSize - 2].block = nullptr; // sentinel + mPointers[BlockSize - 1].block = nullptr; // next block pointer + } + Block*& Next() { return mPointers[BlockSize - 1].block; } + PtrInfoOrBlock* Start() { return &mPointers[0]; } + PtrInfoOrBlock* End() { return &mPointers[BlockSize - 2]; } + }; - // Store the null sentinel so that we can have valid iterators - // before adding any edges and without adding any blocks. - PtrInfoOrBlock mSentinelAndBlocks[2]; + // Store the null sentinel so that we can have valid iterators + // before adding any edges and without adding any blocks. + PtrInfoOrBlock mSentinelAndBlocks[2]; - Block*& Blocks() { return mSentinelAndBlocks[1].block; } - Block* Blocks() const { return mSentinelAndBlocks[1].block; } + Block*& Blocks() { return mSentinelAndBlocks[1].block; } + Block* Blocks() const { return mSentinelAndBlocks[1].block; } public: - class Iterator + class Iterator + { + public: + Iterator() : mPointer(nullptr) {} + Iterator(PtrInfoOrBlock *aPointer) : mPointer(aPointer) {} + Iterator(const Iterator& aOther) : mPointer(aOther.mPointer) {} + + Iterator& operator++() { - public: - Iterator() : mPointer(nullptr) {} - Iterator(PtrInfoOrBlock *aPointer) : mPointer(aPointer) {} - Iterator(const Iterator& aOther) : mPointer(aOther.mPointer) {} + if (mPointer->ptrInfo == nullptr) { + // Null pointer is a sentinel for link to the next block. + mPointer = (mPointer + 1)->block->mPointers; + } + ++mPointer; + return *this; + } - Iterator& operator++() - { - if (mPointer->ptrInfo == nullptr) { - // Null pointer is a sentinel for link to the next block. - mPointer = (mPointer + 1)->block->mPointers; - } - ++mPointer; - return *this; - } - - PtrInfo* operator*() const - { - if (mPointer->ptrInfo == nullptr) { - // Null pointer is a sentinel for link to the next block. - return (mPointer + 1)->block->mPointers->ptrInfo; - } - return mPointer->ptrInfo; - } - bool operator==(const Iterator& aOther) const - { return mPointer == aOther.mPointer; } - bool operator!=(const Iterator& aOther) const - { return mPointer != aOther.mPointer; } + PtrInfo* operator*() const + { + if (mPointer->ptrInfo == nullptr) { + // Null pointer is a sentinel for link to the next block. + return (mPointer + 1)->block->mPointers->ptrInfo; + } + return mPointer->ptrInfo; + } + bool operator==(const Iterator& aOther) const + { return mPointer == aOther.mPointer; } + bool operator!=(const Iterator& aOther) const + { return mPointer != aOther.mPointer; } #ifdef DEBUG_CC_GRAPH - bool Initialized() const - { - return mPointer != nullptr; - } + bool Initialized() const + { + return mPointer != nullptr; + } #endif - private: - PtrInfoOrBlock *mPointer; - }; + private: + PtrInfoOrBlock *mPointer; + }; - class Builder; - friend class Builder; - class Builder { - public: - Builder(EdgePool &aPool) - : mCurrent(&aPool.mSentinelAndBlocks[0]), - mBlockEnd(&aPool.mSentinelAndBlocks[0]), - mNextBlockPtr(&aPool.Blocks()) - { - } - - Iterator Mark() { return Iterator(mCurrent); } - - void Add(PtrInfo* aEdge) { - if (mCurrent == mBlockEnd) { - Block *b = new Block(); - *mNextBlockPtr = b; - mCurrent = b->Start(); - mBlockEnd = b->End(); - mNextBlockPtr = &b->Next(); - } - (mCurrent++)->ptrInfo = aEdge; - } - private: - // mBlockEnd points to space for null sentinel - PtrInfoOrBlock *mCurrent, *mBlockEnd; - Block **mNextBlockPtr; - }; - - size_t SizeOfExcludingThis(MallocSizeOf aMallocSizeOf) const { - size_t n = 0; - Block *b = Blocks(); - while (b) { - n += aMallocSizeOf(b); - b = b->Next(); - } - return n; + class Builder; + friend class Builder; + class Builder { + public: + Builder(EdgePool &aPool) + : mCurrent(&aPool.mSentinelAndBlocks[0]), + mBlockEnd(&aPool.mSentinelAndBlocks[0]), + mNextBlockPtr(&aPool.Blocks()) + { } + + Iterator Mark() { return Iterator(mCurrent); } + + void Add(PtrInfo* aEdge) { + if (mCurrent == mBlockEnd) { + Block *b = new Block(); + *mNextBlockPtr = b; + mCurrent = b->Start(); + mBlockEnd = b->End(); + mNextBlockPtr = &b->Next(); + } + (mCurrent++)->ptrInfo = aEdge; + } + private: + // mBlockEnd points to space for null sentinel + PtrInfoOrBlock *mCurrent, *mBlockEnd; + Block **mNextBlockPtr; + }; + + size_t SizeOfExcludingThis(MallocSizeOf aMallocSizeOf) const { + size_t n = 0; + Block *b = Blocks(); + while (b) { + n += aMallocSizeOf(b); + b = b->Next(); + } + return n; + } }; #ifdef DEBUG_CC_GRAPH @@ -508,61 +508,61 @@ enum NodeColor { black, white, grey }; struct PtrInfo { - void *mPointer; - nsCycleCollectionParticipant *mParticipant; - uint32_t mColor : 2; - uint32_t mInternalRefs : 30; - uint32_t mRefCount; + void *mPointer; + nsCycleCollectionParticipant *mParticipant; + uint32_t mColor : 2; + uint32_t mInternalRefs : 30; + uint32_t mRefCount; private: - EdgePool::Iterator mFirstChild; + EdgePool::Iterator mFirstChild; public: - PtrInfo(void *aPointer, nsCycleCollectionParticipant *aParticipant) - : mPointer(aPointer), - mParticipant(aParticipant), - mColor(grey), - mInternalRefs(0), - mRefCount(UINT32_MAX - 1), - mFirstChild() - { - // We initialize mRefCount to a large non-zero value so - // that it doesn't look like a JS object to the cycle collector - // in the case where the object dies before being traversed. + PtrInfo(void *aPointer, nsCycleCollectionParticipant *aParticipant) + : mPointer(aPointer), + mParticipant(aParticipant), + mColor(grey), + mInternalRefs(0), + mRefCount(UINT32_MAX - 1), + mFirstChild() + { + // We initialize mRefCount to a large non-zero value so + // that it doesn't look like a JS object to the cycle collector + // in the case where the object dies before being traversed. - MOZ_ASSERT(aParticipant); - } + MOZ_ASSERT(aParticipant); + } - // Allow NodePool::Block's constructor to compile. - PtrInfo() { - NS_NOTREACHED("should never be called"); - } + // Allow NodePool::Block's constructor to compile. + PtrInfo() { + NS_NOTREACHED("should never be called"); + } - EdgePool::Iterator FirstChild() - { - CC_GRAPH_ASSERT(mFirstChild.Initialized()); - return mFirstChild; - } + EdgePool::Iterator FirstChild() + { + CC_GRAPH_ASSERT(mFirstChild.Initialized()); + return mFirstChild; + } - // this PtrInfo must be part of a NodePool - EdgePool::Iterator LastChild() - { - CC_GRAPH_ASSERT((this + 1)->mFirstChild.Initialized()); - return (this + 1)->mFirstChild; - } + // this PtrInfo must be part of a NodePool + EdgePool::Iterator LastChild() + { + CC_GRAPH_ASSERT((this + 1)->mFirstChild.Initialized()); + return (this + 1)->mFirstChild; + } - void SetFirstChild(EdgePool::Iterator aFirstChild) - { - CC_GRAPH_ASSERT(aFirstChild.Initialized()); - mFirstChild = aFirstChild; - } + void SetFirstChild(EdgePool::Iterator aFirstChild) + { + CC_GRAPH_ASSERT(aFirstChild.Initialized()); + mFirstChild = aFirstChild; + } - // this PtrInfo must be part of a NodePool - void SetLastChild(EdgePool::Iterator aLastChild) - { - CC_GRAPH_ASSERT(aLastChild.Initialized()); - (this + 1)->mFirstChild = aLastChild; - } + // this PtrInfo must be part of a NodePool + void SetLastChild(EdgePool::Iterator aLastChild) + { + CC_GRAPH_ASSERT(aLastChild.Initialized()); + (this + 1)->mFirstChild = aLastChild; + } }; /** @@ -572,140 +572,140 @@ public: class NodePool { private: - enum { BlockSize = 8 * 1024 }; // could be int template parameter + enum { BlockSize = 8 * 1024 }; // could be int template parameter - struct Block { - // We create and destroy Block using NS_Alloc/NS_Free rather - // than new and delete to avoid calling its constructor and - // destructor. - Block() { NS_NOTREACHED("should never be called"); } - ~Block() { NS_NOTREACHED("should never be called"); } + struct Block { + // We create and destroy Block using NS_Alloc/NS_Free rather + // than new and delete to avoid calling its constructor and + // destructor. + Block() { NS_NOTREACHED("should never be called"); } + ~Block() { NS_NOTREACHED("should never be called"); } - Block* mNext; - PtrInfo mEntries[BlockSize + 1]; // +1 to store last child of last node - }; + Block* mNext; + PtrInfo mEntries[BlockSize + 1]; // +1 to store last child of last node + }; public: - NodePool() - : mBlocks(nullptr), - mLast(nullptr) - { + NodePool() + : mBlocks(nullptr), + mLast(nullptr) + { + } + + ~NodePool() + { + MOZ_ASSERT(!mBlocks, "Didn't call Clear()?"); + } + + void Clear() + { + Block *b = mBlocks; + while (b) { + Block *n = b->mNext; + NS_Free(b); + b = n; } - ~NodePool() - { - MOZ_ASSERT(!mBlocks, "Didn't call Clear()?"); - } - - void Clear() - { - Block *b = mBlocks; - while (b) { - Block *n = b->mNext; - NS_Free(b); - b = n; - } - - mBlocks = nullptr; - mLast = nullptr; - } + mBlocks = nullptr; + mLast = nullptr; + } #ifdef DEBUG - bool IsEmpty() - { - return !mBlocks && !mLast; - } + bool IsEmpty() + { + return !mBlocks && !mLast; + } #endif - class Builder; - friend class Builder; - class Builder { - public: - Builder(NodePool& aPool) - : mNextBlock(&aPool.mBlocks), - mNext(aPool.mLast), - mBlockEnd(nullptr) - { - MOZ_ASSERT(aPool.mBlocks == nullptr && aPool.mLast == nullptr, - "pool not empty"); - } - PtrInfo *Add(void *aPointer, nsCycleCollectionParticipant *aParticipant) - { - if (mNext == mBlockEnd) { - Block *block = static_cast(NS_Alloc(sizeof(Block))); - *mNextBlock = block; - mNext = block->mEntries; - mBlockEnd = block->mEntries + BlockSize; - block->mNext = nullptr; - mNextBlock = &block->mNext; - } - return new (mNext++) PtrInfo(aPointer, aParticipant); - } - private: - Block **mNextBlock; - PtrInfo *&mNext; - PtrInfo *mBlockEnd; - }; + class Builder; + friend class Builder; + class Builder { + public: + Builder(NodePool& aPool) + : mNextBlock(&aPool.mBlocks), + mNext(aPool.mLast), + mBlockEnd(nullptr) + { + MOZ_ASSERT(aPool.mBlocks == nullptr && aPool.mLast == nullptr, + "pool not empty"); + } + PtrInfo *Add(void *aPointer, nsCycleCollectionParticipant *aParticipant) + { + if (mNext == mBlockEnd) { + Block *block = static_cast(NS_Alloc(sizeof(Block))); + *mNextBlock = block; + mNext = block->mEntries; + mBlockEnd = block->mEntries + BlockSize; + block->mNext = nullptr; + mNextBlock = &block->mNext; + } + return new (mNext++) PtrInfo(aPointer, aParticipant); + } + private: + Block **mNextBlock; + PtrInfo *&mNext; + PtrInfo *mBlockEnd; + }; - class Enumerator; - friend class Enumerator; - class Enumerator { - public: - Enumerator(NodePool& aPool) - : mFirstBlock(aPool.mBlocks), - mCurBlock(nullptr), - mNext(nullptr), - mBlockEnd(nullptr), - mLast(aPool.mLast) - { - } - - bool IsDone() const - { - return mNext == mLast; - } - - bool AtBlockEnd() const - { - return mNext == mBlockEnd; - } - - PtrInfo* GetNext() - { - MOZ_ASSERT(!IsDone(), "calling GetNext when done"); - if (mNext == mBlockEnd) { - Block *nextBlock = mCurBlock ? mCurBlock->mNext : mFirstBlock; - mNext = nextBlock->mEntries; - mBlockEnd = mNext + BlockSize; - mCurBlock = nextBlock; - } - return mNext++; - } - private: - // mFirstBlock is a reference to allow an Enumerator to be constructed - // for an empty graph. - Block *&mFirstBlock; - Block *mCurBlock; - // mNext is the next value we want to return, unless mNext == mBlockEnd - // NB: mLast is a reference to allow enumerating while building! - PtrInfo *mNext, *mBlockEnd, *&mLast; - }; - - size_t SizeOfExcludingThis(MallocSizeOf aMallocSizeOf) const { - // We don't measure the things pointed to by mEntries[] because those - // pointers are non-owning. - size_t n = 0; - Block *b = mBlocks; - while (b) { - n += aMallocSizeOf(b); - b = b->mNext; - } - return n; + class Enumerator; + friend class Enumerator; + class Enumerator { + public: + Enumerator(NodePool& aPool) + : mFirstBlock(aPool.mBlocks), + mCurBlock(nullptr), + mNext(nullptr), + mBlockEnd(nullptr), + mLast(aPool.mLast) + { } + bool IsDone() const + { + return mNext == mLast; + } + + bool AtBlockEnd() const + { + return mNext == mBlockEnd; + } + + PtrInfo* GetNext() + { + MOZ_ASSERT(!IsDone(), "calling GetNext when done"); + if (mNext == mBlockEnd) { + Block *nextBlock = mCurBlock ? mCurBlock->mNext : mFirstBlock; + mNext = nextBlock->mEntries; + mBlockEnd = mNext + BlockSize; + mCurBlock = nextBlock; + } + return mNext++; + } + private: + // mFirstBlock is a reference to allow an Enumerator to be constructed + // for an empty graph. + Block *&mFirstBlock; + Block *mCurBlock; + // mNext is the next value we want to return, unless mNext == mBlockEnd + // NB: mLast is a reference to allow enumerating while building! + PtrInfo *mNext, *mBlockEnd, *&mLast; + }; + + size_t SizeOfExcludingThis(MallocSizeOf aMallocSizeOf) const { + // We don't measure the things pointed to by mEntries[] because those + // pointers are non-owning. + size_t n = 0; + Block *b = mBlocks; + while (b) { + n += aMallocSizeOf(b); + b = b->mNext; + } + return n; + } + private: - Block *mBlocks; - PtrInfo *mLast; + Block *mBlocks; + PtrInfo *mLast; }; @@ -713,8 +713,8 @@ private: struct PtrToNodeEntry : public PLDHashEntryHdr { - // The key is mNode->mPointer - PtrInfo *mNode; + // The key is mNode->mPointer + PtrInfo *mNode; }; static bool @@ -722,138 +722,138 @@ PtrToNodeMatchEntry(PLDHashTable *table, const PLDHashEntryHdr *entry, const void *key) { - const PtrToNodeEntry *n = static_cast(entry); - return n->mNode->mPointer == key; + const PtrToNodeEntry *n = static_cast(entry); + return n->mNode->mPointer == key; } static PLDHashTableOps PtrNodeOps = { - PL_DHashAllocTable, - PL_DHashFreeTable, - PL_DHashVoidPtrKeyStub, - PtrToNodeMatchEntry, - PL_DHashMoveEntryStub, - PL_DHashClearEntryStub, - PL_DHashFinalizeStub, - nullptr + PL_DHashAllocTable, + PL_DHashFreeTable, + PL_DHashVoidPtrKeyStub, + PtrToNodeMatchEntry, + PL_DHashMoveEntryStub, + PL_DHashClearEntryStub, + PL_DHashFinalizeStub, + nullptr }; struct WeakMapping { - // map and key will be null if the corresponding objects are GC marked - PtrInfo *mMap; - PtrInfo *mKey; - PtrInfo *mKeyDelegate; - PtrInfo *mVal; + // map and key will be null if the corresponding objects are GC marked + PtrInfo *mMap; + PtrInfo *mKey; + PtrInfo *mKeyDelegate; + PtrInfo *mVal; }; class GCGraphBuilder; struct GCGraph { - NodePool mNodes; - EdgePool mEdges; - nsTArray mWeakMaps; - uint32_t mRootCount; + NodePool mNodes; + EdgePool mEdges; + nsTArray mWeakMaps; + uint32_t mRootCount; private: - PLDHashTable mPtrToNodeMap; + PLDHashTable mPtrToNodeMap; public: - GCGraph() : mRootCount(0) - { - mPtrToNodeMap.ops = nullptr; - } + GCGraph() : mRootCount(0) + { + mPtrToNodeMap.ops = nullptr; + } - ~GCGraph() - { - if (mPtrToNodeMap.ops) { - PL_DHashTableFinish(&mPtrToNodeMap); - } + ~GCGraph() + { + if (mPtrToNodeMap.ops) { + PL_DHashTableFinish(&mPtrToNodeMap); } + } - void Init() - { - MOZ_ASSERT(IsEmpty(), "Failed to call GCGraph::Clear"); - PL_DHashTableInit(&mPtrToNodeMap, &PtrNodeOps, nullptr, - sizeof(PtrToNodeEntry), 32768); - } + void Init() + { + MOZ_ASSERT(IsEmpty(), "Failed to call GCGraph::Clear"); + PL_DHashTableInit(&mPtrToNodeMap, &PtrNodeOps, nullptr, + sizeof(PtrToNodeEntry), 32768); + } - void Clear() - { - mNodes.Clear(); - mEdges.Clear(); - mWeakMaps.Clear(); - mRootCount = 0; - PL_DHashTableFinish(&mPtrToNodeMap); - mPtrToNodeMap.ops = nullptr; - } + void Clear() + { + mNodes.Clear(); + mEdges.Clear(); + mWeakMaps.Clear(); + mRootCount = 0; + PL_DHashTableFinish(&mPtrToNodeMap); + mPtrToNodeMap.ops = nullptr; + } #ifdef DEBUG - bool IsEmpty() - { - return mNodes.IsEmpty() && mEdges.IsEmpty() && - mWeakMaps.IsEmpty() && mRootCount == 0 && - !mPtrToNodeMap.ops; - } + bool IsEmpty() + { + return mNodes.IsEmpty() && mEdges.IsEmpty() && + mWeakMaps.IsEmpty() && mRootCount == 0 && + !mPtrToNodeMap.ops; + } #endif - PtrInfo* FindNode(void *aPtr); - PtrToNodeEntry* AddNodeToMap(void *aPtr); - void RemoveNodeFromMap(void *aPtr); + PtrInfo* FindNode(void *aPtr); + PtrToNodeEntry* AddNodeToMap(void *aPtr); + void RemoveNodeFromMap(void *aPtr); - uint32_t MapCount() const - { - return mPtrToNodeMap.entryCount; - } + uint32_t MapCount() const + { + return mPtrToNodeMap.entryCount; + } - void SizeOfExcludingThis(MallocSizeOf aMallocSizeOf, - size_t *aNodesSize, size_t *aEdgesSize, - size_t *aWeakMapsSize) const { - *aNodesSize = mNodes.SizeOfExcludingThis(aMallocSizeOf); - *aEdgesSize = mEdges.SizeOfExcludingThis(aMallocSizeOf); + void SizeOfExcludingThis(MallocSizeOf aMallocSizeOf, + size_t *aNodesSize, size_t *aEdgesSize, + size_t *aWeakMapsSize) const { + *aNodesSize = mNodes.SizeOfExcludingThis(aMallocSizeOf); + *aEdgesSize = mEdges.SizeOfExcludingThis(aMallocSizeOf); - // We don't measure what the WeakMappings point to, because the - // pointers are non-owning. - *aWeakMapsSize = mWeakMaps.SizeOfExcludingThis(aMallocSizeOf); - } + // We don't measure what the WeakMappings point to, because the + // pointers are non-owning. + *aWeakMapsSize = mWeakMaps.SizeOfExcludingThis(aMallocSizeOf); + } }; PtrInfo* GCGraph::FindNode(void *aPtr) { - PtrToNodeEntry *e = static_cast(PL_DHashTableOperate(&mPtrToNodeMap, aPtr, PL_DHASH_LOOKUP)); - if (!PL_DHASH_ENTRY_IS_BUSY(e)) { - return nullptr; - } - return e->mNode; + PtrToNodeEntry *e = static_cast(PL_DHashTableOperate(&mPtrToNodeMap, aPtr, PL_DHASH_LOOKUP)); + if (!PL_DHASH_ENTRY_IS_BUSY(e)) { + return nullptr; + } + return e->mNode; } PtrToNodeEntry* GCGraph::AddNodeToMap(void *aPtr) { - PtrToNodeEntry *e = static_cast(PL_DHashTableOperate(&mPtrToNodeMap, aPtr, PL_DHASH_ADD)); - if (!e) { - // Caller should track OOMs - return nullptr; - } - return e; + PtrToNodeEntry *e = static_cast(PL_DHashTableOperate(&mPtrToNodeMap, aPtr, PL_DHASH_ADD)); + if (!e) { + // Caller should track OOMs + return nullptr; + } + return e; } void GCGraph::RemoveNodeFromMap(void *aPtr) { - PL_DHashTableOperate(&mPtrToNodeMap, aPtr, PL_DHASH_REMOVE); + PL_DHashTableOperate(&mPtrToNodeMap, aPtr, PL_DHASH_REMOVE); } static nsISupports * CanonicalizeXPCOMParticipant(nsISupports *in) { - nsISupports* out; - in->QueryInterface(NS_GET_IID(nsCycleCollectionISupports), - reinterpret_cast(&out)); - return out; + nsISupports* out; + in->QueryInterface(NS_GET_IID(nsCycleCollectionISupports), + reinterpret_cast(&out)); + return out; } static inline void @@ -862,19 +862,19 @@ ToParticipant(nsISupports *s, nsXPCOMCycleCollectionParticipant **cp); static void CanonicalizeParticipant(void **parti, nsCycleCollectionParticipant **cp) { - // If the participant is null, this is an nsISupports participant, - // so we must QI to get the real participant. + // If the participant is null, this is an nsISupports participant, + // so we must QI to get the real participant. - if (!*cp) { - nsISupports *nsparti = static_cast(*parti); - nsparti = CanonicalizeXPCOMParticipant(nsparti); - NS_ASSERTION(nsparti, - "Don't add objects that don't participate in collection!"); - nsXPCOMCycleCollectionParticipant *xcp; - ToParticipant(nsparti, &xcp); - *parti = nsparti; - *cp = xcp; - } + if (!*cp) { + nsISupports *nsparti = static_cast(*parti); + nsparti = CanonicalizeXPCOMParticipant(nsparti); + NS_ASSERTION(nsparti, + "Don't add objects that don't participate in collection!"); + nsXPCOMCycleCollectionParticipant *xcp; + ToParticipant(nsparti, &xcp); + *parti = nsparti; + *cp = xcp; + } } struct nsPurpleBufferEntry { @@ -893,200 +893,200 @@ class nsCycleCollector; struct nsPurpleBuffer { private: - struct Block { - Block *mNext; - // Try to match the size of a jemalloc bucket, to minimize slop bytes. - // - On 32-bit platforms sizeof(nsPurpleBufferEntry) is 12, so mEntries - // is 16,380 bytes, which leaves 4 bytes for mNext. - // - On 64-bit platforms sizeof(nsPurpleBufferEntry) is 24, so mEntries - // is 32,544 bytes, which leaves 8 bytes for mNext. - nsPurpleBufferEntry mEntries[1365]; + struct Block { + Block *mNext; + // Try to match the size of a jemalloc bucket, to minimize slop bytes. + // - On 32-bit platforms sizeof(nsPurpleBufferEntry) is 12, so mEntries + // is 16,380 bytes, which leaves 4 bytes for mNext. + // - On 64-bit platforms sizeof(nsPurpleBufferEntry) is 24, so mEntries + // is 32,544 bytes, which leaves 8 bytes for mNext. + nsPurpleBufferEntry mEntries[1365]; - Block() : mNext(nullptr) { - // Ensure Block is the right size (see above). - static_assert( - sizeof(Block) == 16384 || // 32-bit - sizeof(Block) == 32768, // 64-bit - "ill-sized nsPurpleBuffer::Block" - ); - } - - template - void VisitEntries(nsPurpleBuffer &aBuffer, PurpleVisitor &aVisitor) - { - nsPurpleBufferEntry *eEnd = ArrayEnd(mEntries); - for (nsPurpleBufferEntry *e = mEntries; e != eEnd; ++e) { - if (!(uintptr_t(e->mObject) & uintptr_t(1))) { - aVisitor.Visit(aBuffer, e); - } - } - } - }; - // This class wraps a linked list of the elements in the purple - // buffer. - - uint32_t mCount; - Block mFirstBlock; - nsPurpleBufferEntry *mFreeList; - -public: - nsPurpleBuffer() - { - InitBlocks(); - } - - ~nsPurpleBuffer() - { - FreeBlocks(); + Block() : mNext(nullptr) { + // Ensure Block is the right size (see above). + static_assert( + sizeof(Block) == 16384 || // 32-bit + sizeof(Block) == 32768, // 64-bit + "ill-sized nsPurpleBuffer::Block" + ); } template - void VisitEntries(PurpleVisitor &aVisitor) + void VisitEntries(nsPurpleBuffer &aBuffer, PurpleVisitor &aVisitor) { - for (Block *b = &mFirstBlock; b; b = b->mNext) { - b->VisitEntries(*this, aVisitor); + nsPurpleBufferEntry *eEnd = ArrayEnd(mEntries); + for (nsPurpleBufferEntry *e = mEntries; e != eEnd; ++e) { + if (!(uintptr_t(e->mObject) & uintptr_t(1))) { + aVisitor.Visit(aBuffer, e); } + } + } + }; + // This class wraps a linked list of the elements in the purple + // buffer. + + uint32_t mCount; + Block mFirstBlock; + nsPurpleBufferEntry *mFreeList; + +public: + nsPurpleBuffer() + { + InitBlocks(); + } + + ~nsPurpleBuffer() + { + FreeBlocks(); + } + + template + void VisitEntries(PurpleVisitor &aVisitor) + { + for (Block *b = &mFirstBlock; b; b = b->mNext) { + b->VisitEntries(*this, aVisitor); + } + } + + void InitBlocks() + { + mCount = 0; + mFreeList = nullptr; + StartBlock(&mFirstBlock); + } + + void StartBlock(Block *aBlock) + { + NS_ABORT_IF_FALSE(!mFreeList, "should not have free list"); + + // Put all the entries in the block on the free list. + nsPurpleBufferEntry *entries = aBlock->mEntries; + mFreeList = entries; + for (uint32_t i = 1; i < ArrayLength(aBlock->mEntries); ++i) { + entries[i - 1].mNextInFreeList = + (nsPurpleBufferEntry*)(uintptr_t(entries + i) | 1); + } + entries[ArrayLength(aBlock->mEntries) - 1].mNextInFreeList = + (nsPurpleBufferEntry*)1; + } + + void FreeBlocks() + { + if (mCount > 0) + UnmarkRemainingPurple(&mFirstBlock); + Block *b = mFirstBlock.mNext; + while (b) { + if (mCount > 0) + UnmarkRemainingPurple(b); + Block *next = b->mNext; + delete b; + b = next; + } + mFirstBlock.mNext = nullptr; + } + + struct UnmarkRemainingPurpleVisitor + { + void + Visit(nsPurpleBuffer &aBuffer, nsPurpleBufferEntry *aEntry) + { + if (aEntry->mRefCnt) { + aEntry->mRefCnt->RemoveFromPurpleBuffer(); + aEntry->mRefCnt = nullptr; + } + aEntry->mObject = nullptr; + --aBuffer.mCount; + } + }; + + void UnmarkRemainingPurple(Block *b) + { + UnmarkRemainingPurpleVisitor visitor; + b->VisitEntries(*this, visitor); + } + + void SelectPointers(GCGraphBuilder &builder); + + // RemoveSkippable removes entries from the purple buffer synchronously + // (1) if aAsyncSnowWhiteFreeing is false and nsPurpleBufferEntry::mRefCnt is 0 or + // (2) if the object's nsXPCOMCycleCollectionParticipant::CanSkip() returns true or + // (3) if nsPurpleBufferEntry::mRefCnt->IsPurple() is false. + // (4) If removeChildlessNodes is true, then any nodes in the purple buffer + // that will have no children in the cycle collector graph will also be + // removed. CanSkip() may be run on these children. + void RemoveSkippable(nsCycleCollector* aCollector, + bool removeChildlessNodes, + bool aAsyncSnowWhiteFreeing, + CC_ForgetSkippableCallback aCb); + + MOZ_ALWAYS_INLINE nsPurpleBufferEntry* NewEntry() + { + if (MOZ_UNLIKELY(!mFreeList)) { + Block *b = new Block; + StartBlock(b); + + // Add the new block as the second block in the list. + b->mNext = mFirstBlock.mNext; + mFirstBlock.mNext = b; } - void InitBlocks() - { - mCount = 0; - mFreeList = nullptr; - StartBlock(&mFirstBlock); + nsPurpleBufferEntry *e = mFreeList; + mFreeList = (nsPurpleBufferEntry*) + (uintptr_t(mFreeList->mNextInFreeList) & ~uintptr_t(1)); + return e; + } + + MOZ_ALWAYS_INLINE void Put(void *p, nsCycleCollectionParticipant *cp, + nsCycleCollectingAutoRefCnt *aRefCnt) + { + nsPurpleBufferEntry *e = NewEntry(); + + ++mCount; + + e->mObject = p; + e->mRefCnt = aRefCnt; + e->mParticipant = cp; + } + + void Remove(nsPurpleBufferEntry *e) + { + MOZ_ASSERT(mCount != 0, "must have entries"); + + if (e->mRefCnt) { + e->mRefCnt->RemoveFromPurpleBuffer(); + e->mRefCnt = nullptr; + } + e->mNextInFreeList = + (nsPurpleBufferEntry*)(uintptr_t(mFreeList) | uintptr_t(1)); + mFreeList = e; + + --mCount; + } + + uint32_t Count() const + { + return mCount; + } + + size_t SizeOfExcludingThis(MallocSizeOf aMallocSizeOf) const + { + size_t n = 0; + + // Don't measure mFirstBlock because it's within |this|. + const Block *block = mFirstBlock.mNext; + while (block) { + n += aMallocSizeOf(block); + block = block->mNext; } - void StartBlock(Block *aBlock) - { - NS_ABORT_IF_FALSE(!mFreeList, "should not have free list"); + // mFreeList is deliberately not measured because it points into + // the purple buffer, which is within mFirstBlock and thus within |this|. + // + // We also don't measure the things pointed to by mEntries[] because + // those pointers are non-owning. - // Put all the entries in the block on the free list. - nsPurpleBufferEntry *entries = aBlock->mEntries; - mFreeList = entries; - for (uint32_t i = 1; i < ArrayLength(aBlock->mEntries); ++i) { - entries[i - 1].mNextInFreeList = - (nsPurpleBufferEntry*)(uintptr_t(entries + i) | 1); - } - entries[ArrayLength(aBlock->mEntries) - 1].mNextInFreeList = - (nsPurpleBufferEntry*)1; - } - - void FreeBlocks() - { - if (mCount > 0) - UnmarkRemainingPurple(&mFirstBlock); - Block *b = mFirstBlock.mNext; - while (b) { - if (mCount > 0) - UnmarkRemainingPurple(b); - Block *next = b->mNext; - delete b; - b = next; - } - mFirstBlock.mNext = nullptr; - } - - struct UnmarkRemainingPurpleVisitor - { - void - Visit(nsPurpleBuffer &aBuffer, nsPurpleBufferEntry *aEntry) - { - if (aEntry->mRefCnt) { - aEntry->mRefCnt->RemoveFromPurpleBuffer(); - aEntry->mRefCnt = nullptr; - } - aEntry->mObject = nullptr; - --aBuffer.mCount; - } - }; - - void UnmarkRemainingPurple(Block *b) - { - UnmarkRemainingPurpleVisitor visitor; - b->VisitEntries(*this, visitor); - } - - void SelectPointers(GCGraphBuilder &builder); - - // RemoveSkippable removes entries from the purple buffer synchronously - // (1) if aAsyncSnowWhiteFreeing is false and nsPurpleBufferEntry::mRefCnt is 0 or - // (2) if the object's nsXPCOMCycleCollectionParticipant::CanSkip() returns true or - // (3) if nsPurpleBufferEntry::mRefCnt->IsPurple() is false. - // (4) If removeChildlessNodes is true, then any nodes in the purple buffer - // that will have no children in the cycle collector graph will also be - // removed. CanSkip() may be run on these children. - void RemoveSkippable(nsCycleCollector* aCollector, - bool removeChildlessNodes, - bool aAsyncSnowWhiteFreeing, - CC_ForgetSkippableCallback aCb); - - MOZ_ALWAYS_INLINE nsPurpleBufferEntry* NewEntry() - { - if (MOZ_UNLIKELY(!mFreeList)) { - Block *b = new Block; - StartBlock(b); - - // Add the new block as the second block in the list. - b->mNext = mFirstBlock.mNext; - mFirstBlock.mNext = b; - } - - nsPurpleBufferEntry *e = mFreeList; - mFreeList = (nsPurpleBufferEntry*) - (uintptr_t(mFreeList->mNextInFreeList) & ~uintptr_t(1)); - return e; - } - - MOZ_ALWAYS_INLINE void Put(void *p, nsCycleCollectionParticipant *cp, - nsCycleCollectingAutoRefCnt *aRefCnt) - { - nsPurpleBufferEntry *e = NewEntry(); - - ++mCount; - - e->mObject = p; - e->mRefCnt = aRefCnt; - e->mParticipant = cp; - } - - void Remove(nsPurpleBufferEntry *e) - { - MOZ_ASSERT(mCount != 0, "must have entries"); - - if (e->mRefCnt) { - e->mRefCnt->RemoveFromPurpleBuffer(); - e->mRefCnt = nullptr; - } - e->mNextInFreeList = - (nsPurpleBufferEntry*)(uintptr_t(mFreeList) | uintptr_t(1)); - mFreeList = e; - - --mCount; - } - - uint32_t Count() const - { - return mCount; - } - - size_t SizeOfExcludingThis(MallocSizeOf aMallocSizeOf) const - { - size_t n = 0; - - // Don't measure mFirstBlock because it's within |this|. - const Block *block = mFirstBlock.mNext; - while (block) { - n += aMallocSizeOf(block); - block = block->mNext; - } - - // mFreeList is deliberately not measured because it points into - // the purple buffer, which is within mFirstBlock and thus within |this|. - // - // We also don't measure the things pointed to by mEntries[] because - // those pointers are non-owning. - - return n; - } + return n; + } }; static bool @@ -1094,50 +1094,50 @@ AddPurpleRoot(GCGraphBuilder &aBuilder, void *aRoot, nsCycleCollectionParticipan struct SelectPointersVisitor { - SelectPointersVisitor(GCGraphBuilder &aBuilder) - : mBuilder(aBuilder) - {} + SelectPointersVisitor(GCGraphBuilder &aBuilder) + : mBuilder(aBuilder) + {} - void - Visit(nsPurpleBuffer &aBuffer, nsPurpleBufferEntry *aEntry) - { - MOZ_ASSERT(aEntry->mObject, "Null object in purple buffer"); - MOZ_ASSERT(aEntry->mRefCnt->get() != 0, - "SelectPointersVisitor: snow-white object in the purple buffer"); - if (!aEntry->mRefCnt->IsPurple() || - AddPurpleRoot(mBuilder, aEntry->mObject, aEntry->mParticipant)) { - aBuffer.Remove(aEntry); - } + void + Visit(nsPurpleBuffer &aBuffer, nsPurpleBufferEntry *aEntry) + { + MOZ_ASSERT(aEntry->mObject, "Null object in purple buffer"); + MOZ_ASSERT(aEntry->mRefCnt->get() != 0, + "SelectPointersVisitor: snow-white object in the purple buffer"); + if (!aEntry->mRefCnt->IsPurple() || + AddPurpleRoot(mBuilder, aEntry->mObject, aEntry->mParticipant)) { + aBuffer.Remove(aEntry); } + } private: - GCGraphBuilder &mBuilder; + GCGraphBuilder &mBuilder; }; void nsPurpleBuffer::SelectPointers(GCGraphBuilder &aBuilder) { - SelectPointersVisitor visitor(aBuilder); - VisitEntries(visitor); + SelectPointersVisitor visitor(aBuilder); + VisitEntries(visitor); - NS_ASSERTION(mCount == 0, "AddPurpleRoot failed"); - if (mCount == 0) { - FreeBlocks(); - InitBlocks(); - } + NS_ASSERTION(mCount == 0, "AddPurpleRoot failed"); + if (mCount == 0) { + FreeBlocks(); + InitBlocks(); + } } enum ccPhase { - IdlePhase, - GraphBuildingPhase, - ScanAndCollectWhitePhase, - CleanupPhase + IdlePhase, + GraphBuildingPhase, + ScanAndCollectWhitePhase, + CleanupPhase }; enum ccType { - SliceCC, /* If a CC is in progress, continue it. Otherwise, start a new one. */ - ManualCC, /* Explicitly triggered. */ - ShutdownCC /* Shutdown CC, used for finding leaks. */ + SliceCC, /* If a CC is in progress, continue it. Otherwise, start a new one. */ + ManualCC, /* Explicitly triggered. */ + ShutdownCC /* Shutdown CC, used for finding leaks. */ }; #ifdef MOZ_NUWA_PROCESS @@ -1154,100 +1154,100 @@ class JSPurpleBuffer; class nsCycleCollector : public nsIMemoryReporter { - NS_DECL_ISUPPORTS - NS_DECL_NSIMEMORYREPORTER + NS_DECL_ISUPPORTS + NS_DECL_NSIMEMORYREPORTER - bool mActivelyCollecting; - bool mFreeingSnowWhite; - // mScanInProgress should be false when we're collecting white objects. - bool mScanInProgress; - CycleCollectorResults mResults; - TimeStamp mCollectionStart; + bool mActivelyCollecting; + bool mFreeingSnowWhite; + // mScanInProgress should be false when we're collecting white objects. + bool mScanInProgress; + CycleCollectorResults mResults; + TimeStamp mCollectionStart; - CycleCollectedJSRuntime *mJSRuntime; + CycleCollectedJSRuntime *mJSRuntime; - ccPhase mIncrementalPhase; - GCGraph mGraph; - nsAutoPtr mBuilder; - nsAutoPtr mCurrNode; - nsCOMPtr mListener; + ccPhase mIncrementalPhase; + GCGraph mGraph; + nsAutoPtr mBuilder; + nsAutoPtr mCurrNode; + nsCOMPtr mListener; - nsIThread* mThread; + nsIThread* mThread; - nsCycleCollectorParams mParams; + nsCycleCollectorParams mParams; - uint32_t mWhiteNodeCount; + uint32_t mWhiteNodeCount; - CC_BeforeUnlinkCallback mBeforeUnlinkCB; - CC_ForgetSkippableCallback mForgetSkippableCB; + CC_BeforeUnlinkCallback mBeforeUnlinkCB; + CC_ForgetSkippableCallback mForgetSkippableCB; - nsPurpleBuffer mPurpleBuf; + nsPurpleBuffer mPurpleBuf; - uint32_t mUnmergedNeeded; - uint32_t mMergedInARow; + uint32_t mUnmergedNeeded; + uint32_t mMergedInARow; - JSPurpleBuffer* mJSPurpleBuffer; + JSPurpleBuffer* mJSPurpleBuffer; public: - nsCycleCollector(); - virtual ~nsCycleCollector(); + nsCycleCollector(); + virtual ~nsCycleCollector(); - void RegisterJSRuntime(CycleCollectedJSRuntime *aJSRuntime); - void ForgetJSRuntime(); + void RegisterJSRuntime(CycleCollectedJSRuntime *aJSRuntime); + void ForgetJSRuntime(); - void SetBeforeUnlinkCallback(CC_BeforeUnlinkCallback aBeforeUnlinkCB) - { - CheckThreadSafety(); - mBeforeUnlinkCB = aBeforeUnlinkCB; - } + void SetBeforeUnlinkCallback(CC_BeforeUnlinkCallback aBeforeUnlinkCB) + { + CheckThreadSafety(); + mBeforeUnlinkCB = aBeforeUnlinkCB; + } - void SetForgetSkippableCallback(CC_ForgetSkippableCallback aForgetSkippableCB) - { - CheckThreadSafety(); - mForgetSkippableCB = aForgetSkippableCB; - } + void SetForgetSkippableCallback(CC_ForgetSkippableCallback aForgetSkippableCB) + { + CheckThreadSafety(); + mForgetSkippableCB = aForgetSkippableCB; + } - void Suspect(void *n, nsCycleCollectionParticipant *cp, - nsCycleCollectingAutoRefCnt *aRefCnt); - uint32_t SuspectedCount(); - void ForgetSkippable(bool aRemoveChildlessNodes, bool aAsyncSnowWhiteFreeing); - bool FreeSnowWhite(bool aUntilNoSWInPurpleBuffer); + void Suspect(void *n, nsCycleCollectionParticipant *cp, + nsCycleCollectingAutoRefCnt *aRefCnt); + uint32_t SuspectedCount(); + void ForgetSkippable(bool aRemoveChildlessNodes, bool aAsyncSnowWhiteFreeing); + bool FreeSnowWhite(bool aUntilNoSWInPurpleBuffer); - // This method assumes its argument is already canonicalized. - void RemoveObjectFromGraph(void *aPtr); + // This method assumes its argument is already canonicalized. + void RemoveObjectFromGraph(void *aPtr); - void PrepareForGarbageCollection(); + void PrepareForGarbageCollection(); - bool Collect(ccType aCCType, - SliceBudget &aBudget, - nsICycleCollectorListener *aManualListener); - void Shutdown(); + bool Collect(ccType aCCType, + SliceBudget &aBudget, + nsICycleCollectorListener *aManualListener); + void Shutdown(); - void SizeOfIncludingThis(mozilla::MallocSizeOf aMallocSizeOf, - size_t *aObjectSize, - size_t *aGraphNodesSize, - size_t *aGraphEdgesSize, - size_t *aWeakMapsSize, - size_t *aPurpleBufferSize) const; + void SizeOfIncludingThis(mozilla::MallocSizeOf aMallocSizeOf, + size_t *aObjectSize, + size_t *aGraphNodesSize, + size_t *aGraphEdgesSize, + size_t *aWeakMapsSize, + size_t *aPurpleBufferSize) const; - JSPurpleBuffer* GetJSPurpleBuffer(); + JSPurpleBuffer* GetJSPurpleBuffer(); private: - void CheckThreadSafety(); - void ShutdownCollect(); + void CheckThreadSafety(); + void ShutdownCollect(); - void FixGrayBits(bool aForceGC); - bool ShouldMergeZones(ccType aCCType); + void FixGrayBits(bool aForceGC); + bool ShouldMergeZones(ccType aCCType); - void BeginCollection(ccType aCCType, nsICycleCollectorListener *aManualListener); - void MarkRoots(SliceBudget &aBudget); - void ScanRoots(bool aFullySynchGraphBuild); - void ScanIncrementalRoots(); - void ScanWeakMaps(); + void BeginCollection(ccType aCCType, nsICycleCollectorListener *aManualListener); + void MarkRoots(SliceBudget &aBudget); + void ScanRoots(bool aFullySynchGraphBuild); + void ScanIncrementalRoots(); + void ScanWeakMaps(); - // returns whether anything was collected - bool CollectWhite(); + // returns whether anything was collected + bool CollectWhite(); - void CleanupAfterCollection(); + void CleanupAfterCollection(); }; NS_IMPL_ISUPPORTS(nsCycleCollector, nsIMemoryReporter) @@ -1263,26 +1263,26 @@ template class GraphWalker { private: - Visitor mVisitor; + Visitor mVisitor; - void DoWalk(nsDeque &aQueue); + void DoWalk(nsDeque &aQueue); - void CheckedPush(nsDeque &aQueue, PtrInfo *pi) - { - if (!pi) { - MOZ_CRASH(); - } - if (!aQueue.Push(pi, fallible_t())) { - mVisitor.Failed(); - } + void CheckedPush(nsDeque &aQueue, PtrInfo *pi) + { + if (!pi) { + MOZ_CRASH(); } + if (!aQueue.Push(pi, fallible_t())) { + mVisitor.Failed(); + } + } public: - void Walk(PtrInfo *s0); - void WalkFromRoots(GCGraph &aGraph); - // copy-constructing the visitor should be cheap, and less - // indirection than using a reference - GraphWalker(const Visitor aVisitor) : mVisitor(aVisitor) {} + void Walk(PtrInfo *s0); + void WalkFromRoots(GCGraph &aGraph); + // copy-constructing the visitor should be cheap, and less + // indirection than using a reference + GraphWalker(const Visitor aVisitor) : mVisitor(aVisitor) {} }; @@ -1304,75 +1304,75 @@ static mozilla::ThreadLocal sCollectorData; MOZ_NEVER_INLINE static void Fault(const char *msg, const void *ptr=nullptr) { - if (ptr) - printf("Fault in cycle collector: %s (ptr: %p)\n", msg, ptr); - else - printf("Fault in cycle collector: %s\n", msg); + if (ptr) + printf("Fault in cycle collector: %s (ptr: %p)\n", msg, ptr); + else + printf("Fault in cycle collector: %s\n", msg); - NS_RUNTIMEABORT("cycle collector fault"); + NS_RUNTIMEABORT("cycle collector fault"); } static void Fault(const char *msg, PtrInfo *pi) { - Fault(msg, pi->mPointer); + Fault(msg, pi->mPointer); } static inline void ToParticipant(nsISupports *s, nsXPCOMCycleCollectionParticipant **cp) { - // We use QI to move from an nsISupports to an - // nsXPCOMCycleCollectionParticipant, which is a per-class singleton helper - // object that implements traversal and unlinking logic for the nsISupports - // in question. - CallQueryInterface(s, cp); + // We use QI to move from an nsISupports to an + // nsXPCOMCycleCollectionParticipant, which is a per-class singleton helper + // object that implements traversal and unlinking logic for the nsISupports + // in question. + CallQueryInterface(s, cp); } template MOZ_NEVER_INLINE void GraphWalker::Walk(PtrInfo *s0) { - nsDeque queue; - CheckedPush(queue, s0); - DoWalk(queue); + nsDeque queue; + CheckedPush(queue, s0); + DoWalk(queue); } template MOZ_NEVER_INLINE void GraphWalker::WalkFromRoots(GCGraph& aGraph) { - nsDeque queue; - NodePool::Enumerator etor(aGraph.mNodes); - for (uint32_t i = 0; i < aGraph.mRootCount; ++i) { - CheckedPush(queue, etor.GetNext()); - } - DoWalk(queue); + nsDeque queue; + NodePool::Enumerator etor(aGraph.mNodes); + for (uint32_t i = 0; i < aGraph.mRootCount; ++i) { + CheckedPush(queue, etor.GetNext()); + } + DoWalk(queue); } template MOZ_NEVER_INLINE void GraphWalker::DoWalk(nsDeque &aQueue) { - // Use a aQueue to match the breadth-first traversal used when we - // built the graph, for hopefully-better locality. - while (aQueue.GetSize() > 0) { - PtrInfo *pi = static_cast(aQueue.PopFront()); + // Use a aQueue to match the breadth-first traversal used when we + // built the graph, for hopefully-better locality. + while (aQueue.GetSize() > 0) { + PtrInfo *pi = static_cast(aQueue.PopFront()); - if (pi->mParticipant && mVisitor.ShouldVisitNode(pi)) { - mVisitor.VisitNode(pi); - for (EdgePool::Iterator child = pi->FirstChild(), - child_end = pi->LastChild(); - child != child_end; ++child) { - CheckedPush(aQueue, *child); - } - } + if (pi->mParticipant && mVisitor.ShouldVisitNode(pi)) { + mVisitor.VisitNode(pi); + for (EdgePool::Iterator child = pi->FirstChild(), + child_end = pi->LastChild(); + child != child_end; ++child) { + CheckedPush(aQueue, *child); + } } + } } struct CCGraphDescriber : public LinkedListElement { CCGraphDescriber() - : mAddress("0x"), mCnt(0), mType(eUnknown) {} + : mAddress("0x"), mCnt(0), mType(eUnknown) {} enum Type { @@ -1395,416 +1395,416 @@ struct CCGraphDescriber : public LinkedListElement class nsCycleCollectorLogger MOZ_FINAL : public nsICycleCollectorListener { public: - nsCycleCollectorLogger() : - mStream(nullptr), mWantAllTraces(false), - mDisableLog(false), mWantAfterProcessing(false) - { + nsCycleCollectorLogger() : + mStream(nullptr), mWantAllTraces(false), + mDisableLog(false), mWantAfterProcessing(false) + { + } + ~nsCycleCollectorLogger() + { + ClearDescribers(); + if (mStream) { + MozillaUnRegisterDebugFILE(mStream); + fclose(mStream); } - ~nsCycleCollectorLogger() - { - ClearDescribers(); - if (mStream) { - MozillaUnRegisterDebugFILE(mStream); - fclose(mStream); - } - } - NS_DECL_ISUPPORTS + } + NS_DECL_ISUPPORTS - void SetAllTraces() - { - mWantAllTraces = true; - } + void SetAllTraces() + { + mWantAllTraces = true; + } - NS_IMETHOD AllTraces(nsICycleCollectorListener** aListener) - { - SetAllTraces(); - NS_ADDREF(*aListener = this); - return NS_OK; - } + NS_IMETHOD AllTraces(nsICycleCollectorListener** aListener) + { + SetAllTraces(); + NS_ADDREF(*aListener = this); + return NS_OK; + } - NS_IMETHOD GetWantAllTraces(bool* aAllTraces) - { - *aAllTraces = mWantAllTraces; - return NS_OK; - } + NS_IMETHOD GetWantAllTraces(bool* aAllTraces) + { + *aAllTraces = mWantAllTraces; + return NS_OK; + } - NS_IMETHOD GetDisableLog(bool* aDisableLog) - { - *aDisableLog = mDisableLog; - return NS_OK; - } + NS_IMETHOD GetDisableLog(bool* aDisableLog) + { + *aDisableLog = mDisableLog; + return NS_OK; + } - NS_IMETHOD SetDisableLog(bool aDisableLog) - { - mDisableLog = aDisableLog; - return NS_OK; - } + NS_IMETHOD SetDisableLog(bool aDisableLog) + { + mDisableLog = aDisableLog; + return NS_OK; + } - NS_IMETHOD GetWantAfterProcessing(bool* aWantAfterProcessing) - { - *aWantAfterProcessing = mWantAfterProcessing; - return NS_OK; - } + NS_IMETHOD GetWantAfterProcessing(bool* aWantAfterProcessing) + { + *aWantAfterProcessing = mWantAfterProcessing; + return NS_OK; + } - NS_IMETHOD SetWantAfterProcessing(bool aWantAfterProcessing) - { - mWantAfterProcessing = aWantAfterProcessing; - return NS_OK; - } + NS_IMETHOD SetWantAfterProcessing(bool aWantAfterProcessing) + { + mWantAfterProcessing = aWantAfterProcessing; + return NS_OK; + } - NS_IMETHOD GetFilenameIdentifier(nsAString& aIdentifier) - { - aIdentifier = mFilenameIdentifier; - return NS_OK; - } + NS_IMETHOD GetFilenameIdentifier(nsAString& aIdentifier) + { + aIdentifier = mFilenameIdentifier; + return NS_OK; + } - NS_IMETHOD SetFilenameIdentifier(const nsAString& aIdentifier) - { - mFilenameIdentifier = aIdentifier; - return NS_OK; - } + NS_IMETHOD SetFilenameIdentifier(const nsAString& aIdentifier) + { + mFilenameIdentifier = aIdentifier; + return NS_OK; + } - NS_IMETHOD GetGcLogPath(nsAString &aPath) - { - aPath = mGCLogPath; + NS_IMETHOD GetGcLogPath(nsAString &aPath) + { + aPath = mGCLogPath; + return NS_OK; + } + + NS_IMETHOD GetCcLogPath(nsAString &aPath) + { + aPath = mCCLogPath; + return NS_OK; + } + + NS_IMETHOD Begin() + { + mCurrentAddress.AssignLiteral("0x"); + ClearDescribers(); + if (mDisableLog) { return NS_OK; } - NS_IMETHOD GetCcLogPath(nsAString &aPath) - { - aPath = mCCLogPath; - return NS_OK; + // Initially create the log in a file starting with + // "incomplete-gc-edges". We'll move the file and strip off the + // "incomplete-" once the dump completes. (We do this because we don't + // want scripts which poll the filesystem looking for gc/cc dumps to + // grab a file before we're finished writing to it.) + nsCOMPtr gcLogFile = CreateTempFile("incomplete-gc-edges"); + if (NS_WARN_IF(!gcLogFile)) + return NS_ERROR_UNEXPECTED; + + // Dump the JS heap. + FILE* gcLogANSIFile = nullptr; + gcLogFile->OpenANSIFileDesc("w", &gcLogANSIFile); + if (NS_WARN_IF(!gcLogANSIFile)) + return NS_ERROR_UNEXPECTED; + MozillaRegisterDebugFILE(gcLogANSIFile); + CollectorData *data = sCollectorData.get(); + if (data && data->mRuntime) + data->mRuntime->DumpJSHeap(gcLogANSIFile); + MozillaUnRegisterDebugFILE(gcLogANSIFile); + fclose(gcLogANSIFile); + + // Strip off "incomplete-". + nsCOMPtr gcLogFileFinalDestination = + CreateTempFile("gc-edges"); + if (NS_WARN_IF(!gcLogFileFinalDestination)) + return NS_ERROR_UNEXPECTED; + + nsAutoString gcLogFileFinalDestinationName; + gcLogFileFinalDestination->GetLeafName(gcLogFileFinalDestinationName); + if (NS_WARN_IF(gcLogFileFinalDestinationName.IsEmpty())) + return NS_ERROR_UNEXPECTED; + + gcLogFile->MoveTo(/* directory */ nullptr, gcLogFileFinalDestinationName); + + // Log to the error console. + nsCOMPtr cs = + do_GetService(NS_CONSOLESERVICE_CONTRACTID); + if (cs) { + nsAutoString gcLogPath; + gcLogFileFinalDestination->GetPath(gcLogPath); + + nsString msg = NS_LITERAL_STRING("Garbage Collector log dumped to ") + + gcLogPath; + cs->LogStringMessage(msg.get()); + + mGCLogPath = gcLogPath; } - NS_IMETHOD Begin() - { - mCurrentAddress.AssignLiteral("0x"); - ClearDescribers(); - if (mDisableLog) { - return NS_OK; - } + // Open a file for dumping the CC graph. We again prefix with + // "incomplete-". + mOutFile = CreateTempFile("incomplete-cc-edges"); + if (NS_WARN_IF(!mOutFile)) + return NS_ERROR_UNEXPECTED; + MOZ_ASSERT(!mStream); + mOutFile->OpenANSIFileDesc("w", &mStream); + if (NS_WARN_IF(!mStream)) + return NS_ERROR_UNEXPECTED; + MozillaRegisterDebugFILE(mStream); - // Initially create the log in a file starting with - // "incomplete-gc-edges". We'll move the file and strip off the - // "incomplete-" once the dump completes. (We do this because we don't - // want scripts which poll the filesystem looking for gc/cc dumps to - // grab a file before we're finished writing to it.) - nsCOMPtr gcLogFile = CreateTempFile("incomplete-gc-edges"); - if (NS_WARN_IF(!gcLogFile)) - return NS_ERROR_UNEXPECTED; + fprintf(mStream, "# WantAllTraces=%s\n", mWantAllTraces ? "true" : "false"); - // Dump the JS heap. - FILE* gcLogANSIFile = nullptr; - gcLogFile->OpenANSIFileDesc("w", &gcLogANSIFile); - if (NS_WARN_IF(!gcLogANSIFile)) - return NS_ERROR_UNEXPECTED; - MozillaRegisterDebugFILE(gcLogANSIFile); - CollectorData *data = sCollectorData.get(); - if (data && data->mRuntime) - data->mRuntime->DumpJSHeap(gcLogANSIFile); - MozillaUnRegisterDebugFILE(gcLogANSIFile); - fclose(gcLogANSIFile); - - // Strip off "incomplete-". - nsCOMPtr gcLogFileFinalDestination = - CreateTempFile("gc-edges"); - if (NS_WARN_IF(!gcLogFileFinalDestination)) - return NS_ERROR_UNEXPECTED; - - nsAutoString gcLogFileFinalDestinationName; - gcLogFileFinalDestination->GetLeafName(gcLogFileFinalDestinationName); - if (NS_WARN_IF(gcLogFileFinalDestinationName.IsEmpty())) - return NS_ERROR_UNEXPECTED; - - gcLogFile->MoveTo(/* directory */ nullptr, gcLogFileFinalDestinationName); - - // Log to the error console. - nsCOMPtr cs = - do_GetService(NS_CONSOLESERVICE_CONTRACTID); - if (cs) { - nsAutoString gcLogPath; - gcLogFileFinalDestination->GetPath(gcLogPath); - - nsString msg = NS_LITERAL_STRING("Garbage Collector log dumped to ") + - gcLogPath; - cs->LogStringMessage(msg.get()); - - mGCLogPath = gcLogPath; - } - - // Open a file for dumping the CC graph. We again prefix with - // "incomplete-". - mOutFile = CreateTempFile("incomplete-cc-edges"); - if (NS_WARN_IF(!mOutFile)) - return NS_ERROR_UNEXPECTED; - MOZ_ASSERT(!mStream); - mOutFile->OpenANSIFileDesc("w", &mStream); - if (NS_WARN_IF(!mStream)) - return NS_ERROR_UNEXPECTED; - MozillaRegisterDebugFILE(mStream); - - fprintf(mStream, "# WantAllTraces=%s\n", mWantAllTraces ? "true" : "false"); - - return NS_OK; + return NS_OK; + } + NS_IMETHOD NoteRefCountedObject(uint64_t aAddress, uint32_t refCount, + const char *aObjectDescription) + { + if (!mDisableLog) { + fprintf(mStream, "%p [rc=%u] %s\n", (void*)aAddress, refCount, + aObjectDescription); } - NS_IMETHOD NoteRefCountedObject(uint64_t aAddress, uint32_t refCount, - const char *aObjectDescription) - { - if (!mDisableLog) { - fprintf(mStream, "%p [rc=%u] %s\n", (void*)aAddress, refCount, - aObjectDescription); - } - if (mWantAfterProcessing) { - CCGraphDescriber* d = new CCGraphDescriber(); - mDescribers.insertBack(d); - mCurrentAddress.AssignLiteral("0x"); - mCurrentAddress.AppendInt(aAddress, 16); - d->mType = CCGraphDescriber::eRefCountedObject; - d->mAddress = mCurrentAddress; - d->mCnt = refCount; - d->mName.Append(aObjectDescription); - } - return NS_OK; + if (mWantAfterProcessing) { + CCGraphDescriber* d = new CCGraphDescriber(); + mDescribers.insertBack(d); + mCurrentAddress.AssignLiteral("0x"); + mCurrentAddress.AppendInt(aAddress, 16); + d->mType = CCGraphDescriber::eRefCountedObject; + d->mAddress = mCurrentAddress; + d->mCnt = refCount; + d->mName.Append(aObjectDescription); } - NS_IMETHOD NoteGCedObject(uint64_t aAddress, bool aMarked, - const char *aObjectDescription, - uint64_t aCompartmentAddress) - { - if (!mDisableLog) { - fprintf(mStream, "%p [gc%s] %s\n", (void*)aAddress, - aMarked ? ".marked" : "", aObjectDescription); - } - if (mWantAfterProcessing) { - CCGraphDescriber* d = new CCGraphDescriber(); - mDescribers.insertBack(d); - mCurrentAddress.AssignLiteral("0x"); - mCurrentAddress.AppendInt(aAddress, 16); - d->mType = aMarked ? CCGraphDescriber::eGCMarkedObject : - CCGraphDescriber::eGCedObject; - d->mAddress = mCurrentAddress; - d->mName.Append(aObjectDescription); - if (aCompartmentAddress) { - d->mCompartmentOrToAddress.AssignLiteral("0x"); - d->mCompartmentOrToAddress.AppendInt(aCompartmentAddress, 16); - } else { - d->mCompartmentOrToAddress.SetIsVoid(true); - } - } - return NS_OK; + return NS_OK; + } + NS_IMETHOD NoteGCedObject(uint64_t aAddress, bool aMarked, + const char *aObjectDescription, + uint64_t aCompartmentAddress) + { + if (!mDisableLog) { + fprintf(mStream, "%p [gc%s] %s\n", (void*)aAddress, + aMarked ? ".marked" : "", aObjectDescription); } - NS_IMETHOD NoteEdge(uint64_t aToAddress, const char *aEdgeName) - { - if (!mDisableLog) { - fprintf(mStream, "> %p %s\n", (void*)aToAddress, aEdgeName); - } - if (mWantAfterProcessing) { - CCGraphDescriber* d = new CCGraphDescriber(); - mDescribers.insertBack(d); - d->mType = CCGraphDescriber::eEdge; - d->mAddress = mCurrentAddress; - d->mCompartmentOrToAddress.AssignLiteral("0x"); - d->mCompartmentOrToAddress.AppendInt(aToAddress, 16); - d->mName.Append(aEdgeName); - } - return NS_OK; - } - NS_IMETHOD NoteWeakMapEntry(uint64_t aMap, uint64_t aKey, - uint64_t aKeyDelegate, uint64_t aValue) - { - if (!mDisableLog) { - fprintf(mStream, "WeakMapEntry map=%p key=%p keyDelegate=%p value=%p\n", - (void*)aMap, (void*)aKey, (void*)aKeyDelegate, (void*)aValue); - } - // We don't support after-processing for weak map entries. - return NS_OK; - } - NS_IMETHOD NoteIncrementalRoot(uint64_t aAddress) - { - if (!mDisableLog) { - fprintf(mStream, "IncrementalRoot %p\n", (void*)aAddress); - } - // We don't support after-processing for incremental roots. - return NS_OK; - } - NS_IMETHOD BeginResults() - { - if (!mDisableLog) { - fputs("==========\n", mStream); - } - return NS_OK; - } - NS_IMETHOD DescribeRoot(uint64_t aAddress, uint32_t aKnownEdges) - { - if (!mDisableLog) { - fprintf(mStream, "%p [known=%u]\n", (void*)aAddress, aKnownEdges); - } - if (mWantAfterProcessing) { - CCGraphDescriber* d = new CCGraphDescriber(); - mDescribers.insertBack(d); - d->mType = CCGraphDescriber::eRoot; - d->mAddress.AppendInt(aAddress, 16); - d->mCnt = aKnownEdges; - } - return NS_OK; - } - NS_IMETHOD DescribeGarbage(uint64_t aAddress) - { - if (!mDisableLog) { - fprintf(mStream, "%p [garbage]\n", (void*)aAddress); - } - if (mWantAfterProcessing) { - CCGraphDescriber* d = new CCGraphDescriber(); - mDescribers.insertBack(d); - d->mType = CCGraphDescriber::eGarbage; - d->mAddress.AppendInt(aAddress, 16); - } - return NS_OK; - } - NS_IMETHOD End() - { - if (!mDisableLog) { - MOZ_ASSERT(mStream); - MOZ_ASSERT(mOutFile); - - MozillaUnRegisterDebugFILE(mStream); - fclose(mStream); - mStream = nullptr; - - // Strip off "incomplete-" from the log file's name. - nsCOMPtr logFileFinalDestination = - CreateTempFile("cc-edges"); - if (NS_WARN_IF(!logFileFinalDestination)) - return NS_ERROR_UNEXPECTED; - - nsAutoString logFileFinalDestinationName; - logFileFinalDestination->GetLeafName(logFileFinalDestinationName); - if (NS_WARN_IF(logFileFinalDestinationName.IsEmpty())) - return NS_ERROR_UNEXPECTED; - - mOutFile->MoveTo(/* directory = */ nullptr, - logFileFinalDestinationName); - mOutFile = nullptr; - - // Log to the error console. - nsCOMPtr cs = - do_GetService(NS_CONSOLESERVICE_CONTRACTID); - if (cs) { - nsAutoString ccLogPath; - logFileFinalDestination->GetPath(ccLogPath); - - nsString msg = NS_LITERAL_STRING("Cycle Collector log dumped to ") + - ccLogPath; - cs->LogStringMessage(msg.get()); - - mCCLogPath = ccLogPath; - } - } - return NS_OK; - } - NS_IMETHOD ProcessNext(nsICycleCollectorHandler* aHandler, - bool* aCanContinue) - { - if (NS_WARN_IF(!aHandler) || NS_WARN_IF(!mWantAfterProcessing)) - return NS_ERROR_UNEXPECTED; - CCGraphDescriber* d = mDescribers.popFirst(); - if (d) { - switch (d->mType) { - case CCGraphDescriber::eRefCountedObject: - aHandler->NoteRefCountedObject(d->mAddress, - d->mCnt, - d->mName); - break; - case CCGraphDescriber::eGCedObject: - case CCGraphDescriber::eGCMarkedObject: - aHandler->NoteGCedObject(d->mAddress, - d->mType == - CCGraphDescriber::eGCMarkedObject, - d->mName, - d->mCompartmentOrToAddress); - break; - case CCGraphDescriber::eEdge: - aHandler->NoteEdge(d->mAddress, - d->mCompartmentOrToAddress, - d->mName); - break; - case CCGraphDescriber::eRoot: - aHandler->DescribeRoot(d->mAddress, - d->mCnt); - break; - case CCGraphDescriber::eGarbage: - aHandler->DescribeGarbage(d->mAddress); - break; - case CCGraphDescriber::eUnknown: - NS_NOTREACHED("CCGraphDescriber::eUnknown"); - break; - } - delete d; - } - if (!(*aCanContinue = !mDescribers.isEmpty())) { - mCurrentAddress.AssignLiteral("0x"); - } - return NS_OK; - } -private: - /** - * Create a new file named something like aPrefix.$PID.$IDENTIFIER.log in - * $MOZ_CC_LOG_DIRECTORY or in the system's temp directory. No existing - * file will be overwritten; if aPrefix.$PID.$IDENTIFIER.log exists, we'll - * try a file named something like aPrefix.$PID.$IDENTIFIER-1.log, and so - * on. - */ - already_AddRefed - CreateTempFile(const char* aPrefix) - { - nsPrintfCString filename("%s.%d%s%s.log", - aPrefix, - base::GetCurrentProcId(), - mFilenameIdentifier.IsEmpty() ? "" : ".", - NS_ConvertUTF16toUTF8(mFilenameIdentifier).get()); - - // Get the log directory either from $MOZ_CC_LOG_DIRECTORY or from - // the fallback directories in OpenTempFile. We don't use an nsCOMPtr - // here because OpenTempFile uses an in/out param and getter_AddRefs - // wouldn't work. - nsIFile* logFile = nullptr; - if (char* env = PR_GetEnv("MOZ_CC_LOG_DIRECTORY")) { - NS_NewNativeLocalFile(nsCString(env), /* followLinks = */ true, - &logFile); - } - - // In Android case, this function will open a file named aFilename under - // specific folder (/data/local/tmp/memory-reports). Otherwise, it will - // open a file named aFilename under "NS_OS_TEMP_DIR". - nsresult rv = nsDumpUtils::OpenTempFile( - filename, - &logFile, - NS_LITERAL_CSTRING("memory-reports")); - if (NS_FAILED(rv)) { - NS_IF_RELEASE(logFile); - return nullptr; - } - - return dont_AddRef(logFile); - } - - void ClearDescribers() - { - CCGraphDescriber* d; - while((d = mDescribers.popFirst())) { - delete d; + if (mWantAfterProcessing) { + CCGraphDescriber* d = new CCGraphDescriber(); + mDescribers.insertBack(d); + mCurrentAddress.AssignLiteral("0x"); + mCurrentAddress.AppendInt(aAddress, 16); + d->mType = aMarked ? CCGraphDescriber::eGCMarkedObject : + CCGraphDescriber::eGCedObject; + d->mAddress = mCurrentAddress; + d->mName.Append(aObjectDescription); + if (aCompartmentAddress) { + d->mCompartmentOrToAddress.AssignLiteral("0x"); + d->mCompartmentOrToAddress.AppendInt(aCompartmentAddress, 16); + } else { + d->mCompartmentOrToAddress.SetIsVoid(true); } } + return NS_OK; + } + NS_IMETHOD NoteEdge(uint64_t aToAddress, const char *aEdgeName) + { + if (!mDisableLog) { + fprintf(mStream, "> %p %s\n", (void*)aToAddress, aEdgeName); + } + if (mWantAfterProcessing) { + CCGraphDescriber* d = new CCGraphDescriber(); + mDescribers.insertBack(d); + d->mType = CCGraphDescriber::eEdge; + d->mAddress = mCurrentAddress; + d->mCompartmentOrToAddress.AssignLiteral("0x"); + d->mCompartmentOrToAddress.AppendInt(aToAddress, 16); + d->mName.Append(aEdgeName); + } + return NS_OK; + } + NS_IMETHOD NoteWeakMapEntry(uint64_t aMap, uint64_t aKey, + uint64_t aKeyDelegate, uint64_t aValue) + { + if (!mDisableLog) { + fprintf(mStream, "WeakMapEntry map=%p key=%p keyDelegate=%p value=%p\n", + (void*)aMap, (void*)aKey, (void*)aKeyDelegate, (void*)aValue); + } + // We don't support after-processing for weak map entries. + return NS_OK; + } + NS_IMETHOD NoteIncrementalRoot(uint64_t aAddress) + { + if (!mDisableLog) { + fprintf(mStream, "IncrementalRoot %p\n", (void*)aAddress); + } + // We don't support after-processing for incremental roots. + return NS_OK; + } + NS_IMETHOD BeginResults() + { + if (!mDisableLog) { + fputs("==========\n", mStream); + } + return NS_OK; + } + NS_IMETHOD DescribeRoot(uint64_t aAddress, uint32_t aKnownEdges) + { + if (!mDisableLog) { + fprintf(mStream, "%p [known=%u]\n", (void*)aAddress, aKnownEdges); + } + if (mWantAfterProcessing) { + CCGraphDescriber* d = new CCGraphDescriber(); + mDescribers.insertBack(d); + d->mType = CCGraphDescriber::eRoot; + d->mAddress.AppendInt(aAddress, 16); + d->mCnt = aKnownEdges; + } + return NS_OK; + } + NS_IMETHOD DescribeGarbage(uint64_t aAddress) + { + if (!mDisableLog) { + fprintf(mStream, "%p [garbage]\n", (void*)aAddress); + } + if (mWantAfterProcessing) { + CCGraphDescriber* d = new CCGraphDescriber(); + mDescribers.insertBack(d); + d->mType = CCGraphDescriber::eGarbage; + d->mAddress.AppendInt(aAddress, 16); + } + return NS_OK; + } + NS_IMETHOD End() + { + if (!mDisableLog) { + MOZ_ASSERT(mStream); + MOZ_ASSERT(mOutFile); - FILE *mStream; - nsCOMPtr mOutFile; - bool mWantAllTraces; - bool mDisableLog; - bool mWantAfterProcessing; - nsString mFilenameIdentifier; - nsString mGCLogPath; - nsString mCCLogPath; - nsCString mCurrentAddress; - mozilla::LinkedList mDescribers; + MozillaUnRegisterDebugFILE(mStream); + fclose(mStream); + mStream = nullptr; + + // Strip off "incomplete-" from the log file's name. + nsCOMPtr logFileFinalDestination = + CreateTempFile("cc-edges"); + if (NS_WARN_IF(!logFileFinalDestination)) + return NS_ERROR_UNEXPECTED; + + nsAutoString logFileFinalDestinationName; + logFileFinalDestination->GetLeafName(logFileFinalDestinationName); + if (NS_WARN_IF(logFileFinalDestinationName.IsEmpty())) + return NS_ERROR_UNEXPECTED; + + mOutFile->MoveTo(/* directory = */ nullptr, + logFileFinalDestinationName); + mOutFile = nullptr; + + // Log to the error console. + nsCOMPtr cs = + do_GetService(NS_CONSOLESERVICE_CONTRACTID); + if (cs) { + nsAutoString ccLogPath; + logFileFinalDestination->GetPath(ccLogPath); + + nsString msg = NS_LITERAL_STRING("Cycle Collector log dumped to ") + + ccLogPath; + cs->LogStringMessage(msg.get()); + + mCCLogPath = ccLogPath; + } + } + return NS_OK; + } + NS_IMETHOD ProcessNext(nsICycleCollectorHandler* aHandler, + bool* aCanContinue) + { + if (NS_WARN_IF(!aHandler) || NS_WARN_IF(!mWantAfterProcessing)) + return NS_ERROR_UNEXPECTED; + CCGraphDescriber* d = mDescribers.popFirst(); + if (d) { + switch (d->mType) { + case CCGraphDescriber::eRefCountedObject: + aHandler->NoteRefCountedObject(d->mAddress, + d->mCnt, + d->mName); + break; + case CCGraphDescriber::eGCedObject: + case CCGraphDescriber::eGCMarkedObject: + aHandler->NoteGCedObject(d->mAddress, + d->mType == + CCGraphDescriber::eGCMarkedObject, + d->mName, + d->mCompartmentOrToAddress); + break; + case CCGraphDescriber::eEdge: + aHandler->NoteEdge(d->mAddress, + d->mCompartmentOrToAddress, + d->mName); + break; + case CCGraphDescriber::eRoot: + aHandler->DescribeRoot(d->mAddress, + d->mCnt); + break; + case CCGraphDescriber::eGarbage: + aHandler->DescribeGarbage(d->mAddress); + break; + case CCGraphDescriber::eUnknown: + NS_NOTREACHED("CCGraphDescriber::eUnknown"); + break; + } + delete d; + } + if (!(*aCanContinue = !mDescribers.isEmpty())) { + mCurrentAddress.AssignLiteral("0x"); + } + return NS_OK; + } +private: + /** + * Create a new file named something like aPrefix.$PID.$IDENTIFIER.log in + * $MOZ_CC_LOG_DIRECTORY or in the system's temp directory. No existing + * file will be overwritten; if aPrefix.$PID.$IDENTIFIER.log exists, we'll + * try a file named something like aPrefix.$PID.$IDENTIFIER-1.log, and so + * on. + */ + already_AddRefed + CreateTempFile(const char* aPrefix) + { + nsPrintfCString filename("%s.%d%s%s.log", + aPrefix, + base::GetCurrentProcId(), + mFilenameIdentifier.IsEmpty() ? "" : ".", + NS_ConvertUTF16toUTF8(mFilenameIdentifier).get()); + + // Get the log directory either from $MOZ_CC_LOG_DIRECTORY or from + // the fallback directories in OpenTempFile. We don't use an nsCOMPtr + // here because OpenTempFile uses an in/out param and getter_AddRefs + // wouldn't work. + nsIFile* logFile = nullptr; + if (char* env = PR_GetEnv("MOZ_CC_LOG_DIRECTORY")) { + NS_NewNativeLocalFile(nsCString(env), /* followLinks = */ true, + &logFile); + } + + // In Android case, this function will open a file named aFilename under + // specific folder (/data/local/tmp/memory-reports). Otherwise, it will + // open a file named aFilename under "NS_OS_TEMP_DIR". + nsresult rv = nsDumpUtils::OpenTempFile( + filename, + &logFile, + NS_LITERAL_CSTRING("memory-reports")); + if (NS_FAILED(rv)) { + NS_IF_RELEASE(logFile); + return nullptr; + } + + return dont_AddRef(logFile); + } + + void ClearDescribers() + { + CCGraphDescriber* d; + while((d = mDescribers.popFirst())) { + delete d; + } + } + + FILE *mStream; + nsCOMPtr mOutFile; + bool mWantAllTraces; + bool mDisableLog; + bool mWantAfterProcessing; + nsString mFilenameIdentifier; + nsString mGCLogPath; + nsString mCCLogPath; + nsCString mCurrentAddress; + mozilla::LinkedList mDescribers; }; NS_IMPL_ISUPPORTS(nsCycleCollectorLogger, nsICycleCollectorListener) @@ -1814,12 +1814,12 @@ nsCycleCollectorLoggerConstructor(nsISupports* aOuter, const nsIID& aIID, void* *aInstancePtr) { - if (NS_WARN_IF(aOuter)) - return NS_ERROR_NO_AGGREGATION; + if (NS_WARN_IF(aOuter)) + return NS_ERROR_NO_AGGREGATION; - nsISupports *logger = new nsCycleCollectorLogger(); + nsISupports *logger = new nsCycleCollectorLogger(); - return logger->QueryInterface(aIID, aInstancePtr); + return logger->QueryInterface(aIID, aInstancePtr); } //////////////////////////////////////////////////////////////////////// @@ -1830,98 +1830,98 @@ class GCGraphBuilder : public nsCycleCollectionTraversalCallback, public nsCycleCollectionNoteRootCallback { private: - GCGraph &mGraph; - CycleCollectorResults &mResults; - NodePool::Builder mNodeBuilder; - EdgePool::Builder mEdgeBuilder; - PtrInfo *mCurrPi; - nsCycleCollectionParticipant *mJSParticipant; - nsCycleCollectionParticipant *mJSZoneParticipant; - nsCString mNextEdgeName; - nsICycleCollectorListener *mListener; - bool mMergeZones; - bool mRanOutOfMemory; + GCGraph &mGraph; + CycleCollectorResults &mResults; + NodePool::Builder mNodeBuilder; + EdgePool::Builder mEdgeBuilder; + PtrInfo *mCurrPi; + nsCycleCollectionParticipant *mJSParticipant; + nsCycleCollectionParticipant *mJSZoneParticipant; + nsCString mNextEdgeName; + nsICycleCollectorListener *mListener; + bool mMergeZones; + bool mRanOutOfMemory; public: - GCGraphBuilder(GCGraph &aGraph, - CycleCollectorResults &aResults, - CycleCollectedJSRuntime *aJSRuntime, - nsICycleCollectorListener *aListener, - bool aMergeZones); - virtual ~GCGraphBuilder(); + GCGraphBuilder(GCGraph &aGraph, + CycleCollectorResults &aResults, + CycleCollectedJSRuntime *aJSRuntime, + nsICycleCollectorListener *aListener, + bool aMergeZones); + virtual ~GCGraphBuilder(); - bool WantAllTraces() const - { - return nsCycleCollectionNoteRootCallback::WantAllTraces(); - } + bool WantAllTraces() const + { + return nsCycleCollectionNoteRootCallback::WantAllTraces(); + } - PtrInfo* AddNode(void *aPtr, nsCycleCollectionParticipant *aParticipant); - PtrInfo* AddWeakMapNode(void* node); - void Traverse(PtrInfo* aPtrInfo); - void SetLastChild(); + PtrInfo* AddNode(void *aPtr, nsCycleCollectionParticipant *aParticipant); + PtrInfo* AddWeakMapNode(void* node); + void Traverse(PtrInfo* aPtrInfo); + void SetLastChild(); - bool RanOutOfMemory() const { return mRanOutOfMemory; } + bool RanOutOfMemory() const { return mRanOutOfMemory; } private: - void DescribeNode(uint32_t refCount, const char *objName) - { - mCurrPi->mRefCount = refCount; - } + void DescribeNode(uint32_t refCount, const char *objName) + { + mCurrPi->mRefCount = refCount; + } public: - // nsCycleCollectionNoteRootCallback methods. - NS_IMETHOD_(void) NoteXPCOMRoot(nsISupports *root); - NS_IMETHOD_(void) NoteJSRoot(void *root); - NS_IMETHOD_(void) NoteNativeRoot(void *root, nsCycleCollectionParticipant *participant); - NS_IMETHOD_(void) NoteWeakMapping(void *map, void *key, void *kdelegate, void *val); + // nsCycleCollectionNoteRootCallback methods. + NS_IMETHOD_(void) NoteXPCOMRoot(nsISupports *root); + NS_IMETHOD_(void) NoteJSRoot(void *root); + NS_IMETHOD_(void) NoteNativeRoot(void *root, nsCycleCollectionParticipant *participant); + NS_IMETHOD_(void) NoteWeakMapping(void *map, void *key, void *kdelegate, void *val); - // nsCycleCollectionTraversalCallback methods. - NS_IMETHOD_(void) DescribeRefCountedNode(nsrefcnt refCount, - const char *objName); - NS_IMETHOD_(void) DescribeGCedNode(bool isMarked, const char *objName, - uint64_t aCompartmentAddress); + // nsCycleCollectionTraversalCallback methods. + NS_IMETHOD_(void) DescribeRefCountedNode(nsrefcnt refCount, + const char *objName); + NS_IMETHOD_(void) DescribeGCedNode(bool isMarked, const char *objName, + uint64_t aCompartmentAddress); - NS_IMETHOD_(void) NoteXPCOMChild(nsISupports *child); - NS_IMETHOD_(void) NoteJSChild(void *child); - NS_IMETHOD_(void) NoteNativeChild(void *child, - nsCycleCollectionParticipant *participant); - NS_IMETHOD_(void) NoteNextEdgeName(const char* name); + NS_IMETHOD_(void) NoteXPCOMChild(nsISupports *child); + NS_IMETHOD_(void) NoteJSChild(void *child); + NS_IMETHOD_(void) NoteNativeChild(void *child, + nsCycleCollectionParticipant *participant); + NS_IMETHOD_(void) NoteNextEdgeName(const char* name); private: - NS_IMETHOD_(void) NoteRoot(void *root, - nsCycleCollectionParticipant *participant) - { - MOZ_ASSERT(root); - MOZ_ASSERT(participant); + NS_IMETHOD_(void) NoteRoot(void *root, + nsCycleCollectionParticipant *participant) + { + MOZ_ASSERT(root); + MOZ_ASSERT(participant); - if (!participant->CanSkipInCC(root) || MOZ_UNLIKELY(WantAllTraces())) { - AddNode(root, participant); - } + if (!participant->CanSkipInCC(root) || MOZ_UNLIKELY(WantAllTraces())) { + AddNode(root, participant); } + } - NS_IMETHOD_(void) NoteChild(void *child, nsCycleCollectionParticipant *cp, - nsCString edgeName) - { - PtrInfo *childPi = AddNode(child, cp); - if (!childPi) - return; - mEdgeBuilder.Add(childPi); - if (mListener) { - mListener->NoteEdge((uint64_t)child, edgeName.get()); - } - ++childPi->mInternalRefs; + NS_IMETHOD_(void) NoteChild(void *child, nsCycleCollectionParticipant *cp, + nsCString edgeName) + { + PtrInfo *childPi = AddNode(child, cp); + if (!childPi) + return; + mEdgeBuilder.Add(childPi); + if (mListener) { + mListener->NoteEdge((uint64_t)child, edgeName.get()); } + ++childPi->mInternalRefs; + } - JS::Zone *MergeZone(void *gcthing) { - if (!mMergeZones) { - return nullptr; - } - JS::Zone *zone = JS::GetGCThingZone(gcthing); - if (js::IsSystemZone(zone)) { - return nullptr; - } - return zone; + JS::Zone *MergeZone(void *gcthing) { + if (!mMergeZones) { + return nullptr; } + JS::Zone *zone = JS::GetGCThingZone(gcthing); + if (js::IsSystemZone(zone)) { + return nullptr; + } + return zone; + } }; GCGraphBuilder::GCGraphBuilder(GCGraph &aGraph, @@ -1929,38 +1929,38 @@ GCGraphBuilder::GCGraphBuilder(GCGraph &aGraph, CycleCollectedJSRuntime *aJSRuntime, nsICycleCollectorListener *aListener, bool aMergeZones) - : mGraph(aGraph), - mResults(aResults), - mNodeBuilder(aGraph.mNodes), - mEdgeBuilder(aGraph.mEdges), - mJSParticipant(nullptr), - mJSZoneParticipant(nullptr), - mListener(aListener), - mMergeZones(aMergeZones), - mRanOutOfMemory(false) + : mGraph(aGraph), + mResults(aResults), + mNodeBuilder(aGraph.mNodes), + mEdgeBuilder(aGraph.mEdges), + mJSParticipant(nullptr), + mJSZoneParticipant(nullptr), + mListener(aListener), + mMergeZones(aMergeZones), + mRanOutOfMemory(false) { - if (aJSRuntime) { - mJSParticipant = aJSRuntime->GCThingParticipant(); - mJSZoneParticipant = aJSRuntime->ZoneParticipant(); + if (aJSRuntime) { + mJSParticipant = aJSRuntime->GCThingParticipant(); + mJSZoneParticipant = aJSRuntime->ZoneParticipant(); + } + + uint32_t flags = 0; + if (!flags && mListener) { + flags = nsCycleCollectionTraversalCallback::WANT_DEBUG_INFO; + bool all = false; + mListener->GetWantAllTraces(&all); + if (all) { + flags |= nsCycleCollectionTraversalCallback::WANT_ALL_TRACES; + mWantAllTraces = true; // for nsCycleCollectionNoteRootCallback } + } - uint32_t flags = 0; - if (!flags && mListener) { - flags = nsCycleCollectionTraversalCallback::WANT_DEBUG_INFO; - bool all = false; - mListener->GetWantAllTraces(&all); - if (all) { - flags |= nsCycleCollectionTraversalCallback::WANT_ALL_TRACES; - mWantAllTraces = true; // for nsCycleCollectionNoteRootCallback - } - } + mFlags |= flags; - mFlags |= flags; + mMergeZones = mMergeZones && MOZ_LIKELY(!WantAllTraces()); - mMergeZones = mMergeZones && MOZ_LIKELY(!WantAllTraces()); - - MOZ_ASSERT(nsCycleCollectionNoteRootCallback::WantAllTraces() == - nsCycleCollectionTraversalCallback::WantAllTraces()); + MOZ_ASSERT(nsCycleCollectionNoteRootCallback::WantAllTraces() == + nsCycleCollectionTraversalCallback::WantAllTraces()); } GCGraphBuilder::~GCGraphBuilder() @@ -1970,219 +1970,219 @@ GCGraphBuilder::~GCGraphBuilder() PtrInfo* GCGraphBuilder::AddNode(void *aPtr, nsCycleCollectionParticipant *aParticipant) { - PtrToNodeEntry *e = mGraph.AddNodeToMap(aPtr); - if (!e) { - mRanOutOfMemory = true; - return nullptr; - } + PtrToNodeEntry *e = mGraph.AddNodeToMap(aPtr); + if (!e) { + mRanOutOfMemory = true; + return nullptr; + } - PtrInfo *result; - if (!e->mNode) { - // New entry. - result = mNodeBuilder.Add(aPtr, aParticipant); - e->mNode = result; - NS_ASSERTION(result, "mNodeBuilder.Add returned null"); - } else { - result = e->mNode; - MOZ_ASSERT(result->mParticipant == aParticipant, - "nsCycleCollectionParticipant shouldn't change!"); - } - return result; + PtrInfo *result; + if (!e->mNode) { + // New entry. + result = mNodeBuilder.Add(aPtr, aParticipant); + e->mNode = result; + NS_ASSERTION(result, "mNodeBuilder.Add returned null"); + } else { + result = e->mNode; + MOZ_ASSERT(result->mParticipant == aParticipant, + "nsCycleCollectionParticipant shouldn't change!"); + } + return result; } MOZ_NEVER_INLINE void GCGraphBuilder::Traverse(PtrInfo* aPtrInfo) { - mCurrPi = aPtrInfo; + mCurrPi = aPtrInfo; - mCurrPi->SetFirstChild(mEdgeBuilder.Mark()); + mCurrPi->SetFirstChild(mEdgeBuilder.Mark()); - if (!aPtrInfo->mParticipant) { - return; - } + if (!aPtrInfo->mParticipant) { + return; + } - nsresult rv = aPtrInfo->mParticipant->Traverse(aPtrInfo->mPointer, *this); - if (NS_FAILED(rv)) { - Fault("script pointer traversal failed", aPtrInfo); - } + nsresult rv = aPtrInfo->mParticipant->Traverse(aPtrInfo->mPointer, *this); + if (NS_FAILED(rv)) { + Fault("script pointer traversal failed", aPtrInfo); + } } void GCGraphBuilder::SetLastChild() { - mCurrPi->SetLastChild(mEdgeBuilder.Mark()); + mCurrPi->SetLastChild(mEdgeBuilder.Mark()); } NS_IMETHODIMP_(void) GCGraphBuilder::NoteXPCOMRoot(nsISupports *root) { - root = CanonicalizeXPCOMParticipant(root); - NS_ASSERTION(root, - "Don't add objects that don't participate in collection!"); + root = CanonicalizeXPCOMParticipant(root); + NS_ASSERTION(root, + "Don't add objects that don't participate in collection!"); - nsXPCOMCycleCollectionParticipant *cp; - ToParticipant(root, &cp); + nsXPCOMCycleCollectionParticipant *cp; + ToParticipant(root, &cp); - NoteRoot(root, cp); + NoteRoot(root, cp); } NS_IMETHODIMP_(void) GCGraphBuilder::NoteJSRoot(void *root) { - if (JS::Zone *zone = MergeZone(root)) { - NoteRoot(zone, mJSZoneParticipant); - } else { - NoteRoot(root, mJSParticipant); - } + if (JS::Zone *zone = MergeZone(root)) { + NoteRoot(zone, mJSZoneParticipant); + } else { + NoteRoot(root, mJSParticipant); + } } NS_IMETHODIMP_(void) GCGraphBuilder::NoteNativeRoot(void *root, nsCycleCollectionParticipant *participant) { - NoteRoot(root, participant); + NoteRoot(root, participant); } NS_IMETHODIMP_(void) GCGraphBuilder::DescribeRefCountedNode(nsrefcnt refCount, const char *objName) { - if (refCount == 0) - Fault("zero refcount", mCurrPi); - if (refCount == UINT32_MAX) - Fault("overflowing refcount", mCurrPi); - mResults.mVisitedRefCounted++; + if (refCount == 0) + Fault("zero refcount", mCurrPi); + if (refCount == UINT32_MAX) + Fault("overflowing refcount", mCurrPi); + mResults.mVisitedRefCounted++; - if (mListener) { - mListener->NoteRefCountedObject((uint64_t)mCurrPi->mPointer, refCount, - objName); - } + if (mListener) { + mListener->NoteRefCountedObject((uint64_t)mCurrPi->mPointer, refCount, + objName); + } - DescribeNode(refCount, objName); + DescribeNode(refCount, objName); } NS_IMETHODIMP_(void) GCGraphBuilder::DescribeGCedNode(bool isMarked, const char *objName, uint64_t aCompartmentAddress) { - uint32_t refCount = isMarked ? UINT32_MAX : 0; - mResults.mVisitedGCed++; + uint32_t refCount = isMarked ? UINT32_MAX : 0; + mResults.mVisitedGCed++; - if (mListener) { - mListener->NoteGCedObject((uint64_t)mCurrPi->mPointer, isMarked, - objName, aCompartmentAddress); - } + if (mListener) { + mListener->NoteGCedObject((uint64_t)mCurrPi->mPointer, isMarked, + objName, aCompartmentAddress); + } - DescribeNode(refCount, objName); + DescribeNode(refCount, objName); } NS_IMETHODIMP_(void) GCGraphBuilder::NoteXPCOMChild(nsISupports *child) { - nsCString edgeName; - if (WantDebugInfo()) { - edgeName.Assign(mNextEdgeName); - mNextEdgeName.Truncate(); - } - if (!child || !(child = CanonicalizeXPCOMParticipant(child))) - return; + nsCString edgeName; + if (WantDebugInfo()) { + edgeName.Assign(mNextEdgeName); + mNextEdgeName.Truncate(); + } + if (!child || !(child = CanonicalizeXPCOMParticipant(child))) + return; - nsXPCOMCycleCollectionParticipant *cp; - ToParticipant(child, &cp); - if (cp && (!cp->CanSkipThis(child) || WantAllTraces())) { - NoteChild(child, cp, edgeName); - } + nsXPCOMCycleCollectionParticipant *cp; + ToParticipant(child, &cp); + if (cp && (!cp->CanSkipThis(child) || WantAllTraces())) { + NoteChild(child, cp, edgeName); + } } NS_IMETHODIMP_(void) GCGraphBuilder::NoteNativeChild(void *child, nsCycleCollectionParticipant *participant) { - nsCString edgeName; - if (WantDebugInfo()) { - edgeName.Assign(mNextEdgeName); - mNextEdgeName.Truncate(); - } - if (!child) - return; + nsCString edgeName; + if (WantDebugInfo()) { + edgeName.Assign(mNextEdgeName); + mNextEdgeName.Truncate(); + } + if (!child) + return; - MOZ_ASSERT(participant, "Need a nsCycleCollectionParticipant!"); - NoteChild(child, participant, edgeName); + MOZ_ASSERT(participant, "Need a nsCycleCollectionParticipant!"); + NoteChild(child, participant, edgeName); } NS_IMETHODIMP_(void) GCGraphBuilder::NoteJSChild(void *child) { - if (!child) { - return; - } + if (!child) { + return; + } - nsCString edgeName; - if (MOZ_UNLIKELY(WantDebugInfo())) { - edgeName.Assign(mNextEdgeName); - mNextEdgeName.Truncate(); - } + nsCString edgeName; + if (MOZ_UNLIKELY(WantDebugInfo())) { + edgeName.Assign(mNextEdgeName); + mNextEdgeName.Truncate(); + } - if (xpc_GCThingIsGrayCCThing(child) || MOZ_UNLIKELY(WantAllTraces())) { - if (JS::Zone *zone = MergeZone(child)) { - NoteChild(zone, mJSZoneParticipant, edgeName); - } else { - NoteChild(child, mJSParticipant, edgeName); - } + if (xpc_GCThingIsGrayCCThing(child) || MOZ_UNLIKELY(WantAllTraces())) { + if (JS::Zone *zone = MergeZone(child)) { + NoteChild(zone, mJSZoneParticipant, edgeName); + } else { + NoteChild(child, mJSParticipant, edgeName); } + } } NS_IMETHODIMP_(void) GCGraphBuilder::NoteNextEdgeName(const char* name) { - if (WantDebugInfo()) { - mNextEdgeName = name; - } + if (WantDebugInfo()) { + mNextEdgeName = name; + } } PtrInfo* GCGraphBuilder::AddWeakMapNode(void *node) { - MOZ_ASSERT(node, "Weak map node should be non-null."); + MOZ_ASSERT(node, "Weak map node should be non-null."); - if (!xpc_GCThingIsGrayCCThing(node) && !WantAllTraces()) - return nullptr; + if (!xpc_GCThingIsGrayCCThing(node) && !WantAllTraces()) + return nullptr; - if (JS::Zone *zone = MergeZone(node)) { - return AddNode(zone, mJSZoneParticipant); - } else { - return AddNode(node, mJSParticipant); - } + if (JS::Zone *zone = MergeZone(node)) { + return AddNode(zone, mJSZoneParticipant); + } else { + return AddNode(node, mJSParticipant); + } } NS_IMETHODIMP_(void) GCGraphBuilder::NoteWeakMapping(void *map, void *key, void *kdelegate, void *val) { - // Don't try to optimize away the entry here, as we've already attempted to - // do that in TraceWeakMapping in nsXPConnect. - WeakMapping *mapping = mGraph.mWeakMaps.AppendElement(); - mapping->mMap = map ? AddWeakMapNode(map) : nullptr; - mapping->mKey = key ? AddWeakMapNode(key) : nullptr; - mapping->mKeyDelegate = kdelegate ? AddWeakMapNode(kdelegate) : mapping->mKey; - mapping->mVal = val ? AddWeakMapNode(val) : nullptr; + // Don't try to optimize away the entry here, as we've already attempted to + // do that in TraceWeakMapping in nsXPConnect. + WeakMapping *mapping = mGraph.mWeakMaps.AppendElement(); + mapping->mMap = map ? AddWeakMapNode(map) : nullptr; + mapping->mKey = key ? AddWeakMapNode(key) : nullptr; + mapping->mKeyDelegate = kdelegate ? AddWeakMapNode(kdelegate) : mapping->mKey; + mapping->mVal = val ? AddWeakMapNode(val) : nullptr; - if (mListener) { - mListener->NoteWeakMapEntry((uint64_t)map, (uint64_t)key, - (uint64_t)kdelegate, (uint64_t)val); - } + if (mListener) { + mListener->NoteWeakMapEntry((uint64_t)map, (uint64_t)key, + (uint64_t)kdelegate, (uint64_t)val); + } } static bool AddPurpleRoot(GCGraphBuilder &aBuilder, void *aRoot, nsCycleCollectionParticipant *aParti) { - CanonicalizeParticipant(&aRoot, &aParti); + CanonicalizeParticipant(&aRoot, &aParti); - if (aBuilder.WantAllTraces() || !aParti->CanSkipInCC(aRoot)) { - PtrInfo *pinfo = aBuilder.AddNode(aRoot, aParti); - if (!pinfo) { - return false; - } + if (aBuilder.WantAllTraces() || !aParti->CanSkipInCC(aRoot)) { + PtrInfo *pinfo = aBuilder.AddNode(aRoot, aParti); + if (!pinfo) { + return false; } + } - return true; + return true; } // MayHaveChild() will be false after a Traverse if the object does @@ -2190,61 +2190,61 @@ AddPurpleRoot(GCGraphBuilder &aBuilder, void *aRoot, nsCycleCollectionParticipan class ChildFinder : public nsCycleCollectionTraversalCallback { public: - ChildFinder() : mMayHaveChild(false) {} + ChildFinder() : mMayHaveChild(false) {} - // The logic of the Note*Child functions must mirror that of their - // respective functions in GCGraphBuilder. - NS_IMETHOD_(void) NoteXPCOMChild(nsISupports *child); - NS_IMETHOD_(void) NoteNativeChild(void *child, - nsCycleCollectionParticipant *helper); - NS_IMETHOD_(void) NoteJSChild(void *child); + // The logic of the Note*Child functions must mirror that of their + // respective functions in GCGraphBuilder. + NS_IMETHOD_(void) NoteXPCOMChild(nsISupports *child); + NS_IMETHOD_(void) NoteNativeChild(void *child, + nsCycleCollectionParticipant *helper); + NS_IMETHOD_(void) NoteJSChild(void *child); - NS_IMETHOD_(void) DescribeRefCountedNode(nsrefcnt refcount, - const char *objname) {} - NS_IMETHOD_(void) DescribeGCedNode(bool ismarked, - const char *objname, - uint64_t aCompartmentAddress) {} - NS_IMETHOD_(void) NoteNextEdgeName(const char* name) {} - bool MayHaveChild() { - return mMayHaveChild; - } + NS_IMETHOD_(void) DescribeRefCountedNode(nsrefcnt refcount, + const char *objname) {} + NS_IMETHOD_(void) DescribeGCedNode(bool ismarked, + const char *objname, + uint64_t aCompartmentAddress) {} + NS_IMETHOD_(void) NoteNextEdgeName(const char* name) {} + bool MayHaveChild() { + return mMayHaveChild; + } private: - bool mMayHaveChild; + bool mMayHaveChild; }; NS_IMETHODIMP_(void) ChildFinder::NoteXPCOMChild(nsISupports *child) { - if (!child || !(child = CanonicalizeXPCOMParticipant(child))) - return; - nsXPCOMCycleCollectionParticipant *cp; - ToParticipant(child, &cp); - if (cp && !cp->CanSkip(child, true)) - mMayHaveChild = true; + if (!child || !(child = CanonicalizeXPCOMParticipant(child))) + return; + nsXPCOMCycleCollectionParticipant *cp; + ToParticipant(child, &cp); + if (cp && !cp->CanSkip(child, true)) + mMayHaveChild = true; } NS_IMETHODIMP_(void) ChildFinder::NoteNativeChild(void *child, nsCycleCollectionParticipant *helper) { - if (child) - mMayHaveChild = true; + if (child) + mMayHaveChild = true; } NS_IMETHODIMP_(void) ChildFinder::NoteJSChild(void *child) { - if (child && xpc_GCThingIsGrayCCThing(child)) { - mMayHaveChild = true; - } + if (child && xpc_GCThingIsGrayCCThing(child)) { + mMayHaveChild = true; + } } static bool MayHaveChild(void *o, nsCycleCollectionParticipant* cp) { - ChildFinder cf; - cp->Traverse(o, cf); - return cf.MayHaveChild(); + ChildFinder cf; + cp->Traverse(o, cf); + return cf.MayHaveChild(); } template @@ -2257,41 +2257,41 @@ template class SegmentedArray { public: - ~SegmentedArray() - { - MOZ_ASSERT(IsEmpty()); - } + ~SegmentedArray() + { + MOZ_ASSERT(IsEmpty()); + } - void AppendElement(T& aElement) - { - SegmentedArrayElement* last = mSegments.getLast(); - if (!last || last->Length() == last->Capacity()) { - last = new SegmentedArrayElement(); - mSegments.insertBack(last); - } - last->AppendElement(aElement); + void AppendElement(T& aElement) + { + SegmentedArrayElement* last = mSegments.getLast(); + if (!last || last->Length() == last->Capacity()) { + last = new SegmentedArrayElement(); + mSegments.insertBack(last); } + last->AppendElement(aElement); + } - void Clear() - { - SegmentedArrayElement* first; - while ((first = mSegments.popFirst())) { - delete first; - } + void Clear() + { + SegmentedArrayElement* first; + while ((first = mSegments.popFirst())) { + delete first; } + } - SegmentedArrayElement* GetFirstSegment() - { - return mSegments.getFirst(); - } + SegmentedArrayElement* GetFirstSegment() + { + return mSegments.getFirst(); + } - bool IsEmpty() - { - return !GetFirstSegment(); - } + bool IsEmpty() + { + return !GetFirstSegment(); + } private: - mozilla::LinkedList> mSegments; + mozilla::LinkedList> mSegments; }; // JSPurpleBuffer keeps references to GCThings which might affect the @@ -2302,49 +2302,49 @@ private: class JSPurpleBuffer { public: - JSPurpleBuffer(JSPurpleBuffer*& aReferenceToThis) - : mReferenceToThis(aReferenceToThis) - { - mReferenceToThis = this; - NS_ADDREF_THIS(); - mozilla::HoldJSObjects(this); - } + JSPurpleBuffer(JSPurpleBuffer*& aReferenceToThis) + : mReferenceToThis(aReferenceToThis) + { + mReferenceToThis = this; + NS_ADDREF_THIS(); + mozilla::HoldJSObjects(this); + } - ~JSPurpleBuffer() - { - MOZ_ASSERT(mValues.IsEmpty()); - MOZ_ASSERT(mObjects.IsEmpty()); - MOZ_ASSERT(mTenuredObjects.IsEmpty()); - } + ~JSPurpleBuffer() + { + MOZ_ASSERT(mValues.IsEmpty()); + MOZ_ASSERT(mObjects.IsEmpty()); + MOZ_ASSERT(mTenuredObjects.IsEmpty()); + } - void Destroy() - { - mReferenceToThis = nullptr; - mValues.Clear(); - mObjects.Clear(); - mTenuredObjects.Clear(); - mozilla::DropJSObjects(this); - NS_RELEASE_THIS(); - } + void Destroy() + { + mReferenceToThis = nullptr; + mValues.Clear(); + mObjects.Clear(); + mTenuredObjects.Clear(); + mozilla::DropJSObjects(this); + NS_RELEASE_THIS(); + } - NS_INLINE_DECL_CYCLE_COLLECTING_NATIVE_REFCOUNTING(JSPurpleBuffer) - NS_DECL_CYCLE_COLLECTION_SCRIPT_HOLDER_NATIVE_CLASS(JSPurpleBuffer) + NS_INLINE_DECL_CYCLE_COLLECTING_NATIVE_REFCOUNTING(JSPurpleBuffer) + NS_DECL_CYCLE_COLLECTION_SCRIPT_HOLDER_NATIVE_CLASS(JSPurpleBuffer) - JSPurpleBuffer*& mReferenceToThis; - SegmentedArray> mValues; - SegmentedArray> mObjects; - SegmentedArray> mTenuredObjects; + JSPurpleBuffer*& mReferenceToThis; + SegmentedArray> mValues; + SegmentedArray> mObjects; + SegmentedArray> mTenuredObjects; }; NS_IMPL_CYCLE_COLLECTION_CLASS(JSPurpleBuffer) NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(JSPurpleBuffer) - tmp->Destroy(); + tmp->Destroy(); NS_IMPL_CYCLE_COLLECTION_UNLINK_END NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(JSPurpleBuffer) - CycleCollectionNoteChild(cb, tmp, "self"); - NS_IMPL_CYCLE_COLLECTION_TRAVERSE_SCRIPT_OBJECTS + CycleCollectionNoteChild(cb, tmp, "self"); + NS_IMPL_CYCLE_COLLECTION_TRAVERSE_SCRIPT_OBJECTS NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END #define NS_TRACE_SEGMENTED_ARRAY(_field) \ @@ -2359,9 +2359,9 @@ NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END } NS_IMPL_CYCLE_COLLECTION_TRACE_BEGIN(JSPurpleBuffer) - NS_TRACE_SEGMENTED_ARRAY(mValues) - NS_TRACE_SEGMENTED_ARRAY(mObjects) - NS_TRACE_SEGMENTED_ARRAY(mTenuredObjects) + NS_TRACE_SEGMENTED_ARRAY(mValues) + NS_TRACE_SEGMENTED_ARRAY(mObjects) + NS_TRACE_SEGMENTED_ARRAY(mTenuredObjects) NS_IMPL_CYCLE_COLLECTION_TRACE_END NS_IMPL_CYCLE_COLLECTION_ROOT_NATIVE(JSPurpleBuffer, AddRef) @@ -2377,161 +2377,161 @@ struct SnowWhiteObject class SnowWhiteKiller : public TraceCallbacks { public: - SnowWhiteKiller(nsCycleCollector *aCollector, uint32_t aMaxCount) - : mCollector(aCollector) - { - MOZ_ASSERT(mCollector, "Calling SnowWhiteKiller after nsCC went away"); - while (true) { - if (mObjects.SetCapacity(aMaxCount)) { - break; - } - if (aMaxCount == 1) { - NS_RUNTIMEABORT("Not enough memory to even delete objects!"); - } - aMaxCount /= 2; - } + SnowWhiteKiller(nsCycleCollector *aCollector, uint32_t aMaxCount) + : mCollector(aCollector) + { + MOZ_ASSERT(mCollector, "Calling SnowWhiteKiller after nsCC went away"); + while (true) { + if (mObjects.SetCapacity(aMaxCount)) { + break; + } + if (aMaxCount == 1) { + NS_RUNTIMEABORT("Not enough memory to even delete objects!"); + } + aMaxCount /= 2; } + } - ~SnowWhiteKiller() - { - for (uint32_t i = 0; i < mObjects.Length(); ++i) { - SnowWhiteObject& o = mObjects[i]; - if (!o.mRefCnt->get() && !o.mRefCnt->IsInPurpleBuffer()) { - mCollector->RemoveObjectFromGraph(o.mPointer); - o.mRefCnt->stabilizeForDeletion(); - o.mParticipant->Trace(o.mPointer, *this, nullptr); - o.mParticipant->DeleteCycleCollectable(o.mPointer); - } - } + ~SnowWhiteKiller() + { + for (uint32_t i = 0; i < mObjects.Length(); ++i) { + SnowWhiteObject& o = mObjects[i]; + if (!o.mRefCnt->get() && !o.mRefCnt->IsInPurpleBuffer()) { + mCollector->RemoveObjectFromGraph(o.mPointer); + o.mRefCnt->stabilizeForDeletion(); + o.mParticipant->Trace(o.mPointer, *this, nullptr); + o.mParticipant->DeleteCycleCollectable(o.mPointer); + } } + } - void - Visit(nsPurpleBuffer& aBuffer, nsPurpleBufferEntry* aEntry) - { - MOZ_ASSERT(aEntry->mObject, "Null object in purple buffer"); - if (!aEntry->mRefCnt->get()) { - void *o = aEntry->mObject; - nsCycleCollectionParticipant *cp = aEntry->mParticipant; - CanonicalizeParticipant(&o, &cp); - SnowWhiteObject swo = { o, cp, aEntry->mRefCnt }; - if (mObjects.AppendElement(swo)) { - aBuffer.Remove(aEntry); - } - } + void + Visit(nsPurpleBuffer& aBuffer, nsPurpleBufferEntry* aEntry) + { + MOZ_ASSERT(aEntry->mObject, "Null object in purple buffer"); + if (!aEntry->mRefCnt->get()) { + void *o = aEntry->mObject; + nsCycleCollectionParticipant *cp = aEntry->mParticipant; + CanonicalizeParticipant(&o, &cp); + SnowWhiteObject swo = { o, cp, aEntry->mRefCnt }; + if (mObjects.AppendElement(swo)) { + aBuffer.Remove(aEntry); + } } + } - bool HasSnowWhiteObjects() const - { - return mObjects.Length() > 0; - } + bool HasSnowWhiteObjects() const + { + return mObjects.Length() > 0; + } - virtual void Trace(JS::Heap* aValue, const char* aName, - void* aClosure) const - { - if (aValue->isMarkable()) { - void* thing = aValue->toGCThing(); - if (thing && xpc_GCThingIsGrayCCThing(thing)) { - mCollector->GetJSPurpleBuffer()->mValues.AppendElement(*aValue); - } - } + virtual void Trace(JS::Heap* aValue, const char* aName, + void* aClosure) const + { + if (aValue->isMarkable()) { + void* thing = aValue->toGCThing(); + if (thing && xpc_GCThingIsGrayCCThing(thing)) { + mCollector->GetJSPurpleBuffer()->mValues.AppendElement(*aValue); + } } + } - virtual void Trace(JS::Heap* aId, const char* aName, - void* aClosure) const - { - } + virtual void Trace(JS::Heap* aId, const char* aName, + void* aClosure) const + { + } - virtual void Trace(JS::Heap* aObject, const char* aName, - void* aClosure) const - { - if (*aObject && xpc_GCThingIsGrayCCThing(*aObject)) { - mCollector->GetJSPurpleBuffer()->mObjects.AppendElement(*aObject); - } + virtual void Trace(JS::Heap* aObject, const char* aName, + void* aClosure) const + { + if (*aObject && xpc_GCThingIsGrayCCThing(*aObject)) { + mCollector->GetJSPurpleBuffer()->mObjects.AppendElement(*aObject); } + } - virtual void Trace(JS::TenuredHeap* aObject, const char* aName, - void* aClosure) const - { - if (*aObject && xpc_GCThingIsGrayCCThing(*aObject)) { - mCollector->GetJSPurpleBuffer()->mTenuredObjects.AppendElement(*aObject); - } + virtual void Trace(JS::TenuredHeap* aObject, const char* aName, + void* aClosure) const + { + if (*aObject && xpc_GCThingIsGrayCCThing(*aObject)) { + mCollector->GetJSPurpleBuffer()->mTenuredObjects.AppendElement(*aObject); } + } - virtual void Trace(JS::Heap* aString, const char* aName, - void* aClosure) const - { - } + virtual void Trace(JS::Heap* aString, const char* aName, + void* aClosure) const + { + } - virtual void Trace(JS::Heap* aScript, const char* aName, - void* aClosure) const - { - } + virtual void Trace(JS::Heap* aScript, const char* aName, + void* aClosure) const + { + } - virtual void Trace(JS::Heap* aFunction, const char* aName, - void* aClosure) const - { - } + virtual void Trace(JS::Heap* aFunction, const char* aName, + void* aClosure) const + { + } private: - nsCycleCollector *mCollector; - FallibleTArray mObjects; + nsCycleCollector *mCollector; + FallibleTArray mObjects; }; class RemoveSkippableVisitor : public SnowWhiteKiller { public: - RemoveSkippableVisitor(nsCycleCollector* aCollector, - uint32_t aMaxCount, bool aRemoveChildlessNodes, - bool aAsyncSnowWhiteFreeing, - CC_ForgetSkippableCallback aCb) - : SnowWhiteKiller(aCollector, aAsyncSnowWhiteFreeing ? 0 : aMaxCount), - mRemoveChildlessNodes(aRemoveChildlessNodes), - mAsyncSnowWhiteFreeing(aAsyncSnowWhiteFreeing), - mDispatchedDeferredDeletion(false), - mCallback(aCb) - {} + RemoveSkippableVisitor(nsCycleCollector* aCollector, + uint32_t aMaxCount, bool aRemoveChildlessNodes, + bool aAsyncSnowWhiteFreeing, + CC_ForgetSkippableCallback aCb) + : SnowWhiteKiller(aCollector, aAsyncSnowWhiteFreeing ? 0 : aMaxCount), + mRemoveChildlessNodes(aRemoveChildlessNodes), + mAsyncSnowWhiteFreeing(aAsyncSnowWhiteFreeing), + mDispatchedDeferredDeletion(false), + mCallback(aCb) + {} - ~RemoveSkippableVisitor() - { - // Note, we must call the callback before SnowWhiteKiller calls - // DeleteCycleCollectable! - if (mCallback) { - mCallback(); - } - if (HasSnowWhiteObjects()) { - // Effectively a continuation. - nsCycleCollector_dispatchDeferredDeletion(true); - } + ~RemoveSkippableVisitor() + { + // Note, we must call the callback before SnowWhiteKiller calls + // DeleteCycleCollectable! + if (mCallback) { + mCallback(); } + if (HasSnowWhiteObjects()) { + // Effectively a continuation. + nsCycleCollector_dispatchDeferredDeletion(true); + } + } - void - Visit(nsPurpleBuffer &aBuffer, nsPurpleBufferEntry *aEntry) - { - MOZ_ASSERT(aEntry->mObject, "null mObject in purple buffer"); - if (!aEntry->mRefCnt->get()) { - if (!mAsyncSnowWhiteFreeing) { - SnowWhiteKiller::Visit(aBuffer, aEntry); - } else if (!mDispatchedDeferredDeletion) { - mDispatchedDeferredDeletion = true; - nsCycleCollector_dispatchDeferredDeletion(false); - } - return; - } - void *o = aEntry->mObject; - nsCycleCollectionParticipant *cp = aEntry->mParticipant; - CanonicalizeParticipant(&o, &cp); - if (aEntry->mRefCnt->IsPurple() && !cp->CanSkip(o, false) && - (!mRemoveChildlessNodes || MayHaveChild(o, cp))) { - return; - } - aBuffer.Remove(aEntry); + void + Visit(nsPurpleBuffer &aBuffer, nsPurpleBufferEntry *aEntry) + { + MOZ_ASSERT(aEntry->mObject, "null mObject in purple buffer"); + if (!aEntry->mRefCnt->get()) { + if (!mAsyncSnowWhiteFreeing) { + SnowWhiteKiller::Visit(aBuffer, aEntry); + } else if (!mDispatchedDeferredDeletion) { + mDispatchedDeferredDeletion = true; + nsCycleCollector_dispatchDeferredDeletion(false); + } + return; } + void *o = aEntry->mObject; + nsCycleCollectionParticipant *cp = aEntry->mParticipant; + CanonicalizeParticipant(&o, &cp); + if (aEntry->mRefCnt->IsPurple() && !cp->CanSkip(o, false) && + (!mRemoveChildlessNodes || MayHaveChild(o, cp))) { + return; + } + aBuffer.Remove(aEntry); + } private: - bool mRemoveChildlessNodes; - bool mAsyncSnowWhiteFreeing; - bool mDispatchedDeferredDeletion; - CC_ForgetSkippableCallback mCallback; + bool mRemoveChildlessNodes; + bool mAsyncSnowWhiteFreeing; + bool mDispatchedDeferredDeletion; + CC_ForgetSkippableCallback mCallback; }; void @@ -2540,101 +2540,101 @@ nsPurpleBuffer::RemoveSkippable(nsCycleCollector* aCollector, bool aAsyncSnowWhiteFreeing, CC_ForgetSkippableCallback aCb) { - RemoveSkippableVisitor visitor(aCollector, Count(), aRemoveChildlessNodes, - aAsyncSnowWhiteFreeing, aCb); - VisitEntries(visitor); + RemoveSkippableVisitor visitor(aCollector, Count(), aRemoveChildlessNodes, + aAsyncSnowWhiteFreeing, aCb); + VisitEntries(visitor); } bool nsCycleCollector::FreeSnowWhite(bool aUntilNoSWInPurpleBuffer) { - CheckThreadSafety(); + CheckThreadSafety(); - if (mFreeingSnowWhite) { - return false; + if (mFreeingSnowWhite) { + return false; + } + + AutoRestore ar(mFreeingSnowWhite); + mFreeingSnowWhite = true; + + bool hadSnowWhiteObjects = false; + do { + SnowWhiteKiller visitor(this, mPurpleBuf.Count()); + mPurpleBuf.VisitEntries(visitor); + hadSnowWhiteObjects = hadSnowWhiteObjects || + visitor.HasSnowWhiteObjects(); + if (!visitor.HasSnowWhiteObjects()) { + break; } - - AutoRestore ar(mFreeingSnowWhite); - mFreeingSnowWhite = true; - - bool hadSnowWhiteObjects = false; - do { - SnowWhiteKiller visitor(this, mPurpleBuf.Count()); - mPurpleBuf.VisitEntries(visitor); - hadSnowWhiteObjects = hadSnowWhiteObjects || - visitor.HasSnowWhiteObjects(); - if (!visitor.HasSnowWhiteObjects()) { - break; - } - } while (aUntilNoSWInPurpleBuffer); - return hadSnowWhiteObjects; + } while (aUntilNoSWInPurpleBuffer); + return hadSnowWhiteObjects; } void nsCycleCollector::ForgetSkippable(bool aRemoveChildlessNodes, bool aAsyncSnowWhiteFreeing) { - CheckThreadSafety(); + CheckThreadSafety(); - // If we remove things from the purple buffer during graph building, we may - // lose track of an object that was mutated during graph building. - MOZ_ASSERT(mIncrementalPhase == IdlePhase); + // If we remove things from the purple buffer during graph building, we may + // lose track of an object that was mutated during graph building. + MOZ_ASSERT(mIncrementalPhase == IdlePhase); - if (mJSRuntime) { - mJSRuntime->PrepareForForgetSkippable(); - } - MOZ_ASSERT(!mScanInProgress, "Don't forget skippable or free snow-white while scan is in progress."); - mPurpleBuf.RemoveSkippable(this, aRemoveChildlessNodes, - aAsyncSnowWhiteFreeing, mForgetSkippableCB); + if (mJSRuntime) { + mJSRuntime->PrepareForForgetSkippable(); + } + MOZ_ASSERT(!mScanInProgress, "Don't forget skippable or free snow-white while scan is in progress."); + mPurpleBuf.RemoveSkippable(this, aRemoveChildlessNodes, + aAsyncSnowWhiteFreeing, mForgetSkippableCB); } MOZ_NEVER_INLINE void nsCycleCollector::MarkRoots(SliceBudget &aBudget) { - const intptr_t kNumNodesBetweenTimeChecks = 1000; - const intptr_t kStep = SliceBudget::CounterReset / kNumNodesBetweenTimeChecks; + const intptr_t kNumNodesBetweenTimeChecks = 1000; + const intptr_t kStep = SliceBudget::CounterReset / kNumNodesBetweenTimeChecks; - TimeLog timeLog; - AutoRestore ar(mScanInProgress); - MOZ_ASSERT(!mScanInProgress); - mScanInProgress = true; - MOZ_ASSERT(mIncrementalPhase == GraphBuildingPhase); - MOZ_ASSERT(mCurrNode); + TimeLog timeLog; + AutoRestore ar(mScanInProgress); + MOZ_ASSERT(!mScanInProgress); + mScanInProgress = true; + MOZ_ASSERT(mIncrementalPhase == GraphBuildingPhase); + MOZ_ASSERT(mCurrNode); - while (!aBudget.isOverBudget() && !mCurrNode->IsDone()) { - PtrInfo *pi = mCurrNode->GetNext(); - if (!pi) { - MOZ_CRASH(); - } - - // We need to call the builder's Traverse() method on deleted nodes, to - // set their firstChild() that may be read by a prior non-deleted - // neighbor. - mBuilder->Traverse(pi); - if (mCurrNode->AtBlockEnd()) { - mBuilder->SetLastChild(); - } - aBudget.step(kStep); + while (!aBudget.isOverBudget() && !mCurrNode->IsDone()) { + PtrInfo *pi = mCurrNode->GetNext(); + if (!pi) { + MOZ_CRASH(); } - if (!mCurrNode->IsDone()) { - timeLog.Checkpoint("MarkRoots()"); - return; + // We need to call the builder's Traverse() method on deleted nodes, to + // set their firstChild() that may be read by a prior non-deleted + // neighbor. + mBuilder->Traverse(pi); + if (mCurrNode->AtBlockEnd()) { + mBuilder->SetLastChild(); } + aBudget.step(kStep); + } - if (mGraph.mRootCount > 0) { - mBuilder->SetLastChild(); - } - - if (mBuilder->RanOutOfMemory()) { - MOZ_ASSERT(false, "Ran out of memory while building cycle collector graph"); - CC_TELEMETRY(_OOM, true); - } - - mBuilder = nullptr; - mCurrNode = nullptr; - mIncrementalPhase = ScanAndCollectWhitePhase; + if (!mCurrNode->IsDone()) { timeLog.Checkpoint("MarkRoots()"); + return; + } + + if (mGraph.mRootCount > 0) { + mBuilder->SetLastChild(); + } + + if (mBuilder->RanOutOfMemory()) { + MOZ_ASSERT(false, "Ran out of memory while building cycle collector graph"); + CC_TELEMETRY(_OOM, true); + } + + mBuilder = nullptr; + mCurrNode = nullptr; + mIncrementalPhase = ScanAndCollectWhitePhase; + timeLog.Checkpoint("MarkRoots()"); } @@ -2645,78 +2645,78 @@ nsCycleCollector::MarkRoots(SliceBudget &aBudget) struct ScanBlackVisitor { - ScanBlackVisitor(uint32_t &aWhiteNodeCount, bool &aFailed) - : mWhiteNodeCount(aWhiteNodeCount), mFailed(aFailed) - { - } + ScanBlackVisitor(uint32_t &aWhiteNodeCount, bool &aFailed) + : mWhiteNodeCount(aWhiteNodeCount), mFailed(aFailed) + { + } - bool ShouldVisitNode(PtrInfo const *pi) - { - return pi->mColor != black; - } + bool ShouldVisitNode(PtrInfo const *pi) + { + return pi->mColor != black; + } - MOZ_NEVER_INLINE void VisitNode(PtrInfo *pi) - { - if (pi->mColor == white) - --mWhiteNodeCount; - pi->mColor = black; - } + MOZ_NEVER_INLINE void VisitNode(PtrInfo *pi) + { + if (pi->mColor == white) + --mWhiteNodeCount; + pi->mColor = black; + } - void Failed() - { - mFailed = true; - } + void Failed() + { + mFailed = true; + } private: - uint32_t &mWhiteNodeCount; - bool &mFailed; + uint32_t &mWhiteNodeCount; + bool &mFailed; }; struct scanVisitor { - scanVisitor(uint32_t &aWhiteNodeCount, bool &aFailed, bool aWasIncremental) - : mWhiteNodeCount(aWhiteNodeCount), mFailed(aFailed), - mWasIncremental(aWasIncremental) - { + scanVisitor(uint32_t &aWhiteNodeCount, bool &aFailed, bool aWasIncremental) + : mWhiteNodeCount(aWhiteNodeCount), mFailed(aFailed), + mWasIncremental(aWasIncremental) + { + } + + bool ShouldVisitNode(PtrInfo const *pi) + { + return pi->mColor == grey; + } + + MOZ_NEVER_INLINE void VisitNode(PtrInfo *pi) + { + if (pi->mInternalRefs > pi->mRefCount && pi->mRefCount > 0) { + // If we found more references to an object than its ref count, then + // the object should have already been marked as an incremental + // root. Note that this is imprecise, because pi could have been + // marked black for other reasons. Always fault if we weren't + // incremental, as there were no incremental roots in that case. + if (!mWasIncremental || pi->mColor != black) { + Fault("traversed refs exceed refcount", pi); + } } - bool ShouldVisitNode(PtrInfo const *pi) - { - return pi->mColor == grey; + if (pi->mInternalRefs == pi->mRefCount || pi->mRefCount == 0) { + pi->mColor = white; + ++mWhiteNodeCount; + } else { + GraphWalker(ScanBlackVisitor(mWhiteNodeCount, mFailed)).Walk(pi); + MOZ_ASSERT(pi->mColor == black, + "Why didn't ScanBlackVisitor make pi black?"); } + } - MOZ_NEVER_INLINE void VisitNode(PtrInfo *pi) - { - if (pi->mInternalRefs > pi->mRefCount && pi->mRefCount > 0) { - // If we found more references to an object than its ref count, then - // the object should have already been marked as an incremental - // root. Note that this is imprecise, because pi could have been - // marked black for other reasons. Always fault if we weren't - // incremental, as there were no incremental roots in that case. - if (!mWasIncremental || pi->mColor != black) { - Fault("traversed refs exceed refcount", pi); - } - } - - if (pi->mInternalRefs == pi->mRefCount || pi->mRefCount == 0) { - pi->mColor = white; - ++mWhiteNodeCount; - } else { - GraphWalker(ScanBlackVisitor(mWhiteNodeCount, mFailed)).Walk(pi); - MOZ_ASSERT(pi->mColor == black, - "Why didn't ScanBlackVisitor make pi black?"); - } - } - - void Failed() { - mFailed = true; - } + void Failed() { + mFailed = true; + } private: - uint32_t &mWhiteNodeCount; - bool &mFailed; - bool mWasIncremental; + uint32_t &mWhiteNodeCount; + bool &mFailed; + bool mWasIncremental; }; // Iterate over the WeakMaps. If we mark anything while iterating @@ -2724,87 +2724,87 @@ private: void nsCycleCollector::ScanWeakMaps() { - bool anyChanged; - bool failed = false; - do { - anyChanged = false; - for (uint32_t i = 0; i < mGraph.mWeakMaps.Length(); i++) { - WeakMapping *wm = &mGraph.mWeakMaps[i]; + bool anyChanged; + bool failed = false; + do { + anyChanged = false; + for (uint32_t i = 0; i < mGraph.mWeakMaps.Length(); i++) { + WeakMapping *wm = &mGraph.mWeakMaps[i]; - // If any of these are null, the original object was marked black. - uint32_t mColor = wm->mMap ? wm->mMap->mColor : black; - uint32_t kColor = wm->mKey ? wm->mKey->mColor : black; - uint32_t kdColor = wm->mKeyDelegate ? wm->mKeyDelegate->mColor : black; - uint32_t vColor = wm->mVal ? wm->mVal->mColor : black; + // If any of these are null, the original object was marked black. + uint32_t mColor = wm->mMap ? wm->mMap->mColor : black; + uint32_t kColor = wm->mKey ? wm->mKey->mColor : black; + uint32_t kdColor = wm->mKeyDelegate ? wm->mKeyDelegate->mColor : black; + uint32_t vColor = wm->mVal ? wm->mVal->mColor : black; - // All non-null weak mapping maps, keys and values are - // roots (in the sense of WalkFromRoots) in the cycle - // collector graph, and thus should have been colored - // either black or white in ScanRoots(). - MOZ_ASSERT(mColor != grey, "Uncolored weak map"); - MOZ_ASSERT(kColor != grey, "Uncolored weak map key"); - MOZ_ASSERT(kdColor != grey, "Uncolored weak map key delegate"); - MOZ_ASSERT(vColor != grey, "Uncolored weak map value"); + // All non-null weak mapping maps, keys and values are + // roots (in the sense of WalkFromRoots) in the cycle + // collector graph, and thus should have been colored + // either black or white in ScanRoots(). + MOZ_ASSERT(mColor != grey, "Uncolored weak map"); + MOZ_ASSERT(kColor != grey, "Uncolored weak map key"); + MOZ_ASSERT(kdColor != grey, "Uncolored weak map key delegate"); + MOZ_ASSERT(vColor != grey, "Uncolored weak map value"); - if (mColor == black && kColor != black && kdColor == black) { - GraphWalker(ScanBlackVisitor(mWhiteNodeCount, failed)).Walk(wm->mKey); - anyChanged = true; - } + if (mColor == black && kColor != black && kdColor == black) { + GraphWalker(ScanBlackVisitor(mWhiteNodeCount, failed)).Walk(wm->mKey); + anyChanged = true; + } - if (mColor == black && kColor == black && vColor != black) { - GraphWalker(ScanBlackVisitor(mWhiteNodeCount, failed)).Walk(wm->mVal); - anyChanged = true; - } - } - } while (anyChanged); - - if (failed) { - MOZ_ASSERT(false, "Ran out of memory in ScanWeakMaps"); - CC_TELEMETRY(_OOM, true); + if (mColor == black && kColor == black && vColor != black) { + GraphWalker(ScanBlackVisitor(mWhiteNodeCount, failed)).Walk(wm->mVal); + anyChanged = true; + } } + } while (anyChanged); + + if (failed) { + MOZ_ASSERT(false, "Ran out of memory in ScanWeakMaps"); + CC_TELEMETRY(_OOM, true); + } } // Flood black from any objects in the purple buffer that are in the CC graph. class PurpleScanBlackVisitor { public: - PurpleScanBlackVisitor(GCGraph &aGraph, nsICycleCollectorListener *aListener, - uint32_t &aCount, bool &aFailed) - : mGraph(aGraph), mListener(aListener), mCount(aCount), mFailed(aFailed) - { + PurpleScanBlackVisitor(GCGraph &aGraph, nsICycleCollectorListener *aListener, + uint32_t &aCount, bool &aFailed) + : mGraph(aGraph), mListener(aListener), mCount(aCount), mFailed(aFailed) + { + } + + void + Visit(nsPurpleBuffer &aBuffer, nsPurpleBufferEntry *aEntry) + { + MOZ_ASSERT(aEntry->mObject, "Entries with null mObject shouldn't be in the purple buffer."); + MOZ_ASSERT(aEntry->mRefCnt->get() != 0, "Snow-white objects shouldn't be in the purple buffer."); + + void *obj = aEntry->mObject; + if (!aEntry->mParticipant) { + obj = CanonicalizeXPCOMParticipant(static_cast(obj)); + MOZ_ASSERT(obj, "Don't add objects that don't participate in collection!"); } - void - Visit(nsPurpleBuffer &aBuffer, nsPurpleBufferEntry *aEntry) - { - MOZ_ASSERT(aEntry->mObject, "Entries with null mObject shouldn't be in the purple buffer."); - MOZ_ASSERT(aEntry->mRefCnt->get() != 0, "Snow-white objects shouldn't be in the purple buffer."); - - void *obj = aEntry->mObject; - if (!aEntry->mParticipant) { - obj = CanonicalizeXPCOMParticipant(static_cast(obj)); - MOZ_ASSERT(obj, "Don't add objects that don't participate in collection!"); - } - - PtrInfo *pi = mGraph.FindNode(obj); - if (!pi) { - return; - } - MOZ_ASSERT(pi->mParticipant, "No dead objects should be in the purple buffer."); - if (MOZ_UNLIKELY(mListener)) { - mListener->NoteIncrementalRoot((uint64_t)pi->mPointer); - } - if (pi->mColor == black) { - return; - } - GraphWalker(ScanBlackVisitor(mCount, mFailed)).Walk(pi); + PtrInfo *pi = mGraph.FindNode(obj); + if (!pi) { + return; } + MOZ_ASSERT(pi->mParticipant, "No dead objects should be in the purple buffer."); + if (MOZ_UNLIKELY(mListener)) { + mListener->NoteIncrementalRoot((uint64_t)pi->mPointer); + } + if (pi->mColor == black) { + return; + } + GraphWalker(ScanBlackVisitor(mCount, mFailed)).Walk(pi); + } private: - GCGraph &mGraph; - nsICycleCollectorListener *mListener; - uint32_t &mCount; - bool &mFailed; + GCGraph &mGraph; + nsICycleCollectorListener *mListener; + uint32_t &mCount; + bool &mFailed; }; // Objects that have been stored somewhere since the start of incremental graph building must @@ -2813,146 +2813,146 @@ private: void nsCycleCollector::ScanIncrementalRoots() { - TimeLog timeLog; + TimeLog timeLog; - // Reference counted objects: - // We cleared the purple buffer at the start of the current ICC, so if a - // refcounted object is purple, it may have been AddRef'd during the current - // ICC. (It may also have only been released.) If that is the case, we cannot - // be sure that the set of things pointing to the object in the CC graph - // is accurate. Therefore, for safety, we treat any purple objects as being - // live during the current CC. We don't remove anything from the purple - // buffer here, so these objects will be suspected and freed in the next CC - // if they are garbage. - bool failed = false; - PurpleScanBlackVisitor purpleScanBlackVisitor(mGraph, mListener, mWhiteNodeCount, failed); - mPurpleBuf.VisitEntries(purpleScanBlackVisitor); - timeLog.Checkpoint("ScanIncrementalRoots::fix purple"); + // Reference counted objects: + // We cleared the purple buffer at the start of the current ICC, so if a + // refcounted object is purple, it may have been AddRef'd during the current + // ICC. (It may also have only been released.) If that is the case, we cannot + // be sure that the set of things pointing to the object in the CC graph + // is accurate. Therefore, for safety, we treat any purple objects as being + // live during the current CC. We don't remove anything from the purple + // buffer here, so these objects will be suspected and freed in the next CC + // if they are garbage. + bool failed = false; + PurpleScanBlackVisitor purpleScanBlackVisitor(mGraph, mListener, mWhiteNodeCount, failed); + mPurpleBuf.VisitEntries(purpleScanBlackVisitor); + timeLog.Checkpoint("ScanIncrementalRoots::fix purple"); - // Garbage collected objects: - // If a GCed object was added to the graph with a refcount of zero, and is - // now marked black by the GC, it was probably gray before and was exposed - // to active JS, so it may have been stored somewhere, so it needs to be - // treated as live. - if (mJSRuntime) { - nsCycleCollectionParticipant *jsParticipant = mJSRuntime->GCThingParticipant(); - nsCycleCollectionParticipant *zoneParticipant = mJSRuntime->ZoneParticipant(); - NodePool::Enumerator etor(mGraph.mNodes); + // Garbage collected objects: + // If a GCed object was added to the graph with a refcount of zero, and is + // now marked black by the GC, it was probably gray before and was exposed + // to active JS, so it may have been stored somewhere, so it needs to be + // treated as live. + if (mJSRuntime) { + nsCycleCollectionParticipant *jsParticipant = mJSRuntime->GCThingParticipant(); + nsCycleCollectionParticipant *zoneParticipant = mJSRuntime->ZoneParticipant(); + NodePool::Enumerator etor(mGraph.mNodes); - while (!etor.IsDone()) { - PtrInfo *pi = etor.GetNext(); + while (!etor.IsDone()) { + PtrInfo *pi = etor.GetNext(); - // If the refcount is non-zero, pi can't have been a gray JS object. - if (pi->mRefCount != 0) { - continue; - } + // If the refcount is non-zero, pi can't have been a gray JS object. + if (pi->mRefCount != 0) { + continue; + } - // As an optimization, if an object has already been determined to be live, - // don't consider it further. We can't do this if there is a listener, - // because the listener wants to know the complete set of incremental roots. - if (pi->mColor == black && MOZ_LIKELY(!mListener)) { - continue; - } + // As an optimization, if an object has already been determined to be live, + // don't consider it further. We can't do this if there is a listener, + // because the listener wants to know the complete set of incremental roots. + if (pi->mColor == black && MOZ_LIKELY(!mListener)) { + continue; + } - // If the object is still marked gray by the GC, nothing could have gotten - // hold of it, so it isn't an incremental root. - if (pi->mParticipant == jsParticipant) { - if (xpc_GCThingIsGrayCCThing(pi->mPointer)) { - continue; - } - } else if (pi->mParticipant == zoneParticipant) { - JS::Zone *zone = static_cast(pi->mPointer); - if (js::ZoneGlobalsAreAllGray(zone)) { - continue; - } - } else { - MOZ_ASSERT(false, "Non-JS thing with 0 refcount? Treating as live."); - } - - // At this point, pi must be an incremental root. - - // If there's a listener, tell it about this root. We don't bother with the - // optimization of skipping the Walk() if pi is black: it will just return - // without doing anything and there's no need to make this case faster. - if (MOZ_UNLIKELY(mListener)) { - mListener->NoteIncrementalRoot((uint64_t)pi->mPointer); - } - - GraphWalker(ScanBlackVisitor(mWhiteNodeCount, failed)).Walk(pi); + // If the object is still marked gray by the GC, nothing could have gotten + // hold of it, so it isn't an incremental root. + if (pi->mParticipant == jsParticipant) { + if (xpc_GCThingIsGrayCCThing(pi->mPointer)) { + continue; } + } else if (pi->mParticipant == zoneParticipant) { + JS::Zone *zone = static_cast(pi->mPointer); + if (js::ZoneGlobalsAreAllGray(zone)) { + continue; + } + } else { + MOZ_ASSERT(false, "Non-JS thing with 0 refcount? Treating as live."); + } - timeLog.Checkpoint("ScanIncrementalRoots::fix JS"); + // At this point, pi must be an incremental root. + + // If there's a listener, tell it about this root. We don't bother with the + // optimization of skipping the Walk() if pi is black: it will just return + // without doing anything and there's no need to make this case faster. + if (MOZ_UNLIKELY(mListener)) { + mListener->NoteIncrementalRoot((uint64_t)pi->mPointer); + } + + GraphWalker(ScanBlackVisitor(mWhiteNodeCount, failed)).Walk(pi); } - if (failed) { - NS_ASSERTION(false, "Ran out of memory in ScanIncrementalRoots"); - CC_TELEMETRY(_OOM, true); - } + timeLog.Checkpoint("ScanIncrementalRoots::fix JS"); + } + + if (failed) { + NS_ASSERTION(false, "Ran out of memory in ScanIncrementalRoots"); + CC_TELEMETRY(_OOM, true); + } } void nsCycleCollector::ScanRoots(bool aFullySynchGraphBuild) { - AutoRestore ar(mScanInProgress); - MOZ_ASSERT(!mScanInProgress); - mScanInProgress = true; - mWhiteNodeCount = 0; - MOZ_ASSERT(mIncrementalPhase == ScanAndCollectWhitePhase); + AutoRestore ar(mScanInProgress); + MOZ_ASSERT(!mScanInProgress); + mScanInProgress = true; + mWhiteNodeCount = 0; + MOZ_ASSERT(mIncrementalPhase == ScanAndCollectWhitePhase); - if (!aFullySynchGraphBuild) { - ScanIncrementalRoots(); + if (!aFullySynchGraphBuild) { + ScanIncrementalRoots(); + } + + TimeLog timeLog; + + // On the assumption that most nodes will be black, it's + // probably faster to use a GraphWalker than a + // NodePool::Enumerator. + bool failed = false; + scanVisitor sv(mWhiteNodeCount, failed, !aFullySynchGraphBuild); + GraphWalker(sv).WalkFromRoots(mGraph); + timeLog.Checkpoint("ScanRoots::WalkFromRoots"); + + if (failed) { + NS_ASSERTION(false, "Ran out of memory in ScanRoots"); + CC_TELEMETRY(_OOM, true); + } + + // Scanning weak maps must be done last. + ScanWeakMaps(); + timeLog.Checkpoint("ScanRoots::ScanWeakMaps"); + + if (mListener) { + mListener->BeginResults(); + + NodePool::Enumerator etor(mGraph.mNodes); + while (!etor.IsDone()) { + PtrInfo *pi = etor.GetNext(); + if (!pi->mParticipant) { + continue; + } + switch (pi->mColor) { + case black: + if (pi->mRefCount > 0 && pi->mRefCount < UINT32_MAX && + pi->mInternalRefs != pi->mRefCount) { + mListener->DescribeRoot((uint64_t)pi->mPointer, + pi->mInternalRefs); + } + break; + case white: + mListener->DescribeGarbage((uint64_t)pi->mPointer); + break; + case grey: + // With incremental CC, we can end up with a grey object after + // scanning if it is only reachable from an object that gets freed. + break; + } } - TimeLog timeLog; - - // On the assumption that most nodes will be black, it's - // probably faster to use a GraphWalker than a - // NodePool::Enumerator. - bool failed = false; - scanVisitor sv(mWhiteNodeCount, failed, !aFullySynchGraphBuild); - GraphWalker(sv).WalkFromRoots(mGraph); - timeLog.Checkpoint("ScanRoots::WalkFromRoots"); - - if (failed) { - NS_ASSERTION(false, "Ran out of memory in ScanRoots"); - CC_TELEMETRY(_OOM, true); - } - - // Scanning weak maps must be done last. - ScanWeakMaps(); - timeLog.Checkpoint("ScanRoots::ScanWeakMaps"); - - if (mListener) { - mListener->BeginResults(); - - NodePool::Enumerator etor(mGraph.mNodes); - while (!etor.IsDone()) { - PtrInfo *pi = etor.GetNext(); - if (!pi->mParticipant) { - continue; - } - switch (pi->mColor) { - case black: - if (pi->mRefCount > 0 && pi->mRefCount < UINT32_MAX && - pi->mInternalRefs != pi->mRefCount) { - mListener->DescribeRoot((uint64_t)pi->mPointer, - pi->mInternalRefs); - } - break; - case white: - mListener->DescribeGarbage((uint64_t)pi->mPointer); - break; - case grey: - // With incremental CC, we can end up with a grey object after - // scanning if it is only reachable from an object that gets freed. - break; - } - } - - mListener->End(); - mListener = nullptr; - timeLog.Checkpoint("ScanRoots::listener"); - } + mListener->End(); + mListener = nullptr; + timeLog.Checkpoint("ScanRoots::listener"); + } } @@ -2963,78 +2963,78 @@ nsCycleCollector::ScanRoots(bool aFullySynchGraphBuild) bool nsCycleCollector::CollectWhite() { - // Explanation of "somewhat modified": we have no way to collect the - // set of whites "all at once", we have to ask each of them to drop - // their outgoing links and assume this will cause the garbage cycle - // to *mostly* self-destruct (except for the reference we continue - // to hold). - // - // To do this "safely" we must make sure that the white nodes we're - // operating on are stable for the duration of our operation. So we - // make 3 sets of calls to language runtimes: - // - // - Root(whites), which should pin the whites in memory. - // - Unlink(whites), which drops outgoing links on each white. - // - Unroot(whites), which returns the whites to normal GC. + // Explanation of "somewhat modified": we have no way to collect the + // set of whites "all at once", we have to ask each of them to drop + // their outgoing links and assume this will cause the garbage cycle + // to *mostly* self-destruct (except for the reference we continue + // to hold). + // + // To do this "safely" we must make sure that the white nodes we're + // operating on are stable for the duration of our operation. So we + // make 3 sets of calls to language runtimes: + // + // - Root(whites), which should pin the whites in memory. + // - Unlink(whites), which drops outgoing links on each white. + // - Unroot(whites), which returns the whites to normal GC. - TimeLog timeLog; - nsAutoTArray whiteNodes; + TimeLog timeLog; + nsAutoTArray whiteNodes; - MOZ_ASSERT(mIncrementalPhase == ScanAndCollectWhitePhase); + MOZ_ASSERT(mIncrementalPhase == ScanAndCollectWhitePhase); - whiteNodes.SetCapacity(mWhiteNodeCount); - uint32_t numWhiteGCed = 0; + whiteNodes.SetCapacity(mWhiteNodeCount); + uint32_t numWhiteGCed = 0; - NodePool::Enumerator etor(mGraph.mNodes); - while (!etor.IsDone()) - { - PtrInfo *pinfo = etor.GetNext(); - if (pinfo->mColor == white && pinfo->mParticipant) { - whiteNodes.AppendElement(pinfo); - pinfo->mParticipant->Root(pinfo->mPointer); - if (pinfo->mRefCount == 0) { - // only JS objects have a refcount of 0 - ++numWhiteGCed; - } - } + NodePool::Enumerator etor(mGraph.mNodes); + while (!etor.IsDone()) + { + PtrInfo *pinfo = etor.GetNext(); + if (pinfo->mColor == white && pinfo->mParticipant) { + whiteNodes.AppendElement(pinfo); + pinfo->mParticipant->Root(pinfo->mPointer); + if (pinfo->mRefCount == 0) { + // only JS objects have a refcount of 0 + ++numWhiteGCed; + } } + } - uint32_t count = whiteNodes.Length(); - MOZ_ASSERT(numWhiteGCed <= count, - "More freed GCed nodes than total freed nodes."); - mResults.mFreedRefCounted += count - numWhiteGCed; - mResults.mFreedGCed += numWhiteGCed; + uint32_t count = whiteNodes.Length(); + MOZ_ASSERT(numWhiteGCed <= count, + "More freed GCed nodes than total freed nodes."); + mResults.mFreedRefCounted += count - numWhiteGCed; + mResults.mFreedGCed += numWhiteGCed; - timeLog.Checkpoint("CollectWhite::Root"); + timeLog.Checkpoint("CollectWhite::Root"); - if (mBeforeUnlinkCB) { - mBeforeUnlinkCB(); - timeLog.Checkpoint("CollectWhite::BeforeUnlinkCB"); - } + if (mBeforeUnlinkCB) { + mBeforeUnlinkCB(); + timeLog.Checkpoint("CollectWhite::BeforeUnlinkCB"); + } - for (uint32_t i = 0; i < count; ++i) { - PtrInfo *pinfo = whiteNodes.ElementAt(i); - MOZ_ASSERT(pinfo->mParticipant, "Unlink shouldn't see objects removed from graph."); - pinfo->mParticipant->Unlink(pinfo->mPointer); + for (uint32_t i = 0; i < count; ++i) { + PtrInfo *pinfo = whiteNodes.ElementAt(i); + MOZ_ASSERT(pinfo->mParticipant, "Unlink shouldn't see objects removed from graph."); + pinfo->mParticipant->Unlink(pinfo->mPointer); #ifdef DEBUG - if (mJSRuntime) { - mJSRuntime->AssertNoObjectsToTrace(pinfo->mPointer); - } + if (mJSRuntime) { + mJSRuntime->AssertNoObjectsToTrace(pinfo->mPointer); + } #endif - } - timeLog.Checkpoint("CollectWhite::Unlink"); + } + timeLog.Checkpoint("CollectWhite::Unlink"); - for (uint32_t i = 0; i < count; ++i) { - PtrInfo *pinfo = whiteNodes.ElementAt(i); - MOZ_ASSERT(pinfo->mParticipant, "Unroot shouldn't see objects removed from graph."); - pinfo->mParticipant->Unroot(pinfo->mPointer); - } - timeLog.Checkpoint("CollectWhite::Unroot"); + for (uint32_t i = 0; i < count; ++i) { + PtrInfo *pinfo = whiteNodes.ElementAt(i); + MOZ_ASSERT(pinfo->mParticipant, "Unroot shouldn't see objects removed from graph."); + pinfo->mParticipant->Unroot(pinfo->mPointer); + } + timeLog.Checkpoint("CollectWhite::Unroot"); - nsCycleCollector_dispatchDeferredDeletion(false); - mIncrementalPhase = CleanupPhase; + nsCycleCollector_dispatchDeferredDeletion(false); + mIncrementalPhase = CleanupPhase; - return count > 0; + return count > 0; } @@ -3048,13 +3048,13 @@ NS_IMETHODIMP nsCycleCollector::CollectReports(nsIHandleReportCallback* aHandleReport, nsISupports* aData) { - size_t objectSize, graphNodesSize, graphEdgesSize, weakMapsSize, - purpleBufferSize; - SizeOfIncludingThis(CycleCollectorMallocSizeOf, - &objectSize, - &graphNodesSize, &graphEdgesSize, - &weakMapsSize, - &purpleBufferSize); + size_t objectSize, graphNodesSize, graphEdgesSize, weakMapsSize, + purpleBufferSize; + SizeOfIncludingThis(CycleCollectorMallocSizeOf, + &objectSize, + &graphNodesSize, &graphEdgesSize, + &weakMapsSize, + &purpleBufferSize); #define REPORT(_path, _amount, _desc) \ do { \ @@ -3071,28 +3071,28 @@ nsCycleCollector::CollectReports(nsIHandleReportCallback* aHandleReport, } \ } while (0) - REPORT("explicit/cycle-collector/collector-object", objectSize, - "Memory used for the cycle collector object itself."); + REPORT("explicit/cycle-collector/collector-object", objectSize, + "Memory used for the cycle collector object itself."); - REPORT("explicit/cycle-collector/graph-nodes", graphNodesSize, - "Memory used for the nodes of the cycle collector's graph. " - "This should be zero when the collector is idle."); + REPORT("explicit/cycle-collector/graph-nodes", graphNodesSize, + "Memory used for the nodes of the cycle collector's graph. " + "This should be zero when the collector is idle."); - REPORT("explicit/cycle-collector/graph-edges", graphEdgesSize, - "Memory used for the edges of the cycle collector's graph. " - "This should be zero when the collector is idle."); + REPORT("explicit/cycle-collector/graph-edges", graphEdgesSize, + "Memory used for the edges of the cycle collector's graph. " + "This should be zero when the collector is idle."); - REPORT("explicit/cycle-collector/weak-maps", weakMapsSize, - "Memory used for the representation of weak maps in the " - "cycle collector's graph. " - "This should be zero when the collector is idle."); + REPORT("explicit/cycle-collector/weak-maps", weakMapsSize, + "Memory used for the representation of weak maps in the " + "cycle collector's graph. " + "This should be zero when the collector is idle."); - REPORT("explicit/cycle-collector/purple-buffer", purpleBufferSize, - "Memory used for the cycle collector's purple buffer."); + REPORT("explicit/cycle-collector/purple-buffer", purpleBufferSize, + "Memory used for the cycle collector's purple buffer."); #undef REPORT - return NS_OK; + return NS_OK; }; @@ -3101,64 +3101,64 @@ nsCycleCollector::CollectReports(nsIHandleReportCallback* aHandleReport, //////////////////////////////////////////////////////////////////////// nsCycleCollector::nsCycleCollector() : - mActivelyCollecting(false), - mFreeingSnowWhite(false), - mScanInProgress(false), - mJSRuntime(nullptr), - mIncrementalPhase(IdlePhase), - mThread(NS_GetCurrentThread()), - mWhiteNodeCount(0), - mBeforeUnlinkCB(nullptr), - mForgetSkippableCB(nullptr), - mUnmergedNeeded(0), - mMergedInARow(0), - mJSPurpleBuffer(nullptr) + mActivelyCollecting(false), + mFreeingSnowWhite(false), + mScanInProgress(false), + mJSRuntime(nullptr), + mIncrementalPhase(IdlePhase), + mThread(NS_GetCurrentThread()), + mWhiteNodeCount(0), + mBeforeUnlinkCB(nullptr), + mForgetSkippableCB(nullptr), + mUnmergedNeeded(0), + mMergedInARow(0), + mJSPurpleBuffer(nullptr) { } nsCycleCollector::~nsCycleCollector() { - UnregisterWeakMemoryReporter(this); + UnregisterWeakMemoryReporter(this); } void nsCycleCollector::RegisterJSRuntime(CycleCollectedJSRuntime *aJSRuntime) { - if (mJSRuntime) - Fault("multiple registrations of cycle collector JS runtime", aJSRuntime); + if (mJSRuntime) + Fault("multiple registrations of cycle collector JS runtime", aJSRuntime); - mJSRuntime = aJSRuntime; + mJSRuntime = aJSRuntime; - // We can't register as a reporter in nsCycleCollector() because that runs - // before the memory reporter manager is initialized. So we do it here - // instead. - static bool registered = false; - if (!registered) { - RegisterWeakMemoryReporter(this); - registered = true; - } + // We can't register as a reporter in nsCycleCollector() because that runs + // before the memory reporter manager is initialized. So we do it here + // instead. + static bool registered = false; + if (!registered) { + RegisterWeakMemoryReporter(this); + registered = true; + } } void nsCycleCollector::ForgetJSRuntime() { - if (!mJSRuntime) - Fault("forgetting non-registered cycle collector JS runtime"); + if (!mJSRuntime) + Fault("forgetting non-registered cycle collector JS runtime"); - mJSRuntime = nullptr; + mJSRuntime = nullptr; } #ifdef DEBUG static bool HasParticipant(void *aPtr, nsCycleCollectionParticipant *aParti) { - if (aParti) { - return true; - } + if (aParti) { + return true; + } - nsXPCOMCycleCollectionParticipant *xcp; - ToParticipant(static_cast(aPtr), &xcp); - return xcp != nullptr; + nsXPCOMCycleCollectionParticipant *xcp; + ToParticipant(static_cast(aPtr), &xcp); + return xcp != nullptr; } #endif @@ -3166,32 +3166,32 @@ MOZ_ALWAYS_INLINE void nsCycleCollector::Suspect(void *aPtr, nsCycleCollectionParticipant *aParti, nsCycleCollectingAutoRefCnt *aRefCnt) { - CheckThreadSafety(); + CheckThreadSafety(); - // Re-entering ::Suspect during collection used to be a fault, but - // we are canonicalizing nsISupports pointers using QI, so we will - // see some spurious refcount traffic here. + // Re-entering ::Suspect during collection used to be a fault, but + // we are canonicalizing nsISupports pointers using QI, so we will + // see some spurious refcount traffic here. - if (MOZ_UNLIKELY(mScanInProgress)) { - return; - } + if (MOZ_UNLIKELY(mScanInProgress)) { + return; + } - MOZ_ASSERT(aPtr, "Don't suspect null pointers"); + MOZ_ASSERT(aPtr, "Don't suspect null pointers"); - MOZ_ASSERT(HasParticipant(aPtr, aParti), - "Suspected nsISupports pointer must QI to nsXPCOMCycleCollectionParticipant"); + MOZ_ASSERT(HasParticipant(aPtr, aParti), + "Suspected nsISupports pointer must QI to nsXPCOMCycleCollectionParticipant"); - mPurpleBuf.Put(aPtr, aParti, aRefCnt); + mPurpleBuf.Put(aPtr, aParti, aRefCnt); } void nsCycleCollector::CheckThreadSafety() { #ifdef DEBUG - nsIThread* currentThread = NS_GetCurrentThread(); - // XXXkhuey we can be called so late in shutdown that NS_GetCurrentThread - // returns null (after the thread manager has shut down) - MOZ_ASSERT(mThread == currentThread || !currentThread); + nsIThread* currentThread = NS_GetCurrentThread(); + // XXXkhuey we can be called so late in shutdown that NS_GetCurrentThread + // returns null (after the thread manager has shut down) + MOZ_ASSERT(mThread == currentThread || !currentThread); #endif } @@ -3204,76 +3204,76 @@ nsCycleCollector::CheckThreadSafety() void nsCycleCollector::FixGrayBits(bool aForceGC) { - CheckThreadSafety(); + CheckThreadSafety(); - if (!mJSRuntime) - return; + if (!mJSRuntime) + return; - if (!aForceGC) { - mJSRuntime->FixWeakMappingGrayBits(); + if (!aForceGC) { + mJSRuntime->FixWeakMappingGrayBits(); - bool needGC = mJSRuntime->NeedCollect(); - // Only do a telemetry ping for non-shutdown CCs. - CC_TELEMETRY(_NEED_GC, needGC); - if (!needGC) - return; - mResults.mForcedGC = true; - } + bool needGC = mJSRuntime->NeedCollect(); + // Only do a telemetry ping for non-shutdown CCs. + CC_TELEMETRY(_NEED_GC, needGC); + if (!needGC) + return; + mResults.mForcedGC = true; + } - TimeLog timeLog; - mJSRuntime->Collect(aForceGC ? JS::gcreason::SHUTDOWN_CC : JS::gcreason::CC_FORCED); - timeLog.Checkpoint("GC()"); + TimeLog timeLog; + mJSRuntime->Collect(aForceGC ? JS::gcreason::SHUTDOWN_CC : JS::gcreason::CC_FORCED); + timeLog.Checkpoint("GC()"); } void nsCycleCollector::CleanupAfterCollection() { - MOZ_ASSERT(mIncrementalPhase == CleanupPhase); - mGraph.Clear(); + MOZ_ASSERT(mIncrementalPhase == CleanupPhase); + mGraph.Clear(); - uint32_t interval = (uint32_t) ((TimeStamp::Now() - mCollectionStart).ToMilliseconds()); + uint32_t interval = (uint32_t) ((TimeStamp::Now() - mCollectionStart).ToMilliseconds()); #ifdef COLLECT_TIME_DEBUG - printf("cc: total cycle collector time was %ums\n", interval); - printf("cc: visited %u ref counted and %u GCed objects, freed %d ref counted and %d GCed objects", - mResults.mVisitedRefCounted, mResults.mVisitedGCed, - mResults.mFreedRefCounted, mResults.mFreedGCed); - uint32_t numVisited = mResults.mVisitedRefCounted + mResults.mVisitedGCed; - if (numVisited > 1000) { - uint32_t numFreed = mResults.mFreedRefCounted + mResults.mFreedGCed; - printf(" (%d%%)", 100 * numFreed / numVisited); - } - printf(".\ncc: \n"); + printf("cc: total cycle collector time was %ums\n", interval); + printf("cc: visited %u ref counted and %u GCed objects, freed %d ref counted and %d GCed objects", + mResults.mVisitedRefCounted, mResults.mVisitedGCed, + mResults.mFreedRefCounted, mResults.mFreedGCed); + uint32_t numVisited = mResults.mVisitedRefCounted + mResults.mVisitedGCed; + if (numVisited > 1000) { + uint32_t numFreed = mResults.mFreedRefCounted + mResults.mFreedGCed; + printf(" (%d%%)", 100 * numFreed / numVisited); + } + printf(".\ncc: \n"); #endif - CC_TELEMETRY( , interval); - CC_TELEMETRY(_VISITED_REF_COUNTED, mResults.mVisitedRefCounted); - CC_TELEMETRY(_VISITED_GCED, mResults.mVisitedGCed); - CC_TELEMETRY(_COLLECTED, mWhiteNodeCount); + CC_TELEMETRY( , interval); + CC_TELEMETRY(_VISITED_REF_COUNTED, mResults.mVisitedRefCounted); + CC_TELEMETRY(_VISITED_GCED, mResults.mVisitedGCed); + CC_TELEMETRY(_COLLECTED, mWhiteNodeCount); - if (mJSRuntime) { - mJSRuntime->EndCycleCollectionCallback(mResults); - } - mIncrementalPhase = IdlePhase; + if (mJSRuntime) { + mJSRuntime->EndCycleCollectionCallback(mResults); + } + mIncrementalPhase = IdlePhase; } void nsCycleCollector::ShutdownCollect() { - SliceBudget unlimitedBudget; - uint32_t i; - for (i = 0; i < DEFAULT_SHUTDOWN_COLLECTIONS; ++i) { - if (!Collect(ShutdownCC, unlimitedBudget, nullptr)) { - break; - } + SliceBudget unlimitedBudget; + uint32_t i; + for (i = 0; i < DEFAULT_SHUTDOWN_COLLECTIONS; ++i) { + if (!Collect(ShutdownCC, unlimitedBudget, nullptr)) { + break; } - NS_WARN_IF_FALSE(i < NORMAL_SHUTDOWN_COLLECTIONS, "Extra shutdown CC"); + } + NS_WARN_IF_FALSE(i < NORMAL_SHUTDOWN_COLLECTIONS, "Extra shutdown CC"); } static void PrintPhase(const char *aPhase) { #ifdef DEBUG_PHASES - printf("cc: begin %s on %s\n", aPhase, - NS_IsMainThread() ? "mainthread" : "worker"); + printf("cc: begin %s on %s\n", aPhase, + NS_IsMainThread() ? "mainthread" : "worker"); #endif } @@ -3282,69 +3282,69 @@ nsCycleCollector::Collect(ccType aCCType, SliceBudget &aBudget, nsICycleCollectorListener *aManualListener) { - CheckThreadSafety(); + CheckThreadSafety(); - // This can legitimately happen in a few cases. See bug 383651. - if (mActivelyCollecting || mFreeingSnowWhite) { - return false; + // This can legitimately happen in a few cases. See bug 383651. + if (mActivelyCollecting || mFreeingSnowWhite) { + return false; + } + mActivelyCollecting = true; + + bool startedIdle = (mIncrementalPhase == IdlePhase); + bool collectedAny = false; + + // If the CC started idle, it will call BeginCollection, which + // will do FreeSnowWhite, so it doesn't need to be done here. + if (!startedIdle) { + FreeSnowWhite(true); + } + + bool finished = false; + do { + switch (mIncrementalPhase) { + case IdlePhase: + PrintPhase("BeginCollection"); + BeginCollection(aCCType, aManualListener); + break; + case GraphBuildingPhase: + PrintPhase("MarkRoots"); + MarkRoots(aBudget); + break; + case ScanAndCollectWhitePhase: + // We do ScanRoots and CollectWhite in a single slice to ensure + // that we won't unlink a live object if a weak reference is + // promoted to a strong reference after ScanRoots has finished. + // See bug 926533. + PrintPhase("ScanRoots"); + ScanRoots(startedIdle); + PrintPhase("CollectWhite"); + collectedAny = CollectWhite(); + break; + case CleanupPhase: + PrintPhase("CleanupAfterCollection"); + CleanupAfterCollection(); + finished = true; + break; } - mActivelyCollecting = true; + } while (!aBudget.checkOverBudget() && !finished); - bool startedIdle = (mIncrementalPhase == IdlePhase); - bool collectedAny = false; + // Clear mActivelyCollecting here to ensure that a recursive call to + // Collect() does something. + mActivelyCollecting = false; - // If the CC started idle, it will call BeginCollection, which - // will do FreeSnowWhite, so it doesn't need to be done here. - if (!startedIdle) { - FreeSnowWhite(true); + if (aCCType != SliceCC && !startedIdle) { + // We were in the middle of an incremental CC (using its own listener). + // Somebody has forced a CC, so after having finished out the current CC, + // run the CC again using the new listener. + MOZ_ASSERT(mIncrementalPhase == IdlePhase); + if (Collect(aCCType, aBudget, aManualListener)) { + collectedAny = true; } + } - bool finished = false; - do { - switch (mIncrementalPhase) { - case IdlePhase: - PrintPhase("BeginCollection"); - BeginCollection(aCCType, aManualListener); - break; - case GraphBuildingPhase: - PrintPhase("MarkRoots"); - MarkRoots(aBudget); - break; - case ScanAndCollectWhitePhase: - // We do ScanRoots and CollectWhite in a single slice to ensure - // that we won't unlink a live object if a weak reference is - // promoted to a strong reference after ScanRoots has finished. - // See bug 926533. - PrintPhase("ScanRoots"); - ScanRoots(startedIdle); - PrintPhase("CollectWhite"); - collectedAny = CollectWhite(); - break; - case CleanupPhase: - PrintPhase("CleanupAfterCollection"); - CleanupAfterCollection(); - finished = true; - break; - } - } while (!aBudget.checkOverBudget() && !finished); + MOZ_ASSERT_IF(aCCType != SliceCC, mIncrementalPhase == IdlePhase); - // Clear mActivelyCollecting here to ensure that a recursive call to - // Collect() does something. - mActivelyCollecting = false; - - if (aCCType != SliceCC && !startedIdle) { - // We were in the middle of an incremental CC (using its own listener). - // Somebody has forced a CC, so after having finished out the current CC, - // run the CC again using the new listener. - MOZ_ASSERT(mIncrementalPhase == IdlePhase); - if (Collect(aCCType, aBudget, aManualListener)) { - collectedAny = true; - } - } - - MOZ_ASSERT_IF(aCCType != SliceCC, mIncrementalPhase == IdlePhase); - - return collectedAny; + return collectedAny; } // Any JS objects we have in the graph could die when we GC, but we @@ -3354,20 +3354,20 @@ nsCycleCollector::Collect(ccType aCCType, void nsCycleCollector::PrepareForGarbageCollection() { - if (mIncrementalPhase == IdlePhase) { - MOZ_ASSERT(mGraph.IsEmpty(), "Non-empty graph when idle"); - MOZ_ASSERT(!mBuilder, "Non-null builder when idle"); - if (mJSPurpleBuffer) { - mJSPurpleBuffer->Destroy(); - } - return; + if (mIncrementalPhase == IdlePhase) { + MOZ_ASSERT(mGraph.IsEmpty(), "Non-empty graph when idle"); + MOZ_ASSERT(!mBuilder, "Non-null builder when idle"); + if (mJSPurpleBuffer) { + mJSPurpleBuffer->Destroy(); } + return; + } - SliceBudget unlimitedBudget; - PrintPhase("PrepareForGarbageCollection"); - // Use SliceCC because we only want to finish the CC in progress. - Collect(SliceCC, unlimitedBudget, nullptr); - MOZ_ASSERT(mIncrementalPhase == IdlePhase); + SliceBudget unlimitedBudget; + PrintPhase("PrepareForGarbageCollection"); + // Use SliceCC because we only want to finish the CC in progress. + Collect(SliceCC, unlimitedBudget, nullptr); + MOZ_ASSERT(mIncrementalPhase == IdlePhase); } // Don't merge too many times in a row, and do at least a minimum @@ -3378,139 +3378,139 @@ static const uint32_t kMaxConsecutiveMerged = 3; bool nsCycleCollector::ShouldMergeZones(ccType aCCType) { - if (!mJSRuntime) { - return false; - } + if (!mJSRuntime) { + return false; + } - MOZ_ASSERT(mUnmergedNeeded <= kMinConsecutiveUnmerged); - MOZ_ASSERT(mMergedInARow <= kMaxConsecutiveMerged); + MOZ_ASSERT(mUnmergedNeeded <= kMinConsecutiveUnmerged); + MOZ_ASSERT(mMergedInARow <= kMaxConsecutiveMerged); - if (mMergedInARow == kMaxConsecutiveMerged) { - MOZ_ASSERT(mUnmergedNeeded == 0); - mUnmergedNeeded = kMinConsecutiveUnmerged; - } + if (mMergedInARow == kMaxConsecutiveMerged) { + MOZ_ASSERT(mUnmergedNeeded == 0); + mUnmergedNeeded = kMinConsecutiveUnmerged; + } - if (mUnmergedNeeded > 0) { - mUnmergedNeeded--; - mMergedInARow = 0; - return false; - } + if (mUnmergedNeeded > 0) { + mUnmergedNeeded--; + mMergedInARow = 0; + return false; + } - if (aCCType == SliceCC && mJSRuntime->UsefulToMergeZones()) { - mMergedInARow++; - return true; - } else { - mMergedInARow = 0; - return false; - } + if (aCCType == SliceCC && mJSRuntime->UsefulToMergeZones()) { + mMergedInARow++; + return true; + } else { + mMergedInARow = 0; + return false; + } } void nsCycleCollector::BeginCollection(ccType aCCType, nsICycleCollectorListener *aManualListener) { - TimeLog timeLog; - MOZ_ASSERT(mIncrementalPhase == IdlePhase); + TimeLog timeLog; + MOZ_ASSERT(mIncrementalPhase == IdlePhase); - mCollectionStart = TimeStamp::Now(); + mCollectionStart = TimeStamp::Now(); - if (mJSRuntime) { - mJSRuntime->BeginCycleCollectionCallback(); - timeLog.Checkpoint("BeginCycleCollectionCallback()"); + if (mJSRuntime) { + mJSRuntime->BeginCycleCollectionCallback(); + timeLog.Checkpoint("BeginCycleCollectionCallback()"); + } + + bool isShutdown = (aCCType == ShutdownCC); + + // Set up the listener for this CC. + MOZ_ASSERT_IF(isShutdown, !aManualListener); + MOZ_ASSERT(!mListener, "Forgot to clear a previous listener?"); + mListener = aManualListener; + aManualListener = nullptr; + if (!mListener && mParams.LogThisCC(isShutdown)) { + nsRefPtr logger = new nsCycleCollectorLogger(); + if (mParams.AllTracesThisCC(isShutdown)) { + logger->SetAllTraces(); } + mListener = logger.forget(); + } - bool isShutdown = (aCCType == ShutdownCC); + bool forceGC = isShutdown; + if (!forceGC && mListener) { + // On a WantAllTraces CC, force a synchronous global GC to prevent + // hijinks from ForgetSkippable and compartmental GCs. + mListener->GetWantAllTraces(&forceGC); + } + FixGrayBits(forceGC); - // Set up the listener for this CC. - MOZ_ASSERT_IF(isShutdown, !aManualListener); - MOZ_ASSERT(!mListener, "Forgot to clear a previous listener?"); - mListener = aManualListener; - aManualListener = nullptr; - if (!mListener && mParams.LogThisCC(isShutdown)) { - nsRefPtr logger = new nsCycleCollectorLogger(); - if (mParams.AllTracesThisCC(isShutdown)) { - logger->SetAllTraces(); - } - mListener = logger.forget(); - } + FreeSnowWhite(true); - bool forceGC = isShutdown; - if (!forceGC && mListener) { - // On a WantAllTraces CC, force a synchronous global GC to prevent - // hijinks from ForgetSkippable and compartmental GCs. - mListener->GetWantAllTraces(&forceGC); - } - FixGrayBits(forceGC); + if (mListener && NS_FAILED(mListener->Begin())) { + mListener = nullptr; + } - FreeSnowWhite(true); + // Set up the data structures for building the graph. + mGraph.Init(); + mResults.Init(); + bool mergeZones = ShouldMergeZones(aCCType); + mResults.mMergedZones = mergeZones; - if (mListener && NS_FAILED(mListener->Begin())) { - mListener = nullptr; - } + MOZ_ASSERT(!mBuilder, "Forgot to clear mBuilder"); + mBuilder = new GCGraphBuilder(mGraph, mResults, mJSRuntime, mListener, mergeZones); - // Set up the data structures for building the graph. - mGraph.Init(); - mResults.Init(); - bool mergeZones = ShouldMergeZones(aCCType); - mResults.mMergedZones = mergeZones; + if (mJSRuntime) { + mJSRuntime->TraverseRoots(*mBuilder); + timeLog.Checkpoint("mJSRuntime->TraverseRoots()"); + } - MOZ_ASSERT(!mBuilder, "Forgot to clear mBuilder"); - mBuilder = new GCGraphBuilder(mGraph, mResults, mJSRuntime, mListener, mergeZones); + AutoRestore ar(mScanInProgress); + MOZ_ASSERT(!mScanInProgress); + mScanInProgress = true; + mPurpleBuf.SelectPointers(*mBuilder); + timeLog.Checkpoint("SelectPointers()"); - if (mJSRuntime) { - mJSRuntime->TraverseRoots(*mBuilder); - timeLog.Checkpoint("mJSRuntime->TraverseRoots()"); - } + // We've finished adding roots, and everything in the graph is a root. + mGraph.mRootCount = mGraph.MapCount(); - AutoRestore ar(mScanInProgress); - MOZ_ASSERT(!mScanInProgress); - mScanInProgress = true; - mPurpleBuf.SelectPointers(*mBuilder); - timeLog.Checkpoint("SelectPointers()"); - - // We've finished adding roots, and everything in the graph is a root. - mGraph.mRootCount = mGraph.MapCount(); - - mCurrNode = new NodePool::Enumerator(mGraph.mNodes); - mIncrementalPhase = GraphBuildingPhase; + mCurrNode = new NodePool::Enumerator(mGraph.mNodes); + mIncrementalPhase = GraphBuildingPhase; } uint32_t nsCycleCollector::SuspectedCount() { - CheckThreadSafety(); - return mPurpleBuf.Count(); + CheckThreadSafety(); + return mPurpleBuf.Count(); } void nsCycleCollector::Shutdown() { - CheckThreadSafety(); + CheckThreadSafety(); - // Always delete snow white objects. - FreeSnowWhite(true); + // Always delete snow white objects. + FreeSnowWhite(true); #ifndef DEBUG - if (PR_GetEnv("MOZ_CC_RUN_DURING_SHUTDOWN")) + if (PR_GetEnv("MOZ_CC_RUN_DURING_SHUTDOWN")) #endif - { - ShutdownCollect(); - } + { + ShutdownCollect(); + } } void nsCycleCollector::RemoveObjectFromGraph(void *aObj) { - if (mIncrementalPhase == IdlePhase) { - return; - } + if (mIncrementalPhase == IdlePhase) { + return; + } - if (PtrInfo *pinfo = mGraph.FindNode(aObj)) { - mGraph.RemoveNodeFromMap(aObj); + if (PtrInfo *pinfo = mGraph.FindNode(aObj)) { + mGraph.RemoveNodeFromMap(aObj); - pinfo->mPointer = nullptr; - pinfo->mParticipant = nullptr; - } + pinfo->mPointer = nullptr; + pinfo->mParticipant = nullptr; + } } void @@ -3521,16 +3521,16 @@ nsCycleCollector::SizeOfIncludingThis(mozilla::MallocSizeOf aMallocSizeOf, size_t *aWeakMapsSize, size_t *aPurpleBufferSize) const { - *aObjectSize = aMallocSizeOf(this); + *aObjectSize = aMallocSizeOf(this); - mGraph.SizeOfExcludingThis(aMallocSizeOf, aGraphNodesSize, aGraphEdgesSize, - aWeakMapsSize); + mGraph.SizeOfExcludingThis(aMallocSizeOf, aGraphNodesSize, aGraphEdgesSize, + aWeakMapsSize); - *aPurpleBufferSize = mPurpleBuf.SizeOfExcludingThis(aMallocSizeOf); + *aPurpleBufferSize = mPurpleBuf.SizeOfExcludingThis(aMallocSizeOf); - // These fields are deliberately not measured: - // - mJSRuntime: because it's non-owning and measured by JS reporters. - // - mParams: because it only contains scalars. + // These fields are deliberately not measured: + // - mJSRuntime: because it's non-owning and measured by JS reporters. + // - mParams: because it only contains scalars. } JSPurpleBuffer* @@ -3553,47 +3553,47 @@ nsCycleCollector::GetJSPurpleBuffer() void nsCycleCollector_registerJSRuntime(CycleCollectedJSRuntime *rt) { - CollectorData *data = sCollectorData.get(); + CollectorData *data = sCollectorData.get(); - // We should have started the cycle collector by now. - MOZ_ASSERT(data); - MOZ_ASSERT(data->mCollector); - // But we shouldn't already have a runtime. - MOZ_ASSERT(!data->mRuntime); + // We should have started the cycle collector by now. + MOZ_ASSERT(data); + MOZ_ASSERT(data->mCollector); + // But we shouldn't already have a runtime. + MOZ_ASSERT(!data->mRuntime); - data->mRuntime = rt; - data->mCollector->RegisterJSRuntime(rt); + data->mRuntime = rt; + data->mCollector->RegisterJSRuntime(rt); } void nsCycleCollector_forgetJSRuntime() { - CollectorData *data = sCollectorData.get(); + CollectorData *data = sCollectorData.get(); - // We should have started the cycle collector by now. - MOZ_ASSERT(data); - // And we shouldn't have already forgotten our runtime. - MOZ_ASSERT(data->mRuntime); + // We should have started the cycle collector by now. + MOZ_ASSERT(data); + // And we shouldn't have already forgotten our runtime. + MOZ_ASSERT(data->mRuntime); - // But it may have shutdown already. - if (data->mCollector) { - data->mCollector->ForgetJSRuntime(); - data->mRuntime = nullptr; - } else { - data->mRuntime = nullptr; - delete data; - sCollectorData.set(nullptr); - } + // But it may have shutdown already. + if (data->mCollector) { + data->mCollector->ForgetJSRuntime(); + data->mRuntime = nullptr; + } else { + data->mRuntime = nullptr; + delete data; + sCollectorData.set(nullptr); + } } /* static */ CycleCollectedJSRuntime* CycleCollectedJSRuntime::Get() { - CollectorData* data = sCollectorData.get(); - if (data) { - return data->mRuntime; - } - return nullptr; + CollectorData* data = sCollectorData.get(); + if (data) { + return data->mRuntime; + } + return nullptr; } @@ -3603,84 +3603,84 @@ namespace cyclecollector { void HoldJSObjectsImpl(void* aHolder, nsScriptObjectTracer* aTracer) { - CollectorData* data = sCollectorData.get(); + CollectorData* data = sCollectorData.get(); - // We should have started the cycle collector by now. - MOZ_ASSERT(data); - MOZ_ASSERT(data->mCollector); - // And we should have a runtime. - MOZ_ASSERT(data->mRuntime); + // We should have started the cycle collector by now. + MOZ_ASSERT(data); + MOZ_ASSERT(data->mCollector); + // And we should have a runtime. + MOZ_ASSERT(data->mRuntime); - data->mRuntime->AddJSHolder(aHolder, aTracer); + data->mRuntime->AddJSHolder(aHolder, aTracer); } void HoldJSObjectsImpl(nsISupports* aHolder) { - nsXPCOMCycleCollectionParticipant* participant; - CallQueryInterface(aHolder, &participant); - MOZ_ASSERT(participant, "Failed to QI to nsXPCOMCycleCollectionParticipant!"); - MOZ_ASSERT(participant->CheckForRightISupports(aHolder), - "The result of QIing a JS holder should be the same as ToSupports"); + nsXPCOMCycleCollectionParticipant* participant; + CallQueryInterface(aHolder, &participant); + MOZ_ASSERT(participant, "Failed to QI to nsXPCOMCycleCollectionParticipant!"); + MOZ_ASSERT(participant->CheckForRightISupports(aHolder), + "The result of QIing a JS holder should be the same as ToSupports"); - HoldJSObjectsImpl(aHolder, participant); + HoldJSObjectsImpl(aHolder, participant); } void DropJSObjectsImpl(void* aHolder) { - CollectorData* data = sCollectorData.get(); + CollectorData* data = sCollectorData.get(); - // We should have started the cycle collector by now, and not completely - // shut down. - MOZ_ASSERT(data); - // And we should have a runtime. - MOZ_ASSERT(data->mRuntime); + // We should have started the cycle collector by now, and not completely + // shut down. + MOZ_ASSERT(data); + // And we should have a runtime. + MOZ_ASSERT(data->mRuntime); - data->mRuntime->RemoveJSHolder(aHolder); + data->mRuntime->RemoveJSHolder(aHolder); } void DropJSObjectsImpl(nsISupports* aHolder) { #ifdef DEBUG - nsXPCOMCycleCollectionParticipant* participant; - CallQueryInterface(aHolder, &participant); - MOZ_ASSERT(participant, "Failed to QI to nsXPCOMCycleCollectionParticipant!"); - MOZ_ASSERT(participant->CheckForRightISupports(aHolder), - "The result of QIing a JS holder should be the same as ToSupports"); + nsXPCOMCycleCollectionParticipant* participant; + CallQueryInterface(aHolder, &participant); + MOZ_ASSERT(participant, "Failed to QI to nsXPCOMCycleCollectionParticipant!"); + MOZ_ASSERT(participant->CheckForRightISupports(aHolder), + "The result of QIing a JS holder should be the same as ToSupports"); #endif - DropJSObjectsImpl(static_cast(aHolder)); + DropJSObjectsImpl(static_cast(aHolder)); } #ifdef DEBUG bool IsJSHolder(void* aHolder) { - CollectorData *data = sCollectorData.get(); + CollectorData *data = sCollectorData.get(); - // We should have started the cycle collector by now, and not completely - // shut down. - MOZ_ASSERT(data); - // And we should have a runtime. - MOZ_ASSERT(data->mRuntime); + // We should have started the cycle collector by now, and not completely + // shut down. + MOZ_ASSERT(data); + // And we should have a runtime. + MOZ_ASSERT(data->mRuntime); - return data->mRuntime->IsJSHolder(aHolder); + return data->mRuntime->IsJSHolder(aHolder); } #endif void DeferredFinalize(nsISupports* aSupports) { - CollectorData *data = sCollectorData.get(); + CollectorData *data = sCollectorData.get(); - // We should have started the cycle collector by now, and not completely - // shut down. - MOZ_ASSERT(data); - // And we should have a runtime. - MOZ_ASSERT(data->mRuntime); + // We should have started the cycle collector by now, and not completely + // shut down. + MOZ_ASSERT(data); + // And we should have a runtime. + MOZ_ASSERT(data->mRuntime); - data->mRuntime->DeferredFinalize(aSupports); + data->mRuntime->DeferredFinalize(aSupports); } void @@ -3688,15 +3688,15 @@ DeferredFinalize(DeferredFinalizeAppendFunction aAppendFunc, DeferredFinalizeFunction aFunc, void* aThing) { - CollectorData *data = sCollectorData.get(); + CollectorData *data = sCollectorData.get(); - // We should have started the cycle collector by now, and not completely - // shut down. - MOZ_ASSERT(data); - // And we should have a runtime. - MOZ_ASSERT(data->mRuntime); + // We should have started the cycle collector by now, and not completely + // shut down. + MOZ_ASSERT(data); + // And we should have a runtime. + MOZ_ASSERT(data->mRuntime); - data->mRuntime->DeferredFinalize(aAppendFunc, aFunc, aThing); + data->mRuntime->DeferredFinalize(aAppendFunc, aFunc, aThing); } } // namespace cyclecollector @@ -3708,19 +3708,19 @@ SuspectAfterShutdown(void* n, nsCycleCollectionParticipant* cp, nsCycleCollectingAutoRefCnt* aRefCnt, bool* aShouldDelete) { - if (aRefCnt->get() == 0) { - if (!aShouldDelete) { - // The CC is shut down, so we can't be in the middle of an ICC. - CanonicalizeParticipant(&n, &cp); - aRefCnt->stabilizeForDeletion(); - cp->DeleteCycleCollectable(n); - } else { - *aShouldDelete = true; - } + if (aRefCnt->get() == 0) { + if (!aShouldDelete) { + // The CC is shut down, so we can't be in the middle of an ICC. + CanonicalizeParticipant(&n, &cp); + aRefCnt->stabilizeForDeletion(); + cp->DeleteCycleCollectable(n); } else { - // Make sure we'll get called again. - aRefCnt->RemoveFromPurpleBuffer(); + *aShouldDelete = true; } + } else { + // Make sure we'll get called again. + aRefCnt->RemoveFromPurpleBuffer(); + } } void @@ -3728,184 +3728,184 @@ NS_CycleCollectorSuspect3(void *n, nsCycleCollectionParticipant *cp, nsCycleCollectingAutoRefCnt *aRefCnt, bool* aShouldDelete) { - CollectorData *data = sCollectorData.get(); + CollectorData *data = sCollectorData.get(); - // We should have started the cycle collector by now. - MOZ_ASSERT(data); + // We should have started the cycle collector by now. + MOZ_ASSERT(data); - if (MOZ_LIKELY(data->mCollector)) { - data->mCollector->Suspect(n, cp, aRefCnt); - return; - } - SuspectAfterShutdown(n, cp, aRefCnt, aShouldDelete); + if (MOZ_LIKELY(data->mCollector)) { + data->mCollector->Suspect(n, cp, aRefCnt); + return; + } + SuspectAfterShutdown(n, cp, aRefCnt, aShouldDelete); } uint32_t nsCycleCollector_suspectedCount() { - CollectorData *data = sCollectorData.get(); + CollectorData *data = sCollectorData.get(); - // We should have started the cycle collector by now. - MOZ_ASSERT(data); + // We should have started the cycle collector by now. + MOZ_ASSERT(data); - if (!data->mCollector) { - return 0; - } + if (!data->mCollector) { + return 0; + } - return data->mCollector->SuspectedCount(); + return data->mCollector->SuspectedCount(); } bool nsCycleCollector_init() { - MOZ_ASSERT(NS_IsMainThread(), "Wrong thread!"); - MOZ_ASSERT(!sCollectorData.initialized(), "Called twice!?"); + MOZ_ASSERT(NS_IsMainThread(), "Wrong thread!"); + MOZ_ASSERT(!sCollectorData.initialized(), "Called twice!?"); - return sCollectorData.init(); + return sCollectorData.init(); } void nsCycleCollector_startup() { - MOZ_ASSERT(sCollectorData.initialized(), - "Forgot to call nsCycleCollector_init!"); - if (sCollectorData.get()) { - MOZ_CRASH(); - } + MOZ_ASSERT(sCollectorData.initialized(), + "Forgot to call nsCycleCollector_init!"); + if (sCollectorData.get()) { + MOZ_CRASH(); + } - CollectorData* data = new CollectorData; - data->mCollector = new nsCycleCollector(); - data->mRuntime = nullptr; + CollectorData* data = new CollectorData; + data->mCollector = new nsCycleCollector(); + data->mRuntime = nullptr; - sCollectorData.set(data); + sCollectorData.set(data); } void nsCycleCollector_setBeforeUnlinkCallback(CC_BeforeUnlinkCallback aCB) { - CollectorData *data = sCollectorData.get(); + CollectorData *data = sCollectorData.get(); - // We should have started the cycle collector by now. - MOZ_ASSERT(data); - MOZ_ASSERT(data->mCollector); + // We should have started the cycle collector by now. + MOZ_ASSERT(data); + MOZ_ASSERT(data->mCollector); - data->mCollector->SetBeforeUnlinkCallback(aCB); + data->mCollector->SetBeforeUnlinkCallback(aCB); } void nsCycleCollector_setForgetSkippableCallback(CC_ForgetSkippableCallback aCB) { - CollectorData *data = sCollectorData.get(); + CollectorData *data = sCollectorData.get(); - // We should have started the cycle collector by now. - MOZ_ASSERT(data); - MOZ_ASSERT(data->mCollector); + // We should have started the cycle collector by now. + MOZ_ASSERT(data); + MOZ_ASSERT(data->mCollector); - data->mCollector->SetForgetSkippableCallback(aCB); + data->mCollector->SetForgetSkippableCallback(aCB); } void nsCycleCollector_forgetSkippable(bool aRemoveChildlessNodes, bool aAsyncSnowWhiteFreeing) { - CollectorData *data = sCollectorData.get(); + CollectorData *data = sCollectorData.get(); - // We should have started the cycle collector by now. - MOZ_ASSERT(data); - MOZ_ASSERT(data->mCollector); + // We should have started the cycle collector by now. + MOZ_ASSERT(data); + MOZ_ASSERT(data->mCollector); - PROFILER_LABEL("CC", "nsCycleCollector_forgetSkippable"); - TimeLog timeLog; - data->mCollector->ForgetSkippable(aRemoveChildlessNodes, - aAsyncSnowWhiteFreeing); - timeLog.Checkpoint("ForgetSkippable()"); + PROFILER_LABEL("CC", "nsCycleCollector_forgetSkippable"); + TimeLog timeLog; + data->mCollector->ForgetSkippable(aRemoveChildlessNodes, + aAsyncSnowWhiteFreeing); + timeLog.Checkpoint("ForgetSkippable()"); } void nsCycleCollector_dispatchDeferredDeletion(bool aContinuation) { - CollectorData *data = sCollectorData.get(); + CollectorData *data = sCollectorData.get(); - if (!data || !data->mRuntime) { - return; - } + if (!data || !data->mRuntime) { + return; + } - data->mRuntime->DispatchDeferredDeletion(aContinuation); + data->mRuntime->DispatchDeferredDeletion(aContinuation); } bool nsCycleCollector_doDeferredDeletion() { - CollectorData *data = sCollectorData.get(); + CollectorData *data = sCollectorData.get(); - // We should have started the cycle collector by now. - MOZ_ASSERT(data); - MOZ_ASSERT(data->mCollector); - MOZ_ASSERT(data->mRuntime); + // We should have started the cycle collector by now. + MOZ_ASSERT(data); + MOZ_ASSERT(data->mCollector); + MOZ_ASSERT(data->mRuntime); - return data->mCollector->FreeSnowWhite(false); + return data->mCollector->FreeSnowWhite(false); } void nsCycleCollector_collect(nsICycleCollectorListener *aManualListener) { - CollectorData *data = sCollectorData.get(); + CollectorData *data = sCollectorData.get(); - // We should have started the cycle collector by now. - MOZ_ASSERT(data); - MOZ_ASSERT(data->mCollector); + // We should have started the cycle collector by now. + MOZ_ASSERT(data); + MOZ_ASSERT(data->mCollector); - PROFILER_LABEL("CC", "nsCycleCollector_collect"); - SliceBudget unlimitedBudget; - data->mCollector->Collect(ManualCC, unlimitedBudget, aManualListener); + PROFILER_LABEL("CC", "nsCycleCollector_collect"); + SliceBudget unlimitedBudget; + data->mCollector->Collect(ManualCC, unlimitedBudget, aManualListener); } void nsCycleCollector_collectSlice(int64_t aSliceTime) { - CollectorData *data = sCollectorData.get(); + CollectorData *data = sCollectorData.get(); - // We should have started the cycle collector by now. - MOZ_ASSERT(data); - MOZ_ASSERT(data->mCollector); + // We should have started the cycle collector by now. + MOZ_ASSERT(data); + MOZ_ASSERT(data->mCollector); - PROFILER_LABEL("CC", "nsCycleCollector_collectSlice"); - SliceBudget budget; - if (aSliceTime > 0) { - budget = SliceBudget::TimeBudget(aSliceTime); - } else if (aSliceTime == 0) { - budget = SliceBudget::WorkBudget(1); - } - data->mCollector->Collect(SliceCC, budget, nullptr); + PROFILER_LABEL("CC", "nsCycleCollector_collectSlice"); + SliceBudget budget; + if (aSliceTime > 0) { + budget = SliceBudget::TimeBudget(aSliceTime); + } else if (aSliceTime == 0) { + budget = SliceBudget::WorkBudget(1); + } + data->mCollector->Collect(SliceCC, budget, nullptr); } void nsCycleCollector_prepareForGarbageCollection() { - CollectorData *data = sCollectorData.get(); + CollectorData *data = sCollectorData.get(); - MOZ_ASSERT(data); + MOZ_ASSERT(data); - if (!data->mCollector) { - return; - } + if (!data->mCollector) { + return; + } - data->mCollector->PrepareForGarbageCollection(); + data->mCollector->PrepareForGarbageCollection(); } void nsCycleCollector_shutdown() { - CollectorData *data = sCollectorData.get(); + CollectorData *data = sCollectorData.get(); - if (data) { - MOZ_ASSERT(data->mCollector); - PROFILER_LABEL("CC", "nsCycleCollector_shutdown"); - data->mCollector->Shutdown(); - data->mCollector = nullptr; - if (!data->mRuntime) { - delete data; - sCollectorData.set(nullptr); - } + if (data) { + MOZ_ASSERT(data->mCollector); + PROFILER_LABEL("CC", "nsCycleCollector_shutdown"); + data->mCollector->Shutdown(); + data->mCollector = nullptr; + if (!data->mRuntime) { + delete data; + sCollectorData.set(nullptr); } + } } diff --git a/xpcom/base/nsDebugImpl.cpp b/xpcom/base/nsDebugImpl.cpp index d66ba6260714..8ae1310fe30e 100644 --- a/xpcom/base/nsDebugImpl.cpp +++ b/xpcom/base/nsDebugImpl.cpp @@ -1,4 +1,5 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ @@ -221,26 +222,26 @@ static nsAssertBehavior GetAssertBehavior() if (!assertString || !*assertString) return gAssertBehavior; - if (!strcmp(assertString, "warn")) - return gAssertBehavior = NS_ASSERT_WARN; + if (!strcmp(assertString, "warn")) + return gAssertBehavior = NS_ASSERT_WARN; - if (!strcmp(assertString, "suspend")) - return gAssertBehavior = NS_ASSERT_SUSPEND; + if (!strcmp(assertString, "suspend")) + return gAssertBehavior = NS_ASSERT_SUSPEND; - if (!strcmp(assertString, "stack")) - return gAssertBehavior = NS_ASSERT_STACK; + if (!strcmp(assertString, "stack")) + return gAssertBehavior = NS_ASSERT_STACK; - if (!strcmp(assertString, "abort")) - return gAssertBehavior = NS_ASSERT_ABORT; + if (!strcmp(assertString, "abort")) + return gAssertBehavior = NS_ASSERT_ABORT; - if (!strcmp(assertString, "trap") || !strcmp(assertString, "break")) - return gAssertBehavior = NS_ASSERT_TRAP; + if (!strcmp(assertString, "trap") || !strcmp(assertString, "break")) + return gAssertBehavior = NS_ASSERT_TRAP; - if (!strcmp(assertString, "stack-and-abort")) - return gAssertBehavior = NS_ASSERT_STACK_AND_ABORT; + if (!strcmp(assertString, "stack-and-abort")) + return gAssertBehavior = NS_ASSERT_STACK_AND_ABORT; - fprintf(stderr, "Unrecognized value of XPCOM_DEBUG_BREAK\n"); - return gAssertBehavior; + fprintf(stderr, "Unrecognized value of XPCOM_DEBUG_BREAK\n"); + return gAssertBehavior; } struct FixedBuffer @@ -256,7 +257,7 @@ StuffFixedBuffer(void *closure, const char *buf, uint32_t len) { if (!len) return 0; - + FixedBuffer *fb = (FixedBuffer*) closure; // strip the trailing null, we add it again later @@ -279,115 +280,115 @@ EXPORT_XPCOM_API(void) NS_DebugBreak(uint32_t aSeverity, const char *aStr, const char *aExpr, const char *aFile, int32_t aLine) { - InitLog(); + InitLog(); - FixedBuffer buf; - PRLogModuleLevel ll = PR_LOG_WARNING; - const char *sevString = "WARNING"; + FixedBuffer buf; + PRLogModuleLevel ll = PR_LOG_WARNING; + const char *sevString = "WARNING"; - switch (aSeverity) { - case NS_DEBUG_ASSERTION: - sevString = "###!!! ASSERTION"; - ll = PR_LOG_ERROR; - break; + switch (aSeverity) { + case NS_DEBUG_ASSERTION: + sevString = "###!!! ASSERTION"; + ll = PR_LOG_ERROR; + break; - case NS_DEBUG_BREAK: - sevString = "###!!! BREAK"; - ll = PR_LOG_ALWAYS; - break; + case NS_DEBUG_BREAK: + sevString = "###!!! BREAK"; + ll = PR_LOG_ALWAYS; + break; - case NS_DEBUG_ABORT: - sevString = "###!!! ABORT"; - ll = PR_LOG_ALWAYS; - break; + case NS_DEBUG_ABORT: + sevString = "###!!! ABORT"; + ll = PR_LOG_ALWAYS; + break; - default: - aSeverity = NS_DEBUG_WARNING; - }; + default: + aSeverity = NS_DEBUG_WARNING; + }; # define PrintToBuffer(...) PR_sxprintf(StuffFixedBuffer, &buf, __VA_ARGS__) - // Print "[PID]" or "[Desc PID]" at the beginning of the message. - PrintToBuffer("["); - if (sMultiprocessDescription) { - PrintToBuffer("%s ", sMultiprocessDescription); - } - PrintToBuffer("%d] ", base::GetCurrentProcId()); + // Print "[PID]" or "[Desc PID]" at the beginning of the message. + PrintToBuffer("["); + if (sMultiprocessDescription) { + PrintToBuffer("%s ", sMultiprocessDescription); + } + PrintToBuffer("%d] ", base::GetCurrentProcId()); - PrintToBuffer("%s: ", sevString); + PrintToBuffer("%s: ", sevString); - if (aStr) - PrintToBuffer("%s: ", aStr); + if (aStr) + PrintToBuffer("%s: ", aStr); - if (aExpr) - PrintToBuffer("'%s', ", aExpr); + if (aExpr) + PrintToBuffer("'%s', ", aExpr); - if (aFile) - PrintToBuffer("file %s, ", aFile); + if (aFile) + PrintToBuffer("file %s, ", aFile); - if (aLine != -1) - PrintToBuffer("line %d", aLine); + if (aLine != -1) + PrintToBuffer("line %d", aLine); # undef PrintToBuffer - // Write out the message to the debug log - PR_LOG(gDebugLog, ll, ("%s", buf.buffer)); - PR_LogFlush(); + // Write out the message to the debug log + PR_LOG(gDebugLog, ll, ("%s", buf.buffer)); + PR_LogFlush(); - // errors on platforms without a debugdlg ring a bell on stderr + // errors on platforms without a debugdlg ring a bell on stderr #if !defined(XP_WIN) - if (ll != PR_LOG_WARNING) - fprintf(stderr, "\07"); + if (ll != PR_LOG_WARNING) + fprintf(stderr, "\07"); #endif #ifdef ANDROID - __android_log_print(ANDROID_LOG_INFO, "Gecko", "%s", buf.buffer); + __android_log_print(ANDROID_LOG_INFO, "Gecko", "%s", buf.buffer); #endif - // Write the message to stderr unless it's a warning and MOZ_IGNORE_WARNINGS - // is set. - if (!(PR_GetEnv("MOZ_IGNORE_WARNINGS") && aSeverity == NS_DEBUG_WARNING)) { - fprintf(stderr, "%s\n", buf.buffer); - fflush(stderr); - } + // Write the message to stderr unless it's a warning and MOZ_IGNORE_WARNINGS + // is set. + if (!(PR_GetEnv("MOZ_IGNORE_WARNINGS") && aSeverity == NS_DEBUG_WARNING)) { + fprintf(stderr, "%s\n", buf.buffer); + fflush(stderr); + } - switch (aSeverity) { - case NS_DEBUG_WARNING: - return; + switch (aSeverity) { + case NS_DEBUG_WARNING: + return; - case NS_DEBUG_BREAK: - Break(buf.buffer); - return; + case NS_DEBUG_BREAK: + Break(buf.buffer); + return; - case NS_DEBUG_ABORT: { + case NS_DEBUG_ABORT: { #if defined(MOZ_CRASHREPORTER) - nsCString note("xpcom_runtime_abort("); - note += buf.buffer; - note += ")"; - CrashReporter::AppendAppNotesToCrashReport(note); - CrashReporter::AnnotateCrashReport(NS_LITERAL_CSTRING("AbortMessage"), - nsDependentCString(buf.buffer)); + nsCString note("xpcom_runtime_abort("); + note += buf.buffer; + note += ")"; + CrashReporter::AppendAppNotesToCrashReport(note); + CrashReporter::AnnotateCrashReport(NS_LITERAL_CSTRING("AbortMessage"), + nsDependentCString(buf.buffer)); #endif // MOZ_CRASHREPORTER #if defined(DEBUG) && defined(_WIN32) - RealBreak(); + RealBreak(); #endif #ifdef DEBUG - nsTraceRefcnt::WalkTheStack(stderr); + nsTraceRefcnt::WalkTheStack(stderr); #endif - Abort(buf.buffer); - return; - } - } + Abort(buf.buffer); + return; + } + } - // Now we deal with assertions - gAssertionCount++; + // Now we deal with assertions + gAssertionCount++; - switch (GetAssertBehavior()) { - case NS_ASSERT_WARN: - return; + switch (GetAssertBehavior()) { + case NS_ASSERT_WARN: + return; - case NS_ASSERT_SUSPEND: + case NS_ASSERT_SUSPEND: #ifdef XP_UNIX fprintf(stderr, "Suspending process; attach with the debugger.\n"); kill(0, SIGSTOP); @@ -396,23 +397,23 @@ NS_DebugBreak(uint32_t aSeverity, const char *aStr, const char *aExpr, #endif return; - case NS_ASSERT_STACK: - nsTraceRefcnt::WalkTheStack(stderr); - return; + case NS_ASSERT_STACK: + nsTraceRefcnt::WalkTheStack(stderr); + return; - case NS_ASSERT_STACK_AND_ABORT: - nsTraceRefcnt::WalkTheStack(stderr); - // Fall through to abort + case NS_ASSERT_STACK_AND_ABORT: + nsTraceRefcnt::WalkTheStack(stderr); + // Fall through to abort - case NS_ASSERT_ABORT: - Abort(buf.buffer); - return; + case NS_ASSERT_ABORT: + Abort(buf.buffer); + return; - case NS_ASSERT_TRAP: - case NS_ASSERT_UNINITIALIZED: // Default to "trap" behavior - Break(buf.buffer); - return; - } + case NS_ASSERT_TRAP: + case NS_ASSERT_UNINITIALIZED: // Default to "trap" behavior + Break(buf.buffer); + return; + } } static void @@ -427,25 +428,25 @@ RealBreak() #if defined(_WIN32) ::DebugBreak(); #elif defined(XP_MACOSX) - raise(SIGTRAP); + raise(SIGTRAP); #elif defined(__GNUC__) && (defined(__i386__) || defined(__i386) || defined(__x86_64__)) - asm("int $3"); + asm("int $3"); #elif defined(__arm__) - asm( + asm( #ifdef __ARM_ARCH_4T__ -/* ARMv4T doesn't support the BKPT instruction, so if the compiler target - * is ARMv4T, we want to ensure the assembler will understand that ARMv5T - * instruction, while keeping the resulting object tagged as ARMv4T. - */ - ".arch armv5t\n" - ".object_arch armv4t\n" + /* ARMv4T doesn't support the BKPT instruction, so if the compiler target + * is ARMv4T, we want to ensure the assembler will understand that ARMv5T + * instruction, while keeping the resulting object tagged as ARMv4T. + */ + ".arch armv5t\n" + ".object_arch armv4t\n" #endif - "BKPT #0"); + "BKPT #0"); #elif defined(SOLARIS) #if defined(__i386__) || defined(__i386) || defined(__x86_64__) - asm("int $3"); + asm("int $3"); #else - raise(SIGTRAP); + raise(SIGTRAP); #endif #else #warning do not know how to break on this platform @@ -465,7 +466,7 @@ Break(const char *aMsg) if ((ignoreDebugger == 2) || !::IsDebuggerPresent()) { DWORD code = IDRETRY; - /* Create the debug dialog out of process to avoid the crashes caused by + /* Create the debug dialog out of process to avoid the crashes caused by * Windows events leaking into our event loop from an in process dialog. * We do this by launching windbgdlg.exe (built in xpcom/windbgdlg). * See http://bugzilla.mozilla.org/show_bug.cgi?id=54792 @@ -486,11 +487,11 @@ Break(const char *aMsg) wcscpy(msgCopy, NS_ConvertUTF8toUTF16(aMsg).get()); if(GetModuleFileNameW(GetModuleHandleW(L"xpcom.dll"), executable, MAX_PATH) && - nullptr != (pName = wcsrchr(executable, '\\')) && - nullptr != wcscpy(pName + 1, L"windbgdlg.exe") && - CreateProcessW(executable, msgCopy, nullptr, nullptr, - false, DETACHED_PROCESS | NORMAL_PRIORITY_CLASS, - nullptr, nullptr, &si, &pi)) { + nullptr != (pName = wcsrchr(executable, '\\')) && + nullptr != wcscpy(pName + 1, L"windbgdlg.exe") && + CreateProcessW(executable, msgCopy, nullptr, nullptr, + false, DETACHED_PROCESS | NORMAL_PRIORITY_CLASS, + nullptr, nullptr, &si, &pi)) { WaitForSingleObject(pi.hProcess, INFINITE); GetExitCodeProcess(pi.hProcess, &code); CloseHandle(pi.hProcess); @@ -498,30 +499,30 @@ Break(const char *aMsg) } switch(code) { - case IDABORT: - //This should exit us - raise(SIGABRT); - //If we are ignored exit this way.. - _exit(3); - - case IDIGNORE: - return; + case IDABORT: + //This should exit us + raise(SIGABRT); + //If we are ignored exit this way.. + _exit(3); + + case IDIGNORE: + return; } } RealBreak(); #elif defined(XP_MACOSX) - /* Note that we put this Mac OS X test above the GNUC/x86 test because the - * GNUC/x86 test is also true on Intel Mac OS X and we want the PPC/x86 - * impls to be the same. - */ - RealBreak(); + /* Note that we put this Mac OS X test above the GNUC/x86 test because the + * GNUC/x86 test is also true on Intel Mac OS X and we want the PPC/x86 + * impls to be the same. + */ + RealBreak(); #elif defined(__GNUC__) && (defined(__i386__) || defined(__i386) || defined(__x86_64__)) - RealBreak(); + RealBreak(); #elif defined(__arm__) - RealBreak(); + RealBreak(); #elif defined(SOLARIS) - RealBreak(); + RealBreak(); #else #warning do not know how to break on this platform #endif @@ -544,24 +545,24 @@ nsDebugImpl::Create(nsISupports* outer, const nsIID& aIID, void* *aInstancePtr) nsresult NS_ErrorAccordingToNSPR() { - PRErrorCode err = PR_GetError(); - switch (err) { - case PR_OUT_OF_MEMORY_ERROR: return NS_ERROR_OUT_OF_MEMORY; - case PR_WOULD_BLOCK_ERROR: return NS_BASE_STREAM_WOULD_BLOCK; - case PR_FILE_NOT_FOUND_ERROR: return NS_ERROR_FILE_NOT_FOUND; - case PR_READ_ONLY_FILESYSTEM_ERROR: return NS_ERROR_FILE_READ_ONLY; - case PR_NOT_DIRECTORY_ERROR: return NS_ERROR_FILE_NOT_DIRECTORY; - case PR_IS_DIRECTORY_ERROR: return NS_ERROR_FILE_IS_DIRECTORY; - case PR_LOOP_ERROR: return NS_ERROR_FILE_UNRESOLVABLE_SYMLINK; - case PR_FILE_EXISTS_ERROR: return NS_ERROR_FILE_ALREADY_EXISTS; - case PR_FILE_IS_LOCKED_ERROR: return NS_ERROR_FILE_IS_LOCKED; - case PR_FILE_TOO_BIG_ERROR: return NS_ERROR_FILE_TOO_BIG; - case PR_NO_DEVICE_SPACE_ERROR: return NS_ERROR_FILE_NO_DEVICE_SPACE; - case PR_NAME_TOO_LONG_ERROR: return NS_ERROR_FILE_NAME_TOO_LONG; - case PR_DIRECTORY_NOT_EMPTY_ERROR: return NS_ERROR_FILE_DIR_NOT_EMPTY; - case PR_NO_ACCESS_RIGHTS_ERROR: return NS_ERROR_FILE_ACCESS_DENIED; - default: return NS_ERROR_FAILURE; - } + PRErrorCode err = PR_GetError(); + switch (err) { + case PR_OUT_OF_MEMORY_ERROR: return NS_ERROR_OUT_OF_MEMORY; + case PR_WOULD_BLOCK_ERROR: return NS_BASE_STREAM_WOULD_BLOCK; + case PR_FILE_NOT_FOUND_ERROR: return NS_ERROR_FILE_NOT_FOUND; + case PR_READ_ONLY_FILESYSTEM_ERROR: return NS_ERROR_FILE_READ_ONLY; + case PR_NOT_DIRECTORY_ERROR: return NS_ERROR_FILE_NOT_DIRECTORY; + case PR_IS_DIRECTORY_ERROR: return NS_ERROR_FILE_IS_DIRECTORY; + case PR_LOOP_ERROR: return NS_ERROR_FILE_UNRESOLVABLE_SYMLINK; + case PR_FILE_EXISTS_ERROR: return NS_ERROR_FILE_ALREADY_EXISTS; + case PR_FILE_IS_LOCKED_ERROR: return NS_ERROR_FILE_IS_LOCKED; + case PR_FILE_TOO_BIG_ERROR: return NS_ERROR_FILE_TOO_BIG; + case PR_NO_DEVICE_SPACE_ERROR: return NS_ERROR_FILE_NO_DEVICE_SPACE; + case PR_NAME_TOO_LONG_ERROR: return NS_ERROR_FILE_NAME_TOO_LONG; + case PR_DIRECTORY_NOT_EMPTY_ERROR: return NS_ERROR_FILE_DIR_NOT_EMPTY; + case PR_NO_ACCESS_RIGHTS_ERROR: return NS_ERROR_FILE_ACCESS_DENIED; + default: return NS_ERROR_FAILURE; + } } void diff --git a/xpcom/base/nsDebugImpl.h b/xpcom/base/nsDebugImpl.h index 547675d78cea..d0840786fb03 100644 --- a/xpcom/base/nsDebugImpl.h +++ b/xpcom/base/nsDebugImpl.h @@ -1,3 +1,5 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ @@ -11,20 +13,20 @@ class nsDebugImpl : public nsIDebug2 { public: - nsDebugImpl() {} - NS_DECL_ISUPPORTS - NS_DECL_NSIDEBUG - NS_DECL_NSIDEBUG2 + nsDebugImpl() {} + NS_DECL_ISUPPORTS + NS_DECL_NSIDEBUG + NS_DECL_NSIDEBUG2 - static nsresult Create(nsISupports* outer, const nsIID& aIID, void* *aInstancePtr); + static nsresult Create(nsISupports* outer, const nsIID& aIID, void* *aInstancePtr); - /* - * Inform nsDebugImpl that we're in multiprocess mode. - * - * If aDesc is not nullptr, the string it points to must be - * statically-allocated (i.e., it must be a string literal). - */ - static void SetMultiprocessMode(const char *aDesc); + /* + * Inform nsDebugImpl that we're in multiprocess mode. + * + * If aDesc is not nullptr, the string it points to must be + * statically-allocated (i.e., it must be a string literal). + */ + static void SetMultiprocessMode(const char *aDesc); }; diff --git a/xpcom/base/nsDumpUtils.cpp b/xpcom/base/nsDumpUtils.cpp index 852602e1c39e..b80bf12f331a 100644 --- a/xpcom/base/nsDumpUtils.cpp +++ b/xpcom/base/nsDumpUtils.cpp @@ -49,7 +49,7 @@ using namespace mozilla; static Atomic sDumpPipeWriteFd(-1); const char* const FifoWatcher::kPrefName = - "memory_info_dumper.watch_fifo.enabled"; + "memory_info_dumper.watch_fifo.enabled"; static void DumpSignalHandler(int aSignum) @@ -73,8 +73,8 @@ void FdWatcher::Init() os->AddObserver(this, "xpcom-shutdown", /* ownsWeak = */ false); XRE_GetIOMessageLoop()->PostTask( - FROM_HERE, - NewRunnableMethod(this, &FdWatcher::StartWatching)); + FROM_HERE, + NewRunnableMethod(this, &FdWatcher::StartWatching)); } // Implementations may call this function multiple times if they ensure that @@ -337,9 +337,9 @@ int FifoWatcher::OpenFd() } #ifdef ANDROID - // Android runs with a umask, so we need to chmod our fifo to make it - // world-writable. - chmod(path.get(), 0666); + // Android runs with a umask, so we need to chmod our fifo to make it + // world-writable. + chmod(path.get(), 0666); #endif int fd; @@ -478,15 +478,15 @@ nsDumpUtils::OpenTempFile(const nsACString& aFilename, nsIFile** aFile, return rv; #ifdef ANDROID - // Make this file world-read/writable; the permissions passed to the - // CreateUnique call above are not sufficient on Android, which runs with a - // umask. - nsAutoCString path; - rv = file->GetNativePath(path); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + // Make this file world-read/writable; the permissions passed to the + // CreateUnique call above are not sufficient on Android, which runs with a + // umask. + nsAutoCString path; + rv = file->GetNativePath(path); + if (NS_WARN_IF(NS_FAILED(rv))) + return rv; - while (chmod(path.get(), 0666) == -1 && errno == EINTR) {} + while (chmod(path.get(), 0666) == -1 && errno == EINTR) {} #endif return NS_OK; diff --git a/xpcom/base/nsDumpUtils.h b/xpcom/base/nsDumpUtils.h index 86addad4d2f3..1aaced435af1 100644 --- a/xpcom/base/nsDumpUtils.h +++ b/xpcom/base/nsDumpUtils.h @@ -91,8 +91,8 @@ public: MOZ_ASSERT(!strcmp(aTopic, "xpcom-shutdown")); XRE_GetIOMessageLoop()->PostTask( - FROM_HERE, - NewRunnableMethod(this, &FdWatcher::StopWatching)); + FROM_HERE, + NewRunnableMethod(this, &FdWatcher::StopWatching)); return NS_OK; } @@ -190,8 +190,8 @@ public: * instead. */ static nsresult OpenTempFile(const nsACString& aFilename, - nsIFile** aFile, - const nsACString& aFoldername = EmptyCString()); + nsIFile** aFile, + const nsACString& aFoldername = EmptyCString()); }; #endif diff --git a/xpcom/base/nsError.h b/xpcom/base/nsError.h index 96540c615c25..c6f51d4cfecf 100644 --- a/xpcom/base/nsError.h +++ b/xpcom/base/nsError.h @@ -1,4 +1,5 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ @@ -199,9 +200,9 @@ static_assert(sizeof(nsresult) == sizeof(uint32_t), */ #define NS_ERROR_GENERATE(sev, module, code) \ - (nsresult)(((uint32_t)(sev) << 31) | \ - ((uint32_t)(module + NS_ERROR_MODULE_BASE_OFFSET) << 16) | \ - ((uint32_t)(code))) + (nsresult)(((uint32_t)(sev) << 31) | \ + ((uint32_t)(module + NS_ERROR_MODULE_BASE_OFFSET) << 16) | \ + ((uint32_t)(code))) #define NS_ERROR_GENERATE_SUCCESS(module, code) \ NS_ERROR_GENERATE(NS_ERROR_SEVERITY_SUCCESS, module, code) diff --git a/xpcom/base/nsErrorService.cpp b/xpcom/base/nsErrorService.cpp index 297a4fc59758..f4eeb12d96f4 100644 --- a/xpcom/base/nsErrorService.cpp +++ b/xpcom/base/nsErrorService.cpp @@ -1,4 +1,5 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ @@ -21,7 +22,7 @@ DeleteCString(nsHashKey *aKey, void *aData, void* closure) } nsInt2StrHashtable::nsInt2StrHashtable() - : mHashtable(CloneCString, nullptr, DeleteCString, nullptr, 16) + : mHashtable(CloneCString, nullptr, DeleteCString, nullptr, 16) { } @@ -38,7 +39,7 @@ nsInt2StrHashtable::Put(uint32_t key, const char* aData) return NS_OK; } -char* +char* nsInt2StrHashtable::Get(uint32_t key) { nsPRUint32Key k(key); @@ -65,32 +66,32 @@ NS_IMPL_ISUPPORTS(nsErrorService, nsIErrorService) nsresult nsErrorService::Create(nsISupports* outer, const nsIID& aIID, void* *aInstancePtr) { - if (NS_WARN_IF(outer)) - return NS_ERROR_NO_AGGREGATION; - nsRefPtr serv = new nsErrorService(); - return serv->QueryInterface(aIID, aInstancePtr); + if (NS_WARN_IF(outer)) + return NS_ERROR_NO_AGGREGATION; + nsRefPtr serv = new nsErrorService(); + return serv->QueryInterface(aIID, aInstancePtr); } NS_IMETHODIMP nsErrorService::RegisterErrorStringBundle(int16_t errorModule, const char *stringBundleURL) { - return mErrorStringBundleURLMap.Put(errorModule, stringBundleURL); + return mErrorStringBundleURLMap.Put(errorModule, stringBundleURL); } NS_IMETHODIMP nsErrorService::UnregisterErrorStringBundle(int16_t errorModule) { - return mErrorStringBundleURLMap.Remove(errorModule); + return mErrorStringBundleURLMap.Remove(errorModule); } NS_IMETHODIMP nsErrorService::GetErrorStringBundle(int16_t errorModule, char **result) { - char* value = mErrorStringBundleURLMap.Get(errorModule); - if (value == nullptr) - return NS_ERROR_OUT_OF_MEMORY; - *result = value; - return NS_OK; + char* value = mErrorStringBundleURLMap.Get(errorModule); + if (value == nullptr) + return NS_ERROR_OUT_OF_MEMORY; + *result = value; + return NS_OK; } //////////////////////////////////////////////////////////////////////////////// diff --git a/xpcom/base/nsErrorService.h b/xpcom/base/nsErrorService.h index b005b9426087..f7277b415855 100644 --- a/xpcom/base/nsErrorService.h +++ b/xpcom/base/nsErrorService.h @@ -1,4 +1,5 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ @@ -14,32 +15,32 @@ class nsInt2StrHashtable { public: - nsInt2StrHashtable(); + nsInt2StrHashtable(); - nsresult Put(uint32_t key, const char* aData); - char* Get(uint32_t key); - nsresult Remove(uint32_t key); + nsresult Put(uint32_t key, const char* aData); + char* Get(uint32_t key); + nsresult Remove(uint32_t key); protected: - nsObjectHashtable mHashtable; + nsObjectHashtable mHashtable; }; class nsErrorService MOZ_FINAL : public nsIErrorService { public: - NS_DECL_ISUPPORTS - NS_DECL_NSIERRORSERVICE + NS_DECL_ISUPPORTS + NS_DECL_NSIERRORSERVICE - nsErrorService() {} + nsErrorService() {} - static nsresult - Create(nsISupports* outer, const nsIID& aIID, void* *aInstancePtr); + static nsresult + Create(nsISupports* outer, const nsIID& aIID, void* *aInstancePtr); private: - ~nsErrorService() {} + ~nsErrorService() {} protected: - nsInt2StrHashtable mErrorStringBundleURLMap; + nsInt2StrHashtable mErrorStringBundleURLMap; }; #endif // nsErrorService_h__ diff --git a/xpcom/base/nsISupportsObsolete.h b/xpcom/base/nsISupportsObsolete.h index 53d520ec0a18..24ce7938e563 100644 --- a/xpcom/base/nsISupportsObsolete.h +++ b/xpcom/base/nsISupportsObsolete.h @@ -1,3 +1,5 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ @@ -23,13 +25,13 @@ * NS_FREE_XPCOM_POINTER_ARRAY directly and using NS_RELEASE as your * free function. * - * @param size Number of elements in the array. If not a constant, this - * should be a int32_t. Note that this means this macro + * @param size Number of elements in the array. If not a constant, this + * should be a int32_t. Note that this means this macro * will not work if size >= 2^31. * @param array The array to be freed. */ #define NS_FREE_XPCOM_ISUPPORTS_POINTER_ARRAY(size, array) \ - NS_FREE_XPCOM_POINTER_ARRAY((size), (array), NS_IF_RELEASE) + NS_FREE_XPCOM_POINTER_ARRAY((size), (array), NS_IF_RELEASE) /////////////////////////////////////////////////////////////////////////////// @@ -41,16 +43,16 @@ #define NS_METHOD_GETTER(_method, _type, _member) \ _method(_type* aResult) \ {\ - if (!aResult) return NS_ERROR_NULL_POINTER; \ - *aResult = _member; \ - return NS_OK; \ + if (!aResult) return NS_ERROR_NULL_POINTER; \ + *aResult = _member; \ + return NS_OK; \ } - + #define NS_METHOD_SETTER(_method, _type, _member) \ _method(_type aResult) \ { \ - _member = aResult; \ - return NS_OK; \ + _member = aResult; \ + return NS_OK; \ } /* @@ -60,21 +62,21 @@ _method(_type aResult) \ #define NS_METHOD_GETTER_STR(_method,_member) \ _method(char* *aString) \ { \ - if (!aString) return NS_ERROR_NULL_POINTER; \ - if (!(*aString = PL_strdup(_member))) \ - return NS_ERROR_OUT_OF_MEMORY; \ - return NS_OK; \ + if (!aString) return NS_ERROR_NULL_POINTER; \ + if (!(*aString = PL_strdup(_member))) \ + return NS_ERROR_OUT_OF_MEMORY; \ + return NS_OK; \ } #define NS_METHOD_SETTER_STR(_method, _member) \ _method(const char *aString) \ { \ - if (_member) PR_Free(_member); \ - if (!aString) \ - _member = nullptr; \ - else if (!(_member = PL_strdup(aString))) \ - return NS_ERROR_OUT_OF_MEMORY; \ - return NS_OK; \ + if (_member) PR_Free(_member); \ + if (!aString) \ + _member = nullptr; \ + else if (!(_member = PL_strdup(aString))) \ + return NS_ERROR_OUT_OF_MEMORY; \ + return NS_OK; \ } /* Getter/Setter macros. @@ -82,7 +84,7 @@ _method(const char *aString) \ NS_IMPL_[CLASS_]GETTER[_](method, [type,] member); NS_IMPL_[CLASS_]SETTER[_](method, [type,] member); NS_IMPL_[CLASS_]GETSET[_]([class, ]postfix, [type,] member); - + where: CLASS_ - implementation is inside a class definition (otherwise the class name is needed) @@ -96,14 +98,14 @@ _method(const char *aString) \ member - class member variable such as m_width or mColor class - the class name, such as Window or MyObject postfix - Method part after Get/Set such as "Width" for "GetWidth" - + Example: class Window { public: NS_IMPL_CLASS_GETSET(Width, int, m_width); NS_IMPL_CLASS_GETTER_STR(GetColor, m_color); NS_IMETHOD SetColor(char *color); - + private: int m_width; // read/write char *m_color; // readonly @@ -115,7 +117,7 @@ _method(const char *aString) \ Questions/Comments to alecf@netscape.com */ - + /* * Getter/Setter implementation within a class definition */ diff --git a/xpcom/base/nsMacUtilsImpl.cpp b/xpcom/base/nsMacUtilsImpl.cpp index a6f6004cca49..3379e03afb27 100644 --- a/xpcom/base/nsMacUtilsImpl.cpp +++ b/xpcom/base/nsMacUtilsImpl.cpp @@ -1,4 +1,5 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ @@ -19,9 +20,9 @@ nsresult nsMacUtilsImpl::GetArchString(nsAString& archString) archString.Truncate(); bool foundPPC = false, - foundX86 = false, - foundPPC64 = false, - foundX86_64 = false; + foundX86 = false, + foundPPC64 = false, + foundX86_64 = false; CFBundleRef mainBundle = ::CFBundleGetMainBundle(); if (!mainBundle) { diff --git a/xpcom/base/nsMemoryImpl.cpp b/xpcom/base/nsMemoryImpl.cpp index 8fd6dddd83f2..c244c73380b4 100644 --- a/xpcom/base/nsMemoryImpl.cpp +++ b/xpcom/base/nsMemoryImpl.cpp @@ -1,4 +1,5 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ @@ -30,146 +31,146 @@ NS_IMPL_QUERY_INTERFACE(nsMemoryImpl, nsIMemory) NS_IMETHODIMP_(void*) nsMemoryImpl::Alloc(size_t size) { - return NS_Alloc(size); + return NS_Alloc(size); } NS_IMETHODIMP_(void*) nsMemoryImpl::Realloc(void* ptr, size_t size) { - return NS_Realloc(ptr, size); + return NS_Realloc(ptr, size); } NS_IMETHODIMP_(void) nsMemoryImpl::Free(void* ptr) { - NS_Free(ptr); + NS_Free(ptr); } NS_IMETHODIMP nsMemoryImpl::HeapMinimize(bool aImmediate) { - return FlushMemory(MOZ_UTF16("heap-minimize"), aImmediate); + return FlushMemory(MOZ_UTF16("heap-minimize"), aImmediate); } NS_IMETHODIMP nsMemoryImpl::IsLowMemory(bool *result) { - NS_ERROR("IsLowMemory is deprecated. See bug 592308."); - *result = false; - return NS_OK; + NS_ERROR("IsLowMemory is deprecated. See bug 592308."); + *result = false; + return NS_OK; } NS_IMETHODIMP nsMemoryImpl::IsLowMemoryPlatform(bool *result) { #ifdef ANDROID - static int sLowMemory = -1; // initialize to unknown, lazily evaluate to 0 or 1 - if (sLowMemory == -1) { - sLowMemory = 0; // assume "not low memory" in case file operations fail - *result = false; - - // check if MemTotal from /proc/meminfo is less than LOW_MEMORY_THRESHOLD_KB - FILE* fd = fopen("/proc/meminfo", "r"); - if (!fd) { - return NS_OK; - } - uint64_t mem = 0; - int rv = fscanf(fd, "MemTotal: %llu kB", &mem); - if (fclose(fd)) { - return NS_OK; - } - if (rv != 1) { - return NS_OK; - } - sLowMemory = (mem < LOW_MEMORY_THRESHOLD_KB) ? 1 : 0; - } - *result = (sLowMemory == 1); -#else + static int sLowMemory = -1; // initialize to unknown, lazily evaluate to 0 or 1 + if (sLowMemory == -1) { + sLowMemory = 0; // assume "not low memory" in case file operations fail *result = false; + + // check if MemTotal from /proc/meminfo is less than LOW_MEMORY_THRESHOLD_KB + FILE* fd = fopen("/proc/meminfo", "r"); + if (!fd) { + return NS_OK; + } + uint64_t mem = 0; + int rv = fscanf(fd, "MemTotal: %llu kB", &mem); + if (fclose(fd)) { + return NS_OK; + } + if (rv != 1) { + return NS_OK; + } + sLowMemory = (mem < LOW_MEMORY_THRESHOLD_KB) ? 1 : 0; + } + *result = (sLowMemory == 1); +#else + *result = false; #endif - return NS_OK; + return NS_OK; } /*static*/ nsresult nsMemoryImpl::Create(nsISupports* outer, const nsIID& aIID, void **aResult) { - if (NS_WARN_IF(outer)) - return NS_ERROR_NO_AGGREGATION; - return sGlobalMemory.QueryInterface(aIID, aResult); + if (NS_WARN_IF(outer)) + return NS_ERROR_NO_AGGREGATION; + return sGlobalMemory.QueryInterface(aIID, aResult); } nsresult nsMemoryImpl::FlushMemory(const char16_t* aReason, bool aImmediate) { - nsresult rv = NS_OK; + nsresult rv = NS_OK; - if (aImmediate) { - // They've asked us to run the flusher *immediately*. We've - // got to be on the UI main thread for us to be able to do - // that...are we? - if (!NS_IsMainThread()) { - NS_ERROR("can't synchronously flush memory: not on UI thread"); - return NS_ERROR_FAILURE; - } + if (aImmediate) { + // They've asked us to run the flusher *immediately*. We've + // got to be on the UI main thread for us to be able to do + // that...are we? + if (!NS_IsMainThread()) { + NS_ERROR("can't synchronously flush memory: not on UI thread"); + return NS_ERROR_FAILURE; } + } - bool lastVal = sIsFlushing.exchange(true); - if (lastVal) - return NS_OK; + bool lastVal = sIsFlushing.exchange(true); + if (lastVal) + return NS_OK; - PRIntervalTime now = PR_IntervalNow(); + PRIntervalTime now = PR_IntervalNow(); - // Run the flushers immediately if we can; otherwise, proxy to the - // UI thread an run 'em asynchronously. - if (aImmediate) { - rv = RunFlushers(aReason); - } - else { - // Don't broadcast more than once every 1000ms to avoid being noisy - if (PR_IntervalToMicroseconds(now - sLastFlushTime) > 1000) { - sFlushEvent.mReason = aReason; - rv = NS_DispatchToMainThread(&sFlushEvent, NS_DISPATCH_NORMAL); - } + // Run the flushers immediately if we can; otherwise, proxy to the + // UI thread an run 'em asynchronously. + if (aImmediate) { + rv = RunFlushers(aReason); + } + else { + // Don't broadcast more than once every 1000ms to avoid being noisy + if (PR_IntervalToMicroseconds(now - sLastFlushTime) > 1000) { + sFlushEvent.mReason = aReason; + rv = NS_DispatchToMainThread(&sFlushEvent, NS_DISPATCH_NORMAL); } + } - sLastFlushTime = now; - return rv; + sLastFlushTime = now; + return rv; } nsresult nsMemoryImpl::RunFlushers(const char16_t* aReason) { - nsCOMPtr os = mozilla::services::GetObserverService(); - if (os) { + nsCOMPtr os = mozilla::services::GetObserverService(); + if (os) { - // Instead of: - // os->NotifyObservers(this, "memory-pressure", aReason); - // we are going to do this manually to see who/what is - // deallocating. + // Instead of: + // os->NotifyObservers(this, "memory-pressure", aReason); + // we are going to do this manually to see who/what is + // deallocating. - nsCOMPtr e; - os->EnumerateObservers("memory-pressure", getter_AddRefs(e)); + nsCOMPtr e; + os->EnumerateObservers("memory-pressure", getter_AddRefs(e)); - if ( e ) { - nsCOMPtr observer; - bool loop = true; + if ( e ) { + nsCOMPtr observer; + bool loop = true; - while (NS_SUCCEEDED(e->HasMoreElements(&loop)) && loop) - { - nsCOMPtr supports; - e->GetNext(getter_AddRefs(supports)); + while (NS_SUCCEEDED(e->HasMoreElements(&loop)) && loop) + { + nsCOMPtr supports; + e->GetNext(getter_AddRefs(supports)); - if (!supports) - continue; + if (!supports) + continue; - observer = do_QueryInterface(supports); - observer->Observe(observer, "memory-pressure", aReason); - } - } + observer = do_QueryInterface(supports); + observer->Observe(observer, "memory-pressure", aReason); + } } + } - sIsFlushing = false; - return NS_OK; + sIsFlushing = false; + return NS_OK; } // XXX need NS_IMPL_STATIC_ADDREF/RELEASE @@ -180,8 +181,8 @@ NS_IMPL_QUERY_INTERFACE(nsMemoryImpl::FlushEvent, nsIRunnable) NS_IMETHODIMP nsMemoryImpl::FlushEvent::Run() { - sGlobalMemory.RunFlushers(mReason); - return NS_OK; + sGlobalMemory.RunFlushers(mReason); + return NS_OK; } mozilla::Atomic @@ -196,23 +197,23 @@ nsMemoryImpl::sFlushEvent; XPCOM_API(void*) NS_Alloc(size_t size) { - return moz_xmalloc(size); + return moz_xmalloc(size); } XPCOM_API(void*) NS_Realloc(void* ptr, size_t size) { - return moz_xrealloc(ptr, size); + return moz_xrealloc(ptr, size); } XPCOM_API(void) NS_Free(void* ptr) { - moz_free(ptr); + moz_free(ptr); } nsresult NS_GetMemoryManager(nsIMemory* *result) { - return sGlobalMemory.QueryInterface(NS_GET_IID(nsIMemory), (void**) result); + return sGlobalMemory.QueryInterface(NS_GET_IID(nsIMemory), (void**) result); } diff --git a/xpcom/base/nsMemoryImpl.h b/xpcom/base/nsMemoryImpl.h index e5cfce178b24..73f0b37658ca 100644 --- a/xpcom/base/nsMemoryImpl.h +++ b/xpcom/base/nsMemoryImpl.h @@ -1,4 +1,5 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ @@ -18,29 +19,29 @@ class nsMemoryImpl : public nsIMemory { public: - // We don't use the generic macros because we are a special static object - NS_IMETHOD QueryInterface(REFNSIID aIID, void** aResult); - NS_IMETHOD_(MozExternalRefCountType) AddRef(void) { return 1; } - NS_IMETHOD_(MozExternalRefCountType) Release(void) { return 1; } + // We don't use the generic macros because we are a special static object + NS_IMETHOD QueryInterface(REFNSIID aIID, void** aResult); + NS_IMETHOD_(MozExternalRefCountType) AddRef(void) { return 1; } + NS_IMETHOD_(MozExternalRefCountType) Release(void) { return 1; } - NS_DECL_NSIMEMORY + NS_DECL_NSIMEMORY - static nsresult Create(nsISupports* outer, - const nsIID& aIID, void **aResult); + static nsresult Create(nsISupports* outer, + const nsIID& aIID, void **aResult); - NS_HIDDEN_(nsresult) FlushMemory(const char16_t* aReason, bool aImmediate); - NS_HIDDEN_(nsresult) RunFlushers(const char16_t* aReason); + NS_HIDDEN_(nsresult) FlushMemory(const char16_t* aReason, bool aImmediate); + NS_HIDDEN_(nsresult) RunFlushers(const char16_t* aReason); protected: - struct FlushEvent : public nsIRunnable { - NS_DECL_ISUPPORTS_INHERITED - NS_DECL_NSIRUNNABLE - const char16_t* mReason; - }; + struct FlushEvent : public nsIRunnable { + NS_DECL_ISUPPORTS_INHERITED + NS_DECL_NSIRUNNABLE + const char16_t* mReason; + }; - static mozilla::Atomic sIsFlushing; - static FlushEvent sFlushEvent; - static PRIntervalTime sLastFlushTime; + static mozilla::Atomic sIsFlushing; + static FlushEvent sFlushEvent; + static PRIntervalTime sLastFlushTime; }; #endif // nsMemoryImpl_h__ diff --git a/xpcom/base/nsMemoryInfoDumper.cpp b/xpcom/base/nsMemoryInfoDumper.cpp index c725a3544a2e..c7c16d42353b 100644 --- a/xpcom/base/nsMemoryInfoDumper.cpp +++ b/xpcom/base/nsMemoryInfoDumper.cpp @@ -56,8 +56,8 @@ class DumpMemoryInfoToTempDirRunnable : public nsRunnable public: DumpMemoryInfoToTempDirRunnable(const nsAString& aIdentifier, bool aMinimizeMemoryUsage) - : mIdentifier(aIdentifier) - , mMinimizeMemoryUsage(aMinimizeMemoryUsage) + : mIdentifier(aIdentifier) + , mMinimizeMemoryUsage(aMinimizeMemoryUsage) {} NS_IMETHOD Run() @@ -152,9 +152,9 @@ void doGCCCDump(const uint8_t recvSig) // Dump GC and CC logs (from the main thread). nsRefPtr runnable = new GCAndCCLogDumpRunnable( - /* identifier = */ EmptyString(), - /* allTraces = */ true, - /* dumpChildProcesses = */ true); + /* identifier = */ EmptyString(), + /* allTraces = */ true, + /* dumpChildProcesses = */ true); NS_DispatchToMainThread(runnable); } @@ -180,8 +180,8 @@ void doGCCCDump(const nsCString& inputStr) LOG("FifoWatcher(command:%s) dispatching GC/CC log runnable.", inputStr.get()); nsRefPtr runnable = new GCAndCCLogDumpRunnable(/* identifier = */ EmptyString(), - doAllTracesGCCCDump, - /* dumpChildProcesses = */ true); + doAllTracesGCCCDump, + /* dumpChildProcesses = */ true); NS_DispatchToMainThread(runnable); } @@ -336,9 +336,9 @@ public: {} NS_IMETHOD Callback(const nsACString &aProcess, const nsACString &aPath, - int32_t aKind, int32_t aUnits, int64_t aAmount, - const nsACString &aDescription, - nsISupports *aData) + int32_t aKind, int32_t aUnits, int64_t aAmount, + const nsACString &aDescription, + nsISupports *aData) { if (mIsFirst) { DUMP(mWriter, "["); diff --git a/xpcom/base/nsMemoryReporterManager.cpp b/xpcom/base/nsMemoryReporterManager.cpp index 8650b26fb95f..160ace6d0f16 100644 --- a/xpcom/base/nsMemoryReporterManager.cpp +++ b/xpcom/base/nsMemoryReporterManager.cpp @@ -799,15 +799,15 @@ public: dmd::SizeOf(&sizes); #define REPORT(_path, _amount, _desc) \ - do { \ - nsresult rv; \ - rv = aHandleReport->Callback(EmptyCString(), NS_LITERAL_CSTRING(_path), \ - KIND_HEAP, UNITS_BYTES, _amount, \ - NS_LITERAL_CSTRING(_desc), aData); \ - if (NS_WARN_IF(NS_FAILED(rv))) { \ - return rv; \ - } \ - } while (0) + do { \ + nsresult rv; \ + rv = aHandleReport->Callback(EmptyCString(), NS_LITERAL_CSTRING(_path), \ + KIND_HEAP, UNITS_BYTES, _amount, \ + NS_LITERAL_CSTRING(_desc), aData); \ + if (NS_WARN_IF(NS_FAILED(rv))) { \ + return rv; \ + } \ + } while (0) REPORT("explicit/dmd/stack-traces/used", sizes.mStackTracesUsed, @@ -1513,11 +1513,11 @@ nsMemoryReporterManager::GetResidentFast(int64_t* aAmount) int64_t nsMemoryReporterManager::ResidentFast() { #ifdef HAVE_VSIZE_AND_RESIDENT_REPORTERS - int64_t amount; - ResidentFastDistinguishedAmount(&amount); - return amount; + int64_t amount; + ResidentFastDistinguishedAmount(&amount); + return amount; #else - return 0; + return 0; #endif } @@ -1744,14 +1744,14 @@ nsMemoryReporterManager::SizeOfTab(nsIDOMWindow* aTopWindow, TimeStamp t3 = TimeStamp::Now(); *aTotalSize = 0; - #define DO(aN, n) { *aN = (n); *aTotalSize += (n); } +#define DO(aN, n) { *aN = (n); *aTotalSize += (n); } DO(aJSObjectsSize, jsObjectsSize); DO(aJSStringsSize, jsStringsSize); DO(aJSOtherSize, jsOtherSize); DO(aDomSize, jsPrivateSize + domSize); DO(aStyleSize, styleSize); DO(aOtherSize, otherSize); - #undef DO +#undef DO *aJSMilliseconds = (t2 - t1).ToMilliseconds(); *aNonJSMilliseconds = (t3 - t2).ToMilliseconds(); diff --git a/xpcom/base/nsObjCExceptions.h b/xpcom/base/nsObjCExceptions.h index de624fdfb70d..e6ed1b673b3c 100644 --- a/xpcom/base/nsObjCExceptions.h +++ b/xpcom/base/nsObjCExceptions.h @@ -1,4 +1,5 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ diff --git a/xpcom/base/nsSecurityConsoleMessage.h b/xpcom/base/nsSecurityConsoleMessage.h index 1b8c03165e28..6edc492aea40 100644 --- a/xpcom/base/nsSecurityConsoleMessage.h +++ b/xpcom/base/nsSecurityConsoleMessage.h @@ -1,3 +1,5 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ @@ -9,18 +11,18 @@ class nsSecurityConsoleMessage MOZ_FINAL : public nsISecurityConsoleMessage { - public: - NS_DECL_ISUPPORTS - NS_DECL_NSISECURITYCONSOLEMESSAGE +public: + NS_DECL_ISUPPORTS + NS_DECL_NSISECURITYCONSOLEMESSAGE - nsSecurityConsoleMessage(); + nsSecurityConsoleMessage(); - private: - ~nsSecurityConsoleMessage(); +private: + ~nsSecurityConsoleMessage(); - protected: - nsString mTag; - nsString mCategory; +protected: + nsString mTag; + nsString mCategory; }; #define NS_SECURITY_CONSOLE_MESSAGE_CID \ diff --git a/xpcom/base/nsStackWalk.cpp b/xpcom/base/nsStackWalk.cpp index 48cb41053ba0..68789aeb2e4e 100644 --- a/xpcom/base/nsStackWalk.cpp +++ b/xpcom/base/nsStackWalk.cpp @@ -1,5 +1,5 @@ -/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- - * vim: set shiftwidth=4 tabstop=8 autoindent cindent expandtab: */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ @@ -34,17 +34,17 @@ static CriticalAddress gCriticalAddress; #endif #define NSSTACKWALK_SUPPORTS_MACOSX \ - (defined(XP_MACOSX) && \ - (defined(__i386) || defined(__ppc__) || defined(HAVE__UNWIND_BACKTRACE))) + (defined(XP_MACOSX) && \ + (defined(__i386) || defined(__ppc__) || defined(HAVE__UNWIND_BACKTRACE))) #define NSSTACKWALK_SUPPORTS_LINUX \ - (defined(linux) && \ - ((defined(__GNUC__) && (defined(__i386) || defined(PPC))) || \ - defined(HAVE__UNWIND_BACKTRACE))) + (defined(linux) && \ + ((defined(__GNUC__) && (defined(__i386) || defined(PPC))) || \ + defined(HAVE__UNWIND_BACKTRACE))) #define NSSTACKWALK_SUPPORTS_SOLARIS \ - (defined(__sun) && \ - (defined(__sparc) || defined(sparc) || defined(__i386) || defined(i386))) + (defined(__sun) && \ + (defined(__sparc) || defined(sparc) || defined(__i386) || defined(i386))) #if NSSTACKWALK_SUPPORTS_MACOSX #include @@ -202,7 +202,7 @@ StackWalkInitCriticalAddress() // extern "C" { -extern HANDLE hStackWalkMutex; +extern HANDLE hStackWalkMutex; bool EnsureSymInitialized(); @@ -238,244 +238,244 @@ CRITICAL_SECTION gDbgHelpCS; // Routine to print an error message to standard error. void PrintError(const char *prefix) { - LPVOID lpMsgBuf; - DWORD lastErr = GetLastError(); - FormatMessageA( - FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, - nullptr, - lastErr, - MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language - (LPSTR) &lpMsgBuf, - 0, - nullptr - ); - fprintf(stderr, "### ERROR: %s: %s", - prefix, lpMsgBuf ? lpMsgBuf : "(null)\n"); - fflush(stderr); - LocalFree(lpMsgBuf); + LPVOID lpMsgBuf; + DWORD lastErr = GetLastError(); + FormatMessageA( + FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, + nullptr, + lastErr, + MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language + (LPSTR) &lpMsgBuf, + 0, + nullptr + ); + fprintf(stderr, "### ERROR: %s: %s", + prefix, lpMsgBuf ? lpMsgBuf : "(null)\n"); + fflush(stderr); + LocalFree(lpMsgBuf); } bool EnsureWalkThreadReady() { - static bool walkThreadReady = false; - static HANDLE stackWalkThread = nullptr; - static HANDLE readyEvent = nullptr; + static bool walkThreadReady = false; + static HANDLE stackWalkThread = nullptr; + static HANDLE readyEvent = nullptr; - if (walkThreadReady) - return walkThreadReady; + if (walkThreadReady) + return walkThreadReady; + if (stackWalkThread == nullptr) { + readyEvent = ::CreateEvent(nullptr, FALSE /* auto-reset*/, + FALSE /* initially non-signaled */, + nullptr); + if (readyEvent == nullptr) { + PrintError("CreateEvent"); + return false; + } + + unsigned int threadID; + stackWalkThread = (HANDLE) + _beginthreadex(nullptr, 0, WalkStackThread, (void*)readyEvent, + 0, &threadID); if (stackWalkThread == nullptr) { - readyEvent = ::CreateEvent(nullptr, FALSE /* auto-reset*/, - FALSE /* initially non-signaled */, - nullptr); - if (readyEvent == nullptr) { - PrintError("CreateEvent"); - return false; - } - - unsigned int threadID; - stackWalkThread = (HANDLE) - _beginthreadex(nullptr, 0, WalkStackThread, (void*)readyEvent, - 0, &threadID); - if (stackWalkThread == nullptr) { - PrintError("CreateThread"); - ::CloseHandle(readyEvent); - readyEvent = nullptr; - return false; - } - gStackWalkThread = threadID; - ::CloseHandle(stackWalkThread); + PrintError("CreateThread"); + ::CloseHandle(readyEvent); + readyEvent = nullptr; + return false; } + gStackWalkThread = threadID; + ::CloseHandle(stackWalkThread); + } - MOZ_ASSERT((stackWalkThread != nullptr && readyEvent != nullptr) || - (stackWalkThread == nullptr && readyEvent == nullptr)); + MOZ_ASSERT((stackWalkThread != nullptr && readyEvent != nullptr) || + (stackWalkThread == nullptr && readyEvent == nullptr)); - // The thread was created. Try to wait an arbitrary amount of time (1 second - // should be enough) for its event loop to start before posting events to it. - DWORD waitRet = ::WaitForSingleObject(readyEvent, 1000); - if (waitRet == WAIT_TIMEOUT) { - // We get a timeout if we're called during static initialization because - // the thread will only start executing after we return so it couldn't - // have signalled the event. If that is the case, give up for now and - // try again next time we're called. - return false; - } - ::CloseHandle(readyEvent); - stackWalkThread = nullptr; - readyEvent = nullptr; + // The thread was created. Try to wait an arbitrary amount of time (1 second + // should be enough) for its event loop to start before posting events to it. + DWORD waitRet = ::WaitForSingleObject(readyEvent, 1000); + if (waitRet == WAIT_TIMEOUT) { + // We get a timeout if we're called during static initialization because + // the thread will only start executing after we return so it couldn't + // have signalled the event. If that is the case, give up for now and + // try again next time we're called. + return false; + } + ::CloseHandle(readyEvent); + stackWalkThread = nullptr; + readyEvent = nullptr; - ::InitializeCriticalSection(&gDbgHelpCS); + ::InitializeCriticalSection(&gDbgHelpCS); - return walkThreadReady = true; + return walkThreadReady = true; } void WalkStackMain64(struct WalkStackData* data) { - // Get the context information for the thread. That way we will - // know where our sp, fp, pc, etc. are and can fill in the - // STACKFRAME64 with the initial values. - CONTEXT context; - HANDLE myProcess = data->process; - HANDLE myThread = data->thread; - DWORD64 addr; - DWORD64 spaddr; - STACKFRAME64 frame64; - // skip our own stack walking frames - int skip = (data->walkCallingThread ? 3 : 0) + data->skipFrames; - BOOL ok; + // Get the context information for the thread. That way we will + // know where our sp, fp, pc, etc. are and can fill in the + // STACKFRAME64 with the initial values. + CONTEXT context; + HANDLE myProcess = data->process; + HANDLE myThread = data->thread; + DWORD64 addr; + DWORD64 spaddr; + STACKFRAME64 frame64; + // skip our own stack walking frames + int skip = (data->walkCallingThread ? 3 : 0) + data->skipFrames; + BOOL ok; - // Get a context for the specified thread. - if (!data->platformData) { - memset(&context, 0, sizeof(CONTEXT)); - context.ContextFlags = CONTEXT_FULL; - if (!GetThreadContext(myThread, &context)) { - if (data->walkCallingThread) { - PrintError("GetThreadContext"); - } - return; - } - } else { - context = *static_cast(data->platformData); + // Get a context for the specified thread. + if (!data->platformData) { + memset(&context, 0, sizeof(CONTEXT)); + context.ContextFlags = CONTEXT_FULL; + if (!GetThreadContext(myThread, &context)) { + if (data->walkCallingThread) { + PrintError("GetThreadContext"); + } + return; } + } else { + context = *static_cast(data->platformData); + } - // Setup initial stack frame to walk from - memset(&frame64, 0, sizeof(frame64)); + // Setup initial stack frame to walk from + memset(&frame64, 0, sizeof(frame64)); #ifdef _M_IX86 - frame64.AddrPC.Offset = context.Eip; - frame64.AddrStack.Offset = context.Esp; - frame64.AddrFrame.Offset = context.Ebp; + frame64.AddrPC.Offset = context.Eip; + frame64.AddrStack.Offset = context.Esp; + frame64.AddrFrame.Offset = context.Ebp; #elif defined _M_AMD64 - frame64.AddrPC.Offset = context.Rip; - frame64.AddrStack.Offset = context.Rsp; - frame64.AddrFrame.Offset = context.Rbp; + frame64.AddrPC.Offset = context.Rip; + frame64.AddrStack.Offset = context.Rsp; + frame64.AddrFrame.Offset = context.Rbp; #elif defined _M_IA64 - frame64.AddrPC.Offset = context.StIIP; - frame64.AddrStack.Offset = context.SP; - frame64.AddrFrame.Offset = context.RsBSP; + frame64.AddrPC.Offset = context.StIIP; + frame64.AddrStack.Offset = context.SP; + frame64.AddrFrame.Offset = context.RsBSP; #else #error "Should not have compiled this code" #endif - frame64.AddrPC.Mode = AddrModeFlat; - frame64.AddrStack.Mode = AddrModeFlat; - frame64.AddrFrame.Mode = AddrModeFlat; - frame64.AddrReturn.Mode = AddrModeFlat; + frame64.AddrPC.Mode = AddrModeFlat; + frame64.AddrStack.Mode = AddrModeFlat; + frame64.AddrFrame.Mode = AddrModeFlat; + frame64.AddrReturn.Mode = AddrModeFlat; - // Now walk the stack - while (1) { + // Now walk the stack + while (1) { - // debug routines are not threadsafe, so grab the lock. - EnterCriticalSection(&gDbgHelpCS); - ok = StackWalk64( + // debug routines are not threadsafe, so grab the lock. + EnterCriticalSection(&gDbgHelpCS); + ok = StackWalk64( #ifdef _M_AMD64 - IMAGE_FILE_MACHINE_AMD64, + IMAGE_FILE_MACHINE_AMD64, #elif defined _M_IA64 - IMAGE_FILE_MACHINE_IA64, + IMAGE_FILE_MACHINE_IA64, #elif defined _M_IX86 - IMAGE_FILE_MACHINE_I386, + IMAGE_FILE_MACHINE_I386, #else #error "Should not have compiled this code" #endif - myProcess, - myThread, - &frame64, - &context, - nullptr, - SymFunctionTableAccess64, // function table access routine - SymGetModuleBase64, // module base routine - 0 - ); - LeaveCriticalSection(&gDbgHelpCS); + myProcess, + myThread, + &frame64, + &context, + nullptr, + SymFunctionTableAccess64, // function table access routine + SymGetModuleBase64, // module base routine + 0 + ); + LeaveCriticalSection(&gDbgHelpCS); - if (ok) { - addr = frame64.AddrPC.Offset; - spaddr = frame64.AddrStack.Offset; - } else { - addr = 0; - spaddr = 0; - if (data->walkCallingThread) { - PrintError("WalkStack64"); - } - } - - if (!ok || (addr == 0)) { - break; - } - - if (skip-- > 0) { - continue; - } - - if (data->pc_count < data->pc_size) - data->pcs[data->pc_count] = (void*)addr; - ++data->pc_count; - - if (data->sp_count < data->sp_size) - data->sps[data->sp_count] = (void*)spaddr; - ++data->sp_count; - - if (data->pc_max != 0 && data->pc_count == data->pc_max) - break; - - if (frame64.AddrReturn.Offset == 0) - break; + if (ok) { + addr = frame64.AddrPC.Offset; + spaddr = frame64.AddrStack.Offset; + } else { + addr = 0; + spaddr = 0; + if (data->walkCallingThread) { + PrintError("WalkStack64"); + } } - return; + + if (!ok || (addr == 0)) { + break; + } + + if (skip-- > 0) { + continue; + } + + if (data->pc_count < data->pc_size) + data->pcs[data->pc_count] = (void*)addr; + ++data->pc_count; + + if (data->sp_count < data->sp_size) + data->sps[data->sp_count] = (void*)spaddr; + ++data->sp_count; + + if (data->pc_max != 0 && data->pc_count == data->pc_max) + break; + + if (frame64.AddrReturn.Offset == 0) + break; + } + return; } unsigned int WINAPI WalkStackThread(void* aData) { - BOOL msgRet; - MSG msg; + BOOL msgRet; + MSG msg; - // Call PeekMessage to force creation of a message queue so that - // other threads can safely post events to us. - ::PeekMessage(&msg, nullptr, WM_USER, WM_USER, PM_NOREMOVE); + // Call PeekMessage to force creation of a message queue so that + // other threads can safely post events to us. + ::PeekMessage(&msg, nullptr, WM_USER, WM_USER, PM_NOREMOVE); - // and tell the thread that created us that we're ready. - HANDLE readyEvent = (HANDLE)aData; - ::SetEvent(readyEvent); + // and tell the thread that created us that we're ready. + HANDLE readyEvent = (HANDLE)aData; + ::SetEvent(readyEvent); - while ((msgRet = ::GetMessage(&msg, (HWND)-1, 0, 0)) != 0) { - if (msgRet == -1) { - PrintError("GetMessage"); - } else { - DWORD ret; + while ((msgRet = ::GetMessage(&msg, (HWND)-1, 0, 0)) != 0) { + if (msgRet == -1) { + PrintError("GetMessage"); + } else { + DWORD ret; - struct WalkStackData *data = (WalkStackData *)msg.lParam; - if (!data) - continue; + struct WalkStackData *data = (WalkStackData *)msg.lParam; + if (!data) + continue; - // Don't suspend the calling thread until it's waiting for - // us; otherwise the number of frames on the stack could vary. - ret = ::WaitForSingleObject(data->eventStart, INFINITE); - if (ret != WAIT_OBJECT_0) - PrintError("WaitForSingleObject"); + // Don't suspend the calling thread until it's waiting for + // us; otherwise the number of frames on the stack could vary. + ret = ::WaitForSingleObject(data->eventStart, INFINITE); + if (ret != WAIT_OBJECT_0) + PrintError("WaitForSingleObject"); - // Suspend the calling thread, dump his stack, and then resume him. - // He's currently waiting for us to finish so now should be a good time. - ret = ::SuspendThread( data->thread ); - if (ret == -1) { - PrintError("ThreadSuspend"); - } - else { - WalkStackMain64(data); + // Suspend the calling thread, dump his stack, and then resume him. + // He's currently waiting for us to finish so now should be a good time. + ret = ::SuspendThread( data->thread ); + if (ret == -1) { + PrintError("ThreadSuspend"); + } + else { + WalkStackMain64(data); - ret = ::ResumeThread(data->thread); - if (ret == -1) { - PrintError("ThreadResume"); - } - } - - ::SetEvent(data->eventEnd); + ret = ::ResumeThread(data->thread); + if (ret == -1) { + PrintError("ThreadResume"); } - } + } - return 0; + ::SetEvent(data->eventEnd); + } + } + + return 0; } /** @@ -491,116 +491,116 @@ NS_StackWalk(NS_WalkStackCallback aCallback, uint32_t aSkipFrames, uint32_t aMaxFrames, void *aClosure, uintptr_t aThread, void *aPlatformData) { - StackWalkInitCriticalAddress(); - static HANDLE myProcess = nullptr; - HANDLE myThread; - DWORD walkerReturn; - struct WalkStackData data; + StackWalkInitCriticalAddress(); + static HANDLE myProcess = nullptr; + HANDLE myThread; + DWORD walkerReturn; + struct WalkStackData data; - if (!EnsureWalkThreadReady()) - return NS_ERROR_FAILURE; + if (!EnsureWalkThreadReady()) + return NS_ERROR_FAILURE; - HANDLE targetThread = ::GetCurrentThread(); - data.walkCallingThread = true; - if (aThread) { - HANDLE threadToWalk = reinterpret_cast (aThread); - // walkCallingThread indicates whether we are walking the caller's stack - data.walkCallingThread = (threadToWalk == targetThread); - targetThread = threadToWalk; - } + HANDLE targetThread = ::GetCurrentThread(); + data.walkCallingThread = true; + if (aThread) { + HANDLE threadToWalk = reinterpret_cast (aThread); + // walkCallingThread indicates whether we are walking the caller's stack + data.walkCallingThread = (threadToWalk == targetThread); + targetThread = threadToWalk; + } - // We need to avoid calling fprintf and friends if we're walking the stack of - // another thread, in order to avoid deadlocks. - const bool shouldBeThreadSafe = !!aThread; + // We need to avoid calling fprintf and friends if we're walking the stack of + // another thread, in order to avoid deadlocks. + const bool shouldBeThreadSafe = !!aThread; - // Have to duplicate handle to get a real handle. - if (!myProcess) { - if (!::DuplicateHandle(::GetCurrentProcess(), - ::GetCurrentProcess(), - ::GetCurrentProcess(), - &myProcess, - PROCESS_ALL_ACCESS, FALSE, 0)) { - if (!shouldBeThreadSafe) { - PrintError("DuplicateHandle (process)"); - } - return NS_ERROR_FAILURE; - } - } + // Have to duplicate handle to get a real handle. + if (!myProcess) { if (!::DuplicateHandle(::GetCurrentProcess(), - targetThread, ::GetCurrentProcess(), - &myThread, - THREAD_ALL_ACCESS, FALSE, 0)) { - if (!shouldBeThreadSafe) { - PrintError("DuplicateHandle (thread)"); - } - return NS_ERROR_FAILURE; + ::GetCurrentProcess(), + &myProcess, + PROCESS_ALL_ACCESS, FALSE, 0)) { + if (!shouldBeThreadSafe) { + PrintError("DuplicateHandle (process)"); + } + return NS_ERROR_FAILURE; + } + } + if (!::DuplicateHandle(::GetCurrentProcess(), + targetThread, + ::GetCurrentProcess(), + &myThread, + THREAD_ALL_ACCESS, FALSE, 0)) { + if (!shouldBeThreadSafe) { + PrintError("DuplicateHandle (thread)"); + } + return NS_ERROR_FAILURE; + } + + data.skipFrames = aSkipFrames; + data.thread = myThread; + data.process = myProcess; + void *local_pcs[1024]; + data.pcs = local_pcs; + data.pc_count = 0; + data.pc_size = ArrayLength(local_pcs); + data.pc_max = aMaxFrames; + void *local_sps[1024]; + data.sps = local_sps; + data.sp_count = 0; + data.sp_size = ArrayLength(local_sps); + data.platformData = aPlatformData; + + if (aThread) { + // If we're walking the stack of another thread, we don't need to + // use a separate walker thread. + WalkStackMain64(&data); + + if (data.pc_count > data.pc_size) { + data.pcs = (void**) _alloca(data.pc_count * sizeof(void*)); + data.pc_size = data.pc_count; + data.pc_count = 0; + data.sps = (void**) _alloca(data.sp_count * sizeof(void*)); + data.sp_size = data.sp_count; + data.sp_count = 0; + WalkStackMain64(&data); + } + } else { + data.eventStart = ::CreateEvent(nullptr, FALSE /* auto-reset*/, + FALSE /* initially non-signaled */, nullptr); + data.eventEnd = ::CreateEvent(nullptr, FALSE /* auto-reset*/, + FALSE /* initially non-signaled */, nullptr); + + ::PostThreadMessage(gStackWalkThread, WM_USER, 0, (LPARAM)&data); + + walkerReturn = ::SignalObjectAndWait(data.eventStart, + data.eventEnd, INFINITE, FALSE); + if (walkerReturn != WAIT_OBJECT_0 && !shouldBeThreadSafe) + PrintError("SignalObjectAndWait (1)"); + if (data.pc_count > data.pc_size) { + data.pcs = (void**) _alloca(data.pc_count * sizeof(void*)); + data.pc_size = data.pc_count; + data.pc_count = 0; + data.sps = (void**) _alloca(data.sp_count * sizeof(void*)); + data.sp_size = data.sp_count; + data.sp_count = 0; + ::PostThreadMessage(gStackWalkThread, WM_USER, 0, (LPARAM)&data); + walkerReturn = ::SignalObjectAndWait(data.eventStart, + data.eventEnd, INFINITE, FALSE); + if (walkerReturn != WAIT_OBJECT_0 && !shouldBeThreadSafe) + PrintError("SignalObjectAndWait (2)"); } - data.skipFrames = aSkipFrames; - data.thread = myThread; - data.process = myProcess; - void *local_pcs[1024]; - data.pcs = local_pcs; - data.pc_count = 0; - data.pc_size = ArrayLength(local_pcs); - data.pc_max = aMaxFrames; - void *local_sps[1024]; - data.sps = local_sps; - data.sp_count = 0; - data.sp_size = ArrayLength(local_sps); - data.platformData = aPlatformData; + ::CloseHandle(data.eventStart); + ::CloseHandle(data.eventEnd); + } - if (aThread) { - // If we're walking the stack of another thread, we don't need to - // use a separate walker thread. - WalkStackMain64(&data); + ::CloseHandle(myThread); - if (data.pc_count > data.pc_size) { - data.pcs = (void**) _alloca(data.pc_count * sizeof(void*)); - data.pc_size = data.pc_count; - data.pc_count = 0; - data.sps = (void**) _alloca(data.sp_count * sizeof(void*)); - data.sp_size = data.sp_count; - data.sp_count = 0; - WalkStackMain64(&data); - } - } else { - data.eventStart = ::CreateEvent(nullptr, FALSE /* auto-reset*/, - FALSE /* initially non-signaled */, nullptr); - data.eventEnd = ::CreateEvent(nullptr, FALSE /* auto-reset*/, - FALSE /* initially non-signaled */, nullptr); + for (uint32_t i = 0; i < data.pc_count; ++i) + (*aCallback)(data.pcs[i], data.sps[i], aClosure); - ::PostThreadMessage(gStackWalkThread, WM_USER, 0, (LPARAM)&data); - - walkerReturn = ::SignalObjectAndWait(data.eventStart, - data.eventEnd, INFINITE, FALSE); - if (walkerReturn != WAIT_OBJECT_0 && !shouldBeThreadSafe) - PrintError("SignalObjectAndWait (1)"); - if (data.pc_count > data.pc_size) { - data.pcs = (void**) _alloca(data.pc_count * sizeof(void*)); - data.pc_size = data.pc_count; - data.pc_count = 0; - data.sps = (void**) _alloca(data.sp_count * sizeof(void*)); - data.sp_size = data.sp_count; - data.sp_count = 0; - ::PostThreadMessage(gStackWalkThread, WM_USER, 0, (LPARAM)&data); - walkerReturn = ::SignalObjectAndWait(data.eventStart, - data.eventEnd, INFINITE, FALSE); - if (walkerReturn != WAIT_OBJECT_0 && !shouldBeThreadSafe) - PrintError("SignalObjectAndWait (2)"); - } - - ::CloseHandle(data.eventStart); - ::CloseHandle(data.eventEnd); - } - - ::CloseHandle(myThread); - - for (uint32_t i = 0; i < data.pc_count; ++i) - (*aCallback)(data.pcs[i], data.sps[i], aClosure); - - return data.pc_count == 0 ? NS_ERROR_FAILURE : NS_OK; + return data.pc_count == 0 ? NS_ERROR_FAILURE : NS_OK; } @@ -610,31 +610,31 @@ static BOOL CALLBACK callbackEspecial64( ULONG aModuleSize, PVOID aUserContext) { - BOOL retval = TRUE; - DWORD64 addr = *(DWORD64*)aUserContext; + BOOL retval = TRUE; + DWORD64 addr = *(DWORD64*)aUserContext; - /* - * You'll want to control this if we are running on an - * architecture where the addresses go the other direction. - * Not sure this is even a realistic consideration. - */ - const BOOL addressIncreases = TRUE; + /* + * You'll want to control this if we are running on an + * architecture where the addresses go the other direction. + * Not sure this is even a realistic consideration. + */ + const BOOL addressIncreases = TRUE; - /* - * If it falls in side the known range, load the symbols. - */ - if (addressIncreases - ? (addr >= aModuleBase && addr <= (aModuleBase + aModuleSize)) - : (addr <= aModuleBase && addr >= (aModuleBase - aModuleSize)) - ) { - retval = !!SymLoadModule64(GetCurrentProcess(), nullptr, - (PSTR)aModuleName, nullptr, - aModuleBase, aModuleSize); - if (!retval) - PrintError("SymLoadModule64"); - } + /* + * If it falls in side the known range, load the symbols. + */ + if (addressIncreases + ? (addr >= aModuleBase && addr <= (aModuleBase + aModuleSize)) + : (addr <= aModuleBase && addr >= (aModuleBase - aModuleSize)) + ) { + retval = !!SymLoadModule64(GetCurrentProcess(), nullptr, + (PSTR)aModuleName, nullptr, + aModuleBase, aModuleSize); + if (!retval) + PrintError("SymLoadModule64"); + } - return retval; + return retval; } /* @@ -664,176 +664,176 @@ static BOOL CALLBACK callbackEspecial64( BOOL SymGetModuleInfoEspecial64(HANDLE aProcess, DWORD64 aAddr, PIMAGEHLP_MODULE64 aModuleInfo, PIMAGEHLP_LINE64 aLineInfo) { - BOOL retval = FALSE; + BOOL retval = FALSE; + + /* + * Init the vars if we have em. + */ + aModuleInfo->SizeOfStruct = NS_IMAGEHLP_MODULE64_SIZE; + if (nullptr != aLineInfo) { + aLineInfo->SizeOfStruct = sizeof(IMAGEHLP_LINE64); + } + + /* + * Give it a go. + * It may already be loaded. + */ + retval = SymGetModuleInfo64(aProcess, aAddr, aModuleInfo); + + if (FALSE == retval) { + BOOL enumRes = FALSE; /* - * Init the vars if we have em. + * Not loaded, here's the magic. + * Go through all the modules. */ - aModuleInfo->SizeOfStruct = NS_IMAGEHLP_MODULE64_SIZE; - if (nullptr != aLineInfo) { - aLineInfo->SizeOfStruct = sizeof(IMAGEHLP_LINE64); + // Need to cast to PENUMLOADED_MODULES_CALLBACK64 because the + // constness of the first parameter of + // PENUMLOADED_MODULES_CALLBACK64 varies over SDK versions (from + // non-const to const over time). See bug 391848 and bug + // 415426. + enumRes = EnumerateLoadedModules64(aProcess, (PENUMLOADED_MODULES_CALLBACK64)callbackEspecial64, (PVOID)&aAddr); + if (FALSE != enumRes) + { + /* + * One final go. + * If it fails, then well, we have other problems. + */ + retval = SymGetModuleInfo64(aProcess, aAddr, aModuleInfo); } + } - /* - * Give it a go. - * It may already be loaded. - */ - retval = SymGetModuleInfo64(aProcess, aAddr, aModuleInfo); - - if (FALSE == retval) { - BOOL enumRes = FALSE; - - /* - * Not loaded, here's the magic. - * Go through all the modules. - */ - // Need to cast to PENUMLOADED_MODULES_CALLBACK64 because the - // constness of the first parameter of - // PENUMLOADED_MODULES_CALLBACK64 varies over SDK versions (from - // non-const to const over time). See bug 391848 and bug - // 415426. - enumRes = EnumerateLoadedModules64(aProcess, (PENUMLOADED_MODULES_CALLBACK64)callbackEspecial64, (PVOID)&aAddr); - if (FALSE != enumRes) - { - /* - * One final go. - * If it fails, then well, we have other problems. - */ - retval = SymGetModuleInfo64(aProcess, aAddr, aModuleInfo); - } + /* + * If we got module info, we may attempt line info as well. + * We will not report failure if this does not work. + */ + if (FALSE != retval && nullptr != aLineInfo) { + DWORD displacement = 0; + BOOL lineRes = FALSE; + lineRes = SymGetLineFromAddr64(aProcess, aAddr, &displacement, aLineInfo); + if (!lineRes) { + // Clear out aLineInfo to indicate that it's not valid + memset(aLineInfo, 0, sizeof(*aLineInfo)); } + } - /* - * If we got module info, we may attempt line info as well. - * We will not report failure if this does not work. - */ - if (FALSE != retval && nullptr != aLineInfo) { - DWORD displacement = 0; - BOOL lineRes = FALSE; - lineRes = SymGetLineFromAddr64(aProcess, aAddr, &displacement, aLineInfo); - if (!lineRes) { - // Clear out aLineInfo to indicate that it's not valid - memset(aLineInfo, 0, sizeof(*aLineInfo)); - } - } - - return retval; + return retval; } bool EnsureSymInitialized() { - static bool gInitialized = false; - bool retStat; + static bool gInitialized = false; + bool retStat; - if (gInitialized) - return gInitialized; + if (gInitialized) + return gInitialized; - if (!EnsureWalkThreadReady()) - return false; + if (!EnsureWalkThreadReady()) + return false; - SymSetOptions(SYMOPT_LOAD_LINES | SYMOPT_UNDNAME); - retStat = SymInitialize(GetCurrentProcess(), nullptr, TRUE); - if (!retStat) - PrintError("SymInitialize"); + SymSetOptions(SYMOPT_LOAD_LINES | SYMOPT_UNDNAME); + retStat = SymInitialize(GetCurrentProcess(), nullptr, TRUE); + if (!retStat) + PrintError("SymInitialize"); - gInitialized = retStat; - /* XXX At some point we need to arrange to call SymCleanup */ + gInitialized = retStat; + /* XXX At some point we need to arrange to call SymCleanup */ - return retStat; + return retStat; } EXPORT_XPCOM_API(nsresult) NS_DescribeCodeAddress(void *aPC, nsCodeAddressDetails *aDetails) { - aDetails->library[0] = '\0'; - aDetails->loffset = 0; - aDetails->filename[0] = '\0'; - aDetails->lineno = 0; - aDetails->function[0] = '\0'; - aDetails->foffset = 0; + aDetails->library[0] = '\0'; + aDetails->loffset = 0; + aDetails->filename[0] = '\0'; + aDetails->lineno = 0; + aDetails->function[0] = '\0'; + aDetails->foffset = 0; - if (!EnsureSymInitialized()) - return NS_ERROR_FAILURE; + if (!EnsureSymInitialized()) + return NS_ERROR_FAILURE; - HANDLE myProcess = ::GetCurrentProcess(); - BOOL ok; + HANDLE myProcess = ::GetCurrentProcess(); + BOOL ok; - // debug routines are not threadsafe, so grab the lock. - EnterCriticalSection(&gDbgHelpCS); + // debug routines are not threadsafe, so grab the lock. + EnterCriticalSection(&gDbgHelpCS); - // - // Attempt to load module info before we attempt to resolve the symbol. - // This just makes sure we get good info if available. - // + // + // Attempt to load module info before we attempt to resolve the symbol. + // This just makes sure we get good info if available. + // - DWORD64 addr = (DWORD64)aPC; - IMAGEHLP_MODULE64 modInfo; - IMAGEHLP_LINE64 lineInfo; - BOOL modInfoRes; - modInfoRes = SymGetModuleInfoEspecial64(myProcess, addr, &modInfo, &lineInfo); + DWORD64 addr = (DWORD64)aPC; + IMAGEHLP_MODULE64 modInfo; + IMAGEHLP_LINE64 lineInfo; + BOOL modInfoRes; + modInfoRes = SymGetModuleInfoEspecial64(myProcess, addr, &modInfo, &lineInfo); - if (modInfoRes) { - PL_strncpyz(aDetails->library, modInfo.ModuleName, - sizeof(aDetails->library)); - aDetails->loffset = (char*) aPC - (char*) modInfo.BaseOfImage; - - if (lineInfo.FileName) { - PL_strncpyz(aDetails->filename, lineInfo.FileName, - sizeof(aDetails->filename)); - aDetails->lineno = lineInfo.LineNumber; - } + if (modInfoRes) { + PL_strncpyz(aDetails->library, modInfo.ModuleName, + sizeof(aDetails->library)); + aDetails->loffset = (char*) aPC - (char*) modInfo.BaseOfImage; + + if (lineInfo.FileName) { + PL_strncpyz(aDetails->filename, lineInfo.FileName, + sizeof(aDetails->filename)); + aDetails->lineno = lineInfo.LineNumber; } + } - ULONG64 buffer[(sizeof(SYMBOL_INFO) + - MAX_SYM_NAME*sizeof(TCHAR) + sizeof(ULONG64) - 1) / sizeof(ULONG64)]; - PSYMBOL_INFO pSymbol = (PSYMBOL_INFO)buffer; - pSymbol->SizeOfStruct = sizeof(SYMBOL_INFO); - pSymbol->MaxNameLen = MAX_SYM_NAME; + ULONG64 buffer[(sizeof(SYMBOL_INFO) + + MAX_SYM_NAME*sizeof(TCHAR) + sizeof(ULONG64) - 1) / sizeof(ULONG64)]; + PSYMBOL_INFO pSymbol = (PSYMBOL_INFO)buffer; + pSymbol->SizeOfStruct = sizeof(SYMBOL_INFO); + pSymbol->MaxNameLen = MAX_SYM_NAME; - DWORD64 displacement; - ok = SymFromAddr(myProcess, addr, &displacement, pSymbol); + DWORD64 displacement; + ok = SymFromAddr(myProcess, addr, &displacement, pSymbol); - if (ok) { - PL_strncpyz(aDetails->function, pSymbol->Name, - sizeof(aDetails->function)); - aDetails->foffset = static_cast(displacement); - } + if (ok) { + PL_strncpyz(aDetails->function, pSymbol->Name, + sizeof(aDetails->function)); + aDetails->foffset = static_cast(displacement); + } - LeaveCriticalSection(&gDbgHelpCS); // release our lock - return NS_OK; + LeaveCriticalSection(&gDbgHelpCS); // release our lock + return NS_OK; } EXPORT_XPCOM_API(nsresult) NS_FormatCodeAddressDetails(void *aPC, const nsCodeAddressDetails *aDetails, char *aBuffer, uint32_t aBufferSize) { - if (aDetails->function[0]) { - _snprintf(aBuffer, aBufferSize, "%s+0x%08lX [%s +0x%016lX]", - aDetails->function, aDetails->foffset, - aDetails->library, aDetails->loffset); - } else if (aDetails->library[0]) { - _snprintf(aBuffer, aBufferSize, "UNKNOWN [%s +0x%016lX]", - aDetails->library, aDetails->loffset); - } else { - _snprintf(aBuffer, aBufferSize, "UNKNOWN 0x%016lX", aPC); - } + if (aDetails->function[0]) { + _snprintf(aBuffer, aBufferSize, "%s+0x%08lX [%s +0x%016lX]", + aDetails->function, aDetails->foffset, + aDetails->library, aDetails->loffset); + } else if (aDetails->library[0]) { + _snprintf(aBuffer, aBufferSize, "UNKNOWN [%s +0x%016lX]", + aDetails->library, aDetails->loffset); + } else { + _snprintf(aBuffer, aBufferSize, "UNKNOWN 0x%016lX", aPC); + } - aBuffer[aBufferSize - 1] = '\0'; + aBuffer[aBufferSize - 1] = '\0'; - uint32_t len = strlen(aBuffer); - if (aDetails->filename[0]) { - _snprintf(aBuffer + len, aBufferSize - len, " (%s, line %d)\n", - aDetails->filename, aDetails->lineno); - } else { - aBuffer[len] = '\n'; - if (++len != aBufferSize) - aBuffer[len] = '\0'; - } - aBuffer[aBufferSize - 2] = '\n'; - aBuffer[aBufferSize - 1] = '\0'; - return NS_OK; + uint32_t len = strlen(aBuffer); + if (aDetails->filename[0]) { + _snprintf(aBuffer + len, aBufferSize - len, " (%s, line %d)\n", + aDetails->filename, aDetails->lineno); + } else { + aBuffer[len] = '\n'; + if (++len != aBufferSize) + aBuffer[len] = '\0'; + } + aBuffer[aBufferSize - 2] = '\n'; + aBuffer[aBufferSize - 1] = '\0'; + return NS_OK; } // WIN32 x86 stack walking code @@ -860,21 +860,21 @@ NS_FormatCodeAddressDetails(void *aPC, const nsCodeAddressDetails *aDetails, #include #endif // MOZ_DEMANGLE_SYMBOLS -void DemangleSymbol(const char * aSymbol, +void DemangleSymbol(const char * aSymbol, char * aBuffer, int aBufLen) { - aBuffer[0] = '\0'; + aBuffer[0] = '\0'; #if defined(MOZ_DEMANGLE_SYMBOLS) - /* See demangle.h in the gcc source for the voodoo */ - char * demangled = abi::__cxa_demangle(aSymbol,0,0,0); + /* See demangle.h in the gcc source for the voodoo */ + char * demangled = abi::__cxa_demangle(aSymbol,0,0,0); - if (demangled) - { - PL_strncpyz(aBuffer,demangled,aBufLen); - free(demangled); - } + if (demangled) + { + PL_strncpyz(aBuffer,demangled,aBufLen); + free(demangled); + } #endif // MOZ_DEMANGLE_SYMBOLS } @@ -923,17 +923,17 @@ static int initialized = 0; #endif struct bucket { - void * pc; - int index; - struct bucket * next; + void * pc; + int index; + struct bucket * next; }; struct my_user_args { - NS_WalkStackCallback callback; - uint32_t skipFrames; - uint32_t maxFrames; - uint32_t numFrames; - void *closure; + NS_WalkStackCallback callback; + uint32_t skipFrames; + uint32_t maxFrames; + uint32_t numFrames; + void *closure; }; @@ -945,116 +945,116 @@ static void myinit() { - if (! initialized) { + if (! initialized) { #ifndef __GNUC__ - void *handle; - const char *libdem = "libdemangle.so.1"; + void *handle; + const char *libdem = "libdemangle.so.1"; - /* load libdemangle if we can and need to (only try this once) */ - if ((handle = dlopen(libdem, RTLD_LAZY)) != nullptr) { - demf = (demf_t *)dlsym(handle, - "cplus_demangle"); /*lint !e611 */ - /* - * lint override above is to prevent lint from - * complaining about "suspicious cast". - */ - } + /* load libdemangle if we can and need to (only try this once) */ + if ((handle = dlopen(libdem, RTLD_LAZY)) != nullptr) { + demf = (demf_t *)dlsym(handle, + "cplus_demangle"); /*lint !e611 */ + /* + * lint override above is to prevent lint from + * complaining about "suspicious cast". + */ + } #endif /*__GNUC__*/ - } - initialized = 1; + } + initialized = 1; } static int load_address(void * pc, void * arg) { - static struct bucket table[2048]; - static mutex_t lock; - struct bucket * ptr; - struct my_user_args * args = (struct my_user_args *) arg; + static struct bucket table[2048]; + static mutex_t lock; + struct bucket * ptr; + struct my_user_args * args = (struct my_user_args *) arg; - unsigned int val = NS_PTR_TO_INT32(pc); + unsigned int val = NS_PTR_TO_INT32(pc); - ptr = table + ((val >> 2)&2047); + ptr = table + ((val >> 2)&2047); - mutex_lock(&lock); - while (ptr->next) { - if (ptr->next->pc == pc) - break; - ptr = ptr->next; - } + mutex_lock(&lock); + while (ptr->next) { + if (ptr->next->pc == pc) + break; + ptr = ptr->next; + } - int stop = 0; - if (ptr->next) { - mutex_unlock(&lock); - } else { - (args->callback)(pc, args->closure); - args->numFrames++; - if (args->maxFrames != 0 && args->numFrames == args->maxFrames) - stop = 1; // causes us to stop getting frames + int stop = 0; + if (ptr->next) { + mutex_unlock(&lock); + } else { + (args->callback)(pc, args->closure); + args->numFrames++; + if (args->maxFrames != 0 && args->numFrames == args->maxFrames) + stop = 1; // causes us to stop getting frames - ptr->next = newbucket(pc); - mutex_unlock(&lock); - } - return stop; + ptr->next = newbucket(pc); + mutex_unlock(&lock); + } + return stop; } static struct bucket * newbucket(void * pc) { - struct bucket * ptr = (struct bucket *) malloc(sizeof (*ptr)); - static int index; /* protected by lock in caller */ - - ptr->index = index++; - ptr->next = nullptr; - ptr->pc = pc; - return (ptr); + struct bucket * ptr = (struct bucket *) malloc(sizeof (*ptr)); + static int index; /* protected by lock in caller */ + + ptr->index = index++; + ptr->next = nullptr; + ptr->pc = pc; + return (ptr); } static struct frame * csgetframeptr() { - ucontext_t u; - struct frame *fp; + ucontext_t u; + struct frame *fp; - (void) getcontext(&u); + (void) getcontext(&u); - fp = (struct frame *) - ((char *)u.uc_mcontext.gregs[FRAME_PTR_REGISTER] + - STACK_BIAS); + fp = (struct frame *) + ((char *)u.uc_mcontext.gregs[FRAME_PTR_REGISTER] + + STACK_BIAS); - /* make sure to return parents frame pointer.... */ + /* make sure to return parents frame pointer.... */ - return ((struct frame *)((ulong_t)fp->fr_savfp + STACK_BIAS)); + return ((struct frame *)((ulong_t)fp->fr_savfp + STACK_BIAS)); } static void cswalkstack(struct frame *fp, int (*operate_func)(void *, void *, void *), - void *usrarg) + void *usrarg) { - while (fp != 0 && fp->fr_savpc != 0) { + while (fp != 0 && fp->fr_savpc != 0) { - if (operate_func((void *)fp->fr_savpc, nullptr, usrarg) != 0) - break; - /* - * watch out - libthread stacks look funny at the top - * so they may not have their STACK_BIAS set - */ + if (operate_func((void *)fp->fr_savpc, nullptr, usrarg) != 0) + break; + /* + * watch out - libthread stacks look funny at the top + * so they may not have their STACK_BIAS set + */ - fp = (struct frame *)((ulong_t)fp->fr_savfp + - (fp->fr_savfp?(ulong_t)STACK_BIAS:0)); - } + fp = (struct frame *)((ulong_t)fp->fr_savfp + + (fp->fr_savfp?(ulong_t)STACK_BIAS:0)); + } } static void cs_operate(int (*operate_func)(void *, void *, void *), void * usrarg) { - cswalkstack(csgetframeptr(), operate_func, usrarg); + cswalkstack(csgetframeptr(), operate_func, usrarg); } EXPORT_XPCOM_API(nsresult) @@ -1062,70 +1062,70 @@ NS_StackWalk(NS_WalkStackCallback aCallback, uint32_t aSkipFrames, uint32_t aMaxFrames, void *aClosure, uintptr_t aThread, void *aPlatformData) { - MOZ_ASSERT(!aThread); - MOZ_ASSERT(!aPlatformData); - struct my_user_args args; + MOZ_ASSERT(!aThread); + MOZ_ASSERT(!aPlatformData); + struct my_user_args args; - StackWalkInitCriticalAddress(); + StackWalkInitCriticalAddress(); - if (!initialized) - myinit(); + if (!initialized) + myinit(); - args.callback = aCallback; - args.skipFrames = aSkipFrames; /* XXX Not handled! */ - args.maxFrames = aMaxFrames; - args.numFrames = 0; - args.closure = aClosure; - cs_operate(load_address, &args); - return args.numFrames == 0 ? NS_ERROR_FAILURE : NS_OK; + args.callback = aCallback; + args.skipFrames = aSkipFrames; /* XXX Not handled! */ + args.maxFrames = aMaxFrames; + args.numFrames = 0; + args.closure = aClosure; + cs_operate(load_address, &args); + return args.numFrames == 0 ? NS_ERROR_FAILURE : NS_OK; } EXPORT_XPCOM_API(nsresult) NS_DescribeCodeAddress(void *aPC, nsCodeAddressDetails *aDetails) { - aDetails->library[0] = '\0'; - aDetails->loffset = 0; - aDetails->filename[0] = '\0'; - aDetails->lineno = 0; - aDetails->function[0] = '\0'; - aDetails->foffset = 0; + aDetails->library[0] = '\0'; + aDetails->loffset = 0; + aDetails->filename[0] = '\0'; + aDetails->lineno = 0; + aDetails->function[0] = '\0'; + aDetails->foffset = 0; - char dembuff[4096]; - Dl_info info; + char dembuff[4096]; + Dl_info info; - if (dladdr(aPC, & info)) { - if (info.dli_fname) { - PL_strncpyz(aDetails->library, info.dli_fname, - sizeof(aDetails->library)); - aDetails->loffset = (char*)aPC - (char*)info.dli_fbase; - } - if (info.dli_sname) { - aDetails->foffset = (char*)aPC - (char*)info.dli_saddr; -#ifdef __GNUC__ - DemangleSymbol(info.dli_sname, dembuff, sizeof(dembuff)); -#else - if (!demf || demf(info.dli_sname, dembuff, sizeof (dembuff))) - dembuff[0] = 0; -#endif /*__GNUC__*/ - PL_strncpyz(aDetails->function, - (dembuff[0] != '\0') ? dembuff : info.dli_sname, - sizeof(aDetails->function)); - } + if (dladdr(aPC, & info)) { + if (info.dli_fname) { + PL_strncpyz(aDetails->library, info.dli_fname, + sizeof(aDetails->library)); + aDetails->loffset = (char*)aPC - (char*)info.dli_fbase; } + if (info.dli_sname) { + aDetails->foffset = (char*)aPC - (char*)info.dli_saddr; +#ifdef __GNUC__ + DemangleSymbol(info.dli_sname, dembuff, sizeof(dembuff)); +#else + if (!demf || demf(info.dli_sname, dembuff, sizeof (dembuff))) + dembuff[0] = 0; +#endif /*__GNUC__*/ + PL_strncpyz(aDetails->function, + (dembuff[0] != '\0') ? dembuff : info.dli_sname, + sizeof(aDetails->function)); + } + } - return NS_OK; + return NS_OK; } EXPORT_XPCOM_API(nsresult) NS_FormatCodeAddressDetails(void *aPC, const nsCodeAddressDetails *aDetails, char *aBuffer, uint32_t aBufferSize) { - snprintf(aBuffer, aBufferSize, "%p %s:%s+0x%lx\n", - aPC, - aDetails->library[0] ? aDetails->library : "??", - aDetails->function[0] ? aDetails->function : "??", - aDetails->foffset); - return NS_OK; + snprintf(aBuffer, aBufferSize, "%p %s:%s+0x%lx\n", + aPC, + aDetails->library[0] ? aDetails->library : "??", + aDetails->function[0] ? aDetails->function : "??", + aDetails->foffset); + return NS_OK; } #else // not __sun-specific @@ -1205,7 +1205,7 @@ NS_StackWalk(NS_WalkStackCallback aCallback, uint32_t aSkipFrames, // Get the frame pointer void **bp; -#if defined(__i386) +#if defined(__i386) __asm__( "movl %%ebp, %0" : "=g"(bp)); #else // It would be nice if this worked uniformly, but at least on i386 and @@ -1231,37 +1231,37 @@ NS_StackWalk(NS_WalkStackCallback aCallback, uint32_t aSkipFrames, #include struct unwind_info { - NS_WalkStackCallback callback; - int skip; - int maxFrames; - int numFrames; - bool isCriticalAbort; - void *closure; + NS_WalkStackCallback callback; + int skip; + int maxFrames; + int numFrames; + bool isCriticalAbort; + void *closure; }; static _Unwind_Reason_Code unwind_callback (struct _Unwind_Context *context, void *closure) { - unwind_info *info = static_cast(closure); - void *pc = reinterpret_cast(_Unwind_GetIP(context)); - // TODO Use something like '_Unwind_GetGR()' to get the stack pointer. - if (IsCriticalAddress(pc)) { - printf("Aborting stack trace, PC is critical\n"); - info->isCriticalAbort = true; - // We just want to stop the walk, so any error code will do. Using - // _URC_NORMAL_STOP would probably be the most accurate, but it is not - // defined on Android for ARM. - return _URC_FOREIGN_EXCEPTION_CAUGHT; + unwind_info *info = static_cast(closure); + void *pc = reinterpret_cast(_Unwind_GetIP(context)); + // TODO Use something like '_Unwind_GetGR()' to get the stack pointer. + if (IsCriticalAddress(pc)) { + printf("Aborting stack trace, PC is critical\n"); + info->isCriticalAbort = true; + // We just want to stop the walk, so any error code will do. Using + // _URC_NORMAL_STOP would probably be the most accurate, but it is not + // defined on Android for ARM. + return _URC_FOREIGN_EXCEPTION_CAUGHT; + } + if (--info->skip < 0) { + (*info->callback)(pc, nullptr, info->closure); + info->numFrames++; + if (info->maxFrames != 0 && info->numFrames == info->maxFrames) { + // Again, any error code that stops the walk will do. + return _URC_FOREIGN_EXCEPTION_CAUGHT; } - if (--info->skip < 0) { - (*info->callback)(pc, nullptr, info->closure); - info->numFrames++; - if (info->maxFrames != 0 && info->numFrames == info->maxFrames) { - // Again, any error code that stops the walk will do. - return _URC_FOREIGN_EXCEPTION_CAUGHT; - } - } - return _URC_NO_REASON; + } + return _URC_NO_REASON; } EXPORT_XPCOM_API(nsresult) @@ -1269,30 +1269,30 @@ NS_StackWalk(NS_WalkStackCallback aCallback, uint32_t aSkipFrames, uint32_t aMaxFrames, void *aClosure, uintptr_t aThread, void *aPlatformData) { - MOZ_ASSERT(!aThread); - MOZ_ASSERT(!aPlatformData); - StackWalkInitCriticalAddress(); - unwind_info info; - info.callback = aCallback; - info.skip = aSkipFrames + 1; - info.maxFrames = aMaxFrames; - info.numFrames = 0; - info.isCriticalAbort = false; - info.closure = aClosure; + MOZ_ASSERT(!aThread); + MOZ_ASSERT(!aPlatformData); + StackWalkInitCriticalAddress(); + unwind_info info; + info.callback = aCallback; + info.skip = aSkipFrames + 1; + info.maxFrames = aMaxFrames; + info.numFrames = 0; + info.isCriticalAbort = false; + info.closure = aClosure; - (void)_Unwind_Backtrace(unwind_callback, &info); + (void)_Unwind_Backtrace(unwind_callback, &info); - // We ignore the return value from _Unwind_Backtrace and instead determine - // the outcome from |info|. There are two main reasons for this: - // - On ARM/Android bionic's _Unwind_Backtrace usually (always?) returns - // _URC_FAILURE. See - // https://bugzilla.mozilla.org/show_bug.cgi?id=717853#c110. - // - If aMaxFrames != 0, we want to stop early, and the only way to do that - // is to make unwind_callback return something other than _URC_NO_REASON, - // which causes _Unwind_Backtrace to return a non-success code. - if (info.isCriticalAbort) - return NS_ERROR_UNEXPECTED; - return info.numFrames == 0 ? NS_ERROR_FAILURE : NS_OK; + // We ignore the return value from _Unwind_Backtrace and instead determine + // the outcome from |info|. There are two main reasons for this: + // - On ARM/Android bionic's _Unwind_Backtrace usually (always?) returns + // _URC_FAILURE. See + // https://bugzilla.mozilla.org/show_bug.cgi?id=717853#c110. + // - If aMaxFrames != 0, we want to stop early, and the only way to do that + // is to make unwind_callback return something other than _URC_NO_REASON, + // which causes _Unwind_Backtrace to return a non-success code. + if (info.isCriticalAbort) + return NS_ERROR_UNEXPECTED; + return info.numFrames == 0 ? NS_ERROR_FAILURE : NS_OK; } #endif @@ -1340,12 +1340,12 @@ NS_FormatCodeAddressDetails(void *aPC, const nsCodeAddressDetails *aDetails, snprintf(aBuffer, aBufferSize, "UNKNOWN %p\n", aPC); } else if (!aDetails->function[0]) { snprintf(aBuffer, aBufferSize, "UNKNOWN [%s +0x%08" PRIXPTR "]\n", - aDetails->library, aDetails->loffset); + aDetails->library, aDetails->loffset); } else { snprintf(aBuffer, aBufferSize, "%s+0x%08" PRIXPTR - " [%s +0x%08" PRIXPTR "]\n", - aDetails->function, aDetails->foffset, - aDetails->library, aDetails->loffset); + " [%s +0x%08" PRIXPTR "]\n", + aDetails->function, aDetails->foffset, + aDetails->library, aDetails->loffset); } return NS_OK; } @@ -1359,9 +1359,9 @@ NS_StackWalk(NS_WalkStackCallback aCallback, uint32_t aSkipFrames, uint32_t aMaxFrames, void *aClosure, uintptr_t aThread, void *aPlatformData) { - MOZ_ASSERT(!aThread); - MOZ_ASSERT(!aPlatformData); - return NS_ERROR_NOT_IMPLEMENTED; + MOZ_ASSERT(!aThread); + MOZ_ASSERT(!aPlatformData); + return NS_ERROR_NOT_IMPLEMENTED; } namespace mozilla { @@ -1369,28 +1369,28 @@ nsresult FramePointerStackWalk(NS_WalkStackCallback aCallback, uint32_t aSkipFrames, void *aClosure, void **bp) { - return NS_ERROR_NOT_IMPLEMENTED; + return NS_ERROR_NOT_IMPLEMENTED; } } EXPORT_XPCOM_API(nsresult) NS_DescribeCodeAddress(void *aPC, nsCodeAddressDetails *aDetails) { - aDetails->library[0] = '\0'; - aDetails->loffset = 0; - aDetails->filename[0] = '\0'; - aDetails->lineno = 0; - aDetails->function[0] = '\0'; - aDetails->foffset = 0; - return NS_ERROR_NOT_IMPLEMENTED; + aDetails->library[0] = '\0'; + aDetails->loffset = 0; + aDetails->filename[0] = '\0'; + aDetails->lineno = 0; + aDetails->function[0] = '\0'; + aDetails->foffset = 0; + return NS_ERROR_NOT_IMPLEMENTED; } EXPORT_XPCOM_API(nsresult) NS_FormatCodeAddressDetails(void *aPC, const nsCodeAddressDetails *aDetails, char *aBuffer, uint32_t aBufferSize) { - aBuffer[0] = '\0'; - return NS_ERROR_NOT_IMPLEMENTED; + aBuffer[0] = '\0'; + return NS_ERROR_NOT_IMPLEMENTED; } #endif diff --git a/xpcom/base/nsStackWalk.h b/xpcom/base/nsStackWalk.h index 6e0d9474d3fd..7793affb9c09 100644 --- a/xpcom/base/nsStackWalk.h +++ b/xpcom/base/nsStackWalk.h @@ -1,4 +1,5 @@ -/* vim: set shiftwidth=4 tabstop=8 autoindent cindent expandtab: */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ @@ -65,26 +66,26 @@ NS_StackWalk(NS_WalkStackCallback aCallback, uint32_t aSkipFrames, void *aPlatformData); typedef struct { - /* - * The name of the shared library or executable containing an - * address and the address's offset within that library, or empty - * string and zero if unknown. - */ - char library[256]; - ptrdiff_t loffset; - /* - * The name of the file name and line number of the code - * corresponding to the address, or empty string and zero if - * unknown. - */ - char filename[256]; - unsigned long lineno; - /* - * The name of the function containing an address and the address's - * offset within that function, or empty string and zero if unknown. - */ - char function[256]; - ptrdiff_t foffset; + /* + * The name of the shared library or executable containing an + * address and the address's offset within that library, or empty + * string and zero if unknown. + */ + char library[256]; + ptrdiff_t loffset; + /* + * The name of the file name and line number of the code + * corresponding to the address, or empty string and zero if + * unknown. + */ + char filename[256]; + unsigned long lineno; + /* + * The name of the function containing an address and the address's + * offset within that function, or empty string and zero if unknown. + */ + char function[256]; + ptrdiff_t foffset; } nsCodeAddressDetails; /** diff --git a/xpcom/base/nsStatusReporterManager.cpp b/xpcom/base/nsStatusReporterManager.cpp index bf9b1770f977..1d9d695df6c6 100644 --- a/xpcom/base/nsStatusReporterManager.cpp +++ b/xpcom/base/nsStatusReporterManager.cpp @@ -74,13 +74,13 @@ nsresult getStatus(nsACString& desc) NS_STATUS_REPORTER_IMPLEMENT(StatusReporter, "StatusReporter State", getStatus) #define DUMP(o, s) \ - do { \ - const char* s2 = (s); \ - uint32_t dummy; \ - nsresult rv = (o)->Write((s2), strlen(s2), &dummy); \ - if (NS_WARN_IF(NS_FAILED(rv))) \ - return rv; \ - } while (0) + do { \ + const char* s2 = (s); \ + uint32_t dummy; \ + nsresult rv = (o)->Write((s2), strlen(s2), &dummy); \ + if (NS_WARN_IF(NS_FAILED(rv))) \ + return rv; \ + } while (0) static nsresult DumpReport(nsIFileOutputStream* aOStream, const nsCString& aProcess, @@ -157,9 +157,9 @@ nsStatusReporterManager::DumpReports() // begining, it will be rename as "status-reports-pid-number.json" in the end. nsCOMPtr tmpFile; rv = nsDumpUtils::OpenTempFile(NS_LITERAL_CSTRING("incomplete-") + - filename, - getter_AddRefs(tmpFile), - NS_LITERAL_CSTRING("status-reports")); + filename, + getter_AddRefs(tmpFile), + NS_LITERAL_CSTRING("status-reports")); if (NS_WARN_IF(NS_FAILED(rv))) return rv; diff --git a/xpcom/base/nsSystemInfo.cpp b/xpcom/base/nsSystemInfo.cpp index 313c7e85b503..7f90ed8e0542 100644 --- a/xpcom/base/nsSystemInfo.cpp +++ b/xpcom/base/nsSystemInfo.cpp @@ -1,4 +1,5 @@ -/* -*- Mode: C++; tab-width: 50; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ @@ -52,74 +53,74 @@ namespace { nsresult GetHDDInfo(const char* aSpecialDirName, nsAutoCString& aModel, nsAutoCString& aRevision) { - aModel.Truncate(); - aRevision.Truncate(); + aModel.Truncate(); + aRevision.Truncate(); - nsCOMPtr profDir; - nsresult rv = NS_GetSpecialDirectory(aSpecialDirName, - getter_AddRefs(profDir)); - NS_ENSURE_SUCCESS(rv, rv); - nsAutoString profDirPath; - rv = profDir->GetPath(profDirPath); - NS_ENSURE_SUCCESS(rv, rv); - wchar_t volumeMountPoint[MAX_PATH] = {L'\\', L'\\', L'.', L'\\'}; - const size_t PREFIX_LEN = 4; - if (!::GetVolumePathNameW(profDirPath.get(), volumeMountPoint + PREFIX_LEN, - mozilla::ArrayLength(volumeMountPoint) - - PREFIX_LEN)) { - return NS_ERROR_UNEXPECTED; - } - size_t volumeMountPointLen = wcslen(volumeMountPoint); - // Since we would like to open a drive and not a directory, we need to - // remove any trailing backslash. A drive handle is valid for - // DeviceIoControl calls, a directory handle is not. - if (volumeMountPoint[volumeMountPointLen - 1] == L'\\') { - volumeMountPoint[volumeMountPointLen - 1] = L'\0'; - } - ScopedHandle handle(::CreateFileW(volumeMountPoint, 0, - FILE_SHARE_READ | FILE_SHARE_WRITE, - nullptr, OPEN_EXISTING, 0, nullptr)); - if (!handle.IsValid()) { - return NS_ERROR_UNEXPECTED; - } - STORAGE_PROPERTY_QUERY queryParameters = {StorageDeviceProperty, - PropertyStandardQuery}; - STORAGE_DEVICE_DESCRIPTOR outputHeader = {sizeof(STORAGE_DEVICE_DESCRIPTOR)}; - DWORD bytesRead = 0; - if (!::DeviceIoControl(handle, IOCTL_STORAGE_QUERY_PROPERTY, - &queryParameters, sizeof(queryParameters), - &outputHeader, sizeof(outputHeader), &bytesRead, - nullptr)) { - return NS_ERROR_FAILURE; - } - PSTORAGE_DEVICE_DESCRIPTOR deviceOutput = - (PSTORAGE_DEVICE_DESCRIPTOR)malloc(outputHeader.Size); - if (!::DeviceIoControl(handle, IOCTL_STORAGE_QUERY_PROPERTY, - &queryParameters, sizeof(queryParameters), - deviceOutput, outputHeader.Size, &bytesRead, - nullptr)) { - free(deviceOutput); - return NS_ERROR_FAILURE; - } - // Some HDDs are including product ID info in the vendor field. Since PNP - // IDs include vendor info and product ID concatenated together, we'll do - // that here and interpret the result as a unique ID for the HDD model. - if (deviceOutput->VendorIdOffset) { - aModel = reinterpret_cast(deviceOutput) + - deviceOutput->VendorIdOffset; - } - if (deviceOutput->ProductIdOffset) { - aModel += reinterpret_cast(deviceOutput) + - deviceOutput->ProductIdOffset; - } - aModel.CompressWhitespace(); - if (deviceOutput->ProductRevisionOffset) { - aRevision = reinterpret_cast(deviceOutput) + - deviceOutput->ProductRevisionOffset; - aRevision.CompressWhitespace(); - } + nsCOMPtr profDir; + nsresult rv = NS_GetSpecialDirectory(aSpecialDirName, + getter_AddRefs(profDir)); + NS_ENSURE_SUCCESS(rv, rv); + nsAutoString profDirPath; + rv = profDir->GetPath(profDirPath); + NS_ENSURE_SUCCESS(rv, rv); + wchar_t volumeMountPoint[MAX_PATH] = {L'\\', L'\\', L'.', L'\\'}; + const size_t PREFIX_LEN = 4; + if (!::GetVolumePathNameW(profDirPath.get(), volumeMountPoint + PREFIX_LEN, + mozilla::ArrayLength(volumeMountPoint) - + PREFIX_LEN)) { + return NS_ERROR_UNEXPECTED; + } + size_t volumeMountPointLen = wcslen(volumeMountPoint); + // Since we would like to open a drive and not a directory, we need to + // remove any trailing backslash. A drive handle is valid for + // DeviceIoControl calls, a directory handle is not. + if (volumeMountPoint[volumeMountPointLen - 1] == L'\\') { + volumeMountPoint[volumeMountPointLen - 1] = L'\0'; + } + ScopedHandle handle(::CreateFileW(volumeMountPoint, 0, + FILE_SHARE_READ | FILE_SHARE_WRITE, + nullptr, OPEN_EXISTING, 0, nullptr)); + if (!handle.IsValid()) { + return NS_ERROR_UNEXPECTED; + } + STORAGE_PROPERTY_QUERY queryParameters = {StorageDeviceProperty, + PropertyStandardQuery}; + STORAGE_DEVICE_DESCRIPTOR outputHeader = {sizeof(STORAGE_DEVICE_DESCRIPTOR)}; + DWORD bytesRead = 0; + if (!::DeviceIoControl(handle, IOCTL_STORAGE_QUERY_PROPERTY, + &queryParameters, sizeof(queryParameters), + &outputHeader, sizeof(outputHeader), &bytesRead, + nullptr)) { + return NS_ERROR_FAILURE; + } + PSTORAGE_DEVICE_DESCRIPTOR deviceOutput = + (PSTORAGE_DEVICE_DESCRIPTOR)malloc(outputHeader.Size); + if (!::DeviceIoControl(handle, IOCTL_STORAGE_QUERY_PROPERTY, + &queryParameters, sizeof(queryParameters), + deviceOutput, outputHeader.Size, &bytesRead, + nullptr)) { free(deviceOutput); - return NS_OK; + return NS_ERROR_FAILURE; + } + // Some HDDs are including product ID info in the vendor field. Since PNP + // IDs include vendor info and product ID concatenated together, we'll do + // that here and interpret the result as a unique ID for the HDD model. + if (deviceOutput->VendorIdOffset) { + aModel = reinterpret_cast(deviceOutput) + + deviceOutput->VendorIdOffset; + } + if (deviceOutput->ProductIdOffset) { + aModel += reinterpret_cast(deviceOutput) + + deviceOutput->ProductIdOffset; + } + aModel.CompressWhitespace(); + if (deviceOutput->ProductRevisionOffset) { + aRevision = reinterpret_cast(deviceOutput) + + deviceOutput->ProductRevisionOffset; + aRevision.CompressWhitespace(); + } + free(deviceOutput); + return NS_OK; } } // anonymous namespace #endif // defined(XP_WIN) @@ -136,168 +137,168 @@ nsSystemInfo::~nsSystemInfo() // CPU-specific information. static const struct PropItems { - const char *name; - bool (*propfun)(void); + const char *name; + bool (*propfun)(void); } cpuPropItems[] = { - // x86-specific bits. - { "hasMMX", mozilla::supports_mmx }, - { "hasSSE", mozilla::supports_sse }, - { "hasSSE2", mozilla::supports_sse2 }, - { "hasSSE3", mozilla::supports_sse3 }, - { "hasSSSE3", mozilla::supports_ssse3 }, - { "hasSSE4A", mozilla::supports_sse4a }, - { "hasSSE4_1", mozilla::supports_sse4_1 }, - { "hasSSE4_2", mozilla::supports_sse4_2 }, - // ARM-specific bits. - { "hasEDSP", mozilla::supports_edsp }, - { "hasARMv6", mozilla::supports_armv6 }, - { "hasARMv7", mozilla::supports_armv7 }, - { "hasNEON", mozilla::supports_neon } + // x86-specific bits. + { "hasMMX", mozilla::supports_mmx }, + { "hasSSE", mozilla::supports_sse }, + { "hasSSE2", mozilla::supports_sse2 }, + { "hasSSE3", mozilla::supports_sse3 }, + { "hasSSSE3", mozilla::supports_ssse3 }, + { "hasSSE4A", mozilla::supports_sse4a }, + { "hasSSE4_1", mozilla::supports_sse4_1 }, + { "hasSSE4_2", mozilla::supports_sse4_2 }, + // ARM-specific bits. + { "hasEDSP", mozilla::supports_edsp }, + { "hasARMv6", mozilla::supports_armv6 }, + { "hasARMv7", mozilla::supports_armv7 }, + { "hasNEON", mozilla::supports_neon } }; nsresult nsSystemInfo::Init() { - nsresult rv; + nsresult rv; - static const struct { - PRSysInfo cmd; - const char *name; - } items[] = { - { PR_SI_SYSNAME, "name" }, - { PR_SI_HOSTNAME, "host" }, - { PR_SI_ARCHITECTURE, "arch" }, - { PR_SI_RELEASE, "version" } - }; + static const struct { + PRSysInfo cmd; + const char *name; + } items[] = { + { PR_SI_SYSNAME, "name" }, + { PR_SI_HOSTNAME, "host" }, + { PR_SI_ARCHITECTURE, "arch" }, + { PR_SI_RELEASE, "version" } + }; - for (uint32_t i = 0; i < (sizeof(items) / sizeof(items[0])); i++) { - char buf[SYS_INFO_BUFFER_LENGTH]; - if (PR_GetSystemInfo(items[i].cmd, buf, sizeof(buf)) == PR_SUCCESS) { - rv = SetPropertyAsACString(NS_ConvertASCIItoUTF16(items[i].name), - nsDependentCString(buf)); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; - } - else { - NS_WARNING("PR_GetSystemInfo failed"); - } - } - -#if defined(XP_WIN) && defined(MOZ_METRO) - // Create "hasWindowsTouchInterface" property. - nsAutoString version; - rv = GetPropertyAsAString(NS_LITERAL_STRING("version"), version); - NS_ENSURE_SUCCESS(rv, rv); - double versionDouble = version.ToDouble(&rv); - NS_ENSURE_SUCCESS(rv, rv); - - rv = SetPropertyAsBool(NS_ConvertASCIItoUTF16("hasWindowsTouchInterface"), - versionDouble >= 6.2); - NS_ENSURE_SUCCESS(rv, rv); -#else - rv = SetPropertyAsBool(NS_ConvertASCIItoUTF16("hasWindowsTouchInterface"), false); - NS_ENSURE_SUCCESS(rv, rv); -#endif - - // Additional informations not available through PR_GetSystemInfo. - SetInt32Property(NS_LITERAL_STRING("pagesize"), PR_GetPageSize()); - SetInt32Property(NS_LITERAL_STRING("pageshift"), PR_GetPageShift()); - SetInt32Property(NS_LITERAL_STRING("memmapalign"), PR_GetMemMapAlignment()); - SetInt32Property(NS_LITERAL_STRING("cpucount"), PR_GetNumberOfProcessors()); - SetUint64Property(NS_LITERAL_STRING("memsize"), PR_GetPhysicalMemorySize()); - SetUint32Property(NS_LITERAL_STRING("umask"), nsSystemInfo::gUserUmask); - - for (uint32_t i = 0; i < ArrayLength(cpuPropItems); i++) { - rv = SetPropertyAsBool(NS_ConvertASCIItoUTF16(cpuPropItems[i].name), - cpuPropItems[i].propfun()); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; - } - -#ifdef XP_WIN - BOOL isWow64; - BOOL gotWow64Value = IsWow64Process(GetCurrentProcess(), &isWow64); - NS_WARN_IF_FALSE(gotWow64Value, "IsWow64Process failed"); - if (gotWow64Value) { - rv = SetPropertyAsBool(NS_LITERAL_STRING("isWow64"), !!isWow64); + for (uint32_t i = 0; i < (sizeof(items) / sizeof(items[0])); i++) { + char buf[SYS_INFO_BUFFER_LENGTH]; + if (PR_GetSystemInfo(items[i].cmd, buf, sizeof(buf)) == PR_SUCCESS) { + rv = SetPropertyAsACString(NS_ConvertASCIItoUTF16(items[i].name), + nsDependentCString(buf)); if (NS_WARN_IF(NS_FAILED(rv))) return rv; } - nsAutoCString hddModel, hddRevision; - if (NS_SUCCEEDED(GetHDDInfo(NS_APP_USER_PROFILE_50_DIR, hddModel, - hddRevision))) { - rv = SetPropertyAsACString(NS_LITERAL_STRING("profileHDDModel"), hddModel); - NS_ENSURE_SUCCESS(rv, rv); - rv = SetPropertyAsACString(NS_LITERAL_STRING("profileHDDRevision"), - hddRevision); - NS_ENSURE_SUCCESS(rv, rv); - } - if (NS_SUCCEEDED(GetHDDInfo(NS_GRE_DIR, hddModel, hddRevision))) { - rv = SetPropertyAsACString(NS_LITERAL_STRING("binHDDModel"), hddModel); - NS_ENSURE_SUCCESS(rv, rv); - rv = SetPropertyAsACString(NS_LITERAL_STRING("binHDDRevision"), - hddRevision); - NS_ENSURE_SUCCESS(rv, rv); - } - if (NS_SUCCEEDED(GetHDDInfo(NS_WIN_WINDOWS_DIR, hddModel, hddRevision))) { - rv = SetPropertyAsACString(NS_LITERAL_STRING("winHDDModel"), hddModel); - NS_ENSURE_SUCCESS(rv, rv); - rv = SetPropertyAsACString(NS_LITERAL_STRING("winHDDRevision"), - hddRevision); - NS_ENSURE_SUCCESS(rv, rv); + else { + NS_WARNING("PR_GetSystemInfo failed"); } + } + +#if defined(XP_WIN) && defined(MOZ_METRO) + // Create "hasWindowsTouchInterface" property. + nsAutoString version; + rv = GetPropertyAsAString(NS_LITERAL_STRING("version"), version); + NS_ENSURE_SUCCESS(rv, rv); + double versionDouble = version.ToDouble(&rv); + NS_ENSURE_SUCCESS(rv, rv); + + rv = SetPropertyAsBool(NS_ConvertASCIItoUTF16("hasWindowsTouchInterface"), + versionDouble >= 6.2); + NS_ENSURE_SUCCESS(rv, rv); +#else + rv = SetPropertyAsBool(NS_ConvertASCIItoUTF16("hasWindowsTouchInterface"), false); + NS_ENSURE_SUCCESS(rv, rv); +#endif + + // Additional informations not available through PR_GetSystemInfo. + SetInt32Property(NS_LITERAL_STRING("pagesize"), PR_GetPageSize()); + SetInt32Property(NS_LITERAL_STRING("pageshift"), PR_GetPageShift()); + SetInt32Property(NS_LITERAL_STRING("memmapalign"), PR_GetMemMapAlignment()); + SetInt32Property(NS_LITERAL_STRING("cpucount"), PR_GetNumberOfProcessors()); + SetUint64Property(NS_LITERAL_STRING("memsize"), PR_GetPhysicalMemorySize()); + SetUint32Property(NS_LITERAL_STRING("umask"), nsSystemInfo::gUserUmask); + + for (uint32_t i = 0; i < ArrayLength(cpuPropItems); i++) { + rv = SetPropertyAsBool(NS_ConvertASCIItoUTF16(cpuPropItems[i].name), + cpuPropItems[i].propfun()); + if (NS_WARN_IF(NS_FAILED(rv))) + return rv; + } + +#ifdef XP_WIN + BOOL isWow64; + BOOL gotWow64Value = IsWow64Process(GetCurrentProcess(), &isWow64); + NS_WARN_IF_FALSE(gotWow64Value, "IsWow64Process failed"); + if (gotWow64Value) { + rv = SetPropertyAsBool(NS_LITERAL_STRING("isWow64"), !!isWow64); + if (NS_WARN_IF(NS_FAILED(rv))) + return rv; + } + nsAutoCString hddModel, hddRevision; + if (NS_SUCCEEDED(GetHDDInfo(NS_APP_USER_PROFILE_50_DIR, hddModel, + hddRevision))) { + rv = SetPropertyAsACString(NS_LITERAL_STRING("profileHDDModel"), hddModel); + NS_ENSURE_SUCCESS(rv, rv); + rv = SetPropertyAsACString(NS_LITERAL_STRING("profileHDDRevision"), + hddRevision); + NS_ENSURE_SUCCESS(rv, rv); + } + if (NS_SUCCEEDED(GetHDDInfo(NS_GRE_DIR, hddModel, hddRevision))) { + rv = SetPropertyAsACString(NS_LITERAL_STRING("binHDDModel"), hddModel); + NS_ENSURE_SUCCESS(rv, rv); + rv = SetPropertyAsACString(NS_LITERAL_STRING("binHDDRevision"), + hddRevision); + NS_ENSURE_SUCCESS(rv, rv); + } + if (NS_SUCCEEDED(GetHDDInfo(NS_WIN_WINDOWS_DIR, hddModel, hddRevision))) { + rv = SetPropertyAsACString(NS_LITERAL_STRING("winHDDModel"), hddModel); + NS_ENSURE_SUCCESS(rv, rv); + rv = SetPropertyAsACString(NS_LITERAL_STRING("winHDDRevision"), + hddRevision); + NS_ENSURE_SUCCESS(rv, rv); + } #endif #if defined(MOZ_WIDGET_GTK) - // This must be done here because NSPR can only separate OS's when compiled, not libraries. - char* gtkver = PR_smprintf("GTK %u.%u.%u", gtk_major_version, gtk_minor_version, gtk_micro_version); - if (gtkver) { - rv = SetPropertyAsACString(NS_LITERAL_STRING("secondaryLibrary"), - nsDependentCString(gtkver)); - PR_smprintf_free(gtkver); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; - } + // This must be done here because NSPR can only separate OS's when compiled, not libraries. + char* gtkver = PR_smprintf("GTK %u.%u.%u", gtk_major_version, gtk_minor_version, gtk_micro_version); + if (gtkver) { + rv = SetPropertyAsACString(NS_LITERAL_STRING("secondaryLibrary"), + nsDependentCString(gtkver)); + PR_smprintf_free(gtkver); + if (NS_WARN_IF(NS_FAILED(rv))) + return rv; + } #endif #ifdef MOZ_WIDGET_ANDROID - if (mozilla::AndroidBridge::Bridge()) { - nsAutoString str; - if (mozilla::AndroidBridge::Bridge()->GetStaticStringField("android/os/Build", "MODEL", str)) - SetPropertyAsAString(NS_LITERAL_STRING("device"), str); - if (mozilla::AndroidBridge::Bridge()->GetStaticStringField("android/os/Build", "MANUFACTURER", str)) - SetPropertyAsAString(NS_LITERAL_STRING("manufacturer"), str); - if (mozilla::AndroidBridge::Bridge()->GetStaticStringField("android/os/Build$VERSION", "RELEASE", str)) - SetPropertyAsAString(NS_LITERAL_STRING("release_version"), str); - int32_t version; - if (!mozilla::AndroidBridge::Bridge()->GetStaticIntField("android/os/Build$VERSION", "SDK_INT", &version)) - version = 0; - android_sdk_version = version; - if (version >= 8 && mozilla::AndroidBridge::Bridge()->GetStaticStringField("android/os/Build", "HARDWARE", str)) - SetPropertyAsAString(NS_LITERAL_STRING("hardware"), str); - bool isTablet = mozilla::widget::android::GeckoAppShell::IsTablet(); - SetPropertyAsBool(NS_LITERAL_STRING("tablet"), isTablet); - // NSPR "version" is the kernel version. For Android we want the Android version. - // Rename SDK version to version and put the kernel version into kernel_version. - rv = GetPropertyAsAString(NS_LITERAL_STRING("version"), str); - if (NS_SUCCEEDED(rv)) { - SetPropertyAsAString(NS_LITERAL_STRING("kernel_version"), str); - } - SetPropertyAsInt32(NS_LITERAL_STRING("version"), android_sdk_version); + if (mozilla::AndroidBridge::Bridge()) { + nsAutoString str; + if (mozilla::AndroidBridge::Bridge()->GetStaticStringField("android/os/Build", "MODEL", str)) + SetPropertyAsAString(NS_LITERAL_STRING("device"), str); + if (mozilla::AndroidBridge::Bridge()->GetStaticStringField("android/os/Build", "MANUFACTURER", str)) + SetPropertyAsAString(NS_LITERAL_STRING("manufacturer"), str); + if (mozilla::AndroidBridge::Bridge()->GetStaticStringField("android/os/Build$VERSION", "RELEASE", str)) + SetPropertyAsAString(NS_LITERAL_STRING("release_version"), str); + int32_t version; + if (!mozilla::AndroidBridge::Bridge()->GetStaticIntField("android/os/Build$VERSION", "SDK_INT", &version)) + version = 0; + android_sdk_version = version; + if (version >= 8 && mozilla::AndroidBridge::Bridge()->GetStaticStringField("android/os/Build", "HARDWARE", str)) + SetPropertyAsAString(NS_LITERAL_STRING("hardware"), str); + bool isTablet = mozilla::widget::android::GeckoAppShell::IsTablet(); + SetPropertyAsBool(NS_LITERAL_STRING("tablet"), isTablet); + // NSPR "version" is the kernel version. For Android we want the Android version. + // Rename SDK version to version and put the kernel version into kernel_version. + rv = GetPropertyAsAString(NS_LITERAL_STRING("version"), str); + if (NS_SUCCEEDED(rv)) { + SetPropertyAsAString(NS_LITERAL_STRING("kernel_version"), str); } + SetPropertyAsInt32(NS_LITERAL_STRING("version"), android_sdk_version); + } #endif #ifdef MOZ_WIDGET_GONK - char sdk[PROP_VALUE_MAX], characteristics[PROP_VALUE_MAX]; - if (__system_property_get("ro.build.version.sdk", sdk)) - android_sdk_version = atoi(sdk); - if (__system_property_get("ro.build.characteristics", characteristics)) { - if (!strcmp(characteristics, "tablet")) - SetPropertyAsBool(NS_LITERAL_STRING("tablet"), true); - } + char sdk[PROP_VALUE_MAX], characteristics[PROP_VALUE_MAX]; + if (__system_property_get("ro.build.version.sdk", sdk)) + android_sdk_version = atoi(sdk); + if (__system_property_get("ro.build.characteristics", characteristics)) { + if (!strcmp(characteristics, "tablet")) + SetPropertyAsBool(NS_LITERAL_STRING("tablet"), true); + } #endif - return NS_OK; + return NS_OK; } void diff --git a/xpcom/base/nsSystemInfo.h b/xpcom/base/nsSystemInfo.h index e3a27a6e9bd9..32f817208d99 100644 --- a/xpcom/base/nsSystemInfo.h +++ b/xpcom/base/nsSystemInfo.h @@ -1,4 +1,5 @@ -/* -*- Mode: C++; tab-width: 50; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ @@ -10,24 +11,24 @@ class nsSystemInfo : public nsHashPropertyBag { public: - nsSystemInfo(); + nsSystemInfo(); - nsresult Init(); + nsresult Init(); - // Slot for NS_InitXPCOM2 to pass information to nsSystemInfo::Init. - // See comments above the variable definition and in NS_InitXPCOM2. - static uint32_t gUserUmask; + // Slot for NS_InitXPCOM2 to pass information to nsSystemInfo::Init. + // See comments above the variable definition and in NS_InitXPCOM2. + static uint32_t gUserUmask; protected: - void SetInt32Property(const nsAString &aPropertyName, - const int32_t aValue); - void SetUint32Property(const nsAString &aPropertyName, - const uint32_t aValue); - void SetUint64Property(const nsAString &aPropertyName, - const uint64_t aValue); + void SetInt32Property(const nsAString &aPropertyName, + const int32_t aValue); + void SetUint32Property(const nsAString &aPropertyName, + const uint32_t aValue); + void SetUint64Property(const nsAString &aPropertyName, + const uint64_t aValue); private: - ~nsSystemInfo(); + ~nsSystemInfo(); }; #define NS_SYSTEMINFO_CONTRACTID "@mozilla.org/system-info;1" diff --git a/xpcom/base/nsTraceRefcnt.cpp b/xpcom/base/nsTraceRefcnt.cpp index d3944bf31a01..16672a5a4963 100644 --- a/xpcom/base/nsTraceRefcnt.cpp +++ b/xpcom/base/nsTraceRefcnt.cpp @@ -1,4 +1,5 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ @@ -126,7 +127,7 @@ struct nsTraceRefcntStats { double mObjsOutstandingSquared; }; - // I hope to turn this on for everybody once we hit it a little less. +// I hope to turn this on for everybody once we hit it a little less. #ifdef DEBUG static const char kStaticCtorDtorWarning[] = "XPCOM objects created/destroyed from static ctor/dtor"; @@ -158,47 +159,47 @@ AssertActivityIsLegal() static void * DefaultAllocTable(void *pool, size_t size) { - return PR_MALLOC(size); + return PR_MALLOC(size); } static void DefaultFreeTable(void *pool, void *item) { - PR_Free(item); + PR_Free(item); } static PLHashEntry * DefaultAllocEntry(void *pool, const void *key) { - return PR_NEW(PLHashEntry); + return PR_NEW(PLHashEntry); } static void SerialNumberFreeEntry(void *pool, PLHashEntry *he, unsigned flag) { - if (flag == HT_FREE_ENTRY) { - PR_Free(reinterpret_cast(he->value)); - PR_Free(he); - } + if (flag == HT_FREE_ENTRY) { + PR_Free(reinterpret_cast(he->value)); + PR_Free(he); + } } static void TypesToLogFreeEntry(void *pool, PLHashEntry *he, unsigned flag) { - if (flag == HT_FREE_ENTRY) { - free(const_cast(reinterpret_cast(he->key))); - PR_Free(he); - } + if (flag == HT_FREE_ENTRY) { + free(const_cast(reinterpret_cast(he->key))); + PR_Free(he); + } } static const PLHashAllocOps serialNumberHashAllocOps = { - DefaultAllocTable, DefaultFreeTable, - DefaultAllocEntry, SerialNumberFreeEntry + DefaultAllocTable, DefaultFreeTable, + DefaultAllocEntry, SerialNumberFreeEntry }; static const PLHashAllocOps typesToLogHashAllocOps = { - DefaultAllocTable, DefaultFreeTable, - DefaultAllocEntry, TypesToLogFreeEntry + DefaultAllocTable, DefaultFreeTable, + DefaultAllocEntry, TypesToLogFreeEntry }; //////////////////////////////////////////////////////////////////////////////// @@ -232,15 +233,15 @@ public: } void Accumulate() { - mAllStats.mAddRefs += mNewStats.mAddRefs; - mAllStats.mReleases += mNewStats.mReleases; - mAllStats.mCreates += mNewStats.mCreates; - mAllStats.mDestroys += mNewStats.mDestroys; - mAllStats.mRefsOutstandingTotal += mNewStats.mRefsOutstandingTotal; - mAllStats.mRefsOutstandingSquared += mNewStats.mRefsOutstandingSquared; - mAllStats.mObjsOutstandingTotal += mNewStats.mObjsOutstandingTotal; - mAllStats.mObjsOutstandingSquared += mNewStats.mObjsOutstandingSquared; - Clear(&mNewStats); + mAllStats.mAddRefs += mNewStats.mAddRefs; + mAllStats.mReleases += mNewStats.mReleases; + mAllStats.mCreates += mNewStats.mCreates; + mAllStats.mDestroys += mNewStats.mDestroys; + mAllStats.mRefsOutstandingTotal += mNewStats.mRefsOutstandingTotal; + mAllStats.mRefsOutstandingSquared += mNewStats.mRefsOutstandingSquared; + mAllStats.mObjsOutstandingTotal += mNewStats.mObjsOutstandingTotal; + mAllStats.mObjsOutstandingSquared += mNewStats.mObjsOutstandingSquared; + Clear(&mNewStats); } void AddRef(nsrefcnt refcnt) { @@ -310,8 +311,8 @@ public: uint64_t count = (mNewStats.mCreates + mAllStats.mCreates); total->mClassSize += mClassSize * count; // adjust for average in DumpTotal total->mTotalLeaked += (uint64_t)(mClassSize * - ((mNewStats.mCreates + mAllStats.mCreates) - -(mNewStats.mDestroys + mAllStats.mDestroys))); + ((mNewStats.mCreates + mAllStats.mCreates) + -(mNewStats.mDestroys + mAllStats.mDestroys))); } void DumpTotal(FILE* out) { @@ -333,9 +334,9 @@ public: return false; fprintf(out, - "\n" \ - " |<----------------Class--------------->|<-----Bytes------>|<----------------Objects---------------->|<--------------References-------------->|\n" \ - " Per-Inst Leaked Total Rem Mean StdDev Total Rem Mean StdDev\n"); + "\n" \ + " |<----------------Class--------------->|<-----Bytes------>|<----------------Objects---------------->|<--------------References-------------->|\n" \ + " Per-Inst Leaked Total Rem Mean StdDev Total Rem Mean StdDev\n"); this->DumpTotal(out); @@ -372,8 +373,8 @@ public: i+1, mClassName, (int32_t)mClassSize, (nsCRT::strcmp(mClassName, "TOTAL")) - ?(uint64_t)((stats->mCreates - stats->mDestroys) * mClassSize) - :mTotalLeaked, + ?(uint64_t)((stats->mCreates - stats->mDestroys) * mClassSize) + :mTotalLeaked, stats->mCreates, (stats->mCreates - stats->mDestroys), meanObjs, @@ -396,16 +397,16 @@ protected: static void BloatViewFreeEntry(void *pool, PLHashEntry *he, unsigned flag) { - if (flag == HT_FREE_ENTRY) { - BloatEntry* entry = reinterpret_cast(he->value); - delete entry; - PR_Free(he); - } + if (flag == HT_FREE_ENTRY) { + BloatEntry* entry = reinterpret_cast(he->value); + delete entry; + PR_Free(he); + } } const static PLHashAllocOps bloatViewHashAllocOps = { - DefaultAllocTable, DefaultFreeTable, - DefaultAllocEntry, BloatViewFreeEntry + DefaultAllocTable, DefaultFreeTable, + DefaultAllocEntry, BloatViewFreeEntry }; static void @@ -449,17 +450,17 @@ static int DumpSerialNumbers(PLHashEntry* aHashEntry, int aIndex, void* aClosure serialNumberRecord* record = reinterpret_cast(aHashEntry->value); #ifdef HAVE_CPP_DYNAMIC_CAST_TO_VOID_PTR fprintf((FILE*) aClosure, "%" PRIdPTR - " @%p (%d references; %d from COMPtrs)\n", - record->serialNumber, - NS_INT32_TO_PTR(aHashEntry->key), - record->refCount, - record->COMPtrCount); + " @%p (%d references; %d from COMPtrs)\n", + record->serialNumber, + NS_INT32_TO_PTR(aHashEntry->key), + record->refCount, + record->COMPtrCount); #else fprintf((FILE*) aClosure, "%" PRIdPTR - " @%p (%d references)\n", - record->serialNumber, - NS_INT32_TO_PTR(aHashEntry->key), - record->refCount); + " @%p (%d references)\n", + record->serialNumber, + NS_INT32_TO_PTR(aHashEntry->key), + record->refCount); #endif return HT_ENUMERATE_NEXT; } @@ -467,13 +468,13 @@ static int DumpSerialNumbers(PLHashEntry* aHashEntry, int aIndex, void* aClosure template <> class nsDefaultComparator { - public: - bool Equals(BloatEntry* const& aA, BloatEntry* const& aB) const { - return PL_strcmp(aA->GetClassName(), aB->GetClassName()) == 0; - } - bool LessThan(BloatEntry* const& aA, BloatEntry* const& aB) const { - return PL_strcmp(aA->GetClassName(), aB->GetClassName()) < 0; - } +public: + bool Equals(BloatEntry* const& aA, BloatEntry* const& aB) const { + return PL_strcmp(aA->GetClassName(), aB->GetClassName()) == 0; + } + bool LessThan(BloatEntry* const& aA, BloatEntry* const& aB) const { + return PL_strcmp(aA->GetClassName(), aB->GetClassName()) < 0; + } }; #endif /* NS_IMPL_REFCNT_LOGGING */ @@ -638,8 +639,8 @@ static bool InitLog(const char* envVar, const char* msg, FILE* *result) FILE *stream; nsAutoCString fname(value); if (XRE_GetProcessType() != GeckoProcessType_Default) { - bool hasLogExtension = - fname.RFind(".log", true, -1, 4) == kNotFound ? false : true; + bool hasLogExtension = + fname.RFind(".log", true, -1, 4) == kNotFound ? false : true; if (hasLogExtension) fname.Cut(fname.Length() - 4, 4); fname.AppendLiteral("_"); @@ -885,7 +886,7 @@ nsTraceRefcnt::DemangleSymbol(const char * aSymbol, aBuffer[0] = '\0'; #if defined(MOZ_DEMANGLE_SYMBOLS) - /* See demangle.h in the gcc source for the voodoo */ + /* See demangle.h in the gcc source for the voodoo */ char * demangled = abi::__cxa_demangle(aSymbol,0,0,0); if (demangled) @@ -948,7 +949,7 @@ LogTerm() */ BlockingResourceBase::Shutdown(); #endif - + if (gInitialized) { nsTraceRefcnt::DumpStatistics(); nsTraceRefcnt::ResetStatistics(); @@ -1009,11 +1010,11 @@ NS_LogAddRef(void* aPtr, nsrefcnt aRefcnt, (*leakyLogAddRef)(aPtr, aRefcnt - 1, aRefcnt); } else { - // Can't use PR_LOG(), b/c it truncates the line - fprintf(gRefcntsLog, - "\n<%s> 0x%08X %" PRIuPTR " AddRef %" PRIuPTR "\n", aClazz, NS_PTR_TO_INT32(aPtr), serialno, aRefcnt); - nsTraceRefcnt::WalkTheStack(gRefcntsLog); - fflush(gRefcntsLog); + // Can't use PR_LOG(), b/c it truncates the line + fprintf(gRefcntsLog, + "\n<%s> 0x%08X %" PRIuPTR " AddRef %" PRIuPTR "\n", aClazz, NS_PTR_TO_INT32(aPtr), serialno, aRefcnt); + nsTraceRefcnt::WalkTheStack(gRefcntsLog); + fflush(gRefcntsLog); } } UNLOCK_TRACELOG(); @@ -1057,11 +1058,11 @@ NS_LogRelease(void* aPtr, nsrefcnt aRefcnt, const char* aClazz) (*leakyLogRelease)(aPtr, aRefcnt + 1, aRefcnt); } else { - // Can't use PR_LOG(), b/c it truncates the line - fprintf(gRefcntsLog, - "\n<%s> 0x%08X %" PRIuPTR " Release %" PRIuPTR "\n", aClazz, NS_PTR_TO_INT32(aPtr), serialno, aRefcnt); - nsTraceRefcnt::WalkTheStack(gRefcntsLog); - fflush(gRefcntsLog); + // Can't use PR_LOG(), b/c it truncates the line + fprintf(gRefcntsLog, + "\n<%s> 0x%08X %" PRIuPTR " Release %" PRIuPTR "\n", aClazz, NS_PTR_TO_INT32(aPtr), serialno, aRefcnt); + nsTraceRefcnt::WalkTheStack(gRefcntsLog); + fflush(gRefcntsLog); } } @@ -1111,7 +1112,7 @@ NS_LogCtor(void* aPtr, const char* aType, uint32_t aInstanceSize) bool loggingThisObject = (!gObjectsToLog || LogThisObj(serialno)); if (gAllocLog && loggingThisType && loggingThisObject) { fprintf(gAllocLog, "\n<%s> 0x%08X %" PRIdPTR " Ctor (%d)\n", - aType, NS_PTR_TO_INT32(aPtr), serialno, aInstanceSize); + aType, NS_PTR_TO_INT32(aPtr), serialno, aInstanceSize); nsTraceRefcnt::WalkTheStack(gAllocLog); } @@ -1152,7 +1153,7 @@ NS_LogDtor(void* aPtr, const char* aType, uint32_t aInstanceSize) // using LogDeleteXPCOM instead to get file and line numbers.) if (gAllocLog && loggingThisType && loggingThisObject) { fprintf(gAllocLog, "\n<%s> 0x%08X %" PRIdPTR " Dtor (%d)\n", - aType, NS_PTR_TO_INT32(aPtr), serialno, aInstanceSize); + aType, NS_PTR_TO_INT32(aPtr), serialno, aInstanceSize); nsTraceRefcnt::WalkTheStack(gAllocLog); } diff --git a/xpcom/base/nsTraceRefcnt.h b/xpcom/base/nsTraceRefcnt.h index 81f546e24c9d..8822d9519b6c 100644 --- a/xpcom/base/nsTraceRefcnt.h +++ b/xpcom/base/nsTraceRefcnt.h @@ -1,4 +1,5 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ @@ -20,13 +21,13 @@ public: }; static nsresult DumpStatistics(StatisticsType type = ALL_STATS, - FILE* out = 0); + FILE* out = 0); static void ResetStatistics(void); static void DemangleSymbol(const char * aSymbol, - char * aBuffer, - int aBufLen); + char * aBuffer, + int aBufLen); static void WalkTheStack(FILE* aStream); /** diff --git a/xpcom/base/nsUUIDGenerator.cpp b/xpcom/base/nsUUIDGenerator.cpp index edc9d1c3103d..717b5d300af4 100644 --- a/xpcom/base/nsUUIDGenerator.cpp +++ b/xpcom/base/nsUUIDGenerator.cpp @@ -1,4 +1,5 @@ -/* -*- Mode: C++; tab-width: 50; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ @@ -20,7 +21,7 @@ using namespace mozilla; NS_IMPL_ISUPPORTS(nsUUIDGenerator, nsIUUIDGenerator) nsUUIDGenerator::nsUUIDGenerator() - : mLock("nsUUIDGenerator.mLock") + : mLock("nsUUIDGenerator.mLock") { } @@ -31,130 +32,130 @@ nsUUIDGenerator::~nsUUIDGenerator() nsresult nsUUIDGenerator::Init() { - // We're a service, so we're guaranteed that Init() is not going - // to be reentered while we're inside Init(). - + // We're a service, so we're guaranteed that Init() is not going + // to be reentered while we're inside Init(). + #if !defined(XP_WIN) && !defined(XP_MACOSX) && !defined(ANDROID) - /* initialize random number generator using NSPR random noise */ - unsigned int seed; + /* initialize random number generator using NSPR random noise */ + unsigned int seed; - size_t bytes = 0; - while (bytes < sizeof(seed)) { - size_t nbytes = PR_GetRandomNoise(((unsigned char *)&seed)+bytes, - sizeof(seed)-bytes); - if (nbytes == 0) { - return NS_ERROR_FAILURE; - } - bytes += nbytes; + size_t bytes = 0; + while (bytes < sizeof(seed)) { + size_t nbytes = PR_GetRandomNoise(((unsigned char *)&seed)+bytes, + sizeof(seed)-bytes); + if (nbytes == 0) { + return NS_ERROR_FAILURE; } + bytes += nbytes; + } - /* Initialize a new RNG state, and immediately switch - * back to the previous one -- we want to use mState - * only for our own calls to random(). - */ - mSavedState = initstate(seed, mState, sizeof(mState)); - setstate(mSavedState); + /* Initialize a new RNG state, and immediately switch + * back to the previous one -- we want to use mState + * only for our own calls to random(). + */ + mSavedState = initstate(seed, mState, sizeof(mState)); + setstate(mSavedState); - mRBytes = 4; + mRBytes = 4; #ifdef RAND_MAX - if ((unsigned long) RAND_MAX < (unsigned long)0xffffffff) - mRBytes = 3; - if ((unsigned long) RAND_MAX < (unsigned long)0x00ffffff) - mRBytes = 2; - if ((unsigned long) RAND_MAX < (unsigned long)0x0000ffff) - mRBytes = 1; - if ((unsigned long) RAND_MAX < (unsigned long)0x000000ff) - return NS_ERROR_FAILURE; + if ((unsigned long) RAND_MAX < (unsigned long)0xffffffff) + mRBytes = 3; + if ((unsigned long) RAND_MAX < (unsigned long)0x00ffffff) + mRBytes = 2; + if ((unsigned long) RAND_MAX < (unsigned long)0x0000ffff) + mRBytes = 1; + if ((unsigned long) RAND_MAX < (unsigned long)0x000000ff) + return NS_ERROR_FAILURE; #endif #endif /* non XP_WIN and non XP_MACOSX */ - return NS_OK; + return NS_OK; } NS_IMETHODIMP nsUUIDGenerator::GenerateUUID(nsID** ret) { - nsID *id = static_cast(NS_Alloc(sizeof(nsID))); - if (id == nullptr) - return NS_ERROR_OUT_OF_MEMORY; + nsID *id = static_cast(NS_Alloc(sizeof(nsID))); + if (id == nullptr) + return NS_ERROR_OUT_OF_MEMORY; - nsresult rv = GenerateUUIDInPlace(id); - if (NS_FAILED(rv)) { - NS_Free(id); - return rv; - } - - *ret = id; + nsresult rv = GenerateUUIDInPlace(id); + if (NS_FAILED(rv)) { + NS_Free(id); return rv; + } + + *ret = id; + return rv; } NS_IMETHODIMP nsUUIDGenerator::GenerateUUIDInPlace(nsID* id) { - // The various code in this method is probably not threadsafe, so lock - // across the whole method. - MutexAutoLock lock(mLock); + // The various code in this method is probably not threadsafe, so lock + // across the whole method. + MutexAutoLock lock(mLock); #if defined(XP_WIN) - HRESULT hr = CoCreateGuid((GUID*)id); - if (FAILED(hr)) - return NS_ERROR_FAILURE; + HRESULT hr = CoCreateGuid((GUID*)id); + if (FAILED(hr)) + return NS_ERROR_FAILURE; #elif defined(XP_MACOSX) - CFUUIDRef uuid = CFUUIDCreate(kCFAllocatorDefault); - if (!uuid) - return NS_ERROR_FAILURE; + CFUUIDRef uuid = CFUUIDCreate(kCFAllocatorDefault); + if (!uuid) + return NS_ERROR_FAILURE; - CFUUIDBytes bytes = CFUUIDGetUUIDBytes(uuid); - memcpy(id, &bytes, sizeof(nsID)); + CFUUIDBytes bytes = CFUUIDGetUUIDBytes(uuid); + memcpy(id, &bytes, sizeof(nsID)); - CFRelease(uuid); + CFRelease(uuid); #else /* not windows or OS X; generate randomness using random(). */ - /* XXX we should be saving the return of setstate here and switching - * back to it; instead, we use the value returned when we called - * initstate, since older glibc's have broken setstate() return values - */ + /* XXX we should be saving the return of setstate here and switching + * back to it; instead, we use the value returned when we called + * initstate, since older glibc's have broken setstate() return values + */ #ifndef ANDROID - setstate(mState); + setstate(mState); #endif - size_t bytesLeft = sizeof(nsID); - while (bytesLeft > 0) { + size_t bytesLeft = sizeof(nsID); + while (bytesLeft > 0) { #ifdef ANDROID - long rval = arc4random(); - const size_t mRBytes = 4; + long rval = arc4random(); + const size_t mRBytes = 4; #else - long rval = random(); + long rval = random(); #endif - uint8_t *src = (uint8_t*)&rval; - // We want to grab the mRBytes least significant bytes of rval, since - // mRBytes less than sizeof(rval) means the high bytes are 0. + uint8_t *src = (uint8_t*)&rval; + // We want to grab the mRBytes least significant bytes of rval, since + // mRBytes less than sizeof(rval) means the high bytes are 0. #ifdef IS_BIG_ENDIAN - src += sizeof(rval) - mRBytes; + src += sizeof(rval) - mRBytes; #endif - uint8_t *dst = ((uint8_t*) id) + (sizeof(nsID) - bytesLeft); - size_t toWrite = (bytesLeft < mRBytes ? bytesLeft : mRBytes); - for (size_t i = 0; i < toWrite; i++) - dst[i] = src[i]; + uint8_t *dst = ((uint8_t*) id) + (sizeof(nsID) - bytesLeft); + size_t toWrite = (bytesLeft < mRBytes ? bytesLeft : mRBytes); + for (size_t i = 0; i < toWrite; i++) + dst[i] = src[i]; - bytesLeft -= toWrite; - } + bytesLeft -= toWrite; + } - /* Put in the version */ - id->m2 &= 0x0fff; - id->m2 |= 0x4000; + /* Put in the version */ + id->m2 &= 0x0fff; + id->m2 |= 0x4000; - /* Put in the variant */ - id->m3[0] &= 0x3f; - id->m3[0] |= 0x80; + /* Put in the variant */ + id->m3[0] &= 0x3f; + id->m3[0] |= 0x80; #ifndef ANDROID - /* Restore the previous RNG state */ - setstate(mSavedState); + /* Restore the previous RNG state */ + setstate(mSavedState); #endif #endif - return NS_OK; + return NS_OK; } diff --git a/xpcom/base/nsUUIDGenerator.h b/xpcom/base/nsUUIDGenerator.h index 62d059325a51..d59745b9ae34 100644 --- a/xpcom/base/nsUUIDGenerator.h +++ b/xpcom/base/nsUUIDGenerator.h @@ -1,4 +1,5 @@ -/* -*- Mode: C++; tab-width: 50; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ @@ -13,24 +14,24 @@ class nsUUIDGenerator MOZ_FINAL : public nsIUUIDGenerator { public: - nsUUIDGenerator(); + nsUUIDGenerator(); - NS_DECL_THREADSAFE_ISUPPORTS + NS_DECL_THREADSAFE_ISUPPORTS - NS_DECL_NSIUUIDGENERATOR + NS_DECL_NSIUUIDGENERATOR - nsresult Init(); + nsresult Init(); private: - ~nsUUIDGenerator(); + ~nsUUIDGenerator(); protected: - mozilla::Mutex mLock; + mozilla::Mutex mLock; #if !defined(XP_WIN) && !defined(XP_MACOSX) && !defined(ANDROID) - char mState[128]; - char *mSavedState; - uint8_t mRBytes; + char mState[128]; + char *mSavedState; + uint8_t mRBytes; #endif }; diff --git a/xpcom/base/nsVersionComparatorImpl.cpp b/xpcom/base/nsVersionComparatorImpl.cpp index 0f49ba78905a..5773f265b6a4 100644 --- a/xpcom/base/nsVersionComparatorImpl.cpp +++ b/xpcom/base/nsVersionComparatorImpl.cpp @@ -1,3 +1,5 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ @@ -10,10 +12,10 @@ NS_IMPL_ISUPPORTS(nsVersionComparatorImpl, nsIVersionComparator) NS_IMETHODIMP nsVersionComparatorImpl::Compare(const nsACString& A, const nsACString& B, - int32_t *aResult) + int32_t *aResult) { *aResult = mozilla::CompareVersions(PromiseFlatCString(A).get(), - PromiseFlatCString(B).get()); + PromiseFlatCString(B).get()); return NS_OK; } diff --git a/xpcom/base/nsWindowsHelpers.h b/xpcom/base/nsWindowsHelpers.h index 411ab2106cab..4a3740b69b6d 100644 --- a/xpcom/base/nsWindowsHelpers.h +++ b/xpcom/base/nsWindowsHelpers.h @@ -1,3 +1,5 @@ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ @@ -125,63 +127,63 @@ typedef nsAutoRef nsModuleHandle; namespace { - bool - IsRunningInWindowsMetro() - { - static bool alreadyChecked = false; - static bool isMetro = false; - if (alreadyChecked) { - return isMetro; - } - - HMODULE user32DLL = LoadLibraryW(L"user32.dll"); - if (!user32DLL) { - return false; - } - - typedef BOOL (WINAPI* IsImmersiveProcessFunc)(HANDLE process); - IsImmersiveProcessFunc IsImmersiveProcessPtr = - (IsImmersiveProcessFunc)GetProcAddress(user32DLL, - "IsImmersiveProcess"); - FreeLibrary(user32DLL); - if (!IsImmersiveProcessPtr) { - // isMetro is already set to false. - alreadyChecked = true; - return false; - } - - isMetro = IsImmersiveProcessPtr(GetCurrentProcess()); - alreadyChecked = true; +bool +IsRunningInWindowsMetro() +{ + static bool alreadyChecked = false; + static bool isMetro = false; + if (alreadyChecked) { return isMetro; } - HMODULE - LoadLibrarySystem32(LPCWSTR module) - { - WCHAR systemPath[MAX_PATH + 1] = { L'\0' }; - - // If GetSystemPath fails we accept that we'll load the DLLs from the - // normal search path. - GetSystemDirectoryW(systemPath, MAX_PATH + 1); - size_t systemDirLen = wcslen(systemPath); - - // Make the system directory path terminate with a slash - if (systemDirLen && systemPath[systemDirLen - 1] != L'\\') { - systemPath[systemDirLen] = L'\\'; - ++systemDirLen; - // No need to re-nullptr terminate - } - - size_t fileLen = wcslen(module); - wcsncpy(systemPath + systemDirLen, module, - MAX_PATH - systemDirLen); - if (systemDirLen + fileLen <= MAX_PATH) { - systemPath[systemDirLen + fileLen] = L'\0'; - } else { - systemPath[MAX_PATH] = L'\0'; - } - return LoadLibraryW(systemPath); + HMODULE user32DLL = LoadLibraryW(L"user32.dll"); + if (!user32DLL) { + return false; } + + typedef BOOL (WINAPI* IsImmersiveProcessFunc)(HANDLE process); + IsImmersiveProcessFunc IsImmersiveProcessPtr = + (IsImmersiveProcessFunc)GetProcAddress(user32DLL, + "IsImmersiveProcess"); + FreeLibrary(user32DLL); + if (!IsImmersiveProcessPtr) { + // isMetro is already set to false. + alreadyChecked = true; + return false; + } + + isMetro = IsImmersiveProcessPtr(GetCurrentProcess()); + alreadyChecked = true; + return isMetro; +} + +HMODULE +LoadLibrarySystem32(LPCWSTR module) +{ + WCHAR systemPath[MAX_PATH + 1] = { L'\0' }; + + // If GetSystemPath fails we accept that we'll load the DLLs from the + // normal search path. + GetSystemDirectoryW(systemPath, MAX_PATH + 1); + size_t systemDirLen = wcslen(systemPath); + + // Make the system directory path terminate with a slash + if (systemDirLen && systemPath[systemDirLen - 1] != L'\\') { + systemPath[systemDirLen] = L'\\'; + ++systemDirLen; + // No need to re-nullptr terminate + } + + size_t fileLen = wcslen(module); + wcsncpy(systemPath + systemDirLen, module, + MAX_PATH - systemDirLen); + if (systemDirLen + fileLen <= MAX_PATH) { + systemPath[systemDirLen + fileLen] = L'\0'; + } else { + systemPath[MAX_PATH] = L'\0'; + } + return LoadLibraryW(systemPath); +} } #endif diff --git a/xpcom/base/nscore.h b/xpcom/base/nscore.h index b7dd53770595..6f9387ad6ecb 100644 --- a/xpcom/base/nscore.h +++ b/xpcom/base/nscore.h @@ -1,4 +1,5 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ @@ -315,11 +316,11 @@ typedef MozRefCountType nsrefcnt; #define NS_STRINGIFY_HELPER(x_) #x_ #define NS_STRINGIFY(x_) NS_STRINGIFY_HELPER(x_) - /* - * If we're being linked as standalone glue, we don't want a dynamic - * dependency on NSPR libs, so we skip the debug thread-safety - * checks, and we cannot use the THREADSAFE_ISUPPORTS macros. - */ +/* + * If we're being linked as standalone glue, we don't want a dynamic + * dependency on NSPR libs, so we skip the debug thread-safety + * checks, and we cannot use the THREADSAFE_ISUPPORTS macros. + */ #if defined(XPCOM_GLUE) && !defined(XPCOM_GLUE_USE_NSPR) #define XPCOM_GLUE_AVOID_NSPR #endif