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