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