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