]> git.saurik.com Git - wxWidgets.git/blame - src/common/dynlib.cpp
suppress compilation warning
[wxWidgets.git] / src / common / dynlib.cpp
CommitLineData
7a4b9130
GL
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
7b0bfbb2
VZ
12// ============================================================================
13// declarations
14// ============================================================================
15
16// ----------------------------------------------------------------------------
17// headers
18// ----------------------------------------------------------------------------
19
7a4b9130 20#ifdef __GNUG__
a585ca5c 21# pragma implementation "dynlib.h"
7a4b9130
GL
22#endif
23
0c32066b
JS
24#include "wx/wxprec.h"
25
2df7be7f
RR
26#ifdef __BORLANDC__
27 #pragma hdrstop
28#endif
f6bcfd97 29
8a0d4cf6
VZ
30#if wxUSE_DYNLIB_CLASS
31
f6bcfd97
BP
32#if defined(__WINDOWS__)
33 #include "wx/msw/private.h"
34#endif
35
7b0bfbb2
VZ
36#include "wx/dynlib.h"
37#include "wx/filefn.h"
38#include "wx/intl.h"
39#include "wx/log.h"
8a0d4cf6 40#include "wx/tokenzr.h"
7b0bfbb2
VZ
41
42// ----------------------------------------------------------------------------
43// conditional compilation
44// ----------------------------------------------------------------------------
45
1a787c5d
SN
46#if defined(__WXPM__) || defined(__EMX__)
47# define INCL_DOS
48# include <os2.h>
49# define wxDllOpen(error, lib, handle) DosLoadModule(error, sizeof(error), lib, &handle)
50# define wxDllGetSymbol(handle, modaddr) DosQueryProcAddr(handle, 1L, NULL, (PFN*)modaddr)
51# define wxDllClose(handle) DosFreeModule(handle)
52#elif defined(HAVE_DLOPEN)
237c5c02
VZ
53 // note about dlopen() flags: we use RTLD_NOW to have more Windows-like
54 // behaviour (Win won't let you load a library with missing symbols) and
55 // RTLD_GLOBAL because it is needed sometimes and probably doesn't hurt
343a06a5
JJ
56 // otherwise. On True64-Unix RTLD_GLOBAL is not allowed and on VMS the
57 // second argument on dlopen is ignored.
99d96a2b
JJ
58#ifdef __VMS
59# define wxDllOpen(lib) dlopen(lib.fn_str(), 0 )
343a06a5
JJ
60#elif defined( __osf__ )
61# define wxDllOpen(lib) dlopen(lib.fn_str(), RTLD_LAZY )
99d96a2b
JJ
62#else
63# define wxDllOpen(lib) dlopen(lib.fn_str(), RTLD_LAZY | RTLD_GLOBAL)
64#endif
65#define wxDllGetSymbol(handle, name) dlsym(handle, name)
a585ca5c 66# define wxDllClose dlclose
8a0d4cf6 67#elif defined(HAVE_SHL_LOAD)
a585ca5c 68# define wxDllOpen(lib) shl_load(lib.fn_str(), BIND_DEFERRED, 0)
237c5c02 69# define wxDllClose shl_unload
846e1424 70
50920146 71 static inline void *wxDllGetSymbol(shl_t handle, const wxString& name)
7b0bfbb2
VZ
72 {
73 void *sym;
50920146 74 if ( shl_findsym(&handle, name.mb_str(), TYPE_UNDEFINED, &sym) == 0 )
7b0bfbb2
VZ
75 return sym;
76 else
77 return (void *)0;
78 }
f11bdd03
GD
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 */
4c27c3c6
GD
86void *dlopen(const char *path, int mode /* mode is ignored */);
87void *dlsym(void *handle, const char *symbol);
03e11df5 88int dlclose(void *handle);
4c27c3c6 89const char *dlerror(void);
03e11df5
GD
90
91# define wxDllOpen(lib) dlopen(lib.fn_str(), 0)
92# define wxDllGetSymbol(handle, name) dlsym(handle, name)
93# define wxDllClose dlclose
7b0bfbb2 94#elif defined(__WINDOWS__)
90022ddc 95 // using LoadLibraryEx under Win32 to avoid name clash with LoadLibrary
a585ca5c 96# ifdef __WIN32__
f6bcfd97
BP
97#ifdef _UNICODE
98# define wxDllOpen(lib) ::LoadLibraryExW(lib, 0, 0)
99#else
100# define wxDllOpen(lib) ::LoadLibraryExA(lib, 0, 0)
101#endif
a585ca5c
KB
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
763ca781
SC
107#elif defined(__WXMAC__)
108# define wxDllClose(handle) CloseConnection(&handle)
7b0bfbb2 109#else
a585ca5c 110# error "Don't know how to load shared libraries on this platform."
7b0bfbb2 111#endif // OS
7a4b9130
GL
112
113// ---------------------------------------------------------------------------
7b0bfbb2 114// Global variables
7a4b9130
GL
115// ---------------------------------------------------------------------------
116
7b0bfbb2 117wxLibraries wxTheLibraries;
7a4b9130 118
f6bcfd97
BP
119// ============================================================================
120// implementation
121// ============================================================================
123a7fdd 122
7b0bfbb2
VZ
123// construct the full name from the base shared object name: adds a .dll
124// suffix under Windows or .so under Unix
125static wxString ConstructLibraryName(const wxString& basename)
126{
f6bcfd97
BP
127 wxString fullname;
128 fullname << basename << wxDllLoader::GetDllExt();
27529614 129
7b0bfbb2
VZ
130 return fullname;
131}
7a4b9130 132
7a4b9130 133// ---------------------------------------------------------------------------
7b0bfbb2 134// wxLibrary (one instance per dynamic library)
7a4b9130
GL
135// ---------------------------------------------------------------------------
136
7b0bfbb2 137wxLibrary::wxLibrary(wxDllType handle)
7a4b9130 138{
7b0bfbb2
VZ
139 typedef wxClassInfo *(*t_get_first)(void);
140 t_get_first get_first;
7a4b9130 141
7b0bfbb2 142 m_handle = handle;
7a4b9130 143
7b0bfbb2
VZ
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());
7a4b9130
GL
149}
150
151wxLibrary::~wxLibrary()
152{
7b0bfbb2
VZ
153 if ( m_handle )
154 {
155 wxDllClose(m_handle);
156 }
7a4b9130
GL
157}
158
159wxObject *wxLibrary::CreateObject(const wxString& name)
160{
7b0bfbb2 161 wxClassInfo *info = (wxClassInfo *)classTable.Get(name);
f4a8c29f 162
7b0bfbb2
VZ
163 if (!info)
164 return NULL;
f4a8c29f 165
7b0bfbb2 166 return info->CreateObject();
f4a8c29f
GL
167}
168
856d2e52 169void wxLibrary::PrepareClasses(wxClassInfo *first)
f4a8c29f 170{
7b0bfbb2
VZ
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);
6057972b 177 info = (wxClassInfo *)info->GetNext();
7b0bfbb2
VZ
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 }
7a4b9130
GL
190}
191
192void *wxLibrary::GetSymbol(const wxString& symbname)
193{
a585ca5c
KB
194 return wxDllLoader::GetSymbol(m_handle, symbname);
195}
7b0bfbb2 196
a585ca5c
KB
197// ---------------------------------------------------------------------------
198// wxDllLoader
199// ---------------------------------------------------------------------------
7b0bfbb2 200
f6bcfd97
BP
201/* static */
202wxString wxDllLoader::GetDllExt()
203{
204 wxString ext;
205
206#if defined(__WINDOWS__) || defined(__WXPM__) || defined(__EMX__)
207 ext = _T(".dll");
208#elif defined(__UNIX__)
209# if defined(__HPUX__)
210 ext = _T(".sl");
211# else //__HPUX__
212 ext = _T(".so");
213# endif //__HPUX__
214#endif
215
216 return ext;
217}
218
0868079c
KB
219/* static */
220wxDllType
221wxDllLoader::GetProgramHandle(void)
222{
1a787c5d 223#if defined( HAVE_DLOPEN ) && !defined(__EMX__)
7742efff 224 // optain handle for main program
d236a959 225 return dlopen(NULL, RTLD_NOW/*RTLD_LAZY*/);
7742efff
KB
226#elif defined (HAVE_SHL_LOAD)
227 // shl_findsymbol with NULL handle looks up in main program
d236a959 228 return 0;
0868079c 229#else
58c837a4 230 wxFAIL_MSG( wxT("This method is not implemented under Windows or OS/2"));
7742efff 231 return 0;
7cc98b3e 232#endif
0868079c
KB
233}
234
a585ca5c
KB
235/* static */
236wxDllType
7cc98b3e 237wxDllLoader::LoadLibrary(const wxString & libname, bool *success)
a585ca5c 238{
7cc98b3e 239 wxDllType handle;
7b0bfbb2 240
03e11df5 241#if defined(__WXMAC__) && !defined(__UNIX__)
7cc98b3e 242 FSSpec myFSSpec ;
f6bcfd97
BP
243 Ptr myMainAddr ;
244 Str255 myErrName ;
7cc98b3e 245
763ca781 246 wxMacFilename2FSSpec( libname , &myFSSpec ) ;
7cc98b3e
VZ
247 if (GetDiskFragment( &myFSSpec , 0 , kCFragGoesToEOF , "\p" , kPrivateCFragCopy , &handle , &myMainAddr ,
248 myErrName ) != noErr )
249 {
250 p2cstr( myErrName ) ;
763ca781
SC
251 wxLogSysError( _("Failed to load shared library '%s' Error '%s'") , libname.c_str() , (char*)myErrName ) ;
252 handle = NULL ;
7cc98b3e 253 }
1a787c5d 254#elif defined(__WXPM__) || defined(__EMX__)
f6bcfd97 255 char zError[256] = "";
c2ff79b1 256 wxDllOpen(zError, libname, handle);
a585ca5c 257#else // !Mac
93d2bf44 258 handle = wxDllOpen(libname);
a585ca5c
KB
259#endif // OS
260
7cc98b3e
VZ
261 if ( !handle )
262 {
f6bcfd97
BP
263 wxString msg(_("Failed to load shared library '%s'"));
264
265#ifdef HAVE_DLERROR
266 const char *errmsg = dlerror();
267 if ( errmsg )
268 {
269 // the error string format is "libname: ...", but we already have
270 // libname, so cut it off
271 const char *p = strchr(errmsg, ':');
272 if ( p )
273 {
274 if ( *++p == ' ' )
275 p++;
276 }
277 else
278 {
279 p = errmsg;
280 }
281
282 msg += _T(" (%s)");
283 wxLogError(msg, libname.c_str(), p);
284 }
285 else
286#endif // HAVE_DLERROR
287 {
288 wxLogSysError(msg, libname.c_str());
289 }
7cc98b3e
VZ
290 }
291
292 if ( success )
293 {
294 *success = handle != 0;
295 }
296
297 return handle;
a585ca5c
KB
298}
299
752c7d6b
KB
300
301/* static */
302void
303wxDllLoader::UnloadLibrary(wxDllType handle)
304{
305 wxDllClose(handle);
306}
307
a585ca5c
KB
308/* static */
309void *
310wxDllLoader::GetSymbol(wxDllType dllHandle, const wxString &name)
311{
7cc98b3e 312 void *symbol = NULL; // return value
a585ca5c 313
03e11df5 314#if defined(__WXMAC__) && !defined(__UNIX__)
7cc98b3e
VZ
315 Ptr symAddress ;
316 CFragSymbolClass symClass ;
f6bcfd97 317 Str255 symName ;
7cc98b3e 318
03e11df5
GD
319#if TARGET_CARBON
320 c2pstrcpy( (StringPtr) symName , name ) ;
321#else
322 strcpy( (char *) symName , name ) ;
323 c2pstr( (char *) symName ) ;
324#endif
7cc98b3e
VZ
325
326 if ( FindSymbol( dllHandle , symName , &symAddress , &symClass ) == noErr )
327 symbol = (void *)symAddress ;
1a787c5d 328#elif defined( __WXPM__ ) || defined(__EMX__)
c2ff79b1 329 wxDllGetSymbol(dllHandle, symbol);
7b0bfbb2 330#else
f6bcfd97 331 // mb_str() is necessary in Unicode build
4c27c3c6 332 symbol = wxDllGetSymbol(dllHandle, name.mb_str());
123a7fdd 333#endif
7b0bfbb2
VZ
334
335 if ( !symbol )
336 {
7cc98b3e
VZ
337 wxLogSysError(_("Couldn't find symbol '%s' in a dynamic library"),
338 name.c_str());
7b0bfbb2 339 }
7b0bfbb2 340 return symbol;
7a4b9130
GL
341}
342
343// ---------------------------------------------------------------------------
344// wxLibraries (only one instance should normally exist)
345// ---------------------------------------------------------------------------
346
65fd5cb0 347wxLibraries::wxLibraries():m_loaded(wxKEY_STRING)
7a4b9130
GL
348{
349}
350
351wxLibraries::~wxLibraries()
352{
7b0bfbb2 353 wxNode *node = m_loaded.First();
7a4b9130 354
7b0bfbb2
VZ
355 while (node) {
356 wxLibrary *lib = (wxLibrary *)node->Data();
357 delete lib;
7a4b9130 358
7b0bfbb2
VZ
359 node = node->Next();
360 }
7a4b9130
GL
361}
362
363wxLibrary *wxLibraries::LoadLibrary(const wxString& name)
364{
7b0bfbb2
VZ
365 wxNode *node;
366 wxLibrary *lib;
367 wxClassInfo *old_sm_first;
7a4b9130 368
c2ff79b1
DW
369#if defined(__VISAGECPP__)
370 node = m_loaded.Find(name.GetData());
371 if (node != NULL)
372 return ((wxLibrary *)node->Data());
373#else // !OS/2
33ac7e6f 374 if ( (node = m_loaded.Find(name.GetData())) != NULL)
7b0bfbb2 375 return ((wxLibrary *)node->Data());
c2ff79b1 376#endif
7b0bfbb2
VZ
377 // If DLL shares data, this is necessary.
378 old_sm_first = wxClassInfo::sm_first;
379 wxClassInfo::sm_first = NULL;
380
7cc98b3e 381 wxString libname = ConstructLibraryName(name);
856d2e52 382
a585ca5c
KB
383/*
384 Unix automatically builds that library name, at least for dlopen()
385*/
386#if 0
9e4b2f1c 387#if defined(__UNIX__)
8a0d4cf6
VZ
388 // found the first file in LD_LIBRARY_PATH with this name
389 wxString libPath("/lib:/usr/lib"); // system path first
390 const char *envLibPath = getenv("LD_LIBRARY_PATH");
391 if ( envLibPath )
58c837a4 392 libPath << wxT(':') << envLibPath;
223d09f6 393 wxStringTokenizer tokenizer(libPath, wxT(':'));
8a0d4cf6
VZ
394 while ( tokenizer.HasMoreToken() )
395 {
396 wxString fullname(tokenizer.NextToken());
397
58c837a4 398 fullname << wxT('/') << libname;
8a0d4cf6
VZ
399 if ( wxFileExists(fullname) )
400 {
7cc98b3e 401 libname = fullname;
8a0d4cf6
VZ
402
403 // found the library
404 break;
405 }
406 }
407 //else: not found in the path, leave the name as is (secutiry risk?)
408
7b0bfbb2 409#endif // __UNIX__
a585ca5c 410#endif
7a4b9130 411
4dc2c3bb 412 bool success = FALSE;
7cc98b3e 413 wxDllType handle = wxDllLoader::LoadLibrary(libname, &success);
a585ca5c 414 if(success)
7b0bfbb2 415 {
a585ca5c
KB
416 lib = new wxLibrary(handle);
417 wxClassInfo::sm_first = old_sm_first;
418 m_loaded.Append(name.GetData(), lib);
7b0bfbb2 419 }
a585ca5c
KB
420 else
421 lib = NULL;
7b0bfbb2 422 return lib;
7a4b9130
GL
423}
424
425wxObject *wxLibraries::CreateObject(const wxString& path)
426{
7b0bfbb2
VZ
427 wxNode *node = m_loaded.First();
428 wxObject *obj;
7a4b9130 429
7b0bfbb2
VZ
430 while (node) {
431 obj = ((wxLibrary *)node->Data())->CreateObject(path);
432 if (obj)
433 return obj;
7a4b9130 434
7b0bfbb2
VZ
435 node = node->Next();
436 }
437 return NULL;
7a4b9130 438}
8a0d4cf6 439
f11bdd03
GD
440#ifdef __DARWIN__
441// ---------------------------------------------------------------------------
442// For Darwin/Mac OS X
443// supply the sun style dlopen functions in terms of Darwin NS*
444// ---------------------------------------------------------------------------
445
446extern "C" {
447#import <mach-o/dyld.h>
448};
449
450enum dyldErrorSource
451{
452 OFImage,
453};
454
455static char dl_last_error[1024];
456
457static
458void TranslateError(const char *path, enum dyldErrorSource type, int number)
459{
460 unsigned int index;
461 static char *OFIErrorStrings[] =
462 {
463 "%s(%d): Object Image Load Failure\n",
464 "%s(%d): Object Image Load Success\n",
465 "%s(%d): Not an recognisable object file\n",
466 "%s(%d): No valid architecture\n",
467 "%s(%d): Object image has an invalid format\n",
468 "%s(%d): Invalid access (permissions?)\n",
469 "%s(%d): Unknown error code from NSCreateObjectFileImageFromFile\n",
470 };
471#define NUM_OFI_ERRORS (sizeof(OFIErrorStrings) / sizeof(OFIErrorStrings[0]))
472
473 switch (type)
474 {
475 case OFImage:
476 index = number;
477 if (index > NUM_OFI_ERRORS - 1) {
478 index = NUM_OFI_ERRORS - 1;
479 }
480 sprintf(dl_last_error, OFIErrorStrings[index], path, number);
481 break;
482
483 default:
484 sprintf(dl_last_error, "%s(%d): Totally unknown error type %d\n",
485 path, number, type);
486 break;
487 }
488}
489
490const char *dlerror()
491{
492 return dl_last_error;
493}
494
495void *dlopen(const char *path, int mode /* mode is ignored */)
496{
497 int dyld_result;
498 NSObjectFileImage ofile;
499 NSModule handle = NULL;
500
501 dyld_result = NSCreateObjectFileImageFromFile(path, &ofile);
502 if (dyld_result != NSObjectFileImageSuccess)
503 {
504 TranslateError(path, OFImage, dyld_result);
505 }
506 else
507 {
508 // NSLinkModule will cause the run to abort on any link error's
509 // not very friendly but the error recovery functionality is limited.
510 handle = NSLinkModule(ofile, path, TRUE);
511 }
512
513 return handle;
514}
515
516int dlclose(void *handle) /* stub only */
517{
518 return 0;
519}
520
521void *dlsym(void *handle, const char *symbol)
522{
523 void *addr;
524
525 if (NSIsSymbolNameDefined(symbol)) {
526 addr = NSAddressOfSymbol(NSLookupAndBindSymbol(symbol));
527 }
528 else {
529 addr = NULL;
530 }
531 return addr;
532}
533
534#endif // __DARWIN__
535
8a0d4cf6 536#endif // wxUSE_DYNLIB_CLASS