thorplugin.cpp 18 KB

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