2 * Copyright 2008-2011 Novell Inc
3 * Copyright 2011 Xamarin Inc
7 #include "utils/mono-proclib.h"
8 #include "utils/mono-time.h"
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>
30 #include <sys/resource.h>
31 #if defined(__APPLE__)
32 #include <mach/mach.h>
34 #ifdef HAVE_SYS_USER_H
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
44 #define kinfo_pid_member ki_pid
45 #define kinfo_name_member ki_comm
52 * @size: a pointer to a location where the size of the returned array is stored
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.
58 mono_process_list (int *size)
64 size_t data_len = sizeof (struct kinfo_proc2) * 400;
65 struct kinfo_proc2 *processes = malloc (data_len);
68 size_t data_len = sizeof (struct kinfo_proc) * 16;
69 struct kinfo_proc *processes;
71 #endif /* KERN_PROC2 */
83 mib [2] = KERN_PROC_ALL;
85 mib [4] = sizeof(struct kinfo_proc2);
86 mib [5] = 400; /* XXX */
88 res = sysctl (mib, 6, processes, &data_len, NULL, 0);
98 mib [2] = KERN_PROC_ALL;
101 res = sysctl (mib, 4, NULL, &data_len, NULL, 0);
104 processes = malloc (data_len);
105 res = sysctl (mib, 4, processes, &data_len, NULL, 0);
115 #endif /* KERN_PROC2 */
118 res = data_len/sizeof (struct kinfo_proc2);
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);
129 #elif defined(__HAIKU__)
130 /* FIXME: Add back the code from 9185fcc305e43428d0f40f3ee37c8a405d41c9ae */
131 g_assert_not_reached ();
138 GDir *dir = g_dir_open ("/proc/", 0, NULL);
144 while ((name = g_dir_read_name (dir))) {
147 pid = strtol (name, &nend, 10);
148 if (pid <= 0 || nend == name || *nend)
155 buf = g_realloc (buf, count * sizeof (void*));
157 buf [i++] = GINT_TO_POINTER (pid);
166 static G_GNUC_UNUSED char*
167 get_pid_status_item_buf (int pid, const char *item, char *rbuf, int blen, MonoProcessError *error)
172 int len = strlen (item);
174 g_snprintf (buf, sizeof (buf), "/proc/%d/status", pid);
175 f = fopen (buf, "r");
178 *error = MONO_PROCESS_ERROR_NOT_FOUND;
181 while ((s = fgets (buf, blen, f))) {
184 if (strncmp (buf, item, len))
187 while (g_ascii_isspace (*s)) s++;
190 while (g_ascii_isspace (*s)) s++;
193 strncpy (rbuf, s, MIN (len, blen));
194 rbuf [MIN (len, blen) - 1] = 0;
196 *error = MONO_PROCESS_ERROR_NONE;
201 *error = MONO_PROCESS_ERROR_OTHER;
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
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).
215 mono_process_get_name (gpointer pid, char *buf, int len)
221 size_t data_len = sizeof (struct kinfo_proc2);
222 struct kinfo_proc2 processi;
225 size_t data_len = sizeof (struct kinfo_proc);
226 struct kinfo_proc processi;
227 #endif /* KERN_PROC2 */
229 memset (buf, 0, len);
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 */
239 res = sysctl (mib, 6, &processi, &data_len, NULL, 0);
241 if (res < 0 || data_len != sizeof (struct kinfo_proc2)) {
247 mib [2] = KERN_PROC_PID;
248 mib [3] = GPOINTER_TO_UINT (pid);
250 res = sysctl (mib, 4, &processi, &data_len, NULL, 0);
251 if (res < 0 || data_len != sizeof (struct kinfo_proc)) {
254 #endif /* KERN_PROC2 */
255 strncpy (buf, processi.kinfo_name_member, len - 1);
262 sprintf (fname, "/proc/%d/cmdline", GPOINTER_TO_INT (pid));
264 file = fopen (fname, "r");
267 r = fread (buf, 1, len - 1, file);
270 p = strrchr (buf, '/');
274 return get_pid_status_item_buf (GPOINTER_TO_INT (pid), "Name", buf, len, NULL);
281 * /proc/pid/stat format:
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
289 #define RET_ERROR(err) do { \
290 if (error) *error = (err); \
295 get_process_stat_item (int pid, int pos, int sum, MonoProcessError *error)
297 #if defined(__APPLE__)
298 double process_user_time = 0, process_system_time = 0;//, process_percent = 0;
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;
305 if (task_for_pid(mach_task_self(), pid, &task) != KERN_SUCCESS)
306 RET_ERROR (MONO_PROCESS_ERROR_NOT_FOUND);
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);
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);
318 for (i = 0; i < th_count; i++) {
319 double thread_user_time, thread_system_time;//, thread_percent;
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;
328 process_user_time += thread_user_time;
329 process_system_time += thread_system_time;
330 //process_percent += th_percent;
334 for (i = 0; i < th_count; i++)
335 mach_port_deallocate(task, th_array[i]);
337 mach_port_deallocate (mach_task_self (), task);
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;
342 if (pos == 10 && sum == TRUE)
343 return (gint64)((process_user_time + process_system_time) * 10000000);
345 return (gint64)(process_user_time * 10000000);
347 return (gint64)(process_system_time * 10000000);
357 g_snprintf (buf, sizeof (buf), "/proc/%d/stat", pid);
358 f = fopen (buf, "r");
360 RET_ERROR (MONO_PROCESS_ERROR_NOT_FOUND);
361 len = fread (buf, 1, sizeof (buf), f);
364 RET_ERROR (MONO_PROCESS_ERROR_OTHER);
365 s = strchr (buf, ')');
367 RET_ERROR (MONO_PROCESS_ERROR_OTHER);
369 while (g_ascii_isspace (*s)) s++;
371 RET_ERROR (MONO_PROCESS_ERROR_OTHER);
372 /* skip the status char */
373 while (*s && !g_ascii_isspace (*s)) s++;
375 RET_ERROR (MONO_PROCESS_ERROR_OTHER);
376 for (i = 0; i < pos; ++i) {
377 while (g_ascii_isspace (*s)) s++;
379 RET_ERROR (MONO_PROCESS_ERROR_OTHER);
380 while (*s && !g_ascii_isspace (*s)) s++;
382 RET_ERROR (MONO_PROCESS_ERROR_OTHER);
384 /* we are finally at the needed item */
385 value = strtoul (s, &end, 0);
386 /* add also the following value */
388 while (g_ascii_isspace (*s)) s++;
390 RET_ERROR (MONO_PROCESS_ERROR_OTHER);
391 value += strtoul (s, &end, 0);
394 *error = MONO_PROCESS_ERROR_NONE;
402 static int user_hz = 0;
405 user_hz = sysconf (_SC_CLK_TCK);
414 get_process_stat_time (int pid, int pos, int sum, MonoProcessError *error)
416 gint64 val = get_process_stat_item (pid, pos, sum, error);
417 #if defined(__APPLE__)
420 /* return 100ns ticks */
421 return (val * 10000000) / get_user_hz ();
426 get_pid_status_item (int pid, const char *item, MonoProcessError *error, int multiplier)
428 #if defined(__APPLE__)
429 // ignore the multiplier
433 struct task_basic_info t_info;
434 mach_msg_type_number_t th_count = TASK_BASIC_INFO_COUNT;
436 if (pid == getpid ()) {
437 /* task_for_pid () doesn't work on ios, even for the current process */
438 task = mach_task_self ();
440 if (task_for_pid (mach_task_self (), pid, &task) != KERN_SUCCESS)
441 RET_ERROR (MONO_PROCESS_ERROR_NOT_FOUND);
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);
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)
459 if (pid != getpid ())
460 mach_port_deallocate (mach_task_self (), task);
467 s = get_pid_status_item_buf (pid, item, buf, sizeof (buf), error);
469 return ((gint64) atol (s)) * multiplier;
475 * mono_process_get_data:
476 * @pid: pid of the process
477 * @data: description of data to return
479 * Return a data item of a process like user time, memory use etc,
480 * according to the @data argumet.
483 mono_process_get_data_with_error (gpointer pid, MonoProcessData data, MonoProcessError *error)
486 int rpid = GPOINTER_TO_INT (pid);
489 *error = MONO_PROCESS_ERROR_OTHER;
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);
505 val = get_pid_status_item (rpid, "VmRSS", error, 1024);
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);
514 val = get_pid_status_item (rpid, "VmSize", error, 1024);
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);
526 case MONO_PROCESS_END:
533 mono_process_get_data (gpointer pid, MonoProcessData data)
535 MonoProcessError error;
536 return mono_process_get_data_with_error (pid, data, &error);
540 mono_process_current_pid ()
542 #if defined(HAVE_UNISTD_H)
543 return (int) getpid ();
544 #elif defined(HOST_WIN32)
545 return (int) GetCurrentProcessId ();
554 * Return the number of processors on the system.
557 mono_cpu_count (void)
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.
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
572 if (present != -1 && read (present, (char*)buffer, sizeof (buffer)) > 3)
573 count = strtol (((char*)buffer) + 2, NULL, 10);
579 #ifdef _SC_NPROCESSORS_ONLN
580 count = sysconf (_SC_NPROCESSORS_ONLN);
587 size_t len = sizeof (int);
590 if (sysctl (mib, 2, &count, &len, NULL, 0) == 0)
597 GetSystemInfo (&info);
598 return info.dwNumberOfProcessors;
606 get_cpu_times (int cpu_id, gint64 *user, gint64 *systemt, gint64 *irq, gint64 *sirq, gint64 *idle)
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");
616 hz *= mono_cpu_count ();
617 while ((s = fgets (buf, sizeof (buf), f))) {
619 if (cpu_id < 0 && strncmp (s, "cpu", 3) == 0 && g_ascii_isspace (s [3])) {
621 } else if (cpu_id >= 0 && strncmp (s, "cpu", 3) == 0 && strtol (s + 3, &data, 10) == cpu_id) {
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);
641 *user = (user_ticks + nice_ticks) * 10000000 / hz;
643 *systemt = (system_ticks) * 10000000 / hz;
645 *irq = (irq_ticks) * 10000000 / hz;
647 *sirq = (sirq_ticks) * 10000000 / hz;
649 *idle = (idle_ticks) * 10000000 / hz;
654 * @cpu_id: processor number or -1 to get a summary of all the processors
655 * @data: type of data to retrieve
657 * Get data about a processor on the system, like time spent in user space or idle time.
660 mono_cpu_get_data (int cpu_id, MonoCpuData data, MonoProcessError *error)
665 *error = MONO_PROCESS_ERROR_NONE;
667 case MONO_CPU_USER_TIME:
668 get_cpu_times (cpu_id, &value, NULL, NULL, NULL, NULL);
670 case MONO_CPU_PRIV_TIME:
671 get_cpu_times (cpu_id, NULL, &value, NULL, NULL, NULL);
673 case MONO_CPU_INTR_TIME:
674 get_cpu_times (cpu_id, NULL, NULL, &value, NULL, NULL);
676 case MONO_CPU_DCP_TIME:
677 get_cpu_times (cpu_id, NULL, NULL, NULL, &value, NULL);
679 case MONO_CPU_IDLE_TIME:
680 get_cpu_times (cpu_id, NULL, NULL, NULL, NULL, &value);
691 mono_atexit (void (*func)(void))
693 #ifdef PLATFORM_ANDROID
694 /* Some versions of android libc doesn't define atexit () */
697 return atexit (func);
702 mono_cpu_usage (MonoCpuUsageState *prev)
704 gint32 cpu_usage = 0;
705 gint64 cpu_total_time;
706 gint64 cpu_busy_time;
709 struct rusage resource_usage;
714 if (getrusage (RUSAGE_SELF, &resource_usage) == -1) {
715 g_error ("getrusage() failed, errno is %d (%s)\n", errno, strerror (errno));
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;
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 ();
727 prev->kernel_time = kernel_time;
728 prev->user_time = user_time;
729 prev->current_time = current_time;
736 if (!GetSystemTimes ((FILETIME*) &idle_time, (FILETIME*) &kernel_time, (FILETIME*) &user_time)) {
737 g_error ("GetSystemTimes() failed, error code is %d\n", GetLastError ());
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)));
745 prev->idle_time = idle_time;
746 prev->kernel_time = kernel_time;
747 prev->user_time = user_time;
751 if (cpu_total_time > 0 && cpu_busy_time > 0)
752 cpu_usage = (gint32)(cpu_busy_time * 100 / cpu_total_time);
754 g_assert (cpu_usage >= 0);
755 g_assert (cpu_usage <= 100);