1 /////////////////////////////////////////////////////////////////////////////
3 // Purpose: Dynamic library management
4 // Author: Guilhem Lavaux
8 // Copyright: (c) Guilhem Lavaux
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
12 // ============================================================================
14 // ============================================================================
16 // ----------------------------------------------------------------------------
18 // ----------------------------------------------------------------------------
21 # pragma implementation "dynlib.h"
24 #include "wx/wxprec.h"
30 #if wxUSE_DYNLIB_CLASS && !wxUSE_DYNAMIC_LOADER
32 #if defined(__WINDOWS__)
33 #include "wx/msw/private.h"
36 #include "wx/dynlib.h"
37 #include "wx/filefn.h"
41 #if defined(__WXMAC__)
42 #include "wx/mac/private.h"
45 // ----------------------------------------------------------------------------
46 // conditional compilation
47 // ----------------------------------------------------------------------------
49 #if defined(__WXPM__) || defined(__EMX__)
52 # define wxDllOpen(error, lib, handle) DosLoadModule(error, sizeof(error), lib, &handle)
53 # define wxDllGetSymbol(handle, modaddr) DosQueryProcAddr(handle, 1L, NULL, (PFN*)modaddr)
54 # define wxDllClose(handle) DosFreeModule(handle)
55 #elif defined(HAVE_DLOPEN)
56 // note about dlopen() flags: we use RTLD_NOW to have more Windows-like
57 // behaviour (Win won't let you load a library with missing symbols) and
58 // RTLD_GLOBAL because it is needed sometimes and probably doesn't hurt
59 // otherwise. On True64-Unix RTLD_GLOBAL is not allowed and on VMS the
60 // second argument on dlopen is ignored.
62 # define wxDllOpen(lib) dlopen(lib.fn_str(), 0 )
63 #elif defined( __osf__ )
64 # define wxDllOpen(lib) dlopen(lib.fn_str(), RTLD_LAZY )
66 # define wxDllOpen(lib) dlopen(lib.fn_str(), RTLD_LAZY | RTLD_GLOBAL)
68 #define wxDllGetSymbol(handle, name) dlsym(handle, name)
69 # define wxDllClose dlclose
70 #elif defined(HAVE_SHL_LOAD)
71 # define wxDllOpen(lib) shl_load(lib.fn_str(), BIND_DEFERRED, 0)
72 # define wxDllClose shl_unload
74 static inline void *wxDllGetSymbol(shl_t handle
, const wxString
& name
)
77 if ( shl_findsym(&handle
, name
.mb_str(), TYPE_UNDEFINED
, &sym
) == 0 )
83 #elif defined(__DARWIN__)
85 * The dlopen port is a port from dl_next.xs by Anno Siegel.
86 * dl_next.xs is itself a port from dl_dlopen.xs by Paul Marquess.
87 * The method used here is just to supply the sun style dlopen etc.
88 * functions in terms of Darwin NS*.
90 void *dlopen(const char *path
, int mode
/* mode is ignored */);
91 void *dlsym(void *handle
, const char *symbol
);
92 int dlclose(void *handle
);
93 const char *dlerror(void);
95 # define wxDllOpen(lib) dlopen(lib.fn_str(), 0)
96 # define wxDllGetSymbol(handle, name) dlsym(handle, name)
97 # define wxDllClose dlclose
98 #elif defined(__WINDOWS__)
99 // using LoadLibraryEx under Win32 to avoid name clash with LoadLibrary
103 # define wxDllOpen(lib) ::LoadLibrary(lib)
105 # define wxDllOpen(lib) ::LoadLibraryExW(lib, 0, 0)
108 # define wxDllOpen(lib) ::LoadLibraryExA(lib, 0, 0)
111 # define wxDllOpen(lib) ::LoadLibrary(lib)
113 # define wxDllGetSymbol(handle, name) ::GetProcAddress(handle, name)
114 # define wxDllClose ::FreeLibrary
115 #elif defined(__WXMAC__)
116 # define wxDllClose(handle) CloseConnection(&((CFragConnectionID)handle))
118 # error "Don't know how to load shared libraries on this platform."
121 // ---------------------------------------------------------------------------
123 // ---------------------------------------------------------------------------
125 wxLibraries wxTheLibraries
;
127 // ============================================================================
129 // ============================================================================
131 // construct the full name from the base shared object name: adds a .dll
132 // suffix under Windows or .so under Unix
133 static wxString
ConstructLibraryName(const wxString
& basename
)
136 fullname
<< basename
<< wxDllLoader::GetDllExt();
141 // ---------------------------------------------------------------------------
142 // wxLibrary (one instance per dynamic library)
143 // ---------------------------------------------------------------------------
145 wxLibrary::wxLibrary(wxDllType handle
)
147 typedef wxClassInfo
*(*t_get_first
)(void);
148 t_get_first get_first
;
152 // Some system may use a local heap for library.
153 get_first
= (t_get_first
)GetSymbol(_T("wxGetClassFirst"));
154 // It is a wxWindows DLL.
156 PrepareClasses(get_first());
159 wxLibrary::~wxLibrary()
163 wxDllClose(m_handle
);
167 wxObject
*wxLibrary::CreateObject(const wxString
& name
)
169 wxClassInfo
*info
= (wxClassInfo
*)classTable
.Get(name
);
174 return info
->CreateObject();
177 void wxLibrary::PrepareClasses(wxClassInfo
*first
)
179 // Index all class infos by their class name
180 wxClassInfo
*info
= first
;
183 if (info
->m_className
)
184 classTable
.Put(info
->m_className
, (wxObject
*)info
);
188 // Set base pointers for each wxClassInfo
192 if (info
->GetBaseClassName1())
193 info
->m_baseInfo1
= (wxClassInfo
*)classTable
.Get(info
->GetBaseClassName1());
194 if (info
->GetBaseClassName2())
195 info
->m_baseInfo2
= (wxClassInfo
*)classTable
.Get(info
->GetBaseClassName2());
200 void *wxLibrary::GetSymbol(const wxString
& symbname
)
202 return wxDllLoader::GetSymbol(m_handle
, symbname
);
205 // ---------------------------------------------------------------------------
207 // ---------------------------------------------------------------------------
210 #if defined(__WINDOWS__) || defined(__WXPM__) || defined(__EMX__)
211 const wxString
wxDllLoader::ms_dllext( _T(".dll") );
212 #elif defined(__UNIX__)
213 #if defined(__HPUX__)
214 const wxString
wxDllLoader::ms_dllext( _T(".sl") );
216 const wxString
wxDllLoader::ms_dllext( _T(".so") );
218 #elif defined(__WXMAC__)
219 const wxString
wxDllLoader::ms_dllext( _T("") );
223 wxDllType
wxDllLoader::GetProgramHandle()
225 #if defined( HAVE_DLOPEN ) && !defined(__EMX__)
226 // optain handle for main program
227 return dlopen(NULL
, RTLD_NOW
/*RTLD_LAZY*/);
228 #elif defined (HAVE_SHL_LOAD)
229 // shl_findsymbol with NULL handle looks up in main program
232 wxFAIL_MSG( wxT("This method is not implemented under Windows or OS/2"));
238 wxDllType
wxDllLoader::LoadLibrary(const wxString
& libname
, bool *success
)
243 #if defined(__WXMAC__) && !defined(__UNIX__)
248 wxMacFilename2FSSpec( libname
, &myFSSpec
);
250 if( GetDiskFragment( &myFSSpec
,
255 &((CFragConnectionID
)handle
),
257 myErrName
) != noErr
)
260 wxLogSysError( _("Failed to load shared library '%s' Error '%s'"),
267 #elif defined(__WXPM__) || defined(__EMX__)
268 char zError
[256] = "";
269 wxDllOpen(zError
, libname
, handle
);
272 handle
= wxDllOpen(libname
);
278 wxString
msg(_("Failed to load shared library '%s'"));
281 const wxChar
*err
= dlerror();
285 wxLogError( msg
, err
);
289 wxLogSysError( msg
, libname
.c_str() );
301 void wxDllLoader::UnloadLibrary(wxDllType handle
)
307 void *wxDllLoader::GetSymbol(wxDllType dllHandle
, const wxString
&name
, bool *success
)
312 #if defined(__WXMAC__) && !defined(__UNIX__)
314 CFragSymbolClass symClass
;
317 wxMacStringToPascal( name
.c_str() , symName
) ;
319 if( FindSymbol( ((CFragConnectionID
)dllHandle
), symName
, &symAddress
, &symClass
) == noErr
)
320 symbol
= (void *)symAddress
;
322 #elif defined(__WXPM__) || defined(__EMX__)
323 wxDllGetSymbol(dllHandle
, symbol
);
325 #else // Windows or Unix
327 // mb_str() is necessary in Unicode build
329 // "void *" cast is needed by gcc 3.1 + w32api 1.4, don't ask me why
331 symbol
= (void *) wxDllGetSymbol(dllHandle
, name
.c_str());
333 symbol
= (void *) wxDllGetSymbol(dllHandle
, name
.mb_str());
341 const wxChar
*err
= dlerror();
344 wxLogError(wxT("%s"), err
);
348 wxLogSysError(_("Couldn't find symbol '%s' in a dynamic library"),
359 // ---------------------------------------------------------------------------
360 // wxLibraries (only one instance should normally exist)
361 // ---------------------------------------------------------------------------
363 wxLibraries::wxLibraries():m_loaded(wxKEY_STRING
)
367 wxLibraries::~wxLibraries()
369 wxNode
*node
= m_loaded
.First();
372 wxLibrary
*lib
= (wxLibrary
*)node
->Data();
379 wxLibrary
*wxLibraries::LoadLibrary(const wxString
& name
)
382 wxClassInfo
*old_sm_first
;
383 wxNode
*node
= m_loaded
.Find(name
.GetData());
386 return ((wxLibrary
*)node
->Data());
388 // If DLL shares data, this is necessary.
389 old_sm_first
= wxClassInfo::sm_first
;
390 wxClassInfo::sm_first
= NULL
;
392 wxString libname
= ConstructLibraryName(name
);
394 bool success
= FALSE
;
395 wxDllType handle
= wxDllLoader::LoadLibrary(libname
, &success
);
398 lib
= new wxLibrary(handle
);
399 wxClassInfo::sm_first
= old_sm_first
;
401 m_loaded
.Append(name
.GetData(), lib
);
408 wxObject
*wxLibraries::CreateObject(const wxString
& path
)
410 wxNode
*node
= m_loaded
.First();
414 obj
= ((wxLibrary
*)node
->Data())->CreateObject(path
);
423 #endif // wxUSE_DYNLIB_CLASS && !wxUSE_DYNAMIC_LOADER
425 #if defined(__DARWIN__) && (wxUSE_DYNLIB_CLASS || wxUSE_DYNAMIC_LOADER)
426 // ---------------------------------------------------------------------------
427 // For Darwin/Mac OS X
428 // supply the sun style dlopen functions in terms of Darwin NS*
429 // ---------------------------------------------------------------------------
432 #include <mach-o/dyld.h>
434 static char dl_last_error
[1024];
437 void TranslateError(const char *path
, int number
)
440 static char *OFIErrorStrings
[] =
442 "%s(%d): Object Image Load Failure\n",
443 "%s(%d): Object Image Load Success\n",
444 "%s(%d): Not an recognisable object file\n",
445 "%s(%d): No valid architecture\n",
446 "%s(%d): Object image has an invalid format\n",
447 "%s(%d): Invalid access (permissions?)\n",
448 "%s(%d): Unknown error code from NSCreateObjectFileImageFromFile\n",
450 #define NUM_OFI_ERRORS (sizeof(OFIErrorStrings) / sizeof(OFIErrorStrings[0]))
453 if (index
> NUM_OFI_ERRORS
- 1) {
454 index
= NUM_OFI_ERRORS
- 1;
456 sprintf(dl_last_error
, OFIErrorStrings
[index
], path
, number
);
459 const char *dlerror()
461 return dl_last_error
;
464 void *dlopen(const char *path
, int WXUNUSED(mode
) /* mode is ignored */)
467 NSObjectFileImage ofile
;
468 NSModule handle
= NULL
;
470 dyld_result
= NSCreateObjectFileImageFromFile(path
, &ofile
);
471 if (dyld_result
!= NSObjectFileImageSuccess
)
473 TranslateError(path
, dyld_result
);
477 // NSLinkModule will cause the run to abort on any link error's
478 // not very friendly but the error recovery functionality is limited.
479 handle
= NSLinkModule(ofile
, path
, NSLINKMODULE_OPTION_BINDNOW
);
485 int dlclose(void *handle
)
487 NSUnLinkModule( handle
, NSUNLINKMODULE_OPTION_NONE
);
491 void *dlsym(void *handle
, const char *symbol
)
495 NSSymbol nsSymbol
= NSLookupSymbolInModule( handle
, symbol
) ;
499 addr
= NSAddressOfSymbol(nsSymbol
);
508 #endif // defined(__DARWIN__) && (wxUSE_DYNLIB_CLASS || wxUSE_DYNAMIC_LOADER)