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.SystemApi; 22 import android.annotation.TestApi; 23 import android.annotation.UserIdInt; 24 import android.compat.annotation.UnsupportedAppUsage; 25 26 import java.io.PrintWriter; 27 28 /** 29 * Representation of a user on the device. 30 */ 31 public final class UserHandle implements Parcelable { 32 // NOTE: keep logic in sync with system/core/libcutils/multiuser.c 33 34 /** 35 * @hide Range of uids allocated for a user. 36 */ 37 @UnsupportedAppUsage 38 public static final int PER_USER_RANGE = 100000; 39 40 /** @hide A user id to indicate all users on the device */ 41 @UnsupportedAppUsage 42 @TestApi 43 public static final @UserIdInt int USER_ALL = -1; 44 45 /** @hide A user handle to indicate all users on the device */ 46 @SystemApi 47 @TestApi 48 public static final @NonNull UserHandle ALL = new UserHandle(USER_ALL); 49 50 /** @hide A user id to indicate the currently active user */ 51 @UnsupportedAppUsage 52 public static final @UserIdInt int USER_CURRENT = -2; 53 54 /** @hide A user handle to indicate the current user of the device */ 55 @SystemApi 56 @TestApi 57 public static final @NonNull UserHandle CURRENT = new UserHandle(USER_CURRENT); 58 59 /** @hide A user id to indicate that we would like to send to the current 60 * user, but if this is calling from a user process then we will send it 61 * to the caller's user instead of failing with a security exception */ 62 @UnsupportedAppUsage 63 public static final @UserIdInt int USER_CURRENT_OR_SELF = -3; 64 65 /** @hide A user handle to indicate that we would like to send to the current 66 * user, but if this is calling from a user process then we will send it 67 * to the caller's user instead of failing with a security exception */ 68 @UnsupportedAppUsage 69 public static final @NonNull UserHandle CURRENT_OR_SELF = new UserHandle(USER_CURRENT_OR_SELF); 70 71 /** @hide An undefined user id */ 72 @UnsupportedAppUsage 73 @TestApi 74 public static final @UserIdInt int USER_NULL = -10000; 75 76 private static final @NonNull UserHandle NULL = new UserHandle(USER_NULL); 77 78 /** 79 * @hide A user id constant to indicate the "owner" user of the device 80 * @deprecated Consider using either {@link UserHandle#USER_SYSTEM} constant or 81 * check the target user's flag {@link android.content.pm.UserInfo#isAdmin}. 82 */ 83 @UnsupportedAppUsage 84 @Deprecated 85 public static final @UserIdInt int USER_OWNER = 0; 86 87 /** 88 * @hide A user handle to indicate the primary/owner user of the device 89 * @deprecated Consider using either {@link UserHandle#SYSTEM} constant or 90 * check the target user's flag {@link android.content.pm.UserInfo#isAdmin}. 91 */ 92 @UnsupportedAppUsage 93 @Deprecated 94 public static final @NonNull UserHandle OWNER = new UserHandle(USER_OWNER); 95 96 /** @hide A user id constant to indicate the "system" user of the device */ 97 @UnsupportedAppUsage 98 @TestApi 99 public static final @UserIdInt int USER_SYSTEM = 0; 100 101 /** @hide A user serial constant to indicate the "system" user of the device */ 102 @UnsupportedAppUsage 103 public static final int USER_SERIAL_SYSTEM = 0; 104 105 /** @hide A user handle to indicate the "system" user of the device */ 106 @SystemApi 107 @TestApi 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 140 public static final int ERR_GID = -1; 141 /** @hide */ 142 @UnsupportedAppUsage 143 public static final int AID_ROOT = android.os.Process.ROOT_UID; 144 /** @hide */ 145 @UnsupportedAppUsage 146 public static final int AID_APP_START = android.os.Process.FIRST_APPLICATION_UID; 147 /** @hide */ 148 @UnsupportedAppUsage 149 public static final int AID_APP_END = android.os.Process.LAST_APPLICATION_UID; 150 /** @hide */ 151 @UnsupportedAppUsage 152 public static final int AID_SHARED_GID_START = android.os.Process.FIRST_SHARED_APPLICATION_GID; 153 /** @hide */ 154 @UnsupportedAppUsage 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 @TestApi 269 @SystemApi of(@serIdInt int userId)270 public static UserHandle of(@UserIdInt int userId) { 271 if (userId == USER_SYSTEM) { 272 return SYSTEM; // Most common. 273 } 274 // These are sequential; so use a switch. Maybe they'll be optimized to a table lookup. 275 switch (userId) { 276 case USER_ALL: 277 return ALL; 278 279 case USER_CURRENT: 280 return CURRENT; 281 282 case USER_CURRENT_OR_SELF: 283 return CURRENT_OR_SELF; 284 } 285 if (userId >= MIN_SECONDARY_USER_ID 286 && userId < (MIN_SECONDARY_USER_ID + CACHED_USER_INFOS.length)) { 287 return CACHED_USER_INFOS[userId - MIN_SECONDARY_USER_ID]; 288 } 289 if (userId == USER_NULL) { // Not common. 290 return NULL; 291 } 292 return new UserHandle(userId); 293 } 294 295 /** 296 * Returns the uid that is composed from the userId and the appId. 297 * @hide 298 */ 299 @UnsupportedAppUsage 300 @TestApi getUid(@serIdInt int userId, @AppIdInt int appId)301 public static int getUid(@UserIdInt int userId, @AppIdInt int appId) { 302 if (MU_ENABLED) { 303 return userId * PER_USER_RANGE + (appId % PER_USER_RANGE); 304 } else { 305 return appId; 306 } 307 } 308 309 /** 310 * Returns the app id (or base uid) for a given uid, stripping out the user id from it. 311 * @hide 312 */ 313 @TestApi 314 @SystemApi getAppId(int uid)315 public static @AppIdInt int getAppId(int uid) { 316 return uid % PER_USER_RANGE; 317 } 318 319 /** 320 * Returns the gid shared between all apps with this userId. 321 * @hide 322 */ getUserGid(@serIdInt int userId)323 public static int getUserGid(@UserIdInt int userId) { 324 return getUid(userId, Process.SHARED_USER_GID); 325 } 326 327 /** @hide */ getSharedAppGid(int uid)328 public static int getSharedAppGid(int uid) { 329 return getSharedAppGid(getUserId(uid), getAppId(uid)); 330 } 331 332 /** @hide */ getSharedAppGid(@serIdInt int userId, @AppIdInt int appId)333 public static int getSharedAppGid(@UserIdInt int userId, @AppIdInt int appId) { 334 if (appId >= AID_APP_START && appId <= AID_APP_END) { 335 return (appId - AID_APP_START) + AID_SHARED_GID_START; 336 } else if (appId >= AID_ROOT && appId <= AID_APP_START) { 337 return appId; 338 } else { 339 return -1; 340 } 341 } 342 343 /** 344 * Returns the app id for a given shared app gid. Returns -1 if the ID is invalid. 345 * @hide 346 */ 347 @UnsupportedAppUsage getAppIdFromSharedAppGid(int gid)348 public static @AppIdInt int getAppIdFromSharedAppGid(int gid) { 349 final int appId = getAppId(gid) + Process.FIRST_APPLICATION_UID 350 - Process.FIRST_SHARED_APPLICATION_GID; 351 if (appId < 0 || appId >= Process.FIRST_SHARED_APPLICATION_GID) { 352 return -1; 353 } 354 return appId; 355 } 356 357 /** @hide */ getCacheAppGid(int uid)358 public static int getCacheAppGid(int uid) { 359 return getCacheAppGid(getUserId(uid), getAppId(uid)); 360 } 361 362 /** @hide */ getCacheAppGid(@serIdInt int userId, @AppIdInt int appId)363 public static int getCacheAppGid(@UserIdInt int userId, @AppIdInt int appId) { 364 if (appId >= AID_APP_START && appId <= AID_APP_END) { 365 return getUid(userId, (appId - AID_APP_START) + AID_CACHE_GID_START); 366 } else { 367 return -1; 368 } 369 } 370 371 /** 372 * Generate a text representation of the uid, breaking out its individual 373 * components -- user, app, isolated, etc. 374 * @hide 375 */ formatUid(StringBuilder sb, int uid)376 public static void formatUid(StringBuilder sb, int uid) { 377 if (uid < Process.FIRST_APPLICATION_UID) { 378 sb.append(uid); 379 } else { 380 sb.append('u'); 381 sb.append(getUserId(uid)); 382 final int appId = getAppId(uid); 383 if (isIsolated(appId)) { 384 if (appId > Process.FIRST_ISOLATED_UID) { 385 sb.append('i'); 386 sb.append(appId - Process.FIRST_ISOLATED_UID); 387 } else { 388 sb.append("ai"); 389 sb.append(appId - Process.FIRST_APP_ZYGOTE_ISOLATED_UID); 390 } 391 } else if (appId >= Process.FIRST_APPLICATION_UID) { 392 sb.append('a'); 393 sb.append(appId - Process.FIRST_APPLICATION_UID); 394 } else { 395 sb.append('s'); 396 sb.append(appId); 397 } 398 } 399 } 400 401 /** 402 * Generate a text representation of the uid, breaking out its individual 403 * components -- user, app, isolated, etc. 404 * 405 * @param uid The uid to format 406 * @return A string representing the UID with its individual components broken out 407 * @hide 408 */ 409 @SystemApi 410 @NonNull formatUid(int uid)411 public static String formatUid(int uid) { 412 StringBuilder sb = new StringBuilder(); 413 formatUid(sb, uid); 414 return sb.toString(); 415 } 416 417 /** 418 * Generate a text representation of the uid, breaking out its individual 419 * components -- user, app, isolated, etc. 420 * @hide 421 */ 422 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P) formatUid(PrintWriter pw, int uid)423 public static void formatUid(PrintWriter pw, int uid) { 424 if (uid < Process.FIRST_APPLICATION_UID) { 425 pw.print(uid); 426 } else { 427 pw.print('u'); 428 pw.print(getUserId(uid)); 429 final int appId = getAppId(uid); 430 if (isIsolated(appId)) { 431 if (appId > Process.FIRST_ISOLATED_UID) { 432 pw.print('i'); 433 pw.print(appId - Process.FIRST_ISOLATED_UID); 434 } else { 435 pw.print("ai"); 436 pw.print(appId - Process.FIRST_APP_ZYGOTE_ISOLATED_UID); 437 } 438 } else if (appId >= Process.FIRST_APPLICATION_UID) { 439 pw.print('a'); 440 pw.print(appId - Process.FIRST_APPLICATION_UID); 441 } else { 442 pw.print('s'); 443 pw.print(appId); 444 } 445 } 446 } 447 448 /** @hide */ parseUserArg(String arg)449 public static @UserIdInt int parseUserArg(String arg) { 450 int userId; 451 if ("all".equals(arg)) { 452 userId = UserHandle.USER_ALL; 453 } else if ("current".equals(arg) || "cur".equals(arg)) { 454 userId = UserHandle.USER_CURRENT; 455 } else { 456 try { 457 userId = Integer.parseInt(arg); 458 } catch (NumberFormatException e) { 459 throw new IllegalArgumentException("Bad user number: " + arg); 460 } 461 } 462 return userId; 463 } 464 465 /** 466 * Returns the user id of the current process 467 * @return user id of the current process 468 * @hide 469 */ 470 @SystemApi 471 @TestApi myUserId()472 public static @UserIdInt int myUserId() { 473 return getUserId(Process.myUid()); 474 } 475 476 /** 477 * Returns true if this UserHandle refers to the owner user; false otherwise. 478 * @return true if this UserHandle refers to the owner user; false otherwise. 479 * @hide 480 * @deprecated please use {@link #isSystem()} or check for 481 * {@link android.content.pm.UserInfo#isPrimary()} 482 * {@link android.content.pm.UserInfo#isAdmin()} based on your particular use case. 483 */ 484 @Deprecated 485 @SystemApi isOwner()486 public boolean isOwner() { 487 return this.equals(OWNER); 488 } 489 490 /** 491 * @return true if this UserHandle refers to the system user; false otherwise. 492 * @hide 493 */ 494 @SystemApi isSystem()495 public boolean isSystem() { 496 return this.equals(SYSTEM); 497 } 498 499 /** @hide */ 500 @UnsupportedAppUsage UserHandle(@serIdInt int userId)501 public UserHandle(@UserIdInt int userId) { 502 mHandle = userId; 503 } 504 505 /** 506 * Returns the userId stored in this UserHandle. 507 * @hide 508 */ 509 @SystemApi 510 @TestApi getIdentifier()511 public @UserIdInt int getIdentifier() { 512 return mHandle; 513 } 514 515 @Override toString()516 public String toString() { 517 return "UserHandle{" + mHandle + "}"; 518 } 519 520 @Override equals(Object obj)521 public boolean equals(Object obj) { 522 try { 523 if (obj != null) { 524 UserHandle other = (UserHandle)obj; 525 return mHandle == other.mHandle; 526 } 527 } catch (ClassCastException e) { 528 } 529 return false; 530 } 531 532 @Override hashCode()533 public int hashCode() { 534 return mHandle; 535 } 536 describeContents()537 public int describeContents() { 538 return 0; 539 } 540 writeToParcel(Parcel out, int flags)541 public void writeToParcel(Parcel out, int flags) { 542 out.writeInt(mHandle); 543 } 544 545 /** 546 * Write a UserHandle to a Parcel, handling null pointers. Must be 547 * read with {@link #readFromParcel(Parcel)}. 548 * 549 * @param h The UserHandle to be written. 550 * @param out The Parcel in which the UserHandle will be placed. 551 * 552 * @see #readFromParcel(Parcel) 553 */ writeToParcel(UserHandle h, Parcel out)554 public static void writeToParcel(UserHandle h, Parcel out) { 555 if (h != null) { 556 h.writeToParcel(out, 0); 557 } else { 558 out.writeInt(USER_NULL); 559 } 560 } 561 562 /** 563 * Read a UserHandle from a Parcel that was previously written 564 * with {@link #writeToParcel(UserHandle, Parcel)}, returning either 565 * a null or new object as appropriate. 566 * 567 * @param in The Parcel from which to read the UserHandle 568 * @return Returns a new UserHandle matching the previously written 569 * object, or null if a null had been written. 570 * 571 * @see #writeToParcel(UserHandle, Parcel) 572 */ readFromParcel(Parcel in)573 public static UserHandle readFromParcel(Parcel in) { 574 int h = in.readInt(); 575 return h != USER_NULL ? new UserHandle(h) : null; 576 } 577 578 public static final @android.annotation.NonNull Parcelable.Creator<UserHandle> CREATOR 579 = new Parcelable.Creator<UserHandle>() { 580 public UserHandle createFromParcel(Parcel in) { 581 // Try to avoid allocation; use of() here. Keep this and the constructor below 582 // in sync. 583 return UserHandle.of(in.readInt()); 584 } 585 586 public UserHandle[] newArray(int size) { 587 return new UserHandle[size]; 588 } 589 }; 590 591 /** 592 * Instantiate a new UserHandle from the data in a Parcel that was 593 * previously written with {@link #writeToParcel(Parcel, int)}. Note that you 594 * must not use this with data written by 595 * {@link #writeToParcel(UserHandle, Parcel)} since it is not possible 596 * to handle a null UserHandle here. 597 * 598 * @param in The Parcel containing the previously written UserHandle, 599 * positioned at the location in the buffer where it was written. 600 */ UserHandle(Parcel in)601 public UserHandle(Parcel in) { 602 mHandle = in.readInt(); // Keep this and createFromParcel() in sync. 603 } 604 } 605