]> git.saurik.com Git - wxWidgets.git/blob - src/common/dynlib.cpp
Committing in .
[wxWidgets.git] / src / common / dynlib.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: dynlib.cpp
3 // Purpose: Dynamic library management
4 // Author: Guilhem Lavaux
5 // Modified by:
6 // Created: 20/07/98
7 // RCS-ID: $Id$
8 // Copyright: (c) Guilhem Lavaux
9 // Licence: wxWindows license
10 /////////////////////////////////////////////////////////////////////////////
11
12 // ============================================================================
13 // declarations
14 // ============================================================================
15
16 // ----------------------------------------------------------------------------
17 // headers
18 // ----------------------------------------------------------------------------
19
20 #ifdef __GNUG__
21 # pragma implementation "dynlib.h"
22 #endif
23
24 #include "wx/wxprec.h"
25
26 #ifdef __BORLANDC__
27 #pragma hdrstop
28 #endif
29
30 #if wxUSE_DYNLIB_CLASS
31
32 #if defined(__WINDOWS__)
33 #include "wx/msw/private.h"
34 #endif
35
36 #include "wx/dynlib.h"
37 #include "wx/filefn.h"
38 #include "wx/intl.h"
39 #include "wx/log.h"
40 #include "wx/tokenzr.h"
41
42 // ----------------------------------------------------------------------------
43 // conditional compilation
44 // ----------------------------------------------------------------------------
45
46 #if defined(__WXPM__) || defined(__EMX__)
47 # define INCL_DOS
48 # include <os2.h>
49 # define wxDllOpen(error, lib, handle) DosLoadModule(error, sizeof(error), lib, &handle)
50 # define wxDllGetSymbol(handle, modaddr) DosQueryProcAddr(handle, 1L, NULL, (PFN*)modaddr)
51 # define wxDllClose(handle) DosFreeModule(handle)
52 #elif defined(HAVE_DLOPEN)
53 // note about dlopen() flags: we use RTLD_NOW to have more Windows-like
54 // behaviour (Win won't let you load a library with missing symbols) and
55 // RTLD_GLOBAL because it is needed sometimes and probably doesn't hurt
56 // otherwise. On True64-Unix RTLD_GLOBAL is not allowed and on VMS the
57 // second argument on dlopen is ignored.
58 #ifdef __VMS
59 # define wxDllOpen(lib) dlopen(lib.fn_str(), 0 )
60 #elif defined( __osf__ )
61 # define wxDllOpen(lib) dlopen(lib.fn_str(), RTLD_LAZY )
62 #else
63 # define wxDllOpen(lib) dlopen(lib.fn_str(), RTLD_LAZY | RTLD_GLOBAL)
64 #endif
65 #define wxDllGetSymbol(handle, name) dlsym(handle, name)
66 # define wxDllClose dlclose
67 #elif defined(HAVE_SHL_LOAD)
68 # define wxDllOpen(lib) shl_load(lib.fn_str(), BIND_DEFERRED, 0)
69 # define wxDllClose shl_unload
70
71 static inline void *wxDllGetSymbol(shl_t handle, const wxString& name)
72 {
73 void *sym;
74 if ( shl_findsym(&handle, name.mb_str(), TYPE_UNDEFINED, &sym) == 0 )
75 return sym;
76 else
77 return (void *)0;
78 }
79 #elif defined(__WINDOWS__)
80 // using LoadLibraryEx under Win32 to avoid name clash with LoadLibrary
81 # ifdef __WIN32__
82 #ifdef _UNICODE
83 # define wxDllOpen(lib) ::LoadLibraryExW(lib, 0, 0)
84 #else
85 # define wxDllOpen(lib) ::LoadLibraryExA(lib, 0, 0)
86 #endif
87 # else // Win16
88 # define wxDllOpen(lib) ::LoadLibrary(lib)
89 # endif // Win32/16
90 # define wxDllGetSymbol(handle, name) ::GetProcAddress(handle, name)
91 # define wxDllClose ::FreeLibrary
92 #else
93 # error "Don't know how to load shared libraries on this platform."
94 #endif // OS
95
96 // ---------------------------------------------------------------------------
97 // Global variables
98 // ---------------------------------------------------------------------------
99
100 wxLibraries wxTheLibraries;
101
102 // ============================================================================
103 // implementation
104 // ============================================================================
105
106 // construct the full name from the base shared object name: adds a .dll
107 // suffix under Windows or .so under Unix
108 static wxString ConstructLibraryName(const wxString& basename)
109 {
110 wxString fullname;
111 fullname << basename << wxDllLoader::GetDllExt();
112
113 return fullname;
114 }
115
116 // ---------------------------------------------------------------------------
117 // wxLibrary (one instance per dynamic library)
118 // ---------------------------------------------------------------------------
119
120 wxLibrary::wxLibrary(wxDllType handle)
121 {
122 typedef wxClassInfo *(*t_get_first)(void);
123 t_get_first get_first;
124
125 m_handle = handle;
126
127 // Some system may use a local heap for library.
128 get_first = (t_get_first)GetSymbol("wxGetClassFirst");
129 // It is a wxWindows DLL.
130 if (get_first)
131 PrepareClasses(get_first());
132 }
133
134 wxLibrary::~wxLibrary()
135 {
136 if ( m_handle )
137 {
138 wxDllClose(m_handle);
139 }
140 }
141
142 wxObject *wxLibrary::CreateObject(const wxString& name)
143 {
144 wxClassInfo *info = (wxClassInfo *)classTable.Get(name);
145
146 if (!info)
147 return NULL;
148
149 return info->CreateObject();
150 }
151
152 void wxLibrary::PrepareClasses(wxClassInfo *first)
153 {
154 // Index all class infos by their class name
155 wxClassInfo *info = first;
156 while (info)
157 {
158 if (info->m_className)
159 classTable.Put(info->m_className, (wxObject *)info);
160 info = info->GetNext();
161 }
162
163 // Set base pointers for each wxClassInfo
164 info = first;
165 while (info)
166 {
167 if (info->GetBaseClassName1())
168 info->m_baseInfo1 = (wxClassInfo *)classTable.Get(info->GetBaseClassName1());
169 if (info->GetBaseClassName2())
170 info->m_baseInfo2 = (wxClassInfo *)classTable.Get(info->GetBaseClassName2());
171 info = info->m_next;
172 }
173 }
174
175 void *wxLibrary::GetSymbol(const wxString& symbname)
176 {
177 return wxDllLoader::GetSymbol(m_handle, symbname);
178 }
179
180 // ---------------------------------------------------------------------------
181 // wxDllLoader
182 // ---------------------------------------------------------------------------
183
184 /* static */
185 wxString wxDllLoader::GetDllExt()
186 {
187 wxString ext;
188
189 #if defined(__WINDOWS__) || defined(__WXPM__) || defined(__EMX__)
190 ext = _T(".dll");
191 #elif defined(__UNIX__)
192 # if defined(__HPUX__)
193 ext = _T(".sl");
194 # else //__HPUX__
195 ext = _T(".so");
196 # endif //__HPUX__
197 #endif
198
199 return ext;
200 }
201
202 /* static */
203 wxDllType
204 wxDllLoader::GetProgramHandle(void)
205 {
206 #if defined( HAVE_DLOPEN ) && !defined(__EMX__)
207 // optain handle for main program
208 return dlopen(NULL, RTLD_NOW/*RTLD_LAZY*/);
209 #elif defined (HAVE_SHL_LOAD)
210 // shl_findsymbol with NULL handle looks up in main program
211 return 0;
212 #else
213 wxFAIL_MSG( wxT("This method is not implemented under Windows or OS/2"));
214 return 0;
215 #endif
216 }
217
218 /* static */
219 wxDllType
220 wxDllLoader::LoadLibrary(const wxString & libname, bool *success)
221 {
222 wxDllType handle;
223
224 #if defined(__WXMAC__)
225 FSSpec myFSSpec ;
226 Ptr myMainAddr ;
227 Str255 myErrName ;
228
229 wxMacPathToFSSpec( libname , &myFSSpec ) ;
230 if (GetDiskFragment( &myFSSpec , 0 , kCFragGoesToEOF , "\p" , kPrivateCFragCopy , &handle , &myMainAddr ,
231 myErrName ) != noErr )
232 {
233 p2cstr( myErrName ) ;
234 wxASSERT_MSG( 1 , (char*)myErrName ) ;
235 return NULL ;
236 }
237 #elif defined(__WXPM__) || defined(__EMX__)
238 char zError[256] = "";
239 wxDllOpen(zError, libname, handle);
240 #else // !Mac
241 handle = wxDllOpen(libname);
242 #endif // OS
243
244 if ( !handle )
245 {
246 wxString msg(_("Failed to load shared library '%s'"));
247
248 #ifdef HAVE_DLERROR
249 const char *errmsg = dlerror();
250 if ( errmsg )
251 {
252 // the error string format is "libname: ...", but we already have
253 // libname, so cut it off
254 const char *p = strchr(errmsg, ':');
255 if ( p )
256 {
257 if ( *++p == ' ' )
258 p++;
259 }
260 else
261 {
262 p = errmsg;
263 }
264
265 msg += _T(" (%s)");
266 wxLogError(msg, libname.c_str(), p);
267 }
268 else
269 #endif // HAVE_DLERROR
270 {
271 wxLogSysError(msg, libname.c_str());
272 }
273 }
274
275 if ( success )
276 {
277 *success = handle != 0;
278 }
279
280 return handle;
281 }
282
283
284 /* static */
285 void
286 wxDllLoader::UnloadLibrary(wxDllType handle)
287 {
288 wxDllClose(handle);
289 }
290
291 /* static */
292 void *
293 wxDllLoader::GetSymbol(wxDllType dllHandle, const wxString &name)
294 {
295 void *symbol = NULL; // return value
296
297 #if defined( __WXMAC__ )
298 Ptr symAddress ;
299 CFragSymbolClass symClass ;
300 Str255 symName ;
301
302 strcpy( (char*) symName , name ) ;
303 c2pstr( (char*) symName ) ;
304
305 if ( FindSymbol( dllHandle , symName , &symAddress , &symClass ) == noErr )
306 symbol = (void *)symAddress ;
307 #elif defined( __WXPM__ ) || defined(__EMX__)
308 wxDllGetSymbol(dllHandle, symbol);
309 #else
310 // mb_str() is necessary in Unicode build
311 symbol = wxDllGetSymbol(dllHandle, name.mb_str());
312 #endif
313
314 if ( !symbol )
315 {
316 wxLogSysError(_("Couldn't find symbol '%s' in a dynamic library"),
317 name.c_str());
318 }
319 return symbol;
320 }
321
322 // ---------------------------------------------------------------------------
323 // wxLibraries (only one instance should normally exist)
324 // ---------------------------------------------------------------------------
325
326 wxLibraries::wxLibraries():m_loaded(wxKEY_STRING)
327 {
328 }
329
330 wxLibraries::~wxLibraries()
331 {
332 wxNode *node = m_loaded.First();
333
334 while (node) {
335 wxLibrary *lib = (wxLibrary *)node->Data();
336 delete lib;
337
338 node = node->Next();
339 }
340 }
341
342 wxLibrary *wxLibraries::LoadLibrary(const wxString& name)
343 {
344 wxNode *node;
345 wxLibrary *lib;
346 wxClassInfo *old_sm_first;
347
348 #if defined(__VISAGECPP__)
349 node = m_loaded.Find(name.GetData());
350 if (node != NULL)
351 return ((wxLibrary *)node->Data());
352 #else // !OS/2
353 if ( (node = m_loaded.Find(name.GetData())) )
354 return ((wxLibrary *)node->Data());
355 #endif
356 // If DLL shares data, this is necessary.
357 old_sm_first = wxClassInfo::sm_first;
358 wxClassInfo::sm_first = NULL;
359
360 wxString libname = ConstructLibraryName(name);
361
362 /*
363 Unix automatically builds that library name, at least for dlopen()
364 */
365 #if 0
366 #if defined(__UNIX__)
367 // found the first file in LD_LIBRARY_PATH with this name
368 wxString libPath("/lib:/usr/lib"); // system path first
369 const char *envLibPath = getenv("LD_LIBRARY_PATH");
370 if ( envLibPath )
371 libPath << wxT(':') << envLibPath;
372 wxStringTokenizer tokenizer(libPath, wxT(':'));
373 while ( tokenizer.HasMoreToken() )
374 {
375 wxString fullname(tokenizer.NextToken());
376
377 fullname << wxT('/') << libname;
378 if ( wxFileExists(fullname) )
379 {
380 libname = fullname;
381
382 // found the library
383 break;
384 }
385 }
386 //else: not found in the path, leave the name as is (secutiry risk?)
387
388 #endif // __UNIX__
389 #endif
390
391 bool success = FALSE;
392 wxDllType handle = wxDllLoader::LoadLibrary(libname, &success);
393 if(success)
394 {
395 lib = new wxLibrary(handle);
396 wxClassInfo::sm_first = old_sm_first;
397 m_loaded.Append(name.GetData(), lib);
398 }
399 else
400 lib = NULL;
401 return lib;
402 }
403
404 wxObject *wxLibraries::CreateObject(const wxString& path)
405 {
406 wxNode *node = m_loaded.First();
407 wxObject *obj;
408
409 while (node) {
410 obj = ((wxLibrary *)node->Data())->CreateObject(path);
411 if (obj)
412 return obj;
413
414 node = node->Next();
415 }
416 return NULL;
417 }
418
419 #endif // wxUSE_DYNLIB_CLASS