summaryrefslogtreecommitdiffstats
path: root/src/java/com/jogamp/common/os/NativeLibrary.java
blob: 3d8147939f91b23b57d6ecc1b0013d06085d00db (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
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
/*
 * Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
 * Copyright (c) 2011 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:
 * 
 * - Redistribution of source code must retain the above copyright
 *   notice, this list of conditions and the following disclaimer.
 * 
 * - Redistribution 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.
 * 
 * Neither the name of Sun Microsystems, Inc. or the names of
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * 
 * This software is provided "AS IS," without a warranty of any kind. ALL
 * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES,
 * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A
 * PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN
 * MICROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL NOT BE LIABLE FOR
 * ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR
 * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR
 * ITS LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR
 * DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE
 * DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY,
 * ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF
 * SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
 * 
 * You acknowledge that this software is not designed or intended for use
 * in the design, construction, operation or maintenance of any nuclear
 * facility.
 * 
 * Sun gratefully acknowledges that this software was originally authored
 * and developed by Kenneth Bradley Russell and Christopher John Kline.
 */

package com.jogamp.common.os;

import java.io.File;
import java.lang.reflect.Method;
import java.net.URISyntaxException;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.StringTokenizer;

import jogamp.common.os.BionicDynamicLinkerImpl;
import jogamp.common.os.MacOSXDynamicLinkerImpl;
import jogamp.common.os.PlatformPropsImpl;
import jogamp.common.os.PosixDynamicLinkerImpl;
import jogamp.common.os.WindowsDynamicLinkerImpl;

import com.jogamp.common.util.IOUtil;
import com.jogamp.common.util.cache.TempJarCache;

/** Provides low-level, relatively platform-independent access to
    shared ("native") libraries. The core library routines
    <code>System.load()</code> and <code>System.loadLibrary()</code>
    in general provide suitable functionality for applications using
    native code, but are not flexible enough to support certain kinds
    of glue code generation and deployment strategies. This class
    supports direct linking of native libraries to other shared
    objects not necessarily installed on the system (in particular,
    via the use of dlopen(RTLD_GLOBAL) on Unix platforms) as well as
    manual lookup of function names to support e.g. GlueGen's
    ProcAddressTable glue code generation style without additional
    supporting code needed in the generated library. */

public final class NativeLibrary implements DynamicLookupHelper {  
  private static final DynamicLinker dynLink;
  private static final String[] prefixes;
  private static final String[] suffixes;

  static {
    // Instantiate dynamic linker implementation
    switch (PlatformPropsImpl.OS_TYPE) {
      case WINDOWS:
        dynLink = new WindowsDynamicLinkerImpl();
        prefixes = new String[] { "" };
        suffixes = new String[] { ".dll" };
        break;
        
      case MACOS:
        dynLink = new MacOSXDynamicLinkerImpl();
        prefixes = new String[] { "lib" };
        suffixes = new String[] { ".dylib", ".jnilib" };
        break;

      case ANDROID:
        dynLink = new BionicDynamicLinkerImpl();
        prefixes = new String[] { "lib" };
        suffixes = new String[] { ".so" };
        break;
        
      /*
      case FREEBSD:
      case SUNOS:
      case HPUX: 
      case OPENKODE:         
      case LINUX: */
      default:
        dynLink = new PosixDynamicLinkerImpl();
        prefixes = new String[] { "lib" };
        suffixes = new String[] { ".so" };
        break;
    }
  }

  // Platform-specific representation for the handle to the open
  // library. This is an HMODULE on Windows and a void* (the result of
  // a dlopen() call) on Unix and Mac OS X platforms.
  private long libraryHandle;

  // May as well keep around the path to the library we opened
  private final String libraryPath;
  
  private final boolean global;

  // Private constructor to prevent arbitrary instances from floating around
  private NativeLibrary(long libraryHandle, String libraryPath, boolean global) {
    this.libraryHandle = libraryHandle;
    this.libraryPath   = libraryPath;
    this.global        = global;
    if (DEBUG) {
      System.err.println("NativeLibrary.open(): Successfully loaded: " + this);
    }
  }

  public final String toString() {
    return "NativeLibrary[" + libraryPath + ", 0x" + Long.toHexString(libraryHandle) + ", global " + global + "]";
  }

  /** Opens the given native library, assuming it has the same base
      name on all platforms, looking first in the system's search
      path, and in the context of the specified ClassLoader, which is
      used to help find the library in the case of e.g. Java Web Start. */
  public static final NativeLibrary open(String libName, ClassLoader loader) {
    return open(libName, libName, libName, true, loader, true);
  }

  /** Opens the given native library, assuming it has the same base
      name on all platforms, looking first in the system's search
      path, and in the context of the specified ClassLoader, which is
      used to help find the library in the case of e.g. Java Web Start. */
  public static final NativeLibrary open(String libName, ClassLoader loader, boolean global) {
    return open(libName, libName, libName, true, loader, global);
  }

  /** Opens the given native library, assuming it has the given base
      names (no "lib" prefix or ".dll/.so/.dylib" suffix) on the
      Windows, Unix and Mac OS X platforms, respectively, and in the
      context of the specified ClassLoader, which is used to help find
      the library in the case of e.g. Java Web Start. The
      searchSystemPathFirst argument changes the behavior to first
      search the default system path rather than searching it last.
      Note that we do not currently handle DSO versioning on Unix.
      Experience with JOAL and OpenAL has shown that it is extremely
      problematic to rely on a specific .so version (for one thing,
      ClassLoader.findLibrary on Unix doesn't work with files not
      ending in .so, for example .so.0), and in general if this
      dynamic loading facility is used correctly the version number
      will be irrelevant.
  */
  public static final NativeLibrary open(String windowsLibName,
                                         String unixLibName,
                                         String macOSXLibName,
                                         boolean searchSystemPathFirst,
                                         ClassLoader loader) {
    return open(windowsLibName, unixLibName, macOSXLibName, searchSystemPathFirst, loader, true);
  }

  public static final NativeLibrary open(String windowsLibName,
                                         String unixLibName,
                                         String macOSXLibName,
                                         boolean searchSystemPathFirst,
                                         ClassLoader loader, boolean global) {
    List<String> possiblePaths = enumerateLibraryPaths(windowsLibName,
                                                       unixLibName,
                                                       macOSXLibName,
                                                       searchSystemPathFirst,
                                                       loader);
    Platform.initSingleton(); // loads native gluegen-rt library
    // Iterate down these and see which one if any we can actually find.
    for (Iterator<String> iter = possiblePaths.iterator(); iter.hasNext(); ) {
        final String path = iter.next();
        if (DEBUG) {
            System.err.println("NativeLibrary.open(global "+global+"): Trying to load " + path);
        }
        long res;
        Throwable t = null;
        try {
            if(global) {
                res = dynLink.openLibraryGlobal(path, DEBUG);
            } else {
                res = dynLink.openLibraryLocal(path, DEBUG);
            }
        } catch (Throwable t1) {
            t = t1;
            res = 0;
        }
        if ( 0 != res ) {
            return new NativeLibrary(res, path, global);
        } else if( DEBUG ) {
            if( null != t ) {
                System.err.println("NativeLibrary.open: Catched "+t.getClass().getSimpleName()+": "+t.getMessage());
            }
            String errstr;
            try {
                errstr = dynLink.getLastError();
            } catch (Throwable t2) { errstr=null; }
            System.err.println("NativeLibrary.open: Last error "+errstr);
            if( null != t ) {
                t.printStackTrace();
            }
        }      
    }

    if (DEBUG) {
      System.err.println("NativeLibrary.open(global "+global+"): Did not succeed in loading (" + windowsLibName + ", " + unixLibName + ", " + macOSXLibName + ")");
    }

    // For now, just return null to indicate the open operation didn't
    // succeed (could also throw an exception if we could tell which
    // of the openLibrary operations actually failed)
    return null;
  }

  @Override
  public final long dynamicLookupFunction(String funcName) {
    if ( 0 == libraryHandle ) {
      throw new RuntimeException("Library is not open");
    }
    return dynLink.lookupSymbol(libraryHandle, funcName);
  }

  @Override
  public final boolean isFunctionAvailable(String funcName) {
    if ( 0 == libraryHandle ) {
      throw new RuntimeException("Library is not open");
    }
    return 0 != dynLink.lookupSymbol(libraryHandle, funcName);
  }

  /** Looks up the given function name in all loaded libraries. */
  public static final long dynamicLookupFunctionGlobal(String funcName) {
    return dynLink.lookupSymbolGlobal(funcName);
  }

  /** Looks up the given function name in all loaded libraries. */
  public static final boolean isFunctionAvailableGlobal(String funcName) {
    return 0 != dynLink.lookupSymbolGlobal(funcName);
  }

  /** Retrieves the low-level library handle from this NativeLibrary
      object. On the Windows platform this is an HMODULE, and on Unix
      and Mac OS X platforms the void* result of calling dlopen(). */
  public final long getLibraryHandle() {
    return libraryHandle;
  }

  /** Retrieves the path under which this library was opened. */
  public final String getLibraryPath() {
    return libraryPath;
  }

  /** Closes this native library. Further lookup operations are not
      allowed after calling this method. */
  public final void close() {
    if (DEBUG) {
      System.err.println("NativeLibrary.close(): closing " + this);
    }
    if ( 0 == libraryHandle ) {
      throw new RuntimeException("Library already closed");
    }
    long handle = libraryHandle;
    libraryHandle = 0;
    dynLink.closeLibrary(handle);
    if (DEBUG) {
      System.err.println("NativeLibrary.close(): Successfully closed " + this);
      Thread.dumpStack();
    }
  }

  /**
   * Comparison of prefix and suffix of the given libName's basename
   * is performed case insensitive <br>
   *  
   * @param libName the full path library name with prefix and suffix 
   * @param isLowerCaseAlready indicates if libName is already lower-case
   * 
   * @return basename of libName w/o path, ie. /usr/lib/libDrinkBeer.so -> DrinkBeer on Unix systems, but null on Windows.
   */
  public static final String isValidNativeLibraryName(String libName, boolean isLowerCaseAlready) {
    final String libBaseName;
    try {
        libBaseName = IOUtil.getBasename(libName);
    } catch (URISyntaxException uriEx) {
        throw new IllegalArgumentException(uriEx);
    }
    final String libBaseNameLC = isLowerCaseAlready ? libBaseName : libBaseName.toLowerCase();
    int prefixIdx = -1;
    for(int i=0; i<prefixes.length && 0 > prefixIdx; i++) {    
        if (libBaseNameLC.startsWith(prefixes[i])) {
            prefixIdx = i;
        }
    }
    if( 0 <= prefixIdx ) {
        for(int i=0; i<suffixes.length; i++) {
            if (libBaseNameLC.endsWith(suffixes[i])) {
                final int s = prefixes[prefixIdx].length();
                final int e = suffixes[i].length();
                return libBaseName.substring(s, libBaseName.length()-e);
            }
        }
    }
    return null;  
  }
  
  /** Given the base library names (no prefixes/suffixes) for the
      various platforms, enumerate the possible locations and names of
      the indicated native library on the system. */
  public static final List<String> enumerateLibraryPaths(final String windowsLibName,
                                                   final String unixLibName,
                                                   final String macOSXLibName,
                                                   final boolean searchSystemPathFirst,
                                                   final ClassLoader loader) {
    List<String> paths = new ArrayList<String>();
    String libName = selectName(windowsLibName, unixLibName, macOSXLibName);
    if (libName == null) {
      return paths;
    }

    // Allow user's full path specification to override our building of paths
    File file = new File(libName);
    if (file.isAbsolute()) {
        paths.add(libName);
        return paths;
    }

    String[] baseNames = buildNames(libName);

    if (searchSystemPathFirst) {
      // Add just the library names to use the OS's search algorithm
      for (int i = 0; i < baseNames.length; i++) {
        paths.add(baseNames[i]);
      }
    }

    // The idea to ask the ClassLoader to find the library is borrowed
    // from the LWJGL library
    final String clPath = findLibrary(libName, loader);
    if (clPath != null) {
      paths.add(clPath);
    }

    // Add entries from java.library.path
    final String[] javaLibraryPaths =
      AccessController.doPrivileged(new PrivilegedAction<String[]>() {
          public String[] run() {
            int count = 0;
            final String usrPath = System.getProperty("java.library.path");
            if(null != usrPath) {
                count++;
            }
            final String sysPath = System.getProperty("sun.boot.library.path");
            if(null != sysPath) {
                count++;
            }
            final String[] res = new String[count];
            int i=0;
            if (searchSystemPathFirst) {
                if(null != sysPath) {
                    res[i++] = sysPath;
                }                            
            }
            if(null != usrPath) {
                res[i++] = usrPath;
            }
            if (!searchSystemPathFirst) {
                if(null != sysPath) {
                    res[i++] = sysPath;
                }                            
            }
            return res;
          }
        });
    if ( null != javaLibraryPaths ) {
        for( int i=0; i < javaLibraryPaths.length; i++ ) {
            final StringTokenizer tokenizer = new StringTokenizer(javaLibraryPaths[i], File.pathSeparator);
            while (tokenizer.hasMoreTokens()) {
                addPaths(tokenizer.nextToken(), baseNames, paths);
            }
        }
    }

    // Add current working directory
    String userDir =
      AccessController.doPrivileged(new PrivilegedAction<String>() {
          public String run() {
            return System.getProperty("user.dir");
          }
        });
    addPaths(userDir, baseNames, paths);

    if (!searchSystemPathFirst) {
      // Add just the library names to use the OS's search algorithm
      for (int i = 0; i < baseNames.length; i++) {
        paths.add(baseNames[i]);
      }
    }

    // Add probable Mac OS X-specific paths
    if (PlatformPropsImpl.OS_TYPE == Platform.OSType.MACOS) {
      // Add historical location
      addPaths("/Library/Frameworks/" + libName + ".Framework", baseNames, paths);
      // Add current location
      addPaths("/System/Library/Frameworks/" + libName + ".Framework", baseNames, paths);
    }
    
    return paths;
  }


  private static final String selectName(String windowsLibName,
                                   String unixLibName,
                                   String macOSXLibName) {
    switch (PlatformPropsImpl.OS_TYPE) {
      case WINDOWS:
        return windowsLibName;
        
      case MACOS:
        return macOSXLibName;

      /*
      case FREEBSD:
      case DALVIK:
      case SUNOS:
      case HPUX: 
      case OPENKODE:         
      case LINUX: */
      default:
        return unixLibName;
    }
  }

  private static final String[] buildNames(String libName) {
      // If the library name already has the prefix / suffix added
      // (principally because we want to force a version number on Unix
      // operating systems) then just return the library name.
      final String libBaseNameLC;
      try {
          libBaseNameLC = IOUtil.getBasename(libName).toLowerCase();
      } catch (URISyntaxException uriEx) {
          throw new IllegalArgumentException(uriEx);
      }
      
      int prefixIdx = -1;
      for(int i=0; i<prefixes.length && 0 > prefixIdx; i++) {    
          if (libBaseNameLC.startsWith(prefixes[i])) {
              prefixIdx = i;
          }
      }
      if( 0 <= prefixIdx ) {
          for(int i=0; i<suffixes.length; i++) {
              if (libBaseNameLC.endsWith(suffixes[i])) {
                  return new String[] { libName };
              }
          }
          int suffixIdx = -1;
          for(int i=0; i<suffixes.length && 0 > suffixIdx; i++) {
              suffixIdx = libBaseNameLC.indexOf(suffixes[i]);
          }
          boolean ok = true;
          if (suffixIdx >= 0) {
              // Check to see if everything after it is a Unix version number
              for (int i = suffixIdx + suffixes[0].length();
                      i < libName.length();
                      i++) {
                  char c = libName.charAt(i);
                  if (!(c == '.' || (c >= '0' && c <= '9'))) {
                      ok = false;
                      break;
                  }
              }
              if (ok) {
                  return new String[] { libName };
              }
          }
      }

      String[] res = new String[prefixes.length * suffixes.length + 
                                ( PlatformPropsImpl.OS_TYPE == Platform.OSType.MACOS ? 1 : 0 )];
      int idx = 0;
      for (int i = 0; i < prefixes.length; i++) {
          for (int j = 0; j < suffixes.length; j++) {
              res[idx++] = prefixes[i] + libName + suffixes[j];
          }
      }
      if (PlatformPropsImpl.OS_TYPE == Platform.OSType.MACOS) {
          // Plain library-base-name in Framework folder
          res[idx++] = libName;
      }
      return res;
  }

  private static final void addPaths(String path, String[] baseNames, List<String> paths) {
    for (int j = 0; j < baseNames.length; j++) {
      paths.add(path + File.separator + baseNames[j]);
    }
  }

  private static boolean initializedFindLibraryMethod = false;
  private static Method  findLibraryMethod = null;
  private static final String findLibraryImpl(final String libName, final ClassLoader loader) {
    if (loader == null) {
      return null;
    }
    if (!initializedFindLibraryMethod) {
      AccessController.doPrivileged(new PrivilegedAction<Object>() {
          public Object run() {
            try {
              findLibraryMethod = ClassLoader.class.getDeclaredMethod("findLibrary",
                                                                      new Class[] { String.class });
              findLibraryMethod.setAccessible(true);
            } catch (Exception e) {
              // Fail silently disabling this functionality
            }
            initializedFindLibraryMethod = true;
            return null;
          }
        });
    }
    if (findLibraryMethod != null) {
      try {
        return AccessController.doPrivileged(new PrivilegedAction<String>() {
            public String run() {
              try {
                return (String) findLibraryMethod.invoke(loader, new Object[] { libName });
              } catch (Exception e) {
                throw new RuntimeException(e);
              }
            }
          });
      } catch (Exception e) {
        if (DEBUG) {
          e.printStackTrace();
        }
        // Fail silently and continue with other search algorithms
      }
    }
    return null;
  }
  public static final String findLibrary(final String libName, final ClassLoader loader) {
    String res = null;
    if(TempJarCache.isInitialized()) {
        res = TempJarCache.findLibrary(libName);
        if (DEBUG) {
          System.err.println("NativeLibrary.findLibrary(<"+libName+">) (TempJarCache): "+res);
        }
    }
    if(null == res) {
        res = findLibraryImpl(libName, loader);
        if (DEBUG) {
          System.err.println("NativeLibrary.findLibrary(<"+libName+">, "+loader+") (CL): "+res);
        }
    }
    return res;
  }
}