]> git.saurik.com Git - wxWidgets.git/blob - src/unix/dlunix.cpp
Committed forgotten files
[wxWidgets.git] / src / unix / dlunix.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: unix/dlunix.cpp
3 // Purpose: Unix-specific part of wxDynamicLibrary and related classes
4 // Author: Vadim Zeitlin
5 // Modified by:
6 // Created: 2005-01-16 (extracted from common/dynlib.cpp)
7 // RCS-ID: $Id$
8 // Copyright: (c) 2000-2005 Vadim Zeitlin <vadim@wxwindows.org>
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
11
12 // ============================================================================
13 // declarations
14 // ============================================================================
15
16 // ----------------------------------------------------------------------------
17 // headers
18 // ----------------------------------------------------------------------------
19
20 #include "wx/wxprec.h"
21
22 #ifdef __BORLANDC__
23 #pragma hdrstop
24 #endif
25
26 #if wxUSE_DYNLIB_CLASS
27
28 #include "wx/dynlib.h"
29 #include "wx/ffile.h"
30
31 #ifndef WX_PRECOMP
32 #include "wx/intl.h"
33 #include "wx/log.h"
34 #endif
35
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
38 #ifndef __DARWIN__
39 #include <dlfcn.h>
40 #endif
41
42 // if some flags are not supported, just ignore them
43 #ifndef RTLD_LAZY
44 #define RTLD_LAZY 0
45 #endif
46
47 #ifndef RTLD_NOW
48 #define RTLD_NOW 0
49 #endif
50
51 #ifndef RTLD_GLOBAL
52 #define RTLD_GLOBAL 0
53 #endif
54
55
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!"
60 #endif
61
62 // ----------------------------------------------------------------------------
63 // constants
64 // ----------------------------------------------------------------------------
65
66 // standard shared libraries extensions for different Unix versions
67 #if defined(__HPUX__)
68 const wxChar *wxDynamicLibrary::ms_dllext = _T(".sl");
69 #elif defined(__DARWIN__)
70 const wxChar *wxDynamicLibrary::ms_dllext = _T(".bundle");
71 #else
72 const wxChar *wxDynamicLibrary::ms_dllext = _T(".so");
73 #endif
74
75 // ============================================================================
76 // wxDynamicLibrary implementation
77 // ============================================================================
78
79 // ----------------------------------------------------------------------------
80 // dlxxx() emulation for Darwin
81 // ----------------------------------------------------------------------------
82
83 #if defined(__DARWIN__)
84 // ---------------------------------------------------------------------------
85 // For Darwin/Mac OS X
86 // supply the sun style dlopen functions in terms of Darwin NS*
87 // ---------------------------------------------------------------------------
88
89 /* Porting notes:
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*.
94 */
95
96 #include <stdio.h>
97 #include <mach-o/dyld.h>
98
99 static char dl_last_error[1024];
100
101 const char *dlerror()
102 {
103 return dl_last_error;
104 }
105
106 void *dlopen(const char *path, int WXUNUSED(mode) /* mode is ignored */)
107 {
108 NSObjectFileImage ofile;
109 NSModule handle = NULL;
110
111 unsigned dyld_result = NSCreateObjectFileImageFromFile(path, &ofile);
112 if ( dyld_result != NSObjectFileImageSuccess )
113 {
114 handle = NULL;
115
116 static const char *errorStrings[] =
117 {
118 "%d: Object Image Load Failure",
119 "%d: Object Image Load Success",
120 "%d: Not an recognisable object file",
121 "%d: No valid architecture",
122 "%d: Object image has an invalid format",
123 "%d: Invalid access (permissions?)",
124 "%d: Unknown error code from NSCreateObjectFileImageFromFile"
125 };
126
127 const int index = dyld_result < WXSIZEOF(errorStrings)
128 ? dyld_result
129 : WXSIZEOF(errorStrings) - 1;
130
131 // this call to sprintf() is safe as strings above are fixed at
132 // compile-time and are shorter than WXSIZEOF(dl_last_error)
133 sprintf(dl_last_error, errorStrings[index], dyld_result);
134 }
135 else
136 {
137 handle = NSLinkModule
138 (
139 ofile,
140 path,
141 NSLINKMODULE_OPTION_BINDNOW |
142 NSLINKMODULE_OPTION_RETURN_ON_ERROR
143 );
144
145 if ( !handle )
146 {
147 NSLinkEditErrors err;
148 int code;
149 const char *filename;
150 const char *errmsg;
151
152 NSLinkEditError(&err, &code, &filename, &errmsg);
153 strncpy(dl_last_error, errmsg, WXSIZEOF(dl_last_error)-1);
154 dl_last_error[WXSIZEOF(dl_last_error)-1] = '\0';
155 }
156 }
157
158
159 return handle;
160 }
161
162 int dlclose(void *handle)
163 {
164 NSUnLinkModule((NSModule)handle, NSUNLINKMODULE_OPTION_NONE);
165 return 0;
166 }
167
168 void *dlsym(void *handle, const char *symbol)
169 {
170 // as on many other systems, C symbols have prepended underscores under
171 // Darwin but unlike the normal dlopen(), NSLookupSymbolInModule() is not
172 // aware of this
173 wxCharBuffer buf(strlen(symbol) + 1);
174 char *p = buf.data();
175 p[0] = '_';
176 strcpy(p + 1, symbol);
177
178 NSSymbol nsSymbol = NSLookupSymbolInModule((NSModule)handle, p );
179 return nsSymbol ? NSAddressOfSymbol(nsSymbol) : NULL;
180 }
181
182 #endif // defined(__DARWIN__)
183
184 // ----------------------------------------------------------------------------
185 // loading/unloading DLLs
186 // ----------------------------------------------------------------------------
187
188 wxDllType wxDynamicLibrary::GetProgramHandle()
189 {
190 #ifdef USE_POSIX_DL_FUNCS
191 return dlopen(0, RTLD_LAZY);
192 #else
193 return PROG_HANDLE;
194 #endif
195 }
196
197 /* static */
198 wxDllType wxDynamicLibrary::RawLoad(const wxString& libname, int flags)
199 {
200 wxASSERT_MSG( !(flags & wxDL_NOW) || !(flags & wxDL_LAZY),
201 _T("wxDL_LAZY and wxDL_NOW are mutually exclusive.") );
202
203 #ifdef USE_POSIX_DL_FUNCS
204 // we need to use either RTLD_NOW or RTLD_LAZY because if we call dlopen()
205 // with flags == 0 recent versions of glibc just fail the call, so use
206 // RTLD_NOW even if wxDL_NOW was not specified
207 int rtldFlags = flags & wxDL_LAZY ? RTLD_LAZY : RTLD_NOW;
208
209 if ( flags & wxDL_GLOBAL )
210 rtldFlags |= RTLD_GLOBAL;
211
212 return dlopen(libname.fn_str(), rtldFlags);
213 #else // !USE_POSIX_DL_FUNCS
214 int shlFlags = 0;
215
216 if ( flags & wxDL_LAZY )
217 {
218 shlFlags |= BIND_DEFERRED;
219 }
220 else if ( flags & wxDL_NOW )
221 {
222 shlFlags |= BIND_IMMEDIATE;
223 }
224
225 return shl_load(libname.fn_str(), shlFlags, 0);
226 #endif // USE_POSIX_DL_FUNCS/!USE_POSIX_DL_FUNCS
227 }
228
229 /* static */
230 void wxDynamicLibrary::Unload(wxDllType handle)
231 {
232 #ifdef wxHAVE_DYNLIB_ERROR
233 int rc =
234 #endif
235
236 #ifdef USE_POSIX_DL_FUNCS
237 dlclose(handle);
238 #else // !USE_POSIX_DL_FUNCS
239 shl_unload(handle);
240 #endif // USE_POSIX_DL_FUNCS/!USE_POSIX_DL_FUNCS
241
242 #if defined(USE_POSIX_DL_FUNCS) && defined(wxHAVE_DYNLIB_ERROR)
243 if ( rc != 0 )
244 Error();
245 #endif
246 }
247
248 /* static */
249 void *wxDynamicLibrary::RawGetSymbol(wxDllType handle, const wxString& name)
250 {
251 void *symbol;
252
253 #ifdef USE_POSIX_DL_FUNCS
254 symbol = dlsym(handle, name.fn_str());
255 #else // !USE_POSIX_DL_FUNCS
256 // note that shl_findsym modifies the handle argument to indicate where the
257 // symbol was found, but it's ok to modify the local handle copy here
258 if ( shl_findsym(&handle, name.fn_str(), TYPE_UNDEFINED, &symbol) != 0 )
259 symbol = 0;
260 #endif // USE_POSIX_DL_FUNCS/!USE_POSIX_DL_FUNCS
261
262 return symbol;
263 }
264
265 // ----------------------------------------------------------------------------
266 // error handling
267 // ----------------------------------------------------------------------------
268
269 #ifdef wxHAVE_DYNLIB_ERROR
270
271 /* static */
272 void wxDynamicLibrary::Error()
273 {
274 #if wxUSE_UNICODE
275 wxWCharBuffer buffer = wxConvLocal.cMB2WC( dlerror() );
276 const wxChar *err = buffer;
277 #else
278 const wxChar *err = dlerror();
279 #endif
280
281 wxLogError(wxT("%s"), err ? err : _("Unknown dynamic library error"));
282 }
283
284 #endif // wxHAVE_DYNLIB_ERROR
285
286 // ----------------------------------------------------------------------------
287 // listing loaded modules
288 // ----------------------------------------------------------------------------
289
290 // wxDynamicLibraryDetails declares this class as its friend, so put the code
291 // initializing new details objects here
292 class wxDynamicLibraryDetailsCreator
293 {
294 public:
295 // create a new wxDynamicLibraryDetails from the given data
296 static wxDynamicLibraryDetails *
297 New(unsigned long start, unsigned long end, const wxString& path)
298 {
299 wxDynamicLibraryDetails *details = new wxDynamicLibraryDetails;
300 details->m_path = path;
301 details->m_name = path.AfterLast(_T('/'));
302 details->m_address = wxUIntToPtr(start);
303 details->m_length = end - start;
304
305 // try to extract the library version from its name
306 const size_t posExt = path.rfind(_T(".so"));
307 if ( posExt != wxString::npos )
308 {
309 if ( path.c_str()[posExt + 3] == _T('.') )
310 {
311 // assume "libfoo.so.x.y.z" case
312 details->m_version.assign(path, posExt + 4, wxString::npos);
313 }
314 else
315 {
316 size_t posDash = path.find_last_of(_T('-'), posExt);
317 if ( posDash != wxString::npos )
318 {
319 // assume "libbar-x.y.z.so" case
320 posDash++;
321 details->m_version.assign(path, posDash, posExt - posDash);
322 }
323 }
324 }
325
326 return details;
327 }
328 };
329
330 /* static */
331 wxDynamicLibraryDetailsArray wxDynamicLibrary::ListLoaded()
332 {
333 wxDynamicLibraryDetailsArray dlls;
334
335 #ifdef __LINUX__
336 // examine /proc/self/maps to find out what is loaded in our address space
337 wxFFile file(_T("/proc/self/maps"));
338 if ( file.IsOpened() )
339 {
340 // details of the module currently being parsed
341 wxString pathCur;
342 unsigned long startCur = 0,
343 endCur = 0;
344
345 char path[1024];
346 char buf[1024];
347 while ( fgets(buf, WXSIZEOF(buf), file.fp()) )
348 {
349 // format is: start-end perm something? maj:min inode path
350 unsigned long start, end;
351 switch ( sscanf(buf, "%08lx-%08lx %*4s %*08x %*02d:%*02d %*d %1024s\n",
352 &start, &end, path) )
353 {
354 case 2:
355 // there may be no path column
356 path[0] = '\0';
357 break;
358
359 case 3:
360 // nothing to do, read everything we wanted
361 break;
362
363 default:
364 // chop '\n'
365 buf[strlen(buf) - 1] = '\0';
366 wxLogDebug(_T("Failed to parse line \"%s\" in /proc/self/maps."),
367 buf);
368 continue;
369 }
370
371 wxString pathNew = wxString::FromAscii(path);
372 if ( pathCur.empty() )
373 {
374 // new module start
375 pathCur = pathNew;
376 startCur = start;
377 endCur = end;
378 }
379 else if ( pathCur == pathNew )
380 {
381 // continuation of the same module
382 wxASSERT_MSG( start == endCur, _T("hole in /proc/self/maps?") );
383 endCur = end;
384 }
385 else // end of the current module
386 {
387 dlls.Add(wxDynamicLibraryDetailsCreator::New(startCur,
388 endCur,
389 pathCur));
390 pathCur.clear();
391 }
392 }
393 }
394 #endif // __LINUX__
395
396 return dlls;
397 }
398
399 #endif // wxUSE_DYNLIB_CLASS
400