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