blob: 59eb4642298179efdd82ca1b235e64e3fc39e88c [file] [log] [blame]
Chris Lattner24943d22010-06-08 16:52:24 +00001//===-- 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
38extern "C" void init_lldb (void);
39
40using namespace lldb;
41using namespace lldb_private;
42
43const char embedded_interpreter_string[] =
44"import readline\n\
45import code\n\
46import sys\n\
47import traceback\n\
48\n\
49class 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\
Jason Molendaa8a5e562010-06-09 21:56:00 +000091 if (temp_str.lower() == \"quit()\" or temp_str.lower() == \"exit()\"):\n\
Chris Lattner24943d22010-06-08 16:52:24 +000092 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\
130def 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
135static int
136_check_and_flush (FILE *stream)
137{
138 int prev_fail = ferror (stream);
139 return fflush (stream) || prev_fail ? EOF : 0;
140}
141
142ScriptInterpreterPython::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
Eli Friedman3c90d992010-06-09 18:31:38 +0000182 m_compiled_module = static_cast<void*>(compiled_module);
Chris Lattner24943d22010-06-08 16:52:24 +0000183
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
Eli Friedman3c90d992010-06-09 18:31:38 +0000199 PyObject *pmod = PyImport_ExecCodeModule(
200 const_cast<char*>("embedded_interpreter"),
201 static_cast<PyObject*>(m_compiled_module));
Chris Lattner24943d22010-06-08 16:52:24 +0000202 if (pmod != NULL)
203 {
204 PyRun_SimpleString ("ConsoleDict = locals()");
205 PyRun_SimpleString ("from embedded_interpreter import run_python_interpreter");
206 PyRun_SimpleString ("import sys");
207 PyRun_SimpleString ("from termios import *");
208 PyRun_SimpleString ("old_stdin = sys.stdin");
209
210 StreamString run_string;
211 run_string.Printf ("new_stdin = open('%s', 'r')", pty_slave_name);
212 PyRun_SimpleString (run_string.GetData());
213 PyRun_SimpleString ("sys.stdin = new_stdin");
214
215 PyRun_SimpleString ("old_stdout = sys.stdout");
216
217 if (out_fh != NULL)
218 {
219 PyObject *new_sysout = PyFile_FromFile (out_fh, (char *) "", (char *) "w",
220 _check_and_flush);
221 PyObject *sysmod = PyImport_AddModule ("sys");
222 PyObject *sysdict = PyModule_GetDict (sysmod);
223
224 if ((new_sysout != NULL)
225 && (sysmod != NULL)
226 && (sysdict != NULL))
227 {
228 PyDict_SetItemString (sysdict, "stdout", new_sysout);
229 }
230
231 if (PyErr_Occurred())
232 PyErr_Clear();
233 }
234
235 PyRun_SimpleString ("new_mode = tcgetattr(new_stdin)");
236 PyRun_SimpleString ("new_mode[3] = new_mode[3] | ECHO | ICANON");
237 PyRun_SimpleString ("new_mode[6][VEOF] = 255");
238 PyRun_SimpleString ("tcsetattr (new_stdin, TCSANOW, new_mode)");
239 }
240
241
242}
243
244ScriptInterpreterPython::~ScriptInterpreterPython ()
245{
246 PyRun_SimpleString ("sys.stdin = old_stdin");
247 PyRun_SimpleString ("sys.stdout = old_stdout");
248 Py_Finalize ();
249}
250
251void
252ScriptInterpreterPython::ExecuteOneLine (const std::string& line, FILE *out, FILE *err)
253{
254 int success;
255
256 success = PyRun_SimpleString (line.c_str());
257 if (success != 0)
258 {
259 fprintf (err, "error: python failed attempting to evaluate '%s'\n", line.c_str());
260 }
261}
262
263
264
265size_t
266ScriptInterpreterPython::InputReaderCallback
267(
268 void *baton,
269 InputReader *reader,
270 lldb::InputReaderAction notification,
271 const char *bytes,
272 size_t bytes_len
273)
274{
275 if (baton == NULL)
276 return 0;
277
278 ScriptInterpreterPython *interpreter = (ScriptInterpreterPython *) baton;
279 switch (notification)
280 {
281 case eInputReaderActivate:
282 {
283 // Save terminal settings if we can
284 interpreter->m_termios_valid = ::tcgetattr (::fileno (reader->GetInputFileHandle()),
285 &interpreter->m_termios) == 0;
286 struct termios tmp_termios;
287 if (::tcgetattr (::fileno (reader->GetInputFileHandle()), &tmp_termios) == 0)
288 {
289 tmp_termios.c_cc[VEOF] = _POSIX_VDISABLE;
290 ::tcsetattr (::fileno (reader->GetInputFileHandle()), TCSANOW, &tmp_termios);
291 }
292 }
293 break;
294
295 case eInputReaderDeactivate:
296 break;
297
298 case eInputReaderReactivate:
299 break;
300
301 case eInputReaderGotToken:
302 if (bytes && bytes_len)
303 {
304 if ((int) bytes[0] == 4)
305 ::write (interpreter->GetMasterFileDescriptor(), "quit()", 6);
306 else
307 ::write (interpreter->GetMasterFileDescriptor(), bytes, bytes_len);
308 }
309 ::write (interpreter->GetMasterFileDescriptor(), "\n", 1);
310 break;
311
312 case eInputReaderDone:
313 // Send a control D to the script interpreter
314 //::write (interpreter->GetMasterFileDescriptor(), "\nquit()\n", strlen("\nquit()\n"));
315 // Write a newline out to the reader output
316 //::fwrite ("\n", 1, 1, out_fh);
317 // Restore terminal settings if they were validly saved
318 if (interpreter->m_termios_valid)
319 {
320 ::tcsetattr (::fileno (reader->GetInputFileHandle()),
321 TCSANOW,
322 &interpreter->m_termios);
323 }
324 break;
325 }
326
327 return bytes_len;
328}
329
330
331void
332ScriptInterpreterPython::ExecuteInterpreterLoop (FILE *out, FILE *err)
333{
334 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
335
336 InputReaderSP reader_sp (new InputReader());
337 if (reader_sp)
338 {
339 Error error (reader_sp->Initialize (ScriptInterpreterPython::InputReaderCallback,
340 this, // baton
341 eInputReaderGranularityLine, // token size, to pass to callback function
342 NULL, // end token
343 NULL, // prompt
344 true)); // echo input
345
346 if (error.Success())
347 {
348 Debugger::GetSharedInstance().PushInputReader (reader_sp);
349 ExecuteOneLine ("run_python_interpreter(ConsoleDict)", out, err);
350 Debugger::GetSharedInstance().PopInputReader (reader_sp);
351 }
352 }
353}
354
355bool
356ScriptInterpreterPython::ExecuteOneLineWithReturn (const char *in_string,
357 ScriptInterpreter::ReturnType return_type,
358 void *ret_value)
359{
360 PyObject *py_return = NULL;
361 PyObject *mainmod = PyImport_AddModule ("__main__");
362 PyObject *globals = PyModule_GetDict (mainmod);
363 PyObject *locals = globals;
364 PyObject *py_error = NULL;
365 bool ret_success;
366 int success;
367
368 if (in_string != NULL)
369 {
370 py_return = PyRun_String (in_string, Py_eval_input, globals, locals);
371 if (py_return == NULL)
372 {
373 py_error = PyErr_Occurred ();
374 if (py_error != NULL)
375 PyErr_Clear ();
376
377 py_return = PyRun_String (in_string, Py_single_input, globals, locals);
378 }
379
380 if (py_return != NULL)
381 {
382 switch (return_type)
383 {
384 case eCharPtr: // "char *"
385 {
386 const char format[3] = "s#";
387 success = PyArg_Parse (py_return, format, (char **) &ret_value);
388 break;
389 }
390 case eBool:
391 {
392 const char format[2] = "b";
393 success = PyArg_Parse (py_return, format, (bool *) ret_value);
394 break;
395 }
396 case eShortInt:
397 {
398 const char format[2] = "h";
399 success = PyArg_Parse (py_return, format, (short *) ret_value);
400 break;
401 }
402 case eShortIntUnsigned:
403 {
404 const char format[2] = "H";
405 success = PyArg_Parse (py_return, format, (unsigned short *) ret_value);
406 break;
407 }
408 case eInt:
409 {
410 const char format[2] = "i";
411 success = PyArg_Parse (py_return, format, (int *) ret_value);
412 break;
413 }
414 case eIntUnsigned:
415 {
416 const char format[2] = "I";
417 success = PyArg_Parse (py_return, format, (unsigned int *) ret_value);
418 break;
419 }
420 case eLongInt:
421 {
422 const char format[2] = "l";
423 success = PyArg_Parse (py_return, format, (long *) ret_value);
424 break;
425 }
426 case eLongIntUnsigned:
427 {
428 const char format[2] = "k";
429 success = PyArg_Parse (py_return, format, (unsigned long *) ret_value);
430 break;
431 }
432 case eLongLong:
433 {
434 const char format[2] = "L";
435 success = PyArg_Parse (py_return, format, (long long *) ret_value);
436 break;
437 }
438 case eLongLongUnsigned:
439 {
440 const char format[2] = "K";
441 success = PyArg_Parse (py_return, format, (unsigned long long *) ret_value);
442 break;
443 }
444 case eFloat:
445 {
446 const char format[2] = "f";
447 success = PyArg_Parse (py_return, format, (float *) ret_value);
448 break;
449 }
450 case eDouble:
451 {
452 const char format[2] = "d";
453 success = PyArg_Parse (py_return, format, (double *) ret_value);
454 break;
455 }
456 case eChar:
457 {
458 const char format[2] = "c";
459 success = PyArg_Parse (py_return, format, (char *) ret_value);
460 break;
461 }
462 default:
463 {}
464 }
465 Py_DECREF (py_return);
466 if (success)
467 ret_success = true;
468 else
469 ret_success = false;
470 }
471 }
472
473 py_error = PyErr_Occurred();
474 if (py_error != NULL)
475 {
476 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
477 PyErr_Print ();
478 PyErr_Clear();
479 ret_success = false;
480 }
481
482 return ret_success;
483}
484
485bool
486ScriptInterpreterPython::ExecuteMultipleLines (const char *in_string)
487{
488 bool success = false;
489 PyObject *py_return = NULL;
490 PyObject *mainmod = PyImport_AddModule ("__main__");
491 PyObject *globals = PyModule_GetDict (mainmod);
492 PyObject *locals = globals;
493 PyObject *py_error = NULL;
494
495 if (in_string != NULL)
496 {
497 struct _node *compiled_node = PyParser_SimpleParseString (in_string, Py_file_input);
498 if (compiled_node)
499 {
500 PyCodeObject *compiled_code = PyNode_Compile (compiled_node, "temp.py");
501 if (compiled_code)
502 {
503 py_return = PyEval_EvalCode (compiled_code, globals, locals);
504 if (py_return != NULL)
505 {
506 success = true;
507 Py_DECREF (py_return);
508 }
509 }
510 }
511 }
512
513 py_error = PyErr_Occurred ();
514 if (py_error != NULL)
515 {
516 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
517 PyErr_Print ();
518 PyErr_Clear();
519 success = false;
520 }
521
522 return success;
523}
524
525static const char *g_reader_instructions = "Enter your Python command(s). Type 'DONE' to end.";
526
527size_t
528ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback
529(
530 void *baton,
531 InputReader *reader,
532 lldb::InputReaderAction notification,
533 const char *bytes,
534 size_t bytes_len
535)
536{
537 static StringList commands_in_progress;
538
539 FILE *out_fh = reader->GetOutputFileHandle();
540 switch (notification)
541 {
542 case eInputReaderActivate:
543 {
544 commands_in_progress.Clear();
545 if (out_fh)
546 {
547 ::fprintf (out_fh, "%s\n", g_reader_instructions);
548 if (reader->GetPrompt())
549 ::fprintf (out_fh, "%s", reader->GetPrompt());
550 }
551 }
552 break;
553
554 case eInputReaderDeactivate:
555 break;
556
557 case eInputReaderReactivate:
558 if (reader->GetPrompt() && out_fh)
559 ::fprintf (out_fh, "%s", reader->GetPrompt());
560 break;
561
562 case eInputReaderGotToken:
563 {
564 std::string temp_string (bytes, bytes_len);
565 commands_in_progress.AppendString (temp_string.c_str());
566 if (out_fh && !reader->IsDone() && reader->GetPrompt())
567 ::fprintf (out_fh, "%s", reader->GetPrompt());
568 }
569 break;
570
571 case eInputReaderDone:
572 {
573 BreakpointOptions *bp_options = (BreakpointOptions *)baton;
574 std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
575 data_ap->user_source.AppendList (commands_in_progress);
576 if (data_ap.get())
577 {
578 ScriptInterpreter *interpreter = Debugger::GetSharedInstance().GetCommandInterpreter().GetScriptInterpreter();
579 if (interpreter)
580 {
581 if (interpreter->GenerateBreakpointCommandCallbackData (data_ap->user_source,
582 data_ap->script_source))
583 {
584 if (data_ap->script_source.GetSize() == 1)
585 {
586 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
587 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
588 }
589 }
590 }
591 else
592 {
593 // FIXME: Error processing.
594 }
595 }
596 }
597 break;
598
599 }
600
601 return bytes_len;
602}
603
604void
605ScriptInterpreterPython::CollectDataForBreakpointCommandCallback (BreakpointOptions *bp_options,
606 CommandReturnObject &result)
607{
608 InputReaderSP reader_sp (new InputReader ());
609
610 if (reader_sp)
611 {
612 Error err = reader_sp->Initialize (
613 ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback,
614 bp_options, // baton
615 eInputReaderGranularityLine, // token size, for feeding data to callback function
616 "DONE", // end token
617 "> ", // prompt
618 true); // echo input
619
620 if (err.Success())
621 Debugger::GetSharedInstance().PushInputReader (reader_sp);
622 else
623 {
624 result.AppendError (err.AsCString());
625 result.SetStatus (eReturnStatusFailed);
626 }
627 }
628 else
629 {
630 result.AppendError("out of memory");
631 result.SetStatus (eReturnStatusFailed);
632 }
633}
634
635bool
636ScriptInterpreterPython::ExportFunctionDefinitionToInterpreter (StringList &function_def)
637{
638 // Convert StringList to one long, newline delimited, const char *.
639 std::string function_def_string;
640
641 int num_lines = function_def.GetSize();
642
643 for (int i = 0; i < num_lines; ++i)
644 {
645 function_def_string.append (function_def.GetStringAtIndex(i));
646 if (function_def_string.at (function_def_string.length() - 1) != '\n')
647 function_def_string.append ("\n");
648
649 }
650
651 return ExecuteMultipleLines (function_def_string.c_str());
652}
653
654bool
655ScriptInterpreterPython::GenerateBreakpointCommandCallbackData (StringList &user_input, StringList &callback_data)
656{
657 static int num_created_functions = 0;
658
659 user_input.RemoveBlankLines ();
660 int num_lines = user_input.GetSize();
661 std::string last_function_call;
662
663 // Go through lines of input looking for any function definitions. For each function definition found,
664 // export the function definition to Python, create a potential function call for the function, and
665 // mark the lines of the function to be removed from the user input.
666
667 for (int i = 0; i < num_lines; ++i)
668 {
669 int function_start = i;
670 std::string current_str = user_input.GetStringAtIndex (i);
671 const char *current_line = current_str.c_str();
672 int len = 0;
673 if (current_line)
674 len = strlen (current_line);
675
676 // Check to see if the current line is the start of a Python function definition.
677 if (len > 4 && strncmp (current_line, "def ", 4) == 0)
678 {
679 // We've found the first line of a function. First, get the function name.
680
681 // Skip over the 'def '.
682 char *start = (char *) current_line + 4;
683
684 // Skip over white space.
685 while (start[0] == ' ' || start[0] == '\t')
686 ++start;
687
688 // Find the end of the function name.
689 char *end = start;
690 while (isalnum (end[0]) || end[0] == '_')
691 ++end;
692
693 int name_len = end - start;
694 std::string func_name = current_str.substr (4, name_len);
695
696 // Now to find the last line of the function. That will be the first line that does not begin with
697 // any white space (thanks to Python's indentation rules).
698 ++i;
699 bool found = false;
700 while (i < num_lines && !found)
701 {
702 std::string next_str = user_input.GetStringAtIndex (i);
703 const char *next_line = next_str.c_str();
704 if (next_line[0] != ' ' && next_line[0] != '\t')
705 found = true;
706 else
707 ++i;
708 }
709 if (found)
710 --i; // Make 'i' correspond to the last line of the function.
711 int function_end = i;
712
713 // Special case: All of user_input is one big function definition.
714 if ((function_start == 0) && (function_end == (num_lines - 1)))
715 {
716 ExportFunctionDefinitionToInterpreter (user_input);
717 last_function_call = func_name + " ()";
718 callback_data.AppendString (last_function_call.c_str());
719 return callback_data.GetSize() > 0;
720 }
721 else
722 {
723 // Make a copy of the function definition:
724 StringList new_function;
725 for (int k = function_start; k <= function_end; ++k)
726 {
727 new_function.AppendString (user_input.GetStringAtIndex (k));
728 // Mark the string to be deleted from user_input.
729 user_input.DeleteStringAtIndex (k);
730 user_input.InsertStringAtIndex (k, "<lldb_delete>");
731 }
732 ExportFunctionDefinitionToInterpreter (new_function);
733 last_function_call = func_name + " ()";
734 }
735 }
736 }
737
738 // Now instead of trying to really delete the marked lines from user_input, we will just copy all the
739 // unmarked lines into a new StringList.
740
741 StringList new_user_input;
742
743 for (int i = 0; i < num_lines; ++i)
744 {
745 std::string current_string = user_input.GetStringAtIndex (i);
746 if (current_string.compare (0, 13, "<lldb_delete>") == 0)
747 continue;
748
749 new_user_input.AppendString (current_string.c_str());
750 }
751
752 num_lines = new_user_input.GetSize();
753
754 if (num_lines > 0)
755 {
756 if (num_lines == 1
757 && strchr (new_user_input.GetStringAtIndex(0), '\n') == NULL)
758 {
759 // If there's only one line of input, and it doesn't contain any newline characters....
760 callback_data.AppendString (new_user_input.GetStringAtIndex (0));
761 }
762 else
763 {
764 // Create the new function name.
765 StreamString func_name;
766 func_name.Printf ("lldb_bp_callback_func_%d", num_created_functions);
767 //std::string func_name = "lldb_bp_callback_func_" + num_created_functions;
768 ++num_created_functions;
769
770 // Create the function call for the new function.
771 last_function_call = func_name.GetString() + " ()";
772
773 // Create the Python function definition line (which will have to be inserted at the beginning of
774 // the function).
775 std::string def_line = "def " + func_name.GetString() + " ():";
776
777
778 // Indent all lines an additional four spaces (as they are now being put inside a function definition).
779 for (int i = 0; i < num_lines; ++i)
780 {
781 const char *temp_cstring = new_user_input.GetStringAtIndex(i);
782 std::string temp2 = " ";
783 temp2.append(temp_cstring);
784 new_user_input.DeleteStringAtIndex (i);
785 new_user_input.InsertStringAtIndex (i, temp2.c_str());
786 }
787
788 // Insert the function definition line at the top of the new function.
789 new_user_input.InsertStringAtIndex (0, def_line.c_str());
790
791 ExportFunctionDefinitionToInterpreter (new_user_input);
792 callback_data.AppendString (last_function_call.c_str());
793 }
794 }
795 else
796 {
797 if (!last_function_call.empty())
798 callback_data.AppendString (last_function_call.c_str());
799 }
800
801 return callback_data.GetSize() > 0;
802}
803
804bool
805ScriptInterpreterPython::BreakpointCallbackFunction
806(
807 void *baton,
808 StoppointCallbackContext *context,
809 lldb::user_id_t break_id,
810 lldb::user_id_t break_loc_id
811)
812{
813 bool ret_value = true;
814 bool temp_bool;
815
816 BreakpointOptions::CommandData *bp_option_data = (BreakpointOptions::CommandData *) baton;
817
818 const char *python_string = bp_option_data->script_source.GetStringAtIndex(0);
819
820 if (python_string != NULL)
821 {
822 bool success =
823 Debugger::GetSharedInstance().GetCommandInterpreter().GetScriptInterpreter()->ExecuteOneLineWithReturn
824 (python_string,
825 ScriptInterpreter::eBool,
826 (void *) &temp_bool);
827 if (success)
828 ret_value = temp_bool;
829 }
830
831 return ret_value;
832}