2 * Copyright (C) 2013 Team XBMC
5 * This Program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2, or (at your option)
10 * This Program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with XBMC; see the file COPYING. If not, see
17 * <http://www.gnu.org/licenses/>.
21 #if (defined HAVE_CONFIG_H) && (!defined TARGET_WINDOWS)
25 // python.h should always be included first before any other includes
30 #include "PythonInvoker.h"
31 #include "Application.h"
32 #include "ApplicationMessenger.h"
33 #include "addons/AddonManager.h"
34 #include "dialogs/GUIDialogKaiToast.h"
35 #include "filesystem/File.h"
36 #include "filesystem/SpecialProtocol.h"
37 #include "guilib/GraphicContext.h"
38 #include "guilib/GUIWindowManager.h"
39 #include "interfaces/legacy/Addon.h"
40 #include "interfaces/python/LanguageHook.h"
41 #include "interfaces/python/PyContext.h"
42 #include "interfaces/python/pythreadstate.h"
43 #include "interfaces/python/swig.h"
44 #include "interfaces/python/XBPython.h"
45 #include "threads/SingleLock.h"
46 #if defined(TARGET_WINDOWS)
47 #include "utils/CharsetConverter.h"
48 #endif // defined(TARGET_WINDOWS)
49 #include "utils/log.h"
50 #include "utils/StringUtils.h"
51 #include "utils/URIUtils.h"
54 extern "C" FILE *fopen_utf8(const char *_Filename, const char *_Mode);
56 #define fopen_utf8 fopen
63 #define PY_PATH_SEP DELIM
65 // Time before ill-behaved scripts are terminated
66 #define PYTHON_SCRIPT_TIMEOUT 5000 // ms
69 using namespace XFILE;
73 int xbp_chdir(const char *dirname);
74 char* dll_getenv(const char* szKey);
77 #define PythonModulesSize sizeof(PythonModules) / sizeof(PythonModule)
79 CCriticalSection CPythonInvoker::s_critical;
81 static const CStdString getListOfAddonClassesAsString(XBMCAddon::AddonClass::Ref<XBMCAddon::Python::PythonLanguageHook>& languageHook)
84 CSingleLock l(*(languageHook.get()));
85 std::set<XBMCAddon::AddonClass*>& acs = languageHook->GetRegisteredAddonClasses();
86 bool firstTime = true;
87 for (std::set<XBMCAddon::AddonClass*>::iterator iter = acs.begin(); iter != acs.end(); ++iter)
93 message += (*iter)->GetClassname();
99 CPythonInvoker::CPythonInvoker(ILanguageInvocationHandler *invocationHandler)
100 : ILanguageInvoker(invocationHandler),
101 m_source(NULL), m_argc(0), m_argv(NULL),
102 m_threadState(NULL), m_stop(false)
105 CPythonInvoker::~CPythonInvoker()
107 // nothing to do for the default invoker used for registration with the
108 // CScriptInvocationManager
112 if (GetState() < InvokerStateDone)
113 CLog::Log(LOGDEBUG, "CPythonInvoker(%d): waiting for python thread \"%s\" to stop",
114 GetId(), (m_source != NULL ? m_source : "unknown script"));
116 g_pythonParser.PulseGlobalEvent();
121 for (unsigned int i = 0; i < m_argc; i++)
125 g_pythonParser.FinalizeScript();
128 bool CPythonInvoker::Execute(const std::string &script, const std::vector<std::string> &arguments /* = std::vector<std::string>() */)
133 if (!CFile::Exists(script))
135 CLog::Log(LOGERROR, "CPythonInvoker(%d): python script \"%s\" does not exist", GetId(), CSpecialProtocol::TranslatePath(script).c_str());
139 if (!g_pythonParser.InitializeEngine())
142 return ILanguageInvoker::Execute(script, arguments);
145 bool CPythonInvoker::execute(const std::string &script, const std::vector<std::string> &arguments)
147 // copy the code/script into a local string buffer
148 #ifdef TARGET_WINDOWS
149 CStdString strsrc = script;
150 g_charsetConverter.utf8ToSystem(strsrc);
151 m_source = new char[strsrc.length() + 1];
152 strcpy(m_source, strsrc);
154 m_source = new char[script.length() + 1];
155 strcpy(m_source, script.c_str());
158 // copy the arguments into a local buffer
159 m_argc = arguments.size();
160 m_argv = new char*[m_argc];
161 for (unsigned int i = 0; i < m_argc; i++)
163 m_argv[i] = new char[arguments.at(i).length() + 1];
164 strcpy(m_argv[i], arguments.at(i).c_str());
167 CLog::Log(LOGDEBUG, "CPythonInvoker(%d, %s): start processing", GetId(), m_source);
168 int m_Py_file_input = Py_file_input;
170 // get the global lock
171 PyEval_AcquireLock();
172 PyThreadState* state = Py_NewInterpreter();
175 PyEval_ReleaseLock();
176 CLog::Log(LOGERROR, "CPythonInvoker(%d, %s): FAILED to get thread state!", GetId(), m_source);
179 // swap in my thread state
180 PyThreadState_Swap(state);
182 XBMCAddon::AddonClass::Ref<XBMCAddon::Python::PythonLanguageHook> languageHook(new XBMCAddon::Python::PythonLanguageHook(state->interp));
183 languageHook->RegisterMe();
186 setState(InvokerStateInitialized);
188 CLog::Log(LOGDEBUG, "CPythonInvoker(%d, %s): the source file to load is %s", GetId(), m_source, m_source);
190 // get path from script file name and add python path's
191 // this is used for python so it will search modules from script path first
192 CStdString scriptDir = URIUtils::GetDirectory(CSpecialProtocol::TranslatePath(m_source));
193 URIUtils::RemoveSlashAtEnd(scriptDir);
196 // add on any addon modules the user has installed
197 ADDON::VECADDONS addons;
198 ADDON::CAddonMgr::Get().GetAddons(ADDON::ADDON_SCRIPT_MODULE, addons);
199 for (unsigned int i = 0; i < addons.size(); ++i)
200 addPath(CSpecialProtocol::TranslatePath(addons[i]->LibPath()));
202 // we want to use sys.path so it includes site-packages
203 // if this fails, default to using Py_GetPath
204 PyObject *sysMod(PyImport_ImportModule((char*)"sys")); // must call Py_DECREF when finished
205 PyObject *sysModDict(PyModule_GetDict(sysMod)); // borrowed ref, no need to delete
206 PyObject *pathObj(PyDict_GetItemString(sysModDict, "path")); // borrowed ref, no need to delete
208 if (pathObj != NULL && PyList_Check(pathObj))
210 for (int i = 0; i < PyList_Size(pathObj); i++)
212 PyObject *e = PyList_GetItem(pathObj, i); // borrowed ref, no need to delete
213 if (e != NULL && PyString_Check(e))
214 addPath(PyString_AsString(e)); // returns internal data, don't delete or modify
218 addPath(Py_GetPath());
220 Py_DECREF(sysMod); // release ref to sysMod
222 // set current directory and python's path.
224 PySys_SetArgv(m_argc, m_argv);
226 CLog::Log(LOGDEBUG, "CPythonInvoker(%d, %s): setting the Python path to %s", GetId(), m_source, m_pythonPath.c_str());
227 PySys_SetPath((char *)m_pythonPath.c_str());
229 CLog::Log(LOGDEBUG, "CPythonInvoker(%d, %s): entering source directory %s", GetId(), m_source, scriptDir.c_str());
230 PyObject* module = PyImport_AddModule((char*)"__main__");
231 PyObject* moduleDict = PyModule_GetDict(module);
233 // when we are done initing we store thread state so we can be aborted
234 PyThreadState_Swap(NULL);
235 PyEval_ReleaseLock();
237 // we need to check if we was asked to abort before we had inited
238 bool stopping = false;
239 { CSingleLock lock(m_critical);
240 m_threadState = state;
244 PyEval_AcquireLock();
245 PyThreadState_Swap(state);
252 // run script from file
253 // We need to have python open the file because on Windows the DLL that python
254 // is linked against may not be the DLL that xbmc is linked against so
255 // passing a FILE* to python from an fopen has the potential to crash.
256 PyObject* file = PyFile_FromString((char *) CSpecialProtocol::TranslatePath(m_source).c_str(), (char*)"r");
257 FILE *fp = PyFile_AsFile(file);
261 PyObject *f = PyString_FromString(CSpecialProtocol::TranslatePath(m_source).c_str());
262 PyDict_SetItemString(moduleDict, "__file__", f);
264 onPythonModuleInitialization(moduleDict);
267 setState(InvokerStateRunning);
268 XBMCAddon::Python::PyContext pycontext; // this is a guard class that marks this callstack as being in a python context
269 PyRun_FileExFlags(fp, CSpecialProtocol::TranslatePath(m_source).c_str(), m_Py_file_input, moduleDict, moduleDict,1,NULL);
272 CLog::Log(LOGERROR, "CPythonInvoker(%d, %s): %s not found!", GetId(), m_source, m_source);
274 catch (const XbmcCommons::Exception& e)
276 setState(InvokerStateFailed);
282 setState(InvokerStateFailed);
283 CLog::Log(LOGERROR, "CPythonInvoker(%d, %s): failure in script", GetId(), m_source);
288 bool systemExitThrown = false;
289 InvokerState stateToSet;
290 if (!failed && !PyErr_Occurred())
292 CLog::Log(LOGINFO, "CPythonInvoker(%d, %s): script successfully run", GetId(), m_source);
293 stateToSet = InvokerStateDone;
296 else if (PyErr_ExceptionMatches(PyExc_SystemExit))
298 systemExitThrown = true;
299 CLog::Log(LOGINFO, "CPythonInvoker(%d, %s): script aborted", GetId(), m_source);
300 stateToSet = InvokerStateFailed;
305 stateToSet = InvokerStateFailed;
307 // if it failed with an exception we already logged the details
310 PythonBindings::PythonToCppException e;
317 // no need to do anything else because the script has already stopped
320 setState(stateToSet);
324 PyObject *m = PyImport_AddModule((char*)"xbmc");
325 if (m == NULL || PyObject_SetAttrString(m, (char*)"abortRequested", PyBool_FromLong(1)))
326 CLog::Log(LOGERROR, "CPythonInvoker(%d, %s): failed to set abortRequested", GetId(), m_source);
328 // make sure all sub threads have finished
329 for (PyThreadState* s = state->interp->tstate_head, *old = NULL; s;)
338 CLog::Log(LOGINFO, "CPythonInvoker(%d, %s): waiting on thread %"PRIu64, GetId(), m_source, (uint64_t)s->thread_id);
342 CPyThreadState pyState;
346 s = state->interp->tstate_head;
349 // pending calls must be cleared out
350 XBMCAddon::RetardedAsynchCallbackHandler::clearPendingCalls(state);
352 PyThreadState_Swap(NULL);
353 PyEval_ReleaseLock();
355 // set stopped event - this allows ::stop to run and kill remaining threads
356 // this event has to be fired without holding m_critical
357 // also the GIL (PyEval_AcquireLock) must not be held
358 // if not obeyed there is still no deadlock because ::stop waits with timeout (smart one!)
359 m_stoppedEvent.Set();
361 { CSingleLock lock(m_critical);
362 m_threadState = NULL;
365 PyEval_AcquireLock();
366 PyThreadState_Swap(state);
368 onDeinitialization();
370 // run the gc before finishing
372 // if the script exited by throwing a SystemExit excepton then going back
373 // into the interpreter causes this python bug to get hit:
374 // http://bugs.python.org/issue10582
375 // and that causes major failures. So we are not going to go back in
376 // to run the GC if that's the case.
377 if (!m_stop && languageHook->HasRegisteredAddonClasses() && !systemExitThrown &&
378 PyRun_SimpleString(GC_SCRIPT) == -1)
379 CLog::Log(LOGERROR, "CPythonInvoker(%d, %s): failed to run the gc to clean up after running prior to shutting down the Interpreter", GetId(), m_source);
381 Py_EndInterpreter(state);
383 // If we still have objects left around, produce an error message detailing what's been left behind
384 if (languageHook->HasRegisteredAddonClasses())
385 CLog::Log(LOGWARNING, "CPythonInvoker(%d, %s): the python script \"%s\" has left several "
386 "classes in memory that we couldn't clean up. The classes include: %s",
387 GetId(), m_source, m_source, getListOfAddonClassesAsString(languageHook).c_str());
389 // unregister the language hook
390 languageHook->UnregisterMe();
392 PyEval_ReleaseLock();
394 setState(stateToSet);
399 bool CPythonInvoker::stop(bool abort)
401 CSingleLock lock(m_critical);
407 setState(InvokerStateStopping);
409 if (m_threadState != NULL)
411 PyEval_AcquireLock();
412 PyThreadState* old = PyThreadState_Swap((PyThreadState*)m_threadState);
414 //tell xbmc.Monitor to call onAbortRequested()
416 g_pythonParser.OnAbortRequested(m_addon->ID());
419 m = PyImport_AddModule((char*)"xbmc");
420 if (m == NULL || PyObject_SetAttrString(m, (char*)"abortRequested", PyBool_FromLong(1)))
421 CLog::Log(LOGERROR, "CPythonInvoker(%d, %s): failed to set abortRequested", GetId(), m_source);
423 PyThreadState_Swap(old);
425 PyEval_ReleaseLock();
427 XbmcThreads::EndTime timeout(PYTHON_SCRIPT_TIMEOUT);
428 while (!m_stoppedEvent.WaitMSec(15))
430 if (timeout.IsTimePast())
432 CLog::Log(LOGERROR, "CPythonInvoker(%d, %s): script didn't stop in %d seconds - let's kill it", GetId(), m_source, PYTHON_SCRIPT_TIMEOUT / 1000);
436 // We can't empty-spin in the main thread and expect scripts to be able to
437 // dismantle themselves. Python dialogs aren't normal XBMC dialogs, they rely
438 // on TMSG_GUI_PYTHON_DIALOG messages, so pump the message loop.
439 if (g_application.IsCurrentThread())
441 CSingleExit ex(g_graphicsContext);
442 CApplicationMessenger::Get().ProcessMessages();
446 // Useful for add-on performance metrics
447 if (!timeout.IsTimePast())
448 CLog::Log(LOGDEBUG, "CPythonInvoker(%d, %s): script termination took %dms", GetId(), m_source, PYTHON_SCRIPT_TIMEOUT - timeout.MillisLeft());
450 // everything which didn't exit by now gets killed
452 // grabbing the PyLock while holding the m_critical is asking for a deadlock
453 CSingleExit ex2(m_critical);
454 PyEval_AcquireLock();
457 // Since we released the m_critical it's possible that the state is cleaned up
458 // so we need to recheck for m_threadState == NULL
459 if (m_threadState != NULL)
461 old = PyThreadState_Swap((PyThreadState*)m_threadState);
462 for (PyThreadState* state = ((PyThreadState*)m_threadState)->interp->tstate_head; state; state = state->next)
464 // Raise a SystemExit exception in python threads
465 Py_XDECREF(state->async_exc);
466 state->async_exc = PyExc_SystemExit;
467 Py_XINCREF(state->async_exc);
470 // If a dialog entered its doModal(), we need to wake it to see the exception
471 g_pythonParser.PulseGlobalEvent();
475 PyThreadState_Swap(old);
478 PyEval_ReleaseLock();
484 void CPythonInvoker::onExecutionFailed()
486 PyThreadState_Swap(NULL);
487 PyEval_ReleaseLock();
489 setState(InvokerStateFailed);
490 CLog::Log(LOGERROR, "CPythonInvoker(%d, %s): abnormally terminating python thread", GetId(), m_source);
492 CSingleLock lock(m_critical);
493 m_threadState = NULL;
495 ILanguageInvoker::onExecutionFailed();
498 std::map<std::string, CPythonInvoker::PythonModuleInitialization> CPythonInvoker::getModules() const
500 static std::map<std::string, PythonModuleInitialization> modules;
504 void CPythonInvoker::onInitialization()
508 GilSafeSingleLock lock(s_critical);
509 initializeModules(getModules());
512 // get a possible initialization script
513 const char* runscript = getInitializationScript();
514 if (runscript!= NULL && strlen(runscript) > 0)
516 // redirecting default output to debug console
517 if (PyRun_SimpleString(runscript) == -1)
518 CLog::Log(LOGFATAL, "CPythonInvoker(%d, %s): initialize error", GetId(), m_source);
522 void CPythonInvoker::onPythonModuleInitialization(void* moduleDict)
524 if (m_addon.get() == NULL || moduleDict == NULL)
527 PyObject *moduleDictionary = (PyObject *)moduleDict;
529 PyObject *pyaddonid = PyString_FromString(m_addon->ID().c_str());
530 PyDict_SetItemString(moduleDictionary, "__xbmcaddonid__", pyaddonid);
532 CStdString version = ADDON::GetXbmcApiVersionDependency(m_addon);
533 PyObject *pyxbmcapiversion = PyString_FromString(version.c_str());
534 PyDict_SetItemString(moduleDictionary, "__xbmcapiversion__", pyxbmcapiversion);
536 CLog::Log(LOGDEBUG, "CPythonInvoker(%d, %s): instantiating addon using automatically obtained id of \"%s\" dependent on version %s of the xbmc.python api",
537 GetId(), m_source, m_addon->ID().c_str(), version.c_str());
540 void CPythonInvoker::onDeinitialization()
545 void CPythonInvoker::onError()
547 CPyThreadState releaseGil;
548 CSingleLock gc(g_graphicsContext);
550 CGUIDialogKaiToast *pDlgToast = (CGUIDialogKaiToast*)g_windowManager.GetWindow(WINDOW_DIALOG_KAI_TOAST);
551 if (pDlgToast != NULL)
555 if (m_addon.get() != NULL)
556 script = m_addon->Name();
560 URIUtils::Split(m_source, path, script);
561 if (script.Equals("default.py"))
564 URIUtils::RemoveSlashAtEnd(path);
565 URIUtils::Split(path, path2, script);
569 desc = StringUtils::Format(g_localizeStrings.Get(2100), script.c_str());
570 pDlgToast->QueueNotification(CGUIDialogKaiToast::Error, g_localizeStrings.Get(257), desc);
574 const char* CPythonInvoker::getInitializationScript() const
579 void CPythonInvoker::initializeModules(const std::map<std::string, PythonModuleInitialization> &modules)
581 for (std::map<std::string, PythonModuleInitialization>::const_iterator module = modules.begin(); module != modules.end(); ++module)
583 if (!initializeModule(module->second))
584 CLog::Log(LOGWARNING, "CPythonInvoker(%d, %s): unable to initialize python module \"%s\"", GetId(), m_source, module->first.c_str());
588 bool CPythonInvoker::initializeModule(PythonModuleInitialization module)
597 void CPythonInvoker::addPath(const std::string& path)
602 if (!m_pythonPath.empty())
603 m_pythonPath += PY_PATH_SEP;
605 #if defined(TARGET_WINDOWS)
606 CStdString tmp(path);
607 g_charsetConverter.utf8ToSystem(tmp);
610 m_pythonPath += path;
611 #endif // defined(TARGET_WINDOWS)