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