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