1 /* 2 * Copyright (C) 2011 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.annotation.AppIdInt; 20 import android.annotation.NonNull; 21 import android.annotation.Nullable; 22 import android.annotation.SystemApi; 23 import android.annotation.TestApi; 24 import android.annotation.UserIdInt; 25 import android.compat.annotation.UnsupportedAppUsage; 26 27 import java.io.PrintWriter; 28 import java.util.ArrayList; 29 import java.util.List; 30 31 /** 32 * Representation of a user on the device. 33 */ 34 public final class UserHandle implements Parcelable { 35 // NOTE: keep logic in sync with system/core/libcutils/multiuser.c 36 37 /** 38 * @hide Range of uids allocated for a user. 39 */ 40 @UnsupportedAppUsage 41 public static final int PER_USER_RANGE = 100000; 42 43 /** @hide A user id to indicate all users on the device */ 44 @UnsupportedAppUsage 45 @TestApi 46 public static final @UserIdInt int USER_ALL = -1; 47 48 /** @hide A user handle to indicate all users on the device */ 49 @SystemApi 50 public static final @NonNull UserHandle ALL = new UserHandle(USER_ALL); 51 52 /** @hide A user id to indicate the currently active user */ 53 @UnsupportedAppUsage 54 public static final @UserIdInt int USER_CURRENT = -2; 55 56 /** @hide A user handle to indicate the current user of the device */ 57 @SystemApi 58 public static final @NonNull UserHandle CURRENT = new UserHandle(USER_CURRENT); 59 60 /** @hide A user id to indicate that we would like to send to the current 61 * user, but if this is calling from a user process then we will send it 62 * to the caller's user instead of failing with a security exception */ 63 @UnsupportedAppUsage 64 public static final @UserIdInt int USER_CURRENT_OR_SELF = -3; 65 66 /** @hide A user handle to indicate that we would like to send to the current 67 * user, but if this is calling from a user process then we will send it 68 * to the caller's user instead of failing with a security exception */ 69 @UnsupportedAppUsage 70 public static final @NonNull UserHandle CURRENT_OR_SELF = new UserHandle(USER_CURRENT_OR_SELF); 71 72 /** @hide An undefined user id */ 73 @UnsupportedAppUsage 74 @TestApi 75 public static final @UserIdInt int USER_NULL = -10000; 76 77 private static final @NonNull UserHandle NULL = new UserHandle(USER_NULL); 78 79 /** 80 * @hide A user id constant to indicate the "owner" user of the device 81 * @deprecated Consider using either {@link UserHandle#USER_SYSTEM} constant or 82 * check the target user's flag {@link android.content.pm.UserInfo#isAdmin}. 83 */ 84 @UnsupportedAppUsage 85 @Deprecated 86 public static final @UserIdInt int USER_OWNER = 0; 87 88 /** 89 * @hide A user handle to indicate the primary/owner user of the device 90 * @deprecated Consider using either {@link UserHandle#SYSTEM} constant or 91 * check the target user's flag {@link android.content.pm.UserInfo#isAdmin}. 92 */ 93 @UnsupportedAppUsage 94 @Deprecated 95 public static final @NonNull UserHandle OWNER = new UserHandle(USER_OWNER); 96 97 /** @hide A user id constant to indicate the "system" user of the device */ 98 @UnsupportedAppUsage 99 @TestApi 100 public static final @UserIdInt int USER_SYSTEM = 0; 101 102 /** @hide A user serial constant to indicate the "system" user of the device */ 103 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553) 104 public static final int USER_SERIAL_SYSTEM = 0; 105 106 /** @hide A user handle to indicate the "system" user of the device */ 107 @SystemApi 108 public static final @NonNull UserHandle SYSTEM = new UserHandle(USER_SYSTEM); 109 110 /** 111 * @hide Enable multi-user related side effects. Set this to false if 112 * there are problems with single user use-cases. 113 */ 114 @UnsupportedAppUsage 115 public static final boolean MU_ENABLED = true; 116 117 /** @hide */ 118 @TestApi 119 public static final int MIN_SECONDARY_USER_ID = 10; 120 121 /** 122 * Arbitrary user handle cache size. We use the cache even when {@link #MU_ENABLED} is false 123 * anyway, so we can always assume in CTS that UserHandle.of(10) returns a cached instance 124 * even on non-multiuser devices. 125 */ 126 private static final int NUM_CACHED_USERS = 4; 127 128 private static final UserHandle[] CACHED_USER_INFOS = new UserHandle[NUM_CACHED_USERS]; 129 130 static { 131 // Not lazily initializing the cache, so that we can share them across processes. 132 // (We'll create them in zygote.) 133 for (int i = 0; i < CACHED_USER_INFOS.length; i++) { 134 CACHED_USER_INFOS[i] = new UserHandle(MIN_SECONDARY_USER_ID + i); 135 } 136 } 137 138 /** @hide */ 139 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553) 140 public static final int ERR_GID = -1; 141 /** @hide */ 142 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553) 143 public static final int AID_ROOT = android.os.Process.ROOT_UID; 144 /** @hide */ 145 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553) 146 public static final int AID_APP_START = android.os.Process.FIRST_APPLICATION_UID; 147 /** @hide */ 148 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553) 149 public static final int AID_APP_END = android.os.Process.LAST_APPLICATION_UID; 150 /** @hide */ 151 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553) 152 public static final int AID_SHARED_GID_START = android.os.Process.FIRST_SHARED_APPLICATION_GID; 153 /** @hide */ 154 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553) 155 public static final int AID_CACHE_GID_START = android.os.Process.FIRST_APPLICATION_CACHE_GID; 156 157 /** The userId represented by this UserHandle. */ 158 @UnsupportedAppUsage 159 final @UserIdInt int mHandle; 160 161 /** 162 * Checks to see if the user id is the same for the two uids, i.e., they belong to the same 163 * user. 164 * @hide 165 */ isSameUser(int uid1, int uid2)166 public static boolean isSameUser(int uid1, int uid2) { 167 return getUserId(uid1) == getUserId(uid2); 168 } 169 170 /** 171 * Checks to see if both uids are referring to the same app id, ignoring the user id part of the 172 * uids. 173 * @param uid1 uid to compare 174 * @param uid2 other uid to compare 175 * @return whether the appId is the same for both uids 176 * @hide 177 */ 178 @UnsupportedAppUsage isSameApp(int uid1, int uid2)179 public static boolean isSameApp(int uid1, int uid2) { 180 return getAppId(uid1) == getAppId(uid2); 181 } 182 183 /** 184 * Whether a UID is an "isolated" UID. 185 * @hide 186 */ 187 @UnsupportedAppUsage isIsolated(int uid)188 public static boolean isIsolated(int uid) { 189 if (uid > 0) { 190 return Process.isIsolated(uid); 191 } else { 192 return false; 193 } 194 } 195 196 /** 197 * Whether a UID belongs to a regular app. *Note* "Not a regular app" does not mean 198 * "it's system", because of isolated UIDs. Use {@link #isCore} for that. 199 * @hide 200 */ 201 @UnsupportedAppUsage 202 @TestApi isApp(int uid)203 public static boolean isApp(int uid) { 204 if (uid > 0) { 205 final int appId = getAppId(uid); 206 return appId >= Process.FIRST_APPLICATION_UID && appId <= Process.LAST_APPLICATION_UID; 207 } else { 208 return false; 209 } 210 } 211 212 /** 213 * Whether a UID belongs to a system core component or not. 214 * @hide 215 */ isCore(int uid)216 public static boolean isCore(int uid) { 217 if (uid >= 0) { 218 final int appId = getAppId(uid); 219 return appId < Process.FIRST_APPLICATION_UID; 220 } else { 221 return false; 222 } 223 } 224 225 /** 226 * Whether a UID belongs to a shared app gid. 227 * @hide 228 */ isSharedAppGid(int uid)229 public static boolean isSharedAppGid(int uid) { 230 return getAppIdFromSharedAppGid(uid) != -1; 231 } 232 233 /** 234 * Returns the user for a given uid. 235 * @param uid A uid for an application running in a particular user. 236 * @return A {@link UserHandle} for that user. 237 */ getUserHandleForUid(int uid)238 public static UserHandle getUserHandleForUid(int uid) { 239 return of(getUserId(uid)); 240 } 241 242 /** 243 * Returns the user id for a given uid. 244 * @hide 245 */ 246 @UnsupportedAppUsage 247 @TestApi getUserId(int uid)248 public static @UserIdInt int getUserId(int uid) { 249 if (MU_ENABLED) { 250 return uid / PER_USER_RANGE; 251 } else { 252 return UserHandle.USER_SYSTEM; 253 } 254 } 255 256 /** @hide */ 257 @UnsupportedAppUsage getCallingUserId()258 public static @UserIdInt int getCallingUserId() { 259 return getUserId(Binder.getCallingUid()); 260 } 261 262 /** @hide */ getCallingAppId()263 public static @AppIdInt int getCallingAppId() { 264 return getAppId(Binder.getCallingUid()); 265 } 266 267 /** @hide */ 268 @NonNull fromUserHandles(@onNull List<UserHandle> users)269 public static int[] fromUserHandles(@NonNull List<UserHandle> users) { 270 int[] userIds = new int[users.size()]; 271 for (int i = 0; i < userIds.length; ++i) { 272 userIds[i] = users.get(i).getIdentifier(); 273 } 274 return userIds; 275 } 276 277 /** @hide */ 278 @NonNull toUserHandles(@onNull int[] userIds)279 public static List<UserHandle> toUserHandles(@NonNull int[] userIds) { 280 List<UserHandle> users = new ArrayList<>(userIds.length); 281 for (int i = 0; i < userIds.length; ++i) { 282 users.add(UserHandle.of(userIds[i])); 283 } 284 return users; 285 } 286 287 /** @hide */ 288 @SystemApi of(@serIdInt int userId)289 public static UserHandle of(@UserIdInt int userId) { 290 if (userId == USER_SYSTEM) { 291 return SYSTEM; // Most common. 292 } 293 // These are sequential; so use a switch. Maybe they'll be optimized to a table lookup. 294 switch (userId) { 295 case USER_ALL: 296 return ALL; 297 298 case USER_CURRENT: 299 return CURRENT; 300 301 case USER_CURRENT_OR_SELF: 302 return CURRENT_OR_SELF; 303 } 304 if (userId >= MIN_SECONDARY_USER_ID 305 && userId < (MIN_SECONDARY_USER_ID + CACHED_USER_INFOS.length)) { 306 return CACHED_USER_INFOS[userId - MIN_SECONDARY_USER_ID]; 307 } 308 if (userId == USER_NULL) { // Not common. 309 return NULL; 310 } 311 return new UserHandle(userId); 312 } 313 314 /** 315 * Returns the uid that is composed from the userId and the appId. 316 * @hide 317 */ 318 @UnsupportedAppUsage 319 @TestApi getUid(@serIdInt int userId, @AppIdInt int appId)320 public static int getUid(@UserIdInt int userId, @AppIdInt int appId) { 321 if (MU_ENABLED) { 322 return userId * PER_USER_RANGE + (appId % PER_USER_RANGE); 323 } else { 324 return appId; 325 } 326 } 327 328 /** 329 * Returns the uid representing the given appId for this UserHandle. 330 * 331 * @param appId the AppId to compose the uid 332 * @return the uid representing the given appId for this UserHandle 333 * @hide 334 */ 335 @SystemApi getUid(@ppIdInt int appId)336 public int getUid(@AppIdInt int appId) { 337 return getUid(getIdentifier(), appId); 338 } 339 340 /** 341 * Returns the app id (or base uid) for a given uid, stripping out the user id from it. 342 * @hide 343 */ 344 @SystemApi getAppId(int uid)345 public static @AppIdInt int getAppId(int uid) { 346 return uid % PER_USER_RANGE; 347 } 348 349 /** 350 * Returns the gid shared between all apps with this userId. 351 * @hide 352 */ getUserGid(@serIdInt int userId)353 public static int getUserGid(@UserIdInt int userId) { 354 return getUid(userId, Process.SHARED_USER_GID); 355 } 356 357 /** @hide */ getSharedAppGid(int uid)358 public static int getSharedAppGid(int uid) { 359 return getSharedAppGid(getUserId(uid), getAppId(uid)); 360 } 361 362 /** @hide */ getSharedAppGid(@serIdInt int userId, @AppIdInt int appId)363 public static int getSharedAppGid(@UserIdInt int userId, @AppIdInt int appId) { 364 if (appId >= AID_APP_START && appId <= AID_APP_END) { 365 return (appId - AID_APP_START) + AID_SHARED_GID_START; 366 } else if (appId >= AID_ROOT && appId <= AID_APP_START) { 367 return appId; 368 } else { 369 return -1; 370 } 371 } 372 373 /** 374 * Returns the app id for a given shared app gid. Returns -1 if the ID is invalid. 375 * @hide 376 */ 377 @UnsupportedAppUsage getAppIdFromSharedAppGid(int gid)378 public static @AppIdInt int getAppIdFromSharedAppGid(int gid) { 379 final int appId = getAppId(gid) + Process.FIRST_APPLICATION_UID 380 - Process.FIRST_SHARED_APPLICATION_GID; 381 if (appId < 0 || appId >= Process.FIRST_SHARED_APPLICATION_GID) { 382 return -1; 383 } 384 return appId; 385 } 386 387 /** @hide */ getCacheAppGid(int uid)388 public static int getCacheAppGid(int uid) { 389 return getCacheAppGid(getUserId(uid), getAppId(uid)); 390 } 391 392 /** @hide */ getCacheAppGid(@serIdInt int userId, @AppIdInt int appId)393 public static int getCacheAppGid(@UserIdInt int userId, @AppIdInt int appId) { 394 if (appId >= AID_APP_START && appId <= AID_APP_END) { 395 return getUid(userId, (appId - AID_APP_START) + AID_CACHE_GID_START); 396 } else { 397 return -1; 398 } 399 } 400 401 /** 402 * Generate a text representation of the uid, breaking out its individual 403 * components -- user, app, isolated, etc. 404 * @hide 405 */ formatUid(StringBuilder sb, int uid)406 public static void formatUid(StringBuilder sb, int uid) { 407 if (uid < Process.FIRST_APPLICATION_UID) { 408 sb.append(uid); 409 } else { 410 sb.append('u'); 411 sb.append(getUserId(uid)); 412 final int appId = getAppId(uid); 413 if (isIsolated(appId)) { 414 if (appId > Process.FIRST_ISOLATED_UID) { 415 sb.append('i'); 416 sb.append(appId - Process.FIRST_ISOLATED_UID); 417 } else { 418 sb.append("ai"); 419 sb.append(appId - Process.FIRST_APP_ZYGOTE_ISOLATED_UID); 420 } 421 } else if (appId >= Process.FIRST_APPLICATION_UID) { 422 sb.append('a'); 423 sb.append(appId - Process.FIRST_APPLICATION_UID); 424 } else { 425 sb.append('s'); 426 sb.append(appId); 427 } 428 } 429 } 430 431 /** 432 * Generate a text representation of the uid, breaking out its individual 433 * components -- user, app, isolated, etc. 434 * 435 * @param uid The uid to format 436 * @return A string representing the UID with its individual components broken out 437 * @hide 438 */ 439 @SystemApi 440 @NonNull formatUid(int uid)441 public static String formatUid(int uid) { 442 StringBuilder sb = new StringBuilder(); 443 formatUid(sb, uid); 444 return sb.toString(); 445 } 446 447 /** 448 * Generate a text representation of the uid, breaking out its individual 449 * components -- user, app, isolated, etc. 450 * @hide 451 */ 452 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P) formatUid(PrintWriter pw, int uid)453 public static void formatUid(PrintWriter pw, int uid) { 454 if (uid < Process.FIRST_APPLICATION_UID) { 455 pw.print(uid); 456 } else { 457 pw.print('u'); 458 pw.print(getUserId(uid)); 459 final int appId = getAppId(uid); 460 if (isIsolated(appId)) { 461 if (appId > Process.FIRST_ISOLATED_UID) { 462 pw.print('i'); 463 pw.print(appId - Process.FIRST_ISOLATED_UID); 464 } else { 465 pw.print("ai"); 466 pw.print(appId - Process.FIRST_APP_ZYGOTE_ISOLATED_UID); 467 } 468 } else if (appId >= Process.FIRST_APPLICATION_UID) { 469 pw.print('a'); 470 pw.print(appId - Process.FIRST_APPLICATION_UID); 471 } else { 472 pw.print('s'); 473 pw.print(appId); 474 } 475 } 476 } 477 478 /** @hide */ parseUserArg(String arg)479 public static @UserIdInt int parseUserArg(String arg) { 480 int userId; 481 if ("all".equals(arg)) { 482 userId = UserHandle.USER_ALL; 483 } else if ("current".equals(arg) || "cur".equals(arg)) { 484 userId = UserHandle.USER_CURRENT; 485 } else { 486 try { 487 userId = Integer.parseInt(arg); 488 } catch (NumberFormatException e) { 489 throw new IllegalArgumentException("Bad user number: " + arg); 490 } 491 } 492 return userId; 493 } 494 495 /** 496 * Returns the user id of the current process 497 * @return user id of the current process 498 * @hide 499 */ 500 @SystemApi myUserId()501 public static @UserIdInt int myUserId() { 502 return getUserId(Process.myUid()); 503 } 504 505 /** 506 * Returns true if this UserHandle refers to the owner user; false otherwise. 507 * @return true if this UserHandle refers to the owner user; false otherwise. 508 * @hide 509 * @deprecated please use {@link #isSystem()} or check for 510 * {@link android.content.pm.UserInfo#isPrimary()} 511 * {@link android.content.pm.UserInfo#isAdmin()} based on your particular use case. 512 */ 513 @Deprecated 514 @SystemApi isOwner()515 public boolean isOwner() { 516 return this.equals(OWNER); 517 } 518 519 /** 520 * @return true if this UserHandle refers to the system user; false otherwise. 521 * @hide 522 */ 523 @SystemApi isSystem()524 public boolean isSystem() { 525 return this.equals(SYSTEM); 526 } 527 528 /** @hide */ 529 @UnsupportedAppUsage UserHandle(@serIdInt int userId)530 public UserHandle(@UserIdInt int userId) { 531 mHandle = userId; 532 } 533 534 /** 535 * Returns the userId stored in this UserHandle. 536 * @hide 537 */ 538 @SystemApi getIdentifier()539 public @UserIdInt int getIdentifier() { 540 return mHandle; 541 } 542 543 @Override toString()544 public String toString() { 545 return "UserHandle{" + mHandle + "}"; 546 } 547 548 @Override equals(@ullable Object obj)549 public boolean equals(@Nullable Object obj) { 550 try { 551 if (obj != null) { 552 UserHandle other = (UserHandle)obj; 553 return mHandle == other.mHandle; 554 } 555 } catch (ClassCastException ignore) { 556 } 557 return false; 558 } 559 560 @Override hashCode()561 public int hashCode() { 562 return mHandle; 563 } 564 describeContents()565 public int describeContents() { 566 return 0; 567 } 568 writeToParcel(Parcel out, int flags)569 public void writeToParcel(Parcel out, int flags) { 570 out.writeInt(mHandle); 571 } 572 573 /** 574 * Write a UserHandle to a Parcel, handling null pointers. Must be 575 * read with {@link #readFromParcel(Parcel)}. 576 * 577 * @param h The UserHandle to be written. 578 * @param out The Parcel in which the UserHandle will be placed. 579 * 580 * @see #readFromParcel(Parcel) 581 */ writeToParcel(UserHandle h, Parcel out)582 public static void writeToParcel(UserHandle h, Parcel out) { 583 if (h != null) { 584 h.writeToParcel(out, 0); 585 } else { 586 out.writeInt(USER_NULL); 587 } 588 } 589 590 /** 591 * Read a UserHandle from a Parcel that was previously written 592 * with {@link #writeToParcel(UserHandle, Parcel)}, returning either 593 * a null or new object as appropriate. 594 * 595 * @param in The Parcel from which to read the UserHandle 596 * @return Returns a new UserHandle matching the previously written 597 * object, or null if a null had been written. 598 * 599 * @see #writeToParcel(UserHandle, Parcel) 600 */ readFromParcel(Parcel in)601 public static UserHandle readFromParcel(Parcel in) { 602 int h = in.readInt(); 603 return h != USER_NULL ? new UserHandle(h) : null; 604 } 605 606 public static final @android.annotation.NonNull Parcelable.Creator<UserHandle> CREATOR 607 = new Parcelable.Creator<UserHandle>() { 608 public UserHandle createFromParcel(Parcel in) { 609 // Try to avoid allocation; use of() here. Keep this and the constructor below 610 // in sync. 611 return UserHandle.of(in.readInt()); 612 } 613 614 public UserHandle[] newArray(int size) { 615 return new UserHandle[size]; 616 } 617 }; 618 619 /** 620 * Instantiate a new UserHandle from the data in a Parcel that was 621 * previously written with {@link #writeToParcel(Parcel, int)}. Note that you 622 * must not use this with data written by 623 * {@link #writeToParcel(UserHandle, Parcel)} since it is not possible 624 * to handle a null UserHandle here. 625 * 626 * @param in The Parcel containing the previously written UserHandle, 627 * positioned at the location in the buffer where it was written. 628 */ UserHandle(Parcel in)629 public UserHandle(Parcel in) { 630 mHandle = in.readInt(); // Keep this and createFromParcel() in sync. 631 } 632 } 633