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