[runtime] Fixed the build on Android by relying on header checking for system headers.
[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 = 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 = 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 /**
211  * mono_process_get_name:
212  * @pid: pid of the process
213  * @buf: byte buffer where to store the name of the prcoess
214  * @len: size of the buffer @buf
215  *
216  * Return the name of the process identified by @pid, storing it
217  * inside @buf for a maximum of len bytes (including the terminating 0).
218  */
219 char*
220 mono_process_get_name (gpointer pid, char *buf, int len)
221 {
222 #if USE_SYSCTL
223         int res;
224 #ifdef KERN_PROC2
225         int mib [6];
226         size_t data_len = sizeof (struct kinfo_proc2);
227         struct kinfo_proc2 processi;
228 #else
229         int mib [4];
230         size_t data_len = sizeof (struct kinfo_proc);
231         struct kinfo_proc processi;
232 #endif /* KERN_PROC2 */
233
234         memset (buf, 0, len);
235
236 #ifdef KERN_PROC2
237         mib [0] = CTL_KERN;
238         mib [1] = KERN_PROC2;
239         mib [2] = KERN_PROC_PID;
240         mib [3] = GPOINTER_TO_UINT (pid);
241         mib [4] = sizeof(struct kinfo_proc2);
242         mib [5] = 400; /* XXX */
243
244         res = sysctl (mib, 6, &processi, &data_len, NULL, 0);
245
246         if (res < 0 || data_len != sizeof (struct kinfo_proc2)) {
247                 return buf;
248         }
249 #else
250         mib [0] = CTL_KERN;
251         mib [1] = KERN_PROC;
252         mib [2] = KERN_PROC_PID;
253         mib [3] = GPOINTER_TO_UINT (pid);
254         
255         res = sysctl (mib, 4, &processi, &data_len, NULL, 0);
256         if (res < 0 || data_len != sizeof (struct kinfo_proc)) {
257                 return buf;
258         }
259 #endif /* KERN_PROC2 */
260         strncpy (buf, processi.kinfo_name_member, len - 1);
261         return buf;
262 #else
263         char fname [128];
264         FILE *file;
265         char *p;
266         int r;
267         sprintf (fname, "/proc/%d/cmdline", GPOINTER_TO_INT (pid));
268         buf [0] = 0;
269         file = fopen (fname, "r");
270         if (!file)
271                 return buf;
272         r = fread (buf, 1, len - 1, file);
273         fclose (file);
274         buf [r] = 0;
275         p = strrchr (buf, '/');
276         if (p)
277                 return p + 1;
278         if (r == 0) {
279                 return get_pid_status_item_buf (GPOINTER_TO_INT (pid), "Name", buf, len, NULL);
280         }
281         return buf;
282 #endif
283 }
284
285 /*
286  * /proc/pid/stat format:
287  * pid (cmdname) S 
288  *      [0] ppid pgid sid tty_nr tty_pgrp flags min_flt cmin_flt maj_flt cmaj_flt
289  *      [10] utime stime cutime cstime prio nice threads 0 start_time vsize rss
290  *      [20] rss rsslim start_code end_code start_stack esp eip pending blocked sigign
291  *      [30] sigcatch wchan 0 0 exit_signal cpu rt_prio policy
292  */
293
294 #define RET_ERROR(err) do {     \
295                 if (error) *error = (err);      \
296                 return 0;                       \
297         } while (0)
298
299 static gint64
300 get_process_stat_item (int pid, int pos, int sum, MonoProcessError *error)
301 {
302 #if defined(__APPLE__) 
303         double process_user_time = 0, process_system_time = 0;//, process_percent = 0;
304         task_t task;
305         struct task_basic_info t_info;
306         mach_msg_type_number_t t_info_count = TASK_BASIC_INFO_COUNT, th_count;
307         thread_array_t th_array;
308         size_t i;
309
310         if (task_for_pid(mach_task_self(), pid, &task) != KERN_SUCCESS)
311                 RET_ERROR (MONO_PROCESS_ERROR_NOT_FOUND);
312
313         if (task_info(task, TASK_BASIC_INFO, (task_info_t)&t_info, &t_info_count) != KERN_SUCCESS) {
314                 mach_port_deallocate (mach_task_self (), task);
315                 RET_ERROR (MONO_PROCESS_ERROR_OTHER);
316         }
317         
318         if (task_threads(task, &th_array, &th_count) != KERN_SUCCESS) {
319                 mach_port_deallocate (mach_task_self (), task);
320                 RET_ERROR (MONO_PROCESS_ERROR_OTHER);
321         }
322                 
323         for (i = 0; i < th_count; i++) {
324                 double thread_user_time, thread_system_time;//, thread_percent;
325                 
326                 struct thread_basic_info th_info;
327                 mach_msg_type_number_t th_info_count = THREAD_BASIC_INFO_COUNT;
328                 if (thread_info(th_array[i], THREAD_BASIC_INFO, (thread_info_t)&th_info, &th_info_count) == KERN_SUCCESS) {
329                         thread_user_time = th_info.user_time.seconds + th_info.user_time.microseconds / 1e6;
330                         thread_system_time = th_info.system_time.seconds + th_info.system_time.microseconds / 1e6;
331                         //thread_percent = (double)th_info.cpu_usage / TH_USAGE_SCALE;
332                         
333                         process_user_time += thread_user_time;
334                         process_system_time += thread_system_time;
335                         //process_percent += th_percent;
336                 }
337         }
338         
339         for (i = 0; i < th_count; i++)
340                 mach_port_deallocate(task, th_array[i]);
341
342         mach_port_deallocate (mach_task_self (), task);
343
344         process_user_time += t_info.user_time.seconds + t_info.user_time.microseconds / 1e6;
345         process_system_time += t_info.system_time.seconds + t_info.system_time.microseconds / 1e6;
346     
347         if (pos == 10 && sum == TRUE)
348                 return (gint64)((process_user_time + process_system_time) * 10000000);
349         else if (pos == 10)
350                 return (gint64)(process_user_time * 10000000);
351         else if (pos == 11)
352                 return (gint64)(process_system_time * 10000000);
353                 
354         return 0;
355 #else
356         char buf [512];
357         char *s, *end;
358         FILE *f;
359         int len, i;
360         gint64 value;
361
362         g_snprintf (buf, sizeof (buf), "/proc/%d/stat", pid);
363         f = fopen (buf, "r");
364         if (!f)
365                 RET_ERROR (MONO_PROCESS_ERROR_NOT_FOUND);
366         len = fread (buf, 1, sizeof (buf), f);
367         fclose (f);
368         if (len <= 0)
369                 RET_ERROR (MONO_PROCESS_ERROR_OTHER);
370         s = strchr (buf, ')');
371         if (!s)
372                 RET_ERROR (MONO_PROCESS_ERROR_OTHER);
373         s++;
374         while (g_ascii_isspace (*s)) s++;
375         if (!*s)
376                 RET_ERROR (MONO_PROCESS_ERROR_OTHER);
377         /* skip the status char */
378         while (*s && !g_ascii_isspace (*s)) s++;
379         if (!*s)
380                 RET_ERROR (MONO_PROCESS_ERROR_OTHER);
381         for (i = 0; i < pos; ++i) {
382                 while (g_ascii_isspace (*s)) s++;
383                 if (!*s)
384                         RET_ERROR (MONO_PROCESS_ERROR_OTHER);
385                 while (*s && !g_ascii_isspace (*s)) s++;
386                 if (!*s)
387                         RET_ERROR (MONO_PROCESS_ERROR_OTHER);
388         }
389         /* we are finally at the needed item */
390         value = strtoul (s, &end, 0);
391         /* add also the following value */
392         if (sum) {
393                 while (g_ascii_isspace (*s)) s++;
394                 if (!*s)
395                         RET_ERROR (MONO_PROCESS_ERROR_OTHER);
396                 value += strtoul (s, &end, 0);
397         }
398         if (error)
399                 *error = MONO_PROCESS_ERROR_NONE;
400         return value;
401 #endif
402 }
403
404 static int
405 get_user_hz (void)
406 {
407         static int user_hz = 0;
408         if (user_hz == 0) {
409 #ifdef _SC_CLK_TCK
410                 user_hz = sysconf (_SC_CLK_TCK);
411 #endif
412                 if (user_hz == 0)
413                         user_hz = 100;
414         }
415         return user_hz;
416 }
417
418 static gint64
419 get_process_stat_time (int pid, int pos, int sum, MonoProcessError *error)
420 {
421         gint64 val = get_process_stat_item (pid, pos, sum, error);
422 #if defined(__APPLE__)
423         return val;
424 #else
425         /* return 100ns ticks */
426         return (val * 10000000) / get_user_hz ();
427 #endif
428 }
429
430 static gint64
431 get_pid_status_item (int pid, const char *item, MonoProcessError *error, int multiplier)
432 {
433 #if defined(__APPLE__)
434         // ignore the multiplier
435         
436         gint64 ret;
437         task_t task;
438         struct task_basic_info t_info;
439         mach_msg_type_number_t th_count = TASK_BASIC_INFO_COUNT;
440
441         if (pid == getpid ()) {
442                 /* task_for_pid () doesn't work on ios, even for the current process */
443                 task = mach_task_self ();
444         } else {
445                 if (task_for_pid (mach_task_self (), pid, &task) != KERN_SUCCESS)
446                         RET_ERROR (MONO_PROCESS_ERROR_NOT_FOUND);
447         }
448         
449         if (task_info (task, TASK_BASIC_INFO, (task_info_t)&t_info, &th_count) != KERN_SUCCESS) {
450                 if (pid != getpid ())
451                         mach_port_deallocate (mach_task_self (), task);
452                 RET_ERROR (MONO_PROCESS_ERROR_OTHER);
453         }
454
455         if (strcmp (item, "VmRSS") == 0 || strcmp (item, "VmHWM") == 0 || strcmp (item, "VmData") == 0)
456                 ret = t_info.resident_size;
457         else if (strcmp (item, "VmSize") == 0 || strcmp (item, "VmPeak") == 0)
458                 ret = t_info.virtual_size;
459         else if (strcmp (item, "Threads") == 0)
460                 ret = th_count;
461         else
462                 ret = 0;
463
464         if (pid != getpid ())
465                 mach_port_deallocate (mach_task_self (), task);
466         
467         return ret;
468 #else
469         char buf [64];
470         char *s;
471
472         s = get_pid_status_item_buf (pid, item, buf, sizeof (buf), error);
473         if (s)
474                 return ((gint64) atol (s)) * multiplier;
475         return 0;
476 #endif
477 }
478
479 /**
480  * mono_process_get_data:
481  * @pid: pid of the process
482  * @data: description of data to return
483  *
484  * Return a data item of a process like user time, memory use etc,
485  * according to the @data argumet.
486  */
487 gint64
488 mono_process_get_data_with_error (gpointer pid, MonoProcessData data, MonoProcessError *error)
489 {
490         gint64 val;
491         int rpid = GPOINTER_TO_INT (pid);
492
493         if (error)
494                 *error = MONO_PROCESS_ERROR_OTHER;
495
496         switch (data) {
497         case MONO_PROCESS_NUM_THREADS:
498                 return get_pid_status_item (rpid, "Threads", error, 1);
499         case MONO_PROCESS_USER_TIME:
500                 return get_process_stat_time (rpid, 10, FALSE, error);
501         case MONO_PROCESS_SYSTEM_TIME:
502                 return get_process_stat_time (rpid, 11, FALSE, error);
503         case MONO_PROCESS_TOTAL_TIME:
504                 return get_process_stat_time (rpid, 10, TRUE, error);
505         case MONO_PROCESS_WORKING_SET:
506                 return get_pid_status_item (rpid, "VmRSS", error, 1024);
507         case MONO_PROCESS_WORKING_SET_PEAK:
508                 val = get_pid_status_item (rpid, "VmHWM", error, 1024);
509                 if (val == 0)
510                         val = get_pid_status_item (rpid, "VmRSS", error, 1024);
511                 return val;
512         case MONO_PROCESS_PRIVATE_BYTES:
513                 return get_pid_status_item (rpid, "VmData", error, 1024);
514         case MONO_PROCESS_VIRTUAL_BYTES:
515                 return get_pid_status_item (rpid, "VmSize", error, 1024);
516         case MONO_PROCESS_VIRTUAL_BYTES_PEAK:
517                 val = get_pid_status_item (rpid, "VmPeak", error, 1024);
518                 if (val == 0)
519                         val = get_pid_status_item (rpid, "VmSize", error, 1024);
520                 return val;
521         case MONO_PROCESS_FAULTS:
522                 return get_process_stat_item (rpid, 6, TRUE, error);
523         case MONO_PROCESS_ELAPSED:
524                 return get_process_stat_item (rpid, 18, FALSE, error) / get_user_hz ();
525         case MONO_PROCESS_PPID:
526                 return get_process_stat_time (rpid, 0, FALSE, error);
527         case MONO_PROCESS_PAGED_BYTES:
528                 return get_pid_status_item (rpid, "VmSwap", error, 1024);
529
530                 /* Nothing yet */
531         case MONO_PROCESS_END:
532                 return 0;
533         }
534         return 0;
535 }
536
537 gint64
538 mono_process_get_data (gpointer pid, MonoProcessData data)
539 {
540         MonoProcessError error;
541         return mono_process_get_data_with_error (pid, data, &error);
542 }
543
544 int
545 mono_process_current_pid ()
546 {
547 #if defined(HAVE_UNISTD_H)
548         return (int) getpid ();
549 #elif defined(HOST_WIN32)
550         return (int) GetCurrentProcessId ();
551 #else
552 #error getpid
553 #endif
554 }
555
556 /**
557  * mono_cpu_count:
558  *
559  * Return the number of processors on the system.
560  */
561 int
562 mono_cpu_count (void)
563 {
564         int count = 0;
565 #ifdef PLATFORM_ANDROID
566         /* Android tries really hard to save power by powering off CPUs on SMP phones which
567          * means the normal way to query cpu count returns a wrong value with userspace API.
568          * Instead we use /sys entries to query the actual hardware CPU count.
569          */
570         char buffer[8] = {'\0'};
571         int present = open ("/sys/devices/system/cpu/present", O_RDONLY);
572         /* Format of the /sys entry is a cpulist of indexes which in the case
573          * of present is always of the form "0-(n-1)" when there is more than
574          * 1 core, n being the number of CPU cores in the system. Otherwise
575          * the value is simply 0
576          */
577         if (present != -1 && read (present, (char*)buffer, sizeof (buffer)) > 3)
578                 count = strtol (((char*)buffer) + 2, NULL, 10);
579         if (present != -1)
580                 close (present);
581         if (count > 0)
582                 return count + 1;
583 #endif
584 #ifdef _SC_NPROCESSORS_ONLN
585         count = sysconf (_SC_NPROCESSORS_ONLN);
586         if (count > 0)
587                 return count;
588 #endif
589 #ifdef USE_SYSCTL
590         {
591                 int mib [2];
592                 size_t len = sizeof (int);
593                 mib [0] = CTL_HW;
594                 mib [1] = HW_NCPU;
595                 if (sysctl (mib, 2, &count, &len, NULL, 0) == 0)
596                         return count;
597         }
598 #endif
599 #ifdef HOST_WIN32
600         {
601                 SYSTEM_INFO info;
602                 GetSystemInfo (&info);
603                 return info.dwNumberOfProcessors;
604         }
605 #endif
606         /* FIXME: warn */
607         return 1;
608 }
609
610 static void
611 get_cpu_times (int cpu_id, gint64 *user, gint64 *systemt, gint64 *irq, gint64 *sirq, gint64 *idle)
612 {
613         char buf [256];
614         char *s;
615         int hz = get_user_hz ();
616         guint64 user_ticks = 0, nice_ticks = 0, system_ticks = 0, idle_ticks = 0, irq_ticks = 0, sirq_ticks = 0;
617         FILE *f = fopen ("/proc/stat", "r");
618         if (!f)
619                 return;
620         if (cpu_id < 0)
621                 hz *= mono_cpu_count ();
622         while ((s = fgets (buf, sizeof (buf), f))) {
623                 char *data = NULL;
624                 if (cpu_id < 0 && strncmp (s, "cpu", 3) == 0 && g_ascii_isspace (s [3])) {
625                         data = s + 4;
626                 } else if (cpu_id >= 0 && strncmp (s, "cpu", 3) == 0 && strtol (s + 3, &data, 10) == cpu_id) {
627                         if (data == s + 3)
628                                 continue;
629                         data++;
630                 } else {
631                         continue;
632                 }
633                 
634                 user_ticks = strtoull (data, &data, 10);
635                 nice_ticks = strtoull (data, &data, 10);
636                 system_ticks = strtoull (data, &data, 10);
637                 idle_ticks = strtoull (data, &data, 10);
638                 /* iowait_ticks = strtoull (data, &data, 10); */
639                 irq_ticks = strtoull (data, &data, 10);
640                 sirq_ticks = strtoull (data, &data, 10);
641                 break;
642         }
643         fclose (f);
644
645         if (user)
646                 *user = (user_ticks + nice_ticks) * 10000000 / hz;
647         if (systemt)
648                 *systemt = (system_ticks) * 10000000 / hz;
649         if (irq)
650                 *irq = (irq_ticks) * 10000000 / hz;
651         if (sirq)
652                 *sirq = (sirq_ticks) * 10000000 / hz;
653         if (idle)
654                 *idle = (idle_ticks) * 10000000 / hz;
655 }
656
657 /**
658  * mono_cpu_get_data:
659  * @cpu_id: processor number or -1 to get a summary of all the processors
660  * @data: type of data to retrieve
661  *
662  * Get data about a processor on the system, like time spent in user space or idle time.
663  */
664 gint64
665 mono_cpu_get_data (int cpu_id, MonoCpuData data, MonoProcessError *error)
666 {
667         gint64 value = 0;
668
669         if (error)
670                 *error = MONO_PROCESS_ERROR_NONE;
671         switch (data) {
672         case MONO_CPU_USER_TIME:
673                 get_cpu_times (cpu_id, &value, NULL, NULL, NULL, NULL);
674                 break;
675         case MONO_CPU_PRIV_TIME:
676                 get_cpu_times (cpu_id, NULL, &value, NULL, NULL, NULL);
677                 break;
678         case MONO_CPU_INTR_TIME:
679                 get_cpu_times (cpu_id, NULL, NULL, &value, NULL, NULL);
680                 break;
681         case MONO_CPU_DCP_TIME:
682                 get_cpu_times (cpu_id, NULL, NULL, NULL, &value, NULL);
683                 break;
684         case MONO_CPU_IDLE_TIME:
685                 get_cpu_times (cpu_id, NULL, NULL, NULL, NULL, &value);
686                 break;
687
688         case MONO_CPU_END:
689                 /* Nothing yet */
690                 return 0;
691         }
692         return value;
693 }
694
695 int
696 mono_atexit (void (*func)(void))
697 {
698 #ifdef PLATFORM_ANDROID
699         /* Some versions of android libc doesn't define atexit () */
700         return 0;
701 #else
702         return atexit (func);
703 #endif
704 }
705
706 gint32
707 mono_cpu_usage (MonoCpuUsageState *prev)
708 {
709         gint32 cpu_usage = 0;
710         gint64 cpu_total_time;
711         gint64 cpu_busy_time;
712
713 #ifndef HOST_WIN32
714         struct rusage resource_usage;
715         gint64 current_time;
716         gint64 kernel_time;
717         gint64 user_time;
718
719         if (getrusage (RUSAGE_SELF, &resource_usage) == -1) {
720                 g_error ("getrusage() failed, errno is %d (%s)\n", errno, strerror (errno));
721                 return -1;
722         }
723
724         current_time = mono_100ns_ticks ();
725         kernel_time = resource_usage.ru_stime.tv_sec * 1000 * 1000 * 10 + resource_usage.ru_stime.tv_usec * 10;
726         user_time = resource_usage.ru_utime.tv_sec * 1000 * 1000 * 10 + resource_usage.ru_utime.tv_usec * 10;
727
728         cpu_busy_time = (user_time - (prev ? prev->user_time : 0)) + (kernel_time - (prev ? prev->kernel_time : 0));
729         cpu_total_time = (current_time - (prev ? prev->current_time : 0)) * mono_cpu_count ();
730
731         if (prev) {
732                 prev->kernel_time = kernel_time;
733                 prev->user_time = user_time;
734                 prev->current_time = current_time;
735         }
736 #else
737         guint64 idle_time;
738         guint64 kernel_time;
739         guint64 user_time;
740
741         if (!GetSystemTimes ((FILETIME*) &idle_time, (FILETIME*) &kernel_time, (FILETIME*) &user_time)) {
742                 g_error ("GetSystemTimes() failed, error code is %d\n", GetLastError ());
743                 return -1;
744         }
745
746         cpu_total_time = (gint64)((user_time - (prev ? prev->user_time : 0)) + (kernel_time - (prev ? prev->kernel_time : 0)));
747         cpu_busy_time = (gint64)(cpu_total_time - (idle_time - (prev ? prev->idle_time : 0)));
748
749         if (prev) {
750                 prev->idle_time = idle_time;
751                 prev->kernel_time = kernel_time;
752                 prev->user_time = user_time;
753         }
754 #endif
755
756         if (cpu_total_time > 0 && cpu_busy_time > 0)
757                 cpu_usage = (gint32)(cpu_busy_time * 100 / cpu_total_time);
758
759         g_assert (cpu_usage >= 0);
760         g_assert (cpu_usage <= 100);
761
762         return cpu_usage;
763 }