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