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