summaryrefslogtreecommitdiffstats
path: root/chrome/browser/debugger/debugger_shell.cc
blob: fc89a947abcc05349562778f262618fe8216f835 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/debugger/debugger_shell.h"

#include "build/build_config.h"

#include "base/file_util.h"
#include "base/path_service.h"
#include "base/string_util.h"
#include "base/thread.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/debugger/debugger_io.h"
#include "chrome/browser/debugger/debugger_node.h"
#include "chrome/browser/renderer_host/render_process_host.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/resource_bundle.h"

#include "grit/debugger_resources.h"

DebuggerShell::DebuggerShell(DebuggerInputOutput* io) : io_(io),
                                                        debugger_ready_(true) {
}

DebuggerShell::~DebuggerShell() {
  io_->Stop();
  io_ = NULL;

  v8::Locker locked;
  v8::HandleScope scope;
  SubshellFunction("exit", 0, NULL);
  v8::V8::RemoveMessageListeners(&DelegateMessageListener);
  v8_this_.Dispose();
  v8_context_.Dispose();
  shell_.Dispose();
}

void DebuggerShell::Start() {
  io_->Start(this);

  v8::Locker locked;
  v8::HandleScope scope;

  v8_this_ = v8::Persistent<v8::External>::New(v8::External::New(this));

  v8::V8::AddMessageListener(&DelegateMessageListener, v8_this_);

  v8::Local<v8::ObjectTemplate> global_template = v8::ObjectTemplate::New();

  // shell function
  v8::Local<v8::FunctionTemplate> shell_template =
    v8::FunctionTemplate::New(&DelegateSubshell, v8_this_);
  global_template->Set(v8::String::New("shell"), shell_template);

  // print function
  v8::Local<v8::FunctionTemplate> print_template =
    v8::FunctionTemplate::New(&DelegatePrint, v8_this_);
  global_template->Set(v8::String::New("print"), print_template);

  // source function
  v8::Local<v8::FunctionTemplate> source_template =
    v8::FunctionTemplate::New(&DelegateSource, v8_this_);
  global_template->Set(v8::String::New("source"), source_template);

  v8_context_ = v8::Context::New(NULL, global_template);
  v8::Context::Scope ctx(v8_context_);

  // This doesn't really leak. It's wrapped by the NewInstance() return value.
  ChromeNode* chrome = new ChromeNode(this);
  v8_context_->Global()->Set(v8::String::New("chrome"),
                             chrome->NewInstance());

  ResourceBundle& rb = ResourceBundle::GetSharedInstance();
  const std::string& debugger_shell_js =
      rb.GetDataResource(IDR_DEBUGGER_SHELL_JS);
  CompileAndRun(debugger_shell_js, "chrome.dll/debugger_shell.js");
}

void DebuggerShell::HandleWeakReference(v8::Persistent<v8::Value> obj,
                                        void* data) {
  DebuggerNodeWrapper* node = static_cast<DebuggerNodeWrapper*>(data);
  node->Release();
}

v8::Handle<v8::Value> DebuggerShell::SetDebuggerReady(const v8::Arguments& args,
                                                      DebuggerShell* debugger) {
  if (args[0]->IsBoolean()) {
    bool flag = args[0]->BooleanValue();
    debugger->debugger_ready_ = flag;
    debugger->GetIo()->SetDebuggerReady(flag);
  }
  return v8::Undefined();
}

v8::Handle<v8::Value> DebuggerShell::SetDebuggerBreak(const v8::Arguments& args,
                                                      DebuggerShell* debugger) {
  if (args[0]->IsBoolean()) {
    bool flag = args[0]->BooleanValue();
    debugger->GetIo()->SetDebuggerBreak(flag);
  }
  return v8::Undefined();
}

DebuggerInputOutput* DebuggerShell::GetIo() {
  return io_.get();
}

v8::Handle<v8::Value> DebuggerShell::DelegateSubshell(
    const v8::Arguments& args) {
  DebuggerShell* debugger =
    static_cast<DebuggerShell*>(v8::External::Cast(*args.Data())->Value());
  return debugger->Subshell(args);
}

v8::Handle<v8::Value> DebuggerShell::Subshell(const v8::Arguments& args) {
  if (args.Length() != 1) {
    return v8::Undefined();
  }
  if (!shell_.IsEmpty()) {
    shell_.Dispose();
    shell_.Clear();
    v8_context_->Global()->Delete(v8::String::New("shell_"));
  }
  if (args[0]->IsFunction()) {
    v8::Handle<v8::Function> func = v8::Handle<v8::Function>::Cast(args[0]);
    v8::Local<v8::Object> obj = func->NewInstance();
    if (!obj->IsUndefined()) {
      shell_ = v8::Persistent<v8::Object>::New(obj);
      v8_context_->Global()->Set(v8::String::New("shell_"), shell_);
    }
  } else if (args[0]->IsObject()) {
    shell_ =
        v8::Persistent<v8::Object>::New(v8::Local<v8::Object>::Cast(args[0]));
    v8_context_->Global()->Set(v8::String::New("shell_"), shell_);
  }
  return v8::Undefined();
}

v8::Handle<v8::Value> DebuggerShell::SubshellFunction(const char* func,
                                              int argc,
                                              v8::Handle<v8::Value>* argv) {
  if (!shell_.IsEmpty()) {
    v8::Context::Scope scope(v8_context_);
    v8::Local<v8::Value> function = shell_->Get(v8::String::New(func));
    if (function->IsFunction()) {
      v8::Local<v8::Value> ret =
        v8::Function::Cast(*function)->Call(shell_, argc, argv);
      return ret;
    }
  }
  return v8::Undefined();
}

v8::Handle<v8::Value> DebuggerShell::DelegatePrint(const v8::Arguments& args) {
  DebuggerShell* debugger =
    static_cast<DebuggerShell*>(v8::External::Cast(*args.Data())->Value());
  return debugger->Print(args);
}

v8::Handle<v8::Value> DebuggerShell::Print(const v8::Arguments& args) {
  int len = args.Length();
  for (int i = 0; i < len; i++) {
    PrintObject(args[i]);
  }
  return v8::Undefined();
}

v8::Handle<v8::Value> DebuggerShell::DelegateSource(const v8::Arguments& args) {
  DebuggerShell* debugger =
    static_cast<DebuggerShell*>(v8::External::Cast(*args.Data())->Value());
  std::wstring path;
  if (args.Length() == 0) {
    debugger->LoadUserConfig();
  } else {
    ObjectToString(args[0], &path);
    bool ret = debugger->LoadFile(path);
    if (!ret) {
      return v8::String::New("failed to load");
    }
  }
  return v8::Undefined();
}

void DebuggerShell::DelegateMessageListener(v8::Handle<v8::Message> message,
                                    v8::Handle<v8::Value> data) {
  DCHECK(!data.IsEmpty());
  DebuggerShell* debugger =
    static_cast<DebuggerShell*>(v8::External::Cast(*data)->Value());
  debugger->MessageListener(message);
}

void DebuggerShell::MessageListener(v8::Handle<v8::Message> message) {
  v8::HandleScope scope;
  v8::Local<v8::String> msg_str = message->Get();
  PrintObject(msg_str);

  v8::Handle<v8::Value> data = message->GetScriptResourceName();
  if (!data.IsEmpty() && !data->IsUndefined()) {
    std::wstring out;
    ObjectToString(data, &out);
    int line_number = message->GetLineNumber();
    if (line_number >= 0)
      out += StringPrintf(L":%d", line_number);
    PrintLine(out);
    data = message->GetSourceLine();
    if (!data->IsUndefined()) {
      ObjectToString(data, &out);
      PrintLine(out);
    }
  }
}

void DebuggerShell::Debug(TabContents* tab) {
  v8::Locker locked;
  v8::HandleScope outer;
  v8::Context::Scope scope(v8_context_);

  v8::Local<v8::Object> global = v8_context_->Global();
  v8::Local<v8::Value> function = global->Get(v8::String::New("debug"));
  if (function->IsFunction()) {
    TabNode* node = new TabNode(tab);
    v8::Handle<v8::Value> argv[] = {node->NewInstance()};
    PrintObject(v8::Function::Cast(*function)->Call(global, 1, argv));
  }
}

void DebuggerShell::DebugMessage(const std::wstring& msg) {
  v8::Locker locked;
  v8::HandleScope scope;

  if (msg.length()) {
    if ((msg[0] == L'{' || msg[0] == L'[' || msg[0] == L'(') &&
        (!shell_.IsEmpty())) {
      // v8's wide String constructor requires uint16 rather than wchar
      const uint16* data = reinterpret_cast<const uint16* >(msg.c_str());
      v8::Handle<v8::Value> argv[] = {v8::String::New(data)};
      PrintObject(SubshellFunction("response", 1, argv));
      PrintPrompt();
    } else {
      if (msg[msg.length() - 1] == L'\n')
        PrintString(msg);
      else
        PrintLine(msg);
    }
  }
}

void DebuggerShell::OnDebugAttach() {
  v8::Locker locked;
  v8::HandleScope scope;
  SubshellFunction("on_attach", 0, NULL);
}

void DebuggerShell::OnDebugDisconnect() {
  v8::Locker locked;
  v8::HandleScope scope;
  SubshellFunction("on_disconnect", 0, NULL);
}

void DebuggerShell::ObjectToString(v8::Handle<v8::Value> result,
                                   std::wstring* str) {
  v8::HandleScope scope;
  if (!result.IsEmpty() && !result->IsUndefined()) {
    v8::Local<v8::String> str_obj = result->ToString();
    if (!str_obj.IsEmpty()) {
      int length = str_obj->Length();
      wchar_t* buf = new wchar_t[length + 1];
      int size = str_obj->Write(reinterpret_cast<uint16_t*>(buf));
      str->clear();
      str->append(buf, size);
      delete[] buf;
    }
  }
}

void DebuggerShell::ObjectToString(v8::Handle<v8::Value> result,
                                   std::string* str) {
  v8::HandleScope scope;
  if (!result.IsEmpty() && !result->IsUndefined()) {
    v8::Local<v8::String> str_obj = result->ToString();
    if (!str_obj.IsEmpty()) {
      int length = str_obj->Length();
      char* buf = new char[length + 1];
      str_obj->WriteAscii(buf);
      str->clear();
      str->append(buf);
      delete[] buf;
    }
  }
}

void DebuggerShell::PrintObject(v8::Handle<v8::Value> result, bool crlf) {
  if (!result.IsEmpty() && !result->IsUndefined()) {
    std::wstring out;
    ObjectToString(result, &out);
    if (crlf) {
      PrintLine(out);
    } else if (out.length()) {
      PrintString(out);
    }
  }
}

void DebuggerShell::PrintString(const std::wstring& out) {
  if (io_)
    io_->Output(out);
}

void DebuggerShell::PrintLine(const std::wstring& out) {
  if (io_)
    io_->OutputLine(out);
}

void DebuggerShell::PrintString(const std::string& out) {
  if (io_)
    io_->Output(out);
}

void DebuggerShell::PrintLine(const std::string& out) {
  if (io_)
    io_->OutputLine(out);
}

void DebuggerShell::PrintPrompt() {
  std::wstring out = L"Chrome> ";
  if (!shell_.IsEmpty()) {
    if (!debugger_ready_)
      return;
    v8::Locker locked;
    v8::HandleScope outer;
    v8::Handle<v8::Value> result = CompileAndRun("shell_.prompt()");
    if (!result.IsEmpty() && !result->IsUndefined()) {
      ObjectToString(result, &out);
    }
  }
  if (io_)
    io_->OutputPrompt(out);
}

void DebuggerShell::ProcessCommand(const std::wstring& data) {
  v8::Locker locked;
  v8::HandleScope outer;
  v8::Context::Scope scope(v8_context_);
  if (!shell_.IsEmpty() && data.substr(0, 7) != L"source(") {
    if (data == L"exit") {
      PrintObject(SubshellFunction("exit", 0, NULL));
      v8_context_->Global()->Delete(v8::String::New("shell_"));
      shell_.Dispose();
      shell_.Clear();
    } else {
      const uint16* utf16 = reinterpret_cast<const uint16*>(data.c_str());
      v8::Handle<v8::Value> argv[] = {v8::String::New(utf16)};
      PrintObject(SubshellFunction("command", 1, argv));
    }
  } else if (data.length()) {
    //TODO(erikkay): change everything to wstring
    v8::Handle<v8::Value> result = CompileAndRun(data);
    PrintObject(result);
  }
  PrintPrompt();
}

bool DebuggerShell::LoadFile(const std::wstring& file) {
  if (file_util::PathExists(file)) {
    std::string contents;
    if (file_util::ReadFileToString(file, &contents)) {
      std::string afile = WideToUTF8(file);
      CompileAndRun(contents, afile);
      return true;
    }
  }
  return false;
}

void DebuggerShell::LoadUserConfig() {
  std::wstring path;
  PathService::Get(chrome::DIR_USER_DATA, &path);
  file_util::AppendToPath(&path, L"debugger_custom.js");
  LoadFile(path);
}

void DebuggerShell::DidConnect() {
  v8::Locker locked;
  v8::HandleScope outer;
  v8::Context::Scope scope(v8_context_);

  LoadUserConfig();

  PrintPrompt();
}

void DebuggerShell::DidDisconnect() {
  v8::Locker locked;
  v8::HandleScope outer;
  SubshellFunction("exit", 0, NULL);
}

v8::Handle<v8::Value> DebuggerShell::CompileAndRun(
    const std::string& str,
    const std::string& filename) {
  const std::wstring wstr = UTF8ToWide(str);
  return CompileAndRun(wstr, filename);
}

v8::Handle<v8::Value> DebuggerShell::CompileAndRun(
    const std::wstring& wstr,
    const std::string& filename) {
  v8::Locker locked;
  v8::Context::Scope scope(v8_context_);
  v8::Handle<v8::String> scriptname;
  if (filename.length() > 0) {
    scriptname = v8::String::New(filename.c_str());
  } else {
    scriptname = v8::String::New("");
  }
  const uint16* utf16 = reinterpret_cast<const uint16*>(wstr.c_str());
  v8::ScriptOrigin origin = v8::ScriptOrigin(scriptname);
  v8::Local<v8::Script> code =
      v8::Script::Compile(v8::String::New(utf16), &origin);
  if (!code.IsEmpty()) {
    v8::Local<v8::Value> result = code->Run();
    if (!result.IsEmpty()) {
      return result;
    }
  }
  return v8::Undefined();
}