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