pyembed.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728
  1. /*##############################################################################
  2. HPCC SYSTEMS software Copyright (C) 2012 HPCC Systems.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. ############################################################################## */
  13. #include "platform.h"
  14. #include "Python.h"
  15. #include "jexcept.hpp"
  16. #include "jthread.hpp"
  17. #include "deftype.hpp"
  18. #include "eclrtl.hpp"
  19. #include "eclrtl_imp.hpp"
  20. #ifdef _WIN32
  21. #define EXPORT __declspec(dllexport)
  22. #else
  23. #define EXPORT
  24. #endif
  25. namespace pyembed {
  26. // Use class OwnedPyObject for any objects that are not 'borrowed references'
  27. // so that the appropriate Py_DECREF call is made when the OwnedPyObject goes
  28. // out of scope, even if the function returns prematurely (such as via an exception).
  29. // In particular, checkPythonError is a lot easier to call safely if this is used.
  30. class OwnedPyObject
  31. {
  32. PyObject *ptr;
  33. public:
  34. inline OwnedPyObject() : ptr(NULL) {}
  35. inline OwnedPyObject(PyObject *_ptr) : ptr(_ptr) {}
  36. inline ~OwnedPyObject() { if (ptr) Py_DECREF(ptr); }
  37. inline PyObject * get() const { return ptr; }
  38. inline PyObject * operator -> () const { return ptr; }
  39. inline operator PyObject *() const { return ptr; }
  40. inline void clear() { if (ptr) Py_DECREF(ptr); ptr = NULL; }
  41. inline void setown(PyObject *_ptr) { clear(); ptr = _ptr; }
  42. inline void set(PyObject *_ptr) { clear(); ptr = _ptr; if (ptr) Py_INCREF(ptr);}
  43. inline PyObject *getLink() { if (ptr) Py_INCREF(ptr); return ptr;}
  44. inline PyObject **ref() { return &ptr; }
  45. };
  46. // call checkPythonError to throw an exception if Python error state is set
  47. static void checkPythonError()
  48. {
  49. PyObject* err = PyErr_Occurred();
  50. if (err)
  51. {
  52. OwnedPyObject pType, pValue, pTraceBack;
  53. PyErr_Fetch(pType.ref(), pValue.ref(), pTraceBack.ref());
  54. OwnedPyObject valStr = PyObject_Str(pValue);
  55. PyErr_Clear();
  56. VStringBuffer errMessage("pyembed: %s", PyString_AsString(valStr));
  57. rtlFail(0, errMessage.str());
  58. }
  59. }
  60. // The Python Global Interpreter Lock (GIL) won't know about C++-created threads, so we need to
  61. // call PyGILState_Ensure() and PyGILState_Release at the start and end of every function.
  62. // Wrapping them in a class like this ensures that the release always happens even if
  63. // the function exists prematurely
  64. class GILstateWrapper
  65. {
  66. PyGILState_STATE gstate;
  67. public:
  68. GILstateWrapper()
  69. {
  70. gstate = PyGILState_Ensure();
  71. }
  72. ~GILstateWrapper()
  73. {
  74. PyGILState_Release(gstate);
  75. }
  76. };
  77. // There is a singleton PythonThreadContext per thread. This allows us to
  78. // ensure that we can make repeated calls to a Python function efficiently.
  79. class PythonThreadContext
  80. {
  81. public:
  82. PyThreadState *threadState;
  83. public:
  84. PythonThreadContext()
  85. {
  86. threadState = PyEval_SaveThread();
  87. }
  88. ~PythonThreadContext()
  89. {
  90. PyEval_RestoreThread(threadState);
  91. script.clear();
  92. }
  93. inline PyObject * importFunction(size32_t lenChars, const char *utf)
  94. {
  95. size32_t bytes = rtlUtf8Size(lenChars, utf);
  96. StringBuffer text(bytes, utf);
  97. if (!prevtext || strcmp(text, prevtext) != 0)
  98. {
  99. prevtext.clear();
  100. // Name should be in the form module.function
  101. const char *funcname = strrchr(text, '.');
  102. if (!funcname)
  103. rtlFail(0, "pyembed: Expected module.function");
  104. StringBuffer modname(funcname-text, text);
  105. funcname++; // skip the '.'
  106. // If the modname is preceded by a path, add it to the python path before importing
  107. const char *pathsep = strrchr(modname, PATHSEPCHAR);
  108. if (pathsep)
  109. {
  110. StringBuffer path(pathsep-modname, modname);
  111. modname.remove(0, 1+pathsep-modname);
  112. PyObject *sys_path = PySys_GetObject((char *) "path");
  113. OwnedPyObject new_path = PyString_FromString(path);
  114. if (sys_path)
  115. {
  116. PyList_Insert(sys_path, 0, new_path);
  117. checkPythonError();
  118. }
  119. }
  120. module.setown(PyImport_ImportModule(modname));
  121. checkPythonError();
  122. PyObject *dict = PyModule_GetDict(module); // this is a borrowed reference and does not need to be released
  123. script.set(PyDict_GetItemString(dict, funcname));
  124. checkPythonError();
  125. if (!script || !PyCallable_Check(script))
  126. rtlFail(0, "pyembed: Object is not callable");
  127. prevtext.set(text);
  128. }
  129. return script.getLink();
  130. }
  131. inline PyObject *compileEmbeddedScript(size32_t lenChars, const char *utf)
  132. {
  133. size32_t bytes = rtlUtf8Size(lenChars, utf);
  134. StringBuffer text(bytes, utf);
  135. if (!prevtext || strcmp(text, prevtext) != 0)
  136. {
  137. prevtext.clear();
  138. // Try compiling as a eval first... if that fails, try as a script.
  139. script.setown(Py_CompileString(text, "", Py_eval_input));
  140. if (!script)
  141. {
  142. PyErr_Clear();
  143. StringBuffer wrapped;
  144. wrapPythonText(wrapped, text);
  145. script.setown(Py_CompileString(wrapped, "<embed>", Py_file_input));
  146. }
  147. checkPythonError();
  148. prevtext.set(text);
  149. }
  150. return script.getLink();
  151. }
  152. private:
  153. static StringBuffer &wrapPythonText(StringBuffer &out, const char *in)
  154. {
  155. out.append("def __user__():\n ");
  156. char c;
  157. while ((c = *in++) != '\0')
  158. {
  159. out.append(c);
  160. if (c=='\n')
  161. out.append(" ");
  162. }
  163. out.append("\n__result__ = __user__()\n");
  164. return out;
  165. }
  166. GILstateWrapper GILState;
  167. OwnedPyObject module;
  168. OwnedPyObject script;
  169. StringAttr prevtext;
  170. };
  171. static __thread PythonThreadContext* threadContext; // We reuse per thread, for speed
  172. static __thread ThreadTermFunc threadHookChain;
  173. static void releaseContext()
  174. {
  175. if (threadContext)
  176. {
  177. delete threadContext;
  178. threadContext = NULL;
  179. }
  180. if (threadHookChain)
  181. {
  182. (*threadHookChain)();
  183. threadHookChain = NULL;
  184. }
  185. }
  186. // Use a global object to ensure that the Python interpreter is initialized on main thread
  187. static class Python27GlobalState
  188. {
  189. public:
  190. Python27GlobalState()
  191. {
  192. // Initialize the Python Interpreter
  193. Py_Initialize();
  194. PyEval_InitThreads();
  195. tstate = PyEval_SaveThread();
  196. }
  197. ~Python27GlobalState()
  198. {
  199. if (threadContext)
  200. delete threadContext; // The one on the main thread won't get picked up by the thread hook mechanism
  201. threadContext = NULL;
  202. PyEval_RestoreThread(tstate);
  203. // Finish the Python Interpreter
  204. Py_Finalize();
  205. }
  206. protected:
  207. PyThreadState *tstate;
  208. } globalState;
  209. // Each call to a Python function will use a new Python27EmbedFunctionContext object
  210. // This takes care of ensuring that the Python GIL is locked while we are executing python code,
  211. // and released when we are not
  212. class Python27EmbedContextBase : public CInterfaceOf<IEmbedFunctionContext>
  213. {
  214. public:
  215. Python27EmbedContextBase(PythonThreadContext *_sharedCtx)
  216. : sharedCtx(_sharedCtx)
  217. {
  218. PyEval_RestoreThread(sharedCtx->threadState);
  219. locals.setown(PyDict_New());
  220. globals.setown(PyDict_New());
  221. PyDict_SetItemString(locals, "__builtins__", PyEval_GetBuiltins()); // required for import to work
  222. }
  223. ~Python27EmbedContextBase()
  224. {
  225. // We need to clear these before calling savethread, or we won't own the GIL
  226. locals.clear();
  227. globals.clear();
  228. result.clear();
  229. script.clear();
  230. sharedCtx->threadState = PyEval_SaveThread();
  231. }
  232. virtual bool getBooleanResult()
  233. {
  234. assertex(result && result != Py_None);
  235. if (!PyBool_Check(result))
  236. rtlFail(0, "pyembed: Type mismatch on result - value is not BOOLEAN ");
  237. return result == Py_True;
  238. }
  239. virtual void getDataResult(size32_t &__chars, void * &__result)
  240. {
  241. assertex(result && result != Py_None);
  242. if (!PyByteArray_Check(result))
  243. rtlFail(0, "pyembed: Type mismatch on result - value is not a bytearray");
  244. rtlStrToDataX(__chars, __result, PyByteArray_Size(result), PyByteArray_AsString(result));
  245. }
  246. virtual double getRealResult()
  247. {
  248. assertex(result && result != Py_None);
  249. return PyFloat_AsDouble(result);
  250. }
  251. virtual __int64 getSignedResult()
  252. {
  253. assertex(result && result != Py_None);
  254. return (__int64) PyLong_AsLongLong(result);
  255. }
  256. virtual unsigned __int64 getUnsignedResult()
  257. {
  258. assertex(result && result != Py_None);
  259. return (__int64) PyLong_AsUnsignedLongLong(result);
  260. }
  261. virtual void getStringResult(size32_t &__chars, char * &__result)
  262. {
  263. assertex(result && result != Py_None);
  264. if (PyString_Check(result))
  265. {
  266. const char * text = PyString_AsString(result);
  267. checkPythonError();
  268. size_t lenBytes = PyString_Size(result);
  269. rtlStrToStrX(__chars, __result, lenBytes, text);
  270. }
  271. else
  272. rtlFail(0, "pyembed: type mismatch - return value was not a string");
  273. }
  274. virtual void getUTF8Result(size32_t &__chars, char * &__result)
  275. {
  276. assertex(result && result != Py_None);
  277. if (PyUnicode_Check(result))
  278. {
  279. OwnedPyObject utf8 = PyUnicode_AsUTF8String(result);
  280. checkPythonError();
  281. size_t lenBytes = PyString_Size(utf8);
  282. const char * text = PyString_AsString(utf8);
  283. checkPythonError();
  284. size32_t numchars = rtlUtf8Length(lenBytes, text);
  285. rtlUtf8ToUtf8X(__chars, __result, numchars, text);
  286. }
  287. else
  288. rtlFail(0, "pyembed: type mismatch - return value was not a unicode string");
  289. }
  290. virtual void getUnicodeResult(size32_t &__chars, UChar * &__result)
  291. {
  292. assertex(result && result != Py_None);
  293. if (PyUnicode_Check(result))
  294. {
  295. OwnedPyObject utf8 = PyUnicode_AsUTF8String(result);
  296. checkPythonError();
  297. size_t lenBytes = PyString_Size(utf8);
  298. const char * text = PyString_AsString(utf8);
  299. checkPythonError();
  300. size32_t numchars = rtlUtf8Length(lenBytes, text);
  301. rtlUtf8ToUnicodeX(__chars, __result, numchars, text);
  302. }
  303. else
  304. rtlFail(0, "pyembed: type mismatch - return value was not a unicode string");
  305. }
  306. virtual void getSetResult(bool & __isAllResult, size32_t & __resultBytes, void * & __result, int elemType, size32_t elemSize)
  307. {
  308. assertex(result && result != Py_None);
  309. if (!PyList_Check(result))
  310. rtlFail(0, "pyembed: type mismatch - return value was not a list");
  311. Py_ssize_t numResults = PyList_Size(result);
  312. rtlRowBuilder out;
  313. byte *outData = NULL;
  314. size32_t outBytes = 0;
  315. if (elemSize != UNKNOWN_LENGTH)
  316. {
  317. out.ensureAvailable(numResults * elemSize); // MORE - check for overflow?
  318. outData = out.getbytes();
  319. }
  320. for (int i = 0; i < numResults; i++)
  321. {
  322. PyObject *elem = PyList_GetItem(result, i); // note - borrowed reference
  323. switch ((type_t) elemType)
  324. {
  325. case type_int:
  326. rtlWriteInt(outData, PyLong_AsLongLong(elem), elemSize);
  327. break;
  328. case type_unsigned:
  329. rtlWriteInt(outData, PyLong_AsUnsignedLongLong(elem), elemSize);
  330. break;
  331. case type_real:
  332. if (!PyFloat_Check(elem))
  333. rtlFail(0, "pyembed: type mismatch - return value in list was not a REAL");
  334. if (elemSize == sizeof(double))
  335. * (double *) outData = (double) PyFloat_AsDouble(elem);
  336. else
  337. {
  338. assertex(elemSize == sizeof(float));
  339. * (float *) outData = (float) PyFloat_AsDouble(elem);
  340. }
  341. break;
  342. case type_boolean:
  343. assertex(elemSize == sizeof(bool));
  344. if (!PyBool_Check(elem))
  345. rtlFail(0, "pyembed: type mismatch - return value in list was not a BOOLEAN");
  346. * (bool *) outData = (result == Py_True);
  347. break;
  348. case type_string:
  349. case type_varstring:
  350. {
  351. if (!PyString_Check(elem))
  352. rtlFail(0, "pyembed: type mismatch - return value in list was not a STRING");
  353. const char * text = PyString_AsString(elem);
  354. checkPythonError();
  355. size_t lenBytes = PyString_Size(elem);
  356. if (elemSize == UNKNOWN_LENGTH)
  357. {
  358. if (elemType == type_string)
  359. {
  360. out.ensureAvailable(outBytes + lenBytes + sizeof(size32_t));
  361. outData = out.getbytes() + outBytes;
  362. * (size32_t *) outData = lenBytes;
  363. rtlStrToStr(lenBytes, outData+sizeof(size32_t), lenBytes, text);
  364. outBytes += lenBytes + sizeof(size32_t);
  365. }
  366. else
  367. {
  368. out.ensureAvailable(outBytes + lenBytes + 1);
  369. outData = out.getbytes() + outBytes;
  370. rtlStrToVStr(0, outData, lenBytes, text);
  371. outBytes += lenBytes + 1;
  372. }
  373. }
  374. else
  375. {
  376. if (elemType == type_string)
  377. rtlStrToStr(elemSize, outData, lenBytes, text);
  378. else
  379. rtlStrToVStr(elemSize, outData, lenBytes, text); // Fixed size null terminated strings... weird.
  380. }
  381. break;
  382. }
  383. case type_unicode:
  384. case type_utf8:
  385. {
  386. if (!PyUnicode_Check(elem))
  387. rtlFail(0, "pyembed: type mismatch - return value in list was not a unicode STRING");
  388. OwnedPyObject utf8 = PyUnicode_AsUTF8String(elem);
  389. checkPythonError();
  390. size_t lenBytes = PyString_Size(utf8);
  391. const char * text = PyString_AsString(utf8);
  392. checkPythonError();
  393. size32_t numchars = rtlUtf8Length(lenBytes, text);
  394. if (elemType == type_utf8)
  395. {
  396. assertex (elemSize == UNKNOWN_LENGTH);
  397. out.ensureAvailable(outBytes + lenBytes + sizeof(size32_t));
  398. outData = out.getbytes() + outBytes;
  399. * (size32_t *) outData = numchars;
  400. rtlStrToStr(lenBytes, outData+sizeof(size32_t), lenBytes, text);
  401. outBytes += lenBytes + sizeof(size32_t);
  402. }
  403. else
  404. {
  405. if (elemSize == UNKNOWN_LENGTH)
  406. {
  407. out.ensureAvailable(outBytes + numchars*sizeof(UChar) + sizeof(size32_t));
  408. outData = out.getbytes() + outBytes;
  409. // You can't assume that number of chars in utf8 matches number in unicode16 ...
  410. size32_t numchars16;
  411. rtlDataAttr unicode16;
  412. rtlUtf8ToUnicodeX(numchars16, unicode16.refustr(), numchars, text);
  413. * (size32_t *) outData = numchars16;
  414. rtlUnicodeToUnicode(numchars16, (UChar *) (outData+sizeof(size32_t)), numchars16, unicode16.getustr());
  415. outBytes += numchars16*sizeof(UChar) + sizeof(size32_t);
  416. }
  417. else
  418. rtlUtf8ToUnicode(elemSize / sizeof(UChar), (UChar *) outData, numchars, text);
  419. }
  420. break;
  421. }
  422. case type_data:
  423. {
  424. if (!PyByteArray_Check(elem))
  425. rtlFail(0, "pyembed: type mismatch - return value in list was not a bytearray");
  426. size_t lenBytes = PyByteArray_Size(elem); // Could check does not overflow size32_t
  427. const char *data = PyByteArray_AsString(elem);
  428. if (elemSize == UNKNOWN_LENGTH)
  429. {
  430. out.ensureAvailable(outBytes + lenBytes + sizeof(size32_t));
  431. outData = out.getbytes() + outBytes;
  432. * (size32_t *) outData = lenBytes;
  433. rtlStrToData(lenBytes, outData+sizeof(size32_t), lenBytes, data);
  434. outBytes += lenBytes + sizeof(size32_t);
  435. }
  436. else
  437. rtlStrToData(elemSize, outData, lenBytes, data);
  438. break;
  439. }
  440. default:
  441. rtlFail(0, "pyembed: type mismatch - unsupported return type");
  442. }
  443. checkPythonError();
  444. if (elemSize != UNKNOWN_LENGTH)
  445. {
  446. outData += elemSize;
  447. outBytes += elemSize;
  448. }
  449. }
  450. __isAllResult = false;
  451. __resultBytes = outBytes;
  452. __result = out.detachdata();
  453. }
  454. virtual void bindBooleanParam(const char *name, bool val)
  455. {
  456. addArg(name, PyBool_FromLong(val ? 1 : 0));
  457. }
  458. virtual void bindDataParam(const char *name, size32_t len, const void *val)
  459. {
  460. addArg(name, PyByteArray_FromStringAndSize((const char *) val, len));
  461. }
  462. virtual void bindRealParam(const char *name, double val)
  463. {
  464. addArg(name, PyFloat_FromDouble(val));
  465. }
  466. virtual void bindSignedParam(const char *name, __int64 val)
  467. {
  468. addArg(name, PyLong_FromLongLong(val));
  469. }
  470. virtual void bindUnsignedParam(const char *name, unsigned __int64 val)
  471. {
  472. addArg(name, PyLong_FromUnsignedLongLong(val));
  473. }
  474. virtual void bindStringParam(const char *name, size32_t len, const char *val)
  475. {
  476. addArg(name, PyString_FromStringAndSize(val, len));
  477. }
  478. virtual void bindVStringParam(const char *name, const char *val)
  479. {
  480. addArg(name, PyString_FromString(val));
  481. }
  482. virtual void bindUTF8Param(const char *name, size32_t chars, const char *val)
  483. {
  484. size32_t sizeBytes = rtlUtf8Size(chars, val);
  485. PyObject *vval = PyUnicode_FromStringAndSize(val, sizeBytes); // NOTE - requires size in bytes not chars
  486. checkPythonError();
  487. addArg(name, vval);
  488. }
  489. virtual void bindUnicodeParam(const char *name, size32_t chars, const UChar *val)
  490. {
  491. // You don't really know what size Py_UNICODE is (varies from system to system), so go via utf8
  492. unsigned unicodeChars;
  493. char *unicode;
  494. rtlUnicodeToUtf8X(unicodeChars, unicode, chars, val);
  495. size32_t sizeBytes = rtlUtf8Size(unicodeChars, unicode);
  496. PyObject *vval = PyUnicode_FromStringAndSize(unicode, sizeBytes); // NOTE - requires size in bytes not chars
  497. checkPythonError();
  498. addArg(name, vval);
  499. rtlFree(unicode);
  500. }
  501. virtual void bindSetParam(const char *name, int elemType, size32_t elemSize, bool isAll, size32_t totalBytes, void *setData)
  502. {
  503. if (isAll)
  504. rtlFail(0, "pyembed: Cannot pass ALL");
  505. type_t typecode = (type_t) elemType;
  506. const byte *inData = (const byte *) setData;
  507. const byte *endData = inData + totalBytes;
  508. OwnedPyObject vval = PyList_New(0);
  509. while (inData < endData)
  510. {
  511. OwnedPyObject thisElem;
  512. size32_t thisSize = elemSize;
  513. switch (typecode)
  514. {
  515. case type_int:
  516. thisElem.setown(PyLong_FromLongLong(rtlReadInt(inData, elemSize)));
  517. break;
  518. case type_unsigned:
  519. thisElem.setown(PyLong_FromUnsignedLongLong(rtlReadUInt(inData, elemSize)));
  520. break;
  521. case type_varstring:
  522. {
  523. size32_t numChars = strlen((const char *) inData);
  524. thisElem.setown(PyString_FromStringAndSize((const char *) inData, numChars));
  525. if (elemSize == UNKNOWN_LENGTH)
  526. thisSize = numChars + 1;
  527. break;
  528. }
  529. case type_string:
  530. if (elemSize == UNKNOWN_LENGTH)
  531. {
  532. thisSize = * (size32_t *) inData;
  533. inData += sizeof(size32_t);
  534. }
  535. thisElem.setown(PyString_FromStringAndSize((const char *) inData, thisSize));
  536. break;
  537. case type_real:
  538. if (elemSize == sizeof(double))
  539. thisElem.setown(PyFloat_FromDouble(* (double *) inData));
  540. else
  541. thisElem.setown(PyFloat_FromDouble(* (float *) inData));
  542. break;
  543. case type_boolean:
  544. assertex(elemSize == sizeof(bool));
  545. thisElem.setown(PyBool_FromLong(*(bool*)inData ? 1 : 0));
  546. break;
  547. case type_unicode:
  548. {
  549. if (elemSize == UNKNOWN_LENGTH)
  550. {
  551. thisSize = (* (size32_t *) inData) * sizeof(UChar); // NOTE - it's in chars...
  552. inData += sizeof(size32_t);
  553. }
  554. unsigned unicodeChars;
  555. rtlDataAttr unicode;
  556. rtlUnicodeToUtf8X(unicodeChars, unicode.refstr(), thisSize / sizeof(UChar), (const UChar *) inData);
  557. size32_t sizeBytes = rtlUtf8Size(unicodeChars, unicode.getstr());
  558. thisElem.setown(PyUnicode_FromStringAndSize(unicode.getstr(), sizeBytes)); // NOTE - requires size in bytes not chars
  559. checkPythonError();
  560. break;
  561. }
  562. case type_utf8:
  563. {
  564. assertex (elemSize == UNKNOWN_LENGTH);
  565. size32_t numChars = * (size32_t *) inData;
  566. inData += sizeof(size32_t);
  567. thisSize = rtlUtf8Size(numChars, inData);
  568. thisElem.setown(PyUnicode_FromStringAndSize((const char *) inData, thisSize)); // NOTE - requires size in bytes not chars
  569. break;
  570. }
  571. case type_data:
  572. if (elemSize == UNKNOWN_LENGTH)
  573. {
  574. thisSize = * (size32_t *) inData;
  575. inData += sizeof(size32_t);
  576. }
  577. thisElem.setown(PyByteArray_FromStringAndSize((const char *) inData, thisSize));
  578. break;
  579. }
  580. checkPythonError();
  581. inData += thisSize;
  582. PyList_Append(vval, thisElem);
  583. }
  584. addArg(name, vval.getLink());
  585. }
  586. protected:
  587. virtual void addArg(const char *name, PyObject *arg) = 0;
  588. PythonThreadContext *sharedCtx;
  589. OwnedPyObject locals;
  590. OwnedPyObject globals;
  591. OwnedPyObject result;
  592. OwnedPyObject script;
  593. };
  594. class Python27EmbedScriptContext : public Python27EmbedContextBase
  595. {
  596. public:
  597. Python27EmbedScriptContext(PythonThreadContext *_sharedCtx, const char *options)
  598. : Python27EmbedContextBase(_sharedCtx)
  599. {
  600. }
  601. ~Python27EmbedScriptContext()
  602. {
  603. }
  604. virtual void importFunction(size32_t lenChars, const char *text)
  605. {
  606. throwUnexpected();
  607. }
  608. virtual void compileEmbeddedScript(size32_t lenChars, const char *utf)
  609. {
  610. script.setown(sharedCtx->compileEmbeddedScript(lenChars, utf));
  611. }
  612. virtual void callFunction()
  613. {
  614. result.setown(PyEval_EvalCode((PyCodeObject *) script.get(), locals, globals));
  615. checkPythonError();
  616. if (!result || result == Py_None)
  617. result.set(PyDict_GetItemString(locals, "__result__"));
  618. if (!result || result == Py_None)
  619. result.set(PyDict_GetItemString(globals, "__result__"));
  620. }
  621. protected:
  622. virtual void addArg(const char *name, PyObject *arg)
  623. {
  624. assertex(arg);
  625. PyDict_SetItemString(locals, name, arg);
  626. Py_DECREF(arg);
  627. checkPythonError();
  628. }
  629. };
  630. class Python27EmbedImportContext : public Python27EmbedContextBase
  631. {
  632. public:
  633. Python27EmbedImportContext(PythonThreadContext *_sharedCtx, const char *options)
  634. : Python27EmbedContextBase(_sharedCtx)
  635. {
  636. argcount = 0;
  637. }
  638. ~Python27EmbedImportContext()
  639. {
  640. }
  641. virtual void importFunction(size32_t lenChars, const char *utf)
  642. {
  643. script.setown(sharedCtx->importFunction(lenChars, utf));
  644. }
  645. virtual void compileEmbeddedScript(size32_t len, const char *text)
  646. {
  647. throwUnexpected();
  648. }
  649. virtual void callFunction()
  650. {
  651. result.setown(PyObject_CallObject(script, args));
  652. checkPythonError();
  653. }
  654. private:
  655. virtual void addArg(const char *name, PyObject *arg)
  656. {
  657. if (argcount)
  658. _PyTuple_Resize(args.ref(), argcount+1);
  659. else
  660. args.setown(PyTuple_New(1));
  661. PyTuple_SET_ITEM((PyTupleObject *) args.get(), argcount++, arg); // Note - 'steals' the arg reference
  662. }
  663. int argcount;
  664. OwnedPyObject args;
  665. };
  666. class Python27EmbedContext : public CInterfaceOf<IEmbedContext>
  667. {
  668. public:
  669. virtual IEmbedFunctionContext *createFunctionContext(bool isImport, const char *options)
  670. {
  671. if (!threadContext)
  672. {
  673. threadContext = new PythonThreadContext;
  674. threadHookChain = addThreadTermFunc(releaseContext);
  675. }
  676. if (isImport)
  677. return new Python27EmbedImportContext(threadContext, options);
  678. else
  679. return new Python27EmbedScriptContext(threadContext, options);
  680. }
  681. };
  682. extern IEmbedContext* getEmbedContext()
  683. {
  684. return new Python27EmbedContext;
  685. }
  686. extern bool syntaxCheck(const char *script)
  687. {
  688. return true; // MORE
  689. }
  690. } // namespace