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