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