Bug 995730 - Change xpcom/base/ to use 2 space indentation

This also removes trailing whitespace in reindented files.
This commit is contained in:
Birunthan Mohanathas 2014-05-05 20:30:39 +03:00
parent 77b3fc0b0b
commit 8f4f3e6fea
45 changed files with 5575 additions and 5541 deletions

View File

@ -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<intptr_t>(VirtualAllocHook),
(void**) &sVirtualAllocOrig);
reinterpret_cast<intptr_t>(VirtualAllocHook),
(void**) &sVirtualAllocOrig);
sKernel32Intercept.AddHook("MapViewOfFile",
reinterpret_cast<intptr_t>(MapViewOfFileHook),
(void**) &sMapViewOfFileOrig);
reinterpret_cast<intptr_t>(MapViewOfFileHook),
(void**) &sMapViewOfFileOrig);
sGdi32Intercept.Init("Gdi32.dll");
sGdi32Intercept.AddHook("CreateDIBSection",
reinterpret_cast<intptr_t>(CreateDIBSectionHook),
(void**) &sCreateDIBSectionOrig);
reinterpret_cast<intptr_t>(CreateDIBSectionHook),
(void**) &sCreateDIBSectionOrig);
}
sInitialized = true;

View File

@ -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<NoteWeakMapsTracer* >(trc);
@ -691,7 +691,7 @@ CycleCollectedJSRuntime::TraverseZone(JS::Zone* aZone,
CycleCollectedJSRuntime::TraverseObjectShim(void* aData, void* aThing)
{
TraverseObjectShimClosure* closure =
static_cast<TraverseObjectShimClosure*>(aData);
static_cast<TraverseObjectShimClosure*>(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

View File

@ -146,8 +146,8 @@ private:
}
enum TraverseSelect {
TRAVERSE_CPP,
TRAVERSE_FULL
TRAVERSE_CPP,
TRAVERSE_FULL
};
void

View File

@ -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 T>
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<T>& operator=(T* rhs)
{
Assign(rhs);
return *this;
}
StaticAutoPtr<T>& 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<T> &other);
StaticAutoPtr(StaticAutoPtr<T> &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<class T>

View File

@ -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()

View File

@ -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

View File

@ -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<RecordBatch *>(
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;
}

View File

@ -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)

View File

@ -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:

File diff suppressed because it is too large Load Diff

View File

@ -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 T>
class nsAutoRef : public nsAutoRefBase<T>
{
protected:
typedef nsAutoRef<T> ThisClass;
typedef nsAutoRefBase<T> BaseClass;
typedef nsSimpleRef<T> SimpleRef;
typedef typename BaseClass::RawRefOnly RawRefOnly;
typedef typename BaseClass::LocalSimpleRef LocalSimpleRef;
typedef nsAutoRef<T> ThisClass;
typedef nsAutoRefBase<T> BaseClass;
typedef nsSimpleRef<T> 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<T> function return value, which expects
// to give up ownership, transfers ownership.
// (nsReturnRef<T> is converted to const nsReturningRef<T>.)
explicit nsAutoRef(const nsReturningRef<T>& aReturning)
: BaseClass(aReturning)
{
}
// Construction from a nsReturnRef<T> function return value, which expects
// to give up ownership, transfers ownership.
// (nsReturnRef<T> is converted to const nsReturningRef<T>.)
explicit nsAutoRef(const nsReturningRef<T>& 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<T>& aReturning)
{
BaseClass::steal(aReturning.mReturnRef);
return *this;
}
ThisClass& operator=(const nsReturningRef<T>& aReturning)
{
BaseClass::steal(aReturning.mReturnRef);
return *this;
}
// Conversion to a raw reference allow the nsAutoRef<T> to often be used
// like a raw reference.
operator typename SimpleRef::RawRef() const
{
return this->get();
}
// Conversion to a raw reference allow the nsAutoRef<T> 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<T> out()
{
return nsReturnRef<T>(this->disown());
}
// Pass out the reference for a function return values.
nsReturnRef<T> out()
{
return nsReturnRef<T>(this->disown());
}
// operator->() and disown() are provided by nsAutoRefBase<T>.
// The default nsSimpleRef<T> provides get().
// operator->() and disown() are provided by nsAutoRefBase<T>.
// The default nsSimpleRef<T> provides get().
private:
// No copy constructor
explicit nsAutoRef(ThisClass& aRefToSteal);
// No copy constructor
explicit nsAutoRef(ThisClass& aRefToSteal);
};
/**
@ -232,68 +232,68 @@ template <class T>
class nsCountedRef : public nsAutoRef<T>
{
protected:
typedef nsCountedRef<T> ThisClass;
typedef nsAutoRef<T> BaseClass;
typedef nsSimpleRef<T> SimpleRef;
typedef typename BaseClass::RawRef RawRef;
typedef nsCountedRef<T> ThisClass;
typedef nsAutoRef<T> BaseClass;
typedef nsSimpleRef<T> 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<T>& aReturning)
: BaseClass(aReturning)
{
}
ThisClass& operator=(const nsReturningRef<T>& 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<T>& aReturning)
: BaseClass(aReturning)
{
}
ThisClass& operator=(const nsReturningRef<T>& 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 T>
class nsReturnRef : public nsAutoRefBase<T>
{
protected:
typedef nsAutoRefBase<T> BaseClass;
typedef typename BaseClass::RawRefOnly RawRefOnly;
typedef nsAutoRefBase<T> 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<T>& aRefToSteal)
: BaseClass(aRefToSteal)
{
}
// Copy construction transfers ownership
nsReturnRef(nsReturnRef<T>& aRefToSteal)
: BaseClass(aRefToSteal)
{
}
nsReturnRef(const nsReturningRef<T>& aReturning)
: BaseClass(aReturning)
{
}
nsReturnRef(const nsReturningRef<T>& 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<T> function return value to a
// smart reference.
operator nsReturningRef<T>()
{
return nsReturningRef<T>(*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<T> function return value to a
// smart reference.
operator nsReturningRef<T>()
{
return nsReturningRef<T>(*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 T>
class nsReturningRef
{
private:
friend class nsReturnRef<T>;
friend class nsReturnRef<T>;
explicit nsReturningRef(nsReturnRef<T>& aReturnRef)
: mReturnRef(aReturnRef)
{
}
explicit nsReturningRef(nsReturnRef<T>& aReturnRef)
: mReturnRef(aReturnRef)
{
}
public:
nsReturnRef<T>& mReturnRef;
nsReturnRef<T>& mReturnRef;
};
/**
@ -464,10 +464,10 @@ template <class T>
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 T>
class nsSimpleRef : protected nsAutoRefTraits<T>
{
protected:
// The default implementation uses nsAutoRefTrait<T>.
// Specializations need not define this typedef.
typedef nsAutoRefTraits<T> 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<T>.
// Specializations need not define this typedef.
typedef nsAutoRefTraits<T> 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 T>
class nsAutoRefBase : public nsSimpleRef<T>
{
protected:
typedef nsAutoRefBase<T> ThisClass;
typedef nsSimpleRef<T> SimpleRef;
typedef typename SimpleRef::RawRef RawRef;
typedef nsAutoRefBase<T> ThisClass;
typedef nsSimpleRef<T> 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<T>& aReturning)
: SimpleRef(aReturning.mReturnRef.disown())
{
}
~nsAutoRefBase()
{
SafeRelease();
}
// An internal class providing access to protected nsSimpleRef<T>
// 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<T>& aReturning)
: SimpleRef(aReturning.mReturnRef.disown())
{
}
~nsAutoRefBase()
{
SafeRelease();
}
// An internal class providing access to protected nsSimpleRef<T>
// 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<T>::out() for return values, or an
// nsAutoRef<T> 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<T>::out() for return values, or an
// nsAutoRef<T> 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_)

View File

@ -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()
{
}

View File

@ -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__ */

View File

@ -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<nsConsoleService> mConsole;
nsRefPtr<nsConsoleService> 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<nsIConsoleMessage> mMessage;
nsRefPtr<nsConsoleService> mService;
nsCOMPtr<nsIConsoleMessage> mMessage;
nsRefPtr<nsConsoleService> mService;
};
typedef nsCOMArray<nsIConsoleListener> ListenerArrayType;
@ -123,29 +124,29 @@ PLDHashOperator
CollectCurrentListeners(nsISupports* aKey, nsIConsoleListener* aValue,
void* closure)
{
ListenerArrayType* listeners = static_cast<ListenerArrayType*>(closure);
listeners->AppendObject(aValue);
return PL_DHASH_NEXT;
ListenerArrayType* listeners = static_cast<ListenerArrayType*>(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<nsIConsoleListener> listeners;
mService->EnumerateListeners(CollectCurrentListeners, &listeners);
// Snapshot of listeners so that we don't reenter this hash during
// enumeration.
nsCOMArray<nsIConsoleListener> 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<LogMessageRunnable> r;
nsIConsoleMessage *retiredMessage;
nsRefPtr<LogMessageRunnable> 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<nsConsoleMessage> msg(new nsConsoleMessage(message));
return this->LogMessage(msg);
nsRefPtr<nsConsoleMessage> 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<nsISupports> canonical = do_QueryInterface(listener);
nsCOMPtr<nsISupports> 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<nsISupports> canonical = do_QueryInterface(listener);
nsCOMPtr<nsISupports> 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;
}

View File

@ -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<nsISupportsHashKey, nsIConsoleListener> ListenerHash;
void EnumerateListeners(ListenerHash::EnumReadFunction aFunction, void* aClosure);
typedef nsInterfaceHashtable<nsISupportsHashKey, nsIConsoleListener> 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__ */

View File

@ -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);

View File

@ -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);
}

File diff suppressed because it is too large Load Diff

View File

@ -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

View File

@ -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);
};

View File

@ -49,7 +49,7 @@ using namespace mozilla;
static Atomic<int> 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;

View File

@ -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

View File

@ -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)

View File

@ -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<nsErrorService> serv = new nsErrorService();
return serv->QueryInterface(aIID, aInstancePtr);
if (NS_WARN_IF(outer))
return NS_ERROR_NO_AGGREGATION;
nsRefPtr<nsErrorService> 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;
}
////////////////////////////////////////////////////////////////////////////////

View File

@ -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__

View File

@ -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[_<type>](method, [type,] member);
NS_IMPL_[CLASS_]SETTER[_<type>](method, [type,] member);
NS_IMPL_[CLASS_]GETSET[_<type>]([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
*/

View File

@ -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) {

View File

@ -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<nsIObserverService> os = mozilla::services::GetObserverService();
if (os) {
nsCOMPtr<nsIObserverService> 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<nsISimpleEnumerator> e;
os->EnumerateObservers("memory-pressure", getter_AddRefs(e));
nsCOMPtr<nsISimpleEnumerator> e;
os->EnumerateObservers("memory-pressure", getter_AddRefs(e));
if ( e ) {
nsCOMPtr<nsIObserver> observer;
bool loop = true;
if ( e ) {
nsCOMPtr<nsIObserver> observer;
bool loop = true;
while (NS_SUCCEEDED(e->HasMoreElements(&loop)) && loop)
{
nsCOMPtr<nsISupports> supports;
e->GetNext(getter_AddRefs(supports));
while (NS_SUCCEEDED(e->HasMoreElements(&loop)) && loop)
{
nsCOMPtr<nsISupports> 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<bool>
@ -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);
}

View File

@ -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<bool> sIsFlushing;
static FlushEvent sFlushEvent;
static PRIntervalTime sLastFlushTime;
static mozilla::Atomic<bool> sIsFlushing;
static FlushEvent sFlushEvent;
static PRIntervalTime sLastFlushTime;
};
#endif // nsMemoryImpl_h__

View File

@ -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<GCAndCCLogDumpRunnable> 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<GCAndCCLogDumpRunnable> 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, "[");

View File

@ -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();

View File

@ -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/. */

View File

@ -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 \

File diff suppressed because it is too large Load Diff

View File

@ -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;
/**

View File

@ -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<nsIFile> 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;

View File

@ -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<nsIFile> 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<char*>(deviceOutput) +
deviceOutput->VendorIdOffset;
}
if (deviceOutput->ProductIdOffset) {
aModel += reinterpret_cast<char*>(deviceOutput) +
deviceOutput->ProductIdOffset;
}
aModel.CompressWhitespace();
if (deviceOutput->ProductRevisionOffset) {
aRevision = reinterpret_cast<char*>(deviceOutput) +
deviceOutput->ProductRevisionOffset;
aRevision.CompressWhitespace();
}
nsCOMPtr<nsIFile> 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<char*>(deviceOutput) +
deviceOutput->VendorIdOffset;
}
if (deviceOutput->ProductIdOffset) {
aModel += reinterpret_cast<char*>(deviceOutput) +
deviceOutput->ProductIdOffset;
}
aModel.CompressWhitespace();
if (deviceOutput->ProductRevisionOffset) {
aRevision = reinterpret_cast<char*>(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

View File

@ -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"

View File

@ -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<serialNumberRecord*>(he->value));
PR_Free(he);
}
if (flag == HT_FREE_ENTRY) {
PR_Free(reinterpret_cast<serialNumberRecord*>(he->value));
PR_Free(he);
}
}
static void
TypesToLogFreeEntry(void *pool, PLHashEntry *he, unsigned flag)
{
if (flag == HT_FREE_ENTRY) {
free(const_cast<char*>(reinterpret_cast<const char*>(he->key)));
PR_Free(he);
}
if (flag == HT_FREE_ENTRY) {
free(const_cast<char*>(reinterpret_cast<const char*>(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<BloatEntry*>(he->value);
delete entry;
PR_Free(he);
}
if (flag == HT_FREE_ENTRY) {
BloatEntry* entry = reinterpret_cast<BloatEntry*>(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<serialNumberRecord *>(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 <BloatEntry*, BloatEntry*> {
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);
}

View File

@ -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);
/**

View File

@ -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<nsID*>(NS_Alloc(sizeof(nsID)));
if (id == nullptr)
return NS_ERROR_OUT_OF_MEMORY;
nsID *id = static_cast<nsID*>(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;
}

View File

@ -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
};

View File

@ -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;
}

View File

@ -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<HMODULE> 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

View File

@ -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