py3embed.cpp 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754
  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. #ifdef _WIN32
  14. // There's an issue with Python redefining ssize_t resulting in errors - hide their definition
  15. #define ssize_t python_ssize_t
  16. #include "Python.h"
  17. #undef ssize_t
  18. #else
  19. #include "Python.h"
  20. #endif
  21. #include "platform.h"
  22. #include "frameobject.h"
  23. #include "jexcept.hpp"
  24. #include "jutil.hpp"
  25. #include "jthread.hpp"
  26. #include "jregexp.hpp"
  27. #include "hqlplugins.hpp"
  28. #include "deftype.hpp"
  29. #include "eclhelper.hpp"
  30. #include "eclrtl.hpp"
  31. #include "eclrtl_imp.hpp"
  32. #include "rtlds_imp.hpp"
  33. #include "rtlfield.hpp"
  34. #include "nbcd.hpp"
  35. #include "roxiemem.hpp"
  36. #include "enginecontext.hpp"
  37. #if PY_MAJOR_VERSION >=3
  38. #define Py_TPFLAGS_HAVE_ITER 0
  39. #endif
  40. static const char * compatibleVersions[] = {
  41. "Python3.x Embed Helper 1.0.0",
  42. NULL };
  43. static const char *version = "Python3.x Embed Helper 1.0.0";
  44. extern "C" DECL_EXPORT bool getECLPluginDefinition(ECLPluginDefinitionBlock *pb)
  45. {
  46. if (pb->size == sizeof(ECLPluginDefinitionBlockEx))
  47. {
  48. ECLPluginDefinitionBlockEx * pbx = (ECLPluginDefinitionBlockEx *) pb;
  49. pbx->compatibleVersions = compatibleVersions;
  50. }
  51. else if (pb->size != sizeof(ECLPluginDefinitionBlock))
  52. return false;
  53. pb->magicVersion = PLUGIN_VERSION;
  54. pb->version = version;
  55. pb->moduleName = "python3";
  56. pb->ECL = NULL;
  57. pb->flags = PLUGIN_MULTIPLE_VERSIONS;
  58. pb->description = "Python3.x Embed Helper";
  59. return true;
  60. }
  61. namespace py3embed {
  62. // Use class OwnedPyObject for any objects that are not 'borrowed references'
  63. // so that the appropriate Py_DECREF call is made when the OwnedPyObject goes
  64. // out of scope, even if the function returns prematurely (such as via an exception).
  65. // In particular, checkPythonError is a lot easier to call safely if this is used.
  66. class OwnedPyObject
  67. {
  68. PyObject *ptr;
  69. public:
  70. inline OwnedPyObject() : ptr(NULL) {}
  71. inline OwnedPyObject(PyObject *_ptr) : ptr(_ptr) {}
  72. inline ~OwnedPyObject() { if (ptr) Py_DECREF(ptr); }
  73. inline PyObject * get() const { return ptr; }
  74. inline PyObject * getClear() { PyObject *ret = ptr; ptr = NULL; return ret; }
  75. inline PyObject * operator -> () const { return ptr; }
  76. inline operator PyObject *() const { return ptr; }
  77. inline void clear() { if (ptr) Py_DECREF(ptr); ptr = NULL; }
  78. inline void setown(PyObject *_ptr) { clear(); ptr = _ptr; }
  79. inline void set(PyObject *_ptr) { if (_ptr) Py_INCREF(_ptr); clear(); ptr = _ptr; }
  80. inline PyObject *getLink() { if (ptr) Py_INCREF(ptr); return ptr;}
  81. inline PyObject **ref() { return &ptr; }
  82. };
  83. template <class X>
  84. class OwnedPyX
  85. {
  86. X *ptr;
  87. public:
  88. inline OwnedPyX<X>() : ptr(NULL) {}
  89. inline OwnedPyX<X>(X *_ptr) : ptr(_ptr) {}
  90. inline ~OwnedPyX<X>() { if (ptr) Py_DECREF(ptr); }
  91. inline X * get() const { return ptr; }
  92. inline X * getClear() { PyObject *ret = ptr; ptr = NULL; return ret; }
  93. inline X * operator -> () const { return ptr; }
  94. inline operator X *() const { return ptr; }
  95. inline void clear() { if (ptr) Py_DECREF(ptr); ptr = NULL; }
  96. inline void setown(X *_ptr) { clear(); ptr = _ptr; }
  97. inline void set(X *_ptr) { if (_ptr) Py_INCREF(_ptr); clear(); ptr = _ptr; }
  98. inline X *getLink() { if (ptr) Py_INCREF(ptr); return ptr;}
  99. inline X **ref() { return &ptr; }
  100. };
  101. __declspec(noreturn) static void failx(const char *msg, ...) __attribute__((format(printf, 1, 2), noreturn));
  102. static void failx(const char *message, ...)
  103. {
  104. va_list args;
  105. va_start(args,message);
  106. StringBuffer msg;
  107. msg.append("pyembed: ").valist_appendf(message,args);
  108. va_end(args);
  109. rtlFail(0, msg.str());
  110. }
  111. // call checkPythonError to throw an exception if Python error state is set
  112. static void checkPythonError()
  113. {
  114. PyObject* err = PyErr_Occurred();
  115. if (err)
  116. {
  117. OwnedPyObject pType, pValue, pTraceBack;
  118. PyErr_Fetch(pType.ref(), pValue.ref(), pTraceBack.ref());
  119. OwnedPyObject valStr = PyObject_Str(pValue);
  120. PyErr_Clear();
  121. assertex(PyUnicode_Check(valStr));
  122. const char *text = PyUnicode_AsUTF8AndSize(valStr, NULL);
  123. failx("%s", text);
  124. }
  125. }
  126. // The Python Global Interpreter Lock (GIL) won't know about C++-created threads, so we need to
  127. // call PyGILState_Ensure() and PyGILState_Release at the start and end of every function.
  128. // Wrapping them in a class like this ensures that the release always happens even if
  129. // the function exists prematurely
  130. class GILstateWrapper
  131. {
  132. PyGILState_STATE gstate;
  133. public:
  134. GILstateWrapper()
  135. {
  136. gstate = PyGILState_Ensure();
  137. }
  138. ~GILstateWrapper()
  139. {
  140. PyGILState_Release(gstate);
  141. }
  142. };
  143. // There is a singleton PythonThreadContext per thread. This allows us to
  144. // ensure that we can make repeated calls to a Python function efficiently.
  145. class PythonThreadContext
  146. {
  147. public:
  148. PyThreadState *threadState;
  149. public:
  150. PythonThreadContext()
  151. {
  152. threadState = PyEval_SaveThread();
  153. lrutype = NULL;
  154. }
  155. ~PythonThreadContext()
  156. {
  157. PyEval_RestoreThread(threadState);
  158. script.clear();
  159. module.clear();
  160. lru.clear();
  161. }
  162. inline PyObject * importFunction(size32_t lenChars, const char *utf)
  163. {
  164. size32_t bytes = rtlUtf8Size(lenChars, utf);
  165. StringBuffer text(bytes, utf);
  166. if (!prevtext || strcmp(text, prevtext) != 0)
  167. {
  168. prevtext.clear();
  169. // Name should be in the form module.function
  170. const char *funcname = strrchr(text, '.');
  171. if (!funcname)
  172. rtlFail(0, "pyembed: Expected module.function");
  173. StringBuffer modname(funcname-text, text);
  174. funcname++; // skip the '.'
  175. // If the modname is preceded by a path, add it to the python path before importing
  176. const char *pathsep = strrchr(modname, PATHSEPCHAR);
  177. if (pathsep)
  178. {
  179. StringBuffer path(pathsep-modname, modname);
  180. modname.remove(0, 1+pathsep-modname);
  181. PyObject *sys_path = PySys_GetObject((char *) "path");
  182. OwnedPyObject new_path = PyUnicode_FromString(path);
  183. if (sys_path)
  184. {
  185. PyList_Insert(sys_path, 0, new_path);
  186. checkPythonError();
  187. }
  188. }
  189. module.setown(PyImport_ImportModule(modname));
  190. checkPythonError();
  191. PyObject *dict = PyModule_GetDict(module); // this is a borrowed reference and does not need to be released
  192. script.set(PyDict_GetItemString(dict, funcname));
  193. checkPythonError();
  194. if (!script || !PyCallable_Check(script))
  195. rtlFail(0, "pyembed: Object is not callable");
  196. prevtext.set(text);
  197. }
  198. return script.getLink();
  199. }
  200. PyObject *compileEmbeddedScript(size32_t lenChars, const char *utf, const char *argstring);
  201. PyObject *getNamedTupleType(const RtlTypeInfo *type);
  202. private:
  203. GILstateWrapper GILState;
  204. OwnedPyObject module;
  205. OwnedPyObject script;
  206. OwnedPyObject lru;
  207. const RtlTypeInfo *lrutype;
  208. StringAttr prevtext;
  209. };
  210. static __thread PythonThreadContext* threadContext; // We reuse per thread, for speed
  211. static __thread ThreadTermFunc threadHookChain;
  212. static void releaseContext()
  213. {
  214. if (threadContext)
  215. {
  216. delete threadContext;
  217. threadContext = NULL;
  218. }
  219. if (threadHookChain)
  220. {
  221. (*threadHookChain)();
  222. threadHookChain = NULL;
  223. }
  224. }
  225. // Use a global object to ensure that the Python interpreter is initialized on main thread
  226. static HINSTANCE keepLoadedHandle;
  227. static class Python3xGlobalState
  228. {
  229. public:
  230. Python3xGlobalState()
  231. {
  232. pythonLibrary = (HINSTANCE) 0;
  233. #ifndef _WIN32
  234. // If Py_Initialize is called when stdin is set to a directory, it calls exit()
  235. // We don't want that to happen - just disable Python support in such situations
  236. struct stat sb;
  237. if (fstat(fileno(stdin), &sb) == 0 && S_ISDIR(sb.st_mode))
  238. {
  239. initialized = false;
  240. return;
  241. }
  242. #endif
  243. #ifndef _WIN32
  244. // We need to ensure all symbols in the python3.x so are loaded - due to bugs in some distro's python installations
  245. // However this will likely break python2.
  246. // Therefore on systems where both are present, do NOT do this - people using centos systems that suffer from issue
  247. // https://bugs.centos.org/view.php?id=6063 will need to choose which version of python plugin to install but not both
  248. StringBuffer modname, py2modname;
  249. if (findLoadedModule(modname, "libpython3.") && !findLoadedModule(py2modname, "libpython2."))
  250. pythonLibrary = dlopen(modname.str(), RTLD_NOW|RTLD_GLOBAL);
  251. #endif
  252. // Initialize the Python Interpreter
  253. Py_Initialize();
  254. const wchar_t *argv[] = { nullptr };
  255. PySys_SetArgvEx(0, (wchar_t **) argv, 0);
  256. PyEval_InitThreads();
  257. preservedScopes.setown(PyDict_New());
  258. tstate = PyEval_SaveThread();
  259. initialized = true;
  260. }
  261. ~Python3xGlobalState()
  262. {
  263. if (keepLoadedHandle)
  264. FreeSharedObject(keepLoadedHandle); // Must be process termination - ok to free now (and helps stop lockups at closedown in some Python libraries eg Tensorflow).
  265. if (threadContext)
  266. delete threadContext; // The one on the main thread won't get picked up by the thread hook mechanism
  267. threadContext = NULL;
  268. if (initialized)
  269. {
  270. PyEval_RestoreThread(tstate);
  271. // Finish the Python Interpreter
  272. namedtuple.clear();
  273. namedtupleTypes.clear();
  274. compiledScripts.clear();
  275. preservedScopes.clear();
  276. Py_Finalize();
  277. }
  278. if (pythonLibrary)
  279. FreeSharedObject(pythonLibrary);
  280. }
  281. bool isInitialized()
  282. {
  283. return initialized;
  284. }
  285. PyFrameObject *pushDummyFrame()
  286. {
  287. PyThreadState* threadstate = PyThreadState_GET();
  288. if (!threadstate->frame)
  289. {
  290. OwnedPyObject globals = PyDict_New();
  291. OwnedPyObject locals = PyDict_New();
  292. OwnedPyX<PyCodeObject> code = PyCode_NewEmpty("<dummy>","<dummy>", 0);
  293. checkPythonError();
  294. PyFrameObject *frame = PyFrame_New(threadstate, code, globals, locals);
  295. checkPythonError();
  296. threadstate->frame = frame;
  297. return frame;
  298. }
  299. return NULL;
  300. }
  301. void popDummyFrame(PyFrameObject *frame)
  302. {
  303. PyThreadState* threadstate = PyThreadState_GET();
  304. if (threadstate->frame == frame)
  305. threadstate->frame = NULL;
  306. }
  307. PyObject *getNamedTupleType(const RtlTypeInfo *type)
  308. {
  309. // It seems the customized namedtuple types leak, and they are slow to create, so take care to reuse
  310. // Note - we do not need (and must not have) a lock protecting this. It is protected by the Python GIL,
  311. // and if we add our own lock we are liable to deadlock as the code within Py_CompileStringFlags may
  312. // temporarily release then re-acquire the GIL.
  313. if (!namedtuple)
  314. {
  315. namedtupleTypes.setown(PyDict_New());
  316. OwnedPyObject pName = PyUnicode_FromString("collections");
  317. OwnedPyObject collections = PyImport_Import(pName);
  318. checkPythonError();
  319. namedtuple.setown(PyObject_GetAttrString(collections, "namedtuple"));
  320. checkPythonError();
  321. assertex(PyCallable_Check(namedtuple));
  322. }
  323. const RtlFieldInfo * const *fields = type->queryFields();
  324. if (!fields && type->queryChildType())
  325. fields = type->queryChildType()->queryFields();
  326. assertex(fields);
  327. StringBuffer names;
  328. while (*fields)
  329. {
  330. const RtlFieldInfo *field = *fields;
  331. if (names.length())
  332. names.append(',');
  333. names.append(field->name);
  334. fields++;
  335. }
  336. OwnedPyObject pnames = PyUnicode_FromString(names.str());
  337. OwnedPyObject mynamedtupletype;
  338. checkPythonError();
  339. mynamedtupletype.set(PyDict_GetItem(namedtupleTypes, pnames)); // NOTE - returns borrowed reference
  340. if (!mynamedtupletype)
  341. {
  342. OwnedPyObject recname = PyUnicode_FromString("namerec"); // MORE - do we care what the name is?
  343. OwnedPyObject ntargs = PyTuple_Pack(2, recname.get(), pnames.get());
  344. checkPythonError();
  345. OwnedPyX<PyFrameObject> frame = pushDummyFrame();
  346. mynamedtupletype.setown(PyObject_CallObject(namedtuple, ntargs));
  347. popDummyFrame(frame);
  348. checkPythonError();
  349. PyDict_SetItem(namedtupleTypes, pnames, mynamedtupletype);
  350. }
  351. checkPythonError();
  352. assertex(PyCallable_Check(mynamedtupletype));
  353. return mynamedtupletype.getClear();
  354. }
  355. PyObject *compileScript(const char *text, const char *parameters)
  356. {
  357. // Note - we do not need (and must not have) a lock protecting this. It is protected by the Python GIL,
  358. // and if we add our own lock we are liable to deadlock as the code within Py_CompileStringFlags may
  359. // temporarily release then re-acquire the GIL.
  360. if (!compiledScripts)
  361. compiledScripts.setown(PyDict_New());
  362. OwnedPyObject code;
  363. code.set(PyDict_GetItemString(compiledScripts, text));
  364. if (!code)
  365. {
  366. code.setown(Py_CompileString(text, "", Py_eval_input)); // try compiling as simple expression...
  367. if (!code)
  368. {
  369. PyErr_Clear();
  370. PyCompilerFlags flags = { PyCF_SOURCE_IS_UTF8 };
  371. code.setown(Py_CompileStringFlags(text, "<embed>", Py_file_input, &flags)); // try compiling as global code
  372. if (!code)
  373. {
  374. PyErr_Clear();
  375. StringBuffer wrapped;
  376. wrapPythonText(wrapped, text, parameters);
  377. code.setown(Py_CompileStringFlags(wrapped, "<embed>", Py_file_input, &flags)); // try compiling as a function body
  378. }
  379. }
  380. checkPythonError();
  381. if (code)
  382. PyDict_SetItemString(compiledScripts, text, code);
  383. }
  384. return code.getClear();
  385. }
  386. PyObject *getNamedScope(const char *key, bool &isNew)
  387. {
  388. if (!preservedScopes)
  389. preservedScopes.setown(PyDict_New());
  390. OwnedPyObject scope;
  391. scope.set(PyDict_GetItemString(preservedScopes, key));
  392. if (!scope)
  393. {
  394. scope.setown(PyDict_New());
  395. PyDict_SetItemString(preservedScopes, key, scope);
  396. isNew = true;
  397. }
  398. else
  399. isNew = false;
  400. return scope.getClear();
  401. }
  402. void releaseNamedScope(const char *key)
  403. {
  404. if (preservedScopes)
  405. {
  406. PyDict_DelItemString(preservedScopes, key);
  407. PyErr_Clear(); // Should be present, but ignore the error if it is not
  408. }
  409. }
  410. static void unregister(const char *key);
  411. protected:
  412. static StringBuffer &wrapPythonText(StringBuffer &out, const char *in, const char *params)
  413. {
  414. // Complicated by needing to keep future import lines outside defined function
  415. // Per python spec, a future statement must appear near the top of the module. The only lines that can appear before a future statement are:
  416. // the module docstring (if any),
  417. // comments,
  418. // blank lines, and
  419. // other future statements.
  420. // We don't attempt to parse the python to spot these - instead, we pull all lines up to and including the last future statement out to the global scope.
  421. // Because this is a little unsophisticated it will be fooled by code that includes things that look like future statements inside multiline strings.
  422. // I don't care.
  423. StringArray lines;
  424. lines.appendList(in, "\n", false);
  425. RegExpr expr("^ *from +__future__ +import ");
  426. unsigned leadingLines = 0;
  427. ForEachItemIn(idx, lines)
  428. {
  429. if (expr.find(lines.item(idx)))
  430. leadingLines = idx+1;
  431. }
  432. for (unsigned leadingLine = 0; leadingLine < leadingLines; leadingLine++)
  433. out.append(lines.item(leadingLine)).append('\n');
  434. out.appendf("def __user__(%s):\n", params);
  435. for (unsigned line = leadingLines; line < lines.length(); line++)
  436. out.append(" ").append(lines.item(line)).append('\n');
  437. out.appendf("__result__ = __user__(%s)\n", params);
  438. return out;
  439. }
  440. PyThreadState *tstate;
  441. bool initialized;
  442. HINSTANCE pythonLibrary;
  443. OwnedPyObject namedtuple; // collections.namedtuple
  444. OwnedPyObject namedtupleTypes; // dictionary of return values from namedtuple()
  445. OwnedPyObject compiledScripts; // dictionary of previously compiled scripts
  446. OwnedPyObject preservedScopes; // dictionary of preserved scopes
  447. } globalState;
  448. MODULE_INIT(INIT_PRIORITY_STANDARD)
  449. {
  450. // Make sure we are never unloaded (as Python may crash if we are)
  451. // we do this by doing a dynamic load of the pyembed library
  452. #ifdef _WIN32
  453. HINSTANCE me = GetModuleHandle("py3embed");
  454. if (me)
  455. {
  456. char helperLibraryName[_MAX_PATH];
  457. ::GetModuleFileName(me, helperLibraryName, _MAX_PATH);
  458. if (strstr(helperLibraryName, "py3embed"))
  459. {
  460. HINSTANCE h = LoadSharedObject(helperLibraryName, false, false);
  461. DBGLOG("LoadSharedObject returned %p", h);
  462. }
  463. }
  464. #else
  465. FILE *diskfp = fopen("/proc/self/maps", "r");
  466. if (diskfp)
  467. {
  468. char ln[_MAX_PATH];
  469. while (fgets(ln, sizeof(ln), diskfp))
  470. {
  471. if (strstr(ln, "libpy3embed"))
  472. {
  473. const char *fullName = strchr(ln, '/');
  474. if (fullName)
  475. {
  476. char *tail = (char *) strstr(fullName, SharedObjectExtension);
  477. if (tail)
  478. {
  479. tail[strlen(SharedObjectExtension)] = 0;
  480. keepLoadedHandle = LoadSharedObject(fullName, false, false);
  481. break;
  482. }
  483. }
  484. }
  485. }
  486. fclose(diskfp);
  487. }
  488. #endif
  489. return true;
  490. }
  491. static void checkThreadContext()
  492. {
  493. if (!threadContext)
  494. {
  495. if (!globalState.isInitialized())
  496. rtlFail(0, "Python not initialized");
  497. threadContext = new PythonThreadContext;
  498. threadHookChain = addThreadTermFunc(releaseContext);
  499. }
  500. }
  501. PyObject *PythonThreadContext::getNamedTupleType(const RtlTypeInfo *type)
  502. {
  503. if (!lru || (type!=lrutype))
  504. {
  505. lru.setown(globalState.getNamedTupleType(type));
  506. lrutype = type;
  507. }
  508. return lru.getLink();
  509. }
  510. PyObject *PythonThreadContext::compileEmbeddedScript(size32_t lenChars, const char *utf, const char *argstring)
  511. {
  512. size32_t bytes = rtlUtf8Size(lenChars, utf);
  513. StringBuffer text(bytes, utf);
  514. if (!prevtext || strcmp(text, prevtext) != 0)
  515. {
  516. prevtext.clear();
  517. text.stripChar('\r');
  518. script.setown(globalState.compileScript(text, argstring));
  519. prevtext.set(utf, bytes);
  520. }
  521. return script.getLink();
  522. }
  523. // Conversions from Python objects to ECL data
  524. __declspec(noreturn) static void typeError(const char *expected, const RtlFieldInfo *field) __attribute__((noreturn));
  525. static void typeError(const char *expected, const RtlFieldInfo *field)
  526. {
  527. VStringBuffer msg("pyembed: type mismatch - %s expected", expected);
  528. if (field)
  529. msg.appendf(" for field %s", field->name);
  530. else
  531. msg.appendf(" for return value");
  532. rtlFail(0, msg.str());
  533. }
  534. static bool getBooleanResult(const RtlFieldInfo *field, PyObject *obj)
  535. {
  536. if (obj && obj != Py_None)
  537. {
  538. if (PyBool_Check(obj))
  539. return obj == Py_True;
  540. }
  541. typeError("boolean", field);
  542. }
  543. static void getDataResult(const RtlFieldInfo *field, PyObject *obj, size32_t &chars, void * &result)
  544. {
  545. if (obj && obj != Py_None && PyByteArray_Check(obj))
  546. rtlStrToDataX(chars, result, PyByteArray_Size(obj), PyByteArray_AsString(obj));
  547. else
  548. typeError("bytearray", field);
  549. }
  550. static double getRealResult(const RtlFieldInfo *field, PyObject *obj)
  551. {
  552. if (obj && obj != Py_None)
  553. {
  554. if (PyFloat_Check(obj))
  555. return PyFloat_AsDouble(obj);
  556. }
  557. typeError("real", field);
  558. }
  559. static __int64 getSignedResult(const RtlFieldInfo *field, PyObject *obj)
  560. {
  561. if (obj && obj != Py_None)
  562. {
  563. if (PyLong_Check(obj))
  564. return (__int64) PyLong_AsLongLong(obj);
  565. }
  566. typeError("integer", field);
  567. }
  568. static unsigned __int64 getUnsignedResult(const RtlFieldInfo *field, PyObject *obj)
  569. {
  570. if (obj && obj != Py_None)
  571. {
  572. if (PyLong_Check(obj))
  573. return (unsigned __int64) PyLong_AsUnsignedLongLong(obj);
  574. }
  575. typeError("integer", field);
  576. }
  577. static void getStringResult(const RtlFieldInfo *field, PyObject *obj, size32_t &chars, char * &result)
  578. {
  579. if (obj && obj != Py_None)
  580. {
  581. if (PyUnicode_Check(obj))
  582. {
  583. OwnedPyObject temp_bytes = PyUnicode_AsEncodedString(obj, ASCII_LIKE_CODEPAGE, "ignore");
  584. checkPythonError();
  585. const char * text = PyBytes_AsString(temp_bytes);
  586. checkPythonError();
  587. size_t lenBytes = PyBytes_Size(temp_bytes);
  588. rtlStrToStrX(chars, result, lenBytes, text);
  589. }
  590. else if (PyBytes_Check(obj))
  591. {
  592. const char * text = PyBytes_AsString(obj);
  593. checkPythonError();
  594. size_t lenBytes = PyBytes_Size(obj);
  595. rtlStrToStrX(chars, result, lenBytes, text);
  596. }
  597. return;
  598. }
  599. typeError("string", field);
  600. }
  601. static void getUTF8Result(const RtlFieldInfo *field, PyObject *obj, size32_t &chars, char * &result)
  602. {
  603. if (obj && obj != Py_None && PyUnicode_Check(obj))
  604. {
  605. Py_ssize_t lenBytes;
  606. const char *text = PyUnicode_AsUTF8AndSize(obj, &lenBytes);
  607. checkPythonError();
  608. size32_t numchars = rtlUtf8Length(lenBytes, text);
  609. rtlUtf8ToUtf8X(chars, result, numchars, text);
  610. }
  611. else
  612. typeError("unicode string", field);
  613. }
  614. static void getSetResult(PyObject *obj, bool & isAllResult, size32_t & resultBytes, void * & result, int elemType, size32_t elemSize)
  615. {
  616. // MORE - should probably recode to use the getResultDataset mechanism
  617. if (!obj || obj == Py_None || (!PyList_Check(obj) && !PySet_Check(obj)))
  618. rtlFail(0, "pyembed: type mismatch - list or set expected");
  619. rtlRowBuilder out;
  620. size32_t outBytes = 0;
  621. byte *outData = NULL;
  622. OwnedPyObject iter = PyObject_GetIter(obj);
  623. OwnedPyObject elem;
  624. for (elem.setown(PyIter_Next(iter)); elem != NULL; elem.setown(PyIter_Next(iter)))
  625. {
  626. if (elemSize != UNKNOWN_LENGTH)
  627. {
  628. out.ensureAvailable(outBytes + elemSize);
  629. outData = out.getbytes() + outBytes;
  630. outBytes += elemSize;
  631. }
  632. switch ((type_t) elemType)
  633. {
  634. case type_int:
  635. rtlWriteInt(outData, py3embed::getSignedResult(NULL, elem), elemSize);
  636. break;
  637. case type_unsigned:
  638. rtlWriteInt(outData, py3embed::getUnsignedResult(NULL, elem), elemSize);
  639. break;
  640. case type_real:
  641. if (elemSize == sizeof(double))
  642. * (double *) outData = (double) py3embed::getRealResult(NULL, elem);
  643. else
  644. {
  645. assertex(elemSize == sizeof(float));
  646. * (float *) outData = (float) py3embed::getRealResult(NULL, elem);
  647. }
  648. break;
  649. case type_boolean:
  650. assertex(elemSize == sizeof(bool));
  651. * (bool *) outData = py3embed::getBooleanResult(NULL, elem);
  652. break;
  653. case type_string:
  654. case type_varstring:
  655. {
  656. if (!PyUnicode_Check(elem))
  657. rtlFail(0, "pyembed: type mismatch - return value in list was not a STRING");
  658. OwnedPyObject temp_bytes = PyUnicode_AsEncodedString(elem, ASCII_LIKE_CODEPAGE, "ignore");
  659. checkPythonError();
  660. const char * text = PyBytes_AsString(temp_bytes);
  661. checkPythonError();
  662. size_t lenBytes = PyBytes_Size(temp_bytes);
  663. if (elemSize == UNKNOWN_LENGTH)
  664. {
  665. if (elemType == type_string)
  666. {
  667. out.ensureAvailable(outBytes + lenBytes + sizeof(size32_t));
  668. outData = out.getbytes() + outBytes;
  669. * (size32_t *) outData = lenBytes;
  670. rtlStrToStr(lenBytes, outData+sizeof(size32_t), lenBytes, text);
  671. outBytes += lenBytes + sizeof(size32_t);
  672. }
  673. else
  674. {
  675. out.ensureAvailable(outBytes + lenBytes + 1);
  676. outData = out.getbytes() + outBytes;
  677. rtlStrToVStr(0, outData, lenBytes, text);
  678. outBytes += lenBytes + 1;
  679. }
  680. }
  681. else
  682. {
  683. if (elemType == type_string)
  684. rtlStrToStr(elemSize, outData, lenBytes, text);
  685. else
  686. rtlStrToVStr(elemSize, outData, lenBytes, text); // Fixed size null terminated strings... weird.
  687. }
  688. break;
  689. }
  690. case type_unicode:
  691. case type_utf8:
  692. {
  693. if (!PyUnicode_Check(elem))
  694. rtlFail(0, "pyembed: type mismatch - return value in list was not a unicode STRING");
  695. Py_ssize_t lenBytes;
  696. const char *text = PyUnicode_AsUTF8AndSize(elem, &lenBytes);
  697. checkPythonError();
  698. size32_t numchars = rtlUtf8Length(lenBytes, text);
  699. if (elemType == type_utf8)
  700. {
  701. assertex (elemSize == UNKNOWN_LENGTH);
  702. out.ensureAvailable(outBytes + lenBytes + sizeof(size32_t));
  703. outData = out.getbytes() + outBytes;
  704. * (size32_t *) outData = numchars;
  705. rtlStrToStr(lenBytes, outData+sizeof(size32_t), lenBytes, text);
  706. outBytes += lenBytes + sizeof(size32_t);
  707. }
  708. else
  709. {
  710. if (elemSize == UNKNOWN_LENGTH)
  711. {
  712. out.ensureAvailable(outBytes + numchars*sizeof(UChar) + sizeof(size32_t));
  713. outData = out.getbytes() + outBytes;
  714. // You can't assume that number of chars in utf8 matches number in unicode16 ...
  715. size32_t numchars16;
  716. rtlDataAttr unicode16;
  717. rtlUtf8ToUnicodeX(numchars16, unicode16.refustr(), numchars, text);
  718. * (size32_t *) outData = numchars16;
  719. rtlUnicodeToUnicode(numchars16, (UChar *) (outData+sizeof(size32_t)), numchars16, unicode16.getustr());
  720. outBytes += numchars16*sizeof(UChar) + sizeof(size32_t);
  721. }
  722. else
  723. rtlUtf8ToUnicode(elemSize / sizeof(UChar), (UChar *) outData, numchars, text);
  724. }
  725. break;
  726. }
  727. case type_data:
  728. {
  729. if (!PyByteArray_Check(elem))
  730. rtlFail(0, "pyembed: type mismatch - return value in list was not a bytearray");
  731. size_t lenBytes = PyByteArray_Size(elem); // Could check does not overflow size32_t
  732. const char *data = PyByteArray_AsString(elem);
  733. if (elemSize == UNKNOWN_LENGTH)
  734. {
  735. out.ensureAvailable(outBytes + lenBytes + sizeof(size32_t));
  736. outData = out.getbytes() + outBytes;
  737. * (size32_t *) outData = lenBytes;
  738. rtlStrToData(lenBytes, outData+sizeof(size32_t), lenBytes, data);
  739. outBytes += lenBytes + sizeof(size32_t);
  740. }
  741. else
  742. rtlStrToData(elemSize, outData, lenBytes, data);
  743. break;
  744. }
  745. default:
  746. rtlFail(0, "pyembed: type mismatch - unsupported return type");
  747. break;
  748. }
  749. checkPythonError();
  750. }
  751. isAllResult = false;
  752. resultBytes = outBytes;
  753. result = out.detachdata();
  754. }
  755. static void getUnicodeResult(const RtlFieldInfo *field, PyObject *obj, size32_t &chars, UChar * &result)
  756. {
  757. if (obj && obj != Py_None && PyUnicode_Check(obj))
  758. {
  759. Py_ssize_t lenBytes;
  760. const char *text = PyUnicode_AsUTF8AndSize(obj, &lenBytes);
  761. checkPythonError();
  762. size32_t numchars = rtlUtf8Length(lenBytes, text);
  763. rtlUtf8ToUnicodeX(chars, result, numchars, text);
  764. }
  765. else
  766. typeError("unicode string", field);
  767. }
  768. // A PythonRowBuilder object is used to construct an ECL row from a python object
  769. class PythonRowBuilder : public CInterfaceOf<IFieldSource>
  770. {
  771. public:
  772. PythonRowBuilder(PyObject *_row)
  773. : iter(NULL), elem(NULL), named(false)
  774. {
  775. pushback.set(_row);
  776. }
  777. virtual bool getBooleanResult(const RtlFieldInfo *field)
  778. {
  779. nextField(field);
  780. return py3embed::getBooleanResult(field, elem);
  781. }
  782. virtual void getDataResult(const RtlFieldInfo *field, size32_t &len, void * &result)
  783. {
  784. nextField(field);
  785. py3embed::getDataResult(field, elem, len, result);
  786. }
  787. virtual double getRealResult(const RtlFieldInfo *field)
  788. {
  789. nextField(field);
  790. return py3embed::getRealResult(field, elem);
  791. }
  792. virtual __int64 getSignedResult(const RtlFieldInfo *field)
  793. {
  794. nextField(field);
  795. return py3embed::getSignedResult(field, elem);
  796. }
  797. virtual unsigned __int64 getUnsignedResult(const RtlFieldInfo *field)
  798. {
  799. nextField(field);
  800. return py3embed::getUnsignedResult(field, elem);
  801. }
  802. virtual void getStringResult(const RtlFieldInfo *field, size32_t &chars, char * &result)
  803. {
  804. nextField(field);
  805. py3embed::getStringResult(field, elem, chars, result);
  806. }
  807. virtual void getUTF8Result(const RtlFieldInfo *field, size32_t &chars, char * &result)
  808. {
  809. nextField(field);
  810. py3embed::getUTF8Result(field, elem, chars, result);
  811. }
  812. virtual void getUnicodeResult(const RtlFieldInfo *field, size32_t &chars, UChar * &result)
  813. {
  814. nextField(field);
  815. py3embed::getUnicodeResult(field, elem, chars, result);
  816. }
  817. virtual void getDecimalResult(const RtlFieldInfo *field, Decimal &value)
  818. {
  819. nextField(field);
  820. double ret = py3embed::getRealResult(field, elem);
  821. value.setReal(ret);
  822. }
  823. virtual void processBeginSet(const RtlFieldInfo * field, bool &isAll)
  824. {
  825. nextField(field);
  826. isAll = false; // No concept of an 'all' set in Python
  827. if (!elem || elem == Py_None || (!PyList_Check(elem) && !PySet_Check(elem)))
  828. typeError("list or set", field);
  829. push();
  830. }
  831. virtual bool processNextSet(const RtlFieldInfo * field)
  832. {
  833. nextField(NULL);
  834. pushback.setown(elem.getClear());
  835. return pushback != NULL;
  836. }
  837. virtual void processBeginDataset(const RtlFieldInfo * field)
  838. {
  839. nextField(field);
  840. if (!PyList_Check(elem))
  841. typeError("list", field);
  842. push();
  843. }
  844. virtual void processBeginRow(const RtlFieldInfo * field)
  845. {
  846. // Expect to see a tuple here, or possibly (if the ECL record has a single field), an arbitrary scalar object
  847. // If it's a tuple, we push it onto our stack as the active object
  848. nextField(field);
  849. if (!PyTuple_Check(elem))
  850. {
  851. if (countFields(field->type->queryFields())==1)
  852. {
  853. // Python doesn't seem to support the concept of a tuple containing a single element.
  854. // If we are expecting a single field in our row, then the 'tuple' layer will be missing
  855. elem.setown(PyTuple_Pack(1, elem.get()));
  856. }
  857. else
  858. typeError("tuple", field);
  859. }
  860. push();
  861. }
  862. virtual bool processNextRow(const RtlFieldInfo * field)
  863. {
  864. nextField(NULL);
  865. pushback.setown(elem.getClear());
  866. return pushback != NULL;
  867. }
  868. virtual void processEndSet(const RtlFieldInfo * field)
  869. {
  870. pop();
  871. }
  872. virtual void processEndDataset(const RtlFieldInfo * field)
  873. {
  874. pop();
  875. }
  876. virtual void processEndRow(const RtlFieldInfo * field)
  877. {
  878. pop();
  879. }
  880. protected:
  881. void pop()
  882. {
  883. iter.setown((PyObject *) iterStack.popGet());
  884. parent.setown((PyObject *) parentStack.popGet());
  885. named = namedStack.popGet();
  886. elem.clear();
  887. }
  888. void push()
  889. {
  890. iterStack.append(iter.getClear());
  891. parentStack.append(parent.getClear());
  892. namedStack.append(named);
  893. parent.set(elem);
  894. iter.setown(PyObject_GetIter(elem));
  895. named = isNamedTuple(elem);
  896. elem.clear();
  897. }
  898. bool isNamedTuple(PyObject *obj)
  899. {
  900. return PyObject_HasAttrString((PyObject *) obj->ob_type, "_fields");
  901. }
  902. void nextField(const RtlFieldInfo * field)
  903. {
  904. if (pushback)
  905. elem.setown(pushback.getClear());
  906. else if (field && named) // If it's named tuple, expect to always resolve fields by name, not position
  907. {
  908. elem.setown(PyObject_GetAttrString(parent, field->name));
  909. }
  910. else if (iter)
  911. elem.setown(PyIter_Next(iter));
  912. else
  913. elem = NULL;
  914. checkPythonError();
  915. }
  916. OwnedPyObject iter;
  917. OwnedPyObject pushback;
  918. OwnedPyObject elem;
  919. OwnedPyObject parent;
  920. bool named;
  921. PointerArray iterStack;
  922. PointerArray parentStack;
  923. BoolArray namedStack;
  924. };
  925. static size32_t getRowResult(PyObject *result, ARowBuilder &builder)
  926. {
  927. PythonRowBuilder pyRowBuilder(result);
  928. const RtlTypeInfo *typeInfo = builder.queryAllocator()->queryOutputMeta()->queryTypeInfo();
  929. assertex(typeInfo);
  930. RtlFieldStrInfo dummyField("<row>", NULL, typeInfo);
  931. return typeInfo->build(builder, 0, &dummyField, pyRowBuilder);
  932. }
  933. // A PythonNamedTupleBuilder object is used to construct a Python named tuple from an ECL row
  934. class PythonNamedTupleBuilder : public CInterfaceOf<IFieldProcessor>
  935. {
  936. public:
  937. PythonNamedTupleBuilder(PythonThreadContext *_sharedCtx, const RtlFieldInfo *_outerRow)
  938. : outerRow(_outerRow), sharedCtx(_sharedCtx)
  939. {
  940. }
  941. virtual void processString(unsigned len, const char *value, const RtlFieldInfo * field)
  942. {
  943. addArg(PyUnicode_FromStringAndSize(value, len));
  944. }
  945. virtual void processBool(bool value, const RtlFieldInfo * field)
  946. {
  947. addArg(PyBool_FromLong(value ? 1 : 0));
  948. }
  949. virtual void processData(unsigned len, const void *value, const RtlFieldInfo * field)
  950. {
  951. addArg(PyByteArray_FromStringAndSize((const char *) value, len));
  952. }
  953. virtual void processInt(__int64 value, const RtlFieldInfo * field)
  954. {
  955. addArg(PyLong_FromLongLong(value));
  956. }
  957. virtual void processUInt(unsigned __int64 value, const RtlFieldInfo * field)
  958. {
  959. addArg(PyLong_FromUnsignedLongLong(value));
  960. }
  961. virtual void processReal(double value, const RtlFieldInfo * field)
  962. {
  963. addArg(PyFloat_FromDouble(value));
  964. }
  965. virtual void processDecimal(const void *value, unsigned digits, unsigned precision, const RtlFieldInfo * field)
  966. {
  967. Decimal val;
  968. val.setDecimal(digits, precision, value);
  969. addArg(PyFloat_FromDouble(val.getReal()));
  970. }
  971. virtual void processUDecimal(const void *value, unsigned digits, unsigned precision, const RtlFieldInfo * field)
  972. {
  973. Decimal val;
  974. val.setUDecimal(digits, precision, value);
  975. addArg(PyFloat_FromDouble(val.getReal()));
  976. }
  977. virtual void processUnicode(unsigned len, const UChar *value, const RtlFieldInfo * field)
  978. {
  979. // You don't really know what size Py_UNICODE is (varies from system to system), so go via utf8
  980. unsigned unicodeChars;
  981. rtlDataAttr unicode;
  982. rtlUnicodeToUtf8X(unicodeChars, unicode.refstr(), len, value);
  983. processUtf8(unicodeChars, unicode.getstr(), field);
  984. }
  985. virtual void processQString(unsigned len, const char *value, const RtlFieldInfo * field)
  986. {
  987. size32_t charCount;
  988. rtlDataAttr text;
  989. rtlQStrToStrX(charCount, text.refstr(), len, value);
  990. processString(charCount, text.getstr(), field);
  991. }
  992. virtual void processUtf8(unsigned len, const char *value, const RtlFieldInfo * field)
  993. {
  994. size32_t sizeBytes = rtlUtf8Size(len, value);
  995. PyObject *vval = PyUnicode_FromStringAndSize(value, sizeBytes); // NOTE - requires size in bytes not chars
  996. checkPythonError();
  997. addArg(vval);
  998. }
  999. virtual bool processBeginSet(const RtlFieldInfo * field, unsigned numElements, bool isAll, const byte *data)
  1000. {
  1001. push();
  1002. if (isAll)
  1003. rtlFail(0, "pyembed: ALL sets are not supported");
  1004. return true;
  1005. }
  1006. virtual bool processBeginDataset(const RtlFieldInfo * field, unsigned numRows)
  1007. {
  1008. push();
  1009. return true;
  1010. }
  1011. virtual bool processBeginRow(const RtlFieldInfo * field)
  1012. {
  1013. if (field != outerRow)
  1014. push();
  1015. return true;
  1016. }
  1017. virtual void processEndSet(const RtlFieldInfo * field)
  1018. {
  1019. pop();
  1020. }
  1021. virtual void processEndDataset(const RtlFieldInfo * field)
  1022. {
  1023. pop();
  1024. }
  1025. virtual void processEndRow(const RtlFieldInfo * field)
  1026. {
  1027. if (field != outerRow)
  1028. {
  1029. args.setown(getTuple(field->type));
  1030. pop();
  1031. }
  1032. }
  1033. PyObject *getTuple(const RtlTypeInfo *type)
  1034. {
  1035. OwnedPyObject mynamedtupletype = sharedCtx ? sharedCtx->getNamedTupleType(type) : globalState.getNamedTupleType(type);
  1036. OwnedPyObject argsTuple = PyList_AsTuple(args);
  1037. OwnedPyObject mynamedtuple = PyObject_CallObject(mynamedtupletype, argsTuple); // Creates a namedtuple from the supplied tuple
  1038. checkPythonError();
  1039. return mynamedtuple.getClear();
  1040. }
  1041. protected:
  1042. void push()
  1043. {
  1044. stack.append(args.getClear());
  1045. args.setown(PyList_New(0));
  1046. }
  1047. void pop()
  1048. {
  1049. OwnedPyObject arg = args.getClear();
  1050. args.setown((PyObject *) stack.popGet());
  1051. addArg(arg.getClear());
  1052. }
  1053. void addArg(PyObject *arg)
  1054. {
  1055. if (!args)
  1056. {
  1057. args.setown(PyList_New(0));
  1058. }
  1059. PyList_Append(args, arg);
  1060. Py_DECREF(arg);
  1061. }
  1062. OwnedPyObject args;
  1063. PointerArray stack;
  1064. const RtlFieldInfo *outerRow;
  1065. PythonThreadContext *sharedCtx;
  1066. };
  1067. //----------------------------------------------------------------------
  1068. // Wrap an IRowStream into a Python generator
  1069. struct ECLDatasetIterator
  1070. {
  1071. PyObject_HEAD;
  1072. const RtlTypeInfo *typeInfo; // Not linked (or linkable)
  1073. IRowStream * val; // Linked
  1074. };
  1075. PyObject* ECLDatasetIterator_iter(PyObject *self)
  1076. {
  1077. Py_INCREF(self);
  1078. return self;
  1079. }
  1080. void ECLDatasetIterator_dealloc(PyObject *self)
  1081. {
  1082. ECLDatasetIterator *p = (ECLDatasetIterator *)self;
  1083. if (p->val)
  1084. {
  1085. p->val->stop();
  1086. ::Release(p->val);
  1087. p->val = NULL;
  1088. }
  1089. self->ob_type->tp_free(self);
  1090. }
  1091. PyObject* ECLDatasetIterator_iternext(PyObject *self)
  1092. {
  1093. ECLDatasetIterator *p = (ECLDatasetIterator *)self;
  1094. if (p->val)
  1095. {
  1096. roxiemem::OwnedConstRoxieRow nextRow = p->val->ungroupedNextRow();
  1097. if (!nextRow)
  1098. {
  1099. p->val->stop();
  1100. ::Release(p->val);
  1101. p->val = NULL;
  1102. }
  1103. else
  1104. {
  1105. RtlFieldStrInfo dummyField("<row>", NULL, p->typeInfo);
  1106. PythonNamedTupleBuilder tupleBuilder(NULL, &dummyField);
  1107. const byte *brow = (const byte *) nextRow.get();
  1108. p->typeInfo->process(brow, brow, &dummyField, tupleBuilder);
  1109. return tupleBuilder.getTuple(p->typeInfo);
  1110. }
  1111. }
  1112. // If we get here, it's EOF
  1113. PyErr_SetNone(PyExc_StopIteration);
  1114. return NULL;
  1115. }
  1116. static PyTypeObject ECLDatasetIteratorType =
  1117. {
  1118. PyVarObject_HEAD_INIT(NULL, 0)
  1119. "ECLDatasetIterator._MyIter", /*tp_name*/
  1120. sizeof(ECLDatasetIterator), /*tp_basicsize*/
  1121. 0, /*tp_itemsize*/
  1122. ECLDatasetIterator_dealloc, /*tp_dealloc*/
  1123. 0, /*tp_print*/
  1124. 0, /*tp_getattr*/
  1125. 0, /*tp_setattr*/
  1126. 0, /*tp_compare*/
  1127. 0, /*tp_repr*/
  1128. 0, /*tp_as_number*/
  1129. 0, /*tp_as_sequence*/
  1130. 0, /*tp_as_mapping*/
  1131. 0, /*tp_hash */
  1132. 0, /*tp_call*/
  1133. 0, /*tp_str*/
  1134. 0, /*tp_getattro*/
  1135. 0, /*tp_setattro*/
  1136. 0, /*tp_as_buffer*/
  1137. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_ITER, /* tp_flags: tell python to use tp_iter and tp_iternext fields. */
  1138. "ECL dataset iterator object.", /* tp_doc */
  1139. 0, /* tp_traverse */
  1140. 0, /* tp_clear */
  1141. 0, /* tp_richcompare */
  1142. 0, /* tp_weaklistoffset */
  1143. ECLDatasetIterator_iter, /* tp_iter: __iter__() method */
  1144. ECLDatasetIterator_iternext /* tp_iternext: next() method */
  1145. };
  1146. static PyObject *createECLDatasetIterator(const RtlTypeInfo *_typeInfo, IRowStream * _val)
  1147. {
  1148. ECLDatasetIteratorType.tp_new = PyType_GenericNew;
  1149. if (PyType_Ready(&ECLDatasetIteratorType) < 0) return NULL;
  1150. ECLDatasetIterator *p = PyObject_New(ECLDatasetIterator, &ECLDatasetIteratorType);
  1151. if (!p)
  1152. {
  1153. checkPythonError();
  1154. rtlFail(0, "pyembed: failed to create dataset iterator");
  1155. }
  1156. p->typeInfo = _typeInfo;
  1157. p->val = _val;
  1158. return (PyObject *)p;
  1159. }
  1160. //-----------------------------------------------------
  1161. // GILBlock ensures the we hold the Python "Global interpreter lock" for the appropriate duration
  1162. class GILBlock
  1163. {
  1164. public:
  1165. GILBlock(PyThreadState * &_state) : state(_state)
  1166. {
  1167. PyEval_RestoreThread(state);
  1168. }
  1169. ~GILBlock()
  1170. {
  1171. state = PyEval_SaveThread();
  1172. }
  1173. private:
  1174. PyThreadState * &state;
  1175. };
  1176. void Python3xGlobalState::unregister(const char *key)
  1177. {
  1178. checkThreadContext();
  1179. GILBlock b(threadContext->threadState);
  1180. globalState.releaseNamedScope(key);
  1181. }
  1182. // A Python function that returns a dataset will return a PythonRowStream object that can be
  1183. // interrogated to return each row of the result in turn
  1184. class PythonRowStream : public CInterfaceOf<IRowStream>
  1185. {
  1186. public:
  1187. PythonRowStream(PyObject *result, IEngineRowAllocator *_resultAllocator)
  1188. : resultIterator(NULL)
  1189. {
  1190. // NOTE - the caller should already have the GIL lock before creating me
  1191. if (!result || result == Py_None)
  1192. typeError("list or generator", NULL);
  1193. resultIterator.setown(PyObject_GetIter(result)); // We allow anything that is iterable to be returned for a row stream
  1194. checkPythonError();
  1195. resultAllocator.set(_resultAllocator);
  1196. }
  1197. ~PythonRowStream()
  1198. {
  1199. if (resultIterator)
  1200. {
  1201. checkThreadContext();
  1202. GILBlock b(threadContext->threadState);
  1203. resultIterator.clear();
  1204. }
  1205. }
  1206. virtual const void *nextRow()
  1207. {
  1208. checkThreadContext();
  1209. GILBlock b(threadContext->threadState);
  1210. if (!resultIterator)
  1211. return NULL;
  1212. OwnedPyObject row = PyIter_Next(resultIterator);
  1213. if (!row)
  1214. return NULL;
  1215. RtlDynamicRowBuilder rowBuilder(resultAllocator);
  1216. size32_t len = py3embed::getRowResult(row, rowBuilder);
  1217. return rowBuilder.finalizeRowClear(len);
  1218. }
  1219. virtual void stop()
  1220. {
  1221. checkThreadContext();
  1222. GILBlock b(threadContext->threadState);
  1223. resultAllocator.clear();
  1224. resultIterator.clear();
  1225. }
  1226. protected:
  1227. Linked<IEngineRowAllocator> resultAllocator;
  1228. OwnedPyObject resultIterator;
  1229. };
  1230. // Each call to a Python function will use a new Python3xEmbedFunctionContext object
  1231. // This takes care of ensuring that the Python GIL is locked while we are executing python code,
  1232. // and released when we are not
  1233. class Python3xEmbedContextBase : public CInterfaceOf<IEmbedFunctionContext>
  1234. {
  1235. public:
  1236. Python3xEmbedContextBase(PythonThreadContext *_sharedCtx)
  1237. : sharedCtx(_sharedCtx)
  1238. {
  1239. PyEval_RestoreThread(sharedCtx->threadState);
  1240. }
  1241. void setScopes(ICodeContext *codeCtx, const char *_options)
  1242. {
  1243. locals.setown(PyDict_New());
  1244. StringArray options;
  1245. options.appendList(_options, ",");
  1246. StringBuffer scopeKey;
  1247. const char *scopeKey2 = nullptr;
  1248. bool registerCallback = false;
  1249. bool wuidScope = false;
  1250. IEngineContext *engine = nullptr;
  1251. ForEachItemIn(idx, options)
  1252. {
  1253. const char *opt = options.item(idx);
  1254. const char *val = strchr(opt, '=');
  1255. if (val)
  1256. {
  1257. StringBuffer optName(val-opt, opt);
  1258. val++;
  1259. if (strieq(optName, "globalscope"))
  1260. scopeKey2 = val;
  1261. else if (strieq(optName, "persist"))
  1262. {
  1263. if (scopeKey.length())
  1264. failx("persist option specified more than once");
  1265. if (strieq(val, "global"))
  1266. scopeKey.append("global");
  1267. else if (strieq(val, "workunit"))
  1268. {
  1269. engine = codeCtx->queryEngineContext();
  1270. wuidScope = true;
  1271. if (!engine)
  1272. failx("Persist mode 'workunit' not supported here");
  1273. }
  1274. else if (strieq(val, "query"))
  1275. {
  1276. engine = codeCtx->queryEngineContext();
  1277. wuidScope = false;
  1278. if (!engine)
  1279. failx("Persist mode 'query' not supported here");
  1280. }
  1281. else
  1282. failx("Unrecognized persist mode %s", val);
  1283. }
  1284. else
  1285. failx("Unrecognized option %s", optName.str());
  1286. }
  1287. else
  1288. failx("Unrecognized option %s", opt);
  1289. }
  1290. if (engine)
  1291. engine->getQueryId(scopeKey, wuidScope);
  1292. if (scopeKey2)
  1293. scopeKey.append(':').append(scopeKey2);
  1294. if (scopeKey.length())
  1295. {
  1296. bool isNew;
  1297. globals.setown(globalState.getNamedScope(scopeKey, isNew));
  1298. if (isNew && engine)
  1299. engine->onTermination(Python3xGlobalState::unregister, scopeKey.str(), wuidScope);
  1300. }
  1301. else
  1302. globals.setown(PyDict_New());
  1303. PyDict_SetItemString(globals, "__builtins__", PyEval_GetBuiltins()); // required for import to work
  1304. }
  1305. ~Python3xEmbedContextBase()
  1306. {
  1307. // We need to clear these before calling savethread, or we won't own the GIL
  1308. locals.clear();
  1309. globals.clear();
  1310. result.clear();
  1311. script.clear();
  1312. sharedCtx->threadState = PyEval_SaveThread();
  1313. }
  1314. virtual bool getBooleanResult()
  1315. {
  1316. return py3embed::getBooleanResult(NULL, result);
  1317. }
  1318. virtual void getDataResult(size32_t &__chars, void * &__result)
  1319. {
  1320. py3embed::getDataResult(NULL, result, __chars, __result);
  1321. }
  1322. virtual double getRealResult()
  1323. {
  1324. return py3embed::getRealResult(NULL, result);
  1325. }
  1326. virtual __int64 getSignedResult()
  1327. {
  1328. return py3embed::getSignedResult(NULL, result);
  1329. }
  1330. virtual unsigned __int64 getUnsignedResult()
  1331. {
  1332. return py3embed::getUnsignedResult(NULL, result);
  1333. }
  1334. virtual void getStringResult(size32_t &__chars, char * &__result)
  1335. {
  1336. py3embed::getStringResult(NULL, result, __chars, __result);
  1337. }
  1338. virtual void getUTF8Result(size32_t &__chars, char * &__result)
  1339. {
  1340. py3embed::getUTF8Result(NULL, result, __chars, __result);
  1341. }
  1342. virtual void getUnicodeResult(size32_t &__chars, UChar * &__result)
  1343. {
  1344. py3embed::getUnicodeResult(NULL, result, __chars, __result);
  1345. }
  1346. virtual void getSetResult(bool & __isAllResult, size32_t & __resultBytes, void * & __result, int elemType, size32_t elemSize)
  1347. {
  1348. py3embed::getSetResult(result, __isAllResult, __resultBytes, __result, elemType, elemSize);
  1349. }
  1350. virtual IRowStream *getDatasetResult(IEngineRowAllocator * _resultAllocator)
  1351. {
  1352. return new PythonRowStream(result, _resultAllocator);
  1353. }
  1354. virtual byte * getRowResult(IEngineRowAllocator * _resultAllocator)
  1355. {
  1356. RtlDynamicRowBuilder rowBuilder(_resultAllocator);
  1357. size32_t len = py3embed::getRowResult(result, rowBuilder);
  1358. return (byte *) rowBuilder.finalizeRowClear(len);
  1359. }
  1360. virtual size32_t getTransformResult(ARowBuilder & builder)
  1361. {
  1362. return py3embed::getRowResult(result, builder);
  1363. }
  1364. virtual void bindBooleanParam(const char *name, bool val)
  1365. {
  1366. addArg(name, PyBool_FromLong(val ? 1 : 0));
  1367. }
  1368. virtual void bindDataParam(const char *name, size32_t len, const void *val)
  1369. {
  1370. addArg(name, PyByteArray_FromStringAndSize((const char *) val, len));
  1371. }
  1372. virtual void bindFloatParam(const char *name, float val)
  1373. {
  1374. addArg(name, PyFloat_FromDouble((double) val));
  1375. }
  1376. virtual void bindRealParam(const char *name, double val)
  1377. {
  1378. addArg(name, PyFloat_FromDouble(val));
  1379. }
  1380. virtual void bindSignedSizeParam(const char *name, int size, __int64 val)
  1381. {
  1382. addArg(name, PyLong_FromLongLong(val));
  1383. }
  1384. virtual void bindSignedParam(const char *name, __int64 val)
  1385. {
  1386. addArg(name, PyLong_FromLongLong(val));
  1387. }
  1388. virtual void bindUnsignedSizeParam(const char *name, int size, unsigned __int64 val)
  1389. {
  1390. addArg(name, PyLong_FromUnsignedLongLong(val));
  1391. }
  1392. virtual void bindUnsignedParam(const char *name, unsigned __int64 val)
  1393. {
  1394. addArg(name, PyLong_FromUnsignedLongLong(val));
  1395. }
  1396. virtual void bindStringParam(const char *name, size32_t len, const char *val)
  1397. {
  1398. addArg(name, PyUnicode_Decode(val, len, ASCII_LIKE_CODEPAGE, "ignore"));
  1399. }
  1400. virtual void bindVStringParam(const char *name, const char *val)
  1401. {
  1402. addArg(name, PyUnicode_FromString(val));
  1403. }
  1404. virtual void bindUTF8Param(const char *name, size32_t chars, const char *val)
  1405. {
  1406. size32_t sizeBytes = rtlUtf8Size(chars, val);
  1407. PyObject *vval = PyUnicode_FromStringAndSize(val, sizeBytes); // NOTE - requires size in bytes not chars
  1408. checkPythonError();
  1409. addArg(name, vval);
  1410. }
  1411. virtual void bindUnicodeParam(const char *name, size32_t chars, const UChar *val)
  1412. {
  1413. // You don't really know what size Py_UNICODE is (varies from system to system), so go via utf8
  1414. unsigned unicodeChars;
  1415. char *unicode;
  1416. rtlUnicodeToUtf8X(unicodeChars, unicode, chars, val);
  1417. size32_t sizeBytes = rtlUtf8Size(unicodeChars, unicode);
  1418. PyObject *vval = PyUnicode_FromStringAndSize(unicode, sizeBytes); // NOTE - requires size in bytes not chars
  1419. checkPythonError();
  1420. addArg(name, vval);
  1421. rtlFree(unicode);
  1422. }
  1423. virtual void bindSetParam(const char *name, int elemType, size32_t elemSize, bool isAll, size32_t totalBytes, const void *setData)
  1424. {
  1425. if (isAll)
  1426. rtlFail(0, "pyembed: Cannot pass ALL");
  1427. type_t typecode = (type_t) elemType;
  1428. const byte *inData = (const byte *) setData;
  1429. const byte *endData = inData + totalBytes;
  1430. OwnedPyObject vval = PyList_New(0);
  1431. while (inData < endData)
  1432. {
  1433. OwnedPyObject thisElem;
  1434. size32_t thisSize = elemSize;
  1435. switch (typecode)
  1436. {
  1437. case type_int:
  1438. thisElem.setown(PyLong_FromLongLong(rtlReadInt(inData, elemSize)));
  1439. break;
  1440. case type_unsigned:
  1441. thisElem.setown(PyLong_FromUnsignedLongLong(rtlReadUInt(inData, elemSize)));
  1442. break;
  1443. case type_varstring:
  1444. {
  1445. size32_t numChars = strlen((const char *) inData);
  1446. thisElem.setown(PyUnicode_FromStringAndSize((const char *) inData, numChars));
  1447. if (elemSize == UNKNOWN_LENGTH)
  1448. thisSize = numChars + 1;
  1449. break;
  1450. }
  1451. case type_string:
  1452. if (elemSize == UNKNOWN_LENGTH)
  1453. {
  1454. thisSize = * (size32_t *) inData;
  1455. inData += sizeof(size32_t);
  1456. }
  1457. thisElem.setown(PyUnicode_FromStringAndSize((const char *) inData, thisSize));
  1458. break;
  1459. case type_real:
  1460. if (elemSize == sizeof(double))
  1461. thisElem.setown(PyFloat_FromDouble(* (double *) inData));
  1462. else
  1463. thisElem.setown(PyFloat_FromDouble(* (float *) inData));
  1464. break;
  1465. case type_boolean:
  1466. assertex(elemSize == sizeof(bool));
  1467. thisElem.setown(PyBool_FromLong(*(bool*)inData ? 1 : 0));
  1468. break;
  1469. case type_unicode:
  1470. {
  1471. if (elemSize == UNKNOWN_LENGTH)
  1472. {
  1473. thisSize = (* (size32_t *) inData) * sizeof(UChar); // NOTE - it's in chars...
  1474. inData += sizeof(size32_t);
  1475. }
  1476. unsigned unicodeChars;
  1477. rtlDataAttr unicode;
  1478. rtlUnicodeToUtf8X(unicodeChars, unicode.refstr(), thisSize / sizeof(UChar), (const UChar *) inData);
  1479. size32_t sizeBytes = rtlUtf8Size(unicodeChars, unicode.getstr());
  1480. thisElem.setown(PyUnicode_FromStringAndSize(unicode.getstr(), sizeBytes)); // NOTE - requires size in bytes not chars
  1481. checkPythonError();
  1482. break;
  1483. }
  1484. case type_utf8:
  1485. {
  1486. assertex (elemSize == UNKNOWN_LENGTH);
  1487. size32_t numChars = * (size32_t *) inData;
  1488. inData += sizeof(size32_t);
  1489. thisSize = rtlUtf8Size(numChars, inData);
  1490. thisElem.setown(PyUnicode_FromStringAndSize((const char *) inData, thisSize)); // NOTE - requires size in bytes not chars
  1491. break;
  1492. }
  1493. case type_data:
  1494. if (elemSize == UNKNOWN_LENGTH)
  1495. {
  1496. thisSize = * (size32_t *) inData;
  1497. inData += sizeof(size32_t);
  1498. }
  1499. thisElem.setown(PyByteArray_FromStringAndSize((const char *) inData, thisSize));
  1500. break;
  1501. }
  1502. checkPythonError();
  1503. inData += thisSize;
  1504. PyList_Append(vval, thisElem);
  1505. }
  1506. addArg(name, vval.getLink());
  1507. }
  1508. virtual void bindRowParam(const char *name, IOutputMetaData & metaVal, const byte *val) override
  1509. {
  1510. const RtlTypeInfo *typeInfo = metaVal.queryTypeInfo();
  1511. assertex(typeInfo);
  1512. RtlFieldStrInfo dummyField("<row>", NULL, typeInfo);
  1513. PythonNamedTupleBuilder tupleBuilder(sharedCtx, &dummyField);
  1514. typeInfo->process(val, val, &dummyField, tupleBuilder); // Creates a tuple from the incoming ECL row
  1515. addArg(name, tupleBuilder.getTuple(typeInfo));
  1516. }
  1517. virtual void bindDatasetParam(const char *name, IOutputMetaData & metaVal, IRowStream * val)
  1518. {
  1519. addArg(name, createECLDatasetIterator(metaVal.queryTypeInfo(), LINK(val)));
  1520. }
  1521. protected:
  1522. virtual void addArg(const char *name, PyObject *arg) = 0;
  1523. PythonThreadContext *sharedCtx;
  1524. OwnedPyObject locals;
  1525. OwnedPyObject globals;
  1526. OwnedPyObject result;
  1527. OwnedPyObject script;
  1528. };
  1529. class Python3xEmbedScriptContext : public Python3xEmbedContextBase
  1530. {
  1531. public:
  1532. Python3xEmbedScriptContext(PythonThreadContext *_sharedCtx)
  1533. : Python3xEmbedContextBase(_sharedCtx)
  1534. {
  1535. }
  1536. ~Python3xEmbedScriptContext()
  1537. {
  1538. }
  1539. virtual IInterface *bindParamWriter(IInterface *esdl, const char *esdlservice, const char *esdltype, const char *name)
  1540. {
  1541. return NULL;
  1542. }
  1543. virtual void paramWriterCommit(IInterface *writer)
  1544. {
  1545. }
  1546. virtual void writeResult(IInterface *esdl, const char *esdlservice, const char *esdltype, IInterface *writer)
  1547. {
  1548. }
  1549. virtual void importFunction(size32_t lenChars, const char *text)
  1550. {
  1551. throwUnexpected();
  1552. }
  1553. virtual void compileEmbeddedScript(size32_t lenChars, const char *utf)
  1554. {
  1555. script.setown(sharedCtx->compileEmbeddedScript(lenChars, utf, argstring));
  1556. }
  1557. virtual void callFunction()
  1558. {
  1559. result.setown(PyEval_EvalCode(script.get(), globals, locals));
  1560. checkPythonError();
  1561. if (!result || result == Py_None)
  1562. result.set(PyDict_GetItemString(globals, "__result__"));
  1563. if (!result || result == Py_None)
  1564. result.set(PyDict_GetItemString(locals, "__result__"));
  1565. }
  1566. protected:
  1567. virtual void addArg(const char *name, PyObject *arg)
  1568. {
  1569. if (!arg)
  1570. return;
  1571. if (argstring.length())
  1572. argstring.append(',');
  1573. argstring.append(name);
  1574. if (script)
  1575. PyDict_SetItemString(globals, name, arg); // Back compatibility - if compiler did not recognize the prebind flag, we need to use globals
  1576. else
  1577. PyDict_SetItemString(locals, name, arg);
  1578. Py_DECREF(arg);
  1579. checkPythonError();
  1580. }
  1581. StringBuffer argstring;
  1582. };
  1583. class Python3xEmbedImportContext : public Python3xEmbedContextBase
  1584. {
  1585. public:
  1586. Python3xEmbedImportContext(PythonThreadContext *_sharedCtx)
  1587. : Python3xEmbedContextBase(_sharedCtx)
  1588. {
  1589. argcount = 0;
  1590. }
  1591. ~Python3xEmbedImportContext()
  1592. {
  1593. }
  1594. virtual IInterface *bindParamWriter(IInterface *esdl, const char *esdlservice, const char *esdltype, const char *name)
  1595. {
  1596. return NULL;
  1597. }
  1598. virtual void paramWriterCommit(IInterface *writer)
  1599. {
  1600. }
  1601. virtual void writeResult(IInterface *esdl, const char *esdlservice, const char *esdltype, IInterface *writer)
  1602. {
  1603. }
  1604. virtual void importFunction(size32_t lenChars, const char *utf)
  1605. {
  1606. script.setown(sharedCtx->importFunction(lenChars, utf));
  1607. }
  1608. virtual void compileEmbeddedScript(size32_t len, const char *text)
  1609. {
  1610. throwUnexpected();
  1611. }
  1612. virtual void callFunction()
  1613. {
  1614. result.setown(PyObject_CallObject(script, args));
  1615. checkPythonError();
  1616. }
  1617. private:
  1618. virtual void addArg(const char *name, PyObject *arg)
  1619. {
  1620. if (argcount)
  1621. _PyTuple_Resize(args.ref(), argcount+1);
  1622. else
  1623. args.setown(PyTuple_New(1));
  1624. PyTuple_SET_ITEM((PyTupleObject *) args.get(), argcount++, arg); // Note - 'steals' the arg reference
  1625. }
  1626. int argcount;
  1627. OwnedPyObject args;
  1628. };
  1629. class Python3xEmbedContext : public CInterfaceOf<IEmbedContext>
  1630. {
  1631. public:
  1632. virtual IEmbedFunctionContext *createFunctionContext(unsigned flags, const char *options)
  1633. {
  1634. return createFunctionContextEx(NULL, flags, options);
  1635. }
  1636. virtual IEmbedFunctionContext *createFunctionContextEx(ICodeContext * ctx, unsigned flags, const char *options)
  1637. {
  1638. checkThreadContext();
  1639. Owned<Python3xEmbedContextBase> ret;
  1640. if (flags & EFimport)
  1641. ret.setown(new Python3xEmbedImportContext(threadContext));
  1642. else
  1643. ret.setown(new Python3xEmbedScriptContext(threadContext));
  1644. ret->setScopes(ctx, options);
  1645. return ret.getClear();
  1646. }
  1647. virtual IEmbedServiceContext *createServiceContext(const char *service, unsigned flags, const char *options)
  1648. {
  1649. throwUnexpected();
  1650. }
  1651. };
  1652. extern DECL_EXPORT IEmbedContext* getEmbedContext()
  1653. {
  1654. return new Python3xEmbedContext;
  1655. }
  1656. extern DECL_EXPORT bool syntaxCheck(const char *script)
  1657. {
  1658. return true; // MORE
  1659. }
  1660. } // namespace