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