Backed out 10 changesets (bug 1123237) for hazard build failures and Windows test failures

CLOSED TREE

Backed out changeset 9c26b3b787f8 (bug 1123237)
Backed out changeset 1fcec0dc93d5 (bug 1123237)
Backed out changeset 390033ceebb6 (bug 1123237)
Backed out changeset e8a1845876d6 (bug 1123237)
Backed out changeset 714ec40715fa (bug 1123237)
Backed out changeset 5ed952e011c3 (bug 1123237)
Backed out changeset c785df6c0cdf (bug 1123237)
Backed out changeset d69e2d195a24 (bug 1123237)
Backed out changeset 1f328807da1d (bug 1123237)
Backed out changeset a1546857dce9 (bug 1123237)
This commit is contained in:
Phil Ringnalda 2015-09-05 13:49:39 -07:00
parent 4e8b16de83
commit 40ec3df000
37 changed files with 5 additions and 1731 deletions

View File

@ -292,9 +292,6 @@
@RESPATH@/components/layout_xul.xpt
@RESPATH@/components/locale.xpt
@RESPATH@/components/lwbrk.xpt
#ifdef MOZ_ENABLE_PROFILER_SPS
@RESPATH@/components/memory_profiler.xpt
#endif
@RESPATH@/components/migration.xpt
@RESPATH@/components/mimetype.xpt
@RESPATH@/components/mozfind.xpt

View File

@ -276,9 +276,6 @@
@RESPATH@/components/layout_xul.xpt
@RESPATH@/components/locale.xpt
@RESPATH@/components/lwbrk.xpt
#ifdef MOZ_ENABLE_PROFILER_SPS
@RESPATH@/components/memory_profiler.xpt
#endif
@RESPATH@/browser/components/migration.xpt
@RESPATH@/components/mimetype.xpt
@RESPATH@/components/mozfind.xpt

View File

@ -9,7 +9,6 @@
#include "mozilla/Atomics.h"
#include "jsfriendapi.h"
#include "jsgc.h"
#include "gc/Heap.h"
@ -986,8 +985,6 @@ class GCRuntime
GCSchedulingTunables tunables;
GCSchedulingState schedulingState;
MemProfiler mMemProfiler;
private:
// When empty, chunks reside in the emptyChunks pool and are re-used as
// needed or eventually expired if not re-used. The emptyChunks pool gets

View File

@ -17,7 +17,6 @@
#include <stddef.h>
#include <stdint.h>
#include "jsfriendapi.h"
#include "jspubtd.h"
#include "jstypes.h"
#include "jsutil.h"
@ -571,7 +570,6 @@ class FreeList
}
head.checkSpan(thingSize);
JS_EXTRA_POISON(reinterpret_cast<void*>(thing), JS_ALLOCATED_TENURED_PATTERN, thingSize);
MemProfiler::SampleTenured(reinterpret_cast<void*>(thing), thingSize);
return reinterpret_cast<TenuredCell*>(thing);
}
};

View File

@ -2039,6 +2039,7 @@ js::TenuringTracer::moveToTenured(JSObject* src)
CrashAtUnhandlableOOM("Failed to allocate object while tenuring.");
}
JSObject* dst = reinterpret_cast<JSObject*>(t);
tenuredSize += moveObjectToTenured(dst, src, dstKind);
RelocationOverlay* overlay = RelocationOverlay::fromCell(src);
@ -2050,7 +2051,6 @@ js::TenuringTracer::moveToTenured(JSObject* src)
}
TracePromoteToTenured(src, dst);
MemProfiler::MoveNurseryToTenured(src, dst);
return dst;
}

View File

@ -1,48 +0,0 @@
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
* vim: set ts=8 sts=4 et sw=4 tw=99:
* 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/. */
#include "jsfriendapi.h"
#include "vm/Runtime.h"
using js::gc::Cell;
mozilla::Atomic<int> MemProfiler::sActiveProfilerCount;
NativeProfiler* MemProfiler::sNativeProfiler;
GCHeapProfiler*
MemProfiler::GetGCHeapProfiler(void* addr)
{
JSRuntime* runtime = reinterpret_cast<Cell*>(addr)->runtimeFromAnyThread();
return runtime->gc.mMemProfiler.mGCHeapProfiler;
}
GCHeapProfiler*
MemProfiler::GetGCHeapProfiler(JSRuntime* runtime)
{
return runtime->gc.mMemProfiler.mGCHeapProfiler;
}
MemProfiler*
MemProfiler::GetMemProfiler(JSRuntime* runtime)
{
return &runtime->gc.mMemProfiler;
}
void
MemProfiler::start(GCHeapProfiler* aGCHeapProfiler)
{
ReleaseAllJITCode(mRuntime->defaultFreeOp());
mGCHeapProfiler = aGCHeapProfiler;
sActiveProfilerCount++;
}
void
MemProfiler::stop()
{
sActiveProfilerCount--;
mGCHeapProfiler = nullptr;
}

View File

@ -7,12 +7,10 @@
#include "gc/Nursery-inl.h"
#include "mozilla/DebugOnly.h"
#include "mozilla/IntegerPrintfMacros.h"
#include "mozilla/Move.h"
#include "jscompartment.h"
#include "jsfriendapi.h"
#include "jsgc.h"
#include "jsutil.h"
@ -36,7 +34,6 @@ using namespace js;
using namespace gc;
using mozilla::ArrayLength;
using mozilla::DebugOnly;
using mozilla::PodCopy;
using mozilla::PodZero;
@ -235,7 +232,6 @@ js::Nursery::allocate(size_t size)
position_ = position() + size;
JS_EXTRA_POISON(thing, JS_ALLOCATED_NURSERY_PATTERN, size);
MemProfiler::SampleNursery(reinterpret_cast<void*>(thing), size);
return thing;
}
@ -679,7 +675,6 @@ js::Nursery::sweep()
/* Set current start position for isEmpty checks. */
currentStart_ = position();
MemProfiler::SweepNursery(runtime());
}
void

View File

@ -6,7 +6,6 @@
#include "jit/MacroAssembler-inl.h"
#include "jsfriendapi.h"
#include "jsprf.h"
#include "builtin/TypedObject.h"
@ -32,7 +31,7 @@ using JS::GenericNaN;
using JS::ToInt32;
template <typename Source> void
MacroAssembler::guardTypeSet(const Source& address, const TypeSet* types, BarrierKind kind,
MacroAssembler::guardTypeSet(const Source& address, const TypeSet *types, BarrierKind kind,
Register scratch, Label* miss)
{
MOZ_ASSERT(kind == BarrierKind::TypeTagOnly || kind == BarrierKind::TypeSet);
@ -148,7 +147,7 @@ MacroAssembler::guardTypeSetMightBeIncomplete(TypeSet* types, Register obj, Regi
}
void
MacroAssembler::guardObjectType(Register obj, const TypeSet* types,
MacroAssembler::guardObjectType(Register obj, const TypeSet *types,
Register scratch, Label* miss)
{
MOZ_ASSERT(!types->unknown());
@ -1054,9 +1053,8 @@ MacroAssembler::checkUnboxedArrayCapacity(Register obj, const Int32Key& index, R
void
MacroAssembler::checkAllocatorState(Label* fail)
{
// Don't execute the inline path if we are tracing allocations,
// or when the memory profiler is enabled.
if (js::gc::TraceEnabled() || MemProfiler::enabled())
// Don't execute the inline path if we are tracing allocations.
if (js::gc::TraceEnabled())
jump(fail);
# ifdef JS_GC_ZEAL

View File

@ -7,7 +7,6 @@
#ifndef jsfriendapi_h
#define jsfriendapi_h
#include "mozilla/Atomics.h"
#include "mozilla/Casting.h"
#include "mozilla/MemoryReporting.h"
#include "mozilla/UniquePtr.h"
@ -2845,144 +2844,4 @@ JS_StoreStringPostBarrierCallback(JSContext* cx,
extern JS_FRIEND_API(void)
JS_ClearAllPostBarrierCallbacks(JSRuntime *rt);
class NativeProfiler
{
public:
virtual ~NativeProfiler() {};
virtual void sampleNative(void* addr, uint32_t size) = 0;
virtual void removeNative(void* addr) = 0;
virtual void reset() = 0;
};
class GCHeapProfiler
{
public:
virtual ~GCHeapProfiler() {};
virtual void sampleTenured(void* addr, uint32_t size) = 0;
virtual void sampleNursery(void* addr, uint32_t size) = 0;
virtual void markTenuredStart() = 0;
virtual void markTenured(void* addr) = 0;
virtual void sweepTenured() = 0;
virtual void sweepNursery() = 0;
virtual void moveNurseryToTenured(void* addrOld, void* addrNew) = 0;
virtual void reset() = 0;
};
class MemProfiler
{
static mozilla::Atomic<int> sActiveProfilerCount;
static NativeProfiler* sNativeProfiler;
static GCHeapProfiler* GetGCHeapProfiler(void* addr);
static GCHeapProfiler* GetGCHeapProfiler(JSRuntime* runtime);
static NativeProfiler* GetNativeProfiler() {
return sNativeProfiler;
}
GCHeapProfiler* mGCHeapProfiler;
JSRuntime* mRuntime;
public:
explicit MemProfiler(JSRuntime* aRuntime) : mGCHeapProfiler(nullptr), mRuntime(aRuntime) {}
void start(GCHeapProfiler* aGCHeapProfiler);
void stop();
GCHeapProfiler* getGCHeapProfiler() const {
return mGCHeapProfiler;
}
static bool enabled() {
return sActiveProfilerCount > 0;
}
static MemProfiler* GetMemProfiler(JSRuntime* runtime);
static void SetNativeProfiler(NativeProfiler* aProfiler) {
sNativeProfiler = aProfiler;
}
static void SampleNative(void* addr, uint32_t size) {
if (MOZ_LIKELY(!enabled()))
return;
NativeProfiler* profiler = GetNativeProfiler();
if (profiler)
profiler->sampleNative(addr, size);
}
static void SampleTenured(void* addr, uint32_t size) {
if (MOZ_LIKELY(!enabled()))
return;
GCHeapProfiler* profiler = GetGCHeapProfiler(addr);
if (profiler)
profiler->sampleTenured(addr, size);
}
static void SampleNursery(void* addr, uint32_t size) {
if (MOZ_LIKELY(!enabled()))
return;
GCHeapProfiler* profiler = GetGCHeapProfiler(addr);
if (profiler)
profiler->sampleNursery(addr, size);
}
static void RemoveNative(void* addr) {
if (MOZ_LIKELY(!enabled()))
return;
NativeProfiler* profiler = GetNativeProfiler();
if (profiler)
profiler->removeNative(addr);
}
static void MarkTenuredStart(JSRuntime* runtime) {
if (MOZ_LIKELY(!enabled()))
return;
GCHeapProfiler* profiler = GetGCHeapProfiler(runtime);
if (profiler)
profiler->markTenuredStart();
}
static void MarkTenured(void* addr) {
if (MOZ_LIKELY(!enabled()))
return;
GCHeapProfiler* profiler = GetGCHeapProfiler(addr);
if (profiler)
profiler->markTenured(addr);
}
static void SweepTenured(JSRuntime* runtime) {
if (MOZ_LIKELY(!enabled()))
return;
GCHeapProfiler* profiler = GetGCHeapProfiler(runtime);
if (profiler)
profiler->sweepTenured();
}
static void SweepNursery(JSRuntime* runtime) {
if (MOZ_LIKELY(!enabled()))
return;
GCHeapProfiler* profiler = GetGCHeapProfiler(runtime);
if (profiler)
profiler->sweepNursery();
}
static void MoveNurseryToTenured(void* addrOld, void* addrNew) {
if (MOZ_LIKELY(!enabled()))
return;
GCHeapProfiler* profiler = GetGCHeapProfiler(addrOld);
if (profiler)
profiler->moveNurseryToTenured(addrOld, addrNew);
}
};
#endif /* jsfriendapi_h */

View File

@ -197,7 +197,6 @@
#include "jsatom.h"
#include "jscntxt.h"
#include "jscompartment.h"
#include "jsfriendapi.h"
#include "jsobj.h"
#include "jsprf.h"
#include "jsscript.h"
@ -487,14 +486,6 @@ Arena::finalize(FreeOp* fop, AllocKind thingKind, size_t thingSize)
FreeSpan* newListTail = &newListHead;
size_t nmarked = 0;
if (MOZ_UNLIKELY(MemProfiler::enabled())) {
for (ArenaCellIterUnderFinalize i(&aheader); !i.done(); i.next()) {
T* t = i.get<T>();
if (t->asTenured().isMarked())
MemProfiler::MarkTenured(reinterpret_cast<void*>(t));
}
}
for (ArenaCellIterUnderFinalize i(&aheader); !i.done(); i.next()) {
T* t = i.get<T>();
if (t->asTenured().isMarked()) {
@ -1108,7 +1099,6 @@ GCRuntime::GCRuntime(JSRuntime* rt) :
stats(rt),
marker(rt),
usage(nullptr),
mMemProfiler(rt),
maxMallocBytes(0),
numArenasFreeCommitted(0),
verifyPreData(nullptr),
@ -3887,7 +3877,6 @@ GCRuntime::beginMarkPhase(JS::gcreason::Reason reason)
zone->arenas.purge();
}
MemProfiler::MarkTenuredStart(rt);
marker.start();
GCMarker* gcmarker = &marker;
@ -5544,7 +5533,6 @@ GCRuntime::finishCollection(JS::gcreason::Reason reason)
MOZ_ASSERT(marker.isDrained());
marker.stop();
clearBufferedGrayRoots();
MemProfiler::SweepTenured(rt);
uint64_t currentTime = PRMJ_Now();
schedulingState.updateHighFrequencyMode(lastGCTime, currentTime, tunables);

View File

@ -172,7 +172,6 @@ UNIFIED_SOURCES += [
'gc/Iteration.cpp',
'gc/Marking.cpp',
'gc/Memory.cpp',
'gc/MemoryProfiler.cpp',
'gc/Nursery.cpp',
'gc/RootMarking.cpp',
'gc/Statistics.cpp',

View File

@ -24,7 +24,6 @@
#include "jsarray.h"
#include "jscntxt.h"
#include "jscpucfg.h"
#include "jsfriendapi.h"
#include "jsnum.h"
#include "jsobj.h"
#include "jstypes.h"
@ -254,7 +253,6 @@ ReleaseAsmJSMappedData(void* base)
}
# endif
# endif
MemProfiler::RemoveNative(base);
}
#else
static void
@ -301,7 +299,6 @@ TransferAsmJSMappedBuffer(JSContext* cx, const CallArgs& args,
return false;
}
# endif
MemProfiler::SampleNative(diffStart, diffLength);
} else if (newByteLength < oldByteLength) {
void* diffStart = data + newByteLength;
size_t diffLength = oldByteLength - newByteLength;
@ -664,14 +661,12 @@ ArrayBufferObject::prepareForAsmJS(JSContext* cx, Handle<ArrayBufferObject*> buf
# ifdef XP_WIN
if (!VirtualAlloc(data, buffer->byteLength(), MEM_COMMIT, PAGE_READWRITE)) {
VirtualFree(data, 0, MEM_RELEASE);
MemProfiler::RemoveNative(data);
return false;
}
# else
size_t validLength = buffer->byteLength();
if (mprotect(data, validLength, PROT_READ | PROT_WRITE)) {
munmap(data, AsmJSMappedSize);
MemProfiler::RemoveNative(data);
return false;
}
# if defined(MOZ_VALGRIND) && defined(VALGRIND_DISABLE_ADDR_ERROR_REPORTING_IN_RANGE)
@ -707,7 +702,6 @@ ArrayBufferObject::BufferContents
ArrayBufferObject::createMappedContents(int fd, size_t offset, size_t length)
{
void* data = AllocateMappedContent(fd, offset, length, ARRAY_BUFFER_ALIGNMENT);
MemProfiler::SampleNative(data, length);
return BufferContents::create<MAPPED>(data);
}
@ -734,7 +728,6 @@ ArrayBufferObject::releaseData(FreeOp* fop)
fop->free_(dataPointer());
break;
case MAPPED:
MemProfiler::RemoveNative(dataPointer());
DeallocateMappedContent(dataPointer(), byteLength());
break;
case ASMJS_MAPPED:
@ -1461,7 +1454,6 @@ JS_CreateMappedArrayBufferContents(int fd, size_t offset, size_t length)
JS_PUBLIC_API(void)
JS_ReleaseMappedArrayBufferContents(void* contents, size_t length)
{
MemProfiler::RemoveNative(contents);
DeallocateMappedContent(contents, length);
}

View File

@ -205,9 +205,6 @@
@BINPATH@/components/layout_xul.xpt
@BINPATH@/components/locale.xpt
@BINPATH@/components/lwbrk.xpt
#ifdef MOZ_ENABLE_PROFILER_SPS
@BINPATH@/components/memory_profiler.xpt
#endif
@BINPATH@/components/migration.xpt
@BINPATH@/components/mimetype.xpt
@BINPATH@/components/mozfind.xpt

View File

@ -1,66 +0,0 @@
/* 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/. */
"use strict";
const { Cc, Ci, Cu } = require("chrome");
let protocol = require("devtools/server/protocol");
let { method, RetVal, Arg, types } = protocol;
const { reportException } = require("devtools/toolkit/DevToolsUtils");
loader.lazyRequireGetter(this, "events", "sdk/event/core");
let MemprofActor = protocol.ActorClass({
typeName: "memprof",
initialize: function(conn) {
protocol.Actor.prototype.initialize.call(this, conn);
this._profiler = Cc["@mozilla.org/tools/memory-profiler;1"]
.getService(Ci.nsIMemoryProfiler);
},
destroy: function() {
this._profiler = null;
protocol.Actor.prototype.destroy.call(this);
},
startProfiler: method(function() {
this._profiler.startProfiler();
}, {
request: {},
response: {}
}),
stopProfiler: method(function() {
this._profiler.stopProfiler();
}, {
request: {},
response: {}
}),
resetProfiler: method(function() {
this._profiler.resetProfiler();
}, {
request: {},
response: {}
}),
getResults: method(function() {
return this._profiler.getResults();
}, {
request: {},
response: {
ret: RetVal("json")
}
})
});
exports.MemprofActor = MemprofActor;
exports.MemprofFront = protocol.FrontClass(MemprofActor, {
initialize: function(client, form) {
protocol.Front.prototype.initialize.call(this, client, form);
this.actorID = form.memprofActor;
this.manage(this);
}
});

View File

@ -493,11 +493,6 @@ var DebuggerServer = {
constructor: "MemoryActor",
type: { tab: true }
});
this.registerModule("devtools/server/actors/memprof", {
prefix: "memprof",
constructor: "MemprofActor",
type: { global: true, tab: true }
});
this.registerModule("devtools/server/actors/framerate", {
prefix: "framerate",
constructor: "FramerateActor",

View File

@ -54,7 +54,6 @@ EXTRA_JS_MODULES.devtools.server.actors += [
'actors/inspector.js',
'actors/layout.js',
'actors/memory.js',
'actors/memprof.js',
'actors/monitor.js',
'actors/object.js',
'actors/performance-entries.js',

View File

@ -15,7 +15,6 @@ support-files =
inspector-traversal-data.html
large-image.jpg
memory-helpers.js
memprof-helpers.js
nonchrome_unsafeDereference.html
small-image.gif
setup-in-child.js
@ -92,7 +91,6 @@ skip-if = buildapp == 'mulet'
[test_memory_census.html]
[test_memory_gc_01.html]
[test_memory_gc_events.html]
[test_memprof.html]
[test_preference.html]
[test_registerActor.html]
[test_settings.html]

View File

@ -1,54 +0,0 @@
let Cu = Components.utils;
let Cc = Components.classes;
let Ci = Components.interfaces;
Cu.import("resource://gre/modules/Services.jsm");
// Always log packets when running tests.
Services.prefs.setBoolPref("devtools.debugger.log", true);
SimpleTest.registerCleanupFunction(function() {
Services.prefs.clearUserPref("devtools.debugger.log");
});
Cu.import("resource://gre/modules/devtools/dbg-client.jsm");
Cu.import("resource://gre/modules/devtools/dbg-server.jsm");
Cu.import("resource://gre/modules/Task.jsm");
Cu.import("resource://gre/modules/devtools/Loader.jsm");
let { require } = devtools;
let { MemprofFront } = require("devtools/server/actors/memprof");
function startServerAndGetSelectedTabMemprof() {
DebuggerServer.init();
DebuggerServer.addBrowserActors();
var client = new DebuggerClient(DebuggerServer.connectPipe());
return new Promise((resolve, reject) => {
client.connect(response => {
if (response.error) {
reject(new Error(response.error + ": " + response.message));
return;
}
client.listTabs(response => {
if (response.error) {
reject(new Error(response.error + ": " + response.message));
return;
}
var form = response.tabs[response.selected];
var memprof = MemprofFront(client, form);
resolve({ memprof, client });
});
});
});
}
function destroyServerAndFinish(client) {
client.close(() => {
DebuggerServer.destroy();
SimpleTest.finish();
});
}

View File

@ -1,71 +0,0 @@
<!DOCTYPE HTML>
<html>
<!--
Bug 1123237 - Test profiling memory allocations.
-->
<head>
<meta charset="utf-8">
<title>Memory profiler actor test</title>
<script type="application/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
<link rel="stylesheet" type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css">
</head>
<body>
<pre id="test">
<script src="memprof-helpers.js" type="application/javascript;version=1.8"></script>
<script>
window.onload = function() {
SimpleTest.waitForExplicitFinish();
Task.spawn(function* () {
var { memprof, client } = yield startServerAndGetSelectedTabMemprof();
yield memprof.startProfiler();
ok(true, "Can start profiling allocations");
// Allocate some objects.
var alloc;
(function memprof_test_outer() {
(function memprof_test_middle() {
(function memprof_test_inner() {
for (i = 0; i < 65535; ++i) {
alloc = {};
}
}());
}());
}());
yield memprof.stopProfiler();
ok(true, "Can stop profiling allocations");
var results = yield memprof.getResults();
ok(true, "Can get results");
function isTestAllocation(name) {
return /memprof_test_inner/.test(name)
|| /memprof_test_middle/.test(name)
|| /memprof_test_outer/.test(name)
}
var testAllocations = results.names.filter(isTestAllocation);
ok(testAllocations.length >= 3, "Should find our 3 test allocations");
// Ensure the allocation traces has the correct index
var inner = results.traces.find(
trace => /memprof_test_inner/.test(results.names[trace.nameIdx]));
ok(inner, "Find the inner most frame");
var middle = results.traces[inner.parentIdx];
ok(/memprof_test_middle/.test(results.names[middle.nameIdx]),
"Find the middle frame");
var outer = results.traces[middle.parentIdx];
ok(/memprof_test_outer/.test(results.names[outer.nameIdx]),
"Find the outer frame");
yield memprof.resetProfiler();
destroyServerAndFinish(client);
});
};
</script>
</pre>
</body>
</html>

View File

@ -124,7 +124,6 @@ if CONFIG['MOZ_JPROF']:
DIRS += [
'/tools/power',
'/tools/profiler',
'/tools/memory-profiler',
'/xpfe/components',
]

View File

@ -1,116 +0,0 @@
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=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/. */
#ifndef memory_profiler_CompactTraceTable_h
#define memory_profiler_CompactTraceTable_h
#include "mozilla/HashFunctions.h"
#include "nsDataHashtable.h"
#include "nsTArray.h"
namespace mozilla {
struct TrieNode final
{
uint32_t parentIdx;
uint32_t nameIdx;
bool operator==(const TrieNode t) const
{
return parentIdx == t.parentIdx && nameIdx == t.nameIdx;
}
uint32_t Hash() const
{
return HashGeneric(parentIdx, nameIdx);
}
};
// This class maps a Node of type T to its parent's index in the
// map. When serializing, the map is traversed and put into an ordered
// array of Nodes.
template<typename KeyClass, typename T>
class NodeIndexMap final
{
public:
uint32_t Insert(const T& e)
{
uint32_t size = mMap.Count();
if (!mMap.Get(e, nullptr)) {
mMap.Put(e, size);
}
return size;
}
nsTArray<T> Serialize() const
{
nsTArray<T> v;
v.SetLength(mMap.Count());
for (auto iter = mMap.ConstIter(); !iter.Done(); iter.Next()) {
v[iter.Data()] = iter.Key();
}
return v;
}
uint32_t Size() const
{
return mMap.Count();
}
void Clear()
{
mMap.Clear();
}
private:
nsDataHashtable<KeyClass, uint32_t> mMap;
};
// Backtraces are stored in a trie to save spaces.
// Function names are stored in an unique table and TrieNodes contain indexes
// into that table.
// The trie is implemented with a hash table; children are stored in
// traces[TrieNode{parent node index, branch/function name index}].
class CompactTraceTable final
{
public:
CompactTraceTable()
{
mNames.Insert(nsAutoCString("(unknown)"));
mTraces.Insert(TrieNode{0, 0});
}
nsTArray<nsCString> GetNames() const
{
return mNames.Serialize();
}
nsTArray<TrieNode> GetTraces() const
{
return mTraces.Serialize();
}
// Returns an ID to a stacktrace.
uint32_t Insert(const nsTArray<nsCString>& aRawStacktrace)
{
uint32_t parent = 0;
for (auto& frame: aRawStacktrace) {
parent = mTraces.Insert(TrieNode{parent, mNames.Insert(frame)});
}
return parent;
}
void Reset()
{
mNames.Clear();
mTraces.Clear();
}
private:
NodeIndexMap<nsCStringHashKey, nsCString> mNames;
NodeIndexMap<nsGenericHashKey<TrieNode>, TrieNode> mTraces;
};
} // namespace mozilla
#endif // memory_profiler_CompactTraceTable_h

View File

@ -1,168 +0,0 @@
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=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/. */
#include "GCHeapProfilerImpl.h"
#include "UncensoredAllocator.h"
namespace mozilla {
GCHeapProfilerImpl::GCHeapProfilerImpl()
{
mLock = PR_NewLock();
mMarking = false;
}
GCHeapProfilerImpl::~GCHeapProfilerImpl()
{
if (mLock) {
PR_DestroyLock(mLock);
}
}
nsTArray<nsCString>
GCHeapProfilerImpl::GetNames() const
{
return mTraceTable.GetNames();
}
nsTArray<TrieNode>
GCHeapProfilerImpl::GetTraces() const
{
return mTraceTable.GetTraces();
}
const nsTArray<AllocEvent>&
GCHeapProfilerImpl::GetEvents() const
{
return mAllocEvents;
}
void
GCHeapProfilerImpl::reset()
{
mTraceTable.Reset();
mAllocEvents.Clear();
mNurseryEntries.Clear();
mTenuredEntriesFG.Clear();
mTenuredEntriesBG.Clear();
}
void
GCHeapProfilerImpl::sampleTenured(void* addr, uint32_t size)
{
SampleInternal(addr, size, mTenuredEntriesFG);
}
void
GCHeapProfilerImpl::sampleNursery(void* addr, uint32_t size)
{
SampleInternal(addr, size, mNurseryEntries);
}
void
GCHeapProfilerImpl::markTenuredStart()
{
AutoUseUncensoredAllocator ua;
AutoMPLock lock(mLock);
if (!mMarking) {
mMarking = true;
mTenuredEntriesFG.SwapElements(mTenuredEntriesBG);
MOZ_ASSERT(mTenuredEntriesFG.Count() == 0);
}
}
void
GCHeapProfilerImpl::markTenured(void* addr)
{
AutoUseUncensoredAllocator ua;
AutoMPLock lock(mLock);
if (mMarking) {
AllocEntry entry;
if (mTenuredEntriesBG.Get(addr, &entry)) {
entry.mMarked = true;
mTenuredEntriesBG.Put(addr, entry);
}
}
}
void
GCHeapProfilerImpl::sweepTenured()
{
AutoUseUncensoredAllocator ua;
AutoMPLock lock(mLock);
if (mMarking) {
mMarking = false;
for (auto iter = mTenuredEntriesBG.Iter(); !iter.Done(); iter.Next()) {
if (iter.Data().mMarked) {
iter.Data().mMarked = false;
mTenuredEntriesFG.Put(iter.Key(), iter.Data());
} else {
AllocEvent& oldEvent = mAllocEvents[iter.Data().mEventIdx];
AllocEvent newEvent(oldEvent.mTraceIdx, -oldEvent.mSize, TimeStamp::Now());
mAllocEvents.AppendElement(newEvent);
}
}
mTenuredEntriesBG.Clear();
}
}
void
GCHeapProfilerImpl::sweepNursery()
{
AutoUseUncensoredAllocator ua;
AutoMPLock lock(mLock);
for (auto iter = mNurseryEntries.Iter(); !iter.Done(); iter.Next()) {
AllocEvent& oldEvent = mAllocEvents[iter.Data().mEventIdx];
AllocEvent newEvent(oldEvent.mTraceIdx, -oldEvent.mSize, TimeStamp::Now());
mAllocEvents.AppendElement(newEvent);
}
mNurseryEntries.Clear();
}
void
GCHeapProfilerImpl::moveNurseryToTenured(void* addrOld, void* addrNew)
{
AutoUseUncensoredAllocator ua;
AutoMPLock lock(mLock);
AllocEntry entryOld;
if (!mNurseryEntries.Get(addrOld, &entryOld)) {
return;
}
// Because the tenured heap is sampled, the address might already be there.
// If not, the address is inserted with the old event.
AllocEntry tenuredEntryOld;
if (!mTenuredEntriesFG.Get(addrNew, &tenuredEntryOld)) {
mTenuredEntriesFG.Put(addrNew, AllocEntry(entryOld.mEventIdx));
} else {
// If it is already inserted, the insertion above will fail and the
// iterator of the already-inserted element is returned.
// We choose to ignore the the new event by setting its size zero and point
// the newly allocated address to the old event.
// An event of size zero will be skipped when reporting.
mAllocEvents[entryOld.mEventIdx].mSize = 0;
tenuredEntryOld.mEventIdx = entryOld.mEventIdx;
mTenuredEntriesFG.Put(addrNew, tenuredEntryOld);
}
mNurseryEntries.Remove(addrOld);
}
void
GCHeapProfilerImpl::SampleInternal(void* aAddr, uint32_t aSize, AllocMap& aTable)
{
AutoUseUncensoredAllocator ua;
AutoMPLock lock(mLock);
size_t nSamples = AddBytesSampled(aSize);
if (nSamples > 0) {
nsTArray<nsCString> trace = GetStacktrace();
AllocEvent ai(mTraceTable.Insert(trace), nSamples * mSampleSize, TimeStamp::Now());
aTable.Put(aAddr, AllocEntry(mAllocEvents.Length()));
mAllocEvents.AppendElement(ai);
}
}
} // namespace mozilla

View File

@ -1,53 +0,0 @@
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=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/. */
#ifndef memory_profiler_GCHeapProfilerImpl_h
#define memory_profiler_GCHeapProfilerImpl_h
#include "CompactTraceTable.h"
#include "MemoryProfiler.h"
#include "jsfriendapi.h"
namespace mozilla {
class GCHeapProfilerImpl final : public GCHeapProfiler
, public ProfilerImpl
{
public:
GCHeapProfilerImpl();
~GCHeapProfilerImpl() override;
nsTArray<nsCString> GetNames() const override;
nsTArray<TrieNode> GetTraces() const override;
const nsTArray<AllocEvent>& GetEvents() const override;
void reset() override;
void sampleTenured(void* addr, uint32_t size) override;
void sampleNursery(void* addr, uint32_t size) override;
void markTenuredStart() override;
void markTenured(void* addr) override;
void sweepTenured() override;
void sweepNursery() override;
void moveNurseryToTenured(void* addrOld, void* addrNew) override;
private:
void SampleInternal(void* addr, uint32_t size, AllocMap& table);
PRLock* mLock;
bool mMarking;
AllocMap mNurseryEntries;
AllocMap mTenuredEntriesFG;
AllocMap mTenuredEntriesBG;
nsTArray<AllocEvent> mAllocEvents;
CompactTraceTable mTraceTable;
};
} // namespace mozilla
#endif // memory_profiler_GCHeapProfilerImpl_h

View File

@ -1,325 +0,0 @@
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=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/. */
#include "MemoryProfiler.h"
#include <cmath>
#include <cstdlib>
#include "mozilla/ClearOnShutdown.h"
#include "mozilla/Move.h"
#include "mozilla/TimeStamp.h"
#include "GCHeapProfilerImpl.h"
#include "GeckoProfiler.h"
#include "NativeProfilerImpl.h"
#include "UncensoredAllocator.h"
#include "js/TypeDecls.h"
#include "jsfriendapi.h"
#include "nsIDOMClassInfo.h"
#include "nsIGlobalObject.h"
#include "prtime.h"
#include "xpcprivate.h"
struct JSRuntime;
namespace mozilla {
#define MEMORY_PROFILER_SAMPLE_SIZE 65536
#define BACKTRACE_BUFFER_SIZE 16384
ProfilerImpl::ProfilerImpl()
: mSampleSize(MEMORY_PROFILER_SAMPLE_SIZE)
{
mLog1minusP = std::log(1.0 - 1.0 / mSampleSize);
mRemainingBytes = std::floor(std::log(1.0 - DRandom()) / mLog1minusP);
}
nsTArray<nsCString>
ProfilerImpl::GetStacktrace()
{
nsTArray<nsCString> trace;
nsAutoArrayPtr<char> output(new char[BACKTRACE_BUFFER_SIZE]);
profiler_get_backtrace_noalloc(output, BACKTRACE_BUFFER_SIZE);
for (const char* p = output; *p; p += strlen(p) + 1) {
trace.AppendElement(nsDependentCString(p));
}
return trace;
}
// Generate a random number in [0, 1).
double
ProfilerImpl::DRandom()
{
return double(((uint64_t(std::rand()) & ((1 << 26) - 1)) << 27) +
(uint64_t(std::rand()) & ((1 << 27) - 1)))
/ (uint64_t(1) << 53);
}
size_t
ProfilerImpl::AddBytesSampled(uint32_t aBytes)
{
size_t nSamples = 0;
while (mRemainingBytes <= aBytes) {
mRemainingBytes += std::floor(std::log(1.0 - DRandom()) / mLog1minusP);
nSamples++;
}
mRemainingBytes -= aBytes;
return nSamples;
}
NS_IMPL_ISUPPORTS(MemoryProfiler, nsIMemoryProfiler)
PRLock* MemoryProfiler::sLock;
uint32_t MemoryProfiler::sProfileRuntimeCount;
StaticAutoPtr<NativeProfilerImpl> MemoryProfiler::sNativeProfiler;
StaticAutoPtr<JSRuntimeProfilerMap> MemoryProfiler::sJSRuntimeProfilerMap;
TimeStamp MemoryProfiler::sStartTime;
void
MemoryProfiler::InitOnce()
{
MOZ_ASSERT(NS_IsMainThread());
static bool initialized = false;
if (!initialized) {
MallocHook::Initialize();
sLock = PR_NewLock();
sProfileRuntimeCount = 0;
sJSRuntimeProfilerMap = new JSRuntimeProfilerMap();
ClearOnShutdown(&sJSRuntimeProfilerMap);
ClearOnShutdown(&sNativeProfiler);
std::srand(PR_Now());
bool ignored;
sStartTime = TimeStamp::ProcessCreation(ignored);
initialized = true;
}
}
NS_IMETHODIMP
MemoryProfiler::StartProfiler()
{
InitOnce();
AutoUseUncensoredAllocator ua;
AutoMPLock lock(sLock);
JSRuntime* runtime = XPCJSRuntime::Get()->Runtime();
ProfilerForJSRuntime profiler;
if (!sJSRuntimeProfilerMap->Get(runtime, &profiler) ||
!profiler.mEnabled) {
if (sProfileRuntimeCount == 0) {
js::EnableRuntimeProfilingStack(runtime, true);
if (!sNativeProfiler) {
sNativeProfiler = new NativeProfilerImpl();
}
MemProfiler::SetNativeProfiler(sNativeProfiler);
}
GCHeapProfilerImpl* gp = new GCHeapProfilerImpl();
profiler.mEnabled = true;
profiler.mProfiler = gp;
sJSRuntimeProfilerMap->Put(runtime, profiler);
MemProfiler::GetMemProfiler(runtime)->start(gp);
if (sProfileRuntimeCount == 0) {
MallocHook::Enable(sNativeProfiler);
}
sProfileRuntimeCount++;
}
return NS_OK;
}
NS_IMETHODIMP
MemoryProfiler::StopProfiler()
{
InitOnce();
AutoUseUncensoredAllocator ua;
AutoMPLock lock(sLock);
JSRuntime* runtime = XPCJSRuntime::Get()->Runtime();
ProfilerForJSRuntime profiler;
if (sJSRuntimeProfilerMap->Get(runtime, &profiler) &&
profiler.mEnabled) {
MemProfiler::GetMemProfiler(runtime)->stop();
if (--sProfileRuntimeCount == 0) {
MallocHook::Disable();
MemProfiler::SetNativeProfiler(nullptr);
js::EnableRuntimeProfilingStack(runtime, false);
}
profiler.mEnabled = false;
sJSRuntimeProfilerMap->Put(runtime, profiler);
}
return NS_OK;
}
NS_IMETHODIMP
MemoryProfiler::ResetProfiler()
{
InitOnce();
AutoUseUncensoredAllocator ua;
AutoMPLock lock(sLock);
JSRuntime* runtime = XPCJSRuntime::Get()->Runtime();
ProfilerForJSRuntime profiler;
if (!sJSRuntimeProfilerMap->Get(runtime, &profiler) ||
!profiler.mEnabled) {
delete profiler.mProfiler;
profiler.mProfiler = nullptr;
sJSRuntimeProfilerMap->Put(runtime, profiler);
}
if (sProfileRuntimeCount == 0) {
sNativeProfiler = nullptr;
}
return NS_OK;
}
struct MergedTraces
{
nsTArray<nsCString> mNames;
nsTArray<TrieNode> mTraces;
nsTArray<AllocEvent> mEvents;
};
// Merge events and corresponding traces and names.
static MergedTraces
MergeResults(const nsTArray<nsCString>& names0,
const nsTArray<TrieNode>& traces0,
const nsTArray<AllocEvent>& events0,
const nsTArray<nsCString>& names1,
const nsTArray<TrieNode>& traces1,
const nsTArray<AllocEvent>& events1)
{
NodeIndexMap<nsCStringHashKey, nsCString> names;
NodeIndexMap<nsGenericHashKey<TrieNode>, TrieNode> traces;
nsTArray<AllocEvent> events;
nsTArray<size_t> names1Tonames0(names1.Length());
nsTArray<size_t> traces1Totraces0(traces1.Length());
// Merge names.
for (auto& i: names0) {
names.Insert(i);
}
for (auto& i: names1) {
names1Tonames0.AppendElement(names.Insert(i));
}
// Merge traces. Note that traces1[i].parentIdx < i for all i > 0.
for (auto& i: traces0) {
traces.Insert(i);
}
traces1Totraces0.AppendElement(0);
for (size_t i = 1; i < traces1.Length(); i++) {
TrieNode node = traces1[i];
node.parentIdx = traces1Totraces0[node.parentIdx];
node.nameIdx = names1Tonames0[node.nameIdx];
traces1Totraces0.AppendElement(traces.Insert(node));
}
// Merge the events according to timestamps.
auto p0 = events0.begin();
auto p1 = events1.begin();
while (p0 != events0.end() && p1 != events1.end()) {
if (p0->mTimestamp < p1->mTimestamp) {
events.AppendElement(*p0++);
} else {
events.AppendElement(*p1++);
events.LastElement().mTraceIdx =
traces1Totraces0[events.LastElement().mTraceIdx];
}
}
while (p0 != events0.end()) {
events.AppendElement(*p0++);
}
while (p1 != events1.end()) {
events.AppendElement(*p1++);
events.LastElement().mTraceIdx =
traces1Totraces0[events.LastElement().mTraceIdx];
}
return MergedTraces{names.Serialize(), traces.Serialize(), Move(events)};
}
NS_IMETHODIMP
MemoryProfiler::GetResults(JSContext* cx, JS::MutableHandle<JS::Value> aResult)
{
InitOnce();
AutoUseUncensoredAllocator ua;
AutoMPLock lock(sLock);
JSRuntime* runtime = XPCJSRuntime::Get()->Runtime();
// Getting results when the profiler is running is not allowed.
if (sProfileRuntimeCount > 0) {
return NS_OK;
}
// Return immediately when native profiler does not exist.
if (!sNativeProfiler) {
return NS_OK;
}
// Return immediately when there's no result in current runtime.
ProfilerForJSRuntime profiler;
if (!sJSRuntimeProfilerMap->Get(runtime, &profiler) ||
!profiler.mProfiler) {
return NS_OK;
}
GCHeapProfilerImpl* gp = profiler.mProfiler;
auto results = MergeResults(gp->GetNames(), gp->GetTraces(), gp->GetEvents(),
sNativeProfiler->GetNames(),
sNativeProfiler->GetTraces(),
sNativeProfiler->GetEvents());
const nsTArray<nsCString>& names = results.mNames;
const nsTArray<TrieNode>& traces = results.mTraces;
const nsTArray<AllocEvent>& events = results.mEvents;
JS::RootedObject jsnames(cx, JS_NewArrayObject(cx, names.Length()));
JS::RootedObject jstraces(cx, JS_NewArrayObject(cx, traces.Length()));
JS::RootedObject jsevents(cx, JS_NewArrayObject(cx, events.Length()));
for (size_t i = 0; i < names.Length(); i++) {
JS::RootedString name(cx, JS_NewStringCopyZ(cx, names[i].get()));
JS_SetElement(cx, jsnames, i, name);
}
for (size_t i = 0; i < traces.Length(); i++) {
JS::RootedObject tn(cx, JS_NewPlainObject(cx));
JS::RootedValue nameIdx(cx, JS_NumberValue(traces[i].nameIdx));
JS::RootedValue parentIdx(cx, JS_NumberValue(traces[i].parentIdx));
JS_SetProperty(cx, tn, "nameIdx", nameIdx);
JS_SetProperty(cx, tn, "parentIdx", parentIdx);
JS_SetElement(cx, jstraces, i, tn);
}
int i = 0;
for (auto ent: events) {
if (ent.mSize == 0) {
continue;
}
MOZ_ASSERT(!sStartTime.IsNull());
double time = (ent.mTimestamp - sStartTime).ToMilliseconds();
JS::RootedObject tn(cx, JS_NewPlainObject(cx));
JS::RootedValue size(cx, JS_NumberValue(ent.mSize));
JS::RootedValue traceIdx(cx, JS_NumberValue(ent.mTraceIdx));
JS::RootedValue timestamp(cx, JS_NumberValue(time));
JS_SetProperty(cx, tn, "size", size);
JS_SetProperty(cx, tn, "traceIdx", traceIdx);
JS_SetProperty(cx, tn, "timestamp", timestamp);
JS_SetElement(cx, jsevents, i++, tn);
}
JS_SetArrayLength(cx, jsevents, i);
JS::RootedObject result(cx, JS_NewPlainObject(cx));
JS::RootedValue objnames(cx, ObjectOrNullValue(jsnames));
JS_SetProperty(cx, result, "names", objnames);
JS::RootedValue objtraces(cx, ObjectOrNullValue(jstraces));
JS_SetProperty(cx, result, "traces", objtraces);
JS::RootedValue objevents(cx, ObjectOrNullValue(jsevents));
JS_SetProperty(cx, result, "events", objevents);
aResult.setObject(*result);
return NS_OK;
}
} // namespace mozilla

View File

@ -1,160 +0,0 @@
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=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/. */
#ifndef tools_profiler_MemoryProfiler_h
#define tools_profiler_MemoryProfiler_h
#include "nsIMemoryProfiler.h"
#include "mozilla/StaticPtr.h"
#include "mozilla/TimeStamp.h"
#include "CompactTraceTable.h"
#include "nsTArray.h"
#include "prlock.h"
#define MEMORY_PROFILER_CID \
{ 0xf976eaa2, 0xcc1f, 0x47ee, \
{ 0x81, 0x29, 0xb8, 0x26, 0x2a, 0x3d, 0xb6, 0xb2 } }
#define MEMORY_PROFILER_CONTRACT_ID "@mozilla.org/tools/memory-profiler;1"
struct JSRuntime;
struct PRLock;
namespace mozilla {
class NativeProfilerImpl;
class GCHeapProfilerImpl;
struct ProfilerForJSRuntime
{
ProfilerForJSRuntime()
: mProfiler(nullptr)
, mEnabled(false)
{}
GCHeapProfilerImpl* mProfiler;
bool mEnabled;
};
using JSRuntimeProfilerMap =
nsDataHashtable<nsClearingPtrHashKey<JSRuntime>, ProfilerForJSRuntime>;
class MemoryProfiler final : public nsIMemoryProfiler
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSIMEMORYPROFILER
private:
static void InitOnce();
~MemoryProfiler() {}
// The accesses to other static member are guarded by sLock and
// sProfileRuntimeCount.
static PRLock* sLock;
static uint32_t sProfileRuntimeCount;
static StaticAutoPtr<NativeProfilerImpl> sNativeProfiler;
static StaticAutoPtr<JSRuntimeProfilerMap> sJSRuntimeProfilerMap;
static TimeStamp sStartTime;
};
// Allocation events to be reported.
struct AllocEvent {
TimeStamp mTimestamp;
// index to a stacktrace singleton.
uint32_t mTraceIdx;
// Allocation size
int32_t mSize;
AllocEvent(uint32_t aTraceIdx, int32_t aSize, TimeStamp aTimestamp)
: mTimestamp(aTimestamp)
, mTraceIdx(aTraceIdx)
, mSize(aSize)
{}
};
// Index to allocation events but also a mark bit to be GC-able.
struct AllocEntry {
uint32_t mEventIdx : 31;
bool mMarked : 1;
// Default constructor for uninitialized stack value required by
// getter methods.
AllocEntry()
: mEventIdx(0)
, mMarked(false)
{}
explicit AllocEntry(int aEventIdx)
: mEventIdx(aEventIdx)
, mMarked(false)
{}
};
using AllocMap = nsDataHashtable<nsClearingVoidPtrHashKey, AllocEntry>;
class ProfilerImpl
{
public:
static nsTArray<nsCString> GetStacktrace();
static double DRandom();
ProfilerImpl();
virtual nsTArray<nsCString> GetNames() const = 0;
virtual nsTArray<TrieNode> GetTraces() const = 0;
virtual const nsTArray<AllocEvent>& GetEvents() const = 0;
protected:
/**
* The sampler generates a random variable which conforms to a geometric
* distribution of probability p = 1 / mSampleSize to calculate the
* next-to-be-sampled byte directly; It avoids rolling a dice on each byte.
*
* Let Bn denote a Bernoulli process with first success on n-th trial, the
* cumulative distribution function of Bn is Cn = 1 - (1 - p) ^ n.
* Let U denote a uniformly distributed random variable in [0, 1).
* A geometric random variable can be generated by Cn's reverse function:
* G = floor(log(1 - U) / log(1 - p)).
*
* @param aSize the number of bytes seen
* @return the number of events sampled
*/
size_t AddBytesSampled(uint32_t aBytes);
uint32_t mSampleSize;
private:
uint32_t mRemainingBytes;
double mLog1minusP;
};
/*
* This class is used to make sure the profile data is only accessed
* on one thread at a time. Don't use mozilla::Mutex because we don't
* want to allocate memory.
*/
class AutoMPLock
{
public:
explicit AutoMPLock(PRLock* aLock)
{
MOZ_ASSERT(aLock);
mLock = aLock;
PR_Lock(mLock);
}
~AutoMPLock()
{
PR_Unlock(mLock);
}
private:
PRLock* mLock;
};
} // namespace mozilla
#endif

View File

@ -1,82 +0,0 @@
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=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/. */
#include "NativeProfilerImpl.h"
#include "UncensoredAllocator.h"
namespace mozilla {
NativeProfilerImpl::NativeProfilerImpl()
{
mLock = PR_NewLock();
}
NativeProfilerImpl::~NativeProfilerImpl()
{
if (mLock) {
PR_DestroyLock(mLock);
}
}
nsTArray<nsCString>
NativeProfilerImpl::GetNames() const
{
return mTraceTable.GetNames();
}
nsTArray<TrieNode>
NativeProfilerImpl::GetTraces() const
{
return mTraceTable.GetTraces();
}
const nsTArray<AllocEvent>&
NativeProfilerImpl::GetEvents() const
{
return mAllocEvents;
}
void
NativeProfilerImpl::reset()
{
mTraceTable.Reset();
mAllocEvents.Clear();
mNativeEntries.Clear();
}
void
NativeProfilerImpl::sampleNative(void* addr, uint32_t size)
{
AutoUseUncensoredAllocator ua;
AutoMPLock lock(mLock);
size_t nSamples = AddBytesSampled(size);
if (nSamples > 0) {
nsTArray<nsCString> trace = GetStacktrace();
AllocEvent ai(mTraceTable.Insert(trace), nSamples * mSampleSize, TimeStamp::Now());
mNativeEntries.Put(addr, AllocEntry(mAllocEvents.Length()));
mAllocEvents.AppendElement(ai);
}
}
void
NativeProfilerImpl::removeNative(void* addr)
{
AutoUseUncensoredAllocator ua;
AutoMPLock lock(mLock);
AllocEntry entry;
if (!mNativeEntries.Get(addr, &entry)) {
return;
}
AllocEvent& oldEvent = mAllocEvents[entry.mEventIdx];
AllocEvent newEvent(oldEvent.mTraceIdx, -oldEvent.mSize, TimeStamp::Now());
mAllocEvents.AppendElement(newEvent);
mNativeEntries.Remove(addr);
}
} // namespace mozilla

View File

@ -1,43 +0,0 @@
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=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/. */
#ifndef memory_profiler_NativeProfilerImpl_h
#define memory_profiler_NativeProfilerImpl_h
#include "CompactTraceTable.h"
#include "MemoryProfiler.h"
#include "jsfriendapi.h"
struct PRLock;
namespace mozilla {
class NativeProfilerImpl final : public NativeProfiler
, public ProfilerImpl
{
public:
NativeProfilerImpl();
~NativeProfilerImpl() override;
nsTArray<nsCString> GetNames() const override;
nsTArray<TrieNode> GetTraces() const override;
const nsTArray<AllocEvent>& GetEvents() const override;
void reset() override;
void sampleNative(void* addr, uint32_t size) override;
void removeNative(void* addr) override;
private:
PRLock* mLock;
AllocMap mNativeEntries;
nsTArray<AllocEvent> mAllocEvents;
CompactTraceTable mTraceTable;
};
} // namespace mozilla
#endif // memory_profiler_NativeProfilerImpl_h

View File

@ -1,126 +0,0 @@
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=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/. */
#include "UncensoredAllocator.h"
#include "mozilla/Assertions.h"
#include "mozilla/unused.h"
#include "MainThreadUtils.h"
#include "jsfriendapi.h"
#include "nsDebug.h"
#include "prlock.h"
#ifdef MOZ_REPLACE_MALLOC
#include "replace_malloc_bridge.h"
#endif
namespace mozilla {
#ifdef MOZ_REPLACE_MALLOC
ThreadLocal<bool> MallocHook::mEnabledTLS;
NativeProfiler* MallocHook::mNativeProfiler;
malloc_hook_table_t MallocHook::mMallocHook;
#endif
AutoUseUncensoredAllocator::AutoUseUncensoredAllocator()
{
#ifdef MOZ_REPLACE_MALLOC
MallocHook::mEnabledTLS.set(false);
#endif
}
AutoUseUncensoredAllocator::~AutoUseUncensoredAllocator()
{
#ifdef MOZ_REPLACE_MALLOC
MallocHook::mEnabledTLS.set(true);
#endif
}
bool
MallocHook::Enabled()
{
#ifdef MOZ_REPLACE_MALLOC
return mEnabledTLS.get() && mNativeProfiler;
#else
return false;
#endif
}
void*
MallocHook::SampleNative(void* aAddr, size_t aSize)
{
#ifdef MOZ_REPLACE_MALLOC
if (MallocHook::Enabled()) {
mNativeProfiler->sampleNative(aAddr, aSize);
}
#endif
return aAddr;
}
void
MallocHook::RemoveNative(void* aAddr)
{
#ifdef MOZ_REPLACE_MALLOC
if (MallocHook::Enabled()) {
mNativeProfiler->removeNative(aAddr);
}
#endif
}
void
MallocHook::Initialize()
{
#ifdef MOZ_REPLACE_MALLOC
MOZ_ASSERT(NS_IsMainThread());
mMallocHook.free_hook = RemoveNative;
mMallocHook.malloc_hook = SampleNative;
ReplaceMallocBridge* bridge = ReplaceMallocBridge::Get(3);
if (bridge) {
mozilla::unused << bridge->RegisterHook("memory-profiler", nullptr, nullptr);
}
if (!mEnabledTLS.initialized()) {
bool success = mEnabledTLS.init();
if (NS_WARN_IF(!success)) {
return;
}
mEnabledTLS.set(false);
}
#endif
}
void
MallocHook::Enable(NativeProfiler* aNativeProfiler)
{
#ifdef MOZ_REPLACE_MALLOC
MOZ_ASSERT(NS_IsMainThread());
if (NS_WARN_IF(!mEnabledTLS.initialized())) {
return;
}
ReplaceMallocBridge* bridge = ReplaceMallocBridge::Get(3);
if (bridge) {
const malloc_table_t* alloc_funcs =
bridge->RegisterHook("memory-profiler", nullptr, &mMallocHook);
if (alloc_funcs) {
mNativeProfiler = aNativeProfiler;
}
}
#endif
}
void
MallocHook::Disable()
{
#ifdef MOZ_REPLACE_MALLOC
MOZ_ASSERT(NS_IsMainThread());
ReplaceMallocBridge* bridge = ReplaceMallocBridge::Get(3);
if (bridge) {
bridge->RegisterHook("memory-profiler", nullptr, nullptr);
mNativeProfiler = nullptr;
}
#endif
}
} // namespace mozilla

View File

@ -1,47 +0,0 @@
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=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/. */
#ifndef memory_profiler_UncensoredAllocator_h
#define memory_profiler_UncensoredAllocator_h
#include "mozilla/ThreadLocal.h"
#ifdef MOZ_REPLACE_MALLOC
#include "replace_malloc_bridge.h"
#endif
class NativeProfiler;
namespace mozilla {
class MallocHook final
{
public:
static void Initialize();
static void Enable(NativeProfiler* aNativeProfiler);
static void Disable();
static bool Enabled();
private:
static void* SampleNative(void* aAddr, size_t aSize);
static void RemoveNative(void* aAddr);
#ifdef MOZ_REPLACE_MALLOC
static ThreadLocal<bool> mEnabledTLS;
static NativeProfiler* mNativeProfiler;
static malloc_hook_table_t mMallocHook;
#endif
friend class AutoUseUncensoredAllocator;
};
class AutoUseUncensoredAllocator final
{
public:
AutoUseUncensoredAllocator();
~AutoUseUncensoredAllocator();
};
} // namespace mozilla
#endif // memory_profiler_UncensoredAllocator_h

View File

@ -1,27 +0,0 @@
# -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
# vim: set filetype=python:
# 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/.
if CONFIG['MOZ_ENABLE_PROFILER_SPS']:
XPIDL_MODULE = 'memory_profiler'
XPIDL_SOURCES += [
'nsIMemoryProfiler.idl',
]
UNIFIED_SOURCES += [
'GCHeapProfilerImpl.cpp',
'MemoryProfiler.cpp',
'NativeProfilerImpl.cpp',
'nsMemoryProfilerFactory.cpp',
'UncensoredAllocator.cpp',
]
LOCAL_INCLUDES += [
'/js/xpconnect/src',
'/xpcom/base',
]
FINAL_LIBRARY = 'xul'

View File

@ -1,72 +0,0 @@
/* -*- Mode: IDL; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* 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/. */
#include "nsISupports.idl"
/**
* The memory profiler samples allocation events. An allocation event
* includes a type (what and at where is going to be allocated), a
* size, a timestamp and the corresponding stack trace. Free events
* are also tracked. For managed languages, namely languages relying
* on garbage collection, a free event is generated when an object is
* reclaimed by the garbage collector. These sampled events can be
* used to approximate the full history of allocations afterwards.
* That means we can get various memory profiles of a program in
* different perspectives by post-processing the history in different
* ways. The profiler is designed at the very beginning to support not
* only JavaScript but also native codes. Naturally, not only
* JavaScript objects but also native allocations are tracked.
*
* The result returned is the sampled allocation event traces in a
* compact format. The events is sorted according to the timestamp
* when the event happened. Each event has a trace index pointing to
* the traces table. Each trace entry has a name index pointing to the
* names table and a parent index pointing to the parent trace in the
* traces table. By following the trace index one could rebuild the
* complete backtrace of an allocation event.
*
* [ Events ]
* +-------+-------+ +-------+
* | Size | Size | | Size |
* |-------|-------| |-------|
* | Time | Time |......| Time |
* |-------|-------| |-------|
* +-- Trace | Trace | | Trace |
* | +-------+-------+ +-------+
* |
* | [ Traces ]
* +->--------+--------+ +--------+ +--------+
* -| Name | Name | | Name | | Name |
* / |--------|--------|...|--------|...|--------|
* | | Parent | Parent | | Parent | | Parent |
* | +---|----+----^--++ +--^--|--+ +---^----+
* | | | | | | |
* | +---------+ +-------+ +----------+
* | [ Names ]
* | +-----------------+-----------------+
* +-> Function name | Function name |
* | & line numbers | & line numbers |......
* +-----------------+-----------------+
*
*/
[scriptable, uuid(1e10e7a9-bc05-4878-a687-36c9ea4428b1)]
interface nsIMemoryProfiler : nsISupports
{
void startProfiler();
void stopProfiler();
void resetProfiler();
/**
* Get results in an object which contains three tables:
* {
* names, // an array of function names and positions
* traces, // an array of {nameIdx, parentIdx}
* events, // an array of {size, timestamp, traceIdx}
* }
* Should only be called after stopProfiler.
*/
[implicit_jscontext]
jsval getResults();
};

View File

@ -1,32 +0,0 @@
/* -*- Mode: C++; tab-width: 20; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* 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/. */
#include "mozilla/ModuleUtils.h"
#include "nsCOMPtr.h"
#include "MemoryProfiler.h"
using mozilla::MemoryProfiler;
NS_GENERIC_FACTORY_CONSTRUCTOR(MemoryProfiler)
NS_DEFINE_NAMED_CID(MEMORY_PROFILER_CID);
static const mozilla::Module::CIDEntry kMemoryProfilerCIDs[] = {
{ &kMEMORY_PROFILER_CID, false, nullptr, MemoryProfilerConstructor },
{ nullptr }
};
static const mozilla::Module::ContractIDEntry kMemoryProfilerContracts[] = {
{ MEMORY_PROFILER_CONTRACT_ID, &kMEMORY_PROFILER_CID },
{ nullptr }
};
static const mozilla::Module kMemoryProfilerModule = {
mozilla::Module::kVersion,
kMemoryProfilerCIDs,
kMemoryProfilerContracts
};
NSMODULE_DEFN(nsMemoryProfilerModule) = &kMemoryProfilerModule;

View File

@ -1027,33 +1027,6 @@ void mozilla_sampler_free_backtrace(ProfilerBacktrace* aBacktrace)
delete aBacktrace;
}
// Fill the output buffer with the following pattern:
// "Lable 1" "\0" "Label 2" "\0" ... "Label N" "\0" "\0"
// TODO: use the unwinder instead of pseudo stack.
void mozilla_sampler_get_backtrace_noalloc(char *output, size_t outputSize)
{
MOZ_ASSERT(outputSize >= 2);
char *bound = output + outputSize - 2;
output[0] = output[1] = '\0';
PseudoStack *pseudoStack = tlsPseudoStack.get();
if (!pseudoStack) {
return;
}
volatile StackEntry *pseudoFrames = pseudoStack->mStack;
uint32_t pseudoCount = pseudoStack->stackSize();
for (uint32_t i = 0; i < pseudoCount; i++) {
size_t len = strlen(pseudoFrames[i].label());
if (output + len >= bound)
break;
strcpy(output, pseudoFrames[i].label());
output += len;
*output++ = '\0';
*output = '\0';
}
}
void mozilla_sampler_tracing(const char* aCategory, const char* aInfo,
TracingMetadata aMetaData)
{

View File

@ -149,7 +149,6 @@ static inline void profiler_resume() {}
// Immediately capture the current thread's call stack and return it
static inline ProfilerBacktrace* profiler_get_backtrace() { return nullptr; }
static inline void profiler_get_backtrace_noalloc(char *output, size_t outputSize) { return; }
// Free a ProfilerBacktrace returned by profiler_get_backtrace()
static inline void profiler_free_backtrace(ProfilerBacktrace* aBacktrace) {}

View File

@ -48,7 +48,6 @@ void mozilla_sampler_resume();
ProfilerBacktrace* mozilla_sampler_get_backtrace();
void mozilla_sampler_free_backtrace(ProfilerBacktrace* aBacktrace);
void mozilla_sampler_get_backtrace_noalloc(char *output, size_t outputSize);
bool mozilla_sampler_is_active();

View File

@ -121,12 +121,6 @@ void profiler_free_backtrace(ProfilerBacktrace* aBacktrace)
mozilla_sampler_free_backtrace(aBacktrace);
}
static inline
void profiler_get_backtrace_noalloc(char *output, size_t outputSize)
{
return mozilla_sampler_get_backtrace_noalloc(output, outputSize);
}
static inline
bool profiler_is_active()
{

View File

@ -297,15 +297,6 @@ public:
return aMallocSizeOf(this) + ShallowSizeOfExcludingThis(aMallocSizeOf);
}
/**
* Swap the elements in this hashtable with the elements in aOther.
*/
void SwapElements(nsBaseHashtable& aOther)
{
nsTHashtable<EntryType>::SwapElements(aOther);
}
#ifdef DEBUG
using nsTHashtable<EntryType>::MarkImmutable;
#endif