]> git.saurik.com Git - wxWidgets.git/blame_incremental - src/common/dynlib.cpp
renamed project files for 3rd party libs from FooVC.dsp to foo.dsp
[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 license
10/////////////////////////////////////////////////////////////////////////////
11
12// ============================================================================
13// declarations
14// ============================================================================
15
16// ----------------------------------------------------------------------------
17// headers
18// ----------------------------------------------------------------------------
19
20#ifdef __GNUG__
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/private.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/tokenzr.h"
41
42// ----------------------------------------------------------------------------
43// conditional compilation
44// ----------------------------------------------------------------------------
45
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)
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
56 // otherwise. On True64-Unix RTLD_GLOBAL is not allowed and on VMS the
57 // second argument on dlopen is ignored.
58#ifdef __VMS
59# define wxDllOpen(lib) dlopen(lib.fn_str(), 0 )
60#elif defined( __osf__ )
61# define wxDllOpen(lib) dlopen(lib.fn_str(), RTLD_LAZY )
62#else
63# define wxDllOpen(lib) dlopen(lib.fn_str(), RTLD_LAZY | RTLD_GLOBAL)
64#endif
65#define wxDllGetSymbol(handle, name) dlsym(handle, name)
66# define wxDllClose dlclose
67#elif defined(HAVE_SHL_LOAD)
68# define wxDllOpen(lib) shl_load(lib.fn_str(), BIND_DEFERRED, 0)
69# define wxDllClose shl_unload
70
71 static inline void *wxDllGetSymbol(shl_t handle, const wxString& name)
72 {
73 void *sym;
74 if ( shl_findsym(&handle, name.mb_str(), TYPE_UNDEFINED, &sym) == 0 )
75 return sym;
76 else
77 return (void *)0;
78 }
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 */
86void *dlopen(const char *path, int mode /* mode is ignored */);
87void *dlsym(void *handle, const char *symbol);
88int dlclose(void *handle);
89const char *dlerror(void);
90
91# define wxDllOpen(lib) dlopen(lib.fn_str(), 0)
92# define wxDllGetSymbol(handle, name) dlsym(handle, name)
93# define wxDllClose dlclose
94#elif defined(__WINDOWS__)
95 // using LoadLibraryEx under Win32 to avoid name clash with LoadLibrary
96# ifdef __WIN32__
97#ifdef _UNICODE
98# define wxDllOpen(lib) ::LoadLibraryExW(lib, 0, 0)
99#else
100# define wxDllOpen(lib) ::LoadLibraryExA(lib, 0, 0)
101#endif
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
107#elif defined(__WXMAC__)
108# define wxDllClose(handle) CloseConnection(&handle)
109#else
110# error "Don't know how to load shared libraries on this platform."
111#endif // OS
112
113// ---------------------------------------------------------------------------
114// Global variables
115// ---------------------------------------------------------------------------
116
117wxLibraries wxTheLibraries;
118
119// ============================================================================
120// implementation
121// ============================================================================
122
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{
127 wxString fullname;
128 fullname << basename << wxDllLoader::GetDllExt();
129
130 return fullname;
131}
132
133// ---------------------------------------------------------------------------
134// wxLibrary (one instance per dynamic library)
135// ---------------------------------------------------------------------------
136
137wxLibrary::wxLibrary(wxDllType handle)
138{
139 typedef wxClassInfo *(*t_get_first)(void);
140 t_get_first get_first;
141
142 m_handle = handle;
143
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());
149}
150
151wxLibrary::~wxLibrary()
152{
153 if ( m_handle )
154 {
155 wxDllClose(m_handle);
156 }
157}
158
159wxObject *wxLibrary::CreateObject(const wxString& name)
160{
161 wxClassInfo *info = (wxClassInfo *)classTable.Get(name);
162
163 if (!info)
164 return NULL;
165
166 return info->CreateObject();
167}
168
169void wxLibrary::PrepareClasses(wxClassInfo *first)
170{
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);
177 info = (wxClassInfo *)info->GetNext();
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 }
190}
191
192void *wxLibrary::GetSymbol(const wxString& symbname)
193{
194 return wxDllLoader::GetSymbol(m_handle, symbname);
195}
196
197// ---------------------------------------------------------------------------
198// wxDllLoader
199// ---------------------------------------------------------------------------
200
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
219/* static */
220wxDllType
221wxDllLoader::GetProgramHandle(void)
222{
223#if defined( HAVE_DLOPEN ) && !defined(__EMX__)
224 // optain handle for main program
225 return dlopen(NULL, RTLD_NOW/*RTLD_LAZY*/);
226#elif defined (HAVE_SHL_LOAD)
227 // shl_findsymbol with NULL handle looks up in main program
228 return 0;
229#else
230 wxFAIL_MSG( wxT("This method is not implemented under Windows or OS/2"));
231 return 0;
232#endif
233}
234
235/* static */
236wxDllType
237wxDllLoader::LoadLibrary(const wxString & libname, bool *success)
238{
239 wxDllType handle;
240
241#if defined(__WXMAC__) && !defined(__UNIX__)
242 FSSpec myFSSpec ;
243 Ptr myMainAddr ;
244 Str255 myErrName ;
245
246 wxMacFilename2FSSpec( libname , &myFSSpec ) ;
247 if (GetDiskFragment( &myFSSpec , 0 , kCFragGoesToEOF , "\p" , kPrivateCFragCopy , &handle , &myMainAddr ,
248 myErrName ) != noErr )
249 {
250 p2cstr( myErrName ) ;
251 wxLogSysError( _("Failed to load shared library '%s' Error '%s'") , libname.c_str() , (char*)myErrName ) ;
252 handle = NULL ;
253 }
254#elif defined(__WXPM__) || defined(__EMX__)
255 char zError[256] = "";
256 wxDllOpen(zError, libname, handle);
257#else // !Mac
258 handle = wxDllOpen(libname);
259#endif // OS
260
261 if ( !handle )
262 {
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 }
290 }
291
292 if ( success )
293 {
294 *success = handle != 0;
295 }
296
297 return handle;
298}
299
300
301/* static */
302void
303wxDllLoader::UnloadLibrary(wxDllType handle)
304{
305 wxDllClose(handle);
306}
307
308/* static */
309void *
310wxDllLoader::GetSymbol(wxDllType dllHandle, const wxString &name)
311{
312 void *symbol = NULL; // return value
313
314#if defined(__WXMAC__) && !defined(__UNIX__)
315 Ptr symAddress ;
316 CFragSymbolClass symClass ;
317 Str255 symName ;
318
319#if TARGET_CARBON
320 c2pstrcpy( (StringPtr) symName , name ) ;
321#else
322 strcpy( (char *) symName , name ) ;
323 c2pstr( (char *) symName ) ;
324#endif
325
326 if ( FindSymbol( dllHandle , symName , &symAddress , &symClass ) == noErr )
327 symbol = (void *)symAddress ;
328#elif defined( __WXPM__ ) || defined(__EMX__)
329 wxDllGetSymbol(dllHandle, symbol);
330#else
331 // mb_str() is necessary in Unicode build
332 symbol = wxDllGetSymbol(dllHandle, name.mb_str());
333#endif
334
335 if ( !symbol )
336 {
337 wxLogSysError(_("Couldn't find symbol '%s' in a dynamic library"),
338 name.c_str());
339 }
340 return symbol;
341}
342
343// ---------------------------------------------------------------------------
344// wxLibraries (only one instance should normally exist)
345// ---------------------------------------------------------------------------
346
347wxLibraries::wxLibraries():m_loaded(wxKEY_STRING)
348{
349}
350
351wxLibraries::~wxLibraries()
352{
353 wxNode *node = m_loaded.First();
354
355 while (node) {
356 wxLibrary *lib = (wxLibrary *)node->Data();
357 delete lib;
358
359 node = node->Next();
360 }
361}
362
363wxLibrary *wxLibraries::LoadLibrary(const wxString& name)
364{
365 wxNode *node;
366 wxLibrary *lib;
367 wxClassInfo *old_sm_first;
368
369#if defined(__VISAGECPP__)
370 node = m_loaded.Find(name.GetData());
371 if (node != NULL)
372 return ((wxLibrary *)node->Data());
373#else // !OS/2
374 if ( (node = m_loaded.Find(name.GetData())) != NULL)
375 return ((wxLibrary *)node->Data());
376#endif
377 // If DLL shares data, this is necessary.
378 old_sm_first = wxClassInfo::sm_first;
379 wxClassInfo::sm_first = NULL;
380
381 wxString libname = ConstructLibraryName(name);
382
383/*
384 Unix automatically builds that library name, at least for dlopen()
385*/
386#if 0
387#if defined(__UNIX__)
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 )
392 libPath << wxT(':') << envLibPath;
393 wxStringTokenizer tokenizer(libPath, wxT(':'));
394 while ( tokenizer.HasMoreToken() )
395 {
396 wxString fullname(tokenizer.NextToken());
397
398 fullname << wxT('/') << libname;
399 if ( wxFileExists(fullname) )
400 {
401 libname = fullname;
402
403 // found the library
404 break;
405 }
406 }
407 //else: not found in the path, leave the name as is (secutiry risk?)
408
409#endif // __UNIX__
410#endif
411
412 bool success = FALSE;
413 wxDllType handle = wxDllLoader::LoadLibrary(libname, &success);
414 if(success)
415 {
416 lib = new wxLibrary(handle);
417 wxClassInfo::sm_first = old_sm_first;
418 m_loaded.Append(name.GetData(), lib);
419 }
420 else
421 lib = NULL;
422 return lib;
423}
424
425wxObject *wxLibraries::CreateObject(const wxString& path)
426{
427 wxNode *node = m_loaded.First();
428 wxObject *obj;
429
430 while (node) {
431 obj = ((wxLibrary *)node->Data())->CreateObject(path);
432 if (obj)
433 return obj;
434
435 node = node->Next();
436 }
437 return NULL;
438}
439
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
536#endif // wxUSE_DYNLIB_CLASS