2 * Copyright 2008-2011 Novell Inc
3 * Copyright 2011 Xamarin Inc
7 #include "utils/mono-proclib.h"
22 #if defined(__APPLE__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__)
23 #include <sys/param.h>
24 #include <sys/types.h>
25 #include <sys/sysctl.h>
27 #if defined(__APPLE__)
28 #include <mach/mach.h>
30 #ifdef HAVE_SYS_USER_H
33 #ifdef HAVE_STRUCT_KINFO_PROC_KP_PROC
34 # define kinfo_pid_member kp_proc.p_pid
35 # define kinfo_name_member kp_proc.p_comm
36 #elif defined(__OpenBSD__)
37 # define kinfo_pid_member p_pid
38 # define kinfo_name_member p_comm
40 #define kinfo_pid_member ki_pid
41 #define kinfo_name_member ki_comm
48 * @size: a pointer to a location where the size of the returned array is stored
50 * Return an array of pid values for the processes currently running on the system.
51 * The size of the array is stored in @size.
54 mono_process_list (int *size)
60 size_t data_len = sizeof (struct kinfo_proc2) * 400;
61 struct kinfo_proc2 *processes = malloc (data_len);
64 size_t data_len = sizeof (struct kinfo_proc) * 400;
65 struct kinfo_proc *processes = malloc (data_len);
66 #endif /* KERN_PROC2 */
77 mib [2] = KERN_PROC_ALL;
79 mib [4] = sizeof(struct kinfo_proc2);
80 mib [5] = 400; /* XXX */
82 res = sysctl (mib, 6, processes, &data_len, NULL, 0);
86 mib [2] = KERN_PROC_ALL;
89 res = sysctl (mib, 4, processes, &data_len, NULL, 0);
90 #endif /* KERN_PROC2 */
97 res = data_len/sizeof (struct kinfo_proc2);
99 res = data_len/sizeof (struct kinfo_proc);
100 #endif /* KERN_PROC2 */
101 buf = g_realloc (buf, res * sizeof (void*));
102 for (i = 0; i < res; ++i)
103 buf [i] = GINT_TO_POINTER (processes [i].kinfo_pid_member);
113 GDir *dir = g_dir_open ("/proc/", 0, NULL);
119 while ((name = g_dir_read_name (dir))) {
122 pid = strtol (name, &nend, 10);
123 if (pid <= 0 || nend == name || *nend)
130 buf = g_realloc (buf, count * sizeof (void*));
132 buf [i++] = GINT_TO_POINTER (pid);
141 static G_GNUC_UNUSED char*
142 get_pid_status_item_buf (int pid, const char *item, char *rbuf, int blen, MonoProcessError *error)
147 int len = strlen (item);
149 g_snprintf (buf, sizeof (buf), "/proc/%d/status", pid);
150 f = fopen (buf, "r");
153 *error = MONO_PROCESS_ERROR_NOT_FOUND;
156 while ((s = fgets (buf, blen, f))) {
159 if (strncmp (buf, item, len))
162 while (g_ascii_isspace (*s)) s++;
165 while (g_ascii_isspace (*s)) s++;
168 strncpy (rbuf, s, MIN (len, blen));
169 rbuf [MIN (len, blen) - 1] = 0;
171 *error = MONO_PROCESS_ERROR_NONE;
176 *error = MONO_PROCESS_ERROR_OTHER;
181 * mono_process_get_name:
182 * @pid: pid of the process
183 * @buf: byte buffer where to store the name of the prcoess
184 * @len: size of the buffer @buf
186 * Return the name of the process identified by @pid, storing it
187 * inside @buf for a maximum of len bytes (including the terminating 0).
190 mono_process_get_name (gpointer pid, char *buf, int len)
196 size_t data_len = sizeof (struct kinfo_proc2);
197 struct kinfo_proc2 processi;
200 size_t data_len = sizeof (struct kinfo_proc);
201 struct kinfo_proc processi;
202 #endif /* KERN_PROC2 */
204 memset (buf, 0, len);
208 mib [1] = KERN_PROC2;
209 mib [2] = KERN_PROC_PID;
210 mib [3] = GPOINTER_TO_UINT (pid);
211 mib [4] = sizeof(struct kinfo_proc2);
212 mib [5] = 400; /* XXX */
214 res = sysctl (mib, 6, &processi, &data_len, NULL, 0);
216 if (res < 0 || data_len != sizeof (struct kinfo_proc2)) {
222 mib [2] = KERN_PROC_PID;
223 mib [3] = GPOINTER_TO_UINT (pid);
225 res = sysctl (mib, 4, &processi, &data_len, NULL, 0);
226 if (res < 0 || data_len != sizeof (struct kinfo_proc)) {
229 #endif /* KERN_PROC2 */
230 strncpy (buf, processi.kinfo_name_member, len - 1);
237 sprintf (fname, "/proc/%d/cmdline", GPOINTER_TO_INT (pid));
239 file = fopen (fname, "r");
242 r = fread (buf, 1, len - 1, file);
245 p = strrchr (buf, '/');
249 return get_pid_status_item_buf (GPOINTER_TO_INT (pid), "Name", buf, len, NULL);
256 * /proc/pid/stat format:
258 * [0] ppid pgid sid tty_nr tty_pgrp flags min_flt cmin_flt maj_flt cmaj_flt
259 * [10] utime stime cutime cstime prio nice threads 0 start_time vsize rss
260 * [20] rss rsslim start_code end_code start_stack esp eip pending blocked sigign
261 * [30] sigcatch wchan 0 0 exit_signal cpu rt_prio policy
264 #define RET_ERROR(err) do { \
265 if (error) *error = (err); \
270 get_process_stat_item (int pid, int pos, int sum, MonoProcessError *error)
272 #if defined(__APPLE__)
273 double process_user_time = 0, process_system_time = 0;//, process_percent = 0;
275 struct task_basic_info t_info;
276 mach_msg_type_number_t t_info_count = TASK_BASIC_INFO_COUNT, th_count;
277 thread_array_t th_array;
280 if (task_for_pid(mach_task_self(), pid, &task) != KERN_SUCCESS)
281 RET_ERROR (MONO_PROCESS_ERROR_NOT_FOUND);
283 if (task_info(task, TASK_BASIC_INFO, (task_info_t)&t_info, &t_info_count) != KERN_SUCCESS) {
284 mach_port_deallocate (mach_task_self (), task);
285 RET_ERROR (MONO_PROCESS_ERROR_OTHER);
288 if (task_threads(task, &th_array, &th_count) != KERN_SUCCESS) {
289 mach_port_deallocate (mach_task_self (), task);
290 RET_ERROR (MONO_PROCESS_ERROR_OTHER);
293 for (i = 0; i < th_count; i++) {
294 double thread_user_time, thread_system_time;//, thread_percent;
296 struct thread_basic_info th_info;
297 mach_msg_type_number_t th_info_count = THREAD_BASIC_INFO_COUNT;
298 if (thread_info(th_array[i], THREAD_BASIC_INFO, (thread_info_t)&th_info, &th_info_count) == KERN_SUCCESS) {
299 thread_user_time = th_info.user_time.seconds + th_info.user_time.microseconds / 1e6;
300 thread_system_time = th_info.system_time.seconds + th_info.system_time.microseconds / 1e6;
301 //thread_percent = (double)th_info.cpu_usage / TH_USAGE_SCALE;
303 process_user_time += thread_user_time;
304 process_system_time += thread_system_time;
305 //process_percent += th_percent;
309 for (i = 0; i < th_count; i++)
310 mach_port_deallocate(task, th_array[i]);
312 mach_port_deallocate (mach_task_self (), task);
314 process_user_time += t_info.user_time.seconds + t_info.user_time.microseconds / 1e6;
315 process_system_time += t_info.system_time.seconds + t_info.system_time.microseconds / 1e6;
317 if (pos == 10 && sum == TRUE)
318 return (gint64)((process_user_time + process_system_time) * 10000000);
320 return (gint64)(process_user_time * 10000000);
322 return (gint64)(process_system_time * 10000000);
332 g_snprintf (buf, sizeof (buf), "/proc/%d/stat", pid);
333 f = fopen (buf, "r");
335 RET_ERROR (MONO_PROCESS_ERROR_NOT_FOUND);
336 len = fread (buf, 1, sizeof (buf), f);
339 RET_ERROR (MONO_PROCESS_ERROR_OTHER);
340 s = strchr (buf, ')');
342 RET_ERROR (MONO_PROCESS_ERROR_OTHER);
344 while (g_ascii_isspace (*s)) s++;
346 RET_ERROR (MONO_PROCESS_ERROR_OTHER);
347 /* skip the status char */
348 while (*s && !g_ascii_isspace (*s)) s++;
350 RET_ERROR (MONO_PROCESS_ERROR_OTHER);
351 for (i = 0; i < pos; ++i) {
352 while (g_ascii_isspace (*s)) s++;
354 RET_ERROR (MONO_PROCESS_ERROR_OTHER);
355 while (*s && !g_ascii_isspace (*s)) s++;
357 RET_ERROR (MONO_PROCESS_ERROR_OTHER);
359 /* we are finally at the needed item */
360 value = strtoul (s, &end, 0);
361 /* add also the following value */
363 while (g_ascii_isspace (*s)) s++;
365 RET_ERROR (MONO_PROCESS_ERROR_OTHER);
366 value += strtoul (s, &end, 0);
369 *error = MONO_PROCESS_ERROR_NONE;
377 static int user_hz = 0;
380 user_hz = sysconf (_SC_CLK_TCK);
389 get_process_stat_time (int pid, int pos, int sum, MonoProcessError *error)
391 gint64 val = get_process_stat_item (pid, pos, sum, error);
392 #if defined(__APPLE__)
395 /* return 100ns ticks */
396 return (val * 10000000) / get_user_hz ();
401 get_pid_status_item (int pid, const char *item, MonoProcessError *error, int multiplier)
403 #if defined(__APPLE__)
404 // ignore the multiplier
408 struct task_basic_info t_info;
409 mach_msg_type_number_t th_count = TASK_BASIC_INFO_COUNT;
411 if (pid == getpid ()) {
412 /* task_for_pid () doesn't work on ios, even for the current process */
413 task = mach_task_self ();
415 if (task_for_pid (mach_task_self (), pid, &task) != KERN_SUCCESS)
416 RET_ERROR (MONO_PROCESS_ERROR_NOT_FOUND);
419 if (task_info (task, TASK_BASIC_INFO, (task_info_t)&t_info, &th_count) != KERN_SUCCESS) {
420 if (pid != getpid ())
421 mach_port_deallocate (mach_task_self (), task);
422 RET_ERROR (MONO_PROCESS_ERROR_OTHER);
425 if (strcmp (item, "VmRSS") == 0 || strcmp (item, "VmHWM") == 0 || strcmp (item, "VmData") == 0)
426 ret = t_info.resident_size;
427 else if (strcmp (item, "VmSize") == 0 || strcmp (item, "VmPeak") == 0)
428 ret = t_info.virtual_size;
429 else if (strcmp (item, "Threads") == 0)
434 if (pid != getpid ())
435 mach_port_deallocate (mach_task_self (), task);
442 s = get_pid_status_item_buf (pid, item, buf, sizeof (buf), error);
444 return ((gint64) atol (s)) * multiplier;
450 * mono_process_get_data:
451 * @pid: pid of the process
452 * @data: description of data to return
454 * Return a data item of a process like user time, memory use etc,
455 * according to the @data argumet.
458 mono_process_get_data_with_error (gpointer pid, MonoProcessData data, MonoProcessError *error)
461 int rpid = GPOINTER_TO_INT (pid);
464 *error = MONO_PROCESS_ERROR_OTHER;
467 case MONO_PROCESS_NUM_THREADS:
468 return get_pid_status_item (rpid, "Threads", error, 1);
469 case MONO_PROCESS_USER_TIME:
470 return get_process_stat_time (rpid, 10, FALSE, error);
471 case MONO_PROCESS_SYSTEM_TIME:
472 return get_process_stat_time (rpid, 11, FALSE, error);
473 case MONO_PROCESS_TOTAL_TIME:
474 return get_process_stat_time (rpid, 10, TRUE, error);
475 case MONO_PROCESS_WORKING_SET:
476 return get_pid_status_item (rpid, "VmRSS", error, 1024);
477 case MONO_PROCESS_WORKING_SET_PEAK:
478 val = get_pid_status_item (rpid, "VmHWM", error, 1024);
480 val = get_pid_status_item (rpid, "VmRSS", error, 1024);
482 case MONO_PROCESS_PRIVATE_BYTES:
483 return get_pid_status_item (rpid, "VmData", error, 1024);
484 case MONO_PROCESS_VIRTUAL_BYTES:
485 return get_pid_status_item (rpid, "VmSize", error, 1024);
486 case MONO_PROCESS_VIRTUAL_BYTES_PEAK:
487 val = get_pid_status_item (rpid, "VmPeak", error, 1024);
489 val = get_pid_status_item (rpid, "VmSize", error, 1024);
491 case MONO_PROCESS_FAULTS:
492 return get_process_stat_item (rpid, 6, TRUE, error);
493 case MONO_PROCESS_ELAPSED:
494 return get_process_stat_item (rpid, 18, FALSE, error) / get_user_hz ();
495 case MONO_PROCESS_PPID:
496 return get_process_stat_time (rpid, 0, FALSE, error);
499 case MONO_PROCESS_END:
506 mono_process_get_data (gpointer pid, MonoProcessData data)
508 MonoProcessError error;
509 return mono_process_get_data_with_error (pid, data, &error);
513 mono_process_current_pid ()
515 #if defined(HAVE_UNISTD_H)
516 return (int) getpid ();
517 #elif defined(HOST_WIN32)
518 return (int) GetCurrentProcessId ();
527 * Return the number of processors on the system.
530 mono_cpu_count (void)
533 #ifdef PLATFORM_ANDROID
534 /* Android tries really hard to save power by powering off CPUs on SMP phones which
535 * means the normal way to query cpu count returns a wrong value with userspace API.
536 * Instead we use /sys entries to query the actual hardware CPU count.
538 char buffer[8] = {'\0'};
539 int present = open ("/sys/devices/system/cpu/present", O_RDONLY);
540 /* Format of the /sys entry is a cpulist of indexes which in the case
541 * of present is always of the form "0-(n-1)" when there is more than
542 * 1 core, n being the number of CPU cores in the system. Otherwise
543 * the value is simply 0
545 if (present != -1 && read (present, (char*)buffer, sizeof (buffer)) > 3)
546 count = strtol (((char*)buffer) + 2, NULL, 10);
552 #ifdef _SC_NPROCESSORS_ONLN
553 count = sysconf (_SC_NPROCESSORS_ONLN);
560 size_t len = sizeof (int);
563 if (sysctl (mib, 2, &count, &len, NULL, 0) == 0)
570 GetSystemInfo (&info);
571 return info.dwNumberOfProcessors;
579 get_cpu_times (int cpu_id, gint64 *user, gint64 *systemt, gint64 *irq, gint64 *sirq, gint64 *idle)
583 int hz = get_user_hz ();
584 guint64 user_ticks = 0, nice_ticks = 0, system_ticks = 0, idle_ticks = 0, irq_ticks = 0, sirq_ticks = 0;
585 FILE *f = fopen ("/proc/stat", "r");
589 hz *= mono_cpu_count ();
590 while ((s = fgets (buf, sizeof (buf), f))) {
592 if (cpu_id < 0 && strncmp (s, "cpu", 3) == 0 && g_ascii_isspace (s [3])) {
594 } else if (cpu_id >= 0 && strncmp (s, "cpu", 3) == 0 && strtol (s + 3, &data, 10) == cpu_id) {
602 user_ticks = strtoull (data, &data, 10);
603 nice_ticks = strtoull (data, &data, 10);
604 system_ticks = strtoull (data, &data, 10);
605 idle_ticks = strtoull (data, &data, 10);
606 /* iowait_ticks = strtoull (data, &data, 10); */
607 irq_ticks = strtoull (data, &data, 10);
608 sirq_ticks = strtoull (data, &data, 10);
614 *user = (user_ticks + nice_ticks) * 10000000 / hz;
616 *systemt = (system_ticks) * 10000000 / hz;
618 *irq = (irq_ticks) * 10000000 / hz;
620 *sirq = (sirq_ticks) * 10000000 / hz;
622 *idle = (idle_ticks) * 10000000 / hz;
627 * @cpu_id: processor number or -1 to get a summary of all the processors
628 * @data: type of data to retrieve
630 * Get data about a processor on the system, like time spent in user space or idle time.
633 mono_cpu_get_data (int cpu_id, MonoCpuData data, MonoProcessError *error)
638 *error = MONO_PROCESS_ERROR_NONE;
640 case MONO_CPU_USER_TIME:
641 get_cpu_times (cpu_id, &value, NULL, NULL, NULL, NULL);
643 case MONO_CPU_PRIV_TIME:
644 get_cpu_times (cpu_id, NULL, &value, NULL, NULL, NULL);
646 case MONO_CPU_INTR_TIME:
647 get_cpu_times (cpu_id, NULL, NULL, &value, NULL, NULL);
649 case MONO_CPU_DCP_TIME:
650 get_cpu_times (cpu_id, NULL, NULL, NULL, &value, NULL);
652 case MONO_CPU_IDLE_TIME:
653 get_cpu_times (cpu_id, NULL, NULL, NULL, NULL, &value);