thorplugin.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584
  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 "jexcept.hpp"
  14. #include "jmisc.hpp"
  15. #include "jthread.hpp"
  16. #include "jsocket.hpp"
  17. #include "jprop.hpp"
  18. #include "jdebug.hpp"
  19. #include "jlzw.hpp"
  20. #include "eclrtl.hpp"
  21. #ifdef _USE_BINUTILS
  22. #include "bfd.h"
  23. #elif defined(__APPLE__)
  24. #include <mach-o/getsect.h>
  25. #include <sys/mman.h>
  26. #include <sys/stat.h>
  27. #endif
  28. #include "thorplugin.hpp"
  29. void * SimplePluginCtx::ctxMalloc(size_t size)
  30. {
  31. return rtlMalloc(size);
  32. }
  33. void * SimplePluginCtx::ctxRealloc(void * _ptr, size_t size)
  34. {
  35. return rtlRealloc(_ptr, size);
  36. }
  37. void SimplePluginCtx::ctxFree(void * _ptr)
  38. {
  39. rtlFree(_ptr);
  40. }
  41. char * SimplePluginCtx::ctxStrdup(char * _ptr)
  42. {
  43. return strdup(_ptr);
  44. }
  45. int SimplePluginCtx::ctxGetPropInt(const char *propName, int defaultValue) const
  46. {
  47. return defaultValue;
  48. }
  49. const char * SimplePluginCtx::ctxQueryProp(const char *propName) const
  50. {
  51. return NULL;
  52. }
  53. //-------------------------------------------------------------------------------------------------------------------
  54. class HelperDll : public CInterface, implements ILoadedDllEntry
  55. {
  56. SharedObject so;
  57. StringAttr name;
  58. Linked<const IFileIO> dllFile;
  59. bool logLoad;
  60. public:
  61. IMPLEMENT_IINTERFACE;
  62. HelperDll(const char *_name, const IFileIO *dllFile);
  63. ~HelperDll();
  64. //interface ILoadedDllEntry
  65. virtual HINSTANCE getInstance() const;
  66. virtual void * getEntry(const char * name) const;
  67. virtual bool IsShared();
  68. virtual const char * queryVersion() const;
  69. virtual const char * queryName() const;
  70. virtual const byte * getResource(unsigned id) const;
  71. virtual bool getResource(size32_t & len, const void * & data, const char * type, unsigned id) const;
  72. bool load(bool isGlobal, bool raiseOnError);
  73. bool loadCurrentExecutable();
  74. virtual void logLoaded();
  75. virtual bool checkVersion(const char *expected);
  76. };
  77. class PluginDll : public HelperDll
  78. {
  79. ECLPluginDefinitionBlockEx pb;
  80. public:
  81. PluginDll(const char *_name, const IFileIO *_dllFile) : HelperDll(_name, _dllFile) {}
  82. bool init(IPluginContextEx * pluginCtx);
  83. virtual bool checkVersion(const char *expected);
  84. virtual void logLoaded();
  85. };
  86. HelperDll::HelperDll(const char *_name, const IFileIO *_dllFile)
  87. : name(_name), dllFile(_dllFile)
  88. {
  89. logLoad = false;
  90. }
  91. bool HelperDll::load(bool isGlobal, bool raiseOnError)
  92. {
  93. if (!so.load(name, isGlobal, raiseOnError))
  94. return false;
  95. return true;
  96. }
  97. bool HelperDll::loadCurrentExecutable()
  98. {
  99. if (!so.loadCurrentExecutable())
  100. return false;
  101. return true;
  102. }
  103. HelperDll::~HelperDll()
  104. {
  105. if (logLoad)
  106. DBGLOG("Unloading dll %s", name.get());
  107. }
  108. HINSTANCE HelperDll::getInstance() const
  109. {
  110. return so.getInstanceHandle();
  111. }
  112. void * HelperDll::getEntry(const char * name) const
  113. {
  114. return GetSharedProcedure(so.getInstanceHandle(), name);
  115. }
  116. bool HelperDll::IsShared()
  117. {
  118. return CInterface::IsShared();
  119. }
  120. const char * HelperDll::queryVersion() const
  121. {
  122. return "";
  123. }
  124. void HelperDll::logLoaded()
  125. {
  126. logLoad = true;
  127. DBGLOG("Loaded DLL %s", name.get());
  128. }
  129. bool HelperDll::checkVersion(const char *expected)
  130. {
  131. return true;
  132. }
  133. const char * HelperDll::queryName() const
  134. {
  135. return name.get();
  136. }
  137. const byte * HelperDll::getResource(unsigned id) const
  138. {
  139. #ifdef _WIN32
  140. HINSTANCE dllHandle = so.getInstanceHandle();
  141. HRSRC hrsrc = FindResource(dllHandle, MAKEINTRESOURCE(id), "BIGSTRING");
  142. if (hrsrc)
  143. return (const byte *) LoadResource(dllHandle, hrsrc);
  144. return NULL;
  145. #else
  146. StringBuffer resourceName;
  147. resourceName.appendf("BIGSTRING_%d_txt_start", id);
  148. return (const byte *) getEntry(resourceName.str());
  149. #endif
  150. }
  151. const byte resourceHeaderVersion=1;
  152. const size32_t resourceHeaderLength = sizeof(byte) + sizeof(byte) + sizeof(bool) + sizeof(size32_t);
  153. bool HelperDll::getResource(size32_t & len, const void * & data, const char * type, unsigned id) const
  154. {
  155. #ifdef _WIN32
  156. HINSTANCE dllHandle = so.getInstanceHandle();
  157. HRSRC hrsrc = FindResource(dllHandle, MAKEINTRESOURCE(id), type);
  158. if (!hrsrc)
  159. return false;
  160. len = SizeofResource(dllHandle, hrsrc);
  161. data = (const byte *) LoadResource(dllHandle, hrsrc);
  162. return true;
  163. #else
  164. StringBuffer symName;
  165. symName.append(type).append("_").append(id).append("_txt_start");
  166. data = (const void *) getEntry(symName.str());
  167. if (!data)
  168. {
  169. printf("Failed to locate symbol %s", symName.str());
  170. return false;
  171. }
  172. byte bom;
  173. byte version;
  174. bool compressed;
  175. MemoryBuffer mb;
  176. mb.setBuffer(resourceHeaderLength, const_cast<void *>(data));
  177. mb.read(bom);
  178. if (bom!=0x80)
  179. return false;
  180. mb.read(version);
  181. if (version>resourceHeaderVersion)
  182. return false;
  183. mb.read(compressed).read(len);
  184. len+=resourceHeaderLength;
  185. return true;
  186. #endif
  187. }
  188. #ifdef _USE_BINUTILS
  189. struct SecScanParam
  190. {
  191. MemoryBuffer &result;
  192. const char *sectionName;
  193. SecScanParam(MemoryBuffer &_result, const char *_sectionName)
  194. : result(_result), sectionName(_sectionName)
  195. {
  196. }
  197. };
  198. static void secscan (bfd *file, sec_ptr sec, void *userParam)
  199. {
  200. SecScanParam *param = (SecScanParam *) userParam;
  201. if (strcmp(param->sectionName, bfd_section_name (file, sec))==0)
  202. {
  203. bfd_size_type size = bfd_section_size (file, sec);
  204. void *data = (void *) param->result.reserve(size);
  205. bfd_get_section_contents(file, sec, data, 0, size);
  206. }
  207. }
  208. #endif
  209. extern bool getResourceFromFile(const char *filename, MemoryBuffer &data, const char * type, unsigned id)
  210. {
  211. #ifdef _WIN32
  212. HINSTANCE dllHandle = LoadLibraryEx(filename, NULL, LOAD_LIBRARY_AS_DATAFILE|LOAD_LIBRARY_AS_IMAGE_RESOURCE);
  213. if (dllHandle == NULL)
  214. dllHandle = LoadLibraryEx(filename, NULL, LOAD_LIBRARY_AS_DATAFILE); // the LOAD_LIBRARY_AS_IMAGE_RESOURCE flag is not supported on all versions of Windows
  215. if (dllHandle == NULL)
  216. {
  217. DBGLOG("Failed to load library %s: %d", filename, GetLastError());
  218. return false;
  219. }
  220. HRSRC hrsrc = FindResource(dllHandle, MAKEINTRESOURCE(id), type);
  221. if (!hrsrc)
  222. return false;
  223. size32_t len = SizeofResource(dllHandle, hrsrc);
  224. const void *rdata = (const void *) LoadResource(dllHandle, hrsrc);
  225. data.append(len, rdata);
  226. FreeLibrary(dllHandle);
  227. return true;
  228. #elif defined (_USE_BINUTILS)
  229. bfd_init ();
  230. bfd *file = bfd_openr(filename, NULL);
  231. if (file)
  232. {
  233. StringBuffer sectionName;
  234. sectionName.append(type).append("_").append(id).append(".data");
  235. SecScanParam param(data, sectionName.str());
  236. if (bfd_check_format (file, bfd_object))
  237. bfd_map_over_sections (file, secscan, &param);
  238. bfd_close (file);
  239. }
  240. return data.length() != 0;
  241. #elif defined(__APPLE__)
  242. unsigned long len = 0;
  243. struct stat stat_buf;
  244. VStringBuffer sectname("%s_%u", type, id);
  245. int fd = open(filename, O_RDONLY);
  246. if (fd == -1 || fstat(fd, &stat_buf) == -1)
  247. {
  248. DBGLOG("Failed to load library %s: %d", filename, errno);
  249. return false;
  250. }
  251. __uint64 size = stat_buf.st_size;
  252. byte *start_addr = (byte *) mmap(0, size, PROT_READ, MAP_FILE | MAP_PRIVATE, fd, 0);
  253. if (start_addr == MAP_FAILED)
  254. {
  255. DBGLOG("Failed to load library %s: %d", filename, errno);
  256. }
  257. else
  258. {
  259. // The first bytes are the Mach-O header
  260. struct mach_header_64 *mh = (struct mach_header_64 *) start_addr;
  261. if (mh->magic != MH_MAGIC_64)
  262. {
  263. DBGLOG("Failed to load library %s: Does not appear to be a Mach-O 64-bit binary", filename);
  264. }
  265. else
  266. {
  267. unsigned char *data2 = getsectiondata(mh, "__TEXT", sectname.str(), &len);
  268. data.append(len, data2);
  269. }
  270. munmap(start_addr, size);
  271. }
  272. close(fd);
  273. return len != 0;
  274. #else
  275. UNIMPLEMENTED;
  276. #endif
  277. }
  278. //-------------------------------------------------------------------------------------------------------------------
  279. bool PluginDll::init(IPluginContextEx * pluginCtx)
  280. {
  281. HINSTANCE h = getInstance();
  282. assertex(h != (HINSTANCE) -1);
  283. EclPluginSetCtxEx pSetCtxEx = (EclPluginSetCtxEx) GetSharedProcedure(h,"setPluginContextEx");
  284. if (pSetCtxEx)
  285. pSetCtxEx(pluginCtx);
  286. else
  287. {
  288. // Older plugins may only support setPluginContext - fall back to that
  289. EclPluginSetCtx pSetCtx = (EclPluginSetCtx) GetSharedProcedure(h,"setPluginContext");
  290. if (pSetCtx)
  291. pSetCtx(pluginCtx);
  292. }
  293. EclPluginDefinition p= (EclPluginDefinition) GetSharedProcedure(h,"getECLPluginDefinition");
  294. if (!p)
  295. return false;
  296. pb.size = sizeof(ECLPluginDefinitionBlockEx);
  297. if (!p(&pb))
  298. {
  299. pb.compatibleVersions = NULL;
  300. pb.size = sizeof(ECLPluginDefinitionBlock);
  301. if (!p(&pb))
  302. return false;
  303. }
  304. return true;
  305. }
  306. bool PluginDll::checkVersion(const char *expected)
  307. {
  308. assertex(expected);
  309. if (stricmp(pb.version, expected) == 0)
  310. return true;
  311. if (pb.compatibleVersions)
  312. {
  313. const char **finger = pb.compatibleVersions;
  314. while (*finger)
  315. {
  316. if (stricmp(*finger, expected) == 0)
  317. return true;
  318. finger++;
  319. }
  320. }
  321. return false;
  322. }
  323. void PluginDll::logLoaded()
  324. {
  325. HelperDll::logLoaded();
  326. DBGLOG("Current reported version is %s", pb.version);
  327. if (pb.compatibleVersions)
  328. {
  329. const char **finger = pb.compatibleVersions;
  330. while (*finger)
  331. {
  332. DBGLOG("Compatible version %s", *finger);
  333. finger++;
  334. }
  335. }
  336. }
  337. extern DLLSERVER_API ILoadedDllEntry * createDllEntry(const char *path, bool isGlobal, const IFileIO *dllFile)
  338. {
  339. Owned<HelperDll> result = new HelperDll(path, dllFile);
  340. if (!result->load(isGlobal, true))
  341. throw MakeStringException(0, "Failed to create ILoadedDllEntry for dll %s", path);
  342. return result.getClear();
  343. }
  344. extern DLLSERVER_API ILoadedDllEntry * createExeDllEntry(const char *path)
  345. {
  346. Owned<HelperDll> result = new HelperDll(path, NULL);
  347. if (!result->loadCurrentExecutable())
  348. throw MakeStringException(0, "Failed to create ILoadedDllEntry for current executable");
  349. return result.getClear();
  350. }
  351. extern DLLSERVER_API bool decompressResource(size32_t len, const void *data, MemoryBuffer &result)
  352. {
  353. bool hasVersion = len && (*(const byte *)data == 0x80);
  354. MemoryBuffer src;
  355. src.setBuffer(len, const_cast<void *>(data), false);
  356. byte version = 1;
  357. if (hasVersion)
  358. {
  359. src.skip(1);
  360. src.read(version);
  361. }
  362. switch (version)
  363. {
  364. case 1:
  365. decompressToBuffer(result, src);
  366. break;
  367. default:
  368. throwUnexpected();
  369. }
  370. return true;
  371. }
  372. extern DLLSERVER_API bool decompressResource(size32_t len, const void *data, StringBuffer &result)
  373. {
  374. MemoryBuffer tgt;
  375. decompressResource(len, data, tgt);
  376. tgt.append((char)0);
  377. unsigned expandedLen = tgt.length();
  378. result.setBuffer(expandedLen, reinterpret_cast<char *>(tgt.detach()), expandedLen-1);
  379. return true;
  380. }
  381. extern DLLSERVER_API void appendResource(MemoryBuffer & mb, size32_t len, const void *data, bool compress)
  382. {
  383. mb.append((byte)0x80).append(resourceHeaderVersion);
  384. if (compress)
  385. compressToBuffer(mb, len, data);
  386. else
  387. appendToBuffer(mb, len, data);
  388. }
  389. extern DLLSERVER_API void compressResource(MemoryBuffer & compressed, size32_t len, const void *data)
  390. {
  391. appendResource(compressed, len, data, true);
  392. }
  393. extern DLLSERVER_API bool getEmbeddedWorkUnitXML(ILoadedDllEntry *dll, StringBuffer &xml)
  394. {
  395. size32_t len = 0;
  396. const void * data = NULL;
  397. if (!dll->getResource(len, data, "WORKUNIT", 1000))
  398. return false;
  399. return decompressResource(len, data, xml);
  400. }
  401. extern DLLSERVER_API bool getEmbeddedManifestXML(ILoadedDllEntry *dll, StringBuffer &xml)
  402. {
  403. size32_t len = 0;
  404. const void * data = NULL;
  405. if (!dll->getResource(len, data, "MANIFEST", 1000))
  406. return false;
  407. return decompressResource(len, data, xml);
  408. }
  409. extern DLLSERVER_API bool checkEmbeddedWorkUnitXML(ILoadedDllEntry *dll)
  410. {
  411. size32_t len = 0;
  412. const void * data = NULL;
  413. return dll->getResource(len, data, "WORKUNIT", 1000);
  414. }
  415. extern DLLSERVER_API bool getResourceXMLFromFile(const char *filename, const char *type, unsigned id, StringBuffer &xml)
  416. {
  417. MemoryBuffer data;
  418. if (!getResourceFromFile(filename, data, type, id))
  419. return false;
  420. return decompressResource(data.length(), data.toByteArray(), xml);
  421. }
  422. extern DLLSERVER_API bool getWorkunitXMLFromFile(const char *filename, StringBuffer &xml)
  423. {
  424. return getResourceXMLFromFile(filename, "WORKUNIT", 1000, xml);
  425. }
  426. extern DLLSERVER_API bool getManifestXMLFromFile(const char *filename, StringBuffer &xml)
  427. {
  428. return getResourceXMLFromFile(filename, "MANIFEST", 1000, xml);
  429. }
  430. //-------------------------------------------------------------------------------------------------------------------
  431. //-------------------------------------------------------------------------------------------------------------------
  432. bool SafePluginMap::addPlugin(const char *path, const char *dllname)
  433. {
  434. if (!endsWithIgnoreCase(path, SharedObjectExtension))
  435. {
  436. if (trace)
  437. DBGLOG("Ecl plugin %s ignored", path);
  438. return false;
  439. }
  440. try
  441. {
  442. CriticalBlock b(crit);
  443. ILoadedDllEntry *dll = map.getValue(dllname);
  444. if (!dll)
  445. {
  446. Owned<PluginDll> n = new PluginDll(path, NULL);
  447. if (!n->load(true, false) || !n->init(pluginCtx))
  448. throw MakeStringException(0, "Failed to load plugin %s", path);
  449. if (trace)
  450. n->logLoaded();
  451. map.setValue(dllname, n); // note: setValue links arg
  452. return true;
  453. }
  454. return false;
  455. }
  456. catch (IException * e) // MORE - not sure why we don't throw exceptions back here...
  457. {
  458. EXCLOG(e, "Loading plugin");
  459. e->Release();
  460. return false;
  461. }
  462. }
  463. ILoadedDllEntry * SafePluginMap::getPluginDll(const char *id, const char *version, bool checkVersion)
  464. {
  465. CriticalBlock b(crit);
  466. Linked<PluginDll> ret = static_cast<PluginDll *>(map.getValue(id));
  467. if (ret && checkVersion)
  468. {
  469. if (!ret->checkVersion(version))
  470. return NULL;
  471. }
  472. return ret.getLink();
  473. }
  474. void SafePluginMap::loadFromList(const char * pluginsList)
  475. {
  476. const char *pluginDir = pluginsList;
  477. for (;*pluginDir;)
  478. {
  479. StringBuffer thisPlugin;
  480. while (*pluginDir && *pluginDir != ENVSEPCHAR)
  481. thisPlugin.append(*pluginDir++);
  482. if(*pluginDir)
  483. pluginDir++;
  484. if(!thisPlugin.length())
  485. continue;
  486. Owned<IFile> file = createIFile(thisPlugin.str());
  487. if (file->isDirectory() == foundYes)
  488. loadFromDirectory(thisPlugin);
  489. else
  490. {
  491. StringBuffer tail;
  492. splitFilename(thisPlugin, NULL, NULL, &tail, &tail);
  493. addPlugin(thisPlugin, tail.str());
  494. }
  495. }
  496. }
  497. void SafePluginMap::loadFromDirectory(const char * pluginDirectory)
  498. {
  499. const char * mask = "*" SharedObjectExtension;
  500. Owned<IFile> pluginDir = createIFile(pluginDirectory);
  501. Owned<IDirectoryIterator> pluginFiles = pluginDir->directoryFiles(mask,false,false);
  502. ForEach(*pluginFiles)
  503. {
  504. const char *thisPlugin = pluginFiles->query().queryFilename();
  505. StringBuffer tail;
  506. splitFilename(thisPlugin, NULL, NULL, &tail, &tail);
  507. addPlugin(thisPlugin, tail.str());
  508. }
  509. }