1 /////////////////////////////////////////////////////////////////////////////
2 // Name: unix/dlunix.cpp
3 // Purpose: Unix-specific part of wxDynamicLibrary and related classes
4 // Author: Vadim Zeitlin
6 // Created: 2005-01-16 (extracted from common/dynlib.cpp)
8 // Copyright: (c) 2000-2005 Vadim Zeitlin <vadim@wxwindows.org>
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
12 // ============================================================================
14 // ============================================================================
16 // ----------------------------------------------------------------------------
18 // ----------------------------------------------------------------------------
20 #include "wx/wxprec.h"
26 #if wxUSE_DYNLIB_CLASS
28 #include "wx/dynlib.h"
36 // only Mac OS X 10.3+ has dlfcn.h, and it is simpler to always provide our own
37 // wrappers using the native functions instead of doing checks for OS version
42 // if some flags are not supported, just ignore them
56 #if defined(HAVE_DLOPEN) || defined(__DARWIN__)
57 #define USE_POSIX_DL_FUNCS
58 #elif !defined(HAVE_SHL_LOAD)
59 #error "Don't know how to load dynamic libraries on this platform!"
62 // ----------------------------------------------------------------------------
64 // ----------------------------------------------------------------------------
66 // standard shared libraries extensions for different Unix versions
68 const wxChar
*wxDynamicLibrary::ms_dllext
= _T(".sl");
69 #elif defined(__DARWIN__)
70 const wxChar
*wxDynamicLibrary::ms_dllext
= _T(".bundle");
72 const wxChar
*wxDynamicLibrary::ms_dllext
= _T(".so");
75 // ============================================================================
76 // wxDynamicLibrary implementation
77 // ============================================================================
79 // ----------------------------------------------------------------------------
80 // dlxxx() emulation for Darwin
81 // ----------------------------------------------------------------------------
83 #if defined(__DARWIN__)
84 // ---------------------------------------------------------------------------
85 // For Darwin/Mac OS X
86 // supply the sun style dlopen functions in terms of Darwin NS*
87 // ---------------------------------------------------------------------------
90 * The dlopen port is a port from dl_next.xs by Anno Siegel.
91 * dl_next.xs is itself a port from dl_dlopen.xs by Paul Marquess.
92 * The method used here is just to supply the sun style dlopen etc.
93 * functions in terms of Darwin NS*.
97 #include <mach-o/dyld.h>
99 static char dl_last_error
[1024];
102 void TranslateError(const char *path
, int number
)
105 static char *OFIErrorStrings
[] =
107 "%s(%d): Object Image Load Failure\n",
108 "%s(%d): Object Image Load Success\n",
109 "%s(%d): Not an recognisable object file\n",
110 "%s(%d): No valid architecture\n",
111 "%s(%d): Object image has an invalid format\n",
112 "%s(%d): Invalid access (permissions?)\n",
113 "%s(%d): Unknown error code from NSCreateObjectFileImageFromFile\n",
115 #define NUM_OFI_ERRORS (sizeof(OFIErrorStrings) / sizeof(OFIErrorStrings[0]))
118 if (index
> NUM_OFI_ERRORS
- 1) {
119 index
= NUM_OFI_ERRORS
- 1;
121 sprintf(dl_last_error
, OFIErrorStrings
[index
], path
, number
);
124 const char *dlerror()
126 return dl_last_error
;
129 void *dlopen(const char *path
, int WXUNUSED(mode
) /* mode is ignored */)
131 NSObjectFileImage ofile
;
132 NSModule handle
= NULL
;
134 int dyld_result
= NSCreateObjectFileImageFromFile(path
, &ofile
);
135 if ( dyld_result
!= NSObjectFileImageSuccess
)
141 handle
= NSLinkModule
145 NSLINKMODULE_OPTION_BINDNOW
|
146 NSLINKMODULE_OPTION_RETURN_ON_ERROR
151 TranslateError(path
, dyld_result
);
156 int dlclose(void *handle
)
158 NSUnLinkModule((NSModule
)handle
, NSUNLINKMODULE_OPTION_NONE
);
162 void *dlsym(void *handle
, const char *symbol
)
164 // as on many other systems, C symbols have prepended underscores under
165 // Darwin but unlike the normal dlopen(), NSLookupSymbolInModule() is not
167 wxCharBuffer
buf(strlen(symbol
) + 1);
168 char *p
= buf
.data();
170 strcpy(p
+ 1, symbol
);
172 NSSymbol nsSymbol
= NSLookupSymbolInModule((NSModule
)handle
, p
);
173 return nsSymbol
? NSAddressOfSymbol(nsSymbol
) : NULL
;
176 #endif // defined(__DARWIN__)
178 // ----------------------------------------------------------------------------
179 // loading/unloading DLLs
180 // ----------------------------------------------------------------------------
182 wxDllType
wxDynamicLibrary::GetProgramHandle()
184 #ifdef USE_POSIX_DL_FUNCS
185 return dlopen(0, RTLD_LAZY
);
192 wxDllType
wxDynamicLibrary::RawLoad(const wxString
& libname
, int flags
)
194 wxASSERT_MSG( !(flags
& wxDL_NOW
) || !(flags
& wxDL_LAZY
),
195 _T("wxDL_LAZY and wxDL_NOW are mutually exclusive.") );
197 #ifdef USE_POSIX_DL_FUNCS
198 // we need to use either RTLD_NOW or RTLD_LAZY because if we call dlopen()
199 // with flags == 0 recent versions of glibc just fail the call, so use
200 // RTLD_NOW even if wxDL_NOW was not specified
201 int rtldFlags
= flags
& wxDL_LAZY
? RTLD_LAZY
: RTLD_NOW
;
203 if ( flags
& wxDL_GLOBAL
)
204 rtldFlags
|= RTLD_GLOBAL
;
206 return dlopen(libname
.fn_str(), rtldFlags
);
207 #else // !USE_POSIX_DL_FUNCS
210 if ( flags
& wxDL_LAZY
)
212 shlFlags
|= BIND_DEFERRED
;
214 else if ( flags
& wxDL_NOW
)
216 shlFlags
|= BIND_IMMEDIATE
;
219 return shl_load(libname
.fn_str(), shlFlags
, 0);
220 #endif // USE_POSIX_DL_FUNCS/!USE_POSIX_DL_FUNCS
224 void wxDynamicLibrary::Unload(wxDllType handle
)
226 #ifdef wxHAVE_DYNLIB_ERROR
230 #ifdef USE_POSIX_DL_FUNCS
232 #else // !USE_POSIX_DL_FUNCS
234 #endif // USE_POSIX_DL_FUNCS/!USE_POSIX_DL_FUNCS
236 #if defined(USE_POSIX_DL_FUNCS) && defined(wxHAVE_DYNLIB_ERROR)
243 void *wxDynamicLibrary::RawGetSymbol(wxDllType handle
, const wxString
& name
)
247 #ifdef USE_POSIX_DL_FUNCS
248 symbol
= dlsym(handle
, name
.fn_str());
249 #else // !USE_POSIX_DL_FUNCS
250 // note that shl_findsym modifies the handle argument to indicate where the
251 // symbol was found, but it's ok to modify the local handle copy here
252 if ( shl_findsym(&handle
, name
.fn_str(), TYPE_UNDEFINED
, &symbol
) != 0 )
254 #endif // USE_POSIX_DL_FUNCS/!USE_POSIX_DL_FUNCS
259 // ----------------------------------------------------------------------------
261 // ----------------------------------------------------------------------------
263 #ifdef wxHAVE_DYNLIB_ERROR
266 void wxDynamicLibrary::Error()
269 wxWCharBuffer buffer
= wxConvLocal
.cMB2WC( dlerror() );
270 const wxChar
*err
= buffer
;
272 const wxChar
*err
= dlerror();
275 wxLogError(wxT("%s"), err
? err
: _("Unknown dynamic library error"));
278 #endif // wxHAVE_DYNLIB_ERROR
280 // ----------------------------------------------------------------------------
281 // listing loaded modules
282 // ----------------------------------------------------------------------------
284 // wxDynamicLibraryDetails declares this class as its friend, so put the code
285 // initializing new details objects here
286 class wxDynamicLibraryDetailsCreator
289 // create a new wxDynamicLibraryDetails from the given data
290 static wxDynamicLibraryDetails
*
291 New(unsigned long start
, unsigned long end
, const wxString
& path
)
293 wxDynamicLibraryDetails
*details
= new wxDynamicLibraryDetails
;
294 details
->m_path
= path
;
295 details
->m_name
= path
.AfterLast(_T('/'));
296 details
->m_address
= wx_reinterpret_cast(void *, start
);
297 details
->m_length
= end
- start
;
299 // try to extract the library version from its name
300 const size_t posExt
= path
.rfind(_T(".so"));
301 if ( posExt
!= wxString::npos
)
303 if ( path
.c_str()[posExt
+ 3] == _T('.') )
305 // assume "libfoo.so.x.y.z" case
306 details
->m_version
.assign(path
, posExt
+ 4, wxString::npos
);
310 size_t posDash
= path
.find_last_of(_T('-'), posExt
);
311 if ( posDash
!= wxString::npos
)
313 // assume "libbar-x.y.z.so" case
315 details
->m_version
.assign(path
, posDash
, posExt
- posDash
);
325 wxDynamicLibraryDetailsArray
wxDynamicLibrary::ListLoaded()
327 wxDynamicLibraryDetailsArray dlls
;
330 // examine /proc/self/maps to find out what is loaded in our address space
331 wxFFile
file(_T("/proc/self/maps"));
332 if ( file
.IsOpened() )
334 // details of the module currently being parsed
336 unsigned long startCur
= 0,
341 while ( fgets(buf
, WXSIZEOF(buf
), file
.fp()) )
343 // format is: start-end perm something? maj:min inode path
344 unsigned long start
, end
;
345 switch ( sscanf(buf
, "%08lx-%08lx %*4s %*08x %*02d:%*02d %*d %1024s\n",
346 &start
, &end
, path
) )
349 // there may be no path column
354 // nothing to do, read everything we wanted
359 buf
[strlen(buf
) - 1] = '\0';
360 wxLogDebug(_T("Failed to parse line \"%s\" in /proc/self/maps."),
365 wxString pathNew
= wxString::FromAscii(path
);
366 if ( pathCur
.empty() )
373 else if ( pathCur
== pathNew
)
375 // continuation of the same module
376 wxASSERT_MSG( start
== endCur
, _T("hole in /proc/self/maps?") );
379 else // end of the current module
381 dlls
.Add(wxDynamicLibraryDetailsCreator::New(startCur
,
393 #endif // wxUSE_DYNLIB_CLASS