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