1 /////////////////////////////////////////////////////////////////////////////
3 // Purpose: Dynamic loading framework
4 // Author: Ron Lee, David Falkinder, Vadim Zeitlin and a cast of 1000's
5 // (derived in part from dynlib.cpp (c) 1998 Guilhem Lavaux)
9 // Copyright: (c) 2001 Ron Lee <ron@debian.org>
10 // Licence: wxWindows license
11 /////////////////////////////////////////////////////////////////////////////
14 #pragma implementation "dynload.h"
17 // ----------------------------------------------------------------------------
19 // ----------------------------------------------------------------------------
21 #include "wx/wxprec.h"
27 #if wxUSE_DYNAMIC_LOADER
30 #include "wx/msw/private.h"
38 #include "wx/dynload.h"
41 // ============================================================================
43 // ============================================================================
45 // ---------------------------------------------------------------------------
47 // ---------------------------------------------------------------------------
49 //FIXME: This class isn't really common at all, it should be moved into
50 // platform dependent files.
52 #if defined(__WINDOWS__) || defined(__WXPM__) || defined(__EMX__)
53 const wxString
wxDynamicLibrary::ms_dllext( _T(".dll") );
54 #elif defined(__UNIX__)
56 const wxString
wxDynamicLibrary::ms_dllext( _T(".sl") );
58 const wxString
wxDynamicLibrary::ms_dllext( _T(".so") );
62 wxDllType
wxDynamicLibrary::GetProgramHandle()
64 #if defined( HAVE_DLOPEN ) && !defined(__EMX__)
65 return dlopen(0, RTLD_LAZY
);
66 #elif defined (HAVE_SHL_LOAD)
69 wxFAIL_MSG( wxT("This method is not implemented under Windows or OS/2"));
74 bool wxDynamicLibrary::Load(wxString libname
, int flags
)
76 wxASSERT_MSG(m_handle
== 0, _T("Library already loaded."));
78 if( !(flags
& wxDL_VERBATIM
) )
79 libname
+= GetDllExt();
81 #if defined(__WXMAC__) && !defined(__UNIX__)
86 wxMacFilename2FSSpec( libname
, &myFSSpec
);
88 if( GetDiskFragment( &myFSSpec
,
95 myErrName
) != noErr
)
98 wxLogSysError( _("Failed to load shared library '%s' Error '%s'"),
104 #elif defined(__WXPM__) || defined(__EMX__)
106 DosLoadModule(err
, sizeof(err
), libname
.c_str(), &m_handle
)
108 #elif defined(HAVE_DLOPEN)
111 m_handle
= dlopen(libname
.c_str(), 0); // The second parameter is ignored
115 if( flags
& wxDL_LAZY
)
117 wxASSERT_MSG( (flags
& wxDL_NOW
) == 0,
118 _T("wxDL_LAZY and wxDL_NOW are mutually exclusive.") );
119 rtldFlags
|= RTLD_LAZY
;
121 else if( flags
& wxDL_NOW
)
123 rtldFlags
|= RTLD_NOW
;
125 if( flags
& wxDL_GLOBAL
)
128 wxLogDebug(_T("WARNING: RTLD_GLOBAL is not a supported on this platform."));
130 rtldFlags
|= RTLD_GLOBAL
;
133 m_handle
= dlopen(libname
.c_str(), rtldFlags
);
136 #elif defined(HAVE_SHL_LOAD)
139 if( flags
& wxDL_LAZY
)
141 wxASSERT_MSG( (flags
& wxDL_NOW
) == 0,
142 _T("wxDL_LAZY and wxDL_NOW are mutually exclusive.") );
143 shlFlags
|= BIND_DEFERRED
;
145 else if( flags
& wxDL_NOW
)
147 shlFlags
|= BIND_IMMEDIATE
;
149 m_handle
= shl_load(libname
.c_str(), BIND_DEFERRED
, 0);
151 #elif defined(__DARWIN__)
152 NSObjectFileImage ofile
;
153 int dyld_result
= NSCreateObjectFileImageFromFile(libname
.c_str(), &ofile
);
155 if (dyld_result
!= NSObjectFileImageSuccess
)
157 TranslateError(libname
.c_str(), OFImage
, dyld_result
);
161 // NSLinkModule will cause the run to abort on any link error's
162 // not very friendly but the error recovery functionality is limited.
163 m_handle
= NSLinkModule(ofile
, libname
.c_str(), TRUE
);
166 #elif defined(__WINDOWS__)
167 m_handle
= ::LoadLibrary(libname
.c_str());
170 #error "runtime shared lib support not implemented"
175 wxString
msg(_("Failed to load shared library '%s'"));
177 const wxChar
*err
= dlerror();
179 wxLogError( msg
, err
);
181 wxLogSysError( msg
, libname
.c_str() );
188 void wxDynamicLibrary::Unload()
192 #if defined(__WXPM__) || defined(__EMX__)
193 DosFreeModule( m_handle
);
194 #elif defined(HAVE_DLOPEN)
196 #elif defined(HAVE_SHL_LOAD)
197 shl_unload( m_handle
);
198 #elif defined(__WINDOWS__)
199 ::FreeLibrary( m_handle
);
200 #elif defined(__WXMAC__)
201 CloseConnection( &m_handle
);
203 #error "runtime shared lib support not implemented"
209 void *wxDynamicLibrary::GetSymbol(const wxString
&name
, bool *success
) const
211 wxCHECK_MSG( IsLoaded(), NULL
,
212 _T("Can't load symbol from unloaded library") );
217 #if defined(__WXMAC__) && !defined(__UNIX__)
219 CFragSymbolClass symClass
;
222 c2pstrcpy( (StringPtr
) symName
, name
);
224 strcpy( (char *)symName
, name
);
225 c2pstr( (char *)symName
);
227 if( FindSymbol( dllHandle
, symName
, &symAddress
, &symClass
) == noErr
)
228 symbol
= (void *)symAddress
;
230 #elif defined(__WXPM__) || defined(__EMX__)
231 DosQueryProcAddr( m_handle
, 1L, name
.c_str(), (PFN
*)symbol
);
233 #elif defined(HAVE_DLOPEN)
234 symbol
= dlsym( m_handle
, name
.c_str() );
236 #elif defined(HAVE_SHL_LOAD)
237 if( shl_findsym( &m_handle
, name
.c_str(), TYPE_UNDEFINED
, &symbol
) != 0 )
240 #elif defined(__DARWIN__)
241 if( NSIsSymbolNameDefined( name
.c_str() ) )
242 symbol
= NSAddressOfSymbol( NSLookupAndBindSymbol( name
.c_str() ) );
244 #elif defined(__WINDOWS__)
245 symbol
= (void*) ::GetProcAddress( m_handle
, name
.mb_str() );
248 #error "runtime shared lib support not implemented"
253 wxString
msg(_("wxDynamicLibrary failed to GetSymbol '%s'"));
255 const wxChar
*err
= dlerror();
259 wxLogError( msg
, err
);
263 wxLogSysError(_("Couldn't find symbol '%s' in a dynamic library"),
274 // ---------------------------------------------------------------------------
276 // ---------------------------------------------------------------------------
279 wxDLImports
wxPluginLibrary::ms_classes(wxKEY_STRING
);
281 wxPluginLibrary::wxPluginLibrary(const wxString
&libname
, int flags
)
285 m_before
= wxClassInfo::sm_first
;
286 Load( libname
, flags
);
287 m_after
= wxClassInfo::sm_first
;
295 --m_linkcount
; // Flag us for deletion
298 wxPluginLibrary::~wxPluginLibrary()
307 bool wxPluginLibrary::UnrefLib()
309 wxASSERT_MSG( m_objcount
== 0, _T("Library unloaded before all objects were destroyed") );
310 if( m_linkcount
== 0 || --m_linkcount
== 0 )
318 // ------------------------
320 // ------------------------
322 void wxPluginLibrary::UpdateClassInfo()
325 wxHashTable
*t
= wxClassInfo::sm_classTable
;
327 // FIXME: Below is simply a cut and paste specialisation of
328 // wxClassInfo::InitializeClasses. Once this stabilises,
329 // the two should probably be merged.
331 // Actually it's becoming questionable whether we should merge
332 // this info with the main ClassInfo tables since we can nearly
333 // handle this completely internally now and it does expose
334 // certain (minimal % user_stupidy) risks.
336 for(info
= m_after
; info
!= m_before
; info
= info
->m_next
)
338 if( info
->m_className
)
340 if( t
->Get(info
->m_className
) == 0 )
341 t
->Put(info
->m_className
, (wxObject
*)info
);
343 // Hash all the class names into a local table too so
344 // we can quickly find the entry they correspond to.
346 if( ms_classes
.Get(info
->m_className
) == 0 )
347 ms_classes
.Put(info
->m_className
, (wxObject
*) this);
351 for(info
= m_after
; info
!= m_before
; info
= info
->m_next
)
353 if( info
->m_baseClassName1
)
354 info
->m_baseInfo1
= (wxClassInfo
*)t
->Get(info
->m_baseClassName1
);
355 if( info
->m_baseClassName2
)
356 info
->m_baseInfo2
= (wxClassInfo
*)t
->Get(info
->m_baseClassName2
);
360 void wxPluginLibrary::RestoreClassInfo()
364 for(info
= m_after
; info
!= m_before
; info
= info
->m_next
)
366 wxClassInfo::sm_classTable
->Delete(info
->m_className
);
367 ms_classes
.Delete(info
->m_className
);
370 if( wxClassInfo::sm_first
== m_after
)
371 wxClassInfo::sm_first
= m_before
;
374 info
= wxClassInfo::sm_first
;
375 while( info
->m_next
&& info
->m_next
!= m_after
) info
= info
->m_next
;
377 wxASSERT_MSG( info
, _T("ClassInfo from wxPluginLibrary not found on purge"))
379 info
->m_next
= m_before
;
383 void wxPluginLibrary::RegisterModules()
385 // Plugin libraries might have wxModules, Register and initialise them if
388 // Note that these classes are NOT included in the reference counting since
389 // it's implicit that they will be unloaded if and when the last handle to
390 // the library is. We do have to keep a copy of the module's pointer
391 // though, as there is currently no way to Unregister it without it.
393 wxASSERT_MSG( m_linkcount
== 1,
394 _T("RegisterModules should only be called for the first load") );
396 for(wxClassInfo
*info
= m_after
; info
!= m_before
; info
= info
->m_next
)
398 if( info
->IsKindOf(CLASSINFO(wxModule
)) )
400 wxModule
*m
= wxDynamicCast(info
->CreateObject(), wxModule
);
402 wxASSERT_MSG( m
, _T("wxDynamicCast of wxModule failed") );
404 m_wxmodules
.Append(m
);
405 wxModule::RegisterModule(m
);
409 // FIXME: Likewise this is (well was) very similar to InitializeModules()
411 for(wxModuleList::Node
*node
= m_wxmodules
.GetFirst(); node
; node
->GetNext())
413 if( !node
->GetData()->Init() )
415 wxLogDebug(_T("wxModule::Init() failed for wxPluginLibrary"));
417 // XXX: Watch this, a different hash implementation might break it,
418 // a good hash implementation would let us fix it though.
420 // The name of the game is to remove any uninitialised modules and
421 // let the dtor Exit the rest on shutdown, (which we'll initiate
424 wxModuleList::Node
*oldNode
= 0;
426 node
= node
->GetNext();
428 wxModule::UnregisterModule( node
->GetData() );
432 --m_linkcount
; // Flag us for deletion
438 void wxPluginLibrary::UnregisterModules()
440 wxModuleList::Node
*node
;
442 for(node
= m_wxmodules
.GetFirst(); node
; node
->GetNext())
443 node
->GetData()->Exit();
445 for(node
= m_wxmodules
.GetFirst(); node
; node
->GetNext())
446 wxModule::UnregisterModule( node
->GetData() );
448 m_wxmodules
.DeleteContents(TRUE
);
452 // ---------------------------------------------------------------------------
454 // ---------------------------------------------------------------------------
456 wxDLManifest
wxPluginManager::ms_manifest(wxKEY_STRING
);
458 // ------------------------
460 // ------------------------
462 wxPluginLibrary
*wxPluginManager::LoadLibrary(const wxString
&libname
, int flags
)
464 wxString
realname(libname
);
466 if( !(flags
& wxDL_VERBATIM
) )
467 realname
+= wxDynamicLibrary::GetDllExt();
469 wxPluginLibrary
*entry
= (wxPluginLibrary
*) ms_manifest
.Get(realname
);
477 entry
= new wxPluginLibrary( libname
, flags
);
479 if( entry
->IsLoaded() )
481 ms_manifest
.Put(realname
, (wxObject
*) entry
);
485 wxCHECK_MSG( entry
->UnrefLib(), 0,
486 _T("Currently linked library is, ..not loaded??") );
493 bool wxPluginManager::UnloadLibrary(const wxString
&libname
)
495 wxPluginLibrary
*entry
= (wxPluginLibrary
*) ms_manifest
.Get(libname
);
498 entry
= (wxPluginLibrary
*) ms_manifest
.Get(libname
+ wxDynamicLibrary::GetDllExt());
501 return entry
->UnrefLib();
503 wxLogDebug(_T("Attempt to Unlink library '%s' (which is not linked)."), libname
.c_str());
507 #if WXWIN_COMPATIBILITY_2_2
508 wxPluginLibrary
*wxPluginManager::GetObjectFromHandle(wxDllType handle
)
511 ms_manifest
.BeginFind();
513 for(node
= ms_manifest
.Next(); node
; node
= ms_manifest
.Next())
514 if( ((wxPluginLibrary
*)node
->GetData())->GetLibHandle() == handle
)
515 return (wxPluginLibrary
*)node
->GetData();
521 // ------------------------
522 // Class implementation
523 // ------------------------
525 bool wxPluginManager::Load(const wxString
&libname
, int flags
)
527 m_entry
= wxPluginManager::LoadLibrary(libname
, flags
);
531 void wxPluginManager::Unload()
534 ms_manifest
.BeginFind();
536 // It's either this or store the name of the lib just to do this.
538 for(node
= ms_manifest
.Next(); node
; node
= ms_manifest
.Next())
539 if( (wxPluginLibrary
*)node
->GetData() == m_entry
)
542 if( m_entry
&& m_entry
->UnrefLib() )
551 // ---------------------------------------------------------------------------
552 // For Darwin/Mac OS X
553 // supply the sun style dlopen functions in terms of Darwin NS*
554 // ---------------------------------------------------------------------------
557 #import <mach-o/dyld.h>
565 static char dl_last_error
[1024];
567 static void TranslateError(const char *path
, enum dyldErrorSource type
, int number
)
570 static char *OFIErrorStrings
[] =
572 "%s(%d): Object Image Load Failure\n",
573 "%s(%d): Object Image Load Success\n",
574 "%s(%d): Not an recognisable object file\n",
575 "%s(%d): No valid architecture\n",
576 "%s(%d): Object image has an invalid format\n",
577 "%s(%d): Invalid access (permissions?)\n",
578 "%s(%d): Unknown error code from NSCreateObjectFileImageFromFile\n",
580 #define NUM_OFI_ERRORS (sizeof(OFIErrorStrings) / sizeof(OFIErrorStrings[0]))
586 if (index
> NUM_OFI_ERRORS
- 1) {
587 index
= NUM_OFI_ERRORS
- 1;
589 sprintf(dl_last_error
, OFIErrorStrings
[index
], path
, number
);
593 sprintf(dl_last_error
, "%s(%d): Totally unknown error type %d\n",
602 // ---------------------------------------------------------------------------
603 // wxDllLoader (all these methods are static)
604 // ---------------------------------------------------------------------------
606 #if WXWIN_COMPATIBILITY_2_2
608 wxDllType
wxDllLoader::LoadLibrary(const wxString
&name
)
610 wxPluginLibrary
*p
= wxPluginManager::LoadLibrary(name
, wxDL_DEFAULT
| wxDL_VERBATIM
);
611 return p
->GetLibHandle();
614 void wxDllLoader::UnloadLibrary(wxDllType handle
)
616 wxPluginLibrary
*p
= wxPluginManager::GetObjectFromHandle(handle
);
620 void *wxDllLoader::GetSymbol(wxDllType dllHandle
, const wxString
&name
, bool *success
)
622 wxPluginLibrary
*p
= wxPluginManager::GetObjectFromHandle(dllHandle
);
623 return p
->GetSymbol(name
, success
);
626 #endif // WXWIN_COMPATIBILITY_2_2
628 #endif // wxUSE_DYNAMIC_LOADER