1 /////////////////////////////////////////////////////////////////////////////
3 // Purpose: Dynamic library management
4 // Author: Guilhem Lavaux
8 // Copyright: (c) Guilhem Lavaux
9 // Licence: wxWindows license
10 /////////////////////////////////////////////////////////////////////////////
12 // ============================================================================
14 // ============================================================================
16 // ----------------------------------------------------------------------------
18 // ----------------------------------------------------------------------------
21 # pragma implementation "dynlib.h"
24 #include "wx/wxprec.h"
30 #if wxUSE_DYNLIB_CLASS
32 #if defined(__WINDOWS__)
33 #include "wx/msw/private.h"
36 #include "wx/dynlib.h"
37 #include "wx/filefn.h"
40 #include "wx/tokenzr.h"
42 // ----------------------------------------------------------------------------
43 // conditional compilation
44 // ----------------------------------------------------------------------------
46 #if defined(__WXPM__) || defined(__EMX__)
49 # define wxDllOpen(error, lib, handle) DosLoadModule(error, sizeof(error), lib, &handle)
50 # define wxDllGetSymbol(handle, modaddr) DosQueryProcAddr(handle, 1L, NULL, (PFN*)modaddr)
51 # define wxDllClose(handle) DosFreeModule(handle)
52 #elif defined(HAVE_DLOPEN)
53 // note about dlopen() flags: we use RTLD_NOW to have more Windows-like
54 // behaviour (Win won't let you load a library with missing symbols) and
55 // RTLD_GLOBAL because it is needed sometimes and probably doesn't hurt
56 // otherwise. On True64-Unix RTLD_GLOBAL is not allowed and on VMS the
57 // second argument on dlopen is ignored.
59 # define wxDllOpen(lib) dlopen(lib.fn_str(), 0 )
60 #elif defined( __osf__ )
61 # define wxDllOpen(lib) dlopen(lib.fn_str(), RTLD_LAZY )
63 # define wxDllOpen(lib) dlopen(lib.fn_str(), RTLD_LAZY | RTLD_GLOBAL)
65 #define wxDllGetSymbol(handle, name) dlsym(handle, name)
66 # define wxDllClose dlclose
67 #elif defined(HAVE_SHL_LOAD)
68 # define wxDllOpen(lib) shl_load(lib.fn_str(), BIND_DEFERRED, 0)
69 # define wxDllClose shl_unload
71 static inline void *wxDllGetSymbol(shl_t handle
, const wxString
& name
)
74 if ( shl_findsym(&handle
, name
.mb_str(), TYPE_UNDEFINED
, &sym
) == 0 )
79 #elif defined(__DARWIN__)
81 * The dlopen port is a port from dl_next.xs by Anno Siegel.
82 * dl_next.xs is itself a port from dl_dlopen.xs by Paul Marquess.
83 * The method used here is just to supply the sun style dlopen etc.
84 * functions in terms of Darwin NS*.
86 void *dlopen(const char *path
, int mode
/* mode is ignored */);
87 void *dlsym(void *handle
, const char *symbol
);
88 int dlclose(void *handle
);
89 const char *dlerror(void);
91 # define wxDllOpen(lib) dlopen(lib.fn_str(), 0)
92 # define wxDllGetSymbol(handle, name) dlsym(handle, name)
93 # define wxDllClose dlclose
94 #elif defined(__WINDOWS__)
95 // using LoadLibraryEx under Win32 to avoid name clash with LoadLibrary
98 # define wxDllOpen(lib) ::LoadLibraryExW(lib, 0, 0)
100 # define wxDllOpen(lib) ::LoadLibraryExA(lib, 0, 0)
103 # define wxDllOpen(lib) ::LoadLibrary(lib)
105 # define wxDllGetSymbol(handle, name) ::GetProcAddress(handle, name)
106 # define wxDllClose ::FreeLibrary
107 #elif defined(__WXMAC__)
108 # define wxDllClose(handle) CloseConnection(&handle)
110 # error "Don't know how to load shared libraries on this platform."
113 // ---------------------------------------------------------------------------
115 // ---------------------------------------------------------------------------
117 wxLibraries wxTheLibraries
;
119 // ============================================================================
121 // ============================================================================
123 // construct the full name from the base shared object name: adds a .dll
124 // suffix under Windows or .so under Unix
125 static wxString
ConstructLibraryName(const wxString
& basename
)
128 fullname
<< basename
<< wxDllLoader::GetDllExt();
133 // ---------------------------------------------------------------------------
134 // wxLibrary (one instance per dynamic library)
135 // ---------------------------------------------------------------------------
137 wxLibrary::wxLibrary(wxDllType handle
)
139 typedef wxClassInfo
*(*t_get_first
)(void);
140 t_get_first get_first
;
144 // Some system may use a local heap for library.
145 get_first
= (t_get_first
)GetSymbol("wxGetClassFirst");
146 // It is a wxWindows DLL.
148 PrepareClasses(get_first());
151 wxLibrary::~wxLibrary()
155 wxDllClose(m_handle
);
159 wxObject
*wxLibrary::CreateObject(const wxString
& name
)
161 wxClassInfo
*info
= (wxClassInfo
*)classTable
.Get(name
);
166 return info
->CreateObject();
169 void wxLibrary::PrepareClasses(wxClassInfo
*first
)
171 // Index all class infos by their class name
172 wxClassInfo
*info
= first
;
175 if (info
->m_className
)
176 classTable
.Put(info
->m_className
, (wxObject
*)info
);
177 info
= (wxClassInfo
*)info
->GetNext();
180 // Set base pointers for each wxClassInfo
184 if (info
->GetBaseClassName1())
185 info
->m_baseInfo1
= (wxClassInfo
*)classTable
.Get(info
->GetBaseClassName1());
186 if (info
->GetBaseClassName2())
187 info
->m_baseInfo2
= (wxClassInfo
*)classTable
.Get(info
->GetBaseClassName2());
192 void *wxLibrary::GetSymbol(const wxString
& symbname
)
194 return wxDllLoader::GetSymbol(m_handle
, symbname
);
197 // ---------------------------------------------------------------------------
199 // ---------------------------------------------------------------------------
202 wxString
wxDllLoader::GetDllExt()
206 #if defined(__WINDOWS__) || defined(__WXPM__) || defined(__EMX__)
208 #elif defined(__UNIX__)
209 # if defined(__HPUX__)
221 wxDllLoader::GetProgramHandle(void)
223 #if defined( HAVE_DLOPEN ) && !defined(__EMX__)
224 // optain handle for main program
225 return dlopen(NULL
, RTLD_NOW
/*RTLD_LAZY*/);
226 #elif defined (HAVE_SHL_LOAD)
227 // shl_findsymbol with NULL handle looks up in main program
230 wxFAIL_MSG( wxT("This method is not implemented under Windows or OS/2"));
237 wxDllLoader::LoadLibrary(const wxString
& libname
, bool *success
)
241 #if defined(__WXMAC__) && !defined(__UNIX__)
246 wxMacFilename2FSSpec( libname
, &myFSSpec
) ;
247 if (GetDiskFragment( &myFSSpec
, 0 , kCFragGoesToEOF
, "\p" , kPrivateCFragCopy
, &handle
, &myMainAddr
,
248 myErrName
) != noErr
)
250 p2cstr( myErrName
) ;
251 wxLogSysError( _("Failed to load shared library '%s' Error '%s'") , libname
.c_str() , (char*)myErrName
) ;
254 #elif defined(__WXPM__) || defined(__EMX__)
255 char zError
[256] = "";
256 wxDllOpen(zError
, libname
, handle
);
258 handle
= wxDllOpen(libname
);
263 wxString
msg(_("Failed to load shared library '%s'"));
266 const char *errmsg
= dlerror();
269 // the error string format is "libname: ...", but we already have
270 // libname, so cut it off
271 const char *p
= strchr(errmsg
, ':');
283 wxLogError(msg
, libname
.c_str(), p
);
286 #endif // HAVE_DLERROR
288 wxLogSysError(msg
, libname
.c_str());
294 *success
= handle
!= 0;
303 wxDllLoader::UnloadLibrary(wxDllType handle
)
310 wxDllLoader::GetSymbol(wxDllType dllHandle
, const wxString
&name
)
312 void *symbol
= NULL
; // return value
314 #if defined(__WXMAC__) && !defined(__UNIX__)
316 CFragSymbolClass symClass
;
320 c2pstrcpy( (StringPtr
) symName
, name
) ;
322 strcpy( (char *) symName
, name
) ;
323 c2pstr( (char *) symName
) ;
326 if ( FindSymbol( dllHandle
, symName
, &symAddress
, &symClass
) == noErr
)
327 symbol
= (void *)symAddress
;
328 #elif defined( __WXPM__ ) || defined(__EMX__)
329 wxDllGetSymbol(dllHandle
, symbol
);
331 // mb_str() is necessary in Unicode build
332 symbol
= wxDllGetSymbol(dllHandle
, name
.mb_str());
337 wxLogSysError(_("Couldn't find symbol '%s' in a dynamic library"),
343 // ---------------------------------------------------------------------------
344 // wxLibraries (only one instance should normally exist)
345 // ---------------------------------------------------------------------------
347 wxLibraries::wxLibraries():m_loaded(wxKEY_STRING
)
351 wxLibraries::~wxLibraries()
353 wxNode
*node
= m_loaded
.First();
356 wxLibrary
*lib
= (wxLibrary
*)node
->Data();
363 wxLibrary
*wxLibraries::LoadLibrary(const wxString
& name
)
367 wxClassInfo
*old_sm_first
;
369 #if defined(__VISAGECPP__)
370 node
= m_loaded
.Find(name
.GetData());
372 return ((wxLibrary
*)node
->Data());
374 if ( (node
= m_loaded
.Find(name
.GetData())) != NULL
)
375 return ((wxLibrary
*)node
->Data());
377 // If DLL shares data, this is necessary.
378 old_sm_first
= wxClassInfo::sm_first
;
379 wxClassInfo::sm_first
= NULL
;
381 wxString libname
= ConstructLibraryName(name
);
384 Unix automatically builds that library name, at least for dlopen()
387 #if defined(__UNIX__)
388 // found the first file in LD_LIBRARY_PATH with this name
389 wxString
libPath("/lib:/usr/lib"); // system path first
390 const char *envLibPath
= getenv("LD_LIBRARY_PATH");
392 libPath
<< wxT(':') << envLibPath
;
393 wxStringTokenizer
tokenizer(libPath
, wxT(':'));
394 while ( tokenizer
.HasMoreToken() )
396 wxString
fullname(tokenizer
.NextToken());
398 fullname
<< wxT('/') << libname
;
399 if ( wxFileExists(fullname
) )
407 //else: not found in the path, leave the name as is (secutiry risk?)
412 bool success
= FALSE
;
413 wxDllType handle
= wxDllLoader::LoadLibrary(libname
, &success
);
416 lib
= new wxLibrary(handle
);
417 wxClassInfo::sm_first
= old_sm_first
;
418 m_loaded
.Append(name
.GetData(), lib
);
425 wxObject
*wxLibraries::CreateObject(const wxString
& path
)
427 wxNode
*node
= m_loaded
.First();
431 obj
= ((wxLibrary
*)node
->Data())->CreateObject(path
);
441 // ---------------------------------------------------------------------------
442 // For Darwin/Mac OS X
443 // supply the sun style dlopen functions in terms of Darwin NS*
444 // ---------------------------------------------------------------------------
447 #import <mach-o/dyld.h>
455 static char dl_last_error
[1024];
458 void TranslateError(const char *path
, enum dyldErrorSource type
, int number
)
461 static char *OFIErrorStrings
[] =
463 "%s(%d): Object Image Load Failure\n",
464 "%s(%d): Object Image Load Success\n",
465 "%s(%d): Not an recognisable object file\n",
466 "%s(%d): No valid architecture\n",
467 "%s(%d): Object image has an invalid format\n",
468 "%s(%d): Invalid access (permissions?)\n",
469 "%s(%d): Unknown error code from NSCreateObjectFileImageFromFile\n",
471 #define NUM_OFI_ERRORS (sizeof(OFIErrorStrings) / sizeof(OFIErrorStrings[0]))
477 if (index
> NUM_OFI_ERRORS
- 1) {
478 index
= NUM_OFI_ERRORS
- 1;
480 sprintf(dl_last_error
, OFIErrorStrings
[index
], path
, number
);
484 sprintf(dl_last_error
, "%s(%d): Totally unknown error type %d\n",
490 const char *dlerror()
492 return dl_last_error
;
495 void *dlopen(const char *path
, int mode
/* mode is ignored */)
498 NSObjectFileImage ofile
;
499 NSModule handle
= NULL
;
501 dyld_result
= NSCreateObjectFileImageFromFile(path
, &ofile
);
502 if (dyld_result
!= NSObjectFileImageSuccess
)
504 TranslateError(path
, OFImage
, dyld_result
);
508 // NSLinkModule will cause the run to abort on any link error's
509 // not very friendly but the error recovery functionality is limited.
510 handle
= NSLinkModule(ofile
, path
, TRUE
);
516 int dlclose(void *handle
) /* stub only */
521 void *dlsym(void *handle
, const char *symbol
)
525 if (NSIsSymbolNameDefined(symbol
)) {
526 addr
= NSAddressOfSymbol(NSLookupAndBindSymbol(symbol
));
536 #endif // wxUSE_DYNLIB_CLASS