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