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