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