Files
palemoon27/toolkit/devtools/server/ChromeUtils.cpp
T
roytam1 6629d22907 import changes from `dev' branch of rmottola/Arctic-Fox:
- Bug 1170717 - Move heapState check up to readBarrier; r=jonco (b9c4df5ea)
- Bug 1163908 - Export GL draw data to layerscope for drawing heat-map view. r=:djg (cf078d4fd)
- Bug 1161372 - Add EventRegions on LayerScope. r=dglastonbury (49fc29e8a)
- Files as of Bug 1138721 - Application reputation should check mac file extensions. r=mmc (4b76de8d8)
- Bug 1024774 - Part 0: Upgrade the protobuf library. r=mmc,glandium (c98c08fbd)
- Bug 1149397 - JS::ubi::Node::edges should return a mozilla::UniquePtr; r=jimb (32f755867)
- Bug 1110039 - Part 1 - Add nsLayoutUtils::ClampRectToScrollFrames. r=roc (a8812c287)
- Bug 1110039 - Part 2.1 - Add logger facility. r=roc (1a400bb1f)
- Bug 1110039 - Part 2.2 - Add AccessibleCaret. r=roc (d8c2c759f)
- Bug 1110039 - Part 2.3 - Add AccessibleCaretManager. r=roc (ba8ad6424)
- Bug 1110039 - Part 2.4 - Add AccessibleCaretEventHub. r=roc (db4ef1fe6)
- Bug 1110039 - Part 2.5 - Add all files to build system. r=roc (bee54dc43)
- fix nsRefPtr includes - but build still broken (423d9f32d)
- Bug 1110039 - Part 3 - Add gtest for AccessibleCaretEventHub. r=roc (cdf0df240)
- Bug 1110039 - Part 4 - Hook new classes into the system. r=roc (438a4df68)
- Bug 1109183 - Fix imports of the marionette client and remove spurious entry from sys.path provided by mach. r=ahal (86b814562)
- Bug 1110039 - Part 5 - Reuse marionette tests for AccessibleCaret. r=roc (d5cd35016)
- Bug 1110039 followup: Add 'override' keyword to Name() decl in Access# (cd0d9b0f6)
- Bug 1140994 - Notify gaia to hide selection bubble when scrolling without APZ. r=roc (ca15626fa)
- Bug 1143665 - Remove the ambiguous scroll position being passed around in scroll started/stop notifications. r=roc,ehsan (ce8f1d2a9)
- Bug 1140238 - Part 1: Add a test to drag first caret over non-selectable. r=automatedtester (4080723fe)
- Bug 1140238 - Part 2: Adjust ranges after changing selection direction. r=mats (add1f155d)
- Bug 1140238 - Part 3: Clear maintain selection when dragging caret. r=mats (0aba36f24)
- Bug 1024774 - Part 2: Implement a google::protobuf::ZeroCopyOutputStream wrapper around nsIOutputStream; r=jimb (30c6272d2)
- Bug 1024774 - Part 3: Serialize heap snapshots. r=jimb (9d0c8f6ec)
- Bug 1024774 - Part 1: Add the ChromeUtils WebIDL interface. r=bholley (8e81e8344)
- Bug 1024774 - Part 4: Add an xpcshell test for saving heap snapshots. r=jimb (6e0a07069)
- Bug 1024774 - Part 5: Add GTests for core dump serialization. r=jimb (79315c540)
- clean up spurious char (9a1f9bc18)
- Bug 1121528 - Avoid the inspector going blank when quickly navigating; r=bgrins (f4cff269f)
- Bug 1155168 - Always use the same actor pool. r=ochameau (3e6cc5504)
- Bug 1137527 - Part 1: Make the memory actor emit events for garbage collection. r=jryans (6dcdb18f8)
- Bug 1137527 - Part 2: Add a test for GC MemoryActor events. r=jryans (df2bcf120)
- Bug 1024774 - Part 6: Add a mochitest-chrome sanity check test. r=bholley (4b5bffe79)
- Bug 1024774 - Part 7: Add HeapSnapshot WebIDL interface; r=bholley (7b5ae703a)
- Bug 1024774 - Part 8: Add JS::ubi::Node::isLive; r=jimb (42a965f56)
- Bug 1024774 - Part 9: Deserialize heap snapshots; r=jimb (fb3edfbc0)
- Bug 1024774 - Part 10: Add an xpcshell test for reading heap snapshots. r=jimb (09c3390a1)
- Bug 1024774 - Part 11: Implement a JS::ubi::Node specialization for DeserializedNode; r=jimb (d73362efe)
- Bug 1024774 - Part 12: Add a GTest for the JS::ubi::Node specialization for DeserializedNode; r=jimb (4415acb73)
- Bug 1024774 - Part 13: Change to new SpiderMonkey style from bug 1144366; r=me (15c4bcf87)
- Bug 1024774 - Part 14: Ignore protobuf indirect calls in the GC hazard analysis; r=sfink (c5b141c59)
- Bug 1024774 - Followup: Don't redefine the Debugger property in xpcshell tests; r=jorendorff (dc4f1f109)
- Bug 1169791 - Strongly type NoteJSRoot; r=mccr8 (ba722a44f)
- Bug 1169791 - Strongly type MergeZone; r=mccr8 (a118cf612)
- Bug 1169791 - Strongly type GetTenuredGCThingZone; r=jonco, r=mccr8 (a4da82aea)
- Bug 1171780 - We no longer need to cast out of barrieried types in GC; r=jonco (be83218fa)
- Bug 1144361: Re-enable JIT code randomization on Win64. r=jandem (6c88b4312)
- pointer style (458344bcd)
- Bug 1156914 - Fix the MacroAssembler::pushValue(const Address&) footgun on 32 bit platforms. (r=jandem) (52d5c351d)
- Bug 1156030 - Remove some obsolete static assertion macros from the tree; r=Waldo (84d8f3fea)
- pointer style (ac3c92ce1)
- Bug 1151323 - Handle loading unboxed int32 properties into floating point registers, r=jandem. (790920f3d)
- Bug 1023297 - Use explicit constructors for ARM-specific classes. r=jandem (f7f12cd76)
- Bug 1164229 - Rename ARM SetCond_ to SBit. r=efaust (c55e1d535)
- Bug 977805 - Add an option to mark JIT pages as non-writable. r=luke bug 977805 - add missing #include. r=jandem (384abd6ad)
- Bug 1173992 - Add ARM64 build support. r=glandium (540a7c784)
- Bug 1170750 - Replace %f by %.16g in js/src. r=jandem (48f808c73)
- Bug 1170750 - Use mfbt snprintf_literal instead of sprintf. r=jandem (3b2016484)
- Bug 1170750 - jsprf.cpp: Sort headers properly. r=me (0956cd3a5)
- Bug 923717 - Use structured control flow when testing for the forceInlineCaches option, r=nbp. (fc1dcef6e)
- Bug 1158044 - Remove unused TypeWrapper class and untemplatize/cleanup some code. r=bhackett (a4d5de646)
- Bug 1169355 - Remove unnecessary assertion, r=jandem. (f55c99552)
- Bug 1162986 - Allow objects to be turned into singletons dynamically, r=jandem. (9c683e420)
- Bug 1169731 - [[Call]] on a class constructor should throw. (r=jandem) (470895e3f)
and fix for shared-js in UbiNode.h
2020-11-09 23:37:50 +08:00

433 lines
13 KiB
C++

/* -*- Mode: C++; 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 "ChromeUtils.h"
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/io/gzip_stream.h>
#include "mozilla/devtools/HeapSnapshot.h"
#include "mozilla/devtools/ZeroCopyNSIOutputStream.h"
#include "mozilla/Attributes.h"
#include "mozilla/UniquePtr.h"
#include "nsCRTGlue.h"
#include "nsIOutputStream.h"
#include "nsNetUtil.h"
#include "prerror.h"
#include "prio.h"
#include "prtypes.h"
#include "js/Debug.h"
#include "js/TypeDecls.h"
#include "js/UbiNodeTraverse.h"
namespace mozilla {
namespace devtools {
using namespace JS;
using namespace dom;
// If we are only taking a snapshot of the heap affected by the given set of
// globals, find the set of zones the globals are allocated within. Returns
// false on OOM failure.
static bool
PopulateZonesWithGlobals(ZoneSet& zones, AutoObjectVector& globals)
{
if (!zones.init())
return false;
unsigned length = globals.length();
for (unsigned i = 0; i < length; i++) {
if (!zones.put(GetObjectZone(globals[i])))
return false;
}
return true;
}
// Add the given set of globals as explicit roots in the given roots
// list. Returns false on OOM failure.
static bool
AddGlobalsAsRoots(AutoObjectVector& globals, ubi::RootList& roots)
{
unsigned length = globals.length();
for (unsigned i = 0; i < length; i++) {
if (!roots.addRoot(ubi::Node(globals[i].get()),
MOZ_UTF16("heap snapshot global")))
{
return false;
}
}
return true;
}
// Choose roots and limits for a traversal, given `boundaries`. Set `roots` to
// the set of nodes within the boundaries that are referred to by nodes
// outside. If `boundaries` does not include all JS zones, initialize `zones` to
// the set of included zones; otherwise, leave `zones` uninitialized. (You can
// use zones.initialized() to check.)
//
// If `boundaries` is incoherent, or we encounter an error while trying to
// handle it, or we run out of memory, set `rv` appropriately and return
// `false`.
static bool
EstablishBoundaries(JSContext* cx,
ErrorResult& rv,
const HeapSnapshotBoundaries& boundaries,
ubi::RootList& roots,
ZoneSet& zones)
{
MOZ_ASSERT(!roots.initialized());
MOZ_ASSERT(!zones.initialized());
bool foundBoundaryProperty = false;
if (boundaries.mRuntime.WasPassed()) {
foundBoundaryProperty = true;
if (!boundaries.mRuntime.Value()) {
rv.Throw(NS_ERROR_INVALID_ARG);
return false;
}
if (!roots.init()) {
rv.Throw(NS_ERROR_OUT_OF_MEMORY);
return false;
}
}
if (boundaries.mDebugger.WasPassed()) {
if (foundBoundaryProperty) {
rv.Throw(NS_ERROR_INVALID_ARG);
return false;
}
foundBoundaryProperty = true;
JSObject* dbgObj = boundaries.mDebugger.Value();
if (!dbgObj || !dbg::IsDebugger(*dbgObj)) {
rv.Throw(NS_ERROR_INVALID_ARG);
return false;
}
AutoObjectVector globals(cx);
if (!dbg::GetDebuggeeGlobals(cx, *dbgObj, globals) ||
!PopulateZonesWithGlobals(zones, globals) ||
!roots.init(zones) ||
!AddGlobalsAsRoots(globals, roots))
{
rv.Throw(NS_ERROR_OUT_OF_MEMORY);
return false;
}
}
if (boundaries.mGlobals.WasPassed()) {
if (foundBoundaryProperty) {
rv.Throw(NS_ERROR_INVALID_ARG);
return false;
}
foundBoundaryProperty = true;
uint32_t length = boundaries.mGlobals.Value().Length();
if (length == 0) {
rv.Throw(NS_ERROR_INVALID_ARG);
return false;
}
AutoObjectVector globals(cx);
for (uint32_t i = 0; i < length; i++) {
JSObject* global = boundaries.mGlobals.Value().ElementAt(i);
if (!JS_IsGlobalObject(global)) {
rv.Throw(NS_ERROR_INVALID_ARG);
return false;
}
if (!globals.append(global)) {
rv.Throw(NS_ERROR_OUT_OF_MEMORY);
return false;
}
}
if (!PopulateZonesWithGlobals(zones, globals) ||
!roots.init(zones) ||
!AddGlobalsAsRoots(globals, roots))
{
rv.Throw(NS_ERROR_OUT_OF_MEMORY);
return false;
}
}
if (!foundBoundaryProperty) {
rv.Throw(NS_ERROR_INVALID_ARG);
return false;
}
MOZ_ASSERT(roots.initialized());
MOZ_ASSERT_IF(boundaries.mDebugger.WasPassed(), zones.initialized());
MOZ_ASSERT_IF(boundaries.mGlobals.WasPassed(), zones.initialized());
return true;
}
// A `CoreDumpWriter` that serializes nodes to protobufs and writes them to the
// given `ZeroCopyOutputStream`.
class MOZ_STACK_CLASS StreamWriter : public CoreDumpWriter
{
JSContext* cx;
bool wantNames;
::google::protobuf::io::ZeroCopyOutputStream& stream;
bool writeMessage(const ::google::protobuf::MessageLite& message) {
// We have to create a new CodedOutputStream when writing each message so
// that the 64MB size limit used by Coded{Output,Input}Stream to prevent
// integer overflow is enforced per message rather than on the whole stream.
::google::protobuf::io::CodedOutputStream codedStream(&stream);
codedStream.WriteVarint32(message.ByteSize());
message.SerializeWithCachedSizes(&codedStream);
return !codedStream.HadError();
}
public:
StreamWriter(JSContext* cx,
::google::protobuf::io::ZeroCopyOutputStream& stream,
bool wantNames)
: cx(cx)
, wantNames(wantNames)
, stream(stream)
{ }
~StreamWriter() override { }
virtual bool writeMetadata(uint64_t timestamp) override {
protobuf::Metadata metadata;
metadata.set_timestamp(timestamp);
return writeMessage(metadata);
}
virtual bool writeNode(const JS::ubi::Node& ubiNode,
EdgePolicy includeEdges) override {
protobuf::Node protobufNode;
protobufNode.set_id(ubiNode.identifier());
const char16_t* typeName = ubiNode.typeName();
size_t length = NS_strlen(typeName) * sizeof(char16_t);
protobufNode.set_typename_(typeName, length);
JSRuntime* rt = JS_GetRuntime(cx);
mozilla::MallocSizeOf mallocSizeOf = dbg::GetDebuggerMallocSizeOf(rt);
MOZ_ASSERT(mallocSizeOf);
protobufNode.set_size(ubiNode.size(mallocSizeOf));
if (includeEdges) {
auto edges = ubiNode.edges(cx, wantNames);
if (NS_WARN_IF(!edges))
return false;
for ( ; !edges->empty(); edges->popFront()) {
const ubi::Edge& ubiEdge = edges->front();
protobuf::Edge* protobufEdge = protobufNode.add_edges();
if (NS_WARN_IF(!protobufEdge)) {
return false;
}
protobufEdge->set_referent(ubiEdge.referent.identifier());
if (wantNames && ubiEdge.name) {
size_t length = NS_strlen(ubiEdge.name) * sizeof(char16_t);
protobufEdge->set_name(ubiEdge.name, length);
}
}
}
return writeMessage(protobufNode);
}
};
// A JS::ubi::BreadthFirst handler that serializes a snapshot of the heap into a
// core dump.
class MOZ_STACK_CLASS HeapSnapshotHandler {
CoreDumpWriter& writer;
JS::ZoneSet* zones;
public:
HeapSnapshotHandler(CoreDumpWriter& writer,
JS::ZoneSet* zones)
: writer(writer),
zones(zones)
{ }
// JS::ubi::BreadthFirst handler interface.
class NodeData { };
typedef JS::ubi::BreadthFirst<HeapSnapshotHandler> Traversal;
bool operator() (Traversal& traversal,
JS::ubi::Node origin,
const JS::ubi::Edge& edge,
NodeData*,
bool first)
{
// We're only interested in the first time we reach edge.referent, not in
// every edge arriving at that node. "But, don't we want to serialize every
// edge in the heap graph?" you ask. Don't worry! This edge is still
// serialized into the core dump. Serializing a node also serializes each of
// its edges, and if we are traversing a given edge, we must have already
// visited and serialized the origin node and its edges.
if (!first)
return true;
const JS::ubi::Node& referent = edge.referent;
if (!zones)
// We aren't targeting a particular set of zones, so serialize all the
// things!
return writer.writeNode(referent, CoreDumpWriter::INCLUDE_EDGES);
// We are targeting a particular set of zones. If this node is in our target
// set, serialize it and all of its edges. If this node is _not_ in our
// target set, we also serialize under the assumption that it is a shared
// resource being used by something in our target zones since we reached it
// by traversing the heap graph. However, we do not serialize its outgoing
// edges and we abandon further traversal from this node.
JS::Zone* zone = referent.zone();
if (zones->has(zone))
return writer.writeNode(referent, CoreDumpWriter::INCLUDE_EDGES);
traversal.abandonReferent();
return writer.writeNode(referent, CoreDumpWriter::EXCLUDE_EDGES);
}
};
bool
WriteHeapGraph(JSContext* cx,
const JS::ubi::Node& node,
CoreDumpWriter& writer,
bool wantNames,
JS::ZoneSet* zones,
JS::AutoCheckCannotGC& noGC)
{
// Serialize the starting node to the core dump.
if (NS_WARN_IF(!writer.writeNode(node, CoreDumpWriter::INCLUDE_EDGES))) {
return false;
}
// Walk the heap graph starting from the given node and serialize it into the
// core dump.
HeapSnapshotHandler handler(writer, zones);
HeapSnapshotHandler::Traversal traversal(cx, handler, noGC);
if (!traversal.init())
return false;
traversal.wantNames = wantNames;
return traversal.addStartVisited(node) &&
traversal.traverse();
}
/* static */ void
ChromeUtils::SaveHeapSnapshot(GlobalObject& global,
JSContext* cx,
const nsAString& filePath,
const HeapSnapshotBoundaries& boundaries,
ErrorResult& rv)
{
bool wantNames = true;
ZoneSet zones;
Maybe<AutoCheckCannotGC> maybeNoGC;
ubi::RootList rootList(cx, maybeNoGC, wantNames);
if (!EstablishBoundaries(cx, rv, boundaries, rootList, zones))
return;
MOZ_ASSERT(maybeNoGC.isSome());
ubi::Node roots(&rootList);
nsCOMPtr<nsIFile> file;
rv = NS_NewLocalFile(filePath, false, getter_AddRefs(file));
if (NS_WARN_IF(rv.Failed()))
return;
nsCOMPtr<nsIOutputStream> outputStream;
rv = NS_NewLocalFileOutputStream(getter_AddRefs(outputStream), file,
PR_WRONLY | PR_CREATE_FILE | PR_TRUNCATE,
-1, 0);
if (NS_WARN_IF(rv.Failed()))
return;
ZeroCopyNSIOutputStream zeroCopyStream(outputStream);
::google::protobuf::io::GzipOutputStream gzipStream(&zeroCopyStream);
StreamWriter writer(cx, gzipStream, wantNames);
// Serialize the initial heap snapshot metadata to the core dump.
if (!writer.writeMetadata(PR_Now()) ||
// Serialize the heap graph to the core dump, starting from our list of
// roots.
!WriteHeapGraph(cx,
roots,
writer,
wantNames,
zones.initialized() ? &zones : nullptr,
maybeNoGC.ref()))
{
rv.Throw(zeroCopyStream.failed()
? zeroCopyStream.result()
: NS_ERROR_UNEXPECTED);
return;
}
}
/* static */ already_AddRefed<HeapSnapshot>
ChromeUtils::ReadHeapSnapshot(GlobalObject& global,
JSContext* cx,
const nsAString& filePath,
ErrorResult& rv)
{
UniquePtr<char[]> path(ToNewCString(filePath));
if (!path) {
rv.Throw(NS_ERROR_OUT_OF_MEMORY);
return nullptr;
}
PRFileInfo fileInfo;
if (PR_GetFileInfo(path.get(), &fileInfo) != PR_SUCCESS) {
rv.Throw(NS_ERROR_FILE_NOT_FOUND);
return nullptr;
}
uint32_t size = fileInfo.size;
ScopedFreePtr<uint8_t> buffer(static_cast<uint8_t*>(malloc(size)));
if (!buffer) {
rv.Throw(NS_ERROR_OUT_OF_MEMORY);
return nullptr;
}
PRFileDesc* fd = PR_Open(path.get(), PR_RDONLY, 0);
if (!fd) {
rv.Throw(NS_ERROR_UNEXPECTED);
return nullptr;
}
uint32_t bytesRead = 0;
while (bytesRead < size) {
uint32_t bytesLeft = size - bytesRead;
int32_t bytesReadThisTime = PR_Read(fd, buffer.get() + bytesRead, bytesLeft);
if (bytesReadThisTime < 1) {
rv.Throw(NS_ERROR_UNEXPECTED);
return nullptr;
}
bytesRead += bytesReadThisTime;
}
return HeapSnapshot::Create(cx, global, buffer.get(), size, rv);
}
} // namespace devtools
} // namespace mozilla