[mono-config] use right type for result of strlen
[mono.git] / mono / profiler / proflog.c
1 /*
2  * proflog.c: mono log profiler
3  *
4  * Authors:
5  *   Paolo Molaro (lupus@ximian.com)
6  *   Alex Rønne Petersen (alexrp@xamarin.com)
7  *
8  * Copyright 2010 Novell, Inc (http://www.novell.com)
9  * Copyright 2011 Xamarin Inc (http://www.xamarin.com)
10  */
11
12 #include <config.h>
13 #include "../mini/jit.h"
14 #include <mono/metadata/profiler.h>
15 #include <mono/metadata/threads.h>
16 #include <mono/metadata/mono-gc.h>
17 #include <mono/metadata/debug-helpers.h>
18 #include <mono/metadata/mono-perfcounters.h>
19 #include <mono/metadata/appdomain.h>
20 #include <mono/metadata/assembly.h>
21 #include <mono/metadata/tokentype.h>
22 #include <mono/metadata/tabledefs.h>
23 #include <mono/utils/atomic.h>
24 #include <mono/utils/mono-membar.h>
25 #include <mono/utils/mono-counters.h>
26 #include <mono/utils/mono-mutex.h>
27 #include <mono/utils/mono-conc-hashtable.h>
28 #include <mono/utils/lock-free-queue.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <assert.h>
32 #include <glib.h>
33 #ifdef HAVE_UNISTD_H
34 #include <unistd.h>
35 #endif
36 #include <fcntl.h>
37 #include <errno.h>
38 #if defined(HOST_WIN32) || defined(DISABLE_SOCKETS)
39 #define DISABLE_HELPER_THREAD 1
40 #endif
41
42 #ifndef _GNU_SOURCE
43 #define _GNU_SOURCE
44 #endif
45 #ifdef HAVE_DLFCN_H
46 #include <dlfcn.h>
47 #endif
48 #ifdef HAVE_EXECINFO_H
49 #include <execinfo.h>
50 #endif
51 #ifdef HAVE_LINK_H
52 #include <link.h>
53 #endif
54
55 #ifndef DISABLE_HELPER_THREAD
56 #include <sys/types.h>
57 #include <sys/socket.h>
58 #include <netinet/in.h>
59 #include <sys/select.h>
60 #endif
61
62 #ifdef HOST_WIN32
63 #include <windows.h>
64 #else
65 #include <pthread.h>
66 #endif
67
68 #ifdef HAVE_SYS_STAT_H
69 #include <sys/stat.h>
70 #endif
71
72 #include "utils.c"
73 #include "proflog.h"
74
75 #if defined (HAVE_SYS_ZLIB)
76 #include <zlib.h>
77 #endif
78
79 #if defined(__linux__)
80
81 #include <unistd.h>
82 #include <sys/syscall.h>
83 #include "perf_event.h"
84
85 #ifdef ENABLE_PERF_EVENTS
86 #define USE_PERF_EVENTS 1
87
88 static int read_perf_mmap (MonoProfiler* prof, int cpu);
89 #endif
90
91 #endif
92
93 #define BUFFER_SIZE (4096 * 16)
94 static int nocalls = 0;
95 static int notraces = 0;
96 static int use_zip = 0;
97 static int do_report = 0;
98 static int do_heap_shot = 0;
99 static int max_call_depth = 100;
100 static volatile int runtime_inited = 0;
101 static int need_helper_thread = 0;
102 static int command_port = 0;
103 static int heapshot_requested = 0;
104 static int sample_type = 0;
105 static int sample_freq = 0;
106 static int do_mono_sample = 0;
107 static int in_shutdown = 0;
108 static int do_debug = 0;
109 static int do_counters = 0;
110 static int do_coverage = 0;
111 static gboolean debug_coverage = FALSE;
112 static MonoProfileSamplingMode sampling_mode = MONO_PROFILER_STAT_MODE_PROCESS;
113
114 typedef struct _LogBuffer LogBuffer;
115
116 /*
117  * file format:
118  * [header] [buffer]*
119  *
120  * The file is composed by a header followed by 0 or more buffers.
121  * Each buffer contains events that happened on a thread: for a given thread
122  * buffers that appear later in the file are guaranteed to contain events
123  * that happened later in time. Buffers from separate threads could be interleaved,
124  * though.
125  * Buffers are not required to be aligned.
126  *
127  * header format:
128  * [id: 4 bytes] constant value: LOG_HEADER_ID
129  * [major: 1 byte] [minor: 1 byte] major and minor version of the log profiler
130  * [format: 1 byte] version of the data format for the rest of the file
131  * [ptrsize: 1 byte] size in bytes of a pointer in the profiled program
132  * [startup time: 8 bytes] time in milliseconds since the unix epoch when the program started
133  * [timer overhead: 4 bytes] approximate overhead in nanoseconds of the timer
134  * [flags: 4 bytes] file format flags, should be 0 for now
135  * [pid: 4 bytes] pid of the profiled process
136  * [port: 2 bytes] tcp port for server if != 0
137  * [sysid: 2 bytes] operating system and architecture identifier
138  *
139  * The multiple byte integers are in little-endian format.
140  *
141  * buffer format:
142  * [buffer header] [event]*
143  * Buffers have a fixed-size header followed by 0 or more bytes of event data.
144  * Timing information and other values in the event data are usually stored
145  * as uleb128 or sleb128 integers. To save space, as noted for each item below,
146  * some data is represented as a difference between the actual value and
147  * either the last value of the same type (like for timing information) or
148  * as the difference from a value stored in a buffer header.
149  *
150  * For timing information the data is stored as uleb128, since timing
151  * increases in a monotonic way in each thread: the value is the number of
152  * nanoseconds to add to the last seen timing data in a buffer. The first value
153  * in a buffer will be calculated from the time_base field in the buffer head.
154  *
155  * Object or heap sizes are stored as uleb128.
156  * Pointer differences are stored as sleb128, instead.
157  *
158  * If an unexpected value is found, the rest of the buffer should be ignored,
159  * as generally the later values need the former to be interpreted correctly.
160  *
161  * buffer header format:
162  * [bufid: 4 bytes] constant value: BUF_ID
163  * [len: 4 bytes] size of the data following the buffer header
164  * [time_base: 8 bytes] time base in nanoseconds since an unspecified epoch
165  * [ptr_base: 8 bytes] base value for pointers
166  * [obj_base: 8 bytes] base value for object addresses
167  * [thread id: 8 bytes] system-specific thread ID (pthread_t for example)
168  * [method_base: 8 bytes] base value for MonoMethod pointers
169  *
170  * event format:
171  * [extended info: upper 4 bits] [type: lower 4 bits] [data]*
172  * The data that follows depends on type and the extended info.
173  * Type is one of the enum values in proflog.h: TYPE_ALLOC, TYPE_GC,
174  * TYPE_METADATA, TYPE_METHOD, TYPE_EXCEPTION, TYPE_MONITOR, TYPE_HEAP.
175  * The extended info bits are interpreted based on type, see
176  * each individual event description below.
177  * strings are represented as a 0-terminated utf8 sequence.
178  *
179  * backtrace format:
180  * [flags: uleb128] must be 0
181  * [num: uleb128] number of frames following
182  * [frame: sleb128]* num MonoMethod pointers as differences from ptr_base
183  *
184  * type alloc format:
185  * type: TYPE_ALLOC
186  * exinfo: flags: TYPE_ALLOC_BT
187  * [time diff: uleb128] nanoseconds since last timing
188  * [ptr: sleb128] class as a byte difference from ptr_base
189  * [obj: sleb128] object address as a byte difference from obj_base
190  * [size: uleb128] size of the object in the heap
191  * If the TYPE_ALLOC_BT flag is set, a backtrace follows.
192  *
193  * type GC format:
194  * type: TYPE_GC
195  * exinfo: one of TYPE_GC_EVENT, TYPE_GC_RESIZE, TYPE_GC_MOVE, TYPE_GC_HANDLE_CREATED,
196  * TYPE_GC_HANDLE_DESTROYED
197  * [time diff: uleb128] nanoseconds since last timing
198  * if exinfo == TYPE_GC_RESIZE
199  *      [heap_size: uleb128] new heap size
200  * if exinfo == TYPE_GC_EVENT
201  *      [event type: uleb128] GC event (MONO_GC_EVENT_* from profiler.h)
202  *      [generation: uleb128] GC generation event refers to
203  * if exinfo == TYPE_GC_MOVE
204  *      [num_objects: uleb128] number of object moves that follow
205  *      [objaddr: sleb128]+ num_objects object pointer differences from obj_base
206  *      num is always an even number: the even items are the old
207  *      addresses, the odd numbers are the respective new object addresses
208  * if exinfo == TYPE_GC_HANDLE_CREATED
209  *      [handle_type: uleb128] GC handle type (System.Runtime.InteropServices.GCHandleType)
210  *      upper bits reserved as flags
211  *      [handle: uleb128] GC handle value
212  *      [objaddr: sleb128] object pointer differences from obj_base
213  * if exinfo == TYPE_GC_HANDLE_DESTROYED
214  *      [handle_type: uleb128] GC handle type (System.Runtime.InteropServices.GCHandleType)
215  *      upper bits reserved as flags
216  *      [handle: uleb128] GC handle value
217  *
218  * type metadata format:
219  * type: TYPE_METADATA
220  * exinfo: one of: TYPE_END_LOAD, TYPE_END_UNLOAD (optional for TYPE_THREAD and TYPE_DOMAIN)
221  * [time diff: uleb128] nanoseconds since last timing
222  * [mtype: byte] metadata type, one of: TYPE_CLASS, TYPE_IMAGE, TYPE_ASSEMBLY, TYPE_DOMAIN,
223  * TYPE_THREAD, TYPE_CONTEXT
224  * [pointer: sleb128] pointer of the metadata type depending on mtype
225  * if mtype == TYPE_CLASS
226  *      [image: sleb128] MonoImage* as a pointer difference from ptr_base
227  *  [flags: uleb128] must be 0
228  *      [name: string] full class name
229  * if mtype == TYPE_IMAGE
230  *  [flags: uleb128] must be 0
231  *      [name: string] image file name
232  * if mtype == TYPE_ASSEMBLY
233  *  [flags: uleb128] must be 0
234  *      [name: string] assembly name
235  * if mtype == TYPE_DOMAIN
236  *  [flags: uleb128] must be 0
237  * if mtype == TYPE_DOMAIN && exinfo == 0
238  *      [name: string] domain friendly name
239  * if mtype == TYPE_CONTEXT
240  *      [domain: sleb128] domain id as pointer
241  * if mtype == TYPE_THREAD && (format_version < 11 || (format_version > 10 && exinfo == 0))
242  *      [name: string] thread name
243  *
244  * type method format:
245  * type: TYPE_METHOD
246  * exinfo: one of: TYPE_LEAVE, TYPE_ENTER, TYPE_EXC_LEAVE, TYPE_JIT
247  * [time diff: uleb128] nanoseconds since last timing
248  * [method: sleb128] MonoMethod* as a pointer difference from the last such
249  * pointer or the buffer method_base
250  * if exinfo == TYPE_JIT
251  *      [code address: sleb128] pointer to the native code as a diff from ptr_base
252  *      [code size: uleb128] size of the generated code
253  *      [name: string] full method name
254  *
255  * type runtime format:
256  * type: TYPE_RUNTIME
257  * exinfo: one of: TYPE_JITHELPER
258  * [time diff: uleb128] nanoseconds since last timing
259  * if exinfo == TYPE_JITHELPER
260  *      [type: uleb128] MonoProfilerCodeBufferType enum value
261  *      [buffer address: sleb128] pointer to the native code as a diff from ptr_base
262  *      [buffer size: uleb128] size of the generated code
263  *      if type == MONO_PROFILER_CODE_BUFFER_SPECIFIC_TRAMPOLINE
264  *              [name: string] buffer description name
265  *
266  * type monitor format:
267  * type: TYPE_MONITOR
268  * exinfo: TYPE_MONITOR_BT flag and one of: MONO_PROFILER_MONITOR_(CONTENTION|FAIL|DONE)
269  * [time diff: uleb128] nanoseconds since last timing
270  * [object: sleb128] the lock object as a difference from obj_base
271  * if exinfo.low3bits == MONO_PROFILER_MONITOR_CONTENTION
272  *      If the TYPE_MONITOR_BT flag is set, a backtrace follows.
273  *
274  * type heap format
275  * type: TYPE_HEAP
276  * exinfo: one of TYPE_HEAP_START, TYPE_HEAP_END, TYPE_HEAP_OBJECT, TYPE_HEAP_ROOT
277  * if exinfo == TYPE_HEAP_START
278  *      [time diff: uleb128] nanoseconds since last timing
279  * if exinfo == TYPE_HEAP_END
280  *      [time diff: uleb128] nanoseconds since last timing
281  * if exinfo == TYPE_HEAP_OBJECT
282  *      [object: sleb128] the object as a difference from obj_base
283  *      [class: sleb128] the object MonoClass* as a difference from ptr_base
284  *      [size: uleb128] size of the object on the heap
285  *      [num_refs: uleb128] number of object references
286  *      if (format version > 1) each referenced objref is preceded by a
287  *      uleb128 encoded offset: the first offset is from the object address
288  *      and each next offset is relative to the previous one
289  *      [objrefs: sleb128]+ object referenced as a difference from obj_base
290  *      The same object can appear multiple times, but only the first time
291  *      with size != 0: in the other cases this data will only be used to
292  *      provide additional referenced objects.
293  * if exinfo == TYPE_HEAP_ROOT
294  *      [num_roots: uleb128] number of root references
295  *      [num_gc: uleb128] number of major gcs
296  *      [object: sleb128] the object as a difference from obj_base
297  *      [root_type: uleb128] the root_type: MonoProfileGCRootType (profiler.h)
298  *      [extra_info: uleb128] the extra_info value
299  *      object, root_type and extra_info are repeated num_roots times
300  *
301  * type sample format
302  * type: TYPE_SAMPLE
303  * exinfo: one of TYPE_SAMPLE_HIT, TYPE_SAMPLE_USYM, TYPE_SAMPLE_UBIN, TYPE_SAMPLE_COUNTERS_DESC, TYPE_SAMPLE_COUNTERS
304  * if exinfo == TYPE_SAMPLE_HIT
305  *      [sample_type: uleb128] type of sample (SAMPLE_*)
306  *      [timestamp: uleb128] nanoseconds since startup (note: different from other timestamps!)
307  *      if (format_version > 10)
308  *              [thread: sleb128] thread id as difference from ptr_base
309  *      [count: uleb128] number of following instruction addresses
310  *      [ip: sleb128]* instruction pointer as difference from ptr_base
311  *      if (format_version > 5)
312  *              [mbt_count: uleb128] number of managed backtrace info triplets (method + IL offset + native offset)
313  *              [method: sleb128]* MonoMethod* as a pointer difference from the last such
314  *              pointer or the buffer method_base (the first such method can be also indentified by ip, but this is not neccessarily true)
315  *              [il_offset: sleb128]* IL offset inside method where the hit occurred
316  *              [native_offset: sleb128]* native offset inside method where the hit occurred
317  * if exinfo == TYPE_SAMPLE_USYM
318  *      [address: sleb128] symbol address as a difference from ptr_base
319  *      [size: uleb128] symbol size (may be 0 if unknown)
320  *      [name: string] symbol name
321  * if exinfo == TYPE_SAMPLE_UBIN
322  *      [time diff: uleb128] nanoseconds since last timing
323  *      [address: sleb128] address where binary has been loaded
324  *      [offset: uleb128] file offset of mapping (the same file can be mapped multiple times)
325  *      [size: uleb128] memory size
326  *      [name: string] binary name
327  * if exinfo == TYPE_SAMPLE_COUNTERS_DESC
328  *      [len: uleb128] number of counters
329  *      for i = 0 to len
330  *              [section: uleb128] section of counter
331  *              if section == MONO_COUNTER_PERFCOUNTERS:
332  *                      [section_name: string] section name of counter
333  *              [name: string] name of counter
334  *              [type: uleb128] type of counter
335  *              [unit: uleb128] unit of counter
336  *              [variance: uleb128] variance of counter
337  *              [index: uleb128] unique index of counter
338  * if exinfo == TYPE_SAMPLE_COUNTERS
339  *      [timestamp: uleb128] sampling timestamp
340  *      while true:
341  *              [index: uleb128] unique index of counter
342  *              if index == 0:
343  *                      break
344  *              [type: uleb128] type of counter value
345  *              if type == string:
346  *                      if value == null:
347  *                              [0: uleb128] 0 -> value is null
348  *                      else:
349  *                              [1: uleb128] 1 -> value is not null
350  *                              [value: string] counter value
351  *              else:
352  *                      [value: uleb128/sleb128/double] counter value, can be sleb128, uleb128 or double (determined by using type)
353  *
354  * type coverage format
355  * type: TYPE_COVERAGE
356  * exinfo: one of TYPE_COVERAGE_METHOD, TYPE_COVERAGE_STATEMENT, TYPE_COVERAGE_ASSEMBLY, TYPE_COVERAGE_CLASS
357  * if exinfo == TYPE_COVERAGE_METHOD
358  *  [assembly: string] name of assembly
359  *  [class: string] name of the class
360  *  [name: string] name of the method
361  *  [signature: string] the signature of the method
362  *  [filename: string] the file path of the file that contains this method
363  *  [token: uleb128] the method token
364  *  [method_id: uleb128] an ID for this data to associate with the buffers of TYPE_COVERAGE_STATEMENTS
365  *  [len: uleb128] the number of TYPE_COVERAGE_BUFFERS associated with this method
366  * if exinfo == TYPE_COVERAGE_STATEMENTS
367  *  [method_id: uleb128] an the TYPE_COVERAGE_METHOD buffer to associate this with
368  *  [offset: uleb128] the il offset relative to the previous offset
369  *  [counter: uleb128] the counter for this instruction
370  *  [line: uleb128] the line of filename containing this instruction
371  *  [column: uleb128] the column containing this instruction
372  * if exinfo == TYPE_COVERAGE_ASSEMBLY
373  *  [name: string] assembly name
374  *  [guid: string] assembly GUID
375  *  [filename: string] assembly filename
376  *  [number_of_methods: uleb128] the number of methods in this assembly
377  *  [fully_covered: uleb128] the number of fully covered methods
378  *  [partially_covered: uleb128] the number of partially covered methods
379  *    currently partially_covered will always be 0, and fully_covered is the
380  *    number of methods that are fully and partially covered.
381  * if exinfo == TYPE_COVERAGE_CLASS
382  *  [name: string] assembly name
383  *  [class: string] class name
384  *  [number_of_methods: uleb128] the number of methods in this class
385  *  [fully_covered: uleb128] the number of fully covered methods
386  *  [partially_covered: uleb128] the number of partially covered methods
387  *    currently partially_covered will always be 0, and fully_covered is the
388  *    number of methods that are fully and partially covered.
389  */
390
391 /*
392  * Format oddities that we ought to fix:
393  *
394  * - Methods written in emit_bt () should be based on the buffer's base
395  *   method instead of the base pointer.
396  * - The TYPE_SAMPLE_HIT event contains (currently) pointless data like
397  *   always-one unmanaged frame count and always-zero IL offsets.
398  *
399  * These are mostly small things and are not worth a format change by
400  * themselves. They should be done when some other major change has to
401  * be done to the format.
402  */
403
404 struct _LogBuffer {
405         LogBuffer *next;
406         uint64_t time_base;
407         uint64_t last_time;
408         uintptr_t ptr_base;
409         uintptr_t method_base;
410         uintptr_t last_method;
411         uintptr_t obj_base;
412         uintptr_t thread_id;
413         unsigned char* data_end;
414         unsigned char* data;
415         int locked;
416         int size;
417         int call_depth;
418         unsigned char buf [1];
419 };
420
421 static inline void
422 ign_res (int G_GNUC_UNUSED unused, ...)
423 {
424 }
425
426 #define ENTER_LOG(lb,str) if ((lb)->locked) {ign_res (write(2, str, strlen(str))); ign_res (write(2, "\n", 1));return;} else {(lb)->locked++;}
427 #define EXIT_LOG(lb) (lb)->locked--;
428
429 typedef struct _StatBuffer StatBuffer;
430 struct _StatBuffer {
431         StatBuffer *next;
432         uintptr_t size;
433         uintptr_t *data_end;
434         uintptr_t *data;
435         uintptr_t buf [1];
436 };
437
438 typedef struct _BinaryObject BinaryObject;
439
440 struct _BinaryObject {
441         BinaryObject *next;
442         void *addr;
443         char *name;
444 };
445
446 struct _MonoProfiler {
447         StatBuffer *stat_buffers;
448         FILE* file;
449 #if defined (HAVE_SYS_ZLIB)
450         gzFile gzfile;
451 #endif
452         uint64_t startup_time;
453         int pipe_output;
454         int last_gc_gen_started;
455         int command_port;
456         int server_socket;
457         int pipes [2];
458 #ifndef HOST_WIN32
459         pthread_t helper_thread;
460         pthread_t writer_thread;
461 #endif
462         volatile gint32 run_writer_thread;
463         MonoLockFreeQueue writer_queue;
464         MonoConcurrentHashTable *method_table;
465         mono_mutex_t method_table_mutex;
466         BinaryObject *binary_objects;
467         GPtrArray *coverage_filters;
468         GPtrArray *sorted_sample_events;
469 };
470
471 typedef struct _WriterQueueEntry WriterQueueEntry;
472 struct _WriterQueueEntry {
473         MonoLockFreeQueueNode node;
474         GPtrArray *methods;
475         LogBuffer *buffer;
476 };
477
478 typedef struct _MethodInfo MethodInfo;
479 struct _MethodInfo {
480         MonoMethod *method;
481         MonoJitInfo *ji;
482 };
483
484 #ifdef TLS_INIT
485 #undef TLS_INIT
486 #endif
487
488 #ifdef HOST_WIN32
489 #define TLS_SET(x,y) (TlsSetValue (x, y))
490 #define TLS_GET(t,x) ((t *) TlsGetValue (x))
491 #define TLS_INIT(x) (x = TlsAlloc ())
492 static int tlsbuffer;
493 static int tlsmethodlist;
494 #elif HAVE_KW_THREAD
495 #define TLS_SET(x,y) (x = y)
496 #define TLS_GET(t,x) (x)
497 #define TLS_INIT(x)
498 static __thread LogBuffer* tlsbuffer = NULL;
499 static __thread GPtrArray* tlsmethodlist = NULL;
500 #else
501 #define TLS_SET(x,y) (pthread_setspecific (x, y))
502 #define TLS_GET(t,x) ((t *) pthread_getspecific (x))
503 #define TLS_INIT(x) (pthread_key_create (&x, NULL))
504 static pthread_key_t tlsbuffer;
505 static pthread_key_t tlsmethodlist;
506 #endif
507
508 static void safe_send (MonoProfiler *profiler, LogBuffer *logbuffer);
509
510 static char*
511 pstrdup (const char *s)
512 {
513         int len = strlen (s) + 1;
514         char *p = malloc (len);
515         memcpy (p, s, len);
516         return p;
517 }
518
519 static StatBuffer*
520 create_stat_buffer (void)
521 {
522         StatBuffer* buf = alloc_buffer (BUFFER_SIZE);
523         buf->size = BUFFER_SIZE;
524         buf->data_end = (uintptr_t*)((unsigned char*)buf + buf->size);
525         buf->data = buf->buf;
526         return buf;
527 }
528
529 static LogBuffer*
530 create_buffer (void)
531 {
532         LogBuffer* buf = alloc_buffer (BUFFER_SIZE);
533         buf->size = BUFFER_SIZE;
534         buf->time_base = current_time ();
535         buf->last_time = buf->time_base;
536         buf->data_end = (unsigned char*)buf + buf->size;
537         buf->data = buf->buf;
538         return buf;
539 }
540
541 static void
542 init_thread (void)
543 {
544         if (!TLS_GET (LogBuffer, tlsbuffer)) {
545                 LogBuffer *logbuffer = create_buffer ();
546                 TLS_SET (tlsbuffer, logbuffer);
547                 logbuffer->thread_id = thread_id ();
548         }
549         if (!TLS_GET (GPtrArray, tlsmethodlist)) {
550                 GPtrArray *methodlist = g_ptr_array_new ();
551                 TLS_SET (tlsmethodlist, methodlist);
552         }
553
554         //printf ("thread %p at time %llu\n", (void*)logbuffer->thread_id, logbuffer->time_base);
555 }
556
557 static LogBuffer *
558 ensure_logbuf_inner (LogBuffer *old, int bytes)
559 {
560         if (old && old->data + bytes + 100 < old->data_end)
561                 return old;
562
563         LogBuffer *new = create_buffer ();
564         new->thread_id = thread_id ();
565         new->next = old;
566
567         if (old)
568                 new->call_depth = old->call_depth;
569
570         return new;
571 }
572
573 static LogBuffer*
574 ensure_logbuf (int bytes)
575 {
576         LogBuffer *old = TLS_GET (LogBuffer, tlsbuffer);
577         LogBuffer *new = ensure_logbuf_inner (old, bytes);
578
579         if (new == old)
580                 return old; // Still enough space.
581
582         TLS_SET (tlsbuffer, new);
583         init_thread ();
584
585         return new;
586 }
587
588 static void
589 emit_byte (LogBuffer *logbuffer, int value)
590 {
591         logbuffer->data [0] = value;
592         logbuffer->data++;
593         assert (logbuffer->data <= logbuffer->data_end);
594 }
595
596 static void
597 emit_value (LogBuffer *logbuffer, int value)
598 {
599         encode_uleb128 (value, logbuffer->data, &logbuffer->data);
600         assert (logbuffer->data <= logbuffer->data_end);
601 }
602
603 static void
604 emit_time (LogBuffer *logbuffer, uint64_t value)
605 {
606         uint64_t tdiff = value - logbuffer->last_time;
607         if (value < logbuffer->last_time)
608                 printf ("time went backwards\n");
609         //if (tdiff > 1000000)
610         //      printf ("large time offset: %llu\n", tdiff);
611         encode_uleb128 (tdiff, logbuffer->data, &logbuffer->data);
612         /*if (tdiff != decode_uleb128 (p, &p))
613                 printf ("incorrect encoding: %llu\n", tdiff);*/
614         logbuffer->last_time = value;
615         assert (logbuffer->data <= logbuffer->data_end);
616 }
617
618 static void
619 emit_svalue (LogBuffer *logbuffer, int64_t value)
620 {
621         encode_sleb128 (value, logbuffer->data, &logbuffer->data);
622         assert (logbuffer->data <= logbuffer->data_end);
623 }
624
625 static void
626 emit_uvalue (LogBuffer *logbuffer, uint64_t value)
627 {
628         encode_uleb128 (value, logbuffer->data, &logbuffer->data);
629         assert (logbuffer->data <= logbuffer->data_end);
630 }
631
632 static void
633 emit_ptr (LogBuffer *logbuffer, void *ptr)
634 {
635         if (!logbuffer->ptr_base)
636                 logbuffer->ptr_base = (uintptr_t)ptr;
637         emit_svalue (logbuffer, (intptr_t)ptr - logbuffer->ptr_base);
638         assert (logbuffer->data <= logbuffer->data_end);
639 }
640
641 static void
642 emit_method_inner (LogBuffer *logbuffer, void *method)
643 {
644         if (!logbuffer->method_base) {
645                 logbuffer->method_base = (intptr_t)method;
646                 logbuffer->last_method = (intptr_t)method;
647         }
648         encode_sleb128 ((intptr_t)((char*)method - (char*)logbuffer->last_method), logbuffer->data, &logbuffer->data);
649         logbuffer->last_method = (intptr_t)method;
650         assert (logbuffer->data <= logbuffer->data_end);
651 }
652
653 typedef struct {
654         MonoMethod *method;
655         MonoJitInfo *found;
656 } MethodSearch;
657
658 static void
659 find_method (MonoDomain *domain, void *user_data)
660 {
661         MethodSearch *search = user_data;
662
663         if (search->found)
664                 return;
665
666         MonoJitInfo *ji = mono_get_jit_info_from_method (domain, search->method);
667
668         // It could be AOT'd, so we need to get it from the AOT runtime's cache.
669         if (!ji) {
670                 void *ip = mono_aot_get_method (domain, search->method);
671
672                 // Avoid a slow path in mono_jit_info_table_find ().
673                 if (ip)
674                         ji = mono_jit_info_table_find (domain, ip);
675         }
676
677         if (ji)
678                 search->found = ji;
679 }
680
681 static void
682 register_method_local (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *ji)
683 {
684         if (!mono_conc_hashtable_lookup (prof->method_table, method)) {
685                 if (!ji) {
686                         MethodSearch search = { method, NULL };
687
688                         mono_domain_foreach (find_method, &search);
689
690                         ji = search.found;
691                 }
692
693                 g_assert (ji);
694
695                 MethodInfo *info = malloc (sizeof (MethodInfo));
696
697                 info->method = method;
698                 info->ji = ji;
699
700                 g_ptr_array_add (TLS_GET (GPtrArray, tlsmethodlist), info);
701         }
702 }
703
704 static void
705 emit_method (MonoProfiler *prof, LogBuffer *logbuffer, MonoMethod *method)
706 {
707         register_method_local (prof, method, NULL);
708         emit_method_inner (logbuffer, method);
709 }
710
711 static void
712 emit_method_as_ptr (MonoProfiler *prof, LogBuffer *logbuffer, MonoMethod *method)
713 {
714         register_method_local (prof, method, NULL);
715         emit_ptr (logbuffer, method);
716 }
717
718 static void
719 emit_obj (LogBuffer *logbuffer, void *ptr)
720 {
721         if (!logbuffer->obj_base)
722                 logbuffer->obj_base = (uintptr_t)ptr >> 3;
723         emit_svalue (logbuffer, ((uintptr_t)ptr >> 3) - logbuffer->obj_base);
724         assert (logbuffer->data <= logbuffer->data_end);
725 }
726
727 static void
728 emit_string (LogBuffer *logbuffer, const char *str, size_t size)
729 {
730         size_t i = 0;
731         if (str) {
732                 for (; i < size; i++) {
733                         if (str[i] == '\0')
734                                 break;
735                         emit_byte (logbuffer, str [i]);
736                 }
737         }
738         emit_byte (logbuffer, '\0');
739 }
740
741 static void
742 emit_double (LogBuffer *logbuffer, double value)
743 {
744         int i;
745         unsigned char buffer[8];
746         memcpy (buffer, &value, 8);
747 #if G_BYTE_ORDER == G_BIG_ENDIAN
748         for (i = 7; i >= 0; i--)
749 #else
750         for (i = 0; i < 8; i++)
751 #endif
752                 emit_byte (logbuffer, buffer[i]);
753 }
754
755 static char*
756 write_int16 (char *buf, int32_t value)
757 {
758         int i;
759         for (i = 0; i < 2; ++i) {
760                 buf [i] = value;
761                 value >>= 8;
762         }
763         return buf + 2;
764 }
765
766 static char*
767 write_int32 (char *buf, int32_t value)
768 {
769         int i;
770         for (i = 0; i < 4; ++i) {
771                 buf [i] = value;
772                 value >>= 8;
773         }
774         return buf + 4;
775 }
776
777 static char*
778 write_int64 (char *buf, int64_t value)
779 {
780         int i;
781         for (i = 0; i < 8; ++i) {
782                 buf [i] = value;
783                 value >>= 8;
784         }
785         return buf + 8;
786 }
787
788 static void
789 dump_header (MonoProfiler *profiler)
790 {
791         char hbuf [128];
792         char *p = hbuf;
793         p = write_int32 (p, LOG_HEADER_ID);
794         *p++ = LOG_VERSION_MAJOR;
795         *p++ = LOG_VERSION_MINOR;
796         *p++ = LOG_DATA_VERSION;
797         *p++ = sizeof (void*);
798         p = write_int64 (p, ((uint64_t)time (NULL)) * 1000); /* startup time */
799         p = write_int32 (p, get_timer_overhead ()); /* timer overhead */
800         p = write_int32 (p, 0); /* flags */
801         p = write_int32 (p, process_id ()); /* pid */
802         p = write_int16 (p, profiler->command_port); /* port */
803         p = write_int16 (p, 0); /* opsystem */
804 #if defined (HAVE_SYS_ZLIB)
805         if (profiler->gzfile) {
806                 gzwrite (profiler->gzfile, hbuf, p - hbuf);
807         } else {
808                 fwrite (hbuf, p - hbuf, 1, profiler->file);
809         }
810 #else
811         fwrite (hbuf, p - hbuf, 1, profiler->file);
812         fflush (profiler->file);
813 #endif
814 }
815
816 static void
817 send_buffer (MonoProfiler *prof, GPtrArray *methods, LogBuffer *buffer)
818 {
819         WriterQueueEntry *entry = calloc (1, sizeof (WriterQueueEntry));
820         mono_lock_free_queue_node_init (&entry->node, FALSE);
821         entry->methods = methods;
822         entry->buffer = buffer;
823         mono_lock_free_queue_enqueue (&prof->writer_queue, &entry->node);
824 }
825
826 static void
827 dump_buffer (MonoProfiler *profiler, LogBuffer *buf)
828 {
829         char hbuf [128];
830         char *p = hbuf;
831         if (buf->next)
832                 dump_buffer (profiler, buf->next);
833         p = write_int32 (p, BUF_ID);
834         p = write_int32 (p, buf->data - buf->buf);
835         p = write_int64 (p, buf->time_base);
836         p = write_int64 (p, buf->ptr_base);
837         p = write_int64 (p, buf->obj_base);
838         p = write_int64 (p, buf->thread_id);
839         p = write_int64 (p, buf->method_base);
840 #if defined (HAVE_SYS_ZLIB)
841         if (profiler->gzfile) {
842                 gzwrite (profiler->gzfile, hbuf, p - hbuf);
843                 gzwrite (profiler->gzfile, buf->buf, buf->data - buf->buf);
844         } else {
845 #endif
846                 fwrite (hbuf, p - hbuf, 1, profiler->file);
847                 fwrite (buf->buf, buf->data - buf->buf, 1, profiler->file);
848                 fflush (profiler->file);
849 #if defined (HAVE_SYS_ZLIB)
850         }
851 #endif
852         free_buffer (buf, buf->size);
853 }
854
855 static void
856 process_requests (MonoProfiler *profiler)
857 {
858         if (heapshot_requested)
859                 mono_gc_collect (mono_gc_max_generation ());
860 }
861
862 static void counters_init (MonoProfiler *profiler);
863 static void counters_sample (MonoProfiler *profiler, uint64_t timestamp);
864
865 /*
866  * Can be called only at safe callback locations.
867  */
868 static void
869 safe_send (MonoProfiler *profiler, LogBuffer *logbuffer)
870 {
871         /* We need the runtime initialized so that we have threads and hazard
872          * pointers available. Otherwise, the lock free queue will not work and
873          * there won't be a thread to process the data.
874          *
875          * While the runtime isn't initialized, we just accumulate data in the
876          * thread local buffer list.
877          */
878         if (!InterlockedRead (&runtime_inited))
879                 return;
880
881         int cd = logbuffer->call_depth;
882
883         send_buffer (profiler, TLS_GET (GPtrArray, tlsmethodlist), TLS_GET (LogBuffer, tlsbuffer));
884
885         TLS_SET (tlsbuffer, NULL);
886         TLS_SET (tlsmethodlist, NULL);
887
888         init_thread ();
889
890         TLS_GET (LogBuffer, tlsbuffer)->call_depth = cd;
891 }
892
893 static int
894 gc_reference (MonoObject *obj, MonoClass *klass, uintptr_t size, uintptr_t num, MonoObject **refs, uintptr_t *offsets, void *data)
895 {
896         int i;
897         uintptr_t last_offset = 0;
898         //const char *name = mono_class_get_name (klass);
899         LogBuffer *logbuffer = ensure_logbuf (1 + 10 + 10 + 10 + 10 + num * (10 + 10));
900         emit_byte (logbuffer, TYPE_HEAP_OBJECT | TYPE_HEAP);
901         emit_obj (logbuffer, obj);
902         emit_ptr (logbuffer, klass);
903         /* account for object alignment in the heap */
904         size += 7;
905         size &= ~7;
906         emit_value (logbuffer, size);
907         emit_value (logbuffer, num);
908         for (i = 0; i < num; ++i) {
909                 emit_value (logbuffer, offsets [i] - last_offset);
910                 last_offset = offsets [i];
911                 emit_obj (logbuffer, refs [i]);
912         }
913         //if (num)
914         //      printf ("obj: %p, klass: %s, refs: %d, size: %d\n", obj, name, (int)num, (int)size);
915         return 0;
916 }
917
918 static unsigned int hs_mode_ms = 0;
919 static unsigned int hs_mode_gc = 0;
920 static unsigned int hs_mode_ondemand = 0;
921 static unsigned int gc_count = 0;
922 static uint64_t last_hs_time = 0;
923
924 static void
925 heap_walk (MonoProfiler *profiler)
926 {
927         int do_walk = 0;
928         uint64_t now;
929         LogBuffer *logbuffer;
930         if (!do_heap_shot)
931                 return;
932         logbuffer = ensure_logbuf (1 + 10);
933         now = current_time ();
934         if (hs_mode_ms && (now - last_hs_time)/1000000 >= hs_mode_ms)
935                 do_walk = 1;
936         else if (hs_mode_gc && (gc_count % hs_mode_gc) == 0)
937                 do_walk = 1;
938         else if (hs_mode_ondemand)
939                 do_walk = heapshot_requested;
940         else if (!hs_mode_ms && !hs_mode_gc && profiler->last_gc_gen_started == mono_gc_max_generation ())
941                 do_walk = 1;
942
943         if (!do_walk)
944                 return;
945         heapshot_requested = 0;
946         emit_byte (logbuffer, TYPE_HEAP_START | TYPE_HEAP);
947         emit_time (logbuffer, now);
948         mono_gc_walk_heap (0, gc_reference, NULL);
949         logbuffer = ensure_logbuf (1 + 10);
950         now = current_time ();
951         emit_byte (logbuffer, TYPE_HEAP_END | TYPE_HEAP);
952         emit_time (logbuffer, now);
953         last_hs_time = now;
954 }
955
956 static void
957 gc_event (MonoProfiler *profiler, MonoGCEvent ev, int generation) {
958         uint64_t now;
959         LogBuffer *logbuffer = ensure_logbuf (1 + 10 + 10 + 10);
960         now = current_time ();
961         ENTER_LOG (logbuffer, "gcevent");
962         emit_byte (logbuffer, TYPE_GC_EVENT | TYPE_GC);
963         emit_time (logbuffer, now);
964         emit_value (logbuffer, ev);
965         emit_value (logbuffer, generation);
966         /* to deal with nested gen1 after gen0 started */
967         if (ev == MONO_GC_EVENT_START) {
968                 profiler->last_gc_gen_started = generation;
969                 if (generation == mono_gc_max_generation ())
970                         gc_count++;
971         }
972         if (ev == MONO_GC_EVENT_PRE_START_WORLD)
973                 heap_walk (profiler);
974         EXIT_LOG (logbuffer);
975         if (ev == MONO_GC_EVENT_POST_START_WORLD)
976                 safe_send (profiler, logbuffer);
977         //printf ("gc event %d for generation %d\n", ev, generation);
978 }
979
980 static void
981 gc_resize (MonoProfiler *profiler, int64_t new_size) {
982         uint64_t now;
983         LogBuffer *logbuffer = ensure_logbuf (1 + 10 + 10);
984         now = current_time ();
985         ENTER_LOG (logbuffer, "gcresize");
986         emit_byte (logbuffer, TYPE_GC_RESIZE | TYPE_GC);
987         emit_time (logbuffer, now);
988         emit_value (logbuffer, new_size);
989         //printf ("gc resized to %lld\n", new_size);
990         EXIT_LOG (logbuffer);
991 }
992
993 #define MAX_FRAMES 32
994 typedef struct {
995         int count;
996         MonoMethod* methods [MAX_FRAMES];
997         int32_t il_offsets [MAX_FRAMES];
998         int32_t native_offsets [MAX_FRAMES];
999 } FrameData;
1000 static int num_frames = MAX_FRAMES;
1001
1002 static mono_bool
1003 walk_stack (MonoMethod *method, int32_t native_offset, int32_t il_offset, mono_bool managed, void* data)
1004 {
1005         FrameData *frame = data;
1006         if (method && frame->count < num_frames) {
1007                 frame->il_offsets [frame->count] = il_offset;
1008                 frame->native_offsets [frame->count] = native_offset;
1009                 frame->methods [frame->count++] = method;
1010                 //printf ("In %d %s at %d (native: %d)\n", frame->count, mono_method_get_name (method), il_offset, native_offset);
1011         }
1012         return frame->count == num_frames;
1013 }
1014
1015 /*
1016  * a note about stack walks: they can cause more profiler events to fire,
1017  * so we need to make sure they don't happen after we started emitting an
1018  * event, hence the collect_bt/emit_bt split.
1019  */
1020 static void
1021 collect_bt (FrameData *data)
1022 {
1023         data->count = 0;
1024         mono_stack_walk_no_il (walk_stack, data);
1025 }
1026
1027 static void
1028 emit_bt (MonoProfiler *prof, LogBuffer *logbuffer, FrameData *data)
1029 {
1030         /* FIXME: this is actually tons of data and we should
1031          * just output it the first time and use an id the next
1032          */
1033         if (data->count > num_frames)
1034                 printf ("bad num frames: %d\n", data->count);
1035         emit_value (logbuffer, 0); /* flags */
1036         emit_value (logbuffer, data->count);
1037         //if (*p != data.count) {
1038         //      printf ("bad num frames enc at %d: %d -> %d\n", count, data.count, *p); printf ("frames end: %p->%p\n", p, logbuffer->data); exit(0);}
1039         while (data->count) {
1040                 emit_method_as_ptr (prof, logbuffer, data->methods [--data->count]);
1041         }
1042 }
1043
1044 static void
1045 gc_alloc (MonoProfiler *prof, MonoObject *obj, MonoClass *klass)
1046 {
1047         uint64_t now;
1048         uintptr_t len;
1049         int do_bt = (nocalls && InterlockedRead (&runtime_inited) && !notraces)? TYPE_ALLOC_BT: 0;
1050         FrameData data;
1051         LogBuffer *logbuffer;
1052         len = mono_object_get_size (obj);
1053         /* account for object alignment in the heap */
1054         len += 7;
1055         len &= ~7;
1056         if (do_bt)
1057                 collect_bt (&data);
1058         logbuffer = ensure_logbuf (1 + 10 + 10 + 10 + 10 + MAX_FRAMES * (10 + 10 + 10));
1059         now = current_time ();
1060         ENTER_LOG (logbuffer, "gcalloc");
1061         emit_byte (logbuffer, do_bt | TYPE_ALLOC);
1062         emit_time (logbuffer, now);
1063         emit_ptr (logbuffer, klass);
1064         emit_obj (logbuffer, obj);
1065         emit_value (logbuffer, len);
1066         if (do_bt)
1067                 emit_bt (prof, logbuffer, &data);
1068         EXIT_LOG (logbuffer);
1069         if (logbuffer->next)
1070                 safe_send (prof, logbuffer);
1071         process_requests (prof);
1072         //printf ("gc alloc %s at %p\n", mono_class_get_name (klass), obj);
1073 }
1074
1075 static void
1076 gc_moves (MonoProfiler *prof, void **objects, int num)
1077 {
1078         int i;
1079         uint64_t now;
1080         LogBuffer *logbuffer = ensure_logbuf (1 + 10 + 10 + num * 10);
1081         now = current_time ();
1082         ENTER_LOG (logbuffer, "gcmove");
1083         emit_byte (logbuffer, TYPE_GC_MOVE | TYPE_GC);
1084         emit_time (logbuffer, now);
1085         emit_value (logbuffer, num);
1086         for (i = 0; i < num; ++i)
1087                 emit_obj (logbuffer, objects [i]);
1088         //printf ("gc moved %d objects\n", num/2);
1089         EXIT_LOG (logbuffer);
1090 }
1091
1092 static void
1093 gc_roots (MonoProfiler *prof, int num, void **objects, int *root_types, uintptr_t *extra_info)
1094 {
1095         int i;
1096         LogBuffer *logbuffer = ensure_logbuf (1 + 10 + 10 + num * (10 + 10 + 10));
1097         ENTER_LOG (logbuffer, "gcroots");
1098         emit_byte (logbuffer, TYPE_HEAP_ROOT | TYPE_HEAP);
1099         emit_value (logbuffer, num);
1100         emit_value (logbuffer, mono_gc_collection_count (mono_gc_max_generation ()));
1101         for (i = 0; i < num; ++i) {
1102                 emit_obj (logbuffer, objects [i]);
1103                 emit_value (logbuffer, root_types [i]);
1104                 emit_value (logbuffer, extra_info [i]);
1105         }
1106         EXIT_LOG (logbuffer);
1107 }
1108
1109 static void
1110 gc_handle (MonoProfiler *prof, int op, int type, uintptr_t handle, MonoObject *obj)
1111 {
1112         uint64_t now;
1113         LogBuffer *logbuffer = ensure_logbuf (1 + 10 + 10 + 10 + 10);
1114         now = current_time ();
1115         ENTER_LOG (logbuffer, "gchandle");
1116         if (op == MONO_PROFILER_GC_HANDLE_CREATED)
1117                 emit_byte (logbuffer, TYPE_GC_HANDLE_CREATED | TYPE_GC);
1118         else if (op == MONO_PROFILER_GC_HANDLE_DESTROYED)
1119                 emit_byte (logbuffer, TYPE_GC_HANDLE_DESTROYED | TYPE_GC);
1120         else
1121                 return;
1122         emit_time (logbuffer, now);
1123         emit_value (logbuffer, type);
1124         emit_value (logbuffer, handle);
1125         if (op == MONO_PROFILER_GC_HANDLE_CREATED)
1126                 emit_obj (logbuffer, obj);
1127         EXIT_LOG (logbuffer);
1128         process_requests (prof);
1129 }
1130
1131 static char*
1132 push_nesting (char *p, MonoClass *klass)
1133 {
1134         MonoClass *nesting;
1135         const char *name;
1136         const char *nspace;
1137         nesting = mono_class_get_nesting_type (klass);
1138         if (nesting) {
1139                 p = push_nesting (p, nesting);
1140                 *p++ = '/';
1141                 *p = 0;
1142         }
1143         name = mono_class_get_name (klass);
1144         nspace = mono_class_get_namespace (klass);
1145         if (*nspace) {
1146                 strcpy (p, nspace);
1147                 p += strlen (nspace);
1148                 *p++ = '.';
1149                 *p = 0;
1150         }
1151         strcpy (p, name);
1152         p += strlen (name);
1153         return p;
1154 }
1155
1156 static char*
1157 type_name (MonoClass *klass)
1158 {
1159         char buf [1024];
1160         char *p;
1161         push_nesting (buf, klass);
1162         p = malloc (strlen (buf) + 1);
1163         strcpy (p, buf);
1164         return p;
1165 }
1166
1167 static void
1168 image_loaded (MonoProfiler *prof, MonoImage *image, int result)
1169 {
1170         uint64_t now;
1171         const char *name;
1172         int nlen;
1173         LogBuffer *logbuffer;
1174         if (result != MONO_PROFILE_OK)
1175                 return;
1176         name = mono_image_get_filename (image);
1177         nlen = strlen (name) + 1;
1178         logbuffer = ensure_logbuf (1 + 10 + 1 + 10 + 10 + nlen);
1179         now = current_time ();
1180         ENTER_LOG (logbuffer, "image");
1181         emit_byte (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1182         emit_time (logbuffer, now);
1183         emit_byte (logbuffer, TYPE_IMAGE);
1184         emit_ptr (logbuffer, image);
1185         emit_value (logbuffer, 0); /* flags */
1186         memcpy (logbuffer->data, name, nlen);
1187         logbuffer->data += nlen;
1188         //printf ("loaded image %p (%s)\n", image, name);
1189         EXIT_LOG (logbuffer);
1190         if (logbuffer->next)
1191                 safe_send (prof, logbuffer);
1192         process_requests (prof);
1193 }
1194
1195 static void
1196 image_unloaded (MonoProfiler *prof, MonoImage *image)
1197 {
1198         const char *name = mono_image_get_filename (image);
1199         int nlen = strlen (name) + 1;
1200         LogBuffer *logbuffer = ensure_logbuf (1 + 10 + 1 + 10 + 10 + nlen);
1201         uint64_t now = current_time ();
1202
1203         ENTER_LOG (logbuffer, "image-unload");
1204         emit_byte (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
1205         emit_time (logbuffer, now);
1206         emit_byte (logbuffer, TYPE_IMAGE);
1207         emit_ptr (logbuffer, image);
1208         emit_value (logbuffer, 0); /* flags */
1209         memcpy (logbuffer->data, name, nlen);
1210         logbuffer->data += nlen;
1211         EXIT_LOG (logbuffer);
1212
1213         if (logbuffer->next)
1214                 safe_send (prof, logbuffer);
1215
1216         process_requests (prof);
1217 }
1218
1219 static void
1220 assembly_loaded (MonoProfiler *prof, MonoAssembly *assembly, int result)
1221 {
1222         if (result != MONO_PROFILE_OK)
1223                 return;
1224
1225         char *name = mono_stringify_assembly_name (mono_assembly_get_name (assembly));
1226         int nlen = strlen (name) + 1;
1227         LogBuffer *logbuffer = ensure_logbuf (1 + 10 + 1 + 10 + 10 + nlen);
1228         uint64_t now = current_time ();
1229
1230         ENTER_LOG (logbuffer, "assembly-load");
1231         emit_byte (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1232         emit_time (logbuffer, now);
1233         emit_byte (logbuffer, TYPE_ASSEMBLY);
1234         emit_ptr (logbuffer, assembly);
1235         emit_value (logbuffer, 0); /* flags */
1236         memcpy (logbuffer->data, name, nlen);
1237         logbuffer->data += nlen;
1238         EXIT_LOG (logbuffer);
1239
1240         mono_free (name);
1241
1242         if (logbuffer->next)
1243                 safe_send (prof, logbuffer);
1244
1245         process_requests (prof);
1246 }
1247
1248 static void
1249 assembly_unloaded (MonoProfiler *prof, MonoAssembly *assembly)
1250 {
1251         char *name = mono_stringify_assembly_name (mono_assembly_get_name (assembly));
1252         int nlen = strlen (name) + 1;
1253         LogBuffer *logbuffer = ensure_logbuf (1 + 10 + 1 + 10 + 10 + nlen);
1254         uint64_t now = current_time ();
1255
1256         ENTER_LOG (logbuffer, "assembly-unload");
1257         emit_byte (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
1258         emit_time (logbuffer, now);
1259         emit_byte (logbuffer, TYPE_ASSEMBLY);
1260         emit_ptr (logbuffer, assembly);
1261         emit_value (logbuffer, 0); /* flags */
1262         memcpy (logbuffer->data, name, nlen);
1263         logbuffer->data += nlen;
1264         EXIT_LOG (logbuffer);
1265
1266         mono_free (name);
1267
1268         if (logbuffer->next)
1269                 safe_send (prof, logbuffer);
1270
1271         process_requests (prof);
1272 }
1273
1274 static void
1275 class_loaded (MonoProfiler *prof, MonoClass *klass, int result)
1276 {
1277         uint64_t now;
1278         char *name;
1279         int nlen;
1280         MonoImage *image;
1281         LogBuffer *logbuffer;
1282         if (result != MONO_PROFILE_OK)
1283                 return;
1284         if (InterlockedRead (&runtime_inited))
1285                 name = mono_type_get_name (mono_class_get_type (klass));
1286         else
1287                 name = type_name (klass);
1288         nlen = strlen (name) + 1;
1289         image = mono_class_get_image (klass);
1290         logbuffer = ensure_logbuf (1 + 10 + 1 + 10 + 10 + 10 + nlen);
1291         now = current_time ();
1292         ENTER_LOG (logbuffer, "class");
1293         emit_byte (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1294         emit_time (logbuffer, now);
1295         emit_byte (logbuffer, TYPE_CLASS);
1296         emit_ptr (logbuffer, klass);
1297         emit_ptr (logbuffer, image);
1298         emit_value (logbuffer, 0); /* flags */
1299         memcpy (logbuffer->data, name, nlen);
1300         logbuffer->data += nlen;
1301         //printf ("loaded class %p (%s)\n", klass, name);
1302         if (runtime_inited)
1303                 mono_free (name);
1304         else
1305                 free (name);
1306         EXIT_LOG (logbuffer);
1307         if (logbuffer->next)
1308                 safe_send (prof, logbuffer);
1309         process_requests (prof);
1310 }
1311
1312 static void
1313 class_unloaded (MonoProfiler *prof, MonoClass *klass)
1314 {
1315         char *name;
1316
1317         if (InterlockedRead (&runtime_inited))
1318                 name = mono_type_get_name (mono_class_get_type (klass));
1319         else
1320                 name = type_name (klass);
1321
1322         int nlen = strlen (name) + 1;
1323         MonoImage *image = mono_class_get_image (klass);
1324         LogBuffer *logbuffer = ensure_logbuf (1 + 10 + 1 + 10 + 10 + 10 + nlen);
1325         uint64_t now = current_time ();
1326
1327         ENTER_LOG (logbuffer, "class-unload");
1328         emit_byte (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
1329         emit_time (logbuffer, now);
1330         emit_byte (logbuffer, TYPE_CLASS);
1331         emit_ptr (logbuffer, klass);
1332         emit_ptr (logbuffer, image);
1333         emit_value (logbuffer, 0); /* flags */
1334         memcpy (logbuffer->data, name, nlen);
1335         logbuffer->data += nlen;
1336         EXIT_LOG (logbuffer);
1337
1338         if (runtime_inited)
1339                 mono_free (name);
1340         else
1341                 free (name);
1342
1343         if (logbuffer->next)
1344                 safe_send (prof, logbuffer);
1345
1346         process_requests (prof);
1347 }
1348
1349 #ifndef DISABLE_HELPER_THREAD
1350 static void process_method_enter_coverage (MonoProfiler *prof, MonoMethod *method);
1351 #endif /* DISABLE_HELPER_THREAD */
1352
1353 static void
1354 method_enter (MonoProfiler *prof, MonoMethod *method)
1355 {
1356         uint64_t now = current_time ();
1357
1358 #ifndef DISABLE_HELPER_THREAD
1359         process_method_enter_coverage (prof, method);
1360 #endif /* DISABLE_HELPER_THREAD */
1361
1362         LogBuffer *logbuffer = ensure_logbuf (1 + 10 + 10);
1363         if (logbuffer->call_depth++ > max_call_depth)
1364                 return;
1365         ENTER_LOG (logbuffer, "enter");
1366         emit_byte (logbuffer, TYPE_ENTER | TYPE_METHOD);
1367         emit_time (logbuffer, now);
1368         emit_method (prof, logbuffer, method);
1369         EXIT_LOG (logbuffer);
1370
1371         process_requests (prof);
1372 }
1373
1374 static void
1375 method_leave (MonoProfiler *prof, MonoMethod *method)
1376 {
1377         uint64_t now;
1378         LogBuffer *logbuffer = ensure_logbuf (1 + 10 + 10);
1379         if (--logbuffer->call_depth > max_call_depth)
1380                 return;
1381         now = current_time ();
1382         ENTER_LOG (logbuffer, "leave");
1383         emit_byte (logbuffer, TYPE_LEAVE | TYPE_METHOD);
1384         emit_time (logbuffer, now);
1385         emit_method (prof, logbuffer, method);
1386         EXIT_LOG (logbuffer);
1387         if (logbuffer->next)
1388                 safe_send (prof, logbuffer);
1389         process_requests (prof);
1390 }
1391
1392 static void
1393 method_exc_leave (MonoProfiler *prof, MonoMethod *method)
1394 {
1395         uint64_t now;
1396         LogBuffer *logbuffer;
1397         if (nocalls)
1398                 return;
1399         logbuffer = ensure_logbuf (1 + 10 + 10);
1400         if (--logbuffer->call_depth > max_call_depth)
1401                 return;
1402         now = current_time ();
1403         ENTER_LOG (logbuffer, "eleave");
1404         emit_byte (logbuffer, TYPE_EXC_LEAVE | TYPE_METHOD);
1405         emit_time (logbuffer, now);
1406         emit_method (prof, logbuffer, method);
1407         EXIT_LOG (logbuffer);
1408         process_requests (prof);
1409 }
1410
1411 static void
1412 method_jitted (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *ji, int result)
1413 {
1414         if (result != MONO_PROFILE_OK)
1415                 return;
1416
1417         register_method_local (prof, method, ji);
1418
1419         process_requests (prof);
1420 }
1421
1422 static void
1423 code_buffer_new (MonoProfiler *prof, void *buffer, int size, MonoProfilerCodeBufferType type, void *data)
1424 {
1425         uint64_t now;
1426         int nlen;
1427         char *name;
1428         LogBuffer *logbuffer;
1429         if (type == MONO_PROFILER_CODE_BUFFER_SPECIFIC_TRAMPOLINE) {
1430                 name = data;
1431                 nlen = strlen (name) + 1;
1432         } else {
1433                 name = NULL;
1434                 nlen = 0;
1435         }
1436         logbuffer = ensure_logbuf (1 + 10 + 10 + 10 + 10 + nlen);
1437         now = current_time ();
1438         ENTER_LOG (logbuffer, "code buffer");
1439         emit_byte (logbuffer, TYPE_JITHELPER | TYPE_RUNTIME);
1440         emit_time (logbuffer, now);
1441         emit_value (logbuffer, type);
1442         emit_ptr (logbuffer, buffer);
1443         emit_value (logbuffer, size);
1444         if (name) {
1445                 memcpy (logbuffer->data, name, nlen);
1446                 logbuffer->data += nlen;
1447         }
1448         EXIT_LOG (logbuffer);
1449         process_requests (prof);
1450 }
1451
1452 static void
1453 throw_exc (MonoProfiler *prof, MonoObject *object)
1454 {
1455         int do_bt = (nocalls && InterlockedRead (&runtime_inited) && !notraces)? TYPE_EXCEPTION_BT: 0;
1456         uint64_t now;
1457         FrameData data;
1458         LogBuffer *logbuffer;
1459         if (do_bt)
1460                 collect_bt (&data);
1461         logbuffer = ensure_logbuf (1 + 10 + 10 + MAX_FRAMES * (10 + 10 + 10));
1462         now = current_time ();
1463         ENTER_LOG (logbuffer, "throw");
1464         emit_byte (logbuffer, do_bt | TYPE_EXCEPTION);
1465         emit_time (logbuffer, now);
1466         emit_obj (logbuffer, object);
1467         if (do_bt)
1468                 emit_bt (prof, logbuffer, &data);
1469         EXIT_LOG (logbuffer);
1470         process_requests (prof);
1471 }
1472
1473 static void
1474 clause_exc (MonoProfiler *prof, MonoMethod *method, int clause_type, int clause_num)
1475 {
1476         uint64_t now;
1477         LogBuffer *logbuffer = ensure_logbuf (1 + 10 + 10 + 10 + 10);
1478         now = current_time ();
1479         ENTER_LOG (logbuffer, "clause");
1480         emit_byte (logbuffer, TYPE_EXCEPTION | TYPE_CLAUSE);
1481         emit_time (logbuffer, now);
1482         emit_value (logbuffer, clause_type);
1483         emit_value (logbuffer, clause_num);
1484         emit_method (prof, logbuffer, method);
1485         EXIT_LOG (logbuffer);
1486
1487         process_requests (prof);
1488 }
1489
1490 static void
1491 monitor_event (MonoProfiler *profiler, MonoObject *object, MonoProfilerMonitorEvent event)
1492 {
1493         int do_bt = (nocalls && InterlockedRead (&runtime_inited) && !notraces && event == MONO_PROFILER_MONITOR_CONTENTION)? TYPE_MONITOR_BT: 0;
1494         uint64_t now;
1495         FrameData data;
1496         LogBuffer *logbuffer;
1497         if (do_bt)
1498                 collect_bt (&data);
1499         logbuffer = ensure_logbuf (1 + 10 + 10 + MAX_FRAMES * (10 + 10 + 10));
1500         now = current_time ();
1501         ENTER_LOG (logbuffer, "monitor");
1502         emit_byte (logbuffer, (event << 4) | do_bt | TYPE_MONITOR);
1503         emit_time (logbuffer, now);
1504         emit_obj (logbuffer, object);
1505         if (do_bt)
1506                 emit_bt (profiler, logbuffer, &data);
1507         EXIT_LOG (logbuffer);
1508         process_requests (profiler);
1509 }
1510
1511 static void
1512 thread_start (MonoProfiler *prof, uintptr_t tid)
1513 {
1514         //printf ("thread start %p\n", (void*)tid);
1515         init_thread ();
1516
1517         LogBuffer *logbuffer = ensure_logbuf (1 + 10 + 1 + 10 + 10);
1518         uint64_t now = current_time ();
1519
1520         ENTER_LOG (logbuffer, "thread-start");
1521         emit_byte (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1522         emit_time (logbuffer, now);
1523         emit_byte (logbuffer, TYPE_THREAD);
1524         emit_ptr (logbuffer, (void*) tid);
1525         emit_value (logbuffer, 0); /* flags */
1526         EXIT_LOG (logbuffer);
1527
1528         if (logbuffer->next)
1529                 safe_send (prof, logbuffer);
1530
1531         process_requests (prof);
1532 }
1533
1534 static void
1535 thread_end (MonoProfiler *prof, uintptr_t tid)
1536 {
1537         if (TLS_GET (LogBuffer, tlsbuffer)) {
1538                 LogBuffer *logbuffer = ensure_logbuf (1 + 10 + 1 + 10 + 10);
1539                 uint64_t now = current_time ();
1540
1541                 ENTER_LOG (logbuffer, "thread-end");
1542                 emit_byte (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
1543                 emit_time (logbuffer, now);
1544                 emit_byte (logbuffer, TYPE_THREAD);
1545                 emit_ptr (logbuffer, (void*) tid);
1546                 emit_value (logbuffer, 0); /* flags */
1547                 EXIT_LOG (logbuffer);
1548
1549                 send_buffer (prof, TLS_GET (GPtrArray, tlsmethodlist), logbuffer);
1550
1551                 /* Don't process requests as the thread is detached from the runtime. */
1552         }
1553
1554         TLS_SET (tlsbuffer, NULL);
1555         TLS_SET (tlsmethodlist, NULL);
1556 }
1557
1558 static void
1559 domain_loaded (MonoProfiler *prof, MonoDomain *domain, int result)
1560 {
1561         if (result != MONO_PROFILE_OK)
1562                 return;
1563
1564         LogBuffer *logbuffer = ensure_logbuf (1 + 10 + 1 + 10 + 10);
1565         uint64_t now = current_time ();
1566
1567         ENTER_LOG (logbuffer, "domain-start");
1568         emit_byte (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1569         emit_time (logbuffer, now);
1570         emit_byte (logbuffer, TYPE_DOMAIN);
1571         emit_ptr (logbuffer, (void*)(uintptr_t) mono_domain_get_id (domain));
1572         emit_value (logbuffer, 0); /* flags */
1573         EXIT_LOG (logbuffer);
1574
1575         if (logbuffer->next)
1576                 safe_send (prof, logbuffer);
1577
1578         process_requests (prof);
1579 }
1580
1581 static void
1582 domain_unloaded (MonoProfiler *prof, MonoDomain *domain)
1583 {
1584         LogBuffer *logbuffer = ensure_logbuf (1 + 10 + 1 + 10 + 10);
1585         uint64_t now = current_time ();
1586
1587         ENTER_LOG (logbuffer, "domain-end");
1588         emit_byte (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
1589         emit_time (logbuffer, now);
1590         emit_byte (logbuffer, TYPE_DOMAIN);
1591         emit_ptr (logbuffer, (void*)(uintptr_t) mono_domain_get_id (domain));
1592         emit_value (logbuffer, 0); /* flags */
1593         EXIT_LOG (logbuffer);
1594
1595         if (logbuffer->next)
1596                 safe_send (prof, logbuffer);
1597
1598         process_requests (prof);
1599 }
1600
1601 static void
1602 domain_name (MonoProfiler *prof, MonoDomain *domain, const char *name)
1603 {
1604         int nlen = strlen (name) + 1;
1605         LogBuffer *logbuffer = ensure_logbuf (1 + 10 + 1 + 10 + 10 + nlen);
1606         uint64_t now = current_time ();
1607
1608         ENTER_LOG (logbuffer, "domain-name");
1609         emit_byte (logbuffer, TYPE_METADATA);
1610         emit_time (logbuffer, now);
1611         emit_byte (logbuffer, TYPE_DOMAIN);
1612         emit_ptr (logbuffer, (void*)(uintptr_t) mono_domain_get_id (domain));
1613         emit_value (logbuffer, 0); /* flags */
1614         memcpy (logbuffer->data, name, nlen);
1615         logbuffer->data += nlen;
1616         EXIT_LOG (logbuffer);
1617
1618         if (logbuffer->next)
1619                 safe_send (prof, logbuffer);
1620
1621         process_requests (prof);
1622 }
1623
1624 static void
1625 context_loaded (MonoProfiler *prof, MonoAppContext *context)
1626 {
1627         LogBuffer *logbuffer = ensure_logbuf (1 + 10 + 1 + 10 + 10 + 10);
1628         uint64_t now = current_time ();
1629
1630         ENTER_LOG (logbuffer, "context-start");
1631         emit_byte (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1632         emit_time (logbuffer, now);
1633         emit_byte (logbuffer, TYPE_CONTEXT);
1634         emit_ptr (logbuffer, (void*)(uintptr_t) mono_context_get_id (context));
1635         emit_value (logbuffer, 0); /* flags */
1636         emit_ptr (logbuffer, (void*)(uintptr_t) mono_context_get_domain_id (context));
1637         EXIT_LOG (logbuffer);
1638
1639         if (logbuffer->next)
1640                 safe_send (prof, logbuffer);
1641
1642         process_requests (prof);
1643 }
1644
1645 static void
1646 context_unloaded (MonoProfiler *prof, MonoAppContext *context)
1647 {
1648         LogBuffer *logbuffer = ensure_logbuf (1 + 10 + 1 + 10 + 10 + 10);
1649         uint64_t now = current_time ();
1650
1651         ENTER_LOG (logbuffer, "context-end");
1652         emit_byte (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
1653         emit_time (logbuffer, now);
1654         emit_byte (logbuffer, TYPE_CONTEXT);
1655         emit_ptr (logbuffer, (void*)(uintptr_t) mono_context_get_id (context));
1656         emit_value (logbuffer, 0); /* flags */
1657         emit_ptr (logbuffer, (void*)(uintptr_t) mono_context_get_domain_id (context));
1658         EXIT_LOG (logbuffer);
1659
1660         if (logbuffer->next)
1661                 safe_send (prof, logbuffer);
1662
1663         process_requests (prof);
1664 }
1665
1666 static void
1667 thread_name (MonoProfiler *prof, uintptr_t tid, const char *name)
1668 {
1669         int len = strlen (name) + 1;
1670         uint64_t now;
1671         LogBuffer *logbuffer;
1672         logbuffer = ensure_logbuf (1 + 10 + 1 + 10 + 10 + len);
1673         now = current_time ();
1674         ENTER_LOG (logbuffer, "tname");
1675         emit_byte (logbuffer, TYPE_METADATA);
1676         emit_time (logbuffer, now);
1677         emit_byte (logbuffer, TYPE_THREAD);
1678         emit_ptr (logbuffer, (void*)tid);
1679         emit_value (logbuffer, 0); /* flags */
1680         memcpy (logbuffer->data, name, len);
1681         logbuffer->data += len;
1682         EXIT_LOG (logbuffer);
1683
1684         if (logbuffer->next)
1685                 safe_send (prof, logbuffer);
1686
1687         process_requests (prof);
1688 }
1689
1690 typedef struct {
1691         MonoMethod *method;
1692         MonoDomain *domain;
1693         void *base_address;
1694         int offset;
1695 } AsyncFrameInfo;
1696
1697 typedef struct {
1698         int count;
1699         AsyncFrameInfo *data;
1700 } AsyncFrameData;
1701
1702 static mono_bool
1703 async_walk_stack (MonoMethod *method, MonoDomain *domain, void *base_address, int offset, void *data)
1704 {
1705         AsyncFrameData *frame = data;
1706         if (frame->count < num_frames) {
1707                 frame->data [frame->count].method = method;
1708                 frame->data [frame->count].domain = domain;
1709                 frame->data [frame->count].base_address = base_address;
1710                 frame->data [frame->count].offset = offset;
1711                 // printf ("In %d at %p (dom %p) (native: %p)\n", frame->count, method, domain, base_address);
1712                 frame->count++;
1713         }
1714         return frame->count == num_frames;
1715 }
1716
1717 /*
1718 (type | frame count), tid, time, ip, [method, domain, base address, offset] * frames
1719 */
1720 #define SAMPLE_EVENT_SIZE_IN_SLOTS(FRAMES) (4 + (FRAMES) * 4)
1721
1722 static void
1723 mono_sample_hit (MonoProfiler *profiler, unsigned char *ip, void *context)
1724 {
1725         StatBuffer *sbuf;
1726         AsyncFrameInfo frames [num_frames];
1727         AsyncFrameData bt_data = { 0, &frames [0]};
1728         uint64_t now;
1729         uintptr_t *data, *new_data, *old_data;
1730         uintptr_t elapsed;
1731         int timedout = 0;
1732         int i;
1733         if (in_shutdown)
1734                 return;
1735         now = current_time ();
1736
1737         mono_stack_walk_async_safe (&async_walk_stack, context, &bt_data);
1738
1739         elapsed = (now - profiler->startup_time) / 10000;
1740         if (do_debug) {
1741                 int len;
1742                 char buf [256];
1743                 snprintf (buf, sizeof (buf), "hit at %p in thread %p after %llu ms\n", ip, (void*)thread_id (), (unsigned long long int)elapsed/100);
1744                 len = strlen (buf);
1745                 ign_res (write (2, buf, len));
1746         }
1747         sbuf = profiler->stat_buffers;
1748         if (!sbuf)
1749                 return;
1750         /* flush the buffer at 1 second intervals */
1751         if (sbuf->data > sbuf->buf && (elapsed - sbuf->buf [2]) > 100000) {
1752                 timedout = 1;
1753         }
1754         /* overflow: 400 slots is a big enough number to reduce the chance of losing this event if many
1755          * threads hit this same spot at the same time
1756          */
1757         if (timedout || (sbuf->data + 400 >= sbuf->data_end)) {
1758                 StatBuffer *oldsb, *foundsb;
1759                 sbuf = create_stat_buffer ();
1760                 do {
1761                         oldsb = profiler->stat_buffers;
1762                         sbuf->next = oldsb;
1763                         foundsb = InterlockedCompareExchangePointer ((void * volatile*)&profiler->stat_buffers, sbuf, oldsb);
1764                 } while (foundsb != oldsb);
1765                 if (do_debug)
1766                         ign_res (write (2, "overflow\n", 9));
1767                 /* notify the helper thread */
1768                 if (sbuf->next->next) {
1769                         char c = 0;
1770                         ign_res (write (profiler->pipes [1], &c, 1));
1771                         if (do_debug)
1772                                 ign_res (write (2, "notify\n", 7));
1773                 }
1774         }
1775         do {
1776                 old_data = sbuf->data;
1777                 new_data = old_data + SAMPLE_EVENT_SIZE_IN_SLOTS (bt_data.count);
1778                 data = InterlockedCompareExchangePointer ((void * volatile*)&sbuf->data, new_data, old_data);
1779         } while (data != old_data);
1780         if (old_data >= sbuf->data_end)
1781                 return; /* lost event */
1782         old_data [0] = 1 | (sample_type << 16) | (bt_data.count << 8);
1783         old_data [1] = thread_id ();
1784         old_data [2] = elapsed;
1785         old_data [3] = (uintptr_t)ip;
1786         for (i = 0; i < bt_data.count; ++i) {
1787                 old_data [4 + 4 * i + 0] = (uintptr_t)frames [i].method;
1788                 old_data [4 + 4 * i + 1] = (uintptr_t)frames [i].domain;
1789                 old_data [4 + 4 * i + 2] = (uintptr_t)frames [i].base_address;
1790                 old_data [4 + 4 * i + 3] = (uintptr_t)frames [i].offset;
1791         }
1792 }
1793
1794 static uintptr_t *code_pages = 0;
1795 static int num_code_pages = 0;
1796 static int size_code_pages = 0;
1797 #define CPAGE_SHIFT (9)
1798 #define CPAGE_SIZE (1 << CPAGE_SHIFT)
1799 #define CPAGE_MASK (~(CPAGE_SIZE - 1))
1800 #define CPAGE_ADDR(p) ((p) & CPAGE_MASK)
1801
1802 static uintptr_t
1803 add_code_page (uintptr_t *hash, uintptr_t hsize, uintptr_t page)
1804 {
1805         uintptr_t i;
1806         uintptr_t start_pos;
1807         start_pos = (page >> CPAGE_SHIFT) % hsize;
1808         i = start_pos;
1809         do {
1810                 if (hash [i] && CPAGE_ADDR (hash [i]) == CPAGE_ADDR (page)) {
1811                         return 0;
1812                 } else if (!hash [i]) {
1813                         hash [i] = page;
1814                         return 1;
1815                 }
1816                 /* wrap around */
1817                 if (++i == hsize)
1818                         i = 0;
1819         } while (i != start_pos);
1820         /* should not happen */
1821         printf ("failed code page store\n");
1822         return 0;
1823 }
1824
1825 static void
1826 add_code_pointer (uintptr_t ip)
1827 {
1828         uintptr_t i;
1829         if (num_code_pages * 2 >= size_code_pages) {
1830                 uintptr_t *n;
1831                 uintptr_t old_size = size_code_pages;
1832                 size_code_pages *= 2;
1833                 if (size_code_pages == 0)
1834                         size_code_pages = 16;
1835                 n = calloc (sizeof (uintptr_t) * size_code_pages, 1);
1836                 for (i = 0; i < old_size; ++i) {
1837                         if (code_pages [i])
1838                                 add_code_page (n, size_code_pages, code_pages [i]);
1839                 }
1840                 if (code_pages)
1841                         free (code_pages);
1842                 code_pages = n;
1843         }
1844         num_code_pages += add_code_page (code_pages, size_code_pages, ip & CPAGE_MASK);
1845 }
1846
1847 /* ELF code crashes on some systems. */
1848 //#if defined(HAVE_DL_ITERATE_PHDR) && defined(ELFMAG0)
1849 #if 0
1850 static void
1851 dump_ubin (const char *filename, uintptr_t load_addr, uint64_t offset, uintptr_t size)
1852 {
1853         uint64_t now;
1854         LogBuffer *logbuffer;
1855         int len;
1856         len = strlen (filename) + 1;
1857         now = current_time ();
1858         logbuffer = ensure_logbuf (1 + 10 + 10 + 10 + 10 + len);
1859         emit_byte (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_UBIN);
1860         emit_time (logbuffer, now);
1861         emit_svalue (logbuffer, load_addr);
1862         emit_uvalue (logbuffer, offset);
1863         emit_uvalue (logbuffer, size);
1864         memcpy (logbuffer->data, filename, len);
1865         logbuffer->data += len;
1866 }
1867 #endif
1868
1869 static void
1870 dump_usym (const char *name, uintptr_t value, uintptr_t size)
1871 {
1872         LogBuffer *logbuffer;
1873         int len;
1874         len = strlen (name) + 1;
1875         logbuffer = ensure_logbuf (1 + 10 + 10 + len);
1876         emit_byte (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_USYM);
1877         emit_ptr (logbuffer, (void*)value);
1878         emit_value (logbuffer, size);
1879         memcpy (logbuffer->data, name, len);
1880         logbuffer->data += len;
1881 }
1882
1883 /* ELF code crashes on some systems. */
1884 //#if defined(ELFMAG0)
1885 #if 0
1886
1887 #if SIZEOF_VOID_P == 4
1888 #define ELF_WSIZE 32
1889 #else
1890 #define ELF_WSIZE 64
1891 #endif
1892 #ifndef ElfW
1893 #define ElfW(type)      _ElfW (Elf, ELF_WSIZE, type)
1894 #define _ElfW(e,w,t)    _ElfW_1 (e, w, _##t)
1895 #define _ElfW_1(e,w,t)  e##w##t
1896 #endif
1897
1898 static void
1899 dump_elf_symbols (ElfW(Sym) *symbols, int num_symbols, const char *strtab, void *load_addr)
1900 {
1901         int i;
1902         for (i = 0; i < num_symbols; ++i) {
1903                 const char* sym;
1904                 sym =  strtab + symbols [i].st_name;
1905                 if (!symbols [i].st_name || !symbols [i].st_size || (symbols [i].st_info & 0xf) != STT_FUNC)
1906                         continue;
1907                 //printf ("symbol %s at %d\n", sym, symbols [i].st_value);
1908                 dump_usym (sym, (uintptr_t)load_addr + symbols [i].st_value, symbols [i].st_size);
1909         }
1910 }
1911
1912 static int
1913 read_elf_symbols (MonoProfiler *prof, const char *filename, void *load_addr)
1914 {
1915         int fd, i;
1916         void *data;
1917         struct stat statb;
1918         uint64_t file_size;
1919         ElfW(Ehdr) *header;
1920         ElfW(Shdr) *sheader;
1921         ElfW(Shdr) *shstrtabh;
1922         ElfW(Shdr) *symtabh = NULL;
1923         ElfW(Shdr) *strtabh = NULL;
1924         ElfW(Sym) *symbols = NULL;
1925         const char *strtab;
1926         int num_symbols;
1927
1928         fd = open (filename, O_RDONLY);
1929         if (fd < 0)
1930                 return 0;
1931         if (fstat (fd, &statb) != 0) {
1932                 close (fd);
1933                 return 0;
1934         }
1935         file_size = statb.st_size;
1936         data = mmap (NULL, file_size, PROT_READ, MAP_PRIVATE, fd, 0);
1937         close (fd);
1938         if (data == MAP_FAILED)
1939                 return 0;
1940         header = data;
1941         if (header->e_ident [EI_MAG0] != ELFMAG0 ||
1942                         header->e_ident [EI_MAG1] != ELFMAG1 ||
1943                         header->e_ident [EI_MAG2] != ELFMAG2 ||
1944                         header->e_ident [EI_MAG3] != ELFMAG3 ) {
1945                 munmap (data, file_size);
1946                 return 0;
1947         }
1948         sheader = (void*)((char*)data + header->e_shoff);
1949         shstrtabh = (void*)((char*)sheader + (header->e_shentsize * header->e_shstrndx));
1950         strtab = (const char*)data + shstrtabh->sh_offset;
1951         for (i = 0; i < header->e_shnum; ++i) {
1952                 //printf ("section header: %d\n", sheader->sh_type);
1953                 if (sheader->sh_type == SHT_SYMTAB) {
1954                         symtabh = sheader;
1955                         strtabh = (void*)((char*)data + header->e_shoff + sheader->sh_link * header->e_shentsize);
1956                         /*printf ("symtab section header: %d, .strstr: %d\n", i, sheader->sh_link);*/
1957                         break;
1958                 }
1959                 sheader = (void*)((char*)sheader + header->e_shentsize);
1960         }
1961         if (!symtabh || !strtabh) {
1962                 munmap (data, file_size);
1963                 return 0;
1964         }
1965         strtab = (const char*)data + strtabh->sh_offset;
1966         num_symbols = symtabh->sh_size / symtabh->sh_entsize;
1967         symbols = (void*)((char*)data + symtabh->sh_offset);
1968         dump_elf_symbols (symbols, num_symbols, strtab, load_addr);
1969         munmap (data, file_size);
1970         return 1;
1971 }
1972 #endif
1973
1974 /* ELF code crashes on some systems. */
1975 //#if defined(HAVE_DL_ITERATE_PHDR) && defined(ELFMAG0)
1976 #if 0
1977 static int
1978 elf_dl_callback (struct dl_phdr_info *info, size_t size, void *data)
1979 {
1980         MonoProfiler *prof = data;
1981         char buf [256];
1982         const char *filename;
1983         BinaryObject *obj;
1984         char *a = (void*)info->dlpi_addr;
1985         int i, num_sym;
1986         ElfW(Dyn) *dyn = NULL;
1987         ElfW(Sym) *symtab = NULL;
1988         ElfW(Word) *hash_table = NULL;
1989         ElfW(Ehdr) *header = NULL;
1990         const char* strtab = NULL;
1991         for (obj = prof->binary_objects; obj; obj = obj->next) {
1992                 if (obj->addr == a)
1993                         return 0;
1994         }
1995         filename = info->dlpi_name;
1996         if (!filename)
1997                 return 0;
1998         if (!info->dlpi_addr && !filename [0]) {
1999                 int l = readlink ("/proc/self/exe", buf, sizeof (buf) - 1);
2000                 if (l > 0) {
2001                         buf [l] = 0;
2002                         filename = buf;
2003                 }
2004         }
2005         obj = calloc (sizeof (BinaryObject), 1);
2006         obj->addr = (void*)info->dlpi_addr;
2007         obj->name = pstrdup (filename);
2008         obj->next = prof->binary_objects;
2009         prof->binary_objects = obj;
2010         //printf ("loaded file: %s at %p, segments: %d\n", filename, (void*)info->dlpi_addr, info->dlpi_phnum);
2011         a = NULL;
2012         for (i = 0; i < info->dlpi_phnum; ++i) {
2013                 //printf ("segment type %d file offset: %d, size: %d\n", info->dlpi_phdr[i].p_type, info->dlpi_phdr[i].p_offset, info->dlpi_phdr[i].p_memsz);
2014                 if (info->dlpi_phdr[i].p_type == PT_LOAD && !header) {
2015                         header = (ElfW(Ehdr)*)(info->dlpi_addr + info->dlpi_phdr[i].p_vaddr);
2016                         if (header->e_ident [EI_MAG0] != ELFMAG0 ||
2017                                         header->e_ident [EI_MAG1] != ELFMAG1 ||
2018                                         header->e_ident [EI_MAG2] != ELFMAG2 ||
2019                                         header->e_ident [EI_MAG3] != ELFMAG3 ) {
2020                                 header = NULL;
2021                         }
2022                         dump_ubin (filename, info->dlpi_addr + info->dlpi_phdr[i].p_vaddr, info->dlpi_phdr[i].p_offset, info->dlpi_phdr[i].p_memsz);
2023                 } else if (info->dlpi_phdr[i].p_type == PT_DYNAMIC) {
2024                         dyn = (ElfW(Dyn) *)(info->dlpi_addr + info->dlpi_phdr[i].p_vaddr);
2025                 }
2026         }
2027         if (read_elf_symbols (prof, filename, (void*)info->dlpi_addr))
2028                 return 0;
2029         if (!info->dlpi_name || !info->dlpi_name[0])
2030                 return 0;
2031         if (!dyn)
2032                 return 0;
2033         for (i = 0; dyn [i].d_tag != DT_NULL; ++i) {
2034                 if (dyn [i].d_tag == DT_SYMTAB) {
2035                         if (symtab && do_debug)
2036                                 printf ("multiple symtabs: %d\n", i);
2037                         symtab = (ElfW(Sym) *)(a + dyn [i].d_un.d_ptr);
2038                 } else if (dyn [i].d_tag == DT_HASH) {
2039                         hash_table = (ElfW(Word) *)(a + dyn [i].d_un.d_ptr);
2040                 } else if (dyn [i].d_tag == DT_STRTAB) {
2041                         strtab = (const char*)(a + dyn [i].d_un.d_ptr);
2042                 }
2043         }
2044         if (!hash_table)
2045                 return 0;
2046         num_sym = hash_table [1];
2047         dump_elf_symbols (symtab, num_sym, strtab, (void*)info->dlpi_addr);
2048         return 0;
2049 }
2050
2051 static int
2052 load_binaries (MonoProfiler *prof)
2053 {
2054         dl_iterate_phdr (elf_dl_callback, prof);
2055         return 1;
2056 }
2057 #else
2058 static int
2059 load_binaries (MonoProfiler *prof)
2060 {
2061         return 0;
2062 }
2063 #endif
2064
2065 static const char*
2066 symbol_for (uintptr_t code)
2067 {
2068 #ifdef HAVE_DLADDR
2069         void *ip = (void*)code;
2070         Dl_info di;
2071         if (dladdr (ip, &di)) {
2072                 if (di.dli_sname)
2073                         return di.dli_sname;
2074         } else {
2075         /*      char **names;
2076                 names = backtrace_symbols (&ip, 1);
2077                 if (names) {
2078                         const char* p = names [0];
2079                         free (names);
2080                         return p;
2081                 }
2082                 */
2083         }
2084 #endif
2085         return NULL;
2086 }
2087
2088 static void
2089 dump_unmanaged_coderefs (MonoProfiler *prof)
2090 {
2091         int i;
2092         const char* last_symbol;
2093         uintptr_t addr, page_end;
2094
2095         if (load_binaries (prof))
2096                 return;
2097         for (i = 0; i < size_code_pages; ++i) {
2098                 const char* sym;
2099                 if (!code_pages [i] || code_pages [i] & 1)
2100                         continue;
2101                 last_symbol = NULL;
2102                 addr = CPAGE_ADDR (code_pages [i]);
2103                 page_end = addr + CPAGE_SIZE;
2104                 code_pages [i] |= 1;
2105                 /* we dump the symbols for the whole page */
2106                 for (; addr < page_end; addr += 16) {
2107                         sym = symbol_for (addr);
2108                         if (sym && sym == last_symbol)
2109                                 continue;
2110                         last_symbol = sym;
2111                         if (!sym)
2112                                 continue;
2113                         dump_usym (sym, addr, 0); /* let's not guess the size */
2114                         //printf ("found symbol at %p: %s\n", (void*)addr, sym);
2115                 }
2116         }
2117 }
2118
2119 static gint
2120 compare_sample_events (gconstpointer a, gconstpointer b)
2121 {
2122         uintptr_t tid1 = (*(uintptr_t **) a) [1];
2123         uintptr_t tid2 = (*(uintptr_t **) b) [1];
2124
2125         return tid1 > tid2 ? 1 :
2126                tid1 < tid2 ? -1 :
2127                0;
2128 }
2129
2130 static void
2131 dump_sample_hits (MonoProfiler *prof, StatBuffer *sbuf)
2132 {
2133         LogBuffer *logbuffer;
2134         if (!sbuf)
2135                 return;
2136         if (sbuf->next) {
2137                 dump_sample_hits (prof, sbuf->next);
2138                 free_buffer (sbuf->next, sbuf->next->size);
2139                 sbuf->next = NULL;
2140         }
2141
2142         g_ptr_array_set_size (prof->sorted_sample_events, 0);
2143
2144         for (uintptr_t *sample = sbuf->buf; sample < sbuf->data;) {
2145                 int count = sample [0] & 0xff;
2146                 int mbt_count = (sample [0] & 0xff00) >> 8;
2147
2148                 if (sample + SAMPLE_EVENT_SIZE_IN_SLOTS (mbt_count) > sbuf->data)
2149                         break;
2150
2151                 g_ptr_array_add (prof->sorted_sample_events, sample);
2152
2153                 sample += count + 3 + 4 * mbt_count;
2154         }
2155
2156         g_ptr_array_sort (prof->sorted_sample_events, compare_sample_events);
2157
2158         for (guint sidx = 0; sidx < prof->sorted_sample_events->len; sidx++) {
2159                 uintptr_t *sample = g_ptr_array_index (prof->sorted_sample_events, sidx);
2160                 int count = sample [0] & 0xff;
2161                 int mbt_count = (sample [0] & 0xff00) >> 8;
2162                 int type = sample [0] >> 16;
2163                 uintptr_t *managed_sample_base = sample + count + 3;
2164                 uintptr_t thread_id = sample [1];
2165
2166                 for (int i = 0; i < mbt_count; ++i) {
2167                         MonoMethod *method = (MonoMethod*)managed_sample_base [i * 4 + 0];
2168                         MonoDomain *domain = (MonoDomain*)managed_sample_base [i * 4 + 1];
2169                         void *address = (void*)managed_sample_base [i * 4 + 2];
2170
2171                         if (!method) {
2172                                 MonoJitInfo *ji = mono_jit_info_table_find (domain, address);
2173
2174                                 if (ji)
2175                                         managed_sample_base [i * 4 + 0] = (uintptr_t)mono_jit_info_get_method (ji);
2176                         }
2177                 }
2178
2179                 logbuffer = ensure_logbuf (1 + 10 + 10 + 10 + 10 + 10 + 10 + mbt_count * (10 + 10 + 10));
2180                 emit_byte (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_HIT);
2181                 emit_value (logbuffer, type);
2182                 emit_uvalue (logbuffer, prof->startup_time + (uint64_t)sample [2] * (uint64_t)10000);
2183                 emit_ptr (logbuffer, (void *) thread_id);
2184                 emit_value (logbuffer, count);
2185                 for (int i = 0; i < count; ++i) {
2186                         emit_ptr (logbuffer, (void*)sample [i + 3]);
2187                         add_code_pointer (sample [i + 3]);
2188                 }
2189
2190                 sample += count + 3;
2191                 /* new in data version 6 */
2192                 emit_uvalue (logbuffer, mbt_count);
2193                 for (int i = 0; i < mbt_count; ++i) {
2194                         MonoMethod *method = (MonoMethod *) sample [i * 4 + 0];
2195                         uintptr_t native_offset = sample [i * 4 + 3];
2196
2197                         emit_method (prof, logbuffer, method);
2198                         emit_svalue (logbuffer, 0); /* il offset will always be 0 from now on */
2199                         emit_svalue (logbuffer, native_offset);
2200                 }
2201         }
2202
2203         dump_unmanaged_coderefs (prof);
2204 }
2205
2206 #if USE_PERF_EVENTS
2207
2208 static int
2209 mono_cpu_count (void)
2210 {
2211         int count = 0;
2212 #ifdef PLATFORM_ANDROID
2213         /* Android tries really hard to save power by powering off CPUs on SMP phones which
2214          * means the normal way to query cpu count returns a wrong value with userspace API.
2215          * Instead we use /sys entries to query the actual hardware CPU count.
2216          */
2217         char buffer[8] = {'\0'};
2218         int present = open ("/sys/devices/system/cpu/present", O_RDONLY);
2219         /* Format of the /sys entry is a cpulist of indexes which in the case
2220          * of present is always of the form "0-(n-1)" when there is more than
2221          * 1 core, n being the number of CPU cores in the system. Otherwise
2222          * the value is simply 0
2223          */
2224         if (present != -1 && read (present, (char*)buffer, sizeof (buffer)) > 3)
2225                 count = strtol (((char*)buffer) + 2, NULL, 10);
2226         if (present != -1)
2227                 close (present);
2228         if (count > 0)
2229                 return count + 1;
2230 #endif
2231 #ifdef _SC_NPROCESSORS_ONLN
2232         count = sysconf (_SC_NPROCESSORS_ONLN);
2233         if (count > 0)
2234                 return count;
2235 #endif
2236 #ifdef USE_SYSCTL
2237         {
2238                 int mib [2];
2239                 size_t len = sizeof (int);
2240                 mib [0] = CTL_HW;
2241                 mib [1] = HW_NCPU;
2242                 if (sysctl (mib, 2, &count, &len, NULL, 0) == 0)
2243                         return count;
2244         }
2245 #endif
2246 #ifdef HOST_WIN32
2247         {
2248                 SYSTEM_INFO info;
2249                 GetSystemInfo (&info);
2250                 return info.dwNumberOfProcessors;
2251         }
2252 #endif
2253         /* FIXME: warn */
2254         return 1;
2255 }
2256
2257 typedef struct {
2258         int perf_fd;
2259         unsigned int prev_pos;
2260         void *mmap_base;
2261         struct perf_event_mmap_page *page_desc;
2262 } PerfData ;
2263
2264 static PerfData *perf_data = NULL;
2265 static int num_perf;
2266 #define PERF_PAGES_SHIFT 4
2267 static int num_pages = 1 << PERF_PAGES_SHIFT;
2268 static unsigned int mmap_mask;
2269
2270 typedef struct {
2271         struct perf_event_header h;
2272         uint64_t ip;
2273         uint32_t pid;
2274         uint32_t tid;
2275         uint64_t timestamp;
2276         uint64_t period;
2277         uint64_t nframes;
2278 } PSample;
2279
2280 static int
2281 perf_event_syscall (struct perf_event_attr *attr, pid_t pid, int cpu, int group_fd, unsigned long flags)
2282 {
2283         attr->size = PERF_ATTR_SIZE_VER0;
2284         //printf ("perf attr size: %d\n", attr->size);
2285 #if defined(__x86_64__)
2286         return syscall(/*__NR_perf_event_open*/ 298, attr, pid, cpu, group_fd, flags);
2287 #elif defined(__i386__)
2288         return syscall(/*__NR_perf_event_open*/ 336, attr, pid, cpu, group_fd, flags);
2289 #elif defined(__arm__) || defined (__aarch64__)
2290         return syscall(/*__NR_perf_event_open*/ 364, attr, pid, cpu, group_fd, flags);
2291 #else
2292         return -1;
2293 #endif
2294 }
2295
2296 static int
2297 setup_perf_map (PerfData *perf)
2298 {
2299         perf->mmap_base = mmap (NULL, (num_pages + 1) * getpagesize (), PROT_READ|PROT_WRITE, MAP_SHARED, perf->perf_fd, 0);
2300         if (perf->mmap_base == MAP_FAILED) {
2301                 if (do_debug)
2302                         printf ("failed mmap\n");
2303                 return 0;
2304         }
2305         perf->page_desc = perf->mmap_base;
2306         if (do_debug)
2307                 printf ("mmap version: %d\n", perf->page_desc->version);
2308         return 1;
2309 }
2310
2311 static void
2312 dump_perf_hits (MonoProfiler *prof, void *buf, int size)
2313 {
2314         LogBuffer *logbuffer;
2315         void *end = (char*)buf + size;
2316         int samples = 0;
2317         int pid = getpid ();
2318
2319         while (buf < end) {
2320                 PSample *s = buf;
2321                 if (s->h.size == 0)
2322                         break;
2323                 if (pid != s->pid) {
2324                         if (do_debug)
2325                                 printf ("event for different pid: %d\n", s->pid);
2326                         buf = (char*)buf + s->h.size;
2327                         continue;
2328                 }
2329                 /*ip = (void*)s->ip;
2330                 printf ("sample: %d, size: %d, ip: %p (%s), timestamp: %llu, nframes: %llu\n",
2331                         s->h.type, s->h.size, ip, symbol_for (ip), s->timestamp, s->nframes);*/
2332                 logbuffer = ensure_logbuf (1 + 10 + 10 + 10 + 10 + 10);
2333                 emit_byte (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_HIT);
2334                 emit_value (logbuffer, sample_type);
2335                 emit_uvalue (logbuffer, s->timestamp - prof->startup_time);
2336                 /*
2337                  * No useful thread ID to write here, since throughout the
2338                  * profiler we use pthread_self () but the ID we get from
2339                  * perf is the kernel's thread ID.
2340                  */
2341                 emit_ptr (logbuffer, 0);
2342                 emit_value (logbuffer, 1); /* count */
2343                 emit_ptr (logbuffer, (void*)(uintptr_t)s->ip);
2344                 /* no support here yet for the managed backtrace */
2345                 emit_uvalue (logbuffer, 0);
2346                 add_code_pointer (s->ip);
2347                 buf = (char*)buf + s->h.size;
2348                 samples++;
2349         }
2350         if (do_debug)
2351                 printf ("dumped %d samples\n", samples);
2352         dump_unmanaged_coderefs (prof);
2353 }
2354
2355 /* read events from the ring buffer */
2356 static int
2357 read_perf_mmap (MonoProfiler* prof, int cpu)
2358 {
2359         PerfData *perf = perf_data + cpu;
2360         unsigned char *buf;
2361         unsigned char *data = (unsigned char*)perf->mmap_base + getpagesize ();
2362         unsigned int head = perf->page_desc->data_head;
2363         int diff, size;
2364         unsigned int old;
2365
2366         mono_memory_read_barrier ();
2367
2368         old = perf->prev_pos;
2369         diff = head - old;
2370         if (diff < 0) {
2371                 if (do_debug)
2372                         printf ("lost mmap events: old: %d, head: %d\n", old, head);
2373                 old = head;
2374         }
2375         size = head - old;
2376         if ((old & mmap_mask) + size != (head & mmap_mask)) {
2377                 buf = data + (old & mmap_mask);
2378                 size = mmap_mask + 1 - (old & mmap_mask);
2379                 old += size;
2380                 /* size bytes at buf */
2381                 if (do_debug)
2382                         printf ("found1 bytes of events: %d\n", size);
2383                 dump_perf_hits (prof, buf, size);
2384         }
2385         buf = data + (old & mmap_mask);
2386         size = head - old;
2387         /* size bytes at buf */
2388         if (do_debug)
2389                 printf ("found bytes of events: %d\n", size);
2390         dump_perf_hits (prof, buf, size);
2391         old += size;
2392         perf->prev_pos = old;
2393         perf->page_desc->data_tail = old;
2394         return 0;
2395 }
2396
2397 static int
2398 setup_perf_event_for_cpu (PerfData *perf, int cpu)
2399 {
2400         struct perf_event_attr attr;
2401         memset (&attr, 0, sizeof (attr));
2402         attr.type = PERF_TYPE_HARDWARE;
2403         switch (sample_type) {
2404         case SAMPLE_CYCLES: attr.config = PERF_COUNT_HW_CPU_CYCLES; break;
2405         case SAMPLE_INSTRUCTIONS: attr.config = PERF_COUNT_HW_INSTRUCTIONS; break;
2406         case SAMPLE_CACHE_MISSES: attr.config = PERF_COUNT_HW_CACHE_MISSES; break;
2407         case SAMPLE_CACHE_REFS: attr.config = PERF_COUNT_HW_CACHE_REFERENCES; break;
2408         case SAMPLE_BRANCHES: attr.config = PERF_COUNT_HW_BRANCH_INSTRUCTIONS; break;
2409         case SAMPLE_BRANCH_MISSES: attr.config = PERF_COUNT_HW_BRANCH_MISSES; break;
2410         default: attr.config = PERF_COUNT_HW_CPU_CYCLES; break;
2411         }
2412         attr.sample_type = PERF_SAMPLE_IP | PERF_SAMPLE_TID | PERF_SAMPLE_PERIOD | PERF_SAMPLE_TIME;
2413 //      attr.sample_type |= PERF_SAMPLE_CALLCHAIN;
2414         attr.read_format = PERF_FORMAT_TOTAL_TIME_ENABLED | PERF_FORMAT_TOTAL_TIME_RUNNING | PERF_FORMAT_ID;
2415         attr.inherit = 1;
2416         attr.freq = 1;
2417         attr.sample_freq = sample_freq;
2418
2419         perf->perf_fd = perf_event_syscall (&attr, getpid (), cpu, -1, 0);
2420         if (do_debug)
2421                 printf ("perf fd: %d, freq: %d, event: %llu\n", perf->perf_fd, sample_freq, attr.config);
2422         if (perf->perf_fd < 0) {
2423                 if (perf->perf_fd == -EPERM) {
2424                         fprintf (stderr, "Perf syscall denied, do \"echo 1 > /proc/sys/kernel/perf_event_paranoid\" as root to enable.\n");
2425                 } else {
2426                         if (do_debug)
2427                                 perror ("open perf event");
2428                 }
2429                 return 0;
2430         }
2431         if (!setup_perf_map (perf)) {
2432                 close (perf->perf_fd);
2433                 perf->perf_fd = -1;
2434                 return 0;
2435         }
2436         return 1;
2437 }
2438
2439 static int
2440 setup_perf_event (void)
2441 {
2442         int i, count = 0;
2443         mmap_mask = num_pages * getpagesize () - 1;
2444         num_perf = mono_cpu_count ();
2445         perf_data = calloc (num_perf, sizeof (PerfData));
2446         for (i = 0; i < num_perf; ++i) {
2447                 count += setup_perf_event_for_cpu (perf_data + i, i);
2448         }
2449         if (count)
2450                 return 1;
2451         free (perf_data);
2452         perf_data = NULL;
2453         return 0;
2454 }
2455
2456 #endif /* USE_PERF_EVENTS */
2457
2458 #ifndef DISABLE_HELPER_THREAD
2459
2460 typedef struct MonoCounterAgent {
2461         MonoCounter *counter;
2462         // MonoCounterAgent specific data :
2463         void *value;
2464         size_t value_size;
2465         short index;
2466         short emitted;
2467         struct MonoCounterAgent *next;
2468 } MonoCounterAgent;
2469
2470 static MonoCounterAgent* counters;
2471 static gboolean counters_initialized = FALSE;
2472 static int counters_index = 1;
2473 static mono_mutex_t counters_mutex;
2474
2475 static void
2476 counters_add_agent (MonoCounter *counter)
2477 {
2478         MonoCounterAgent *agent, *item;
2479
2480         if (!counters_initialized)
2481                 return;
2482
2483         mono_mutex_lock (&counters_mutex);
2484
2485         for (agent = counters; agent; agent = agent->next) {
2486                 if (agent->counter == counter) {
2487                         agent->value_size = 0;
2488                         if (agent->value) {
2489                                 free (agent->value);
2490                                 agent->value = NULL;
2491                         }
2492                         mono_mutex_unlock (&counters_mutex);
2493                         return;
2494                 }
2495         }
2496
2497         agent = malloc (sizeof (MonoCounterAgent));
2498         agent->counter = counter;
2499         agent->value = NULL;
2500         agent->value_size = 0;
2501         agent->index = counters_index++;
2502         agent->emitted = 0;
2503         agent->next = NULL;
2504
2505         if (!counters) {
2506                 counters = agent;
2507         } else {
2508                 item = counters;
2509                 while (item->next)
2510                         item = item->next;
2511                 item->next = agent;
2512         }
2513
2514         mono_mutex_unlock (&counters_mutex);
2515 }
2516
2517 static mono_bool
2518 counters_init_foreach_callback (MonoCounter *counter, gpointer data)
2519 {
2520         counters_add_agent (counter);
2521         return TRUE;
2522 }
2523
2524 static void
2525 counters_init (MonoProfiler *profiler)
2526 {
2527         assert (!counters_initialized);
2528
2529         mono_mutex_init (&counters_mutex);
2530
2531         counters_initialized = TRUE;
2532
2533         mono_counters_on_register (&counters_add_agent);
2534         mono_counters_foreach (counters_init_foreach_callback, NULL);
2535 }
2536
2537 static void
2538 counters_emit (MonoProfiler *profiler)
2539 {
2540         MonoCounterAgent *agent;
2541         LogBuffer *logbuffer;
2542         int size = 1 + 10, len = 0;
2543
2544         if (!counters_initialized)
2545                 return;
2546
2547         mono_mutex_lock (&counters_mutex);
2548
2549         for (agent = counters; agent; agent = agent->next) {
2550                 if (agent->emitted)
2551                         continue;
2552
2553                 size += 10 + strlen (mono_counter_get_name (agent->counter)) + 1 + 10 + 10 + 10 + 10;
2554                 len += 1;
2555         }
2556
2557         if (!len) {
2558                 mono_mutex_unlock (&counters_mutex);
2559                 return;
2560         }
2561
2562         logbuffer = ensure_logbuf (size);
2563
2564         ENTER_LOG (logbuffer, "counters");
2565         emit_byte (logbuffer, TYPE_SAMPLE_COUNTERS_DESC | TYPE_SAMPLE);
2566         emit_value (logbuffer, len);
2567         for (agent = counters; agent; agent = agent->next) {
2568                 const char *name;
2569
2570                 if (agent->emitted)
2571                         continue;
2572
2573                 name = mono_counter_get_name (agent->counter);
2574                 emit_value (logbuffer, mono_counter_get_section (agent->counter));
2575                 emit_string (logbuffer, name, strlen (name) + 1);
2576                 emit_value (logbuffer, mono_counter_get_type (agent->counter));
2577                 emit_value (logbuffer, mono_counter_get_unit (agent->counter));
2578                 emit_value (logbuffer, mono_counter_get_variance (agent->counter));
2579                 emit_value (logbuffer, agent->index);
2580
2581                 agent->emitted = 1;
2582         }
2583         EXIT_LOG (logbuffer);
2584
2585         safe_send (profiler, logbuffer);
2586
2587         mono_mutex_unlock (&counters_mutex);
2588 }
2589
2590 static void
2591 counters_sample (MonoProfiler *profiler, uint64_t timestamp)
2592 {
2593         MonoCounterAgent *agent;
2594         MonoCounter *counter;
2595         LogBuffer *logbuffer;
2596         int type;
2597         int buffer_size;
2598         void *buffer;
2599         int size;
2600
2601         if (!counters_initialized)
2602                 return;
2603
2604         counters_emit (profiler);
2605
2606         buffer_size = 8;
2607         buffer = calloc (1, buffer_size);
2608
2609         mono_mutex_lock (&counters_mutex);
2610
2611         size = 1 + 10;
2612         for (agent = counters; agent; agent = agent->next)
2613                 size += 10 + 10 + mono_counter_get_size (agent->counter);
2614         size += 10;
2615
2616         logbuffer = ensure_logbuf (size);
2617
2618         ENTER_LOG (logbuffer, "counters");
2619         emit_byte (logbuffer, TYPE_SAMPLE_COUNTERS | TYPE_SAMPLE);
2620         emit_uvalue (logbuffer, timestamp);
2621         for (agent = counters; agent; agent = agent->next) {
2622                 size_t size;
2623
2624                 counter = agent->counter;
2625
2626                 size = mono_counter_get_size (counter);
2627                 if (size < 0) {
2628                         continue; // FIXME error
2629                 } else if (size > buffer_size) {
2630                         buffer_size = size;
2631                         buffer = realloc (buffer, buffer_size);
2632                 }
2633
2634                 memset (buffer, 0, buffer_size);
2635
2636                 if (mono_counters_sample (counter, buffer, size) < 0)
2637                         continue; // FIXME error
2638
2639                 type = mono_counter_get_type (counter);
2640
2641                 if (!agent->value) {
2642                         agent->value = calloc (1, size);
2643                         agent->value_size = size;
2644                 } else {
2645                         if (type == MONO_COUNTER_STRING) {
2646                                 if (strcmp (agent->value, buffer) == 0)
2647                                         continue;
2648                         } else {
2649                                 if (agent->value_size == size && memcmp (agent->value, buffer, size) == 0)
2650                                         continue;
2651                         }
2652                 }
2653
2654                 emit_uvalue (logbuffer, agent->index);
2655                 emit_uvalue (logbuffer, type);
2656                 switch (type) {
2657                 case MONO_COUNTER_INT:
2658 #if SIZEOF_VOID_P == 4
2659                 case MONO_COUNTER_WORD:
2660 #endif
2661                         emit_svalue (logbuffer, *(int*)buffer - *(int*)agent->value);
2662                         break;
2663                 case MONO_COUNTER_UINT:
2664                         emit_uvalue (logbuffer, *(guint*)buffer - *(guint*)agent->value);
2665                         break;
2666                 case MONO_COUNTER_TIME_INTERVAL:
2667                 case MONO_COUNTER_LONG:
2668 #if SIZEOF_VOID_P == 8
2669                 case MONO_COUNTER_WORD:
2670 #endif
2671                         emit_svalue (logbuffer, *(gint64*)buffer - *(gint64*)agent->value);
2672                         break;
2673                 case MONO_COUNTER_ULONG:
2674                         emit_uvalue (logbuffer, *(guint64*)buffer - *(guint64*)agent->value);
2675                         break;
2676                 case MONO_COUNTER_DOUBLE:
2677                         emit_double (logbuffer, *(double*)buffer);
2678                         break;
2679                 case MONO_COUNTER_STRING:
2680                         if (size == 0) {
2681                                 emit_byte (logbuffer, 0);
2682                         } else {
2683                                 emit_byte (logbuffer, 1);
2684                                 emit_string (logbuffer, (char*)buffer, size);
2685                         }
2686                         break;
2687                 default:
2688                         assert (0);
2689                 }
2690
2691                 if (type == MONO_COUNTER_STRING && size > agent->value_size) {
2692                         agent->value = realloc (agent->value, size);
2693                         agent->value_size = size;
2694                 }
2695
2696                 if (size > 0)
2697                         memcpy (agent->value, buffer, size);
2698         }
2699         free (buffer);
2700
2701         emit_value (logbuffer, 0);
2702         EXIT_LOG (logbuffer);
2703
2704         safe_send (profiler, logbuffer);
2705
2706         mono_mutex_unlock (&counters_mutex);
2707 }
2708
2709 typedef struct _PerfCounterAgent PerfCounterAgent;
2710 struct _PerfCounterAgent {
2711         PerfCounterAgent *next;
2712         int index;
2713         char *category_name;
2714         char *name;
2715         int type;
2716         gint64 value;
2717         guint8 emitted;
2718         guint8 updated;
2719         guint8 deleted;
2720 };
2721
2722 static PerfCounterAgent *perfcounters = NULL;
2723
2724 static void
2725 perfcounters_emit (MonoProfiler *profiler)
2726 {
2727         PerfCounterAgent *pcagent;
2728         LogBuffer *logbuffer;
2729         int size = 1 + 10, len = 0;
2730
2731         for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
2732                 if (pcagent->emitted)
2733                         continue;
2734
2735                 size += 10 + strlen (pcagent->category_name) + 1 + strlen (pcagent->name) + 1 + 10 + 10 + 10 + 10;
2736                 len += 1;
2737         }
2738
2739         if (!len)
2740                 return;
2741
2742         logbuffer = ensure_logbuf (size);
2743
2744         ENTER_LOG (logbuffer, "perfcounters");
2745         emit_byte (logbuffer, TYPE_SAMPLE_COUNTERS_DESC | TYPE_SAMPLE);
2746         emit_value (logbuffer, len);
2747         for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
2748                 if (pcagent->emitted)
2749                         continue;
2750
2751                 emit_value (logbuffer, MONO_COUNTER_PERFCOUNTERS);
2752                 emit_string (logbuffer, pcagent->category_name, strlen (pcagent->category_name) + 1);
2753                 emit_string (logbuffer, pcagent->name, strlen (pcagent->name) + 1);
2754                 emit_value (logbuffer, MONO_COUNTER_LONG);
2755                 emit_value (logbuffer, MONO_COUNTER_RAW);
2756                 emit_value (logbuffer, MONO_COUNTER_VARIABLE);
2757                 emit_value (logbuffer, pcagent->index);
2758
2759                 pcagent->emitted = 1;
2760         }
2761         EXIT_LOG (logbuffer);
2762
2763         safe_send (profiler, logbuffer);
2764 }
2765
2766 static gboolean
2767 perfcounters_foreach (char *category_name, char *name, unsigned char type, gint64 value, gpointer user_data)
2768 {
2769         PerfCounterAgent *pcagent;
2770
2771         for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
2772                 if (strcmp (pcagent->category_name, category_name) != 0 || strcmp (pcagent->name, name) != 0)
2773                         continue;
2774                 if (pcagent->value == value)
2775                         return TRUE;
2776
2777                 pcagent->value = value;
2778                 pcagent->updated = 1;
2779                 pcagent->deleted = 0;
2780                 return TRUE;
2781         }
2782
2783         pcagent = g_new0 (PerfCounterAgent, 1);
2784         pcagent->next = perfcounters;
2785         pcagent->index = counters_index++;
2786         pcagent->category_name = g_strdup (category_name);
2787         pcagent->name = g_strdup (name);
2788         pcagent->type = (int) type;
2789         pcagent->value = value;
2790         pcagent->emitted = 0;
2791         pcagent->updated = 1;
2792         pcagent->deleted = 0;
2793
2794         perfcounters = pcagent;
2795
2796         return TRUE;
2797 }
2798
2799 static void
2800 perfcounters_sample (MonoProfiler *profiler, uint64_t timestamp)
2801 {
2802         PerfCounterAgent *pcagent;
2803         LogBuffer *logbuffer;
2804         int size;
2805
2806         if (!counters_initialized)
2807                 return;
2808
2809         mono_mutex_lock (&counters_mutex);
2810
2811         /* mark all perfcounters as deleted, foreach will unmark them as necessary */
2812         for (pcagent = perfcounters; pcagent; pcagent = pcagent->next)
2813                 pcagent->deleted = 1;
2814
2815         mono_perfcounter_foreach (perfcounters_foreach, perfcounters);
2816
2817         perfcounters_emit (profiler);
2818
2819
2820         size = 1 + 10;
2821         for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
2822                 if (pcagent->deleted || !pcagent->updated)
2823                         continue;
2824                 size += 10 + 10 + 10;
2825         }
2826         size += 10;
2827
2828         logbuffer = ensure_logbuf (size);
2829
2830         ENTER_LOG (logbuffer, "perfcounters");
2831         emit_byte (logbuffer, TYPE_SAMPLE_COUNTERS | TYPE_SAMPLE);
2832         emit_uvalue (logbuffer, timestamp);
2833         for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
2834                 if (pcagent->deleted || !pcagent->updated)
2835                         continue;
2836                 emit_uvalue (logbuffer, pcagent->index);
2837                 emit_uvalue (logbuffer, MONO_COUNTER_LONG);
2838                 emit_svalue (logbuffer, pcagent->value);
2839
2840                 pcagent->updated = 0;
2841         }
2842
2843         emit_value (logbuffer, 0);
2844         EXIT_LOG (logbuffer);
2845
2846         safe_send (profiler, logbuffer);
2847
2848         mono_mutex_unlock (&counters_mutex);
2849 }
2850
2851 static void
2852 counters_and_perfcounters_sample (MonoProfiler *prof)
2853 {
2854         static uint64_t start = -1;
2855         uint64_t now;
2856
2857         if (start == -1)
2858                 start = current_time ();
2859
2860         now = current_time ();
2861         counters_sample (prof, (now - start) / 1000/ 1000);
2862         perfcounters_sample (prof, (now - start) / 1000/ 1000);
2863 }
2864
2865 #define COVERAGE_DEBUG(x) if (debug_coverage) {x}
2866 static MonoConcurrentHashTable *coverage_methods = NULL;
2867 static mono_mutex_t coverage_methods_mutex;
2868 static MonoConcurrentHashTable *coverage_assemblies = NULL;
2869 static mono_mutex_t coverage_assemblies_mutex;
2870 static MonoConcurrentHashTable *coverage_classes = NULL;
2871 static mono_mutex_t coverage_classes_mutex;
2872 static MonoConcurrentHashTable *filtered_classes = NULL;
2873 static mono_mutex_t filtered_classes_mutex;
2874 static MonoConcurrentHashTable *entered_methods = NULL;
2875 static mono_mutex_t entered_methods_mutex;
2876 static MonoConcurrentHashTable *image_to_methods = NULL;
2877 static mono_mutex_t image_to_methods_mutex;
2878 static MonoConcurrentHashTable *suppressed_assemblies = NULL;
2879 static mono_mutex_t suppressed_assemblies_mutex;
2880 static gboolean coverage_initialized = FALSE;
2881
2882 static GPtrArray *coverage_data = NULL;
2883 static int previous_offset = 0;
2884
2885 typedef struct _MethodNode MethodNode;
2886 struct _MethodNode {
2887         MonoLockFreeQueueNode node;
2888         MonoMethod *method;
2889 };
2890
2891 typedef struct _CoverageEntry CoverageEntry;
2892 struct _CoverageEntry {
2893         int offset;
2894         int counter;
2895         char *filename;
2896         int line;
2897         int column;
2898 };
2899
2900 static void
2901 free_coverage_entry (gpointer data, gpointer userdata)
2902 {
2903         CoverageEntry *entry = (CoverageEntry *)data;
2904         g_free (entry->filename);
2905         g_free (entry);
2906 }
2907
2908 static void
2909 obtain_coverage_for_method (MonoProfiler *prof, const MonoProfileCoverageEntry *entry)
2910 {
2911         int offset = entry->iloffset - previous_offset;
2912         CoverageEntry *e = g_new (CoverageEntry, 1);
2913
2914         previous_offset = entry->iloffset;
2915
2916         e->offset = offset;
2917         e->counter = entry->counter;
2918         e->filename = g_strdup(entry->filename ? entry->filename : "");
2919         e->line = entry->line;
2920         e->column = entry->col;
2921
2922         g_ptr_array_add (coverage_data, e);
2923 }
2924
2925 static char *
2926 parse_generic_type_names(char *name)
2927 {
2928         char *new_name, *ret;
2929         int within_generic_declaration = 0, generic_members = 1;
2930
2931         if (name == NULL || *name == '\0')
2932                 return g_strdup ("");
2933
2934         if (!(ret = new_name = calloc (strlen (name) * 4 + 1, sizeof (char))))
2935                 return NULL;
2936
2937         do {
2938                 switch (*name) {
2939                         case '<':
2940                                 within_generic_declaration = 1;
2941                                 break;
2942
2943                         case '>':
2944                                 within_generic_declaration = 0;
2945
2946                                 if (*(name - 1) != '<') {
2947                                         *new_name++ = '`';
2948                                         *new_name++ = '0' + generic_members;
2949                                 } else {
2950                                         memcpy (new_name, "&lt;&gt;", 8);
2951                                         new_name += 8;
2952                                 }
2953
2954                                 generic_members = 0;
2955                                 break;
2956
2957                         case ',':
2958                                 generic_members++;
2959                                 break;
2960
2961                         default:
2962                                 if (!within_generic_declaration)
2963                                         *new_name++ = *name;
2964
2965                                 break;
2966                 }
2967         } while (*name++);
2968
2969         return ret;
2970 }
2971
2972 static int method_id;
2973 static void
2974 build_method_buffer (gpointer key, gpointer value, gpointer userdata)
2975 {
2976         MonoMethod *method = (MonoMethod *)value;
2977         MonoProfiler *prof = (MonoProfiler *)userdata;
2978         MonoClass *klass;
2979         MonoImage *image;
2980         char *class_name;
2981         const char *image_name, *method_name, *sig, *first_filename;
2982         LogBuffer *logbuffer;
2983         int size;
2984         guint i;
2985
2986         previous_offset = 0;
2987         coverage_data = g_ptr_array_new ();
2988
2989         mono_profiler_coverage_get (prof, method, obtain_coverage_for_method);
2990
2991         klass = mono_method_get_class (method);
2992         image = mono_class_get_image (klass);
2993         image_name = mono_image_get_name (image);
2994
2995         sig = mono_signature_get_desc (mono_method_signature (method), TRUE);
2996         class_name = parse_generic_type_names (mono_type_get_name (mono_class_get_type (klass)));
2997         method_name = mono_method_get_name (method);
2998
2999         if (coverage_data->len != 0) {
3000                 CoverageEntry *entry = coverage_data->pdata[0];
3001                 first_filename = entry->filename ? entry->filename : "";
3002         } else
3003                 first_filename = "";
3004
3005         image_name = image_name ? image_name : "";
3006         sig = sig ? sig : "";
3007         method_name = method_name ? method_name : "";
3008
3009         size = 1;
3010
3011         size += strlen (image_name) + 1;
3012         size += strlen (class_name) + 1;
3013         size += strlen (method_name) + 1;
3014         size += strlen (sig) + 1;
3015         size += strlen (first_filename) + 1;
3016
3017         size += 10 + 10 + 10; /* token + method_id + n_entries*/
3018
3019         logbuffer = ensure_logbuf (size);
3020         ENTER_LOG (logbuffer, "coverage-methods");
3021
3022         emit_byte (logbuffer, TYPE_COVERAGE_METHOD | TYPE_COVERAGE);
3023         emit_string (logbuffer, image_name, strlen (image_name) + 1);
3024         emit_string (logbuffer, class_name, strlen (class_name) + 1);
3025         emit_string (logbuffer, method_name, strlen (method_name) + 1);
3026         emit_string (logbuffer, sig, strlen (sig) + 1);
3027         emit_string (logbuffer, first_filename, strlen (first_filename) + 1);
3028
3029         emit_uvalue (logbuffer, mono_method_get_token (method));
3030         emit_uvalue (logbuffer, method_id);
3031         emit_value (logbuffer, coverage_data->len);
3032
3033         EXIT_LOG (logbuffer);
3034         safe_send (prof, logbuffer);
3035
3036         for (i = 0; i < coverage_data->len; i++) {
3037                 CoverageEntry *entry = coverage_data->pdata[i];
3038
3039                 logbuffer = ensure_logbuf (1 + 10 + 10 + 10 + 10 + 10);
3040                 ENTER_LOG (logbuffer, "coverage-statement");
3041
3042                 emit_byte (logbuffer, TYPE_COVERAGE_STATEMENT | TYPE_COVERAGE);
3043                 emit_uvalue (logbuffer, method_id);
3044                 emit_uvalue (logbuffer, entry->offset);
3045                 emit_uvalue (logbuffer, entry->counter);
3046                 emit_uvalue (logbuffer, entry->line);
3047                 emit_uvalue (logbuffer, entry->column);
3048
3049                 EXIT_LOG (logbuffer);
3050                 safe_send (prof, logbuffer);
3051         }
3052
3053         method_id++;
3054
3055         g_free (class_name);
3056
3057         g_ptr_array_foreach (coverage_data, free_coverage_entry, NULL);
3058         g_ptr_array_free (coverage_data, TRUE);
3059         coverage_data = NULL;
3060 }
3061
3062 /* This empties the queue */
3063 static guint
3064 count_queue (MonoLockFreeQueue *queue)
3065 {
3066         MonoLockFreeQueueNode *node;
3067         guint count = 0;
3068
3069         while ((node = mono_lock_free_queue_dequeue (queue))) {
3070                 count++;
3071                 mono_lock_free_queue_node_free (node);
3072         }
3073
3074         return count;
3075 }
3076
3077 static void
3078 build_class_buffer (gpointer key, gpointer value, gpointer userdata)
3079 {
3080         MonoClass *klass = (MonoClass *)key;
3081         MonoLockFreeQueue *class_methods = (MonoLockFreeQueue *)value;
3082         MonoProfiler *prof = (MonoProfiler *)userdata;
3083         MonoImage *image;
3084         char *class_name;
3085         const char *assembly_name;
3086         int number_of_methods, partially_covered;
3087         guint fully_covered;
3088         LogBuffer *logbuffer;
3089         int size;
3090
3091         image = mono_class_get_image (klass);
3092         assembly_name = mono_image_get_name (image);
3093         class_name = mono_type_get_name (mono_class_get_type (klass));
3094
3095         assembly_name = assembly_name ? assembly_name : "";
3096         number_of_methods = mono_class_num_methods (klass);
3097         fully_covered = count_queue (class_methods);
3098         /* We don't handle partial covered yet */
3099         partially_covered = 0;
3100
3101         size = 1;
3102
3103         size += strlen (assembly_name) + 1;
3104         size += strlen (class_name) + 1;
3105         size += 10 + 10 + 10; /* number_of_methods, fully_covered, partially_covered */
3106
3107         logbuffer = ensure_logbuf (size);
3108
3109         ENTER_LOG (logbuffer, "coverage-class");
3110         emit_byte (logbuffer, TYPE_COVERAGE_CLASS | TYPE_COVERAGE);
3111         emit_string (logbuffer, assembly_name, strlen (assembly_name) + 1);
3112         emit_string (logbuffer, class_name, strlen (class_name) + 1);
3113         emit_uvalue (logbuffer, number_of_methods);
3114         emit_uvalue (logbuffer, fully_covered);
3115         emit_uvalue (logbuffer, partially_covered);
3116         EXIT_LOG (logbuffer);
3117
3118         safe_send (prof, logbuffer);
3119
3120         g_free (class_name);
3121 }
3122
3123 static void
3124 get_coverage_for_image (MonoImage *image, int *number_of_methods, guint *fully_covered, int *partially_covered)
3125 {
3126         MonoLockFreeQueue *image_methods = mono_conc_hashtable_lookup (image_to_methods, image);
3127
3128         *number_of_methods = mono_image_get_table_rows (image, MONO_TABLE_METHOD);
3129         if (image_methods)
3130                 *fully_covered = count_queue (image_methods);
3131         else
3132                 *fully_covered = 0;
3133
3134         // FIXME: We don't handle partially covered yet.
3135         *partially_covered = 0;
3136 }
3137
3138 static void
3139 build_assembly_buffer (gpointer key, gpointer value, gpointer userdata)
3140 {
3141         MonoAssembly *assembly = (MonoAssembly *)value;
3142         MonoProfiler *prof = (MonoProfiler *)userdata;
3143         MonoImage *image = mono_assembly_get_image (assembly);
3144         LogBuffer *logbuffer;
3145         const char *name, *guid, *filename;
3146         int size;
3147         int number_of_methods = 0, partially_covered = 0;
3148         guint fully_covered = 0;
3149
3150         name = mono_image_get_name (image);
3151         guid = mono_image_get_guid (image);
3152         filename = mono_image_get_filename (image);
3153
3154         name = name ? name : "";
3155         guid = guid ? guid : "";
3156         filename = filename ? filename : "";
3157
3158         get_coverage_for_image (image, &number_of_methods, &fully_covered, &partially_covered);
3159
3160         size = 1;
3161
3162         size += strlen (name) + 1;
3163         size += strlen (guid) + 1;
3164         size += strlen (filename) + 1;
3165         size += 10 + 10 + 10; /* number_of_methods, fully_covered, partially_covered */
3166         logbuffer = ensure_logbuf (size);
3167
3168         ENTER_LOG (logbuffer, "coverage-assemblies");
3169         emit_byte (logbuffer, TYPE_COVERAGE_ASSEMBLY | TYPE_COVERAGE);
3170         emit_string (logbuffer, name, strlen (name) + 1);
3171         emit_string (logbuffer, guid, strlen (guid) + 1);
3172         emit_string (logbuffer, filename, strlen (filename) + 1);
3173         emit_uvalue (logbuffer, number_of_methods);
3174         emit_uvalue (logbuffer, fully_covered);
3175         emit_uvalue (logbuffer, partially_covered);
3176         EXIT_LOG (logbuffer);
3177
3178         safe_send (prof, logbuffer);
3179 }
3180
3181 static void
3182 dump_coverage (MonoProfiler *prof)
3183 {
3184         if (!coverage_initialized)
3185                 return;
3186
3187         COVERAGE_DEBUG(fprintf (stderr, "Coverage: Started dump\n");)
3188         method_id = 0;
3189
3190         mono_conc_hashtable_foreach (coverage_assemblies, build_assembly_buffer, prof);
3191         mono_conc_hashtable_foreach (coverage_classes, build_class_buffer, prof);
3192         mono_conc_hashtable_foreach (coverage_methods, build_method_buffer, prof);
3193
3194         COVERAGE_DEBUG(fprintf (stderr, "Coverage: Finished dump\n");)
3195 }
3196
3197 static void
3198 process_method_enter_coverage (MonoProfiler *prof, MonoMethod *method)
3199 {
3200         MonoClass *klass;
3201         MonoImage *image;
3202
3203         if (!coverage_initialized)
3204                 return;
3205
3206         klass = mono_method_get_class (method);
3207         image = mono_class_get_image (klass);
3208
3209         if (mono_conc_hashtable_lookup (suppressed_assemblies, (gpointer) mono_image_get_name (image)))
3210                 return;
3211
3212         mono_conc_hashtable_insert (entered_methods, method, method);
3213 }
3214
3215 static MonoLockFreeQueueNode *
3216 create_method_node (MonoMethod *method)
3217 {
3218         MethodNode *node = g_malloc (sizeof (MethodNode));
3219         mono_lock_free_queue_node_init ((MonoLockFreeQueueNode *) node, FALSE);
3220         node->method = method;
3221
3222         return (MonoLockFreeQueueNode *) node;
3223 }
3224
3225 static gboolean
3226 coverage_filter (MonoProfiler *prof, MonoMethod *method)
3227 {
3228         MonoClass *klass;
3229         MonoImage *image;
3230         MonoAssembly *assembly;
3231         MonoMethodHeader *header;
3232         guint32 iflags, flags, code_size;
3233         char *fqn, *classname;
3234         gboolean has_positive, found;
3235         MonoLockFreeQueue *image_methods, *class_methods;
3236         MonoLockFreeQueueNode *node;
3237
3238         if (!coverage_initialized)
3239                 return FALSE;
3240
3241         COVERAGE_DEBUG(fprintf (stderr, "Coverage filter for %s\n", mono_method_get_name (method));)
3242
3243         flags = mono_method_get_flags (method, &iflags);
3244         if ((iflags & 0x1000 /*METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL*/) ||
3245             (flags & 0x2000 /*METHOD_ATTRIBUTE_PINVOKE_IMPL*/)) {
3246                 COVERAGE_DEBUG(fprintf (stderr, "   Internal call or pinvoke - ignoring\n");)
3247                 return FALSE;
3248         }
3249
3250         // Don't need to do anything else if we're already tracking this method
3251         if (mono_conc_hashtable_lookup (coverage_methods, method)) {
3252                 COVERAGE_DEBUG(fprintf (stderr, "   Already tracking\n");)
3253                 return TRUE;
3254         }
3255
3256         klass = mono_method_get_class (method);
3257         image = mono_class_get_image (klass);
3258
3259         // Don't handle coverage for the core assemblies
3260         if (mono_conc_hashtable_lookup (suppressed_assemblies, (gpointer) mono_image_get_name (image)) != NULL)
3261                 return FALSE;
3262
3263         if (prof->coverage_filters) {
3264                 /* Check already filtered classes first */
3265                 if (mono_conc_hashtable_lookup (filtered_classes, klass)) {
3266                         COVERAGE_DEBUG(fprintf (stderr, "   Already filtered\n");)
3267                         return FALSE;
3268                 }
3269
3270                 classname = mono_type_get_name (mono_class_get_type (klass));
3271
3272                 fqn = g_strdup_printf ("[%s]%s", mono_image_get_name (image), classname);
3273
3274                 COVERAGE_DEBUG(fprintf (stderr, "   Looking for %s in filter\n", fqn);)
3275                 // Check positive filters first
3276                 has_positive = FALSE;
3277                 found = FALSE;
3278                 for (guint i = 0; i < prof->coverage_filters->len; ++i) {
3279                         char *filter = g_ptr_array_index (prof->coverage_filters, i);
3280
3281                         if (filter [0] == '+') {
3282                                 filter = &filter [1];
3283
3284                                 COVERAGE_DEBUG(fprintf (stderr, "   Checking against +%s ...", filter);)
3285
3286                                 if (strstr (fqn, filter) != NULL) {
3287                                         COVERAGE_DEBUG(fprintf (stderr, "matched\n");)
3288                                         found = TRUE;
3289                                 } else
3290                                         COVERAGE_DEBUG(fprintf (stderr, "no match\n");)
3291
3292                                 has_positive = TRUE;
3293                         }
3294                 }
3295
3296                 if (has_positive && !found) {
3297                         COVERAGE_DEBUG(fprintf (stderr, "   Positive match was not found\n");)
3298
3299                         mono_conc_hashtable_insert (filtered_classes, klass, klass);
3300                         g_free (fqn);
3301                         g_free (classname);
3302
3303                         return FALSE;
3304                 }
3305
3306                 for (guint i = 0; i < prof->coverage_filters->len; ++i) {
3307                         // FIXME: Is substring search sufficient?
3308                         char *filter = g_ptr_array_index (prof->coverage_filters, i);
3309                         if (filter [0] == '+')
3310                                 continue;
3311
3312                         // Skip '-'
3313                         filter = &filter [1];
3314                         COVERAGE_DEBUG(fprintf (stderr, "   Checking against -%s ...", filter);)
3315
3316                         if (strstr (fqn, filter) != NULL) {
3317                                 COVERAGE_DEBUG(fprintf (stderr, "matched\n");)
3318
3319                                 mono_conc_hashtable_insert (filtered_classes, klass, klass);
3320                                 g_free (fqn);
3321                                 g_free (classname);
3322
3323                                 return FALSE;
3324                         } else
3325                                 COVERAGE_DEBUG(fprintf (stderr, "no match\n");)
3326
3327                 }
3328
3329                 g_free (fqn);
3330                 g_free (classname);
3331         }
3332
3333         COVERAGE_DEBUG(fprintf (stderr, "   Handling coverage for %s\n", mono_method_get_name (method));)
3334         header = mono_method_get_header (method);
3335
3336         mono_method_header_get_code (header, &code_size, NULL);
3337
3338         assembly = mono_image_get_assembly (image);
3339
3340         mono_conc_hashtable_insert (coverage_methods, method, method);
3341         mono_conc_hashtable_insert (coverage_assemblies, assembly, assembly);
3342
3343         image_methods = mono_conc_hashtable_lookup (image_to_methods, image);
3344
3345         if (image_methods == NULL) {
3346                 image_methods = g_malloc (sizeof (MonoLockFreeQueue));
3347                 mono_lock_free_queue_init (image_methods);
3348                 mono_conc_hashtable_insert (image_to_methods, image, image_methods);
3349         }
3350
3351         node = create_method_node (method);
3352         mono_lock_free_queue_enqueue (image_methods, node);
3353
3354         class_methods = mono_conc_hashtable_lookup (coverage_classes, klass);
3355
3356         if (class_methods == NULL) {
3357                 class_methods = g_malloc (sizeof (MonoLockFreeQueue));
3358                 mono_lock_free_queue_init (class_methods);
3359                 mono_conc_hashtable_insert (coverage_classes, klass, class_methods);
3360         }
3361
3362         node = create_method_node (method);
3363         mono_lock_free_queue_enqueue (class_methods, node);
3364
3365         return TRUE;
3366 }
3367
3368 #define LINE_BUFFER_SIZE 4096
3369 /* Max file limit of 128KB */
3370 #define MAX_FILE_SIZE 128 * 1024
3371 static char *
3372 get_file_content (FILE *stream)
3373 {
3374         char *buffer;
3375         ssize_t bytes_read;
3376         long filesize;
3377         int res, offset = 0;
3378
3379         res = fseek (stream, 0, SEEK_END);
3380         if (res < 0)
3381           return NULL;
3382
3383         filesize = ftell (stream);
3384         if (filesize < 0)
3385           return NULL;
3386
3387         res = fseek (stream, 0, SEEK_SET);
3388         if (res < 0)
3389           return NULL;
3390
3391         if (filesize > MAX_FILE_SIZE)
3392           return NULL;
3393
3394         buffer = g_malloc ((filesize + 1) * sizeof (char));
3395         while ((bytes_read = fread (buffer + offset, 1, LINE_BUFFER_SIZE, stream)) > 0)
3396                 offset += bytes_read;
3397
3398         /* NULL terminate our buffer */
3399         buffer[filesize] = '\0';
3400         return buffer;
3401 }
3402
3403 static char *
3404 get_next_line (char *contents, char **next_start)
3405 {
3406         char *p = contents;
3407
3408         if (p == NULL || *p == '\0') {
3409                 *next_start = NULL;
3410                 return NULL;
3411         }
3412
3413         while (*p != '\n' && *p != '\0')
3414                 p++;
3415
3416         if (*p == '\n') {
3417                 *p = '\0';
3418                 *next_start = p + 1;
3419         } else
3420                 *next_start = NULL;
3421
3422         return contents;
3423 }
3424
3425 static void
3426 init_suppressed_assemblies (void)
3427 {
3428         char *content;
3429         char *line;
3430         FILE *sa_file;
3431
3432         mono_mutex_init (&suppressed_assemblies_mutex);
3433         suppressed_assemblies = mono_conc_hashtable_new (&suppressed_assemblies_mutex, g_str_hash, g_str_equal);
3434         sa_file = fopen (SUPPRESSION_DIR "/mono-profiler-log.suppression", "r");
3435         if (sa_file == NULL)
3436                 return;
3437
3438         /* Don't need to free @content as it is referred to by the lines stored in @suppressed_assemblies */
3439         content = get_file_content (sa_file);
3440         if (content == NULL) {
3441                 g_error ("mono-profiler-log.suppression is greater than 128kb - aborting\n");
3442         }
3443
3444         while ((line = get_next_line (content, &content))) {
3445                 line = g_strchomp (g_strchug (line));
3446                 mono_conc_hashtable_insert (suppressed_assemblies, line, line);
3447         }
3448
3449         fclose (sa_file);
3450 }
3451
3452 static MonoConcurrentHashTable *
3453 init_hashtable (mono_mutex_t *mutex)
3454 {
3455         mono_mutex_init (mutex);
3456         return mono_conc_hashtable_new (mutex, NULL, NULL);
3457 }
3458
3459 static void
3460 destroy_hashtable (MonoConcurrentHashTable *hashtable, mono_mutex_t *mutex)
3461 {
3462         mono_conc_hashtable_destroy (hashtable);
3463         mono_mutex_destroy (mutex);
3464 }
3465
3466 #endif /* DISABLE_HELPER_THREAD */
3467
3468 static void
3469 coverage_init (MonoProfiler *prof)
3470 {
3471 #ifndef DISABLE_HELPER_THREAD
3472         assert (!coverage_initialized);
3473
3474         COVERAGE_DEBUG(fprintf (stderr, "Coverage initialized\n");)
3475
3476         coverage_methods = init_hashtable (&coverage_methods_mutex);
3477         coverage_assemblies = init_hashtable (&coverage_assemblies_mutex);
3478         coverage_classes = init_hashtable (&coverage_classes_mutex);
3479         filtered_classes = init_hashtable (&filtered_classes_mutex);
3480         entered_methods = init_hashtable (&entered_methods_mutex);
3481         image_to_methods = init_hashtable (&image_to_methods_mutex);
3482         init_suppressed_assemblies ();
3483
3484         coverage_initialized = TRUE;
3485 #endif /* DISABLE_HELPER_THREAD */
3486 }
3487
3488 static void
3489 log_shutdown (MonoProfiler *prof)
3490 {
3491         void *res;
3492
3493         in_shutdown = 1;
3494 #ifndef DISABLE_HELPER_THREAD
3495         counters_and_perfcounters_sample (prof);
3496
3497         dump_coverage (prof);
3498
3499         if (prof->command_port) {
3500                 char c = 1;
3501                 ign_res (write (prof->pipes [1], &c, 1));
3502                 pthread_join (prof->helper_thread, &res);
3503         }
3504 #endif
3505 #if USE_PERF_EVENTS
3506         if (perf_data) {
3507                 int i;
3508                 for (i = 0; i < num_perf; ++i)
3509                         read_perf_mmap (prof, i);
3510         }
3511 #endif
3512
3513         g_ptr_array_free (prof->sorted_sample_events, TRUE);
3514
3515         if (TLS_GET (LogBuffer, tlsbuffer))
3516                 send_buffer (prof, TLS_GET (GPtrArray, tlsmethodlist), TLS_GET (LogBuffer, tlsbuffer));
3517
3518         TLS_SET (tlsbuffer, NULL);
3519         TLS_SET (tlsmethodlist, NULL);
3520
3521         InterlockedWrite (&prof->run_writer_thread, 0);
3522         pthread_join (prof->writer_thread, &res);
3523
3524 #if defined (HAVE_SYS_ZLIB)
3525         if (prof->gzfile)
3526                 gzclose (prof->gzfile);
3527 #endif
3528         if (prof->pipe_output)
3529                 pclose (prof->file);
3530         else
3531                 fclose (prof->file);
3532
3533         destroy_hashtable (prof->method_table, &prof->method_table_mutex);
3534
3535         if (coverage_initialized) {
3536                 destroy_hashtable (coverage_methods, &coverage_methods_mutex);
3537                 destroy_hashtable (coverage_assemblies, &coverage_assemblies_mutex);
3538                 destroy_hashtable (coverage_classes, &coverage_classes_mutex);
3539                 destroy_hashtable (filtered_classes, &filtered_classes_mutex);
3540                 destroy_hashtable (entered_methods, &entered_methods_mutex);
3541                 destroy_hashtable (image_to_methods, &image_to_methods_mutex);
3542                 destroy_hashtable (suppressed_assemblies, &suppressed_assemblies_mutex);
3543         }
3544
3545         free (prof);
3546 }
3547
3548 static char*
3549 new_filename (const char* filename)
3550 {
3551         time_t t = time (NULL);
3552         int pid = process_id ();
3553         char pid_buf [16];
3554         char time_buf [16];
3555         char *res, *d;
3556         const char *p;
3557         int count_dates = 0;
3558         int count_pids = 0;
3559         int s_date, s_pid;
3560         struct tm *ts;
3561         for (p = filename; *p; p++) {
3562                 if (*p != '%')
3563                         continue;
3564                 p++;
3565                 if (*p == 't')
3566                         count_dates++;
3567                 else if (*p == 'p')
3568                         count_pids++;
3569                 else if (*p == 0)
3570                         break;
3571         }
3572         if (!count_dates && !count_pids)
3573                 return pstrdup (filename);
3574         snprintf (pid_buf, sizeof (pid_buf), "%d", pid);
3575         ts = gmtime (&t);
3576         snprintf (time_buf, sizeof (time_buf), "%d%02d%02d%02d%02d%02d",
3577                 1900 + ts->tm_year, 1 + ts->tm_mon, ts->tm_mday, ts->tm_hour, ts->tm_min, ts->tm_sec);
3578         s_date = strlen (time_buf);
3579         s_pid = strlen (pid_buf);
3580         d = res = malloc (strlen (filename) + s_date * count_dates + s_pid * count_pids);
3581         for (p = filename; *p; p++) {
3582                 if (*p != '%') {
3583                         *d++ = *p;
3584                         continue;
3585                 }
3586                 p++;
3587                 if (*p == 't') {
3588                         strcpy (d, time_buf);
3589                         d += s_date;
3590                         continue;
3591                 } else if (*p == 'p') {
3592                         strcpy (d, pid_buf);
3593                         d += s_pid;
3594                         continue;
3595                 } else if (*p == '%') {
3596                         *d++ = '%';
3597                         continue;
3598                 } else if (*p == 0)
3599                         break;
3600                 *d++ = '%';
3601                 *d++ = *p;
3602         }
3603         *d = 0;
3604         return res;
3605 }
3606
3607 //this is exposed by the JIT, but it's not meant to be a supported API for now.
3608 extern void mono_threads_attach_tools_thread (void);
3609
3610 #ifndef DISABLE_HELPER_THREAD
3611
3612 static void*
3613 helper_thread (void* arg)
3614 {
3615         MonoProfiler* prof = arg;
3616         int command_socket;
3617         int len;
3618         char buf [64];
3619         MonoThread *thread = NULL;
3620
3621         mono_threads_attach_tools_thread ();
3622         //fprintf (stderr, "Server listening\n");
3623         command_socket = -1;
3624         while (1) {
3625                 fd_set rfds;
3626                 struct timeval tv;
3627                 int max_fd = -1;
3628                 FD_ZERO (&rfds);
3629                 FD_SET (prof->server_socket, &rfds);
3630                 max_fd = prof->server_socket;
3631                 FD_SET (prof->pipes [0], &rfds);
3632                 if (max_fd < prof->pipes [0])
3633                         max_fd = prof->pipes [0];
3634                 if (command_socket >= 0) {
3635                         FD_SET (command_socket, &rfds);
3636                         if (max_fd < command_socket)
3637                                 max_fd = command_socket;
3638                 }
3639 #if USE_PERF_EVENTS
3640                 if (perf_data) {
3641                         int i;
3642                         for ( i = 0; i < num_perf; ++i) {
3643                                 if (perf_data [i].perf_fd < 0)
3644                                         continue;
3645                                 FD_SET (perf_data [i].perf_fd, &rfds);
3646                                 if (max_fd < perf_data [i].perf_fd)
3647                                         max_fd = perf_data [i].perf_fd;
3648                         }
3649                 }
3650 #endif
3651
3652                 counters_and_perfcounters_sample (prof);
3653
3654                 tv.tv_sec = 1;
3655                 tv.tv_usec = 0;
3656                 len = select (max_fd + 1, &rfds, NULL, NULL, &tv);
3657
3658                 if (len < 0) {
3659                         if (errno == EINTR)
3660                                 continue;
3661
3662                         g_warning ("Error in proflog server: %s", strerror (errno));
3663                         return NULL;
3664                 }
3665
3666                 if (FD_ISSET (prof->pipes [0], &rfds)) {
3667                         char c;
3668                         int r = read (prof->pipes [0], &c, 1);
3669                         if (r == 1 && c == 0) {
3670                                 StatBuffer *sbufbase = prof->stat_buffers;
3671                                 StatBuffer *sbuf;
3672                                 if (!sbufbase->next)
3673                                         continue;
3674                                 sbuf = sbufbase->next->next;
3675                                 sbufbase->next->next = NULL;
3676                                 if (do_debug)
3677                                         fprintf (stderr, "stat buffer dump\n");
3678                                 if (sbuf) {
3679                                         dump_sample_hits (prof, sbuf);
3680                                         free_buffer (sbuf, sbuf->size);
3681                                         safe_send (prof, ensure_logbuf (0));
3682                                 }
3683                                 continue;
3684                         }
3685                         /* time to shut down */
3686                         dump_sample_hits (prof, prof->stat_buffers);
3687                         if (thread)
3688                                 mono_thread_detach (thread);
3689                         if (do_debug)
3690                                 fprintf (stderr, "helper shutdown\n");
3691 #if USE_PERF_EVENTS
3692                         if (perf_data) {
3693                                 int i;
3694                                 for ( i = 0; i < num_perf; ++i) {
3695                                         if (perf_data [i].perf_fd < 0)
3696                                                 continue;
3697                                         if (FD_ISSET (perf_data [i].perf_fd, &rfds))
3698                                                 read_perf_mmap (prof, i);
3699                                 }
3700                         }
3701 #endif
3702                         safe_send (prof, ensure_logbuf (0));
3703                         return NULL;
3704                 }
3705 #if USE_PERF_EVENTS
3706                 if (perf_data) {
3707                         int i;
3708                         for ( i = 0; i < num_perf; ++i) {
3709                                 if (perf_data [i].perf_fd < 0)
3710                                         continue;
3711                                 if (FD_ISSET (perf_data [i].perf_fd, &rfds)) {
3712                                         read_perf_mmap (prof, i);
3713                                         safe_send (prof, ensure_logbuf (0));
3714                                 }
3715                         }
3716                 }
3717 #endif
3718                 if (command_socket >= 0 && FD_ISSET (command_socket, &rfds)) {
3719                         len = read (command_socket, buf, sizeof (buf) - 1);
3720                         if (len < 0)
3721                                 continue;
3722                         if (len == 0) {
3723                                 close (command_socket);
3724                                 command_socket = -1;
3725                                 continue;
3726                         }
3727                         buf [len] = 0;
3728                         if (strcmp (buf, "heapshot\n") == 0) {
3729                                 heapshot_requested = 1;
3730                                 //fprintf (stderr, "perform heapshot\n");
3731                                 if (InterlockedRead (&runtime_inited) && !thread) {
3732                                         thread = mono_thread_attach (mono_get_root_domain ());
3733                                         /*fprintf (stderr, "attached\n");*/
3734                                 }
3735                                 if (thread) {
3736                                         process_requests (prof);
3737                                         mono_thread_detach (thread);
3738                                         thread = NULL;
3739                                 }
3740                         }
3741                         continue;
3742                 }
3743                 if (!FD_ISSET (prof->server_socket, &rfds)) {
3744                         continue;
3745                 }
3746                 command_socket = accept (prof->server_socket, NULL, NULL);
3747                 if (command_socket < 0)
3748                         continue;
3749                 //fprintf (stderr, "Accepted connection\n");
3750         }
3751         return NULL;
3752 }
3753
3754 static int
3755 start_helper_thread (MonoProfiler* prof)
3756 {
3757         struct sockaddr_in server_address;
3758         int r;
3759         socklen_t slen;
3760         if (pipe (prof->pipes) < 0) {
3761                 fprintf (stderr, "Cannot create pipe\n");
3762                 return 0;
3763         }
3764         prof->server_socket = socket (PF_INET, SOCK_STREAM, 0);
3765         if (prof->server_socket < 0) {
3766                 fprintf (stderr, "Cannot create server socket\n");
3767                 return 0;
3768         }
3769         memset (&server_address, 0, sizeof (server_address));
3770         server_address.sin_family = AF_INET;
3771         server_address.sin_addr.s_addr = INADDR_ANY;
3772         server_address.sin_port = htons (prof->command_port);
3773         if (bind (prof->server_socket, (struct sockaddr *) &server_address, sizeof (server_address)) < 0) {
3774                 fprintf (stderr, "Cannot bind server socket, port: %d: %s\n", prof->command_port, strerror (errno));
3775                 close (prof->server_socket);
3776                 return 0;
3777         }
3778         if (listen (prof->server_socket, 1) < 0) {
3779                 fprintf (stderr, "Cannot listen server socket\n");
3780                 close (prof->server_socket);
3781                 return 0;
3782         }
3783         slen = sizeof (server_address);
3784         if (getsockname (prof->server_socket, (struct sockaddr *)&server_address, &slen) == 0) {
3785                 prof->command_port = ntohs (server_address.sin_port);
3786                 /*fprintf (stderr, "Assigned server port: %d\n", prof->command_port);*/
3787         }
3788
3789         r = pthread_create (&prof->helper_thread, NULL, helper_thread, prof);
3790         if (r) {
3791                 close (prof->server_socket);
3792                 return 0;
3793         }
3794         return 1;
3795 }
3796 #endif
3797
3798 static void *
3799 writer_thread (void *arg)
3800 {
3801         MonoProfiler *prof = arg;
3802
3803         mono_threads_attach_tools_thread ();
3804
3805         dump_header (prof);
3806
3807         while (InterlockedRead (&prof->run_writer_thread)) {
3808                 WriterQueueEntry *entry;
3809
3810                 while ((entry = (WriterQueueEntry *) mono_lock_free_queue_dequeue (&prof->writer_queue))) {
3811                         LogBuffer *method_buffer = NULL;
3812                         gboolean new_methods = FALSE;
3813
3814                         if (entry->methods->len)
3815                                 method_buffer = create_buffer ();
3816
3817                         /*
3818                          * Encode the method events in a temporary log buffer that we
3819                          * flush to disk before the main buffer, ensuring that all
3820                          * methods have metadata emitted before they're referenced.
3821                          */
3822                         for (guint i = 0; i < entry->methods->len; i++) {
3823                                 MethodInfo *info = g_ptr_array_index (entry->methods, i);
3824
3825                                 if (mono_conc_hashtable_lookup (prof->method_table, info->method))
3826                                         continue;
3827
3828                                 new_methods = TRUE;
3829
3830                                 /*
3831                                  * Other threads use this hash table to get a general
3832                                  * idea of whether a method has already been emitted to
3833                                  * the stream. Due to the way we add to this table, it
3834                                  * can easily happen that multiple threads queue up the
3835                                  * same methods, but that's OK since eventually all
3836                                  * methods will be in this table and the thread-local
3837                                  * method lists will just be empty for the rest of the
3838                                  * app's lifetime.
3839                                  */
3840                                 mono_conc_hashtable_insert (prof->method_table, info->method, info->method);
3841
3842                                 char *name = mono_method_full_name (info->method, 1);
3843                                 int nlen = strlen (name) + 1;
3844                                 uint64_t now = current_time ();
3845
3846                                 method_buffer = ensure_logbuf_inner (method_buffer, 1 + 10 + 10 + 10 + 10 + nlen);
3847
3848                                 emit_byte (method_buffer, TYPE_JIT | TYPE_METHOD);
3849                                 emit_time (method_buffer, now);
3850                                 emit_method_inner (method_buffer, info->method);
3851                                 emit_ptr (method_buffer, mono_jit_info_get_code_start (info->ji));
3852                                 emit_value (method_buffer, mono_jit_info_get_code_size (info->ji));
3853
3854                                 memcpy (method_buffer->data, name, nlen);
3855                                 method_buffer->data += nlen;
3856
3857                                 mono_free (name);
3858                                 free (info);
3859                         }
3860
3861                         g_ptr_array_free (entry->methods, TRUE);
3862
3863                         if (new_methods)
3864                                 dump_buffer (prof, method_buffer);
3865                         else if (method_buffer)
3866                                 free_buffer (method_buffer, method_buffer->size);
3867
3868                         dump_buffer (prof, entry->buffer);
3869
3870                         free (entry);
3871                 }
3872         }
3873
3874         return NULL;
3875 }
3876
3877 static int
3878 start_writer_thread (MonoProfiler* prof)
3879 {
3880         InterlockedWrite (&prof->run_writer_thread, 1);
3881
3882         return !pthread_create (&prof->writer_thread, NULL, writer_thread, prof);
3883 }
3884
3885 static void
3886 runtime_initialized (MonoProfiler *profiler)
3887 {
3888 #ifndef DISABLE_HELPER_THREAD
3889         if (hs_mode_ondemand || need_helper_thread) {
3890                 if (!start_helper_thread (profiler))
3891                         profiler->command_port = 0;
3892         }
3893 #endif
3894
3895         start_writer_thread (profiler);
3896
3897         InterlockedWrite (&runtime_inited, 1);
3898 #ifndef DISABLE_HELPER_THREAD
3899         counters_init (profiler);
3900         counters_sample (profiler, 0);
3901 #endif
3902         /* ensure the main thread data and startup are available soon */
3903         safe_send (profiler, ensure_logbuf (0));
3904 }
3905
3906 static MonoProfiler*
3907 create_profiler (const char *filename, GPtrArray *filters)
3908 {
3909         MonoProfiler *prof;
3910         char *nf;
3911         int force_delete = 0;
3912         prof = calloc (1, sizeof (MonoProfiler));
3913
3914         prof->command_port = command_port;
3915         if (filename && *filename == '-') {
3916                 force_delete = 1;
3917                 filename++;
3918         }
3919         if (!filename) {
3920                 if (do_report)
3921                         filename = "|mprof-report -";
3922                 else
3923                         filename = "output.mlpd";
3924                 nf = (char*)filename;
3925         } else {
3926                 nf = new_filename (filename);
3927                 if (do_report) {
3928                         int s = strlen (nf) + 32;
3929                         char *p = malloc (s);
3930                         snprintf (p, s, "|mprof-report '--out=%s' -", nf);
3931                         free (nf);
3932                         nf = p;
3933                 }
3934         }
3935         if (*nf == '|') {
3936                 prof->file = popen (nf + 1, "w");
3937                 prof->pipe_output = 1;
3938         } else if (*nf == '#') {
3939                 int fd = strtol (nf + 1, NULL, 10);
3940                 prof->file = fdopen (fd, "a");
3941         } else {
3942                 if (force_delete)
3943                         unlink (nf);
3944                 prof->file = fopen (nf, "wb");
3945         }
3946         if (!prof->file) {
3947                 fprintf (stderr, "Cannot create profiler output: %s\n", nf);
3948                 exit (1);
3949         }
3950 #if defined (HAVE_SYS_ZLIB)
3951         if (use_zip)
3952                 prof->gzfile = gzdopen (fileno (prof->file), "wb");
3953 #endif
3954 #if USE_PERF_EVENTS
3955         if (sample_type && !do_mono_sample)
3956                 need_helper_thread = setup_perf_event ();
3957         if (!perf_data) {
3958                 /* FIXME: warn if different freq or sample type */
3959                 do_mono_sample = 1;
3960         }
3961 #endif
3962         if (do_mono_sample) {
3963                 prof->stat_buffers = create_stat_buffer ();
3964                 need_helper_thread = 1;
3965         }
3966         if (do_counters && !need_helper_thread) {
3967                 need_helper_thread = 1;
3968         }
3969
3970         prof->sorted_sample_events = g_ptr_array_sized_new (BUFFER_SIZE / SAMPLE_EVENT_SIZE_IN_SLOTS (0));
3971
3972 #ifdef DISABLE_HELPER_THREAD
3973         if (hs_mode_ondemand)
3974                 fprintf (stderr, "Ondemand heapshot unavailable on this arch.\n");
3975
3976         if (do_coverage)
3977                 fprintf (stderr, "Coverage unavailable on this arch.\n");
3978
3979 #endif
3980
3981         mono_lock_free_queue_init (&prof->writer_queue);
3982         mono_mutex_init (&prof->method_table_mutex);
3983         prof->method_table = mono_conc_hashtable_new (&prof->method_table_mutex, NULL, NULL);
3984
3985         if (do_coverage)
3986                 coverage_init (prof);
3987         prof->coverage_filters = filters;
3988
3989         prof->startup_time = current_time ();
3990         return prof;
3991 }
3992
3993 static void
3994 usage (int do_exit)
3995 {
3996         printf ("Log profiler version %d.%d (format: %d)\n", LOG_VERSION_MAJOR, LOG_VERSION_MINOR, LOG_DATA_VERSION);
3997         printf ("Usage: mono --profile=log[:OPTION1[,OPTION2...]] program.exe\n");
3998         printf ("Options:\n");
3999         printf ("\thelp                 show this usage info\n");
4000         printf ("\t[no]alloc            enable/disable recording allocation info\n");
4001         printf ("\t[no]calls            enable/disable recording enter/leave method events\n");
4002         printf ("\theapshot[=MODE]      record heap shot info (by default at each major collection)\n");
4003         printf ("\t                     MODE: every XXms milliseconds, every YYgc collections, ondemand\n");
4004         printf ("\tcounters             sample counters every 1s\n");
4005         printf ("\tsample[=TYPE]        use statistical sampling mode (by default cycles/1000)\n");
4006         printf ("\t                     TYPE: cycles,instr,cacherefs,cachemiss,branches,branchmiss\n");
4007         printf ("\t                     TYPE can be followed by /FREQUENCY\n");
4008         printf ("\ttime=fast            use a faster (but more inaccurate) timer\n");
4009         printf ("\tmaxframes=NUM        collect up to NUM stack frames\n");
4010         printf ("\tcalldepth=NUM        ignore method events for call chain depth bigger than NUM\n");
4011         printf ("\toutput=FILENAME      write the data to file FILENAME (-FILENAME to overwrite)\n");
4012         printf ("\toutput=|PROGRAM      write the data to the stdin of PROGRAM\n");
4013         printf ("\t                     %%t is subtituted with date and time, %%p with the pid\n");
4014         printf ("\treport               create a report instead of writing the raw data to a file\n");
4015         printf ("\tzip                  compress the output data\n");
4016         printf ("\tport=PORTNUM         use PORTNUM for the listening command server\n");
4017         printf ("\tcoverage             enable collection of code coverage data\n");
4018         printf ("\tcovfilter=ASSEMBLY   add an assembly to the code coverage filters\n");
4019         printf ("\t                     add a + to include the assembly or a - to exclude it\n");
4020         printf ("\t                     filter=-mscorlib\n");
4021         printf ("\tcovfilter-file=FILE  use FILE to generate the list of assemblies to be filtered\n");
4022         if (do_exit)
4023                 exit (1);
4024 }
4025
4026 static const char*
4027 match_option (const char* p, const char *opt, char **rval)
4028 {
4029         int len = strlen (opt);
4030         if (strncmp (p, opt, len) == 0) {
4031                 if (rval) {
4032                         if (p [len] == '=' && p [len + 1]) {
4033                                 const char *opt = p + len + 1;
4034                                 const char *end = strchr (opt, ',');
4035                                 char *val;
4036                                 int l;
4037                                 if (end == NULL) {
4038                                         l = strlen (opt);
4039                                 } else {
4040                                         l = end - opt;
4041                                 }
4042                                 val = malloc (l + 1);
4043                                 memcpy (val, opt, l);
4044                                 val [l] = 0;
4045                                 *rval = val;
4046                                 return opt + l;
4047                         }
4048                         if (p [len] == 0 || p [len] == ',') {
4049                                 *rval = NULL;
4050                                 return p + len + (p [len] == ',');
4051                         }
4052                         usage (1);
4053                 } else {
4054                         if (p [len] == 0)
4055                                 return p + len;
4056                         if (p [len] == ',')
4057                                 return p + len + 1;
4058                 }
4059         }
4060         return p;
4061 }
4062
4063 typedef struct {
4064         const char *name;
4065         int sample_mode;
4066 } SampleMode;
4067
4068 static const SampleMode sample_modes [] = {
4069         {"cycles", SAMPLE_CYCLES},
4070         {"instr", SAMPLE_INSTRUCTIONS},
4071         {"cachemiss", SAMPLE_CACHE_MISSES},
4072         {"cacherefs", SAMPLE_CACHE_REFS},
4073         {"branches", SAMPLE_BRANCHES},
4074         {"branchmiss", SAMPLE_BRANCH_MISSES},
4075         {NULL, 0}
4076 };
4077
4078 static void
4079 set_sample_mode (char* val, int allow_empty)
4080 {
4081         char *end;
4082         char *maybe_freq = NULL;
4083         unsigned int count;
4084         const SampleMode *smode = sample_modes;
4085 #ifndef USE_PERF_EVENTS
4086         do_mono_sample = 1;
4087 #endif
4088         if (allow_empty && !val) {
4089                 sample_type = SAMPLE_CYCLES;
4090                 sample_freq = 1000;
4091                 return;
4092         }
4093         if (strcmp (val, "mono") == 0) {
4094                 do_mono_sample = 1;
4095                 sample_type = SAMPLE_CYCLES;
4096                 free (val);
4097                 return;
4098         }
4099         for (smode = sample_modes; smode->name; smode++) {
4100                 int l = strlen (smode->name);
4101                 if (strncmp (val, smode->name, l) == 0) {
4102                         sample_type = smode->sample_mode;
4103                         maybe_freq = val + l;
4104                         break;
4105                 }
4106         }
4107         if (!smode->name)
4108                 usage (1);
4109         if (*maybe_freq == '/') {
4110                 count = strtoul (maybe_freq + 1, &end, 10);
4111                 if (maybe_freq + 1 == end)
4112                         usage (1);
4113                 sample_freq = count;
4114         } else if (*maybe_freq != 0) {
4115                 usage (1);
4116         } else {
4117                 sample_freq = 1000;
4118         }
4119         free (val);
4120 }
4121
4122 static void
4123 set_hsmode (char* val, int allow_empty)
4124 {
4125         char *end;
4126         unsigned int count;
4127         if (allow_empty && !val)
4128                 return;
4129         if (strcmp (val, "ondemand") == 0) {
4130                 hs_mode_ondemand = 1;
4131                 free (val);
4132                 return;
4133         }
4134         count = strtoul (val, &end, 10);
4135         if (val == end)
4136                 usage (1);
4137         if (strcmp (end, "ms") == 0)
4138                 hs_mode_ms = count;
4139         else if (strcmp (end, "gc") == 0)
4140                 hs_mode_gc = count;
4141         else
4142                 usage (1);
4143         free (val);
4144 }
4145
4146 /*
4147  * declaration to silence the compiler: this is the entry point that
4148  * mono will load from the shared library and call.
4149  */
4150 extern void
4151 mono_profiler_startup (const char *desc);
4152
4153 extern void
4154 mono_profiler_startup_log (const char *desc);
4155
4156 /*
4157  * this is the entry point that will be used when the profiler
4158  * is embedded inside the main executable.
4159  */
4160 void
4161 mono_profiler_startup_log (const char *desc)
4162 {
4163         mono_profiler_startup (desc);
4164 }
4165
4166 void
4167 mono_profiler_startup (const char *desc)
4168 {
4169         MonoProfiler *prof;
4170         GPtrArray *filters = NULL;
4171         char *filename = NULL;
4172         const char *p;
4173         const char *opt;
4174         int fast_time = 0;
4175         int calls_enabled = 0;
4176         int allocs_enabled = 0;
4177         int only_counters = 0;
4178         int only_coverage = 0;
4179         int events = MONO_PROFILE_GC|MONO_PROFILE_ALLOCATIONS|
4180                 MONO_PROFILE_GC_MOVES|MONO_PROFILE_CLASS_EVENTS|MONO_PROFILE_THREADS|
4181                 MONO_PROFILE_ENTER_LEAVE|MONO_PROFILE_JIT_COMPILATION|MONO_PROFILE_EXCEPTIONS|
4182                 MONO_PROFILE_MONITOR_EVENTS|MONO_PROFILE_MODULE_EVENTS|MONO_PROFILE_GC_ROOTS|
4183                 MONO_PROFILE_INS_COVERAGE|MONO_PROFILE_APPDOMAIN_EVENTS|MONO_PROFILE_CONTEXT_EVENTS|
4184                 MONO_PROFILE_ASSEMBLY_EVENTS;
4185
4186         p = desc;
4187         if (strncmp (p, "log", 3))
4188                 usage (1);
4189         p += 3;
4190         if (*p == ':')
4191                 p++;
4192         for (; *p; p = opt) {
4193                 char *val;
4194                 if (*p == ',') {
4195                         opt = p + 1;
4196                         continue;
4197                 }
4198                 if ((opt = match_option (p, "help", NULL)) != p) {
4199                         usage (0);
4200                         continue;
4201                 }
4202                 if ((opt = match_option (p, "calls", NULL)) != p) {
4203                         calls_enabled = 1;
4204                         continue;
4205                 }
4206                 if ((opt = match_option (p, "nocalls", NULL)) != p) {
4207                         events &= ~MONO_PROFILE_ENTER_LEAVE;
4208                         nocalls = 1;
4209                         continue;
4210                 }
4211                 if ((opt = match_option (p, "alloc", NULL)) != p) {
4212                         allocs_enabled = 1;
4213                         continue;
4214                 }
4215                 if ((opt = match_option (p, "noalloc", NULL)) != p) {
4216                         events &= ~MONO_PROFILE_ALLOCATIONS;
4217                         continue;
4218                 }
4219                 if ((opt = match_option (p, "time", &val)) != p) {
4220                         if (strcmp (val, "fast") == 0)
4221                                 fast_time = 1;
4222                         else if (strcmp (val, "null") == 0)
4223                                 fast_time = 2;
4224                         else
4225                                 usage (1);
4226                         free (val);
4227                         continue;
4228                 }
4229                 if ((opt = match_option (p, "report", NULL)) != p) {
4230                         do_report = 1;
4231                         continue;
4232                 }
4233                 if ((opt = match_option (p, "debug", NULL)) != p) {
4234                         do_debug = 1;
4235                         continue;
4236                 }
4237                 if ((opt = match_option (p, "sampling-real", NULL)) != p) {
4238                         sampling_mode = MONO_PROFILER_STAT_MODE_REAL;
4239                         continue;
4240                 }
4241                 if ((opt = match_option (p, "sampling-process", NULL)) != p) {
4242                         sampling_mode = MONO_PROFILER_STAT_MODE_PROCESS;
4243                         continue;
4244                 }
4245                 if ((opt = match_option (p, "heapshot", &val)) != p) {
4246                         events &= ~MONO_PROFILE_ALLOCATIONS;
4247                         events &= ~MONO_PROFILE_ENTER_LEAVE;
4248                         nocalls = 1;
4249                         do_heap_shot = 1;
4250                         set_hsmode (val, 1);
4251                         continue;
4252                 }
4253                 if ((opt = match_option (p, "sample", &val)) != p) {
4254                         events &= ~MONO_PROFILE_ALLOCATIONS;
4255                         events &= ~MONO_PROFILE_ENTER_LEAVE;
4256                         nocalls = 1;
4257                         set_sample_mode (val, 1);
4258                         continue;
4259                 }
4260                 if ((opt = match_option (p, "hsmode", &val)) != p) {
4261                         fprintf (stderr, "The hsmode profiler option is obsolete, use heapshot=MODE.\n");
4262                         set_hsmode (val, 0);
4263                         continue;
4264                 }
4265                 if ((opt = match_option (p, "zip", NULL)) != p) {
4266                         use_zip = 1;
4267                         continue;
4268                 }
4269                 if ((opt = match_option (p, "output", &val)) != p) {
4270                         filename = val;
4271                         continue;
4272                 }
4273                 if ((opt = match_option (p, "port", &val)) != p) {
4274                         char *end;
4275                         command_port = strtoul (val, &end, 10);
4276                         free (val);
4277                         continue;
4278                 }
4279                 if ((opt = match_option (p, "maxframes", &val)) != p) {
4280                         char *end;
4281                         num_frames = strtoul (val, &end, 10);
4282                         if (num_frames > MAX_FRAMES)
4283                                 num_frames = MAX_FRAMES;
4284                         free (val);
4285                         notraces = num_frames == 0;
4286                         continue;
4287                 }
4288                 if ((opt = match_option (p, "calldepth", &val)) != p) {
4289                         char *end;
4290                         max_call_depth = strtoul (val, &end, 10);
4291                         free (val);
4292                         continue;
4293                 }
4294                 if ((opt = match_option (p, "counters", NULL)) != p) {
4295                         do_counters = 1;
4296                         continue;
4297                 }
4298                 if ((opt = match_option (p, "countersonly", NULL)) != p) {
4299                         only_counters = 1;
4300                         continue;
4301                 }
4302                 if ((opt = match_option (p, "coverage", NULL)) != p) {
4303                         do_coverage = 1;
4304                         events |= MONO_PROFILE_ENTER_LEAVE;
4305                         debug_coverage = (g_getenv ("MONO_PROFILER_DEBUG_COVERAGE") != NULL);
4306                         continue;
4307                 }
4308                 if ((opt = match_option (p, "onlycoverage", NULL)) != p) {
4309                         only_coverage = 1;
4310                         continue;
4311                 }
4312                 if ((opt = match_option (p, "covfilter-file", &val)) != p) {
4313                         FILE *filter_file;
4314                         char *line, *content;
4315
4316                         if (filters == NULL)
4317                                 filters = g_ptr_array_new ();
4318
4319                         filter_file = fopen (val, "r");
4320                         if (filter_file == NULL) {
4321                                 fprintf (stderr, "Unable to open %s\n", val);
4322                                 exit (0);
4323                         }
4324
4325                         /* Don't need to free content as it is referred to by the lines stored in @filters */
4326                         content = get_file_content (filter_file);
4327                         if (content == NULL)
4328                                 fprintf (stderr, "WARNING: %s is greater than 128kb - ignoring\n", val);
4329
4330                         while ((line = get_next_line (content, &content)))
4331                                 g_ptr_array_add (filters, g_strchug (g_strchomp (line)));
4332
4333                         fclose (filter_file);
4334                         continue;
4335                 }
4336                 if ((opt = match_option (p, "covfilter", &val)) != p) {
4337                         if (filters == NULL)
4338                                 filters = g_ptr_array_new ();
4339
4340                         g_ptr_array_add (filters, val);
4341                         continue;
4342                 }
4343                 if (opt == p) {
4344                         usage (0);
4345                         exit (0);
4346                 }
4347         }
4348         if (calls_enabled) {
4349                 events |= MONO_PROFILE_ENTER_LEAVE;
4350                 nocalls = 0;
4351         }
4352         if (allocs_enabled)
4353                 events |= MONO_PROFILE_ALLOCATIONS;
4354         if (only_counters)
4355                 events = 0;
4356         if (only_coverage)
4357                 events = MONO_PROFILE_ENTER_LEAVE | MONO_PROFILE_INS_COVERAGE;
4358
4359         utils_init (fast_time);
4360
4361         prof = create_profiler (filename, filters);
4362         if (!prof)
4363                 return;
4364         init_thread ();
4365
4366         mono_profiler_install (prof, log_shutdown);
4367         mono_profiler_install_gc (gc_event, gc_resize);
4368         mono_profiler_install_allocation (gc_alloc);
4369         mono_profiler_install_gc_moves (gc_moves);
4370         mono_profiler_install_gc_roots (gc_handle, gc_roots);
4371         mono_profiler_install_appdomain (NULL, domain_loaded, NULL, domain_unloaded);
4372         mono_profiler_install_appdomain_name (domain_name);
4373         mono_profiler_install_context (context_loaded, context_unloaded);
4374         mono_profiler_install_class (NULL, class_loaded, NULL, class_unloaded);
4375         mono_profiler_install_module (NULL, image_loaded, NULL, image_unloaded);
4376         mono_profiler_install_assembly (NULL, assembly_loaded, NULL, assembly_unloaded);
4377         mono_profiler_install_thread (thread_start, thread_end);
4378         mono_profiler_install_thread_name (thread_name);
4379         mono_profiler_install_enter_leave (method_enter, method_leave);
4380         mono_profiler_install_jit_end (method_jitted);
4381         mono_profiler_install_code_buffer_new (code_buffer_new);
4382         mono_profiler_install_exception (throw_exc, method_exc_leave, clause_exc);
4383         mono_profiler_install_monitor (monitor_event);
4384         mono_profiler_install_runtime_initialized (runtime_initialized);
4385         if (do_coverage)
4386                 mono_profiler_install_coverage_filter (coverage_filter);
4387
4388         if (do_mono_sample && sample_type == SAMPLE_CYCLES && !only_counters) {
4389                 events |= MONO_PROFILE_STATISTICAL;
4390                 mono_profiler_set_statistical_mode (sampling_mode, 1000000 / sample_freq);
4391                 mono_profiler_install_statistical (mono_sample_hit);
4392         }
4393
4394         mono_profiler_set_events (events);
4395
4396         TLS_INIT (tlsbuffer);
4397         TLS_INIT (tlsmethodlist);
4398 }