Ticket #384: test_exec.c

File test_exec.c, 2.0 kB (added by roustk@alumni.caltech.edu, 10 months ago)

Find uid of owner of this executable on Darwin (Mac OS X 10.4.11)

Line 
1 #include<sys/sysctl.h>
2 #include<sys/stat.h>
3 #include<unistd.h>
4 #include<stdio.h>
5 #include<stdlib.h>
6 #include<strings.h>
7
8 int main()
9 {
10   int mib[3];
11   int argmax;
12   size_t size;
13   char *args;
14   char *path,*tpath;
15   char *cp,*pp,*tcp,*tpp;
16   struct stat sb;
17
18   /* Find the longest possible command line and environment */
19   mib[0] = CTL_KERN;
20   mib[1] = KERN_ARGMAX;
21   size = sizeof(argmax);
22   sysctl(mib,2,&argmax,&size,NULL,0);
23
24   /* Create storage for the command line/environment */
25   args = (char *)malloc(argmax);
26   /* Create storage for the full path to the command */
27   path = (char *)malloc(argmax);
28
29   /* Collect the actual command line and environment for this process */
30   mib[0] = CTL_KERN;
31   mib[1] = KERN_PROCARGS2;
32   mib[2] = getpid();
33   size = (size_t)argmax;
34   sysctl(mib,3,args,&size,NULL,0);
35
36   /* args now contains: argc, command, argv, and environment variables */
37
38   /* Point at the beginning of the command, after argc */
39   cp = args + sizeof(int);
40   /* WARNING: per Darwin 10.4.10 start.s (in Csu-58),
41      "argc is always 4 bytes long, even in __ppc64__".
42      print.c (in ps.proj in adv_cmds-79.1) offsets by sizeof(int).
43      Trusting that ps is correct. */
44
45   tpath = path;
46   if(*cp!='/') {
47     /* a local path, so we need to learn PWD from env */
48     /* search through args until we find the "PWD=" entry */
49     for(pp=args;pp<args+size;pp++) {
50       if(*pp == '\0') {
51         tpp = pp+1;
52         if(*(tpp++) == 'P')
53           if(*(tpp++) == 'W')
54             if(*(tpp++) == 'D')
55               if(*(tpp++) == '=') {
56                 for(;*tpp!='\0';*(tpath++)=*(tpp++));
57                 *(tpath++)='/';
58                 break; }
59   } } }
60
61   /* copy the command to the path */
62   for(tcp=cp;*tcp!='\0';*(tpath++)=*(tcp++));
63   *(tpath) = '\0';
64
65   /* use stat() to collect file status for this program */
66   /* interested in st_uid -- the uid of the owner */
67   stat(path,&sb);
68
69   /* Dumb reporting (only need for stdio.h) */
70   printf("command: %s\n",path);
71   printf("file owner uid: %d\n",sb.st_uid);
72
73   /* Clean up the big stuff */
74   free(args);
75   free(path);
76
77   return 0;
78 }