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