]> git.saurik.com Git - wxWidgets.git/blob - src/common/dynload.cpp
install wxUniv headers in make install and include wxUniv sources in make dist
[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 // ============================================================================
43 // implementation
44 // ============================================================================
45
46 // ---------------------------------------------------------------------------
47 // wxDynamicLibrary
48 // ---------------------------------------------------------------------------
49
50 //FIXME: This class isn't really common at all, it should be moved into
51 // platform dependent files.
52
53 #if defined(__WINDOWS__) || defined(__WXPM__) || defined(__EMX__)
54 const wxString wxDynamicLibrary::ms_dllext( _T(".dll") );
55 #elif defined(__UNIX__)
56 #if defined(__HPUX__)
57 const wxString wxDynamicLibrary::ms_dllext( _T(".sl") );
58 #else
59 const wxString wxDynamicLibrary::ms_dllext( _T(".so") );
60 #endif
61 #endif
62
63 wxDllType wxDynamicLibrary::GetProgramHandle()
64 {
65 #if defined( HAVE_DLOPEN ) && !defined(__EMX__)
66 return dlopen(0, RTLD_LAZY);
67 #elif defined (HAVE_SHL_LOAD)
68 return PROG_HANDLE;
69 #else
70 wxFAIL_MSG( wxT("This method is not implemented under Windows or OS/2"));
71 return 0;
72 #endif
73 }
74
75 bool wxDynamicLibrary::Load(wxString libname, int flags)
76 {
77 wxASSERT_MSG(m_handle == 0, _T("Library already loaded."));
78
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 }
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,
103 &m_handle,
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 );
111 m_handle = 0;
112 }
113
114 #elif defined(__WXPM__) || defined(__EMX__)
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
179 #else
180 #error "runtime shared lib support not implemented"
181 #endif
182
183 if ( m_handle == 0 )
184 {
185 wxString msg(_("Failed to load shared library '%s'"));
186 #ifdef HAVE_DLERROR
187 const wxChar *err = dlerror();
188 if( err )
189 wxLogError( msg, err );
190 #else
191 wxLogSysError( msg, libname.c_str() );
192 #endif
193 }
194
195 return IsLoaded();
196 }
197
198 void wxDynamicLibrary::Unload()
199 {
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 }
217 }
218
219 void *wxDynamicLibrary::GetSymbol(const wxString &name, bool *success) const
220 {
221 wxCHECK_MSG( IsLoaded(), NULL,
222 _T("Can't load symbol from unloaded library") );
223
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
234 strcpy( (char *)symName, name );
235 c2pstr( (char *)symName );
236 #endif
237 if( FindSymbol( dllHandle, symName, &symAddress, &symClass ) == noErr )
238 symbol = (void *)symAddress;
239
240 #elif defined(__WXPM__) || defined(__EMX__)
241 DosQueryProcAddr( m_handle, 1L, name.c_str(), (PFN*)symbol );
242
243 #elif defined(HAVE_DLOPEN)
244 symbol = dlsym( m_handle, name.c_str() );
245
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__)
255 symbol = (void*) ::GetProcAddress( m_handle, name.mb_str() );
256
257 #else
258 #error "runtime shared lib support not implemented"
259 #endif
260
261 if ( !symbol )
262 {
263 wxString msg(_("wxDynamicLibrary failed to GetSymbol '%s'"));
264 #ifdef HAVE_DLERROR
265 const wxChar *err = dlerror();
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 // ---------------------------------------------------------------------------
285 // wxPluginLibrary
286 // ---------------------------------------------------------------------------
287
288
289 wxDLImports wxPluginLibrary::ms_classes(wxKEY_STRING);
290
291 wxPluginLibrary::wxPluginLibrary(const wxString &libname, int flags)
292 : m_linkcount(1)
293 , m_objcount(0)
294 {
295 m_before = wxClassInfo::sm_first;
296 Load( libname, flags );
297 m_after = wxClassInfo::sm_first;
298
299 if( m_handle != 0 )
300 {
301 UpdateClassInfo();
302 RegisterModules();
303 }
304 else
305 --m_linkcount; // Flag us for deletion
306 }
307
308 wxPluginLibrary::~wxPluginLibrary()
309 {
310 if( m_handle != 0 )
311 {
312 UnregisterModules();
313 RestoreClassInfo();
314 }
315 }
316
317 bool wxPluginLibrary::UnrefLib()
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 }
327
328 // ------------------------
329 // Private methods
330 // ------------------------
331
332 void wxPluginLibrary::UpdateClassInfo()
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
370 void wxPluginLibrary::RestoreClassInfo()
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
387 wxASSERT_MSG( info, _T("ClassInfo from wxPluginLibrary not found on purge"))
388
389 info->m_next = m_before;
390 }
391 }
392
393 void wxPluginLibrary::RegisterModules()
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
403 wxASSERT_MSG( m_linkcount == 1,
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 {
425 wxLogDebug(_T("wxModule::Init() failed for wxPluginLibrary"));
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
442 --m_linkcount; // Flag us for deletion
443 break;
444 }
445 }
446 }
447
448 void wxPluginLibrary::UnregisterModules()
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 // ---------------------------------------------------------------------------
463 // wxPluginLibrary
464 // ---------------------------------------------------------------------------
465
466 wxDLManifest wxPluginManager::ms_manifest(wxKEY_STRING);
467
468 // ------------------------
469 // Static accessors
470 // ------------------------
471
472 wxPluginLibrary *wxPluginManager::LoadLibrary(const wxString &libname, int flags)
473 {
474 wxString realname(libname);
475
476 if( !(flags & wxDL_VERBATIM) )
477 realname += wxDynamicLibrary::GetDllExt();
478
479 wxPluginLibrary *entry = (wxPluginLibrary*) ms_manifest.Get(realname);
480
481 if( entry != 0 )
482 {
483 entry->RefLib();
484 }
485 else
486 {
487 entry = new wxPluginLibrary( libname, flags );
488
489 if( entry->IsLoaded() )
490 {
491 ms_manifest.Put(realname, (wxObject*) entry);
492 }
493 else
494 {
495 wxCHECK_MSG( entry->UnrefLib(), 0,
496 _T("Currently linked library is, ..not loaded??") );
497 entry = 0;
498 }
499 }
500 return entry;
501 }
502
503 bool wxPluginManager::UnloadLibrary(const wxString &libname)
504 {
505 wxPluginLibrary *entry = (wxPluginLibrary*) ms_manifest.Get(libname);
506
507 if( !entry )
508 entry = (wxPluginLibrary*) ms_manifest.Get(libname + wxDynamicLibrary::GetDllExt());
509
510 if( entry )
511 return entry->UnrefLib();
512
513 wxLogDebug(_T("Attempt to Unlink library '%s' (which is not linked)."), libname.c_str());
514 return FALSE;
515 }
516
517 #if WXWIN_COMPATIBILITY_2_2
518 wxPluginLibrary *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
527 return 0;
528 }
529 #endif
530
531 // ------------------------
532 // Class implementation
533 // ------------------------
534
535 bool wxPluginManager::Load(const wxString &libname, int flags)
536 {
537 m_entry = wxPluginManager::LoadLibrary(libname, flags);
538 return IsLoaded();
539 }
540
541 void wxPluginManager::Unload()
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())
549 if( (wxPluginLibrary*)node->GetData() == m_entry )
550 break;
551
552 if( m_entry && m_entry->UnrefLib() )
553 {
554 delete node;
555 m_entry = 0;
556 }
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
566 extern "C" {
567 #import <mach-o/dyld.h>
568 };
569
570 enum dyldErrorSource
571 {
572 OFImage,
573 };
574
575 static char dl_last_error[1024];
576
577 static void TranslateError(const char *path, enum dyldErrorSource type, int number)
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
609 #endif // __DARWIN__
610
611
612 // ---------------------------------------------------------------------------
613 // wxDllLoader (all these methods are static)
614 // ---------------------------------------------------------------------------
615
616 #if WXWIN_COMPATIBILITY_2_2
617
618 wxDllType wxDllLoader::LoadLibrary(const wxString &name)
619 {
620 wxPluginLibrary *p = wxPluginManager::LoadLibrary(name, wxDL_DEFAULT | wxDL_VERBATIM);
621 return p->GetLibHandle();
622 }
623
624 void wxDllLoader::UnloadLibrary(wxDllType handle)
625 {
626 wxPluginLibrary *p = wxPluginManager::GetObjectFromHandle(handle);
627 p->UnrefLib();
628 }
629
630 void *wxDllLoader::GetSymbol(wxDllType dllHandle, const wxString &name, bool *success)
631 {
632 wxPluginLibrary *p = wxPluginManager::GetObjectFromHandle(dllHandle);
633 return p->GetSymbol(name, success);
634 }
635
636 #endif // WXWIN_COMPATIBILITY_2_2
637
638 #endif // wxUSE_DYNAMIC_LOADER
639
640 // vi:sts=4:sw=4:et