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