Home | History | Annotate | Download | only in dalvikvm
      1 /*
      2  * copyright (C) 2011 The Android Open Source Project
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  *      http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 
     17 #include <signal.h>
     18 #include <stdio.h>
     19 #include <stdlib.h>
     20 #include <string.h>
     21 #include <algorithm>
     22 #include <memory>
     23 
     24 #include "jni.h"
     25 #include "JniInvocation.h"
     26 #include "ScopedLocalRef.h"
     27 #include "toStringArray.h"
     28 
     29 namespace art {
     30 
     31 // Determine whether or not the specified method is public.
     32 static bool IsMethodPublic(JNIEnv* env, jclass c, jmethodID method_id) {
     33   ScopedLocalRef<jobject> reflected(env, env->ToReflectedMethod(c, method_id, JNI_FALSE));
     34   if (reflected.get() == NULL) {
     35     fprintf(stderr, "Failed to get reflected method\n");
     36     return false;
     37   }
     38   // We now have a Method instance.  We need to call its
     39   // getModifiers() method.
     40   jclass method_class = env->FindClass("java/lang/reflect/Method");
     41   if (method_class == NULL) {
     42     fprintf(stderr, "Failed to find class java.lang.reflect.Method\n");
     43     return false;
     44   }
     45   jmethodID mid = env->GetMethodID(method_class, "getModifiers", "()I");
     46   if (mid == NULL) {
     47     fprintf(stderr, "Failed to find java.lang.reflect.Method.getModifiers\n");
     48     return false;
     49   }
     50   int modifiers = env->CallIntMethod(reflected.get(), mid);
     51   static const int PUBLIC = 0x0001;  // java.lang.reflect.Modifiers.PUBLIC
     52   if ((modifiers & PUBLIC) == 0) {
     53     return false;
     54   }
     55   return true;
     56 }
     57 
     58 static int InvokeMain(JNIEnv* env, char** argv) {
     59   // We want to call main() with a String array with our arguments in
     60   // it.  Create an array and populate it.  Note argv[0] is not
     61   // included.
     62   ScopedLocalRef<jobjectArray> args(env, toStringArray(env, argv + 1));
     63   if (args.get() == NULL) {
     64     env->ExceptionDescribe();
     65     return EXIT_FAILURE;
     66   }
     67 
     68   // Find [class].main(String[]).
     69 
     70   // Convert "com.android.Blah" to "com/android/Blah".
     71   std::string class_name(argv[0]);
     72   std::replace(class_name.begin(), class_name.end(), '.', '/');
     73 
     74   ScopedLocalRef<jclass> klass(env, env->FindClass(class_name.c_str()));
     75   if (klass.get() == NULL) {
     76     fprintf(stderr, "Unable to locate class '%s'\n", class_name.c_str());
     77     env->ExceptionDescribe();
     78     return EXIT_FAILURE;
     79   }
     80 
     81   jmethodID method = env->GetStaticMethodID(klass.get(), "main", "([Ljava/lang/String;)V");
     82   if (method == NULL) {
     83     fprintf(stderr, "Unable to find static main(String[]) in '%s'\n", class_name.c_str());
     84     env->ExceptionDescribe();
     85     return EXIT_FAILURE;
     86   }
     87 
     88   // Make sure the method is public.  JNI doesn't prevent us from
     89   // calling a private method, so we have to check it explicitly.
     90   if (!IsMethodPublic(env, klass.get(), method)) {
     91     fprintf(stderr, "Sorry, main() is not public in '%s'\n", class_name.c_str());
     92     env->ExceptionDescribe();
     93     return EXIT_FAILURE;
     94   }
     95 
     96   // Invoke main().
     97   env->CallStaticVoidMethod(klass.get(), method, args.get());
     98 
     99   // Check whether there was an uncaught exception. We don't log any uncaught exception here;
    100   // detaching this thread will do that for us, but it will clear the exception (and invalidate
    101   // our JNIEnv), so we need to check here.
    102   return env->ExceptionCheck() ? EXIT_FAILURE : EXIT_SUCCESS;
    103 }
    104 
    105 // Parse arguments.  Most of it just gets passed through to the runtime.
    106 // The JNI spec defines a handful of standard arguments.
    107 static int dalvikvm(int argc, char** argv) {
    108   setvbuf(stdout, NULL, _IONBF, 0);
    109 
    110   // Skip over argv[0].
    111   argv++;
    112   argc--;
    113 
    114   // If we're adding any additional stuff, e.g. function hook specifiers,
    115   // add them to the count here.
    116   //
    117   // We're over-allocating, because this includes the options to the runtime
    118   // plus the options to the program.
    119   int option_count = argc;
    120   std::unique_ptr<JavaVMOption[]> options(new JavaVMOption[option_count]());
    121 
    122   // Copy options over.  Everything up to the name of the class starts
    123   // with a '-' (the function hook stuff is strictly internal).
    124   //
    125   // [Do we need to catch & handle "-jar" here?]
    126   bool need_extra = false;
    127   const char* lib = NULL;
    128   const char* what = NULL;
    129   int curr_opt, arg_idx;
    130   for (curr_opt = arg_idx = 0; arg_idx < argc; arg_idx++) {
    131     if (argv[arg_idx][0] != '-' && !need_extra) {
    132       break;
    133     }
    134     if (strncmp(argv[arg_idx], "-XXlib:", strlen("-XXlib:")) == 0) {
    135       lib = argv[arg_idx] + strlen("-XXlib:");
    136       continue;
    137     }
    138 
    139     options[curr_opt++].optionString = argv[arg_idx];
    140 
    141     // Some options require an additional argument.
    142     need_extra = false;
    143     if (strcmp(argv[arg_idx], "-classpath") == 0 || strcmp(argv[arg_idx], "-cp") == 0) {
    144       need_extra = true;
    145       what = argv[arg_idx];
    146     }
    147   }
    148 
    149   if (need_extra) {
    150     fprintf(stderr, "%s must be followed by an additional argument giving a value\n", what);
    151     return EXIT_FAILURE;
    152   }
    153 
    154   if (curr_opt > option_count) {
    155     fprintf(stderr, "curr_opt(%d) >= option_count(%d)\n", curr_opt, option_count);
    156     abort();
    157     return EXIT_FAILURE;
    158   }
    159 
    160   // Find the JNI_CreateJavaVM implementation.
    161   JniInvocation jni_invocation;
    162   if (!jni_invocation.Init(lib)) {
    163     fprintf(stderr, "Failed to initialize JNI invocation API from %s\n", lib);
    164     return EXIT_FAILURE;
    165   }
    166 
    167   JavaVMInitArgs init_args;
    168   init_args.version = JNI_VERSION_1_6;
    169   init_args.options = options.get();
    170   init_args.nOptions = curr_opt;
    171   init_args.ignoreUnrecognized = JNI_FALSE;
    172 
    173   // Start the runtime. The current thread becomes the main thread.
    174   JavaVM* vm = NULL;
    175   JNIEnv* env = NULL;
    176   if (JNI_CreateJavaVM(&vm, &env, &init_args) != JNI_OK) {
    177     fprintf(stderr, "Failed to initialize runtime (check log for details)\n");
    178     return EXIT_FAILURE;
    179   }
    180 
    181   // Make sure they provided a class name. We do this after
    182   // JNI_CreateJavaVM so that things like "-help" have the opportunity
    183   // to emit a usage statement.
    184   if (arg_idx == argc) {
    185     fprintf(stderr, "Class name required\n");
    186     return EXIT_FAILURE;
    187   }
    188 
    189   int rc = InvokeMain(env, &argv[arg_idx]);
    190 
    191 #if defined(NDEBUG)
    192   // The DestroyJavaVM call will detach this thread for us. In debug builds, we don't want to
    193   // detach because detaching disables the CheckSafeToLockOrUnlock checking.
    194   if (vm->DetachCurrentThread() != JNI_OK) {
    195     fprintf(stderr, "Warning: unable to detach main thread\n");
    196     rc = EXIT_FAILURE;
    197   }
    198 #endif
    199 
    200   if (vm->DestroyJavaVM() != 0) {
    201     fprintf(stderr, "Warning: runtime did not shut down cleanly\n");
    202     rc = EXIT_FAILURE;
    203   }
    204 
    205   return rc;
    206 }
    207 
    208 }  // namespace art
    209 
    210 int main(int argc, char** argv) {
    211   return art::dalvikvm(argc, argv);
    212 }
    213