001    // --- BEGIN LICENSE BLOCK ---
002    /* 
003     * Copyright (c) 2009, Mikio L. Braun
004     * All rights reserved.
005     * 
006     * Redistribution and use in source and binary forms, with or without
007     * modification, are permitted provided that the following conditions are
008     * met:
009     * 
010     *     * Redistributions of source code must retain the above copyright
011     *       notice, this list of conditions and the following disclaimer.
012     * 
013     *     * Redistributions in binary form must reproduce the above
014     *       copyright notice, this list of conditions and the following
015     *       disclaimer in the documentation and/or other materials provided
016     *       with the distribution.
017     * 
018     *     * Neither the name of the Technische Universit??t Berlin nor the
019     *       names of its contributors may be used to endorse or promote
020     *       products derived from this software without specific prior
021     *       written permission.
022     * 
023     * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
024     * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
025     * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
026     * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
027     * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
028     * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
029     * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
030     * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
031     * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
032     * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
033     * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
034     */
035    // --- END LICENSE BLOCK ---
036    package org.jblas.util;
037    
038    import java.io.*;
039    
040    /**
041     * Class which allows to load a dynamic file as resource (for example, from a 
042     * jar-file)
043     */
044    public class LibraryLoader {
045    
046        /**
047         * <p>Find the library <tt>libname</tt> as a resource, copy it to a tempfile
048         * and load it using System.load(). The name of the library has to be the
049         * base name, it is mapped to the corresponding system name using
050         * System.mapLibraryName(). For example, the library "foo" is called "libfoo.so"
051         * under Linux and "foo.dll" under Windows, but you just have to pass "foo"
052         * the loadLibrary().</p>
053         *
054         * <p>I'm not quite sure if this doesn't open all kinds of security holes. Any ideas?</p>
055         *
056         * <p>This function reports some more information to the "org.jblas" logger at
057         * the FINE level.</p>
058         *
059         * @param libname basename of the library
060         * @throws UnsatisfiedLinkError if library cannot be founds
061         */
062        public void loadLibrary(String libname, boolean withFlavor) {
063            String libpath;
064            Logger logger = Logger.getLogger();
065    
066            libname = System.mapLibraryName(libname);
067    
068            // We're in a static initializer and need a class. What shall we do?
069            Class cl = getClass();
070    
071            // Trying to copy from here.
072            logger.debug("Trying to copy from /" + libname + ".");
073            libpath = "/" + libname;
074            InputStream is = cl.getResourceAsStream("/" + libname);
075    
076            // Trying to copy from "bin"
077            if (is == null) {
078                logger.debug("Trying to copy from /bin/" + libname + ".");
079                libpath = "/bin/" + libname;
080                is = cl.getResourceAsStream(libpath);
081            }
082    
083            // Trying to extract static version from the jar file. Why the static version?
084            // Because it is more likely to run.
085            if (is == null) {
086                libpath = fatJarLibraryPath("static");
087                logger.debug("Trying to copy from " + libpath + ".");
088                is = cl.getResourceAsStream(libpath + libname);
089            }
090    
091            // Finally, let's see if we can get the dynamic version.
092            if (is == null) {
093                libpath = fatJarLibraryPath("dynamic");
094                logger.debug("Trying to copy from " + libpath + ".");
095                is = cl.getResourceAsStream(libpath + libname);
096            }
097    
098            // And then we do it again for the "Non-Unified" path name.
099            // The reason is that changes in the build process might lead to actually
100            // having "Windows Vista" or something in the path... .
101            if (is == null) {
102                libpath = fatJarLibraryPathNonUnified("static");
103                if (withFlavor) libpath = addFlavor(libpath);
104                logger.debug("Trying to copy from " + libpath + ".");
105                is = cl.getResourceAsStream(libpath + libname);
106            }
107    
108            // Finally, let's see if we can the static version with the unified
109            // path name.
110            if (is == null) {
111                libpath = fatJarLibraryPath("static");
112                if (withFlavor) libpath = addFlavor(libpath);
113                logger.debug("Trying to copy from " + libpath + ".");
114                is = cl.getResourceAsStream(libpath + libname);
115            }
116    
117            // Oh man, have to get out of here!
118            if (is == null) {
119                throw new UnsatisfiedLinkError("Couldn't find the resource " + libname + ".");
120            }
121    
122            logger.config("Loading " + libname + " from " + libpath + ".");
123    
124            try {
125                File tempfile = File.createTempFile("jblas", libname);
126                tempfile.deleteOnExit();
127                OutputStream os = new FileOutputStream(tempfile);
128    
129                logger.debug("tempfile.getPath() = " + tempfile.getPath());
130    
131                long savedTime = System.currentTimeMillis();
132    
133                byte buf[] = new byte[1024];
134                int len;
135                while ((len = is.read(buf)) > 0) {
136                    os.write(buf, 0, len);
137                }
138    
139                double seconds = (double) (System.currentTimeMillis() - savedTime) / 1e3;
140                logger.debug("Copying took " + seconds + " seconds.");
141    
142                os.close();
143    
144                System.load(tempfile.getPath());
145            } catch (IOException io) {
146                logger.error("Could not create the temp file: " + io.toString() + ".\n");
147            } catch (UnsatisfiedLinkError ule) {
148                logger.error("Couldn't load copied link file: " + ule.toString() + ".\n");
149            }
150        }
151    
152        static public String unifyOSName(String osname) {
153            if (osname.startsWith("Windows")) {
154                return "Windows";
155            }
156            return osname;
157        }
158    
159        /** Compute the path to the library. The path is basically
160        "/" + os.name + "/" + os.arch + "/" + libname. */
161        static public String fatJarLibraryPath(String linkage) {
162            String sep = "/"; //System.getProperty("file.separator");
163            String os_name = unifyOSName(System.getProperty("os.name"));
164            String os_arch = System.getProperty("os.arch");
165            String path = sep + "lib" + sep + linkage + sep + os_name + sep + os_arch + sep;
166            return path;
167        }
168    
169        static public String fatJarLibraryPathNonUnified(String linkage) {
170            String sep = "/"; //System.getProperty("file.separator");
171            String os_name = System.getProperty("os.name");
172            String os_arch = System.getProperty("os.arch");
173            String path = sep + "lib" + sep + linkage + sep + os_name + sep + os_arch + sep;
174            return path;
175        }
176    
177        static private String addFlavor(String path) {
178            String sep = "/";
179            String arch_flavor = ArchFlavor.archFlavor();
180            if (arch_flavor != null)
181                path += arch_flavor + sep;
182            return path;
183        }
184    }