void ServiceHelperPrivate::loadPlugin()
{
    QString libPath = getenv("ACCOUNTS_UI_PLUGIN_DIR");
    if (!libPath.isEmpty()) {
        libPath = QDir::cleanPath(libPath) + QDir::separator();
    } else {
        libPath = "/usr/lib/AccountsUI/";
    }
    QString libName("lib%1plugin.so");

    //use the xml element plugin to get the plugin name
    QDomElement root = domDocument.documentElement();
    QDomElement pluginElement = root.firstChildElement("plugin");

    QString path;
    path = libPath + libName.arg(pluginElement.text());
    //fallback use id as a plugin name
    if (!QFile::exists(path)) {
        QString serviceId = root.attribute("id");
        path = libPath + libName.arg(serviceId);
    }

    QObject *plugin = 0;

    qDebug() << "Loading plugin " << path;
    QPluginLoader pluginLoader(path);
    if (QFile::exists(path)) {
        plugin = pluginLoader.instance();
    }

    this->plugin = qobject_cast<ServicePluginInterface *>(plugin);
}
Example #2
0
static void resolveLibs()
{
    static bool triedResolve = false;
#if defined Q_OS_WINCE
    QString libName(QLatin1String("coredll"));
    const char* funcName = "Shell_NotifyIcon";
#else
    QString libName(QLatin1String("shell32"));
    const char* funcName = "Shell_NotifyIconW";
#endif
    if (!triedResolve) {
        QLibrary lib(libName);
            triedResolve = true;
            ptrShell_NotifyIcon = (PtrShell_NotifyIcon) lib.resolve(funcName);
    }
}
Example #3
0
ctkPluginManager::ctkPluginManager()
: d_ptr(new ctkPluginManagerPrivate())
{
  Q_D(ctkPluginManager);

  QString libName("CTKCore");
  QLibrary lib(libName);
  QFileInfo fileInfo(libName);
  QString libBaseName(fileInfo.baseName());
  if (libBaseName.startsWith("lib"))
  {
    libBaseName.remove(0, 3);
  }
  qDebug() << libBaseName;
  lib.load();
  if (lib.isLoaded())
  {
    QString xyz = QString(":/") + libBaseName + "/servicedescriptor.xml";
    qDebug() << "resource string: " << xyz;
    QFile serviceDescriptor(xyz);
    qDebug() << "file exists: " << serviceDescriptor.exists();
    qDebug() << "open returns:" << serviceDescriptor.open(QIODevice::ReadOnly);
    qDebug() << "file open: " << serviceDescriptor.isOpen();
    qDebug() << "file is readable: " << serviceDescriptor.isReadable();
    //QByteArray serviceBA = serviceDescriptor.readAll();
    //qDebug() << serviceBA;
    qDebug() << "Service for " << libBaseName << " registered:" << d->serviceManager.addService(&serviceDescriptor);
    lib.unload();
  }
}
Example #4
0
__LLBC_NS_BEGIN

LLBC_LibraryHandle LLBC_LoadLibrary(const char *fileName)
{
    LLBC_LibraryHandle handle = LLBC_INVALID_LIBRARY_HANDLE;
#if LLBC_TARGET_PLATFORM_NON_WIN32
    if ((handle = dlopen(fileName, RTLD_LAZY)) == LLBC_INVALID_LIBRARY_HANDLE)
    {
        LLBC_SetLastError(LLBC_ERROR_UNKNOWN);
    }

    return handle;
#else // LLBC_TARGET_PLATFORM_WIN32
    // Note, WIN32 API ::GetProcAddress not support slashes(/), so replace it.
    LLBC_String libName(fileName);
    libName.findreplace(LLBC_SLASH_A, LLBC_BACKLASH_A);
    if (libName.empty())
        libName = LLBC_Directory::ModuleFileName();

    if ((handle = ::LoadLibraryExA(libName.c_str(), NULL, 0)) == LLBC_INVALID_LIBRARY_HANDLE)
        LLBC_SetLastError(LLBC_ERROR_OSAPI);

    return handle;
#endif // LLBC_TARGET_PLATFORM_NON_WIN32
}
Example #5
0
	SharedLibContainer()
	{
		// Do not reload the library if is already loaded
		if (libHandle_)
			return;

		libHandle_ = dlopen(libName(), RTLD_LAZY);
	}
Example #6
0
    void set( const std::string& dictLib,
	      const std::string& className,
	      const std::string& containerName,
	      int pkcolumnValue=0) {
      
      ora::SharedLibraryName libName;
      edmplugin::SharedLibrary shared( libName(dictLib) );
      m_token = writeToken(containerName, 0, pkcolumnValue, className);
    }
bool BinaryDependenciesLdd::isLibraryNotInExcludeList(const PlainText::StringRecord & record)
{
  Q_ASSERT(record.columnCount() > 0);

  const auto cmp = [record](const char * const excludeName){
    LibraryName libName(record.data(0));
    return ( QString::compare( libName.name(), QLatin1String(excludeName), Qt::CaseSensitive ) == 0);
  };
  const auto it = std::find_if( LibrayExcludeListLinux.cbegin(), LibrayExcludeListLinux.cend(), cmp );
  return (it == LibrayExcludeListLinux.cend());
}
Example #8
0
jclass anp_system_loadJavaClass(NPP instance, const char* classNameStr)
{
    LOG("%s", __PRETTY_FUNCTION__);

    nsNPAPIPluginInstance* pinst = static_cast<nsNPAPIPluginInstance*>(instance->ndata);
    mozilla::PluginPRLibrary* lib = static_cast<mozilla::PluginPRLibrary*>(pinst->GetPlugin()->GetLibrary());

    NS_ConvertUTF8toUTF16 className(classNameStr);

    nsCString libNameUtf8;
    lib->GetLibraryPath(libNameUtf8);
    NS_ConvertUTF8toUTF16 libName(libNameUtf8);

    return mozilla::widget::android::GeckoAppShell::LoadPluginClass(className, libName);
}
Example #9
0
Poco::Path
CodeCache::GetPathForLibrary(const std::string& name)
{
  // We instructed cmake to replace "." with "_" in library names
  // since they are also used for defines (for Windows dll import/export
  // stuff) and . is bad in identifiers.
  // Hence we must replace all "." with "_" here too
  std::string libName(name);
  std::replace(libName.begin(), libName.end(), '.', '_');

  //BERRY_INFO << "Getting path for library: " << libName << std::endl;
  if (m_LibPaths.find(libName) != m_LibPaths.end())
  {
    return Poco::Path(m_LibPaths[libName].path(), libName + Poco::SharedLibrary::suffix());
  }
  else
  {
    return Poco::Path(m_CachePath.path(), libName + Poco::SharedLibrary::suffix());
  }
}
Example #10
0
/*!
    \internal
    Try to resolve a \a symbol from \a library with the version specified
    by \a vernum.

    Note that, in the case of the Xfixes library, \a vernum is not the same as
    \c XFIXES_MAJOR - it is a part of soname and may differ from the Xfixes
    version.
*/
static void* qt_load_library_runtime(const char *library, int vernum,
                                     int highestVernum, const char *symbol)
{
    QList<int> versions;
    // we try to load in the following order:
    // explicit version -> the default one -> (from the highest (highestVernum) to the lowest (vernum) )
    if (vernum != -1)
        versions << vernum;
    versions << -1;
    if (vernum != -1) {
        for(int i = highestVernum; i > vernum; --i)
            versions << i;
    }
    Q_FOREACH(int version, versions) {
        QLatin1String libName(library);
        QLibrary xfixesLib(libName, version);
        void *ptr = xfixesLib.resolve(symbol);
        if (ptr)
            return ptr;
    }
Example #11
0
bool
CodeCache::HasLibrary(const std::string& name)
{
  //BERRY_INFO << "HasLibrary checks for: " << name;

  std::vector<std::string> files;
  m_CachePath.list(files);

  std::string libName(name);
  //libName.append(Poco::SharedLibrary::suffix());

  std::vector<std::string>::iterator iter;
  for (iter = files.begin(); iter != files.end(); iter++)
  {
    if ((*iter) == libName) {
      //BERRY_INFO << " FOUND\n";
      return true;
    }
  }

  //BERRY_INFO << " NOT FOUND\n";
  return false;
}
Example #12
0
void ctkPluginManager::startAllPlugins()
{
  Q_D(ctkPluginManager);
  QDirIterator it(d->pluginPaths.front(), QDir::Files);
  if (it.hasNext())
  {
    qApp->addLibraryPath(d->pluginPaths.front());
  }
  while (it.hasNext()) {
       QString libName(it.next());
       QLibrary lib(libName);
       QFileInfo fileInfo(libName);
       QString libBaseName(fileInfo.baseName());
       if (libBaseName.startsWith("lib"))
       {
         libBaseName.remove(0, 3);
       }
       qDebug() << libBaseName;
       lib.load();
       if (lib.isLoaded())
       {
         QString xyz = QString(":/") + libBaseName + "/servicedescriptor.xml";
         qDebug() << "resource string: " << xyz;
         QFile serviceDescriptor(xyz);
         //qDebug() << "file exists: " << serviceDescriptor.exists();
         qDebug() << "open returns:" << serviceDescriptor.open(QIODevice::ReadOnly);
         qDebug() << "file open: " << serviceDescriptor.isOpen();
         qDebug() << "file is readable: " << serviceDescriptor.isReadable();
         //QByteArray serviceBA = serviceDescriptor.readAll();
         //qDebug() << serviceBA;
         qDebug() << "Service for " << libBaseName << " registered:" << d->serviceManager.addService(&serviceDescriptor);
         lib.unload();
       }
  }


}
bool CommunicationVoiceLibrary::LoadFromFile(const char* fileName)
{
	MEMSTAT_CONTEXT(EMemStatContextTypes::MSC_Other, 0, "Communication Voice Library" );
	MEMSTAT_CONTEXT_FMT(EMemStatContextTypes::MSC_Other, 0, "Voice Lib: %s",fileName );

	XmlNodeRef root = GetISystem()->LoadXmlFromFile(fileName);
	if (!root)
		return false;

	XmlNodeRef nodeWorksheet = root->findChild("Worksheet");
	if (!nodeWorksheet)
		return false;

	XmlNodeRef nodeTable = nodeWorksheet->findChild("Table");
	if (!nodeTable)
		return false;

	stack_string libName(PathUtil::GetFileName(fileName));

	VoiceLibraryID libraryID = GetVoiceLibraryID(libName.c_str());

	std::pair<VoiceLibraries::iterator, bool> iresult = m_libraries.insert(
		VoiceLibraries::value_type(libraryID, VoiceLibrary()));

	if (!iresult.second)
	{
		if (iresult.first->second.name == libName.c_str())
		{
			AIWarningID("<AICommunicationVoiceLibrary::LoadFromFile> ", 
				"Duplicate voice library '%s'!", libName.c_str());

			return false;
		}
		else
		{
			AIWarningID("<AICommunicationVoiceLibrary::LoadFromFile> ", 
				"Hash collision for voice library name '%s' and '%s'!", libName.c_str(), iresult.first->second.name.c_str());

			return false;
		}
	}

	VoiceLibrary& library = iresult.first->second;
	library.name = string(libName);
	
	VoiceGroup* voiceGroup = 0;
		
	string signalName;
	string lastSignalName;
	string voiceName;

	for (int rowCntr = 0, childN = 0; childN < nodeTable->getChildCount(); ++childN)
	{
		XmlNodeRef nodeRow = nodeTable->getChild(childN);
		if (!nodeRow->isTag("Row"))
			continue;

		++rowCntr;
		if (rowCntr == 1) // skip language
			continue;

		if (rowCntr == 2) // path
		{
			int cellN = 0;
			for (int childrenCntr = 0; childrenCntr < nodeRow->getChildCount(); ++childrenCntr)
			{
				XmlNodeRef nodeCell = nodeRow->getChild(childrenCntr);
				if (!nodeCell->isTag("Cell"))
					continue;

				++cellN;
				if (cellN == 2)
				{
					XmlNodeRef nodeCellData = nodeCell->findChild("Data");
					if (!nodeCellData)
						break;

					library.base = PathUtil::GetLocalizationFolder() + nodeCellData->getContent();
					if (!library.base.empty())
					{
						library.base.replace("\\", "/");
						if (library.base[library.base.length()-1] != '/')
							library.base.append("/");
					}
					break;
				}
			}
			continue;
		}

		if (rowCntr == 3) // headers
			continue;

		signalName.clear();
		voiceName.clear();
		
		for (int childrenCntr = 0, cellIndex = 1; childrenCntr < nodeRow->getChildCount(); ++childrenCntr, ++cellIndex)
		{
			XmlNodeRef nodeCell = nodeRow->getChild(childrenCntr);
			if (!nodeCell->isTag("Cell"))
				continue;

			if (nodeCell->haveAttr("ss:Index"))
			{
				const char* strIdx = nodeCell->getAttr("ss:Index");
				if (sscanf(strIdx, "%d", &cellIndex) != 1)
					continue;
			}

			XmlNodeRef nodeCellData = nodeCell->findChild("Data");
			if (!nodeCellData)
				continue;

			switch (cellIndex)
			{
			case 1:
				signalName = nodeCellData->getContent();
				break;
			case 2:
				voiceName = nodeCellData->getContent();
				break;
			}
		}

		if (!signalName.empty())
		{
			signalName.MakeLower();
			std::pair<VoiceGroups::iterator, bool> itresult = library.voiceGroups.insert(
				VoiceGroups::value_type(signalName, VoiceGroup()));

			voiceGroup = &itresult.first->second;
			// The 20 here comes from inspection of the resulting contents in memreplay
			voiceGroup->variations.reserve(20);

			if (!itresult.second)
			{
				if (lastSignalName != signalName)
					AIWarningID("<AICommunicationVoiceLibrary::LoadFromFile> ", 
						"Duplicate voice signal '%s' in file '%s'.", signalName.c_str(), libName.c_str());
			}

			lastSignalName = signalName;
		}

		if (!voiceGroup || voiceName.empty())
			continue;

		if ((library.base.find_first_of(':') == string::npos) && (voiceName.find_first_of(':') == string::npos))
			voiceName.append(".wav");

		if (voiceGroup->variations.size() < MaxVariationCount)
			voiceGroup->variations.push_back(voiceName);
		else
			AIWarningID("<AICommunicationVoiceLibrary::LoadFromFile> ", 
			"Too many voice variations for signal '%s' in file '%s'. Limit is 32.", signalName.c_str(), libName.c_str());
	}

	return true;
}
Example #14
0
Handle poly_ffi(TaskData *taskData, Handle args, Handle code)
{
    unsigned c = get_C_unsigned(taskData, code->Word());
    switch (c)
    {
    case 0: // malloc
        {
            POLYUNSIGNED size = getPolyUnsigned(taskData, args->Word());
            return toSysWord(taskData, malloc(size));
        }
    case 1: // free
        {
            void *mem = *(void**)(args->WordP());
            free(mem);
            return taskData->saveVec.push(TAGGED(0));
        }

    case 2: // Load library
        {
            TempString libName(args->Word());
#if (defined(_WIN32) && ! defined(__CYGWIN__))
            HINSTANCE lib = LoadLibrary(libName);
            if (lib == NULL)
            {
                char buf[256];
#if (defined(UNICODE))
                _snprintf(buf, sizeof(buf), "Loading <%S> failed. Error %lu", libName, GetLastError());
#else
                _snprintf(buf, sizeof(buf), "Loading <%s> failed. Error %lu", libName, GetLastError());
#endif
                buf[sizeof(buf)-1] = 0; // Terminate just in case
                raise_exception_string(taskData, EXC_foreign, buf);
            }
#else
            void *lib = dlopen(libName, RTLD_LAZY);
            if (lib == NULL)
            {
                char buf[256];
                snprintf(buf, sizeof(buf), "Loading <%s> failed: %s", (const char *)libName, dlerror());
                buf[sizeof(buf)-1] = 0; // Terminate just in case
                raise_exception_string(taskData, EXC_foreign, buf);
            }
#endif
            return toSysWord(taskData, lib);
        }

    case 3: // Load address of executable.
        {
#if (defined(_WIN32) && ! defined(__CYGWIN__))
            HINSTANCE lib = hApplicationInstance;
#else
            void *lib = dlopen(NULL, RTLD_LAZY);
            if (lib == NULL)
            {
                char buf[256];
                snprintf(buf, sizeof(buf), "Loading address of executable failed: %s", dlerror());
                buf[sizeof(buf)-1] = 0; // Terminate just in case
                raise_exception_string(taskData, EXC_foreign, buf);
            }
#endif
            return toSysWord(taskData, lib);
        }
    case 4: // Unload library - Is this actually going to be used?
        {
#if (defined(_WIN32) && ! defined(__CYGWIN__))
            HMODULE hMod = *(HMODULE*)(args->WordP());
            if (! FreeLibrary(hMod))
                raise_syscall(taskData, "FreeLibrary failed", -(int)GetLastError());
#else
            void *lib = *(void**)(args->WordP());
            if (dlclose(lib) != 0)
            {
                char buf[256];
                snprintf(buf, sizeof(buf), "dlclose failed: %s", dlerror());
                buf[sizeof(buf)-1] = 0; // Terminate just in case
                raise_exception_string(taskData, EXC_foreign, buf);
            }
#endif
            return taskData->saveVec.push(TAGGED(0));
        }
    case 5: // Load the address of a symbol from a library.
        {
            TempCString symName(args->WordP()->Get(1));
#if (defined(_WIN32) && ! defined(__CYGWIN__))
            HMODULE hMod = *(HMODULE*)(args->WordP()->Get(0).AsAddress());
            void *sym = (void*)GetProcAddress(hMod, symName);
            if (sym == NULL)
            {
                char buf[256];
                _snprintf(buf, sizeof(buf), "Loading symbol <%s> failed. Error %lu", symName, GetLastError());
                buf[sizeof(buf)-1] = 0; // Terminate just in case
                raise_exception_string(taskData, EXC_foreign, buf);
            }
#else
            void *lib = *(void**)(args->WordP()->Get(0).AsAddress());
            void *sym = dlsym(lib, symName);
            if (sym == NULL)
            {
                char buf[256];
                snprintf(buf, sizeof(buf), "load_sym <%s> : %s", (const char *)symName, dlerror());
                buf[sizeof(buf)-1] = 0; // Terminate just in case
                raise_exception_string(taskData, EXC_foreign, buf);
            }
#endif
            return toSysWord(taskData, sym);
        }

        // Libffi functions
    case 50: // Return a list of available ABIs
            return makeList(taskData, sizeof(abiTable)/sizeof(abiTable[0]),
                            (char*)abiTable, sizeof(abiTable[0]), 0, mkAbitab);

    case 51: // A constant from the table
        {
            unsigned index = get_C_unsigned(taskData, args->Word());
            if (index >= sizeof(constantTable) / sizeof(constantTable[0]))
                raise_exception_string(taskData, EXC_foreign, "Index out of range");
            return Make_arbitrary_precision(taskData, constantTable[index]);
        }

    case 52: // Return an FFI type
        {
            unsigned index = get_C_unsigned(taskData, args->Word());
            if (index >= sizeof(ffiTypeTable) / sizeof(ffiTypeTable[0]))
                raise_exception_string(taskData, EXC_foreign, "Index out of range");
            return toSysWord(taskData, ffiTypeTable[index]);
        }

    case 53: // Extract fields from ffi type.
        {
            ffi_type *ffit = *(ffi_type**)(args->WordP());
            Handle sizeHandle = Make_arbitrary_precision(taskData, ffit->size);
            Handle alignHandle = Make_arbitrary_precision(taskData, ffit->alignment);
            Handle typeHandle = Make_arbitrary_precision(taskData, ffit->type);
            Handle elemHandle = toSysWord(taskData, ffit->elements);
            Handle resHandle = alloc_and_save(taskData, 4);
            resHandle->WordP()->Set(0, sizeHandle->Word());
            resHandle->WordP()->Set(1, alignHandle->Word());
            resHandle->WordP()->Set(2, typeHandle->Word());
            resHandle->WordP()->Set(3, elemHandle->Word());
            return resHandle;
        }

    case 54: // Construct an ffi type.
        {
            // This is probably only used to create structs.
            size_t size = getPolyUnsigned(taskData, args->WordP()->Get(0));
            unsigned short align = get_C_ushort(taskData, args->WordP()->Get(1));
            unsigned short type = get_C_ushort(taskData, args->WordP()->Get(2));
            unsigned nElems = 0;
            for (PolyWord p = args->WordP()->Get(3); !ML_Cons_Cell::IsNull(p); p = ((ML_Cons_Cell*)p.AsObjPtr())->t)
                nElems++;
            size_t space = sizeof(ffi_type);
            // If we need the elements add space for the elements plus
            // one extra for the zero terminator.
            if (nElems != 0) space += (nElems+1) * sizeof(ffi_type *);
            ffi_type *result = (ffi_type*)malloc(space);
            // Raise an exception rather than returning zero.
            if (result == 0) raise_syscall(taskData, "Insufficient memory", ENOMEM);
            ffi_type **elem = 0;
            if (nElems != 0) elem = (ffi_type **)(result+1);
            memset(result, 0, sizeof(ffi_type)); // Zero it in case they add fields
            result->size = size;
            result->alignment = align;
            result->type = type;
            result->elements = elem;
            if (elem != 0)
            {
                for (PolyWord p = args->WordP()->Get(3); !ML_Cons_Cell::IsNull(p); p = ((ML_Cons_Cell*)p.AsObjPtr())->t)
                {
                    PolyWord e = ((ML_Cons_Cell*)p.AsObjPtr())->h;
                    *elem++ = *(ffi_type**)(e.AsAddress());
                }
                *elem = 0;
            }
            return toSysWord(taskData, result);
        }

    case 55: // Create a CIF.  This contains all the types and some extra information.
        // The result is in allocated memory followed immediately by the argument type vector.
        {
            ffi_abi abi = (ffi_abi)get_C_ushort(taskData, args->WordP()->Get(0));
            ffi_type *rtype = *(ffi_type **)args->WordP()->Get(1).AsAddress();
            unsigned nArgs = 0;
            for (PolyWord p = args->WordP()->Get(2); !ML_Cons_Cell::IsNull(p); p = ((ML_Cons_Cell*)p.AsObjPtr())->t)
                nArgs++;
            // Allocate space for the cif followed by the argument type vector
            size_t space = sizeof(ffi_cif) + nArgs * sizeof(ffi_type*);
            ffi_cif *cif = (ffi_cif *)malloc(space);
            if (cif == 0) raise_syscall(taskData, "Insufficient memory", ENOMEM);
            ffi_type **atypes = (ffi_type **)(cif+1);
            // Copy the arguments types.
            ffi_type **at = atypes;
            for (PolyWord p = args->WordP()->Get(2); !ML_Cons_Cell::IsNull(p); p = ((ML_Cons_Cell*)p.AsObjPtr())->t)
            {
                PolyWord e = ((ML_Cons_Cell*)p.AsObjPtr())->h;
                *at++ = *(ffi_type**)(e.AsAddress());
            }
            ffi_status status = ffi_prep_cif(cif, abi, nArgs, rtype, atypes);
            if (status == FFI_BAD_TYPEDEF)
                raise_exception_string(taskData, EXC_foreign, "Bad typedef in ffi_prep_cif");
            else if (status == FFI_BAD_ABI)
                raise_exception_string(taskData, EXC_foreign, "Bad ABI in ffi_prep_cif");
            else if (status != FFI_OK)
                raise_exception_string(taskData, EXC_foreign, "Error in ffi_prep_cif");
            return toSysWord(taskData, cif);
        }

    case 56: // Call a function.
        {
            ffi_cif *cif = *(ffi_cif **)args->WordP()->Get(0).AsAddress();
            void *f = *(void**)args->WordP()->Get(1).AsAddress();
            void *res = *(void**)args->WordP()->Get(2).AsAddress();
            void **arg = *(void***)args->WordP()->Get(3).AsAddress();
            // We release the ML memory across the call so a GC can occur
            // even if this thread is blocked in the C code.
            processes->ThreadReleaseMLMemory(taskData);
            ffi_call(cif, FFI_FN(f), res, arg);
            processes->ThreadUseMLMemory(taskData);
            return taskData->saveVec.push(TAGGED(0));
        }

    case 57: // Create a callback.
        {
#ifdef INTERPRETED
            raise_exception_string(taskData, EXC_foreign, "Callbacks are not implemented in the byte code interpreter");
#endif
            Handle mlFunction = taskData->saveVec.push(args->WordP()->Get(0));
            ffi_cif *cif = *(ffi_cif **)args->WordP()->Get(1).AsAddress();

            void *resultFunction;
            // Allocate the memory.  resultFunction is set to the executable address in or related to
            // the memory.
            ffi_closure *closure = (ffi_closure *)ffi_closure_alloc(sizeof(ffi_closure), &resultFunction);
            if (closure == 0)
                raise_exception_string(taskData, EXC_foreign, "Callbacks not implemented or insufficient memory");

            PLocker pLocker(&callbackTableLock);
            // Find a free entry in the table if there is one.
            unsigned entryNo = 0;
            while (entryNo < callBackEntries && callbackTable[entryNo].closureSpace != 0) entryNo++;
            if (entryNo == callBackEntries)
            {
                // Need to grow the table.
                struct _cbStructEntry *newTable =
                    (struct _cbStructEntry*)realloc(callbackTable, (callBackEntries+1)*sizeof(struct _cbStructEntry));
                if (newTable == 0)
                    raise_exception_string(taskData, EXC_foreign, "Unable to allocate memory for callback table");
                callbackTable = newTable;
                callBackEntries++;
            }

            callbackTable[entryNo].mlFunction = mlFunction->Word();
            callbackTable[entryNo].closureSpace = closure;
            callbackTable[entryNo].resultFunction = resultFunction;

            if (ffi_prep_closure_loc(closure, cif, callbackEntryPt, (void*)((uintptr_t)entryNo), resultFunction) != FFI_OK)
                raise_exception_string(taskData, EXC_foreign,"libffi error: ffi_prep_closure_loc failed");
            return toSysWord(taskData, resultFunction);
        }

    case 58: // Free an existing callback.
        {
            // The address returned from call 57 above is the executable address that can
            // be passed as a callback function.  The writable memory address returned
            // as the result of ffi_closure_alloc may or may not be the same.  To be safe
            // we need to search the table.
            void *resFun = *(void**)args->Word().AsAddress();
            PLocker pLocker(&callbackTableLock);
            unsigned i = 0;
            while (i < callBackEntries)
            {
                if (callbackTable[i].resultFunction == resFun)
                {
                    ffi_closure_free(callbackTable[i].closureSpace);
                    callbackTable[i].closureSpace = 0;
                    callbackTable[i].resultFunction = 0;
                    callbackTable[i].mlFunction = TAGGED(0); // Release the ML function
                    return taskData->saveVec.push(TAGGED(0));
                }
            }
            raise_exception_string(taskData, EXC_foreign, "Invalid callback entry");
        }

    default:
        {
            char msg[100];
            sprintf(msg, "Unknown ffi function: %d", c);
            raise_exception_string(taskData, EXC_foreign, msg);
            return 0;
        }
    }
}
Example #15
0
Foam::word Foam::dynamicCode::libraryBaseName(const fileName& libPath)
{
    word libName(libPath.name(true));
    libName.erase(0, 3);    // Remove leading 'lib' from name
    return libName;
}
Example #16
0
DesktopScene::DesktopScene(QObject * parent)
    : QGraphicsScene(parent),
      m_wheelDesktopSwitch(false),
      m_menu(0),
      m_activePlugin(0)
{
    m_power = new PowerManager(this);
    m_screenSaver = new ScreenSaver(this);

    DesktopConfig::instance()->config->beginGroup("razor");
    QStringList plugins =  DesktopConfig::instance()->config->value("plugins").toStringList();
    m_menuFile = DesktopConfig::instance()->config->value("menu_file", "").toString();
    m_wheelDesktopSwitch = DesktopConfig::instance()->config->value("mouse_wheel_desktop_switch", false).toBool();
    DesktopConfig::instance()->config->endGroup();
    if (m_menuFile.isEmpty())
        m_menuFile = XdgMenu::getMenuFileName();

    m_xdgMenu.setEnvironments(QStringList() << "X-RAZOR" << "Razor");
    bool res = m_xdgMenu.read(m_menuFile);
    connect(&m_xdgMenu, SIGNAL(changed()), this, SLOT(buildMenu()));

    if (res)
    {
        QTimer::singleShot(1000, this, SLOT(buildMenu()));
    }
    else
    {
        QMessageBox::warning(0, "Menu Parse error", m_xdgMenu.errorString());
        return;
    }

    m_actArrangeWidgets = new QAction(tr("Unlock Desktop..."), this);
    m_actArrangeWidgets->setIcon(XdgIcon::fromTheme("object-locked"));
    m_actArrangeWidgets->setCheckable(true);
    connect(m_actArrangeWidgets, SIGNAL(toggled(bool)),
            this, SLOT(arrangeWidgets(bool)));

    m_actAddNewPlugin = new QAction(tr("Add New Desktop Widget..."), this);
    connect(m_actAddNewPlugin, SIGNAL(triggered()),
            this, SLOT(showAddPluginDialog()));

    m_actRemovePlugin = new QAction(tr("Remove Plugin..."), this);
    connect(m_actRemovePlugin, SIGNAL(triggered()),
            this, SLOT(removePlugin()));

    m_actConfigurePlugin = new QAction(tr("Configure Plugin..."), this);
    connect(m_actConfigurePlugin, SIGNAL(triggered()),
            this, SLOT(configurePlugin()));

    m_actSetbackground = new QAction(tr("Set Desktop Background..."), this);
    m_actSetbackground->setIcon(XdgIcon::fromTheme("preferences-desktop-wallpaper"));
    connect(m_actSetbackground, SIGNAL(triggered()),
            this, SLOT(setDesktopBackground()));

    m_actAbout = new QAction(tr("About Razor..."), this);
    m_actAbout->setIcon(XdgIcon::fromTheme("help-browser"));
    connect(m_actAbout, SIGNAL(triggered()), this, SLOT(about()));

    // load plugins
    QStringList desktopDirs = pluginDesktopDirs();
    foreach (QString configId, plugins)
    {
        DesktopConfig::instance()->config->beginGroup(configId);
        QString libName(DesktopConfig::instance()->config->value("plugin", "").toString());

        qreal x = DesktopConfig::instance()->config->value("x", 10.0).toReal();
        qreal y = DesktopConfig::instance()->config->value("y", 10.0).toReal();
        qreal w = DesktopConfig::instance()->config->value("w", 10.0).toReal();
        qreal h = DesktopConfig::instance()->config->value("h", 10.0).toReal();
        QPointF position(x, y);
        QSizeF size(w, h);
        DesktopConfig::instance()->config->endGroup();

        RazorPluginInfoList list = RazorPluginInfo::search(desktopDirs, "RazorDesktop/Plugin", QString("%1.desktop").arg(libName));
        if( !list.count())
        {
            qWarning() << QString("Plugin \"%1\" not found.").arg(libName);
            continue;
        }
        QLibrary* lib = loadPluginLib(list.first());
        if (!lib)
        {
            qWarning() << "RazorWorkSpace::setConfig() Library" << libName << "is not loaded";
            continue;
        }

        DesktopWidgetPlugin * item = m_plugins[configId];
        if (!item)
        {
            item = loadPlugin(lib, configId);
            m_plugins.insert(configId, item);
        }

        item->setSizeAndPosition(position, size);
    }
Example #17
0
int main (int argc, char** argv)
{
  std::vector<coral::Option> secondaryOptions;
  //
  coral::Option csPar("conn_string");
  csPar.flag = "-c";
  csPar.helpEntry = "the database connection string";
  csPar.type = coral::Option::STRING;
  secondaryOptions.push_back(csPar);
  //
  coral::Option contPar("container");
  contPar.flag = "-cn";
  contPar.helpEntry = "the selected container name";
  contPar.type = coral::Option::STRING;
  secondaryOptions.push_back(contPar);
  //
  coral::Option mvPar("mapping_version");
  mvPar.flag = "-mv";
  mvPar.helpEntry ="the mapping version";
  mvPar.type = coral::Option::STRING;
  secondaryOptions.push_back(mvPar);
  //
  coral::Option cvPar("class_versions");
  cvPar.flag = "-cv";
  cvPar.helpEntry ="specify the class versions";
  cvPar.type = coral::Option::BOOLEAN;
  secondaryOptions.push_back(cvPar);
  //
  coral::Option outPar("output_file");
  outPar.flag = "-f";
  outPar.helpEntry = "the database host name";
  outPar.type = coral::Option::STRING;
  secondaryOptions.push_back(outPar);
  //
  coral::Option authPar("authentication_path");
  authPar.flag = "-a";
  authPar.helpEntry = "the authentication path";
  authPar.type = coral::Option::STRING;
  secondaryOptions.push_back(authPar);
  //
  coral::Option classPar("type_name");
  classPar.flag = "-t";
  classPar.helpEntry = "the container type name";
  classPar.type = coral::Option::STRING;
  secondaryOptions.push_back(classPar);
  //
  coral::Option dictPar("dictionary");
  dictPar.flag = "-D";
  dictPar.helpEntry = "the list of dictionary libraries";
  dictPar.type = coral::Option::STRING;
  secondaryOptions.push_back(dictPar);
  //
  coral::Option debugPar("debug");
  debugPar.flag = "-debug";
  debugPar.helpEntry ="print the debug messages";
  debugPar.type = coral::Option::BOOLEAN;
  secondaryOptions.push_back(debugPar);
  //
  std::vector<coral::Command> mainSet;
  //
  coral::Command listCont("list_containers");
  listCont.flag = "-list";
  listCont.helpEntry = "listing the available containers";
  listCont.type = coral::Option::BOOLEAN;
  listCont.exclusive = true;
  listCont.addOption(csPar.name);
  listCont.addOption(authPar.name);
  listCont.addOption(debugPar.name);
  mainSet.push_back(listCont);
  //
  coral::Command createCont("create");
  createCont.flag = "-create";
  createCont.helpEntry = "create a database or a container";
  createCont.type = coral::Option::BOOLEAN;
  createCont.exclusive = true;
  createCont.addOption(csPar.name);
  createCont.addOption(contPar.name);
  createCont.addOption(classPar.name);
  createCont.addOption(dictPar.name);
  createCont.addOption(authPar.name);
  createCont.addOption(debugPar.name);
  mainSet.push_back(createCont);
  //
  coral::Command eraseCont("erase");
  eraseCont.flag = "-erase";
  eraseCont.helpEntry = "erase a database or a container";
  eraseCont.type = coral::Option::BOOLEAN;
  eraseCont.exclusive = true;
  eraseCont.addOption(csPar.name);
  eraseCont.addOption(contPar.name);
  eraseCont.addOption(authPar.name);
  eraseCont.addOption(debugPar.name);
  mainSet.push_back(eraseCont);
  //
  coral::Command listMapp("list_mappings");
  listMapp.flag = "-lm";
  listMapp.helpEntry = "listing the available mapping versions";
  listMapp.type = coral::Option::BOOLEAN;
  listMapp.exclusive = true;
  listMapp.addOption(csPar.name);
  listMapp.addOption(contPar.name);
  listMapp.addOption(cvPar.name);
  listMapp.addOption(authPar.name);
  listMapp.addOption(debugPar.name);
  mainSet.push_back(listMapp);
  //
  coral::Command dumpMapp("dump_mapping");
  dumpMapp.flag = "-dm";
  dumpMapp.helpEntry = "dump the specified mapping in xml format";
  dumpMapp.type = coral::Option::BOOLEAN;
  dumpMapp.exclusive = true;
  dumpMapp.addOption(csPar.name);
  dumpMapp.addOption(mvPar.name);
  dumpMapp.addOption(outPar.name);
  dumpMapp.addOption(authPar.name);
  dumpMapp.addOption(debugPar.name);
  mainSet.push_back(dumpMapp);
  //
  try{
    edmplugin::PluginManager::Config config;
    edmplugin::PluginManager::configure(edmplugin::standard::config());
  
    std::vector<edm::ParameterSet> psets;
    edm::ParameterSet pSet;
    pSet.addParameter("@service_type",std::string("SiteLocalConfigService"));
    psets.push_back(pSet);
    static const edm::ServiceToken services(edm::ServiceRegistry::createSet(psets));
    static const edm::ServiceRegistry::Operate operate(services);

    std::string connectionString("");
    std::string authenticationPath("CORAL_AUTH_PATH=");
    std::string containerName("");
    std::string mappingVersion("");
    std::string fileName("");
    std::string className("");
    std::string dictionary("");
    bool withClassVersion = false;
    bool debug = false;
    coral::CommandLine cmd(secondaryOptions,mainSet);
    cmd.parse(argc,argv);
    const std::map<std::string,std::string>& ops = cmd.userOptions();
    if(cmd.userCommand()==coral::CommandLine::helpOption().name || ops.size()==0){
      cmd.help(std::cout);
      return 0;
    } else {
      std::map<std::string,std::string>::const_iterator iO=ops.find(coral::CommandLine::helpOption().name);
      if(iO!=ops.end()){
        cmd.help(cmd.userCommand(),std::cout);
        return 0;
      } else {
        iO = ops.find(csPar.name);
        if(iO!=ops.end()) {
          connectionString = iO->second;
        } else {
          throw coral::MissingRequiredOptionException(csPar.name);
        }
        iO = ops.find(contPar.name);
        if(iO!=ops.end()) containerName = iO->second;
        iO = ops.find(mvPar.name);
        if(iO!=ops.end()) mappingVersion = iO->second;
        iO = ops.find(authPar.name);
        if(iO!=ops.end()) {
          authenticationPath.append(iO->second);
          ::putenv( (char*)authenticationPath.c_str() );
        }
        iO = ops.find(outPar.name);
        if(iO!=ops.end()) fileName = iO->second;
        iO = ops.find(classPar.name);
        if(iO!=ops.end()) className = iO->second;
        iO = ops.find(dictPar.name);
        if(iO!=ops.end()) dictionary = iO->second;
        iO = ops.find(cvPar.name);
        if(iO!=ops.end()) withClassVersion = true;
        iO = ops.find(debugPar.name);
        if(iO!=ops.end()) debug = true;

        boost::shared_ptr<ora::ConnectionPool> connection( new ora::ConnectionPool );
        connection->configuration().disablePoolAutomaticCleanUp();
        ora::Database db( connection );
        if( debug ) db.configuration().setMessageVerbosity( coral::Debug );

        std::string contTag("container.name");
        std::string classTag("type");
        std::string nobjTag("n.objects");
        std::string mapVerTag("mapping.id");
        std::string classVerTag("class.version");
        std::string space("  ");
        size_t contMax = contTag.length();
        size_t classMax = classTag.length();
        size_t nobjMax = nobjTag.length();
        size_t mapVerMax = mapVerTag.length();
        size_t classVerMax = classVerTag.length();

        if(cmd.userCommand()==listCont.name){
	  db.connect( connectionString, true );
	  ora::ScopedTransaction transaction( db.transaction() );
          transaction.start();
          if( ! db.exists() ){
	    std::cout << "ORA database does not exists in \""<<connectionString<<"\"."<<std::endl;
	    return 0;
	  }
          std::set<std::string> conts = db.containers();

          std::cout << "ORA database in \""<<connectionString<<"\" has "<<conts.size()<<" container(s)."<<std::endl;
          std::cout <<std::endl;
          if( conts.size() ){
            // first find the max lenghts
            for(std::set<std::string>::const_iterator iC = conts.begin(); iC != conts.end(); ++iC ){
              ora::Container cont = db.containerHandle( *iC );
              if(cont.name().length()>contMax ) contMax = cont.name().length();
              if(cont.className().length()>classMax ) classMax = cont.className().length();
            }
            std::cout << std::setiosflags(std::ios_base::left);
            std::cout <<space<<std::setw(contMax)<<contTag;
            std::cout <<space<<std::setw(classMax)<<classTag;
            std::cout <<space<<std::setw(nobjMax)<<nobjTag;
            std::cout <<std::endl;
            
            std::cout <<space<<std::setfill('-');
            std::cout<<std::setw(contMax)<<"";
            std::cout <<space<<std::setw(classMax)<<"";
            std::cout <<space<<std::setw(nobjMax)<<"";
            std::cout <<std::endl;

            std::cout << std::setfill(' ');
            for(std::set<std::string>::const_iterator iC = conts.begin(); iC != conts.end(); ++iC ){
              ora::Container cont = db.containerHandle( *iC );
              std::cout <<space<<std::setw(contMax)<<cont.name();
              std::cout <<space<<std::setw(classMax)<<cont.className();
              std::stringstream ss;
              ss << std::setiosflags(std::ios_base::right);
              ss <<space<<std::setw(nobjMax)<<cont.size();
              std::cout << ss.str();
              std::cout <<std::endl;
            }
          }
          
          transaction.commit();
          return 0;
        }
        if(cmd.userCommand()==createCont.name){
	  db.connect( connectionString );
	  ora::ScopedTransaction transaction( db.transaction() );
          transaction.start(false);
          if( className.empty() ){
            throw coral::MissingRequiredOptionException(classPar.name);
          }
          if( !dictionary.empty() ){
	    ora::SharedLibraryName libName;
            edmplugin::SharedLibrary shared( libName(dictionary)  );
          }
          if( !db.exists() ){
            db.create();
          } else {
            std::set<std::string> conts = db.containers();
            if( conts.find( containerName )!=conts.end() ){
              std::cout << "ERROR: container \"" << containerName << "\" already exists in the database."<<std::endl;
              return -1;
            }
          }
          db.createContainer( className, containerName );
          transaction.commit();
          return 0;
        }
        if(cmd.userCommand()==eraseCont.name){
	  db.connect( connectionString );
	  ora::ScopedTransaction transaction( db.transaction() );
          transaction.start(false);
          if( containerName.empty() ){
            throw coral::MissingRequiredOptionException(contPar.name);
          }
          if( !db.exists() ){
            std::cout << "ERROR: ORA database does not exist."<<std::endl;
            return -1;
          } else {
            std::set<std::string> conts = db.containers();
            if( conts.find( containerName )==conts.end() ){
              std::cout << "ERROR: container \"" << containerName << "\" does not exists in the database."<<std::endl;
              return -1;
            }
            db.dropContainer( containerName );
            transaction.commit();
            return 0;
          }
        }
        if(cmd.userCommand()==listMapp.name){
	  db.connect( connectionString, true );
	  ora::ScopedTransaction transaction( db.transaction() );
          transaction.start();
          if( containerName.empty() ){
            throw coral::MissingRequiredOptionException(contPar.name);
          }
          if( !db.exists() ){
            std::cout << "ERROR: ORA database does not exist."<<std::endl;
            return -1;
          } else {
            ora::DatabaseUtility util = db.utility();
            if(withClassVersion){
              std::map<std::string,std::string> vers = util.listMappings( containerName );

              std::cout << "ORA database in \""<<connectionString<<"\" has "<<vers.size()<<" class version(s) for container \""<<containerName<<"\"."<<std::endl;
              std::cout <<std::endl;
              if( vers.size() ){
                // first find the max lenghts
                for( std::map<std::string,std::string>::const_iterator iM = vers.begin(); iM != vers.end(); ++iM ){
                  if( iM->first.length() > classVerMax ) classVerMax = iM->first.length();
                  if( iM->second.length() > mapVerMax ) mapVerMax = iM->second.length();
                }

                std::cout << std::setiosflags(std::ios_base::left);
                std::cout <<space<<std::setw(classVerMax)<<classVerTag;
                std::cout <<space<<std::setw(mapVerMax)<<mapVerTag;
                std::cout <<std::endl;

                std::cout <<space<<std::setfill('-');
                std::cout<<std::setw(classVerMax)<<"";
                std::cout <<space<<std::setw(mapVerMax)<<"";
                std::cout <<std::endl;

                std::cout << std::setfill(' ');
                for( std::map<std::string,std::string>::const_iterator iM = vers.begin(); iM != vers.end(); ++iM ){
                  std::cout <<space<<std::setw(classVerMax)<<iM->first;
                  std::cout <<space<<std::setw(mapVerMax)<<iM->second;
                  std::cout <<std::endl;
                }
              }              
            } else {
              std::set<std::string> vers = util.listMappingVersions( containerName );

              std::cout << "ORA database in \""<<connectionString<<"\" has "<<vers.size()<<" mapping version(s) for container \""<<containerName<<"\"."<<std::endl;
              std::cout <<std::endl;
              if( vers.size() ){
                // first find the max lenghts
                for( std::set<std::string>::const_iterator iM = vers.begin(); iM != vers.end(); ++iM ){
                  if( iM->length() > mapVerMax ) mapVerMax = iM->length();
                }

                std::cout << std::setiosflags(std::ios_base::left);
                std::cout <<space<<std::setw(mapVerMax)<<mapVerTag;
                std::cout <<std::endl;

                std::cout <<space<<std::setfill('-');
                std::cout <<std::setw(mapVerMax)<<"";
                std::cout <<std::endl;

                std::cout << std::setfill(' ');
                for( std::set<std::string>::const_iterator iM = vers.begin(); iM != vers.end(); ++iM ){
                  std::cout <<space<<std::setw(mapVerMax)<<*iM;
                  std::cout <<std::endl;
                }
              }
            }
            transaction.commit();
            return 0;
          }
        }
        if(cmd.userCommand()==dumpMapp.name){
	  db.connect( connectionString, true );
	  ora::ScopedTransaction transaction( db.transaction() );
          transaction.start();
          if( mappingVersion.empty() ){
            throw coral::MissingRequiredOptionException(mvPar.name);
          }
          if( !db.exists() ){
            std::cout << "ERROR: ORA database does not exist."<<std::endl;
            return -1;
          } else {
            ora::DatabaseUtility util = db.utility();
            std::auto_ptr<std::fstream> file;
            std::ostream* outputStream = &std::cout;
            if( !fileName.empty() ){
              file.reset(new std::fstream);
              file->open( fileName.c_str(),std::fstream::out );
              outputStream = file.get();
            }
            bool dump = util.dumpMapping( mappingVersion, *outputStream );
            if(!dump){
              std::cout << "Mapping with id=\""<<mappingVersion<<"\" has not been found in the database."<<std::endl;
            }
            if( !fileName.empty() ){
              if( dump ) std::cout << "Mapping with id=\""<<mappingVersion<<"\" dumped in file =\""<<fileName<<"\""<<std::endl;
              file->close();
            }
            transaction.commit();
            return 0;
          }
        }
      }
    }

  } catch (const std::exception& e){
    std::cout << "ERROR: " << e.what() << std::endl;
    return -1;
  } catch (...){
    std::cout << "UNEXPECTED FAILURE." << std::endl;
    return -1;
  }
}
   std::set<ComponentType> ComponentPluginManager::AddPlugin(const std::string& abspath, bool saveWithScene)
   {

      // store the name of this plugin
      std::string libName(GetSimpleFileName(abspath));
      libName.assign(GetNameLessAllExtensions(libName));
#if defined(_DEBUG) && (defined(_MSC_VER) || defined(__CYGWIN__) || defined(__MINGW32__) || defined( __BCPLUSPLUS__)  || defined( __MWERKS__))
      // remove debug postfix from lib name
      std::string debugPostfix("d");
      libName = libName.substr(0, libName.size() - debugPostfix.size());
#endif // _DEBUG

#if defined(_MSC_VER) || defined(__CYGWIN__) || defined(__MINGW32__) || defined( __BCPLUSPLUS__)  || defined( __MWERKS__)
#else
   // remove "lib" prefix
   if(libName.length() > 3 && libName.substr(0, 3) == "lib")
   {
      libName = libName.substr(3, libName.length());
   }
#endif

      std::set<ComponentType> result;

      // if already loaded
      if(mLoadedPlugins.find(libName) != mLoadedPlugins.end())
      {
         // modify saveWithScene flag anyway, could have changed
         mLoadedPlugins[libName] = saveWithScene;
         return result;
      }

      if (libName.size() > 0)
      {
         mLoadedPlugins[libName] = saveWithScene;
      }

      std::list<ComponentPluginFactory*> factories;
      LoadPluginFactories(libName, abspath, factories);

      if(factories.empty())
      {
         mLoadedPlugins.erase(libName);
      }
      else
      {
         std::list<ComponentPluginFactory*>::iterator i;
         for(i = factories.begin(); i != factories.end(); ++i)
         {
            ComponentPluginFactory* factory = *i;
            assert(factory != NULL);

            ComponentType ctype = dtEntity::SID(factory->GetName());

            // store this type in output list
            result.insert(ctype);

            LOG_DEBUG("Registered entity system " + dtEntity::GetStringFromSID(ctype));
            // insert factory into factory list
            AddFactory(factory);
         }
      }

      return result;
   }
void CmpSeabaseDDL::createSeabaseRoutine(
				      StmtDDLCreateRoutine * createRoutineNode,
				      NAString &currCatName, 
                                      NAString &currSchName)
{
  Lng32 retcode = 0;
 
  ComObjectName routineName(createRoutineNode->getRoutineName());
  ComAnsiNamePart currCatAnsiName(currCatName);
  ComAnsiNamePart currSchAnsiName(currSchName);
  routineName.applyDefaults(currCatAnsiName, currSchAnsiName);
  const NAString catalogNamePart = 
    routineName.getCatalogNamePartAsAnsiString();
  const NAString schemaNamePart = 
    routineName.getSchemaNamePartAsAnsiString(TRUE);
  const NAString objectNamePart = 
    routineName.getObjectNamePartAsAnsiString(TRUE);
  const NAString extRoutineName = routineName.getExternalName(TRUE);
  ComRoutineType rType          = createRoutineNode->getRoutineType();
  ComRoutineLanguage language   = createRoutineNode->getLanguageType();
  ComRoutineParamStyle ddlStyle = createRoutineNode->getParamStyle();
  ComRoutineParamStyle style    = ddlStyle;
  NABoolean isJava              = (language == COM_LANGUAGE_JAVA);

  // Check to see if user has the authority to create the routine
  ExeCliInterface cliInterface(STMTHEAP, NULL, NULL, 
    CmpCommon::context()->sqlSession()->getParentQid());
  Int32 objectOwnerID = SUPER_USER;
  Int32 schemaOwnerID = SUPER_USER;
  ComSchemaClass schemaClass;

  retcode = verifyDDLCreateOperationAuthorized(&cliInterface,
                                               SQLOperation::CREATE_ROUTINE,
                                               catalogNamePart,
                                               schemaNamePart,
                                               schemaClass,
                                               objectOwnerID,
                                               schemaOwnerID);
  if (retcode != 0)
  {
     handleDDLCreateAuthorizationError(retcode,catalogNamePart,schemaNamePart);
     return;
  }
  
  ExpHbaseInterface * ehi = NULL;

  ehi = allocEHI();
  if (ehi == NULL)
    {
      processReturn();
      return;
    }
  
  retcode = existsInSeabaseMDTable(&cliInterface, 
				   catalogNamePart, schemaNamePart, 
                                   objectNamePart, COM_USER_DEFINED_ROUTINE_OBJECT, 
                                   TRUE, FALSE);
  if (retcode < 0)
    {
      deallocEHI(ehi); 
      processReturn();
      return;
    }

  if (retcode == 1) // already exists
    {
      *CmpCommon::diags() << DgSqlCode(-1390)
			  << DgString0(extRoutineName);
      deallocEHI(ehi); 
      processReturn();
      return;
    }

  
  ComObjectName libName(createRoutineNode->
                        getLibraryName().getQualifiedNameAsAnsiString());
  libName.applyDefaults(currCatAnsiName, currSchAnsiName);	
  NAString libCatNamePart = libName.getCatalogNamePartAsAnsiString();
  NAString libSchNamePart = libName.getSchemaNamePartAsAnsiString(TRUE);
  NAString libObjNamePart = libName.getObjectNamePartAsAnsiString(TRUE);
  const NAString extLibraryName = libName.getExternalName(TRUE);
  char externalPath[512] ;
  Lng32 cliRC = 0;
	
  // this call needs to change
  Int64 libUID = getObjectUID(&cliInterface, 
                              libCatNamePart, 
                              libSchNamePart, 
                              libObjNamePart,
                              COM_LIBRARY_OBJECT_LIT);

  if (libUID < 0)
    {
      processReturn();    
      return;
    }

  if (libUID == 0) // does not exist
    {
      *CmpCommon::diags() << DgSqlCode(-1361)
			  << DgString0(extLibraryName);
      deallocEHI(ehi); 
      processReturn();
      return;
    }

  // read the library path name from the LIBRARIES metadata table

  char * buf = new(STMTHEAP) char[200];
  str_sprintf(buf, "select library_filename from %s.\"%s\".%s"
              " where library_uid = %Ld for read uncommitted access",
              getSystemCatalog(), SEABASE_MD_SCHEMA, SEABASE_LIBRARIES, libUID);

  cliRC = cliInterface.fetchRowsPrologue(buf, TRUE/*no exec*/);
  if (cliRC < 0)
    {
      cliInterface.retrieveSQLDiagnostics(CmpCommon::diags());
      deallocEHI(ehi); 
      processReturn();
      return;
    }

  cliRC = cliInterface.clearExecFetchClose(NULL, 0);
  if (cliRC < 0)
    {
      cliInterface.retrieveSQLDiagnostics(CmpCommon::diags());
      deallocEHI(ehi); 
      processReturn();
      return;
    }
  if (cliRC == 100) // did not find the row
    {
      *CmpCommon::diags() << DgSqlCode(-1231)
                          << DgString0(extRoutineName);
      deallocEHI(ehi); 
      processReturn();
      return;
    }

  char * ptr = NULL;
  Lng32 len = 0;
  cliInterface.getPtrAndLen(1, ptr, len);
  str_cpy_all(externalPath, ptr, len);
  externalPath[len] = '\0'; 

  // determine language and parameter styles based on the library
  // type, unless already specified
  if (!createRoutineNode->isLanguageTypeSpecified())
    {
      NAString extPath(externalPath);
      size_t lastDot = extPath.last('.');
      NAString libSuffix;

      if (lastDot != NA_NPOS)
        libSuffix = extPath(lastDot,extPath.length()-lastDot);

      libSuffix.toUpper();

      if (libSuffix == ".JAR")
        {
          isJava = TRUE;
          language = COM_LANGUAGE_JAVA;
        }
      else if (libSuffix == ".SO" ||
               libSuffix == ".DLL")
        {
          // a known C/C++ library, set
          // language and parameter style below
        }
      else
        {
          // language not specified and library name
          // is inconclusive, issue an error
          *CmpCommon::diags() << DgSqlCode( -3284 )
                              << DgString0( externalPath );
          processReturn();
        }
    }

  // set parameter style and also language, if not already
  // specified, based on routine type and type of library
  if (isJava)
    {
      // library is a jar file

      if (rType == COM_PROCEDURE_TYPE)
        // Java stored procedures use the older Java style
        style = COM_STYLE_JAVA_CALL;
      else
        // Java UDFs use the newer Java object style
        style = COM_STYLE_JAVA_OBJ;
    }
  else
    {
      // assume the library is a DLL with C or C++ code
      if (rType == COM_TABLE_UDF_TYPE &&
          (language == COM_LANGUAGE_CPP ||
           !createRoutineNode->isLanguageTypeSpecified()))
        {
          // Table UDFs (TMUDFs) default to the C++ interface
          language = COM_LANGUAGE_CPP;
          style    = COM_STYLE_CPP_OBJ;
        }
      else if (rType == COM_SCALAR_UDF_TYPE &&
               (language == COM_LANGUAGE_C ||
                !createRoutineNode->isLanguageTypeSpecified()))
        {
          // scalar UDFs default to C and SQL parameter style
          language = COM_LANGUAGE_C;
          style    = COM_STYLE_SQL;
        }
      else
        {
          // some invalid combination of routine type, language and
          // library type
          *CmpCommon::diags() << DgSqlCode(-3286);
          processReturn();
          return;
        }
    } // C/C++ DLL

  if (createRoutineNode->isParamStyleSpecified() &&
      ddlStyle != style)
    {
      // An unsupported PARAMETER STYLE was specified
      *CmpCommon::diags() << DgSqlCode(-3280);
      processReturn();
      return;
    }

  NAString externalName;
  if (language == COM_LANGUAGE_JAVA &&
      style == COM_STYLE_JAVA_CALL)
    {
      // the external name is a Java method signature
      externalName = createRoutineNode->getJavaClassName();
      externalName += "." ;
      externalName += createRoutineNode->getJavaMethodName();
    }
  else
    // the external name is a C/C++ entry point or a
    // Java class name
    externalName = createRoutineNode->getExternalName();

  // Verify that current user has authority to create the routine
  // User must be DB__ROOT or have privileges
  if (isAuthorizationEnabled() && !ComUser::isRootUserID())
    {

      // For now, go get privileges directly.  If we ever cache routines, then
      // make sure privileges are stored in the cache.
      NAString privMgrMDLoc;
      CONCAT_CATSCH(privMgrMDLoc, getSystemCatalog(), SEABASE_PRIVMGR_SCHEMA);
      PrivMgrCommands privInterface(privMgrMDLoc.data(), CmpCommon::diags());
      PrivMgrUserPrivs privs;
      PrivStatus retcode = privInterface.getPrivileges(libUID, COM_LIBRARY_OBJECT, 
                                                       ComUser::getCurrentUser(), privs);
      if (retcode != STATUS_GOOD)
        {
          if (CmpCommon::diags()->getNumber(DgSqlCode::ERROR_) == 0)
            SEABASEDDL_INTERNAL_ERROR("checking routine privilege");
          processReturn();
          return;
        }

      // Requester must have USAGE privilege on the library
      NABoolean hasPriv = TRUE;
      if ( !privs.hasUsagePriv() )
        {
          *CmpCommon::diags() << DgSqlCode( -4481 )
                              << DgString0( "USAGE" )
                              << DgString1( extLibraryName.data());
          processReturn();
          return;
        }
    }

  ElemDDLParamDefArray &routineParamArray =
        createRoutineNode->getParamArray();
  Lng32 numParams = routineParamArray.entries();

  if ((createRoutineNode->getRoutineType() == COM_SCALAR_UDF_TYPE) &&
      (numParams > 32))
    {
      *CmpCommon::diags() << DgSqlCode( -1550 )
                          << DgString0( extRoutineName )
                          << DgInt0( numParams );
      deallocEHI(ehi); 
      processReturn();
      return;
    }
#define MAX_SIGNATURE_LENGTH 8193
  // Allocate buffer for generated signature
  char sigBuf[MAX_SIGNATURE_LENGTH];
  sigBuf[0] = '\0';

  if (style == COM_STYLE_JAVA_CALL) 
  {
     // validate routine for Java call based on signature
     Lng32 numJavaParam = 0;
     ComFSDataType *paramType = new ComFSDataType[numParams];
     ComUInt32     *subType   = new ComUInt32    [numParams];
     ComColumnDirection *direction = new ComColumnDirection[numParams];
     NAType *genericType;

     // Gather the param attributes for LM from the paramDefArray previously
     // populated and from the routineparamList generated from paramDefArray.

     for (CollIndex i = 0; (Int32)i < numParams; i++)
     {
       paramType[i] = (ComFSDataType)routineParamArray[i]->getParamDataType()->getFSDatatype();
       subType[i] = 0;  // default
       // Set subType for special cases detected by LM
       switch ( paramType[i] )
       {
         case COM_SIGNED_BIN16_FSDT :
         case COM_SIGNED_BIN32_FSDT :
         case COM_SIGNED_BIN64_FSDT :
         case COM_UNSIGNED_BIN16_FSDT :
         case COM_UNSIGNED_BIN32_FSDT :
         case COM_UNSIGNED_BPINT_FSDT :
         {
           genericType = routineParamArray[i]->getParamDataType() ;
           if (genericType->getTypeName() == LiteralNumeric)
             subType[i] = genericType->getPrecision();
           else
             subType[i] = 0 ;

           break;
         }

         case COM_DATETIME_FSDT :
         {
           genericType = routineParamArray[i]->getParamDataType() ;
           DatetimeType & datetimeType = (DatetimeType &) *genericType;
            if (datetimeType.getSimpleTypeName() EQU "DATE")
              subType[i] = 1 ;
            else if (datetimeType.getSimpleTypeName() EQU "TIME")
              subType[i] = 2;
            else if (datetimeType.getSimpleTypeName() EQU "TIMESTAMP")
              subType[i] = 3;
         }
       } // end switch paramType[i]

       direction[i] = (ComColumnDirection) routineParamArray[i]->getParamDirection();
     }
    
     // If the syntax specified a signature, pass that to LanguageManager.
     NAString specifiedSig( createRoutineNode->getJavaSignature() );
     char* optionalSig;
     if ( specifiedSig.length() == 0 )
       optionalSig = NULL;
     else
       optionalSig = (char *)specifiedSig.data();
     
     ComBoolean isJavaMain =
       ((str_cmp_ne(createRoutineNode->getJavaMethodName(), "main") == 0) ? TRUE : FALSE);

     LmResult createSigResult;
     LmJavaSignature *lmSignature =  new (STMTHEAP) LmJavaSignature(NULL,
                                                                    STMTHEAP);
     createSigResult = lmSignature->createSig(paramType, subType, direction,
                                              numParams, COM_UNKNOWN_FSDT, 0,
                                              createRoutineNode->getMaxResults(), optionalSig, isJavaMain, sigBuf,
                                              MAX_SIGNATURE_LENGTH,
                                              CmpCommon::diags());
     NADELETE(lmSignature, LmJavaSignature, STMTHEAP);
     delete [] paramType;
     delete [] subType;
     delete [] direction;

     // Lm returned error. Lm fills diags area, so no need to worry about diags.
     if (createSigResult == LM_ERR)
     {
       *CmpCommon::diags() << DgSqlCode(-1231)
			  << DgString0(extRoutineName);
       deallocEHI(ehi); 
       processReturn();
       return;
     }

     numJavaParam = (isJavaMain ? 1 : numParams);

     if (validateRoutine(&cliInterface, 
                         createRoutineNode->getJavaClassName(),
                         createRoutineNode->getJavaMethodName(),
                         externalPath,
                         sigBuf,
                         numJavaParam,
                         createRoutineNode->getMaxResults(),
                         optionalSig))
     {
       *CmpCommon::diags() << DgSqlCode(-1231)
                           << DgString0(extRoutineName);
       deallocEHI(ehi); 
       processReturn();
       return;
     }
  }
  else if (style == COM_STYLE_JAVA_OBJ ||
           style == COM_STYLE_CPP_OBJ)
  {
    // validate existence of the C++ or Java class in the library
    Int32 routineHandle = NullCliRoutineHandle;
    NAString externalPrefix(externalPath);
    NAString externalNameForValidation(externalName);
    NAString containerName;

    if (language == COM_LANGUAGE_C || language == COM_LANGUAGE_CPP)
      {
        // separate the actual DLL name from the prefix
        char separator = '/';
        size_t separatorPos = externalPrefix.last(separator);

        if (separatorPos != NA_NPOS)
          {
            containerName = externalPrefix(separatorPos+1,
                                           externalPrefix.length()-separatorPos-1);
            externalPrefix.remove(separatorPos,
                                  externalPrefix.length()-separatorPos);
          }
        else
          {
            // assume the entire string is a local name
            containerName = externalPrefix;
            externalPrefix = ".";
          }
      }
    else
      {
        // For Java, the way the language manager works is that the
        // external path is the fully qualified name of the jar and
        // the container is the class name (external name).  We load
        // the container (the class) by searching in the path (the
        // jar). The external name is the method name, which in this
        // case is the constructor of the class, <init>.

        // leave externalPrevix unchanged, fully qualified jar file
        containerName = externalName;
        externalNameForValidation = "<init>";
      }

    // use a CLI call to validate that the library contains the routine
    if (cliInterface.getRoutine(
             NULL, // No InvocationInfo specified in this step
             0,
             NULL,
             0,
             (Int32) language,
             (Int32) style,
             externalNameForValidation.data(),
             containerName.data(),
             externalPrefix.data(),
             extLibraryName.data(),
             &routineHandle,
             CmpCommon::diags()) != LME_ROUTINE_VALIDATED)
      {
        if (routineHandle != NullCliRoutineHandle)
          cliInterface.putRoutine(routineHandle,
                                  CmpCommon::diags());

        CMPASSERT(CmpCommon::diags()->mainSQLCODE() < 0);
        processReturn();
        return;
      }

    cliInterface.putRoutine(routineHandle,
                            CmpCommon::diags());
  }

  ComTdbVirtTableColumnInfo * colInfoArray = (ComTdbVirtTableColumnInfo*)
    new(STMTHEAP) ComTdbVirtTableColumnInfo[numParams];

  if (buildColInfoArray(&routineParamArray, colInfoArray))
    {
      processReturn();
      return;
    }

  ComTdbVirtTableTableInfo * tableInfo = new(STMTHEAP) ComTdbVirtTableTableInfo[1];
  tableInfo->tableName = NULL,
  tableInfo->createTime = 0;
  tableInfo->redefTime = 0;
  tableInfo->objUID = 0;
  tableInfo->objOwnerID = objectOwnerID;
  tableInfo->schemaOwnerID = schemaOwnerID;
  tableInfo->isAudited = 1;
  tableInfo->validDef = 1;
  tableInfo->hbaseCreateOptions = NULL;
  tableInfo->numSaltPartns = 0;
  tableInfo->rowFormat = COM_UNKNOWN_FORMAT_TYPE;
  tableInfo->objectFlags = 0;

  Int64 objUID = -1;
  if (updateSeabaseMDTable(&cliInterface, 
			   catalogNamePart, schemaNamePart, objectNamePart,
			   COM_USER_DEFINED_ROUTINE_OBJECT,
			   "N",
			   tableInfo,
			   numParams,
			   colInfoArray,
			   0, NULL,
			   0, NULL,
                           objUID))
    {
      deallocEHI(ehi); 
      processReturn();
      return;
    }

  if (objUID == -1)
    {
      deallocEHI(ehi); 
      processReturn();
      return;
    }

  NAString udrType;
  getRoutineTypeLit(createRoutineNode->getRoutineType(), udrType);
  NAString languageType;
  getLanguageTypeLit(language, languageType);
  NAString sqlAccess;
  getSqlAccessLit(createRoutineNode->getSqlAccess(), sqlAccess);
  NAString paramStyle;
  getParamStyleLit(style, paramStyle);
  NAString transactionAttributes;
  getTransAttributesLit(createRoutineNode->getTransactionAttributes(), transactionAttributes);
  NAString parallelism;
  getParallelismLit(createRoutineNode->getParallelism(), parallelism);
  NAString externalSecurity;
  getExternalSecurityLit(createRoutineNode->getExternalSecurity(), externalSecurity);
  NAString executionMode;
  getExecutionModeLit(createRoutineNode->getExecutionMode(), executionMode);
  

  char * query = new(STMTHEAP) char[2000+MAX_SIGNATURE_LENGTH];
  str_sprintf(query, "insert into %s.\"%s\".%s values (%Ld, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, '%s', '%s', '%s', '%s', '%s', %Ld, '%s' )",
	      getSystemCatalog(), SEABASE_MD_SCHEMA, SEABASE_ROUTINES,
	      objUID,
              udrType.data(),
              languageType.data(),
              createRoutineNode->isDeterministic() ? "Y" : "N" ,
              sqlAccess.data(),
              createRoutineNode->isCallOnNull() ? "Y" : "N" ,
              createRoutineNode->isIsolate() ? "Y" : "N" ,
              paramStyle.data(),
              transactionAttributes.data(),
              createRoutineNode->getMaxResults(),
              createRoutineNode->getStateAreaSize(),
              externalName.data(),
              parallelism.data(),
              createRoutineNode->getUserVersion().data(),
              externalSecurity.data(),
              executionMode.data(),
              libUID,
              sigBuf);
  
  cliRC = cliInterface.executeImmediate(query);
  NADELETEBASIC(query, STMTHEAP);
  if (cliRC < 0)
    {
      cliInterface.retrieveSQLDiagnostics(CmpCommon::diags());
      processReturn();
      return;
    }

  char * query1 = new(STMTHEAP) char[1000];
  str_sprintf(query1, "insert into %s.\"%s\".%s values (%Ld, %Ld)",
	      getSystemCatalog(), SEABASE_MD_SCHEMA, SEABASE_LIBRARIES_USAGE,
	      libUID, objUID);
  
  cliRC = cliInterface.executeImmediate(query1);
  NADELETEBASIC(query1, STMTHEAP);
  if (cliRC < 0)
    {
      cliInterface.retrieveSQLDiagnostics(CmpCommon::diags());
      processReturn();
      return;
    }

  // hope to remove this call soon by setting the valid flag to Y sooner
  if (updateObjectValidDef(&cliInterface, 
			   catalogNamePart, schemaNamePart, objectNamePart,
			   COM_USER_DEFINED_ROUTINE_OBJECT_LIT,
			   "Y"))
    {
      deallocEHI(ehi); 
      processReturn();
      return;
    }

  processReturn();
  return;
}