Merge pull request #2634 from ludovic-henry/coop-fix-managed-to-native
[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         int count = 0;
2500 #ifdef PLATFORM_ANDROID
2501         /* Android tries really hard to save power by powering off CPUs on SMP phones which
2502          * means the normal way to query cpu count returns a wrong value with userspace API.
2503          * Instead we use /sys entries to query the actual hardware CPU count.
2504          */
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 #ifdef HAVE_SCHED_GETAFFINITY
2520         {
2521                 cpu_set_t set;
2522                 if (sched_getaffinity (getpid (), sizeof (set), &set) == 0)
2523                         return CPU_COUNT (&set);
2524         }
2525 #endif
2526 #ifdef _SC_NPROCESSORS_ONLN
2527         count = sysconf (_SC_NPROCESSORS_ONLN);
2528         if (count > 0)
2529                 return count;
2530 #endif
2531 #ifdef USE_SYSCTL
2532         {
2533                 int mib [2];
2534                 size_t len = sizeof (int);
2535                 mib [0] = CTL_HW;
2536                 mib [1] = HW_NCPU;
2537                 if (sysctl (mib, 2, &count, &len, NULL, 0) == 0)
2538                         return count;
2539         }
2540 #endif
2541 #ifdef HOST_WIN32
2542         {
2543                 SYSTEM_INFO info;
2544                 GetSystemInfo (&info);
2545                 return info.dwNumberOfProcessors;
2546         }
2547 #endif
2548         /* FIXME: warn */
2549         return 1;
2550 }
2551
2552 typedef struct {
2553         int perf_fd;
2554         unsigned int prev_pos;
2555         void *mmap_base;
2556         struct perf_event_mmap_page *page_desc;
2557 } PerfData ;
2558
2559 static PerfData *perf_data = NULL;
2560 static int num_perf;
2561 #define PERF_PAGES_SHIFT 4
2562 static int num_pages = 1 << PERF_PAGES_SHIFT;
2563 static unsigned int mmap_mask;
2564
2565 typedef struct {
2566         struct perf_event_header h;
2567         uint64_t ip;
2568         uint32_t pid;
2569         uint32_t tid;
2570         uint64_t timestamp;
2571         uint64_t period;
2572         uint64_t nframes;
2573 } PSample;
2574
2575 static int
2576 perf_event_syscall (struct perf_event_attr *attr, pid_t pid, int cpu, int group_fd, unsigned long flags)
2577 {
2578         attr->size = PERF_ATTR_SIZE_VER0;
2579         //printf ("perf attr size: %d\n", attr->size);
2580 #if defined(__x86_64__)
2581         return syscall(/*__NR_perf_event_open*/ 298, attr, pid, cpu, group_fd, flags);
2582 #elif defined(__i386__)
2583         return syscall(/*__NR_perf_event_open*/ 336, attr, pid, cpu, group_fd, flags);
2584 #elif defined(__arm__) || defined (__aarch64__)
2585         return syscall(/*__NR_perf_event_open*/ 364, attr, pid, cpu, group_fd, flags);
2586 #else
2587         return -1;
2588 #endif
2589 }
2590
2591 static int
2592 setup_perf_map (PerfData *perf)
2593 {
2594         perf->mmap_base = mmap (NULL, (num_pages + 1) * getpagesize (), PROT_READ|PROT_WRITE, MAP_SHARED, perf->perf_fd, 0);
2595         if (perf->mmap_base == MAP_FAILED) {
2596                 if (do_debug)
2597                         printf ("failed mmap\n");
2598                 return 0;
2599         }
2600         perf->page_desc = perf->mmap_base;
2601         if (do_debug)
2602                 printf ("mmap version: %d\n", perf->page_desc->version);
2603         return 1;
2604 }
2605
2606 static void
2607 dump_perf_hits (MonoProfiler *prof, void *buf, int size)
2608 {
2609         LogBuffer *logbuffer;
2610         int count = 1;
2611         int mbt_count = 0;
2612         void *end = (char*)buf + size;
2613         int samples = 0;
2614         int pid = getpid ();
2615
2616         while (buf < end) {
2617                 PSample *s = buf;
2618                 if (s->h.size == 0)
2619                         break;
2620                 if (pid != s->pid) {
2621                         if (do_debug)
2622                                 printf ("event for different pid: %d\n", s->pid);
2623                         buf = (char*)buf + s->h.size;
2624                         continue;
2625                 }
2626                 /*ip = (void*)s->ip;
2627                 printf ("sample: %d, size: %d, ip: %p (%s), timestamp: %llu, nframes: %llu\n",
2628                         s->h.type, s->h.size, ip, symbol_for (ip), s->timestamp, s->nframes);*/
2629                 logbuffer = ensure_logbuf (
2630                         EVENT_SIZE /* event */ +
2631                         LEB128_SIZE /* type */ +
2632                         LEB128_SIZE /* time */ +
2633                         LEB128_SIZE /* tid */ +
2634                         LEB128_SIZE /* count */ +
2635                         count * (
2636                                 LEB128_SIZE /* ip */
2637                         ) +
2638                         LEB128_SIZE /* managed count */ +
2639                         mbt_count * (
2640                                 LEB128_SIZE /* method */ +
2641                                 LEB128_SIZE /* il offset */ +
2642                                 LEB128_SIZE /* native offset */
2643                         )
2644                 );
2645                 emit_byte (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_HIT);
2646                 emit_value (logbuffer, sample_type);
2647                 emit_uvalue (logbuffer, s->timestamp - prof->startup_time);
2648                 /*
2649                  * No useful thread ID to write here, since throughout the
2650                  * profiler we use pthread_self () but the ID we get from
2651                  * perf is the kernel's thread ID.
2652                  */
2653                 emit_ptr (logbuffer, 0);
2654                 emit_value (logbuffer, count);
2655                 emit_ptr (logbuffer, (void*)(uintptr_t)s->ip);
2656                 add_code_pointer (s->ip);
2657                 /* no support here yet for the managed backtrace */
2658                 emit_uvalue (logbuffer, mbt_count);
2659                 buf = (char*)buf + s->h.size;
2660                 samples++;
2661         }
2662         if (do_debug)
2663                 printf ("dumped %d samples\n", samples);
2664         dump_unmanaged_coderefs (prof);
2665 }
2666
2667 /* read events from the ring buffer */
2668 static int
2669 read_perf_mmap (MonoProfiler* prof, int cpu)
2670 {
2671         PerfData *perf = perf_data + cpu;
2672         unsigned char *buf;
2673         unsigned char *data = (unsigned char*)perf->mmap_base + getpagesize ();
2674         unsigned int head = perf->page_desc->data_head;
2675         int diff, size;
2676         unsigned int old;
2677
2678         mono_memory_read_barrier ();
2679
2680         old = perf->prev_pos;
2681         diff = head - old;
2682         if (diff < 0) {
2683                 if (do_debug)
2684                         printf ("lost mmap events: old: %d, head: %d\n", old, head);
2685                 old = head;
2686         }
2687         size = head - old;
2688         if ((old & mmap_mask) + size != (head & mmap_mask)) {
2689                 buf = data + (old & mmap_mask);
2690                 size = mmap_mask + 1 - (old & mmap_mask);
2691                 old += size;
2692                 /* size bytes at buf */
2693                 if (do_debug)
2694                         printf ("found1 bytes of events: %d\n", size);
2695                 dump_perf_hits (prof, buf, size);
2696         }
2697         buf = data + (old & mmap_mask);
2698         size = head - old;
2699         /* size bytes at buf */
2700         if (do_debug)
2701                 printf ("found bytes of events: %d\n", size);
2702         dump_perf_hits (prof, buf, size);
2703         old += size;
2704         perf->prev_pos = old;
2705         perf->page_desc->data_tail = old;
2706         return 0;
2707 }
2708
2709 static int
2710 setup_perf_event_for_cpu (PerfData *perf, int cpu)
2711 {
2712         struct perf_event_attr attr;
2713         memset (&attr, 0, sizeof (attr));
2714         attr.type = PERF_TYPE_HARDWARE;
2715         switch (sample_type) {
2716         case SAMPLE_CYCLES: attr.config = PERF_COUNT_HW_CPU_CYCLES; break;
2717         case SAMPLE_INSTRUCTIONS: attr.config = PERF_COUNT_HW_INSTRUCTIONS; break;
2718         case SAMPLE_CACHE_MISSES: attr.config = PERF_COUNT_HW_CACHE_MISSES; break;
2719         case SAMPLE_CACHE_REFS: attr.config = PERF_COUNT_HW_CACHE_REFERENCES; break;
2720         case SAMPLE_BRANCHES: attr.config = PERF_COUNT_HW_BRANCH_INSTRUCTIONS; break;
2721         case SAMPLE_BRANCH_MISSES: attr.config = PERF_COUNT_HW_BRANCH_MISSES; break;
2722         default: attr.config = PERF_COUNT_HW_CPU_CYCLES; break;
2723         }
2724         attr.sample_type = PERF_SAMPLE_IP | PERF_SAMPLE_TID | PERF_SAMPLE_PERIOD | PERF_SAMPLE_TIME;
2725 //      attr.sample_type |= PERF_SAMPLE_CALLCHAIN;
2726         attr.read_format = PERF_FORMAT_TOTAL_TIME_ENABLED | PERF_FORMAT_TOTAL_TIME_RUNNING | PERF_FORMAT_ID;
2727         attr.inherit = 1;
2728         attr.freq = 1;
2729         attr.sample_freq = sample_freq;
2730
2731         perf->perf_fd = perf_event_syscall (&attr, getpid (), cpu, -1, 0);
2732         if (do_debug)
2733                 printf ("perf fd: %d, freq: %d, event: %llu\n", perf->perf_fd, sample_freq, attr.config);
2734         if (perf->perf_fd < 0) {
2735                 if (perf->perf_fd == -EPERM) {
2736                         fprintf (stderr, "Perf syscall denied, do \"echo 1 > /proc/sys/kernel/perf_event_paranoid\" as root to enable.\n");
2737                 } else {
2738                         if (do_debug)
2739                                 perror ("open perf event");
2740                 }
2741                 return 0;
2742         }
2743         if (!setup_perf_map (perf)) {
2744                 close (perf->perf_fd);
2745                 perf->perf_fd = -1;
2746                 return 0;
2747         }
2748         return 1;
2749 }
2750
2751 static int
2752 setup_perf_event (void)
2753 {
2754         int i, count = 0;
2755         mmap_mask = num_pages * getpagesize () - 1;
2756         num_perf = mono_cpu_count ();
2757         perf_data = calloc (num_perf, sizeof (PerfData));
2758         for (i = 0; i < num_perf; ++i) {
2759                 count += setup_perf_event_for_cpu (perf_data + i, i);
2760         }
2761         if (count)
2762                 return 1;
2763         free (perf_data);
2764         perf_data = NULL;
2765         return 0;
2766 }
2767
2768 #endif /* USE_PERF_EVENTS */
2769
2770 #ifndef DISABLE_HELPER_THREAD
2771
2772 typedef struct MonoCounterAgent {
2773         MonoCounter *counter;
2774         // MonoCounterAgent specific data :
2775         void *value;
2776         size_t value_size;
2777         short index;
2778         short emitted;
2779         struct MonoCounterAgent *next;
2780 } MonoCounterAgent;
2781
2782 static MonoCounterAgent* counters;
2783 static gboolean counters_initialized = FALSE;
2784 static int counters_index = 1;
2785 static mono_mutex_t counters_mutex;
2786
2787 static void
2788 counters_add_agent (MonoCounter *counter)
2789 {
2790         MonoCounterAgent *agent, *item;
2791
2792         if (!counters_initialized)
2793                 return;
2794
2795         mono_os_mutex_lock (&counters_mutex);
2796
2797         for (agent = counters; agent; agent = agent->next) {
2798                 if (agent->counter == counter) {
2799                         agent->value_size = 0;
2800                         if (agent->value) {
2801                                 free (agent->value);
2802                                 agent->value = NULL;
2803                         }
2804                         mono_os_mutex_unlock (&counters_mutex);
2805                         return;
2806                 }
2807         }
2808
2809         agent = (MonoCounterAgent *)malloc (sizeof (MonoCounterAgent));
2810         agent->counter = counter;
2811         agent->value = NULL;
2812         agent->value_size = 0;
2813         agent->index = counters_index++;
2814         agent->emitted = 0;
2815         agent->next = NULL;
2816
2817         if (!counters) {
2818                 counters = agent;
2819         } else {
2820                 item = counters;
2821                 while (item->next)
2822                         item = item->next;
2823                 item->next = agent;
2824         }
2825
2826         mono_os_mutex_unlock (&counters_mutex);
2827 }
2828
2829 static mono_bool
2830 counters_init_foreach_callback (MonoCounter *counter, gpointer data)
2831 {
2832         counters_add_agent (counter);
2833         return TRUE;
2834 }
2835
2836 static void
2837 counters_init (MonoProfiler *profiler)
2838 {
2839         assert (!counters_initialized);
2840
2841         mono_os_mutex_init (&counters_mutex);
2842
2843         counters_initialized = TRUE;
2844
2845         mono_counters_on_register (&counters_add_agent);
2846         mono_counters_foreach (counters_init_foreach_callback, NULL);
2847 }
2848
2849 static void
2850 counters_emit (MonoProfiler *profiler)
2851 {
2852         MonoCounterAgent *agent;
2853         LogBuffer *logbuffer;
2854         int len = 0;
2855         int size =
2856                 EVENT_SIZE /* event */ +
2857                 LEB128_SIZE /* len */
2858         ;
2859
2860         if (!counters_initialized)
2861                 return;
2862
2863         mono_os_mutex_lock (&counters_mutex);
2864
2865         for (agent = counters; agent; agent = agent->next) {
2866                 if (agent->emitted)
2867                         continue;
2868
2869                 size +=
2870                         LEB128_SIZE /* section */ +
2871                         strlen (mono_counter_get_name (agent->counter)) + 1 /* name */ +
2872                         LEB128_SIZE /* type */ +
2873                         LEB128_SIZE /* unit */ +
2874                         LEB128_SIZE /* variance */ +
2875                         LEB128_SIZE /* index */
2876                 ;
2877
2878                 len += 1;
2879         }
2880
2881         if (!len) {
2882                 mono_os_mutex_unlock (&counters_mutex);
2883                 return;
2884         }
2885
2886         logbuffer = ensure_logbuf (size);
2887
2888         ENTER_LOG (logbuffer, "counters");
2889         emit_byte (logbuffer, TYPE_SAMPLE_COUNTERS_DESC | TYPE_SAMPLE);
2890         emit_value (logbuffer, len);
2891         for (agent = counters; agent; agent = agent->next) {
2892                 const char *name;
2893
2894                 if (agent->emitted)
2895                         continue;
2896
2897                 name = mono_counter_get_name (agent->counter);
2898                 emit_value (logbuffer, mono_counter_get_section (agent->counter));
2899                 emit_string (logbuffer, name, strlen (name) + 1);
2900                 emit_value (logbuffer, mono_counter_get_type (agent->counter));
2901                 emit_value (logbuffer, mono_counter_get_unit (agent->counter));
2902                 emit_value (logbuffer, mono_counter_get_variance (agent->counter));
2903                 emit_value (logbuffer, agent->index);
2904
2905                 agent->emitted = 1;
2906         }
2907         EXIT_LOG (logbuffer);
2908
2909         safe_send (profiler, logbuffer);
2910
2911         mono_os_mutex_unlock (&counters_mutex);
2912 }
2913
2914 static void
2915 counters_sample (MonoProfiler *profiler, uint64_t timestamp)
2916 {
2917         MonoCounterAgent *agent;
2918         MonoCounter *counter;
2919         LogBuffer *logbuffer;
2920         int type;
2921         int buffer_size;
2922         void *buffer;
2923         int size;
2924
2925         if (!counters_initialized)
2926                 return;
2927
2928         counters_emit (profiler);
2929
2930         buffer_size = 8;
2931         buffer = calloc (1, buffer_size);
2932
2933         mono_os_mutex_lock (&counters_mutex);
2934
2935         size =
2936                 EVENT_SIZE /* event */ +
2937                 LEB128_SIZE /* time */
2938         ;
2939
2940         for (agent = counters; agent; agent = agent->next) {
2941                 size +=
2942                         LEB128_SIZE /* index */ +
2943                         LEB128_SIZE /* type */ +
2944                         mono_counter_get_size (agent->counter) /* value */
2945                 ;
2946         }
2947
2948         size +=
2949                 LEB128_SIZE /* stop marker */
2950         ;
2951
2952         logbuffer = ensure_logbuf (size);
2953
2954         ENTER_LOG (logbuffer, "counters");
2955         emit_byte (logbuffer, TYPE_SAMPLE_COUNTERS | TYPE_SAMPLE);
2956         emit_uvalue (logbuffer, timestamp);
2957         for (agent = counters; agent; agent = agent->next) {
2958                 size_t size;
2959
2960                 counter = agent->counter;
2961
2962                 size = mono_counter_get_size (counter);
2963                 if (size < 0) {
2964                         continue; // FIXME error
2965                 } else if (size > buffer_size) {
2966                         buffer_size = size;
2967                         buffer = realloc (buffer, buffer_size);
2968                 }
2969
2970                 memset (buffer, 0, buffer_size);
2971
2972                 if (mono_counters_sample (counter, buffer, size) < 0)
2973                         continue; // FIXME error
2974
2975                 type = mono_counter_get_type (counter);
2976
2977                 if (!agent->value) {
2978                         agent->value = calloc (1, size);
2979                         agent->value_size = size;
2980                 } else {
2981                         if (type == MONO_COUNTER_STRING) {
2982                                 if (strcmp (agent->value, buffer) == 0)
2983                                         continue;
2984                         } else {
2985                                 if (agent->value_size == size && memcmp (agent->value, buffer, size) == 0)
2986                                         continue;
2987                         }
2988                 }
2989
2990                 emit_uvalue (logbuffer, agent->index);
2991                 emit_uvalue (logbuffer, type);
2992                 switch (type) {
2993                 case MONO_COUNTER_INT:
2994 #if SIZEOF_VOID_P == 4
2995                 case MONO_COUNTER_WORD:
2996 #endif
2997                         emit_svalue (logbuffer, *(int*)buffer - *(int*)agent->value);
2998                         break;
2999                 case MONO_COUNTER_UINT:
3000                         emit_uvalue (logbuffer, *(guint*)buffer - *(guint*)agent->value);
3001                         break;
3002                 case MONO_COUNTER_TIME_INTERVAL:
3003                 case MONO_COUNTER_LONG:
3004 #if SIZEOF_VOID_P == 8
3005                 case MONO_COUNTER_WORD:
3006 #endif
3007                         emit_svalue (logbuffer, *(gint64*)buffer - *(gint64*)agent->value);
3008                         break;
3009                 case MONO_COUNTER_ULONG:
3010                         emit_uvalue (logbuffer, *(guint64*)buffer - *(guint64*)agent->value);
3011                         break;
3012                 case MONO_COUNTER_DOUBLE:
3013                         emit_double (logbuffer, *(double*)buffer);
3014                         break;
3015                 case MONO_COUNTER_STRING:
3016                         if (size == 0) {
3017                                 emit_byte (logbuffer, 0);
3018                         } else {
3019                                 emit_byte (logbuffer, 1);
3020                                 emit_string (logbuffer, (char*)buffer, size);
3021                         }
3022                         break;
3023                 default:
3024                         assert (0);
3025                 }
3026
3027                 if (type == MONO_COUNTER_STRING && size > agent->value_size) {
3028                         agent->value = realloc (agent->value, size);
3029                         agent->value_size = size;
3030                 }
3031
3032                 if (size > 0)
3033                         memcpy (agent->value, buffer, size);
3034         }
3035         free (buffer);
3036
3037         emit_value (logbuffer, 0);
3038         EXIT_LOG (logbuffer);
3039
3040         safe_send (profiler, logbuffer);
3041
3042         mono_os_mutex_unlock (&counters_mutex);
3043 }
3044
3045 typedef struct _PerfCounterAgent PerfCounterAgent;
3046 struct _PerfCounterAgent {
3047         PerfCounterAgent *next;
3048         int index;
3049         char *category_name;
3050         char *name;
3051         int type;
3052         gint64 value;
3053         guint8 emitted;
3054         guint8 updated;
3055         guint8 deleted;
3056 };
3057
3058 static PerfCounterAgent *perfcounters = NULL;
3059
3060 static void
3061 perfcounters_emit (MonoProfiler *profiler)
3062 {
3063         PerfCounterAgent *pcagent;
3064         LogBuffer *logbuffer;
3065         int len = 0;
3066         int size =
3067                 EVENT_SIZE /* event */ +
3068                 LEB128_SIZE /* len */
3069         ;
3070
3071         for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
3072                 if (pcagent->emitted)
3073                         continue;
3074
3075                 size +=
3076                         LEB128_SIZE /* section */ +
3077                         strlen (pcagent->category_name) + 1 /* category name */ +
3078                         strlen (pcagent->name) + 1 /* name */ +
3079                         LEB128_SIZE /* type */ +
3080                         LEB128_SIZE /* unit */ +
3081                         LEB128_SIZE /* variance */ +
3082                         LEB128_SIZE /* index */
3083                 ;
3084
3085                 len += 1;
3086         }
3087
3088         if (!len)
3089                 return;
3090
3091         logbuffer = ensure_logbuf (size);
3092
3093         ENTER_LOG (logbuffer, "perfcounters");
3094         emit_byte (logbuffer, TYPE_SAMPLE_COUNTERS_DESC | TYPE_SAMPLE);
3095         emit_value (logbuffer, len);
3096         for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
3097                 if (pcagent->emitted)
3098                         continue;
3099
3100                 emit_value (logbuffer, MONO_COUNTER_PERFCOUNTERS);
3101                 emit_string (logbuffer, pcagent->category_name, strlen (pcagent->category_name) + 1);
3102                 emit_string (logbuffer, pcagent->name, strlen (pcagent->name) + 1);
3103                 emit_value (logbuffer, MONO_COUNTER_LONG);
3104                 emit_value (logbuffer, MONO_COUNTER_RAW);
3105                 emit_value (logbuffer, MONO_COUNTER_VARIABLE);
3106                 emit_value (logbuffer, pcagent->index);
3107
3108                 pcagent->emitted = 1;
3109         }
3110         EXIT_LOG (logbuffer);
3111
3112         safe_send (profiler, logbuffer);
3113 }
3114
3115 static gboolean
3116 perfcounters_foreach (char *category_name, char *name, unsigned char type, gint64 value, gpointer user_data)
3117 {
3118         PerfCounterAgent *pcagent;
3119
3120         for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
3121                 if (strcmp (pcagent->category_name, category_name) != 0 || strcmp (pcagent->name, name) != 0)
3122                         continue;
3123                 if (pcagent->value == value)
3124                         return TRUE;
3125
3126                 pcagent->value = value;
3127                 pcagent->updated = 1;
3128                 pcagent->deleted = 0;
3129                 return TRUE;
3130         }
3131
3132         pcagent = g_new0 (PerfCounterAgent, 1);
3133         pcagent->next = perfcounters;
3134         pcagent->index = counters_index++;
3135         pcagent->category_name = g_strdup (category_name);
3136         pcagent->name = g_strdup (name);
3137         pcagent->type = (int) type;
3138         pcagent->value = value;
3139         pcagent->emitted = 0;
3140         pcagent->updated = 1;
3141         pcagent->deleted = 0;
3142
3143         perfcounters = pcagent;
3144
3145         return TRUE;
3146 }
3147
3148 static void
3149 perfcounters_sample (MonoProfiler *profiler, uint64_t timestamp)
3150 {
3151         PerfCounterAgent *pcagent;
3152         LogBuffer *logbuffer;
3153         int size;
3154
3155         if (!counters_initialized)
3156                 return;
3157
3158         mono_os_mutex_lock (&counters_mutex);
3159
3160         /* mark all perfcounters as deleted, foreach will unmark them as necessary */
3161         for (pcagent = perfcounters; pcagent; pcagent = pcagent->next)
3162                 pcagent->deleted = 1;
3163
3164         mono_perfcounter_foreach (perfcounters_foreach, perfcounters);
3165
3166         perfcounters_emit (profiler);
3167
3168         size =
3169                 EVENT_SIZE /* event */ +
3170                 LEB128_SIZE /* time */
3171         ;
3172
3173         for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
3174                 if (pcagent->deleted || !pcagent->updated)
3175                         continue;
3176
3177                 size +=
3178                         LEB128_SIZE /* index */ +
3179                         LEB128_SIZE /* type */ +
3180                         LEB128_SIZE /* value */
3181                 ;
3182         }
3183
3184         size +=
3185                 LEB128_SIZE /* stop marker */
3186         ;
3187
3188         logbuffer = ensure_logbuf (size);
3189
3190         ENTER_LOG (logbuffer, "perfcounters");
3191         emit_byte (logbuffer, TYPE_SAMPLE_COUNTERS | TYPE_SAMPLE);
3192         emit_uvalue (logbuffer, timestamp);
3193         for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
3194                 if (pcagent->deleted || !pcagent->updated)
3195                         continue;
3196                 emit_uvalue (logbuffer, pcagent->index);
3197                 emit_uvalue (logbuffer, MONO_COUNTER_LONG);
3198                 emit_svalue (logbuffer, pcagent->value);
3199
3200                 pcagent->updated = 0;
3201         }
3202
3203         emit_value (logbuffer, 0);
3204         EXIT_LOG (logbuffer);
3205
3206         safe_send (profiler, logbuffer);
3207
3208         mono_os_mutex_unlock (&counters_mutex);
3209 }
3210
3211 static void
3212 counters_and_perfcounters_sample (MonoProfiler *prof)
3213 {
3214         static uint64_t start = -1;
3215         uint64_t now;
3216
3217         if (start == -1)
3218                 start = current_time ();
3219
3220         now = current_time ();
3221         counters_sample (prof, (now - start) / 1000/ 1000);
3222         perfcounters_sample (prof, (now - start) / 1000/ 1000);
3223 }
3224
3225 #define COVERAGE_DEBUG(x) if (debug_coverage) {x}
3226 static mono_mutex_t coverage_mutex;
3227 static MonoConcurrentHashTable *coverage_methods = NULL;
3228 static MonoConcurrentHashTable *coverage_assemblies = NULL;
3229 static MonoConcurrentHashTable *coverage_classes = NULL;
3230
3231 static MonoConcurrentHashTable *filtered_classes = NULL;
3232 static MonoConcurrentHashTable *entered_methods = NULL;
3233 static MonoConcurrentHashTable *image_to_methods = NULL;
3234 static MonoConcurrentHashTable *suppressed_assemblies = NULL;
3235 static gboolean coverage_initialized = FALSE;
3236
3237 static GPtrArray *coverage_data = NULL;
3238 static int previous_offset = 0;
3239
3240 typedef struct _MethodNode MethodNode;
3241 struct _MethodNode {
3242         MonoLockFreeQueueNode node;
3243         MonoMethod *method;
3244 };
3245
3246 typedef struct _CoverageEntry CoverageEntry;
3247 struct _CoverageEntry {
3248         int offset;
3249         int counter;
3250         char *filename;
3251         int line;
3252         int column;
3253 };
3254
3255 static void
3256 free_coverage_entry (gpointer data, gpointer userdata)
3257 {
3258         CoverageEntry *entry = (CoverageEntry *)data;
3259         g_free (entry->filename);
3260         g_free (entry);
3261 }
3262
3263 static void
3264 obtain_coverage_for_method (MonoProfiler *prof, const MonoProfileCoverageEntry *entry)
3265 {
3266         int offset = entry->iloffset - previous_offset;
3267         CoverageEntry *e = g_new (CoverageEntry, 1);
3268
3269         previous_offset = entry->iloffset;
3270
3271         e->offset = offset;
3272         e->counter = entry->counter;
3273         e->filename = g_strdup(entry->filename ? entry->filename : "");
3274         e->line = entry->line;
3275         e->column = entry->col;
3276
3277         g_ptr_array_add (coverage_data, e);
3278 }
3279
3280 static char *
3281 parse_generic_type_names(char *name)
3282 {
3283         char *new_name, *ret;
3284         int within_generic_declaration = 0, generic_members = 1;
3285
3286         if (name == NULL || *name == '\0')
3287                 return g_strdup ("");
3288
3289         if (!(ret = new_name = (char *)calloc (strlen (name) * 4 + 1, sizeof (char))))
3290                 return NULL;
3291
3292         do {
3293                 switch (*name) {
3294                         case '<':
3295                                 within_generic_declaration = 1;
3296                                 break;
3297
3298                         case '>':
3299                                 within_generic_declaration = 0;
3300
3301                                 if (*(name - 1) != '<') {
3302                                         *new_name++ = '`';
3303                                         *new_name++ = '0' + generic_members;
3304                                 } else {
3305                                         memcpy (new_name, "&lt;&gt;", 8);
3306                                         new_name += 8;
3307                                 }
3308
3309                                 generic_members = 0;
3310                                 break;
3311
3312                         case ',':
3313                                 generic_members++;
3314                                 break;
3315
3316                         default:
3317                                 if (!within_generic_declaration)
3318                                         *new_name++ = *name;
3319
3320                                 break;
3321                 }
3322         } while (*name++);
3323
3324         return ret;
3325 }
3326
3327 static int method_id;
3328 static void
3329 build_method_buffer (gpointer key, gpointer value, gpointer userdata)
3330 {
3331         MonoMethod *method = (MonoMethod *)value;
3332         MonoProfiler *prof = (MonoProfiler *)userdata;
3333         MonoClass *klass;
3334         MonoImage *image;
3335         char *class_name;
3336         const char *image_name, *method_name, *sig, *first_filename;
3337         LogBuffer *logbuffer;
3338         guint i;
3339
3340         previous_offset = 0;
3341         coverage_data = g_ptr_array_new ();
3342
3343         mono_profiler_coverage_get (prof, method, obtain_coverage_for_method);
3344
3345         klass = mono_method_get_class (method);
3346         image = mono_class_get_image (klass);
3347         image_name = mono_image_get_name (image);
3348
3349         sig = mono_signature_get_desc (mono_method_signature (method), TRUE);
3350         class_name = parse_generic_type_names (mono_type_get_name (mono_class_get_type (klass)));
3351         method_name = mono_method_get_name (method);
3352
3353         if (coverage_data->len != 0) {
3354                 CoverageEntry *entry = (CoverageEntry *)coverage_data->pdata[0];
3355                 first_filename = entry->filename ? entry->filename : "";
3356         } else
3357                 first_filename = "";
3358
3359         image_name = image_name ? image_name : "";
3360         sig = sig ? sig : "";
3361         method_name = method_name ? method_name : "";
3362
3363         logbuffer = ensure_logbuf (
3364                 EVENT_SIZE /* event */ +
3365                 strlen (image_name) + 1 /* image name */ +
3366                 strlen (class_name) + 1 /* class name */ +
3367                 strlen (method_name) + 1 /* method name */ +
3368                 strlen (sig) + 1 /* signature */ +
3369                 strlen (first_filename) + 1 /* first file name */ +
3370                 LEB128_SIZE /* token */ +
3371                 LEB128_SIZE /* method id */ +
3372                 LEB128_SIZE /* entries */
3373         );
3374         ENTER_LOG (logbuffer, "coverage-methods");
3375
3376         emit_byte (logbuffer, TYPE_COVERAGE_METHOD | TYPE_COVERAGE);
3377         emit_string (logbuffer, image_name, strlen (image_name) + 1);
3378         emit_string (logbuffer, class_name, strlen (class_name) + 1);
3379         emit_string (logbuffer, method_name, strlen (method_name) + 1);
3380         emit_string (logbuffer, sig, strlen (sig) + 1);
3381         emit_string (logbuffer, first_filename, strlen (first_filename) + 1);
3382
3383         emit_uvalue (logbuffer, mono_method_get_token (method));
3384         emit_uvalue (logbuffer, method_id);
3385         emit_value (logbuffer, coverage_data->len);
3386
3387         EXIT_LOG (logbuffer);
3388         safe_send (prof, logbuffer);
3389
3390         for (i = 0; i < coverage_data->len; i++) {
3391                 CoverageEntry *entry = (CoverageEntry *)coverage_data->pdata[i];
3392
3393                 logbuffer = ensure_logbuf (
3394                         EVENT_SIZE /* event */ +
3395                         LEB128_SIZE /* method id */ +
3396                         LEB128_SIZE /* offset */ +
3397                         LEB128_SIZE /* counter */ +
3398                         LEB128_SIZE /* line */ +
3399                         LEB128_SIZE /* column */
3400                 );
3401                 ENTER_LOG (logbuffer, "coverage-statement");
3402
3403                 emit_byte (logbuffer, TYPE_COVERAGE_STATEMENT | TYPE_COVERAGE);
3404                 emit_uvalue (logbuffer, method_id);
3405                 emit_uvalue (logbuffer, entry->offset);
3406                 emit_uvalue (logbuffer, entry->counter);
3407                 emit_uvalue (logbuffer, entry->line);
3408                 emit_uvalue (logbuffer, entry->column);
3409
3410                 EXIT_LOG (logbuffer);
3411                 safe_send (prof, logbuffer);
3412         }
3413
3414         method_id++;
3415
3416         g_free (class_name);
3417
3418         g_ptr_array_foreach (coverage_data, free_coverage_entry, NULL);
3419         g_ptr_array_free (coverage_data, TRUE);
3420         coverage_data = NULL;
3421 }
3422
3423 /* This empties the queue */
3424 static guint
3425 count_queue (MonoLockFreeQueue *queue)
3426 {
3427         MonoLockFreeQueueNode *node;
3428         guint count = 0;
3429
3430         while ((node = mono_lock_free_queue_dequeue (queue))) {
3431                 count++;
3432                 mono_lock_free_queue_node_free (node);
3433         }
3434
3435         return count;
3436 }
3437
3438 static void
3439 build_class_buffer (gpointer key, gpointer value, gpointer userdata)
3440 {
3441         MonoClass *klass = (MonoClass *)key;
3442         MonoLockFreeQueue *class_methods = (MonoLockFreeQueue *)value;
3443         MonoProfiler *prof = (MonoProfiler *)userdata;
3444         MonoImage *image;
3445         char *class_name;
3446         const char *assembly_name;
3447         int number_of_methods, partially_covered;
3448         guint fully_covered;
3449         LogBuffer *logbuffer;
3450
3451         image = mono_class_get_image (klass);
3452         assembly_name = mono_image_get_name (image);
3453         class_name = mono_type_get_name (mono_class_get_type (klass));
3454
3455         assembly_name = assembly_name ? assembly_name : "";
3456         number_of_methods = mono_class_num_methods (klass);
3457         fully_covered = count_queue (class_methods);
3458         /* We don't handle partial covered yet */
3459         partially_covered = 0;
3460
3461         logbuffer = ensure_logbuf (
3462                 EVENT_SIZE /* event */ +
3463                 strlen (assembly_name) + 1 /* assembly name */ +
3464                 strlen (class_name) + 1 /* class name */ +
3465                 LEB128_SIZE /* no. methods */ +
3466                 LEB128_SIZE /* fully covered */ +
3467                 LEB128_SIZE /* partially covered */
3468         );
3469
3470         ENTER_LOG (logbuffer, "coverage-class");
3471         emit_byte (logbuffer, TYPE_COVERAGE_CLASS | TYPE_COVERAGE);
3472         emit_string (logbuffer, assembly_name, strlen (assembly_name) + 1);
3473         emit_string (logbuffer, class_name, strlen (class_name) + 1);
3474         emit_uvalue (logbuffer, number_of_methods);
3475         emit_uvalue (logbuffer, fully_covered);
3476         emit_uvalue (logbuffer, partially_covered);
3477         EXIT_LOG (logbuffer);
3478
3479         safe_send (prof, logbuffer);
3480
3481         g_free (class_name);
3482 }
3483
3484 static void
3485 get_coverage_for_image (MonoImage *image, int *number_of_methods, guint *fully_covered, int *partially_covered)
3486 {
3487         MonoLockFreeQueue *image_methods = (MonoLockFreeQueue *)mono_conc_hashtable_lookup (image_to_methods, image);
3488
3489         *number_of_methods = mono_image_get_table_rows (image, MONO_TABLE_METHOD);
3490         if (image_methods)
3491                 *fully_covered = count_queue (image_methods);
3492         else
3493                 *fully_covered = 0;
3494
3495         // FIXME: We don't handle partially covered yet.
3496         *partially_covered = 0;
3497 }
3498
3499 static void
3500 build_assembly_buffer (gpointer key, gpointer value, gpointer userdata)
3501 {
3502         MonoAssembly *assembly = (MonoAssembly *)value;
3503         MonoProfiler *prof = (MonoProfiler *)userdata;
3504         MonoImage *image = mono_assembly_get_image (assembly);
3505         LogBuffer *logbuffer;
3506         const char *name, *guid, *filename;
3507         int number_of_methods = 0, partially_covered = 0;
3508         guint fully_covered = 0;
3509
3510         name = mono_image_get_name (image);
3511         guid = mono_image_get_guid (image);
3512         filename = mono_image_get_filename (image);
3513
3514         name = name ? name : "";
3515         guid = guid ? guid : "";
3516         filename = filename ? filename : "";
3517
3518         get_coverage_for_image (image, &number_of_methods, &fully_covered, &partially_covered);
3519
3520         logbuffer = ensure_logbuf (
3521                 EVENT_SIZE /* event */ +
3522                 strlen (name) + 1 /* name */ +
3523                 strlen (guid) + 1 /* guid */ +
3524                 strlen (filename) + 1 /* file name */ +
3525                 LEB128_SIZE /* no. methods */ +
3526                 LEB128_SIZE /* fully covered */ +
3527                 LEB128_SIZE /* partially covered */
3528         );
3529
3530         ENTER_LOG (logbuffer, "coverage-assemblies");
3531         emit_byte (logbuffer, TYPE_COVERAGE_ASSEMBLY | TYPE_COVERAGE);
3532         emit_string (logbuffer, name, strlen (name) + 1);
3533         emit_string (logbuffer, guid, strlen (guid) + 1);
3534         emit_string (logbuffer, filename, strlen (filename) + 1);
3535         emit_uvalue (logbuffer, number_of_methods);
3536         emit_uvalue (logbuffer, fully_covered);
3537         emit_uvalue (logbuffer, partially_covered);
3538         EXIT_LOG (logbuffer);
3539
3540         safe_send (prof, logbuffer);
3541 }
3542
3543 static void
3544 dump_coverage (MonoProfiler *prof)
3545 {
3546         if (!coverage_initialized)
3547                 return;
3548
3549         COVERAGE_DEBUG(fprintf (stderr, "Coverage: Started dump\n");)
3550         method_id = 0;
3551
3552         mono_os_mutex_lock (&coverage_mutex);
3553         mono_conc_hashtable_foreach (coverage_assemblies, build_assembly_buffer, prof);
3554         mono_conc_hashtable_foreach (coverage_classes, build_class_buffer, prof);
3555         mono_conc_hashtable_foreach (coverage_methods, build_method_buffer, prof);
3556         mono_os_mutex_unlock (&coverage_mutex);
3557
3558         COVERAGE_DEBUG(fprintf (stderr, "Coverage: Finished dump\n");)
3559 }
3560
3561 static void
3562 process_method_enter_coverage (MonoProfiler *prof, MonoMethod *method)
3563 {
3564         MonoClass *klass;
3565         MonoImage *image;
3566
3567         if (!coverage_initialized)
3568                 return;
3569
3570         klass = mono_method_get_class (method);
3571         image = mono_class_get_image (klass);
3572
3573         if (mono_conc_hashtable_lookup (suppressed_assemblies, (gpointer) mono_image_get_name (image)))
3574                 return;
3575
3576         mono_os_mutex_lock (&coverage_mutex);
3577         mono_conc_hashtable_insert (entered_methods, method, method);
3578         mono_os_mutex_unlock (&coverage_mutex);
3579 }
3580
3581 static MonoLockFreeQueueNode *
3582 create_method_node (MonoMethod *method)
3583 {
3584         MethodNode *node = (MethodNode *)g_malloc (sizeof (MethodNode));
3585         mono_lock_free_queue_node_init ((MonoLockFreeQueueNode *) node, FALSE);
3586         node->method = method;
3587
3588         return (MonoLockFreeQueueNode *) node;
3589 }
3590
3591 static gboolean
3592 coverage_filter (MonoProfiler *prof, MonoMethod *method)
3593 {
3594         MonoError error;
3595         MonoClass *klass;
3596         MonoImage *image;
3597         MonoAssembly *assembly;
3598         MonoMethodHeader *header;
3599         guint32 iflags, flags, code_size;
3600         char *fqn, *classname;
3601         gboolean has_positive, found;
3602         MonoLockFreeQueue *image_methods, *class_methods;
3603         MonoLockFreeQueueNode *node;
3604
3605         if (!coverage_initialized)
3606                 return FALSE;
3607
3608         COVERAGE_DEBUG(fprintf (stderr, "Coverage filter for %s\n", mono_method_get_name (method));)
3609
3610         flags = mono_method_get_flags (method, &iflags);
3611         if ((iflags & 0x1000 /*METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL*/) ||
3612             (flags & 0x2000 /*METHOD_ATTRIBUTE_PINVOKE_IMPL*/)) {
3613                 COVERAGE_DEBUG(fprintf (stderr, "   Internal call or pinvoke - ignoring\n");)
3614                 return FALSE;
3615         }
3616
3617         // Don't need to do anything else if we're already tracking this method
3618         if (mono_conc_hashtable_lookup (coverage_methods, method)) {
3619                 COVERAGE_DEBUG(fprintf (stderr, "   Already tracking\n");)
3620                 return TRUE;
3621         }
3622
3623         klass = mono_method_get_class (method);
3624         image = mono_class_get_image (klass);
3625
3626         // Don't handle coverage for the core assemblies
3627         if (mono_conc_hashtable_lookup (suppressed_assemblies, (gpointer) mono_image_get_name (image)) != NULL)
3628                 return FALSE;
3629
3630         if (prof->coverage_filters) {
3631                 /* Check already filtered classes first */
3632                 if (mono_conc_hashtable_lookup (filtered_classes, klass)) {
3633                         COVERAGE_DEBUG(fprintf (stderr, "   Already filtered\n");)
3634                         return FALSE;
3635                 }
3636
3637                 classname = mono_type_get_name (mono_class_get_type (klass));
3638
3639                 fqn = g_strdup_printf ("[%s]%s", mono_image_get_name (image), classname);
3640
3641                 COVERAGE_DEBUG(fprintf (stderr, "   Looking for %s in filter\n", fqn);)
3642                 // Check positive filters first
3643                 has_positive = FALSE;
3644                 found = FALSE;
3645                 for (guint i = 0; i < prof->coverage_filters->len; ++i) {
3646                         char *filter = (char *)g_ptr_array_index (prof->coverage_filters, i);
3647
3648                         if (filter [0] == '+') {
3649                                 filter = &filter [1];
3650
3651                                 COVERAGE_DEBUG(fprintf (stderr, "   Checking against +%s ...", filter);)
3652
3653                                 if (strstr (fqn, filter) != NULL) {
3654                                         COVERAGE_DEBUG(fprintf (stderr, "matched\n");)
3655                                         found = TRUE;
3656                                 } else
3657                                         COVERAGE_DEBUG(fprintf (stderr, "no match\n");)
3658
3659                                 has_positive = TRUE;
3660                         }
3661                 }
3662
3663                 if (has_positive && !found) {
3664                         COVERAGE_DEBUG(fprintf (stderr, "   Positive match was not found\n");)
3665
3666                         mono_os_mutex_lock (&coverage_mutex);
3667                         mono_conc_hashtable_insert (filtered_classes, klass, klass);
3668                         mono_os_mutex_unlock (&coverage_mutex);
3669                         g_free (fqn);
3670                         g_free (classname);
3671
3672                         return FALSE;
3673                 }
3674
3675                 for (guint i = 0; i < prof->coverage_filters->len; ++i) {
3676                         // FIXME: Is substring search sufficient?
3677                         char *filter = (char *)g_ptr_array_index (prof->coverage_filters, i);
3678                         if (filter [0] == '+')
3679                                 continue;
3680
3681                         // Skip '-'
3682                         filter = &filter [1];
3683                         COVERAGE_DEBUG(fprintf (stderr, "   Checking against -%s ...", filter);)
3684
3685                         if (strstr (fqn, filter) != NULL) {
3686                                 COVERAGE_DEBUG(fprintf (stderr, "matched\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                         } else
3696                                 COVERAGE_DEBUG(fprintf (stderr, "no match\n");)
3697
3698                 }
3699
3700                 g_free (fqn);
3701                 g_free (classname);
3702         }
3703
3704         COVERAGE_DEBUG(fprintf (stderr, "   Handling coverage for %s\n", mono_method_get_name (method));)
3705         header = mono_method_get_header_checked (method, &error);
3706         mono_error_cleanup (&error);
3707
3708         mono_method_header_get_code (header, &code_size, NULL);
3709
3710         assembly = mono_image_get_assembly (image);
3711
3712         mono_os_mutex_lock (&coverage_mutex);
3713         mono_conc_hashtable_insert (coverage_methods, method, method);
3714         mono_conc_hashtable_insert (coverage_assemblies, assembly, assembly);
3715         mono_os_mutex_unlock (&coverage_mutex);
3716
3717         image_methods = (MonoLockFreeQueue *)mono_conc_hashtable_lookup (image_to_methods, image);
3718
3719         if (image_methods == NULL) {
3720                 image_methods = (MonoLockFreeQueue *)g_malloc (sizeof (MonoLockFreeQueue));
3721                 mono_lock_free_queue_init (image_methods);
3722                 mono_os_mutex_lock (&coverage_mutex);
3723                 mono_conc_hashtable_insert (image_to_methods, image, image_methods);
3724                 mono_os_mutex_unlock (&coverage_mutex);
3725         }
3726
3727         node = create_method_node (method);
3728         mono_lock_free_queue_enqueue (image_methods, node);
3729
3730         class_methods = (MonoLockFreeQueue *)mono_conc_hashtable_lookup (coverage_classes, klass);
3731
3732         if (class_methods == NULL) {
3733                 class_methods = (MonoLockFreeQueue *)g_malloc (sizeof (MonoLockFreeQueue));
3734                 mono_lock_free_queue_init (class_methods);
3735                 mono_os_mutex_lock (&coverage_mutex);
3736                 mono_conc_hashtable_insert (coverage_classes, klass, class_methods);
3737                 mono_os_mutex_unlock (&coverage_mutex);
3738         }
3739
3740         node = create_method_node (method);
3741         mono_lock_free_queue_enqueue (class_methods, node);
3742
3743         return TRUE;
3744 }
3745
3746 #define LINE_BUFFER_SIZE 4096
3747 /* Max file limit of 128KB */
3748 #define MAX_FILE_SIZE 128 * 1024
3749 static char *
3750 get_file_content (FILE *stream)
3751 {
3752         char *buffer;
3753         ssize_t bytes_read;
3754         long filesize;
3755         int res, offset = 0;
3756
3757         res = fseek (stream, 0, SEEK_END);
3758         if (res < 0)
3759           return NULL;
3760
3761         filesize = ftell (stream);
3762         if (filesize < 0)
3763           return NULL;
3764
3765         res = fseek (stream, 0, SEEK_SET);
3766         if (res < 0)
3767           return NULL;
3768
3769         if (filesize > MAX_FILE_SIZE)
3770           return NULL;
3771
3772         buffer = (char *)g_malloc ((filesize + 1) * sizeof (char));
3773         while ((bytes_read = fread (buffer + offset, 1, LINE_BUFFER_SIZE, stream)) > 0)
3774                 offset += bytes_read;
3775
3776         /* NULL terminate our buffer */
3777         buffer[filesize] = '\0';
3778         return buffer;
3779 }
3780
3781 static char *
3782 get_next_line (char *contents, char **next_start)
3783 {
3784         char *p = contents;
3785
3786         if (p == NULL || *p == '\0') {
3787                 *next_start = NULL;
3788                 return NULL;
3789         }
3790
3791         while (*p != '\n' && *p != '\0')
3792                 p++;
3793
3794         if (*p == '\n') {
3795                 *p = '\0';
3796                 *next_start = p + 1;
3797         } else
3798                 *next_start = NULL;
3799
3800         return contents;
3801 }
3802
3803 static void
3804 init_suppressed_assemblies (void)
3805 {
3806         char *content;
3807         char *line;
3808         FILE *sa_file;
3809
3810         suppressed_assemblies = mono_conc_hashtable_new (g_str_hash, g_str_equal);
3811         sa_file = fopen (SUPPRESSION_DIR "/mono-profiler-log.suppression", "r");
3812         if (sa_file == NULL)
3813                 return;
3814
3815         /* Don't need to free @content as it is referred to by the lines stored in @suppressed_assemblies */
3816         content = get_file_content (sa_file);
3817         if (content == NULL) {
3818                 g_error ("mono-profiler-log.suppression is greater than 128kb - aborting\n");
3819         }
3820
3821         while ((line = get_next_line (content, &content))) {
3822                 line = g_strchomp (g_strchug (line));
3823                 /* No locking needed as we're doing initialization */
3824                 mono_conc_hashtable_insert (suppressed_assemblies, line, line);
3825         }
3826
3827         fclose (sa_file);
3828 }
3829
3830 #endif /* DISABLE_HELPER_THREAD */
3831
3832 static void
3833 coverage_init (MonoProfiler *prof)
3834 {
3835 #ifndef DISABLE_HELPER_THREAD
3836         assert (!coverage_initialized);
3837
3838         COVERAGE_DEBUG(fprintf (stderr, "Coverage initialized\n");)
3839
3840         mono_os_mutex_init (&coverage_mutex);
3841         coverage_methods = mono_conc_hashtable_new (NULL, NULL);
3842         coverage_assemblies = mono_conc_hashtable_new (NULL, NULL);
3843         coverage_classes = mono_conc_hashtable_new (NULL, NULL);
3844         filtered_classes = mono_conc_hashtable_new (NULL, NULL);
3845         entered_methods = mono_conc_hashtable_new (NULL, NULL);
3846         image_to_methods = mono_conc_hashtable_new (NULL, NULL);
3847         init_suppressed_assemblies ();
3848
3849         coverage_initialized = TRUE;
3850 #endif /* DISABLE_HELPER_THREAD */
3851 }
3852
3853 static void
3854 log_shutdown (MonoProfiler *prof)
3855 {
3856         void *res;
3857
3858         in_shutdown = 1;
3859 #ifndef DISABLE_HELPER_THREAD
3860         counters_and_perfcounters_sample (prof);
3861
3862         dump_coverage (prof);
3863
3864         if (prof->command_port) {
3865                 char c = 1;
3866                 ign_res (write (prof->pipes [1], &c, 1));
3867                 pthread_join (prof->helper_thread, &res);
3868         }
3869 #endif
3870 #if USE_PERF_EVENTS
3871         if (perf_data) {
3872                 int i;
3873                 for (i = 0; i < num_perf; ++i)
3874                         read_perf_mmap (prof, i);
3875         }
3876 #endif
3877
3878         g_ptr_array_free (prof->sorted_sample_events, TRUE);
3879
3880         if (TLS_GET (LogBuffer, tlsbuffer))
3881                 send_buffer (prof, TLS_GET (GPtrArray, tlsmethodlist), TLS_GET (LogBuffer, tlsbuffer));
3882
3883         TLS_SET (tlsbuffer, NULL);
3884         TLS_SET (tlsmethodlist, NULL);
3885
3886         InterlockedWrite (&prof->run_writer_thread, 0);
3887         pthread_join (prof->writer_thread, &res);
3888
3889 #if defined (HAVE_SYS_ZLIB)
3890         if (prof->gzfile)
3891                 gzclose (prof->gzfile);
3892 #endif
3893         if (prof->pipe_output)
3894                 pclose (prof->file);
3895         else
3896                 fclose (prof->file);
3897
3898         mono_conc_hashtable_destroy (prof->method_table);
3899         mono_os_mutex_destroy (&prof->method_table_mutex);
3900
3901         if (coverage_initialized) {
3902                 mono_conc_hashtable_destroy (coverage_methods);
3903                 mono_conc_hashtable_destroy (coverage_assemblies);
3904                 mono_conc_hashtable_destroy (coverage_classes);
3905                 mono_conc_hashtable_destroy (filtered_classes);
3906
3907                 mono_conc_hashtable_destroy (entered_methods);
3908                 mono_conc_hashtable_destroy (image_to_methods);
3909                 mono_conc_hashtable_destroy (suppressed_assemblies);
3910                 mono_os_mutex_destroy (&coverage_mutex);
3911         }
3912
3913         free (prof);
3914 }
3915
3916 static char*
3917 new_filename (const char* filename)
3918 {
3919         time_t t = time (NULL);
3920         int pid = process_id ();
3921         char pid_buf [16];
3922         char time_buf [16];
3923         char *res, *d;
3924         const char *p;
3925         int count_dates = 0;
3926         int count_pids = 0;
3927         int s_date, s_pid;
3928         struct tm *ts;
3929         for (p = filename; *p; p++) {
3930                 if (*p != '%')
3931                         continue;
3932                 p++;
3933                 if (*p == 't')
3934                         count_dates++;
3935                 else if (*p == 'p')
3936                         count_pids++;
3937                 else if (*p == 0)
3938                         break;
3939         }
3940         if (!count_dates && !count_pids)
3941                 return pstrdup (filename);
3942         snprintf (pid_buf, sizeof (pid_buf), "%d", pid);
3943         ts = gmtime (&t);
3944         snprintf (time_buf, sizeof (time_buf), "%d%02d%02d%02d%02d%02d",
3945                 1900 + ts->tm_year, 1 + ts->tm_mon, ts->tm_mday, ts->tm_hour, ts->tm_min, ts->tm_sec);
3946         s_date = strlen (time_buf);
3947         s_pid = strlen (pid_buf);
3948         d = res = (char *)malloc (strlen (filename) + s_date * count_dates + s_pid * count_pids);
3949         for (p = filename; *p; p++) {
3950                 if (*p != '%') {
3951                         *d++ = *p;
3952                         continue;
3953                 }
3954                 p++;
3955                 if (*p == 't') {
3956                         strcpy (d, time_buf);
3957                         d += s_date;
3958                         continue;
3959                 } else if (*p == 'p') {
3960                         strcpy (d, pid_buf);
3961                         d += s_pid;
3962                         continue;
3963                 } else if (*p == '%') {
3964                         *d++ = '%';
3965                         continue;
3966                 } else if (*p == 0)
3967                         break;
3968                 *d++ = '%';
3969                 *d++ = *p;
3970         }
3971         *d = 0;
3972         return res;
3973 }
3974
3975 //this is exposed by the JIT, but it's not meant to be a supported API for now.
3976 extern void mono_threads_attach_tools_thread (void);
3977
3978 #ifndef DISABLE_HELPER_THREAD
3979
3980 static void*
3981 helper_thread (void* arg)
3982 {
3983         MonoProfiler* prof = (MonoProfiler *)arg;
3984         int command_socket;
3985         int len;
3986         char buf [64];
3987         MonoThread *thread = NULL;
3988
3989         mono_threads_attach_tools_thread ();
3990         //fprintf (stderr, "Server listening\n");
3991         command_socket = -1;
3992         while (1) {
3993                 fd_set rfds;
3994                 struct timeval tv;
3995                 int max_fd = -1;
3996                 FD_ZERO (&rfds);
3997                 FD_SET (prof->server_socket, &rfds);
3998                 max_fd = prof->server_socket;
3999                 FD_SET (prof->pipes [0], &rfds);
4000                 if (max_fd < prof->pipes [0])
4001                         max_fd = prof->pipes [0];
4002                 if (command_socket >= 0) {
4003                         FD_SET (command_socket, &rfds);
4004                         if (max_fd < command_socket)
4005                                 max_fd = command_socket;
4006                 }
4007 #if USE_PERF_EVENTS
4008                 if (perf_data) {
4009                         int i;
4010                         for ( i = 0; i < num_perf; ++i) {
4011                                 if (perf_data [i].perf_fd < 0)
4012                                         continue;
4013                                 FD_SET (perf_data [i].perf_fd, &rfds);
4014                                 if (max_fd < perf_data [i].perf_fd)
4015                                         max_fd = perf_data [i].perf_fd;
4016                         }
4017                 }
4018 #endif
4019
4020                 counters_and_perfcounters_sample (prof);
4021
4022                 tv.tv_sec = 1;
4023                 tv.tv_usec = 0;
4024                 len = select (max_fd + 1, &rfds, NULL, NULL, &tv);
4025
4026                 if (len < 0) {
4027                         if (errno == EINTR)
4028                                 continue;
4029
4030                         g_warning ("Error in proflog server: %s", strerror (errno));
4031                         return NULL;
4032                 }
4033
4034                 if (FD_ISSET (prof->pipes [0], &rfds)) {
4035                         char c;
4036                         int r = read (prof->pipes [0], &c, 1);
4037                         if (r == 1 && c == 0) {
4038                                 StatBuffer *sbufbase = prof->stat_buffers;
4039                                 StatBuffer *sbuf;
4040                                 if (!sbufbase->next)
4041                                         continue;
4042                                 sbuf = sbufbase->next->next;
4043                                 sbufbase->next->next = NULL;
4044                                 if (do_debug)
4045                                         fprintf (stderr, "stat buffer dump\n");
4046                                 if (sbuf) {
4047                                         dump_sample_hits (prof, sbuf);
4048                                         free_buffer (sbuf, sbuf->size);
4049                                         safe_send (prof, ensure_logbuf (0));
4050                                 }
4051                                 continue;
4052                         }
4053                         /* time to shut down */
4054                         dump_sample_hits (prof, prof->stat_buffers);
4055                         if (thread)
4056                                 mono_thread_detach (thread);
4057                         if (do_debug)
4058                                 fprintf (stderr, "helper shutdown\n");
4059 #if USE_PERF_EVENTS
4060                         if (perf_data) {
4061                                 int i;
4062                                 for ( i = 0; i < num_perf; ++i) {
4063                                         if (perf_data [i].perf_fd < 0)
4064                                                 continue;
4065                                         if (FD_ISSET (perf_data [i].perf_fd, &rfds))
4066                                                 read_perf_mmap (prof, i);
4067                                 }
4068                         }
4069 #endif
4070                         safe_send (prof, ensure_logbuf (0));
4071                         return NULL;
4072                 }
4073 #if USE_PERF_EVENTS
4074                 if (perf_data) {
4075                         int i;
4076                         for ( i = 0; i < num_perf; ++i) {
4077                                 if (perf_data [i].perf_fd < 0)
4078                                         continue;
4079                                 if (FD_ISSET (perf_data [i].perf_fd, &rfds)) {
4080                                         read_perf_mmap (prof, i);
4081                                         safe_send (prof, ensure_logbuf (0));
4082                                 }
4083                         }
4084                 }
4085 #endif
4086                 if (command_socket >= 0 && FD_ISSET (command_socket, &rfds)) {
4087                         len = read (command_socket, buf, sizeof (buf) - 1);
4088                         if (len < 0)
4089                                 continue;
4090                         if (len == 0) {
4091                                 close (command_socket);
4092                                 command_socket = -1;
4093                                 continue;
4094                         }
4095                         buf [len] = 0;
4096                         if (strcmp (buf, "heapshot\n") == 0) {
4097                                 heapshot_requested = 1;
4098                                 //fprintf (stderr, "perform heapshot\n");
4099                                 if (InterlockedRead (&runtime_inited) && !thread) {
4100                                         thread = mono_thread_attach (mono_get_root_domain ());
4101                                         /*fprintf (stderr, "attached\n");*/
4102                                 }
4103                                 if (thread) {
4104                                         process_requests (prof);
4105                                         mono_thread_detach (thread);
4106                                         thread = NULL;
4107                                 }
4108                         }
4109                         continue;
4110                 }
4111                 if (!FD_ISSET (prof->server_socket, &rfds)) {
4112                         continue;
4113                 }
4114                 command_socket = accept (prof->server_socket, NULL, NULL);
4115                 if (command_socket < 0)
4116                         continue;
4117                 //fprintf (stderr, "Accepted connection\n");
4118         }
4119         return NULL;
4120 }
4121
4122 static int
4123 start_helper_thread (MonoProfiler* prof)
4124 {
4125         struct sockaddr_in server_address;
4126         int r;
4127         socklen_t slen;
4128         if (pipe (prof->pipes) < 0) {
4129                 fprintf (stderr, "Cannot create pipe\n");
4130                 return 0;
4131         }
4132         prof->server_socket = socket (PF_INET, SOCK_STREAM, 0);
4133         if (prof->server_socket < 0) {
4134                 fprintf (stderr, "Cannot create server socket\n");
4135                 return 0;
4136         }
4137         memset (&server_address, 0, sizeof (server_address));
4138         server_address.sin_family = AF_INET;
4139         server_address.sin_addr.s_addr = INADDR_ANY;
4140         server_address.sin_port = htons (prof->command_port);
4141         if (bind (prof->server_socket, (struct sockaddr *) &server_address, sizeof (server_address)) < 0) {
4142                 fprintf (stderr, "Cannot bind server socket, port: %d: %s\n", prof->command_port, strerror (errno));
4143                 close (prof->server_socket);
4144                 return 0;
4145         }
4146         if (listen (prof->server_socket, 1) < 0) {
4147                 fprintf (stderr, "Cannot listen server socket\n");
4148                 close (prof->server_socket);
4149                 return 0;
4150         }
4151         slen = sizeof (server_address);
4152         if (getsockname (prof->server_socket, (struct sockaddr *)&server_address, &slen) == 0) {
4153                 prof->command_port = ntohs (server_address.sin_port);
4154                 /*fprintf (stderr, "Assigned server port: %d\n", prof->command_port);*/
4155         }
4156
4157         r = pthread_create (&prof->helper_thread, NULL, helper_thread, prof);
4158         if (r) {
4159                 close (prof->server_socket);
4160                 return 0;
4161         }
4162         return 1;
4163 }
4164 #endif
4165
4166 static void *
4167 writer_thread (void *arg)
4168 {
4169         MonoProfiler *prof = (MonoProfiler *)arg;
4170
4171         mono_threads_attach_tools_thread ();
4172
4173         dump_header (prof);
4174
4175         while (InterlockedRead (&prof->run_writer_thread)) {
4176                 WriterQueueEntry *entry;
4177
4178                 while ((entry = (WriterQueueEntry *) mono_lock_free_queue_dequeue (&prof->writer_queue))) {
4179                         LogBuffer *method_buffer = NULL;
4180                         gboolean new_methods = FALSE;
4181
4182                         if (entry->methods->len)
4183                                 method_buffer = create_buffer ();
4184
4185                         /*
4186                          * Encode the method events in a temporary log buffer that we
4187                          * flush to disk before the main buffer, ensuring that all
4188                          * methods have metadata emitted before they're referenced.
4189                          */
4190                         for (guint i = 0; i < entry->methods->len; i++) {
4191                                 MethodInfo *info = (MethodInfo *)g_ptr_array_index (entry->methods, i);
4192
4193                                 if (mono_conc_hashtable_lookup (prof->method_table, info->method))
4194                                         continue;
4195
4196                                 new_methods = TRUE;
4197
4198                                 /*
4199                                  * Other threads use this hash table to get a general
4200                                  * idea of whether a method has already been emitted to
4201                                  * the stream. Due to the way we add to this table, it
4202                                  * can easily happen that multiple threads queue up the
4203                                  * same methods, but that's OK since eventually all
4204                                  * methods will be in this table and the thread-local
4205                                  * method lists will just be empty for the rest of the
4206                                  * app's lifetime.
4207                                  */
4208                                 mono_os_mutex_lock (&prof->method_table_mutex);
4209                                 mono_conc_hashtable_insert (prof->method_table, info->method, info->method);
4210                                 mono_os_mutex_unlock (&prof->method_table_mutex);
4211
4212                                 char *name = mono_method_full_name (info->method, 1);
4213                                 int nlen = strlen (name) + 1;
4214                                 void *cstart = info->ji ? mono_jit_info_get_code_start (info->ji) : NULL;
4215                                 int csize = info->ji ? mono_jit_info_get_code_size (info->ji) : 0;
4216
4217                                 method_buffer = ensure_logbuf_inner (method_buffer,
4218                                         EVENT_SIZE /* event */ +
4219                                         LEB128_SIZE /* time */ +
4220                                         LEB128_SIZE /* method */ +
4221                                         LEB128_SIZE /* start */ +
4222                                         LEB128_SIZE /* size */ +
4223                                         nlen /* name */
4224                                 );
4225
4226                                 emit_byte (method_buffer, TYPE_JIT | TYPE_METHOD);
4227                                 emit_time (method_buffer, info->time);
4228                                 emit_method_inner (method_buffer, info->method);
4229                                 emit_ptr (method_buffer, cstart);
4230                                 emit_value (method_buffer, csize);
4231
4232                                 memcpy (method_buffer->data, name, nlen);
4233                                 method_buffer->data += nlen;
4234
4235                                 mono_free (name);
4236                                 free (info);
4237                         }
4238
4239                         g_ptr_array_free (entry->methods, TRUE);
4240
4241                         if (new_methods)
4242                                 dump_buffer (prof, method_buffer);
4243                         else if (method_buffer)
4244                                 free_buffer (method_buffer, method_buffer->size);
4245
4246                         dump_buffer (prof, entry->buffer);
4247
4248                         free (entry);
4249                 }
4250         }
4251
4252         return NULL;
4253 }
4254
4255 static int
4256 start_writer_thread (MonoProfiler* prof)
4257 {
4258         InterlockedWrite (&prof->run_writer_thread, 1);
4259
4260         return !pthread_create (&prof->writer_thread, NULL, writer_thread, prof);
4261 }
4262
4263 static void
4264 runtime_initialized (MonoProfiler *profiler)
4265 {
4266 #ifndef DISABLE_HELPER_THREAD
4267         if (hs_mode_ondemand || need_helper_thread) {
4268                 if (!start_helper_thread (profiler))
4269                         profiler->command_port = 0;
4270         }
4271 #endif
4272
4273         start_writer_thread (profiler);
4274
4275         InterlockedWrite (&runtime_inited, 1);
4276 #ifndef DISABLE_HELPER_THREAD
4277         counters_init (profiler);
4278         counters_sample (profiler, 0);
4279 #endif
4280         /* ensure the main thread data and startup are available soon */
4281         safe_send (profiler, ensure_logbuf (0));
4282 }
4283
4284 static MonoProfiler*
4285 create_profiler (const char *filename, GPtrArray *filters)
4286 {
4287         MonoProfiler *prof;
4288         char *nf;
4289         int force_delete = 0;
4290         prof = (MonoProfiler *)calloc (1, sizeof (MonoProfiler));
4291
4292         prof->command_port = command_port;
4293         if (filename && *filename == '-') {
4294                 force_delete = 1;
4295                 filename++;
4296         }
4297         if (!filename) {
4298                 if (do_report)
4299                         filename = "|mprof-report -";
4300                 else
4301                         filename = "output.mlpd";
4302                 nf = (char*)filename;
4303         } else {
4304                 nf = new_filename (filename);
4305                 if (do_report) {
4306                         int s = strlen (nf) + 32;
4307                         char *p = (char *)malloc (s);
4308                         snprintf (p, s, "|mprof-report '--out=%s' -", nf);
4309                         free (nf);
4310                         nf = p;
4311                 }
4312         }
4313         if (*nf == '|') {
4314                 prof->file = popen (nf + 1, "w");
4315                 prof->pipe_output = 1;
4316         } else if (*nf == '#') {
4317                 int fd = strtol (nf + 1, NULL, 10);
4318                 prof->file = fdopen (fd, "a");
4319         } else {
4320                 if (force_delete)
4321                         unlink (nf);
4322                 prof->file = fopen (nf, "wb");
4323         }
4324         if (!prof->file) {
4325                 fprintf (stderr, "Cannot create profiler output: %s\n", nf);
4326                 exit (1);
4327         }
4328 #if defined (HAVE_SYS_ZLIB)
4329         if (use_zip)
4330                 prof->gzfile = gzdopen (fileno (prof->file), "wb");
4331 #endif
4332 #if USE_PERF_EVENTS
4333         if (sample_type && !do_mono_sample)
4334                 need_helper_thread = setup_perf_event ();
4335         if (!perf_data) {
4336                 /* FIXME: warn if different freq or sample type */
4337                 do_mono_sample = 1;
4338         }
4339 #endif
4340         if (do_mono_sample) {
4341                 prof->stat_buffers = create_stat_buffer ();
4342                 need_helper_thread = 1;
4343         }
4344         if (do_counters && !need_helper_thread) {
4345                 need_helper_thread = 1;
4346         }
4347
4348         prof->sorted_sample_events = g_ptr_array_sized_new (BUFFER_SIZE / SAMPLE_EVENT_SIZE_IN_SLOTS (0));
4349
4350 #ifdef DISABLE_HELPER_THREAD
4351         if (hs_mode_ondemand)
4352                 fprintf (stderr, "Ondemand heapshot unavailable on this arch.\n");
4353
4354         if (do_coverage)
4355                 fprintf (stderr, "Coverage unavailable on this arch.\n");
4356
4357 #endif
4358
4359         mono_lock_free_queue_init (&prof->writer_queue);
4360         mono_os_mutex_init (&prof->method_table_mutex);
4361         prof->method_table = mono_conc_hashtable_new (NULL, NULL);
4362
4363         if (do_coverage)
4364                 coverage_init (prof);
4365         prof->coverage_filters = filters;
4366
4367         prof->startup_time = current_time ();
4368         return prof;
4369 }
4370
4371 static void
4372 usage (int do_exit)
4373 {
4374         printf ("Log profiler version %d.%d (format: %d)\n", LOG_VERSION_MAJOR, LOG_VERSION_MINOR, LOG_DATA_VERSION);
4375         printf ("Usage: mono --profile=log[:OPTION1[,OPTION2...]] program.exe\n");
4376         printf ("Options:\n");
4377         printf ("\thelp                 show this usage info\n");
4378         printf ("\t[no]alloc            enable/disable recording allocation info\n");
4379         printf ("\t[no]calls            enable/disable recording enter/leave method events\n");
4380         printf ("\theapshot[=MODE]      record heap shot info (by default at each major collection)\n");
4381         printf ("\t                     MODE: every XXms milliseconds, every YYgc collections, ondemand\n");
4382         printf ("\tcounters             sample counters every 1s\n");
4383         printf ("\tsample[=TYPE]        use statistical sampling mode (by default cycles/1000)\n");
4384         printf ("\t                     TYPE: cycles,instr,cacherefs,cachemiss,branches,branchmiss\n");
4385         printf ("\t                     TYPE can be followed by /FREQUENCY\n");
4386         printf ("\ttime=fast            use a faster (but more inaccurate) timer\n");
4387         printf ("\tmaxframes=NUM        collect up to NUM stack frames\n");
4388         printf ("\tcalldepth=NUM        ignore method events for call chain depth bigger than NUM\n");
4389         printf ("\toutput=FILENAME      write the data to file FILENAME (-FILENAME to overwrite)\n");
4390         printf ("\toutput=|PROGRAM      write the data to the stdin of PROGRAM\n");
4391         printf ("\t                     %%t is subtituted with date and time, %%p with the pid\n");
4392         printf ("\treport               create a report instead of writing the raw data to a file\n");
4393         printf ("\tzip                  compress the output data\n");
4394         printf ("\tport=PORTNUM         use PORTNUM for the listening command server\n");
4395         printf ("\tcoverage             enable collection of code coverage data\n");
4396         printf ("\tcovfilter=ASSEMBLY   add an assembly to the code coverage filters\n");
4397         printf ("\t                     add a + to include the assembly or a - to exclude it\n");
4398         printf ("\t                     filter=-mscorlib\n");
4399         printf ("\tcovfilter-file=FILE  use FILE to generate the list of assemblies to be filtered\n");
4400         if (do_exit)
4401                 exit (1);
4402 }
4403
4404 static const char*
4405 match_option (const char* p, const char *opt, char **rval)
4406 {
4407         int len = strlen (opt);
4408         if (strncmp (p, opt, len) == 0) {
4409                 if (rval) {
4410                         if (p [len] == '=' && p [len + 1]) {
4411                                 const char *opt = p + len + 1;
4412                                 const char *end = strchr (opt, ',');
4413                                 char *val;
4414                                 int l;
4415                                 if (end == NULL) {
4416                                         l = strlen (opt);
4417                                 } else {
4418                                         l = end - opt;
4419                                 }
4420                                 val = (char *)malloc (l + 1);
4421                                 memcpy (val, opt, l);
4422                                 val [l] = 0;
4423                                 *rval = val;
4424                                 return opt + l;
4425                         }
4426                         if (p [len] == 0 || p [len] == ',') {
4427                                 *rval = NULL;
4428                                 return p + len + (p [len] == ',');
4429                         }
4430                         usage (1);
4431                 } else {
4432                         if (p [len] == 0)
4433                                 return p + len;
4434                         if (p [len] == ',')
4435                                 return p + len + 1;
4436                 }
4437         }
4438         return p;
4439 }
4440
4441 typedef struct {
4442         const char *name;
4443         int sample_mode;
4444 } SampleMode;
4445
4446 static const SampleMode sample_modes [] = {
4447         {"cycles", SAMPLE_CYCLES},
4448         {"instr", SAMPLE_INSTRUCTIONS},
4449         {"cachemiss", SAMPLE_CACHE_MISSES},
4450         {"cacherefs", SAMPLE_CACHE_REFS},
4451         {"branches", SAMPLE_BRANCHES},
4452         {"branchmiss", SAMPLE_BRANCH_MISSES},
4453         {NULL, 0}
4454 };
4455
4456 static void
4457 set_sample_mode (char* val, int allow_empty)
4458 {
4459         char *end;
4460         char *maybe_freq = NULL;
4461         unsigned int count;
4462         const SampleMode *smode = sample_modes;
4463 #ifndef USE_PERF_EVENTS
4464         do_mono_sample = 1;
4465 #endif
4466         if (allow_empty && !val) {
4467                 sample_type = SAMPLE_CYCLES;
4468                 sample_freq = 1000;
4469                 return;
4470         }
4471         if (strcmp (val, "mono") == 0) {
4472                 do_mono_sample = 1;
4473                 sample_type = SAMPLE_CYCLES;
4474                 free (val);
4475                 return;
4476         }
4477         for (smode = sample_modes; smode->name; smode++) {
4478                 int l = strlen (smode->name);
4479                 if (strncmp (val, smode->name, l) == 0) {
4480                         sample_type = smode->sample_mode;
4481                         maybe_freq = val + l;
4482                         break;
4483                 }
4484         }
4485         if (!smode->name)
4486                 usage (1);
4487         if (*maybe_freq == '/') {
4488                 count = strtoul (maybe_freq + 1, &end, 10);
4489                 if (maybe_freq + 1 == end)
4490                         usage (1);
4491                 sample_freq = count;
4492         } else if (*maybe_freq != 0) {
4493                 usage (1);
4494         } else {
4495                 sample_freq = 1000;
4496         }
4497         free (val);
4498 }
4499
4500 static void
4501 set_hsmode (char* val, int allow_empty)
4502 {
4503         char *end;
4504         unsigned int count;
4505         if (allow_empty && !val)
4506                 return;
4507         if (strcmp (val, "ondemand") == 0) {
4508                 hs_mode_ondemand = 1;
4509                 free (val);
4510                 return;
4511         }
4512         count = strtoul (val, &end, 10);
4513         if (val == end)
4514                 usage (1);
4515         if (strcmp (end, "ms") == 0)
4516                 hs_mode_ms = count;
4517         else if (strcmp (end, "gc") == 0)
4518                 hs_mode_gc = count;
4519         else
4520                 usage (1);
4521         free (val);
4522 }
4523
4524 /*
4525  * declaration to silence the compiler: this is the entry point that
4526  * mono will load from the shared library and call.
4527  */
4528 extern void
4529 mono_profiler_startup (const char *desc);
4530
4531 extern void
4532 mono_profiler_startup_log (const char *desc);
4533
4534 /*
4535  * this is the entry point that will be used when the profiler
4536  * is embedded inside the main executable.
4537  */
4538 void
4539 mono_profiler_startup_log (const char *desc)
4540 {
4541         mono_profiler_startup (desc);
4542 }
4543
4544 void
4545 mono_profiler_startup (const char *desc)
4546 {
4547         MonoProfiler *prof;
4548         GPtrArray *filters = NULL;
4549         char *filename = NULL;
4550         const char *p;
4551         const char *opt;
4552         int fast_time = 0;
4553         int calls_enabled = 0;
4554         int allocs_enabled = 0;
4555         int only_counters = 0;
4556         int only_coverage = 0;
4557         int events = MONO_PROFILE_GC|MONO_PROFILE_ALLOCATIONS|
4558                 MONO_PROFILE_GC_MOVES|MONO_PROFILE_CLASS_EVENTS|MONO_PROFILE_THREADS|
4559                 MONO_PROFILE_ENTER_LEAVE|MONO_PROFILE_JIT_COMPILATION|MONO_PROFILE_EXCEPTIONS|
4560                 MONO_PROFILE_MONITOR_EVENTS|MONO_PROFILE_MODULE_EVENTS|MONO_PROFILE_GC_ROOTS|
4561                 MONO_PROFILE_INS_COVERAGE|MONO_PROFILE_APPDOMAIN_EVENTS|MONO_PROFILE_CONTEXT_EVENTS|
4562                 MONO_PROFILE_ASSEMBLY_EVENTS;
4563
4564         p = desc;
4565         if (strncmp (p, "log", 3))
4566                 usage (1);
4567         p += 3;
4568         if (*p == ':')
4569                 p++;
4570         for (; *p; p = opt) {
4571                 char *val;
4572                 if (*p == ',') {
4573                         opt = p + 1;
4574                         continue;
4575                 }
4576                 if ((opt = match_option (p, "help", NULL)) != p) {
4577                         usage (0);
4578                         continue;
4579                 }
4580                 if ((opt = match_option (p, "calls", NULL)) != p) {
4581                         calls_enabled = 1;
4582                         continue;
4583                 }
4584                 if ((opt = match_option (p, "nocalls", NULL)) != p) {
4585                         events &= ~MONO_PROFILE_ENTER_LEAVE;
4586                         nocalls = 1;
4587                         continue;
4588                 }
4589                 if ((opt = match_option (p, "alloc", NULL)) != p) {
4590                         allocs_enabled = 1;
4591                         continue;
4592                 }
4593                 if ((opt = match_option (p, "noalloc", NULL)) != p) {
4594                         events &= ~MONO_PROFILE_ALLOCATIONS;
4595                         continue;
4596                 }
4597                 if ((opt = match_option (p, "time", &val)) != p) {
4598                         if (strcmp (val, "fast") == 0)
4599                                 fast_time = 1;
4600                         else if (strcmp (val, "null") == 0)
4601                                 fast_time = 2;
4602                         else
4603                                 usage (1);
4604                         free (val);
4605                         continue;
4606                 }
4607                 if ((opt = match_option (p, "report", NULL)) != p) {
4608                         do_report = 1;
4609                         continue;
4610                 }
4611                 if ((opt = match_option (p, "debug", NULL)) != p) {
4612                         do_debug = 1;
4613                         continue;
4614                 }
4615                 if ((opt = match_option (p, "sampling-real", NULL)) != p) {
4616                         sampling_mode = MONO_PROFILER_STAT_MODE_REAL;
4617                         continue;
4618                 }
4619                 if ((opt = match_option (p, "sampling-process", NULL)) != p) {
4620                         sampling_mode = MONO_PROFILER_STAT_MODE_PROCESS;
4621                         continue;
4622                 }
4623                 if ((opt = match_option (p, "heapshot", &val)) != p) {
4624                         events &= ~MONO_PROFILE_ALLOCATIONS;
4625                         events &= ~MONO_PROFILE_ENTER_LEAVE;
4626                         nocalls = 1;
4627                         do_heap_shot = 1;
4628                         set_hsmode (val, 1);
4629                         continue;
4630                 }
4631                 if ((opt = match_option (p, "sample", &val)) != p) {
4632                         events &= ~MONO_PROFILE_ALLOCATIONS;
4633                         events &= ~MONO_PROFILE_ENTER_LEAVE;
4634                         nocalls = 1;
4635                         set_sample_mode (val, 1);
4636                         continue;
4637                 }
4638                 if ((opt = match_option (p, "hsmode", &val)) != p) {
4639                         fprintf (stderr, "The hsmode profiler option is obsolete, use heapshot=MODE.\n");
4640                         set_hsmode (val, 0);
4641                         continue;
4642                 }
4643                 if ((opt = match_option (p, "zip", NULL)) != p) {
4644                         use_zip = 1;
4645                         continue;
4646                 }
4647                 if ((opt = match_option (p, "output", &val)) != p) {
4648                         filename = val;
4649                         continue;
4650                 }
4651                 if ((opt = match_option (p, "port", &val)) != p) {
4652                         char *end;
4653                         command_port = strtoul (val, &end, 10);
4654                         free (val);
4655                         continue;
4656                 }
4657                 if ((opt = match_option (p, "maxframes", &val)) != p) {
4658                         char *end;
4659                         num_frames = strtoul (val, &end, 10);
4660                         if (num_frames > MAX_FRAMES)
4661                                 num_frames = MAX_FRAMES;
4662                         free (val);
4663                         notraces = num_frames == 0;
4664                         continue;
4665                 }
4666                 if ((opt = match_option (p, "calldepth", &val)) != p) {
4667                         char *end;
4668                         max_call_depth = strtoul (val, &end, 10);
4669                         free (val);
4670                         continue;
4671                 }
4672                 if ((opt = match_option (p, "counters", NULL)) != p) {
4673                         do_counters = 1;
4674                         continue;
4675                 }
4676                 if ((opt = match_option (p, "countersonly", NULL)) != p) {
4677                         only_counters = 1;
4678                         continue;
4679                 }
4680                 if ((opt = match_option (p, "coverage", NULL)) != p) {
4681                         do_coverage = 1;
4682                         events |= MONO_PROFILE_ENTER_LEAVE;
4683                         debug_coverage = (g_getenv ("MONO_PROFILER_DEBUG_COVERAGE") != NULL);
4684                         continue;
4685                 }
4686                 if ((opt = match_option (p, "onlycoverage", NULL)) != p) {
4687                         only_coverage = 1;
4688                         continue;
4689                 }
4690                 if ((opt = match_option (p, "covfilter-file", &val)) != p) {
4691                         FILE *filter_file;
4692                         char *line, *content;
4693
4694                         if (filters == NULL)
4695                                 filters = g_ptr_array_new ();
4696
4697                         filter_file = fopen (val, "r");
4698                         if (filter_file == NULL) {
4699                                 fprintf (stderr, "Unable to open %s\n", val);
4700                                 exit (0);
4701                         }
4702
4703                         /* Don't need to free content as it is referred to by the lines stored in @filters */
4704                         content = get_file_content (filter_file);
4705                         if (content == NULL)
4706                                 fprintf (stderr, "WARNING: %s is greater than 128kb - ignoring\n", val);
4707
4708                         while ((line = get_next_line (content, &content)))
4709                                 g_ptr_array_add (filters, g_strchug (g_strchomp (line)));
4710
4711                         fclose (filter_file);
4712                         continue;
4713                 }
4714                 if ((opt = match_option (p, "covfilter", &val)) != p) {
4715                         if (filters == NULL)
4716                                 filters = g_ptr_array_new ();
4717
4718                         g_ptr_array_add (filters, val);
4719                         continue;
4720                 }
4721                 if (opt == p) {
4722                         usage (0);
4723                         exit (0);
4724                 }
4725         }
4726         if (calls_enabled) {
4727                 events |= MONO_PROFILE_ENTER_LEAVE;
4728                 nocalls = 0;
4729         }
4730         if (allocs_enabled)
4731                 events |= MONO_PROFILE_ALLOCATIONS;
4732         if (only_counters)
4733                 events = 0;
4734         if (only_coverage)
4735                 events = MONO_PROFILE_ENTER_LEAVE | MONO_PROFILE_INS_COVERAGE;
4736
4737         utils_init (fast_time);
4738
4739         prof = create_profiler (filename, filters);
4740         if (!prof)
4741                 return;
4742         init_thread ();
4743
4744         mono_profiler_install (prof, log_shutdown);
4745         mono_profiler_install_gc (gc_event, gc_resize);
4746         mono_profiler_install_allocation (gc_alloc);
4747         mono_profiler_install_gc_moves (gc_moves);
4748         mono_profiler_install_gc_roots (gc_handle, gc_roots);
4749         mono_profiler_install_appdomain (NULL, domain_loaded, NULL, domain_unloaded);
4750         mono_profiler_install_appdomain_name (domain_name);
4751         mono_profiler_install_context (context_loaded, context_unloaded);
4752         mono_profiler_install_class (NULL, class_loaded, NULL, class_unloaded);
4753         mono_profiler_install_module (NULL, image_loaded, NULL, image_unloaded);
4754         mono_profiler_install_assembly (NULL, assembly_loaded, assembly_unloaded, NULL);
4755         mono_profiler_install_thread (thread_start, thread_end);
4756         mono_profiler_install_thread_name (thread_name);
4757         mono_profiler_install_enter_leave (method_enter, method_leave);
4758         mono_profiler_install_jit_end (method_jitted);
4759         mono_profiler_install_code_buffer_new (code_buffer_new);
4760         mono_profiler_install_exception (throw_exc, method_exc_leave, clause_exc);
4761         mono_profiler_install_monitor (monitor_event);
4762         mono_profiler_install_runtime_initialized (runtime_initialized);
4763         if (do_coverage)
4764                 mono_profiler_install_coverage_filter (coverage_filter);
4765
4766         if (do_mono_sample && sample_type == SAMPLE_CYCLES && !only_counters) {
4767                 events |= MONO_PROFILE_STATISTICAL;
4768                 mono_profiler_set_statistical_mode (sampling_mode, 1000000 / sample_freq);
4769                 mono_profiler_install_statistical (mono_sample_hit);
4770         }
4771
4772         mono_profiler_set_events ((MonoProfileFlags)events);
4773
4774         TLS_INIT (tlsbuffer);
4775         TLS_INIT (tlsmethodlist);
4776 }