]> git.saurik.com Git - wxWidgets.git/blob - src/common/dynlib.cpp
- wxDynamicLibrary::GetDllExt() now returns ".bundle", not ".dylib"
[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 NSSymbol nsSymbol = NSLookupSymbolInModule( handle,
133 wxString(_T('_')) + symbol );
134 return nsSymbol ? NSAddressOfSymbol(nsSymbol) : NULL;
135 }
136
137 #endif // defined(__DARWIN__)
138
139
140 // ---------------------------------------------------------------------------
141 // wxDynamicLibrary
142 // ---------------------------------------------------------------------------
143
144 //FIXME: This class isn't really common at all, it should be moved into
145 // platform dependent files.
146
147 #if defined(__WINDOWS__) || defined(__WXPM__) || defined(__EMX__)
148 const wxChar *wxDynamicLibrary::ms_dllext = _T(".dll");
149 #elif defined(__WXMAC__) && !defined(__DARWIN__)
150 const wxChar *wxDynamicLibrary::ms_dllext = _T("");
151 #elif defined(__UNIX__)
152 #if defined(__HPUX__)
153 const wxChar *wxDynamicLibrary::ms_dllext = _T(".sl");
154 #elif defined(__DARWIN__)
155 const wxChar *wxDynamicLibrary::ms_dllext = _T(".bundle");
156 #else
157 const wxChar *wxDynamicLibrary::ms_dllext = _T(".so");
158 #endif
159 #endif
160
161 wxDllType wxDynamicLibrary::GetProgramHandle()
162 {
163 #if defined( HAVE_DLOPEN ) && !defined(__EMX__)
164 return dlopen(0, RTLD_LAZY);
165 #elif defined (HAVE_SHL_LOAD)
166 return PROG_HANDLE;
167 #else
168 wxFAIL_MSG( wxT("This method is not implemented under Windows or OS/2"));
169 return 0;
170 #endif
171 }
172
173 bool wxDynamicLibrary::Load(wxString libname, int flags)
174 {
175 wxASSERT_MSG(m_handle == 0, _T("Library already loaded."));
176
177 // add the proper extension for the DLL ourselves unless told not to
178 if ( !(flags & wxDL_VERBATIM) )
179 {
180 // and also check that the libname doesn't already have it
181 wxString ext;
182 wxFileName::SplitPath(libname, NULL, NULL, &ext);
183 if ( ext.empty() )
184 {
185 libname += GetDllExt();
186 }
187 }
188
189 // different ways to load a shared library
190 //
191 // FIXME: should go to the platform-specific files!
192 #if defined(__WXMAC__) && !defined(__DARWIN__)
193 FSSpec myFSSpec;
194 Ptr myMainAddr;
195 Str255 myErrName;
196
197 wxMacFilename2FSSpec( libname , &myFSSpec );
198
199 if( GetDiskFragment( &myFSSpec,
200 0,
201 kCFragGoesToEOF,
202 "\p",
203 kPrivateCFragCopy,
204 &m_handle,
205 &myMainAddr,
206 myErrName ) != noErr )
207 {
208 wxLogSysError( _("Failed to load shared library '%s' Error '%s'"),
209 libname.c_str(),
210 wxMacMakeStringFromPascal( myErrName ).c_str() );
211 m_handle = 0;
212 }
213
214 #elif defined(__WXPM__) || defined(__EMX__)
215 char err[256] = "";
216 DosLoadModule(err, sizeof(err), libname.c_str(), &m_handle);
217
218 #elif defined(HAVE_DLOPEN) || defined(__DARWIN__)
219
220 #if defined(__VMS) || defined(__DARWIN__)
221 m_handle = dlopen(libname.fn_str(), 0); // The second parameter is ignored
222 #else // !__VMS && !__DARWIN__
223 int rtldFlags = 0;
224
225 if ( flags & wxDL_LAZY )
226 {
227 wxASSERT_MSG( (flags & wxDL_NOW) == 0,
228 _T("wxDL_LAZY and wxDL_NOW are mutually exclusive.") );
229 #ifdef RTLD_LAZY
230 rtldFlags |= RTLD_LAZY;
231 #else
232 wxLogDebug(_T("wxDL_LAZY is not supported on this platform"));
233 #endif
234 }
235 else if ( flags & wxDL_NOW )
236 {
237 #ifdef RTLD_NOW
238 rtldFlags |= RTLD_NOW;
239 #else
240 wxLogDebug(_T("wxDL_NOW is not supported on this platform"));
241 #endif
242 }
243
244 if ( flags & wxDL_GLOBAL )
245 {
246 #ifdef RTLD_GLOBAL
247 rtldFlags |= RTLD_GLOBAL;
248 #else
249 wxLogDebug(_T("RTLD_GLOBAL is not supported on this platform."));
250 #endif
251 }
252
253 m_handle = dlopen(libname.fn_str(), rtldFlags);
254 #endif // __VMS || __DARWIN__ ?
255
256 #elif defined(HAVE_SHL_LOAD)
257 int shlFlags = 0;
258
259 if( flags & wxDL_LAZY )
260 {
261 wxASSERT_MSG( (flags & wxDL_NOW) == 0,
262 _T("wxDL_LAZY and wxDL_NOW are mutually exclusive.") );
263 shlFlags |= BIND_DEFERRED;
264 }
265 else if( flags & wxDL_NOW )
266 {
267 shlFlags |= BIND_IMMEDIATE;
268 }
269 m_handle = shl_load(libname.fn_str(), BIND_DEFERRED, 0);
270
271 #elif defined(__WINDOWS__)
272 m_handle = ::LoadLibrary(libname.c_str());
273 #else
274 #error "runtime shared lib support not implemented on this platform"
275 #endif
276
277 if ( m_handle == 0 )
278 {
279 wxString msg(_("Failed to load shared library '%s'"));
280 #if defined(HAVE_DLERROR) && !defined(__EMX__)
281
282 #if wxUSE_UNICODE
283 wxWCharBuffer buffer = wxConvLocal.cMB2WC( dlerror() );
284 const wxChar *err = buffer;
285 #else
286 const wxChar *err = dlerror();
287 #endif
288
289 if( err )
290 wxLogError( msg, err );
291 #else
292 wxLogSysError( msg, libname.c_str() );
293 #endif
294 }
295
296 return IsLoaded();
297 }
298
299 /* static */
300 void wxDynamicLibrary::Unload(wxDllType handle)
301 {
302 #if defined(__WXPM__) || defined(__EMX__)
303 DosFreeModule( handle );
304 #elif defined(HAVE_DLOPEN) || defined(__DARWIN__)
305 dlclose( handle );
306 #elif defined(HAVE_SHL_LOAD)
307 shl_unload( handle );
308 #elif defined(__WINDOWS__)
309 ::FreeLibrary( handle );
310 #elif defined(__WXMAC__) && !defined(__DARWIN__)
311 CloseConnection( (CFragConnectionID*) &handle );
312 #else
313 #error "runtime shared lib support not implemented"
314 #endif
315 }
316
317 void *wxDynamicLibrary::GetSymbol(const wxString &name, bool *success) const
318 {
319 wxCHECK_MSG( IsLoaded(), NULL,
320 _T("Can't load symbol from unloaded library") );
321
322 bool failed = false;
323 void *symbol = 0;
324
325 wxUnusedVar(symbol);
326 #if defined(__WXMAC__) && !defined(__DARWIN__)
327 Ptr symAddress;
328 CFragSymbolClass symClass;
329 Str255 symName;
330 #if TARGET_CARBON
331 c2pstrcpy( (StringPtr) symName, name.fn_str() );
332 #else
333 strcpy( (char *)symName, name.fn_str() );
334 c2pstr( (char *)symName );
335 #endif
336 if( FindSymbol( m_handle, symName, &symAddress, &symClass ) == noErr )
337 symbol = (void *)symAddress;
338
339 #elif defined(__WXPM__) || defined(__EMX__)
340 DosQueryProcAddr( m_handle, 1L, name.c_str(), (PFN*)symbol );
341
342 #elif defined(HAVE_DLOPEN) || defined(__DARWIN__)
343 symbol = dlsym( m_handle, name.fn_str() );
344
345 #elif defined(HAVE_SHL_LOAD)
346 // use local variable since shl_findsym modifies the handle argument
347 // to indicate where the symbol was found (GD)
348 wxDllType the_handle = m_handle;
349 if( shl_findsym( &the_handle, name.fn_str(), TYPE_UNDEFINED, &symbol ) != 0 )
350 symbol = 0;
351
352 #elif defined(__WINDOWS__)
353 #ifdef __WXWINCE__
354 symbol = (void*) ::GetProcAddress( m_handle, name );
355 #else
356 symbol = (void*) ::GetProcAddress( m_handle, name.mb_str() );
357 #endif
358
359 #else
360 #error "runtime shared lib support not implemented"
361 #endif
362
363 if ( !symbol )
364 {
365 #if defined(HAVE_DLERROR) && !defined(__EMX__)
366
367 #if wxUSE_UNICODE
368 wxWCharBuffer buffer = wxConvLocal.cMB2WC( dlerror() );
369 const wxChar *err = buffer;
370 #else
371 const wxChar *err = dlerror();
372 #endif
373
374 if( err )
375 {
376 wxLogError(wxT("%s"), err);
377 }
378 #else
379 failed = true;
380 wxLogSysError(_("Couldn't find symbol '%s' in a dynamic library"),
381 name.c_str());
382 #endif
383 }
384 if( success )
385 *success = !failed;
386
387 return symbol;
388 }
389
390
391 /*static*/
392 wxString
393 wxDynamicLibrary::CanonicalizeName(const wxString& name,
394 wxDynamicLibraryCategory
395 #ifdef __UNIX__
396 cat
397 #else // !__UNIX__
398 WXUNUSED(cat)
399 #endif // __UNIX__/!__UNIX__
400 )
401 {
402 wxString nameCanonic;
403
404 // under Unix the library names usually start with "lib" prefix, add it
405 #ifdef __UNIX__
406 switch ( cat )
407 {
408 default:
409 wxFAIL_MSG( _T("unknown wxDynamicLibraryCategory value") );
410 // fall through
411
412 case wxDL_MODULE:
413 // don't do anything for modules, their names are arbitrary
414 break;
415
416 case wxDL_LIBRARY:
417 // library names should start with "lib" under Unix
418 nameCanonic = _T("lib");
419 break;
420 }
421 #endif // __UNIX__
422
423 nameCanonic << name << GetDllExt();
424 return nameCanonic;
425 }
426
427 /*static*/
428 wxString wxDynamicLibrary::CanonicalizePluginName(const wxString& name,
429 wxPluginCategory cat)
430 {
431 wxString suffix;
432 if ( cat == wxDL_PLUGIN_GUI )
433 {
434 wxAppTraits *traits = wxAppConsole::GetInstance() ?
435 wxAppConsole::GetInstance()->GetTraits() : NULL;
436 wxASSERT_MSG( traits,
437 _("can't query for GUI plugins name in console applications") );
438 suffix = traits->GetToolkitInfo().shortName;
439 }
440 #if wxUSE_UNICODE
441 suffix << _T('u');
442 #endif
443 #ifdef __WXDEBUG__
444 suffix << _T('d');
445 #endif
446
447 if ( !suffix.empty() )
448 suffix = wxString(_T("_")) + suffix;
449
450 #define WXSTRINGIZE(x) #x
451 #ifdef __UNIX__
452 #if (wxMINOR_VERSION % 2) == 0
453 #define wxDLLVER(x,y,z) "-" WXSTRINGIZE(x) "." WXSTRINGIZE(y)
454 #else
455 #define wxDLLVER(x,y,z) "-" WXSTRINGIZE(x) "." WXSTRINGIZE(y) "." WXSTRINGIZE(z)
456 #endif
457 #else
458 #if (wxMINOR_VERSION % 2) == 0
459 #define wxDLLVER(x,y,z) WXSTRINGIZE(x) WXSTRINGIZE(y)
460 #else
461 #define wxDLLVER(x,y,z) WXSTRINGIZE(x) WXSTRINGIZE(y) WXSTRINGIZE(z)
462 #endif
463 #endif
464
465 suffix << wxString::FromAscii(wxDLLVER(wxMAJOR_VERSION, wxMINOR_VERSION,
466 wxRELEASE_NUMBER));
467 #undef wxDLLVER
468 #undef WXSTRINGIZE
469
470 #ifdef __WINDOWS__
471 // Add compiler identification:
472 #if defined(__GNUG__)
473 suffix << _T("_gcc");
474 #elif defined(__VISUALC__)
475 suffix << _T("_vc");
476 #elif defined(__WATCOMC__)
477 suffix << _T("_wat");
478 #elif defined(__BORLANDC__)
479 suffix << _T("_bcc");
480 #endif
481 #endif
482
483 return CanonicalizeName(name + suffix, wxDL_MODULE);
484 }
485
486 /*static*/
487 wxString wxDynamicLibrary::GetPluginsDirectory()
488 {
489 #ifdef __UNIX__
490 wxString format = wxGetInstallPrefix();
491 wxString dir;
492 format << wxFILE_SEP_PATH
493 << wxT("lib") << wxFILE_SEP_PATH
494 << wxT("wx") << wxFILE_SEP_PATH
495 #if (wxMINOR_VERSION % 2) == 0
496 << wxT("%i.%i");
497 dir.Printf(format.c_str(), wxMAJOR_VERSION, wxMINOR_VERSION);
498 #else
499 << wxT("%i.%i.%i");
500 dir.Printf(format.c_str(),
501 wxMAJOR_VERSION, wxMINOR_VERSION, wxRELEASE_NUMBER);
502 #endif
503 return dir;
504
505 #else // ! __UNIX__
506 return wxEmptyString;
507 #endif
508 }
509
510
511 #endif // wxUSE_DYNLIB_CLASS