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