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