Merge pull request #1668 from alexanderkyte/bug1856
[mono.git] / mono / utils / mono-proclib.c
1 /*
2  * Copyright 2008-2011 Novell Inc
3  * Copyright 2011 Xamarin Inc
4  */
5
6 #include "config.h"
7 #include "utils/mono-proclib.h"
8 #include "utils/mono-time.h"
9
10 #include <stdlib.h>
11 #include <stdio.h>
12 #include <string.h>
13 #include <fcntl.h>
14 #ifdef HAVE_UNISTD_H
15 #include <unistd.h>
16 #endif
17
18 #ifdef HOST_WIN32
19 #include <windows.h>
20 #include <process.h>
21 #endif
22
23 #if defined(_POSIX_VERSION)
24 #include <sys/errno.h>
25 #include <sys/param.h>
26 #ifdef HAVE_SYS_TYPES_H
27 #include <sys/types.h>
28 #endif
29 #ifdef HAVE_SYS_SYSCTL_H
30 #include <sys/sysctl.h>
31 #endif
32 #include <sys/resource.h>
33 #endif
34 #if defined(__APPLE__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__)
35 #include <sys/proc.h>
36 #if defined(__APPLE__)
37 #include <mach/mach.h>
38 #endif
39 #ifdef HAVE_SYS_USER_H
40 #include <sys/user.h>
41 #endif
42 #ifdef HAVE_STRUCT_KINFO_PROC_KP_PROC
43 #    define kinfo_pid_member kp_proc.p_pid
44 #    define kinfo_name_member kp_proc.p_comm
45 #elif defined(__OpenBSD__)
46 #    define kinfo_pid_member p_pid
47 #    define kinfo_name_member p_comm
48 #else
49 #define kinfo_pid_member ki_pid
50 #define kinfo_name_member ki_comm
51 #endif
52 #define USE_SYSCTL 1
53 #endif
54
55 /**
56  * mono_process_list:
57  * @size: a pointer to a location where the size of the returned array is stored
58  *
59  * Return an array of pid values for the processes currently running on the system.
60  * The size of the array is stored in @size.
61  */
62 gpointer*
63 mono_process_list (int *size)
64 {
65 #if USE_SYSCTL
66         int res, i;
67 #ifdef KERN_PROC2
68         int mib [6];
69         size_t data_len = sizeof (struct kinfo_proc2) * 400;
70         struct kinfo_proc2 *processes = malloc (data_len);
71 #else
72         int mib [4];
73         size_t data_len = sizeof (struct kinfo_proc) * 16;
74         struct kinfo_proc *processes;
75         int limit = 8;
76 #endif /* KERN_PROC2 */
77         void **buf = NULL;
78
79         if (size)
80                 *size = 0;
81
82 #ifdef KERN_PROC2
83         if (!processes)
84                 return NULL;
85
86         mib [0] = CTL_KERN;
87         mib [1] = KERN_PROC2;
88         mib [2] = KERN_PROC_ALL;
89         mib [3] = 0;
90         mib [4] = sizeof(struct kinfo_proc2);
91         mib [5] = 400; /* XXX */
92
93         res = sysctl (mib, 6, processes, &data_len, NULL, 0);
94         if (res < 0) {
95                 free (processes);
96                 return NULL;
97         }
98 #else
99         processes = NULL;
100         while (limit) {
101                 mib [0] = CTL_KERN;
102                 mib [1] = KERN_PROC;
103                 mib [2] = KERN_PROC_ALL;
104                 mib [3] = 0;
105
106                 res = sysctl (mib, 4, NULL, &data_len, NULL, 0);
107                 if (res)
108                         return NULL;
109                 processes = (struct kinfo_proc *) malloc (data_len);
110                 res = sysctl (mib, 4, processes, &data_len, NULL, 0);
111                 if (res < 0) {
112                         free (processes);
113                         if (errno != ENOMEM)
114                                 return NULL;
115                         limit --;
116                 } else {
117                         break;
118                 }
119         }
120 #endif /* KERN_PROC2 */
121
122 #ifdef KERN_PROC2
123         res = data_len/sizeof (struct kinfo_proc2);
124 #else
125         res = data_len/sizeof (struct kinfo_proc);
126 #endif /* KERN_PROC2 */
127         buf = (void **) g_realloc (buf, res * sizeof (void*));
128         for (i = 0; i < res; ++i)
129                 buf [i] = GINT_TO_POINTER (processes [i].kinfo_pid_member);
130         free (processes);
131         if (size)
132                 *size = res;
133         return buf;
134 #elif defined(__HAIKU__)
135         /* FIXME: Add back the code from 9185fcc305e43428d0f40f3ee37c8a405d41c9ae */
136         g_assert_not_reached ();
137         return NULL;
138 #else
139         const char *name;
140         void **buf = NULL;
141         int count = 0;
142         int i = 0;
143         GDir *dir = g_dir_open ("/proc/", 0, NULL);
144         if (!dir) {
145                 if (size)
146                         *size = 0;
147                 return NULL;
148         }
149         while ((name = g_dir_read_name (dir))) {
150                 int pid;
151                 char *nend;
152                 pid = strtol (name, &nend, 10);
153                 if (pid <= 0 || nend == name || *nend)
154                         continue;
155                 if (i >= count) {
156                         if (!count)
157                                 count = 16;
158                         else
159                                 count *= 2;
160                         buf = g_realloc (buf, count * sizeof (void*));
161                 }
162                 buf [i++] = GINT_TO_POINTER (pid);
163         }
164         g_dir_close (dir);
165         if (size)
166                 *size = i;
167         return buf;
168 #endif
169 }
170
171 static G_GNUC_UNUSED char*
172 get_pid_status_item_buf (int pid, const char *item, char *rbuf, int blen, MonoProcessError *error)
173 {
174         char buf [256];
175         char *s;
176         FILE *f;
177         int len = strlen (item);
178
179         g_snprintf (buf, sizeof (buf), "/proc/%d/status", pid);
180         f = fopen (buf, "r");
181         if (!f) {
182                 if (error)
183                         *error = MONO_PROCESS_ERROR_NOT_FOUND;
184                 return NULL;
185         }
186         while ((s = fgets (buf, blen, f))) {
187                 if (*item != *buf)
188                         continue;
189                 if (strncmp (buf, item, len))
190                         continue;
191                 s = buf + len;
192                 while (g_ascii_isspace (*s)) s++;
193                 if (*s++ != ':')
194                         continue;
195                 while (g_ascii_isspace (*s)) s++;
196                 fclose (f);
197                 len = strlen (s);
198                 strncpy (rbuf, s, MIN (len, blen));
199                 rbuf [MIN (len, blen) - 1] = 0;
200                 if (error)
201                         *error = MONO_PROCESS_ERROR_NONE;
202                 return rbuf;
203         }
204         fclose (f);
205         if (error)
206                 *error = MONO_PROCESS_ERROR_OTHER;
207         return NULL;
208 }
209
210 #if USE_SYSCTL
211
212 #ifdef KERN_PROC2
213 #define KINFO_PROC struct kinfo_proc2
214 #else
215 #define KINFO_PROC struct kinfo_proc
216 #endif
217
218 static gboolean
219 sysctl_kinfo_proc (gpointer pid, KINFO_PROC* processi)
220 {
221         int res;
222         size_t data_len = sizeof (KINFO_PROC);
223
224 #ifdef KERN_PROC2
225         int mib [6];
226         mib [0] = CTL_KERN;
227         mib [1] = KERN_PROC2;
228         mib [2] = KERN_PROC_PID;
229         mib [3] = GPOINTER_TO_UINT (pid);
230         mib [4] = sizeof(KINFO_PROC);
231         mib [5] = 400; /* XXX */
232
233         res = sysctl (mib, 6, processi, &data_len, NULL, 0);
234 #else
235         int mib [4];
236         mib [0] = CTL_KERN;
237         mib [1] = KERN_PROC;
238         mib [2] = KERN_PROC_PID;
239         mib [3] = GPOINTER_TO_UINT (pid);
240
241         res = sysctl (mib, 4, processi, &data_len, NULL, 0);
242 #endif /* KERN_PROC2 */
243
244         if (res < 0 || data_len != sizeof (KINFO_PROC))
245                 return FALSE;
246
247         return TRUE;
248 }
249 #endif /* USE_SYSCTL */
250
251 /**
252  * mono_process_get_name:
253  * @pid: pid of the process
254  * @buf: byte buffer where to store the name of the prcoess
255  * @len: size of the buffer @buf
256  *
257  * Return the name of the process identified by @pid, storing it
258  * inside @buf for a maximum of len bytes (including the terminating 0).
259  */
260 char*
261 mono_process_get_name (gpointer pid, char *buf, int len)
262 {
263 #if USE_SYSCTL
264         KINFO_PROC processi;
265
266         memset (buf, 0, len);
267
268         if (sysctl_kinfo_proc (pid, &processi))
269                 strncpy (buf, processi.kinfo_name_member, len - 1);
270
271         return buf;
272 #else
273         char fname [128];
274         FILE *file;
275         char *p;
276         int r;
277         sprintf (fname, "/proc/%d/cmdline", GPOINTER_TO_INT (pid));
278         buf [0] = 0;
279         file = fopen (fname, "r");
280         if (!file)
281                 return buf;
282         r = fread (buf, 1, len - 1, file);
283         fclose (file);
284         buf [r] = 0;
285         p = strrchr (buf, '/');
286         if (p)
287                 return p + 1;
288         if (r == 0) {
289                 return get_pid_status_item_buf (GPOINTER_TO_INT (pid), "Name", buf, len, NULL);
290         }
291         return buf;
292 #endif
293 }
294
295 void
296 mono_process_get_times (gpointer pid, gint64 *start_time, gint64 *user_time, gint64 *kernel_time)
297 {
298         if (user_time)
299                 *user_time = mono_process_get_data (pid, MONO_PROCESS_USER_TIME);
300
301         if (kernel_time)
302                 *kernel_time = mono_process_get_data (pid, MONO_PROCESS_SYSTEM_TIME);
303
304         if (start_time) {
305                 *start_time = 0;
306
307 #if USE_SYSCTL
308                 {
309                         KINFO_PROC processi;
310
311                         if (sysctl_kinfo_proc (pid, &processi))
312                                 *start_time = mono_100ns_datetime_from_timeval (processi.kp_proc.p_starttime);
313                 }
314 #endif
315
316                 if (*start_time == 0) {
317                         static guint64 boot_time = 0;
318                         if (!boot_time)
319                                 boot_time = mono_100ns_datetime () - ((guint64)mono_msec_ticks ()) * 10000;
320
321                         *start_time = boot_time + mono_process_get_data (pid, MONO_PROCESS_ELAPSED);
322                 }
323         }
324 }
325
326 /*
327  * /proc/pid/stat format:
328  * pid (cmdname) S 
329  *      [0] ppid pgid sid tty_nr tty_pgrp flags min_flt cmin_flt maj_flt cmaj_flt
330  *      [10] utime stime cutime cstime prio nice threads 0 start_time vsize
331  *      [20] rss rsslim start_code end_code start_stack esp eip pending blocked sigign
332  *      [30] sigcatch wchan 0 0 exit_signal cpu rt_prio policy
333  */
334
335 #define RET_ERROR(err) do {     \
336                 if (error) *error = (err);      \
337                 return 0;                       \
338         } while (0)
339
340 static gint64
341 get_process_stat_item (int pid, int pos, int sum, MonoProcessError *error)
342 {
343 #if defined(__APPLE__) 
344         double process_user_time = 0, process_system_time = 0;//, process_percent = 0;
345         task_t task;
346         struct task_basic_info t_info;
347         mach_msg_type_number_t t_info_count = TASK_BASIC_INFO_COUNT, th_count;
348         thread_array_t th_array;
349         size_t i;
350
351         if (pid == getpid ()) {
352                 /* task_for_pid () doesn't work on ios, even for the current process */
353                 task = mach_task_self ();
354         } else {
355                 if (task_for_pid (mach_task_self (), pid, &task) != KERN_SUCCESS)
356                         RET_ERROR (MONO_PROCESS_ERROR_NOT_FOUND);
357         }
358
359         if (task_info (task, TASK_BASIC_INFO, (task_info_t)&t_info, &t_info_count) != KERN_SUCCESS) {
360                 if (pid != getpid ())
361                         mach_port_deallocate (mach_task_self (), task);
362                 RET_ERROR (MONO_PROCESS_ERROR_OTHER);
363         }
364         
365         if (task_threads(task, &th_array, &th_count) != KERN_SUCCESS) {
366                 if (pid != getpid ())
367                         mach_port_deallocate (mach_task_self (), task);
368                 RET_ERROR (MONO_PROCESS_ERROR_OTHER);
369         }
370                 
371         for (i = 0; i < th_count; i++) {
372                 double thread_user_time, thread_system_time;//, thread_percent;
373                 
374                 struct thread_basic_info th_info;
375                 mach_msg_type_number_t th_info_count = THREAD_BASIC_INFO_COUNT;
376                 if (thread_info(th_array[i], THREAD_BASIC_INFO, (thread_info_t)&th_info, &th_info_count) == KERN_SUCCESS) {
377                         thread_user_time = th_info.user_time.seconds + th_info.user_time.microseconds / 1e6;
378                         thread_system_time = th_info.system_time.seconds + th_info.system_time.microseconds / 1e6;
379                         //thread_percent = (double)th_info.cpu_usage / TH_USAGE_SCALE;
380                         
381                         process_user_time += thread_user_time;
382                         process_system_time += thread_system_time;
383                         //process_percent += th_percent;
384                 }
385         }
386         
387         for (i = 0; i < th_count; i++)
388                 mach_port_deallocate(task, th_array[i]);
389
390         if (pid != getpid ())
391                 mach_port_deallocate (mach_task_self (), task);
392
393         process_user_time += t_info.user_time.seconds + t_info.user_time.microseconds / 1e6;
394         process_system_time += t_info.system_time.seconds + t_info.system_time.microseconds / 1e6;
395     
396         if (pos == 10 && sum == TRUE)
397                 return (gint64)((process_user_time + process_system_time) * 10000000);
398         else if (pos == 10)
399                 return (gint64)(process_user_time * 10000000);
400         else if (pos == 11)
401                 return (gint64)(process_system_time * 10000000);
402                 
403         return 0;
404 #else
405         char buf [512];
406         char *s, *end;
407         FILE *f;
408         int len, i;
409         gint64 value;
410
411         g_snprintf (buf, sizeof (buf), "/proc/%d/stat", pid);
412         f = fopen (buf, "r");
413         if (!f)
414                 RET_ERROR (MONO_PROCESS_ERROR_NOT_FOUND);
415         len = fread (buf, 1, sizeof (buf), f);
416         fclose (f);
417         if (len <= 0)
418                 RET_ERROR (MONO_PROCESS_ERROR_OTHER);
419         s = strchr (buf, ')');
420         if (!s)
421                 RET_ERROR (MONO_PROCESS_ERROR_OTHER);
422         s++;
423         while (g_ascii_isspace (*s)) s++;
424         if (!*s)
425                 RET_ERROR (MONO_PROCESS_ERROR_OTHER);
426         /* skip the status char */
427         while (*s && !g_ascii_isspace (*s)) s++;
428         if (!*s)
429                 RET_ERROR (MONO_PROCESS_ERROR_OTHER);
430         for (i = 0; i < pos; ++i) {
431                 while (g_ascii_isspace (*s)) s++;
432                 if (!*s)
433                         RET_ERROR (MONO_PROCESS_ERROR_OTHER);
434                 while (*s && !g_ascii_isspace (*s)) s++;
435                 if (!*s)
436                         RET_ERROR (MONO_PROCESS_ERROR_OTHER);
437         }
438         /* we are finally at the needed item */
439         value = strtoul (s, &end, 0);
440         /* add also the following value */
441         if (sum) {
442                 while (g_ascii_isspace (*s)) s++;
443                 if (!*s)
444                         RET_ERROR (MONO_PROCESS_ERROR_OTHER);
445                 value += strtoul (s, &end, 0);
446         }
447         if (error)
448                 *error = MONO_PROCESS_ERROR_NONE;
449         return value;
450 #endif
451 }
452
453 static int
454 get_user_hz (void)
455 {
456         static int user_hz = 0;
457         if (user_hz == 0) {
458 #ifdef _SC_CLK_TCK
459                 user_hz = sysconf (_SC_CLK_TCK);
460 #endif
461                 if (user_hz == 0)
462                         user_hz = 100;
463         }
464         return user_hz;
465 }
466
467 static gint64
468 get_process_stat_time (int pid, int pos, int sum, MonoProcessError *error)
469 {
470         gint64 val = get_process_stat_item (pid, pos, sum, error);
471 #if defined(__APPLE__)
472         return val;
473 #else
474         /* return 100ns ticks */
475         return (val * 10000000) / get_user_hz ();
476 #endif
477 }
478
479 static gint64
480 get_pid_status_item (int pid, const char *item, MonoProcessError *error, int multiplier)
481 {
482 #if defined(__APPLE__)
483         // ignore the multiplier
484         
485         gint64 ret;
486         task_t task;
487         struct task_basic_info t_info;
488         mach_msg_type_number_t th_count = TASK_BASIC_INFO_COUNT;
489
490         if (pid == getpid ()) {
491                 /* task_for_pid () doesn't work on ios, even for the current process */
492                 task = mach_task_self ();
493         } else {
494                 if (task_for_pid (mach_task_self (), pid, &task) != KERN_SUCCESS)
495                         RET_ERROR (MONO_PROCESS_ERROR_NOT_FOUND);
496         }
497         
498         if (task_info (task, TASK_BASIC_INFO, (task_info_t)&t_info, &th_count) != KERN_SUCCESS) {
499                 if (pid != getpid ())
500                         mach_port_deallocate (mach_task_self (), task);
501                 RET_ERROR (MONO_PROCESS_ERROR_OTHER);
502         }
503
504         if (strcmp (item, "VmRSS") == 0 || strcmp (item, "VmHWM") == 0 || strcmp (item, "VmData") == 0)
505                 ret = t_info.resident_size;
506         else if (strcmp (item, "VmSize") == 0 || strcmp (item, "VmPeak") == 0)
507                 ret = t_info.virtual_size;
508         else if (strcmp (item, "Threads") == 0)
509                 ret = th_count;
510         else
511                 ret = 0;
512
513         if (pid != getpid ())
514                 mach_port_deallocate (mach_task_self (), task);
515         
516         return ret;
517 #else
518         char buf [64];
519         char *s;
520
521         s = get_pid_status_item_buf (pid, item, buf, sizeof (buf), error);
522         if (s)
523                 return ((gint64) atol (s)) * multiplier;
524         return 0;
525 #endif
526 }
527
528 /**
529  * mono_process_get_data:
530  * @pid: pid of the process
531  * @data: description of data to return
532  *
533  * Return a data item of a process like user time, memory use etc,
534  * according to the @data argumet.
535  */
536 gint64
537 mono_process_get_data_with_error (gpointer pid, MonoProcessData data, MonoProcessError *error)
538 {
539         gint64 val;
540         int rpid = GPOINTER_TO_INT (pid);
541
542         if (error)
543                 *error = MONO_PROCESS_ERROR_OTHER;
544
545         switch (data) {
546         case MONO_PROCESS_NUM_THREADS:
547                 return get_pid_status_item (rpid, "Threads", error, 1);
548         case MONO_PROCESS_USER_TIME:
549                 return get_process_stat_time (rpid, 10, FALSE, error);
550         case MONO_PROCESS_SYSTEM_TIME:
551                 return get_process_stat_time (rpid, 11, FALSE, error);
552         case MONO_PROCESS_TOTAL_TIME:
553                 return get_process_stat_time (rpid, 10, TRUE, error);
554         case MONO_PROCESS_WORKING_SET:
555                 return get_pid_status_item (rpid, "VmRSS", error, 1024);
556         case MONO_PROCESS_WORKING_SET_PEAK:
557                 val = get_pid_status_item (rpid, "VmHWM", error, 1024);
558                 if (val == 0)
559                         val = get_pid_status_item (rpid, "VmRSS", error, 1024);
560                 return val;
561         case MONO_PROCESS_PRIVATE_BYTES:
562                 return get_pid_status_item (rpid, "VmData", error, 1024);
563         case MONO_PROCESS_VIRTUAL_BYTES:
564                 return get_pid_status_item (rpid, "VmSize", error, 1024);
565         case MONO_PROCESS_VIRTUAL_BYTES_PEAK:
566                 val = get_pid_status_item (rpid, "VmPeak", error, 1024);
567                 if (val == 0)
568                         val = get_pid_status_item (rpid, "VmSize", error, 1024);
569                 return val;
570         case MONO_PROCESS_FAULTS:
571                 return get_process_stat_item (rpid, 6, TRUE, error);
572         case MONO_PROCESS_ELAPSED:
573                 return get_process_stat_time (rpid, 18, FALSE, error);
574         case MONO_PROCESS_PPID:
575                 return get_process_stat_time (rpid, 0, FALSE, error);
576         case MONO_PROCESS_PAGED_BYTES:
577                 return get_pid_status_item (rpid, "VmSwap", error, 1024);
578
579                 /* Nothing yet */
580         case MONO_PROCESS_END:
581                 return 0;
582         }
583         return 0;
584 }
585
586 gint64
587 mono_process_get_data (gpointer pid, MonoProcessData data)
588 {
589         MonoProcessError error;
590         return mono_process_get_data_with_error (pid, data, &error);
591 }
592
593 int
594 mono_process_current_pid ()
595 {
596 #if defined(HAVE_UNISTD_H)
597         return (int) getpid ();
598 #elif defined(HOST_WIN32)
599         return (int) GetCurrentProcessId ();
600 #else
601 #error getpid
602 #endif
603 }
604
605 /**
606  * mono_cpu_count:
607  *
608  * Return the number of processors on the system.
609  */
610 int
611 mono_cpu_count (void)
612 {
613 #ifdef HOST_WIN32
614         SYSTEM_INFO info;
615         GetSystemInfo (&info);
616         return info.dwNumberOfProcessors;
617 #else
618         int count = 0;
619 #ifdef PLATFORM_ANDROID
620         /* Android tries really hard to save power by powering off CPUs on SMP phones which
621          * means the normal way to query cpu count returns a wrong value with userspace API.
622          * Instead we use /sys entries to query the actual hardware CPU count.
623          */
624         char buffer[8] = {'\0'};
625         int present = open ("/sys/devices/system/cpu/present", O_RDONLY);
626         /* Format of the /sys entry is a cpulist of indexes which in the case
627          * of present is always of the form "0-(n-1)" when there is more than
628          * 1 core, n being the number of CPU cores in the system. Otherwise
629          * the value is simply 0
630          */
631         if (present != -1 && read (present, (char*)buffer, sizeof (buffer)) > 3)
632                 count = strtol (((char*)buffer) + 2, NULL, 10);
633         if (present != -1)
634                 close (present);
635         if (count > 0)
636                 return count + 1;
637 #endif
638 #ifdef _SC_NPROCESSORS_CONF
639         count = sysconf (_SC_NPROCESSORS_CONF);
640         if (count > 0)
641                 return count;
642 #endif
643 #ifdef USE_SYSCTL
644         {
645                 int mib [2];
646                 size_t len = sizeof (int);
647                 mib [0] = CTL_HW;
648                 mib [1] = HW_NCPU;
649                 if (sysctl (mib, 2, &count, &len, NULL, 0) == 0)
650                         return count;
651         }
652 #endif
653 #endif
654         /* FIXME: warn */
655         return 1;
656 }
657
658 static void
659 get_cpu_times (int cpu_id, gint64 *user, gint64 *systemt, gint64 *irq, gint64 *sirq, gint64 *idle)
660 {
661         char buf [256];
662         char *s;
663         int hz = get_user_hz ();
664         guint64 user_ticks = 0, nice_ticks = 0, system_ticks = 0, idle_ticks = 0, irq_ticks = 0, sirq_ticks = 0;
665         FILE *f = fopen ("/proc/stat", "r");
666         if (!f)
667                 return;
668         if (cpu_id < 0)
669                 hz *= mono_cpu_count ();
670         while ((s = fgets (buf, sizeof (buf), f))) {
671                 char *data = NULL;
672                 if (cpu_id < 0 && strncmp (s, "cpu", 3) == 0 && g_ascii_isspace (s [3])) {
673                         data = s + 4;
674                 } else if (cpu_id >= 0 && strncmp (s, "cpu", 3) == 0 && strtol (s + 3, &data, 10) == cpu_id) {
675                         if (data == s + 3)
676                                 continue;
677                         data++;
678                 } else {
679                         continue;
680                 }
681                 
682                 user_ticks = strtoull (data, &data, 10);
683                 nice_ticks = strtoull (data, &data, 10);
684                 system_ticks = strtoull (data, &data, 10);
685                 idle_ticks = strtoull (data, &data, 10);
686                 /* iowait_ticks = strtoull (data, &data, 10); */
687                 irq_ticks = strtoull (data, &data, 10);
688                 sirq_ticks = strtoull (data, &data, 10);
689                 break;
690         }
691         fclose (f);
692
693         if (user)
694                 *user = (user_ticks + nice_ticks) * 10000000 / hz;
695         if (systemt)
696                 *systemt = (system_ticks) * 10000000 / hz;
697         if (irq)
698                 *irq = (irq_ticks) * 10000000 / hz;
699         if (sirq)
700                 *sirq = (sirq_ticks) * 10000000 / hz;
701         if (idle)
702                 *idle = (idle_ticks) * 10000000 / hz;
703 }
704
705 /**
706  * mono_cpu_get_data:
707  * @cpu_id: processor number or -1 to get a summary of all the processors
708  * @data: type of data to retrieve
709  *
710  * Get data about a processor on the system, like time spent in user space or idle time.
711  */
712 gint64
713 mono_cpu_get_data (int cpu_id, MonoCpuData data, MonoProcessError *error)
714 {
715         gint64 value = 0;
716
717         if (error)
718                 *error = MONO_PROCESS_ERROR_NONE;
719         switch (data) {
720         case MONO_CPU_USER_TIME:
721                 get_cpu_times (cpu_id, &value, NULL, NULL, NULL, NULL);
722                 break;
723         case MONO_CPU_PRIV_TIME:
724                 get_cpu_times (cpu_id, NULL, &value, NULL, NULL, NULL);
725                 break;
726         case MONO_CPU_INTR_TIME:
727                 get_cpu_times (cpu_id, NULL, NULL, &value, NULL, NULL);
728                 break;
729         case MONO_CPU_DCP_TIME:
730                 get_cpu_times (cpu_id, NULL, NULL, NULL, &value, NULL);
731                 break;
732         case MONO_CPU_IDLE_TIME:
733                 get_cpu_times (cpu_id, NULL, NULL, NULL, NULL, &value);
734                 break;
735
736         case MONO_CPU_END:
737                 /* Nothing yet */
738                 return 0;
739         }
740         return value;
741 }
742
743 int
744 mono_atexit (void (*func)(void))
745 {
746 #ifdef PLATFORM_ANDROID
747         /* Some versions of android libc doesn't define atexit () */
748         return 0;
749 #else
750         return atexit (func);
751 #endif
752 }
753
754 gint32
755 mono_cpu_usage (MonoCpuUsageState *prev)
756 {
757         gint32 cpu_usage = 0;
758         gint64 cpu_total_time;
759         gint64 cpu_busy_time;
760
761 #ifndef HOST_WIN32
762         struct rusage resource_usage;
763         gint64 current_time;
764         gint64 kernel_time;
765         gint64 user_time;
766
767         if (getrusage (RUSAGE_SELF, &resource_usage) == -1) {
768                 g_error ("getrusage() failed, errno is %d (%s)\n", errno, strerror (errno));
769                 return -1;
770         }
771
772         current_time = mono_100ns_ticks ();
773         kernel_time = resource_usage.ru_stime.tv_sec * 1000 * 1000 * 10 + resource_usage.ru_stime.tv_usec * 10;
774         user_time = resource_usage.ru_utime.tv_sec * 1000 * 1000 * 10 + resource_usage.ru_utime.tv_usec * 10;
775
776         cpu_busy_time = (user_time - (prev ? prev->user_time : 0)) + (kernel_time - (prev ? prev->kernel_time : 0));
777         cpu_total_time = (current_time - (prev ? prev->current_time : 0)) * mono_cpu_count ();
778
779         if (prev) {
780                 prev->kernel_time = kernel_time;
781                 prev->user_time = user_time;
782                 prev->current_time = current_time;
783         }
784 #else
785         guint64 idle_time;
786         guint64 kernel_time;
787         guint64 user_time;
788
789         if (!GetSystemTimes ((FILETIME*) &idle_time, (FILETIME*) &kernel_time, (FILETIME*) &user_time)) {
790                 g_error ("GetSystemTimes() failed, error code is %d\n", GetLastError ());
791                 return -1;
792         }
793
794         cpu_total_time = (gint64)((user_time - (prev ? prev->user_time : 0)) + (kernel_time - (prev ? prev->kernel_time : 0)));
795         cpu_busy_time = (gint64)(cpu_total_time - (idle_time - (prev ? prev->idle_time : 0)));
796
797         if (prev) {
798                 prev->idle_time = idle_time;
799                 prev->kernel_time = kernel_time;
800                 prev->user_time = user_time;
801         }
802 #endif
803
804         if (cpu_total_time > 0 && cpu_busy_time > 0)
805                 cpu_usage = (gint32)(cpu_busy_time * 100 / cpu_total_time);
806
807         g_assert (cpu_usage >= 0);
808         g_assert (cpu_usage <= 100);
809
810         return cpu_usage;
811 }