]> git.saurik.com Git - wxWidgets.git/blob - src/unix/dlunix.cpp
Fixed typo
[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 static
102 void TranslateError(const char *path, int number)
103 {
104 unsigned int index;
105 static const char *OFIErrorStrings[] =
106 {
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"
114 };
115 #define NUM_OFI_ERRORS (sizeof(OFIErrorStrings) / sizeof(OFIErrorStrings[0]))
116
117 index = number;
118 if (index > NUM_OFI_ERRORS - 1) {
119 index = NUM_OFI_ERRORS - 1;
120 }
121 sprintf(dl_last_error, OFIErrorStrings[index], path, number);
122 }
123
124 const char *dlerror()
125 {
126 return dl_last_error;
127 }
128
129 void *dlopen(const char *path, int WXUNUSED(mode) /* mode is ignored */)
130 {
131 NSObjectFileImage ofile;
132 NSModule handle = NULL;
133
134 int dyld_result = NSCreateObjectFileImageFromFile(path, &ofile);
135 if ( dyld_result != NSObjectFileImageSuccess )
136 {
137 handle = NULL;
138 }
139 else
140 {
141 handle = NSLinkModule
142 (
143 ofile,
144 path,
145 NSLINKMODULE_OPTION_BINDNOW |
146 NSLINKMODULE_OPTION_RETURN_ON_ERROR
147 );
148 }
149
150 if ( !handle )
151 TranslateError(path, dyld_result);
152
153 return handle;
154 }
155
156 int dlclose(void *handle)
157 {
158 NSUnLinkModule((NSModule)handle, NSUNLINKMODULE_OPTION_NONE);
159 return 0;
160 }
161
162 void *dlsym(void *handle, const char *symbol)
163 {
164 // as on many other systems, C symbols have prepended underscores under
165 // Darwin but unlike the normal dlopen(), NSLookupSymbolInModule() is not
166 // aware of this
167 wxCharBuffer buf(strlen(symbol) + 1);
168 char *p = buf.data();
169 p[0] = '_';
170 strcpy(p + 1, symbol);
171
172 NSSymbol nsSymbol = NSLookupSymbolInModule((NSModule)handle, p );
173 return nsSymbol ? NSAddressOfSymbol(nsSymbol) : NULL;
174 }
175
176 #endif // defined(__DARWIN__)
177
178 // ----------------------------------------------------------------------------
179 // loading/unloading DLLs
180 // ----------------------------------------------------------------------------
181
182 wxDllType wxDynamicLibrary::GetProgramHandle()
183 {
184 #ifdef USE_POSIX_DL_FUNCS
185 return dlopen(0, RTLD_LAZY);
186 #else
187 return PROG_HANDLE;
188 #endif
189 }
190
191 /* static */
192 wxDllType wxDynamicLibrary::RawLoad(const wxString& libname, int flags)
193 {
194 wxASSERT_MSG( !(flags & wxDL_NOW) || !(flags & wxDL_LAZY),
195 _T("wxDL_LAZY and wxDL_NOW are mutually exclusive.") );
196
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;
202
203 if ( flags & wxDL_GLOBAL )
204 rtldFlags |= RTLD_GLOBAL;
205
206 return dlopen(libname.fn_str(), rtldFlags);
207 #else // !USE_POSIX_DL_FUNCS
208 int shlFlags = 0;
209
210 if ( flags & wxDL_LAZY )
211 {
212 shlFlags |= BIND_DEFERRED;
213 }
214 else if ( flags & wxDL_NOW )
215 {
216 shlFlags |= BIND_IMMEDIATE;
217 }
218
219 return shl_load(libname.fn_str(), shlFlags, 0);
220 #endif // USE_POSIX_DL_FUNCS/!USE_POSIX_DL_FUNCS
221 }
222
223 /* static */
224 void wxDynamicLibrary::Unload(wxDllType handle)
225 {
226 #ifdef wxHAVE_DYNLIB_ERROR
227 int rc =
228 #endif
229
230 #ifdef USE_POSIX_DL_FUNCS
231 dlclose(handle);
232 #else // !USE_POSIX_DL_FUNCS
233 shl_unload(handle);
234 #endif // USE_POSIX_DL_FUNCS/!USE_POSIX_DL_FUNCS
235
236 #if defined(USE_POSIX_DL_FUNCS) && defined(wxHAVE_DYNLIB_ERROR)
237 if ( rc != 0 )
238 Error();
239 #endif
240 }
241
242 /* static */
243 void *wxDynamicLibrary::RawGetSymbol(wxDllType handle, const wxString& name)
244 {
245 void *symbol;
246
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 )
253 symbol = 0;
254 #endif // USE_POSIX_DL_FUNCS/!USE_POSIX_DL_FUNCS
255
256 return symbol;
257 }
258
259 // ----------------------------------------------------------------------------
260 // error handling
261 // ----------------------------------------------------------------------------
262
263 #ifdef wxHAVE_DYNLIB_ERROR
264
265 /* static */
266 void wxDynamicLibrary::Error()
267 {
268 #if wxUSE_UNICODE
269 wxWCharBuffer buffer = wxConvLocal.cMB2WC( dlerror() );
270 const wxChar *err = buffer;
271 #else
272 const wxChar *err = dlerror();
273 #endif
274
275 wxLogError(wxT("%s"), err ? err : _("Unknown dynamic library error"));
276 }
277
278 #endif // wxHAVE_DYNLIB_ERROR
279
280 // ----------------------------------------------------------------------------
281 // listing loaded modules
282 // ----------------------------------------------------------------------------
283
284 // wxDynamicLibraryDetails declares this class as its friend, so put the code
285 // initializing new details objects here
286 class wxDynamicLibraryDetailsCreator
287 {
288 public:
289 // create a new wxDynamicLibraryDetails from the given data
290 static wxDynamicLibraryDetails *
291 New(unsigned long start, unsigned long end, const wxString& path)
292 {
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;
298
299 // try to extract the library version from its name
300 const size_t posExt = path.rfind(_T(".so"));
301 if ( posExt != wxString::npos )
302 {
303 if ( path.c_str()[posExt + 3] == _T('.') )
304 {
305 // assume "libfoo.so.x.y.z" case
306 details->m_version.assign(path, posExt + 4, wxString::npos);
307 }
308 else
309 {
310 size_t posDash = path.find_last_of(_T('-'), posExt);
311 if ( posDash != wxString::npos )
312 {
313 // assume "libbar-x.y.z.so" case
314 posDash++;
315 details->m_version.assign(path, posDash, posExt - posDash);
316 }
317 }
318 }
319
320 return details;
321 }
322 };
323
324 /* static */
325 wxDynamicLibraryDetailsArray wxDynamicLibrary::ListLoaded()
326 {
327 wxDynamicLibraryDetailsArray dlls;
328
329 #ifdef __LINUX__
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() )
333 {
334 // details of the module currently being parsed
335 wxString pathCur;
336 unsigned long startCur = 0,
337 endCur = 0;
338
339 char path[1024];
340 char buf[1024];
341 while ( fgets(buf, WXSIZEOF(buf), file.fp()) )
342 {
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) )
347 {
348 case 2:
349 // there may be no path column
350 path[0] = '\0';
351 break;
352
353 case 3:
354 // nothing to do, read everything we wanted
355 break;
356
357 default:
358 // chop '\n'
359 buf[strlen(buf) - 1] = '\0';
360 wxLogDebug(_T("Failed to parse line \"%s\" in /proc/self/maps."),
361 buf);
362 continue;
363 }
364
365 wxString pathNew = wxString::FromAscii(path);
366 if ( pathCur.empty() )
367 {
368 // new module start
369 pathCur = pathNew;
370 startCur = start;
371 endCur = end;
372 }
373 else if ( pathCur == pathNew )
374 {
375 // continuation of the same module
376 wxASSERT_MSG( start == endCur, _T("hole in /proc/self/maps?") );
377 endCur = end;
378 }
379 else // end of the current module
380 {
381 dlls.Add(wxDynamicLibraryDetailsCreator::New(startCur,
382 endCur,
383 pathCur));
384 pathCur.clear();
385 }
386 }
387 }
388 #endif // __LINUX__
389
390 return dlls;
391 }
392
393 #endif // wxUSE_DYNLIB_CLASS
394