]> git.saurik.com Git - wxWidgets.git/blob - src/common/dynlib.cpp
make sure gs_captureWindow is always set to NULL in DoReleaseMouse
[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 && !wxUSE_DYNAMIC_LOADER
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
41 #if defined(__WXMAC__)
42 #include "wx/mac/private.h"
43 #endif
44
45 // ----------------------------------------------------------------------------
46 // conditional compilation
47 // ----------------------------------------------------------------------------
48
49 #if defined(__WXPM__) || defined(__EMX__)
50 # define INCL_DOS
51 # include <os2.h>
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.
61 #ifdef __VMS
62 # define wxDllOpen(lib) dlopen(lib.fn_str(), 0 )
63 #elif defined( __osf__ )
64 # define wxDllOpen(lib) dlopen(lib.fn_str(), RTLD_LAZY )
65 #else
66 # define wxDllOpen(lib) dlopen(lib.fn_str(), RTLD_LAZY | RTLD_GLOBAL)
67 #endif
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
73
74 static inline void *wxDllGetSymbol(shl_t handle, const wxString& name)
75 {
76 void *sym;
77 if ( shl_findsym(&handle, name.mb_str(), TYPE_UNDEFINED, &sym) == 0 )
78 return sym;
79 else
80 return 0;
81 }
82
83 #elif defined(__DARWIN__)
84 /* Porting notes:
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*.
89 */
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);
94
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
100 # ifdef __WIN32__
101 #ifdef _UNICODE
102 # define wxDllOpen(lib) ::LoadLibraryExW(lib, 0, 0)
103 #else
104 # define wxDllOpen(lib) ::LoadLibraryExA(lib, 0, 0)
105 #endif
106 # else // Win16
107 # define wxDllOpen(lib) ::LoadLibrary(lib)
108 # endif // Win32/16
109 # define wxDllGetSymbol(handle, name) ::GetProcAddress(handle, name)
110 # define wxDllClose ::FreeLibrary
111 #elif defined(__WXMAC__)
112 # define wxDllClose(handle) CloseConnection(&((CFragConnectionID)handle))
113 #else
114 # error "Don't know how to load shared libraries on this platform."
115 #endif // OS
116
117 // ---------------------------------------------------------------------------
118 // Global variables
119 // ---------------------------------------------------------------------------
120
121 wxLibraries wxTheLibraries;
122
123 // ============================================================================
124 // implementation
125 // ============================================================================
126
127 // construct the full name from the base shared object name: adds a .dll
128 // suffix under Windows or .so under Unix
129 static wxString ConstructLibraryName(const wxString& basename)
130 {
131 wxString fullname;
132 fullname << basename << wxDllLoader::GetDllExt();
133
134 return fullname;
135 }
136
137 // ---------------------------------------------------------------------------
138 // wxLibrary (one instance per dynamic library)
139 // ---------------------------------------------------------------------------
140
141 wxLibrary::wxLibrary(wxDllType handle)
142 {
143 typedef wxClassInfo *(*t_get_first)(void);
144 t_get_first get_first;
145
146 m_handle = handle;
147
148 // Some system may use a local heap for library.
149 get_first = (t_get_first)GetSymbol("wxGetClassFirst");
150 // It is a wxWindows DLL.
151 if (get_first)
152 PrepareClasses(get_first());
153 }
154
155 wxLibrary::~wxLibrary()
156 {
157 if ( m_handle )
158 {
159 wxDllClose(m_handle);
160 }
161 }
162
163 wxObject *wxLibrary::CreateObject(const wxString& name)
164 {
165 wxClassInfo *info = (wxClassInfo *)classTable.Get(name);
166
167 if (!info)
168 return NULL;
169
170 return info->CreateObject();
171 }
172
173 void wxLibrary::PrepareClasses(wxClassInfo *first)
174 {
175 // Index all class infos by their class name
176 wxClassInfo *info = first;
177 while (info)
178 {
179 if (info->m_className)
180 classTable.Put(info->m_className, (wxObject *)info);
181 info = info->m_next;
182 }
183
184 // Set base pointers for each wxClassInfo
185 info = first;
186 while (info)
187 {
188 if (info->GetBaseClassName1())
189 info->m_baseInfo1 = (wxClassInfo *)classTable.Get(info->GetBaseClassName1());
190 if (info->GetBaseClassName2())
191 info->m_baseInfo2 = (wxClassInfo *)classTable.Get(info->GetBaseClassName2());
192 info = info->m_next;
193 }
194 }
195
196 void *wxLibrary::GetSymbol(const wxString& symbname)
197 {
198 return wxDllLoader::GetSymbol(m_handle, symbname);
199 }
200
201 // ---------------------------------------------------------------------------
202 // wxDllLoader
203 // ---------------------------------------------------------------------------
204
205
206 #if defined(__WINDOWS__) || defined(__WXPM__) || defined(__EMX__)
207 const wxString wxDllLoader::ms_dllext( _T(".dll") );
208 #elif defined(__UNIX__)
209 #if defined(__HPUX__)
210 const wxString wxDllLoader::ms_dllext( _T(".sl") );
211 #else
212 const wxString wxDllLoader::ms_dllext( _T(".so") );
213 #endif
214 #endif
215
216 /* static */
217 wxDllType wxDllLoader::GetProgramHandle()
218 {
219 #if defined( HAVE_DLOPEN ) && !defined(__EMX__)
220 // optain handle for main program
221 return dlopen(NULL, RTLD_NOW/*RTLD_LAZY*/);
222 #elif defined (HAVE_SHL_LOAD)
223 // shl_findsymbol with NULL handle looks up in main program
224 return 0;
225 #else
226 wxFAIL_MSG( wxT("This method is not implemented under Windows or OS/2"));
227 return 0;
228 #endif
229 }
230
231 /* static */
232 wxDllType wxDllLoader::LoadLibrary(const wxString & libname, bool *success)
233 {
234 wxDllType handle;
235 bool failed = FALSE;
236
237 #if defined(__WXMAC__) && !defined(__UNIX__)
238 FSSpec myFSSpec;
239 Ptr myMainAddr;
240 Str255 myErrName;
241
242 wxMacFilename2FSSpec( libname , &myFSSpec );
243
244 if( GetDiskFragment( &myFSSpec,
245 0,
246 kCFragGoesToEOF,
247 "\p",
248 kPrivateCFragCopy,
249 &((CFragConnectionID)handle),
250 &myMainAddr,
251 myErrName ) != noErr )
252 {
253 p2cstr( myErrName );
254 wxLogSysError( _("Failed to load shared library '%s' Error '%s'"),
255 libname.c_str(),
256 (char*)myErrName );
257 handle = 0;
258 failed = TRUE;
259 }
260
261 #elif defined(__WXPM__) || defined(__EMX__)
262 char zError[256] = "";
263 wxDllOpen(zError, libname, handle);
264
265 #else
266 handle = wxDllOpen(libname);
267
268 #endif
269
270 if ( !handle )
271 {
272 wxString msg(_("Failed to load shared library '%s'"));
273
274 #ifdef HAVE_DLERROR
275 const wxChar *err = dlerror();
276 if( err )
277 {
278 failed = TRUE;
279 wxLogError( msg, err );
280 }
281 #else
282 failed = TRUE;
283 wxLogSysError( msg, libname.c_str() );
284 #endif
285 }
286
287 if ( success )
288 *success = !failed;
289
290 return handle;
291 }
292
293
294 /* static */
295 void wxDllLoader::UnloadLibrary(wxDllType handle)
296 {
297 wxDllClose(handle);
298 }
299
300 /* static */
301 void *wxDllLoader::GetSymbol(wxDllType dllHandle, const wxString &name, bool *success)
302 {
303 bool failed = FALSE;
304 void *symbol = 0;
305
306 #if defined(__WXMAC__) && !defined(__UNIX__)
307 Ptr symAddress;
308 CFragSymbolClass symClass;
309 Str255 symName;
310
311 #if TARGET_CARBON
312 c2pstrcpy( (StringPtr) symName, name );
313 #else
314 strcpy( (char *) symName, name );
315 c2pstr( (char *) symName );
316 #endif
317 if( FindSymbol( ((CFragConnectionID)dllHandle), symName, &symAddress, &symClass ) == noErr )
318 symbol = (void *)symAddress;
319
320 #elif defined(__WXPM__) || defined(__EMX__)
321 wxDllGetSymbol(dllHandle, symbol);
322
323 #else
324 // mb_str() is necessary in Unicode build
325 symbol = wxDllGetSymbol(dllHandle, name.mb_str());
326
327 #endif
328
329 if ( !symbol )
330 {
331 wxString msg(_("wxDllLoader failed to GetSymbol '%s'"));
332
333 #ifdef HAVE_DLERROR
334 const wxChar *err = dlerror();
335 if( err )
336 {
337 failed = TRUE;
338 wxLogError( msg, err );
339 }
340 #else
341 failed = TRUE;
342 wxLogSysError(_("Couldn't find symbol '%s' in a dynamic library"),
343 name.c_str());
344 #endif
345 }
346
347 if( success )
348 *success = !failed;
349
350 return symbol;
351 }
352
353 // ---------------------------------------------------------------------------
354 // wxLibraries (only one instance should normally exist)
355 // ---------------------------------------------------------------------------
356
357 wxLibraries::wxLibraries():m_loaded(wxKEY_STRING)
358 {
359 }
360
361 wxLibraries::~wxLibraries()
362 {
363 wxNode *node = m_loaded.First();
364
365 while (node) {
366 wxLibrary *lib = (wxLibrary *)node->Data();
367 delete lib;
368
369 node = node->Next();
370 }
371 }
372
373 wxLibrary *wxLibraries::LoadLibrary(const wxString& name)
374 {
375 wxLibrary *lib;
376 wxClassInfo *old_sm_first;
377 wxNode *node = m_loaded.Find(name.GetData());
378
379 if (node != NULL)
380 return ((wxLibrary *)node->Data());
381
382 // If DLL shares data, this is necessary.
383 old_sm_first = wxClassInfo::sm_first;
384 wxClassInfo::sm_first = NULL;
385
386 wxString libname = ConstructLibraryName(name);
387
388 bool success = FALSE;
389 wxDllType handle = wxDllLoader::LoadLibrary(libname, &success);
390 if(success)
391 {
392 lib = new wxLibrary(handle);
393 wxClassInfo::sm_first = old_sm_first;
394
395 m_loaded.Append(name.GetData(), lib);
396 }
397 else
398 lib = NULL;
399 return lib;
400 }
401
402 wxObject *wxLibraries::CreateObject(const wxString& path)
403 {
404 wxNode *node = m_loaded.First();
405 wxObject *obj;
406
407 while (node) {
408 obj = ((wxLibrary *)node->Data())->CreateObject(path);
409 if (obj)
410 return obj;
411
412 node = node->Next();
413 }
414 return NULL;
415 }
416
417 #ifdef __DARWIN__
418 // ---------------------------------------------------------------------------
419 // For Darwin/Mac OS X
420 // supply the sun style dlopen functions in terms of Darwin NS*
421 // ---------------------------------------------------------------------------
422
423 extern "C" {
424 #import <mach-o/dyld.h>
425 };
426
427 enum dyldErrorSource
428 {
429 OFImage,
430 };
431
432 static char dl_last_error[1024];
433
434 static
435 void TranslateError(const char *path, enum dyldErrorSource type, int number)
436 {
437 unsigned int index;
438 static char *OFIErrorStrings[] =
439 {
440 "%s(%d): Object Image Load Failure\n",
441 "%s(%d): Object Image Load Success\n",
442 "%s(%d): Not an recognisable object file\n",
443 "%s(%d): No valid architecture\n",
444 "%s(%d): Object image has an invalid format\n",
445 "%s(%d): Invalid access (permissions?)\n",
446 "%s(%d): Unknown error code from NSCreateObjectFileImageFromFile\n",
447 };
448 #define NUM_OFI_ERRORS (sizeof(OFIErrorStrings) / sizeof(OFIErrorStrings[0]))
449
450 switch (type)
451 {
452 case OFImage:
453 index = number;
454 if (index > NUM_OFI_ERRORS - 1) {
455 index = NUM_OFI_ERRORS - 1;
456 }
457 sprintf(dl_last_error, OFIErrorStrings[index], path, number);
458 break;
459
460 default:
461 sprintf(dl_last_error, "%s(%d): Totally unknown error type %d\n",
462 path, number, type);
463 break;
464 }
465 }
466
467 const char *dlerror()
468 {
469 return dl_last_error;
470 }
471
472 void *dlopen(const char *path, int mode /* mode is ignored */)
473 {
474 int dyld_result;
475 NSObjectFileImage ofile;
476 NSModule handle = NULL;
477
478 dyld_result = NSCreateObjectFileImageFromFile(path, &ofile);
479 if (dyld_result != NSObjectFileImageSuccess)
480 {
481 TranslateError(path, OFImage, dyld_result);
482 }
483 else
484 {
485 // NSLinkModule will cause the run to abort on any link error's
486 // not very friendly but the error recovery functionality is limited.
487 handle = NSLinkModule(ofile, path, TRUE);
488 }
489
490 return handle;
491 }
492
493 int dlclose(void *handle) /* stub only */
494 {
495 return 0;
496 }
497
498 void *dlsym(void *handle, const char *symbol)
499 {
500 void *addr;
501
502 if (NSIsSymbolNameDefined(symbol)) {
503 addr = NSAddressOfSymbol(NSLookupAndBindSymbol(symbol));
504 }
505 else {
506 addr = NULL;
507 }
508 return addr;
509 }
510
511 #endif // __DARWIN__
512
513 #endif // wxUSE_DYNLIB_CLASS