System. loadLibrary

Source: Internet
Author: User

System. loadLibrary
System. loadLibrary

When loading the so library, we usually useWe also know the loadLibrary () function.Load () is the absolute path of the so file,How does loadLibrary find so? Today, let's look at what happened next to it.

public static void loadLibrary(String libname) {    Runtime.getRuntime().loadLibrary0(VMStack.getCallingClassLoader(), libname);}  

Is it a bit confusing here?LoadLibrary0 () this function is easy to understand,Libname,Which ClassLoader is returned by VMStack. getCallingClassLoader? In fact, the returned result is to start thisThe loader of the class where the System. loadLibrary function is called. This is A bit confusing. For example, it is called in Class.LoadLibrary (), thenVMStack. getCallingClassLoader () returns the classloader of Class. Okay. GoInside the loadLibrary0 () function, let's see what happened later.

1. Search for so files
synchronized void loadLibrary0(ClassLoader loader, String libname) { ...... String libraryName = libname; if (loader != null) { String filename = loader.findLibrary(libraryName); if (filename == null) { // It's not necessarily true that the ClassLoader used // System.mapLibraryName, but the default setup does, and it's // misleading to say we didn't find "libMyLibrary.so" when we // actually searched for "liblibMyLibrary.so.so". throw new UnsatisfiedLinkError(loader + " couldn't find \"" + System.mapLibraryName(libraryName) + "\""); } String error = doLoad(filename, loader); if (error != null) { throw new UnsatisfiedLinkError(error); } return; } String filename = System.mapLibraryName(libraryName); List  candidates = new ArrayList  (); String lastError = null; for (String directory : getLibPaths()) { String candidate = directory + filename; candidates.add(candidate); if (IoUtils.canOpenReadOnly(candidate)) { String error = doLoad(candidate, loader); if (error == null) { return; // We successfully loaded the library. Job done. } lastError = error; } } if (lastError != null) { throw new UnsatisfiedLinkError(lastError); } throw new UnsatisfiedLinkError("Library " + libraryName + " not found; tried " + candidates);}  

Under normal circumstances, the uploaded loader is non-empty, and few loader will be empty. Therefore, we will focus on analyzing the case where the load is not empty. When the loader is not empty, the function loader. findLibrary is called first. The function parameter is the name of the so library we passed. Now we will go to the loader internal analysis. We will analyze the findLibrary function in DexClassLoader. Based on the inheritance system of android classloader, findLibrary is implemented in BaseDexClassLoader.

@Overridepublic String findLibrary(String name) { return pathList.findLibrary(name);} 

FindLibrary will eventually call the findLibrary function of pathList. What is pathList? Let's take a look at the BaseDexClassLoader function constructor. By the way, the DexClassLoader constructor will be easier to understand:

public DexClassLoader(String dexPath, String optimizedDirectory, String librarySearchPath, ClassLoader parent) { super(dexPath, new File(optimizedDirectory), librarySearchPath, parent);}public BaseDexClassLoader(String dexPath, File optimizedDirectory, String librarySearchPath, ClassLoader parent) { super(parent); this.pathList = new DexPathList(this, dexPath, librarySearchPath, optimizedDirectory);} 

We can find that our dexPath (the path of the apk file), optimizedDirectory (the directory of the odex file), and librarySearchPath (the directory of the so file) are passed during custom DexClassLoader ), parent (parent loader); when constructing the DexPathList object, the dexPath, librarySearchPath, and optimizedDirectory are passed. OK. Let's go to DexPathList to see the specific implementation of the findLibrary function.

public String findLibrary(String libraryName) { String fileName = System.mapLibraryName(libraryName); for (Element element : nativeLibraryPathElements) { String path = element.findNativeLibrary(fileName); if (path != null) { return path; } } return null;} 

You can see thatSystem. mapLibraryName (libraryName. The literal meaning of this function is to map the passed libraryName to another name. I will go !!! This may be why the so file name is libxx. so, but we can still find the reason when we wear xx. I have to check it out here.The specific implementation of the function System. mapLibraryName (libraryName. Ah, it's a native implementation, and the Intelligence gets rid of the native source code. The specific implementation of this method is in/libcore/ojluni/src/main/native/System. c.

JNIEXPORT jstring JNICALLSystem_mapLibraryName(JNIEnv *env, jclass ign, jstring libname){ int len; int prefix_len = (int) strlen(JNI_LIB_PREFIX); int suffix_len = (int) strlen(JNI_LIB_SUFFIX); jchar chars[256]; if (libname == NULL) { JNU_ThrowNullPointerException(env, 0); return NULL; } len = (*env)->GetStringLength(env, libname); if (len > 240) { JNU_ThrowIllegalArgumentException(env, "name too long"); return NULL; } cpchars(chars, JNI_LIB_PREFIX, prefix_len); (*env)->GetStringRegion(env, libname, 0, len, chars + prefix_len); len += prefix_len; cpchars(chars + len, JNI_LIB_SUFFIX, suffix_len); len += suffix_len; return (*env)->NewString(env, chars, len);} 

By analyzing the source code, we can find that JNI_LIB_PREFIX and JNI_LIB_SUFFIX are added before and after libname, and then we can see how these two constants are defined. The two constants are defined in/libcore/ojluni/src/main/native/jvm_md.h:

#define JNI_LIB_PREFIX "lib"#define JNI_LIB_SUFFIX ".so" 

The function System. mapLibraryName is used to indicate that the transferred xx is changed to libxx. so.

Next, analyze the remaining parts of the DexPathList findLibrary function:

for (Element element : nativeLibraryPathElements) { String path = element.findNativeLibrary(fileName); if (path != null) { return path; }} 

The nativeLibraryPathElements variable does not post code. This variable records the path of the so file to be searched by the application. This path includes the system path./Vendor/lib /,/System/lib/and the so file search path defined when classload is created. If the required so file can be found in any path, the absolute path of the so file is returned.
The above is the so file search process.

2. Load the so file

In section 1, the system finds the absolute path of the so file, and then the system loads the so file according to the absolute path of the so file.

doLoad(filename, loader); 

The final loaded function isDoLoad (dilename, loader), which has not been studied yet. You may think of another function to load the so file.System. load (), comparedFor the System. loadLibrary () function, when the parameter value is set, the absolute path of the so file does not need to be searched.

Okay, the so file loading process is here.


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.