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