| 1 |
{ |
| 2 |
Copyright 2003-2023 Michalis Kamburelis. |
| 3 |
|
| 4 |
This file is part of "Castle Game Engine". |
| 5 |
|
| 6 |
"Castle Game Engine" is free software; see the file COPYING.txt, |
| 7 |
included in this distribution, for details about the copyright. |
| 8 |
|
| 9 |
"Castle Game Engine" is distributed in the hope that it will be useful, |
| 10 |
but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 11 |
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| 12 |
|
| 13 |
---------------------------------------------------------------------------- |
| 14 |
} |
| 15 |
|
| 16 |
{ Dynamic libraries loading (TDynLib). } |
| 17 |
unit CastleDynLib; |
| 18 |
|
| 19 |
{$I castleconf.inc} |
| 20 |
|
| 21 |
interface |
| 22 |
|
| 23 |
uses SysUtils |
| 24 |
{$ifdef FPC} |
| 25 |
{ With FPC, use cross-platform DynLibs unit. } |
| 26 |
, DynLibs |
| 27 |
{$else} |
| 28 |
{ With Delphi, use Windows functions directly. |
| 29 |
On non-Windows, Delphi SysUtils defines compatible functions |
| 30 |
LoadLibrary, FreeLibrary, GetProcAddress |
| 31 |
(note: using PChar, not PAnsiChar) and HMODULE type. } |
| 32 |
{$ifdef MSWINDOWS} , Windows {$endif} |
| 33 |
{$endif}; |
| 34 |
|
| 35 |
type |
| 36 |
TDynLibHandle = {$ifdef FPC} TLibHandle {$else} HModule {$endif}; |
| 37 |
|
| 38 |
const |
| 39 |
{ Invalid TDynLibHandle value (meaning : LoadLibrary failed) } |
| 40 |
InvalidDynLibHandle: TDynLibHandle = {$ifdef FPC} DynLibs.NilHandle {$else} 0 {$endif}; |
| 41 |
|
| 42 |
type |
| 43 |
{ } |
| 44 |
EDynLibError = class(Exception); |
| 45 |
|
| 46 |
TDynLibSymbolError = (seRaise, seReturnNil, seWarnAndReturnNil); |
| 47 |
|
| 48 |
(*Load functions from dynamic libraries. |
| 49 |
|
| 50 |
This class allows to load functions from dynamic libraries (.dll on Windows, |
| 51 |
.so on most Unix platforms, .dylib on macOS and iOS). |
| 52 |
|
| 53 |
Features: |
| 54 |
|
| 55 |
@unorderedList( |
| 56 |
@item(The @link(Load) and @link(Symbol) functions |
| 57 |
@italic(by default do error checking) (and raise necessary exceptions).) |
| 58 |
|
| 59 |
@item(The field SymbolError allows to |
| 60 |
specify @italic(once for all subsequent Symbol calls) |
| 61 |
what error checking we want. |
| 62 |
Default is to check errors and raise exceptions. |
| 63 |
There is also a very usefull value reWarnAndContinue: |
| 64 |
it allows you to run program @italic(once) and see all symbols that |
| 65 |
are missing from dynamic library.) |
| 66 |
|
| 67 |
@item(The interface of this is OS-independent and works for |
| 68 |
both FPC and Delphi.) |
| 69 |
) |
| 70 |
|
| 71 |
Typical usage: |
| 72 |
|
| 73 |
@longCode(# |
| 74 |
var |
| 75 |
ALLibrary: TDynLib = nil; |
| 76 |
initialization |
| 77 |
ALLibrary := TDynLib.Load('libopenal.so.1'); |
| 78 |
{ ... some calls to ALLibrary.Symbol() ... } |
| 79 |
finalization |
| 80 |
FreeAndNil(ALLibrary); |
| 81 |
end. |
| 82 |
#) |
| 83 |
|
| 84 |
It is important that ALLibrary is initialized to nil and that in finalization |
| 85 |
you use FreeAndNil. This allows you to exit gracefully if library does not |
| 86 |
exist on the system and @link(Load) will raise an exception: ALLibrary will |
| 87 |
stay then as nil. |
| 88 |
*) |
| 89 |
TDynLib = class |
| 90 |
private |
| 91 |
{ In this class, we always have a valid FHandle. } |
| 92 |
FHandle: TDynLibHandle; |
| 93 |
FName: string; |
| 94 |
FSymbolError: TDynLibSymbolError; |
| 95 |
public |
| 96 |
{ Standard constructor, requires a valid TDynLibHandle already. |
| 97 |
Usually you will prefer to use @link(Load) method instead of |
| 98 |
directly calling this constructor. |
| 99 |
|
| 100 |
@raises(ECheckFailed if you supply invalid handle.) } |
| 101 |
constructor Create(const AName: string; AHandle: TDynLibHandle); |
| 102 |
destructor Destroy; override; |
| 103 |
|
| 104 |
{ Name of the library to link to. In practice, file name of the *.so |
| 105 |
or *.dylib or *.dll file. |
| 106 |
|
| 107 |
A precise strategy where this library is searched |
| 108 |
is specific to a platform, see the semantics of SysUtils.LoadLibrary |
| 109 |
(DynLibs for FPC) call on given OS. } |
| 110 |
property Name: string read FName; |
| 111 |
|
| 112 |
{ Link to a dynamic library specified by Name. Returns created |
| 113 |
TDynLib instance. |
| 114 |
|
| 115 |
If the library is not found and RaiseExceptionOnError is @false, |
| 116 |
@nil will be returned. |
| 117 |
If RaiseExceptionOnError is @true then EDynLibError will be raised |
| 118 |
in case library is not found. |
| 119 |
So if RaiseExceptionOnError is @true, @nil is |
| 120 |
never returned. |
| 121 |
|
| 122 |
Note that the default situation prevents from unintentionally ignoring |
| 123 |
an error and @italic(that's good). |
| 124 |
|
| 125 |
@raises(EDynLibError If library not found and RaiseExceptionOnError |
| 126 |
is @true.) } |
| 127 |
class function Load(const AName: string; RaiseExceptionOnError: boolean = true): TDynLib; |
| 128 |
|
| 129 |
{ What happens when @link(Symbol) fails. } |
| 130 |
property SymbolError: TDynLibSymbolError |
| 131 |
read FSymbolError write FSymbolError default seRaise; |
| 132 |
|
| 133 |
{ Return address of given symbol (function name etc.) from loaded dynamic |
| 134 |
library. If the symbol doesn't exist, then SymbolError |
| 135 |
says what happens: |
| 136 |
|
| 137 |
@unorderedList( |
| 138 |
@item(seRaise (default), then EDynLibError will be raised.) |
| 139 |
@item(seReturnNil, then return @nil (and continue, ignoring error).) |
| 140 |
@item(seWarnAndReturnNil, then write warning (using WarningWrite) |
| 141 |
and return @nil (and continue, ignoring error). |
| 142 |
|
| 143 |
This is useful for debugging : you can easily open the library and after |
| 144 |
one run of the program you can see what symbols (that you requested) |
| 145 |
were missing from the library. This is useful when you have a library |
| 146 |
but you are not sure whether it is compatible and contains all the |
| 147 |
symbols that you want.) |
| 148 |
) |
| 149 |
|
| 150 |
@raises(EDynLibError If SymbolName doesn't exist and |
| 151 |
SymbolError is seRaise.) |
| 152 |
|
| 153 |
} |
| 154 |
function Symbol(const SymbolName: PChar): Pointer; |
| 155 |
end; |
| 156 |
|
| 157 |
var |
| 158 |
{ Disable all dynamic libraries loading. |
| 159 |
All TDynLib.Load calls will return InvalidDynLibHandle. |
| 160 |
This is useful: |
| 161 |
|
| 162 |
@orderedList( |
| 163 |
@item(For testing purposes. CGE applications should gracefully work |
| 164 |
even without various dynamic libraries. |
| 165 |
E.g. without OpenAL library, no sound is played. |
| 166 |
Without LibPng we use PNG internal implementation using FpImage. |
| 167 |
) |
| 168 |
|
| 169 |
@item(By the build tool. Commands like "castle-engine compile" |
| 170 |
and "castle-engine clear" want to delete/override dll files, |
| 171 |
but it is impossible on Windows, because the build tool would use dll |
| 172 |
files in the project's directory. |
| 173 |
|
| 174 |
The build tool doesn't need dynamic libraries for anything, |
| 175 |
but some code pulled by dependencies could accidentally load them. |
| 176 |
E.g. OpenAL unit loads it in initialization. |
| 177 |
) |
| 178 |
) |
| 179 |
} |
| 180 |
InternalDisableDynamicLibraries: Boolean = false; |
| 181 |
|
| 182 |
implementation |
| 183 |
|
| 184 |
uses CastleUtils, CastleLog; |
| 185 |
|
| 186 |
constructor TDynLib.Create(const AName: string; AHandle: TDynLibHandle); |
| 187 |
begin |
| 188 |
inherited Create; |
| 189 |
FName := AName; |
| 190 |
FHandle := AHandle; |
| 191 |
Check(AHandle <> InvalidDynLibHandle, |
| 192 |
'TDynLib can not be created with invalid DynLibHandle'); |
| 193 |
SymbolError := seRaise; |
| 194 |
end; |
| 195 |
|
| 196 |
destructor TDynLib.Destroy; |
| 197 |
begin |
| 198 |
{ Delphi on Posix (Linux) implementation of FreeLibrary has a trivial error: |
| 199 |
It returns "Result := LongBool(dlclose(Module));" which is the opposite |
| 200 |
of what it should return, because dlclose returns 0 on success. |
| 201 |
|
| 202 |
But FreeLibrary should return True on success, False on failure, |
| 203 |
Delphi evidently wanted it to be consistent with FreeLibrary |
| 204 |
on WinAPI ( https://learn.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-freelibrary ) |
| 205 |
that has "If the function succeeds, the return value is nonzero". |
| 206 |
|
| 207 |
So Delphi FreeLibrary should be fixed to report |
| 208 |
"Result := dlclose(Module) = 0;" |
| 209 |
Reported to Embarcadero: https://quality.embarcadero.com/browse/RSP-44047 |
| 210 |
} |
| 211 |
{$if (not defined(FPC)) and (not defined(MSWINDOWS))} |
| 212 |
{$define IGNORE_FREE_LIBRARY_ERRORS} |
| 213 |
{$endif} |
| 214 |
|
| 215 |
{$ifdef IGNORE_FREE_LIBRARY_ERRORS} |
| 216 |
FreeLibrary(FHandle); |
| 217 |
{$else} |
| 218 |
if not FreeLibrary(FHandle) then |
| 219 |
WriteLnWarning('Unloading library ' + Name + ' failed'); |
| 220 |
{$endif} |
| 221 |
|
| 222 |
inherited; |
| 223 |
end; |
| 224 |
|
| 225 |
class function TDynLib.Load(const AName: string; RaiseExceptionOnError: boolean): TDynLib; |
| 226 |
|
| 227 |
{ On Unix, right now this simply uses LoadLibrary that calls dlopen(..., RTLD_LAZY) |
| 228 |
(see in FPC rtl/unix/dynlibs.inc). |
| 229 |
|
| 230 |
Historic notes: |
| 231 |
|
| 232 |
- Long time ago we used here explicit |
| 233 |
dlopen(.., RTLD_LAZY or RTLD_GLOBAL) |
| 234 |
Reasons: loading GLU under Linux required RTLD_GLOBAL |
| 235 |
(Maybe GLU requires that someone else loads GL symbols for it?) |
| 236 |
|
| 237 |
Later, this workaround doesn't seem needed anymore, |
| 238 |
and we actually don't load GLU using CastleDynLib. |
| 239 |
|
| 240 |
- Note that on Android, RTLD_GLOBAL *cannot* be used |
| 241 |
if you want to successfully open |
| 242 |
libopenal.so on Android (tested necessity on Nexus 5). |
| 243 |
And it seems that RTLD_NOW or RTLD_LAZY don't matter. |
| 244 |
Found thanks to mentions in |
| 245 |
http://grokbase.com/t/gg/android-ndk/133mh6mk8b/unable-to-dlopen-libtest-so-cannot-load-library-link-image-1995-failed-to-link-libtest-so |
| 246 |
|
| 247 |
In summary, simply using LoadLibrary is perfect now. |
| 248 |
} |
| 249 |
|
| 250 |
var |
| 251 |
Handle: TDynLibHandle; |
| 252 |
begin |
| 253 |
if InternalDisableDynamicLibraries then |
| 254 |
Handle := InvalidDynLibHandle |
| 255 |
else |
| 256 |
Handle := LoadLibrary(PChar(AName)); |
| 257 |
if Handle = InvalidDynLibHandle then |
| 258 |
begin |
| 259 |
if RaiseExceptionOnError then |
| 260 |
raise EDynLibError.Create('Cannot load dynamic library "' +AName+ '"') |
| 261 |
else |
| 262 |
Result := nil; |
| 263 |
end else |
| 264 |
Result := Self.Create(AName, Handle); |
| 265 |
end; |
| 266 |
|
| 267 |
function TDynLib.Symbol(const SymbolName: PChar): Pointer; |
| 268 |
|
| 269 |
function ErrStr: string; |
| 270 |
begin |
| 271 |
Result := 'Symbol "' + SymbolName + '" not found in library "' + Name + '"'; |
| 272 |
end; |
| 273 |
|
| 274 |
begin |
| 275 |
Result := GetProcAddress(FHandle, SymbolName); |
| 276 |
if Result = nil then |
| 277 |
case SymbolError of |
| 278 |
seRaise: raise EDynLibError.Create(ErrStr); |
| 279 |
seReturnNil: ; |
| 280 |
seWarnAndReturnNil: WarningWrite(ErrStr); |
| 281 |
{$ifndef COMPILER_CASE_ANALYSIS} |
| 282 |
else raise EInternalError.Create('SymbolError=?'); |
| 283 |
{$endif} |
| 284 |
end; |
| 285 |
end; |
| 286 |
|
| 287 |
end. |