android support! thanks to TachiWeb devs.

This commit is contained in:
Aria Moradi
2021-01-02 04:57:20 +03:30
parent ced07d4e1e
commit 1e46a0c78c
291 changed files with 68699 additions and 16 deletions

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,102 @@
package android.os;
import xyz.nulldev.androidcompat.config.SystemConfigModule;
import xyz.nulldev.ts.config.ConfigManager;
import xyz.nulldev.ts.config.GlobalConfigManager;
/**
* Android compat class
*/
public class Build {
private static ConfigManager configManager = GlobalConfigManager.INSTANCE;
private static SystemConfigModule configModule = configManager.module(SystemConfigModule.class);
public static boolean IS_DEBUGGABLE = configModule.isDebuggable();
//TODO Make all of this stuff configurable!
public static final String BOARD = null;
public static final String BOOTLOADER = null;
public static final String BRAND = null;
/** @deprecated */
@Deprecated
public static final String CPU_ABI = null;
/** @deprecated */
@Deprecated
public static final String CPU_ABI2 = null;
public static final String DEVICE = null;
public static final String DISPLAY = null;
public static final String FINGERPRINT = null;
public static final String HARDWARE = null;
public static final String HOST = null;
public static final String ID = null;
public static final String MANUFACTURER = null;
public static final String MODEL = null;
public static final String PRODUCT = null;
/** @deprecated */
@Deprecated
public static final String RADIO = null;
public static final String SERIAL = null;
public static final String[] SUPPORTED_32_BIT_ABIS = null;
public static final String[] SUPPORTED_64_BIT_ABIS = null;
public static final String[] SUPPORTED_ABIS = null;
public static final String TAGS = null;
public static final long TIME = 0L;
public static final String TYPE = null;
public static final String UNKNOWN = "unknown";
public static final String USER = null;
public Build() {
throw new RuntimeException("This class cannot be instantiated!");
}
public static String getRadioVersion() {
throw new RuntimeException("Stub!");
}
public static class VERSION_CODES {
public static final int BASE = 1;
public static final int BASE_1_1 = 2;
public static final int CUPCAKE = 3;
public static final int CUR_DEVELOPMENT = 10000;
public static final int DONUT = 4;
public static final int ECLAIR = 5;
public static final int ECLAIR_0_1 = 6;
public static final int ECLAIR_MR1 = 7;
public static final int FROYO = 8;
public static final int GINGERBREAD = 9;
public static final int GINGERBREAD_MR1 = 10;
public static final int HONEYCOMB = 11;
public static final int HONEYCOMB_MR1 = 12;
public static final int HONEYCOMB_MR2 = 13;
public static final int ICE_CREAM_SANDWICH = 14;
public static final int ICE_CREAM_SANDWICH_MR1 = 15;
public static final int JELLY_BEAN = 16;
public static final int JELLY_BEAN_MR1 = 17;
public static final int JELLY_BEAN_MR2 = 18;
public static final int KITKAT = 19;
public static final int KITKAT_WATCH = 20;
public static final int LOLLIPOP = 21;
public static final int LOLLIPOP_MR1 = 22;
public static final int M = 23;
public static final int N = 24;
public static final int O = 25;
}
public static class VERSION {
public static final String BASE_OS = null;
public static final String CODENAME = null;
public static final String INCREMENTAL = null;
public static final int PREVIEW_SDK_INT = 0;
public static final String RELEASE = null;
/** @deprecated */
@Deprecated
public static final String SDK = null;
public static final int SDK_INT = 0;
public static final String SECURITY_PATCH = null;
public VERSION() {
throw new RuntimeException("Stub!");
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,96 @@
package android.os;
import xyz.nulldev.androidcompat.io.AndroidFiles;
import xyz.nulldev.androidcompat.util.KodeinGlobalHelper;
import java.io.File;
/**
* Android compatibility layer for files
*/
public class Environment {
private static AndroidFiles androidFiles = KodeinGlobalHelper.instance(AndroidFiles.class);
public static String DIRECTORY_ALARMS = getHomeDirectory("Alarms").getAbsolutePath();
public static String DIRECTORY_DCIM = getHomeDirectory("DCIM").getAbsolutePath();
public static String DIRECTORY_DOCUMENTS = getHomeDirectory("Documents").getAbsolutePath();
public static String DIRECTORY_DOWNLOADS = getHomeDirectory("Downloads").getAbsolutePath();
public static String DIRECTORY_MOVIES = getHomeDirectory("Movies").getAbsolutePath();
public static String DIRECTORY_MUSIC = getHomeDirectory("Music").getAbsolutePath();
public static String DIRECTORY_NOTIFICATIONS = getHomeDirectory("Notifications").getAbsolutePath();
public static String DIRECTORY_PICTURES = getHomeDirectory("Pictures").getAbsolutePath();
public static String DIRECTORY_PODCASTS = getHomeDirectory("Podcasts").getAbsolutePath();
public static String DIRECTORY_RINGTONES = getHomeDirectory("Ringtones").getAbsolutePath();
public static final String MEDIA_BAD_REMOVAL = "bad_removal";
public static final String MEDIA_CHECKING = "checking";
public static final String MEDIA_EJECTING = "ejecting";
public static final String MEDIA_MOUNTED = "mounted";
public static final String MEDIA_MOUNTED_READ_ONLY = "mounted_ro";
public static final String MEDIA_NOFS = "nofs";
public static final String MEDIA_REMOVED = "removed";
public static final String MEDIA_SHARED = "shared";
public static final String MEDIA_UNKNOWN = "unknown";
public static final String MEDIA_UNMOUNTABLE = "unmountable";
public static final String MEDIA_UNMOUNTED = "unmounted";
public static File getHomeDirectory(String nestedFolder) {
return new File(getExternalStorageDirectory(), nestedFolder);
}
public static File getRootDirectory() {
return androidFiles.getRootDir();
}
public static File getDataDirectory() {
return androidFiles.getDataDir();
}
public static File getExternalStorageDirectory() {
return androidFiles.getExternalStorageDir();
}
public static File getExternalStoragePublicDirectory(String type) {
return androidFiles.getExternalStorageDir();
}
public static File getDownloadCacheDirectory() {
return androidFiles.getDownloadCacheDir();
}
public static String getExternalStorageState() {
return MEDIA_MOUNTED;
}
/** @deprecated */
@Deprecated
public static String getStorageState(File path) {
//TODO Maybe actually check?
return MEDIA_MOUNTED;
}
public static String getExternalStorageState(File path) {
//TODO Maybe actually check?
return MEDIA_MOUNTED;
}
public static boolean isExternalStorageRemovable() {
return false;
}
public static boolean isExternalStorageRemovable(File path) {
//TODO Maybe actually check?
return false;
}
public static boolean isExternalStorageEmulated() {
return false;
}
public static boolean isExternalStorageEmulated(File path) {
return false;
}
public static File getLegacyExternalStorageDirectory() {
return getExternalStorageDirectory();
}
}

View File

@@ -0,0 +1,148 @@
/*
* Copyright (C) 2006 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.os;
/**
* Interface for classes whose instances can be written to
* and restored from a {@link Parcel}. Classes implementing the Parcelable
* interface must also have a non-null static field called <code>CREATOR</code>
* of a type that implements the {@link Parcelable.Creator} interface.
*
* <p>A typical implementation of Parcelable is:</p>
*
* <pre>
* public class MyParcelable implements Parcelable {
* private int mData;
*
* public int describeContents() {
* return 0;
* }
*
* public void writeToParcel(Parcel out, int flags) {
* out.writeInt(mData);
* }
*
* public static final Parcelable.Creator&lt;MyParcelable&gt; CREATOR
* = new Parcelable.Creator&lt;MyParcelable&gt;() {
* public MyParcelable createFromParcel(Parcel in) {
* return new MyParcelable(in);
* }
*
* public MyParcelable[] newArray(int size) {
* return new MyParcelable[size];
* }
* };
*
* private MyParcelable(Parcel in) {
* mData = in.readInt();
* }
* }</pre>
*/
public interface Parcelable {
/**
* Flag for use with {@link #writeToParcel}: the object being written
* is a return value, that is the result of a function such as
* "<code>Parcelable someFunction()</code>",
* "<code>void someFunction(out Parcelable)</code>", or
* "<code>void someFunction(inout Parcelable)</code>". Some implementations
* may want to release resources at this point.
*/
public static final int PARCELABLE_WRITE_RETURN_VALUE = 0x0001;
/**
* Flag for use with {@link #writeToParcel}: a parent object will take
* care of managing duplicate state/data that is nominally replicated
* across its inner data members. This flag instructs the inner data
* types to omit that data during marshaling. Exact behavior may vary
* on a case by case basis.
* @hide
*/
public static final int PARCELABLE_ELIDE_DUPLICATES = 0x0002;
/*
* Bit masks for use with {@link #describeContents}: each bit represents a
* kind of object considered to have potential special significance when
* marshalled.
*/
/**
* Descriptor bit used with {@link #describeContents()}: indicates that
* the Parcelable object's flattened representation includes a file descriptor.
*
* @see #describeContents()
*/
public static final int CONTENTS_FILE_DESCRIPTOR = 0x0001;
/**
* Describe the kinds of special objects contained in this Parcelable
* instance's marshaled representation. For example, if the object will
* include a file descriptor in the output of {@link #writeToParcel(Parcel, int)},
* the return value of this method must include the
* {@link #CONTENTS_FILE_DESCRIPTOR} bit.
*
* @return a bitmask indicating the set of special object types marshaled
* by this Parcelable object instance.
*
* @see #CONTENTS_FILE_DESCRIPTOR
*/
public int describeContents();
/**
* Flatten this object in to a Parcel.
*
* @param dest The Parcel in which the object should be written.
* @param flags Additional flags about how the object should be written.
* May be 0 or {@link #PARCELABLE_WRITE_RETURN_VALUE}.
*/
public void writeToParcel(Parcel dest, int flags);
/**
* Interface that must be implemented and provided as a public CREATOR
* field that generates instances of your Parcelable class from a Parcel.
*/
public interface Creator<T> {
/**
* Create a new instance of the Parcelable class, instantiating it
* from the given Parcel whose data had previously been written by
* {@link Parcelable#writeToParcel Parcelable.writeToParcel()}.
*
* @param source The Parcel to read the object's data from.
* @return Returns a new instance of the Parcelable class.
*/
public T createFromParcel(Parcel source);
/**
* Create a new array of the Parcelable class.
*
* @param size Size of the array.
* @return Returns an array of the Parcelable class, with every entry
* initialized to null.
*/
public T[] newArray(int size);
}
/**
* Specialization of {@link Creator} that allows you to receive the
* ClassLoader the object is being created in.
*/
public interface ClassLoaderCreator<T> extends Creator<T> {
/**
* Create a new instance of the Parcelable class, instantiating it
* from the given Parcel whose data had previously been written by
* {@link Parcelable#writeToParcel Parcelable.writeToParcel()} and
* using the given ClassLoader.
*
* @param source The Parcel to read the object's data from.
* @param loader The ClassLoader that this object is being created in.
* @return Returns a new instance of the Parcelable class.
*/
public T createFromParcel(Parcel source, ClassLoader loader);
}
}

View File

@@ -0,0 +1,293 @@
/*
* Copyright (C) 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.os;
import android.annotation.Nullable;
import android.util.ArrayMap;
import com.android.internal.util.XmlUtils;
import kotlin.NotImplementedError;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlSerializer;
import java.io.IOException;
import java.util.ArrayList;
/**
* A mapping from String keys to values of various types. The set of types
* supported by this class is purposefully restricted to simple objects that can
* safely be persisted to and restored from disk.
*
* @see Bundle
*/
public final class PersistableBundle extends BaseBundle implements Cloneable, Parcelable,
XmlUtils.WriteMapCallback {
private static final String TAG_PERSISTABLEMAP = "pbundle_as_map";
public static final PersistableBundle EMPTY;
static {
EMPTY = new PersistableBundle();
EMPTY.mMap = ArrayMap.EMPTY;
}
/** @hide */
public static boolean isValidType(Object value) {
return (value instanceof Integer) || (value instanceof Long) ||
(value instanceof Double) || (value instanceof String) ||
(value instanceof int[]) || (value instanceof long[]) ||
(value instanceof double[]) || (value instanceof String[]) ||
(value instanceof PersistableBundle) || (value == null) ||
(value instanceof Boolean) || (value instanceof boolean[]);
}
/**
* Constructs a new, empty PersistableBundle.
*/
public PersistableBundle() {
super();
mFlags = FLAG_DEFUSABLE;
}
/**
* Constructs a new, empty PersistableBundle sized to hold the given number of
* elements. The PersistableBundle will grow as needed.
*
* @param capacity the initial capacity of the PersistableBundle
*/
public PersistableBundle(int capacity) {
super(capacity);
mFlags = FLAG_DEFUSABLE;
}
/**
* Constructs a PersistableBundle containing a copy of the mappings from the given
* PersistableBundle. Does only a shallow copy of the original PersistableBundle -- see
* {@link #deepCopy()} if that is not what you want.
*
* @param b a PersistableBundle to be copied.
*
* @see #deepCopy()
*/
public PersistableBundle(PersistableBundle b) {
super(b);
mFlags = b.mFlags;
}
/**
* Constructs a PersistableBundle from a Bundle. Does only a shallow copy of the Bundle.
*
* @param b a Bundle to be copied.
*
* @throws IllegalArgumentException if any element of {@code b} cannot be persisted.
*
* @hide
*/
public PersistableBundle(Bundle b) {
this(b.getMap());
}
/**
* Constructs a PersistableBundle containing the mappings passed in.
*
* @param map a Map containing only those items that can be persisted.
* @throws IllegalArgumentException if any element of #map cannot be persisted.
*/
private PersistableBundle(ArrayMap<String, Object> map) {
super();
mFlags = FLAG_DEFUSABLE;
// First stuff everything in.
putAll(map);
// Now verify each item throwing an exception if there is a violation.
final int N = mMap.size();
for (int i=0; i<N; i++) {
Object value = mMap.valueAt(i);
if (value instanceof ArrayMap) {
// Fix up any Maps by replacing them with PersistableBundles.
mMap.setValueAt(i, new PersistableBundle((ArrayMap<String, Object>) value));
} else if (value instanceof Bundle) {
mMap.setValueAt(i, new PersistableBundle(((Bundle) value)));
} else if (!isValidType(value)) {
throw new IllegalArgumentException("Bad value in PersistableBundle key="
+ mMap.keyAt(i) + " value=" + value);
}
}
}
/* package */ PersistableBundle(Parcel parcelledData, int length) {
super(parcelledData, length);
mFlags = FLAG_DEFUSABLE;
}
/**
* Constructs a PersistableBundle without initializing it.
*/
PersistableBundle(boolean doInit) {
super(doInit);
}
/**
* Make a PersistableBundle for a single key/value pair.
*
* @hide
*/
public static PersistableBundle forPair(String key, String value) {
PersistableBundle b = new PersistableBundle(1);
b.putString(key, value);
return b;
}
/**
* Clones the current PersistableBundle. The internal map is cloned, but the keys and
* values to which it refers are copied by reference.
*/
@Override
public Object clone() {
return new PersistableBundle(this);
}
/**
* Make a deep copy of the given bundle. Traverses into inner containers and copies
* them as well, so they are not shared across bundles. Will traverse in to
* {@link Bundle}, {@link PersistableBundle}, {@link ArrayList}, and all types of
* primitive arrays. Other types of objects (such as Parcelable or Serializable)
* are referenced as-is and not copied in any way.
*/
public PersistableBundle deepCopy() {
PersistableBundle b = new PersistableBundle(false);
b.copyInternal(this, true);
return b;
}
/**
* Inserts a PersistableBundle value into the mapping of this Bundle, replacing
* any existing value for the given key. Either key or value may be null.
*
* @param key a String, or null
* @param value a Bundle object, or null
*/
public void putPersistableBundle(@Nullable String key, @Nullable PersistableBundle value) {
unparcel();
mMap.put(key, value);
}
/**
* Returns the value associated with the given key, or null if
* no mapping of the desired type exists for the given key or a null
* value is explicitly associated with the key.
*
* @param key a String, or null
* @return a Bundle value, or null
*/
@Nullable
public PersistableBundle getPersistableBundle(@Nullable String key) {
unparcel();
Object o = mMap.get(key);
if (o == null) {
return null;
}
try {
return (PersistableBundle) o;
} catch (ClassCastException e) {
typeWarning(key, o, "Bundle", e);
return null;
}
}
public static final Parcelable.Creator<PersistableBundle> CREATOR =
new Parcelable.Creator<PersistableBundle>() {
@Override
public PersistableBundle createFromParcel(Parcel in) {
return in.readPersistableBundle();
}
@Override
public PersistableBundle[] newArray(int size) {
return new PersistableBundle[size];
}
};
/** @hide */
@Override
public void writeUnknownObject(Object v, String name, XmlSerializer out)
throws XmlPullParserException, IOException {
if (v instanceof PersistableBundle) {
out.startTag(null, TAG_PERSISTABLEMAP);
out.attribute(null, "name", name);
((PersistableBundle) v).saveToXml(out);
out.endTag(null, TAG_PERSISTABLEMAP);
} else {
throw new XmlPullParserException("Unknown Object o=" + v);
}
}
/** @hide */
public void saveToXml(XmlSerializer out) throws IOException, XmlPullParserException {
unparcel();
XmlUtils.writeMapXml(mMap, out, this);
}
/** @hide */
static class MyReadMapCallback implements XmlUtils.ReadMapCallback {
@Override
public Object readThisUnknownObjectXml(XmlPullParser in, String tag)
throws XmlPullParserException, IOException {
if (TAG_PERSISTABLEMAP.equals(tag)) {
return restoreFromXml(in);
}
throw new XmlPullParserException("Unknown tag=" + tag);
}
}
/**
* Report the nature of this Parcelable's contents
*/
@Override
public int describeContents() {
return 0;
}
/**
* Writes the PersistableBundle contents to a Parcel, typically in order for
* it to be passed through an IBinder connection.
* @param parcel The parcel to copy this bundle to.
*/
@Override
public void writeToParcel(Parcel parcel, int flags) {
throw new NotImplementedError();
// final boolean oldAllowFds = parcel.pushAllowFds(false);
// try {
// writeToParcelInner(parcel, flags);
// } finally {
// parcel.restoreAllowFds(oldAllowFds);
// }
}
/** @hide */
public static PersistableBundle restoreFromXml(XmlPullParser in) throws IOException,
XmlPullParserException {
final int outerDepth = in.getDepth();
final String startTag = in.getName();
final String[] tagName = new String[1];
int event;
while (((event = in.next()) != XmlPullParser.END_DOCUMENT) &&
(event != XmlPullParser.END_TAG || in.getDepth() < outerDepth)) {
if (event == XmlPullParser.START_TAG) {
return new PersistableBundle((ArrayMap<String, Object>)
XmlUtils.readThisArrayMapXml(in, startTag, tagName,
new MyReadMapCallback()));
}
}
return EMPTY;
}
@Override
synchronized public String toString() {
if (mParcelledData != null) {
if (isEmptyParcel()) {
return "PersistableBundle[EMPTY_PARCEL]";
} else {
return "PersistableBundle[mParcelledData.dataSize=" +
mParcelledData.dataSize() + "]";
}
}
return "PersistableBundle[" + mMap.toString() + "]";
}
/** @hide */
synchronized public String toShortString() {
if (mParcelledData != null) {
if (isEmptyParcel()) {
return "EMPTY_PARCEL";
} else {
return "mParcelledData.dataSize=" + mParcelledData.dataSize();
}
}
return mMap.toString();
}
}

View File

@@ -0,0 +1,99 @@
package android.os;
import kotlin.NotImplementedError;
/**
* Power manager compat class
*/
public final class PowerManager {
public static final int ACQUIRE_CAUSES_WAKEUP = 268435456;
public static final String ACTION_DEVICE_IDLE_MODE_CHANGED = "android.os.action.DEVICE_IDLE_MODE_CHANGED";
public static final String ACTION_POWER_SAVE_MODE_CHANGED = "android.os.action.POWER_SAVE_MODE_CHANGED";
/** @deprecated */
@Deprecated
public static final int FULL_WAKE_LOCK = 26;
public static final int ON_AFTER_RELEASE = 536870912;
public static final int PARTIAL_WAKE_LOCK = 1;
public static final int PROXIMITY_SCREEN_OFF_WAKE_LOCK = 32;
public static final int RELEASE_FLAG_WAIT_FOR_NO_PROXIMITY = 1;
/** @deprecated */
@Deprecated
public static final int SCREEN_BRIGHT_WAKE_LOCK = 10;
/** @deprecated */
@Deprecated
public static final int SCREEN_DIM_WAKE_LOCK = 6;
public static final PowerManager INSTANCE = new PowerManager();
public PowerManager.WakeLock newWakeLock(int levelAndFlags, String tag) {
return new WakeLock();
}
public boolean isWakeLockLevelSupported(int level) {
return true;
}
/** @deprecated */
@Deprecated
public boolean isScreenOn() {
return true;
}
public boolean isInteractive() {
return true;
}
public void reboot(String reason) {
throw new NotImplementedError("This device cannot be rebooted!");
}
public boolean isPowerSaveMode() {
return false;
}
public boolean isDeviceIdleMode() {
return false;
}
public boolean isIgnoringBatteryOptimizations(String packageName) {
return true;
}
public boolean isSustainedPerformanceModeSupported() {
return true;
}
public final class WakeLock {
int count = 0;
public void setReferenceCounted(boolean value) {
count = -1;
}
public void acquire() {
if(count != -1 && count != -2)
count++;
}
public void acquire(long timeout) {
acquire();
}
public void release() {
if(count > 0 || count == -1)
count--;
}
public void release(int flags) {
release();
}
public boolean isHeld() {
return count > 0 || count == -1;
}
public void setWorkSource(WorkSource ws) {
//Do nothing
}
}
}

View File

@@ -0,0 +1,916 @@
/*
* Copyright (C) 2006 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.os;
import android.annotation.TestApi;
import android.system.Os;
import android.system.OsConstants;
import kotlin.NotImplementedError;
/**
* Tools for managing OS processes.
*/
public class Process {
private static final String LOG_TAG = "Process";
/**
* @hide for internal use only.
*/
public static final String ZYGOTE_SOCKET = "zygote";
/**
* @hide for internal use only.
*/
public static final String SECONDARY_ZYGOTE_SOCKET = "zygote_secondary";
/**
* Defines the root UID.
* @hide
*/
public static final int ROOT_UID = 0;
/**
* Defines the UID/GID under which system code runs.
*/
public static final int SYSTEM_UID = 1000;
/**
* Defines the UID/GID under which the telephony code runs.
*/
public static final int PHONE_UID = 1001;
/**
* Defines the UID/GID for the user shell.
* @hide
*/
public static final int SHELL_UID = 2000;
/**
* Defines the UID/GID for the log group.
* @hide
*/
public static final int LOG_UID = 1007;
/**
* Defines the UID/GID for the WIFI supplicant process.
* @hide
*/
public static final int WIFI_UID = 1010;
/**
* Defines the UID/GID for the mediaserver process.
* @hide
*/
public static final int MEDIA_UID = 1013;
/**
* Defines the UID/GID for the DRM process.
* @hide
*/
public static final int DRM_UID = 1019;
/**
* Defines the UID/GID for the group that controls VPN services.
* @hide
*/
public static final int VPN_UID = 1016;
/**
* Defines the UID/GID for keystore.
* @hide
*/
public static final int KEYSTORE_UID = 1017;
/**
* Defines the UID/GID for the NFC service process.
* @hide
*/
public static final int NFC_UID = 1027;
/**
* Defines the UID/GID for the Bluetooth service process.
* @hide
*/
public static final int BLUETOOTH_UID = 1002;
/**
* Defines the GID for the group that allows write access to the internal media storage.
* @hide
*/
public static final int MEDIA_RW_GID = 1023;
/**
* Access to installed package details
* @hide
*/
public static final int PACKAGE_INFO_GID = 1032;
/**
* Defines the UID/GID for the shared RELRO file updater process.
* @hide
*/
public static final int SHARED_RELRO_UID = 1037;
/**
* Defines the UID/GID for the audioserver process.
* @hide
*/
public static final int AUDIOSERVER_UID = 1041;
/**
* Defines the UID/GID for the cameraserver process
* @hide
*/
public static final int CAMERASERVER_UID = 1047;
/**
* Defines the UID/GID for the WebView zygote process.
* @hide
*/
public static final int WEBVIEW_ZYGOTE_UID = 1051;
/**
* Defines the UID used for resource tracking for OTA updates.
* @hide
*/
public static final int OTA_UPDATE_UID = 1061;
/** {@hide} */
public static final int NOBODY_UID = 9999;
/**
* Defines the start of a range of UIDs (and GIDs), going from this
* number to {@link #LAST_APPLICATION_UID} that are reserved for assigning
* to applications.
*/
public static final int FIRST_APPLICATION_UID = 10000;
/**
* Last of application-specific UIDs starting at
* {@link #FIRST_APPLICATION_UID}.
*/
public static final int LAST_APPLICATION_UID = 19999;
/**
* First uid used for fully isolated sandboxed processes (with no permissions of their own)
* @hide
*/
public static final int FIRST_ISOLATED_UID = 99000;
/**
* Last uid used for fully isolated sandboxed processes (with no permissions of their own)
* @hide
*/
public static final int LAST_ISOLATED_UID = 99999;
/**
* Defines the gid shared by all applications running under the same profile.
* @hide
*/
public static final int SHARED_USER_GID = 9997;
/**
* First gid for applications to share resources. Used when forward-locking
* is enabled but all UserHandles need to be able to read the resources.
* @hide
*/
public static final int FIRST_SHARED_APPLICATION_GID = 50000;
/**
* Last gid for applications to share resources. Used when forward-locking
* is enabled but all UserHandles need to be able to read the resources.
* @hide
*/
public static final int LAST_SHARED_APPLICATION_GID = 59999;
/** {@hide} */
public static final int FIRST_APPLICATION_CACHE_GID = 20000;
/** {@hide} */
public static final int LAST_APPLICATION_CACHE_GID = 29999;
/**
* Standard priority of application threads.
* Use with {@link #setThreadPriority(int)} and
* {@link #setThreadPriority(int, int)}, <b>not</b> with the normal
* {@link java.lang.Thread} class.
*/
public static final int THREAD_PRIORITY_DEFAULT = 0;
/*
* ***************************************
* ** Keep in sync with utils/threads.h **
* ***************************************
*/
/**
* Lowest available thread priority. Only for those who really, really
* don't want to run if anything else is happening.
* Use with {@link #setThreadPriority(int)} and
* {@link #setThreadPriority(int, int)}, <b>not</b> with the normal
* {@link java.lang.Thread} class.
*/
public static final int THREAD_PRIORITY_LOWEST = 19;
/**
* Standard priority background threads. This gives your thread a slightly
* lower than normal priority, so that it will have less chance of impacting
* the responsiveness of the user interface.
* Use with {@link #setThreadPriority(int)} and
* {@link #setThreadPriority(int, int)}, <b>not</b> with the normal
* {@link java.lang.Thread} class.
*/
public static final int THREAD_PRIORITY_BACKGROUND = 10;
/**
* Standard priority of threads that are currently running a user interface
* that the user is interacting with. Applications can not normally
* change to this priority; the system will automatically adjust your
* application threads as the user moves through the UI.
* Use with {@link #setThreadPriority(int)} and
* {@link #setThreadPriority(int, int)}, <b>not</b> with the normal
* {@link java.lang.Thread} class.
*/
public static final int THREAD_PRIORITY_FOREGROUND = -2;
/**
* Standard priority of system display threads, involved in updating
* the user interface. Applications can not
* normally change to this priority.
* Use with {@link #setThreadPriority(int)} and
* {@link #setThreadPriority(int, int)}, <b>not</b> with the normal
* {@link java.lang.Thread} class.
*/
public static final int THREAD_PRIORITY_DISPLAY = -4;
/**
* Standard priority of the most important display threads, for compositing
* the screen and retrieving input events. Applications can not normally
* change to this priority.
* Use with {@link #setThreadPriority(int)} and
* {@link #setThreadPriority(int, int)}, <b>not</b> with the normal
* {@link java.lang.Thread} class.
*/
public static final int THREAD_PRIORITY_URGENT_DISPLAY = -8;
/**
* Standard priority of audio threads. Applications can not normally
* change to this priority.
* Use with {@link #setThreadPriority(int)} and
* {@link #setThreadPriority(int, int)}, <b>not</b> with the normal
* {@link java.lang.Thread} class.
*/
public static final int THREAD_PRIORITY_AUDIO = -16;
/**
* Standard priority of the most important audio threads.
* Applications can not normally change to this priority.
* Use with {@link #setThreadPriority(int)} and
* {@link #setThreadPriority(int, int)}, <b>not</b> with the normal
* {@link java.lang.Thread} class.
*/
public static final int THREAD_PRIORITY_URGENT_AUDIO = -19;
/**
* Minimum increment to make a priority more favorable.
*/
public static final int THREAD_PRIORITY_MORE_FAVORABLE = -1;
/**
* Minimum increment to make a priority less favorable.
*/
public static final int THREAD_PRIORITY_LESS_FAVORABLE = +1;
/**
* Default scheduling policy
* @hide
*/
public static final int SCHED_OTHER = 0;
/**
* First-In First-Out scheduling policy
* @hide
*/
public static final int SCHED_FIFO = 1;
/**
* Round-Robin scheduling policy
* @hide
*/
public static final int SCHED_RR = 2;
/**
* Batch scheduling policy
* @hide
*/
public static final int SCHED_BATCH = 3;
/**
* Idle scheduling policy
* @hide
*/
public static final int SCHED_IDLE = 5;
/**
* Reset scheduler choice on fork.
* @hide
*/
public static final int SCHED_RESET_ON_FORK = 0x40000000;
// Keep in sync with SP_* constants of enum type SchedPolicy
// declared in system/core/include/cutils/sched_policy.h,
// except THREAD_GROUP_DEFAULT does not correspond to any SP_* value.
/**
* Default thread group -
* has meaning with setProcessGroup() only, cannot be used with setThreadGroup().
* When used with setProcessGroup(), the group of each thread in the process
* is conditionally changed based on that thread's current priority, as follows:
* threads with priority numerically less than THREAD_PRIORITY_BACKGROUND
* are moved to foreground thread group. All other threads are left unchanged.
* @hide
*/
public static final int THREAD_GROUP_DEFAULT = -1;
/**
* Background thread group - All threads in
* this group are scheduled with a reduced share of the CPU.
* Value is same as constant SP_BACKGROUND of enum SchedPolicy.
* FIXME rename to THREAD_GROUP_BACKGROUND.
* @hide
*/
public static final int THREAD_GROUP_BG_NONINTERACTIVE = 0;
/**
* Foreground thread group - All threads in
* this group are scheduled with a normal share of the CPU.
* Value is same as constant SP_FOREGROUND of enum SchedPolicy.
* Not used at this level.
* @hide
**/
private static final int THREAD_GROUP_FOREGROUND = 1;
/**
* System thread group.
* @hide
**/
public static final int THREAD_GROUP_SYSTEM = 2;
/**
* Application audio thread group.
* @hide
**/
public static final int THREAD_GROUP_AUDIO_APP = 3;
/**
* System audio thread group.
* @hide
**/
public static final int THREAD_GROUP_AUDIO_SYS = 4;
/**
* Thread group for top foreground app.
* @hide
**/
public static final int THREAD_GROUP_TOP_APP = 5;
/**
* Thread group for RT app.
* @hide
**/
public static final int THREAD_GROUP_RT_APP = 6;
public static final int SIGNAL_QUIT = 3;
public static final int SIGNAL_KILL = 9;
public static final int SIGNAL_USR1 = 10;
private static long sStartElapsedRealtime;
private static long sStartUptimeMillis;
/**
* State associated with the zygote process.
* @hide
*/
public static final ZygoteProcess zygoteProcess =
new ZygoteProcess(ZYGOTE_SOCKET, SECONDARY_ZYGOTE_SOCKET);
/**
* Start a new process.
*
* <p>If processes are enabled, a new process is created and the
* static main() function of a <var>processClass</var> is executed there.
* The process will continue running after this function returns.
*
* <p>If processes are not enabled, a new thread in the caller's
* process is created and main() of <var>processClass</var> called there.
*
* <p>The niceName parameter, if not an empty string, is a custom name to
* give to the process instead of using processClass. This allows you to
* make easily identifyable processes even if you are using the same base
* <var>processClass</var> to start them.
*
* When invokeWith is not null, the process will be started as a fresh app
* and not a zygote fork. Note that this is only allowed for uid 0 or when
* runtimeFlags contains DEBUG_ENABLE_DEBUGGER.
*
* @param processClass The class to use as the process's main entry
* point.
* @param niceName A more readable name to use for the process.
* @param uid The user-id under which the process will run.
* @param gid The group-id under which the process will run.
* @param gids Additional group-ids associated with the process.
* @param runtimeFlags Additional flags for the runtime.
* @param targetSdkVersion The target SDK version for the app.
* @param seInfo null-ok SELinux information for the new process.
* @param abi non-null the ABI this app should be started with.
* @param instructionSet null-ok the instruction set to use.
* @param appDataDir null-ok the data directory of the app.
* @param invokeWith null-ok the command to invoke with.
* @param zygoteArgs Additional arguments to supply to the zygote process.
*
* @return An object that describes the result of the attempt to start the process.
* @throws RuntimeException on fatal start failure
*
* {@hide}
*/
public static final ProcessStartResult start(final String processClass,
final String niceName,
int uid, int gid, int[] gids,
int runtimeFlags, int mountExternal,
int targetSdkVersion,
String seInfo,
String abi,
String instructionSet,
String appDataDir,
String invokeWith,
String[] zygoteArgs) {
return zygoteProcess.start(processClass, niceName, uid, gid, gids,
runtimeFlags, mountExternal, targetSdkVersion, seInfo,
abi, instructionSet, appDataDir, invokeWith, zygoteArgs);
}
/** @hide */
public static final ProcessStartResult startWebView(final String processClass,
final String niceName,
int uid, int gid, int[] gids,
int runtimeFlags, int mountExternal,
int targetSdkVersion,
String seInfo,
String abi,
String instructionSet,
String appDataDir,
String invokeWith,
String[] zygoteArgs) {
throw new NotImplementedError();
}
/**
* Returns elapsed milliseconds of the time this process has run.
* @return Returns the number of milliseconds this process has return.
*/
public static final native long getElapsedCpuTime();
/**
* Return the {@link SystemClock#elapsedRealtime()} at which this process was started.
*/
public static final long getStartElapsedRealtime() {
return sStartElapsedRealtime;
}
/**
* Return the {@link SystemClock#uptimeMillis()} at which this process was started.
*/
public static final long getStartUptimeMillis() {
return sStartUptimeMillis;
}
/** @hide */
public static final void setStartTimes(long elapsedRealtime, long uptimeMillis) {
sStartElapsedRealtime = elapsedRealtime;
sStartUptimeMillis = uptimeMillis;
}
/**
* Returns true if the current process is a 64-bit runtime.
*/
public static final boolean is64Bit() {
throw new NotImplementedError();
}
/**
* Returns the identifier of this process, which can be used with
* {@link #killProcess} and {@link #sendSignal}.
*/
public static final int myPid() {
return Os.getpid();
}
/**
* Returns the identifier of this process' parent.
* @hide
*/
public static final int myPpid() {
return Os.getppid();
}
/**
* Returns the identifier of the calling thread, which be used with
* {@link #setThreadPriority(int, int)}.
*/
public static final int myTid() {
return Os.gettid();
}
/**
* Returns the identifier of this process's uid. This is the kernel uid
* that the process is running under, which is the identity of its
* app-specific sandbox. It is different from {@link #myUserHandle} in that
* a uid identifies a specific app sandbox in a specific user.
*/
public static final int myUid() {
return Os.getuid();
}
/**
* Returns this process's user handle. This is the
* user the process is running under. It is distinct from
* {@link #myUid()} in that a particular user will have multiple
* distinct apps running under it each with their own uid.
*/
public static UserHandle myUserHandle() {
return UserHandle.of(UserHandle.getUserId(myUid()));
}
/**
* Returns whether the given uid belongs to an application.
* @param uid A kernel uid.
* @return Whether the uid corresponds to an application sandbox running in
* a specific user.
*/
public static boolean isApplicationUid(int uid) {
return UserHandle.isApp(uid);
}
/**
* Returns whether the current process is in an isolated sandbox.
* @hide
*/
public static final boolean isIsolated() {
return isIsolated(myUid());
}
/** {@hide} */
public static final boolean isIsolated(int uid) {
uid = UserHandle.getAppId(uid);
return uid >= FIRST_ISOLATED_UID && uid <= LAST_ISOLATED_UID;
}
/**
* Returns the UID assigned to a particular user name, or -1 if there is
* none. If the given string consists of only numbers, it is converted
* directly to a uid.
*/
public static final native int getUidForName(String name);
/**
* Returns the GID assigned to a particular user name, or -1 if there is
* none. If the given string consists of only numbers, it is converted
* directly to a gid.
*/
public static final native int getGidForName(String name);
/**
* Returns a uid for a currently running process.
* @param pid the process id
* @return the uid of the process, or -1 if the process is not running.
* @hide pending API council review
*/
public static final int getUidForPid(int pid) {
String[] procStatusLabels = { "Uid:" };
long[] procStatusValues = new long[1];
procStatusValues[0] = -1;
Process.readProcLines("/proc/" + pid + "/status", procStatusLabels, procStatusValues);
return (int) procStatusValues[0];
}
/**
* Returns the parent process id for a currently running process.
* @param pid the process id
* @return the parent process id of the process, or -1 if the process is not running.
* @hide
*/
public static final int getParentPid(int pid) {
String[] procStatusLabels = { "PPid:" };
long[] procStatusValues = new long[1];
procStatusValues[0] = -1;
Process.readProcLines("/proc/" + pid + "/status", procStatusLabels, procStatusValues);
return (int) procStatusValues[0];
}
/**
* Returns the thread group leader id for a currently running thread.
* @param tid the thread id
* @return the thread group leader id of the thread, or -1 if the thread is not running.
* This is same as what getpid(2) would return if called by tid.
* @hide
*/
public static final int getThreadGroupLeader(int tid) {
String[] procStatusLabels = { "Tgid:" };
long[] procStatusValues = new long[1];
procStatusValues[0] = -1;
Process.readProcLines("/proc/" + tid + "/status", procStatusLabels, procStatusValues);
return (int) procStatusValues[0];
}
/**
* Set the priority of a thread, based on Linux priorities.
*
* @param tid The identifier of the thread/process to change.
* @param priority A Linux priority level, from -20 for highest scheduling
* priority to 19 for lowest scheduling priority.
*
* @throws IllegalArgumentException Throws IllegalArgumentException if
* <var>tid</var> does not exist.
* @throws SecurityException Throws SecurityException if your process does
* not have permission to modify the given thread, or to use the given
* priority.
*/
public static final native void setThreadPriority(int tid, int priority)
throws IllegalArgumentException, SecurityException;
/**
* Call with 'false' to cause future calls to {@link #setThreadPriority(int)} to
* throw an exception if passed a background-level thread priority. This is only
* effective if the JNI layer is built with GUARD_THREAD_PRIORITY defined to 1.
*
* @hide
*/
public static final native void setCanSelfBackground(boolean backgroundOk);
/**
* Sets the scheduling group for a thread.
* @hide
* @param tid The identifier of the thread to change.
* @param group The target group for this thread from THREAD_GROUP_*.
*
* @throws IllegalArgumentException Throws IllegalArgumentException if
* <var>tid</var> does not exist.
* @throws SecurityException Throws SecurityException if your process does
* not have permission to modify the given thread, or to use the given
* priority.
* If the thread is a thread group leader, that is it's gettid() == getpid(),
* then the other threads in the same thread group are _not_ affected.
*
* Does not set cpuset for some historical reason, just calls
* libcutils::set_sched_policy().
*/
public static final native void setThreadGroup(int tid, int group)
throws IllegalArgumentException, SecurityException;
/**
* Sets the scheduling group and the corresponding cpuset group
* @hide
* @param tid The identifier of the thread to change.
* @param group The target group for this thread from THREAD_GROUP_*.
*
* @throws IllegalArgumentException Throws IllegalArgumentException if
* <var>tid</var> does not exist.
* @throws SecurityException Throws SecurityException if your process does
* not have permission to modify the given thread, or to use the given
* priority.
*/
public static final native void setThreadGroupAndCpuset(int tid, int group)
throws IllegalArgumentException, SecurityException;
/**
* Sets the scheduling group for a process and all child threads
* @hide
* @param pid The identifier of the process to change.
* @param group The target group for this process from THREAD_GROUP_*.
*
* @throws IllegalArgumentException Throws IllegalArgumentException if
* <var>tid</var> does not exist.
* @throws SecurityException Throws SecurityException if your process does
* not have permission to modify the given thread, or to use the given
* priority.
*
* group == THREAD_GROUP_DEFAULT means to move all non-background priority
* threads to the foreground scheduling group, but to leave background
* priority threads alone. group == THREAD_GROUP_BG_NONINTERACTIVE moves all
* threads, regardless of priority, to the background scheduling group.
* group == THREAD_GROUP_FOREGROUND is not allowed.
*
* Always sets cpusets.
*/
public static final native void setProcessGroup(int pid, int group)
throws IllegalArgumentException, SecurityException;
/**
* Return the scheduling group of requested process.
*
* @hide
*/
public static final native int getProcessGroup(int pid)
throws IllegalArgumentException, SecurityException;
/**
* On some devices, the foreground process may have one or more CPU
* cores exclusively reserved for it. This method can be used to
* retrieve which cores that are (if any), so the calling process
* can then use sched_setaffinity() to lock a thread to these cores.
* Note that the calling process must currently be running in the
* foreground for this method to return any cores.
*
* The CPU core(s) exclusively reserved for the foreground process will
* stay reserved for as long as the process stays in the foreground.
*
* As soon as a process leaves the foreground, those CPU cores will
* no longer be reserved for it, and will most likely be reserved for
* the new foreground process. It's not necessary to change the affinity
* of your process when it leaves the foreground (if you had previously
* set it to use a reserved core); the OS will automatically take care
* of resetting the affinity at that point.
*
* @return an array of integers, indicating the CPU cores exclusively
* reserved for this process. The array will have length zero if no
* CPU cores are exclusively reserved for this process at this point
* in time.
*/
public static final native int[] getExclusiveCores();
/**
* Set the priority of the calling thread, based on Linux priorities. See
* {@link #setThreadPriority(int, int)} for more information.
*
* @param priority A Linux priority level, from -20 for highest scheduling
* priority to 19 for lowest scheduling priority.
*
* @throws IllegalArgumentException Throws IllegalArgumentException if
* <var>tid</var> does not exist.
* @throws SecurityException Throws SecurityException if your process does
* not have permission to modify the given thread, or to use the given
* priority.
*
* @see #setThreadPriority(int, int)
*/
public static final native void setThreadPriority(int priority)
throws IllegalArgumentException, SecurityException;
/**
* Return the current priority of a thread, based on Linux priorities.
*
* @param tid The identifier of the thread/process. If tid equals zero, the priority of the
* calling process/thread will be returned.
*
* @return Returns the current priority, as a Linux priority level,
* from -20 for highest scheduling priority to 19 for lowest scheduling
* priority.
*
* @throws IllegalArgumentException Throws IllegalArgumentException if
* <var>tid</var> does not exist.
*/
public static final native int getThreadPriority(int tid)
throws IllegalArgumentException;
/**
* Return the current scheduling policy of a thread, based on Linux.
*
* @param tid The identifier of the thread/process to get the scheduling policy.
*
* @throws IllegalArgumentException Throws IllegalArgumentException if
* <var>tid</var> does not exist, or if <var>priority</var> is out of range for the policy.
* @throws SecurityException Throws SecurityException if your process does
* not have permission to modify the given thread, or to use the given
* scheduling policy or priority.
*
* {@hide}
*/
@TestApi
public static final native int getThreadScheduler(int tid)
throws IllegalArgumentException;
/**
* Set the scheduling policy and priority of a thread, based on Linux.
*
* @param tid The identifier of the thread/process to change.
* @param policy A Linux scheduling policy such as SCHED_OTHER etc.
* @param priority A Linux priority level in a range appropriate for the given policy.
*
* @throws IllegalArgumentException Throws IllegalArgumentException if
* <var>tid</var> does not exist, or if <var>priority</var> is out of range for the policy.
* @throws SecurityException Throws SecurityException if your process does
* not have permission to modify the given thread, or to use the given
* scheduling policy or priority.
*
* {@hide}
*/
public static final native void setThreadScheduler(int tid, int policy, int priority)
throws IllegalArgumentException;
/**
* Determine whether the current environment supports multiple processes.
*
* @return Returns true if the system can run in multiple processes, else
* false if everything is running in a single process.
*
* @deprecated This method always returns true. Do not use.
*/
@Deprecated
public static final boolean supportsProcesses() {
return true;
}
/**
* Adjust the swappiness level for a process.
*
* @param pid The process identifier to set.
* @param is_increased Whether swappiness should be increased or default.
*
* @return Returns true if the underlying system supports this
* feature, else false.
*
* {@hide}
*/
public static final native boolean setSwappiness(int pid, boolean is_increased);
/**
* Change this process's argv[0] parameter. This can be useful to show
* more descriptive information in things like the 'ps' command.
*
* @param text The new name of this process.
*
* {@hide}
*/
public static final native void setArgV0(String text);
/**
* Kill the process with the given PID.
* Note that, though this API allows us to request to
* kill any process based on its PID, the kernel will
* still impose standard restrictions on which PIDs you
* are actually able to kill. Typically this means only
* the process running the caller's packages/application
* and any additional processes created by that app; packages
* sharing a common UID will also be able to kill each
* other's processes.
*/
public static final void killProcess(int pid) {
sendSignal(pid, SIGNAL_KILL);
}
/** @hide */
public static final native int setUid(int uid);
/** @hide */
public static final native int setGid(int uid);
/**
* Send a signal to the given process.
*
* @param pid The pid of the target process.
* @param signal The signal to send.
*/
public static final native void sendSignal(int pid, int signal);
/**
* @hide
* Private impl for avoiding a log message... DO NOT USE without doing
* your own log, or the Android Illuminati will find you some night and
* beat you up.
*/
public static final void killProcessQuiet(int pid) {
sendSignalQuiet(pid, SIGNAL_KILL);
}
/**
* @hide
* Private impl for avoiding a log message... DO NOT USE without doing
* your own log, or the Android Illuminati will find you some night and
* beat you up.
*/
public static final native void sendSignalQuiet(int pid, int signal);
/** @hide */
public static final native long getFreeMemory();
/** @hide */
public static final native long getTotalMemory();
/** @hide */
public static final native void readProcLines(String path,
String[] reqFields, long[] outSizes);
/** @hide */
public static final native int[] getPids(String path, int[] lastArray);
/** @hide */
public static final int PROC_TERM_MASK = 0xff;
/** @hide */
public static final int PROC_ZERO_TERM = 0;
/** @hide */
public static final int PROC_SPACE_TERM = (int)' ';
/** @hide */
public static final int PROC_TAB_TERM = (int)'\t';
/** @hide */
public static final int PROC_COMBINE = 0x100;
/** @hide */
public static final int PROC_PARENS = 0x200;
/** @hide */
public static final int PROC_QUOTES = 0x400;
/** @hide */
public static final int PROC_CHAR = 0x800;
/** @hide */
public static final int PROC_OUT_STRING = 0x1000;
/** @hide */
public static final int PROC_OUT_LONG = 0x2000;
/** @hide */
public static final int PROC_OUT_FLOAT = 0x4000;
/** @hide */
public static final native boolean readProcFile(String file, int[] format,
String[] outStrings, long[] outLongs, float[] outFloats);
/** @hide */
public static final native boolean parseProcLine(byte[] buffer, int startIndex,
int endIndex, int[] format, String[] outStrings, long[] outLongs, float[] outFloats);
/** @hide */
public static final native int[] getPidsForCommands(String[] cmds);
/**
* Gets the total Pss value for a given process, in bytes.
*
* @param pid the process to the Pss for
* @return the total Pss value for the given process in bytes,
* or -1 if the value cannot be determined
* @hide
*/
public static final native long getPss(int pid);
/**
* Specifies the outcome of having started a process.
* @hide
*/
public static final class ProcessStartResult {
/**
* The PID of the newly started process.
* Always >= 0. (If the start failed, an exception will have been thrown instead.)
*/
public int pid;
/**
* True if the process was started with a wrapper attached.
*/
public boolean usingWrapper;
}
/**
* Kill all processes in a process group started for the given
* pid.
* @hide
*/
public static final native int killProcessGroup(int uid, int pid);
/**
* Remove all process groups. Expected to be called when ActivityManager
* is restarted.
* @hide
*/
public static final native void removeAllProcessGroups();
/**
* Check to see if a thread belongs to a given process. This may require
* more permissions than apps generally have.
* @return true if this thread belongs to a process
* @hide
*/
public static final boolean isThreadInProcess(int tid, int pid) {
StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
try {
if (Os.access("/proc/" + tid + "/task/" + pid, OsConstants.F_OK)) {
return true;
} else {
return false;
}
} catch (Exception e) {
return false;
} finally {
StrictMode.setThreadPolicy(oldPolicy);
}
}
}

View File

@@ -0,0 +1,55 @@
/*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.os;
import java.time.Clock;
import java.time.Instant;
import java.time.ZoneId;
/**
* {@hide}
*/
public abstract class SimpleClock extends Clock {
private final ZoneId zone;
public SimpleClock(ZoneId zone) {
this.zone = zone;
}
@Override
public ZoneId getZone() {
return zone;
}
@Override
public Clock withZone(ZoneId zone) {
return new SimpleClock(zone) {
@Override
public long millis() {
return SimpleClock.this.millis();
}
};
}
@Override
public abstract long millis();
@Override
public Instant instant() {
return Instant.ofEpochMilli(millis());
}
}

View File

@@ -0,0 +1,296 @@
/*
* Copyright (C) 2006 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.os;
import android.annotation.NonNull;
import java.lang.management.ManagementFactory;
import java.time.Clock;
import java.time.DateTimeException;
import java.time.ZoneOffset;
/**
* Core timekeeping facilities.
*
* <p> Three different clocks are available, and they should not be confused:
*
* <ul>
* <li> <p> {@link System#currentTimeMillis System.currentTimeMillis()}
* is the standard "wall" clock (time and date) expressing milliseconds
* since the epoch. The wall clock can be set by the user or the phone
* network (see {@link #setCurrentTimeMillis}), so the time may jump
* backwards or forwards unpredictably. This clock should only be used
* when correspondence with real-world dates and times is important, such
* as in a calendar or alarm clock application. Interval or elapsed
* time measurements should use a different clock. If you are using
* System.currentTimeMillis(), consider listening to the
* {@link android.content.Intent#ACTION_TIME_TICK ACTION_TIME_TICK},
* {@link android.content.Intent#ACTION_TIME_CHANGED ACTION_TIME_CHANGED}
* and {@link android.content.Intent#ACTION_TIMEZONE_CHANGED
* ACTION_TIMEZONE_CHANGED} {@link android.content.Intent Intent}
* broadcasts to find out when the time changes.
*
* <li> <p> {@link #uptimeMillis} is counted in milliseconds since the
* system was booted. This clock stops when the system enters deep
* sleep (CPU off, display dark, device waiting for external input),
* but is not affected by clock scaling, idle, or other power saving
* mechanisms. This is the basis for most interval timing
* such as {@link Thread#sleep(long) Thread.sleep(millls)},
* {@link Object#wait(long) Object.wait(millis)}, and
* {@link System#nanoTime System.nanoTime()}. This clock is guaranteed
* to be monotonic, and is suitable for interval timing when the
* interval does not span device sleep. Most methods that accept a
* timestamp value currently expect the {@link #uptimeMillis} clock.
*
* <li> <p> {@link #elapsedRealtime} and {@link #elapsedRealtimeNanos}
* return the time since the system was booted, and include deep sleep.
* This clock is guaranteed to be monotonic, and continues to tick even
* when the CPU is in power saving modes, so is the recommend basis
* for general purpose interval timing.
*
* </ul>
* <p>
* There are several mechanisms for controlling the timing of events:
*
* <ul>
* <li> <p> Standard functions like {@link Thread#sleep(long)
* Thread.sleep(millis)} and {@link Object#wait(long) Object.wait(millis)}
* are always available. These functions use the {@link #uptimeMillis}
* clock; if the device enters sleep, the remainder of the time will be
* postponed until the device wakes up. These synchronous functions may
* be interrupted with {@link Thread#interrupt Thread.interrupt()}, and
* you must handle {@link InterruptedException}.
*
* <li> <p> {@link #sleep SystemClock.sleep(millis)} is a utility function
* very similar to {@link Thread#sleep(long) Thread.sleep(millis)}, but it
* ignores {@link InterruptedException}. Use this function for delays if
* you do not use {@link Thread#interrupt Thread.interrupt()}, as it will
* preserve the interrupted state of the thread.
*
* <li> <p> The {@link android.os.Handler} class can schedule asynchronous
* callbacks at an absolute or relative time. Handler objects also use the
* {@link #uptimeMillis} clock, and require an {@link android.os.Looper
* event loop} (normally present in any GUI application).
*
* <li> <p> The {@link android.app.AlarmManager} can trigger one-time or
* recurring events which occur even when the device is in deep sleep
* or your application is not running. Events may be scheduled with your
* choice of {@link java.lang.System#currentTimeMillis} (RTC) or
* {@link #elapsedRealtime} (ELAPSED_REALTIME), and cause an
* {@link android.content.Intent} broadcast when they occur.
* </ul>
*/
public final class SystemClock {
private static final String TAG = "SystemClock";
/**
* This class is uninstantiable.
*/
private SystemClock() {
// This space intentionally left blank.
}
/**
* Waits a given number of milliseconds (of uptimeMillis) before returning.
* Similar to {@link java.lang.Thread#sleep(long)}, but does not throw
* {@link InterruptedException}; {@link Thread#interrupt()} events are
* deferred until the next interruptible operation. Does not return until
* at least the specified number of milliseconds has elapsed.
*
* @param ms to sleep before returning, in milliseconds of uptime.
*/
public static void sleep(long ms) {
long start = uptimeMillis();
long duration = ms;
boolean interrupted = false;
do {
try {
Thread.sleep(duration);
} catch (InterruptedException e) {
interrupted = true;
}
duration = start + ms - uptimeMillis();
} while (duration > 0);
if (interrupted) {
// Important: we don't want to quietly eat an interrupt() event,
// so we make sure to re-interrupt the thread so that the next
// call to Thread.sleep() or Object.wait() will be interrupted.
Thread.currentThread().interrupt();
}
}
/**
* Sets the current wall time, in milliseconds. Requires the calling
* process to have appropriate permissions.
*
* @return if the clock was successfully set to the specified time.
*/
public static boolean setCurrentTimeMillis(long millis) {
// Permission denied
return false;
}
/**
* Returns milliseconds since boot, not counting time spent in deep sleep.
*
* @return milliseconds of non-sleep uptime since boot.
*/
public static long uptimeMillis() {
return ManagementFactory.getRuntimeMXBean().getUptime();
}
/**
* @removed
*/
@Deprecated
public static @NonNull
Clock uptimeMillisClock() {
return uptimeClock();
}
/**
* Return {@link Clock} that starts at system boot, not counting time spent
* in deep sleep.
*
* @removed
*/
public static @NonNull
Clock uptimeClock() {
return new SimpleClock(ZoneOffset.UTC) {
@Override
public long millis() {
return SystemClock.uptimeMillis();
}
};
}
/**
* Returns milliseconds since boot, including time spent in sleep.
*
* @return elapsed milliseconds since boot.
*/
public static long elapsedRealtime() {
// Just return JVM uptime, no application will ever need the real system uptime
return uptimeMillis();
}
/**
* Return {@link Clock} that starts at system boot, including time spent in
* sleep.
*
* @removed
*/
public static @NonNull
Clock elapsedRealtimeClock() {
return new SimpleClock(ZoneOffset.UTC) {
@Override
public long millis() {
return SystemClock.elapsedRealtime();
}
};
}
/**
* Returns nanoseconds since boot, including time spent in sleep.
*
* @return elapsed nanoseconds since boot.
*/
public static long elapsedRealtimeNanos() {
// Just convert ms realtime to nanos, we can't get nano uptime
return elapsedRealtime() * 1000000;
}
/**
* Returns milliseconds running in the current thread.
*
* @return elapsed milliseconds in the thread
*/
public static long currentThreadTimeMillis() {
// Return JVM uptime instead, we have no means of getting this info
return uptimeMillis();
}
/**
* Returns microseconds running in the current thread.
*
* @return elapsed microseconds in the thread
* @hide
*/
public static long currentThreadTimeMicro() {
// Return JVM uptime converted to microseconds instead, we have no means of getting this info
return uptimeMillis() * 1000;
}
/**
* Returns current wall time in microseconds.
*
* @return elapsed microseconds in wall time
* @hide
*/
public static long currentTimeMicro() {
// Return millis converted to microseconds, we have no means of getting system time in microseconds
return System.currentTimeMillis() * 1000;
}
/**
* Returns milliseconds since January 1, 1970 00:00:00.0 UTC, synchronized
* using a remote network source outside the device.
* <p>
* While the time returned by {@link System#currentTimeMillis()} can be
* adjusted by the user, the time returned by this method cannot be adjusted
* by the user. Note that synchronization may occur using an insecure
* network protocol, so the returned time should not be used for security
* purposes.
* <p>
* This performs no blocking network operations and returns values based on
* a recent successful synchronization event; it will either return a valid
* time or throw.
*
* @throws DateTimeException when no accurate network time can be provided.
* @hide
*/
public static long currentNetworkTimeMillis() {
// No need for such accurate time
return System.currentTimeMillis();
}
/**
* Returns a {@link Clock} that starts at January 1, 1970 00:00:00.0 UTC,
* synchronized using a remote network source outside the device.
* <p>
* While the time returned by {@link System#currentTimeMillis()} can be
* adjusted by the user, the time returned by this method cannot be adjusted
* by the user. Note that synchronization may occur using an insecure
* network protocol, so the returned time should not be used for security
* purposes.
* <p>
* This performs no blocking network operations and returns values based on
* a recent successful synchronization event; it will either return a valid
* time or throw.
*
* @throws DateTimeException when no accurate network time can be provided.
* @hide
*/
public static @NonNull
Clock currentNetworkTimeClock() {
return new SimpleClock(ZoneOffset.UTC) {
@Override
public long millis() {
return SystemClock.currentNetworkTimeMillis();
}
};
}
}

View File

@@ -0,0 +1,126 @@
/*
* Copyright (C) 2006 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.os;
import kotlin.NotImplementedError;
import xyz.nulldev.androidcompat.config.SystemConfigModule;
import xyz.nulldev.ts.config.ConfigManager;
import xyz.nulldev.ts.config.GlobalConfigManager;
/**
* Gives access to the system properties store. The system properties
* store contains a list of string key-value pairs.
*
* {@hide}
*/
public class SystemProperties {
private static ConfigManager configManager = GlobalConfigManager.INSTANCE;
private static SystemConfigModule configModule = configManager.module(SystemConfigModule.class);
public static final int PROP_VALUE_MAX = 91;
private static String native_get(String key) {
return configModule.getStringProperty(key);
}
private static String native_get(String key, String def) {
if(!configModule.hasProperty(key))
return def;
else
return native_get(key);
}
private static int native_get_int(String key, int def) {
if(configModule.hasProperty(key))
return def;
else
return configModule.getIntProperty(key);
}
private static long native_get_long(String key, long def) {
if(configModule.hasProperty(key))
return def;
else
return configModule.getLongProperty(key);
}
private static boolean native_get_boolean(String key, boolean def) {
if(configModule.hasProperty(key))
return def;
else
return configModule.getBooleanProperty(key);
}
private static void native_set(String key, String def) {
throw new NotImplementedError("TODO");
}
/**
* Get the value for the given key.
* @return an empty string if the key isn't found
*/
public static String get(String key) {
return native_get(key);
}
/**
* Get the value for the given key.
* @return if the key isn't found, return def if it isn't null, or an empty string otherwise
*/
public static String get(String key, String def) {
return native_get(key, def);
}
/**
* Get the value for the given key, and return as an integer.
* @param key the key to lookup
* @param def a default value to return
* @return the key parsed as an integer, or def if the key isn't found or
* cannot be parsed
*/
public static int getInt(String key, int def) {
return native_get_int(key, def);
}
/**
* Get the value for the given key, and return as a long.
* @param key the key to lookup
* @param def a default value to return
* @return the key parsed as a long, or def if the key isn't found or
* cannot be parsed
*/
public static long getLong(String key, long def) {
return native_get_long(key, def);
}
/**
* Get the value for the given key, returned as a boolean.
* Values 'n', 'no', '0', 'false' or 'off' are considered false.
* Values 'y', 'yes', '1', 'true' or 'on' are considered true.
* (case sensitive).
* If the key does not exist, or has any other value, then the default
* result is returned.
* @param key the key to lookup
* @param def a default value to return
* @return the key parsed as a boolean, or def if the key isn't found or is
* not able to be parsed as a boolean.
*/
public static boolean getBoolean(String key, boolean def) {
return native_get_boolean(key, def);
}
/**
* Set the value for the given key.
* @throws IllegalArgumentException if the value exceeds 92 characters
*/
public static void set(String key, String val) {
if (val != null && val.length() > PROP_VALUE_MAX) {
throw new IllegalArgumentException("val.length > " +
PROP_VALUE_MAX);
}
native_set(key, val);
}
}

View File

@@ -0,0 +1,418 @@
/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.os;
import android.annotation.AppIdInt;
import android.annotation.SystemApi;
import android.annotation.TestApi;
import android.annotation.UserIdInt;
import java.io.PrintWriter;
/**
* Representation of a user on the device.
*/
public final class UserHandle implements Parcelable {
// NOTE: keep logic in sync with system/core/libcutils/multiuser.c
/**
* @hide Range of uids allocated for a user.
*/
public static final int PER_USER_RANGE = 100000;
/** @hide A user id to indicate all users on the device */
public static final @UserIdInt int USER_ALL = -1;
/** @hide A user handle to indicate all users on the device */
public static final UserHandle ALL = new UserHandle(USER_ALL);
/** @hide A user id to indicate the currently active user */
public static final @UserIdInt int USER_CURRENT = -2;
/** @hide A user handle to indicate the current user of the device */
public static final UserHandle CURRENT = new UserHandle(USER_CURRENT);
/** @hide A user id to indicate that we would like to send to the current
* user, but if this is calling from a user process then we will send it
* to the caller's user instead of failing with a security exception */
public static final @UserIdInt int USER_CURRENT_OR_SELF = -3;
/** @hide A user handle to indicate that we would like to send to the current
* user, but if this is calling from a user process then we will send it
* to the caller's user instead of failing with a security exception */
public static final UserHandle CURRENT_OR_SELF = new UserHandle(USER_CURRENT_OR_SELF);
/** @hide An undefined user id */
public static final @UserIdInt int USER_NULL = -10000;
/**
* @hide A user id constant to indicate the "owner" user of the device
* @deprecated Consider using either {@link UserHandle#USER_SYSTEM} constant or
* check the target user's flag {@link android.content.pm.UserInfo#isAdmin}.
*/
@Deprecated
public static final @UserIdInt int USER_OWNER = 0;
/**
* @hide A user handle to indicate the primary/owner user of the device
* @deprecated Consider using either {@link UserHandle#SYSTEM} constant or
* check the target user's flag {@link android.content.pm.UserInfo#isAdmin}.
*/
@Deprecated
public static final UserHandle OWNER = new UserHandle(USER_OWNER);
/** @hide A user id constant to indicate the "system" user of the device */
public static final @UserIdInt int USER_SYSTEM = 0;
/** @hide A user serial constant to indicate the "system" user of the device */
public static final int USER_SERIAL_SYSTEM = 0;
/** @hide A user handle to indicate the "system" user of the device */
public static final UserHandle SYSTEM = new UserHandle(USER_SYSTEM);
/**
* @hide Enable multi-user related side effects. Set this to false if
* there are problems with single user use-cases.
*/
public static final boolean MU_ENABLED = true;
/** @hide */
public static final int ERR_GID = -1;
/** @hide */
public static final int AID_ROOT = android.os.Process.ROOT_UID;
/** @hide */
public static final int AID_APP_START = android.os.Process.FIRST_APPLICATION_UID;
/** @hide */
public static final int AID_APP_END = android.os.Process.LAST_APPLICATION_UID;
/** @hide */
public static final int AID_SHARED_GID_START = android.os.Process.FIRST_SHARED_APPLICATION_GID;
/** @hide */
public static final int AID_CACHE_GID_START = android.os.Process.FIRST_APPLICATION_CACHE_GID;
final int mHandle;
/**
* Checks to see if the user id is the same for the two uids, i.e., they belong to the same
* user.
* @hide
*/
public static boolean isSameUser(int uid1, int uid2) {
return getUserId(uid1) == getUserId(uid2);
}
/**
* Checks to see if both uids are referring to the same app id, ignoring the user id part of the
* uids.
* @param uid1 uid to compare
* @param uid2 other uid to compare
* @return whether the appId is the same for both uids
* @hide
*/
public static boolean isSameApp(int uid1, int uid2) {
return getAppId(uid1) == getAppId(uid2);
}
/** @hide */
public static boolean isIsolated(int uid) {
if (uid > 0) {
final int appId = getAppId(uid);
return appId >= Process.FIRST_ISOLATED_UID && appId <= Process.LAST_ISOLATED_UID;
} else {
return false;
}
}
/** @hide */
public static boolean isApp(int uid) {
if (uid > 0) {
final int appId = getAppId(uid);
return appId >= Process.FIRST_APPLICATION_UID && appId <= Process.LAST_APPLICATION_UID;
} else {
return false;
}
}
/**
* Returns the user for a given uid.
* @param uid A uid for an application running in a particular user.
* @return A {@link UserHandle} for that user.
*/
public static UserHandle getUserHandleForUid(int uid) {
return of(getUserId(uid));
}
/**
* Returns the user id for a given uid.
* @hide
*/
public static @UserIdInt int getUserId(int uid) {
if (MU_ENABLED) {
return uid / PER_USER_RANGE;
} else {
return UserHandle.USER_SYSTEM;
}
}
/** @hide */
public static @UserIdInt int getCallingUserId() {
return getUserId(Binder.getCallingUid());
}
/** @hide */
public static @AppIdInt int getCallingAppId() {
return getAppId(Binder.getCallingUid());
}
/** @hide */
@SystemApi
public static UserHandle of(@UserIdInt int userId) {
return userId == USER_SYSTEM ? SYSTEM : new UserHandle(userId);
}
/**
* Returns the uid that is composed from the userId and the appId.
* @hide
*/
public static int getUid(@UserIdInt int userId, @AppIdInt int appId) {
if (MU_ENABLED) {
return userId * PER_USER_RANGE + (appId % PER_USER_RANGE);
} else {
return appId;
}
}
/**
* Returns the app id (or base uid) for a given uid, stripping out the user id from it.
* @hide
*/
@TestApi
public static @AppIdInt int getAppId(int uid) {
return uid % PER_USER_RANGE;
}
/**
* Returns the gid shared between all apps with this userId.
* @hide
*/
public static int getUserGid(@UserIdInt int userId) {
return getUid(userId, Process.SHARED_USER_GID);
}
/** @hide */
public static int getSharedAppGid(int uid) {
return getSharedAppGid(getUserId(uid), getAppId(uid));
}
/** @hide */
public static int getSharedAppGid(int userId, int appId) {
if (appId >= AID_APP_START && appId <= AID_APP_END) {
return (appId - AID_APP_START) + AID_SHARED_GID_START;
} else if (appId >= AID_ROOT && appId <= AID_APP_START) {
return appId;
} else {
return -1;
}
}
/**
* Returns the app id for a given shared app gid. Returns -1 if the ID is invalid.
* @hide
*/
public static @AppIdInt int getAppIdFromSharedAppGid(int gid) {
final int appId = getAppId(gid) + Process.FIRST_APPLICATION_UID
- Process.FIRST_SHARED_APPLICATION_GID;
if (appId < 0 || appId >= Process.FIRST_SHARED_APPLICATION_GID) {
return -1;
}
return appId;
}
/** @hide */
public static int getCacheAppGid(int uid) {
return getCacheAppGid(getUserId(uid), getAppId(uid));
}
/** @hide */
public static int getCacheAppGid(int userId, int appId) {
if (appId >= AID_APP_START && appId <= AID_APP_END) {
return getUid(userId, (appId - AID_APP_START) + AID_CACHE_GID_START);
} else {
return -1;
}
}
/**
* Generate a text representation of the uid, breaking out its individual
* components -- user, app, isolated, etc.
* @hide
*/
public static void formatUid(StringBuilder sb, int uid) {
if (uid < Process.FIRST_APPLICATION_UID) {
sb.append(uid);
} else {
sb.append('u');
sb.append(getUserId(uid));
final int appId = getAppId(uid);
if (appId >= Process.FIRST_ISOLATED_UID && appId <= Process.LAST_ISOLATED_UID) {
sb.append('i');
sb.append(appId - Process.FIRST_ISOLATED_UID);
} else if (appId >= Process.FIRST_APPLICATION_UID) {
sb.append('a');
sb.append(appId - Process.FIRST_APPLICATION_UID);
} else {
sb.append('s');
sb.append(appId);
}
}
}
/**
* Generate a text representation of the uid, breaking out its individual
* components -- user, app, isolated, etc.
* @hide
*/
public static String formatUid(int uid) {
StringBuilder sb = new StringBuilder();
formatUid(sb, uid);
return sb.toString();
}
/**
* Generate a text representation of the uid, breaking out its individual
* components -- user, app, isolated, etc.
* @hide
*/
public static void formatUid(PrintWriter pw, int uid) {
if (uid < Process.FIRST_APPLICATION_UID) {
pw.print(uid);
} else {
pw.print('u');
pw.print(getUserId(uid));
final int appId = getAppId(uid);
if (appId >= Process.FIRST_ISOLATED_UID && appId <= Process.LAST_ISOLATED_UID) {
pw.print('i');
pw.print(appId - Process.FIRST_ISOLATED_UID);
} else if (appId >= Process.FIRST_APPLICATION_UID) {
pw.print('a');
pw.print(appId - Process.FIRST_APPLICATION_UID);
} else {
pw.print('s');
pw.print(appId);
}
}
}
/** @hide */
public static @UserIdInt int parseUserArg(String arg) {
int userId;
if ("all".equals(arg)) {
userId = UserHandle.USER_ALL;
} else if ("current".equals(arg) || "cur".equals(arg)) {
userId = UserHandle.USER_CURRENT;
} else {
try {
userId = Integer.parseInt(arg);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Bad user number: " + arg);
}
}
return userId;
}
/**
* Returns the user id of the current process
* @return user id of the current process
* @hide
*/
@SystemApi
public static @UserIdInt int myUserId() {
return getUserId(Process.myUid());
}
/**
* Returns true if this UserHandle refers to the owner user; false otherwise.
* @return true if this UserHandle refers to the owner user; false otherwise.
* @hide
* @deprecated please use {@link #isSystem()} or check for
* {@link android.content.pm.UserInfo#isPrimary()}
* {@link android.content.pm.UserInfo#isAdmin()} based on your particular use case.
*/
@Deprecated
@SystemApi
public boolean isOwner() {
return this.equals(OWNER);
}
/**
* @return true if this UserHandle refers to the system user; false otherwise.
* @hide
*/
@SystemApi
public boolean isSystem() {
return this.equals(SYSTEM);
}
/** @hide */
public UserHandle(int h) {
mHandle = h;
}
/**
* Returns the userId stored in this UserHandle.
* @hide
*/
@SystemApi
@TestApi
public @UserIdInt int getIdentifier() {
return mHandle;
}
@Override
public String toString() {
return "UserHandle{" + mHandle + "}";
}
@Override
public boolean equals(Object obj) {
try {
if (obj != null) {
UserHandle other = (UserHandle)obj;
return mHandle == other.mHandle;
}
} catch (ClassCastException e) {
}
return false;
}
@Override
public int hashCode() {
return mHandle;
}
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel out, int flags) {
out.writeInt(mHandle);
}
/**
* Write a UserHandle to a Parcel, handling null pointers. Must be
* read with {@link #readFromParcel(Parcel)}.
*
* @param h The UserHandle to be written.
* @param out The Parcel in which the UserHandle will be placed.
*
* @see #readFromParcel(Parcel)
*/
public static void writeToParcel(UserHandle h, Parcel out) {
if (h != null) {
h.writeToParcel(out, 0);
} else {
out.writeInt(USER_NULL);
}
}
/**
* Read a UserHandle from a Parcel that was previously written
* with {@link #writeToParcel(UserHandle, Parcel)}, returning either
* a null or new object as appropriate.
*
* @param in The Parcel from which to read the UserHandle
* @return Returns a new UserHandle matching the previously written
* object, or null if a null had been written.
*
* @see #writeToParcel(UserHandle, Parcel)
*/
public static UserHandle readFromParcel(Parcel in) {
int h = in.readInt();
return h != USER_NULL ? new UserHandle(h) : null;
}
public static final Parcelable.Creator<UserHandle> CREATOR
= new Parcelable.Creator<UserHandle>() {
public UserHandle createFromParcel(Parcel in) {
return new UserHandle(in);
}
public UserHandle[] newArray(int size) {
return new UserHandle[size];
}
};
/**
* Instantiate a new UserHandle from the data in a Parcel that was
* previously written with {@link #writeToParcel(Parcel, int)}. Note that you
* must not use this with data written by
* {@link #writeToParcel(UserHandle, Parcel)} since it is not possible
* to handle a null UserHandle here.
*
* @param in The Parcel containing the previously written UserHandle,
* positioned at the location in the buffer where it was written.
*/
public UserHandle(Parcel in) {
mHandle = in.readInt();
}
}

View File

@@ -0,0 +1,407 @@
/*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.os;
import android.net.LocalSocket;
import android.net.LocalSocketAddress;
import android.util.Log;
import com.android.internal.util.Preconditions;
import kotlin.NotImplementedError;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/*package*/ class ZygoteStartFailedEx extends Exception {
ZygoteStartFailedEx(String s) {
super(s);
}
ZygoteStartFailedEx(Throwable cause) {
super(cause);
}
ZygoteStartFailedEx(String s, Throwable cause) {
super(s, cause);
}
}
/**
* Maintains communication state with the zygote processes. This class is responsible
* for the sockets opened to the zygotes and for starting processes on behalf of the
* {@link android.os.Process} class.
*
* {@hide}
*/
public class ZygoteProcess {
private static final String LOG_TAG = "ZygoteProcess";
/**
* The name of the socket used to communicate with the primary zygote.
*/
private final String mSocket;
/**
* The name of the secondary (alternate ABI) zygote socket.
*/
private final String mSecondarySocket;
public ZygoteProcess(String primarySocket, String secondarySocket) {
mSocket = primarySocket;
mSecondarySocket = secondarySocket;
}
/**
* State for communicating with the zygote process.
*/
public static class ZygoteState {
final LocalSocket socket;
final DataInputStream inputStream;
final BufferedWriter writer;
final List<String> abiList;
boolean mClosed;
private ZygoteState(LocalSocket socket, DataInputStream inputStream,
BufferedWriter writer, List<String> abiList) {
this.socket = socket;
this.inputStream = inputStream;
this.writer = writer;
this.abiList = abiList;
}
public static ZygoteState connect(String socketAddress) throws IOException {
DataInputStream zygoteInputStream = null;
BufferedWriter zygoteWriter = null;
final LocalSocket zygoteSocket = new LocalSocket();
try {
zygoteSocket.connect(new LocalSocketAddress(socketAddress,
LocalSocketAddress.Namespace.RESERVED));
zygoteInputStream = new DataInputStream(zygoteSocket.getInputStream());
zygoteWriter = new BufferedWriter(new OutputStreamWriter(
zygoteSocket.getOutputStream()), 256);
} catch (IOException ex) {
try {
zygoteSocket.close();
} catch (IOException ignore) {
}
throw ex;
}
String abiListString = getAbiList(zygoteWriter, zygoteInputStream);
Log.i("Zygote", "Process: zygote socket " + socketAddress + " opened, supported ABIS: "
+ abiListString);
return new ZygoteState(zygoteSocket, zygoteInputStream, zygoteWriter,
Arrays.asList(abiListString.split(",")));
}
boolean matches(String abi) {
return abiList.contains(abi);
}
public void close() {
try {
socket.close();
} catch (IOException ex) {
Log.e(LOG_TAG,"I/O exception on routine close", ex);
}
mClosed = true;
}
boolean isClosed() {
return mClosed;
}
}
/**
* Lock object to protect access to the two ZygoteStates below. This lock must be
* acquired while communicating over the ZygoteState's socket, to prevent
* interleaved access.
*/
private final Object mLock = new Object();
/**
* The state of the connection to the primary zygote.
*/
private ZygoteState primaryZygoteState;
/**
* The state of the connection to the secondary zygote.
*/
private ZygoteState secondaryZygoteState;
/**
* Start a new process.
*
* <p>If processes are enabled, a new process is created and the
* static main() function of a <var>processClass</var> is executed there.
* The process will continue running after this function returns.
*
* <p>If processes are not enabled, a new thread in the caller's
* process is created and main() of <var>processClass</var> called there.
*
* <p>The niceName parameter, if not an empty string, is a custom name to
* give to the process instead of using processClass. This allows you to
* make easily identifyable processes even if you are using the same base
* <var>processClass</var> to start them.
*
* When invokeWith is not null, the process will be started as a fresh app
* and not a zygote fork. Note that this is only allowed for uid 0 or when
* runtimeFlags contains DEBUG_ENABLE_DEBUGGER.
*
* @param processClass The class to use as the process's main entry
* point.
* @param niceName A more readable name to use for the process.
* @param uid The user-id under which the process will run.
* @param gid The group-id under which the process will run.
* @param gids Additional group-ids associated with the process.
* @param runtimeFlags Additional flags.
* @param targetSdkVersion The target SDK version for the app.
* @param seInfo null-ok SELinux information for the new process.
* @param abi non-null the ABI this app should be started with.
* @param instructionSet null-ok the instruction set to use.
* @param appDataDir null-ok the data directory of the app.
* @param invokeWith null-ok the command to invoke with.
* @param zygoteArgs Additional arguments to supply to the zygote process.
*
* @return An object that describes the result of the attempt to start the process.
* @throws RuntimeException on fatal start failure
*/
public final Process.ProcessStartResult start(final String processClass,
final String niceName,
int uid, int gid, int[] gids,
int runtimeFlags, int mountExternal,
int targetSdkVersion,
String seInfo,
String abi,
String instructionSet,
String appDataDir,
String invokeWith,
String[] zygoteArgs) {
try {
return startViaZygote(processClass, niceName, uid, gid, gids,
runtimeFlags, mountExternal, targetSdkVersion, seInfo,
abi, instructionSet, appDataDir, invokeWith, zygoteArgs);
} catch (ZygoteStartFailedEx ex) {
Log.e(LOG_TAG,
"Starting VM process through Zygote failed");
throw new RuntimeException(
"Starting VM process through Zygote failed", ex);
}
}
/** retry interval for opening a zygote socket */
static final int ZYGOTE_RETRY_MILLIS = 500;
/**
* Queries the zygote for the list of ABIS it supports.
*
* @throws ZygoteStartFailedEx if the query failed.
*/
private static String getAbiList(BufferedWriter writer, DataInputStream inputStream)
throws IOException {
// Each query starts with the argument count (1 in this case)
writer.write("1");
// ... followed by a new-line.
writer.newLine();
// ... followed by our only argument.
writer.write("--query-abi-list");
writer.newLine();
writer.flush();
// The response is a length prefixed stream of ASCII bytes.
int numBytes = inputStream.readInt();
byte[] bytes = new byte[numBytes];
inputStream.readFully(bytes);
return new String(bytes, StandardCharsets.US_ASCII);
}
/**
* Sends an argument list to the zygote process, which starts a new child
* and returns the child's pid. Please note: the present implementation
* replaces newlines in the argument list with spaces.
*
* @throws ZygoteStartFailedEx if process start failed for any reason
*/
private static Process.ProcessStartResult zygoteSendArgsAndGetResult(
ZygoteState zygoteState, ArrayList<String> args)
throws ZygoteStartFailedEx {
try {
// Throw early if any of the arguments are malformed. This means we can
// avoid writing a partial response to the zygote.
int sz = args.size();
for (int i = 0; i < sz; i++) {
if (args.get(i).indexOf('\n') >= 0) {
throw new ZygoteStartFailedEx("embedded newlines not allowed");
}
}
/**
* See com.android.internal.os.SystemZygoteInit.readArgumentList()
* Presently the wire format to the zygote process is:
* a) a count of arguments (argc, in essence)
* b) a number of newline-separated argument strings equal to count
*
* After the zygote process reads these it will write the pid of
* the child or -1 on failure, followed by boolean to
* indicate whether a wrapper process was used.
*/
final BufferedWriter writer = zygoteState.writer;
final DataInputStream inputStream = zygoteState.inputStream;
writer.write(Integer.toString(args.size()));
writer.newLine();
for (int i = 0; i < sz; i++) {
String arg = args.get(i);
writer.write(arg);
writer.newLine();
}
writer.flush();
// Should there be a timeout on this?
Process.ProcessStartResult result = new Process.ProcessStartResult();
// Always read the entire result from the input stream to avoid leaving
// bytes in the stream for future process starts to accidentally stumble
// upon.
result.pid = inputStream.readInt();
result.usingWrapper = inputStream.readBoolean();
if (result.pid < 0) {
throw new ZygoteStartFailedEx("fork() failed");
}
return result;
} catch (IOException ex) {
zygoteState.close();
throw new ZygoteStartFailedEx(ex);
}
}
/**
* Starts a new process via the zygote mechanism.
*
* @param processClass Class name whose static main() to run
* @param niceName 'nice' process name to appear in ps
* @param uid a POSIX uid that the new process should setuid() to
* @param gid a POSIX gid that the new process shuold setgid() to
* @param gids null-ok; a list of supplementary group IDs that the
* new process should setgroup() to.
* @param runtimeFlags Additional flags for the runtime.
* @param targetSdkVersion The target SDK version for the app.
* @param seInfo null-ok SELinux information for the new process.
* @param abi the ABI the process should use.
* @param instructionSet null-ok the instruction set to use.
* @param appDataDir null-ok the data directory of the app.
* @param extraArgs Additional arguments to supply to the zygote process.
* @return An object that describes the result of the attempt to start the process.
* @throws ZygoteStartFailedEx if process start failed for any reason
*/
private Process.ProcessStartResult startViaZygote(final String processClass,
final String niceName,
final int uid, final int gid,
final int[] gids,
int runtimeFlags, int mountExternal,
int targetSdkVersion,
String seInfo,
String abi,
String instructionSet,
String appDataDir,
String invokeWith,
String[] extraArgs)
throws ZygoteStartFailedEx {
throw new NotImplementedError();
}
/**
* Tries to establish a connection to the zygote that handles a given {@code abi}. Might block
* and retry if the zygote is unresponsive. This method is a no-op if a connection is
* already open.
*/
public void establishZygoteConnectionForAbi(String abi) {
try {
synchronized(mLock) {
openZygoteSocketIfNeeded(abi);
}
} catch (ZygoteStartFailedEx ex) {
throw new RuntimeException("Unable to connect to zygote for abi: " + abi, ex);
}
}
/**
* Tries to open socket to Zygote process if not already open. If
* already open, does nothing. May block and retry. Requires that mLock be held.
*/
private ZygoteState openZygoteSocketIfNeeded(String abi) throws ZygoteStartFailedEx {
Preconditions.checkState(Thread.holdsLock(mLock), "ZygoteProcess lock not held");
if (primaryZygoteState == null || primaryZygoteState.isClosed()) {
try {
primaryZygoteState = ZygoteState.connect(mSocket);
} catch (IOException ioe) {
throw new ZygoteStartFailedEx("Error connecting to primary zygote", ioe);
}
}
if (primaryZygoteState.matches(abi)) {
return primaryZygoteState;
}
// The primary zygote didn't match. Try the secondary.
if (secondaryZygoteState == null || secondaryZygoteState.isClosed()) {
try {
secondaryZygoteState = ZygoteState.connect(mSecondarySocket);
} catch (IOException ioe) {
throw new ZygoteStartFailedEx("Error connecting to secondary zygote", ioe);
}
}
if (secondaryZygoteState.matches(abi)) {
return secondaryZygoteState;
}
throw new ZygoteStartFailedEx("Unsupported zygote ABI: " + abi);
}
/**
* Instructs the zygote to pre-load the classes and native libraries at the given paths
* for the specified abi. Not all zygotes support this function.
*/
public boolean preloadPackageForAbi(String packagePath, String libsPath, String cacheKey,
String abi) throws ZygoteStartFailedEx, IOException {
synchronized(mLock) {
ZygoteState state = openZygoteSocketIfNeeded(abi);
state.writer.write("4");
state.writer.newLine();
state.writer.write("--preload-package");
state.writer.newLine();
state.writer.write(packagePath);
state.writer.newLine();
state.writer.write(libsPath);
state.writer.newLine();
state.writer.write(cacheKey);
state.writer.newLine();
state.writer.flush();
return (state.inputStream.readInt() == 0);
}
}
/**
* Instructs the zygote to preload the default set of classes and resources. Returns
* {@code true} if a preload was performed as a result of this call, and {@code false}
* otherwise. The latter usually means that the zygote eagerly preloaded at startup
* or due to a previous call to {@code preloadDefault}. Note that this call is synchronous.
*/
public boolean preloadDefault(String abi) throws ZygoteStartFailedEx, IOException {
synchronized (mLock) {
ZygoteState state = openZygoteSocketIfNeeded(abi);
// Each query starts with the argument count (1 in this case)
state.writer.write("1");
state.writer.newLine();
state.writer.write("--preload-default");
state.writer.newLine();
state.writer.flush();
return (state.inputStream.readInt() == 0);
}
}
/**
* Try connecting to the Zygote over and over again until we hit a time-out.
* @param socketName The name of the socket to connect to.
*/
public static void waitForConnectionToZygote(String socketName) {
for (int n = 20; n >= 0; n--) {
try {
final ZygoteState zs = ZygoteState.connect(socketName);
zs.close();
return;
} catch (IOException ioe) {
Log.w(LOG_TAG,
"Got error connecting to zygote, retrying. msg= " + ioe.getMessage());
}
try {
Thread.sleep(1000);
} catch (InterruptedException ie) {
}
}
// Slog.wtf(LOG_TAG, "Failed to connect to Zygote through socket " + socketName);
}
}