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 static android.annotation.SystemApi.Client.MODULE_LIBRARIES; 20 21 import android.annotation.NonNull; 22 import android.annotation.Nullable; 23 import android.annotation.SystemApi; 24 import android.annotation.TestApi; 25 import android.compat.annotation.UnsupportedAppUsage; 26 import android.system.ErrnoException; 27 import android.system.Os; 28 import android.system.OsConstants; 29 import android.system.StructPollfd; 30 import android.util.Pair; 31 import android.webkit.WebViewZygote; 32 33 import dalvik.system.VMRuntime; 34 35 import libcore.io.IoUtils; 36 37 import java.io.FileDescriptor; 38 import java.io.IOException; 39 import java.util.Map; 40 import java.util.concurrent.TimeoutException; 41 42 /** 43 * Tools for managing OS processes. 44 */ 45 public class Process { 46 private static final String LOG_TAG = "Process"; 47 48 /** 49 * An invalid UID value. 50 */ 51 public static final int INVALID_UID = -1; 52 53 /** 54 * Defines the root UID. 55 */ 56 public static final int ROOT_UID = 0; 57 58 /** 59 * Defines the UID/GID under which system code runs. 60 */ 61 public static final int SYSTEM_UID = 1000; 62 63 /** 64 * Defines the UID/GID under which the telephony code runs. 65 */ 66 public static final int PHONE_UID = 1001; 67 68 /** 69 * Defines the UID/GID for the user shell. 70 */ 71 public static final int SHELL_UID = 2000; 72 73 /** 74 * Defines the UID/GID for the log group. 75 * @hide 76 */ 77 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553) 78 public static final int LOG_UID = 1007; 79 80 /** 81 * Defines the UID/GID for the WIFI native processes like wificond, supplicant, hostapd, 82 * vendor HAL, etc. 83 */ 84 public static final int WIFI_UID = 1010; 85 86 /** 87 * Defines the UID/GID for the mediaserver process. 88 * @hide 89 */ 90 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553) 91 public static final int MEDIA_UID = 1013; 92 93 /** 94 * Defines the UID/GID for the DRM process. 95 * @hide 96 */ 97 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553) 98 public static final int DRM_UID = 1019; 99 100 /** 101 * Defines the GID for the group that allows write access to the internal media storage. 102 * @hide 103 */ 104 public static final int SDCARD_RW_GID = 1015; 105 106 /** 107 * Defines the UID/GID for the group that controls VPN services. 108 * @hide 109 */ 110 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553) 111 @SystemApi(client = MODULE_LIBRARIES) 112 public static final int VPN_UID = 1016; 113 114 /** 115 * Defines the UID/GID for keystore. 116 * @hide 117 */ 118 public static final int KEYSTORE_UID = 1017; 119 120 /** 121 * Defines the UID/GID for credstore. 122 * @hide 123 */ 124 public static final int CREDSTORE_UID = 1076; 125 126 /** 127 * Defines the UID/GID for the NFC service process. 128 * @hide 129 */ 130 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553) 131 @TestApi 132 public static final int NFC_UID = 1027; 133 134 /** 135 * Defines the UID/GID for the clatd process. 136 * @hide 137 * */ 138 public static final int CLAT_UID = 1029; 139 140 /** 141 * Defines the UID/GID for the Bluetooth service process. 142 */ 143 public static final int BLUETOOTH_UID = 1002; 144 145 /** 146 * Defines the GID for the group that allows write access to the internal media storage. 147 * @hide 148 */ 149 public static final int MEDIA_RW_GID = 1023; 150 151 /** 152 * Access to installed package details 153 * @hide 154 */ 155 public static final int PACKAGE_INFO_GID = 1032; 156 157 /** 158 * Defines the UID/GID for the shared RELRO file updater process. 159 * @hide 160 */ 161 public static final int SHARED_RELRO_UID = 1037; 162 163 /** 164 * Defines the UID/GID for the audioserver process. 165 * @hide 166 */ 167 public static final int AUDIOSERVER_UID = 1041; 168 169 /** 170 * Defines the UID/GID for the cameraserver process 171 * @hide 172 */ 173 public static final int CAMERASERVER_UID = 1047; 174 175 /** 176 * Defines the UID/GID for the tethering DNS resolver (currently dnsmasq). 177 * @hide 178 */ 179 public static final int DNS_TETHER_UID = 1052; 180 181 /** 182 * Defines the UID/GID for the WebView zygote process. 183 * @hide 184 */ 185 public static final int WEBVIEW_ZYGOTE_UID = 1053; 186 187 /** 188 * Defines the UID used for resource tracking for OTA updates. 189 * @hide 190 */ 191 public static final int OTA_UPDATE_UID = 1061; 192 193 /** 194 * Defines the UID used for statsd 195 * @hide 196 */ 197 public static final int STATSD_UID = 1066; 198 199 /** 200 * Defines the UID used for incidentd. 201 * @hide 202 */ 203 public static final int INCIDENTD_UID = 1067; 204 205 /** 206 * Defines the UID/GID for the Secure Element service process. 207 * @hide 208 */ 209 public static final int SE_UID = 1068; 210 211 /** 212 * Defines the UID/GID for the iorapd. 213 * @hide 214 */ 215 public static final int IORAPD_UID = 1071; 216 217 /** 218 * Defines the UID/GID for the NetworkStack app. 219 * @hide 220 */ 221 public static final int NETWORK_STACK_UID = 1073; 222 223 /** 224 * Defines the UID/GID for fs-verity certificate ownership in keystore. 225 * @hide 226 */ 227 public static final int FSVERITY_CERT_UID = 1075; 228 229 /** 230 * GID that gives access to USB OTG (unreliable) volumes on /mnt/media_rw/<vol name> 231 * @hide 232 */ 233 public static final int EXTERNAL_STORAGE_GID = 1077; 234 235 /** 236 * GID that gives write access to app-private data directories on external 237 * storage (used on devices without sdcardfs only). 238 * @hide 239 */ 240 public static final int EXT_DATA_RW_GID = 1078; 241 242 /** 243 * GID that gives write access to app-private OBB directories on external 244 * storage (used on devices without sdcardfs only). 245 * @hide 246 */ 247 public static final int EXT_OBB_RW_GID = 1079; 248 249 /** 250 * Defines the UID/GID for the Uwb service process. 251 * @hide 252 */ 253 public static final int UWB_UID = 1083; 254 255 /** 256 * GID that corresponds to the INTERNET permission. 257 * Must match the value of AID_INET. 258 * @hide 259 */ 260 public static final int INET_GID = 3003; 261 262 /** {@hide} */ 263 public static final int NOBODY_UID = 9999; 264 265 /** 266 * Defines the start of a range of UIDs (and GIDs), going from this 267 * number to {@link #LAST_APPLICATION_UID} that are reserved for assigning 268 * to applications. 269 */ 270 public static final int FIRST_APPLICATION_UID = 10000; 271 272 /** 273 * Last of application-specific UIDs starting at 274 * {@link #FIRST_APPLICATION_UID}. 275 */ 276 public static final int LAST_APPLICATION_UID = 19999; 277 278 /** 279 * First uid used for fully isolated sandboxed processes spawned from an app zygote 280 * @hide 281 */ 282 @TestApi 283 public static final int FIRST_APP_ZYGOTE_ISOLATED_UID = 90000; 284 285 /** 286 * Number of UIDs we allocate per application zygote 287 * @hide 288 */ 289 @TestApi 290 public static final int NUM_UIDS_PER_APP_ZYGOTE = 100; 291 292 /** 293 * Last uid used for fully isolated sandboxed processes spawned from an app zygote 294 * @hide 295 */ 296 @TestApi 297 public static final int LAST_APP_ZYGOTE_ISOLATED_UID = 98999; 298 299 /** 300 * First uid used for fully isolated sandboxed processes (with no permissions of their own) 301 * @hide 302 */ 303 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553) 304 @TestApi 305 public static final int FIRST_ISOLATED_UID = 99000; 306 307 /** 308 * Last uid used for fully isolated sandboxed processes (with no permissions of their own) 309 * @hide 310 */ 311 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553) 312 @TestApi 313 public static final int LAST_ISOLATED_UID = 99999; 314 315 /** 316 * Defines the gid shared by all applications running under the same profile. 317 * @hide 318 */ 319 public static final int SHARED_USER_GID = 9997; 320 321 /** 322 * First gid for applications to share resources. Used when forward-locking 323 * is enabled but all UserHandles need to be able to read the resources. 324 * @hide 325 */ 326 public static final int FIRST_SHARED_APPLICATION_GID = 50000; 327 328 /** 329 * Last gid for applications to share resources. Used when forward-locking 330 * is enabled but all UserHandles need to be able to read the resources. 331 * @hide 332 */ 333 public static final int LAST_SHARED_APPLICATION_GID = 59999; 334 335 /** {@hide} */ 336 public static final int FIRST_APPLICATION_CACHE_GID = 20000; 337 /** {@hide} */ 338 public static final int LAST_APPLICATION_CACHE_GID = 29999; 339 340 /** 341 * Standard priority of application threads. 342 * Use with {@link #setThreadPriority(int)} and 343 * {@link #setThreadPriority(int, int)}, <b>not</b> with the normal 344 * {@link java.lang.Thread} class. 345 */ 346 public static final int THREAD_PRIORITY_DEFAULT = 0; 347 348 /* 349 * *************************************** 350 * ** Keep in sync with utils/threads.h ** 351 * *************************************** 352 */ 353 354 /** 355 * Lowest available thread priority. Only for those who really, really 356 * don't want to run if anything else is happening. 357 * Use with {@link #setThreadPriority(int)} and 358 * {@link #setThreadPriority(int, int)}, <b>not</b> with the normal 359 * {@link java.lang.Thread} class. 360 */ 361 public static final int THREAD_PRIORITY_LOWEST = 19; 362 363 /** 364 * Standard priority background threads. This gives your thread a slightly 365 * lower than normal priority, so that it will have less chance of impacting 366 * the responsiveness of the user interface. 367 * Use with {@link #setThreadPriority(int)} and 368 * {@link #setThreadPriority(int, int)}, <b>not</b> with the normal 369 * {@link java.lang.Thread} class. 370 */ 371 public static final int THREAD_PRIORITY_BACKGROUND = 10; 372 373 /** 374 * Standard priority of threads that are currently running a user interface 375 * that the user is interacting with. Applications can not normally 376 * change to this priority; the system will automatically adjust your 377 * application threads as the user moves through the UI. 378 * Use with {@link #setThreadPriority(int)} and 379 * {@link #setThreadPriority(int, int)}, <b>not</b> with the normal 380 * {@link java.lang.Thread} class. 381 */ 382 public static final int THREAD_PRIORITY_FOREGROUND = -2; 383 384 /** 385 * Standard priority of system display threads, involved in updating 386 * the user interface. Applications can not 387 * normally change to this priority. 388 * Use with {@link #setThreadPriority(int)} and 389 * {@link #setThreadPriority(int, int)}, <b>not</b> with the normal 390 * {@link java.lang.Thread} class. 391 */ 392 public static final int THREAD_PRIORITY_DISPLAY = -4; 393 394 /** 395 * Standard priority of the most important display threads, for compositing 396 * the screen and retrieving input events. Applications can not normally 397 * change to this priority. 398 * Use with {@link #setThreadPriority(int)} and 399 * {@link #setThreadPriority(int, int)}, <b>not</b> with the normal 400 * {@link java.lang.Thread} class. 401 */ 402 public static final int THREAD_PRIORITY_URGENT_DISPLAY = -8; 403 404 /** 405 * Standard priority of video threads. Applications can not normally 406 * change to this priority. 407 * Use with {@link #setThreadPriority(int)} and 408 * {@link #setThreadPriority(int, int)}, <b>not</b> with the normal 409 * {@link java.lang.Thread} class. 410 */ 411 public static final int THREAD_PRIORITY_VIDEO = -10; 412 413 /** 414 * Priority we boost main thread and RT of top app to. 415 * @hide 416 */ 417 public static final int THREAD_PRIORITY_TOP_APP_BOOST = -10; 418 419 /** 420 * Standard priority of audio threads. Applications can not normally 421 * change to this priority. 422 * Use with {@link #setThreadPriority(int)} and 423 * {@link #setThreadPriority(int, int)}, <b>not</b> with the normal 424 * {@link java.lang.Thread} class. 425 */ 426 public static final int THREAD_PRIORITY_AUDIO = -16; 427 428 /** 429 * Standard priority of the most important audio threads. 430 * Applications can not normally change to this priority. 431 * Use with {@link #setThreadPriority(int)} and 432 * {@link #setThreadPriority(int, int)}, <b>not</b> with the normal 433 * {@link java.lang.Thread} class. 434 */ 435 public static final int THREAD_PRIORITY_URGENT_AUDIO = -19; 436 437 /** 438 * Minimum increment to make a priority more favorable. 439 */ 440 public static final int THREAD_PRIORITY_MORE_FAVORABLE = -1; 441 442 /** 443 * Minimum increment to make a priority less favorable. 444 */ 445 public static final int THREAD_PRIORITY_LESS_FAVORABLE = +1; 446 447 /** 448 * Default scheduling policy 449 * @hide 450 */ 451 public static final int SCHED_OTHER = 0; 452 453 /** 454 * First-In First-Out scheduling policy 455 * @hide 456 */ 457 public static final int SCHED_FIFO = 1; 458 459 /** 460 * Round-Robin scheduling policy 461 * @hide 462 */ 463 public static final int SCHED_RR = 2; 464 465 /** 466 * Batch scheduling policy 467 * @hide 468 */ 469 public static final int SCHED_BATCH = 3; 470 471 /** 472 * Idle scheduling policy 473 * @hide 474 */ 475 public static final int SCHED_IDLE = 5; 476 477 /** 478 * Reset scheduler choice on fork. 479 * @hide 480 */ 481 public static final int SCHED_RESET_ON_FORK = 0x40000000; 482 483 // Keep in sync with SP_* constants of enum type SchedPolicy 484 // declared in system/core/include/cutils/sched_policy.h, 485 // except THREAD_GROUP_DEFAULT does not correspond to any SP_* value. 486 487 /** 488 * Default thread group - 489 * has meaning with setProcessGroup() only, cannot be used with setThreadGroup(). 490 * When used with setProcessGroup(), the group of each thread in the process 491 * is conditionally changed based on that thread's current priority, as follows: 492 * threads with priority numerically less than THREAD_PRIORITY_BACKGROUND 493 * are moved to foreground thread group. All other threads are left unchanged. 494 * @hide 495 */ 496 public static final int THREAD_GROUP_DEFAULT = -1; 497 498 /** 499 * Background thread group - All threads in 500 * this group are scheduled with a reduced share of the CPU. 501 * Value is same as constant SP_BACKGROUND of enum SchedPolicy. 502 * @hide 503 */ 504 public static final int THREAD_GROUP_BACKGROUND = 0; 505 506 /** 507 * Foreground thread group - All threads in 508 * this group are scheduled with a normal share of the CPU. 509 * Value is same as constant SP_FOREGROUND of enum SchedPolicy. 510 * Not used at this level. 511 * @hide 512 **/ 513 private static final int THREAD_GROUP_FOREGROUND = 1; 514 515 /** 516 * System thread group. 517 * @hide 518 **/ 519 public static final int THREAD_GROUP_SYSTEM = 2; 520 521 /** 522 * Application audio thread group. 523 * @hide 524 **/ 525 public static final int THREAD_GROUP_AUDIO_APP = 3; 526 527 /** 528 * System audio thread group. 529 * @hide 530 **/ 531 public static final int THREAD_GROUP_AUDIO_SYS = 4; 532 533 /** 534 * Thread group for top foreground app. 535 * @hide 536 **/ 537 public static final int THREAD_GROUP_TOP_APP = 5; 538 539 /** 540 * Thread group for RT app. 541 * @hide 542 **/ 543 public static final int THREAD_GROUP_RT_APP = 6; 544 545 /** 546 * Thread group for bound foreground services that should 547 * have additional CPU restrictions during screen off 548 * @hide 549 **/ 550 public static final int THREAD_GROUP_RESTRICTED = 7; 551 552 public static final int SIGNAL_QUIT = 3; 553 public static final int SIGNAL_KILL = 9; 554 public static final int SIGNAL_USR1 = 10; 555 556 private static long sStartElapsedRealtime; 557 private static long sStartUptimeMillis; 558 559 private static final int PIDFD_UNKNOWN = 0; 560 private static final int PIDFD_SUPPORTED = 1; 561 private static final int PIDFD_UNSUPPORTED = 2; 562 563 /** 564 * Whether or not the underlying OS supports pidfd 565 */ 566 private static int sPidFdSupported = PIDFD_UNKNOWN; 567 568 /** 569 * Value used to indicate that there is no special information about an application launch. App 570 * launches with this policy will occur through the primary or secondary Zygote with no special 571 * treatment. 572 * 573 * @hide 574 */ 575 public static final int ZYGOTE_POLICY_FLAG_EMPTY = 0; 576 577 /** 578 * Flag used to indicate that an application launch is user-visible and latency sensitive. Any 579 * launch with this policy will use a Unspecialized App Process Pool if the target Zygote 580 * supports it. 581 * 582 * @hide 583 */ 584 public static final int ZYGOTE_POLICY_FLAG_LATENCY_SENSITIVE = 1 << 0; 585 586 /** 587 * Flag used to indicate that the launch is one in a series of app launches that will be 588 * performed in quick succession. For future use. 589 * 590 * @hide 591 */ 592 public static final int ZYGOTE_POLICY_FLAG_BATCH_LAUNCH = 1 << 1; 593 594 /** 595 * Flag used to indicate that the current launch event is for a system process. All system 596 * processes are equally important, so none of them should be prioritized over the others. 597 * 598 * @hide 599 */ 600 public static final int ZYGOTE_POLICY_FLAG_SYSTEM_PROCESS = 1 << 2; 601 602 /** 603 * State associated with the zygote process. 604 * @hide 605 */ 606 public static final ZygoteProcess ZYGOTE_PROCESS = new ZygoteProcess(); 607 608 /** 609 * Start a new process. 610 * 611 * <p>If processes are enabled, a new process is created and the 612 * static main() function of a <var>processClass</var> is executed there. 613 * The process will continue running after this function returns. 614 * 615 * <p>If processes are not enabled, a new thread in the caller's 616 * process is created and main() of <var>processClass</var> called there. 617 * 618 * <p>The niceName parameter, if not an empty string, is a custom name to 619 * give to the process instead of using processClass. This allows you to 620 * make easily identifyable processes even if you are using the same base 621 * <var>processClass</var> to start them. 622 * 623 * When invokeWith is not null, the process will be started as a fresh app 624 * and not a zygote fork. Note that this is only allowed for uid 0 or when 625 * runtimeFlags contains DEBUG_ENABLE_DEBUGGER. 626 * 627 * @param processClass The class to use as the process's main entry 628 * point. 629 * @param niceName A more readable name to use for the process. 630 * @param uid The user-id under which the process will run. 631 * @param gid The group-id under which the process will run. 632 * @param gids Additional group-ids associated with the process. 633 * @param runtimeFlags Additional flags for the runtime. 634 * @param targetSdkVersion The target SDK version for the app. 635 * @param seInfo null-ok SELinux information for the new process. 636 * @param abi non-null the ABI this app should be started with. 637 * @param instructionSet null-ok the instruction set to use. 638 * @param appDataDir null-ok the data directory of the app. 639 * @param invokeWith null-ok the command to invoke with. 640 * @param packageName null-ok the name of the package this process belongs to. 641 * @param zygotePolicyFlags Flags used to determine how to launch the application 642 * @param isTopApp whether the process starts for high priority application. 643 * @param disabledCompatChanges null-ok list of disabled compat changes for the process being 644 * started. 645 * @param pkgDataInfoMap Map from related package names to private data directory 646 * volume UUID and inode number. 647 * @param whitelistedDataInfoMap Map from allowlisted package names to private data directory 648 * volume UUID and inode number. 649 * @param bindMountAppsData whether zygote needs to mount CE and DE data. 650 * @param bindMountAppStorageDirs whether zygote needs to mount Android/obb and Android/data. 651 * @param zygoteArgs Additional arguments to supply to the zygote process. 652 * @return An object that describes the result of the attempt to start the process. 653 * @throws RuntimeException on fatal start failure 654 * 655 * {@hide} 656 */ start(@onNull final String processClass, @Nullable final String niceName, int uid, int gid, @Nullable int[] gids, int runtimeFlags, int mountExternal, int targetSdkVersion, @Nullable String seInfo, @NonNull String abi, @Nullable String instructionSet, @Nullable String appDataDir, @Nullable String invokeWith, @Nullable String packageName, int zygotePolicyFlags, boolean isTopApp, @Nullable long[] disabledCompatChanges, @Nullable Map<String, Pair<String, Long>> pkgDataInfoMap, @Nullable Map<String, Pair<String, Long>> whitelistedDataInfoMap, boolean bindMountAppsData, boolean bindMountAppStorageDirs, @Nullable String[] zygoteArgs)657 public static ProcessStartResult start(@NonNull final String processClass, 658 @Nullable final String niceName, 659 int uid, int gid, @Nullable int[] gids, 660 int runtimeFlags, 661 int mountExternal, 662 int targetSdkVersion, 663 @Nullable String seInfo, 664 @NonNull String abi, 665 @Nullable String instructionSet, 666 @Nullable String appDataDir, 667 @Nullable String invokeWith, 668 @Nullable String packageName, 669 int zygotePolicyFlags, 670 boolean isTopApp, 671 @Nullable long[] disabledCompatChanges, 672 @Nullable Map<String, Pair<String, Long>> 673 pkgDataInfoMap, 674 @Nullable Map<String, Pair<String, Long>> 675 whitelistedDataInfoMap, 676 boolean bindMountAppsData, 677 boolean bindMountAppStorageDirs, 678 @Nullable String[] zygoteArgs) { 679 return ZYGOTE_PROCESS.start(processClass, niceName, uid, gid, gids, 680 runtimeFlags, mountExternal, targetSdkVersion, seInfo, 681 abi, instructionSet, appDataDir, invokeWith, packageName, 682 zygotePolicyFlags, isTopApp, disabledCompatChanges, 683 pkgDataInfoMap, whitelistedDataInfoMap, bindMountAppsData, 684 bindMountAppStorageDirs, zygoteArgs); 685 } 686 687 /** @hide */ startWebView(@onNull final String processClass, @Nullable final String niceName, int uid, int gid, @Nullable int[] gids, int runtimeFlags, int mountExternal, int targetSdkVersion, @Nullable String seInfo, @NonNull String abi, @Nullable String instructionSet, @Nullable String appDataDir, @Nullable String invokeWith, @Nullable String packageName, @Nullable long[] disabledCompatChanges, @Nullable String[] zygoteArgs)688 public static ProcessStartResult startWebView(@NonNull final String processClass, 689 @Nullable final String niceName, 690 int uid, int gid, @Nullable int[] gids, 691 int runtimeFlags, 692 int mountExternal, 693 int targetSdkVersion, 694 @Nullable String seInfo, 695 @NonNull String abi, 696 @Nullable String instructionSet, 697 @Nullable String appDataDir, 698 @Nullable String invokeWith, 699 @Nullable String packageName, 700 @Nullable long[] disabledCompatChanges, 701 @Nullable String[] zygoteArgs) { 702 // Webview zygote can't access app private data files, so doesn't need to know its data 703 // info. 704 return WebViewZygote.getProcess().start(processClass, niceName, uid, gid, gids, 705 runtimeFlags, mountExternal, targetSdkVersion, seInfo, 706 abi, instructionSet, appDataDir, invokeWith, packageName, 707 /*zygotePolicyFlags=*/ ZYGOTE_POLICY_FLAG_EMPTY, /*isTopApp=*/ false, 708 disabledCompatChanges, /* pkgDataInfoMap */ null, 709 /* whitelistedDataInfoMap */ null, false, false, zygoteArgs); 710 } 711 712 /** 713 * Returns elapsed milliseconds of the time this process has run. 714 * @return Returns the number of milliseconds this process has return. 715 */ getElapsedCpuTime()716 public static final native long getElapsedCpuTime(); 717 718 /** 719 * Return the {@link SystemClock#elapsedRealtime()} at which this process was started. 720 */ getStartElapsedRealtime()721 public static final long getStartElapsedRealtime() { 722 return sStartElapsedRealtime; 723 } 724 725 /** 726 * Return the {@link SystemClock#uptimeMillis()} at which this process was started. 727 */ getStartUptimeMillis()728 public static final long getStartUptimeMillis() { 729 return sStartUptimeMillis; 730 } 731 732 /** @hide */ setStartTimes(long elapsedRealtime, long uptimeMillis)733 public static final void setStartTimes(long elapsedRealtime, long uptimeMillis) { 734 sStartElapsedRealtime = elapsedRealtime; 735 sStartUptimeMillis = uptimeMillis; 736 } 737 738 /** 739 * Returns true if the current process is a 64-bit runtime. 740 */ is64Bit()741 public static final boolean is64Bit() { 742 return VMRuntime.getRuntime().is64Bit(); 743 } 744 745 /** 746 * Returns the identifier of this process, which can be used with 747 * {@link #killProcess} and {@link #sendSignal}. 748 */ myPid()749 public static final int myPid() { 750 return Os.getpid(); 751 } 752 753 /** 754 * Returns the identifier of this process' parent. 755 * @hide 756 */ 757 @UnsupportedAppUsage(trackingBug = 171962076) myPpid()758 public static final int myPpid() { 759 return Os.getppid(); 760 } 761 762 /** 763 * Returns the identifier of the calling thread, which be used with 764 * {@link #setThreadPriority(int, int)}. 765 */ myTid()766 public static final int myTid() { 767 return Os.gettid(); 768 } 769 770 /** 771 * Returns the identifier of this process's uid. This is the kernel uid 772 * that the process is running under, which is the identity of its 773 * app-specific sandbox. It is different from {@link #myUserHandle} in that 774 * a uid identifies a specific app sandbox in a specific user. 775 */ myUid()776 public static final int myUid() { 777 return Os.getuid(); 778 } 779 780 /** 781 * Returns this process's user handle. This is the 782 * user the process is running under. It is distinct from 783 * {@link #myUid()} in that a particular user will have multiple 784 * distinct apps running under it each with their own uid. 785 */ myUserHandle()786 public static UserHandle myUserHandle() { 787 return UserHandle.of(UserHandle.getUserId(myUid())); 788 } 789 790 /** 791 * Returns whether the given uid belongs to a system core component or not. 792 * @hide 793 */ isCoreUid(int uid)794 public static boolean isCoreUid(int uid) { 795 return UserHandle.isCore(uid); 796 } 797 798 /** 799 * Returns whether the given uid belongs to an application. 800 * @param uid A kernel uid. 801 * @return Whether the uid corresponds to an application sandbox running in 802 * a specific user. 803 */ isApplicationUid(int uid)804 public static boolean isApplicationUid(int uid) { 805 return UserHandle.isApp(uid); 806 } 807 808 /** 809 * Returns whether the current process is in an isolated sandbox. 810 */ isIsolated()811 public static final boolean isIsolated() { 812 return isIsolated(myUid()); 813 } 814 815 /** {@hide} */ 816 @UnsupportedAppUsage isIsolated(int uid)817 public static final boolean isIsolated(int uid) { 818 uid = UserHandle.getAppId(uid); 819 return (uid >= FIRST_ISOLATED_UID && uid <= LAST_ISOLATED_UID) 820 || (uid >= FIRST_APP_ZYGOTE_ISOLATED_UID && uid <= LAST_APP_ZYGOTE_ISOLATED_UID); 821 } 822 823 /** 824 * Returns the UID assigned to a particular user name, or -1 if there is 825 * none. If the given string consists of only numbers, it is converted 826 * directly to a uid. 827 */ getUidForName(String name)828 public static final native int getUidForName(String name); 829 830 /** 831 * Returns the GID assigned to a particular user name, or -1 if there is 832 * none. If the given string consists of only numbers, it is converted 833 * directly to a gid. 834 */ getGidForName(String name)835 public static final native int getGidForName(String name); 836 837 /** 838 * Returns a uid for a currently running process. 839 * @param pid the process id 840 * @return the uid of the process, or -1 if the process is not running. 841 * @hide pending API council review 842 */ 843 @UnsupportedAppUsage getUidForPid(int pid)844 public static final int getUidForPid(int pid) { 845 String[] procStatusLabels = { "Uid:" }; 846 long[] procStatusValues = new long[1]; 847 procStatusValues[0] = -1; 848 Process.readProcLines("/proc/" + pid + "/status", procStatusLabels, procStatusValues); 849 return (int) procStatusValues[0]; 850 } 851 852 /** 853 * Returns the parent process id for a currently running process. 854 * @param pid the process id 855 * @return the parent process id of the process, or -1 if the process is not running. 856 * @hide 857 */ 858 @UnsupportedAppUsage getParentPid(int pid)859 public static final int getParentPid(int pid) { 860 String[] procStatusLabels = { "PPid:" }; 861 long[] procStatusValues = new long[1]; 862 procStatusValues[0] = -1; 863 Process.readProcLines("/proc/" + pid + "/status", procStatusLabels, procStatusValues); 864 return (int) procStatusValues[0]; 865 } 866 867 /** 868 * Returns the thread group leader id for a currently running thread. 869 * @param tid the thread id 870 * @return the thread group leader id of the thread, or -1 if the thread is not running. 871 * This is same as what getpid(2) would return if called by tid. 872 * @hide 873 */ getThreadGroupLeader(int tid)874 public static final int getThreadGroupLeader(int tid) { 875 String[] procStatusLabels = { "Tgid:" }; 876 long[] procStatusValues = new long[1]; 877 procStatusValues[0] = -1; 878 Process.readProcLines("/proc/" + tid + "/status", procStatusLabels, procStatusValues); 879 return (int) procStatusValues[0]; 880 } 881 882 /** 883 * Set the priority of a thread, based on Linux priorities. 884 * 885 * @param tid The identifier of the thread/process to change. 886 * @param priority A Linux priority level, from -20 for highest scheduling 887 * priority to 19 for lowest scheduling priority. 888 * 889 * @throws IllegalArgumentException Throws IllegalArgumentException if 890 * <var>tid</var> does not exist. 891 * @throws SecurityException Throws SecurityException if your process does 892 * not have permission to modify the given thread, or to use the given 893 * priority. 894 */ setThreadPriority(int tid, int priority)895 public static final native void setThreadPriority(int tid, int priority) 896 throws IllegalArgumentException, SecurityException; 897 898 /** 899 * Call with 'false' to cause future calls to {@link #setThreadPriority(int)} to 900 * throw an exception if passed a background-level thread priority. This is only 901 * effective if the JNI layer is built with GUARD_THREAD_PRIORITY defined to 1. 902 * 903 * @hide 904 */ setCanSelfBackground(boolean backgroundOk)905 public static final native void setCanSelfBackground(boolean backgroundOk); 906 907 /** 908 * Sets the scheduling group for a thread. 909 * @hide 910 * @param tid The identifier of the thread to change. 911 * @param group The target group for this thread from THREAD_GROUP_*. 912 * 913 * @throws IllegalArgumentException Throws IllegalArgumentException if 914 * <var>tid</var> does not exist. 915 * @throws SecurityException Throws SecurityException if your process does 916 * not have permission to modify the given thread, or to use the given 917 * priority. 918 * If the thread is a thread group leader, that is it's gettid() == getpid(), 919 * then the other threads in the same thread group are _not_ affected. 920 * 921 * Does not set cpuset for some historical reason, just calls 922 * libcutils::set_sched_policy(). 923 */ setThreadGroup(int tid, int group)924 public static final native void setThreadGroup(int tid, int group) 925 throws IllegalArgumentException, SecurityException; 926 927 /** 928 * Sets the scheduling group and the corresponding cpuset group 929 * @hide 930 * @param tid The identifier of the thread to change. 931 * @param group The target group for this thread from THREAD_GROUP_*. 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 */ setThreadGroupAndCpuset(int tid, int group)939 public static final native void setThreadGroupAndCpuset(int tid, int group) 940 throws IllegalArgumentException, SecurityException; 941 942 /** 943 * Sets the scheduling group for a process and all child threads 944 * @hide 945 * @param pid The identifier of the process to change. 946 * @param group The target group for this process from THREAD_GROUP_*. 947 * 948 * @throws IllegalArgumentException Throws IllegalArgumentException if 949 * <var>tid</var> does not exist. 950 * @throws SecurityException Throws SecurityException if your process does 951 * not have permission to modify the given thread, or to use the given 952 * priority. 953 * 954 * group == THREAD_GROUP_DEFAULT means to move all non-background priority 955 * threads to the foreground scheduling group, but to leave background 956 * priority threads alone. group == THREAD_GROUP_BACKGROUND moves all 957 * threads, regardless of priority, to the background scheduling group. 958 * group == THREAD_GROUP_FOREGROUND is not allowed. 959 * 960 * Always sets cpusets. 961 */ 962 @UnsupportedAppUsage setProcessGroup(int pid, int group)963 public static final native void setProcessGroup(int pid, int group) 964 throws IllegalArgumentException, SecurityException; 965 966 /** 967 * Freeze or unfreeze the specified process. 968 * 969 * @param pid Identifier of the process to freeze or unfreeze. 970 * @param uid Identifier of the user the process is running under. 971 * @param frozen Specify whether to free (true) or unfreeze (false). 972 * 973 * @hide 974 */ setProcessFrozen(int pid, int uid, boolean frozen)975 public static final native void setProcessFrozen(int pid, int uid, boolean frozen); 976 977 /** 978 * Enable or disable the freezer. When enable == false all frozen processes are unfrozen, 979 * but aren't removed from the freezer. While in this state, processes can be added or removed 980 * by using setProcessFrozen, but they won't actually be frozen until the freezer is enabled 981 * again. If enable == true the freezer is enabled again, and all processes 982 * in the freezer (including the ones added while the freezer was disabled) are frozen. 983 * 984 * @param enable Specify whether to enable (true) or disable (false) the freezer. 985 * 986 * @hide 987 */ enableFreezer(boolean enable)988 public static final native void enableFreezer(boolean enable); 989 990 /** 991 * Return the scheduling group of requested process. 992 * 993 * @hide 994 */ getProcessGroup(int pid)995 public static final native int getProcessGroup(int pid) 996 throws IllegalArgumentException, SecurityException; 997 998 /** 999 * 1000 * Create a new process group in the cgroup uid/pid hierarchy 1001 * 1002 * @return <0 in case of error 1003 * 1004 * @hide 1005 */ createProcessGroup(int uid, int pid)1006 public static final native int createProcessGroup(int uid, int pid); 1007 1008 /** 1009 * On some devices, the foreground process may have one or more CPU 1010 * cores exclusively reserved for it. This method can be used to 1011 * retrieve which cores that are (if any), so the calling process 1012 * can then use sched_setaffinity() to lock a thread to these cores. 1013 * Note that the calling process must currently be running in the 1014 * foreground for this method to return any cores. 1015 * 1016 * The CPU core(s) exclusively reserved for the foreground process will 1017 * stay reserved for as long as the process stays in the foreground. 1018 * 1019 * As soon as a process leaves the foreground, those CPU cores will 1020 * no longer be reserved for it, and will most likely be reserved for 1021 * the new foreground process. It's not necessary to change the affinity 1022 * of your process when it leaves the foreground (if you had previously 1023 * set it to use a reserved core); the OS will automatically take care 1024 * of resetting the affinity at that point. 1025 * 1026 * @return an array of integers, indicating the CPU cores exclusively 1027 * reserved for this process. The array will have length zero if no 1028 * CPU cores are exclusively reserved for this process at this point 1029 * in time. 1030 */ getExclusiveCores()1031 public static final native int[] getExclusiveCores(); 1032 1033 /** 1034 * Set the priority of the calling thread, based on Linux priorities. See 1035 * {@link #setThreadPriority(int, int)} for more information. 1036 * 1037 * @param priority A Linux priority level, from -20 for highest scheduling 1038 * priority to 19 for lowest scheduling priority. 1039 * 1040 * @throws IllegalArgumentException Throws IllegalArgumentException if 1041 * <var>tid</var> does not exist. 1042 * @throws SecurityException Throws SecurityException if your process does 1043 * not have permission to modify the given thread, or to use the given 1044 * priority. 1045 * 1046 * @see #setThreadPriority(int, int) 1047 */ setThreadPriority(int priority)1048 public static final native void setThreadPriority(int priority) 1049 throws IllegalArgumentException, SecurityException; 1050 1051 /** 1052 * Return the current priority of a thread, based on Linux priorities. 1053 * 1054 * @param tid The identifier of the thread/process. If tid equals zero, the priority of the 1055 * calling process/thread will be returned. 1056 * 1057 * @return Returns the current priority, as a Linux priority level, 1058 * from -20 for highest scheduling priority to 19 for lowest scheduling 1059 * priority. 1060 * 1061 * @throws IllegalArgumentException Throws IllegalArgumentException if 1062 * <var>tid</var> does not exist. 1063 */ getThreadPriority(int tid)1064 public static final native int getThreadPriority(int tid) 1065 throws IllegalArgumentException; 1066 1067 /** 1068 * Return the current scheduling policy of a thread, based on Linux. 1069 * 1070 * @param tid The identifier of the thread/process to get the scheduling policy. 1071 * 1072 * @throws IllegalArgumentException Throws IllegalArgumentException if 1073 * <var>tid</var> does not exist, or if <var>priority</var> is out of range for the policy. 1074 * @throws SecurityException Throws SecurityException if your process does 1075 * not have permission to modify the given thread, or to use the given 1076 * scheduling policy or priority. 1077 * 1078 * {@hide} 1079 */ 1080 1081 @TestApi getThreadScheduler(int tid)1082 public static final native int getThreadScheduler(int tid) 1083 throws IllegalArgumentException; 1084 1085 /** 1086 * Set the scheduling policy and priority of a thread, based on Linux. 1087 * 1088 * @param tid The identifier of the thread/process to change. 1089 * @param policy A Linux scheduling policy such as SCHED_OTHER etc. 1090 * @param priority A Linux priority level in a range appropriate for the given policy. 1091 * 1092 * @throws IllegalArgumentException Throws IllegalArgumentException if 1093 * <var>tid</var> does not exist, or if <var>priority</var> is out of range for the policy. 1094 * @throws SecurityException Throws SecurityException if your process does 1095 * not have permission to modify the given thread, or to use the given 1096 * scheduling policy or priority. 1097 * 1098 * {@hide} 1099 */ 1100 setThreadScheduler(int tid, int policy, int priority)1101 public static final native void setThreadScheduler(int tid, int policy, int priority) 1102 throws IllegalArgumentException; 1103 1104 /** 1105 * Determine whether the current environment supports multiple processes. 1106 * 1107 * @return Returns true if the system can run in multiple processes, else 1108 * false if everything is running in a single process. 1109 * 1110 * @deprecated This method always returns true. Do not use. 1111 */ 1112 @Deprecated supportsProcesses()1113 public static final boolean supportsProcesses() { 1114 return true; 1115 } 1116 1117 /** 1118 * Adjust the swappiness level for a process. 1119 * 1120 * @param pid The process identifier to set. 1121 * @param is_increased Whether swappiness should be increased or default. 1122 * 1123 * @return Returns true if the underlying system supports this 1124 * feature, else false. 1125 * 1126 * {@hide} 1127 */ setSwappiness(int pid, boolean is_increased)1128 public static final native boolean setSwappiness(int pid, boolean is_increased); 1129 1130 /** 1131 * Change this process's argv[0] parameter. This can be useful to show 1132 * more descriptive information in things like the 'ps' command. 1133 * 1134 * @param text The new name of this process. 1135 * 1136 * {@hide} 1137 */ 1138 @UnsupportedAppUsage setArgV0(String text)1139 public static final native void setArgV0(String text); 1140 1141 /** 1142 * Kill the process with the given PID. 1143 * Note that, though this API allows us to request to 1144 * kill any process based on its PID, the kernel will 1145 * still impose standard restrictions on which PIDs you 1146 * are actually able to kill. Typically this means only 1147 * the process running the caller's packages/application 1148 * and any additional processes created by that app; packages 1149 * sharing a common UID will also be able to kill each 1150 * other's processes. 1151 */ killProcess(int pid)1152 public static final void killProcess(int pid) { 1153 sendSignal(pid, SIGNAL_KILL); 1154 } 1155 1156 /** @hide */ setUid(int uid)1157 public static final native int setUid(int uid); 1158 1159 /** @hide */ setGid(int uid)1160 public static final native int setGid(int uid); 1161 1162 /** 1163 * Send a signal to the given process. 1164 * 1165 * @param pid The pid of the target process. 1166 * @param signal The signal to send. 1167 */ sendSignal(int pid, int signal)1168 public static final native void sendSignal(int pid, int signal); 1169 1170 /** 1171 * @hide 1172 * Private impl for avoiding a log message... DO NOT USE without doing 1173 * your own log, or the Android Illuminati will find you some night and 1174 * beat you up. 1175 */ killProcessQuiet(int pid)1176 public static final void killProcessQuiet(int pid) { 1177 sendSignalQuiet(pid, SIGNAL_KILL); 1178 } 1179 1180 /** 1181 * @hide 1182 * Private impl for avoiding a log message... DO NOT USE without doing 1183 * your own log, or the Android Illuminati will find you some night and 1184 * beat you up. 1185 */ 1186 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P) sendSignalQuiet(int pid, int signal)1187 public static final native void sendSignalQuiet(int pid, int signal); 1188 1189 /** @hide */ 1190 @UnsupportedAppUsage getFreeMemory()1191 public static final native long getFreeMemory(); 1192 1193 /** @hide */ 1194 @UnsupportedAppUsage getTotalMemory()1195 public static final native long getTotalMemory(); 1196 1197 /** @hide */ 1198 @UnsupportedAppUsage readProcLines(String path, String[] reqFields, long[] outSizes)1199 public static final native void readProcLines(String path, 1200 String[] reqFields, long[] outSizes); 1201 1202 /** @hide */ 1203 @UnsupportedAppUsage getPids(String path, int[] lastArray)1204 public static final native int[] getPids(String path, int[] lastArray); 1205 1206 /** @hide */ 1207 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553) 1208 public static final int PROC_TERM_MASK = 0xff; 1209 /** @hide */ 1210 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553) 1211 public static final int PROC_ZERO_TERM = 0; 1212 /** @hide */ 1213 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553) 1214 public static final int PROC_SPACE_TERM = (int)' '; 1215 /** @hide */ 1216 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553) 1217 public static final int PROC_TAB_TERM = (int)'\t'; 1218 /** @hide */ 1219 public static final int PROC_NEWLINE_TERM = (int) '\n'; 1220 /** @hide */ 1221 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553) 1222 public static final int PROC_COMBINE = 0x100; 1223 /** @hide */ 1224 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553) 1225 public static final int PROC_PARENS = 0x200; 1226 /** @hide */ 1227 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553) 1228 public static final int PROC_QUOTES = 0x400; 1229 /** @hide */ 1230 public static final int PROC_CHAR = 0x800; 1231 /** @hide */ 1232 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553) 1233 public static final int PROC_OUT_STRING = 0x1000; 1234 /** @hide */ 1235 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553) 1236 public static final int PROC_OUT_LONG = 0x2000; 1237 /** @hide */ 1238 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553) 1239 public static final int PROC_OUT_FLOAT = 0x4000; 1240 1241 /** 1242 * Read and parse a {@code proc} file in the given format. 1243 * 1244 * <p>The format is a list of integers, where every integer describes a variable in the file. It 1245 * specifies how the variable is syntactically terminated (e.g. {@link Process#PROC_SPACE_TERM}, 1246 * {@link Process#PROC_TAB_TERM}, {@link Process#PROC_ZERO_TERM}, {@link 1247 * Process#PROC_NEWLINE_TERM}). 1248 * 1249 * <p>If the variable should be parsed and returned to the caller, the termination type should 1250 * be binary OR'd with the type of output (e.g. {@link Process#PROC_OUT_STRING}, {@link 1251 * Process#PROC_OUT_LONG}, {@link Process#PROC_OUT_FLOAT}. 1252 * 1253 * <p>If the variable is wrapped in quotation marks it should be binary OR'd with {@link 1254 * Process#PROC_QUOTES}. If the variable is wrapped in parentheses it should be binary OR'd with 1255 * {@link Process#PROC_PARENS}. 1256 * 1257 * <p>If the variable is not formatted as a string and should be cast directly from characters 1258 * to a long, the {@link Process#PROC_CHAR} integer should be binary OR'd. 1259 * 1260 * <p>If the terminating character can be repeated, the {@link Process#PROC_COMBINE} integer 1261 * should be binary OR'd. 1262 * 1263 * @param file the path of the {@code proc} file to read 1264 * @param format the format of the file 1265 * @param outStrings the parsed {@code String}s from the file 1266 * @param outLongs the parsed {@code long}s from the file 1267 * @param outFloats the parsed {@code float}s from the file 1268 * @hide 1269 */ 1270 @UnsupportedAppUsage readProcFile(String file, int[] format, String[] outStrings, long[] outLongs, float[] outFloats)1271 public static final native boolean readProcFile(String file, int[] format, 1272 String[] outStrings, long[] outLongs, float[] outFloats); 1273 1274 /** @hide */ 1275 @UnsupportedAppUsage parseProcLine(byte[] buffer, int startIndex, int endIndex, int[] format, String[] outStrings, long[] outLongs, float[] outFloats)1276 public static final native boolean parseProcLine(byte[] buffer, int startIndex, 1277 int endIndex, int[] format, String[] outStrings, long[] outLongs, float[] outFloats); 1278 1279 /** @hide */ 1280 @UnsupportedAppUsage getPidsForCommands(String[] cmds)1281 public static final native int[] getPidsForCommands(String[] cmds); 1282 1283 /** 1284 * Gets the total Pss value for a given process, in bytes. 1285 * 1286 * @param pid the process to the Pss for 1287 * @return the total Pss value for the given process in bytes, 1288 * or -1 if the value cannot be determined 1289 * @hide 1290 */ 1291 @UnsupportedAppUsage getPss(int pid)1292 public static final native long getPss(int pid); 1293 1294 /** @hide */ getRss(int pid)1295 public static final native long[] getRss(int pid); 1296 1297 /** 1298 * Specifies the outcome of having started a process. 1299 * @hide 1300 */ 1301 public static final class ProcessStartResult { 1302 /** 1303 * The PID of the newly started process. 1304 * Always >= 0. (If the start failed, an exception will have been thrown instead.) 1305 */ 1306 public int pid; 1307 1308 /** 1309 * True if the process was started with a wrapper attached. 1310 */ 1311 public boolean usingWrapper; 1312 } 1313 1314 /** 1315 * Kill all processes in a process group started for the given 1316 * pid. 1317 * @hide 1318 */ killProcessGroup(int uid, int pid)1319 public static final native int killProcessGroup(int uid, int pid); 1320 1321 /** 1322 * Remove all process groups. Expected to be called when ActivityManager 1323 * is restarted. 1324 * @hide 1325 */ removeAllProcessGroups()1326 public static final native void removeAllProcessGroups(); 1327 1328 /** 1329 * Check to see if a thread belongs to a given process. This may require 1330 * more permissions than apps generally have. 1331 * @return true if this thread belongs to a process 1332 * @hide 1333 */ isThreadInProcess(int tid, int pid)1334 public static final boolean isThreadInProcess(int tid, int pid) { 1335 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads(); 1336 try { 1337 if (Os.access("/proc/" + tid + "/task/" + pid, OsConstants.F_OK)) { 1338 return true; 1339 } else { 1340 return false; 1341 } 1342 } catch (Exception e) { 1343 return false; 1344 } finally { 1345 StrictMode.setThreadPolicy(oldPolicy); 1346 } 1347 1348 } 1349 1350 /** 1351 * Wait for the death of the given process. 1352 * 1353 * @param pid The process ID to be waited on 1354 * @param timeout The maximum time to wait in milliseconds, or -1 to wait forever 1355 * @hide 1356 */ waitForProcessDeath(int pid, int timeout)1357 public static void waitForProcessDeath(int pid, int timeout) 1358 throws InterruptedException, TimeoutException { 1359 boolean fallback = supportsPidFd(); 1360 if (!fallback) { 1361 FileDescriptor pidfd = null; 1362 try { 1363 final int fd = nativePidFdOpen(pid, 0); 1364 if (fd >= 0) { 1365 pidfd = new FileDescriptor(); 1366 pidfd.setInt$(fd); 1367 } else { 1368 fallback = true; 1369 } 1370 if (pidfd != null) { 1371 StructPollfd[] fds = new StructPollfd[] { 1372 new StructPollfd() 1373 }; 1374 fds[0].fd = pidfd; 1375 fds[0].events = (short) OsConstants.POLLIN; 1376 fds[0].revents = 0; 1377 fds[0].userData = null; 1378 int res = Os.poll(fds, timeout); 1379 if (res > 0) { 1380 return; 1381 } else if (res == 0) { 1382 throw new TimeoutException(); 1383 } else { 1384 // We should get an ErrnoException now 1385 } 1386 } 1387 } catch (ErrnoException e) { 1388 if (e.errno == OsConstants.EINTR) { 1389 throw new InterruptedException(); 1390 } 1391 fallback = true; 1392 } finally { 1393 if (pidfd != null) { 1394 IoUtils.closeQuietly(pidfd); 1395 } 1396 } 1397 } 1398 if (fallback) { 1399 boolean infinity = timeout < 0; 1400 long now = System.currentTimeMillis(); 1401 final long end = now + timeout; 1402 while (infinity || now < end) { 1403 try { 1404 Os.kill(pid, 0); 1405 } catch (ErrnoException e) { 1406 if (e.errno == OsConstants.ESRCH) { 1407 return; 1408 } 1409 } 1410 Thread.sleep(1); 1411 now = System.currentTimeMillis(); 1412 } 1413 } 1414 throw new TimeoutException(); 1415 } 1416 1417 /** 1418 * Determine whether the system supports pidfd APIs 1419 * 1420 * @return Returns true if the system supports pidfd APIs 1421 * @hide 1422 */ 1423 public static boolean supportsPidFd() { 1424 if (sPidFdSupported == PIDFD_UNKNOWN) { 1425 int fd = -1; 1426 try { 1427 fd = nativePidFdOpen(myPid(), 0); 1428 sPidFdSupported = PIDFD_SUPPORTED; 1429 } catch (ErrnoException e) { 1430 sPidFdSupported = e.errno != OsConstants.ENOSYS 1431 ? PIDFD_SUPPORTED : PIDFD_UNSUPPORTED; 1432 } finally { 1433 if (fd >= 0) { 1434 final FileDescriptor f = new FileDescriptor(); 1435 f.setInt$(fd); 1436 IoUtils.closeQuietly(f); 1437 } 1438 } 1439 } 1440 return sPidFdSupported == PIDFD_SUPPORTED; 1441 } 1442 1443 /** 1444 * Open process file descriptor for given pid. 1445 * 1446 * @param pid The process ID to open for 1447 * @param flags Reserved, unused now, must be 0 1448 * @return The process file descriptor for given pid 1449 * @throws IOException if it can't be opened 1450 * 1451 * @hide 1452 */ 1453 public static @Nullable FileDescriptor openPidFd(int pid, int flags) throws IOException { 1454 if (!supportsPidFd()) { 1455 return null; 1456 } 1457 if (flags != 0) { 1458 throw new IllegalArgumentException(); 1459 } 1460 try { 1461 FileDescriptor pidfd = new FileDescriptor(); 1462 pidfd.setInt$(nativePidFdOpen(pid, flags)); 1463 return pidfd; 1464 } catch (ErrnoException e) { 1465 IOException ex = new IOException(); 1466 ex.initCause(e); 1467 throw ex; 1468 } 1469 } 1470 1471 private static native int nativePidFdOpen(int pid, int flags) throws ErrnoException; 1472 } 1473