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