]> git.saurik.com Git - wxWidgets.git/blame - src/unix/dlunix.cpp
allow having children of status bar in XRC (patch 1704125)
[wxWidgets.git] / src / unix / dlunix.cpp
CommitLineData
da55d064
VZ
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"
297ebe6b 29#include "wx/ffile.h"
da55d064 30
ac6b7b3c
VZ
31#ifndef WX_PRECOMP
32 #include "wx/intl.h"
33 #include "wx/log.h"
34#endif
35
bc5f4d98
VZ
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__
d8e342b7
DE
39 #include <dlfcn.h>
40#endif
41
bc5f4d98
VZ
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
bcd1ec33 52 #define RTLD_GLOBAL 0
bc5f4d98
VZ
53#endif
54
55
da55d064
VZ
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
99static char dl_last_error[1024];
100
da55d064
VZ
101const char *dlerror()
102{
103 return dl_last_error;
104}
105
106void *dlopen(const char *path, int WXUNUSED(mode) /* mode is ignored */)
107{
108 NSObjectFileImage ofile;
109 NSModule handle = NULL;
110
84ac8772 111 unsigned dyld_result = NSCreateObjectFileImageFromFile(path, &ofile);
da55d064
VZ
112 if ( dyld_result != NSObjectFileImageSuccess )
113 {
114 handle = NULL;
84ac8772
VZ
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);
da55d064
VZ
134 }
135 else
136 {
137 handle = NSLinkModule
138 (
139 ofile,
140 path,
141 NSLINKMODULE_OPTION_BINDNOW |
142 NSLINKMODULE_OPTION_RETURN_ON_ERROR
143 );
84ac8772
VZ
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 }
da55d064
VZ
156 }
157
da55d064
VZ
158
159 return handle;
160}
161
162int dlclose(void *handle)
163{
5b74902d 164 NSUnLinkModule((NSModule)handle, NSUNLINKMODULE_OPTION_NONE);
da55d064
VZ
165 return 0;
166}
167
168void *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
5b74902d 178 NSSymbol nsSymbol = NSLookupSymbolInModule((NSModule)handle, p );
da55d064
VZ
179 return nsSymbol ? NSAddressOfSymbol(nsSymbol) : NULL;
180}
181
182#endif // defined(__DARWIN__)
183
184// ----------------------------------------------------------------------------
185// loading/unloading DLLs
186// ----------------------------------------------------------------------------
187
188wxDllType 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 */
198wxDllType wxDynamicLibrary::RawLoad(const wxString& libname, int flags)
199{
cf72919c 200 wxASSERT_MSG( !(flags & wxDL_NOW) || !(flags & wxDL_LAZY),
da55d064
VZ
201 _T("wxDL_LAZY and wxDL_NOW are mutually exclusive.") );
202
203#ifdef USE_POSIX_DL_FUNCS
cf72919c
VZ
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;
da55d064 208
da55d064 209 if ( flags & wxDL_GLOBAL )
da55d064 210 rtldFlags |= RTLD_GLOBAL;
da55d064
VZ
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 */
230void 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
d8e342b7 242#if defined(USE_POSIX_DL_FUNCS) && defined(wxHAVE_DYNLIB_ERROR)
da55d064
VZ
243 if ( rc != 0 )
244 Error();
245#endif
246}
247
248/* static */
249void *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
297ebe6b
VZ
265// ----------------------------------------------------------------------------
266// error handling
267// ----------------------------------------------------------------------------
268
da55d064
VZ
269#ifdef wxHAVE_DYNLIB_ERROR
270
271/* static */
272void wxDynamicLibrary::Error()
273{
c9f78968
VS
274 wxString err(dlerror());
275
276 if ( err.empty() )
277 err = _("Unknown dynamic library error");
da55d064 278
c9f78968 279 wxLogError(wxT("%s"), err);
da55d064
VZ
280}
281
282#endif // wxHAVE_DYNLIB_ERROR
283
297ebe6b
VZ
284// ----------------------------------------------------------------------------
285// listing loaded modules
286// ----------------------------------------------------------------------------
287
288// wxDynamicLibraryDetails declares this class as its friend, so put the code
289// initializing new details objects here
290class wxDynamicLibraryDetailsCreator
291{
292public:
293 // create a new wxDynamicLibraryDetails from the given data
294 static wxDynamicLibraryDetails *
ad41e209 295 New(void *start, void *end, const wxString& path)
297ebe6b
VZ
296 {
297 wxDynamicLibraryDetails *details = new wxDynamicLibraryDetails;
298 details->m_path = path;
299 details->m_name = path.AfterLast(_T('/'));
ad41e209
VZ
300 details->m_address = start;
301 details->m_length = (char *)end - (char *)start;
297ebe6b
VZ
302
303 // try to extract the library version from its name
304 const size_t posExt = path.rfind(_T(".so"));
305 if ( posExt != wxString::npos )
306 {
307 if ( path.c_str()[posExt + 3] == _T('.') )
308 {
309 // assume "libfoo.so.x.y.z" case
310 details->m_version.assign(path, posExt + 4, wxString::npos);
311 }
312 else
313 {
314 size_t posDash = path.find_last_of(_T('-'), posExt);
315 if ( posDash != wxString::npos )
316 {
317 // assume "libbar-x.y.z.so" case
318 posDash++;
319 details->m_version.assign(path, posDash, posExt - posDash);
320 }
321 }
322 }
323
324 return details;
325 }
326};
327
328/* static */
329wxDynamicLibraryDetailsArray wxDynamicLibrary::ListLoaded()
330{
331 wxDynamicLibraryDetailsArray dlls;
332
333#ifdef __LINUX__
334 // examine /proc/self/maps to find out what is loaded in our address space
5e4f63c8 335 wxFFile file(_T("/proc/self/maps"));
297ebe6b
VZ
336 if ( file.IsOpened() )
337 {
338 // details of the module currently being parsed
339 wxString pathCur;
ad41e209
VZ
340 void *startCur = NULL,
341 *endCur = NULL;
297ebe6b
VZ
342
343 char path[1024];
344 char buf[1024];
345 while ( fgets(buf, WXSIZEOF(buf), file.fp()) )
346 {
ad41e209
VZ
347 // format is: "start-end perm offset maj:min inode path", see proc(5)
348 void *start,
349 *end;
350 switch ( sscanf(buf, "%p-%p %*4s %*p %*02x:%*02x %*d %1024s\n",
297ebe6b
VZ
351 &start, &end, path) )
352 {
353 case 2:
354 // there may be no path column
355 path[0] = '\0';
356 break;
357
358 case 3:
359 // nothing to do, read everything we wanted
360 break;
361
362 default:
363 // chop '\n'
364 buf[strlen(buf) - 1] = '\0';
365 wxLogDebug(_T("Failed to parse line \"%s\" in /proc/self/maps."),
366 buf);
367 continue;
368 }
369
ad41e209
VZ
370 wxASSERT_MSG( start >= endCur,
371 _T("overlapping regions in /proc/self/maps?") );
372
297ebe6b
VZ
373 wxString pathNew = wxString::FromAscii(path);
374 if ( pathCur.empty() )
375 {
376 // new module start
377 pathCur = pathNew;
378 startCur = start;
379 endCur = end;
380 }
ad41e209 381 else if ( pathCur == pathNew && endCur == end )
297ebe6b 382 {
ad41e209 383 // continuation of the same module in the address space
297ebe6b
VZ
384 endCur = end;
385 }
386 else // end of the current module
387 {
388 dlls.Add(wxDynamicLibraryDetailsCreator::New(startCur,
389 endCur,
390 pathCur));
391 pathCur.clear();
392 }
393 }
394 }
395#endif // __LINUX__
396
397 return dlls;
398}
399
da55d064
VZ
400#endif // wxUSE_DYNLIB_CLASS
401