2010-06-15 Zoltan Varga <vargaz@gmail.com>
[mono.git] / mono / utils / mono-proclib.c
1 #include "config.h"
2 #include "utils/mono-proclib.h"
3
4 #include <stdlib.h>
5 #include <stdio.h>
6 #include <string.h>
7 #ifdef HAVE_UNISTD_H
8 #include <unistd.h>
9 #endif
10
11 #ifdef HOST_WIN32
12 #include <windows.h>
13 #endif
14
15 /* FIXME: bsds untested */
16 #if defined(__APPLE__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__)
17 #include <sys/param.h>
18 #include <sys/types.h>
19 #include <sys/sysctl.h>
20 #include <sys/proc.h>
21 #ifdef HAVE_SYS_USER_H
22 #include <sys/user.h>
23 #endif
24 #ifdef HAVE_STRUCT_KINFO_PROC_KP_PROC
25 #  ifdef KERN_PROC2
26 #    define kinfo_pid_member p_pid
27 #    define kinfo_name_member p_comm
28 #  else
29 #    define kinfo_pid_member kp_proc.p_pid
30 #    define kinfo_name_member kp_proc.p_comm
31 #  endif
32 #else
33 #define kinfo_pid_member ki_pid
34 #define kinfo_name_member ki_comm
35 #endif
36 #define USE_SYSCTL 1
37 #endif
38
39 /**
40  * mono_process_list:
41  * @size: a pointer to a location where the size of the returned array is stored
42  *
43  * Return an array of pid values for the processes currently running on the system.
44  * The size of the array is stored in @size.
45  */
46 gpointer*
47 mono_process_list (int *size)
48 {
49 #if USE_SYSCTL
50         int res, i;
51 #ifdef KERN_PROC2
52         int mib [6];
53         size_t data_len = sizeof (struct kinfo_proc2) * 400;
54         struct kinfo_proc2 *processes = malloc (data_len);
55 #else
56         int mib [4];
57         size_t data_len = sizeof (struct kinfo_proc) * 400;
58         struct kinfo_proc *processes = malloc (data_len);
59 #endif /* KERN_PROC2 */
60         void **buf = NULL;
61
62         if (size)
63                 *size = 0;
64         if (!processes)
65                 return NULL;
66
67 #ifdef KERN_PROC2
68         mib [0] = CTL_KERN;
69         mib [1] = KERN_PROC2;
70         mib [2] = KERN_PROC_ALL;
71         mib [3] = 0;
72         mib [4] = sizeof(struct kinfo_proc2);
73         mib [5] = 400; /* XXX */
74
75         res = sysctl (mib, 6, processes, &data_len, NULL, 0);
76 #else
77         mib [0] = CTL_KERN;
78         mib [1] = KERN_PROC;
79         mib [2] = KERN_PROC_ALL;
80         mib [3] = 0;
81         
82         res = sysctl (mib, 4, processes, &data_len, NULL, 0);
83 #endif /* KERN_PROC2 */
84
85         if (res < 0) {
86                 free (processes);
87                 return NULL;
88         }
89 #ifdef KERN_PROC2
90         res = data_len/sizeof (struct kinfo_proc2);
91 #else
92         res = data_len/sizeof (struct kinfo_proc);
93 #endif /* KERN_PROC2 */
94         buf = g_realloc (buf, res * sizeof (void*));
95         for (i = 0; i < res; ++i)
96                 buf [i] = GINT_TO_POINTER (processes [i].kinfo_pid_member);
97         free (processes);
98         if (size)
99                 *size = res;
100         return buf;
101 #else
102         const char *name;
103         void **buf = NULL;
104         int count = 0;
105         int i = 0;
106         GDir *dir = g_dir_open ("/proc/", 0, NULL);
107         if (!dir) {
108                 if (size)
109                         *size = 0;
110                 return NULL;
111         }
112         while ((name = g_dir_read_name (dir))) {
113                 int pid;
114                 char *nend;
115                 pid = strtol (name, &nend, 10);
116                 if (pid <= 0 || nend == name || *nend)
117                         continue;
118                 if (i >= count) {
119                         if (!count)
120                                 count = 16;
121                         else
122                                 count *= 2;
123                         buf = g_realloc (buf, count * sizeof (void*));
124                 }
125                 buf [i++] = GINT_TO_POINTER (pid);
126         }
127         g_dir_close (dir);
128         if (size)
129                 *size = i;
130         return buf;
131 #endif
132 }
133
134 static char*
135 get_pid_status_item_buf (int pid, const char *item, char *rbuf, int blen, MonoProcessError *error)
136 {
137         char buf [256];
138         char *s;
139         FILE *f;
140         int len = strlen (item);
141
142         g_snprintf (buf, sizeof (buf), "/proc/%d/status", pid);
143         f = fopen (buf, "r");
144         if (!f) {
145                 if (error)
146                         *error = MONO_PROCESS_ERROR_NOT_FOUND;
147                 return NULL;
148         }
149         while ((s = fgets (buf, blen, f))) {
150                 if (*item != *buf)
151                         continue;
152                 if (strncmp (buf, item, len))
153                         continue;
154                 s = buf + len;
155                 while (g_ascii_isspace (*s)) s++;
156                 if (*s++ != ':')
157                         continue;
158                 while (g_ascii_isspace (*s)) s++;
159                 fclose (f);
160                 len = strlen (s);
161                 strncpy (rbuf, s, MIN (len, blen));
162                 rbuf [MIN (len, blen) - 1] = 0;
163                 if (error)
164                         *error = MONO_PROCESS_ERROR_NONE;
165                 return rbuf;
166         }
167         fclose (f);
168         if (error)
169                 *error = MONO_PROCESS_ERROR_OTHER;
170         return NULL;
171 }
172
173 /**
174  * mono_process_get_name:
175  * @pid: pid of the process
176  * @buf: byte buffer where to store the name of the prcoess
177  * @len: size of the buffer @buf
178  *
179  * Return the name of the process identified by @pid, storing it
180  * inside @buf for a maximum of len bytes (including the terminating 0).
181  */
182 char*
183 mono_process_get_name (gpointer pid, char *buf, int len)
184 {
185 #if USE_SYSCTL
186         int res;
187 #ifdef KERN_PROC2
188         int mib [6];
189         size_t data_len = sizeof (struct kinfo_proc2);
190         struct kinfo_proc2 processi;
191 #else
192         int mib [4];
193         size_t data_len = sizeof (struct kinfo_proc);
194         struct kinfo_proc processi;
195 #endif /* KERN_PROC2 */
196
197         memset (buf, 0, len);
198
199 #ifdef KERN_PROC2
200         mib [0] = CTL_KERN;
201         mib [1] = KERN_PROC2;
202         mib [2] = KERN_PROC_PID;
203         mib [3] = GPOINTER_TO_UINT (pid);
204         mib [4] = sizeof(struct kinfo_proc2);
205         mib [5] = 400; /* XXX */
206
207         res = sysctl (mib, 6, &processi, &data_len, NULL, 0);
208
209         if (res < 0 || data_len != sizeof (struct kinfo_proc2)) {
210                 return buf;
211         }
212 #else
213         mib [0] = CTL_KERN;
214         mib [1] = KERN_PROC;
215         mib [2] = KERN_PROC_PID;
216         mib [3] = GPOINTER_TO_UINT (pid);
217         
218         res = sysctl (mib, 4, &processi, &data_len, NULL, 0);
219         if (res < 0 || data_len != sizeof (struct kinfo_proc)) {
220                 return buf;
221         }
222 #endif /* KERN_PROC2 */
223         strncpy (buf, processi.kinfo_name_member, len - 1);
224         return buf;
225 #else
226         char fname [128];
227         FILE *file;
228         char *p;
229         int r;
230         sprintf (fname, "/proc/%d/cmdline", GPOINTER_TO_INT (pid));
231         buf [0] = 0;
232         file = fopen (fname, "r");
233         if (!file)
234                 return buf;
235         r = fread (buf, 1, len - 1, file);
236         fclose (file);
237         buf [r] = 0;
238         p = strrchr (buf, '/');
239         if (p)
240                 return p + 1;
241         if (r == 0) {
242                 return get_pid_status_item_buf (GPOINTER_TO_INT (pid), "Name", buf, len, NULL);
243         }
244         return buf;
245 #endif
246 }
247
248 /*
249  * /proc/pid/stat format:
250  * pid (cmdname) S 
251  *      [0] ppid pgid sid tty_nr tty_pgrp flags min_flt cmin_flt maj_flt cmaj_flt
252  *      [10] utime stime cutime cstime prio nice threads 0 start_time vsize rss
253  *      [20] rss rsslim start_code end_code start_stack esp eip pending blocked sigign
254  *      [30] sigcatch wchan 0 0 exit_signal cpu rt_prio policy
255  */
256
257 #define RET_ERROR(err) do {     \
258                 if (error) *error = (err);      \
259                 return 0;                       \
260         } while (0)
261
262 static gint64
263 get_process_stat_item (int pid, int pos, int sum, MonoProcessError *error)
264 {
265         char buf [512];
266         char *s, *end;
267         FILE *f;
268         int len, i;
269         gint64 value;
270
271         g_snprintf (buf, sizeof (buf), "/proc/%d/stat", pid);
272         f = fopen (buf, "r");
273         if (!f)
274                 RET_ERROR (MONO_PROCESS_ERROR_NOT_FOUND);
275         len = fread (buf, 1, sizeof (buf), f);
276         fclose (f);
277         if (len <= 0)
278                 RET_ERROR (MONO_PROCESS_ERROR_OTHER);
279         s = strchr (buf, ')');
280         if (!s)
281                 RET_ERROR (MONO_PROCESS_ERROR_OTHER);
282         s++;
283         while (g_ascii_isspace (*s)) s++;
284         if (!*s)
285                 RET_ERROR (MONO_PROCESS_ERROR_OTHER);
286         /* skip the status char */
287         while (*s && !g_ascii_isspace (*s)) s++;
288         if (!*s)
289                 RET_ERROR (MONO_PROCESS_ERROR_OTHER);
290         for (i = 0; i < pos; ++i) {
291                 while (g_ascii_isspace (*s)) s++;
292                 if (!*s)
293                         RET_ERROR (MONO_PROCESS_ERROR_OTHER);
294                 while (*s && !g_ascii_isspace (*s)) s++;
295                 if (!*s)
296                         RET_ERROR (MONO_PROCESS_ERROR_OTHER);
297         }
298         /* we are finally at the needed item */
299         value = strtoul (s, &end, 0);
300         /* add also the following value */
301         if (sum) {
302                 while (g_ascii_isspace (*s)) s++;
303                 if (!*s)
304                         RET_ERROR (MONO_PROCESS_ERROR_OTHER);
305                 value += strtoul (s, &end, 0);
306         }
307         if (error)
308                 *error = MONO_PROCESS_ERROR_NONE;
309         return value;
310 }
311
312 static int
313 get_user_hz (void)
314 {
315         static int user_hz = 0;
316         if (user_hz == 0) {
317 #ifdef _SC_CLK_TCK
318                 user_hz = sysconf (_SC_CLK_TCK);
319 #endif
320                 if (user_hz == 0)
321                         user_hz = 100;
322         }
323         return user_hz;
324 }
325
326 static gint64
327 get_process_stat_time (int pid, int pos, int sum, MonoProcessError *error)
328 {
329         gint64 val = get_process_stat_item (pid, pos, sum, error);
330         /* return 100ns ticks */
331         return (val * 10000000) / get_user_hz ();
332 }
333
334 static gint64
335 get_pid_status_item (int pid, const char *item, MonoProcessError *error)
336 {
337         char buf [64];
338         char *s;
339
340         s = get_pid_status_item_buf (pid, item, buf, sizeof (buf), error);
341         if (s)
342                 return atoi (s);
343         return 0;
344 }
345
346 /**
347  * mono_process_get_data:
348  * @pid: pid of the process
349  * @data: description of data to return
350  *
351  * Return a data item of a process like user time, memory use etc,
352  * according to the @data argumet.
353  */
354 gint64
355 mono_process_get_data_with_error (gpointer pid, MonoProcessData data, MonoProcessError *error)
356 {
357         gint64 val;
358         int rpid = GPOINTER_TO_INT (pid);
359
360         if (error)
361                 *error = MONO_PROCESS_ERROR_OTHER;
362
363         switch (data) {
364         case MONO_PROCESS_NUM_THREADS:
365                 return get_pid_status_item (rpid, "Threads", error);
366         case MONO_PROCESS_USER_TIME:
367                 return get_process_stat_time (rpid, 10, FALSE, error);
368         case MONO_PROCESS_SYSTEM_TIME:
369                 return get_process_stat_time (rpid, 11, FALSE, error);
370         case MONO_PROCESS_TOTAL_TIME:
371                 return get_process_stat_time (rpid, 10, TRUE, error);
372         case MONO_PROCESS_WORKING_SET:
373                 return get_pid_status_item (rpid, "VmRSS", error) * 1024;
374         case MONO_PROCESS_WORKING_SET_PEAK:
375                 val = get_pid_status_item (rpid, "VmHWM", error) * 1024;
376                 if (val == 0)
377                         val = get_pid_status_item (rpid, "VmRSS", error) * 1024;
378                 return val;
379         case MONO_PROCESS_PRIVATE_BYTES:
380                 return get_pid_status_item (rpid, "VmData", error) * 1024;
381         case MONO_PROCESS_VIRTUAL_BYTES:
382                 return get_pid_status_item (rpid, "VmSize", error) * 1024;
383         case MONO_PROCESS_VIRTUAL_BYTES_PEAK:
384                 val = get_pid_status_item (rpid, "VmPeak", error) * 1024;
385                 if (val == 0)
386                         val = get_pid_status_item (rpid, "VmSize", error) * 1024;
387                 return val;
388         case MONO_PROCESS_FAULTS:
389                 return get_process_stat_item (rpid, 6, TRUE, error);
390         case MONO_PROCESS_ELAPSED:
391                 return get_process_stat_item (rpid, 18, FALSE, error) / get_user_hz ();
392         case MONO_PROCESS_PPID:
393                 return get_process_stat_time (rpid, 0, FALSE, error);
394
395                 /* Nothing yet */
396         case MONO_PROCESS_END:
397                 return 0;
398         }
399         return 0;
400 }
401
402 gint64
403 mono_process_get_data (gpointer pid, MonoProcessData data)
404 {
405         MonoProcessError error;
406         return mono_process_get_data_with_error (pid, data, &error);
407 }
408
409 /**
410  * mono_cpu_count:
411  *
412  * Return the number of processors on the system.
413  */
414 int
415 mono_cpu_count (void)
416 {
417         int count;
418 #ifdef _SC_NPROCESSORS_ONLN
419         count = sysconf (_SC_NPROCESSORS_ONLN);
420         if (count > 0)
421                 return count;
422 #endif
423 #ifdef USE_SYSCTL
424         {
425                 int mib [2];
426                 size_t len = sizeof (int);
427                 mib [0] = CTL_HW;
428                 mib [1] = HW_NCPU;
429                 if (sysctl (mib, 2, &count, &len, NULL, 0) == 0)
430                         return count;
431         }
432 #endif
433 #ifdef HOST_WIN32
434         {
435                 SYSTEM_INFO info;
436                 GetSystemInfo (&info);
437                 return info.dwNumberOfProcessors;
438         }
439 #endif
440         /* FIXME: warn */
441         return 1;
442 }
443
444 static void
445 get_cpu_times (int cpu_id, gint64 *user, gint64 *systemt, gint64 *irq, gint64 *sirq, gint64 *idle)
446 {
447         char buf [256];
448         char *s;
449         int hz = get_user_hz ();
450         long long unsigned int user_ticks, nice_ticks, system_ticks, idle_ticks, iowait_ticks, irq_ticks, sirq_ticks;
451         FILE *f = fopen ("/proc/stat", "r");
452         if (!f)
453                 return;
454         if (cpu_id < 0)
455                 hz *= mono_cpu_count ();
456         while ((s = fgets (buf, sizeof (buf), f))) {
457                 char *data = NULL;
458                 if (cpu_id < 0 && strncmp (s, "cpu", 3) == 0 && g_ascii_isspace (s [3])) {
459                         data = s + 4;
460                 } else if (cpu_id >= 0 && strncmp (s, "cpu", 3) == 0 && strtol (s + 3, &data, 10) == cpu_id) {
461                         if (data == s + 3)
462                                 continue;
463                         data++;
464                 } else {
465                         continue;
466                 }
467                 sscanf (data, "%Lu %Lu %Lu %Lu %Lu %Lu %Lu", &user_ticks, &nice_ticks, &system_ticks, &idle_ticks, &iowait_ticks, &irq_ticks, &sirq_ticks);
468         }
469         fclose (f);
470
471         if (user)
472                 *user = (user_ticks + nice_ticks) * 10000000 / hz;
473         if (systemt)
474                 *systemt = (system_ticks) * 10000000 / hz;
475         if (irq)
476                 *irq = (irq_ticks) * 10000000 / hz;
477         if (sirq)
478                 *sirq = (sirq_ticks) * 10000000 / hz;
479         if (idle)
480                 *idle = (idle_ticks) * 10000000 / hz;
481 }
482
483 /**
484  * mono_cpu_get_data:
485  * @cpu_id: processor number or -1 to get a summary of all the processors
486  * @data: type of data to retrieve
487  *
488  * Get data about a processor on the system, like time spent in user space or idle time.
489  */
490 gint64
491 mono_cpu_get_data (int cpu_id, MonoCpuData data, MonoProcessError *error)
492 {
493         gint64 value = 0;
494
495         if (error)
496                 *error = MONO_PROCESS_ERROR_NONE;
497         switch (data) {
498         case MONO_CPU_USER_TIME:
499                 get_cpu_times (cpu_id, &value, NULL, NULL, NULL, NULL);
500                 break;
501         case MONO_CPU_PRIV_TIME:
502                 get_cpu_times (cpu_id, NULL, &value, NULL, NULL, NULL);
503                 break;
504         case MONO_CPU_INTR_TIME:
505                 get_cpu_times (cpu_id, NULL, NULL, &value, NULL, NULL);
506                 break;
507         case MONO_CPU_DCP_TIME:
508                 get_cpu_times (cpu_id, NULL, NULL, NULL, &value, NULL);
509                 break;
510         case MONO_CPU_IDLE_TIME:
511                 get_cpu_times (cpu_id, NULL, NULL, NULL, NULL, &value);
512                 break;
513
514         case MONO_CPU_END:
515                 /* Nothing yet */
516                 return 0;
517         }
518         return value;
519 }
520