summaryrefslogtreecommitdiffstats
path: root/src/java/com/jogamp/common/os/DynamicLibraryBundle.java
blob: 0f5ea8f6abe653c4bb900a229fb7c85475ceac48 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
/**
 * Copyright 2010 JogAmp Community. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification, are
 * permitted provided that the following conditions are met:
 *
 *    1. Redistributions of source code must retain the above copyright notice, this list of
 *       conditions and the following disclaimer.
 *
 *    2. Redistributions in binary form must reproduce the above copyright notice, this list
 *       of conditions and the following disclaimer in the documentation and/or other materials
 *       provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY JogAmp Community ``AS IS'' AND ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
 * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JogAmp Community OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * The views and conclusions contained in the software and documentation are those of the
 * authors and should not be interpreted as representing official policies, either expressed
 * or implied, of JogAmp Community.
 */

package com.jogamp.common.os;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;

import com.jogamp.common.jvm.JNILibLoaderBase;
import com.jogamp.common.util.RunnableExecutor;

/**
 * Provides bundling of:<br>
 * <ul>
 * <li>The to-be-glued native library, eg OpenGL32.dll. From here on this is referred as the Tool.</li>
 * <li>The JNI glue-code native library, eg jogl_desktop.dll. From here on this is referred as the Glue</li>
 * </ul>
 * <p>
 * An {@link DynamicLibraryBundleInfo} instance is being passed in the constructor,
 * providing the required information about the tool and glue libraries.
 * The ClassLoader of it's implementation is also being used to help locating the native libraries.
 * </p>
 * An instance provides a complete {@link com.jogamp.common.os.DynamicLookupHelper}
 * to {@link com.jogamp.gluegen.runtime.ProcAddressTable#reset(com.jogamp.common.os.DynamicLookupHelper) reset}
 * the {@link com.jogamp.gluegen.runtime.ProcAddressTable}.<br>
 * At construction, it:
 * <ul>
 *  <li> loads the Tool native library via
 *       {@link com.jogamp.common.os.NativeLibrary#open(java.lang.String, java.lang.ClassLoader, boolean) NativeLibrary's open method}</li>
 *  <li> loads the {@link com.jogamp.common.jvm.JNILibLoaderBase#loadLibrary(java.lang.String, java.lang.String[], boolean, ClassLoader)  Glue native library}</li>
 *  <li> resolves the Tool's {@link com.jogamp.common.os.DynamicLibraryBundleInfo#getToolGetProcAddressFuncNameList() GetProcAddress}. (optional)</li>
 * </ul>
 */
public class DynamicLibraryBundle implements DynamicLookupHelper {
    private final DynamicLibraryBundleInfo info;

    protected final List<NativeLibrary> nativeLibraries;
    private final List<List<String>> toolLibNames;
    private final List<String> glueLibNames;
    private final boolean[] toolLibLoaded;

    private int toolLibLoadedNumber;

    private final boolean[] glueLibLoaded;
    private int glueLibLoadedNumber;

    private long toolGetProcAddressHandle;
    private boolean toolGetProcAddressComplete;
    private HashSet<String> toolGetProcAddressFuncNameSet;
    private final List<String> toolGetProcAddressFuncNameList;

    /** Returns an AWT-EDT {@link RunnableExecutor} implementation if AWT is available, otherwise {@link RunnableExecutor#currentThreadExecutor}. */
    public static RunnableExecutor getDefaultRunnableExecutor() {
        return RunnableExecutor.currentThreadExecutor;
    }

    /**
     * Instantiates and loads all {@link NativeLibrary}s incl. JNI libraries.
     * <p>
     * The ClassLoader of the {@link DynamicLibraryBundleInfo} implementation class
     * is being used to help locating the native libraries.
     * </p>
     */
    public DynamicLibraryBundle(final DynamicLibraryBundleInfo info) {
        if(null==info) {
            throw new RuntimeException("Null DynamicLibraryBundleInfo");
        }
        this.info = info;
        if(DEBUG) {
            System.err.println(Thread.currentThread().getName()+" - DynamicLibraryBundle.init start with: "+info.getClass().getName());
        }
        nativeLibraries = new ArrayList<NativeLibrary>();
        toolLibNames = info.getToolLibNames();
        glueLibNames = info.getGlueLibNames();
        toolLibLoaded = new boolean[toolLibNames.size()];
        if(DEBUG) {
            if( toolLibNames.size() == 0 ) {
                System.err.println("No Tool native library names given");
            }

            if( glueLibNames.size() == 0 ) {
                System.err.println("No Glue native library names given");
            }
        }

        for(int i=toolLibNames.size()-1; i>=0; i--) {
            toolLibLoaded[i] = false;
        }
        glueLibLoaded = new boolean[glueLibNames.size()];
        for(int i=glueLibNames.size()-1; i>=0; i--) {
            glueLibLoaded[i] = false;
        }

        info.getLibLoaderExecutor().invoke(true, new Runnable() {
                @Override
                public void run() {
                    loadLibraries();
                } } ) ;

        toolGetProcAddressFuncNameList = info.getToolGetProcAddressFuncNameList();
        if( null != toolGetProcAddressFuncNameList ) {
            toolGetProcAddressFuncNameSet = new HashSet<String>(toolGetProcAddressFuncNameList);
            toolGetProcAddressHandle = getToolGetProcAddressHandle();
            toolGetProcAddressComplete = 0 != toolGetProcAddressHandle;
        } else {
            toolGetProcAddressFuncNameSet = new HashSet<String>();
            toolGetProcAddressHandle = 0;
            toolGetProcAddressComplete = true;
        }
        if(DEBUG) {
            System.err.println("DynamicLibraryBundle.init Summary: "+info.getClass().getName());
            System.err.println("     toolGetProcAddressFuncNameList: "+toolGetProcAddressFuncNameList+", complete: "+toolGetProcAddressComplete+", 0x"+Long.toHexString(toolGetProcAddressHandle));
            System.err.println("     Tool Lib Names : "+toolLibNames);
            System.err.println("     Tool Lib Loaded: "+getToolLibLoadedNumber()+"/"+getToolLibNumber()+" "+Arrays.toString(toolLibLoaded)+", complete "+isToolLibComplete());
            System.err.println("     Glue Lib Names : "+glueLibNames);
            System.err.println("     Glue Lib Loaded: "+getGlueLibLoadedNumber()+"/"+getGlueLibNumber()+" "+Arrays.toString(glueLibLoaded)+", complete "+isGlueLibComplete());
            System.err.println("     All Complete: "+isLibComplete());
            System.err.println("     LibLoaderExecutor: "+info.getLibLoaderExecutor().getClass().getName());
        }
    }

    /** Unload all {@link NativeLibrary}s, and remove all references. */
    public final void destroy() {
        if(DEBUG) {
            System.err.println(Thread.currentThread().getName()+" - DynamicLibraryBundle.destroy() START: "+info.getClass().getName());
        }
        toolGetProcAddressFuncNameSet = null;
        toolGetProcAddressHandle = 0;
        toolGetProcAddressComplete = false;
        for(int i = 0; i<nativeLibraries.size(); i++) {
            nativeLibraries.get(i).close();
        }
        nativeLibraries.clear();
        toolLibNames.clear();
        glueLibNames.clear();
        if(DEBUG) {
            System.err.println(Thread.currentThread().getName()+" - DynamicLibraryBundle.destroy() END: "+info.getClass().getName());
        }
    }

    public final boolean isLibComplete() {
        return isToolLibComplete() && isGlueLibComplete() ;
    }

    public final int getToolLibNumber() {
        return toolLibNames.size();
    }

    public final int getToolLibLoadedNumber() {
        return toolLibLoadedNumber;
    }

    /**
     * @return true if all tool libraries are loaded,
     *         otherwise false.
     *
     * @see DynamicLibraryBundleInfo#getToolLibNames()
     */
    public final boolean isToolLibComplete() {
        return toolGetProcAddressComplete && getToolLibNumber() == getToolLibLoadedNumber();
    }

    public final boolean isToolLibLoaded() {
        return 0 < toolLibLoadedNumber;
    }

    public final boolean isToolLibLoaded(final int i) {
        if(0 <= i && i < toolLibLoaded.length) {
            return toolLibLoaded[i];
        }
        return false;
    }

    public final int getGlueLibNumber() {
        return glueLibNames.size();
    }

    public final int getGlueLibLoadedNumber() {
        return glueLibLoadedNumber;
    }

    /**
     * @return true if the last entry has been loaded,
     *         while ignoring the preload dependencies.
     *         Otherwise false.
     *
     * @see DynamicLibraryBundleInfo#getGlueLibNames()
     */
    public final boolean isGlueLibComplete() {
        return 0 == getGlueLibNumber() || isGlueLibLoaded(getGlueLibNumber() - 1);
    }

    public final boolean isGlueLibLoaded(final int i) {
        if(0 <= i && i < glueLibLoaded.length) {
            return glueLibLoaded[i];
        }
        return false;
    }

    public final DynamicLibraryBundleInfo getBundleInfo() { return info; }

    protected final long getToolGetProcAddressHandle() {
        if(!isToolLibLoaded()) {
            return 0;
        }
        long aptr = 0;
        for (int i=0; i < toolGetProcAddressFuncNameList.size(); i++) {
            final String name = toolGetProcAddressFuncNameList.get(i);
            aptr = dynamicLookupFunctionOnLibs(name);
            if(DEBUG) {
                System.err.println("getToolGetProcAddressHandle: "+name+" -> 0x"+Long.toHexString(aptr));
            }
        }
        return aptr;
    }

    protected final NativeLibrary loadFirstAvailable(final List<String> libNames, final ClassLoader loader, final boolean global) {
        for (int i=0; i < libNames.size(); i++) {
            final NativeLibrary lib = NativeLibrary.open(libNames.get(i), loader, global);
            if (lib != null) {
                return lib;
            }
        }
        return null;
    }

    final void loadLibraries() {
        int i;
        toolLibLoadedNumber = 0;
        final ClassLoader cl = info.getClass().getClassLoader();
        NativeLibrary lib = null;

        for (i=0; i < toolLibNames.size(); i++) {
            final List<String> libNames = toolLibNames.get(i);
            if( null != libNames && libNames.size() > 0 ) {
                lib = loadFirstAvailable(libNames, cl, info.shallLinkGlobal());
                if ( null == lib ) {
                    if(DEBUG) {
                        System.err.println("Unable to load any Tool library of: "+libNames);
                    }
                } else {
                    nativeLibraries.add(lib);
                    toolLibLoaded[i]=true;
                    toolLibLoadedNumber++;
                    if(DEBUG) {
                        System.err.println("Loaded Tool library: "+lib);
                    }
                }
            }
        }
        if( toolLibNames.size() > 0 && !isToolLibLoaded() ) {
            if(DEBUG) {
                System.err.println("No Tool libraries loaded");
            }
            return;
        }

        glueLibLoadedNumber = 0;
        for (i=0; i < glueLibNames.size(); i++) {
            final String libName = glueLibNames.get(i);
            final boolean ignoreError = true;
            boolean res;
            try {
                res = GlueJNILibLoader.loadLibrary(libName, ignoreError, cl);
                if(DEBUG && !res) {
                    System.err.println("Info: Could not load JNI/Glue library: "+libName);
                }
            } catch (final UnsatisfiedLinkError e) {
                res = false;
                if(DEBUG) {
                    System.err.println("Unable to load JNI/Glue library: "+libName);
                    e.printStackTrace();
                }
            }
            glueLibLoaded[i] = res;
            if(res) {
                glueLibLoadedNumber++;
            }
        }
    }

    private final long dynamicLookupFunctionOnLibs(final String funcName) {
        if(!isToolLibLoaded() || null==funcName) {
            if(DEBUG_LOOKUP && !isToolLibLoaded()) {
                System.err.println("Lookup-Native: <" + funcName + "> ** FAILED ** Tool native library not loaded");
            }
            return 0;
        }
        long addr = 0;
        NativeLibrary lib = null;

        if( info.shallLookupGlobal() ) {
            // Try a global symbol lookup first ..
            addr = NativeLibrary.dynamicLookupFunctionGlobal(funcName);
        }
        // Look up this function name in all known libraries
        for (int i=0; 0==addr && i < nativeLibraries.size(); i++) {
            lib = nativeLibraries.get(i);
            addr = lib.dynamicLookupFunction(funcName);
        }
        if(DEBUG_LOOKUP) {
            final String libName = ( null == lib ) ? "GLOBAL" : lib.toString();
            if(0!=addr) {
                System.err.println("Lookup-Native: <" + funcName + "> 0x" + Long.toHexString(addr) + " in lib " + libName );
            } else {
                System.err.println("Lookup-Native: <" + funcName + "> ** FAILED ** in libs " + nativeLibraries);
            }
        }
        return addr;
    }

    private final long toolDynamicLookupFunction(final String funcName) {
        if(0 != toolGetProcAddressHandle) {
            final long addr = info.toolGetProcAddress(toolGetProcAddressHandle, funcName);
            if(DEBUG_LOOKUP) {
                if(0!=addr) {
                    System.err.println("Lookup-Tool: <"+funcName+"> 0x"+Long.toHexString(addr));
                }
            }
            return addr;
        }
        return 0;
    }

    @Override
    public final long dynamicLookupFunction(final String funcName) {
        if(!isToolLibLoaded() || null==funcName) {
            if(DEBUG_LOOKUP && !isToolLibLoaded()) {
                System.err.println("Lookup: <" + funcName + "> ** FAILED ** Tool native library not loaded");
            }
            return 0;
        }

        if(toolGetProcAddressFuncNameSet.contains(funcName)) {
            return toolGetProcAddressHandle;
        }

        long addr = 0;
        final boolean useToolGetProcAdressFirst = info.useToolGetProcAdressFirst(funcName);

        if(useToolGetProcAdressFirst) {
            addr = toolDynamicLookupFunction(funcName);
        }
        if(0==addr) {
            addr = dynamicLookupFunctionOnLibs(funcName);
        }
        if(0==addr && !useToolGetProcAdressFirst) {
            addr = toolDynamicLookupFunction(funcName);
        }
        return addr;
    }

    @Override
    public final boolean isFunctionAvailable(final String funcName) {
        return 0 != dynamicLookupFunction(funcName);
    }

    /** Inherit access */
    static final class GlueJNILibLoader extends JNILibLoaderBase {
      protected static synchronized boolean loadLibrary(final String libname, final boolean ignoreError, final ClassLoader cl) {
        return JNILibLoaderBase.loadLibrary(libname, ignoreError, cl);
      }
    }
}