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