uv_err_t UVDPluginEngine::loadByPath(const std::string &path, bool reportErrors) { UVDPlugin *plugin = NULL; void *library = NULL; UVDPlugin::PluginMain pluginMain = NULL; const char *lastError = NULL; uv_err_t rcTemp = UV_ERR_GENERAL; std::string name; printf_plugin_debug("trying to load plugin path %s\n", path.c_str()); //Clear errors dlerror(); library = dlopen(path.c_str(), RTLD_LAZY); lastError = dlerror(); if( !library || lastError ) { if( reportErrors ) { //Maybe should be a warning? //is there any reason why we'd lazily try to load a plugin only if it exists? if( !lastError ) { lastError = "<UNKNOWN>"; } printf_error("%s: load library failed: %s\n", path.c_str(), lastError); return UV_DEBUG(UV_ERR_NOTSUPPORTED); } else { if( !lastError ) { lastError = "<UNKNOWN>"; } printf_plugin_debug("%s: load library failed: %s\n", path.c_str(), lastError); return UV_ERR_NOTSUPPORTED; } } /* Prefer mangled symbol since its more type safe */ pluginMain = (UVDPlugin::PluginMain)dlsym(library, UVD_PLUGIN_MAIN_MANGLED_SYMBOL_STRING); lastError = dlerror(); if( !pluginMain || lastError ) { //But settle for the extern'd symbol if they do that for w/e reason pluginMain = (UVDPlugin::PluginMain)dlsym(library, UVD_PLUGIN_MAIN_SYMBOL_STRING); lastError = dlerror(); if( !pluginMain || lastError ) { if( reportErrors ) { if( !lastError ) { lastError = "<UNKNOWN>"; } printf_error("plugin %s: failed to load main: %s\n", path.c_str(), lastError); dlclose(library); return UV_DEBUG(UV_ERR_NOTSUPPORTED); } else { if( !lastError ) { lastError = "<UNKNOWN>"; } printf_plugin_debug("plugin %s: failed to load main: %s\n", path.c_str(), lastError); dlclose(library); return UV_ERR_NOTSUPPORTED; } } } // typedef PluginMain uv_err_t (*)(UVD *uvd, UVDPlugin **out); UVDConfig *config = NULL; if( m_uvd ) { config = m_uvd->m_config; } else { uv_assert_ret(g_config); config = g_config; } rcTemp = UV_DEBUG(pluginMain(config, &plugin)); if( UV_FAILED(rcTemp) ) { //Don't do report error checks since it has demonstrated reasonable effort at being a valid plugin printf_error("plugin %s: main failed\n", path.c_str()); dlclose(library); return UV_DEBUG(UV_ERR_GENERAL); } if( !plugin ) { if( !config->m_suppressErrors ) { printf_error("plugin %s: didn't return a plugin object\n", path.c_str()); } dlclose(library); return UV_DEBUG(UV_ERR_GENERAL); } rcTemp = UV_DEBUG(plugin->getName(name)); if( UV_FAILED(rcTemp) ) { dlclose(library); return UV_DEBUG(UV_ERR_GENERAL); } if( name.empty() ) { /* we could do name = path; but it might cause issues later refusing to load makes people stop being lazy */ printf_error("plugin %s: didn't provide a name\n", path.c_str()); dlclose(library); return UV_DEBUG(UV_ERR_GENERAL); } plugin->m_hLibrary = library; m_plugins[name] = plugin; printf_plugin_debug("loaded plugin: %s\n", name.c_str()); return UV_ERR_OK; }
static int xmlModulePlatformClose(void *handle) { return dlclose(handle); }
void kadm5_setup_passwd_quality_check(krb5_context context, const char *check_library, const char *check_function) { #ifdef HAVE_DLOPEN void *handle; void *sym; int *version; const char *tmp; if(check_library == NULL) { tmp = krb5_config_get_string(context, NULL, "password_quality", "check_library", NULL); if(tmp != NULL) check_library = tmp; } if(check_function == NULL) { tmp = krb5_config_get_string(context, NULL, "password_quality", "check_function", NULL); if(tmp != NULL) check_function = tmp; } if(check_library != NULL && check_function == NULL) check_function = "passwd_check"; if(check_library == NULL) return; handle = dlopen(check_library, RTLD_NOW); if(handle == NULL) { krb5_warnx(context, "failed to open `%s'", check_library); return; } version = (int *) dlsym(handle, "version"); if(version == NULL) { krb5_warnx(context, "didn't find `version' symbol in `%s'", check_library); dlclose(handle); return; } if(*version != KADM5_PASSWD_VERSION_V0) { krb5_warnx(context, "version of loaded library is %d (expected %d)", *version, KADM5_PASSWD_VERSION_V0); dlclose(handle); return; } sym = dlsym(handle, check_function); if(sym == NULL) { krb5_warnx(context, "didn't find `%s' symbol in `%s'", check_function, check_library); dlclose(handle); return; } passwd_quality_check = (kadm5_passwd_quality_check_func_v0) sym; #endif /* HAVE_DLOPEN */ }
void grp_teardown(void) { if(dl_handle) dlclose(dl_handle); }
void RemoveApplication(nsINIParser& parser, const char* curExeDir, const char* profile) { if (!isProfileOverridden) { // Remove the desktop entry file. char desktopEntryFilePath[MAXPATHLEN]; char* dataDir = getenv("XDG_DATA_HOME"); if (dataDir && *dataDir) { snprintf(desktopEntryFilePath, MAXPATHLEN, "%s/applications/owa-%s.desktop", dataDir, profile); } else { char* home = getenv("HOME"); snprintf(desktopEntryFilePath, MAXPATHLEN, "%s/.local/share/applications/owa-%s.desktop", home, profile); } unlink(desktopEntryFilePath); } // Remove the files from the installation directory. char webAppIniPath[MAXPATHLEN]; snprintf(webAppIniPath, MAXPATHLEN, "%s/%s", curExeDir, kWEBAPP_INI); unlink(webAppIniPath); char curExePath[MAXPATHLEN]; snprintf(curExePath, MAXPATHLEN, "%s/%s", curExeDir, kAPP_RT); unlink(curExePath); char webAppJsonPath[MAXPATHLEN]; snprintf(webAppJsonPath, MAXPATHLEN, "%s/%s", curExeDir, kWEBAPP_JSON); unlink(webAppJsonPath); char iconPath[MAXPATHLEN]; snprintf(iconPath, MAXPATHLEN, "%s/icon.png", curExeDir); unlink(iconPath); char packagePath[MAXPATHLEN]; snprintf(packagePath, MAXPATHLEN, "%s/%s", curExeDir, kWEBAPP_PACKAGE); unlink(packagePath); char appName[MAXPATHLEN]; if (NS_FAILED(parser.GetString("Webapp", "Name", appName, MAXPATHLEN))) { strcpy(appName, profile); } char uninstallMsg[MAXPATHLEN]; if (NS_SUCCEEDED(parser.GetString("Webapp", "UninstallMsg", uninstallMsg, MAXPATHLEN))) { /** * The only difference between libnotify.so.4 and libnotify.so.1 for these symbols * is that notify_notification_new takes three arguments in libnotify.so.4 and * four in libnotify.so.1. * Passing the fourth argument as nullptr is binary compatible. */ typedef void (*notify_init_t)(const char*); typedef void* (*notify_notification_new_t)(const char*, const char*, const char*, const char*); typedef void (*notify_notification_show_t)(void*, void**); void *handle = dlopen("libnotify.so.4", RTLD_LAZY); if (!handle) { handle = dlopen("libnotify.so.1", RTLD_LAZY); if (!handle) return; } notify_init_t nn_init = (notify_init_t)(uintptr_t)dlsym(handle, "notify_init"); notify_notification_new_t nn_new = (notify_notification_new_t)(uintptr_t)dlsym(handle, "notify_notification_new"); notify_notification_show_t nn_show = (notify_notification_show_t)(uintptr_t)dlsym(handle, "notify_notification_show"); if (!nn_init || !nn_new || !nn_show) { dlclose(handle); return; } nn_init(appName); void* n = nn_new(uninstallMsg, nullptr, "dialog-information", nullptr); nn_show(n, nullptr); dlclose(handle); } }
void SplashFreeLibrary() { if (hSplashLib) { dlclose(hSplashLib); hSplashLib = NULL; } }
/** ** \fn ~Plugin() ** \brief Destructeur du plugin */ Plugin::~Plugin() { if (this->_lib != NULL) dlclose(this->_lib); }
static int do_test (void) { #ifdef USE_TLS static const char modname1[] = "tst-tlsmod3.so"; static const char modname2[] = "tst-tlsmod4.so"; int result = 0; int (*fp1) (void); int (*fp2) (int, int *); void *h1; void *h2; int i; size_t modid1 = (size_t) -1; size_t modid2 = (size_t) -1; int *bazp; for (i = 0; i < 10; ++i) { h1 = dlopen (modname1, RTLD_LAZY); if (h1 == NULL) { printf ("cannot open '%s': %s\n", modname1, dlerror ()); exit (1); } /* Dirty test code here: we peek into a private data structure. We make sure that the module gets assigned the same ID every time. The value of the first round is used. */ #ifdef __UCLIBC__ if (modid1 == (size_t) -1) modid1 = ((struct dyn_elf *) h1)->dyn->l_tls_modid; else if (((struct dyn_elf *)h1)->dyn->l_tls_modid != (size_t) modid1) { printf ("round %d: modid now %zd, initially %zd\n", i, ((struct dyn_elf *)h1)->dyn->l_tls_modid, modid1); result = 1; } #else if (modid1 == (size_t) -1) modid1 = ((struct link_map *) h1)->l_tls_modid; else if (((struct link_map *) h1)->l_tls_modid != modid1) { printf ("round %d: modid now %zd, initially %zd\n", i, ((struct link_map *) h1)->l_tls_modid, modid1); result = 1; } #endif fp1 = dlsym (h1, "in_dso2"); if (fp1 == NULL) { printf ("cannot get symbol 'in_dso2' in %s\n", modname1); exit (1); } result |= fp1 (); h2 = dlopen (modname2, RTLD_LAZY); if (h2 == NULL) { printf ("cannot open '%s': %s\n", modname2, dlerror ()); exit (1); } /* Dirty test code here: we peek into a private data structure. We make sure that the module gets assigned the same ID every time. The value of the first round is used. */ #ifdef __UCLIBC__ if (modid2 == (size_t) -1) modid2 = ((struct dyn_elf *)h2)->dyn->l_tls_modid; else if (((struct dyn_elf *)h2)->dyn->l_tls_modid != (size_t) modid2) { printf ("round %d: modid now %zd, initially %zd\n", i, ((struct dyn_elf *)h2)->dyn->l_tls_modid, modid2); result = 1; } #else if (modid2 == (size_t) -1) modid2 = ((struct link_map *) h2)->l_tls_modid; else if (((struct link_map *) h2)->l_tls_modid != modid2) { printf ("round %d: modid now %zd, initially %zd\n", i, ((struct link_map *) h2)->l_tls_modid, modid2); result = 1; } #endif bazp = dlsym (h2, "baz"); if (bazp == NULL) { printf ("cannot get symbol 'baz' in %s\n", modname2); exit (1); } *bazp = 42 + i; fp2 = dlsym (h2, "in_dso"); if (fp2 == NULL) { printf ("cannot get symbol 'in_dso' in %s\n", modname2); exit (1); } result |= fp2 (42 + i, bazp); dlclose (h1); dlclose (h2); h1 = dlopen (modname1, RTLD_LAZY); if (h1 == NULL) { printf ("cannot open '%s': %s\n", modname1, dlerror ()); exit (1); } /* Dirty test code here: we peek into a private data structure. We make sure that the module gets assigned the same ID every time. The value of the first round is used. */ #ifdef __UCLIBC__ if (((struct dyn_elf *)h1)->dyn->l_tls_modid != modid1) { printf ("round %d: modid now %zd, initially %zd\n", i, ((struct dyn_elf *)h1)->dyn->l_tls_modid, modid1); result = 1; } #else if (((struct link_map *) h1)->l_tls_modid != modid1) { printf ("round %d: modid now %zd, initially %zd\n", i, ((struct link_map *) h1)->l_tls_modid, modid1); result = 1; } #endif fp1 = dlsym (h1, "in_dso2"); if (fp1 == NULL) { printf ("cannot get symbol 'in_dso2' in %s\n", modname1); exit (1); } result |= fp1 (); h2 = dlopen (modname2, RTLD_LAZY); if (h2 == NULL) { printf ("cannot open '%s': %s\n", modname2, dlerror ()); exit (1); } /* Dirty test code here: we peek into a private data structure. We make sure that the module gets assigned the same ID every time. The value of the first round is used. */ #ifdef __UCLIBC__ if (((struct dyn_elf *)h2)->dyn->l_tls_modid != modid2) { printf ("round %d: modid now %zd, initially %zd\n", i, ((struct dyn_elf *)h2)->dyn->l_tls_modid, modid2); result = 1; } #else if (((struct link_map *) h2)->l_tls_modid != modid2) { printf ("round %d: modid now %zd, initially %zd\n", i, ((struct link_map *) h2)->l_tls_modid, modid2); result = 1; } #endif bazp = dlsym (h2, "baz"); if (bazp == NULL) { printf ("cannot get symbol 'baz' in %s\n", modname2); exit (1); } *bazp = 62 + i; fp2 = dlsym (h2, "in_dso"); if (fp2 == NULL) { printf ("cannot get symbol 'in_dso' in %s\n", modname2); exit (1); } result |= fp2 (62 + i, bazp); /* This time the dlclose calls are in reverse order. */ dlclose (h2); dlclose (h1); } return result; #else return 0; #endif }
/** * Setup read functions with either libdvdcss or minimal DVD access. */ int dvdinput_setup(void) { void *dvdcss_library = NULL; #ifdef HAVE_DVDCSS_DVDCSS_H /* linking to libdvdcss */ dvdcss_library = &dvdcss_library; /* Give it some value != NULL */ TRACE(TRACE_INFO, "libdvdread", "Using own dvdcss."); #else /* dlopening libdvdcss */ #ifdef __APPLE__ #define CSS_LIB "libdvdcss.2.dylib" #elif defined(WIN32) #define CSS_LIB "libdvdcss-2.dll" #elif defined(__OS2__) #define CSS_LIB "dvdcss.dll" #else #define CSS_LIB "libdvdcss.so.2" #endif dvdcss_library = dlopen(CSS_LIB, RTLD_LAZY); if(dvdcss_library != NULL) { #if defined(__OpenBSD__) && !defined(__ELF__) || defined(__OS2__) #define U_S "_" #else #define U_S #endif DVDcss_open = (dvdcss_t (*)(const char*)) dlsym(dvdcss_library, U_S "dvdcss_open"); DVDcss_close = (int (*)(dvdcss_t)) dlsym(dvdcss_library, U_S "dvdcss_close"); DVDcss_seek = (int (*)(dvdcss_t, int, int)) dlsym(dvdcss_library, U_S "dvdcss_seek"); DVDcss_read = (int (*)(dvdcss_t, void*, int, int)) dlsym(dvdcss_library, U_S "dvdcss_read"); DVDcss_error = (char* (*)(dvdcss_t)) dlsym(dvdcss_library, U_S "dvdcss_error"); if(dlsym(dvdcss_library, U_S "dvdcss_crack")) { fprintf(stderr, "libdvdread: Old (pre-0.0.2) version of libdvdcss found.\n" "libdvdread: You should get the latest version from " "http://www.videolan.org/\n" ); dlclose(dvdcss_library); dvdcss_library = NULL; } else if(!DVDcss_open || !DVDcss_close || !DVDcss_seek || !DVDcss_read || !DVDcss_error) { fprintf(stderr, "libdvdread: Missing symbols in %s, " "this shouldn't happen !\n", CSS_LIB); dlclose(dvdcss_library); dvdcss_library = NULL; } } #endif /* HAVE_DVDCSS_DVDCSS_H */ if(dvdcss_library != NULL) { /* char *psz_method = getenv( "DVDCSS_METHOD" ); char *psz_verbose = getenv( "DVDCSS_VERBOSE" ); fprintf(stderr, "DVDCSS_METHOD %s\n", psz_method); fprintf(stderr, "DVDCSS_VERBOSE %s\n", psz_verbose); */ /* libdvdcss wrapper functions */ dvdinput_open = css_open; dvdinput_close = css_close; dvdinput_seek = css_seek; dvdinput_title = css_title; dvdinput_read = css_read; dvdinput_error = css_error; return 1; } else { fprintf(stderr, "libdvdread: Encrypted DVD support unavailable.\n"); /* libdvdcss replacement functions */ dvdinput_open = file_open; dvdinput_close = file_close; dvdinput_seek = file_seek; dvdinput_title = file_title; dvdinput_read = file_read; dvdinput_error = file_error; return 0; } }
void msdk_so_free(msdk_so_handle handle) { if (!handle) return; dlclose(handle); }
void *MemoryUtils::ResolveSymbol(void *handle, const char *symbol) { #if defined(WIN32) return GetProcAddress((HMODULE)handle, symbol); #elif defined(__linux__) void *address = dlsym(handle, symbol); if (address != NULL) { return address; } struct link_map *dlmap; struct stat dlstat; int dlfile; uintptr_t map_base; Elf32_Ehdr *file_hdr; Elf32_Shdr *sections, *shstrtab_hdr, *symtab_hdr, *strtab_hdr; Elf32_Sym *symtab; const char *shstrtab, *strtab; uint16_t section_count; uint32_t symbol_count; LibSymbolTable *libtable; SymbolTable *table; Symbol *symbol_entry; dlmap = (struct link_map *)handle; symtab_hdr = NULL; strtab_hdr = NULL; table = NULL; /* See if we already have a symbol table for this library */ for (size_t i = 0; i < m_SymTables.length(); i++) { libtable = m_SymTables[i]; if (libtable->lib_base == dlmap->l_addr) { table = &libtable->table; break; } } /* If we don't have a symbol table for this library, then create one */ if (table == NULL) { libtable = new LibSymbolTable(); libtable->table.Initialize(); libtable->lib_base = dlmap->l_addr; libtable->last_pos = 0; table = &libtable->table; m_SymTables.append(libtable); } /* See if the symbol is already cached in our table */ symbol_entry = table->FindSymbol(symbol, strlen(symbol)); if (symbol_entry != NULL) { return symbol_entry->address; } /* If symbol isn't in our table, then we have open the actual library */ dlfile = open(dlmap->l_name, O_RDONLY); if (dlfile == -1 || fstat(dlfile, &dlstat) == -1) { close(dlfile); return NULL; } /* Map library file into memory */ file_hdr = (Elf32_Ehdr *)mmap(NULL, dlstat.st_size, PROT_READ, MAP_PRIVATE, dlfile, 0); map_base = (uintptr_t)file_hdr; if (file_hdr == MAP_FAILED) { close(dlfile); return NULL; } close(dlfile); if (file_hdr->e_shoff == 0 || file_hdr->e_shstrndx == SHN_UNDEF) { munmap(file_hdr, dlstat.st_size); return NULL; } sections = (Elf32_Shdr *)(map_base + file_hdr->e_shoff); section_count = file_hdr->e_shnum; /* Get ELF section header string table */ shstrtab_hdr = §ions[file_hdr->e_shstrndx]; shstrtab = (const char *)(map_base + shstrtab_hdr->sh_offset); /* Iterate sections while looking for ELF symbol table and string table */ for (uint16_t i = 0; i < section_count; i++) { Elf32_Shdr &hdr = sections[i]; const char *section_name = shstrtab + hdr.sh_name; if (strcmp(section_name, ".symtab") == 0) { symtab_hdr = &hdr; } else if (strcmp(section_name, ".strtab") == 0) { strtab_hdr = &hdr; } } /* Uh oh, we don't have a symbol table or a string table */ if (symtab_hdr == NULL || strtab_hdr == NULL) { munmap(file_hdr, dlstat.st_size); return NULL; } symtab = (Elf32_Sym *)(map_base + symtab_hdr->sh_offset); strtab = (const char *)(map_base + strtab_hdr->sh_offset); symbol_count = symtab_hdr->sh_size / symtab_hdr->sh_entsize; /* Iterate symbol table starting from the position we were at last time */ for (uint32_t i = libtable->last_pos; i < symbol_count; i++) { Elf32_Sym &sym = symtab[i]; unsigned char sym_type = ELF32_ST_TYPE(sym.st_info); const char *sym_name = strtab + sym.st_name; Symbol *cur_sym; /* Skip symbols that are undefined or do not refer to functions or objects */ if (sym.st_shndx == SHN_UNDEF || (sym_type != STT_FUNC && sym_type != STT_OBJECT)) { continue; } /* Caching symbols as we go along */ cur_sym = table->InternSymbol(sym_name, strlen(sym_name), (void *)(dlmap->l_addr + sym.st_value)); if (strcmp(symbol, sym_name) == 0) { symbol_entry = cur_sym; libtable->last_pos = ++i; break; } } munmap(file_hdr, dlstat.st_size); return symbol_entry ? symbol_entry->address : NULL; #elif defined(__APPLE__) uintptr_t dlbase, linkedit_addr; uint32_t image_count; struct mach_header *file_hdr; struct load_command *loadcmds; struct segment_command *linkedit_hdr; struct symtab_command *symtab_hdr; struct nlist *symtab; const char *strtab; uint32_t loadcmd_count; uint32_t symbol_count; LibSymbolTable *libtable; SymbolTable *table; Symbol *symbol_entry; dlbase = 0; image_count = m_ImageList->infoArrayCount; linkedit_hdr = NULL; symtab_hdr = NULL; table = NULL; /* Loop through mach-o images in process. * We can skip index 0 since that is just the executable. */ for (uint32_t i = 1; i < image_count; i++) { const struct dyld_image_info &info = m_ImageList->infoArray[i]; /* "Load" each one until we get a matching handle */ void *h = dlopen(info.imageFilePath, RTLD_NOLOAD); if (h == handle) { dlbase = (uintptr_t)info.imageLoadAddress; dlclose(h); break; } dlclose(h); } if (!dlbase) { /* Uh oh, we couldn't find a matching handle */ return NULL; } /* See if we already have a symbol table for this library */ for (size_t i = 0; i < m_SymTables.length(); i++) { libtable = m_SymTables[i]; if (libtable->lib_base == dlbase) { table = &libtable->table; break; } } /* If we don't have a symbol table for this library, then create one */ if (table == NULL) { libtable = new LibSymbolTable(); libtable->table.Initialize(); libtable->lib_base = dlbase; libtable->last_pos = 0; table = &libtable->table; m_SymTables.append(libtable); } /* See if the symbol is already cached in our table */ symbol_entry = table->FindSymbol(symbol, strlen(symbol)); if (symbol_entry != NULL) { return symbol_entry->address; } /* If symbol isn't in our table, then we have to locate it in memory */ file_hdr = (struct mach_header *)dlbase; loadcmds = (struct load_command *)(dlbase + sizeof(struct mach_header)); loadcmd_count = file_hdr->ncmds; /* Loop through load commands until we find the ones for the symbol table */ for (uint32_t i = 0; i < loadcmd_count; i++) { if (loadcmds->cmd == LC_SEGMENT && !linkedit_hdr) { struct segment_command *seg = (struct segment_command *)loadcmds; if (strcmp(seg->segname, "__LINKEDIT") == 0) { linkedit_hdr = seg; if (symtab_hdr) { break; } } } else if (loadcmds->cmd == LC_SYMTAB) { symtab_hdr = (struct symtab_command *)loadcmds; if (linkedit_hdr) { break; } } /* Load commands are not of a fixed size which is why we add the size */ loadcmds = (struct load_command *)((uintptr_t)loadcmds + loadcmds->cmdsize); } if (!linkedit_hdr || !symtab_hdr || !symtab_hdr->symoff || !symtab_hdr->stroff) { /* Uh oh, no symbol table */ return NULL; } linkedit_addr = dlbase + linkedit_hdr->vmaddr; symtab = (struct nlist *)(linkedit_addr + symtab_hdr->symoff - linkedit_hdr->fileoff); strtab = (const char *)(linkedit_addr + symtab_hdr->stroff - linkedit_hdr->fileoff); symbol_count = symtab_hdr->nsyms; /* Iterate symbol table starting from the position we were at last time */ for (uint32_t i = libtable->last_pos; i < symbol_count; i++) { struct nlist &sym = symtab[i]; /* Ignore the prepended underscore on all symbols, so +1 here */ const char *sym_name = strtab + sym.n_un.n_strx + 1; Symbol *cur_sym; /* Skip symbols that are undefined */ if (sym.n_sect == NO_SECT) { continue; } /* Caching symbols as we go along */ cur_sym = table->InternSymbol(sym_name, strlen(sym_name), (void *)(dlbase + sym.n_value)); if (strcmp(symbol, sym_name) == 0) { symbol_entry = cur_sym; libtable->last_pos = ++i; break; } } return symbol_entry ? symbol_entry->address : NULL; #endif }
void DynLib::close() { dlclose(this->handle); }
unsigned int IOFactory::findPlugins( const std::string &path ) { boost::filesystem::path p( path ); if ( !exists( p ) ) { LOG( Runtime, warning ) << util::MSubject( p.file_string() ) << " not found"; return 0; } if ( !boost::filesystem::is_directory( p ) ) { LOG( Runtime, warning ) << util::MSubject( p.file_string() ) << " is no directory"; return 0; } LOG( Runtime, info ) << "Scanning " << util::MSubject( p ) << " for plugins"; boost::regex pluginFilter( std::string( "^" ) + DL_PREFIX + "isisImageFormat_" + "[[:word:]]+" + DL_SUFFIX + "$" ); unsigned int ret = 0; for ( boost::filesystem::directory_iterator itr( p ); itr != boost::filesystem::directory_iterator(); ++itr ) { if ( boost::filesystem::is_directory( *itr ) )continue; if ( boost::regex_match( itr->path().leaf(), pluginFilter ) ) { const std::string pluginName = itr->path().file_string(); #ifdef WIN32 HINSTANCE handle = LoadLibrary( pluginName.c_str() ); #else void *handle = dlopen( pluginName.c_str(), RTLD_NOW ); #endif if ( handle ) { #ifdef WIN32 image_io::FileFormat* ( *factory_func )() = ( image_io::FileFormat * ( * )() )GetProcAddress( handle, "factory" ); #else image_io::FileFormat* ( *factory_func )() = ( image_io::FileFormat * ( * )() )dlsym( handle, "factory" ); #endif if ( factory_func ) { FileFormatPtr io_class( factory_func(), _internal::pluginDeleter( handle, pluginName ) ); if ( registerFileFormat( io_class ) ) { io_class->plugin_file = pluginName; ret++; } else { LOG( Runtime, warning ) << "failed to register plugin " << util::MSubject( pluginName ); } } else { #ifdef WIN32 LOG( Runtime, warning ) << "could not get format factory function from " << util::MSubject( pluginName ); FreeLibrary( handle ); #else LOG( Runtime, warning ) << "could not get format factory function from " << util::MSubject( pluginName ) << ":" << util::MSubject( dlerror() ); dlclose( handle ); #endif } } else #ifdef WIN32 LOG( Runtime, warning ) << "Could not load library " << util::MSubject( pluginName ); #else LOG( Runtime, warning ) << "Could not load library " << util::MSubject( pluginName ) << ":" << util::MSubject( dlerror() ); #endif } else { LOG( Runtime, verbose_info ) << "Ignoring " << *itr << " because it doesn't match " << pluginFilter.str(); } } return ret; }
ShellAndroid::~ShellAndroid() { cleanup_vk(); dlclose(lib_handle_); }
int module_load(const char *modules_path) { DIR *dir = opendir(modules_path); struct dirent *ent = NULL; void *module_handle = NULL; void (*module_init)() = NULL; if (dir == NULL) { log_error("%s","Error loading modules!\n"); return -1; } char file_path[256]; while ((ent = readdir(dir)) != NULL) { module_t *module = NULL; if (strcmp(ent->d_name, ".") == 0 || strcmp(ent->d_name, "..") == 0) continue; sprintf(file_path, "%s%s/%s%s.so", modules_path, ent->d_name, MODULES_PREFIX, ent->d_name); if (!fs_file_exists(file_path)) { log_error("%s%s%s","Error loading mod_", ent->d_name, ".so. No such file!\n"); continue; } module_handle = dlopen(file_path, RTLD_LAZY); if (module_handle == NULL) { log_error("%s%s%s","Error loading mod_", ent->d_name, ".so. Invalid module!\n"); continue; } module_init = dlsym(module_handle, "init"); if (module_init == NULL) { log_error("%s%s%s","Module mod_", ent->d_name, ".so doesn`t have a init function. Ignoring...!\n"); dlclose(module_handle); continue; } log_message("%s%s\n","Loading module: mod_", ent->d_name); num_modules++; modules = util_alloc(modules, num_modules * sizeof(*module)); if (modules != NULL) { module_init(); module = malloc(sizeof(*module)); if (module != NULL) { module->name = malloc(strlen(ent->d_name) + strlen(MODULES_PREFIX) + 1); sprintf(module->name, "%s%s", MODULES_PREFIX, ent->d_name); module->handle = module_handle; modules[num_modules-1] = module; continue; } } log_message("%s%s\n", "Error allocating memory for module mod_", ent->d_name); dlclose(module_handle); num_modules--; return -1; } closedir(dir); return 0; }
/* ================= Sys_UnloadGame ================= */ void Sys_UnloadCGame (void) { if (cgame_library) dlclose (cgame_library); cgame_library = NULL; }
/* This function loads the collector dll and the relevant functions. * on success: all functions load, iJIT_DLL_is_missing = 0, return value = 1 * on failure: all functions are NULL, iJIT_DLL_is_missing = 1, return value = 0 */ static int loadiJIT_Funcs() { static int bDllWasLoaded = 0; char *dllName = (char*)rcsid; /* !! Just to avoid unused code elimination */ #if ITT_PLATFORM==ITT_PLATFORM_WIN DWORD dNameLength = 0; #endif /* ITT_PLATFORM==ITT_PLATFORM_WIN */ if(bDllWasLoaded) { /* dll was already loaded, no need to do it for the second time */ return 1; } /* Assumes that the DLL will not be found */ iJIT_DLL_is_missing = 1; FUNC_NotifyEvent = NULL; if (m_libHandle) { #if ITT_PLATFORM==ITT_PLATFORM_WIN FreeLibrary(m_libHandle); #else /* ITT_PLATFORM==ITT_PLATFORM_WIN */ dlclose(m_libHandle); #endif /* ITT_PLATFORM==ITT_PLATFORM_WIN */ m_libHandle = NULL; } /* Try to get the dll name from the environment */ #if ITT_PLATFORM==ITT_PLATFORM_WIN dNameLength = GetEnvironmentVariableA(NEW_DLL_ENVIRONMENT_VAR, NULL, 0); if (dNameLength) { DWORD envret = 0; dllName = (char*)malloc(sizeof(char) * (dNameLength + 1)); if(dllName != NULL) { envret = GetEnvironmentVariableA(NEW_DLL_ENVIRONMENT_VAR, dllName, dNameLength); if (envret) { /* Try to load the dll from the PATH... */ m_libHandle = LoadLibraryExA(dllName, NULL, LOAD_WITH_ALTERED_SEARCH_PATH); } free(dllName); } } else { /* Try to use old VS_PROFILER variable */ dNameLength = GetEnvironmentVariableA(DLL_ENVIRONMENT_VAR, NULL, 0); if (dNameLength) { DWORD envret = 0; dllName = (char*)malloc(sizeof(char) * (dNameLength + 1)); if(dllName != NULL) { envret = GetEnvironmentVariableA(DLL_ENVIRONMENT_VAR, dllName, dNameLength); if (envret) { /* Try to load the dll from the PATH... */ m_libHandle = LoadLibraryA(dllName); } free(dllName); } } } #else /* ITT_PLATFORM==ITT_PLATFORM_WIN */ dllName = getenv(NEW_DLL_ENVIRONMENT_VAR); if (!dllName) dllName = getenv(DLL_ENVIRONMENT_VAR); #if defined(__ANDROID__) || defined(ANDROID) if (!dllName) dllName = ANDROID_JIT_AGENT_PATH; #endif if (dllName) { /* Try to load the dll from the PATH... */ m_libHandle = dlopen(dllName, RTLD_LAZY); } #endif /* ITT_PLATFORM==ITT_PLATFORM_WIN */ if (!m_libHandle) { #if ITT_PLATFORM==ITT_PLATFORM_WIN m_libHandle = LoadLibraryA(DEFAULT_DLLNAME); #else /* ITT_PLATFORM==ITT_PLATFORM_WIN */ m_libHandle = dlopen(DEFAULT_DLLNAME, RTLD_LAZY); #endif /* ITT_PLATFORM==ITT_PLATFORM_WIN */ } /* if the dll wasn't loaded - exit. */ if (!m_libHandle) { iJIT_DLL_is_missing = 1; /* don't try to initialize * JIT agent the second time */ return 0; } #if ITT_PLATFORM==ITT_PLATFORM_WIN FUNC_NotifyEvent = (TPNotify)GetProcAddress(m_libHandle, "NotifyEvent"); #else /* ITT_PLATFORM==ITT_PLATFORM_WIN */ FUNC_NotifyEvent = (TPNotify)dlsym(m_libHandle, "NotifyEvent"); #endif /* ITT_PLATFORM==ITT_PLATFORM_WIN */ if (!FUNC_NotifyEvent) { FUNC_Initialize = NULL; return 0; } #if ITT_PLATFORM==ITT_PLATFORM_WIN FUNC_Initialize = (TPInitialize)GetProcAddress(m_libHandle, "Initialize"); #else /* ITT_PLATFORM==ITT_PLATFORM_WIN */ FUNC_Initialize = (TPInitialize)dlsym(m_libHandle, "Initialize"); #endif /* ITT_PLATFORM==ITT_PLATFORM_WIN */ if (!FUNC_Initialize) { FUNC_NotifyEvent = NULL; return 0; } executionMode = (iJIT_IsProfilingActiveFlags)FUNC_Initialize(); bDllWasLoaded = 1; iJIT_DLL_is_missing = 0; /* DLL is ok. */ return 1; }
/* ================= Sys_UnloadUI ================= */ void Sys_UnloadUI(void) { if (ui_library) dlclose (ui_library); ui_library = NULL; }
ExternalFeature::~ExternalFeature() { delete ff_ext; dlclose(lib_handle); }
/** * Try load C API .so/dylib/dll from the specified location and resolve all * the symbols we need. Tries both the new style and legacy name. * * @returns 0 on success, -1 on failure. * @param pszHome The directory where to try load VBoxCAPI/VBoxXPCOMC * from. Can be NULL. * @param fSetAppHome Whether to set the VBOX_APP_HOME env.var. or not * (boolean). */ static int tryLoadLibrary(const char *pszHome, int fSetAppHome) { size_t cchHome = pszHome ? strlen(pszHome) : 0; size_t cbBufNeeded; char szName[4096]; /* * Construct the full name. */ cbBufNeeded = cchHome + sizeof("/" DYNLIB_NAME); if (cbBufNeeded > sizeof(szName)) { setErrMsg(1, "path buffer too small: %u bytes needed", (unsigned)cbBufNeeded); return -1; } if (cchHome) { memcpy(szName, pszHome, cchHome); szName[cchHome] = '/'; cchHome++; } memcpy(&szName[cchHome], DYNLIB_NAME, sizeof(DYNLIB_NAME)); /* * Try load it by that name, setting the VBOX_APP_HOME first (for now). * Then resolve and call the function table getter. */ if (fSetAppHome) { #ifndef WIN32 if (pszHome) setenv("VBOX_APP_HOME", pszHome, 1 /* always override */); else unsetenv("VBOX_APP_HOME"); #endif /* !WIN32 */ } #ifndef WIN32 g_hVBoxCAPI = dlopen(szName, RTLD_NOW | RTLD_LOCAL); if (g_hVBoxCAPI) { PFNVBOXGETCAPIFUNCTIONS pfnGetFunctions; pfnGetFunctions = (PFNVBOXGETCAPIFUNCTIONS)(uintptr_t) dlsym(g_hVBoxCAPI, VBOX_GET_CAPI_FUNCTIONS_SYMBOL_NAME); #ifdef VBOX_GET_XPCOM_FUNCTIONS_SYMBOL_NAME if (!pfnGetFunctions) pfnGetFunctions = (PFNVBOXGETCAPIFUNCTIONS)(uintptr_t) dlsym(g_hVBoxCAPI, VBOX_GET_XPCOM_FUNCTIONS_SYMBOL_NAME); #endif /* VBOX_GET_XPCOM_FUNCTIONS_SYMBOL_NAME */ if (pfnGetFunctions) { g_pVBoxFuncs = pfnGetFunctions(VBOX_CAPI_VERSION); if (g_pVBoxFuncs) { g_pfnGetFunctions = pfnGetFunctions; return 0; } /* bail out */ setErrMsg(1, "%.80s: pfnGetFunctions(%#x) failed", szName, VBOX_CAPI_VERSION); } else setErrMsg(1, "dlsym(%.80s/%.32s): %.128s", szName, VBOX_GET_CAPI_FUNCTIONS_SYMBOL_NAME, dlerror()); dlclose(g_hVBoxCAPI); g_hVBoxCAPI = NULL; } else setErrMsg(0, "dlopen(%.80s): %.160s", szName, dlerror()); #else /* !WIN32 */ g_hVBoxCAPI = LoadLibraryExA(szName, NULL /* hFile */, 0 /* dwFlags */); if (g_hVBoxCAPI) { PFNVBOXGETCAPIFUNCTIONS pfnGetFunctions; pfnGetFunctions = (PFNVBOXGETCAPIFUNCTIONS) GetProcAddress(g_hVBoxCAPI, VBOX_GET_CAPI_FUNCTIONS_SYMBOL_NAME); if (pfnGetFunctions) { g_pVBoxFuncs = pfnGetFunctions(VBOX_CAPI_VERSION); if (g_pVBoxFuncs) { g_pfnGetFunctions = pfnGetFunctions; return 0; } /* bail out */ setErrMsg(1, "%.80s: pfnGetFunctions(%#x) failed", szName, VBOX_CAPI_VERSION); } else setErrMsg(1, "GetProcAddress(%.80s/%.32s): %d", szName, VBOX_GET_CAPI_FUNCTIONS_SYMBOL_NAME, GetLastError()); FreeLibrary(g_hVBoxCAPI); g_hVBoxCAPI = NULL; } else setErrMsg(0, "LoadLibraryEx(%.80s): %d", szName, GetLastError()); #endif /* !WIN32 */ return -1; }
void plugin::closePlugin() { dlclose(this->handle); }
int main () { // Prepare our context and socket zmq::context_t context (1); zmq::socket_t socket (context, ZMQ_REP); socket.bind ("tcp://*:7000"); char dir_buffer[PATH_BUFFER_SIZE]; char* ret = getcwd(dir_buffer, PATH_BUFFER_SIZE); (void) ret; std::string dir(dir_buffer); std::unordered_map<std::string, void*> relations; assert(std::system(NULL)); while (true) { zmq::message_t request; // Wait for next request from client. socket.recv (&request); char* msg = (char*)request.data(); std::cout << "received a message" << std::endl; // Write the message to a file. std::ofstream outfile(CPP_FILE_NAME); outfile << msg; outfile.close(); // Compile the file. std::cout << COMPILE_COMMAND << std::endl; int status = std::system(COMPILE_COMMAND.c_str()); if (status != 0) { replyToClient("FAILURE: compilation errors", socket); continue; } // Open and run the file. void* handle = dlopen((dir + "/" + OBJ_FILE_NAME).c_str(), RTLD_NOW); if (!handle) { std::cerr << "dlopen() error: " << dlerror() << std::endl; return 1; } run_t run = (run_t)dlsym(handle, "run"); char* error = dlerror(); if (error) { std::cerr << "dlsym() error: " << error << std::endl; dlclose(handle); return 1; } std::cout << "successfully compiled and loaded run() function" << std::endl; // Redirect cout while running the file std::streambuf* oldCoutStreamBuf = std::cout.rdbuf(); std::ostringstream strCout; std::cout.rdbuf( strCout.rdbuf() ); run(relations); // Restore old cout std::cout.rdbuf( oldCoutStreamBuf ); dlclose(handle); replyToClient(("SUCCESS: executed file\n" + strCout.str()).c_str(), socket); std::cout << "successfully executed file" << std::endl; } return 0; }
void unloadLADSPAPluginLibrary(void * pvLADSPAPluginLibrary) { dlclose(pvLADSPAPluginLibrary); }
/*=========================================================================== FUNCTION isp_tintless_open DESCRIPTION ===========================================================================*/ static tintless_return_t isp_tintless_bg_pca_open(void ** const res, uint32_t * updates_needed) { tintless_return_t rc = TINTLESS_LIB_NOT_LOADED; dmlroc_version_t v; tintless_lib_t * tintless_lib = NULL; tintless_lib_t ** pp_tintless; char lib_name[BUFF_SIZE_255] = { 0 }; CDBG_TINTLESS("%s : Enter!\n", __func__); if (res != NULL){ pp_tintless = (tintless_lib_t **)res; } else { CDBG_ERROR("%s : res pointer NULL!\n", __func__); goto ERROR; } *pp_tintless = (tintless_lib_t *) malloc(sizeof (tintless_lib_t)); if (*pp_tintless == NULL) { rc = TINTLESS_NO_MEMORY; goto ERROR; } tintless_lib = (tintless_lib_t *) *pp_tintless; memset(tintless_lib, 0, sizeof(tintless_lib_t)); strlcpy(lib_name, "libmmcamera_tintless_bg_pca_algo.so", BUFF_SIZE_255); dlerror(); tintless_lib->plib = dlopen(lib_name, RTLD_NOW); if (!tintless_lib->plib) { CDBG_ERROR("%s:Failed to dlopen %s: %s", __func__, lib_name, dlerror()); goto ERROR; } *(void **)&(tintless_lib->init_func) = dlsym(tintless_lib->plib, "dmlroc_init"); if (!tintless_lib->init_func) CDBG_ERROR("%s:init Failed to dlsym %s: %s", __func__, lib_name, dlerror()); *(void **)&(tintless_lib->update_func) = dlsym(tintless_lib->plib, "dmlroc_entry"); if (!tintless_lib->update_func) CDBG_ERROR("%s:update Failed to dlsym %s: %s", __func__, lib_name, dlerror()); *(void **)&(tintless_lib->get_version_func) = dlsym(tintless_lib->plib, "dmlroc_get_version"); if (!tintless_lib->get_version_func) CDBG_ERROR("%s:version Failed to dlsym %s: %s", __func__, lib_name, dlerror()); *(void **)&(tintless_lib->deinit_func) = dlsym(tintless_lib->plib, "dmlroc_deinit"); if (!tintless_lib->deinit_func) CDBG_ERROR("%s:deinit Failed to dlsym %s: %s", __func__, lib_name, dlerror()); if (!tintless_lib->init_func || !tintless_lib->update_func || !tintless_lib->get_version_func || !tintless_lib->deinit_func) { CDBG_ERROR("%s:Failed to dlsym %s: %s", __func__, lib_name, dlerror()); goto ERROR; } // subscribe to cfg updates *updates_needed = (TINTLESS_UPDATE_STATS | TINTLESS_UPDATE_MESH | TINTLESS_UPDATE_CHROMATIX_PARAMS); tintless_lib->updates = *updates_needed; tintless_lib->cfg.tint_correction_strength = UINT8_MAX; return TINTLESS_SUCCESS; ERROR: if (tintless_lib != NULL) { if (tintless_lib->plib) { dlclose(tintless_lib->plib); } free(tintless_lib); *pp_tintless = NULL; } return rc; } /* isp_tintless_open */
EXTERNALLY_VISIBLE void apc_load(int thread) { static void *handle = NULL; if (handle || apcExtension::PrimeLibrary.empty() || !apcExtension::Enable) { static uint64_t keep_entry_points_around_under_lto; if (++keep_entry_points_around_under_lto == std::numeric_limits<uint64_t>::max()) { // this had better never happen... // Fill out a cache_info to prevent g++ from optimizing out // the calls to const_load_impl* cache_info info; info.a_name = "dummy"; info.use_const = true; const_load(); const_load_impl(&info, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL); const_load_impl_compressed(&info, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL); apc_load_impl(&info, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL); apc_load_impl_compressed(&info, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL); } return; } Timer timer(Timer::WallTime, "loading APC data"); handle = dlopen(apcExtension::PrimeLibrary.c_str(), RTLD_LAZY); if (!handle) { throw Exception("Unable to open apc prime library %s: %s", apcExtension::PrimeLibrary.c_str(), dlerror()); } if (thread <= 1) { apc_load_func(handle, "_apc_load_all")(); } else { int count = ((int(*)())apc_load_func(handle, "_apc_load_count"))(); ApcLoadJobPtrVec jobs; jobs.reserve(count); for (int i = 0; i < count; i++) { jobs.push_back(ApcLoadJobPtr(new ApcLoadJob(handle, i))); } JobDispatcher<ApcLoadJob, ApcLoadWorker>(jobs, thread).run(); } s_apc_store[0].primeDone(); if (apcExtension::EnableConstLoad) { #ifdef USE_JEMALLOC size_t allocated_before = 0; size_t allocated_after = 0; size_t sz = sizeof(size_t); if (mallctl) { uint64_t epoch = 1; mallctl("epoch", NULL, NULL, &epoch, sizeof(epoch)); mallctl("stats.allocated", &allocated_before, &sz, NULL, 0); // Ignore the first result because it may be inaccurate due to internal // allocation. epoch = 1; mallctl("epoch", NULL, NULL, &epoch, sizeof(epoch)); mallctl("stats.allocated", &allocated_before, &sz, NULL, 0); } #endif apc_load_func(handle, "_hphp_const_load_all")(); #ifdef USE_JEMALLOC if (mallctl) { uint64_t epoch = 1; mallctl("epoch", NULL, NULL, &epoch, sizeof(epoch)); sz = sizeof(size_t); mallctl("stats.allocated", &allocated_after, &sz, NULL, 0); s_const_map_size = allocated_after - allocated_before; } #endif } // We've copied all the data out, so close it out. dlclose(handle); }
/* Search just the one directory. */ static void LADSPADirectoryPluginSearch (const char * pcDirectory, LADSPAPluginSearchCallbackFunction fCallbackFunction, void* user_data) { char * pcFilename; DIR * psDirectory; DSSI_Descriptor_Function fDescriptorFunction; long lDirLength; long iNeedSlash; struct dirent * psDirectoryEntry; void * pvPluginHandle; bool is_DSSI = false; lDirLength = strlen(pcDirectory); if (!lDirLength) return; if (pcDirectory[lDirLength - 1] == '/') iNeedSlash = 0; else iNeedSlash = 1; psDirectory = opendir(pcDirectory); if (!psDirectory) return; while (1) { psDirectoryEntry = readdir(psDirectory); if (!psDirectoryEntry) { closedir(psDirectory); return; } pcFilename = malloc(lDirLength + strlen(psDirectoryEntry->d_name) + 1 + iNeedSlash); strcpy(pcFilename, pcDirectory); if (iNeedSlash) strcat(pcFilename, "/"); strcat(pcFilename, psDirectoryEntry->d_name); pvPluginHandle = dlopen(pcFilename, RTLD_LAZY); if (pvPluginHandle) { /* This is a file and the file is a shared library! */ dlerror(); if((fDescriptorFunction = (DSSI_Descriptor_Function)dlsym(pvPluginHandle, "ladspa_descriptor"))) { is_DSSI = false; } else if ((fDescriptorFunction = (DSSI_Descriptor_Function)dlsym(pvPluginHandle, "dssi_descriptor"))) { is_DSSI = true; } if (dlerror() == NULL && fDescriptorFunction) { /* We've successfully found a ladspa_descriptor function. Pass it to the callback function. */ fCallbackFunction(pcFilename, pvPluginHandle, fDescriptorFunction, user_data, is_DSSI); dlclose (pvPluginHandle); } else { /* It was a library, but not a LADSPA one. Unload it. */ dlclose(pcFilename); } } } }
int mtev_load_image(const char *file, const char *name, mtev_hash_table *registry, int (*validate)(mtev_image_t *), size_t obj_size) { char module_file[PATH_MAX]; const char *dlsymname; void *dlhandle = NULL; void *dlsymbol; mtev_image_t *obj; if(file[0] == '/') { strlcpy(module_file, file, sizeof(module_file)); dlhandle = dlopen(module_file, RTLD_LAZY | RTLD_GLOBAL); } else { char *basepath, *base, *brk; if(!mtev_conf_get_string(NULL, "//modules/@directory", &basepath)) basepath = strdup(""); for (base = strtok_r(basepath, ";:", &brk); base; base = strtok_r(NULL, ";:", &brk)) { snprintf(module_file, sizeof(module_file), "%s/%s.%s", base, file, MODULEEXT); dlhandle = dlopen(module_file, RTLD_LAZY | RTLD_GLOBAL); if(dlhandle) { mtevL(mtev_debug, "Successfully opened image '%s'\n", module_file); break; } else { mtevL(mtev_debug, "Tried to open image '%s' but failed: %s\n", module_file, dlerror()); } } free(basepath); if(!dlhandle) { snprintf(module_file, sizeof(module_file), "%s/%s.%s", MTEV_MODULES_DIR, file, MODULEEXT); dlhandle = dlopen(module_file, RTLD_LAZY | RTLD_GLOBAL); } } if(!dlhandle) { mtevL(mtev_stderr, "Cannot open image '%s': %s\n", module_file, dlerror()); return -1; } dlsymname = strrchr(name, ':'); if(!dlsymname) dlsymname = name; else dlsymname++; dlsymbol = dlsym(dlhandle, dlsymname); if(!dlsymbol) { mtevL(mtev_stderr, "Cannot find '%s' in image '%s': %s\n", dlsymname, module_file, dlerror()); dlclose(dlhandle); return -1; } if(validate(dlsymbol) == -1) { mtevL(mtev_stderr, "I can't understand module %s\n", name); dlclose(dlhandle); return -1; } obj = calloc(1, obj_size); memcpy(obj, dlsymbol, obj_size); obj->opaque_handle = calloc(1, sizeof(struct __extended_image_data)); if(obj->onload && obj->onload(obj)) { free(obj->opaque_handle); free(obj); dlclose(dlhandle); return -1; } char *namecopy = strdup(name); if(!mtev_hash_store(registry, namecopy, strlen(namecopy), obj)) { mtevL(mtev_error, "Attempted to load module %s more than once.\n", name); dlclose(dlhandle); free(namecopy); return -1; } ((struct __extended_image_data *)obj->opaque_handle)->dlhandle = dlhandle; return 0; }
static Handle_Type *dynamic_link_module (SLFUTURE_CONST char *module) { Handle_Type *h; VOID_STAR handle; SLFUTURE_CONST char *err; char filebuf[1024]; char *save_file; char *save_err; int api_version; int *api_version_ptr; #define MAX_MODULE_NAME_SIZE 256 char module_so[MAX_MODULE_NAME_SIZE + 32]; char *module_name; char *file, *pathfile; if (strlen (module) >= MAX_MODULE_NAME_SIZE) { _pSLang_verror (SL_LimitExceeded_Error, "module name too long"); return NULL; } SLsnprintf (module_so, sizeof(module_so), "%s-module.%s", module, SO_SUFFIX); if (Module_Path != NULL) pathfile = SLpath_find_file_in_path (Module_Path, module_so); else pathfile = NULL; if ((pathfile == NULL) && (NULL != (pathfile = _pSLsecure_getenv (MODULE_PATH_ENV_NAME)))) pathfile = SLpath_find_file_in_path (pathfile, module_so); if (pathfile == NULL) pathfile = SLpath_find_file_in_path (MODULE_INSTALL_DIR, module_so); if (pathfile != NULL) file = pathfile; else file = module_so; save_err = NULL; save_file = file; while (1) { #ifndef RTLD_GLOBAL # define RTLD_GLOBAL 0 #endif #ifdef RTLD_NOW handle = (VOID_STAR) dlopen (file, RTLD_NOW | RTLD_GLOBAL); #else handle = (VOID_STAR) dlopen (file, RTLD_LAZY | RTLD_GLOBAL); #endif if (handle != NULL) { if (_pSLang_Load_File_Verbose & SLANG_LOAD_MODULE_VERBOSE) SLang_vmessage ("Importing %s", file); if (save_err != NULL) SLfree (save_err); break; } /* Purify reports that dlerror returns a pointer that generates UMR * errors. There is nothing that I can do about that.... */ if ((NULL == strchr (file, '/')) && (strlen(file) < sizeof(filebuf))) { err = (char *) dlerror (); if (err != NULL) save_err = SLmake_string (err); SLsnprintf (filebuf, sizeof (filebuf), "./%s", file); file = filebuf; continue; } if ((NULL == (err = save_err)) && (NULL == (err = (char *) dlerror ()))) err = "UNKNOWN"; _pSLang_verror (SL_Import_Error, "Error linking to %s: %s", save_file, err); if (save_err != NULL) SLfree (save_err); if (pathfile != NULL) SLfree (pathfile); return NULL; } /* Using SLpath_basename allows, e.g., import ("/path/to/module"); */ module_name = SLpath_basename (module); api_version_ptr = (int *) do_dlsym (handle, file, 0, "SLmodule_%s_api_version", module_name); if (api_version_ptr == NULL) api_version_ptr = (int *) do_dlsym (handle, file, 0, "_SLmodule_%s_api_version", module_name); if (api_version_ptr == NULL) api_version = 0; else api_version = *api_version_ptr; if ((-1 == check_api_version (file, api_version)) || (NULL == (h = allocate_handle_type (module, handle)))) { SLfree (pathfile); /* NULL ok */ dlclose (handle); return NULL; } if (NULL == (h->ns_init_fun = (int (*)(SLCONST char *)) do_dlsym (handle, file, 1, "init_%s_module_ns", module_name))) { SLfree (pathfile); free_handle_type (h); dlclose (handle); return NULL; } h->deinit_fun = (void (*)(void)) do_dlsym (handle, file, 0, "deinit_%s_module", module_name); SLfree (pathfile); /* NULL ok */ h->next = Handle_List; Handle_List = h; return h; }
static void ll_unloadlib (void *lib) { dlclose(lib); }
void *uwsgi_load_plugin(int modifier, char *plugin, char *has_option) { void *plugin_handle = NULL; char *plugin_abs_path = NULL; char *plugin_filename = NULL; int need_free = 0; char *plugin_name = uwsgi_strip(uwsgi_str(plugin)); char *plugin_symbol_name_start; struct uwsgi_plugin *up; char linkpath_buf[1024], linkpath[1024]; int linkpath_size; char *colon = strchr(plugin_name, ':'); if (colon) { colon[0] = 0; modifier = atoi(plugin_name); plugin_name = colon + 1; colon[0] = ':'; } char *init_func = strchr(plugin_name, '|'); if (init_func) { init_func[0] = 0; init_func++; } if (!uwsgi_endswith(plugin_name, "_plugin.so")) { plugin_name = uwsgi_concat2(plugin_name, "_plugin.so"); need_free = 1; } plugin_symbol_name_start = plugin_name; // step 1: check for absolute plugin (stop if it fails) if (strchr(plugin_name, '/')) { #ifdef UWSGI_ELF uwsgi_plugin_parse_section(plugin_name); #endif plugin_handle = dlopen(plugin_name, RTLD_NOW | RTLD_GLOBAL); if (!plugin_handle) { if (!has_option) uwsgi_log("%s\n", dlerror()); goto end; } plugin_symbol_name_start = uwsgi_get_last_char(plugin_name, '/'); plugin_symbol_name_start++; plugin_abs_path = plugin_name; goto success; } // step dir, check for user-supplied plugins directory struct uwsgi_string_list *pdir = uwsgi.plugins_dir; while (pdir) { plugin_filename = uwsgi_concat3(pdir->value, "/", plugin_name); #ifdef UWSGI_ELF uwsgi_plugin_parse_section(plugin_filename); #endif plugin_handle = dlopen(plugin_filename, RTLD_NOW | RTLD_GLOBAL); if (plugin_handle) { plugin_abs_path = plugin_filename; //free(plugin_filename); goto success; } free(plugin_filename); plugin_filename = NULL; pdir = pdir->next; } // last step: search in compile-time plugin_dir if (!plugin_handle) { plugin_filename = uwsgi_concat3(UWSGI_PLUGIN_DIR, "/", plugin_name); #ifdef UWSGI_ELF uwsgi_plugin_parse_section(plugin_filename); #endif plugin_handle = dlopen(plugin_filename, RTLD_NOW | RTLD_GLOBAL); plugin_abs_path = plugin_filename; //free(plugin_filename); } success: if (!plugin_handle) { if (!has_option) uwsgi_log("!!! UNABLE to load uWSGI plugin: %s !!!\n", dlerror()); } else { if (init_func) { void (*plugin_init_func)() = dlsym(plugin_handle, init_func); if (plugin_init_func) { plugin_init_func(); } } char *plugin_entry_symbol = uwsgi_concat2n(plugin_symbol_name_start, strlen(plugin_symbol_name_start) - 3, "", 0); up = dlsym(plugin_handle, plugin_entry_symbol); if (!up) { // is it a link ? memset(linkpath_buf, 0, 1024); memset(linkpath, 0, 1024); if ((linkpath_size = readlink(plugin_abs_path, linkpath_buf, 1023)) > 0) { do { linkpath_buf[linkpath_size] = '\0'; strncpy(linkpath, linkpath_buf, linkpath_size + 1); } while ((linkpath_size = readlink(linkpath, linkpath_buf, 1023)) > 0); #ifdef UWSGI_DEBUG uwsgi_log("%s\n", linkpath); #endif free(plugin_entry_symbol); char *slash = uwsgi_get_last_char(linkpath, '/'); if (!slash) { slash = linkpath; } else { slash++; } plugin_entry_symbol = uwsgi_concat2n(slash, strlen(slash) - 3, "", 0); up = dlsym(plugin_handle, plugin_entry_symbol); } } if (up) { if (!up->name) { uwsgi_log("the loaded plugin (%s) has no .name attribute\n", plugin_name); if (dlclose(plugin_handle)) { uwsgi_error("dlclose()"); } if (need_free) free(plugin_name); if (plugin_filename) free(plugin_filename); free(plugin_entry_symbol); return NULL; } if (plugin_already_loaded(up->name)) { if (dlclose(plugin_handle)) { uwsgi_error("dlclose()"); } if (need_free) free(plugin_name); if (plugin_filename) free(plugin_filename); free(plugin_entry_symbol); return NULL; } if (has_option) { struct uwsgi_option *op = up->options; int found = 0; while (op && op->name) { if (!strcmp(has_option, op->name)) { found = 1; break; } op++; } if (!found) { if (dlclose(plugin_handle)) { uwsgi_error("dlclose()"); } if (need_free) free(plugin_name); if (plugin_filename) free(plugin_filename); free(plugin_entry_symbol); return NULL; } } if (modifier != -1) { fill_plugin_table(modifier, up); up->modifier1 = modifier; } else { fill_plugin_table(up->modifier1, up); } if (need_free) free(plugin_name); if (plugin_filename) free(plugin_filename); free(plugin_entry_symbol); if (up->on_load) up->on_load(); return plugin_handle; } if (!has_option) uwsgi_log("%s\n", dlerror()); } end: if (need_free) free(plugin_name); if (plugin_filename) free(plugin_filename); return NULL; }