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