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