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