2 * Copyright 2008-2011 Novell Inc
3 * Copyright 2011 Xamarin Inc
7 #include "utils/mono-proclib.h"
21 #if defined(__APPLE__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__)
22 #include <sys/param.h>
23 #include <sys/types.h>
24 #include <sys/sysctl.h>
26 #if defined(__APPLE__)
27 #include <mach/mach.h>
29 #ifdef HAVE_SYS_USER_H
32 #ifdef HAVE_STRUCT_KINFO_PROC_KP_PROC
33 # define kinfo_pid_member kp_proc.p_pid
34 # define kinfo_name_member kp_proc.p_comm
35 #elif defined(__OpenBSD__)
36 # define kinfo_pid_member p_pid
37 # define kinfo_name_member p_comm
39 #define kinfo_pid_member ki_pid
40 #define kinfo_name_member ki_comm
47 * @size: a pointer to a location where the size of the returned array is stored
49 * Return an array of pid values for the processes currently running on the system.
50 * The size of the array is stored in @size.
53 mono_process_list (int *size)
59 size_t data_len = sizeof (struct kinfo_proc2) * 400;
60 struct kinfo_proc2 *processes = malloc (data_len);
63 size_t data_len = sizeof (struct kinfo_proc) * 400;
64 struct kinfo_proc *processes = malloc (data_len);
65 #endif /* KERN_PROC2 */
76 mib [2] = KERN_PROC_ALL;
78 mib [4] = sizeof(struct kinfo_proc2);
79 mib [5] = 400; /* XXX */
81 res = sysctl (mib, 6, processes, &data_len, NULL, 0);
85 mib [2] = KERN_PROC_ALL;
88 res = sysctl (mib, 4, processes, &data_len, NULL, 0);
89 #endif /* KERN_PROC2 */
96 res = data_len/sizeof (struct kinfo_proc2);
98 res = data_len/sizeof (struct kinfo_proc);
99 #endif /* KERN_PROC2 */
100 buf = g_realloc (buf, res * sizeof (void*));
101 for (i = 0; i < res; ++i)
102 buf [i] = GINT_TO_POINTER (processes [i].kinfo_pid_member);
112 GDir *dir = g_dir_open ("/proc/", 0, NULL);
118 while ((name = g_dir_read_name (dir))) {
121 pid = strtol (name, &nend, 10);
122 if (pid <= 0 || nend == name || *nend)
129 buf = g_realloc (buf, count * sizeof (void*));
131 buf [i++] = GINT_TO_POINTER (pid);
140 static G_GNUC_UNUSED char*
141 get_pid_status_item_buf (int pid, const char *item, char *rbuf, int blen, MonoProcessError *error)
146 int len = strlen (item);
148 g_snprintf (buf, sizeof (buf), "/proc/%d/status", pid);
149 f = fopen (buf, "r");
152 *error = MONO_PROCESS_ERROR_NOT_FOUND;
155 while ((s = fgets (buf, blen, f))) {
158 if (strncmp (buf, item, len))
161 while (g_ascii_isspace (*s)) s++;
164 while (g_ascii_isspace (*s)) s++;
167 strncpy (rbuf, s, MIN (len, blen));
168 rbuf [MIN (len, blen) - 1] = 0;
170 *error = MONO_PROCESS_ERROR_NONE;
175 *error = MONO_PROCESS_ERROR_OTHER;
180 * mono_process_get_name:
181 * @pid: pid of the process
182 * @buf: byte buffer where to store the name of the prcoess
183 * @len: size of the buffer @buf
185 * Return the name of the process identified by @pid, storing it
186 * inside @buf for a maximum of len bytes (including the terminating 0).
189 mono_process_get_name (gpointer pid, char *buf, int len)
195 size_t data_len = sizeof (struct kinfo_proc2);
196 struct kinfo_proc2 processi;
199 size_t data_len = sizeof (struct kinfo_proc);
200 struct kinfo_proc processi;
201 #endif /* KERN_PROC2 */
203 memset (buf, 0, len);
207 mib [1] = KERN_PROC2;
208 mib [2] = KERN_PROC_PID;
209 mib [3] = GPOINTER_TO_UINT (pid);
210 mib [4] = sizeof(struct kinfo_proc2);
211 mib [5] = 400; /* XXX */
213 res = sysctl (mib, 6, &processi, &data_len, NULL, 0);
215 if (res < 0 || data_len != sizeof (struct kinfo_proc2)) {
221 mib [2] = KERN_PROC_PID;
222 mib [3] = GPOINTER_TO_UINT (pid);
224 res = sysctl (mib, 4, &processi, &data_len, NULL, 0);
225 if (res < 0 || data_len != sizeof (struct kinfo_proc)) {
228 #endif /* KERN_PROC2 */
229 strncpy (buf, processi.kinfo_name_member, len - 1);
236 sprintf (fname, "/proc/%d/cmdline", GPOINTER_TO_INT (pid));
238 file = fopen (fname, "r");
241 r = fread (buf, 1, len - 1, file);
244 p = strrchr (buf, '/');
248 return get_pid_status_item_buf (GPOINTER_TO_INT (pid), "Name", buf, len, NULL);
255 * /proc/pid/stat format:
257 * [0] ppid pgid sid tty_nr tty_pgrp flags min_flt cmin_flt maj_flt cmaj_flt
258 * [10] utime stime cutime cstime prio nice threads 0 start_time vsize rss
259 * [20] rss rsslim start_code end_code start_stack esp eip pending blocked sigign
260 * [30] sigcatch wchan 0 0 exit_signal cpu rt_prio policy
263 #define RET_ERROR(err) do { \
264 if (error) *error = (err); \
269 get_process_stat_item (int pid, int pos, int sum, MonoProcessError *error)
271 #if defined(__APPLE__)
272 double process_user_time = 0, process_system_time = 0;//, process_percent = 0;
274 struct task_basic_info t_info;
275 mach_msg_type_number_t t_info_count = TASK_BASIC_INFO_COUNT, th_count;
276 thread_array_t th_array;
279 if (task_for_pid(mach_task_self(), pid, &task) != KERN_SUCCESS)
280 RET_ERROR (MONO_PROCESS_ERROR_NOT_FOUND);
282 if (task_info(task, TASK_BASIC_INFO, (task_info_t)&t_info, &t_info_count) != KERN_SUCCESS) {
283 mach_port_deallocate (mach_task_self (), task);
284 RET_ERROR (MONO_PROCESS_ERROR_OTHER);
287 if (task_threads(task, &th_array, &th_count) != KERN_SUCCESS) {
288 mach_port_deallocate (mach_task_self (), task);
289 RET_ERROR (MONO_PROCESS_ERROR_OTHER);
292 for (i = 0; i < th_count; i++) {
293 double thread_user_time, thread_system_time;//, thread_percent;
295 struct thread_basic_info th_info;
296 mach_msg_type_number_t th_info_count = THREAD_BASIC_INFO_COUNT;
297 if (thread_info(th_array[i], THREAD_BASIC_INFO, (thread_info_t)&th_info, &th_info_count) == KERN_SUCCESS) {
298 thread_user_time = th_info.user_time.seconds + th_info.user_time.microseconds / 1e6;
299 thread_system_time = th_info.system_time.seconds + th_info.system_time.microseconds / 1e6;
300 //thread_percent = (double)th_info.cpu_usage / TH_USAGE_SCALE;
302 process_user_time += thread_user_time;
303 process_system_time += thread_system_time;
304 //process_percent += th_percent;
308 for (i = 0; i < th_count; i++)
309 mach_port_deallocate(task, th_array[i]);
311 mach_port_deallocate (mach_task_self (), task);
313 process_user_time += t_info.user_time.seconds + t_info.user_time.microseconds / 1e6;
314 process_system_time += t_info.system_time.seconds + t_info.system_time.microseconds / 1e6;
316 if (pos == 10 && sum == TRUE)
317 return (gint64)((process_user_time + process_system_time) * 10000000);
319 return (gint64)(process_user_time * 10000000);
321 return (gint64)(process_system_time * 10000000);
331 g_snprintf (buf, sizeof (buf), "/proc/%d/stat", pid);
332 f = fopen (buf, "r");
334 RET_ERROR (MONO_PROCESS_ERROR_NOT_FOUND);
335 len = fread (buf, 1, sizeof (buf), f);
338 RET_ERROR (MONO_PROCESS_ERROR_OTHER);
339 s = strchr (buf, ')');
341 RET_ERROR (MONO_PROCESS_ERROR_OTHER);
343 while (g_ascii_isspace (*s)) s++;
345 RET_ERROR (MONO_PROCESS_ERROR_OTHER);
346 /* skip the status char */
347 while (*s && !g_ascii_isspace (*s)) s++;
349 RET_ERROR (MONO_PROCESS_ERROR_OTHER);
350 for (i = 0; i < pos; ++i) {
351 while (g_ascii_isspace (*s)) s++;
353 RET_ERROR (MONO_PROCESS_ERROR_OTHER);
354 while (*s && !g_ascii_isspace (*s)) s++;
356 RET_ERROR (MONO_PROCESS_ERROR_OTHER);
358 /* we are finally at the needed item */
359 value = strtoul (s, &end, 0);
360 /* add also the following value */
362 while (g_ascii_isspace (*s)) s++;
364 RET_ERROR (MONO_PROCESS_ERROR_OTHER);
365 value += strtoul (s, &end, 0);
368 *error = MONO_PROCESS_ERROR_NONE;
376 static int user_hz = 0;
379 user_hz = sysconf (_SC_CLK_TCK);
388 get_process_stat_time (int pid, int pos, int sum, MonoProcessError *error)
390 gint64 val = get_process_stat_item (pid, pos, sum, error);
391 #if defined(__APPLE__)
394 /* return 100ns ticks */
395 return (val * 10000000) / get_user_hz ();
400 get_pid_status_item (int pid, const char *item, MonoProcessError *error, int multiplier)
402 #if defined(__APPLE__)
403 // ignore the multiplier
407 struct task_basic_info t_info;
408 mach_msg_type_number_t th_count = TASK_BASIC_INFO_COUNT;
410 if (task_for_pid (mach_task_self (), pid, &task) != KERN_SUCCESS)
411 RET_ERROR (MONO_PROCESS_ERROR_NOT_FOUND);
413 if (task_info (task, TASK_BASIC_INFO, (task_info_t)&t_info, &th_count) != KERN_SUCCESS) {
414 mach_port_deallocate (mach_task_self (), task);
415 RET_ERROR (MONO_PROCESS_ERROR_OTHER);
418 if (strcmp (item, "VmRSS") == 0 || strcmp (item, "VmHWM") == 0)
419 ret = t_info.resident_size;
420 else if (strcmp (item, "VmSize") == 0 || strcmp (item, "VmPeak") == 0)
421 ret = t_info.virtual_size;
422 else if (strcmp (item, "Threads") == 0)
427 mach_port_deallocate (mach_task_self (), task);
434 s = get_pid_status_item_buf (pid, item, buf, sizeof (buf), error);
436 return ((gint64) atol (s)) * multiplier;
442 * mono_process_get_data:
443 * @pid: pid of the process
444 * @data: description of data to return
446 * Return a data item of a process like user time, memory use etc,
447 * according to the @data argumet.
450 mono_process_get_data_with_error (gpointer pid, MonoProcessData data, MonoProcessError *error)
453 int rpid = GPOINTER_TO_INT (pid);
456 *error = MONO_PROCESS_ERROR_OTHER;
459 case MONO_PROCESS_NUM_THREADS:
460 return get_pid_status_item (rpid, "Threads", error, 1);
461 case MONO_PROCESS_USER_TIME:
462 return get_process_stat_time (rpid, 10, FALSE, error);
463 case MONO_PROCESS_SYSTEM_TIME:
464 return get_process_stat_time (rpid, 11, FALSE, error);
465 case MONO_PROCESS_TOTAL_TIME:
466 return get_process_stat_time (rpid, 10, TRUE, error);
467 case MONO_PROCESS_WORKING_SET:
468 return get_pid_status_item (rpid, "VmRSS", error, 1024);
469 case MONO_PROCESS_WORKING_SET_PEAK:
470 val = get_pid_status_item (rpid, "VmHWM", error, 1024);
472 val = get_pid_status_item (rpid, "VmRSS", error, 1024);
474 case MONO_PROCESS_PRIVATE_BYTES:
475 return get_pid_status_item (rpid, "VmData", error, 1024);
476 case MONO_PROCESS_VIRTUAL_BYTES:
477 return get_pid_status_item (rpid, "VmSize", error, 1024);
478 case MONO_PROCESS_VIRTUAL_BYTES_PEAK:
479 val = get_pid_status_item (rpid, "VmPeak", error, 1024);
481 val = get_pid_status_item (rpid, "VmSize", error, 1024);
483 case MONO_PROCESS_FAULTS:
484 return get_process_stat_item (rpid, 6, TRUE, error);
485 case MONO_PROCESS_ELAPSED:
486 return get_process_stat_item (rpid, 18, FALSE, error) / get_user_hz ();
487 case MONO_PROCESS_PPID:
488 return get_process_stat_time (rpid, 0, FALSE, error);
491 case MONO_PROCESS_END:
498 mono_process_get_data (gpointer pid, MonoProcessData data)
500 MonoProcessError error;
501 return mono_process_get_data_with_error (pid, data, &error);
507 * Return the number of processors on the system.
510 mono_cpu_count (void)
513 #ifdef PLATFORM_ANDROID
514 /* Android tries really hard to save power by powering off CPUs on SMP phones which
515 * means the normal way to query cpu count returns a wrong value with userspace API.
516 * Instead we use /sys entries to query the actual hardware CPU count.
518 char buffer[8] = {'\0'};
519 int present = open ("/sys/devices/system/cpu/present", O_RDONLY);
520 /* Format of the /sys entry is a cpulist of indexes which in the case
521 * of present is always of the form "0-(n-1)" when there is more than
522 * 1 core, n being the number of CPU cores in the system. Otherwise
523 * the value is simply 0
525 if (present != -1 && read (present, (char*)buffer, sizeof (buffer)) > 3)
526 count = strtol (((char*)buffer) + 2, NULL, 10);
532 #ifdef _SC_NPROCESSORS_ONLN
533 count = sysconf (_SC_NPROCESSORS_ONLN);
540 size_t len = sizeof (int);
543 if (sysctl (mib, 2, &count, &len, NULL, 0) == 0)
550 GetSystemInfo (&info);
551 return info.dwNumberOfProcessors;
559 get_cpu_times (int cpu_id, gint64 *user, gint64 *systemt, gint64 *irq, gint64 *sirq, gint64 *idle)
563 int hz = get_user_hz ();
564 guint64 user_ticks = 0, nice_ticks = 0, system_ticks = 0, idle_ticks = 0, iowait_ticks, irq_ticks = 0, sirq_ticks = 0;
565 FILE *f = fopen ("/proc/stat", "r");
569 hz *= mono_cpu_count ();
570 while ((s = fgets (buf, sizeof (buf), f))) {
572 if (cpu_id < 0 && strncmp (s, "cpu", 3) == 0 && g_ascii_isspace (s [3])) {
574 } else if (cpu_id >= 0 && strncmp (s, "cpu", 3) == 0 && strtol (s + 3, &data, 10) == cpu_id) {
582 user_ticks = strtoull (data, &data, 10);
583 nice_ticks = strtoull (data, &data, 10);
584 system_ticks = strtoull (data, &data, 10);
585 idle_ticks = strtoull (data, &data, 10);
586 iowait_ticks = strtoull (data, &data, 10);
587 irq_ticks = strtoull (data, &data, 10);
588 sirq_ticks = strtoull (data, &data, 10);
594 *user = (user_ticks + nice_ticks) * 10000000 / hz;
596 *systemt = (system_ticks) * 10000000 / hz;
598 *irq = (irq_ticks) * 10000000 / hz;
600 *sirq = (sirq_ticks) * 10000000 / hz;
602 *idle = (idle_ticks) * 10000000 / hz;
607 * @cpu_id: processor number or -1 to get a summary of all the processors
608 * @data: type of data to retrieve
610 * Get data about a processor on the system, like time spent in user space or idle time.
613 mono_cpu_get_data (int cpu_id, MonoCpuData data, MonoProcessError *error)
618 *error = MONO_PROCESS_ERROR_NONE;
620 case MONO_CPU_USER_TIME:
621 get_cpu_times (cpu_id, &value, NULL, NULL, NULL, NULL);
623 case MONO_CPU_PRIV_TIME:
624 get_cpu_times (cpu_id, NULL, &value, NULL, NULL, NULL);
626 case MONO_CPU_INTR_TIME:
627 get_cpu_times (cpu_id, NULL, NULL, &value, NULL, NULL);
629 case MONO_CPU_DCP_TIME:
630 get_cpu_times (cpu_id, NULL, NULL, NULL, &value, NULL);
632 case MONO_CPU_IDLE_TIME:
633 get_cpu_times (cpu_id, NULL, NULL, NULL, NULL, &value);