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) * 16;
65 struct kinfo_proc *processes;
67 #endif /* KERN_PROC2 */
79 mib [2] = KERN_PROC_ALL;
81 mib [4] = sizeof(struct kinfo_proc2);
82 mib [5] = 400; /* XXX */
84 res = sysctl (mib, 6, processes, &data_len, NULL, 0);
94 mib [2] = KERN_PROC_ALL;
97 res = sysctl (mib, 4, NULL, &data_len, NULL, 0);
100 processes = malloc (data_len);
101 res = sysctl (mib, 4, NULL, &data_len, NULL, 0);
111 #endif /* KERN_PROC2 */
114 res = data_len/sizeof (struct kinfo_proc2);
116 res = data_len/sizeof (struct kinfo_proc);
117 #endif /* KERN_PROC2 */
118 buf = g_realloc (buf, res * sizeof (void*));
119 for (i = 0; i < res; ++i)
120 buf [i] = GINT_TO_POINTER (processes [i].kinfo_pid_member);
125 #elif defined(__HAIKU__)
126 /* FIXME: Add back the code from 9185fcc305e43428d0f40f3ee37c8a405d41c9ae */
127 g_assert_not_reached ();
134 GDir *dir = g_dir_open ("/proc/", 0, NULL);
140 while ((name = g_dir_read_name (dir))) {
143 pid = strtol (name, &nend, 10);
144 if (pid <= 0 || nend == name || *nend)
151 buf = g_realloc (buf, count * sizeof (void*));
153 buf [i++] = GINT_TO_POINTER (pid);
162 static G_GNUC_UNUSED char*
163 get_pid_status_item_buf (int pid, const char *item, char *rbuf, int blen, MonoProcessError *error)
168 int len = strlen (item);
170 g_snprintf (buf, sizeof (buf), "/proc/%d/status", pid);
171 f = fopen (buf, "r");
174 *error = MONO_PROCESS_ERROR_NOT_FOUND;
177 while ((s = fgets (buf, blen, f))) {
180 if (strncmp (buf, item, len))
183 while (g_ascii_isspace (*s)) s++;
186 while (g_ascii_isspace (*s)) s++;
189 strncpy (rbuf, s, MIN (len, blen));
190 rbuf [MIN (len, blen) - 1] = 0;
192 *error = MONO_PROCESS_ERROR_NONE;
197 *error = MONO_PROCESS_ERROR_OTHER;
202 * mono_process_get_name:
203 * @pid: pid of the process
204 * @buf: byte buffer where to store the name of the prcoess
205 * @len: size of the buffer @buf
207 * Return the name of the process identified by @pid, storing it
208 * inside @buf for a maximum of len bytes (including the terminating 0).
211 mono_process_get_name (gpointer pid, char *buf, int len)
217 size_t data_len = sizeof (struct kinfo_proc2);
218 struct kinfo_proc2 processi;
221 size_t data_len = sizeof (struct kinfo_proc);
222 struct kinfo_proc processi;
223 #endif /* KERN_PROC2 */
225 memset (buf, 0, len);
229 mib [1] = KERN_PROC2;
230 mib [2] = KERN_PROC_PID;
231 mib [3] = GPOINTER_TO_UINT (pid);
232 mib [4] = sizeof(struct kinfo_proc2);
233 mib [5] = 400; /* XXX */
235 res = sysctl (mib, 6, &processi, &data_len, NULL, 0);
237 if (res < 0 || data_len != sizeof (struct kinfo_proc2)) {
243 mib [2] = KERN_PROC_PID;
244 mib [3] = GPOINTER_TO_UINT (pid);
246 res = sysctl (mib, 4, &processi, &data_len, NULL, 0);
247 if (res < 0 || data_len != sizeof (struct kinfo_proc)) {
250 #endif /* KERN_PROC2 */
251 strncpy (buf, processi.kinfo_name_member, len - 1);
258 sprintf (fname, "/proc/%d/cmdline", GPOINTER_TO_INT (pid));
260 file = fopen (fname, "r");
263 r = fread (buf, 1, len - 1, file);
266 p = strrchr (buf, '/');
270 return get_pid_status_item_buf (GPOINTER_TO_INT (pid), "Name", buf, len, NULL);
277 * /proc/pid/stat format:
279 * [0] ppid pgid sid tty_nr tty_pgrp flags min_flt cmin_flt maj_flt cmaj_flt
280 * [10] utime stime cutime cstime prio nice threads 0 start_time vsize rss
281 * [20] rss rsslim start_code end_code start_stack esp eip pending blocked sigign
282 * [30] sigcatch wchan 0 0 exit_signal cpu rt_prio policy
285 #define RET_ERROR(err) do { \
286 if (error) *error = (err); \
291 get_process_stat_item (int pid, int pos, int sum, MonoProcessError *error)
293 #if defined(__APPLE__)
294 double process_user_time = 0, process_system_time = 0;//, process_percent = 0;
296 struct task_basic_info t_info;
297 mach_msg_type_number_t t_info_count = TASK_BASIC_INFO_COUNT, th_count;
298 thread_array_t th_array;
301 if (task_for_pid(mach_task_self(), pid, &task) != KERN_SUCCESS)
302 RET_ERROR (MONO_PROCESS_ERROR_NOT_FOUND);
304 if (task_info(task, TASK_BASIC_INFO, (task_info_t)&t_info, &t_info_count) != KERN_SUCCESS) {
305 mach_port_deallocate (mach_task_self (), task);
306 RET_ERROR (MONO_PROCESS_ERROR_OTHER);
309 if (task_threads(task, &th_array, &th_count) != KERN_SUCCESS) {
310 mach_port_deallocate (mach_task_self (), task);
311 RET_ERROR (MONO_PROCESS_ERROR_OTHER);
314 for (i = 0; i < th_count; i++) {
315 double thread_user_time, thread_system_time;//, thread_percent;
317 struct thread_basic_info th_info;
318 mach_msg_type_number_t th_info_count = THREAD_BASIC_INFO_COUNT;
319 if (thread_info(th_array[i], THREAD_BASIC_INFO, (thread_info_t)&th_info, &th_info_count) == KERN_SUCCESS) {
320 thread_user_time = th_info.user_time.seconds + th_info.user_time.microseconds / 1e6;
321 thread_system_time = th_info.system_time.seconds + th_info.system_time.microseconds / 1e6;
322 //thread_percent = (double)th_info.cpu_usage / TH_USAGE_SCALE;
324 process_user_time += thread_user_time;
325 process_system_time += thread_system_time;
326 //process_percent += th_percent;
330 for (i = 0; i < th_count; i++)
331 mach_port_deallocate(task, th_array[i]);
333 mach_port_deallocate (mach_task_self (), task);
335 process_user_time += t_info.user_time.seconds + t_info.user_time.microseconds / 1e6;
336 process_system_time += t_info.system_time.seconds + t_info.system_time.microseconds / 1e6;
338 if (pos == 10 && sum == TRUE)
339 return (gint64)((process_user_time + process_system_time) * 10000000);
341 return (gint64)(process_user_time * 10000000);
343 return (gint64)(process_system_time * 10000000);
353 g_snprintf (buf, sizeof (buf), "/proc/%d/stat", pid);
354 f = fopen (buf, "r");
356 RET_ERROR (MONO_PROCESS_ERROR_NOT_FOUND);
357 len = fread (buf, 1, sizeof (buf), f);
360 RET_ERROR (MONO_PROCESS_ERROR_OTHER);
361 s = strchr (buf, ')');
363 RET_ERROR (MONO_PROCESS_ERROR_OTHER);
365 while (g_ascii_isspace (*s)) s++;
367 RET_ERROR (MONO_PROCESS_ERROR_OTHER);
368 /* skip the status char */
369 while (*s && !g_ascii_isspace (*s)) s++;
371 RET_ERROR (MONO_PROCESS_ERROR_OTHER);
372 for (i = 0; i < pos; ++i) {
373 while (g_ascii_isspace (*s)) s++;
375 RET_ERROR (MONO_PROCESS_ERROR_OTHER);
376 while (*s && !g_ascii_isspace (*s)) s++;
378 RET_ERROR (MONO_PROCESS_ERROR_OTHER);
380 /* we are finally at the needed item */
381 value = strtoul (s, &end, 0);
382 /* add also the following value */
384 while (g_ascii_isspace (*s)) s++;
386 RET_ERROR (MONO_PROCESS_ERROR_OTHER);
387 value += strtoul (s, &end, 0);
390 *error = MONO_PROCESS_ERROR_NONE;
398 static int user_hz = 0;
401 user_hz = sysconf (_SC_CLK_TCK);
410 get_process_stat_time (int pid, int pos, int sum, MonoProcessError *error)
412 gint64 val = get_process_stat_item (pid, pos, sum, error);
413 #if defined(__APPLE__)
416 /* return 100ns ticks */
417 return (val * 10000000) / get_user_hz ();
422 get_pid_status_item (int pid, const char *item, MonoProcessError *error, int multiplier)
424 #if defined(__APPLE__)
425 // ignore the multiplier
429 struct task_basic_info t_info;
430 mach_msg_type_number_t th_count = TASK_BASIC_INFO_COUNT;
432 if (pid == getpid ()) {
433 /* task_for_pid () doesn't work on ios, even for the current process */
434 task = mach_task_self ();
436 if (task_for_pid (mach_task_self (), pid, &task) != KERN_SUCCESS)
437 RET_ERROR (MONO_PROCESS_ERROR_NOT_FOUND);
440 if (task_info (task, TASK_BASIC_INFO, (task_info_t)&t_info, &th_count) != KERN_SUCCESS) {
441 if (pid != getpid ())
442 mach_port_deallocate (mach_task_self (), task);
443 RET_ERROR (MONO_PROCESS_ERROR_OTHER);
446 if (strcmp (item, "VmRSS") == 0 || strcmp (item, "VmHWM") == 0 || strcmp (item, "VmData") == 0)
447 ret = t_info.resident_size;
448 else if (strcmp (item, "VmSize") == 0 || strcmp (item, "VmPeak") == 0)
449 ret = t_info.virtual_size;
450 else if (strcmp (item, "Threads") == 0)
455 if (pid != getpid ())
456 mach_port_deallocate (mach_task_self (), task);
463 s = get_pid_status_item_buf (pid, item, buf, sizeof (buf), error);
465 return ((gint64) atol (s)) * multiplier;
471 * mono_process_get_data:
472 * @pid: pid of the process
473 * @data: description of data to return
475 * Return a data item of a process like user time, memory use etc,
476 * according to the @data argumet.
479 mono_process_get_data_with_error (gpointer pid, MonoProcessData data, MonoProcessError *error)
482 int rpid = GPOINTER_TO_INT (pid);
485 *error = MONO_PROCESS_ERROR_OTHER;
488 case MONO_PROCESS_NUM_THREADS:
489 return get_pid_status_item (rpid, "Threads", error, 1);
490 case MONO_PROCESS_USER_TIME:
491 return get_process_stat_time (rpid, 10, FALSE, error);
492 case MONO_PROCESS_SYSTEM_TIME:
493 return get_process_stat_time (rpid, 11, FALSE, error);
494 case MONO_PROCESS_TOTAL_TIME:
495 return get_process_stat_time (rpid, 10, TRUE, error);
496 case MONO_PROCESS_WORKING_SET:
497 return get_pid_status_item (rpid, "VmRSS", error, 1024);
498 case MONO_PROCESS_WORKING_SET_PEAK:
499 val = get_pid_status_item (rpid, "VmHWM", error, 1024);
501 val = get_pid_status_item (rpid, "VmRSS", error, 1024);
503 case MONO_PROCESS_PRIVATE_BYTES:
504 return get_pid_status_item (rpid, "VmData", error, 1024);
505 case MONO_PROCESS_VIRTUAL_BYTES:
506 return get_pid_status_item (rpid, "VmSize", error, 1024);
507 case MONO_PROCESS_VIRTUAL_BYTES_PEAK:
508 val = get_pid_status_item (rpid, "VmPeak", error, 1024);
510 val = get_pid_status_item (rpid, "VmSize", error, 1024);
512 case MONO_PROCESS_FAULTS:
513 return get_process_stat_item (rpid, 6, TRUE, error);
514 case MONO_PROCESS_ELAPSED:
515 return get_process_stat_item (rpid, 18, FALSE, error) / get_user_hz ();
516 case MONO_PROCESS_PPID:
517 return get_process_stat_time (rpid, 0, FALSE, error);
518 case MONO_PROCESS_PAGED_BYTES:
519 return get_pid_status_item (rpid, "VmSwap", error, 1024);
522 case MONO_PROCESS_END:
529 mono_process_get_data (gpointer pid, MonoProcessData data)
531 MonoProcessError error;
532 return mono_process_get_data_with_error (pid, data, &error);
536 mono_process_current_pid ()
538 #if defined(HAVE_UNISTD_H)
539 return (int) getpid ();
540 #elif defined(HOST_WIN32)
541 return (int) GetCurrentProcessId ();
550 * Return the number of processors on the system.
553 mono_cpu_count (void)
556 #ifdef PLATFORM_ANDROID
557 /* Android tries really hard to save power by powering off CPUs on SMP phones which
558 * means the normal way to query cpu count returns a wrong value with userspace API.
559 * Instead we use /sys entries to query the actual hardware CPU count.
561 char buffer[8] = {'\0'};
562 int present = open ("/sys/devices/system/cpu/present", O_RDONLY);
563 /* Format of the /sys entry is a cpulist of indexes which in the case
564 * of present is always of the form "0-(n-1)" when there is more than
565 * 1 core, n being the number of CPU cores in the system. Otherwise
566 * the value is simply 0
568 if (present != -1 && read (present, (char*)buffer, sizeof (buffer)) > 3)
569 count = strtol (((char*)buffer) + 2, NULL, 10);
575 #ifdef _SC_NPROCESSORS_ONLN
576 count = sysconf (_SC_NPROCESSORS_ONLN);
583 size_t len = sizeof (int);
586 if (sysctl (mib, 2, &count, &len, NULL, 0) == 0)
593 GetSystemInfo (&info);
594 return info.dwNumberOfProcessors;
602 get_cpu_times (int cpu_id, gint64 *user, gint64 *systemt, gint64 *irq, gint64 *sirq, gint64 *idle)
606 int hz = get_user_hz ();
607 guint64 user_ticks = 0, nice_ticks = 0, system_ticks = 0, idle_ticks = 0, irq_ticks = 0, sirq_ticks = 0;
608 FILE *f = fopen ("/proc/stat", "r");
612 hz *= mono_cpu_count ();
613 while ((s = fgets (buf, sizeof (buf), f))) {
615 if (cpu_id < 0 && strncmp (s, "cpu", 3) == 0 && g_ascii_isspace (s [3])) {
617 } else if (cpu_id >= 0 && strncmp (s, "cpu", 3) == 0 && strtol (s + 3, &data, 10) == cpu_id) {
625 user_ticks = strtoull (data, &data, 10);
626 nice_ticks = strtoull (data, &data, 10);
627 system_ticks = strtoull (data, &data, 10);
628 idle_ticks = strtoull (data, &data, 10);
629 /* iowait_ticks = strtoull (data, &data, 10); */
630 irq_ticks = strtoull (data, &data, 10);
631 sirq_ticks = strtoull (data, &data, 10);
637 *user = (user_ticks + nice_ticks) * 10000000 / hz;
639 *systemt = (system_ticks) * 10000000 / hz;
641 *irq = (irq_ticks) * 10000000 / hz;
643 *sirq = (sirq_ticks) * 10000000 / hz;
645 *idle = (idle_ticks) * 10000000 / hz;
650 * @cpu_id: processor number or -1 to get a summary of all the processors
651 * @data: type of data to retrieve
653 * Get data about a processor on the system, like time spent in user space or idle time.
656 mono_cpu_get_data (int cpu_id, MonoCpuData data, MonoProcessError *error)
661 *error = MONO_PROCESS_ERROR_NONE;
663 case MONO_CPU_USER_TIME:
664 get_cpu_times (cpu_id, &value, NULL, NULL, NULL, NULL);
666 case MONO_CPU_PRIV_TIME:
667 get_cpu_times (cpu_id, NULL, &value, NULL, NULL, NULL);
669 case MONO_CPU_INTR_TIME:
670 get_cpu_times (cpu_id, NULL, NULL, &value, NULL, NULL);
672 case MONO_CPU_DCP_TIME:
673 get_cpu_times (cpu_id, NULL, NULL, NULL, &value, NULL);
675 case MONO_CPU_IDLE_TIME:
676 get_cpu_times (cpu_id, NULL, NULL, NULL, NULL, &value);
687 mono_atexit (void (*func)(void))
689 #ifdef PLATFORM_ANDROID
690 /* Some versions of android libc doesn't define atexit () */
693 return atexit (func);