heap_snapshot.cc 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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 "base/memory/raw_ptr.h"
  7. #include "v8/include/v8-profiler.h"
  8. #include "v8/include/v8.h"
  9. namespace {
  10. class HeapSnapshotOutputStream : public v8::OutputStream {
  11. public:
  12. explicit HeapSnapshotOutputStream(base::File* file) : file_(file) {
  13. DCHECK(file_);
  14. }
  15. bool IsComplete() const { return is_complete_; }
  16. // v8::OutputStream
  17. int GetChunkSize() override { return 65536; }
  18. void EndOfStream() override { is_complete_ = true; }
  19. v8::OutputStream::WriteResult WriteAsciiChunk(char* data, int size) override {
  20. auto bytes_written = file_->WriteAtCurrentPos(data, size);
  21. return bytes_written == size ? kContinue : kAbort;
  22. }
  23. private:
  24. raw_ptr<base::File> file_ = nullptr;
  25. bool is_complete_ = false;
  26. };
  27. } // namespace
  28. namespace electron {
  29. bool TakeHeapSnapshot(v8::Isolate* isolate, base::File* file) {
  30. DCHECK(isolate);
  31. DCHECK(file);
  32. if (!file->IsValid())
  33. return false;
  34. auto* snapshot = isolate->GetHeapProfiler()->TakeHeapSnapshot();
  35. if (!snapshot)
  36. return false;
  37. HeapSnapshotOutputStream stream(file);
  38. snapshot->Serialize(&stream, v8::HeapSnapshot::kJSON);
  39. const_cast<v8::HeapSnapshot*>(snapshot)->Delete();
  40. return stream.IsComplete();
  41. }
  42. } // namespace electron