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