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