bool load(const char* dllname) { if (library(dllname)) { DBG("'%s' is already loaded\n", dllname); return true; } std::list<std::string> libnames = sLibNamesMap[dllname]; if (libnames.empty()) libnames.push_back(dllname); std::list<std::string>::const_iterator it; QLibrary *dll = new QLibrary(); for (it = libnames.begin(); it != libnames.end(); ++it) { dll->setFileName((*it).c_str()); if (dll->load()) break; DBG("%s\n", dll->errorString().toLocal8Bit().constData()); //why qDebug use toUtf8() and printf use toLocal8Bit()? } if (it == libnames.end()) { DBG("No dll loaded\n"); delete dll; return false; } DBG("'%s' is loaded~~~\n", dll->fileName().toUtf8().constData()); sDllMap[dllname] = dll; //map.insert will not replace the old one return true; }
QLibrary* RazorPluginInfo::loadLibrary(const QString& libDir) const { QString baseName, path; QFileInfo fi = QFileInfo(fileName()); path = fi.canonicalPath(); baseName = value("X-Razor-Library", fi.completeBaseName()).toString(); QString soPath = QString("%1/lib%2.so").arg(libDir, baseName); QLibrary* library = new QLibrary(soPath); if (!library->load()) { qWarning() << QString("Can't load plugin lib \"%1\"").arg(soPath) << library->errorString(); delete library; return 0; } QString locale = QLocale::system().name(); QTranslator* translator = new QTranslator(library); translator->load(QString("%1/%2/%2_%3.qm").arg(path, baseName, locale)); qApp->installTranslator(translator); return library; }
Garmin::IDevice * CDeviceGarmin::getDevice() { Garmin::IDevice * (*func)(const char*) = 0; Garmin::IDevice * dev = 0; #if defined(Q_OS_MAC) // MacOS X: plug-ins are stored in the bundle folder QString libname = QString("%1/lib%2" XSTR(SHARED_LIB_EXT)) .arg(QCoreApplication::applicationDirPath().replace(QRegExp("MacOS$"), "Resources/Drivers")) .arg(devkey); #else QString libname = QString("%1/lib%2" XSTR(SHARED_LIB_EXT)).arg(XSTR(PLUGINDIR)).arg(devkey); #endif QString funcname = QString("init%1").arg(devkey); QLibrary lib; lib.setFileName(libname); bool lib_loaded = lib.load(); if (lib_loaded) { func = (Garmin::IDevice * (*)(const char*))lib.resolve(funcname.toLatin1()); } if(!lib_loaded || func == 0) { QMessageBox warn; warn.setIcon(QMessageBox::Warning); warn.setWindowTitle(tr("Error ...")); warn.setText(tr("Failed to load driver.")); warn.setDetailedText(lib.errorString()); warn.setStandardButtons(QMessageBox::Ok); warn.exec(); return 0; } dev = func(INTERFACE_VERSION); if(dev == 0) { QMessageBox warn; warn.setIcon(QMessageBox::Warning); warn.setWindowTitle(tr("Error ...")); warn.setText(tr("Driver version mismatch.")); QString detail = QString( tr("The version of your driver plugin \"%1\" does not match the version QLandkarteGT expects (\"%2\").") ).arg(libname).arg(INTERFACE_VERSION); warn.setDetailedText(detail); warn.setStandardButtons(QMessageBox::Ok); warn.exec(); func = 0; } if(dev) { dev->setPort(port.toLatin1()); dev->setGuiCallback(GUICallback,this); } return dev; }
static T resolveFunction(QLibrary &lib, const char *name) { T temp = reinterpret_cast<T>(lib.resolve(name)); if (temp == nullptr) { throw std::runtime_error(QObject::tr("invalid 7-zip32.dll: %1").arg(lib.errorString()).toLatin1().constData()); } return temp; }
//---------------------------------------------------------------------------- void ctkPluginFrameworkContext::init() { log() << "initializing"; if (firstInit && ctkPluginConstants::FRAMEWORK_STORAGE_CLEAN_ONFIRSTINIT == props[ctkPluginConstants::FRAMEWORK_STORAGE_CLEAN]) { deleteFWDir(); firstInit = false; } // Pre-load libraries // This may speed up installing new plug-ins if they have dependencies on // one of these libraries. It prevents repeated loading and unloading of the // pre-loaded libraries during caching of the plug-in meta-data. if (props[ctkPluginConstants::FRAMEWORK_PRELOAD_LIBRARIES].isValid()) { QStringList preloadLibs = props[ctkPluginConstants::FRAMEWORK_PRELOAD_LIBRARIES].toStringList(); QLibrary::LoadHints loadHints; QVariant loadHintsVariant = props[ctkPluginConstants::FRAMEWORK_PLUGIN_LOAD_HINTS]; if (loadHintsVariant.isValid()) { loadHints = loadHintsVariant.value<QLibrary::LoadHints>(); } foreach(QString preloadLib, preloadLibs) { QLibrary lib; QStringList nameAndVersion = preloadLib.split(":"); QString libraryName; if (nameAndVersion.count() == 1) { libraryName = nameAndVersion.front(); lib.setFileName(nameAndVersion.front()); } else if (nameAndVersion.count() == 2) { libraryName = nameAndVersion.front() + "." + nameAndVersion.back(); lib.setFileNameAndVersion(nameAndVersion.front(), nameAndVersion.back()); } else { qWarning() << "Wrong syntax in" << preloadLib << ". Use <lib-name>[:version]. Skipping."; continue; } lib.setLoadHints(loadHints); log() << "Pre-loading library" << lib.fileName() << "with hints [" << static_cast<int>(loadHints) << "]"; if (!lib.load()) { qWarning() << "Pre-loading library" << lib.fileName() << "failed:" << lib.errorString() << "\nCheck your library search paths."; } }
bool unload(const char* dllname) { QLibrary *dll = library(dllname); if (!dll) { DBG("'%s' is not loaded\n", dllname); return true; } if (!dll->unload()) { DBG("%s", dll->errorString().toUtf8().constData()); return false; } sDllMap.erase(std::find_if(sDllMap.begin(), sDllMap.end(), std::bind2nd(map_value_equal<dllmap_t>(), dll))->first); delete dll; return true; }
QLibrary *QgsProviderRegistry::providerLibrary( QString const & providerKey ) const { QLibrary *myLib = new QLibrary( library( providerKey ) ); QgsDebugMsg( "Library name is " + myLib->fileName() ); if ( myLib->load() ) return myLib; QgsDebugMsg( "Cannot load library: " + myLib->errorString() ); delete myLib; return 0; }
QLibrary *QgsAuthMethodRegistry::authMethodLibrary( const QString &authMethodKey ) const { QLibrary *myLib = new QLibrary( library( authMethodKey ) ); QgsDebugMsg( "Library name is " + myLib->fileName() ); if ( myLib->load() ) return myLib; QgsDebugMsg( "Cannot load library: " + myLib->errorString() ); delete myLib; return 0; }
static PyObject *meth_QLibrary_errorString(PyObject *sipSelf, PyObject *sipArgs) { PyObject *sipParseErr = NULL; { QLibrary *sipCpp; if (sipParseArgs(&sipParseErr, sipArgs, "B", &sipSelf, sipType_QLibrary, &sipCpp)) { QString *sipRes; Py_BEGIN_ALLOW_THREADS sipRes = new QString(sipCpp->errorString()); Py_END_ALLOW_THREADS return sipConvertFromNewType(sipRes,sipType_QString,NULL); } }
bool PluginManager::loadPlugin(QString file, bool silent) { QLibrary* library = new QLibrary(file); if(!library->load()) { if(!silent) { QMessageBox::critical (_gi, tr("Error loading plugin"), library->errorString()); } return false; } std::cout << file.toStdString() << " loaded" << std::endl; QFunctionPointer ptr = library->resolve("loadPlugin"); if(ptr == 0) { if(!silent) { QMessageBox::critical (_gi, tr("Error loading plugin"), tr("Could not find the plugin's entry point \"loadPlugin\"")); } return false; } std::cout << file.toStdString() << ": entry point found" << std::endl; typedef Plugin* (*entryPoint)(); entryPoint getPlugin = reinterpret_cast<entryPoint>(ptr); Plugin* plugin = getPlugin(); if(plugin==NULL) { if(!silent) { QMessageBox::critical (_gi, tr("Error loading plugin"), tr("The getPlugin entry point does not return a valid Plugin")); } return false; } std::cout << file.toStdString() << ": got Plugin" << std::endl; vector<GenericOperation*> operations = plugin->getOperations(); std::cout << "Plugin " << plugin->getName() << " loaded : " << operations.size() << " operations "<< std::endl; //PluginService* pluginService = new PluginService(plugin); _plugins.insert(pair<string,Plugin*>(file.toStdString(), plugin)); _libraries.insert(pair<Plugin*,QLibrary*>(plugin, library)); //_gi->addService(pluginService); emit addPlugin(plugin); return true; }
void tst_QLibrary::errorString() { QFETCH(int, operation); QFETCH(QString, fileName); QFETCH(bool, success); QFETCH(QString, errorString); QLibrary lib; if (!(operation & DontSetFileName)) { lib.setFileName(fileName); } bool ok = false; switch (operation & OperationMask) { case Load: ok = lib.load(); break; case Unload: ok = lib.load(); //### ok = lib.unload(); break; case Resolve: { ok = lib.load(); QCOMPARE(ok, true); if (success) { ok = lib.resolve("mylibversion"); } else { ok = lib.resolve("nosuchsymbol"); } break;} default: QFAIL(qPrintable(QString("Unknown operation: %1").arg(operation))); break; } QRegExp re(errorString); QString libErrorString = lib.errorString(); QVERIFY(!lib.isLoaded() || lib.unload()); QVERIFY2(re.exactMatch(libErrorString), qPrintable(libErrorString)); QCOMPARE(ok, success); }
int main (int argc, char* argv[]) { RazorDesktopApplication app(argc,argv); XdgIcon::setThemeName(RazorSettings::globalSettings()->value("icon_theme").toString()); app.setWindowIcon(QIcon(QString(SHARE_DIR) + "/graphics/razor_logo.png")); RazorSettings config("desktop"); app.setStyleSheet(razorTheme->qss("desktop")); QString configId(config.value("desktop", "razor").toString()); QString libraryFileName = QString(DESKTOP_PLUGIN_DIR) + "libdesktop-" + configId + ".so"; qDebug() << "RazorDesktop: try to load " << libraryFileName; QLibrary * lib = new QLibrary(libraryFileName); PluginInitFunction initFunc = (PluginInitFunction) lib->resolve("init"); if (!initFunc) { qDebug() << lib->errorString(); delete lib; return 0; } DesktopPlugin * plugin = initFunc(configId, &config); Q_ASSERT(plugin); if (plugin) { //lib->setParent(plugin); qDebug() << " * Plugin loaded."; qDebug() << plugin->info(); } app.setDesktopPlugin(plugin); return app.exec(); }
PlazaClient::PlazaClient(QWidget *parent) :QWidget(parent) ,ui(new Ui::wgtPlazaMainUI) ,m_process(NULL) { ui->setupUi(this); connect(ui->btnStartGame,SIGNAL(clicked()),this,SLOT(sltStartGame())); connect(ui->btnSendData,SIGNAL(clicked()),this,SLOT(sltSendData())); connect(ui->btnCloseGame,SIGNAL(clicked()),this,SLOT(sltGameClosed())); connect(qApp,SIGNAL(aboutToQuit()),this,SLOT()); QLibrary *libChannelModule = new QLibrary(this); #if defined(Q_OS_WIN) #if defined(QT_DEBUG) libChannelModule->setFileName("H:/MyProjects/QtBasis/IPCTest/build-Debug/ChannelModule/debug/ChannelModule.dll"); #elif defined(QT_RELEASE) libChannelModule->setFileName("H:/MyProjects/QtBasis/IPCTest/build-Release/ChannelModule/release/ChannelModule.dll"); #endif #elif defined(Q_OS_LINUX) #if defined(QT_DEBUG) libChannelModule->setFileName("H:/MyProjects/QtBasis/IPCTest/build-Debug/ChannelModule/debug/ChannelModule.dll"); #elif defined(QT_RELEASE) libChannelModule->setFileName("H:/MyProjects/QtBasis/IPCTest/build-Release/ChannelModule/release/ChannelModule.dll"); #endif #endif if(!libChannelModule->load()) { qDebug() << "PlazaUI initial failed:ChannelModule load failed.ErrorString:" << libChannelModule->errorString() << endl; } else { pCreate f = (pCreate)libChannelModule->resolve("create"); if(f) { m_pChannelModule = f(); } else { qDebug() << Utility::instance()->strErrorPosition(QString::fromUtf8(__FILE__), QString::fromUtf8(__FUNCTION__), __LINE__) << libChannelModule->errorString() << endl; } } }
// // Returns 'true' if all seems OK. // bool FTNoIR_Protocol::checkServerInstallationOK() { if (!SCClientLib.isLoaded()) { qDebug() << "SCCheckClientDLL says: Starting Function"; SCClientLib.setFileName("SimConnect.DLL"); ActivationContext ctx(142); if (!SCClientLib.load()) { qDebug() << "SC load" << SCClientLib.errorString(); return false; } } else { qDebug() << "SimConnect already loaded"; } // // Get the functions from the DLL. // simconnect_open = (importSimConnect_Open) SCClientLib.resolve("SimConnect_Open"); if (simconnect_open == NULL) { qDebug() << "FTNoIR_Protocol::checkServerInstallationOK() says: SimConnect_Open function not found in DLL!"; return false; } simconnect_set6DOF = (importSimConnect_CameraSetRelative6DOF) SCClientLib.resolve("SimConnect_CameraSetRelative6DOF"); if (simconnect_set6DOF == NULL) { qDebug() << "FTNoIR_Protocol::checkServerInstallationOK() says: SimConnect_CameraSetRelative6DOF function not found in DLL!"; return false; } simconnect_close = (importSimConnect_Close) SCClientLib.resolve("SimConnect_Close"); if (simconnect_close == NULL) { qDebug() << "FTNoIR_Protocol::checkServerInstallationOK() says: SimConnect_Close function not found in DLL!"; return false; } //return true; simconnect_calldispatch = (importSimConnect_CallDispatch) SCClientLib.resolve("SimConnect_CallDispatch"); if (simconnect_calldispatch == NULL) { qDebug() << "FTNoIR_Protocol::checkServerInstallationOK() says: SimConnect_CallDispatch function not found in DLL!"; return false; } simconnect_subscribetosystemevent = (importSimConnect_SubscribeToSystemEvent) SCClientLib.resolve("SimConnect_SubscribeToSystemEvent"); if (simconnect_subscribetosystemevent == NULL) { qDebug() << "FTNoIR_Protocol::checkServerInstallationOK() says: SimConnect_SubscribeToSystemEvent function not found in DLL!"; return false; } simconnect_mapclienteventtosimevent = (importSimConnect_MapClientEventToSimEvent) SCClientLib.resolve("SimConnect_MapClientEventToSimEvent"); if (simconnect_subscribetosystemevent == NULL) { qDebug() << "FTNoIR_Protocol::checkServerInstallationOK() says: SimConnect_MapClientEventToSimEvent function not found in DLL!"; return false; } simconnect_addclienteventtonotificationgroup = (importSimConnect_AddClientEventToNotificationGroup) SCClientLib.resolve("SimConnect_AddClientEventToNotificationGroup"); if (simconnect_subscribetosystemevent == NULL) { qDebug() << "FTNoIR_Protocol::checkServerInstallationOK() says: SimConnect_AddClientEventToNotificationGroup function not found in DLL!"; return false; } simconnect_setnotificationgrouppriority = (importSimConnect_SetNotificationGroupPriority) SCClientLib.resolve("SimConnect_SetNotificationGroupPriority"); if (simconnect_subscribetosystemevent == NULL) { qDebug() << "FTNoIR_Protocol::checkServerInstallationOK() says: SimConnect_SetNotificationGroupPriority function not found in DLL!"; return false; } qDebug() << "FTNoIR_Protocol::checkServerInstallationOK() says: SimConnect functions resolved in DLL!"; return true; }
int main(int argc, char *argv[]) { int ret = -1; LibraryCleanupHandler cleanup; { ::initApp("tokoloshtail", argc, argv); QCoreApplication app(argc, argv); if (!QDBusConnection::sessionBus().isConnected()) { fprintf(stderr, "Cannot connect to the D-Bus session bus.\n" "To start it, run:\n" "\teval `dbus-launch --auto-syntax`\n"); return 1; } { QDBusInterface iface(SERVICE_NAME, "/"); if (iface.isValid()) { iface.call("quit"); } } // const QString pluginDirectory = Config::value<QString>("plugindir", PLUGINDIR); // ### Can't make this work const QString pluginDirectory = Config::value<QString>("plugindir", QDir::cleanPath(QCoreApplication::applicationDirPath() + "/../plugins")); Log::log(10) << "Using plugin directory" << pluginDirectory; const QString backendName = Config::value<QString>("backend", "xine"); Log::log(10) << "Searching for backend" << backendName; QDir dir(pluginDirectory); if (!dir.exists()) { Log::log(0) << pluginDirectory << " doesn't seem to exist"; return 1; } { Tail tail; Backend *backend = 0; QLibrary *library = 0; QHash<QLibrary*, BackendPlugin*> candidates; foreach(const QFileInfo &fi, dir.entryInfoList(QDir::Files, QDir::Size)) { QLibrary *lib = new QLibrary(fi.absoluteFilePath()); CreateBackend createBackend = 0; if (lib->load() && (createBackend = (CreateBackend)lib->resolve("createTokoloshBackendInterface"))) { BackendPlugin *interface = createBackend(); if (interface && interface->keys().contains(backendName, Qt::CaseInsensitive)) { backend = interface->createBackend(&tail); if (backend) { library = lib; break; } else { Log::log(0) << fi.absoluteFilePath() << "doesn't seem to be able to create a backend"; } delete interface; } else if (!interface) { delete lib; } else { candidates[lib] = interface; } } else { if (lib->isLoaded()) { Log::log(1) << "Can't load" << fi.absoluteFilePath() << lib->errorString(); } delete lib; } } Q_ASSERT(!backend == !library); if (!backend) { for (QHash<QLibrary*, BackendPlugin*>::const_iterator it = candidates.begin(); it != candidates.end(); ++it) { const bool hadBackend = backend != 0; if (!backend) backend = it.value()->createBackend(&app); if (hadBackend || !backend) { it.key()->unload(); delete it.key(); } else { library = it.key(); } delete it.value(); } } if (!backend) { Log::log(0) << "Can't find a suitable backend"; return 1; } cleanup.library = library; bool registered = false; for (int i=0; i<5; ++i) { if (QDBusConnection::sessionBus().registerService(SERVICE_NAME)) { registered = true; break; } ::sleep(500); } if (!registered) { Log::log(0) << "Can't seem to register service" << QDBusConnection::sessionBus().lastError().message(); return 1; } if (!tail.setBackend(backend)) { Log::log(0) << backend->errorMessage() << backend->errorCode(); return 1; } QDBusConnection::sessionBus().registerObject("/", &tail, QDBusConnection::ExportScriptableSlots |QDBusConnection::ExportScriptableSignals); Log::log(10) << "Using" << backend->name(); ret = app.exec(); } } return ret; }
void Init( bool b, int rate2, int bits2, int chn2, int /*buff*/ ) { mustReset = false; if ( !b ) { Save.odczytajopcje(); fs.Init(); fs.ApplyB(); } PlErr = false; if ( b ) { if ( !isOpen ) { if ( !pa_lib.isLoaded() ) { QString libName = "libpulse-simple" + libExt; #ifdef Q_WS_X11 libName += ".0"; #endif pa_lib.setFileName( libName ); if ( !pa_lib.load() ) { errStr = pa_lib.errorString(); PlErr = true; return; } qmplay_pa_simple_new = ( _qmplay_pa_simple_new )pa_lib.resolve( "pa_simple_new" ); qmplay_pa_simple_free = ( _qmplay_pa_simple_free )pa_lib.resolve( "pa_simple_free" ); qmplay_pa_simple_write = ( _qmplay_pa_simple_write )pa_lib.resolve( "pa_simple_write" ); qmplay_pa_simple_read = ( _qmplay_pa_simple_read )pa_lib.resolve( "pa_simple_read" ); qmplay_pa_simple_flush = ( _qmplay_pa_simple_flush )pa_lib.resolve( "pa_simple_flush" ); if ( !qmplay_pa_simple_new || !qmplay_pa_simple_free || !qmplay_pa_simple_write || !qmplay_pa_simple_read || !qmplay_pa_simple_flush ) { pa_lib.unload(); errStr = "błąd podczas pobierania funkcji z biblioteki: " + libName; PlErr = true; return; } } switch ( bits2 ) { case 8: ss.format = PA_SAMPLE_U8; break; case 16: ss.format = PA_SAMPLE_S16NE; break; case 24: ss.format = PA_SAMPLE_S24NE; break; case 32: ss.format = PA_SAMPLE_S32NE; break; } ss.channels = chn2; ss.rate = rate2; attr.maxlength = ( uint32_t ) -1; attr.tlength = delay * ( rate2 * ( bits2/8 ) * chn2 ); attr.prebuf = ( uint32_t ) -1; attr.minreq = ( uint32_t ) -1; attr.fragsize = attr.tlength; pa_channel_map *chn_map = NULL; if ( chn2 > 2 && chn2 <= 8 ) { chn_map = new pa_channel_map; chn_map->channels = chn2; chn_map->map[ 0 ] = PA_CHANNEL_POSITION_FRONT_LEFT; chn_map->map[ 1 ] = PA_CHANNEL_POSITION_FRONT_RIGHT; chn_map->map[ 2 ] = PA_CHANNEL_POSITION_FRONT_CENTER; chn_map->map[ 3 ] = PA_CHANNEL_POSITION_LFE; chn_map->map[ 4 ] = PA_CHANNEL_POSITION_REAR_LEFT; chn_map->map[ 5 ] = PA_CHANNEL_POSITION_REAR_RIGHT; chn_map->map[ 6 ] = PA_CHANNEL_POSITION_SIDE_LEFT; chn_map->map[ 7 ] = PA_CHANNEL_POSITION_SIDE_RIGHT; } pulse = qmplay_pa_simple_new( NULL, "QMPlay", PA_STREAM_PLAYBACK, NULL, "Output", &ss, chn_map, &attr, NULL ); delete chn_map; if ( !pulse ) { pa_lib.unload(); errStr = "błąd podczas otwierania wyjścia PulseAudio"; PlErr = true; return; } if ( REC ) { pulseREC = qmplay_pa_simple_new( NULL, "QMPlay", PA_STREAM_RECORD, NULL, "Input", &ss, chn_map, &attr, NULL ); if ( !pulseREC ) { qmplay_pa_simple_free( pulse ); pa_lib.unload(); errStr = "błąd podczas otwierania wejścia PulseAudio"; PlErr = true; return; } } isOpen = true; } } }
void SupportLibraryLoader::loadLibraries() const{ std::map<quint32, QString> order; QLibrary lib; bool ok = order.size() > 0; for(auto name : _order){ QFileInfo file; if (QFileInfo(name.second).exists()) { file = QFileInfo(name.second); } else { file = QFileInfo(_configLocation.absolutePath() + "/../" + name.second); } QString path = file.canonicalFilePath(); lib.setFileName(path); ok = lib.load(); if ( !ok){ kernel()->issues()->log(TR("Could not load library ") + path + ",error :" + lib.errorString()); } } }
void QgsPluginManager::getPluginDescriptions() { QString sharedLibExtension; #ifdef WIN32 sharedLibExtension = "*.dll"; #else sharedLibExtension = "*.so*"; #endif // check all libs in the current ans user plugins directories, and get name and descriptions QSettings settings; QStringList myPathList( lblPluginDir->text() ); QString myPaths = settings.value( "plugins/searchPathsForPlugins", "" ).toString(); if ( !myPaths.isEmpty() ) { myPathList.append( myPaths.split( "|" ) ); } for ( int j = 0; j < myPathList.size(); ++j ) { QString myPluginDir = myPathList.at( j ); QDir pluginDir( myPluginDir, sharedLibExtension, QDir::Name | QDir::IgnoreCase, QDir::Files | QDir::NoSymLinks ); if ( pluginDir.count() == 0 ) { QMessageBox::information( this, tr( "No Plugins" ), tr( "No QGIS plugins found in %1" ).arg( myPluginDir ) ); return; } QgsDebugMsg( "PLUGIN MANAGER:" ); for ( uint i = 0; i < pluginDir.count(); i++ ) { QString lib = QString( "%1/%2" ).arg( myPluginDir ).arg( pluginDir[i] ); #ifdef TESTLIB // This doesn't work on WIN32 and causes problems with plugins // on OS X (the code doesn't cause a problem but including dlfcn.h // renders plugins unloadable) #if !defined(WIN32) && !defined(Q_OS_MACX) // test code to help debug loading problems // This doesn't work on WIN32 and causes problems with plugins // on OS X (the code doesn't cause a problem but including dlfcn.h // renders plugins unloadable) //void *handle = dlopen((const char *) lib, RTLD_LAZY); void *handle = dlopen( lib.toLocal8Bit().data(), RTLD_LAZY | RTLD_GLOBAL ); if ( !handle ) { QgsDebugMsg( "Error in dlopen: " ); QgsDebugMsg( dlerror() ); } else { QgsDebugMsg( "dlopen suceeded for " + lib ); dlclose( handle ); } #endif //#ifndef WIN32 && Q_OS_MACX #endif //#ifdef TESTLIB QgsDebugMsg( "Examining: " + lib ); QLibrary *myLib = new QLibrary( lib ); bool loaded = myLib->load(); if ( !loaded ) { QgsDebugMsg( QString( "Failed to load: %1 (%2)" ).arg( myLib->fileName() ).arg( myLib->errorString() ) ); delete myLib; continue; } QgsDebugMsg( "Loaded library: " + myLib->fileName() ); // Don't bother with libraries that are providers //if(!myLib->resolve("isProvider")) //MH: Replaced to allow for plugins that are linked to providers //type is only used in non-provider plugins if ( !myLib->resolve( "type" ) ) { delete myLib; continue; } // resolve the metadata from plugin name_t *pName = ( name_t * ) cast_to_fptr( myLib->resolve( "name" ) ); description_t *pDesc = ( description_t * ) cast_to_fptr( myLib->resolve( "description" ) ); category_t *pCat = ( category_t * ) cast_to_fptr( myLib->resolve( "category" ) ); version_t *pVersion = ( version_t * ) cast_to_fptr( myLib->resolve( "version" ) ); icon_t* pIcon = ( icon_t * ) cast_to_fptr( myLib->resolve( "icon" ) ); // show the values (or lack of) for each function if ( pName ) { QgsDebugMsg( "Plugin name: " + pName() ); } else { QgsDebugMsg( "Plugin name not returned when queried" ); } if ( pDesc ) { QgsDebugMsg( "Plugin description: " + pDesc() ); } else { QgsDebugMsg( "Plugin description not returned when queried" ); } if ( pCat ) { QgsDebugMsg( "Plugin category: " + pCat() ); } else { QgsDebugMsg( "Plugin category not returned when queried" ); } if ( pVersion ) { QgsDebugMsg( "Plugin version: " + pVersion() ); } else { QgsDebugMsg( "Plugin version not returned when queried" ); } if ( pIcon ) { QgsDebugMsg( "Plugin icon: " + pIcon() ); } if ( !pName || !pDesc || !pVersion ) { QgsDebugMsg( "Failed to get name, description, or type for " + myLib->fileName() ); delete myLib; continue; } QString pluginName = pName(); QString pluginDesc = pDesc(); // if no category defined - use default value QString pluginCat = ( pCat ? pCat() : tr( "Plugins" ) ); QString pluginVersion = pVersion(); QString pluginIconFileName = ( pIcon ? pIcon() : QString() ); QString baseName = QFileInfo( lib ).baseName(); QString myLibraryName = pluginDir[i]; // filtering will be done on the display role so give it name and desription // user wont see this text since we are using a custome delegate QStandardItem * mypDetailItem = new QStandardItem( pluginName + " - " + pluginDesc ); mypDetailItem->setData( myLibraryName, PLUGIN_LIBRARY_ROLE ); mypDetailItem->setData( myPluginDir, PLUGIN_DIRECTORY_ROLE ); mypDetailItem->setData( baseName, PLUGIN_BASE_NAME_ROLE ); //for matching in registry later QgsDetailedItemData myData; myData.setTitle( pluginName ); myData.setDetail( pluginDesc ); myData.setCategory( tr( "Installed in %1 menu/toolbar" ).arg( pluginCat ) ); myData.setRenderAsWidget( false ); myData.setCheckable( true ); myData.setChecked( false ); //start unchecked - we will check it later if needed if ( pluginIconFileName.isEmpty() ) myData.setIcon( QPixmap( QgsApplication::defaultThemePath() + "/plugin.png" ) ); else myData.setIcon( QPixmap( pluginIconFileName ) ); QgsDebugMsg( "Getting an instance of the QgsPluginRegistry" ); // check to see if the plugin is loaded and set the checkbox accordingly QgsPluginRegistry *pRegistry = QgsPluginRegistry::instance(); // get the library using the plugin description if ( !pRegistry->isLoaded( baseName ) ) { QgsDebugMsg( "Couldn't find plugin in the registry" ); } else { QgsDebugMsg( "Found plugin in the registry" ); // TODO: this check shouldn't be necessary, plugin base names must be unique if ( pRegistry->library( baseName ) == myLib->fileName() ) { // set the checkbox myData.setChecked( true ); } } QVariant myVariant = qVariantFromValue( myData ); mypDetailItem->setData( myVariant, PLUGIN_DATA_ROLE ); // Add items to model mModelPlugins->appendRow( mypDetailItem ); delete myLib; } } }
bool KviModuleManager::loadModule(const QString &modName) { if(findModule(modName)) { //qDebug("MODULE %s ALREADY IN CORE MEMORY",modName); return true; } QString tmp; QString szName; #if defined(COMPILE_ON_WINDOWS) KviQString::appendFormatted(szName,"kvi%Q.dll",&modName); #elif defined(COMPILE_ON_MINGW) KviQString::appendFormatted(szName,"libkvi%Q.dll",&modName); #else KviQString::appendFormatted(szName,"libkvi%Q.so",&modName); #endif szName=szName.toLower(); g_pApp->getLocalKvircDirectory(tmp,KviApplication::Modules,szName); if(!KviFileUtils::fileExists(tmp)) { g_pApp->getGlobalKvircDirectory(tmp,KviApplication::Modules,szName); } QLibrary* pLibrary = new QLibrary(tmp); pLibrary->setLoadHints(QLibrary::ExportExternalSymbolsHint); if(!pLibrary->load()) { m_szLastError = pLibrary->errorString(); delete pLibrary; return false; } KviModuleInfo * info = (KviModuleInfo *)pLibrary->resolve(KVIRC_MODULE_STRUCTURE_SYMBOL); if(!info) { m_szLastError = __tr2qs("No " KVIRC_MODULE_STRUCTURE_SYMBOL " symbol exported: not a kvirc module ?"); pLibrary->unload(); delete pLibrary; return false; } if(!info->szKVIrcVersion) { m_szLastError = __tr2qs("This module has no version information: refusing to load it"); pLibrary->unload(); delete pLibrary; return false; } if(!KVI_OPTION_BOOL(KviOption_boolIgnoreModuleVersions)) { if(!kvi_strEqualCS(info->szKVIrcVersion,KVI_VERSION)) { m_szLastError = __tr2qs("This module was compiled for a different KVIrc version and can't be loaded"); m_szLastError += " ("; m_szLastError += info->szKVIrcVersion; m_szLastError += ")"; pLibrary->unload(); delete pLibrary; return false; } } KviModule * module = new KviModule(pLibrary,info,modName,szName.toUtf8().data()); // the module is probably up.. the only thing can fail is the init_routine now // load the message catalogue if any if(info->szModuleContext) { QString szDir; // it's more probable to have the translations in the global directory // try it as first... (yes, catalogue overriding is impossible this way.. but, anybody cares ?) g_pApp->getGlobalKvircDirectory(szDir,KviApplication::Locale); if(!KviLocale::instance()->loadCatalogue(info->szModuleContext,szDir)) { // try the local directory then g_pApp->getLocalKvircDirectory(szDir,KviApplication::Locale); KviLocale::instance()->loadCatalogue(info->szModuleContext,szDir); } } if(info->init_routine) { if(!((info->init_routine)(module))) { m_szLastError = __tr2qs("Failed to execute the init routine"); //qDebug("ERROR IN LOADING MODULE %s (%s): failed to execute the init routine",modName,szName.ptr()); delete module; // kill the message catalogue too then KviLocale::instance()->unloadCatalogue(modName); return false; } } m_pModuleDict->insert(modName,module); /* registerDefaultCommands(module); */ module->registerDefaultCommands(); if(KVI_OPTION_BOOL(KviOption_boolCleanupUnusedModules)) { if(!m_pCleanupTimer->isActive()) { if(KVI_OPTION_UINT(KviOption_uintModuleCleanupTimerInterval) < 30) KVI_OPTION_UINT(KviOption_uintModuleCleanupTimerInterval) = 30; m_pCleanupTimer->start(KVI_OPTION_UINT(KviOption_uintModuleCleanupTimerInterval) * 1000); } } // be verbose if needed....just make sure that we're not shutting down... if(_OUTPUT_VERBOSE && !g_pApp->kviClosingDown()) { if(g_pMainWindow) { KviConsoleWindow * pWnd = g_pMainWindow->firstConsole(); if(pWnd) // this may be NULL when the app is starting up pWnd->output( KVI_OUT_VERBOSE, __tr2qs("Loaded module '%s' (%s)"), modName.toUtf8().data(), szName.toUtf8().data() ); } } return true; }
void JVM::jvmStartup(QString libname) { QLibrary lib (libname); cjvm_fn fn = (cjvm_fn) lib.resolve("JNI_CreateJavaVM"); qDebug() << "libjvm found in" << libname; setSettingsValue("extensions/jvm_path", libname); if (!fn) { Logger::global()->enterLogMessage("JPlugin", QObject::tr("Failed to load the correct libjvm: %1").arg(lib.errorString())); return; } jint res; JavaVMInitArgs vm_args; #ifdef DEBUG_BUILD JavaVMOption options[9]; #else JavaVMOption options[7]; #endif JNIEnv* env; QByteArray classpath = getClassPath().toUtf8(); int mb = getSettingsValue("java/maxheap").toInt(); if (!mb) mb = 16; classpath.prepend("-Djava.class.path="); qDebug() << "Java Classpath set to" << classpath; options[0].optionString = classpath.data(); options[1].optionString = static_cast<char*>(alloca(24)); snprintf(options[1].optionString, 24, "-Xmx%dm", mb); options[2].optionString = const_cast<char*>("-Djava.security.manager"); options[3].optionString = const_cast<char*>("-Djava.security.policy=" DATA_LOCATION "/data/java/extension.policy"); options[4].optionString = const_cast<char*>("-XX:+UseParNewGC"); options[5].optionString = const_cast<char*>("-XX:MinHeapFreeRatio=5"); options[6].optionString = const_cast<char*>("-XX:MaxHeapFreeRatio=10"); #ifdef DEBUG_BUILD options[7].optionString = const_cast<char*>("-Xdebug"); options[8].optionString = const_cast<char*>("-Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=8222"); #endif vm_args.version = 0x00010006; vm_args.options = options; vm_args.nOptions = sizeof(options)/sizeof(options[0]); vm_args.ignoreUnrecognized = JNI_TRUE; res = fn(&m_jvm, (void**)&env, &vm_args); if (res < 0) { Logger::global()->enterLogMessage("JPlugin", QObject::tr("Failed to create a Java VM")); return; } JNIEnv** penv = new JNIEnv*; *penv = env; m_env.setLocalData(penv); if (!m_instance) m_instance = this; try { singleCObjectRegisterNatives(); JSettings::registerNatives(); JPlugin::registerNatives(); JTransferPlugin::registerNatives(); JDownloadPlugin::registerNatives(); JBackgroundWorker::registerNatives(); JAccountStatusPlugin::registerNatives(); } catch (...) { qDebug() << "Failed to register JNI functions. This usually happens when there is an API discrepancy between the Java and the native code.\nPlease, remove ~/.local/share/fatrat/data/java/libs/fatrat-jplugins-core.jar, and try again"; abort(); } }