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