Merge pull request #1972 from esdrubal/proc_pidpath
[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 MonoConcurrentHashTable *coverage_methods = NULL;
3195 static mono_mutex_t coverage_methods_mutex;
3196 static MonoConcurrentHashTable *coverage_assemblies = NULL;
3197 static mono_mutex_t coverage_assemblies_mutex;
3198 static MonoConcurrentHashTable *coverage_classes = NULL;
3199 static mono_mutex_t coverage_classes_mutex;
3200 static MonoConcurrentHashTable *filtered_classes = NULL;
3201 static mono_mutex_t filtered_classes_mutex;
3202 static MonoConcurrentHashTable *entered_methods = NULL;
3203 static mono_mutex_t entered_methods_mutex;
3204 static MonoConcurrentHashTable *image_to_methods = NULL;
3205 static mono_mutex_t image_to_methods_mutex;
3206 static MonoConcurrentHashTable *suppressed_assemblies = NULL;
3207 static mono_mutex_t suppressed_assemblies_mutex;
3208 static gboolean coverage_initialized = FALSE;
3209
3210 static GPtrArray *coverage_data = NULL;
3211 static int previous_offset = 0;
3212
3213 typedef struct _MethodNode MethodNode;
3214 struct _MethodNode {
3215         MonoLockFreeQueueNode node;
3216         MonoMethod *method;
3217 };
3218
3219 typedef struct _CoverageEntry CoverageEntry;
3220 struct _CoverageEntry {
3221         int offset;
3222         int counter;
3223         char *filename;
3224         int line;
3225         int column;
3226 };
3227
3228 static void
3229 free_coverage_entry (gpointer data, gpointer userdata)
3230 {
3231         CoverageEntry *entry = (CoverageEntry *)data;
3232         g_free (entry->filename);
3233         g_free (entry);
3234 }
3235
3236 static void
3237 obtain_coverage_for_method (MonoProfiler *prof, const MonoProfileCoverageEntry *entry)
3238 {
3239         int offset = entry->iloffset - previous_offset;
3240         CoverageEntry *e = g_new (CoverageEntry, 1);
3241
3242         previous_offset = entry->iloffset;
3243
3244         e->offset = offset;
3245         e->counter = entry->counter;
3246         e->filename = g_strdup(entry->filename ? entry->filename : "");
3247         e->line = entry->line;
3248         e->column = entry->col;
3249
3250         g_ptr_array_add (coverage_data, e);
3251 }
3252
3253 static char *
3254 parse_generic_type_names(char *name)
3255 {
3256         char *new_name, *ret;
3257         int within_generic_declaration = 0, generic_members = 1;
3258
3259         if (name == NULL || *name == '\0')
3260                 return g_strdup ("");
3261
3262         if (!(ret = new_name = calloc (strlen (name) * 4 + 1, sizeof (char))))
3263                 return NULL;
3264
3265         do {
3266                 switch (*name) {
3267                         case '<':
3268                                 within_generic_declaration = 1;
3269                                 break;
3270
3271                         case '>':
3272                                 within_generic_declaration = 0;
3273
3274                                 if (*(name - 1) != '<') {
3275                                         *new_name++ = '`';
3276                                         *new_name++ = '0' + generic_members;
3277                                 } else {
3278                                         memcpy (new_name, "&lt;&gt;", 8);
3279                                         new_name += 8;
3280                                 }
3281
3282                                 generic_members = 0;
3283                                 break;
3284
3285                         case ',':
3286                                 generic_members++;
3287                                 break;
3288
3289                         default:
3290                                 if (!within_generic_declaration)
3291                                         *new_name++ = *name;
3292
3293                                 break;
3294                 }
3295         } while (*name++);
3296
3297         return ret;
3298 }
3299
3300 static int method_id;
3301 static void
3302 build_method_buffer (gpointer key, gpointer value, gpointer userdata)
3303 {
3304         MonoMethod *method = (MonoMethod *)value;
3305         MonoProfiler *prof = (MonoProfiler *)userdata;
3306         MonoClass *klass;
3307         MonoImage *image;
3308         char *class_name;
3309         const char *image_name, *method_name, *sig, *first_filename;
3310         LogBuffer *logbuffer;
3311         guint i;
3312
3313         previous_offset = 0;
3314         coverage_data = g_ptr_array_new ();
3315
3316         mono_profiler_coverage_get (prof, method, obtain_coverage_for_method);
3317
3318         klass = mono_method_get_class (method);
3319         image = mono_class_get_image (klass);
3320         image_name = mono_image_get_name (image);
3321
3322         sig = mono_signature_get_desc (mono_method_signature (method), TRUE);
3323         class_name = parse_generic_type_names (mono_type_get_name (mono_class_get_type (klass)));
3324         method_name = mono_method_get_name (method);
3325
3326         if (coverage_data->len != 0) {
3327                 CoverageEntry *entry = coverage_data->pdata[0];
3328                 first_filename = entry->filename ? entry->filename : "";
3329         } else
3330                 first_filename = "";
3331
3332         image_name = image_name ? image_name : "";
3333         sig = sig ? sig : "";
3334         method_name = method_name ? method_name : "";
3335
3336         logbuffer = ensure_logbuf (
3337                 EVENT_SIZE /* event */ +
3338                 strlen (image_name) + 1 /* image name */ +
3339                 strlen (class_name) + 1 /* class name */ +
3340                 strlen (method_name) + 1 /* method name */ +
3341                 strlen (sig) + 1 /* signature */ +
3342                 strlen (first_filename) + 1 /* first file name */ +
3343                 LEB128_SIZE /* token */ +
3344                 LEB128_SIZE /* method id */ +
3345                 LEB128_SIZE /* entries */
3346         );
3347         ENTER_LOG (logbuffer, "coverage-methods");
3348
3349         emit_byte (logbuffer, TYPE_COVERAGE_METHOD | TYPE_COVERAGE);
3350         emit_string (logbuffer, image_name, strlen (image_name) + 1);
3351         emit_string (logbuffer, class_name, strlen (class_name) + 1);
3352         emit_string (logbuffer, method_name, strlen (method_name) + 1);
3353         emit_string (logbuffer, sig, strlen (sig) + 1);
3354         emit_string (logbuffer, first_filename, strlen (first_filename) + 1);
3355
3356         emit_uvalue (logbuffer, mono_method_get_token (method));
3357         emit_uvalue (logbuffer, method_id);
3358         emit_value (logbuffer, coverage_data->len);
3359
3360         EXIT_LOG (logbuffer);
3361         safe_send (prof, logbuffer);
3362
3363         for (i = 0; i < coverage_data->len; i++) {
3364                 CoverageEntry *entry = coverage_data->pdata[i];
3365
3366                 logbuffer = ensure_logbuf (
3367                         EVENT_SIZE /* event */ +
3368                         LEB128_SIZE /* method id */ +
3369                         LEB128_SIZE /* offset */ +
3370                         LEB128_SIZE /* counter */ +
3371                         LEB128_SIZE /* line */ +
3372                         LEB128_SIZE /* column */
3373                 );
3374                 ENTER_LOG (logbuffer, "coverage-statement");
3375
3376                 emit_byte (logbuffer, TYPE_COVERAGE_STATEMENT | TYPE_COVERAGE);
3377                 emit_uvalue (logbuffer, method_id);
3378                 emit_uvalue (logbuffer, entry->offset);
3379                 emit_uvalue (logbuffer, entry->counter);
3380                 emit_uvalue (logbuffer, entry->line);
3381                 emit_uvalue (logbuffer, entry->column);
3382
3383                 EXIT_LOG (logbuffer);
3384                 safe_send (prof, logbuffer);
3385         }
3386
3387         method_id++;
3388
3389         g_free (class_name);
3390
3391         g_ptr_array_foreach (coverage_data, free_coverage_entry, NULL);
3392         g_ptr_array_free (coverage_data, TRUE);
3393         coverage_data = NULL;
3394 }
3395
3396 /* This empties the queue */
3397 static guint
3398 count_queue (MonoLockFreeQueue *queue)
3399 {
3400         MonoLockFreeQueueNode *node;
3401         guint count = 0;
3402
3403         while ((node = mono_lock_free_queue_dequeue (queue))) {
3404                 count++;
3405                 mono_lock_free_queue_node_free (node);
3406         }
3407
3408         return count;
3409 }
3410
3411 static void
3412 build_class_buffer (gpointer key, gpointer value, gpointer userdata)
3413 {
3414         MonoClass *klass = (MonoClass *)key;
3415         MonoLockFreeQueue *class_methods = (MonoLockFreeQueue *)value;
3416         MonoProfiler *prof = (MonoProfiler *)userdata;
3417         MonoImage *image;
3418         char *class_name;
3419         const char *assembly_name;
3420         int number_of_methods, partially_covered;
3421         guint fully_covered;
3422         LogBuffer *logbuffer;
3423
3424         image = mono_class_get_image (klass);
3425         assembly_name = mono_image_get_name (image);
3426         class_name = mono_type_get_name (mono_class_get_type (klass));
3427
3428         assembly_name = assembly_name ? assembly_name : "";
3429         number_of_methods = mono_class_num_methods (klass);
3430         fully_covered = count_queue (class_methods);
3431         /* We don't handle partial covered yet */
3432         partially_covered = 0;
3433
3434         logbuffer = ensure_logbuf (
3435                 EVENT_SIZE /* event */ +
3436                 strlen (assembly_name) + 1 /* assembly name */ +
3437                 strlen (class_name) + 1 /* class name */ +
3438                 LEB128_SIZE /* no. methods */ +
3439                 LEB128_SIZE /* fully covered */ +
3440                 LEB128_SIZE /* partially covered */
3441         );
3442
3443         ENTER_LOG (logbuffer, "coverage-class");
3444         emit_byte (logbuffer, TYPE_COVERAGE_CLASS | TYPE_COVERAGE);
3445         emit_string (logbuffer, assembly_name, strlen (assembly_name) + 1);
3446         emit_string (logbuffer, class_name, strlen (class_name) + 1);
3447         emit_uvalue (logbuffer, number_of_methods);
3448         emit_uvalue (logbuffer, fully_covered);
3449         emit_uvalue (logbuffer, partially_covered);
3450         EXIT_LOG (logbuffer);
3451
3452         safe_send (prof, logbuffer);
3453
3454         g_free (class_name);
3455 }
3456
3457 static void
3458 get_coverage_for_image (MonoImage *image, int *number_of_methods, guint *fully_covered, int *partially_covered)
3459 {
3460         MonoLockFreeQueue *image_methods = mono_conc_hashtable_lookup (image_to_methods, image);
3461
3462         *number_of_methods = mono_image_get_table_rows (image, MONO_TABLE_METHOD);
3463         if (image_methods)
3464                 *fully_covered = count_queue (image_methods);
3465         else
3466                 *fully_covered = 0;
3467
3468         // FIXME: We don't handle partially covered yet.
3469         *partially_covered = 0;
3470 }
3471
3472 static void
3473 build_assembly_buffer (gpointer key, gpointer value, gpointer userdata)
3474 {
3475         MonoAssembly *assembly = (MonoAssembly *)value;
3476         MonoProfiler *prof = (MonoProfiler *)userdata;
3477         MonoImage *image = mono_assembly_get_image (assembly);
3478         LogBuffer *logbuffer;
3479         const char *name, *guid, *filename;
3480         int number_of_methods = 0, partially_covered = 0;
3481         guint fully_covered = 0;
3482
3483         name = mono_image_get_name (image);
3484         guid = mono_image_get_guid (image);
3485         filename = mono_image_get_filename (image);
3486
3487         name = name ? name : "";
3488         guid = guid ? guid : "";
3489         filename = filename ? filename : "";
3490
3491         get_coverage_for_image (image, &number_of_methods, &fully_covered, &partially_covered);
3492
3493         logbuffer = ensure_logbuf (
3494                 EVENT_SIZE /* event */ +
3495                 strlen (name) + 1 /* name */ +
3496                 strlen (guid) + 1 /* guid */ +
3497                 strlen (filename) + 1 /* file name */ +
3498                 LEB128_SIZE /* no. methods */ +
3499                 LEB128_SIZE /* fully covered */ +
3500                 LEB128_SIZE /* partially covered */
3501         );
3502
3503         ENTER_LOG (logbuffer, "coverage-assemblies");
3504         emit_byte (logbuffer, TYPE_COVERAGE_ASSEMBLY | TYPE_COVERAGE);
3505         emit_string (logbuffer, name, strlen (name) + 1);
3506         emit_string (logbuffer, guid, strlen (guid) + 1);
3507         emit_string (logbuffer, filename, strlen (filename) + 1);
3508         emit_uvalue (logbuffer, number_of_methods);
3509         emit_uvalue (logbuffer, fully_covered);
3510         emit_uvalue (logbuffer, partially_covered);
3511         EXIT_LOG (logbuffer);
3512
3513         safe_send (prof, logbuffer);
3514 }
3515
3516 static void
3517 dump_coverage (MonoProfiler *prof)
3518 {
3519         if (!coverage_initialized)
3520                 return;
3521
3522         COVERAGE_DEBUG(fprintf (stderr, "Coverage: Started dump\n");)
3523         method_id = 0;
3524
3525         mono_conc_hashtable_foreach (coverage_assemblies, build_assembly_buffer, prof);
3526         mono_conc_hashtable_foreach (coverage_classes, build_class_buffer, prof);
3527         mono_conc_hashtable_foreach (coverage_methods, build_method_buffer, prof);
3528
3529         COVERAGE_DEBUG(fprintf (stderr, "Coverage: Finished dump\n");)
3530 }
3531
3532 static void
3533 process_method_enter_coverage (MonoProfiler *prof, MonoMethod *method)
3534 {
3535         MonoClass *klass;
3536         MonoImage *image;
3537
3538         if (!coverage_initialized)
3539                 return;
3540
3541         klass = mono_method_get_class (method);
3542         image = mono_class_get_image (klass);
3543
3544         if (mono_conc_hashtable_lookup (suppressed_assemblies, (gpointer) mono_image_get_name (image)))
3545                 return;
3546
3547         mono_conc_hashtable_insert (entered_methods, method, method);
3548 }
3549
3550 static MonoLockFreeQueueNode *
3551 create_method_node (MonoMethod *method)
3552 {
3553         MethodNode *node = g_malloc (sizeof (MethodNode));
3554         mono_lock_free_queue_node_init ((MonoLockFreeQueueNode *) node, FALSE);
3555         node->method = method;
3556
3557         return (MonoLockFreeQueueNode *) node;
3558 }
3559
3560 static gboolean
3561 coverage_filter (MonoProfiler *prof, MonoMethod *method)
3562 {
3563         MonoClass *klass;
3564         MonoImage *image;
3565         MonoAssembly *assembly;
3566         MonoMethodHeader *header;
3567         guint32 iflags, flags, code_size;
3568         char *fqn, *classname;
3569         gboolean has_positive, found;
3570         MonoLockFreeQueue *image_methods, *class_methods;
3571         MonoLockFreeQueueNode *node;
3572
3573         if (!coverage_initialized)
3574                 return FALSE;
3575
3576         COVERAGE_DEBUG(fprintf (stderr, "Coverage filter for %s\n", mono_method_get_name (method));)
3577
3578         flags = mono_method_get_flags (method, &iflags);
3579         if ((iflags & 0x1000 /*METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL*/) ||
3580             (flags & 0x2000 /*METHOD_ATTRIBUTE_PINVOKE_IMPL*/)) {
3581                 COVERAGE_DEBUG(fprintf (stderr, "   Internal call or pinvoke - ignoring\n");)
3582                 return FALSE;
3583         }
3584
3585         // Don't need to do anything else if we're already tracking this method
3586         if (mono_conc_hashtable_lookup (coverage_methods, method)) {
3587                 COVERAGE_DEBUG(fprintf (stderr, "   Already tracking\n");)
3588                 return TRUE;
3589         }
3590
3591         klass = mono_method_get_class (method);
3592         image = mono_class_get_image (klass);
3593
3594         // Don't handle coverage for the core assemblies
3595         if (mono_conc_hashtable_lookup (suppressed_assemblies, (gpointer) mono_image_get_name (image)) != NULL)
3596                 return FALSE;
3597
3598         if (prof->coverage_filters) {
3599                 /* Check already filtered classes first */
3600                 if (mono_conc_hashtable_lookup (filtered_classes, klass)) {
3601                         COVERAGE_DEBUG(fprintf (stderr, "   Already filtered\n");)
3602                         return FALSE;
3603                 }
3604
3605                 classname = mono_type_get_name (mono_class_get_type (klass));
3606
3607                 fqn = g_strdup_printf ("[%s]%s", mono_image_get_name (image), classname);
3608
3609                 COVERAGE_DEBUG(fprintf (stderr, "   Looking for %s in filter\n", fqn);)
3610                 // Check positive filters first
3611                 has_positive = FALSE;
3612                 found = FALSE;
3613                 for (guint i = 0; i < prof->coverage_filters->len; ++i) {
3614                         char *filter = g_ptr_array_index (prof->coverage_filters, i);
3615
3616                         if (filter [0] == '+') {
3617                                 filter = &filter [1];
3618
3619                                 COVERAGE_DEBUG(fprintf (stderr, "   Checking against +%s ...", filter);)
3620
3621                                 if (strstr (fqn, filter) != NULL) {
3622                                         COVERAGE_DEBUG(fprintf (stderr, "matched\n");)
3623                                         found = TRUE;
3624                                 } else
3625                                         COVERAGE_DEBUG(fprintf (stderr, "no match\n");)
3626
3627                                 has_positive = TRUE;
3628                         }
3629                 }
3630
3631                 if (has_positive && !found) {
3632                         COVERAGE_DEBUG(fprintf (stderr, "   Positive match was not found\n");)
3633
3634                         mono_conc_hashtable_insert (filtered_classes, klass, klass);
3635                         g_free (fqn);
3636                         g_free (classname);
3637
3638                         return FALSE;
3639                 }
3640
3641                 for (guint i = 0; i < prof->coverage_filters->len; ++i) {
3642                         // FIXME: Is substring search sufficient?
3643                         char *filter = g_ptr_array_index (prof->coverage_filters, i);
3644                         if (filter [0] == '+')
3645                                 continue;
3646
3647                         // Skip '-'
3648                         filter = &filter [1];
3649                         COVERAGE_DEBUG(fprintf (stderr, "   Checking against -%s ...", filter);)
3650
3651                         if (strstr (fqn, filter) != NULL) {
3652                                 COVERAGE_DEBUG(fprintf (stderr, "matched\n");)
3653
3654                                 mono_conc_hashtable_insert (filtered_classes, klass, klass);
3655                                 g_free (fqn);
3656                                 g_free (classname);
3657
3658                                 return FALSE;
3659                         } else
3660                                 COVERAGE_DEBUG(fprintf (stderr, "no match\n");)
3661
3662                 }
3663
3664                 g_free (fqn);
3665                 g_free (classname);
3666         }
3667
3668         COVERAGE_DEBUG(fprintf (stderr, "   Handling coverage for %s\n", mono_method_get_name (method));)
3669         header = mono_method_get_header (method);
3670
3671         mono_method_header_get_code (header, &code_size, NULL);
3672
3673         assembly = mono_image_get_assembly (image);
3674
3675         mono_conc_hashtable_insert (coverage_methods, method, method);
3676         mono_conc_hashtable_insert (coverage_assemblies, assembly, assembly);
3677
3678         image_methods = mono_conc_hashtable_lookup (image_to_methods, image);
3679
3680         if (image_methods == NULL) {
3681                 image_methods = g_malloc (sizeof (MonoLockFreeQueue));
3682                 mono_lock_free_queue_init (image_methods);
3683                 mono_conc_hashtable_insert (image_to_methods, image, image_methods);
3684         }
3685
3686         node = create_method_node (method);
3687         mono_lock_free_queue_enqueue (image_methods, node);
3688
3689         class_methods = mono_conc_hashtable_lookup (coverage_classes, klass);
3690
3691         if (class_methods == NULL) {
3692                 class_methods = g_malloc (sizeof (MonoLockFreeQueue));
3693                 mono_lock_free_queue_init (class_methods);
3694                 mono_conc_hashtable_insert (coverage_classes, klass, class_methods);
3695         }
3696
3697         node = create_method_node (method);
3698         mono_lock_free_queue_enqueue (class_methods, node);
3699
3700         return TRUE;
3701 }
3702
3703 #define LINE_BUFFER_SIZE 4096
3704 /* Max file limit of 128KB */
3705 #define MAX_FILE_SIZE 128 * 1024
3706 static char *
3707 get_file_content (FILE *stream)
3708 {
3709         char *buffer;
3710         ssize_t bytes_read;
3711         long filesize;
3712         int res, offset = 0;
3713
3714         res = fseek (stream, 0, SEEK_END);
3715         if (res < 0)
3716           return NULL;
3717
3718         filesize = ftell (stream);
3719         if (filesize < 0)
3720           return NULL;
3721
3722         res = fseek (stream, 0, SEEK_SET);
3723         if (res < 0)
3724           return NULL;
3725
3726         if (filesize > MAX_FILE_SIZE)
3727           return NULL;
3728
3729         buffer = g_malloc ((filesize + 1) * sizeof (char));
3730         while ((bytes_read = fread (buffer + offset, 1, LINE_BUFFER_SIZE, stream)) > 0)
3731                 offset += bytes_read;
3732
3733         /* NULL terminate our buffer */
3734         buffer[filesize] = '\0';
3735         return buffer;
3736 }
3737
3738 static char *
3739 get_next_line (char *contents, char **next_start)
3740 {
3741         char *p = contents;
3742
3743         if (p == NULL || *p == '\0') {
3744                 *next_start = NULL;
3745                 return NULL;
3746         }
3747
3748         while (*p != '\n' && *p != '\0')
3749                 p++;
3750
3751         if (*p == '\n') {
3752                 *p = '\0';
3753                 *next_start = p + 1;
3754         } else
3755                 *next_start = NULL;
3756
3757         return contents;
3758 }
3759
3760 static void
3761 init_suppressed_assemblies (void)
3762 {
3763         char *content;
3764         char *line;
3765         FILE *sa_file;
3766
3767         mono_mutex_init (&suppressed_assemblies_mutex);
3768         suppressed_assemblies = mono_conc_hashtable_new (&suppressed_assemblies_mutex, g_str_hash, g_str_equal);
3769         sa_file = fopen (SUPPRESSION_DIR "/mono-profiler-log.suppression", "r");
3770         if (sa_file == NULL)
3771                 return;
3772
3773         /* Don't need to free @content as it is referred to by the lines stored in @suppressed_assemblies */
3774         content = get_file_content (sa_file);
3775         if (content == NULL) {
3776                 g_error ("mono-profiler-log.suppression is greater than 128kb - aborting\n");
3777         }
3778
3779         while ((line = get_next_line (content, &content))) {
3780                 line = g_strchomp (g_strchug (line));
3781                 mono_conc_hashtable_insert (suppressed_assemblies, line, line);
3782         }
3783
3784         fclose (sa_file);
3785 }
3786
3787 static MonoConcurrentHashTable *
3788 init_hashtable (mono_mutex_t *mutex)
3789 {
3790         mono_mutex_init (mutex);
3791         return mono_conc_hashtable_new (mutex, NULL, NULL);
3792 }
3793
3794 static void
3795 destroy_hashtable (MonoConcurrentHashTable *hashtable, mono_mutex_t *mutex)
3796 {
3797         mono_conc_hashtable_destroy (hashtable);
3798         mono_mutex_destroy (mutex);
3799 }
3800
3801 #endif /* DISABLE_HELPER_THREAD */
3802
3803 static void
3804 coverage_init (MonoProfiler *prof)
3805 {
3806 #ifndef DISABLE_HELPER_THREAD
3807         assert (!coverage_initialized);
3808
3809         COVERAGE_DEBUG(fprintf (stderr, "Coverage initialized\n");)
3810
3811         coverage_methods = init_hashtable (&coverage_methods_mutex);
3812         coverage_assemblies = init_hashtable (&coverage_assemblies_mutex);
3813         coverage_classes = init_hashtable (&coverage_classes_mutex);
3814         filtered_classes = init_hashtable (&filtered_classes_mutex);
3815         entered_methods = init_hashtable (&entered_methods_mutex);
3816         image_to_methods = init_hashtable (&image_to_methods_mutex);
3817         init_suppressed_assemblies ();
3818
3819         coverage_initialized = TRUE;
3820 #endif /* DISABLE_HELPER_THREAD */
3821 }
3822
3823 static void
3824 log_shutdown (MonoProfiler *prof)
3825 {
3826         void *res;
3827
3828         in_shutdown = 1;
3829 #ifndef DISABLE_HELPER_THREAD
3830         counters_and_perfcounters_sample (prof);
3831
3832         dump_coverage (prof);
3833
3834         if (prof->command_port) {
3835                 char c = 1;
3836                 ign_res (write (prof->pipes [1], &c, 1));
3837                 pthread_join (prof->helper_thread, &res);
3838         }
3839 #endif
3840 #if USE_PERF_EVENTS
3841         if (perf_data) {
3842                 int i;
3843                 for (i = 0; i < num_perf; ++i)
3844                         read_perf_mmap (prof, i);
3845         }
3846 #endif
3847
3848         g_ptr_array_free (prof->sorted_sample_events, TRUE);
3849
3850         if (TLS_GET (LogBuffer, tlsbuffer))
3851                 send_buffer (prof, TLS_GET (GPtrArray, tlsmethodlist), TLS_GET (LogBuffer, tlsbuffer));
3852
3853         TLS_SET (tlsbuffer, NULL);
3854         TLS_SET (tlsmethodlist, NULL);
3855
3856         InterlockedWrite (&prof->run_writer_thread, 0);
3857         pthread_join (prof->writer_thread, &res);
3858
3859 #if defined (HAVE_SYS_ZLIB)
3860         if (prof->gzfile)
3861                 gzclose (prof->gzfile);
3862 #endif
3863         if (prof->pipe_output)
3864                 pclose (prof->file);
3865         else
3866                 fclose (prof->file);
3867
3868         destroy_hashtable (prof->method_table, &prof->method_table_mutex);
3869
3870         if (coverage_initialized) {
3871                 destroy_hashtable (coverage_methods, &coverage_methods_mutex);
3872                 destroy_hashtable (coverage_assemblies, &coverage_assemblies_mutex);
3873                 destroy_hashtable (coverage_classes, &coverage_classes_mutex);
3874                 destroy_hashtable (filtered_classes, &filtered_classes_mutex);
3875                 destroy_hashtable (entered_methods, &entered_methods_mutex);
3876                 destroy_hashtable (image_to_methods, &image_to_methods_mutex);
3877                 destroy_hashtable (suppressed_assemblies, &suppressed_assemblies_mutex);
3878         }
3879
3880         free (prof);
3881 }
3882
3883 static char*
3884 new_filename (const char* filename)
3885 {
3886         time_t t = time (NULL);
3887         int pid = process_id ();
3888         char pid_buf [16];
3889         char time_buf [16];
3890         char *res, *d;
3891         const char *p;
3892         int count_dates = 0;
3893         int count_pids = 0;
3894         int s_date, s_pid;
3895         struct tm *ts;
3896         for (p = filename; *p; p++) {
3897                 if (*p != '%')
3898                         continue;
3899                 p++;
3900                 if (*p == 't')
3901                         count_dates++;
3902                 else if (*p == 'p')
3903                         count_pids++;
3904                 else if (*p == 0)
3905                         break;
3906         }
3907         if (!count_dates && !count_pids)
3908                 return pstrdup (filename);
3909         snprintf (pid_buf, sizeof (pid_buf), "%d", pid);
3910         ts = gmtime (&t);
3911         snprintf (time_buf, sizeof (time_buf), "%d%02d%02d%02d%02d%02d",
3912                 1900 + ts->tm_year, 1 + ts->tm_mon, ts->tm_mday, ts->tm_hour, ts->tm_min, ts->tm_sec);
3913         s_date = strlen (time_buf);
3914         s_pid = strlen (pid_buf);
3915         d = res = malloc (strlen (filename) + s_date * count_dates + s_pid * count_pids);
3916         for (p = filename; *p; p++) {
3917                 if (*p != '%') {
3918                         *d++ = *p;
3919                         continue;
3920                 }
3921                 p++;
3922                 if (*p == 't') {
3923                         strcpy (d, time_buf);
3924                         d += s_date;
3925                         continue;
3926                 } else if (*p == 'p') {
3927                         strcpy (d, pid_buf);
3928                         d += s_pid;
3929                         continue;
3930                 } else if (*p == '%') {
3931                         *d++ = '%';
3932                         continue;
3933                 } else if (*p == 0)
3934                         break;
3935                 *d++ = '%';
3936                 *d++ = *p;
3937         }
3938         *d = 0;
3939         return res;
3940 }
3941
3942 //this is exposed by the JIT, but it's not meant to be a supported API for now.
3943 extern void mono_threads_attach_tools_thread (void);
3944
3945 #ifndef DISABLE_HELPER_THREAD
3946
3947 static void*
3948 helper_thread (void* arg)
3949 {
3950         MonoProfiler* prof = arg;
3951         int command_socket;
3952         int len;
3953         char buf [64];
3954         MonoThread *thread = NULL;
3955
3956         mono_threads_attach_tools_thread ();
3957         //fprintf (stderr, "Server listening\n");
3958         command_socket = -1;
3959         while (1) {
3960                 fd_set rfds;
3961                 struct timeval tv;
3962                 int max_fd = -1;
3963                 FD_ZERO (&rfds);
3964                 FD_SET (prof->server_socket, &rfds);
3965                 max_fd = prof->server_socket;
3966                 FD_SET (prof->pipes [0], &rfds);
3967                 if (max_fd < prof->pipes [0])
3968                         max_fd = prof->pipes [0];
3969                 if (command_socket >= 0) {
3970                         FD_SET (command_socket, &rfds);
3971                         if (max_fd < command_socket)
3972                                 max_fd = command_socket;
3973                 }
3974 #if USE_PERF_EVENTS
3975                 if (perf_data) {
3976                         int i;
3977                         for ( i = 0; i < num_perf; ++i) {
3978                                 if (perf_data [i].perf_fd < 0)
3979                                         continue;
3980                                 FD_SET (perf_data [i].perf_fd, &rfds);
3981                                 if (max_fd < perf_data [i].perf_fd)
3982                                         max_fd = perf_data [i].perf_fd;
3983                         }
3984                 }
3985 #endif
3986
3987                 counters_and_perfcounters_sample (prof);
3988
3989                 tv.tv_sec = 1;
3990                 tv.tv_usec = 0;
3991                 len = select (max_fd + 1, &rfds, NULL, NULL, &tv);
3992
3993                 if (len < 0) {
3994                         if (errno == EINTR)
3995                                 continue;
3996
3997                         g_warning ("Error in proflog server: %s", strerror (errno));
3998                         return NULL;
3999                 }
4000
4001                 if (FD_ISSET (prof->pipes [0], &rfds)) {
4002                         char c;
4003                         int r = read (prof->pipes [0], &c, 1);
4004                         if (r == 1 && c == 0) {
4005                                 StatBuffer *sbufbase = prof->stat_buffers;
4006                                 StatBuffer *sbuf;
4007                                 if (!sbufbase->next)
4008                                         continue;
4009                                 sbuf = sbufbase->next->next;
4010                                 sbufbase->next->next = NULL;
4011                                 if (do_debug)
4012                                         fprintf (stderr, "stat buffer dump\n");
4013                                 if (sbuf) {
4014                                         dump_sample_hits (prof, sbuf);
4015                                         free_buffer (sbuf, sbuf->size);
4016                                         safe_send (prof, ensure_logbuf (0));
4017                                 }
4018                                 continue;
4019                         }
4020                         /* time to shut down */
4021                         dump_sample_hits (prof, prof->stat_buffers);
4022                         if (thread)
4023                                 mono_thread_detach (thread);
4024                         if (do_debug)
4025                                 fprintf (stderr, "helper shutdown\n");
4026 #if USE_PERF_EVENTS
4027                         if (perf_data) {
4028                                 int i;
4029                                 for ( i = 0; i < num_perf; ++i) {
4030                                         if (perf_data [i].perf_fd < 0)
4031                                                 continue;
4032                                         if (FD_ISSET (perf_data [i].perf_fd, &rfds))
4033                                                 read_perf_mmap (prof, i);
4034                                 }
4035                         }
4036 #endif
4037                         safe_send (prof, ensure_logbuf (0));
4038                         return NULL;
4039                 }
4040 #if USE_PERF_EVENTS
4041                 if (perf_data) {
4042                         int i;
4043                         for ( i = 0; i < num_perf; ++i) {
4044                                 if (perf_data [i].perf_fd < 0)
4045                                         continue;
4046                                 if (FD_ISSET (perf_data [i].perf_fd, &rfds)) {
4047                                         read_perf_mmap (prof, i);
4048                                         safe_send (prof, ensure_logbuf (0));
4049                                 }
4050                         }
4051                 }
4052 #endif
4053                 if (command_socket >= 0 && FD_ISSET (command_socket, &rfds)) {
4054                         len = read (command_socket, buf, sizeof (buf) - 1);
4055                         if (len < 0)
4056                                 continue;
4057                         if (len == 0) {
4058                                 close (command_socket);
4059                                 command_socket = -1;
4060                                 continue;
4061                         }
4062                         buf [len] = 0;
4063                         if (strcmp (buf, "heapshot\n") == 0) {
4064                                 heapshot_requested = 1;
4065                                 //fprintf (stderr, "perform heapshot\n");
4066                                 if (InterlockedRead (&runtime_inited) && !thread) {
4067                                         thread = mono_thread_attach (mono_get_root_domain ());
4068                                         /*fprintf (stderr, "attached\n");*/
4069                                 }
4070                                 if (thread) {
4071                                         process_requests (prof);
4072                                         mono_thread_detach (thread);
4073                                         thread = NULL;
4074                                 }
4075                         }
4076                         continue;
4077                 }
4078                 if (!FD_ISSET (prof->server_socket, &rfds)) {
4079                         continue;
4080                 }
4081                 command_socket = accept (prof->server_socket, NULL, NULL);
4082                 if (command_socket < 0)
4083                         continue;
4084                 //fprintf (stderr, "Accepted connection\n");
4085         }
4086         return NULL;
4087 }
4088
4089 static int
4090 start_helper_thread (MonoProfiler* prof)
4091 {
4092         struct sockaddr_in server_address;
4093         int r;
4094         socklen_t slen;
4095         if (pipe (prof->pipes) < 0) {
4096                 fprintf (stderr, "Cannot create pipe\n");
4097                 return 0;
4098         }
4099         prof->server_socket = socket (PF_INET, SOCK_STREAM, 0);
4100         if (prof->server_socket < 0) {
4101                 fprintf (stderr, "Cannot create server socket\n");
4102                 return 0;
4103         }
4104         memset (&server_address, 0, sizeof (server_address));
4105         server_address.sin_family = AF_INET;
4106         server_address.sin_addr.s_addr = INADDR_ANY;
4107         server_address.sin_port = htons (prof->command_port);
4108         if (bind (prof->server_socket, (struct sockaddr *) &server_address, sizeof (server_address)) < 0) {
4109                 fprintf (stderr, "Cannot bind server socket, port: %d: %s\n", prof->command_port, strerror (errno));
4110                 close (prof->server_socket);
4111                 return 0;
4112         }
4113         if (listen (prof->server_socket, 1) < 0) {
4114                 fprintf (stderr, "Cannot listen server socket\n");
4115                 close (prof->server_socket);
4116                 return 0;
4117         }
4118         slen = sizeof (server_address);
4119         if (getsockname (prof->server_socket, (struct sockaddr *)&server_address, &slen) == 0) {
4120                 prof->command_port = ntohs (server_address.sin_port);
4121                 /*fprintf (stderr, "Assigned server port: %d\n", prof->command_port);*/
4122         }
4123
4124         r = pthread_create (&prof->helper_thread, NULL, helper_thread, prof);
4125         if (r) {
4126                 close (prof->server_socket);
4127                 return 0;
4128         }
4129         return 1;
4130 }
4131 #endif
4132
4133 static void *
4134 writer_thread (void *arg)
4135 {
4136         MonoProfiler *prof = arg;
4137
4138         mono_threads_attach_tools_thread ();
4139
4140         dump_header (prof);
4141
4142         while (InterlockedRead (&prof->run_writer_thread)) {
4143                 WriterQueueEntry *entry;
4144
4145                 while ((entry = (WriterQueueEntry *) mono_lock_free_queue_dequeue (&prof->writer_queue))) {
4146                         LogBuffer *method_buffer = NULL;
4147                         gboolean new_methods = FALSE;
4148
4149                         if (entry->methods->len)
4150                                 method_buffer = create_buffer ();
4151
4152                         /*
4153                          * Encode the method events in a temporary log buffer that we
4154                          * flush to disk before the main buffer, ensuring that all
4155                          * methods have metadata emitted before they're referenced.
4156                          */
4157                         for (guint i = 0; i < entry->methods->len; i++) {
4158                                 MethodInfo *info = g_ptr_array_index (entry->methods, i);
4159
4160                                 if (mono_conc_hashtable_lookup (prof->method_table, info->method))
4161                                         continue;
4162
4163                                 new_methods = TRUE;
4164
4165                                 /*
4166                                  * Other threads use this hash table to get a general
4167                                  * idea of whether a method has already been emitted to
4168                                  * the stream. Due to the way we add to this table, it
4169                                  * can easily happen that multiple threads queue up the
4170                                  * same methods, but that's OK since eventually all
4171                                  * methods will be in this table and the thread-local
4172                                  * method lists will just be empty for the rest of the
4173                                  * app's lifetime.
4174                                  */
4175                                 mono_conc_hashtable_insert (prof->method_table, info->method, info->method);
4176
4177                                 char *name = mono_method_full_name (info->method, 1);
4178                                 int nlen = strlen (name) + 1;
4179                                 uint64_t now = current_time ();
4180
4181                                 method_buffer = ensure_logbuf_inner (method_buffer,
4182                                         EVENT_SIZE /* event */ +
4183                                         LEB128_SIZE /* time */ +
4184                                         LEB128_SIZE /* method */ +
4185                                         LEB128_SIZE /* start */ +
4186                                         LEB128_SIZE /* size */ +
4187                                         nlen /* name */
4188                                 );
4189
4190                                 emit_byte (method_buffer, TYPE_JIT | TYPE_METHOD);
4191                                 emit_time (method_buffer, now);
4192                                 emit_method_inner (method_buffer, info->method);
4193                                 emit_ptr (method_buffer, mono_jit_info_get_code_start (info->ji));
4194                                 emit_value (method_buffer, mono_jit_info_get_code_size (info->ji));
4195
4196                                 memcpy (method_buffer->data, name, nlen);
4197                                 method_buffer->data += nlen;
4198
4199                                 mono_free (name);
4200                                 free (info);
4201                         }
4202
4203                         g_ptr_array_free (entry->methods, TRUE);
4204
4205                         if (new_methods)
4206                                 dump_buffer (prof, method_buffer);
4207                         else if (method_buffer)
4208                                 free_buffer (method_buffer, method_buffer->size);
4209
4210                         dump_buffer (prof, entry->buffer);
4211
4212                         free (entry);
4213                 }
4214         }
4215
4216         return NULL;
4217 }
4218
4219 static int
4220 start_writer_thread (MonoProfiler* prof)
4221 {
4222         InterlockedWrite (&prof->run_writer_thread, 1);
4223
4224         return !pthread_create (&prof->writer_thread, NULL, writer_thread, prof);
4225 }
4226
4227 static void
4228 runtime_initialized (MonoProfiler *profiler)
4229 {
4230 #ifndef DISABLE_HELPER_THREAD
4231         if (hs_mode_ondemand || need_helper_thread) {
4232                 if (!start_helper_thread (profiler))
4233                         profiler->command_port = 0;
4234         }
4235 #endif
4236
4237         start_writer_thread (profiler);
4238
4239         InterlockedWrite (&runtime_inited, 1);
4240 #ifndef DISABLE_HELPER_THREAD
4241         counters_init (profiler);
4242         counters_sample (profiler, 0);
4243 #endif
4244         /* ensure the main thread data and startup are available soon */
4245         safe_send (profiler, ensure_logbuf (0));
4246 }
4247
4248 static MonoProfiler*
4249 create_profiler (const char *filename, GPtrArray *filters)
4250 {
4251         MonoProfiler *prof;
4252         char *nf;
4253         int force_delete = 0;
4254         prof = calloc (1, sizeof (MonoProfiler));
4255
4256         prof->command_port = command_port;
4257         if (filename && *filename == '-') {
4258                 force_delete = 1;
4259                 filename++;
4260         }
4261         if (!filename) {
4262                 if (do_report)
4263                         filename = "|mprof-report -";
4264                 else
4265                         filename = "output.mlpd";
4266                 nf = (char*)filename;
4267         } else {
4268                 nf = new_filename (filename);
4269                 if (do_report) {
4270                         int s = strlen (nf) + 32;
4271                         char *p = malloc (s);
4272                         snprintf (p, s, "|mprof-report '--out=%s' -", nf);
4273                         free (nf);
4274                         nf = p;
4275                 }
4276         }
4277         if (*nf == '|') {
4278                 prof->file = popen (nf + 1, "w");
4279                 prof->pipe_output = 1;
4280         } else if (*nf == '#') {
4281                 int fd = strtol (nf + 1, NULL, 10);
4282                 prof->file = fdopen (fd, "a");
4283         } else {
4284                 if (force_delete)
4285                         unlink (nf);
4286                 prof->file = fopen (nf, "wb");
4287         }
4288         if (!prof->file) {
4289                 fprintf (stderr, "Cannot create profiler output: %s\n", nf);
4290                 exit (1);
4291         }
4292 #if defined (HAVE_SYS_ZLIB)
4293         if (use_zip)
4294                 prof->gzfile = gzdopen (fileno (prof->file), "wb");
4295 #endif
4296 #if USE_PERF_EVENTS
4297         if (sample_type && !do_mono_sample)
4298                 need_helper_thread = setup_perf_event ();
4299         if (!perf_data) {
4300                 /* FIXME: warn if different freq or sample type */
4301                 do_mono_sample = 1;
4302         }
4303 #endif
4304         if (do_mono_sample) {
4305                 prof->stat_buffers = create_stat_buffer ();
4306                 need_helper_thread = 1;
4307         }
4308         if (do_counters && !need_helper_thread) {
4309                 need_helper_thread = 1;
4310         }
4311
4312         prof->sorted_sample_events = g_ptr_array_sized_new (BUFFER_SIZE / SAMPLE_EVENT_SIZE_IN_SLOTS (0));
4313
4314 #ifdef DISABLE_HELPER_THREAD
4315         if (hs_mode_ondemand)
4316                 fprintf (stderr, "Ondemand heapshot unavailable on this arch.\n");
4317
4318         if (do_coverage)
4319                 fprintf (stderr, "Coverage unavailable on this arch.\n");
4320
4321 #endif
4322
4323         mono_lock_free_queue_init (&prof->writer_queue);
4324         mono_mutex_init (&prof->method_table_mutex);
4325         prof->method_table = mono_conc_hashtable_new (&prof->method_table_mutex, NULL, NULL);
4326
4327         if (do_coverage)
4328                 coverage_init (prof);
4329         prof->coverage_filters = filters;
4330
4331         prof->startup_time = current_time ();
4332         return prof;
4333 }
4334
4335 static void
4336 usage (int do_exit)
4337 {
4338         printf ("Log profiler version %d.%d (format: %d)\n", LOG_VERSION_MAJOR, LOG_VERSION_MINOR, LOG_DATA_VERSION);
4339         printf ("Usage: mono --profile=log[:OPTION1[,OPTION2...]] program.exe\n");
4340         printf ("Options:\n");
4341         printf ("\thelp                 show this usage info\n");
4342         printf ("\t[no]alloc            enable/disable recording allocation info\n");
4343         printf ("\t[no]calls            enable/disable recording enter/leave method events\n");
4344         printf ("\theapshot[=MODE]      record heap shot info (by default at each major collection)\n");
4345         printf ("\t                     MODE: every XXms milliseconds, every YYgc collections, ondemand\n");
4346         printf ("\tcounters             sample counters every 1s\n");
4347         printf ("\tsample[=TYPE]        use statistical sampling mode (by default cycles/1000)\n");
4348         printf ("\t                     TYPE: cycles,instr,cacherefs,cachemiss,branches,branchmiss\n");
4349         printf ("\t                     TYPE can be followed by /FREQUENCY\n");
4350         printf ("\ttime=fast            use a faster (but more inaccurate) timer\n");
4351         printf ("\tmaxframes=NUM        collect up to NUM stack frames\n");
4352         printf ("\tcalldepth=NUM        ignore method events for call chain depth bigger than NUM\n");
4353         printf ("\toutput=FILENAME      write the data to file FILENAME (-FILENAME to overwrite)\n");
4354         printf ("\toutput=|PROGRAM      write the data to the stdin of PROGRAM\n");
4355         printf ("\t                     %%t is subtituted with date and time, %%p with the pid\n");
4356         printf ("\treport               create a report instead of writing the raw data to a file\n");
4357         printf ("\tzip                  compress the output data\n");
4358         printf ("\tport=PORTNUM         use PORTNUM for the listening command server\n");
4359         printf ("\tcoverage             enable collection of code coverage data\n");
4360         printf ("\tcovfilter=ASSEMBLY   add an assembly to the code coverage filters\n");
4361         printf ("\t                     add a + to include the assembly or a - to exclude it\n");
4362         printf ("\t                     filter=-mscorlib\n");
4363         printf ("\tcovfilter-file=FILE  use FILE to generate the list of assemblies to be filtered\n");
4364         if (do_exit)
4365                 exit (1);
4366 }
4367
4368 static const char*
4369 match_option (const char* p, const char *opt, char **rval)
4370 {
4371         int len = strlen (opt);
4372         if (strncmp (p, opt, len) == 0) {
4373                 if (rval) {
4374                         if (p [len] == '=' && p [len + 1]) {
4375                                 const char *opt = p + len + 1;
4376                                 const char *end = strchr (opt, ',');
4377                                 char *val;
4378                                 int l;
4379                                 if (end == NULL) {
4380                                         l = strlen (opt);
4381                                 } else {
4382                                         l = end - opt;
4383                                 }
4384                                 val = malloc (l + 1);
4385                                 memcpy (val, opt, l);
4386                                 val [l] = 0;
4387                                 *rval = val;
4388                                 return opt + l;
4389                         }
4390                         if (p [len] == 0 || p [len] == ',') {
4391                                 *rval = NULL;
4392                                 return p + len + (p [len] == ',');
4393                         }
4394                         usage (1);
4395                 } else {
4396                         if (p [len] == 0)
4397                                 return p + len;
4398                         if (p [len] == ',')
4399                                 return p + len + 1;
4400                 }
4401         }
4402         return p;
4403 }
4404
4405 typedef struct {
4406         const char *name;
4407         int sample_mode;
4408 } SampleMode;
4409
4410 static const SampleMode sample_modes [] = {
4411         {"cycles", SAMPLE_CYCLES},
4412         {"instr", SAMPLE_INSTRUCTIONS},
4413         {"cachemiss", SAMPLE_CACHE_MISSES},
4414         {"cacherefs", SAMPLE_CACHE_REFS},
4415         {"branches", SAMPLE_BRANCHES},
4416         {"branchmiss", SAMPLE_BRANCH_MISSES},
4417         {NULL, 0}
4418 };
4419
4420 static void
4421 set_sample_mode (char* val, int allow_empty)
4422 {
4423         char *end;
4424         char *maybe_freq = NULL;
4425         unsigned int count;
4426         const SampleMode *smode = sample_modes;
4427 #ifndef USE_PERF_EVENTS
4428         do_mono_sample = 1;
4429 #endif
4430         if (allow_empty && !val) {
4431                 sample_type = SAMPLE_CYCLES;
4432                 sample_freq = 1000;
4433                 return;
4434         }
4435         if (strcmp (val, "mono") == 0) {
4436                 do_mono_sample = 1;
4437                 sample_type = SAMPLE_CYCLES;
4438                 free (val);
4439                 return;
4440         }
4441         for (smode = sample_modes; smode->name; smode++) {
4442                 int l = strlen (smode->name);
4443                 if (strncmp (val, smode->name, l) == 0) {
4444                         sample_type = smode->sample_mode;
4445                         maybe_freq = val + l;
4446                         break;
4447                 }
4448         }
4449         if (!smode->name)
4450                 usage (1);
4451         if (*maybe_freq == '/') {
4452                 count = strtoul (maybe_freq + 1, &end, 10);
4453                 if (maybe_freq + 1 == end)
4454                         usage (1);
4455                 sample_freq = count;
4456         } else if (*maybe_freq != 0) {
4457                 usage (1);
4458         } else {
4459                 sample_freq = 1000;
4460         }
4461         free (val);
4462 }
4463
4464 static void
4465 set_hsmode (char* val, int allow_empty)
4466 {
4467         char *end;
4468         unsigned int count;
4469         if (allow_empty && !val)
4470                 return;
4471         if (strcmp (val, "ondemand") == 0) {
4472                 hs_mode_ondemand = 1;
4473                 free (val);
4474                 return;
4475         }
4476         count = strtoul (val, &end, 10);
4477         if (val == end)
4478                 usage (1);
4479         if (strcmp (end, "ms") == 0)
4480                 hs_mode_ms = count;
4481         else if (strcmp (end, "gc") == 0)
4482                 hs_mode_gc = count;
4483         else
4484                 usage (1);
4485         free (val);
4486 }
4487
4488 /*
4489  * declaration to silence the compiler: this is the entry point that
4490  * mono will load from the shared library and call.
4491  */
4492 extern void
4493 mono_profiler_startup (const char *desc);
4494
4495 extern void
4496 mono_profiler_startup_log (const char *desc);
4497
4498 /*
4499  * this is the entry point that will be used when the profiler
4500  * is embedded inside the main executable.
4501  */
4502 void
4503 mono_profiler_startup_log (const char *desc)
4504 {
4505         mono_profiler_startup (desc);
4506 }
4507
4508 void
4509 mono_profiler_startup (const char *desc)
4510 {
4511         MonoProfiler *prof;
4512         GPtrArray *filters = NULL;
4513         char *filename = NULL;
4514         const char *p;
4515         const char *opt;
4516         int fast_time = 0;
4517         int calls_enabled = 0;
4518         int allocs_enabled = 0;
4519         int only_counters = 0;
4520         int only_coverage = 0;
4521         int events = MONO_PROFILE_GC|MONO_PROFILE_ALLOCATIONS|
4522                 MONO_PROFILE_GC_MOVES|MONO_PROFILE_CLASS_EVENTS|MONO_PROFILE_THREADS|
4523                 MONO_PROFILE_ENTER_LEAVE|MONO_PROFILE_JIT_COMPILATION|MONO_PROFILE_EXCEPTIONS|
4524                 MONO_PROFILE_MONITOR_EVENTS|MONO_PROFILE_MODULE_EVENTS|MONO_PROFILE_GC_ROOTS|
4525                 MONO_PROFILE_INS_COVERAGE|MONO_PROFILE_APPDOMAIN_EVENTS|MONO_PROFILE_CONTEXT_EVENTS|
4526                 MONO_PROFILE_ASSEMBLY_EVENTS;
4527
4528         p = desc;
4529         if (strncmp (p, "log", 3))
4530                 usage (1);
4531         p += 3;
4532         if (*p == ':')
4533                 p++;
4534         for (; *p; p = opt) {
4535                 char *val;
4536                 if (*p == ',') {
4537                         opt = p + 1;
4538                         continue;
4539                 }
4540                 if ((opt = match_option (p, "help", NULL)) != p) {
4541                         usage (0);
4542                         continue;
4543                 }
4544                 if ((opt = match_option (p, "calls", NULL)) != p) {
4545                         calls_enabled = 1;
4546                         continue;
4547                 }
4548                 if ((opt = match_option (p, "nocalls", NULL)) != p) {
4549                         events &= ~MONO_PROFILE_ENTER_LEAVE;
4550                         nocalls = 1;
4551                         continue;
4552                 }
4553                 if ((opt = match_option (p, "alloc", NULL)) != p) {
4554                         allocs_enabled = 1;
4555                         continue;
4556                 }
4557                 if ((opt = match_option (p, "noalloc", NULL)) != p) {
4558                         events &= ~MONO_PROFILE_ALLOCATIONS;
4559                         continue;
4560                 }
4561                 if ((opt = match_option (p, "time", &val)) != p) {
4562                         if (strcmp (val, "fast") == 0)
4563                                 fast_time = 1;
4564                         else if (strcmp (val, "null") == 0)
4565                                 fast_time = 2;
4566                         else
4567                                 usage (1);
4568                         free (val);
4569                         continue;
4570                 }
4571                 if ((opt = match_option (p, "report", NULL)) != p) {
4572                         do_report = 1;
4573                         continue;
4574                 }
4575                 if ((opt = match_option (p, "debug", NULL)) != p) {
4576                         do_debug = 1;
4577                         continue;
4578                 }
4579                 if ((opt = match_option (p, "sampling-real", NULL)) != p) {
4580                         sampling_mode = MONO_PROFILER_STAT_MODE_REAL;
4581                         continue;
4582                 }
4583                 if ((opt = match_option (p, "sampling-process", NULL)) != p) {
4584                         sampling_mode = MONO_PROFILER_STAT_MODE_PROCESS;
4585                         continue;
4586                 }
4587                 if ((opt = match_option (p, "heapshot", &val)) != p) {
4588                         events &= ~MONO_PROFILE_ALLOCATIONS;
4589                         events &= ~MONO_PROFILE_ENTER_LEAVE;
4590                         nocalls = 1;
4591                         do_heap_shot = 1;
4592                         set_hsmode (val, 1);
4593                         continue;
4594                 }
4595                 if ((opt = match_option (p, "sample", &val)) != p) {
4596                         events &= ~MONO_PROFILE_ALLOCATIONS;
4597                         events &= ~MONO_PROFILE_ENTER_LEAVE;
4598                         nocalls = 1;
4599                         set_sample_mode (val, 1);
4600                         continue;
4601                 }
4602                 if ((opt = match_option (p, "hsmode", &val)) != p) {
4603                         fprintf (stderr, "The hsmode profiler option is obsolete, use heapshot=MODE.\n");
4604                         set_hsmode (val, 0);
4605                         continue;
4606                 }
4607                 if ((opt = match_option (p, "zip", NULL)) != p) {
4608                         use_zip = 1;
4609                         continue;
4610                 }
4611                 if ((opt = match_option (p, "output", &val)) != p) {
4612                         filename = val;
4613                         continue;
4614                 }
4615                 if ((opt = match_option (p, "port", &val)) != p) {
4616                         char *end;
4617                         command_port = strtoul (val, &end, 10);
4618                         free (val);
4619                         continue;
4620                 }
4621                 if ((opt = match_option (p, "maxframes", &val)) != p) {
4622                         char *end;
4623                         num_frames = strtoul (val, &end, 10);
4624                         if (num_frames > MAX_FRAMES)
4625                                 num_frames = MAX_FRAMES;
4626                         free (val);
4627                         notraces = num_frames == 0;
4628                         continue;
4629                 }
4630                 if ((opt = match_option (p, "calldepth", &val)) != p) {
4631                         char *end;
4632                         max_call_depth = strtoul (val, &end, 10);
4633                         free (val);
4634                         continue;
4635                 }
4636                 if ((opt = match_option (p, "counters", NULL)) != p) {
4637                         do_counters = 1;
4638                         continue;
4639                 }
4640                 if ((opt = match_option (p, "countersonly", NULL)) != p) {
4641                         only_counters = 1;
4642                         continue;
4643                 }
4644                 if ((opt = match_option (p, "coverage", NULL)) != p) {
4645                         do_coverage = 1;
4646                         events |= MONO_PROFILE_ENTER_LEAVE;
4647                         debug_coverage = (g_getenv ("MONO_PROFILER_DEBUG_COVERAGE") != NULL);
4648                         continue;
4649                 }
4650                 if ((opt = match_option (p, "onlycoverage", NULL)) != p) {
4651                         only_coverage = 1;
4652                         continue;
4653                 }
4654                 if ((opt = match_option (p, "covfilter-file", &val)) != p) {
4655                         FILE *filter_file;
4656                         char *line, *content;
4657
4658                         if (filters == NULL)
4659                                 filters = g_ptr_array_new ();
4660
4661                         filter_file = fopen (val, "r");
4662                         if (filter_file == NULL) {
4663                                 fprintf (stderr, "Unable to open %s\n", val);
4664                                 exit (0);
4665                         }
4666
4667                         /* Don't need to free content as it is referred to by the lines stored in @filters */
4668                         content = get_file_content (filter_file);
4669                         if (content == NULL)
4670                                 fprintf (stderr, "WARNING: %s is greater than 128kb - ignoring\n", val);
4671
4672                         while ((line = get_next_line (content, &content)))
4673                                 g_ptr_array_add (filters, g_strchug (g_strchomp (line)));
4674
4675                         fclose (filter_file);
4676                         continue;
4677                 }
4678                 if ((opt = match_option (p, "covfilter", &val)) != p) {
4679                         if (filters == NULL)
4680                                 filters = g_ptr_array_new ();
4681
4682                         g_ptr_array_add (filters, val);
4683                         continue;
4684                 }
4685                 if (opt == p) {
4686                         usage (0);
4687                         exit (0);
4688                 }
4689         }
4690         if (calls_enabled) {
4691                 events |= MONO_PROFILE_ENTER_LEAVE;
4692                 nocalls = 0;
4693         }
4694         if (allocs_enabled)
4695                 events |= MONO_PROFILE_ALLOCATIONS;
4696         if (only_counters)
4697                 events = 0;
4698         if (only_coverage)
4699                 events = MONO_PROFILE_ENTER_LEAVE | MONO_PROFILE_INS_COVERAGE;
4700
4701         utils_init (fast_time);
4702
4703         prof = create_profiler (filename, filters);
4704         if (!prof)
4705                 return;
4706         init_thread ();
4707
4708         mono_profiler_install (prof, log_shutdown);
4709         mono_profiler_install_gc (gc_event, gc_resize);
4710         mono_profiler_install_allocation (gc_alloc);
4711         mono_profiler_install_gc_moves (gc_moves);
4712         mono_profiler_install_gc_roots (gc_handle, gc_roots);
4713         mono_profiler_install_appdomain (NULL, domain_loaded, NULL, domain_unloaded);
4714         mono_profiler_install_appdomain_name (domain_name);
4715         mono_profiler_install_context (context_loaded, context_unloaded);
4716         mono_profiler_install_class (NULL, class_loaded, NULL, class_unloaded);
4717         mono_profiler_install_module (NULL, image_loaded, NULL, image_unloaded);
4718         mono_profiler_install_assembly (NULL, assembly_loaded, NULL, assembly_unloaded);
4719         mono_profiler_install_thread (thread_start, thread_end);
4720         mono_profiler_install_thread_name (thread_name);
4721         mono_profiler_install_enter_leave (method_enter, method_leave);
4722         mono_profiler_install_jit_end (method_jitted);
4723         mono_profiler_install_code_buffer_new (code_buffer_new);
4724         mono_profiler_install_exception (throw_exc, method_exc_leave, clause_exc);
4725         mono_profiler_install_monitor (monitor_event);
4726         mono_profiler_install_runtime_initialized (runtime_initialized);
4727         if (do_coverage)
4728                 mono_profiler_install_coverage_filter (coverage_filter);
4729
4730         if (do_mono_sample && sample_type == SAMPLE_CYCLES && !only_counters) {
4731                 events |= MONO_PROFILE_STATISTICAL;
4732                 mono_profiler_set_statistical_mode (sampling_mode, 1000000 / sample_freq);
4733                 mono_profiler_install_statistical (mono_sample_hit);
4734         }
4735
4736         mono_profiler_set_events (events);
4737
4738         TLS_INIT (tlsbuffer);
4739         TLS_INIT (tlsmethodlist);
4740 }