]> git.saurik.com Git - wxWidgets.git/blame - src/common/dynload.cpp
added workaround for Unicode functions not working under MSLU
[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__
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
0b9ab0bd
RL
40
41// ============================================================================
42// implementation
43// ============================================================================
44
45// ---------------------------------------------------------------------------
4f89dbc4 46// wxDynamicLibrary
0b9ab0bd
RL
47// ---------------------------------------------------------------------------
48
4f89dbc4
RL
49//FIXME: This class isn't really common at all, it should be moved into
50// platform dependent files.
0b9ab0bd
RL
51
52#if defined(__WINDOWS__) || defined(__WXPM__) || defined(__EMX__)
4f89dbc4 53const wxString wxDynamicLibrary::ms_dllext( _T(".dll") );
0b9ab0bd
RL
54#elif defined(__UNIX__)
55#if defined(__HPUX__)
4f89dbc4 56const wxString wxDynamicLibrary::ms_dllext( _T(".sl") );
0b9ab0bd 57#else
4f89dbc4 58const wxString wxDynamicLibrary::ms_dllext( _T(".so") );
0b9ab0bd
RL
59#endif
60#endif
61
4f89dbc4 62wxDllType wxDynamicLibrary::GetProgramHandle()
0b9ab0bd
RL
63{
64#if defined( HAVE_DLOPEN ) && !defined(__EMX__)
4f89dbc4 65 return dlopen(0, RTLD_LAZY);
0b9ab0bd 66#elif defined (HAVE_SHL_LOAD)
4f89dbc4 67 return PROG_HANDLE;
0b9ab0bd
RL
68#else
69 wxFAIL_MSG( wxT("This method is not implemented under Windows or OS/2"));
70 return 0;
71#endif
72}
73
4f89dbc4 74bool wxDynamicLibrary::Load(wxString libname, wxDLFlags flags)
0b9ab0bd 75{
4f89dbc4
RL
76 wxASSERT_MSG(m_handle == 0, _T("Library already loaded."));
77
78 if( !(flags & wxDL_VERBATIM) )
79 libname += GetDllExt();
0b9ab0bd
RL
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,
4f89dbc4 93 &m_handle,
0b9ab0bd
RL
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 );
4f89dbc4 101 m_handle = 0;
0b9ab0bd
RL
102 }
103
104#elif defined(__WXPM__) || defined(__EMX__)
4f89dbc4
RL
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
0b9ab0bd 169#else
4f89dbc4 170#error "runtime shared lib support not implemented"
0b9ab0bd 171#endif
4f89dbc4
RL
172
173 if ( m_handle == 0 )
0b9ab0bd
RL
174 {
175 wxString msg(_("Failed to load shared library '%s'"));
176#ifdef HAVE_DLERROR
a1706592 177 const wxChar *err = dlerror();
0b9ab0bd
RL
178 if( err )
179 wxLogError( msg, err );
180#else
181 wxLogSysError( msg, libname.c_str() );
182#endif
183 }
4f89dbc4
RL
184
185 return IsLoaded();
0b9ab0bd
RL
186}
187
4f89dbc4 188void wxDynamicLibrary::Unload()
0b9ab0bd 189{
4f89dbc4
RL
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 }
0b9ab0bd
RL
207}
208
4f89dbc4 209void *wxDynamicLibrary::GetSymbol(const wxString &name, bool *success) const
0b9ab0bd 210{
4f89dbc4
RL
211 wxCHECK_MSG( IsLoaded(), NULL,
212 _T("Can't load symbol from unloaded library") );
213
0b9ab0bd
RL
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
4f89dbc4
RL
224 strcpy( (char *)symName, name );
225 c2pstr( (char *)symName );
0b9ab0bd
RL
226#endif
227 if( FindSymbol( dllHandle, symName, &symAddress, &symClass ) == noErr )
228 symbol = (void *)symAddress;
229
230#elif defined(__WXPM__) || defined(__EMX__)
4f89dbc4
RL
231 DosQueryProcAddr( m_handle, 1L, name.c_str(), (PFN*)symbol );
232
233#elif defined(HAVE_DLOPEN)
234 symbol = dlsym( m_handle, name.c_str() );
0b9ab0bd 235
4f89dbc4
RL
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.c_str() );
246
247#else
248#error "runtime shared lib support not implemented"
0b9ab0bd
RL
249#endif
250
251 if ( !symbol )
252 {
4f89dbc4 253 wxString msg(_("wxDynamicLibrary failed to GetSymbol '%s'"));
0b9ab0bd 254#ifdef HAVE_DLERROR
a1706592 255 const wxChar *err = dlerror();
0b9ab0bd
RL
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// ---------------------------------------------------------------------------
4f89dbc4 275// wxPluginLibrary
0b9ab0bd
RL
276// ---------------------------------------------------------------------------
277
278
4f89dbc4 279wxDLImports wxPluginLibrary::ms_classes(wxKEY_STRING);
0b9ab0bd 280
4f89dbc4
RL
281wxPluginLibrary::wxPluginLibrary(const wxString &libname, wxDLFlags flags)
282 : m_linkcount(1)
7c1e2b44 283 , m_objcount(0)
0b9ab0bd 284{
4f89dbc4
RL
285 m_before = wxClassInfo::sm_first;
286 Load( libname, flags );
287 m_after = wxClassInfo::sm_first;
288
0b9ab0bd
RL
289 if( m_handle != 0 )
290 {
291 UpdateClassInfo();
292 RegisterModules();
293 }
294 else
7c1e2b44 295 --m_linkcount; // Flag us for deletion
0b9ab0bd
RL
296}
297
4f89dbc4 298wxPluginLibrary::~wxPluginLibrary()
0b9ab0bd 299{
01610529
RL
300 if( m_handle != 0 )
301 {
302 UnregisterModules();
303 RestoreClassInfo();
01610529 304 }
0b9ab0bd
RL
305}
306
4f89dbc4 307bool wxPluginLibrary::UnrefLib()
7c1e2b44
RL
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}
0b9ab0bd
RL
317
318// ------------------------
319// Private methods
320// ------------------------
321
4f89dbc4 322void wxPluginLibrary::UpdateClassInfo()
0b9ab0bd
RL
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
4f89dbc4 360void wxPluginLibrary::RestoreClassInfo()
0b9ab0bd
RL
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
4f89dbc4 377 wxASSERT_MSG( info, _T("ClassInfo from wxPluginLibrary not found on purge"))
0b9ab0bd
RL
378
379 info->m_next = m_before;
380 }
381}
382
4f89dbc4 383void wxPluginLibrary::RegisterModules()
0b9ab0bd
RL
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
7c1e2b44 393 wxASSERT_MSG( m_linkcount == 1,
0b9ab0bd
RL
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 {
4f89dbc4 415 wxLogDebug(_T("wxModule::Init() failed for wxPluginLibrary"));
0b9ab0bd
RL
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
7c1e2b44 432 --m_linkcount; // Flag us for deletion
0b9ab0bd
RL
433 break;
434 }
435 }
436}
437
4f89dbc4 438void wxPluginLibrary::UnregisterModules()
0b9ab0bd
RL
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// ---------------------------------------------------------------------------
4f89dbc4 453// wxPluginLibrary
0b9ab0bd
RL
454// ---------------------------------------------------------------------------
455
4f89dbc4 456wxDLManifest wxPluginManager::ms_manifest(wxKEY_STRING);
0b9ab0bd
RL
457
458// ------------------------
459// Static accessors
460// ------------------------
461
4f89dbc4 462wxPluginLibrary *wxPluginManager::LoadLibrary(const wxString &libname, wxDLFlags flags)
0b9ab0bd 463{
4f89dbc4 464 wxString realname(libname);
0b9ab0bd 465
4f89dbc4
RL
466 if( !(flags & wxDL_VERBATIM) )
467 realname += wxDynamicLibrary::GetDllExt();
468
469 wxPluginLibrary *entry = (wxPluginLibrary*) ms_manifest.Get(realname);
470
471 if( entry != 0 )
0b9ab0bd 472 {
7c1e2b44 473 entry->RefLib();
0b9ab0bd
RL
474 }
475 else
476 {
4f89dbc4 477 entry = new wxPluginLibrary( libname, flags );
0b9ab0bd
RL
478
479 if( entry->IsLoaded() )
480 {
4f89dbc4 481 ms_manifest.Put(realname, (wxObject*) entry);
0b9ab0bd
RL
482 }
483 else
484 {
01610529 485 wxCHECK_MSG( entry->UnrefLib(), 0,
0b9ab0bd
RL
486 _T("Currently linked library is, ..not loaded??") );
487 entry = 0;
488 }
489 }
490 return entry;
491}
492
4f89dbc4 493bool wxPluginManager::UnloadLibrary(const wxString &libname)
0b9ab0bd 494{
4f89dbc4
RL
495 wxPluginLibrary *entry = (wxPluginLibrary*) ms_manifest.Get(libname);
496
497 if( !entry )
498 entry = (wxPluginLibrary*) ms_manifest.Get(libname + wxDynamicLibrary::GetDllExt());
0b9ab0bd
RL
499
500 if( entry )
7c1e2b44 501 return entry->UnrefLib();
0b9ab0bd
RL
502
503 wxLogDebug(_T("Attempt to Unlink library '%s' (which is not linked)."), libname.c_str());
4f89dbc4
RL
504 return FALSE;
505}
506
507#if WXWIN_COMPATIBILITY_2_2
508wxPluginLibrary *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
0b9ab0bd
RL
517 return 0;
518}
4f89dbc4 519#endif
0b9ab0bd
RL
520
521// ------------------------
522// Class implementation
523// ------------------------
524
4f89dbc4 525bool wxPluginManager::Load(const wxString &libname, wxDLFlags flags)
0b9ab0bd 526{
4f89dbc4
RL
527 m_entry = wxPluginManager::LoadLibrary(libname, flags);
528 return IsLoaded();
0b9ab0bd
RL
529}
530
4f89dbc4 531void wxPluginManager::Unload()
0b9ab0bd
RL
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())
4f89dbc4 539 if( (wxPluginLibrary*)node->GetData() == m_entry )
0b9ab0bd
RL
540 break;
541
7c1e2b44 542 if( m_entry && m_entry->UnrefLib() )
4f89dbc4 543 {
0b9ab0bd 544 delete node;
4f89dbc4
RL
545 m_entry = 0;
546 }
0b9ab0bd
RL
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
556extern "C" {
557#import <mach-o/dyld.h>
558};
559
560enum dyldErrorSource
561{
562 OFImage,
563};
564
565static char dl_last_error[1024];
566
4f89dbc4 567static void TranslateError(const char *path, enum dyldErrorSource type, int number)
0b9ab0bd
RL
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
4f89dbc4 599#endif // __DARWIN__
0b9ab0bd 600
0b9ab0bd 601
4f89dbc4
RL
602// ---------------------------------------------------------------------------
603// wxDllLoader (all these methods are static)
604// ---------------------------------------------------------------------------
605
606#if WXWIN_COMPATIBILITY_2_2
607
608wxDllType wxDllLoader::LoadLibrary(const wxString &name)
609{
610 wxPluginLibrary *p = wxPluginManager::LoadLibrary(name, wxDL_DEFAULT | wxDL_VERBATIM);
611 return p->GetLibHandle();
0b9ab0bd
RL
612}
613
4f89dbc4 614void wxDllLoader::UnloadLibrary(wxDllType handle)
0b9ab0bd 615{
4f89dbc4
RL
616 wxPluginLibrary *p = wxPluginManager::GetObjectFromHandle(handle);
617 p->UnrefLib();
0b9ab0bd
RL
618}
619
4f89dbc4 620void *wxDllLoader::GetSymbol(wxDllType dllHandle, const wxString &name, bool *success)
0b9ab0bd 621{
4f89dbc4
RL
622 wxPluginLibrary *p = wxPluginManager::GetObjectFromHandle(dllHandle);
623 return p->GetSymbol(name, success);
0b9ab0bd
RL
624}
625
4f89dbc4
RL
626#endif // WXWIN_COMPATIBILITY_2_2
627
0b9ab0bd
RL
628#endif // wxUSE_DYNAMIC_LOADER
629
630// vi:sts=4:sw=4:et