• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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.h>
26 
27 #include <limits>
28 
29 #include "android-base/properties.h"
30 #include "android-base/stringprintf.h"
31 #include "android-base/strings.h"
32 #include "arch/instruction_set.h"
33 #include "art_method-inl.h"
34 #include "base/pointer_size.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/art-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 "metrics/statsd.h"
54 #include "mirror/array-alloc-inl.h"
55 #include "mirror/class-inl.h"
56 #include "mirror/dex_cache-inl.h"
57 #include "mirror/object-inl.h"
58 #include "native_util.h"
59 #include "nativehelper/jni_macros.h"
60 #include "nativehelper/scoped_local_ref.h"
61 #include "nativehelper/scoped_utf_chars.h"
62 #include "runtime.h"
63 #include "scoped_fast_native_object_access-inl.h"
64 #include "scoped_thread_state_change-inl.h"
65 #include "startup_completed_task.h"
66 #include "string_array_utils.h"
67 #include "thread-inl.h"
68 #include "thread_list.h"
69 
70 namespace art HIDDEN {
71 
72 using android::base::StringPrintf;
73 
VMRuntime_getTargetHeapUtilization(JNIEnv *,jobject)74 static jfloat VMRuntime_getTargetHeapUtilization(JNIEnv*, jobject) {
75   return Runtime::Current()->GetHeap()->GetTargetHeapUtilization();
76 }
77 
VMRuntime_nativeSetTargetHeapUtilization(JNIEnv *,jobject,jfloat target)78 static void VMRuntime_nativeSetTargetHeapUtilization(JNIEnv*, jobject, jfloat target) {
79   Runtime::Current()->GetHeap()->SetTargetHeapUtilization(target);
80 }
81 
VMRuntime_setHiddenApiExemptions(JNIEnv * env,jclass,jobjectArray exemptions)82 static void VMRuntime_setHiddenApiExemptions(JNIEnv* env,
83                                             jclass,
84                                             jobjectArray exemptions) {
85   std::vector<std::string> exemptions_vec;
86   int exemptions_length = env->GetArrayLength(exemptions);
87   for (int i = 0; i < exemptions_length; i++) {
88     jstring exemption = reinterpret_cast<jstring>(env->GetObjectArrayElement(exemptions, i));
89     const char* raw_exemption = env->GetStringUTFChars(exemption, nullptr);
90     exemptions_vec.push_back(raw_exemption);
91     env->ReleaseStringUTFChars(exemption, raw_exemption);
92   }
93 
94   Runtime::Current()->SetHiddenApiExemptions(exemptions_vec);
95 }
96 
VMRuntime_setHiddenApiAccessLogSamplingRate(JNIEnv *,jclass,jint rate)97 static void VMRuntime_setHiddenApiAccessLogSamplingRate(JNIEnv*, jclass, jint rate) {
98   Runtime::Current()->SetHiddenApiEventLogSampleRate(rate);
99 }
100 
VMRuntime_newNonMovableArray(JNIEnv * env,jobject,jclass javaElementClass,jint length)101 static jobject VMRuntime_newNonMovableArray(JNIEnv* env, jobject, jclass javaElementClass,
102                                             jint length) {
103   ScopedFastNativeObjectAccess soa(env);
104   if (UNLIKELY(length < 0)) {
105     ThrowNegativeArraySizeException(length);
106     return nullptr;
107   }
108   ObjPtr<mirror::Class> element_class = soa.Decode<mirror::Class>(javaElementClass);
109   if (UNLIKELY(element_class == nullptr)) {
110     ThrowNullPointerException("element class == null");
111     return nullptr;
112   }
113   Runtime* runtime = Runtime::Current();
114   ObjPtr<mirror::Class> array_class =
115       runtime->GetClassLinker()->FindArrayClass(soa.Self(), element_class);
116   if (UNLIKELY(array_class == nullptr)) {
117     return nullptr;
118   }
119   gc::AllocatorType allocator = runtime->GetHeap()->GetCurrentNonMovingAllocator();
120   ObjPtr<mirror::Array> result = mirror::Array::Alloc(soa.Self(),
121                                                       array_class,
122                                                       length,
123                                                       array_class->GetComponentSizeShift(),
124                                                       allocator);
125   return soa.AddLocalReference<jobject>(result);
126 }
127 
VMRuntime_newUnpaddedArray(JNIEnv * env,jobject,jclass javaElementClass,jint length)128 static jobject VMRuntime_newUnpaddedArray(JNIEnv* env, jobject, jclass javaElementClass,
129                                           jint length) {
130   ScopedFastNativeObjectAccess soa(env);
131   if (UNLIKELY(length < 0)) {
132     ThrowNegativeArraySizeException(length);
133     return nullptr;
134   }
135   ObjPtr<mirror::Class> element_class = soa.Decode<mirror::Class>(javaElementClass);
136   if (UNLIKELY(element_class == nullptr)) {
137     ThrowNullPointerException("element class == null");
138     return nullptr;
139   }
140   Runtime* runtime = Runtime::Current();
141   ObjPtr<mirror::Class> array_class = runtime->GetClassLinker()->FindArrayClass(soa.Self(),
142                                                                                 element_class);
143   if (UNLIKELY(array_class == nullptr)) {
144     return nullptr;
145   }
146   gc::AllocatorType allocator = runtime->GetHeap()->GetCurrentAllocator();
147   ObjPtr<mirror::Array> result =
148       mirror::Array::Alloc</*kIsInstrumented=*/ true, /*kFillUsable=*/ 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 (array->IsObjectArray()) {
168     ThrowIllegalArgumentException("not a primitive array");
169     return 0;
170   }
171   if (Runtime::Current()->GetHeap()->IsMovableObject(array)) {
172     ThrowRuntimeException("Trying to get address of movable array object");
173     return 0;
174   }
175   return reinterpret_cast<uintptr_t>(array->GetRawData(array->GetClass()->GetComponentSize(), 0));
176 }
177 
VMRuntime_clearGrowthLimit(JNIEnv *,jobject)178 static void VMRuntime_clearGrowthLimit(JNIEnv*, jobject) {
179   Runtime::Current()->GetHeap()->ClearGrowthLimit();
180 }
181 
VMRuntime_clampGrowthLimit(JNIEnv *,jobject)182 static void VMRuntime_clampGrowthLimit(JNIEnv*, jobject) {
183   Runtime::Current()->GetHeap()->ClampGrowthLimit();
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   const std::vector<std::string>& properties = Runtime::Current()->GetProperties();
196   ScopedObjectAccess soa(Thread::ForEnv(env));
197   return soa.AddLocalReference<jobjectArray>(CreateStringArray(soa.Self(), properties));
198 }
199 
200 // This is for backward compatibility with dalvik which returned the
201 // meaningless "." when no boot classpath or classpath was
202 // specified. Unfortunately, some tests were using java.class.path to
203 // lookup relative file locations, so they are counting on this to be
204 // ".", presumably some applications or libraries could have as well.
DefaultToDot(const std::string & class_path)205 static const char* DefaultToDot(const std::string& class_path) {
206   return class_path.empty() ? "." : class_path.c_str();
207 }
208 
VMRuntime_bootClassPath(JNIEnv * env,jobject)209 static jstring VMRuntime_bootClassPath(JNIEnv* env, jobject) {
210   std::string boot_class_path = android::base::Join(Runtime::Current()->GetBootClassPath(), ':');
211   return env->NewStringUTF(DefaultToDot(boot_class_path));
212 }
213 
VMRuntime_classPath(JNIEnv * env,jobject)214 static jstring VMRuntime_classPath(JNIEnv* env, jobject) {
215   return env->NewStringUTF(DefaultToDot(Runtime::Current()->GetClassPathString()));
216 }
217 
VMRuntime_vmVersion(JNIEnv * env,jobject)218 static jstring VMRuntime_vmVersion(JNIEnv* env, jobject) {
219   return env->NewStringUTF(Runtime::GetVersion());
220 }
221 
VMRuntime_vmLibrary(JNIEnv * env,jobject)222 static jstring VMRuntime_vmLibrary(JNIEnv* env, jobject) {
223   return env->NewStringUTF(kIsDebugBuild ? "libartd.so" : "libart.so");
224 }
225 
VMRuntime_vmInstructionSet(JNIEnv * env,jobject)226 static jstring VMRuntime_vmInstructionSet(JNIEnv* env, jobject) {
227   InstructionSet isa = Runtime::Current()->GetInstructionSet();
228   const char* isa_string = GetInstructionSetString(isa);
229   return env->NewStringUTF(isa_string);
230 }
231 
VMRuntime_is64Bit(JNIEnv *,jobject)232 static jboolean VMRuntime_is64Bit(JNIEnv*, jobject) {
233   bool is64BitMode = (sizeof(void*) == sizeof(uint64_t));
234   return is64BitMode ? JNI_TRUE : JNI_FALSE;
235 }
236 
VMRuntime_isCheckJniEnabled(JNIEnv * env,jobject)237 static jboolean VMRuntime_isCheckJniEnabled(JNIEnv* env, jobject) {
238   return down_cast<JNIEnvExt*>(env)->GetVm()->IsCheckJniEnabled() ? JNI_TRUE : JNI_FALSE;
239 }
240 
VMRuntime_getSdkVersionNative(JNIEnv * env,jclass klass,jint default_sdk_version)241 static jint VMRuntime_getSdkVersionNative([[maybe_unused]] JNIEnv* env,
242                                           [[maybe_unused]] jclass klass,
243                                           jint default_sdk_version) {
244   return android::base::GetIntProperty("ro.build.version.sdk",
245                                        default_sdk_version);
246 }
247 
VMRuntime_getIntSystemProperty(JNIEnv * env,jclass klass,jstring attribute_name,jint default_value)248 static jint VMRuntime_getIntSystemProperty([[maybe_unused]] JNIEnv* env,
249                                            [[maybe_unused]] jclass klass,
250                                            jstring attribute_name,
251                                            jint default_value) {
252   return android::base::GetIntProperty(std::string(ScopedUtfChars(env, attribute_name)),
253                                        default_value);
254 }
255 
VMRuntime_setTargetSdkVersionNative(JNIEnv *,jobject,jint target_sdk_version)256 static void VMRuntime_setTargetSdkVersionNative(JNIEnv*, jobject, jint target_sdk_version) {
257   // This is the target SDK version of the app we're about to run. It is intended that this a place
258   // where workarounds can be enabled.
259   // Note that targetSdkVersion may be CUR_DEVELOPMENT (10000).
260   // Note that targetSdkVersion may be 0, meaning "current".
261   uint32_t uint_target_sdk_version =
262       target_sdk_version <= 0 ? static_cast<uint32_t>(SdkVersion::kUnset)
263                               : static_cast<uint32_t>(target_sdk_version);
264   Runtime::Current()->SetTargetSdkVersion(uint_target_sdk_version);
265 
266 #ifdef ART_TARGET_ANDROID
267   // This part is letting libc/dynamic linker know about current app's
268   // target sdk version to enable compatibility workarounds.
269   android_set_application_target_sdk_version(uint_target_sdk_version);
270 #endif
271 }
272 
VMRuntime_setDisabledCompatChangesNative(JNIEnv * env,jobject,jlongArray disabled_compat_changes)273 static void VMRuntime_setDisabledCompatChangesNative(JNIEnv* env, jobject,
274     jlongArray disabled_compat_changes) {
275   if (disabled_compat_changes == nullptr) {
276     return;
277   }
278   std::set<uint64_t> disabled_compat_changes_set;
279   {
280     ScopedObjectAccess soa(env);
281     ObjPtr<mirror::LongArray> array = soa.Decode<mirror::LongArray>(disabled_compat_changes);
282     int length = array->GetLength();
283     for (int i = 0; i < length; i++) {
284       disabled_compat_changes_set.insert(static_cast<uint64_t>(array->Get(i)));
285     }
286   }
287   Runtime::Current()->GetCompatFramework().SetDisabledCompatChanges(disabled_compat_changes_set);
288 }
289 
clamp_to_size_t(jlong n)290 static inline size_t clamp_to_size_t(jlong n) {
291   if (sizeof(jlong) > sizeof(size_t)
292       && UNLIKELY(n > static_cast<jlong>(std::numeric_limits<size_t>::max()))) {
293     return std::numeric_limits<size_t>::max();
294   } else {
295     return n;
296   }
297 }
298 
VMRuntime_registerNativeAllocation(JNIEnv * env,jobject,jlong bytes)299 static void VMRuntime_registerNativeAllocation(JNIEnv* env, jobject, jlong bytes) {
300   if (UNLIKELY(bytes < 0)) {
301     ScopedObjectAccess soa(env);
302     ThrowRuntimeException("allocation size negative %" PRId64, bytes);
303     return;
304   }
305   Runtime::Current()->GetHeap()->RegisterNativeAllocation(env, clamp_to_size_t(bytes));
306 }
307 
VMRuntime_registerNativeFree(JNIEnv * env,jobject,jlong bytes)308 static void VMRuntime_registerNativeFree(JNIEnv* env, jobject, jlong bytes) {
309   if (UNLIKELY(bytes < 0)) {
310     ScopedObjectAccess soa(env);
311     ThrowRuntimeException("allocation size negative %" PRId64, bytes);
312     return;
313   }
314   Runtime::Current()->GetHeap()->RegisterNativeFree(env, clamp_to_size_t(bytes));
315 }
316 
VMRuntime_getNotifyNativeInterval(JNIEnv *,jclass)317 static jint VMRuntime_getNotifyNativeInterval(JNIEnv*, jclass) {
318   return Runtime::Current()->GetHeap()->GetNotifyNativeInterval();
319 }
320 
VMRuntime_notifyNativeAllocationsInternal(JNIEnv * env,jobject)321 static void VMRuntime_notifyNativeAllocationsInternal(JNIEnv* env, jobject) {
322   Runtime::Current()->GetHeap()->NotifyNativeAllocations(env);
323 }
324 
VMRuntime_getFinalizerTimeoutMs(JNIEnv *,jobject)325 static jlong VMRuntime_getFinalizerTimeoutMs(JNIEnv*, jobject) {
326   return Runtime::Current()->GetFinalizerTimeoutMs();
327 }
328 
VMRuntime_registerSensitiveThread(JNIEnv *,jobject)329 static void VMRuntime_registerSensitiveThread(JNIEnv*, jobject) {
330   Runtime::Current()->RegisterSensitiveThread();
331 }
332 
VMRuntime_updateProcessState(JNIEnv *,jobject,jint process_state)333 static void VMRuntime_updateProcessState(JNIEnv*, jobject, jint process_state) {
334   Runtime* runtime = Runtime::Current();
335   runtime->UpdateProcessState(static_cast<ProcessState>(process_state));
336 }
337 
VMRuntime_notifyStartupCompleted(JNIEnv *,jobject)338 static void VMRuntime_notifyStartupCompleted(JNIEnv*, jobject) {
339   Runtime::Current()->GetHeap()->AddHeapTask(new StartupCompletedTask(NanoTime()));
340 }
341 
VMRuntime_trimHeap(JNIEnv * env,jobject)342 static void VMRuntime_trimHeap(JNIEnv* env, jobject) {
343   Runtime::Current()->GetHeap()->Trim(Thread::ForEnv(env));
344 }
345 
VMRuntime_requestHeapTrim(JNIEnv * env,jobject)346 static void VMRuntime_requestHeapTrim(JNIEnv* env, jobject) {
347   Runtime::Current()->GetHeap()->RequestTrim(Thread::ForEnv(env));
348 }
349 
VMRuntime_requestConcurrentGC(JNIEnv * env,jobject)350 static void VMRuntime_requestConcurrentGC(JNIEnv* env, jobject) {
351   gc::Heap *heap = Runtime::Current()->GetHeap();
352   heap->RequestConcurrentGC(Thread::ForEnv(env),
353                             gc::kGcCauseBackground,
354                             true,
355                             heap->GetCurrentGcNum());
356 }
357 
VMRuntime_startHeapTaskProcessor(JNIEnv * env,jobject)358 static void VMRuntime_startHeapTaskProcessor(JNIEnv* env, jobject) {
359   Runtime::Current()->GetHeap()->GetTaskProcessor()->Start(Thread::ForEnv(env));
360 }
361 
VMRuntime_stopHeapTaskProcessor(JNIEnv * env,jobject)362 static void VMRuntime_stopHeapTaskProcessor(JNIEnv* env, jobject) {
363   Runtime::Current()->GetHeap()->GetTaskProcessor()->Stop(Thread::ForEnv(env));
364 }
365 
VMRuntime_runHeapTasks(JNIEnv * env,jobject)366 static void VMRuntime_runHeapTasks(JNIEnv* env, jobject) {
367   Runtime::Current()->GetHeap()->GetTaskProcessor()->RunAllTasks(Thread::ForEnv(env));
368 }
369 
VMRuntime_preloadDexCaches(JNIEnv * env,jobject)370 static void VMRuntime_preloadDexCaches([[maybe_unused]] JNIEnv* env, jobject) {}
371 
372 /*
373  * This is called by the framework after it loads a code path on behalf of the app.
374  * The code_path_type indicates the type of the apk being loaded and can be used
375  * for more precise telemetry (e.g. is the split apk odex up to date?) and debugging.
376  */
VMRuntime_registerAppInfo(JNIEnv * env,jclass clazz,jstring package_name,jstring cur_profile_file,jstring ref_profile_file,jobjectArray code_paths,jint code_path_type)377 static void VMRuntime_registerAppInfo(JNIEnv* env,
378                                       [[maybe_unused]] jclass clazz,
379                                       jstring package_name,
380                                       jstring cur_profile_file,
381                                       jstring ref_profile_file,
382                                       jobjectArray code_paths,
383                                       jint code_path_type) {
384   std::vector<std::string> code_paths_vec;
385   int code_paths_length = env->GetArrayLength(code_paths);
386   for (int i = 0; i < code_paths_length; i++) {
387     jstring code_path = reinterpret_cast<jstring>(env->GetObjectArrayElement(code_paths, i));
388     const char* raw_code_path = env->GetStringUTFChars(code_path, nullptr);
389     code_paths_vec.push_back(raw_code_path);
390     env->ReleaseStringUTFChars(code_path, raw_code_path);
391   }
392 
393   const char* raw_cur_profile_file = env->GetStringUTFChars(cur_profile_file, nullptr);
394   std::string cur_profile_file_str(raw_cur_profile_file);
395   env->ReleaseStringUTFChars(cur_profile_file, raw_cur_profile_file);
396 
397   const char* raw_ref_profile_file = env->GetStringUTFChars(ref_profile_file, nullptr);
398   std::string ref_profile_file_str(raw_ref_profile_file);
399   env->ReleaseStringUTFChars(ref_profile_file, raw_ref_profile_file);
400 
401   const char* raw_package_name = env->GetStringUTFChars(package_name, nullptr);
402   std::string package_name_str(raw_package_name);
403   env->ReleaseStringUTFChars(package_name, raw_package_name);
404 
405   Runtime::Current()->RegisterAppInfo(
406       package_name_str,
407       code_paths_vec,
408       cur_profile_file_str,
409       ref_profile_file_str,
410       static_cast<int32_t>(code_path_type));
411 }
412 
VMRuntime_isBootClassPathOnDisk(JNIEnv * env,jclass,jstring java_instruction_set)413 static jboolean VMRuntime_isBootClassPathOnDisk(JNIEnv* env, jclass, jstring java_instruction_set) {
414   ScopedUtfChars instruction_set(env, java_instruction_set);
415   if (instruction_set.c_str() == nullptr) {
416     return JNI_FALSE;
417   }
418   InstructionSet isa = GetInstructionSetFromString(instruction_set.c_str());
419   if (isa == InstructionSet::kNone) {
420     ScopedLocalRef<jclass> iae(env, env->FindClass("java/lang/IllegalArgumentException"));
421     std::string message(StringPrintf("Instruction set %s is invalid.", instruction_set.c_str()));
422     env->ThrowNew(iae.get(), message.c_str());
423     return JNI_FALSE;
424   }
425   return gc::space::ImageSpace::IsBootClassPathOnDisk(isa);
426 }
427 
VMRuntime_getCurrentInstructionSet(JNIEnv * env,jclass)428 static jstring VMRuntime_getCurrentInstructionSet(JNIEnv* env, jclass) {
429   return env->NewStringUTF(GetInstructionSetString(kRuntimeISA));
430 }
431 
VMRuntime_setSystemDaemonThreadPriority(JNIEnv * env,jclass klass)432 static void VMRuntime_setSystemDaemonThreadPriority([[maybe_unused]] JNIEnv* env,
433                                                     [[maybe_unused]] jclass klass) {
434 #ifdef ART_TARGET_ANDROID
435   Thread* self = Thread::Current();
436   DCHECK(self != nullptr);
437   pid_t tid = self->GetTid();
438   // We use a priority lower than the default for the system daemon threads (eg HeapTaskDaemon) to
439   // avoid jank due to CPU contentions between GC and other UI-related threads. b/36631902.
440   // We may use a native priority that doesn't have a corresponding java.lang.Thread-level priority.
441   static constexpr int kSystemDaemonNiceValue = 4;  // priority 124
442   if (setpriority(PRIO_PROCESS, tid, kSystemDaemonNiceValue) != 0) {
443     PLOG(INFO) << *self << " setpriority(PRIO_PROCESS, " << tid << ", "
444                << kSystemDaemonNiceValue << ") failed";
445   }
446 #endif
447 }
448 
VMRuntime_setDedupeHiddenApiWarnings(JNIEnv * env,jclass klass,jboolean dedupe)449 static void VMRuntime_setDedupeHiddenApiWarnings([[maybe_unused]] JNIEnv* env,
450                                                  [[maybe_unused]] jclass klass,
451                                                  jboolean dedupe) {
452   Runtime::Current()->SetDedupeHiddenApiWarnings(dedupe);
453 }
454 
VMRuntime_setProcessPackageName(JNIEnv * env,jclass klass,jstring java_package_name)455 static void VMRuntime_setProcessPackageName(JNIEnv* env,
456                                             [[maybe_unused]] jclass klass,
457                                             jstring java_package_name) {
458   ScopedUtfChars package_name(env, java_package_name);
459   Runtime::Current()->SetProcessPackageName(package_name.c_str());
460 }
461 
VMRuntime_setProcessDataDirectory(JNIEnv * env,jclass,jstring java_data_dir)462 static void VMRuntime_setProcessDataDirectory(JNIEnv* env, jclass, jstring java_data_dir) {
463   ScopedUtfChars data_dir(env, java_data_dir);
464   Runtime::Current()->SetProcessDataDirectory(data_dir.c_str());
465 }
466 
VMRuntime_bootCompleted(JNIEnv * env,jclass klass)467 static void VMRuntime_bootCompleted([[maybe_unused]] JNIEnv* env, [[maybe_unused]] jclass klass) {
468   jit::Jit* jit = Runtime::Current()->GetJit();
469   if (jit != nullptr) {
470     jit->BootCompleted();
471   }
472 
473   if (Runtime::Current()->IsSystemServer()) {
474     metrics::SetupCallbackForDeviceStatus();
475   }
476 }
477 
478 class ClearJitCountersVisitor : public ClassVisitor {
479  public:
operator ()(ObjPtr<mirror::Class> klass)480   bool operator()(ObjPtr<mirror::Class> klass) override REQUIRES_SHARED(Locks::mutator_lock_) {
481     // Avoid some types of classes that don't need their methods visited.
482     if (klass->IsProxyClass() ||
483         klass->IsArrayClass() ||
484         klass->IsPrimitive() ||
485         !klass->IsResolved() ||
486         klass->IsErroneousResolved()) {
487       return true;
488     }
489     uint16_t threshold = Runtime::Current()->GetJITOptions()->GetWarmupThreshold();
490     for (ArtMethod& m : klass->GetMethods(kRuntimePointerSize)) {
491       if (!m.IsAbstract()) {
492         m.ResetCounter(threshold);
493       }
494     }
495     return true;
496   }
497 };
498 
VMRuntime_resetJitCounters(JNIEnv * env,jclass klass)499 static void VMRuntime_resetJitCounters(JNIEnv* env, [[maybe_unused]] jclass klass) {
500   ScopedObjectAccess soa(env);
501   ClearJitCountersVisitor visitor;
502   Runtime::Current()->GetClassLinker()->VisitClasses(&visitor);
503 }
504 
VMRuntime_isValidClassLoaderContext(JNIEnv * env,jclass klass,jstring jencoded_class_loader_context)505 static jboolean VMRuntime_isValidClassLoaderContext(JNIEnv* env,
506                                                     [[maybe_unused]] jclass klass,
507                                                     jstring jencoded_class_loader_context) {
508   if (UNLIKELY(jencoded_class_loader_context == nullptr)) {
509     ScopedFastNativeObjectAccess soa(env);
510     ThrowNullPointerException("encoded_class_loader_context == null");
511     return false;
512   }
513   ScopedUtfChars encoded_class_loader_context(env, jencoded_class_loader_context);
514   return ClassLoaderContext::IsValidEncoding(encoded_class_loader_context.c_str());
515 }
516 
VMRuntime_getBaseApkOptimizationInfo(JNIEnv * env,jclass klass)517 static jobject VMRuntime_getBaseApkOptimizationInfo(JNIEnv* env, [[maybe_unused]] jclass klass) {
518   AppInfo* app_info = Runtime::Current()->GetAppInfo();
519   DCHECK(app_info != nullptr);
520 
521   std::string compiler_filter;
522   std::string compilation_reason;
523   app_info->GetPrimaryApkOptimizationStatus(&compiler_filter, &compilation_reason);
524 
525   ScopedLocalRef<jclass> cls(env, env->FindClass("dalvik/system/DexFile$OptimizationInfo"));
526   if (cls == nullptr) {
527     DCHECK(env->ExceptionCheck());
528     return nullptr;
529   }
530 
531   jmethodID ctor = env->GetMethodID(cls.get(), "<init>", "(Ljava/lang/String;Ljava/lang/String;)V");
532   if (ctor == nullptr) {
533     DCHECK(env->ExceptionCheck());
534     return nullptr;
535   }
536 
537   ScopedLocalRef<jstring> j_compiler_filter(env, env->NewStringUTF(compiler_filter.c_str()));
538   if (j_compiler_filter == nullptr) {
539     DCHECK(env->ExceptionCheck());
540     return nullptr;
541   }
542 
543   ScopedLocalRef<jstring> j_compilation_reason(env, env->NewStringUTF(compilation_reason.c_str()));
544   if (j_compilation_reason == nullptr) {
545     DCHECK(env->ExceptionCheck());
546     return nullptr;
547   }
548 
549   return env->NewObject(cls.get(), ctor, j_compiler_filter.get(), j_compilation_reason.get());
550 }
551 
VMRuntime_getFullGcCount(JNIEnv * env,jclass klass)552 static jlong VMRuntime_getFullGcCount([[maybe_unused]] JNIEnv* env, [[maybe_unused]] jclass klass) {
553   metrics::ArtMetrics* metrics = GetMetrics();
554   return metrics->FullGcCount()->Value();
555 }
556 
557 static JNINativeMethod gMethods[] = {
558     FAST_NATIVE_METHOD(VMRuntime, addressOf, "(Ljava/lang/Object;)J"),
559     NATIVE_METHOD(VMRuntime, bootClassPath, "()Ljava/lang/String;"),
560     NATIVE_METHOD(VMRuntime, clampGrowthLimit, "()V"),
561     NATIVE_METHOD(VMRuntime, classPath, "()Ljava/lang/String;"),
562     NATIVE_METHOD(VMRuntime, clearGrowthLimit, "()V"),
563     NATIVE_METHOD(VMRuntime, setHiddenApiExemptions, "([Ljava/lang/String;)V"),
564     NATIVE_METHOD(VMRuntime, setHiddenApiAccessLogSamplingRate, "(I)V"),
565     NATIVE_METHOD(VMRuntime, getTargetHeapUtilization, "()F"),
566     FAST_NATIVE_METHOD(VMRuntime, isNativeDebuggable, "()Z"),
567     NATIVE_METHOD(VMRuntime, isJavaDebuggable, "()Z"),
568     NATIVE_METHOD(VMRuntime, nativeSetTargetHeapUtilization, "(F)V"),
569     FAST_NATIVE_METHOD(VMRuntime, newNonMovableArray, "(Ljava/lang/Class;I)Ljava/lang/Object;"),
570     FAST_NATIVE_METHOD(VMRuntime, newUnpaddedArray, "(Ljava/lang/Class;I)Ljava/lang/Object;"),
571     NATIVE_METHOD(VMRuntime, properties, "()[Ljava/lang/String;"),
572     NATIVE_METHOD(VMRuntime, getSdkVersionNative, "(I)I"),
573     FAST_NATIVE_METHOD(VMRuntime, getIntSystemProperty, "(Ljava/lang/String;I)I"),
574     NATIVE_METHOD(VMRuntime, setTargetSdkVersionNative, "(I)V"),
575     NATIVE_METHOD(VMRuntime, setDisabledCompatChangesNative, "([J)V"),
576     NATIVE_METHOD(VMRuntime, registerNativeAllocation, "(J)V"),
577     NATIVE_METHOD(VMRuntime, registerNativeFree, "(J)V"),
578     NATIVE_METHOD(VMRuntime, getNotifyNativeInterval, "()I"),
579     NATIVE_METHOD(VMRuntime, getFinalizerTimeoutMs, "()J"),
580     NATIVE_METHOD(VMRuntime, notifyNativeAllocationsInternal, "()V"),
581     NATIVE_METHOD(VMRuntime, notifyStartupCompleted, "()V"),
582     NATIVE_METHOD(VMRuntime, registerSensitiveThread, "()V"),
583     NATIVE_METHOD(VMRuntime, requestConcurrentGC, "()V"),
584     NATIVE_METHOD(VMRuntime, requestHeapTrim, "()V"),
585     NATIVE_METHOD(VMRuntime, runHeapTasks, "()V"),
586     NATIVE_METHOD(VMRuntime, updateProcessState, "(I)V"),
587     NATIVE_METHOD(VMRuntime, startHeapTaskProcessor, "()V"),
588     NATIVE_METHOD(VMRuntime, stopHeapTaskProcessor, "()V"),
589     NATIVE_METHOD(VMRuntime, trimHeap, "()V"),
590     NATIVE_METHOD(VMRuntime, vmVersion, "()Ljava/lang/String;"),
591     NATIVE_METHOD(VMRuntime, vmLibrary, "()Ljava/lang/String;"),
592     NATIVE_METHOD(VMRuntime, vmInstructionSet, "()Ljava/lang/String;"),
593     FAST_NATIVE_METHOD(VMRuntime, is64Bit, "()Z"),
594     FAST_NATIVE_METHOD(VMRuntime, isCheckJniEnabled, "()Z"),
595     NATIVE_METHOD(VMRuntime, preloadDexCaches, "()V"),
596     NATIVE_METHOD(VMRuntime,
597                   registerAppInfo,
598                   "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;[Ljava/lang/String;I)V"),
599     NATIVE_METHOD(VMRuntime, isBootClassPathOnDisk, "(Ljava/lang/String;)Z"),
600     NATIVE_METHOD(VMRuntime, getCurrentInstructionSet, "()Ljava/lang/String;"),
601     NATIVE_METHOD(VMRuntime, setSystemDaemonThreadPriority, "()V"),
602     NATIVE_METHOD(VMRuntime, setDedupeHiddenApiWarnings, "(Z)V"),
603     NATIVE_METHOD(VMRuntime, setProcessPackageName, "(Ljava/lang/String;)V"),
604     NATIVE_METHOD(VMRuntime, setProcessDataDirectory, "(Ljava/lang/String;)V"),
605     NATIVE_METHOD(VMRuntime, bootCompleted, "()V"),
606     NATIVE_METHOD(VMRuntime, resetJitCounters, "()V"),
607     NATIVE_METHOD(VMRuntime, isValidClassLoaderContext, "(Ljava/lang/String;)Z"),
608     NATIVE_METHOD(
609         VMRuntime, getBaseApkOptimizationInfo, "()Ldalvik/system/DexFile$OptimizationInfo;"),
610     NATIVE_METHOD(VMRuntime, getFullGcCount, "()J"),
611 };
612 
register_dalvik_system_VMRuntime(JNIEnv * env)613 void register_dalvik_system_VMRuntime(JNIEnv* env) {
614   if (Runtime::Current()->GetTargetSdkVersion() <= static_cast<uint32_t>(SdkVersion::kU)) {
615     real_register_dalvik_system_VMRuntime(env);
616   } else {
617     Runtime::Current()->Abort(
618         "Call to internal function 'register_dalvik_system_VMRuntime' is not allowed");
619   }
620 }
621 
real_register_dalvik_system_VMRuntime(JNIEnv * env)622 void real_register_dalvik_system_VMRuntime(JNIEnv* env) {
623   REGISTER_NATIVE_METHODS("dalvik/system/VMRuntime");
624 }
625 
626 }  // namespace art
627