2

I want to get the UID of an application, I have the applications package name and I want it in C.

Are there any API that returns the UID related with given package in source? In what class and what are its requirements then?

auselen
  • 27,577
  • 7
  • 73
  • 114
Neji
  • 6,591
  • 5
  • 43
  • 66

3 Answers3

2

You can do this in Java with Process.myUid().

On native, you can use getuid(), when including unistd.h and sys/types.h.

If you want to get it for another application, use PackageManager and see this answer on SO.

In general read this Unix question about UIDs. and GIDs

Community
  • 1
  • 1
auselen
  • 27,577
  • 7
  • 73
  • 114
  • we have talked in past, i want to create rom that has root access only to my app and thats why i'm trying to update SU.c and want to add clause to check if the requesting UID is related with my app – Neji Sep 04 '13 at 12:30
  • @Neji http://developer.android.com/reference/android/Manifest.permission.html#FACTORY_TEST – auselen Sep 04 '13 at 12:35
1

You can refer to the system standard 'PS' implementation. The package name is the cmdline in procfs.

The complete code is at https://android.googlesource.com/platform/system/core/+/master/toolbox/ps.c

I think the code might be like:

iterate the proc/pid/cmdline find the pid first and then do something like this:

sprintf(statline, "/proc/%d/stat", pid);
struct stat stats;
stat(statline, &stats);
uid = stats.st_uid
Robin
  • 10,052
  • 6
  • 31
  • 52
  • what if i want to check the package name related with the UID – Neji Sep 04 '13 at 13:17
  • As I said, according to the default implementation of Android framework, the Zygote process will always set the /proc/pid/cmdline to the package name of the process. So, you can iterate the /proc/pid to find the target pid and then check the cmdline to find the package name. – Robin Sep 04 '13 at 13:41
1
pid_t pid;
char args[4096], path[4096];

uid = getuid();

snprintf(path, sizeof(path), "/proc/%u/cmdline", pid);
fd = open(path, O_RDONLY);
if (fd < 0) {
    return -1; 
}   
len = read(fd, args, sizeof(args));
err = errno;
close(fd);
if (len < 0 || len == sizeof(args)) {
    return -1; 
}   

printf("The package name is %s\n", args);
Kevin Liu
  • 1,603
  • 3
  • 11
  • 14
  • and what should be the actual content of path, I want to get UID from package name in C – Neji Oct 10 '13 at 09:26