thorplugin.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864
  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 "jregexp.hpp"
  20. #include "jlzw.hpp"
  21. #include "eclrtl.hpp"
  22. #include "build-config.h"
  23. #if defined(__APPLE__)
  24. #include <mach-o/getsect.h>
  25. #include <sys/mman.h>
  26. #include <sys/stat.h>
  27. #elif !defined(_WIN32)
  28. #include <sys/mman.h>
  29. #include <sys/stat.h>
  30. #include <elf.h>
  31. #endif
  32. #include "thorplugin.hpp"
  33. void * SimplePluginCtx::ctxMalloc(size_t size)
  34. {
  35. return rtlMalloc(size);
  36. }
  37. void * SimplePluginCtx::ctxRealloc(void * _ptr, size_t size)
  38. {
  39. return rtlRealloc(_ptr, size);
  40. }
  41. void SimplePluginCtx::ctxFree(void * _ptr)
  42. {
  43. rtlFree(_ptr);
  44. }
  45. char * SimplePluginCtx::ctxStrdup(char * _ptr)
  46. {
  47. return strdup(_ptr);
  48. }
  49. int SimplePluginCtx::ctxGetPropInt(const char *propName, int defaultValue) const
  50. {
  51. return defaultValue;
  52. }
  53. const char * SimplePluginCtx::ctxQueryProp(const char *propName) const
  54. {
  55. return NULL;
  56. }
  57. //-------------------------------------------------------------------------------------------------------------------
  58. static bool getResourceFromMappedFile(const char * filename, const byte * start_addr, size32_t & lenData, const void * & data, const char * type, unsigned id)
  59. {
  60. #if defined(_WIN32)
  61. throwUnexpected();
  62. #elif defined(__APPLE__)
  63. VStringBuffer sectname("%s_%u", type, id);
  64. // The first bytes are the Mach-O header
  65. const struct mach_header_64 *mh = (const struct mach_header_64 *) start_addr;
  66. if (mh->magic != MH_MAGIC_64)
  67. {
  68. DBGLOG("Failed to extract resource %s: Does not appear to be a Mach-O 64-bit binary", filename);
  69. return false;
  70. }
  71. unsigned long len = 0;
  72. data = getsectiondata(mh, "__TEXT", sectname.str(), &len);
  73. lenData = (size32_t)len;
  74. return true;
  75. #elif defined (__64BIT__)
  76. // The first bytes are the ELF header
  77. const Elf64_Ehdr * hdr = (const Elf64_Ehdr *) start_addr;
  78. if (memcmp(hdr->e_ident, ELFMAG, SELFMAG) != 0)
  79. {
  80. DBGLOG("Failed to extract resource %s: Does not appear to be a ELF binary", filename);
  81. return false;
  82. }
  83. if (hdr->e_ident[EI_CLASS] != ELFCLASS64)
  84. {
  85. DBGLOG("Failed to extract resource %s: Does not appear to be a ELF 64-bit binary", filename);
  86. return false;
  87. }
  88. //Check that there is a symbol table for the sections.
  89. if (hdr->e_shstrndx == SHN_UNDEF)
  90. {
  91. DBGLOG("Failed to extract resource %s: Does not include a section symbol table", filename);
  92. return false;
  93. }
  94. //Now walk the sections comparing the section names
  95. Elf64_Half numSections = hdr->e_shnum;
  96. const Elf64_Shdr * sectionHeaders = reinterpret_cast<const Elf64_Shdr *>(start_addr + hdr->e_shoff);
  97. const Elf64_Shdr & symbolTableSection = sectionHeaders[hdr->e_shstrndx];
  98. const char * symbolTable = (const char *)start_addr + symbolTableSection.sh_offset;
  99. VStringBuffer sectname("%s_%u", type, id);
  100. for (unsigned iSect= 0; iSect < numSections; iSect++)
  101. {
  102. const Elf64_Shdr & section = sectionHeaders[iSect];
  103. const char * sectionName = symbolTable + section.sh_name;
  104. if (streq(sectionName, sectname))
  105. {
  106. lenData = (size32_t)section.sh_size;
  107. data = start_addr + section.sh_offset;
  108. return true;
  109. }
  110. }
  111. DBGLOG("Failed to extract resource %s: Does not include a matching entry", filename);
  112. return false;
  113. #else
  114. // The first bytes are the ELF header
  115. const Elf32_Ehdr * hdr = (const Elf32_Ehdr *) start_addr;
  116. if (memcmp(hdr->e_ident, ELFMAG, SELFMAG) != 0)
  117. {
  118. DBGLOG("Failed to extract resource %s: Does not appear to be a ELF binary", filename);
  119. return false;
  120. }
  121. if (hdr->e_ident[EI_CLASS] != ELFCLASS32)
  122. {
  123. DBGLOG("Failed to extract resource %s: Does not appear to be a ELF 32-bit binary", filename);
  124. return false;
  125. }
  126. //Check that there is a symbol table for the sections.
  127. if (hdr->e_shstrndx == SHN_UNDEF)
  128. {
  129. DBGLOG("Failed to extract resource %s: Does not include a section symbol table", filename);
  130. return false;
  131. }
  132. //Now walk the sections comparing the section names
  133. Elf32_Half numSections = hdr->e_shnum;
  134. const Elf32_Shdr * sectionHeaders = reinterpret_cast<const Elf32_Shdr *>(start_addr + hdr->e_shoff);
  135. const Elf32_Shdr & symbolTableSection = sectionHeaders[hdr->e_shstrndx];
  136. const char * symbolTable = (const char *)start_addr + symbolTableSection.sh_offset;
  137. VStringBuffer sectname("%s_%u", type, id);
  138. for (unsigned iSect= 0; iSect < numSections; iSect++)
  139. {
  140. const Elf32_Shdr & section = sectionHeaders[iSect];
  141. const char * sectionName = symbolTable + section.sh_name;
  142. if (streq(sectionName, sectname))
  143. {
  144. lenData = (size32_t)section.sh_size;
  145. data = start_addr + section.sh_offset;
  146. return true;
  147. }
  148. }
  149. DBGLOG("Failed to extract resource %s: Does not include a matching entry", filename);
  150. return false;
  151. #endif
  152. }
  153. static bool getResourceFromMappedFile(const char * filename, const byte * start_addr, MemoryBuffer & result, const char * type, unsigned id)
  154. {
  155. size32_t len = 0;
  156. const void * data = nullptr;
  157. bool ok = getResourceFromMappedFile(filename, start_addr, len, data, type, id);
  158. if (ok)
  159. result.append(len, data);
  160. return ok;
  161. }
  162. extern bool getResourceFromFile(const char *filename, MemoryBuffer &data, const char * type, unsigned id)
  163. {
  164. #ifdef _WIN32
  165. HINSTANCE dllHandle = LoadLibraryEx(filename, NULL, LOAD_LIBRARY_AS_DATAFILE|LOAD_LIBRARY_AS_IMAGE_RESOURCE);
  166. if (dllHandle == NULL)
  167. dllHandle = LoadLibraryEx(filename, NULL, LOAD_LIBRARY_AS_DATAFILE); // the LOAD_LIBRARY_AS_IMAGE_RESOURCE flag is not supported on all versions of Windows
  168. if (dllHandle == NULL)
  169. {
  170. DBGLOG("Failed to load library %s: %d", filename, GetLastError());
  171. return false;
  172. }
  173. HRSRC hrsrc = FindResource(dllHandle, MAKEINTRESOURCE(id), type);
  174. if (!hrsrc)
  175. return false;
  176. size32_t len = SizeofResource(dllHandle, hrsrc);
  177. const void *rdata = (const void *) LoadResource(dllHandle, hrsrc);
  178. data.append(len, rdata);
  179. FreeLibrary(dllHandle);
  180. return true;
  181. #else
  182. struct stat stat_buf;
  183. VStringBuffer sectname("%s_%u", type, id);
  184. int fd = open(filename, O_RDONLY);
  185. if (fd == -1)
  186. {
  187. DBGLOG("Failed to load library %s: %d", filename, errno);
  188. return false;
  189. }
  190. bool ok = false;
  191. if (fstat(fd, &stat_buf) != -1)
  192. {
  193. __uint64 size = stat_buf.st_size;
  194. const byte *start_addr = (const byte *) mmap(0, size, PROT_READ, MAP_FILE | MAP_PRIVATE, fd, 0);
  195. if (start_addr == MAP_FAILED)
  196. {
  197. DBGLOG("Failed to load library %s: %d", filename, errno);
  198. }
  199. else
  200. {
  201. ok = getResourceFromMappedFile(filename, start_addr, data, type, id);
  202. munmap((void *)start_addr, size);
  203. }
  204. }
  205. else
  206. DBGLOG("Failed to load library %s: %d", filename, errno);
  207. close(fd);
  208. return ok;
  209. #endif
  210. }
  211. //-------------------------------------------------------------------------------------------------------------------
  212. class ManifestFileList : public MappingBase
  213. {
  214. StringArray filenames;
  215. StringAttr type;
  216. StringAttr dir;
  217. void recursiveRemoveDirectory(const char *fullPath)
  218. {
  219. if (rmdir(fullPath) == 0 && !streq(fullPath, dir))
  220. {
  221. StringBuffer head;
  222. splitFilename(fullPath, &head, &head, NULL, NULL);
  223. if (head.length() > 1)
  224. {
  225. head.setLength(head.length()-1);
  226. recursiveRemoveDirectory(head);
  227. }
  228. }
  229. }
  230. void removeFileAndEmptyParents(const char *fullFileName)
  231. {
  232. remove(fullFileName);
  233. StringBuffer path;
  234. splitFilename(fullFileName, &path, &path, NULL, NULL);
  235. if (path.length() > 1)
  236. {
  237. path.setLength(path.length()-1);
  238. recursiveRemoveDirectory(path.str());
  239. }
  240. }
  241. public:
  242. ManifestFileList(const char *_type, const char *_dir) : type(_type), dir(_dir) {}
  243. ~ManifestFileList()
  244. {
  245. ForEachItemIn(idx, filenames)
  246. {
  247. removeFileAndEmptyParents(filenames.item(idx));
  248. }
  249. rmdir(dir); // If the specified temporary directory is now empty, remove it.
  250. }
  251. void append(const char *filename)
  252. {
  253. assertex(strncmp(filename, dir, strlen(dir))==0);
  254. filenames.append(filename);
  255. }
  256. inline const StringArray &queryFileNames() { return filenames; }
  257. virtual const void * getKey() const { return type; }
  258. };
  259. class HelperDll : implements ILoadedDllEntry, public CInterface
  260. {
  261. SharedObject so;
  262. StringAttr name;
  263. Linked<const IFileIO> dllFile;
  264. Owned<IMemoryMappedFile> mappedDll;
  265. mutable std::atomic<IPropertyTree *> manifest {nullptr};
  266. mutable CriticalSection manifestLock;
  267. mutable StringMapOf<ManifestFileList> manifestFiles;
  268. bool logLoad;
  269. public:
  270. IMPLEMENT_IINTERFACE;
  271. HelperDll(const char *_name, const IFileIO *dllFile);
  272. ~HelperDll();
  273. //interface ILoadedDllEntry
  274. virtual HINSTANCE getInstance() const;
  275. virtual void * getEntry(const char * name) const;
  276. virtual bool IsShared();
  277. virtual const char * queryVersion() const;
  278. virtual const char * queryName() const;
  279. virtual const byte * getResource(unsigned id) const;
  280. virtual bool getResource(size32_t & len, const void * & data, const char * type, unsigned id, bool trace) const;
  281. virtual IPropertyTree &queryManifest() const override;
  282. virtual const StringArray &queryManifestFiles(const char *type, const char *wuid) const override;
  283. bool load(bool isGlobal, bool raiseOnError);
  284. bool loadCurrentExecutable();
  285. bool loadResources();
  286. virtual void logLoaded();
  287. virtual bool checkVersion(const char *expected);
  288. };
  289. class PluginDll : public HelperDll
  290. {
  291. ECLPluginDefinitionBlockEx pb;
  292. public:
  293. PluginDll(const char *_name, const IFileIO *_dllFile) : HelperDll(_name, _dllFile) {}
  294. bool init(IPluginContextEx * pluginCtx);
  295. virtual bool checkVersion(const char *expected);
  296. virtual void logLoaded();
  297. };
  298. HelperDll::HelperDll(const char *_name, const IFileIO *_dllFile)
  299. : name(_name), dllFile(_dllFile), manifestFiles(false)
  300. {
  301. logLoad = false;
  302. }
  303. bool HelperDll::load(bool isGlobal, bool raiseOnError)
  304. {
  305. if (!so.load(name, isGlobal, raiseOnError))
  306. return false;
  307. return true;
  308. }
  309. bool HelperDll::loadResources()
  310. {
  311. #ifdef _WIN32
  312. return so.loadResources(name);
  313. #else
  314. Owned<IFile> file = createIFile(name);
  315. mappedDll.setown(file->openMemoryMapped());
  316. return mappedDll != nullptr;
  317. #endif
  318. }
  319. bool HelperDll::loadCurrentExecutable()
  320. {
  321. if (!so.loadCurrentExecutable())
  322. return false;
  323. return true;
  324. }
  325. HelperDll::~HelperDll()
  326. {
  327. if (logLoad)
  328. DBGLOG("Unloading dll %s", name.get());
  329. ::Release(manifest.load(std::memory_order_relaxed));
  330. }
  331. HINSTANCE HelperDll::getInstance() const
  332. {
  333. if (!so.loaded())
  334. throw MakeStringException(0, "Dll %s only loaded for resources", name.str());
  335. return so.getInstanceHandle();
  336. }
  337. void * HelperDll::getEntry(const char * entry) const
  338. {
  339. if (!so.loaded())
  340. throw MakeStringException(0, "Dll %s only loaded for resources", name.str());
  341. return so.getEntry(entry);
  342. }
  343. bool HelperDll::IsShared()
  344. {
  345. return CInterface::IsShared();
  346. }
  347. const char * HelperDll::queryVersion() const
  348. {
  349. return "";
  350. }
  351. void HelperDll::logLoaded()
  352. {
  353. logLoad = true;
  354. DBGLOG("Loaded DLL %s", name.get());
  355. }
  356. bool HelperDll::checkVersion(const char *expected)
  357. {
  358. return true;
  359. }
  360. const char * HelperDll::queryName() const
  361. {
  362. return name.get();
  363. }
  364. const byte * HelperDll::getResource(unsigned id) const
  365. {
  366. if (so.loaded())
  367. {
  368. #ifdef _WIN32
  369. HINSTANCE dllHandle = so.getInstanceHandle();
  370. HRSRC hrsrc = FindResource(dllHandle, MAKEINTRESOURCE(id), "BIGSTRING");
  371. if (hrsrc)
  372. return (const byte *)LoadResource(dllHandle, hrsrc);
  373. return NULL;
  374. #else
  375. StringBuffer resourceName;
  376. resourceName.appendf("BIGSTRING_%d_txt_start", id);
  377. return (const byte *)getEntry(resourceName.str());
  378. #endif
  379. }
  380. else
  381. {
  382. size32_t len;
  383. const void * data;
  384. if (getResource(len, data, "BIGSTRING", id, false))
  385. return (const byte *)data;
  386. return nullptr;
  387. }
  388. }
  389. const byte resourceHeaderVersion=1;
  390. const size32_t resourceHeaderLength = sizeof(byte) + sizeof(byte) + sizeof(bool) + sizeof(size32_t);
  391. bool HelperDll::getResource(size32_t & len, const void * & data, const char * type, unsigned id, bool trace) const
  392. {
  393. if (so.loaded())
  394. {
  395. #ifdef _WIN32
  396. HINSTANCE dllHandle = so.getInstanceHandle();
  397. HRSRC hrsrc = FindResource(dllHandle, MAKEINTRESOURCE(id), type);
  398. if (!hrsrc)
  399. return false;
  400. len = SizeofResource(dllHandle, hrsrc);
  401. data = (const byte *)LoadResource(dllHandle, hrsrc);
  402. return true;
  403. #else
  404. StringBuffer symName;
  405. symName.append(type).append("_").append(id).append("_txt_start");
  406. data = (const void *)getEntry(symName.str());
  407. if (!data)
  408. {
  409. if (trace)
  410. printf("Failed to locate symbol %s\n", symName.str());
  411. return false;
  412. }
  413. byte bom;
  414. byte version;
  415. bool compressed;
  416. MemoryBuffer mb;
  417. mb.setBuffer(resourceHeaderLength, const_cast<void *>(data));
  418. mb.read(bom);
  419. if (bom != 0x80)
  420. return false;
  421. mb.read(version);
  422. if (version > resourceHeaderVersion)
  423. return false;
  424. mb.read(compressed).read(len);
  425. len += resourceHeaderLength;
  426. return true;
  427. #endif
  428. }
  429. else
  430. {
  431. #ifdef _WIN32
  432. return false;
  433. #endif
  434. if (!mappedDll)
  435. return false;
  436. return getResourceFromMappedFile(name, mappedDll->base(), len, data, type, id);
  437. }
  438. }
  439. IPropertyTree &HelperDll::queryManifest() const
  440. {
  441. return *querySingleton(manifest, manifestLock, [this]{ return getEmbeddedManifestPTree(this); });
  442. }
  443. const StringArray &HelperDll::queryManifestFiles(const char *type, const char *wuid) const
  444. {
  445. CriticalBlock b(manifestLock);
  446. Linked<ManifestFileList> list = manifestFiles.find(type);
  447. if (!list)
  448. {
  449. // The temporary path we unpack to is based on so file's current location and workunit
  450. // MORE - this is good for deployed cases, may not be so good for standalone executables.
  451. StringBuffer tempDir;
  452. splitFilename(name, &tempDir, &tempDir, &tempDir, nullptr);
  453. list.setown(new ManifestFileList(type, tempDir));
  454. tempDir.append(".tmp").append(PATHSEPCHAR).append(wuid);
  455. VStringBuffer xpath("Resource[@type='%s']", type);
  456. Owned<IPropertyTreeIterator> resourceFiles = queryManifest().getElements(xpath.str());
  457. ForEach(*resourceFiles)
  458. {
  459. IPropertyTree &resourceFile = resourceFiles->query();
  460. unsigned id = resourceFile.getPropInt("@id", 0);
  461. size32_t len = 0;
  462. const void *data = nullptr;
  463. if (!getResource(len, data, type, id, false))
  464. throwUnexpected();
  465. MemoryBuffer decompressed;
  466. if (resourceFile.getPropBool("@compressed"))
  467. {
  468. // MORE - would be better to try to spot files that are not worth recompressing (like jar files)?
  469. decompressResource(len, data, decompressed);
  470. data = decompressed.toByteArray();
  471. len = decompressed.length();
  472. }
  473. else
  474. {
  475. // Data is preceded by the resource header
  476. // MORE - does this depend on whether @header is set? is that what @header means?
  477. data = ((const byte *) data) + resourceHeaderLength;
  478. len -= resourceHeaderLength;
  479. }
  480. StringBuffer extractName(tempDir);
  481. extractName.append(PATHSEPCHAR);
  482. if (resourceFile.hasProp("@filename"))
  483. resourceFile.getProp("@filename", extractName);
  484. else
  485. extractName.append(id).append('.').append(type);
  486. recursiveCreateDirectoryForFile(extractName);
  487. OwnedIFile f = createIFile(extractName);
  488. OwnedIFileIO o = f->open(IFOcreaterw);
  489. assertex(o.get() != nullptr);
  490. o->write(0, len, data);
  491. list->append(extractName);
  492. }
  493. manifestFiles.replaceOwn(*list.getLink());
  494. }
  495. return list->queryFileNames();
  496. }
  497. //-------------------------------------------------------------------------------------------------------------------
  498. bool PluginDll::init(IPluginContextEx * pluginCtx)
  499. {
  500. HINSTANCE h = getInstance();
  501. assertex(h != (HINSTANCE) -1);
  502. EclPluginSetCtxEx pSetCtxEx = (EclPluginSetCtxEx) GetSharedProcedure(h,"setPluginContextEx");
  503. if (pSetCtxEx)
  504. pSetCtxEx(pluginCtx);
  505. else
  506. {
  507. // Older plugins may only support setPluginContext - fall back to that
  508. EclPluginSetCtx pSetCtx = (EclPluginSetCtx) GetSharedProcedure(h,"setPluginContext");
  509. if (pSetCtx)
  510. pSetCtx(pluginCtx);
  511. }
  512. EclPluginDefinition p= (EclPluginDefinition) GetSharedProcedure(h,"getECLPluginDefinition");
  513. if (!p)
  514. return false;
  515. pb.size = sizeof(ECLPluginDefinitionBlockEx);
  516. if (!p(&pb))
  517. {
  518. pb.compatibleVersions = NULL;
  519. pb.size = sizeof(ECLPluginDefinitionBlock);
  520. if (!p(&pb))
  521. return false;
  522. }
  523. return true;
  524. }
  525. bool PluginDll::checkVersion(const char *expected)
  526. {
  527. assertex(expected);
  528. if (stricmp(pb.version, expected) == 0)
  529. return true;
  530. if (pb.compatibleVersions)
  531. {
  532. const char **finger = pb.compatibleVersions;
  533. while (*finger)
  534. {
  535. if (stricmp(*finger, expected) == 0)
  536. return true;
  537. finger++;
  538. }
  539. }
  540. return false;
  541. }
  542. void PluginDll::logLoaded()
  543. {
  544. HelperDll::logLoaded();
  545. DBGLOG("Current reported version is %s", pb.version);
  546. if (pb.compatibleVersions)
  547. {
  548. const char **finger = pb.compatibleVersions;
  549. while (*finger)
  550. {
  551. DBGLOG("Compatible version %s", *finger);
  552. finger++;
  553. }
  554. }
  555. }
  556. extern DLLSERVER_API ILoadedDllEntry * createDllEntry(const char *path, bool isGlobal, const IFileIO *dllFile, bool resourcesOnly)
  557. {
  558. Owned<HelperDll> result = new HelperDll(path, dllFile);
  559. bool ok;
  560. if (!resourcesOnly)
  561. ok = result->load(isGlobal, true);
  562. else
  563. ok = result->loadResources();
  564. if (!ok)
  565. throw MakeStringException(0, "Failed to create ILoadedDllEntry for dll %s", path);
  566. return result.getClear();
  567. }
  568. extern DLLSERVER_API ILoadedDllEntry * createExeDllEntry(const char *path)
  569. {
  570. Owned<HelperDll> result = new HelperDll(path, NULL);
  571. if (!result->loadCurrentExecutable())
  572. throw MakeStringException(0, "Failed to create ILoadedDllEntry for current executable");
  573. return result.getClear();
  574. }
  575. extern DLLSERVER_API bool decompressResource(size32_t len, const void *data, MemoryBuffer &result)
  576. {
  577. bool hasVersion = len && (*(const byte *)data == 0x80);
  578. MemoryBuffer src;
  579. src.setBuffer(len, const_cast<void *>(data), false);
  580. byte version = 1;
  581. if (hasVersion)
  582. {
  583. src.skip(1);
  584. src.read(version);
  585. }
  586. switch (version)
  587. {
  588. case 1:
  589. decompressToBuffer(result, src);
  590. break;
  591. default:
  592. throwUnexpected();
  593. }
  594. return true;
  595. }
  596. extern DLLSERVER_API bool decompressResource(size32_t len, const void *data, StringBuffer &result)
  597. {
  598. MemoryBuffer tgt;
  599. decompressResource(len, data, tgt);
  600. tgt.append((char)0);
  601. unsigned expandedLen = tgt.length();
  602. result.setBuffer(expandedLen, reinterpret_cast<char *>(tgt.detach()), expandedLen-1);
  603. return true;
  604. }
  605. extern DLLSERVER_API void appendResource(MemoryBuffer & mb, size32_t len, const void *data, bool compress)
  606. {
  607. mb.append((byte)0x80).append(resourceHeaderVersion);
  608. if (compress)
  609. compressToBuffer(mb, len, data);
  610. else
  611. appendToBuffer(mb, len, data);
  612. }
  613. extern DLLSERVER_API void compressResource(MemoryBuffer & compressed, size32_t len, const void *data)
  614. {
  615. appendResource(compressed, len, data, true);
  616. }
  617. extern DLLSERVER_API bool getEmbeddedWorkUnitXML(ILoadedDllEntry *dll, StringBuffer &xml)
  618. {
  619. size32_t len = 0;
  620. const void * data = NULL;
  621. if (!dll->getResource(len, data, "WORKUNIT", 1000))
  622. return false;
  623. return decompressResource(len, data, xml);
  624. }
  625. extern DLLSERVER_API bool getEmbeddedManifestXML(const ILoadedDllEntry *dll, StringBuffer &xml)
  626. {
  627. size32_t len = 0;
  628. const void * data = NULL;
  629. if (!dll->getResource(len, data, "MANIFEST", 1000))
  630. return false;
  631. return decompressResource(len, data, xml);
  632. }
  633. extern DLLSERVER_API IPropertyTree *getEmbeddedManifestPTree(const ILoadedDllEntry *dll)
  634. {
  635. StringBuffer xml;
  636. return getEmbeddedManifestXML(dll, xml) ? createPTreeFromXMLString(xml.str()) : createPTree();
  637. }
  638. extern DLLSERVER_API bool checkEmbeddedWorkUnitXML(ILoadedDllEntry *dll)
  639. {
  640. size32_t len = 0;
  641. const void * data = NULL;
  642. return dll->getResource(len, data, "WORKUNIT", 1000, false);
  643. }
  644. extern DLLSERVER_API bool getResourceXMLFromFile(const char *filename, const char *type, unsigned id, StringBuffer &xml)
  645. {
  646. MemoryBuffer data;
  647. if (!getResourceFromFile(filename, data, type, id))
  648. return false;
  649. return decompressResource(data.length(), data.toByteArray(), xml);
  650. }
  651. extern DLLSERVER_API bool getWorkunitXMLFromFile(const char *filename, StringBuffer &xml)
  652. {
  653. return getResourceXMLFromFile(filename, "WORKUNIT", 1000, xml);
  654. }
  655. extern DLLSERVER_API bool getArchiveXMLFromFile(const char *filename, StringBuffer &xml)
  656. {
  657. return getResourceXMLFromFile(filename, "ARCHIVE", 1000, xml);
  658. }
  659. extern DLLSERVER_API bool getManifestXMLFromFile(const char *filename, StringBuffer &xml)
  660. {
  661. return getResourceXMLFromFile(filename, "MANIFEST", 1000, xml);
  662. }
  663. //-------------------------------------------------------------------------------------------------------------------
  664. extern DLLSERVER_API void getAdditionalPluginsPath(StringBuffer &pluginsPath, const char *_base)
  665. {
  666. // We only add the additional plugins if the plugins path already includes the default plugins location
  667. StringBuffer base(_base);
  668. removeTrailingPathSepChar(base);
  669. removeTrailingPathSepChar(pluginsPath);
  670. StringBuffer defaultLocation(base);
  671. defaultLocation.append(PATHSEPSTR "plugins");
  672. StringArray paths;
  673. paths.appendList(pluginsPath, ENVSEPSTR);
  674. if (paths.contains(defaultLocation))
  675. {
  676. const char *additional = queryEnvironmentConf().queryProp("additionalPlugins");
  677. if (additional)
  678. {
  679. StringArray additionalPaths;
  680. additionalPaths.appendList(additional, ENVSEPSTR);
  681. ForEachItemIn(idx, additionalPaths)
  682. {
  683. const char *additionalPath = additionalPaths.item(idx);
  684. pluginsPath.append(ENVSEPCHAR);
  685. if (!isAbsolutePath(additionalPath))
  686. pluginsPath.append(base).append(PATHSEPSTR "versioned" PATHSEPSTR);
  687. pluginsPath.append(additionalPath);
  688. }
  689. }
  690. }
  691. }
  692. bool SafePluginMap::addPlugin(const char *path, const char *dllname)
  693. {
  694. if (!endsWithIgnoreCase(path, SharedObjectExtension))
  695. {
  696. if (trace)
  697. DBGLOG("Ecl plugin %s ignored", path);
  698. return false;
  699. }
  700. try
  701. {
  702. CriticalBlock b(crit);
  703. ILoadedDllEntry *dll = map.getValue(dllname);
  704. if (!dll)
  705. {
  706. Owned<PluginDll> n = new PluginDll(path, NULL);
  707. // Note - we used to load plugins with global=true, but that caused issues when loading
  708. // Python3 and Python2 plugins at the same time as the export similar symbols
  709. // Loading with global=false should not cause any adverse issues
  710. if (!n->load(false, false) || !n->init(pluginCtx))
  711. throw MakeStringException(0, "Failed to load plugin %s", path);
  712. if (trace)
  713. n->logLoaded();
  714. map.setValue(dllname, n); // note: setValue links arg
  715. return true;
  716. }
  717. return false;
  718. }
  719. catch (IException * e) // MORE - not sure why we don't throw exceptions back here...
  720. {
  721. EXCLOG(e, "Loading plugin");
  722. e->Release();
  723. return false;
  724. }
  725. }
  726. ILoadedDllEntry * SafePluginMap::getPluginDll(const char *id, const char *version, bool checkVersion)
  727. {
  728. CriticalBlock b(crit);
  729. Linked<PluginDll> ret = static_cast<PluginDll *>(map.getValue(id));
  730. if (ret && checkVersion)
  731. {
  732. if (!ret->checkVersion(version))
  733. return NULL;
  734. }
  735. return ret.getLink();
  736. }
  737. void SafePluginMap::loadFromList(const char * pluginsList)
  738. {
  739. const char *pluginDir = pluginsList;
  740. for (;*pluginDir;)
  741. {
  742. StringBuffer thisPlugin;
  743. while (*pluginDir && *pluginDir != ENVSEPCHAR)
  744. thisPlugin.append(*pluginDir++);
  745. if(*pluginDir)
  746. pluginDir++;
  747. if(!thisPlugin.length())
  748. continue;
  749. Owned<IFile> file = createIFile(thisPlugin.str());
  750. if (file->isDirectory() == fileBool::foundYes)
  751. loadFromDirectory(thisPlugin);
  752. else
  753. {
  754. StringBuffer tail;
  755. splitFilename(thisPlugin, NULL, NULL, &tail, &tail);
  756. addPlugin(thisPlugin, tail.str());
  757. }
  758. }
  759. }
  760. void SafePluginMap::loadFromDirectory(const char * pluginDirectory)
  761. {
  762. const char * mask = "*" SharedObjectExtension;
  763. Owned<IFile> pluginDir = createIFile(pluginDirectory);
  764. Owned<IDirectoryIterator> pluginFiles = pluginDir->directoryFiles(mask,false,false);
  765. ForEach(*pluginFiles)
  766. {
  767. const char *thisPlugin = pluginFiles->query().queryFilename();
  768. StringBuffer tail;
  769. splitFilename(thisPlugin, NULL, NULL, &tail, &tail);
  770. addPlugin(thisPlugin, tail.str());
  771. }
  772. }