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