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