예제 #1
0
		IPlugin* load(const char* path) override
		{
			g_log_info.log("plugins") << "loading plugin " << path;
			typedef IPlugin* (*PluginCreator)(Engine&);

			auto* lib = loadLibrary(path);
			if (lib)
			{
				PluginCreator creator = (PluginCreator)getLibrarySymbol(lib, "createPlugin");
				if (creator)
				{
					IPlugin* plugin = creator(m_engine);
					if (!plugin || !plugin->create())
					{
						LUMIX_DELETE(m_engine.getAllocator(), plugin);
						ASSERT(false);
						return nullptr;
					}
					m_plugins.push(plugin);
					m_libraries.push(lib);
					m_library_loaded.invoke(lib);
					g_log_info.log("plugins") << "plugin loaded";
					return plugin;
				}
			}
			unloadLibrary(lib);
			return 0;
		}
bool OsmAnd::CoreResourcesEmbeddedBundle_P::loadFromCurrentExecutable()
{
#if defined(OSMAND_TARGET_OS_windows)
    _bundleLibraryNeedsClose = false;
    _bundleLibrary = GetModuleHandleA(NULL);
    if (_bundleLibrary == NULL)
    {
        LogPrintf(LogSeverityLevel::Error,
            "Failed to open main program executable as library");
        return false;
    }
#else
    _bundleLibraryNeedsClose = true;
    _bundleLibrary = dlopen(NULL, RTLD_NOW | RTLD_GLOBAL);
    if (_bundleLibrary == NULL)
    {
        const auto error = dlerror();
        LogPrintf(LogSeverityLevel::Error,
            "Failed to open main program executable as library: %s", error ? error : "unknown");
        return false;
    }
#endif

    if (!loadResources())
    {
        unloadLibrary();
        return false;
    }

    return true;
}
void 
SharedLibrary::loadLibary()
{
  unloadLibrary();
  RString nstr = _library->convertToNative();
  _libReference = (void*)LoadLibrary(ACDK_API_CONSTCHARPTR(nstr->native_c_str()));
}
예제 #4
0
bool SharedLibrary::unload() {
    if (mHandle == NULL)
        return true;
    bool success=unloadLibrary(mHandle);
    mHandle=NULL;
    return success;
}
bool OsmAnd::CoreResourcesEmbeddedBundle_P::loadFromLibrary(const QString& libraryNameOrFilename)
{
#if defined(OSMAND_TARGET_OS_windows)
    _bundleLibraryNeedsClose = true;
    _bundleLibrary = LoadLibraryA(qPrintable(libraryNameOrFilename));
    if (_bundleLibrary == NULL)
    {
        LogPrintf(LogSeverityLevel::Error,
            "Failed to load library from '%s'", qPrintable(libraryNameOrFilename));
        return false;
    }
#else
    _bundleLibraryNeedsClose = true;
    _bundleLibrary = dlopen(qPrintable(libraryNameOrFilename), RTLD_NOW | RTLD_GLOBAL);
    if (_bundleLibrary == NULL)
    {
        const auto error = dlerror();
        LogPrintf(LogSeverityLevel::Error,
            "Failed to load library from '%s': %s",
            qPrintable(libraryNameOrFilename),
            error ? error : "unknown");
        return false;
    }
#endif

    if (!loadResources())
    {
        unloadLibrary();
        return false;
    }

    return true;
}
예제 #6
0
void
PluginLoader::Impl::pluginDeleted(PluginDeletionNotifyAdapter *adapter)
{
    void *handle = m_pluginLibraryHandleMap[adapter];
    if (handle) unloadLibrary(handle);
    m_pluginLibraryHandleMap.erase(adapter);
}
예제 #7
0
			void onGameModeToggled(bool is_starting)
			{
				if (is_starting)
				{
					if (!m_library)
					{
						m_library = Library::create(m_library_path, m_allocator);
						if (!m_library->load())
						{
							g_log_error.log("script") << "Could not load " << m_library_path.c_str();
							Library::destroy(m_library);
							m_library = NULL;
							return;
						}
						m_update_function = (UpdateFunction)m_library->resolve("update");
						m_done_function = (DoneFunction)m_library->resolve("done");
						m_serialize_function = (SerializeFunction)m_library->resolve("serialize");
						m_deserialize_function = (DeserializeFunction)m_library->resolve("deserialize");
						InitFunction init_function = (InitFunction)m_library->resolve("init");
						if (!m_update_function || !init_function)
						{
							g_log_error.log("script") << "Script interface in " << m_library_path.c_str() << " is not complete";
						}

						if (init_function)
						{
							init_function(this);
						}
					}
				}
				else
				{
					unloadLibrary();
				}
			}
예제 #8
0
void Foam::codedBase::updateLibrary
(
    const word& name
) const
{
    const dictionary& dict = this->codeDict();

    dynamicCode::checkSecurity
    (
        "codedBase::updateLibrary()",
        dict
    );

    dynamicCodeContext context(dict);

    // codeName: name + _<sha1>
    // codeDir : name
    dynamicCode dynCode
    (
        name + context.sha1().str(true),
        name
    );
    const fileName libPath = dynCode.libPath();


    // the correct library was already loaded => we are done
    if (libs().findLibrary(libPath))
    {
        return;
    }

    Info<< "Using dynamicCode for " << this->description().c_str()
        << " at line " << dict.startLineNumber()
        << " in " << dict.name() << endl;


    // remove instantiation of fvPatchField provided by library
    this->clearRedirect();

    // may need to unload old library
    unloadLibrary
    (
        oldLibPath_,
        dynamicCode::libraryBaseName(oldLibPath_),
        context.dict()
    );

    // try loading an existing library (avoid compilation when possible)
    if (!loadLibrary(libPath, dynCode.codeName(), context.dict()))
    {
        createLibrary(dynCode, context);

        loadLibrary(libPath, dynCode.codeName(), context.dict());
    }

    // retain for future reference
    oldLibPath_ = libPath;
}
예제 #9
0
		IPlugin* load(const char* path) override
		{
			char path_with_ext[MAX_PATH_LENGTH];
			copyString(path_with_ext, path);
			const char* ext =
			#ifdef _WIN32
				".dll";
			#elif defined __linux__
				".so";
			#else 
				#error Unknown platform
			#endif
			if (!PathUtils::hasExtension(path, ext + 1)) catString(path_with_ext, ext);
			g_log_info.log("Core") << "loading plugin " << path_with_ext;
			typedef IPlugin* (*PluginCreator)(Engine&);
			auto* lib = loadLibrary(path_with_ext);
			if (lib)
			{
				PluginCreator creator = (PluginCreator)getLibrarySymbol(lib, "createPlugin");
				if (creator)
				{
					IPlugin* plugin = creator(m_engine);
					if (!plugin)
					{
						g_log_error.log("Core") << "createPlugin failed.";
						LUMIX_DELETE(m_engine.getAllocator(), plugin);
						ASSERT(false);
					}
					else
					{
						addPlugin(plugin);
						m_libraries.push(lib);
						m_library_loaded.invoke(lib);
						g_log_info.log("Core") << "Plugin loaded.";
						Debug::StackTree::refreshModuleList();
						return plugin;
					}
				}
				else
				{
					g_log_error.log("Core") << "No createPlugin function in plugin.";
				}
				unloadLibrary(lib);
			}
			else
			{
				auto* plugin = StaticPluginRegister::create(path, m_engine);
				if (plugin)
				{
					g_log_info.log("Core") << "Plugin loaded.";
					addPlugin(plugin);
					return plugin;
				}
				g_log_warning.log("Core") << "Failed to load plugin.";
			}
			return nullptr;
		}
예제 #10
0
		void unload(IPlugin* plugin) override
		{
			int idx = m_plugins.indexOf(plugin);
			ASSERT(idx >= 0);
			LUMIX_DELETE(m_engine.getAllocator(), m_plugins[idx]);
			unloadLibrary(m_libraries[idx]);
			m_libraries.erase(idx);
			m_plugins.erase(idx);
		}
예제 #11
0
PluginManager::~PluginManager()
{
    // Note: The plugins do not need to (and must not) be destroyed, because this is done
    // inside the plugin library, when deinitialize() is called.

    // Unload plugin libraries
    for (const std::pair<std::string, PluginLibrary *> & it : m_librariesByFilePath) {
        unloadLibrary(it.second);
    }
}
예제 #12
0
int EffectUnloadLibrary(int handle)
{
    int ret = init();
    if (ret < 0) {
        return ret;
    }

    ret = unloadLibrary(handle);
    updateNumEffects();
    return ret;
}
예제 #13
0
void Foam::codedFunctionObject::updateLibrary() const
{
    dynamicCode::checkSecurity
    (
        "codedFunctionObject::updateLibrary()",
        dict_
    );

    dynamicCodeContext context(dict_);

    // codeName: redirectType + _<sha1>
    // codeDir : redirectType
    dynamicCode dynCode
    (
        redirectType_ + context.sha1().str(true),
        redirectType_
    );
    const fileName libPath = dynCode.libPath();


    // the correct library was already loaded => we are done
    if (const_cast<Time&>(time_).libs().findLibrary(libPath))
    {
        return;
    }

    Info<< "Using dynamicCode for functionObject " << name()
        << " at line " << dict_.startLineNumber()
        << " in " << dict_.name() << endl;


    // remove instantiation of fvPatchField provided by library
    redirectFunctionObjectPtr_.clear();

    // may need to unload old library
    unloadLibrary
    (
        oldLibPath_,
        dynamicCode::libraryBaseName(oldLibPath_),
        context.dict()
    );

    // try loading an existing library (avoid compilation when possible)
    if (!loadLibrary(libPath, dynCode.codeName(), context.dict()))
    {
        createLibrary(dynCode, context);

        loadLibrary(libPath, dynCode.codeName(), context.dict());
    }

    // retain for future reference
    oldLibPath_ = libPath;
}
예제 #14
0
		~PluginManagerImpl()
		{
			for (int i = m_plugins.size() - 1; i >= 0; --i)
			{
				LUMIX_DELETE(m_engine.getAllocator(), m_plugins[i]);
			}

			for (int i = 0; i < m_libraries.size(); ++i)
			{
				unloadLibrary(m_libraries[i]);
			}
		}
예제 #15
0
extern "C" DECLSPEC void SDLCALL Java_paulscode_android_mupen64plusae_jni_NativeExports_unloadLibraries(JNIEnv* env, jclass cls)
{
    // Unload the libraries to ensure that static variables are re-initialized next time
    LOGI("Unloading native libraries");

    // Clear stale error messages
    dlerror();

    // Find and call the JNI_OnUnLoad functions from the SDL2 library
    pJNI_OnUnload JNI_OnUnLoad = (pJNI_OnUnload) locateFunction(handleSDL, "SDL2",       "JNI_OnUnload");
    JNI_OnUnLoad(mVm, mReserved);
    JNI_OnUnLoad = NULL;

    // Nullify function pointers so that they can no longer be used
    aeiInit         = NULL;
    sdlInit         = NULL;
    sdlSetScreen    = NULL;
    sdlMainReady    = NULL;
    coreDoCommand   = NULL;
    frontMain       = NULL;
    nativeResume    = NULL;
    nativePause     = NULL;

    // Close shared libraries
    unloadLibrary(handleFront,    "mupen64plus-ui-console");
    unloadLibrary(handleCore,     coreLibraryName);
    unloadLibrary(handleFreetype, "freetype");
    unloadLibrary(handleSDL,      "SDL2");
    unloadLibrary(handleAEI,      "ae-imports");

    // Nullify handles so that they can no longer be used
    handleFront    = NULL;
    handleCore     = NULL;
    handleFreetype = NULL;
    handleSDL      = NULL;
    handleAEI      = NULL;

    coreLibraryName = "mupen64plus-core";
}
예제 #16
0
void SharedLibrary::gc(DL_HANDLE handle) {
    static std::vector<DL_HANDLE> *sHandles=new std::vector<DL_HANDLE>;
    if (handle) {
        if (sHandles==NULL)
            sHandles=new std::vector<DL_HANDLE>;
        sHandles->push_back(handle);
    }else if(sHandles){
        for (std::vector<DL_HANDLE>::iterator i=sHandles->begin();i!=sHandles->end();++i) {
            unloadLibrary(*i);
        }
        delete sHandles;
        sHandles=NULL;
    }
}
예제 #17
0
bool PluginManager::loadLibrary(const std::string & filePath, bool reload)
{
    // Check if library is already loaded and reload is not requested
    auto it = m_librariesByFilePath.find(filePath);
    if (it != m_librariesByFilePath.cend() && !reload) {
        return true;
    }

    // Get path to directory containing the plugin library
    std::string pluginPath = iozeug::removeTrailingPathSeparator(iozeug::getPath(filePath));

    // Load extra information from "PluginInfo.json" if present
    Variant pluginInfo = Variant();
    SerializerJSON json;
    if (json.load(pluginInfo, pluginPath + iozeug::SystemInfo::pathSeperator() + "PluginInfo.json"))
    {
        // Replace every occurance of ${PluginPath} with respective path
        std::string jsonString = pluginInfo.toJSON();
        auto from = std::string("${PluginPath}");
        size_t start_pos = 0;
        while((start_pos = jsonString.find(from, start_pos)) != std::string::npos) {
            jsonString.replace(start_pos, from.length(), pluginPath);
            start_pos += pluginPath.length();
        }

        // Convert back to JSON Variant
        json.fromString(pluginInfo, jsonString);
    }

    // If library was already loaded, remember it in case reloading fails
    PluginLibrary * previous = nullptr;
    if (it != m_librariesByFilePath.cend()) {
        previous = it->second;
    }

    // Open plugin library
    PluginLibraryImpl * library = new PluginLibraryImpl(filePath);
    if (!library->isValid())
    {
        // Loading failed. Destroy library object and return failure.
        globjects::warning() << (previous ? "Reloading" : "Loading") << " plugin(s) from '" << filePath << "' failed.";

        delete library;
        return false;
    }

    // Library has been loaded. Unload previous incarnation.
    if (previous) {
        unloadLibrary(previous);
    }

    // Add library to list (in case of reload, this overwrites the previous)
    m_librariesByFilePath[filePath] = library;

    // Initialize plugin library
    library->initialize();

    // Iterate over plugins
    const unsigned int numPlugins = library->numPlugins();
    for (unsigned int i = 0; i < numPlugins; ++i) 
    {
        // Get plugin
        gloperate::Plugin * plugin = library->plugin(i);
        if (!plugin)
            continue;

        // // Set relative data path for plugin (if known)
        // if (!relDataPath.empty()) {
        //     plugin->setRelDataPath(relDataPath.c_str());
        // }
        if (!pluginInfo.isNull())
        {
            plugin->setPluginInfo(pluginInfo);
        }

        // Add plugin to list
        m_plugins.push_back(plugin);

        // Save plugin by name
        std::string name = plugin->name();
        m_pluginsByName[name] = plugin;
    }

    // Return success
    return true;
}
예제 #18
0
void displayError(WCHAR* pwszError)
{
	MessageBoxW(NULL, pwszError, L"Raw Input error!", MB_ICONERROR | MB_OK);
	CRawInput::hookLibrary(false);
	unloadLibrary();
}
void Foam::codedFixedValueFvPatchField<Type>::updateLibrary() const
{
    dynamicCode::checkSecurity
    (
        "codedFixedValueFvPatchField<Type>::updateLibrary()",
        dict_
    );

    // use system/codeDict or in-line
    const dictionary& codeDict =
    (
        dict_.found("code")
      ? dict_
      : this->dict().subDict(redirectType_)
    );

    dynamicCodeContext context(codeDict);

    // codeName: redirectType + _<sha1>
    // codeDir : redirectType
    dynamicCode dynCode
    (
        redirectType_ + context.sha1().str(true),
        redirectType_
    );
    const fileName libPath = dynCode.libPath();


    // the correct library was already loaded => we are done
    if (const_cast<Time&>(this->db().time()).libs().findLibrary(libPath))
    {
        return;
    }

    Info<< "Using dynamicCode for patch " << this->patch().name()
        << " on field " << this->dimensionedInternalField().name() << nl
        << "at line " << codeDict.startLineNumber()
        << " in " << codeDict.name() << endl;


    // remove instantiation of fvPatchField provided by library
    redirectPatchFieldPtr_.clear();

    // may need to unload old library
    unloadLibrary
    (
        oldLibPath_,
        dynamicCode::libraryBaseName(oldLibPath_),
        context.dict()
    );

    // try loading an existing library (avoid compilation when possible)
    if (!loadLibrary(libPath, dynCode.codeName(), context.dict()))
    {
        createLibrary(dynCode, context);

        loadLibrary(libPath, dynCode.codeName(), context.dict());
    }

    // retain for future reference
    oldLibPath_ = libPath;
}
OsmAnd::CoreResourcesEmbeddedBundle_P::~CoreResourcesEmbeddedBundle_P()
{
    unloadLibrary();
}
예제 #21
0
int main( int argc, _TCHAR* argv[] )
{
    _TCHAR*  errorMsg;
    _TCHAR*  program;
    _TCHAR*  iniFile;
    _TCHAR*  ch;
    _TCHAR** configArgv = NULL;
    int 	 configArgc = 0;
    int      exitCode = 0;
    int      ret = 0;
    void *	 handle = 0;
    RunMethod 		runMethod;
    SetInitialArgs  setArgs;

    setlocale(LC_ALL, "");

    initialArgc = argc;
    initialArgv = malloc((argc + 1) * sizeof(_TCHAR*));
    memcpy(initialArgv, argv, (argc + 1) * sizeof(_TCHAR*));

    /*
     * Strip off any extroneous <CR> from the last argument. If a shell script
     * on Linux is created in DOS format (lines end with <CR><LF>), the C-shell
     * does not strip off the <CR> and hence the argument is bogus and may
     * not be recognized by the launcher or eclipse itself.
     */
    ch = _tcschr( argv[ argc - 1 ], _T_ECLIPSE('\r') );
    if (ch != NULL)
    {
        *ch = _T_ECLIPSE('\0');
    }

    /* Determine the full pathname of this program. */
    program = findProgram(argv);

    /* Parse configuration file arguments */
    iniFile = checkForIni(argc, argv);
    if (iniFile != NULL)
        ret = readConfigFile(iniFile, &configArgc, &configArgv);
    else
        ret = readIniFile(program, &configArgc, &configArgv);
    if (ret == 0)
    {
        parseArgs (&configArgc, configArgv);
    }

    /* Parse command line arguments           */
    /* Overrides configuration file arguments */
    parseArgs( &argc, argv );

    /* Special case - user arguments specified in the config file
     * are appended to the user arguments passed from the command line.
     */
    if (configArgc > 0)
    {
        createUserArgs(configArgc, configArgv, &argc, &argv);
    }

    /* Initialize official program name */
    officialName = name != NULL ? _tcsdup( name ) : getDefaultOfficialName(program);

    /* Find the directory where the Eclipse program is installed. */
    programDir = getProgramDir(program);

    /* Find the eclipse library */
    eclipseLibrary = findLibrary(eclipseLibrary, program);

    if(eclipseLibrary != NULL)
        handle = loadLibrary(eclipseLibrary);
    if(handle == NULL) {
        errorMsg = malloc( (_tcslen(libraryMsg) + _tcslen(officialName) + 10) * sizeof(_TCHAR) );
        _stprintf( errorMsg, libraryMsg, officialName );
        if (!suppressErrors)
            displayMessage( officialName, errorMsg );
        else
            _ftprintf(stderr, _T_ECLIPSE("%s:\n%s\n"), officialName, errorMsg);
        free( errorMsg );
        exit( 1 );
    }

    setArgs = (SetInitialArgs)findSymbol(handle, SET_INITIAL_ARGS);
    if(setArgs != NULL)
        setArgs(initialArgc, initialArgv, eclipseLibrary);
    else {
        if(!suppressErrors)
            displayMessage(officialName, entryMsg);
        else
            _ftprintf(stderr, _T_ECLIPSE("%s:\n%s\n"), officialName, entryMsg);
        exit(1);
    }

    runMethod = (RunMethod)findSymbol(handle, RUN_METHOD);
    if(runMethod != NULL)
        exitCode = runMethod(argc, argv, userVMarg);
    else {
        if(!suppressErrors)
            displayMessage(officialName, entryMsg);
        else
            _ftprintf(stderr, _T_ECLIPSE("%s:\n%s\n"), officialName, entryMsg);
        exit(1);
    }
    unloadLibrary(handle);

    free( eclipseLibrary );
    free( programDir );
    free( program );
    free( officialName );

    return exitCode;
}
예제 #22
0
			virtual void beforeScriptCompiled() override
			{
				m_reload_after_compile = true;
				m_is_compiling = true;
				unloadLibrary();
			}
예제 #23
0
Plugin *
PluginLoader::Impl::loadPlugin(PluginKey key,
                               float inputSampleRate, int adapterFlags)
{
    string libname, identifier;
    if (!decomposePluginKey(key, libname, identifier)) {
        std::cerr << "Vamp::HostExt::PluginLoader: Invalid plugin key \""
                  << key << "\" in loadPlugin" << std::endl;
        return 0;
    }
        
    string fullPath = getLibraryPathForPlugin(key);
    if (fullPath == "") return 0;
    
    void *handle = loadLibrary(fullPath);
    if (!handle) return 0;
    
    VampGetPluginDescriptorFunction fn =
        (VampGetPluginDescriptorFunction)lookupInLibrary
        (handle, "vampGetPluginDescriptor");

    if (!fn) {
        unloadLibrary(handle);
        return 0;
    }

    int index = 0;
    const VampPluginDescriptor *descriptor = 0;

    while ((descriptor = fn(VAMP_API_VERSION, index))) {

        if (string(descriptor->identifier) == identifier) {

            Vamp::PluginHostAdapter *plugin =
                new Vamp::PluginHostAdapter(descriptor, inputSampleRate);

            Plugin *adapter = new PluginDeletionNotifyAdapter(plugin, this);

            m_pluginLibraryHandleMap[adapter] = handle;

            if (adapterFlags & ADAPT_INPUT_DOMAIN) {
                if (adapter->getInputDomain() == Plugin::FrequencyDomain) {
                    adapter = new PluginInputDomainAdapter(adapter);
                }
            }

            if (adapterFlags & ADAPT_BUFFER_SIZE) {
                adapter = new PluginBufferingAdapter(adapter);
            }

            if (adapterFlags & ADAPT_CHANNEL_COUNT) {
                adapter = new PluginChannelAdapter(adapter);
            }

            return adapter;
        }

        ++index;
    }

    cerr << "Vamp::HostExt::PluginLoader: Plugin \""
         << identifier << "\" not found in library \""
         << fullPath << "\"" << endl;

    return 0;
}
예제 #24
0
Common::Error ComposerEngine::run() {
	Common::Event event;

	_vars.resize(1000);
	for (uint i = 0; i < _vars.size(); i++)
		_vars[i] = 0;

	_queuedScripts.resize(10);
	for (uint i = 0; i < _queuedScripts.size(); i++) {
		_queuedScripts[i]._count = 0;
		_queuedScripts[i]._scriptId = 0;
	}

	if (!_bookIni.loadFromFile("book.ini")) {
		_directoriesToStrip = 0;
		if (!_bookIni.loadFromFile("programs/book.ini")) {
			// mac version?
			if (!_bookIni.loadFromFile("Darby the Dragon.ini"))
				if (!_bookIni.loadFromFile("Gregory.ini"))
					error("failed to find book.ini");
		}
	}

	uint width = 640;
	if (_bookIni.hasKey("Width", "Common"))
		width = atoi(getStringFromConfig("Common", "Width").c_str());
	uint height = 480;
	if (_bookIni.hasKey("Height", "Common"))
		height = atoi(getStringFromConfig("Common", "Height").c_str());
	initGraphics(width, height, true);
	_screen.create(width, height, Graphics::PixelFormat::createFormatCLUT8());

	Graphics::Cursor *cursor = Graphics::makeDefaultWinCursor();
	CursorMan.replaceCursor(cursor->getSurface(), cursor->getWidth(), cursor->getHeight(), cursor->getHotspotX(),
		cursor->getHotspotY(), cursor->getKeyColor());
	CursorMan.replaceCursorPalette(cursor->getPalette(), cursor->getPaletteStartIndex(), cursor->getPaletteCount());
	delete cursor;

	_console = new Console(this);

	loadLibrary(0);

	uint fps = atoi(getStringFromConfig("Common", "FPS").c_str());
	uint frameTime = 125; // Default to 125ms (1000/8)
	if (fps != 0)
		frameTime = 1000 / fps;
	else
		warning("FPS in book.ini is zero. Defaulting to 8...");
	uint32 lastDrawTime = 0;

	while (!shouldQuit()) {
		for (uint i = 0; i < _pendingPageChanges.size(); i++) {
			if (_pendingPageChanges[i]._remove)
				unloadLibrary(_pendingPageChanges[i]._pageId);
			else
				loadLibrary(_pendingPageChanges[i]._pageId);

			lastDrawTime = _system->getMillis();
		}
		_pendingPageChanges.clear();

		uint32 thisTime = _system->getMillis();
		// maintain our own internal timing, since otherwise we get
		// confused when starved of CPU (for example when the user
		// is dragging the scummvm window around)
		if (thisTime > _lastTime + frameTime)
			_currentTime += frameTime;
		else
			_currentTime += thisTime - _lastTime;
		_lastTime = thisTime;

		for (uint i = 0; i < _queuedScripts.size(); i++) {
			QueuedScript &script = _queuedScripts[i];
			if (!script._count)
				continue;
			if (script._baseTime + script._duration > _currentTime)
				continue;
			if (script._count != 0xffffffff)
				script._count--;
			script._baseTime = _currentTime;
			runScript(script._scriptId, i, 0, 0);
		}

		if (lastDrawTime + frameTime <= thisTime) {
			// catch up if we're more than 2 frames behind
			if (lastDrawTime + (frameTime * 2) <= thisTime)
				lastDrawTime = thisTime;
			else
				lastDrawTime += frameTime;

			redraw();

			tickOldScripts();
			processAnimFrame();
		} else if (_needsUpdate) {
			redraw();
		}

		while (_eventMan->pollEvent(event)) {
			switch (event.type) {
			case Common::EVENT_LBUTTONDOWN:
				onMouseDown(event.mouse);
				break;

			case Common::EVENT_LBUTTONUP:
				break;

			case Common::EVENT_RBUTTONDOWN:
				break;

			case Common::EVENT_MOUSEMOVE:
				onMouseMove(event.mouse);
				break;

			case Common::EVENT_KEYDOWN:
				switch (event.kbd.keycode) {
				case Common::KEYCODE_d:
					if (event.kbd.hasFlags(Common::KBD_CTRL)) {
						// Start the debugger
						getDebugger()->attach();
						getDebugger()->onFrame();
					}
					break;

				case Common::KEYCODE_q:
					if (event.kbd.hasFlags(Common::KBD_CTRL))
						quitGame();
					break;

				default:
					break;
				}

				onKeyDown(event.kbd.keycode);
				break;

			default:
				break;
			}
		}

		_system->delayMillis(20);
	}

	_screen.free();

	return Common::kNoError;
}
예제 #25
0
// The main function
int main(int argc, char* argv[])
{
	int option_index = 0;
	int opt;

	char* dbPath = NULL;
	char* userPIN = NULL;
	char* module = NULL;
	char* slot = NULL;
	char* serial = NULL;
	char* token = NULL;
	char *errMsg = NULL;
	int noPublicKey = 0;

	int result = 0;
	CK_RV rv;

	moduleHandle = NULL;
	p11 = NULL;
	CK_SLOT_ID slotID = 0;

	if (argc == 1)
	{
		usage();
		exit(0);
	}

	while ((opt = getopt_long(argc, argv, "hv", long_options, &option_index)) != -1)
	{
		switch (opt)
		{
			case OPT_DB:
				dbPath = optarg;
				break;
			case OPT_SLOT:
				slot = optarg;
				break;
			case OPT_SERIAL:
				serial = optarg;
				break;
			case OPT_TOKEN:
				token = optarg;
				break;
			case OPT_MODULE:
				module = optarg;
				break;
			case OPT_NO_PUBLIC_KEY:
				noPublicKey = 1;
				break;
			case OPT_PIN:
				userPIN = optarg;
				break;
			case OPT_VERSION:
			case 'v':
				printf("%s\n", PACKAGE_VERSION);
				exit(0);
				break;
			case OPT_HELP:
			case 'h':
			default:
				usage();
				exit(0);
				break;
		}
	}

	// Get a pointer to the function list for PKCS#11 library
	CK_C_GetFunctionList pGetFunctionList = loadLibrary(module, &moduleHandle, &errMsg);
	if (pGetFunctionList == NULL)
	{
		fprintf(stderr, "ERROR: Could not load the library: %s\n", errMsg);
		exit(1);
	}

	// Load the function list
	(*pGetFunctionList)(&p11);

	// Initialize the library
	rv = p11->C_Initialize(NULL_PTR);
	if (rv != CKR_OK)
	{
		fprintf(stderr, "ERROR: Could not initialize the library.\n");
		exit(1);
	}

	// Get the slotID
	result = findSlot(slot, serial, token, slotID);

	if (!result)
	{
		// Migrate the database
		result = migrate(dbPath, slotID, userPIN, noPublicKey);
	}

	// Finalize the library
	p11->C_Finalize(NULL_PTR);
	unloadLibrary(moduleHandle);

	return result;
}
예제 #26
0
ADSI::~ADSI()
{
    unloadLibrary();
}
예제 #27
0
void ComposerEngine::loadLibrary(uint id) {
	if (getGameType() == GType_ComposerV1 && !_libraries.empty()) {
		// kill the previous page, starting with any scripts running on it

		for (Common::List<OldScript *>::iterator i = _oldScripts.begin(); i != _oldScripts.end(); i++)
			delete *i;
		_oldScripts.clear();

		Library *library = &_libraries.front();
		unloadLibrary(library->_id);
	}

	Common::String filename;

	if (getGameType() == GType_ComposerV1) {
		if (!id || _bookGroup.empty())
			filename = getStringFromConfig("Common", "StartPage");
		else
			filename = getStringFromConfig(_bookGroup, Common::String::format("%d", id));
		filename = mangleFilename(filename);

		// bookGroup is the basename of the path.
		// TODO: tidy this up.
		_bookGroup.clear();
		for (uint i = 0; i < filename.size(); i++) {
			if (filename[i] == '~' || filename[i] == '/' || filename[i] == ':')
				continue;
			for (uint j = 0; j < filename.size(); j++) {
				if (filename[j] == '/') {
					_bookGroup.clear();
					continue;
				}
				if (filename[j] == '.')
					break;
				_bookGroup += filename[j];
			}
			break;
		}
	} else {
		if (!id)
			id = atoi(getStringFromConfig("Common", "StartUp").c_str());
		filename = getFilename("Libs", id);
	}

	Library library;

	library._id = id;
	library._archive = new ComposerArchive();
	if (!library._archive->openFile(filename))
		error("failed to open '%s'", filename.c_str());
	_libraries.push_front(library);

	Library &newLib = _libraries.front();

	Common::Array<uint16> buttonResources = library._archive->getResourceIDList(ID_BUTN);
	for (uint i = 0; i < buttonResources.size(); i++) {
		uint16 buttonId = buttonResources[i];
		Common::SeekableReadStream *stream = library._archive->getResource(ID_BUTN, buttonId);
		Button button(stream, buttonId, getGameType());

		bool inserted = false;
		for (Common::List<Button>::iterator b = newLib._buttons.begin(); b != newLib._buttons.end(); b++) {
			if (button._zorder < b->_zorder)
				continue;
			newLib._buttons.insert(b, button);
			inserted = true;
			break;
		}
		if (!inserted)
			newLib._buttons.push_back(button);
	}

	Common::Array<uint16> ambientResources = library._archive->getResourceIDList(ID_AMBI);
	for (uint i = 0; i < ambientResources.size(); i++) {
		Common::SeekableReadStream *stream = library._archive->getResource(ID_AMBI, ambientResources[i]);
		Button button(stream);
		newLib._buttons.insert(newLib._buttons.begin(), button);
	}

	Common::Array<uint16> accelResources = library._archive->getResourceIDList(ID_ACEL);
	for (uint i = 0; i < accelResources.size(); i++) {
		Common::SeekableReadStream *stream = library._archive->getResource(ID_ACEL, accelResources[i]);
		KeyboardHandler handler;
		handler.keyId = stream->readUint16LE();
		handler.modifierId = stream->readUint16LE();
		handler.scriptId = stream->readUint16LE();
		newLib._keyboardHandlers.push_back(handler);
	}

	Common::Array<uint16> randResources = library._archive->getResourceIDList(ID_RAND);
	for (uint i = 0; i < randResources.size(); i++) {
		Common::SeekableReadStream *stream = library._archive->getResource(ID_RAND, randResources[i]);
		Common::Array<RandomEvent> &events = _randomEvents[randResources[i]];
		uint16 count = stream->readUint16LE();
		for (uint j = 0; j < count; j++) {
			RandomEvent random;
			random.scriptId = stream->readUint16LE();
			random.weight = stream->readUint16LE();
			events.push_back(random);
		}
		delete stream;
	}

	// add background sprite, if it exists
	if (hasResource(ID_BMAP, 1000))
		setBackground(1000);

	// TODO: better CTBL logic
	loadCTBL(1000, 100);

	// Run the startup script.
	runScript(1000, 0, 0, 0);

	_mouseEnabled = true;
	onMouseMove(_lastMousePos);

	runEvent(kEventLoad, id, 0, 0);
}
예제 #28
0
bool ADSI::loadLibrary(const QString &fileName)
{

    if(!adsiLibrary) {
        adsiLibrary = new QLibrary(this);
    }
    if(adsiLibrary->isLoaded()) {
        m_lastErrorString = "Library '" + fileName + "'already loaded!";
        qCritical() << m_lastErrorString;
        return false;
    }

//    adsiLibrary->unload();
    adsiLibrary->setFileName(fileName);
    adsiLibrary->load();
    if(!adsiLibrary->isLoaded()) {
        m_lastErrorString = "Failed to load library '" + fileName + "'!" + adsiLibrary->errorString();
        qCritical() << m_lastErrorString;
        return false;
    }

    m_AD_Open = (AD_OpenFunction) adsiLibrary->resolve("AD_Open");
    if(!m_AD_Open) {
        unloadLibrary();
        m_lastErrorString = "Failed to resolve function  'AD_Open' !" ;
        qCritical() << m_lastErrorString;
        return false;
    }

    m_AD_Close = (AD_CloseFunction) adsiLibrary->resolve("AD_Close");
    if(!m_AD_Close) {
        unloadLibrary();
        m_lastErrorString = "Failed to resolve function  'AD_Close' !" ;
        qCritical() << m_lastErrorString;
        return false;
    }

    m_AD_GetLastErrorCode = (AD_GetLastErrorCodeFunction) adsiLibrary->resolve("AD_GetLastErrorCode");
    if(!m_AD_GetLastErrorCode) {
        unloadLibrary();
        m_lastErrorString = "Failed to resolve function  'AD_GetLastErrorCode' !" ;
        qCritical() << m_lastErrorString;
        return false;
    }

    m_AD_GetLastErrorString = (AD_GetLastErrorStringFunction) adsiLibrary->resolve("AD_GetLastErrorString");
    if(!m_AD_GetLastErrorString) {
        unloadLibrary();
        m_lastErrorString = "Failed to resolve function  'AD_GetLastErrorString' !" ;
        qCritical() << m_lastErrorString;
        return false;
    }

    m_AD_DefaultNamingContext = (AD_DefaultNamingContextFunction) adsiLibrary->resolve("AD_DefaultNamingContext");
    if(!m_AD_DefaultNamingContext) {
        unloadLibrary();
        m_lastErrorString = "Failed to resolve function  'AD_DefaultNamingContext' !" ;
        qCritical() << m_lastErrorString;
        return false;
    }

    m_AD_ObjectExists = (AD_ObjectExistsFunction) adsiLibrary->resolve("AD_ObjectExists");
    if(!m_AD_ObjectExists) {
        unloadLibrary();
        m_lastErrorString = "Failed to resolve function  'AD_ObjectExists' !" ;
        qCritical() << m_lastErrorString;
        return false;
    }

    m_AD_RenameObject = (AD_RenameObjectFunction) adsiLibrary->resolve("AD_RenameObject");
    if(!m_AD_RenameObject) {
        unloadLibrary();
        m_lastErrorString = "Failed to resolve function  'AD_RenameObject' !" ;
        qCritical() << m_lastErrorString;
        return false;
    }

    m_AD_MoveObject = (AD_MoveObjectFunction) adsiLibrary->resolve("AD_MoveObject");
    if(!m_AD_MoveObject) {
        unloadLibrary();
        m_lastErrorString = "Failed to resolve function  'AD_MoveObject' !" ;
        qCritical() << m_lastErrorString;
        return false;
    }

    m_AD_DeleteObject = (AD_DeleteObjectFunction) adsiLibrary->resolve("AD_DeleteObject");
    if(!m_AD_DeleteObject) {
        unloadLibrary();
        m_lastErrorString = "Failed to resolve function  'AD_DeleteObject' !" ;
        qCritical() << m_lastErrorString;
        return false;
    }

    m_AD_UnlockObject = (AD_UnlockObjectFunction) adsiLibrary->resolve("AD_UnlockObject");
    if(!m_AD_UnlockObject) {
        unloadLibrary();
        m_lastErrorString = "Failed to resolve function  'AD_UnlockObject' !" ;
        qCritical() << m_lastErrorString;
        return false;
    }

    m_AD_EnableObject = (AD_EnableObjectFunction) adsiLibrary->resolve("AD_EnableObject");
    if(!m_AD_EnableObject) {
        unloadLibrary();
        m_lastErrorString = "Failed to resolve function  'AD_EnableObject' !" ;
        qCritical() << m_lastErrorString;
        return false;
    }

    m_AD_IsObjectDisabled = (AD_IsObjectDisabledFunction) adsiLibrary->resolve("AD_IsObjectDisabled");
    if(!m_AD_IsObjectDisabled) {
        unloadLibrary();
        m_lastErrorString = "Failed to resolve function  'AD_IsObjectDisabled' !" ;
        qCritical() << m_lastErrorString;
        return false;
    }

    m_AD_SetAccountExpire = (AD_SetAccountExpireFunction) adsiLibrary->resolve("AD_SetAccountExpire");
    if(!m_AD_SetAccountExpire) {
        unloadLibrary();
        m_lastErrorString = "Failed to resolve function  'AD_SetAccountExpire' !" ;
        qCritical() << m_lastErrorString;
        return false;
    }

    m_AD_SetPasswordExpire = (AD_SetPasswordExpireFunction) adsiLibrary->resolve("AD_SetPasswordExpire");
    if(!m_AD_SetPasswordExpire) {
        unloadLibrary();
        m_lastErrorString = "Failed to resolve function  'AD_SetPasswordExpire' !" ;
        qCritical() << m_lastErrorString;
        return false;
    }

    m_AD_SetUserCannotChangePassword = (AD_SetUserCannotChangePasswordFunction) adsiLibrary->resolve("AD_SetUserCannotChangePassword");
    if(!m_AD_SetUserCannotChangePassword) {
        unloadLibrary();
        m_lastErrorString = "Failed to resolve function  'AD_SetUserCannotChangePassword' !" ;
        qCritical() << m_lastErrorString;
        return false;
    }

    m_AD_GetUserCannotChangePassword = (AD_GetUserCannotChangePasswordFunction) adsiLibrary->resolve("AD_GetUserCannotChangePassword");
    if(!m_AD_GetUserCannotChangePassword) {
        unloadLibrary();
        m_lastErrorString = "Failed to resolve function  'AD_GetUserCannotChangePassword' !" ;
        qCritical() << m_lastErrorString;
        return false;
    }

    m_AD_SetUserPasswordChange = (AD_SetUserPasswordChangeFunction) adsiLibrary->resolve("AD_SetUserPasswordChange");
    if(!m_AD_SetUserPasswordChange) {
        unloadLibrary();
        m_lastErrorString = "Failed to resolve function  'AD_SetUserPasswordChange' !" ;
        qCritical() << m_lastErrorString;
        return false;
    }

    m_AD_GetUserPasswordChange = (AD_GetUserPasswordChangeFunction) adsiLibrary->resolve("AD_GetUserPasswordChange");
    if(!m_AD_GetUserPasswordChange) {
        unloadLibrary();
        m_lastErrorString = "Failed to resolve function  'AD_GetUserPasswordChange' !" ;
        qCritical() << m_lastErrorString;
        return false;
    }

    m_AD_GetObjectAttribute = (AD_GetObjectAttributeFunction) adsiLibrary->resolve("AD_GetObjectAttribute");
    if(!m_AD_GetObjectAttribute) {
        unloadLibrary();
        m_lastErrorString = "Failed to resolve function  'AD_GetObjectAttribute' !" ;
        qCritical() << m_lastErrorString;
        return false;
    }

    m_AD_ModifyAttribute = (AD_ModifyAttributeFunction) adsiLibrary->resolve("AD_ModifyAttribute");
    if(!m_AD_ModifyAttribute) {
        unloadLibrary();
        m_lastErrorString = "Failed to resolve function  'AD_ModifyAttribute' !" ;
        qCritical() << m_lastErrorString;
        return false;
    }

    m_AD_CreateOU = (AD_CreateOUFunction) adsiLibrary->resolve("AD_CreateOU");
    if(!m_AD_CreateOU) {
        unloadLibrary();
        m_lastErrorString = "Failed to resolve function  'AD_CreateOU' !" ;
        qCritical() << m_lastErrorString;
        return false;
    }

    m_AD_GetAllOUs = (AD_GetAllOUsFunction) adsiLibrary->resolve("AD_GetAllOUs");
    if(!m_AD_GetAllOUs) {
        unloadLibrary();
        m_lastErrorString = "Failed to resolve function  'AD_GetAllOUs' !" ;
        qCritical() << m_lastErrorString;
        return false;
    }

    m_AD_GetObjectsInOU = (AD_GetObjectsInOUFunction) adsiLibrary->resolve("AD_GetObjectsInOU");
    if(!m_AD_GetObjectsInOU) {
        unloadLibrary();
        m_lastErrorString = "Failed to resolve function  'AD_GetObjectsInOU' !" ;
        qCritical() << m_lastErrorString;
        return false;
    }

    m_AD_CreateUser = (AD_CreateUserFunction) adsiLibrary->resolve("AD_CreateUser");
    if(!m_AD_CreateUser) {
        unloadLibrary();
        m_lastErrorString = "Failed to resolve function  'AD_CreateUser' !" ;
        qCritical() << m_lastErrorString;
        return false;
    }

    m_AD_SetPassword = (AD_SetPasswordFunction) adsiLibrary->resolve("AD_SetPassword");
    if(!m_AD_SetPassword) {
        unloadLibrary();
        m_lastErrorString = "Failed to resolve function  'AD_SetPassword' !" ;
        qCritical() << m_lastErrorString;
        return false;
    }

    m_ComputerName = (ComputerNameFunction) adsiLibrary->resolve("ComputerName");
    if(!m_ComputerName) {
        unloadLibrary();
        m_lastErrorString = "Failed to resolve function  'ComputerName' !" ;
        qCritical() << m_lastErrorString;
        return false;
    }

    m_UserNameOfCurrentThread = (UserNameOfCurrentThreadFunction) adsiLibrary->resolve("UserNameOfCurrentThread");
    if(!m_UserNameOfCurrentThread) {
        unloadLibrary();
        m_lastErrorString = "Failed to resolve function  'UserNameOfCurrentThread' !" ;
        qCritical() << m_lastErrorString;
        return false;
    }

    return true;
}
예제 #29
0
bool ComponentManager::loadLibrary(const std::string & filePath, bool reload)
{
    // Check if library is already loaded and reload is not requested
    auto it = m_librariesByFilePath.find(filePath);
    if (it != m_librariesByFilePath.cend() && !reload) {
        return true;
    }

    // Load module information file, if present
    cpplocate::ModuleInfo modInfo;
    modInfo.load(filePath + ".modinfo");

    // If library was already loaded, remember it in case reloading fails
    PluginLibrary * previous = nullptr;
    if (it != m_librariesByFilePath.cend()) {
        previous = it->second;
    }

    // Open plugin library
    PluginLibrary * library = new PluginLibrary(filePath);
    if (!library->isValid())
    {
        // Loading failed. Destroy library object and return failure.
        cppassist::warning() << (previous ? "Reloading" : "Loading") << " plugin(s) from '" << filePath << "' failed.";

        delete library;
        return false;
    }

    // Library has been loaded. Unload previous incarnation.
    if (previous) {
        unloadLibrary(previous);
    }

    // Add library to list (in case of reload, this overwrites the previous)
    m_librariesByFilePath[filePath] = library;

    // Initialize plugin library
    library->initialize();

    // Iterate over plugins
    const unsigned int numComponents = library->numComponents();
    for (unsigned int i = 0; i < numComponents; ++i) 
    {
        // Get component
        AbstractComponent * component = library->component(i);
        if (!component)
            continue;

        // Set module information
        if (!modInfo.empty())
        {
            component->setModuleInfo(modInfo);
        }

        // Add component to list
        m_components.push_back(component);

        // Save component by name
        std::string name = component->name();
        m_componentsByName[name] = component;
    }

    // Return success
    return true;
}
예제 #30
0
void
PluginLoader::Impl::enumeratePlugins(PluginKey forPlugin)
{
    vector<string> path = PluginHostAdapter::getPluginPath();

    string libraryName, identifier;
    if (forPlugin != "") {
        if (!decomposePluginKey(forPlugin, libraryName, identifier)) {
            std::cerr << "WARNING: Vamp::HostExt::PluginLoader: Invalid plugin key \""
                      << forPlugin << "\" in enumerate" << std::endl;
            return;
        }
    }

    for (size_t i = 0; i < path.size(); ++i) {
        
        vector<string> files = listFiles(path[i], PLUGIN_SUFFIX);

        for (vector<string>::iterator fi = files.begin();
             fi != files.end(); ++fi) {
            
            if (libraryName != "") {
                // libraryName is lowercased and lacking an extension,
                // as it came from the plugin key
                string temp = *fi;
                for (size_t i = 0; i < temp.length(); ++i) {
                    temp[i] = tolower(temp[i]);
                }
                string::size_type pi = temp.find('.');
                if (pi == string::npos) {
                    if (libraryName != temp) continue;
                } else {
                    if (libraryName != temp.substr(0, pi)) continue;
                }
            }

            string fullPath = path[i];
            fullPath = splicePath(fullPath, *fi);
            void *handle = loadLibrary(fullPath);
            if (!handle) continue;
            
            VampGetPluginDescriptorFunction fn =
                (VampGetPluginDescriptorFunction)lookupInLibrary
                (handle, "vampGetPluginDescriptor");
            
            if (!fn) {
                unloadLibrary(handle);
                continue;
            }
            
            int index = 0;
            const VampPluginDescriptor *descriptor = 0;
            
            while ((descriptor = fn(VAMP_API_VERSION, index))) {
                ++index;
                if (identifier != "") {
                    if (descriptor->identifier != identifier) continue;
                }
                PluginKey key = composePluginKey(*fi, descriptor->identifier);
//                std::cerr << "enumerate: " << key << " (path: " << fullPath << ")" << std::endl;
                if (m_pluginLibraryNameMap.find(key) ==
                    m_pluginLibraryNameMap.end()) {
                    m_pluginLibraryNameMap[key] = fullPath;
                }
            }
            
            unloadLibrary(handle);
        }
    }

    if (forPlugin == "") m_allPluginsEnumerated = true;
}