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