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