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