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