[jit] Expose helper method to the rest of the JIT to get specific trampoline descript...
[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                 const char *name;
2070
2071                 if (agent->emitted)
2072                         continue;
2073
2074                 name = mono_counter_get_name (agent->counter);
2075                 emit_value (logbuffer, mono_counter_get_section (agent->counter));
2076                 emit_string (logbuffer, name, strlen (name) + 1);
2077                 emit_value (logbuffer, mono_counter_get_type (agent->counter));
2078                 emit_value (logbuffer, mono_counter_get_unit (agent->counter));
2079                 emit_value (logbuffer, mono_counter_get_variance (agent->counter));
2080                 emit_value (logbuffer, agent->index);
2081
2082                 agent->emitted = 1;
2083         }
2084         EXIT_LOG (logbuffer);
2085
2086         safe_dump (profiler, ensure_logbuf (0));
2087
2088         mono_mutex_unlock (&counters_mutex);
2089 }
2090
2091 static void
2092 counters_sample (MonoProfiler *profiler, uint64_t timestamp)
2093 {
2094         MonoCounterAgent *agent;
2095         MonoCounter *counter;
2096         LogBuffer *logbuffer;
2097         int type;
2098         int buffer_size;
2099         void *buffer;
2100         int size;
2101
2102         if (!counters_initialized)
2103                 return;
2104
2105         counters_emit (profiler);
2106
2107         buffer_size = 8;
2108         buffer = calloc (1, buffer_size);
2109
2110         mono_mutex_lock (&counters_mutex);
2111
2112         size = 1 + 10 + 5;
2113         for (agent = counters; agent; agent = agent->next)
2114                 size += 10 * 2 + mono_counter_get_size (agent->counter);
2115
2116         logbuffer = ensure_logbuf (size);
2117
2118         ENTER_LOG (logbuffer, "counters");
2119         emit_byte (logbuffer, TYPE_SAMPLE_COUNTERS | TYPE_SAMPLE);
2120         emit_uvalue (logbuffer, timestamp);
2121         for (agent = counters; agent; agent = agent->next) {
2122                 size_t size;
2123
2124                 counter = agent->counter;
2125
2126                 size = mono_counter_get_size (counter);
2127                 if (size < 0) {
2128                         continue; // FIXME error
2129                 } else if (size > buffer_size) {
2130                         buffer_size = size;
2131                         buffer = realloc (buffer, buffer_size);
2132                 }
2133
2134                 memset (buffer, 0, buffer_size);
2135
2136                 if (mono_counters_sample (counter, buffer, size) < 0)
2137                         continue; // FIXME error
2138
2139                 type = mono_counter_get_type (counter);
2140
2141                 if (!agent->value) {
2142                         agent->value = calloc (1, size);
2143                         agent->value_size = size;
2144                 } else {
2145                         if (type == MONO_COUNTER_STRING) {
2146                                 if (strcmp (agent->value, buffer) == 0)
2147                                         continue;
2148                         } else {
2149                                 if (agent->value_size == size && memcmp (agent->value, buffer, size) == 0)
2150                                         continue;
2151                         }
2152                 }
2153
2154                 emit_uvalue (logbuffer, agent->index);
2155                 emit_uvalue (logbuffer, type);
2156                 switch (type) {
2157                 case MONO_COUNTER_INT:
2158 #if SIZEOF_VOID_P == 4
2159                 case MONO_COUNTER_WORD:
2160 #endif
2161                         emit_svalue (logbuffer, *(int*)buffer - *(int*)agent->value);
2162                         break;
2163                 case MONO_COUNTER_UINT:
2164                         emit_uvalue (logbuffer, *(guint*)buffer - *(guint*)agent->value);
2165                         break;
2166                 case MONO_COUNTER_TIME_INTERVAL:
2167                 case MONO_COUNTER_LONG:
2168 #if SIZEOF_VOID_P == 8
2169                 case MONO_COUNTER_WORD:
2170 #endif
2171                         emit_svalue (logbuffer, *(gint64*)buffer - *(gint64*)agent->value);
2172                         break;
2173                 case MONO_COUNTER_ULONG:
2174                         emit_uvalue (logbuffer, *(guint64*)buffer - *(guint64*)agent->value);
2175                         break;
2176                 case MONO_COUNTER_DOUBLE:
2177                         emit_double (logbuffer, *(double*)buffer);
2178                         break;
2179                 case MONO_COUNTER_STRING:
2180                         if (size == 0) {
2181                                 emit_byte (logbuffer, 0);
2182                         } else {
2183                                 emit_byte (logbuffer, 1);
2184                                 emit_string (logbuffer, (char*)buffer, size);
2185                         }
2186                         break;
2187                 default:
2188                         assert (0);
2189                 }
2190
2191                 if (type == MONO_COUNTER_STRING && size > agent->value_size) {
2192                         agent->value = realloc (agent->value, size);
2193                         agent->value_size = size;
2194                 }
2195
2196                 if (size > 0)
2197                         memcpy (agent->value, buffer, size);
2198         }
2199         free (buffer);
2200
2201         emit_value (logbuffer, 0);
2202         EXIT_LOG (logbuffer);
2203
2204         safe_dump (profiler, ensure_logbuf (0));
2205
2206         mono_mutex_unlock (&counters_mutex);
2207 }
2208
2209 typedef struct _PerfCounterAgent PerfCounterAgent;
2210 struct _PerfCounterAgent {
2211         PerfCounterAgent *next;
2212         int index;
2213         char *category_name;
2214         char *name;
2215         int type;
2216         gint64 value;
2217         guint8 emitted;
2218         guint8 updated;
2219         guint8 deleted;
2220 };
2221
2222 static PerfCounterAgent *perfcounters = NULL;
2223
2224 static void
2225 perfcounters_emit (MonoProfiler *profiler)
2226 {
2227         PerfCounterAgent *pcagent;
2228         LogBuffer *logbuffer;
2229         int size = 1 + 5, len = 0;
2230
2231         for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
2232                 if (pcagent->emitted)
2233                         continue;
2234
2235                 size += strlen (pcagent->name) + 1 + 5 * 5;
2236                 len += 1;
2237         }
2238
2239         if (!len)
2240                 return;
2241
2242         logbuffer = ensure_logbuf (size);
2243
2244         ENTER_LOG (logbuffer, "perfcounters");
2245         emit_byte (logbuffer, TYPE_SAMPLE_COUNTERS_DESC | TYPE_SAMPLE);
2246         emit_value (logbuffer, len);
2247         for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
2248                 if (pcagent->emitted)
2249                         continue;
2250
2251                 emit_value (logbuffer, MONO_COUNTER_PERFCOUNTERS);
2252                 emit_string (logbuffer, pcagent->category_name, strlen (pcagent->category_name) + 1);
2253                 emit_string (logbuffer, pcagent->name, strlen (pcagent->name) + 1);
2254                 emit_value (logbuffer, MONO_COUNTER_LONG);
2255                 emit_value (logbuffer, MONO_COUNTER_RAW);
2256                 emit_value (logbuffer, MONO_COUNTER_VARIABLE);
2257                 emit_value (logbuffer, pcagent->index);
2258
2259                 pcagent->emitted = 1;
2260         }
2261         EXIT_LOG (logbuffer);
2262
2263         safe_dump (profiler, ensure_logbuf (0));
2264 }
2265
2266 static gboolean
2267 perfcounters_foreach (char *category_name, char *name, unsigned char type, gint64 value, gpointer user_data)
2268 {
2269         PerfCounterAgent *pcagent;
2270
2271         for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
2272                 if (strcmp (pcagent->category_name, category_name) != 0 || strcmp (pcagent->name, name) != 0)
2273                         continue;
2274                 if (pcagent->value == value)
2275                         return TRUE;
2276
2277                 pcagent->value = value;
2278                 pcagent->updated = 1;
2279                 pcagent->deleted = 0;
2280                 return TRUE;
2281         }
2282
2283         pcagent = g_new0 (PerfCounterAgent, 1);
2284         pcagent->next = perfcounters;
2285         pcagent->index = counters_index++;
2286         pcagent->category_name = g_strdup (category_name);
2287         pcagent->name = g_strdup (name);
2288         pcagent->type = (int) type;
2289         pcagent->value = value;
2290         pcagent->emitted = 0;
2291         pcagent->updated = 1;
2292         pcagent->deleted = 0;
2293
2294         perfcounters = pcagent;
2295
2296         return TRUE;
2297 }
2298
2299 static void
2300 perfcounters_sample (MonoProfiler *profiler, uint64_t timestamp)
2301 {
2302         PerfCounterAgent *pcagent;
2303         LogBuffer *logbuffer;
2304         int size;
2305
2306         if (!counters_initialized)
2307                 return;
2308
2309         mono_mutex_lock (&counters_mutex);
2310
2311         /* mark all perfcounters as deleted, foreach will unmark them as necessary */
2312         for (pcagent = perfcounters; pcagent; pcagent = pcagent->next)
2313                 pcagent->deleted = 1;
2314
2315         mono_perfcounter_foreach (perfcounters_foreach, perfcounters);
2316
2317         perfcounters_emit (profiler);
2318
2319
2320         size = 1 + 10 + 5;
2321         for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
2322                 if (pcagent->deleted || !pcagent->updated)
2323                         continue;
2324                 size += 10 * 2 + sizeof (gint64);
2325         }
2326
2327         logbuffer = ensure_logbuf (size);
2328
2329         ENTER_LOG (logbuffer, "perfcounters");
2330         emit_byte (logbuffer, TYPE_SAMPLE_COUNTERS | TYPE_SAMPLE);
2331         emit_uvalue (logbuffer, timestamp);
2332         for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
2333                 if (pcagent->deleted || !pcagent->updated)
2334                         continue;
2335                 emit_uvalue (logbuffer, pcagent->index);
2336                 emit_uvalue (logbuffer, MONO_COUNTER_LONG);
2337                 emit_svalue (logbuffer, pcagent->value);
2338
2339                 pcagent->updated = 0;
2340         }
2341
2342         emit_value (logbuffer, 0);
2343         EXIT_LOG (logbuffer);
2344
2345         safe_dump (profiler, ensure_logbuf (0));
2346
2347         mono_mutex_unlock (&counters_mutex);
2348 }
2349
2350 static void
2351 counters_and_perfcounters_sample (MonoProfiler *prof)
2352 {
2353         static uint64_t start = -1;
2354         uint64_t now;
2355
2356         if (start == -1)
2357                 start = current_time ();
2358
2359         now = current_time ();
2360         counters_sample (prof, (now - start) / 1000/ 1000);
2361         perfcounters_sample (prof, (now - start) / 1000/ 1000);
2362 }
2363
2364 #endif /* DISABLE_HELPER_THREAD */
2365
2366 static void
2367 log_shutdown (MonoProfiler *prof)
2368 {
2369         in_shutdown = 1;
2370 #ifndef DISABLE_HELPER_THREAD
2371         counters_and_perfcounters_sample (prof);
2372
2373         if (prof->command_port) {
2374                 char c = 1;
2375                 void *res;
2376                 ign_res (write (prof->pipes [1], &c, 1));
2377                 pthread_join (prof->helper_thread, &res);
2378         }
2379 #endif
2380 #if USE_PERF_EVENTS
2381         if (perf_data) {
2382                 int i;
2383                 for (i = 0; i < num_perf; ++i)
2384                         read_perf_mmap (prof, i);
2385         }
2386 #endif
2387         dump_sample_hits (prof, prof->stat_buffers, 1);
2388         take_lock ();
2389         if (TLS_GET (tlsbuffer))
2390                 dump_buffer (prof, TLS_GET (tlsbuffer));
2391         TLS_SET (tlsbuffer, NULL);
2392         release_lock ();
2393 #if defined (HAVE_SYS_ZLIB)
2394         if (prof->gzfile)
2395                 gzclose (prof->gzfile);
2396 #endif
2397         if (prof->pipe_output)
2398                 pclose (prof->file);
2399         else
2400                 fclose (prof->file);
2401         free (prof);
2402 }
2403
2404 static char*
2405 new_filename (const char* filename)
2406 {
2407         time_t t = time (NULL);
2408         int pid = process_id ();
2409         char pid_buf [16];
2410         char time_buf [16];
2411         char *res, *d;
2412         const char *p;
2413         int count_dates = 0;
2414         int count_pids = 0;
2415         int s_date, s_pid;
2416         struct tm *ts;
2417         for (p = filename; *p; p++) {
2418                 if (*p != '%')
2419                         continue;
2420                 p++;
2421                 if (*p == 't')
2422                         count_dates++;
2423                 else if (*p == 'p')
2424                         count_pids++;
2425                 else if (*p == 0)
2426                         break;
2427         }
2428         if (!count_dates && !count_pids)
2429                 return pstrdup (filename);
2430         snprintf (pid_buf, sizeof (pid_buf), "%d", pid);
2431         ts = gmtime (&t);
2432         snprintf (time_buf, sizeof (time_buf), "%d%02d%02d%02d%02d%02d",
2433                 1900 + ts->tm_year, 1 + ts->tm_mon, ts->tm_mday, ts->tm_hour, ts->tm_min, ts->tm_sec);
2434         s_date = strlen (time_buf);
2435         s_pid = strlen (pid_buf);
2436         d = res = malloc (strlen (filename) + s_date * count_dates + s_pid * count_pids);
2437         for (p = filename; *p; p++) {
2438                 if (*p != '%') {
2439                         *d++ = *p;
2440                         continue;
2441                 }
2442                 p++;
2443                 if (*p == 't') {
2444                         strcpy (d, time_buf);
2445                         d += s_date;
2446                         continue;
2447                 } else if (*p == 'p') {
2448                         strcpy (d, pid_buf);
2449                         d += s_pid;
2450                         continue;
2451                 } else if (*p == '%') {
2452                         *d++ = '%';
2453                         continue;
2454                 } else if (*p == 0)
2455                         break;
2456                 *d++ = '%';
2457                 *d++ = *p;
2458         }
2459         *d = 0;
2460         return res;
2461 }
2462
2463 #ifndef DISABLE_HELPER_THREAD
2464
2465 //this is exposed by the JIT, but it's not meant to be a supported API for now.
2466 extern void mono_threads_attach_tools_thread (void);
2467
2468 static void*
2469 helper_thread (void* arg)
2470 {
2471         MonoProfiler* prof = arg;
2472         int command_socket;
2473         int len;
2474         char buf [64];
2475         MonoThread *thread = NULL;
2476
2477         mono_threads_attach_tools_thread ();
2478         //fprintf (stderr, "Server listening\n");
2479         command_socket = -1;
2480         while (1) {
2481                 fd_set rfds;
2482                 struct timeval tv;
2483                 int max_fd = -1;
2484                 FD_ZERO (&rfds);
2485                 FD_SET (prof->server_socket, &rfds);
2486                 max_fd = prof->server_socket;
2487                 FD_SET (prof->pipes [0], &rfds);
2488                 if (max_fd < prof->pipes [0])
2489                         max_fd = prof->pipes [0];
2490                 if (command_socket >= 0) {
2491                         FD_SET (command_socket, &rfds);
2492                         if (max_fd < command_socket)
2493                                 max_fd = command_socket;
2494                 }
2495 #if USE_PERF_EVENTS
2496                 if (perf_data) {
2497                         int i;
2498                         for ( i = 0; i < num_perf; ++i) {
2499                                 if (perf_data [i].perf_fd < 0)
2500                                         continue;
2501                                 FD_SET (perf_data [i].perf_fd, &rfds);
2502                                 if (max_fd < perf_data [i].perf_fd)
2503                                         max_fd = perf_data [i].perf_fd;
2504                         }
2505                 }
2506 #endif
2507
2508                 counters_and_perfcounters_sample (prof);
2509
2510                 tv.tv_sec = 1;
2511                 tv.tv_usec = 0;
2512                 len = select (max_fd + 1, &rfds, NULL, NULL, &tv);
2513
2514                 if (len < 0) {
2515                         if (errno == EINTR)
2516                                 continue;
2517                         
2518                         g_warning ("Error in proflog server: %s", strerror (errno));
2519                         return NULL;
2520                 }
2521                 
2522                 if (FD_ISSET (prof->pipes [0], &rfds)) {
2523                         char c;
2524                         int r = read (prof->pipes [0], &c, 1);
2525                         if (r == 1 && c == 0) {
2526                                 StatBuffer *sbufbase = prof->stat_buffers;
2527                                 StatBuffer *sbuf;
2528                                 if (!sbufbase->next)
2529                                         continue;
2530                                 sbuf = sbufbase->next->next;
2531                                 sbufbase->next->next = NULL;
2532                                 if (do_debug)
2533                                         fprintf (stderr, "stat buffer dump\n");
2534                                 if (sbuf) {
2535                                         dump_sample_hits (prof, sbuf, 1);
2536                                         free_buffer (sbuf, sbuf->size);
2537                                         safe_dump (prof, ensure_logbuf (0));
2538                                 }
2539                                 continue;
2540                         }
2541                         /* time to shut down */
2542                         if (thread)
2543                                 mono_thread_detach (thread);
2544                         if (do_debug)
2545                                 fprintf (stderr, "helper shutdown\n");
2546 #if USE_PERF_EVENTS
2547                         if (perf_data) {
2548                                 int i;
2549                                 for ( i = 0; i < num_perf; ++i) {
2550                                         if (perf_data [i].perf_fd < 0)
2551                                                 continue;
2552                                         if (FD_ISSET (perf_data [i].perf_fd, &rfds))
2553                                                 read_perf_mmap (prof, i);
2554                                 }
2555                         }
2556 #endif
2557                         safe_dump (prof, ensure_logbuf (0));
2558                         return NULL;
2559                 }
2560 #if USE_PERF_EVENTS
2561                 if (perf_data) {
2562                         int i;
2563                         for ( i = 0; i < num_perf; ++i) {
2564                                 if (perf_data [i].perf_fd < 0)
2565                                         continue;
2566                                 if (FD_ISSET (perf_data [i].perf_fd, &rfds)) {
2567                                         read_perf_mmap (prof, i);
2568                                         safe_dump (prof, ensure_logbuf (0));
2569                                 }
2570                         }
2571                 }
2572 #endif
2573                 if (command_socket >= 0 && FD_ISSET (command_socket, &rfds)) {
2574                         len = read (command_socket, buf, sizeof (buf) - 1);
2575                         if (len < 0)
2576                                 continue;
2577                         if (len == 0) {
2578                                 close (command_socket);
2579                                 command_socket = -1;
2580                                 continue;
2581                         }
2582                         buf [len] = 0;
2583                         if (strcmp (buf, "heapshot\n") == 0) {
2584                                 heapshot_requested = 1;
2585                                 //fprintf (stderr, "perform heapshot\n");
2586                                 if (runtime_inited && !thread) {
2587                                         thread = mono_thread_attach (mono_get_root_domain ());
2588                                         /*fprintf (stderr, "attached\n");*/
2589                                 }
2590                                 if (thread) {
2591                                         process_requests (prof);
2592                                         mono_thread_detach (thread);
2593                                         thread = NULL;
2594                                 }
2595                         }
2596                         continue;
2597                 }
2598                 if (!FD_ISSET (prof->server_socket, &rfds)) {
2599                         continue;
2600                 }
2601                 command_socket = accept (prof->server_socket, NULL, NULL);
2602                 if (command_socket < 0)
2603                         continue;
2604                 //fprintf (stderr, "Accepted connection\n");
2605         }
2606         return NULL;
2607 }
2608
2609 static int
2610 start_helper_thread (MonoProfiler* prof)
2611 {
2612         struct sockaddr_in server_address;
2613         int r;
2614         socklen_t slen;
2615         if (pipe (prof->pipes) < 0) {
2616                 fprintf (stderr, "Cannot create pipe\n");
2617                 return 0;
2618         }
2619         prof->server_socket = socket (PF_INET, SOCK_STREAM, 0);
2620         if (prof->server_socket < 0) {
2621                 fprintf (stderr, "Cannot create server socket\n");
2622                 return 0;
2623         }
2624         memset (&server_address, 0, sizeof (server_address));
2625         server_address.sin_family = AF_INET;
2626         server_address.sin_addr.s_addr = INADDR_ANY;
2627         server_address.sin_port = htons (prof->command_port);
2628         if (bind (prof->server_socket, (struct sockaddr *) &server_address, sizeof (server_address)) < 0) {
2629                 fprintf (stderr, "Cannot bind server socket, port: %d: %s\n", prof->command_port, strerror (errno));
2630                 close (prof->server_socket);
2631                 return 0;
2632         }
2633         if (listen (prof->server_socket, 1) < 0) {
2634                 fprintf (stderr, "Cannot listen server socket\n");
2635                 close (prof->server_socket);
2636                 return 0;
2637         }
2638         slen = sizeof (server_address);
2639         if (getsockname (prof->server_socket, (struct sockaddr *)&server_address, &slen) == 0) {
2640                 prof->command_port = ntohs (server_address.sin_port);
2641                 /*fprintf (stderr, "Assigned server port: %d\n", prof->command_port);*/
2642         }
2643
2644         r = pthread_create (&prof->helper_thread, NULL, helper_thread, prof);
2645         if (r) {
2646                 close (prof->server_socket);
2647                 return 0;
2648         }
2649         return 1;
2650 }
2651 #endif
2652
2653 static MonoProfiler*
2654 create_profiler (const char *filename)
2655 {
2656         MonoProfiler *prof;
2657         char *nf;
2658         int force_delete = 0;
2659         int need_helper_thread = 0;
2660         prof = calloc (1, sizeof (MonoProfiler));
2661
2662         prof->command_port = command_port;
2663         if (filename && *filename == '-') {
2664                 force_delete = 1;
2665                 filename++;
2666         }
2667         if (!filename) {
2668                 if (do_report)
2669                         filename = "|mprof-report -";
2670                 else
2671                         filename = "output.mlpd";
2672                 nf = (char*)filename;
2673         } else {
2674                 nf = new_filename (filename);
2675                 if (do_report) {
2676                         int s = strlen (nf) + 32;
2677                         char *p = malloc (s);
2678                         snprintf (p, s, "|mprof-report '--out=%s' -", nf);
2679                         free (nf);
2680                         nf = p;
2681                 }
2682         }
2683         if (*nf == '|') {
2684                 prof->file = popen (nf + 1, "w");
2685                 prof->pipe_output = 1;
2686         } else if (*nf == '#') {
2687                 int fd = strtol (nf + 1, NULL, 10);
2688                 prof->file = fdopen (fd, "a");
2689         } else {
2690                 FILE *f;
2691                 if (force_delete)
2692                         unlink (nf);
2693                 if ((f = fopen (nf, "r"))) {
2694                         fclose (f);
2695                         fprintf (stderr, "The Mono profiler won't overwrite existing filename: %s.\n", nf);
2696                         fprintf (stderr, "Profiling disabled: use a different name or -FILENAME to force overwrite.\n");
2697                         free (prof);
2698                         return NULL;
2699                 }
2700                 prof->file = fopen (nf, "wb");
2701         }
2702         if (!prof->file) {
2703                 fprintf (stderr, "Cannot create profiler output: %s\n", nf);
2704                 exit (1);
2705         }
2706 #if defined (HAVE_SYS_ZLIB)
2707         if (use_zip)
2708                 prof->gzfile = gzdopen (fileno (prof->file), "wb");
2709 #endif
2710 #if USE_PERF_EVENTS
2711         if (sample_type && !do_mono_sample)
2712                 need_helper_thread = setup_perf_event ();
2713         if (!perf_data) {
2714                 /* FIXME: warn if different freq or sample type */
2715                 do_mono_sample = 1;
2716         }
2717 #endif
2718         if (do_mono_sample) {
2719                 prof->stat_buffers = create_stat_buffer ();
2720                 need_helper_thread = 1;
2721         }
2722         if (do_counters && !need_helper_thread) {
2723                 need_helper_thread = 1;
2724         }
2725 #ifndef DISABLE_HELPER_THREAD
2726         if (hs_mode_ondemand || need_helper_thread) {
2727                 if (!start_helper_thread (prof))
2728                         prof->command_port = 0;
2729         }
2730 #else
2731         if (hs_mode_ondemand)
2732                 fprintf (stderr, "Ondemand heapshot unavailable on this arch.\n");
2733 #endif
2734         prof->startup_time = current_time ();
2735         dump_header (prof);
2736         return prof;
2737 }
2738
2739 static void
2740 usage (int do_exit)
2741 {
2742         printf ("Log profiler version %d.%d (format: %d)\n", LOG_VERSION_MAJOR, LOG_VERSION_MINOR, LOG_DATA_VERSION);
2743         printf ("Usage: mono --profile=log[:OPTION1[,OPTION2...]] program.exe\n");
2744         printf ("Options:\n");
2745         printf ("\thelp             show this usage info\n");
2746         printf ("\t[no]alloc        enable/disable recording allocation info\n");
2747         printf ("\t[no]calls        enable/disable recording enter/leave method events\n");
2748         printf ("\theapshot[=MODE]  record heap shot info (by default at each major collection)\n");
2749         printf ("\t                 MODE: every XXms milliseconds, every YYgc collections, ondemand\n");
2750         printf ("\tcounters         sample counters every 1s\n");
2751         printf ("\tsample[=TYPE]    use statistical sampling mode (by default cycles/1000)\n");
2752         printf ("\t                 TYPE: cycles,instr,cacherefs,cachemiss,branches,branchmiss\n");
2753         printf ("\t                 TYPE can be followed by /FREQUENCY\n");
2754         printf ("\ttime=fast        use a faster (but more inaccurate) timer\n");
2755         printf ("\tmaxframes=NUM    collect up to NUM stack frames\n");
2756         printf ("\tcalldepth=NUM    ignore method events for call chain depth bigger than NUM\n");
2757         printf ("\toutput=FILENAME  write the data to file FILENAME (-FILENAME to overwrite)\n");
2758         printf ("\toutput=|PROGRAM  write the data to the stdin of PROGRAM\n");
2759         printf ("\t                 %%t is subtituted with date and time, %%p with the pid\n");
2760         printf ("\treport           create a report instead of writing the raw data to a file\n");
2761         printf ("\tzip              compress the output data\n");
2762         printf ("\tport=PORTNUM     use PORTNUM for the listening command server\n");
2763         if (do_exit)
2764                 exit (1);
2765 }
2766
2767 static const char*
2768 match_option (const char* p, const char *opt, char **rval)
2769 {
2770         int len = strlen (opt);
2771         if (strncmp (p, opt, len) == 0) {
2772                 if (rval) {
2773                         if (p [len] == '=' && p [len + 1]) {
2774                                 const char *opt = p + len + 1;
2775                                 const char *end = strchr (opt, ',');
2776                                 char *val;
2777                                 int l;
2778                                 if (end == NULL) {
2779                                         l = strlen (opt);
2780                                 } else {
2781                                         l = end - opt;
2782                                 }
2783                                 val = malloc (l + 1);
2784                                 memcpy (val, opt, l);
2785                                 val [l] = 0;
2786                                 *rval = val;
2787                                 return opt + l;
2788                         }
2789                         if (p [len] == 0 || p [len] == ',') {
2790                                 *rval = NULL;
2791                                 return p + len + (p [len] == ',');
2792                         }
2793                         usage (1);
2794                 } else {
2795                         if (p [len] == 0)
2796                                 return p + len;
2797                         if (p [len] == ',')
2798                                 return p + len + 1;
2799                 }
2800         }
2801         return p;
2802 }
2803
2804 typedef struct {
2805         const char *name;
2806         int sample_mode;
2807 } SampleMode;
2808
2809 static const SampleMode sample_modes [] = {
2810         {"cycles", SAMPLE_CYCLES},
2811         {"instr", SAMPLE_INSTRUCTIONS},
2812         {"cachemiss", SAMPLE_CACHE_MISSES},
2813         {"cacherefs", SAMPLE_CACHE_REFS},
2814         {"branches", SAMPLE_BRANCHES},
2815         {"branchmiss", SAMPLE_BRANCH_MISSES},
2816         {NULL, 0}
2817 };
2818
2819 static void
2820 set_sample_mode (char* val, int allow_empty)
2821 {
2822         char *end;
2823         char *maybe_freq = NULL;
2824         unsigned int count;
2825         const SampleMode *smode = sample_modes;
2826 #ifndef USE_PERF_EVENTS
2827         do_mono_sample = 1;
2828 #endif
2829         if (allow_empty && !val) {
2830                 sample_type = SAMPLE_CYCLES;
2831                 sample_freq = 1000;
2832                 return;
2833         }
2834         if (strcmp (val, "mono") == 0) {
2835                 do_mono_sample = 1;
2836                 sample_type = SAMPLE_CYCLES;
2837                 free (val);
2838                 return;
2839         }
2840         for (smode = sample_modes; smode->name; smode++) {
2841                 int l = strlen (smode->name);
2842                 if (strncmp (val, smode->name, l) == 0) {
2843                         sample_type = smode->sample_mode;
2844                         maybe_freq = val + l;
2845                         break;
2846                 }
2847         }
2848         if (!smode->name)
2849                 usage (1);
2850         if (*maybe_freq == '/') {
2851                 count = strtoul (maybe_freq + 1, &end, 10);
2852                 if (maybe_freq + 1 == end)
2853                         usage (1);
2854                 sample_freq = count;
2855         } else if (*maybe_freq != 0) {
2856                 usage (1);
2857         } else {
2858                 sample_freq = 1000;
2859         }
2860         free (val);
2861 }
2862
2863 static void
2864 set_hsmode (char* val, int allow_empty)
2865 {
2866         char *end;
2867         unsigned int count;
2868         if (allow_empty && !val)
2869                 return;
2870         if (strcmp (val, "ondemand") == 0) {
2871                 hs_mode_ondemand = 1;
2872                 free (val);
2873                 return;
2874         }
2875         count = strtoul (val, &end, 10);
2876         if (val == end)
2877                 usage (1);
2878         if (strcmp (end, "ms") == 0)
2879                 hs_mode_ms = count;
2880         else if (strcmp (end, "gc") == 0)
2881                 hs_mode_gc = count;
2882         else
2883                 usage (1);
2884         free (val);
2885 }
2886
2887 /* 
2888  * declaration to silence the compiler: this is the entry point that
2889  * mono will load from the shared library and call.
2890  */
2891 extern void
2892 mono_profiler_startup (const char *desc);
2893
2894 extern void
2895 mono_profiler_startup_log (const char *desc);
2896
2897 /*
2898  * this is the entry point that will be used when the profiler
2899  * is embedded inside the main executable.
2900  */
2901 void
2902 mono_profiler_startup_log (const char *desc)
2903 {
2904         mono_profiler_startup (desc);
2905 }
2906
2907 void
2908 mono_profiler_startup (const char *desc)
2909 {
2910         MonoProfiler *prof;
2911         char *filename = NULL;
2912         const char *p;
2913         const char *opt;
2914         int fast_time = 0;
2915         int calls_enabled = 0;
2916         int allocs_enabled = 0;
2917         int only_counters = 0;
2918         int events = MONO_PROFILE_GC|MONO_PROFILE_ALLOCATIONS|
2919                 MONO_PROFILE_GC_MOVES|MONO_PROFILE_CLASS_EVENTS|MONO_PROFILE_THREADS|
2920                 MONO_PROFILE_ENTER_LEAVE|MONO_PROFILE_JIT_COMPILATION|MONO_PROFILE_EXCEPTIONS|
2921                 MONO_PROFILE_MONITOR_EVENTS|MONO_PROFILE_MODULE_EVENTS|MONO_PROFILE_GC_ROOTS;
2922
2923         p = desc;
2924         if (strncmp (p, "log", 3))
2925                 usage (1);
2926         p += 3;
2927         if (*p == ':')
2928                 p++;
2929         for (; *p; p = opt) {
2930                 char *val;
2931                 if (*p == ',') {
2932                         opt = p + 1;
2933                         continue;
2934                 }
2935                 if ((opt = match_option (p, "help", NULL)) != p) {
2936                         usage (0);
2937                         continue;
2938                 }
2939                 if ((opt = match_option (p, "calls", NULL)) != p) {
2940                         calls_enabled = 1;
2941                         continue;
2942                 }
2943                 if ((opt = match_option (p, "nocalls", NULL)) != p) {
2944                         events &= ~MONO_PROFILE_ENTER_LEAVE;
2945                         nocalls = 1;
2946                         continue;
2947                 }
2948                 if ((opt = match_option (p, "alloc", NULL)) != p) {
2949                         allocs_enabled = 1;
2950                         continue;
2951                 }
2952                 if ((opt = match_option (p, "noalloc", NULL)) != p) {
2953                         events &= ~MONO_PROFILE_ALLOCATIONS;
2954                         continue;
2955                 }
2956                 if ((opt = match_option (p, "time", &val)) != p) {
2957                         if (strcmp (val, "fast") == 0)
2958                                 fast_time = 1;
2959                         else if (strcmp (val, "null") == 0)
2960                                 fast_time = 2;
2961                         else
2962                                 usage (1);
2963                         free (val);
2964                         continue;
2965                 }
2966                 if ((opt = match_option (p, "report", NULL)) != p) {
2967                         do_report = 1;
2968                         continue;
2969                 }
2970                 if ((opt = match_option (p, "debug", NULL)) != p) {
2971                         do_debug = 1;
2972                         continue;
2973                 }
2974                 if ((opt = match_option (p, "sampling-real", NULL)) != p) {
2975                         sampling_mode = MONO_PROFILER_STAT_MODE_REAL;
2976                         continue;
2977                 }
2978                 if ((opt = match_option (p, "sampling-process", NULL)) != p) {
2979                         sampling_mode = MONO_PROFILER_STAT_MODE_PROCESS;
2980                         continue;
2981                 }
2982                 if ((opt = match_option (p, "heapshot", &val)) != p) {
2983                         events &= ~MONO_PROFILE_ALLOCATIONS;
2984                         events &= ~MONO_PROFILE_ENTER_LEAVE;
2985                         nocalls = 1;
2986                         do_heap_shot = 1;
2987                         set_hsmode (val, 1);
2988                         continue;
2989                 }
2990                 if ((opt = match_option (p, "sample", &val)) != p) {
2991                         events &= ~MONO_PROFILE_ALLOCATIONS;
2992                         events &= ~MONO_PROFILE_ENTER_LEAVE;
2993                         nocalls = 1;
2994                         set_sample_mode (val, 1);
2995                         continue;
2996                 }
2997                 if ((opt = match_option (p, "hsmode", &val)) != p) {
2998                         fprintf (stderr, "The hsmode profiler option is obsolete, use heapshot=MODE.\n");
2999                         set_hsmode (val, 0);
3000                         continue;
3001                 }
3002                 if ((opt = match_option (p, "zip", NULL)) != p) {
3003                         use_zip = 1;
3004                         continue;
3005                 }
3006                 if ((opt = match_option (p, "output", &val)) != p) {
3007                         filename = val;
3008                         continue;
3009                 }
3010                 if ((opt = match_option (p, "port", &val)) != p) {
3011                         char *end;
3012                         command_port = strtoul (val, &end, 10);
3013                         free (val);
3014                         continue;
3015                 }
3016                 if ((opt = match_option (p, "maxframes", &val)) != p) {
3017                         char *end;
3018                         num_frames = strtoul (val, &end, 10);
3019                         if (num_frames > MAX_FRAMES)
3020                                 num_frames = MAX_FRAMES;
3021                         free (val);
3022                         notraces = num_frames == 0;
3023                         continue;
3024                 }
3025                 if ((opt = match_option (p, "calldepth", &val)) != p) {
3026                         char *end;
3027                         max_call_depth = strtoul (val, &end, 10);
3028                         free (val);
3029                         continue;
3030                 }
3031                 if ((opt = match_option (p, "counters", NULL)) != p) {
3032                         do_counters = 1;
3033                         continue;
3034                 }
3035                 if ((opt = match_option (p, "countersonly", NULL)) != p) {
3036                         only_counters = 1;
3037                         continue;
3038                 }
3039                 if (opt == p) {
3040                         usage (0);
3041                         exit (0);
3042                 }
3043         }
3044         if (calls_enabled) {
3045                 events |= MONO_PROFILE_ENTER_LEAVE;
3046                 nocalls = 0;
3047         }
3048         if (allocs_enabled)
3049                 events |= MONO_PROFILE_ALLOCATIONS;
3050         if (only_counters)
3051                 events = 0;
3052         utils_init (fast_time);
3053
3054         prof = create_profiler (filename);
3055         if (!prof)
3056                 return;
3057         init_thread ();
3058
3059         mono_profiler_install (prof, log_shutdown);
3060         mono_profiler_install_gc (gc_event, gc_resize);
3061         mono_profiler_install_allocation (gc_alloc);
3062         mono_profiler_install_gc_moves (gc_moves);
3063         mono_profiler_install_gc_roots (gc_handle, gc_roots);
3064         mono_profiler_install_class (NULL, class_loaded, NULL, NULL);
3065         mono_profiler_install_module (NULL, image_loaded, NULL, NULL);
3066         mono_profiler_install_thread (thread_start, thread_end);
3067         mono_profiler_install_thread_name (thread_name);
3068         mono_profiler_install_enter_leave (method_enter, method_leave);
3069         mono_profiler_install_jit_end (method_jitted);
3070         mono_profiler_install_exception (throw_exc, method_exc_leave, clause_exc);
3071         mono_profiler_install_monitor (monitor_event);
3072         mono_profiler_install_runtime_initialized (runtime_initialized);
3073
3074         
3075         if (do_mono_sample && sample_type == SAMPLE_CYCLES && !only_counters) {
3076                 events |= MONO_PROFILE_STATISTICAL;
3077                 mono_profiler_set_statistical_mode (sampling_mode, 1000000 / sample_freq);
3078                 mono_profiler_install_statistical (mono_sample_hit);
3079         }
3080
3081         mono_profiler_set_events (events);
3082
3083         TLS_INIT (tlsbuffer);
3084 }
3085