Merge pull request #2894 from marek-safar/mono.security
[mono.git] / mono / utils / mono-proclib.c
1 /*
2  * Copyright 2008-2011 Novell Inc
3  * Copyright 2011 Xamarin Inc
4  * Licensed under the MIT license. See LICENSE file in the project root for full license information.
5  */
6
7 #include "config.h"
8 #include "utils/mono-proclib.h"
9 #include "utils/mono-time.h"
10
11 #include <stdlib.h>
12 #include <stdio.h>
13 #include <string.h>
14 #include <fcntl.h>
15 #ifdef HAVE_UNISTD_H
16 #include <unistd.h>
17 #endif
18 #ifdef HAVE_SCHED_GETAFFINITY
19 #include <sched.h>
20 #endif
21
22 #ifdef HOST_WIN32
23 #include <windows.h>
24 #include <process.h>
25 #endif
26
27 #if defined(_POSIX_VERSION)
28 #include <sys/errno.h>
29 #include <sys/param.h>
30 #ifdef HAVE_SYS_TYPES_H
31 #include <sys/types.h>
32 #endif
33 #ifdef HAVE_SYS_SYSCTL_H
34 #include <sys/sysctl.h>
35 #endif
36 #include <sys/resource.h>
37 #endif
38 #if defined(__APPLE__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__)
39 #include <sys/proc.h>
40 #if defined(__APPLE__)
41 #include <mach/mach.h>
42 #endif
43 #ifdef HAVE_SYS_USER_H
44 #include <sys/user.h>
45 #endif
46 #ifdef HAVE_STRUCT_KINFO_PROC_KP_PROC
47 #    define kinfo_starttime_member kp_proc.p_starttime
48 #    define kinfo_pid_member kp_proc.p_pid
49 #    define kinfo_name_member kp_proc.p_comm
50 #elif defined(__OpenBSD__)
51 // Can not figure out how to get the proc's start time on OpenBSD
52 #    undef kinfo_starttime_member 
53 #    define kinfo_pid_member p_pid
54 #    define kinfo_name_member p_comm
55 #else
56 #define kinfo_starttime_member ki_start
57 #define kinfo_pid_member ki_pid
58 #define kinfo_name_member ki_comm
59 #endif
60 #define USE_SYSCTL 1
61 #endif
62
63 /**
64  * mono_process_list:
65  * @size: a pointer to a location where the size of the returned array is stored
66  *
67  * Return an array of pid values for the processes currently running on the system.
68  * The size of the array is stored in @size.
69  */
70 gpointer*
71 mono_process_list (int *size)
72 {
73 #if USE_SYSCTL
74         int res, i;
75 #ifdef KERN_PROC2
76         int mib [6];
77         size_t data_len = sizeof (struct kinfo_proc2) * 400;
78         struct kinfo_proc2 *processes = malloc (data_len);
79 #else
80         int mib [4];
81         size_t data_len = sizeof (struct kinfo_proc) * 16;
82         struct kinfo_proc *processes;
83         int limit = 8;
84 #endif /* KERN_PROC2 */
85         void **buf = NULL;
86
87         if (size)
88                 *size = 0;
89
90 #ifdef KERN_PROC2
91         if (!processes)
92                 return NULL;
93
94         mib [0] = CTL_KERN;
95         mib [1] = KERN_PROC2;
96         mib [2] = KERN_PROC_ALL;
97         mib [3] = 0;
98         mib [4] = sizeof(struct kinfo_proc2);
99         mib [5] = 400; /* XXX */
100
101         res = sysctl (mib, 6, processes, &data_len, NULL, 0);
102         if (res < 0) {
103                 free (processes);
104                 return NULL;
105         }
106 #else
107         processes = NULL;
108         while (limit) {
109                 mib [0] = CTL_KERN;
110                 mib [1] = KERN_PROC;
111                 mib [2] = KERN_PROC_ALL;
112                 mib [3] = 0;
113
114                 res = sysctl (mib, 4, NULL, &data_len, NULL, 0);
115                 if (res)
116                         return NULL;
117                 processes = (struct kinfo_proc *) malloc (data_len);
118                 res = sysctl (mib, 4, processes, &data_len, NULL, 0);
119                 if (res < 0) {
120                         free (processes);
121                         if (errno != ENOMEM)
122                                 return NULL;
123                         limit --;
124                 } else {
125                         break;
126                 }
127         }
128 #endif /* KERN_PROC2 */
129
130 #ifdef KERN_PROC2
131         res = data_len/sizeof (struct kinfo_proc2);
132 #else
133         res = data_len/sizeof (struct kinfo_proc);
134 #endif /* KERN_PROC2 */
135         buf = (void **) g_realloc (buf, res * sizeof (void*));
136         for (i = 0; i < res; ++i)
137                 buf [i] = GINT_TO_POINTER (processes [i].kinfo_pid_member);
138         free (processes);
139         if (size)
140                 *size = res;
141         return buf;
142 #elif defined(__HAIKU__)
143         /* FIXME: Add back the code from 9185fcc305e43428d0f40f3ee37c8a405d41c9ae */
144         g_assert_not_reached ();
145         return NULL;
146 #else
147         const char *name;
148         void **buf = NULL;
149         int count = 0;
150         int i = 0;
151         GDir *dir = g_dir_open ("/proc/", 0, NULL);
152         if (!dir) {
153                 if (size)
154                         *size = 0;
155                 return NULL;
156         }
157         while ((name = g_dir_read_name (dir))) {
158                 int pid;
159                 char *nend;
160                 pid = strtol (name, &nend, 10);
161                 if (pid <= 0 || nend == name || *nend)
162                         continue;
163                 if (i >= count) {
164                         if (!count)
165                                 count = 16;
166                         else
167                                 count *= 2;
168                         buf = (void **)g_realloc (buf, count * sizeof (void*));
169                 }
170                 buf [i++] = GINT_TO_POINTER (pid);
171         }
172         g_dir_close (dir);
173         if (size)
174                 *size = i;
175         return buf;
176 #endif
177 }
178
179 static G_GNUC_UNUSED char*
180 get_pid_status_item_buf (int pid, const char *item, char *rbuf, int blen, MonoProcessError *error)
181 {
182         char buf [256];
183         char *s;
184         FILE *f;
185         int len = strlen (item);
186
187         g_snprintf (buf, sizeof (buf), "/proc/%d/status", pid);
188         f = fopen (buf, "r");
189         if (!f) {
190                 if (error)
191                         *error = MONO_PROCESS_ERROR_NOT_FOUND;
192                 return NULL;
193         }
194         while ((s = fgets (buf, sizeof (buf), f))) {
195                 if (*item != *buf)
196                         continue;
197                 if (strncmp (buf, item, len))
198                         continue;
199                 s = buf + len;
200                 while (g_ascii_isspace (*s)) s++;
201                 if (*s++ != ':')
202                         continue;
203                 while (g_ascii_isspace (*s)) s++;
204                 fclose (f);
205                 len = strlen (s);
206                 strncpy (rbuf, s, MIN (len, blen));
207                 rbuf [MIN (len, blen) - 1] = 0;
208                 if (error)
209                         *error = MONO_PROCESS_ERROR_NONE;
210                 return rbuf;
211         }
212         fclose (f);
213         if (error)
214                 *error = MONO_PROCESS_ERROR_OTHER;
215         return NULL;
216 }
217
218 #if USE_SYSCTL
219
220 #ifdef KERN_PROC2
221 #define KINFO_PROC struct kinfo_proc2
222 #else
223 #define KINFO_PROC struct kinfo_proc
224 #endif
225
226 static gboolean
227 sysctl_kinfo_proc (gpointer pid, KINFO_PROC* processi)
228 {
229         int res;
230         size_t data_len = sizeof (KINFO_PROC);
231
232 #ifdef KERN_PROC2
233         int mib [6];
234         mib [0] = CTL_KERN;
235         mib [1] = KERN_PROC2;
236         mib [2] = KERN_PROC_PID;
237         mib [3] = GPOINTER_TO_UINT (pid);
238         mib [4] = sizeof(KINFO_PROC);
239         mib [5] = 400; /* XXX */
240
241         res = sysctl (mib, 6, processi, &data_len, NULL, 0);
242 #else
243         int mib [4];
244         mib [0] = CTL_KERN;
245         mib [1] = KERN_PROC;
246         mib [2] = KERN_PROC_PID;
247         mib [3] = GPOINTER_TO_UINT (pid);
248
249         res = sysctl (mib, 4, processi, &data_len, NULL, 0);
250 #endif /* KERN_PROC2 */
251
252         if (res < 0 || data_len != sizeof (KINFO_PROC))
253                 return FALSE;
254
255         return TRUE;
256 }
257 #endif /* USE_SYSCTL */
258
259 /**
260  * mono_process_get_name:
261  * @pid: pid of the process
262  * @buf: byte buffer where to store the name of the prcoess
263  * @len: size of the buffer @buf
264  *
265  * Return the name of the process identified by @pid, storing it
266  * inside @buf for a maximum of len bytes (including the terminating 0).
267  */
268 char*
269 mono_process_get_name (gpointer pid, char *buf, int len)
270 {
271 #if USE_SYSCTL
272         KINFO_PROC processi;
273
274         memset (buf, 0, len);
275
276         if (sysctl_kinfo_proc (pid, &processi))
277                 strncpy (buf, processi.kinfo_name_member, len - 1);
278
279         return buf;
280 #else
281         char fname [128];
282         FILE *file;
283         char *p;
284         int r;
285         sprintf (fname, "/proc/%d/cmdline", GPOINTER_TO_INT (pid));
286         buf [0] = 0;
287         file = fopen (fname, "r");
288         if (!file)
289                 return buf;
290         r = fread (buf, 1, len - 1, file);
291         fclose (file);
292         buf [r] = 0;
293         p = strrchr (buf, '/');
294         if (p)
295                 return p + 1;
296         if (r == 0) {
297                 return get_pid_status_item_buf (GPOINTER_TO_INT (pid), "Name", buf, len, NULL);
298         }
299         return buf;
300 #endif
301 }
302
303 void
304 mono_process_get_times (gpointer pid, gint64 *start_time, gint64 *user_time, gint64 *kernel_time)
305 {
306         if (user_time)
307                 *user_time = mono_process_get_data (pid, MONO_PROCESS_USER_TIME);
308
309         if (kernel_time)
310                 *kernel_time = mono_process_get_data (pid, MONO_PROCESS_SYSTEM_TIME);
311
312         if (start_time) {
313                 *start_time = 0;
314
315 #if USE_SYSCTL && defined(kinfo_starttime_member)
316                 {
317                         KINFO_PROC processi;
318
319                         if (sysctl_kinfo_proc (pid, &processi))
320                                 *start_time = mono_100ns_datetime_from_timeval (processi.kinfo_starttime_member);
321                 }
322 #endif
323
324                 if (*start_time == 0) {
325                         static guint64 boot_time = 0;
326                         if (!boot_time)
327                                 boot_time = mono_100ns_datetime () - ((guint64)mono_msec_ticks ()) * 10000;
328
329                         *start_time = boot_time + mono_process_get_data (pid, MONO_PROCESS_ELAPSED);
330                 }
331         }
332 }
333
334 /*
335  * /proc/pid/stat format:
336  * pid (cmdname) S 
337  *      [0] ppid pgid sid tty_nr tty_pgrp flags min_flt cmin_flt maj_flt cmaj_flt
338  *      [10] utime stime cutime cstime prio nice threads 0 start_time vsize
339  *      [20] rss rsslim start_code end_code start_stack esp eip pending blocked sigign
340  *      [30] sigcatch wchan 0 0 exit_signal cpu rt_prio policy
341  */
342
343 #define RET_ERROR(err) do {     \
344                 if (error) *error = (err);      \
345                 return 0;                       \
346         } while (0)
347
348 static gint64
349 get_process_stat_item (int pid, int pos, int sum, MonoProcessError *error)
350 {
351 #if defined(__APPLE__) 
352         double process_user_time = 0, process_system_time = 0;//, process_percent = 0;
353         task_t task;
354         struct task_basic_info t_info;
355         mach_msg_type_number_t t_info_count = TASK_BASIC_INFO_COUNT, th_count;
356         thread_array_t th_array;
357         size_t i;
358         kern_return_t ret;
359
360         if (pid == getpid ()) {
361                 /* task_for_pid () doesn't work on ios, even for the current process */
362                 task = mach_task_self ();
363         } else {
364                 do {
365                         ret = task_for_pid (mach_task_self (), pid, &task);
366                 } while (ret == KERN_ABORTED);
367
368                 if (ret != KERN_SUCCESS)
369                         RET_ERROR (MONO_PROCESS_ERROR_NOT_FOUND);
370         }
371
372         do {
373                 ret = task_info (task, TASK_BASIC_INFO, (task_info_t)&t_info, &t_info_count);
374         } while (ret == KERN_ABORTED);
375
376         if (ret != KERN_SUCCESS) {
377                 if (pid != getpid ())
378                         mach_port_deallocate (mach_task_self (), task);
379                 RET_ERROR (MONO_PROCESS_ERROR_OTHER);
380         }
381
382         do {
383                 ret = task_threads (task, &th_array, &th_count);
384         } while (ret == KERN_ABORTED);
385         
386         if (ret  != KERN_SUCCESS) {
387                 if (pid != getpid ())
388                         mach_port_deallocate (mach_task_self (), task);
389                 RET_ERROR (MONO_PROCESS_ERROR_OTHER);
390         }
391                 
392         for (i = 0; i < th_count; i++) {
393                 double thread_user_time, thread_system_time;//, thread_percent;
394                 
395                 struct thread_basic_info th_info;
396                 mach_msg_type_number_t th_info_count = THREAD_BASIC_INFO_COUNT;
397                 do {
398                         ret = thread_info(th_array[i], THREAD_BASIC_INFO, (thread_info_t)&th_info, &th_info_count);
399                 } while (ret == KERN_ABORTED);
400
401                 if (ret == KERN_SUCCESS) {
402                         thread_user_time = th_info.user_time.seconds + th_info.user_time.microseconds / 1e6;
403                         thread_system_time = th_info.system_time.seconds + th_info.system_time.microseconds / 1e6;
404                         //thread_percent = (double)th_info.cpu_usage / TH_USAGE_SCALE;
405                         
406                         process_user_time += thread_user_time;
407                         process_system_time += thread_system_time;
408                         //process_percent += th_percent;
409                 }
410         }
411         
412         for (i = 0; i < th_count; i++)
413                 mach_port_deallocate(task, th_array[i]);
414
415         if (pid != getpid ())
416                 mach_port_deallocate (mach_task_self (), task);
417
418         process_user_time += t_info.user_time.seconds + t_info.user_time.microseconds / 1e6;
419         process_system_time += t_info.system_time.seconds + t_info.system_time.microseconds / 1e6;
420     
421         if (pos == 10 && sum == TRUE)
422                 return (gint64)((process_user_time + process_system_time) * 10000000);
423         else if (pos == 10)
424                 return (gint64)(process_user_time * 10000000);
425         else if (pos == 11)
426                 return (gint64)(process_system_time * 10000000);
427                 
428         return 0;
429 #else
430         char buf [512];
431         char *s, *end;
432         FILE *f;
433         int len, i;
434         gint64 value;
435
436         g_snprintf (buf, sizeof (buf), "/proc/%d/stat", pid);
437         f = fopen (buf, "r");
438         if (!f)
439                 RET_ERROR (MONO_PROCESS_ERROR_NOT_FOUND);
440         len = fread (buf, 1, sizeof (buf), f);
441         fclose (f);
442         if (len <= 0)
443                 RET_ERROR (MONO_PROCESS_ERROR_OTHER);
444         s = strchr (buf, ')');
445         if (!s)
446                 RET_ERROR (MONO_PROCESS_ERROR_OTHER);
447         s++;
448         while (g_ascii_isspace (*s)) s++;
449         if (!*s)
450                 RET_ERROR (MONO_PROCESS_ERROR_OTHER);
451         /* skip the status char */
452         while (*s && !g_ascii_isspace (*s)) s++;
453         if (!*s)
454                 RET_ERROR (MONO_PROCESS_ERROR_OTHER);
455         for (i = 0; i < pos; ++i) {
456                 while (g_ascii_isspace (*s)) s++;
457                 if (!*s)
458                         RET_ERROR (MONO_PROCESS_ERROR_OTHER);
459                 while (*s && !g_ascii_isspace (*s)) s++;
460                 if (!*s)
461                         RET_ERROR (MONO_PROCESS_ERROR_OTHER);
462         }
463         /* we are finally at the needed item */
464         value = strtoul (s, &end, 0);
465         /* add also the following value */
466         if (sum) {
467                 while (g_ascii_isspace (*s)) s++;
468                 if (!*s)
469                         RET_ERROR (MONO_PROCESS_ERROR_OTHER);
470                 value += strtoul (s, &end, 0);
471         }
472         if (error)
473                 *error = MONO_PROCESS_ERROR_NONE;
474         return value;
475 #endif
476 }
477
478 static int
479 get_user_hz (void)
480 {
481         static int user_hz = 0;
482         if (user_hz == 0) {
483 #ifdef _SC_CLK_TCK
484                 user_hz = sysconf (_SC_CLK_TCK);
485 #endif
486                 if (user_hz == 0)
487                         user_hz = 100;
488         }
489         return user_hz;
490 }
491
492 static gint64
493 get_process_stat_time (int pid, int pos, int sum, MonoProcessError *error)
494 {
495         gint64 val = get_process_stat_item (pid, pos, sum, error);
496 #if defined(__APPLE__)
497         return val;
498 #else
499         /* return 100ns ticks */
500         return (val * 10000000) / get_user_hz ();
501 #endif
502 }
503
504 static gint64
505 get_pid_status_item (int pid, const char *item, MonoProcessError *error, int multiplier)
506 {
507 #if defined(__APPLE__)
508         // ignore the multiplier
509         
510         gint64 ret;
511         task_t task;
512         struct task_basic_info t_info;
513         mach_msg_type_number_t th_count = TASK_BASIC_INFO_COUNT;
514         kern_return_t mach_ret;
515
516         if (pid == getpid ()) {
517                 /* task_for_pid () doesn't work on ios, even for the current process */
518                 task = mach_task_self ();
519         } else {
520                 do {
521                         mach_ret = task_for_pid (mach_task_self (), pid, &task);
522                 } while (mach_ret == KERN_ABORTED);
523
524                 if (mach_ret != KERN_SUCCESS)
525                         RET_ERROR (MONO_PROCESS_ERROR_NOT_FOUND);
526         }
527
528         do {
529                 mach_ret = task_info (task, TASK_BASIC_INFO, (task_info_t)&t_info, &th_count);
530         } while (mach_ret == KERN_ABORTED);
531
532         if (mach_ret != KERN_SUCCESS) {
533                 if (pid != getpid ())
534                         mach_port_deallocate (mach_task_self (), task);
535                 RET_ERROR (MONO_PROCESS_ERROR_OTHER);
536         }
537
538         if (strcmp (item, "VmRSS") == 0 || strcmp (item, "VmHWM") == 0 || strcmp (item, "VmData") == 0)
539                 ret = t_info.resident_size;
540         else if (strcmp (item, "VmSize") == 0 || strcmp (item, "VmPeak") == 0)
541                 ret = t_info.virtual_size;
542         else if (strcmp (item, "Threads") == 0)
543                 ret = th_count;
544         else
545                 ret = 0;
546
547         if (pid != getpid ())
548                 mach_port_deallocate (mach_task_self (), task);
549         
550         return ret;
551 #else
552         char buf [64];
553         char *s;
554
555         s = get_pid_status_item_buf (pid, item, buf, sizeof (buf), error);
556         if (s)
557                 return ((gint64) atol (s)) * multiplier;
558         return 0;
559 #endif
560 }
561
562 /**
563  * mono_process_get_data:
564  * @pid: pid of the process
565  * @data: description of data to return
566  *
567  * Return a data item of a process like user time, memory use etc,
568  * according to the @data argumet.
569  */
570 gint64
571 mono_process_get_data_with_error (gpointer pid, MonoProcessData data, MonoProcessError *error)
572 {
573         gint64 val;
574         int rpid = GPOINTER_TO_INT (pid);
575
576         if (error)
577                 *error = MONO_PROCESS_ERROR_OTHER;
578
579         switch (data) {
580         case MONO_PROCESS_NUM_THREADS:
581                 return get_pid_status_item (rpid, "Threads", error, 1);
582         case MONO_PROCESS_USER_TIME:
583                 return get_process_stat_time (rpid, 10, FALSE, error);
584         case MONO_PROCESS_SYSTEM_TIME:
585                 return get_process_stat_time (rpid, 11, FALSE, error);
586         case MONO_PROCESS_TOTAL_TIME:
587                 return get_process_stat_time (rpid, 10, TRUE, error);
588         case MONO_PROCESS_WORKING_SET:
589                 return get_pid_status_item (rpid, "VmRSS", error, 1024);
590         case MONO_PROCESS_WORKING_SET_PEAK:
591                 val = get_pid_status_item (rpid, "VmHWM", error, 1024);
592                 if (val == 0)
593                         val = get_pid_status_item (rpid, "VmRSS", error, 1024);
594                 return val;
595         case MONO_PROCESS_PRIVATE_BYTES:
596                 return get_pid_status_item (rpid, "VmData", error, 1024);
597         case MONO_PROCESS_VIRTUAL_BYTES:
598                 return get_pid_status_item (rpid, "VmSize", error, 1024);
599         case MONO_PROCESS_VIRTUAL_BYTES_PEAK:
600                 val = get_pid_status_item (rpid, "VmPeak", error, 1024);
601                 if (val == 0)
602                         val = get_pid_status_item (rpid, "VmSize", error, 1024);
603                 return val;
604         case MONO_PROCESS_FAULTS:
605                 return get_process_stat_item (rpid, 6, TRUE, error);
606         case MONO_PROCESS_ELAPSED:
607                 return get_process_stat_time (rpid, 18, FALSE, error);
608         case MONO_PROCESS_PPID:
609                 return get_process_stat_time (rpid, 0, FALSE, error);
610         case MONO_PROCESS_PAGED_BYTES:
611                 return get_pid_status_item (rpid, "VmSwap", error, 1024);
612
613                 /* Nothing yet */
614         case MONO_PROCESS_END:
615                 return 0;
616         }
617         return 0;
618 }
619
620 gint64
621 mono_process_get_data (gpointer pid, MonoProcessData data)
622 {
623         MonoProcessError error;
624         return mono_process_get_data_with_error (pid, data, &error);
625 }
626
627 int
628 mono_process_current_pid ()
629 {
630 #if defined(HAVE_UNISTD_H)
631         return (int) getpid ();
632 #elif defined(HOST_WIN32)
633         return (int) GetCurrentProcessId ();
634 #else
635 #error getpid
636 #endif
637 }
638
639 /**
640  * mono_cpu_count:
641  *
642  * Return the number of processors on the system.
643  */
644 int
645 mono_cpu_count (void)
646 {
647 #ifdef HOST_WIN32
648         SYSTEM_INFO info;
649         GetSystemInfo (&info);
650         return info.dwNumberOfProcessors;
651 #else
652 #ifdef PLATFORM_ANDROID
653         /* Android tries really hard to save power by powering off CPUs on SMP phones which
654          * means the normal way to query cpu count returns a wrong value with userspace API.
655          * Instead we use /sys entries to query the actual hardware CPU count.
656          */
657         int count = 0;
658         char buffer[8] = {'\0'};
659         int present = open ("/sys/devices/system/cpu/present", O_RDONLY);
660         /* Format of the /sys entry is a cpulist of indexes which in the case
661          * of present is always of the form "0-(n-1)" when there is more than
662          * 1 core, n being the number of CPU cores in the system. Otherwise
663          * the value is simply 0
664          */
665         if (present != -1 && read (present, (char*)buffer, sizeof (buffer)) > 3)
666                 count = strtol (((char*)buffer) + 2, NULL, 10);
667         if (present != -1)
668                 close (present);
669         if (count > 0)
670                 return count + 1;
671 #endif
672
673 #if defined(HOST_ARM) || defined (HOST_ARM64)
674
675 /*
676  * Recap from Alexander Köplinger <alex.koeplinger@outlook.com>:
677  *
678  * When we merged the change from PR #2722, we started seeing random failures on ARM in
679  * the MonoTests.System.Threading.ThreadPoolTests.SetAndGetMaxThreads and
680  * MonoTests.System.Threading.ManualResetEventSlimTests.Constructor_Defaults tests. Both
681  * of those tests are dealing with Environment.ProcessorCount to verify some implementation
682  * details.
683  *
684  * It turns out that on the Jetson TK1 board we use on public Jenkins and on ARM kernels
685  * in general, the value returned by sched_getaffinity (or _SC_NPROCESSORS_ONLN) doesn't
686  * contain CPUs/cores that are powered off for power saving reasons. This is contrary to
687  * what happens on x86, where even cores in deep-sleep state are returned [1], [2]. This
688  * means that we would get a processor count of 1 at one point in time and a higher value
689  * when load increases later on as the system wakes CPUs.
690  *
691  * Various runtime pieces like the threadpool and also user code however relies on the
692  * value returned by Environment.ProcessorCount e.g. for deciding how many parallel tasks
693  * to start, thereby limiting the performance when that code thinks we only have one CPU.
694  *
695  * Talking to a few people, this was the reason why we changed to _SC_NPROCESSORS_CONF in
696  * mono#1688 and why we added a special case for Android in mono@de3addc to get the "real"
697  * number of processors in the system.
698  *
699  * Because of those issues Android/Dalvik also switched from _ONLN to _SC_NPROCESSORS_CONF
700  * for the Java API Runtime.availableProcessors() too [3], citing:
701  * > Traditionally this returned the number currently online, but many mobile devices are
702  * able to take unused cores offline to save power, so releases newer than Android 4.2 (Jelly
703  * Bean) return the maximum number of cores that could be made available if there were no
704  * power or heat constraints.
705  *
706  * The problem with sticking to _SC_NPROCESSORS_CONF however is that it breaks down in
707  * constrained environments like Docker or with an explicit CPU affinity set by the Linux
708  * `taskset` command, They'd get a higher CPU count than can be used, start more threads etc.
709  * which results in unnecessary context switches and overloaded systems. That's why we need
710  * to respect sched_getaffinity.
711  *
712  * So while in an ideal world we would be able to rely on sched_getaffinity/_SC_NPROCESSORS_ONLN
713  * to return the number of theoretically available CPUs regardless of power saving measures
714  * everywhere, we can't do this on ARM.
715  *
716  * I think the pragmatic solution is the following:
717  * * use sched_getaffinity (+ fallback to _SC_NPROCESSORS_ONLN in case of error) on x86. This
718  * ensures we're inline with what OpenJDK [4] and CoreCLR [5] do
719  * * use _SC_NPROCESSORS_CONF exclusively on ARM (I think we could eventually even get rid of
720  * the PLATFORM_ANDROID special case)
721  *
722  * Helpful links:
723  *
724  * [1] https://sourceware.org/ml/libc-alpha/2013-07/msg00383.html
725  * [2] https://lists.01.org/pipermail/powertop/2012-September/000433.html
726  * [3] https://android.googlesource.com/platform/libcore/+/750dc634e56c58d1d04f6a138734ac2b772900b5%5E1..750dc634e56c58d1d04f6a138734ac2b772900b5/
727  * [4] https://bugs.openjdk.java.net/browse/JDK-6515172
728  * [5] https://github.com/dotnet/coreclr/blob/7058273693db2555f127ce16e6b0c5b40fb04867/src/pal/src/misc/sysinfo.cpp#L148
729  */
730
731 #ifdef _SC_NPROCESSORS_CONF
732         {
733                 int count = sysconf (_SC_NPROCESSORS_CONF);
734                 if (count > 0)
735                         return count;
736         }
737 #endif
738
739 #else
740
741 #ifdef HAVE_SCHED_GETAFFINITY
742         {
743                 cpu_set_t set;
744                 if (sched_getaffinity (mono_process_current_pid (), sizeof (set), &set) == 0)
745                         return CPU_COUNT (&set);
746         }
747 #endif
748 #ifdef _SC_NPROCESSORS_ONLN
749         {
750                 int count = sysconf (_SC_NPROCESSORS_ONLN);
751                 if (count > 0)
752                         return count;
753         }
754 #endif
755
756 #endif /* defined(HOST_ARM) || defined (HOST_ARM64) */
757
758 #ifdef USE_SYSCTL
759         {
760                 int count;
761                 int mib [2];
762                 size_t len = sizeof (int);
763                 mib [0] = CTL_HW;
764                 mib [1] = HW_NCPU;
765                 if (sysctl (mib, 2, &count, &len, NULL, 0) == 0)
766                         return count;
767         }
768 #endif
769 #endif /* HOST_WIN32 */
770         /* FIXME: warn */
771         return 1;
772 }
773
774 static void
775 get_cpu_times (int cpu_id, gint64 *user, gint64 *systemt, gint64 *irq, gint64 *sirq, gint64 *idle)
776 {
777         char buf [256];
778         char *s;
779         int hz = get_user_hz ();
780         guint64 user_ticks = 0, nice_ticks = 0, system_ticks = 0, idle_ticks = 0, irq_ticks = 0, sirq_ticks = 0;
781         FILE *f = fopen ("/proc/stat", "r");
782         if (!f)
783                 return;
784         if (cpu_id < 0)
785                 hz *= mono_cpu_count ();
786         while ((s = fgets (buf, sizeof (buf), f))) {
787                 char *data = NULL;
788                 if (cpu_id < 0 && strncmp (s, "cpu", 3) == 0 && g_ascii_isspace (s [3])) {
789                         data = s + 4;
790                 } else if (cpu_id >= 0 && strncmp (s, "cpu", 3) == 0 && strtol (s + 3, &data, 10) == cpu_id) {
791                         if (data == s + 3)
792                                 continue;
793                         data++;
794                 } else {
795                         continue;
796                 }
797                 
798                 user_ticks = strtoull (data, &data, 10);
799                 nice_ticks = strtoull (data, &data, 10);
800                 system_ticks = strtoull (data, &data, 10);
801                 idle_ticks = strtoull (data, &data, 10);
802                 /* iowait_ticks = strtoull (data, &data, 10); */
803                 irq_ticks = strtoull (data, &data, 10);
804                 sirq_ticks = strtoull (data, &data, 10);
805                 break;
806         }
807         fclose (f);
808
809         if (user)
810                 *user = (user_ticks + nice_ticks) * 10000000 / hz;
811         if (systemt)
812                 *systemt = (system_ticks) * 10000000 / hz;
813         if (irq)
814                 *irq = (irq_ticks) * 10000000 / hz;
815         if (sirq)
816                 *sirq = (sirq_ticks) * 10000000 / hz;
817         if (idle)
818                 *idle = (idle_ticks) * 10000000 / hz;
819 }
820
821 /**
822  * mono_cpu_get_data:
823  * @cpu_id: processor number or -1 to get a summary of all the processors
824  * @data: type of data to retrieve
825  *
826  * Get data about a processor on the system, like time spent in user space or idle time.
827  */
828 gint64
829 mono_cpu_get_data (int cpu_id, MonoCpuData data, MonoProcessError *error)
830 {
831         gint64 value = 0;
832
833         if (error)
834                 *error = MONO_PROCESS_ERROR_NONE;
835         switch (data) {
836         case MONO_CPU_USER_TIME:
837                 get_cpu_times (cpu_id, &value, NULL, NULL, NULL, NULL);
838                 break;
839         case MONO_CPU_PRIV_TIME:
840                 get_cpu_times (cpu_id, NULL, &value, NULL, NULL, NULL);
841                 break;
842         case MONO_CPU_INTR_TIME:
843                 get_cpu_times (cpu_id, NULL, NULL, &value, NULL, NULL);
844                 break;
845         case MONO_CPU_DCP_TIME:
846                 get_cpu_times (cpu_id, NULL, NULL, NULL, &value, NULL);
847                 break;
848         case MONO_CPU_IDLE_TIME:
849                 get_cpu_times (cpu_id, NULL, NULL, NULL, NULL, &value);
850                 break;
851
852         case MONO_CPU_END:
853                 /* Nothing yet */
854                 return 0;
855         }
856         return value;
857 }
858
859 int
860 mono_atexit (void (*func)(void))
861 {
862 #ifdef PLATFORM_ANDROID
863         /* Some versions of android libc doesn't define atexit () */
864         return 0;
865 #else
866         return atexit (func);
867 #endif
868 }
869
870 /*
871  * This function returns the cpu usage in percentage,
872  * normalized on the number of cores.
873  *
874  * Warning : the percentage returned can be > 100%. This
875  * might happens on systems like Android which, for
876  * battery and performance reasons, shut down cores and
877  * lie about the number of active cores.
878  */
879 gint32
880 mono_cpu_usage (MonoCpuUsageState *prev)
881 {
882         gint32 cpu_usage = 0;
883         gint64 cpu_total_time;
884         gint64 cpu_busy_time;
885
886 #ifndef HOST_WIN32
887         struct rusage resource_usage;
888         gint64 current_time;
889         gint64 kernel_time;
890         gint64 user_time;
891
892         if (getrusage (RUSAGE_SELF, &resource_usage) == -1) {
893                 g_error ("getrusage() failed, errno is %d (%s)\n", errno, strerror (errno));
894                 return -1;
895         }
896
897         current_time = mono_100ns_ticks ();
898         kernel_time = resource_usage.ru_stime.tv_sec * 1000 * 1000 * 10 + resource_usage.ru_stime.tv_usec * 10;
899         user_time = resource_usage.ru_utime.tv_sec * 1000 * 1000 * 10 + resource_usage.ru_utime.tv_usec * 10;
900
901         cpu_busy_time = (user_time - (prev ? prev->user_time : 0)) + (kernel_time - (prev ? prev->kernel_time : 0));
902         cpu_total_time = (current_time - (prev ? prev->current_time : 0)) * mono_cpu_count ();
903
904         if (prev) {
905                 prev->kernel_time = kernel_time;
906                 prev->user_time = user_time;
907                 prev->current_time = current_time;
908         }
909 #else
910         guint64 idle_time;
911         guint64 kernel_time;
912         guint64 user_time;
913
914         if (!GetSystemTimes ((FILETIME*) &idle_time, (FILETIME*) &kernel_time, (FILETIME*) &user_time)) {
915                 g_error ("GetSystemTimes() failed, error code is %d\n", GetLastError ());
916                 return -1;
917         }
918
919         cpu_total_time = (gint64)((user_time - (prev ? prev->user_time : 0)) + (kernel_time - (prev ? prev->kernel_time : 0)));
920         cpu_busy_time = (gint64)(cpu_total_time - (idle_time - (prev ? prev->idle_time : 0)));
921
922         if (prev) {
923                 prev->idle_time = idle_time;
924                 prev->kernel_time = kernel_time;
925                 prev->user_time = user_time;
926         }
927 #endif
928
929         if (cpu_total_time > 0 && cpu_busy_time > 0)
930                 cpu_usage = (gint32)(cpu_busy_time * 100 / cpu_total_time);
931
932         return cpu_usage;
933 }