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