1 /////////////////////////////////////////////////////////////////////////////
3 // Purpose: Dynamic library management
4 // Author: Guilhem Lavaux
8 // Copyright: (c) Guilhem Lavaux
9 // Licence: wxWindows license
10 /////////////////////////////////////////////////////////////////////////////
12 // ============================================================================
14 // ============================================================================
16 // ----------------------------------------------------------------------------
18 // ----------------------------------------------------------------------------
21 # pragma implementation "dynlib.h"
24 #include "wx/wxprec.h"
30 #if wxUSE_DYNLIB_CLASS
32 #if defined(__WINDOWS__)
33 #include "wx/msw/private.h"
36 #include "wx/dynlib.h"
37 #include "wx/filefn.h"
41 // ----------------------------------------------------------------------------
42 // conditional compilation
43 // ----------------------------------------------------------------------------
45 #if defined(__WXPM__) || defined(__EMX__)
48 # define wxDllOpen(error, lib, handle) DosLoadModule(error, sizeof(error), lib, &handle)
49 # define wxDllGetSymbol(handle, modaddr) DosQueryProcAddr(handle, 1L, NULL, (PFN*)modaddr)
50 # define wxDllClose(handle) DosFreeModule(handle)
51 #elif defined(HAVE_DLOPEN)
52 // note about dlopen() flags: we use RTLD_NOW to have more Windows-like
53 // behaviour (Win won't let you load a library with missing symbols) and
54 // RTLD_GLOBAL because it is needed sometimes and probably doesn't hurt
55 // otherwise. On True64-Unix RTLD_GLOBAL is not allowed and on VMS the
56 // second argument on dlopen is ignored.
58 # define wxDllOpen(lib) dlopen(lib.fn_str(), 0 )
59 #elif defined( __osf__ )
60 # define wxDllOpen(lib) dlopen(lib.fn_str(), RTLD_LAZY )
62 # define wxDllOpen(lib) dlopen(lib.fn_str(), RTLD_LAZY | RTLD_GLOBAL)
64 #define wxDllGetSymbol(handle, name) dlsym(handle, name)
65 # define wxDllClose dlclose
66 #elif defined(HAVE_SHL_LOAD)
67 # define wxDllOpen(lib) shl_load(lib.fn_str(), BIND_DEFERRED, 0)
68 # define wxDllClose shl_unload
70 static inline void *wxDllGetSymbol(shl_t handle
, const wxString
& name
)
73 if ( shl_findsym(&handle
, name
.mb_str(), TYPE_UNDEFINED
, &sym
) == 0 )
79 #elif defined(__DARWIN__)
81 * The dlopen port is a port from dl_next.xs by Anno Siegel.
82 * dl_next.xs is itself a port from dl_dlopen.xs by Paul Marquess.
83 * The method used here is just to supply the sun style dlopen etc.
84 * functions in terms of Darwin NS*.
86 void *dlopen(const char *path
, int mode
/* mode is ignored */);
87 void *dlsym(void *handle
, const char *symbol
);
88 int dlclose(void *handle
);
89 const char *dlerror(void);
91 # define wxDllOpen(lib) dlopen(lib.fn_str(), 0)
92 # define wxDllGetSymbol(handle, name) dlsym(handle, name)
93 # define wxDllClose dlclose
94 #elif defined(__WINDOWS__)
95 // using LoadLibraryEx under Win32 to avoid name clash with LoadLibrary
98 # define wxDllOpen(lib) ::LoadLibraryExW(lib, 0, 0)
100 # define wxDllOpen(lib) ::LoadLibraryExA(lib, 0, 0)
103 # define wxDllOpen(lib) ::LoadLibrary(lib)
105 # define wxDllGetSymbol(handle, name) ::GetProcAddress(handle, name)
106 # define wxDllClose ::FreeLibrary
107 #elif defined(__WXMAC__)
108 # define wxDllClose(handle) CloseConnection(&handle)
110 # error "Don't know how to load shared libraries on this platform."
113 // ---------------------------------------------------------------------------
115 // ---------------------------------------------------------------------------
117 wxLibraries wxTheLibraries
;
119 // ============================================================================
121 // ============================================================================
123 // construct the full name from the base shared object name: adds a .dll
124 // suffix under Windows or .so under Unix
125 static wxString
ConstructLibraryName(const wxString
& basename
)
128 fullname
<< basename
<< wxDllLoader::GetDllExt();
133 // ---------------------------------------------------------------------------
134 // wxLibrary (one instance per dynamic library)
135 // ---------------------------------------------------------------------------
137 wxLibrary::wxLibrary(wxDllType handle
)
139 typedef wxClassInfo
*(*t_get_first
)(void);
140 t_get_first get_first
;
144 // Some system may use a local heap for library.
145 get_first
= (t_get_first
)GetSymbol("wxGetClassFirst");
146 // It is a wxWindows DLL.
148 PrepareClasses(get_first());
151 wxLibrary::~wxLibrary()
155 wxDllClose(m_handle
);
159 wxObject
*wxLibrary::CreateObject(const wxString
& name
)
161 wxClassInfo
*info
= (wxClassInfo
*)classTable
.Get(name
);
166 return info
->CreateObject();
169 void wxLibrary::PrepareClasses(wxClassInfo
*first
)
171 // Index all class infos by their class name
172 wxClassInfo
*info
= first
;
175 if (info
->m_className
)
176 classTable
.Put(info
->m_className
, (wxObject
*)info
);
180 // Set base pointers for each wxClassInfo
184 if (info
->GetBaseClassName1())
185 info
->m_baseInfo1
= (wxClassInfo
*)classTable
.Get(info
->GetBaseClassName1());
186 if (info
->GetBaseClassName2())
187 info
->m_baseInfo2
= (wxClassInfo
*)classTable
.Get(info
->GetBaseClassName2());
192 void *wxLibrary::GetSymbol(const wxString
& symbname
)
194 return wxDllLoader::GetSymbol(m_handle
, symbname
);
197 // ---------------------------------------------------------------------------
199 // ---------------------------------------------------------------------------
202 #if defined(__WINDOWS__) || defined(__WXPM__) || defined(__EMX__)
203 const wxString
wxDllLoader::ms_dllext( _T(".dll") );
204 #elif defined(__UNIX__)
205 #if defined(__HPUX__)
206 const wxString
wxDllLoader::ms_dllext( _T(".sl") );
208 const wxString
wxDllLoader::ms_dllext( _T(".so") );
213 wxDllType
wxDllLoader::GetProgramHandle()
215 #if defined( HAVE_DLOPEN ) && !defined(__EMX__)
216 // optain handle for main program
217 return dlopen(NULL
, RTLD_NOW
/*RTLD_LAZY*/);
218 #elif defined (HAVE_SHL_LOAD)
219 // shl_findsymbol with NULL handle looks up in main program
222 wxFAIL_MSG( wxT("This method is not implemented under Windows or OS/2"));
228 wxDllType
wxDllLoader::LoadLibrary(const wxString
& libname
, bool *success
)
233 #if defined(__WXMAC__) && !defined(__UNIX__)
238 wxMacFilename2FSSpec( libname
, &myFSSpec
);
240 if( GetDiskFragment( &myFSSpec
,
247 myErrName
) != noErr
)
250 wxLogSysError( _("Failed to load shared library '%s' Error '%s'"),
257 #elif defined(__WXPM__) || defined(__EMX__)
258 char zError
[256] = "";
259 wxDllOpen(zError
, libname
, handle
);
262 handle
= wxDllOpen(libname
);
268 wxString
msg(_("Failed to load shared library '%s'"));
271 wxChar
*err
= dlerror();
275 wxLogError( msg
, err
);
279 wxLogSysError( msg
, libname
.c_str() );
291 void wxDllLoader::UnloadLibrary(wxDllType handle
)
297 void *wxDllLoader::GetSymbol(wxDllType dllHandle
, const wxString
&name
, bool *success
)
302 #if defined(__WXMAC__) && !defined(__UNIX__)
304 CFragSymbolClass symClass
;
308 c2pstrcpy( (StringPtr
) symName
, name
);
310 strcpy( (char *) symName
, name
);
311 c2pstr( (char *) symName
);
313 if( FindSymbol( dllHandle
, symName
, &symAddress
, &symClass
) == noErr
)
314 symbol
= (void *)symAddress
;
316 #elif defined(__WXPM__) || defined(__EMX__)
317 wxDllGetSymbol(dllHandle
, symbol
);
320 // mb_str() is necessary in Unicode build
321 symbol
= wxDllGetSymbol(dllHandle
, name
.mb_str());
327 wxString
msg(_("wxDllLoader failed to GetSymbol '%s'"));
330 wxChar
*err
= dlerror();
334 wxLogError( msg
, err
);
338 wxLogSysError(_("Couldn't find symbol '%s' in a dynamic library"),
349 // ---------------------------------------------------------------------------
350 // wxLibraries (only one instance should normally exist)
351 // ---------------------------------------------------------------------------
353 wxLibraries::wxLibraries():m_loaded(wxKEY_STRING
)
357 wxLibraries::~wxLibraries()
359 wxNode
*node
= m_loaded
.First();
362 wxLibrary
*lib
= (wxLibrary
*)node
->Data();
369 wxLibrary
*wxLibraries::LoadLibrary(const wxString
& name
)
372 wxClassInfo
*old_sm_first
;
373 wxNode
*node
= m_loaded
.Find(name
.GetData());
376 return ((wxLibrary
*)node
->Data());
378 // If DLL shares data, this is necessary.
379 old_sm_first
= wxClassInfo::sm_first
;
380 wxClassInfo::sm_first
= NULL
;
382 wxString libname
= ConstructLibraryName(name
);
384 bool success
= FALSE
;
385 wxDllType handle
= wxDllLoader::LoadLibrary(libname
, &success
);
388 lib
= new wxLibrary(handle
);
389 wxClassInfo::sm_first
= old_sm_first
;
391 m_loaded
.Append(name
.GetData(), lib
);
398 wxObject
*wxLibraries::CreateObject(const wxString
& path
)
400 wxNode
*node
= m_loaded
.First();
404 obj
= ((wxLibrary
*)node
->Data())->CreateObject(path
);
414 // ---------------------------------------------------------------------------
415 // For Darwin/Mac OS X
416 // supply the sun style dlopen functions in terms of Darwin NS*
417 // ---------------------------------------------------------------------------
420 #import <mach-o/dyld.h>
428 static char dl_last_error
[1024];
431 void TranslateError(const char *path
, enum dyldErrorSource type
, int number
)
434 static char *OFIErrorStrings
[] =
436 "%s(%d): Object Image Load Failure\n",
437 "%s(%d): Object Image Load Success\n",
438 "%s(%d): Not an recognisable object file\n",
439 "%s(%d): No valid architecture\n",
440 "%s(%d): Object image has an invalid format\n",
441 "%s(%d): Invalid access (permissions?)\n",
442 "%s(%d): Unknown error code from NSCreateObjectFileImageFromFile\n",
444 #define NUM_OFI_ERRORS (sizeof(OFIErrorStrings) / sizeof(OFIErrorStrings[0]))
450 if (index
> NUM_OFI_ERRORS
- 1) {
451 index
= NUM_OFI_ERRORS
- 1;
453 sprintf(dl_last_error
, OFIErrorStrings
[index
], path
, number
);
457 sprintf(dl_last_error
, "%s(%d): Totally unknown error type %d\n",
463 const char *dlerror()
465 return dl_last_error
;
468 void *dlopen(const char *path
, int mode
/* mode is ignored */)
471 NSObjectFileImage ofile
;
472 NSModule handle
= NULL
;
474 dyld_result
= NSCreateObjectFileImageFromFile(path
, &ofile
);
475 if (dyld_result
!= NSObjectFileImageSuccess
)
477 TranslateError(path
, OFImage
, dyld_result
);
481 // NSLinkModule will cause the run to abort on any link error's
482 // not very friendly but the error recovery functionality is limited.
483 handle
= NSLinkModule(ofile
, path
, TRUE
);
489 int dlclose(void *handle
) /* stub only */
494 void *dlsym(void *handle
, const char *symbol
)
498 if (NSIsSymbolNameDefined(symbol
)) {
499 addr
= NSAddressOfSymbol(NSLookupAndBindSymbol(symbol
));
509 #endif // wxUSE_DYNLIB_CLASS