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