OpenJDK HotSpot JVM:如何定位main方法类及主线程识别逻辑?
Tracking the Main Class in OpenJDK HotSpot JVM
Hey there! Let's break down your questions about locating and logging the main class in OpenJDK HotSpot's source code step by step:
1. How to find where the main() class is handled in HotSpot source?
The HotSpot JVM doesn't "search" for the main class on its own—it gets the class name from the launcher that starts the JVM. Here's the key flow:
- First, the native launcher (look at
src/java.base/share/native/launcher/main.c) parses command-line arguments. If you run a class directly, it grabs the class name from the args; if you run a JAR, it reads theMain-Classattribute from the JAR's manifest. - This class name is passed to the JVM during initialization. Inside HotSpot, the
Argumentsclass (defined insrc/hotspot/share/runtime/arguments.cpp) stores this value. You can access it via theArguments::main_class()method, which returns aSymbol*representing the fully qualified main class name (likecom.example.MyApp).
2. Logging the main class name/package early (right around VM creation)
Since you've already found Threads::create_vm, you're in the right spot to add your logging. Here's how to do it:
Step 1: Access the main class name
The Arguments::main_class() method gives you the fully qualified name of the main class. To print it as a C string, use symbol->as_C_string().
Step 2: Add logging code at the right place
You have two good options for early logging:
- After VM initialization (inside
Threads::create_vm): At the end of theThreads::create_vmfunction insrc/hotspot/share/runtime/thread.cpp, right before the method returns success, add:if (Arguments::main_class() != nullptr) { const char* main_class_str = Arguments::main_class()->as_C_string(); printf("Detected main class: %s\n", main_class_str); // Split into package and class name const char* last_dot = strrchr(main_class_str, '.'); if (last_dot != nullptr) { printf("Package name: %.*s\n", (int)(last_dot - main_class_str), main_class_str); printf("Simple class name: %s\n", last_dot + 1); } else { printf("Package name: (no package)\n"); printf("Simple class name: %s\n", main_class_str); } } - Even earlier (after argument parsing): If you want to log before VM initialization completes, add the same code at the end of
Arguments::parse()insrc/hotspot/share/runtime/arguments.cpp. This runs right after the launcher passes the main class name to the JVM.
Notes
- Make sure to include
<cstring>forstrrchrif it's not already included in the file. - This works for both direct class execution and JAR files, since
Arguments::main_class()handles both cases correctly.
内容的提问来源于stack exchange,提问作者Markus Weninger
相关产品推荐
相关产品推荐

