]> git.saurik.com Git - wxWidgets.git/blob - src/common/dynlib.cpp
Committed William Osborne's wxPalmOS port
[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 licence
10 /////////////////////////////////////////////////////////////////////////////
11
12 // ============================================================================
13 // declarations
14 // ============================================================================
15
16 // ----------------------------------------------------------------------------
17 // headers
18 // ----------------------------------------------------------------------------
19
20 #if defined(__GNUG__) && !defined(NO_GCC_PRAGMA)
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/wrapwin.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/utils.h"
41 #include "wx/filename.h" // for SplitPath()
42 #include "wx/app.h"
43 #include "wx/apptrait.h"
44
45 #if defined(__WXMAC__)
46 #include "wx/mac/private.h"
47 #endif
48
49
50 // ============================================================================
51 // implementation
52 // ============================================================================
53
54 #if defined(__DARWIN__)
55 // ---------------------------------------------------------------------------
56 // For Darwin/Mac OS X
57 // supply the sun style dlopen functions in terms of Darwin NS*
58 // ---------------------------------------------------------------------------
59
60 /* Porting notes:
61 * The dlopen port is a port from dl_next.xs by Anno Siegel.
62 * dl_next.xs is itself a port from dl_dlopen.xs by Paul Marquess.
63 * The method used here is just to supply the sun style dlopen etc.
64 * functions in terms of Darwin NS*.
65 */
66
67 #include <stdio.h>
68 #include <mach-o/dyld.h>
69
70 static char dl_last_error[1024];
71
72 static
73 void TranslateError(const char *path, int number)
74 {
75 unsigned int index;
76 static char *OFIErrorStrings[] =
77 {
78 "%s(%d): Object Image Load Failure\n",
79 "%s(%d): Object Image Load Success\n",
80 "%s(%d): Not an recognisable object file\n",
81 "%s(%d): No valid architecture\n",
82 "%s(%d): Object image has an invalid format\n",
83 "%s(%d): Invalid access (permissions?)\n",
84 "%s(%d): Unknown error code from NSCreateObjectFileImageFromFile\n",
85 };
86 #define NUM_OFI_ERRORS (sizeof(OFIErrorStrings) / sizeof(OFIErrorStrings[0]))
87
88 index = number;
89 if (index > NUM_OFI_ERRORS - 1) {
90 index = NUM_OFI_ERRORS - 1;
91 }
92 sprintf(dl_last_error, OFIErrorStrings[index], path, number);
93 }
94
95 const char *dlerror()
96 {
97 return dl_last_error;
98 }
99
100 void *dlopen(const char *path, int WXUNUSED(mode) /* mode is ignored */)
101 {
102 int dyld_result;
103 NSObjectFileImage ofile;
104 NSModule handle = NULL;
105
106 dyld_result = NSCreateObjectFileImageFromFile(path, &ofile);
107 if (dyld_result != NSObjectFileImageSuccess)
108 {
109 TranslateError(path, dyld_result);
110 }
111 else
112 {
113 // NSLinkModule will cause the run to abort on any link error's
114 // not very friendly but the error recovery functionality is limited.
115 handle = NSLinkModule(ofile, path, NSLINKMODULE_OPTION_BINDNOW);
116 }
117
118 return handle;
119 }
120
121 int dlclose(void *handle)
122 {
123 NSUnLinkModule( handle, NSUNLINKMODULE_OPTION_NONE);
124 return 0;
125 }
126
127 void *dlsym(void *handle, const char *symbol)
128 {
129 // as on many other systems, C symbols have prepended underscores under
130 // Darwin but unlike the normal dlopen(), NSLookupSymbolInModule() is not
131 // aware of this
132 wxCharBuffer buf(strlen(symbol) + 1);
133 char *p = buf.data();
134 p[0] = '_';
135 strcpy(p + 1, symbol);
136
137 NSSymbol nsSymbol = NSLookupSymbolInModule( handle, p );
138 return nsSymbol ? NSAddressOfSymbol(nsSymbol) : NULL;
139 }
140
141 #endif // defined(__DARWIN__)
142
143
144 // ---------------------------------------------------------------------------
145 // wxDynamicLibrary
146 // ---------------------------------------------------------------------------
147
148 //FIXME: This class isn't really common at all, it should be moved into
149 // platform dependent files.
150
151 #if defined(__WINDOWS__) || defined(__WXPM__) || defined(__EMX__)
152 const wxChar *wxDynamicLibrary::ms_dllext = _T(".dll");
153 #elif defined(__WXMAC__) && !defined(__DARWIN__)
154 const wxChar *wxDynamicLibrary::ms_dllext = _T("");
155 #elif defined(__UNIX__)
156 #if defined(__HPUX__)
157 const wxChar *wxDynamicLibrary::ms_dllext = _T(".sl");
158 #elif defined(__DARWIN__)
159 const wxChar *wxDynamicLibrary::ms_dllext = _T(".bundle");
160 #else
161 const wxChar *wxDynamicLibrary::ms_dllext = _T(".so");
162 #endif
163 #endif
164
165 wxDllType wxDynamicLibrary::GetProgramHandle()
166 {
167 #if defined( HAVE_DLOPEN ) && !defined(__EMX__)
168 return dlopen(0, RTLD_LAZY);
169 #elif defined (HAVE_SHL_LOAD)
170 return PROG_HANDLE;
171 #else
172 wxFAIL_MSG( wxT("This method is not implemented under Windows or OS/2"));
173 return 0;
174 #endif
175 }
176
177 bool wxDynamicLibrary::Load(wxString libname, int flags)
178 {
179 wxASSERT_MSG(m_handle == 0, _T("Library already loaded."));
180
181 // add the proper extension for the DLL ourselves unless told not to
182 if ( !(flags & wxDL_VERBATIM) )
183 {
184 // and also check that the libname doesn't already have it
185 wxString ext;
186 wxFileName::SplitPath(libname, NULL, NULL, &ext);
187 if ( ext.empty() )
188 {
189 libname += GetDllExt();
190 }
191 }
192
193 // different ways to load a shared library
194 //
195 // FIXME: should go to the platform-specific files!
196 #if defined(__WXMAC__) && !defined(__DARWIN__)
197 FSSpec myFSSpec;
198 Ptr myMainAddr;
199 Str255 myErrName;
200
201 wxMacFilename2FSSpec( libname , &myFSSpec );
202
203 if( GetDiskFragment( &myFSSpec,
204 0,
205 kCFragGoesToEOF,
206 "\p",
207 kPrivateCFragCopy,
208 &m_handle,
209 &myMainAddr,
210 myErrName ) != noErr )
211 {
212 wxLogSysError( _("Failed to load shared library '%s' Error '%s'"),
213 libname.c_str(),
214 wxMacMakeStringFromPascal( myErrName ).c_str() );
215 m_handle = 0;
216 }
217
218 #elif defined(__WXPM__) || defined(__EMX__)
219 char err[256] = "";
220 DosLoadModule(err, sizeof(err), libname.c_str(), &m_handle);
221
222 #elif defined(HAVE_DLOPEN) || defined(__DARWIN__)
223
224 #if defined(__VMS) || defined(__DARWIN__)
225 m_handle = dlopen(libname.fn_str(), 0); // The second parameter is ignored
226 #else // !__VMS && !__DARWIN__
227 int rtldFlags = 0;
228
229 if ( flags & wxDL_LAZY )
230 {
231 wxASSERT_MSG( (flags & wxDL_NOW) == 0,
232 _T("wxDL_LAZY and wxDL_NOW are mutually exclusive.") );
233 #ifdef RTLD_LAZY
234 rtldFlags |= RTLD_LAZY;
235 #else
236 wxLogDebug(_T("wxDL_LAZY is not supported on this platform"));
237 #endif
238 }
239 else if ( flags & wxDL_NOW )
240 {
241 #ifdef RTLD_NOW
242 rtldFlags |= RTLD_NOW;
243 #else
244 wxLogDebug(_T("wxDL_NOW is not supported on this platform"));
245 #endif
246 }
247
248 if ( flags & wxDL_GLOBAL )
249 {
250 #ifdef RTLD_GLOBAL
251 rtldFlags |= RTLD_GLOBAL;
252 #else
253 wxLogDebug(_T("RTLD_GLOBAL is not supported on this platform."));
254 #endif
255 }
256
257 m_handle = dlopen(libname.fn_str(), rtldFlags);
258 #endif // __VMS || __DARWIN__ ?
259
260 #elif defined(HAVE_SHL_LOAD)
261 int shlFlags = 0;
262
263 if( flags & wxDL_LAZY )
264 {
265 wxASSERT_MSG( (flags & wxDL_NOW) == 0,
266 _T("wxDL_LAZY and wxDL_NOW are mutually exclusive.") );
267 shlFlags |= BIND_DEFERRED;
268 }
269 else if( flags & wxDL_NOW )
270 {
271 shlFlags |= BIND_IMMEDIATE;
272 }
273 m_handle = shl_load(libname.fn_str(), BIND_DEFERRED, 0);
274
275 #elif defined(__WINDOWS__)
276 m_handle = ::LoadLibrary(libname.c_str());
277 #else
278 #error "runtime shared lib support not implemented on this platform"
279 #endif
280
281 if ( m_handle == 0 )
282 {
283 wxString msg(_("Failed to load shared library '%s'"));
284 #if defined(HAVE_DLERROR) && !defined(__EMX__)
285
286 #if wxUSE_UNICODE
287 wxWCharBuffer buffer = wxConvLocal.cMB2WC( dlerror() );
288 const wxChar *err = buffer;
289 #else
290 const wxChar *err = dlerror();
291 #endif
292
293 if( err )
294 wxLogError( msg, err );
295 #else
296 wxLogSysError( msg, libname.c_str() );
297 #endif
298 }
299
300 return IsLoaded();
301 }
302
303 /* static */
304 void wxDynamicLibrary::Unload(wxDllType handle)
305 {
306 #if defined(__WXPM__) || defined(__EMX__)
307 DosFreeModule( handle );
308 #elif defined(HAVE_DLOPEN) || defined(__DARWIN__)
309 dlclose( handle );
310 #elif defined(HAVE_SHL_LOAD)
311 shl_unload( handle );
312 #elif defined(__WINDOWS__)
313 ::FreeLibrary( handle );
314 #elif defined(__WXMAC__) && !defined(__DARWIN__)
315 CloseConnection( (CFragConnectionID*) &handle );
316 #else
317 #error "runtime shared lib support not implemented"
318 #endif
319 }
320
321 void *wxDynamicLibrary::DoGetSymbol(const wxString &name, bool *success) const
322 {
323 wxCHECK_MSG( IsLoaded(), NULL,
324 _T("Can't load symbol from unloaded library") );
325
326 void *symbol = 0;
327
328 wxUnusedVar(symbol);
329 #if defined(__WXMAC__) && !defined(__DARWIN__)
330 Ptr symAddress;
331 CFragSymbolClass symClass;
332 Str255 symName;
333 #if TARGET_CARBON
334 c2pstrcpy( (StringPtr) symName, name.fn_str() );
335 #else
336 strcpy( (char *)symName, name.fn_str() );
337 c2pstr( (char *)symName );
338 #endif
339 if( FindSymbol( m_handle, symName, &symAddress, &symClass ) == noErr )
340 symbol = (void *)symAddress;
341
342 #elif defined(__WXPM__) || defined(__EMX__)
343 DosQueryProcAddr( m_handle, 1L, name.c_str(), (PFN*)symbol );
344
345 #elif defined(HAVE_DLOPEN) || defined(__DARWIN__)
346 symbol = dlsym( m_handle, name.fn_str() );
347
348 #elif defined(HAVE_SHL_LOAD)
349 // use local variable since shl_findsym modifies the handle argument
350 // to indicate where the symbol was found (GD)
351 wxDllType the_handle = m_handle;
352 if( shl_findsym( &the_handle, name.fn_str(), TYPE_UNDEFINED, &symbol ) != 0 )
353 symbol = 0;
354
355 #elif defined(__WINDOWS__)
356 #ifdef __WXWINCE__
357 symbol = (void*) ::GetProcAddress( m_handle, name );
358 #else
359 symbol = (void*) ::GetProcAddress( m_handle, name.mb_str() );
360 #endif
361
362 #else
363 #error "runtime shared lib support not implemented"
364 #endif
365
366 if ( success )
367 *success = symbol != NULL;
368
369 return symbol;
370 }
371
372 void *wxDynamicLibrary::GetSymbol(const wxString& name, bool *success) const
373 {
374 void *symbol = DoGetSymbol(name, success);
375 if ( !symbol )
376 {
377 #if defined(HAVE_DLERROR) && !defined(__EMX__)
378
379 #if wxUSE_UNICODE
380 wxWCharBuffer buffer = wxConvLocal.cMB2WC( dlerror() );
381 const wxChar *err = buffer;
382 #else
383 const wxChar *err = dlerror();
384 #endif
385
386 if( err )
387 {
388 wxLogError(wxT("%s"), err);
389 }
390 #else
391 wxLogSysError(_("Couldn't find symbol '%s' in a dynamic library"),
392 name.c_str());
393 #endif
394 }
395
396 return symbol;
397 }
398
399 /*static*/
400 wxString
401 wxDynamicLibrary::CanonicalizeName(const wxString& name,
402 wxDynamicLibraryCategory
403 #ifdef __UNIX__
404 cat
405 #else // !__UNIX__
406 WXUNUSED(cat)
407 #endif // __UNIX__/!__UNIX__
408 )
409 {
410 wxString nameCanonic;
411
412 // under Unix the library names usually start with "lib" prefix, add it
413 #ifdef __UNIX__
414 switch ( cat )
415 {
416 default:
417 wxFAIL_MSG( _T("unknown wxDynamicLibraryCategory value") );
418 // fall through
419
420 case wxDL_MODULE:
421 // don't do anything for modules, their names are arbitrary
422 break;
423
424 case wxDL_LIBRARY:
425 // library names should start with "lib" under Unix
426 nameCanonic = _T("lib");
427 break;
428 }
429 #endif // __UNIX__
430
431 nameCanonic << name << GetDllExt();
432 return nameCanonic;
433 }
434
435 /*static*/
436 wxString wxDynamicLibrary::CanonicalizePluginName(const wxString& name,
437 wxPluginCategory cat)
438 {
439 wxString suffix;
440 if ( cat == wxDL_PLUGIN_GUI )
441 {
442 wxAppTraits *traits = wxAppConsole::GetInstance() ?
443 wxAppConsole::GetInstance()->GetTraits() : NULL;
444 wxASSERT_MSG( traits,
445 _("can't query for GUI plugins name in console applications") );
446 suffix = traits->GetToolkitInfo().shortName;
447 }
448 #if wxUSE_UNICODE
449 suffix << _T('u');
450 #endif
451 #ifdef __WXDEBUG__
452 suffix << _T('d');
453 #endif
454
455 if ( !suffix.empty() )
456 suffix = wxString(_T("_")) + suffix;
457
458 #define WXSTRINGIZE(x) #x
459 #ifdef __UNIX__
460 #if (wxMINOR_VERSION % 2) == 0
461 #define wxDLLVER(x,y,z) "-" WXSTRINGIZE(x) "." WXSTRINGIZE(y)
462 #else
463 #define wxDLLVER(x,y,z) "-" WXSTRINGIZE(x) "." WXSTRINGIZE(y) "." WXSTRINGIZE(z)
464 #endif
465 #else
466 #if (wxMINOR_VERSION % 2) == 0
467 #define wxDLLVER(x,y,z) WXSTRINGIZE(x) WXSTRINGIZE(y)
468 #else
469 #define wxDLLVER(x,y,z) WXSTRINGIZE(x) WXSTRINGIZE(y) WXSTRINGIZE(z)
470 #endif
471 #endif
472
473 suffix << wxString::FromAscii(wxDLLVER(wxMAJOR_VERSION, wxMINOR_VERSION,
474 wxRELEASE_NUMBER));
475 #undef wxDLLVER
476 #undef WXSTRINGIZE
477
478 #ifdef __WINDOWS__
479 // Add compiler identification:
480 #if defined(__GNUG__)
481 suffix << _T("_gcc");
482 #elif defined(__VISUALC__)
483 suffix << _T("_vc");
484 #elif defined(__WATCOMC__)
485 suffix << _T("_wat");
486 #elif defined(__BORLANDC__)
487 suffix << _T("_bcc");
488 #endif
489 #endif
490
491 return CanonicalizeName(name + suffix, wxDL_MODULE);
492 }
493
494 /*static*/
495 wxString wxDynamicLibrary::GetPluginsDirectory()
496 {
497 #ifdef __UNIX__
498 wxString format = wxGetInstallPrefix();
499 wxString dir;
500 format << wxFILE_SEP_PATH
501 << wxT("lib") << wxFILE_SEP_PATH
502 << wxT("wx") << wxFILE_SEP_PATH
503 #if (wxMINOR_VERSION % 2) == 0
504 << wxT("%i.%i");
505 dir.Printf(format.c_str(), wxMAJOR_VERSION, wxMINOR_VERSION);
506 #else
507 << wxT("%i.%i.%i");
508 dir.Printf(format.c_str(),
509 wxMAJOR_VERSION, wxMINOR_VERSION, wxRELEASE_NUMBER);
510 #endif
511 return dir;
512
513 #else // ! __UNIX__
514 return wxEmptyString;
515 #endif
516 }
517
518
519 #endif // wxUSE_DYNLIB_CLASS