]> git.saurik.com Git - wxWidgets.git/blob - src/common/dynload.cpp
b127ecf5d2985daa86a860feb902ac9382655a54
[wxWidgets.git] / src / common / dynload.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: dynload.cpp
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)
6 // Modified by:
7 // Created: 03/12/01
8 // RCS-ID: $Id$
9 // Copyright: (c) 2001 Ron Lee <ron@debian.org>
10 // Licence: wxWindows license
11 /////////////////////////////////////////////////////////////////////////////
12
13 #ifdef __GNUG__
14 #pragma implementation "dynload.h"
15 #endif
16
17 // ----------------------------------------------------------------------------
18 // headers
19 // ----------------------------------------------------------------------------
20
21 #include "wx/wxprec.h"
22
23 #ifdef __BORLANDC__
24 #pragma hdrstop
25 #endif
26
27 #if wxUSE_DYNAMIC_LOADER
28
29 #ifdef __WINDOWS__
30 #include "wx/msw/private.h"
31 #endif
32
33 #ifndef WX_PRECOMP
34 #include "wx/log.h"
35 #include "wx/intl.h"
36 #endif
37
38 #include "wx/filename.h" // for SplitPath()
39
40 #include "wx/dynload.h"
41
42 #if defined(__DARWIN__)
43 /* Porting notes:
44 * The dlopen port is a port from dl_next.xs by Anno Siegel.
45 * dl_next.xs is itself a port from dl_dlopen.xs by Paul Marquess.
46 * The method used here is just to supply the sun style dlopen etc.
47 * functions in terms of Darwin NS*.
48 */
49 void *dlopen(const char *path, int mode /* mode is ignored */);
50 void *dlsym(void *handle, const char *symbol);
51 int dlclose(void *handle);
52 const char *dlerror(void);
53 #endif
54
55 // ============================================================================
56 // implementation
57 // ============================================================================
58
59 // ---------------------------------------------------------------------------
60 // wxDynamicLibrary
61 // ---------------------------------------------------------------------------
62
63 //FIXME: This class isn't really common at all, it should be moved into
64 // platform dependent files.
65
66 #if defined(__WINDOWS__) || defined(__WXPM__) || defined(__EMX__)
67 const wxString wxDynamicLibrary::ms_dllext( _T(".dll") );
68 #elif defined(__UNIX__)
69 #if defined(__HPUX__)
70 const wxString wxDynamicLibrary::ms_dllext( _T(".sl") );
71 #else
72 const wxString wxDynamicLibrary::ms_dllext( _T(".so") );
73 #endif
74 #endif
75
76 wxDllType wxDynamicLibrary::GetProgramHandle()
77 {
78 #if defined( HAVE_DLOPEN ) && !defined(__EMX__)
79 return dlopen(0, RTLD_LAZY);
80 #elif defined (HAVE_SHL_LOAD)
81 return PROG_HANDLE;
82 #else
83 wxFAIL_MSG( wxT("This method is not implemented under Windows or OS/2"));
84 return 0;
85 #endif
86 }
87
88 bool wxDynamicLibrary::Load(wxString libname, int flags)
89 {
90 wxASSERT_MSG(m_handle == 0, _T("Library already loaded."));
91
92 // add the proper extension for the DLL ourselves unless told not to
93 if ( !(flags & wxDL_VERBATIM) )
94 {
95 // and also check that the libname doesn't already have it
96 wxString ext;
97 wxFileName::SplitPath(libname, NULL, NULL, &ext);
98 if ( ext.empty() )
99 {
100 libname += GetDllExt();
101 }
102 }
103
104 #if defined(__WXMAC__) && !defined(__DARWIN__)
105 FSSpec myFSSpec;
106 Ptr myMainAddr;
107 Str255 myErrName;
108
109 wxMacFilename2FSSpec( libname , &myFSSpec );
110
111 if( GetDiskFragment( &myFSSpec,
112 0,
113 kCFragGoesToEOF,
114 "\p",
115 kPrivateCFragCopy,
116 &m_handle,
117 &myMainAddr,
118 myErrName ) != noErr )
119 {
120 p2cstr( myErrName );
121 wxLogSysError( _("Failed to load shared library '%s' Error '%s'"),
122 libname.c_str(),
123 (char*)myErrName );
124 m_handle = 0;
125 }
126
127 #elif defined(__WXPM__) || defined(__EMX__)
128 char err[256] = "";
129 DosLoadModule(err, sizeof(err), libname.c_str(), &m_handle);
130
131 #elif defined(HAVE_DLOPEN) || defined(__DARWIN__)
132
133 #if defined(__VMS) || defined(__DARWIN__)
134 m_handle = dlopen(libname.c_str(), 0); // The second parameter is ignored
135 #else
136 int rtldFlags = 0;
137
138 if( flags & wxDL_LAZY )
139 {
140 wxASSERT_MSG( (flags & wxDL_NOW) == 0,
141 _T("wxDL_LAZY and wxDL_NOW are mutually exclusive.") );
142 rtldFlags |= RTLD_LAZY;
143 }
144 else if( flags & wxDL_NOW )
145 {
146 rtldFlags |= RTLD_NOW;
147 }
148 if( flags & wxDL_GLOBAL )
149 {
150 #ifdef __osf__
151 wxLogDebug(_T("WARNING: RTLD_GLOBAL is not a supported on this platform."));
152 #endif
153 rtldFlags |= RTLD_GLOBAL;
154 }
155
156 m_handle = dlopen(libname.c_str(), rtldFlags);
157 #endif // __VMS || __DARWIN__
158
159 #elif defined(HAVE_SHL_LOAD)
160 int shlFlags = 0;
161
162 if( flags & wxDL_LAZY )
163 {
164 wxASSERT_MSG( (flags & wxDL_NOW) == 0,
165 _T("wxDL_LAZY and wxDL_NOW are mutually exclusive.") );
166 shlFlags |= BIND_DEFERRED;
167 }
168 else if( flags & wxDL_NOW )
169 {
170 shlFlags |= BIND_IMMEDIATE;
171 }
172 m_handle = shl_load(libname.c_str(), BIND_DEFERRED, 0);
173
174 #elif defined(__WINDOWS__)
175 m_handle = ::LoadLibrary(libname.c_str());
176
177 #else
178 #error "runtime shared lib support not implemented"
179 #endif
180
181 if ( m_handle == 0 )
182 {
183 wxString msg(_("Failed to load shared library '%s'"));
184 #if defined(HAVE_DLERROR) && !defined(__EMX__)
185 const wxChar *err = dlerror();
186 if( err )
187 wxLogError( msg, err );
188 #else
189 wxLogSysError( msg, libname.c_str() );
190 #endif
191 }
192
193 return IsLoaded();
194 }
195
196 void wxDynamicLibrary::Unload()
197 {
198 if( IsLoaded() )
199 {
200 #if defined(__WXPM__) || defined(__EMX__)
201 DosFreeModule( m_handle );
202 #elif defined(HAVE_DLOPEN) || defined(__DARWIN__)
203 dlclose( m_handle );
204 #elif defined(HAVE_SHL_LOAD)
205 shl_unload( m_handle );
206 #elif defined(__WINDOWS__)
207 ::FreeLibrary( m_handle );
208 #elif defined(__WXMAC__) && !defined(__DARWIN__)
209 CloseConnection( (CFragConnectionID*) &m_handle );
210 #else
211 #error "runtime shared lib support not implemented"
212 #endif
213 m_handle = 0;
214 }
215 }
216
217 void *wxDynamicLibrary::GetSymbol(const wxString &name, bool *success) const
218 {
219 wxCHECK_MSG( IsLoaded(), NULL,
220 _T("Can't load symbol from unloaded library") );
221
222 bool failed = FALSE;
223 void *symbol = 0;
224
225 #if defined(__WXMAC__) && !defined(__DARWIN__)
226 Ptr symAddress;
227 CFragSymbolClass symClass;
228 Str255 symName;
229 #if TARGET_CARBON
230 c2pstrcpy( (StringPtr) symName, name );
231 #else
232 strcpy( (char *)symName, name );
233 c2pstr( (char *)symName );
234 #endif
235 if( FindSymbol( dllHandle, symName, &symAddress, &symClass ) == noErr )
236 symbol = (void *)symAddress;
237
238 #elif defined(__WXPM__) || defined(__EMX__)
239 DosQueryProcAddr( m_handle, 1L, name.c_str(), (PFN*)symbol );
240
241 #elif defined(HAVE_DLOPEN) || defined(__DARWIN__)
242 symbol = dlsym( m_handle, name.c_str() );
243
244 #elif defined(HAVE_SHL_LOAD)
245 if( shl_findsym( &m_handle, name.c_str(), TYPE_UNDEFINED, &symbol ) != 0 )
246 symbol = 0;
247
248 #elif defined(__WINDOWS__)
249 symbol = (void*) ::GetProcAddress( m_handle, name.mb_str() );
250
251 #else
252 #error "runtime shared lib support not implemented"
253 #endif
254
255 if ( !symbol )
256 {
257 wxString msg(_("wxDynamicLibrary failed to GetSymbol '%s'"));
258 #if defined(HAVE_DLERROR) && !defined(__EMX__)
259 const wxChar *err = dlerror();
260 if( err )
261 {
262 failed = TRUE;
263 wxLogError( msg, err );
264 }
265 #else
266 failed = TRUE;
267 wxLogSysError(_("Couldn't find symbol '%s' in a dynamic library"),
268 name.c_str());
269 #endif
270 }
271 if( success )
272 *success = !failed;
273
274 return symbol;
275 }
276
277
278 // ---------------------------------------------------------------------------
279 // wxPluginLibrary
280 // ---------------------------------------------------------------------------
281
282
283 wxDLImports wxPluginLibrary::ms_classes(wxKEY_STRING);
284
285 wxPluginLibrary::wxPluginLibrary(const wxString &libname, int flags)
286 : m_linkcount(1)
287 , m_objcount(0)
288 {
289 m_before = wxClassInfo::sm_first;
290 Load( libname, flags );
291 m_after = wxClassInfo::sm_first;
292
293 if( m_handle != 0 )
294 {
295 UpdateClassInfo();
296 RegisterModules();
297 }
298 else
299 --m_linkcount; // Flag us for deletion
300 }
301
302 wxPluginLibrary::~wxPluginLibrary()
303 {
304 if( m_handle != 0 )
305 {
306 UnregisterModules();
307 RestoreClassInfo();
308 }
309 }
310
311 bool wxPluginLibrary::UnrefLib()
312 {
313 wxASSERT_MSG( m_objcount == 0, _T("Library unloaded before all objects were destroyed") );
314 if( m_linkcount == 0 || --m_linkcount == 0 )
315 {
316 delete this;
317 return TRUE;
318 }
319 return FALSE;
320 }
321
322 // ------------------------
323 // Private methods
324 // ------------------------
325
326 void wxPluginLibrary::UpdateClassInfo()
327 {
328 wxClassInfo *info;
329 wxHashTable *t = wxClassInfo::sm_classTable;
330
331 // FIXME: Below is simply a cut and paste specialisation of
332 // wxClassInfo::InitializeClasses. Once this stabilises,
333 // the two should probably be merged.
334 //
335 // Actually it's becoming questionable whether we should merge
336 // this info with the main ClassInfo tables since we can nearly
337 // handle this completely internally now and it does expose
338 // certain (minimal % user_stupidy) risks.
339
340 for(info = m_after; info != m_before; info = info->m_next)
341 {
342 if( info->m_className )
343 {
344 if( t->Get(info->m_className) == 0 )
345 t->Put(info->m_className, (wxObject *)info);
346
347 // Hash all the class names into a local table too so
348 // we can quickly find the entry they correspond to.
349
350 if( ms_classes.Get(info->m_className) == 0 )
351 ms_classes.Put(info->m_className, (wxObject *) this);
352 }
353 }
354
355 for(info = m_after; info != m_before; info = info->m_next)
356 {
357 if( info->m_baseClassName1 )
358 info->m_baseInfo1 = (wxClassInfo *)t->Get(info->m_baseClassName1);
359 if( info->m_baseClassName2 )
360 info->m_baseInfo2 = (wxClassInfo *)t->Get(info->m_baseClassName2);
361 }
362 }
363
364 void wxPluginLibrary::RestoreClassInfo()
365 {
366 wxClassInfo *info;
367
368 for(info = m_after; info != m_before; info = info->m_next)
369 {
370 wxClassInfo::sm_classTable->Delete(info->m_className);
371 ms_classes.Delete(info->m_className);
372 }
373
374 if( wxClassInfo::sm_first == m_after )
375 wxClassInfo::sm_first = m_before;
376 else
377 {
378 info = wxClassInfo::sm_first;
379 while( info->m_next && info->m_next != m_after ) info = info->m_next;
380
381 wxASSERT_MSG( info, _T("ClassInfo from wxPluginLibrary not found on purge"))
382
383 info->m_next = m_before;
384 }
385 }
386
387 void wxPluginLibrary::RegisterModules()
388 {
389 // Plugin libraries might have wxModules, Register and initialise them if
390 // they do.
391 //
392 // Note that these classes are NOT included in the reference counting since
393 // it's implicit that they will be unloaded if and when the last handle to
394 // the library is. We do have to keep a copy of the module's pointer
395 // though, as there is currently no way to Unregister it without it.
396
397 wxASSERT_MSG( m_linkcount == 1,
398 _T("RegisterModules should only be called for the first load") );
399
400 for(wxClassInfo *info = m_after; info != m_before; info = info->m_next)
401 {
402 if( info->IsKindOf(CLASSINFO(wxModule)) )
403 {
404 wxModule *m = wxDynamicCast(info->CreateObject(), wxModule);
405
406 wxASSERT_MSG( m, _T("wxDynamicCast of wxModule failed") );
407
408 m_wxmodules.Append(m);
409 wxModule::RegisterModule(m);
410 }
411 }
412
413 // FIXME: Likewise this is (well was) very similar to InitializeModules()
414
415 for(wxModuleList::Node *node = m_wxmodules.GetFirst(); node; node->GetNext())
416 {
417 if( !node->GetData()->Init() )
418 {
419 wxLogDebug(_T("wxModule::Init() failed for wxPluginLibrary"));
420
421 // XXX: Watch this, a different hash implementation might break it,
422 // a good hash implementation would let us fix it though.
423
424 // The name of the game is to remove any uninitialised modules and
425 // let the dtor Exit the rest on shutdown, (which we'll initiate
426 // shortly).
427
428 wxModuleList::Node *oldNode = 0;
429 do {
430 node = node->GetNext();
431 delete oldNode;
432 wxModule::UnregisterModule( node->GetData() );
433 oldNode = node;
434 } while( node );
435
436 --m_linkcount; // Flag us for deletion
437 break;
438 }
439 }
440 }
441
442 void wxPluginLibrary::UnregisterModules()
443 {
444 wxModuleList::Node *node;
445
446 for(node = m_wxmodules.GetFirst(); node; node->GetNext())
447 node->GetData()->Exit();
448
449 for(node = m_wxmodules.GetFirst(); node; node->GetNext())
450 wxModule::UnregisterModule( node->GetData() );
451
452 m_wxmodules.DeleteContents(TRUE);
453 }
454
455
456 // ---------------------------------------------------------------------------
457 // wxPluginLibrary
458 // ---------------------------------------------------------------------------
459
460 wxDLManifest wxPluginManager::ms_manifest(wxKEY_STRING);
461
462 // ------------------------
463 // Static accessors
464 // ------------------------
465
466 wxPluginLibrary *wxPluginManager::LoadLibrary(const wxString &libname, int flags)
467 {
468 wxString realname(libname);
469
470 if( !(flags & wxDL_VERBATIM) )
471 realname += wxDynamicLibrary::GetDllExt();
472
473 wxPluginLibrary *entry = (wxPluginLibrary*) ms_manifest.Get(realname);
474
475 if( entry != 0 )
476 {
477 entry->RefLib();
478 }
479 else
480 {
481 entry = new wxPluginLibrary( libname, flags );
482
483 if( entry->IsLoaded() )
484 {
485 ms_manifest.Put(realname, (wxObject*) entry);
486 }
487 else
488 {
489 wxCHECK_MSG( entry->UnrefLib(), 0,
490 _T("Currently linked library is, ..not loaded??") );
491 entry = 0;
492 }
493 }
494 return entry;
495 }
496
497 bool wxPluginManager::UnloadLibrary(const wxString &libname)
498 {
499 wxPluginLibrary *entry = (wxPluginLibrary*) ms_manifest.Get(libname);
500
501 if( !entry )
502 entry = (wxPluginLibrary*) ms_manifest.Get(libname + wxDynamicLibrary::GetDllExt());
503
504 if( entry )
505 return entry->UnrefLib();
506
507 wxLogDebug(_T("Attempt to Unlink library '%s' (which is not linked)."), libname.c_str());
508 return FALSE;
509 }
510
511 #if WXWIN_COMPATIBILITY_2_2
512 wxPluginLibrary *wxPluginManager::GetObjectFromHandle(wxDllType handle)
513 {
514 wxNode *node;
515 ms_manifest.BeginFind();
516
517 for(node = ms_manifest.Next(); node; node = ms_manifest.Next())
518 if( ((wxPluginLibrary*)node->GetData())->GetLibHandle() == handle )
519 return (wxPluginLibrary*)node->GetData();
520
521 return 0;
522 }
523 #endif
524
525 // ------------------------
526 // Class implementation
527 // ------------------------
528
529 bool wxPluginManager::Load(const wxString &libname, int flags)
530 {
531 m_entry = wxPluginManager::LoadLibrary(libname, flags);
532 return IsLoaded();
533 }
534
535 void wxPluginManager::Unload()
536 {
537 wxNode *node;
538 ms_manifest.BeginFind();
539
540 // It's either this or store the name of the lib just to do this.
541
542 for(node = ms_manifest.Next(); node; node = ms_manifest.Next())
543 if( (wxPluginLibrary*)node->GetData() == m_entry )
544 break;
545
546 if( m_entry && m_entry->UnrefLib() )
547 {
548 delete node;
549 m_entry = 0;
550 }
551 }
552
553 // ---------------------------------------------------------------------------
554 // wxDllLoader (all these methods are static)
555 // ---------------------------------------------------------------------------
556
557 #if WXWIN_COMPATIBILITY_2_2
558
559 wxDllType wxDllLoader::LoadLibrary(const wxString &name)
560 {
561 wxPluginLibrary *p = wxPluginManager::LoadLibrary(name, wxDL_DEFAULT | wxDL_VERBATIM);
562 return p->GetLibHandle();
563 }
564
565 void wxDllLoader::UnloadLibrary(wxDllType handle)
566 {
567 wxPluginLibrary *p = wxPluginManager::GetObjectFromHandle(handle);
568 p->UnrefLib();
569 }
570
571 void *wxDllLoader::GetSymbol(wxDllType dllHandle, const wxString &name, bool *success)
572 {
573 wxPluginLibrary *p = wxPluginManager::GetObjectFromHandle(dllHandle);
574 return p->GetSymbol(name, success);
575 }
576
577 #endif // WXWIN_COMPATIBILITY_2_2
578
579 #endif // wxUSE_DYNAMIC_LOADER
580
581 // vi:sts=4:sw=4:et