• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2007 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 package dalvik.system;
18 
19 import static android.annotation.SystemApi.Client.MODULE_LIBRARIES;
20 
21 import android.annotation.SystemApi;
22 import android.annotation.FlaggedApi;
23 import android.compat.annotation.ChangeId;
24 import android.compat.annotation.EnabledSince;
25 import android.compat.annotation.Disabled;
26 import android.compat.annotation.UnsupportedAppUsage;
27 
28 import com.android.libcore.Flags;
29 
30 import dalvik.annotation.compat.VersionCodes;
31 import dalvik.annotation.optimization.FastNative;
32 
33 import java.lang.ref.FinalizerReference;
34 import java.util.ArrayList;
35 import java.util.HashMap;
36 import java.util.List;
37 import java.util.Map;
38 import java.util.concurrent.atomic.AtomicInteger;
39 import java.util.function.Consumer;
40 
41 import libcore.util.NonNull;
42 
43 /**
44  * Provides an interface to VM-global, Dalvik-specific features.
45  * An application cannot create its own Runtime instance, and must obtain
46  * one from the getRuntime method.
47  *
48  * @hide
49  */
50 @SystemApi(client = MODULE_LIBRARIES)
51 @libcore.api.IntraCoreApi
52 public final class VMRuntime {
53 
54     /**
55      * Holds the VMRuntime singleton.
56      */
57     private static final VMRuntime THE_ONE = new VMRuntime();
58 
59     // Note: Instruction set names are used to construct the names of some
60     // system properties. To be sure that the properties stay valid the
61     // instruction set name should not exceed 7 characters. See installd
62     // and the package manager for the actual propeties.
63     private static final Map<String, String> ABI_TO_INSTRUCTION_SET_MAP
64             = new HashMap<String, String>(16);
65     static {
66         ABI_TO_INSTRUCTION_SET_MAP.put("armeabi", "arm");
67         ABI_TO_INSTRUCTION_SET_MAP.put("armeabi-v7a", "arm");
68         ABI_TO_INSTRUCTION_SET_MAP.put("x86", "x86");
69         ABI_TO_INSTRUCTION_SET_MAP.put("x86_64", "x86_64");
70         ABI_TO_INSTRUCTION_SET_MAP.put("arm64-v8a", "arm64");
71         ABI_TO_INSTRUCTION_SET_MAP.put("arm64-v8a-hwasan", "arm64");
72         ABI_TO_INSTRUCTION_SET_MAP.put("riscv64", "riscv64");
73     }
74 
75     /**
76      * Remove meta-reflection workaround for hidden api usage for apps targeting R+. This allowed
77      * apps to obtain references to blocklist fields and methods through an extra layer of
78      * reflection.
79      */
80     @ChangeId
81     @EnabledSince(targetSdkVersion = VersionCodes.R)
82     private static final long
83         PREVENT_META_REFLECTION_BLOCKLIST_ACCESS = 142365358; // This is a bug id.
84 
85     /**
86      * Gating access to greylist-max-p APIs.
87      */
88     @ChangeId
89     @EnabledSince(targetSdkVersion = VersionCodes.Q)
90     private static final long HIDE_MAXTARGETSDK_P_HIDDEN_APIS = 149997251; // This is a bug id.
91 
92     /**
93      * Gating access to greylist-max-q APIs.
94      */
95     @ChangeId
96     @EnabledSince(targetSdkVersion = VersionCodes.R)
97     private static final long HIDE_MAXTARGETSDK_Q_HIDDEN_APIS = 149994052; // This is a bug id.
98 
99     /**
100      * Allow apps accessing @TestApi APIs.
101      *
102      * <p>This will always be disabled by default and should only be used by platform test code.
103      */
104     @ChangeId
105     @Disabled
106     private static final long ALLOW_TEST_API_ACCESS = 166236554; // This is a bug id.
107 
108     /**
109      * Interface for logging hidden API usage events.
110      *
111      * @hide
112      */
113     @SystemApi(client = MODULE_LIBRARIES)
114     public interface HiddenApiUsageLogger {
115 
116         // The following ACCESS_METHOD_ constants must match the values in
117         // art/runtime/hidden_api.h
118         /**
119          * Internal test value that does not correspond to an actual access by the
120          * application. Never logged, added for completeness.
121          *
122          * @hide
123          */
124         @SystemApi(client = MODULE_LIBRARIES)
125         public static final int ACCESS_METHOD_NONE = 0;
126 
127         /**
128          *  Used when a method has been accessed via reflection.
129          *
130          * @hide
131          */
132         @SystemApi(client = MODULE_LIBRARIES)
133         public static final int ACCESS_METHOD_REFLECTION = 1;
134 
135         /**
136          *  Used when a method has been accessed via JNI.
137          *
138          * @hide
139          */
140         @SystemApi(client = MODULE_LIBRARIES)
141         public static final int ACCESS_METHOD_JNI = 2;
142 
143         /**
144          * Used when a method is accessed at link time. Never logged, added only
145          * for completeness.
146          *
147          * @hide
148          */
149         @SystemApi(client = MODULE_LIBRARIES)
150         public static final int ACCESS_METHOD_LINKING = 3;
151 
152         /**
153          * Logs hidden API access
154          *
155          * @param sampledValue value that was sampled, to be compared against the
156          *      sampling rate
157          * @param appPackageName package name of the app attempting the access
158          * @param signature signature of the method being called, i.e
159          *      class_name->member_name:type_signature (e.g.
160          *      {@code com.android.app.Activity->mDoReportFullyDrawn:Z}) for fields and
161          *      class_name->method_name_and_signature for methods (e.g
162          *      {@code com.android.app.Activity->finish(I)V})
163          * @param accessType how the accessed was done
164          * @param accessDenied whether the access was allowed or not
165          *
166          * @hide
167          */
168         @SystemApi(client = MODULE_LIBRARIES)
hiddenApiUsed(int sampledValue, String appPackageName, String signature, int accessType, boolean accessDenied)169         public void hiddenApiUsed(int sampledValue, String appPackageName,
170             String signature, int accessType, boolean accessDenied);
171     }
172 
173     static HiddenApiUsageLogger hiddenApiUsageLogger;
174 
175     /**
176      * Sets the hidden API usage logger {@link #hiddenApiUsageLogger}.
177      * It should only be called if {@link #setHiddenApiAccessLogSamplingRate(int)}
178      * is called with a value > 0
179      *
180      * @param hiddenApiUsageLogger an object implement {@code HiddenApiUsageLogger} that the runtime
181      *          will call for logging hidden API checks.
182      *
183      * @hide
184      */
185     @SystemApi(client = MODULE_LIBRARIES)
setHiddenApiUsageLogger(HiddenApiUsageLogger hiddenApiUsageLogger)186     public static void setHiddenApiUsageLogger(HiddenApiUsageLogger hiddenApiUsageLogger) {
187         VMRuntime.hiddenApiUsageLogger = hiddenApiUsageLogger;
188     }
189 
190     /**
191      * Records an attempted hidden API access to
192      * {@link HiddenApiUsageLogger#hiddenApiUsed(int, String, String, int, boolean}
193      * if a logger is registered via {@link #setHiddenApiUsageLogger}.
194      */
hiddenApiUsed(int sampledValue, String appPackageName, String signature, int accessType, boolean accessDenied)195     private static void hiddenApiUsed(int sampledValue, String appPackageName, String signature,
196          int accessType, boolean accessDenied) {
197         if (VMRuntime.hiddenApiUsageLogger != null) {
198             VMRuntime.hiddenApiUsageLogger.hiddenApiUsed(sampledValue, appPackageName,
199                 signature, accessType, accessDenied);
200         }
201     }
202 
203     /**
204      * Magic version number for a current development build, which has not
205      * yet turned into an official release. This number must be larger than
206      * any released version in {@code android.os.Build.VERSION_CODES}.
207      * @hide
208      */
209     @SystemApi(client = MODULE_LIBRARIES)
210     // Must match android.os.Build.VERSION_CODES.CUR_DEVELOPMENT.
211     public static final int SDK_VERSION_CUR_DEVELOPMENT = 10000;
212 
213     private static Consumer<String> nonSdkApiUsageConsumer = null;
214 
215     private int targetSdkVersion = SDK_VERSION_CUR_DEVELOPMENT;
216 
217     // notifyNativeAllocationsInternal (below) should be called every notifyNativeInterval
218     // allocations. Initialized on demand to allow completely static class initialization.
219     private int notifyNativeInterval;
220 
221     // Allocations since last call to native layer. See notifyNativeAllocation().
222     private final AtomicInteger allocationCount = new AtomicInteger(0);
223 
224     private long[] disabledCompatChanges = new long[0];
225 
226     private static final List<Runnable> postCleanupCallbacks = new ArrayList<>();
227 
228     /**
229      * Prevents this class from being instantiated.
230      */
VMRuntime()231     private VMRuntime() {
232     }
233 
234     /**
235      * Returns the object that represents the current runtime.
236      * @return the runtime object
237      *
238      * @hide
239      */
240     @UnsupportedAppUsage
241     @SystemApi(client = MODULE_LIBRARIES)
242     @libcore.api.IntraCoreApi
getRuntime()243     public static VMRuntime getRuntime() {
244         return THE_ONE;
245     }
246 
247     /**
248      * Returns a copy of the VM's command-line property settings.
249      * These are in the form "name=value" rather than "-Dname=value".
250      *
251      * @hide
252      */
properties()253     public native String[] properties();
254 
255     /**
256      * Returns the VM's boot class path.
257      *
258      * @hide
259      */
bootClassPath()260     public native String bootClassPath();
261 
262     /**
263      * Returns the VM's class path.
264      *
265      * @hide
266      */
classPath()267     public native String classPath();
268 
269     /**
270      * Returns the VM's version.
271      *
272      * @hide
273      */
vmVersion()274     public native String vmVersion();
275 
276     /**
277      * Returns the name of the shared library providing the VM implementation.
278      *
279      * @return the name of the shared library providing the VM implementation.
280      *
281      * @hide
282      */
283     @UnsupportedAppUsage
284     @SystemApi(client = MODULE_LIBRARIES)
vmLibrary()285     public native String vmLibrary();
286 
287     /**
288      * Returns the VM's instruction set.
289      *
290      * @return the VM's instruction set.
291      *
292      * @hide
293      */
294     @UnsupportedAppUsage
295     @SystemApi(client = MODULE_LIBRARIES)
vmInstructionSet()296     public native String vmInstructionSet();
297 
298     /**
299      * Returns whether the VM is running in 64-bit mode.
300      *
301      * @return true if VM is running in 64-bit mode, false otherwise.
302      *
303      * @hide
304      */
305     @UnsupportedAppUsage
306     @SystemApi(client = MODULE_LIBRARIES)
307     @FastNative
is64Bit()308     public native boolean is64Bit();
309 
310     /**
311      * Returns whether the VM is running with JNI checking enabled.
312      *
313      * @return true if the VM is running with JNI checking enabled,
314      *         and false otherwise.
315      *
316      * @hide
317      */
318     @SystemApi(client = MODULE_LIBRARIES)
319     @FastNative
isCheckJniEnabled()320     public native boolean isCheckJniEnabled();
321 
322     /**
323      * Gets the current ideal heap utilization, represented as a number
324      * between zero and one.  After a GC happens, the Dalvik heap may
325      * be resized so that (size of live objects) / (size of heap) is
326      * equal to this number.
327      *
328      * @return the current ideal heap utilization
329      *
330      * @hide
331      */
getTargetHeapUtilization()332     public native float getTargetHeapUtilization();
333 
334     /**
335      * Retrieves the finalizer timeout in milliseconds.
336      * Finalizers that fail to terminate in this amount of time cause the
337      * runtime to abort.
338      *
339      * @hide
340      */
getFinalizerTimeoutMs()341     public native long getFinalizerTimeoutMs();
342 
343     /**
344      * Sets the current ideal heap utilization, represented as a number
345      * between zero and one.  After a GC happens, the Dalvik heap may
346      * be resized so that (size of live objects) / (size of heap) is
347      * equal to this number.
348      *
349      * <p>This is only a hint to the garbage collector and may be ignored.
350      *
351      * @param newTarget the new suggested ideal heap utilization.
352      *                  This value may be adjusted internally.
353      * @return the previous ideal heap utilization
354      * @throws IllegalArgumentException if newTarget is &lt;= 0.0 or &gt;= 1.0
355      *
356      * @hide
357      */
358     @UnsupportedAppUsage
setTargetHeapUtilization(float newTarget)359     public float setTargetHeapUtilization(float newTarget) {
360         if (newTarget <= 0.0f || newTarget >= 1.0f) {
361             throw new IllegalArgumentException(newTarget + " out of range (0,1)");
362         }
363         /* The native code assumes a value >= 0.1. Clamp it to that. */
364         if (newTarget < 0.1f) {
365             newTarget = 0.1f;
366         }
367         /* Synchronize to make sure that only one thread gets a given "old" value if both
368          * update at the same time.  Allows for reliable save-and-restore semantics.
369          */
370         synchronized (this) {
371             float oldTarget = getTargetHeapUtilization();
372             nativeSetTargetHeapUtilization(newTarget);
373             return oldTarget;
374         }
375     }
376 
377     /**
378      * Sets the target SDK version. Should only be called before the
379      * app starts to run, because it may change the VM's behavior in
380      * dangerous ways. Defaults to {@link #SDK_VERSION_CUR_DEVELOPMENT}.
381      *
382      * @param targetSdkVersion the SDK version the app wants to run with.
383      *
384      * @hide
385      */
386     @UnsupportedAppUsage(maxTargetSdk=0, publicAlternatives="Use the {@code targetSdkVersion}"
387         +" attribute in the {@code uses-sdk} manifest tag instead.")
388     @SystemApi(client = MODULE_LIBRARIES)
setTargetSdkVersion(int targetSdkVersion)389     public synchronized void setTargetSdkVersion(int targetSdkVersion) {
390         this.targetSdkVersion = targetSdkVersion;
391         setTargetSdkVersionNative(this.targetSdkVersion);
392     }
393 
394 
395     /**
396      * Sets the disabled compat changes. Should only be called before the
397      * app starts to run, because it may change the VM's behavior in
398      * dangerous ways. Defaults to empty.
399      *
400      * @param disabledCompatChanges An array of ChangeIds that we want to disable.
401      *
402      * @hide
403      */
404     @SystemApi(client = MODULE_LIBRARIES)
setDisabledCompatChanges(long[] disabledCompatChanges)405     public synchronized void setDisabledCompatChanges(long[] disabledCompatChanges) {
406         this.disabledCompatChanges = disabledCompatChanges;
407         setDisabledCompatChangesNative(this.disabledCompatChanges);
408     }
409 
410     @FastNative
getSdkVersionNative(int default_sdk_value)411     private static native int getSdkVersionNative(int default_sdk_value);
412 
413     /**
414      * A container to avoid initialized by the unstarted runtime.
415      *
416      * {@link #sdkVersion} needs a separate container because {@link VMRuntime} could be initialized
417      * in the unstarted runtime where the values of the system properties could be misleading.
418      */
419     private static class SdkVersionContainer {
420         // Similar to android.os.Build.VERSION.SDK_INT in the boot classpath, the default sdk is 0.
421         private static final int sdkVersion = getSdkVersionNative(/*default_sdk_value=*/0);
422         private static final int sdkExtensionS =
423                 getIntSystemProperty("build.version.extensions.s", /* defaultValue= */ 0);
424     }
425 
426     /**
427      * Gets the SDK version of the software currently running on this hardware
428      * device. This value never changes while a device is booted, but it may
429      * increase when the hardware manufacturer provides an OTA update.
430      * <p>
431      * Possible values are defined in {@link VersionCodes}.
432      *
433      * It's expected to use by the ART module. Please use android.os.Build.VERSION.SDK_INT if
434      * the usage is not in the ART module.
435      *
436      * @implNote This returns {@code "ro.build.version.sdk"} system property on Android
437      *
438      * @hide
439      */
getSdkVersion()440     public static int getSdkVersion() {
441         return SdkVersionContainer.sdkVersion;
442     }
443 
444     /**
445      * Gets the SDK extension for S of the software currently running on this hardware
446      * device. This value never changes while a device is booted, but it may
447      * increase when the hardware manufacturer provides an OTA update.
448      * <p>
449      *
450      * For use by the ART module. Please use android.os.ext.SdkExtensions if
451      * the usage is not in the ART module.
452      *
453      * @implNote This returns {@code "build.version.extensions.s"} system property on Android
454      *
455      * @hide
456      */
getSdkExtensionSLevel()457     public static int getSdkExtensionSLevel() {
458         return SdkVersionContainer.sdkExtensionS;
459     }
460 
461     /**
462      * Gets the target SDK version. See {@link #setTargetSdkVersion} for
463      * special values.
464      *
465      * @return the target SDK version.
466      *
467      * @hide
468      */
469     @SystemApi(client = MODULE_LIBRARIES)
getTargetSdkVersion()470     public synchronized int getTargetSdkVersion() {
471         return targetSdkVersion;
472     }
473 
setTargetSdkVersionNative(int targetSdkVersion)474     private native void setTargetSdkVersionNative(int targetSdkVersion);
475 
476     @FastNative
getIntSystemProperty(String sdkExtensionName, int defaultValue)477     private static native int getIntSystemProperty(String sdkExtensionName, int defaultValue);
setDisabledCompatChangesNative(long[] disabledCompatChanges)478     private native void setDisabledCompatChangesNative(long[] disabledCompatChanges);
479 
480     /**
481      * This method exists for binary compatibility.  It was part of a
482      * heap sizing API which was removed in Android 3.0 (Honeycomb).
483      *
484      * @hide
485      */
486     @UnsupportedAppUsage
487     @Deprecated
getMinimumHeapSize()488     public long getMinimumHeapSize() {
489         return 0;
490     }
491 
492     /**
493      * This method exists for binary compatibility.  It was part of a
494      * heap sizing API which was removed in Android 3.0 (Honeycomb).
495      *
496      * @hide
497      */
498     @UnsupportedAppUsage
499     @Deprecated
setMinimumHeapSize(long size)500     public long setMinimumHeapSize(long size) {
501         return 0;
502     }
503 
504     /**
505      * This method exists for binary compatibility.  It used to
506      * perform a garbage collection that cleared SoftReferences.
507      *
508      * @hide
509      */
510     @UnsupportedAppUsage
511     @Deprecated
gcSoftReferences()512     public void gcSoftReferences() {}
513 
514     /**
515      * This method exists for binary compatibility.  It is equivalent
516      * to {@link System#runFinalization}.
517      *
518      * @hide
519      */
520     @UnsupportedAppUsage
521     @Deprecated
runFinalizationSync()522     public void runFinalizationSync() {
523         System.runFinalization();
524     }
525 
526     /**
527      * Implements setTargetHeapUtilization().
528      *
529      * @param newTarget the new suggested ideal heap utilization.
530      *                  This value may be adjusted internally.
531      */
nativeSetTargetHeapUtilization(float newTarget)532     private native void nativeSetTargetHeapUtilization(float newTarget);
533 
534     /**
535      * This method exists for binary compatibility.  It was part of
536      * the external allocation API which was removed in Android 3.0 (Honeycomb).
537      *
538      * @hide
539      */
540     @UnsupportedAppUsage
541     @Deprecated
trackExternalAllocation(long size)542     public boolean trackExternalAllocation(long size) {
543         return true;
544     }
545 
546     /**
547      * This method exists for binary compatibility.  It was part of
548      * the external allocation API which was removed in Android 3.0 (Honeycomb).
549      *
550      * @hide
551      */
552     @UnsupportedAppUsage
553     @Deprecated
trackExternalFree(long size)554     public void trackExternalFree(long size) {}
555 
556     /**
557      * This method exists for binary compatibility.  It was part of
558      * the external allocation API which was removed in Android 3.0 (Honeycomb).
559      *
560      * @hide
561      */
562     @UnsupportedAppUsage
563     @Deprecated
getExternalBytesAllocated()564     public long getExternalBytesAllocated() {
565         return 0;
566     }
567 
568     /**
569      * Sets the list of exemptions from hidden API access enforcement.
570      *
571      * @param signaturePrefixes
572      *         A list of signature prefixes. Each item in the list is a prefix match on the type
573      *         signature of a blacklisted API. All matching APIs are treated as if they were on
574      *         the whitelist: access permitted, and no logging..
575      *
576      * @hide
577      */
578     @SystemApi(client = MODULE_LIBRARIES)
setHiddenApiExemptions(String[] signaturePrefixes)579     public native void setHiddenApiExemptions(String[] signaturePrefixes);
580 
581     /**
582      * Sets the log sampling rate of hidden API accesses written to the event log.
583      *
584      * @param rate Proportion of hidden API accesses that will be logged; an integer between
585      *                0 and 0x10000 inclusive.
586      *
587      * @hide
588      */
589     @SystemApi(client = MODULE_LIBRARIES)
setHiddenApiAccessLogSamplingRate(int rate)590     public native void setHiddenApiAccessLogSamplingRate(int rate);
591 
592     /**
593      * Returns an array allocated in an area of the Java heap where it will never be moved.
594      * This is used to implement native allocations on the Java heap, such as DirectByteBuffers
595      * and Bitmaps.
596      *
597      * @param componentType the component type of the returned array.
598      * @param length the length of the returned array.
599      * @return array allocated in an area of the heap where it will never be moved.
600      *
601      * @hide
602      */
603     @UnsupportedAppUsage
604     @SystemApi(client = MODULE_LIBRARIES)
605     @libcore.api.IntraCoreApi
606     @FastNative
newNonMovableArray(Class<?> componentType, int length)607     public native Object newNonMovableArray(Class<?> componentType, int length);
608 
609     /**
610      * Returns an array of at least {@code minLength}, but potentially larger. The increased size
611      * comes from avoiding any padding after the array. The amount of padding varies depending on
612      * the componentType and the memory allocator implementation.
613      *
614      * @param componentType the component type of the returned array.
615      * @param minLength     the minimum length of the returned array. The actual length could
616      *                      be greater.
617      * @return              array of at least of {@code minLength}
618      *
619      * @hide
620      */
621     @SystemApi(client = MODULE_LIBRARIES)
622     @FastNative
newUnpaddedArray(Class<?> componentType, int minLength)623     public native Object newUnpaddedArray(Class<?> componentType, int minLength);
624 
625     /**
626      * Returns the address of {@code array[0]}. This differs from using JNI in that JNI
627      * might lie and give you the address of a copy of the array when in forcecopy mode.
628      *
629      * @param array the object we want the native address of. Must be a non-movable
630      * primitive array.
631      * @return native address of {@code array[0]}.
632      *
633      * @hide
634      */
635     @UnsupportedAppUsage
636     @SystemApi(client = MODULE_LIBRARIES)
637     @libcore.api.IntraCoreApi
638     @FastNative
addressOf(Object array)639     public native long addressOf(Object array);
640 
641     /**
642      * Removes any growth limits, allowing the application to allocate
643      * up to the maximum heap size.
644      *
645      * @hide
646      */
647     @UnsupportedAppUsage
648     @SystemApi(client = MODULE_LIBRARIES)
clearGrowthLimit()649     public native void clearGrowthLimit();
650 
651     /**
652      * Make the current growth limit the new non growth limit capacity by releasing pages which
653      * are after the growth limit but before the non growth limit capacity.
654      *
655      * @hide
656      */
657     @SystemApi(client = MODULE_LIBRARIES)
clampGrowthLimit()658     public native void clampGrowthLimit();
659 
660     /**
661      * Returns true if native debugging is on.
662      *
663      * @return true if native debugging is on, false otherwise.
664      *
665      * @hide
666      */
667     @SystemApi(client = MODULE_LIBRARIES)
668     @FastNative
isNativeDebuggable()669     public native boolean isNativeDebuggable();
670 
671     /**
672      * Returns true if Java debugging is enabled.
673      *
674      * @hide
675      */
isJavaDebuggable()676     public native boolean isJavaDebuggable();
677 
678     /**
679      * Registers a native allocation so that the heap knows about it and performs GC as required.
680      * If the number of native allocated bytes exceeds the native allocation watermark, the
681      * function requests a concurrent GC. If the native bytes allocated exceeds a second higher
682      * watermark, it is determined that the application is registering native allocations at an
683      * unusually high rate and a GC is performed inside of the function to prevent memory usage
684      * from excessively increasing. Memory allocated via system malloc() should not be included
685      * in this count. The argument must be the same as that later passed to registerNativeFree(),
686      * but may otherwise be approximate.
687      *
688      * @param bytes the number of bytes of the native object.
689      *
690      * @hide
691      */
692     @UnsupportedAppUsage
693     @SystemApi(client = MODULE_LIBRARIES)
registerNativeAllocation(long bytes)694     public native void registerNativeAllocation(long bytes);
695 
696     /**
697      * Backward compatibility version of {@link #registerNativeAllocation(long)}. We used to pass
698      * an int instead of a long. The RenderScript support library looks it up via reflection.
699      * @deprecated Use {@link #registerNativeAllocation(long)} instead.
700      *
701      * @param bytes the number of bytes of the native object.
702      *
703      * @hide
704      */
705     @UnsupportedAppUsage
706     @Deprecated
707     @SystemApi(client = MODULE_LIBRARIES)
registerNativeAllocation(int bytes)708     public void registerNativeAllocation(int bytes) {
709         registerNativeAllocation((long) bytes);
710     }
711 
712     /**
713      * Registers a native free by reducing the number of native bytes accounted for.
714      *
715      * @param bytes the number of bytes of the freed object.
716      *
717      * @hide
718      */
719     @UnsupportedAppUsage
720     @SystemApi(client = MODULE_LIBRARIES)
registerNativeFree(long bytes)721     public native void registerNativeFree(long bytes);
722 
723     /**
724      * Backward compatibility version of {@link #registerNativeFree(long)}.
725      * @deprecated Use {@link #registerNativeFree(long)} instead.
726      *
727      * @param bytes the number of bytes of the freed object.
728      *
729      * @hide
730      */
731     @UnsupportedAppUsage
732     @Deprecated
733     @SystemApi(client = MODULE_LIBRARIES)
registerNativeFree(int bytes)734     public void registerNativeFree(int bytes) {
735         registerNativeFree((long) bytes);
736     }
737 
738     /**
739      * Return the number of native objects that are reported by a single call to
740      * notifyNativeAllocation().
741      */
getNotifyNativeInterval()742     private static native int getNotifyNativeInterval();
743 
744     /**
745      * Report a native malloc()-only allocation to the GC.
746      *
747      * @hide
748      */
notifyNativeAllocation()749     public void notifyNativeAllocation() {
750         // Minimize JNI calls by notifying once every notifyNativeInterval allocations.
751         // The native code cannot do anything without calling mallinfo(), which is too
752         // expensive to perform on every allocation. To avoid the JNI overhead on every
753         // allocation, we do the sampling here, rather than in native code.
754         // Initialize notifyNativeInterval carefully. Multiple initializations may race.
755         int myNotifyNativeInterval = notifyNativeInterval;
756         if (myNotifyNativeInterval == 0) {
757             // This can race. By Java rules, that's OK.
758             myNotifyNativeInterval = notifyNativeInterval = getNotifyNativeInterval();
759         }
760         // myNotifyNativeInterval is correct here. If another thread won the initial race,
761         // notifyNativeInterval may not be.
762         if (allocationCount.addAndGet(1) % myNotifyNativeInterval == 0) {
763             notifyNativeAllocationsInternal();
764         }
765     }
766 
767     /**
768      * Report to the GC that roughly notifyNativeInterval native malloc()-based
769      * allocations have occurred since the last call to notifyNativeAllocationsInternal().
770      * Hints that we should check whether a GC is required.
771      *
772      * @hide
773      */
notifyNativeAllocationsInternal()774     public native void notifyNativeAllocationsInternal();
775 
776     /**
777      * Wait for objects to be finalized.
778      *
779      * If finalization takes longer than timeout, then the function returns before all objects are
780      * finalized.
781      *
782      * @param timeout
783      *            timeout in nanoseconds of the maximum time to wait until all pending finalizers
784      *            are run. If timeout is 0, then there is no timeout. Note that the timeout does
785      *            not stop the finalization process, it merely stops the wait.
786      *
787      * @see #Runtime.runFinalization()
788      * @see #wait(long,int)
789      *
790      * @hide
791      */
792     @UnsupportedAppUsage
runFinalization(long timeout)793     public static void runFinalization(long timeout) {
794         try {
795             FinalizerReference.finalizeAllEnqueued(timeout);
796         } catch (InterruptedException e) {
797             // Interrupt the current thread without actually throwing the InterruptionException
798             // for the caller.
799             Thread.currentThread().interrupt();
800         }
801     }
802 
803     /**
804      * Request that a garbage collection gets started on a different thread.
805      *
806      * @hide
807      */
808     @SystemApi(client = MODULE_LIBRARIES)
requestConcurrentGC()809     public native void requestConcurrentGC();
810 
811     /**
812      *
813      * @hide
814      */
requestHeapTrim()815     public native void requestHeapTrim();
816 
817     /**
818      *
819      * @hide
820      */
trimHeap()821     public native void trimHeap();
822 
823     /**
824      *
825      * @hide
826      */
startHeapTaskProcessor()827     public native void startHeapTaskProcessor();
828 
829     /**
830      *
831      * @hide
832      */
stopHeapTaskProcessor()833     public native void stopHeapTaskProcessor();
834 
835     /**
836      *
837      * @hide
838      */
runHeapTasks()839     public native void runHeapTasks();
840 
841     /**
842      * Let the heap know of the new "jank perceptibility" process state. This can change allocation
843      * and garbage collection behavior regarding trimming and compaction. Should be called when it
844      * appears likely that process response time will remain invisible to the user for an extended
845      * period, and then again immediately after slow process response becomes user-visible again.
846      *
847      * @param state The state of the process, as defined in art/runtime/process_state.h.
848      *
849      * @hide
850      */
851     @SystemApi(client = MODULE_LIBRARIES)
updateProcessState(int state)852     public native void updateProcessState(int state);
853 
854     /**
855      * Let the runtime know that the application startup is completed. This may affect behavior
856      * related to profiling and startup caches.
857      *
858      * @hide
859      */
860     @SystemApi(client = MODULE_LIBRARIES)
notifyStartupCompleted()861     public native void notifyStartupCompleted();
862 
863     /**
864      * Fill in dex caches with classes, fields, and methods that are
865      * already loaded. Typically used after Zygote preloading.
866      *
867      * @hide
868      */
869     @SystemApi(client = MODULE_LIBRARIES)
preloadDexCaches()870     public native void preloadDexCaches();
871 
872     /**
873      * Flag denoting that the code paths passed to
874      * {@link #registerAppInfo(String, String, String, String[], int, boolean)}
875      * contains the app primary APK.
876      *
877      * @hide
878      */
879     @SystemApi(client = MODULE_LIBRARIES)
880     public static final int CODE_PATH_TYPE_PRIMARY_APK = 1 << 0;
881     /**
882      * Flag denoting that the code paths passed to
883      * {@link #registerAppInfo(String, String, String, String[], int, boolean)}
884      * contains the a split APK.
885      *
886      * @hide
887      */
888     @SystemApi(client = MODULE_LIBRARIES)
889     public static final int CODE_PATH_TYPE_SPLIT_APK = 1 << 1;
890     /**
891      * Flag denoting that the code paths passed to
892      * {@link #registerAppInfo(String, String, String, String[], int, boolean)}
893      * contains a secondary dex file (dynamically loaded by the app).
894      *
895      * @hide
896      */
897     @SystemApi(client = MODULE_LIBRARIES)
898     public static final int CODE_PATH_TYPE_SECONDARY_DEX = 1 << 2;
899 
900     /**
901      * Register application info to ART.
902      * This enables ART to support certain low level features (such as profiling) and provide
903      * better debug information. The method should be called after the application loads its
904      * apks or dex files.
905      *
906      * @param packageName the name of the package being ran.
907      * @param currentProfileFile the path of the file where the profile information for the current
908      *        execution should be stored.
909      * @param referenceProfileFile the path of the file where the reference profile information
910      *        (for past executions) is stored.
911      * @param appCodePaths the code paths (apk/dex files) of the applications that were loaded.
912      *        These paths will also be profiled.
913      * @param codePathsTypes the type of the code paths.
914      *
915      * @hide
916      */
917     @SystemApi(client = MODULE_LIBRARIES)
registerAppInfo( String packageName, String currentProfileFile, String referenceProfileFile, String[] appCodePaths, int codePathsType)918     public static native void registerAppInfo(
919             String packageName,
920             String currentProfileFile,
921             String referenceProfileFile,
922             String[] appCodePaths,
923             int codePathsType);
924 
925     /**
926      * Returns the runtime instruction set corresponding to a given ABI. Multiple
927      * compatible ABIs might map to the same instruction set. For example
928      * {@code armeabi-v7a} and {@code armeabi} might map to the instruction set {@code arm}.
929      *
930      * This influences the compilation of the applications classes.
931      *
932      * @param abi The ABI we want the instruction set from.
933      *
934      * @hide
935      */
936     @UnsupportedAppUsage
937     @SystemApi(client = MODULE_LIBRARIES)
getInstructionSet(String abi)938     public static String getInstructionSet(String abi) {
939         final String instructionSet = ABI_TO_INSTRUCTION_SET_MAP.get(abi);
940         if (instructionSet == null) {
941             throw new IllegalArgumentException("Unsupported ABI: " + abi);
942         }
943 
944         return instructionSet;
945     }
946 
947     /**
948      * Returns whether the given {@code instructionSet} is 64 bits.
949      *
950      * @param instructionSet a string representing an instruction set.
951      *
952      * @return true if given {@code instructionSet} is 64 bits, false otherwise.
953      *
954      * @hide
955      */
956     @SystemApi(client = MODULE_LIBRARIES)
is64BitInstructionSet(String instructionSet)957     public static boolean is64BitInstructionSet(String instructionSet) {
958         return (instructionSet != null) && instructionSet.contains("64");
959     }
960 
961     /**
962      * Returns whether the given {@code abi} is 64 bits.
963      *
964      * @param abi a string representing an ABI.
965      *
966      * @return true if given {@code abi} is 64 bits, false otherwise.
967      *
968      * @hide
969      */
970     @UnsupportedAppUsage
971     @SystemApi(client = MODULE_LIBRARIES)
is64BitAbi(String abi)972     public static boolean is64BitAbi(String abi) {
973         return is64BitInstructionSet(getInstructionSet(abi));
974     }
975 
976     /**
977      * Return false if the boot class path for the given instruction
978      * set mapped from disk storage, versus being interpretted from
979      * dirty pages in memory.
980      *
981      * @hide
982      */
isBootClassPathOnDisk(String instructionSet)983     public static native boolean isBootClassPathOnDisk(String instructionSet);
984 
985     /**
986      * Used to notify the runtime that boot completed.
987      *
988      * @hide
989      */
990     @SystemApi(client = MODULE_LIBRARIES)
bootCompleted()991     public static native void bootCompleted();
992 
993     /**
994      * Used to notify the runtime to reset Jit counters. This is done for the boot image
995      * profiling configuration to avoid samples during class preloading. This helps avoid
996      * the regression from disabling class profiling.
997      *
998      * @hide
999      */
1000     @SystemApi(client = MODULE_LIBRARIES)
resetJitCounters()1001     public static native void resetJitCounters();
1002 
1003     /**
1004      * Returns the instruction set of the current runtime.
1005      *
1006      * @return instruction set of the current runtime.
1007      *
1008      * @hide
1009      */
1010     @UnsupportedAppUsage
1011     @SystemApi(client = MODULE_LIBRARIES)
getCurrentInstructionSet()1012     public static native String getCurrentInstructionSet();
1013 
1014     /**
1015      * Register the current execution thread to the runtime as sensitive thread.
1016      * Should be called just once. Subsequent calls are ignored.
1017      *
1018      * @hide
1019      */
1020     @SystemApi(client = MODULE_LIBRARIES)
registerSensitiveThread()1021     public static native void registerSensitiveThread();
1022 
1023     /**
1024      * Sets up the priority of the system daemon thread (caller).
1025      *
1026      * @hide
1027      */
setSystemDaemonThreadPriority()1028     public static native void setSystemDaemonThreadPriority();
1029 
1030     /**
1031      * Sets a callback that the runtime can call whenever a usage of a non SDK API is detected.
1032      *
1033      * @param consumer an object implementing the {@code java.util.function.Consumer} interface that
1034      *      the runtime will call whenever a usage of a non SDK API is detected.
1035      *
1036      * @hide
1037      */
1038     @SystemApi(client = MODULE_LIBRARIES)
setNonSdkApiUsageConsumer(Consumer<String> consumer)1039     public static void setNonSdkApiUsageConsumer(Consumer<String> consumer) {
1040         nonSdkApiUsageConsumer = consumer;
1041     }
1042 
1043     /**
1044      * Adds a callback that the runtime will call post-cleanup, i.e. when all the references
1045      * marked by previous GC are cleaned up, and so ReferenceQueue is empty.
1046      *
1047      * @hide
1048      */
1049     @FlaggedApi(com.android.libcore.Flags.FLAG_POST_CLEANUP_APIS)
1050     @SystemApi(client = MODULE_LIBRARIES)
addPostCleanupCallback(@onNull Runnable runnable)1051     public static void addPostCleanupCallback(@NonNull Runnable runnable) {
1052         synchronized(postCleanupCallbacks) {
1053             postCleanupCallbacks.add(runnable);
1054         }
1055     }
1056 
1057     /**
1058      * Removes a callback that the runtime will call post-cleanup
1059      *
1060      * @hide
1061      */
1062     @FlaggedApi(com.android.libcore.Flags.FLAG_POST_CLEANUP_APIS)
1063     @SystemApi(client = MODULE_LIBRARIES)
removePostCleanupCallback(@onNull Runnable runnable)1064     public static void removePostCleanupCallback(@NonNull Runnable runnable) {
1065         synchronized(postCleanupCallbacks) {
1066             postCleanupCallbacks.remove(runnable);
1067         }
1068     }
1069 
1070     /**
1071      * @hide
1072      */
onPostCleanup()1073     public static void onPostCleanup() {
1074         synchronized(postCleanupCallbacks) {
1075             for (Runnable runnable : postCleanupCallbacks) {
1076                 runnable.run();
1077             }
1078         }
1079     }
1080 
1081     /**
1082      * Sets whether or not the runtime should dedupe detection and warnings for hidden API usage.
1083      *
1084      * @param dedupe if set, only the first usage of each API will be detected. The default
1085      *      behaviour is to dedupe.
1086      *
1087      * @hide
1088      */
1089     @SystemApi(client = MODULE_LIBRARIES)
setDedupeHiddenApiWarnings(boolean dedupe)1090     public static native void setDedupeHiddenApiWarnings(boolean dedupe);
1091 
1092     /**
1093      * Sets the package name of the app running in this process.
1094      *
1095      * @param packageName the value being set
1096      *
1097      * @hide
1098      */
1099     @SystemApi(client = MODULE_LIBRARIES)
setProcessPackageName(String packageName)1100     public static native void setProcessPackageName(String packageName);
1101 
1102     /**
1103      * Sets the full path to data directory of the app running in this process.
1104      *
1105      * @param dataDir the value being set
1106      *
1107      * @hide
1108      */
1109     @SystemApi(client = MODULE_LIBRARIES)
setProcessDataDirectory(String dataDir)1110     public static native void setProcessDataDirectory(String dataDir);
1111 
1112     /**
1113      * Returns whether {@code encodedClassLoaderContext} is a valid encoded class loader context.
1114      * A class loader context is an internal opaque format used by the runtime to encode the
1115      * class loader hierarchy (including each ClassLoader's classpath) used to load a dex file.
1116      *
1117      * @param encodedClassLoaderContext the class loader context to analyze
1118      * @throws NullPointerException if {@code encodedClassLoaderContext is null.
1119      * @return {@code true} if {@code encodedClassLoaderContext} is a non-null valid encoded class
1120      *         loader context.
1121      *
1122      * @hide
1123      */
1124     @SystemApi(client = MODULE_LIBRARIES)
isValidClassLoaderContext(String encodedClassLoaderContext)1125     public static native boolean isValidClassLoaderContext(String encodedClassLoaderContext);
1126 
1127     /**
1128      * Returns the optimization status of the base APK loaded in this process. If called in a
1129      * process without an APK, returns
1130      *
1131      * @hide
1132      */
getBaseApkOptimizationInfo()1133     public static native DexFile.OptimizationInfo getBaseApkOptimizationInfo();
1134 
1135     /**
1136      * @hide for internal testing.
1137      */
isVTrunkStableFlagEnabled()1138     public static boolean isVTrunkStableFlagEnabled() {
1139         return Flags.vApis();
1140     }
1141 
1142     /**
1143      * @hide for internal testing.
1144      */
isArtTestFlagEnabled()1145     public static boolean isArtTestFlagEnabled() {
1146         return com.android.art.flags.Flags.test();
1147     }
1148 
1149     /**
1150      * Returns the full GC count - how many times did full GC happen
1151      * @hide
1152      */
getFullGcCount()1153     public static native long getFullGcCount();
1154 }
1155