]> git.saurik.com Git - wxWidgets.git/blame - src/unix/dlunix.cpp
Simplified and extended compiler detection for OS/2.
[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
101static
102void TranslateError(const char *path, int number)
103{
104 unsigned int index;
105 static 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
124const char *dlerror()
125{
126 return dl_last_error;
127}
128
129void *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
156int dlclose(void *handle)
157{
5b74902d 158 NSUnLinkModule((NSModule)handle, NSUNLINKMODULE_OPTION_NONE);
da55d064
VZ
159 return 0;
160}
161
162void *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
5b74902d 172 NSSymbol nsSymbol = NSLookupSymbolInModule((NSModule)handle, p );
da55d064
VZ
173 return nsSymbol ? NSAddressOfSymbol(nsSymbol) : NULL;
174}
175
176#endif // defined(__DARWIN__)
177
178// ----------------------------------------------------------------------------
179// loading/unloading DLLs
180// ----------------------------------------------------------------------------
181
182wxDllType 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 */
192wxDllType wxDynamicLibrary::RawLoad(const wxString& libname, int flags)
193{
194 wxASSERT_MSG( (flags & wxDL_NOW) == 0,
195 _T("wxDL_LAZY and wxDL_NOW are mutually exclusive.") );
196
197#ifdef USE_POSIX_DL_FUNCS
198 int rtldFlags = 0;
199
da55d064
VZ
200 if ( flags & wxDL_LAZY )
201 {
202 rtldFlags |= RTLD_LAZY;
203 }
da55d064
VZ
204 if ( flags & wxDL_NOW )
205 {
206 rtldFlags |= RTLD_NOW;
207 }
da55d064
VZ
208 if ( flags & wxDL_GLOBAL )
209 {
210 rtldFlags |= RTLD_GLOBAL;
211 }
da55d064
VZ
212
213 return dlopen(libname.fn_str(), rtldFlags);
214#else // !USE_POSIX_DL_FUNCS
215 int shlFlags = 0;
216
217 if ( flags & wxDL_LAZY )
218 {
219 shlFlags |= BIND_DEFERRED;
220 }
221 else if ( flags & wxDL_NOW )
222 {
223 shlFlags |= BIND_IMMEDIATE;
224 }
225
226 return shl_load(libname.fn_str(), shlFlags, 0);
227#endif // USE_POSIX_DL_FUNCS/!USE_POSIX_DL_FUNCS
228}
229
230/* static */
231void wxDynamicLibrary::Unload(wxDllType handle)
232{
233#ifdef wxHAVE_DYNLIB_ERROR
234 int rc =
235#endif
236
237#ifdef USE_POSIX_DL_FUNCS
238 dlclose(handle);
239#else // !USE_POSIX_DL_FUNCS
240 shl_unload(handle);
241#endif // USE_POSIX_DL_FUNCS/!USE_POSIX_DL_FUNCS
242
d8e342b7 243#if defined(USE_POSIX_DL_FUNCS) && defined(wxHAVE_DYNLIB_ERROR)
da55d064
VZ
244 if ( rc != 0 )
245 Error();
246#endif
247}
248
249/* static */
250void *wxDynamicLibrary::RawGetSymbol(wxDllType handle, const wxString& name)
251{
252 void *symbol;
253
254#ifdef USE_POSIX_DL_FUNCS
255 symbol = dlsym(handle, name.fn_str());
256#else // !USE_POSIX_DL_FUNCS
257 // note that shl_findsym modifies the handle argument to indicate where the
258 // symbol was found, but it's ok to modify the local handle copy here
259 if ( shl_findsym(&handle, name.fn_str(), TYPE_UNDEFINED, &symbol) != 0 )
260 symbol = 0;
261#endif // USE_POSIX_DL_FUNCS/!USE_POSIX_DL_FUNCS
262
263 return symbol;
264}
265
297ebe6b
VZ
266// ----------------------------------------------------------------------------
267// error handling
268// ----------------------------------------------------------------------------
269
da55d064
VZ
270#ifdef wxHAVE_DYNLIB_ERROR
271
272/* static */
273void wxDynamicLibrary::Error()
274{
275#if wxUSE_UNICODE
276 wxWCharBuffer buffer = wxConvLocal.cMB2WC( dlerror() );
277 const wxChar *err = buffer;
278#else
279 const wxChar *err = dlerror();
280#endif
281
282 wxLogError(wxT("%s"), err ? err : _("Unknown dynamic library error"));
283}
284
285#endif // wxHAVE_DYNLIB_ERROR
286
297ebe6b
VZ
287// ----------------------------------------------------------------------------
288// listing loaded modules
289// ----------------------------------------------------------------------------
290
291// wxDynamicLibraryDetails declares this class as its friend, so put the code
292// initializing new details objects here
293class wxDynamicLibraryDetailsCreator
294{
295public:
296 // create a new wxDynamicLibraryDetails from the given data
297 static wxDynamicLibraryDetails *
298 New(unsigned long start, unsigned long end, const wxString& path)
299 {
300 wxDynamicLibraryDetails *details = new wxDynamicLibraryDetails;
301 details->m_path = path;
302 details->m_name = path.AfterLast(_T('/'));
303 details->m_address = wx_reinterpret_cast(void *, start);
304 details->m_length = end - start;
305
306 // try to extract the library version from its name
307 const size_t posExt = path.rfind(_T(".so"));
308 if ( posExt != wxString::npos )
309 {
310 if ( path.c_str()[posExt + 3] == _T('.') )
311 {
312 // assume "libfoo.so.x.y.z" case
313 details->m_version.assign(path, posExt + 4, wxString::npos);
314 }
315 else
316 {
317 size_t posDash = path.find_last_of(_T('-'), posExt);
318 if ( posDash != wxString::npos )
319 {
320 // assume "libbar-x.y.z.so" case
321 posDash++;
322 details->m_version.assign(path, posDash, posExt - posDash);
323 }
324 }
325 }
326
327 return details;
328 }
329};
330
331/* static */
332wxDynamicLibraryDetailsArray wxDynamicLibrary::ListLoaded()
333{
334 wxDynamicLibraryDetailsArray dlls;
335
336#ifdef __LINUX__
337 // examine /proc/self/maps to find out what is loaded in our address space
5e4f63c8 338 wxFFile file(_T("/proc/self/maps"));
297ebe6b
VZ
339 if ( file.IsOpened() )
340 {
341 // details of the module currently being parsed
342 wxString pathCur;
343 unsigned long startCur,
344 endCur;
345
346 char path[1024];
347 char buf[1024];
348 while ( fgets(buf, WXSIZEOF(buf), file.fp()) )
349 {
350 // format is: start-end perm something? maj:min inode path
351 unsigned long start, end;
352 switch ( sscanf(buf, "%08lx-%08lx %*4s %*08x %*02d:%*02d %*d %1024s\n",
353 &start, &end, path) )
354 {
355 case 2:
356 // there may be no path column
357 path[0] = '\0';
358 break;
359
360 case 3:
361 // nothing to do, read everything we wanted
362 break;
363
364 default:
365 // chop '\n'
366 buf[strlen(buf) - 1] = '\0';
367 wxLogDebug(_T("Failed to parse line \"%s\" in /proc/self/maps."),
368 buf);
369 continue;
370 }
371
372 wxString pathNew = wxString::FromAscii(path);
373 if ( pathCur.empty() )
374 {
375 // new module start
376 pathCur = pathNew;
377 startCur = start;
378 endCur = end;
379 }
380 else if ( pathCur == pathNew )
381 {
382 // continuation of the same module
383 wxASSERT_MSG( start == endCur, _T("hole in /proc/self/maps?") );
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