Bug 734691 - Add multi-thread support to profiler. r=benwa

This commit is contained in:
James Willcox 2013-03-28 19:51:15 -04:00
parent 30b1021382
commit f272cdf825
15 changed files with 391 additions and 63 deletions

View File

@ -42,6 +42,8 @@
#include "OSFileConstants.h"
#include <algorithm>
#include "GeckoProfiler.h"
using namespace mozilla;
using namespace mozilla::dom;
@ -510,6 +512,8 @@ public:
return NS_ERROR_FAILURE;
}
profiler_register_thread("WebWorker");
{
JSAutoRequest ar(cx);
workerPrivate->DoRunLoop(cx);
@ -538,6 +542,7 @@ public:
JS_DestroyRuntime(rt);
workerPrivate->ScheduleDeletion(false);
profiler_unregister_thread();
return NS_OK;
}
};

View File

@ -8,6 +8,7 @@
#include "base/string_util.h"
#include "base/thread_local.h"
#include "base/waitable_event.h"
#include "GeckoProfiler.h"
namespace base {
@ -136,6 +137,8 @@ void Thread::StopSoon() {
}
void Thread::ThreadMain() {
profiler_register_thread(name_.c_str());
// The message loop for this thread.
MessageLoop message_loop(startup_data_->options.message_loop_type);
@ -161,6 +164,8 @@ void Thread::ThreadMain() {
// Assert that MessageLoop::Quit was called by ThreadQuitTask.
DCHECK(GetThreadWasQuitProperly());
profiler_unregister_thread();
// We can't receive messages anymore.
message_loop_ = NULL;
thread_id_ = 0;

View File

@ -157,6 +157,13 @@ void genPseudoBacktraceEntries(/*MODIFIED*/UnwinderThreadBuffer* utb,
// RUNS IN SIGHANDLER CONTEXT
void BreakpadSampler::Tick(TickSample* sample)
{
if (!sample->threadProfile) {
// Platform doesn't support multithread, so use the main thread profile we created
sample->threadProfile = GetPrimaryThreadProfile();
}
ThreadProfile& currThreadProfile = *sample->threadProfile;
/* Get hold of an empty inter-thread buffer into which to park
the ProfileEntries for this sample. */
UnwinderThreadBuffer* utb = uwt__acquire_empty_buffer();
@ -171,7 +178,7 @@ void BreakpadSampler::Tick(TickSample* sample)
thread, and park them in |utb|. */
// Marker(s) come before the sample
PseudoStack* stack = mPrimaryThreadProfile.GetPseudoStack();
PseudoStack* stack = currThreadProfile.GetPseudoStack();
for (int i = 0; stack->getMarker(i) != NULL; i++) {
utb__addEntry( utb, ProfileEntry('m', stack->getMarker(i)) );
}
@ -185,7 +192,7 @@ void BreakpadSampler::Tick(TickSample* sample)
// XXX: we also probably want to add an entry to the profile to help
// distinguish which samples are part of the same event. That, or record
// the event generation in each sample
mPrimaryThreadProfile.erase();
currThreadProfile.erase();
}
sLastSampledEventGeneration = sCurrentEventGeneration;
@ -292,9 +299,9 @@ void BreakpadSampler::Tick(TickSample* sample)
# else
# error "Unsupported platform"
# endif
uwt__release_full_buffer(&mPrimaryThreadProfile, utb, ucV);
uwt__release_full_buffer(&currThreadProfile, utb, ucV);
} else {
uwt__release_full_buffer(&mPrimaryThreadProfile, utb, NULL);
uwt__release_full_buffer(&currThreadProfile, utb, NULL);
}
}

View File

@ -135,6 +135,9 @@ static inline void profiler_lock() {}
// Re-enable the profiler and notify 'profiler-unlocked'.
static inline void profiler_unlock() {}
static inline void profiler_register_thread(const char* name) {}
static inline void profiler_unregister_thread() {}
#else
#include "GeckoProfilerImpl.h"

View File

@ -57,6 +57,10 @@ void mozilla_sampler_lock();
// Unlock the profiler, leaving it stopped and fires profiler-unlocked.
void mozilla_sampler_unlock();
// Register/unregister threads with the profiler
bool mozilla_sampler_register_thread(const char* name);
void mozilla_sampler_unregister_thread();
/* Returns true if env var SPS_NEW is set to anything, else false. */
extern bool sps_version2();

View File

@ -140,6 +140,18 @@ void profiler_unlock()
return mozilla_sampler_unlock();
}
static inline
void profiler_register_thread(const char* name)
{
mozilla_sampler_register_thread(name);
}
static inline
void profiler_unregister_thread()
{
mozilla_sampler_unregister_thread();
}
// we want the class and function name but can't easily get that using preprocessor macros
// __func__ doesn't have the class name and __PRETTY_FUNCTION__ has the parameters
@ -154,6 +166,7 @@ void profiler_unlock()
#define PROFILER_MAIN_THREAD_LABEL_PRINTF(name_space, info, ...) MOZ_ASSERT(NS_IsMainThread(), "This can only be called on the main thread"); mozilla::SamplerStackFramePrintfRAII SAMPLER_APPEND_LINE_NUMBER(sampler_raii)(name_space "::" info, __LINE__, __VA_ARGS__)
#define PROFILER_MAIN_THREAD_MARKER(info) MOZ_ASSERT(NS_IsMainThread(), "This can only be called on the main thread"); mozilla_sampler_add_marker(info)
/* FIXME/bug 789667: memory constraints wouldn't much of a problem for
* this small a sample buffer size, except that serializing the
* profile data is extremely, unnecessarily memory intensive. */

View File

@ -134,19 +134,23 @@ std::ostream& operator<<(std::ostream& stream, const ProfileEntry& entry)
#define DYNAMIC_MAX_STRING 512
ThreadProfile::ThreadProfile(int aEntrySize, PseudoStack *aStack)
ThreadProfile::ThreadProfile(const char* aName, int aEntrySize, PseudoStack *aStack, int aThreadId, bool aIsMainThread)
: mWritePos(0)
, mLastFlushPos(0)
, mReadPos(0)
, mEntrySize(aEntrySize)
, mPseudoStack(aStack)
, mMutex("ThreadProfile::mMutex")
, mName(strdup(aName))
, mThreadId(aThreadId)
, mIsMainThread(aIsMainThread)
{
mEntries = new ProfileEntry[mEntrySize];
}
ThreadProfile::~ThreadProfile()
{
free(mName);
delete[] mEntries;
}
@ -299,6 +303,10 @@ JSCustomObject* ThreadProfile::ToJSObject(JSContext *aCx)
}
void ThreadProfile::BuildJSObject(JSAObjectBuilder& b, JSCustomObject* profile) {
// Thread meta data
b.DefineProperty(profile, "name", mName);
b.DefineProperty(profile, "tid", mThreadId);
JSCustomArray *samples = b.CreateArray();
b.DefineProperty(profile, "samples", samples);

View File

@ -6,6 +6,7 @@
#ifndef MOZ_PROFILE_ENTRY_H
#define MOZ_PROFILE_ENTRY_H
#include <ostream>
#include "GeckoProfilerImpl.h"
#include "JSAObjectBuilder.h"
#include "platform.h"
@ -56,7 +57,7 @@ typedef void (*IterateTagsCallback)(const ProfileEntry& entry, const char* tagSt
class ThreadProfile
{
public:
ThreadProfile(int aEntrySize, PseudoStack *aStack);
ThreadProfile(const char* aName, int aEntrySize, PseudoStack *aStack, int aThreadId, bool aIsMainThread);
~ThreadProfile();
void addTag(ProfileEntry aTag);
void flush();
@ -70,6 +71,11 @@ public:
PseudoStack* GetPseudoStack();
mozilla::Mutex* GetMutex();
void BuildJSObject(JSAObjectBuilder& b, JSCustomObject* profile);
bool IsMainThread() const { return mIsMainThread; }
const char* Name() const { return mName; }
int ThreadId() const { return mThreadId; }
private:
// Circular buffer 'Keep One Slot Open' implementation
// for simplicity
@ -80,6 +86,9 @@ private:
int mEntrySize;
PseudoStack* mPseudoStack;
mozilla::Mutex mMutex;
char* mName;
int mThreadId;
bool mIsMainThread;
};
std::ostream& operator<<(std::ostream& stream, const ThreadProfile& profile);

View File

@ -173,16 +173,22 @@ void TableTicker::BuildJSObject(JSAObjectBuilder& b, JSCustomObject* profile)
JSCustomArray *threads = b.CreateArray();
b.DefineProperty(profile, "threads", threads);
// For now we only have one thread
SetPaused(true);
ThreadProfile* prof = GetPrimaryThreadProfile();
prof->GetMutex()->Lock();
JSCustomObject* threadSamples = b.CreateObject();
prof->BuildJSObject(b, threadSamples);
b.ArrayPush(threads, threadSamples);
prof->GetMutex()->Unlock();
{
mozilla::MutexAutoLock lock(sRegisteredThreadsMutex);
for (size_t i = 0; i < sRegisteredThreads.size(); i++) {
MutexAutoLock lock(*sRegisteredThreads[i]->Profile()->GetMutex());
JSCustomObject* threadSamples = b.CreateObject();
sRegisteredThreads[i]->Profile()->BuildJSObject(b, threadSamples);
b.ArrayPush(threads, threadSamples);
}
}
SetPaused(false);
}
}
// END SaveProfileTask et al
////////////////////////////////////////////////////////////////////////
@ -383,10 +389,17 @@ void doSampleStackTrace(PseudoStack *aStack, ThreadProfile &aProfile, TickSample
void TableTicker::Tick(TickSample* sample)
{
if (!sample->threadProfile) {
// Platform doesn't support multithread, so use the main thread profile we created
sample->threadProfile = GetPrimaryThreadProfile();
}
ThreadProfile& currThreadProfile = *sample->threadProfile;
// Marker(s) come before the sample
PseudoStack* stack = mPrimaryThreadProfile.GetPseudoStack();
PseudoStack* stack = currThreadProfile.GetPseudoStack();
for (int i = 0; stack->getMarker(i) != NULL; i++) {
addDynamicTag(mPrimaryThreadProfile, 'm', stack->getMarker(i));
addDynamicTag(currThreadProfile, 'm', stack->getMarker(i));
}
stack->mQueueClearMarker = true;
@ -398,7 +411,7 @@ void TableTicker::Tick(TickSample* sample)
// XXX: we also probably want to add an entry to the profile to help
// distinguish which samples are part of the same event. That, or record
// the event generation in each sample
mPrimaryThreadProfile.erase();
currThreadProfile.erase();
}
sLastSampledEventGeneration = sCurrentEventGeneration;
@ -414,29 +427,29 @@ void TableTicker::Tick(TickSample* sample)
#if defined(USE_BACKTRACE) || defined(USE_NS_STACKWALK)
if (mUseStackWalk) {
doNativeBacktrace(mPrimaryThreadProfile, sample);
doNativeBacktrace(currThreadProfile, sample);
} else {
doSampleStackTrace(stack, mPrimaryThreadProfile, mAddLeafAddresses ? sample : nullptr);
doSampleStackTrace(stack, currThreadProfile, mAddLeafAddresses ? sample : nullptr);
}
#else
doSampleStackTrace(stack, mPrimaryThreadProfile, mAddLeafAddresses ? sample : nullptr);
doSampleStackTrace(stack, currThreadProfile, mAddLeafAddresses ? sample : nullptr);
#endif
if (recordSample)
mPrimaryThreadProfile.flush();
currThreadProfile.flush();
if (!sLastTracerEvent.IsNull() && sample) {
if (!sLastTracerEvent.IsNull() && sample && currThreadProfile.IsMainThread()) {
TimeDuration delta = sample->timestamp - sLastTracerEvent;
mPrimaryThreadProfile.addTag(ProfileEntry('r', delta.ToMilliseconds()));
currThreadProfile.addTag(ProfileEntry('r', delta.ToMilliseconds()));
}
if (sample) {
TimeDuration delta = sample->timestamp - mStartTime;
mPrimaryThreadProfile.addTag(ProfileEntry('t', delta.ToMilliseconds()));
currThreadProfile.addTag(ProfileEntry('t', delta.ToMilliseconds()));
}
if (sLastFrameNumber != sFrameNumber) {
mPrimaryThreadProfile.addTag(ProfileEntry('f', sFrameNumber));
currThreadProfile.addTag(ProfileEntry('f', sFrameNumber));
sLastFrameNumber = sFrameNumber;
}
}
@ -460,7 +473,8 @@ void mozilla_sampler_print_location1()
return;
}
ThreadProfile threadProfile(1000, stack);
ThreadProfile threadProfile("Temp", PROFILE_DEFAULT_ENTRY, stack,
0, false);
doSampleStackTrace(stack, threadProfile, NULL);
threadProfile.flush();

View File

@ -5,6 +5,7 @@
#include "platform.h"
#include "ProfileEntry.h"
#include "mozilla/Mutex.h"
static bool
hasFeature(const char** aFeatures, uint32_t aFeatureCount, const char* aFeature) {
@ -32,8 +33,8 @@ class TableTicker: public Sampler {
public:
TableTicker(int aInterval, int aEntrySize, PseudoStack *aStack,
const char** aFeatures, uint32_t aFeatureCount)
: Sampler(aInterval, true)
, mPrimaryThreadProfile(aEntrySize, aStack)
: Sampler(aInterval, true, aEntrySize)
, mPrimaryThreadProfile(nullptr)
, mStartTime(TimeStamp::Now())
, mSaveRequested(false)
{
@ -43,10 +44,46 @@ class TableTicker: public Sampler {
mJankOnly = hasFeature(aFeatures, aFeatureCount, "jank");
mProfileJS = hasFeature(aFeatures, aFeatureCount, "js");
mAddLeafAddresses = hasFeature(aFeatures, aFeatureCount, "leaf");
mPrimaryThreadProfile.addTag(ProfileEntry('m', "Start"));
{
mozilla::MutexAutoLock lock(sRegisteredThreadsMutex);
// Create ThreadProfile for each registered thread
for (uint32_t i = 0; i < sRegisteredThreads.size(); i++) {
ThreadInfo* info = sRegisteredThreads[i];
ThreadProfile* profile = new ThreadProfile(info->Name(),
aEntrySize,
info->Stack(),
info->ThreadId(),
info->IsMainThread());
profile->addTag(ProfileEntry('m', "Start"));
info->SetProfile(profile);
}
SetActiveSampler(this);
}
}
~TableTicker() { if (IsActive()) Stop(); }
~TableTicker() {
if (IsActive())
Stop();
SetActiveSampler(nullptr);
// Destroy ThreadProfile for all threads
{
mozilla::MutexAutoLock lock(sRegisteredThreadsMutex);
for (uint32_t i = 0; i < sRegisteredThreads.size(); i++) {
ThreadProfile* profile = sRegisteredThreads[i]->Profile();
if (profile) {
delete profile;
sRegisteredThreads[i]->SetProfile(nullptr);
}
}
}
}
virtual void SampleStack(TickSample* sample) {}
@ -63,7 +100,18 @@ class TableTicker: public Sampler {
ThreadProfile* GetPrimaryThreadProfile()
{
return &mPrimaryThreadProfile;
if (!mPrimaryThreadProfile) {
mozilla::MutexAutoLock lock(sRegisteredThreadsMutex);
for (uint32_t i = 0; i < sRegisteredThreads.size(); i++) {
if (sRegisteredThreads[i]->IsMainThread()) {
mPrimaryThreadProfile = sRegisteredThreads[i]->Profile();
break;
}
}
}
return mPrimaryThreadProfile;
}
void ToStreamAsJSON(std::ostream& stream);
@ -81,7 +129,7 @@ protected:
void BuildJSObject(JSAObjectBuilder& b, JSCustomObject* profile);
// This represent the application's main thread (SAMPLER_INIT)
ThreadProfile mPrimaryThreadProfile;
ThreadProfile* mPrimaryThreadProfile;
TimeStamp mStartTime;
bool mSaveRequested;
bool mAddLeafAddresses;

View File

@ -39,6 +39,7 @@
#include <sys/syscall.h>
#include <sys/types.h>
#include <stdlib.h>
#include <sched.h>
#ifdef ANDROID
#include <android/log.h>
#else
@ -60,9 +61,13 @@
#include <stdarg.h>
#include "platform.h"
#include "GeckoProfilerImpl.h"
#include "mozilla/Mutex.h"
#include "ProfileEntry.h"
#include "nsThreadUtils.h"
#include <string.h>
#include <stdio.h>
#include <list>
#define SIGNAL_SAVE_PROFILE SIGUSR2
@ -75,15 +80,14 @@ pid_t gettid()
}
#endif
static Sampler* sActiveSampler = NULL;
#ifdef ANDROID
#include "android-signal-defs.h"
#endif
static ThreadProfile* sCurrentThreadProfile = NULL;
static void ProfilerSaveSignalHandler(int signal, siginfo_t* info, void* context) {
sActiveSampler->RequestSave();
Sampler::GetActiveSampler()->RequestSave();
}
#ifdef ANDROID
@ -94,7 +98,7 @@ static void ProfilerSaveSignalHandler(int signal, siginfo_t* info, void* context
#define V8_HOST_ARCH_X64 1
#endif
static void ProfilerSignalHandler(int signal, siginfo_t* info, void* context) {
if (!sActiveSampler)
if (!Sampler::GetActiveSampler())
return;
TickSample sample_obj;
@ -103,7 +107,7 @@ static void ProfilerSignalHandler(int signal, siginfo_t* info, void* context) {
#ifdef ENABLE_SPS_LEAF_DATA
// If profiling, we extract the current pc and sp.
if (sActiveSampler->IsProfiling()) {
if (Sampler::GetActiveSampler()->IsProfiling()) {
// Extracting the sample from the context is extremely machine dependent.
ucontext_t* ucontext = reinterpret_cast<ucontext_t*>(context);
mcontext_t& mcontext = ucontext->uc_mcontext;
@ -138,14 +142,17 @@ static void ProfilerSignalHandler(int signal, siginfo_t* info, void* context) {
#endif
}
#endif
sample->threadProfile = sCurrentThreadProfile;
sample->timestamp = mozilla::TimeStamp::Now();
sActiveSampler->Tick(sample);
Sampler::GetActiveSampler()->Tick(sample);
sCurrentThreadProfile = NULL;
}
#ifndef XP_MACOSX
void tgkill(pid_t tgid, pid_t tid, int signalno) {
syscall(SYS_tgkill, tgid, tid, signalno);
int tgkill(pid_t tgid, pid_t tid, int signalno) {
return syscall(SYS_tgkill, tgid, tid, signalno);
}
#endif
@ -173,8 +180,33 @@ class Sampler::PlatformData : public Malloced {
#ifdef XP_MACOSX
pthread_kill(signal_receiver_, SIGPROF);
#else
// Glibc doesn't provide a wrapper for tgkill(2).
tgkill(vm_tgid_, vm_tid_, SIGPROF);
std::vector<ThreadInfo*> threads = GetRegisteredThreads();
for (uint32_t i = 0; i < threads.size(); i++) {
ThreadInfo* info = threads[i];
// We use sCurrentThreadProfile the ThreadProfile for the
// thread we're profiling to the signal handler
sCurrentThreadProfile = info->Profile();
int threadId = info->ThreadId();
if (threadId == 0) {
threadId = vm_tid_;
}
if (tgkill(vm_tgid_, threadId, SIGPROF) != 0) {
printf_stderr("profiler failed to signal tid=%d\n", threadId);
#ifdef DEBUG
abort();
#endif
continue;
}
// Wait for the signal handler to run before moving on to the next one
while (sCurrentThreadProfile)
sched_yield();
}
#endif
}
@ -209,11 +241,12 @@ static void* SenderEntry(void* arg) {
}
Sampler::Sampler(int interval, bool profiling)
Sampler::Sampler(int interval, bool profiling, int entrySize)
: interval_(interval),
profiling_(profiling),
paused_(false),
active_(false) {
active_(false),
entrySize_(entrySize) {
data_ = new PlatformData(this);
}
@ -225,7 +258,6 @@ Sampler::~Sampler() {
void Sampler::Start() {
LOG("Sampler started");
if (sActiveSampler != NULL) return;
// Request profiling signals.
LOG("Request signal");
@ -259,9 +291,6 @@ void Sampler::Start() {
data_->signal_sender_launched_ = true;
}
LOG("Profiler thread started");
// Set this sampler as the active sampler.
sActiveSampler = this;
}
@ -281,9 +310,40 @@ void Sampler::Stop() {
sigaction(SIGPROF, &data_->old_sigprof_signal_handler_, 0);
data_->signal_handler_installed_ = false;
}
}
// This sampler is no longer the active sampler.
sActiveSampler = NULL;
bool Sampler::RegisterCurrentThread(const char* aName, PseudoStack* aPseudoStack, bool aIsMainThread)
{
mozilla::MutexAutoLock lock(sRegisteredThreadsMutex);
ThreadInfo* info = new ThreadInfo(aName, gettid(), aIsMainThread, aPseudoStack);
if (sActiveSampler) {
// We need to create the ThreadProfile now
info->SetProfile(new ThreadProfile(info->Name(),
sActiveSampler->EntrySize(),
info->Stack(),
info->ThreadId(),
aIsMainThread));
}
sRegisteredThreads.push_back(info);
return true;
}
void Sampler::UnregisterCurrentThread()
{
mozilla::MutexAutoLock lock(sRegisteredThreadsMutex);
int id = gettid();
for (uint32_t i = 0; i < sRegisteredThreads.size(); i++) {
if (sRegisteredThreads[i]->ThreadId() == id) {
delete sRegisteredThreads[i];
sRegisteredThreads.erase(sRegisteredThreads.begin() + i);
break;
}
}
}
#ifdef ANDROID
@ -307,3 +367,4 @@ void OS::RegisterStartHandler()
}
}
#endif

View File

@ -28,6 +28,8 @@
#include <string.h>
#include <errno.h>
#include "nsThreadUtils.h"
#include "platform.h"
#include "UnwinderThread2.h" /* uwt__register_thread_for_profiling */
@ -199,8 +201,8 @@ class Sampler::PlatformData : public Malloced {
class SamplerThread : public Thread {
public:
explicit SamplerThread(int interval)
: Thread("SamplerThread"),
interval_(interval) {}
: Thread("SamplerThread")
, interval_(interval) {}
static void AddActiveSampler(Sampler* sampler) {
ScopedLock lock(mutex_);
@ -279,6 +281,7 @@ class SamplerThread : public Thread {
sample->sp = reinterpret_cast<Address>(state.REGISTER_FIELD(sp));
sample->fp = reinterpret_cast<Address>(state.REGISTER_FIELD(bp));
sample->timestamp = mozilla::TimeStamp::Now();
sample->threadProfile = NULL;
sampler->SampleStack(sample);
sampler->Tick(sample);
}
@ -302,12 +305,13 @@ Mutex* SamplerThread::mutex_ = OS::CreateMutex();
SamplerThread* SamplerThread::instance_ = NULL;
Sampler::Sampler(int interval, bool profiling)
Sampler::Sampler(int interval, bool profiling, int entrySize)
: // isolate_(isolate),
interval_(interval),
profiling_(profiling),
paused_(false),
active_(false) /*,
active_(false),
entrySize_(entrySize) /*,
samples_taken_(0)*/ {
data_ = new PlatformData;
}
@ -337,3 +341,30 @@ Sampler::GetProfiledThread(Sampler::PlatformData* aData)
{
return aData->profiled_pthread();
}
bool Sampler::RegisterCurrentThread(const char* aName, PseudoStack* aPseudoStack, bool aIsMainThread)
{
mozilla::MutexAutoLock lock(sRegisteredThreadsMutex);
if (!aIsMainThread)
return false;
ThreadInfo* info = new ThreadInfo(aName, 0, true, aPseudoStack);
if (sActiveSampler) {
// We need to create the ThreadProfile now
info->SetProfile(new ThreadProfile(info->Name(),
sActiveSampler->EntrySize(),
info->Stack(),
info->ThreadId(),
true));
}
sRegisteredThreads.push_back(info);
return true;
}
void Sampler::UnregisterCurrentThread()
{
// We only have the main thread currently and that will never be unregistered
}

View File

@ -28,9 +28,9 @@
#include <windows.h>
#include <mmsystem.h>
#include "platform.h"
#include <process.h>
#include "platform.h"
#include "ProfileEntry.h"
class Sampler::PlatformData : public Malloced {
public:
@ -67,9 +67,9 @@ Sampler::GetThreadHandle(Sampler::PlatformData* aData)
class SamplerThread : public Thread {
public:
SamplerThread(int interval, Sampler* sampler)
: Thread("SamplerThread"),
interval_(interval),
sampler_(sampler) {}
: Thread("SamplerThread")
, interval_(interval)
, sampler_(sampler) {}
static void StartSampler(Sampler* sampler) {
if (instance_ == NULL) {
@ -120,6 +120,7 @@ class SamplerThread : public Thread {
// Grab the timestamp before pausing the thread, to avoid deadlocks.
sample->timestamp = mozilla::TimeStamp::Now();
sample->threadProfile = NULL;
static const DWORD kSuspendFailed = static_cast<DWORD>(-1);
if (SuspendThread(profiled_thread) == kSuspendFailed)
@ -155,11 +156,12 @@ class SamplerThread : public Thread {
SamplerThread* SamplerThread::instance_ = NULL;
Sampler::Sampler(int interval, bool profiling)
Sampler::Sampler(int interval, bool profiling, int entrySize)
: interval_(interval),
profiling_(profiling),
paused_(false),
active_(false),
entrySize_(entrySize),
data_(new PlatformData) {
}
@ -238,3 +240,30 @@ void Thread::Join() {
void OS::Sleep(int milliseconds) {
::Sleep(milliseconds);
}
bool Sampler::RegisterCurrentThread(const char* aName, PseudoStack* aPseudoStack, bool aIsMainThread)
{
mozilla::MutexAutoLock lock(sRegisteredThreadsMutex);
if (!aIsMainThread)
return false;
ThreadInfo* info = new ThreadInfo(aName, 0, true, aPseudoStack);
if (sActiveSampler) {
// We need to create the ThreadProfile now
info->SetProfile(new ThreadProfile(info->Name(),
sActiveSampler->EntrySize(),
info->Stack(),
info->ThreadId(),
true));
}
sRegisteredThreads.push_back(info);
return true;
}
void Sampler::UnregisterCurrentThread()
{
// We only have the main thread currently and that will never be unregistered
}

View File

@ -18,6 +18,7 @@
#include "nsDirectoryServiceUtils.h"
#include "nsDirectoryServiceDefs.h"
#include "mozilla/Services.h"
#include "nsThreadUtils.h"
mozilla::ThreadLocal<PseudoStack *> tlsPseudoStack;
mozilla::ThreadLocal<TableTicker *> tlsTicker;
@ -43,6 +44,18 @@ unsigned int sCurrentEventGeneration = 0;
* a problem if 2^32 events happen between samples that we need
* to know are associated with different events */
std::vector<ThreadInfo*> Sampler::sRegisteredThreads;
mozilla::Mutex Sampler::sRegisteredThreadsMutex("sRegisteredThreads mutex");
Sampler* Sampler::sActiveSampler;
ThreadInfo::~ThreadInfo() {
free(mName);
if (mProfile)
delete mProfile;
}
bool sps_version2()
{
static int version = 0; // Raced on, potentially
@ -185,6 +198,8 @@ void mozilla_sampler_init()
PseudoStack *stack = new PseudoStack();
tlsPseudoStack.set(stack);
Sampler::RegisterCurrentThread("Gecko", stack, true);
if (sps_version2()) {
// Read mode settings from MOZ_PROFILER_MODE and interval
// settings from MOZ_PROFILER_INTERVAL.
@ -252,6 +267,8 @@ void mozilla_sampler_shutdown()
uwt__deinit();
}
Sampler::ClearRegisteredThreads();
profiler_stop();
// We can't delete the Stack because we can be between a
// sampler call_enter/call_exit point.
@ -446,6 +463,20 @@ void mozilla_sampler_unlock()
os->NotifyObservers(nullptr, "profiler-unlocked", nullptr);
}
bool mozilla_sampler_register_thread(const char* aName)
{
PseudoStack* stack = new PseudoStack();
tlsPseudoStack.set(stack);
return Sampler::RegisterCurrentThread(aName, stack, false);
}
void mozilla_sampler_unregister_thread()
{
Sampler::UnregisterCurrentThread();
}
// END externally visible functions
////////////////////////////////////////////////////////////////////////

View File

@ -43,6 +43,7 @@
#include "mozilla/unused.h"
#include "mozilla/TimeStamp.h"
#include "PlatformMacros.h"
#include "mozilla/Mutex.h"
#include "v8-support.h"
#include <vector>
#define ASSERT(a) MOZ_ASSERT(a)
@ -215,6 +216,9 @@ class Thread {
// (if used for profiling) the program counter and stack pointer for
// the thread that created it.
class PseudoStack;
class ThreadProfile;
// TickSample captures the information collected for each sample.
class TickSample {
public:
@ -238,16 +242,44 @@ class TickSample {
Address function; // The last called JS function.
void* context; // The context from the signal handler, if available. On
// Win32 this may contain the windows thread context.
ThreadProfile* threadProfile;
static const int kMaxFramesCount = 64;
Address stack[kMaxFramesCount]; // Call stack.
int frames_count; // Number of captured frames.
mozilla::TimeStamp timestamp;
};
class ThreadInfo {
public:
ThreadInfo(const char* aName, int aThreadId, bool aIsMainThread, PseudoStack* aPseudoStack)
: mName(strdup(aName))
, mThreadId(aThreadId)
, mIsMainThread(aIsMainThread)
, mPseudoStack(aPseudoStack)
, mProfile(NULL) {}
virtual ~ThreadInfo();
const char* Name() const { return mName; }
int ThreadId() const { return mThreadId; }
bool IsMainThread() const { return mIsMainThread; }
PseudoStack* Stack() const { return mPseudoStack; }
void SetProfile(ThreadProfile* aProfile) { mProfile = aProfile; }
ThreadProfile* Profile() const { return mProfile; }
private:
char* mName;
int mThreadId;
const bool mIsMainThread;
PseudoStack* mPseudoStack;
ThreadProfile* mProfile;
};
class Sampler {
public:
// Initialize sampler.
explicit Sampler(int interval, bool profiling);
explicit Sampler(int interval, bool profiling, int entrySize);
virtual ~Sampler();
int interval() const { return interval_; }
@ -278,6 +310,8 @@ class Sampler {
bool IsPaused() const { return paused_; }
void SetPaused(bool value) { NoBarrier_Store(&paused_, value); }
int EntrySize() { return entrySize_; }
class PlatformData;
PlatformData* platform_data() { return data_; }
@ -291,6 +325,31 @@ class Sampler {
#ifdef XP_MACOSX
static pthread_t GetProfiledThread(PlatformData*);
#endif
static std::vector<ThreadInfo*> GetRegisteredThreads() {
mozilla::MutexAutoLock lock(sRegisteredThreadsMutex);
return sRegisteredThreads;
}
static bool RegisterCurrentThread(const char* aName, PseudoStack* aPseudoStack, bool aIsMainThread);
static void UnregisterCurrentThread();
// Should only be called on shutdown
static void ClearRegisteredThreads() {
while (sRegisteredThreads.size() > 0) {
sRegisteredThreads.pop_back();
}
}
static Sampler* GetActiveSampler() { return sActiveSampler; }
static void SetActiveSampler(Sampler* sampler) { sActiveSampler = sampler; }
protected:
static std::vector<ThreadInfo*> sRegisteredThreads;
static mozilla::Mutex sRegisteredThreadsMutex;
static Sampler* sActiveSampler;
private:
void SetActive(bool value) { NoBarrier_Store(&active_, value); }
@ -298,6 +357,7 @@ class Sampler {
const bool profiling_;
Atomic32 paused_;
Atomic32 active_;
const int entrySize_;
PlatformData* data_; // Platform specific data.
};