Files
roytam1 f18df9acf8 import changes from `dev' branch of rmottola/Arctic-Fox:
- Bug 1239496 - Load the UA sheet lazily so we can invalidate it for pref changes. Make it depend on the "layout.css.grid.enabled" pref. r=heycam (e4a1ac18b4)
- Bug 1225192 - fix eslint complaints about css-logic.js; r=pbrosset (ef19819c21)
- Bug 1225192 - remove leading whitespace before prettifying css; r=pbrosset (6b39d08907)
- Bug 1230491 - rewrite CssLogic.isContentStylesheet; r=bgrins (14c86cee67)
- Bug 1230491 - add CSSStyleSheet::parsingMode; r=heycam,bz (9ecabe232e)
- Bug 1239336 - set parsing mode on about:PreferenceStyleSheet; r=heycam,bgrins (cac07e099f)
- Bug 1224433 - Part 1: Add reftest. r=roc (28c8a47812)
- Bug 1195491 - use nsCOMPtr in RDFContentSinkImpl; r=bsmedberg (9804abe22e)
- Bug 1205713 - Merge ImageHostOverlay/ImageClientOverlay to ImageHost/ImageClient r=nical (2871e70466)
- Bug 1234472 - Add gonk sideband stream handling to gfx ipc r=nical (559f788a10)
- Bug 1049296 - Handle Sideband stream compositing in HwcComposer2D r=mwu,nical (b6dbac1a1b)
- Bug 1237508 - Odin: move GC allocation up to fix spurious hazard warning (there was an AutoKeepAtoms already) (r=hazard-red) (b5d0e54993)
- Bug 1229399: Group all IR's enums into a single one; r=luke (a7cfedc16a)
- Bug 1229399: Make {Get,Set}{Loc,Glo} opcodes type-independent; r=luke (0ed8e44098)
- Bug 1239211 - Odin: tweak wasm::Decoder (r=bbouvier) (980e08dc1e)
- Bug 1229399: Implement write/readVarU32 and use it for locals/globals; r=luke (5a6f654a14)
- Bug 1229399: Unite all the Emit* functions in WasmIonCompile; r=luke (64e517d18f)
- Bug 1240524: Fix AsmJS checkedValueType of Bool32x4; r=luke (d98ee763c7)
- Bug 1229399: Add list of wasm opcodes described in v8 design document; r=luke (1e05832624)
- Bug 1241339 - ObserverService may keep Console object alive until shutdown, r=baku (330d9e7bc0)
- Bug 1239177 - Odin: make calls more like wasm (r=bbouvier) (4bab27c7bc)
- Bug 1234985 - Odin: hoist read/writeOp into wasm::Decoder/Encoder (r=bbouvier) (de3ba3c3f9)
- Bug 1229399: Add test file forgotten in previous rebase/checkin; r=bustage (a2bdda0e86)
- Bug 1234985 - Odin: tweak ModuleGenerator interface for Baldr use (r=bbouvier) (5f52fd6777)
- Bug 1234985 - BaldrMonkey: testing-only (not content visible) wasm hello world (r=bbouvier) (e49e7f4db2)
- Bug 1234985 - Fix js/src/asmjs build errors with unified builds disabled. r=luke (acb7954471)
- Bug 1231335 - part 1, runtime switch for SAB+Atomics. r=waldo (973eb7edc1)
- Bug 1231335 - part 2, asm.js runtime SAB+Atomics gating. r=luke (b40a8d0b3f)
- Bug 1225040 - generalize jsapi-tests for SAB. r=arai (29240f91e1)
- Bug 1232211 - Don't perform various SharedArrayBuffer-centric typed array tests in builds with SharedArrayBuffer disabled (i.e. Aurora at next uplift). rs=lth over IRC, responding to cassandra!philor's concerns (f3df4b0c17)
- Bug 1231335 - part 3, testing functions and test cases. r=waldo (b91910ea28)
- Bug 1231335 - part 4, js shell. r=waldo (4a96addbde)
- Bug 1234985 - Odin: move mutedError and displayURL into AsmJSModule (r=bbouvier) (6be0172a15)
- Bug 1229399: Remove expression statements opcodes in wasm; r=luke (a046188e98)
- Bug 1229399: Allow to peek into the internal wasm IR; r=luke (f4b0497d89)
- Bug 1234985 - Odin: make names optional and supplied at the end (r=b ouvier) (ee7864fe7e)
- Bug 1238679 - Rename s/SIMD/Simd/ in type and function names. r=bbouvier (1d6c277644)
- Bug 1238679 - Add enum class SIMDOperation. r=bbouvier (eb7ce840da)
- Bug 1187232 - Access TypedArray's [[ArrayLength]] instead of performing property access; r=Waldo (a66850e72f)
- Bug 1239068 - Inline "PossiblyTypedArrayLength" intrinsic; r=Waldo (1a39045055)
- Bug 1238679 - Put JSJitInfo::depth in anonymous union. r=nbp (64d6859ee2)
- Bug 1238679 - Provide per-operation JSJitInfo for the SIMD functions. r=bbouvier (cd242c1f5d)
- Backed out changeset 7bda46f81215 (bug 1225031) for spidermonkey test failures (7c7de9af43)
- Bug 1225031 - get rid of the AnyTypedArray abstraction (updated). r=waldo (a8e3593280)
- Bug 1237284: Make inlineSimd* functions take MIRType to avoid an indirection; r=jolesen (c046f5ac06)
- Bug 1238679 - Make inlineSimdLoad/Store take a MIRType argument. r=bbouvier (7aceb59fc1)
- Bug 1238679 - Implement main SIMD inlining dispatch. r=bbouvier (3b19775b14)
- Bug 1237445 - Use GCHashMap for VMWrapperMap, r=terrence (4a5b3a1575)
- Bug 1241454: Hoist SimdTypeDescr::Type into SimdType, unify AsmJSSimdType and SimdType; r=jolesen (6cf5f03517)
- Bug 1241454: Unify AsmJSSimdOperation and SimdOperation; r=jolesen (7506dec0e4)
- Bug 1241454: Change SIMD opcodes encoding in wasm; r=luke, r=jolesen (afa2b74cab)
- Bug 1242804 - Baldr: check enum limits (r=bbouvier) (1a68daa1c3)
- Bug 1242804 - Baldr: add local/get_local/set_local (r=bbouvier) (cc2448d2e9)
- Bug 1243239 - Baldr: tighten signature index check (r=bbouvier) (fd7081ab39)
- Bug 1243373: Ensure all declared functions are defined; r=luke (3c42295668)
- Bug 1243031: Throw when WebAssembly is not supported; r=luke (ade7cdc6a6)
- Bug 1242772 - Baldr: fix unterminated string literal (r=bbouvier) (273e26e669)
- Bug 1241886: Fix debug assertion if we're in dead code; r=luke (59c009191b)
- Bug 1234985 - Odin: use VarU32 for integer literals (r=bbouvier) (62c7292462)
- Bug 1234985 - Odin: stop requiring explicit final return (r=bbouvier) (2a8bf1639e)
- Bug 1242949: Implement Block in WebAssembly; r=luke (e8997f2a2e)
- Bug 1242949: Add explicit keyword to WasmAstBlock ctor; r=bustage (239cdcf5d4)
- Bug 1243626 - Baldr: tweak block text format (r=bbouvier) (a6fe9248ce)
- Bug 1243252 - Baldr: refactor exports (r=bbouvier) (49ca6f519f)
- Bug 1243632 - Baldr: check TypeError vs. SyntaxError (r=bbouvier) (c70ab8e8ec)
- Bug 1243252 - Baldr: add import section (r=bbouvier) (16b98660c8)
- Bug 1243633 - Baldr: add call/call_import (r=bbouvier) (63dd480e7d)
- Bug 1234985 - Hoist CStringHasher (r=sfink) (c019cff4b3)
- Bug 1237445 - Implement GCRekeyableHashMap, r=terrence (c4acd75ad0)
- Bug 1244272 - BaldrMonkey: Implement support for i32.add. r=luke (ede8918dfe)
- Bug 1244272 - BaldrMonkey: Implement the rest of the i32 binary operators. r=luke (bf11a38b86)
- Bug 1244272 - BaldrMonkey: Implement the f32 and 64 operators. r=luke (2ea37d6a95)
- Bug 1244403 - Baldr: move kind out of WasmAstNode and into WasmAstExpr (r=bbouvier) (498fd0b4a5)
- Silence a GCC warning in JitCompartment.h. No bug#, rs=jandem on IRC. (a23ccc42b3)
- Bug 1237445 - Use GCHashMap for ICStubCodeMap, r=terrence (b1d970f3c9)
- Bug 1244403 - Baldr: remove unnecessary 'end' argument from (r=bbouvier) (8da28c587c)
- Bug 1244403 - Baldr: expose export func entry offsets directly (r=bbouvier) (c6f82070fb)
- Bug 1234862 - Part 2: Always use DefaultGCPolicy with GCVector; r=sfink (6d8cf44216)
- Bug 1237445 - Use GCHashTables for ObjectGroup sweeping, r=terrence (7fd47cc6fb)
- Bug 1237445 - Use GCHashMap for (CCW) WrapperMap, r=terrence (cf6788b6a4)
- Bug 1237447 - Disable the crashreporter when crashing intentionally in TestPLDHash. r=njn (d4744f47d4)
- Bug 1237445 - Rekey ArrayObjectTable, r=terrence (2ccfca974c)
- Bug 1234862 - Part 3: Always use DefaultGCPolicy for GCHashTables; r=sfink (d0f2472c1b)
- Bug 1234862 - Part 4: Always use DefaultGCPolicy for TraceableFifo; r=sfink (069e134534)
- Bug 1239494 - Use GCHashMap to simplify nsWrapperCache; r=jonco (0bb0069fc4)
- Bug 1234862 - Part 5: Rename DefaultGCPolicy to GCPolicy; r=sfink (cb93f0c133)
- Bug 1234862 - Part 5.1: Followup comment fixes; r=sfink (bd2930ddf2)
- Fix recent non-unified build bustage (no bug, rs=sunfish) (6c40eba8bc)
- Bug 1243815: Put hard limits to some variable lengths in wasm; r=luke (1df12aa08e)
- Bug 1244403 - Baldr: factor out DynamicLinkData (r=bbouvier) (f257b901a3)
- Bug 1244403 - Baldr: put import section first (r=bbouvier) (47e726c907)
- Bug 1244571 - BaldrMonkey: Implement the unary operators. r=luke (e22132ccb1)
- Bug 1244571 - BaldrMonkey: Implement the comparison operators. r=luke (aa6e7a71cd)
- Bug 1244571 - BaldrMonkey: Implement parsing, encoding, and decoding for the conversion operators. r=luke (73d65dc416)
- Bug 1244571 - BaldrMonkey: Type-check the unary and binary operators. r=luke (4d7d41d49b)
- Bug 1244571 - BaldrMonkey: Implement parsing, encoding, and decoding for i64 operators. r=luke (c42a9b5496)
- Bug 1244571 - BaldrMonkey: Improve the readability of the parser code. r=luke (298c9c57a5)
- Bug 1244571 - BaldrMonkey: Fail decoding for operators which are not yet implemented r=luke (fdd4deff21)
- Bug 1245250 - BaldrMonkey: Refacfor min/max to make variadicity AsmJS-specific r=luke (f30e0471b9)
- Bug 1242342: Add If and IfElse to WebAssembly; r=luke (653223fdd3)
- Bug 1247755 - Baldr: disallow duplicate signature table entries (r=sunfish) (419fd0be57)
- Bug 1234397 - dispatch on the correct value. r=luke (4c7d5f5105)
- Bug 1233863 - ARM64: Allow test to pass with --no-asmjs, and when no JIT exists. r=luke (b89522c52c)
- Bug 1244405 - Odin: switch to dynamic page size, move heap constants to Wasm (r=bbouvier) (31d4b684b7)
- Bug 1234038 - Self-host ArrayBuffer.prototype.slice. r=lth (ab81205e4a)
- Bug 1121937 - Implement %TypedArray%.prototype.sort; r=jorendorff (aef7bb1228)
- Bug 1101256 - Implement detachment checks for %TypedArray% methods (patch 1 of 2); r=Waldo (cb13a5078b)
- Bug 1101256 - Implement detachment checks for %TypedArray% methods (patch 2 of 2); r=Waldo (b429b87a3d)
- Bug 715181 - Self-host Array.sort; r=till (f87f85634c)
- Bug 1079844 - Adjust TypedArray.js comments to refer to detachment rather than neutering. r=mrrrgn (ac2b366958)
- Bug 1079844 - Rename scattered bits of 'neuter' terminology to detachment terminology. r=jandem (ae20a9677c)
- Bug 1079844 - Rename JS_ARRAYBUFFER_NEUTERED_FLAG to use detachment terminology. r=sfink (670281d8b0)
- Bug 1079844 - Rename isNeutered() to isDetached(), and rename isNeutered() on views to hasDetachedBuffer(). r=sfink (b5595746aa)
- Bug 1079844 - Convert the JS_NeuterArrayBufferObject API to detachment terminology. r=till (2d176589bd)
- Bug 1079844 - Rename JS_IsNeuteredArrayBufferObject to JS_IsDetachedArrayBufferObject. r=till (9607cf673d)
- Bug 1079844 - Refer to "detaching" instead of "neutering" of ArrayBuffers, in JIT optimization tracking code. r=jandem (a4a17233d0)
- Bug 1079844 - Rename TI's ObjectKey flag to use detachment terminology. r=jandem (8865017109)
- Bug 1079844 - Rename CheckForNeuteredTypedObject and the flag underlying it to use detachment terminology. r=jandem (67ace7669e)
- Bug 1079844 - Rename ABO::neuter to ABO::detach. r=sfink (37c71de755)
- Bug 1079844 - Rename ArrayBufferViewObject::neuter to ABVO::notifyBufferDetached. Detachment applies only to ArrayBuffers, and the methods didn't actually neuter anything, so "notify" makes more sense as the verb here. r=sfink (2ebf7779a7)
- Bug 1079844 - Rename ABO::neuterView to a standalone NoteViewBufferWasDetached function. r=sfink (3ce2977123)
- Bug 1244405 - Odin: refactor ArrayBufferObject::createForWasm out of prepareForAsmJS (r=bbouvier) (3f5ed523f0)
- Bug 1243633 - Odin: tidy up call emitting (r=bbouvier) (89256a6d57)
- Bug 1243633 - Odin: switch to lineOrBytecode from line/column (r=bbouvier) (ded5ff23de)
- Bug 1242342: Set return type accordingly to the compilation mode; r=luke (f4cdff1644)
- Bug 1244405 - Baldr: fix wasm function export name (r=bbouvier) (c6ea5f8194)
- Bug 1244405 - Baldr: add memory section (r=bbouvier) (c98fc66e50)
- Bug 1243252 - Remove const restriction on CharsToNewUTF8CharsZ (r=jandem) (9ef020aff6)
- fix neutered/detached (2a675ae62e)
- Bug 1242342: Replace Ternary by IfElse which return expressions; r=luke (aa1535de89)
- Bug 1244405 - Baldr: add memory exports (r=bbouvier) (9a495599df)
- Bug 1240583 - Odin: remove the sync interrupt stub (r=bbouvier) (a3811b0cc5)
- Bug 1242043 - {Array,%TypedArray%}.prototype.{i,lastI}ndexOf should never return -0. r=jorendorff (485f5d62dc)
- Bug 1180290 - Part 1: Add prefix parameter to IdToFunctionName. r=till (e33ed94f64)
- Bug 1180290 - Part 2: Handle prefix in DefinePropertyById. r=till,smaug (5c3333ef68)
- Bug 1180290 - Part 3: Use canonical name in native getter. r=till (213b6d1b7f)
- Bug 1180290 - Part 4: Add tests for builtin getter name. r=till (005f1e4da7)
- Bug 1180290 - Part 5: Remove getter/setter variant for ThrowInvalidThis message. r=bz (fa8224af50)
- Bug 1236548 - Allow JS_UNINITIALIZED_LEXICAL in jit::InvokeFunction. (r=Waldo) (33b1f88506)
- Bug 1212533 - Change the out-param of js/JS::Construct from MutableHandleValue to MutableHandleObject. r=arai, r=jorendorff (7910b24126)
- Bug 1233857 - Teach the JIT how to put individual elements' edges in the store buffer; r=jandem (7d0b35b028)
- Bug 1236548 - Followup: Make added test actually pass. (rs=Waldo) (0f1e6861b1)
- Bug 1216166 - Unify CustomEvent.cpp with the rest of the unified sources, r=smaug (eacd905246)
- Bug 1233831 - Part 0: JSAPI plumbing for nursery collection callbacks; r=terrence (1417ff456a)
- Bug 1233831 - Part 1: Call the callback on nursery collections; r=terrence (cf720fc8c9)
- Bug 1233831 - Part 2: Expose JS::gcreason::ExplainReason to embedders; r=terrence (5eaceb2a58)
- Bug 1233831 - Part 3: Install a callback to trace nursery collections; r=mccr8 (13bc8d19ff)
- Bug 1233831 - Part 4: Add metadata for the minor GC markers; r=vporof (cb42e1e42a)
- Bug 1233831 - Part 5: Test the minor GC markers; r=vporof (5f8ae59242)
- Bug 1218468 - Remove worker markers on each check in browser_timelineMarkers-02.js, r=me (33efc054c0)
- Bug 1233831 - Follow up: Expand sanitizeMarkers to filter out minor GC markers; r=jsantell (b99fb1dbbc)
- Bug 1239314 - Make marking validation a normal zeal mode; r=jonco (4668054d11)
- Bug 1233857 - Follow up: Add a new GC zeal mode for the elements edges barrier; r=terrence (61a7db4357)
- Bug 1245767 - Allow combining different gczeal modes. r=terrence (8d90fd103e)
- Bug 1242262 - Remove the last vestiges of JS_GC_MARKING_VALIDATION (it's a GC Zeal mode now). r=terrence (3ca086aed4)
- Bug 1249795 - Clear strong refs to message managers once we've destroyed nsFrameLoader, r=billm (b562395eb9)
- Bug 1244405 - Baldr: add memory segments (r=sunfish) (c7850ee495)
- Bug 1246433 - BaldrMonkey: Implement integer and float literals. r=luke (d668caa1bd)
- Bug 1240583 - Odin: refactor x86/x64 loads/stores (r=sunfish) (df85bc0aa3)
- Bug 1240583 - Odin: replace retargetWithOffset (r=bbouvier) (627815cb6d)
- Bug 757969 - use __thread in ThreadLocal; r=froydnj (5e06f7ef9e)
- bug 1244128 - stop exporting js friend api symbols from libxul r=glandium (894792316d)
- Bug 912337 - Make a new Error subclass: Debugger.DebuggeeWouldRun. (r=jimb) (a020dfd40c)
- Bug 1248101 - Make dtoa_malloc infallible. r=sfink. (0828c1b15b)
- Bug 1245737 (part 1) - Enable |Omit_Private_Memory| for our dtoa implementation. r=bhackett. (aaa0ebad66)
- Bug 1245737 (part 0) - Fix a leak in DtoaState. r=sfink. (3007242e86)
- Bug 1245737 (part 2) - Don't bother measuring DtoaState. r=bhackett. (db33501ddd)
- Bug 1243888 - Derive RootKind automatically from TraceKind; r=sfink (08421e1c6c)
- Bug 1244358 - Support all types in PersistentRooted; r=sfink (bc1a8ada00)
- Bug 1248233. Make js::ReportOutOfMemory respect the autoJSAPIOwnsErrorReporting() flag on the context options. r=luke (5ee05b61e6)
- Bug 1235151 - Factor all the install.rdfs used for langpacks. r=mshal (0e10679502)
- Bug 1235151 - Use #include in toolkit/locales/generic/install.rdf instead of -I on the preprocessor command line. r=mshal (31fdfea3de)
- Bug 1227388 - Finish removing dehydra support. r=mshal (aa43dfce95)
- Bug 1205814 - mozilla eslint plug: allow top level var only r=pbrosset (f247252d4b)
- Bug 1218409 - Eslint rule that checks for balanced listeners. r=miker (45d42a1014)
- Bug 1205814 - Missed a brief description in rst docs r=pbrosset (13fb24c5c4)
- Bug 1218425 - ESLint rule that warns against aArg notation in function params; r=miker (e811f2c8f7)
- Bug 1217851 - Fix mozplugin's import-headjs-globals on Windows. r=pbro (685f450fcb)
- Bug 1218412 - Create ESLint rule to check for CPOWS in browser mochitests r=pbrosset (c505ab4ed3)
- Bug 1217922 - eslint head.js plugin does not seem to work r=pbrosset (8d3782057e)
- Bug 1224735 - don't use "for..of" in eslint plugin. r=miker (90ecebec24)
- Bug 1225289 - Make eslint plugin code conform to .eslintrc r=pbrosset (007bf4c6b8)
- Bug 1222232 - Help mach eslint find espree and escope r=pbrosset (d0f7c5987b)
- Bug 1229858: Add a preprocessor to convert XBL into JavaScript blocks for eslint. r=miker (99bd8d62c4)
- Bug 1230300: Fix mach eslint to pass command arguments through to eslint. r=gps (7b54b30a8f)
- Bug 1231720 - Log when ESLint finishes running. r=nalexander (12705e260d)
- Bug 1234164 - Fix Ion GETNAME stubs to check for uninitialized lexicals. (r=efaust) (561d6e2d1c)
- Bug 1239519 - Fix debug-only initializion order issue detected by ASan. r=luke (8aa8b63fb6)
- Bug 1242840 - Drop profiler invalidation event if we hit OOM and make invalidation infallible r=jandem (8dfe4d99a5)
- Bug 1232386 - Fix NativeObject::growSlotsStatic to recover from OOM. r=terrence (284f47d6b1)
- Bug 1235032 - check value of obj, remake while () {} to do { } while(). r=jorendorff (0cb646a76e)
- Bug 1228327 - Fix bogus assert in GenerateDenseElementHole, add some comments. r=bhackett (e7fc0db6a0)
- Bug 1232859 - Don't crash or abort compilation if we're unable to compile the regex stubs. r=nbp (0ec48d44b5)
- Bug 1237566 - Bake in global this-value in IonBuilder::jsop_functionthis in some cases. r=h4writer (bd1fb0e8d8)
- Bug 1000780 - Part 7: Fix perf regressions introduced in part 1. r=jandem (629452aa16)
- Bug 1240100: IonMonkey: Magic values cannot flow through an instruction, r=jandem (f644caf377)
- Bug 1244098 - Attempt to fold JSOP_IN to false in IonBuilder based on TI. r=bhackett (e964e1d2bf)
- Bug 1238592 - IonMonkey: Optimize away any OSR fixup blocks that are ultimately unreachable. r=nbp (3e7ad0d61a)
- Bug 1245171 - Ensure enough ballast space in js::jit::AddKeepAliveInstructions. r=jandem (ba48c30163)
- Bug 1244828 - Ensure enough ballast space in TypeAnalyzer::adjustPhiInputs. r=h4writer (126c899284)
- Bug 1244828 - Ensure enough ballast space in TypeAnalyzer::adjustInputs. r=h4writer (0bf3d584b9)
- Bug 1112537 - Optimize String#split('foo').join('bar') pattern. r=nbp (75fb0e4124)
2023-08-27 23:02:30 +08:00

1255 lines
32 KiB
C++

/* 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 <ostream>
#include <fstream>
#include <sstream>
#include <errno.h>
#include "platform.h"
#include "PlatformMacros.h"
#include "mozilla/ArrayUtils.h"
#include "mozilla/UniquePtr.h"
#include "GeckoProfiler.h"
#ifndef SPS_STANDALONE
#include "ProfilerIOInterposeObserver.h"
#include "mozilla/StaticPtr.h"
#endif
#include "mozilla/ThreadLocal.h"
#include "mozilla/TimeStamp.h"
#include "PseudoStack.h"
#include "GeckoSampler.h"
#ifndef SPS_STANDALONE
#include "nsIObserverService.h"
#include "nsDirectoryServiceUtils.h"
#include "nsDirectoryServiceDefs.h"
#include "nsXULAppAPI.h"
#include "nsProfilerStartParams.h"
#include "mozilla/Services.h"
#include "nsThreadUtils.h"
#endif
#include "ProfilerMarkers.h"
#ifdef MOZ_TASK_TRACER
#include "GeckoTaskTracer.h"
#endif
#if defined(SPS_OS_android) && !defined(MOZ_WIDGET_GONK)
#include "AndroidBridge.h"
#endif
#if defined(SPS_OS_android) && !defined(MOZ_WIDGET_GONK)
#include "GeneratedJNINatives.h"
#endif
#ifndef SPS_STANDALONE
#if defined(SPS_PLAT_amd64_linux) || defined(SPS_PLAT_x86_linux)
# define USE_LUL_STACKWALK
# include "lul/LulMain.h"
# include "lul/platform-linux-lul.h"
#endif
#endif
#if defined(SPS_OS_android) && !defined(MOZ_WIDGET_GONK)
class GeckoJavaSampler : public widget::GeckoJavaSampler::Natives<GeckoJavaSampler>
{
private:
GeckoJavaSampler();
public:
static double GetProfilerTime() {
if (!profiler_is_active()) {
return 0.0;
}
return profiler_time();
};
};
#endif
MOZ_THREAD_LOCAL(PseudoStack *) tlsPseudoStack;
MOZ_THREAD_LOCAL(GeckoSampler *) tlsTicker;
MOZ_THREAD_LOCAL(void *) tlsStackTop;
// We need to track whether we've been initialized otherwise
// we end up using tlsStack without initializing it.
// Because tlsStack is totally opaque to us we can't reuse
// it as the flag itself.
bool stack_key_initialized;
mozilla::TimeStamp sLastTracerEvent; // is raced on
mozilla::TimeStamp sStartTime;
int sFrameNumber = 0;
int sLastFrameNumber = 0;
int sInitCount = 0; // Each init must have a matched shutdown.
static bool sIsProfiling = false; // is raced on
static bool sIsGPUProfiling = false; // is raced on
static bool sIsLayersDump = false; // is raced on
static bool sIsDisplayListDump = false; // is raced on
static bool sIsRestyleProfiling = false; // is raced on
// Environment variables to control the profiler
const char* PROFILER_HELP = "MOZ_PROFILER_HELP";
const char* PROFILER_INTERVAL = "MOZ_PROFILER_INTERVAL";
const char* PROFILER_ENTRIES = "MOZ_PROFILER_ENTRIES";
const char* PROFILER_STACK = "MOZ_PROFILER_STACK_SCAN";
const char* PROFILER_FEATURES = "MOZ_PROFILING_FEATURES";
/* we don't need to worry about overflow because we only treat the
* case of them being the same as special. i.e. we only run into
* a problem if 2^32 events happen between samples that we need
* to know are associated with different events */
// Values harvested from env vars, that control the profiler.
static int sUnwindInterval; /* in milliseconds */
static int sUnwindStackScan; /* max # of dubious frames allowed */
static int sProfileEntries; /* how many entries do we store? */
std::vector<ThreadInfo*>* Sampler::sRegisteredThreads = nullptr;
mozilla::UniquePtr< ::Mutex> Sampler::sRegisteredThreadsMutex;
GeckoSampler* Sampler::sActiveSampler;
#ifndef SPS_STANDALONE
static mozilla::StaticAutoPtr<mozilla::ProfilerIOInterposeObserver>
sInterposeObserver;
#endif
// The name that identifies the gecko thread for calls to
// profiler_register_thread.
static const char * gGeckoThreadName = "GeckoMain";
void Sampler::Startup() {
sRegisteredThreads = new std::vector<ThreadInfo*>();
sRegisteredThreadsMutex = OS::CreateMutex("sRegisteredThreads mutex");
// We could create the sLUL object and read unwind info into it at
// this point. That would match the lifetime implied by destruction
// of it in Sampler::Shutdown just below. However, that gives a big
// delay on startup, even if no profiling is actually to be done.
// So, instead, sLUL is created on demand at the first call to
// Sampler::Start.
}
void Sampler::Shutdown() {
while (sRegisteredThreads->size() > 0) {
delete sRegisteredThreads->back();
sRegisteredThreads->pop_back();
}
sRegisteredThreadsMutex = nullptr;
delete sRegisteredThreads;
// UnregisterThread can be called after shutdown in XPCShell. Thus
// we need to point to null to ignore such a call after shutdown.
sRegisteredThreadsMutex = nullptr;
sRegisteredThreads = nullptr;
#if defined(USE_LUL_STACKWALK)
// Delete the sLUL object, if it actually got created.
if (sLUL) {
delete sLUL;
sLUL = nullptr;
}
#endif
}
StackOwningThreadInfo::StackOwningThreadInfo(const char* aName, int aThreadId,
bool aIsMainThread,
PseudoStack* aPseudoStack,
void* aStackTop)
: ThreadInfo(aName, aThreadId, aIsMainThread, aPseudoStack, aStackTop)
{
aPseudoStack->ref();
}
StackOwningThreadInfo::~StackOwningThreadInfo()
{
PseudoStack* stack = Stack();
if (stack) {
stack->deref();
}
}
void
StackOwningThreadInfo::SetPendingDelete()
{
PseudoStack* stack = Stack();
if (stack) {
stack->deref();
}
ThreadInfo::SetPendingDelete();
}
ProfilerMarker::ProfilerMarker(const char* aMarkerName,
ProfilerMarkerPayload* aPayload,
double aTime)
: mMarkerName(strdup(aMarkerName))
, mPayload(aPayload)
, mTime(aTime)
{
}
ProfilerMarker::~ProfilerMarker() {
free(mMarkerName);
delete mPayload;
}
void
ProfilerMarker::SetGeneration(uint32_t aGenID) {
mGenID = aGenID;
}
double
ProfilerMarker::GetTime() const {
return mTime;
}
void ProfilerMarker::StreamJSON(SpliceableJSONWriter& aWriter,
UniqueStacks& aUniqueStacks) const
{
// Schema:
// [name, time, data]
aWriter.StartArrayElement();
{
aUniqueStacks.mUniqueStrings.WriteElement(aWriter, GetMarkerName());
aWriter.DoubleElement(mTime);
// TODO: Store the callsite for this marker if available:
// if have location data
// b.NameValue(marker, "location", ...);
if (mPayload) {
aWriter.StartObjectElement();
{
mPayload->StreamPayload(aWriter, aUniqueStacks);
}
aWriter.EndObject();
}
}
aWriter.EndArray();
}
/* Has MOZ_PROFILER_VERBOSE been set? */
// Verbosity control for the profiler. The aim is to check env var
// MOZ_PROFILER_VERBOSE only once. However, we may need to temporarily
// override that so as to print the profiler's help message. That's
// what moz_profiler_set_verbosity is for.
enum class ProfilerVerbosity : int8_t { UNCHECKED, NOTVERBOSE, VERBOSE };
// Raced on, potentially
static ProfilerVerbosity profiler_verbosity = ProfilerVerbosity::UNCHECKED;
bool moz_profiler_verbose()
{
if (profiler_verbosity == ProfilerVerbosity::UNCHECKED) {
if (getenv("MOZ_PROFILER_VERBOSE") != nullptr)
profiler_verbosity = ProfilerVerbosity::VERBOSE;
else
profiler_verbosity = ProfilerVerbosity::NOTVERBOSE;
}
return profiler_verbosity == ProfilerVerbosity::VERBOSE;
}
void moz_profiler_set_verbosity(ProfilerVerbosity pv)
{
MOZ_ASSERT(pv == ProfilerVerbosity::UNCHECKED ||
pv == ProfilerVerbosity::VERBOSE);
profiler_verbosity = pv;
}
bool set_profiler_interval(const char* interval) {
if (interval) {
errno = 0;
long int n = strtol(interval, (char**)nullptr, 10);
if (errno == 0 && n >= 1 && n <= 1000) {
sUnwindInterval = n;
return true;
}
return false;
}
return true;
}
bool set_profiler_entries(const char* entries) {
if (entries) {
errno = 0;
long int n = strtol(entries, (char**)nullptr, 10);
if (errno == 0 && n > 0) {
sProfileEntries = n;
return true;
}
return false;
}
return true;
}
bool set_profiler_scan(const char* scanCount) {
if (scanCount) {
errno = 0;
long int n = strtol(scanCount, (char**)nullptr, 10);
if (errno == 0 && n >= 0 && n <= 100) {
sUnwindStackScan = n;
return true;
}
return false;
}
return true;
}
bool is_native_unwinding_avail() {
# if defined(HAVE_NATIVE_UNWIND)
return true;
#else
return false;
#endif
}
// Read env vars at startup, so as to set:
// sUnwindInterval, sProfileEntries, sUnwindStackScan.
void read_profiler_env_vars()
{
/* Set defaults */
sUnwindInterval = 0; /* We'll have to look elsewhere */
sProfileEntries = 0;
const char* interval = getenv(PROFILER_INTERVAL);
const char* entries = getenv(PROFILER_ENTRIES);
const char* scanCount = getenv(PROFILER_STACK);
if (getenv(PROFILER_HELP)) {
// Enable verbose output
moz_profiler_set_verbosity(ProfilerVerbosity::VERBOSE);
profiler_usage();
// Now force the next enquiry of moz_profiler_verbose to re-query
// env var MOZ_PROFILER_VERBOSE.
moz_profiler_set_verbosity(ProfilerVerbosity::UNCHECKED);
}
if (!set_profiler_interval(interval) ||
!set_profiler_entries(entries) ||
!set_profiler_scan(scanCount)) {
profiler_usage();
} else {
LOG( "SPS:");
LOGF("SPS: Sampling interval = %d ms (zero means \"platform default\")",
(int)sUnwindInterval);
LOGF("SPS: Entry store size = %d (zero means \"platform default\")",
(int)sProfileEntries);
LOGF("SPS: UnwindStackScan = %d (max dubious frames per unwind).",
(int)sUnwindStackScan);
LOG( "SPS:");
}
}
void profiler_usage() {
LOG( "SPS: ");
LOG( "SPS: Environment variable usage:");
LOG( "SPS: ");
LOG( "SPS: MOZ_PROFILER_HELP");
LOG( "SPS: If set to any value, prints this message.");
LOG( "SPS: ");
LOG( "SPS: MOZ_PROFILER_INTERVAL=<number> (milliseconds, 1 to 1000)");
LOG( "SPS: If unset, platform default is used.");
LOG( "SPS: ");
LOG( "SPS: MOZ_PROFILER_ENTRIES=<number> (count, minimum of 1)");
LOG( "SPS: If unset, platform default is used.");
LOG( "SPS: ");
LOG( "SPS: MOZ_PROFILER_VERBOSE");
LOG( "SPS: If set to any value, increases verbosity (recommended).");
LOG( "SPS: ");
LOG( "SPS: MOZ_PROFILER_STACK_SCAN=<number> (default is zero)");
LOG( "SPS: The number of dubious (stack-scanned) frames allowed");
LOG( "SPS: ");
LOG( "SPS: MOZ_PROFILER_LUL_TEST");
LOG( "SPS: If set to any value, runs LUL unit tests at startup of");
LOG( "SPS: the unwinder thread, and prints a short summary of results.");
LOG( "SPS: ");
LOGF("SPS: This platform %s native unwinding.",
is_native_unwinding_avail() ? "supports" : "does not support");
LOG( "SPS: ");
/* Re-set defaults */
sUnwindInterval = 0; /* We'll have to look elsewhere */
sProfileEntries = 0;
sUnwindStackScan = 0;
LOG( "SPS:");
LOGF("SPS: Sampling interval = %d ms (zero means \"platform default\")",
(int)sUnwindInterval);
LOGF("SPS: Entry store size = %d (zero means \"platform default\")",
(int)sProfileEntries);
LOGF("SPS: UnwindStackScan = %d (max dubious frames per unwind).",
(int)sUnwindStackScan);
LOG( "SPS:");
return;
}
void set_tls_stack_top(void* stackTop)
{
// Round |stackTop| up to the end of the containing page. We may
// as well do this -- there's no danger of a fault, and we might
// get a few more base-of-the-stack frames as a result. This
// assumes that no target has a page size smaller than 4096.
uintptr_t stackTopR = (uintptr_t)stackTop;
if (stackTop) {
stackTopR = (stackTopR & ~(uintptr_t)4095) + (uintptr_t)4095;
}
tlsStackTop.set((void*)stackTopR);
}
bool is_main_thread_name(const char* aName) {
if (!aName) {
return false;
}
return strcmp(aName, gGeckoThreadName) == 0;
}
#ifndef SPS_STANDALONE
#ifdef HAVE_VA_COPY
#define VARARGS_ASSIGN(foo, bar) VA_COPY(foo,bar)
#elif defined(HAVE_VA_LIST_AS_ARRAY)
#define VARARGS_ASSIGN(foo, bar) foo[0] = bar[0]
#else
#define VARARGS_ASSIGN(foo, bar) (foo) = (bar)
#endif
void
mozilla_sampler_log(const char *fmt, va_list args)
{
if (profiler_is_active()) {
// nsAutoCString AppendPrintf would be nicer but
// this is mozilla external code
char buf[2048];
va_list argsCpy;
VARARGS_ASSIGN(argsCpy, args);
int required = vsnprintf(buf, sizeof(buf), fmt, argsCpy);
va_end(argsCpy);
if (required < 0) {
return; // silently drop for now
} else if (required < 2048) {
profiler_tracing("log", buf, TRACING_EVENT);
} else {
char* heapBuf = new char[required+1];
va_list argsCpy;
VARARGS_ASSIGN(argsCpy, args);
vsnprintf(heapBuf, required+1, fmt, argsCpy);
va_end(argsCpy);
// EVENT_BACKTRACE could be used to get a source
// for all log events. This could be a runtime
// flag later.
profiler_tracing("log", heapBuf, TRACING_EVENT);
delete[] heapBuf;
}
}
}
#endif
////////////////////////////////////////////////////////////////////////
// BEGIN externally visible functions
void mozilla_sampler_init(void* stackTop)
{
sInitCount++;
if (stack_key_initialized)
return;
#ifdef MOZ_TASK_TRACER
mozilla::tasktracer::InitTaskTracer();
#endif
#ifdef SPS_STANDALONE
mozilla::TimeStamp::Startup();
#endif
LOG("BEGIN mozilla_sampler_init");
if (!tlsPseudoStack.init() || !tlsTicker.init() || !tlsStackTop.init()) {
LOG("Failed to init.");
return;
}
bool ignore;
sStartTime = mozilla::TimeStamp::ProcessCreation(ignore);
stack_key_initialized = true;
Sampler::Startup();
PseudoStack *stack = PseudoStack::create();
tlsPseudoStack.set(stack);
bool isMainThread = true;
Sampler::RegisterCurrentThread(isMainThread ?
gGeckoThreadName : "Application Thread",
stack, isMainThread, stackTop);
// Read interval settings from MOZ_PROFILER_INTERVAL and stack-scan
// threshhold from MOZ_PROFILER_STACK_SCAN.
read_profiler_env_vars();
// platform specific initialization
OS::Startup();
#ifndef SPS_STANDALONE
set_stderr_callback(mozilla_sampler_log);
#endif
#if defined(SPS_OS_android) && !defined(MOZ_WIDGET_GONK)
if (mozilla::jni::IsAvailable()) {
GeckoJavaSampler::Init();
}
#endif
// We can't open pref so we use an environment variable
// to know if we should trigger the profiler on startup
// NOTE: Default
const char *val = getenv("MOZ_PROFILER_STARTUP");
if (!val || !*val) {
return;
}
const char* features[] = {"js"
, "leaf"
, "threads"
#if defined(XP_WIN) || defined(XP_MACOSX) \
|| (defined(SPS_ARCH_arm) && defined(linux)) \
|| defined(SPS_PLAT_amd64_linux) || defined(SPS_PLAT_x86_linux)
, "stackwalk"
#endif
#if defined(SPS_OS_android) && !defined(MOZ_WIDGET_GONK)
, "java"
#endif
};
const char* threadFilters[] = { "GeckoMain", "Compositor" };
profiler_start(PROFILE_DEFAULT_ENTRY, PROFILE_DEFAULT_INTERVAL,
features, MOZ_ARRAY_LENGTH(features),
threadFilters, MOZ_ARRAY_LENGTH(threadFilters));
LOG("END mozilla_sampler_init");
}
void mozilla_sampler_shutdown()
{
sInitCount--;
if (sInitCount > 0)
return;
// Save the profile on shutdown if requested.
GeckoSampler *t = tlsTicker.get();
if (t) {
const char *val = getenv("MOZ_PROFILER_SHUTDOWN");
if (val) {
std::ofstream stream;
stream.open(val);
if (stream.is_open()) {
t->ToStreamAsJSON(stream);
stream.close();
}
}
}
profiler_stop();
#ifndef SPS_STANDALONE
set_stderr_callback(nullptr);
#endif
Sampler::Shutdown();
#ifdef SPS_STANDALONE
mozilla::TimeStamp::Shutdown();
#endif
PseudoStack *stack = tlsPseudoStack.get();
stack->deref();
tlsPseudoStack.set(nullptr);
#ifdef MOZ_TASK_TRACER
mozilla::tasktracer::ShutdownTaskTracer();
#endif
}
void mozilla_sampler_save()
{
GeckoSampler *t = tlsTicker.get();
if (!t) {
return;
}
t->RequestSave();
// We're on the main thread already so we don't
// have to wait to handle the save request.
t->HandleSaveRequest();
}
mozilla::UniquePtr<char[]> mozilla_sampler_get_profile(double aSinceTime)
{
GeckoSampler *t = tlsTicker.get();
if (!t) {
return nullptr;
}
return t->ToJSON(aSinceTime);
}
#ifndef SPS_STANDALONE
JSObject *mozilla_sampler_get_profile_data(JSContext *aCx, double aSinceTime)
{
GeckoSampler *t = tlsTicker.get();
if (!t) {
return nullptr;
}
return t->ToJSObject(aCx, aSinceTime);
}
void mozilla_sampler_get_profile_data_async(double aSinceTime,
mozilla::dom::Promise* aPromise)
{
GeckoSampler *t = tlsTicker.get();
if (NS_WARN_IF(!t)) {
return;
}
t->ToJSObjectAsync(aSinceTime, aPromise);
}
void mozilla_sampler_get_profiler_start_params(int* aEntrySize,
double* aInterval,
mozilla::Vector<const char*>* aFilters,
mozilla::Vector<const char*>* aFeatures)
{
if (NS_WARN_IF(!aEntrySize) || NS_WARN_IF(!aInterval) ||
NS_WARN_IF(!aFilters) || NS_WARN_IF(!aFeatures)) {
return;
}
GeckoSampler *t = tlsTicker.get();
if (NS_WARN_IF(!t)) {
return;
}
*aEntrySize = t->EntrySize();
*aInterval = t->interval();
const ThreadNameFilterList& threadNameFilterList = t->ThreadNameFilters();
MOZ_ALWAYS_TRUE(aFilters->resize(threadNameFilterList.length()));
for (uint32_t i = 0; i < threadNameFilterList.length(); ++i) {
(*aFilters)[i] = threadNameFilterList[i].c_str();
}
const FeatureList& featureList = t->Features();
MOZ_ALWAYS_TRUE(aFeatures->resize(featureList.length()));
for (size_t i = 0; i < featureList.length(); ++i) {
(*aFeatures)[i] = featureList[i].c_str();
}
}
void mozilla_sampler_get_gatherer(nsISupports** aRetVal)
{
if (!aRetVal) {
return;
}
if (NS_WARN_IF(!profiler_is_active())) {
*aRetVal = nullptr;
return;
}
GeckoSampler *t = tlsTicker.get();
if (NS_WARN_IF(!t)) {
*aRetVal = nullptr;
return;
}
t->GetGatherer(aRetVal);
}
#endif
void mozilla_sampler_save_profile_to_file(const char* aFilename)
{
GeckoSampler *t = tlsTicker.get();
if (!t) {
return;
}
std::ofstream stream;
stream.open(aFilename);
if (stream.is_open()) {
t->ToStreamAsJSON(stream);
stream.close();
LOGF("Saved to %s", aFilename);
} else {
LOG("Fail to open profile log file.");
}
}
const char** mozilla_sampler_get_features()
{
static const char* features[] = {
#if defined(MOZ_PROFILING) && defined(HAVE_NATIVE_UNWIND)
// Walk the C++ stack.
"stackwalk",
#endif
#if defined(ENABLE_SPS_LEAF_DATA)
// Include the C++ leaf node if not stackwalking. DevTools
// profiler doesn't want the native addresses.
"leaf",
#endif
#if !defined(SPS_OS_windows)
// Use a seperate thread of walking the stack.
"unwinder",
#endif
"java",
// Only record samples during periods of bad responsiveness
"jank",
// Tell the JS engine to emmit pseudostack entries in the
// pro/epilogue.
"js",
// GPU Profiling (may not be supported by the GL)
"gpu",
// Profile the registered secondary threads.
"threads",
// Do not include user-identifiable information
"privacy",
// Dump the layer tree with the textures.
"layersdump",
// Dump the display list with the textures.
"displaylistdump",
// Add main thread I/O to the profile
"mainthreadio",
// Add RSS collection
"memory",
#ifdef MOZ_TASK_TRACER
// Start profiling with feature TaskTracer.
"tasktracer",
#endif
#if defined(XP_WIN)
// Add power collection
"power",
#endif
nullptr
};
return features;
}
void mozilla_sampler_get_buffer_info(uint32_t *aCurrentPosition, uint32_t *aTotalSize,
uint32_t *aGeneration)
{
*aCurrentPosition = 0;
*aTotalSize = 0;
*aGeneration = 0;
if (!stack_key_initialized)
return;
GeckoSampler *t = tlsTicker.get();
if (!t)
return;
t->GetBufferInfo(aCurrentPosition, aTotalSize, aGeneration);
}
// Values are only honored on the first start
void mozilla_sampler_start(int aProfileEntries, double aInterval,
const char** aFeatures, uint32_t aFeatureCount,
const char** aThreadNameFilters, uint32_t aFilterCount)
{
LOG("BEGIN mozilla_sampler_start");
if (!stack_key_initialized)
profiler_init(nullptr);
/* If the sampling interval was set using env vars, use that
in preference to anything else. */
if (sUnwindInterval > 0)
aInterval = sUnwindInterval;
/* If the entry count was set using env vars, use that, too: */
if (sProfileEntries > 0)
aProfileEntries = sProfileEntries;
// Reset the current state if the profiler is running
profiler_stop();
GeckoSampler* t;
t = new GeckoSampler(aInterval ? aInterval : PROFILE_DEFAULT_INTERVAL,
aProfileEntries ? aProfileEntries : PROFILE_DEFAULT_ENTRY,
aFeatures, aFeatureCount,
aThreadNameFilters, aFilterCount);
tlsTicker.set(t);
t->Start();
if (t->ProfileJS() || t->InPrivacyMode()) {
::MutexAutoLock lock(*Sampler::sRegisteredThreadsMutex);
std::vector<ThreadInfo*> threads = t->GetRegisteredThreads();
for (uint32_t i = 0; i < threads.size(); i++) {
ThreadInfo* info = threads[i];
if (info->IsPendingDelete()) {
continue;
}
ThreadProfile* thread_profile = info->Profile();
if (!thread_profile) {
continue;
}
thread_profile->GetPseudoStack()->reinitializeOnResume();
#ifndef SPS_STANDALONE
if (t->ProfileJS()) {
thread_profile->GetPseudoStack()->enableJSSampling();
}
if (t->InPrivacyMode()) {
thread_profile->GetPseudoStack()->mPrivacyMode = true;
}
#endif
}
}
#if defined(SPS_OS_android) && !defined(MOZ_WIDGET_GONK)
if (t->ProfileJava()) {
int javaInterval = aInterval;
// Java sampling doesn't accuratly keep up with 1ms sampling
if (javaInterval < 10) {
aInterval = 10;
}
mozilla::widget::GeckoJavaSampler::StartJavaProfiling(javaInterval, 1000);
}
#endif
#ifndef SPS_STANDALONE
if (t->AddMainThreadIO()) {
if (!sInterposeObserver) {
// Lazily create IO interposer observer
sInterposeObserver = new mozilla::ProfilerIOInterposeObserver();
}
mozilla::IOInterposer::Register(mozilla::IOInterposeObserver::OpAll,
sInterposeObserver);
}
#endif
sIsProfiling = true;
#ifndef SPS_STANDALONE
sIsGPUProfiling = t->ProfileGPU();
sIsLayersDump = t->LayersDump();
sIsDisplayListDump = t->DisplayListDump();
sIsRestyleProfiling = t->ProfileRestyle();
if (Sampler::CanNotifyObservers()) {
nsCOMPtr<nsIObserverService> os = mozilla::services::GetObserverService();
if (os) {
nsTArray<nsCString> featuresArray;
nsTArray<nsCString> threadNameFiltersArray;
for (size_t i = 0; i < aFeatureCount; ++i) {
featuresArray.AppendElement(aFeatures[i]);
}
for (size_t i = 0; i < aFilterCount; ++i) {
threadNameFiltersArray.AppendElement(aThreadNameFilters[i]);
}
nsCOMPtr<nsIProfilerStartParams> params =
new nsProfilerStartParams(aProfileEntries, aInterval, featuresArray,
threadNameFiltersArray);
os->NotifyObservers(params, "profiler-started", nullptr);
}
}
#endif
LOG("END mozilla_sampler_start");
}
void mozilla_sampler_stop()
{
LOG("BEGIN mozilla_sampler_stop");
if (!stack_key_initialized)
return;
GeckoSampler *t = tlsTicker.get();
if (!t) {
LOG("END mozilla_sampler_stop-early");
return;
}
bool disableJS = t->ProfileJS();
t->Stop();
delete t;
tlsTicker.set(nullptr);
#ifndef SPS_STANDALONE
if (disableJS) {
PseudoStack *stack = tlsPseudoStack.get();
ASSERT(stack != nullptr);
stack->disableJSSampling();
}
mozilla::IOInterposer::Unregister(mozilla::IOInterposeObserver::OpAll,
sInterposeObserver);
sInterposeObserver = nullptr;
#endif
sIsProfiling = false;
#ifndef SPS_STANDALONE
sIsGPUProfiling = false;
sIsLayersDump = false;
sIsDisplayListDump = false;
sIsRestyleProfiling = false;
if (Sampler::CanNotifyObservers()) {
nsCOMPtr<nsIObserverService> os = mozilla::services::GetObserverService();
if (os)
os->NotifyObservers(nullptr, "profiler-stopped", nullptr);
}
#endif
LOG("END mozilla_sampler_stop");
}
bool mozilla_sampler_is_paused() {
if (Sampler::GetActiveSampler()) {
return Sampler::GetActiveSampler()->IsPaused();
} else {
return false;
}
}
void mozilla_sampler_pause() {
if (Sampler::GetActiveSampler()) {
Sampler::GetActiveSampler()->SetPaused(true);
#ifndef SPS_STANDALONE
if (Sampler::CanNotifyObservers()) {
nsCOMPtr<nsIObserverService> os = mozilla::services::GetObserverService();
if (os)
os->NotifyObservers(nullptr, "profiler-paused", nullptr);
}
#endif
}
}
void mozilla_sampler_resume() {
if (Sampler::GetActiveSampler()) {
Sampler::GetActiveSampler()->SetPaused(false);
#ifndef SPS_STANDALONE
if (Sampler::CanNotifyObservers()) {
nsCOMPtr<nsIObserverService> os = mozilla::services::GetObserverService();
if (os)
os->NotifyObservers(nullptr, "profiler-resumed", nullptr);
}
#endif
}
}
bool mozilla_sampler_feature_active(const char* aName)
{
if (!profiler_is_active()) {
return false;
}
if (strcmp(aName, "gpu") == 0) {
return sIsGPUProfiling;
}
if (strcmp(aName, "layersdump") == 0) {
return sIsLayersDump;
}
if (strcmp(aName, "displaylistdump") == 0) {
return sIsDisplayListDump;
}
if (strcmp(aName, "restyle") == 0) {
return sIsRestyleProfiling;
}
return false;
}
bool mozilla_sampler_is_active()
{
return sIsProfiling;
}
void mozilla_sampler_responsiveness(const mozilla::TimeStamp& aTime)
{
sLastTracerEvent = aTime;
}
void mozilla_sampler_frame_number(int frameNumber)
{
sFrameNumber = frameNumber;
}
void mozilla_sampler_lock()
{
profiler_stop();
#ifndef SPS_STANDALONE
nsCOMPtr<nsIObserverService> os = mozilla::services::GetObserverService();
if (os)
os->NotifyObservers(nullptr, "profiler-locked", nullptr);
#endif
}
void mozilla_sampler_unlock()
{
#ifndef SPS_STANDALONE
nsCOMPtr<nsIObserverService> os = mozilla::services::GetObserverService();
if (os)
os->NotifyObservers(nullptr, "profiler-unlocked", nullptr);
#endif
}
bool mozilla_sampler_register_thread(const char* aName, void* aGuessStackTop)
{
if (sInitCount == 0) {
return false;
}
#if defined(MOZ_WIDGET_GONK) && !defined(MOZ_PROFILING)
// The only way to profile secondary threads on b2g
// is to build with profiling OR have the profiler
// running on startup.
if (!profiler_is_active()) {
return false;
}
#endif
MOZ_ASSERT(tlsPseudoStack.get() == nullptr);
PseudoStack* stack = PseudoStack::create();
tlsPseudoStack.set(stack);
bool isMainThread = is_main_thread_name(aName);
void* stackTop = GetStackTop(aGuessStackTop);
return Sampler::RegisterCurrentThread(aName, stack, isMainThread, stackTop);
}
void mozilla_sampler_unregister_thread()
{
// Don't check sInitCount count here -- we may be unregistering the
// thread after the sampler was shut down.
if (!stack_key_initialized) {
return;
}
PseudoStack *stack = tlsPseudoStack.get();
if (!stack) {
return;
}
stack->deref();
tlsPseudoStack.set(nullptr);
Sampler::UnregisterCurrentThread();
}
void mozilla_sampler_sleep_start() {
if (sInitCount == 0) {
return;
}
PseudoStack *stack = tlsPseudoStack.get();
if (stack == nullptr) {
return;
}
stack->setSleeping(1);
}
void mozilla_sampler_sleep_end() {
if (sInitCount == 0) {
return;
}
PseudoStack *stack = tlsPseudoStack.get();
if (stack == nullptr) {
return;
}
stack->setSleeping(0);
}
double mozilla_sampler_time(const mozilla::TimeStamp& aTime)
{
mozilla::TimeDuration delta = aTime - sStartTime;
return delta.ToMilliseconds();
}
double mozilla_sampler_time()
{
return mozilla_sampler_time(mozilla::TimeStamp::Now());
}
ProfilerBacktrace* mozilla_sampler_get_backtrace()
{
if (!stack_key_initialized)
return nullptr;
// Don't capture a stack if we're not profiling
if (!profiler_is_active()) {
return nullptr;
}
// Don't capture a stack if we don't want to include personal information
if (profiler_in_privacy_mode()) {
return nullptr;
}
GeckoSampler* t = tlsTicker.get();
if (!t) {
return nullptr;
}
return new ProfilerBacktrace(t->GetBacktrace());
}
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)
{
mozilla_sampler_add_marker(aInfo, new ProfilerMarkerTracing(aCategory, aMetaData));
}
void mozilla_sampler_tracing(const char* aCategory, const char* aInfo,
ProfilerBacktrace* aCause,
TracingMetadata aMetaData)
{
mozilla_sampler_add_marker(aInfo, new ProfilerMarkerTracing(aCategory, aMetaData, aCause));
}
void mozilla_sampler_add_marker(const char *aMarker, ProfilerMarkerPayload *aPayload)
{
// Note that aPayload may be allocated by the caller, so we need to make sure
// that we free it at some point.
mozilla::UniquePtr<ProfilerMarkerPayload> payload(aPayload);
if (!stack_key_initialized)
return;
// Don't insert a marker if we're not profiling to avoid
// the heap copy (malloc).
if (!profiler_is_active()) {
return;
}
// Don't add a marker if we don't want to include personal information
if (profiler_in_privacy_mode()) {
return;
}
PseudoStack *stack = tlsPseudoStack.get();
if (!stack) {
return;
}
mozilla::TimeStamp origin = (aPayload && !aPayload->GetStartTime().IsNull()) ?
aPayload->GetStartTime() : mozilla::TimeStamp::Now();
mozilla::TimeDuration delta = origin - sStartTime;
stack->addMarker(aMarker, payload.release(), delta.ToMilliseconds());
}
#ifndef SPS_STANDALONE
#include "mozilla/Mutex.h"
class GeckoMutex : public ::Mutex {
public:
explicit GeckoMutex(const char* aDesc) :
mMutex(aDesc)
{}
virtual ~GeckoMutex() {}
virtual int Lock() {
mMutex.Lock();
return 0;
}
virtual int Unlock() {
mMutex.Unlock();
return 0;
}
private:
mozilla::Mutex mMutex;
};
mozilla::UniquePtr< ::Mutex> OS::CreateMutex(const char* aDesc) {
return mozilla::MakeUnique<GeckoMutex>(aDesc);
}
#else
// Otherwise use c++11 Mutex
#include <mutex>
class OSXMutex : public ::Mutex {
public:
OSXMutex(const char* aDesc) :
mMutex()
{}
virtual ~OSXMutex() {}
virtual int Lock() {
mMutex.lock();
return 0;
}
virtual int Unlock() {
mMutex.unlock();
return 0;
}
private:
std::mutex mMutex;
};
mozilla::UniquePtr< ::Mutex> OS::CreateMutex(const char* aDesc) {
return mozilla::MakeUnique<GeckoMutex>(aDesc);
}
#endif
// END externally visible functions
////////////////////////////////////////////////////////////////////////