1 /*
2  * Copyright (C) 2008 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 "dalvik_system_VMRuntime.h"
18 
19 #ifdef ART_TARGET_ANDROID
20 #include <sys/resource.h>
21 #include <sys/time.h>
22 extern "C" void android_set_application_target_sdk_version(uint32_t version);
23 #endif
24 #include <inttypes.h>
25 #include <limits>
26 #include <limits.h>
27 #include "nativehelper/scoped_utf_chars.h"
28 
29 #include <android-base/stringprintf.h>
30 #include <android-base/strings.h>
31 
32 #include "arch/instruction_set.h"
33 #include "art_method-inl.h"
34 #include "base/enums.h"
35 #include "base/sdk_version.h"
36 #include "class_linker-inl.h"
37 #include "common_throws.h"
38 #include "debugger.h"
39 #include "dex/class_accessor-inl.h"
40 #include "dex/dex_file-inl.h"
41 #include "dex/dex_file_types.h"
42 #include "gc/accounting/card_table-inl.h"
43 #include "gc/allocator/dlmalloc.h"
44 #include "gc/heap.h"
45 #include "gc/space/dlmalloc_space.h"
46 #include "gc/space/image_space.h"
47 #include "gc/task_processor.h"
48 #include "intern_table.h"
49 #include "jni/java_vm_ext.h"
50 #include "jni/jni_internal.h"
51 #include "mirror/array-alloc-inl.h"
52 #include "mirror/class-inl.h"
53 #include "mirror/dex_cache-inl.h"
54 #include "mirror/object-inl.h"
55 #include "native_util.h"
56 #include "nativehelper/jni_macros.h"
57 #include "nativehelper/scoped_local_ref.h"
58 #include "runtime.h"
59 #include "scoped_fast_native_object_access-inl.h"
60 #include "scoped_thread_state_change-inl.h"
61 #include "thread.h"
62 #include "thread_list.h"
63 #include "well_known_classes.h"
64 
65 namespace art {
66 
67 using android::base::StringPrintf;
68 
VMRuntime_getTargetHeapUtilization(JNIEnv *,jobject)69 static jfloat VMRuntime_getTargetHeapUtilization(JNIEnv*, jobject) {
70   return Runtime::Current()->GetHeap()->GetTargetHeapUtilization();
71 }
72 
VMRuntime_nativeSetTargetHeapUtilization(JNIEnv *,jobject,jfloat target)73 static void VMRuntime_nativeSetTargetHeapUtilization(JNIEnv*, jobject, jfloat target) {
74   Runtime::Current()->GetHeap()->SetTargetHeapUtilization(target);
75 }
76 
VMRuntime_startJitCompilation(JNIEnv *,jobject)77 static void VMRuntime_startJitCompilation(JNIEnv*, jobject) {
78 }
79 
VMRuntime_disableJitCompilation(JNIEnv *,jobject)80 static void VMRuntime_disableJitCompilation(JNIEnv*, jobject) {
81 }
82 
VMRuntime_setHiddenApiExemptions(JNIEnv * env,jclass,jobjectArray exemptions)83 static void VMRuntime_setHiddenApiExemptions(JNIEnv* env,
84                                             jclass,
85                                             jobjectArray exemptions) {
86   std::vector<std::string> exemptions_vec;
87   int exemptions_length = env->GetArrayLength(exemptions);
88   for (int i = 0; i < exemptions_length; i++) {
89     jstring exemption = reinterpret_cast<jstring>(env->GetObjectArrayElement(exemptions, i));
90     const char* raw_exemption = env->GetStringUTFChars(exemption, nullptr);
91     exemptions_vec.push_back(raw_exemption);
92     env->ReleaseStringUTFChars(exemption, raw_exemption);
93   }
94 
95   Runtime::Current()->SetHiddenApiExemptions(exemptions_vec);
96 }
97 
VMRuntime_setHiddenApiAccessLogSamplingRate(JNIEnv *,jclass,jint rate)98 static void VMRuntime_setHiddenApiAccessLogSamplingRate(JNIEnv*, jclass, jint rate) {
99   Runtime::Current()->SetHiddenApiEventLogSampleRate(rate);
100 }
101 
VMRuntime_newNonMovableArray(JNIEnv * env,jobject,jclass javaElementClass,jint length)102 static jobject VMRuntime_newNonMovableArray(JNIEnv* env, jobject, jclass javaElementClass,
103                                             jint length) {
104   ScopedFastNativeObjectAccess soa(env);
105   if (UNLIKELY(length < 0)) {
106     ThrowNegativeArraySizeException(length);
107     return nullptr;
108   }
109   ObjPtr<mirror::Class> element_class = soa.Decode<mirror::Class>(javaElementClass);
110   if (UNLIKELY(element_class == nullptr)) {
111     ThrowNullPointerException("element class == null");
112     return nullptr;
113   }
114   Runtime* runtime = Runtime::Current();
115   ObjPtr<mirror::Class> array_class =
116       runtime->GetClassLinker()->FindArrayClass(soa.Self(), element_class);
117   if (UNLIKELY(array_class == nullptr)) {
118     return nullptr;
119   }
120   gc::AllocatorType allocator = runtime->GetHeap()->GetCurrentNonMovingAllocator();
121   ObjPtr<mirror::Array> result = mirror::Array::Alloc<true>(soa.Self(),
122                                                             array_class,
123                                                             length,
124                                                             array_class->GetComponentSizeShift(),
125                                                             allocator);
126   return soa.AddLocalReference<jobject>(result);
127 }
128 
VMRuntime_newUnpaddedArray(JNIEnv * env,jobject,jclass javaElementClass,jint length)129 static jobject VMRuntime_newUnpaddedArray(JNIEnv* env, jobject, jclass javaElementClass,
130                                           jint length) {
131   ScopedFastNativeObjectAccess soa(env);
132   if (UNLIKELY(length < 0)) {
133     ThrowNegativeArraySizeException(length);
134     return nullptr;
135   }
136   ObjPtr<mirror::Class> element_class = soa.Decode<mirror::Class>(javaElementClass);
137   if (UNLIKELY(element_class == nullptr)) {
138     ThrowNullPointerException("element class == null");
139     return nullptr;
140   }
141   Runtime* runtime = Runtime::Current();
142   ObjPtr<mirror::Class> array_class = runtime->GetClassLinker()->FindArrayClass(soa.Self(),
143                                                                                 element_class);
144   if (UNLIKELY(array_class == nullptr)) {
145     return nullptr;
146   }
147   gc::AllocatorType allocator = runtime->GetHeap()->GetCurrentAllocator();
148   ObjPtr<mirror::Array> result = mirror::Array::Alloc<true, true>(
149       soa.Self(),
150       array_class,
151       length,
152       array_class->GetComponentSizeShift(),
153       allocator);
154   return soa.AddLocalReference<jobject>(result);
155 }
156 
VMRuntime_addressOf(JNIEnv * env,jobject,jobject javaArray)157 static jlong VMRuntime_addressOf(JNIEnv* env, jobject, jobject javaArray) {
158   if (javaArray == nullptr) {  // Most likely allocation failed
159     return 0;
160   }
161   ScopedFastNativeObjectAccess soa(env);
162   ObjPtr<mirror::Array> array = soa.Decode<mirror::Array>(javaArray);
163   if (!array->IsArrayInstance()) {
164     ThrowIllegalArgumentException("not an array");
165     return 0;
166   }
167   if (Runtime::Current()->GetHeap()->IsMovableObject(array)) {
168     ThrowRuntimeException("Trying to get address of movable array object");
169     return 0;
170   }
171   return reinterpret_cast<uintptr_t>(array->GetRawData(array->GetClass()->GetComponentSize(), 0));
172 }
173 
VMRuntime_clearGrowthLimit(JNIEnv *,jobject)174 static void VMRuntime_clearGrowthLimit(JNIEnv*, jobject) {
175   Runtime::Current()->GetHeap()->ClearGrowthLimit();
176 }
177 
VMRuntime_clampGrowthLimit(JNIEnv *,jobject)178 static void VMRuntime_clampGrowthLimit(JNIEnv*, jobject) {
179   Runtime::Current()->GetHeap()->ClampGrowthLimit();
180 }
181 
VMRuntime_isDebuggerActive(JNIEnv *,jobject)182 static jboolean VMRuntime_isDebuggerActive(JNIEnv*, jobject) {
183   return Dbg::IsDebuggerActive();
184 }
185 
VMRuntime_isNativeDebuggable(JNIEnv *,jobject)186 static jboolean VMRuntime_isNativeDebuggable(JNIEnv*, jobject) {
187   return Runtime::Current()->IsNativeDebuggable();
188 }
189 
VMRuntime_isJavaDebuggable(JNIEnv *,jobject)190 static jboolean VMRuntime_isJavaDebuggable(JNIEnv*, jobject) {
191   return Runtime::Current()->IsJavaDebuggable();
192 }
193 
VMRuntime_properties(JNIEnv * env,jobject)194 static jobjectArray VMRuntime_properties(JNIEnv* env, jobject) {
195   DCHECK(WellKnownClasses::java_lang_String != nullptr);
196 
197   const std::vector<std::string>& properties = Runtime::Current()->GetProperties();
198   ScopedLocalRef<jobjectArray> ret(env,
199                                    env->NewObjectArray(static_cast<jsize>(properties.size()),
200                                                        WellKnownClasses::java_lang_String,
201                                                        nullptr /* initial element */));
202   if (ret == nullptr) {
203     DCHECK(env->ExceptionCheck());
204     return nullptr;
205   }
206   for (size_t i = 0; i != properties.size(); ++i) {
207     ScopedLocalRef<jstring> str(env, env->NewStringUTF(properties[i].c_str()));
208     if (str == nullptr) {
209       DCHECK(env->ExceptionCheck());
210       return nullptr;
211     }
212     env->SetObjectArrayElement(ret.get(), static_cast<jsize>(i), str.get());
213     DCHECK(!env->ExceptionCheck());
214   }
215   return ret.release();
216 }
217 
218 // This is for backward compatibility with dalvik which returned the
219 // meaningless "." when no boot classpath or classpath was
220 // specified. Unfortunately, some tests were using java.class.path to
221 // lookup relative file locations, so they are counting on this to be
222 // ".", presumably some applications or libraries could have as well.
DefaultToDot(const std::string & class_path)223 static const char* DefaultToDot(const std::string& class_path) {
224   return class_path.empty() ? "." : class_path.c_str();
225 }
226 
VMRuntime_bootClassPath(JNIEnv * env,jobject)227 static jstring VMRuntime_bootClassPath(JNIEnv* env, jobject) {
228   std::string boot_class_path = android::base::Join(Runtime::Current()->GetBootClassPath(), ':');
229   return env->NewStringUTF(DefaultToDot(boot_class_path));
230 }
231 
VMRuntime_classPath(JNIEnv * env,jobject)232 static jstring VMRuntime_classPath(JNIEnv* env, jobject) {
233   return env->NewStringUTF(DefaultToDot(Runtime::Current()->GetClassPathString()));
234 }
235 
VMRuntime_vmVersion(JNIEnv * env,jobject)236 static jstring VMRuntime_vmVersion(JNIEnv* env, jobject) {
237   return env->NewStringUTF(Runtime::GetVersion());
238 }
239 
VMRuntime_vmLibrary(JNIEnv * env,jobject)240 static jstring VMRuntime_vmLibrary(JNIEnv* env, jobject) {
241   return env->NewStringUTF(kIsDebugBuild ? "libartd.so" : "libart.so");
242 }
243 
VMRuntime_vmInstructionSet(JNIEnv * env,jobject)244 static jstring VMRuntime_vmInstructionSet(JNIEnv* env, jobject) {
245   InstructionSet isa = Runtime::Current()->GetInstructionSet();
246   const char* isa_string = GetInstructionSetString(isa);
247   return env->NewStringUTF(isa_string);
248 }
249 
VMRuntime_is64Bit(JNIEnv *,jobject)250 static jboolean VMRuntime_is64Bit(JNIEnv*, jobject) {
251   bool is64BitMode = (sizeof(void*) == sizeof(uint64_t));
252   return is64BitMode ? JNI_TRUE : JNI_FALSE;
253 }
254 
VMRuntime_isCheckJniEnabled(JNIEnv * env,jobject)255 static jboolean VMRuntime_isCheckJniEnabled(JNIEnv* env, jobject) {
256   return down_cast<JNIEnvExt*>(env)->GetVm()->IsCheckJniEnabled() ? JNI_TRUE : JNI_FALSE;
257 }
258 
VMRuntime_setTargetSdkVersionNative(JNIEnv *,jobject,jint target_sdk_version)259 static void VMRuntime_setTargetSdkVersionNative(JNIEnv*, jobject, jint target_sdk_version) {
260   // This is the target SDK version of the app we're about to run. It is intended that this a place
261   // where workarounds can be enabled.
262   // Note that targetSdkVersion may be CUR_DEVELOPMENT (10000).
263   // Note that targetSdkVersion may be 0, meaning "current".
264   uint32_t uint_target_sdk_version =
265       target_sdk_version <= 0 ? static_cast<uint32_t>(SdkVersion::kUnset)
266                               : static_cast<uint32_t>(target_sdk_version);
267   Runtime::Current()->SetTargetSdkVersion(uint_target_sdk_version);
268 
269 #ifdef ART_TARGET_ANDROID
270   // This part is letting libc/dynamic linker know about current app's
271   // target sdk version to enable compatibility workarounds.
272   android_set_application_target_sdk_version(uint_target_sdk_version);
273 #endif
274 }
275 
clamp_to_size_t(jlong n)276 static inline size_t clamp_to_size_t(jlong n) {
277   if (sizeof(jlong) > sizeof(size_t)
278       && UNLIKELY(n > static_cast<jlong>(std::numeric_limits<size_t>::max()))) {
279     return std::numeric_limits<size_t>::max();
280   } else {
281     return n;
282   }
283 }
284 
VMRuntime_registerNativeAllocation(JNIEnv * env,jobject,jlong bytes)285 static void VMRuntime_registerNativeAllocation(JNIEnv* env, jobject, jlong bytes) {
286   if (UNLIKELY(bytes < 0)) {
287     ScopedObjectAccess soa(env);
288     ThrowRuntimeException("allocation size negative %" PRId64, bytes);
289     return;
290   }
291   Runtime::Current()->GetHeap()->RegisterNativeAllocation(env, clamp_to_size_t(bytes));
292 }
293 
VMRuntime_registerNativeFree(JNIEnv * env,jobject,jlong bytes)294 static void VMRuntime_registerNativeFree(JNIEnv* env, jobject, jlong bytes) {
295   if (UNLIKELY(bytes < 0)) {
296     ScopedObjectAccess soa(env);
297     ThrowRuntimeException("allocation size negative %" PRId64, bytes);
298     return;
299   }
300   Runtime::Current()->GetHeap()->RegisterNativeFree(env, clamp_to_size_t(bytes));
301 }
302 
VMRuntime_getNotifyNativeInterval(JNIEnv *,jclass)303 static jint VMRuntime_getNotifyNativeInterval(JNIEnv*, jclass) {
304   return Runtime::Current()->GetHeap()->GetNotifyNativeInterval();
305 }
306 
VMRuntime_notifyNativeAllocationsInternal(JNIEnv * env,jobject)307 static void VMRuntime_notifyNativeAllocationsInternal(JNIEnv* env, jobject) {
308   Runtime::Current()->GetHeap()->NotifyNativeAllocations(env);
309 }
310 
VMRuntime_getFinalizerTimeoutMs(JNIEnv *,jobject)311 static jlong VMRuntime_getFinalizerTimeoutMs(JNIEnv*, jobject) {
312   return Runtime::Current()->GetFinalizerTimeoutMs();
313 }
314 
VMRuntime_registerSensitiveThread(JNIEnv *,jobject)315 static void VMRuntime_registerSensitiveThread(JNIEnv*, jobject) {
316   Runtime::Current()->RegisterSensitiveThread();
317 }
318 
VMRuntime_updateProcessState(JNIEnv *,jobject,jint process_state)319 static void VMRuntime_updateProcessState(JNIEnv*, jobject, jint process_state) {
320   Runtime* runtime = Runtime::Current();
321   runtime->UpdateProcessState(static_cast<ProcessState>(process_state));
322 }
323 
VMRuntime_notifyStartupCompleted(JNIEnv *,jobject)324 static void VMRuntime_notifyStartupCompleted(JNIEnv*, jobject) {
325   Runtime::Current()->NotifyStartupCompleted();
326 }
327 
VMRuntime_trimHeap(JNIEnv * env,jobject)328 static void VMRuntime_trimHeap(JNIEnv* env, jobject) {
329   Runtime::Current()->GetHeap()->Trim(ThreadForEnv(env));
330 }
331 
VMRuntime_concurrentGC(JNIEnv * env,jobject)332 static void VMRuntime_concurrentGC(JNIEnv* env, jobject) {
333   Runtime::Current()->GetHeap()->ConcurrentGC(ThreadForEnv(env), gc::kGcCauseBackground, true);
334 }
335 
VMRuntime_requestHeapTrim(JNIEnv * env,jobject)336 static void VMRuntime_requestHeapTrim(JNIEnv* env, jobject) {
337   Runtime::Current()->GetHeap()->RequestTrim(ThreadForEnv(env));
338 }
339 
VMRuntime_requestConcurrentGC(JNIEnv * env,jobject)340 static void VMRuntime_requestConcurrentGC(JNIEnv* env, jobject) {
341   Runtime::Current()->GetHeap()->RequestConcurrentGC(ThreadForEnv(env),
342                                                      gc::kGcCauseBackground,
343                                                      true);
344 }
345 
VMRuntime_startHeapTaskProcessor(JNIEnv * env,jobject)346 static void VMRuntime_startHeapTaskProcessor(JNIEnv* env, jobject) {
347   Runtime::Current()->GetHeap()->GetTaskProcessor()->Start(ThreadForEnv(env));
348 }
349 
VMRuntime_stopHeapTaskProcessor(JNIEnv * env,jobject)350 static void VMRuntime_stopHeapTaskProcessor(JNIEnv* env, jobject) {
351   Runtime::Current()->GetHeap()->GetTaskProcessor()->Stop(ThreadForEnv(env));
352 }
353 
VMRuntime_runHeapTasks(JNIEnv * env,jobject)354 static void VMRuntime_runHeapTasks(JNIEnv* env, jobject) {
355   Runtime::Current()->GetHeap()->GetTaskProcessor()->RunAllTasks(ThreadForEnv(env));
356 }
357 
358 using StringTable = std::map<std::string, ObjPtr<mirror::String>>;
359 
360 class PreloadDexCachesStringsVisitor : public SingleRootVisitor {
361  public:
PreloadDexCachesStringsVisitor(StringTable * table)362   explicit PreloadDexCachesStringsVisitor(StringTable* table) : table_(table) { }
363 
VisitRoot(mirror::Object * root,const RootInfo & info ATTRIBUTE_UNUSED)364   void VisitRoot(mirror::Object* root, const RootInfo& info ATTRIBUTE_UNUSED)
365       override REQUIRES_SHARED(Locks::mutator_lock_) {
366     ObjPtr<mirror::String> string = root->AsString();
367     table_->operator[](string->ToModifiedUtf8()) = string;
368   }
369 
370  private:
371   StringTable* const table_;
372 };
373 
374 // Based on ClassLinker::ResolveString.
PreloadDexCachesResolveString(ObjPtr<mirror::DexCache> dex_cache,dex::StringIndex string_idx,StringTable & strings)375 static void PreloadDexCachesResolveString(
376     ObjPtr<mirror::DexCache> dex_cache, dex::StringIndex string_idx, StringTable& strings)
377     REQUIRES_SHARED(Locks::mutator_lock_) {
378   uint32_t slot_idx = dex_cache->StringSlotIndex(string_idx);
379   auto pair = dex_cache->GetStrings()[slot_idx].load(std::memory_order_relaxed);
380   if (!pair.object.IsNull()) {
381     return;  // The entry already contains some String.
382   }
383   const DexFile* dex_file = dex_cache->GetDexFile();
384   const char* utf8 = dex_file->StringDataByIdx(string_idx);
385   ObjPtr<mirror::String> string = strings[utf8];
386   if (string == nullptr) {
387     return;
388   }
389   // LOG(INFO) << "VMRuntime.preloadDexCaches resolved string=" << utf8;
390   dex_cache->SetResolvedString(string_idx, string);
391 }
392 
393 // Based on ClassLinker::ResolveType.
PreloadDexCachesResolveType(Thread * self,ObjPtr<mirror::DexCache> dex_cache,dex::TypeIndex type_idx)394 static void PreloadDexCachesResolveType(Thread* self,
395                                         ObjPtr<mirror::DexCache> dex_cache,
396                                         dex::TypeIndex type_idx)
397     REQUIRES_SHARED(Locks::mutator_lock_) {
398   uint32_t slot_idx = dex_cache->TypeSlotIndex(type_idx);
399   auto pair = dex_cache->GetResolvedTypes()[slot_idx].load(std::memory_order_relaxed);
400   if (!pair.object.IsNull()) {
401     return;  // The entry already contains some Class.
402   }
403   const DexFile* dex_file = dex_cache->GetDexFile();
404   const char* class_name = dex_file->StringByTypeIdx(type_idx);
405   ClassLinker* linker = Runtime::Current()->GetClassLinker();
406   ObjPtr<mirror::Class> klass = (class_name[1] == '\0')
407       ? linker->LookupPrimitiveClass(class_name[0])
408       : linker->LookupClass(self, class_name, nullptr);
409   if (klass == nullptr) {
410     return;
411   }
412   // LOG(INFO) << "VMRuntime.preloadDexCaches resolved klass=" << class_name;
413   dex_cache->SetResolvedType(type_idx, klass);
414   // Skip uninitialized classes because filled static storage entry implies it is initialized.
415   if (!klass->IsInitialized()) {
416     // LOG(INFO) << "VMRuntime.preloadDexCaches uninitialized klass=" << class_name;
417     return;
418   }
419   // LOG(INFO) << "VMRuntime.preloadDexCaches static storage klass=" << class_name;
420 }
421 
422 // Based on ClassLinker::ResolveField.
PreloadDexCachesResolveField(ObjPtr<mirror::DexCache> dex_cache,uint32_t field_idx,bool is_static)423 static void PreloadDexCachesResolveField(ObjPtr<mirror::DexCache> dex_cache,
424                                          uint32_t field_idx,
425                                          bool is_static)
426     REQUIRES_SHARED(Locks::mutator_lock_) {
427   uint32_t slot_idx = dex_cache->FieldSlotIndex(field_idx);
428   auto pair = mirror::DexCache::GetNativePairPtrSize(dex_cache->GetResolvedFields(),
429                                                      slot_idx,
430                                                      kRuntimePointerSize);
431   if (pair.object != nullptr) {
432     return;  // The entry already contains some ArtField.
433   }
434   const DexFile* dex_file = dex_cache->GetDexFile();
435   const dex::FieldId& field_id = dex_file->GetFieldId(field_idx);
436   ObjPtr<mirror::Class> klass = Runtime::Current()->GetClassLinker()->LookupResolvedType(
437       field_id.class_idx_, dex_cache, /* class_loader= */ nullptr);
438   if (klass == nullptr) {
439     return;
440   }
441   ArtField* field = is_static
442       ? mirror::Class::FindStaticField(Thread::Current(), klass, dex_cache, field_idx)
443       : klass->FindInstanceField(dex_cache, field_idx);
444   if (field == nullptr) {
445     return;
446   }
447   dex_cache->SetResolvedField(field_idx, field, kRuntimePointerSize);
448 }
449 
450 // Based on ClassLinker::ResolveMethod.
PreloadDexCachesResolveMethod(ObjPtr<mirror::DexCache> dex_cache,uint32_t method_idx)451 static void PreloadDexCachesResolveMethod(ObjPtr<mirror::DexCache> dex_cache, uint32_t method_idx)
452     REQUIRES_SHARED(Locks::mutator_lock_) {
453   uint32_t slot_idx = dex_cache->MethodSlotIndex(method_idx);
454   auto pair = mirror::DexCache::GetNativePairPtrSize(dex_cache->GetResolvedMethods(),
455                                                      slot_idx,
456                                                      kRuntimePointerSize);
457   if (pair.object != nullptr) {
458     return;  // The entry already contains some ArtMethod.
459   }
460   const DexFile* dex_file = dex_cache->GetDexFile();
461   const dex::MethodId& method_id = dex_file->GetMethodId(method_idx);
462   ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
463 
464   ObjPtr<mirror::Class> klass = class_linker->LookupResolvedType(
465       method_id.class_idx_, dex_cache, /* class_loader= */ nullptr);
466   if (klass == nullptr) {
467     return;
468   }
469   // Call FindResolvedMethod to populate the dex cache.
470   class_linker->FindResolvedMethod(klass, dex_cache, /* class_loader= */ nullptr, method_idx);
471 }
472 
473 struct DexCacheStats {
474     uint32_t num_strings;
475     uint32_t num_types;
476     uint32_t num_fields;
477     uint32_t num_methods;
DexCacheStatsart::DexCacheStats478     DexCacheStats() : num_strings(0),
479                       num_types(0),
480                       num_fields(0),
481                       num_methods(0) {}
482 };
483 
484 static const bool kPreloadDexCachesEnabled = true;
485 
486 // Disabled because it takes a long time (extra half second) but
487 // gives almost no benefit in terms of saving private dirty pages.
488 static const bool kPreloadDexCachesStrings = false;
489 
490 static const bool kPreloadDexCachesTypes = true;
491 static const bool kPreloadDexCachesFieldsAndMethods = true;
492 
493 static const bool kPreloadDexCachesCollectStats = true;
494 
PreloadDexCachesStatsTotal(DexCacheStats * total)495 static void PreloadDexCachesStatsTotal(DexCacheStats* total) {
496   if (!kPreloadDexCachesCollectStats) {
497     return;
498   }
499 
500   ClassLinker* linker = Runtime::Current()->GetClassLinker();
501   const std::vector<const DexFile*>& boot_class_path = linker->GetBootClassPath();
502   for (size_t i = 0; i< boot_class_path.size(); i++) {
503     const DexFile* dex_file = boot_class_path[i];
504     CHECK(dex_file != nullptr);
505     total->num_strings += dex_file->NumStringIds();
506     total->num_fields += dex_file->NumFieldIds();
507     total->num_methods += dex_file->NumMethodIds();
508     total->num_types += dex_file->NumTypeIds();
509   }
510 }
511 
PreloadDexCachesStatsFilled(DexCacheStats * filled)512 static void PreloadDexCachesStatsFilled(DexCacheStats* filled)
513     REQUIRES_SHARED(Locks::mutator_lock_) {
514   if (!kPreloadDexCachesCollectStats) {
515     return;
516   }
517   // TODO: Update for hash-based DexCache arrays.
518   ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
519   Thread* const self = Thread::Current();
520   for (const DexFile* dex_file : class_linker->GetBootClassPath()) {
521     CHECK(dex_file != nullptr);
522     // In fallback mode, not all boot classpath components might be registered, yet.
523     if (!class_linker->IsDexFileRegistered(self, *dex_file)) {
524       continue;
525     }
526     const ObjPtr<mirror::DexCache> dex_cache = class_linker->FindDexCache(self, *dex_file);
527     DCHECK(dex_cache != nullptr);  // Boot class path dex caches are never unloaded.
528     for (size_t j = 0, num_strings = dex_cache->NumStrings(); j < num_strings; ++j) {
529       auto pair = dex_cache->GetStrings()[j].load(std::memory_order_relaxed);
530       if (!pair.object.IsNull()) {
531         filled->num_strings++;
532       }
533     }
534     for (size_t j = 0, num_types = dex_cache->NumResolvedTypes(); j < num_types; ++j) {
535       auto pair = dex_cache->GetResolvedTypes()[j].load(std::memory_order_relaxed);
536       if (!pair.object.IsNull()) {
537         filled->num_types++;
538       }
539     }
540     for (size_t j = 0, num_fields = dex_cache->NumResolvedFields(); j < num_fields; ++j) {
541       auto pair = mirror::DexCache::GetNativePairPtrSize(dex_cache->GetResolvedFields(),
542                                                          j,
543                                                          kRuntimePointerSize);
544       if (pair.object != nullptr) {
545         filled->num_fields++;
546       }
547     }
548     for (size_t j = 0, num_methods = dex_cache->NumResolvedMethods(); j < num_methods; ++j) {
549       auto pair = mirror::DexCache::GetNativePairPtrSize(dex_cache->GetResolvedMethods(),
550                                                          j,
551                                                          kRuntimePointerSize);
552       if (pair.object != nullptr) {
553         filled->num_methods++;
554       }
555     }
556   }
557 }
558 
559 // TODO: http://b/11309598 This code was ported over based on the
560 // Dalvik version. However, ART has similar code in other places such
561 // as the CompilerDriver. This code could probably be refactored to
562 // serve both uses.
VMRuntime_preloadDexCaches(JNIEnv * env,jobject)563 static void VMRuntime_preloadDexCaches(JNIEnv* env, jobject) {
564   if (!kPreloadDexCachesEnabled) {
565     return;
566   }
567 
568   ScopedObjectAccess soa(env);
569 
570   DexCacheStats total;
571   DexCacheStats before;
572   if (kPreloadDexCachesCollectStats) {
573     LOG(INFO) << "VMRuntime.preloadDexCaches starting";
574     PreloadDexCachesStatsTotal(&total);
575     PreloadDexCachesStatsFilled(&before);
576   }
577 
578   Runtime* runtime = Runtime::Current();
579   ClassLinker* linker = runtime->GetClassLinker();
580 
581   // We use a std::map to avoid heap allocating StringObjects to lookup in gDvm.literalStrings
582   StringTable strings;
583   if (kPreloadDexCachesStrings) {
584     PreloadDexCachesStringsVisitor visitor(&strings);
585     runtime->GetInternTable()->VisitRoots(&visitor, kVisitRootFlagAllRoots);
586   }
587 
588   const std::vector<const DexFile*>& boot_class_path = linker->GetBootClassPath();
589   for (size_t i = 0; i < boot_class_path.size(); i++) {
590     const DexFile* dex_file = boot_class_path[i];
591     CHECK(dex_file != nullptr);
592     ObjPtr<mirror::DexCache> dex_cache = linker->RegisterDexFile(*dex_file, nullptr);
593     CHECK(dex_cache != nullptr);  // Boot class path dex caches are never unloaded.
594     if (kPreloadDexCachesStrings) {
595       for (size_t j = 0; j < dex_cache->NumStrings(); j++) {
596         PreloadDexCachesResolveString(dex_cache, dex::StringIndex(j), strings);
597       }
598     }
599 
600     if (kPreloadDexCachesTypes) {
601       for (size_t j = 0; j < dex_cache->NumResolvedTypes(); j++) {
602         PreloadDexCachesResolveType(soa.Self(), dex_cache, dex::TypeIndex(j));
603       }
604     }
605 
606     if (kPreloadDexCachesFieldsAndMethods) {
607       for (ClassAccessor accessor : dex_file->GetClasses()) {
608         for (const ClassAccessor::Field& field : accessor.GetFields()) {
609           PreloadDexCachesResolveField(dex_cache, field.GetIndex(), field.IsStatic());
610         }
611         for (const ClassAccessor::Method& method : accessor.GetMethods()) {
612           PreloadDexCachesResolveMethod(dex_cache, method.GetIndex());
613         }
614       }
615     }
616   }
617 
618   if (kPreloadDexCachesCollectStats) {
619     DexCacheStats after;
620     PreloadDexCachesStatsFilled(&after);
621     LOG(INFO) << StringPrintf("VMRuntime.preloadDexCaches strings total=%d before=%d after=%d",
622                               total.num_strings, before.num_strings, after.num_strings);
623     LOG(INFO) << StringPrintf("VMRuntime.preloadDexCaches types total=%d before=%d after=%d",
624                               total.num_types, before.num_types, after.num_types);
625     LOG(INFO) << StringPrintf("VMRuntime.preloadDexCaches fields total=%d before=%d after=%d",
626                               total.num_fields, before.num_fields, after.num_fields);
627     LOG(INFO) << StringPrintf("VMRuntime.preloadDexCaches methods total=%d before=%d after=%d",
628                               total.num_methods, before.num_methods, after.num_methods);
629     LOG(INFO) << StringPrintf("VMRuntime.preloadDexCaches finished");
630   }
631 }
632 
633 
634 /*
635  * This is called by the framework when it knows the application directory and
636  * process name.
637  */
VMRuntime_registerAppInfo(JNIEnv * env,jclass clazz ATTRIBUTE_UNUSED,jstring profile_file,jobjectArray code_paths)638 static void VMRuntime_registerAppInfo(JNIEnv* env,
639                                       jclass clazz ATTRIBUTE_UNUSED,
640                                       jstring profile_file,
641                                       jobjectArray code_paths) {
642   std::vector<std::string> code_paths_vec;
643   int code_paths_length = env->GetArrayLength(code_paths);
644   for (int i = 0; i < code_paths_length; i++) {
645     jstring code_path = reinterpret_cast<jstring>(env->GetObjectArrayElement(code_paths, i));
646     const char* raw_code_path = env->GetStringUTFChars(code_path, nullptr);
647     code_paths_vec.push_back(raw_code_path);
648     env->ReleaseStringUTFChars(code_path, raw_code_path);
649   }
650 
651   const char* raw_profile_file = env->GetStringUTFChars(profile_file, nullptr);
652   std::string profile_file_str(raw_profile_file);
653   env->ReleaseStringUTFChars(profile_file, raw_profile_file);
654 
655   Runtime::Current()->RegisterAppInfo(code_paths_vec, profile_file_str);
656 }
657 
VMRuntime_isBootClassPathOnDisk(JNIEnv * env,jclass,jstring java_instruction_set)658 static jboolean VMRuntime_isBootClassPathOnDisk(JNIEnv* env, jclass, jstring java_instruction_set) {
659   ScopedUtfChars instruction_set(env, java_instruction_set);
660   if (instruction_set.c_str() == nullptr) {
661     return JNI_FALSE;
662   }
663   InstructionSet isa = GetInstructionSetFromString(instruction_set.c_str());
664   if (isa == InstructionSet::kNone) {
665     ScopedLocalRef<jclass> iae(env, env->FindClass("java/lang/IllegalArgumentException"));
666     std::string message(StringPrintf("Instruction set %s is invalid.", instruction_set.c_str()));
667     env->ThrowNew(iae.get(), message.c_str());
668     return JNI_FALSE;
669   }
670   std::string error_msg;
671   Runtime* runtime = Runtime::Current();
672   std::unique_ptr<ImageHeader> image_header(gc::space::ImageSpace::ReadImageHeader(
673       runtime->GetImageLocation().c_str(), isa, runtime->GetImageSpaceLoadingOrder(), &error_msg));
674   return image_header.get() != nullptr;
675 }
676 
VMRuntime_getCurrentInstructionSet(JNIEnv * env,jclass)677 static jstring VMRuntime_getCurrentInstructionSet(JNIEnv* env, jclass) {
678   return env->NewStringUTF(GetInstructionSetString(kRuntimeISA));
679 }
680 
VMRuntime_didPruneDalvikCache(JNIEnv * env ATTRIBUTE_UNUSED,jclass klass ATTRIBUTE_UNUSED)681 static jboolean VMRuntime_didPruneDalvikCache(JNIEnv* env ATTRIBUTE_UNUSED,
682                                               jclass klass ATTRIBUTE_UNUSED) {
683   return Runtime::Current()->GetPrunedDalvikCache() ? JNI_TRUE : JNI_FALSE;
684 }
685 
VMRuntime_setSystemDaemonThreadPriority(JNIEnv * env ATTRIBUTE_UNUSED,jclass klass ATTRIBUTE_UNUSED)686 static void VMRuntime_setSystemDaemonThreadPriority(JNIEnv* env ATTRIBUTE_UNUSED,
687                                                     jclass klass ATTRIBUTE_UNUSED) {
688 #ifdef ART_TARGET_ANDROID
689   Thread* self = Thread::Current();
690   DCHECK(self != nullptr);
691   pid_t tid = self->GetTid();
692   // We use a priority lower than the default for the system daemon threads (eg HeapTaskDaemon) to
693   // avoid jank due to CPU contentions between GC and other UI-related threads. b/36631902.
694   // We may use a native priority that doesn't have a corresponding java.lang.Thread-level priority.
695   static constexpr int kSystemDaemonNiceValue = 4;  // priority 124
696   if (setpriority(PRIO_PROCESS, tid, kSystemDaemonNiceValue) != 0) {
697     PLOG(INFO) << *self << " setpriority(PRIO_PROCESS, " << tid << ", "
698                << kSystemDaemonNiceValue << ") failed";
699   }
700 #endif
701 }
702 
VMRuntime_setDedupeHiddenApiWarnings(JNIEnv * env ATTRIBUTE_UNUSED,jclass klass ATTRIBUTE_UNUSED,jboolean dedupe)703 static void VMRuntime_setDedupeHiddenApiWarnings(JNIEnv* env ATTRIBUTE_UNUSED,
704                                                  jclass klass ATTRIBUTE_UNUSED,
705                                                  jboolean dedupe) {
706   Runtime::Current()->SetDedupeHiddenApiWarnings(dedupe);
707 }
708 
VMRuntime_setProcessPackageName(JNIEnv * env,jclass klass ATTRIBUTE_UNUSED,jstring java_package_name)709 static void VMRuntime_setProcessPackageName(JNIEnv* env,
710                                             jclass klass ATTRIBUTE_UNUSED,
711                                             jstring java_package_name) {
712   ScopedUtfChars package_name(env, java_package_name);
713   Runtime::Current()->SetProcessPackageName(package_name.c_str());
714 }
715 
VMRuntime_setProcessDataDirectory(JNIEnv * env,jclass,jstring java_data_dir)716 static void VMRuntime_setProcessDataDirectory(JNIEnv* env, jclass, jstring java_data_dir) {
717   ScopedUtfChars data_dir(env, java_data_dir);
718   Runtime::Current()->SetProcessDataDirectory(data_dir.c_str());
719 }
720 
VMRuntime_hasBootImageSpaces(JNIEnv * env ATTRIBUTE_UNUSED,jclass klass ATTRIBUTE_UNUSED)721 static jboolean VMRuntime_hasBootImageSpaces(JNIEnv* env ATTRIBUTE_UNUSED,
722                                              jclass klass ATTRIBUTE_UNUSED) {
723   return Runtime::Current()->GetHeap()->HasBootImageSpace() ? JNI_TRUE : JNI_FALSE;
724 }
725 
726 static JNINativeMethod gMethods[] = {
727   FAST_NATIVE_METHOD(VMRuntime, addressOf, "(Ljava/lang/Object;)J"),
728   NATIVE_METHOD(VMRuntime, bootClassPath, "()Ljava/lang/String;"),
729   NATIVE_METHOD(VMRuntime, clampGrowthLimit, "()V"),
730   NATIVE_METHOD(VMRuntime, classPath, "()Ljava/lang/String;"),
731   NATIVE_METHOD(VMRuntime, clearGrowthLimit, "()V"),
732   NATIVE_METHOD(VMRuntime, concurrentGC, "()V"),
733   NATIVE_METHOD(VMRuntime, disableJitCompilation, "()V"),
734   FAST_NATIVE_METHOD(VMRuntime, hasBootImageSpaces, "()Z"),  // Could be CRITICAL.
735   NATIVE_METHOD(VMRuntime, setHiddenApiExemptions, "([Ljava/lang/String;)V"),
736   NATIVE_METHOD(VMRuntime, setHiddenApiAccessLogSamplingRate, "(I)V"),
737   NATIVE_METHOD(VMRuntime, getTargetHeapUtilization, "()F"),
738   FAST_NATIVE_METHOD(VMRuntime, isDebuggerActive, "()Z"),
739   FAST_NATIVE_METHOD(VMRuntime, isNativeDebuggable, "()Z"),
740   NATIVE_METHOD(VMRuntime, isJavaDebuggable, "()Z"),
741   NATIVE_METHOD(VMRuntime, nativeSetTargetHeapUtilization, "(F)V"),
742   FAST_NATIVE_METHOD(VMRuntime, newNonMovableArray, "(Ljava/lang/Class;I)Ljava/lang/Object;"),
743   FAST_NATIVE_METHOD(VMRuntime, newUnpaddedArray, "(Ljava/lang/Class;I)Ljava/lang/Object;"),
744   NATIVE_METHOD(VMRuntime, properties, "()[Ljava/lang/String;"),
745   NATIVE_METHOD(VMRuntime, setTargetSdkVersionNative, "(I)V"),
746   NATIVE_METHOD(VMRuntime, registerNativeAllocation, "(J)V"),
747   NATIVE_METHOD(VMRuntime, registerNativeFree, "(J)V"),
748   NATIVE_METHOD(VMRuntime, getNotifyNativeInterval, "()I"),
749   NATIVE_METHOD(VMRuntime, getFinalizerTimeoutMs, "()J"),
750   NATIVE_METHOD(VMRuntime, notifyNativeAllocationsInternal, "()V"),
751   NATIVE_METHOD(VMRuntime, notifyStartupCompleted, "()V"),
752   NATIVE_METHOD(VMRuntime, registerSensitiveThread, "()V"),
753   NATIVE_METHOD(VMRuntime, requestConcurrentGC, "()V"),
754   NATIVE_METHOD(VMRuntime, requestHeapTrim, "()V"),
755   NATIVE_METHOD(VMRuntime, runHeapTasks, "()V"),
756   NATIVE_METHOD(VMRuntime, updateProcessState, "(I)V"),
757   NATIVE_METHOD(VMRuntime, startHeapTaskProcessor, "()V"),
758   NATIVE_METHOD(VMRuntime, startJitCompilation, "()V"),
759   NATIVE_METHOD(VMRuntime, stopHeapTaskProcessor, "()V"),
760   NATIVE_METHOD(VMRuntime, trimHeap, "()V"),
761   NATIVE_METHOD(VMRuntime, vmVersion, "()Ljava/lang/String;"),
762   NATIVE_METHOD(VMRuntime, vmLibrary, "()Ljava/lang/String;"),
763   NATIVE_METHOD(VMRuntime, vmInstructionSet, "()Ljava/lang/String;"),
764   FAST_NATIVE_METHOD(VMRuntime, is64Bit, "()Z"),
765   FAST_NATIVE_METHOD(VMRuntime, isCheckJniEnabled, "()Z"),
766   NATIVE_METHOD(VMRuntime, preloadDexCaches, "()V"),
767   NATIVE_METHOD(VMRuntime, registerAppInfo, "(Ljava/lang/String;[Ljava/lang/String;)V"),
768   NATIVE_METHOD(VMRuntime, isBootClassPathOnDisk, "(Ljava/lang/String;)Z"),
769   NATIVE_METHOD(VMRuntime, getCurrentInstructionSet, "()Ljava/lang/String;"),
770   NATIVE_METHOD(VMRuntime, didPruneDalvikCache, "()Z"),
771   NATIVE_METHOD(VMRuntime, setSystemDaemonThreadPriority, "()V"),
772   NATIVE_METHOD(VMRuntime, setDedupeHiddenApiWarnings, "(Z)V"),
773   NATIVE_METHOD(VMRuntime, setProcessPackageName, "(Ljava/lang/String;)V"),
774   NATIVE_METHOD(VMRuntime, setProcessDataDirectory, "(Ljava/lang/String;)V"),
775 };
776 
register_dalvik_system_VMRuntime(JNIEnv * env)777 void register_dalvik_system_VMRuntime(JNIEnv* env) {
778   REGISTER_NATIVE_METHODS("dalvik/system/VMRuntime");
779 }
780 
781 }  // namespace art
782