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/errno.h>
24 #include <sys/param.h>
25 #include <sys/types.h>
26 #include <sys/sysctl.h>
28 #if defined(__APPLE__)
29 #include <mach/mach.h>
31 #ifdef HAVE_SYS_USER_H
34 #ifdef HAVE_STRUCT_KINFO_PROC_KP_PROC
35 # define kinfo_pid_member kp_proc.p_pid
36 # define kinfo_name_member kp_proc.p_comm
37 #elif defined(__OpenBSD__)
38 # define kinfo_pid_member p_pid
39 # define kinfo_name_member p_comm
41 #define kinfo_pid_member ki_pid
42 #define kinfo_name_member ki_comm
49 * @size: a pointer to a location where the size of the returned array is stored
51 * Return an array of pid values for the processes currently running on the system.
52 * The size of the array is stored in @size.
55 mono_process_list (int *size)
61 size_t data_len = sizeof (struct kinfo_proc2) * 400;
62 struct kinfo_proc2 *processes = malloc (data_len);
65 size_t data_len = sizeof (struct kinfo_proc) * 16;
66 struct kinfo_proc *processes;
68 #endif /* KERN_PROC2 */
80 mib [2] = KERN_PROC_ALL;
82 mib [4] = sizeof(struct kinfo_proc2);
83 mib [5] = 400; /* XXX */
85 res = sysctl (mib, 6, processes, &data_len, NULL, 0);
95 mib [2] = KERN_PROC_ALL;
98 res = sysctl (mib, 4, NULL, &data_len, NULL, 0);
101 processes = malloc (data_len);
102 res = sysctl (mib, 4, processes, &data_len, NULL, 0);
112 #endif /* KERN_PROC2 */
115 res = data_len/sizeof (struct kinfo_proc2);
117 res = data_len/sizeof (struct kinfo_proc);
118 #endif /* KERN_PROC2 */
119 buf = g_realloc (buf, res * sizeof (void*));
120 for (i = 0; i < res; ++i)
121 buf [i] = GINT_TO_POINTER (processes [i].kinfo_pid_member);
126 #elif defined(__HAIKU__)
127 /* FIXME: Add back the code from 9185fcc305e43428d0f40f3ee37c8a405d41c9ae */
128 g_assert_not_reached ();
135 GDir *dir = g_dir_open ("/proc/", 0, NULL);
141 while ((name = g_dir_read_name (dir))) {
144 pid = strtol (name, &nend, 10);
145 if (pid <= 0 || nend == name || *nend)
152 buf = g_realloc (buf, count * sizeof (void*));
154 buf [i++] = GINT_TO_POINTER (pid);
163 static G_GNUC_UNUSED char*
164 get_pid_status_item_buf (int pid, const char *item, char *rbuf, int blen, MonoProcessError *error)
169 int len = strlen (item);
171 g_snprintf (buf, sizeof (buf), "/proc/%d/status", pid);
172 f = fopen (buf, "r");
175 *error = MONO_PROCESS_ERROR_NOT_FOUND;
178 while ((s = fgets (buf, blen, f))) {
181 if (strncmp (buf, item, len))
184 while (g_ascii_isspace (*s)) s++;
187 while (g_ascii_isspace (*s)) s++;
190 strncpy (rbuf, s, MIN (len, blen));
191 rbuf [MIN (len, blen) - 1] = 0;
193 *error = MONO_PROCESS_ERROR_NONE;
198 *error = MONO_PROCESS_ERROR_OTHER;
203 * mono_process_get_name:
204 * @pid: pid of the process
205 * @buf: byte buffer where to store the name of the prcoess
206 * @len: size of the buffer @buf
208 * Return the name of the process identified by @pid, storing it
209 * inside @buf for a maximum of len bytes (including the terminating 0).
212 mono_process_get_name (gpointer pid, char *buf, int len)
218 size_t data_len = sizeof (struct kinfo_proc2);
219 struct kinfo_proc2 processi;
222 size_t data_len = sizeof (struct kinfo_proc);
223 struct kinfo_proc processi;
224 #endif /* KERN_PROC2 */
226 memset (buf, 0, len);
230 mib [1] = KERN_PROC2;
231 mib [2] = KERN_PROC_PID;
232 mib [3] = GPOINTER_TO_UINT (pid);
233 mib [4] = sizeof(struct kinfo_proc2);
234 mib [5] = 400; /* XXX */
236 res = sysctl (mib, 6, &processi, &data_len, NULL, 0);
238 if (res < 0 || data_len != sizeof (struct kinfo_proc2)) {
244 mib [2] = KERN_PROC_PID;
245 mib [3] = GPOINTER_TO_UINT (pid);
247 res = sysctl (mib, 4, &processi, &data_len, NULL, 0);
248 if (res < 0 || data_len != sizeof (struct kinfo_proc)) {
251 #endif /* KERN_PROC2 */
252 strncpy (buf, processi.kinfo_name_member, len - 1);
259 sprintf (fname, "/proc/%d/cmdline", GPOINTER_TO_INT (pid));
261 file = fopen (fname, "r");
264 r = fread (buf, 1, len - 1, file);
267 p = strrchr (buf, '/');
271 return get_pid_status_item_buf (GPOINTER_TO_INT (pid), "Name", buf, len, NULL);
278 * /proc/pid/stat format:
280 * [0] ppid pgid sid tty_nr tty_pgrp flags min_flt cmin_flt maj_flt cmaj_flt
281 * [10] utime stime cutime cstime prio nice threads 0 start_time vsize rss
282 * [20] rss rsslim start_code end_code start_stack esp eip pending blocked sigign
283 * [30] sigcatch wchan 0 0 exit_signal cpu rt_prio policy
286 #define RET_ERROR(err) do { \
287 if (error) *error = (err); \
292 get_process_stat_item (int pid, int pos, int sum, MonoProcessError *error)
294 #if defined(__APPLE__)
295 double process_user_time = 0, process_system_time = 0;//, process_percent = 0;
297 struct task_basic_info t_info;
298 mach_msg_type_number_t t_info_count = TASK_BASIC_INFO_COUNT, th_count;
299 thread_array_t th_array;
302 if (task_for_pid(mach_task_self(), pid, &task) != KERN_SUCCESS)
303 RET_ERROR (MONO_PROCESS_ERROR_NOT_FOUND);
305 if (task_info(task, TASK_BASIC_INFO, (task_info_t)&t_info, &t_info_count) != KERN_SUCCESS) {
306 mach_port_deallocate (mach_task_self (), task);
307 RET_ERROR (MONO_PROCESS_ERROR_OTHER);
310 if (task_threads(task, &th_array, &th_count) != KERN_SUCCESS) {
311 mach_port_deallocate (mach_task_self (), task);
312 RET_ERROR (MONO_PROCESS_ERROR_OTHER);
315 for (i = 0; i < th_count; i++) {
316 double thread_user_time, thread_system_time;//, thread_percent;
318 struct thread_basic_info th_info;
319 mach_msg_type_number_t th_info_count = THREAD_BASIC_INFO_COUNT;
320 if (thread_info(th_array[i], THREAD_BASIC_INFO, (thread_info_t)&th_info, &th_info_count) == KERN_SUCCESS) {
321 thread_user_time = th_info.user_time.seconds + th_info.user_time.microseconds / 1e6;
322 thread_system_time = th_info.system_time.seconds + th_info.system_time.microseconds / 1e6;
323 //thread_percent = (double)th_info.cpu_usage / TH_USAGE_SCALE;
325 process_user_time += thread_user_time;
326 process_system_time += thread_system_time;
327 //process_percent += th_percent;
331 for (i = 0; i < th_count; i++)
332 mach_port_deallocate(task, th_array[i]);
334 mach_port_deallocate (mach_task_self (), task);
336 process_user_time += t_info.user_time.seconds + t_info.user_time.microseconds / 1e6;
337 process_system_time += t_info.system_time.seconds + t_info.system_time.microseconds / 1e6;
339 if (pos == 10 && sum == TRUE)
340 return (gint64)((process_user_time + process_system_time) * 10000000);
342 return (gint64)(process_user_time * 10000000);
344 return (gint64)(process_system_time * 10000000);
354 g_snprintf (buf, sizeof (buf), "/proc/%d/stat", pid);
355 f = fopen (buf, "r");
357 RET_ERROR (MONO_PROCESS_ERROR_NOT_FOUND);
358 len = fread (buf, 1, sizeof (buf), f);
361 RET_ERROR (MONO_PROCESS_ERROR_OTHER);
362 s = strchr (buf, ')');
364 RET_ERROR (MONO_PROCESS_ERROR_OTHER);
366 while (g_ascii_isspace (*s)) s++;
368 RET_ERROR (MONO_PROCESS_ERROR_OTHER);
369 /* skip the status char */
370 while (*s && !g_ascii_isspace (*s)) s++;
372 RET_ERROR (MONO_PROCESS_ERROR_OTHER);
373 for (i = 0; i < pos; ++i) {
374 while (g_ascii_isspace (*s)) s++;
376 RET_ERROR (MONO_PROCESS_ERROR_OTHER);
377 while (*s && !g_ascii_isspace (*s)) s++;
379 RET_ERROR (MONO_PROCESS_ERROR_OTHER);
381 /* we are finally at the needed item */
382 value = strtoul (s, &end, 0);
383 /* add also the following value */
385 while (g_ascii_isspace (*s)) s++;
387 RET_ERROR (MONO_PROCESS_ERROR_OTHER);
388 value += strtoul (s, &end, 0);
391 *error = MONO_PROCESS_ERROR_NONE;
399 static int user_hz = 0;
402 user_hz = sysconf (_SC_CLK_TCK);
411 get_process_stat_time (int pid, int pos, int sum, MonoProcessError *error)
413 gint64 val = get_process_stat_item (pid, pos, sum, error);
414 #if defined(__APPLE__)
417 /* return 100ns ticks */
418 return (val * 10000000) / get_user_hz ();
423 get_pid_status_item (int pid, const char *item, MonoProcessError *error, int multiplier)
425 #if defined(__APPLE__)
426 // ignore the multiplier
430 struct task_basic_info t_info;
431 mach_msg_type_number_t th_count = TASK_BASIC_INFO_COUNT;
433 if (pid == getpid ()) {
434 /* task_for_pid () doesn't work on ios, even for the current process */
435 task = mach_task_self ();
437 if (task_for_pid (mach_task_self (), pid, &task) != KERN_SUCCESS)
438 RET_ERROR (MONO_PROCESS_ERROR_NOT_FOUND);
441 if (task_info (task, TASK_BASIC_INFO, (task_info_t)&t_info, &th_count) != KERN_SUCCESS) {
442 if (pid != getpid ())
443 mach_port_deallocate (mach_task_self (), task);
444 RET_ERROR (MONO_PROCESS_ERROR_OTHER);
447 if (strcmp (item, "VmRSS") == 0 || strcmp (item, "VmHWM") == 0 || strcmp (item, "VmData") == 0)
448 ret = t_info.resident_size;
449 else if (strcmp (item, "VmSize") == 0 || strcmp (item, "VmPeak") == 0)
450 ret = t_info.virtual_size;
451 else if (strcmp (item, "Threads") == 0)
456 if (pid != getpid ())
457 mach_port_deallocate (mach_task_self (), task);
464 s = get_pid_status_item_buf (pid, item, buf, sizeof (buf), error);
466 return ((gint64) atol (s)) * multiplier;
472 * mono_process_get_data:
473 * @pid: pid of the process
474 * @data: description of data to return
476 * Return a data item of a process like user time, memory use etc,
477 * according to the @data argumet.
480 mono_process_get_data_with_error (gpointer pid, MonoProcessData data, MonoProcessError *error)
483 int rpid = GPOINTER_TO_INT (pid);
486 *error = MONO_PROCESS_ERROR_OTHER;
489 case MONO_PROCESS_NUM_THREADS:
490 return get_pid_status_item (rpid, "Threads", error, 1);
491 case MONO_PROCESS_USER_TIME:
492 return get_process_stat_time (rpid, 10, FALSE, error);
493 case MONO_PROCESS_SYSTEM_TIME:
494 return get_process_stat_time (rpid, 11, FALSE, error);
495 case MONO_PROCESS_TOTAL_TIME:
496 return get_process_stat_time (rpid, 10, TRUE, error);
497 case MONO_PROCESS_WORKING_SET:
498 return get_pid_status_item (rpid, "VmRSS", error, 1024);
499 case MONO_PROCESS_WORKING_SET_PEAK:
500 val = get_pid_status_item (rpid, "VmHWM", error, 1024);
502 val = get_pid_status_item (rpid, "VmRSS", error, 1024);
504 case MONO_PROCESS_PRIVATE_BYTES:
505 return get_pid_status_item (rpid, "VmData", error, 1024);
506 case MONO_PROCESS_VIRTUAL_BYTES:
507 return get_pid_status_item (rpid, "VmSize", error, 1024);
508 case MONO_PROCESS_VIRTUAL_BYTES_PEAK:
509 val = get_pid_status_item (rpid, "VmPeak", error, 1024);
511 val = get_pid_status_item (rpid, "VmSize", error, 1024);
513 case MONO_PROCESS_FAULTS:
514 return get_process_stat_item (rpid, 6, TRUE, error);
515 case MONO_PROCESS_ELAPSED:
516 return get_process_stat_item (rpid, 18, FALSE, error) / get_user_hz ();
517 case MONO_PROCESS_PPID:
518 return get_process_stat_time (rpid, 0, FALSE, error);
519 case MONO_PROCESS_PAGED_BYTES:
520 return get_pid_status_item (rpid, "VmSwap", error, 1024);
523 case MONO_PROCESS_END:
530 mono_process_get_data (gpointer pid, MonoProcessData data)
532 MonoProcessError error;
533 return mono_process_get_data_with_error (pid, data, &error);
537 mono_process_current_pid ()
539 #if defined(HAVE_UNISTD_H)
540 return (int) getpid ();
541 #elif defined(HOST_WIN32)
542 return (int) GetCurrentProcessId ();
551 * Return the number of processors on the system.
554 mono_cpu_count (void)
557 #ifdef PLATFORM_ANDROID
558 /* Android tries really hard to save power by powering off CPUs on SMP phones which
559 * means the normal way to query cpu count returns a wrong value with userspace API.
560 * Instead we use /sys entries to query the actual hardware CPU count.
562 char buffer[8] = {'\0'};
563 int present = open ("/sys/devices/system/cpu/present", O_RDONLY);
564 /* Format of the /sys entry is a cpulist of indexes which in the case
565 * of present is always of the form "0-(n-1)" when there is more than
566 * 1 core, n being the number of CPU cores in the system. Otherwise
567 * the value is simply 0
569 if (present != -1 && read (present, (char*)buffer, sizeof (buffer)) > 3)
570 count = strtol (((char*)buffer) + 2, NULL, 10);
576 #ifdef _SC_NPROCESSORS_ONLN
577 count = sysconf (_SC_NPROCESSORS_ONLN);
584 size_t len = sizeof (int);
587 if (sysctl (mib, 2, &count, &len, NULL, 0) == 0)
594 GetSystemInfo (&info);
595 return info.dwNumberOfProcessors;
603 get_cpu_times (int cpu_id, gint64 *user, gint64 *systemt, gint64 *irq, gint64 *sirq, gint64 *idle)
607 int hz = get_user_hz ();
608 guint64 user_ticks = 0, nice_ticks = 0, system_ticks = 0, idle_ticks = 0, irq_ticks = 0, sirq_ticks = 0;
609 FILE *f = fopen ("/proc/stat", "r");
613 hz *= mono_cpu_count ();
614 while ((s = fgets (buf, sizeof (buf), f))) {
616 if (cpu_id < 0 && strncmp (s, "cpu", 3) == 0 && g_ascii_isspace (s [3])) {
618 } else if (cpu_id >= 0 && strncmp (s, "cpu", 3) == 0 && strtol (s + 3, &data, 10) == cpu_id) {
626 user_ticks = strtoull (data, &data, 10);
627 nice_ticks = strtoull (data, &data, 10);
628 system_ticks = strtoull (data, &data, 10);
629 idle_ticks = strtoull (data, &data, 10);
630 /* iowait_ticks = strtoull (data, &data, 10); */
631 irq_ticks = strtoull (data, &data, 10);
632 sirq_ticks = strtoull (data, &data, 10);
638 *user = (user_ticks + nice_ticks) * 10000000 / hz;
640 *systemt = (system_ticks) * 10000000 / hz;
642 *irq = (irq_ticks) * 10000000 / hz;
644 *sirq = (sirq_ticks) * 10000000 / hz;
646 *idle = (idle_ticks) * 10000000 / hz;
651 * @cpu_id: processor number or -1 to get a summary of all the processors
652 * @data: type of data to retrieve
654 * Get data about a processor on the system, like time spent in user space or idle time.
657 mono_cpu_get_data (int cpu_id, MonoCpuData data, MonoProcessError *error)
662 *error = MONO_PROCESS_ERROR_NONE;
664 case MONO_CPU_USER_TIME:
665 get_cpu_times (cpu_id, &value, NULL, NULL, NULL, NULL);
667 case MONO_CPU_PRIV_TIME:
668 get_cpu_times (cpu_id, NULL, &value, NULL, NULL, NULL);
670 case MONO_CPU_INTR_TIME:
671 get_cpu_times (cpu_id, NULL, NULL, &value, NULL, NULL);
673 case MONO_CPU_DCP_TIME:
674 get_cpu_times (cpu_id, NULL, NULL, NULL, &value, NULL);
676 case MONO_CPU_IDLE_TIME:
677 get_cpu_times (cpu_id, NULL, NULL, NULL, NULL, &value);
688 mono_atexit (void (*func)(void))
690 #ifdef PLATFORM_ANDROID
691 /* Some versions of android libc doesn't define atexit () */
694 return atexit (func);