]> git.saurik.com Git - wxWidgets.git/blame_incremental - src/common/dynlib.cpp
Warning fix and source cleaning.
[wxWidgets.git] / src / common / dynlib.cpp
... / ...
CommitLineData
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
70static char dl_last_error[1024];
71
72static
73void 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
95const char *dlerror()
96{
97 return dl_last_error;
98}
99
100void *dlopen(const char *path, int WXUNUSED(mode) /* mode is ignored */)
101{
102 NSObjectFileImage ofile;
103 NSModule handle = NULL;
104
105 int dyld_result = NSCreateObjectFileImageFromFile(path, &ofile);
106 if ( dyld_result != NSObjectFileImageSuccess )
107 {
108 handle = NULL;
109 }
110 else
111 {
112 handle = NSLinkModule
113 (
114 ofile,
115 path,
116 NSLINKMODULE_OPTION_BINDNOW |
117 NSLINKMODULE_OPTION_RETURN_ON_ERROR
118 );
119 }
120
121 if ( !handle )
122 TranslateError(path, dyld_result);
123
124 return handle;
125}
126
127int dlclose(void *handle)
128{
129 NSUnLinkModule( handle, NSUNLINKMODULE_OPTION_NONE);
130 return 0;
131}
132
133void *dlsym(void *handle, const char *symbol)
134{
135 // as on many other systems, C symbols have prepended underscores under
136 // Darwin but unlike the normal dlopen(), NSLookupSymbolInModule() is not
137 // aware of this
138 wxCharBuffer buf(strlen(symbol) + 1);
139 char *p = buf.data();
140 p[0] = '_';
141 strcpy(p + 1, symbol);
142
143 NSSymbol nsSymbol = NSLookupSymbolInModule( handle, p );
144 return nsSymbol ? NSAddressOfSymbol(nsSymbol) : NULL;
145}
146
147#endif // defined(__DARWIN__)
148
149
150// ---------------------------------------------------------------------------
151// wxDynamicLibrary
152// ---------------------------------------------------------------------------
153
154//FIXME: This class isn't really common at all, it should be moved into
155// platform dependent files.
156
157#if defined(__WINDOWS__) || defined(__WXPM__) || defined(__EMX__)
158 const wxChar *wxDynamicLibrary::ms_dllext = _T(".dll");
159#elif defined(__WXMAC__) && !defined(__DARWIN__)
160 const wxChar *wxDynamicLibrary::ms_dllext = _T("");
161#elif defined(__UNIX__)
162 #if defined(__HPUX__)
163 const wxChar *wxDynamicLibrary::ms_dllext = _T(".sl");
164 #elif defined(__DARWIN__)
165 const wxChar *wxDynamicLibrary::ms_dllext = _T(".bundle");
166 #else
167 const wxChar *wxDynamicLibrary::ms_dllext = _T(".so");
168 #endif
169#endif
170
171wxDllType wxDynamicLibrary::GetProgramHandle()
172{
173#if defined( HAVE_DLOPEN ) && !defined(__EMX__)
174 return dlopen(0, RTLD_LAZY);
175#elif defined (HAVE_SHL_LOAD)
176 return PROG_HANDLE;
177#else
178 wxFAIL_MSG( wxT("This method is not implemented under Windows or OS/2"));
179 return 0;
180#endif
181}
182
183bool wxDynamicLibrary::Load(wxString libname, int flags)
184{
185 wxASSERT_MSG(m_handle == 0, _T("Library already loaded."));
186
187 // add the proper extension for the DLL ourselves unless told not to
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 = ::LoadLibrary(libname.c_str());
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/* static */
310void wxDynamicLibrary::Unload(wxDllType handle)
311{
312#if defined(__WXPM__) || defined(__EMX__)
313 DosFreeModule( handle );
314#elif defined(HAVE_DLOPEN) || defined(__DARWIN__)
315 dlclose( handle );
316#elif defined(HAVE_SHL_LOAD)
317 shl_unload( handle );
318#elif defined(__WINDOWS__)
319 ::FreeLibrary( 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
327void *wxDynamicLibrary::DoGetSymbol(const wxString &name, bool *success) const
328{
329 wxCHECK_MSG( IsLoaded(), NULL,
330 _T("Can't load symbol from unloaded library") );
331
332 void *symbol = 0;
333
334 wxUnusedVar(symbol);
335#if defined(__WXMAC__) && !defined(__DARWIN__)
336 Ptr symAddress;
337 CFragSymbolClass symClass;
338 Str255 symName;
339#if TARGET_CARBON
340 c2pstrcpy( (StringPtr) symName, name.fn_str() );
341#else
342 strcpy( (char *)symName, name.fn_str() );
343 c2pstr( (char *)symName );
344#endif
345 if( FindSymbol( m_handle, symName, &symAddress, &symClass ) == noErr )
346 symbol = (void *)symAddress;
347
348#elif defined(__WXPM__) || defined(__EMX__)
349 DosQueryProcAddr( m_handle, 1L, name.c_str(), (PFN*)symbol );
350
351#elif defined(HAVE_DLOPEN) || defined(__DARWIN__)
352 symbol = dlsym( m_handle, name.fn_str() );
353
354#elif defined(HAVE_SHL_LOAD)
355 // use local variable since shl_findsym modifies the handle argument
356 // to indicate where the symbol was found (GD)
357 wxDllType the_handle = m_handle;
358 if( shl_findsym( &the_handle, name.fn_str(), TYPE_UNDEFINED, &symbol ) != 0 )
359 symbol = 0;
360
361#elif defined(__WINDOWS__)
362#ifdef __WXWINCE__
363 symbol = (void*) ::GetProcAddress( m_handle, name );
364#else
365 symbol = (void*) ::GetProcAddress( m_handle, name.mb_str() );
366#endif
367
368#else
369#error "runtime shared lib support not implemented"
370#endif
371
372 if ( success )
373 *success = symbol != NULL;
374
375 return symbol;
376}
377
378void *wxDynamicLibrary::GetSymbol(const wxString& name, bool *success) const
379{
380 void *symbol = DoGetSymbol(name, success);
381 if ( !symbol )
382 {
383#if defined(HAVE_DLERROR) && !defined(__EMX__)
384
385#if wxUSE_UNICODE
386 wxWCharBuffer buffer = wxConvLocal.cMB2WC( dlerror() );
387 const wxChar *err = buffer;
388#else
389 const wxChar *err = dlerror();
390#endif
391
392 if( err )
393 {
394 wxLogError(wxT("%s"), err);
395 }
396#else
397 wxLogSysError(_("Couldn't find symbol '%s' in a dynamic library"),
398 name.c_str());
399#endif
400 }
401
402 return symbol;
403}
404
405/*static*/
406wxString
407wxDynamicLibrary::CanonicalizeName(const wxString& name,
408 wxDynamicLibraryCategory
409#ifdef __UNIX__
410 cat
411#else // !__UNIX__
412 WXUNUSED(cat)
413#endif // __UNIX__/!__UNIX__
414 )
415{
416 wxString nameCanonic;
417
418 // under Unix the library names usually start with "lib" prefix, add it
419#ifdef __UNIX__
420 switch ( cat )
421 {
422 default:
423 wxFAIL_MSG( _T("unknown wxDynamicLibraryCategory value") );
424 // fall through
425
426 case wxDL_MODULE:
427 // don't do anything for modules, their names are arbitrary
428 break;
429
430 case wxDL_LIBRARY:
431 // library names should start with "lib" under Unix
432 nameCanonic = _T("lib");
433 break;
434 }
435#endif // __UNIX__
436
437 nameCanonic << name << GetDllExt();
438 return nameCanonic;
439}
440
441/*static*/
442wxString wxDynamicLibrary::CanonicalizePluginName(const wxString& name,
443 wxPluginCategory cat)
444{
445 wxString suffix;
446 if ( cat == wxDL_PLUGIN_GUI )
447 {
448 wxAppTraits *traits = wxAppConsole::GetInstance() ?
449 wxAppConsole::GetInstance()->GetTraits() : NULL;
450 wxASSERT_MSG( traits,
451 _("can't query for GUI plugins name in console applications") );
452 suffix = traits->GetToolkitInfo().shortName;
453 }
454#if wxUSE_UNICODE
455 suffix << _T('u');
456#endif
457#ifdef __WXDEBUG__
458 suffix << _T('d');
459#endif
460
461 if ( !suffix.empty() )
462 suffix = wxString(_T("_")) + suffix;
463
464#define WXSTRINGIZE(x) #x
465#ifdef __UNIX__
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#else
472 #if (wxMINOR_VERSION % 2) == 0
473 #define wxDLLVER(x,y,z) WXSTRINGIZE(x) WXSTRINGIZE(y)
474 #else
475 #define wxDLLVER(x,y,z) WXSTRINGIZE(x) WXSTRINGIZE(y) WXSTRINGIZE(z)
476 #endif
477#endif
478
479 suffix << wxString::FromAscii(wxDLLVER(wxMAJOR_VERSION, wxMINOR_VERSION,
480 wxRELEASE_NUMBER));
481#undef wxDLLVER
482#undef WXSTRINGIZE
483
484#ifdef __WINDOWS__
485 // Add compiler identification:
486 #if defined(__GNUG__)
487 suffix << _T("_gcc");
488 #elif defined(__VISUALC__)
489 suffix << _T("_vc");
490 #elif defined(__WATCOMC__)
491 suffix << _T("_wat");
492 #elif defined(__BORLANDC__)
493 suffix << _T("_bcc");
494 #endif
495#endif
496
497 return CanonicalizeName(name + suffix, wxDL_MODULE);
498}
499
500/*static*/
501wxString wxDynamicLibrary::GetPluginsDirectory()
502{
503#ifdef __UNIX__
504 wxString format = wxGetInstallPrefix();
505 wxString dir;
506 format << wxFILE_SEP_PATH
507 << wxT("lib") << wxFILE_SEP_PATH
508 << wxT("wx") << wxFILE_SEP_PATH
509#if (wxMINOR_VERSION % 2) == 0
510 << wxT("%i.%i");
511 dir.Printf(format.c_str(), wxMAJOR_VERSION, wxMINOR_VERSION);
512#else
513 << wxT("%i.%i.%i");
514 dir.Printf(format.c_str(),
515 wxMAJOR_VERSION, wxMINOR_VERSION, wxRELEASE_NUMBER);
516#endif
517 return dir;
518
519#else // ! __UNIX__
520 return wxEmptyString;
521#endif
522}
523
524
525#endif // wxUSE_DYNLIB_CLASS