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 <dlfcn.h>
18 #include <signal.h>
19 #include <stdio.h>
20 #include <stdlib.h>
21 #include <string.h>
22
23 #include <algorithm>
24 #include <memory>
25
26 #include "base/fast_exit.h"
27 #include "jni.h"
28 #include "nativehelper/JniInvocation.h"
29 #include "nativehelper/ScopedLocalRef.h"
30 #include "nativehelper/toStringArray.h"
31
32 #ifdef ART_TARGET_ANDROID
33 #include "nativeloader/dlext_namespaces.h"
34 #endif
35
36 namespace art {
37
38 // This complements the treatment of NATIVELOADER_DEFAULT_NAMESPACE_LIBS in
39 // art/libnativeloader/native_loader.cpp: The libraries listed in that variable
40 // are added to the default namespace, which for dalvikvm runs means they can
41 // access all internal libs in com_android_art. However, to allow the opposite
42 // direction we need links for them from com_android_art back to default, and
43 // that's done here. See comments in native_loader.cpp for full discussion.
initNativeloaderExtraLibsLinks()44 static bool initNativeloaderExtraLibsLinks() {
45 #ifdef ART_TARGET_ANDROID
46 const char* links = getenv("NATIVELOADER_DEFAULT_NAMESPACE_LIBS");
47 if (links == nullptr || *links == 0) {
48 return true;
49 }
50 struct android_namespace_t* art_ns = android_get_exported_namespace("com_android_art");
51 if (art_ns == nullptr) {
52 fprintf(stderr,
53 "Warning: com_android_art namespace not found - "
54 "NATIVELOADER_DEFAULT_NAMESPACE_LIBS ignored\n");
55 return true;
56 }
57 if (!android_link_namespaces(art_ns, nullptr, links)) {
58 fprintf(stderr,
59 "Error adding linker namespace links from com_android_art to default for %s: %s",
60 links,
61 dlerror());
62 return false;
63 }
64 #endif // ART_TARGET_ANDROID
65 return true;
66 }
67
68 // Determine whether or not the specified method is public.
IsMethodPublic(JNIEnv * env,jclass c,jmethodID method_id)69 static bool IsMethodPublic(JNIEnv* env, jclass c, jmethodID method_id) {
70 ScopedLocalRef<jobject> reflected(env, env->ToReflectedMethod(c, method_id, JNI_FALSE));
71 if (reflected.get() == nullptr) {
72 fprintf(stderr, "Failed to get reflected method\n");
73 return false;
74 }
75 // We now have a Method instance. We need to call its
76 // getModifiers() method.
77 jclass method_class = env->FindClass("java/lang/reflect/Method");
78 if (method_class == nullptr) {
79 fprintf(stderr, "Failed to find class java.lang.reflect.Method\n");
80 return false;
81 }
82 jmethodID mid = env->GetMethodID(method_class, "getModifiers", "()I");
83 if (mid == nullptr) {
84 fprintf(stderr, "Failed to find java.lang.reflect.Method.getModifiers\n");
85 return false;
86 }
87 int modifiers = env->CallIntMethod(reflected.get(), mid);
88 static const int PUBLIC = 0x0001; // java.lang.reflect.Modifiers.PUBLIC
89 if ((modifiers & PUBLIC) == 0) {
90 fprintf(stderr, "Modifiers mismatch\n");
91 return false;
92 }
93 return true;
94 }
95
InvokeMain(JNIEnv * env,char ** argv)96 static int InvokeMain(JNIEnv* env, char** argv) {
97 // We want to call main() with a String array with our arguments in
98 // it. Create an array and populate it. Note argv[0] is not
99 // included.
100 ScopedLocalRef<jobjectArray> args(env, toStringArray(env, argv + 1));
101 if (args.get() == nullptr) {
102 env->ExceptionDescribe();
103 return EXIT_FAILURE;
104 }
105
106 // Find [class].main(String[]).
107
108 // Convert "com.android.Blah" to "com/android/Blah".
109 std::string class_name(argv[0]);
110 std::replace(class_name.begin(), class_name.end(), '.', '/');
111
112 ScopedLocalRef<jclass> klass(env, env->FindClass(class_name.c_str()));
113 if (klass.get() == nullptr) {
114 fprintf(stderr, "Unable to locate class '%s'\n", class_name.c_str());
115 env->ExceptionDescribe();
116 return EXIT_FAILURE;
117 }
118
119 jmethodID method = env->GetStaticMethodID(klass.get(), "main", "([Ljava/lang/String;)V");
120 if (method == nullptr) {
121 fprintf(stderr, "Unable to find static main(String[]) in '%s'\n", class_name.c_str());
122 env->ExceptionDescribe();
123 return EXIT_FAILURE;
124 }
125
126 // Make sure the method is public. JNI doesn't prevent us from
127 // calling a private method, so we have to check it explicitly.
128 if (!IsMethodPublic(env, klass.get(), method)) {
129 fprintf(stderr, "Sorry, main() is not public in '%s'\n", class_name.c_str());
130 env->ExceptionDescribe();
131 return EXIT_FAILURE;
132 }
133
134 // Invoke main().
135 env->CallStaticVoidMethod(klass.get(), method, args.get());
136
137 // Check whether there was an uncaught exception. We don't log any uncaught exception here;
138 // detaching this thread will do that for us, but it will clear the exception (and invalidate
139 // our JNIEnv), so we need to check here.
140 return env->ExceptionCheck() ? EXIT_FAILURE : EXIT_SUCCESS;
141 }
142
143 // Parse arguments. Most of it just gets passed through to the runtime.
144 // The JNI spec defines a handful of standard arguments.
dalvikvm(int argc,char ** argv)145 static int dalvikvm(int argc, char** argv) {
146 setvbuf(stdout, nullptr, _IONBF, 0);
147
148 // Skip over argv[0].
149 argv++;
150 argc--;
151
152 // If we're adding any additional stuff, e.g. function hook specifiers,
153 // add them to the count here.
154 //
155 // We're over-allocating, because this includes the options to the runtime
156 // plus the options to the program.
157 int option_count = argc;
158 std::unique_ptr<JavaVMOption[]> options(new JavaVMOption[option_count]());
159
160 // Copy options over. Everything up to the name of the class starts
161 // with a '-' (the function hook stuff is strictly internal).
162 //
163 // [Do we need to catch & handle "-jar" here?]
164 bool need_extra = false;
165 const char* lib = nullptr;
166 const char* what = nullptr;
167 int curr_opt, arg_idx;
168 for (curr_opt = arg_idx = 0; arg_idx < argc; arg_idx++) {
169 if (argv[arg_idx][0] != '-' && !need_extra) {
170 break;
171 }
172 if (strncmp(argv[arg_idx], "-XXlib:", strlen("-XXlib:")) == 0) {
173 lib = argv[arg_idx] + strlen("-XXlib:");
174 continue;
175 }
176
177 options[curr_opt++].optionString = argv[arg_idx];
178
179 // Some options require an additional argument.
180 need_extra = false;
181 if (strcmp(argv[arg_idx], "-classpath") == 0 || strcmp(argv[arg_idx], "-cp") == 0) {
182 need_extra = true;
183 what = argv[arg_idx];
184 }
185 }
186
187 if (!initNativeloaderExtraLibsLinks()) {
188 return EXIT_FAILURE;
189 }
190
191 if (need_extra) {
192 fprintf(stderr, "%s must be followed by an additional argument giving a value\n", what);
193 return EXIT_FAILURE;
194 }
195
196 if (curr_opt > option_count) {
197 fprintf(stderr, "curr_opt(%d) > option_count(%d)\n", curr_opt, option_count);
198 abort();
199 return EXIT_FAILURE;
200 }
201
202 // Find the JNI_CreateJavaVM implementation.
203 JniInvocation jni_invocation;
204 if (!jni_invocation.Init(lib)) {
205 fprintf(stderr, "Failed to initialize JNI invocation API from %s\n", lib);
206 return EXIT_FAILURE;
207 }
208
209 JavaVMInitArgs init_args;
210 init_args.version = JNI_VERSION_1_6;
211 init_args.options = options.get();
212 init_args.nOptions = curr_opt;
213 init_args.ignoreUnrecognized = JNI_FALSE;
214
215 // Start the runtime. The current thread becomes the main thread.
216 JavaVM* vm = nullptr;
217 JNIEnv* env = nullptr;
218 if (JNI_CreateJavaVM(&vm, &env, &init_args) != JNI_OK) {
219 fprintf(stderr, "Failed to initialize runtime (check log for details)\n");
220 return EXIT_FAILURE;
221 }
222
223 // Make sure they provided a class name. We do this after
224 // JNI_CreateJavaVM so that things like "-help" have the opportunity
225 // to emit a usage statement.
226 if (arg_idx == argc) {
227 fprintf(stderr, "Class name required\n");
228 return EXIT_FAILURE;
229 }
230
231 int rc = InvokeMain(env, &argv[arg_idx]);
232
233 #if defined(NDEBUG)
234 // The DestroyJavaVM call will detach this thread for us. In debug builds, we don't want to
235 // detach because detaching disables the CheckSafeToLockOrUnlock checking.
236 if (vm->DetachCurrentThread() != JNI_OK) {
237 fprintf(stderr, "Warning: unable to detach main thread\n");
238 rc = EXIT_FAILURE;
239 }
240 #endif
241
242 if (vm->DestroyJavaVM() != 0) {
243 fprintf(stderr, "Warning: runtime did not shut down cleanly\n");
244 rc = EXIT_FAILURE;
245 }
246
247 return rc;
248 }
249
250 } // namespace art
251
252 // TODO(b/141622862): stop leaks
__asan_default_options()253 extern "C" const char *__asan_default_options() {
254 return "detect_leaks=0";
255 }
256
main(int argc,char ** argv)257 int main(int argc, char** argv) {
258 // Do not allow static destructors to be called, since it's conceivable that
259 // daemons may still awaken (literally).
260 art::FastExit(art::dalvikvm(argc, argv));
261 }
262