Merge pull request #1588 from BrzVlad/feature-aot-wbarrier
[mono.git] / mono / profiler / proflog.c
1 /*
2  * proflog.c: mono log profiler
3  *
4  * Author:
5  *   Paolo Molaro (lupus@ximian.com)
6  *
7  * Copyright 2010 Novell, Inc (http://www.novell.com)
8  * Copyright 2011 Xamarin Inc (http://www.xamarin.com)
9  */
10
11 #include <config.h>
12 #include "../mini/jit.h"
13 #include <mono/metadata/profiler.h>
14 #include <mono/metadata/threads.h>
15 #include <mono/metadata/mono-gc.h>
16 #include <mono/metadata/debug-helpers.h>
17 #include <mono/metadata/mono-perfcounters.h>
18 #include <mono/metadata/appdomain.h>
19 #include <mono/utils/atomic.h>
20 #include <mono/utils/mono-membar.h>
21 #include <mono/utils/mono-counters.h>
22 #include <mono/utils/mono-mutex.h>
23 #include <mono/utils/mono-conc-hashtable.h>
24 #include <mono/utils/lock-free-queue.h>
25 #include <stdlib.h>
26 #include <string.h>
27 #include <assert.h>
28 #include <glib.h>
29 #ifdef HAVE_UNISTD_H
30 #include <unistd.h>
31 #endif
32 #include <fcntl.h>
33 #include <errno.h>
34 #if defined(HOST_WIN32) || defined(DISABLE_SOCKETS)
35 #define DISABLE_HELPER_THREAD 1
36 #endif
37
38 #ifndef _GNU_SOURCE
39 #define _GNU_SOURCE
40 #endif
41 #ifdef HAVE_DLFCN_H
42 #include <dlfcn.h>
43 #endif
44 #ifdef HAVE_EXECINFO_H
45 #include <execinfo.h>
46 #endif
47 #ifdef HAVE_LINK_H
48 #include <link.h>
49 #endif
50
51 #ifndef DISABLE_HELPER_THREAD
52 #include <sys/types.h>
53 #include <sys/socket.h>
54 #include <netinet/in.h>
55 #include <sys/select.h>
56 #endif
57
58 #ifdef HOST_WIN32
59 #include <windows.h>
60 #else
61 #include <pthread.h>
62 #endif
63
64 #ifdef HAVE_SYS_STAT_H
65 #include <sys/stat.h>
66 #endif
67
68 #include "utils.c"
69 #include "proflog.h"
70
71 #if defined (HAVE_SYS_ZLIB)
72 #include <zlib.h>
73 #endif
74
75 #if defined(__linux__)
76
77 #include <unistd.h>
78 #include <sys/syscall.h>
79 #include "perf_event.h"
80
81 #ifndef DISABLE_PERF_EVENTS
82 #define USE_PERF_EVENTS 1
83
84 static int read_perf_mmap (MonoProfiler* prof, int cpu);
85 #endif
86
87 #endif
88
89 #define BUFFER_SIZE (4096 * 16)
90 static int nocalls = 0;
91 static int notraces = 0;
92 static int use_zip = 0;
93 static int do_report = 0;
94 static int do_heap_shot = 0;
95 static int max_call_depth = 100;
96 static int runtime_inited = 0;
97 static int command_port = 0;
98 static int heapshot_requested = 0;
99 static int sample_type = 0;
100 static int sample_freq = 0;
101 static int do_mono_sample = 0;
102 static int in_shutdown = 0;
103 static int do_debug = 0;
104 static int do_counters = 0;
105 static MonoProfileSamplingMode sampling_mode = MONO_PROFILER_STAT_MODE_PROCESS;
106
107 /* For linux compile with:
108  * gcc -fPIC -shared -o libmono-profiler-log.so proflog.c utils.c -Wall -g -lz `pkg-config --cflags --libs mono-2`
109  * gcc -o mprof-report decode.c utils.c -Wall -g -lz -lrt -lpthread `pkg-config --cflags mono-2`
110  *
111  * For osx compile with:
112  * gcc -m32 -Dmono_free=free shared -o libmono-profiler-log.dylib proflog.c utils.c -Wall -g -lz `pkg-config --cflags mono-2` -undefined suppress -flat_namespace
113  * gcc -m32 -o mprof-report decode.c utils.c -Wall -g -lz -lrt -lpthread `pkg-config --cflags mono-2`
114  *
115  * Install with:
116  * sudo cp mprof-report /usr/local/bin
117  * sudo cp libmono-profiler-log.so /usr/local/lib
118  * sudo ldconfig
119  */
120
121 typedef struct _LogBuffer LogBuffer;
122
123 /*
124  * file format:
125  * [header] [buffer]*
126  *
127  * The file is composed by a header followed by 0 or more buffers.
128  * Each buffer contains events that happened on a thread: for a given thread
129  * buffers that appear later in the file are guaranteed to contain events
130  * that happened later in time. Buffers from separate threads could be interleaved,
131  * though.
132  * Buffers are not required to be aligned.
133  *
134  * header format:
135  * [id: 4 bytes] constant value: LOG_HEADER_ID
136  * [major: 1 byte] [minor: 1 byte] major and minor version of the log profiler
137  * [format: 1 byte] version of the data format for the rest of the file
138  * [ptrsize: 1 byte] size in bytes of a pointer in the profiled program
139  * [startup time: 8 bytes] time in milliseconds since the unix epoch when the program started
140  * [timer overhead: 4 bytes] approximate overhead in nanoseconds of the timer
141  * [flags: 4 bytes] file format flags, should be 0 for now
142  * [pid: 4 bytes] pid of the profiled process
143  * [port: 2 bytes] tcp port for server if != 0
144  * [sysid: 2 bytes] operating system and architecture identifier
145  *
146  * The multiple byte integers are in little-endian format.
147  *
148  * buffer format:
149  * [buffer header] [event]*
150  * Buffers have a fixed-size header followed by 0 or more bytes of event data.
151  * Timing information and other values in the event data are usually stored
152  * as uleb128 or sleb128 integers. To save space, as noted for each item below,
153  * some data is represented as a difference between the actual value and
154  * either the last value of the same type (like for timing information) or
155  * as the difference from a value stored in a buffer header.
156  *
157  * For timing information the data is stored as uleb128, since timing
158  * increases in a monotonic way in each thread: the value is the number of
159  * nanoseconds to add to the last seen timing data in a buffer. The first value
160  * in a buffer will be calculated from the time_base field in the buffer head.
161  *
162  * Object or heap sizes are stored as uleb128.
163  * Pointer differences are stored as sleb128, instead.
164  *
165  * If an unexpected value is found, the rest of the buffer should be ignored,
166  * as generally the later values need the former to be interpreted correctly.
167  *
168  * buffer header format:
169  * [bufid: 4 bytes] constant value: BUF_ID
170  * [len: 4 bytes] size of the data following the buffer header
171  * [time_base: 8 bytes] time base in nanoseconds since an unspecified epoch
172  * [ptr_base: 8 bytes] base value for pointers
173  * [obj_base: 8 bytes] base value for object addresses
174  * [thread id: 8 bytes] system-specific thread ID (pthread_t for example)
175  * [method_base: 8 bytes] base value for MonoMethod pointers
176  *
177  * event format:
178  * [extended info: upper 4 bits] [type: lower 4 bits] [data]*
179  * The data that follows depends on type and the extended info.
180  * Type is one of the enum values in proflog.h: TYPE_ALLOC, TYPE_GC,
181  * TYPE_METADATA, TYPE_METHOD, TYPE_EXCEPTION, TYPE_MONITOR, TYPE_HEAP.
182  * The extended info bits are interpreted based on type, see
183  * each individual event description below.
184  * strings are represented as a 0-terminated utf8 sequence.
185  *
186  * backtrace format:
187  * [flags: uleb128] must be 0
188  * [num: uleb128] number of frames following
189  * [frame: sleb128]* num MonoMethod pointers as differences from ptr_base
190  *
191  * type alloc format:
192  * type: TYPE_ALLOC
193  * exinfo: flags: TYPE_ALLOC_BT
194  * [time diff: uleb128] nanoseconds since last timing
195  * [ptr: sleb128] class as a byte difference from ptr_base
196  * [obj: sleb128] object address as a byte difference from obj_base
197  * [size: uleb128] size of the object in the heap
198  * If the TYPE_ALLOC_BT flag is set, a backtrace follows.
199  *
200  * type GC format:
201  * type: TYPE_GC
202  * exinfo: one of TYPE_GC_EVENT, TYPE_GC_RESIZE, TYPE_GC_MOVE, TYPE_GC_HANDLE_CREATED,
203  * TYPE_GC_HANDLE_DESTROYED
204  * [time diff: uleb128] nanoseconds since last timing
205  * if exinfo == TYPE_GC_RESIZE
206  *      [heap_size: uleb128] new heap size
207  * if exinfo == TYPE_GC_EVENT
208  *      [event type: uleb128] GC event (MONO_GC_EVENT_* from profiler.h)
209  *      [generation: uleb128] GC generation event refers to
210  * if exinfo == TYPE_GC_MOVE
211  *      [num_objects: uleb128] number of object moves that follow
212  *      [objaddr: sleb128]+ num_objects object pointer differences from obj_base
213  *      num is always an even number: the even items are the old
214  *      addresses, the odd numbers are the respective new object addresses
215  * if exinfo == TYPE_GC_HANDLE_CREATED
216  *      [handle_type: uleb128] GC handle type (System.Runtime.InteropServices.GCHandleType)
217  *      upper bits reserved as flags
218  *      [handle: uleb128] GC handle value
219  *      [objaddr: sleb128] object pointer differences from obj_base
220  * if exinfo == TYPE_GC_HANDLE_DESTROYED
221  *      [handle_type: uleb128] GC handle type (System.Runtime.InteropServices.GCHandleType)
222  *      upper bits reserved as flags
223  *      [handle: uleb128] GC handle value
224  *
225  * type metadata format:
226  * type: TYPE_METADATA
227  * exinfo: flags: TYPE_LOAD_ERR
228  * [time diff: uleb128] nanoseconds since last timing
229  * [mtype: byte] metadata type, one of: TYPE_CLASS, TYPE_IMAGE, TYPE_ASSEMBLY, TYPE_DOMAIN,
230  * TYPE_THREAD
231  * [pointer: sleb128] pointer of the metadata type depending on mtype
232  * if mtype == TYPE_CLASS
233  *      [image: sleb128] MonoImage* as a pointer difference from ptr_base
234  *      [flags: uleb128] must be 0
235  *      [name: string] full class name
236  * if mtype == TYPE_IMAGE
237  *      [flags: uleb128] must be 0
238  *      [name: string] image file name
239  * if mtype == TYPE_THREAD
240  *      [flags: uleb128] must be 0
241  *      [name: string] thread name
242  *
243  * type method format:
244  * type: TYPE_METHOD
245  * exinfo: one of: TYPE_LEAVE, TYPE_ENTER, TYPE_EXC_LEAVE, TYPE_JIT
246  * [time diff: uleb128] nanoseconds since last timing
247  * [method: sleb128] MonoMethod* as a pointer difference from the last such
248  * pointer or the buffer method_base
249  * if exinfo == TYPE_JIT
250  *      [code address: sleb128] pointer to the native code as a diff from ptr_base
251  *      [code size: uleb128] size of the generated code
252  *      [name: string] full method name
253  *
254  * type runtime format:
255  * type: TYPE_RUNTIME
256  * exinfo: one of: TYPE_JITHELPER
257  * [time diff: uleb128] nanoseconds since last timing
258  * if exinfo == TYPE_JITHELPER
259  *      [type: uleb128] MonoProfilerCodeBufferType enum value
260  *      [buffer address: sleb128] pointer to the native code as a diff from ptr_base
261  *      [buffer size: uleb128] size of the generated code
262  *      if type == MONO_PROFILER_CODE_BUFFER_SPECIFIC_TRAMPOLINE
263  *              [name: string] buffer description name
264  *
265  * type monitor format:
266  * type: TYPE_MONITOR
267  * exinfo: TYPE_MONITOR_BT flag and one of: MONO_PROFILER_MONITOR_(CONTENTION|FAIL|DONE)
268  * [time diff: uleb128] nanoseconds since last timing
269  * [object: sleb128] the lock object as a difference from obj_base
270  * if exinfo.low3bits == MONO_PROFILER_MONITOR_CONTENTION
271  *      If the TYPE_MONITOR_BT flag is set, a backtrace follows.
272  *
273  * type heap format
274  * type: TYPE_HEAP
275  * exinfo: one of TYPE_HEAP_START, TYPE_HEAP_END, TYPE_HEAP_OBJECT, TYPE_HEAP_ROOT
276  * if exinfo == TYPE_HEAP_START
277  *      [time diff: uleb128] nanoseconds since last timing
278  * if exinfo == TYPE_HEAP_END
279  *      [time diff: uleb128] nanoseconds since last timing
280  * if exinfo == TYPE_HEAP_OBJECT
281  *      [object: sleb128] the object as a difference from obj_base
282  *      [class: sleb128] the object MonoClass* as a difference from ptr_base
283  *      [size: uleb128] size of the object on the heap
284  *      [num_refs: uleb128] number of object references
285  *      if (format version > 1) each referenced objref is preceded by a
286  *      uleb128 encoded offset: the first offset is from the object address
287  *      and each next offset is relative to the previous one
288  *      [objrefs: sleb128]+ object referenced as a difference from obj_base
289  *      The same object can appear multiple times, but only the first time
290  *      with size != 0: in the other cases this data will only be used to
291  *      provide additional referenced objects.
292  * if exinfo == TYPE_HEAP_ROOT
293  *      [num_roots: uleb128] number of root references
294  *      [num_gc: uleb128] number of major gcs
295  *      [object: sleb128] the object as a difference from obj_base
296  *      [root_type: uleb128] the root_type: MonoProfileGCRootType (profiler.h)
297  *      [extra_info: uleb128] the extra_info value
298  *      object, root_type and extra_info are repeated num_roots times
299  *
300  * type sample format
301  * type: TYPE_SAMPLE
302  * exinfo: one of TYPE_SAMPLE_HIT, TYPE_SAMPLE_USYM, TYPE_SAMPLE_UBIN, TYPE_SAMPLE_COUNTERS_DESC, TYPE_SAMPLE_COUNTERS
303  * if exinfo == TYPE_SAMPLE_HIT
304  *      [sample_type: uleb128] type of sample (SAMPLE_*)
305  *      [timestamp: uleb128] nanoseconds since startup (note: different from other timestamps!)
306  *      [count: uleb128] number of following instruction addresses
307  *      [ip: sleb128]* instruction pointer as difference from ptr_base
308  *      if (format_version > 5)
309  *              [mbt_count: uleb128] number of managed backtrace info triplets (method + IL offset + native offset)
310  *              [method: sleb128]* MonoMethod* as a pointer difference from the last such
311  *              pointer or the buffer method_base (the first such method can be also indentified by ip, but this is not neccessarily true)
312  *              [il_offset: sleb128]* IL offset inside method where the hit occurred
313  *              [native_offset: sleb128]* native offset inside method where the hit occurred
314  * if exinfo == TYPE_SAMPLE_USYM
315  *      [address: sleb128] symbol address as a difference from ptr_base
316  *      [size: uleb128] symbol size (may be 0 if unknown)
317  *      [name: string] symbol name
318  * if exinfo == TYPE_SAMPLE_UBIN
319  *      [time diff: uleb128] nanoseconds since last timing
320  *      [address: sleb128] address where binary has been loaded
321  *      [offset: uleb128] file offset of mapping (the same file can be mapped multiple times)
322  *      [size: uleb128] memory size
323  *      [name: string] binary name
324  * if exinfo == TYPE_SAMPLE_COUNTERS_DESC
325  *      [len: uleb128] number of counters
326  *      for i = 0 to len
327  *              [section: uleb128] section of counter
328  *              if section == MONO_COUNTER_PERFCOUNTERS:
329  *                      [section_name: string] section name of counter
330  *              [name: string] name of counter
331  *              [type: uleb128] type of counter
332  *              [unit: uleb128] unit of counter
333  *              [variance: uleb128] variance of counter
334  *              [index: uleb128] unique index of counter
335  * if exinfo == TYPE_SAMPLE_COUNTERS
336  *      [timestamp: uleb128] sampling timestamp
337  *      while true:
338  *              [index: uleb128] unique index of counter
339  *              if index == 0:
340  *                      break
341  *              [type: uleb128] type of counter value
342  *              if type == string:
343  *                      if value == null:
344  *                              [0: uleb128] 0 -> value is null
345  *                      else:
346  *                              [1: uleb128] 1 -> value is not null
347  *                              [value: string] counter value
348  *              else:
349  *                      [value: uleb128/sleb128/double] counter value, can be sleb128, uleb128 or double (determined by using type)
350  *
351  */
352 struct _LogBuffer {
353         LogBuffer *next;
354         uint64_t time_base;
355         uint64_t last_time;
356         uintptr_t ptr_base;
357         uintptr_t method_base;
358         uintptr_t last_method;
359         uintptr_t obj_base;
360         uintptr_t thread_id;
361         unsigned char* data_end;
362         unsigned char* data;
363         int locked;
364         int size;
365         int call_depth;
366         unsigned char buf [1];
367 };
368
369 static inline void
370 ign_res (int G_GNUC_UNUSED unused, ...)
371 {
372 }
373
374 #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++;}
375 #define EXIT_LOG(lb) (lb)->locked--;
376
377 typedef struct _StatBuffer StatBuffer;
378 struct _StatBuffer {
379         StatBuffer *next;
380         uintptr_t size;
381         uintptr_t *data_end;
382         uintptr_t *data;
383         uintptr_t buf [1];
384 };
385
386 typedef struct _BinaryObject BinaryObject;
387
388 struct _BinaryObject {
389         BinaryObject *next;
390         void *addr;
391         char *name;
392 };
393
394 struct _MonoProfiler {
395         StatBuffer *stat_buffers;
396         FILE* file;
397 #if defined (HAVE_SYS_ZLIB)
398         gzFile gzfile;
399 #endif
400         uint64_t startup_time;
401         int pipe_output;
402         int last_gc_gen_started;
403         int command_port;
404         int server_socket;
405         int pipes [2];
406 #ifndef HOST_WIN32
407         pthread_t helper_thread;
408         pthread_t writer_thread;
409 #endif
410         volatile gint32 run_writer_thread;
411         MonoLockFreeQueue writer_queue;
412         MonoConcurrentHashTable *method_table;
413         mono_mutex_t method_table_mutex;
414         BinaryObject *binary_objects;
415 };
416
417 typedef struct _WriterQueueEntry WriterQueueEntry;
418 struct _WriterQueueEntry {
419         MonoLockFreeQueueNode node;
420         GPtrArray *methods;
421         LogBuffer *buffer;
422 };
423
424 typedef struct _MethodInfo MethodInfo;
425 struct _MethodInfo {
426         MonoMethod *method;
427         MonoJitInfo *ji;
428 };
429
430 #ifdef HOST_WIN32
431 #define TLS_SET(x,y) (TlsSetValue (x, y))
432 #define TLS_GET(t,x) ((t *) TlsGetValue (x))
433 #define TLS_INIT(x) (x = TlsAlloc ())
434 static int tlsbuffer;
435 static int tlsmethodlist;
436 #elif HAVE_KW_THREAD
437 #define TLS_SET(x,y) (x = y)
438 #define TLS_GET(t,x) (x)
439 #define TLS_INIT(x)
440 static __thread LogBuffer* tlsbuffer = NULL;
441 static __thread GPtrArray* tlsmethodlist = NULL;
442 #else
443 #define TLS_SET(x,y) (pthread_setspecific (x, y))
444 #define TLS_GET(t,x) ((t *) pthread_getspecific (x))
445 #define TLS_INIT(x) (pthread_key_create (&x, NULL))
446 static pthread_key_t tlsbuffer;
447 static pthread_key_t tlsmethodlist;
448 #endif
449
450 static void safe_send (MonoProfiler *profiler, LogBuffer *logbuffer);
451
452 static char*
453 pstrdup (const char *s)
454 {
455         int len = strlen (s) + 1;
456         char *p = malloc (len);
457         memcpy (p, s, len);
458         return p;
459 }
460
461 static StatBuffer*
462 create_stat_buffer (void)
463 {
464         StatBuffer* buf = alloc_buffer (BUFFER_SIZE);
465         buf->size = BUFFER_SIZE;
466         buf->data_end = (uintptr_t*)((unsigned char*)buf + buf->size);
467         buf->data = buf->buf;
468         return buf;
469 }
470
471 static LogBuffer*
472 create_buffer (void)
473 {
474         LogBuffer* buf = alloc_buffer (BUFFER_SIZE);
475         buf->size = BUFFER_SIZE;
476         buf->time_base = current_time ();
477         buf->last_time = buf->time_base;
478         buf->data_end = (unsigned char*)buf + buf->size;
479         buf->data = buf->buf;
480         return buf;
481 }
482
483 static void
484 init_thread (void)
485 {
486         if (!TLS_GET (LogBuffer, tlsbuffer)) {
487                 LogBuffer *logbuffer = create_buffer ();
488                 TLS_SET (tlsbuffer, logbuffer);
489                 logbuffer->thread_id = thread_id ();
490         }
491         if (!TLS_GET (GPtrArray, tlsmethodlist)) {
492                 GPtrArray *methodlist = g_ptr_array_new ();
493                 TLS_SET (tlsmethodlist, methodlist);
494         }
495
496         //printf ("thread %p at time %llu\n", (void*)logbuffer->thread_id, logbuffer->time_base);
497 }
498
499 static LogBuffer *
500 ensure_logbuf_inner (LogBuffer *old, int bytes)
501 {
502         if (old && old->data + bytes + 100 < old->data_end)
503                 return old;
504
505         LogBuffer *new = create_buffer ();
506         new->thread_id = thread_id ();
507         new->next = old;
508
509         if (old)
510                 new->call_depth = old->call_depth;
511
512         return new;
513 }
514
515 static LogBuffer*
516 ensure_logbuf (int bytes)
517 {
518         LogBuffer *old = TLS_GET (LogBuffer, tlsbuffer);
519         LogBuffer *new = ensure_logbuf_inner (old, bytes);
520
521         if (new == old)
522                 return old; // Still enough space.
523
524         TLS_SET (tlsbuffer, new);
525         init_thread ();
526
527         return new;
528 }
529
530 static void
531 emit_byte (LogBuffer *logbuffer, int value)
532 {
533         logbuffer->data [0] = value;
534         logbuffer->data++;
535         assert (logbuffer->data <= logbuffer->data_end);
536 }
537
538 static void
539 emit_value (LogBuffer *logbuffer, int value)
540 {
541         encode_uleb128 (value, logbuffer->data, &logbuffer->data);
542         assert (logbuffer->data <= logbuffer->data_end);
543 }
544
545 static void
546 emit_time (LogBuffer *logbuffer, uint64_t value)
547 {
548         uint64_t tdiff = value - logbuffer->last_time;
549         if (value < logbuffer->last_time)
550                 printf ("time went backwards\n");
551         //if (tdiff > 1000000)
552         //      printf ("large time offset: %llu\n", tdiff);
553         encode_uleb128 (tdiff, logbuffer->data, &logbuffer->data);
554         /*if (tdiff != decode_uleb128 (p, &p))
555                 printf ("incorrect encoding: %llu\n", tdiff);*/
556         logbuffer->last_time = value;
557         assert (logbuffer->data <= logbuffer->data_end);
558 }
559
560 static void
561 emit_svalue (LogBuffer *logbuffer, int64_t value)
562 {
563         encode_sleb128 (value, logbuffer->data, &logbuffer->data);
564         assert (logbuffer->data <= logbuffer->data_end);
565 }
566
567 static void
568 emit_uvalue (LogBuffer *logbuffer, uint64_t value)
569 {
570         encode_uleb128 (value, logbuffer->data, &logbuffer->data);
571         assert (logbuffer->data <= logbuffer->data_end);
572 }
573
574 static void
575 emit_ptr (LogBuffer *logbuffer, void *ptr)
576 {
577         if (!logbuffer->ptr_base)
578                 logbuffer->ptr_base = (uintptr_t)ptr;
579         emit_svalue (logbuffer, (intptr_t)ptr - logbuffer->ptr_base);
580         assert (logbuffer->data <= logbuffer->data_end);
581 }
582
583 static void
584 emit_method_inner (LogBuffer *logbuffer, void *method)
585 {
586         if (!logbuffer->method_base) {
587                 logbuffer->method_base = (intptr_t)method;
588                 logbuffer->last_method = (intptr_t)method;
589         }
590         encode_sleb128 ((intptr_t)((char*)method - (char*)logbuffer->last_method), logbuffer->data, &logbuffer->data);
591         logbuffer->last_method = (intptr_t)method;
592         assert (logbuffer->data <= logbuffer->data_end);
593 }
594
595 typedef struct {
596         MonoMethod *method;
597         MonoJitInfo *found;
598 } MethodSearch;
599
600 static void
601 find_method (MonoDomain *domain, void *user_data)
602 {
603         MethodSearch *search = user_data;
604
605         if (search->found)
606                 return;
607
608         MonoJitInfo *ji = mono_get_jit_info_from_method (domain, search->method);
609
610         // It could be AOT'd, so we need to force it to be loaded.
611         if (!ji) {
612                 // Loads the method as a side effect.
613                 mono_aot_get_method (domain, search->method);
614
615                 ji = mono_get_jit_info_from_method (domain, search->method);
616         }
617
618         if (ji)
619                 search->found = ji;
620 }
621
622 static void
623 register_method_local (MonoProfiler *prof, MonoDomain *domain, MonoMethod *method, MonoJitInfo *ji)
624 {
625         if (!domain)
626                 g_assert (ji);
627
628         if (!mono_conc_hashtable_lookup (prof->method_table, method)) {
629                 if (!ji) {
630                         MethodSearch search = { method, NULL };
631
632                         mono_domain_foreach (find_method, &search);
633
634                         ji = search.found;
635                 }
636
637                 g_assert (ji);
638
639                 MethodInfo *info = malloc (sizeof (MethodInfo));
640
641                 info->method = method;
642                 info->ji = ji;
643
644                 g_ptr_array_add (TLS_GET (GPtrArray, tlsmethodlist), info);
645         }
646 }
647
648 static void
649 emit_method (MonoProfiler *prof, LogBuffer *logbuffer, MonoDomain *domain, MonoMethod *method)
650 {
651         register_method_local (prof, domain, method, NULL);
652         emit_method_inner (logbuffer, method);
653 }
654
655 static void
656 emit_obj (LogBuffer *logbuffer, void *ptr)
657 {
658         if (!logbuffer->obj_base)
659                 logbuffer->obj_base = (uintptr_t)ptr >> 3;
660         emit_svalue (logbuffer, ((uintptr_t)ptr >> 3) - logbuffer->obj_base);
661         assert (logbuffer->data <= logbuffer->data_end);
662 }
663
664 static void
665 emit_string (LogBuffer *logbuffer, const char *str, size_t size)
666 {
667         size_t i = 0;
668         if (str) {
669                 for (; i < size; i++) {
670                         if (str[i] == '\0')
671                                 break;
672                         emit_byte (logbuffer, str [i]);
673                 }
674         }
675         emit_byte (logbuffer, '\0');
676 }
677
678 static void
679 emit_double (LogBuffer *logbuffer, double value)
680 {
681         int i;
682         unsigned char buffer[8];
683         memcpy (buffer, &value, 8);
684 #if G_BYTE_ORDER == G_BIG_ENDIAN
685         for (i = 7; i >= 0; i--)
686 #else
687         for (i = 0; i < 8; i++)
688 #endif
689                 emit_byte (logbuffer, buffer[i]);
690 }
691
692 static char*
693 write_int16 (char *buf, int32_t value)
694 {
695         int i;
696         for (i = 0; i < 2; ++i) {
697                 buf [i] = value;
698                 value >>= 8;
699         }
700         return buf + 2;
701 }
702
703 static char*
704 write_int32 (char *buf, int32_t value)
705 {
706         int i;
707         for (i = 0; i < 4; ++i) {
708                 buf [i] = value;
709                 value >>= 8;
710         }
711         return buf + 4;
712 }
713
714 static char*
715 write_int64 (char *buf, int64_t value)
716 {
717         int i;
718         for (i = 0; i < 8; ++i) {
719                 buf [i] = value;
720                 value >>= 8;
721         }
722         return buf + 8;
723 }
724
725 static void
726 dump_header (MonoProfiler *profiler)
727 {
728         char hbuf [128];
729         char *p = hbuf;
730         p = write_int32 (p, LOG_HEADER_ID);
731         *p++ = LOG_VERSION_MAJOR;
732         *p++ = LOG_VERSION_MINOR;
733         *p++ = LOG_DATA_VERSION;
734         *p++ = sizeof (void*);
735         p = write_int64 (p, ((uint64_t)time (NULL)) * 1000); /* startup time */
736         p = write_int32 (p, get_timer_overhead ()); /* timer overhead */
737         p = write_int32 (p, 0); /* flags */
738         p = write_int32 (p, process_id ()); /* pid */
739         p = write_int16 (p, profiler->command_port); /* port */
740         p = write_int16 (p, 0); /* opsystem */
741 #if defined (HAVE_SYS_ZLIB)
742         if (profiler->gzfile) {
743                 gzwrite (profiler->gzfile, hbuf, p - hbuf);
744         } else {
745                 fwrite (hbuf, p - hbuf, 1, profiler->file);
746         }
747 #else
748         fwrite (hbuf, p - hbuf, 1, profiler->file);
749         fflush (profiler->file);
750 #endif
751 }
752
753 static void
754 send_buffer (MonoProfiler *prof, GPtrArray *methods, LogBuffer *buffer)
755 {
756         WriterQueueEntry *entry = calloc (1, sizeof (WriterQueueEntry));
757         mono_lock_free_queue_node_init (&entry->node, FALSE);
758         entry->methods = methods;
759         entry->buffer = buffer;
760         mono_lock_free_queue_enqueue (&prof->writer_queue, &entry->node);
761 }
762
763 static void
764 dump_buffer (MonoProfiler *profiler, LogBuffer *buf)
765 {
766         char hbuf [128];
767         char *p = hbuf;
768         if (buf->next)
769                 dump_buffer (profiler, buf->next);
770         p = write_int32 (p, BUF_ID);
771         p = write_int32 (p, buf->data - buf->buf);
772         p = write_int64 (p, buf->time_base);
773         p = write_int64 (p, buf->ptr_base);
774         p = write_int64 (p, buf->obj_base);
775         p = write_int64 (p, buf->thread_id);
776         p = write_int64 (p, buf->method_base);
777 #if defined (HAVE_SYS_ZLIB)
778         if (profiler->gzfile) {
779                 gzwrite (profiler->gzfile, hbuf, p - hbuf);
780                 gzwrite (profiler->gzfile, buf->buf, buf->data - buf->buf);
781         } else {
782 #endif
783                 fwrite (hbuf, p - hbuf, 1, profiler->file);
784                 fwrite (buf->buf, buf->data - buf->buf, 1, profiler->file);
785                 fflush (profiler->file);
786 #if defined (HAVE_SYS_ZLIB)
787         }
788 #endif
789         free_buffer (buf, buf->size);
790 }
791
792 static void
793 process_requests (MonoProfiler *profiler)
794 {
795         if (heapshot_requested)
796                 mono_gc_collect (mono_gc_max_generation ());
797 }
798
799 static void counters_init (MonoProfiler *profiler);
800 static void counters_sample (MonoProfiler *profiler, uint64_t timestamp);
801
802 static void
803 runtime_initialized (MonoProfiler *profiler)
804 {
805         runtime_inited = 1;
806 #ifndef DISABLE_HELPER_THREAD
807         counters_init (profiler);
808         counters_sample (profiler, 0);
809 #endif
810         /* ensure the main thread data and startup are available soon */
811         safe_send (profiler, ensure_logbuf (0));
812 }
813
814 /*
815  * Can be called only at safe callback locations.
816  */
817 static void
818 safe_send (MonoProfiler *profiler, LogBuffer *logbuffer)
819 {
820         int cd = logbuffer->call_depth;
821
822         send_buffer (profiler, TLS_GET (GPtrArray, tlsmethodlist), TLS_GET (LogBuffer, tlsbuffer));
823
824         TLS_SET (tlsbuffer, NULL);
825         TLS_SET (tlsmethodlist, NULL);
826
827         init_thread ();
828
829         TLS_GET (LogBuffer, tlsbuffer)->call_depth = cd;
830 }
831
832 static int
833 gc_reference (MonoObject *obj, MonoClass *klass, uintptr_t size, uintptr_t num, MonoObject **refs, uintptr_t *offsets, void *data)
834 {
835         int i;
836         uintptr_t last_offset = 0;
837         //const char *name = mono_class_get_name (klass);
838         LogBuffer *logbuffer = ensure_logbuf (20 + num * 8);
839         emit_byte (logbuffer, TYPE_HEAP_OBJECT | TYPE_HEAP);
840         emit_obj (logbuffer, obj);
841         emit_ptr (logbuffer, klass);
842         /* account for object alignment in the heap */
843         size += 7;
844         size &= ~7;
845         emit_value (logbuffer, size);
846         emit_value (logbuffer, num);
847         for (i = 0; i < num; ++i) {
848                 emit_value (logbuffer, offsets [i] - last_offset);
849                 last_offset = offsets [i];
850                 emit_obj (logbuffer, refs [i]);
851         }
852         //if (num)
853         //      printf ("obj: %p, klass: %s, refs: %d, size: %d\n", obj, name, (int)num, (int)size);
854         return 0;
855 }
856
857 static unsigned int hs_mode_ms = 0;
858 static unsigned int hs_mode_gc = 0;
859 static unsigned int hs_mode_ondemand = 0;
860 static unsigned int gc_count = 0;
861 static uint64_t last_hs_time = 0;
862
863 static void
864 heap_walk (MonoProfiler *profiler)
865 {
866         int do_walk = 0;
867         uint64_t now;
868         LogBuffer *logbuffer;
869         if (!do_heap_shot)
870                 return;
871         logbuffer = ensure_logbuf (10);
872         now = current_time ();
873         if (hs_mode_ms && (now - last_hs_time)/1000000 >= hs_mode_ms)
874                 do_walk = 1;
875         else if (hs_mode_gc && (gc_count % hs_mode_gc) == 0)
876                 do_walk = 1;
877         else if (hs_mode_ondemand)
878                 do_walk = heapshot_requested;
879         else if (!hs_mode_ms && !hs_mode_gc && profiler->last_gc_gen_started == mono_gc_max_generation ())
880                 do_walk = 1;
881
882         if (!do_walk)
883                 return;
884         heapshot_requested = 0;
885         emit_byte (logbuffer, TYPE_HEAP_START | TYPE_HEAP);
886         emit_time (logbuffer, now);
887         mono_gc_walk_heap (0, gc_reference, NULL);
888         logbuffer = ensure_logbuf (10);
889         now = current_time ();
890         emit_byte (logbuffer, TYPE_HEAP_END | TYPE_HEAP);
891         emit_time (logbuffer, now);
892         last_hs_time = now;
893 }
894
895 static void
896 gc_event (MonoProfiler *profiler, MonoGCEvent ev, int generation) {
897         uint64_t now;
898         LogBuffer *logbuffer = ensure_logbuf (10);
899         now = current_time ();
900         ENTER_LOG (logbuffer, "gcevent");
901         emit_byte (logbuffer, TYPE_GC_EVENT | TYPE_GC);
902         emit_time (logbuffer, now);
903         emit_value (logbuffer, ev);
904         emit_value (logbuffer, generation);
905         /* to deal with nested gen1 after gen0 started */
906         if (ev == MONO_GC_EVENT_START) {
907                 profiler->last_gc_gen_started = generation;
908                 if (generation == mono_gc_max_generation ())
909                         gc_count++;
910         }
911         if (ev == MONO_GC_EVENT_PRE_START_WORLD)
912                 heap_walk (profiler);
913         EXIT_LOG (logbuffer);
914         if (ev == MONO_GC_EVENT_POST_START_WORLD)
915                 safe_send (profiler, logbuffer);
916         //printf ("gc event %d for generation %d\n", ev, generation);
917 }
918
919 static void
920 gc_resize (MonoProfiler *profiler, int64_t new_size) {
921         uint64_t now;
922         LogBuffer *logbuffer = ensure_logbuf (10);
923         now = current_time ();
924         ENTER_LOG (logbuffer, "gcresize");
925         emit_byte (logbuffer, TYPE_GC_RESIZE | TYPE_GC);
926         emit_time (logbuffer, now);
927         emit_value (logbuffer, new_size);
928         //printf ("gc resized to %lld\n", new_size);
929         EXIT_LOG (logbuffer);
930 }
931
932 #define MAX_FRAMES 32
933 typedef struct {
934         int count;
935         MonoMethod* methods [MAX_FRAMES];
936         int32_t il_offsets [MAX_FRAMES];
937         int32_t native_offsets [MAX_FRAMES];
938 } FrameData;
939 static int num_frames = MAX_FRAMES;
940
941 static mono_bool
942 walk_stack (MonoMethod *method, int32_t native_offset, int32_t il_offset, mono_bool managed, void* data)
943 {
944         FrameData *frame = data;
945         if (method && frame->count < num_frames) {
946                 frame->il_offsets [frame->count] = il_offset;
947                 frame->native_offsets [frame->count] = native_offset;
948                 frame->methods [frame->count++] = method;
949                 //printf ("In %d %s at %d (native: %d)\n", frame->count, mono_method_get_name (method), il_offset, native_offset);
950         }
951         return frame->count == num_frames;
952 }
953
954 /*
955  * a note about stack walks: they can cause more profiler events to fire,
956  * so we need to make sure they don't happen after we started emitting an
957  * event, hence the collect_bt/emit_bt split.
958  */
959 static void
960 collect_bt (FrameData *data)
961 {
962         data->count = 0;
963         mono_stack_walk_no_il (walk_stack, data);
964 }
965
966 static void
967 emit_bt (LogBuffer *logbuffer, FrameData *data)
968 {
969         /* FIXME: this is actually tons of data and we should
970          * just output it the first time and use an id the next
971          */
972         if (data->count > num_frames)
973                 printf ("bad num frames: %d\n", data->count);
974         emit_value (logbuffer, 0); /* flags */
975         emit_value (logbuffer, data->count);
976         //if (*p != data.count) {
977         //      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);}
978         while (data->count) {
979                 emit_ptr (logbuffer, data->methods [--data->count]);
980         }
981 }
982
983 static void
984 gc_alloc (MonoProfiler *prof, MonoObject *obj, MonoClass *klass)
985 {
986         uint64_t now;
987         uintptr_t len;
988         int do_bt = (nocalls && runtime_inited && !notraces)? TYPE_ALLOC_BT: 0;
989         FrameData data;
990         LogBuffer *logbuffer;
991         len = mono_object_get_size (obj);
992         /* account for object alignment in the heap */
993         len += 7;
994         len &= ~7;
995         if (do_bt)
996                 collect_bt (&data);
997         logbuffer = ensure_logbuf (32 + MAX_FRAMES * 8);
998         now = current_time ();
999         ENTER_LOG (logbuffer, "gcalloc");
1000         emit_byte (logbuffer, do_bt | TYPE_ALLOC);
1001         emit_time (logbuffer, now);
1002         emit_ptr (logbuffer, klass);
1003         emit_obj (logbuffer, obj);
1004         emit_value (logbuffer, len);
1005         if (do_bt)
1006                 emit_bt (logbuffer, &data);
1007         EXIT_LOG (logbuffer);
1008         if (logbuffer->next)
1009                 safe_send (prof, logbuffer);
1010         process_requests (prof);
1011         //printf ("gc alloc %s at %p\n", mono_class_get_name (klass), obj);
1012 }
1013
1014 static void
1015 gc_moves (MonoProfiler *prof, void **objects, int num)
1016 {
1017         int i;
1018         uint64_t now;
1019         LogBuffer *logbuffer = ensure_logbuf (10 + num * 8);
1020         now = current_time ();
1021         ENTER_LOG (logbuffer, "gcmove");
1022         emit_byte (logbuffer, TYPE_GC_MOVE | TYPE_GC);
1023         emit_time (logbuffer, now);
1024         emit_value (logbuffer, num);
1025         for (i = 0; i < num; ++i)
1026                 emit_obj (logbuffer, objects [i]);
1027         //printf ("gc moved %d objects\n", num/2);
1028         EXIT_LOG (logbuffer);
1029 }
1030
1031 static void
1032 gc_roots (MonoProfiler *prof, int num, void **objects, int *root_types, uintptr_t *extra_info)
1033 {
1034         int i;
1035         LogBuffer *logbuffer = ensure_logbuf (5 + num * 18);
1036         ENTER_LOG (logbuffer, "gcroots");
1037         emit_byte (logbuffer, TYPE_HEAP_ROOT | TYPE_HEAP);
1038         emit_value (logbuffer, num);
1039         emit_value (logbuffer, mono_gc_collection_count (mono_gc_max_generation ()));
1040         for (i = 0; i < num; ++i) {
1041                 emit_obj (logbuffer, objects [i]);
1042                 emit_value (logbuffer, root_types [i]);
1043                 emit_value (logbuffer, extra_info [i]);
1044         }
1045         EXIT_LOG (logbuffer);
1046 }
1047
1048 static void
1049 gc_handle (MonoProfiler *prof, int op, int type, uintptr_t handle, MonoObject *obj)
1050 {
1051         uint64_t now;
1052         LogBuffer *logbuffer = ensure_logbuf (16);
1053         now = current_time ();
1054         ENTER_LOG (logbuffer, "gchandle");
1055         if (op == MONO_PROFILER_GC_HANDLE_CREATED)
1056                 emit_byte (logbuffer, TYPE_GC_HANDLE_CREATED | TYPE_GC);
1057         else if (op == MONO_PROFILER_GC_HANDLE_DESTROYED)
1058                 emit_byte (logbuffer, TYPE_GC_HANDLE_DESTROYED | TYPE_GC);
1059         else
1060                 return;
1061         emit_time (logbuffer, now);
1062         emit_value (logbuffer, type);
1063         emit_value (logbuffer, handle);
1064         if (op == MONO_PROFILER_GC_HANDLE_CREATED)
1065                 emit_obj (logbuffer, obj);
1066         EXIT_LOG (logbuffer);
1067         process_requests (prof);
1068 }
1069
1070 static char*
1071 push_nesting (char *p, MonoClass *klass)
1072 {
1073         MonoClass *nesting;
1074         const char *name;
1075         const char *nspace;
1076         nesting = mono_class_get_nesting_type (klass);
1077         if (nesting) {
1078                 p = push_nesting (p, nesting);
1079                 *p++ = '/';
1080                 *p = 0;
1081         }
1082         name = mono_class_get_name (klass);
1083         nspace = mono_class_get_namespace (klass);
1084         if (*nspace) {
1085                 strcpy (p, nspace);
1086                 p += strlen (nspace);
1087                 *p++ = '.';
1088                 *p = 0;
1089         }
1090         strcpy (p, name);
1091         p += strlen (name);
1092         return p;
1093 }
1094
1095 static char*
1096 type_name (MonoClass *klass)
1097 {
1098         char buf [1024];
1099         char *p;
1100         push_nesting (buf, klass);
1101         p = malloc (strlen (buf) + 1);
1102         strcpy (p, buf);
1103         return p;
1104 }
1105
1106 static void
1107 image_loaded (MonoProfiler *prof, MonoImage *image, int result)
1108 {
1109         uint64_t now;
1110         const char *name;
1111         int nlen;
1112         LogBuffer *logbuffer;
1113         if (result != MONO_PROFILE_OK)
1114                 return;
1115         name = mono_image_get_filename (image);
1116         nlen = strlen (name) + 1;
1117         logbuffer = ensure_logbuf (16 + nlen);
1118         now = current_time ();
1119         ENTER_LOG (logbuffer, "image");
1120         emit_byte (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1121         emit_time (logbuffer, now);
1122         emit_byte (logbuffer, TYPE_IMAGE);
1123         emit_ptr (logbuffer, image);
1124         emit_value (logbuffer, 0); /* flags */
1125         memcpy (logbuffer->data, name, nlen);
1126         logbuffer->data += nlen;
1127         //printf ("loaded image %p (%s)\n", image, name);
1128         EXIT_LOG (logbuffer);
1129         if (logbuffer->next)
1130                 safe_send (prof, logbuffer);
1131         process_requests (prof);
1132 }
1133
1134 static void
1135 class_loaded (MonoProfiler *prof, MonoClass *klass, int result)
1136 {
1137         uint64_t now;
1138         char *name;
1139         int nlen;
1140         MonoImage *image;
1141         LogBuffer *logbuffer;
1142         if (result != MONO_PROFILE_OK)
1143                 return;
1144         if (runtime_inited)
1145                 name = mono_type_get_name (mono_class_get_type (klass));
1146         else
1147                 name = type_name (klass);
1148         nlen = strlen (name) + 1;
1149         image = mono_class_get_image (klass);
1150         logbuffer = ensure_logbuf (24 + nlen);
1151         now = current_time ();
1152         ENTER_LOG (logbuffer, "class");
1153         emit_byte (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1154         emit_time (logbuffer, now);
1155         emit_byte (logbuffer, TYPE_CLASS);
1156         emit_ptr (logbuffer, klass);
1157         emit_ptr (logbuffer, image);
1158         emit_value (logbuffer, 0); /* flags */
1159         memcpy (logbuffer->data, name, nlen);
1160         logbuffer->data += nlen;
1161         //printf ("loaded class %p (%s)\n", klass, name);
1162         if (runtime_inited)
1163                 mono_free (name);
1164         else
1165                 free (name);
1166         EXIT_LOG (logbuffer);
1167         if (logbuffer->next)
1168                 safe_send (prof, logbuffer);
1169         process_requests (prof);
1170 }
1171
1172 static void
1173 method_enter (MonoProfiler *prof, MonoMethod *method)
1174 {
1175         uint64_t now;
1176         LogBuffer *logbuffer = ensure_logbuf (16);
1177         if (logbuffer->call_depth++ > max_call_depth)
1178                 return;
1179         now = current_time ();
1180         ENTER_LOG (logbuffer, "enter");
1181         emit_byte (logbuffer, TYPE_ENTER | TYPE_METHOD);
1182         emit_time (logbuffer, now);
1183         emit_method (prof, logbuffer, mono_domain_get (), method);
1184         EXIT_LOG (logbuffer);
1185         process_requests (prof);
1186 }
1187
1188 static void
1189 method_leave (MonoProfiler *prof, MonoMethod *method)
1190 {
1191         uint64_t now;
1192         LogBuffer *logbuffer = ensure_logbuf (16);
1193         if (--logbuffer->call_depth > max_call_depth)
1194                 return;
1195         now = current_time ();
1196         ENTER_LOG (logbuffer, "leave");
1197         emit_byte (logbuffer, TYPE_LEAVE | TYPE_METHOD);
1198         emit_time (logbuffer, now);
1199         emit_method (prof, logbuffer, mono_domain_get (), method);
1200         EXIT_LOG (logbuffer);
1201         if (logbuffer->next)
1202                 safe_send (prof, logbuffer);
1203         process_requests (prof);
1204 }
1205
1206 static void
1207 method_exc_leave (MonoProfiler *prof, MonoMethod *method)
1208 {
1209         uint64_t now;
1210         LogBuffer *logbuffer;
1211         if (nocalls)
1212                 return;
1213         logbuffer = ensure_logbuf (16);
1214         if (--logbuffer->call_depth > max_call_depth)
1215                 return;
1216         now = current_time ();
1217         ENTER_LOG (logbuffer, "eleave");
1218         emit_byte (logbuffer, TYPE_EXC_LEAVE | TYPE_METHOD);
1219         emit_time (logbuffer, now);
1220         emit_method (prof, logbuffer, mono_domain_get (), method);
1221         EXIT_LOG (logbuffer);
1222         process_requests (prof);
1223 }
1224
1225 static void
1226 method_jitted (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *ji, int result)
1227 {
1228         if (result != MONO_PROFILE_OK)
1229                 return;
1230
1231         register_method_local (prof, NULL, method, ji);
1232 }
1233
1234 static void
1235 code_buffer_new (MonoProfiler *prof, void *buffer, int size, MonoProfilerCodeBufferType type, void *data)
1236 {
1237         uint64_t now;
1238         int nlen;
1239         char *name;
1240         LogBuffer *logbuffer;
1241         if (type == MONO_PROFILER_CODE_BUFFER_SPECIFIC_TRAMPOLINE) {
1242                 name = data;
1243                 nlen = strlen (name) + 1;
1244         } else {
1245                 name = NULL;
1246                 nlen = 0;
1247         }
1248         logbuffer = ensure_logbuf (32 + nlen);
1249         now = current_time ();
1250         ENTER_LOG (logbuffer, "code buffer");
1251         emit_byte (logbuffer, TYPE_JITHELPER | TYPE_RUNTIME);
1252         emit_time (logbuffer, now);
1253         emit_value (logbuffer, type);
1254         emit_ptr (logbuffer, buffer);
1255         emit_value (logbuffer, size);
1256         if (name) {
1257                 memcpy (logbuffer->data, name, nlen);
1258                 logbuffer->data += nlen;
1259         }
1260         EXIT_LOG (logbuffer);
1261         process_requests (prof);
1262 }
1263
1264 static void
1265 throw_exc (MonoProfiler *prof, MonoObject *object)
1266 {
1267         int do_bt = (nocalls && runtime_inited && !notraces)? TYPE_EXCEPTION_BT: 0;
1268         uint64_t now;
1269         FrameData data;
1270         LogBuffer *logbuffer;
1271         if (do_bt)
1272                 collect_bt (&data);
1273         logbuffer = ensure_logbuf (16 + MAX_FRAMES * 8);
1274         now = current_time ();
1275         ENTER_LOG (logbuffer, "throw");
1276         emit_byte (logbuffer, do_bt | TYPE_EXCEPTION);
1277         emit_time (logbuffer, now);
1278         emit_obj (logbuffer, object);
1279         if (do_bt)
1280                 emit_bt (logbuffer, &data);
1281         EXIT_LOG (logbuffer);
1282         process_requests (prof);
1283 }
1284
1285 static void
1286 clause_exc (MonoProfiler *prof, MonoMethod *method, int clause_type, int clause_num)
1287 {
1288         uint64_t now;
1289         LogBuffer *logbuffer = ensure_logbuf (16);
1290         now = current_time ();
1291         ENTER_LOG (logbuffer, "clause");
1292         emit_byte (logbuffer, TYPE_EXCEPTION | TYPE_CLAUSE);
1293         emit_time (logbuffer, now);
1294         emit_value (logbuffer, clause_type);
1295         emit_value (logbuffer, clause_num);
1296         emit_method (prof, logbuffer, mono_domain_get (), method);
1297         EXIT_LOG (logbuffer);
1298 }
1299
1300 static void
1301 monitor_event (MonoProfiler *profiler, MonoObject *object, MonoProfilerMonitorEvent event)
1302 {
1303         int do_bt = (nocalls && runtime_inited && !notraces && event == MONO_PROFILER_MONITOR_CONTENTION)? TYPE_MONITOR_BT: 0;
1304         uint64_t now;
1305         FrameData data;
1306         LogBuffer *logbuffer;
1307         if (do_bt)
1308                 collect_bt (&data);
1309         logbuffer = ensure_logbuf (16 + MAX_FRAMES * 8);
1310         now = current_time ();
1311         ENTER_LOG (logbuffer, "monitor");
1312         emit_byte (logbuffer, (event << 4) | do_bt | TYPE_MONITOR);
1313         emit_time (logbuffer, now);
1314         emit_obj (logbuffer, object);
1315         if (do_bt)
1316                 emit_bt (logbuffer, &data);
1317         EXIT_LOG (logbuffer);
1318         process_requests (profiler);
1319 }
1320
1321 static void
1322 thread_start (MonoProfiler *prof, uintptr_t tid)
1323 {
1324         //printf ("thread start %p\n", (void*)tid);
1325         init_thread ();
1326 }
1327
1328 static void
1329 thread_end (MonoProfiler *prof, uintptr_t tid)
1330 {
1331         if (TLS_GET (LogBuffer, tlsbuffer))
1332                 send_buffer (prof, TLS_GET (GPtrArray, tlsmethodlist), TLS_GET (LogBuffer, tlsbuffer));
1333
1334         TLS_SET (tlsbuffer, NULL);
1335         TLS_SET (tlsmethodlist, NULL);
1336 }
1337
1338 static void
1339 thread_name (MonoProfiler *prof, uintptr_t tid, const char *name)
1340 {
1341         int len = strlen (name) + 1;
1342         uint64_t now;
1343         LogBuffer *logbuffer;
1344         logbuffer = ensure_logbuf (10 + len);
1345         now = current_time ();
1346         ENTER_LOG (logbuffer, "tname");
1347         emit_byte (logbuffer, TYPE_METADATA);
1348         emit_time (logbuffer, now);
1349         emit_byte (logbuffer, TYPE_THREAD);
1350         emit_ptr (logbuffer, (void*)tid);
1351         emit_value (logbuffer, 0); /* flags */
1352         memcpy (logbuffer->data, name, len);
1353         logbuffer->data += len;
1354         EXIT_LOG (logbuffer);
1355 }
1356
1357 typedef struct {
1358         MonoMethod *method;
1359         MonoDomain *domain;
1360         void *base_address;
1361         int offset;
1362 } AsyncFrameInfo;
1363
1364 typedef struct {
1365         int count;
1366         AsyncFrameInfo *data;
1367 } AsyncFrameData;
1368
1369 static mono_bool
1370 async_walk_stack (MonoMethod *method, MonoDomain *domain, void *base_address, int offset, void *data)
1371 {
1372         AsyncFrameData *frame = data;
1373         if (frame->count < num_frames) {
1374                 frame->data [frame->count].method = method;
1375                 frame->data [frame->count].domain = domain;
1376                 frame->data [frame->count].base_address = base_address;
1377                 frame->data [frame->count].offset = offset;
1378                 // printf ("In %d at %p (dom %p) (native: %p)\n", frame->count, method, domain, base_address);
1379                 frame->count++;
1380         }
1381         return frame->count == num_frames;
1382 }
1383
1384 /*
1385 (type | frame count), tid, time, ip, [method, domain, base address, offset] * frames
1386 */
1387 #define SAMPLE_EVENT_SIZE_IN_SLOTS(FRAMES) (4 + (FRAMES) * 4)
1388
1389 static void
1390 mono_sample_hit (MonoProfiler *profiler, unsigned char *ip, void *context)
1391 {
1392         StatBuffer *sbuf;
1393         AsyncFrameInfo frames [num_frames];
1394         AsyncFrameData bt_data = { 0, &frames [0]};
1395         uint64_t now;
1396         uintptr_t *data, *new_data, *old_data;
1397         uintptr_t elapsed;
1398         int timedout = 0;
1399         int i;
1400         if (in_shutdown)
1401                 return;
1402         now = current_time ();
1403
1404         mono_stack_walk_async_safe (&async_walk_stack, context, &bt_data);
1405
1406         elapsed = (now - profiler->startup_time) / 10000;
1407         if (do_debug) {
1408                 int len;
1409                 char buf [256];
1410                 snprintf (buf, sizeof (buf), "hit at %p in thread %p after %llu ms\n", ip, (void*)thread_id (), (unsigned long long int)elapsed/100);
1411                 len = strlen (buf);
1412                 ign_res (write (2, buf, len));
1413         }
1414         sbuf = profiler->stat_buffers;
1415         if (!sbuf)
1416                 return;
1417         /* flush the buffer at 1 second intervals */
1418         if (sbuf->data > sbuf->buf && (elapsed - sbuf->buf [2]) > 100000) {
1419                 timedout = 1;
1420         }
1421         /* overflow: 400 slots is a big enough number to reduce the chance of losing this event if many
1422          * threads hit this same spot at the same time
1423          */
1424         if (timedout || (sbuf->data + 400 >= sbuf->data_end)) {
1425                 StatBuffer *oldsb, *foundsb;
1426                 sbuf = create_stat_buffer ();
1427                 do {
1428                         oldsb = profiler->stat_buffers;
1429                         sbuf->next = oldsb;
1430                         foundsb = InterlockedCompareExchangePointer ((void * volatile*)&profiler->stat_buffers, sbuf, oldsb);
1431                 } while (foundsb != oldsb);
1432                 if (do_debug)
1433                         ign_res (write (2, "overflow\n", 9));
1434                 /* notify the helper thread */
1435                 if (sbuf->next->next) {
1436                         char c = 0;
1437                         ign_res (write (profiler->pipes [1], &c, 1));
1438                         if (do_debug)
1439                                 ign_res (write (2, "notify\n", 7));
1440                 }
1441         }
1442         do {
1443                 old_data = sbuf->data;
1444                 new_data = old_data + SAMPLE_EVENT_SIZE_IN_SLOTS (bt_data.count);
1445                 data = InterlockedCompareExchangePointer ((void * volatile*)&sbuf->data, new_data, old_data);
1446         } while (data != old_data);
1447         if (old_data >= sbuf->data_end)
1448                 return; /* lost event */
1449         old_data [0] = 1 | (sample_type << 16) | (bt_data.count << 8);
1450         old_data [1] = thread_id ();
1451         old_data [2] = elapsed;
1452         old_data [3] = (uintptr_t)ip;
1453         for (i = 0; i < bt_data.count; ++i) {
1454                 old_data [4 + 4 * i + 0] = (uintptr_t)frames [i].method;
1455                 old_data [4 + 4 * i + 1] = (uintptr_t)frames [i].domain;
1456                 old_data [4 + 4 * i + 2] = (uintptr_t)frames [i].base_address;
1457                 old_data [4 + 4 * i + 3] = (uintptr_t)frames [i].offset;
1458         }
1459 }
1460
1461 static uintptr_t *code_pages = 0;
1462 static int num_code_pages = 0;
1463 static int size_code_pages = 0;
1464 #define CPAGE_SHIFT (9)
1465 #define CPAGE_SIZE (1 << CPAGE_SHIFT)
1466 #define CPAGE_MASK (~(CPAGE_SIZE - 1))
1467 #define CPAGE_ADDR(p) ((p) & CPAGE_MASK)
1468
1469 static uintptr_t
1470 add_code_page (uintptr_t *hash, uintptr_t hsize, uintptr_t page)
1471 {
1472         uintptr_t i;
1473         uintptr_t start_pos;
1474         start_pos = (page >> CPAGE_SHIFT) % hsize;
1475         i = start_pos;
1476         do {
1477                 if (hash [i] && CPAGE_ADDR (hash [i]) == CPAGE_ADDR (page)) {
1478                         return 0;
1479                 } else if (!hash [i]) {
1480                         hash [i] = page;
1481                         return 1;
1482                 }
1483                 /* wrap around */
1484                 if (++i == hsize)
1485                         i = 0;
1486         } while (i != start_pos);
1487         /* should not happen */
1488         printf ("failed code page store\n");
1489         return 0;
1490 }
1491
1492 static void
1493 add_code_pointer (uintptr_t ip)
1494 {
1495         uintptr_t i;
1496         if (num_code_pages * 2 >= size_code_pages) {
1497                 uintptr_t *n;
1498                 uintptr_t old_size = size_code_pages;
1499                 size_code_pages *= 2;
1500                 if (size_code_pages == 0)
1501                         size_code_pages = 16;
1502                 n = calloc (sizeof (uintptr_t) * size_code_pages, 1);
1503                 for (i = 0; i < old_size; ++i) {
1504                         if (code_pages [i])
1505                                 add_code_page (n, size_code_pages, code_pages [i]);
1506                 }
1507                 if (code_pages)
1508                         free (code_pages);
1509                 code_pages = n;
1510         }
1511         num_code_pages += add_code_page (code_pages, size_code_pages, ip & CPAGE_MASK);
1512 }
1513
1514 #if defined(HAVE_DL_ITERATE_PHDR) && defined(ELFMAG0)
1515 static void
1516 dump_ubin (const char *filename, uintptr_t load_addr, uint64_t offset, uintptr_t size)
1517 {
1518         uint64_t now;
1519         LogBuffer *logbuffer;
1520         int len;
1521         len = strlen (filename) + 1;
1522         now = current_time ();
1523         logbuffer = ensure_logbuf (20 + len);
1524         emit_byte (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_UBIN);
1525         emit_time (logbuffer, now);
1526         emit_svalue (logbuffer, load_addr);
1527         emit_uvalue (logbuffer, offset);
1528         emit_uvalue (logbuffer, size);
1529         memcpy (logbuffer->data, filename, len);
1530         logbuffer->data += len;
1531 }
1532 #endif
1533
1534 static void
1535 dump_usym (const char *name, uintptr_t value, uintptr_t size)
1536 {
1537         LogBuffer *logbuffer;
1538         int len;
1539         len = strlen (name) + 1;
1540         logbuffer = ensure_logbuf (20 + len);
1541         emit_byte (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_USYM);
1542         emit_ptr (logbuffer, (void*)value);
1543         emit_value (logbuffer, size);
1544         memcpy (logbuffer->data, name, len);
1545         logbuffer->data += len;
1546 }
1547
1548 #ifdef ELFMAG0
1549
1550 #if SIZEOF_VOID_P == 4
1551 #define ELF_WSIZE 32
1552 #else
1553 #define ELF_WSIZE 64
1554 #endif
1555 #ifndef ElfW
1556 #define ElfW(type)      _ElfW (Elf, ELF_WSIZE, type)
1557 #define _ElfW(e,w,t)    _ElfW_1 (e, w, _##t)
1558 #define _ElfW_1(e,w,t)  e##w##t
1559 #endif
1560
1561 static void
1562 dump_elf_symbols (ElfW(Sym) *symbols, int num_symbols, const char *strtab, void *load_addr)
1563 {
1564         int i;
1565         for (i = 0; i < num_symbols; ++i) {
1566                 const char* sym;
1567                 sym =  strtab + symbols [i].st_name;
1568                 if (!symbols [i].st_name || !symbols [i].st_size || (symbols [i].st_info & 0xf) != STT_FUNC)
1569                         continue;
1570                 //printf ("symbol %s at %d\n", sym, symbols [i].st_value);
1571                 dump_usym (sym, (uintptr_t)load_addr + symbols [i].st_value, symbols [i].st_size);
1572         }
1573 }
1574
1575 static int
1576 read_elf_symbols (MonoProfiler *prof, const char *filename, void *load_addr)
1577 {
1578         int fd, i;
1579         void *data;
1580         struct stat statb;
1581         uint64_t file_size;
1582         ElfW(Ehdr) *header;
1583         ElfW(Shdr) *sheader;
1584         ElfW(Shdr) *shstrtabh;
1585         ElfW(Shdr) *symtabh = NULL;
1586         ElfW(Shdr) *strtabh = NULL;
1587         ElfW(Sym) *symbols = NULL;
1588         const char *strtab;
1589         int num_symbols;
1590
1591         fd = open (filename, O_RDONLY);
1592         if (fd < 0)
1593                 return 0;
1594         if (fstat (fd, &statb) != 0) {
1595                 close (fd);
1596                 return 0;
1597         }
1598         file_size = statb.st_size;
1599         data = mmap (NULL, file_size, PROT_READ, MAP_PRIVATE, fd, 0);
1600         close (fd);
1601         if (data == MAP_FAILED)
1602                 return 0;
1603         header = data;
1604         if (header->e_ident [EI_MAG0] != ELFMAG0 ||
1605                         header->e_ident [EI_MAG1] != ELFMAG1 ||
1606                         header->e_ident [EI_MAG2] != ELFMAG2 ||
1607                         header->e_ident [EI_MAG3] != ELFMAG3 ) {
1608                 munmap (data, file_size);
1609                 return 0;
1610         }
1611         sheader = (void*)((char*)data + header->e_shoff);
1612         shstrtabh = (void*)((char*)sheader + (header->e_shentsize * header->e_shstrndx));
1613         strtab = (const char*)data + shstrtabh->sh_offset;
1614         for (i = 0; i < header->e_shnum; ++i) {
1615                 //printf ("section header: %d\n", sheader->sh_type);
1616                 if (sheader->sh_type == SHT_SYMTAB) {
1617                         symtabh = sheader;
1618                         strtabh = (void*)((char*)data + header->e_shoff + sheader->sh_link * header->e_shentsize);
1619                         /*printf ("symtab section header: %d, .strstr: %d\n", i, sheader->sh_link);*/
1620                         break;
1621                 }
1622                 sheader = (void*)((char*)sheader + header->e_shentsize);
1623         }
1624         if (!symtabh || !strtabh) {
1625                 munmap (data, file_size);
1626                 return 0;
1627         }
1628         strtab = (const char*)data + strtabh->sh_offset;
1629         num_symbols = symtabh->sh_size / symtabh->sh_entsize;
1630         symbols = (void*)((char*)data + symtabh->sh_offset);
1631         dump_elf_symbols (symbols, num_symbols, strtab, load_addr);
1632         munmap (data, file_size);
1633         return 1;
1634 }
1635 #endif
1636
1637 #if defined(HAVE_DL_ITERATE_PHDR) && defined(ELFMAG0)
1638 static int
1639 elf_dl_callback (struct dl_phdr_info *info, size_t size, void *data)
1640 {
1641         MonoProfiler *prof = data;
1642         char buf [256];
1643         const char *filename;
1644         BinaryObject *obj;
1645         char *a = (void*)info->dlpi_addr;
1646         int i, num_sym;
1647         ElfW(Dyn) *dyn = NULL;
1648         ElfW(Sym) *symtab = NULL;
1649         ElfW(Word) *hash_table = NULL;
1650         ElfW(Ehdr) *header = NULL;
1651         const char* strtab = NULL;
1652         for (obj = prof->binary_objects; obj; obj = obj->next) {
1653                 if (obj->addr == a)
1654                         return 0;
1655         }
1656         filename = info->dlpi_name;
1657         if (!filename)
1658                 return 0;
1659         if (!info->dlpi_addr && !filename [0]) {
1660                 int l = readlink ("/proc/self/exe", buf, sizeof (buf) - 1);
1661                 if (l > 0) {
1662                         buf [l] = 0;
1663                         filename = buf;
1664                 }
1665         }
1666         obj = calloc (sizeof (BinaryObject), 1);
1667         obj->addr = (void*)info->dlpi_addr;
1668         obj->name = pstrdup (filename);
1669         obj->next = prof->binary_objects;
1670         prof->binary_objects = obj;
1671         //printf ("loaded file: %s at %p, segments: %d\n", filename, (void*)info->dlpi_addr, info->dlpi_phnum);
1672         a = NULL;
1673         for (i = 0; i < info->dlpi_phnum; ++i) {
1674                 //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);
1675                 if (info->dlpi_phdr[i].p_type == PT_LOAD && !header) {
1676                         header = (ElfW(Ehdr)*)(info->dlpi_addr + info->dlpi_phdr[i].p_vaddr);
1677                         if (header->e_ident [EI_MAG0] != ELFMAG0 ||
1678                                         header->e_ident [EI_MAG1] != ELFMAG1 ||
1679                                         header->e_ident [EI_MAG2] != ELFMAG2 ||
1680                                         header->e_ident [EI_MAG3] != ELFMAG3 ) {
1681                                 header = NULL;
1682                         }
1683                         dump_ubin (filename, info->dlpi_addr + info->dlpi_phdr[i].p_vaddr, info->dlpi_phdr[i].p_offset, info->dlpi_phdr[i].p_memsz);
1684                 } else if (info->dlpi_phdr[i].p_type == PT_DYNAMIC) {
1685                         dyn = (ElfW(Dyn) *)(info->dlpi_addr + info->dlpi_phdr[i].p_vaddr);
1686                 }
1687         }
1688         if (read_elf_symbols (prof, filename, (void*)info->dlpi_addr))
1689                 return 0;
1690         if (!info->dlpi_name || !info->dlpi_name[0])
1691                 return 0;
1692         if (!dyn)
1693                 return 0;
1694         for (i = 0; dyn [i].d_tag != DT_NULL; ++i) {
1695                 if (dyn [i].d_tag == DT_SYMTAB) {
1696                         if (symtab && do_debug)
1697                                 printf ("multiple symtabs: %d\n", i);
1698                         symtab = (ElfW(Sym) *)(a + dyn [i].d_un.d_ptr);
1699                 } else if (dyn [i].d_tag == DT_HASH) {
1700                         hash_table = (ElfW(Word) *)(a + dyn [i].d_un.d_ptr);
1701                 } else if (dyn [i].d_tag == DT_STRTAB) {
1702                         strtab = (const char*)(a + dyn [i].d_un.d_ptr);
1703                 }
1704         }
1705         if (!hash_table)
1706                 return 0;
1707         num_sym = hash_table [1];
1708         dump_elf_symbols (symtab, num_sym, strtab, (void*)info->dlpi_addr);
1709         return 0;
1710 }
1711
1712 static int
1713 load_binaries (MonoProfiler *prof)
1714 {
1715         dl_iterate_phdr (elf_dl_callback, prof);
1716         return 1;
1717 }
1718 #else
1719 static int
1720 load_binaries (MonoProfiler *prof)
1721 {
1722         return 0;
1723 }
1724 #endif
1725
1726 static const char*
1727 symbol_for (uintptr_t code)
1728 {
1729 #ifdef HAVE_DLADDR
1730         void *ip = (void*)code;
1731         Dl_info di;
1732         if (dladdr (ip, &di)) {
1733                 if (di.dli_sname)
1734                         return di.dli_sname;
1735         } else {
1736         /*      char **names;
1737                 names = backtrace_symbols (&ip, 1);
1738                 if (names) {
1739                         const char* p = names [0];
1740                         free (names);
1741                         return p;
1742                 }
1743                 */
1744         }
1745 #endif
1746         return NULL;
1747 }
1748
1749 static void
1750 dump_unmanaged_coderefs (MonoProfiler *prof)
1751 {
1752         int i;
1753         const char* last_symbol;
1754         uintptr_t addr, page_end;
1755
1756         if (load_binaries (prof))
1757                 return;
1758         for (i = 0; i < size_code_pages; ++i) {
1759                 const char* sym;
1760                 if (!code_pages [i] || code_pages [i] & 1)
1761                         continue;
1762                 last_symbol = NULL;
1763                 addr = CPAGE_ADDR (code_pages [i]);
1764                 page_end = addr + CPAGE_SIZE;
1765                 code_pages [i] |= 1;
1766                 /* we dump the symbols for the whole page */
1767                 for (; addr < page_end; addr += 16) {
1768                         sym = symbol_for (addr);
1769                         if (sym && sym == last_symbol)
1770                                 continue;
1771                         last_symbol = sym;
1772                         if (!sym)
1773                                 continue;
1774                         dump_usym (sym, addr, 0); /* let's not guess the size */
1775                         //printf ("found symbol at %p: %s\n", (void*)addr, sym);
1776                 }
1777         }
1778 }
1779
1780 static void
1781 dump_sample_hits (MonoProfiler *prof, StatBuffer *sbuf)
1782 {
1783         uintptr_t *sample;
1784         LogBuffer *logbuffer;
1785         if (!sbuf)
1786                 return;
1787         if (sbuf->next) {
1788                 dump_sample_hits (prof, sbuf->next);
1789                 free_buffer (sbuf->next, sbuf->next->size);
1790                 sbuf->next = NULL;
1791         }
1792         for (sample = sbuf->buf; sample < sbuf->data;) {
1793                 int i;
1794                 int count = sample [0] & 0xff;
1795                 int mbt_count = (sample [0] & 0xff00) >> 8;
1796                 int type = sample [0] >> 16;
1797                 uintptr_t *managed_sample_base = sample + count + 3;
1798
1799                 if (sample + SAMPLE_EVENT_SIZE_IN_SLOTS (mbt_count) > sbuf->data)
1800                         break;
1801
1802                 for (i = 0; i < mbt_count; ++i) {
1803                         MonoMethod *method = (MonoMethod*)managed_sample_base [i * 4 + 0];
1804                         MonoDomain *domain = (MonoDomain*)managed_sample_base [i * 4 + 1];
1805                         void *address = (void*)managed_sample_base [i * 4 + 2];
1806
1807                         if (!method) {
1808                                 MonoJitInfo *ji = mono_jit_info_table_find (domain, address);
1809
1810                                 if (ji)
1811                                         managed_sample_base [i * 4 + 0] = (uintptr_t)mono_jit_info_get_method (ji);
1812                         }
1813                 }
1814                 logbuffer = ensure_logbuf (20 + count * 8);
1815                 emit_byte (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_HIT);
1816                 emit_value (logbuffer, type);
1817                 emit_uvalue (logbuffer, prof->startup_time + (uint64_t)sample [2] * (uint64_t)10000);
1818                 emit_value (logbuffer, count);
1819                 for (i = 0; i < count; ++i) {
1820                         emit_ptr (logbuffer, (void*)sample [i + 3]);
1821                         add_code_pointer (sample [i + 3]);
1822                 }
1823
1824                 sample += count + 3;
1825                 /* new in data version 6 */
1826                 emit_uvalue (logbuffer, mbt_count);
1827                 for (i = 0; i < mbt_count; ++i) {
1828                         MonoMethod *method = (MonoMethod *) sample [i * 4 + 0];
1829                         MonoDomain *domain = (MonoDomain *) sample [i * 4 + 1];
1830                         uintptr_t native_offset = sample [i * 4 + 3];
1831
1832                         emit_method (prof, logbuffer, domain, method);
1833                         emit_svalue (logbuffer, 0); /* il offset will always be 0 from now on */
1834                         emit_svalue (logbuffer, native_offset);
1835                 }
1836                 sample += 4 * mbt_count;
1837         }
1838         dump_unmanaged_coderefs (prof);
1839 }
1840
1841 #if USE_PERF_EVENTS
1842
1843 static int
1844 mono_cpu_count (void)
1845 {
1846         int count = 0;
1847 #ifdef PLATFORM_ANDROID
1848         /* Android tries really hard to save power by powering off CPUs on SMP phones which
1849          * means the normal way to query cpu count returns a wrong value with userspace API.
1850          * Instead we use /sys entries to query the actual hardware CPU count.
1851          */
1852         char buffer[8] = {'\0'};
1853         int present = open ("/sys/devices/system/cpu/present", O_RDONLY);
1854         /* Format of the /sys entry is a cpulist of indexes which in the case
1855          * of present is always of the form "0-(n-1)" when there is more than
1856          * 1 core, n being the number of CPU cores in the system. Otherwise
1857          * the value is simply 0
1858          */
1859         if (present != -1 && read (present, (char*)buffer, sizeof (buffer)) > 3)
1860                 count = strtol (((char*)buffer) + 2, NULL, 10);
1861         if (present != -1)
1862                 close (present);
1863         if (count > 0)
1864                 return count + 1;
1865 #endif
1866 #ifdef _SC_NPROCESSORS_ONLN
1867         count = sysconf (_SC_NPROCESSORS_ONLN);
1868         if (count > 0)
1869                 return count;
1870 #endif
1871 #ifdef USE_SYSCTL
1872         {
1873                 int mib [2];
1874                 size_t len = sizeof (int);
1875                 mib [0] = CTL_HW;
1876                 mib [1] = HW_NCPU;
1877                 if (sysctl (mib, 2, &count, &len, NULL, 0) == 0)
1878                         return count;
1879         }
1880 #endif
1881 #ifdef HOST_WIN32
1882         {
1883                 SYSTEM_INFO info;
1884                 GetSystemInfo (&info);
1885                 return info.dwNumberOfProcessors;
1886         }
1887 #endif
1888         /* FIXME: warn */
1889         return 1;
1890 }
1891
1892 typedef struct {
1893         int perf_fd;
1894         unsigned int prev_pos;
1895         void *mmap_base;
1896         struct perf_event_mmap_page *page_desc;
1897 } PerfData ;
1898
1899 static PerfData *perf_data = NULL;
1900 static int num_perf;
1901 #define PERF_PAGES_SHIFT 4
1902 static int num_pages = 1 << PERF_PAGES_SHIFT;
1903 static unsigned int mmap_mask;
1904
1905 typedef struct {
1906         struct perf_event_header h;
1907         uint64_t ip;
1908         uint32_t pid;
1909         uint32_t tid;
1910         uint64_t timestamp;
1911         uint64_t period;
1912         uint64_t nframes;
1913 } PSample;
1914
1915 static int
1916 perf_event_syscall (struct perf_event_attr *attr, pid_t pid, int cpu, int group_fd, unsigned long flags)
1917 {
1918         attr->size = PERF_ATTR_SIZE_VER0;
1919         //printf ("perf attr size: %d\n", attr->size);
1920 #if defined(__x86_64__)
1921         return syscall(/*__NR_perf_event_open*/ 298, attr, pid, cpu, group_fd, flags);
1922 #elif defined(__i386__)
1923         return syscall(/*__NR_perf_event_open*/ 336, attr, pid, cpu, group_fd, flags);
1924 #elif defined(__arm__) || defined (__aarch64__)
1925         return syscall(/*__NR_perf_event_open*/ 364, attr, pid, cpu, group_fd, flags);
1926 #else
1927         return -1;
1928 #endif
1929 }
1930
1931 static int
1932 setup_perf_map (PerfData *perf)
1933 {
1934         perf->mmap_base = mmap (NULL, (num_pages + 1) * getpagesize (), PROT_READ|PROT_WRITE, MAP_SHARED, perf->perf_fd, 0);
1935         if (perf->mmap_base == MAP_FAILED) {
1936                 if (do_debug)
1937                         printf ("failed mmap\n");
1938                 return 0;
1939         }
1940         perf->page_desc = perf->mmap_base;
1941         if (do_debug)
1942                 printf ("mmap version: %d\n", perf->page_desc->version);
1943         return 1;
1944 }
1945
1946 static void
1947 dump_perf_hits (MonoProfiler *prof, void *buf, int size)
1948 {
1949         LogBuffer *logbuffer;
1950         void *end = (char*)buf + size;
1951         int samples = 0;
1952         int pid = getpid ();
1953
1954         while (buf < end) {
1955                 PSample *s = buf;
1956                 if (s->h.size == 0)
1957                         break;
1958                 if (pid != s->pid) {
1959                         if (do_debug)
1960                                 printf ("event for different pid: %d\n", s->pid);
1961                         buf = (char*)buf + s->h.size;
1962                         continue;
1963                 }
1964                 /*ip = (void*)s->ip;
1965                 printf ("sample: %d, size: %d, ip: %p (%s), timestamp: %llu, nframes: %llu\n",
1966                         s->h.type, s->h.size, ip, symbol_for (ip), s->timestamp, s->nframes);*/
1967                 logbuffer = ensure_logbuf (20 + s->nframes * 8);
1968                 emit_byte (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_HIT);
1969                 emit_value (logbuffer, sample_type);
1970                 emit_uvalue (logbuffer, s->timestamp - prof->startup_time);
1971                 emit_value (logbuffer, 1); /* count */
1972                 emit_ptr (logbuffer, (void*)(uintptr_t)s->ip);
1973                 /* no support here yet for the managed backtrace */
1974                 emit_uvalue (logbuffer, 0);
1975                 add_code_pointer (s->ip);
1976                 buf = (char*)buf + s->h.size;
1977                 samples++;
1978         }
1979         if (do_debug)
1980                 printf ("dumped %d samples\n", samples);
1981         dump_unmanaged_coderefs (prof);
1982 }
1983
1984 /* read events from the ring buffer */
1985 static int
1986 read_perf_mmap (MonoProfiler* prof, int cpu)
1987 {
1988         PerfData *perf = perf_data + cpu;
1989         unsigned char *buf;
1990         unsigned char *data = (unsigned char*)perf->mmap_base + getpagesize ();
1991         unsigned int head = perf->page_desc->data_head;
1992         int diff, size;
1993         unsigned int old;
1994
1995         mono_memory_read_barrier ();
1996
1997         old = perf->prev_pos;
1998         diff = head - old;
1999         if (diff < 0) {
2000                 if (do_debug)
2001                         printf ("lost mmap events: old: %d, head: %d\n", old, head);
2002                 old = head;
2003         }
2004         size = head - old;
2005         if ((old & mmap_mask) + size != (head & mmap_mask)) {
2006                 buf = data + (old & mmap_mask);
2007                 size = mmap_mask + 1 - (old & mmap_mask);
2008                 old += size;
2009                 /* size bytes at buf */
2010                 if (do_debug)
2011                         printf ("found1 bytes of events: %d\n", size);
2012                 dump_perf_hits (prof, buf, size);
2013         }
2014         buf = data + (old & mmap_mask);
2015         size = head - old;
2016         /* size bytes at buf */
2017         if (do_debug)
2018                 printf ("found bytes of events: %d\n", size);
2019         dump_perf_hits (prof, buf, size);
2020         old += size;
2021         perf->prev_pos = old;
2022         perf->page_desc->data_tail = old;
2023         return 0;
2024 }
2025
2026 static int
2027 setup_perf_event_for_cpu (PerfData *perf, int cpu)
2028 {
2029         struct perf_event_attr attr;
2030         memset (&attr, 0, sizeof (attr));
2031         attr.type = PERF_TYPE_HARDWARE;
2032         switch (sample_type) {
2033         case SAMPLE_CYCLES: attr.config = PERF_COUNT_HW_CPU_CYCLES; break;
2034         case SAMPLE_INSTRUCTIONS: attr.config = PERF_COUNT_HW_INSTRUCTIONS; break;
2035         case SAMPLE_CACHE_MISSES: attr.config = PERF_COUNT_HW_CACHE_MISSES; break;
2036         case SAMPLE_CACHE_REFS: attr.config = PERF_COUNT_HW_CACHE_REFERENCES; break;
2037         case SAMPLE_BRANCHES: attr.config = PERF_COUNT_HW_BRANCH_INSTRUCTIONS; break;
2038         case SAMPLE_BRANCH_MISSES: attr.config = PERF_COUNT_HW_BRANCH_MISSES; break;
2039         default: attr.config = PERF_COUNT_HW_CPU_CYCLES; break;
2040         }
2041         attr.sample_type = PERF_SAMPLE_IP | PERF_SAMPLE_TID | PERF_SAMPLE_PERIOD | PERF_SAMPLE_TIME;
2042 //      attr.sample_type |= PERF_SAMPLE_CALLCHAIN;
2043         attr.read_format = PERF_FORMAT_TOTAL_TIME_ENABLED | PERF_FORMAT_TOTAL_TIME_RUNNING | PERF_FORMAT_ID;
2044         attr.inherit = 1;
2045         attr.freq = 1;
2046         attr.sample_freq = sample_freq;
2047
2048         perf->perf_fd = perf_event_syscall (&attr, getpid (), cpu, -1, 0);
2049         if (do_debug)
2050                 printf ("perf fd: %d, freq: %d, event: %llu\n", perf->perf_fd, sample_freq, attr.config);
2051         if (perf->perf_fd < 0) {
2052                 if (perf->perf_fd == -EPERM) {
2053                         fprintf (stderr, "Perf syscall denied, do \"echo 1 > /proc/sys/kernel/perf_event_paranoid\" as root to enable.\n");
2054                 } else {
2055                         if (do_debug)
2056                                 perror ("open perf event");
2057                 }
2058                 return 0;
2059         }
2060         if (!setup_perf_map (perf)) {
2061                 close (perf->perf_fd);
2062                 perf->perf_fd = -1;
2063                 return 0;
2064         }
2065         return 1;
2066 }
2067
2068 static int
2069 setup_perf_event (void)
2070 {
2071         int i, count = 0;
2072         mmap_mask = num_pages * getpagesize () - 1;
2073         num_perf = mono_cpu_count ();
2074         perf_data = calloc (num_perf, sizeof (PerfData));
2075         for (i = 0; i < num_perf; ++i) {
2076                 count += setup_perf_event_for_cpu (perf_data + i, i);
2077         }
2078         if (count)
2079                 return 1;
2080         free (perf_data);
2081         perf_data = NULL;
2082         return 0;
2083 }
2084
2085 #endif /* USE_PERF_EVENTS */
2086
2087 #ifndef DISABLE_HELPER_THREAD
2088
2089 typedef struct MonoCounterAgent {
2090         MonoCounter *counter;
2091         // MonoCounterAgent specific data :
2092         void *value;
2093         size_t value_size;
2094         short index;
2095         short emitted;
2096         struct MonoCounterAgent *next;
2097 } MonoCounterAgent;
2098
2099 static MonoCounterAgent* counters;
2100 static gboolean counters_initialized = FALSE;
2101 static int counters_index = 1;
2102 static mono_mutex_t counters_mutex;
2103
2104 static void
2105 counters_add_agent (MonoCounter *counter)
2106 {
2107         MonoCounterAgent *agent, *item;
2108
2109         if (!counters_initialized)
2110                 return;
2111
2112         mono_mutex_lock (&counters_mutex);
2113
2114         for (agent = counters; agent; agent = agent->next) {
2115                 if (agent->counter == counter) {
2116                         agent->value_size = 0;
2117                         if (agent->value) {
2118                                 free (agent->value);
2119                                 agent->value = NULL;
2120                         }
2121                         mono_mutex_unlock (&counters_mutex);
2122                         return;
2123                 }
2124         }
2125
2126         agent = malloc (sizeof (MonoCounterAgent));
2127         agent->counter = counter;
2128         agent->value = NULL;
2129         agent->value_size = 0;
2130         agent->index = counters_index++;
2131         agent->emitted = 0;
2132         agent->next = NULL;
2133
2134         if (!counters) {
2135                 counters = agent;
2136         } else {
2137                 item = counters;
2138                 while (item->next)
2139                         item = item->next;
2140                 item->next = agent;
2141         }
2142
2143         mono_mutex_unlock (&counters_mutex);
2144 }
2145
2146 static mono_bool
2147 counters_init_foreach_callback (MonoCounter *counter, gpointer data)
2148 {
2149         counters_add_agent (counter);
2150         return TRUE;
2151 }
2152
2153 static void
2154 counters_init (MonoProfiler *profiler)
2155 {
2156         assert (!counters_initialized);
2157
2158         mono_mutex_init (&counters_mutex);
2159
2160         counters_initialized = TRUE;
2161
2162         mono_counters_on_register (&counters_add_agent);
2163         mono_counters_foreach (counters_init_foreach_callback, NULL);
2164 }
2165
2166 static void
2167 counters_emit (MonoProfiler *profiler)
2168 {
2169         MonoCounterAgent *agent;
2170         LogBuffer *logbuffer;
2171         int size = 1 + 5, len = 0;
2172
2173         if (!counters_initialized)
2174                 return;
2175
2176         mono_mutex_lock (&counters_mutex);
2177
2178         for (agent = counters; agent; agent = agent->next) {
2179                 if (agent->emitted)
2180                         continue;
2181
2182                 size += strlen (mono_counter_get_name (agent->counter)) + 1 + 5 * 5;
2183                 len += 1;
2184         }
2185
2186         if (!len) {
2187                 mono_mutex_unlock (&counters_mutex);
2188                 return;
2189         }
2190
2191         logbuffer = ensure_logbuf (size);
2192
2193         ENTER_LOG (logbuffer, "counters");
2194         emit_byte (logbuffer, TYPE_SAMPLE_COUNTERS_DESC | TYPE_SAMPLE);
2195         emit_value (logbuffer, len);
2196         for (agent = counters; agent; agent = agent->next) {
2197                 const char *name;
2198
2199                 if (agent->emitted)
2200                         continue;
2201
2202                 name = mono_counter_get_name (agent->counter);
2203                 emit_value (logbuffer, mono_counter_get_section (agent->counter));
2204                 emit_string (logbuffer, name, strlen (name) + 1);
2205                 emit_value (logbuffer, mono_counter_get_type (agent->counter));
2206                 emit_value (logbuffer, mono_counter_get_unit (agent->counter));
2207                 emit_value (logbuffer, mono_counter_get_variance (agent->counter));
2208                 emit_value (logbuffer, agent->index);
2209
2210                 agent->emitted = 1;
2211         }
2212         EXIT_LOG (logbuffer);
2213
2214         safe_send (profiler, ensure_logbuf (0));
2215
2216         mono_mutex_unlock (&counters_mutex);
2217 }
2218
2219 static void
2220 counters_sample (MonoProfiler *profiler, uint64_t timestamp)
2221 {
2222         MonoCounterAgent *agent;
2223         MonoCounter *counter;
2224         LogBuffer *logbuffer;
2225         int type;
2226         int buffer_size;
2227         void *buffer;
2228         int size;
2229
2230         if (!counters_initialized)
2231                 return;
2232
2233         counters_emit (profiler);
2234
2235         buffer_size = 8;
2236         buffer = calloc (1, buffer_size);
2237
2238         mono_mutex_lock (&counters_mutex);
2239
2240         size = 1 + 10 + 5;
2241         for (agent = counters; agent; agent = agent->next)
2242                 size += 10 * 2 + mono_counter_get_size (agent->counter);
2243
2244         logbuffer = ensure_logbuf (size);
2245
2246         ENTER_LOG (logbuffer, "counters");
2247         emit_byte (logbuffer, TYPE_SAMPLE_COUNTERS | TYPE_SAMPLE);
2248         emit_uvalue (logbuffer, timestamp);
2249         for (agent = counters; agent; agent = agent->next) {
2250                 size_t size;
2251
2252                 counter = agent->counter;
2253
2254                 size = mono_counter_get_size (counter);
2255                 if (size < 0) {
2256                         continue; // FIXME error
2257                 } else if (size > buffer_size) {
2258                         buffer_size = size;
2259                         buffer = realloc (buffer, buffer_size);
2260                 }
2261
2262                 memset (buffer, 0, buffer_size);
2263
2264                 if (mono_counters_sample (counter, buffer, size) < 0)
2265                         continue; // FIXME error
2266
2267                 type = mono_counter_get_type (counter);
2268
2269                 if (!agent->value) {
2270                         agent->value = calloc (1, size);
2271                         agent->value_size = size;
2272                 } else {
2273                         if (type == MONO_COUNTER_STRING) {
2274                                 if (strcmp (agent->value, buffer) == 0)
2275                                         continue;
2276                         } else {
2277                                 if (agent->value_size == size && memcmp (agent->value, buffer, size) == 0)
2278                                         continue;
2279                         }
2280                 }
2281
2282                 emit_uvalue (logbuffer, agent->index);
2283                 emit_uvalue (logbuffer, type);
2284                 switch (type) {
2285                 case MONO_COUNTER_INT:
2286 #if SIZEOF_VOID_P == 4
2287                 case MONO_COUNTER_WORD:
2288 #endif
2289                         emit_svalue (logbuffer, *(int*)buffer - *(int*)agent->value);
2290                         break;
2291                 case MONO_COUNTER_UINT:
2292                         emit_uvalue (logbuffer, *(guint*)buffer - *(guint*)agent->value);
2293                         break;
2294                 case MONO_COUNTER_TIME_INTERVAL:
2295                 case MONO_COUNTER_LONG:
2296 #if SIZEOF_VOID_P == 8
2297                 case MONO_COUNTER_WORD:
2298 #endif
2299                         emit_svalue (logbuffer, *(gint64*)buffer - *(gint64*)agent->value);
2300                         break;
2301                 case MONO_COUNTER_ULONG:
2302                         emit_uvalue (logbuffer, *(guint64*)buffer - *(guint64*)agent->value);
2303                         break;
2304                 case MONO_COUNTER_DOUBLE:
2305                         emit_double (logbuffer, *(double*)buffer);
2306                         break;
2307                 case MONO_COUNTER_STRING:
2308                         if (size == 0) {
2309                                 emit_byte (logbuffer, 0);
2310                         } else {
2311                                 emit_byte (logbuffer, 1);
2312                                 emit_string (logbuffer, (char*)buffer, size);
2313                         }
2314                         break;
2315                 default:
2316                         assert (0);
2317                 }
2318
2319                 if (type == MONO_COUNTER_STRING && size > agent->value_size) {
2320                         agent->value = realloc (agent->value, size);
2321                         agent->value_size = size;
2322                 }
2323
2324                 if (size > 0)
2325                         memcpy (agent->value, buffer, size);
2326         }
2327         free (buffer);
2328
2329         emit_value (logbuffer, 0);
2330         EXIT_LOG (logbuffer);
2331
2332         safe_send (profiler, ensure_logbuf (0));
2333
2334         mono_mutex_unlock (&counters_mutex);
2335 }
2336
2337 typedef struct _PerfCounterAgent PerfCounterAgent;
2338 struct _PerfCounterAgent {
2339         PerfCounterAgent *next;
2340         int index;
2341         char *category_name;
2342         char *name;
2343         int type;
2344         gint64 value;
2345         guint8 emitted;
2346         guint8 updated;
2347         guint8 deleted;
2348 };
2349
2350 static PerfCounterAgent *perfcounters = NULL;
2351
2352 static void
2353 perfcounters_emit (MonoProfiler *profiler)
2354 {
2355         PerfCounterAgent *pcagent;
2356         LogBuffer *logbuffer;
2357         int size = 1 + 5, len = 0;
2358
2359         for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
2360                 if (pcagent->emitted)
2361                         continue;
2362
2363                 size += strlen (pcagent->name) + 1 + 5 * 5;
2364                 len += 1;
2365         }
2366
2367         if (!len)
2368                 return;
2369
2370         logbuffer = ensure_logbuf (size);
2371
2372         ENTER_LOG (logbuffer, "perfcounters");
2373         emit_byte (logbuffer, TYPE_SAMPLE_COUNTERS_DESC | TYPE_SAMPLE);
2374         emit_value (logbuffer, len);
2375         for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
2376                 if (pcagent->emitted)
2377                         continue;
2378
2379                 emit_value (logbuffer, MONO_COUNTER_PERFCOUNTERS);
2380                 emit_string (logbuffer, pcagent->category_name, strlen (pcagent->category_name) + 1);
2381                 emit_string (logbuffer, pcagent->name, strlen (pcagent->name) + 1);
2382                 emit_value (logbuffer, MONO_COUNTER_LONG);
2383                 emit_value (logbuffer, MONO_COUNTER_RAW);
2384                 emit_value (logbuffer, MONO_COUNTER_VARIABLE);
2385                 emit_value (logbuffer, pcagent->index);
2386
2387                 pcagent->emitted = 1;
2388         }
2389         EXIT_LOG (logbuffer);
2390
2391         safe_send (profiler, ensure_logbuf (0));
2392 }
2393
2394 static gboolean
2395 perfcounters_foreach (char *category_name, char *name, unsigned char type, gint64 value, gpointer user_data)
2396 {
2397         PerfCounterAgent *pcagent;
2398
2399         for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
2400                 if (strcmp (pcagent->category_name, category_name) != 0 || strcmp (pcagent->name, name) != 0)
2401                         continue;
2402                 if (pcagent->value == value)
2403                         return TRUE;
2404
2405                 pcagent->value = value;
2406                 pcagent->updated = 1;
2407                 pcagent->deleted = 0;
2408                 return TRUE;
2409         }
2410
2411         pcagent = g_new0 (PerfCounterAgent, 1);
2412         pcagent->next = perfcounters;
2413         pcagent->index = counters_index++;
2414         pcagent->category_name = g_strdup (category_name);
2415         pcagent->name = g_strdup (name);
2416         pcagent->type = (int) type;
2417         pcagent->value = value;
2418         pcagent->emitted = 0;
2419         pcagent->updated = 1;
2420         pcagent->deleted = 0;
2421
2422         perfcounters = pcagent;
2423
2424         return TRUE;
2425 }
2426
2427 static void
2428 perfcounters_sample (MonoProfiler *profiler, uint64_t timestamp)
2429 {
2430         PerfCounterAgent *pcagent;
2431         LogBuffer *logbuffer;
2432         int size;
2433
2434         if (!counters_initialized)
2435                 return;
2436
2437         mono_mutex_lock (&counters_mutex);
2438
2439         /* mark all perfcounters as deleted, foreach will unmark them as necessary */
2440         for (pcagent = perfcounters; pcagent; pcagent = pcagent->next)
2441                 pcagent->deleted = 1;
2442
2443         mono_perfcounter_foreach (perfcounters_foreach, perfcounters);
2444
2445         perfcounters_emit (profiler);
2446
2447
2448         size = 1 + 10 + 5;
2449         for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
2450                 if (pcagent->deleted || !pcagent->updated)
2451                         continue;
2452                 size += 10 * 2 + sizeof (gint64);
2453         }
2454
2455         logbuffer = ensure_logbuf (size);
2456
2457         ENTER_LOG (logbuffer, "perfcounters");
2458         emit_byte (logbuffer, TYPE_SAMPLE_COUNTERS | TYPE_SAMPLE);
2459         emit_uvalue (logbuffer, timestamp);
2460         for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
2461                 if (pcagent->deleted || !pcagent->updated)
2462                         continue;
2463                 emit_uvalue (logbuffer, pcagent->index);
2464                 emit_uvalue (logbuffer, MONO_COUNTER_LONG);
2465                 emit_svalue (logbuffer, pcagent->value);
2466
2467                 pcagent->updated = 0;
2468         }
2469
2470         emit_value (logbuffer, 0);
2471         EXIT_LOG (logbuffer);
2472
2473         safe_send (profiler, ensure_logbuf (0));
2474
2475         mono_mutex_unlock (&counters_mutex);
2476 }
2477
2478 static void
2479 counters_and_perfcounters_sample (MonoProfiler *prof)
2480 {
2481         static uint64_t start = -1;
2482         uint64_t now;
2483
2484         if (start == -1)
2485                 start = current_time ();
2486
2487         now = current_time ();
2488         counters_sample (prof, (now - start) / 1000/ 1000);
2489         perfcounters_sample (prof, (now - start) / 1000/ 1000);
2490 }
2491
2492 #endif /* DISABLE_HELPER_THREAD */
2493
2494 static void
2495 log_shutdown (MonoProfiler *prof)
2496 {
2497         void *res;
2498
2499         in_shutdown = 1;
2500 #ifndef DISABLE_HELPER_THREAD
2501         counters_and_perfcounters_sample (prof);
2502
2503         if (prof->command_port) {
2504                 char c = 1;
2505                 ign_res (write (prof->pipes [1], &c, 1));
2506                 pthread_join (prof->helper_thread, &res);
2507         }
2508 #endif
2509 #if USE_PERF_EVENTS
2510         if (perf_data) {
2511                 int i;
2512                 for (i = 0; i < num_perf; ++i)
2513                         read_perf_mmap (prof, i);
2514         }
2515 #endif
2516         dump_sample_hits (prof, prof->stat_buffers);
2517
2518         if (TLS_GET (LogBuffer, tlsbuffer))
2519                 send_buffer (prof, TLS_GET (GPtrArray, tlsmethodlist), TLS_GET (LogBuffer, tlsbuffer));
2520
2521         TLS_SET (tlsbuffer, NULL);
2522         TLS_SET (tlsmethodlist, NULL);
2523
2524         InterlockedWrite (&prof->run_writer_thread, 0);
2525         pthread_join (prof->writer_thread, &res);
2526
2527 #if defined (HAVE_SYS_ZLIB)
2528         if (prof->gzfile)
2529                 gzclose (prof->gzfile);
2530 #endif
2531         if (prof->pipe_output)
2532                 pclose (prof->file);
2533         else
2534                 fclose (prof->file);
2535
2536         mono_conc_hashtable_destroy (prof->method_table);
2537         mono_mutex_destroy (&prof->method_table_mutex);
2538
2539         free (prof);
2540 }
2541
2542 static char*
2543 new_filename (const char* filename)
2544 {
2545         time_t t = time (NULL);
2546         int pid = process_id ();
2547         char pid_buf [16];
2548         char time_buf [16];
2549         char *res, *d;
2550         const char *p;
2551         int count_dates = 0;
2552         int count_pids = 0;
2553         int s_date, s_pid;
2554         struct tm *ts;
2555         for (p = filename; *p; p++) {
2556                 if (*p != '%')
2557                         continue;
2558                 p++;
2559                 if (*p == 't')
2560                         count_dates++;
2561                 else if (*p == 'p')
2562                         count_pids++;
2563                 else if (*p == 0)
2564                         break;
2565         }
2566         if (!count_dates && !count_pids)
2567                 return pstrdup (filename);
2568         snprintf (pid_buf, sizeof (pid_buf), "%d", pid);
2569         ts = gmtime (&t);
2570         snprintf (time_buf, sizeof (time_buf), "%d%02d%02d%02d%02d%02d",
2571                 1900 + ts->tm_year, 1 + ts->tm_mon, ts->tm_mday, ts->tm_hour, ts->tm_min, ts->tm_sec);
2572         s_date = strlen (time_buf);
2573         s_pid = strlen (pid_buf);
2574         d = res = malloc (strlen (filename) + s_date * count_dates + s_pid * count_pids);
2575         for (p = filename; *p; p++) {
2576                 if (*p != '%') {
2577                         *d++ = *p;
2578                         continue;
2579                 }
2580                 p++;
2581                 if (*p == 't') {
2582                         strcpy (d, time_buf);
2583                         d += s_date;
2584                         continue;
2585                 } else if (*p == 'p') {
2586                         strcpy (d, pid_buf);
2587                         d += s_pid;
2588                         continue;
2589                 } else if (*p == '%') {
2590                         *d++ = '%';
2591                         continue;
2592                 } else if (*p == 0)
2593                         break;
2594                 *d++ = '%';
2595                 *d++ = *p;
2596         }
2597         *d = 0;
2598         return res;
2599 }
2600
2601 //this is exposed by the JIT, but it's not meant to be a supported API for now.
2602 extern void mono_threads_attach_tools_thread (void);
2603
2604 #ifndef DISABLE_HELPER_THREAD
2605
2606 static void*
2607 helper_thread (void* arg)
2608 {
2609         MonoProfiler* prof = arg;
2610         int command_socket;
2611         int len;
2612         char buf [64];
2613         MonoThread *thread = NULL;
2614
2615         mono_threads_attach_tools_thread ();
2616         //fprintf (stderr, "Server listening\n");
2617         command_socket = -1;
2618         while (1) {
2619                 fd_set rfds;
2620                 struct timeval tv;
2621                 int max_fd = -1;
2622                 FD_ZERO (&rfds);
2623                 FD_SET (prof->server_socket, &rfds);
2624                 max_fd = prof->server_socket;
2625                 FD_SET (prof->pipes [0], &rfds);
2626                 if (max_fd < prof->pipes [0])
2627                         max_fd = prof->pipes [0];
2628                 if (command_socket >= 0) {
2629                         FD_SET (command_socket, &rfds);
2630                         if (max_fd < command_socket)
2631                                 max_fd = command_socket;
2632                 }
2633 #if USE_PERF_EVENTS
2634                 if (perf_data) {
2635                         int i;
2636                         for ( i = 0; i < num_perf; ++i) {
2637                                 if (perf_data [i].perf_fd < 0)
2638                                         continue;
2639                                 FD_SET (perf_data [i].perf_fd, &rfds);
2640                                 if (max_fd < perf_data [i].perf_fd)
2641                                         max_fd = perf_data [i].perf_fd;
2642                         }
2643                 }
2644 #endif
2645
2646                 counters_and_perfcounters_sample (prof);
2647
2648                 tv.tv_sec = 1;
2649                 tv.tv_usec = 0;
2650                 len = select (max_fd + 1, &rfds, NULL, NULL, &tv);
2651
2652                 if (len < 0) {
2653                         if (errno == EINTR)
2654                                 continue;
2655                         
2656                         g_warning ("Error in proflog server: %s", strerror (errno));
2657                         return NULL;
2658                 }
2659                 
2660                 if (FD_ISSET (prof->pipes [0], &rfds)) {
2661                         char c;
2662                         int r = read (prof->pipes [0], &c, 1);
2663                         if (r == 1 && c == 0) {
2664                                 StatBuffer *sbufbase = prof->stat_buffers;
2665                                 StatBuffer *sbuf;
2666                                 if (!sbufbase->next)
2667                                         continue;
2668                                 sbuf = sbufbase->next->next;
2669                                 sbufbase->next->next = NULL;
2670                                 if (do_debug)
2671                                         fprintf (stderr, "stat buffer dump\n");
2672                                 if (sbuf) {
2673                                         dump_sample_hits (prof, sbuf);
2674                                         free_buffer (sbuf, sbuf->size);
2675                                         safe_send (prof, ensure_logbuf (0));
2676                                 }
2677                                 continue;
2678                         }
2679                         /* time to shut down */
2680                         if (thread)
2681                                 mono_thread_detach (thread);
2682                         if (do_debug)
2683                                 fprintf (stderr, "helper shutdown\n");
2684 #if USE_PERF_EVENTS
2685                         if (perf_data) {
2686                                 int i;
2687                                 for ( i = 0; i < num_perf; ++i) {
2688                                         if (perf_data [i].perf_fd < 0)
2689                                                 continue;
2690                                         if (FD_ISSET (perf_data [i].perf_fd, &rfds))
2691                                                 read_perf_mmap (prof, i);
2692                                 }
2693                         }
2694 #endif
2695                         safe_send (prof, ensure_logbuf (0));
2696                         return NULL;
2697                 }
2698 #if USE_PERF_EVENTS
2699                 if (perf_data) {
2700                         int i;
2701                         for ( i = 0; i < num_perf; ++i) {
2702                                 if (perf_data [i].perf_fd < 0)
2703                                         continue;
2704                                 if (FD_ISSET (perf_data [i].perf_fd, &rfds)) {
2705                                         read_perf_mmap (prof, i);
2706                                         safe_send (prof, ensure_logbuf (0));
2707                                 }
2708                         }
2709                 }
2710 #endif
2711                 if (command_socket >= 0 && FD_ISSET (command_socket, &rfds)) {
2712                         len = read (command_socket, buf, sizeof (buf) - 1);
2713                         if (len < 0)
2714                                 continue;
2715                         if (len == 0) {
2716                                 close (command_socket);
2717                                 command_socket = -1;
2718                                 continue;
2719                         }
2720                         buf [len] = 0;
2721                         if (strcmp (buf, "heapshot\n") == 0) {
2722                                 heapshot_requested = 1;
2723                                 //fprintf (stderr, "perform heapshot\n");
2724                                 if (runtime_inited && !thread) {
2725                                         thread = mono_thread_attach (mono_get_root_domain ());
2726                                         /*fprintf (stderr, "attached\n");*/
2727                                 }
2728                                 if (thread) {
2729                                         process_requests (prof);
2730                                         mono_thread_detach (thread);
2731                                         thread = NULL;
2732                                 }
2733                         }
2734                         continue;
2735                 }
2736                 if (!FD_ISSET (prof->server_socket, &rfds)) {
2737                         continue;
2738                 }
2739                 command_socket = accept (prof->server_socket, NULL, NULL);
2740                 if (command_socket < 0)
2741                         continue;
2742                 //fprintf (stderr, "Accepted connection\n");
2743         }
2744         return NULL;
2745 }
2746
2747 static int
2748 start_helper_thread (MonoProfiler* prof)
2749 {
2750         struct sockaddr_in server_address;
2751         int r;
2752         socklen_t slen;
2753         if (pipe (prof->pipes) < 0) {
2754                 fprintf (stderr, "Cannot create pipe\n");
2755                 return 0;
2756         }
2757         prof->server_socket = socket (PF_INET, SOCK_STREAM, 0);
2758         if (prof->server_socket < 0) {
2759                 fprintf (stderr, "Cannot create server socket\n");
2760                 return 0;
2761         }
2762         memset (&server_address, 0, sizeof (server_address));
2763         server_address.sin_family = AF_INET;
2764         server_address.sin_addr.s_addr = INADDR_ANY;
2765         server_address.sin_port = htons (prof->command_port);
2766         if (bind (prof->server_socket, (struct sockaddr *) &server_address, sizeof (server_address)) < 0) {
2767                 fprintf (stderr, "Cannot bind server socket, port: %d: %s\n", prof->command_port, strerror (errno));
2768                 close (prof->server_socket);
2769                 return 0;
2770         }
2771         if (listen (prof->server_socket, 1) < 0) {
2772                 fprintf (stderr, "Cannot listen server socket\n");
2773                 close (prof->server_socket);
2774                 return 0;
2775         }
2776         slen = sizeof (server_address);
2777         if (getsockname (prof->server_socket, (struct sockaddr *)&server_address, &slen) == 0) {
2778                 prof->command_port = ntohs (server_address.sin_port);
2779                 /*fprintf (stderr, "Assigned server port: %d\n", prof->command_port);*/
2780         }
2781
2782         r = pthread_create (&prof->helper_thread, NULL, helper_thread, prof);
2783         if (r) {
2784                 close (prof->server_socket);
2785                 return 0;
2786         }
2787         return 1;
2788 }
2789 #endif
2790
2791 static void *
2792 writer_thread (void *arg)
2793 {
2794         MonoProfiler *prof = arg;
2795
2796         mono_threads_attach_tools_thread ();
2797
2798         dump_header (prof);
2799
2800         while (InterlockedRead (&prof->run_writer_thread)) {
2801                 WriterQueueEntry *entry;
2802
2803                 while ((entry = (WriterQueueEntry *) mono_lock_free_queue_dequeue (&prof->writer_queue))) {
2804                         LogBuffer *method_buffer = NULL;
2805                         gboolean new_methods = FALSE;
2806
2807                         if (entry->methods->len)
2808                                 method_buffer = create_buffer ();
2809
2810                         /*
2811                          * Encode the method events in a temporary log buffer that we
2812                          * flush to disk before the main buffer, ensuring that all
2813                          * methods have metadata emitted before they're referenced.
2814                          */
2815                         for (guint i = 0; i < entry->methods->len; i++) {
2816                                 MethodInfo *info = g_ptr_array_index (entry->methods, i);
2817
2818                                 if (mono_conc_hashtable_lookup (prof->method_table, info->method))
2819                                         continue;
2820
2821                                 new_methods = TRUE;
2822
2823                                 /*
2824                                  * Other threads use this hash table to get a general
2825                                  * idea of whether a method has already been emitted to
2826                                  * the stream. Due to the way we add to this table, it
2827                                  * can easily happen that multiple threads queue up the
2828                                  * same methods, but that's OK since eventually all
2829                                  * methods will be in this table and the thread-local
2830                                  * method lists will just be empty for the rest of the
2831                                  * app's lifetime.
2832                                  */
2833                                 mono_conc_hashtable_insert (prof->method_table, info->method, info->method);
2834
2835                                 char *name = mono_method_full_name (info->method, 1);
2836                                 int nlen = strlen (name) + 1;
2837                                 uint64_t now = current_time ();
2838
2839                                 method_buffer = ensure_logbuf_inner (method_buffer, 32 + nlen);
2840
2841                                 emit_byte (method_buffer, TYPE_JIT | TYPE_METHOD);
2842                                 emit_time (method_buffer, now);
2843                                 emit_method_inner (method_buffer, info->method);
2844                                 emit_ptr (method_buffer, mono_jit_info_get_code_start (info->ji));
2845                                 emit_value (method_buffer, mono_jit_info_get_code_size (info->ji));
2846
2847                                 memcpy (method_buffer->data, name, nlen);
2848                                 method_buffer->data += nlen;
2849
2850                                 mono_free (name);
2851                                 free (info);
2852                         }
2853
2854                         g_ptr_array_free (entry->methods, TRUE);
2855
2856                         if (new_methods)
2857                                 dump_buffer (prof, method_buffer);
2858                         else if (method_buffer)
2859                                 free_buffer (method_buffer, method_buffer->size);
2860
2861                         dump_buffer (prof, entry->buffer);
2862
2863                         free (entry);
2864                 }
2865         }
2866
2867         return NULL;
2868 }
2869
2870 static int
2871 start_writer_thread (MonoProfiler* prof)
2872 {
2873         InterlockedWrite (&prof->run_writer_thread, 1);
2874
2875         return !pthread_create (&prof->writer_thread, NULL, writer_thread, prof);
2876 }
2877
2878 static MonoProfiler*
2879 create_profiler (const char *filename)
2880 {
2881         MonoProfiler *prof;
2882         char *nf;
2883         int force_delete = 0;
2884         int need_helper_thread = 0;
2885         prof = calloc (1, sizeof (MonoProfiler));
2886
2887         prof->command_port = command_port;
2888         if (filename && *filename == '-') {
2889                 force_delete = 1;
2890                 filename++;
2891         }
2892         if (!filename) {
2893                 if (do_report)
2894                         filename = "|mprof-report -";
2895                 else
2896                         filename = "output.mlpd";
2897                 nf = (char*)filename;
2898         } else {
2899                 nf = new_filename (filename);
2900                 if (do_report) {
2901                         int s = strlen (nf) + 32;
2902                         char *p = malloc (s);
2903                         snprintf (p, s, "|mprof-report '--out=%s' -", nf);
2904                         free (nf);
2905                         nf = p;
2906                 }
2907         }
2908         if (*nf == '|') {
2909                 prof->file = popen (nf + 1, "w");
2910                 prof->pipe_output = 1;
2911         } else if (*nf == '#') {
2912                 int fd = strtol (nf + 1, NULL, 10);
2913                 prof->file = fdopen (fd, "a");
2914         } else {
2915                 if (force_delete)
2916                         unlink (nf);
2917                 prof->file = fopen (nf, "wb");
2918         }
2919         if (!prof->file) {
2920                 fprintf (stderr, "Cannot create profiler output: %s\n", nf);
2921                 exit (1);
2922         }
2923 #if defined (HAVE_SYS_ZLIB)
2924         if (use_zip)
2925                 prof->gzfile = gzdopen (fileno (prof->file), "wb");
2926 #endif
2927 #if USE_PERF_EVENTS
2928         if (sample_type && !do_mono_sample)
2929                 need_helper_thread = setup_perf_event ();
2930         if (!perf_data) {
2931                 /* FIXME: warn if different freq or sample type */
2932                 do_mono_sample = 1;
2933         }
2934 #endif
2935         if (do_mono_sample) {
2936                 prof->stat_buffers = create_stat_buffer ();
2937                 need_helper_thread = 1;
2938         }
2939         if (do_counters && !need_helper_thread) {
2940                 need_helper_thread = 1;
2941         }
2942 #ifndef DISABLE_HELPER_THREAD
2943         if (hs_mode_ondemand || need_helper_thread) {
2944                 if (!start_helper_thread (prof))
2945                         prof->command_port = 0;
2946         }
2947 #else
2948         if (hs_mode_ondemand)
2949                 fprintf (stderr, "Ondemand heapshot unavailable on this arch.\n");
2950 #endif
2951
2952         mono_lock_free_queue_init (&prof->writer_queue);
2953         mono_mutex_init (&prof->method_table_mutex);
2954         prof->method_table = mono_conc_hashtable_new (&prof->method_table_mutex, NULL, NULL);
2955
2956         start_writer_thread (prof);
2957
2958         prof->startup_time = current_time ();
2959         return prof;
2960 }
2961
2962 static void
2963 usage (int do_exit)
2964 {
2965         printf ("Log profiler version %d.%d (format: %d)\n", LOG_VERSION_MAJOR, LOG_VERSION_MINOR, LOG_DATA_VERSION);
2966         printf ("Usage: mono --profile=log[:OPTION1[,OPTION2...]] program.exe\n");
2967         printf ("Options:\n");
2968         printf ("\thelp             show this usage info\n");
2969         printf ("\t[no]alloc        enable/disable recording allocation info\n");
2970         printf ("\t[no]calls        enable/disable recording enter/leave method events\n");
2971         printf ("\theapshot[=MODE]  record heap shot info (by default at each major collection)\n");
2972         printf ("\t                 MODE: every XXms milliseconds, every YYgc collections, ondemand\n");
2973         printf ("\tcounters         sample counters every 1s\n");
2974         printf ("\tsample[=TYPE]    use statistical sampling mode (by default cycles/1000)\n");
2975         printf ("\t                 TYPE: cycles,instr,cacherefs,cachemiss,branches,branchmiss\n");
2976         printf ("\t                 TYPE can be followed by /FREQUENCY\n");
2977         printf ("\ttime=fast        use a faster (but more inaccurate) timer\n");
2978         printf ("\tmaxframes=NUM    collect up to NUM stack frames\n");
2979         printf ("\tcalldepth=NUM    ignore method events for call chain depth bigger than NUM\n");
2980         printf ("\toutput=FILENAME  write the data to file FILENAME (-FILENAME to overwrite)\n");
2981         printf ("\toutput=|PROGRAM  write the data to the stdin of PROGRAM\n");
2982         printf ("\t                 %%t is subtituted with date and time, %%p with the pid\n");
2983         printf ("\treport           create a report instead of writing the raw data to a file\n");
2984         printf ("\tzip              compress the output data\n");
2985         printf ("\tport=PORTNUM     use PORTNUM for the listening command server\n");
2986         if (do_exit)
2987                 exit (1);
2988 }
2989
2990 static const char*
2991 match_option (const char* p, const char *opt, char **rval)
2992 {
2993         int len = strlen (opt);
2994         if (strncmp (p, opt, len) == 0) {
2995                 if (rval) {
2996                         if (p [len] == '=' && p [len + 1]) {
2997                                 const char *opt = p + len + 1;
2998                                 const char *end = strchr (opt, ',');
2999                                 char *val;
3000                                 int l;
3001                                 if (end == NULL) {
3002                                         l = strlen (opt);
3003                                 } else {
3004                                         l = end - opt;
3005                                 }
3006                                 val = malloc (l + 1);
3007                                 memcpy (val, opt, l);
3008                                 val [l] = 0;
3009                                 *rval = val;
3010                                 return opt + l;
3011                         }
3012                         if (p [len] == 0 || p [len] == ',') {
3013                                 *rval = NULL;
3014                                 return p + len + (p [len] == ',');
3015                         }
3016                         usage (1);
3017                 } else {
3018                         if (p [len] == 0)
3019                                 return p + len;
3020                         if (p [len] == ',')
3021                                 return p + len + 1;
3022                 }
3023         }
3024         return p;
3025 }
3026
3027 typedef struct {
3028         const char *name;
3029         int sample_mode;
3030 } SampleMode;
3031
3032 static const SampleMode sample_modes [] = {
3033         {"cycles", SAMPLE_CYCLES},
3034         {"instr", SAMPLE_INSTRUCTIONS},
3035         {"cachemiss", SAMPLE_CACHE_MISSES},
3036         {"cacherefs", SAMPLE_CACHE_REFS},
3037         {"branches", SAMPLE_BRANCHES},
3038         {"branchmiss", SAMPLE_BRANCH_MISSES},
3039         {NULL, 0}
3040 };
3041
3042 static void
3043 set_sample_mode (char* val, int allow_empty)
3044 {
3045         char *end;
3046         char *maybe_freq = NULL;
3047         unsigned int count;
3048         const SampleMode *smode = sample_modes;
3049 #ifndef USE_PERF_EVENTS
3050         do_mono_sample = 1;
3051 #endif
3052         if (allow_empty && !val) {
3053                 sample_type = SAMPLE_CYCLES;
3054                 sample_freq = 1000;
3055                 return;
3056         }
3057         if (strcmp (val, "mono") == 0) {
3058                 do_mono_sample = 1;
3059                 sample_type = SAMPLE_CYCLES;
3060                 free (val);
3061                 return;
3062         }
3063         for (smode = sample_modes; smode->name; smode++) {
3064                 int l = strlen (smode->name);
3065                 if (strncmp (val, smode->name, l) == 0) {
3066                         sample_type = smode->sample_mode;
3067                         maybe_freq = val + l;
3068                         break;
3069                 }
3070         }
3071         if (!smode->name)
3072                 usage (1);
3073         if (*maybe_freq == '/') {
3074                 count = strtoul (maybe_freq + 1, &end, 10);
3075                 if (maybe_freq + 1 == end)
3076                         usage (1);
3077                 sample_freq = count;
3078         } else if (*maybe_freq != 0) {
3079                 usage (1);
3080         } else {
3081                 sample_freq = 1000;
3082         }
3083         free (val);
3084 }
3085
3086 static void
3087 set_hsmode (char* val, int allow_empty)
3088 {
3089         char *end;
3090         unsigned int count;
3091         if (allow_empty && !val)
3092                 return;
3093         if (strcmp (val, "ondemand") == 0) {
3094                 hs_mode_ondemand = 1;
3095                 free (val);
3096                 return;
3097         }
3098         count = strtoul (val, &end, 10);
3099         if (val == end)
3100                 usage (1);
3101         if (strcmp (end, "ms") == 0)
3102                 hs_mode_ms = count;
3103         else if (strcmp (end, "gc") == 0)
3104                 hs_mode_gc = count;
3105         else
3106                 usage (1);
3107         free (val);
3108 }
3109
3110 /* 
3111  * declaration to silence the compiler: this is the entry point that
3112  * mono will load from the shared library and call.
3113  */
3114 extern void
3115 mono_profiler_startup (const char *desc);
3116
3117 extern void
3118 mono_profiler_startup_log (const char *desc);
3119
3120 /*
3121  * this is the entry point that will be used when the profiler
3122  * is embedded inside the main executable.
3123  */
3124 void
3125 mono_profiler_startup_log (const char *desc)
3126 {
3127         mono_profiler_startup (desc);
3128 }
3129
3130 void
3131 mono_profiler_startup (const char *desc)
3132 {
3133         MonoProfiler *prof;
3134         char *filename = NULL;
3135         const char *p;
3136         const char *opt;
3137         int fast_time = 0;
3138         int calls_enabled = 0;
3139         int allocs_enabled = 0;
3140         int only_counters = 0;
3141         int events = MONO_PROFILE_GC|MONO_PROFILE_ALLOCATIONS|
3142                 MONO_PROFILE_GC_MOVES|MONO_PROFILE_CLASS_EVENTS|MONO_PROFILE_THREADS|
3143                 MONO_PROFILE_ENTER_LEAVE|MONO_PROFILE_JIT_COMPILATION|MONO_PROFILE_EXCEPTIONS|
3144                 MONO_PROFILE_MONITOR_EVENTS|MONO_PROFILE_MODULE_EVENTS|MONO_PROFILE_GC_ROOTS;
3145
3146         p = desc;
3147         if (strncmp (p, "log", 3))
3148                 usage (1);
3149         p += 3;
3150         if (*p == ':')
3151                 p++;
3152         for (; *p; p = opt) {
3153                 char *val;
3154                 if (*p == ',') {
3155                         opt = p + 1;
3156                         continue;
3157                 }
3158                 if ((opt = match_option (p, "help", NULL)) != p) {
3159                         usage (0);
3160                         continue;
3161                 }
3162                 if ((opt = match_option (p, "calls", NULL)) != p) {
3163                         calls_enabled = 1;
3164                         continue;
3165                 }
3166                 if ((opt = match_option (p, "nocalls", NULL)) != p) {
3167                         events &= ~MONO_PROFILE_ENTER_LEAVE;
3168                         nocalls = 1;
3169                         continue;
3170                 }
3171                 if ((opt = match_option (p, "alloc", NULL)) != p) {
3172                         allocs_enabled = 1;
3173                         continue;
3174                 }
3175                 if ((opt = match_option (p, "noalloc", NULL)) != p) {
3176                         events &= ~MONO_PROFILE_ALLOCATIONS;
3177                         continue;
3178                 }
3179                 if ((opt = match_option (p, "time", &val)) != p) {
3180                         if (strcmp (val, "fast") == 0)
3181                                 fast_time = 1;
3182                         else if (strcmp (val, "null") == 0)
3183                                 fast_time = 2;
3184                         else
3185                                 usage (1);
3186                         free (val);
3187                         continue;
3188                 }
3189                 if ((opt = match_option (p, "report", NULL)) != p) {
3190                         do_report = 1;
3191                         continue;
3192                 }
3193                 if ((opt = match_option (p, "debug", NULL)) != p) {
3194                         do_debug = 1;
3195                         continue;
3196                 }
3197                 if ((opt = match_option (p, "sampling-real", NULL)) != p) {
3198                         sampling_mode = MONO_PROFILER_STAT_MODE_REAL;
3199                         continue;
3200                 }
3201                 if ((opt = match_option (p, "sampling-process", NULL)) != p) {
3202                         sampling_mode = MONO_PROFILER_STAT_MODE_PROCESS;
3203                         continue;
3204                 }
3205                 if ((opt = match_option (p, "heapshot", &val)) != p) {
3206                         events &= ~MONO_PROFILE_ALLOCATIONS;
3207                         events &= ~MONO_PROFILE_ENTER_LEAVE;
3208                         nocalls = 1;
3209                         do_heap_shot = 1;
3210                         set_hsmode (val, 1);
3211                         continue;
3212                 }
3213                 if ((opt = match_option (p, "sample", &val)) != p) {
3214                         events &= ~MONO_PROFILE_ALLOCATIONS;
3215                         events &= ~MONO_PROFILE_ENTER_LEAVE;
3216                         nocalls = 1;
3217                         set_sample_mode (val, 1);
3218                         continue;
3219                 }
3220                 if ((opt = match_option (p, "hsmode", &val)) != p) {
3221                         fprintf (stderr, "The hsmode profiler option is obsolete, use heapshot=MODE.\n");
3222                         set_hsmode (val, 0);
3223                         continue;
3224                 }
3225                 if ((opt = match_option (p, "zip", NULL)) != p) {
3226                         use_zip = 1;
3227                         continue;
3228                 }
3229                 if ((opt = match_option (p, "output", &val)) != p) {
3230                         filename = val;
3231                         continue;
3232                 }
3233                 if ((opt = match_option (p, "port", &val)) != p) {
3234                         char *end;
3235                         command_port = strtoul (val, &end, 10);
3236                         free (val);
3237                         continue;
3238                 }
3239                 if ((opt = match_option (p, "maxframes", &val)) != p) {
3240                         char *end;
3241                         num_frames = strtoul (val, &end, 10);
3242                         if (num_frames > MAX_FRAMES)
3243                                 num_frames = MAX_FRAMES;
3244                         free (val);
3245                         notraces = num_frames == 0;
3246                         continue;
3247                 }
3248                 if ((opt = match_option (p, "calldepth", &val)) != p) {
3249                         char *end;
3250                         max_call_depth = strtoul (val, &end, 10);
3251                         free (val);
3252                         continue;
3253                 }
3254                 if ((opt = match_option (p, "counters", NULL)) != p) {
3255                         do_counters = 1;
3256                         continue;
3257                 }
3258                 if ((opt = match_option (p, "countersonly", NULL)) != p) {
3259                         only_counters = 1;
3260                         continue;
3261                 }
3262                 if (opt == p) {
3263                         usage (0);
3264                         exit (0);
3265                 }
3266         }
3267         if (calls_enabled) {
3268                 events |= MONO_PROFILE_ENTER_LEAVE;
3269                 nocalls = 0;
3270         }
3271         if (allocs_enabled)
3272                 events |= MONO_PROFILE_ALLOCATIONS;
3273         if (only_counters)
3274                 events = 0;
3275         utils_init (fast_time);
3276
3277         prof = create_profiler (filename);
3278         if (!prof)
3279                 return;
3280         init_thread ();
3281
3282         mono_profiler_install (prof, log_shutdown);
3283         mono_profiler_install_gc (gc_event, gc_resize);
3284         mono_profiler_install_allocation (gc_alloc);
3285         mono_profiler_install_gc_moves (gc_moves);
3286         mono_profiler_install_gc_roots (gc_handle, gc_roots);
3287         mono_profiler_install_class (NULL, class_loaded, NULL, NULL);
3288         mono_profiler_install_module (NULL, image_loaded, NULL, NULL);
3289         mono_profiler_install_thread (thread_start, thread_end);
3290         mono_profiler_install_thread_name (thread_name);
3291         mono_profiler_install_enter_leave (method_enter, method_leave);
3292         mono_profiler_install_jit_end (method_jitted);
3293         mono_profiler_install_code_buffer_new (code_buffer_new);
3294         mono_profiler_install_exception (throw_exc, method_exc_leave, clause_exc);
3295         mono_profiler_install_monitor (monitor_event);
3296         mono_profiler_install_runtime_initialized (runtime_initialized);
3297
3298         
3299         if (do_mono_sample && sample_type == SAMPLE_CYCLES && !only_counters) {
3300                 events |= MONO_PROFILE_STATISTICAL;
3301                 mono_profiler_set_statistical_mode (sampling_mode, 1000000 / sample_freq);
3302                 mono_profiler_install_statistical (mono_sample_hit);
3303         }
3304
3305         mono_profiler_set_events (events);
3306
3307         TLS_INIT (tlsbuffer);
3308         TLS_INIT (tlsmethodlist);
3309 }
3310