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