2 * Copyright 2008-2011 Novell Inc
3 * Copyright 2011 Xamarin Inc
7 #include "utils/mono-proclib.h"
8 #include "utils/mono-time.h"
17 #ifdef HAVE_SCHED_GETAFFINITY
26 #if defined(_POSIX_VERSION)
27 #include <sys/errno.h>
28 #include <sys/param.h>
29 #ifdef HAVE_SYS_TYPES_H
30 #include <sys/types.h>
32 #ifdef HAVE_SYS_SYSCTL_H
33 #include <sys/sysctl.h>
35 #include <sys/resource.h>
37 #if defined(__APPLE__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__)
39 #if defined(__APPLE__)
40 #include <mach/mach.h>
42 #ifdef HAVE_SYS_USER_H
45 #ifdef HAVE_STRUCT_KINFO_PROC_KP_PROC
46 # define kinfo_starttime_member kp_proc.p_starttime
47 # define kinfo_pid_member kp_proc.p_pid
48 # define kinfo_name_member kp_proc.p_comm
49 #elif defined(__OpenBSD__)
50 // Can not figure out how to get the proc's start time on OpenBSD
51 # undef kinfo_starttime_member
52 # define kinfo_pid_member p_pid
53 # define kinfo_name_member p_comm
55 #define kinfo_starttime_member ki_start
56 #define kinfo_pid_member ki_pid
57 #define kinfo_name_member ki_comm
64 * @size: a pointer to a location where the size of the returned array is stored
66 * Return an array of pid values for the processes currently running on the system.
67 * The size of the array is stored in @size.
70 mono_process_list (int *size)
76 size_t data_len = sizeof (struct kinfo_proc2) * 400;
77 struct kinfo_proc2 *processes = malloc (data_len);
80 size_t data_len = sizeof (struct kinfo_proc) * 16;
81 struct kinfo_proc *processes;
83 #endif /* KERN_PROC2 */
95 mib [2] = KERN_PROC_ALL;
97 mib [4] = sizeof(struct kinfo_proc2);
98 mib [5] = 400; /* XXX */
100 res = sysctl (mib, 6, processes, &data_len, NULL, 0);
110 mib [2] = KERN_PROC_ALL;
113 res = sysctl (mib, 4, NULL, &data_len, NULL, 0);
116 processes = (struct kinfo_proc *) malloc (data_len);
117 res = sysctl (mib, 4, processes, &data_len, NULL, 0);
127 #endif /* KERN_PROC2 */
130 res = data_len/sizeof (struct kinfo_proc2);
132 res = data_len/sizeof (struct kinfo_proc);
133 #endif /* KERN_PROC2 */
134 buf = (void **) g_realloc (buf, res * sizeof (void*));
135 for (i = 0; i < res; ++i)
136 buf [i] = GINT_TO_POINTER (processes [i].kinfo_pid_member);
141 #elif defined(__HAIKU__)
142 /* FIXME: Add back the code from 9185fcc305e43428d0f40f3ee37c8a405d41c9ae */
143 g_assert_not_reached ();
150 GDir *dir = g_dir_open ("/proc/", 0, NULL);
156 while ((name = g_dir_read_name (dir))) {
159 pid = strtol (name, &nend, 10);
160 if (pid <= 0 || nend == name || *nend)
167 buf = (void **)g_realloc (buf, count * sizeof (void*));
169 buf [i++] = GINT_TO_POINTER (pid);
178 static G_GNUC_UNUSED char*
179 get_pid_status_item_buf (int pid, const char *item, char *rbuf, int blen, MonoProcessError *error)
184 int len = strlen (item);
186 g_snprintf (buf, sizeof (buf), "/proc/%d/status", pid);
187 f = fopen (buf, "r");
190 *error = MONO_PROCESS_ERROR_NOT_FOUND;
193 while ((s = fgets (buf, sizeof (buf), f))) {
196 if (strncmp (buf, item, len))
199 while (g_ascii_isspace (*s)) s++;
202 while (g_ascii_isspace (*s)) s++;
205 strncpy (rbuf, s, MIN (len, blen));
206 rbuf [MIN (len, blen) - 1] = 0;
208 *error = MONO_PROCESS_ERROR_NONE;
213 *error = MONO_PROCESS_ERROR_OTHER;
220 #define KINFO_PROC struct kinfo_proc2
222 #define KINFO_PROC struct kinfo_proc
226 sysctl_kinfo_proc (gpointer pid, KINFO_PROC* processi)
229 size_t data_len = sizeof (KINFO_PROC);
234 mib [1] = KERN_PROC2;
235 mib [2] = KERN_PROC_PID;
236 mib [3] = GPOINTER_TO_UINT (pid);
237 mib [4] = sizeof(KINFO_PROC);
238 mib [5] = 400; /* XXX */
240 res = sysctl (mib, 6, processi, &data_len, NULL, 0);
245 mib [2] = KERN_PROC_PID;
246 mib [3] = GPOINTER_TO_UINT (pid);
248 res = sysctl (mib, 4, processi, &data_len, NULL, 0);
249 #endif /* KERN_PROC2 */
251 if (res < 0 || data_len != sizeof (KINFO_PROC))
256 #endif /* USE_SYSCTL */
259 * mono_process_get_name:
260 * @pid: pid of the process
261 * @buf: byte buffer where to store the name of the prcoess
262 * @len: size of the buffer @buf
264 * Return the name of the process identified by @pid, storing it
265 * inside @buf for a maximum of len bytes (including the terminating 0).
268 mono_process_get_name (gpointer pid, char *buf, int len)
273 memset (buf, 0, len);
275 if (sysctl_kinfo_proc (pid, &processi))
276 strncpy (buf, processi.kinfo_name_member, len - 1);
284 sprintf (fname, "/proc/%d/cmdline", GPOINTER_TO_INT (pid));
286 file = fopen (fname, "r");
289 r = fread (buf, 1, len - 1, file);
292 p = strrchr (buf, '/');
296 return get_pid_status_item_buf (GPOINTER_TO_INT (pid), "Name", buf, len, NULL);
303 mono_process_get_times (gpointer pid, gint64 *start_time, gint64 *user_time, gint64 *kernel_time)
306 *user_time = mono_process_get_data (pid, MONO_PROCESS_USER_TIME);
309 *kernel_time = mono_process_get_data (pid, MONO_PROCESS_SYSTEM_TIME);
314 #if USE_SYSCTL && defined(kinfo_starttime_member)
318 if (sysctl_kinfo_proc (pid, &processi))
319 *start_time = mono_100ns_datetime_from_timeval (processi.kinfo_starttime_member);
323 if (*start_time == 0) {
324 static guint64 boot_time = 0;
326 boot_time = mono_100ns_datetime () - ((guint64)mono_msec_ticks ()) * 10000;
328 *start_time = boot_time + mono_process_get_data (pid, MONO_PROCESS_ELAPSED);
334 * /proc/pid/stat format:
336 * [0] ppid pgid sid tty_nr tty_pgrp flags min_flt cmin_flt maj_flt cmaj_flt
337 * [10] utime stime cutime cstime prio nice threads 0 start_time vsize
338 * [20] rss rsslim start_code end_code start_stack esp eip pending blocked sigign
339 * [30] sigcatch wchan 0 0 exit_signal cpu rt_prio policy
342 #define RET_ERROR(err) do { \
343 if (error) *error = (err); \
348 get_process_stat_item (int pid, int pos, int sum, MonoProcessError *error)
350 #if defined(__APPLE__)
351 double process_user_time = 0, process_system_time = 0;//, process_percent = 0;
353 struct task_basic_info t_info;
354 mach_msg_type_number_t t_info_count = TASK_BASIC_INFO_COUNT, th_count;
355 thread_array_t th_array;
358 if (pid == getpid ()) {
359 /* task_for_pid () doesn't work on ios, even for the current process */
360 task = mach_task_self ();
362 if (task_for_pid (mach_task_self (), pid, &task) != KERN_SUCCESS)
363 RET_ERROR (MONO_PROCESS_ERROR_NOT_FOUND);
366 if (task_info (task, TASK_BASIC_INFO, (task_info_t)&t_info, &t_info_count) != KERN_SUCCESS) {
367 if (pid != getpid ())
368 mach_port_deallocate (mach_task_self (), task);
369 RET_ERROR (MONO_PROCESS_ERROR_OTHER);
372 if (task_threads(task, &th_array, &th_count) != KERN_SUCCESS) {
373 if (pid != getpid ())
374 mach_port_deallocate (mach_task_self (), task);
375 RET_ERROR (MONO_PROCESS_ERROR_OTHER);
378 for (i = 0; i < th_count; i++) {
379 double thread_user_time, thread_system_time;//, thread_percent;
381 struct thread_basic_info th_info;
382 mach_msg_type_number_t th_info_count = THREAD_BASIC_INFO_COUNT;
383 if (thread_info(th_array[i], THREAD_BASIC_INFO, (thread_info_t)&th_info, &th_info_count) == KERN_SUCCESS) {
384 thread_user_time = th_info.user_time.seconds + th_info.user_time.microseconds / 1e6;
385 thread_system_time = th_info.system_time.seconds + th_info.system_time.microseconds / 1e6;
386 //thread_percent = (double)th_info.cpu_usage / TH_USAGE_SCALE;
388 process_user_time += thread_user_time;
389 process_system_time += thread_system_time;
390 //process_percent += th_percent;
394 for (i = 0; i < th_count; i++)
395 mach_port_deallocate(task, th_array[i]);
397 if (pid != getpid ())
398 mach_port_deallocate (mach_task_self (), task);
400 process_user_time += t_info.user_time.seconds + t_info.user_time.microseconds / 1e6;
401 process_system_time += t_info.system_time.seconds + t_info.system_time.microseconds / 1e6;
403 if (pos == 10 && sum == TRUE)
404 return (gint64)((process_user_time + process_system_time) * 10000000);
406 return (gint64)(process_user_time * 10000000);
408 return (gint64)(process_system_time * 10000000);
418 g_snprintf (buf, sizeof (buf), "/proc/%d/stat", pid);
419 f = fopen (buf, "r");
421 RET_ERROR (MONO_PROCESS_ERROR_NOT_FOUND);
422 len = fread (buf, 1, sizeof (buf), f);
425 RET_ERROR (MONO_PROCESS_ERROR_OTHER);
426 s = strchr (buf, ')');
428 RET_ERROR (MONO_PROCESS_ERROR_OTHER);
430 while (g_ascii_isspace (*s)) s++;
432 RET_ERROR (MONO_PROCESS_ERROR_OTHER);
433 /* skip the status char */
434 while (*s && !g_ascii_isspace (*s)) s++;
436 RET_ERROR (MONO_PROCESS_ERROR_OTHER);
437 for (i = 0; i < pos; ++i) {
438 while (g_ascii_isspace (*s)) s++;
440 RET_ERROR (MONO_PROCESS_ERROR_OTHER);
441 while (*s && !g_ascii_isspace (*s)) s++;
443 RET_ERROR (MONO_PROCESS_ERROR_OTHER);
445 /* we are finally at the needed item */
446 value = strtoul (s, &end, 0);
447 /* add also the following value */
449 while (g_ascii_isspace (*s)) s++;
451 RET_ERROR (MONO_PROCESS_ERROR_OTHER);
452 value += strtoul (s, &end, 0);
455 *error = MONO_PROCESS_ERROR_NONE;
463 static int user_hz = 0;
466 user_hz = sysconf (_SC_CLK_TCK);
475 get_process_stat_time (int pid, int pos, int sum, MonoProcessError *error)
477 gint64 val = get_process_stat_item (pid, pos, sum, error);
478 #if defined(__APPLE__)
481 /* return 100ns ticks */
482 return (val * 10000000) / get_user_hz ();
487 get_pid_status_item (int pid, const char *item, MonoProcessError *error, int multiplier)
489 #if defined(__APPLE__)
490 // ignore the multiplier
494 struct task_basic_info t_info;
495 mach_msg_type_number_t th_count = TASK_BASIC_INFO_COUNT;
497 if (pid == getpid ()) {
498 /* task_for_pid () doesn't work on ios, even for the current process */
499 task = mach_task_self ();
501 if (task_for_pid (mach_task_self (), pid, &task) != KERN_SUCCESS)
502 RET_ERROR (MONO_PROCESS_ERROR_NOT_FOUND);
505 if (task_info (task, TASK_BASIC_INFO, (task_info_t)&t_info, &th_count) != KERN_SUCCESS) {
506 if (pid != getpid ())
507 mach_port_deallocate (mach_task_self (), task);
508 RET_ERROR (MONO_PROCESS_ERROR_OTHER);
511 if (strcmp (item, "VmRSS") == 0 || strcmp (item, "VmHWM") == 0 || strcmp (item, "VmData") == 0)
512 ret = t_info.resident_size;
513 else if (strcmp (item, "VmSize") == 0 || strcmp (item, "VmPeak") == 0)
514 ret = t_info.virtual_size;
515 else if (strcmp (item, "Threads") == 0)
520 if (pid != getpid ())
521 mach_port_deallocate (mach_task_self (), task);
528 s = get_pid_status_item_buf (pid, item, buf, sizeof (buf), error);
530 return ((gint64) atol (s)) * multiplier;
536 * mono_process_get_data:
537 * @pid: pid of the process
538 * @data: description of data to return
540 * Return a data item of a process like user time, memory use etc,
541 * according to the @data argumet.
544 mono_process_get_data_with_error (gpointer pid, MonoProcessData data, MonoProcessError *error)
547 int rpid = GPOINTER_TO_INT (pid);
550 *error = MONO_PROCESS_ERROR_OTHER;
553 case MONO_PROCESS_NUM_THREADS:
554 return get_pid_status_item (rpid, "Threads", error, 1);
555 case MONO_PROCESS_USER_TIME:
556 return get_process_stat_time (rpid, 10, FALSE, error);
557 case MONO_PROCESS_SYSTEM_TIME:
558 return get_process_stat_time (rpid, 11, FALSE, error);
559 case MONO_PROCESS_TOTAL_TIME:
560 return get_process_stat_time (rpid, 10, TRUE, error);
561 case MONO_PROCESS_WORKING_SET:
562 return get_pid_status_item (rpid, "VmRSS", error, 1024);
563 case MONO_PROCESS_WORKING_SET_PEAK:
564 val = get_pid_status_item (rpid, "VmHWM", error, 1024);
566 val = get_pid_status_item (rpid, "VmRSS", error, 1024);
568 case MONO_PROCESS_PRIVATE_BYTES:
569 return get_pid_status_item (rpid, "VmData", error, 1024);
570 case MONO_PROCESS_VIRTUAL_BYTES:
571 return get_pid_status_item (rpid, "VmSize", error, 1024);
572 case MONO_PROCESS_VIRTUAL_BYTES_PEAK:
573 val = get_pid_status_item (rpid, "VmPeak", error, 1024);
575 val = get_pid_status_item (rpid, "VmSize", error, 1024);
577 case MONO_PROCESS_FAULTS:
578 return get_process_stat_item (rpid, 6, TRUE, error);
579 case MONO_PROCESS_ELAPSED:
580 return get_process_stat_time (rpid, 18, FALSE, error);
581 case MONO_PROCESS_PPID:
582 return get_process_stat_time (rpid, 0, FALSE, error);
583 case MONO_PROCESS_PAGED_BYTES:
584 return get_pid_status_item (rpid, "VmSwap", error, 1024);
587 case MONO_PROCESS_END:
594 mono_process_get_data (gpointer pid, MonoProcessData data)
596 MonoProcessError error;
597 return mono_process_get_data_with_error (pid, data, &error);
601 mono_process_current_pid ()
603 #if defined(HAVE_UNISTD_H)
604 return (int) getpid ();
605 #elif defined(HOST_WIN32)
606 return (int) GetCurrentProcessId ();
615 * Return the number of processors on the system.
618 mono_cpu_count (void)
622 GetSystemInfo (&info);
623 return info.dwNumberOfProcessors;
626 #ifdef PLATFORM_ANDROID
627 /* Android tries really hard to save power by powering off CPUs on SMP phones which
628 * means the normal way to query cpu count returns a wrong value with userspace API.
629 * Instead we use /sys entries to query the actual hardware CPU count.
631 char buffer[8] = {'\0'};
632 int present = open ("/sys/devices/system/cpu/present", O_RDONLY);
633 /* Format of the /sys entry is a cpulist of indexes which in the case
634 * of present is always of the form "0-(n-1)" when there is more than
635 * 1 core, n being the number of CPU cores in the system. Otherwise
636 * the value is simply 0
638 if (present != -1 && read (present, (char*)buffer, sizeof (buffer)) > 3)
639 count = strtol (((char*)buffer) + 2, NULL, 10);
645 #ifdef HAVE_SCHED_GETAFFINITY
648 if (sched_getaffinity (mono_process_current_pid (), sizeof (set), &set) == 0)
649 return CPU_COUNT (&set);
652 #ifdef _SC_NPROCESSORS_CONF
653 count = sysconf (_SC_NPROCESSORS_CONF);
660 size_t len = sizeof (int);
663 if (sysctl (mib, 2, &count, &len, NULL, 0) == 0)
673 get_cpu_times (int cpu_id, gint64 *user, gint64 *systemt, gint64 *irq, gint64 *sirq, gint64 *idle)
677 int hz = get_user_hz ();
678 guint64 user_ticks = 0, nice_ticks = 0, system_ticks = 0, idle_ticks = 0, irq_ticks = 0, sirq_ticks = 0;
679 FILE *f = fopen ("/proc/stat", "r");
683 hz *= mono_cpu_count ();
684 while ((s = fgets (buf, sizeof (buf), f))) {
686 if (cpu_id < 0 && strncmp (s, "cpu", 3) == 0 && g_ascii_isspace (s [3])) {
688 } else if (cpu_id >= 0 && strncmp (s, "cpu", 3) == 0 && strtol (s + 3, &data, 10) == cpu_id) {
696 user_ticks = strtoull (data, &data, 10);
697 nice_ticks = strtoull (data, &data, 10);
698 system_ticks = strtoull (data, &data, 10);
699 idle_ticks = strtoull (data, &data, 10);
700 /* iowait_ticks = strtoull (data, &data, 10); */
701 irq_ticks = strtoull (data, &data, 10);
702 sirq_ticks = strtoull (data, &data, 10);
708 *user = (user_ticks + nice_ticks) * 10000000 / hz;
710 *systemt = (system_ticks) * 10000000 / hz;
712 *irq = (irq_ticks) * 10000000 / hz;
714 *sirq = (sirq_ticks) * 10000000 / hz;
716 *idle = (idle_ticks) * 10000000 / hz;
721 * @cpu_id: processor number or -1 to get a summary of all the processors
722 * @data: type of data to retrieve
724 * Get data about a processor on the system, like time spent in user space or idle time.
727 mono_cpu_get_data (int cpu_id, MonoCpuData data, MonoProcessError *error)
732 *error = MONO_PROCESS_ERROR_NONE;
734 case MONO_CPU_USER_TIME:
735 get_cpu_times (cpu_id, &value, NULL, NULL, NULL, NULL);
737 case MONO_CPU_PRIV_TIME:
738 get_cpu_times (cpu_id, NULL, &value, NULL, NULL, NULL);
740 case MONO_CPU_INTR_TIME:
741 get_cpu_times (cpu_id, NULL, NULL, &value, NULL, NULL);
743 case MONO_CPU_DCP_TIME:
744 get_cpu_times (cpu_id, NULL, NULL, NULL, &value, NULL);
746 case MONO_CPU_IDLE_TIME:
747 get_cpu_times (cpu_id, NULL, NULL, NULL, NULL, &value);
758 mono_atexit (void (*func)(void))
760 #ifdef PLATFORM_ANDROID
761 /* Some versions of android libc doesn't define atexit () */
764 return atexit (func);
769 * This function returns the cpu usage in percentage,
770 * normalized on the number of cores.
772 * Warning : the percentage returned can be > 100%. This
773 * might happens on systems like Android which, for
774 * battery and performance reasons, shut down cores and
775 * lie about the number of active cores.
778 mono_cpu_usage (MonoCpuUsageState *prev)
780 gint32 cpu_usage = 0;
781 gint64 cpu_total_time;
782 gint64 cpu_busy_time;
785 struct rusage resource_usage;
790 if (getrusage (RUSAGE_SELF, &resource_usage) == -1) {
791 g_error ("getrusage() failed, errno is %d (%s)\n", errno, strerror (errno));
795 current_time = mono_100ns_ticks ();
796 kernel_time = resource_usage.ru_stime.tv_sec * 1000 * 1000 * 10 + resource_usage.ru_stime.tv_usec * 10;
797 user_time = resource_usage.ru_utime.tv_sec * 1000 * 1000 * 10 + resource_usage.ru_utime.tv_usec * 10;
799 cpu_busy_time = (user_time - (prev ? prev->user_time : 0)) + (kernel_time - (prev ? prev->kernel_time : 0));
800 cpu_total_time = (current_time - (prev ? prev->current_time : 0)) * mono_cpu_count ();
803 prev->kernel_time = kernel_time;
804 prev->user_time = user_time;
805 prev->current_time = current_time;
812 if (!GetSystemTimes ((FILETIME*) &idle_time, (FILETIME*) &kernel_time, (FILETIME*) &user_time)) {
813 g_error ("GetSystemTimes() failed, error code is %d\n", GetLastError ());
817 cpu_total_time = (gint64)((user_time - (prev ? prev->user_time : 0)) + (kernel_time - (prev ? prev->kernel_time : 0)));
818 cpu_busy_time = (gint64)(cpu_total_time - (idle_time - (prev ? prev->idle_time : 0)));
821 prev->idle_time = idle_time;
822 prev->kernel_time = kernel_time;
823 prev->user_time = user_time;
827 if (cpu_total_time > 0 && cpu_busy_time > 0)
828 cpu_usage = (gint32)(cpu_busy_time * 100 / cpu_total_time);