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