]> git.saurik.com Git - wxWidgets.git/blame - src/unix/dlunix.cpp
Fix for handling of invalid gifs, patch 1587754 Noel Byron.
[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{
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
297ebe6b
VZ
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
292class wxDynamicLibraryDetailsCreator
293{
294public:
295 // create a new wxDynamicLibraryDetails from the given data
296 static wxDynamicLibraryDetails *
ad41e209 297 New(void *start, void *end, const wxString& path)
297ebe6b
VZ
298 {
299 wxDynamicLibraryDetails *details = new wxDynamicLibraryDetails;
300 details->m_path = path;
301 details->m_name = path.AfterLast(_T('/'));
ad41e209
VZ
302 details->m_address = start;
303 details->m_length = (char *)end - (char *)start;
297ebe6b
VZ
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 */
331wxDynamicLibraryDetailsArray 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
5e4f63c8 337 wxFFile file(_T("/proc/self/maps"));
297ebe6b
VZ
338 if ( file.IsOpened() )
339 {
340 // details of the module currently being parsed
341 wxString pathCur;
ad41e209
VZ
342 void *startCur = NULL,
343 *endCur = NULL;
297ebe6b
VZ
344
345 char path[1024];
346 char buf[1024];
347 while ( fgets(buf, WXSIZEOF(buf), file.fp()) )
348 {
ad41e209
VZ
349 // format is: "start-end perm offset maj:min inode path", see proc(5)
350 void *start,
351 *end;
352 switch ( sscanf(buf, "%p-%p %*4s %*p %*02x:%*02x %*d %1024s\n",
297ebe6b
VZ
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
ad41e209
VZ
372 wxASSERT_MSG( start >= endCur,
373 _T("overlapping regions in /proc/self/maps?") );
374
297ebe6b
VZ
375 wxString pathNew = wxString::FromAscii(path);
376 if ( pathCur.empty() )
377 {
378 // new module start
379 pathCur = pathNew;
380 startCur = start;
381 endCur = end;
382 }
ad41e209 383 else if ( pathCur == pathNew && endCur == end )
297ebe6b 384 {
ad41e209 385 // continuation of the same module in the address space
297ebe6b
VZ
386 endCur = end;
387 }
388 else // end of the current module
389 {
390 dlls.Add(wxDynamicLibraryDetailsCreator::New(startCur,
391 endCur,
392 pathCur));
393 pathCur.clear();
394 }
395 }
396 }
397#endif // __LINUX__
398
399 return dlls;
400}
401
da55d064
VZ
402#endif // wxUSE_DYNLIB_CLASS
403