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