1 /*
2  * Copyright (C) 2006 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package android.os;
18 
19 import android.net.LocalSocket;
20 import android.net.LocalSocketAddress;
21 import android.system.Os;
22 import android.util.Log;
23 import com.android.internal.os.Zygote;
24 import dalvik.system.VMRuntime;
25 import java.io.BufferedWriter;
26 import java.io.DataInputStream;
27 import java.io.IOException;
28 import java.io.OutputStreamWriter;
29 import java.nio.charset.StandardCharsets;
30 import java.util.ArrayList;
31 import java.util.Arrays;
32 import java.util.List;
33 
34 /*package*/ class ZygoteStartFailedEx extends Exception {
ZygoteStartFailedEx(String s)35     ZygoteStartFailedEx(String s) {
36         super(s);
37     }
38 
ZygoteStartFailedEx(Throwable cause)39     ZygoteStartFailedEx(Throwable cause) {
40         super(cause);
41     }
42 
ZygoteStartFailedEx(String s, Throwable cause)43     ZygoteStartFailedEx(String s, Throwable cause) {
44         super(s, cause);
45     }
46 }
47 
48 /**
49  * Tools for managing OS processes.
50  */
51 public class Process {
52     private static final String LOG_TAG = "Process";
53 
54     /**
55      * @hide for internal use only.
56      */
57     public static final String ZYGOTE_SOCKET = "zygote";
58 
59     /**
60      * @hide for internal use only.
61      */
62     public static final String SECONDARY_ZYGOTE_SOCKET = "zygote_secondary";
63 
64     /**
65      * Defines the root UID.
66      * @hide
67      */
68     public static final int ROOT_UID = 0;
69 
70     /**
71      * Defines the UID/GID under which system code runs.
72      */
73     public static final int SYSTEM_UID = 1000;
74 
75     /**
76      * Defines the UID/GID under which the telephony code runs.
77      */
78     public static final int PHONE_UID = 1001;
79 
80     /**
81      * Defines the UID/GID for the user shell.
82      * @hide
83      */
84     public static final int SHELL_UID = 2000;
85 
86     /**
87      * Defines the UID/GID for the log group.
88      * @hide
89      */
90     public static final int LOG_UID = 1007;
91 
92     /**
93      * Defines the UID/GID for the WIFI supplicant process.
94      * @hide
95      */
96     public static final int WIFI_UID = 1010;
97 
98     /**
99      * Defines the UID/GID for the mediaserver process.
100      * @hide
101      */
102     public static final int MEDIA_UID = 1013;
103 
104     /**
105      * Defines the UID/GID for the DRM process.
106      * @hide
107      */
108     public static final int DRM_UID = 1019;
109 
110     /**
111      * Defines the UID/GID for the group that controls VPN services.
112      * @hide
113      */
114     public static final int VPN_UID = 1016;
115 
116     /**
117      * Defines the UID/GID for the NFC service process.
118      * @hide
119      */
120     public static final int NFC_UID = 1027;
121 
122     /**
123      * Defines the UID/GID for the Bluetooth service process.
124      * @hide
125      */
126     public static final int BLUETOOTH_UID = 1002;
127 
128     /**
129      * Defines the GID for the group that allows write access to the internal media storage.
130      * @hide
131      */
132     public static final int MEDIA_RW_GID = 1023;
133 
134     /**
135      * Access to installed package details
136      * @hide
137      */
138     public static final int PACKAGE_INFO_GID = 1032;
139 
140     /**
141      * Defines the UID/GID for the shared RELRO file updater process.
142      * @hide
143      */
144     public static final int SHARED_RELRO_UID = 1037;
145 
146     /**
147      * Defines the start of a range of UIDs (and GIDs), going from this
148      * number to {@link #LAST_APPLICATION_UID} that are reserved for assigning
149      * to applications.
150      */
151     public static final int FIRST_APPLICATION_UID = 10000;
152 
153     /**
154      * Last of application-specific UIDs starting at
155      * {@link #FIRST_APPLICATION_UID}.
156      */
157     public static final int LAST_APPLICATION_UID = 19999;
158 
159     /**
160      * First uid used for fully isolated sandboxed processes (with no permissions of their own)
161      * @hide
162      */
163     public static final int FIRST_ISOLATED_UID = 99000;
164 
165     /**
166      * Last uid used for fully isolated sandboxed processes (with no permissions of their own)
167      * @hide
168      */
169     public static final int LAST_ISOLATED_UID = 99999;
170 
171     /**
172      * Defines the gid shared by all applications running under the same profile.
173      * @hide
174      */
175     public static final int SHARED_USER_GID = 9997;
176 
177     /**
178      * First gid for applications to share resources. Used when forward-locking
179      * is enabled but all UserHandles need to be able to read the resources.
180      * @hide
181      */
182     public static final int FIRST_SHARED_APPLICATION_GID = 50000;
183 
184     /**
185      * Last gid for applications to share resources. Used when forward-locking
186      * is enabled but all UserHandles need to be able to read the resources.
187      * @hide
188      */
189     public static final int LAST_SHARED_APPLICATION_GID = 59999;
190 
191     /**
192      * Standard priority of application threads.
193      * Use with {@link #setThreadPriority(int)} and
194      * {@link #setThreadPriority(int, int)}, <b>not</b> with the normal
195      * {@link java.lang.Thread} class.
196      */
197     public static final int THREAD_PRIORITY_DEFAULT = 0;
198 
199     /*
200      * ***************************************
201      * ** Keep in sync with utils/threads.h **
202      * ***************************************
203      */
204 
205     /**
206      * Lowest available thread priority.  Only for those who really, really
207      * don't want to run if anything else is happening.
208      * Use with {@link #setThreadPriority(int)} and
209      * {@link #setThreadPriority(int, int)}, <b>not</b> with the normal
210      * {@link java.lang.Thread} class.
211      */
212     public static final int THREAD_PRIORITY_LOWEST = 19;
213 
214     /**
215      * Standard priority background threads.  This gives your thread a slightly
216      * lower than normal priority, so that it will have less chance of impacting
217      * the responsiveness of the user interface.
218      * Use with {@link #setThreadPriority(int)} and
219      * {@link #setThreadPriority(int, int)}, <b>not</b> with the normal
220      * {@link java.lang.Thread} class.
221      */
222     public static final int THREAD_PRIORITY_BACKGROUND = 10;
223 
224     /**
225      * Standard priority of threads that are currently running a user interface
226      * that the user is interacting with.  Applications can not normally
227      * change to this priority; the system will automatically adjust your
228      * application threads as the user moves through the UI.
229      * Use with {@link #setThreadPriority(int)} and
230      * {@link #setThreadPriority(int, int)}, <b>not</b> with the normal
231      * {@link java.lang.Thread} class.
232      */
233     public static final int THREAD_PRIORITY_FOREGROUND = -2;
234 
235     /**
236      * Standard priority of system display threads, involved in updating
237      * the user interface.  Applications can not
238      * normally change to this priority.
239      * Use with {@link #setThreadPriority(int)} and
240      * {@link #setThreadPriority(int, int)}, <b>not</b> with the normal
241      * {@link java.lang.Thread} class.
242      */
243     public static final int THREAD_PRIORITY_DISPLAY = -4;
244 
245     /**
246      * Standard priority of the most important display threads, for compositing
247      * the screen and retrieving input events.  Applications can not normally
248      * change to this priority.
249      * Use with {@link #setThreadPriority(int)} and
250      * {@link #setThreadPriority(int, int)}, <b>not</b> with the normal
251      * {@link java.lang.Thread} class.
252      */
253     public static final int THREAD_PRIORITY_URGENT_DISPLAY = -8;
254 
255     /**
256      * Standard priority of audio threads.  Applications can not normally
257      * change to this priority.
258      * Use with {@link #setThreadPriority(int)} and
259      * {@link #setThreadPriority(int, int)}, <b>not</b> with the normal
260      * {@link java.lang.Thread} class.
261      */
262     public static final int THREAD_PRIORITY_AUDIO = -16;
263 
264     /**
265      * Standard priority of the most important audio threads.
266      * Applications can not normally change to this priority.
267      * Use with {@link #setThreadPriority(int)} and
268      * {@link #setThreadPriority(int, int)}, <b>not</b> with the normal
269      * {@link java.lang.Thread} class.
270      */
271     public static final int THREAD_PRIORITY_URGENT_AUDIO = -19;
272 
273     /**
274      * Minimum increment to make a priority more favorable.
275      */
276     public static final int THREAD_PRIORITY_MORE_FAVORABLE = -1;
277 
278     /**
279      * Minimum increment to make a priority less favorable.
280      */
281     public static final int THREAD_PRIORITY_LESS_FAVORABLE = +1;
282 
283     /**
284      * Default scheduling policy
285      * @hide
286      */
287     public static final int SCHED_OTHER = 0;
288 
289     /**
290      * First-In First-Out scheduling policy
291      * @hide
292      */
293     public static final int SCHED_FIFO = 1;
294 
295     /**
296      * Round-Robin scheduling policy
297      * @hide
298      */
299     public static final int SCHED_RR = 2;
300 
301     /**
302      * Batch scheduling policy
303      * @hide
304      */
305     public static final int SCHED_BATCH = 3;
306 
307     /**
308      * Idle scheduling policy
309      * @hide
310      */
311     public static final int SCHED_IDLE = 5;
312 
313     // Keep in sync with SP_* constants of enum type SchedPolicy
314     // declared in system/core/include/cutils/sched_policy.h,
315     // except THREAD_GROUP_DEFAULT does not correspond to any SP_* value.
316 
317     /**
318      * Default thread group -
319      * has meaning with setProcessGroup() only, cannot be used with setThreadGroup().
320      * When used with setProcessGroup(), the group of each thread in the process
321      * is conditionally changed based on that thread's current priority, as follows:
322      * threads with priority numerically less than THREAD_PRIORITY_BACKGROUND
323      * are moved to foreground thread group.  All other threads are left unchanged.
324      * @hide
325      */
326     public static final int THREAD_GROUP_DEFAULT = -1;
327 
328     /**
329      * Background thread group - All threads in
330      * this group are scheduled with a reduced share of the CPU.
331      * Value is same as constant SP_BACKGROUND of enum SchedPolicy.
332      * FIXME rename to THREAD_GROUP_BACKGROUND.
333      * @hide
334      */
335     public static final int THREAD_GROUP_BG_NONINTERACTIVE = 0;
336 
337     /**
338      * Foreground thread group - All threads in
339      * this group are scheduled with a normal share of the CPU.
340      * Value is same as constant SP_FOREGROUND of enum SchedPolicy.
341      * Not used at this level.
342      * @hide
343      **/
344     private static final int THREAD_GROUP_FOREGROUND = 1;
345 
346     /**
347      * System thread group.
348      * @hide
349      **/
350     public static final int THREAD_GROUP_SYSTEM = 2;
351 
352     /**
353      * Application audio thread group.
354      * @hide
355      **/
356     public static final int THREAD_GROUP_AUDIO_APP = 3;
357 
358     /**
359      * System audio thread group.
360      * @hide
361      **/
362     public static final int THREAD_GROUP_AUDIO_SYS = 4;
363 
364     public static final int SIGNAL_QUIT = 3;
365     public static final int SIGNAL_KILL = 9;
366     public static final int SIGNAL_USR1 = 10;
367 
368     /**
369      * State for communicating with the zygote process.
370      *
371      * @hide for internal use only.
372      */
373     public static class ZygoteState {
374         final LocalSocket socket;
375         final DataInputStream inputStream;
376         final BufferedWriter writer;
377         final List<String> abiList;
378 
379         boolean mClosed;
380 
ZygoteState(LocalSocket socket, DataInputStream inputStream, BufferedWriter writer, List<String> abiList)381         private ZygoteState(LocalSocket socket, DataInputStream inputStream,
382                 BufferedWriter writer, List<String> abiList) {
383             this.socket = socket;
384             this.inputStream = inputStream;
385             this.writer = writer;
386             this.abiList = abiList;
387         }
388 
connect(String socketAddress)389         public static ZygoteState connect(String socketAddress) throws IOException {
390             DataInputStream zygoteInputStream = null;
391             BufferedWriter zygoteWriter = null;
392             final LocalSocket zygoteSocket = new LocalSocket();
393 
394             try {
395                 zygoteSocket.connect(new LocalSocketAddress(socketAddress,
396                         LocalSocketAddress.Namespace.RESERVED));
397 
398                 zygoteInputStream = new DataInputStream(zygoteSocket.getInputStream());
399 
400                 zygoteWriter = new BufferedWriter(new OutputStreamWriter(
401                         zygoteSocket.getOutputStream()), 256);
402             } catch (IOException ex) {
403                 try {
404                     zygoteSocket.close();
405                 } catch (IOException ignore) {
406                 }
407 
408                 throw ex;
409             }
410 
411             String abiListString = getAbiList(zygoteWriter, zygoteInputStream);
412             Log.i("Zygote", "Process: zygote socket opened, supported ABIS: " + abiListString);
413 
414             return new ZygoteState(zygoteSocket, zygoteInputStream, zygoteWriter,
415                     Arrays.asList(abiListString.split(",")));
416         }
417 
matches(String abi)418         boolean matches(String abi) {
419             return abiList.contains(abi);
420         }
421 
close()422         public void close() {
423             try {
424                 socket.close();
425             } catch (IOException ex) {
426                 Log.e(LOG_TAG,"I/O exception on routine close", ex);
427             }
428 
429             mClosed = true;
430         }
431 
isClosed()432         boolean isClosed() {
433             return mClosed;
434         }
435     }
436 
437     /**
438      * The state of the connection to the primary zygote.
439      */
440     static ZygoteState primaryZygoteState;
441 
442     /**
443      * The state of the connection to the secondary zygote.
444      */
445     static ZygoteState secondaryZygoteState;
446 
447     /**
448      * Start a new process.
449      *
450      * <p>If processes are enabled, a new process is created and the
451      * static main() function of a <var>processClass</var> is executed there.
452      * The process will continue running after this function returns.
453      *
454      * <p>If processes are not enabled, a new thread in the caller's
455      * process is created and main() of <var>processClass</var> called there.
456      *
457      * <p>The niceName parameter, if not an empty string, is a custom name to
458      * give to the process instead of using processClass.  This allows you to
459      * make easily identifyable processes even if you are using the same base
460      * <var>processClass</var> to start them.
461      *
462      * @param processClass The class to use as the process's main entry
463      *                     point.
464      * @param niceName A more readable name to use for the process.
465      * @param uid The user-id under which the process will run.
466      * @param gid The group-id under which the process will run.
467      * @param gids Additional group-ids associated with the process.
468      * @param debugFlags Additional flags.
469      * @param targetSdkVersion The target SDK version for the app.
470      * @param seInfo null-ok SELinux information for the new process.
471      * @param abi non-null the ABI this app should be started with.
472      * @param instructionSet null-ok the instruction set to use.
473      * @param appDataDir null-ok the data directory of the app.
474      * @param zygoteArgs Additional arguments to supply to the zygote process.
475      *
476      * @return An object that describes the result of the attempt to start the process.
477      * @throws RuntimeException on fatal start failure
478      *
479      * {@hide}
480      */
start(final String processClass, final String niceName, int uid, int gid, int[] gids, int debugFlags, int mountExternal, int targetSdkVersion, String seInfo, String abi, String instructionSet, String appDataDir, String[] zygoteArgs)481     public static final ProcessStartResult start(final String processClass,
482                                   final String niceName,
483                                   int uid, int gid, int[] gids,
484                                   int debugFlags, int mountExternal,
485                                   int targetSdkVersion,
486                                   String seInfo,
487                                   String abi,
488                                   String instructionSet,
489                                   String appDataDir,
490                                   String[] zygoteArgs) {
491         try {
492             return startViaZygote(processClass, niceName, uid, gid, gids,
493                     debugFlags, mountExternal, targetSdkVersion, seInfo,
494                     abi, instructionSet, appDataDir, zygoteArgs);
495         } catch (ZygoteStartFailedEx ex) {
496             Log.e(LOG_TAG,
497                     "Starting VM process through Zygote failed");
498             throw new RuntimeException(
499                     "Starting VM process through Zygote failed", ex);
500         }
501     }
502 
503     /** retry interval for opening a zygote socket */
504     static final int ZYGOTE_RETRY_MILLIS = 500;
505 
506     /**
507      * Queries the zygote for the list of ABIS it supports.
508      *
509      * @throws ZygoteStartFailedEx if the query failed.
510      */
getAbiList(BufferedWriter writer, DataInputStream inputStream)511     private static String getAbiList(BufferedWriter writer, DataInputStream inputStream)
512             throws IOException {
513         // Each query starts with the argument count (1 in this case)
514         writer.write("1");
515         // ... followed by a new-line.
516         writer.newLine();
517         // ... followed by our only argument.
518         writer.write("--query-abi-list");
519         writer.newLine();
520         writer.flush();
521 
522         // The response is a length prefixed stream of ASCII bytes.
523         int numBytes = inputStream.readInt();
524         byte[] bytes = new byte[numBytes];
525         inputStream.readFully(bytes);
526 
527         return new String(bytes, StandardCharsets.US_ASCII);
528     }
529 
530     /**
531      * Sends an argument list to the zygote process, which starts a new child
532      * and returns the child's pid. Please note: the present implementation
533      * replaces newlines in the argument list with spaces.
534      *
535      * @throws ZygoteStartFailedEx if process start failed for any reason
536      */
zygoteSendArgsAndGetResult( ZygoteState zygoteState, ArrayList<String> args)537     private static ProcessStartResult zygoteSendArgsAndGetResult(
538             ZygoteState zygoteState, ArrayList<String> args)
539             throws ZygoteStartFailedEx {
540         try {
541             /**
542              * See com.android.internal.os.ZygoteInit.readArgumentList()
543              * Presently the wire format to the zygote process is:
544              * a) a count of arguments (argc, in essence)
545              * b) a number of newline-separated argument strings equal to count
546              *
547              * After the zygote process reads these it will write the pid of
548              * the child or -1 on failure, followed by boolean to
549              * indicate whether a wrapper process was used.
550              */
551             final BufferedWriter writer = zygoteState.writer;
552             final DataInputStream inputStream = zygoteState.inputStream;
553 
554             writer.write(Integer.toString(args.size()));
555             writer.newLine();
556 
557             int sz = args.size();
558             for (int i = 0; i < sz; i++) {
559                 String arg = args.get(i);
560                 if (arg.indexOf('\n') >= 0) {
561                     throw new ZygoteStartFailedEx(
562                             "embedded newlines not allowed");
563                 }
564                 writer.write(arg);
565                 writer.newLine();
566             }
567 
568             writer.flush();
569 
570             // Should there be a timeout on this?
571             ProcessStartResult result = new ProcessStartResult();
572             result.pid = inputStream.readInt();
573             if (result.pid < 0) {
574                 throw new ZygoteStartFailedEx("fork() failed");
575             }
576             result.usingWrapper = inputStream.readBoolean();
577             return result;
578         } catch (IOException ex) {
579             zygoteState.close();
580             throw new ZygoteStartFailedEx(ex);
581         }
582     }
583 
584     /**
585      * Starts a new process via the zygote mechanism.
586      *
587      * @param processClass Class name whose static main() to run
588      * @param niceName 'nice' process name to appear in ps
589      * @param uid a POSIX uid that the new process should setuid() to
590      * @param gid a POSIX gid that the new process shuold setgid() to
591      * @param gids null-ok; a list of supplementary group IDs that the
592      * new process should setgroup() to.
593      * @param debugFlags Additional flags.
594      * @param targetSdkVersion The target SDK version for the app.
595      * @param seInfo null-ok SELinux information for the new process.
596      * @param abi the ABI the process should use.
597      * @param instructionSet null-ok the instruction set to use.
598      * @param appDataDir null-ok the data directory of the app.
599      * @param extraArgs Additional arguments to supply to the zygote process.
600      * @return An object that describes the result of the attempt to start the process.
601      * @throws ZygoteStartFailedEx if process start failed for any reason
602      */
startViaZygote(final String processClass, final String niceName, final int uid, final int gid, final int[] gids, int debugFlags, int mountExternal, int targetSdkVersion, String seInfo, String abi, String instructionSet, String appDataDir, String[] extraArgs)603     private static ProcessStartResult startViaZygote(final String processClass,
604                                   final String niceName,
605                                   final int uid, final int gid,
606                                   final int[] gids,
607                                   int debugFlags, int mountExternal,
608                                   int targetSdkVersion,
609                                   String seInfo,
610                                   String abi,
611                                   String instructionSet,
612                                   String appDataDir,
613                                   String[] extraArgs)
614                                   throws ZygoteStartFailedEx {
615         synchronized(Process.class) {
616             ArrayList<String> argsForZygote = new ArrayList<String>();
617 
618             // --runtime-args, --setuid=, --setgid=,
619             // and --setgroups= must go first
620             argsForZygote.add("--runtime-args");
621             argsForZygote.add("--setuid=" + uid);
622             argsForZygote.add("--setgid=" + gid);
623             if ((debugFlags & Zygote.DEBUG_ENABLE_JNI_LOGGING) != 0) {
624                 argsForZygote.add("--enable-jni-logging");
625             }
626             if ((debugFlags & Zygote.DEBUG_ENABLE_SAFEMODE) != 0) {
627                 argsForZygote.add("--enable-safemode");
628             }
629             if ((debugFlags & Zygote.DEBUG_ENABLE_DEBUGGER) != 0) {
630                 argsForZygote.add("--enable-debugger");
631             }
632             if ((debugFlags & Zygote.DEBUG_ENABLE_CHECKJNI) != 0) {
633                 argsForZygote.add("--enable-checkjni");
634             }
635             if ((debugFlags & Zygote.DEBUG_ENABLE_JIT) != 0) {
636                 argsForZygote.add("--enable-jit");
637             }
638             if ((debugFlags & Zygote.DEBUG_GENERATE_DEBUG_INFO) != 0) {
639                 argsForZygote.add("--generate-debug-info");
640             }
641             if ((debugFlags & Zygote.DEBUG_ENABLE_ASSERT) != 0) {
642                 argsForZygote.add("--enable-assert");
643             }
644             if (mountExternal == Zygote.MOUNT_EXTERNAL_DEFAULT) {
645                 argsForZygote.add("--mount-external-default");
646             } else if (mountExternal == Zygote.MOUNT_EXTERNAL_READ) {
647                 argsForZygote.add("--mount-external-read");
648             } else if (mountExternal == Zygote.MOUNT_EXTERNAL_WRITE) {
649                 argsForZygote.add("--mount-external-write");
650             }
651             argsForZygote.add("--target-sdk-version=" + targetSdkVersion);
652 
653             //TODO optionally enable debuger
654             //argsForZygote.add("--enable-debugger");
655 
656             // --setgroups is a comma-separated list
657             if (gids != null && gids.length > 0) {
658                 StringBuilder sb = new StringBuilder();
659                 sb.append("--setgroups=");
660 
661                 int sz = gids.length;
662                 for (int i = 0; i < sz; i++) {
663                     if (i != 0) {
664                         sb.append(',');
665                     }
666                     sb.append(gids[i]);
667                 }
668 
669                 argsForZygote.add(sb.toString());
670             }
671 
672             if (niceName != null) {
673                 argsForZygote.add("--nice-name=" + niceName);
674             }
675 
676             if (seInfo != null) {
677                 argsForZygote.add("--seinfo=" + seInfo);
678             }
679 
680             if (instructionSet != null) {
681                 argsForZygote.add("--instruction-set=" + instructionSet);
682             }
683 
684             if (appDataDir != null) {
685                 argsForZygote.add("--app-data-dir=" + appDataDir);
686             }
687 
688             argsForZygote.add(processClass);
689 
690             if (extraArgs != null) {
691                 for (String arg : extraArgs) {
692                     argsForZygote.add(arg);
693                 }
694             }
695 
696             return zygoteSendArgsAndGetResult(openZygoteSocketIfNeeded(abi), argsForZygote);
697         }
698     }
699 
700     /**
701      * Tries to establish a connection to the zygote that handles a given {@code abi}. Might block and retry if the
702      * zygote is unresponsive. This method is a no-op if a connection is already open.
703      *
704      * @hide
705      */
establishZygoteConnectionForAbi(String abi)706     public static void establishZygoteConnectionForAbi(String abi) {
707         try {
708             openZygoteSocketIfNeeded(abi);
709         } catch (ZygoteStartFailedEx ex) {
710             throw new RuntimeException("Unable to connect to zygote for abi: " + abi, ex);
711         }
712     }
713 
714     /**
715      * Tries to open socket to Zygote process if not already open. If
716      * already open, does nothing.  May block and retry.
717      */
openZygoteSocketIfNeeded(String abi)718     private static ZygoteState openZygoteSocketIfNeeded(String abi) throws ZygoteStartFailedEx {
719         if (primaryZygoteState == null || primaryZygoteState.isClosed()) {
720             try {
721                 primaryZygoteState = ZygoteState.connect(ZYGOTE_SOCKET);
722             } catch (IOException ioe) {
723                 throw new ZygoteStartFailedEx("Error connecting to primary zygote", ioe);
724             }
725         }
726 
727         if (primaryZygoteState.matches(abi)) {
728             return primaryZygoteState;
729         }
730 
731         // The primary zygote didn't match. Try the secondary.
732         if (secondaryZygoteState == null || secondaryZygoteState.isClosed()) {
733             try {
734             secondaryZygoteState = ZygoteState.connect(SECONDARY_ZYGOTE_SOCKET);
735             } catch (IOException ioe) {
736                 throw new ZygoteStartFailedEx("Error connecting to secondary zygote", ioe);
737             }
738         }
739 
740         if (secondaryZygoteState.matches(abi)) {
741             return secondaryZygoteState;
742         }
743 
744         throw new ZygoteStartFailedEx("Unsupported zygote ABI: " + abi);
745     }
746 
747     /**
748      * Returns elapsed milliseconds of the time this process has run.
749      * @return  Returns the number of milliseconds this process has return.
750      */
getElapsedCpuTime()751     public static final native long getElapsedCpuTime();
752 
753     /**
754      * Returns true if the current process is a 64-bit runtime.
755      */
is64Bit()756     public static final boolean is64Bit() {
757         return VMRuntime.getRuntime().is64Bit();
758     }
759 
760     /**
761      * Returns the identifier of this process, which can be used with
762      * {@link #killProcess} and {@link #sendSignal}.
763      */
myPid()764     public static final int myPid() {
765         return Os.getpid();
766     }
767 
768     /**
769      * Returns the identifier of this process' parent.
770      * @hide
771      */
myPpid()772     public static final int myPpid() {
773         return Os.getppid();
774     }
775 
776     /**
777      * Returns the identifier of the calling thread, which be used with
778      * {@link #setThreadPriority(int, int)}.
779      */
myTid()780     public static final int myTid() {
781         return Os.gettid();
782     }
783 
784     /**
785      * Returns the identifier of this process's uid.  This is the kernel uid
786      * that the process is running under, which is the identity of its
787      * app-specific sandbox.  It is different from {@link #myUserHandle} in that
788      * a uid identifies a specific app sandbox in a specific user.
789      */
myUid()790     public static final int myUid() {
791         return Os.getuid();
792     }
793 
794     /**
795      * Returns this process's user handle.  This is the
796      * user the process is running under.  It is distinct from
797      * {@link #myUid()} in that a particular user will have multiple
798      * distinct apps running under it each with their own uid.
799      */
myUserHandle()800     public static final UserHandle myUserHandle() {
801         return new UserHandle(UserHandle.getUserId(myUid()));
802     }
803 
804     /**
805      * Returns whether the current process is in an isolated sandbox.
806      * @hide
807      */
isIsolated()808     public static final boolean isIsolated() {
809         return isIsolated(myUid());
810     }
811 
812     /** {@hide} */
isIsolated(int uid)813     public static final boolean isIsolated(int uid) {
814         uid = UserHandle.getAppId(uid);
815         return uid >= FIRST_ISOLATED_UID && uid <= LAST_ISOLATED_UID;
816     }
817 
818     /**
819      * Returns the UID assigned to a particular user name, or -1 if there is
820      * none.  If the given string consists of only numbers, it is converted
821      * directly to a uid.
822      */
getUidForName(String name)823     public static final native int getUidForName(String name);
824 
825     /**
826      * Returns the GID assigned to a particular user name, or -1 if there is
827      * none.  If the given string consists of only numbers, it is converted
828      * directly to a gid.
829      */
getGidForName(String name)830     public static final native int getGidForName(String name);
831 
832     /**
833      * Returns a uid for a currently running process.
834      * @param pid the process id
835      * @return the uid of the process, or -1 if the process is not running.
836      * @hide pending API council review
837      */
getUidForPid(int pid)838     public static final int getUidForPid(int pid) {
839         String[] procStatusLabels = { "Uid:" };
840         long[] procStatusValues = new long[1];
841         procStatusValues[0] = -1;
842         Process.readProcLines("/proc/" + pid + "/status", procStatusLabels, procStatusValues);
843         return (int) procStatusValues[0];
844     }
845 
846     /**
847      * Returns the parent process id for a currently running process.
848      * @param pid the process id
849      * @return the parent process id of the process, or -1 if the process is not running.
850      * @hide
851      */
getParentPid(int pid)852     public static final int getParentPid(int pid) {
853         String[] procStatusLabels = { "PPid:" };
854         long[] procStatusValues = new long[1];
855         procStatusValues[0] = -1;
856         Process.readProcLines("/proc/" + pid + "/status", procStatusLabels, procStatusValues);
857         return (int) procStatusValues[0];
858     }
859 
860     /**
861      * Returns the thread group leader id for a currently running thread.
862      * @param tid the thread id
863      * @return the thread group leader id of the thread, or -1 if the thread is not running.
864      *         This is same as what getpid(2) would return if called by tid.
865      * @hide
866      */
getThreadGroupLeader(int tid)867     public static final int getThreadGroupLeader(int tid) {
868         String[] procStatusLabels = { "Tgid:" };
869         long[] procStatusValues = new long[1];
870         procStatusValues[0] = -1;
871         Process.readProcLines("/proc/" + tid + "/status", procStatusLabels, procStatusValues);
872         return (int) procStatusValues[0];
873     }
874 
875     /**
876      * Set the priority of a thread, based on Linux priorities.
877      *
878      * @param tid The identifier of the thread/process to change.
879      * @param priority A Linux priority level, from -20 for highest scheduling
880      * priority to 19 for lowest scheduling priority.
881      *
882      * @throws IllegalArgumentException Throws IllegalArgumentException if
883      * <var>tid</var> does not exist.
884      * @throws SecurityException Throws SecurityException if your process does
885      * not have permission to modify the given thread, or to use the given
886      * priority.
887      */
setThreadPriority(int tid, int priority)888     public static final native void setThreadPriority(int tid, int priority)
889             throws IllegalArgumentException, SecurityException;
890 
891     /**
892      * Call with 'false' to cause future calls to {@link #setThreadPriority(int)} to
893      * throw an exception if passed a background-level thread priority.  This is only
894      * effective if the JNI layer is built with GUARD_THREAD_PRIORITY defined to 1.
895      *
896      * @hide
897      */
setCanSelfBackground(boolean backgroundOk)898     public static final native void setCanSelfBackground(boolean backgroundOk);
899 
900     /**
901      * Sets the scheduling group for a thread.
902      * @hide
903      * @param tid The identifier of the thread to change.
904      * @param group The target group for this thread from THREAD_GROUP_*.
905      *
906      * @throws IllegalArgumentException Throws IllegalArgumentException if
907      * <var>tid</var> does not exist.
908      * @throws SecurityException Throws SecurityException if your process does
909      * not have permission to modify the given thread, or to use the given
910      * priority.
911      * If the thread is a thread group leader, that is it's gettid() == getpid(),
912      * then the other threads in the same thread group are _not_ affected.
913      */
setThreadGroup(int tid, int group)914     public static final native void setThreadGroup(int tid, int group)
915             throws IllegalArgumentException, SecurityException;
916 
917     /**
918      * Sets the scheduling group for a process and all child threads
919      * @hide
920      * @param pid The identifier of the process to change.
921      * @param group The target group for this process from THREAD_GROUP_*.
922      *
923      * @throws IllegalArgumentException Throws IllegalArgumentException if
924      * <var>tid</var> does not exist.
925      * @throws SecurityException Throws SecurityException if your process does
926      * not have permission to modify the given thread, or to use the given
927      * priority.
928      *
929      * group == THREAD_GROUP_DEFAULT means to move all non-background priority
930      * threads to the foreground scheduling group, but to leave background
931      * priority threads alone.  group == THREAD_GROUP_BG_NONINTERACTIVE moves all
932      * threads, regardless of priority, to the background scheduling group.
933      * group == THREAD_GROUP_FOREGROUND is not allowed.
934      */
setProcessGroup(int pid, int group)935     public static final native void setProcessGroup(int pid, int group)
936             throws IllegalArgumentException, SecurityException;
937 
938     /**
939      * Return the scheduling group of requested process.
940      *
941      * @hide
942      */
getProcessGroup(int pid)943     public static final native int getProcessGroup(int pid)
944             throws IllegalArgumentException, SecurityException;
945 
946     /**
947      * Set the priority of the calling thread, based on Linux priorities.  See
948      * {@link #setThreadPriority(int, int)} for more information.
949      *
950      * @param priority A Linux priority level, from -20 for highest scheduling
951      * priority to 19 for lowest scheduling priority.
952      *
953      * @throws IllegalArgumentException Throws IllegalArgumentException if
954      * <var>tid</var> does not exist.
955      * @throws SecurityException Throws SecurityException if your process does
956      * not have permission to modify the given thread, or to use the given
957      * priority.
958      *
959      * @see #setThreadPriority(int, int)
960      */
setThreadPriority(int priority)961     public static final native void setThreadPriority(int priority)
962             throws IllegalArgumentException, SecurityException;
963 
964     /**
965      * Return the current priority of a thread, based on Linux priorities.
966      *
967      * @param tid The identifier of the thread/process to change.
968      *
969      * @return Returns the current priority, as a Linux priority level,
970      * from -20 for highest scheduling priority to 19 for lowest scheduling
971      * priority.
972      *
973      * @throws IllegalArgumentException Throws IllegalArgumentException if
974      * <var>tid</var> does not exist.
975      */
getThreadPriority(int tid)976     public static final native int getThreadPriority(int tid)
977             throws IllegalArgumentException;
978 
979     /**
980      * Set the scheduling policy and priority of a thread, based on Linux.
981      *
982      * @param tid The identifier of the thread/process to change.
983      * @param policy A Linux scheduling policy such as SCHED_OTHER etc.
984      * @param priority A Linux priority level in a range appropriate for the given policy.
985      *
986      * @throws IllegalArgumentException Throws IllegalArgumentException if
987      * <var>tid</var> does not exist, or if <var>priority</var> is out of range for the policy.
988      * @throws SecurityException Throws SecurityException if your process does
989      * not have permission to modify the given thread, or to use the given
990      * scheduling policy or priority.
991      *
992      * {@hide}
993      */
setThreadScheduler(int tid, int policy, int priority)994     public static final native void setThreadScheduler(int tid, int policy, int priority)
995             throws IllegalArgumentException;
996 
997     /**
998      * Determine whether the current environment supports multiple processes.
999      *
1000      * @return Returns true if the system can run in multiple processes, else
1001      * false if everything is running in a single process.
1002      *
1003      * @deprecated This method always returns true.  Do not use.
1004      */
1005     @Deprecated
supportsProcesses()1006     public static final boolean supportsProcesses() {
1007         return true;
1008     }
1009 
1010     /**
1011      * Adjust the swappiness level for a process.
1012      *
1013      * @param pid The process identifier to set.
1014      * @param is_increased Whether swappiness should be increased or default.
1015      *
1016      * @return Returns true if the underlying system supports this
1017      *         feature, else false.
1018      *
1019      * {@hide}
1020      */
setSwappiness(int pid, boolean is_increased)1021     public static final native boolean setSwappiness(int pid, boolean is_increased);
1022 
1023     /**
1024      * Change this process's argv[0] parameter.  This can be useful to show
1025      * more descriptive information in things like the 'ps' command.
1026      *
1027      * @param text The new name of this process.
1028      *
1029      * {@hide}
1030      */
setArgV0(String text)1031     public static final native void setArgV0(String text);
1032 
1033     /**
1034      * Kill the process with the given PID.
1035      * Note that, though this API allows us to request to
1036      * kill any process based on its PID, the kernel will
1037      * still impose standard restrictions on which PIDs you
1038      * are actually able to kill.  Typically this means only
1039      * the process running the caller's packages/application
1040      * and any additional processes created by that app; packages
1041      * sharing a common UID will also be able to kill each
1042      * other's processes.
1043      */
killProcess(int pid)1044     public static final void killProcess(int pid) {
1045         sendSignal(pid, SIGNAL_KILL);
1046     }
1047 
1048     /** @hide */
setUid(int uid)1049     public static final native int setUid(int uid);
1050 
1051     /** @hide */
setGid(int uid)1052     public static final native int setGid(int uid);
1053 
1054     /**
1055      * Send a signal to the given process.
1056      *
1057      * @param pid The pid of the target process.
1058      * @param signal The signal to send.
1059      */
sendSignal(int pid, int signal)1060     public static final native void sendSignal(int pid, int signal);
1061 
1062     /**
1063      * @hide
1064      * Private impl for avoiding a log message...  DO NOT USE without doing
1065      * your own log, or the Android Illuminati will find you some night and
1066      * beat you up.
1067      */
killProcessQuiet(int pid)1068     public static final void killProcessQuiet(int pid) {
1069         sendSignalQuiet(pid, SIGNAL_KILL);
1070     }
1071 
1072     /**
1073      * @hide
1074      * Private impl for avoiding a log message...  DO NOT USE without doing
1075      * your own log, or the Android Illuminati will find you some night and
1076      * beat you up.
1077      */
sendSignalQuiet(int pid, int signal)1078     public static final native void sendSignalQuiet(int pid, int signal);
1079 
1080     /** @hide */
getFreeMemory()1081     public static final native long getFreeMemory();
1082 
1083     /** @hide */
getTotalMemory()1084     public static final native long getTotalMemory();
1085 
1086     /** @hide */
readProcLines(String path, String[] reqFields, long[] outSizes)1087     public static final native void readProcLines(String path,
1088             String[] reqFields, long[] outSizes);
1089 
1090     /** @hide */
getPids(String path, int[] lastArray)1091     public static final native int[] getPids(String path, int[] lastArray);
1092 
1093     /** @hide */
1094     public static final int PROC_TERM_MASK = 0xff;
1095     /** @hide */
1096     public static final int PROC_ZERO_TERM = 0;
1097     /** @hide */
1098     public static final int PROC_SPACE_TERM = (int)' ';
1099     /** @hide */
1100     public static final int PROC_TAB_TERM = (int)'\t';
1101     /** @hide */
1102     public static final int PROC_COMBINE = 0x100;
1103     /** @hide */
1104     public static final int PROC_PARENS = 0x200;
1105     /** @hide */
1106     public static final int PROC_QUOTES = 0x400;
1107     /** @hide */
1108     public static final int PROC_OUT_STRING = 0x1000;
1109     /** @hide */
1110     public static final int PROC_OUT_LONG = 0x2000;
1111     /** @hide */
1112     public static final int PROC_OUT_FLOAT = 0x4000;
1113 
1114     /** @hide */
readProcFile(String file, int[] format, String[] outStrings, long[] outLongs, float[] outFloats)1115     public static final native boolean readProcFile(String file, int[] format,
1116             String[] outStrings, long[] outLongs, float[] outFloats);
1117 
1118     /** @hide */
parseProcLine(byte[] buffer, int startIndex, int endIndex, int[] format, String[] outStrings, long[] outLongs, float[] outFloats)1119     public static final native boolean parseProcLine(byte[] buffer, int startIndex,
1120             int endIndex, int[] format, String[] outStrings, long[] outLongs, float[] outFloats);
1121 
1122     /** @hide */
getPidsForCommands(String[] cmds)1123     public static final native int[] getPidsForCommands(String[] cmds);
1124 
1125     /**
1126      * Gets the total Pss value for a given process, in bytes.
1127      *
1128      * @param pid the process to the Pss for
1129      * @return the total Pss value for the given process in bytes,
1130      *  or -1 if the value cannot be determined
1131      * @hide
1132      */
getPss(int pid)1133     public static final native long getPss(int pid);
1134 
1135     /**
1136      * Specifies the outcome of having started a process.
1137      * @hide
1138      */
1139     public static final class ProcessStartResult {
1140         /**
1141          * The PID of the newly started process.
1142          * Always >= 0.  (If the start failed, an exception will have been thrown instead.)
1143          */
1144         public int pid;
1145 
1146         /**
1147          * True if the process was started with a wrapper attached.
1148          */
1149         public boolean usingWrapper;
1150     }
1151 
1152     /**
1153      * Kill all processes in a process group started for the given
1154      * pid.
1155      * @hide
1156      */
killProcessGroup(int uid, int pid)1157     public static final native int killProcessGroup(int uid, int pid);
1158 
1159     /**
1160      * Remove all process groups.  Expected to be called when ActivityManager
1161      * is restarted.
1162      * @hide
1163      */
removeAllProcessGroups()1164     public static final native void removeAllProcessGroups();
1165 }
1166