ModHandle CModules::OpenModule(const CString& sModule, const CString& sModPath, bool &bVersionMismatch,
		bool &bIsGlobal, CString& sDesc, CString& sRetMsg) {
	// Some sane defaults in case anything errors out below
	bVersionMismatch = false;
	bIsGlobal = false;
	sDesc.clear();
	sRetMsg.clear();

	for (unsigned int a = 0; a < sModule.length(); a++) {
		if (((sModule[a] < '0') || (sModule[a] > '9')) && ((sModule[a] < 'a') || (sModule[a] > 'z')) && ((sModule[a] < 'A') || (sModule[a] > 'Z')) && (sModule[a] != '_')) {
			sRetMsg = "Module names can only contain letters, numbers and underscores, [" + sModule + "] is invalid.";
			return NULL;
		}
	}

#ifndef _WIN32
	// The second argument to dlopen() has a long history. It seems clear
	// that (despite what the man page says) we must include either of
	// RTLD_NOW and RTLD_LAZY and either of RTLD_GLOBAL and RTLD_LOCAL.
	//
	// RTLD_NOW vs. RTLD_LAZY: We use RTLD_NOW to avoid znc dying due to
	// failed symbol lookups later on. Doesn't really seem to have much of a
	// performance impact.
	//
	// RTLD_GLOBAL vs. RTLD_LOCAL: If perl is loaded with RTLD_LOCAL and later on
	// loads own modules (which it apparently does with RTLD_LAZY), we will die in a
	// name lookup since one of perl's symbols isn't found. That's worse
	// than any theoretical issue with RTLD_GLOBAL.
	ModHandle p = dlopen((sModPath).c_str(), RTLD_NOW | RTLD_GLOBAL);
#else
	ModHandle p = dlopen((sModPath).c_str(), RTLD_NOW | RTLD_LOCAL);
#endif

	if (!p) {
		sRetMsg = "Unable to open module [" + sModule + "] [" + dlerror() + "]";
		return NULL;
	}

	typedef double (*dFP)();
	dFP Version = (dFP) dlsym(p, "ZNCModVersion");

	if (!Version) {
		dlclose(p);
		sRetMsg = "Could not find ZNCModVersion() in module [" + sModule + "]";
		return NULL;
	}

	typedef bool (*bFP)();
	bFP IsGlobal = (bFP) dlsym(p, "ZNCModGlobal");

	if (!IsGlobal) {
		dlclose(p);
		sRetMsg = "Could not find ZNCModGlobal() in module [" + sModule + "]";
		return NULL;
	}

	typedef const char *(*sFP)();
	sFP GetDesc = (sFP) dlsym(p, "ZNCModDescription");

	if (!GetDesc) {
		dlclose(p);
		sRetMsg = "Could not find ZNCModDescription() in module [" + sModule + "]";
		return NULL;
	}

	if (CModule::GetCoreVersion() != Version()) {
		bVersionMismatch = true;
#ifndef _WIN32
		sRetMsg = "Version mismatch, recompile this module.";
#else
		sRetMsg = "Module version is '" + CString(Version(), 3) + "', but core expects '" +
			CString(CModule::GetCoreVersion(), 3) + "'. Please re-download/re-install/re-compile the module.";
#endif
	} else {
		sRetMsg = "";
		bVersionMismatch = false;
		bIsGlobal = IsGlobal();
		sDesc = GetDesc();
	}

	return p;
}
CMMBDataSource::CMMBDataSource(int fd)
{
    const char* dlerr;
    //do null
    pVideoFrame = NULL;
    FrameOffset = 0;

    
    libcmmbsp_handle = dlopen("/data/data/com.mediatek.cmmb.app/lib/libcmmbsp.so",RTLD_NOW);                           // dlopen ´ò¿ªso

    dlerr = dlerror();
    if (dlerr != NULL) 
	    LOGE("CMMBDataSource: dlopen() error: %s\n", dlerr);
    if(!libcmmbsp_handle)
    {
	    LOGE("CMMBDataSource dlopen /data/data/com.mediatek.cmmb.app/lib/libcmmbsp fail,then open /system/lib/so");
	    libcmmbsp_handle = dlopen("libcmmbsp.so",RTLD_NOW);
	    if(!libcmmbsp_handle)
	    {
		    LOGE("CMMBDataSource dlopen /system/lib/so fail");
	    }
    }
    if(libcmmbsp_handle){
            LOGI("dlopen success,then dlsym");
	    // get CmmbFreeVideoFrame function point 
	    F_CmmbFreeVideoFrame = (CmmbFreeVideoFrame_T)dlsym(libcmmbsp_handle,"CmmbFreeVideoFrame");    
	    dlerr = dlerror();
	    if (dlerr != NULL){
		    LOGE( "CMMBDataSource::CMMBDataSource CmmbFreeVideoFrame dlsym() error: %s\n", dlerr);
                    F_CmmbFreeVideoFrame=NULL;
	    }
	    // get CmmbReadVideoFrame function point 
	    F_CmmbReadVideoFrame = (CmmbReadVideoFrame_T)dlsym(libcmmbsp_handle,"CmmbReadVideoFrame");    
	    dlerr = dlerror();
	    if (dlerr != NULL){
		    LOGE( "CMMBDataSource::CMMBDataSource CmmbReadVideoFrame dlsym() error: %s\n", dlerr);
                    F_CmmbReadVideoFrame = NULL;
	    }
	    // get CmmbReadAudioFrame function point
	    F_CmmbReadAudioFrame=(CmmbReadAudioFrame_T)dlsym(libcmmbsp_handle,"CmmbReadAudioFrame");    
	    dlerr = dlerror();
	    if (dlerr != NULL){
		    LOGE( "CMMBDataSource::CMMBDataSource CmmbReadAudioFrame dlsym() error: %s\n", dlerr);
                    F_CmmbReadAudioFrame=NULL;
	    }
	    // get CmmbFreeAudioFrame function point 
	    F_CmmbFreeAudioFrame = (CmmbFreeAudioFrame_T)dlsym(libcmmbsp_handle,"CmmbFreeAudioFrame");   
	    dlerr = dlerror();
	    if (dlerr != NULL){
		    LOGE( "CMMBDataSource::CMMBDataSource CmmbFreeAudioFrame dlsym() error: %s\n", dlerr);
                    F_CmmbFreeAudioFrame=NULL;
	    }
	    // get CmmbFlushAVFrame function point 
	    F_CmmbFlushAVFrame = (CmmbFlushAVFrame_T)dlsym(libcmmbsp_handle,"CmmbFlushAVFrame");    
	    dlerr = dlerror();
	    if (dlerr != NULL){
		    LOGE( "CMMBDataSource::CMMBDataSource CmmbFlushAVFrame dlsym() error: %s\n", dlerr);
                    F_CmmbFlushAVFrame =NULL;
	    }
	    // get CmmbGetMetadata function point 
	    F_CmmbGetMetadata = (CmmbGetMetadata_T)dlsym(libcmmbsp_handle,"CmmbGetMetadata");    
	    dlerr = dlerror();
	    if (dlerr != NULL){
		    LOGE( "CMMBDataSource::CMMBDataSource CmmbGetMetadata dlsym() error: %s\n", dlerr);
                    F_CmmbGetMetadata = NULL;
	    }

	    // get CmmbFlushOldestFrame function point 
	    F_CmmbFlushOldestFrame = (CmmbFlushOldestFrame_T)dlsym(libcmmbsp_handle,"CmmbFlushOldestFrame");    
	    dlerr = dlerror();
	    if (dlerr != NULL){
		    LOGE( "CMMBDataSource::CMMBDataSource CmmbFlushOldestFrame dlsym() error: %s\n", dlerr);
                    F_CmmbFlushOldestFrame = NULL;
	    }
    }

    /*release redundancy frame to push forward playback*/
    if(F_CmmbFlushOldestFrame)
    {
	    F_CmmbFlushOldestFrame();
    }
    else
    {
	    LOGE("Error F_CmmbFlushOldestFrame=NULL");
    }
    //test	
 #if 0   
    filesource = new CMMBFileSource;
#endif	
}
Exemple #3
0
static int
load_dll(ClipMachine * mp, const char *name, struct Coll *names, ClipVar * resp)
{
	void *hp;
	char buf[256], *s, *e;
	char uname[128];
	const char **spp;
	ClipModule *entry;
	ClipFunction **fpp;
	ClipNameEntry *np;
	ClipFile **cpp;
	struct DBFuncTable **dpp;
	unsigned l, i;
	int ret = 0;

	s = strrchr(name, '/');
	if (s)
		snprintf(buf, sizeof(buf), "%s", name);
	else
		snprintf(buf, sizeof(buf), "%s/lib/%s", CLIPROOT, name);

	if (!loaded_dlls)
	{
		loaded_dlls = new_Coll(free, strcmp);
	}
	else
	{
		if (search_Coll(loaded_dlls, buf, 0))
			return 0;
	}

	hp = dlopen(buf, RTLD_NOW);
	if (!hp)
	{
		_clip_trap_printf(mp, __FILE__, __LINE__, "shared loading problem: %s: file %s", dlerror(), buf);
		return _clip_call_errblock(mp, 1);
	}

	insert_Coll(loaded_dlls, strdup(buf));

/*
   path/name.ext -> name_module entry symbol
 */

	s = strrchr(name, '/');
	if (!s)
		s = (char *) name;
	else
		s = s + 1;
	e = strchr(s, '.');
	if (e)
		l = e - s;
	else
		l = strlen(s);
	if (l > sizeof(uname))
		l = sizeof(uname);

	for (i = 0; i < l; i++, s++)
	{
		if (*s == '-')
			uname[i] = '_';
		else
			uname[i] = toupper(*s);
	}
	uname[l] = 0;
	snprintf(buf, sizeof(buf), "clip__MODULE_%s", uname);

	entry = (ClipModule *) dlsym(hp, buf);

	if (!entry)
	{
		_clip_trap_printf(mp, __FILE__, __LINE__, "shared '%s' fetch name '%s' problem: %s", name, buf, dlerror());
		return _clip_call_errblock(mp, 1);
	}

	for (np = entry->cfunctions; np && np->f; ++np)
		_clip_register_hash(mp, np->f, np->hash);

	for (fpp = entry->inits; fpp && *fpp; ++fpp)
		_clip_main_func(mp, *fpp, _clip_argc, _clip_argv, _clip_envp);

	for (fpp = entry->exits; fpp && *fpp; ++fpp)
	{
		mp->cexits = realloc(mp->cexits, (mp->ncexits + 1) * sizeof(ClipFunction *));
		mp->cexits[mp->ncexits] = *fpp;
		++mp->ncexits;
	}

	for (spp = entry->pfunctions; spp && *spp; ++spp)
		if (_clip_load(mp, *spp, 0, 0))
			++ret;
/*
	if (entry->cpfile && _clip_register_file(mp, entry->cpfile))
		++ret;
*/
	for (cpp = entry->cpfiles; cpp && *cpp; ++cpp)
		if (_clip_register_file(mp, *cpp))
			++ret;

	for (dpp = entry->dbdrivers; dpp && *dpp; ++dpp)
		if (_clip_register_driver(mp, *dpp))
			++ret;

	add_ClipVect(&mp->dlls, hp);

	return ret;
}
/*
==============
VID_LoadRefresh
==============
*/
qboolean VID_LoadRefresh( char *name )
{
	refimport_t	ri;
	GetRefAPI_t	GetRefAPI;
	char	fn[MAX_OSPATH];
	struct stat st;
	extern uid_t saved_euid;
	FILE *fp;
	
	if ( reflib_active )
	{
		if (KBD_Close_fp)
			KBD_Close_fp();
		if (RW_IN_Shutdown_fp)
			RW_IN_Shutdown_fp();
		KBD_Close_fp = NULL;
		RW_IN_Shutdown_fp = NULL;
		re.Shutdown();
		VID_FreeReflib ();
	}

	Com_Printf( "------- Loading %s -------\n", name );

	//regain root
	seteuid(saved_euid);

	if ((fp = fopen(so_file, "r")) == NULL) {
		Com_Printf( "LoadLibrary(\"%s\") failed: can't open %s (required for location of ref libraries)\n", name, so_file);
		return false;
	}
	fgets(fn, sizeof(fn), fp);
	fclose(fp);
	while (*fn && isspace(fn[strlen(fn) - 1]))
		fn[strlen(fn) - 1] = 0;

	strcat(fn, "/");
	strcat(fn, name);

	// permission checking
	if (strstr(fn, "softx") == NULL) { // softx doesn't require root
		if (stat(fn, &st) == -1) {
			Com_Printf( "LoadLibrary(\"%s\") failed: %s\n", name, strerror(errno));
			return false;
		}
#if 0
		if (st.st_uid != 0) {
			Com_Printf( "LoadLibrary(\"%s\") failed: ref is not owned by root\n", name);
			return false;
		}
		if ((st.st_mode & 0777) & ~0700) {
			Com_Printf( "LoadLibrary(\"%s\") failed: invalid permissions, must be 700 for security considerations\n", name);
			return false;
		}
#endif
	} else {
		// softx requires we give up root now
		setreuid(getuid(), getuid());
		setegid(getgid());
	}

	if ( ( reflib_library = dlopen( fn, RTLD_LAZY | RTLD_GLOBAL ) ) == 0 )
	{
		Com_Printf( "LoadLibrary(\"%s\") failed: %s\n", name , dlerror());
		return false;
	}

  Com_Printf( "LoadLibrary(\"%s\")\n", fn );

	ri.Cmd_AddCommand = Cmd_AddCommand;
	ri.Cmd_RemoveCommand = Cmd_RemoveCommand;
	ri.Cmd_Argc = Cmd_Argc;
	ri.Cmd_Argv = Cmd_Argv;
	ri.Cmd_ExecuteText = Cbuf_ExecuteText;
	ri.Con_Printf = VID_Printf;
	ri.Sys_Error = VID_Error;
	ri.FS_LoadFile = FS_LoadFile;
	ri.FS_FreeFile = FS_FreeFile;
	ri.FS_Gamedir = FS_Gamedir;
	ri.Cvar_Get = Cvar_Get;
	ri.Cvar_Set = Cvar_Set;
	ri.Cvar_SetValue = Cvar_SetValue;
	ri.Vid_GetModeInfo = VID_GetModeInfo;
	ri.Vid_MenuInit = VID_MenuInit;
	ri.Vid_NewWindow = VID_NewWindow;

	if ( ( GetRefAPI = (void *) dlsym( reflib_library, "GetRefAPI" ) ) == 0 )
		Com_Error( ERR_FATAL, "dlsym failed on %s", name );

	re = GetRefAPI( ri );

	if (re.api_version != API_VERSION)
	{
		VID_FreeReflib ();
		Com_Error (ERR_FATAL, "%s has incompatible api_version", name);
	}

	/* Init IN (Mouse) */
	in_state.IN_CenterView_fp = IN_CenterView;
	in_state.Key_Event_fp = Do_Key_Event;
	in_state.viewangles = cl.viewangles;
	in_state.in_strafe_state = &in_strafe.state;

	if ((RW_IN_Init_fp = dlsym(reflib_library, "RW_IN_Init")) == NULL ||
		(RW_IN_Shutdown_fp = dlsym(reflib_library, "RW_IN_Shutdown")) == NULL ||
		(RW_IN_Activate_fp = dlsym(reflib_library, "RW_IN_Activate")) == NULL ||
		(RW_IN_Commands_fp = dlsym(reflib_library, "RW_IN_Commands")) == NULL ||
		(RW_IN_Move_fp = dlsym(reflib_library, "RW_IN_Move")) == NULL ||
		(RW_IN_Frame_fp = dlsym(reflib_library, "RW_IN_Frame")) == NULL)
		Sys_Error("No RW_IN functions in REF.\n");

	Real_IN_Init();

	if ( re.Init( 0, 0 ) == -1 )
	{
		re.Shutdown();
		VID_FreeReflib ();
		return false;
	}

	/* Init KBD */
#if 1
	if ((KBD_Init_fp = dlsym(reflib_library, "KBD_Init")) == NULL ||
		(KBD_Update_fp = dlsym(reflib_library, "KBD_Update")) == NULL ||
		(KBD_Close_fp = dlsym(reflib_library, "KBD_Close")) == NULL)
		Sys_Error("No KBD functions in REF.\n");
#else
	{
		void KBD_Init(void);
		void KBD_Update(void);
		void KBD_Close(void);

		KBD_Init_fp = KBD_Init;
		KBD_Update_fp = KBD_Update;
		KBD_Close_fp = KBD_Close;
	}
#endif
	KBD_Init_fp(Do_Key_Event);

	// give up root now
	setreuid(getuid(), getuid());
	setegid(getgid());

	Com_Printf( "------------------------------------\n");
	reflib_active = true;
	return true;
}
OMX_ERRORTYPE RKOMXPlugin::AddCore(const char* coreName)
{
   bool isRKCore = false;
   if (!strcmp(coreName, "libOMX_Core.so")) {
       isRKCore = true;
   }
   void* libHandle = dlopen(coreName, RTLD_NOW);

   if (libHandle != NULL) {
        RKOMXCore* core = (RKOMXCore*)calloc(1,sizeof(RKOMXCore));

        if (!core) {
            dlclose(libHandle);
            return OMX_ErrorUndefined;
        }
        // set plugin lib handle and methods
        core->mLibHandle = libHandle;
		if (isRKCore) {
            core->mInit = (RKOMXCore::InitFunc)dlsym(libHandle, "RKOMX_Init");
            core->mDeinit = (RKOMXCore::DeinitFunc)dlsym(libHandle, "RKOMX_DeInit");

            core->mComponentNameEnum =
            (RKOMXCore::ComponentNameEnumFunc)dlsym(libHandle, "RKOMX_ComponentNameEnum");

            core->mGetHandle = (RKOMXCore::GetHandleFunc)dlsym(libHandle, "RKOMX_GetHandle");
            core->mFreeHandle = (RKOMXCore::FreeHandleFunc)dlsym(libHandle, "RKOMX_FreeHandle");

            core->mGetRolesOfComponentHandle =
                (RKOMXCore::GetRolesOfComponentFunc)dlsym(
                        libHandle, "RKOMX_GetRolesOfComponent");

		} else {
            core->mInit = (RKOMXCore::InitFunc)dlsym(libHandle, "OMX_Init");
            core->mDeinit = (RKOMXCore::DeinitFunc)dlsym(libHandle, "OMX_Deinit");

            core->mComponentNameEnum =
            (RKOMXCore::ComponentNameEnumFunc)dlsym(libHandle, "OMX_ComponentNameEnum");

            core->mGetHandle = (RKOMXCore::GetHandleFunc)dlsym(libHandle, "OMX_GetHandle");
            core->mFreeHandle = (RKOMXCore::FreeHandleFunc)dlsym(libHandle, "OMX_FreeHandle");

            core->mGetRolesOfComponentHandle =
                (RKOMXCore::GetRolesOfComponentFunc)dlsym(
                        libHandle, "OMX_GetRolesOfComponent");
		}
        if (core->mInit != NULL) {
            (*(core->mInit))();
        }
        if (core->mComponentNameEnum != NULL) {
            // calculating number of components registered inside given OMX core
            char tmpComponentName[OMX_MAX_STRINGNAME_SIZE] = { 0 };
            OMX_U32 tmpIndex = 0;
            while (OMX_ErrorNone == ((*(core->mComponentNameEnum))(tmpComponentName, OMX_MAX_STRINGNAME_SIZE, tmpIndex))) {
                tmpIndex++;
            ALOGI("OMX IL core %s: declares component %s", coreName, tmpComponentName);
            }
            core->mNumComponents = tmpIndex;
            ALOGI("OMX IL core %s: contains %ld components", coreName, core->mNumComponents);
        }
        // add plugin to the vector
        mCores.push_back(core);
    }
    else {
        ALOGW("OMX IL core %s not found", coreName);
        return OMX_ErrorUndefined; // Do we need to return error message
    }
    return OMX_ErrorNone;
}
Exemple #6
0
s32 ifm_process_unregister_notify(const s8 * ifname, s32 ifindex)
{
	void *handle;
	s32 (* subif_del_handle)(const s8 *);
	s8 *error;	
    s32 ret = ERROR_SUCCESS;
	struct if_stat *ifstat=NULL;
	ifstat=if_stat_list;
    sqlite3 *db= NULL;
	sqlite3_res res=NULL;
	s8 sqlite_sql_buf[SQLITE_SQL_BUF_SIZE];
	s32 count=0;
    while(ifstat!=NULL)
    {
        if((strcmp(ifstat->name,ifname) == 0)&&(ifstat->use_flag==IFMD_INFO_USE))
        {   
            
            ifstat->use_flag=IFMD_INFO_UN_USE;
			syslogex_syslog_send("ifmd",LOG_NOTICE|LOG_DAEMON,"Interface %s is unregister\n",ifstat->name);
			break;
		}
		else
		{
			ifstat = ifstat->next;
		}
	} 
	if((strncmp(ifname,"eth",3)==0)&&(strchr(ifname,'.') != NULL))
	{
		
		handle = dlopen("/usr/lib/liblogicinterface.so", RTLD_LAZY);
		if(handle)
		{
			return ERROR_SUCCESS;
		}
		dlerror();
		
		subif_del_handle = dlsym(handle, "subInterface_db_delete");
		if ((error = dlerror()) != NULL)  
		{
			return ERROR_SYSTEM;
		}		
		if(ERROR_SUCCESS != if_get_index_by_name(ifname, &ifindex))
		{
			return ERROR_SYSTEM;
		}
		db = sqlite3_open_ex(1,IFMODE_DB);
		if(NULL == db)
		{
			dlclose(handle);
			return ERROR_SYSTEM;
		}
		snprintf(sqlite_sql_buf, SQLITE_SQL_BUF_SIZE,
                "select count(ifindex) as count from (select l3.ifindex from tb_port_l3 as l3 where l3.ifindex = '%d' union all select l2.ifindex from tb_port_l2 as l2 where l2.ifindex = '%d');", ifindex, ifindex);
		 

		 
		ret = sqlite3_exec_query_ex (db, sqlite_sql_buf, &res);
		if (SQLITE_OK != ret)
		{
			sqlite3_close_ex(db);
			dlclose(handle);
			return VLAN_DB_OPT_UNSUCCESS;
		}
		ret = sqlite3_get_u32_ex (res, 0, "count", (u32*) &count);
		if (SQLITE_OK != ret)
		{
			count = VLAN_DB_OPT_UNSUCCESS;	
		}
		sqlite3_res_free_ex(res);
		res = NULL;
		sqlite3_close_ex(db);
		 
		if(count>0)
		{   
			ret = subif_del_handle(ifname);
			if(ret!=ERROR_SUCCESS)
			{
				dlclose(handle);
			    return ret;
			}
		}
		else
		{   
			dlclose(handle);
			return ret;
		}
		
	}
    return ret;
}
Exemple #7
0
  std::string unity_global::load_toolkit(std::string soname,
                                         std::string module_subpath) {
    // rewrite "local" protocol
    std::string protocol = fileio::get_protocol(soname);
    if (protocol == "local") {
      soname = fileio::remove_protocol(soname);
    }

    so_registration_list regentry;
    regentry.original_soname = soname;
    logstream(LOG_INFO) << "Attempt loading of " << sanitize_url(soname) << std::endl;

    // see if the file exists and whether we need to donwnload it
    if (fileio::try_to_open_file(soname) == false) {
      return "Unable to open file " + sanitize_url(soname);
    }

    if (protocol != "") {
      // there is a protocol associated. We need to copy this file to local
      // issue a copy to copy it to the local temp directory
      std::string tempname = get_temp_name();
      fileio::copy(soname, tempname);
      soname = tempname;
    }
    if (!file_contains_substring(soname, "get_toolkit_function_registration") &&
        !file_contains_substring(soname, "get_toolkit_class_registration")) {
      return soname + " is not a valid extension";
    }



    // get the base name of the shared library (without the .so)
    std::string modulename = fileio::get_filename(regentry.original_soname);
    std::vector<std::string> split_names;
    boost::algorithm::split(split_names, modulename, boost::is_any_of("."));
    if (split_names.size() == 0) return "Invalid filename";
    if (module_subpath.empty()) {
      regentry.modulename = split_names[0];
    } else if (module_subpath == "..") {
      regentry.modulename = "";
    } else {
      regentry.modulename = module_subpath + "." + split_names[0];
    }

    // goody. now for the dl loading
#ifndef _WIN32
    void* dl = dlopen(soname.c_str(), RTLD_NOW | RTLD_LOCAL);
#else
    void *dl = (void *)LoadLibrary(soname.c_str());
#endif
    logstream(LOG_INFO) << "Library load of " << sanitize_url(soname) << std::endl;
    regentry.effective_soname = soname;
    regentry.dl = dl;
    // check for failure
    if (dl == NULL) {
#ifndef _WIN32
      char* err = dlerror();
      // I think we need to copy this out early
      std::string ret = err;
      logstream(LOG_ERROR) << "Unable to load " << sanitize_url(soname) << ": " << ret << std::endl;
      if (err) return ret;
      else return "dlopen failed due to an unknown error";
#else
      std::string ret = get_last_err_str(GetLastError());
      logstream(LOG_ERROR) << "Unable to load " << sanitize_url(soname) << ": " << ret << std::endl;
      if (!ret.empty()) return ret;
      else return "LoadLibrary failed due to an unknown error";
#endif
    }

  /**************************************************************************/
  /*                                                                        */
  /*                         Function Registration                          */
  /*                                                                        */
  /**************************************************************************/
    // get the registration symbols
    std::vector<std::string> toolkit_function_reg_names
                {"get_toolkit_function_registration",
                  "_Z33get_toolkit_function_registrationv",
                  "__Z33get_toolkit_function_registrationv"};

    get_toolkit_function_registration_type get_toolkit_function_registration = nullptr;
    for (auto reg_name : toolkit_function_reg_names) {
      get_toolkit_function_registration =
          reinterpret_cast<get_toolkit_function_registration_type>
          (
#ifndef _WIN32
           dlsym(dl, reg_name.c_str())
#else
           (void *)GetProcAddress((HMODULE)dl, reg_name.c_str())
#endif
           );
      if (get_toolkit_function_registration != nullptr) break;
    }

    // register functions
    if (get_toolkit_function_registration) {
      auto functions = (*get_toolkit_function_registration)();
      for (auto& fn: functions) {
        if (!regentry.modulename.empty()) {
          fn.name = regentry.modulename + "." + fn.name;
        }
        fn.description["file"] = regentry.original_soname;
        logstream(LOG_INFO) << "Adding function: " << fn.name << std::endl;
        regentry.functions.push_back(fn.name);
      }
      toolkit_functions->register_toolkit_function(functions);
    }

/**************************************************************************/
/*                                                                        */
/*                           Class Registration                           */
/*                                                                        */
/**************************************************************************/

    std::vector<std::string> toolkit_class_reg_names
                {"get_toolkit_class_registration",
                 "_Z30get_toolkit_class_registrationv",
                 "__Z30get_toolkit_class_registrationv"};
    get_toolkit_class_registration_type get_toolkit_class_registration = nullptr;
    for (auto reg_name : toolkit_class_reg_names) {
      get_toolkit_class_registration =
          reinterpret_cast<get_toolkit_class_registration_type>
          (
#ifndef _WIN32
           dlsym(dl, reg_name.c_str())
#else
           (void *)GetProcAddress((HMODULE)dl, reg_name.c_str())
#endif
           );
      if (get_toolkit_class_registration != nullptr) break;
    }

    // register classes
    if (get_toolkit_class_registration) {
      auto class_reg = (*get_toolkit_class_registration)();
      for (auto& cl: class_reg) {
        if (!regentry.modulename.empty()) {
          cl.name = regentry.modulename + "." + cl.name;
        }
        cl.description["file"] = regentry.original_soname;
        logstream(LOG_INFO) << "Adding class : " << cl.name << std::endl;
        regentry.functions.push_back(cl.name);
      }
      classes->register_toolkit_class(class_reg);
    }


    if (regentry.functions.empty() && regentry.classes.empty()) {
      // nothing has been registered! unload the dl
#ifndef _WIN32
      dlclose(dl);
#else
      FreeLibrary((HMODULE)dl);
#endif
      return "No functions or classes registered by " + sanitize_url(soname);
    }
    // note that it is possible to load a toolkit multiple times.
    // It is not safe to unload previously loaded toolkits since I may have
    // a reference to it (for instance a class). We just keep loading over
    // and hope for the best.

    // store and remember the dlhandle and what was registered;
    dynamic_loaded_toolkits[regentry.original_soname] = regentry;
    return std::string();
  }
int uv__set_process_title(const char* title) {
#if TARGET_OS_IPHONE
  return uv__pthread_setname_np(title);
#else
  CFStringRef (*pCFStringCreateWithCString)(CFAllocatorRef,
                                            const char*,
                                            CFStringEncoding);
  CFBundleRef (*pCFBundleGetBundleWithIdentifier)(CFStringRef);
  void *(*pCFBundleGetDataPointerForName)(CFBundleRef, CFStringRef);
  void *(*pCFBundleGetFunctionPointerForName)(CFBundleRef, CFStringRef);
  CFTypeRef (*pLSGetCurrentApplicationASN)(void);
  OSStatus (*pLSSetApplicationInformationItem)(int,
                                               CFTypeRef,
                                               CFStringRef,
                                               CFStringRef,
                                               CFDictionaryRef*);
  void* application_services_handle;
  void* core_foundation_handle;
  CFBundleRef launch_services_bundle;
  CFStringRef* display_name_key;
  CFDictionaryRef (*pCFBundleGetInfoDictionary)(CFBundleRef);
  CFBundleRef (*pCFBundleGetMainBundle)(void);
  CFBundleRef hi_services_bundle;
  OSStatus (*pSetApplicationIsDaemon)(int);
  CFDictionaryRef (*pLSApplicationCheckIn)(int, CFDictionaryRef);
  void (*pLSSetApplicationLaunchServicesServerConnectionStatus)(uint64_t,
                                                                void*);
  CFTypeRef asn;
  int err;

  err = UV_ENOENT;
  application_services_handle = dlopen("/System/Library/Frameworks/"
                                       "ApplicationServices.framework/"
                                       "Versions/A/ApplicationServices",
                                       RTLD_LAZY | RTLD_LOCAL);
  core_foundation_handle = dlopen("/System/Library/Frameworks/"
                                  "CoreFoundation.framework/"
                                  "Versions/A/CoreFoundation",
                                  RTLD_LAZY | RTLD_LOCAL);

  if (application_services_handle == NULL || core_foundation_handle == NULL)
    goto out;

  *(void **)(&pCFStringCreateWithCString) =
      dlsym(core_foundation_handle, "CFStringCreateWithCString");
  *(void **)(&pCFBundleGetBundleWithIdentifier) =
      dlsym(core_foundation_handle, "CFBundleGetBundleWithIdentifier");
  *(void **)(&pCFBundleGetDataPointerForName) =
      dlsym(core_foundation_handle, "CFBundleGetDataPointerForName");
  *(void **)(&pCFBundleGetFunctionPointerForName) =
      dlsym(core_foundation_handle, "CFBundleGetFunctionPointerForName");

  if (pCFStringCreateWithCString == NULL ||
      pCFBundleGetBundleWithIdentifier == NULL ||
      pCFBundleGetDataPointerForName == NULL ||
      pCFBundleGetFunctionPointerForName == NULL) {
    goto out;
  }

#define S(s) pCFStringCreateWithCString(NULL, (s), kCFStringEncodingUTF8)

  launch_services_bundle =
      pCFBundleGetBundleWithIdentifier(S("com.apple.LaunchServices"));

  if (launch_services_bundle == NULL)
    goto out;

  *(void **)(&pLSGetCurrentApplicationASN) =
      pCFBundleGetFunctionPointerForName(launch_services_bundle,
                                         S("_LSGetCurrentApplicationASN"));

  if (pLSGetCurrentApplicationASN == NULL)
    goto out;

  *(void **)(&pLSSetApplicationInformationItem) =
      pCFBundleGetFunctionPointerForName(launch_services_bundle,
                                         S("_LSSetApplicationInformationItem"));

  if (pLSSetApplicationInformationItem == NULL)
    goto out;

  display_name_key = pCFBundleGetDataPointerForName(launch_services_bundle,
                                                    S("_kLSDisplayNameKey"));

  if (display_name_key == NULL || *display_name_key == NULL)
    goto out;

  *(void **)(&pCFBundleGetInfoDictionary) = dlsym(core_foundation_handle,
                                     "CFBundleGetInfoDictionary");
  *(void **)(&pCFBundleGetMainBundle) = dlsym(core_foundation_handle,
                                 "CFBundleGetMainBundle");
  if (pCFBundleGetInfoDictionary == NULL || pCFBundleGetMainBundle == NULL)
    goto out;

  /* Black 10.9 magic, to remove (Not responding) mark in Activity Monitor */
  hi_services_bundle =
      pCFBundleGetBundleWithIdentifier(S("com.apple.HIServices"));
  err = UV_ENOENT;
  if (hi_services_bundle == NULL)
    goto out;

  *(void **)(&pSetApplicationIsDaemon) = pCFBundleGetFunctionPointerForName(
      hi_services_bundle,
      S("SetApplicationIsDaemon"));
  *(void **)(&pLSApplicationCheckIn) = pCFBundleGetFunctionPointerForName(
      launch_services_bundle,
      S("_LSApplicationCheckIn"));
  *(void **)(&pLSSetApplicationLaunchServicesServerConnectionStatus) =
      pCFBundleGetFunctionPointerForName(
          launch_services_bundle,
          S("_LSSetApplicationLaunchServicesServerConnectionStatus"));
  if (pSetApplicationIsDaemon == NULL ||
      pLSApplicationCheckIn == NULL ||
      pLSSetApplicationLaunchServicesServerConnectionStatus == NULL) {
    goto out;
  }

  if (pSetApplicationIsDaemon(1) != noErr)
    goto out;

  pLSSetApplicationLaunchServicesServerConnectionStatus(0, NULL);

  /* Check into process manager?! */
  pLSApplicationCheckIn(-2,
                        pCFBundleGetInfoDictionary(pCFBundleGetMainBundle()));

  asn = pLSGetCurrentApplicationASN();

  err = UV_EINVAL;
  if (pLSSetApplicationInformationItem(-2,  /* Magic value. */
                                       asn,
                                       *display_name_key,
                                       S(title),
                                       NULL) != noErr) {
    goto out;
  }

  uv__pthread_setname_np(title);  /* Don't care if it fails. */
  err = 0;

out:
  if (core_foundation_handle != NULL)
    dlclose(core_foundation_handle);

  if (application_services_handle != NULL)
    dlclose(application_services_handle);

  return err;
#endif  /* !TARGET_OS_IPHONE */
}
Exemple #9
0
/*
 * Class:     sun_awt_X11SurfaceData
 * Method:    initIDs
 * Signature: ()V
 */
JNIEXPORT void JNICALL
Java_sun_awt_X11SurfaceData_initIDs(JNIEnv *env, jclass xsd, jclass XORComp)
{
#ifndef HEADLESS
    void *lib = 0;

    union {
        char c[4];
        int i;
    } endian;
    
    endian.i = 0xff000000;
    nativeByteOrder = (endian.c[0]) ? MSBFirst : LSBFirst;

    cachedXImage = NULL;

    if (sizeof(X11RIPrivate) > SD_RASINFO_PRIVATE_SIZE) {
	JNU_ThrowInternalError(env, "Private RasInfo structure too large!");
	return;
    }

    xorCompClass = (*env)->NewGlobalRef(env, XORComp);

    if (getenv("NO_J2D_DGA") == NULL) {
    /* we use RTLD_NOW because of bug 4032715 */
#ifdef DEBUG
        lib = dlopen("libsunwjdga_g.so", RTLD_NOW);
#else
        lib = dlopen("libsunwjdga.so", RTLD_NOW);
#endif
    }
    dgaAvailable = JNI_FALSE;
    if (lib != NULL) {
	JDgaStatus ret = JDGA_FAILED;
	void *sym = dlsym(lib, "JDgaLibInit");
	if (sym != NULL) {
	    theJDgaInfo.display = awt_display;
	    AWT_LOCK();
	    ret = (*(JDgaLibInitFunc *)sym)(env, &theJDgaInfo);
	    AWT_UNLOCK();
	}
	if (ret == JDGA_SUCCESS) {
	    pJDgaInfo = &theJDgaInfo;
	    dgaAvailable = JNI_TRUE;
	    useDGAWithPixmaps = (getenv("USE_DGA_PIXMAPS") != NULL);
	} else {
	    dlclose(lib);
	    lib = NULL;
	}
    }

#ifdef MITSHM
    if (getenv("NO_AWT_MITSHM") == NULL && 
	getenv("NO_J2D_MITSHM") == NULL) {
	char * force;
	TryInitMITShm(env, &useMitShmExt, &useMitShmPixmaps);
	useMitShmPixmaps = (useMitShmPixmaps == CAN_USE_MITSHM);
	force = getenv("J2D_PIXMAPS");
	if (force != NULL) {
	    if (strcmp(force, "shared") == 0) {
		forceSharedPixmaps = JNI_TRUE;
	    } else if (strcmp(force, "server") == 0) {
		useMitShmPixmaps = JNI_FALSE;
	    }
	}
    }
#endif /* MITSHM */

#endif /* !HEADLESS */
}
Exemple #10
0
plugin_err_t
plugin_load_from_file(plugin_handle_t *p, const char *fq_path)
{
	plugin_handle_t plug;
	int (*init)(void);
	uint32_t *version;
	char *type = NULL;

	*p = PLUGIN_INVALID_HANDLE;

	/*
	 *  Check for file existence and access permissions
	 */
	if (access(fq_path, R_OK) < 0) {
		if (errno == ENOENT)
			return EPLUGIN_NOTFOUND;
		else
			return EPLUGIN_ACCESS_ERROR;
	}

	/*
	 * Try to open the shared object.
	 *
	 * Use RTLD_LAZY to allow plugins to use symbols that may be
	 * defined in only one slurm entity (e.g. srun and not slurmd),
	 * when the use of that symbol is restricted to within the
	 * entity from which it is available. (i.e. srun symbols are only
	 * used in the context of srun, not slurmd.)
	 *
	 */
	plug = dlopen(fq_path, RTLD_LAZY);
	if (plug == NULL) {
		error("plugin_load_from_file: dlopen(%s): %s",
		      fq_path,
		      _dlerror());
		return EPLUGIN_DLOPEN_FAILED;
	}

	/* Now see if our required symbols are defined. */
	if ((dlsym(plug, PLUGIN_NAME) == NULL) ||
	    ((type = dlsym(plug, PLUGIN_TYPE)) == NULL)) {
		dlclose(plug);
		return EPLUGIN_MISSING_NAME;
	}

	version = (uint32_t *) dlsym(plug, PLUGIN_VERSION);
	if (!version) {
		verbose("%s: plugin_version symbol not defined", fq_path);
	} else if ((*version != SLURM_VERSION_NUMBER) && xstrcmp(type,"spank")){
		/* NOTE: We could alternatly test just the MAJOR.MINOR values */
		int plugin_major, plugin_minor, plugin_micro;
		plugin_major = SLURM_VERSION_MAJOR(*version);
		plugin_minor = SLURM_VERSION_MINOR(*version);
		plugin_micro = SLURM_VERSION_MICRO(*version);
		dlclose(plug);
		info("%s: Incompatible Slurm plugin version (%d.%d.%d)",
		     fq_path, plugin_major, plugin_minor, plugin_micro);
		return EPLUGIN_BAD_VERSION;
	}

	/*
	 * Now call its init() function, if present.  If the function
	 * returns nonzero, unload the plugin and signal an error.
	 */
	if ((init = dlsym(plug, "init")) != NULL) {
		if ((*init)() != 0) {
			dlclose(plug);
			return EPLUGIN_INIT_FAILED;
		}
	}

	*p = plug;
	return EPLUGIN_SUCCESS;
}
Exemple #11
0
/*
 * Function
 *	linuxModInfoDir
 *
 * Description
 *	Retrieve info about the modules whose shared library files are contained in a given directory
 *	(for each shared library, load it, retrieve info about the module (tModInfo struct),
 *	 and finally unload the library).
 *
 * Parameters
 *	dir	(in)     directory to search (relative)
 *	level   (in)     if 1, load any shared library contained in the subdirs of dir
 *	                 and whose name is the same as the containing subdir (ex: bt/bt.so)
 *	                 if 0, load any shared library contained in dir (ignore subdirs)
 *	modlist	(in/out) list of module description structure (may begin empty)
 *
 * Return
 *	>=0	number of modules loaded
 *	-1	error
 *
 * Remarks
 *	The loaded module info structures are added in the list according to each module's priority
 *	(NOT at the head of the list).
 *	
 */
static int
linuxModInfoDir(unsigned int /* gfid */, const char *dir, int level, tModList **modlist)
{
	char		 sopath[256];	/* path of the lib[x].so */
	tSOHandle		 handle;
	DIR			*dp;
	struct dirent	*ep;
	int			 modnb;		/* number on loaded modules */
	tModList		*curMod;
	
	modnb = 0;
	
	/* open the current directory */
	dp = opendir(dir);
	if (dp)
	{
		/* some files in it */
		while ((ep = readdir (dp)) != 0) 
		{
			if (((strlen(ep->d_name) > 4) && 
				 (strcmp(".so", ep->d_name+strlen(ep->d_name)-3) == 0)) /* xxxx.so */
				|| ((level == 1) && (ep->d_name[0] != '.')))
			{
				if (level == 1)
					sprintf(sopath, "%s/%s/%s.so", dir, ep->d_name, ep->d_name);
				else
					sprintf(sopath, "%s/%s", dir, ep->d_name);
				
				/* Try and avoid loading the same module twice (WARNING: Only checks sopath equality !) */
				if (!GfModIsInList(sopath, *modlist))
				{
					/* Load the shared library */
					GfLogTrace("Querying module %s\n", sopath);
					handle = dlopen(sopath, RTLD_LAZY);
					if (handle)
					{
						/* Initialize the module */
						if (GfModInitialize(handle, sopath, GfIdAny, &curMod) == 0)
						{
							if (curMod) /* Retained against gfid */
							{
								/* Get associated info */
								modnb++;
								GfModAddInList(curMod, modlist, /* priosort */ 1);
							}
							
							/* Terminate the module */
							GfModTerminate(handle, sopath);
						}
						
						/* Close the shared library */
						dlclose(handle);
					} 
					else 
					{
						GfLogError("linuxModInfoDir: ...  %s\n", dlerror());
					}
				}
			}
		}
		(void)closedir(dp);
	} 
	else 
	{
		GfLogError("linuxModInfoDir: ... Couldn't open the directory %s.\n", dir);
		return -1;
	}
	
	return modnb;
}
Exemple #12
0
/* build NULL-terminated table of name + init-function */

typedef struct {
	const char* name;
	int (*plugin_init)(plugin *p);
} plugin_load_functions;

static const plugin_load_functions load_functions[] = {
#define PLUGIN_INIT(x) \
	{ #x, &x ## _plugin_init },

#include "plugin-static.h"

	{ NULL, NULL }
#undef PLUGIN_INIT
};

int plugins_load(server *srv) {
	plugin *p;
	size_t i, j;

	for (i = 0; i < srv->srvconf.modules->used; i++) {
		data_string *d = (data_string *)srv->srvconf.modules->data[i];
		char *module = d->value->ptr;

		for (j = 0; j < i; j++) {
			if (buffer_is_equal(d->value, ((data_string *) srv->srvconf.modules->data[j])->value)) {
				log_error_write(srv, __FILE__, __LINE__, "sbs",
					"Cannot load plugin", d->value,
					"more than once, please fix your config (lighttpd may not accept such configs in future releases)");
				continue;
			}
		}

		for (j = 0; load_functions[j].name; ++j) {
			if (0 == strcmp(load_functions[j].name, module)) {
				p = plugin_init();
				if ((*load_functions[j].plugin_init)(p)) {
					log_error_write(srv, __FILE__, __LINE__, "ss", module, "plugin init failed" );
					plugin_free(p);
					return -1;
				}
				plugins_register(srv, p);
				break;
			}
		}
		if (!load_functions[j].name) {
			log_error_write(srv, __FILE__, __LINE__, "ss", module, " plugin not found" );
			return -1;
		}
	}

	return 0;
}
#else /* defined(LIGHTTPD_STATIC) */
int plugins_load(server *srv) {
	plugin *p;
	int (*init)(plugin *pl);
	size_t i, j;

	for (i = 0; i < srv->srvconf.modules->used; i++) {
		data_string *d = (data_string *)srv->srvconf.modules->data[i];
		char *module = d->value->ptr;

		for (j = 0; j < i; j++) {
			if (buffer_is_equal(d->value, ((data_string *) srv->srvconf.modules->data[j])->value)) {
				log_error_write(srv, __FILE__, __LINE__, "sbs",
					"Cannot load plugin", d->value,
					"more than once, please fix your config (lighttpd may not accept such configs in future releases)");
				continue;
			}
		}

		buffer_copy_buffer(srv->tmp_buf, srv->srvconf.modules_dir);

		buffer_append_string_len(srv->tmp_buf, CONST_STR_LEN("/"));
		buffer_append_string(srv->tmp_buf, module);
#if defined(__WIN32) || defined(__CYGWIN__)
		buffer_append_string_len(srv->tmp_buf, CONST_STR_LEN(".dll"));
#else
		buffer_append_string_len(srv->tmp_buf, CONST_STR_LEN(".so"));
#endif

		p = plugin_init();
#ifdef __WIN32
		if (NULL == (p->lib = LoadLibrary(srv->tmp_buf->ptr))) {
			LPVOID lpMsgBuf;
			FormatMessage(
				FORMAT_MESSAGE_ALLOCATE_BUFFER |
					FORMAT_MESSAGE_FROM_SYSTEM,
				NULL,
				GetLastError(),
				MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
				(LPTSTR) &lpMsgBuf,
				0, NULL);

			log_error_write(srv, __FILE__, __LINE__, "ssb", "LoadLibrary() failed",
				lpMsgBuf, srv->tmp_buf);

			plugin_free(p);

			return -1;

		}
#else
		if (NULL == (p->lib = dlopen(srv->tmp_buf->ptr, RTLD_NOW|RTLD_GLOBAL))) {
			log_error_write(srv, __FILE__, __LINE__, "sbs", "dlopen() failed for:",
				srv->tmp_buf, dlerror());

			plugin_free(p);

			return -1;
		}

#endif
		buffer_reset(srv->tmp_buf);
		buffer_copy_string(srv->tmp_buf, module);
		buffer_append_string_len(srv->tmp_buf, CONST_STR_LEN("_plugin_init"));

#ifdef __WIN32
		init = GetProcAddress(p->lib, srv->tmp_buf->ptr);

		if (init == NULL) {
			LPVOID lpMsgBuf;
			FormatMessage(
				FORMAT_MESSAGE_ALLOCATE_BUFFER |
					FORMAT_MESSAGE_FROM_SYSTEM,
				NULL,
				GetLastError(),
				MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
				(LPTSTR) &lpMsgBuf,
				0, NULL);

			log_error_write(srv, __FILE__, __LINE__, "sbs", "getprocaddress failed:", srv->tmp_buf, lpMsgBuf);

			plugin_free(p);
			return -1;
		}

#else
#if 1
		init = (int (*)(plugin *))(intptr_t)dlsym(p->lib, srv->tmp_buf->ptr);
#else
		*(void **)(&init) = dlsym(p->lib, srv->tmp_buf->ptr);
#endif
		if (NULL == init) {
			const char *error = dlerror();
			if (error != NULL) {
				log_error_write(srv, __FILE__, __LINE__, "ss", "dlsym:", error);
			} else {
				log_error_write(srv, __FILE__, __LINE__, "ss", "dlsym symbol not found:", srv->tmp_buf->ptr);
			}

			plugin_free(p);
			return -1;
		}

#endif
		if ((*init)(p)) {
			log_error_write(srv, __FILE__, __LINE__, "ss", module, "plugin init failed" );

			plugin_free(p);
			return -1;
		}
#if 0
		log_error_write(srv, __FILE__, __LINE__, "ss", module, "plugin loaded" );
#endif
		plugins_register(srv, p);
	}

	return 0;
}
Exemple #13
0
/**************************************************************************
 * Name: LoadSharedLibrary
 *
 * Description: Load the library 
 *
 * Inputs:  library name
 *
 * Outputs: pointer to library loaded
 *
 * Returns:	SUUCESS/FAILURE
 ************************************************************************* */
int LoadSharedLibrary(const char* libName, void** libPointer, char* errstr)
{
  char fullLibName[50];
  char errormessage[200]; 
  int flags;
  int ret;
     
  ret = SUCCESS;
  fullLibName[0] = '\0';
  
  #if defined(WIN32) 
    sprintf(fullLibName, "%s.dll", libName);
  #else
    sprintf(fullLibName, "lib%s", libName);
  #endif
      
  #ifndef WIN32
  #if defined(SOLARIS) || defined(OSF1) || defined(_AIX) || defined(LINUX)
     strcat(fullLibName, ".so");
  #elif defined(HPUX)
     strcat(fullLibName, ".sl");
  #endif
  #endif
      
  strcpy(errormessage, "Loading ");
  strcat(errormessage, fullLibName);
  strcat(errormessage, " library FAILED ...");
   
  /* Load the library */
#if defined(WIN32)
  *libPointer = LoadLibrary(fullLibName);
  if (NULL == *libPointer)
    {
      strcpy(errstr, errormessage);
      /* emit(SHLIB_ERRLOC, MPS_GENERIC_DEBUG, errormessage); */
      return FAILURE;
    }
#elif defined(SOLARIS) || defined(OSF1) || defined(HPUX_64) || defined(_AIX) || defined(LINUX)
  *libPointer = dlopen( fullLibName, OPEN_MODE);
  if (NULL == *libPointer)
    {
      strcpy(errstr, errormessage);
      /* emit(SHLIB_ERRLOC, MPS_GENERIC_DEBUG, errormessage); */
      return FAILURE;
    }
#elif defined(HPUX)
  flags = OPEN_MODE;
  flags |= BIND_DEFERRED;
  *libPointer = shl_load( fullLibName, flags, 0L);
  if (NULL == *libPointer)
    {
      strcpy(errstr, errormessage);
      /* emit(SHLIB_ERRLOC, MPS_GENERIC_DEBUG, errormessage);  */
      return FAILURE;
    }
#else
#error SendToTHSlibLoader not defined for this platform you must define it now Load
#endif
    
  return ret;
  
}  
Exemple #14
0
    //==============================================================================
    void scanForDevices()
    {
        hasScanned = true;
        inputNames.clear();
        inputIds.clear();
        outputNames.clear();
        outputIds.clear();

        if (juce_libjackHandle == nullptr)
        {
            juce_libjackHandle = dlopen ("libjack.so", RTLD_LAZY);

            if (juce_libjackHandle == nullptr)
                return;
        }

        // open a dummy client
        jack_status_t status;
        jack_client_t* client = juce::jack_client_open ("JuceJackDummy", JackNoStartServer, &status);

        if (client == nullptr)
        {
            dumpJackErrorMessage (status);
        }
        else
        {
            // scan for output devices
            const char** ports = juce::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsOutput);

            if (ports != nullptr)
            {
                int j = 0;
                while (ports[j] != 0)
                {
                    String clientName (ports[j]);
                    clientName = clientName.upToFirstOccurrenceOf (":", false, false);

                    if (clientName != String (JUCE_JACK_CLIENT_NAME)
                         && ! inputNames.contains (clientName))
                    {
                        inputNames.add (clientName);
                        inputIds.add (ports [j]);
                    }

                    ++j;
                }

                free (ports);
            }

            // scan for input devices
            ports = juce::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsInput);

            if (ports != nullptr)
            {
                int j = 0;
                while (ports[j] != 0)
                {
                    String clientName (ports[j]);
                    clientName = clientName.upToFirstOccurrenceOf (":", false, false);

                    if (clientName != String (JUCE_JACK_CLIENT_NAME)
                         && ! outputNames.contains (clientName))
                    {
                        outputNames.add (clientName);
                        outputIds.add (ports [j]);
                    }

                    ++j;
                }

                free (ports);
            }

            juce::jack_client_close (client);
        }
    }
Exemple #15
0
int load_opus(char *name){
  void *lib;
  const char *msg;
  int *num=NULL;
  struct coreInfo_t **core;
  SPICEdev **devs;
  Evt_Udn_Info_t  **udns;
  funptr_t fetch;

  lib = dlopen(name,RTLD_NOW);
  if(!lib){
    msg = dlerror();
    printf("%s\n", msg);
    return 1;
  }
  
  fetch = dlsym(lib,"CMdevNum");
  if(fetch){
    num = ((int * (*)(void)) fetch) ();
#ifdef TRACE
    printf("Got %u devices.\n",*num);
#endif
  }else{
    msg = dlerror();
    printf("%s\n", msg);
    return 1;
  }

  fetch = dlsym(lib,"CMdevs");
  if(fetch){
    devs = ((SPICEdev ** (*)(void)) fetch) ();
  }else{
    msg = dlerror();
    printf("%s\n", msg);
    return 1;
  }

  fetch = dlsym(lib,"CMgetCoreItfPtr");
  if(fetch){
    core = ((struct coreInfo_t ** (*)(void)) fetch) ();
    *core = &coreInfo;
  }else{
    msg = dlerror();
    printf("%s\n", msg);
    return 1;
  }
  add_device(*num,devs,1);

  fetch = dlsym(lib,"CMudnNum");
  if(fetch){
    num = ((int * (*)(void)) fetch) ();
#ifdef TRACE
    printf("Got %u udns.\n",*num);
#endif
  }else{
    msg = dlerror();
    printf("%s\n", msg);
    return 1;
  }

  fetch = dlsym(lib,"CMudns");
  if(fetch){
    udns = ((Evt_Udn_Info_t  ** (*)(void)) fetch) ();
  }else{
    msg = dlerror();
    printf("%s\n", msg);
    return 1;
  }

  add_udn(*num,udns);

  return 0;
}
Exemple #16
0
 void UdfHandler::openUdfLibrary(const std::string & s)
 {
   this->M_lib_handle=dlopen(s.c_str(),RTLD_LAZY);
   if (!this->M_lib_handle)
     throw std::invalid_argument("Udf library " + s + " not found");
 }
Exemple #17
0
static void *ll_load (lua_State *L, const char *path) {
  void *lib = dlopen(path, RTLD_NOW);
  if (lib == NULL) lua_pushstring(L, dlerror());
  return lib;
}
Exemple #18
0
void context::load_module(v8::FunctionCallbackInfo<v8::Value> const& args)
{
	v8::Isolate* isolate = args.GetIsolate();

	v8::EscapableHandleScope scope(isolate);
	v8::Local<v8::Value> result;
	try
	{
		std::string const name = from_v8<std::string>(isolate, args[0], "");
		if (name.empty())
		{
			throw std::runtime_error("load_module: require module name string argument");
		}

		context* ctx = detail::get_external_data<context*>(args.Data());
		context::dynamic_modules::iterator it = ctx->modules_.find(name);

		// check if module is already loaded
		if (it != ctx->modules_.end())
		{
			result = v8::Local<v8::Value>::New(isolate, it->second.exports);
		}
		else
		{
			std::string filename = name;
			if (!ctx->lib_path_.empty())
			{
				filename = ctx->lib_path_ + path_sep + name;
			}
			std::string const suffix = V8PP_PLUGIN_SUFFIX;
			if (filename.size() >= suffix.size()
				&& filename.compare(filename.size() - suffix.size(), suffix.size(), suffix) != 0)
			{
				filename += suffix;
			}

			dynamic_module module;
#if defined(WIN32)
			UINT const prev_error_mode = SetErrorMode(SEM_NOOPENFILEERRORBOX);
			module.handle = LoadLibraryA(filename.c_str());
			::SetErrorMode(prev_error_mode);
#else
			module.handle = dlopen(filename.c_str(), RTLD_LAZY);
#endif

			if (!module.handle)
			{
				throw std::runtime_error("load_module(" + name + "): could not load shared library " + filename);
			}
#if defined(WIN32)
			void *sym = ::GetProcAddress((HMODULE)module.handle, STRINGIZE(V8PP_PLUGIN_INIT_PROC_NAME));
#else
			void *sym = dlsym(module.handle, STRINGIZE(V8PP_PLUGIN_INIT_PROC_NAME));
#endif
			if (!sym)
			{
				throw std::runtime_error("load_module(" + name + "): initialization function "
					STRINGIZE(V8PP_PLUGIN_INIT_PROC_NAME) " not found in " + filename);
			}

			using module_init_proc = v8::Handle<v8::Value>(*)(v8::Isolate*);
			module_init_proc init_proc = reinterpret_cast<module_init_proc>(sym);
			result = init_proc(isolate);
			module.exports.Reset(isolate, result);
			ctx->modules_.emplace(name, std::move(module));
		}
	}
	catch (std::exception const& ex)
	{
		result = throw_ex(isolate, ex.what());
	}
	args.GetReturnValue().Set(scope.Escape(result));
}
Exemple #19
0
static void* mydlopen(const char *filename, int flag) {
    char *buf;
    const char *end, *start, *ladspapath;
    int endsinso, needslash;
    size_t filenamelen;
    void *result = NULL;

#if defined(__MINGW32__) || defined(__CYGWIN__)
    /* For Windows there's only absolute path support.
     * If you have a Windows machine, feel free to fix this.
     * (path separator, shared objects extension, et cetera). */
        mp_msg(MSGT_AFILTER, MSGL_V, "\ton windows, only absolute pathnames "
                "are supported\n");
        mp_msg(MSGT_AFILTER, MSGL_V, "\ttrying %s\n", filename);
        return dlopen(filename, flag);
#endif

    filenamelen = strlen(filename);

    endsinso = 0;
    if (filenamelen > 3)
        endsinso = (strcmp(filename+filenamelen-3, ".so") == 0);
    if (!endsinso) {
        buf=malloc(filenamelen+4);
        strcpy(buf, filename);
        strcat(buf, ".so");
        result=mydlopen(buf, flag);
        free(buf);
    }

    if (result)
        return result;

    ladspapath=getenv("LADSPA_PATH");

    if (ladspapath) {

        start=ladspapath;
        while (*start != '\0') {
            end=start;
            while ( (*end != ':') && (*end != '\0') )
                end++;

            buf=malloc(filenamelen + 2 + (end-start) );
            if (end > start)
                strncpy(buf, start, end-start);
            needslash=0;
            if (end > start)
                if (*(end-1) != '/') {
                    needslash = 1;
                    buf[end-start] = '/';
                }
            strcpy(buf+needslash+(end-start), filename);

            mp_msg(MSGT_AFILTER, MSGL_V, "\ttrying %s\n", buf);
            result=dlopen(buf, flag);

            free(buf);
            if (result)
                return result;

            start = end;
            if (*start == ':')
                start++;
        } /* end while there's still more in the path */
    } /* end if there's a ladspapath */

    /* last resort, just open it again, so the dlerror() message is correct */
    mp_msg(MSGT_AFILTER, MSGL_V, "\ttrying %s\n", filename);
    return dlopen(filename,flag);
}
Exemple #20
0
static int loadpng() {
    /* Oops someone might have libpng without libz. If we try to load libpng */
    /*  first we crash and burn horribly, so... */
    if ( dlopen("libz" SO_EXT,RTLD_GLOBAL|RTLD_LAZY)==NULL
#ifdef SO_1_EXT
	    && dlopen("libz" SO_1_EXT,RTLD_LAZY)==NULL
#endif
	    ) {
	fprintf(stderr,"%s\n", dlerror());
return( 0 );
    }
#  if !defined(PNG_LIBPNG_VER_MAJOR) || (PNG_LIBPNG_VER_MAJOR==1 && PNG_LIBPNG_VER_MINOR<2)
/* Early versions are called libpng. Later libpng10/libpng12/libpng14... */
    libpng = dlopen("libpng" SO_EXT,RTLD_LAZY);
#    ifdef SO_2_EXT
    if ( libpng==NULL )
	libpng = dlopen("libpng" SO_2_EXT,RTLD_LAZY);
#    endif
#  else		/* After version 1.2.1 (I think) dynamic libpng is called libpng12/libpng14... */
#    define xstr(s) str(s)
#    define str(s) #s
#    define PNGLIBNAME	"libpng" xstr(PNG_LIBPNG_VER_MAJOR) xstr(PNG_LIBPNG_VER_MINOR)
    libpng = dlopen(PNGLIBNAME SO_EXT,RTLD_LAZY);
#    ifdef SO_0_EXT
    if ( libpng==NULL )
	libpng = dlopen(PNGLIBNAME SO_0_EXT,RTLD_LAZY);
#    endif
    if ( libpng==NULL ) {
	libpng = dlopen("libpng" SO_EXT,RTLD_LAZY);
#    ifdef SO_2_EXT
	if ( libpng==NULL )
	    libpng = dlopen("libpng" SO_2_EXT,RTLD_LAZY);
#    endif
    }
#  endif
    if ( libpng==NULL ) {
	fprintf(stderr,"%s", dlerror());
return( 0 );
    }
    _png_create_write_struct = (png_structp (*)(char *, png_voidp, png_error_ptr, png_error_ptr))
	    dlsym(libpng,"png_create_write_struct");
    _png_create_info_struct = (png_infop (*)(png_structp))
	    dlsym(libpng,"png_create_info_struct");
    _png_destroy_write_struct = (void (*)(png_structpp, png_infopp))
	    dlsym(libpng,"png_destroy_write_struct");
    _png_init_io = (void (*)(png_structp, FILE *))
	    dlsym(libpng,"png_init_io");
    _png_write_info = (void (*)(png_structp, png_infop))
	    dlsym(libpng,"png_write_info");
    _png_set_packing = (void (*)(png_structp))
	    dlsym(libpng,"png_set_packing");
    _png_set_filler = (void (*)(png_structp,png_uint_32,int))
	    dlsym(libpng,"png_set_filler");
    _png_write_image = (void (*)(png_structp,png_bytep*))
	    dlsym(libpng,"png_write_image");
    _png_write_end = (void (*)(png_structp,png_infop))
	    dlsym(libpng,"png_write_end");
#if (PNG_LIBPNG_VER >= 10500)
    _png_longjmp = (void (*)(png_structp, int))
	    dlsym(libpng,"png_longjmp");
    _png_set_longjmp_fn = (jmp_buf* (*)(png_structp,png_longjmp_ptr,size_t))
	    dlsym(libpng,"png_set_longjmp_fn");
#endif
    _png_set_IHDR = (void (*)(png_structp,png_infop,png_uint_32,png_uint_32,int,int,int,int,int))
	    dlsym(libpng,"png_set_IHDR");
    _png_set_PLTE = (void (*)(png_structp,png_infop,png_colorp,int))
	    dlsym(libpng,"png_set_PLTE");
    _png_set_tRNS = (void (*)(png_structp,png_infop,png_bytep,int,png_color_16p))
	    dlsym(libpng,"png_set_tRNS");
    if ( _png_create_write_struct && _png_create_info_struct && _png_destroy_write_struct &&
	    _png_init_io && _png_set_filler && _png_write_info && _png_set_packing &&
	    _png_write_image && _png_write_end)
return( 1 );
    dlclose(libpng);
    fprintf(stderr,"%s", dlerror());
return( 0 );
}
Exemple #21
0
int dl_dcli_init(boot_flag)
{

	void (*dcli_init_func)(int); /*dcli_main*/
	/***************sem*************/ 
	void (*dcli_sem_init_func)(void);
	void (*dcli_fpga_init_func)(void);
	/***************npd*************/
	void (*dcli_diag_init_func)(void);
	void (*dcli_vlan_init_func)(void);
	void (*dcli_trunk_init_func)(void);
	void (*dcli_dynamic_trunk_init_func)(void);
	void (*dcli_fdb_init_func)(void);
	void (*dcli_qos_init_func)(void);
	void (*dcli_acl_init_func)(void);
	void (*dcli_stp_element_init_func)(void);
	void (*dcli_drv_routesyn_init_func)(void);
	void (*dcli_tunnel_init_func)(void);
	void (*dcli_pvlan_init_func)(void);
	void (*dcli_prot_vlan_element_init_func)(void);
	void (*dcli_igmp_snp_element_init_func)(void);
	void (*dcli_mld_snp_element_init_func)(void);
	void (*dcli_mirror_init_func)(void);
	/*************asd****************/
	void (*dcli_sta_init_func)(void);
	void (*dcli_security_init_func)(void);
	/************wid******************/
	void (*dcli_wtp_init_func)(void);
	void (*dcli_radio_init_func)(void);
	void (*dcli_ac_init_func)(void);
	void (*dcli_wlan_init_func)(void);
	void (*dcli_ebr_init_func)(void); 
	void (*dcli_aciplist_init_func)(void);
	void (*dcli_ac_group_init_func)(void);
    void (*dcli_ap_group_init_func)(void);
	void (*dcli_bsd_init_func)(void);
	void (*dcli_license_init_func)(void);
	void (*dcli_wbridge_init_func)(void);
	void (*dcli_scanlocate_init_func)(void);
	
	char *error;
	int temp=boot_flag;

/***********************dcli_main********************/
	dcli_dl_handle = dlopen("libdcli.so.0",RTLD_NOW);
	if (!dcli_dl_handle) {
		fputs (dlerror(),stderr);
		printf(" Run without /opt/lib/libdcli.so.0\n");
		EXIT(1);

	}
	dcli_init_func = dlsym(dcli_dl_handle,"dcli_init");
	if ((error = dlerror()) != NULL) {
		printf(" Run without dcli_init be called.\n");
		fputs(error,stderr);
		EXIT(1);
	}
	(*dcli_init_func)(temp);


/***********************dcli_sem**********************/

	if (dcli_dl_handle_sem = dlopen("libdcli_sem.so",RTLD_NOW)){

		dcli_sem_init_func = dlsym(dcli_dl_handle_sem,"dcli_sem_init");
		if ((error = dlerror()) != NULL) {
			printf(" Run without dcli_sem_init be called.\n");
			fputs(error,stderr);
			//EXIT(1);
		} 
		else 
		{
			(*dcli_sem_init_func)(); 
		}

		dcli_fpga_init_func = dlsym(dcli_dl_handle_sem,"dcli_fpga_init");
		if ((error = dlerror()) != NULL) {
			printf(" Run without dcli_fpga_init be called.\n");
			fputs(error,stderr);
			//EXIT(1);
		} 
		else 
		{
			(*dcli_fpga_init_func)(); 
		}

	}
	else 
	{
		fputs (dlerror(),stderr);
		printf(" Run without /opt/lib/libdcli_sem.so\n");
	}
#ifndef _D_NANOCELL_
/*******************dcli_npd****************************/
	if (dcli_dl_handle_npd = dlopen("libdcli_npd.so",RTLD_NOW)){

		dcli_diag_init_func = dlsym(dcli_dl_handle_npd,"dcli_diag_init");
		if ((error = dlerror()) != NULL) 
		{
			printf(" Run without dcli_diag_init be called.\n");
			fputs(error,stderr);
		} 
		else 
		{
			(*dcli_diag_init_func)(); 
		}


		dcli_vlan_init_func = dlsym(dcli_dl_handle_npd,"dcli_vlan_init");
		if ((error = dlerror()) != NULL) {
			printf(" Run without dcli_vlan_init be called.\n");
			fputs(error,stderr);
		} 
		else 
		{
			(*dcli_vlan_init_func)(); 
		}


		dcli_trunk_init_func = dlsym(dcli_dl_handle_npd,"dcli_trunk_init");
		if ((error = dlerror()) != NULL) {
			printf(" Run without dcli_trunk_init be called.\n");
			fputs(error,stderr);
		} 
		else 
		{
			(*dcli_trunk_init_func)(); 
		}


		dcli_dynamic_trunk_init_func = dlsym(dcli_dl_handle_npd,"dcli_dynamic_trunk_init");
		if ((error = dlerror()) != NULL) {
			printf(" Run without dcli_dynamic_trunk_init be called.\n");
			fputs(error,stderr);
		} 
		else 
		{
			(*dcli_dynamic_trunk_init_func)(); 
		}

		dcli_fdb_init_func = dlsym(dcli_dl_handle_npd,"dcli_fdb_init");
		if ((error = dlerror()) != NULL) {
			printf(" Run without dcli_fdb_init be called.\n");
			fputs(error,stderr);
		} 
		else 
		{
			(*dcli_fdb_init_func)(); 
		}

		dcli_qos_init_func = dlsym(dcli_dl_handle_npd,"dcli_qos_init");
		if ((error = dlerror()) != NULL) {
			printf(" Run without dcli_qos_init be called.\n");
			fputs(error,stderr);
		} 
		else 
		{
			(*dcli_qos_init_func)(); 
		}

		dcli_acl_init_func = dlsym(dcli_dl_handle_npd,"dcli_acl_init");
		if ((error = dlerror()) != NULL) {
			printf(" Run without dcli_acl_init be called.\n");
			fputs(error,stderr);
		} 
		else 
		{
			(*dcli_acl_init_func)(); 
		}

		dcli_stp_element_init_func = dlsym(dcli_dl_handle_npd,"dcli_stp_element_init");
		if ((error = dlerror()) != NULL) {
			printf(" Run without dcli_stp_element_init be called.\n");
			fputs(error,stderr);
		} 
		else 
		{
			(*dcli_stp_element_init_func)(); 
		}

		dcli_drv_routesyn_init_func = dlsym(dcli_dl_handle_npd,"dcli_drv_routesyn_init");
		if ((error = dlerror()) != NULL) {
			printf(" Run without dcli_drv_routesyn_init_func be called.\n");
			fputs(error,stderr);
		} 
		else 
		{
			(*dcli_drv_routesyn_init_func)(); 
		}

		dcli_tunnel_init_func = dlsym(dcli_dl_handle_npd,"dcli_tunnel_init");
		if ((error = dlerror()) != NULL) {
			printf(" Run without dcli_tunnel_init_func be called.\n");
			fputs(error,stderr);
		} 
		else 
		{
			(*dcli_tunnel_init_func)(); 
		}

		dcli_pvlan_init_func = dlsym(dcli_dl_handle_npd,"dcli_pvlan_init");
		if ((error = dlerror()) != NULL) {
			printf(" Run without dcli_pvlan_init_func be called.\n");
			fputs(error,stderr);
		} 
		else 
		{
			(*dcli_pvlan_init_func)(); 
		}

		dcli_prot_vlan_element_init_func = dlsym(dcli_dl_handle_npd,"dcli_prot_vlan_element_init");
		if ((error = dlerror()) != NULL) {
			printf(" Run without dcli_prot_vlan_element_init_func be called.\n");
			fputs(error,stderr);
		} 
		else 
		{
			(*dcli_prot_vlan_element_init_func)(); 
		}	

		dcli_igmp_snp_element_init_func = dlsym(dcli_dl_handle_npd,"dcli_igmp_snp_element_init");
		if ((error = dlerror()) != NULL) {
			printf(" Run without dcli_igmp_snp_element_init_func be called.\n");
			fputs(error,stderr);
		} 
		else 
		{
			(*dcli_igmp_snp_element_init_func)(); 
		}	


		dcli_mld_snp_element_init_func = dlsym(dcli_dl_handle_npd,"dcli_mld_snp_element_init");
		if ((error = dlerror()) != NULL) {
			printf(" Run without dcli_mld_snp_element_init_func be called.\n");
			fputs(error,stderr);
		} 
		else 
		{
			(*dcli_mld_snp_element_init_func)(); 
		}	

		dcli_mirror_init_func = dlsym(dcli_dl_handle_npd,"dcli_mirror_init");
		if ((error = dlerror()) != NULL) {
			printf(" Run without dcli_mirror_init_func be called.\n");
			fputs(error,stderr);
		} 
		else 
		{
			(*dcli_mirror_init_func)(); 
		}


	}
	else 
	{
		fputs (dlerror(),stderr);
		printf(" Run without /opt/lib/libdcli_npd.so\n");
	}
#endif

/*******************dcli_asd****************************/

	if (dcli_dl_handle_asd = dlopen("libdcli_asd.so",RTLD_NOW)){

		dcli_sta_init_func = dlsym(dcli_dl_handle_asd,"dcli_sta_init");
		if ((error = dlerror()) != NULL) {
			printf(" Run without dcli_sta_init be called.\n");
			fputs(error,stderr);
			//EXIT(1);
		} 
		else 
		{
			(*dcli_sta_init_func)(); 
		}


		dcli_security_init_func = dlsym(dcli_dl_handle_asd,"dcli_security_init");
		if ((error = dlerror()) != NULL) {
			printf(" Run without dcli_security_init be called.\n");
			fputs(error,stderr);
			//EXIT(1);
		} 
		else 
		{
			(*dcli_security_init_func)(); 
		}

	}
	else 
	{
		fputs (dlerror(),stderr);
		printf(" Run without /opt/lib/libdcli_sta.so\n");
	}


/*******************dcli_wid************************************/

	if (dcli_dl_handle_wid = dlopen("libdcli_wid.so",RTLD_NOW)){

		dcli_wtp_init_func = dlsym(dcli_dl_handle_wid,"dcli_wtp_init");
		if ((error = dlerror()) != NULL) {
			printf(" Run without dcli_wtp_init be called.\n");
			fputs(error,stderr);
		} 
		else 
		{
			(*dcli_wtp_init_func)(); 
		}


		dcli_radio_init_func = dlsym(dcli_dl_handle_wid,"dcli_radio_init");
		if ((error = dlerror()) != NULL) {
			printf(" Run without dcli_radio_init be called.\n");
			fputs(error,stderr);
		} 
		else 
		{
			(*dcli_radio_init_func)(); 
		}

		dcli_ac_init_func = dlsym(dcli_dl_handle_wid,"dcli_ac_init");
		if ((error = dlerror()) != NULL) {
			printf(" Run without dcli_ac_init be called.\n");
			fputs(error,stderr);
		} 
		else 
		{
			(*dcli_ac_init_func)(); 
		}


		dcli_wlan_init_func = dlsym(dcli_dl_handle_wid,"dcli_wlan_init");
		if ((error = dlerror()) != NULL) {
			printf(" Run without dcli_wlan_init be called.\n");
			fputs(error,stderr);
		} 
		else 
		{
			(*dcli_wlan_init_func)(); 
		}

		dcli_ebr_init_func = dlsym(dcli_dl_handle_wid,"dcli_ebr_init");
		if ((error = dlerror()) != NULL) {
			printf(" Run without dcli_ebr_init be called.\n");
			fputs(error,stderr);
		} 
		else 
		{
			(*dcli_ebr_init_func)(); 
		}

		dcli_aciplist_init_func = dlsym(dcli_dl_handle_wid,"dcli_aciplist_init");
		if ((error = dlerror()) != NULL) {
			printf(" Run without dcli_aciplist_init be called.\n");
			fputs(error,stderr);
		} 
		else 
		{
			(*dcli_aciplist_init_func)(); 
		}

		dcli_ac_group_init_func = dlsym(dcli_dl_handle_wid,"dcli_ac_group_init");
		if ((error = dlerror()) != NULL) {
			printf(" Run without dcli_ac_group_init be called.\n");
			fputs(error,stderr);
		} 
		else 
		{
			(*dcli_ac_group_init_func)(); 
		}

		dcli_ap_group_init_func = dlsym(dcli_dl_handle_wid,"dcli_ap_group_init");
		if ((error = dlerror()) != NULL) {
			printf(" Run without dcli_ap_group_init be called.\n");
			fputs(error,stderr);
		} 
		else 
		{
			(*dcli_ap_group_init_func)(); 
		}

	
		dcli_bsd_init_func = dlsym(dcli_dl_handle_wid,"dcli_bsd_init");
		if ((error = dlerror()) != NULL) {
			printf(" Run without dcli_bsd_init be called.\n");
			fputs(error,stderr);
		} 
		else 
		{
			(*dcli_bsd_init_func)(); 
		}		

		dcli_license_init_func = dlsym(dcli_dl_handle_wid,"dcli_license_init");
		if ((error = dlerror()) != NULL) {
			printf(" Run without dcli_license_init be called.\n");
			fputs(error,stderr);
		} 
		else 
		{
			(*dcli_license_init_func)(); 
		}	

		dcli_wbridge_init_func = dlsym(dcli_dl_handle_wid,"dcli_wbridge_init");
		if ((error = dlerror()) != NULL) {
			printf(" Run without dcli_wbridge_init be called.\n");
			fputs(error,stderr);
		} 
		else 
		{
			(*dcli_wbridge_init_func)(); 
		}	

		#if 1
		dcli_scanlocate_init_func = dlsym(dcli_dl_handle_wid, "dcli_scanlocate_init");
		if ((error = dlerror()) != NULL) {
			printf(" Run without dcli_wbridge_init be called.\n");
			fputs(error,stderr);
		} 
		else 
		{
			(*dcli_scanlocate_init_func)(); 
		}
		#endif
	}
	else 
	{
		fputs (dlerror(),stderr);
		printf(" Run without /opt/lib/libdcli_wid.so\n");
	}
	vtysh_send_dbus_signal_init();

	vtysh_sync_file_init();

	vtysh_get_rpa_broadcast_mask_init();

	/*
	 * The handle should not be closed before we do not use libdcli any more.
	 */
	return 1;

}
Exemple #22
0
int CMainCtrl::Initialize(char* pProName,char* pConfigFile)
{
	//读配置
	strcpy(m_stConfig.m_szSvrName,pProName);
	int iRet = ReadCfgFile(pConfigFile);
	if( 0 != iRet )
	{
		return iRet;
	}

	//连接资源限制,root用户下有效
	rlimit rlim;
	rlim.rlim_cur = m_stConfig.MAX_SOCKET_NUM+10240;
	rlim.rlim_max = m_stConfig.MAX_SOCKET_NUM+10240;
	setrlimit(RLIMIT_NOFILE, &rlim);	

	//bind cpu
	if(m_stConfig.m_iBindCpu >= 0)
	{
		cpu_set_t mask;
		int iCpuId = m_stConfig.m_iBindCpu;
		printf("set cpu affinity %d.\n",iCpuId);
		
		CPU_ZERO(&mask);
		CPU_SET(iCpuId, &mask);
		sched_setaffinity(0, sizeof(mask), &mask);
	}
	
	//读so
	void* pHandle = dlopen(m_stConfig.m_szNetCompleteSo, RTLD_LAZY);
	if (!pHandle)
	{
		printf("open %s failed!\n",m_stConfig.m_szNetCompleteSo);
		printf("use ccs/src/make -f makefile.complete to make these so,and choose the one you want.\n");
		return -1;
	}	
	dlerror();  	//Clear any existing error 
	net_complete_func = (check_complete)dlsym(pHandle, "net_complete_func");
	if (dlerror() != NULL)
	{
		printf("get net_complete_func from %s failed!\n",m_stConfig.m_szNetCompleteSo);
		return -1;
	}
	msg_header_len_func = (msg_header_len)dlsym(pHandle, "msg_header_len");
	if (dlerror() != NULL)
	{
		printf("get msg_header_len from %s failed!\n",m_stConfig.m_szNetCompleteSo);
		return -1;
	}
	m_iMsgHeaderLen = msg_header_len_func();

	//初始化epoll端口
	if(m_stEPollFlow.Create(m_stConfig.MAX_SOCKET_NUM))
	{
		printf("epoll create error!");
		return -1;
	}

	//创建管道
	if(CCodeQueue::CreateMQByFile(m_stConfig.m_szMeToSvrMQ,&m_Me2SvrPipe))
	{
		printf("CreateCodeMQ %s failed!\n",m_stConfig.m_szMeToSvrMQ);
		return -1;	
	}
	
	if(CCodeQueue::CreateMQByFile(m_stConfig.m_szSvrToMeMQ,&m_Svr2MePipe))
	{
		printf("CreateCodeMQ %s failed!\n",m_stConfig.m_szSvrToMeMQ);
		return -1;	
	}
	long long ullMemCost = 0;
	
	//创建CS消息缓冲区
	int iMemSize = TIdxObjMng::CountMemSize(m_stConfig.RCV_BLOCK_SIZE,m_stConfig.RCV_BLOCK_NUM,1);
	char* pMem = new char[iMemSize];
	m_stIdxObjMngRecv.AttachMem(pMem,iMemSize,m_stConfig.RCV_BLOCK_SIZE,m_stConfig.RCV_BLOCK_NUM,emInit,1);
	ullMemCost += (long long)iMemSize;

	iMemSize = CBuffMng::CountMemSize(m_stConfig.MAX_SOCKET_NUM);
	pMem = new char[iMemSize];	
	m_stBuffMngRecv.AttachMem(pMem,iMemSize,m_stConfig.MAX_SOCKET_NUM);
	ullMemCost += (long long)iMemSize;

	m_stBuffMngRecv.AttachIdxObjMng(&m_stIdxObjMngRecv);
	
	//创建SC消息缓冲区
	iMemSize = TIdxObjMng::CountMemSize(m_stConfig.SND_BLOCK_SIZE,m_stConfig.SND_BLOCK_NUM,1);
	pMem = new char[iMemSize];
	m_stIdxObjMngSend.AttachMem(pMem,iMemSize,m_stConfig.SND_BLOCK_SIZE,m_stConfig.SND_BLOCK_NUM,emInit,1);
	ullMemCost += (long long)iMemSize;

	iMemSize = CBuffMng::CountMemSize(m_stConfig.MAX_SOCKET_NUM);
	pMem = new char[iMemSize];	
	m_stBuffMngSend.AttachMem(pMem,iMemSize,m_stConfig.MAX_SOCKET_NUM);
	ullMemCost += (long long)iMemSize;

	m_stBuffMngSend.AttachIdxObjMng(&m_stIdxObjMngSend);

	//创建socket管理区
	iMemSize = TIdxObjMng::CountMemSize(sizeof(TSocketNode),m_stConfig.MAX_SOCKET_NUM,1);
	pMem = new char[iMemSize];
	m_stSocketNodeMng.AttachMem(pMem,iMemSize,sizeof(TSocketNode),m_stConfig.MAX_SOCKET_NUM,emInit,1);
	ullMemCost += (long long)iMemSize;

	iMemSize = CHashTab::CountMemSize(m_stConfig.MAX_SOCKET_NUM);
	pMem = new char[iMemSize];
	m_stSocketNodeHash.AttachMem(pMem, iMemSize,m_stConfig.MAX_SOCKET_NUM);
	ullMemCost += (long long)iMemSize;

	m_stSocketNodeHash.AttachIdxObjMng(&m_stSocketNodeMng,SetSocketNodeKey,GetSocketNodeKey);

	//内存管道监听
	if (m_Svr2MePipe.GetReadNotifyFD() >= 0)
	{
		iRet = CreateSocketNode(m_Svr2MePipe.GetReadNotifyFD(),TSocketNode::STATUS_OK,
							0,0,"_PIPE_",TSocketNode::PIPE_SOCKET);
		if(iRet < 0)
		{
			printf("CreateSocketNode Failed!iRet=%d\n",iRet);
			return iRet;
		}		
	}

	//管理端口
	if(m_stConfig.m_iAdminPort > 0)
	{
		unsigned short usListenPort = (unsigned short)m_stConfig.m_iAdminPort;
		unsigned int unListenIP = inet_addr(m_stConfig.m_szAdminIp);
		
		int iListenSocket = CreateListenSocket(unListenIP,usListenPort,
					m_stConfig.SOCKET_RCVBUF,m_stConfig.SOCKET_SNDBUF);
		if (iListenSocket < 0)
		{
			printf("CreateListenSocket %u:%u failed!\n",unListenIP,usListenPort);
			TLib_Log_LogMsg("CreateListenSocket %u:%u failed!\n",unListenIP,usListenPort);
			return -2;		
		}
		
		//加入监听数组
		int iNewSuffix = CreateSocketNode(iListenSocket,TSocketNode::STATUS_OK,
						unListenIP,usListenPort,"_ADMIN_",TSocketNode::ADMIN_LISTEN_SOCKET);
		if (iNewSuffix < 0)
		{
			close(iListenSocket);		
			printf("add to socket array failed!\n");
			TLib_Log_LogMsg("add to socket array failed!\n");
			return -3;
		}		

		printf("Admin Listen on %s:%u Success!\n", m_stConfig.m_szAdminIp, m_stConfig.m_iAdminPort);		
	}

	printf("%s Cost Mem %llu bytes.\n",SVR_NAME,ullMemCost);
	TLib_Log_LogMsg("Cost Mem %llu bytes.\n",ullMemCost);	
	printf("Server Init Success!\n");
	TLib_Log_LogMsg("Server Init Success!\n");
	return 0;
}
void vt_plugin_cntr_init() {
  char ** plugins;
  int nr_selected_plugins = 0;
  char * plugin_read_start;
  int read_plugin;
  char * current_plugin;

  char * env_vt_plugin_metrics;
  char current_plugin_metric[255];
  char * next_plugin_metric;

  char * env_vt_callback_buffer;

  char buffer[512];

  char * dl_lib_error;

  void * handle;
  vt_plugin_cntr_info info;

  /* used union to get rid of compiler warning */
  union {
    void * vp;
    vt_plugin_cntr_info (* function)(void);

  } get_info;

  int index;
  int i;
  int found = 0;

  struct vt_plugin * current;

  /* set some internal variables to zero */
  vt_plugin_handles = calloc(VT_PLUGIN_CNTR_SYNCH_TYPE_MAX,
      sizeof(struct vt_plugin *));
  nr_plugins = calloc(VT_PLUGIN_CNTR_SYNCH_TYPE_MAX, sizeof(uint32_t));

  /* check whether plugins are activated */
  env_vt_plugin_metrics = getenv("VT_PLUGIN_CNTR_METRICS");
  if (env_vt_plugin_metrics == NULL)
    return;

  env_vt_callback_buffer = getenv("VT_PLUGIN_CNTR_CALLBACK_BUFFER");
  /* default: 1 M elements (16 MiB memory) per thread and callback counter */
  if (env_vt_callback_buffer == NULL)
    max_values_callback = 1024 * 1024;
  else
    max_values_callback = atoi(env_vt_callback_buffer);

  /* extract the plugin names */
  plugin_read_start = env_vt_plugin_metrics;
  read_plugin = 1;
  current_plugin = plugin_read_start;
  plugins = NULL;
  /* go through the plugin env. variable */
  for (; *current_plugin != '\0'; current_plugin++) {
    if (read_plugin) {
      if (*current_plugin == '_') {
        /* do not use the same plugin twice! */
        memcpy(buffer, plugin_read_start,
            ((current_plugin - plugin_read_start)) * sizeof(char));
        buffer[(current_plugin - plugin_read_start)] = '\0';
        found = 0;
        for (i = 0; i < nr_selected_plugins; i++) {
          if (strcmp(buffer, plugins[i]) == 0)
            found = 1;
        }
        if (found) {
          read_plugin = 0;
          continue;
        } else {
          nr_selected_plugins++;
          /* allocate the plugin name buffer */
          plugins = realloc(plugins, nr_selected_plugins * sizeof(char*));
          plugins[nr_selected_plugins - 1] = malloc(
              (current_plugin - plugin_read_start + 1) * sizeof(char));
          /* copy the content to the buffer */
          memcpy(plugins[nr_selected_plugins - 1], plugin_read_start,
              ((current_plugin - plugin_read_start)) * sizeof(char));
          /* finish with null */
          plugins[nr_selected_plugins - 1]
                 [(current_plugin - plugin_read_start)] = '\0';
          read_plugin = 0;
        }
      }
    } else {
      /* a new plugin/counter starts after the ':' */
      if (*current_plugin == ':') {
        read_plugin = 1;
        plugin_read_start = current_plugin + 1;
      }
    }
  }
  /*go through all plugins:*/
  for (i = 0; i < nr_selected_plugins; i++) {
    uint32_t group = 0;
    current_plugin = plugins[i];
    vt_cntl_msg(2, "Loading plugin counter library: lib%s.so", current_plugin);
    /* next one is stored in next_plugin,
     / * current is stored in current_plugin_buffer */
    /* load it from LD_LIBRARY_PATH*/
    sprintf(buffer, "lib%s.so", current_plugin);

    /* now dlopen it */
    handle = dlopen(buffer, RTLD_NOW);

    /* if it is not valid */
    if ((dl_lib_error = dlerror()) != NULL) {
      vt_error_msg("Error loading plugin: %s\n", dl_lib_error);
      /* try loading next */
      continue;
    }

    /* now get the info */
    get_info.vp = dlsym(handle, "get_info");
    if ((dl_lib_error = dlerror()) != NULL) {
      vt_error_msg("Error getting info from plugin: %s\n", dl_lib_error);
      dlclose(handle);
      /* try loading next */
      continue;
    }

    /* now store it */

    /* get the info */
    info = get_info.function();

    /* check the run per type */

    if (info.run_per == VT_PLUGIN_CNTR_PER_PROCESS) {
      if (thread_group == INVALID_GROUP_NUMBER){
        vt_cntl_msg(3, "No process group defined, using master thread for %s",
            current_plugin);
      }
      else{
# if (defined(VT_MT) || defined(VT_HYB))
        /* only called per process */
        group = vt_get_curid();
        thread_group = group;
# else
        /* not multithreaded -> keep information on local process */
#endif
      }
    }

    if (info.run_per == VT_PLUGIN_CNTR_PER_HOST) {
      if (!vt_my_trace_is_master)
        continue;
      else if (host_group == INVALID_GROUP_NUMBER){
        host_group = vt_node_pgid;
        vt_def_procgrp_attributes(VT_MY_THREAD ,vt_node_pgid,
            VT_PROCGRP_HASCOUNTERS);
      }
      group = host_group;
    }

    if (info.run_per == VT_PLUGIN_CNTR_ONCE) {
      if (vt_my_trace != 0)
        continue;
      else if (all_group == INVALID_GROUP_NUMBER){
        all_group = vt_all_pgid;
        vt_def_procgrp_attributes(VT_MY_THREAD ,vt_all_pgid,
            VT_PROCGRP_HASCOUNTERS);
      }
      group = all_group;
    }

    if (info.init == NULL) {
      vt_error_msg(
          "Init not implemented in plugin %s\n",
          current_plugin);
      /* try loading next */
      continue;
    }

    if (info.add_counter == NULL) {
      vt_error_msg(
          "Add counter not implemented in plugin %s\n",
          current_plugin);
      /* try loading next */
      continue;
    }

    if (info.get_event_info == NULL) {
      vt_error_msg("Get event info not implemented in plugin %s\n",
          current_plugin);
      /* try loading next */
      continue;
    }

    /* check the type of plugin */
    switch (info.synch) {
    case VT_PLUGIN_CNTR_SYNCH:
      nr_plugins[VT_PLUGIN_CNTR_SYNCH]++;
      vt_plugin_handles[VT_PLUGIN_CNTR_SYNCH] = realloc(
          vt_plugin_handles[VT_PLUGIN_CNTR_SYNCH],
          nr_plugins[VT_PLUGIN_CNTR_SYNCH] * sizeof(struct vt_plugin));
      current
          = &vt_plugin_handles[VT_PLUGIN_CNTR_SYNCH]
                              [nr_plugins[VT_PLUGIN_CNTR_SYNCH] - 1];
      if (info.get_current_value == NULL) {
        nr_plugins[VT_PLUGIN_CNTR_SYNCH]--;
        vt_error_msg("Get current results not implemented in plugin %s\n",
            current_plugin);
        /* try loading next */
        continue;
      }
      break;
    case VT_PLUGIN_CNTR_ASYNCH_CALLBACK:
      nr_plugins[VT_PLUGIN_CNTR_ASYNCH_CALLBACK]++;
      vt_plugin_handles[VT_PLUGIN_CNTR_ASYNCH_CALLBACK]
          = realloc(
              vt_plugin_handles[VT_PLUGIN_CNTR_ASYNCH_CALLBACK],
              nr_plugins[VT_PLUGIN_CNTR_ASYNCH_CALLBACK]
                  * sizeof(struct vt_plugin));
      current
          = &vt_plugin_handles[VT_PLUGIN_CNTR_ASYNCH_CALLBACK]
                              [nr_plugins[VT_PLUGIN_CNTR_ASYNCH_CALLBACK] - 1];
      if (info.set_callback_function == NULL) {
        nr_plugins[VT_PLUGIN_CNTR_ASYNCH_CALLBACK]--;
        vt_error_msg("set callback not implemented in plugin %s\n",
            current_plugin);
        /* try loading next */
        continue;
      }
      if (info.set_pform_wtime_function == NULL) {
        nr_plugins[VT_PLUGIN_CNTR_ASYNCH_CALLBACK]--;
        vt_error_msg(
            "set wtime not implemented in plugin %s\n",
            current_plugin);
        /* try loading next */
        continue;
      }
      break;
    case VT_PLUGIN_CNTR_ASYNCH_EVENT:
      nr_plugins[VT_PLUGIN_CNTR_ASYNCH_EVENT]++;
      vt_plugin_handles[VT_PLUGIN_CNTR_ASYNCH_EVENT] = realloc(
          vt_plugin_handles[VT_PLUGIN_CNTR_ASYNCH_EVENT],
          nr_plugins[VT_PLUGIN_CNTR_ASYNCH_EVENT] * sizeof(struct vt_plugin));
      current
          = &vt_plugin_handles[VT_PLUGIN_CNTR_ASYNCH_EVENT]
                               [nr_plugins[VT_PLUGIN_CNTR_ASYNCH_EVENT] - 1];
      if (info.get_all_values == NULL) {
        nr_plugins[VT_PLUGIN_CNTR_ASYNCH_EVENT]--;
        vt_error_msg("get all values not implemented in plugin %s\n",
            current_plugin);
        /* try loading next */
        continue;
      }
      if (info.set_pform_wtime_function == NULL) {
        nr_plugins[VT_PLUGIN_CNTR_ASYNCH_EVENT]--;
        vt_error_msg(
            "set wtime not implemented in plugin %s\n",
            current_plugin);
        /* try loading next */
        continue;
      }
      break;
    case VT_PLUGIN_CNTR_ASYNCH_POST_MORTEM:
      nr_plugins[VT_PLUGIN_CNTR_ASYNCH_POST_MORTEM]++;
      vt_plugin_handles[VT_PLUGIN_CNTR_ASYNCH_POST_MORTEM] = realloc(
          vt_plugin_handles[VT_PLUGIN_CNTR_ASYNCH_POST_MORTEM],
          nr_plugins[VT_PLUGIN_CNTR_ASYNCH_POST_MORTEM]
              * sizeof(struct vt_plugin));
      current
          = &vt_plugin_handles[VT_PLUGIN_CNTR_ASYNCH_POST_MORTEM]
                           [nr_plugins[VT_PLUGIN_CNTR_ASYNCH_POST_MORTEM] - 1];
      if (info.get_all_values == NULL) {
        vt_error_msg("get all values not implemented in plugin %s\n",
            current_plugin);
        nr_plugins[VT_PLUGIN_CNTR_ASYNCH_POST_MORTEM]--;
        /* try loading next */
        continue;
      }
      if (info.set_pform_wtime_function == NULL) {
        vt_error_msg(
            "set wtime not implemented in plugin %s\n",
            current_plugin);
        nr_plugins[VT_PLUGIN_CNTR_ASYNCH_POST_MORTEM]--;
        /* try loading next */
        continue;
      }
      break;
    default:
      vt_error_msg(
          "Error getting synch type from plugin (invalid synch type)\n");
      continue;
    }

    /* clear out current plugin */
    memset(current, 0, sizeof(struct vt_plugin));

    /* add handle (should be closed in the end) */
    current->dlfcn_handle = handle;

    /* store the info object of the plugin */
    current->info = info;

    /* store the name of the plugin */
    current->name = current_plugin;

    /* give plugin the wtime function to make it possible to convert times */
    if (current->info.set_pform_wtime_function != NULL) {
      current->info.set_pform_wtime_function(vt_pform_wtime);
    }
    vt_cntl_msg(3, "Initializing plugin counter library: lib%s.so",
        current_plugin);
    /* initialize plugin */
    if (current->info.init()) {
      vt_error_msg("Error initializing plugin %s, init returned != 0\n",
          current_plugin);
      continue;
    }
    /* define a counter group for every plugin*/
    current->counter_group = vt_def_counter_group(VT_MY_THREAD, current_plugin);

    /* now search for all available events on that plugin */
    next_plugin_metric = env_vt_plugin_metrics;
    while (next_plugin_metric[0] != 0) {
      /* shall contain current index in environment VT_PLUGIN_METRICS */
      index = 0;

      /* copy metric to current_plugin_metric char by char */
      while ((next_plugin_metric[index] != ':') && (next_plugin_metric[index]
          != '\0')) {
        current_plugin_metric[index] = next_plugin_metric[index];
        index++;
      }
      current_plugin_metric[index] = 0;
      if (next_plugin_metric[index] == ':')
        next_plugin_metric = &next_plugin_metric[index + 1];
      else
        next_plugin_metric = &next_plugin_metric[index];
      /* If the plugin metric belongs to the current plugin */
      if (strstr(current_plugin_metric, current_plugin)
          == current_plugin_metric) {
        /* some meta data*/
        char * unit = NULL;
        uint32_t otf_prop = 0;

        /* This will be needed to iterate over the infos */
        vt_plugin_cntr_metric_info * current_event_info;

        /* check the event name from plugin */
        /* it could contain wildcards and other stuff */
        vt_plugin_cntr_metric_info * event_infos = info.get_event_info(
            &current_plugin_metric[strlen(current_plugin) + 1]);

        vt_cntl_msg(3, "Adding metric %s for plugin counter library: lib%s.so",
            current_plugin_metric, current_plugin);

        /* check the event name from plugin */
        /* it could contain wildcards and other stuff */
        if (event_infos == NULL) {
          vt_error_msg(
              "Error initializing plugin metric %s, no info returned\n",
              current_plugin_metric);
          continue;
        }
        /* now for all events which are present in the struct */
        current_event_info = event_infos;
        for (current_event_info = event_infos;
            current_event_info->name != NULL;
            current_event_info++) {

          vt_cntl_msg(3,
              "Retrieved metric %s for plugin counter library: lib%s.so."
                " Initializing data structures", current_event_info->name,
              current_plugin);

          /* event is part of this plugin */
          current->num_selected_events++;

          /* allocate space for events */
          current->selected_events = realloc(current->selected_events,
              current->num_selected_events * sizeof(char*));

          /*the metric is everything after "plugin_"*/
          current->selected_events[current->num_selected_events - 1]
              = current_event_info->name;

          current->vt_counter_ids = realloc(current->vt_counter_ids,
              current->num_selected_events * sizeof(uint32_t));

          current->vt_asynch_keys = realloc(current->vt_asynch_keys,
              current->num_selected_events * sizeof(uint32_t));

          /* if a unit is provided, use it */
          unit = current_event_info->unit == NULL ? "#"
              : current_event_info->unit;

          /* if otf properties are provided, use them */
          otf_prop = current_event_info->cntr_property;
          /* define new counter */
          current->vt_counter_ids[current->num_selected_events - 1]
              = vt_def_counter(VT_MY_THREAD,
                  current->selected_events[current->num_selected_events - 1],
                  unit, otf_prop, current->counter_group, group);

          if (current->info.synch != VT_PLUGIN_CNTR_SYNCH) {
            char buffer[512];
            sprintf(buffer, "%s_%s", current_plugin, current_event_info->name);
            current->vt_asynch_keys[current->num_selected_events - 1]
                = vt_def_async_source(VT_MY_THREAD, buffer);
          }
          /* enable plugin counters */
          vt_plugin_cntr_used = 1;
        } /* end of: for all metrics related to the metric string */
        if (event_infos != NULL)
          free(event_infos);
      } /* end of if metric belongs to this plugin */
    } /* end of: for all plugin metrics */
  } /* end of: for all plugins */

  /* free temporary variables */
  if (plugins != NULL)
    free(plugins);

}
Exemple #24
0
int main (int argc, char **argv) {
	int expect = 0;
	int error_fail = 0;
	int verbose = 0;

	char const * glibmm = "libglibmm-2.4.so";

	const struct option long_options[] = {
		{ "fail",       no_argument,       0, 'f' },
		{ "help",       no_argument,       0, 'h' },
		{ "gcc4",       no_argument,       0, '4' },
		{ "gcc5",       no_argument,       0, '5' },
		{ "glibmm",     required_argument, 0, 'g' },
		{ "verbose",    no_argument,       0, 'v' },
		{ "version",    no_argument,       0, 'V' },
	};

	const char *optstring = "fh45g:vV";

	int c;
	while ((c = getopt_long (argc, argv, optstring, long_options, NULL)) != -1) {
		switch (c) {
			case 'f':
				error_fail = 1;
				break;
			case 'h':
				print_usage ();
				return 0;
				break;
			case '4':
				expect |= 1;
				break;
			case '5':
				expect |= 2;
				break;
			case 'g':
				glibmm = optarg;
				break;
			case 'v':
				verbose = 1;
				break;
			case 'V':
				print_version ();
				return 0;
				break;
			default:
				fprintf (stderr, "invalid argument.\n");
				print_usage ();
				return -1;
				break;
		}
	}

	int gcc5 = 0;
	int gcc4 = 0;

	dlerror (); // reset error

	void *h = dlopen (glibmm, RTLD_LAZY);
	if (!h) {
		if (verbose) {
			fprintf (stderr, "Cannot open '%s': %s.\n", glibmm, dlerror ());
		}
		return error_fail ? 3 : 0;
	}

	// Glib::ustring::ustring(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)
	if (dlsym (h, "_ZN4Glib7ustringC1ERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE")) {
		gcc5 |= 1;
	}

	// Glib::ustring::ustring(std::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)
	if (dlsym (h, "_ZN4Glib7ustringC1ERKSs")) {
		gcc4 |= 1;
	}


	// Glib::Module::Module(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, Glib::ModuleFlags)
	if (dlsym (h, "_ZN4Glib6ModuleC1ERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEENS_11ModuleFlagsE")) {
		gcc5 |= 2;
	}

	// Glib::Module::Module(std::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, Glib::ModuleFlags)
	if (dlsym (h, "_ZN4Glib6ModuleC1ERKSsNS_11ModuleFlagsE")) {
		gcc4 |= 2;
	}


	// Glib::ustring::operator=(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)
	if (dlsym (h, "_ZN4Glib7ustringaSERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE")) {
		gcc5 |= 4;
	}

	// Glib::ustring::operator=(std::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)
	if (dlsym (h, "_ZN4Glib7ustringaSERKSs")) {
		gcc4 |= 4;
	}

	dlclose (h);

	if (7 != (gcc4 ^ gcc5)) {
		if (verbose) {
			fprintf (stderr, "Inconsistent result: gcc4=%x gcc5=%x\n", gcc4, gcc5);
		}
	}
	else if (gcc4 == 7) {
		if (verbose) {
			printf ("System uses gcc4 c++ ABI\n");
		}
		if (expect != 0) {
			return (expect & 1) ? 0 : 1;
		}
	}
	else if (gcc5 == 7) {
		if (verbose) {
			printf ("System uses gcc5 c++11 ABI\n");
		}
		if (expect != 0) {
			return (expect & 2) ? 0 : 1;
		}
	}
	else if (verbose) {
		fprintf (stderr, "Incomplete result: gcc4=%x gcc5=%x\n", gcc4, gcc5);
	}

	return error_fail ? 2 : 0;
}
Exemple #25
0
static Eina_Bool
_ecore_drm2_link(void)
{
   int i, fail;
   const char *drm_libs[] =
     {
        "libdrm.so.2",
        "libdrm.so.1",
        "libdrm.so.0",
        "libdrm.so",
        NULL,
     };

#define SYM(lib, xx)                         \
   do {                                      \
      sym_ ## xx = dlsym(lib, #xx);          \
      if (!(sym_ ## xx)) {                   \
         fail = 1;                           \
      }                                      \
   } while (0)

   if (drm_lib) return EINA_TRUE;

   for (i = 0; drm_libs[i]; i++)
     {
        drm_lib = dlopen(drm_libs[i], RTLD_LOCAL | RTLD_LAZY);
        if (!drm_lib) continue;

        fail = 0;

        SYM(drm_lib, drmIoctl);
        /* SYM(drm_lib, drmClose); */
        /* SYM(drm_lib, drmWaitVBlank); */
        SYM(drm_lib, drmHandleEvent);
        SYM(drm_lib, drmGetVersion);
        SYM(drm_lib, drmFreeVersion);
        SYM(drm_lib, drmModeGetProperty);
        SYM(drm_lib, drmModeFreeProperty);
        SYM(drm_lib, drmModeGetPropertyBlob);
        SYM(drm_lib, drmModeFreePropertyBlob);
        SYM(drm_lib, drmModeDestroyPropertyBlob);
        SYM(drm_lib, drmModeObjectGetProperties);
        SYM(drm_lib, drmModeFreeObjectProperties);
        SYM(drm_lib, drmModeCreatePropertyBlob);
#ifdef HAVE_ATOMIC_DRM
        SYM(drm_lib, drmModeAtomicAlloc);
        SYM(drm_lib, drmModeAtomicFree);
        SYM(drm_lib, drmModeAtomicAddProperty);
        SYM(drm_lib, drmModeAtomicCommit);
        SYM(drm_lib, drmModeAtomicSetCursor);
        SYM(drm_lib, drmModeAtomicMerge);
#endif
        SYM(drm_lib, drmModeGetEncoder);
        SYM(drm_lib, drmModeFreeEncoder);
        SYM(drm_lib, drmModeGetCrtc);
        SYM(drm_lib, drmModeFreeCrtc);
        SYM(drm_lib, drmModeSetCrtc);
        SYM(drm_lib, drmModeGetResources);
        SYM(drm_lib, drmModeFreeResources);
        SYM(drm_lib, drmModeGetConnector);
        SYM(drm_lib, drmModeFreeConnector);
        SYM(drm_lib, drmModeConnectorSetProperty);
        SYM(drm_lib, drmGetCap);
        SYM(drm_lib, drmSetClientCap);
        SYM(drm_lib, drmModeGetPlaneResources);
        SYM(drm_lib, drmModeFreePlaneResources);
        SYM(drm_lib, drmModeGetPlane);
        SYM(drm_lib, drmModeFreePlane);
        SYM(drm_lib, drmModeAddFB);
        SYM(drm_lib, drmModeAddFB2);
        SYM(drm_lib, drmModeRmFB);
        SYM(drm_lib, drmModePageFlip);
        SYM(drm_lib, drmModeDirtyFB);
        SYM(drm_lib, drmModeCrtcSetGamma);
        SYM(drm_lib, drmPrimeFDToHandle);

        if (fail)
          {
             dlclose(drm_lib);
             drm_lib = NULL;
          }
        else
          break;
     }

   if (!drm_lib) return EINA_FALSE;
   return EINA_TRUE;
}
Exemple #26
0
int main() {dlopen("a",RTLD_LAZY); return 0;}
Exemple #27
0
static void startup_desktop()
{
#if 0
	char error[1024];
	void *libwine_handle;
	//char *args[]={"wineloader","c:\\gcc.exe","/c","/FAs","c:\\myfile.c",NULL};				//For VC++6.0 cl
	char *args[]={"wineloader","c:\\gcc.exe","c:\\myfile.c",NULL};							//For notepad
	//char *args[]={"wineloader","c:\\AngryBirds\\AngryBirds.exe",NULL};							//For angrybirds
	//char *args[]={"wineloader","c:\\mplayer.exe","c:\\a.flv","-vo", "none",NULL};										//For notepad
	//char *args[]={"wineloader","c:\\gcc.exe","/DLL","c:\\windows\\myfile.obj"};				//For VC++6.0 linker
	//char *args[]={"wineloader","c:\\gcc.exe","-s","myfile","-l","language\\chinese.oic"};		//For Olanguage
	void (*wine_init)(int argc, char *argv[], char *error, int error_size );
	char *pWineBaseDir = "/0:/wine/";
	
	FASetCurrentThreadNameA("winapp 主线程.");
	FAVfsInitTTY();												//必须将客户端的0,1,2 FD 对应的位置预留起来,WINE内部是固定用这几个来作为CONSOLE处理的,它要将0,1,2发送给server,导致发送失败
	setenv("WINEDLLPATH","dlls",TRUE);							//WINE dll目录;
	setenv("WINEPREFIX",pWineBaseDir,TRUE);						//Server Connect需要得到当前工作目录;
	//setenv("WINEDEBUG","+all,trace-heap",TRUE);					//OPen all messages
	setenv("WINEDEBUG","+trace-heap",TRUE);					//OPen all messages
	setenv("PWD","0:",TRUE);
	setenv("DISPLAY","unix:0.0",TRUE);							/*	X defualt display name */
	
	dprintf("\n正在启动 wine server...");
	FAStartupServiceA("WINESERVER",TRUE);
	dprintf("\n正在启动 wine ...");
#ifdef __i386__
	__asm("mov $0,%ax\n\t "
		  "mov %ax,%fs\n\t");
#endif
	
	
	/*
	 切换当前工作路径
	 */
	if(FAChangeDirByStringA(pWineBaseDir)!=FASTATUS_SUCCESS)
	{
		dprintf("\n系统没有安装Wine.");
		return 0;
	}
	/*
	 打开第一个动态库
	 */
	libwine_handle = dlopen(ELF_FILE_NAME,NULL);
	if(libwine_handle==NULL)
	{
		dprintf("\nWINLOADER:无法找到%s.",ELF_FILE_NAME);
		return 0;
	}
	FASleepThreadMs(5000);						//waiting the wineserver is ready.
	wine_init	= dlsym(libwine_handle,"wine_init");/*Call wine Init*/
	if(wine_init)
		wine_init( sizeof(args)/(sizeof(char*))-1/*MUST escape the null*/, args, error, sizeof(error) );
	else
	{
		dprintf("\nWINLOADER:无法找到入口wine_init.");
		return 0;
	}
	/*Load the libwine,因为wine_init这个入口函数在libwine.a中,根据loader\main.c中的流程,在运行wine_init之前还要运行preloader,和pthread,不知道是干什么的*/
	return 0;
#endif
}
static void load_module(const char *name)
{
        void *handle, *cast;
        autofree(char) *path = NULL;
        char *error = NULL;
        cve_plugin_init init_func;
        CvePlugin *plugin = NULL;

#ifdef TEST_SUITE_BUILD
        if (!asprintf(&path, TOP_BUILD_DIR"/tests/dummy_install/%s", name)) {
#else
        if (!asprintf(&path, "%s/%s", MODULE_DIR, name)) {
#endif
                fprintf(stderr, "No memory\n");
                return;
        }
        handle = dlopen(path, RTLD_LAZY);
        if (!handle) {
                fprintf(stderr, "Unable to load module: %s\n", dlerror());
                return;
        }
        dlerror();
        cast = dlsym(handle, "cve_plugin_module_init");
        if (!cast || (error = dlerror()) != NULL) {
                fprintf(stderr, "Cannot load module: %s\n", error);
                abort();
        }
        dlerror();
        memcpy(&init_func, &cast, sizeof(init_func));

        plugin = calloc(1, sizeof(struct CvePlugin));
        if (!plugin) {
                fprintf(stderr, "Unable to allocate memory\n");
                abort();
        }
        if (!init_func(plugin)) {
                fprintf(stderr, "Plugin initialisation failed\n");
                abort();
        }
        if (!plugin->name) {
                fprintf(stderr, "Plugin %s does not set a name - aborting\n", name);
                abort();
        }
        plugin->handle = handle;
        cve_hashmap_put(_plugins, (char*)plugin->name, plugin);
}

static void destroy_plugin(CvePlugin *plugin)
{
        if (plugin->destroy) {
                plugin->destroy(plugin);
        }
        if (plugin->handle) {
                dlclose(plugin->handle);
        }
        free(plugin);
}

void cve_plugin_manager_init()
{
        DIR *dir = NULL;
        struct dirent *ent = NULL;

        if (_plugins) {
                return;
        }
        _plugins = cve_hashmap_new_full(string_hash, string_compare, NULL, (hash_free_func)destroy_plugin);

#ifdef TEST_SUITE_BUILD
        if (!(dir = opendir(TOP_BUILD_DIR "/tests/dummy_install"))) {
#else
        if (!(dir = opendir(MODULE_DIR))) {
#endif
                fprintf(stderr, "Unable to list modules: %s\n", strerror(errno));
                return;
        }

        while ((ent = readdir(dir))) {
                if (g_str_has_suffix(ent->d_name, ".so")) {
                        load_module(ent->d_name);
                }
        }
        if (dir) {
                closedir(dir);
        }
}

void cve_plugin_manager_destroy()
{
        if (!_plugins) {
                return;
        }
        cve_hashmap_free(_plugins);
        _plugins = NULL;
}


CvePlugin *cve_plugin_get_by_name(const char *name)
{
        CvePlugin *ret = NULL;

        if (!_plugins) {
                return NULL;
        }
        ret = cve_hashmap_get(_plugins, name);
        return ret;
}
/* Load a plugin from disk and put the function table into a driver_list
   struct. */
static driver_list *_get_plugin(char *plugin_file)
{
        ao_device *device = ao_global_dummy;
	driver_list *dt;
	void *handle;
        char *prompt="";

	handle = dlopen(plugin_file, DLOPEN_FLAG /* See ao_private.h */);

	if (handle) {
                prompt="calloc() failed";
                dt = (driver_list *)calloc(1,sizeof(driver_list));
		if (!dt) return NULL;

		dt->handle = handle;

		dt->functions = (ao_functions *)calloc(1,sizeof(ao_functions));
		if (!(dt->functions)) {
			free(dt);
			return NULL;
		}

                prompt="ao_plugin_test() missing";
		dt->functions->test = dlsym(dt->handle, "ao_plugin_test");
		if (!(dt->functions->test)) goto failed;

                prompt="ao_plugin_driver_info() missing";
		dt->functions->driver_info =
		  dlsym(dt->handle, "ao_plugin_driver_info");
		if (!(dt->functions->driver_info)) goto failed;

                prompt="ao_plugin_device_list() missing";
		dt->functions->device_init =
		  dlsym(dt->handle, "ao_plugin_device_init");
		if (!(dt->functions->device_init )) goto failed;

                prompt="ao_plugin_set_option() missing";
		dt->functions->set_option =
		  dlsym(dt->handle, "ao_plugin_set_option");
		if (!(dt->functions->set_option)) goto failed;

                prompt="ao_plugin_open() missing";
		dt->functions->open = dlsym(dt->handle, "ao_plugin_open");
		if (!(dt->functions->open)) goto failed;

                prompt="ao_plugin_play() missing";
		dt->functions->play = dlsym(dt->handle, "ao_plugin_play");
		if (!(dt->functions->play)) goto failed;

                prompt="ao_plugin_close() missing";
		dt->functions->close = dlsym(dt->handle, "ao_plugin_close");
		if (!(dt->functions->close)) goto failed;

                prompt="ao_plugin_clear() missing";
		dt->functions->device_clear =
		  dlsym(dt->handle, "ao_plugin_device_clear");
		if (!(dt->functions->device_clear)) goto failed;


	} else {
          aerror("Failed to load plugin %s => dlopen() failed\n",plugin_file);
          return NULL;
	}

        adebug("Loaded driver %s\n",dt->functions->driver_info()->short_name);
	return dt;

 failed:
        aerror("Failed to load plugin %s => %s\n",plugin_file,prompt);
	free(dt->functions);
	free(dt);
	return NULL;
}
Exemple #30
0
/* Create (if necessary), find, lock, fill in, and return our globals.  
   Return NULL on error, in which case the globals will not be locked.  
   The caller should call keymgr_set_and_unlock.  */
static struct keymgr_atexit_list *
get_globals (void)
{
  struct keymgr_atexit_list * r;
  
#ifdef __ppc__
  /* 10.3.9 doesn't have _keymgr_get_and_lock_processwide_ptr_2 so the
     PPC side can't use it.  On 10.4 this just means the error gets
     reported a little later when
     _keymgr_set_and_unlock_processwide_ptr finds that the key was
     never locked.  */
  r = _keymgr_get_and_lock_processwide_ptr (KEYMGR_ATEXIT_LIST);
#else
  void * rr;
  if (_keymgr_get_and_lock_processwide_ptr_2 (KEYMGR_ATEXIT_LIST, &rr))
    return NULL;
  r = rr;
#endif
  
  if (r == NULL)
    {
      r = calloc (sizeof (struct keymgr_atexit_list), 1);
      if (! r)
	return NULL;
    }

  if (r->atexit_status == atexit_status_unknown)
    {
      void *handle;

      handle = dlopen ("/usr/lib/libSystem.B.dylib", RTLD_NOLOAD);
      if (!handle)
	{
#ifdef __ppc__
	  r->atexit_status = atexit_status_missing;
	  r->atexit_f = find_atexit_10_3 ();
	  if (! r->atexit_f)
	    goto error;
	  if (r->atexit_f (our_atexit))
	    goto error;
#else
	  goto error;
#endif
	}
      else
	{
	  int chk_result;

	  r->cxa_atexit_f = (cxa_atexit_p)dlsym (handle, "__cxa_atexit");
	  r->cxa_finalize_f = (cxa_finalize_p)dlsym (handle, "__cxa_finalize");
	  if (! r->cxa_atexit_f || ! r->cxa_finalize_f)
	    goto error;

	  chk_result = check_cxa_atexit (r->cxa_atexit_f, r->cxa_finalize_f);
	  if (chk_result == -1)
	    goto error;
	  else if (chk_result == 0)
	    r->atexit_status = atexit_status_broken;
	  else
	    {
	      r->atexit_f = (atexit_p)dlsym (handle, "atexit");
	      if (! r->atexit_f)
		goto error;
	      r->atexit_status = atexit_status_working;
	    }
	}
    }

  return r;
  
 error:
  _keymgr_set_and_unlock_processwide_ptr (KEYMGR_ATEXIT_LIST, r);
  return NULL;
}