2 * Copyright 2008-2011 Novell Inc
3 * Copyright 2011 Xamarin Inc
7 #include "utils/mono-proclib.h"
8 #include "utils/mono-time.h"
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>
29 #ifdef HAVE_SYS_SYSCTL_H
30 #include <sys/sysctl.h>
32 #include <sys/resource.h>
34 #if defined(__APPLE__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__)
36 #if defined(__APPLE__)
37 #include <mach/mach.h>
39 #ifdef HAVE_SYS_USER_H
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
49 #define kinfo_pid_member ki_pid
50 #define kinfo_name_member ki_comm
57 * @size: a pointer to a location where the size of the returned array is stored
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.
63 mono_process_list (int *size)
69 size_t data_len = sizeof (struct kinfo_proc2) * 400;
70 struct kinfo_proc2 *processes = malloc (data_len);
73 size_t data_len = sizeof (struct kinfo_proc) * 16;
74 struct kinfo_proc *processes;
76 #endif /* KERN_PROC2 */
88 mib [2] = KERN_PROC_ALL;
90 mib [4] = sizeof(struct kinfo_proc2);
91 mib [5] = 400; /* XXX */
93 res = sysctl (mib, 6, processes, &data_len, NULL, 0);
103 mib [2] = KERN_PROC_ALL;
106 res = sysctl (mib, 4, NULL, &data_len, NULL, 0);
109 processes = malloc (data_len);
110 res = sysctl (mib, 4, processes, &data_len, NULL, 0);
120 #endif /* KERN_PROC2 */
123 res = data_len/sizeof (struct kinfo_proc2);
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);
134 #elif defined(__HAIKU__)
135 /* FIXME: Add back the code from 9185fcc305e43428d0f40f3ee37c8a405d41c9ae */
136 g_assert_not_reached ();
143 GDir *dir = g_dir_open ("/proc/", 0, NULL);
149 while ((name = g_dir_read_name (dir))) {
152 pid = strtol (name, &nend, 10);
153 if (pid <= 0 || nend == name || *nend)
160 buf = g_realloc (buf, count * sizeof (void*));
162 buf [i++] = GINT_TO_POINTER (pid);
171 static G_GNUC_UNUSED char*
172 get_pid_status_item_buf (int pid, const char *item, char *rbuf, int blen, MonoProcessError *error)
177 int len = strlen (item);
179 g_snprintf (buf, sizeof (buf), "/proc/%d/status", pid);
180 f = fopen (buf, "r");
183 *error = MONO_PROCESS_ERROR_NOT_FOUND;
186 while ((s = fgets (buf, blen, f))) {
189 if (strncmp (buf, item, len))
192 while (g_ascii_isspace (*s)) s++;
195 while (g_ascii_isspace (*s)) s++;
198 strncpy (rbuf, s, MIN (len, blen));
199 rbuf [MIN (len, blen) - 1] = 0;
201 *error = MONO_PROCESS_ERROR_NONE;
206 *error = MONO_PROCESS_ERROR_OTHER;
213 #define KINFO_PROC struct kinfo_proc2
215 #define KINFO_PROC struct kinfo_proc
219 sysctl_kinfo_proc (gpointer pid, KINFO_PROC* processi)
222 size_t data_len = sizeof (KINFO_PROC);
227 mib [1] = KERN_PROC2;
228 mib [2] = KERN_PROC_PID;
229 mib [3] = GPOINTER_TO_UINT (pid);
230 mib [4] = sizeof(KINFO_PROC);
231 mib [5] = 400; /* XXX */
233 res = sysctl (mib, 6, processi, &data_len, NULL, 0);
238 mib [2] = KERN_PROC_PID;
239 mib [3] = GPOINTER_TO_UINT (pid);
241 res = sysctl (mib, 4, processi, &data_len, NULL, 0);
242 #endif /* KERN_PROC2 */
244 if (res < 0 || data_len != sizeof (KINFO_PROC))
249 #endif /* USE_SYSCTL */
252 * mono_process_get_name:
253 * @pid: pid of the process
254 * @buf: byte buffer where to store the name of the prcoess
255 * @len: size of the buffer @buf
257 * Return the name of the process identified by @pid, storing it
258 * inside @buf for a maximum of len bytes (including the terminating 0).
261 mono_process_get_name (gpointer pid, char *buf, int len)
266 memset (buf, 0, len);
268 if (sysctl_kinfo_proc (pid, &processi))
269 strncpy (buf, processi.kinfo_name_member, len - 1);
277 sprintf (fname, "/proc/%d/cmdline", GPOINTER_TO_INT (pid));
279 file = fopen (fname, "r");
282 r = fread (buf, 1, len - 1, file);
285 p = strrchr (buf, '/');
289 return get_pid_status_item_buf (GPOINTER_TO_INT (pid), "Name", buf, len, NULL);
296 mono_process_get_times (gpointer pid, gint64 *start_time, gint64 *user_time, gint64 *kernel_time)
299 *user_time = mono_process_get_data (pid, MONO_PROCESS_USER_TIME);
302 *kernel_time = mono_process_get_data (pid, MONO_PROCESS_SYSTEM_TIME);
311 if (sysctl_kinfo_proc (pid, &processi))
312 *start_time = mono_100ns_datetime_from_timeval (processi.kp_proc.p_starttime);
316 if (*start_time == 0) {
317 static guint64 boot_time = 0;
319 boot_time = mono_100ns_datetime () - ((guint64)mono_msec_ticks ()) * 10000;
321 *start_time = boot_time + mono_process_get_data (pid, MONO_PROCESS_ELAPSED);
327 * /proc/pid/stat format:
329 * [0] ppid pgid sid tty_nr tty_pgrp flags min_flt cmin_flt maj_flt cmaj_flt
330 * [10] utime stime cutime cstime prio nice threads 0 start_time vsize
331 * [20] rss rsslim start_code end_code start_stack esp eip pending blocked sigign
332 * [30] sigcatch wchan 0 0 exit_signal cpu rt_prio policy
335 #define RET_ERROR(err) do { \
336 if (error) *error = (err); \
341 get_process_stat_item (int pid, int pos, int sum, MonoProcessError *error)
343 #if defined(__APPLE__)
344 double process_user_time = 0, process_system_time = 0;//, process_percent = 0;
346 struct task_basic_info t_info;
347 mach_msg_type_number_t t_info_count = TASK_BASIC_INFO_COUNT, th_count;
348 thread_array_t th_array;
351 if (task_for_pid(mach_task_self(), pid, &task) != KERN_SUCCESS)
352 RET_ERROR (MONO_PROCESS_ERROR_NOT_FOUND);
354 if (task_info(task, TASK_BASIC_INFO, (task_info_t)&t_info, &t_info_count) != KERN_SUCCESS) {
355 mach_port_deallocate (mach_task_self (), task);
356 RET_ERROR (MONO_PROCESS_ERROR_OTHER);
359 if (task_threads(task, &th_array, &th_count) != KERN_SUCCESS) {
360 mach_port_deallocate (mach_task_self (), task);
361 RET_ERROR (MONO_PROCESS_ERROR_OTHER);
364 for (i = 0; i < th_count; i++) {
365 double thread_user_time, thread_system_time;//, thread_percent;
367 struct thread_basic_info th_info;
368 mach_msg_type_number_t th_info_count = THREAD_BASIC_INFO_COUNT;
369 if (thread_info(th_array[i], THREAD_BASIC_INFO, (thread_info_t)&th_info, &th_info_count) == KERN_SUCCESS) {
370 thread_user_time = th_info.user_time.seconds + th_info.user_time.microseconds / 1e6;
371 thread_system_time = th_info.system_time.seconds + th_info.system_time.microseconds / 1e6;
372 //thread_percent = (double)th_info.cpu_usage / TH_USAGE_SCALE;
374 process_user_time += thread_user_time;
375 process_system_time += thread_system_time;
376 //process_percent += th_percent;
380 for (i = 0; i < th_count; i++)
381 mach_port_deallocate(task, th_array[i]);
383 mach_port_deallocate (mach_task_self (), task);
385 process_user_time += t_info.user_time.seconds + t_info.user_time.microseconds / 1e6;
386 process_system_time += t_info.system_time.seconds + t_info.system_time.microseconds / 1e6;
388 if (pos == 10 && sum == TRUE)
389 return (gint64)((process_user_time + process_system_time) * 10000000);
391 return (gint64)(process_user_time * 10000000);
393 return (gint64)(process_system_time * 10000000);
403 g_snprintf (buf, sizeof (buf), "/proc/%d/stat", pid);
404 f = fopen (buf, "r");
406 RET_ERROR (MONO_PROCESS_ERROR_NOT_FOUND);
407 len = fread (buf, 1, sizeof (buf), f);
410 RET_ERROR (MONO_PROCESS_ERROR_OTHER);
411 s = strchr (buf, ')');
413 RET_ERROR (MONO_PROCESS_ERROR_OTHER);
415 while (g_ascii_isspace (*s)) s++;
417 RET_ERROR (MONO_PROCESS_ERROR_OTHER);
418 /* skip the status char */
419 while (*s && !g_ascii_isspace (*s)) s++;
421 RET_ERROR (MONO_PROCESS_ERROR_OTHER);
422 for (i = 0; i < pos; ++i) {
423 while (g_ascii_isspace (*s)) s++;
425 RET_ERROR (MONO_PROCESS_ERROR_OTHER);
426 while (*s && !g_ascii_isspace (*s)) s++;
428 RET_ERROR (MONO_PROCESS_ERROR_OTHER);
430 /* we are finally at the needed item */
431 value = strtoul (s, &end, 0);
432 /* add also the following value */
434 while (g_ascii_isspace (*s)) s++;
436 RET_ERROR (MONO_PROCESS_ERROR_OTHER);
437 value += strtoul (s, &end, 0);
440 *error = MONO_PROCESS_ERROR_NONE;
448 static int user_hz = 0;
451 user_hz = sysconf (_SC_CLK_TCK);
460 get_process_stat_time (int pid, int pos, int sum, MonoProcessError *error)
462 gint64 val = get_process_stat_item (pid, pos, sum, error);
463 #if defined(__APPLE__)
466 /* return 100ns ticks */
467 return (val * 10000000) / get_user_hz ();
472 get_pid_status_item (int pid, const char *item, MonoProcessError *error, int multiplier)
474 #if defined(__APPLE__)
475 // ignore the multiplier
479 struct task_basic_info t_info;
480 mach_msg_type_number_t th_count = TASK_BASIC_INFO_COUNT;
482 if (pid == getpid ()) {
483 /* task_for_pid () doesn't work on ios, even for the current process */
484 task = mach_task_self ();
486 if (task_for_pid (mach_task_self (), pid, &task) != KERN_SUCCESS)
487 RET_ERROR (MONO_PROCESS_ERROR_NOT_FOUND);
490 if (task_info (task, TASK_BASIC_INFO, (task_info_t)&t_info, &th_count) != KERN_SUCCESS) {
491 if (pid != getpid ())
492 mach_port_deallocate (mach_task_self (), task);
493 RET_ERROR (MONO_PROCESS_ERROR_OTHER);
496 if (strcmp (item, "VmRSS") == 0 || strcmp (item, "VmHWM") == 0 || strcmp (item, "VmData") == 0)
497 ret = t_info.resident_size;
498 else if (strcmp (item, "VmSize") == 0 || strcmp (item, "VmPeak") == 0)
499 ret = t_info.virtual_size;
500 else if (strcmp (item, "Threads") == 0)
505 if (pid != getpid ())
506 mach_port_deallocate (mach_task_self (), task);
513 s = get_pid_status_item_buf (pid, item, buf, sizeof (buf), error);
515 return ((gint64) atol (s)) * multiplier;
521 * mono_process_get_data:
522 * @pid: pid of the process
523 * @data: description of data to return
525 * Return a data item of a process like user time, memory use etc,
526 * according to the @data argumet.
529 mono_process_get_data_with_error (gpointer pid, MonoProcessData data, MonoProcessError *error)
532 int rpid = GPOINTER_TO_INT (pid);
535 *error = MONO_PROCESS_ERROR_OTHER;
538 case MONO_PROCESS_NUM_THREADS:
539 return get_pid_status_item (rpid, "Threads", error, 1);
540 case MONO_PROCESS_USER_TIME:
541 return get_process_stat_time (rpid, 10, FALSE, error);
542 case MONO_PROCESS_SYSTEM_TIME:
543 return get_process_stat_time (rpid, 11, FALSE, error);
544 case MONO_PROCESS_TOTAL_TIME:
545 return get_process_stat_time (rpid, 10, TRUE, error);
546 case MONO_PROCESS_WORKING_SET:
547 return get_pid_status_item (rpid, "VmRSS", error, 1024);
548 case MONO_PROCESS_WORKING_SET_PEAK:
549 val = get_pid_status_item (rpid, "VmHWM", error, 1024);
551 val = get_pid_status_item (rpid, "VmRSS", error, 1024);
553 case MONO_PROCESS_PRIVATE_BYTES:
554 return get_pid_status_item (rpid, "VmData", error, 1024);
555 case MONO_PROCESS_VIRTUAL_BYTES:
556 return get_pid_status_item (rpid, "VmSize", error, 1024);
557 case MONO_PROCESS_VIRTUAL_BYTES_PEAK:
558 val = get_pid_status_item (rpid, "VmPeak", error, 1024);
560 val = get_pid_status_item (rpid, "VmSize", error, 1024);
562 case MONO_PROCESS_FAULTS:
563 return get_process_stat_item (rpid, 6, TRUE, error);
564 case MONO_PROCESS_ELAPSED:
565 return get_process_stat_time (rpid, 18, FALSE, error);
566 case MONO_PROCESS_PPID:
567 return get_process_stat_time (rpid, 0, FALSE, error);
568 case MONO_PROCESS_PAGED_BYTES:
569 return get_pid_status_item (rpid, "VmSwap", error, 1024);
572 case MONO_PROCESS_END:
579 mono_process_get_data (gpointer pid, MonoProcessData data)
581 MonoProcessError error;
582 return mono_process_get_data_with_error (pid, data, &error);
586 mono_process_current_pid ()
588 #if defined(HAVE_UNISTD_H)
589 return (int) getpid ();
590 #elif defined(HOST_WIN32)
591 return (int) GetCurrentProcessId ();
600 * Return the number of processors on the system.
603 mono_cpu_count (void)
606 #ifdef PLATFORM_ANDROID
607 /* Android tries really hard to save power by powering off CPUs on SMP phones which
608 * means the normal way to query cpu count returns a wrong value with userspace API.
609 * Instead we use /sys entries to query the actual hardware CPU count.
611 char buffer[8] = {'\0'};
612 int present = open ("/sys/devices/system/cpu/present", O_RDONLY);
613 /* Format of the /sys entry is a cpulist of indexes which in the case
614 * of present is always of the form "0-(n-1)" when there is more than
615 * 1 core, n being the number of CPU cores in the system. Otherwise
616 * the value is simply 0
618 if (present != -1 && read (present, (char*)buffer, sizeof (buffer)) > 3)
619 count = strtol (((char*)buffer) + 2, NULL, 10);
625 #ifdef _SC_NPROCESSORS_ONLN
626 count = sysconf (_SC_NPROCESSORS_ONLN);
633 size_t len = sizeof (int);
636 if (sysctl (mib, 2, &count, &len, NULL, 0) == 0)
643 GetSystemInfo (&info);
644 return info.dwNumberOfProcessors;
652 get_cpu_times (int cpu_id, gint64 *user, gint64 *systemt, gint64 *irq, gint64 *sirq, gint64 *idle)
656 int hz = get_user_hz ();
657 guint64 user_ticks = 0, nice_ticks = 0, system_ticks = 0, idle_ticks = 0, irq_ticks = 0, sirq_ticks = 0;
658 FILE *f = fopen ("/proc/stat", "r");
662 hz *= mono_cpu_count ();
663 while ((s = fgets (buf, sizeof (buf), f))) {
665 if (cpu_id < 0 && strncmp (s, "cpu", 3) == 0 && g_ascii_isspace (s [3])) {
667 } else if (cpu_id >= 0 && strncmp (s, "cpu", 3) == 0 && strtol (s + 3, &data, 10) == cpu_id) {
675 user_ticks = strtoull (data, &data, 10);
676 nice_ticks = strtoull (data, &data, 10);
677 system_ticks = strtoull (data, &data, 10);
678 idle_ticks = strtoull (data, &data, 10);
679 /* iowait_ticks = strtoull (data, &data, 10); */
680 irq_ticks = strtoull (data, &data, 10);
681 sirq_ticks = strtoull (data, &data, 10);
687 *user = (user_ticks + nice_ticks) * 10000000 / hz;
689 *systemt = (system_ticks) * 10000000 / hz;
691 *irq = (irq_ticks) * 10000000 / hz;
693 *sirq = (sirq_ticks) * 10000000 / hz;
695 *idle = (idle_ticks) * 10000000 / hz;
700 * @cpu_id: processor number or -1 to get a summary of all the processors
701 * @data: type of data to retrieve
703 * Get data about a processor on the system, like time spent in user space or idle time.
706 mono_cpu_get_data (int cpu_id, MonoCpuData data, MonoProcessError *error)
711 *error = MONO_PROCESS_ERROR_NONE;
713 case MONO_CPU_USER_TIME:
714 get_cpu_times (cpu_id, &value, NULL, NULL, NULL, NULL);
716 case MONO_CPU_PRIV_TIME:
717 get_cpu_times (cpu_id, NULL, &value, NULL, NULL, NULL);
719 case MONO_CPU_INTR_TIME:
720 get_cpu_times (cpu_id, NULL, NULL, &value, NULL, NULL);
722 case MONO_CPU_DCP_TIME:
723 get_cpu_times (cpu_id, NULL, NULL, NULL, &value, NULL);
725 case MONO_CPU_IDLE_TIME:
726 get_cpu_times (cpu_id, NULL, NULL, NULL, NULL, &value);
737 mono_atexit (void (*func)(void))
739 #ifdef PLATFORM_ANDROID
740 /* Some versions of android libc doesn't define atexit () */
743 return atexit (func);
748 mono_cpu_usage (MonoCpuUsageState *prev)
750 gint32 cpu_usage = 0;
751 gint64 cpu_total_time;
752 gint64 cpu_busy_time;
755 struct rusage resource_usage;
760 if (getrusage (RUSAGE_SELF, &resource_usage) == -1) {
761 g_error ("getrusage() failed, errno is %d (%s)\n", errno, strerror (errno));
765 current_time = mono_100ns_ticks ();
766 kernel_time = resource_usage.ru_stime.tv_sec * 1000 * 1000 * 10 + resource_usage.ru_stime.tv_usec * 10;
767 user_time = resource_usage.ru_utime.tv_sec * 1000 * 1000 * 10 + resource_usage.ru_utime.tv_usec * 10;
769 cpu_busy_time = (user_time - (prev ? prev->user_time : 0)) + (kernel_time - (prev ? prev->kernel_time : 0));
770 cpu_total_time = (current_time - (prev ? prev->current_time : 0)) * mono_cpu_count ();
773 prev->kernel_time = kernel_time;
774 prev->user_time = user_time;
775 prev->current_time = current_time;
782 if (!GetSystemTimes ((FILETIME*) &idle_time, (FILETIME*) &kernel_time, (FILETIME*) &user_time)) {
783 g_error ("GetSystemTimes() failed, error code is %d\n", GetLastError ());
787 cpu_total_time = (gint64)((user_time - (prev ? prev->user_time : 0)) + (kernel_time - (prev ? prev->kernel_time : 0)));
788 cpu_busy_time = (gint64)(cpu_total_time - (idle_time - (prev ? prev->idle_time : 0)));
791 prev->idle_time = idle_time;
792 prev->kernel_time = kernel_time;
793 prev->user_time = user_time;
797 if (cpu_total_time > 0 && cpu_busy_time > 0)
798 cpu_usage = (gint32)(cpu_busy_time * 100 / cpu_total_time);
800 g_assert (cpu_usage >= 0);
801 g_assert (cpu_usage <= 100);