]> git.saurik.com Git - wxWidgets.git/blob - src/common/dynload.cpp
tried to clean strdup() mess: we now have wxStrdup[AW] which should be always available
[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 #include "wx/hash.h"
37 #endif
38
39 #include "wx/filename.h" // for SplitPath()
40 #include "wx/strconv.h"
41
42 #include "wx/dynload.h"
43 #include "wx/module.h"
44
45 #if defined(__DARWIN__)
46 /* Porting notes:
47 * The dlopen port is a port from dl_next.xs by Anno Siegel.
48 * dl_next.xs is itself a port from dl_dlopen.xs by Paul Marquess.
49 * The method used here is just to supply the sun style dlopen etc.
50 * functions in terms of Darwin NS*.
51 */
52 void *dlopen(const char *path, int mode /* mode is ignored */);
53 void *dlsym(void *handle, const char *symbol);
54 int dlclose(void *handle);
55 const char *dlerror(void);
56 #endif
57
58 // ============================================================================
59 // implementation
60 // ============================================================================
61
62 // ---------------------------------------------------------------------------
63 // wxDynamicLibrary
64 // ---------------------------------------------------------------------------
65
66 //FIXME: This class isn't really common at all, it should be moved into
67 // platform dependent files.
68
69 #if defined(__WINDOWS__) || defined(__WXPM__) || defined(__EMX__)
70 const wxChar *wxDynamicLibrary::ms_dllext = _T(".dll");
71 #elif defined(__UNIX__)
72 #if defined(__HPUX__)
73 const wxChar *wxDynamicLibrary::ms_dllext = _T(".sl");
74 #else
75 const wxChar *wxDynamicLibrary::ms_dllext = _T(".so");
76 #endif
77 #endif
78
79 wxDllType wxDynamicLibrary::GetProgramHandle()
80 {
81 #if defined( HAVE_DLOPEN ) && !defined(__EMX__)
82 return dlopen(0, RTLD_LAZY);
83 #elif defined (HAVE_SHL_LOAD)
84 return PROG_HANDLE;
85 #else
86 wxFAIL_MSG( wxT("This method is not implemented under Windows or OS/2"));
87 return 0;
88 #endif
89 }
90
91 bool wxDynamicLibrary::Load(wxString libname, int flags)
92 {
93 wxASSERT_MSG(m_handle == 0, _T("Library already loaded."));
94
95 // add the proper extension for the DLL ourselves unless told not to
96 if ( !(flags & wxDL_VERBATIM) )
97 {
98 // and also check that the libname doesn't already have it
99 wxString ext;
100 wxFileName::SplitPath(libname, NULL, NULL, &ext);
101 if ( ext.empty() )
102 {
103 libname += GetDllExt();
104 }
105 }
106
107 // different ways to load a shared library
108 //
109 // FIXME: should go to the platform-specific files!
110 #if defined(__WXMAC__) && !defined(__DARWIN__)
111 FSSpec myFSSpec;
112 Ptr myMainAddr;
113 Str255 myErrName;
114
115 wxMacFilename2FSSpec( libname , &myFSSpec );
116
117 if( GetDiskFragment( &myFSSpec,
118 0,
119 kCFragGoesToEOF,
120 "\p",
121 kPrivateCFragCopy,
122 &m_handle,
123 &myMainAddr,
124 myErrName ) != noErr )
125 {
126 p2cstr( myErrName );
127 wxLogSysError( _("Failed to load shared library '%s' Error '%s'"),
128 libname.c_str(),
129 (char*)myErrName );
130 m_handle = 0;
131 }
132
133 #elif defined(__WXPM__) || defined(__EMX__)
134 char err[256] = "";
135 DosLoadModule(err, sizeof(err), libname.c_str(), &m_handle);
136
137 #elif defined(HAVE_DLOPEN) || defined(__DARWIN__)
138
139 #if defined(__VMS) || defined(__DARWIN__)
140 m_handle = dlopen(libname.c_str(), 0); // The second parameter is ignored
141 #else // !__VMS && !__DARWIN__
142 int rtldFlags = 0;
143
144 if ( flags & wxDL_LAZY )
145 {
146 wxASSERT_MSG( (flags & wxDL_NOW) == 0,
147 _T("wxDL_LAZY and wxDL_NOW are mutually exclusive.") );
148 #ifdef RTLD_LAZY
149 rtldFlags |= RTLD_LAZY;
150 #else
151 wxLogDebug(_T("wxDL_LAZY is not supported on this platform"));
152 #endif
153 }
154 else if ( flags & wxDL_NOW )
155 {
156 #ifdef RTLD_NOW
157 rtldFlags |= RTLD_NOW;
158 #else
159 wxLogDebug(_T("wxDL_NOW is not supported on this platform"));
160 #endif
161 }
162
163 if ( flags & wxDL_GLOBAL )
164 {
165 #ifdef RTLD_GLOBAL
166 rtldFlags |= RTLD_GLOBAL;
167 #else
168 wxLogDebug(_T("RTLD_GLOBAL is not supported on this platform."));
169 #endif
170 }
171
172 m_handle = dlopen(libname.fn_str(), rtldFlags);
173 #endif // __VMS || __DARWIN__ ?
174
175 #elif defined(HAVE_SHL_LOAD)
176 int shlFlags = 0;
177
178 if( flags & wxDL_LAZY )
179 {
180 wxASSERT_MSG( (flags & wxDL_NOW) == 0,
181 _T("wxDL_LAZY and wxDL_NOW are mutually exclusive.") );
182 shlFlags |= BIND_DEFERRED;
183 }
184 else if( flags & wxDL_NOW )
185 {
186 shlFlags |= BIND_IMMEDIATE;
187 }
188 m_handle = shl_load(libname.fn_str(), BIND_DEFERRED, 0);
189
190 #elif defined(__WINDOWS__)
191 m_handle = ::LoadLibrary(libname.c_str());
192 #else
193 #error "runtime shared lib support not implemented on this platform"
194 #endif
195
196 if ( m_handle == 0 )
197 {
198 wxString msg(_("Failed to load shared library '%s'"));
199 #if defined(HAVE_DLERROR) && !defined(__EMX__)
200
201 #if wxUSE_UNICODE
202 wxWCharBuffer buffer = wxConvLocal.cMB2WC( dlerror() );
203 const wxChar *err = buffer;
204 #else
205 const wxChar *err = dlerror();
206 #endif
207
208 if( err )
209 wxLogError( msg, err );
210 #else
211 wxLogSysError( msg, libname.c_str() );
212 #endif
213 }
214
215 return IsLoaded();
216 }
217
218 void wxDynamicLibrary::Unload()
219 {
220 if( IsLoaded() )
221 {
222 #if defined(__WXPM__) || defined(__EMX__)
223 DosFreeModule( m_handle );
224 #elif defined(HAVE_DLOPEN) || defined(__DARWIN__)
225 dlclose( m_handle );
226 #elif defined(HAVE_SHL_LOAD)
227 shl_unload( m_handle );
228 #elif defined(__WINDOWS__)
229 ::FreeLibrary( m_handle );
230 #elif defined(__WXMAC__) && !defined(__DARWIN__)
231 CloseConnection( (CFragConnectionID*) &m_handle );
232 #else
233 #error "runtime shared lib support not implemented"
234 #endif
235 m_handle = 0;
236 }
237 }
238
239 void *wxDynamicLibrary::GetSymbol(const wxString &name, bool *success) const
240 {
241 wxCHECK_MSG( IsLoaded(), NULL,
242 _T("Can't load symbol from unloaded library") );
243
244 bool failed = FALSE;
245 void *symbol = 0;
246
247 #if defined(__WXMAC__) && !defined(__DARWIN__)
248 Ptr symAddress;
249 CFragSymbolClass symClass;
250 Str255 symName;
251 #if TARGET_CARBON
252 c2pstrcpy( (StringPtr) symName, name );
253 #else
254 strcpy( (char *)symName, name );
255 c2pstr( (char *)symName );
256 #endif
257 if( FindSymbol( dllHandle, symName, &symAddress, &symClass ) == noErr )
258 symbol = (void *)symAddress;
259
260 #elif defined(__WXPM__) || defined(__EMX__)
261 DosQueryProcAddr( m_handle, 1L, name.c_str(), (PFN*)symbol );
262
263 #elif defined(HAVE_DLOPEN) || defined(__DARWIN__)
264 symbol = dlsym( m_handle, name.fn_str() );
265
266 #elif defined(HAVE_SHL_LOAD)
267 // use local variable since shl_findsym modifies the handle argument
268 // to indicate where the symbol was found (GD)
269 wxDllType the_handle = m_handle;
270 if( shl_findsym( &the_handle, name.fn_str(), TYPE_UNDEFINED, &symbol ) != 0 )
271 symbol = 0;
272
273 #elif defined(__WINDOWS__)
274 symbol = (void*) ::GetProcAddress( m_handle, name.mb_str() );
275
276 #else
277 #error "runtime shared lib support not implemented"
278 #endif
279
280 if ( !symbol )
281 {
282 wxString msg(_("wxDynamicLibrary failed to GetSymbol '%s'"));
283 #if defined(HAVE_DLERROR) && !defined(__EMX__)
284
285 #if wxUSE_UNICODE
286 wxWCharBuffer buffer = wxConvLocal.cMB2WC( dlerror() );
287 const wxChar *err = buffer;
288 #else
289 const wxChar *err = dlerror();
290 #endif
291
292 if( err )
293 {
294 failed = TRUE;
295 wxLogError( msg, err );
296 }
297 #else
298 failed = TRUE;
299 wxLogSysError(_("Couldn't find symbol '%s' in a dynamic library"),
300 name.c_str());
301 #endif
302 }
303 if( success )
304 *success = !failed;
305
306 return symbol;
307 }
308
309
310 // ---------------------------------------------------------------------------
311 // wxPluginLibrary
312 // ---------------------------------------------------------------------------
313
314
315 wxDLImports* wxPluginLibrary::ms_classes = NULL;
316
317 class wxPluginLibraryModule : public wxModule
318 {
319 public:
320 wxPluginLibraryModule() { }
321
322 // TODO: create ms_classes on demand, why always preallocate it?
323 virtual bool OnInit()
324 {
325 wxPluginLibrary::ms_classes = new wxDLImports(wxKEY_STRING);
326 wxPluginManager::CreateManifest();
327 return TRUE;
328 }
329
330 virtual void OnExit()
331 {
332 delete wxPluginLibrary::ms_classes;
333 wxPluginLibrary::ms_classes = NULL;
334 wxPluginManager::ClearManifest();
335 }
336
337 private:
338 DECLARE_DYNAMIC_CLASS(wxPluginLibraryModule )
339 };
340
341 IMPLEMENT_DYNAMIC_CLASS(wxPluginLibraryModule, wxModule)
342
343
344 wxPluginLibrary::wxPluginLibrary(const wxString &libname, int flags)
345 : m_linkcount(1)
346 , m_objcount(0)
347 {
348 m_before = wxClassInfo::sm_first;
349 Load( libname, flags );
350 m_after = wxClassInfo::sm_first;
351
352 if( m_handle != 0 )
353 {
354 UpdateClassInfo();
355 RegisterModules();
356 }
357 else
358 {
359 // Flag us for deletion
360 --m_linkcount;
361 }
362 }
363
364 wxPluginLibrary::~wxPluginLibrary()
365 {
366 if( m_handle != 0 )
367 {
368 UnregisterModules();
369 RestoreClassInfo();
370 }
371 }
372
373 wxPluginLibrary *wxPluginLibrary::RefLib()
374 {
375 wxCHECK_MSG( m_linkcount > 0, NULL,
376 _T("Library had been already deleted!") );
377
378 ++m_linkcount;
379 return this;
380 }
381
382 bool wxPluginLibrary::UnrefLib()
383 {
384 wxASSERT_MSG( m_objcount == 0,
385 _T("Library unloaded before all objects were destroyed") );
386
387 if ( --m_linkcount == 0 )
388 {
389 delete this;
390 return TRUE;
391 }
392
393 return FALSE;
394 }
395
396 // ------------------------
397 // Private methods
398 // ------------------------
399
400 void wxPluginLibrary::UpdateClassInfo()
401 {
402 wxClassInfo *info;
403 wxHashTable *t = wxClassInfo::sm_classTable;
404
405 // FIXME: Below is simply a cut and paste specialisation of
406 // wxClassInfo::InitializeClasses. Once this stabilises,
407 // the two should probably be merged.
408 //
409 // Actually it's becoming questionable whether we should merge
410 // this info with the main ClassInfo tables since we can nearly
411 // handle this completely internally now and it does expose
412 // certain (minimal % user_stupidy) risks.
413
414 for(info = m_after; info != m_before; info = info->m_next)
415 {
416 if( info->m_className )
417 {
418 if( t->Get(info->m_className) == 0 )
419 t->Put(info->m_className, (wxObject *)info);
420
421 // Hash all the class names into a local table too so
422 // we can quickly find the entry they correspond to.
423 (*ms_classes)[info->m_className] = this;
424 }
425 }
426
427 for(info = m_after; info != m_before; info = info->m_next)
428 {
429 if( info->m_baseClassName1 )
430 info->m_baseInfo1 = (wxClassInfo *)t->Get(info->m_baseClassName1);
431 if( info->m_baseClassName2 )
432 info->m_baseInfo2 = (wxClassInfo *)t->Get(info->m_baseClassName2);
433 }
434 }
435
436 void wxPluginLibrary::RestoreClassInfo()
437 {
438 wxClassInfo *info;
439
440 for(info = m_after; info != m_before; info = info->m_next)
441 {
442 wxClassInfo::sm_classTable->Delete(info->m_className);
443 ms_classes->erase(ms_classes->find(info->m_className));
444 }
445
446 if( wxClassInfo::sm_first == m_after )
447 wxClassInfo::sm_first = m_before;
448 else
449 {
450 info = wxClassInfo::sm_first;
451 while( info->m_next && info->m_next != m_after ) info = info->m_next;
452
453 wxASSERT_MSG( info, _T("ClassInfo from wxPluginLibrary not found on purge"));
454
455 info->m_next = m_before;
456 }
457 }
458
459 void wxPluginLibrary::RegisterModules()
460 {
461 // Plugin libraries might have wxModules, Register and initialise them if
462 // they do.
463 //
464 // Note that these classes are NOT included in the reference counting since
465 // it's implicit that they will be unloaded if and when the last handle to
466 // the library is. We do have to keep a copy of the module's pointer
467 // though, as there is currently no way to Unregister it without it.
468
469 wxASSERT_MSG( m_linkcount == 1,
470 _T("RegisterModules should only be called for the first load") );
471
472 for ( wxClassInfo *info = m_after; info != m_before; info = info->m_next)
473 {
474 if( info->IsKindOf(CLASSINFO(wxModule)) )
475 {
476 wxModule *m = wxDynamicCast(info->CreateObject(), wxModule);
477
478 wxASSERT_MSG( m, _T("wxDynamicCast of wxModule failed") );
479
480 m_wxmodules.Append(m);
481 wxModule::RegisterModule(m);
482 }
483 }
484
485 // FIXME: Likewise this is (well was) very similar to InitializeModules()
486
487 for ( wxModuleList::Node *node = m_wxmodules.GetFirst();
488 node;
489 node = node->GetNext())
490 {
491 if( !node->GetData()->Init() )
492 {
493 wxLogDebug(_T("wxModule::Init() failed for wxPluginLibrary"));
494
495 // XXX: Watch this, a different hash implementation might break it,
496 // a good hash implementation would let us fix it though.
497
498 // The name of the game is to remove any uninitialised modules and
499 // let the dtor Exit the rest on shutdown, (which we'll initiate
500 // shortly).
501
502 wxModuleList::Node *oldNode = 0;
503 do {
504 node = node->GetNext();
505 delete oldNode;
506 wxModule::UnregisterModule( node->GetData() );
507 oldNode = node;
508 } while( node );
509
510 --m_linkcount; // Flag us for deletion
511 break;
512 }
513 }
514 }
515
516 void wxPluginLibrary::UnregisterModules()
517 {
518 wxModuleList::Node *node;
519
520 for ( node = m_wxmodules.GetFirst(); node; node = node->GetNext() )
521 node->GetData()->Exit();
522
523 for ( node = m_wxmodules.GetFirst(); node; node = node->GetNext() )
524 wxModule::UnregisterModule( node->GetData() );
525
526 m_wxmodules.DeleteContents(TRUE);
527 }
528
529
530 // ---------------------------------------------------------------------------
531 // wxPluginManager
532 // ---------------------------------------------------------------------------
533
534 wxDLManifest* wxPluginManager::ms_manifest = NULL;
535
536 // ------------------------
537 // Static accessors
538 // ------------------------
539
540 wxPluginLibrary *
541 wxPluginManager::LoadLibrary(const wxString &libname, int flags)
542 {
543 wxString realname(libname);
544
545 if( !(flags & wxDL_VERBATIM) )
546 realname += wxDynamicLibrary::GetDllExt();
547
548 wxPluginLibrary *entry;
549
550 if ( flags & wxDL_NOSHARE )
551 {
552 entry = NULL;
553 }
554 else
555 {
556 entry = FindByName(realname);
557 }
558
559 if ( entry )
560 {
561 wxLogTrace(_T("dll"),
562 _T("LoadLibrary(%s): already loaded."), realname.c_str());
563
564 entry->RefLib();
565 }
566 else
567 {
568 entry = new wxPluginLibrary( libname, flags );
569
570 if ( entry->IsLoaded() )
571 {
572 (*ms_manifest)[realname] = entry;
573
574 wxLogTrace(_T("dll"),
575 _T("LoadLibrary(%s): loaded ok."), realname.c_str());
576
577 }
578 else
579 {
580 wxLogTrace(_T("dll"),
581 _T("LoadLibrary(%s): failed to load."), realname.c_str());
582
583 // we have created entry just above
584 if ( !entry->UnrefLib() )
585 {
586 // ... so UnrefLib() is supposed to delete it
587 wxFAIL_MSG( _T("Currently linked library is not loaded?") );
588 }
589
590 entry = NULL;
591 }
592 }
593
594 return entry;
595 }
596
597 bool wxPluginManager::UnloadLibrary(const wxString& libname)
598 {
599 wxString realname = libname;
600
601 wxPluginLibrary *entry = FindByName(realname);
602
603 if ( !entry )
604 {
605 realname += wxDynamicLibrary::GetDllExt();
606
607 entry = FindByName(realname);
608 }
609
610 if ( !entry )
611 {
612 wxLogDebug(_T("Attempt to unload library '%s' which is not loaded."),
613 libname.c_str());
614
615 return FALSE;
616 }
617
618 wxLogTrace(_T("dll"), _T("UnloadLibrary(%s)"), realname.c_str());
619
620 if ( !entry->UnrefLib() )
621 {
622 // not really unloaded yet
623 return FALSE;
624 }
625
626 ms_manifest->erase(ms_manifest->find(realname));
627
628 return TRUE;
629 }
630
631 #if WXWIN_COMPATIBILITY_2_2
632 wxPluginLibrary *wxPluginManager::GetObjectFromHandle(wxDllType handle)
633 {
634 for ( wxDLManifest::iterator i = ms_manifest->begin();
635 i != ms_manifest->end();
636 ++i )
637 {
638 wxPluginLibrary * const lib = i->second;
639
640 if ( lib->GetLibHandle() == handle )
641 return lib;
642 }
643
644 return NULL;
645 }
646 #endif // WXWIN_COMPATIBILITY_2_2
647
648 // ------------------------
649 // Class implementation
650 // ------------------------
651
652 bool wxPluginManager::Load(const wxString &libname, int flags)
653 {
654 m_entry = wxPluginManager::LoadLibrary(libname, flags);
655
656 return IsLoaded();
657 }
658
659 void wxPluginManager::Unload()
660 {
661 wxCHECK_RET( m_entry, _T("unloading an invalid wxPluginManager?") );
662
663 for ( wxDLManifest::iterator i = ms_manifest->begin();
664 i != ms_manifest->end();
665 ++i )
666 {
667 if ( i->second == m_entry )
668 {
669 ms_manifest->erase(i);
670 return;
671 }
672 }
673
674 m_entry->UnrefLib();
675
676 m_entry = NULL;
677 }
678
679 // ---------------------------------------------------------------------------
680 // wxDllLoader (all these methods are static)
681 // ---------------------------------------------------------------------------
682
683 #if WXWIN_COMPATIBILITY_2_2
684
685 wxDllType wxDllLoader::LoadLibrary(const wxString &name, bool *success)
686 {
687 wxPluginLibrary *p = wxPluginManager::LoadLibrary
688 (
689 name,
690 wxDL_DEFAULT | wxDL_VERBATIM | wxDL_NOSHARE
691 );
692
693 if ( success )
694 *success = p != NULL;
695
696 return p ? p->GetLibHandle() : 0;
697 }
698
699 void wxDllLoader::UnloadLibrary(wxDllType handle)
700 {
701 wxPluginLibrary *p = wxPluginManager::GetObjectFromHandle(handle);
702
703 wxCHECK_RET( p, _T("Unloading a library not loaded with wxDllLoader?") );
704
705 p->UnrefLib();
706 }
707
708 void *
709 wxDllLoader::GetSymbol(wxDllType dllHandle, const wxString &name, bool *success)
710 {
711 wxPluginLibrary *p = wxPluginManager::GetObjectFromHandle(dllHandle);
712
713 if ( !p )
714 {
715 wxFAIL_MSG( _T("Using a library not loaded with wxDllLoader?") );
716
717 if ( success )
718 *success = FALSE;
719
720 return NULL;
721 }
722
723 return p->GetSymbol(name, success);
724 }
725
726 #endif // WXWIN_COMPATIBILITY_2_2
727
728 #endif // wxUSE_DYNAMIC_LOADER
729