heap_snapshot.cc 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. // Copyright (c) 2018 GitHub, Inc.
  2. // Use of this source code is governed by the MIT license that can be
  3. // found in the LICENSE file.
  4. #include "shell/common/heap_snapshot.h"
  5. #include "base/files/file.h"
  6. #include "v8/include/v8-profiler.h"
  7. #include "v8/include/v8.h"
  8. namespace {
  9. class HeapSnapshotOutputStream : public v8::OutputStream {
  10. public:
  11. explicit HeapSnapshotOutputStream(base::File* file) : file_(file) {
  12. DCHECK(file_);
  13. }
  14. bool IsComplete() const { return is_complete_; }
  15. // v8::OutputStream
  16. int GetChunkSize() override { return 65536; }
  17. void EndOfStream() override { is_complete_ = true; }
  18. v8::OutputStream::WriteResult WriteAsciiChunk(char* data, int size) override {
  19. auto bytes_written = file_->WriteAtCurrentPos(data, size);
  20. return bytes_written == size ? kContinue : kAbort;
  21. }
  22. private:
  23. base::File* file_ = nullptr;
  24. bool is_complete_ = false;
  25. };
  26. } // namespace
  27. namespace electron {
  28. bool TakeHeapSnapshot(v8::Isolate* isolate, base::File* file) {
  29. DCHECK(isolate);
  30. DCHECK(file);
  31. if (!file->IsValid())
  32. return false;
  33. auto* snapshot = isolate->GetHeapProfiler()->TakeHeapSnapshot();
  34. if (!snapshot)
  35. return false;
  36. HeapSnapshotOutputStream stream(file);
  37. snapshot->Serialize(&stream, v8::HeapSnapshot::kJSON);
  38. const_cast<v8::HeapSnapshot*>(snapshot)->Delete();
  39. return stream.IsComplete();
  40. }
  41. } // namespace electron