2 * mono-profiler-log.c: mono log profiler
5 * Paolo Molaro (lupus@ximian.com)
6 * Alex Rønne Petersen (alexrp@xamarin.com)
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.
14 #include <mono/metadata/assembly.h>
15 #include <mono/metadata/debug-helpers.h>
16 #include "../metadata/metadata-internals.h"
17 #include <mono/metadata/mono-config.h>
18 #include <mono/metadata/mono-gc.h>
19 #include <mono/metadata/mono-perfcounters.h>
20 #include <mono/utils/atomic.h>
21 #include <mono/utils/hazard-pointer.h>
22 #include <mono/utils/lock-free-alloc.h>
23 #include <mono/utils/lock-free-queue.h>
24 #include <mono/utils/mono-conc-hashtable.h>
25 #include <mono/utils/mono-counters.h>
26 #include <mono/utils/mono-logger-internals.h>
27 #include <mono/utils/mono-linked-list-set.h>
28 #include <mono/utils/mono-membar.h>
29 #include <mono/utils/mono-mmap.h>
30 #include <mono/utils/mono-os-mutex.h>
31 #include <mono/utils/mono-os-semaphore.h>
32 #include <mono/utils/mono-threads.h>
33 #include <mono/utils/mono-threads-api.h>
46 #if defined(__APPLE__)
47 #include <mach/mach_time.h>
49 #include <netinet/in.h>
50 #ifdef HAVE_SYS_MMAN_H
53 #include <sys/socket.h>
54 #if defined (HAVE_SYS_ZLIB)
62 * The file is composed by a header followed by 0 or more buffers.
63 * Each buffer contains events that happened on a thread: for a given thread
64 * buffers that appear later in the file are guaranteed to contain events
65 * that happened later in time. Buffers from separate threads could be interleaved,
67 * Buffers are not required to be aligned.
70 * [id: 4 bytes] constant value: LOG_HEADER_ID
71 * [major: 1 byte] [minor: 1 byte] major and minor version of the log profiler
72 * [format: 1 byte] version of the data format for the rest of the file
73 * [ptrsize: 1 byte] size in bytes of a pointer in the profiled program
74 * [startup time: 8 bytes] time in milliseconds since the unix epoch when the program started
75 * [timer overhead: 4 bytes] approximate overhead in nanoseconds of the timer
76 * [flags: 4 bytes] file format flags, should be 0 for now
77 * [pid: 4 bytes] pid of the profiled process
78 * [port: 2 bytes] tcp port for server if != 0
79 * [args size: 4 bytes] size of args
80 * [args: string] arguments passed to the profiler
81 * [arch size: 4 bytes] size of arch
82 * [arch: string] architecture the profiler is running on
83 * [os size: 4 bytes] size of os
84 * [os: string] operating system the profiler is running on
86 * The multiple byte integers are in little-endian format.
89 * [buffer header] [event]*
90 * Buffers have a fixed-size header followed by 0 or more bytes of event data.
91 * Timing information and other values in the event data are usually stored
92 * as uleb128 or sleb128 integers. To save space, as noted for each item below,
93 * some data is represented as a difference between the actual value and
94 * either the last value of the same type (like for timing information) or
95 * as the difference from a value stored in a buffer header.
97 * For timing information the data is stored as uleb128, since timing
98 * increases in a monotonic way in each thread: the value is the number of
99 * nanoseconds to add to the last seen timing data in a buffer. The first value
100 * in a buffer will be calculated from the time_base field in the buffer head.
102 * Object or heap sizes are stored as uleb128.
103 * Pointer differences are stored as sleb128, instead.
105 * If an unexpected value is found, the rest of the buffer should be ignored,
106 * as generally the later values need the former to be interpreted correctly.
108 * buffer header format:
109 * [bufid: 4 bytes] constant value: BUF_ID
110 * [len: 4 bytes] size of the data following the buffer header
111 * [time_base: 8 bytes] time base in nanoseconds since an unspecified epoch
112 * [ptr_base: 8 bytes] base value for pointers
113 * [obj_base: 8 bytes] base value for object addresses
114 * [thread id: 8 bytes] system-specific thread ID (pthread_t for example)
115 * [method_base: 8 bytes] base value for MonoMethod pointers
118 * [extended info: upper 4 bits] [type: lower 4 bits]
119 * [time diff: uleb128] nanoseconds since last timing
121 * The data that follows depends on type and the extended info.
122 * Type is one of the enum values in mono-profiler-log.h: TYPE_ALLOC, TYPE_GC,
123 * TYPE_METADATA, TYPE_METHOD, TYPE_EXCEPTION, TYPE_MONITOR, TYPE_HEAP.
124 * The extended info bits are interpreted based on type, see
125 * each individual event description below.
126 * strings are represented as a 0-terminated utf8 sequence.
129 * [num: uleb128] number of frames following
130 * [frame: sleb128]* mum MonoMethod* as a pointer difference from the last such
131 * pointer or the buffer method_base
135 * exinfo: zero or TYPE_ALLOC_BT
136 * [ptr: sleb128] class as a byte difference from ptr_base
137 * [obj: sleb128] object address as a byte difference from obj_base
138 * [size: uleb128] size of the object in the heap
139 * If exinfo == TYPE_ALLOC_BT, a backtrace follows.
143 * exinfo: one of TYPE_GC_EVENT, TYPE_GC_RESIZE, TYPE_GC_MOVE, TYPE_GC_HANDLE_CREATED[_BT],
144 * TYPE_GC_HANDLE_DESTROYED[_BT], TYPE_GC_FINALIZE_START, TYPE_GC_FINALIZE_END,
145 * TYPE_GC_FINALIZE_OBJECT_START, TYPE_GC_FINALIZE_OBJECT_END
146 * if exinfo == TYPE_GC_RESIZE
147 * [heap_size: uleb128] new heap size
148 * if exinfo == TYPE_GC_EVENT
149 * [event type: byte] GC event (MONO_GC_EVENT_* from profiler.h)
150 * [generation: byte] GC generation event refers to
151 * if exinfo == TYPE_GC_MOVE
152 * [num_objects: uleb128] number of object moves that follow
153 * [objaddr: sleb128]+ num_objects object pointer differences from obj_base
154 * num is always an even number: the even items are the old
155 * addresses, the odd numbers are the respective new object addresses
156 * if exinfo == TYPE_GC_HANDLE_CREATED[_BT]
157 * [handle_type: uleb128] MonoGCHandleType enum value
158 * upper bits reserved as flags
159 * [handle: uleb128] GC handle value
160 * [objaddr: sleb128] object pointer differences from obj_base
161 * If exinfo == TYPE_GC_HANDLE_CREATED_BT, a backtrace follows.
162 * if exinfo == TYPE_GC_HANDLE_DESTROYED[_BT]
163 * [handle_type: uleb128] MonoGCHandleType enum value
164 * upper bits reserved as flags
165 * [handle: uleb128] GC handle value
166 * If exinfo == TYPE_GC_HANDLE_DESTROYED_BT, a backtrace follows.
167 * if exinfo == TYPE_GC_FINALIZE_OBJECT_{START,END}
168 * [object: sleb128] the object as a difference from obj_base
170 * type metadata format:
171 * type: TYPE_METADATA
172 * exinfo: one of: TYPE_END_LOAD, TYPE_END_UNLOAD (optional for TYPE_THREAD and TYPE_DOMAIN,
173 * doesn't occur for TYPE_CLASS)
174 * [mtype: byte] metadata type, one of: TYPE_CLASS, TYPE_IMAGE, TYPE_ASSEMBLY, TYPE_DOMAIN,
175 * TYPE_THREAD, TYPE_CONTEXT
176 * [pointer: sleb128] pointer of the metadata type depending on mtype
177 * if mtype == TYPE_CLASS
178 * [image: sleb128] MonoImage* as a pointer difference from ptr_base
179 * [name: string] full class name
180 * if mtype == TYPE_IMAGE
181 * [name: string] image file name
182 * if mtype == TYPE_ASSEMBLY
183 * [image: sleb128] MonoImage* as a pointer difference from ptr_base
184 * [name: string] assembly name
185 * if mtype == TYPE_DOMAIN && exinfo == 0
186 * [name: string] domain friendly name
187 * if mtype == TYPE_CONTEXT
188 * [domain: sleb128] domain id as pointer
189 * if mtype == TYPE_THREAD && exinfo == 0
190 * [name: string] thread name
192 * type method format:
194 * exinfo: one of: TYPE_LEAVE, TYPE_ENTER, TYPE_EXC_LEAVE, TYPE_JIT
195 * [method: sleb128] MonoMethod* as a pointer difference from the last such
196 * pointer or the buffer method_base
197 * if exinfo == TYPE_JIT
198 * [code address: sleb128] pointer to the native code as a diff from ptr_base
199 * [code size: uleb128] size of the generated code
200 * [name: string] full method name
202 * type exception format:
203 * type: TYPE_EXCEPTION
204 * exinfo: zero, TYPE_CLAUSE, or TYPE_THROW_BT
205 * if exinfo == TYPE_CLAUSE
206 * [clause type: byte] MonoExceptionEnum enum value
207 * [clause index: uleb128] index of the current clause
208 * [method: sleb128] MonoMethod* as a pointer difference from the last such
209 * pointer or the buffer method_base
210 * [object: sleb128] the exception object as a difference from obj_base
212 * [object: sleb128] the exception object as a difference from obj_base
213 * If exinfo == TYPE_THROW_BT, a backtrace follows.
215 * type runtime format:
217 * exinfo: one of: TYPE_JITHELPER
218 * if exinfo == TYPE_JITHELPER
219 * [type: byte] MonoProfilerCodeBufferType enum value
220 * [buffer address: sleb128] pointer to the native code as a diff from ptr_base
221 * [buffer size: uleb128] size of the generated code
222 * if type == MONO_PROFILER_CODE_BUFFER_SPECIFIC_TRAMPOLINE
223 * [name: string] buffer description name
225 * type monitor format:
227 * exinfo: zero or TYPE_MONITOR_BT
228 * [type: byte] MonoProfilerMonitorEvent enum value
229 * [object: sleb128] the lock object as a difference from obj_base
230 * If exinfo == TYPE_MONITOR_BT, a backtrace follows.
234 * exinfo: one of TYPE_HEAP_START, TYPE_HEAP_END, TYPE_HEAP_OBJECT, TYPE_HEAP_ROOT
235 * if exinfo == TYPE_HEAP_OBJECT
236 * [object: sleb128] the object as a difference from obj_base
237 * [class: sleb128] the object MonoClass* as a difference from ptr_base
238 * [size: uleb128] size of the object on the heap
239 * [num_refs: uleb128] number of object references
240 * each referenced objref is preceded by a uleb128 encoded offset: the
241 * first offset is from the object address and each next offset is relative
242 * to the previous one
243 * [objrefs: sleb128]+ object referenced as a difference from obj_base
244 * The same object can appear multiple times, but only the first time
245 * with size != 0: in the other cases this data will only be used to
246 * provide additional referenced objects.
247 * if exinfo == TYPE_HEAP_ROOT
248 * [num_roots: uleb128] number of root references
249 * [num_gc: uleb128] number of major gcs
250 * [object: sleb128] the object as a difference from obj_base
251 * [root_type: byte] the root_type: MonoProfileGCRootType (profiler.h)
252 * [extra_info: uleb128] the extra_info value
253 * object, root_type and extra_info are repeated num_roots times
257 * exinfo: one of TYPE_SAMPLE_HIT, TYPE_SAMPLE_USYM, TYPE_SAMPLE_UBIN, TYPE_SAMPLE_COUNTERS_DESC, TYPE_SAMPLE_COUNTERS
258 * if exinfo == TYPE_SAMPLE_HIT
259 * [thread: sleb128] thread id as difference from ptr_base
260 * [count: uleb128] number of following instruction addresses
261 * [ip: sleb128]* instruction pointer as difference from ptr_base
262 * [mbt_count: uleb128] number of managed backtrace frames
263 * [method: sleb128]* MonoMethod* as a pointer difference from the last such
264 * pointer or the buffer method_base (the first such method can be also indentified by ip, but this is not neccessarily true)
265 * if exinfo == TYPE_SAMPLE_USYM
266 * [address: sleb128] symbol address as a difference from ptr_base
267 * [size: uleb128] symbol size (may be 0 if unknown)
268 * [name: string] symbol name
269 * if exinfo == TYPE_SAMPLE_UBIN
270 * [address: sleb128] address where binary has been loaded as a difference from ptr_base
271 * [offset: uleb128] file offset of mapping (the same file can be mapped multiple times)
272 * [size: uleb128] memory size
273 * [name: string] binary name
274 * if exinfo == TYPE_SAMPLE_COUNTERS_DESC
275 * [len: uleb128] number of counters
277 * [section: uleb128] section of counter
278 * if section == MONO_COUNTER_PERFCOUNTERS:
279 * [section_name: string] section name of counter
280 * [name: string] name of counter
281 * [type: byte] type of counter
282 * [unit: byte] unit of counter
283 * [variance: byte] variance of counter
284 * [index: uleb128] unique index of counter
285 * if exinfo == TYPE_SAMPLE_COUNTERS
287 * [index: uleb128] unique index of counter
290 * [type: byte] type of counter value
293 * [0: byte] 0 -> value is null
295 * [1: byte] 1 -> value is not null
296 * [value: string] counter value
298 * [value: uleb128/sleb128/double] counter value, can be sleb128, uleb128 or double (determined by using type)
300 * type coverage format
301 * type: TYPE_COVERAGE
302 * exinfo: one of TYPE_COVERAGE_METHOD, TYPE_COVERAGE_STATEMENT, TYPE_COVERAGE_ASSEMBLY, TYPE_COVERAGE_CLASS
303 * if exinfo == TYPE_COVERAGE_METHOD
304 * [assembly: string] name of assembly
305 * [class: string] name of the class
306 * [name: string] name of the method
307 * [signature: string] the signature of the method
308 * [filename: string] the file path of the file that contains this method
309 * [token: uleb128] the method token
310 * [method_id: uleb128] an ID for this data to associate with the buffers of TYPE_COVERAGE_STATEMENTS
311 * [len: uleb128] the number of TYPE_COVERAGE_BUFFERS associated with this method
312 * if exinfo == TYPE_COVERAGE_STATEMENTS
313 * [method_id: uleb128] an the TYPE_COVERAGE_METHOD buffer to associate this with
314 * [offset: uleb128] the il offset relative to the previous offset
315 * [counter: uleb128] the counter for this instruction
316 * [line: uleb128] the line of filename containing this instruction
317 * [column: uleb128] the column containing this instruction
318 * if exinfo == TYPE_COVERAGE_ASSEMBLY
319 * [name: string] assembly name
320 * [guid: string] assembly GUID
321 * [filename: string] assembly filename
322 * [number_of_methods: uleb128] the number of methods in this assembly
323 * [fully_covered: uleb128] the number of fully covered methods
324 * [partially_covered: uleb128] the number of partially covered methods
325 * currently partially_covered will always be 0, and fully_covered is the
326 * number of methods that are fully and partially covered.
327 * if exinfo == TYPE_COVERAGE_CLASS
328 * [name: string] assembly name
329 * [class: string] class name
330 * [number_of_methods: uleb128] the number of methods in this class
331 * [fully_covered: uleb128] the number of fully covered methods
332 * [partially_covered: uleb128] the number of partially covered methods
333 * currently partially_covered will always be 0, and fully_covered is the
334 * number of methods that are fully and partially covered.
338 * exinfo: one of: TYPE_SYNC_POINT
339 * if exinfo == TYPE_SYNC_POINT
340 * [type: byte] MonoProfilerSyncPointType enum value
343 // Statistics for internal profiler data structures.
344 static gint32 sample_allocations_ctr,
345 buffer_allocations_ctr;
347 // Statistics for profiler events.
348 static gint32 sync_points_ctr,
357 gc_handle_creations_ctr,
358 gc_handle_deletions_ctr,
361 finalize_object_begins_ctr,
362 finalize_object_ends_ctr,
366 assembly_unloads_ctr,
371 method_exception_exits_ctr,
374 exception_throws_ctr,
375 exception_clauses_ctr,
388 counter_descriptors_ctr,
390 perfcounter_descriptors_ctr,
391 perfcounter_samples_ctr,
392 coverage_methods_ctr,
393 coverage_statements_ctr,
394 coverage_classes_ctr,
395 coverage_assemblies_ctr;
397 // Pending data to be written to the log, for a single thread.
398 // Threads periodically flush their own LogBuffers by calling safe_send
399 typedef struct _LogBuffer LogBuffer;
401 // Next (older) LogBuffer in processing queue
407 uintptr_t method_base;
408 uintptr_t last_method;
412 // Bytes allocated for this LogBuffer
415 // Start of currently unused space in buffer
416 unsigned char* cursor;
418 // Pointer to start-of-structure-plus-size (for convenience)
419 unsigned char* buf_end;
421 // Start of data in buffer. Contents follow "buffer format" described above.
422 unsigned char buf [1];
426 MonoLinkedListSetNode node;
428 // Was this thread added to the LLS?
431 // The current log buffer for this thread.
434 // Methods referenced by events in `buffer`, see `MethodInfo`.
437 // Current call depth for enter/leave events.
440 // Indicates whether this thread is currently writing to its `buffer`.
443 // Has this thread written a thread end event to `buffer`?
446 // Stored in `buffer_lock_state` to take the exclusive lock.
448 } MonoProfilerThread;
450 // Do not use these TLS macros directly unless you know what you're doing.
454 #define PROF_TLS_SET(VAL) (TlsSetValue (profiler_tls, (VAL)))
455 #define PROF_TLS_GET() ((MonoProfilerThread *) TlsGetValue (profiler_tls))
456 #define PROF_TLS_INIT() (profiler_tls = TlsAlloc ())
457 #define PROF_TLS_FREE() (TlsFree (profiler_tls))
459 static DWORD profiler_tls;
463 #define PROF_TLS_SET(VAL) (profiler_tls = (VAL))
464 #define PROF_TLS_GET() (profiler_tls)
465 #define PROF_TLS_INIT()
466 #define PROF_TLS_FREE()
468 static __thread MonoProfilerThread *profiler_tls;
472 #define PROF_TLS_SET(VAL) (pthread_setspecific (profiler_tls, (VAL)))
473 #define PROF_TLS_GET() ((MonoProfilerThread *) pthread_getspecific (profiler_tls))
474 #define PROF_TLS_INIT() (pthread_key_create (&profiler_tls, NULL))
475 #define PROF_TLS_FREE() (pthread_key_delete (profiler_tls))
477 static pthread_key_t profiler_tls;
484 return (uintptr_t) mono_native_thread_id_get ();
491 return (uintptr_t) GetCurrentProcessId ();
493 return (uintptr_t) getpid ();
497 #define ENABLED(EVT) (log_config.effective_mask & (EVT))
500 * These macros should be used when writing an event to a log buffer. They
501 * take care of a bunch of stuff that can be repetitive and error-prone, such
502 * as attaching the current thread, acquiring/releasing the buffer lock,
503 * incrementing the event counter, expanding the log buffer, etc. They also
504 * create a scope so that it's harder to leak the LogBuffer pointer, which can
505 * be problematic as the pointer is unstable when the buffer lock isn't
508 * If the calling thread is already attached, these macros will not alter its
509 * attach mode (i.e. whether it's added to the LLS). If the thread is not
510 * attached, init_thread () will be called with add_to_lls = TRUE.
513 #define ENTER_LOG(COUNTER, BUFFER, SIZE) \
515 MonoProfilerThread *thread__ = get_thread (); \
516 if (thread__->attached) \
518 g_assert (!thread__->busy && "Why are we trying to write a new event while already writing one?"); \
519 thread__->busy = TRUE; \
520 InterlockedIncrement ((COUNTER)); \
521 LogBuffer *BUFFER = ensure_logbuf_unsafe (thread__, (SIZE))
523 #define EXIT_LOG_EXPLICIT(SEND) \
524 thread__->busy = FALSE; \
526 send_log_unsafe (TRUE); \
527 if (thread__->attached) \
531 // Pass these to EXIT_LOG_EXPLICIT () for easier reading.
533 #define NO_SEND FALSE
535 #define EXIT_LOG EXIT_LOG_EXPLICIT (DO_SEND)
537 typedef struct _BinaryObject BinaryObject;
538 struct _BinaryObject {
544 typedef struct MonoCounterAgent {
545 MonoCounter *counter;
546 // MonoCounterAgent specific data :
551 struct MonoCounterAgent *next;
554 typedef struct _PerfCounterAgent PerfCounterAgent;
555 struct _PerfCounterAgent {
556 PerfCounterAgent *next;
567 struct _MonoProfiler {
568 MonoProfilerHandle handle;
571 #if defined (HAVE_SYS_ZLIB)
576 uint64_t startup_time;
580 mach_timebase_info_data_t timebase_info;
581 #elif defined (HOST_WIN32)
582 LARGE_INTEGER pcounter_freq;
590 MonoLinkedListSet profiler_thread_list;
591 volatile gint32 buffer_lock_state;
592 volatile gint32 buffer_lock_exclusive_intent;
594 volatile gint32 runtime_inited;
595 volatile gint32 in_shutdown;
597 MonoNativeThreadId helper_thread;
599 MonoNativeThreadId writer_thread;
600 volatile gint32 run_writer_thread;
601 MonoLockFreeQueue writer_queue;
602 MonoSemType writer_queue_sem;
604 MonoLockFreeAllocSizeClass writer_entry_size_class;
605 MonoLockFreeAllocator writer_entry_allocator;
607 MonoConcurrentHashTable *method_table;
608 mono_mutex_t method_table_mutex;
610 MonoNativeThreadId dumper_thread;
611 volatile gint32 run_dumper_thread;
612 MonoLockFreeQueue dumper_queue;
613 MonoSemType dumper_queue_sem;
615 MonoLockFreeAllocSizeClass sample_size_class;
616 MonoLockFreeAllocator sample_allocator;
617 MonoLockFreeQueue sample_reuse_queue;
619 BinaryObject *binary_objects;
621 gboolean heapshot_requested;
623 guint64 last_hs_time;
624 gboolean do_heap_walk;
625 gboolean ignore_heap_events;
627 mono_mutex_t counters_mutex;
628 MonoCounterAgent *counters;
629 PerfCounterAgent *perfcounters;
630 guint32 counters_index;
632 mono_mutex_t coverage_mutex;
633 GPtrArray *coverage_data;
635 GPtrArray *coverage_filters;
636 MonoConcurrentHashTable *coverage_filtered_classes;
637 MonoConcurrentHashTable *coverage_suppressed_assemblies;
639 MonoConcurrentHashTable *coverage_methods;
640 MonoConcurrentHashTable *coverage_assemblies;
641 MonoConcurrentHashTable *coverage_classes;
643 MonoConcurrentHashTable *coverage_image_to_methods;
645 guint32 coverage_previous_offset;
646 guint32 coverage_method_id;
649 static ProfilerConfig log_config;
650 static struct _MonoProfiler log_profiler;
653 MonoLockFreeQueueNode node;
658 #define WRITER_ENTRY_BLOCK_SIZE (mono_pagesize ())
666 #define TICKS_PER_SEC 1000000000LL
672 uint64_t time = mach_absolute_time ();
674 time *= log_profiler.timebase_info.numer;
675 time /= log_profiler.timebase_info.denom;
678 #elif defined (HOST_WIN32)
681 QueryPerformanceCounter (&value);
683 return value.QuadPart * TICKS_PER_SEC / log_profiler.pcounter_freq.QuadPart;
684 #elif defined (CLOCK_MONOTONIC)
685 struct timespec tspec;
687 clock_gettime (CLOCK_MONOTONIC, &tspec);
689 return ((uint64_t) tspec.tv_sec * TICKS_PER_SEC + tspec.tv_nsec);
693 gettimeofday (&tv, NULL);
695 return ((uint64_t) tv.tv_sec * TICKS_PER_SEC + tv.tv_usec * 1000);
703 mach_timebase_info (&log_profiler.timebase_info);
704 #elif defined (HOST_WIN32)
705 QueryPerformanceFrequency (&log_profiler.pcounter_freq);
708 uint64_t time_start = current_time ();
710 for (int i = 0; i < 256; ++i)
713 uint64_t time_end = current_time ();
715 log_profiler.timer_overhead = (time_end - time_start) / 256;
719 pstrdup (const char *s)
721 int len = strlen (s) + 1;
722 char *p = (char *) g_malloc (len);
727 #define BUFFER_SIZE (4096 * 16)
729 /* Worst-case size in bytes of a 64-bit value encoded with LEB128. */
730 #define LEB128_SIZE 10
732 /* Size of a value encoded as a single byte. */
733 #undef BYTE_SIZE // mach/i386/vm_param.h on OS X defines this to 8, but it isn't used for anything.
736 /* Size in bytes of the event prefix (ID + time). */
737 #define EVENT_SIZE (BYTE_SIZE + LEB128_SIZE)
740 alloc_buffer (int size)
742 return mono_valloc (NULL, size, MONO_MMAP_READ | MONO_MMAP_WRITE | MONO_MMAP_ANON | MONO_MMAP_PRIVATE, MONO_MEM_ACCOUNT_PROFILER);
746 free_buffer (void *buf, int size)
748 mono_vfree (buf, size, MONO_MEM_ACCOUNT_PROFILER);
752 create_buffer (uintptr_t tid, int bytes)
754 LogBuffer* buf = (LogBuffer *) alloc_buffer (MAX (BUFFER_SIZE, bytes));
756 InterlockedIncrement (&buffer_allocations_ctr);
758 buf->size = BUFFER_SIZE;
759 buf->time_base = current_time ();
760 buf->last_time = buf->time_base;
761 buf->buf_end = (unsigned char *) buf + buf->size;
762 buf->cursor = buf->buf;
763 buf->thread_id = tid;
769 * Must be called with the reader lock held if thread is the current thread, or
770 * the exclusive lock if thread is a different thread. However, if thread is
771 * the current thread, and init_thread () was called with add_to_lls = FALSE,
772 * then no locking is necessary.
775 init_buffer_state (MonoProfilerThread *thread)
777 thread->buffer = create_buffer (thread->node.key, 0);
778 thread->methods = NULL;
782 clear_hazard_pointers (MonoThreadHazardPointers *hp)
784 mono_hazard_pointer_clear (hp, 0);
785 mono_hazard_pointer_clear (hp, 1);
786 mono_hazard_pointer_clear (hp, 2);
789 static MonoProfilerThread *
790 init_thread (gboolean add_to_lls)
792 MonoProfilerThread *thread = PROF_TLS_GET ();
795 * Sometimes we may try to initialize a thread twice. One example is the
796 * main thread: We initialize it when setting up the profiler, but we will
797 * also get a thread_start () callback for it. Another example is when
798 * attaching new threads to the runtime: We may get a gc_alloc () callback
799 * for that thread's thread object (where we initialize it), soon followed
800 * by a thread_start () callback.
802 * These cases are harmless anyhow. Just return if we've already done the
803 * initialization work.
808 thread = g_malloc (sizeof (MonoProfilerThread));
809 thread->node.key = thread_id ();
810 thread->attached = add_to_lls;
811 thread->call_depth = 0;
813 thread->ended = FALSE;
815 init_buffer_state (thread);
817 thread->small_id = mono_thread_info_register_small_id ();
820 * Some internal profiler threads don't need to be cleaned up
821 * by the main thread on shutdown.
824 MonoThreadHazardPointers *hp = mono_hazard_pointer_get ();
825 g_assert (mono_lls_insert (&log_profiler.profiler_thread_list, hp, &thread->node) && "Why can't we insert the thread in the LLS?");
826 clear_hazard_pointers (hp);
829 PROF_TLS_SET (thread);
834 // Only valid if init_thread () was called with add_to_lls = FALSE.
836 deinit_thread (MonoProfilerThread *thread)
838 g_assert (!thread->attached && "Why are we manually freeing an attached thread?");
844 static MonoProfilerThread *
847 return init_thread (TRUE);
850 // Only valid if init_thread () was called with add_to_lls = FALSE.
852 ensure_logbuf_unsafe (MonoProfilerThread *thread, int bytes)
854 LogBuffer *old = thread->buffer;
856 if (old->cursor + bytes < old->buf_end)
859 LogBuffer *new_ = create_buffer (thread->node.key, bytes);
861 thread->buffer = new_;
867 * This is a reader/writer spin lock of sorts used to protect log buffers.
868 * When a thread modifies its own log buffer, it increments the reader
869 * count. When a thread wants to access log buffers of other threads, it
870 * takes the exclusive lock.
872 * `buffer_lock_state` holds the reader count in its lower 16 bits, and
873 * the small ID of the thread currently holding the exclusive (writer)
874 * lock in its upper 16 bits. Both can be zero. It's important that the
875 * whole lock state is a single word that can be read/written atomically
876 * to avoid race conditions where there could end up being readers while
877 * the writer lock is held.
879 * The lock is writer-biased. When a thread wants to take the exclusive
880 * lock, it increments `buffer_lock_exclusive_intent` which will make new
881 * readers spin until it's back to zero, then takes the exclusive lock
882 * once the reader count has reached zero. After releasing the exclusive
883 * lock, it decrements `buffer_lock_exclusive_intent`, which, when it
884 * reaches zero again, allows readers to increment the reader count.
886 * The writer bias is necessary because we take the exclusive lock in
887 * `gc_event ()` during STW. If the writer bias was not there, and a
888 * program had a large number of threads, STW-induced pauses could be
889 * significantly longer than they have to be. Also, we emit periodic
890 * sync points from the helper thread, which requires taking the
891 * exclusive lock, and we need those to arrive with a reasonably
892 * consistent frequency so that readers don't have to queue up too many
893 * events between sync points.
895 * The lock does not support recursion.
902 * If the thread holding the exclusive lock tries to modify the
903 * reader count, just make it a no-op. This way, we also avoid
904 * invoking the GC safe point macros below, which could break if
905 * done from a thread that is currently the initiator of STW.
907 * In other words, we rely on the fact that the GC thread takes
908 * the exclusive lock in the gc_event () callback when the world
911 if (InterlockedRead (&log_profiler.buffer_lock_state) != get_thread ()->small_id << 16) {
918 // Hold off if a thread wants to take the exclusive lock.
919 while (InterlockedRead (&log_profiler.buffer_lock_exclusive_intent))
920 mono_thread_info_yield ();
922 old = InterlockedRead (&log_profiler.buffer_lock_state);
924 // Is a thread holding the exclusive lock?
926 mono_thread_info_yield ();
931 } while (InterlockedCompareExchange (&log_profiler.buffer_lock_state, new_, old) != old);
936 mono_memory_barrier ();
942 mono_memory_barrier ();
944 gint32 state = InterlockedRead (&log_profiler.buffer_lock_state);
946 // See the comment in buffer_lock ().
947 if (state == PROF_TLS_GET ()->small_id << 16)
950 g_assert (state && "Why are we decrementing a zero reader count?");
951 g_assert (!(state >> 16) && "Why is the exclusive lock held?");
953 InterlockedDecrement (&log_profiler.buffer_lock_state);
957 buffer_lock_excl (void)
959 gint32 new_ = get_thread ()->small_id << 16;
961 g_assert (InterlockedRead (&log_profiler.buffer_lock_state) != new_ && "Why are we taking the exclusive lock twice?");
963 InterlockedIncrement (&log_profiler.buffer_lock_exclusive_intent);
967 while (InterlockedCompareExchange (&log_profiler.buffer_lock_state, new_, 0))
968 mono_thread_info_yield ();
972 mono_memory_barrier ();
976 buffer_unlock_excl (void)
978 mono_memory_barrier ();
980 gint32 state = InterlockedRead (&log_profiler.buffer_lock_state);
981 gint32 excl = state >> 16;
983 g_assert (excl && "Why is the exclusive lock not held?");
984 g_assert (excl == PROF_TLS_GET ()->small_id && "Why does another thread hold the exclusive lock?");
985 g_assert (!(state & 0xFFFF) && "Why are there readers when the exclusive lock is held?");
987 InterlockedWrite (&log_profiler.buffer_lock_state, 0);
988 InterlockedDecrement (&log_profiler.buffer_lock_exclusive_intent);
992 encode_uleb128 (uint64_t value, uint8_t *buf, uint8_t **endbuf)
997 uint8_t b = value & 0x7f;
1000 if (value != 0) /* more bytes to come */
1010 encode_sleb128 (intptr_t value, uint8_t *buf, uint8_t **endbuf)
1013 int negative = (value < 0);
1014 unsigned int size = sizeof (intptr_t) * 8;
1019 byte = value & 0x7f;
1022 /* the following is unnecessary if the
1023 * implementation of >>= uses an arithmetic rather
1024 * than logical shift for a signed left operand
1028 value |= - ((intptr_t) 1 <<(size - 7));
1030 /* sign bit of byte is second high order bit (0x40) */
1031 if ((value == 0 && !(byte & 0x40)) ||
1032 (value == -1 && (byte & 0x40)))
1044 emit_byte (LogBuffer *logbuffer, int value)
1046 logbuffer->cursor [0] = value;
1047 logbuffer->cursor++;
1049 g_assert (logbuffer->cursor <= logbuffer->buf_end && "Why are we writing past the buffer end?");
1053 emit_value (LogBuffer *logbuffer, int value)
1055 encode_uleb128 (value, logbuffer->cursor, &logbuffer->cursor);
1057 g_assert (logbuffer->cursor <= logbuffer->buf_end && "Why are we writing past the buffer end?");
1061 emit_time (LogBuffer *logbuffer, uint64_t value)
1063 uint64_t tdiff = value - logbuffer->last_time;
1064 encode_uleb128 (tdiff, logbuffer->cursor, &logbuffer->cursor);
1065 logbuffer->last_time = value;
1067 g_assert (logbuffer->cursor <= logbuffer->buf_end && "Why are we writing past the buffer end?");
1071 emit_event_time (LogBuffer *logbuffer, int event, uint64_t time)
1073 emit_byte (logbuffer, event);
1074 emit_time (logbuffer, time);
1078 emit_event (LogBuffer *logbuffer, int event)
1080 emit_event_time (logbuffer, event, current_time ());
1084 emit_svalue (LogBuffer *logbuffer, int64_t value)
1086 encode_sleb128 (value, logbuffer->cursor, &logbuffer->cursor);
1088 g_assert (logbuffer->cursor <= logbuffer->buf_end && "Why are we writing past the buffer end?");
1092 emit_uvalue (LogBuffer *logbuffer, uint64_t value)
1094 encode_uleb128 (value, logbuffer->cursor, &logbuffer->cursor);
1096 g_assert (logbuffer->cursor <= logbuffer->buf_end && "Why are we writing past the buffer end?");
1100 emit_ptr (LogBuffer *logbuffer, const void *ptr)
1102 if (!logbuffer->ptr_base)
1103 logbuffer->ptr_base = (uintptr_t) ptr;
1105 emit_svalue (logbuffer, (intptr_t) ptr - logbuffer->ptr_base);
1107 g_assert (logbuffer->cursor <= logbuffer->buf_end && "Why are we writing past the buffer end?");
1111 emit_method_inner (LogBuffer *logbuffer, void *method)
1113 if (!logbuffer->method_base) {
1114 logbuffer->method_base = (intptr_t) method;
1115 logbuffer->last_method = (intptr_t) method;
1118 encode_sleb128 ((intptr_t) ((char *) method - (char *) logbuffer->last_method), logbuffer->cursor, &logbuffer->cursor);
1119 logbuffer->last_method = (intptr_t) method;
1121 g_assert (logbuffer->cursor <= logbuffer->buf_end && "Why are we writing past the buffer end?");
1124 // The reader lock must be held.
1126 register_method_local (MonoMethod *method, MonoJitInfo *ji)
1128 MonoProfilerThread *thread = get_thread ();
1130 if (!mono_conc_hashtable_lookup (log_profiler.method_table, method)) {
1131 MethodInfo *info = (MethodInfo *) g_malloc (sizeof (MethodInfo));
1133 info->method = method;
1135 info->time = current_time ();
1137 GPtrArray *arr = thread->methods ? thread->methods : (thread->methods = g_ptr_array_new ());
1138 g_ptr_array_add (arr, info);
1143 emit_method (LogBuffer *logbuffer, MonoMethod *method)
1145 register_method_local (method, NULL);
1146 emit_method_inner (logbuffer, method);
1150 emit_obj (LogBuffer *logbuffer, void *ptr)
1152 if (!logbuffer->obj_base)
1153 logbuffer->obj_base = (uintptr_t) ptr >> 3;
1155 emit_svalue (logbuffer, ((uintptr_t) ptr >> 3) - logbuffer->obj_base);
1157 g_assert (logbuffer->cursor <= logbuffer->buf_end && "Why are we writing past the buffer end?");
1161 emit_string (LogBuffer *logbuffer, const char *str, size_t size)
1165 for (; i < size; i++) {
1168 emit_byte (logbuffer, str [i]);
1171 emit_byte (logbuffer, '\0');
1175 emit_double (LogBuffer *logbuffer, double value)
1178 unsigned char buffer[8];
1179 memcpy (buffer, &value, 8);
1180 #if G_BYTE_ORDER == G_BIG_ENDIAN
1181 for (i = 7; i >= 0; i--)
1183 for (i = 0; i < 8; i++)
1185 emit_byte (logbuffer, buffer[i]);
1189 write_int16 (char *buf, int32_t value)
1192 for (i = 0; i < 2; ++i) {
1200 write_int32 (char *buf, int32_t value)
1203 for (i = 0; i < 4; ++i) {
1211 write_int64 (char *buf, int64_t value)
1214 for (i = 0; i < 8; ++i) {
1222 write_header_string (char *p, const char *str)
1224 size_t len = strlen (str) + 1;
1226 p = write_int32 (p, len);
1235 const char *args = log_profiler.args;
1236 const char *arch = mono_config_get_cpu ();
1237 const char *os = mono_config_get_os ();
1239 char *hbuf = g_malloc (
1240 sizeof (gint32) /* header id */ +
1241 sizeof (gint8) /* major version */ +
1242 sizeof (gint8) /* minor version */ +
1243 sizeof (gint8) /* data version */ +
1244 sizeof (gint8) /* word size */ +
1245 sizeof (gint64) /* startup time */ +
1246 sizeof (gint32) /* timer overhead */ +
1247 sizeof (gint32) /* flags */ +
1248 sizeof (gint32) /* process id */ +
1249 sizeof (gint16) /* command port */ +
1250 sizeof (gint32) + strlen (args) + 1 /* arguments */ +
1251 sizeof (gint32) + strlen (arch) + 1 /* architecture */ +
1252 sizeof (gint32) + strlen (os) + 1 /* operating system */
1256 p = write_int32 (p, LOG_HEADER_ID);
1257 *p++ = LOG_VERSION_MAJOR;
1258 *p++ = LOG_VERSION_MINOR;
1259 *p++ = LOG_DATA_VERSION;
1260 *p++ = sizeof (void *);
1261 p = write_int64 (p, ((uint64_t) time (NULL)) * 1000);
1262 p = write_int32 (p, log_profiler.timer_overhead);
1263 p = write_int32 (p, 0); /* flags */
1264 p = write_int32 (p, process_id ());
1265 p = write_int16 (p, log_profiler.command_port);
1266 p = write_header_string (p, args);
1267 p = write_header_string (p, arch);
1268 p = write_header_string (p, os);
1270 #if defined (HAVE_SYS_ZLIB)
1271 if (log_profiler.gzfile) {
1272 gzwrite (log_profiler.gzfile, hbuf, p - hbuf);
1276 fwrite (hbuf, p - hbuf, 1, log_profiler.file);
1277 fflush (log_profiler.file);
1284 * Must be called with the reader lock held if thread is the current thread, or
1285 * the exclusive lock if thread is a different thread. However, if thread is
1286 * the current thread, and init_thread () was called with add_to_lls = FALSE,
1287 * then no locking is necessary.
1290 send_buffer (MonoProfilerThread *thread)
1292 WriterQueueEntry *entry = mono_lock_free_alloc (&log_profiler.writer_entry_allocator);
1293 entry->methods = thread->methods;
1294 entry->buffer = thread->buffer;
1296 mono_lock_free_queue_node_init (&entry->node, FALSE);
1298 mono_lock_free_queue_enqueue (&log_profiler.writer_queue, &entry->node);
1299 mono_os_sem_post (&log_profiler.writer_queue_sem);
1303 free_thread (gpointer p)
1305 MonoProfilerThread *thread = p;
1307 if (!thread->ended) {
1309 * The thread is being cleaned up by the main thread during
1310 * shutdown. This typically happens for internal runtime
1311 * threads. We need to synthesize a thread end event.
1314 InterlockedIncrement (&thread_ends_ctr);
1316 if (ENABLED (PROFLOG_THREAD_EVENTS)) {
1317 LogBuffer *buf = ensure_logbuf_unsafe (thread,
1318 EVENT_SIZE /* event */ +
1319 BYTE_SIZE /* type */ +
1320 LEB128_SIZE /* tid */
1323 emit_event (buf, TYPE_END_UNLOAD | TYPE_METADATA);
1324 emit_byte (buf, TYPE_THREAD);
1325 emit_ptr (buf, (void *) thread->node.key);
1329 send_buffer (thread);
1335 remove_thread (MonoProfilerThread *thread)
1337 MonoThreadHazardPointers *hp = mono_hazard_pointer_get ();
1339 if (mono_lls_remove (&log_profiler.profiler_thread_list, hp, &thread->node))
1340 mono_thread_hazardous_try_free (thread, free_thread);
1342 clear_hazard_pointers (hp);
1346 dump_buffer (LogBuffer *buf)
1352 dump_buffer (buf->next);
1354 if (buf->cursor - buf->buf) {
1355 p = write_int32 (p, BUF_ID);
1356 p = write_int32 (p, buf->cursor - buf->buf);
1357 p = write_int64 (p, buf->time_base);
1358 p = write_int64 (p, buf->ptr_base);
1359 p = write_int64 (p, buf->obj_base);
1360 p = write_int64 (p, buf->thread_id);
1361 p = write_int64 (p, buf->method_base);
1363 #if defined (HAVE_SYS_ZLIB)
1364 if (log_profiler.gzfile) {
1365 gzwrite (log_profiler.gzfile, hbuf, p - hbuf);
1366 gzwrite (log_profiler.gzfile, buf->buf, buf->cursor - buf->buf);
1370 fwrite (hbuf, p - hbuf, 1, log_profiler.file);
1371 fwrite (buf->buf, buf->cursor - buf->buf, 1, log_profiler.file);
1372 fflush (log_profiler.file);
1376 free_buffer (buf, buf->size);
1380 dump_buffer_threadless (LogBuffer *buf)
1382 for (LogBuffer *iter = buf; iter; iter = iter->next)
1383 iter->thread_id = 0;
1388 // Only valid if init_thread () was called with add_to_lls = FALSE.
1390 send_log_unsafe (gboolean if_needed)
1392 MonoProfilerThread *thread = PROF_TLS_GET ();
1394 if (!if_needed || (if_needed && thread->buffer->next)) {
1395 if (!thread->attached)
1396 for (LogBuffer *iter = thread->buffer; iter; iter = iter->next)
1397 iter->thread_id = 0;
1399 send_buffer (thread);
1400 init_buffer_state (thread);
1404 // Assumes that the exclusive lock is held.
1406 sync_point_flush (void)
1408 g_assert (InterlockedRead (&log_profiler.buffer_lock_state) == PROF_TLS_GET ()->small_id << 16 && "Why don't we hold the exclusive lock?");
1410 MONO_LLS_FOREACH_SAFE (&log_profiler.profiler_thread_list, MonoProfilerThread, thread) {
1411 g_assert (thread->attached && "Why is a thread in the LLS not attached?");
1413 send_buffer (thread);
1414 init_buffer_state (thread);
1415 } MONO_LLS_FOREACH_SAFE_END
1418 // Assumes that the exclusive lock is held.
1420 sync_point_mark (MonoProfilerSyncPointType type)
1422 g_assert (InterlockedRead (&log_profiler.buffer_lock_state) == PROF_TLS_GET ()->small_id << 16 && "Why don't we hold the exclusive lock?");
1424 ENTER_LOG (&sync_points_ctr, logbuffer,
1425 EVENT_SIZE /* event */ +
1426 LEB128_SIZE /* type */
1429 emit_event (logbuffer, TYPE_META | TYPE_SYNC_POINT);
1430 emit_byte (logbuffer, type);
1432 EXIT_LOG_EXPLICIT (NO_SEND);
1434 send_log_unsafe (FALSE);
1437 // Assumes that the exclusive lock is held.
1439 sync_point (MonoProfilerSyncPointType type)
1441 sync_point_flush ();
1442 sync_point_mark (type);
1446 gc_reference (MonoObject *obj, MonoClass *klass, uintptr_t size, uintptr_t num, MonoObject **refs, uintptr_t *offsets, void *data)
1448 /* account for object alignment in the heap */
1452 ENTER_LOG (&heap_objects_ctr, logbuffer,
1453 EVENT_SIZE /* event */ +
1454 LEB128_SIZE /* obj */ +
1455 LEB128_SIZE /* klass */ +
1456 LEB128_SIZE /* size */ +
1457 LEB128_SIZE /* num */ +
1459 LEB128_SIZE /* offset */ +
1460 LEB128_SIZE /* ref */
1464 emit_event (logbuffer, TYPE_HEAP_OBJECT | TYPE_HEAP);
1465 emit_obj (logbuffer, obj);
1466 emit_ptr (logbuffer, klass);
1467 emit_value (logbuffer, size);
1468 emit_value (logbuffer, num);
1470 uintptr_t last_offset = 0;
1472 for (int i = 0; i < num; ++i) {
1473 emit_value (logbuffer, offsets [i] - last_offset);
1474 last_offset = offsets [i];
1475 emit_obj (logbuffer, refs [i]);
1478 EXIT_LOG_EXPLICIT (DO_SEND);
1484 gc_roots (MonoProfiler *prof, MonoObject *const *objects, const MonoProfilerGCRootType *root_types, const uintptr_t *extra_info, uint64_t num)
1486 if (log_profiler.ignore_heap_events)
1489 ENTER_LOG (&heap_roots_ctr, logbuffer,
1490 EVENT_SIZE /* event */ +
1491 LEB128_SIZE /* num */ +
1492 LEB128_SIZE /* collections */ +
1494 LEB128_SIZE /* object */ +
1495 LEB128_SIZE /* root type */ +
1496 LEB128_SIZE /* extra info */
1500 emit_event (logbuffer, TYPE_HEAP_ROOT | TYPE_HEAP);
1501 emit_value (logbuffer, num);
1502 emit_value (logbuffer, mono_gc_collection_count (mono_gc_max_generation ()));
1504 for (int i = 0; i < num; ++i) {
1505 emit_obj (logbuffer, objects [i]);
1506 emit_byte (logbuffer, root_types [i]);
1507 emit_value (logbuffer, extra_info [i]);
1510 EXIT_LOG_EXPLICIT (DO_SEND);
1515 trigger_on_demand_heapshot (void)
1517 if (log_profiler.heapshot_requested)
1518 mono_gc_collect (mono_gc_max_generation ());
1521 #define ALL_GC_EVENTS_MASK (PROFLOG_GC_MOVES_EVENTS | PROFLOG_GC_ROOT_EVENTS | PROFLOG_GC_EVENTS | PROFLOG_HEAPSHOT_FEATURE)
1524 gc_event (MonoProfiler *profiler, MonoProfilerGCEvent ev, uint32_t generation)
1526 if (ev == MONO_GC_EVENT_START) {
1527 uint64_t now = current_time ();
1529 if (log_config.hs_mode_ms && (now - log_profiler.last_hs_time) / 1000 * 1000 >= log_config.hs_mode_ms)
1530 log_profiler.do_heap_walk = TRUE;
1531 else if (log_config.hs_mode_gc && !(log_profiler.gc_count % log_config.hs_mode_gc))
1532 log_profiler.do_heap_walk = TRUE;
1533 else if (log_config.hs_mode_ondemand)
1534 log_profiler.do_heap_walk = log_profiler.heapshot_requested;
1535 else if (!log_config.hs_mode_ms && !log_config.hs_mode_gc && generation == mono_gc_max_generation ())
1536 log_profiler.do_heap_walk = TRUE;
1538 //If using heapshot, ignore events for collections we don't care
1539 if (ENABLED (PROFLOG_HEAPSHOT_FEATURE)) {
1540 // Ignore events generated during the collection itself (IE GC ROOTS)
1541 log_profiler.ignore_heap_events = !log_profiler.do_heap_walk;
1546 if (ENABLED (PROFLOG_GC_EVENTS)) {
1547 ENTER_LOG (&gc_events_ctr, logbuffer,
1548 EVENT_SIZE /* event */ +
1549 BYTE_SIZE /* gc event */ +
1550 BYTE_SIZE /* generation */
1553 emit_event (logbuffer, TYPE_GC_EVENT | TYPE_GC);
1554 emit_byte (logbuffer, ev);
1555 emit_byte (logbuffer, generation);
1557 EXIT_LOG_EXPLICIT (NO_SEND);
1561 case MONO_GC_EVENT_START:
1562 if (generation == mono_gc_max_generation ())
1563 log_profiler.gc_count++;
1566 case MONO_GC_EVENT_PRE_STOP_WORLD_LOCKED:
1568 * Ensure that no thread can be in the middle of writing to
1569 * a buffer when the world stops...
1571 buffer_lock_excl ();
1573 case MONO_GC_EVENT_POST_STOP_WORLD:
1575 * ... So that we now have a consistent view of all buffers.
1576 * This allows us to flush them. We need to do this because
1577 * they may contain object allocation events that need to be
1578 * committed to the log file before any object move events
1579 * that will be produced during this GC.
1581 if (ENABLED (ALL_GC_EVENTS_MASK))
1582 sync_point (SYNC_POINT_WORLD_STOP);
1585 * All heap events are surrounded by a HEAP_START and a HEAP_ENV event.
1586 * Right now, that's the case for GC Moves, GC Roots or heapshots.
1588 if (ENABLED (PROFLOG_GC_MOVES_EVENTS | PROFLOG_GC_ROOT_EVENTS) || log_profiler.do_heap_walk) {
1589 ENTER_LOG (&heap_starts_ctr, logbuffer,
1590 EVENT_SIZE /* event */
1593 emit_event (logbuffer, TYPE_HEAP_START | TYPE_HEAP);
1595 EXIT_LOG_EXPLICIT (DO_SEND);
1599 case MONO_GC_EVENT_PRE_START_WORLD:
1600 if (ENABLED (PROFLOG_HEAPSHOT_FEATURE) && log_profiler.do_heap_walk)
1601 mono_gc_walk_heap (0, gc_reference, NULL);
1603 /* Matching HEAP_END to the HEAP_START from above */
1604 if (ENABLED (PROFLOG_GC_MOVES_EVENTS | PROFLOG_GC_ROOT_EVENTS) || log_profiler.do_heap_walk) {
1605 ENTER_LOG (&heap_ends_ctr, logbuffer,
1606 EVENT_SIZE /* event */
1609 emit_event (logbuffer, TYPE_HEAP_END | TYPE_HEAP);
1611 EXIT_LOG_EXPLICIT (DO_SEND);
1614 if (ENABLED (PROFLOG_HEAPSHOT_FEATURE) && log_profiler.do_heap_walk) {
1615 log_profiler.do_heap_walk = FALSE;
1616 log_profiler.heapshot_requested = FALSE;
1617 log_profiler.last_hs_time = current_time ();
1621 * Similarly, we must now make sure that any object moves
1622 * written to the GC thread's buffer are flushed. Otherwise,
1623 * object allocation events for certain addresses could come
1624 * after the move events that made those addresses available.
1626 if (ENABLED (ALL_GC_EVENTS_MASK))
1627 sync_point_mark (SYNC_POINT_WORLD_START);
1629 case MONO_GC_EVENT_POST_START_WORLD_UNLOCKED:
1631 * Finally, it is safe to allow other threads to write to
1632 * their buffers again.
1634 buffer_unlock_excl ();
1642 gc_resize (MonoProfiler *profiler, uintptr_t new_size)
1644 ENTER_LOG (&gc_resizes_ctr, logbuffer,
1645 EVENT_SIZE /* event */ +
1646 LEB128_SIZE /* new size */
1649 emit_event (logbuffer, TYPE_GC_RESIZE | TYPE_GC);
1650 emit_value (logbuffer, new_size);
1652 EXIT_LOG_EXPLICIT (DO_SEND);
1657 MonoMethod* methods [MAX_FRAMES];
1658 int32_t il_offsets [MAX_FRAMES];
1659 int32_t native_offsets [MAX_FRAMES];
1663 walk_stack (MonoMethod *method, int32_t native_offset, int32_t il_offset, mono_bool managed, void* data)
1665 FrameData *frame = (FrameData *)data;
1666 if (method && frame->count < log_config.num_frames) {
1667 frame->il_offsets [frame->count] = il_offset;
1668 frame->native_offsets [frame->count] = native_offset;
1669 frame->methods [frame->count++] = method;
1671 return frame->count == log_config.num_frames;
1675 * a note about stack walks: they can cause more profiler events to fire,
1676 * so we need to make sure they don't happen after we started emitting an
1677 * event, hence the collect_bt/emit_bt split.
1680 collect_bt (FrameData *data)
1683 mono_stack_walk_no_il (walk_stack, data);
1687 emit_bt (LogBuffer *logbuffer, FrameData *data)
1689 emit_value (logbuffer, data->count);
1692 emit_method (logbuffer, data->methods [--data->count]);
1696 gc_alloc (MonoProfiler *prof, MonoObject *obj)
1698 int do_bt = (!ENABLED (PROFLOG_CALL_EVENTS) && InterlockedRead (&log_profiler.runtime_inited) && !log_config.notraces) ? TYPE_ALLOC_BT : 0;
1700 uintptr_t len = mono_object_get_size (obj);
1701 /* account for object alignment in the heap */
1708 ENTER_LOG (&gc_allocs_ctr, logbuffer,
1709 EVENT_SIZE /* event */ +
1710 LEB128_SIZE /* klass */ +
1711 LEB128_SIZE /* obj */ +
1712 LEB128_SIZE /* size */ +
1714 LEB128_SIZE /* count */ +
1716 LEB128_SIZE /* method */
1721 emit_event (logbuffer, do_bt | TYPE_ALLOC);
1722 emit_ptr (logbuffer, mono_object_get_class (obj));
1723 emit_obj (logbuffer, obj);
1724 emit_value (logbuffer, len);
1727 emit_bt (logbuffer, &data);
1733 gc_moves (MonoProfiler *prof, MonoObject *const *objects, uint64_t num)
1735 ENTER_LOG (&gc_moves_ctr, logbuffer,
1736 EVENT_SIZE /* event */ +
1737 LEB128_SIZE /* num */ +
1739 LEB128_SIZE /* object */
1743 emit_event (logbuffer, TYPE_GC_MOVE | TYPE_GC);
1744 emit_value (logbuffer, num);
1746 for (int i = 0; i < num; ++i)
1747 emit_obj (logbuffer, objects [i]);
1749 EXIT_LOG_EXPLICIT (DO_SEND);
1753 gc_handle (MonoProfiler *prof, int op, MonoGCHandleType type, uint32_t handle, MonoObject *obj)
1755 int do_bt = !ENABLED (PROFLOG_CALL_EVENTS) && InterlockedRead (&log_profiler.runtime_inited) && !log_config.notraces;
1761 gint32 *ctr = op == MONO_PROFILER_GC_HANDLE_CREATED ? &gc_handle_creations_ctr : &gc_handle_deletions_ctr;
1763 ENTER_LOG (ctr, logbuffer,
1764 EVENT_SIZE /* event */ +
1765 LEB128_SIZE /* type */ +
1766 LEB128_SIZE /* handle */ +
1767 (op == MONO_PROFILER_GC_HANDLE_CREATED ? (
1768 LEB128_SIZE /* obj */
1771 LEB128_SIZE /* count */ +
1773 LEB128_SIZE /* method */
1778 if (op == MONO_PROFILER_GC_HANDLE_CREATED)
1779 emit_event (logbuffer, (do_bt ? TYPE_GC_HANDLE_CREATED_BT : TYPE_GC_HANDLE_CREATED) | TYPE_GC);
1780 else if (op == MONO_PROFILER_GC_HANDLE_DESTROYED)
1781 emit_event (logbuffer, (do_bt ? TYPE_GC_HANDLE_DESTROYED_BT : TYPE_GC_HANDLE_DESTROYED) | TYPE_GC);
1783 g_assert_not_reached ();
1785 emit_value (logbuffer, type);
1786 emit_value (logbuffer, handle);
1788 if (op == MONO_PROFILER_GC_HANDLE_CREATED)
1789 emit_obj (logbuffer, obj);
1792 emit_bt (logbuffer, &data);
1798 gc_handle_created (MonoProfiler *prof, uint32_t handle, MonoGCHandleType type, MonoObject *obj)
1800 gc_handle (prof, MONO_PROFILER_GC_HANDLE_CREATED, type, handle, obj);
1804 gc_handle_deleted (MonoProfiler *prof, uint32_t handle, MonoGCHandleType type)
1806 gc_handle (prof, MONO_PROFILER_GC_HANDLE_DESTROYED, type, handle, NULL);
1810 finalize_begin (MonoProfiler *prof)
1812 ENTER_LOG (&finalize_begins_ctr, buf,
1813 EVENT_SIZE /* event */
1816 emit_event (buf, TYPE_GC_FINALIZE_START | TYPE_GC);
1822 finalize_end (MonoProfiler *prof)
1824 trigger_on_demand_heapshot ();
1825 if (ENABLED (PROFLOG_FINALIZATION_EVENTS)) {
1826 ENTER_LOG (&finalize_ends_ctr, buf,
1827 EVENT_SIZE /* event */
1830 emit_event (buf, TYPE_GC_FINALIZE_END | TYPE_GC);
1837 finalize_object_begin (MonoProfiler *prof, MonoObject *obj)
1839 ENTER_LOG (&finalize_object_begins_ctr, buf,
1840 EVENT_SIZE /* event */ +
1841 LEB128_SIZE /* obj */
1844 emit_event (buf, TYPE_GC_FINALIZE_OBJECT_START | TYPE_GC);
1845 emit_obj (buf, obj);
1851 finalize_object_end (MonoProfiler *prof, MonoObject *obj)
1853 ENTER_LOG (&finalize_object_ends_ctr, buf,
1854 EVENT_SIZE /* event */ +
1855 LEB128_SIZE /* obj */
1858 emit_event (buf, TYPE_GC_FINALIZE_OBJECT_END | TYPE_GC);
1859 emit_obj (buf, obj);
1865 push_nesting (char *p, MonoClass *klass)
1870 nesting = mono_class_get_nesting_type (klass);
1872 p = push_nesting (p, nesting);
1876 name = mono_class_get_name (klass);
1877 nspace = mono_class_get_namespace (klass);
1880 p += strlen (nspace);
1890 type_name (MonoClass *klass)
1894 push_nesting (buf, klass);
1895 p = (char *) g_malloc (strlen (buf) + 1);
1901 image_loaded (MonoProfiler *prof, MonoImage *image)
1903 const char *name = mono_image_get_filename (image);
1904 int nlen = strlen (name) + 1;
1906 ENTER_LOG (&image_loads_ctr, logbuffer,
1907 EVENT_SIZE /* event */ +
1908 BYTE_SIZE /* type */ +
1909 LEB128_SIZE /* image */ +
1913 emit_event (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1914 emit_byte (logbuffer, TYPE_IMAGE);
1915 emit_ptr (logbuffer, image);
1916 memcpy (logbuffer->cursor, name, nlen);
1917 logbuffer->cursor += nlen;
1923 image_unloaded (MonoProfiler *prof, MonoImage *image)
1925 const char *name = mono_image_get_filename (image);
1926 int nlen = strlen (name) + 1;
1928 ENTER_LOG (&image_unloads_ctr, logbuffer,
1929 EVENT_SIZE /* event */ +
1930 BYTE_SIZE /* type */ +
1931 LEB128_SIZE /* image */ +
1935 emit_event (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
1936 emit_byte (logbuffer, TYPE_IMAGE);
1937 emit_ptr (logbuffer, image);
1938 memcpy (logbuffer->cursor, name, nlen);
1939 logbuffer->cursor += nlen;
1945 assembly_loaded (MonoProfiler *prof, MonoAssembly *assembly)
1947 char *name = mono_stringify_assembly_name (mono_assembly_get_name (assembly));
1948 int nlen = strlen (name) + 1;
1949 MonoImage *image = mono_assembly_get_image (assembly);
1951 ENTER_LOG (&assembly_loads_ctr, logbuffer,
1952 EVENT_SIZE /* event */ +
1953 BYTE_SIZE /* type */ +
1954 LEB128_SIZE /* assembly */ +
1955 LEB128_SIZE /* image */ +
1959 emit_event (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1960 emit_byte (logbuffer, TYPE_ASSEMBLY);
1961 emit_ptr (logbuffer, assembly);
1962 emit_ptr (logbuffer, image);
1963 memcpy (logbuffer->cursor, name, nlen);
1964 logbuffer->cursor += nlen;
1972 assembly_unloaded (MonoProfiler *prof, MonoAssembly *assembly)
1974 char *name = mono_stringify_assembly_name (mono_assembly_get_name (assembly));
1975 int nlen = strlen (name) + 1;
1976 MonoImage *image = mono_assembly_get_image (assembly);
1978 ENTER_LOG (&assembly_unloads_ctr, logbuffer,
1979 EVENT_SIZE /* event */ +
1980 BYTE_SIZE /* type */ +
1981 LEB128_SIZE /* assembly */ +
1982 LEB128_SIZE /* image */ +
1986 emit_event (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
1987 emit_byte (logbuffer, TYPE_ASSEMBLY);
1988 emit_ptr (logbuffer, assembly);
1989 emit_ptr (logbuffer, image);
1990 memcpy (logbuffer->cursor, name, nlen);
1991 logbuffer->cursor += nlen;
1999 class_loaded (MonoProfiler *prof, MonoClass *klass)
2003 if (InterlockedRead (&log_profiler.runtime_inited))
2004 name = mono_type_get_name (mono_class_get_type (klass));
2006 name = type_name (klass);
2008 int nlen = strlen (name) + 1;
2009 MonoImage *image = mono_class_get_image (klass);
2011 ENTER_LOG (&class_loads_ctr, logbuffer,
2012 EVENT_SIZE /* event */ +
2013 BYTE_SIZE /* type */ +
2014 LEB128_SIZE /* klass */ +
2015 LEB128_SIZE /* image */ +
2019 emit_event (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
2020 emit_byte (logbuffer, TYPE_CLASS);
2021 emit_ptr (logbuffer, klass);
2022 emit_ptr (logbuffer, image);
2023 memcpy (logbuffer->cursor, name, nlen);
2024 logbuffer->cursor += nlen;
2028 if (InterlockedRead (&log_profiler.runtime_inited))
2035 method_enter (MonoProfiler *prof, MonoMethod *method)
2037 if (get_thread ()->call_depth++ <= log_config.max_call_depth) {
2038 ENTER_LOG (&method_entries_ctr, logbuffer,
2039 EVENT_SIZE /* event */ +
2040 LEB128_SIZE /* method */
2043 emit_event (logbuffer, TYPE_ENTER | TYPE_METHOD);
2044 emit_method (logbuffer, method);
2051 method_leave (MonoProfiler *prof, MonoMethod *method)
2053 if (--get_thread ()->call_depth <= log_config.max_call_depth) {
2054 ENTER_LOG (&method_exits_ctr, logbuffer,
2055 EVENT_SIZE /* event */ +
2056 LEB128_SIZE /* method */
2059 emit_event (logbuffer, TYPE_LEAVE | TYPE_METHOD);
2060 emit_method (logbuffer, method);
2067 method_exc_leave (MonoProfiler *prof, MonoMethod *method, MonoObject *exc)
2069 if (--get_thread ()->call_depth <= log_config.max_call_depth) {
2070 ENTER_LOG (&method_exception_exits_ctr, logbuffer,
2071 EVENT_SIZE /* event */ +
2072 LEB128_SIZE /* method */
2075 emit_event (logbuffer, TYPE_EXC_LEAVE | TYPE_METHOD);
2076 emit_method (logbuffer, method);
2082 static MonoProfilerCallInstrumentationFlags
2083 method_filter (MonoProfiler *prof, MonoMethod *method)
2085 return MONO_PROFILER_CALL_INSTRUMENTATION_PROLOGUE | MONO_PROFILER_CALL_INSTRUMENTATION_EPILOGUE;
2089 method_jitted (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *ji)
2093 register_method_local (method, ji);
2099 code_buffer_new (MonoProfiler *prof, const mono_byte *buffer, uint64_t size, MonoProfilerCodeBufferType type, const void *data)
2104 if (type == MONO_PROFILER_CODE_BUFFER_SPECIFIC_TRAMPOLINE) {
2105 name = (const char *) data;
2106 nlen = strlen (name) + 1;
2112 ENTER_LOG (&code_buffers_ctr, logbuffer,
2113 EVENT_SIZE /* event */ +
2114 BYTE_SIZE /* type */ +
2115 LEB128_SIZE /* buffer */ +
2116 LEB128_SIZE /* size */ +
2122 emit_event (logbuffer, TYPE_JITHELPER | TYPE_RUNTIME);
2123 emit_byte (logbuffer, type);
2124 emit_ptr (logbuffer, buffer);
2125 emit_value (logbuffer, size);
2128 memcpy (logbuffer->cursor, name, nlen);
2129 logbuffer->cursor += nlen;
2136 throw_exc (MonoProfiler *prof, MonoObject *object)
2138 int do_bt = (!ENABLED (PROFLOG_CALL_EVENTS) && InterlockedRead (&log_profiler.runtime_inited) && !log_config.notraces) ? TYPE_THROW_BT : 0;
2144 ENTER_LOG (&exception_throws_ctr, logbuffer,
2145 EVENT_SIZE /* event */ +
2146 LEB128_SIZE /* object */ +
2148 LEB128_SIZE /* count */ +
2150 LEB128_SIZE /* method */
2155 emit_event (logbuffer, do_bt | TYPE_EXCEPTION);
2156 emit_obj (logbuffer, object);
2159 emit_bt (logbuffer, &data);
2165 clause_exc (MonoProfiler *prof, MonoMethod *method, uint32_t clause_num, MonoExceptionEnum clause_type, MonoObject *exc)
2167 ENTER_LOG (&exception_clauses_ctr, logbuffer,
2168 EVENT_SIZE /* event */ +
2169 BYTE_SIZE /* clause type */ +
2170 LEB128_SIZE /* clause num */ +
2171 LEB128_SIZE /* method */
2174 emit_event (logbuffer, TYPE_EXCEPTION | TYPE_CLAUSE);
2175 emit_byte (logbuffer, clause_type);
2176 emit_value (logbuffer, clause_num);
2177 emit_method (logbuffer, method);
2178 emit_obj (logbuffer, exc);
2184 monitor_event (MonoProfiler *profiler, MonoObject *object, MonoProfilerMonitorEvent ev)
2186 int do_bt = (!ENABLED (PROFLOG_CALL_EVENTS) && InterlockedRead (&log_profiler.runtime_inited) && !log_config.notraces) ? TYPE_MONITOR_BT : 0;
2192 ENTER_LOG (&monitor_events_ctr, logbuffer,
2193 EVENT_SIZE /* event */ +
2194 BYTE_SIZE /* ev */ +
2195 LEB128_SIZE /* object */ +
2197 LEB128_SIZE /* count */ +
2199 LEB128_SIZE /* method */
2204 emit_event (logbuffer, do_bt | TYPE_MONITOR);
2205 emit_byte (logbuffer, ev);
2206 emit_obj (logbuffer, object);
2209 emit_bt (logbuffer, &data);
2215 monitor_contention (MonoProfiler *prof, MonoObject *object)
2217 monitor_event (prof, object, MONO_PROFILER_MONITOR_CONTENTION);
2221 monitor_acquired (MonoProfiler *prof, MonoObject *object)
2223 monitor_event (prof, object, MONO_PROFILER_MONITOR_DONE);
2227 monitor_failed (MonoProfiler *prof, MonoObject *object)
2229 monitor_event (prof, object, MONO_PROFILER_MONITOR_FAIL);
2233 thread_start (MonoProfiler *prof, uintptr_t tid)
2235 if (ENABLED (PROFLOG_THREAD_EVENTS)) {
2236 ENTER_LOG (&thread_starts_ctr, logbuffer,
2237 EVENT_SIZE /* event */ +
2238 BYTE_SIZE /* type */ +
2239 LEB128_SIZE /* tid */
2242 emit_event (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
2243 emit_byte (logbuffer, TYPE_THREAD);
2244 emit_ptr (logbuffer, (void*) tid);
2251 thread_end (MonoProfiler *prof, uintptr_t tid)
2253 if (ENABLED (PROFLOG_THREAD_EVENTS)) {
2254 ENTER_LOG (&thread_ends_ctr, logbuffer,
2255 EVENT_SIZE /* event */ +
2256 BYTE_SIZE /* type */ +
2257 LEB128_SIZE /* tid */
2260 emit_event (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
2261 emit_byte (logbuffer, TYPE_THREAD);
2262 emit_ptr (logbuffer, (void*) tid);
2264 EXIT_LOG_EXPLICIT (NO_SEND);
2267 MonoProfilerThread *thread = get_thread ();
2269 thread->ended = TRUE;
2270 remove_thread (thread);
2272 PROF_TLS_SET (NULL);
2276 thread_name (MonoProfiler *prof, uintptr_t tid, const char *name)
2278 int len = strlen (name) + 1;
2280 if (ENABLED (PROFLOG_THREAD_EVENTS)) {
2281 ENTER_LOG (&thread_names_ctr, logbuffer,
2282 EVENT_SIZE /* event */ +
2283 BYTE_SIZE /* type */ +
2284 LEB128_SIZE /* tid */ +
2288 emit_event (logbuffer, TYPE_METADATA);
2289 emit_byte (logbuffer, TYPE_THREAD);
2290 emit_ptr (logbuffer, (void*)tid);
2291 memcpy (logbuffer->cursor, name, len);
2292 logbuffer->cursor += len;
2299 domain_loaded (MonoProfiler *prof, MonoDomain *domain)
2301 ENTER_LOG (&domain_loads_ctr, logbuffer,
2302 EVENT_SIZE /* event */ +
2303 BYTE_SIZE /* type */ +
2304 LEB128_SIZE /* domain id */
2307 emit_event (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
2308 emit_byte (logbuffer, TYPE_DOMAIN);
2309 emit_ptr (logbuffer, (void*)(uintptr_t) mono_domain_get_id (domain));
2315 domain_unloaded (MonoProfiler *prof, MonoDomain *domain)
2317 ENTER_LOG (&domain_unloads_ctr, logbuffer,
2318 EVENT_SIZE /* event */ +
2319 BYTE_SIZE /* type */ +
2320 LEB128_SIZE /* domain id */
2323 emit_event (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
2324 emit_byte (logbuffer, TYPE_DOMAIN);
2325 emit_ptr (logbuffer, (void*)(uintptr_t) mono_domain_get_id (domain));
2331 domain_name (MonoProfiler *prof, MonoDomain *domain, const char *name)
2333 int nlen = strlen (name) + 1;
2335 ENTER_LOG (&domain_names_ctr, logbuffer,
2336 EVENT_SIZE /* event */ +
2337 BYTE_SIZE /* type */ +
2338 LEB128_SIZE /* domain id */ +
2342 emit_event (logbuffer, TYPE_METADATA);
2343 emit_byte (logbuffer, TYPE_DOMAIN);
2344 emit_ptr (logbuffer, (void*)(uintptr_t) mono_domain_get_id (domain));
2345 memcpy (logbuffer->cursor, name, nlen);
2346 logbuffer->cursor += nlen;
2352 context_loaded (MonoProfiler *prof, MonoAppContext *context)
2354 ENTER_LOG (&context_loads_ctr, logbuffer,
2355 EVENT_SIZE /* event */ +
2356 BYTE_SIZE /* type */ +
2357 LEB128_SIZE /* context id */ +
2358 LEB128_SIZE /* domain id */
2361 emit_event (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
2362 emit_byte (logbuffer, TYPE_CONTEXT);
2363 emit_ptr (logbuffer, (void*)(uintptr_t) mono_context_get_id (context));
2364 emit_ptr (logbuffer, (void*)(uintptr_t) mono_context_get_domain_id (context));
2370 context_unloaded (MonoProfiler *prof, MonoAppContext *context)
2372 ENTER_LOG (&context_unloads_ctr, logbuffer,
2373 EVENT_SIZE /* event */ +
2374 BYTE_SIZE /* type */ +
2375 LEB128_SIZE /* context id */ +
2376 LEB128_SIZE /* domain id */
2379 emit_event (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
2380 emit_byte (logbuffer, TYPE_CONTEXT);
2381 emit_ptr (logbuffer, (void*)(uintptr_t) mono_context_get_id (context));
2382 emit_ptr (logbuffer, (void*)(uintptr_t) mono_context_get_domain_id (context));
2395 MonoLockFreeQueueNode node;
2400 AsyncFrameInfo frames [MONO_ZERO_LEN_ARRAY];
2404 async_walk_stack (MonoMethod *method, MonoDomain *domain, void *base_address, int offset, void *data)
2406 SampleHit *sample = (SampleHit *) data;
2408 if (sample->count < log_config.num_frames) {
2409 int i = sample->count;
2411 sample->frames [i].method = method;
2412 sample->frames [i].domain = domain;
2413 sample->frames [i].base_address = base_address;
2414 sample->frames [i].offset = offset;
2419 return sample->count == log_config.num_frames;
2422 #define SAMPLE_SLOT_SIZE(FRAMES) (sizeof (SampleHit) + sizeof (AsyncFrameInfo) * (FRAMES - MONO_ZERO_LEN_ARRAY))
2423 #define SAMPLE_BLOCK_SIZE (mono_pagesize ())
2426 enqueue_sample_hit (gpointer p)
2428 SampleHit *sample = p;
2430 mono_lock_free_queue_node_unpoison (&sample->node);
2431 mono_lock_free_queue_enqueue (&log_profiler.dumper_queue, &sample->node);
2432 mono_os_sem_post (&log_profiler.dumper_queue_sem);
2436 mono_sample_hit (MonoProfiler *profiler, const mono_byte *ip, const void *context)
2439 * Please note: We rely on the runtime loading the profiler with
2440 * MONO_DL_EAGER (RTLD_NOW) so that references to runtime functions within
2441 * this function (and its siblings) are resolved when the profiler is
2442 * loaded. Otherwise, we would potentially invoke the dynamic linker when
2443 * invoking runtime functions, which is not async-signal-safe.
2446 if (InterlockedRead (&log_profiler.in_shutdown))
2449 SampleHit *sample = (SampleHit *) mono_lock_free_queue_dequeue (&profiler->sample_reuse_queue);
2453 * If we're out of reusable sample events and we're not allowed to
2454 * allocate more, we have no choice but to drop the event.
2456 if (InterlockedRead (&sample_allocations_ctr) >= log_config.max_allocated_sample_hits)
2459 sample = mono_lock_free_alloc (&profiler->sample_allocator);
2460 mono_lock_free_queue_node_init (&sample->node, TRUE);
2462 InterlockedIncrement (&sample_allocations_ctr);
2466 mono_stack_walk_async_safe (&async_walk_stack, (void *) context, sample);
2468 sample->time = current_time ();
2469 sample->tid = thread_id ();
2472 mono_thread_hazardous_try_free (sample, enqueue_sample_hit);
2475 static uintptr_t *code_pages = 0;
2476 static int num_code_pages = 0;
2477 static int size_code_pages = 0;
2478 #define CPAGE_SHIFT (9)
2479 #define CPAGE_SIZE (1 << CPAGE_SHIFT)
2480 #define CPAGE_MASK (~(CPAGE_SIZE - 1))
2481 #define CPAGE_ADDR(p) ((p) & CPAGE_MASK)
2484 add_code_page (uintptr_t *hash, uintptr_t hsize, uintptr_t page)
2487 uintptr_t start_pos;
2488 start_pos = (page >> CPAGE_SHIFT) % hsize;
2491 if (hash [i] && CPAGE_ADDR (hash [i]) == CPAGE_ADDR (page)) {
2493 } else if (!hash [i]) {
2500 } while (i != start_pos);
2501 g_assert_not_reached ();
2506 add_code_pointer (uintptr_t ip)
2509 if (num_code_pages * 2 >= size_code_pages) {
2511 uintptr_t old_size = size_code_pages;
2512 size_code_pages *= 2;
2513 if (size_code_pages == 0)
2514 size_code_pages = 16;
2515 n = (uintptr_t *) g_calloc (sizeof (uintptr_t) * size_code_pages, 1);
2516 for (i = 0; i < old_size; ++i) {
2518 add_code_page (n, size_code_pages, code_pages [i]);
2521 g_free (code_pages);
2524 num_code_pages += add_code_page (code_pages, size_code_pages, ip & CPAGE_MASK);
2527 /* ELF code crashes on some systems. */
2528 //#if defined(HAVE_DL_ITERATE_PHDR) && defined(ELFMAG0)
2531 dump_ubin (const char *filename, uintptr_t load_addr, uint64_t offset, uintptr_t size)
2533 int len = strlen (filename) + 1;
2535 ENTER_LOG (&sample_ubins_ctr, logbuffer,
2536 EVENT_SIZE /* event */ +
2537 LEB128_SIZE /* load address */ +
2538 LEB128_SIZE /* offset */ +
2539 LEB128_SIZE /* size */ +
2540 nlen /* file name */
2543 emit_event (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_UBIN);
2544 emit_ptr (logbuffer, load_addr);
2545 emit_uvalue (logbuffer, offset);
2546 emit_uvalue (logbuffer, size);
2547 memcpy (logbuffer->cursor, filename, len);
2548 logbuffer->cursor += len;
2550 EXIT_LOG_EXPLICIT (DO_SEND);
2555 dump_usym (const char *name, uintptr_t value, uintptr_t size)
2557 int len = strlen (name) + 1;
2559 ENTER_LOG (&sample_usyms_ctr, logbuffer,
2560 EVENT_SIZE /* event */ +
2561 LEB128_SIZE /* value */ +
2562 LEB128_SIZE /* size */ +
2566 emit_event (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_USYM);
2567 emit_ptr (logbuffer, (void*)value);
2568 emit_value (logbuffer, size);
2569 memcpy (logbuffer->cursor, name, len);
2570 logbuffer->cursor += len;
2572 EXIT_LOG_EXPLICIT (DO_SEND);
2575 /* ELF code crashes on some systems. */
2576 //#if defined(ELFMAG0)
2579 #if SIZEOF_VOID_P == 4
2580 #define ELF_WSIZE 32
2582 #define ELF_WSIZE 64
2585 #define ElfW(type) _ElfW (Elf, ELF_WSIZE, type)
2586 #define _ElfW(e,w,t) _ElfW_1 (e, w, _##t)
2587 #define _ElfW_1(e,w,t) e##w##t
2591 dump_elf_symbols (ElfW(Sym) *symbols, int num_symbols, const char *strtab, void *load_addr)
2594 for (i = 0; i < num_symbols; ++i) {
2596 sym = strtab + symbols [i].st_name;
2597 if (!symbols [i].st_name || !symbols [i].st_size || (symbols [i].st_info & 0xf) != STT_FUNC)
2599 dump_usym (sym, (uintptr_t)load_addr + symbols [i].st_value, symbols [i].st_size);
2604 read_elf_symbols (MonoProfiler *prof, const char *filename, void *load_addr)
2611 ElfW(Shdr) *sheader;
2612 ElfW(Shdr) *shstrtabh;
2613 ElfW(Shdr) *symtabh = NULL;
2614 ElfW(Shdr) *strtabh = NULL;
2615 ElfW(Sym) *symbols = NULL;
2619 fd = open (filename, O_RDONLY);
2622 if (fstat (fd, &statb) != 0) {
2626 file_size = statb.st_size;
2627 data = mmap (NULL, file_size, PROT_READ, MAP_PRIVATE, fd, 0);
2629 if (data == MAP_FAILED)
2632 if (header->e_ident [EI_MAG0] != ELFMAG0 ||
2633 header->e_ident [EI_MAG1] != ELFMAG1 ||
2634 header->e_ident [EI_MAG2] != ELFMAG2 ||
2635 header->e_ident [EI_MAG3] != ELFMAG3 ) {
2636 munmap (data, file_size);
2639 sheader = (void*)((char*)data + header->e_shoff);
2640 shstrtabh = (void*)((char*)sheader + (header->e_shentsize * header->e_shstrndx));
2641 strtab = (const char*)data + shstrtabh->sh_offset;
2642 for (i = 0; i < header->e_shnum; ++i) {
2643 if (sheader->sh_type == SHT_SYMTAB) {
2645 strtabh = (void*)((char*)data + header->e_shoff + sheader->sh_link * header->e_shentsize);
2648 sheader = (void*)((char*)sheader + header->e_shentsize);
2650 if (!symtabh || !strtabh) {
2651 munmap (data, file_size);
2654 strtab = (const char*)data + strtabh->sh_offset;
2655 num_symbols = symtabh->sh_size / symtabh->sh_entsize;
2656 symbols = (void*)((char*)data + symtabh->sh_offset);
2657 dump_elf_symbols (symbols, num_symbols, strtab, load_addr);
2658 munmap (data, file_size);
2663 /* ELF code crashes on some systems. */
2664 //#if defined(HAVE_DL_ITERATE_PHDR) && defined(ELFMAG0)
2667 elf_dl_callback (struct dl_phdr_info *info, size_t size, void *data)
2670 const char *filename;
2672 char *a = (void*)info->dlpi_addr;
2674 ElfW(Dyn) *dyn = NULL;
2675 ElfW(Sym) *symtab = NULL;
2676 ElfW(Word) *hash_table = NULL;
2677 ElfW(Ehdr) *header = NULL;
2678 const char* strtab = NULL;
2679 for (obj = log_profiler.binary_objects; obj; obj = obj->next) {
2683 filename = info->dlpi_name;
2686 if (!info->dlpi_addr && !filename [0]) {
2687 int l = readlink ("/proc/self/exe", buf, sizeof (buf) - 1);
2693 obj = g_calloc (sizeof (BinaryObject), 1);
2694 obj->addr = (void*)info->dlpi_addr;
2695 obj->name = pstrdup (filename);
2696 obj->next = log_profiler.binary_objects;
2697 log_profiler.binary_objects = obj;
2699 for (i = 0; i < info->dlpi_phnum; ++i) {
2700 if (info->dlpi_phdr[i].p_type == PT_LOAD && !header) {
2701 header = (ElfW(Ehdr)*)(info->dlpi_addr + info->dlpi_phdr[i].p_vaddr);
2702 if (header->e_ident [EI_MAG0] != ELFMAG0 ||
2703 header->e_ident [EI_MAG1] != ELFMAG1 ||
2704 header->e_ident [EI_MAG2] != ELFMAG2 ||
2705 header->e_ident [EI_MAG3] != ELFMAG3 ) {
2708 dump_ubin (filename, info->dlpi_addr + info->dlpi_phdr[i].p_vaddr, info->dlpi_phdr[i].p_offset, info->dlpi_phdr[i].p_memsz);
2709 } else if (info->dlpi_phdr[i].p_type == PT_DYNAMIC) {
2710 dyn = (ElfW(Dyn) *)(info->dlpi_addr + info->dlpi_phdr[i].p_vaddr);
2713 if (read_elf_symbols (filename, (void*)info->dlpi_addr))
2715 if (!info->dlpi_name || !info->dlpi_name[0])
2719 for (i = 0; dyn [i].d_tag != DT_NULL; ++i) {
2720 if (dyn [i].d_tag == DT_SYMTAB) {
2721 symtab = (ElfW(Sym) *)(a + dyn [i].d_un.d_ptr);
2722 } else if (dyn [i].d_tag == DT_HASH) {
2723 hash_table = (ElfW(Word) *)(a + dyn [i].d_un.d_ptr);
2724 } else if (dyn [i].d_tag == DT_STRTAB) {
2725 strtab = (const char*)(a + dyn [i].d_un.d_ptr);
2730 num_sym = hash_table [1];
2731 dump_elf_symbols (symtab, num_sym, strtab, (void*)info->dlpi_addr);
2736 load_binaries (void)
2738 dl_iterate_phdr (elf_dl_callback, NULL);
2743 load_binaries (void)
2750 symbol_for (uintptr_t code)
2753 void *ip = (void*)code;
2755 if (dladdr (ip, &di)) {
2757 return di.dli_sname;
2760 names = backtrace_symbols (&ip, 1);
2762 const char* p = names [0];
2773 dump_unmanaged_coderefs (void)
2776 const char* last_symbol;
2777 uintptr_t addr, page_end;
2779 if (load_binaries ())
2781 for (i = 0; i < size_code_pages; ++i) {
2783 if (!code_pages [i] || code_pages [i] & 1)
2786 addr = CPAGE_ADDR (code_pages [i]);
2787 page_end = addr + CPAGE_SIZE;
2788 code_pages [i] |= 1;
2789 /* we dump the symbols for the whole page */
2790 for (; addr < page_end; addr += 16) {
2791 sym = symbol_for (addr);
2792 if (sym && sym == last_symbol)
2797 dump_usym (sym, addr, 0); /* let's not guess the size */
2803 counters_add_agent (MonoCounter *counter)
2805 if (InterlockedRead (&log_profiler.in_shutdown))
2808 MonoCounterAgent *agent, *item;
2810 mono_os_mutex_lock (&log_profiler.counters_mutex);
2812 for (agent = log_profiler.counters; agent; agent = agent->next) {
2813 if (agent->counter == counter) {
2814 agent->value_size = 0;
2816 g_free (agent->value);
2817 agent->value = NULL;
2823 agent = (MonoCounterAgent *) g_malloc (sizeof (MonoCounterAgent));
2824 agent->counter = counter;
2825 agent->value = NULL;
2826 agent->value_size = 0;
2827 agent->index = log_profiler.counters_index++;
2831 if (!log_profiler.counters) {
2832 log_profiler.counters = agent;
2834 item = log_profiler.counters;
2841 mono_os_mutex_unlock (&log_profiler.counters_mutex);
2845 counters_init_foreach_callback (MonoCounter *counter, gpointer data)
2847 counters_add_agent (counter);
2852 counters_init (void)
2854 mono_os_mutex_init (&log_profiler.counters_mutex);
2856 log_profiler.counters_index = 1;
2858 mono_counters_on_register (&counters_add_agent);
2859 mono_counters_foreach (counters_init_foreach_callback, NULL);
2863 counters_emit (void)
2865 MonoCounterAgent *agent;
2868 EVENT_SIZE /* event */ +
2869 LEB128_SIZE /* len */
2872 mono_os_mutex_lock (&log_profiler.counters_mutex);
2874 for (agent = log_profiler.counters; agent; agent = agent->next) {
2879 LEB128_SIZE /* section */ +
2880 strlen (mono_counter_get_name (agent->counter)) + 1 /* name */ +
2881 BYTE_SIZE /* type */ +
2882 BYTE_SIZE /* unit */ +
2883 BYTE_SIZE /* variance */ +
2884 LEB128_SIZE /* index */
2893 ENTER_LOG (&counter_descriptors_ctr, logbuffer, size);
2895 emit_event (logbuffer, TYPE_SAMPLE_COUNTERS_DESC | TYPE_SAMPLE);
2896 emit_value (logbuffer, len);
2898 for (agent = log_profiler.counters; agent; agent = agent->next) {
2904 name = mono_counter_get_name (agent->counter);
2905 emit_value (logbuffer, mono_counter_get_section (agent->counter));
2906 emit_string (logbuffer, name, strlen (name) + 1);
2907 emit_byte (logbuffer, mono_counter_get_type (agent->counter));
2908 emit_byte (logbuffer, mono_counter_get_unit (agent->counter));
2909 emit_byte (logbuffer, mono_counter_get_variance (agent->counter));
2910 emit_value (logbuffer, agent->index);
2915 EXIT_LOG_EXPLICIT (DO_SEND);
2918 mono_os_mutex_unlock (&log_profiler.counters_mutex);
2922 counters_sample (uint64_t timestamp)
2924 MonoCounterAgent *agent;
2925 MonoCounter *counter;
2934 buffer = g_calloc (1, buffer_size);
2936 mono_os_mutex_lock (&log_profiler.counters_mutex);
2939 EVENT_SIZE /* event */
2942 for (agent = log_profiler.counters; agent; agent = agent->next) {
2944 LEB128_SIZE /* index */ +
2945 BYTE_SIZE /* type */ +
2946 mono_counter_get_size (agent->counter) /* value */
2951 LEB128_SIZE /* stop marker */
2954 ENTER_LOG (&counter_samples_ctr, logbuffer, size);
2956 emit_event_time (logbuffer, TYPE_SAMPLE_COUNTERS | TYPE_SAMPLE, timestamp);
2958 for (agent = log_profiler.counters; agent; agent = agent->next) {
2961 counter = agent->counter;
2963 size = mono_counter_get_size (counter);
2965 if (size > buffer_size) {
2967 buffer = g_realloc (buffer, buffer_size);
2970 memset (buffer, 0, buffer_size);
2972 g_assert (mono_counters_sample (counter, buffer, size));
2974 type = mono_counter_get_type (counter);
2976 if (!agent->value) {
2977 agent->value = g_calloc (1, size);
2978 agent->value_size = size;
2980 if (type == MONO_COUNTER_STRING) {
2981 if (strcmp (agent->value, buffer) == 0)
2984 if (agent->value_size == size && memcmp (agent->value, buffer, size) == 0)
2989 emit_uvalue (logbuffer, agent->index);
2990 emit_byte (logbuffer, type);
2992 case MONO_COUNTER_INT:
2993 #if SIZEOF_VOID_P == 4
2994 case MONO_COUNTER_WORD:
2996 emit_svalue (logbuffer, *(int*)buffer - *(int*)agent->value);
2998 case MONO_COUNTER_UINT:
2999 emit_uvalue (logbuffer, *(guint*)buffer - *(guint*)agent->value);
3001 case MONO_COUNTER_TIME_INTERVAL:
3002 case MONO_COUNTER_LONG:
3003 #if SIZEOF_VOID_P == 8
3004 case MONO_COUNTER_WORD:
3006 emit_svalue (logbuffer, *(gint64*)buffer - *(gint64*)agent->value);
3008 case MONO_COUNTER_ULONG:
3009 emit_uvalue (logbuffer, *(guint64*)buffer - *(guint64*)agent->value);
3011 case MONO_COUNTER_DOUBLE:
3012 emit_double (logbuffer, *(double*)buffer);
3014 case MONO_COUNTER_STRING:
3016 emit_byte (logbuffer, 0);
3018 emit_byte (logbuffer, 1);
3019 emit_string (logbuffer, (char*)buffer, size);
3023 g_assert_not_reached ();
3026 if (type == MONO_COUNTER_STRING && size > agent->value_size) {
3027 agent->value = g_realloc (agent->value, size);
3028 agent->value_size = size;
3032 memcpy (agent->value, buffer, size);
3036 emit_value (logbuffer, 0);
3038 EXIT_LOG_EXPLICIT (DO_SEND);
3040 mono_os_mutex_unlock (&log_profiler.counters_mutex);
3044 perfcounters_emit (void)
3046 PerfCounterAgent *pcagent;
3049 EVENT_SIZE /* event */ +
3050 LEB128_SIZE /* len */
3053 for (pcagent = log_profiler.perfcounters; pcagent; pcagent = pcagent->next) {
3054 if (pcagent->emitted)
3058 LEB128_SIZE /* section */ +
3059 strlen (pcagent->category_name) + 1 /* category name */ +
3060 strlen (pcagent->name) + 1 /* name */ +
3061 BYTE_SIZE /* type */ +
3062 BYTE_SIZE /* unit */ +
3063 BYTE_SIZE /* variance */ +
3064 LEB128_SIZE /* index */
3073 ENTER_LOG (&perfcounter_descriptors_ctr, logbuffer, size);
3075 emit_event (logbuffer, TYPE_SAMPLE_COUNTERS_DESC | TYPE_SAMPLE);
3076 emit_value (logbuffer, len);
3078 for (pcagent = log_profiler.perfcounters; pcagent; pcagent = pcagent->next) {
3079 if (pcagent->emitted)
3082 emit_value (logbuffer, MONO_COUNTER_PERFCOUNTERS);
3083 emit_string (logbuffer, pcagent->category_name, strlen (pcagent->category_name) + 1);
3084 emit_string (logbuffer, pcagent->name, strlen (pcagent->name) + 1);
3085 emit_byte (logbuffer, MONO_COUNTER_LONG);
3086 emit_byte (logbuffer, MONO_COUNTER_RAW);
3087 emit_byte (logbuffer, MONO_COUNTER_VARIABLE);
3088 emit_value (logbuffer, pcagent->index);
3090 pcagent->emitted = 1;
3093 EXIT_LOG_EXPLICIT (DO_SEND);
3097 perfcounters_foreach (char *category_name, char *name, unsigned char type, gint64 value, gpointer user_data)
3099 PerfCounterAgent *pcagent;
3101 for (pcagent = log_profiler.perfcounters; pcagent; pcagent = pcagent->next) {
3102 if (strcmp (pcagent->category_name, category_name) != 0 || strcmp (pcagent->name, name) != 0)
3104 if (pcagent->value == value)
3107 pcagent->value = value;
3108 pcagent->updated = 1;
3109 pcagent->deleted = 0;
3113 pcagent = g_new0 (PerfCounterAgent, 1);
3114 pcagent->next = log_profiler.perfcounters;
3115 pcagent->index = log_profiler.counters_index++;
3116 pcagent->category_name = g_strdup (category_name);
3117 pcagent->name = g_strdup (name);
3118 pcagent->type = (int) type;
3119 pcagent->value = value;
3120 pcagent->emitted = 0;
3121 pcagent->updated = 1;
3122 pcagent->deleted = 0;
3124 log_profiler.perfcounters = pcagent;
3130 perfcounters_sample (uint64_t timestamp)
3132 PerfCounterAgent *pcagent;
3136 mono_os_mutex_lock (&log_profiler.counters_mutex);
3138 /* mark all perfcounters as deleted, foreach will unmark them as necessary */
3139 for (pcagent = log_profiler.perfcounters; pcagent; pcagent = pcagent->next)
3140 pcagent->deleted = 1;
3142 mono_perfcounter_foreach (perfcounters_foreach, NULL);
3144 perfcounters_emit ();
3147 EVENT_SIZE /* event */
3150 for (pcagent = log_profiler.perfcounters; pcagent; pcagent = pcagent->next) {
3151 if (pcagent->deleted || !pcagent->updated)
3155 LEB128_SIZE /* index */ +
3156 BYTE_SIZE /* type */ +
3157 LEB128_SIZE /* value */
3167 LEB128_SIZE /* stop marker */
3170 ENTER_LOG (&perfcounter_samples_ctr, logbuffer, size);
3172 emit_event_time (logbuffer, TYPE_SAMPLE_COUNTERS | TYPE_SAMPLE, timestamp);
3174 for (pcagent = log_profiler.perfcounters; pcagent; pcagent = pcagent->next) {
3175 if (pcagent->deleted || !pcagent->updated)
3177 emit_uvalue (logbuffer, pcagent->index);
3178 emit_byte (logbuffer, MONO_COUNTER_LONG);
3179 emit_svalue (logbuffer, pcagent->value);
3181 pcagent->updated = 0;
3184 emit_value (logbuffer, 0);
3186 EXIT_LOG_EXPLICIT (DO_SEND);
3189 mono_os_mutex_unlock (&log_profiler.counters_mutex);
3193 counters_and_perfcounters_sample (void)
3195 uint64_t now = current_time ();
3197 counters_sample (now);
3198 perfcounters_sample (now);
3202 MonoLockFreeQueueNode node;
3215 free_coverage_entry (gpointer data, gpointer userdata)
3217 CoverageEntry *entry = (CoverageEntry *)data;
3218 g_free (entry->filename);
3223 obtain_coverage_for_method (MonoProfiler *prof, const MonoProfilerCoverageData *entry)
3225 int offset = entry->il_offset - log_profiler.coverage_previous_offset;
3226 CoverageEntry *e = g_new (CoverageEntry, 1);
3228 log_profiler.coverage_previous_offset = entry->il_offset;
3231 e->counter = entry->counter;
3232 e->filename = g_strdup(entry->file_name ? entry->file_name : "");
3233 e->line = entry->line;
3234 e->column = entry->column;
3236 g_ptr_array_add (log_profiler.coverage_data, e);
3240 parse_generic_type_names(char *name)
3242 char *new_name, *ret;
3243 int within_generic_declaration = 0, generic_members = 1;
3245 if (name == NULL || *name == '\0')
3246 return g_strdup ("");
3248 if (!(ret = new_name = (char *) g_calloc (strlen (name) * 4 + 1, sizeof (char))))
3254 within_generic_declaration = 1;
3258 within_generic_declaration = 0;
3260 if (*(name - 1) != '<') {
3262 *new_name++ = '0' + generic_members;
3264 memcpy (new_name, "<>", 8);
3268 generic_members = 0;
3276 if (!within_generic_declaration)
3277 *new_name++ = *name;
3287 build_method_buffer (gpointer key, gpointer value, gpointer userdata)
3289 MonoMethod *method = (MonoMethod *)value;
3293 const char *image_name, *method_name, *sig, *first_filename;
3296 log_profiler.coverage_previous_offset = 0;
3297 log_profiler.coverage_data = g_ptr_array_new ();
3299 mono_profiler_get_coverage_data (log_profiler.handle, method, obtain_coverage_for_method);
3301 klass = mono_method_get_class (method);
3302 image = mono_class_get_image (klass);
3303 image_name = mono_image_get_name (image);
3305 sig = mono_signature_get_desc (mono_method_signature (method), TRUE);
3306 class_name = parse_generic_type_names (mono_type_get_name (mono_class_get_type (klass)));
3307 method_name = mono_method_get_name (method);
3309 if (log_profiler.coverage_data->len != 0) {
3310 CoverageEntry *entry = (CoverageEntry *)log_profiler.coverage_data->pdata[0];
3311 first_filename = entry->filename ? entry->filename : "";
3313 first_filename = "";
3315 image_name = image_name ? image_name : "";
3316 sig = sig ? sig : "";
3317 method_name = method_name ? method_name : "";
3319 ENTER_LOG (&coverage_methods_ctr, logbuffer,
3320 EVENT_SIZE /* event */ +
3321 strlen (image_name) + 1 /* image name */ +
3322 strlen (class_name) + 1 /* class name */ +
3323 strlen (method_name) + 1 /* method name */ +
3324 strlen (sig) + 1 /* signature */ +
3325 strlen (first_filename) + 1 /* first file name */ +
3326 LEB128_SIZE /* token */ +
3327 LEB128_SIZE /* method id */ +
3328 LEB128_SIZE /* entries */
3331 emit_event (logbuffer, TYPE_COVERAGE_METHOD | TYPE_COVERAGE);
3332 emit_string (logbuffer, image_name, strlen (image_name) + 1);
3333 emit_string (logbuffer, class_name, strlen (class_name) + 1);
3334 emit_string (logbuffer, method_name, strlen (method_name) + 1);
3335 emit_string (logbuffer, sig, strlen (sig) + 1);
3336 emit_string (logbuffer, first_filename, strlen (first_filename) + 1);
3338 emit_uvalue (logbuffer, mono_method_get_token (method));
3339 emit_uvalue (logbuffer, log_profiler.coverage_method_id);
3340 emit_value (logbuffer, log_profiler.coverage_data->len);
3342 EXIT_LOG_EXPLICIT (DO_SEND);
3344 for (i = 0; i < log_profiler.coverage_data->len; i++) {
3345 CoverageEntry *entry = (CoverageEntry *)log_profiler.coverage_data->pdata[i];
3347 ENTER_LOG (&coverage_statements_ctr, logbuffer,
3348 EVENT_SIZE /* event */ +
3349 LEB128_SIZE /* method id */ +
3350 LEB128_SIZE /* offset */ +
3351 LEB128_SIZE /* counter */ +
3352 LEB128_SIZE /* line */ +
3353 LEB128_SIZE /* column */
3356 emit_event (logbuffer, TYPE_COVERAGE_STATEMENT | TYPE_COVERAGE);
3357 emit_uvalue (logbuffer, log_profiler.coverage_method_id);
3358 emit_uvalue (logbuffer, entry->offset);
3359 emit_uvalue (logbuffer, entry->counter);
3360 emit_uvalue (logbuffer, entry->line);
3361 emit_uvalue (logbuffer, entry->column);
3363 EXIT_LOG_EXPLICIT (DO_SEND);
3366 log_profiler.coverage_method_id++;
3368 g_free (class_name);
3370 g_ptr_array_foreach (log_profiler.coverage_data, free_coverage_entry, NULL);
3371 g_ptr_array_free (log_profiler.coverage_data, TRUE);
3374 /* This empties the queue */
3376 count_queue (MonoLockFreeQueue *queue)
3378 MonoLockFreeQueueNode *node;
3381 while ((node = mono_lock_free_queue_dequeue (queue))) {
3383 mono_thread_hazardous_try_free (node, g_free);
3390 build_class_buffer (gpointer key, gpointer value, gpointer userdata)
3392 MonoClass *klass = (MonoClass *)key;
3393 MonoLockFreeQueue *class_methods = (MonoLockFreeQueue *)value;
3396 const char *assembly_name;
3397 int number_of_methods, partially_covered;
3398 guint fully_covered;
3400 image = mono_class_get_image (klass);
3401 assembly_name = mono_image_get_name (image);
3402 class_name = mono_type_get_name (mono_class_get_type (klass));
3404 assembly_name = assembly_name ? assembly_name : "";
3405 number_of_methods = mono_class_num_methods (klass);
3406 fully_covered = count_queue (class_methods);
3407 /* We don't handle partial covered yet */
3408 partially_covered = 0;
3410 ENTER_LOG (&coverage_classes_ctr, logbuffer,
3411 EVENT_SIZE /* event */ +
3412 strlen (assembly_name) + 1 /* assembly name */ +
3413 strlen (class_name) + 1 /* class name */ +
3414 LEB128_SIZE /* no. methods */ +
3415 LEB128_SIZE /* fully covered */ +
3416 LEB128_SIZE /* partially covered */
3419 emit_event (logbuffer, TYPE_COVERAGE_CLASS | TYPE_COVERAGE);
3420 emit_string (logbuffer, assembly_name, strlen (assembly_name) + 1);
3421 emit_string (logbuffer, class_name, strlen (class_name) + 1);
3422 emit_uvalue (logbuffer, number_of_methods);
3423 emit_uvalue (logbuffer, fully_covered);
3424 emit_uvalue (logbuffer, partially_covered);
3426 EXIT_LOG_EXPLICIT (DO_SEND);
3428 g_free (class_name);
3432 get_coverage_for_image (MonoImage *image, int *number_of_methods, guint *fully_covered, int *partially_covered)
3434 MonoLockFreeQueue *image_methods = (MonoLockFreeQueue *)mono_conc_hashtable_lookup (log_profiler.coverage_image_to_methods, image);
3436 *number_of_methods = mono_image_get_table_rows (image, MONO_TABLE_METHOD);
3438 *fully_covered = count_queue (image_methods);
3442 // FIXME: We don't handle partially covered yet.
3443 *partially_covered = 0;
3447 build_assembly_buffer (gpointer key, gpointer value, gpointer userdata)
3449 MonoAssembly *assembly = (MonoAssembly *)value;
3450 MonoImage *image = mono_assembly_get_image (assembly);
3451 const char *name, *guid, *filename;
3452 int number_of_methods = 0, partially_covered = 0;
3453 guint fully_covered = 0;
3455 name = mono_image_get_name (image);
3456 guid = mono_image_get_guid (image);
3457 filename = mono_image_get_filename (image);
3459 name = name ? name : "";
3460 guid = guid ? guid : "";
3461 filename = filename ? filename : "";
3463 get_coverage_for_image (image, &number_of_methods, &fully_covered, &partially_covered);
3465 ENTER_LOG (&coverage_assemblies_ctr, logbuffer,
3466 EVENT_SIZE /* event */ +
3467 strlen (name) + 1 /* name */ +
3468 strlen (guid) + 1 /* guid */ +
3469 strlen (filename) + 1 /* file name */ +
3470 LEB128_SIZE /* no. methods */ +
3471 LEB128_SIZE /* fully covered */ +
3472 LEB128_SIZE /* partially covered */
3475 emit_event (logbuffer, TYPE_COVERAGE_ASSEMBLY | TYPE_COVERAGE);
3476 emit_string (logbuffer, name, strlen (name) + 1);
3477 emit_string (logbuffer, guid, strlen (guid) + 1);
3478 emit_string (logbuffer, filename, strlen (filename) + 1);
3479 emit_uvalue (logbuffer, number_of_methods);
3480 emit_uvalue (logbuffer, fully_covered);
3481 emit_uvalue (logbuffer, partially_covered);
3483 EXIT_LOG_EXPLICIT (DO_SEND);
3487 dump_coverage (void)
3489 mono_os_mutex_lock (&log_profiler.coverage_mutex);
3490 mono_conc_hashtable_foreach (log_profiler.coverage_assemblies, build_assembly_buffer, NULL);
3491 mono_conc_hashtable_foreach (log_profiler.coverage_classes, build_class_buffer, NULL);
3492 mono_conc_hashtable_foreach (log_profiler.coverage_methods, build_method_buffer, NULL);
3493 mono_os_mutex_unlock (&log_profiler.coverage_mutex);
3496 static MonoLockFreeQueueNode *
3497 create_method_node (MonoMethod *method)
3499 MethodNode *node = (MethodNode *) g_malloc (sizeof (MethodNode));
3500 mono_lock_free_queue_node_init ((MonoLockFreeQueueNode *) node, FALSE);
3501 node->method = method;
3503 return (MonoLockFreeQueueNode *) node;
3507 coverage_filter (MonoProfiler *prof, MonoMethod *method)
3512 MonoAssembly *assembly;
3513 MonoMethodHeader *header;
3514 guint32 iflags, flags, code_size;
3515 char *fqn, *classname;
3516 gboolean has_positive, found;
3517 MonoLockFreeQueue *image_methods, *class_methods;
3518 MonoLockFreeQueueNode *node;
3520 flags = mono_method_get_flags (method, &iflags);
3521 if ((iflags & 0x1000 /*METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL*/) ||
3522 (flags & 0x2000 /*METHOD_ATTRIBUTE_PINVOKE_IMPL*/))
3525 // Don't need to do anything else if we're already tracking this method
3526 if (mono_conc_hashtable_lookup (log_profiler.coverage_methods, method))
3529 klass = mono_method_get_class (method);
3530 image = mono_class_get_image (klass);
3532 // Don't handle coverage for the core assemblies
3533 if (mono_conc_hashtable_lookup (log_profiler.coverage_suppressed_assemblies, (gpointer) mono_image_get_name (image)) != NULL)
3536 if (prof->coverage_filters) {
3537 /* Check already filtered classes first */
3538 if (mono_conc_hashtable_lookup (log_profiler.coverage_filtered_classes, klass))
3541 classname = mono_type_get_name (mono_class_get_type (klass));
3543 fqn = g_strdup_printf ("[%s]%s", mono_image_get_name (image), classname);
3545 // Check positive filters first
3546 has_positive = FALSE;
3548 for (guint i = 0; i < prof->coverage_filters->len; ++i) {
3549 char *filter = (char *)g_ptr_array_index (prof->coverage_filters, i);
3551 if (filter [0] == '+') {
3552 filter = &filter [1];
3554 if (strstr (fqn, filter) != NULL)
3557 has_positive = TRUE;
3561 if (has_positive && !found) {
3562 mono_os_mutex_lock (&log_profiler.coverage_mutex);
3563 mono_conc_hashtable_insert (log_profiler.coverage_filtered_classes, klass, klass);
3564 mono_os_mutex_unlock (&log_profiler.coverage_mutex);
3571 for (guint i = 0; i < prof->coverage_filters->len; ++i) {
3572 // FIXME: Is substring search sufficient?
3573 char *filter = (char *)g_ptr_array_index (prof->coverage_filters, i);
3574 if (filter [0] == '+')
3578 filter = &filter [1];
3580 if (strstr (fqn, filter) != NULL) {
3581 mono_os_mutex_lock (&log_profiler.coverage_mutex);
3582 mono_conc_hashtable_insert (log_profiler.coverage_filtered_classes, klass, klass);
3583 mono_os_mutex_unlock (&log_profiler.coverage_mutex);
3595 header = mono_method_get_header_checked (method, &error);
3596 mono_error_cleanup (&error);
3598 mono_method_header_get_code (header, &code_size, NULL);
3600 assembly = mono_image_get_assembly (image);
3602 // Need to keep the assemblies around for as long as they are kept in the hashtable
3603 // Nunit, for example, has a habit of unloading them before the coverage statistics are
3604 // generated causing a crash. See https://bugzilla.xamarin.com/show_bug.cgi?id=39325
3605 mono_assembly_addref (assembly);
3607 mono_os_mutex_lock (&log_profiler.coverage_mutex);
3608 mono_conc_hashtable_insert (log_profiler.coverage_methods, method, method);
3609 mono_conc_hashtable_insert (log_profiler.coverage_assemblies, assembly, assembly);
3610 mono_os_mutex_unlock (&log_profiler.coverage_mutex);
3612 image_methods = (MonoLockFreeQueue *)mono_conc_hashtable_lookup (log_profiler.coverage_image_to_methods, image);
3614 if (image_methods == NULL) {
3615 image_methods = (MonoLockFreeQueue *) g_malloc (sizeof (MonoLockFreeQueue));
3616 mono_lock_free_queue_init (image_methods);
3617 mono_os_mutex_lock (&log_profiler.coverage_mutex);
3618 mono_conc_hashtable_insert (log_profiler.coverage_image_to_methods, image, image_methods);
3619 mono_os_mutex_unlock (&log_profiler.coverage_mutex);
3622 node = create_method_node (method);
3623 mono_lock_free_queue_enqueue (image_methods, node);
3625 class_methods = (MonoLockFreeQueue *)mono_conc_hashtable_lookup (log_profiler.coverage_classes, klass);
3627 if (class_methods == NULL) {
3628 class_methods = (MonoLockFreeQueue *) g_malloc (sizeof (MonoLockFreeQueue));
3629 mono_lock_free_queue_init (class_methods);
3630 mono_os_mutex_lock (&log_profiler.coverage_mutex);
3631 mono_conc_hashtable_insert (log_profiler.coverage_classes, klass, class_methods);
3632 mono_os_mutex_unlock (&log_profiler.coverage_mutex);
3635 node = create_method_node (method);
3636 mono_lock_free_queue_enqueue (class_methods, node);
3641 #define LINE_BUFFER_SIZE 4096
3642 /* Max file limit of 128KB */
3643 #define MAX_FILE_SIZE 128 * 1024
3645 get_file_content (FILE *stream)
3650 int res, offset = 0;
3652 res = fseek (stream, 0, SEEK_END);
3656 filesize = ftell (stream);
3660 res = fseek (stream, 0, SEEK_SET);
3664 if (filesize > MAX_FILE_SIZE)
3667 buffer = (char *) g_malloc ((filesize + 1) * sizeof (char));
3668 while ((bytes_read = fread (buffer + offset, 1, LINE_BUFFER_SIZE, stream)) > 0)
3669 offset += bytes_read;
3671 /* NULL terminate our buffer */
3672 buffer[filesize] = '\0';
3677 get_next_line (char *contents, char **next_start)
3681 if (p == NULL || *p == '\0') {
3686 while (*p != '\n' && *p != '\0')
3691 *next_start = p + 1;
3699 init_suppressed_assemblies (void)
3705 log_profiler.coverage_suppressed_assemblies = mono_conc_hashtable_new (g_str_hash, g_str_equal);
3706 sa_file = fopen (SUPPRESSION_DIR "/mono-profiler-log.suppression", "r");
3707 if (sa_file == NULL)
3710 /* Don't need to free @content as it is referred to by the lines stored in @suppressed_assemblies */
3711 content = get_file_content (sa_file);
3712 if (content == NULL)
3713 g_error ("mono-profiler-log.suppression is greater than 128kb - aborting.");
3715 while ((line = get_next_line (content, &content))) {
3716 line = g_strchomp (g_strchug (line));
3717 /* No locking needed as we're doing initialization */
3718 mono_conc_hashtable_insert (log_profiler.coverage_suppressed_assemblies, line, line);
3725 parse_cov_filter_file (GPtrArray *filters, const char *file)
3727 FILE *filter_file = fopen (file, "r");
3729 if (filter_file == NULL) {
3730 mono_profiler_printf_err ("Could not open coverage filter file '%s'.", file);
3734 /* Don't need to free content as it is referred to by the lines stored in @filters */
3735 char *content = get_file_content (filter_file);
3737 if (content == NULL)
3738 mono_profiler_printf_err ("Coverage filter file '%s' is larger than 128kb - ignoring.", file);
3742 while ((line = get_next_line (content, &content)))
3743 g_ptr_array_add (filters, g_strchug (g_strchomp (line)));
3745 fclose (filter_file);
3749 coverage_init (void)
3751 mono_os_mutex_init (&log_profiler.coverage_mutex);
3752 log_profiler.coverage_methods = mono_conc_hashtable_new (NULL, NULL);
3753 log_profiler.coverage_assemblies = mono_conc_hashtable_new (NULL, NULL);
3754 log_profiler.coverage_classes = mono_conc_hashtable_new (NULL, NULL);
3755 log_profiler.coverage_filtered_classes = mono_conc_hashtable_new (NULL, NULL);
3756 log_profiler.coverage_image_to_methods = mono_conc_hashtable_new (NULL, NULL);
3757 init_suppressed_assemblies ();
3761 unref_coverage_assemblies (gpointer key, gpointer value, gpointer userdata)
3763 MonoAssembly *assembly = (MonoAssembly *)value;
3764 mono_assembly_close (assembly);
3768 free_sample_hit (gpointer p)
3770 mono_lock_free_free (p, SAMPLE_BLOCK_SIZE);
3774 cleanup_reusable_samples (void)
3778 while ((sample = (SampleHit *) mono_lock_free_queue_dequeue (&log_profiler.sample_reuse_queue)))
3779 mono_thread_hazardous_try_free (sample, free_sample_hit);
3783 log_shutdown (MonoProfiler *prof)
3785 InterlockedWrite (&log_profiler.in_shutdown, 1);
3787 if (ENABLED (PROFLOG_COUNTER_EVENTS))
3788 counters_and_perfcounters_sample ();
3790 if (ENABLED (PROFLOG_CODE_COV_FEATURE))
3795 if (write (prof->pipes [1], &c, 1) != 1) {
3796 mono_profiler_printf_err ("Could not write to log profiler pipe: %s", strerror (errno));
3800 mono_native_thread_join (prof->helper_thread);
3802 mono_os_mutex_destroy (&log_profiler.counters_mutex);
3804 MonoCounterAgent *mc_next;
3806 for (MonoCounterAgent *cur = log_profiler.counters; cur; cur = mc_next) {
3807 mc_next = cur->next;
3811 PerfCounterAgent *pc_next;
3813 for (PerfCounterAgent *cur = log_profiler.perfcounters; cur; cur = pc_next) {
3814 pc_next = cur->next;
3819 * Ensure that we empty the LLS completely, even if some nodes are
3820 * not immediately removed upon calling mono_lls_remove (), by
3821 * iterating until the head is NULL.
3823 while (log_profiler.profiler_thread_list.head) {
3824 MONO_LLS_FOREACH_SAFE (&log_profiler.profiler_thread_list, MonoProfilerThread, thread) {
3825 g_assert (thread->attached && "Why is a thread in the LLS not attached?");
3827 remove_thread (thread);
3828 } MONO_LLS_FOREACH_SAFE_END
3832 * Ensure that all threads have been freed, so that we don't miss any
3833 * buffers when we shut down the writer thread below.
3835 mono_thread_hazardous_try_free_all ();
3837 InterlockedWrite (&prof->run_dumper_thread, 0);
3838 mono_os_sem_post (&prof->dumper_queue_sem);
3839 mono_native_thread_join (prof->dumper_thread);
3840 mono_os_sem_destroy (&prof->dumper_queue_sem);
3842 InterlockedWrite (&prof->run_writer_thread, 0);
3843 mono_os_sem_post (&prof->writer_queue_sem);
3844 mono_native_thread_join (prof->writer_thread);
3845 mono_os_sem_destroy (&prof->writer_queue_sem);
3848 * Free all writer queue entries, and ensure that all sample hits will be
3849 * added to the sample reuse queue.
3851 mono_thread_hazardous_try_free_all ();
3853 cleanup_reusable_samples ();
3856 * Finally, make sure that all sample hits are freed. This should cover all
3857 * hazardous data from the profiler. We can now be sure that the runtime
3858 * won't later invoke free functions in the profiler library after it has
3861 mono_thread_hazardous_try_free_all ();
3863 gint32 state = InterlockedRead (&log_profiler.buffer_lock_state);
3865 g_assert (!(state & 0xFFFF) && "Why is the reader count still non-zero?");
3866 g_assert (!(state >> 16) && "Why is the exclusive lock still held?");
3868 #if defined (HAVE_SYS_ZLIB)
3870 gzclose (prof->gzfile);
3872 if (prof->pipe_output)
3873 pclose (prof->file);
3875 fclose (prof->file);
3877 mono_conc_hashtable_destroy (prof->method_table);
3878 mono_os_mutex_destroy (&prof->method_table_mutex);
3880 if (ENABLED (PROFLOG_CODE_COV_FEATURE)) {
3881 mono_os_mutex_lock (&log_profiler.coverage_mutex);
3882 mono_conc_hashtable_foreach (log_profiler.coverage_assemblies, unref_coverage_assemblies, NULL);
3883 mono_os_mutex_unlock (&log_profiler.coverage_mutex);
3885 mono_conc_hashtable_destroy (log_profiler.coverage_methods);
3886 mono_conc_hashtable_destroy (log_profiler.coverage_assemblies);
3887 mono_conc_hashtable_destroy (log_profiler.coverage_classes);
3888 mono_conc_hashtable_destroy (log_profiler.coverage_filtered_classes);
3890 mono_conc_hashtable_destroy (log_profiler.coverage_image_to_methods);
3891 mono_conc_hashtable_destroy (log_profiler.coverage_suppressed_assemblies);
3892 mono_os_mutex_destroy (&log_profiler.coverage_mutex);
3897 g_free (prof->args);
3901 new_filename (const char* filename)
3903 time_t t = time (NULL);
3904 int pid = process_id ();
3909 int count_dates = 0;
3913 for (p = filename; *p; p++) {
3924 if (!count_dates && !count_pids)
3925 return pstrdup (filename);
3926 snprintf (pid_buf, sizeof (pid_buf), "%d", pid);
3928 snprintf (time_buf, sizeof (time_buf), "%d%02d%02d%02d%02d%02d",
3929 1900 + ts->tm_year, 1 + ts->tm_mon, ts->tm_mday, ts->tm_hour, ts->tm_min, ts->tm_sec);
3930 s_date = strlen (time_buf);
3931 s_pid = strlen (pid_buf);
3932 d = res = (char *) g_malloc (strlen (filename) + s_date * count_dates + s_pid * count_pids);
3933 for (p = filename; *p; p++) {
3940 strcpy (d, time_buf);
3943 } else if (*p == 'p') {
3944 strcpy (d, pid_buf);
3947 } else if (*p == '%') {
3960 add_to_fd_set (fd_set *set, int fd, int *max_fd)
3963 * This should only trigger for the basic FDs (server socket, pipes) at
3964 * startup if for some mysterious reason they're too large. In this case,
3965 * the profiler really can't function, and we're better off printing an
3966 * error and exiting.
3968 if (fd >= FD_SETSIZE) {
3969 mono_profiler_printf_err ("File descriptor is out of bounds for fd_set: %d", fd);
3980 helper_thread (void *arg)
3982 mono_threads_attach_tools_thread ();
3983 mono_native_thread_set_name (mono_native_thread_id_get (), "Profiler helper");
3985 MonoProfilerThread *thread = init_thread (FALSE);
3987 GArray *command_sockets = g_array_new (FALSE, FALSE, sizeof (int));
3995 add_to_fd_set (&rfds, log_profiler.server_socket, &max_fd);
3996 add_to_fd_set (&rfds, log_profiler.pipes [0], &max_fd);
3998 for (gint i = 0; i < command_sockets->len; i++)
3999 add_to_fd_set (&rfds, g_array_index (command_sockets, int, i), &max_fd);
4001 struct timeval tv = { .tv_sec = 1, .tv_usec = 0 };
4003 // Sleep for 1sec or until a file descriptor has data.
4004 if (select (max_fd + 1, &rfds, NULL, NULL, &tv) == -1) {
4008 mono_profiler_printf_err ("Could not poll in log profiler helper thread: %s", strerror (errno));
4012 if (ENABLED (PROFLOG_COUNTER_EVENTS))
4013 counters_and_perfcounters_sample ();
4015 buffer_lock_excl ();
4017 sync_point (SYNC_POINT_PERIODIC);
4019 buffer_unlock_excl ();
4021 // Are we shutting down?
4022 if (FD_ISSET (log_profiler.pipes [0], &rfds)) {
4024 read (log_profiler.pipes [0], &c, 1);
4028 for (gint i = 0; i < command_sockets->len; i++) {
4029 int fd = g_array_index (command_sockets, int, i);
4031 if (!FD_ISSET (fd, &rfds))
4035 int len = read (fd, buf, sizeof (buf) - 1);
4041 // The other end disconnected.
4042 g_array_remove_index (command_sockets, i);
4050 if (!strcmp (buf, "heapshot\n") && log_config.hs_mode_ondemand) {
4051 // Rely on the finalization callback triggering a GC.
4052 log_profiler.heapshot_requested = TRUE;
4053 mono_gc_finalize_notify ();
4057 if (FD_ISSET (log_profiler.server_socket, &rfds)) {
4058 int fd = accept (log_profiler.server_socket, NULL, NULL);
4061 if (fd >= FD_SETSIZE)
4064 g_array_append_val (command_sockets, fd);
4069 for (gint i = 0; i < command_sockets->len; i++)
4070 close (g_array_index (command_sockets, int, i));
4072 g_array_free (command_sockets, TRUE);
4074 send_log_unsafe (FALSE);
4075 deinit_thread (thread);
4077 mono_thread_info_detach ();
4083 start_helper_thread (void)
4085 if (pipe (log_profiler.pipes) == -1) {
4086 mono_profiler_printf_err ("Could not create log profiler pipe: %s", strerror (errno));
4090 log_profiler.server_socket = socket (PF_INET, SOCK_STREAM, 0);
4092 if (log_profiler.server_socket == -1) {
4093 mono_profiler_printf_err ("Could not create log profiler server socket: %s", strerror (errno));
4097 struct sockaddr_in server_address;
4099 memset (&server_address, 0, sizeof (server_address));
4100 server_address.sin_family = AF_INET;
4101 server_address.sin_addr.s_addr = INADDR_ANY;
4102 server_address.sin_port = htons (log_profiler.command_port);
4104 if (bind (log_profiler.server_socket, (struct sockaddr *) &server_address, sizeof (server_address)) == -1) {
4105 mono_profiler_printf_err ("Could not bind log profiler server socket on port %d: %s", log_profiler.command_port, strerror (errno));
4106 close (log_profiler.server_socket);
4110 if (listen (log_profiler.server_socket, 1) == -1) {
4111 mono_profiler_printf_err ("Could not listen on log profiler server socket: %s", strerror (errno));
4112 close (log_profiler.server_socket);
4116 socklen_t slen = sizeof (server_address);
4118 if (getsockname (log_profiler.server_socket, (struct sockaddr *) &server_address, &slen)) {
4119 mono_profiler_printf_err ("Could not retrieve assigned port for log profiler server socket: %s", strerror (errno));
4120 close (log_profiler.server_socket);
4124 log_profiler.command_port = ntohs (server_address.sin_port);
4126 if (!mono_native_thread_create (&log_profiler.helper_thread, helper_thread, NULL)) {
4127 mono_profiler_printf_err ("Could not start log profiler helper thread");
4128 close (log_profiler.server_socket);
4134 free_writer_entry (gpointer p)
4136 mono_lock_free_free (p, WRITER_ENTRY_BLOCK_SIZE);
4140 handle_writer_queue_entry (void)
4142 WriterQueueEntry *entry;
4144 if ((entry = (WriterQueueEntry *) mono_lock_free_queue_dequeue (&log_profiler.writer_queue))) {
4145 if (!entry->methods)
4148 gboolean wrote_methods = FALSE;
4151 * Encode the method events in a temporary log buffer that we
4152 * flush to disk before the main buffer, ensuring that all
4153 * methods have metadata emitted before they're referenced.
4155 * We use a 'proper' thread-local buffer for this as opposed
4156 * to allocating and freeing a buffer by hand because the call
4157 * to mono_method_full_name () below may trigger class load
4158 * events when it retrieves the signature of the method. So a
4159 * thread-local buffer needs to exist when such events occur.
4161 for (guint i = 0; i < entry->methods->len; i++) {
4162 MethodInfo *info = (MethodInfo *) g_ptr_array_index (entry->methods, i);
4164 if (mono_conc_hashtable_lookup (log_profiler.method_table, info->method))
4165 goto free_info; // This method already has metadata emitted.
4168 * Other threads use this hash table to get a general
4169 * idea of whether a method has already been emitted to
4170 * the stream. Due to the way we add to this table, it
4171 * can easily happen that multiple threads queue up the
4172 * same methods, but that's OK since eventually all
4173 * methods will be in this table and the thread-local
4174 * method lists will just be empty for the rest of the
4177 mono_os_mutex_lock (&log_profiler.method_table_mutex);
4178 mono_conc_hashtable_insert (log_profiler.method_table, info->method, info->method);
4179 mono_os_mutex_unlock (&log_profiler.method_table_mutex);
4181 char *name = mono_method_full_name (info->method, 1);
4182 int nlen = strlen (name) + 1;
4183 void *cstart = info->ji ? mono_jit_info_get_code_start (info->ji) : NULL;
4184 int csize = info->ji ? mono_jit_info_get_code_size (info->ji) : 0;
4186 ENTER_LOG (&method_jits_ctr, logbuffer,
4187 EVENT_SIZE /* event */ +
4188 LEB128_SIZE /* method */ +
4189 LEB128_SIZE /* start */ +
4190 LEB128_SIZE /* size */ +
4194 emit_event_time (logbuffer, TYPE_JIT | TYPE_METHOD, info->time);
4195 emit_method_inner (logbuffer, info->method);
4196 emit_ptr (logbuffer, cstart);
4197 emit_value (logbuffer, csize);
4199 memcpy (logbuffer->cursor, name, nlen);
4200 logbuffer->cursor += nlen;
4202 EXIT_LOG_EXPLICIT (NO_SEND);
4206 wrote_methods = TRUE;
4212 g_ptr_array_free (entry->methods, TRUE);
4214 if (wrote_methods) {
4215 MonoProfilerThread *thread = PROF_TLS_GET ();
4217 dump_buffer_threadless (thread->buffer);
4218 init_buffer_state (thread);
4222 dump_buffer (entry->buffer);
4224 mono_thread_hazardous_try_free (entry, free_writer_entry);
4233 writer_thread (void *arg)
4235 mono_threads_attach_tools_thread ();
4236 mono_native_thread_set_name (mono_native_thread_id_get (), "Profiler writer");
4240 MonoProfilerThread *thread = init_thread (FALSE);
4242 while (InterlockedRead (&log_profiler.run_writer_thread)) {
4243 mono_os_sem_wait (&log_profiler.writer_queue_sem, MONO_SEM_FLAGS_NONE);
4244 handle_writer_queue_entry ();
4247 /* Drain any remaining entries on shutdown. */
4248 while (handle_writer_queue_entry ());
4250 free_buffer (thread->buffer, thread->buffer->size);
4251 deinit_thread (thread);
4253 mono_thread_info_detach ();
4259 start_writer_thread (void)
4261 InterlockedWrite (&log_profiler.run_writer_thread, 1);
4263 if (!mono_native_thread_create (&log_profiler.writer_thread, writer_thread, NULL)) {
4264 mono_profiler_printf_err ("Could not start log profiler writer thread");
4270 reuse_sample_hit (gpointer p)
4272 SampleHit *sample = p;
4274 mono_lock_free_queue_node_unpoison (&sample->node);
4275 mono_lock_free_queue_enqueue (&log_profiler.sample_reuse_queue, &sample->node);
4279 handle_dumper_queue_entry (void)
4283 if ((sample = (SampleHit *) mono_lock_free_queue_dequeue (&log_profiler.dumper_queue))) {
4284 for (int i = 0; i < sample->count; ++i) {
4285 MonoMethod *method = sample->frames [i].method;
4286 MonoDomain *domain = sample->frames [i].domain;
4287 void *address = sample->frames [i].base_address;
4290 g_assert (domain && "What happened to the domain pointer?");
4291 g_assert (address && "What happened to the instruction pointer?");
4293 MonoJitInfo *ji = mono_jit_info_table_find (domain, (char *) address);
4296 sample->frames [i].method = mono_jit_info_get_method (ji);
4300 ENTER_LOG (&sample_hits_ctr, logbuffer,
4301 EVENT_SIZE /* event */ +
4302 LEB128_SIZE /* tid */ +
4303 LEB128_SIZE /* count */ +
4305 LEB128_SIZE /* ip */
4307 LEB128_SIZE /* managed count */ +
4309 LEB128_SIZE /* method */
4313 emit_event_time (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_HIT, sample->time);
4314 emit_ptr (logbuffer, (void *) sample->tid);
4315 emit_value (logbuffer, 1);
4317 // TODO: Actual native unwinding.
4318 for (int i = 0; i < 1; ++i) {
4319 emit_ptr (logbuffer, sample->ip);
4320 add_code_pointer ((uintptr_t) sample->ip);
4323 /* new in data version 6 */
4324 emit_uvalue (logbuffer, sample->count);
4326 for (int i = 0; i < sample->count; ++i)
4327 emit_method (logbuffer, sample->frames [i].method);
4329 EXIT_LOG_EXPLICIT (DO_SEND);
4331 mono_thread_hazardous_try_free (sample, reuse_sample_hit);
4333 dump_unmanaged_coderefs ();
4340 dumper_thread (void *arg)
4342 mono_threads_attach_tools_thread ();
4343 mono_native_thread_set_name (mono_native_thread_id_get (), "Profiler dumper");
4345 MonoProfilerThread *thread = init_thread (FALSE);
4347 while (InterlockedRead (&log_profiler.run_dumper_thread)) {
4349 * Flush samples every second so it doesn't seem like the profiler is
4350 * not working if the program is mostly idle.
4352 if (mono_os_sem_timedwait (&log_profiler.dumper_queue_sem, 1000, MONO_SEM_FLAGS_NONE) == MONO_SEM_TIMEDWAIT_RET_TIMEDOUT)
4353 send_log_unsafe (FALSE);
4355 handle_dumper_queue_entry ();
4358 /* Drain any remaining entries on shutdown. */
4359 while (handle_dumper_queue_entry ());
4361 send_log_unsafe (FALSE);
4362 deinit_thread (thread);
4364 mono_thread_info_detach ();
4370 start_dumper_thread (void)
4372 InterlockedWrite (&log_profiler.run_dumper_thread, 1);
4374 if (!mono_native_thread_create (&log_profiler.dumper_thread, dumper_thread, NULL)) {
4375 mono_profiler_printf_err ("Could not start log profiler dumper thread");
4381 register_counter (const char *name, gint32 *counter)
4383 mono_counters_register (name, MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, counter);
4387 runtime_initialized (MonoProfiler *profiler)
4389 InterlockedWrite (&log_profiler.runtime_inited, 1);
4391 register_counter ("Sample events allocated", &sample_allocations_ctr);
4392 register_counter ("Log buffers allocated", &buffer_allocations_ctr);
4394 register_counter ("Event: Sync points", &sync_points_ctr);
4395 register_counter ("Event: Heap objects", &heap_objects_ctr);
4396 register_counter ("Event: Heap starts", &heap_starts_ctr);
4397 register_counter ("Event: Heap ends", &heap_ends_ctr);
4398 register_counter ("Event: Heap roots", &heap_roots_ctr);
4399 register_counter ("Event: GC events", &gc_events_ctr);
4400 register_counter ("Event: GC resizes", &gc_resizes_ctr);
4401 register_counter ("Event: GC allocations", &gc_allocs_ctr);
4402 register_counter ("Event: GC moves", &gc_moves_ctr);
4403 register_counter ("Event: GC handle creations", &gc_handle_creations_ctr);
4404 register_counter ("Event: GC handle deletions", &gc_handle_deletions_ctr);
4405 register_counter ("Event: GC finalize starts", &finalize_begins_ctr);
4406 register_counter ("Event: GC finalize ends", &finalize_ends_ctr);
4407 register_counter ("Event: GC finalize object starts", &finalize_object_begins_ctr);
4408 register_counter ("Event: GC finalize object ends", &finalize_object_ends_ctr);
4409 register_counter ("Event: Image loads", &image_loads_ctr);
4410 register_counter ("Event: Image unloads", &image_unloads_ctr);
4411 register_counter ("Event: Assembly loads", &assembly_loads_ctr);
4412 register_counter ("Event: Assembly unloads", &assembly_unloads_ctr);
4413 register_counter ("Event: Class loads", &class_loads_ctr);
4414 register_counter ("Event: Class unloads", &class_unloads_ctr);
4415 register_counter ("Event: Method entries", &method_entries_ctr);
4416 register_counter ("Event: Method exits", &method_exits_ctr);
4417 register_counter ("Event: Method exception leaves", &method_exception_exits_ctr);
4418 register_counter ("Event: Method JITs", &method_jits_ctr);
4419 register_counter ("Event: Code buffers", &code_buffers_ctr);
4420 register_counter ("Event: Exception throws", &exception_throws_ctr);
4421 register_counter ("Event: Exception clauses", &exception_clauses_ctr);
4422 register_counter ("Event: Monitor events", &monitor_events_ctr);
4423 register_counter ("Event: Thread starts", &thread_starts_ctr);
4424 register_counter ("Event: Thread ends", &thread_ends_ctr);
4425 register_counter ("Event: Thread names", &thread_names_ctr);
4426 register_counter ("Event: Domain loads", &domain_loads_ctr);
4427 register_counter ("Event: Domain unloads", &domain_unloads_ctr);
4428 register_counter ("Event: Domain names", &domain_names_ctr);
4429 register_counter ("Event: Context loads", &context_loads_ctr);
4430 register_counter ("Event: Context unloads", &context_unloads_ctr);
4431 register_counter ("Event: Sample binaries", &sample_ubins_ctr);
4432 register_counter ("Event: Sample symbols", &sample_usyms_ctr);
4433 register_counter ("Event: Sample hits", &sample_hits_ctr);
4434 register_counter ("Event: Counter descriptors", &counter_descriptors_ctr);
4435 register_counter ("Event: Counter samples", &counter_samples_ctr);
4436 register_counter ("Event: Performance counter descriptors", &perfcounter_descriptors_ctr);
4437 register_counter ("Event: Performance counter samples", &perfcounter_samples_ctr);
4438 register_counter ("Event: Coverage methods", &coverage_methods_ctr);
4439 register_counter ("Event: Coverage statements", &coverage_statements_ctr);
4440 register_counter ("Event: Coverage classes", &coverage_classes_ctr);
4441 register_counter ("Event: Coverage assemblies", &coverage_assemblies_ctr);
4446 * We must start the helper thread before the writer thread. This is
4447 * because the helper thread sets up the command port which is written to
4448 * the log header by the writer thread.
4450 start_helper_thread ();
4451 start_writer_thread ();
4452 start_dumper_thread ();
4456 create_profiler (const char *args, const char *filename, GPtrArray *filters)
4460 log_profiler.args = pstrdup (args);
4461 log_profiler.command_port = log_config.command_port;
4463 //If filename begin with +, append the pid at the end
4464 if (filename && *filename == '+')
4465 filename = g_strdup_printf ("%s.%d", filename + 1, getpid ());
4468 if (log_config.do_report)
4469 filename = "|mprof-report -";
4471 filename = "output.mlpd";
4472 nf = (char*)filename;
4474 nf = new_filename (filename);
4475 if (log_config.do_report) {
4476 int s = strlen (nf) + 32;
4477 char *p = (char *) g_malloc (s);
4478 snprintf (p, s, "|mprof-report '--out=%s' -", nf);
4484 log_profiler.file = popen (nf + 1, "w");
4485 log_profiler.pipe_output = 1;
4486 } else if (*nf == '#') {
4487 int fd = strtol (nf + 1, NULL, 10);
4488 log_profiler.file = fdopen (fd, "a");
4490 log_profiler.file = fopen (nf, "wb");
4492 if (!log_profiler.file) {
4493 mono_profiler_printf_err ("Could not create log profiler output file '%s'.", nf);
4497 #if defined (HAVE_SYS_ZLIB)
4498 if (log_config.use_zip)
4499 log_profiler.gzfile = gzdopen (fileno (log_profiler.file), "wb");
4503 * If you hit this assert while increasing MAX_FRAMES, you need to increase
4504 * SAMPLE_BLOCK_SIZE as well.
4506 g_assert (SAMPLE_SLOT_SIZE (MAX_FRAMES) * 2 < LOCK_FREE_ALLOC_SB_USABLE_SIZE (SAMPLE_BLOCK_SIZE));
4508 // FIXME: We should free this stuff too.
4509 mono_lock_free_allocator_init_size_class (&log_profiler.sample_size_class, SAMPLE_SLOT_SIZE (log_config.num_frames), SAMPLE_BLOCK_SIZE);
4510 mono_lock_free_allocator_init_allocator (&log_profiler.sample_allocator, &log_profiler.sample_size_class, MONO_MEM_ACCOUNT_PROFILER);
4512 mono_lock_free_queue_init (&log_profiler.sample_reuse_queue);
4514 g_assert (sizeof (WriterQueueEntry) * 2 < LOCK_FREE_ALLOC_SB_USABLE_SIZE (WRITER_ENTRY_BLOCK_SIZE));
4516 // FIXME: We should free this stuff too.
4517 mono_lock_free_allocator_init_size_class (&log_profiler.writer_entry_size_class, sizeof (WriterQueueEntry), WRITER_ENTRY_BLOCK_SIZE);
4518 mono_lock_free_allocator_init_allocator (&log_profiler.writer_entry_allocator, &log_profiler.writer_entry_size_class, MONO_MEM_ACCOUNT_PROFILER);
4520 mono_lock_free_queue_init (&log_profiler.writer_queue);
4521 mono_os_sem_init (&log_profiler.writer_queue_sem, 0);
4523 mono_lock_free_queue_init (&log_profiler.dumper_queue);
4524 mono_os_sem_init (&log_profiler.dumper_queue_sem, 0);
4526 mono_os_mutex_init (&log_profiler.method_table_mutex);
4527 log_profiler.method_table = mono_conc_hashtable_new (NULL, NULL);
4529 if (ENABLED (PROFLOG_CODE_COV_FEATURE))
4532 log_profiler.coverage_filters = filters;
4534 log_profiler.startup_time = current_time ();
4538 * declaration to silence the compiler: this is the entry point that
4539 * mono will load from the shared library and call.
4542 mono_profiler_init (const char *desc);
4545 mono_profiler_init_log (const char *desc);
4548 * this is the entry point that will be used when the profiler
4549 * is embedded inside the main executable.
4552 mono_profiler_init_log (const char *desc)
4554 mono_profiler_init (desc);
4558 mono_profiler_init (const char *desc)
4560 GPtrArray *filters = NULL;
4562 proflog_parse_args (&log_config, desc [3] == ':' ? desc + 4 : "");
4564 if (log_config.cov_filter_files) {
4565 filters = g_ptr_array_new ();
4567 for (i = 0; i < log_config.cov_filter_files->len; ++i) {
4568 const char *name = log_config.cov_filter_files->pdata [i];
4569 parse_cov_filter_file (filters, name);
4577 create_profiler (desc, log_config.output_filename, filters);
4579 mono_lls_init (&log_profiler.profiler_thread_list, NULL);
4581 MonoProfilerHandle handle = log_profiler.handle = mono_profiler_install (&log_profiler);
4583 //Required callbacks
4584 mono_profiler_set_runtime_shutdown_end_callback (handle, log_shutdown);
4585 mono_profiler_set_runtime_initialized_callback (handle, runtime_initialized);
4587 mono_profiler_set_gc_event_callback (handle, gc_event);
4588 mono_profiler_set_gc_resize_callback (handle, gc_resize);
4589 mono_profiler_set_thread_started_callback (handle, thread_start);
4590 mono_profiler_set_thread_stopped_callback (handle, thread_end);
4592 //It's questionable whether we actually want this to be mandatory, maybe put it behind the actual event?
4593 mono_profiler_set_thread_name_callback (handle, thread_name);
4595 if (log_config.effective_mask & PROFLOG_DOMAIN_EVENTS) {
4596 mono_profiler_set_domain_loaded_callback (handle, domain_loaded);
4597 mono_profiler_set_domain_unloading_callback (handle, domain_unloaded);
4598 mono_profiler_set_domain_name_callback (handle, domain_name);
4601 if (log_config.effective_mask & PROFLOG_ASSEMBLY_EVENTS) {
4602 mono_profiler_set_assembly_loaded_callback (handle, assembly_loaded);
4603 mono_profiler_set_assembly_unloading_callback (handle, assembly_unloaded);
4606 if (log_config.effective_mask & PROFLOG_MODULE_EVENTS) {
4607 mono_profiler_set_image_loaded_callback (handle, image_loaded);
4608 mono_profiler_set_image_unloading_callback (handle, image_unloaded);
4611 if (log_config.effective_mask & PROFLOG_CLASS_EVENTS)
4612 mono_profiler_set_class_loaded_callback (handle, class_loaded);
4614 if (log_config.effective_mask & PROFLOG_JIT_COMPILATION_EVENTS) {
4615 mono_profiler_set_jit_done_callback (handle, method_jitted);
4616 mono_profiler_set_jit_code_buffer_callback (handle, code_buffer_new);
4619 if (log_config.effective_mask & PROFLOG_EXCEPTION_EVENTS) {
4620 mono_profiler_set_exception_throw_callback (handle, throw_exc);
4621 mono_profiler_set_exception_clause_callback (handle, clause_exc);
4624 if (log_config.effective_mask & PROFLOG_ALLOCATION_EVENTS) {
4625 mono_profiler_enable_allocations ();
4626 mono_profiler_set_gc_allocation_callback (handle, gc_alloc);
4629 //PROFLOG_GC_EVENTS is mandatory
4630 //PROFLOG_THREAD_EVENTS is mandatory
4632 if (log_config.effective_mask & PROFLOG_CALL_EVENTS) {
4633 mono_profiler_set_call_instrumentation_filter_callback (handle, method_filter);
4634 mono_profiler_set_method_enter_callback (handle, method_enter);
4635 mono_profiler_set_method_leave_callback (handle, method_leave);
4636 mono_profiler_set_method_exception_leave_callback (handle, method_exc_leave);
4639 if (log_config.effective_mask & PROFLOG_INS_COVERAGE_EVENTS)
4640 mono_profiler_set_coverage_filter_callback (handle, coverage_filter);
4642 if (log_config.effective_mask & PROFLOG_SAMPLING_EVENTS) {
4643 mono_profiler_enable_sampling (handle);
4645 if (!mono_profiler_set_sample_mode (handle, log_config.sampling_mode, log_config.sample_freq))
4646 mono_profiler_printf_err ("Another profiler controls sampling parameters; the log profiler will not be able to modify them.");
4648 mono_profiler_set_sample_hit_callback (handle, mono_sample_hit);
4651 if (log_config.effective_mask & PROFLOG_MONITOR_EVENTS) {
4652 mono_profiler_set_monitor_contention_callback (handle, monitor_contention);
4653 mono_profiler_set_monitor_acquired_callback (handle, monitor_acquired);
4654 mono_profiler_set_monitor_failed_callback (handle, monitor_failed);
4657 if (log_config.effective_mask & PROFLOG_GC_MOVES_EVENTS)
4658 mono_profiler_set_gc_moves_callback (handle, gc_moves);
4660 if (log_config.effective_mask & PROFLOG_GC_ROOT_EVENTS)
4661 mono_profiler_set_gc_roots_callback (handle, gc_roots);
4663 if (log_config.effective_mask & PROFLOG_CONTEXT_EVENTS) {
4664 mono_profiler_set_context_loaded_callback (handle, context_loaded);
4665 mono_profiler_set_context_unloaded_callback (handle, context_unloaded);
4668 if (log_config.effective_mask & PROFLOG_FINALIZATION_EVENTS) {
4669 mono_profiler_set_gc_finalizing_callback (handle, finalize_begin);
4670 mono_profiler_set_gc_finalized_callback (handle, finalize_end);
4671 mono_profiler_set_gc_finalizing_object_callback (handle, finalize_object_begin);
4672 mono_profiler_set_gc_finalized_object_callback (handle, finalize_object_end);
4673 } else if (ENABLED (PROFLOG_HEAPSHOT_FEATURE) && log_config.hs_mode_ondemand) {
4674 //On Demand heapshot uses the finalizer thread to force a collection and thus a heapshot
4675 mono_profiler_set_gc_finalized_callback (handle, finalize_end);
4678 //PROFLOG_COUNTER_EVENTS is a pseudo event controled by the no_counters global var
4680 if (log_config.effective_mask & PROFLOG_GC_HANDLE_EVENTS) {
4681 mono_profiler_set_gc_handle_created_callback (handle, gc_handle_created);
4682 mono_profiler_set_gc_handle_deleted_callback (handle, gc_handle_deleted);