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