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