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