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