2010-03-12 Jb Evain <jbevain@novell.com>
[mono.git] / mono / metadata / mono-perfcounters.c
1 /*
2  * mono-perfcounters.c
3  *
4  * Performance counters support.
5  *
6  * Author: Paolo Molaro (lupus@ximian.com)
7  *
8  * Copyright 2008-2009 Novell, Inc (http://www.novell.com)
9  */
10
11 #include "config.h"
12 #include <time.h>
13 #include <string.h>
14 #include <stdlib.h>
15 #ifdef HAVE_SYS_TIME_H
16 #include <sys/time.h>
17 #endif
18 #include "metadata/mono-perfcounters.h"
19 #include "metadata/appdomain.h"
20 #include "metadata/object-internals.h"
21 /* for mono_stats */
22 #include "metadata/class-internals.h"
23 #include "utils/mono-time.h"
24 #include "utils/mono-mmap.h"
25 #include "utils/mono-proclib.h"
26 #include "utils/mono-networkinterfaces.h"
27 #include "utils/mono-error-internals.h"
28 #include <mono/io-layer/io-layer.h>
29
30 /* map of CounterSample.cs */
31 struct _MonoCounterSample {
32         gint64 rawValue;
33         gint64 baseValue;
34         gint64 counterFrequency;
35         gint64 systemFrequency;
36         gint64 timeStamp;
37         gint64 timeStamp100nSec;
38         gint64 counterTimeStamp;
39         int counterType;
40 };
41
42 /* map of PerformanceCounterType.cs */
43 enum {
44         NumberOfItemsHEX32=0x00000000,
45         NumberOfItemsHEX64=0x00000100,
46         NumberOfItems32=0x00010000,
47         NumberOfItems64=0x00010100,
48         CounterDelta32=0x00400400,
49         CounterDelta64=0x00400500,
50         SampleCounter=0x00410400,
51         CountPerTimeInterval32=0x00450400,
52         CountPerTimeInterval64=0x00450500,
53         RateOfCountsPerSecond32=0x10410400,
54         RateOfCountsPerSecond64=0x10410500,
55         RawFraction=0x20020400,
56         CounterTimer=0x20410500,
57         Timer100Ns=0x20510500,
58         SampleFraction=0x20C20400,
59         CounterTimerInverse=0x21410500,
60         Timer100NsInverse=0x21510500,
61         CounterMultiTimer=0x22410500,
62         CounterMultiTimer100Ns=0x22510500,
63         CounterMultiTimerInverse=0x23410500,
64         CounterMultiTimer100NsInverse=0x23510500,
65         AverageTimer32=0x30020400,
66         ElapsedTime=0x30240500,
67         AverageCount64=0x40020500,
68         SampleBase=0x40030401,
69         AverageBase=0x40030402,
70         RawBase=0x40030403,
71         CounterMultiBase=0x42030500
72 };
73
74 /* maps a small integer type to the counter types above */
75 static const int
76 simple_type_to_type [] = {
77         NumberOfItemsHEX32, NumberOfItemsHEX64,
78         NumberOfItems32, NumberOfItems64,
79         CounterDelta32, CounterDelta64,
80         SampleCounter, CountPerTimeInterval32,
81         CountPerTimeInterval64, RateOfCountsPerSecond32,
82         RateOfCountsPerSecond64, RawFraction,
83         CounterTimer, Timer100Ns,
84         SampleFraction, CounterTimerInverse,
85         Timer100NsInverse, CounterMultiTimer,
86         CounterMultiTimer100Ns, CounterMultiTimerInverse,
87         CounterMultiTimer100NsInverse, AverageTimer32,
88         ElapsedTime, AverageCount64,
89         SampleBase, AverageBase,
90         RawBase, CounterMultiBase
91 };
92
93 enum {
94         SingleInstance,
95         MultiInstance,
96         CatTypeUnknown = -1
97 };
98
99 enum {
100         ProcessInstance,
101         ThreadInstance,
102         CPUInstance,
103         MonoInstance,
104         NetworkInterfaceInstance,
105         CustomInstance
106 };
107
108 #define PERFCTR_CAT(id,name,help,type,inst,first_counter) CATEGORY_ ## id,
109 #define PERFCTR_COUNTER(id,name,help,type,field)
110 enum {
111 #include "mono-perfcounters-def.h"
112         NUM_CATEGORIES
113 };
114
115 #undef PERFCTR_CAT
116 #undef PERFCTR_COUNTER
117 #define PERFCTR_CAT(id,name,help,type,inst,first_counter) CATEGORY_START_ ## id = -1,
118 #define PERFCTR_COUNTER(id,name,help,type,field) COUNTER_ ## id,
119 /* each counter is assigned an id starting from 0 inside the category */
120 enum {
121 #include "mono-perfcounters-def.h"
122         END_COUNTERS
123 };
124
125 #undef PERFCTR_CAT
126 #undef PERFCTR_COUNTER
127 #define PERFCTR_CAT(id,name,help,type,inst,first_counter)
128 #define PERFCTR_COUNTER(id,name,help,type,field) CCOUNTER_ ## id,
129 /* this is used just to count the number of counters */
130 enum {
131 #include "mono-perfcounters-def.h"
132         NUM_COUNTERS
133 };
134
135 static CRITICAL_SECTION perfctr_mutex;
136 #define perfctr_lock() EnterCriticalSection (&perfctr_mutex)
137 #define perfctr_unlock() LeaveCriticalSection (&perfctr_mutex)
138
139 typedef struct {
140         char reserved [16];
141         int size;
142         unsigned short counters_start;
143         unsigned short counters_size;
144         unsigned short data_start;
145         MonoPerfCounters counters;
146         char data [1];
147 } MonoSharedArea;
148
149 /*
150   binary format of custom counters in shared memory, starting from MonoSharedArea* + data_start;
151   basic stanza:
152   struct stanza_header {
153         byte stanza_type; // FTYPE_*
154         byte other_info;
155         ushort stanza_length; // includeas header
156         ... data ...
157   }
158
159 // strings are utf8
160 // perfcat and perfinstance are 4-bytes aligned
161 struct perfcat {
162         byte typeidx;
163         byte categorytype;
164         ushort length; // includes the counters
165         ushort num_counters;
166         ushort counters_data_size;
167         int num_instances;
168         char name[]; // null terminated
169         char help[]; // null terminated
170         // perfcounters follow
171         {
172                 byte countertype;
173                 char name[]; // null terminated
174                 char help[]; // null terminated
175         }
176         0-byte
177 };
178
179 struct perfinstance {
180         byte typeidx;
181         byte data_offset; // offset of counters from beginning of struct
182         ushort length;
183         uint category_offset; // offset of category in the shared area
184         char name[]; // null terminated
185         // data follows: this is always 8-byte aligned
186 };
187
188 */
189
190 enum {
191         FTYPE_CATEGORY = 'C',
192         FTYPE_DELETED = 'D',
193         FTYPE_PREDEF_INSTANCE = 'P', // an instance of a predef counter
194         FTYPE_INSTANCE = 'I',
195         FTYPE_DIRTY = 'd',
196         FTYPE_END = 0
197 };
198
199 typedef struct {
200         unsigned char ftype;
201         unsigned char extra;
202         unsigned short size;
203 } SharedHeader;
204
205 typedef struct {
206         SharedHeader header;
207         unsigned short num_counters;
208         unsigned short counters_data_size;
209         int num_instances;
210         /* variable length data follows */
211         char name [1];
212 } SharedCategory;
213
214 typedef struct {
215         SharedHeader header;
216         unsigned int category_offset;
217         /* variable length data follows */
218         char instance_name [1];
219 } SharedInstance;
220
221 typedef struct {
222         unsigned char type;
223         guint8 seq_num;
224         /* variable length data follows */
225         char name [1];
226 } SharedCounter;
227
228 typedef struct {
229         const char *name;
230         const char *help;
231         unsigned char id;
232         signed int type : 2;
233         unsigned int instance_type : 6;
234         short first_counter;
235 } CategoryDesc;
236
237 typedef struct {
238         const char *name;
239         const char *help;
240         short id;
241         unsigned short offset; // offset inside MonoPerfCounters
242         int type;
243 } CounterDesc;
244
245 #undef PERFCTR_CAT
246 #undef PERFCTR_COUNTER
247 #define PERFCTR_CAT(id,name,help,type,inst,first_counter) {name, help, CATEGORY_ ## id, type, inst ## Instance, CCOUNTER_ ## first_counter},
248 #define PERFCTR_COUNTER(id,name,help,type,field)
249 static const CategoryDesc
250 predef_categories [] = {
251 #include "mono-perfcounters-def.h"
252         {NULL, NULL, NUM_CATEGORIES, -1, 0, NUM_COUNTERS}
253 };
254
255 #undef PERFCTR_CAT
256 #undef PERFCTR_COUNTER
257 #define PERFCTR_CAT(id,name,help,type,inst,first_counter)
258 #define PERFCTR_COUNTER(id,name,help,type,field) {name, help, COUNTER_ ## id, G_STRUCT_OFFSET (MonoPerfCounters, field), type},
259 static const CounterDesc
260 predef_counters [] = {
261 #include "mono-perfcounters-def.h"
262         {NULL, NULL, -1, 0, 0}
263 };
264
265 /*
266  * We have several different classes of counters:
267  * *) system counters
268  * *) runtime counters
269  * *) remote counters
270  * *) user-defined counters
271  * *) windows counters (the implementation on windows will use this)
272  *
273  * To easily handle the differences we create a vtable for each class that contains the
274  * function pointers with the actual implementation to access the counters.
275  */
276 typedef struct _ImplVtable ImplVtable;
277
278 typedef MonoBoolean (*SampleFunc) (ImplVtable *vtable, MonoBoolean only_value, MonoCounterSample* sample);
279 typedef gint64 (*UpdateFunc) (ImplVtable *vtable, MonoBoolean do_incr, gint64 value);
280 typedef void (*CleanupFunc) (ImplVtable *vtable);
281
282 struct _ImplVtable {
283         void *arg;
284         SampleFunc sample;
285         UpdateFunc update;
286         CleanupFunc cleanup;
287 };
288
289 typedef struct {
290         int id;
291         char *name;
292 } NetworkVtableArg;
293
294 typedef struct {
295         ImplVtable vtable;
296         MonoPerfCounters *counters;
297         int pid;
298 } PredefVtable;
299
300 typedef struct {
301         ImplVtable vtable;
302         SharedInstance *instance_desc;
303         SharedCounter *counter_desc;
304 } CustomVTable;
305
306 static ImplVtable*
307 create_vtable (void *arg, SampleFunc sample, UpdateFunc update)
308 {
309         ImplVtable *vtable = g_new0 (ImplVtable, 1);
310         vtable->arg = arg;
311         vtable->sample = sample;
312         vtable->update = update;
313         return vtable;
314 }
315
316 MonoPerfCounters *mono_perfcounters = NULL;
317 static MonoSharedArea *shared_area = NULL;
318
319 typedef struct {
320         void *sarea;
321         int refcount;
322 } ExternalSArea;
323
324 /* maps a pid to a ExternalSArea pointer */
325 static GHashTable *pid_to_shared_area = NULL;
326
327 static MonoSharedArea *
328 load_sarea_for_pid (int pid)
329 {
330         ExternalSArea *data;
331         MonoSharedArea *area = NULL;
332
333         perfctr_lock ();
334         if (pid_to_shared_area == NULL)
335                 pid_to_shared_area = g_hash_table_new (NULL, NULL);
336         data = g_hash_table_lookup (pid_to_shared_area, GINT_TO_POINTER (pid));
337         if (!data) {
338                 area = mono_shared_area_for_pid (GINT_TO_POINTER (pid));
339                 if (area) {
340                         data = g_new (ExternalSArea, 1);
341                         data->sarea = area;
342                         data->refcount = 1;
343                         g_hash_table_insert (pid_to_shared_area, GINT_TO_POINTER (pid), data);
344                 }
345         } else {
346                 area = data->sarea;
347                 data->refcount ++;
348         }
349         perfctr_unlock ();
350         return area;
351 }
352
353 static void
354 unref_pid_unlocked (int pid)
355 {
356         ExternalSArea *data;
357         data = g_hash_table_lookup (pid_to_shared_area, GINT_TO_POINTER (pid));
358         if (data) {
359                 data->refcount--;
360                 if (!data->refcount) {
361                         g_hash_table_remove (pid_to_shared_area, GINT_TO_POINTER (pid));
362                         mono_shared_area_unload (data->sarea);
363                         g_free (data);
364                 }
365         }
366 }
367
368 static void
369 predef_cleanup (ImplVtable *vtable)
370 {
371         PredefVtable *vt = (PredefVtable*)vtable;
372         /* ExternalSArea *data; */
373         
374         perfctr_lock ();
375         if (!pid_to_shared_area) {
376                 perfctr_unlock ();
377                 return;
378         }
379         unref_pid_unlocked (vt->pid);
380         perfctr_unlock ();
381 }
382
383 void
384 mono_perfcounters_init (void)
385 {
386         int d_offset = G_STRUCT_OFFSET (MonoSharedArea, data);
387         d_offset += 7;
388         d_offset &= ~7;
389
390         InitializeCriticalSection (&perfctr_mutex);
391
392         shared_area = mono_shared_area ();
393         shared_area->counters_start = G_STRUCT_OFFSET (MonoSharedArea, counters);
394         shared_area->counters_size = sizeof (MonoPerfCounters);
395         shared_area->data_start = d_offset;
396         shared_area->size = 4096;
397         mono_perfcounters = &shared_area->counters;
398 }
399
400 static int
401 perfctr_type_compress (int type)
402 {
403         int i;
404         for (i = 0; i < G_N_ELEMENTS (simple_type_to_type); ++i) {
405                 if (simple_type_to_type [i] == type)
406                         return i;
407         }
408         /* NumberOfItems32 */
409         return 2;
410 }
411
412 static unsigned char*
413 shared_data_find_room (int size)
414 {
415         unsigned char *p = (unsigned char *)shared_area + shared_area->data_start;
416         unsigned char *end = (unsigned char *)shared_area + shared_area->size;
417
418         size += 7;
419         size &= ~7;
420         while (p < end) {
421                 unsigned short *next;
422                 if (*p == FTYPE_END) {
423                         if (size < (end - p))
424                                 return p;
425                         return NULL;
426                 }
427                 if (p + 4 > end)
428                         return NULL;
429                 next = (unsigned short*)(p + 2);
430                 if (*p == FTYPE_DELETED) {
431                         /* we reuse only if it's the same size */
432                         if (*next == size) {
433                                 return p;
434                         }
435                 }
436                 p += *next;
437         }
438         return NULL;
439 }
440
441 typedef gboolean (*SharedFunc) (SharedHeader *header, void *data);
442
443 static void
444 foreach_shared_item_in_area (unsigned char *p, unsigned char *end, SharedFunc func, void *data)
445 {
446         while (p < end) {
447                 unsigned short *next;
448                 if (p + 4 > end)
449                         return;
450                 next = (unsigned short*)(p + 2);
451                 if (!func ((SharedHeader*)p, data))
452                         return;
453                 if (*p == FTYPE_END)
454                         return;
455                 p += *next;
456         }
457 }
458
459 static void
460 foreach_shared_item (SharedFunc func, void *data)
461 {
462         unsigned char *p = (unsigned char *)shared_area + shared_area->data_start;
463         unsigned char *end = (unsigned char *)shared_area + shared_area->size;
464
465         foreach_shared_item_in_area (p, end, func, data);
466 }
467
468 static int
469 mono_string_compare_ascii (MonoString *str, const char *ascii_str)
470 {
471         /* FIXME: make this case insensitive */
472         guint16 *strc = mono_string_chars (str);
473         while (*strc == *ascii_str++) {
474                 if (*strc == 0)
475                         return 0;
476                 strc++;
477         }
478         return *strc - *(const unsigned char *)(ascii_str - 1);
479 }
480
481 typedef struct {
482         MonoString *name;
483         SharedCategory *cat;
484 } CatSearch;
485
486 static gboolean
487 category_search (SharedHeader *header, void *data)
488 {
489         CatSearch *search = data;
490         if (header->ftype == FTYPE_CATEGORY) {
491                 SharedCategory *cat = (SharedCategory*)header;
492                 if (mono_string_compare_ascii (search->name, cat->name) == 0) {
493                         search->cat = cat;
494                         return FALSE;
495                 }
496         }
497         return TRUE;
498 }
499
500 static SharedCategory*
501 find_custom_category (MonoString *name)
502 {
503         CatSearch search;
504         search.name = name;
505         search.cat = NULL;
506         foreach_shared_item (category_search, &search);
507         return search.cat;
508 }
509
510 static gboolean
511 category_collect (SharedHeader *header, void *data)
512 {
513         GSList **list = data;
514         if (header->ftype == FTYPE_CATEGORY) {
515                 *list = g_slist_prepend (*list, header);
516         }
517         return TRUE;
518 }
519
520 static GSList*
521 get_custom_categories (void) {
522         GSList *list = NULL;
523         foreach_shared_item (category_collect, &list);
524         return list;
525 }
526
527 static char*
528 custom_category_counters (SharedCategory* cat)
529 {
530         char *p = cat->name + strlen (cat->name) + 1;
531         p += strlen (p) + 1; /* skip category help */
532         return p;
533 }
534
535 static SharedCounter*
536 find_custom_counter (SharedCategory* cat, MonoString *name)
537 {
538         int i;
539         char *p = custom_category_counters (cat);
540         for (i = 0; i < cat->num_counters; ++i) {
541                 SharedCounter *counter = (SharedCounter*)p;
542                 if (mono_string_compare_ascii (name, counter->name) == 0)
543                         return counter;
544                 p += 1 + strlen (p + 1) + 1; /* skip counter type and name */
545                 p += strlen (p) + 1; /* skip counter help */
546         }
547         return NULL;
548 }
549
550 typedef struct {
551         unsigned int cat_offset;
552         SharedCategory* cat;
553         MonoString *instance;
554         SharedInstance* result;
555         GSList *list;
556 } InstanceSearch;
557
558 static gboolean
559 instance_search (SharedHeader *header, void *data)
560 {
561         InstanceSearch *search = data;
562         if (header->ftype == FTYPE_INSTANCE) {
563                 SharedInstance *ins = (SharedInstance*)header;
564                 if (search->cat_offset == ins->category_offset) {
565                         if (search->instance) {
566                                 if (mono_string_compare_ascii (search->instance, ins->instance_name) == 0) {
567                                         search->result = ins;
568                                         return FALSE;
569                                 }
570                         } else {
571                                 search->list = g_slist_prepend (search->list, ins);
572                         }
573                 }
574         }
575         return TRUE;
576 }
577
578 static SharedInstance*
579 find_custom_instance (SharedCategory* cat, MonoString *instance)
580 {
581         InstanceSearch search;
582         search.cat_offset = (char*)cat - (char*)shared_area;
583         search.cat = cat;
584         search.instance = instance;
585         search.list = NULL;
586         search.result = NULL;
587         foreach_shared_item (instance_search, &search);
588         return search.result;
589 }
590
591 static GSList*
592 get_custom_instances_list (SharedCategory* cat)
593 {
594         InstanceSearch search;
595         search.cat_offset = (char*)cat - (char*)shared_area;
596         search.cat = cat;
597         search.instance = NULL;
598         search.list = NULL;
599         search.result = NULL;
600         foreach_shared_item (instance_search, &search);
601         return search.list;
602 }
603
604 static char*
605 custom_category_help (SharedCategory* cat)
606 {
607         return cat->name + strlen (cat->name) + 1;
608 }
609
610 static const CounterDesc*
611 get_counter_in_category (const CategoryDesc *desc, MonoString *counter)
612 {
613         const CounterDesc *cdesc = &predef_counters [desc->first_counter];
614         const CounterDesc *end = &predef_counters [desc [1].first_counter];
615         for (; cdesc < end; ++cdesc) {
616                 if (mono_string_compare_ascii (counter, cdesc->name) == 0)
617                         return cdesc;
618         }
619         return NULL;
620 }
621
622 /* fill the info in sample (except the raw value) */
623 static void
624 fill_sample (MonoCounterSample *sample)
625 {
626         sample->timeStamp = mono_100ns_ticks ();
627         sample->timeStamp100nSec = sample->timeStamp;
628         sample->counterTimeStamp = sample->timeStamp;
629         sample->counterFrequency = 10000000;
630         sample->systemFrequency = 10000000;
631         // the real basevalue needs to be get from a different counter...
632         sample->baseValue = 0;
633 }
634
635 static int
636 id_from_string (MonoString *instance, gboolean is_process)
637 {
638         int id = -1;
639         if (mono_string_length (instance)) {
640                 char *id_str = mono_string_to_utf8 (instance);
641                 char *end;
642                 id = strtol (id_str, &end, 0);
643                 if (end == id_str && !is_process)
644                         id = -1;
645                 g_free (id_str);
646         }
647         return id;
648 }
649
650 static MonoBoolean
651 get_cpu_counter (ImplVtable *vtable, MonoBoolean only_value, MonoCounterSample *sample)
652 {
653         MonoProcessError error;
654         int id = GPOINTER_TO_INT (vtable->arg);
655         int pid = id >> 5;
656         id &= 0x1f;
657         if (!only_value) {
658                 fill_sample (sample);
659                 sample->baseValue = 1;
660         }
661         sample->counterType = predef_counters [predef_categories [CATEGORY_CPU].first_counter + id].type;
662         switch (id) {
663         case COUNTER_CPU_USER_TIME:
664                 sample->rawValue = mono_cpu_get_data (pid, MONO_CPU_USER_TIME, &error);
665                 return TRUE;
666         case COUNTER_CPU_PRIV_TIME:
667                 sample->rawValue = mono_cpu_get_data (pid, MONO_CPU_PRIV_TIME, &error);
668                 return TRUE;
669         case COUNTER_CPU_INTR_TIME:
670                 sample->rawValue = mono_cpu_get_data (pid, MONO_CPU_INTR_TIME, &error);
671                 return TRUE;
672         case COUNTER_CPU_DCP_TIME:
673                 sample->rawValue = mono_cpu_get_data (pid, MONO_CPU_DCP_TIME, &error);
674                 return TRUE;
675         case COUNTER_CPU_PROC_TIME:
676                 sample->rawValue = mono_cpu_get_data (pid, MONO_CPU_IDLE_TIME, &error);
677                 return TRUE;
678         }
679         return FALSE;
680 }
681
682 static void*
683 cpu_get_impl (MonoString* counter, MonoString* instance, int *type, MonoBoolean *custom)
684 {
685         int id = id_from_string (instance, FALSE) << 5;
686         const CounterDesc *cdesc;
687         *custom = FALSE;
688         /* increase the shift above and the mask also in the implementation functions */
689         //g_assert (32 > desc [1].first_counter - desc->first_counter);
690         if ((cdesc = get_counter_in_category (&predef_categories [CATEGORY_CPU], counter))) {
691                 *type = cdesc->type;
692                 return create_vtable (GINT_TO_POINTER (id | cdesc->id), get_cpu_counter, NULL);
693         }
694         return NULL;
695 }
696
697 static MonoBoolean
698 get_network_counter (ImplVtable *vtable, MonoBoolean only_value, MonoCounterSample *sample)
699 {
700         MonoNetworkError error = MONO_NETWORK_ERROR_OTHER;
701         NetworkVtableArg *narg = (NetworkVtableArg*) vtable->arg;
702         if (!only_value) {
703                 fill_sample (sample);
704         }
705
706         sample->counterType = predef_counters [predef_categories [CATEGORY_NETWORK].first_counter + narg->id].type;
707         switch (narg->id) {
708         case COUNTER_NETWORK_BYTESRECSEC:
709                 sample->rawValue = mono_network_get_data (narg->name, MONO_NETWORK_BYTESREC, &error);
710                 break;
711         case COUNTER_NETWORK_BYTESSENTSEC:
712                 sample->rawValue = mono_network_get_data (narg->name, MONO_NETWORK_BYTESSENT, &error);
713                 break;
714         case COUNTER_NETWORK_BYTESTOTALSEC:
715                 sample->rawValue = mono_network_get_data (narg->name, MONO_NETWORK_BYTESTOTAL, &error);
716                 break;
717         }
718
719         if (error == MONO_NETWORK_ERROR_NONE)
720                 return TRUE;
721         else
722                 return FALSE;
723 }
724
725 static void
726 network_cleanup (ImplVtable *vtable)
727 {
728         NetworkVtableArg *narg;
729
730         if (vtable == NULL)
731                 return;
732
733         narg = vtable->arg;
734         if (narg == NULL)
735                 return;
736
737         g_free (narg->name);
738         narg->name = NULL;
739         g_free (narg);
740         vtable->arg = NULL;
741 }
742
743 static void*
744 network_get_impl (MonoString* counter, MonoString* instance, int *type, MonoBoolean *custom)
745 {
746         const CounterDesc *cdesc;
747         NetworkVtableArg *narg;
748         ImplVtable *vtable;
749         char *instance_name;
750
751         *custom = FALSE;
752         if ((cdesc = get_counter_in_category (&predef_categories [CATEGORY_NETWORK], counter))) {
753                 instance_name = mono_string_to_utf8 (instance);
754                 narg = g_new0 (NetworkVtableArg, 1);
755                 narg->id = cdesc->id;
756                 narg->name = instance_name;
757                 *type = cdesc->type;
758                 vtable = create_vtable (narg, get_network_counter, NULL);
759                 vtable->cleanup = network_cleanup;
760                 return vtable;
761         }
762         return NULL;
763 }
764
765 static MonoBoolean
766 get_process_counter (ImplVtable *vtable, MonoBoolean only_value, MonoCounterSample *sample)
767 {
768         int id = GPOINTER_TO_INT (vtable->arg);
769         int pid = id >> 5;
770         if (pid < 0)
771                 return FALSE;
772         id &= 0x1f;
773         if (!only_value) {
774                 fill_sample (sample);
775                 sample->baseValue = 1;
776         }
777         sample->counterType = predef_counters [predef_categories [CATEGORY_PROC].first_counter + id].type;
778         switch (id) {
779         case COUNTER_PROC_USER_TIME:
780                 sample->rawValue = mono_process_get_data (GINT_TO_POINTER (pid), MONO_PROCESS_USER_TIME);
781                 return TRUE;
782         case COUNTER_PROC_PRIV_TIME:
783                 sample->rawValue = mono_process_get_data (GINT_TO_POINTER (pid), MONO_PROCESS_SYSTEM_TIME);
784                 return TRUE;
785         case COUNTER_PROC_PROC_TIME:
786                 sample->rawValue = mono_process_get_data (GINT_TO_POINTER (pid), MONO_PROCESS_TOTAL_TIME);
787                 return TRUE;
788         case COUNTER_PROC_THREADS:
789                 sample->rawValue = mono_process_get_data (GINT_TO_POINTER (pid), MONO_PROCESS_NUM_THREADS);
790                 return TRUE;
791         case COUNTER_PROC_VBYTES:
792                 sample->rawValue = mono_process_get_data (GINT_TO_POINTER (pid), MONO_PROCESS_VIRTUAL_BYTES);
793                 return TRUE;
794         case COUNTER_PROC_WSET:
795                 sample->rawValue = mono_process_get_data (GINT_TO_POINTER (pid), MONO_PROCESS_WORKING_SET);
796                 return TRUE;
797         case COUNTER_PROC_PBYTES:
798                 sample->rawValue = mono_process_get_data (GINT_TO_POINTER (pid), MONO_PROCESS_PRIVATE_BYTES);
799                 return TRUE;
800         }
801         return FALSE;
802 }
803
804 static void*
805 process_get_impl (MonoString* counter, MonoString* instance, int *type, MonoBoolean *custom)
806 {
807         int id = id_from_string (instance, TRUE) << 5;
808         const CounterDesc *cdesc;
809         *custom = FALSE;
810         /* increase the shift above and the mask also in the implementation functions */
811         //g_assert (32 > desc [1].first_counter - desc->first_counter);
812         if ((cdesc = get_counter_in_category (&predef_categories [CATEGORY_PROC], counter))) {
813                 *type = cdesc->type;
814                 return create_vtable (GINT_TO_POINTER (id | cdesc->id), get_process_counter, NULL);
815         }
816         return NULL;
817 }
818
819 static MonoBoolean
820 mono_mem_counter (ImplVtable *vtable, MonoBoolean only_value, MonoCounterSample *sample)
821 {
822         int id = GPOINTER_TO_INT (vtable->arg);
823         if (!only_value) {
824                 fill_sample (sample);
825                 sample->baseValue = 1;
826         }
827         sample->counterType = predef_counters [predef_categories [CATEGORY_MONO_MEM].first_counter + id].type;
828         switch (id) {
829         case COUNTER_MEM_NUM_OBJECTS:
830                 sample->rawValue = mono_stats.new_object_count;
831                 return TRUE;
832         }
833         return FALSE;
834 }
835
836 static void*
837 mono_mem_get_impl (MonoString* counter, MonoString* instance, int *type, MonoBoolean *custom)
838 {
839         const CounterDesc *cdesc;
840         *custom = FALSE;
841         if ((cdesc = get_counter_in_category (&predef_categories [CATEGORY_MONO_MEM], counter))) {
842                 *type = cdesc->type;
843                 return create_vtable (GINT_TO_POINTER ((gint) cdesc->id), mono_mem_counter, NULL);
844         }
845         return NULL;
846 }
847
848 static MonoBoolean
849 predef_readonly_counter (ImplVtable *vtable, MonoBoolean only_value, MonoCounterSample *sample)
850 {
851         PredefVtable *vt = (PredefVtable *)vtable;
852         const CounterDesc *desc;
853         int cat_id = GPOINTER_TO_INT (vtable->arg);
854         int id = cat_id >> 16;
855         cat_id &= 0xffff;
856         if (!only_value) {
857                 fill_sample (sample);
858                 sample->baseValue = 1;
859         }
860         desc = &predef_counters [predef_categories [cat_id].first_counter + id];
861         sample->counterType = desc->type;
862         /* FIXME: check that the offset fits inside imported counters */
863         /*g_print ("loading %s at %d\n", desc->name, desc->offset);*/
864         sample->rawValue = *(guint32*)((char*)vt->counters + desc->offset);
865         return TRUE;
866 }
867
868 static ImplVtable*
869 predef_vtable (void *arg, MonoString *instance)
870 {
871         MonoSharedArea *area;
872         PredefVtable *vtable;
873         char *pids = mono_string_to_utf8 (instance);
874         int pid;
875
876         pid = atoi (pids);
877         g_free (pids);
878         area = load_sarea_for_pid (pid);
879         if (!area)
880                 return NULL;
881
882         vtable = g_new (PredefVtable, 1);
883         vtable->vtable.arg = arg;
884         vtable->vtable.sample = predef_readonly_counter;
885         vtable->vtable.cleanup = predef_cleanup;
886         vtable->counters = (MonoPerfCounters*)((char*)area + area->counters_start);
887         vtable->pid = pid;
888
889         return (ImplVtable*)vtable;
890 }
891
892 /* consider storing the pointer directly in vtable->arg, so the runtime overhead is lower:
893  * this needs some way to set sample->counterType as well, though.
894  */
895 static MonoBoolean
896 predef_writable_counter (ImplVtable *vtable, MonoBoolean only_value, MonoCounterSample *sample)
897 {
898         int cat_id = GPOINTER_TO_INT (vtable->arg);
899         int id = cat_id >> 16;
900         cat_id &= 0xffff;
901         if (!only_value) {
902                 fill_sample (sample);
903                 sample->baseValue = 1;
904         }
905         sample->counterType = predef_counters [predef_categories [cat_id].first_counter + id].type;
906         switch (cat_id) {
907         case CATEGORY_EXC:
908                 switch (id) {
909                 case COUNTER_EXC_THROWN:
910                         sample->rawValue = mono_perfcounters->exceptions_thrown;
911                         return TRUE;
912                 }
913                 break;
914         case CATEGORY_ASPNET:
915                 switch (id) {
916                 case COUNTER_ASPNET_REQ_Q:
917                         sample->rawValue = mono_perfcounters->aspnet_requests_queued;
918                         return TRUE;
919                 case COUNTER_ASPNET_REQ_TOTAL:
920                         sample->rawValue = mono_perfcounters->aspnet_requests;
921                         return TRUE;
922                 }
923                 break;
924         case CATEGORY_THREADPOOL:
925                 switch (id) {
926                 case COUNTER_THREADPOOL_WORKITEMS:
927                         sample->rawValue = mono_perfcounters->threadpool_workitems;
928                         return TRUE;
929                 case COUNTER_THREADPOOL_IOWORKITEMS:
930                         sample->rawValue = mono_perfcounters->threadpool_ioworkitems;
931                         return TRUE;
932                 }
933                 break;
934         }
935         return FALSE;
936 }
937
938 static gint64
939 predef_writable_update (ImplVtable *vtable, MonoBoolean do_incr, gint64 value)
940 {
941         guint32 *volatile ptr = NULL;
942         gint64 *volatile ptr64 = NULL;
943         int cat_id = GPOINTER_TO_INT (vtable->arg);
944         int id = cat_id >> 16;
945         cat_id &= 0xffff;
946         switch (cat_id) {
947         case CATEGORY_ASPNET:
948                 switch (id) {
949                 case COUNTER_ASPNET_REQ_Q: ptr = &mono_perfcounters->aspnet_requests_queued; break;
950                 case COUNTER_ASPNET_REQ_TOTAL: ptr = &mono_perfcounters->aspnet_requests; break;
951                 }
952                 break;
953         case CATEGORY_THREADPOOL:
954                 switch (id) {
955                 case COUNTER_THREADPOOL_WORKITEMS: ptr64 = (gint64 *) &mono_perfcounters->threadpool_workitems; break;
956                 case COUNTER_THREADPOOL_IOWORKITEMS: ptr64 = (gint64 *) &mono_perfcounters->threadpool_ioworkitems; break;
957                 }
958                 break;
959         }
960         if (ptr) {
961                 if (do_incr) {
962                         if (value == 1)
963                                 return InterlockedIncrement ((gint32 *) ptr); /* FIXME: sign */
964                         if (value == -1)
965                                 return InterlockedDecrement ((gint32 *) ptr); /* FIXME: sign */
966
967                         *ptr += value;
968                         return *ptr;
969                 }
970                 /* this can be non-atomic */
971                 *ptr = value;
972                 return value;
973         } else if (ptr64) {
974                 if (do_incr) {
975                         /* FIXME: we need to do this atomically */
976                         /* No InterlockedIncrement64() yet */
977                         /*
978                         if (value == 1)
979                                 return InterlockedIncrement64 (ptr);
980                         if (value == -1)
981                                 return InterlockedDecrement64 (ptr);
982                         */
983
984                         *ptr64 += value;
985                         return *ptr64;
986                 }
987                 /* this can be non-atomic */
988                 *ptr64 = value;
989                 return value;
990         }
991         return 0;
992 }
993
994 static void*
995 predef_writable_get_impl (int cat, MonoString* counter, MonoString* instance, int *type, MonoBoolean *custom)
996 {
997         const CounterDesc *cdesc;
998         *custom = TRUE;
999         if ((cdesc = get_counter_in_category (&predef_categories [cat], counter))) {
1000                 *type = cdesc->type;
1001                 if (instance == NULL || mono_string_compare_ascii (instance, "") == 0)
1002                         return create_vtable (GINT_TO_POINTER ((cdesc->id << 16) | cat), predef_writable_counter, predef_writable_update);
1003                 else
1004                         return predef_vtable (GINT_TO_POINTER ((cdesc->id << 16) | cat), instance);
1005         }
1006         return NULL;
1007 }
1008
1009 static MonoBoolean
1010 custom_writable_counter (ImplVtable *vtable, MonoBoolean only_value, MonoCounterSample *sample)
1011 {
1012         CustomVTable *counter_data = (CustomVTable *)vtable;
1013         if (!only_value) {
1014                 fill_sample (sample);
1015                 sample->baseValue = 1;
1016         }
1017         sample->counterType = simple_type_to_type [counter_data->counter_desc->type];
1018         if (!vtable->arg)
1019                 sample->rawValue = 0;
1020         else
1021                 sample->rawValue = *(guint64*)vtable->arg;
1022         return TRUE;
1023 }
1024
1025 static gint64
1026 custom_writable_update (ImplVtable *vtable, MonoBoolean do_incr, gint64 value)
1027 {
1028         /* FIXME: check writability */
1029         guint64 *ptr = vtable->arg;
1030         if (ptr) {
1031                 if (do_incr) {
1032                         /* FIXME: we need to do this atomically */
1033                         *ptr += value;
1034                         return *ptr;
1035                 }
1036                 /* this can be non-atomic */
1037                 *ptr = value;
1038                 return value;
1039         }
1040         return 0;
1041 }
1042
1043 static SharedInstance*
1044 custom_get_instance (SharedCategory *cat, SharedCounter *scounter, MonoString* instance)
1045 {
1046         SharedInstance* inst;
1047         unsigned char *ptr;
1048         char *p;
1049         int size, data_offset;
1050         char *name;
1051         inst = find_custom_instance (cat, instance);
1052         if (inst)
1053                 return inst;
1054         name = mono_string_to_utf8 (instance);
1055         size = sizeof (SharedInstance) + strlen (name);
1056         size += 7;
1057         size &= ~7;
1058         data_offset = size;
1059         size += (sizeof (guint64) * cat->num_counters);
1060         perfctr_lock ();
1061         ptr = shared_data_find_room (size);
1062         if (!ptr) {
1063                 perfctr_unlock ();
1064                 g_free (name);
1065                 return NULL;
1066         }
1067         inst = (SharedInstance*)ptr;
1068         inst->header.extra = 0; /* data_offset could overflow here, so we leave this field unused */
1069         inst->header.size = size;
1070         inst->category_offset = (char*)cat - (char*)shared_area;
1071         cat->num_instances++;
1072         /* now copy the variable data */
1073         p = inst->instance_name;
1074         strcpy (p, name);
1075         p += strlen (name) + 1;
1076         inst->header.ftype = FTYPE_INSTANCE;
1077         perfctr_unlock ();
1078         g_free (name);
1079
1080         return inst;
1081 }
1082
1083 static ImplVtable*
1084 custom_vtable (SharedCounter *scounter, SharedInstance* inst, char *data)
1085 {
1086         CustomVTable* vtable;
1087         vtable = g_new0 (CustomVTable, 1);
1088         vtable->vtable.arg = data;
1089         vtable->vtable.sample = custom_writable_counter;
1090         vtable->vtable.update = custom_writable_update;
1091         vtable->instance_desc = inst;
1092         vtable->counter_desc = scounter;
1093
1094         return (ImplVtable*)vtable;
1095 }
1096
1097 static void*
1098 custom_get_impl (SharedCategory *cat, MonoString* counter, MonoString* instance, int *type)
1099 {
1100         SharedCounter *scounter;
1101         SharedInstance* inst;
1102         int size;
1103
1104         scounter = find_custom_counter (cat, counter);
1105         if (!scounter)
1106                 return NULL;
1107         *type = simple_type_to_type [scounter->type];
1108         inst = custom_get_instance (cat, scounter, instance);
1109         if (!inst)
1110                 return NULL;
1111         size = sizeof (SharedInstance) + strlen (inst->instance_name);
1112         size += 7;
1113         size &= ~7;
1114         return custom_vtable (scounter, inst, (char*)inst + size + scounter->seq_num * sizeof (guint64));
1115 }
1116
1117 static const CategoryDesc*
1118 find_category (MonoString *category)
1119 {
1120         int i;
1121         for (i = 0; i < NUM_CATEGORIES; ++i) {
1122                 if (mono_string_compare_ascii (category, predef_categories [i].name) == 0)
1123                         return &predef_categories [i];
1124         }
1125         return NULL;
1126 }
1127
1128 void*
1129 mono_perfcounter_get_impl (MonoString* category, MonoString* counter, MonoString* instance,
1130                 MonoString* machine, int *type, MonoBoolean *custom)
1131 {
1132         const CategoryDesc *cdesc;
1133         /* no support for counters on other machines */
1134         if (mono_string_compare_ascii (machine, "."))
1135                 return NULL;
1136         cdesc = find_category (category);
1137         if (!cdesc) {
1138                 SharedCategory *scat = find_custom_category (category);
1139                 if (!scat)
1140                         return NULL;
1141                 *custom = TRUE;
1142                 return custom_get_impl (scat, counter, instance, type);
1143         }
1144         switch (cdesc->id) {
1145         case CATEGORY_CPU:
1146                 return cpu_get_impl (counter, instance, type, custom);
1147         case CATEGORY_PROC:
1148                 return process_get_impl (counter, instance, type, custom);
1149         case CATEGORY_MONO_MEM:
1150                 return mono_mem_get_impl (counter, instance, type, custom);
1151         case CATEGORY_NETWORK:
1152                 return network_get_impl (counter, instance, type, custom);
1153         case CATEGORY_JIT:
1154         case CATEGORY_EXC:
1155         case CATEGORY_GC:
1156         case CATEGORY_REMOTING:
1157         case CATEGORY_LOADING:
1158         case CATEGORY_THREAD:
1159         case CATEGORY_INTEROP:
1160         case CATEGORY_SECURITY:
1161         case CATEGORY_ASPNET:
1162         case CATEGORY_THREADPOOL:
1163                 return predef_writable_get_impl (cdesc->id, counter, instance, type, custom);
1164         }
1165         return NULL;
1166 }
1167
1168 MonoBoolean
1169 mono_perfcounter_get_sample (void *impl, MonoBoolean only_value, MonoCounterSample *sample)
1170 {
1171         ImplVtable *vtable = impl;
1172         if (vtable && vtable->sample)
1173                 return vtable->sample (vtable, only_value, sample);
1174         return FALSE;
1175 }
1176
1177 gint64
1178 mono_perfcounter_update_value (void *impl, MonoBoolean do_incr, gint64 value)
1179 {
1180         ImplVtable *vtable = impl;
1181         if (vtable && vtable->update)
1182                 return vtable->update (vtable, do_incr, value);
1183         return 0;
1184 }
1185
1186 void
1187 mono_perfcounter_free_data (void *impl)
1188 {
1189         ImplVtable *vtable = impl;
1190         if (vtable && vtable->cleanup)
1191                 vtable->cleanup (vtable);
1192         g_free (impl);
1193 }
1194
1195 /* Category icalls */
1196 MonoBoolean
1197 mono_perfcounter_category_del (MonoString *name)
1198 {
1199         const CategoryDesc *cdesc;
1200         SharedCategory *cat;
1201         cdesc = find_category (name);
1202         /* can't delete a predefined category */
1203         if (cdesc)
1204                 return FALSE;
1205         perfctr_lock ();
1206         cat = find_custom_category (name);
1207         /* FIXME: check the semantics, if deleting a category means also deleting the instances */
1208         if (!cat || cat->num_instances) {
1209                 perfctr_unlock ();
1210                 return FALSE;
1211         }
1212         cat->header.ftype = FTYPE_DELETED;
1213         perfctr_unlock ();
1214         return TRUE;
1215 }
1216
1217 MonoString*
1218 mono_perfcounter_category_help (MonoString *category, MonoString *machine)
1219 {
1220         const CategoryDesc *cdesc;
1221         /* no support for counters on other machines */
1222         if (mono_string_compare_ascii (machine, "."))
1223                 return NULL;
1224         cdesc = find_category (category);
1225         if (!cdesc) {
1226                 SharedCategory *scat = find_custom_category (category);
1227                 if (!scat)
1228                         return NULL;
1229                 return mono_string_new (mono_domain_get (), custom_category_help (scat));
1230         }
1231         return mono_string_new (mono_domain_get (), cdesc->help);
1232 }
1233
1234 /*
1235  * Check if the category named @category exists on @machine. If @counter is not NULL, return
1236  * TRUE only if a counter with that name exists in the category.
1237  */
1238 MonoBoolean
1239 mono_perfcounter_category_exists (MonoString *counter, MonoString *category, MonoString *machine)
1240 {
1241         const CategoryDesc *cdesc;
1242         /* no support for counters on other machines */
1243         if (mono_string_compare_ascii (machine, "."))
1244                 return FALSE;
1245         cdesc = find_category (category);
1246         if (!cdesc) {
1247                 SharedCategory *scat = find_custom_category (category);
1248                 if (!scat)
1249                         return FALSE;
1250                 /* counter is allowed to be null */
1251                 if (!counter)
1252                         return TRUE;
1253                 /* search through the custom category */
1254                 return find_custom_counter (scat, counter) != NULL;
1255         }
1256         /* counter is allowed to be null */
1257         if (!counter)
1258                 return TRUE;
1259         if (get_counter_in_category (cdesc, counter))
1260                 return TRUE;
1261         return FALSE;
1262 }
1263
1264 /* C map of the type with the same name */
1265 typedef struct {
1266         MonoObject object;
1267         MonoString *help;
1268         MonoString *name;
1269         int type;
1270 } CounterCreationData;
1271
1272 /*
1273  * Since we'll keep a copy of the category per-process, we should also make sure
1274  * categories with the same name are compatible.
1275  */
1276 MonoBoolean
1277 mono_perfcounter_create (MonoString *category, MonoString *help, int type, MonoArray *items)
1278 {
1279         MonoError error;
1280         int result = FALSE;
1281         int i, size;
1282         int num_counters = mono_array_length (items);
1283         int counters_data_size;
1284         char *name = NULL;
1285         char *chelp = NULL;
1286         char **counter_info = NULL;
1287         unsigned char *ptr;
1288         char *p;
1289         SharedCategory *cat;
1290
1291         /* FIXME: ensure there isn't a category created already */
1292         mono_error_init (&error);
1293         name = mono_string_to_utf8_checked (category, &error);
1294         if (!mono_error_ok (&error))
1295                 goto failure;
1296         chelp = mono_string_to_utf8_checked (help, &error);
1297         if (!mono_error_ok (&error))
1298                 goto failure;
1299         counter_info = g_new0 (char*, num_counters * 2);
1300         /* calculate the size we need structure size + name/help + 2 0 string terminators */
1301         size = G_STRUCT_OFFSET (SharedCategory, name) + strlen (name) + strlen (chelp) + 2;
1302         for (i = 0; i < num_counters; ++i) {
1303                 CounterCreationData *data = mono_array_get (items, CounterCreationData*, i);
1304                 counter_info [i * 2] = mono_string_to_utf8_checked (data->name, &error);
1305                 if (!mono_error_ok (&error))
1306                         goto failure;
1307                 counter_info [i * 2 + 1] = mono_string_to_utf8_checked (data->help, &error);
1308                 if (!mono_error_ok (&error))
1309                         goto failure;
1310                 size += sizeof (SharedCounter) + 1; /* 1 is for the help 0 terminator */
1311         }
1312         for (i = 0; i < num_counters * 2; ++i) {
1313                 if (!counter_info [i])
1314                         goto failure;
1315                 size += strlen (counter_info [i]) + 1;
1316         }
1317         size += 7;
1318         size &= ~7;
1319         counters_data_size = num_counters * 8; /* optimize for size later */
1320         if (size > 65535)
1321                 goto failure;
1322         perfctr_lock ();
1323         ptr = shared_data_find_room (size);
1324         if (!ptr) {
1325                 perfctr_unlock ();
1326                 goto failure;
1327         }
1328         cat = (SharedCategory*)ptr;
1329         cat->header.extra = type;
1330         cat->header.size = size;
1331         cat->num_counters = num_counters;
1332         cat->counters_data_size = counters_data_size;
1333         /* now copy the vaiable data */
1334         p = cat->name;
1335         strcpy (p, name);
1336         p += strlen (name) + 1;
1337         strcpy (p, chelp);
1338         p += strlen (chelp) + 1;
1339         for (i = 0; i < num_counters; ++i) {
1340                 CounterCreationData *data = mono_array_get (items, CounterCreationData*, i);
1341                 /* emit the SharedCounter structures */
1342                 *p++ = perfctr_type_compress (data->type);
1343                 *p++ = i;
1344                 strcpy (p, counter_info [i * 2]);
1345                 p += strlen (counter_info [i * 2]) + 1;
1346                 strcpy (p, counter_info [i * 2 + 1]);
1347                 p += strlen (counter_info [i * 2 + 1]) + 1;
1348         }
1349         cat->header.ftype = FTYPE_CATEGORY;
1350
1351         perfctr_unlock ();
1352         result = TRUE;
1353 failure:
1354         if (counter_info) {
1355                 for (i = 0; i < num_counters * 2; ++i) {
1356                         g_free (counter_info [i]);
1357                 }
1358                 g_free (counter_info);
1359         }
1360         g_free (name);
1361         g_free (chelp);
1362         mono_error_cleanup (&error);
1363         return result;
1364 }
1365
1366 int
1367 mono_perfcounter_instance_exists (MonoString *instance, MonoString *category, MonoString *machine)
1368 {
1369         const CategoryDesc *cdesc;
1370         /* no support for counters on other machines */
1371         /*FIXME: machine appears to be wrong
1372         if (mono_string_compare_ascii (machine, "."))
1373                 return FALSE;*/
1374         cdesc = find_category (category);
1375         if (!cdesc) {
1376                 SharedCategory *scat;
1377                 scat = find_custom_category (category);
1378                 if (!scat)
1379                         return FALSE;
1380                 if (find_custom_instance (scat, instance))
1381                         return TRUE;
1382         } else {
1383                 /* FIXME: search instance */
1384         }
1385         return FALSE;
1386 }
1387
1388 MonoArray*
1389 mono_perfcounter_category_names (MonoString *machine)
1390 {
1391         int i;
1392         MonoArray *res;
1393         MonoDomain *domain = mono_domain_get ();
1394         GSList *custom_categories, *tmp;
1395         /* no support for counters on other machines */
1396         if (mono_string_compare_ascii (machine, "."))
1397                 return mono_array_new (domain, mono_get_string_class (), 0);
1398         perfctr_lock ();
1399         custom_categories = get_custom_categories ();
1400         res = mono_array_new (domain, mono_get_string_class (), NUM_CATEGORIES + g_slist_length (custom_categories));
1401         for (i = 0; i < NUM_CATEGORIES; ++i) {
1402                 const CategoryDesc *cdesc = &predef_categories [i];
1403                 mono_array_setref (res, i, mono_string_new (domain, cdesc->name));
1404         }
1405         for (tmp = custom_categories; tmp; tmp = tmp->next) {
1406                 SharedCategory *scat = tmp->data;
1407                 mono_array_setref (res, i, mono_string_new (domain, scat->name));
1408                 i++;
1409         }
1410         perfctr_unlock ();
1411         g_slist_free (custom_categories);
1412         return res;
1413 }
1414
1415 MonoArray*
1416 mono_perfcounter_counter_names (MonoString *category, MonoString *machine)
1417 {
1418         int i;
1419         SharedCategory *scat;
1420         const CategoryDesc *cdesc;
1421         MonoArray *res;
1422         MonoDomain *domain = mono_domain_get ();
1423         /* no support for counters on other machines */
1424         if (mono_string_compare_ascii (machine, "."))
1425                 return mono_array_new (domain, mono_get_string_class (), 0);
1426         cdesc = find_category (category);
1427         if (cdesc) {
1428                 res = mono_array_new (domain, mono_get_string_class (), cdesc [1].first_counter - cdesc->first_counter);
1429                 for (i = cdesc->first_counter; i < cdesc [1].first_counter; ++i) {
1430                         const CounterDesc *desc = &predef_counters [i];
1431                         mono_array_setref (res, i - cdesc->first_counter, mono_string_new (domain, desc->name));
1432                 }
1433                 return res;
1434         }
1435         perfctr_lock ();
1436         scat = find_custom_category (category);
1437         if (scat) {
1438                 char *p = custom_category_counters (scat);
1439                 int i;
1440                 res = mono_array_new (domain, mono_get_string_class (), scat->num_counters);
1441                 for (i = 0; i < scat->num_counters; ++i) {
1442                         mono_array_setref (res, i, mono_string_new (domain, p + 1));
1443                         p += 1 + strlen (p + 1) + 1; /* skip counter type and name */
1444                         p += strlen (p) + 1; /* skip counter help */
1445                 }
1446                 perfctr_unlock ();
1447                 return res;
1448         }
1449         perfctr_unlock ();
1450         return mono_array_new (domain, mono_get_string_class (), 0);
1451 }
1452
1453 static MonoArray*
1454 get_string_array (void **array, int count, gboolean is_process)
1455 {
1456         int i;
1457         MonoDomain *domain = mono_domain_get ();
1458         MonoArray * res = mono_array_new (mono_domain_get (), mono_get_string_class (), count);
1459         for (i = 0; i < count; ++i) {
1460                 char buf [128];
1461                 char *p;
1462                 if (is_process) {
1463                         char *pname = mono_process_get_name (array [i], buf, sizeof (buf));
1464                         p = g_strdup_printf ("%d/%s", GPOINTER_TO_INT (array [i]), pname);
1465                 } else {
1466                         sprintf (buf, "%d", GPOINTER_TO_INT (array [i]));
1467                         p = buf;
1468                 }
1469                 mono_array_setref (res, i, mono_string_new (domain, p));
1470                 if (p != buf)
1471                         g_free (p);
1472         }
1473         return res;
1474 }
1475
1476 static MonoArray*
1477 get_string_array_of_strings (void **array, int count)
1478 {
1479         int i;
1480         MonoDomain *domain = mono_domain_get ();
1481         MonoArray * res = mono_array_new (mono_domain_get (), mono_get_string_class (), count);
1482         for (i = 0; i < count; ++i) {
1483                 char* p = array[i];
1484                 mono_array_setref (res, i, mono_string_new (domain, p));
1485         }
1486
1487         return res;
1488 }
1489
1490 static MonoArray*
1491 get_mono_instances (void)
1492 {
1493         int count = 64;
1494         int res;
1495         void **buf = NULL;
1496         MonoArray *array;
1497         do {
1498                 count *= 2;
1499                 g_free (buf);
1500                 buf = g_new (void*, count);
1501                 res = mono_shared_area_instances (buf, count);
1502         } while (res == count);
1503         array = get_string_array (buf, res, TRUE);
1504         g_free (buf);
1505         return array;
1506 }
1507
1508 static MonoArray*
1509 get_cpu_instances (void)
1510 {
1511         void **buf = NULL;
1512         int i, count;
1513         MonoArray *array;
1514
1515         count = mono_cpu_count () + 1; /* +1 for "_Total" */
1516         buf = g_new (void*, count);
1517         for (i = 0; i < count; ++i)
1518                 buf [i] = GINT_TO_POINTER (i - 1); /* -1 => _Total */
1519         array = get_string_array (buf, count, FALSE);
1520         g_free (buf);
1521         mono_array_setref (array, 0, mono_string_new (mono_domain_get (), "_Total"));
1522         return array;
1523 }
1524
1525 static MonoArray*
1526 get_processes_instances (void)
1527 {
1528         MonoArray *array;
1529         int count = 0;
1530         void **buf = mono_process_list (&count);
1531         if (!buf)
1532                 return get_string_array (NULL, 0, FALSE);
1533         array = get_string_array (buf, count, TRUE);
1534         g_free (buf);
1535         return array;
1536 }
1537
1538 static MonoArray*
1539 get_networkinterface_instances (void)
1540 {
1541         MonoArray *array;
1542         int count = 0;
1543         void **buf = mono_networkinterface_list (&count);
1544         if (!buf)
1545                 return get_string_array_of_strings (NULL, 0);
1546         array = get_string_array_of_strings (buf, count);
1547         g_strfreev ((char **) buf);
1548         return array;
1549 }
1550
1551 static MonoArray*
1552 get_custom_instances (MonoString *category)
1553 {
1554         SharedCategory *scat;
1555         scat = find_custom_category (category);
1556         if (scat) {
1557                 GSList *list = get_custom_instances_list (scat);
1558                 GSList *tmp;
1559                 int i = 0;
1560                 MonoArray *array = mono_array_new (mono_domain_get (), mono_get_string_class (), g_slist_length (list));
1561                 for (tmp = list; tmp; tmp = tmp->next) {
1562                         SharedInstance *inst = tmp->data;
1563                         mono_array_setref (array, i, mono_string_new (mono_domain_get (), inst->instance_name));
1564                         i++;
1565                 }
1566                 g_slist_free (list);
1567                 return array;
1568         }
1569         return mono_array_new (mono_domain_get (), mono_get_string_class (), 0);
1570 }
1571
1572 MonoArray*
1573 mono_perfcounter_instance_names (MonoString *category, MonoString *machine)
1574 {
1575         const CategoryDesc* cat;
1576         if (mono_string_compare_ascii (machine, "."))
1577                 return mono_array_new (mono_domain_get (), mono_get_string_class (), 0);
1578         cat = find_category (category);
1579         if (!cat)
1580                 return get_custom_instances (category);
1581         switch (cat->instance_type) {
1582         case MonoInstance:
1583                 return get_mono_instances ();
1584         case CPUInstance:
1585                 return get_cpu_instances ();
1586         case ProcessInstance:
1587                 return get_processes_instances ();
1588         case NetworkInterfaceInstance:
1589                 return get_networkinterface_instances ();
1590         case ThreadInstance:
1591         default:
1592                 return mono_array_new (mono_domain_get (), mono_get_string_class (), 0);
1593         }
1594 }
1595