Execute Java and java files

Source: Internet
Author: User
Tags bootstrap classes

Execute Java and java files


I recently read the JVM source code and wrote some experiences as a Blog to share them. So I started this topic.


I am very confused when I get the name in the first article. I read the code from launcher's start, and I cannot get the name like "JVM Startup Process Analysis", but also the corresponding code of java.exe (if it is a windows platform, because the analysis of the main process is not at this level, it is a strange name for the moment.


If this series can continue, without special instructions, the JDK and JVM versions used are 8u20, from OpenJDK: http://hg.openjdk.java.net/jdk8u


I am a JAVA programmer. when analyzing a large number of JVM C/C ++ programs, it is inevitable that some readers will be confused. There is no limit between time and code, and the specific implementation details cannot be comprehensive. only focus on analyzing and understanding the general process and mechanism. If there are important details missing, please leave a message to discuss them.


In this series, the relative path is used for any description of the source file location. jdk/Represents the root directory where Jdk source code is placed, and hotspot/Represents the root directory where jvm source code is placed.


I. Launcher code analysis

(1) Main in main. c

Location: jdk/src/bin/main. c

When we call the java command, we must first enter the main function of C/C ++, just like the helloworld I wrote a few years ago.

This main function is located in jdk/src/bin/main. c. It is placed in jdk 8 and in earlier versions of JVM-related code.

There is almost no substantive logic in main. c. It mainly involves copying some parameters, processing some calls in the windows platform, and then passing the parameters to JLI_launch for execution. The related code is in line 2.

return JLI_Launch(margc, margv,                   sizeof(const_jargs) / sizeof(char *), const_jargs,                   sizeof(const_appclasspath) / sizeof(char *), const_appclasspath,                   FULL_VERSION,                   DOT_VERSION,                   (const_progname != NULL) ? const_progname : *margv,                   (const_launcher != NULL) ? const_launcher : *margv,                   (const_jargs != NULL) ? JNI_TRUE : JNI_FALSE,                   const_cpwildcard, const_javaw, const_ergo_class);



(2) JLI_Launch in java. c

Location: jdk/src/bin/java. c

According to the annotations in java. c, we can see the meanings of the parameters of this function:

JLI_Launch(int argc, char ** argv,              /* main argc, argc */        int jargc, const char** jargv,          /* java args */        int appclassc, const char** appclassv,  /* app classpath */        const char* fullversion,                /* full version defined */        const char* dotversion,                 /* dot version defined */        const char* pname,                      /* program name */        const char* lname,                      /* launcher name */        jboolean javaargs,                      /* JAVA_ARGS */        jboolean cpwildcard,                    /* classpath wildcard*/        jboolean javaw,                         /* windows-only javaw */        jint ergo                               /* ergonomics class policy */

Call the system function in line 3 to obtain the environment variables and assign values to jrepath, jvmpath, and jvmcfg. (The environment variables set in each basic Java Tutorial Work here)

    CreateExecutionEnvironment(&argc, &argv,                               jrepath, sizeof(jrepath),                               jvmpath, sizeof(jvmpath),                               jvmcfg,  sizeof(jvmcfg));

248th lines load jvm. dll file. It only loads the file to the memory and does not perform any operations. At the same time, it assigns a value to this FN struct (assign a value based on the dll extraction function call address ), the FN struct contains three key function pointers.

if (!LoadJavaVM(jvmpath, &ifn)) {        return(6);    }
The structure of the interferon is as follows:

typedef struct {    CreateJavaVM_t CreateJavaVM;    GetDefaultJavaVMInitArgs_t GetDefaultJavaVMInitArgs;    GetCreatedJavaVMs_t GetCreatedJavaVMs;} InvocationFunctions;
According to the function name, we can probably guess that the first is to create a virtual machine, the second is to obtain the initial parameters, and the third is to create many virtual machines? (Does vms represent the plural form of a virtual machine? I guess ..).

Then, some additional processing (including getting classpath, printing debugging information, and adding additional parameters) is performed on the parameters, and JVMInit is called to initialize the Virtual Machine in line 3.

    return JVMInit(&ifn, threadStackSize, argc, argv, mode, what, ret);


(3) JVMInit in Java. c

Location: jdk/src/bin/java. c

There are few codes. First, print the information and call the ConitueInNewThread function. From the function name, we can see that a new thread is enabled to create JVM.

intJVMInit(InvocationFunctions* ifn, jlong threadStackSize,        int argc, char **argv,        int mode, char *what, int ret){    ShowSplashScreen();    return ContinueInNewThread(ifn, threadStackSize, argc, argv, mode, what, ret);}


(4) ContinueInNewThread in Java. c

Location: jdk/src/bin/java. c

This function still does nothing. It encapsulates the parameters and delegates them to ContinueInNewThread0. While ContinueInNewThread0 starts a new thread and executes the JavaMain function.


(5) JavaMain in Java. c

Location: jdk/src/bin/java. c

First, initialize JVM In line 3, and the InitializeJVM function is used to call FN-> createJavaVM. The specific JVM startup process is too deep to be analyzed here. If the initialization is successful, vm objects and env objects are assigned values. env is a very important object and is frequently used for JNI calls.

if (!InitializeJVM(&vm, &env, &ifn)) {        JLI_ReportErrorMessage(JVM_ERROR1);        exit(1);    }
Check whether the Jar file or a class name is passed in. If not, print the Usage.

The next 439th rows obtain the primary class. The method for obtaining the primary class is interesting and will be analyzed later. Next, check whether an exception is thrown. if an exception is thrown, the system exits.

    mainClass = LoadMainClass(env, mode, what);    CHECK_EXCEPTION_NULL_LEAVE(mainClass);


Then load something for JavaFX (if needed), obtain the ID of the main method, combine parameters, and Invoke.

Each step checks whether an exception is thrown.

 mainID = (*env)->GetStaticMethodID(env, mainClass, "main",                                       "([Ljava/lang/String;)V");    CHECK_EXCEPTION_NULL_LEAVE(mainID);    /* Build platform specific argument array */    mainArgs = CreateApplicationArgs(env, argv, argc);    CHECK_EXCEPTION_NULL_LEAVE(mainArgs);    /* Invoke main method. */    (*env)->CallStaticVoidMethod(env, mainClass, mainID, mainArgs);    /*     * The launcher's exit code (in the absence of calls to     * System.exit) will be non-zero if main threw an exception.     */    ret = (*env)->ExceptionOccurred(env) == NULL ? 0 : 1;



(To be continued)







How are java files executed?

First, use the javac command to compile the. java file into a. class file (bytecode file)
Then, the JVM (java Virtual Machine) loads the. class file and translates it into a machine code to run the java program;
Learn Together ----- refer:
We manually execute the java program as follows:
1. Write the source program in notepad or UE text editor;
2. Use the javac command to compile the source program into a. class file;
The compiled. class (class bytecode) file contains the following content:

ConstantPool: symbol table;
FieldInfo: Information about member variables in the class;
MethodInfo: Method description in the class;
Attribute: optional additional nodes.
The FieldInfo node contains the names of member variables, such as public, private, and static. The ConstantValue attribute is used to store static unchanged member variable values. Deprecated and Synthetic are used to mark a member variable that is not recommended or generated by the compiler.

3. With the. class file, we can run the java program by executing the java interpretation command.

Now we will mainly discuss what will happen after the java command is executed?
First, the JVM mounts. class, that is, the class Loader loads class bytecode. A Class Loader is also a java class. Therefore, the Class Loader itself needs to be loaded by another class loader, which is similar to having an egg first or having a chicken first. However, the class loader in JAVA is easy to solve. JAVA Virtual Machine (JVM) is embedded with a Bootstrap class loader, which is implemented with local code specific to the operating system and belongs to the JAVA Virtual Machine kernel, bootstrap classes do not need dedicated class loaders for loading. The Bootstrap Class is responsible for loading the classes in the JAVA core package (that is, the classes in the rt. jar file). The returned value of the Class. getClassLoader () method of these classes is null, that is, the Bootstrap Class loader. The JAVA core package has two other class loaders: ExtClassLoader and AppClassLoader. They are all JAVA classes written in JAVA, the ExtClassLoader class is responsible for loading the classes in the jar package stored in the <JAVA_HOME>/jre/lib/ext directory, and the AppClassLoader is responsible for loading the startup execution class of the application, that is, when you use java commands to start and execute a class, the java virtual machine uses AppClassLoader to load the class. When compiling and running JAVA programs, you can use the ExtClassLoader class loader to search for the classes to be loaded in the JAR package under the <JAVA_HOME>/jre/lib/ext directory, if you want to include a jar package such as Servlet API or javamail. copy the jar package to this directory. when compiling the Servlet or JavaMail program, you do not need to add the jar package containing the Servlet API or javamail to the classpath environment variable. jar package file.
The above is a general process of JAVA program execution.

Java cannot run

Open the Java Control Panel ---> Security
Click to edit the Site List
Paste your website
OK

 

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.