1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/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)
7 // Copyright: (c) 2000-2005 Vadim Zeitlin <vadim@wxwindows.org>
8 // Licence: wxWindows licence
9 /////////////////////////////////////////////////////////////////////////////
11 // ============================================================================
13 // ============================================================================
15 // ----------------------------------------------------------------------------
17 // ----------------------------------------------------------------------------
19 #include "wx/wxprec.h"
25 #if wxUSE_DYNLIB_CLASS
27 #include "wx/dynlib.h"
40 #include <AvailabilityMacros.h>
43 // if some flags are not supported, just ignore them
57 #if defined(HAVE_DLOPEN) || defined(__DARWIN__)
58 #define USE_POSIX_DL_FUNCS
59 #elif !defined(HAVE_SHL_LOAD)
60 #error "Don't know how to load dynamic libraries on this platform!"
63 // ----------------------------------------------------------------------------
65 // ----------------------------------------------------------------------------
67 // ============================================================================
68 // wxDynamicLibrary implementation
69 // ============================================================================
71 // ----------------------------------------------------------------------------
72 // dlxxx() emulation for Darwin
73 // Only useful if the OS X version could be < 10.3 at runtime
74 // ----------------------------------------------------------------------------
76 #if defined(__DARWIN__) && (MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_3)
77 // ---------------------------------------------------------------------------
78 // For Darwin/Mac OS X
79 // supply the sun style dlopen functions in terms of Darwin NS*
80 // ---------------------------------------------------------------------------
83 * The dlopen port is a port from dl_next.xs by Anno Siegel.
84 * dl_next.xs is itself a port from dl_dlopen.xs by Paul Marquess.
85 * The method used here is just to supply the sun style dlopen etc.
86 * functions in terms of Darwin NS*.
90 #include <mach-o/dyld.h>
92 static char dl_last_error
[1024];
94 static const char *wx_darwin_dlerror()
99 static void *wx_darwin_dlopen(const char *path
, int WXUNUSED(mode
) /* mode is ignored */)
101 NSObjectFileImage ofile
;
102 NSModule handle
= NULL
;
104 unsigned dyld_result
= NSCreateObjectFileImageFromFile(path
, &ofile
);
105 if ( dyld_result
!= NSObjectFileImageSuccess
)
109 static const char *const errorStrings
[] =
111 "%d: Object Image Load Failure",
112 "%d: Object Image Load Success",
113 "%d: Not an recognisable object file",
114 "%d: No valid architecture",
115 "%d: Object image has an invalid format",
116 "%d: Invalid access (permissions?)",
117 "%d: Unknown error code from NSCreateObjectFileImageFromFile"
120 const int index
= dyld_result
< WXSIZEOF(errorStrings
)
122 : WXSIZEOF(errorStrings
) - 1;
124 // this call to sprintf() is safe as strings above are fixed at
125 // compile-time and are shorter than WXSIZEOF(dl_last_error)
126 sprintf(dl_last_error
, errorStrings
[index
], dyld_result
);
130 handle
= NSLinkModule
134 NSLINKMODULE_OPTION_BINDNOW
|
135 NSLINKMODULE_OPTION_RETURN_ON_ERROR
140 NSLinkEditErrors err
;
142 const char *filename
;
145 NSLinkEditError(&err
, &code
, &filename
, &errmsg
);
146 strncpy(dl_last_error
, errmsg
, WXSIZEOF(dl_last_error
)-1);
147 dl_last_error
[WXSIZEOF(dl_last_error
)-1] = '\0';
155 static int wx_darwin_dlclose(void *handle
)
157 NSUnLinkModule((NSModule
)handle
, NSUNLINKMODULE_OPTION_NONE
);
161 static void *wx_darwin_dlsym(void *handle
, const char *symbol
)
163 // as on many other systems, C symbols have prepended underscores under
164 // Darwin but unlike the normal dlopen(), NSLookupSymbolInModule() is not
166 wxCharBuffer
buf(strlen(symbol
) + 1);
167 char *p
= buf
.data();
169 strcpy(p
+ 1, symbol
);
171 NSSymbol nsSymbol
= NSLookupSymbolInModule((NSModule
)handle
, p
);
172 return nsSymbol
? NSAddressOfSymbol(nsSymbol
) : NULL
;
175 // Add the weak linking attribute to dlopen's declaration
176 extern void * dlopen(const char * __path
, int __mode
) AVAILABLE_MAC_OS_X_VERSION_10_3_AND_LATER
;
178 // For all of these methods we test dlopen since all of the dl functions we use were added
179 // to OS X at the same time. This also ensures we don't dlopen with the real function then
180 // dlclose with the internal implementation.
182 static inline void *wx_dlopen(const char *__path
, int __mode
)
186 return dlopen(__path
, __mode
);
189 return wx_darwin_dlopen(__path
, __mode
);
192 static inline int wx_dlclose(void *__handle
)
196 return dlclose(__handle
);
199 return wx_darwin_dlclose(__handle
);
202 static inline const char *wx_dlerror()
209 return wx_darwin_dlerror();
212 static inline void *wx_dlsym(void *__handle
, const char *__symbol
)
216 return dlsym(__handle
, __symbol
);
219 return wx_darwin_dlsym(__handle
, __symbol
);
222 #else // __DARWIN__/!__DARWIN__
224 // Use preprocessor definitions for non-Darwin or OS X >= 10.3
225 #define wx_dlopen(__path,__mode) dlopen(__path,__mode)
226 #define wx_dlclose(__handle) dlclose(__handle)
227 #define wx_dlerror() dlerror()
228 #define wx_dlsym(__handle,__symbol) dlsym(__handle,__symbol)
230 #endif // defined(__DARWIN__)
232 // ----------------------------------------------------------------------------
233 // loading/unloading DLLs
234 // ----------------------------------------------------------------------------
236 wxDllType
wxDynamicLibrary::GetProgramHandle()
238 #ifdef USE_POSIX_DL_FUNCS
239 return wx_dlopen(0, RTLD_LAZY
);
246 wxDllType
wxDynamicLibrary::RawLoad(const wxString
& libname
, int flags
)
248 wxASSERT_MSG( !(flags
& wxDL_NOW
) || !(flags
& wxDL_LAZY
),
249 wxT("wxDL_LAZY and wxDL_NOW are mutually exclusive.") );
251 #ifdef USE_POSIX_DL_FUNCS
252 // we need to use either RTLD_NOW or RTLD_LAZY because if we call dlopen()
253 // with flags == 0 recent versions of glibc just fail the call, so use
254 // RTLD_NOW even if wxDL_NOW was not specified
255 int rtldFlags
= flags
& wxDL_LAZY
? RTLD_LAZY
: RTLD_NOW
;
257 if ( flags
& wxDL_GLOBAL
)
258 rtldFlags
|= RTLD_GLOBAL
;
260 return wx_dlopen(libname
.fn_str(), rtldFlags
);
261 #else // !USE_POSIX_DL_FUNCS
264 if ( flags
& wxDL_LAZY
)
266 shlFlags
|= BIND_DEFERRED
;
268 else if ( flags
& wxDL_NOW
)
270 shlFlags
|= BIND_IMMEDIATE
;
273 return shl_load(libname
.fn_str(), shlFlags
, 0);
274 #endif // USE_POSIX_DL_FUNCS/!USE_POSIX_DL_FUNCS
278 void wxDynamicLibrary::Unload(wxDllType handle
)
280 #ifdef wxHAVE_DYNLIB_ERROR
284 #ifdef USE_POSIX_DL_FUNCS
286 #else // !USE_POSIX_DL_FUNCS
288 #endif // USE_POSIX_DL_FUNCS/!USE_POSIX_DL_FUNCS
290 #if defined(USE_POSIX_DL_FUNCS) && defined(wxHAVE_DYNLIB_ERROR)
297 void *wxDynamicLibrary::RawGetSymbol(wxDllType handle
, const wxString
& name
)
301 #ifdef USE_POSIX_DL_FUNCS
302 symbol
= wx_dlsym(handle
, name
.fn_str());
303 #else // !USE_POSIX_DL_FUNCS
304 // note that shl_findsym modifies the handle argument to indicate where the
305 // symbol was found, but it's ok to modify the local handle copy here
306 if ( shl_findsym(&handle
, name
.fn_str(), TYPE_UNDEFINED
, &symbol
) != 0 )
308 #endif // USE_POSIX_DL_FUNCS/!USE_POSIX_DL_FUNCS
313 // ----------------------------------------------------------------------------
315 // ----------------------------------------------------------------------------
317 #ifdef wxHAVE_DYNLIB_ERROR
320 void wxDynamicLibrary::Error()
322 wxString
err(wx_dlerror());
325 err
= _("Unknown dynamic library error");
327 wxLogError(wxT("%s"), err
);
330 #endif // wxHAVE_DYNLIB_ERROR
332 // ----------------------------------------------------------------------------
333 // listing loaded modules
334 // ----------------------------------------------------------------------------
336 // wxDynamicLibraryDetails declares this class as its friend, so put the code
337 // initializing new details objects here
338 class wxDynamicLibraryDetailsCreator
341 // create a new wxDynamicLibraryDetails from the given data
342 static wxDynamicLibraryDetails
*
343 New(void *start
, void *end
, const wxString
& path
)
345 wxDynamicLibraryDetails
*details
= new wxDynamicLibraryDetails
;
346 details
->m_path
= path
;
347 details
->m_name
= path
.AfterLast(wxT('/'));
348 details
->m_address
= start
;
349 details
->m_length
= (char *)end
- (char *)start
;
351 // try to extract the library version from its name
352 const size_t posExt
= path
.rfind(wxT(".so"));
353 if ( posExt
!= wxString::npos
)
355 if ( path
.c_str()[posExt
+ 3] == wxT('.') )
357 // assume "libfoo.so.x.y.z" case
358 details
->m_version
.assign(path
, posExt
+ 4, wxString::npos
);
362 size_t posDash
= path
.find_last_of(wxT('-'), posExt
);
363 if ( posDash
!= wxString::npos
)
365 // assume "libbar-x.y.z.so" case
367 details
->m_version
.assign(path
, posDash
, posExt
- posDash
);
377 wxDynamicLibraryDetailsArray
wxDynamicLibrary::ListLoaded()
379 wxDynamicLibraryDetailsArray dlls
;
382 // examine /proc/self/maps to find out what is loaded in our address space
383 wxFFile
file(wxT("/proc/self/maps"));
384 if ( file
.IsOpened() )
386 // details of the module currently being parsed
388 void *startCur
= NULL
,
393 while ( fgets(buf
, WXSIZEOF(buf
), file
.fp()) )
395 // format is: "start-end perm offset maj:min inode path", see proc(5)
398 switch ( sscanf(buf
, "%p-%p %*4s %*p %*02x:%*02x %*d %1024s\n",
399 &start
, &end
, path
) )
402 // there may be no path column
407 // nothing to do, read everything we wanted
412 buf
[strlen(buf
) - 1] = '\0';
413 wxLogDebug(wxT("Failed to parse line \"%s\" in /proc/self/maps."),
418 wxASSERT_MSG( start
>= endCur
,
419 wxT("overlapping regions in /proc/self/maps?") );
421 wxString pathNew
= wxString::FromAscii(path
);
422 if ( pathCur
.empty() )
429 else if ( pathCur
== pathNew
&& endCur
== end
)
431 // continuation of the same module in the address space
434 else // end of the current module
436 dlls
.Add(wxDynamicLibraryDetailsCreator::New(startCur
,
448 #endif // wxUSE_DYNLIB_CLASS