Debian Codegraph @

core/java/android/os/UserHandle.java

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