Chris Lattner | 24943d2 | 2010-06-08 16:52:24 +0000 | [diff] [blame^] | 1 | //===-- ScriptInterpreterPython.cpp -----------------------------*- C++ -*-===// |
| 2 | // |
| 3 | // The LLVM Compiler Infrastructure |
| 4 | // |
| 5 | // This file is distributed under the University of Illinois Open Source |
| 6 | // License. See LICENSE.TXT for details. |
| 7 | // |
| 8 | //===----------------------------------------------------------------------===// |
| 9 | |
| 10 | // In order to guarantee correct working with Python, Python.h *MUST* be |
| 11 | // the *FIRST* header file included: |
| 12 | |
| 13 | #include <Python.h> |
| 14 | |
| 15 | #include "lldb/Interpreter/ScriptInterpreterPython.h" |
| 16 | |
| 17 | |
| 18 | #include <sys/ioctl.h> |
| 19 | #include <termios.h> |
| 20 | #include <stdlib.h> |
| 21 | #include <stdio.h> |
| 22 | |
| 23 | #include <string> |
| 24 | |
| 25 | #include "lldb/Breakpoint/Breakpoint.h" |
| 26 | #include "lldb/Breakpoint/BreakpointLocation.h" |
| 27 | #include "lldb/Core/Debugger.h" |
| 28 | #include "lldb/Core/FileSpec.h" |
| 29 | #include "lldb/Core/InputReader.h" |
| 30 | #include "lldb/Core/Stream.h" |
| 31 | #include "lldb/Core/StreamString.h" |
| 32 | #include "lldb/Core/Timer.h" |
| 33 | #include "lldb/Host/Host.h" |
| 34 | #include "lldb/Interpreter/CommandInterpreter.h" |
| 35 | #include "lldb/Interpreter/CommandReturnObject.h" |
| 36 | #include "lldb/Target/Process.h" |
| 37 | |
| 38 | extern "C" void init_lldb (void); |
| 39 | |
| 40 | using namespace lldb; |
| 41 | using namespace lldb_private; |
| 42 | |
| 43 | const char embedded_interpreter_string[] = |
| 44 | "import readline\n\ |
| 45 | import code\n\ |
| 46 | import sys\n\ |
| 47 | import traceback\n\ |
| 48 | \n\ |
| 49 | class SimpleREPL(code.InteractiveConsole):\n\ |
| 50 | def __init__(self, prompt, dict):\n\ |
| 51 | code.InteractiveConsole.__init__(self,dict)\n\ |
| 52 | self.prompt = prompt\n\ |
| 53 | self.loop_exit = False\n\ |
| 54 | self.dict = dict\n\ |
| 55 | \n\ |
| 56 | def interact(self):\n\ |
| 57 | try:\n\ |
| 58 | sys.ps1\n\ |
| 59 | except AttributeError:\n\ |
| 60 | sys.ps1 = \">>> \"\n\ |
| 61 | try:\n\ |
| 62 | sys.ps2\n\ |
| 63 | except AttributeError:\n\ |
| 64 | sys.ps2 = \"... \"\n\ |
| 65 | \n\ |
| 66 | while not self.loop_exit:\n\ |
| 67 | try:\n\ |
| 68 | self.read_py_command()\n\ |
| 69 | except (SystemExit, EOFError):\n\ |
| 70 | # EOF while in Python just breaks out to top level.\n\ |
| 71 | self.write('\\n')\n\ |
| 72 | self.loop_exit = True\n\ |
| 73 | break\n\ |
| 74 | except KeyboardInterrupt:\n\ |
| 75 | self.write(\"\\nKeyboardInterrupt\\n\")\n\ |
| 76 | self.resetbuffer()\n\ |
| 77 | more = 0\n\ |
| 78 | except:\n\ |
| 79 | traceback.print_exc()\n\ |
| 80 | \n\ |
| 81 | def process_input (self, in_str):\n\ |
| 82 | # Canonicalize the format of the input string\n\ |
| 83 | temp_str = in_str\n\ |
| 84 | temp_str.strip(' \t')\n\ |
| 85 | words = temp_str.split()\n\ |
| 86 | temp_str = ('').join(words)\n\ |
| 87 | \n\ |
| 88 | # Check the input string to see if it was the quit\n\ |
| 89 | # command. If so, intercept it, so that it doesn't\n\ |
| 90 | # close stdin on us!\n\ |
| 91 | if (temp_str.lower() == \"quit()\"):\n\ |
| 92 | self.loop_exit = True\n\ |
| 93 | in_str = \"raise SystemExit \"\n\ |
| 94 | return in_str\n\ |
| 95 | \n\ |
| 96 | def my_raw_input (self, prompt):\n\ |
| 97 | stream = sys.stdout\n\ |
| 98 | stream.write (prompt)\n\ |
| 99 | stream.flush ()\n\ |
| 100 | try:\n\ |
| 101 | line = sys.stdin.readline()\n\ |
| 102 | except KeyboardInterrupt:\n\ |
| 103 | line = \" \\n\"\n\ |
| 104 | except (SystemExit, EOFError):\n\ |
| 105 | line = \"quit()\\n\"\n\ |
| 106 | if not line:\n\ |
| 107 | raise EOFError\n\ |
| 108 | if line[-1] == '\\n':\n\ |
| 109 | line = line[:-1]\n\ |
| 110 | return line\n\ |
| 111 | \n\ |
| 112 | def read_py_command(self):\n\ |
| 113 | # Read off a complete Python command.\n\ |
| 114 | more = 0\n\ |
| 115 | while 1:\n\ |
| 116 | if more:\n\ |
| 117 | prompt = sys.ps2\n\ |
| 118 | else:\n\ |
| 119 | prompt = sys.ps1\n\ |
| 120 | line = self.my_raw_input(prompt)\n\ |
| 121 | # Can be None if sys.stdin was redefined\n\ |
| 122 | encoding = getattr(sys.stdin, \"encoding\", None)\n\ |
| 123 | if encoding and not isinstance(line, unicode):\n\ |
| 124 | line = line.decode(encoding)\n\ |
| 125 | line = self.process_input (line)\n\ |
| 126 | more = self.push(line)\n\ |
| 127 | if not more:\n\ |
| 128 | break\n\ |
| 129 | \n\ |
| 130 | def run_python_interpreter (dict):\n\ |
| 131 | # Pass in the dictionary, for continuity from one session to the next.\n\ |
| 132 | repl = SimpleREPL('>>> ', dict)\n\ |
| 133 | repl.interact()\n"; |
| 134 | |
| 135 | static int |
| 136 | _check_and_flush (FILE *stream) |
| 137 | { |
| 138 | int prev_fail = ferror (stream); |
| 139 | return fflush (stream) || prev_fail ? EOF : 0; |
| 140 | } |
| 141 | |
| 142 | ScriptInterpreterPython::ScriptInterpreterPython () : |
| 143 | ScriptInterpreter (eScriptLanguagePython), |
| 144 | m_compiled_module (NULL), |
| 145 | m_termios_valid (false) |
| 146 | { |
| 147 | |
| 148 | Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__); |
| 149 | // Find the module that owns this code and use that path we get to |
| 150 | // set the PYTHONPATH appropriately. |
| 151 | |
| 152 | FileSpec this_module (Host::GetModuleFileSpecForHostAddress ((void *)init_lldb)); |
| 153 | std::string python_path; |
| 154 | |
| 155 | if (this_module.GetDirectory()) |
| 156 | { |
| 157 | // Append the directory that the module that loaded this code |
| 158 | // belongs to |
| 159 | python_path += this_module.GetDirectory().AsCString(""); |
| 160 | |
| 161 | #if defined (__APPLE__) |
| 162 | // If we are running on MacOSX we might be in a framework and should |
| 163 | // add an appropriate path so Resource can be found in a bundle |
| 164 | |
| 165 | if (::strstr(this_module.GetDirectory().AsCString(""), ".framework")) |
| 166 | { |
| 167 | python_path.append(1, ':'); |
| 168 | python_path.append(this_module.GetDirectory().AsCString("")); |
| 169 | python_path.append("/Resources/Python"); |
| 170 | } |
| 171 | #endif |
| 172 | // The the PYTHONPATH environment variable so that Python can find |
| 173 | // our lldb.py module and our _lldb.so. |
| 174 | ::setenv ("PYTHONPATH", python_path.c_str(), 1); |
| 175 | } |
| 176 | |
| 177 | Py_Initialize (); |
| 178 | |
| 179 | PyObject *compiled_module = Py_CompileString (embedded_interpreter_string, "embedded_interpreter.py", |
| 180 | Py_file_input); |
| 181 | |
| 182 | m_compiled_module = compiled_module; |
| 183 | |
| 184 | init_lldb (); |
| 185 | |
| 186 | // Update the path python uses to search for modules to include the current directory. |
| 187 | |
| 188 | int success = PyRun_SimpleString ("import sys"); |
| 189 | success = PyRun_SimpleString ("sys.path.append ('.')"); |
| 190 | if (success == 0) |
| 191 | { |
| 192 | // Import the Script Bridge module. |
| 193 | success = PyRun_SimpleString ("from lldb import *"); |
| 194 | } |
| 195 | |
| 196 | const char *pty_slave_name = GetScriptInterpreterPtyName (); |
| 197 | FILE *out_fh = Debugger::GetSharedInstance().GetOutputFileHandle(); |
| 198 | |
| 199 | PyObject *pmod = PyImport_ExecCodeModule((char *)"embedded_interpreter", m_compiled_module); |
| 200 | if (pmod != NULL) |
| 201 | { |
| 202 | PyRun_SimpleString ("ConsoleDict = locals()"); |
| 203 | PyRun_SimpleString ("from embedded_interpreter import run_python_interpreter"); |
| 204 | PyRun_SimpleString ("import sys"); |
| 205 | PyRun_SimpleString ("from termios import *"); |
| 206 | PyRun_SimpleString ("old_stdin = sys.stdin"); |
| 207 | |
| 208 | StreamString run_string; |
| 209 | run_string.Printf ("new_stdin = open('%s', 'r')", pty_slave_name); |
| 210 | PyRun_SimpleString (run_string.GetData()); |
| 211 | PyRun_SimpleString ("sys.stdin = new_stdin"); |
| 212 | |
| 213 | PyRun_SimpleString ("old_stdout = sys.stdout"); |
| 214 | |
| 215 | if (out_fh != NULL) |
| 216 | { |
| 217 | PyObject *new_sysout = PyFile_FromFile (out_fh, (char *) "", (char *) "w", |
| 218 | _check_and_flush); |
| 219 | PyObject *sysmod = PyImport_AddModule ("sys"); |
| 220 | PyObject *sysdict = PyModule_GetDict (sysmod); |
| 221 | |
| 222 | if ((new_sysout != NULL) |
| 223 | && (sysmod != NULL) |
| 224 | && (sysdict != NULL)) |
| 225 | { |
| 226 | PyDict_SetItemString (sysdict, "stdout", new_sysout); |
| 227 | } |
| 228 | |
| 229 | if (PyErr_Occurred()) |
| 230 | PyErr_Clear(); |
| 231 | } |
| 232 | |
| 233 | PyRun_SimpleString ("new_mode = tcgetattr(new_stdin)"); |
| 234 | PyRun_SimpleString ("new_mode[3] = new_mode[3] | ECHO | ICANON"); |
| 235 | PyRun_SimpleString ("new_mode[6][VEOF] = 255"); |
| 236 | PyRun_SimpleString ("tcsetattr (new_stdin, TCSANOW, new_mode)"); |
| 237 | } |
| 238 | |
| 239 | |
| 240 | } |
| 241 | |
| 242 | ScriptInterpreterPython::~ScriptInterpreterPython () |
| 243 | { |
| 244 | PyRun_SimpleString ("sys.stdin = old_stdin"); |
| 245 | PyRun_SimpleString ("sys.stdout = old_stdout"); |
| 246 | Py_Finalize (); |
| 247 | } |
| 248 | |
| 249 | void |
| 250 | ScriptInterpreterPython::ExecuteOneLine (const std::string& line, FILE *out, FILE *err) |
| 251 | { |
| 252 | int success; |
| 253 | |
| 254 | success = PyRun_SimpleString (line.c_str()); |
| 255 | if (success != 0) |
| 256 | { |
| 257 | fprintf (err, "error: python failed attempting to evaluate '%s'\n", line.c_str()); |
| 258 | } |
| 259 | } |
| 260 | |
| 261 | |
| 262 | |
| 263 | size_t |
| 264 | ScriptInterpreterPython::InputReaderCallback |
| 265 | ( |
| 266 | void *baton, |
| 267 | InputReader *reader, |
| 268 | lldb::InputReaderAction notification, |
| 269 | const char *bytes, |
| 270 | size_t bytes_len |
| 271 | ) |
| 272 | { |
| 273 | if (baton == NULL) |
| 274 | return 0; |
| 275 | |
| 276 | ScriptInterpreterPython *interpreter = (ScriptInterpreterPython *) baton; |
| 277 | switch (notification) |
| 278 | { |
| 279 | case eInputReaderActivate: |
| 280 | { |
| 281 | // Save terminal settings if we can |
| 282 | interpreter->m_termios_valid = ::tcgetattr (::fileno (reader->GetInputFileHandle()), |
| 283 | &interpreter->m_termios) == 0; |
| 284 | struct termios tmp_termios; |
| 285 | if (::tcgetattr (::fileno (reader->GetInputFileHandle()), &tmp_termios) == 0) |
| 286 | { |
| 287 | tmp_termios.c_cc[VEOF] = _POSIX_VDISABLE; |
| 288 | ::tcsetattr (::fileno (reader->GetInputFileHandle()), TCSANOW, &tmp_termios); |
| 289 | } |
| 290 | } |
| 291 | break; |
| 292 | |
| 293 | case eInputReaderDeactivate: |
| 294 | break; |
| 295 | |
| 296 | case eInputReaderReactivate: |
| 297 | break; |
| 298 | |
| 299 | case eInputReaderGotToken: |
| 300 | if (bytes && bytes_len) |
| 301 | { |
| 302 | if ((int) bytes[0] == 4) |
| 303 | ::write (interpreter->GetMasterFileDescriptor(), "quit()", 6); |
| 304 | else |
| 305 | ::write (interpreter->GetMasterFileDescriptor(), bytes, bytes_len); |
| 306 | } |
| 307 | ::write (interpreter->GetMasterFileDescriptor(), "\n", 1); |
| 308 | break; |
| 309 | |
| 310 | case eInputReaderDone: |
| 311 | // Send a control D to the script interpreter |
| 312 | //::write (interpreter->GetMasterFileDescriptor(), "\nquit()\n", strlen("\nquit()\n")); |
| 313 | // Write a newline out to the reader output |
| 314 | //::fwrite ("\n", 1, 1, out_fh); |
| 315 | // Restore terminal settings if they were validly saved |
| 316 | if (interpreter->m_termios_valid) |
| 317 | { |
| 318 | ::tcsetattr (::fileno (reader->GetInputFileHandle()), |
| 319 | TCSANOW, |
| 320 | &interpreter->m_termios); |
| 321 | } |
| 322 | break; |
| 323 | } |
| 324 | |
| 325 | return bytes_len; |
| 326 | } |
| 327 | |
| 328 | |
| 329 | void |
| 330 | ScriptInterpreterPython::ExecuteInterpreterLoop (FILE *out, FILE *err) |
| 331 | { |
| 332 | Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__); |
| 333 | |
| 334 | InputReaderSP reader_sp (new InputReader()); |
| 335 | if (reader_sp) |
| 336 | { |
| 337 | Error error (reader_sp->Initialize (ScriptInterpreterPython::InputReaderCallback, |
| 338 | this, // baton |
| 339 | eInputReaderGranularityLine, // token size, to pass to callback function |
| 340 | NULL, // end token |
| 341 | NULL, // prompt |
| 342 | true)); // echo input |
| 343 | |
| 344 | if (error.Success()) |
| 345 | { |
| 346 | Debugger::GetSharedInstance().PushInputReader (reader_sp); |
| 347 | ExecuteOneLine ("run_python_interpreter(ConsoleDict)", out, err); |
| 348 | Debugger::GetSharedInstance().PopInputReader (reader_sp); |
| 349 | } |
| 350 | } |
| 351 | } |
| 352 | |
| 353 | bool |
| 354 | ScriptInterpreterPython::ExecuteOneLineWithReturn (const char *in_string, |
| 355 | ScriptInterpreter::ReturnType return_type, |
| 356 | void *ret_value) |
| 357 | { |
| 358 | PyObject *py_return = NULL; |
| 359 | PyObject *mainmod = PyImport_AddModule ("__main__"); |
| 360 | PyObject *globals = PyModule_GetDict (mainmod); |
| 361 | PyObject *locals = globals; |
| 362 | PyObject *py_error = NULL; |
| 363 | bool ret_success; |
| 364 | int success; |
| 365 | |
| 366 | if (in_string != NULL) |
| 367 | { |
| 368 | py_return = PyRun_String (in_string, Py_eval_input, globals, locals); |
| 369 | if (py_return == NULL) |
| 370 | { |
| 371 | py_error = PyErr_Occurred (); |
| 372 | if (py_error != NULL) |
| 373 | PyErr_Clear (); |
| 374 | |
| 375 | py_return = PyRun_String (in_string, Py_single_input, globals, locals); |
| 376 | } |
| 377 | |
| 378 | if (py_return != NULL) |
| 379 | { |
| 380 | switch (return_type) |
| 381 | { |
| 382 | case eCharPtr: // "char *" |
| 383 | { |
| 384 | const char format[3] = "s#"; |
| 385 | success = PyArg_Parse (py_return, format, (char **) &ret_value); |
| 386 | break; |
| 387 | } |
| 388 | case eBool: |
| 389 | { |
| 390 | const char format[2] = "b"; |
| 391 | success = PyArg_Parse (py_return, format, (bool *) ret_value); |
| 392 | break; |
| 393 | } |
| 394 | case eShortInt: |
| 395 | { |
| 396 | const char format[2] = "h"; |
| 397 | success = PyArg_Parse (py_return, format, (short *) ret_value); |
| 398 | break; |
| 399 | } |
| 400 | case eShortIntUnsigned: |
| 401 | { |
| 402 | const char format[2] = "H"; |
| 403 | success = PyArg_Parse (py_return, format, (unsigned short *) ret_value); |
| 404 | break; |
| 405 | } |
| 406 | case eInt: |
| 407 | { |
| 408 | const char format[2] = "i"; |
| 409 | success = PyArg_Parse (py_return, format, (int *) ret_value); |
| 410 | break; |
| 411 | } |
| 412 | case eIntUnsigned: |
| 413 | { |
| 414 | const char format[2] = "I"; |
| 415 | success = PyArg_Parse (py_return, format, (unsigned int *) ret_value); |
| 416 | break; |
| 417 | } |
| 418 | case eLongInt: |
| 419 | { |
| 420 | const char format[2] = "l"; |
| 421 | success = PyArg_Parse (py_return, format, (long *) ret_value); |
| 422 | break; |
| 423 | } |
| 424 | case eLongIntUnsigned: |
| 425 | { |
| 426 | const char format[2] = "k"; |
| 427 | success = PyArg_Parse (py_return, format, (unsigned long *) ret_value); |
| 428 | break; |
| 429 | } |
| 430 | case eLongLong: |
| 431 | { |
| 432 | const char format[2] = "L"; |
| 433 | success = PyArg_Parse (py_return, format, (long long *) ret_value); |
| 434 | break; |
| 435 | } |
| 436 | case eLongLongUnsigned: |
| 437 | { |
| 438 | const char format[2] = "K"; |
| 439 | success = PyArg_Parse (py_return, format, (unsigned long long *) ret_value); |
| 440 | break; |
| 441 | } |
| 442 | case eFloat: |
| 443 | { |
| 444 | const char format[2] = "f"; |
| 445 | success = PyArg_Parse (py_return, format, (float *) ret_value); |
| 446 | break; |
| 447 | } |
| 448 | case eDouble: |
| 449 | { |
| 450 | const char format[2] = "d"; |
| 451 | success = PyArg_Parse (py_return, format, (double *) ret_value); |
| 452 | break; |
| 453 | } |
| 454 | case eChar: |
| 455 | { |
| 456 | const char format[2] = "c"; |
| 457 | success = PyArg_Parse (py_return, format, (char *) ret_value); |
| 458 | break; |
| 459 | } |
| 460 | default: |
| 461 | {} |
| 462 | } |
| 463 | Py_DECREF (py_return); |
| 464 | if (success) |
| 465 | ret_success = true; |
| 466 | else |
| 467 | ret_success = false; |
| 468 | } |
| 469 | } |
| 470 | |
| 471 | py_error = PyErr_Occurred(); |
| 472 | if (py_error != NULL) |
| 473 | { |
| 474 | if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError)) |
| 475 | PyErr_Print (); |
| 476 | PyErr_Clear(); |
| 477 | ret_success = false; |
| 478 | } |
| 479 | |
| 480 | return ret_success; |
| 481 | } |
| 482 | |
| 483 | bool |
| 484 | ScriptInterpreterPython::ExecuteMultipleLines (const char *in_string) |
| 485 | { |
| 486 | bool success = false; |
| 487 | PyObject *py_return = NULL; |
| 488 | PyObject *mainmod = PyImport_AddModule ("__main__"); |
| 489 | PyObject *globals = PyModule_GetDict (mainmod); |
| 490 | PyObject *locals = globals; |
| 491 | PyObject *py_error = NULL; |
| 492 | |
| 493 | if (in_string != NULL) |
| 494 | { |
| 495 | struct _node *compiled_node = PyParser_SimpleParseString (in_string, Py_file_input); |
| 496 | if (compiled_node) |
| 497 | { |
| 498 | PyCodeObject *compiled_code = PyNode_Compile (compiled_node, "temp.py"); |
| 499 | if (compiled_code) |
| 500 | { |
| 501 | py_return = PyEval_EvalCode (compiled_code, globals, locals); |
| 502 | if (py_return != NULL) |
| 503 | { |
| 504 | success = true; |
| 505 | Py_DECREF (py_return); |
| 506 | } |
| 507 | } |
| 508 | } |
| 509 | } |
| 510 | |
| 511 | py_error = PyErr_Occurred (); |
| 512 | if (py_error != NULL) |
| 513 | { |
| 514 | if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError)) |
| 515 | PyErr_Print (); |
| 516 | PyErr_Clear(); |
| 517 | success = false; |
| 518 | } |
| 519 | |
| 520 | return success; |
| 521 | } |
| 522 | |
| 523 | static const char *g_reader_instructions = "Enter your Python command(s). Type 'DONE' to end."; |
| 524 | |
| 525 | size_t |
| 526 | ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback |
| 527 | ( |
| 528 | void *baton, |
| 529 | InputReader *reader, |
| 530 | lldb::InputReaderAction notification, |
| 531 | const char *bytes, |
| 532 | size_t bytes_len |
| 533 | ) |
| 534 | { |
| 535 | static StringList commands_in_progress; |
| 536 | |
| 537 | FILE *out_fh = reader->GetOutputFileHandle(); |
| 538 | switch (notification) |
| 539 | { |
| 540 | case eInputReaderActivate: |
| 541 | { |
| 542 | commands_in_progress.Clear(); |
| 543 | if (out_fh) |
| 544 | { |
| 545 | ::fprintf (out_fh, "%s\n", g_reader_instructions); |
| 546 | if (reader->GetPrompt()) |
| 547 | ::fprintf (out_fh, "%s", reader->GetPrompt()); |
| 548 | } |
| 549 | } |
| 550 | break; |
| 551 | |
| 552 | case eInputReaderDeactivate: |
| 553 | break; |
| 554 | |
| 555 | case eInputReaderReactivate: |
| 556 | if (reader->GetPrompt() && out_fh) |
| 557 | ::fprintf (out_fh, "%s", reader->GetPrompt()); |
| 558 | break; |
| 559 | |
| 560 | case eInputReaderGotToken: |
| 561 | { |
| 562 | std::string temp_string (bytes, bytes_len); |
| 563 | commands_in_progress.AppendString (temp_string.c_str()); |
| 564 | if (out_fh && !reader->IsDone() && reader->GetPrompt()) |
| 565 | ::fprintf (out_fh, "%s", reader->GetPrompt()); |
| 566 | } |
| 567 | break; |
| 568 | |
| 569 | case eInputReaderDone: |
| 570 | { |
| 571 | BreakpointOptions *bp_options = (BreakpointOptions *)baton; |
| 572 | std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData()); |
| 573 | data_ap->user_source.AppendList (commands_in_progress); |
| 574 | if (data_ap.get()) |
| 575 | { |
| 576 | ScriptInterpreter *interpreter = Debugger::GetSharedInstance().GetCommandInterpreter().GetScriptInterpreter(); |
| 577 | if (interpreter) |
| 578 | { |
| 579 | if (interpreter->GenerateBreakpointCommandCallbackData (data_ap->user_source, |
| 580 | data_ap->script_source)) |
| 581 | { |
| 582 | if (data_ap->script_source.GetSize() == 1) |
| 583 | { |
| 584 | BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release())); |
| 585 | bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp); |
| 586 | } |
| 587 | } |
| 588 | } |
| 589 | else |
| 590 | { |
| 591 | // FIXME: Error processing. |
| 592 | } |
| 593 | } |
| 594 | } |
| 595 | break; |
| 596 | |
| 597 | } |
| 598 | |
| 599 | return bytes_len; |
| 600 | } |
| 601 | |
| 602 | void |
| 603 | ScriptInterpreterPython::CollectDataForBreakpointCommandCallback (BreakpointOptions *bp_options, |
| 604 | CommandReturnObject &result) |
| 605 | { |
| 606 | InputReaderSP reader_sp (new InputReader ()); |
| 607 | |
| 608 | if (reader_sp) |
| 609 | { |
| 610 | Error err = reader_sp->Initialize ( |
| 611 | ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback, |
| 612 | bp_options, // baton |
| 613 | eInputReaderGranularityLine, // token size, for feeding data to callback function |
| 614 | "DONE", // end token |
| 615 | "> ", // prompt |
| 616 | true); // echo input |
| 617 | |
| 618 | if (err.Success()) |
| 619 | Debugger::GetSharedInstance().PushInputReader (reader_sp); |
| 620 | else |
| 621 | { |
| 622 | result.AppendError (err.AsCString()); |
| 623 | result.SetStatus (eReturnStatusFailed); |
| 624 | } |
| 625 | } |
| 626 | else |
| 627 | { |
| 628 | result.AppendError("out of memory"); |
| 629 | result.SetStatus (eReturnStatusFailed); |
| 630 | } |
| 631 | } |
| 632 | |
| 633 | bool |
| 634 | ScriptInterpreterPython::ExportFunctionDefinitionToInterpreter (StringList &function_def) |
| 635 | { |
| 636 | // Convert StringList to one long, newline delimited, const char *. |
| 637 | std::string function_def_string; |
| 638 | |
| 639 | int num_lines = function_def.GetSize(); |
| 640 | |
| 641 | for (int i = 0; i < num_lines; ++i) |
| 642 | { |
| 643 | function_def_string.append (function_def.GetStringAtIndex(i)); |
| 644 | if (function_def_string.at (function_def_string.length() - 1) != '\n') |
| 645 | function_def_string.append ("\n"); |
| 646 | |
| 647 | } |
| 648 | |
| 649 | return ExecuteMultipleLines (function_def_string.c_str()); |
| 650 | } |
| 651 | |
| 652 | bool |
| 653 | ScriptInterpreterPython::GenerateBreakpointCommandCallbackData (StringList &user_input, StringList &callback_data) |
| 654 | { |
| 655 | static int num_created_functions = 0; |
| 656 | |
| 657 | user_input.RemoveBlankLines (); |
| 658 | int num_lines = user_input.GetSize(); |
| 659 | std::string last_function_call; |
| 660 | |
| 661 | // Go through lines of input looking for any function definitions. For each function definition found, |
| 662 | // export the function definition to Python, create a potential function call for the function, and |
| 663 | // mark the lines of the function to be removed from the user input. |
| 664 | |
| 665 | for (int i = 0; i < num_lines; ++i) |
| 666 | { |
| 667 | int function_start = i; |
| 668 | std::string current_str = user_input.GetStringAtIndex (i); |
| 669 | const char *current_line = current_str.c_str(); |
| 670 | int len = 0; |
| 671 | if (current_line) |
| 672 | len = strlen (current_line); |
| 673 | |
| 674 | // Check to see if the current line is the start of a Python function definition. |
| 675 | if (len > 4 && strncmp (current_line, "def ", 4) == 0) |
| 676 | { |
| 677 | // We've found the first line of a function. First, get the function name. |
| 678 | |
| 679 | // Skip over the 'def '. |
| 680 | char *start = (char *) current_line + 4; |
| 681 | |
| 682 | // Skip over white space. |
| 683 | while (start[0] == ' ' || start[0] == '\t') |
| 684 | ++start; |
| 685 | |
| 686 | // Find the end of the function name. |
| 687 | char *end = start; |
| 688 | while (isalnum (end[0]) || end[0] == '_') |
| 689 | ++end; |
| 690 | |
| 691 | int name_len = end - start; |
| 692 | std::string func_name = current_str.substr (4, name_len); |
| 693 | |
| 694 | // Now to find the last line of the function. That will be the first line that does not begin with |
| 695 | // any white space (thanks to Python's indentation rules). |
| 696 | ++i; |
| 697 | bool found = false; |
| 698 | while (i < num_lines && !found) |
| 699 | { |
| 700 | std::string next_str = user_input.GetStringAtIndex (i); |
| 701 | const char *next_line = next_str.c_str(); |
| 702 | if (next_line[0] != ' ' && next_line[0] != '\t') |
| 703 | found = true; |
| 704 | else |
| 705 | ++i; |
| 706 | } |
| 707 | if (found) |
| 708 | --i; // Make 'i' correspond to the last line of the function. |
| 709 | int function_end = i; |
| 710 | |
| 711 | // Special case: All of user_input is one big function definition. |
| 712 | if ((function_start == 0) && (function_end == (num_lines - 1))) |
| 713 | { |
| 714 | ExportFunctionDefinitionToInterpreter (user_input); |
| 715 | last_function_call = func_name + " ()"; |
| 716 | callback_data.AppendString (last_function_call.c_str()); |
| 717 | return callback_data.GetSize() > 0; |
| 718 | } |
| 719 | else |
| 720 | { |
| 721 | // Make a copy of the function definition: |
| 722 | StringList new_function; |
| 723 | for (int k = function_start; k <= function_end; ++k) |
| 724 | { |
| 725 | new_function.AppendString (user_input.GetStringAtIndex (k)); |
| 726 | // Mark the string to be deleted from user_input. |
| 727 | user_input.DeleteStringAtIndex (k); |
| 728 | user_input.InsertStringAtIndex (k, "<lldb_delete>"); |
| 729 | } |
| 730 | ExportFunctionDefinitionToInterpreter (new_function); |
| 731 | last_function_call = func_name + " ()"; |
| 732 | } |
| 733 | } |
| 734 | } |
| 735 | |
| 736 | // Now instead of trying to really delete the marked lines from user_input, we will just copy all the |
| 737 | // unmarked lines into a new StringList. |
| 738 | |
| 739 | StringList new_user_input; |
| 740 | |
| 741 | for (int i = 0; i < num_lines; ++i) |
| 742 | { |
| 743 | std::string current_string = user_input.GetStringAtIndex (i); |
| 744 | if (current_string.compare (0, 13, "<lldb_delete>") == 0) |
| 745 | continue; |
| 746 | |
| 747 | new_user_input.AppendString (current_string.c_str()); |
| 748 | } |
| 749 | |
| 750 | num_lines = new_user_input.GetSize(); |
| 751 | |
| 752 | if (num_lines > 0) |
| 753 | { |
| 754 | if (num_lines == 1 |
| 755 | && strchr (new_user_input.GetStringAtIndex(0), '\n') == NULL) |
| 756 | { |
| 757 | // If there's only one line of input, and it doesn't contain any newline characters.... |
| 758 | callback_data.AppendString (new_user_input.GetStringAtIndex (0)); |
| 759 | } |
| 760 | else |
| 761 | { |
| 762 | // Create the new function name. |
| 763 | StreamString func_name; |
| 764 | func_name.Printf ("lldb_bp_callback_func_%d", num_created_functions); |
| 765 | //std::string func_name = "lldb_bp_callback_func_" + num_created_functions; |
| 766 | ++num_created_functions; |
| 767 | |
| 768 | // Create the function call for the new function. |
| 769 | last_function_call = func_name.GetString() + " ()"; |
| 770 | |
| 771 | // Create the Python function definition line (which will have to be inserted at the beginning of |
| 772 | // the function). |
| 773 | std::string def_line = "def " + func_name.GetString() + " ():"; |
| 774 | |
| 775 | |
| 776 | // Indent all lines an additional four spaces (as they are now being put inside a function definition). |
| 777 | for (int i = 0; i < num_lines; ++i) |
| 778 | { |
| 779 | const char *temp_cstring = new_user_input.GetStringAtIndex(i); |
| 780 | std::string temp2 = " "; |
| 781 | temp2.append(temp_cstring); |
| 782 | new_user_input.DeleteStringAtIndex (i); |
| 783 | new_user_input.InsertStringAtIndex (i, temp2.c_str()); |
| 784 | } |
| 785 | |
| 786 | // Insert the function definition line at the top of the new function. |
| 787 | new_user_input.InsertStringAtIndex (0, def_line.c_str()); |
| 788 | |
| 789 | ExportFunctionDefinitionToInterpreter (new_user_input); |
| 790 | callback_data.AppendString (last_function_call.c_str()); |
| 791 | } |
| 792 | } |
| 793 | else |
| 794 | { |
| 795 | if (!last_function_call.empty()) |
| 796 | callback_data.AppendString (last_function_call.c_str()); |
| 797 | } |
| 798 | |
| 799 | return callback_data.GetSize() > 0; |
| 800 | } |
| 801 | |
| 802 | bool |
| 803 | ScriptInterpreterPython::BreakpointCallbackFunction |
| 804 | ( |
| 805 | void *baton, |
| 806 | StoppointCallbackContext *context, |
| 807 | lldb::user_id_t break_id, |
| 808 | lldb::user_id_t break_loc_id |
| 809 | ) |
| 810 | { |
| 811 | bool ret_value = true; |
| 812 | bool temp_bool; |
| 813 | |
| 814 | BreakpointOptions::CommandData *bp_option_data = (BreakpointOptions::CommandData *) baton; |
| 815 | |
| 816 | const char *python_string = bp_option_data->script_source.GetStringAtIndex(0); |
| 817 | |
| 818 | if (python_string != NULL) |
| 819 | { |
| 820 | bool success = |
| 821 | Debugger::GetSharedInstance().GetCommandInterpreter().GetScriptInterpreter()->ExecuteOneLineWithReturn |
| 822 | (python_string, |
| 823 | ScriptInterpreter::eBool, |
| 824 | (void *) &temp_bool); |
| 825 | if (success) |
| 826 | ret_value = temp_bool; |
| 827 | } |
| 828 | |
| 829 | return ret_value; |
| 830 | } |