[profiler] Load the profiler with MONO_DL_EAGER.
[mono.git] / mono / profiler / proflog.c
1 /*
2  * proflog.c: mono log profiler
3  *
4  * Authors:
5  *   Paolo Molaro (lupus@ximian.com)
6  *   Alex Rønne Petersen (alexrp@xamarin.com)
7  *
8  * Copyright 2010 Novell, Inc (http://www.novell.com)
9  * Copyright 2011 Xamarin Inc (http://www.xamarin.com)
10  * Licensed under the MIT license. See LICENSE file in the project root for full license information.
11  */
12
13 #include <config.h>
14 #include "../mini/jit.h"
15 #include "../metadata/metadata-internals.h"
16 #include <mono/metadata/profiler.h>
17 #include <mono/metadata/threads.h>
18 #include <mono/metadata/mono-gc.h>
19 #include <mono/metadata/debug-helpers.h>
20 #include <mono/metadata/mono-perfcounters.h>
21 #include <mono/metadata/appdomain.h>
22 #include <mono/metadata/assembly.h>
23 #include <mono/metadata/tokentype.h>
24 #include <mono/metadata/tabledefs.h>
25 #include <mono/utils/atomic.h>
26 #include <mono/utils/mono-membar.h>
27 #include <mono/utils/mono-mmap.h>
28 #include <mono/utils/mono-counters.h>
29 #include <mono/utils/mono-os-mutex.h>
30 #include <mono/utils/mono-conc-hashtable.h>
31 #include <mono/utils/lock-free-alloc.h>
32 #include <mono/utils/lock-free-queue.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include <assert.h>
36 #include <glib.h>
37 #ifdef HAVE_UNISTD_H
38 #include <unistd.h>
39 #endif
40 #ifdef HAVE_SCHED_GETAFFINITY
41 #include <sched.h>
42 #endif
43 #include <fcntl.h>
44 #include <errno.h>
45 #if defined(HOST_WIN32) || defined(DISABLE_SOCKETS)
46 #define DISABLE_HELPER_THREAD 1
47 #endif
48
49 #ifndef _GNU_SOURCE
50 #define _GNU_SOURCE
51 #endif
52 #ifdef HAVE_DLFCN_H
53 #include <dlfcn.h>
54 #endif
55 #ifdef HAVE_EXECINFO_H
56 #include <execinfo.h>
57 #endif
58 #ifdef HAVE_LINK_H
59 #include <link.h>
60 #endif
61
62 #ifndef DISABLE_HELPER_THREAD
63 #include <sys/types.h>
64 #include <sys/socket.h>
65 #include <netinet/in.h>
66 #include <sys/select.h>
67 #endif
68
69 #ifdef HOST_WIN32
70 #include <windows.h>
71 #else
72 #include <pthread.h>
73 #endif
74
75 #ifdef HAVE_SYS_STAT_H
76 #include <sys/stat.h>
77 #endif
78
79 #include "utils.c"
80 #include "proflog.h"
81
82 #if defined (HAVE_SYS_ZLIB)
83 #include <zlib.h>
84 #endif
85
86 #if defined(__linux__)
87
88 #include <unistd.h>
89 #include <sys/syscall.h>
90
91 #ifdef ENABLE_PERF_EVENTS
92 #include <linux/perf_event.h>
93
94 #define USE_PERF_EVENTS 1
95
96 static int read_perf_mmap (MonoProfiler* prof, int cpu);
97 #endif
98
99 #endif
100
101 #define BUFFER_SIZE (4096 * 16)
102
103 /* Worst-case size in bytes of a 64-bit value encoded with LEB128. */
104 #define LEB128_SIZE 10
105 /* Size in bytes of the event ID prefix. */
106 #define EVENT_SIZE 1
107
108 static int nocalls = 0;
109 static int notraces = 0;
110 static int use_zip = 0;
111 static int do_report = 0;
112 static int do_heap_shot = 0;
113 static int max_call_depth = 100;
114 static volatile int runtime_inited = 0;
115 static int need_helper_thread = 0;
116 static int command_port = 0;
117 static int heapshot_requested = 0;
118 static int sample_type = 0;
119 static int sample_freq = 0;
120 static int do_mono_sample = 0;
121 static int in_shutdown = 0;
122 static int do_debug = 0;
123 static int do_counters = 0;
124 static int do_coverage = 0;
125 static gboolean debug_coverage = FALSE;
126 static MonoProfileSamplingMode sampling_mode = MONO_PROFILER_STAT_MODE_PROCESS;
127 static int max_allocated_sample_hits;
128
129 static gint32 sample_hits;
130 static gint32 sample_flushes;
131 static gint32 sample_allocations;
132 static gint32 buffer_allocations;
133 static gint32 thread_starts;
134 static gint32 thread_ends;
135 static gint32 domain_loads;
136 static gint32 domain_unloads;
137 static gint32 context_loads;
138 static gint32 context_unloads;
139 static gint32 assembly_loads;
140 static gint32 assembly_unloads;
141 static gint32 image_loads;
142 static gint32 image_unloads;
143 static gint32 class_loads;
144 static gint32 class_unloads;
145
146 typedef struct _LogBuffer LogBuffer;
147
148 /*
149  * file format:
150  * [header] [buffer]*
151  *
152  * The file is composed by a header followed by 0 or more buffers.
153  * Each buffer contains events that happened on a thread: for a given thread
154  * buffers that appear later in the file are guaranteed to contain events
155  * that happened later in time. Buffers from separate threads could be interleaved,
156  * though.
157  * Buffers are not required to be aligned.
158  *
159  * header format:
160  * [id: 4 bytes] constant value: LOG_HEADER_ID
161  * [major: 1 byte] [minor: 1 byte] major and minor version of the log profiler
162  * [format: 1 byte] version of the data format for the rest of the file
163  * [ptrsize: 1 byte] size in bytes of a pointer in the profiled program
164  * [startup time: 8 bytes] time in milliseconds since the unix epoch when the program started
165  * [timer overhead: 4 bytes] approximate overhead in nanoseconds of the timer
166  * [flags: 4 bytes] file format flags, should be 0 for now
167  * [pid: 4 bytes] pid of the profiled process
168  * [port: 2 bytes] tcp port for server if != 0
169  * [sysid: 2 bytes] operating system and architecture identifier
170  *
171  * The multiple byte integers are in little-endian format.
172  *
173  * buffer format:
174  * [buffer header] [event]*
175  * Buffers have a fixed-size header followed by 0 or more bytes of event data.
176  * Timing information and other values in the event data are usually stored
177  * as uleb128 or sleb128 integers. To save space, as noted for each item below,
178  * some data is represented as a difference between the actual value and
179  * either the last value of the same type (like for timing information) or
180  * as the difference from a value stored in a buffer header.
181  *
182  * For timing information the data is stored as uleb128, since timing
183  * increases in a monotonic way in each thread: the value is the number of
184  * nanoseconds to add to the last seen timing data in a buffer. The first value
185  * in a buffer will be calculated from the time_base field in the buffer head.
186  *
187  * Object or heap sizes are stored as uleb128.
188  * Pointer differences are stored as sleb128, instead.
189  *
190  * If an unexpected value is found, the rest of the buffer should be ignored,
191  * as generally the later values need the former to be interpreted correctly.
192  *
193  * buffer header format:
194  * [bufid: 4 bytes] constant value: BUF_ID
195  * [len: 4 bytes] size of the data following the buffer header
196  * [time_base: 8 bytes] time base in nanoseconds since an unspecified epoch
197  * [ptr_base: 8 bytes] base value for pointers
198  * [obj_base: 8 bytes] base value for object addresses
199  * [thread id: 8 bytes] system-specific thread ID (pthread_t for example)
200  * [method_base: 8 bytes] base value for MonoMethod pointers
201  *
202  * event format:
203  * [extended info: upper 4 bits] [type: lower 4 bits] [data]*
204  * The data that follows depends on type and the extended info.
205  * Type is one of the enum values in proflog.h: TYPE_ALLOC, TYPE_GC,
206  * TYPE_METADATA, TYPE_METHOD, TYPE_EXCEPTION, TYPE_MONITOR, TYPE_HEAP.
207  * The extended info bits are interpreted based on type, see
208  * each individual event description below.
209  * strings are represented as a 0-terminated utf8 sequence.
210  *
211  * backtrace format:
212  * [flags: uleb128] must be 0
213  * [num: uleb128] number of frames following
214  * [frame: sleb128]* num MonoMethod pointers as differences from ptr_base
215  *
216  * type alloc format:
217  * type: TYPE_ALLOC
218  * exinfo: flags: TYPE_ALLOC_BT
219  * [time diff: uleb128] nanoseconds since last timing
220  * [ptr: sleb128] class as a byte difference from ptr_base
221  * [obj: sleb128] object address as a byte difference from obj_base
222  * [size: uleb128] size of the object in the heap
223  * If the TYPE_ALLOC_BT flag is set, a backtrace follows.
224  *
225  * type GC format:
226  * type: TYPE_GC
227  * exinfo: one of TYPE_GC_EVENT, TYPE_GC_RESIZE, TYPE_GC_MOVE, TYPE_GC_HANDLE_CREATED[_BT],
228  * TYPE_GC_HANDLE_DESTROYED[_BT]
229  * [time diff: uleb128] nanoseconds since last timing
230  * if exinfo == TYPE_GC_RESIZE
231  *      [heap_size: uleb128] new heap size
232  * if exinfo == TYPE_GC_EVENT
233  *      [event type: uleb128] GC event (MONO_GC_EVENT_* from profiler.h)
234  *      [generation: uleb128] GC generation event refers to
235  * if exinfo == TYPE_GC_MOVE
236  *      [num_objects: uleb128] number of object moves that follow
237  *      [objaddr: sleb128]+ num_objects object pointer differences from obj_base
238  *      num is always an even number: the even items are the old
239  *      addresses, the odd numbers are the respective new object addresses
240  * if exinfo == TYPE_GC_HANDLE_CREATED[_BT]
241  *      [handle_type: uleb128] GC handle type (System.Runtime.InteropServices.GCHandleType)
242  *      upper bits reserved as flags
243  *      [handle: uleb128] GC handle value
244  *      [objaddr: sleb128] object pointer differences from obj_base
245  *      If exinfo == TYPE_GC_HANDLE_CREATED_BT, a backtrace follows.
246  * if exinfo == TYPE_GC_HANDLE_DESTROYED[_BT]
247  *      [handle_type: uleb128] GC handle type (System.Runtime.InteropServices.GCHandleType)
248  *      upper bits reserved as flags
249  *      [handle: uleb128] GC handle value
250  *      If exinfo == TYPE_GC_HANDLE_DESTROYED_BT, a backtrace follows.
251  *
252  * type metadata format:
253  * type: TYPE_METADATA
254  * exinfo: one of: TYPE_END_LOAD, TYPE_END_UNLOAD (optional for TYPE_THREAD and TYPE_DOMAIN)
255  * [time diff: uleb128] nanoseconds since last timing
256  * [mtype: byte] metadata type, one of: TYPE_CLASS, TYPE_IMAGE, TYPE_ASSEMBLY, TYPE_DOMAIN,
257  * TYPE_THREAD, TYPE_CONTEXT
258  * [pointer: sleb128] pointer of the metadata type depending on mtype
259  * if mtype == TYPE_CLASS
260  *      [image: sleb128] MonoImage* as a pointer difference from ptr_base
261  *      [flags: uleb128] must be 0
262  *      [name: string] full class name
263  * if mtype == TYPE_IMAGE
264  *      [flags: uleb128] must be 0
265  *      [name: string] image file name
266  * if mtype == TYPE_ASSEMBLY
267  *      [flags: uleb128] must be 0
268  *      [name: string] assembly name
269  * if mtype == TYPE_DOMAIN
270  *      [flags: uleb128] must be 0
271  * if mtype == TYPE_DOMAIN && exinfo == 0
272  *      [name: string] domain friendly name
273  * if mtype == TYPE_CONTEXT
274  *      [flags: uleb128] must be 0
275  *      [domain: sleb128] domain id as pointer
276  * if mtype == TYPE_THREAD && (format_version < 11 || (format_version > 10 && exinfo == 0))
277  *      [flags: uleb128] must be 0
278  *      [name: string] thread name
279  *
280  * type method format:
281  * type: TYPE_METHOD
282  * exinfo: one of: TYPE_LEAVE, TYPE_ENTER, TYPE_EXC_LEAVE, TYPE_JIT
283  * [time diff: uleb128] nanoseconds since last timing
284  * [method: sleb128] MonoMethod* as a pointer difference from the last such
285  * pointer or the buffer method_base
286  * if exinfo == TYPE_JIT
287  *      [code address: sleb128] pointer to the native code as a diff from ptr_base
288  *      [code size: uleb128] size of the generated code
289  *      [name: string] full method name
290  *
291  * type runtime format:
292  * type: TYPE_RUNTIME
293  * exinfo: one of: TYPE_JITHELPER
294  * [time diff: uleb128] nanoseconds since last timing
295  * if exinfo == TYPE_JITHELPER
296  *      [type: uleb128] MonoProfilerCodeBufferType enum value
297  *      [buffer address: sleb128] pointer to the native code as a diff from ptr_base
298  *      [buffer size: uleb128] size of the generated code
299  *      if type == MONO_PROFILER_CODE_BUFFER_SPECIFIC_TRAMPOLINE
300  *              [name: string] buffer description name
301  *
302  * type monitor format:
303  * type: TYPE_MONITOR
304  * exinfo: TYPE_MONITOR_BT flag and one of: MONO_PROFILER_MONITOR_(CONTENTION|FAIL|DONE)
305  * [time diff: uleb128] nanoseconds since last timing
306  * [object: sleb128] the lock object as a difference from obj_base
307  * if exinfo.low3bits == MONO_PROFILER_MONITOR_CONTENTION
308  *      If the TYPE_MONITOR_BT flag is set, a backtrace follows.
309  *
310  * type heap format
311  * type: TYPE_HEAP
312  * exinfo: one of TYPE_HEAP_START, TYPE_HEAP_END, TYPE_HEAP_OBJECT, TYPE_HEAP_ROOT
313  * if exinfo == TYPE_HEAP_START
314  *      [time diff: uleb128] nanoseconds since last timing
315  * if exinfo == TYPE_HEAP_END
316  *      [time diff: uleb128] nanoseconds since last timing
317  * if exinfo == TYPE_HEAP_OBJECT
318  *      [object: sleb128] the object as a difference from obj_base
319  *      [class: sleb128] the object MonoClass* as a difference from ptr_base
320  *      [size: uleb128] size of the object on the heap
321  *      [num_refs: uleb128] number of object references
322  *      if (format version > 1) each referenced objref is preceded by a
323  *      uleb128 encoded offset: the first offset is from the object address
324  *      and each next offset is relative to the previous one
325  *      [objrefs: sleb128]+ object referenced as a difference from obj_base
326  *      The same object can appear multiple times, but only the first time
327  *      with size != 0: in the other cases this data will only be used to
328  *      provide additional referenced objects.
329  * if exinfo == TYPE_HEAP_ROOT
330  *      [num_roots: uleb128] number of root references
331  *      [num_gc: uleb128] number of major gcs
332  *      [object: sleb128] the object as a difference from obj_base
333  *      [root_type: uleb128] the root_type: MonoProfileGCRootType (profiler.h)
334  *      [extra_info: uleb128] the extra_info value
335  *      object, root_type and extra_info are repeated num_roots times
336  *
337  * type sample format
338  * type: TYPE_SAMPLE
339  * exinfo: one of TYPE_SAMPLE_HIT, TYPE_SAMPLE_USYM, TYPE_SAMPLE_UBIN, TYPE_SAMPLE_COUNTERS_DESC, TYPE_SAMPLE_COUNTERS
340  * if exinfo == TYPE_SAMPLE_HIT
341  *      [sample_type: uleb128] type of sample (SAMPLE_*)
342  *      [timestamp: uleb128] nanoseconds since startup (note: different from other timestamps!)
343  *      if (format_version > 10)
344  *              [thread: sleb128] thread id as difference from ptr_base
345  *      [count: uleb128] number of following instruction addresses
346  *      [ip: sleb128]* instruction pointer as difference from ptr_base
347  *      if (format_version > 5)
348  *              [mbt_count: uleb128] number of managed backtrace info triplets (method + IL offset + native offset)
349  *              [method: sleb128]* MonoMethod* as a pointer difference from the last such
350  *              pointer or the buffer method_base (the first such method can be also indentified by ip, but this is not neccessarily true)
351  *              [il_offset: sleb128]* IL offset inside method where the hit occurred
352  *              [native_offset: sleb128]* native offset inside method where the hit occurred
353  * if exinfo == TYPE_SAMPLE_USYM
354  *      [address: sleb128] symbol address as a difference from ptr_base
355  *      [size: uleb128] symbol size (may be 0 if unknown)
356  *      [name: string] symbol name
357  * if exinfo == TYPE_SAMPLE_UBIN
358  *      [time diff: uleb128] nanoseconds since last timing
359  *      [address: sleb128] address where binary has been loaded
360  *      [offset: uleb128] file offset of mapping (the same file can be mapped multiple times)
361  *      [size: uleb128] memory size
362  *      [name: string] binary name
363  * if exinfo == TYPE_SAMPLE_COUNTERS_DESC
364  *      [len: uleb128] number of counters
365  *      for i = 0 to len
366  *              [section: uleb128] section of counter
367  *              if section == MONO_COUNTER_PERFCOUNTERS:
368  *                      [section_name: string] section name of counter
369  *              [name: string] name of counter
370  *              [type: uleb128] type of counter
371  *              [unit: uleb128] unit of counter
372  *              [variance: uleb128] variance of counter
373  *              [index: uleb128] unique index of counter
374  * if exinfo == TYPE_SAMPLE_COUNTERS
375  *      [timestamp: uleb128] sampling timestamp
376  *      while true:
377  *              [index: uleb128] unique index of counter
378  *              if index == 0:
379  *                      break
380  *              [type: uleb128] type of counter value
381  *              if type == string:
382  *                      if value == null:
383  *                              [0: uleb128] 0 -> value is null
384  *                      else:
385  *                              [1: uleb128] 1 -> value is not null
386  *                              [value: string] counter value
387  *              else:
388  *                      [value: uleb128/sleb128/double] counter value, can be sleb128, uleb128 or double (determined by using type)
389  *
390  * type coverage format
391  * type: TYPE_COVERAGE
392  * exinfo: one of TYPE_COVERAGE_METHOD, TYPE_COVERAGE_STATEMENT, TYPE_COVERAGE_ASSEMBLY, TYPE_COVERAGE_CLASS
393  * if exinfo == TYPE_COVERAGE_METHOD
394  *  [assembly: string] name of assembly
395  *  [class: string] name of the class
396  *  [name: string] name of the method
397  *  [signature: string] the signature of the method
398  *  [filename: string] the file path of the file that contains this method
399  *  [token: uleb128] the method token
400  *  [method_id: uleb128] an ID for this data to associate with the buffers of TYPE_COVERAGE_STATEMENTS
401  *  [len: uleb128] the number of TYPE_COVERAGE_BUFFERS associated with this method
402  * if exinfo == TYPE_COVERAGE_STATEMENTS
403  *  [method_id: uleb128] an the TYPE_COVERAGE_METHOD buffer to associate this with
404  *  [offset: uleb128] the il offset relative to the previous offset
405  *  [counter: uleb128] the counter for this instruction
406  *  [line: uleb128] the line of filename containing this instruction
407  *  [column: uleb128] the column containing this instruction
408  * if exinfo == TYPE_COVERAGE_ASSEMBLY
409  *  [name: string] assembly name
410  *  [guid: string] assembly GUID
411  *  [filename: string] assembly filename
412  *  [number_of_methods: uleb128] the number of methods in this assembly
413  *  [fully_covered: uleb128] the number of fully covered methods
414  *  [partially_covered: uleb128] the number of partially covered methods
415  *    currently partially_covered will always be 0, and fully_covered is the
416  *    number of methods that are fully and partially covered.
417  * if exinfo == TYPE_COVERAGE_CLASS
418  *  [name: string] assembly name
419  *  [class: string] class name
420  *  [number_of_methods: uleb128] the number of methods in this class
421  *  [fully_covered: uleb128] the number of fully covered methods
422  *  [partially_covered: uleb128] the number of partially covered methods
423  *    currently partially_covered will always be 0, and fully_covered is the
424  *    number of methods that are fully and partially covered.
425  */
426
427 /*
428  * Format oddities that we ought to fix:
429  *
430  * - Methods written in emit_bt () should be based on the buffer's base
431  *   method instead of the base pointer.
432  * - The TYPE_SAMPLE_HIT event contains (currently) pointless data like
433  *   always-one unmanaged frame count and always-zero IL offsets.
434  *
435  * These are mostly small things and are not worth a format change by
436  * themselves. They should be done when some other major change has to
437  * be done to the format.
438  */
439
440 // Pending data to be written to the log, for a single thread.
441 // Threads periodically flush their own LogBuffers by calling safe_send
442 struct _LogBuffer {
443         // Next (older) LogBuffer in processing queue
444         LogBuffer *next;
445
446         uint64_t time_base;
447         uint64_t last_time;
448         uintptr_t ptr_base;
449         uintptr_t method_base;
450         uintptr_t last_method;
451         uintptr_t obj_base;
452         uintptr_t thread_id;
453         int locked;
454         int call_depth;
455
456         // Bytes allocated for this LogBuffer
457         int size;
458
459         // Start of currently unused space in buffer
460         unsigned char* cursor;
461
462         // Pointer to start-of-structure-plus-size (for convenience)
463         unsigned char* buf_end;
464
465         // Start of data in buffer. Contents follow "buffer format" described above.
466         unsigned char buf [1];
467 };
468
469 static inline void
470 ign_res (int G_GNUC_UNUSED unused, ...)
471 {
472 }
473
474 #define ENTER_LOG(lb,str) if ((lb)->locked) {ign_res (write(2, str, strlen(str))); ign_res (write(2, "\n", 1));return;} else {(lb)->locked++;}
475 #define EXIT_LOG(lb) (lb)->locked--;
476
477 typedef struct _BinaryObject BinaryObject;
478
479 struct _BinaryObject {
480         BinaryObject *next;
481         void *addr;
482         char *name;
483 };
484
485 struct _MonoProfiler {
486         FILE* file;
487 #if defined (HAVE_SYS_ZLIB)
488         gzFile gzfile;
489 #endif
490         uint64_t startup_time;
491         int pipe_output;
492         int last_gc_gen_started;
493         int command_port;
494         int server_socket;
495         int pipes [2];
496 #ifndef HOST_WIN32
497         pthread_t helper_thread;
498         pthread_t writer_thread;
499         pthread_t dumper_thread;
500 #endif
501         volatile gint32 run_writer_thread;
502         MonoLockFreeQueue writer_queue;
503         MonoSemType writer_queue_sem;
504         MonoConcurrentHashTable *method_table;
505         mono_mutex_t method_table_mutex;
506         volatile gint32 run_dumper_thread;
507         MonoLockFreeQueue dumper_queue;
508         MonoSemType dumper_queue_sem;
509         MonoLockFreeAllocSizeClass sample_size_class;
510         MonoLockFreeAllocator sample_allocator;
511         MonoLockFreeQueue sample_reuse_queue;
512         BinaryObject *binary_objects;
513         GPtrArray *coverage_filters;
514 };
515
516 typedef struct _WriterQueueEntry WriterQueueEntry;
517 struct _WriterQueueEntry {
518         MonoLockFreeQueueNode node;
519         GPtrArray *methods;
520         LogBuffer *buffer;
521 };
522
523 typedef struct _MethodInfo MethodInfo;
524 struct _MethodInfo {
525         MonoMethod *method;
526         MonoJitInfo *ji;
527         uint64_t time;
528 };
529
530 #ifdef TLS_INIT
531 #undef TLS_INIT
532 #endif
533
534 #ifdef HOST_WIN32
535 #define TLS_SET(x,y) (TlsSetValue (x, y))
536 #define TLS_GET(t,x) ((t *) TlsGetValue (x))
537 #define TLS_INIT(x) (x = TlsAlloc ())
538 static int tlsbuffer;
539 static int tlsmethodlist;
540 #elif HAVE_KW_THREAD
541 #define TLS_SET(x,y) (x = y)
542 #define TLS_GET(t,x) (x)
543 #define TLS_INIT(x)
544 static __thread LogBuffer* tlsbuffer = NULL;
545 static __thread GPtrArray* tlsmethodlist = NULL;
546 #else
547 #define TLS_SET(x,y) (pthread_setspecific (x, y))
548 #define TLS_GET(t,x) ((t *) pthread_getspecific (x))
549 #define TLS_INIT(x) (pthread_key_create (&x, NULL))
550 static pthread_key_t tlsbuffer;
551 static pthread_key_t tlsmethodlist;
552 #endif
553
554 static void safe_send (MonoProfiler *profiler, LogBuffer *logbuffer);
555
556 static char*
557 pstrdup (const char *s)
558 {
559         int len = strlen (s) + 1;
560         char *p = (char *)malloc (len);
561         memcpy (p, s, len);
562         return p;
563 }
564
565 static LogBuffer*
566 create_buffer (void)
567 {
568         LogBuffer* buf = (LogBuffer *)alloc_buffer (BUFFER_SIZE);
569
570         InterlockedIncrement (&buffer_allocations);
571
572         buf->size = BUFFER_SIZE;
573         buf->time_base = current_time ();
574         buf->last_time = buf->time_base;
575         buf->buf_end = (unsigned char*)buf + buf->size;
576         buf->cursor = buf->buf;
577         return buf;
578 }
579
580 static void
581 init_thread (void)
582 {
583         if (!TLS_GET (LogBuffer, tlsbuffer)) {
584                 LogBuffer *logbuffer = create_buffer ();
585                 TLS_SET (tlsbuffer, logbuffer);
586                 logbuffer->thread_id = thread_id ();
587         }
588         if (!TLS_GET (GPtrArray, tlsmethodlist)) {
589                 GPtrArray *methodlist = g_ptr_array_new ();
590                 TLS_SET (tlsmethodlist, methodlist);
591         }
592
593         //printf ("thread %p at time %llu\n", (void*)logbuffer->thread_id, logbuffer->time_base);
594 }
595
596 static LogBuffer *
597 ensure_logbuf_inner (LogBuffer *old, int bytes)
598 {
599         if (old && old->cursor + bytes + 100 < old->buf_end)
600                 return old;
601
602         LogBuffer *new_ = (LogBuffer *)create_buffer ();
603         new_->thread_id = thread_id ();
604         new_->next = old;
605
606         if (old)
607                 new_->call_depth = old->call_depth;
608
609         return new_;
610 }
611
612 static LogBuffer*
613 ensure_logbuf (int bytes)
614 {
615         LogBuffer *old = TLS_GET (LogBuffer, tlsbuffer);
616         LogBuffer *new_ = ensure_logbuf_inner (old, bytes);
617
618         if (new_ == old)
619                 return old; // Still enough space.
620
621         TLS_SET (tlsbuffer, new_);
622         init_thread ();
623
624         return new_;
625 }
626
627 static void
628 emit_byte (LogBuffer *logbuffer, int value)
629 {
630         logbuffer->cursor [0] = value;
631         logbuffer->cursor++;
632         assert (logbuffer->cursor <= logbuffer->buf_end);
633 }
634
635 static void
636 emit_value (LogBuffer *logbuffer, int value)
637 {
638         encode_uleb128 (value, logbuffer->cursor, &logbuffer->cursor);
639         assert (logbuffer->cursor <= logbuffer->buf_end);
640 }
641
642 static void
643 emit_time (LogBuffer *logbuffer, uint64_t value)
644 {
645         uint64_t tdiff = value - logbuffer->last_time;
646         //if (value < logbuffer->last_time)
647         //      printf ("time went backwards\n");
648         //if (tdiff > 1000000)
649         //      printf ("large time offset: %llu\n", tdiff);
650         encode_uleb128 (tdiff, logbuffer->cursor, &logbuffer->cursor);
651         /*if (tdiff != decode_uleb128 (p, &p))
652                 printf ("incorrect encoding: %llu\n", tdiff);*/
653         logbuffer->last_time = value;
654         assert (logbuffer->cursor <= logbuffer->buf_end);
655 }
656
657 static void
658 emit_svalue (LogBuffer *logbuffer, int64_t value)
659 {
660         encode_sleb128 (value, logbuffer->cursor, &logbuffer->cursor);
661         assert (logbuffer->cursor <= logbuffer->buf_end);
662 }
663
664 static void
665 emit_uvalue (LogBuffer *logbuffer, uint64_t value)
666 {
667         encode_uleb128 (value, logbuffer->cursor, &logbuffer->cursor);
668         assert (logbuffer->cursor <= logbuffer->buf_end);
669 }
670
671 static void
672 emit_ptr (LogBuffer *logbuffer, void *ptr)
673 {
674         if (!logbuffer->ptr_base)
675                 logbuffer->ptr_base = (uintptr_t)ptr;
676         emit_svalue (logbuffer, (intptr_t)ptr - logbuffer->ptr_base);
677         assert (logbuffer->cursor <= logbuffer->buf_end);
678 }
679
680 static void
681 emit_method_inner (LogBuffer *logbuffer, void *method)
682 {
683         if (!logbuffer->method_base) {
684                 logbuffer->method_base = (intptr_t)method;
685                 logbuffer->last_method = (intptr_t)method;
686         }
687         encode_sleb128 ((intptr_t)((char*)method - (char*)logbuffer->last_method), logbuffer->cursor, &logbuffer->cursor);
688         logbuffer->last_method = (intptr_t)method;
689         assert (logbuffer->cursor <= logbuffer->buf_end);
690 }
691
692 /*
693 typedef struct {
694         MonoMethod *method;
695         MonoJitInfo *found;
696 } MethodSearch;
697
698 static void
699 find_method (MonoDomain *domain, void *user_data)
700 {
701         MethodSearch *search = user_data;
702
703         if (search->found)
704                 return;
705
706         MonoJitInfo *ji = mono_get_jit_info_from_method (domain, search->method);
707
708         // It could be AOT'd, so we need to get it from the AOT runtime's cache.
709         if (!ji) {
710                 void *ip = mono_aot_get_method (domain, search->method);
711
712                 // Avoid a slow path in mono_jit_info_table_find ().
713                 if (ip)
714                         ji = mono_jit_info_table_find (domain, ip);
715         }
716
717         if (ji)
718                 search->found = ji;
719 }
720 */
721
722 static void
723 register_method_local (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *ji)
724 {
725         if (!mono_conc_hashtable_lookup (prof->method_table, method)) {
726                 /*
727                  * FIXME: In some cases, we crash while looking up JIT info for AOT'd methods.
728                  * This usually happens for static constructors. This code is disabled for now
729                  * as we don't need this info for anything critical.
730                  *
731                  * https://bugzilla.xamarin.com/show_bug.cgi?id=35171
732                  */
733                 /*
734                 if (!ji) {
735                         MethodSearch search = { method, NULL };
736
737                         mono_domain_foreach (find_method, &search);
738
739                         ji = search.found;
740                 }
741                 */
742
743                 /*
744                  * FIXME: We can't always find JIT info for a generic shared method, especially
745                  * if we obtained the MonoMethod during an async stack walk. For now, we deal
746                  * with this by giving the generic shared method name and dummy code start/size
747                  * information (i.e. zeroes).
748                  */
749                 //g_assert (ji);
750
751                 MethodInfo *info = (MethodInfo *)malloc (sizeof (MethodInfo));
752
753                 info->method = method;
754                 info->ji = ji;
755                 info->time = current_time ();
756
757                 g_ptr_array_add (TLS_GET (GPtrArray, tlsmethodlist), info);
758         }
759 }
760
761 static void
762 emit_method (MonoProfiler *prof, LogBuffer *logbuffer, MonoMethod *method)
763 {
764         register_method_local (prof, method, NULL);
765         emit_method_inner (logbuffer, method);
766 }
767
768 static void
769 emit_method_as_ptr (MonoProfiler *prof, LogBuffer *logbuffer, MonoMethod *method)
770 {
771         register_method_local (prof, method, NULL);
772         emit_ptr (logbuffer, method);
773 }
774
775 static void
776 emit_obj (LogBuffer *logbuffer, void *ptr)
777 {
778         if (!logbuffer->obj_base)
779                 logbuffer->obj_base = (uintptr_t)ptr >> 3;
780         emit_svalue (logbuffer, ((uintptr_t)ptr >> 3) - logbuffer->obj_base);
781         assert (logbuffer->cursor <= logbuffer->buf_end);
782 }
783
784 static void
785 emit_string (LogBuffer *logbuffer, const char *str, size_t size)
786 {
787         size_t i = 0;
788         if (str) {
789                 for (; i < size; i++) {
790                         if (str[i] == '\0')
791                                 break;
792                         emit_byte (logbuffer, str [i]);
793                 }
794         }
795         emit_byte (logbuffer, '\0');
796 }
797
798 static void
799 emit_double (LogBuffer *logbuffer, double value)
800 {
801         int i;
802         unsigned char buffer[8];
803         memcpy (buffer, &value, 8);
804 #if G_BYTE_ORDER == G_BIG_ENDIAN
805         for (i = 7; i >= 0; i--)
806 #else
807         for (i = 0; i < 8; i++)
808 #endif
809                 emit_byte (logbuffer, buffer[i]);
810 }
811
812 static char*
813 write_int16 (char *buf, int32_t value)
814 {
815         int i;
816         for (i = 0; i < 2; ++i) {
817                 buf [i] = value;
818                 value >>= 8;
819         }
820         return buf + 2;
821 }
822
823 static char*
824 write_int32 (char *buf, int32_t value)
825 {
826         int i;
827         for (i = 0; i < 4; ++i) {
828                 buf [i] = value;
829                 value >>= 8;
830         }
831         return buf + 4;
832 }
833
834 static char*
835 write_int64 (char *buf, int64_t value)
836 {
837         int i;
838         for (i = 0; i < 8; ++i) {
839                 buf [i] = value;
840                 value >>= 8;
841         }
842         return buf + 8;
843 }
844
845 static void
846 dump_header (MonoProfiler *profiler)
847 {
848         char hbuf [128];
849         char *p = hbuf;
850         p = write_int32 (p, LOG_HEADER_ID);
851         *p++ = LOG_VERSION_MAJOR;
852         *p++ = LOG_VERSION_MINOR;
853         *p++ = LOG_DATA_VERSION;
854         *p++ = sizeof (void*);
855         p = write_int64 (p, ((uint64_t)time (NULL)) * 1000); /* startup time */
856         p = write_int32 (p, get_timer_overhead ()); /* timer overhead */
857         p = write_int32 (p, 0); /* flags */
858         p = write_int32 (p, process_id ()); /* pid */
859         p = write_int16 (p, profiler->command_port); /* port */
860         p = write_int16 (p, 0); /* opsystem */
861 #if defined (HAVE_SYS_ZLIB)
862         if (profiler->gzfile) {
863                 gzwrite (profiler->gzfile, hbuf, p - hbuf);
864         } else {
865                 fwrite (hbuf, p - hbuf, 1, profiler->file);
866         }
867 #else
868         fwrite (hbuf, p - hbuf, 1, profiler->file);
869         fflush (profiler->file);
870 #endif
871 }
872
873 static void
874 send_buffer (MonoProfiler *prof, GPtrArray *methods, LogBuffer *buffer)
875 {
876         WriterQueueEntry *entry = (WriterQueueEntry *)calloc (1, sizeof (WriterQueueEntry));
877         mono_lock_free_queue_node_init (&entry->node, FALSE);
878         entry->methods = methods;
879         entry->buffer = buffer;
880         mono_lock_free_queue_enqueue (&prof->writer_queue, &entry->node);
881         mono_os_sem_post (&prof->writer_queue_sem);
882 }
883
884 static void
885 dump_buffer (MonoProfiler *profiler, LogBuffer *buf)
886 {
887         char hbuf [128];
888         char *p = hbuf;
889         if (buf->next)
890                 dump_buffer (profiler, buf->next);
891         p = write_int32 (p, BUF_ID);
892         p = write_int32 (p, buf->cursor - buf->buf);
893         p = write_int64 (p, buf->time_base);
894         p = write_int64 (p, buf->ptr_base);
895         p = write_int64 (p, buf->obj_base);
896         p = write_int64 (p, buf->thread_id);
897         p = write_int64 (p, buf->method_base);
898 #if defined (HAVE_SYS_ZLIB)
899         if (profiler->gzfile) {
900                 gzwrite (profiler->gzfile, hbuf, p - hbuf);
901                 gzwrite (profiler->gzfile, buf->buf, buf->cursor - buf->buf);
902         } else {
903 #endif
904                 fwrite (hbuf, p - hbuf, 1, profiler->file);
905                 fwrite (buf->buf, buf->cursor - buf->buf, 1, profiler->file);
906                 fflush (profiler->file);
907 #if defined (HAVE_SYS_ZLIB)
908         }
909 #endif
910         free_buffer (buf, buf->size);
911 }
912
913 static void
914 process_requests (MonoProfiler *profiler)
915 {
916         if (heapshot_requested)
917                 mono_gc_collect (mono_gc_max_generation ());
918 }
919
920 static void counters_init (MonoProfiler *profiler);
921 static void counters_sample (MonoProfiler *profiler, uint64_t timestamp, gboolean threadless);
922
923 /*
924  * Can be called only at safe callback locations.
925  */
926 static void
927 safe_send (MonoProfiler *profiler, LogBuffer *logbuffer)
928 {
929         /* We need the runtime initialized so that we have threads and hazard
930          * pointers available. Otherwise, the lock free queue will not work and
931          * there won't be a thread to process the data.
932          *
933          * While the runtime isn't initialized, we just accumulate data in the
934          * thread local buffer list.
935          */
936         if (!InterlockedRead (&runtime_inited))
937                 return;
938
939         int cd = logbuffer->call_depth;
940
941         send_buffer (profiler, TLS_GET (GPtrArray, tlsmethodlist), TLS_GET (LogBuffer, tlsbuffer));
942
943         TLS_SET (tlsbuffer, NULL);
944         TLS_SET (tlsmethodlist, NULL);
945
946         init_thread ();
947
948         TLS_GET (LogBuffer, tlsbuffer)->call_depth = cd;
949 }
950
951 static void
952 safe_send_threadless (MonoProfiler *prof, LogBuffer *buf)
953 {
954         for (LogBuffer *iter = buf; iter; iter = iter->next)
955                 iter->thread_id = 0;
956
957         safe_send (prof, buf);
958 }
959
960 static int
961 gc_reference (MonoObject *obj, MonoClass *klass, uintptr_t size, uintptr_t num, MonoObject **refs, uintptr_t *offsets, void *data)
962 {
963         int i;
964         uintptr_t last_offset = 0;
965         //const char *name = mono_class_get_name (klass);
966         LogBuffer *logbuffer = ensure_logbuf (
967                 EVENT_SIZE /* event */ +
968                 LEB128_SIZE /* obj */ +
969                 LEB128_SIZE /* klass */ +
970                 LEB128_SIZE /* size */ +
971                 LEB128_SIZE /* num */ +
972                 num * (
973                         LEB128_SIZE /* offset */ +
974                         LEB128_SIZE /* ref */
975                 )
976         );
977         emit_byte (logbuffer, TYPE_HEAP_OBJECT | TYPE_HEAP);
978         emit_obj (logbuffer, obj);
979         emit_ptr (logbuffer, klass);
980         /* account for object alignment in the heap */
981         size += 7;
982         size &= ~7;
983         emit_value (logbuffer, size);
984         emit_value (logbuffer, num);
985         for (i = 0; i < num; ++i) {
986                 emit_value (logbuffer, offsets [i] - last_offset);
987                 last_offset = offsets [i];
988                 emit_obj (logbuffer, refs [i]);
989         }
990         //if (num)
991         //      printf ("obj: %p, klass: %s, refs: %d, size: %d\n", obj, name, (int)num, (int)size);
992         return 0;
993 }
994
995 static unsigned int hs_mode_ms = 0;
996 static unsigned int hs_mode_gc = 0;
997 static unsigned int hs_mode_ondemand = 0;
998 static unsigned int gc_count = 0;
999 static uint64_t last_hs_time = 0;
1000
1001 static void
1002 heap_walk (MonoProfiler *profiler)
1003 {
1004         int do_walk = 0;
1005         uint64_t now;
1006         LogBuffer *logbuffer;
1007         if (!do_heap_shot)
1008                 return;
1009         logbuffer = ensure_logbuf (
1010                 EVENT_SIZE /* event */ +
1011                 LEB128_SIZE /* time */
1012         );
1013         now = current_time ();
1014         if (hs_mode_ms && (now - last_hs_time)/1000000 >= hs_mode_ms)
1015                 do_walk = 1;
1016         else if (hs_mode_gc && (gc_count % hs_mode_gc) == 0)
1017                 do_walk = 1;
1018         else if (hs_mode_ondemand)
1019                 do_walk = heapshot_requested;
1020         else if (!hs_mode_ms && !hs_mode_gc && profiler->last_gc_gen_started == mono_gc_max_generation ())
1021                 do_walk = 1;
1022
1023         if (!do_walk)
1024                 return;
1025         heapshot_requested = 0;
1026         emit_byte (logbuffer, TYPE_HEAP_START | TYPE_HEAP);
1027         emit_time (logbuffer, now);
1028         mono_gc_walk_heap (0, gc_reference, NULL);
1029         logbuffer = ensure_logbuf (
1030                 EVENT_SIZE /* event */ +
1031                 LEB128_SIZE /* time */
1032         );
1033         now = current_time ();
1034         emit_byte (logbuffer, TYPE_HEAP_END | TYPE_HEAP);
1035         emit_time (logbuffer, now);
1036         last_hs_time = now;
1037 }
1038
1039 static void
1040 gc_event (MonoProfiler *profiler, MonoGCEvent ev, int generation) {
1041         uint64_t now;
1042         LogBuffer *logbuffer = ensure_logbuf (
1043                 EVENT_SIZE /* event */ +
1044                 LEB128_SIZE /* time */ +
1045                 LEB128_SIZE /* gc event */ +
1046                 LEB128_SIZE /* generation */
1047         );
1048         now = current_time ();
1049         ENTER_LOG (logbuffer, "gcevent");
1050         emit_byte (logbuffer, TYPE_GC_EVENT | TYPE_GC);
1051         emit_time (logbuffer, now);
1052         emit_value (logbuffer, ev);
1053         emit_value (logbuffer, generation);
1054         /* to deal with nested gen1 after gen0 started */
1055         if (ev == MONO_GC_EVENT_START) {
1056                 profiler->last_gc_gen_started = generation;
1057                 if (generation == mono_gc_max_generation ())
1058                         gc_count++;
1059         }
1060         if (ev == MONO_GC_EVENT_PRE_START_WORLD)
1061                 heap_walk (profiler);
1062         EXIT_LOG (logbuffer);
1063         if (ev == MONO_GC_EVENT_POST_START_WORLD)
1064                 safe_send (profiler, logbuffer);
1065         //printf ("gc event %d for generation %d\n", ev, generation);
1066 }
1067
1068 static void
1069 gc_resize (MonoProfiler *profiler, int64_t new_size) {
1070         uint64_t now;
1071         LogBuffer *logbuffer = ensure_logbuf (
1072                 EVENT_SIZE /* event */ +
1073                 LEB128_SIZE /* time */ +
1074                 LEB128_SIZE /* new size */
1075         );
1076         now = current_time ();
1077         ENTER_LOG (logbuffer, "gcresize");
1078         emit_byte (logbuffer, TYPE_GC_RESIZE | TYPE_GC);
1079         emit_time (logbuffer, now);
1080         emit_value (logbuffer, new_size);
1081         //printf ("gc resized to %lld\n", new_size);
1082         EXIT_LOG (logbuffer);
1083 }
1084
1085 // If you alter MAX_FRAMES, you may need to alter SAMPLE_BLOCK_SIZE too.
1086 #define MAX_FRAMES 32
1087
1088 typedef struct {
1089         int count;
1090         MonoMethod* methods [MAX_FRAMES];
1091         int32_t il_offsets [MAX_FRAMES];
1092         int32_t native_offsets [MAX_FRAMES];
1093 } FrameData;
1094
1095 static int num_frames = MAX_FRAMES;
1096
1097 static mono_bool
1098 walk_stack (MonoMethod *method, int32_t native_offset, int32_t il_offset, mono_bool managed, void* data)
1099 {
1100         FrameData *frame = (FrameData *)data;
1101         if (method && frame->count < num_frames) {
1102                 frame->il_offsets [frame->count] = il_offset;
1103                 frame->native_offsets [frame->count] = native_offset;
1104                 frame->methods [frame->count++] = method;
1105                 //printf ("In %d %s at %d (native: %d)\n", frame->count, mono_method_get_name (method), il_offset, native_offset);
1106         }
1107         return frame->count == num_frames;
1108 }
1109
1110 /*
1111  * a note about stack walks: they can cause more profiler events to fire,
1112  * so we need to make sure they don't happen after we started emitting an
1113  * event, hence the collect_bt/emit_bt split.
1114  */
1115 static void
1116 collect_bt (FrameData *data)
1117 {
1118         data->count = 0;
1119         mono_stack_walk_no_il (walk_stack, data);
1120 }
1121
1122 static void
1123 emit_bt (MonoProfiler *prof, LogBuffer *logbuffer, FrameData *data)
1124 {
1125         /* FIXME: this is actually tons of data and we should
1126          * just output it the first time and use an id the next
1127          */
1128         if (data->count > num_frames)
1129                 printf ("bad num frames: %d\n", data->count);
1130         emit_value (logbuffer, 0); /* flags */
1131         emit_value (logbuffer, data->count);
1132         //if (*p != data.count) {
1133         //      printf ("bad num frames enc at %d: %d -> %d\n", count, data.count, *p); printf ("frames end: %p->%p\n", p, logbuffer->cursor); exit(0);}
1134         while (data->count) {
1135                 emit_method_as_ptr (prof, logbuffer, data->methods [--data->count]);
1136         }
1137 }
1138
1139 static void
1140 gc_alloc (MonoProfiler *prof, MonoObject *obj, MonoClass *klass)
1141 {
1142         uint64_t now;
1143         uintptr_t len;
1144         int do_bt = (nocalls && InterlockedRead (&runtime_inited) && !notraces)? TYPE_ALLOC_BT: 0;
1145         FrameData data;
1146         LogBuffer *logbuffer;
1147         len = mono_object_get_size (obj);
1148         /* account for object alignment in the heap */
1149         len += 7;
1150         len &= ~7;
1151         if (do_bt)
1152                 collect_bt (&data);
1153         logbuffer = ensure_logbuf (
1154                 EVENT_SIZE /* event */ +
1155                 LEB128_SIZE /* time */ +
1156                 LEB128_SIZE /* klass */ +
1157                 LEB128_SIZE /* obj */ +
1158                 LEB128_SIZE /* size */ +
1159                 (do_bt ? (
1160                         LEB128_SIZE /* flags */ +
1161                         LEB128_SIZE /* count */ +
1162                         data.count * (
1163                                 LEB128_SIZE /* method */
1164                         )
1165                 ) : 0)
1166         );
1167         now = current_time ();
1168         ENTER_LOG (logbuffer, "gcalloc");
1169         emit_byte (logbuffer, do_bt | TYPE_ALLOC);
1170         emit_time (logbuffer, now);
1171         emit_ptr (logbuffer, klass);
1172         emit_obj (logbuffer, obj);
1173         emit_value (logbuffer, len);
1174         if (do_bt)
1175                 emit_bt (prof, logbuffer, &data);
1176         EXIT_LOG (logbuffer);
1177         if (logbuffer->next)
1178                 safe_send (prof, logbuffer);
1179         process_requests (prof);
1180         //printf ("gc alloc %s at %p\n", mono_class_get_name (klass), obj);
1181 }
1182
1183 static void
1184 gc_moves (MonoProfiler *prof, void **objects, int num)
1185 {
1186         int i;
1187         uint64_t now;
1188         LogBuffer *logbuffer = ensure_logbuf (
1189                 EVENT_SIZE /* event */ +
1190                 LEB128_SIZE /* time */ +
1191                 LEB128_SIZE /* num */ +
1192                 num * (
1193                         LEB128_SIZE /* object */
1194                 )
1195         );
1196         now = current_time ();
1197         ENTER_LOG (logbuffer, "gcmove");
1198         emit_byte (logbuffer, TYPE_GC_MOVE | TYPE_GC);
1199         emit_time (logbuffer, now);
1200         emit_value (logbuffer, num);
1201         for (i = 0; i < num; ++i)
1202                 emit_obj (logbuffer, objects [i]);
1203         //printf ("gc moved %d objects\n", num/2);
1204         EXIT_LOG (logbuffer);
1205 }
1206
1207 static void
1208 gc_roots (MonoProfiler *prof, int num, void **objects, int *root_types, uintptr_t *extra_info)
1209 {
1210         int i;
1211         LogBuffer *logbuffer = ensure_logbuf (
1212                 EVENT_SIZE /* event */ +
1213                 LEB128_SIZE /* num */ +
1214                 LEB128_SIZE /* collections */ +
1215                 num * (
1216                         LEB128_SIZE /* object */ +
1217                         LEB128_SIZE /* root type */ +
1218                         LEB128_SIZE /* extra info */
1219                 )
1220         );
1221         ENTER_LOG (logbuffer, "gcroots");
1222         emit_byte (logbuffer, TYPE_HEAP_ROOT | TYPE_HEAP);
1223         emit_value (logbuffer, num);
1224         emit_value (logbuffer, mono_gc_collection_count (mono_gc_max_generation ()));
1225         for (i = 0; i < num; ++i) {
1226                 emit_obj (logbuffer, objects [i]);
1227                 emit_value (logbuffer, root_types [i]);
1228                 emit_value (logbuffer, extra_info [i]);
1229         }
1230         EXIT_LOG (logbuffer);
1231 }
1232
1233 static void
1234 gc_handle (MonoProfiler *prof, int op, int type, uintptr_t handle, MonoObject *obj)
1235 {
1236         int do_bt = nocalls && InterlockedRead (&runtime_inited) && !notraces;
1237         uint64_t now;
1238         FrameData data;
1239
1240         if (do_bt)
1241                 collect_bt (&data);
1242
1243         LogBuffer *logbuffer = ensure_logbuf (
1244                 EVENT_SIZE /* event */ +
1245                 LEB128_SIZE /* time */ +
1246                 LEB128_SIZE /* type */ +
1247                 LEB128_SIZE /* handle */ +
1248                 (op == MONO_PROFILER_GC_HANDLE_CREATED ? (
1249                         LEB128_SIZE /* obj */
1250                 ) : 0) +
1251                 (do_bt ? (
1252                         LEB128_SIZE /* flags */ +
1253                         LEB128_SIZE /* count */ +
1254                         data.count * (
1255                                 LEB128_SIZE /* method */
1256                         )
1257                 ) : 0)
1258         );
1259
1260         now = current_time ();
1261         ENTER_LOG (logbuffer, "gchandle");
1262
1263         if (op == MONO_PROFILER_GC_HANDLE_CREATED)
1264                 emit_byte (logbuffer, (do_bt ? TYPE_GC_HANDLE_CREATED_BT : TYPE_GC_HANDLE_CREATED) | TYPE_GC);
1265         else if (op == MONO_PROFILER_GC_HANDLE_DESTROYED)
1266                 emit_byte (logbuffer, (do_bt ? TYPE_GC_HANDLE_DESTROYED_BT : TYPE_GC_HANDLE_DESTROYED) | TYPE_GC);
1267         else
1268                 g_assert_not_reached ();
1269
1270         emit_time (logbuffer, now);
1271         emit_value (logbuffer, type);
1272         emit_value (logbuffer, handle);
1273
1274         if (op == MONO_PROFILER_GC_HANDLE_CREATED)
1275                 emit_obj (logbuffer, obj);
1276
1277         if (do_bt)
1278                 emit_bt (prof, logbuffer, &data);
1279
1280         EXIT_LOG (logbuffer);
1281         process_requests (prof);
1282 }
1283
1284 static char*
1285 push_nesting (char *p, MonoClass *klass)
1286 {
1287         MonoClass *nesting;
1288         const char *name;
1289         const char *nspace;
1290         nesting = mono_class_get_nesting_type (klass);
1291         if (nesting) {
1292                 p = push_nesting (p, nesting);
1293                 *p++ = '/';
1294                 *p = 0;
1295         }
1296         name = mono_class_get_name (klass);
1297         nspace = mono_class_get_namespace (klass);
1298         if (*nspace) {
1299                 strcpy (p, nspace);
1300                 p += strlen (nspace);
1301                 *p++ = '.';
1302                 *p = 0;
1303         }
1304         strcpy (p, name);
1305         p += strlen (name);
1306         return p;
1307 }
1308
1309 static char*
1310 type_name (MonoClass *klass)
1311 {
1312         char buf [1024];
1313         char *p;
1314         push_nesting (buf, klass);
1315         p = (char *)malloc (strlen (buf) + 1);
1316         strcpy (p, buf);
1317         return p;
1318 }
1319
1320 static void
1321 image_loaded (MonoProfiler *prof, MonoImage *image, int result)
1322 {
1323         uint64_t now;
1324         const char *name;
1325         int nlen;
1326         LogBuffer *logbuffer;
1327         if (result != MONO_PROFILE_OK)
1328                 return;
1329         name = mono_image_get_filename (image);
1330         nlen = strlen (name) + 1;
1331         logbuffer = ensure_logbuf (
1332                 EVENT_SIZE /* event */ +
1333                 LEB128_SIZE /* time */ +
1334                 EVENT_SIZE /* type */ +
1335                 LEB128_SIZE /* image */ +
1336                 LEB128_SIZE /* flags */ +
1337                 nlen /* name */
1338         );
1339         now = current_time ();
1340         ENTER_LOG (logbuffer, "image");
1341         emit_byte (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1342         emit_time (logbuffer, now);
1343         emit_byte (logbuffer, TYPE_IMAGE);
1344         emit_ptr (logbuffer, image);
1345         emit_value (logbuffer, 0); /* flags */
1346         memcpy (logbuffer->cursor, name, nlen);
1347         logbuffer->cursor += nlen;
1348         //printf ("loaded image %p (%s)\n", image, name);
1349         EXIT_LOG (logbuffer);
1350         if (logbuffer->next)
1351                 safe_send (prof, logbuffer);
1352         process_requests (prof);
1353
1354         InterlockedIncrement (&image_loads);
1355 }
1356
1357 static void
1358 image_unloaded (MonoProfiler *prof, MonoImage *image)
1359 {
1360         const char *name = mono_image_get_filename (image);
1361         int nlen = strlen (name) + 1;
1362         LogBuffer *logbuffer = ensure_logbuf (
1363                 EVENT_SIZE /* event */ +
1364                 LEB128_SIZE /* time */ +
1365                 EVENT_SIZE /* type */ +
1366                 LEB128_SIZE /* image */ +
1367                 LEB128_SIZE /* flags */ +
1368                 nlen /* name */
1369         );
1370         uint64_t now = current_time ();
1371
1372         ENTER_LOG (logbuffer, "image-unload");
1373         emit_byte (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
1374         emit_time (logbuffer, now);
1375         emit_byte (logbuffer, TYPE_IMAGE);
1376         emit_ptr (logbuffer, image);
1377         emit_value (logbuffer, 0); /* flags */
1378         memcpy (logbuffer->cursor, name, nlen);
1379         logbuffer->cursor += nlen;
1380         EXIT_LOG (logbuffer);
1381
1382         if (logbuffer->next)
1383                 safe_send (prof, logbuffer);
1384
1385         process_requests (prof);
1386
1387         InterlockedIncrement (&image_unloads);
1388 }
1389
1390 static void
1391 assembly_loaded (MonoProfiler *prof, MonoAssembly *assembly, int result)
1392 {
1393         if (result != MONO_PROFILE_OK)
1394                 return;
1395
1396         char *name = mono_stringify_assembly_name (mono_assembly_get_name (assembly));
1397         int nlen = strlen (name) + 1;
1398         LogBuffer *logbuffer = ensure_logbuf (
1399                 EVENT_SIZE /* event */ +
1400                 LEB128_SIZE /* time */ +
1401                 EVENT_SIZE /* type */ +
1402                 LEB128_SIZE /* assembly */ +
1403                 LEB128_SIZE /* flags */ +
1404                 nlen /* name */
1405         );
1406         uint64_t now = current_time ();
1407
1408         ENTER_LOG (logbuffer, "assembly-load");
1409         emit_byte (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1410         emit_time (logbuffer, now);
1411         emit_byte (logbuffer, TYPE_ASSEMBLY);
1412         emit_ptr (logbuffer, assembly);
1413         emit_value (logbuffer, 0); /* flags */
1414         memcpy (logbuffer->cursor, name, nlen);
1415         logbuffer->cursor += nlen;
1416         EXIT_LOG (logbuffer);
1417
1418         mono_free (name);
1419
1420         if (logbuffer->next)
1421                 safe_send (prof, logbuffer);
1422
1423         process_requests (prof);
1424
1425         InterlockedIncrement (&assembly_loads);
1426 }
1427
1428 static void
1429 assembly_unloaded (MonoProfiler *prof, MonoAssembly *assembly)
1430 {
1431         char *name = mono_stringify_assembly_name (mono_assembly_get_name (assembly));
1432         int nlen = strlen (name) + 1;
1433         LogBuffer *logbuffer = ensure_logbuf (
1434                 EVENT_SIZE /* event */ +
1435                 LEB128_SIZE /* time */ +
1436                 EVENT_SIZE /* type */ +
1437                 LEB128_SIZE /* assembly */ +
1438                 LEB128_SIZE /* flags */ +
1439                 nlen /* name */
1440         );
1441         uint64_t now = current_time ();
1442
1443         ENTER_LOG (logbuffer, "assembly-unload");
1444         emit_byte (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
1445         emit_time (logbuffer, now);
1446         emit_byte (logbuffer, TYPE_ASSEMBLY);
1447         emit_ptr (logbuffer, assembly);
1448         emit_value (logbuffer, 0); /* flags */
1449         memcpy (logbuffer->cursor, name, nlen);
1450         logbuffer->cursor += nlen;
1451         EXIT_LOG (logbuffer);
1452
1453         mono_free (name);
1454
1455         if (logbuffer->next)
1456                 safe_send (prof, logbuffer);
1457
1458         process_requests (prof);
1459
1460         InterlockedIncrement (&assembly_unloads);
1461 }
1462
1463 static void
1464 class_loaded (MonoProfiler *prof, MonoClass *klass, int result)
1465 {
1466         uint64_t now;
1467         char *name;
1468         int nlen;
1469         MonoImage *image;
1470         LogBuffer *logbuffer;
1471         if (result != MONO_PROFILE_OK)
1472                 return;
1473         if (InterlockedRead (&runtime_inited))
1474                 name = mono_type_get_name (mono_class_get_type (klass));
1475         else
1476                 name = type_name (klass);
1477         nlen = strlen (name) + 1;
1478         image = mono_class_get_image (klass);
1479         logbuffer = ensure_logbuf (
1480                 EVENT_SIZE /* event */ +
1481                 LEB128_SIZE /* time */ +
1482                 EVENT_SIZE /* type */ +
1483                 LEB128_SIZE /* klass */ +
1484                 LEB128_SIZE /* image */ +
1485                 LEB128_SIZE /* flags */ +
1486                 nlen /* name */
1487         );
1488         now = current_time ();
1489         ENTER_LOG (logbuffer, "class");
1490         emit_byte (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1491         emit_time (logbuffer, now);
1492         emit_byte (logbuffer, TYPE_CLASS);
1493         emit_ptr (logbuffer, klass);
1494         emit_ptr (logbuffer, image);
1495         emit_value (logbuffer, 0); /* flags */
1496         memcpy (logbuffer->cursor, name, nlen);
1497         logbuffer->cursor += nlen;
1498         //printf ("loaded class %p (%s)\n", klass, name);
1499         if (runtime_inited)
1500                 mono_free (name);
1501         else
1502                 free (name);
1503         EXIT_LOG (logbuffer);
1504         if (logbuffer->next)
1505                 safe_send (prof, logbuffer);
1506         process_requests (prof);
1507
1508         InterlockedIncrement (&class_loads);
1509 }
1510
1511 static void
1512 class_unloaded (MonoProfiler *prof, MonoClass *klass)
1513 {
1514         char *name;
1515
1516         if (InterlockedRead (&runtime_inited))
1517                 name = mono_type_get_name (mono_class_get_type (klass));
1518         else
1519                 name = type_name (klass);
1520
1521         int nlen = strlen (name) + 1;
1522         MonoImage *image = mono_class_get_image (klass);
1523         LogBuffer *logbuffer = ensure_logbuf (
1524                 EVENT_SIZE /* event */ +
1525                 LEB128_SIZE /* time */ +
1526                 EVENT_SIZE /* type */ +
1527                 LEB128_SIZE /* klass */ +
1528                 LEB128_SIZE /* image */ +
1529                 LEB128_SIZE /* flags */ +
1530                 nlen /* name */
1531         );
1532         uint64_t now = current_time ();
1533
1534         ENTER_LOG (logbuffer, "class-unload");
1535         emit_byte (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
1536         emit_time (logbuffer, now);
1537         emit_byte (logbuffer, TYPE_CLASS);
1538         emit_ptr (logbuffer, klass);
1539         emit_ptr (logbuffer, image);
1540         emit_value (logbuffer, 0); /* flags */
1541         memcpy (logbuffer->cursor, name, nlen);
1542         logbuffer->cursor += nlen;
1543         EXIT_LOG (logbuffer);
1544
1545         if (runtime_inited)
1546                 mono_free (name);
1547         else
1548                 free (name);
1549
1550         if (logbuffer->next)
1551                 safe_send (prof, logbuffer);
1552
1553         process_requests (prof);
1554
1555         InterlockedIncrement (&class_unloads);
1556 }
1557
1558 #ifndef DISABLE_HELPER_THREAD
1559 static void process_method_enter_coverage (MonoProfiler *prof, MonoMethod *method);
1560 #endif /* DISABLE_HELPER_THREAD */
1561
1562 static void
1563 method_enter (MonoProfiler *prof, MonoMethod *method)
1564 {
1565         uint64_t now = current_time ();
1566
1567 #ifndef DISABLE_HELPER_THREAD
1568         process_method_enter_coverage (prof, method);
1569 #endif /* DISABLE_HELPER_THREAD */
1570
1571         LogBuffer *logbuffer = ensure_logbuf (
1572                 EVENT_SIZE /* event */ +
1573                 LEB128_SIZE /* time */ +
1574                 LEB128_SIZE /* method */
1575         );
1576         if (logbuffer->call_depth++ > max_call_depth)
1577                 return;
1578         ENTER_LOG (logbuffer, "enter");
1579         emit_byte (logbuffer, TYPE_ENTER | TYPE_METHOD);
1580         emit_time (logbuffer, now);
1581         emit_method (prof, logbuffer, method);
1582         EXIT_LOG (logbuffer);
1583
1584         process_requests (prof);
1585 }
1586
1587 static void
1588 method_leave (MonoProfiler *prof, MonoMethod *method)
1589 {
1590         uint64_t now;
1591         LogBuffer *logbuffer = ensure_logbuf (
1592                 EVENT_SIZE /* event */ +
1593                 LEB128_SIZE /* time */ +
1594                 LEB128_SIZE /* method */
1595         );
1596         if (--logbuffer->call_depth > max_call_depth)
1597                 return;
1598         now = current_time ();
1599         ENTER_LOG (logbuffer, "leave");
1600         emit_byte (logbuffer, TYPE_LEAVE | TYPE_METHOD);
1601         emit_time (logbuffer, now);
1602         emit_method (prof, logbuffer, method);
1603         EXIT_LOG (logbuffer);
1604         if (logbuffer->next)
1605                 safe_send (prof, logbuffer);
1606         process_requests (prof);
1607 }
1608
1609 static void
1610 method_exc_leave (MonoProfiler *prof, MonoMethod *method)
1611 {
1612         uint64_t now;
1613         LogBuffer *logbuffer;
1614         if (nocalls)
1615                 return;
1616         logbuffer = ensure_logbuf (
1617                 EVENT_SIZE /* event */ +
1618                 LEB128_SIZE /* time */ +
1619                 LEB128_SIZE /* method */
1620         );
1621         if (--logbuffer->call_depth > max_call_depth)
1622                 return;
1623         now = current_time ();
1624         ENTER_LOG (logbuffer, "eleave");
1625         emit_byte (logbuffer, TYPE_EXC_LEAVE | TYPE_METHOD);
1626         emit_time (logbuffer, now);
1627         emit_method (prof, logbuffer, method);
1628         EXIT_LOG (logbuffer);
1629         process_requests (prof);
1630 }
1631
1632 static void
1633 method_jitted (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *ji, int result)
1634 {
1635         if (result != MONO_PROFILE_OK)
1636                 return;
1637
1638         register_method_local (prof, method, ji);
1639
1640         process_requests (prof);
1641 }
1642
1643 static void
1644 code_buffer_new (MonoProfiler *prof, void *buffer, int size, MonoProfilerCodeBufferType type, void *data)
1645 {
1646         uint64_t now;
1647         int nlen;
1648         char *name;
1649         LogBuffer *logbuffer;
1650         if (type == MONO_PROFILER_CODE_BUFFER_SPECIFIC_TRAMPOLINE) {
1651                 name = (char *)data;
1652                 nlen = strlen (name) + 1;
1653         } else {
1654                 name = NULL;
1655                 nlen = 0;
1656         }
1657         logbuffer = ensure_logbuf (
1658                 EVENT_SIZE /* event */ +
1659                 LEB128_SIZE /* time */ +
1660                 LEB128_SIZE /* type */ +
1661                 LEB128_SIZE /* buffer */ +
1662                 LEB128_SIZE /* size */ +
1663                 (name ? (
1664                         nlen /* name */
1665                 ) : 0)
1666         );
1667         now = current_time ();
1668         ENTER_LOG (logbuffer, "code buffer");
1669         emit_byte (logbuffer, TYPE_JITHELPER | TYPE_RUNTIME);
1670         emit_time (logbuffer, now);
1671         emit_value (logbuffer, type);
1672         emit_ptr (logbuffer, buffer);
1673         emit_value (logbuffer, size);
1674         if (name) {
1675                 memcpy (logbuffer->cursor, name, nlen);
1676                 logbuffer->cursor += nlen;
1677         }
1678         EXIT_LOG (logbuffer);
1679         process_requests (prof);
1680 }
1681
1682 static void
1683 throw_exc (MonoProfiler *prof, MonoObject *object)
1684 {
1685         int do_bt = (nocalls && InterlockedRead (&runtime_inited) && !notraces)? TYPE_EXCEPTION_BT: 0;
1686         uint64_t now;
1687         FrameData data;
1688         LogBuffer *logbuffer;
1689         if (do_bt)
1690                 collect_bt (&data);
1691         logbuffer = ensure_logbuf (
1692                 EVENT_SIZE /* event */ +
1693                 LEB128_SIZE /* time */ +
1694                 LEB128_SIZE /* object */ +
1695                 (do_bt ? (
1696                         LEB128_SIZE /* flags */ +
1697                         LEB128_SIZE /* count */ +
1698                         data.count * (
1699                                 LEB128_SIZE /* method */
1700                         )
1701                 ) : 0)
1702         );
1703         now = current_time ();
1704         ENTER_LOG (logbuffer, "throw");
1705         emit_byte (logbuffer, do_bt | TYPE_EXCEPTION);
1706         emit_time (logbuffer, now);
1707         emit_obj (logbuffer, object);
1708         if (do_bt)
1709                 emit_bt (prof, logbuffer, &data);
1710         EXIT_LOG (logbuffer);
1711         process_requests (prof);
1712 }
1713
1714 static void
1715 clause_exc (MonoProfiler *prof, MonoMethod *method, int clause_type, int clause_num)
1716 {
1717         uint64_t now;
1718         LogBuffer *logbuffer = ensure_logbuf (
1719                 EVENT_SIZE /* event */ +
1720                 LEB128_SIZE /* time */ +
1721                 LEB128_SIZE /* clause type */ +
1722                 LEB128_SIZE /* clause num */ +
1723                 LEB128_SIZE /* method */
1724         );
1725         now = current_time ();
1726         ENTER_LOG (logbuffer, "clause");
1727         emit_byte (logbuffer, TYPE_EXCEPTION | TYPE_CLAUSE);
1728         emit_time (logbuffer, now);
1729         emit_value (logbuffer, clause_type);
1730         emit_value (logbuffer, clause_num);
1731         emit_method (prof, logbuffer, method);
1732         EXIT_LOG (logbuffer);
1733
1734         process_requests (prof);
1735 }
1736
1737 static void
1738 monitor_event (MonoProfiler *profiler, MonoObject *object, MonoProfilerMonitorEvent event)
1739 {
1740         int do_bt = (nocalls && InterlockedRead (&runtime_inited) && !notraces && event == MONO_PROFILER_MONITOR_CONTENTION)? TYPE_MONITOR_BT: 0;
1741         uint64_t now;
1742         FrameData data;
1743         LogBuffer *logbuffer;
1744         if (do_bt)
1745                 collect_bt (&data);
1746         logbuffer = ensure_logbuf (
1747                 EVENT_SIZE /* event */ +
1748                 LEB128_SIZE /* time */ +
1749                 LEB128_SIZE /* object */ +
1750                 (do_bt ? (
1751                         LEB128_SIZE /* flags */ +
1752                         LEB128_SIZE /* count */ +
1753                         data.count * (
1754                                 LEB128_SIZE /* method */
1755                         )
1756                 ) : 0)
1757         );
1758         now = current_time ();
1759         ENTER_LOG (logbuffer, "monitor");
1760         emit_byte (logbuffer, (event << 4) | do_bt | TYPE_MONITOR);
1761         emit_time (logbuffer, now);
1762         emit_obj (logbuffer, object);
1763         if (do_bt)
1764                 emit_bt (profiler, logbuffer, &data);
1765         EXIT_LOG (logbuffer);
1766         process_requests (profiler);
1767 }
1768
1769 static void
1770 thread_start (MonoProfiler *prof, uintptr_t tid)
1771 {
1772         //printf ("thread start %p\n", (void*)tid);
1773         init_thread ();
1774
1775         LogBuffer *logbuffer = ensure_logbuf (
1776                 EVENT_SIZE /* event */ +
1777                 LEB128_SIZE /* time */ +
1778                 EVENT_SIZE /* type */ +
1779                 LEB128_SIZE /* tid */ +
1780                 LEB128_SIZE /* flags */
1781         );
1782         uint64_t now = current_time ();
1783
1784         ENTER_LOG (logbuffer, "thread-start");
1785         emit_byte (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1786         emit_time (logbuffer, now);
1787         emit_byte (logbuffer, TYPE_THREAD);
1788         emit_ptr (logbuffer, (void*) tid);
1789         emit_value (logbuffer, 0); /* flags */
1790         EXIT_LOG (logbuffer);
1791
1792         if (logbuffer->next)
1793                 safe_send (prof, logbuffer);
1794
1795         process_requests (prof);
1796
1797         InterlockedIncrement (&thread_starts);
1798 }
1799
1800 static void
1801 thread_end (MonoProfiler *prof, uintptr_t tid)
1802 {
1803         if (TLS_GET (LogBuffer, tlsbuffer)) {
1804                 LogBuffer *logbuffer = ensure_logbuf (
1805                         EVENT_SIZE /* event */ +
1806                         LEB128_SIZE /* time */ +
1807                         EVENT_SIZE /* type */ +
1808                         LEB128_SIZE /* tid */ +
1809                         LEB128_SIZE /* flags */
1810                 );
1811                 uint64_t now = current_time ();
1812
1813                 ENTER_LOG (logbuffer, "thread-end");
1814                 emit_byte (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
1815                 emit_time (logbuffer, now);
1816                 emit_byte (logbuffer, TYPE_THREAD);
1817                 emit_ptr (logbuffer, (void*) tid);
1818                 emit_value (logbuffer, 0); /* flags */
1819                 EXIT_LOG (logbuffer);
1820
1821                 send_buffer (prof, TLS_GET (GPtrArray, tlsmethodlist), logbuffer);
1822
1823                 /* Don't process requests as the thread is detached from the runtime. */
1824         }
1825
1826         TLS_SET (tlsbuffer, NULL);
1827         TLS_SET (tlsmethodlist, NULL);
1828
1829         InterlockedIncrement (&thread_ends);
1830 }
1831
1832 static void
1833 domain_loaded (MonoProfiler *prof, MonoDomain *domain, int result)
1834 {
1835         if (result != MONO_PROFILE_OK)
1836                 return;
1837
1838         LogBuffer *logbuffer = ensure_logbuf (
1839                 EVENT_SIZE /* event */ +
1840                 LEB128_SIZE /* time */ +
1841                 EVENT_SIZE /* type */ +
1842                 LEB128_SIZE /* domain id */ +
1843                 LEB128_SIZE /* flags */
1844         );
1845         uint64_t now = current_time ();
1846
1847         ENTER_LOG (logbuffer, "domain-start");
1848         emit_byte (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1849         emit_time (logbuffer, now);
1850         emit_byte (logbuffer, TYPE_DOMAIN);
1851         emit_ptr (logbuffer, (void*)(uintptr_t) mono_domain_get_id (domain));
1852         emit_value (logbuffer, 0); /* flags */
1853         EXIT_LOG (logbuffer);
1854
1855         if (logbuffer->next)
1856                 safe_send (prof, logbuffer);
1857
1858         process_requests (prof);
1859
1860         InterlockedIncrement (&domain_loads);
1861 }
1862
1863 static void
1864 domain_unloaded (MonoProfiler *prof, MonoDomain *domain)
1865 {
1866         LogBuffer *logbuffer = ensure_logbuf (
1867                 EVENT_SIZE /* event */ +
1868                 LEB128_SIZE /* time */ +
1869                 EVENT_SIZE /* type */ +
1870                 LEB128_SIZE /* domain id */ +
1871                 LEB128_SIZE /* flags */
1872         );
1873         uint64_t now = current_time ();
1874
1875         ENTER_LOG (logbuffer, "domain-end");
1876         emit_byte (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
1877         emit_time (logbuffer, now);
1878         emit_byte (logbuffer, TYPE_DOMAIN);
1879         emit_ptr (logbuffer, (void*)(uintptr_t) mono_domain_get_id (domain));
1880         emit_value (logbuffer, 0); /* flags */
1881         EXIT_LOG (logbuffer);
1882
1883         if (logbuffer->next)
1884                 safe_send (prof, logbuffer);
1885
1886         process_requests (prof);
1887
1888         InterlockedIncrement (&domain_unloads);
1889 }
1890
1891 static void
1892 domain_name (MonoProfiler *prof, MonoDomain *domain, const char *name)
1893 {
1894         int nlen = strlen (name) + 1;
1895         LogBuffer *logbuffer = ensure_logbuf (
1896                 EVENT_SIZE /* event */ +
1897                 LEB128_SIZE /* time */ +
1898                 EVENT_SIZE /* type */ +
1899                 LEB128_SIZE /* domain id */ +
1900                 LEB128_SIZE /* flags */ +
1901                 nlen /* name */
1902         );
1903         uint64_t now = current_time ();
1904
1905         ENTER_LOG (logbuffer, "domain-name");
1906         emit_byte (logbuffer, TYPE_METADATA);
1907         emit_time (logbuffer, now);
1908         emit_byte (logbuffer, TYPE_DOMAIN);
1909         emit_ptr (logbuffer, (void*)(uintptr_t) mono_domain_get_id (domain));
1910         emit_value (logbuffer, 0); /* flags */
1911         memcpy (logbuffer->cursor, name, nlen);
1912         logbuffer->cursor += nlen;
1913         EXIT_LOG (logbuffer);
1914
1915         if (logbuffer->next)
1916                 safe_send (prof, logbuffer);
1917
1918         process_requests (prof);
1919 }
1920
1921 static void
1922 context_loaded (MonoProfiler *prof, MonoAppContext *context)
1923 {
1924         LogBuffer *logbuffer = ensure_logbuf (
1925                 EVENT_SIZE /* event */ +
1926                 LEB128_SIZE /* time */ +
1927                 EVENT_SIZE /* type */ +
1928                 LEB128_SIZE /* context id */ +
1929                 LEB128_SIZE /* flags */ +
1930                 LEB128_SIZE /* domain id */
1931         );
1932         uint64_t now = current_time ();
1933
1934         ENTER_LOG (logbuffer, "context-start");
1935         emit_byte (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1936         emit_time (logbuffer, now);
1937         emit_byte (logbuffer, TYPE_CONTEXT);
1938         emit_ptr (logbuffer, (void*)(uintptr_t) mono_context_get_id (context));
1939         emit_value (logbuffer, 0); /* flags */
1940         emit_ptr (logbuffer, (void*)(uintptr_t) mono_context_get_domain_id (context));
1941         EXIT_LOG (logbuffer);
1942
1943         if (logbuffer->next)
1944                 safe_send (prof, logbuffer);
1945
1946         process_requests (prof);
1947
1948         InterlockedIncrement (&context_loads);
1949 }
1950
1951 static void
1952 context_unloaded (MonoProfiler *prof, MonoAppContext *context)
1953 {
1954         LogBuffer *logbuffer = ensure_logbuf (
1955                 EVENT_SIZE /* event */ +
1956                 LEB128_SIZE /* time */ +
1957                 EVENT_SIZE /* type */ +
1958                 LEB128_SIZE /* context id */ +
1959                 LEB128_SIZE /* flags */ +
1960                 LEB128_SIZE /* domain id */
1961         );
1962         uint64_t now = current_time ();
1963
1964         ENTER_LOG (logbuffer, "context-end");
1965         emit_byte (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
1966         emit_time (logbuffer, now);
1967         emit_byte (logbuffer, TYPE_CONTEXT);
1968         emit_ptr (logbuffer, (void*)(uintptr_t) mono_context_get_id (context));
1969         emit_value (logbuffer, 0); /* flags */
1970         emit_ptr (logbuffer, (void*)(uintptr_t) mono_context_get_domain_id (context));
1971         EXIT_LOG (logbuffer);
1972
1973         if (logbuffer->next)
1974                 safe_send (prof, logbuffer);
1975
1976         process_requests (prof);
1977
1978         InterlockedIncrement (&context_unloads);
1979 }
1980
1981 static void
1982 thread_name (MonoProfiler *prof, uintptr_t tid, const char *name)
1983 {
1984         int len = strlen (name) + 1;
1985         uint64_t now;
1986         LogBuffer *logbuffer;
1987         logbuffer = ensure_logbuf (
1988                 EVENT_SIZE /* event */ +
1989                 LEB128_SIZE /* time */ +
1990                 EVENT_SIZE /* type */ +
1991                 LEB128_SIZE /* tid */ +
1992                 LEB128_SIZE /* flags */ +
1993                 len /* name */
1994         );
1995         now = current_time ();
1996         ENTER_LOG (logbuffer, "tname");
1997         emit_byte (logbuffer, TYPE_METADATA);
1998         emit_time (logbuffer, now);
1999         emit_byte (logbuffer, TYPE_THREAD);
2000         emit_ptr (logbuffer, (void*)tid);
2001         emit_value (logbuffer, 0); /* flags */
2002         memcpy (logbuffer->cursor, name, len);
2003         logbuffer->cursor += len;
2004         EXIT_LOG (logbuffer);
2005
2006         if (logbuffer->next)
2007                 safe_send (prof, logbuffer);
2008
2009         process_requests (prof);
2010 }
2011
2012 typedef struct {
2013         MonoMethod *method;
2014         MonoDomain *domain;
2015         void *base_address;
2016         int offset;
2017 } AsyncFrameInfo;
2018
2019 typedef struct {
2020         MonoLockFreeQueueNode node;
2021         MonoProfiler *prof;
2022         uint64_t elapsed;
2023         uintptr_t tid;
2024         void *ip;
2025         int count;
2026         AsyncFrameInfo frames [MONO_ZERO_LEN_ARRAY];
2027 } SampleHit;
2028
2029 static mono_bool
2030 async_walk_stack (MonoMethod *method, MonoDomain *domain, void *base_address, int offset, void *data)
2031 {
2032         SampleHit *sample = (SampleHit *) data;
2033
2034         if (sample->count < num_frames) {
2035                 int i = sample->count;
2036
2037                 sample->frames [i].method = method;
2038                 sample->frames [i].domain = domain;
2039                 sample->frames [i].base_address = base_address;
2040                 sample->frames [i].offset = offset;
2041
2042                 sample->count++;
2043         }
2044
2045         return sample->count == num_frames;
2046 }
2047
2048 #define SAMPLE_SLOT_SIZE(FRAMES) (sizeof (SampleHit) + sizeof (AsyncFrameInfo) * (FRAMES - MONO_ZERO_LEN_ARRAY))
2049 #define SAMPLE_BLOCK_SIZE (mono_pagesize ())
2050
2051 static void
2052 enqueue_sample_hit (gpointer p)
2053 {
2054         SampleHit *sample = p;
2055
2056         mono_lock_free_queue_node_unpoison (&sample->node);
2057         mono_lock_free_queue_enqueue (&sample->prof->dumper_queue, &sample->node);
2058         mono_os_sem_post (&sample->prof->dumper_queue_sem);
2059
2060         InterlockedIncrement (&sample_flushes);
2061 }
2062
2063 static void
2064 mono_sample_hit (MonoProfiler *profiler, unsigned char *ip, void *context)
2065 {
2066         /*
2067          * Please note: We rely on the runtime loading the profiler with
2068          * MONO_DL_EAGER (RTLD_NOW) so that references to runtime functions within
2069          * this function (and its siblings) are resolved when the profiler is
2070          * loaded. Otherwise, we would potentially invoke the dynamic linker when
2071          * invoking runtime functions, which is not async-signal-safe.
2072          */
2073
2074         if (in_shutdown)
2075                 return;
2076
2077         InterlockedIncrement (&sample_hits);
2078
2079         uint64_t now = current_time ();
2080
2081         SampleHit *sample = (SampleHit *) mono_lock_free_queue_dequeue (&profiler->sample_reuse_queue);
2082
2083         if (!sample) {
2084                 /*
2085                  * If we're out of reusable sample events and we're not allowed to
2086                  * allocate more, we have no choice but to drop the event.
2087                  */
2088                 if (InterlockedRead (&sample_allocations) >= max_allocated_sample_hits)
2089                         return;
2090
2091                 sample = mono_lock_free_alloc (&profiler->sample_allocator);
2092                 sample->prof = profiler;
2093
2094                 InterlockedIncrement (&sample_allocations);
2095         }
2096
2097         mono_lock_free_queue_node_init (&sample->node, TRUE);
2098
2099         sample->count = 0;
2100         mono_stack_walk_async_safe (&async_walk_stack, context, sample);
2101
2102         uintptr_t elapsed = (now - profiler->startup_time) / 10000;
2103
2104         sample->elapsed = elapsed;
2105         sample->tid = thread_id ();
2106         sample->ip = ip;
2107
2108         if (do_debug) {
2109                 int len;
2110                 char buf [256];
2111                 snprintf (buf, sizeof (buf), "hit at %p in thread %p after %llu ms\n", ip, (void *) thread_id (), (unsigned long long int) elapsed / 100);
2112                 len = strlen (buf);
2113                 ign_res (write (2, buf, len));
2114         }
2115
2116         mono_thread_hazardous_try_free (sample, enqueue_sample_hit);
2117 }
2118
2119 static uintptr_t *code_pages = 0;
2120 static int num_code_pages = 0;
2121 static int size_code_pages = 0;
2122 #define CPAGE_SHIFT (9)
2123 #define CPAGE_SIZE (1 << CPAGE_SHIFT)
2124 #define CPAGE_MASK (~(CPAGE_SIZE - 1))
2125 #define CPAGE_ADDR(p) ((p) & CPAGE_MASK)
2126
2127 static uintptr_t
2128 add_code_page (uintptr_t *hash, uintptr_t hsize, uintptr_t page)
2129 {
2130         uintptr_t i;
2131         uintptr_t start_pos;
2132         start_pos = (page >> CPAGE_SHIFT) % hsize;
2133         i = start_pos;
2134         do {
2135                 if (hash [i] && CPAGE_ADDR (hash [i]) == CPAGE_ADDR (page)) {
2136                         return 0;
2137                 } else if (!hash [i]) {
2138                         hash [i] = page;
2139                         return 1;
2140                 }
2141                 /* wrap around */
2142                 if (++i == hsize)
2143                         i = 0;
2144         } while (i != start_pos);
2145         /* should not happen */
2146         printf ("failed code page store\n");
2147         return 0;
2148 }
2149
2150 static void
2151 add_code_pointer (uintptr_t ip)
2152 {
2153         uintptr_t i;
2154         if (num_code_pages * 2 >= size_code_pages) {
2155                 uintptr_t *n;
2156                 uintptr_t old_size = size_code_pages;
2157                 size_code_pages *= 2;
2158                 if (size_code_pages == 0)
2159                         size_code_pages = 16;
2160                 n = (uintptr_t *)calloc (sizeof (uintptr_t) * size_code_pages, 1);
2161                 for (i = 0; i < old_size; ++i) {
2162                         if (code_pages [i])
2163                                 add_code_page (n, size_code_pages, code_pages [i]);
2164                 }
2165                 if (code_pages)
2166                         free (code_pages);
2167                 code_pages = n;
2168         }
2169         num_code_pages += add_code_page (code_pages, size_code_pages, ip & CPAGE_MASK);
2170 }
2171
2172 /* ELF code crashes on some systems. */
2173 //#if defined(HAVE_DL_ITERATE_PHDR) && defined(ELFMAG0)
2174 #if 0
2175 static void
2176 dump_ubin (const char *filename, uintptr_t load_addr, uint64_t offset, uintptr_t size)
2177 {
2178         uint64_t now;
2179         LogBuffer *logbuffer;
2180         int len;
2181         len = strlen (filename) + 1;
2182         now = current_time ();
2183         logbuffer = ensure_logbuf (
2184                 EVENT_SIZE /* event */ +
2185                 LEB128_SIZE /* time */ +
2186                 LEB128_SIZE /* load address */ +
2187                 LEB128_SIZE /* offset */ +
2188                 LEB128_SIZE /* size */ +
2189                 nlen /* file name */
2190         );
2191         emit_byte (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_UBIN);
2192         emit_time (logbuffer, now);
2193         emit_svalue (logbuffer, load_addr);
2194         emit_uvalue (logbuffer, offset);
2195         emit_uvalue (logbuffer, size);
2196         memcpy (logbuffer->cursor, filename, len);
2197         logbuffer->cursor += len;
2198 }
2199 #endif
2200
2201 static void
2202 dump_usym (const char *name, uintptr_t value, uintptr_t size)
2203 {
2204         LogBuffer *logbuffer;
2205         int len;
2206         len = strlen (name) + 1;
2207         logbuffer = ensure_logbuf (
2208                 EVENT_SIZE /* event */ +
2209                 LEB128_SIZE /* value */ +
2210                 LEB128_SIZE /* size */ +
2211                 len /* name */
2212         );
2213         emit_byte (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_USYM);
2214         emit_ptr (logbuffer, (void*)value);
2215         emit_value (logbuffer, size);
2216         memcpy (logbuffer->cursor, name, len);
2217         logbuffer->cursor += len;
2218 }
2219
2220 /* ELF code crashes on some systems. */
2221 //#if defined(ELFMAG0)
2222 #if 0
2223
2224 #if SIZEOF_VOID_P == 4
2225 #define ELF_WSIZE 32
2226 #else
2227 #define ELF_WSIZE 64
2228 #endif
2229 #ifndef ElfW
2230 #define ElfW(type)      _ElfW (Elf, ELF_WSIZE, type)
2231 #define _ElfW(e,w,t)    _ElfW_1 (e, w, _##t)
2232 #define _ElfW_1(e,w,t)  e##w##t
2233 #endif
2234
2235 static void
2236 dump_elf_symbols (ElfW(Sym) *symbols, int num_symbols, const char *strtab, void *load_addr)
2237 {
2238         int i;
2239         for (i = 0; i < num_symbols; ++i) {
2240                 const char* sym;
2241                 sym =  strtab + symbols [i].st_name;
2242                 if (!symbols [i].st_name || !symbols [i].st_size || (symbols [i].st_info & 0xf) != STT_FUNC)
2243                         continue;
2244                 //printf ("symbol %s at %d\n", sym, symbols [i].st_value);
2245                 dump_usym (sym, (uintptr_t)load_addr + symbols [i].st_value, symbols [i].st_size);
2246         }
2247 }
2248
2249 static int
2250 read_elf_symbols (MonoProfiler *prof, const char *filename, void *load_addr)
2251 {
2252         int fd, i;
2253         void *data;
2254         struct stat statb;
2255         uint64_t file_size;
2256         ElfW(Ehdr) *header;
2257         ElfW(Shdr) *sheader;
2258         ElfW(Shdr) *shstrtabh;
2259         ElfW(Shdr) *symtabh = NULL;
2260         ElfW(Shdr) *strtabh = NULL;
2261         ElfW(Sym) *symbols = NULL;
2262         const char *strtab;
2263         int num_symbols;
2264
2265         fd = open (filename, O_RDONLY);
2266         if (fd < 0)
2267                 return 0;
2268         if (fstat (fd, &statb) != 0) {
2269                 close (fd);
2270                 return 0;
2271         }
2272         file_size = statb.st_size;
2273         data = mmap (NULL, file_size, PROT_READ, MAP_PRIVATE, fd, 0);
2274         close (fd);
2275         if (data == MAP_FAILED)
2276                 return 0;
2277         header = data;
2278         if (header->e_ident [EI_MAG0] != ELFMAG0 ||
2279                         header->e_ident [EI_MAG1] != ELFMAG1 ||
2280                         header->e_ident [EI_MAG2] != ELFMAG2 ||
2281                         header->e_ident [EI_MAG3] != ELFMAG3 ) {
2282                 munmap (data, file_size);
2283                 return 0;
2284         }
2285         sheader = (void*)((char*)data + header->e_shoff);
2286         shstrtabh = (void*)((char*)sheader + (header->e_shentsize * header->e_shstrndx));
2287         strtab = (const char*)data + shstrtabh->sh_offset;
2288         for (i = 0; i < header->e_shnum; ++i) {
2289                 //printf ("section header: %d\n", sheader->sh_type);
2290                 if (sheader->sh_type == SHT_SYMTAB) {
2291                         symtabh = sheader;
2292                         strtabh = (void*)((char*)data + header->e_shoff + sheader->sh_link * header->e_shentsize);
2293                         /*printf ("symtab section header: %d, .strstr: %d\n", i, sheader->sh_link);*/
2294                         break;
2295                 }
2296                 sheader = (void*)((char*)sheader + header->e_shentsize);
2297         }
2298         if (!symtabh || !strtabh) {
2299                 munmap (data, file_size);
2300                 return 0;
2301         }
2302         strtab = (const char*)data + strtabh->sh_offset;
2303         num_symbols = symtabh->sh_size / symtabh->sh_entsize;
2304         symbols = (void*)((char*)data + symtabh->sh_offset);
2305         dump_elf_symbols (symbols, num_symbols, strtab, load_addr);
2306         munmap (data, file_size);
2307         return 1;
2308 }
2309 #endif
2310
2311 /* ELF code crashes on some systems. */
2312 //#if defined(HAVE_DL_ITERATE_PHDR) && defined(ELFMAG0)
2313 #if 0
2314 static int
2315 elf_dl_callback (struct dl_phdr_info *info, size_t size, void *data)
2316 {
2317         MonoProfiler *prof = data;
2318         char buf [256];
2319         const char *filename;
2320         BinaryObject *obj;
2321         char *a = (void*)info->dlpi_addr;
2322         int i, num_sym;
2323         ElfW(Dyn) *dyn = NULL;
2324         ElfW(Sym) *symtab = NULL;
2325         ElfW(Word) *hash_table = NULL;
2326         ElfW(Ehdr) *header = NULL;
2327         const char* strtab = NULL;
2328         for (obj = prof->binary_objects; obj; obj = obj->next) {
2329                 if (obj->addr == a)
2330                         return 0;
2331         }
2332         filename = info->dlpi_name;
2333         if (!filename)
2334                 return 0;
2335         if (!info->dlpi_addr && !filename [0]) {
2336                 int l = readlink ("/proc/self/exe", buf, sizeof (buf) - 1);
2337                 if (l > 0) {
2338                         buf [l] = 0;
2339                         filename = buf;
2340                 }
2341         }
2342         obj = calloc (sizeof (BinaryObject), 1);
2343         obj->addr = (void*)info->dlpi_addr;
2344         obj->name = pstrdup (filename);
2345         obj->next = prof->binary_objects;
2346         prof->binary_objects = obj;
2347         //printf ("loaded file: %s at %p, segments: %d\n", filename, (void*)info->dlpi_addr, info->dlpi_phnum);
2348         a = NULL;
2349         for (i = 0; i < info->dlpi_phnum; ++i) {
2350                 //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);
2351                 if (info->dlpi_phdr[i].p_type == PT_LOAD && !header) {
2352                         header = (ElfW(Ehdr)*)(info->dlpi_addr + info->dlpi_phdr[i].p_vaddr);
2353                         if (header->e_ident [EI_MAG0] != ELFMAG0 ||
2354                                         header->e_ident [EI_MAG1] != ELFMAG1 ||
2355                                         header->e_ident [EI_MAG2] != ELFMAG2 ||
2356                                         header->e_ident [EI_MAG3] != ELFMAG3 ) {
2357                                 header = NULL;
2358                         }
2359                         dump_ubin (filename, info->dlpi_addr + info->dlpi_phdr[i].p_vaddr, info->dlpi_phdr[i].p_offset, info->dlpi_phdr[i].p_memsz);
2360                 } else if (info->dlpi_phdr[i].p_type == PT_DYNAMIC) {
2361                         dyn = (ElfW(Dyn) *)(info->dlpi_addr + info->dlpi_phdr[i].p_vaddr);
2362                 }
2363         }
2364         if (read_elf_symbols (prof, filename, (void*)info->dlpi_addr))
2365                 return 0;
2366         if (!info->dlpi_name || !info->dlpi_name[0])
2367                 return 0;
2368         if (!dyn)
2369                 return 0;
2370         for (i = 0; dyn [i].d_tag != DT_NULL; ++i) {
2371                 if (dyn [i].d_tag == DT_SYMTAB) {
2372                         if (symtab && do_debug)
2373                                 printf ("multiple symtabs: %d\n", i);
2374                         symtab = (ElfW(Sym) *)(a + dyn [i].d_un.d_ptr);
2375                 } else if (dyn [i].d_tag == DT_HASH) {
2376                         hash_table = (ElfW(Word) *)(a + dyn [i].d_un.d_ptr);
2377                 } else if (dyn [i].d_tag == DT_STRTAB) {
2378                         strtab = (const char*)(a + dyn [i].d_un.d_ptr);
2379                 }
2380         }
2381         if (!hash_table)
2382                 return 0;
2383         num_sym = hash_table [1];
2384         dump_elf_symbols (symtab, num_sym, strtab, (void*)info->dlpi_addr);
2385         return 0;
2386 }
2387
2388 static int
2389 load_binaries (MonoProfiler *prof)
2390 {
2391         dl_iterate_phdr (elf_dl_callback, prof);
2392         return 1;
2393 }
2394 #else
2395 static int
2396 load_binaries (MonoProfiler *prof)
2397 {
2398         return 0;
2399 }
2400 #endif
2401
2402 static const char*
2403 symbol_for (uintptr_t code)
2404 {
2405 #ifdef HAVE_DLADDR
2406         void *ip = (void*)code;
2407         Dl_info di;
2408         if (dladdr (ip, &di)) {
2409                 if (di.dli_sname)
2410                         return di.dli_sname;
2411         } else {
2412         /*      char **names;
2413                 names = backtrace_symbols (&ip, 1);
2414                 if (names) {
2415                         const char* p = names [0];
2416                         free (names);
2417                         return p;
2418                 }
2419                 */
2420         }
2421 #endif
2422         return NULL;
2423 }
2424
2425 static void
2426 dump_unmanaged_coderefs (MonoProfiler *prof)
2427 {
2428         int i;
2429         const char* last_symbol;
2430         uintptr_t addr, page_end;
2431
2432         if (load_binaries (prof))
2433                 return;
2434         for (i = 0; i < size_code_pages; ++i) {
2435                 const char* sym;
2436                 if (!code_pages [i] || code_pages [i] & 1)
2437                         continue;
2438                 last_symbol = NULL;
2439                 addr = CPAGE_ADDR (code_pages [i]);
2440                 page_end = addr + CPAGE_SIZE;
2441                 code_pages [i] |= 1;
2442                 /* we dump the symbols for the whole page */
2443                 for (; addr < page_end; addr += 16) {
2444                         sym = symbol_for (addr);
2445                         if (sym && sym == last_symbol)
2446                                 continue;
2447                         last_symbol = sym;
2448                         if (!sym)
2449                                 continue;
2450                         dump_usym (sym, addr, 0); /* let's not guess the size */
2451                         //printf ("found symbol at %p: %s\n", (void*)addr, sym);
2452                 }
2453         }
2454 }
2455
2456 static int
2457 mono_cpu_count (void)
2458 {
2459 #ifdef PLATFORM_ANDROID
2460         /* Android tries really hard to save power by powering off CPUs on SMP phones which
2461          * means the normal way to query cpu count returns a wrong value with userspace API.
2462          * Instead we use /sys entries to query the actual hardware CPU count.
2463          */
2464         int count = 0;
2465         char buffer[8] = {'\0'};
2466         int present = open ("/sys/devices/system/cpu/present", O_RDONLY);
2467         /* Format of the /sys entry is a cpulist of indexes which in the case
2468          * of present is always of the form "0-(n-1)" when there is more than
2469          * 1 core, n being the number of CPU cores in the system. Otherwise
2470          * the value is simply 0
2471          */
2472         if (present != -1 && read (present, (char*)buffer, sizeof (buffer)) > 3)
2473                 count = strtol (((char*)buffer) + 2, NULL, 10);
2474         if (present != -1)
2475                 close (present);
2476         if (count > 0)
2477                 return count + 1;
2478 #endif
2479
2480 #if defined(HOST_ARM) || defined (HOST_ARM64)
2481
2482         /* ARM platforms tries really hard to save power by powering off CPUs on SMP phones which
2483          * means the normal way to query cpu count returns a wrong value with userspace API. */
2484
2485 #ifdef _SC_NPROCESSORS_CONF
2486         {
2487                 int count = sysconf (_SC_NPROCESSORS_CONF);
2488                 if (count > 0)
2489                         return count;
2490         }
2491 #endif
2492
2493 #else
2494
2495 #ifdef HAVE_SCHED_GETAFFINITY
2496         {
2497                 cpu_set_t set;
2498                 if (sched_getaffinity (getpid (), sizeof (set), &set) == 0)
2499                         return CPU_COUNT (&set);
2500         }
2501 #endif
2502 #ifdef _SC_NPROCESSORS_ONLN
2503         {
2504                 int count = sysconf (_SC_NPROCESSORS_ONLN);
2505                 if (count > 0)
2506                         return count;
2507         }
2508 #endif
2509
2510 #endif /* defined(HOST_ARM) || defined (HOST_ARM64) */
2511
2512 #ifdef USE_SYSCTL
2513         {
2514                 int count;
2515                 int mib [2];
2516                 size_t len = sizeof (int);
2517                 mib [0] = CTL_HW;
2518                 mib [1] = HW_NCPU;
2519                 if (sysctl (mib, 2, &count, &len, NULL, 0) == 0)
2520                         return count;
2521         }
2522 #endif
2523 #ifdef HOST_WIN32
2524         {
2525                 SYSTEM_INFO info;
2526                 GetSystemInfo (&info);
2527                 return info.dwNumberOfProcessors;
2528         }
2529 #endif
2530         /* FIXME: warn */
2531         return 1;
2532 }
2533
2534 #if USE_PERF_EVENTS
2535
2536 typedef struct {
2537         int perf_fd;
2538         unsigned int prev_pos;
2539         void *mmap_base;
2540         struct perf_event_mmap_page *page_desc;
2541 } PerfData ;
2542
2543 static PerfData *perf_data = NULL;
2544 static int num_perf;
2545 #define PERF_PAGES_SHIFT 4
2546 static int num_pages = 1 << PERF_PAGES_SHIFT;
2547 static unsigned int mmap_mask;
2548
2549 typedef struct {
2550         struct perf_event_header h;
2551         uint64_t ip;
2552         uint32_t pid;
2553         uint32_t tid;
2554         uint64_t timestamp;
2555         uint64_t period;
2556         uint64_t nframes;
2557 } PSample;
2558
2559 static int
2560 perf_event_syscall (struct perf_event_attr *attr, pid_t pid, int cpu, int group_fd, unsigned long flags)
2561 {
2562         attr->size = PERF_ATTR_SIZE_VER0;
2563         //printf ("perf attr size: %d\n", attr->size);
2564 #if defined(__x86_64__)
2565         return syscall(/*__NR_perf_event_open*/ 298, attr, pid, cpu, group_fd, flags);
2566 #elif defined(__i386__)
2567         return syscall(/*__NR_perf_event_open*/ 336, attr, pid, cpu, group_fd, flags);
2568 #elif defined(__arm__) || defined (__aarch64__)
2569         return syscall(/*__NR_perf_event_open*/ 364, attr, pid, cpu, group_fd, flags);
2570 #else
2571         return -1;
2572 #endif
2573 }
2574
2575 static int
2576 setup_perf_map (PerfData *perf)
2577 {
2578         perf->mmap_base = mmap (NULL, (num_pages + 1) * getpagesize (), PROT_READ|PROT_WRITE, MAP_SHARED, perf->perf_fd, 0);
2579         if (perf->mmap_base == MAP_FAILED) {
2580                 if (do_debug)
2581                         printf ("failed mmap\n");
2582                 return 0;
2583         }
2584         perf->page_desc = perf->mmap_base;
2585         if (do_debug)
2586                 printf ("mmap version: %d\n", perf->page_desc->version);
2587         return 1;
2588 }
2589
2590 static void
2591 dump_perf_hits (MonoProfiler *prof, void *buf, int size)
2592 {
2593         LogBuffer *logbuffer;
2594         int count = 1;
2595         int mbt_count = 0;
2596         void *end = (char*)buf + size;
2597         int samples = 0;
2598         int pid = getpid ();
2599
2600         while (buf < end) {
2601                 PSample *s = buf;
2602                 if (s->h.size == 0)
2603                         break;
2604                 if (pid != s->pid) {
2605                         if (do_debug)
2606                                 printf ("event for different pid: %d\n", s->pid);
2607                         buf = (char*)buf + s->h.size;
2608                         continue;
2609                 }
2610                 /*ip = (void*)s->ip;
2611                 printf ("sample: %d, size: %d, ip: %p (%s), timestamp: %llu, nframes: %llu\n",
2612                         s->h.type, s->h.size, ip, symbol_for (ip), s->timestamp, s->nframes);*/
2613                 logbuffer = ensure_logbuf (
2614                         EVENT_SIZE /* event */ +
2615                         LEB128_SIZE /* type */ +
2616                         LEB128_SIZE /* time */ +
2617                         LEB128_SIZE /* tid */ +
2618                         LEB128_SIZE /* count */ +
2619                         count * (
2620                                 LEB128_SIZE /* ip */
2621                         ) +
2622                         LEB128_SIZE /* managed count */ +
2623                         mbt_count * (
2624                                 LEB128_SIZE /* method */ +
2625                                 LEB128_SIZE /* il offset */ +
2626                                 LEB128_SIZE /* native offset */
2627                         )
2628                 );
2629                 emit_byte (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_HIT);
2630                 emit_value (logbuffer, sample_type);
2631                 emit_uvalue (logbuffer, s->timestamp - prof->startup_time);
2632                 /*
2633                  * No useful thread ID to write here, since throughout the
2634                  * profiler we use pthread_self () but the ID we get from
2635                  * perf is the kernel's thread ID.
2636                  */
2637                 emit_ptr (logbuffer, 0);
2638                 emit_value (logbuffer, count);
2639                 emit_ptr (logbuffer, (void*)(uintptr_t)s->ip);
2640                 add_code_pointer (s->ip);
2641                 /* no support here yet for the managed backtrace */
2642                 emit_uvalue (logbuffer, mbt_count);
2643                 buf = (char*)buf + s->h.size;
2644                 samples++;
2645         }
2646         if (do_debug)
2647                 printf ("dumped %d samples\n", samples);
2648         dump_unmanaged_coderefs (prof);
2649 }
2650
2651 /* read events from the ring buffer */
2652 static int
2653 read_perf_mmap (MonoProfiler* prof, int cpu)
2654 {
2655         PerfData *perf = perf_data + cpu;
2656         unsigned char *buf;
2657         unsigned char *data = (unsigned char*)perf->mmap_base + getpagesize ();
2658         unsigned int head = perf->page_desc->data_head;
2659         int diff, size;
2660         unsigned int old;
2661
2662         mono_memory_read_barrier ();
2663
2664         old = perf->prev_pos;
2665         diff = head - old;
2666         if (diff < 0) {
2667                 if (do_debug)
2668                         printf ("lost mmap events: old: %d, head: %d\n", old, head);
2669                 old = head;
2670         }
2671         size = head - old;
2672         if ((old & mmap_mask) + size != (head & mmap_mask)) {
2673                 buf = data + (old & mmap_mask);
2674                 size = mmap_mask + 1 - (old & mmap_mask);
2675                 old += size;
2676                 /* size bytes at buf */
2677                 if (do_debug)
2678                         printf ("found1 bytes of events: %d\n", size);
2679                 dump_perf_hits (prof, buf, size);
2680         }
2681         buf = data + (old & mmap_mask);
2682         size = head - old;
2683         /* size bytes at buf */
2684         if (do_debug)
2685                 printf ("found bytes of events: %d\n", size);
2686         dump_perf_hits (prof, buf, size);
2687         old += size;
2688         perf->prev_pos = old;
2689         perf->page_desc->data_tail = old;
2690         return 0;
2691 }
2692
2693 static int
2694 setup_perf_event_for_cpu (PerfData *perf, int cpu)
2695 {
2696         struct perf_event_attr attr;
2697         memset (&attr, 0, sizeof (attr));
2698         attr.type = PERF_TYPE_HARDWARE;
2699         switch (sample_type) {
2700         case SAMPLE_CYCLES: attr.config = PERF_COUNT_HW_CPU_CYCLES; break;
2701         case SAMPLE_INSTRUCTIONS: attr.config = PERF_COUNT_HW_INSTRUCTIONS; break;
2702         case SAMPLE_CACHE_MISSES: attr.config = PERF_COUNT_HW_CACHE_MISSES; break;
2703         case SAMPLE_CACHE_REFS: attr.config = PERF_COUNT_HW_CACHE_REFERENCES; break;
2704         case SAMPLE_BRANCHES: attr.config = PERF_COUNT_HW_BRANCH_INSTRUCTIONS; break;
2705         case SAMPLE_BRANCH_MISSES: attr.config = PERF_COUNT_HW_BRANCH_MISSES; break;
2706         default: attr.config = PERF_COUNT_HW_CPU_CYCLES; break;
2707         }
2708         attr.sample_type = PERF_SAMPLE_IP | PERF_SAMPLE_TID | PERF_SAMPLE_PERIOD | PERF_SAMPLE_TIME;
2709 //      attr.sample_type |= PERF_SAMPLE_CALLCHAIN;
2710         attr.read_format = PERF_FORMAT_TOTAL_TIME_ENABLED | PERF_FORMAT_TOTAL_TIME_RUNNING | PERF_FORMAT_ID;
2711         attr.inherit = 1;
2712         attr.freq = 1;
2713         attr.sample_freq = sample_freq;
2714
2715         perf->perf_fd = perf_event_syscall (&attr, getpid (), cpu, -1, 0);
2716         if (do_debug)
2717                 printf ("perf fd: %d, freq: %d, event: %llu\n", perf->perf_fd, sample_freq, attr.config);
2718         if (perf->perf_fd < 0) {
2719                 if (perf->perf_fd == -EPERM) {
2720                         fprintf (stderr, "Perf syscall denied, do \"echo 1 > /proc/sys/kernel/perf_event_paranoid\" as root to enable.\n");
2721                 } else {
2722                         if (do_debug)
2723                                 perror ("open perf event");
2724                 }
2725                 return 0;
2726         }
2727         if (!setup_perf_map (perf)) {
2728                 close (perf->perf_fd);
2729                 perf->perf_fd = -1;
2730                 return 0;
2731         }
2732         return 1;
2733 }
2734
2735 static int
2736 setup_perf_event (void)
2737 {
2738         int i, count = 0;
2739         mmap_mask = num_pages * getpagesize () - 1;
2740         num_perf = mono_cpu_count ();
2741         perf_data = calloc (num_perf, sizeof (PerfData));
2742         for (i = 0; i < num_perf; ++i) {
2743                 count += setup_perf_event_for_cpu (perf_data + i, i);
2744         }
2745         if (count)
2746                 return 1;
2747         free (perf_data);
2748         perf_data = NULL;
2749         return 0;
2750 }
2751
2752 #endif /* USE_PERF_EVENTS */
2753
2754 #ifndef DISABLE_HELPER_THREAD
2755
2756 typedef struct MonoCounterAgent {
2757         MonoCounter *counter;
2758         // MonoCounterAgent specific data :
2759         void *value;
2760         size_t value_size;
2761         short index;
2762         short emitted;
2763         struct MonoCounterAgent *next;
2764 } MonoCounterAgent;
2765
2766 static MonoCounterAgent* counters;
2767 static gboolean counters_initialized = FALSE;
2768 static int counters_index = 1;
2769 static mono_mutex_t counters_mutex;
2770
2771 static void
2772 counters_add_agent (MonoCounter *counter)
2773 {
2774         MonoCounterAgent *agent, *item;
2775
2776         if (!counters_initialized)
2777                 return;
2778
2779         mono_os_mutex_lock (&counters_mutex);
2780
2781         for (agent = counters; agent; agent = agent->next) {
2782                 if (agent->counter == counter) {
2783                         agent->value_size = 0;
2784                         if (agent->value) {
2785                                 free (agent->value);
2786                                 agent->value = NULL;
2787                         }
2788                         mono_os_mutex_unlock (&counters_mutex);
2789                         return;
2790                 }
2791         }
2792
2793         agent = (MonoCounterAgent *)malloc (sizeof (MonoCounterAgent));
2794         agent->counter = counter;
2795         agent->value = NULL;
2796         agent->value_size = 0;
2797         agent->index = counters_index++;
2798         agent->emitted = 0;
2799         agent->next = NULL;
2800
2801         if (!counters) {
2802                 counters = agent;
2803         } else {
2804                 item = counters;
2805                 while (item->next)
2806                         item = item->next;
2807                 item->next = agent;
2808         }
2809
2810         mono_os_mutex_unlock (&counters_mutex);
2811 }
2812
2813 static mono_bool
2814 counters_init_foreach_callback (MonoCounter *counter, gpointer data)
2815 {
2816         counters_add_agent (counter);
2817         return TRUE;
2818 }
2819
2820 static void
2821 counters_init (MonoProfiler *profiler)
2822 {
2823         assert (!counters_initialized);
2824
2825         mono_os_mutex_init (&counters_mutex);
2826
2827         counters_initialized = TRUE;
2828
2829         mono_counters_on_register (&counters_add_agent);
2830         mono_counters_foreach (counters_init_foreach_callback, NULL);
2831 }
2832
2833 static void
2834 counters_emit (MonoProfiler *profiler, gboolean threadless)
2835 {
2836         MonoCounterAgent *agent;
2837         LogBuffer *logbuffer;
2838         int len = 0;
2839         int size =
2840                 EVENT_SIZE /* event */ +
2841                 LEB128_SIZE /* len */
2842         ;
2843
2844         if (!counters_initialized)
2845                 return;
2846
2847         mono_os_mutex_lock (&counters_mutex);
2848
2849         for (agent = counters; agent; agent = agent->next) {
2850                 if (agent->emitted)
2851                         continue;
2852
2853                 size +=
2854                         LEB128_SIZE /* section */ +
2855                         strlen (mono_counter_get_name (agent->counter)) + 1 /* name */ +
2856                         LEB128_SIZE /* type */ +
2857                         LEB128_SIZE /* unit */ +
2858                         LEB128_SIZE /* variance */ +
2859                         LEB128_SIZE /* index */
2860                 ;
2861
2862                 len += 1;
2863         }
2864
2865         if (!len) {
2866                 mono_os_mutex_unlock (&counters_mutex);
2867                 return;
2868         }
2869
2870         logbuffer = ensure_logbuf (size);
2871
2872         ENTER_LOG (logbuffer, "counters");
2873         emit_byte (logbuffer, TYPE_SAMPLE_COUNTERS_DESC | TYPE_SAMPLE);
2874         emit_value (logbuffer, len);
2875         for (agent = counters; agent; agent = agent->next) {
2876                 const char *name;
2877
2878                 if (agent->emitted)
2879                         continue;
2880
2881                 name = mono_counter_get_name (agent->counter);
2882                 emit_value (logbuffer, mono_counter_get_section (agent->counter));
2883                 emit_string (logbuffer, name, strlen (name) + 1);
2884                 emit_value (logbuffer, mono_counter_get_type (agent->counter));
2885                 emit_value (logbuffer, mono_counter_get_unit (agent->counter));
2886                 emit_value (logbuffer, mono_counter_get_variance (agent->counter));
2887                 emit_value (logbuffer, agent->index);
2888
2889                 agent->emitted = 1;
2890         }
2891         EXIT_LOG (logbuffer);
2892
2893         if (threadless)
2894                 safe_send_threadless (profiler, logbuffer);
2895         else
2896                 safe_send (profiler, logbuffer);
2897
2898         mono_os_mutex_unlock (&counters_mutex);
2899 }
2900
2901 static void
2902 counters_sample (MonoProfiler *profiler, uint64_t timestamp, gboolean threadless)
2903 {
2904         MonoCounterAgent *agent;
2905         MonoCounter *counter;
2906         LogBuffer *logbuffer;
2907         int type;
2908         int buffer_size;
2909         void *buffer;
2910         int size;
2911
2912         if (!counters_initialized)
2913                 return;
2914
2915         counters_emit (profiler, threadless);
2916
2917         buffer_size = 8;
2918         buffer = calloc (1, buffer_size);
2919
2920         mono_os_mutex_lock (&counters_mutex);
2921
2922         size =
2923                 EVENT_SIZE /* event */ +
2924                 LEB128_SIZE /* time */
2925         ;
2926
2927         for (agent = counters; agent; agent = agent->next) {
2928                 size +=
2929                         LEB128_SIZE /* index */ +
2930                         LEB128_SIZE /* type */ +
2931                         mono_counter_get_size (agent->counter) /* value */
2932                 ;
2933         }
2934
2935         size +=
2936                 LEB128_SIZE /* stop marker */
2937         ;
2938
2939         logbuffer = ensure_logbuf (size);
2940
2941         ENTER_LOG (logbuffer, "counters");
2942         emit_byte (logbuffer, TYPE_SAMPLE_COUNTERS | TYPE_SAMPLE);
2943         emit_uvalue (logbuffer, timestamp);
2944         for (agent = counters; agent; agent = agent->next) {
2945                 size_t size;
2946
2947                 counter = agent->counter;
2948
2949                 size = mono_counter_get_size (counter);
2950                 if (size < 0) {
2951                         continue; // FIXME error
2952                 } else if (size > buffer_size) {
2953                         buffer_size = size;
2954                         buffer = realloc (buffer, buffer_size);
2955                 }
2956
2957                 memset (buffer, 0, buffer_size);
2958
2959                 if (mono_counters_sample (counter, buffer, size) < 0)
2960                         continue; // FIXME error
2961
2962                 type = mono_counter_get_type (counter);
2963
2964                 if (!agent->value) {
2965                         agent->value = calloc (1, size);
2966                         agent->value_size = size;
2967                 } else {
2968                         if (type == MONO_COUNTER_STRING) {
2969                                 if (strcmp (agent->value, buffer) == 0)
2970                                         continue;
2971                         } else {
2972                                 if (agent->value_size == size && memcmp (agent->value, buffer, size) == 0)
2973                                         continue;
2974                         }
2975                 }
2976
2977                 emit_uvalue (logbuffer, agent->index);
2978                 emit_uvalue (logbuffer, type);
2979                 switch (type) {
2980                 case MONO_COUNTER_INT:
2981 #if SIZEOF_VOID_P == 4
2982                 case MONO_COUNTER_WORD:
2983 #endif
2984                         emit_svalue (logbuffer, *(int*)buffer - *(int*)agent->value);
2985                         break;
2986                 case MONO_COUNTER_UINT:
2987                         emit_uvalue (logbuffer, *(guint*)buffer - *(guint*)agent->value);
2988                         break;
2989                 case MONO_COUNTER_TIME_INTERVAL:
2990                 case MONO_COUNTER_LONG:
2991 #if SIZEOF_VOID_P == 8
2992                 case MONO_COUNTER_WORD:
2993 #endif
2994                         emit_svalue (logbuffer, *(gint64*)buffer - *(gint64*)agent->value);
2995                         break;
2996                 case MONO_COUNTER_ULONG:
2997                         emit_uvalue (logbuffer, *(guint64*)buffer - *(guint64*)agent->value);
2998                         break;
2999                 case MONO_COUNTER_DOUBLE:
3000                         emit_double (logbuffer, *(double*)buffer);
3001                         break;
3002                 case MONO_COUNTER_STRING:
3003                         if (size == 0) {
3004                                 emit_byte (logbuffer, 0);
3005                         } else {
3006                                 emit_byte (logbuffer, 1);
3007                                 emit_string (logbuffer, (char*)buffer, size);
3008                         }
3009                         break;
3010                 default:
3011                         assert (0);
3012                 }
3013
3014                 if (type == MONO_COUNTER_STRING && size > agent->value_size) {
3015                         agent->value = realloc (agent->value, size);
3016                         agent->value_size = size;
3017                 }
3018
3019                 if (size > 0)
3020                         memcpy (agent->value, buffer, size);
3021         }
3022         free (buffer);
3023
3024         emit_value (logbuffer, 0);
3025         EXIT_LOG (logbuffer);
3026
3027         if (threadless)
3028                 safe_send_threadless (profiler, logbuffer);
3029         else
3030                 safe_send (profiler, logbuffer);
3031
3032         mono_os_mutex_unlock (&counters_mutex);
3033 }
3034
3035 typedef struct _PerfCounterAgent PerfCounterAgent;
3036 struct _PerfCounterAgent {
3037         PerfCounterAgent *next;
3038         int index;
3039         char *category_name;
3040         char *name;
3041         int type;
3042         gint64 value;
3043         guint8 emitted;
3044         guint8 updated;
3045         guint8 deleted;
3046 };
3047
3048 static PerfCounterAgent *perfcounters = NULL;
3049
3050 static void
3051 perfcounters_emit (MonoProfiler *profiler, gboolean threadless)
3052 {
3053         PerfCounterAgent *pcagent;
3054         LogBuffer *logbuffer;
3055         int len = 0;
3056         int size =
3057                 EVENT_SIZE /* event */ +
3058                 LEB128_SIZE /* len */
3059         ;
3060
3061         for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
3062                 if (pcagent->emitted)
3063                         continue;
3064
3065                 size +=
3066                         LEB128_SIZE /* section */ +
3067                         strlen (pcagent->category_name) + 1 /* category name */ +
3068                         strlen (pcagent->name) + 1 /* name */ +
3069                         LEB128_SIZE /* type */ +
3070                         LEB128_SIZE /* unit */ +
3071                         LEB128_SIZE /* variance */ +
3072                         LEB128_SIZE /* index */
3073                 ;
3074
3075                 len += 1;
3076         }
3077
3078         if (!len)
3079                 return;
3080
3081         logbuffer = ensure_logbuf (size);
3082
3083         ENTER_LOG (logbuffer, "perfcounters");
3084         emit_byte (logbuffer, TYPE_SAMPLE_COUNTERS_DESC | TYPE_SAMPLE);
3085         emit_value (logbuffer, len);
3086         for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
3087                 if (pcagent->emitted)
3088                         continue;
3089
3090                 emit_value (logbuffer, MONO_COUNTER_PERFCOUNTERS);
3091                 emit_string (logbuffer, pcagent->category_name, strlen (pcagent->category_name) + 1);
3092                 emit_string (logbuffer, pcagent->name, strlen (pcagent->name) + 1);
3093                 emit_value (logbuffer, MONO_COUNTER_LONG);
3094                 emit_value (logbuffer, MONO_COUNTER_RAW);
3095                 emit_value (logbuffer, MONO_COUNTER_VARIABLE);
3096                 emit_value (logbuffer, pcagent->index);
3097
3098                 pcagent->emitted = 1;
3099         }
3100         EXIT_LOG (logbuffer);
3101
3102         if (threadless)
3103                 safe_send_threadless (profiler, logbuffer);
3104         else
3105                 safe_send (profiler, logbuffer);
3106 }
3107
3108 static gboolean
3109 perfcounters_foreach (char *category_name, char *name, unsigned char type, gint64 value, gpointer user_data)
3110 {
3111         PerfCounterAgent *pcagent;
3112
3113         for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
3114                 if (strcmp (pcagent->category_name, category_name) != 0 || strcmp (pcagent->name, name) != 0)
3115                         continue;
3116                 if (pcagent->value == value)
3117                         return TRUE;
3118
3119                 pcagent->value = value;
3120                 pcagent->updated = 1;
3121                 pcagent->deleted = 0;
3122                 return TRUE;
3123         }
3124
3125         pcagent = g_new0 (PerfCounterAgent, 1);
3126         pcagent->next = perfcounters;
3127         pcagent->index = counters_index++;
3128         pcagent->category_name = g_strdup (category_name);
3129         pcagent->name = g_strdup (name);
3130         pcagent->type = (int) type;
3131         pcagent->value = value;
3132         pcagent->emitted = 0;
3133         pcagent->updated = 1;
3134         pcagent->deleted = 0;
3135
3136         perfcounters = pcagent;
3137
3138         return TRUE;
3139 }
3140
3141 static void
3142 perfcounters_sample (MonoProfiler *profiler, uint64_t timestamp, gboolean threadless)
3143 {
3144         PerfCounterAgent *pcagent;
3145         LogBuffer *logbuffer;
3146         int size;
3147
3148         if (!counters_initialized)
3149                 return;
3150
3151         mono_os_mutex_lock (&counters_mutex);
3152
3153         /* mark all perfcounters as deleted, foreach will unmark them as necessary */
3154         for (pcagent = perfcounters; pcagent; pcagent = pcagent->next)
3155                 pcagent->deleted = 1;
3156
3157         mono_perfcounter_foreach (perfcounters_foreach, perfcounters);
3158
3159         perfcounters_emit (profiler, threadless);
3160
3161         size =
3162                 EVENT_SIZE /* event */ +
3163                 LEB128_SIZE /* time */
3164         ;
3165
3166         for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
3167                 if (pcagent->deleted || !pcagent->updated)
3168                         continue;
3169
3170                 size +=
3171                         LEB128_SIZE /* index */ +
3172                         LEB128_SIZE /* type */ +
3173                         LEB128_SIZE /* value */
3174                 ;
3175         }
3176
3177         size +=
3178                 LEB128_SIZE /* stop marker */
3179         ;
3180
3181         logbuffer = ensure_logbuf (size);
3182
3183         ENTER_LOG (logbuffer, "perfcounters");
3184         emit_byte (logbuffer, TYPE_SAMPLE_COUNTERS | TYPE_SAMPLE);
3185         emit_uvalue (logbuffer, timestamp);
3186         for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
3187                 if (pcagent->deleted || !pcagent->updated)
3188                         continue;
3189                 emit_uvalue (logbuffer, pcagent->index);
3190                 emit_uvalue (logbuffer, MONO_COUNTER_LONG);
3191                 emit_svalue (logbuffer, pcagent->value);
3192
3193                 pcagent->updated = 0;
3194         }
3195
3196         emit_value (logbuffer, 0);
3197         EXIT_LOG (logbuffer);
3198
3199         if (threadless)
3200                 safe_send_threadless (profiler, logbuffer);
3201         else
3202                 safe_send (profiler, logbuffer);
3203
3204         mono_os_mutex_unlock (&counters_mutex);
3205 }
3206
3207 static void
3208 counters_and_perfcounters_sample (MonoProfiler *prof, gboolean threadless)
3209 {
3210         static uint64_t start = -1;
3211         uint64_t now;
3212
3213         if (start == -1)
3214                 start = current_time ();
3215
3216         now = current_time ();
3217         counters_sample (prof, (now - start) / 1000/ 1000, threadless);
3218         perfcounters_sample (prof, (now - start) / 1000/ 1000, threadless);
3219 }
3220
3221 #define COVERAGE_DEBUG(x) if (debug_coverage) {x}
3222 static mono_mutex_t coverage_mutex;
3223 static MonoConcurrentHashTable *coverage_methods = NULL;
3224 static MonoConcurrentHashTable *coverage_assemblies = NULL;
3225 static MonoConcurrentHashTable *coverage_classes = NULL;
3226
3227 static MonoConcurrentHashTable *filtered_classes = NULL;
3228 static MonoConcurrentHashTable *entered_methods = NULL;
3229 static MonoConcurrentHashTable *image_to_methods = NULL;
3230 static MonoConcurrentHashTable *suppressed_assemblies = NULL;
3231 static gboolean coverage_initialized = FALSE;
3232
3233 static GPtrArray *coverage_data = NULL;
3234 static int previous_offset = 0;
3235
3236 typedef struct _MethodNode MethodNode;
3237 struct _MethodNode {
3238         MonoLockFreeQueueNode node;
3239         MonoMethod *method;
3240 };
3241
3242 typedef struct _CoverageEntry CoverageEntry;
3243 struct _CoverageEntry {
3244         int offset;
3245         int counter;
3246         char *filename;
3247         int line;
3248         int column;
3249 };
3250
3251 static void
3252 free_coverage_entry (gpointer data, gpointer userdata)
3253 {
3254         CoverageEntry *entry = (CoverageEntry *)data;
3255         g_free (entry->filename);
3256         g_free (entry);
3257 }
3258
3259 static void
3260 obtain_coverage_for_method (MonoProfiler *prof, const MonoProfileCoverageEntry *entry)
3261 {
3262         int offset = entry->iloffset - previous_offset;
3263         CoverageEntry *e = g_new (CoverageEntry, 1);
3264
3265         previous_offset = entry->iloffset;
3266
3267         e->offset = offset;
3268         e->counter = entry->counter;
3269         e->filename = g_strdup(entry->filename ? entry->filename : "");
3270         e->line = entry->line;
3271         e->column = entry->col;
3272
3273         g_ptr_array_add (coverage_data, e);
3274 }
3275
3276 static char *
3277 parse_generic_type_names(char *name)
3278 {
3279         char *new_name, *ret;
3280         int within_generic_declaration = 0, generic_members = 1;
3281
3282         if (name == NULL || *name == '\0')
3283                 return g_strdup ("");
3284
3285         if (!(ret = new_name = (char *)calloc (strlen (name) * 4 + 1, sizeof (char))))
3286                 return NULL;
3287
3288         do {
3289                 switch (*name) {
3290                         case '<':
3291                                 within_generic_declaration = 1;
3292                                 break;
3293
3294                         case '>':
3295                                 within_generic_declaration = 0;
3296
3297                                 if (*(name - 1) != '<') {
3298                                         *new_name++ = '`';
3299                                         *new_name++ = '0' + generic_members;
3300                                 } else {
3301                                         memcpy (new_name, "&lt;&gt;", 8);
3302                                         new_name += 8;
3303                                 }
3304
3305                                 generic_members = 0;
3306                                 break;
3307
3308                         case ',':
3309                                 generic_members++;
3310                                 break;
3311
3312                         default:
3313                                 if (!within_generic_declaration)
3314                                         *new_name++ = *name;
3315
3316                                 break;
3317                 }
3318         } while (*name++);
3319
3320         return ret;
3321 }
3322
3323 static int method_id;
3324 static void
3325 build_method_buffer (gpointer key, gpointer value, gpointer userdata)
3326 {
3327         MonoMethod *method = (MonoMethod *)value;
3328         MonoProfiler *prof = (MonoProfiler *)userdata;
3329         MonoClass *klass;
3330         MonoImage *image;
3331         char *class_name;
3332         const char *image_name, *method_name, *sig, *first_filename;
3333         LogBuffer *logbuffer;
3334         guint i;
3335
3336         previous_offset = 0;
3337         coverage_data = g_ptr_array_new ();
3338
3339         mono_profiler_coverage_get (prof, method, obtain_coverage_for_method);
3340
3341         klass = mono_method_get_class (method);
3342         image = mono_class_get_image (klass);
3343         image_name = mono_image_get_name (image);
3344
3345         sig = mono_signature_get_desc (mono_method_signature (method), TRUE);
3346         class_name = parse_generic_type_names (mono_type_get_name (mono_class_get_type (klass)));
3347         method_name = mono_method_get_name (method);
3348
3349         if (coverage_data->len != 0) {
3350                 CoverageEntry *entry = (CoverageEntry *)coverage_data->pdata[0];
3351                 first_filename = entry->filename ? entry->filename : "";
3352         } else
3353                 first_filename = "";
3354
3355         image_name = image_name ? image_name : "";
3356         sig = sig ? sig : "";
3357         method_name = method_name ? method_name : "";
3358
3359         logbuffer = ensure_logbuf (
3360                 EVENT_SIZE /* event */ +
3361                 strlen (image_name) + 1 /* image name */ +
3362                 strlen (class_name) + 1 /* class name */ +
3363                 strlen (method_name) + 1 /* method name */ +
3364                 strlen (sig) + 1 /* signature */ +
3365                 strlen (first_filename) + 1 /* first file name */ +
3366                 LEB128_SIZE /* token */ +
3367                 LEB128_SIZE /* method id */ +
3368                 LEB128_SIZE /* entries */
3369         );
3370         ENTER_LOG (logbuffer, "coverage-methods");
3371
3372         emit_byte (logbuffer, TYPE_COVERAGE_METHOD | TYPE_COVERAGE);
3373         emit_string (logbuffer, image_name, strlen (image_name) + 1);
3374         emit_string (logbuffer, class_name, strlen (class_name) + 1);
3375         emit_string (logbuffer, method_name, strlen (method_name) + 1);
3376         emit_string (logbuffer, sig, strlen (sig) + 1);
3377         emit_string (logbuffer, first_filename, strlen (first_filename) + 1);
3378
3379         emit_uvalue (logbuffer, mono_method_get_token (method));
3380         emit_uvalue (logbuffer, method_id);
3381         emit_value (logbuffer, coverage_data->len);
3382
3383         EXIT_LOG (logbuffer);
3384         safe_send (prof, logbuffer);
3385
3386         for (i = 0; i < coverage_data->len; i++) {
3387                 CoverageEntry *entry = (CoverageEntry *)coverage_data->pdata[i];
3388
3389                 logbuffer = ensure_logbuf (
3390                         EVENT_SIZE /* event */ +
3391                         LEB128_SIZE /* method id */ +
3392                         LEB128_SIZE /* offset */ +
3393                         LEB128_SIZE /* counter */ +
3394                         LEB128_SIZE /* line */ +
3395                         LEB128_SIZE /* column */
3396                 );
3397                 ENTER_LOG (logbuffer, "coverage-statement");
3398
3399                 emit_byte (logbuffer, TYPE_COVERAGE_STATEMENT | TYPE_COVERAGE);
3400                 emit_uvalue (logbuffer, method_id);
3401                 emit_uvalue (logbuffer, entry->offset);
3402                 emit_uvalue (logbuffer, entry->counter);
3403                 emit_uvalue (logbuffer, entry->line);
3404                 emit_uvalue (logbuffer, entry->column);
3405
3406                 EXIT_LOG (logbuffer);
3407                 safe_send (prof, logbuffer);
3408         }
3409
3410         method_id++;
3411
3412         g_free (class_name);
3413
3414         g_ptr_array_foreach (coverage_data, free_coverage_entry, NULL);
3415         g_ptr_array_free (coverage_data, TRUE);
3416         coverage_data = NULL;
3417 }
3418
3419 /* This empties the queue */
3420 static guint
3421 count_queue (MonoLockFreeQueue *queue)
3422 {
3423         MonoLockFreeQueueNode *node;
3424         guint count = 0;
3425
3426         while ((node = mono_lock_free_queue_dequeue (queue))) {
3427                 count++;
3428                 mono_thread_hazardous_try_free (node, free);
3429         }
3430
3431         return count;
3432 }
3433
3434 static void
3435 build_class_buffer (gpointer key, gpointer value, gpointer userdata)
3436 {
3437         MonoClass *klass = (MonoClass *)key;
3438         MonoLockFreeQueue *class_methods = (MonoLockFreeQueue *)value;
3439         MonoProfiler *prof = (MonoProfiler *)userdata;
3440         MonoImage *image;
3441         char *class_name;
3442         const char *assembly_name;
3443         int number_of_methods, partially_covered;
3444         guint fully_covered;
3445         LogBuffer *logbuffer;
3446
3447         image = mono_class_get_image (klass);
3448         assembly_name = mono_image_get_name (image);
3449         class_name = mono_type_get_name (mono_class_get_type (klass));
3450
3451         assembly_name = assembly_name ? assembly_name : "";
3452         number_of_methods = mono_class_num_methods (klass);
3453         fully_covered = count_queue (class_methods);
3454         /* We don't handle partial covered yet */
3455         partially_covered = 0;
3456
3457         logbuffer = ensure_logbuf (
3458                 EVENT_SIZE /* event */ +
3459                 strlen (assembly_name) + 1 /* assembly name */ +
3460                 strlen (class_name) + 1 /* class name */ +
3461                 LEB128_SIZE /* no. methods */ +
3462                 LEB128_SIZE /* fully covered */ +
3463                 LEB128_SIZE /* partially covered */
3464         );
3465
3466         ENTER_LOG (logbuffer, "coverage-class");
3467         emit_byte (logbuffer, TYPE_COVERAGE_CLASS | TYPE_COVERAGE);
3468         emit_string (logbuffer, assembly_name, strlen (assembly_name) + 1);
3469         emit_string (logbuffer, class_name, strlen (class_name) + 1);
3470         emit_uvalue (logbuffer, number_of_methods);
3471         emit_uvalue (logbuffer, fully_covered);
3472         emit_uvalue (logbuffer, partially_covered);
3473         EXIT_LOG (logbuffer);
3474
3475         safe_send (prof, logbuffer);
3476
3477         g_free (class_name);
3478 }
3479
3480 static void
3481 get_coverage_for_image (MonoImage *image, int *number_of_methods, guint *fully_covered, int *partially_covered)
3482 {
3483         MonoLockFreeQueue *image_methods = (MonoLockFreeQueue *)mono_conc_hashtable_lookup (image_to_methods, image);
3484
3485         *number_of_methods = mono_image_get_table_rows (image, MONO_TABLE_METHOD);
3486         if (image_methods)
3487                 *fully_covered = count_queue (image_methods);
3488         else
3489                 *fully_covered = 0;
3490
3491         // FIXME: We don't handle partially covered yet.
3492         *partially_covered = 0;
3493 }
3494
3495 static void
3496 build_assembly_buffer (gpointer key, gpointer value, gpointer userdata)
3497 {
3498         MonoAssembly *assembly = (MonoAssembly *)value;
3499         MonoProfiler *prof = (MonoProfiler *)userdata;
3500         MonoImage *image = mono_assembly_get_image (assembly);
3501         LogBuffer *logbuffer;
3502         const char *name, *guid, *filename;
3503         int number_of_methods = 0, partially_covered = 0;
3504         guint fully_covered = 0;
3505
3506         name = mono_image_get_name (image);
3507         guid = mono_image_get_guid (image);
3508         filename = mono_image_get_filename (image);
3509
3510         name = name ? name : "";
3511         guid = guid ? guid : "";
3512         filename = filename ? filename : "";
3513
3514         get_coverage_for_image (image, &number_of_methods, &fully_covered, &partially_covered);
3515
3516         logbuffer = ensure_logbuf (
3517                 EVENT_SIZE /* event */ +
3518                 strlen (name) + 1 /* name */ +
3519                 strlen (guid) + 1 /* guid */ +
3520                 strlen (filename) + 1 /* file name */ +
3521                 LEB128_SIZE /* no. methods */ +
3522                 LEB128_SIZE /* fully covered */ +
3523                 LEB128_SIZE /* partially covered */
3524         );
3525
3526         ENTER_LOG (logbuffer, "coverage-assemblies");
3527         emit_byte (logbuffer, TYPE_COVERAGE_ASSEMBLY | TYPE_COVERAGE);
3528         emit_string (logbuffer, name, strlen (name) + 1);
3529         emit_string (logbuffer, guid, strlen (guid) + 1);
3530         emit_string (logbuffer, filename, strlen (filename) + 1);
3531         emit_uvalue (logbuffer, number_of_methods);
3532         emit_uvalue (logbuffer, fully_covered);
3533         emit_uvalue (logbuffer, partially_covered);
3534         EXIT_LOG (logbuffer);
3535
3536         safe_send (prof, logbuffer);
3537 }
3538
3539 static void
3540 dump_coverage (MonoProfiler *prof)
3541 {
3542         if (!coverage_initialized)
3543                 return;
3544
3545         COVERAGE_DEBUG(fprintf (stderr, "Coverage: Started dump\n");)
3546         method_id = 0;
3547
3548         mono_os_mutex_lock (&coverage_mutex);
3549         mono_conc_hashtable_foreach (coverage_assemblies, build_assembly_buffer, prof);
3550         mono_conc_hashtable_foreach (coverage_classes, build_class_buffer, prof);
3551         mono_conc_hashtable_foreach (coverage_methods, build_method_buffer, prof);
3552         mono_os_mutex_unlock (&coverage_mutex);
3553
3554         COVERAGE_DEBUG(fprintf (stderr, "Coverage: Finished dump\n");)
3555 }
3556
3557 static void
3558 process_method_enter_coverage (MonoProfiler *prof, MonoMethod *method)
3559 {
3560         MonoClass *klass;
3561         MonoImage *image;
3562
3563         if (!coverage_initialized)
3564                 return;
3565
3566         klass = mono_method_get_class (method);
3567         image = mono_class_get_image (klass);
3568
3569         if (mono_conc_hashtable_lookup (suppressed_assemblies, (gpointer) mono_image_get_name (image)))
3570                 return;
3571
3572         mono_os_mutex_lock (&coverage_mutex);
3573         mono_conc_hashtable_insert (entered_methods, method, method);
3574         mono_os_mutex_unlock (&coverage_mutex);
3575 }
3576
3577 static MonoLockFreeQueueNode *
3578 create_method_node (MonoMethod *method)
3579 {
3580         MethodNode *node = (MethodNode *)g_malloc (sizeof (MethodNode));
3581         mono_lock_free_queue_node_init ((MonoLockFreeQueueNode *) node, FALSE);
3582         node->method = method;
3583
3584         return (MonoLockFreeQueueNode *) node;
3585 }
3586
3587 static gboolean
3588 coverage_filter (MonoProfiler *prof, MonoMethod *method)
3589 {
3590         MonoError error;
3591         MonoClass *klass;
3592         MonoImage *image;
3593         MonoAssembly *assembly;
3594         MonoMethodHeader *header;
3595         guint32 iflags, flags, code_size;
3596         char *fqn, *classname;
3597         gboolean has_positive, found;
3598         MonoLockFreeQueue *image_methods, *class_methods;
3599         MonoLockFreeQueueNode *node;
3600
3601         if (!coverage_initialized)
3602                 return FALSE;
3603
3604         COVERAGE_DEBUG(fprintf (stderr, "Coverage filter for %s\n", mono_method_get_name (method));)
3605
3606         flags = mono_method_get_flags (method, &iflags);
3607         if ((iflags & 0x1000 /*METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL*/) ||
3608             (flags & 0x2000 /*METHOD_ATTRIBUTE_PINVOKE_IMPL*/)) {
3609                 COVERAGE_DEBUG(fprintf (stderr, "   Internal call or pinvoke - ignoring\n");)
3610                 return FALSE;
3611         }
3612
3613         // Don't need to do anything else if we're already tracking this method
3614         if (mono_conc_hashtable_lookup (coverage_methods, method)) {
3615                 COVERAGE_DEBUG(fprintf (stderr, "   Already tracking\n");)
3616                 return TRUE;
3617         }
3618
3619         klass = mono_method_get_class (method);
3620         image = mono_class_get_image (klass);
3621
3622         // Don't handle coverage for the core assemblies
3623         if (mono_conc_hashtable_lookup (suppressed_assemblies, (gpointer) mono_image_get_name (image)) != NULL)
3624                 return FALSE;
3625
3626         if (prof->coverage_filters) {
3627                 /* Check already filtered classes first */
3628                 if (mono_conc_hashtable_lookup (filtered_classes, klass)) {
3629                         COVERAGE_DEBUG(fprintf (stderr, "   Already filtered\n");)
3630                         return FALSE;
3631                 }
3632
3633                 classname = mono_type_get_name (mono_class_get_type (klass));
3634
3635                 fqn = g_strdup_printf ("[%s]%s", mono_image_get_name (image), classname);
3636
3637                 COVERAGE_DEBUG(fprintf (stderr, "   Looking for %s in filter\n", fqn);)
3638                 // Check positive filters first
3639                 has_positive = FALSE;
3640                 found = FALSE;
3641                 for (guint i = 0; i < prof->coverage_filters->len; ++i) {
3642                         char *filter = (char *)g_ptr_array_index (prof->coverage_filters, i);
3643
3644                         if (filter [0] == '+') {
3645                                 filter = &filter [1];
3646
3647                                 COVERAGE_DEBUG(fprintf (stderr, "   Checking against +%s ...", filter);)
3648
3649                                 if (strstr (fqn, filter) != NULL) {
3650                                         COVERAGE_DEBUG(fprintf (stderr, "matched\n");)
3651                                         found = TRUE;
3652                                 } else
3653                                         COVERAGE_DEBUG(fprintf (stderr, "no match\n");)
3654
3655                                 has_positive = TRUE;
3656                         }
3657                 }
3658
3659                 if (has_positive && !found) {
3660                         COVERAGE_DEBUG(fprintf (stderr, "   Positive match was not found\n");)
3661
3662                         mono_os_mutex_lock (&coverage_mutex);
3663                         mono_conc_hashtable_insert (filtered_classes, klass, klass);
3664                         mono_os_mutex_unlock (&coverage_mutex);
3665                         g_free (fqn);
3666                         g_free (classname);
3667
3668                         return FALSE;
3669                 }
3670
3671                 for (guint i = 0; i < prof->coverage_filters->len; ++i) {
3672                         // FIXME: Is substring search sufficient?
3673                         char *filter = (char *)g_ptr_array_index (prof->coverage_filters, i);
3674                         if (filter [0] == '+')
3675                                 continue;
3676
3677                         // Skip '-'
3678                         filter = &filter [1];
3679                         COVERAGE_DEBUG(fprintf (stderr, "   Checking against -%s ...", filter);)
3680
3681                         if (strstr (fqn, filter) != NULL) {
3682                                 COVERAGE_DEBUG(fprintf (stderr, "matched\n");)
3683
3684                                 mono_os_mutex_lock (&coverage_mutex);
3685                                 mono_conc_hashtable_insert (filtered_classes, klass, klass);
3686                                 mono_os_mutex_unlock (&coverage_mutex);
3687                                 g_free (fqn);
3688                                 g_free (classname);
3689
3690                                 return FALSE;
3691                         } else
3692                                 COVERAGE_DEBUG(fprintf (stderr, "no match\n");)
3693
3694                 }
3695
3696                 g_free (fqn);
3697                 g_free (classname);
3698         }
3699
3700         COVERAGE_DEBUG(fprintf (stderr, "   Handling coverage for %s\n", mono_method_get_name (method));)
3701         header = mono_method_get_header_checked (method, &error);
3702         mono_error_cleanup (&error);
3703
3704         mono_method_header_get_code (header, &code_size, NULL);
3705
3706         assembly = mono_image_get_assembly (image);
3707
3708         // Need to keep the assemblies around for as long as they are kept in the hashtable
3709         // Nunit, for example, has a habit of unloading them before the coverage statistics are
3710         // generated causing a crash. See https://bugzilla.xamarin.com/show_bug.cgi?id=39325
3711         mono_assembly_addref (assembly);
3712
3713         mono_os_mutex_lock (&coverage_mutex);
3714         mono_conc_hashtable_insert (coverage_methods, method, method);
3715         mono_conc_hashtable_insert (coverage_assemblies, assembly, assembly);
3716         mono_os_mutex_unlock (&coverage_mutex);
3717
3718         image_methods = (MonoLockFreeQueue *)mono_conc_hashtable_lookup (image_to_methods, image);
3719
3720         if (image_methods == NULL) {
3721                 image_methods = (MonoLockFreeQueue *)g_malloc (sizeof (MonoLockFreeQueue));
3722                 mono_lock_free_queue_init (image_methods);
3723                 mono_os_mutex_lock (&coverage_mutex);
3724                 mono_conc_hashtable_insert (image_to_methods, image, image_methods);
3725                 mono_os_mutex_unlock (&coverage_mutex);
3726         }
3727
3728         node = create_method_node (method);
3729         mono_lock_free_queue_enqueue (image_methods, node);
3730
3731         class_methods = (MonoLockFreeQueue *)mono_conc_hashtable_lookup (coverage_classes, klass);
3732
3733         if (class_methods == NULL) {
3734                 class_methods = (MonoLockFreeQueue *)g_malloc (sizeof (MonoLockFreeQueue));
3735                 mono_lock_free_queue_init (class_methods);
3736                 mono_os_mutex_lock (&coverage_mutex);
3737                 mono_conc_hashtable_insert (coverage_classes, klass, class_methods);
3738                 mono_os_mutex_unlock (&coverage_mutex);
3739         }
3740
3741         node = create_method_node (method);
3742         mono_lock_free_queue_enqueue (class_methods, node);
3743
3744         return TRUE;
3745 }
3746
3747 #define LINE_BUFFER_SIZE 4096
3748 /* Max file limit of 128KB */
3749 #define MAX_FILE_SIZE 128 * 1024
3750 static char *
3751 get_file_content (FILE *stream)
3752 {
3753         char *buffer;
3754         ssize_t bytes_read;
3755         long filesize;
3756         int res, offset = 0;
3757
3758         res = fseek (stream, 0, SEEK_END);
3759         if (res < 0)
3760           return NULL;
3761
3762         filesize = ftell (stream);
3763         if (filesize < 0)
3764           return NULL;
3765
3766         res = fseek (stream, 0, SEEK_SET);
3767         if (res < 0)
3768           return NULL;
3769
3770         if (filesize > MAX_FILE_SIZE)
3771           return NULL;
3772
3773         buffer = (char *)g_malloc ((filesize + 1) * sizeof (char));
3774         while ((bytes_read = fread (buffer + offset, 1, LINE_BUFFER_SIZE, stream)) > 0)
3775                 offset += bytes_read;
3776
3777         /* NULL terminate our buffer */
3778         buffer[filesize] = '\0';
3779         return buffer;
3780 }
3781
3782 static char *
3783 get_next_line (char *contents, char **next_start)
3784 {
3785         char *p = contents;
3786
3787         if (p == NULL || *p == '\0') {
3788                 *next_start = NULL;
3789                 return NULL;
3790         }
3791
3792         while (*p != '\n' && *p != '\0')
3793                 p++;
3794
3795         if (*p == '\n') {
3796                 *p = '\0';
3797                 *next_start = p + 1;
3798         } else
3799                 *next_start = NULL;
3800
3801         return contents;
3802 }
3803
3804 static void
3805 init_suppressed_assemblies (void)
3806 {
3807         char *content;
3808         char *line;
3809         FILE *sa_file;
3810
3811         suppressed_assemblies = mono_conc_hashtable_new (g_str_hash, g_str_equal);
3812         sa_file = fopen (SUPPRESSION_DIR "/mono-profiler-log.suppression", "r");
3813         if (sa_file == NULL)
3814                 return;
3815
3816         /* Don't need to free @content as it is referred to by the lines stored in @suppressed_assemblies */
3817         content = get_file_content (sa_file);
3818         if (content == NULL) {
3819                 g_error ("mono-profiler-log.suppression is greater than 128kb - aborting\n");
3820         }
3821
3822         while ((line = get_next_line (content, &content))) {
3823                 line = g_strchomp (g_strchug (line));
3824                 /* No locking needed as we're doing initialization */
3825                 mono_conc_hashtable_insert (suppressed_assemblies, line, line);
3826         }
3827
3828         fclose (sa_file);
3829 }
3830
3831 #endif /* DISABLE_HELPER_THREAD */
3832
3833 static void
3834 coverage_init (MonoProfiler *prof)
3835 {
3836 #ifndef DISABLE_HELPER_THREAD
3837         assert (!coverage_initialized);
3838
3839         COVERAGE_DEBUG(fprintf (stderr, "Coverage initialized\n");)
3840
3841         mono_os_mutex_init (&coverage_mutex);
3842         coverage_methods = mono_conc_hashtable_new (NULL, NULL);
3843         coverage_assemblies = mono_conc_hashtable_new (NULL, NULL);
3844         coverage_classes = mono_conc_hashtable_new (NULL, NULL);
3845         filtered_classes = mono_conc_hashtable_new (NULL, NULL);
3846         entered_methods = mono_conc_hashtable_new (NULL, NULL);
3847         image_to_methods = mono_conc_hashtable_new (NULL, NULL);
3848         init_suppressed_assemblies ();
3849
3850         coverage_initialized = TRUE;
3851 #endif /* DISABLE_HELPER_THREAD */
3852 }
3853
3854 static void
3855 unref_coverage_assemblies (gpointer key, gpointer value, gpointer userdata)
3856 {
3857         MonoAssembly *assembly = (MonoAssembly *)value;
3858         mono_assembly_close (assembly);
3859 }
3860
3861 static void
3862 free_sample_hit (gpointer p)
3863 {
3864         mono_lock_free_free (p, SAMPLE_BLOCK_SIZE);
3865 }
3866
3867 static void
3868 cleanup_reusable_samples (MonoProfiler *prof)
3869 {
3870         SampleHit *sample;
3871
3872         while ((sample = (SampleHit *) mono_lock_free_queue_dequeue (&prof->sample_reuse_queue)))
3873                 mono_thread_hazardous_try_free (sample, free_sample_hit);
3874 }
3875
3876 static void
3877 log_shutdown (MonoProfiler *prof)
3878 {
3879         void *res;
3880
3881         in_shutdown = 1;
3882 #ifndef DISABLE_HELPER_THREAD
3883         counters_and_perfcounters_sample (prof, FALSE);
3884
3885         dump_coverage (prof);
3886
3887         if (prof->command_port) {
3888                 char c = 1;
3889                 ign_res (write (prof->pipes [1], &c, 1));
3890                 pthread_join (prof->helper_thread, &res);
3891         }
3892 #endif
3893 #if USE_PERF_EVENTS
3894         if (perf_data) {
3895                 int i;
3896                 for (i = 0; i < num_perf; ++i)
3897                         read_perf_mmap (prof, i);
3898         }
3899 #endif
3900
3901         if (TLS_GET (LogBuffer, tlsbuffer))
3902                 send_buffer (prof, TLS_GET (GPtrArray, tlsmethodlist), TLS_GET (LogBuffer, tlsbuffer));
3903
3904         TLS_SET (tlsbuffer, NULL);
3905         TLS_SET (tlsmethodlist, NULL);
3906
3907         InterlockedWrite (&prof->run_dumper_thread, 0);
3908         mono_os_sem_post (&prof->dumper_queue_sem);
3909         pthread_join (prof->dumper_thread, &res);
3910         mono_os_sem_destroy (&prof->dumper_queue_sem);
3911
3912         InterlockedWrite (&prof->run_writer_thread, 0);
3913         mono_os_sem_post (&prof->writer_queue_sem);
3914         pthread_join (prof->writer_thread, &res);
3915         mono_os_sem_destroy (&prof->writer_queue_sem);
3916
3917         cleanup_reusable_samples (prof);
3918
3919 #if defined (HAVE_SYS_ZLIB)
3920         if (prof->gzfile)
3921                 gzclose (prof->gzfile);
3922 #endif
3923         if (prof->pipe_output)
3924                 pclose (prof->file);
3925         else
3926                 fclose (prof->file);
3927
3928         mono_conc_hashtable_destroy (prof->method_table);
3929         mono_os_mutex_destroy (&prof->method_table_mutex);
3930
3931         if (coverage_initialized) {
3932                 mono_os_mutex_lock (&coverage_mutex);
3933                 mono_conc_hashtable_foreach (coverage_assemblies, unref_coverage_assemblies, prof);
3934                 mono_os_mutex_unlock (&coverage_mutex);
3935
3936                 mono_conc_hashtable_destroy (coverage_methods);
3937                 mono_conc_hashtable_destroy (coverage_assemblies);
3938                 mono_conc_hashtable_destroy (coverage_classes);
3939                 mono_conc_hashtable_destroy (filtered_classes);
3940
3941                 mono_conc_hashtable_destroy (entered_methods);
3942                 mono_conc_hashtable_destroy (image_to_methods);
3943                 mono_conc_hashtable_destroy (suppressed_assemblies);
3944                 mono_os_mutex_destroy (&coverage_mutex);
3945         }
3946
3947         free (prof);
3948 }
3949
3950 static char*
3951 new_filename (const char* filename)
3952 {
3953         time_t t = time (NULL);
3954         int pid = process_id ();
3955         char pid_buf [16];
3956         char time_buf [16];
3957         char *res, *d;
3958         const char *p;
3959         int count_dates = 0;
3960         int count_pids = 0;
3961         int s_date, s_pid;
3962         struct tm *ts;
3963         for (p = filename; *p; p++) {
3964                 if (*p != '%')
3965                         continue;
3966                 p++;
3967                 if (*p == 't')
3968                         count_dates++;
3969                 else if (*p == 'p')
3970                         count_pids++;
3971                 else if (*p == 0)
3972                         break;
3973         }
3974         if (!count_dates && !count_pids)
3975                 return pstrdup (filename);
3976         snprintf (pid_buf, sizeof (pid_buf), "%d", pid);
3977         ts = gmtime (&t);
3978         snprintf (time_buf, sizeof (time_buf), "%d%02d%02d%02d%02d%02d",
3979                 1900 + ts->tm_year, 1 + ts->tm_mon, ts->tm_mday, ts->tm_hour, ts->tm_min, ts->tm_sec);
3980         s_date = strlen (time_buf);
3981         s_pid = strlen (pid_buf);
3982         d = res = (char *)malloc (strlen (filename) + s_date * count_dates + s_pid * count_pids);
3983         for (p = filename; *p; p++) {
3984                 if (*p != '%') {
3985                         *d++ = *p;
3986                         continue;
3987                 }
3988                 p++;
3989                 if (*p == 't') {
3990                         strcpy (d, time_buf);
3991                         d += s_date;
3992                         continue;
3993                 } else if (*p == 'p') {
3994                         strcpy (d, pid_buf);
3995                         d += s_pid;
3996                         continue;
3997                 } else if (*p == '%') {
3998                         *d++ = '%';
3999                         continue;
4000                 } else if (*p == 0)
4001                         break;
4002                 *d++ = '%';
4003                 *d++ = *p;
4004         }
4005         *d = 0;
4006         return res;
4007 }
4008
4009 //this is exposed by the JIT, but it's not meant to be a supported API for now.
4010 extern void mono_threads_attach_tools_thread (void);
4011
4012 #ifndef DISABLE_HELPER_THREAD
4013
4014 static void*
4015 helper_thread (void* arg)
4016 {
4017         MonoProfiler* prof = (MonoProfiler *)arg;
4018         int command_socket;
4019         int len;
4020         char buf [64];
4021         MonoThread *thread = NULL;
4022
4023         mono_threads_attach_tools_thread ();
4024         mono_thread_info_set_name (mono_native_thread_id_get (), "Profiler helper");
4025
4026         //fprintf (stderr, "Server listening\n");
4027         command_socket = -1;
4028         while (1) {
4029                 fd_set rfds;
4030                 struct timeval tv;
4031                 int max_fd = -1;
4032                 FD_ZERO (&rfds);
4033                 FD_SET (prof->server_socket, &rfds);
4034                 max_fd = prof->server_socket;
4035                 FD_SET (prof->pipes [0], &rfds);
4036                 if (max_fd < prof->pipes [0])
4037                         max_fd = prof->pipes [0];
4038                 if (command_socket >= 0) {
4039                         FD_SET (command_socket, &rfds);
4040                         if (max_fd < command_socket)
4041                                 max_fd = command_socket;
4042                 }
4043 #if USE_PERF_EVENTS
4044                 if (perf_data) {
4045                         int i;
4046                         for ( i = 0; i < num_perf; ++i) {
4047                                 if (perf_data [i].perf_fd < 0)
4048                                         continue;
4049                                 FD_SET (perf_data [i].perf_fd, &rfds);
4050                                 if (max_fd < perf_data [i].perf_fd)
4051                                         max_fd = perf_data [i].perf_fd;
4052                         }
4053                 }
4054 #endif
4055
4056                 counters_and_perfcounters_sample (prof, TRUE);
4057
4058                 tv.tv_sec = 1;
4059                 tv.tv_usec = 0;
4060                 len = select (max_fd + 1, &rfds, NULL, NULL, &tv);
4061
4062                 if (len < 0) {
4063                         if (errno == EINTR)
4064                                 continue;
4065
4066                         g_warning ("Error in proflog server: %s", strerror (errno));
4067                         return NULL;
4068                 }
4069
4070                 if (FD_ISSET (prof->pipes [0], &rfds)) {
4071                         char c;
4072                         read (prof->pipes [0], &c, 1);
4073                         if (thread)
4074                                 mono_thread_detach (thread);
4075                         if (do_debug)
4076                                 fprintf (stderr, "helper shutdown\n");
4077 #if USE_PERF_EVENTS
4078                         if (perf_data) {
4079                                 int i;
4080                                 for ( i = 0; i < num_perf; ++i) {
4081                                         if (perf_data [i].perf_fd < 0)
4082                                                 continue;
4083                                         if (FD_ISSET (perf_data [i].perf_fd, &rfds))
4084                                                 read_perf_mmap (prof, i);
4085                                 }
4086                         }
4087 #endif
4088                         safe_send_threadless (prof, ensure_logbuf (0));
4089                         return NULL;
4090                 }
4091 #if USE_PERF_EVENTS
4092                 if (perf_data) {
4093                         int i;
4094                         for ( i = 0; i < num_perf; ++i) {
4095                                 if (perf_data [i].perf_fd < 0)
4096                                         continue;
4097                                 if (FD_ISSET (perf_data [i].perf_fd, &rfds)) {
4098                                         read_perf_mmap (prof, i);
4099                                         safe_send_threadless (prof, ensure_logbuf (0));
4100                                 }
4101                         }
4102                 }
4103 #endif
4104                 if (command_socket >= 0 && FD_ISSET (command_socket, &rfds)) {
4105                         len = read (command_socket, buf, sizeof (buf) - 1);
4106                         if (len < 0)
4107                                 continue;
4108                         if (len == 0) {
4109                                 close (command_socket);
4110                                 command_socket = -1;
4111                                 continue;
4112                         }
4113                         buf [len] = 0;
4114                         if (strcmp (buf, "heapshot\n") == 0) {
4115                                 heapshot_requested = 1;
4116                                 //fprintf (stderr, "perform heapshot\n");
4117                                 if (InterlockedRead (&runtime_inited) && !thread) {
4118                                         thread = mono_thread_attach (mono_get_root_domain ());
4119                                         /*fprintf (stderr, "attached\n");*/
4120                                 }
4121                                 if (thread) {
4122                                         process_requests (prof);
4123                                         mono_thread_detach (thread);
4124                                         thread = NULL;
4125                                 }
4126                         }
4127                         continue;
4128                 }
4129                 if (!FD_ISSET (prof->server_socket, &rfds)) {
4130                         continue;
4131                 }
4132                 command_socket = accept (prof->server_socket, NULL, NULL);
4133                 if (command_socket < 0)
4134                         continue;
4135                 //fprintf (stderr, "Accepted connection\n");
4136         }
4137
4138         mono_thread_info_detach ();
4139
4140         return NULL;
4141 }
4142
4143 static int
4144 start_helper_thread (MonoProfiler* prof)
4145 {
4146         struct sockaddr_in server_address;
4147         int r;
4148         socklen_t slen;
4149         if (pipe (prof->pipes) < 0) {
4150                 fprintf (stderr, "Cannot create pipe\n");
4151                 return 0;
4152         }
4153         prof->server_socket = socket (PF_INET, SOCK_STREAM, 0);
4154         if (prof->server_socket < 0) {
4155                 fprintf (stderr, "Cannot create server socket\n");
4156                 return 0;
4157         }
4158         memset (&server_address, 0, sizeof (server_address));
4159         server_address.sin_family = AF_INET;
4160         server_address.sin_addr.s_addr = INADDR_ANY;
4161         server_address.sin_port = htons (prof->command_port);
4162         if (bind (prof->server_socket, (struct sockaddr *) &server_address, sizeof (server_address)) < 0) {
4163                 fprintf (stderr, "Cannot bind server socket, port: %d: %s\n", prof->command_port, strerror (errno));
4164                 close (prof->server_socket);
4165                 return 0;
4166         }
4167         if (listen (prof->server_socket, 1) < 0) {
4168                 fprintf (stderr, "Cannot listen server socket\n");
4169                 close (prof->server_socket);
4170                 return 0;
4171         }
4172         slen = sizeof (server_address);
4173         if (getsockname (prof->server_socket, (struct sockaddr *)&server_address, &slen) == 0) {
4174                 prof->command_port = ntohs (server_address.sin_port);
4175                 /*fprintf (stderr, "Assigned server port: %d\n", prof->command_port);*/
4176         }
4177
4178         r = pthread_create (&prof->helper_thread, NULL, helper_thread, prof);
4179         if (r) {
4180                 close (prof->server_socket);
4181                 return 0;
4182         }
4183         return 1;
4184 }
4185 #endif
4186
4187 static gboolean
4188 handle_writer_queue_entry (MonoProfiler *prof)
4189 {
4190         WriterQueueEntry *entry;
4191
4192         if ((entry = (WriterQueueEntry *) mono_lock_free_queue_dequeue (&prof->writer_queue))) {
4193                 LogBuffer *method_buffer = NULL;
4194                 gboolean new_methods = FALSE;
4195
4196                 if (entry->methods->len)
4197                         method_buffer = create_buffer ();
4198
4199                 /*
4200                  * Encode the method events in a temporary log buffer that we
4201                  * flush to disk before the main buffer, ensuring that all
4202                  * methods have metadata emitted before they're referenced.
4203                  */
4204                 for (guint i = 0; i < entry->methods->len; i++) {
4205                         MethodInfo *info = (MethodInfo *)g_ptr_array_index (entry->methods, i);
4206
4207                         if (mono_conc_hashtable_lookup (prof->method_table, info->method))
4208                                 continue;
4209
4210                         new_methods = TRUE;
4211
4212                         /*
4213                          * Other threads use this hash table to get a general
4214                          * idea of whether a method has already been emitted to
4215                          * the stream. Due to the way we add to this table, it
4216                          * can easily happen that multiple threads queue up the
4217                          * same methods, but that's OK since eventually all
4218                          * methods will be in this table and the thread-local
4219                          * method lists will just be empty for the rest of the
4220                          * app's lifetime.
4221                          */
4222                         mono_os_mutex_lock (&prof->method_table_mutex);
4223                         mono_conc_hashtable_insert (prof->method_table, info->method, info->method);
4224                         mono_os_mutex_unlock (&prof->method_table_mutex);
4225
4226                         char *name = mono_method_full_name (info->method, 1);
4227                         int nlen = strlen (name) + 1;
4228                         void *cstart = info->ji ? mono_jit_info_get_code_start (info->ji) : NULL;
4229                         int csize = info->ji ? mono_jit_info_get_code_size (info->ji) : 0;
4230
4231                         method_buffer = ensure_logbuf_inner (method_buffer,
4232                                 EVENT_SIZE /* event */ +
4233                                 LEB128_SIZE /* time */ +
4234                                 LEB128_SIZE /* method */ +
4235                                 LEB128_SIZE /* start */ +
4236                                 LEB128_SIZE /* size */ +
4237                                 nlen /* name */
4238                         );
4239
4240                         emit_byte (method_buffer, TYPE_JIT | TYPE_METHOD);
4241                         emit_time (method_buffer, info->time);
4242                         emit_method_inner (method_buffer, info->method);
4243                         emit_ptr (method_buffer, cstart);
4244                         emit_value (method_buffer, csize);
4245
4246                         memcpy (method_buffer->cursor, name, nlen);
4247                         method_buffer->cursor += nlen;
4248
4249                         mono_free (name);
4250                         free (info);
4251                 }
4252
4253                 g_ptr_array_free (entry->methods, TRUE);
4254
4255                 if (new_methods) {
4256                         for (LogBuffer *iter = method_buffer; iter; iter = iter->next)
4257                                 iter->thread_id = 0;
4258
4259                         dump_buffer (prof, method_buffer);
4260                 } else if (method_buffer)
4261                         free_buffer (method_buffer, method_buffer->size);
4262
4263                 dump_buffer (prof, entry->buffer);
4264
4265                 mono_thread_hazardous_try_free (entry, free);
4266
4267                 return TRUE;
4268         }
4269
4270         return FALSE;
4271 }
4272
4273 static void *
4274 writer_thread (void *arg)
4275 {
4276         MonoProfiler *prof = (MonoProfiler *)arg;
4277
4278         mono_threads_attach_tools_thread ();
4279         mono_thread_info_set_name (mono_native_thread_id_get (), "Profiler writer");
4280
4281         dump_header (prof);
4282
4283         while (InterlockedRead (&prof->run_writer_thread)) {
4284                 mono_os_sem_wait (&prof->writer_queue_sem, MONO_SEM_FLAGS_NONE);
4285                 handle_writer_queue_entry (prof);
4286         }
4287
4288         /* Drain any remaining entries on shutdown. */
4289         while (handle_writer_queue_entry (prof));
4290
4291         mono_thread_info_detach ();
4292
4293         return NULL;
4294 }
4295
4296 static int
4297 start_writer_thread (MonoProfiler* prof)
4298 {
4299         InterlockedWrite (&prof->run_writer_thread, 1);
4300
4301         return !pthread_create (&prof->writer_thread, NULL, writer_thread, prof);
4302 }
4303
4304 static void
4305 reuse_sample_hit (gpointer p)
4306 {
4307         SampleHit *sample = p;
4308
4309         mono_lock_free_queue_node_unpoison (&sample->node);
4310         mono_lock_free_queue_enqueue (&sample->prof->sample_reuse_queue, &sample->node);
4311 }
4312
4313 static gboolean
4314 handle_dumper_queue_entry (MonoProfiler *prof)
4315 {
4316         SampleHit *sample;
4317
4318         if ((sample = (SampleHit *) mono_lock_free_queue_dequeue (&prof->dumper_queue))) {
4319                 mono_lock_free_queue_node_init (&sample->node, TRUE);
4320
4321                 for (int i = 0; i < sample->count; ++i) {
4322                         MonoMethod *method = sample->frames [i].method;
4323                         MonoDomain *domain = sample->frames [i].domain;
4324                         void *address = sample->frames [i].base_address;
4325
4326                         if (!method) {
4327                                 g_assert (domain);
4328                                 g_assert (address);
4329
4330                                 MonoJitInfo *ji = mono_jit_info_table_find (domain, (char *) address);
4331
4332                                 if (ji)
4333                                         sample->frames [i].method = mono_jit_info_get_method (ji);
4334                         }
4335                 }
4336
4337                 LogBuffer *logbuffer = ensure_logbuf (
4338                         EVENT_SIZE /* event */ +
4339                         LEB128_SIZE /* type */ +
4340                         LEB128_SIZE /* time */ +
4341                         LEB128_SIZE /* tid */ +
4342                         LEB128_SIZE /* count */ +
4343                         1 * (
4344                                 LEB128_SIZE /* ip */
4345                         ) +
4346                         LEB128_SIZE /* managed count */ +
4347                         sample->count * (
4348                                 LEB128_SIZE /* method */ +
4349                                 LEB128_SIZE /* il offset */ +
4350                                 LEB128_SIZE /* native offset */
4351                         )
4352                 );
4353
4354                 emit_byte (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_HIT);
4355                 emit_value (logbuffer, sample_type);
4356                 emit_uvalue (logbuffer, prof->startup_time + sample->elapsed * 10000);
4357                 emit_ptr (logbuffer, (void *) sample->tid);
4358                 emit_value (logbuffer, 1);
4359
4360                 // TODO: Actual native unwinding.
4361                 for (int i = 0; i < 1; ++i) {
4362                         emit_ptr (logbuffer, sample->ip);
4363                         add_code_pointer ((uintptr_t) sample->ip);
4364                 }
4365
4366                 /* new in data version 6 */
4367                 emit_uvalue (logbuffer, sample->count);
4368
4369                 for (int i = 0; i < sample->count; ++i) {
4370                         emit_method (prof, logbuffer, sample->frames [i].method);
4371                         emit_svalue (logbuffer, 0); /* il offset will always be 0 from now on */
4372                         emit_svalue (logbuffer, sample->frames [i].offset);
4373                 }
4374
4375                 mono_thread_hazardous_try_free (sample, reuse_sample_hit);
4376
4377                 dump_unmanaged_coderefs (prof);
4378
4379                 if (logbuffer->next)
4380                         safe_send_threadless (prof, logbuffer);
4381         }
4382
4383         return FALSE;
4384 }
4385
4386 static void *
4387 dumper_thread (void *arg)
4388 {
4389         MonoProfiler *prof = (MonoProfiler *)arg;
4390
4391         mono_threads_attach_tools_thread ();
4392         mono_thread_info_set_name (mono_native_thread_id_get (), "Profiler dumper");
4393
4394         while (InterlockedRead (&prof->run_dumper_thread)) {
4395                 mono_os_sem_wait (&prof->dumper_queue_sem, MONO_SEM_FLAGS_NONE);
4396                 handle_dumper_queue_entry (prof);
4397         }
4398
4399         /* Drain any remaining entries on shutdown. */
4400         while (handle_dumper_queue_entry (prof));
4401
4402         safe_send_threadless (prof, ensure_logbuf (0));
4403
4404         mono_thread_info_detach ();
4405
4406         return NULL;
4407 }
4408
4409 static int
4410 start_dumper_thread (MonoProfiler* prof)
4411 {
4412         InterlockedWrite (&prof->run_dumper_thread, 1);
4413
4414         return !pthread_create (&prof->dumper_thread, NULL, dumper_thread, prof);
4415 }
4416
4417 static void
4418 runtime_initialized (MonoProfiler *profiler)
4419 {
4420 #ifndef DISABLE_HELPER_THREAD
4421         if (hs_mode_ondemand || need_helper_thread) {
4422                 if (!start_helper_thread (profiler))
4423                         profiler->command_port = 0;
4424         }
4425 #endif
4426
4427         start_writer_thread (profiler);
4428         start_dumper_thread (profiler);
4429
4430         InterlockedWrite (&runtime_inited, 1);
4431 #ifndef DISABLE_HELPER_THREAD
4432         counters_init (profiler);
4433         counters_sample (profiler, 0, FALSE);
4434 #endif
4435         /* ensure the main thread data and startup are available soon */
4436         safe_send (profiler, ensure_logbuf (0));
4437 }
4438
4439 static MonoProfiler*
4440 create_profiler (const char *filename, GPtrArray *filters)
4441 {
4442         MonoProfiler *prof;
4443         char *nf;
4444         int force_delete = 0;
4445         prof = (MonoProfiler *)calloc (1, sizeof (MonoProfiler));
4446
4447         prof->command_port = command_port;
4448         if (filename && *filename == '-') {
4449                 force_delete = 1;
4450                 filename++;
4451         }
4452         if (!filename) {
4453                 if (do_report)
4454                         filename = "|mprof-report -";
4455                 else
4456                         filename = "output.mlpd";
4457                 nf = (char*)filename;
4458         } else {
4459                 nf = new_filename (filename);
4460                 if (do_report) {
4461                         int s = strlen (nf) + 32;
4462                         char *p = (char *)malloc (s);
4463                         snprintf (p, s, "|mprof-report '--out=%s' -", nf);
4464                         free (nf);
4465                         nf = p;
4466                 }
4467         }
4468         if (*nf == '|') {
4469                 prof->file = popen (nf + 1, "w");
4470                 prof->pipe_output = 1;
4471         } else if (*nf == '#') {
4472                 int fd = strtol (nf + 1, NULL, 10);
4473                 prof->file = fdopen (fd, "a");
4474         } else {
4475                 if (force_delete)
4476                         unlink (nf);
4477                 prof->file = fopen (nf, "wb");
4478         }
4479         if (!prof->file) {
4480                 fprintf (stderr, "Cannot create profiler output: %s\n", nf);
4481                 exit (1);
4482         }
4483 #if defined (HAVE_SYS_ZLIB)
4484         if (use_zip)
4485                 prof->gzfile = gzdopen (fileno (prof->file), "wb");
4486 #endif
4487 #if USE_PERF_EVENTS
4488         if (sample_type && !do_mono_sample)
4489                 need_helper_thread = setup_perf_event ();
4490         if (!perf_data) {
4491                 /* FIXME: warn if different freq or sample type */
4492                 do_mono_sample = 1;
4493         }
4494 #endif
4495         if (do_mono_sample) {
4496                 need_helper_thread = 1;
4497         }
4498         if (do_counters && !need_helper_thread) {
4499                 need_helper_thread = 1;
4500         }
4501
4502         /*
4503          * If you hit this assert while increasing MAX_FRAMES, you need to increase
4504          * SAMPLE_BLOCK_SIZE as well.
4505          */
4506         g_assert (SAMPLE_SLOT_SIZE (MAX_FRAMES) * 2 < LOCK_FREE_ALLOC_SB_USABLE_SIZE (SAMPLE_BLOCK_SIZE));
4507
4508         // FIXME: We should free this stuff too.
4509         mono_lock_free_allocator_init_size_class (&prof->sample_size_class, SAMPLE_SLOT_SIZE (num_frames), SAMPLE_BLOCK_SIZE);
4510         mono_lock_free_allocator_init_allocator (&prof->sample_allocator, &prof->sample_size_class);
4511
4512         mono_lock_free_queue_init (&prof->sample_reuse_queue);
4513
4514 #ifdef DISABLE_HELPER_THREAD
4515         if (hs_mode_ondemand)
4516                 fprintf (stderr, "Ondemand heapshot unavailable on this arch.\n");
4517
4518         if (do_coverage)
4519                 fprintf (stderr, "Coverage unavailable on this arch.\n");
4520
4521 #endif
4522
4523         mono_lock_free_queue_init (&prof->writer_queue);
4524         mono_os_sem_init (&prof->writer_queue_sem, 0);
4525
4526         mono_lock_free_queue_init (&prof->dumper_queue);
4527         mono_os_sem_init (&prof->dumper_queue_sem, 0);
4528
4529         mono_os_mutex_init (&prof->method_table_mutex);
4530         prof->method_table = mono_conc_hashtable_new (NULL, NULL);
4531
4532         if (do_coverage)
4533                 coverage_init (prof);
4534         prof->coverage_filters = filters;
4535
4536         prof->startup_time = current_time ();
4537         return prof;
4538 }
4539
4540 static void
4541 usage (int do_exit)
4542 {
4543         printf ("Log profiler version %d.%d (format: %d)\n", LOG_VERSION_MAJOR, LOG_VERSION_MINOR, LOG_DATA_VERSION);
4544         printf ("Usage: mono --profile=log[:OPTION1[,OPTION2...]] program.exe\n");
4545         printf ("Options:\n");
4546         printf ("\thelp                 show this usage info\n");
4547         printf ("\t[no]alloc            enable/disable recording allocation info\n");
4548         printf ("\t[no]calls            enable/disable recording enter/leave method events\n");
4549         printf ("\theapshot[=MODE]      record heap shot info (by default at each major collection)\n");
4550         printf ("\t                     MODE: every XXms milliseconds, every YYgc collections, ondemand\n");
4551         printf ("\tcounters             sample counters every 1s\n");
4552         printf ("\tsample[=TYPE]        use statistical sampling mode (by default cycles/100)\n");
4553         printf ("\t                     TYPE: cycles,instr,cacherefs,cachemiss,branches,branchmiss\n");
4554         printf ("\t                     TYPE can be followed by /FREQUENCY\n");
4555         printf ("\ttime=fast            use a faster (but more inaccurate) timer\n");
4556         printf ("\tmaxframes=NUM        collect up to NUM stack frames\n");
4557         printf ("\tcalldepth=NUM        ignore method events for call chain depth bigger than NUM\n");
4558         printf ("\toutput=FILENAME      write the data to file FILENAME (-FILENAME to overwrite)\n");
4559         printf ("\toutput=|PROGRAM      write the data to the stdin of PROGRAM\n");
4560         printf ("\t                     %%t is subtituted with date and time, %%p with the pid\n");
4561         printf ("\treport               create a report instead of writing the raw data to a file\n");
4562         printf ("\tzip                  compress the output data\n");
4563         printf ("\tport=PORTNUM         use PORTNUM for the listening command server\n");
4564         printf ("\tcoverage             enable collection of code coverage data\n");
4565         printf ("\tcovfilter=ASSEMBLY   add an assembly to the code coverage filters\n");
4566         printf ("\t                     add a + to include the assembly or a - to exclude it\n");
4567         printf ("\t                     filter=-mscorlib\n");
4568         printf ("\tcovfilter-file=FILE  use FILE to generate the list of assemblies to be filtered\n");
4569         if (do_exit)
4570                 exit (1);
4571 }
4572
4573 static const char*
4574 match_option (const char* p, const char *opt, char **rval)
4575 {
4576         int len = strlen (opt);
4577         if (strncmp (p, opt, len) == 0) {
4578                 if (rval) {
4579                         if (p [len] == '=' && p [len + 1]) {
4580                                 const char *opt = p + len + 1;
4581                                 const char *end = strchr (opt, ',');
4582                                 char *val;
4583                                 int l;
4584                                 if (end == NULL) {
4585                                         l = strlen (opt);
4586                                 } else {
4587                                         l = end - opt;
4588                                 }
4589                                 val = (char *)malloc (l + 1);
4590                                 memcpy (val, opt, l);
4591                                 val [l] = 0;
4592                                 *rval = val;
4593                                 return opt + l;
4594                         }
4595                         if (p [len] == 0 || p [len] == ',') {
4596                                 *rval = NULL;
4597                                 return p + len + (p [len] == ',');
4598                         }
4599                         usage (1);
4600                 } else {
4601                         if (p [len] == 0)
4602                                 return p + len;
4603                         if (p [len] == ',')
4604                                 return p + len + 1;
4605                 }
4606         }
4607         return p;
4608 }
4609
4610 typedef struct {
4611         const char *name;
4612         int sample_mode;
4613 } SampleMode;
4614
4615 static const SampleMode sample_modes [] = {
4616         {"cycles", SAMPLE_CYCLES},
4617         {"instr", SAMPLE_INSTRUCTIONS},
4618         {"cachemiss", SAMPLE_CACHE_MISSES},
4619         {"cacherefs", SAMPLE_CACHE_REFS},
4620         {"branches", SAMPLE_BRANCHES},
4621         {"branchmiss", SAMPLE_BRANCH_MISSES},
4622         {NULL, 0}
4623 };
4624
4625 static void
4626 set_sample_mode (char* val, int allow_empty)
4627 {
4628         char *end;
4629         char *maybe_freq = NULL;
4630         unsigned int count;
4631         const SampleMode *smode = sample_modes;
4632 #ifndef USE_PERF_EVENTS
4633         do_mono_sample = 1;
4634 #endif
4635         if (allow_empty && !val) {
4636                 sample_type = SAMPLE_CYCLES;
4637                 sample_freq = 100;
4638                 return;
4639         }
4640         if (strcmp (val, "mono") == 0) {
4641                 do_mono_sample = 1;
4642                 sample_type = SAMPLE_CYCLES;
4643                 free (val);
4644                 return;
4645         }
4646         for (smode = sample_modes; smode->name; smode++) {
4647                 int l = strlen (smode->name);
4648                 if (strncmp (val, smode->name, l) == 0) {
4649                         sample_type = smode->sample_mode;
4650                         maybe_freq = val + l;
4651                         break;
4652                 }
4653         }
4654         if (!smode->name)
4655                 usage (1);
4656         if (*maybe_freq == '/') {
4657                 count = strtoul (maybe_freq + 1, &end, 10);
4658                 if (maybe_freq + 1 == end)
4659                         usage (1);
4660                 sample_freq = count;
4661         } else if (*maybe_freq != 0) {
4662                 usage (1);
4663         } else {
4664                 sample_freq = 100;
4665         }
4666         free (val);
4667 }
4668
4669 static void
4670 set_hsmode (char* val, int allow_empty)
4671 {
4672         char *end;
4673         unsigned int count;
4674         if (allow_empty && !val)
4675                 return;
4676         if (strcmp (val, "ondemand") == 0) {
4677                 hs_mode_ondemand = 1;
4678                 free (val);
4679                 return;
4680         }
4681         count = strtoul (val, &end, 10);
4682         if (val == end)
4683                 usage (1);
4684         if (strcmp (end, "ms") == 0)
4685                 hs_mode_ms = count;
4686         else if (strcmp (end, "gc") == 0)
4687                 hs_mode_gc = count;
4688         else
4689                 usage (1);
4690         free (val);
4691 }
4692
4693 /*
4694  * declaration to silence the compiler: this is the entry point that
4695  * mono will load from the shared library and call.
4696  */
4697 extern void
4698 mono_profiler_startup (const char *desc);
4699
4700 extern void
4701 mono_profiler_startup_log (const char *desc);
4702
4703 /*
4704  * this is the entry point that will be used when the profiler
4705  * is embedded inside the main executable.
4706  */
4707 void
4708 mono_profiler_startup_log (const char *desc)
4709 {
4710         mono_profiler_startup (desc);
4711 }
4712
4713 void
4714 mono_profiler_startup (const char *desc)
4715 {
4716         MonoProfiler *prof;
4717         GPtrArray *filters = NULL;
4718         char *filename = NULL;
4719         const char *p;
4720         const char *opt;
4721         int fast_time = 0;
4722         int calls_enabled = 0;
4723         int allocs_enabled = 0;
4724         int only_counters = 0;
4725         int only_coverage = 0;
4726         int events = MONO_PROFILE_GC|MONO_PROFILE_ALLOCATIONS|
4727                 MONO_PROFILE_GC_MOVES|MONO_PROFILE_CLASS_EVENTS|MONO_PROFILE_THREADS|
4728                 MONO_PROFILE_ENTER_LEAVE|MONO_PROFILE_JIT_COMPILATION|MONO_PROFILE_EXCEPTIONS|
4729                 MONO_PROFILE_MONITOR_EVENTS|MONO_PROFILE_MODULE_EVENTS|MONO_PROFILE_GC_ROOTS|
4730                 MONO_PROFILE_INS_COVERAGE|MONO_PROFILE_APPDOMAIN_EVENTS|MONO_PROFILE_CONTEXT_EVENTS|
4731                 MONO_PROFILE_ASSEMBLY_EVENTS;
4732
4733         max_allocated_sample_hits = mono_cpu_count () * 1000;
4734
4735         mono_counters_register ("Sample hits", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &sample_hits);
4736         mono_counters_register ("Sample flushes", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &sample_flushes);
4737         mono_counters_register ("Sample events allocated", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &sample_allocations);
4738         mono_counters_register ("Log buffers allocated", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &buffer_allocations);
4739         mono_counters_register ("Thread start events", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &thread_starts);
4740         mono_counters_register ("Thread stop events", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &thread_ends);
4741         mono_counters_register ("Domain load events", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &domain_loads);
4742         mono_counters_register ("Domain unload events", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &domain_unloads);
4743         mono_counters_register ("Context load events", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &context_loads);
4744         mono_counters_register ("Context unload events", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &context_unloads);
4745         mono_counters_register ("Assembly load events", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &assembly_loads);
4746         mono_counters_register ("Assembly unload events", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &assembly_unloads);
4747         mono_counters_register ("Image load events", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &image_loads);
4748         mono_counters_register ("Image unload events", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &image_unloads);
4749         mono_counters_register ("Class load events", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &class_loads);
4750         mono_counters_register ("Class unload events", MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, &class_unloads);
4751
4752         p = desc;
4753         if (strncmp (p, "log", 3))
4754                 usage (1);
4755         p += 3;
4756         if (*p == ':')
4757                 p++;
4758         for (; *p; p = opt) {
4759                 char *val;
4760                 if (*p == ',') {
4761                         opt = p + 1;
4762                         continue;
4763                 }
4764                 if ((opt = match_option (p, "help", NULL)) != p) {
4765                         usage (0);
4766                         continue;
4767                 }
4768                 if ((opt = match_option (p, "calls", NULL)) != p) {
4769                         calls_enabled = 1;
4770                         continue;
4771                 }
4772                 if ((opt = match_option (p, "nocalls", NULL)) != p) {
4773                         events &= ~MONO_PROFILE_ENTER_LEAVE;
4774                         nocalls = 1;
4775                         continue;
4776                 }
4777                 if ((opt = match_option (p, "alloc", NULL)) != p) {
4778                         allocs_enabled = 1;
4779                         continue;
4780                 }
4781                 if ((opt = match_option (p, "noalloc", NULL)) != p) {
4782                         events &= ~MONO_PROFILE_ALLOCATIONS;
4783                         continue;
4784                 }
4785                 if ((opt = match_option (p, "time", &val)) != p) {
4786                         if (strcmp (val, "fast") == 0)
4787                                 fast_time = 1;
4788                         else if (strcmp (val, "null") == 0)
4789                                 fast_time = 2;
4790                         else
4791                                 usage (1);
4792                         free (val);
4793                         continue;
4794                 }
4795                 if ((opt = match_option (p, "report", NULL)) != p) {
4796                         do_report = 1;
4797                         continue;
4798                 }
4799                 if ((opt = match_option (p, "debug", NULL)) != p) {
4800                         do_debug = 1;
4801                         continue;
4802                 }
4803                 if ((opt = match_option (p, "sampling-real", NULL)) != p) {
4804                         sampling_mode = MONO_PROFILER_STAT_MODE_REAL;
4805                         continue;
4806                 }
4807                 if ((opt = match_option (p, "sampling-process", NULL)) != p) {
4808                         sampling_mode = MONO_PROFILER_STAT_MODE_PROCESS;
4809                         continue;
4810                 }
4811                 if ((opt = match_option (p, "heapshot", &val)) != p) {
4812                         events &= ~MONO_PROFILE_ALLOCATIONS;
4813                         events &= ~MONO_PROFILE_ENTER_LEAVE;
4814                         nocalls = 1;
4815                         do_heap_shot = 1;
4816                         set_hsmode (val, 1);
4817                         continue;
4818                 }
4819                 if ((opt = match_option (p, "sample", &val)) != p) {
4820                         events &= ~MONO_PROFILE_ALLOCATIONS;
4821                         events &= ~MONO_PROFILE_ENTER_LEAVE;
4822                         nocalls = 1;
4823                         set_sample_mode (val, 1);
4824                         continue;
4825                 }
4826                 if ((opt = match_option (p, "hsmode", &val)) != p) {
4827                         fprintf (stderr, "The hsmode profiler option is obsolete, use heapshot=MODE.\n");
4828                         set_hsmode (val, 0);
4829                         continue;
4830                 }
4831                 if ((opt = match_option (p, "zip", NULL)) != p) {
4832                         use_zip = 1;
4833                         continue;
4834                 }
4835                 if ((opt = match_option (p, "output", &val)) != p) {
4836                         filename = val;
4837                         continue;
4838                 }
4839                 if ((opt = match_option (p, "port", &val)) != p) {
4840                         char *end;
4841                         command_port = strtoul (val, &end, 10);
4842                         free (val);
4843                         continue;
4844                 }
4845                 if ((opt = match_option (p, "maxframes", &val)) != p) {
4846                         char *end;
4847                         num_frames = strtoul (val, &end, 10);
4848                         if (num_frames > MAX_FRAMES)
4849                                 num_frames = MAX_FRAMES;
4850                         free (val);
4851                         notraces = num_frames == 0;
4852                         continue;
4853                 }
4854                 if ((opt = match_option (p, "maxsamples", &val)) != p) {
4855                         char *end;
4856                         max_allocated_sample_hits = strtoul (val, &end, 10);
4857                         if (!max_allocated_sample_hits)
4858                                 max_allocated_sample_hits = G_MAXINT32;
4859                         free (val);
4860                         continue;
4861                 }
4862                 if ((opt = match_option (p, "calldepth", &val)) != p) {
4863                         char *end;
4864                         max_call_depth = strtoul (val, &end, 10);
4865                         free (val);
4866                         continue;
4867                 }
4868                 if ((opt = match_option (p, "counters", NULL)) != p) {
4869                         do_counters = 1;
4870                         continue;
4871                 }
4872                 if ((opt = match_option (p, "countersonly", NULL)) != p) {
4873                         only_counters = 1;
4874                         continue;
4875                 }
4876                 if ((opt = match_option (p, "coverage", NULL)) != p) {
4877                         do_coverage = 1;
4878                         events |= MONO_PROFILE_ENTER_LEAVE;
4879                         debug_coverage = (g_getenv ("MONO_PROFILER_DEBUG_COVERAGE") != NULL);
4880                         continue;
4881                 }
4882                 if ((opt = match_option (p, "onlycoverage", NULL)) != p) {
4883                         only_coverage = 1;
4884                         continue;
4885                 }
4886                 if ((opt = match_option (p, "covfilter-file", &val)) != p) {
4887                         FILE *filter_file;
4888                         char *line, *content;
4889
4890                         if (filters == NULL)
4891                                 filters = g_ptr_array_new ();
4892
4893                         filter_file = fopen (val, "r");
4894                         if (filter_file == NULL) {
4895                                 fprintf (stderr, "Unable to open %s\n", val);
4896                                 exit (0);
4897                         }
4898
4899                         /* Don't need to free content as it is referred to by the lines stored in @filters */
4900                         content = get_file_content (filter_file);
4901                         if (content == NULL)
4902                                 fprintf (stderr, "WARNING: %s is greater than 128kb - ignoring\n", val);
4903
4904                         while ((line = get_next_line (content, &content)))
4905                                 g_ptr_array_add (filters, g_strchug (g_strchomp (line)));
4906
4907                         fclose (filter_file);
4908                         continue;
4909                 }
4910                 if ((opt = match_option (p, "covfilter", &val)) != p) {
4911                         if (filters == NULL)
4912                                 filters = g_ptr_array_new ();
4913
4914                         g_ptr_array_add (filters, val);
4915                         continue;
4916                 }
4917                 if (opt == p) {
4918                         usage (0);
4919                         exit (0);
4920                 }
4921         }
4922         if (calls_enabled) {
4923                 events |= MONO_PROFILE_ENTER_LEAVE;
4924                 nocalls = 0;
4925         }
4926         if (allocs_enabled)
4927                 events |= MONO_PROFILE_ALLOCATIONS;
4928         if (only_counters)
4929                 events = 0;
4930         if (only_coverage)
4931                 events = MONO_PROFILE_ENTER_LEAVE | MONO_PROFILE_INS_COVERAGE;
4932
4933         utils_init (fast_time);
4934
4935         prof = create_profiler (filename, filters);
4936         if (!prof)
4937                 return;
4938
4939         init_thread ();
4940
4941         mono_profiler_install (prof, log_shutdown);
4942         mono_profiler_install_gc (gc_event, gc_resize);
4943         mono_profiler_install_allocation (gc_alloc);
4944         mono_profiler_install_gc_moves (gc_moves);
4945         mono_profiler_install_gc_roots (gc_handle, gc_roots);
4946         mono_profiler_install_appdomain (NULL, domain_loaded, domain_unloaded, NULL);
4947         mono_profiler_install_appdomain_name (domain_name);
4948         mono_profiler_install_context (context_loaded, context_unloaded);
4949         mono_profiler_install_class (NULL, class_loaded, class_unloaded, NULL);
4950         mono_profiler_install_module (NULL, image_loaded, image_unloaded, NULL);
4951         mono_profiler_install_assembly (NULL, assembly_loaded, assembly_unloaded, NULL);
4952         mono_profiler_install_thread (thread_start, thread_end);
4953         mono_profiler_install_thread_name (thread_name);
4954         mono_profiler_install_enter_leave (method_enter, method_leave);
4955         mono_profiler_install_jit_end (method_jitted);
4956         mono_profiler_install_code_buffer_new (code_buffer_new);
4957         mono_profiler_install_exception (throw_exc, method_exc_leave, clause_exc);
4958         mono_profiler_install_monitor (monitor_event);
4959         mono_profiler_install_runtime_initialized (runtime_initialized);
4960         if (do_coverage)
4961                 mono_profiler_install_coverage_filter (coverage_filter);
4962
4963         if (do_mono_sample && sample_type == SAMPLE_CYCLES && !only_counters) {
4964                 events |= MONO_PROFILE_STATISTICAL;
4965                 mono_profiler_set_statistical_mode (sampling_mode, sample_freq);
4966                 mono_profiler_install_statistical (mono_sample_hit);
4967         }
4968
4969         mono_profiler_set_events ((MonoProfileFlags)events);
4970
4971         TLS_INIT (tlsbuffer);
4972         TLS_INIT (tlsmethodlist);
4973 }