Upstream version 5.34.104.0
[platform/framework/web/crosswalk.git] / src / chrome / test / chromedriver / chrome / heap_snapshot_taker.cc
1 // Copyright 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "chrome/test/chromedriver/chrome/heap_snapshot_taker.h"
6
7 #include "base/json/json_reader.h"
8 #include "base/logging.h"
9 #include "base/values.h"
10 #include "chrome/test/chromedriver/chrome/devtools_client.h"
11 #include "chrome/test/chromedriver/chrome/status.h"
12
13 HeapSnapshotTaker::HeapSnapshotTaker(DevToolsClient* client)
14     : client_(client) {
15   client_->AddListener(this);
16 }
17
18 HeapSnapshotTaker::~HeapSnapshotTaker() {}
19
20 Status HeapSnapshotTaker::TakeSnapshot(scoped_ptr<base::Value>* snapshot) {
21   Status status1 = TakeSnapshotInternal();
22   base::DictionaryValue params;
23   Status status2 = client_->SendCommand("Debugger.disable", params);
24
25   Status status3(kOk);
26   if (status1.IsOk() && status2.IsOk()) {
27     scoped_ptr<base::Value> value(base::JSONReader::Read(snapshot_));
28     if (!value)
29       status3 = Status(kUnknownError, "heap snapshot not in JSON format");
30     else
31       *snapshot = value.Pass();
32   }
33   snapshot_.clear();
34   if (status1.IsError())
35     return status1;
36   else if (status2.IsError())
37     return status2;
38   else
39     return status3;
40 }
41
42 Status HeapSnapshotTaker::TakeSnapshotInternal() {
43   base::DictionaryValue params;
44   const char* kMethods[] = {
45       "Debugger.enable",
46       "HeapProfiler.collectGarbage",
47       "HeapProfiler.takeHeapSnapshot"
48   };
49   for (size_t i = 0; i < arraysize(kMethods); ++i) {
50     Status status = client_->SendCommand(kMethods[i], params);
51     if (status.IsError())
52       return status;
53   }
54
55   return Status(kOk);
56 }
57
58 Status HeapSnapshotTaker::OnEvent(DevToolsClient* client,
59                                   const std::string& method,
60                                   const base::DictionaryValue& params) {
61   if (method == "HeapProfiler.addHeapSnapshotChunk") {
62     std::string chunk;
63     if (!params.GetString("chunk", &chunk)) {
64       return Status(kUnknownError,
65                     "HeapProfiler.addHeapSnapshotChunk has no 'chunk'");
66     }
67     snapshot_.append(chunk);
68   }
69   return Status(kOk);
70 }