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