Debian Codegraph @

src/Gui/PythonDebugger.cpp

raw
1 /***************************************************************************
2 * Copyright (c) 2010 Werner Mayer <wmayer[at]users.sourceforge.net> *
3 * *
4 * This file is part of the FreeCAD CAx development system. *
5 * *
6 * This library is free software; you can redistribute it and/or *
7 * modify it under the terms of the GNU Library General Public *
8 * License as published by the Free Software Foundation; either *
9 * version 2 of the License, or (at your option) any later version. *
10 * *
11 * This library is distributed in the hope that it will be useful, *
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
14 * GNU Library General Public License for more details. *
15 * *
16 * You should have received a copy of the GNU Library General Public *
17 * License along with this library; see the file COPYING.LIB. If not, *
18 * write to the Free Software Foundation, Inc., 59 Temple Place, *
19 * Suite 330, Boston, MA 02111-1307, USA *
20 * *
21 ***************************************************************************/
22
23
24 #include <QCoreApplication>
25 #include <QEventLoop>
26
27 #include <FCConfig.h>
28
29 #include <Base/Console.h>
30 #include <Base/Interpreter.h>
31
32 #include "PythonDebugger.h"
33 #include "BitmapFactory.h"
34 #include "EditorView.h"
35 #include "MainWindow.h"
36 #include "PythonEditor.h"
37
38
39 using namespace Gui;
40
41 Breakpoint::Breakpoint() = default;
42
43 Breakpoint::Breakpoint(const Breakpoint& rBp)
44 {
45 setFilename(rBp.filename());
46 for (int it : rBp._linenums) {
47 _linenums.insert(it);
48 }
49 }
50
51 Breakpoint& Breakpoint::operator=(const Breakpoint& rBp)
52 {
53 if (this == &rBp) {
54 return *this;
55 }
56 setFilename(rBp.filename());
57 _linenums.clear();
58 for (int it : rBp._linenums) {
59 _linenums.insert(it);
60 }
61 return *this;
62 }
63
64 Breakpoint::~Breakpoint() = default;
65
66 void Breakpoint::setFilename(const QString& fn)
67 {
68 _filename = fn;
69 }
70
71 void Breakpoint::addLine(int line)
72 {
73 _linenums.insert(line);
74 }
75
76 void Breakpoint::removeLine(int line)
77 {
78 _linenums.erase(line);
79 }
80
81 bool Breakpoint::checkLine(int line)
82 {
83 return (_linenums.find(line) != _linenums.end());
84 }
85
86 int Breakpoint::lineIndex(int ind) const
87 {
88 int i = 0;
89 for (int it : _linenums) {
90 if (ind == i++) {
91 return it;
92 }
93 }
94 return -1;
95 }
96
97 // -----------------------------------------------------
98
99 void PythonDebugModule::init_module()
100 {
101 PythonDebugStdout::init_type();
102 PythonDebugStderr::init_type();
103 PythonDebugExcept::init_type();
104 Base::Interpreter().addModule(new PythonDebugModule);
105 }
106
107 PythonDebugModule::PythonDebugModule()
108 : Py::ExtensionModule<PythonDebugModule>("FreeCADDbg")
109 {
110 add_varargs_method(
111 "getFunctionCallCount",
112 &PythonDebugModule::getFunctionCallCount,
113 "Get the total number of function calls executed and the number executed since the last "
114 "call to this function."
115 );
116 add_varargs_method(
117 "getExceptionCount",
118 &PythonDebugModule::getExceptionCount,
119 "Get the total number of exceptions and the number executed since the last call to this "
120 "function."
121 );
122 add_varargs_method(
123 "getLineCount",
124 &PythonDebugModule::getLineCount,
125 "Get the total number of lines executed and the number executed since the last call to "
126 "this function."
127 );
128 add_varargs_method(
129 "getFunctionReturnCount",
130 &PythonDebugModule::getFunctionReturnCount,
131 "Get the total number of function returns executed and the number executed since the last "
132 "call to this function."
133 );
134
135 initialize("The FreeCAD Python debug module");
136
137 Py::Dict d(moduleDictionary());
138 Py::Object out(Py::asObject(new PythonDebugStdout()));
139 d["StdOut"] = out;
140 Py::Object err(Py::asObject(new PythonDebugStderr()));
141 d["StdErr"] = err;
142 }
143
144 PythonDebugModule::~PythonDebugModule()
145 {
146 Py::Dict d(moduleDictionary());
147 d["StdOut"] = Py::None();
148 d["StdErr"] = Py::None();
149 }
150
151 Py::Object PythonDebugModule::getFunctionCallCount(const Py::Tuple&)
152 {
153 return Py::None();
154 }
155
156 Py::Object PythonDebugModule::getExceptionCount(const Py::Tuple&)
157 {
158 return Py::None();
159 }
160
161 Py::Object PythonDebugModule::getLineCount(const Py::Tuple&)
162 {
163 return Py::None();
164 }
165
166 Py::Object PythonDebugModule::getFunctionReturnCount(const Py::Tuple&)
167 {
168 return Py::None();
169 }
170
171 // -----------------------------------------------------
172
173 void PythonDebugStdout::init_type()
174 {
175 behaviors().name("PythonDebugStdout");
176 behaviors().doc("Redirection of stdout to FreeCAD's Python debugger window");
177 // you must have overwritten the virtual functions
178 behaviors().supportRepr();
179 add_varargs_method("write", &PythonDebugStdout::write, "write to stdout");
180 add_varargs_method("flush", &PythonDebugStdout::flush, "flush the output");
181 }
182
183 PythonDebugStdout::PythonDebugStdout() = default;
184
185 PythonDebugStdout::~PythonDebugStdout() = default;
186
187 Py::Object PythonDebugStdout::repr()
188 {
189 return Py::String("PythonDebugStdout");
190 }
191
192 Py::Object PythonDebugStdout::write(const Py::Tuple& args)
193 {
194 char* msg;
195 // args contains a single parameter which is the string to write.
196 if (!PyArg_ParseTuple(args.ptr(), "s:OutputString", &msg)) {
197 throw Py::Exception();
198 }
199
200 if (strlen(msg) > 0) {
201 // send it to our stdout
202 printf("%s\n", msg);
203 }
204 return Py::None();
205 }
206
207 Py::Object PythonDebugStdout::flush(const Py::Tuple&)
208 {
209 return Py::None();
210 }
211
212 // -----------------------------------------------------
213
214 void PythonDebugStderr::init_type()
215 {
216 behaviors().name("PythonDebugStderr");
217 behaviors().doc("Redirection of stderr to FreeCAD's Python debugger window");
218 // you must have overwritten the virtual functions
219 behaviors().supportRepr();
220 add_varargs_method("write", &PythonDebugStderr::write, "write to stderr");
221 }
222
223 PythonDebugStderr::PythonDebugStderr() = default;
224
225 PythonDebugStderr::~PythonDebugStderr() = default;
226
227 Py::Object PythonDebugStderr::repr()
228 {
229 return Py::String("PythonDebugStderr");
230 }
231
232 Py::Object PythonDebugStderr::write(const Py::Tuple& args)
233 {
234 char* msg;
235 // args contains a single parameter which is the string to write.
236 if (!PyArg_ParseTuple(args.ptr(), "s:OutputDebugString", &msg)) {
237 throw Py::Exception();
238 }
239
240 if (strlen(msg) > 0) {
241 Base::Console().error("%s", msg);
242 }
243
244 return Py::None();
245 }
246
247 // -----------------------------------------------------
248
249 void PythonDebugExcept::init_type()
250 {
251 behaviors().name("PythonDebugExcept");
252 behaviors().doc("Custom exception handler");
253 // you must have overwritten the virtual functions
254 behaviors().supportRepr();
255 add_varargs_method("fc_excepthook", &PythonDebugExcept::excepthook, "Custom exception handler");
256 }
257
258 PythonDebugExcept::PythonDebugExcept() = default;
259
260 PythonDebugExcept::~PythonDebugExcept() = default;
261
262 Py::Object PythonDebugExcept::repr()
263 {
264 return Py::String("PythonDebugExcept");
265 }
266
267 Py::Object PythonDebugExcept::excepthook(const Py::Tuple& args)
268 {
269 PyObject *exc, *value, *tb;
270 if (!PyArg_UnpackTuple(args.ptr(), "excepthook", 3, 3, &exc, &value, &tb)) {
271 throw Py::Exception();
272 }
273
274 PyErr_NormalizeException(&exc, &value, &tb);
275
276 PyErr_Display(exc, value, tb);
277
278 return Py::None();
279 }
280
281 // -----------------------------------------------------
282
283 namespace Gui
284 {
285 class PythonDebuggerPy: public Py::PythonExtension<PythonDebuggerPy>
286 {
287 public:
288 explicit PythonDebuggerPy(PythonDebugger* d)
289 : dbg(d)
290 , depth(0)
291 {}
292 ~PythonDebuggerPy() override = default;
293 PythonDebugger* dbg;
294 int depth;
295 };
296
297 class RunningState
298 {
299 public:
300 explicit RunningState(bool& s)
301 : state(s)
302 {
303 state = true;
304 }
305 ~RunningState()
306 {
307 state = false;
308 }
309
310 private:
311 bool& state;
312 };
313
314 struct PythonDebuggerP
315 {
316 PyObject* out_o {nullptr};
317 PyObject* err_o {nullptr};
318 PyObject* exc_o {nullptr};
319 PyObject* out_n {nullptr};
320 PyObject* err_n {nullptr};
321 PyObject* exc_n {nullptr};
322 PythonDebugExcept* pypde;
323 bool init {false}, trystop {false}, running {false};
324 QEventLoop loop;
325 PyObject* pydbg {nullptr};
326 std::vector<Breakpoint> bps;
327
328 explicit PythonDebuggerP(PythonDebugger* that)
329 {
330 Base::PyGILStateLocker lock;
331 out_n = new PythonDebugStdout();
332 err_n = new PythonDebugStderr();
333 pypde = new PythonDebugExcept();
334 Py::Object func = pypde->getattr("fc_excepthook");
335 exc_n = Py::new_reference_to(func);
336 pydbg = new PythonDebuggerPy(that);
337 }
338 ~PythonDebuggerP()
339 {
340 Base::PyGILStateLocker lock;
341 Py_DECREF(out_n);
342 Py_DECREF(err_n);
343 Py_DECREF(exc_n);
344 Py_DECREF(pypde);
345 Py_DECREF(pydbg);
346 }
347 };
348 } // namespace Gui
349
350 PythonDebugger::PythonDebugger()
351 : d(new PythonDebuggerP(this))
352 {}
353
354 PythonDebugger::~PythonDebugger()
355 {
356 delete d;
357 }
358
359 Breakpoint PythonDebugger::getBreakpoint(const QString& fn) const
360 {
361 for (const Breakpoint& it : d->bps) {
362 if (fn == it.filename()) {
363 return it;
364 }
365 }
366
367 return {};
368 }
369
370 bool PythonDebugger::toggleBreakpoint(int line, const QString& fn)
371 {
372 for (Breakpoint& it : d->bps) {
373 if (fn == it.filename()) {
374 if (it.checkLine(line)) {
375 it.removeLine(line);
376 return false;
377 }
378 else {
379 it.addLine(line);
380 return true;
381 }
382 }
383 }
384
385 Breakpoint bp;
386 bp.setFilename(fn);
387 bp.addLine(line);
388 d->bps.push_back(bp);
389 return true;
390 }
391
392 void PythonDebugger::runFile(const QString& fn)
393 {
394 try {
395 RunningState state(d->running);
396 QByteArray pxFileName = fn.toUtf8();
397 #ifdef FC_OS_WIN32
398 Base::FileInfo fi((const char*)pxFileName);
399 FILE* fp = _wfopen(fi.toStdWString().c_str(), L"r");
400 #else
401 FILE* fp = fopen((const char*)pxFileName, "r");
402 #endif
403 if (!fp) {
404 return;
405 }
406
407 Base::PyGILStateLocker locker;
408 PyObject *module, *dict;
409 module = PyImport_AddModule("__main__");
410 dict = PyModule_GetDict(module);
411 dict = PyDict_Copy(dict);
412 if (!PyDict_GetItemString(dict, "__file__")) {
413 PyObject* pyObj = PyUnicode_FromString((const char*)pxFileName);
414 if (!pyObj) {
415 fclose(fp);
416 return;
417 }
418 if (PyDict_SetItemString(dict, "__file__", pyObj) < 0) {
419 Py_DECREF(pyObj);
420 fclose(fp);
421 return;
422 }
423 Py_DECREF(pyObj);
424 }
425
426 PyObject* result = PyRun_File(fp, (const char*)pxFileName, Py_file_input, dict, dict);
427 fclose(fp);
428 Py_DECREF(dict);
429
430 if (!result) {
431 PyErr_Print();
432 }
433 else {
434 Py_DECREF(result);
435 }
436 }
437 catch (const Base::PyException& /* e*/) {
438 // PySys_WriteStderr("Exception: %s\n", e.what());
439 }
440 catch (...) {
441 Base::Console().warning("Unknown exception thrown during macro debugging\n");
442 }
443 }
444
445 bool PythonDebugger::isRunning() const
446 {
447 return d->running;
448 }
449
450 bool PythonDebugger::start()
451 {
452 if (d->init) {
453 return false;
454 }
455 d->init = true;
456 d->trystop = false;
457 Base::PyGILStateLocker lock;
458 d->out_o = PySys_GetObject("stdout");
459 d->err_o = PySys_GetObject("stderr");
460 d->exc_o = PySys_GetObject("excepthook");
461
462 PySys_SetObject("stdout", d->out_n);
463 PySys_SetObject("stderr", d->err_n);
464 PySys_SetObject("excepthook", d->exc_o);
465
466 PyEval_SetTrace(tracer_callback, d->pydbg);
467 return true;
468 }
469
470 bool PythonDebugger::stop()
471 {
472 if (!d->init) {
473 return false;
474 }
475 Base::PyGILStateLocker lock;
476 PyEval_SetTrace(nullptr, nullptr);
477 PySys_SetObject("stdout", d->out_o);
478 PySys_SetObject("stderr", d->err_o);
479 PySys_SetObject("excepthook", d->exc_o);
480 d->init = false;
481 return true;
482 }
483
484 void PythonDebugger::tryStop()
485 {
486 d->trystop = true;
487 Q_EMIT signalNextStep();
488 }
489
490 void PythonDebugger::stepOver()
491 {
492 Q_EMIT signalNextStep();
493 }
494
495 void PythonDebugger::stepInto()
496 {
497 Q_EMIT signalNextStep();
498 }
499
500 void PythonDebugger::stepRun()
501 {
502 Q_EMIT signalNextStep();
503 }
504
505 void PythonDebugger::showDebugMarker(const QString& fn, int line)
506 {
507 PythonEditorView* edit = nullptr;
508 QList<QWidget*> mdis = getMainWindow()->windows();
509 for (const auto& mdi : mdis) {
510 edit = qobject_cast<PythonEditorView*>(mdi);
511 if (edit && edit->fileName() == fn) {
512 break;
513 }
514 }
515
516 if (!edit) {
517 auto editor = new PythonEditor();
518 editor->setWindowIcon(Gui::BitmapFactory().iconFromTheme("applications-python"));
519 edit = new PythonEditorView(editor, getMainWindow());
520 edit->open(fn);
521 edit->resize(400, 300);
522 getMainWindow()->addWindow(edit);
523 }
524
525 getMainWindow()->setActiveWindow(edit);
526 edit->showDebugMarker(line);
527 }
528
529 void PythonDebugger::hideDebugMarker(const QString& fn)
530 {
531 PythonEditorView* edit = nullptr;
532 QList<QWidget*> mdis = getMainWindow()->windows();
533 for (const auto& mdi : mdis) {
534 edit = qobject_cast<PythonEditorView*>(mdi);
535 if (edit && edit->fileName() == fn) {
536 edit->hideDebugMarker();
537 break;
538 }
539 }
540 }
541
542
543 // http://www.koders.com/cpp/fidBA6CD8A0FE5F41F1464D74733D9A711DA257D20B.aspx?s=PyEval_SetTrace
544 // http://code.google.com/p/idapython/source/browse/trunk/python.cpp
545 // http://www.koders.com/cpp/fid191F7B13CF73133935A7A2E18B7BF43ACC6D1784.aspx?s=PyEval_SetTrace
546
547 int PythonDebugger::tracer_callback(PyObject* obj, PyFrameObject* frame, int what, PyObject* /*arg*/)
548 {
549 auto self = static_cast<PythonDebuggerPy*>(obj);
550 PythonDebugger* dbg = self->dbg;
551 if (dbg->d->trystop) {
552 PyErr_SetInterrupt();
553 }
554 QCoreApplication::processEvents();
555 PyCodeObject* code = PyFrame_GetCode(frame);
556 QString file = QString::fromUtf8(PyUnicode_AsUTF8(code->co_filename));
557 Py_DECREF(code);
558 switch (what) {
559 case PyTrace_CALL:
560 self->depth++;
561 return 0;
562 case PyTrace_RETURN:
563 if (self->depth > 0) {
564 self->depth--;
565 }
566 return 0;
567 case PyTrace_LINE: {
568 PyCodeObject* f_code = PyFrame_GetCode(frame);
569 int f_lasti = PyFrame_GetLineNumber(frame);
570 int line = PyCode_Addr2Line(f_code, f_lasti);
571 Py_DECREF(f_code);
572
573 if (!dbg->d->trystop) {
574 Breakpoint bp = dbg->getBreakpoint(file);
575 if (bp.checkLine(line)) {
576 dbg->showDebugMarker(file, line);
577 QEventLoop loop;
578 QObject::connect(dbg, &PythonDebugger::signalNextStep, &loop, &QEventLoop::quit);
579 loop.exec();
580 dbg->hideDebugMarker(file);
581 }
582 }
583 return 0;
584 }
585 case PyTrace_EXCEPTION:
586 return 0;
587 case PyTrace_C_CALL:
588 return 0;
589 case PyTrace_C_EXCEPTION:
590 return 0;
591 case PyTrace_C_RETURN:
592 return 0;
593 default:
594 /* ignore PyTrace_EXCEPTION */
595 break;
596 }
597 return 0;
598 }
599
600 #include "moc_PythonDebugger.cpp"