| 1 |
// SPDX-License-Identifier: LGPL-2.1-or-later |
| 2 |
|
| 3 |
/*************************************************************************** |
| 4 |
* Copyright (c) 2002 Jürgen Riegel <[email protected]> * |
| 5 |
* * |
| 6 |
* This file is part of the FreeCAD CAx development system. * |
| 7 |
* * |
| 8 |
* This program is free software; you can redistribute it and/or modify * |
| 9 |
* it under the terms of the GNU Library General Public License (LGPL) * |
| 10 |
* as published by the Free Software Foundation; either version 2 of * |
| 11 |
* the License, or (at your option) any later version. * |
| 12 |
* for detail see the LICENCE text file. * |
| 13 |
* * |
| 14 |
* FreeCAD is distributed in the hope that it will be useful, * |
| 15 |
* but WITHOUT ANY WARRANTY; without even the implied warranty of * |
| 16 |
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * |
| 17 |
* GNU Library General Public License for more details. * |
| 18 |
* * |
| 19 |
* You should have received a copy of the GNU Library General Public * |
| 20 |
* License along with FreeCAD; if not, write to the Free Software * |
| 21 |
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * |
| 22 |
* USA * |
| 23 |
* * |
| 24 |
***************************************************************************/ |
| 25 |
|
| 26 |
#include <sstream> |
| 27 |
#include <boost/regex.hpp> |
| 28 |
|
| 29 |
#include <FCConfig.h> |
| 30 |
|
| 31 |
#include "Interpreter.h" |
| 32 |
#include "Console.h" |
| 33 |
#include "ExceptionFactory.h" |
| 34 |
#include "FileInfo.h" |
| 35 |
#include "PyObjectBase.h" |
| 36 |
#include "PyTools.h" |
| 37 |
#include "Stream.h" |
| 38 |
|
| 39 |
|
| 40 |
char format2[1024]; // Warning! Can't go over 512 characters!!! |
| 41 |
unsigned int format2_len = 1024; |
| 42 |
|
| 43 |
using namespace Base; |
| 44 |
|
| 45 |
PyException::PyException(const Py::Object& obj) |
| 46 |
{ |
| 47 |
setMessage(obj.as_string()); |
| 48 |
// WARNING: we are assuming that python type object will never be |
| 49 |
// destroyed, so we don't keep reference here to save book-keeping in |
| 50 |
// our copy constructor and destructor |
| 51 |
// NOLINTBEGIN |
| 52 |
_exceptionType = reinterpret_cast<PyObject*>(obj.ptr()->ob_type); |
| 53 |
_errorType = obj.ptr()->ob_type->tp_name; |
| 54 |
// NOLINTEND |
| 55 |
} |
| 56 |
|
| 57 |
PyException::PyException() |
| 58 |
{ |
| 59 |
PP_Fetch_Error_Text(); /* fetch (and clear) exception */ |
| 60 |
|
| 61 |
setPyObject(PP_PyDict_Object); |
| 62 |
|
| 63 |
std::string prefix = PP_last_error_type; /* exception name text */ |
| 64 |
std::string error = PP_last_error_info; /* exception data text */ |
| 65 |
|
| 66 |
setMessage(error); |
| 67 |
_errorType = prefix; |
| 68 |
|
| 69 |
// NOLINTNEXTLINE |
| 70 |
_exceptionType = PP_last_exception_type; |
| 71 |
|
| 72 |
if (PP_last_exception_type) { |
| 73 |
// WARNING: we are assuming that python type object will never be |
| 74 |
// destroyed, so we don't keep reference here to save book-keeping in |
| 75 |
// our copy constructor and destructor |
| 76 |
Py_DECREF(PP_last_exception_type); |
| 77 |
PP_last_exception_type = nullptr; |
| 78 |
} |
| 79 |
|
| 80 |
_stackTrace = PP_last_error_trace; /* exception traceback text */ |
| 81 |
|
| 82 |
// This should be done in the constructor because when doing |
| 83 |
// in the destructor it's not always clear when it is called |
| 84 |
// and thus may clear a Python exception when it should not. |
| 85 |
PyGILStateLocker locker; |
| 86 |
PyErr_Clear(); // must be called to keep Python interpreter in a valid state (Werner) |
| 87 |
} |
| 88 |
|
| 89 |
PyException::~PyException() noexcept = default; |
| 90 |
|
| 91 |
void PyException::throwException() |
| 92 |
{ |
| 93 |
PyException myexcp; |
| 94 |
myexcp.reportException(); |
| 95 |
myexcp.raiseException(); |
| 96 |
} |
| 97 |
|
| 98 |
void PyException::raiseException() |
| 99 |
{ |
| 100 |
PyGILStateLocker locker; |
| 101 |
if (PP_PyDict_Object) { |
| 102 |
// delete the Python dict upon destruction of edict |
| 103 |
Py::Dict edict(PP_PyDict_Object, true); |
| 104 |
PP_PyDict_Object = nullptr; |
| 105 |
|
| 106 |
std::string exceptionname; |
| 107 |
if (_exceptionType == Base::PyExc_FC_FreeCADAbort) { |
| 108 |
edict.setItem("sclassname", Py::String(typeid(AbortException).name())); |
| 109 |
} |
| 110 |
if (getReported()) { |
| 111 |
edict.setItem("breported", Py::True()); |
| 112 |
} |
| 113 |
Base::ExceptionFactory::Instance().raiseException(edict.ptr()); |
| 114 |
} |
| 115 |
|
| 116 |
PyExceptionData data {_exceptionType, getMessage(), getReported()}; |
| 117 |
Base::ExceptionFactory::Instance().raiseExceptionByType(data); |
| 118 |
|
| 119 |
// Fallback |
| 120 |
throw *this; |
| 121 |
} |
| 122 |
|
| 123 |
void PyException::reportException() const |
| 124 |
{ |
| 125 |
if (!getReported()) { |
| 126 |
setReported(true); |
| 127 |
// set sys.last_vars to make post-mortem debugging work |
| 128 |
PyGILStateLocker locker; |
| 129 |
PySys_SetObject("last_traceback", PP_last_traceback); |
| 130 |
Console().developerError( |
| 131 |
"pyException", |
| 132 |
"%s%s: %s\n", |
| 133 |
_stackTrace.c_str(), |
| 134 |
_errorType.c_str(), |
| 135 |
what() |
| 136 |
); |
| 137 |
} |
| 138 |
} |
| 139 |
|
| 140 |
void PyException::setPyException() const |
| 141 |
{ |
| 142 |
std::stringstream str; |
| 143 |
str << getStackTrace() << getErrorType() << ": " << what(); |
| 144 |
PyErr_SetString(getPyExceptionType(), str.str().c_str()); |
| 145 |
} |
| 146 |
|
| 147 |
// --------------------------------------------------------- |
| 148 |
|
| 149 |
SystemExitException::SystemExitException() |
| 150 |
{ |
| 151 |
// Set exception message and code based upon the python sys.exit() code and/or message |
| 152 |
// based upon the following sys.exit() call semantics. |
| 153 |
// |
| 154 |
// Invocation | _exitCode | _sErrMsg |
| 155 |
// ---------------- + --------- + -------- |
| 156 |
// sys.exit(int#) | int# | "System Exit" |
| 157 |
// sys.exit(string) | 1 | string |
| 158 |
// sys.exit() | 1 | "System Exit" |
| 159 |
|
| 160 |
long int errCode = 1; |
| 161 |
std::string errMsg = "System exit"; |
| 162 |
PyObject* type {}; |
| 163 |
PyObject* value {}; |
| 164 |
PyObject* traceback {}; |
| 165 |
PyObject* code {}; |
| 166 |
|
| 167 |
PyGILStateLocker locker; |
| 168 |
PyErr_Fetch(&type, &value, &traceback); |
| 169 |
PyErr_NormalizeException(&type, &value, &traceback); |
| 170 |
|
| 171 |
if (value) { |
| 172 |
code = PyObject_GetAttrString(value, "code"); |
| 173 |
if (code && value != Py_None) { |
| 174 |
Py_DECREF(value); |
| 175 |
value = code; |
| 176 |
} |
| 177 |
|
| 178 |
if (PyLong_Check(value)) { |
| 179 |
errCode = PyLong_AsLong(value); |
| 180 |
} |
| 181 |
else { |
| 182 |
const char* str = PyUnicode_AsUTF8(value); |
| 183 |
if (str) { |
| 184 |
errMsg = errMsg + ": " + str; |
| 185 |
} |
| 186 |
} |
| 187 |
} |
| 188 |
|
| 189 |
setMessage(errMsg); |
| 190 |
_exitCode = errCode; |
| 191 |
} |
| 192 |
|
| 193 |
// --------------------------------------------------------- |
| 194 |
|
| 195 |
// Fixes #0000831: python print causes File descriptor error on windows |
| 196 |
// NOLINTNEXTLINE |
| 197 |
class PythonStdOutput: public Py::PythonExtension<PythonStdOutput> |
| 198 |
{ |
| 199 |
public: |
| 200 |
static void init_type() |
| 201 |
{ |
| 202 |
behaviors().name("PythonStdOutput"); |
| 203 |
behaviors().doc("Python standard output"); |
| 204 |
add_varargs_method("write", &PythonStdOutput::write, "write()"); |
| 205 |
add_varargs_method("flush", &PythonStdOutput::flush, "flush()"); |
| 206 |
} |
| 207 |
|
| 208 |
PythonStdOutput() = default; |
| 209 |
~PythonStdOutput() override = default; |
| 210 |
|
| 211 |
Py::Object write(const Py::Tuple&) |
| 212 |
{ |
| 213 |
return Py::None(); |
| 214 |
} |
| 215 |
Py::Object flush(const Py::Tuple&) |
| 216 |
{ |
| 217 |
return Py::None(); |
| 218 |
} |
| 219 |
}; |
| 220 |
|
| 221 |
// --------------------------------------------------------- |
| 222 |
|
| 223 |
InterpreterSingleton::InterpreterSingleton() |
| 224 |
{ |
| 225 |
this->_global = nullptr; |
| 226 |
} |
| 227 |
|
| 228 |
InterpreterSingleton::~InterpreterSingleton() = default; |
| 229 |
|
| 230 |
|
| 231 |
std::string InterpreterSingleton::runString(const char* sCmd) |
| 232 |
{ |
| 233 |
PyObject* module {}; |
| 234 |
PyObject* dict {}; |
| 235 |
PyObject* presult {}; |
| 236 |
|
| 237 |
PyGILStateLocker locker; |
| 238 |
module = PP_Load_Module("__main__"); /* get module, init python */ |
| 239 |
if (!module) { |
| 240 |
throw PyException(); /* not incref'd */ |
| 241 |
} |
| 242 |
dict = PyModule_GetDict(module); /* get dict namespace */ |
| 243 |
if (!dict) { |
| 244 |
throw PyException(); /* not incref'd */ |
| 245 |
} |
| 246 |
|
| 247 |
|
| 248 |
presult = PyRun_String(sCmd, Py_file_input, dict, dict); /* eval direct */ |
| 249 |
if (!presult) { |
| 250 |
if (PyErr_ExceptionMatches(PyExc_SystemExit)) { |
| 251 |
throw SystemExitException(); |
| 252 |
} |
| 253 |
|
| 254 |
PyException::throwException(); |
| 255 |
return {}; // just to quieten code analyzers |
| 256 |
} |
| 257 |
|
| 258 |
PyObject* repr = PyObject_Repr(presult); |
| 259 |
Py_DECREF(presult); |
| 260 |
if (repr) { |
| 261 |
std::string ret(PyUnicode_AsUTF8(repr)); |
| 262 |
Py_DECREF(repr); |
| 263 |
return ret; |
| 264 |
} |
| 265 |
|
| 266 |
PyErr_Clear(); |
| 267 |
return {}; |
| 268 |
} |
| 269 |
|
| 270 |
/** runStringWithKey(psCmd, key, key_initial_value) |
| 271 |
* psCmd is python script to run |
| 272 |
* key is the name of a python string variable the script will have read/write |
| 273 |
* access to during script execution. It will be our return value. |
| 274 |
* key_initial_value is the initial value c++ will set before calling the script |
| 275 |
* If the script runs successfully it will be able to change the value of key as |
| 276 |
* the return value, but if there is a runtime error key will not be changed even |
| 277 |
* if the error occurs after changing it inside the script. |
| 278 |
*/ |
| 279 |
|
| 280 |
std::string InterpreterSingleton::runStringWithKey( |
| 281 |
const char* psCmd, |
| 282 |
const char* key, |
| 283 |
const char* key_initial_value |
| 284 |
) |
| 285 |
{ |
| 286 |
PyGILStateLocker locker; |
| 287 |
Py::Module module("__main__"); |
| 288 |
Py::Dict globalDictionary = module.getDict(); |
| 289 |
Py::Dict localDictionary; |
| 290 |
Py::String initial_value(key_initial_value); |
| 291 |
localDictionary.setItem(key, initial_value); |
| 292 |
|
| 293 |
PyObject* presult |
| 294 |
= PyRun_String(psCmd, Py_file_input, globalDictionary.ptr(), localDictionary.ptr()); |
| 295 |
if (!presult) { |
| 296 |
if (PyErr_ExceptionMatches(PyExc_SystemExit)) { |
| 297 |
throw SystemExitException(); |
| 298 |
} |
| 299 |
|
| 300 |
PyException::throwException(); |
| 301 |
return {}; // just to quieten code analyzers |
| 302 |
} |
| 303 |
Py_DECREF(presult); |
| 304 |
|
| 305 |
Py::Object key_return_value = localDictionary.getItem(key); |
| 306 |
if (!key_return_value.isString()) { |
| 307 |
key_return_value = key_return_value.str(); // NOLINT |
| 308 |
} |
| 309 |
|
| 310 |
Py::Bytes str = Py::String(key_return_value).encode("utf-8"); |
| 311 |
std::string result = static_cast<std::string>(str); |
| 312 |
return result; |
| 313 |
} |
| 314 |
|
| 315 |
Py::Object InterpreterSingleton::runStringObject(const char* sCmd) |
| 316 |
{ |
| 317 |
PyObject* module {}; |
| 318 |
PyObject* dict {}; |
| 319 |
PyObject* presult {}; |
| 320 |
|
| 321 |
PyGILStateLocker locker; |
| 322 |
module = PP_Load_Module("__main__"); /* get module, init python */ |
| 323 |
if (!module) { |
| 324 |
throw PyException(); /* not incref'd */ |
| 325 |
} |
| 326 |
dict = PyModule_GetDict(module); /* get dict namespace */ |
| 327 |
if (!dict) { |
| 328 |
throw PyException(); /* not incref'd */ |
| 329 |
} |
| 330 |
|
| 331 |
|
| 332 |
presult = PyRun_String(sCmd, Py_eval_input, dict, dict); /* eval direct */ |
| 333 |
if (!presult) { |
| 334 |
if (PyErr_ExceptionMatches(PyExc_SystemExit)) { |
| 335 |
throw SystemExitException(); |
| 336 |
} |
| 337 |
|
| 338 |
throw PyException(); |
| 339 |
} |
| 340 |
|
| 341 |
return Py::asObject(presult); |
| 342 |
} |
| 343 |
|
| 344 |
void InterpreterSingleton::systemExit() |
| 345 |
{ |
| 346 |
/* This code is taken from the original Python code */ |
| 347 |
PyObject* exception {}; |
| 348 |
PyObject* value {}; |
| 349 |
PyObject* tb {}; |
| 350 |
int exitcode = 0; |
| 351 |
|
| 352 |
PyErr_Fetch(&exception, &value, &tb); |
| 353 |
fflush(stdout); |
| 354 |
if (!value || value == Py_None) { |
| 355 |
goto done; // NOLINT |
| 356 |
} |
| 357 |
if (PyExceptionInstance_Check(value)) { |
| 358 |
/* The error code should be in the `code' attribute. */ |
| 359 |
PyObject* code = PyObject_GetAttrString(value, "code"); |
| 360 |
if (code) { |
| 361 |
Py_DECREF(value); |
| 362 |
value = code; |
| 363 |
if (value == Py_None) { |
| 364 |
goto done; // NOLINT |
| 365 |
} |
| 366 |
} |
| 367 |
/* If we failed to dig out the 'code' attribute, |
| 368 |
just let the else clause below print the error. */ |
| 369 |
} |
| 370 |
if (PyLong_Check(value)) { |
| 371 |
exitcode = (int)PyLong_AsLong(value); |
| 372 |
} |
| 373 |
else { |
| 374 |
PyObject_Print(value, stderr, Py_PRINT_RAW); |
| 375 |
PySys_WriteStderr("\n"); |
| 376 |
exitcode = 1; |
| 377 |
} |
| 378 |
done: |
| 379 |
/* Restore and clear the exception info, in order to properly decref |
| 380 |
* the exception, value, and traceback. If we just exit instead, |
| 381 |
* these leak, which confuses PYTHONDUMPREFS output, and may prevent |
| 382 |
* some finalizers from running. |
| 383 |
*/ |
| 384 |
PyErr_Restore(exception, value, tb); |
| 385 |
PyErr_Clear(); |
| 386 |
Py_Exit(exitcode); |
| 387 |
/* NOTREACHED */ |
| 388 |
} |
| 389 |
|
| 390 |
void InterpreterSingleton::runInteractiveString(const char* sCmd) |
| 391 |
{ |
| 392 |
PyObject* module {}; |
| 393 |
PyObject* dict {}; |
| 394 |
PyObject* presult {}; |
| 395 |
|
| 396 |
PyGILStateLocker locker; |
| 397 |
module = PP_Load_Module("__main__"); /* get module, init python */ |
| 398 |
if (!module) { |
| 399 |
throw PyException(); /* not incref'd */ |
| 400 |
} |
| 401 |
dict = PyModule_GetDict(module); /* get dict namespace */ |
| 402 |
if (!dict) { |
| 403 |
throw PyException(); /* not incref'd */ |
| 404 |
} |
| 405 |
|
| 406 |
presult = PyRun_String(sCmd, Py_single_input, dict, dict); /* eval direct */ |
| 407 |
if (!presult) { |
| 408 |
if (PyErr_ExceptionMatches(PyExc_SystemExit)) { |
| 409 |
throw SystemExitException(); |
| 410 |
} |
| 411 |
/* get latest python exception information */ |
| 412 |
/* and print the error to the error output */ |
| 413 |
PyObject* errobj {}; |
| 414 |
PyObject* errdata {}; |
| 415 |
PyObject* errtraceback {}; |
| 416 |
PyErr_Fetch(&errobj, &errdata, &errtraceback); |
| 417 |
|
| 418 |
RuntimeError exc(""); // do not use PyException since this clears the error indicator |
| 419 |
if (errdata) { |
| 420 |
if (PyUnicode_Check(errdata)) { |
| 421 |
exc.setMessage(PyUnicode_AsUTF8(errdata)); |
| 422 |
} |
| 423 |
} |
| 424 |
PyErr_Restore(errobj, errdata, errtraceback); |
| 425 |
if (PyErr_Occurred()) { |
| 426 |
PyErr_Print(); |
| 427 |
} |
| 428 |
throw exc; |
| 429 |
} |
| 430 |
|
| 431 |
Py_DECREF(presult); |
| 432 |
} |
| 433 |
|
| 434 |
void InterpreterSingleton::runFile(const char* pxFileName, bool local) |
| 435 |
{ |
| 436 |
#ifdef FC_OS_WIN32 |
| 437 |
FileInfo fi(pxFileName); |
| 438 |
FILE* fp = _wfopen(fi.toStdWString().c_str(), L"r"); |
| 439 |
#else |
| 440 |
FILE* fp = fopen(pxFileName, "r"); |
| 441 |
#endif |
| 442 |
if (!fp) { |
| 443 |
throw FileException("Unknown file", pxFileName); |
| 444 |
} |
| 445 |
|
| 446 |
PyGILStateLocker locker; |
| 447 |
PyObject* module {}; |
| 448 |
PyObject* dict {}; |
| 449 |
module = PyImport_AddModule("__main__"); |
| 450 |
dict = PyModule_GetDict(module); |
| 451 |
if (local) { |
| 452 |
dict = PyDict_Copy(dict); |
| 453 |
} |
| 454 |
else { |
| 455 |
Py_INCREF(dict); // avoid to further distinguish between local and global dict |
| 456 |
} |
| 457 |
|
| 458 |
if (!PyDict_GetItemString(dict, "__file__")) { |
| 459 |
PyObject* pyObj = PyUnicode_FromString(pxFileName); |
| 460 |
if (!pyObj) { |
| 461 |
fclose(fp); |
| 462 |
Py_DECREF(dict); |
| 463 |
return; |
| 464 |
} |
| 465 |
if (PyDict_SetItemString(dict, "__file__", pyObj) < 0) { |
| 466 |
Py_DECREF(pyObj); |
| 467 |
fclose(fp); |
| 468 |
Py_DECREF(dict); |
| 469 |
return; |
| 470 |
} |
| 471 |
Py_DECREF(pyObj); |
| 472 |
} |
| 473 |
|
| 474 |
PyObject* result = PyRun_File(fp, pxFileName, Py_file_input, dict, dict); |
| 475 |
fclose(fp); |
| 476 |
Py_DECREF(dict); |
| 477 |
|
| 478 |
if (!result) { |
| 479 |
if (PyErr_ExceptionMatches(PyExc_SystemExit)) { |
| 480 |
throw SystemExitException(); |
| 481 |
} |
| 482 |
throw PyException(); |
| 483 |
} |
| 484 |
Py_DECREF(result); |
| 485 |
} |
| 486 |
|
| 487 |
bool InterpreterSingleton::loadModule(const char* psModName) |
| 488 |
{ |
| 489 |
PyObject* module {}; |
| 490 |
|
| 491 |
PyGILStateLocker locker; |
| 492 |
module = PP_Load_Module(psModName); |
| 493 |
|
| 494 |
if (!module) { |
| 495 |
if (PyErr_ExceptionMatches(PyExc_SystemExit)) { |
| 496 |
throw SystemExitException(); |
| 497 |
} |
| 498 |
|
| 499 |
throw PyException(); |
| 500 |
} |
| 501 |
|
| 502 |
return true; |
| 503 |
} |
| 504 |
|
| 505 |
PyObject* InterpreterSingleton::addModule(Py::ExtensionModuleBase* mod) |
| 506 |
{ |
| 507 |
_modules.push_back(mod); |
| 508 |
return mod->module().ptr(); |
| 509 |
} |
| 510 |
|
| 511 |
void InterpreterSingleton::cleanupModules() |
| 512 |
{ |
| 513 |
// This is only needed to make the address sanitizer happy |
| 514 |
#if defined(__has_feature) |
| 515 |
# if __has_feature(address_sanitizer) |
| 516 |
for (auto it : _modules) { |
| 517 |
delete it; |
| 518 |
} |
| 519 |
_modules.clear(); |
| 520 |
# endif |
| 521 |
#endif |
| 522 |
} |
| 523 |
|
| 524 |
void InterpreterSingleton::addType(PyTypeObject* Type, PyObject* Module, const char* Name) |
| 525 |
{ |
| 526 |
// NOTE: To finish the initialization of our own type objects we must |
| 527 |
// call PyType_Ready, otherwise we run into a segmentation fault, later on. |
| 528 |
// This function is responsible for adding inherited slots from a type's base class. |
| 529 |
if (PyType_Ready(Type) < 0) { |
| 530 |
return; |
| 531 |
} |
| 532 |
PyModule_AddObject(Module, Name, Base::getTypeAsObject(Type)); |
| 533 |
} |
| 534 |
|
| 535 |
void InterpreterSingleton::addPythonPath(const char* Path) |
| 536 |
{ |
| 537 |
PyGILStateLocker locker; |
| 538 |
Py::List list(PySys_GetObject("path")); |
| 539 |
list.append(Py::String(Path)); |
| 540 |
} |
| 541 |
|
| 542 |
std::string InterpreterSingleton::getPythonPath() |
| 543 |
{ |
| 544 |
// Construct something that looks like the output of the now-deprecated Py_GetPath |
| 545 |
PyGILStateLocker lock; |
| 546 |
PyObject* path = PySys_GetObject("path"); |
| 547 |
std::string result; |
| 548 |
const char* separator = ":"; // Use ":" on Unix-like systems, ";" on Windows |
| 549 |
#ifdef FC_OS_WIN32 |
| 550 |
separator = ";"; |
| 551 |
#endif |
| 552 |
Py_ssize_t length = PyList_Size(path); |
| 553 |
for (Py_ssize_t i = 0; i < length; ++i) { |
| 554 |
PyObject* item = PyList_GetItem(path, i); // Borrowed reference |
| 555 |
if (!item) { |
| 556 |
throw Base::RuntimeError("Failed to retrieve item from path"); |
| 557 |
} |
| 558 |
const char* item_str = PyUnicode_AsUTF8(item); |
| 559 |
if (!item_str) { |
| 560 |
throw Base::RuntimeError("Failed to convert path item to UTF-8 string"); |
| 561 |
} |
| 562 |
if (!result.empty()) { |
| 563 |
result += separator; |
| 564 |
} |
| 565 |
result += item_str; |
| 566 |
} |
| 567 |
return result; |
| 568 |
} |
| 569 |
|
| 570 |
#if PY_VERSION_HEX < 0x030b0000 |
| 571 |
std::string InterpreterSingleton::init(int argc, char* argv[]) |
| 572 |
{ |
| 573 |
if (!Py_IsInitialized()) { |
| 574 |
Py_SetProgramName(Py_DecodeLocale(argv[0], nullptr)); |
| 575 |
// There is a serious bug in VS from 2010 until 2013 where the file descriptor for stdin, |
| 576 |
// stdout or stderr returns a valid value for GUI applications (i.e. subsystem = Windows) |
| 577 |
// where it shouldn't. This causes Python to fail during initialization. A workaround is to |
| 578 |
// use freopen on stdin, stdout and stderr. See the class Redirection inside main() |
| 579 |
// https://bugs.python.org/issue17797#msg197474 |
| 580 |
// |
| 581 |
Py_Initialize(); |
| 582 |
const char* virtualenv = getenv("VIRTUAL_ENV"); |
| 583 |
if (virtualenv) { |
| 584 |
PyRun_SimpleString( |
| 585 |
"# Check for virtualenv, and activate if present.\n" |
| 586 |
"# See " |
| 587 |
"https://virtualenv.pypa.io/en/latest/" |
| 588 |
"#using-virtualenv-without-bin-python\n" |
| 589 |
"import os\n" |
| 590 |
"import sys\n" |
| 591 |
"base_path = os.getenv(\"VIRTUAL_ENV\")\n" |
| 592 |
"if not base_path is None:\n" |
| 593 |
" activate_this = os.path.join(base_path, \"bin\", \"activate_this.py\")\n" |
| 594 |
" exec(open(activate_this).read(), {'__file__':activate_this})\n" |
| 595 |
); |
| 596 |
} |
| 597 |
|
| 598 |
size_t size = argc; |
| 599 |
static std::vector<wchar_t*> _argv(size); |
| 600 |
for (int i = 0; i < argc; i++) { |
| 601 |
_argv[i] = Py_DecodeLocale(argv[i], nullptr); |
| 602 |
} |
| 603 |
PySys_SetArgv(argc, _argv.data()); |
| 604 |
PythonStdOutput::init_type(); |
| 605 |
this->_global = PyEval_SaveThread(); |
| 606 |
} |
| 607 |
|
| 608 |
PyGILStateLocker lock; |
| 609 |
return Py_EncodeLocale(Py_GetPath(), nullptr); |
| 610 |
} |
| 611 |
#else |
| 612 |
namespace |
| 613 |
{ |
| 614 |
void initInterpreter(int argc, char* argv[]) |
| 615 |
{ |
| 616 |
PyStatus status; |
| 617 |
PyConfig config; |
| 618 |
PyConfig_InitIsolatedConfig(&config); |
| 619 |
config.isolated = 0; |
| 620 |
config.user_site_directory = 1; |
| 621 |
|
| 622 |
status = PyConfig_SetBytesArgv(&config, argc, argv); |
| 623 |
if (PyStatus_Exception(status)) { |
| 624 |
throw Base::RuntimeError("Failed to set config"); |
| 625 |
} |
| 626 |
|
| 627 |
status = Py_InitializeFromConfig(&config); |
| 628 |
if (PyStatus_Exception(status)) { |
| 629 |
throw Base::RuntimeError("Failed to init from config"); |
| 630 |
} |
| 631 |
|
| 632 |
// If FreeCAD was run from within a Python virtual environment, ensure that the site-packages |
| 633 |
// directory from that environment is used. |
| 634 |
const char* virtualenv = getenv("VIRTUAL_ENV"); |
| 635 |
if (virtualenv) { |
| 636 |
std::wstringstream ss; |
| 637 |
PyConfig_Read(&config); |
| 638 |
ss << virtualenv << L"/lib/python" << PY_MAJOR_VERSION << "." << PY_MINOR_VERSION |
| 639 |
<< "/site-packages"; |
| 640 |
PyObject* venvLocation = PyUnicode_FromWideChar(ss.str().c_str(), ss.str().size()); |
| 641 |
PyObject* path = PySys_GetObject("path"); |
| 642 |
PyList_Append(path, venvLocation); |
| 643 |
} |
| 644 |
|
| 645 |
PyConfig_Clear(&config); |
| 646 |
|
| 647 |
Py_Initialize(); |
| 648 |
} |
| 649 |
} // namespace |
| 650 |
std::string InterpreterSingleton::init(int argc, char* argv[]) |
| 651 |
{ |
| 652 |
try { |
| 653 |
if (!Py_IsInitialized()) { |
| 654 |
initInterpreter(argc, argv); |
| 655 |
|
| 656 |
PythonStdOutput::init_type(); |
| 657 |
this->_global = PyEval_SaveThread(); |
| 658 |
} |
| 659 |
return getPythonPath(); |
| 660 |
} |
| 661 |
catch (const Exception& e) { |
| 662 |
e.reportException(); |
| 663 |
throw; |
| 664 |
} |
| 665 |
} |
| 666 |
#endif |
| 667 |
|
| 668 |
void InterpreterSingleton::replaceStdOutput() |
| 669 |
{ |
| 670 |
PyGILStateLocker locker; |
| 671 |
PythonStdOutput* out = new PythonStdOutput(); |
| 672 |
PySys_SetObject("stdout", out); |
| 673 |
PySys_SetObject("stderr", out); |
| 674 |
} |
| 675 |
|
| 676 |
int InterpreterSingleton::cleanup(void (*func)()) |
| 677 |
{ |
| 678 |
return Py_AtExit(func); |
| 679 |
} |
| 680 |
|
| 681 |
void InterpreterSingleton::finalize() |
| 682 |
{ |
| 683 |
try { |
| 684 |
PyEval_RestoreThread(this->_global); |
| 685 |
cleanupModules(); |
| 686 |
Py_Finalize(); |
| 687 |
} |
| 688 |
catch (...) { |
| 689 |
} |
| 690 |
} |
| 691 |
|
| 692 |
void InterpreterSingleton::runStringArg(const char* psCom, ...) |
| 693 |
{ |
| 694 |
// va stuff |
| 695 |
va_list namelessVars; |
| 696 |
va_start(namelessVars, psCom); // Get the "..." vars |
| 697 |
int len = vsnprintf(format2, format2_len, psCom, namelessVars); |
| 698 |
va_end(namelessVars); |
| 699 |
if (len == -1) { |
| 700 |
// argument too long |
| 701 |
assert(false); |
| 702 |
} |
| 703 |
|
| 704 |
runString(format2); |
| 705 |
} |
| 706 |
|
| 707 |
|
| 708 |
// Singleton: |
| 709 |
|
| 710 |
InterpreterSingleton* InterpreterSingleton::_pcSingleton = nullptr; |
| 711 |
|
| 712 |
InterpreterSingleton& InterpreterSingleton::Instance() |
| 713 |
{ |
| 714 |
// not initialized! |
| 715 |
if (!_pcSingleton) { |
| 716 |
_pcSingleton = new InterpreterSingleton(); |
| 717 |
} |
| 718 |
return *_pcSingleton; |
| 719 |
} |
| 720 |
|
| 721 |
void InterpreterSingleton::Destruct() |
| 722 |
{ |
| 723 |
// not initialized or double destruct! |
| 724 |
assert(_pcSingleton); |
| 725 |
delete _pcSingleton; |
| 726 |
_pcSingleton = nullptr; |
| 727 |
} |
| 728 |
|
| 729 |
int InterpreterSingleton::runCommandLine(const char* prompt) |
| 730 |
{ |
| 731 |
PyGILStateLocker locker; |
| 732 |
return PP_Run_Command_Line(prompt); |
| 733 |
} |
| 734 |
|
| 735 |
/** |
| 736 |
* Runs a member method of an object with no parameter and no return value |
| 737 |
* void (void). There are other methods to run with returns |
| 738 |
*/ |
| 739 |
void InterpreterSingleton::runMethodVoid(PyObject* pobject, const char* method) |
| 740 |
{ |
| 741 |
PyGILStateLocker locker; |
| 742 |
if (PP_Run_Method( |
| 743 |
pobject, // object |
| 744 |
method, // run method |
| 745 |
nullptr, // no return type |
| 746 |
nullptr, // so no return object |
| 747 |
"()" |
| 748 |
) // no arguments |
| 749 |
!= 0) { |
| 750 |
throw PyException(/*"Error running InterpreterSingleton::RunMethodVoid()"*/); |
| 751 |
} |
| 752 |
} |
| 753 |
|
| 754 |
PyObject* InterpreterSingleton::runMethodObject(PyObject* pobject, const char* method) |
| 755 |
{ |
| 756 |
PyObject* pcO {}; |
| 757 |
|
| 758 |
PyGILStateLocker locker; |
| 759 |
if (PP_Run_Method( |
| 760 |
pobject, // object |
| 761 |
method, // run method |
| 762 |
"O", // return type |
| 763 |
&pcO, // return object |
| 764 |
"()" |
| 765 |
) // no arguments |
| 766 |
!= 0) { |
| 767 |
throw PyException(); |
| 768 |
} |
| 769 |
|
| 770 |
return pcO; |
| 771 |
} |
| 772 |
|
| 773 |
void InterpreterSingleton::runMethod( |
| 774 |
PyObject* pobject, |
| 775 |
const char* method, |
| 776 |
const char* resfmt, |
| 777 |
void* cresult, /* convert to c/c++ */ |
| 778 |
const char* argfmt, |
| 779 |
... |
| 780 |
) /* convert to python */ |
| 781 |
{ |
| 782 |
PyObject* pmeth {}; |
| 783 |
PyObject* pargs {}; |
| 784 |
PyObject* presult {}; |
| 785 |
va_list argslist; /* "pobject.method(args)" */ |
| 786 |
va_start(argslist, argfmt); |
| 787 |
|
| 788 |
PyGILStateLocker locker; |
| 789 |
pmeth = PyObject_GetAttrString(pobject, method); |
| 790 |
if (!pmeth) { /* get callable object */ |
| 791 |
va_end(argslist); |
| 792 |
throw AttributeError( |
| 793 |
"Error running InterpreterSingleton::RunMethod() method not defined" |
| 794 |
); /* bound method? |
| 795 |
has self */ |
| 796 |
} |
| 797 |
|
| 798 |
pargs = Py_VaBuildValue(argfmt, argslist); /* args: c->python */ |
| 799 |
va_end(argslist); |
| 800 |
|
| 801 |
if (!pargs) { |
| 802 |
Py_DECREF(pmeth); |
| 803 |
throw TypeError("InterpreterSingleton::RunMethod() wrong arguments"); |
| 804 |
} |
| 805 |
|
| 806 |
presult = PyObject_CallObject(pmeth, pargs); /* run interpreter */ |
| 807 |
|
| 808 |
Py_DECREF(pmeth); |
| 809 |
Py_DECREF(pargs); |
| 810 |
if (PP_Convert_Result(presult, resfmt, cresult) != 0) { |
| 811 |
if (PyErr_Occurred()) { |
| 812 |
PyErr_Print(); |
| 813 |
} |
| 814 |
throw RuntimeError( |
| 815 |
"Error running InterpreterSingleton::RunMethod() exception in called method" |
| 816 |
); |
| 817 |
} |
| 818 |
} |
| 819 |
|
| 820 |
PyObject* InterpreterSingleton::getValue(const char* key, const char* result_var) |
| 821 |
{ |
| 822 |
PyObject* module {}; |
| 823 |
PyObject* dict {}; |
| 824 |
PyObject* presult {}; |
| 825 |
|
| 826 |
PyGILStateLocker locker; |
| 827 |
module = PP_Load_Module("__main__"); /* get module, init python */ |
| 828 |
if (!module) { |
| 829 |
throw PyException(); /* not incref'd */ |
| 830 |
} |
| 831 |
dict = PyModule_GetDict(module); /* get dict namespace */ |
| 832 |
if (!dict) { |
| 833 |
throw PyException(); /* not incref'd */ |
| 834 |
} |
| 835 |
|
| 836 |
|
| 837 |
presult = PyRun_String(key, Py_file_input, dict, dict); /* eval direct */ |
| 838 |
if (!presult) { |
| 839 |
throw PyException(); |
| 840 |
} |
| 841 |
Py_DECREF(presult); |
| 842 |
|
| 843 |
return PyObject_GetAttrString(module, result_var); |
| 844 |
} |
| 845 |
|
| 846 |
void InterpreterSingleton::dbgObserveFile(const char* sFileName) |
| 847 |
{ |
| 848 |
if (sFileName) { |
| 849 |
_cDebugFileName = sFileName; |
| 850 |
} |
| 851 |
else { |
| 852 |
_cDebugFileName = ""; |
| 853 |
} |
| 854 |
} |
| 855 |
|
| 856 |
|
| 857 |
std::string InterpreterSingleton::strToPython(const char* Str) |
| 858 |
{ |
| 859 |
std::string result; |
| 860 |
const char* It = Str; |
| 861 |
|
| 862 |
while (*It != '\0') { |
| 863 |
switch (*It) { |
| 864 |
case '\\': |
| 865 |
result += "\\\\"; |
| 866 |
break; |
| 867 |
case '\"': |
| 868 |
result += "\\\""; |
| 869 |
break; |
| 870 |
case '\'': |
| 871 |
result += "\\\'"; |
| 872 |
break; |
| 873 |
default: |
| 874 |
result += *It; |
| 875 |
} |
| 876 |
It++; |
| 877 |
} |
| 878 |
|
| 879 |
return result; |
| 880 |
} |
| 881 |
|
| 882 |
// -------------------------------------------------------------------- |
| 883 |
|
| 884 |
int getSWIGVersionFromModule(const std::string& module) |
| 885 |
{ |
| 886 |
static std::map<std::string, int> moduleMap; |
| 887 |
std::map<std::string, int>::iterator it = moduleMap.find(module); |
| 888 |
if (it != moduleMap.end()) { |
| 889 |
return it->second; |
| 890 |
} |
| 891 |
try { |
| 892 |
// Get the module and check its __file__ attribute |
| 893 |
Py::Dict dict(PyImport_GetModuleDict()); |
| 894 |
if (!dict.hasKey(module)) { |
| 895 |
return 0; |
| 896 |
} |
| 897 |
Py::Module mod(module); |
| 898 |
Py::String file(mod.getAttr("__file__")); |
| 899 |
std::string filename = (std::string)file; |
| 900 |
// file can have the extension .py or .pyc |
| 901 |
filename = filename.substr(0, filename.rfind('.')); |
| 902 |
filename += ".py"; |
| 903 |
boost::regex rx("^# Version ([1-9])\\.([0-9])\\.([0-9]+)"); |
| 904 |
boost::cmatch what; |
| 905 |
|
| 906 |
std::string line; |
| 907 |
Base::FileInfo fi(filename); |
| 908 |
|
| 909 |
Base::ifstream str(fi, std::ios::in); |
| 910 |
while (str && std::getline(str, line)) { |
| 911 |
if (boost::regex_match(line.c_str(), what, rx)) { |
| 912 |
int major = std::atoi(what[1].first); |
| 913 |
int minor = std::atoi(what[2].first); |
| 914 |
int micro = std::atoi(what[3].first); |
| 915 |
int version = (major << 16) + (minor << 8) + micro; |
| 916 |
moduleMap[module] = version; |
| 917 |
return version; |
| 918 |
} |
| 919 |
} |
| 920 |
} |
| 921 |
catch (Py::Exception& e) { |
| 922 |
e.clear(); |
| 923 |
} |
| 924 |
|
| 925 |
#if (defined(HAVE_SWIG) && (HAVE_SWIG == 1)) |
| 926 |
moduleMap[module] = 0; |
| 927 |
#endif |
| 928 |
return 0; |
| 929 |
} |
| 930 |
|
| 931 |
#if (defined(HAVE_SWIG) && (HAVE_SWIG == 1)) |
| 932 |
namespace Swig_python |
| 933 |
{ |
| 934 |
extern int createSWIGPointerObj_T(const char* TypeName, void* obj, PyObject** ptr, int own); |
| 935 |
extern int convertSWIGPointerObj_T(const char* TypeName, PyObject* obj, void** ptr, int flags); |
| 936 |
extern void cleanupSWIG_T(const char* TypeName); |
| 937 |
extern int getSWIGPointerTypeObj_T(const char* TypeName, PyTypeObject** ptr); |
| 938 |
} // namespace Swig_python |
| 939 |
#endif |
| 940 |
|
| 941 |
PyObject* InterpreterSingleton::createSWIGPointerObj( |
| 942 |
const char* Module, |
| 943 |
const char* TypeName, |
| 944 |
void* Pointer, |
| 945 |
int own |
| 946 |
) |
| 947 |
{ |
| 948 |
int result = 0; |
| 949 |
PyObject* proxy = nullptr; |
| 950 |
PyGILStateLocker locker; |
| 951 |
(void)Module; |
| 952 |
#if (defined(HAVE_SWIG) && (HAVE_SWIG == 1)) |
| 953 |
result = Swig_python::createSWIGPointerObj_T(TypeName, Pointer, &proxy, own); |
| 954 |
#else |
| 955 |
(void)TypeName; |
| 956 |
(void)Pointer; |
| 957 |
(void)own; |
| 958 |
result = -1; // indicates error |
| 959 |
#endif |
| 960 |
|
| 961 |
if (result == 0) { |
| 962 |
return proxy; |
| 963 |
} |
| 964 |
|
| 965 |
// none of the SWIG's succeeded |
| 966 |
throw Base::RuntimeError("No SWIG wrapped library loaded"); |
| 967 |
} |
| 968 |
|
| 969 |
bool InterpreterSingleton::convertSWIGPointerObj( |
| 970 |
const char* Module, |
| 971 |
const char* TypeName, |
| 972 |
PyObject* obj, |
| 973 |
void** ptr, |
| 974 |
int flags |
| 975 |
) |
| 976 |
{ |
| 977 |
int result = 0; |
| 978 |
PyGILStateLocker locker; |
| 979 |
(void)Module; |
| 980 |
#if (defined(HAVE_SWIG) && (HAVE_SWIG == 1)) |
| 981 |
result = Swig_python::convertSWIGPointerObj_T(TypeName, obj, ptr, flags); |
| 982 |
#else |
| 983 |
(void)TypeName; |
| 984 |
(void)obj; |
| 985 |
(void)ptr; |
| 986 |
(void)flags; |
| 987 |
result = -1; // indicates error |
| 988 |
#endif |
| 989 |
|
| 990 |
if (result == 0) { |
| 991 |
return true; |
| 992 |
} |
| 993 |
|
| 994 |
// none of the SWIG's succeeded |
| 995 |
throw Base::RuntimeError("No SWIG wrapped library loaded"); |
| 996 |
} |
| 997 |
|
| 998 |
void InterpreterSingleton::cleanupSWIG(const char* TypeName) |
| 999 |
{ |
| 1000 |
PyGILStateLocker locker; |
| 1001 |
#if (defined(HAVE_SWIG) && (HAVE_SWIG == 1)) |
| 1002 |
Swig_python::cleanupSWIG_T(TypeName); |
| 1003 |
#else |
| 1004 |
(void)TypeName; |
| 1005 |
#endif |
| 1006 |
} |
| 1007 |
|
| 1008 |
PyTypeObject* InterpreterSingleton::getSWIGPointerTypeObj(const char* Module, const char* TypeName) |
| 1009 |
{ |
| 1010 |
int result = 0; |
| 1011 |
PyTypeObject* proxy = nullptr; |
| 1012 |
PyGILStateLocker locker; |
| 1013 |
(void)Module; |
| 1014 |
#if (defined(HAVE_SWIG) && (HAVE_SWIG == 1)) |
| 1015 |
result = Swig_python::getSWIGPointerTypeObj_T(TypeName, &proxy); |
| 1016 |
#else |
| 1017 |
(void)TypeName; |
| 1018 |
result = -1; // indicates error |
| 1019 |
#endif |
| 1020 |
|
| 1021 |
if (result == 0) { |
| 1022 |
return proxy; |
| 1023 |
} |
| 1024 |
|
| 1025 |
// none of the SWIG's succeeded |
| 1026 |
throw Base::RuntimeError("No SWIG wrapped library loaded"); |
| 1027 |
} |