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