extern "C" FUNC_RET_TYPE FUNC_NAME(ARGS_WITH_NAME){ typedef FUNC_RET_TYPE (*orig_func_type)(ARGS_WITHOUT_NAME); static orig_func_type orig_func; void * handle; FUNC_RET_TYPE ret; void *eip = 0; if (!orig_func) { if(!(handle=dlopen("LIB_PATH", RTLD_LAZY))) { perror("dlopen"); puts("here dlopen"); abort(); } orig_func = (orig_func_type) dlsym(handle, "FUNC_NAME"); if(dlerror()) { perror("dlsym"); puts("here dlsym"); abort(); } dlclose(handle); } #ifdef __USE_TERN_RUNTIME if (Space::isApp()) { if (options::DMT) { //fprintf(stderr, "Parrot hook: pid %d self %u calls %s\n", getpid(), (unsigned)pthread_self(), "FUNC_NAME"); #ifdef __NEED_INPUT_INSID if (options::dync_geteip) { Space::enterSys(); eip = get_eip(); Space::exitSys(); } record_rdtsc_op("FUNC_NAME", "START", 0, eip); ret = tern_FUNC_NAME((unsigned)(uint64_t) eip, ARGS_ONLY_NAME); #else ret = tern_FUNC_NAME(ARGS_ONLY_NAME); #endif record_rdtsc_op("FUNC_NAME", "END", 0, eip); return ret; } else {// For performance debugging, by doing this, we are still able to get the sync wait time for non-det mode. if (options::dync_geteip) { Space::enterSys(); eip = get_eip(); Space::exitSys(); } record_rdtsc_op("FUNC_NAME", "START", 0, eip); Space::enterSys(); ret = orig_func(ARGS_ONLY_NAME); Space::exitSys(); record_rdtsc_op("FUNC_NAME", "END", 0, eip); return ret; } } #endif ret = orig_func(ARGS_ONLY_NAME); return ret; }
int uv_os_homedir(char* buffer, size_t* size) { struct passwd pw; struct passwd* result; char* buf; uid_t uid; size_t bufsize; size_t len; long initsize; int r; #if defined(__ANDROID_API__) && __ANDROID_API__ < 21 int (*getpwuid_r)(uid_t, struct passwd*, char*, size_t, struct passwd**); #endif if (buffer == NULL || size == NULL || *size == 0) return -EINVAL; /* Check if the HOME environment variable is set first */ buf = getenv("HOME"); if (buf != NULL) { len = strlen(buf); if (len >= *size) { *size = len; return -ENOBUFS; } memcpy(buffer, buf, len + 1); *size = len; return 0; } #if defined(__ANDROID_API__) && __ANDROID_API__ < 21 getpwuid_r = dlsym(RTLD_DEFAULT, "getpwuid_r"); if (getpwuid_r == NULL) return -ENOSYS; #endif /* HOME is not set, so call getpwuid() */ initsize = sysconf(_SC_GETPW_R_SIZE_MAX); if (initsize <= 0) bufsize = 4096; else bufsize = (size_t) initsize; uid = getuid(); buf = NULL; for (;;) { uv__free(buf); buf = uv__malloc(bufsize); if (buf == NULL) return -ENOMEM; r = getpwuid_r(uid, &pw, buf, bufsize, &result); if (r != ERANGE) break; bufsize *= 2; } if (r != 0) { uv__free(buf); return -r; } if (result == NULL) { uv__free(buf); return -ENOENT; } len = strlen(pw.pw_dir); if (len >= *size) { *size = len; uv__free(buf); return -ENOBUFS; } memcpy(buffer, pw.pw_dir, len + 1); *size = len; uv__free(buf); return 0; }
/* * Loads the game dll */ void * Sys_GetGameAPI(void *parms) { void *(*GetGameAPI)(void *); FILE *fp; char name[MAX_OSPATH]; char *path; char *str_p; #ifdef __APPLE__ const char *gamename = "game.dylib"; #else const char *gamename = "game.so"; #endif setreuid(getuid(), getuid()); setegid(getgid()); if (game_library) { Com_Error(ERR_FATAL, "Sys_GetGameAPI without Sys_UnloadingGame"); } Com_Printf("LoadLibrary(\"%s\")\n", gamename); /* now run through the search paths */ path = NULL; while (1) { path = FS_NextPath(path); if (!path) { return NULL; /* couldn't find one anywhere */ } snprintf(name, MAX_OSPATH, "%s/%s", path, gamename); /* skip it if it just doesn't exist */ fp = fopen(name, "rb"); if (fp == NULL) { continue; } fclose(fp); game_library = dlopen(name, RTLD_NOW); if (game_library) { Com_MDPrintf("LoadLibrary (%s)\n", name); break; } else { Com_Printf("LoadLibrary (%s):", name); path = (char *)dlerror(); str_p = strchr(path, ':'); /* skip the path (already shown) */ if (str_p == NULL) { str_p = path; } else { str_p++; } Com_Printf("%s\n", str_p); return NULL; } } GetGameAPI = (void *)dlsym(game_library, "GetGameAPI"); if (!GetGameAPI) { Sys_UnloadGame(); return NULL; } return GetGameAPI(parms); }
// Initialize X11 display and look for supported X11 extensions // static GLFWbool initExtensions(void) { _glfw.x11.vidmode.handle = dlopen("libXxf86vm.so.1", RTLD_LAZY | RTLD_GLOBAL); if (_glfw.x11.vidmode.handle) { _glfw.x11.vidmode.QueryExtension = (PFN_XF86VidModeQueryExtension) dlsym(_glfw.x11.vidmode.handle, "XF86VidModeQueryExtension"); _glfw.x11.vidmode.GetGammaRamp = (PFN_XF86VidModeGetGammaRamp) dlsym(_glfw.x11.vidmode.handle, "XF86VidModeGetGammaRamp"); _glfw.x11.vidmode.SetGammaRamp = (PFN_XF86VidModeSetGammaRamp) dlsym(_glfw.x11.vidmode.handle, "XF86VidModeSetGammaRamp"); _glfw.x11.vidmode.GetGammaRampSize = (PFN_XF86VidModeGetGammaRampSize) dlsym(_glfw.x11.vidmode.handle, "XF86VidModeGetGammaRampSize"); _glfw.x11.vidmode.available = XF86VidModeQueryExtension(_glfw.x11.display, &_glfw.x11.vidmode.eventBase, &_glfw.x11.vidmode.errorBase); } _glfw.x11.xi.handle = dlopen("libXi.so", RTLD_LAZY | RTLD_GLOBAL); if (_glfw.x11.xi.handle) { _glfw.x11.xi.QueryVersion = (PFN_XIQueryVersion) dlsym(_glfw.x11.xi.handle, "XIQueryVersion"); _glfw.x11.xi.SelectEvents = (PFN_XISelectEvents) dlsym(_glfw.x11.xi.handle, "XISelectEvents"); if (XQueryExtension(_glfw.x11.display, "XInputExtension", &_glfw.x11.xi.majorOpcode, &_glfw.x11.xi.eventBase, &_glfw.x11.xi.errorBase)) { _glfw.x11.xi.major = 2; _glfw.x11.xi.minor = 0; if (XIQueryVersion(_glfw.x11.display, &_glfw.x11.xi.major, &_glfw.x11.xi.minor) == Success) { _glfw.x11.xi.available = GLFW_TRUE; } } } // Check for RandR extension if (XRRQueryExtension(_glfw.x11.display, &_glfw.x11.randr.eventBase, &_glfw.x11.randr.errorBase)) { if (XRRQueryVersion(_glfw.x11.display, &_glfw.x11.randr.major, &_glfw.x11.randr.minor)) { // The GLFW RandR path requires at least version 1.3 if (_glfw.x11.randr.major > 1 || _glfw.x11.randr.minor >= 3) _glfw.x11.randr.available = GLFW_TRUE; } else { _glfwInputError(GLFW_PLATFORM_ERROR, "X11: Failed to query RandR version"); } } if (_glfw.x11.randr.available) { XRRScreenResources* sr = XRRGetScreenResourcesCurrent(_glfw.x11.display, _glfw.x11.root); if (!sr->ncrtc || !XRRGetCrtcGammaSize(_glfw.x11.display, sr->crtcs[0])) { // This is either a headless system or an older Nvidia binary driver // with broken gamma support // Flag it as useless and fall back to Xf86VidMode gamma, if // available _glfwInputError(GLFW_PLATFORM_ERROR, "X11: Detected broken RandR gamma ramp support"); _glfw.x11.randr.gammaBroken = GLFW_TRUE; } if (!sr->ncrtc || !sr->noutput || !sr->nmode) { // This is either a headless system or broken Cygwin/X RandR // Flag it as useless and fall back to Xlib display functions _glfwInputError(GLFW_PLATFORM_ERROR, "X11: Detected broken RandR monitor support"); _glfw.x11.randr.monitorBroken = GLFW_TRUE; } XRRFreeScreenResources(sr); XRRSelectInput(_glfw.x11.display, _glfw.x11.root, RROutputChangeNotifyMask); } if (XineramaQueryExtension(_glfw.x11.display, &_glfw.x11.xinerama.major, &_glfw.x11.xinerama.minor)) { if (XineramaIsActive(_glfw.x11.display)) _glfw.x11.xinerama.available = GLFW_TRUE; } // Check if Xkb is supported on this display _glfw.x11.xkb.major = 1; _glfw.x11.xkb.minor = 0; _glfw.x11.xkb.available = XkbQueryExtension(_glfw.x11.display, &_glfw.x11.xkb.majorOpcode, &_glfw.x11.xkb.eventBase, &_glfw.x11.xkb.errorBase, &_glfw.x11.xkb.major, &_glfw.x11.xkb.minor); if (_glfw.x11.xkb.available) { Bool supported; if (XkbSetDetectableAutoRepeat(_glfw.x11.display, True, &supported)) { if (supported) _glfw.x11.xkb.detectable = GLFW_TRUE; } } _glfw.x11.x11xcb.handle = dlopen("libX11-xcb.so.1", RTLD_LAZY | RTLD_GLOBAL); if (_glfw.x11.x11xcb.handle) { _glfw.x11.x11xcb.XGetXCBConnection = (PFN_XGetXCBConnection) dlsym(_glfw.x11.x11xcb.handle, "XGetXCBConnection"); } // Update the key code LUT // FIXME: We should listen to XkbMapNotify events to track changes to // the keyboard mapping. createKeyTables(); // Detect whether an EWMH-conformant window manager is running detectEWMH(); // String format atoms _glfw.x11.NULL_ = XInternAtom(_glfw.x11.display, "NULL", False); _glfw.x11.UTF8_STRING = XInternAtom(_glfw.x11.display, "UTF8_STRING", False); _glfw.x11.COMPOUND_STRING = XInternAtom(_glfw.x11.display, "COMPOUND_STRING", False); _glfw.x11.ATOM_PAIR = XInternAtom(_glfw.x11.display, "ATOM_PAIR", False); // Custom selection property atom _glfw.x11.GLFW_SELECTION = XInternAtom(_glfw.x11.display, "GLFW_SELECTION", False); // ICCCM standard clipboard atoms _glfw.x11.TARGETS = XInternAtom(_glfw.x11.display, "TARGETS", False); _glfw.x11.MULTIPLE = XInternAtom(_glfw.x11.display, "MULTIPLE", False); _glfw.x11.CLIPBOARD = XInternAtom(_glfw.x11.display, "CLIPBOARD", False); // Clipboard manager atoms _glfw.x11.CLIPBOARD_MANAGER = XInternAtom(_glfw.x11.display, "CLIPBOARD_MANAGER", False); _glfw.x11.SAVE_TARGETS = XInternAtom(_glfw.x11.display, "SAVE_TARGETS", False); // Xdnd (drag and drop) atoms _glfw.x11.XdndAware = XInternAtom(_glfw.x11.display, "XdndAware", False); _glfw.x11.XdndEnter = XInternAtom(_glfw.x11.display, "XdndEnter", False); _glfw.x11.XdndPosition = XInternAtom(_glfw.x11.display, "XdndPosition", False); _glfw.x11.XdndStatus = XInternAtom(_glfw.x11.display, "XdndStatus", False); _glfw.x11.XdndActionCopy = XInternAtom(_glfw.x11.display, "XdndActionCopy", False); _glfw.x11.XdndDrop = XInternAtom(_glfw.x11.display, "XdndDrop", False); _glfw.x11.XdndFinished = XInternAtom(_glfw.x11.display, "XdndFinished", False); _glfw.x11.XdndSelection = XInternAtom(_glfw.x11.display, "XdndSelection", False); _glfw.x11.XdndTypeList = XInternAtom(_glfw.x11.display, "XdndTypeList", False); _glfw.x11.text_uri_list = XInternAtom(_glfw.x11.display, "text/uri-list", False); // ICCCM, EWMH and Motif window property atoms // These can be set safely even without WM support // The EWMH atoms that require WM support are handled in detectEWMH _glfw.x11.WM_PROTOCOLS = XInternAtom(_glfw.x11.display, "WM_PROTOCOLS", False); _glfw.x11.WM_STATE = XInternAtom(_glfw.x11.display, "WM_STATE", False); _glfw.x11.WM_DELETE_WINDOW = XInternAtom(_glfw.x11.display, "WM_DELETE_WINDOW", False); _glfw.x11.NET_WM_ICON = XInternAtom(_glfw.x11.display, "_NET_WM_ICON", False); _glfw.x11.NET_WM_PING = XInternAtom(_glfw.x11.display, "_NET_WM_PING", False); _glfw.x11.NET_WM_PID = XInternAtom(_glfw.x11.display, "_NET_WM_PID", False); _glfw.x11.NET_WM_NAME = XInternAtom(_glfw.x11.display, "_NET_WM_NAME", False); _glfw.x11.NET_WM_ICON_NAME = XInternAtom(_glfw.x11.display, "_NET_WM_ICON_NAME", False); _glfw.x11.NET_WM_BYPASS_COMPOSITOR = XInternAtom(_glfw.x11.display, "_NET_WM_BYPASS_COMPOSITOR", False); _glfw.x11.MOTIF_WM_HINTS = XInternAtom(_glfw.x11.display, "_MOTIF_WM_HINTS", False); return GLFW_TRUE; }
int f_init_func(char *p_option,char *p_mod) { const char *p_error; char *p_modpath=MOD_PATH; char s_module[MAX_BUF]; if(!strcasecmp(p_option,"open-external")) { if (p_mod!=NULL) { memset(s_module,'\0',sizeof(s_module)); tc_snprintf(s_module, sizeof(s_module), "%s/export_%s.so", p_modpath,p_mod); f_ext_handle=dlopen(s_module, RTLD_GLOBAL|RTLD_LAZY); if (!f_ext_handle) { fputs (dlerror(), stderr); dlclose(f_handle); return(1); } tc_export = dlsym(f_ext_handle, "tc_export"); if ((p_error = dlerror()) != NULL) { fputs(p_error, stderr); return(1); } } } else if(!strcasecmp(p_option,"close-external")) { if (f_ext_handle!=NULL) dlclose(f_ext_handle); f_ext_handle=NULL; tc_export=NULL; } else if(!strcasecmp(p_option,"status-external")) { if(f_ext_handle!=NULL) return(1); } else if(!strcasecmp(p_option,"open")) { if (p_mod!=NULL) { tc_accel = ac_cpuinfo(); memset(s_module,'\0',sizeof(s_module)); tc_snprintf(s_module, sizeof(s_module), "%s/export_%s.so", p_modpath,p_mod); f_ext_handle=dlopen(s_module, RTLD_GLOBAL|RTLD_LAZY); if (!f_ext_handle) { fputs (dlerror(), stderr); dlclose(f_handle); return(1); } tc_export = dlsym(f_ext_handle, "tc_export"); if ((p_error = dlerror()) != NULL) { fputs(p_error, stderr); return(1); } } if ((f_handle=f_init_pvm_func("open",NULL))==NULL) return(1); } else if(!strcasecmp(p_option,"close")) { if (f_ext_handle!=NULL) dlclose(f_ext_handle); (void *)f_init_pvm_func("close",f_handle); f_ext_handle=NULL; f_handle=NULL; } else { fprintf(stderr,"(%s) invalid command \"%s\"\n",__FILE__,p_option); return(1); } return(0); }
struct module *module_load(const char *module_name, struct parameters *args) { void *module_handle = NULL; struct module *module = NULL; char *full_module_name; size_t module_name_len; assert(module_name); module_name_len = strlen(HAKA_MODULE_PREFIX) + strlen(module_name) + strlen(HAKA_MODULE_SUFFIX) + 1; full_module_name = malloc(module_name_len); if (!full_module_name) { return NULL; } snprintf(full_module_name, module_name_len, "%s%s%s", HAKA_MODULE_PREFIX, module_name, HAKA_MODULE_SUFFIX); assert(strlen(full_module_name)+1 == module_name_len); { char *current_path = modules_cpath, *iter; char *full_path; while ((iter = strchr(current_path, '*')) != NULL) { const int len = iter - current_path; const size_t full_path_len = len + strlen(full_module_name) + 1; full_path = malloc(full_path_len); if (!full_path) { return NULL; } snprintf(full_path, full_path_len, "%.*s%s", len, current_path, full_module_name); assert(strlen(full_path)+1 == full_path_len); module_handle = dlopen(full_path, RTLD_NOW); current_path = iter+1; if (*current_path != 0) ++current_path; free(full_path); full_path = NULL; if (module_handle) { break; } } } if (!module_handle) { free(full_module_name); error(L"%s", strdup(dlerror())); return NULL; } module = (struct module*)dlsym(module_handle, "HAKA_MODULE"); if (!module) { error(L"%s", strdup(dlerror())); dlclose(module); free(full_module_name); return NULL; } module->handle = module_handle; if (module->api_version != HAKA_API_VERSION) { messagef(HAKA_LOG_INFO, L"core", L"%s: invalid API version", full_module_name); dlclose(module->handle); free(full_module_name); return NULL; } if (atomic_get(&module->ref) == 0) { /* Initialize the module */ if (module->name && module->author) { messagef(HAKA_LOG_INFO, L"core", L"load module '%s', %ls, %ls", full_module_name, module->name, module->author); } else if (module->name || module->author) { messagef(HAKA_LOG_INFO, L"core", L"load module '%s', %ls%ls", full_module_name, module->name ? module->name : L"", module->author ? module->author : L""); } else { messagef(HAKA_LOG_INFO, L"core", L"load module '%s'", full_module_name); } if (module->init(args) || check_error()) { if (check_error()) { error(L"unable to initialize module: %ls", clear_error()); } else { error(L"unable to initialize module"); } dlclose(module->handle); free(full_module_name); return NULL; } } free(full_module_name); module_addref(module); return module; }
static int display_fill_symbols(display_table_t *device) { void *handle = device->handle; device->func_probe = (display_type_t *(*) (void)) dlsym(handle, device->func_probe_str); device->func_init = (void *(*) (char *, unsigned int)) dlsym(handle, device->func_init_str); device->func_run = (void (*) (void *)) dlsym(handle, device->func_run_str); device->func_done = (void (*) (void *)) dlsym(handle, device->func_done_str); device->func_finish = (void (*) (void *)) dlsym(handle, device->func_finish_str); device->func_getf = (struct video_frame *(*) (void *)) dlsym(handle, device->func_getf_str); device->func_putf = (int (*) (void *, char *)) dlsym(handle, device->func_putf_str); device->func_reconfigure = (int (*)(void *, struct video_desc)) dlsym(handle, device->func_reconfigure_str); device->func_get_property = (int (*)(void *, int, void *, size_t *)) dlsym(handle, device->func_get_property_str); device->func_get_audio_frame = (struct audio_frame *(*) (void *)) dlsym(handle, device->func_get_audio_frame_str); device->func_put_audio_frame = (void (*) (void *, struct audio_frame *)) dlsym(handle, device->func_put_audio_frame_str); device->func_reconfigure_audio = (int (*) (void *, int, int, int)) dlsym(handle, device->func_reconfigure_audio_str); if(!device->func_probe || !device->func_init || !device->func_run || !device->func_done || !device->func_finish || !device->func_getf || !device->func_getf || !device->func_putf || !device->func_reconfigure || !device->func_get_property || !device->func_get_audio_frame || !device->func_put_audio_frame || !device->func_reconfigure_audio) { fprintf(stderr, "Library %s opening error: %s \n", device->library_name, dlerror()); return FALSE; } return TRUE; }
/* * Load the specified plugin and run its init function. * Returns -1 if unable to open the plugin, else it returns * the value from the plugin's init function. */ int group_plugin_load(char *plugin_info) { struct stat sb; char *args, path[PATH_MAX]; char **argv = NULL; int len, rc = -1; /* * Fill in .so path and split out args (if any). */ args = strpbrk(plugin_info, " \t"); if ((args = strpbrk(plugin_info, " \t")) != NULL) { len = snprintf(path, sizeof(path), "%s%.*s", (*plugin_info != '/') ? _PATH_SUDO_PLUGIN_DIR : "", (int)(args - plugin_info), plugin_info); args++; } else { len = snprintf(path, sizeof(path), "%s%s", (*plugin_info != '/') ? _PATH_SUDO_PLUGIN_DIR : "", plugin_info); } if (len <= 0 || len >= sizeof(path)) { warningx("%s%s: %s", (*plugin_info != '/') ? _PATH_SUDO_PLUGIN_DIR : "", plugin_info, strerror(ENAMETOOLONG)); goto done; } /* Sanity check plugin path. */ if (stat(path, &sb) != 0) { warning("%s", path); goto done; } if (sb.st_uid != ROOT_UID) { warningx("%s must be owned by uid %d", path, ROOT_UID); goto done; } if ((sb.st_mode & (S_IWGRP|S_IWOTH)) != 0) { warningx("%s must be only be writable by owner", path); goto done; } /* Open plugin and map in symbol. */ group_handle = dlopen(path, RTLD_LAZY|RTLD_LOCAL); if (!group_handle) { warningx("unable to dlopen %s: %s", path, dlerror()); goto done; } group_plugin = dlsym(group_handle, "group_plugin"); if (group_plugin == NULL) { warningx("unable to find symbol \"group_plugin\" in %s", path); goto done; } if (GROUP_API_VERSION_GET_MAJOR(group_plugin->version) != GROUP_API_VERSION_MAJOR) { warningx("%s: incompatible group plugin major version %d, expected %d", path, GROUP_API_VERSION_GET_MAJOR(group_plugin->version), GROUP_API_VERSION_MAJOR); goto done; } /* * Split args into a vector if specified. */ if (args != NULL) { int ac = 0, wasblank = TRUE; char *cp; for (cp = args; *cp != '\0'; cp++) { if (isblank((unsigned char)*cp)) { wasblank = TRUE; } else if (wasblank) { wasblank = FALSE; ac++; } } if (ac != 0) { argv = emalloc2(ac, sizeof(char *)); ac = 0; for ((cp = strtok(args, " \t")); cp; (cp = strtok(NULL, " \t"))) argv[ac++] = cp; } } rc = (group_plugin->init)(GROUP_API_VERSION, sudo_printf, argv); done: efree(argv); if (rc != TRUE) { if (group_handle != NULL) { dlclose(group_handle); group_handle = NULL; group_plugin = NULL; } } return rc; }
static int sys_do_load_lib(t_canvas *canvas, const char *objectname, const char *path) { char symname[MAXPDSTRING], filename[MAXPDSTRING], dirbuf[MAXPDSTRING], *nameptr, altsymname[MAXPDSTRING]; const char *classname, *cnameptr; void *dlobj; t_xxx makeout = NULL; int i, hexmunge = 0, fd; #ifdef _WIN32 HINSTANCE ntdll; #endif /* NULL-path is only used as a last resort, but we have already tried all paths */ if(!path)return (0); if ((classname = strrchr(objectname, '/'))) classname++; else classname = objectname; for (i = 0, cnameptr = classname; i < MAXPDSTRING-7 && *cnameptr; cnameptr++) { char c = *cnameptr; if ((c>='0' && c<='9') || (c>='A' && c<='Z')|| (c>='a' && c<='z' )|| c == '_') { symname[i] = c; i++; } /* trailing tilde becomes "_tilde" */ else if (c == '~' && cnameptr[1] == 0) { strcpy(symname+i, "_tilde"); i += strlen(symname+i); } else /* anything you can't put in a C symbol is sprintf'ed in hex */ { sprintf(symname+i, "0x%02x", c); i += strlen(symname+i); hexmunge = 1; } } symname[i] = 0; if (hexmunge) { memmove(symname+6, symname, strlen(symname)+1); strncpy(symname, "setup_", 6); } else strcat(symname, "_setup"); #if 0 fprintf(stderr, "lib: %s\n", classname); #endif /* try looking in the path for (objectname).(sys_dllextent) ... */ if ((fd = sys_trytoopenone(path, objectname, sys_dllextent, dirbuf, &nameptr, MAXPDSTRING, 1)) >= 0) goto gotone; /* same, with the more generic sys_dllextent2 */ if ((fd = sys_trytoopenone(path, objectname, sys_dllextent2, dirbuf, &nameptr, MAXPDSTRING, 1)) >= 0) goto gotone; /* next try (objectname)/(classname).(sys_dllextent) ... */ strncpy(filename, objectname, MAXPDSTRING); filename[MAXPDSTRING-2] = 0; strcat(filename, "/"); strncat(filename, classname, MAXPDSTRING-strlen(filename)); filename[MAXPDSTRING-1] = 0; if ((fd = sys_trytoopenone(path, filename, sys_dllextent, dirbuf, &nameptr, MAXPDSTRING, 1)) >= 0) goto gotone; if ((fd = sys_trytoopenone(path, filename, sys_dllextent2, dirbuf, &nameptr, MAXPDSTRING, 1)) >= 0) goto gotone; #ifdef ANDROID /* Android libs have a 'lib' prefix, '.so' suffix and don't allow ~ */ char libname[MAXPDSTRING] = "lib"; strncat(libname, objectname, MAXPDSTRING - 4); int len = strlen(libname); if (libname[len-1] == '~' && len < MAXPDSTRING - 6) { strcpy(libname+len-1, "_tilde"); } if ((fd = sys_trytoopenone(path, libname, ".so", dirbuf, &nameptr, MAXPDSTRING, 1)) >= 0) goto gotone; #endif return (0); gotone: close(fd); class_set_extern_dir(gensym(dirbuf)); /* rebuild the absolute pathname */ strncpy(filename, dirbuf, MAXPDSTRING); filename[MAXPDSTRING-2] = 0; strcat(filename, "/"); strncat(filename, nameptr, MAXPDSTRING-strlen(filename)); filename[MAXPDSTRING-1] = 0; #ifdef _WIN32 { char dirname[MAXPDSTRING], *s, *basename; sys_bashfilename(filename, filename); /* set the dirname as DllDirectory, meaning in the path for loading other DLLs so that dependent libraries can be included in the same folder as the external. SetDllDirectory() needs a minimum supported version of Windows XP SP1 for SetDllDirectory, so WINVER must be 0x0502 */ strncpy(dirname, filename, MAXPDSTRING); s = strrchr(dirname, '\\'); basename = s; if (s && *s) *s = '\0'; if (!SetDllDirectory(dirname)) error("Could not set '%s' as DllDirectory(), '%s' might not load.", dirname, basename); /* now load the DLL for the external */ ntdll = LoadLibrary(filename); if (!ntdll) { verbose(1, "%s: couldn't load", filename); class_set_extern_dir(&s_); return (0); } makeout = (t_xxx)GetProcAddress(ntdll, symname); if (!makeout) makeout = (t_xxx)GetProcAddress(ntdll, "setup"); SetDllDirectory(NULL); /* reset DLL dir to nothing */ } #elif defined(HAVE_LIBDL) || defined(__FreeBSD__) dlobj = dlopen(filename, RTLD_NOW | RTLD_GLOBAL); if (!dlobj) { verbose(1, "%s: %s", filename, dlerror()); class_set_extern_dir(&s_); return (0); } makeout = (t_xxx)dlsym(dlobj, symname); if(!makeout) makeout = (t_xxx)dlsym(dlobj, "setup"); #else #warning "No dynamic loading mechanism specified, \ libdl or WIN32 required for loading externals!" #endif if (!makeout) { verbose(1, "load_object: Symbol \"%s\" not found", symname); class_set_extern_dir(&s_); return 0; } (*makeout)(); class_set_extern_dir(&s_); return (1); }
jboolean cups_init() { void *handle = dlopen(VERSIONED_JNI_LIB_NAME("cups", "2"), RTLD_LAZY | RTLD_GLOBAL); if (handle == NULL) { handle = dlopen(JNI_LIB_NAME("cups"), RTLD_LAZY | RTLD_GLOBAL); if (handle == NULL) { return JNI_FALSE; } } j2d_cupsServer = (fn_cupsServer)dlsym(handle, "cupsServer"); if (j2d_cupsServer == NULL) { dlclose(handle); return JNI_FALSE; } j2d_ippPort = (fn_ippPort)dlsym(handle, "ippPort"); if (j2d_ippPort == NULL) { dlclose(handle); return JNI_FALSE; } j2d_httpConnect = (fn_httpConnect)dlsym(handle, "httpConnect"); if (j2d_httpConnect == NULL) { dlclose(handle); return JNI_FALSE; } j2d_httpClose = (fn_httpClose)dlsym(handle, "httpClose"); if (j2d_httpClose == NULL) { dlclose(handle); return JNI_FALSE; } j2d_cupsGetPPD = (fn_cupsGetPPD)dlsym(handle, "cupsGetPPD"); if (j2d_cupsGetPPD == NULL) { dlclose(handle); return JNI_FALSE; } j2d_ppdOpenFile = (fn_ppdOpenFile)dlsym(handle, "ppdOpenFile"); if (j2d_ppdOpenFile == NULL) { dlclose(handle); return JNI_FALSE; } j2d_ppdClose = (fn_ppdClose)dlsym(handle, "ppdClose"); if (j2d_ppdClose == NULL) { dlclose(handle); return JNI_FALSE; } j2d_ppdFindOption = (fn_ppdFindOption)dlsym(handle, "ppdFindOption"); if (j2d_ppdFindOption == NULL) { dlclose(handle); return JNI_FALSE; } j2d_ppdPageSize = (fn_ppdPageSize)dlsym(handle, "ppdPageSize"); if (j2d_ppdPageSize == NULL) { dlclose(handle); return JNI_FALSE; } return JNI_TRUE; }
MySQLService::MySQLService(bool fatal_necessity) : Service(),mysql_lib_handle(nullptr),serviceHandle(nullptr), library_init(nullptr),library_end(nullptr),select_db(nullptr),close(nullptr),data_seek(nullptr),my_errno(nullptr),error(nullptr), fetch_field_direct(nullptr), fetch_lengths(nullptr),fetch_row(nullptr),free_result(nullptr),init(nullptr),insert_id(nullptr),list_fields(nullptr), list_tables(nullptr),num_fields(nullptr),num_rows(nullptr),options(nullptr),real_connect(nullptr),real_escape_string(nullptr), real_query(nullptr),row_seek(nullptr),row_tell(nullptr),character_set_name(nullptr),set_character_set(nullptr),store_result(nullptr) { if (String::Deflate::available()) { string libdir,libname; if (!Environment::getbenv("OBYX_LIBMYSQLCRSO",libname)) { //legacy method if (Environment::getbenv("OBYX_LIBMYSQLDIR",libdir)) { if (!libdir.empty() && *libdir.rbegin() != '/') libdir.push_back('/'); } libname = SO(libdir,libmysqlclient_r); } mysql_lib_handle = dlopen(libname.c_str(),RTLD_LAZY); if (mysql_lib_handle != nullptr ) { library_init = (int (*)(int, char **,char **)) dlsym(mysql_lib_handle,"mysql_server_init"); library_end = (void (*)()) dlsym(mysql_lib_handle,"mysql_server_end"); select_db = (int (*)(MYSQL*, const char*)) dlsym(mysql_lib_handle,"mysql_select_db"); close = (void (*)(MYSQL*)) dlsym(mysql_lib_handle,"mysql_close"); data_seek = (void (*)(MYSQL_RES*,my_ulonglong)) dlsym(mysql_lib_handle,"mysql_data_seek"); my_errno = (unsigned int (*)(MYSQL*)) dlsym(mysql_lib_handle,"mysql_errno"); error = (const char* (*)(MYSQL*)) dlsym(mysql_lib_handle,"mysql_error"); fetch_field_direct = (MYSQL_FIELD* (*)(MYSQL_RES*,unsigned int)) dlsym(mysql_lib_handle,"mysql_fetch_field_direct"); fetch_lengths = (unsigned long* (*)(MYSQL_RES*)) dlsym(mysql_lib_handle,"mysql_fetch_lengths"); fetch_row = (MYSQL_ROW (*)(MYSQL_RES*)) dlsym(mysql_lib_handle,"mysql_fetch_row"); free_result = (void (*)(MYSQL_RES*)) dlsym(mysql_lib_handle,"mysql_free_result"); init = (MYSQL* (*)(MYSQL*)) dlsym(mysql_lib_handle,"mysql_init"); insert_id = (my_ulonglong (*)(MYSQL*)) dlsym(mysql_lib_handle,"mysql_insert_id"); list_fields = (MYSQL_RES* (*)(MYSQL*, const char*,const char*)) dlsym(mysql_lib_handle,"mysql_list_fields"); list_tables = (MYSQL_RES* (*)(MYSQL*,const char*)) dlsym(mysql_lib_handle,"mysql_list_tables"); num_fields = (unsigned int (*)(MYSQL_RES*)) dlsym(mysql_lib_handle,"mysql_num_fields"); num_rows = (my_ulonglong (*)(MYSQL_RES*)) dlsym(mysql_lib_handle,"mysql_num_rows"); options = (int (*)(MYSQL *,enum mysql_option,const char*)) dlsym(mysql_lib_handle,"mysql_options"); real_connect = (MYSQL* (*)(MYSQL*, const char*,const char*,const char*,const char*, unsigned int,const char*, unsigned long)) dlsym(mysql_lib_handle,"mysql_real_connect"); real_escape_string = (unsigned long (*)(MYSQL*,char*,const char*, unsigned long)) dlsym(mysql_lib_handle,"mysql_real_escape_string"); real_query = (int (*)(MYSQL*, const char*, unsigned long)) dlsym(mysql_lib_handle,"mysql_real_query"); row_seek = (MYSQL_ROW_OFFSET (*)(MYSQL_RES*, MYSQL_ROW_OFFSET)) dlsym(mysql_lib_handle,"mysql_row_seek"); row_tell = (MYSQL_ROW_OFFSET (*)(MYSQL_RES*)) dlsym(mysql_lib_handle,"mysql_row_tell"); character_set_name = (const char* (*)(MYSQL *)) dlsym(mysql_lib_handle,"mysql_character_set_name"); set_character_set = (int (*)(MYSQL*, const char*)) dlsym(mysql_lib_handle,"mysql_set_character_set"); store_result = (MYSQL_RES* (*)(MYSQL*)) dlsym(mysql_lib_handle,"mysql_store_result"); service=true; } else { service=false; if (fatal_necessity) { string msg; char* err = dlerror(); if ( err != nullptr) msg=err; *Logger::log << Log::fatal << Log::LI << "MySQLService error:: Failed to load the " << libname << " dynamic library. " << msg << Log::LO << Log::blockend; } } if (service) { serviceHandle = init(nullptr); if (serviceHandle == nullptr) { service=false; if (fatal_necessity) { *Logger::log << Log::fatal << Log::LI << "MySQLService error:: Failed to initialise a MySQL client service handle." << Log::LO << Log::blockend; } if ( mysql_lib_handle != nullptr ) { if (fatal_necessity) { *Logger::log << " mysql_lib_handle was found."; } dlclose(mysql_lib_handle); mysql_lib_handle = nullptr; } else { if (fatal_necessity) { *Logger::log << " mysql_lib_handle was NOT found."; } } if (fatal_necessity) { *Logger::log << Log::LO << Log::blockend; } } else { unsigned int c_to_secs = 5; unsigned int q_to_secs = 90; options(serviceHandle,MYSQL_READ_DEFAULT_GROUP,"cgi_sql_services"); options(serviceHandle,MYSQL_SET_CHARSET_NAME,"utf8"); options(serviceHandle,MYSQL_OPT_CONNECT_TIMEOUT,(const char *)&c_to_secs); options(serviceHandle,MYSQL_OPT_READ_TIMEOUT,(const char *)&q_to_secs); options(serviceHandle,MYSQL_OPT_WRITE_TIMEOUT,(const char *)&q_to_secs); } } } else { service=false; } }
Task* import_heap_image (const char* fname, Heapcleaner_Args* params) { // ================= // Task* task; Heapfile_Header image_header; Heap_Header heap_header; Val *externs; Pthread_Image image; Inbuf inbuf; if (fname != NULL) { // // Resolve the name of the image. // If the file exists use it, otherwise try the // pathname with the machine ID as an extension. if ((inbuf.file = fopen(fname, "rb"))) { // if (verbosity > 0) say("loading %s ", fname); } else { // if ((inbuf.file = fopen(fname, "rb"))) { // if (verbosity > 0) say("loading %s ", fname); } else { die ("unable to open heap image \"%s\"\n", fname); } } inbuf.needs_to_be_byteswapped = FALSE; inbuf.buf = NULL; inbuf.nbytes = 0; } else { // // fname == NULL, so try to find // an in-core heap image: #if defined(DLOPEN) && !defined(OPSYS_WIN32) // void *lib = dlopen (NULL, RTLD_LAZY); void *vimg, *vimglenptr; if ((vimg = dlsym(lib,HEAP_IMAGE_SYMBOL )) == NULL) die("no in-core heap image found\n"); if ((vimglenptr = dlsym(lib,HEAP_IMAGE_LEN_SYMBOL)) == NULL) die("unable to find length of in-core heap image\n"); inbuf.file = NULL; inbuf.needs_to_be_byteswapped = FALSE; inbuf.base = vimg; inbuf.buf = inbuf.base; inbuf.nbytes = *(long*)vimglenptr; #else die("in-core heap images not implemented\n"); #endif } READ(&inbuf, image_header); if (image_header.byte_order != ORDER) die ("incorrect byte order in heap image\n"); if (image_header.magic != IMAGE_MAGIC) die ("bad magic number (%#x) in heap image\n", image_header.magic); if ((image_header.kind != EXPORT_HEAP_IMAGE) && (image_header.kind != EXPORT_FN_IMAGE)) die ("bad image kind (%d) in heap image\n", image_header.kind); READ(&inbuf, heap_header); // Check for command-line overrides of heap parameters: // if (params->agegroup0_buffer_bytesize == 0) { params->agegroup0_buffer_bytesize = heap_header.agegroup0_buffer_bytesize; } if (params->active_agegroups < heap_header.active_agegroups) { params->active_agegroups = heap_header.active_agegroups; } if (params->oldest_agegroup_keeping_idle_fromspace_buffers < 0) { params->oldest_agegroup_keeping_idle_fromspace_buffers = heap_header.oldest_agegroup_keeping_idle_fromspace_buffers; } task = make_task( FALSE, params ); // make_task def in src/c/main/runtime-state.c // Get the run-time pointers into the heap: // *PTR_CAST( Val*, PERVASIVE_PACKAGE_PICKLE_LIST_REFCELL__GLOBAL ) = heap_header.pervasive_package_pickle_list; // This carefully constructed fake looks like a normal // compiled package from the Mythryl side but actually // links to compile C code -- see the hack in // // src/c/main/load-compiledfiles.c // runtime_package__global = heap_header.runtime_pseudopackage; #ifdef ASM_MATH mathvec__global = heap_header.math_package; #endif externs = heapio__read_externs_table (&inbuf); // Read the externals table. READ(&inbuf, image); // Read and initialize the Mythryl state info. // if (image_header.kind == EXPORT_HEAP_IMAGE) { // Load the live registers: // ASSIGN( POSIX_INTERPROCESS_SIGNAL_HANDLER_REFCELL__GLOBAL, image.posix_interprocess_signal_handler ); // task->argument = image.stdArg; task->fate = image.stdCont; task->current_closure = image.stdClos; task->program_counter = image.pc; task->exception_fate = image.exception_fate; task->current_thread = image.current_thread; // task->callee_saved_registers[0] = image.calleeSave[0]; task->callee_saved_registers[1] = image.calleeSave[1]; task->callee_saved_registers[2] = image.calleeSave[2]; read_heap (&inbuf, &heap_header, task, externs); // Read the Mythryl heap. /* cleaner_messages_are_enabled__global = TRUE; */ // Cleaning messages are on by default for interactive images. } else { // EXPORT_FN_IMAGE Val function_to_run; Val program_name; Val args; // Restore the signal handler: // ASSIGN( POSIX_INTERPROCESS_SIGNAL_HANDLER_REFCELL__GLOBAL, image.posix_interprocess_signal_handler ); // Read the Mythryl heap: // task->argument = image.stdArg; read_heap (&inbuf, &heap_header, task, externs); // Initialize the calling context (taken from run_mythryl_function): // run_mythryl_function def in src/c/main/run-mythryl-code-and-runtime-eventloop.c // function_to_run = task->argument; // task->exception_fate = PTR_CAST( Val, handle_uncaught_exception_closure_v + 1 ); task->current_thread = HEAP_VOID; // task->fate = PTR_CAST( Val, return_to_c_level_c ); task->current_closure = function_to_run; // task->program_counter = task->link_register = GET_CODE_ADDRESS_FROM_CLOSURE( function_to_run ); // Set up the arguments to the imported function: // program_name = make_ascii_string_from_c_string(task, mythryl_program_name__global); args = make_ascii_strings_from_vector_of_c_strings (task, commandline_arguments); REC_ALLOC2(task, task->argument, program_name, args); // debug_say("arg = %#x : [%#x, %#x]\n", task->argument, GET_TUPLE_SLOT_AS_VAL(task->argument, 0), GET_TUPLE_SLOT_AS_VAL(task->argument, 1)); // Cleaner messages are off by // default for spawn_to_disk images: // cleaner_messages_are_enabled__global = FALSE; } FREE( externs ); if (inbuf.file) fclose (inbuf.file); if (verbosity > 0) say(" done\n"); return task; } // fun import_heap_image
int xlator_dynload (xlator_t *xl) { int ret = -1; char *name = NULL; void *handle = NULL; volume_opt_list_t *vol_opt = NULL; GF_VALIDATE_OR_GOTO ("xlator", xl, out); INIT_LIST_HEAD (&xl->volume_options); ret = gf_asprintf (&name, "%s/%s.so", XLATORDIR, xl->type); if (-1 == ret) { gf_log ("xlator", GF_LOG_ERROR, "asprintf failed"); goto out; } ret = -1; gf_log ("xlator", GF_LOG_TRACE, "attempt to load file %s", name); handle = dlopen (name, RTLD_NOW|RTLD_GLOBAL); if (!handle) { gf_log ("xlator", GF_LOG_WARNING, "%s", dlerror ()); goto out; } xl->dlhandle = handle; if (!(xl->fops = dlsym (handle, "fops"))) { gf_log ("xlator", GF_LOG_WARNING, "dlsym(fops) on %s", dlerror ()); goto out; } if (!(xl->cbks = dlsym (handle, "cbks"))) { gf_log ("xlator", GF_LOG_WARNING, "dlsym(cbks) on %s", dlerror ()); goto out; } if (!(*VOID(&xl->init) = dlsym (handle, "init"))) { gf_log ("xlator", GF_LOG_WARNING, "dlsym(init) on %s", dlerror ()); goto out; } if (!(*VOID(&(xl->fini)) = dlsym (handle, "fini"))) { gf_log ("xlator", GF_LOG_WARNING, "dlsym(fini) on %s", dlerror ()); goto out; } if (!(*VOID(&(xl->notify)) = dlsym (handle, "notify"))) { gf_log ("xlator", GF_LOG_TRACE, "dlsym(notify) on %s -- neglecting", dlerror ()); } if (!(xl->dumpops = dlsym (handle, "dumpops"))) { gf_log ("xlator", GF_LOG_TRACE, "dlsym(dumpops) on %s -- neglecting", dlerror ()); } if (!(*VOID(&(xl->mem_acct_init)) = dlsym (handle, "mem_acct_init"))) { gf_log (xl->name, GF_LOG_TRACE, "dlsym(mem_acct_init) on %s -- neglecting", dlerror ()); } if (!(*VOID(&(xl->reconfigure)) = dlsym (handle, "reconfigure"))) { gf_log ("xlator", GF_LOG_TRACE, "dlsym(reconfigure) on %s -- neglecting", dlerror()); } vol_opt = GF_CALLOC (1, sizeof (volume_opt_list_t), gf_common_mt_volume_opt_list_t); if (!vol_opt) { goto out; } if (!(vol_opt->given_opt = dlsym (handle, "options"))) { dlerror (); gf_log (xl->name, GF_LOG_TRACE, "Strict option validation not enforced -- neglecting"); } INIT_LIST_HEAD (&vol_opt->list); list_add_tail (&vol_opt->list, &xl->volume_options); fill_defaults (xl); ret = 0; out: GF_FREE (name); return ret; }
int xlator_volopt_dynload (char *xlator_type, void **dl_handle, volume_opt_list_t *opt_list) { int ret = -1; char *name = NULL; void *handle = NULL; volume_opt_list_t *vol_opt = NULL; GF_VALIDATE_OR_GOTO ("xlator", xlator_type, out); GF_ASSERT (dl_handle); if (*dl_handle) if (dlclose (*dl_handle)) gf_log ("xlator", GF_LOG_WARNING, "Unable to close " "previously opened handle( may be stale)." "Ignoring the invalid handle"); ret = gf_asprintf (&name, "%s/%s.so", XLATORDIR, xlator_type); if (-1 == ret) { gf_log ("xlator", GF_LOG_ERROR, "asprintf failed"); goto out; } ret = -1; gf_log ("xlator", GF_LOG_TRACE, "attempt to load file %s", name); handle = dlopen (name, RTLD_NOW|RTLD_GLOBAL); if (!handle) { gf_log ("xlator", GF_LOG_WARNING, "%s", dlerror ()); goto out; } *dl_handle = handle; vol_opt = GF_CALLOC (1, sizeof (volume_opt_list_t), gf_common_mt_volume_opt_list_t); if (!vol_opt) { goto out; } if (!(vol_opt->given_opt = dlsym (handle, "options"))) { dlerror (); gf_log ("xlator", GF_LOG_DEBUG, "Strict option validation not enforced -- neglecting"); } opt_list->given_opt = vol_opt->given_opt; INIT_LIST_HEAD (&vol_opt->list); list_add_tail (&vol_opt->list, &opt_list->list); ret = 0; out: GF_FREE (name); gf_log ("xlator", GF_LOG_DEBUG, "Returning %d", ret); return ret; }
static ompt_start_tool_result_t * ompt_try_start_tool(unsigned int omp_version, const char *runtime_version) { ompt_start_tool_result_t *ret = NULL; ompt_start_tool_t start_tool = NULL; #if KMP_OS_WINDOWS // Cannot use colon to describe a list of absolute paths on Windows const char *sep = ";"; #else const char *sep = ":"; #endif #if KMP_OS_DARWIN // Try in the current address space ret = ompt_tool_darwin(omp_version, runtime_version); #elif OMPT_HAVE_WEAK_ATTRIBUTE ret = ompt_start_tool(omp_version, runtime_version); #elif OMPT_HAVE_PSAPI ret = ompt_tool_windows(omp_version, runtime_version); #else #error Activation of OMPT is not supported on this platform. #endif if (ret) return ret; // Try tool-libraries-var ICV const char *tool_libs = getenv("OMP_TOOL_LIBRARIES"); if (tool_libs) { char *libs = __kmp_str_format("%s", tool_libs); char *buf; char *fname = __kmp_str_token(libs, sep, &buf); while (fname) { #if KMP_OS_UNIX void *h = dlopen(fname, RTLD_LAZY); if (h) { start_tool = (ompt_start_tool_t)dlsym(h, "ompt_start_tool"); #elif KMP_OS_WINDOWS HMODULE h = LoadLibrary(fname); if (h) { start_tool = (ompt_start_tool_t)GetProcAddress(h, "ompt_start_tool"); #else #error Activation of OMPT is not supported on this platform. #endif if (start_tool && (ret = (*start_tool)(omp_version, runtime_version))) break; } fname = __kmp_str_token(NULL, sep, &buf); } __kmp_str_free(&libs); } return ret; } void ompt_pre_init() { //-------------------------------------------------- // Execute the pre-initialization logic only once. //-------------------------------------------------- static int ompt_pre_initialized = 0; if (ompt_pre_initialized) return; ompt_pre_initialized = 1; //-------------------------------------------------- // Use a tool iff a tool is enabled and available. //-------------------------------------------------- const char *ompt_env_var = getenv("OMP_TOOL"); tool_setting_e tool_setting = omp_tool_error; if (!ompt_env_var || !strcmp(ompt_env_var, "")) tool_setting = omp_tool_unset; else if (OMPT_STR_MATCH(ompt_env_var, "disabled")) tool_setting = omp_tool_disabled; else if (OMPT_STR_MATCH(ompt_env_var, "enabled")) tool_setting = omp_tool_enabled; #if OMPT_DEBUG printf("ompt_pre_init(): tool_setting = %d\n", tool_setting); #endif switch (tool_setting) { case omp_tool_disabled: break; case omp_tool_unset: case omp_tool_enabled: //-------------------------------------------------- // Load tool iff specified in environment variable //-------------------------------------------------- ompt_start_tool_result = ompt_try_start_tool(__kmp_openmp_version, ompt_get_runtime_version()); memset(&ompt_enabled, 0, sizeof(ompt_enabled)); break; case omp_tool_error: fprintf(stderr, "Warning: OMP_TOOL has invalid value \"%s\".\n" " legal values are (NULL,\"\",\"disabled\"," "\"enabled\").\n", ompt_env_var); break; } #if OMPT_DEBUG printf("ompt_pre_init(): ompt_enabled = %d\n", ompt_enabled); #endif } void ompt_post_init() { //-------------------------------------------------- // Execute the post-initialization logic only once. //-------------------------------------------------- static int ompt_post_initialized = 0; if (ompt_post_initialized) return; ompt_post_initialized = 1; //-------------------------------------------------- // Initialize the tool if so indicated. //-------------------------------------------------- if (ompt_start_tool_result) { ompt_enabled.enabled = !!ompt_start_tool_result->initialize( ompt_fn_lookup, &(ompt_start_tool_result->tool_data)); if (!ompt_enabled.enabled) { // tool not enabled, zero out the bitmap, and done memset(&ompt_enabled, 0, sizeof(ompt_enabled)); return; } ompt_thread_t *root_thread = ompt_get_thread(); ompt_set_thread_state(root_thread, omp_state_overhead); if (ompt_enabled.ompt_callback_thread_begin) { ompt_callbacks.ompt_callback(ompt_callback_thread_begin)( ompt_thread_initial, __ompt_get_thread_data_internal()); } ompt_data_t *task_data; __ompt_get_task_info_internal(0, NULL, &task_data, NULL, NULL, NULL); if (ompt_enabled.ompt_callback_task_create) { ompt_callbacks.ompt_callback(ompt_callback_task_create)( NULL, NULL, task_data, ompt_task_initial, 0, NULL); } ompt_set_thread_state(root_thread, omp_state_work_serial); } } void ompt_fini() { if (ompt_enabled.enabled) { ompt_start_tool_result->finalize(&(ompt_start_tool_result->tool_data)); } memset(&ompt_enabled, 0, sizeof(ompt_enabled)); } /***************************************************************************** * interface operations ****************************************************************************/ /***************************************************************************** * state ****************************************************************************/ OMPT_API_ROUTINE int ompt_enumerate_states(int current_state, int *next_state, const char **next_state_name) { const static int len = sizeof(omp_state_info) / sizeof(omp_state_info_t); int i = 0; for (i = 0; i < len - 1; i++) { if (omp_state_info[i].state_id == current_state) { *next_state = omp_state_info[i + 1].state_id; *next_state_name = omp_state_info[i + 1].state_name; return 1; } } return 0; } OMPT_API_ROUTINE int ompt_enumerate_mutex_impls(int current_impl, int *next_impl, const char **next_impl_name) { const static int len = sizeof(kmp_mutex_impl_info) / sizeof(kmp_mutex_impl_info_t); int i = 0; for (i = 0; i < len - 1; i++) { if (kmp_mutex_impl_info[i].id != current_impl) continue; *next_impl = kmp_mutex_impl_info[i + 1].id; *next_impl_name = kmp_mutex_impl_info[i + 1].name; return 1; } return 0; } /***************************************************************************** * callbacks ****************************************************************************/ OMPT_API_ROUTINE int ompt_set_callback(ompt_callbacks_t which, ompt_callback_t callback) { switch (which) { #define ompt_event_macro(event_name, callback_type, event_id) \ case event_name: \ if (ompt_event_implementation_status(event_name)) { \ ompt_callbacks.ompt_callback(event_name) = (callback_type)callback; \ ompt_enabled.event_name = (callback != 0); \ } \ if (callback) \ return ompt_event_implementation_status(event_name); \ else \ return ompt_set_always; FOREACH_OMPT_EVENT(ompt_event_macro) #undef ompt_event_macro default: return ompt_set_error; } } OMPT_API_ROUTINE int ompt_get_callback(ompt_callbacks_t which, ompt_callback_t *callback) { switch (which) { #define ompt_event_macro(event_name, callback_type, event_id) \ case event_name: \ if (ompt_event_implementation_status(event_name)) { \ ompt_callback_t mycb = \ (ompt_callback_t)ompt_callbacks.ompt_callback(event_name); \ if (mycb) { \ *callback = mycb; \ return ompt_get_callback_success; \ } \ } \ return ompt_get_callback_failure; FOREACH_OMPT_EVENT(ompt_event_macro) #undef ompt_event_macro default: return ompt_get_callback_failure; } } /***************************************************************************** * parallel regions ****************************************************************************/ OMPT_API_ROUTINE int ompt_get_parallel_info(int ancestor_level, ompt_data_t **parallel_data, int *team_size) { return __ompt_get_parallel_info_internal(ancestor_level, parallel_data, team_size); } OMPT_API_ROUTINE omp_state_t ompt_get_state(omp_wait_id_t *wait_id) { omp_state_t thread_state = __ompt_get_state_internal(wait_id); if (thread_state == omp_state_undefined) { thread_state = omp_state_work_serial; } return thread_state; }
int main(int argc, char *argv[]) { int opt, c_flag = 0; CK_SLOT_ID slot_id = 0; char *so_pin = NULL, *user_pin = NULL, *data_store = NULL; CK_FUNCTION_LIST *funcs; CK_ULONG slot_count; CK_SESSION_HANDLE sess; CK_RV rv; struct object *objs_to_migrate = NULL, *tmp, *to_free; int exit_code = 0, rc; lib_csulcca = dlopen("libcsulcca.so", (RTLD_GLOBAL | RTLD_NOW)); if (lib_csulcca == NULL) { print_error("Couldn't get a handle to the CCA library."); return NULL; } CSNDKTC = dlsym(lib_csulcca, "CSNDKTC_32"); CSNBKTC = dlsym(lib_csulcca, "CSNBKTC_32"); while ((opt = getopt(argc, argv, "c:d:s:u:nvh")) != -1) { switch (opt) { case 'c': c_flag++; slot_id = atoi(optarg); break; case 'd': data_store = strdup(optarg); break; case 's': so_pin = strdup(optarg); break; case 'u': user_pin = strdup(optarg); break; case 'n': n_flag++; break; case 'v': v_flag++; break; case 'h': usage(argv[0]); return 0; default: usage(argv[0]); return 1; } } if (!c_flag || !data_store || !so_pin || !user_pin) { usage(argv[0]); return 1; } if (n_flag) printf("Dry-run of migration in progress\n"); funcs = p11_init(); if (!funcs) { return 2; } rv = funcs->C_GetSlotList(TRUE, NULL_PTR, &slot_count); if (rv != CKR_OK) { p11_error("C_GetSlotList", rv); exit_code = 3; goto finalize; } if (slot_id >= slot_count) { print_error("%lu is not a valid slot ID.", slot_id); exit_code = 4; goto finalize; } if (v_flag > 1) printf("Slot id %lu is valid\n", slot_id); /* Open a r/w session */ rv = funcs->C_OpenSession(slot_id, CKF_RW_SESSION|CKF_SERIAL_SESSION, NULL_PTR, NULL_PTR, &sess); if (rv != CKR_OK) { p11_error("C_OpenSession", rv); exit_code = 5; goto finalize; } if (v_flag > 1) printf("PKCS#11 r/w session opened\n"); /* Login as the SO just validate the supplied pin */ rv = funcs->C_Login(sess, CKU_SO, (CK_BYTE *)so_pin, strlen(so_pin)); if (rv != CKR_OK) { p11_error("C_Login (SO)", rv); exit_code = 6; goto finalize; } if (v_flag > 1) printf("PKCS#11 SO login successful\n"); /* Logout the SO */ rv = funcs->C_Logout(sess); if (rv != CKR_OK) { p11_error("C_Logout", rv); exit_code = 7; goto finalize; } /* Login as the USER to validate the supplied pin and do the migration */ rv = funcs->C_Login(sess, CKU_USER, (CK_BYTE *)user_pin, strlen(user_pin)); if (rv != CKR_OK) { p11_error("C_Login (USER)", rv); exit_code = 8; goto finalize; } if (v_flag > 1) printf("PKCS#11 USER login successful\n"); /* Find the affected PKCS#11 objects */ rc = find_opaque_objects(funcs, sess, &objs_to_migrate); if (rc) { exit_code = 9; goto close; } /* XXX Print status: migrating X pub keys, X priv keys, X 3DES keys... */ /* Use the CCA lib to migrate them to the new master key */ rv = migrate_objects(objs_to_migrate); if (rv != CKR_OK) { exit_code = 10; goto close; } /* XXX Print status */ /* Delete the old PKCS#11 objects (or just attribs if possible) and replace with the * migrated data */ rc = replace_objects(funcs, sess, objs_to_migrate); if (rc) { exit_code = 11; goto close; } /* XXX Print status: X objects successfully migrated */ /* Free the list of PKCS#11 objects */ for (to_free = objs_to_migrate; to_free; to_free = tmp) { tmp = to_free->next; free(to_free->opaque_attr); free(to_free); } /* Migrate the keys used to encrypt the data store */ rc = migrate_master_keys(so_pin, user_pin, data_store); if (rc) { exit_code = 12; goto close; } close: funcs->C_CloseSession(sess); finalize: p11_fini(funcs); return exit_code; }
AbaqusUmatMaterial::AbaqusUmatMaterial(const std::string & name, InputParameters parameters) : SolidModel( name, parameters ), _plugin(getParam<FileName>("plugin")), _mechanical_constants(getParam<std::vector<Real> >("mechanical_constants")), _thermal_constants(getParam<std::vector<Real> >("thermal_constants")), _num_state_vars(getParam<unsigned int>("num_state_vars")), _grad_disp_x(coupledGradient("disp_x")), _grad_disp_y(coupledGradient("disp_y")), _grad_disp_z(coupledGradient("disp_z")), _grad_disp_x_old(coupledGradientOld("disp_x")), _grad_disp_y_old(coupledGradientOld("disp_y")), _grad_disp_z_old(coupledGradientOld("disp_z")), _state_var(declareProperty<std::vector<Real> >("state_var")), _state_var_old(declarePropertyOld<std::vector<Real> >("state_var")), _Fbar(declareProperty<ColumnMajorMatrix>("Fbar")), _Fbar_old(declarePropertyOld<ColumnMajorMatrix>("Fbar")), _elastic_strain_energy(declareProperty<Real>("elastic_strain_energy")), _plastic_dissipation(declareProperty<Real>("plastic_dissipation")), _creep_dissipation(declareProperty<Real>("creep_dissipation")) { #if defined(METHOD) _plugin += std::string("-") + QUOTE(METHOD) + ".plugin"; #endif //Size and create full (mechanical+thermal) material property array _num_props = _mechanical_constants.size() + _thermal_constants.size(); std::vector<Real> props_array(_num_props); for (unsigned int i=0; i<_mechanical_constants.size(); ++i) props_array[i] = _mechanical_constants[i]; for (unsigned int i=_mechanical_constants.size(); i<_num_props; ++i) props_array[i] = _thermal_constants[i]; //Read mesh dimension and size UMAT arrays if (_mesh.dimension()==3) //3D case { _NTENS=6; //Size of the stress or strain component array (NDI+NSHR) _NSHR=3; //Number of engineering shear stress components _NDI=3; //Number of direct stress components (always 3) } else if (_mesh.dimension()==2) //2D case { _NTENS=4; _NSHR=1; _NDI=3; } _STATEV = new Real[_num_state_vars]; _DDSDDT = new Real[_NTENS]; _DRPLDE = new Real[_NTENS]; _STRAN = new Real[_NTENS]; _DFGRD0 = new Real[9]; _DFGRD1 = new Real[9]; _STRESS = new Real[_NTENS]; _DDSDDE = new Real[_NTENS*_NTENS]; _DSTRAN = new Real[_NTENS]; _PROPS = new Real[_num_props]; for (unsigned int i=0; i<_num_state_vars; ++i) { _STATEV[i] = 0.0; } for (int i=0; i<_NTENS; ++i) { _DDSDDT[i] = 0.0; _DRPLDE[i] = 0.0; _STRAN[i] = 0.0; _STRESS[i] = 0.0; _DSTRAN[i] = 0.0; } for (unsigned int i=0; i<9; ++i) { _DFGRD0[i] = 0.0; _DFGRD1[i] = 0.0; } for (int i=0; i<_NTENS*_NTENS; ++i) { _DDSDDE[i] = 0.0; } //Assign materials properties from vector form into an array for (unsigned int i=0; i<_num_props; ++i) { _PROPS[i] = props_array[i]; } //Size UMAT state variable (NSTATV) and material constant (NPROPS) arrays _NSTATV = _num_state_vars; _NPROPS = _num_props; // Open the library _handle = dlopen(_plugin.c_str(), RTLD_LAZY); if (!_handle) { std::ostringstream error; error << "Cannot open library: " << dlerror() << '\n'; mooseError(error.str()); } // Reset errors dlerror(); // Snag the function pointer from the library { void * pointer = dlsym(_handle, "umat_"); _umat = *reinterpret_cast<umat_t*>( &pointer ); } // Catch errors const char *dlsym_error = dlerror(); if (dlsym_error) { dlclose(_handle); std::ostringstream error; error << "Cannot load symbol 'umat_': " << dlsym_error << '\n'; mooseError(error.str()); } }
static int ibm_xlsmp_1_6_GetOpenMPHookPoints (int rank) { int count = 0; UNREFERENCED_PARAMETER(rank) /* Obtain @ for _xlsmpParallelDoSetup_TPO */ _xlsmpParallelDoSetup_TPO_real = (void(*)(int,void**,long,long,long,long,void**,void**,void**,long,long,void**,long)) dlsym (RTLD_NEXT, "_xlsmpParallelDoSetup_TPO"); INC_IF_NOT_NULL(_xlsmpParallelDoSetup_TPO_real,count); /* Obtain @ for _xlsmpParRegionSetup_TPO */ _xlsmpParRegionSetup_TPO_real = (void(*)(int,void*,int,void*,void*,void**,long,long)) dlsym (RTLD_NEXT, "_xlsmpParRegionSetup_TPO"); INC_IF_NOT_NULL(_xlsmpParRegionSetup_TPO_real,count); /* Obtain @ for _xlsmpWSDoSetup_TPO */ _xlsmpWSDoSetup_TPO_real = (void(*)(int,void*,long,long,long,long,void*,void*,void**,long)) dlsym (RTLD_NEXT, "_xlsmpWSDoSetup_TPO"); INC_IF_NOT_NULL(_xlsmpWSDoSetup_TPO_real,count); /* Obtain @ for _xlsmpWSSectSetup_TPO */ _xlsmpWSSectSetup_TPO_real = (void(*)(int,void*,long,void*,void*,void**,long,long)) dlsym (RTLD_NEXT, "_xlsmpWSSectSetup_TPO"); INC_IF_NOT_NULL(_xlsmpWSSectSetup_TPO_real,count); /* Obtain @ for _xlsmpSingleSetup_TPO */ _xlsmpSingleSetup_TPO_real = (void(*)(int,void*,int,void*)) dlsym (RTLD_NEXT, "_xlsmpSingleSetup_TPO"); INC_IF_NOT_NULL(_xlsmpSingleSetup_TPO_real,count); /* Obtain @ for _xlsmpBarrier_TPO */ _xlsmpBarrier_TPO_real = (void(*)(int,int*)) dlsym (RTLD_NEXT, "_xlsmpBarrier_TPO"); INC_IF_NOT_NULL(_xlsmpBarrier_TPO_real,count); /* Obtain @ for _xlsmpGetDefaultSLock */ _xlsmpGetDefaultSLock_real = (void(*)(void*)) dlsym (RTLD_NEXT, "_xlsmpGetDefaultSLock"); INC_IF_NOT_NULL(_xlsmpGetDefaultSLock_real,count); /* Obtain @ for _xlsmpRelDefaultSLock */ _xlsmpRelDefaultSLock_real = (void(*)(void*)) dlsym (RTLD_NEXT, "_xlsmpRelDefaultSLock"); INC_IF_NOT_NULL(_xlsmpRelDefaultSLock_real,count); /* Obtain @ for _xlsmpGetSLock */ _xlsmpGetSLock_real = (void(*)(void*)) dlsym (RTLD_NEXT, "_xlsmpGetSLock"); INC_IF_NOT_NULL(_xlsmpGetSLock_real,count); /* Obtain @ for _xlsmpRelSLock */ _xlsmpRelSLock_real = (void(*)(void*)) dlsym (RTLD_NEXT, "_xlsmpRelSLock"); INC_IF_NOT_NULL(_xlsmpRelSLock_real,count); /* Any hook point? */ return count > 0; }
SLV2UIInstance slv2_ui_instantiate(SLV2Plugin plugin, SLV2UI ui, LV2UI_Write_Function write_function, LV2UI_Controller controller, const LV2_Feature* const* features) { struct _SLV2UIInstance* result = NULL; bool local_features = (features == NULL); if (local_features) { features = malloc(sizeof(LV2_Feature)); ((LV2_Feature**)features)[0] = NULL; } const char* const lib_uri = slv2_value_as_string(slv2_ui_get_binary_uri(ui)); const char* const lib_path = slv2_uri_to_path(lib_uri); if (!lib_path) return NULL; dlerror(); void* lib = dlopen(lib_path, RTLD_NOW); if (!lib) { fprintf(stderr, "Unable to open UI library %s (%s)\n", lib_path, dlerror()); return NULL; } LV2UI_DescriptorFunction df = dlsym(lib, "lv2ui_descriptor"); if (!df) { fprintf(stderr, "Could not find symbol 'lv2ui_descriptor', " "%s is not a LV2 plugin UI.\n", lib_path); dlclose(lib); return NULL; } else { const char* bundle_path = slv2_uri_to_path(slv2_value_as_uri(slv2_ui_get_bundle_uri(ui))); for (uint32_t i=0; 1; ++i) { const LV2UI_Descriptor* ld = df(i); if (!ld) { fprintf(stderr, "Did not find UI %s in %s\n", slv2_value_as_uri(slv2_ui_get_uri(ui)), lib_path); dlclose(lib); break; // return NULL } else if (!strcmp(ld->URI, slv2_value_as_uri(slv2_ui_get_uri(ui)))) { assert(plugin->plugin_uri); printf("Found UI %s at index %u in:\n\t%s\n\n", slv2_value_as_uri(plugin->plugin_uri), i, lib_path); assert(ld->instantiate); // Create SLV2UIInstance to return result = malloc(sizeof(struct _SLV2UIInstance)); struct _SLV2UIInstanceImpl* impl = malloc(sizeof(struct _SLV2UIInstanceImpl)); impl->lv2ui_descriptor = ld; impl->lv2ui_handle = ld->instantiate(ld, slv2_value_as_uri(slv2_plugin_get_uri(plugin)), (char*)bundle_path, write_function, controller, &impl->widget, features); impl->lib_handle = lib; result->pimpl = impl; break; } } } // Failed to instantiate if (result == NULL || result->pimpl->lv2ui_handle == NULL) { //printf("Failed to instantiate %s\n", plugin->plugin_uri); free(result); return NULL; } // Failed to create a widget, but still got a handle - this means that // the plugin is buggy if (result->pimpl->widget == NULL) { slv2_ui_instance_free(result); return NULL; } if (local_features) free((LV2_Feature**)features); return result; }
void* FindSymbol(dll_t dll, const char* sym) { return dlsym(dll, sym); }
int main(int argc, char *argv[]) { const char libcover[] = "libmpicover.so"; const char mainname[] = str(RENAME_MAIN); std::string bindir = vistle::getbindir(argc, argv); MPI_Init(&argc, &argv); int rank = -1; MPI_Comm_rank(MPI_COMM_WORLD, &rank); std::map<std::string, std::string> env; std::map<std::string, bool> envToSet; if (rank == 0) { std::vector<std::string> envvars; // system envvars.push_back("PATH"); envvars.push_back("LD_LIBRARY_PATH"); envvars.push_back("DYLD_LIBRARY_PATH"); envvars.push_back("DYLD_FRAMEWORK_PATH"); envvars.push_back("LANG"); // covise config envvars.push_back("COCONFIG"); envvars.push_back("COCONFIG_LOCAL"); envvars.push_back("COCONFIG_DEBUG"); envvars.push_back("COCONFIG_DIR"); envvars.push_back("COCONFIG_SCHEMA"); envvars.push_back("COVISE_CONFIG"); // cover envvars.push_back("COVER_PLUGINS"); envvars.push_back("COVER_TABLETPC"); envvars.push_back("COVISE_SG_DEBUG"); //envvars.push_back("COVISE_HOST"); envvars.push_back("COVISEDIR"); envvars.push_back("COVISE_PATH"); envvars.push_back("ARCHSUFFIX"); // OpenSceneGraph envvars.push_back("OSGFILEPATH"); envvars.push_back("OSG_FILE_PATH"); envvars.push_back("OSG_NOTIFY_LEVEL"); envvars.push_back("OSG_LIBRARY_PATH"); envvars.push_back("OSG_LD_LIBRARY_PATH"); for (auto v: envvars) { const char *val = getenv(v.c_str()); if (val) env[v] = val; } std::string covisedir = env["COVISEDIR"]; std::string archsuffix = env["ARCHSUFFIX"]; if (!covisedir.empty()) { if (FILE *fp = popen((covisedir+"/bin/print_covise_env").c_str(), "r")) { std::vector<char> buf(10000); while (fgets(buf.data(), buf.size(), fp)) { auto sep = std::find(buf.begin(), buf.end(), '='); if (sep != buf.end()) { std::string name = std::string(buf.begin(), sep); ++sep; auto end = std::find(sep, buf.end(), '\n'); std::string val = std::string(sep, end); //std::cerr << name << "=" << val << std::endl; env[name] = val; } //ld_library_path = buf.data(); //std::cerr << "read ld_lib: " << ld_library_path << std::endl; } pclose(fp); } } } std::string vistleplugin = bindir + "/../../../" + env["ARCHSUFFIX"] + "/lib/OpenCOVER/plugins/libVistlePlugin"; #ifdef __APPLE__ vistleplugin += ".so"; #else vistleplugin += ".so"; #endif env["VISTLE_PLUGIN"] = vistleplugin; //std::cerr << "Vistle plugin: " << vistleplugin << std::endl; std::string ldpath, dyldpath, dyldfwpath, covisepath; int numvars = env.size(); MPI_Bcast(&numvars, 1, MPI_INT, 0, MPI_COMM_WORLD); auto it = env.begin(); for (int i=0; i<numvars; ++i) { std::string name; std::string value; if (rank == 0) { name = it->first; value = it->second; } auto sync_string = [rank](std::string &s) { std::vector<char> buf; int len = -1; if (rank == 0) len = s.length()+1; MPI_Bcast(&len, 1, MPI_INT, 0, MPI_COMM_WORLD); buf.resize(len); if (rank == 0) strcpy(buf.data(), s.c_str()); MPI_Bcast(buf.data(), buf.size(), MPI_BYTE, 0, MPI_COMM_WORLD); s = buf.data(); }; sync_string(name); sync_string(value); #if 0 if (name == "COVISE_PATH") { // adapt in order to find VistlePlugin covisepath = bindir + "/../.."; if (!value.empty()) { covisepath += ":"; covisepath += value; } value = covisepath; } #endif setenv(name.c_str(), value.c_str(), 1 /* overwrite */); if (rank == 0) ++it; else env[name] = value; //std::cerr << name << " -> " << value << std::endl; } typedef int (*main_t)(int, char *[]); main_t realmain = NULL; int ret = 0; #if 0 std::string abslib = bindir + "/../../lib/" + libcover; #else std::string coviselibdir = env["COVISEDIR"] + "/" + env["ARCHSUFFIX"] + "/lib/"; std::string abslib = coviselibdir + libcover; #endif void *handle = dlopen(abslib.c_str(), RTLD_LAZY); if (!handle) { std::cerr << "failed to dlopen " << abslib << ": " << dlerror() << std::endl; ret = 1; goto finish; } realmain = (main_t)dlsym(handle, mainname); if (!realmain) { std::cerr << "could not find " << mainname << " in " << libcover << std::endl; ret = 1; goto finish; } ret = realmain(argc, argv); finish: if (handle) dlclose(handle); MPI_Finalize(); return 0; }
LWS_VISIBLE int lws_plat_plugins_init(struct lws_context * context, const char *d) { struct lws_plugin_capability lcaps; struct lws_plugin *plugin; lws_plugin_init_func initfunc; struct dirent **namelist; int n, i, m, ret = 0; char path[256]; void *l; n = scandir(d, &namelist, filter, alphasort); if (n < 0) { lwsl_err("Scandir on %s failed\n", d); return 1; } lwsl_notice(" Plugins:\n"); for (i = 0; i < n; i++) { if (strlen(namelist[i]->d_name) < 7) goto inval; lwsl_notice(" %s\n", namelist[i]->d_name); snprintf(path, sizeof(path) - 1, "%s/%s", d, namelist[i]->d_name); l = dlopen(path, RTLD_NOW); if (!l) { lwsl_err("Error loading DSO: %s\n", dlerror()); while (i++ < n) free(namelist[i]); goto bail; } /* we could open it, can we get his init function? */ m = snprintf(path, sizeof(path) - 1, "init_%s", namelist[i]->d_name + 3 /* snip lib... */); path[m - 3] = '\0'; /* snip the .so */ initfunc = dlsym(l, path); if (!initfunc) { lwsl_err("Failed to get init on %s: %s", namelist[i]->d_name, dlerror()); dlclose(l); } lcaps.api_magic = LWS_PLUGIN_API_MAGIC; m = initfunc(context, &lcaps); if (m) { lwsl_err("Initializing %s failed %d\n", namelist[i]->d_name, m); dlclose(l); goto skip; } plugin = lws_malloc(sizeof(*plugin)); if (!plugin) { lwsl_err("OOM\n"); goto bail; } plugin->list = context->plugin_list; context->plugin_list = plugin; strncpy(plugin->name, namelist[i]->d_name, sizeof(plugin->name) - 1); plugin->name[sizeof(plugin->name) - 1] = '\0'; plugin->l = l; plugin->caps = lcaps; context->plugin_protocol_count += lcaps.count_protocols; context->plugin_extension_count += lcaps.count_extensions; free(namelist[i]); continue; skip: dlclose(l); inval: free(namelist[i]); } bail: free(namelist); return ret; }
DECLARE_EXPORT void Environment::loadModule(string lib, ParameterList& parameters) { // Type definition of the initialization function typedef const char* (*func)(const ParameterList&); // Validate if (lib.empty()) throw DataException("Error: No library name specified for loading"); #ifdef WIN32 // Load the library - The windows way // Change the error mode: we handle errors now, not the operating system UINT em = SetErrorMode(SEM_FAILCRITICALERRORS); HINSTANCE handle = LoadLibraryEx(lib.c_str(),NULL,LOAD_WITH_ALTERED_SEARCH_PATH); if (!handle) handle = LoadLibraryEx(lib.c_str(), NULL, 0); if (!handle) { // Get the error description char error[256]; FormatMessage( FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(), 0, error, 256, NULL ); throw RuntimeException(error); } SetErrorMode(em); // Restore the previous error mode // Find the initialization routine func inithandle = reinterpret_cast<func>(GetProcAddress(HMODULE(handle), "initialize")); if (!inithandle) { // Get the error description char error[256]; FormatMessage( FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(), 0, error, 256, NULL ); throw RuntimeException(error); } #else // Load the library - The UNIX way // Search the frePPLe directories for the library string fullpath = Environment::searchFile(lib); if (fullpath.empty()) throw RuntimeException("Module '" + lib + "' not found"); dlerror(); // Clear the previous error void *handle = dlopen(fullpath.c_str(), RTLD_NOW | RTLD_GLOBAL); const char *err = dlerror(); // Pick up the error string if (err) { // Search the normal path for the library dlerror(); // Clear the previous error handle = dlopen(lib.c_str(), RTLD_NOW | RTLD_GLOBAL); err = dlerror(); // Pick up the error string if (err) throw RuntimeException(err); } // Find the initialization routine func inithandle = (func)(dlsym(handle, "initialize")); err = dlerror(); // Pick up the error string if (err) throw RuntimeException(err); #endif // Call the initialization routine with the parameter list string x = (inithandle)(parameters); if (x.empty()) throw DataException("Invalid module"); // Insert the new module in the registry moduleRegistry.insert(x); }
EXTERN int NpLoadLibrary(HMODULE *tclHandle, char *dllName, int dllNameSize, char *me) { char *envdll, libname[MAX_PATH]; HMODULE handle = (HMODULE) NULL; char path[MAX_PATH], *p ; *tclHandle = NULL; if(me) strcpy(path, me) ; if(me && (p = strrchr(path,'/'))) { *(++p) = '\0' ; sprintf(libname, "%s%s", path, TCL_LIB_FILE) ; NpLog("Attempt to load from executable directory '%s'\n", libname) ; if(!(handle = dlopen(libname, RTLD_NOW | RTLD_GLOBAL))) { sprintf(libname, "%s../lib/%s", path, TCL_LIB_FILE) ; NpLog("Attempt to load from relative lib directory '%s'\n", libname) ; handle = dlopen(libname, RTLD_NOW | RTLD_GLOBAL) ; } } else { handle = NULL ; } /* * Try a user-supplied Tcl dll to start with. */ if(!handle) { envdll = getenv("TCL_PLUGIN_DLL"); if (envdll != NULL) { NpLog("Attempt to load Tcl dll (TCL_PLUGIN_DLL) '%s'\n", envdll); handle = dlopen(envdll, RTLD_NOW | RTLD_GLOBAL); if (handle) { memcpy(libname, envdll, MAX_PATH); } } } if (!handle) { /* * Try based on full path. */ snprintf(libname, MAX_PATH, "%s%s", defaultLibraryDir, TCL_LIB_FILE); NpLog("Attempt to load Tcl dll (default) '%s'\n", libname); handle = dlopen(libname, RTLD_NOW | RTLD_GLOBAL); } if (!handle) { /* * Try based on anywhere in the path. */ strncpy(libname, TCL_LIB_FILE, MAX_PATH); NpLog("Attempt to load Tcl dll (libpath) '%s'\n", libname); handle = dlopen(libname, RTLD_NOW | RTLD_GLOBAL); } if (!handle) { /* * Try different versions anywhere in the path. */ char *pos; pos = strstr(libname, "tcl")+4; if (*pos == '.') { pos++; } *pos = '9'; /* count down from '8' to '4'*/ while (!handle && (--*pos > '3')) { NpLog("Attempt to load Tcl dll (default_ver) '%s'\n", libname); handle = dlopen(libname, RTLD_NOW | RTLD_GLOBAL); } } if (!handle) { NpPlatformMsg("Failed to load Tcl dll!", "NpCreateMainInterp"); return TCL_ERROR; } *tclHandle = handle; if (dllNameSize > 0) { # ifdef HAVE_DLADDR /* * Use dladdr if possible to get the real libname we are loading. * Grab any symbol - we just need one for reverse mapping */ int (* tcl_Init)(Tcl_Interp *) = (int (*)(Tcl_Interp *)) dlsym(handle, "Tcl_Init"); Dl_info info; if (tcl_Init && dladdr(tcl_Init, &info)) { NpLog3("using dladdr '%s' => '%s'\n", libname, info.dli_fname); snprintf(dllName, dllNameSize, "%s", info.dli_fname); /* format arg was missing */ } else # endif snprintf(dllName, dllNameSize, "%s", libname); /* format arg was missing */ } return TCL_OK; }
// Call back Declaration ReturnType DigitalIOComp::onInitialize() { // XML에 저장된 프라퍼티를 parameter에 저장 Property parameter; std::map<std::string, std::string> temp = getPropertyMap(); parameter.SetProperty(temp); // dll 파일이름을 확인하여 없으면 에러 리턴 if(parameter.FindName("APIName") == false) { PrintMessage("ERROR : DigitalIOComp::onInitialize() -> Can't find the APIName in property\n"); return OPROS_FIND_PROPERTY_ERROR; } #if defined(WIN32) // DLL 로드 hOprosAPI = LoadLibrary((LPCSTR)parameter.GetValue("APIName").c_str()); if(hOprosAPI == NULL) { PrintMessage("ERROR : DigitalIOComp::onInitialize() -> Can't find the %s\n", parameter.GetValue("APIName").c_str()); return OPROS_FIND_DLL_ERROR; } // API 로드 GET_OPROS_API getOprosAPI; getOprosAPI = (GET_OPROS_API)GetProcAddress(hOprosAPI, "GetAPI"); if(getOprosAPI == NULL) { PrintMessage("ERROR : DigitalIOComp::onInitialize() -> Can't get a handle of GetAPI Funtion\n"); FreeLibrary(hOprosAPI); hOprosAPI = NULL; return OPROS_LOAD_DLL_ERROR; } #else hOprosAPI = dlopen(parameter.GetValue("DllName").c_str(), RTLD_LAZY); if(hOprosAPI == NULL) { PrintMessage("ERROR : DigitalIOComp::onInitialize() -> Can't find the %s\n", parameter.GetValue("DllName").c_str()); return OPROS_FIND_DLL_ERROR; } GET_OPROS_API getOprosAPI; getOprosAPI = (GET_OPROS_API)dlsym(hOprosAPI, "GetAPI"); char *error = dlerror(); if(error != NULL) { PrintMessage("ERROR : DigitalIOComp::onInitialize() -> Can't get a handle of GetAPI Funtion\n"); dlclose(hOprosAPI); hOprosAPI = NULL; return OPROS_LOAD_DLL_ERROR; } #endif digitalIO = dynamic_cast<DigitalIO *>(getOprosAPI()); if(digitalIO == NULL) { PrintMessage("ERROR : DigitalIOComp::onInitialize() -> Can't get a handle of Digital IO API\n"); #if defined(WIN32) FreeLibrary(hOprosAPI); #else dlclose(hOprosAPI); #endif hOprosAPI = NULL; return OPROS_LOAD_DLL_ERROR; } // API 초기화 if(digitalIO->Initialize(parameter) != API_SUCCESS) { PrintMessage("ERROR : DigitalIOComp::onInitialize() -> Can't initialize a Digital IO API\n"); delete digitalIO; digitalIO = NULL; #if defined(WIN32) FreeLibrary(hOprosAPI); #else dlclose(hOprosAPI); #endif hOprosAPI = NULL; return OPROS_INITIALIZE_API_ERROR; } error = 0; return OPROS_SUCCESS; }
int plugins_load(server *srv) { plugin *p; int (*init)(plugin *pl); const char *error; size_t i; for (i = 0; i < srv->srvconf.modules->used; i++) { data_string *d = (data_string *)srv->srvconf.modules->data[i]; char *modules = d->value->ptr; buffer_copy_string_buffer(srv->tmp_buf, srv->srvconf.modules_dir); buffer_append_string_len(srv->tmp_buf, CONST_STR_LEN("/")); buffer_append_string(srv->tmp_buf, modules); #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, modules); 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 ((error = dlerror()) != NULL) { log_error_write(srv, __FILE__, __LINE__, "s", error); plugin_free(p); return -1; } #endif if ((*init)(p)) { log_error_write(srv, __FILE__, __LINE__, "ss", modules, "plugin init failed" ); plugin_free(p); return -1; } #if 0 log_error_write(srv, __FILE__, __LINE__, "ss", modules, "plugin loaded" ); #endif plugins_register(srv, p); } return 0; }
bool EnsureInitialized() { if (mInitialized) { return true; } void *handle = dlopen(ANDROID_EGL_PATH, RTLD_LAZY); if (!handle) { LOG("Couldn't load EGL library"); return false; } fGetDisplay = (pfnGetDisplay)dlsym(handle, "eglGetDisplay"); fEGLGetError = (pfnEGLGetError)dlsym(handle, "eglGetError"); fCreateImageKHR = (pfnCreateImageKHR)dlsym(handle, "eglCreateImageKHR"); fDestroyImageKHR = (pfnDestroyImageKHR)dlsym(handle, "eglDestroyImageKHR"); if (!fGetDisplay || !fEGLGetError || !fCreateImageKHR || !fDestroyImageKHR) { LOG("Failed to find some EGL functions"); return false; } handle = dlopen(ANDROID_GLES_PATH, RTLD_LAZY); if (!handle) { LOG("Couldn't load GL library"); return false; } fImageTargetTexture2DOES = (pfnImageTargetTexture2DOES)dlsym(handle, "glEGLImageTargetTexture2DOES"); fBindTexture = (pfnBindTexture)dlsym(handle, "glBindTexture"); fGLGetError = (pfnGLGetError)dlsym(handle, "glGetError"); if (!fImageTargetTexture2DOES || !fBindTexture || !fGLGetError) { LOG("Failed to find some GL functions"); return false; } handle = dlopen(ANDROID_LIBUI_PATH, RTLD_LAZY); if (!handle) { LOG("Couldn't load libui.so"); return false; } fGraphicBufferCtor = (pfnGraphicBufferCtor)dlsym(handle, "_ZN7android13GraphicBufferC1Ejjij"); fGraphicBufferDtor = (pfnGraphicBufferDtor)dlsym(handle, "_ZN7android13GraphicBufferD1Ev"); fGraphicBufferLock = (pfnGraphicBufferLock)dlsym(handle, "_ZN7android13GraphicBuffer4lockEjPPv"); fGraphicBufferLockRect = (pfnGraphicBufferLockRect)dlsym(handle, "_ZN7android13GraphicBuffer4lockEjRKNS_4RectEPPv"); fGraphicBufferUnlock = (pfnGraphicBufferUnlock)dlsym(handle, "_ZN7android13GraphicBuffer6unlockEv"); fGraphicBufferGetNativeBuffer = (pfnGraphicBufferGetNativeBuffer)dlsym(handle, "_ZNK7android13GraphicBuffer15getNativeBufferEv"); fGraphicBufferReallocate = (pfnGraphicBufferReallocate)dlsym(handle, "_ZN7android13GraphicBuffer10reallocateEjjij"); if (!fGraphicBufferCtor || !fGraphicBufferDtor || !fGraphicBufferLock || !fGraphicBufferUnlock || !fGraphicBufferGetNativeBuffer) { LOG("Failed to lookup some GraphicBuffer functions"); return false; } mInitialized = true; return true; }
bool Extension::load(string ext_name, string filename){ string ext_full_path; string func_name; void *handle; void *sym; if(ext_path.empty()){ cerr << "please specify extension path " << endl; return false; } ext_full_path = ext_path + "/" + filename; handle = dlopen(ext_full_path.c_str(), RTLD_LAZY); if(!handle){ cerr << "fail to load " << dlerror() << endl; return false; } func_name.clear(); func_name = ext_name + "_parse_req"; sym = dlsym(handle, func_name.c_str()); if(sym != NULL){ parse_req[ext_name] = (parse_req_t)sym; }else{ cerr << "fail to load sym " << func_name << endl; } func_name.clear(); func_name = ext_name + "_create_req"; sym = dlsym(handle, func_name.c_str()); if(sym != NULL){ create_req[ext_name] = (create_req_t)sym; }else{ cerr << "fail to load sym " << func_name << endl; } func_name.clear(); func_name = ext_name + "_create_req_async"; sym = dlsym(handle, func_name.c_str()); if(sym != NULL){ create_req_async[ext_name] = (create_req_async_t)sym; }else{ cerr << "fail to load sym " << func_name << endl; } func_name.clear(); func_name = ext_name + "_parse_resp"; sym = dlsym(handle, func_name.c_str()); if(sym != NULL){ parse_resp[ext_name] = (parse_resp_t)sym; }else{ cerr << "fail to load sym " << func_name << endl; } func_name.clear(); func_name = ext_name + "_create_resp"; sym = dlsym(handle, func_name.c_str()); if(sym != NULL){ create_resp[ext_name] = (create_resp_t)sym; }else{ cerr << "fail to load sym " << func_name << endl; } func_name.clear(); func_name = ext_name + "_ext_version"; sym = dlsym(handle, func_name.c_str()); if(sym != NULL){ ext_version[ext_name] = (ext_version_t)sym; }else{ cerr << "fail to load sym " << func_name << endl; } return true; //dlclose(handle); }
static void * evgl_eng_proc_address_get(const char *name) { if (glsym_eglGetProcAddress) return glsym_eglGetProcAddress(name); return dlsym(RTLD_DEFAULT, name); }
/* * is_llvm_bitcode_from_memory() is passed a pointer and size of a memory * buffer, a pointer to an arch_flag struct and an pointer to return the lto * module if not NULL. If it the memory is an llvm bit code it returns 1 and * sets the fields in the arch flag. If pmod is not NULL it stores the lto * module in their, if not it frees the lto module. If the memory buffer is * not an llvm bit code it returns 0. */ __private_extern__ int is_llvm_bitcode_from_memory( char *addr, uint32_t size, struct arch_flag *arch_flag, void **pmod) /* maybe NULL */ { uint32_t bufsize; char *p, *prefix, *lto_path, buf[MAXPATHLEN], resolved_name[PATH_MAX]; int i; void *mod; /* * The libLTO API's can't handle empty files. So return 0 to indicate * this is not a bitcode file if it has a zero size. */ if(size == 0) return(0); if(tried_to_load_lto == 0){ tried_to_load_lto = 1; /* * Construct the prefix to this executable assuming it is in a bin * directory relative to a lib directory of the matching lto library * and first try to load that. If not then fall back to trying * "/Applications/Xcode.app/Contents/Developer/Toolchains/ * XcodeDefault.xctoolchain/usr/lib/libLTO.dylib". */ bufsize = MAXPATHLEN; p = buf; i = _NSGetExecutablePath(p, &bufsize); if(i == -1){ p = allocate(bufsize); _NSGetExecutablePath(p, &bufsize); } prefix = realpath(p, resolved_name); p = (prefix ? rindex(prefix, '/') : NULL); if(p != NULL) p[1] = '\0'; #ifdef __APPLE__ lto_path = makestr(prefix, "../lib/libLTO.dylib", NULL); lto_handle = dlopen(lto_path, RTLD_NOW); if(lto_handle == NULL){ free(lto_path); lto_path = NULL; lto_handle = dlopen("/Applications/Xcode.app/Contents/" "Developer/Toolchains/XcodeDefault." "xctoolchain/usr/lib/libLTO.dylib", RTLD_NOW); } if(lto_handle == NULL) return(0); #else lto_path = NULL; lto_handle = load_liblto(); if(lto_handle == NULL) { fprintf(stderr, "cannot find or load libLTO.so\n"); return(0); } #endif /* __APPLE__ */ lto_is_object = dlsym(lto_handle, "lto_module_is_object_file_in_memory"); lto_create = dlsym(lto_handle, "lto_module_create_from_memory"); lto_dispose = dlsym(lto_handle, "lto_module_dispose"); lto_get_target = dlsym(lto_handle, "lto_module_get_target_triple"); lto_get_num_symbols = dlsym(lto_handle, "lto_module_get_num_symbols"); lto_get_sym_attr = dlsym(lto_handle, "lto_module_get_symbol_attribute"); lto_get_sym_name = dlsym(lto_handle, "lto_module_get_symbol_name"); if(lto_is_object == NULL || lto_create == NULL || lto_dispose == NULL || lto_get_target == NULL || lto_get_num_symbols == NULL || lto_get_sym_attr == NULL || lto_get_sym_name == NULL){ dlclose(lto_handle); if(lto_path != NULL) free(lto_path); return(0); } } if(lto_handle == NULL) return(0); if(!lto_is_object(addr, size)) return(0); mod = lto_create(addr, size); if(mod == NULL) return(0); /* * It is possible for new targets to be added to lto that are not yet * known to this code. So we will try to get lucky and let them pass * through with the cputype set to 0. This should work for things * like libtool(1) as long as we don't get two different unknown * targets. But we'll hope that just doesn't happen. */ arch_flag->cputype = 0; arch_flag->cpusubtype = 0; arch_flag->name = NULL; (void)get_lto_cputype(arch_flag, lto_get_target(mod)); if(pmod != NULL) *pmod = mod; else lto_free(mod); return(1); }