2 * 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;
566 struct _MonoProfiler {
567 MonoProfilerHandle handle;
570 #if defined (HAVE_SYS_ZLIB)
575 uint64_t startup_time;
579 mach_timebase_info_data_t timebase_info;
580 #elif defined (HOST_WIN32)
581 LARGE_INTEGER pcounter_freq;
589 MonoLinkedListSet profiler_thread_list;
590 volatile gint32 buffer_lock_state;
591 volatile gint32 buffer_lock_exclusive_intent;
593 volatile gint32 runtime_inited;
594 volatile gint32 in_shutdown;
596 MonoNativeThreadId helper_thread;
598 MonoNativeThreadId writer_thread;
599 volatile gint32 run_writer_thread;
600 MonoLockFreeQueue writer_queue;
601 MonoSemType writer_queue_sem;
603 MonoLockFreeAllocSizeClass writer_entry_size_class;
604 MonoLockFreeAllocator writer_entry_allocator;
606 MonoConcurrentHashTable *method_table;
607 mono_mutex_t method_table_mutex;
609 MonoNativeThreadId dumper_thread;
610 volatile gint32 run_dumper_thread;
611 MonoLockFreeQueue dumper_queue;
612 MonoSemType dumper_queue_sem;
614 MonoLockFreeAllocSizeClass sample_size_class;
615 MonoLockFreeAllocator sample_allocator;
616 MonoLockFreeQueue sample_reuse_queue;
618 BinaryObject *binary_objects;
620 volatile gint32 heapshot_requested;
622 guint64 last_hs_time;
623 gboolean do_heap_walk;
625 mono_mutex_t counters_mutex;
626 MonoCounterAgent *counters;
627 PerfCounterAgent *perfcounters;
628 guint32 counters_index;
630 mono_mutex_t coverage_mutex;
631 GPtrArray *coverage_data;
633 GPtrArray *coverage_filters;
634 MonoConcurrentHashTable *coverage_filtered_classes;
635 MonoConcurrentHashTable *coverage_suppressed_assemblies;
637 MonoConcurrentHashTable *coverage_methods;
638 MonoConcurrentHashTable *coverage_assemblies;
639 MonoConcurrentHashTable *coverage_classes;
641 MonoConcurrentHashTable *coverage_image_to_methods;
643 guint32 coverage_previous_offset;
644 guint32 coverage_method_id;
647 static ProfilerConfig log_config;
648 static struct _MonoProfiler log_profiler;
651 MonoLockFreeQueueNode node;
656 #define WRITER_ENTRY_BLOCK_SIZE (mono_pagesize ())
664 #define TICKS_PER_SEC 1000000000LL
670 uint64_t time = mach_absolute_time ();
672 time *= log_profiler.timebase_info.numer;
673 time /= log_profiler.timebase_info.denom;
676 #elif defined (HOST_WIN32)
679 QueryPerformanceCounter (&value);
681 return value.QuadPart * TICKS_PER_SEC / log_profiler.pcounter_freq.QuadPart;
682 #elif defined (CLOCK_MONOTONIC)
683 struct timespec tspec;
685 clock_gettime (CLOCK_MONOTONIC, &tspec);
687 return ((uint64_t) tspec.tv_sec * TICKS_PER_SEC + tspec.tv_nsec);
691 gettimeofday (&tv, NULL);
693 return ((uint64_t) tv.tv_sec * TICKS_PER_SEC + tv.tv_usec * 1000);
701 mach_timebase_info (&log_profiler.timebase_info);
702 #elif defined (HOST_WIN32)
703 QueryPerformanceFrequency (&log_profiler.pcounter_freq);
706 uint64_t time_start = current_time ();
708 for (int i = 0; i < 256; ++i)
711 uint64_t time_end = current_time ();
713 log_profiler.timer_overhead = (time_end - time_start) / 256;
717 pstrdup (const char *s)
719 int len = strlen (s) + 1;
720 char *p = (char *) g_malloc (len);
725 #define BUFFER_SIZE (4096 * 16)
727 /* Worst-case size in bytes of a 64-bit value encoded with LEB128. */
728 #define LEB128_SIZE 10
730 /* Size of a value encoded as a single byte. */
731 #undef BYTE_SIZE // mach/i386/vm_param.h on OS X defines this to 8, but it isn't used for anything.
734 /* Size in bytes of the event prefix (ID + time). */
735 #define EVENT_SIZE (BYTE_SIZE + LEB128_SIZE)
738 alloc_buffer (int size)
740 return mono_valloc (NULL, size, MONO_MMAP_READ | MONO_MMAP_WRITE | MONO_MMAP_ANON | MONO_MMAP_PRIVATE, MONO_MEM_ACCOUNT_PROFILER);
744 free_buffer (void *buf, int size)
746 mono_vfree (buf, size, MONO_MEM_ACCOUNT_PROFILER);
750 create_buffer (uintptr_t tid, int bytes)
752 LogBuffer* buf = (LogBuffer *) alloc_buffer (MAX (BUFFER_SIZE, bytes));
754 InterlockedIncrement (&buffer_allocations_ctr);
756 buf->size = BUFFER_SIZE;
757 buf->time_base = current_time ();
758 buf->last_time = buf->time_base;
759 buf->buf_end = (unsigned char *) buf + buf->size;
760 buf->cursor = buf->buf;
761 buf->thread_id = tid;
767 * Must be called with the reader lock held if thread is the current thread, or
768 * the exclusive lock if thread is a different thread. However, if thread is
769 * the current thread, and init_thread () was called with add_to_lls = FALSE,
770 * then no locking is necessary.
773 init_buffer_state (MonoProfilerThread *thread)
775 thread->buffer = create_buffer (thread->node.key, 0);
776 thread->methods = NULL;
780 clear_hazard_pointers (MonoThreadHazardPointers *hp)
782 mono_hazard_pointer_clear (hp, 0);
783 mono_hazard_pointer_clear (hp, 1);
784 mono_hazard_pointer_clear (hp, 2);
787 static MonoProfilerThread *
788 init_thread (gboolean add_to_lls)
790 MonoProfilerThread *thread = PROF_TLS_GET ();
793 * Sometimes we may try to initialize a thread twice. One example is the
794 * main thread: We initialize it when setting up the profiler, but we will
795 * also get a thread_start () callback for it. Another example is when
796 * attaching new threads to the runtime: We may get a gc_alloc () callback
797 * for that thread's thread object (where we initialize it), soon followed
798 * by a thread_start () callback.
800 * These cases are harmless anyhow. Just return if we've already done the
801 * initialization work.
806 thread = g_malloc (sizeof (MonoProfilerThread));
807 thread->node.key = thread_id ();
808 thread->attached = add_to_lls;
809 thread->call_depth = 0;
811 thread->ended = FALSE;
813 init_buffer_state (thread);
815 thread->small_id = mono_thread_info_register_small_id ();
818 * Some internal profiler threads don't need to be cleaned up
819 * by the main thread on shutdown.
822 MonoThreadHazardPointers *hp = mono_hazard_pointer_get ();
823 g_assert (mono_lls_insert (&log_profiler.profiler_thread_list, hp, &thread->node) && "Why can't we insert the thread in the LLS?");
824 clear_hazard_pointers (hp);
827 PROF_TLS_SET (thread);
832 // Only valid if init_thread () was called with add_to_lls = FALSE.
834 deinit_thread (MonoProfilerThread *thread)
836 g_assert (!thread->attached && "Why are we manually freeing an attached thread?");
842 static MonoProfilerThread *
845 return init_thread (TRUE);
848 // Only valid if init_thread () was called with add_to_lls = FALSE.
850 ensure_logbuf_unsafe (MonoProfilerThread *thread, int bytes)
852 LogBuffer *old = thread->buffer;
854 if (old->cursor + bytes < old->buf_end)
857 LogBuffer *new_ = create_buffer (thread->node.key, bytes);
859 thread->buffer = new_;
865 * This is a reader/writer spin lock of sorts used to protect log buffers.
866 * When a thread modifies its own log buffer, it increments the reader
867 * count. When a thread wants to access log buffers of other threads, it
868 * takes the exclusive lock.
870 * `buffer_lock_state` holds the reader count in its lower 16 bits, and
871 * the small ID of the thread currently holding the exclusive (writer)
872 * lock in its upper 16 bits. Both can be zero. It's important that the
873 * whole lock state is a single word that can be read/written atomically
874 * to avoid race conditions where there could end up being readers while
875 * the writer lock is held.
877 * The lock is writer-biased. When a thread wants to take the exclusive
878 * lock, it increments `buffer_lock_exclusive_intent` which will make new
879 * readers spin until it's back to zero, then takes the exclusive lock
880 * once the reader count has reached zero. After releasing the exclusive
881 * lock, it decrements `buffer_lock_exclusive_intent`, which, when it
882 * reaches zero again, allows readers to increment the reader count.
884 * The writer bias is necessary because we take the exclusive lock in
885 * `gc_event ()` during STW. If the writer bias was not there, and a
886 * program had a large number of threads, STW-induced pauses could be
887 * significantly longer than they have to be. Also, we emit periodic
888 * sync points from the helper thread, which requires taking the
889 * exclusive lock, and we need those to arrive with a reasonably
890 * consistent frequency so that readers don't have to queue up too many
891 * events between sync points.
893 * The lock does not support recursion.
900 * If the thread holding the exclusive lock tries to modify the
901 * reader count, just make it a no-op. This way, we also avoid
902 * invoking the GC safe point macros below, which could break if
903 * done from a thread that is currently the initiator of STW.
905 * In other words, we rely on the fact that the GC thread takes
906 * the exclusive lock in the gc_event () callback when the world
909 if (InterlockedRead (&log_profiler.buffer_lock_state) != get_thread ()->small_id << 16) {
916 // Hold off if a thread wants to take the exclusive lock.
917 while (InterlockedRead (&log_profiler.buffer_lock_exclusive_intent))
918 mono_thread_info_yield ();
920 old = InterlockedRead (&log_profiler.buffer_lock_state);
922 // Is a thread holding the exclusive lock?
924 mono_thread_info_yield ();
929 } while (InterlockedCompareExchange (&log_profiler.buffer_lock_state, new_, old) != old);
934 mono_memory_barrier ();
940 mono_memory_barrier ();
942 gint32 state = InterlockedRead (&log_profiler.buffer_lock_state);
944 // See the comment in buffer_lock ().
945 if (state == PROF_TLS_GET ()->small_id << 16)
948 g_assert (state && "Why are we decrementing a zero reader count?");
949 g_assert (!(state >> 16) && "Why is the exclusive lock held?");
951 InterlockedDecrement (&log_profiler.buffer_lock_state);
955 buffer_lock_excl (void)
957 gint32 new_ = get_thread ()->small_id << 16;
959 g_assert (InterlockedRead (&log_profiler.buffer_lock_state) != new_ && "Why are we taking the exclusive lock twice?");
961 InterlockedIncrement (&log_profiler.buffer_lock_exclusive_intent);
965 while (InterlockedCompareExchange (&log_profiler.buffer_lock_state, new_, 0))
966 mono_thread_info_yield ();
970 mono_memory_barrier ();
974 buffer_unlock_excl (void)
976 mono_memory_barrier ();
978 gint32 state = InterlockedRead (&log_profiler.buffer_lock_state);
979 gint32 excl = state >> 16;
981 g_assert (excl && "Why is the exclusive lock not held?");
982 g_assert (excl == PROF_TLS_GET ()->small_id && "Why does another thread hold the exclusive lock?");
983 g_assert (!(state & 0xFFFF) && "Why are there readers when the exclusive lock is held?");
985 InterlockedWrite (&log_profiler.buffer_lock_state, 0);
986 InterlockedDecrement (&log_profiler.buffer_lock_exclusive_intent);
990 encode_uleb128 (uint64_t value, uint8_t *buf, uint8_t **endbuf)
995 uint8_t b = value & 0x7f;
998 if (value != 0) /* more bytes to come */
1008 encode_sleb128 (intptr_t value, uint8_t *buf, uint8_t **endbuf)
1011 int negative = (value < 0);
1012 unsigned int size = sizeof (intptr_t) * 8;
1017 byte = value & 0x7f;
1020 /* the following is unnecessary if the
1021 * implementation of >>= uses an arithmetic rather
1022 * than logical shift for a signed left operand
1026 value |= - ((intptr_t) 1 <<(size - 7));
1028 /* sign bit of byte is second high order bit (0x40) */
1029 if ((value == 0 && !(byte & 0x40)) ||
1030 (value == -1 && (byte & 0x40)))
1042 emit_byte (LogBuffer *logbuffer, int value)
1044 logbuffer->cursor [0] = value;
1045 logbuffer->cursor++;
1047 g_assert (logbuffer->cursor <= logbuffer->buf_end && "Why are we writing past the buffer end?");
1051 emit_value (LogBuffer *logbuffer, int value)
1053 encode_uleb128 (value, logbuffer->cursor, &logbuffer->cursor);
1055 g_assert (logbuffer->cursor <= logbuffer->buf_end && "Why are we writing past the buffer end?");
1059 emit_time (LogBuffer *logbuffer, uint64_t value)
1061 uint64_t tdiff = value - logbuffer->last_time;
1062 encode_uleb128 (tdiff, logbuffer->cursor, &logbuffer->cursor);
1063 logbuffer->last_time = value;
1065 g_assert (logbuffer->cursor <= logbuffer->buf_end && "Why are we writing past the buffer end?");
1069 emit_event_time (LogBuffer *logbuffer, int event, uint64_t time)
1071 emit_byte (logbuffer, event);
1072 emit_time (logbuffer, time);
1076 emit_event (LogBuffer *logbuffer, int event)
1078 emit_event_time (logbuffer, event, current_time ());
1082 emit_svalue (LogBuffer *logbuffer, int64_t value)
1084 encode_sleb128 (value, logbuffer->cursor, &logbuffer->cursor);
1086 g_assert (logbuffer->cursor <= logbuffer->buf_end && "Why are we writing past the buffer end?");
1090 emit_uvalue (LogBuffer *logbuffer, uint64_t value)
1092 encode_uleb128 (value, logbuffer->cursor, &logbuffer->cursor);
1094 g_assert (logbuffer->cursor <= logbuffer->buf_end && "Why are we writing past the buffer end?");
1098 emit_ptr (LogBuffer *logbuffer, const void *ptr)
1100 if (!logbuffer->ptr_base)
1101 logbuffer->ptr_base = (uintptr_t) ptr;
1103 emit_svalue (logbuffer, (intptr_t) ptr - logbuffer->ptr_base);
1105 g_assert (logbuffer->cursor <= logbuffer->buf_end && "Why are we writing past the buffer end?");
1109 emit_method_inner (LogBuffer *logbuffer, void *method)
1111 if (!logbuffer->method_base) {
1112 logbuffer->method_base = (intptr_t) method;
1113 logbuffer->last_method = (intptr_t) method;
1116 encode_sleb128 ((intptr_t) ((char *) method - (char *) logbuffer->last_method), logbuffer->cursor, &logbuffer->cursor);
1117 logbuffer->last_method = (intptr_t) method;
1119 g_assert (logbuffer->cursor <= logbuffer->buf_end && "Why are we writing past the buffer end?");
1122 // The reader lock must be held.
1124 register_method_local (MonoMethod *method, MonoJitInfo *ji)
1126 MonoProfilerThread *thread = get_thread ();
1128 if (!mono_conc_hashtable_lookup (log_profiler.method_table, method)) {
1129 MethodInfo *info = (MethodInfo *) g_malloc (sizeof (MethodInfo));
1131 info->method = method;
1133 info->time = current_time ();
1135 GPtrArray *arr = thread->methods ? thread->methods : (thread->methods = g_ptr_array_new ());
1136 g_ptr_array_add (arr, info);
1141 emit_method (LogBuffer *logbuffer, MonoMethod *method)
1143 register_method_local (method, NULL);
1144 emit_method_inner (logbuffer, method);
1148 emit_obj (LogBuffer *logbuffer, void *ptr)
1150 if (!logbuffer->obj_base)
1151 logbuffer->obj_base = (uintptr_t) ptr >> 3;
1153 emit_svalue (logbuffer, ((uintptr_t) ptr >> 3) - logbuffer->obj_base);
1155 g_assert (logbuffer->cursor <= logbuffer->buf_end && "Why are we writing past the buffer end?");
1159 emit_string (LogBuffer *logbuffer, const char *str, size_t size)
1163 for (; i < size; i++) {
1166 emit_byte (logbuffer, str [i]);
1169 emit_byte (logbuffer, '\0');
1173 emit_double (LogBuffer *logbuffer, double value)
1176 unsigned char buffer[8];
1177 memcpy (buffer, &value, 8);
1178 #if G_BYTE_ORDER == G_BIG_ENDIAN
1179 for (i = 7; i >= 0; i--)
1181 for (i = 0; i < 8; i++)
1183 emit_byte (logbuffer, buffer[i]);
1187 write_int16 (char *buf, int32_t value)
1190 for (i = 0; i < 2; ++i) {
1198 write_int32 (char *buf, int32_t value)
1201 for (i = 0; i < 4; ++i) {
1209 write_int64 (char *buf, int64_t value)
1212 for (i = 0; i < 8; ++i) {
1220 write_header_string (char *p, const char *str)
1222 size_t len = strlen (str) + 1;
1224 p = write_int32 (p, len);
1233 const char *args = log_profiler.args;
1234 const char *arch = mono_config_get_cpu ();
1235 const char *os = mono_config_get_os ();
1237 char *hbuf = g_malloc (
1238 sizeof (gint32) /* header id */ +
1239 sizeof (gint8) /* major version */ +
1240 sizeof (gint8) /* minor version */ +
1241 sizeof (gint8) /* data version */ +
1242 sizeof (gint8) /* word size */ +
1243 sizeof (gint64) /* startup time */ +
1244 sizeof (gint32) /* timer overhead */ +
1245 sizeof (gint32) /* flags */ +
1246 sizeof (gint32) /* process id */ +
1247 sizeof (gint16) /* command port */ +
1248 sizeof (gint32) + strlen (args) + 1 /* arguments */ +
1249 sizeof (gint32) + strlen (arch) + 1 /* architecture */ +
1250 sizeof (gint32) + strlen (os) + 1 /* operating system */
1254 p = write_int32 (p, LOG_HEADER_ID);
1255 *p++ = LOG_VERSION_MAJOR;
1256 *p++ = LOG_VERSION_MINOR;
1257 *p++ = LOG_DATA_VERSION;
1258 *p++ = sizeof (void *);
1259 p = write_int64 (p, ((uint64_t) time (NULL)) * 1000);
1260 p = write_int32 (p, log_profiler.timer_overhead);
1261 p = write_int32 (p, 0); /* flags */
1262 p = write_int32 (p, process_id ());
1263 p = write_int16 (p, log_profiler.command_port);
1264 p = write_header_string (p, args);
1265 p = write_header_string (p, arch);
1266 p = write_header_string (p, os);
1268 #if defined (HAVE_SYS_ZLIB)
1269 if (log_profiler.gzfile) {
1270 gzwrite (log_profiler.gzfile, hbuf, p - hbuf);
1274 fwrite (hbuf, p - hbuf, 1, log_profiler.file);
1275 fflush (log_profiler.file);
1282 * Must be called with the reader lock held if thread is the current thread, or
1283 * the exclusive lock if thread is a different thread. However, if thread is
1284 * the current thread, and init_thread () was called with add_to_lls = FALSE,
1285 * then no locking is necessary.
1288 send_buffer (MonoProfilerThread *thread)
1290 WriterQueueEntry *entry = mono_lock_free_alloc (&log_profiler.writer_entry_allocator);
1291 entry->methods = thread->methods;
1292 entry->buffer = thread->buffer;
1294 mono_lock_free_queue_node_init (&entry->node, FALSE);
1296 mono_lock_free_queue_enqueue (&log_profiler.writer_queue, &entry->node);
1297 mono_os_sem_post (&log_profiler.writer_queue_sem);
1301 free_thread (gpointer p)
1303 MonoProfilerThread *thread = p;
1305 if (!thread->ended) {
1307 * The thread is being cleaned up by the main thread during
1308 * shutdown. This typically happens for internal runtime
1309 * threads. We need to synthesize a thread end event.
1312 InterlockedIncrement (&thread_ends_ctr);
1314 LogBuffer *buf = ensure_logbuf_unsafe (thread,
1315 EVENT_SIZE /* event */ +
1316 BYTE_SIZE /* type */ +
1317 LEB128_SIZE /* tid */
1320 emit_event (buf, TYPE_END_UNLOAD | TYPE_METADATA);
1321 emit_byte (buf, TYPE_THREAD);
1322 emit_ptr (buf, (void *) thread->node.key);
1325 send_buffer (thread);
1331 remove_thread (MonoProfilerThread *thread)
1333 MonoThreadHazardPointers *hp = mono_hazard_pointer_get ();
1335 if (mono_lls_remove (&log_profiler.profiler_thread_list, hp, &thread->node))
1336 mono_thread_hazardous_try_free (thread, free_thread);
1338 clear_hazard_pointers (hp);
1342 dump_buffer (LogBuffer *buf)
1348 dump_buffer (buf->next);
1350 if (buf->cursor - buf->buf) {
1351 p = write_int32 (p, BUF_ID);
1352 p = write_int32 (p, buf->cursor - buf->buf);
1353 p = write_int64 (p, buf->time_base);
1354 p = write_int64 (p, buf->ptr_base);
1355 p = write_int64 (p, buf->obj_base);
1356 p = write_int64 (p, buf->thread_id);
1357 p = write_int64 (p, buf->method_base);
1359 #if defined (HAVE_SYS_ZLIB)
1360 if (log_profiler.gzfile) {
1361 gzwrite (log_profiler.gzfile, hbuf, p - hbuf);
1362 gzwrite (log_profiler.gzfile, buf->buf, buf->cursor - buf->buf);
1366 fwrite (hbuf, p - hbuf, 1, log_profiler.file);
1367 fwrite (buf->buf, buf->cursor - buf->buf, 1, log_profiler.file);
1368 fflush (log_profiler.file);
1372 free_buffer (buf, buf->size);
1376 dump_buffer_threadless (LogBuffer *buf)
1378 for (LogBuffer *iter = buf; iter; iter = iter->next)
1379 iter->thread_id = 0;
1384 // Only valid if init_thread () was called with add_to_lls = FALSE.
1386 send_log_unsafe (gboolean if_needed)
1388 MonoProfilerThread *thread = PROF_TLS_GET ();
1390 if (!if_needed || (if_needed && thread->buffer->next)) {
1391 if (!thread->attached)
1392 for (LogBuffer *iter = thread->buffer; iter; iter = iter->next)
1393 iter->thread_id = 0;
1395 send_buffer (thread);
1396 init_buffer_state (thread);
1400 // Assumes that the exclusive lock is held.
1402 sync_point_flush (void)
1404 g_assert (InterlockedRead (&log_profiler.buffer_lock_state) == PROF_TLS_GET ()->small_id << 16 && "Why don't we hold the exclusive lock?");
1406 MONO_LLS_FOREACH_SAFE (&log_profiler.profiler_thread_list, MonoProfilerThread, thread) {
1407 g_assert (thread->attached && "Why is a thread in the LLS not attached?");
1409 send_buffer (thread);
1410 init_buffer_state (thread);
1411 } MONO_LLS_FOREACH_SAFE_END
1414 // Assumes that the exclusive lock is held.
1416 sync_point_mark (MonoProfilerSyncPointType type)
1418 g_assert (InterlockedRead (&log_profiler.buffer_lock_state) == PROF_TLS_GET ()->small_id << 16 && "Why don't we hold the exclusive lock?");
1420 ENTER_LOG (&sync_points_ctr, logbuffer,
1421 EVENT_SIZE /* event */ +
1422 LEB128_SIZE /* type */
1425 emit_event (logbuffer, TYPE_META | TYPE_SYNC_POINT);
1426 emit_byte (logbuffer, type);
1428 EXIT_LOG_EXPLICIT (NO_SEND);
1430 send_log_unsafe (FALSE);
1433 // Assumes that the exclusive lock is held.
1435 sync_point (MonoProfilerSyncPointType type)
1437 sync_point_flush ();
1438 sync_point_mark (type);
1442 gc_reference (MonoObject *obj, MonoClass *klass, uintptr_t size, uintptr_t num, MonoObject **refs, uintptr_t *offsets, void *data)
1444 /* account for object alignment in the heap */
1448 ENTER_LOG (&heap_objects_ctr, logbuffer,
1449 EVENT_SIZE /* event */ +
1450 LEB128_SIZE /* obj */ +
1451 LEB128_SIZE /* klass */ +
1452 LEB128_SIZE /* size */ +
1453 LEB128_SIZE /* num */ +
1455 LEB128_SIZE /* offset */ +
1456 LEB128_SIZE /* ref */
1460 emit_event (logbuffer, TYPE_HEAP_OBJECT | TYPE_HEAP);
1461 emit_obj (logbuffer, obj);
1462 emit_ptr (logbuffer, klass);
1463 emit_value (logbuffer, size);
1464 emit_value (logbuffer, num);
1466 uintptr_t last_offset = 0;
1468 for (int i = 0; i < num; ++i) {
1469 emit_value (logbuffer, offsets [i] - last_offset);
1470 last_offset = offsets [i];
1471 emit_obj (logbuffer, refs [i]);
1480 gc_roots (MonoProfiler *prof, MonoObject *const *objects, const MonoProfilerGCRootType *root_types, const uintptr_t *extra_info, uint64_t num)
1482 ENTER_LOG (&heap_roots_ctr, logbuffer,
1483 EVENT_SIZE /* event */ +
1484 LEB128_SIZE /* num */ +
1485 LEB128_SIZE /* collections */ +
1487 LEB128_SIZE /* object */ +
1488 LEB128_SIZE /* root type */ +
1489 LEB128_SIZE /* extra info */
1493 emit_event (logbuffer, TYPE_HEAP_ROOT | TYPE_HEAP);
1494 emit_value (logbuffer, num);
1495 emit_value (logbuffer, mono_gc_collection_count (mono_gc_max_generation ()));
1497 for (int i = 0; i < num; ++i) {
1498 emit_obj (logbuffer, objects [i]);
1499 emit_byte (logbuffer, root_types [i]);
1500 emit_value (logbuffer, extra_info [i]);
1508 trigger_on_demand_heapshot (void)
1510 if (InterlockedRead (&log_profiler.heapshot_requested))
1511 mono_gc_collect (mono_gc_max_generation ());
1514 #define ALL_GC_EVENTS_MASK (PROFLOG_GC_EVENTS | PROFLOG_GC_MOVE_EVENTS | PROFLOG_GC_ROOT_EVENTS)
1517 gc_event (MonoProfiler *profiler, MonoProfilerGCEvent ev, uint32_t generation)
1519 if (ENABLED (PROFLOG_GC_EVENTS)) {
1520 ENTER_LOG (&gc_events_ctr, logbuffer,
1521 EVENT_SIZE /* event */ +
1522 BYTE_SIZE /* gc event */ +
1523 BYTE_SIZE /* generation */
1526 emit_event (logbuffer, TYPE_GC_EVENT | TYPE_GC);
1527 emit_byte (logbuffer, ev);
1528 emit_byte (logbuffer, generation);
1534 case MONO_GC_EVENT_START:
1535 if (generation == mono_gc_max_generation ())
1536 log_profiler.gc_count++;
1538 switch (log_config.hs_mode) {
1539 case MONO_PROFILER_HEAPSHOT_NONE:
1540 log_profiler.do_heap_walk = FALSE;
1542 case MONO_PROFILER_HEAPSHOT_MAJOR:
1543 log_profiler.do_heap_walk = generation == mono_gc_max_generation ();
1545 case MONO_PROFILER_HEAPSHOT_ON_DEMAND:
1546 log_profiler.do_heap_walk = InterlockedRead (&log_profiler.heapshot_requested);
1548 case MONO_PROFILER_HEAPSHOT_X_GC:
1549 log_profiler.do_heap_walk = !(log_profiler.gc_count % log_config.hs_freq_gc);
1551 case MONO_PROFILER_HEAPSHOT_X_MS:
1552 log_profiler.do_heap_walk = (current_time () - log_profiler.last_hs_time) / 1000 * 1000 >= log_config.hs_freq_ms;
1555 g_assert_not_reached ();
1558 if (ENABLED (PROFLOG_GC_ROOT_EVENTS) && log_profiler.do_heap_walk)
1559 mono_profiler_set_gc_roots_callback (log_profiler.handle, gc_roots);
1562 case MONO_GC_EVENT_PRE_STOP_WORLD_LOCKED:
1564 * Ensure that no thread can be in the middle of writing to
1565 * a buffer when the world stops...
1567 buffer_lock_excl ();
1569 case MONO_GC_EVENT_POST_STOP_WORLD:
1571 * ... So that we now have a consistent view of all buffers.
1572 * This allows us to flush them. We need to do this because
1573 * they may contain object allocation events that need to be
1574 * committed to the log file before any object move events
1575 * that will be produced during this GC.
1577 if (ENABLED (ALL_GC_EVENTS_MASK))
1578 sync_point (SYNC_POINT_WORLD_STOP);
1580 // Surround heapshots with HEAP_START/HEAP_END events.
1581 if (log_profiler.do_heap_walk) {
1582 ENTER_LOG (&heap_starts_ctr, logbuffer,
1583 EVENT_SIZE /* event */
1586 emit_event (logbuffer, TYPE_HEAP_START | TYPE_HEAP);
1592 case MONO_GC_EVENT_PRE_START_WORLD:
1593 mono_profiler_set_gc_roots_callback (log_profiler.handle, NULL);
1595 if (log_profiler.do_heap_walk) {
1596 mono_gc_walk_heap (0, gc_reference, NULL);
1598 ENTER_LOG (&heap_ends_ctr, logbuffer,
1599 EVENT_SIZE /* event */
1602 emit_event (logbuffer, TYPE_HEAP_END | TYPE_HEAP);
1606 log_profiler.do_heap_walk = FALSE;
1607 log_profiler.last_hs_time = current_time ();
1609 InterlockedWrite (&log_profiler.heapshot_requested, 0);
1613 * Similarly, we must now make sure that any object moves
1614 * written to the GC thread's buffer are flushed. Otherwise,
1615 * object allocation events for certain addresses could come
1616 * after the move events that made those addresses available.
1618 if (ENABLED (ALL_GC_EVENTS_MASK))
1619 sync_point_mark (SYNC_POINT_WORLD_START);
1621 case MONO_GC_EVENT_POST_START_WORLD_UNLOCKED:
1623 * Finally, it is safe to allow other threads to write to
1624 * their buffers again.
1626 buffer_unlock_excl ();
1634 gc_resize (MonoProfiler *profiler, uintptr_t new_size)
1636 ENTER_LOG (&gc_resizes_ctr, logbuffer,
1637 EVENT_SIZE /* event */ +
1638 LEB128_SIZE /* new size */
1641 emit_event (logbuffer, TYPE_GC_RESIZE | TYPE_GC);
1642 emit_value (logbuffer, new_size);
1649 MonoMethod* methods [MAX_FRAMES];
1650 int32_t il_offsets [MAX_FRAMES];
1651 int32_t native_offsets [MAX_FRAMES];
1655 walk_stack (MonoMethod *method, int32_t native_offset, int32_t il_offset, mono_bool managed, void* data)
1657 FrameData *frame = (FrameData *)data;
1658 if (method && frame->count < log_config.num_frames) {
1659 frame->il_offsets [frame->count] = il_offset;
1660 frame->native_offsets [frame->count] = native_offset;
1661 frame->methods [frame->count++] = method;
1663 return frame->count == log_config.num_frames;
1667 * a note about stack walks: they can cause more profiler events to fire,
1668 * so we need to make sure they don't happen after we started emitting an
1669 * event, hence the collect_bt/emit_bt split.
1672 collect_bt (FrameData *data)
1675 mono_stack_walk_no_il (walk_stack, data);
1679 emit_bt (LogBuffer *logbuffer, FrameData *data)
1681 emit_value (logbuffer, data->count);
1684 emit_method (logbuffer, data->methods [--data->count]);
1688 gc_alloc (MonoProfiler *prof, MonoObject *obj)
1690 int do_bt = (!log_config.enter_leave && InterlockedRead (&log_profiler.runtime_inited) && log_config.num_frames) ? TYPE_ALLOC_BT : 0;
1692 uintptr_t len = mono_object_get_size (obj);
1693 /* account for object alignment in the heap */
1700 ENTER_LOG (&gc_allocs_ctr, logbuffer,
1701 EVENT_SIZE /* event */ +
1702 LEB128_SIZE /* klass */ +
1703 LEB128_SIZE /* obj */ +
1704 LEB128_SIZE /* size */ +
1706 LEB128_SIZE /* count */ +
1708 LEB128_SIZE /* method */
1713 emit_event (logbuffer, do_bt | TYPE_ALLOC);
1714 emit_ptr (logbuffer, mono_object_get_class (obj));
1715 emit_obj (logbuffer, obj);
1716 emit_value (logbuffer, len);
1719 emit_bt (logbuffer, &data);
1725 gc_moves (MonoProfiler *prof, MonoObject *const *objects, uint64_t num)
1727 ENTER_LOG (&gc_moves_ctr, logbuffer,
1728 EVENT_SIZE /* event */ +
1729 LEB128_SIZE /* num */ +
1731 LEB128_SIZE /* object */
1735 emit_event (logbuffer, TYPE_GC_MOVE | TYPE_GC);
1736 emit_value (logbuffer, num);
1738 for (int i = 0; i < num; ++i)
1739 emit_obj (logbuffer, objects [i]);
1745 gc_handle (MonoProfiler *prof, int op, MonoGCHandleType type, uint32_t handle, MonoObject *obj)
1747 int do_bt = !log_config.enter_leave && InterlockedRead (&log_profiler.runtime_inited) && log_config.num_frames;
1753 gint32 *ctr = op == MONO_PROFILER_GC_HANDLE_CREATED ? &gc_handle_creations_ctr : &gc_handle_deletions_ctr;
1755 ENTER_LOG (ctr, logbuffer,
1756 EVENT_SIZE /* event */ +
1757 LEB128_SIZE /* type */ +
1758 LEB128_SIZE /* handle */ +
1759 (op == MONO_PROFILER_GC_HANDLE_CREATED ? (
1760 LEB128_SIZE /* obj */
1763 LEB128_SIZE /* count */ +
1765 LEB128_SIZE /* method */
1770 if (op == MONO_PROFILER_GC_HANDLE_CREATED)
1771 emit_event (logbuffer, (do_bt ? TYPE_GC_HANDLE_CREATED_BT : TYPE_GC_HANDLE_CREATED) | TYPE_GC);
1772 else if (op == MONO_PROFILER_GC_HANDLE_DESTROYED)
1773 emit_event (logbuffer, (do_bt ? TYPE_GC_HANDLE_DESTROYED_BT : TYPE_GC_HANDLE_DESTROYED) | TYPE_GC);
1775 g_assert_not_reached ();
1777 emit_value (logbuffer, type);
1778 emit_value (logbuffer, handle);
1780 if (op == MONO_PROFILER_GC_HANDLE_CREATED)
1781 emit_obj (logbuffer, obj);
1784 emit_bt (logbuffer, &data);
1790 gc_handle_created (MonoProfiler *prof, uint32_t handle, MonoGCHandleType type, MonoObject *obj)
1792 gc_handle (prof, MONO_PROFILER_GC_HANDLE_CREATED, type, handle, obj);
1796 gc_handle_deleted (MonoProfiler *prof, uint32_t handle, MonoGCHandleType type)
1798 gc_handle (prof, MONO_PROFILER_GC_HANDLE_DESTROYED, type, handle, NULL);
1802 finalize_begin (MonoProfiler *prof)
1804 ENTER_LOG (&finalize_begins_ctr, buf,
1805 EVENT_SIZE /* event */
1808 emit_event (buf, TYPE_GC_FINALIZE_START | TYPE_GC);
1814 finalize_end (MonoProfiler *prof)
1816 trigger_on_demand_heapshot ();
1817 if (ENABLED (PROFLOG_FINALIZATION_EVENTS)) {
1818 ENTER_LOG (&finalize_ends_ctr, buf,
1819 EVENT_SIZE /* event */
1822 emit_event (buf, TYPE_GC_FINALIZE_END | TYPE_GC);
1829 finalize_object_begin (MonoProfiler *prof, MonoObject *obj)
1831 ENTER_LOG (&finalize_object_begins_ctr, buf,
1832 EVENT_SIZE /* event */ +
1833 LEB128_SIZE /* obj */
1836 emit_event (buf, TYPE_GC_FINALIZE_OBJECT_START | TYPE_GC);
1837 emit_obj (buf, obj);
1843 finalize_object_end (MonoProfiler *prof, MonoObject *obj)
1845 ENTER_LOG (&finalize_object_ends_ctr, buf,
1846 EVENT_SIZE /* event */ +
1847 LEB128_SIZE /* obj */
1850 emit_event (buf, TYPE_GC_FINALIZE_OBJECT_END | TYPE_GC);
1851 emit_obj (buf, obj);
1857 push_nesting (char *p, MonoClass *klass)
1862 nesting = mono_class_get_nesting_type (klass);
1864 p = push_nesting (p, nesting);
1868 name = mono_class_get_name (klass);
1869 nspace = mono_class_get_namespace (klass);
1872 p += strlen (nspace);
1882 type_name (MonoClass *klass)
1886 push_nesting (buf, klass);
1887 p = (char *) g_malloc (strlen (buf) + 1);
1893 image_loaded (MonoProfiler *prof, MonoImage *image)
1895 const char *name = mono_image_get_filename (image);
1896 int nlen = strlen (name) + 1;
1898 ENTER_LOG (&image_loads_ctr, logbuffer,
1899 EVENT_SIZE /* event */ +
1900 BYTE_SIZE /* type */ +
1901 LEB128_SIZE /* image */ +
1905 emit_event (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1906 emit_byte (logbuffer, TYPE_IMAGE);
1907 emit_ptr (logbuffer, image);
1908 memcpy (logbuffer->cursor, name, nlen);
1909 logbuffer->cursor += nlen;
1915 image_unloaded (MonoProfiler *prof, MonoImage *image)
1917 const char *name = mono_image_get_filename (image);
1918 int nlen = strlen (name) + 1;
1920 ENTER_LOG (&image_unloads_ctr, logbuffer,
1921 EVENT_SIZE /* event */ +
1922 BYTE_SIZE /* type */ +
1923 LEB128_SIZE /* image */ +
1927 emit_event (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
1928 emit_byte (logbuffer, TYPE_IMAGE);
1929 emit_ptr (logbuffer, image);
1930 memcpy (logbuffer->cursor, name, nlen);
1931 logbuffer->cursor += nlen;
1937 assembly_loaded (MonoProfiler *prof, MonoAssembly *assembly)
1939 char *name = mono_stringify_assembly_name (mono_assembly_get_name (assembly));
1940 int nlen = strlen (name) + 1;
1941 MonoImage *image = mono_assembly_get_image (assembly);
1943 ENTER_LOG (&assembly_loads_ctr, logbuffer,
1944 EVENT_SIZE /* event */ +
1945 BYTE_SIZE /* type */ +
1946 LEB128_SIZE /* assembly */ +
1947 LEB128_SIZE /* image */ +
1951 emit_event (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1952 emit_byte (logbuffer, TYPE_ASSEMBLY);
1953 emit_ptr (logbuffer, assembly);
1954 emit_ptr (logbuffer, image);
1955 memcpy (logbuffer->cursor, name, nlen);
1956 logbuffer->cursor += nlen;
1964 assembly_unloaded (MonoProfiler *prof, MonoAssembly *assembly)
1966 char *name = mono_stringify_assembly_name (mono_assembly_get_name (assembly));
1967 int nlen = strlen (name) + 1;
1968 MonoImage *image = mono_assembly_get_image (assembly);
1970 ENTER_LOG (&assembly_unloads_ctr, logbuffer,
1971 EVENT_SIZE /* event */ +
1972 BYTE_SIZE /* type */ +
1973 LEB128_SIZE /* assembly */ +
1974 LEB128_SIZE /* image */ +
1978 emit_event (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
1979 emit_byte (logbuffer, TYPE_ASSEMBLY);
1980 emit_ptr (logbuffer, assembly);
1981 emit_ptr (logbuffer, image);
1982 memcpy (logbuffer->cursor, name, nlen);
1983 logbuffer->cursor += nlen;
1991 class_loaded (MonoProfiler *prof, MonoClass *klass)
1995 if (InterlockedRead (&log_profiler.runtime_inited))
1996 name = mono_type_get_name (mono_class_get_type (klass));
1998 name = type_name (klass);
2000 int nlen = strlen (name) + 1;
2001 MonoImage *image = mono_class_get_image (klass);
2003 ENTER_LOG (&class_loads_ctr, logbuffer,
2004 EVENT_SIZE /* event */ +
2005 BYTE_SIZE /* type */ +
2006 LEB128_SIZE /* klass */ +
2007 LEB128_SIZE /* image */ +
2011 emit_event (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
2012 emit_byte (logbuffer, TYPE_CLASS);
2013 emit_ptr (logbuffer, klass);
2014 emit_ptr (logbuffer, image);
2015 memcpy (logbuffer->cursor, name, nlen);
2016 logbuffer->cursor += nlen;
2020 if (InterlockedRead (&log_profiler.runtime_inited))
2027 method_enter (MonoProfiler *prof, MonoMethod *method)
2029 if (get_thread ()->call_depth++ <= log_config.max_call_depth) {
2030 ENTER_LOG (&method_entries_ctr, logbuffer,
2031 EVENT_SIZE /* event */ +
2032 LEB128_SIZE /* method */
2035 emit_event (logbuffer, TYPE_ENTER | TYPE_METHOD);
2036 emit_method (logbuffer, method);
2043 method_leave (MonoProfiler *prof, MonoMethod *method)
2045 if (--get_thread ()->call_depth <= log_config.max_call_depth) {
2046 ENTER_LOG (&method_exits_ctr, logbuffer,
2047 EVENT_SIZE /* event */ +
2048 LEB128_SIZE /* method */
2051 emit_event (logbuffer, TYPE_LEAVE | TYPE_METHOD);
2052 emit_method (logbuffer, method);
2059 method_exc_leave (MonoProfiler *prof, MonoMethod *method, MonoObject *exc)
2061 if (--get_thread ()->call_depth <= log_config.max_call_depth) {
2062 ENTER_LOG (&method_exception_exits_ctr, logbuffer,
2063 EVENT_SIZE /* event */ +
2064 LEB128_SIZE /* method */
2067 emit_event (logbuffer, TYPE_EXC_LEAVE | TYPE_METHOD);
2068 emit_method (logbuffer, method);
2074 static MonoProfilerCallInstrumentationFlags
2075 method_filter (MonoProfiler *prof, MonoMethod *method)
2077 return MONO_PROFILER_CALL_INSTRUMENTATION_PROLOGUE | MONO_PROFILER_CALL_INSTRUMENTATION_EPILOGUE;
2081 method_jitted (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *ji)
2085 register_method_local (method, ji);
2091 code_buffer_new (MonoProfiler *prof, const mono_byte *buffer, uint64_t size, MonoProfilerCodeBufferType type, const void *data)
2096 if (type == MONO_PROFILER_CODE_BUFFER_SPECIFIC_TRAMPOLINE) {
2097 name = (const char *) data;
2098 nlen = strlen (name) + 1;
2104 ENTER_LOG (&code_buffers_ctr, logbuffer,
2105 EVENT_SIZE /* event */ +
2106 BYTE_SIZE /* type */ +
2107 LEB128_SIZE /* buffer */ +
2108 LEB128_SIZE /* size */ +
2114 emit_event (logbuffer, TYPE_JITHELPER | TYPE_RUNTIME);
2115 emit_byte (logbuffer, type);
2116 emit_ptr (logbuffer, buffer);
2117 emit_value (logbuffer, size);
2120 memcpy (logbuffer->cursor, name, nlen);
2121 logbuffer->cursor += nlen;
2128 throw_exc (MonoProfiler *prof, MonoObject *object)
2130 int do_bt = (!log_config.enter_leave && InterlockedRead (&log_profiler.runtime_inited) && log_config.num_frames) ? TYPE_THROW_BT : 0;
2136 ENTER_LOG (&exception_throws_ctr, logbuffer,
2137 EVENT_SIZE /* event */ +
2138 LEB128_SIZE /* object */ +
2140 LEB128_SIZE /* count */ +
2142 LEB128_SIZE /* method */
2147 emit_event (logbuffer, do_bt | TYPE_EXCEPTION);
2148 emit_obj (logbuffer, object);
2151 emit_bt (logbuffer, &data);
2157 clause_exc (MonoProfiler *prof, MonoMethod *method, uint32_t clause_num, MonoExceptionEnum clause_type, MonoObject *exc)
2159 ENTER_LOG (&exception_clauses_ctr, logbuffer,
2160 EVENT_SIZE /* event */ +
2161 BYTE_SIZE /* clause type */ +
2162 LEB128_SIZE /* clause num */ +
2163 LEB128_SIZE /* method */
2166 emit_event (logbuffer, TYPE_EXCEPTION | TYPE_CLAUSE);
2167 emit_byte (logbuffer, clause_type);
2168 emit_value (logbuffer, clause_num);
2169 emit_method (logbuffer, method);
2170 emit_obj (logbuffer, exc);
2176 monitor_event (MonoProfiler *profiler, MonoObject *object, MonoProfilerMonitorEvent ev)
2178 int do_bt = (!log_config.enter_leave && InterlockedRead (&log_profiler.runtime_inited) && log_config.num_frames) ? TYPE_MONITOR_BT : 0;
2184 ENTER_LOG (&monitor_events_ctr, logbuffer,
2185 EVENT_SIZE /* event */ +
2186 BYTE_SIZE /* ev */ +
2187 LEB128_SIZE /* object */ +
2189 LEB128_SIZE /* count */ +
2191 LEB128_SIZE /* method */
2196 emit_event (logbuffer, do_bt | TYPE_MONITOR);
2197 emit_byte (logbuffer, ev);
2198 emit_obj (logbuffer, object);
2201 emit_bt (logbuffer, &data);
2207 monitor_contention (MonoProfiler *prof, MonoObject *object)
2209 monitor_event (prof, object, MONO_PROFILER_MONITOR_CONTENTION);
2213 monitor_acquired (MonoProfiler *prof, MonoObject *object)
2215 monitor_event (prof, object, MONO_PROFILER_MONITOR_DONE);
2219 monitor_failed (MonoProfiler *prof, MonoObject *object)
2221 monitor_event (prof, object, MONO_PROFILER_MONITOR_FAIL);
2225 thread_start (MonoProfiler *prof, uintptr_t tid)
2227 ENTER_LOG (&thread_starts_ctr, logbuffer,
2228 EVENT_SIZE /* event */ +
2229 BYTE_SIZE /* type */ +
2230 LEB128_SIZE /* tid */
2233 emit_event (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
2234 emit_byte (logbuffer, TYPE_THREAD);
2235 emit_ptr (logbuffer, (void*) tid);
2241 thread_end (MonoProfiler *prof, uintptr_t tid)
2243 ENTER_LOG (&thread_ends_ctr, logbuffer,
2244 EVENT_SIZE /* event */ +
2245 BYTE_SIZE /* type */ +
2246 LEB128_SIZE /* tid */
2249 emit_event (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
2250 emit_byte (logbuffer, TYPE_THREAD);
2251 emit_ptr (logbuffer, (void*) tid);
2253 EXIT_LOG_EXPLICIT (NO_SEND);
2255 MonoProfilerThread *thread = get_thread ();
2257 thread->ended = TRUE;
2258 remove_thread (thread);
2260 PROF_TLS_SET (NULL);
2264 thread_name (MonoProfiler *prof, uintptr_t tid, const char *name)
2266 int len = strlen (name) + 1;
2268 ENTER_LOG (&thread_names_ctr, logbuffer,
2269 EVENT_SIZE /* event */ +
2270 BYTE_SIZE /* type */ +
2271 LEB128_SIZE /* tid */ +
2275 emit_event (logbuffer, TYPE_METADATA);
2276 emit_byte (logbuffer, TYPE_THREAD);
2277 emit_ptr (logbuffer, (void*)tid);
2278 memcpy (logbuffer->cursor, name, len);
2279 logbuffer->cursor += len;
2285 domain_loaded (MonoProfiler *prof, MonoDomain *domain)
2287 ENTER_LOG (&domain_loads_ctr, logbuffer,
2288 EVENT_SIZE /* event */ +
2289 BYTE_SIZE /* type */ +
2290 LEB128_SIZE /* domain id */
2293 emit_event (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
2294 emit_byte (logbuffer, TYPE_DOMAIN);
2295 emit_ptr (logbuffer, (void*)(uintptr_t) mono_domain_get_id (domain));
2301 domain_unloaded (MonoProfiler *prof, MonoDomain *domain)
2303 ENTER_LOG (&domain_unloads_ctr, logbuffer,
2304 EVENT_SIZE /* event */ +
2305 BYTE_SIZE /* type */ +
2306 LEB128_SIZE /* domain id */
2309 emit_event (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
2310 emit_byte (logbuffer, TYPE_DOMAIN);
2311 emit_ptr (logbuffer, (void*)(uintptr_t) mono_domain_get_id (domain));
2317 domain_name (MonoProfiler *prof, MonoDomain *domain, const char *name)
2319 int nlen = strlen (name) + 1;
2321 ENTER_LOG (&domain_names_ctr, logbuffer,
2322 EVENT_SIZE /* event */ +
2323 BYTE_SIZE /* type */ +
2324 LEB128_SIZE /* domain id */ +
2328 emit_event (logbuffer, TYPE_METADATA);
2329 emit_byte (logbuffer, TYPE_DOMAIN);
2330 emit_ptr (logbuffer, (void*)(uintptr_t) mono_domain_get_id (domain));
2331 memcpy (logbuffer->cursor, name, nlen);
2332 logbuffer->cursor += nlen;
2338 context_loaded (MonoProfiler *prof, MonoAppContext *context)
2340 ENTER_LOG (&context_loads_ctr, logbuffer,
2341 EVENT_SIZE /* event */ +
2342 BYTE_SIZE /* type */ +
2343 LEB128_SIZE /* context id */ +
2344 LEB128_SIZE /* domain id */
2347 emit_event (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
2348 emit_byte (logbuffer, TYPE_CONTEXT);
2349 emit_ptr (logbuffer, (void*)(uintptr_t) mono_context_get_id (context));
2350 emit_ptr (logbuffer, (void*)(uintptr_t) mono_context_get_domain_id (context));
2356 context_unloaded (MonoProfiler *prof, MonoAppContext *context)
2358 ENTER_LOG (&context_unloads_ctr, logbuffer,
2359 EVENT_SIZE /* event */ +
2360 BYTE_SIZE /* type */ +
2361 LEB128_SIZE /* context id */ +
2362 LEB128_SIZE /* domain id */
2365 emit_event (logbuffer, TYPE_END_UNLOAD | TYPE_METADATA);
2366 emit_byte (logbuffer, TYPE_CONTEXT);
2367 emit_ptr (logbuffer, (void*)(uintptr_t) mono_context_get_id (context));
2368 emit_ptr (logbuffer, (void*)(uintptr_t) mono_context_get_domain_id (context));
2381 MonoLockFreeQueueNode node;
2386 AsyncFrameInfo frames [MONO_ZERO_LEN_ARRAY];
2390 async_walk_stack (MonoMethod *method, MonoDomain *domain, void *base_address, int offset, void *data)
2392 SampleHit *sample = (SampleHit *) data;
2394 if (sample->count < log_config.num_frames) {
2395 int i = sample->count;
2397 sample->frames [i].method = method;
2398 sample->frames [i].domain = domain;
2399 sample->frames [i].base_address = base_address;
2400 sample->frames [i].offset = offset;
2405 return sample->count == log_config.num_frames;
2408 #define SAMPLE_SLOT_SIZE(FRAMES) (sizeof (SampleHit) + sizeof (AsyncFrameInfo) * (FRAMES - MONO_ZERO_LEN_ARRAY))
2409 #define SAMPLE_BLOCK_SIZE (mono_pagesize ())
2412 enqueue_sample_hit (gpointer p)
2414 SampleHit *sample = p;
2416 mono_lock_free_queue_node_unpoison (&sample->node);
2417 mono_lock_free_queue_enqueue (&log_profiler.dumper_queue, &sample->node);
2418 mono_os_sem_post (&log_profiler.dumper_queue_sem);
2422 mono_sample_hit (MonoProfiler *profiler, const mono_byte *ip, const void *context)
2425 * Please note: We rely on the runtime loading the profiler with
2426 * MONO_DL_EAGER (RTLD_NOW) so that references to runtime functions within
2427 * this function (and its siblings) are resolved when the profiler is
2428 * loaded. Otherwise, we would potentially invoke the dynamic linker when
2429 * invoking runtime functions, which is not async-signal-safe.
2432 if (InterlockedRead (&log_profiler.in_shutdown))
2435 SampleHit *sample = (SampleHit *) mono_lock_free_queue_dequeue (&profiler->sample_reuse_queue);
2439 * If we're out of reusable sample events and we're not allowed to
2440 * allocate more, we have no choice but to drop the event.
2442 if (InterlockedRead (&sample_allocations_ctr) >= log_config.max_allocated_sample_hits)
2445 sample = mono_lock_free_alloc (&profiler->sample_allocator);
2446 mono_lock_free_queue_node_init (&sample->node, TRUE);
2448 InterlockedIncrement (&sample_allocations_ctr);
2452 mono_stack_walk_async_safe (&async_walk_stack, (void *) context, sample);
2454 sample->time = current_time ();
2455 sample->tid = thread_id ();
2458 mono_thread_hazardous_try_free (sample, enqueue_sample_hit);
2461 static uintptr_t *code_pages = 0;
2462 static int num_code_pages = 0;
2463 static int size_code_pages = 0;
2464 #define CPAGE_SHIFT (9)
2465 #define CPAGE_SIZE (1 << CPAGE_SHIFT)
2466 #define CPAGE_MASK (~(CPAGE_SIZE - 1))
2467 #define CPAGE_ADDR(p) ((p) & CPAGE_MASK)
2470 add_code_page (uintptr_t *hash, uintptr_t hsize, uintptr_t page)
2473 uintptr_t start_pos;
2474 start_pos = (page >> CPAGE_SHIFT) % hsize;
2477 if (hash [i] && CPAGE_ADDR (hash [i]) == CPAGE_ADDR (page)) {
2479 } else if (!hash [i]) {
2486 } while (i != start_pos);
2487 g_assert_not_reached ();
2492 add_code_pointer (uintptr_t ip)
2495 if (num_code_pages * 2 >= size_code_pages) {
2497 uintptr_t old_size = size_code_pages;
2498 size_code_pages *= 2;
2499 if (size_code_pages == 0)
2500 size_code_pages = 16;
2501 n = (uintptr_t *) g_calloc (sizeof (uintptr_t) * size_code_pages, 1);
2502 for (i = 0; i < old_size; ++i) {
2504 add_code_page (n, size_code_pages, code_pages [i]);
2507 g_free (code_pages);
2510 num_code_pages += add_code_page (code_pages, size_code_pages, ip & CPAGE_MASK);
2513 /* ELF code crashes on some systems. */
2514 //#if defined(HAVE_DL_ITERATE_PHDR) && defined(ELFMAG0)
2517 dump_ubin (const char *filename, uintptr_t load_addr, uint64_t offset, uintptr_t size)
2519 int len = strlen (filename) + 1;
2521 ENTER_LOG (&sample_ubins_ctr, logbuffer,
2522 EVENT_SIZE /* event */ +
2523 LEB128_SIZE /* load address */ +
2524 LEB128_SIZE /* offset */ +
2525 LEB128_SIZE /* size */ +
2526 nlen /* file name */
2529 emit_event (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_UBIN);
2530 emit_ptr (logbuffer, load_addr);
2531 emit_uvalue (logbuffer, offset);
2532 emit_uvalue (logbuffer, size);
2533 memcpy (logbuffer->cursor, filename, len);
2534 logbuffer->cursor += len;
2541 dump_usym (const char *name, uintptr_t value, uintptr_t size)
2543 int len = strlen (name) + 1;
2545 ENTER_LOG (&sample_usyms_ctr, logbuffer,
2546 EVENT_SIZE /* event */ +
2547 LEB128_SIZE /* value */ +
2548 LEB128_SIZE /* size */ +
2552 emit_event (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_USYM);
2553 emit_ptr (logbuffer, (void*)value);
2554 emit_value (logbuffer, size);
2555 memcpy (logbuffer->cursor, name, len);
2556 logbuffer->cursor += len;
2561 /* ELF code crashes on some systems. */
2562 //#if defined(ELFMAG0)
2565 #if SIZEOF_VOID_P == 4
2566 #define ELF_WSIZE 32
2568 #define ELF_WSIZE 64
2571 #define ElfW(type) _ElfW (Elf, ELF_WSIZE, type)
2572 #define _ElfW(e,w,t) _ElfW_1 (e, w, _##t)
2573 #define _ElfW_1(e,w,t) e##w##t
2577 dump_elf_symbols (ElfW(Sym) *symbols, int num_symbols, const char *strtab, void *load_addr)
2580 for (i = 0; i < num_symbols; ++i) {
2582 sym = strtab + symbols [i].st_name;
2583 if (!symbols [i].st_name || !symbols [i].st_size || (symbols [i].st_info & 0xf) != STT_FUNC)
2585 dump_usym (sym, (uintptr_t)load_addr + symbols [i].st_value, symbols [i].st_size);
2590 read_elf_symbols (MonoProfiler *prof, const char *filename, void *load_addr)
2597 ElfW(Shdr) *sheader;
2598 ElfW(Shdr) *shstrtabh;
2599 ElfW(Shdr) *symtabh = NULL;
2600 ElfW(Shdr) *strtabh = NULL;
2601 ElfW(Sym) *symbols = NULL;
2605 fd = open (filename, O_RDONLY);
2608 if (fstat (fd, &statb) != 0) {
2612 file_size = statb.st_size;
2613 data = mmap (NULL, file_size, PROT_READ, MAP_PRIVATE, fd, 0);
2615 if (data == MAP_FAILED)
2618 if (header->e_ident [EI_MAG0] != ELFMAG0 ||
2619 header->e_ident [EI_MAG1] != ELFMAG1 ||
2620 header->e_ident [EI_MAG2] != ELFMAG2 ||
2621 header->e_ident [EI_MAG3] != ELFMAG3 ) {
2622 munmap (data, file_size);
2625 sheader = (void*)((char*)data + header->e_shoff);
2626 shstrtabh = (void*)((char*)sheader + (header->e_shentsize * header->e_shstrndx));
2627 strtab = (const char*)data + shstrtabh->sh_offset;
2628 for (i = 0; i < header->e_shnum; ++i) {
2629 if (sheader->sh_type == SHT_SYMTAB) {
2631 strtabh = (void*)((char*)data + header->e_shoff + sheader->sh_link * header->e_shentsize);
2634 sheader = (void*)((char*)sheader + header->e_shentsize);
2636 if (!symtabh || !strtabh) {
2637 munmap (data, file_size);
2640 strtab = (const char*)data + strtabh->sh_offset;
2641 num_symbols = symtabh->sh_size / symtabh->sh_entsize;
2642 symbols = (void*)((char*)data + symtabh->sh_offset);
2643 dump_elf_symbols (symbols, num_symbols, strtab, load_addr);
2644 munmap (data, file_size);
2649 /* ELF code crashes on some systems. */
2650 //#if defined(HAVE_DL_ITERATE_PHDR) && defined(ELFMAG0)
2653 elf_dl_callback (struct dl_phdr_info *info, size_t size, void *data)
2656 const char *filename;
2658 char *a = (void*)info->dlpi_addr;
2660 ElfW(Dyn) *dyn = NULL;
2661 ElfW(Sym) *symtab = NULL;
2662 ElfW(Word) *hash_table = NULL;
2663 ElfW(Ehdr) *header = NULL;
2664 const char* strtab = NULL;
2665 for (obj = log_profiler.binary_objects; obj; obj = obj->next) {
2669 filename = info->dlpi_name;
2672 if (!info->dlpi_addr && !filename [0]) {
2673 int l = readlink ("/proc/self/exe", buf, sizeof (buf) - 1);
2679 obj = g_calloc (sizeof (BinaryObject), 1);
2680 obj->addr = (void*)info->dlpi_addr;
2681 obj->name = pstrdup (filename);
2682 obj->next = log_profiler.binary_objects;
2683 log_profiler.binary_objects = obj;
2685 for (i = 0; i < info->dlpi_phnum; ++i) {
2686 if (info->dlpi_phdr[i].p_type == PT_LOAD && !header) {
2687 header = (ElfW(Ehdr)*)(info->dlpi_addr + info->dlpi_phdr[i].p_vaddr);
2688 if (header->e_ident [EI_MAG0] != ELFMAG0 ||
2689 header->e_ident [EI_MAG1] != ELFMAG1 ||
2690 header->e_ident [EI_MAG2] != ELFMAG2 ||
2691 header->e_ident [EI_MAG3] != ELFMAG3 ) {
2694 dump_ubin (filename, info->dlpi_addr + info->dlpi_phdr[i].p_vaddr, info->dlpi_phdr[i].p_offset, info->dlpi_phdr[i].p_memsz);
2695 } else if (info->dlpi_phdr[i].p_type == PT_DYNAMIC) {
2696 dyn = (ElfW(Dyn) *)(info->dlpi_addr + info->dlpi_phdr[i].p_vaddr);
2699 if (read_elf_symbols (filename, (void*)info->dlpi_addr))
2701 if (!info->dlpi_name || !info->dlpi_name[0])
2705 for (i = 0; dyn [i].d_tag != DT_NULL; ++i) {
2706 if (dyn [i].d_tag == DT_SYMTAB) {
2707 symtab = (ElfW(Sym) *)(a + dyn [i].d_un.d_ptr);
2708 } else if (dyn [i].d_tag == DT_HASH) {
2709 hash_table = (ElfW(Word) *)(a + dyn [i].d_un.d_ptr);
2710 } else if (dyn [i].d_tag == DT_STRTAB) {
2711 strtab = (const char*)(a + dyn [i].d_un.d_ptr);
2716 num_sym = hash_table [1];
2717 dump_elf_symbols (symtab, num_sym, strtab, (void*)info->dlpi_addr);
2722 load_binaries (void)
2724 dl_iterate_phdr (elf_dl_callback, NULL);
2729 load_binaries (void)
2736 symbol_for (uintptr_t code)
2739 void *ip = (void*)code;
2741 if (dladdr (ip, &di)) {
2743 return di.dli_sname;
2746 names = backtrace_symbols (&ip, 1);
2748 const char* p = names [0];
2759 dump_unmanaged_coderefs (void)
2762 const char* last_symbol;
2763 uintptr_t addr, page_end;
2765 if (load_binaries ())
2767 for (i = 0; i < size_code_pages; ++i) {
2769 if (!code_pages [i] || code_pages [i] & 1)
2772 addr = CPAGE_ADDR (code_pages [i]);
2773 page_end = addr + CPAGE_SIZE;
2774 code_pages [i] |= 1;
2775 /* we dump the symbols for the whole page */
2776 for (; addr < page_end; addr += 16) {
2777 sym = symbol_for (addr);
2778 if (sym && sym == last_symbol)
2783 dump_usym (sym, addr, 0); /* let's not guess the size */
2789 counters_add_agent (MonoCounter *counter)
2791 if (InterlockedRead (&log_profiler.in_shutdown))
2794 MonoCounterAgent *agent, *item;
2796 mono_os_mutex_lock (&log_profiler.counters_mutex);
2798 for (agent = log_profiler.counters; agent; agent = agent->next) {
2799 if (agent->counter == counter) {
2800 agent->value_size = 0;
2802 g_free (agent->value);
2803 agent->value = NULL;
2809 agent = (MonoCounterAgent *) g_malloc (sizeof (MonoCounterAgent));
2810 agent->counter = counter;
2811 agent->value = NULL;
2812 agent->value_size = 0;
2813 agent->index = log_profiler.counters_index++;
2814 agent->emitted = FALSE;
2817 if (!log_profiler.counters) {
2818 log_profiler.counters = agent;
2820 item = log_profiler.counters;
2827 mono_os_mutex_unlock (&log_profiler.counters_mutex);
2831 counters_init_foreach_callback (MonoCounter *counter, gpointer data)
2833 counters_add_agent (counter);
2838 counters_init (void)
2840 mono_os_mutex_init (&log_profiler.counters_mutex);
2842 log_profiler.counters_index = 1;
2844 mono_counters_on_register (&counters_add_agent);
2845 mono_counters_foreach (counters_init_foreach_callback, NULL);
2849 counters_emit (void)
2851 MonoCounterAgent *agent;
2854 EVENT_SIZE /* event */ +
2855 LEB128_SIZE /* len */
2858 mono_os_mutex_lock (&log_profiler.counters_mutex);
2860 for (agent = log_profiler.counters; agent; agent = agent->next) {
2865 LEB128_SIZE /* section */ +
2866 strlen (mono_counter_get_name (agent->counter)) + 1 /* name */ +
2867 BYTE_SIZE /* type */ +
2868 BYTE_SIZE /* unit */ +
2869 BYTE_SIZE /* variance */ +
2870 LEB128_SIZE /* index */
2879 ENTER_LOG (&counter_descriptors_ctr, logbuffer, size);
2881 emit_event (logbuffer, TYPE_SAMPLE_COUNTERS_DESC | TYPE_SAMPLE);
2882 emit_value (logbuffer, len);
2884 for (agent = log_profiler.counters; agent; agent = agent->next) {
2890 name = mono_counter_get_name (agent->counter);
2891 emit_value (logbuffer, mono_counter_get_section (agent->counter));
2892 emit_string (logbuffer, name, strlen (name) + 1);
2893 emit_byte (logbuffer, mono_counter_get_type (agent->counter));
2894 emit_byte (logbuffer, mono_counter_get_unit (agent->counter));
2895 emit_byte (logbuffer, mono_counter_get_variance (agent->counter));
2896 emit_value (logbuffer, agent->index);
2898 agent->emitted = TRUE;
2904 mono_os_mutex_unlock (&log_profiler.counters_mutex);
2908 counters_sample (uint64_t timestamp)
2910 MonoCounterAgent *agent;
2911 MonoCounter *counter;
2920 buffer = g_calloc (1, buffer_size);
2922 mono_os_mutex_lock (&log_profiler.counters_mutex);
2925 EVENT_SIZE /* event */
2928 for (agent = log_profiler.counters; agent; agent = agent->next) {
2930 LEB128_SIZE /* index */ +
2931 BYTE_SIZE /* type */ +
2932 mono_counter_get_size (agent->counter) /* value */
2937 LEB128_SIZE /* stop marker */
2940 ENTER_LOG (&counter_samples_ctr, logbuffer, size);
2942 emit_event_time (logbuffer, TYPE_SAMPLE_COUNTERS | TYPE_SAMPLE, timestamp);
2944 for (agent = log_profiler.counters; agent; agent = agent->next) {
2947 counter = agent->counter;
2949 size = mono_counter_get_size (counter);
2951 if (size > buffer_size) {
2953 buffer = g_realloc (buffer, buffer_size);
2956 memset (buffer, 0, buffer_size);
2958 g_assert (mono_counters_sample (counter, buffer, size));
2960 type = mono_counter_get_type (counter);
2962 if (!agent->value) {
2963 agent->value = g_calloc (1, size);
2964 agent->value_size = size;
2966 if (type == MONO_COUNTER_STRING) {
2967 if (strcmp (agent->value, buffer) == 0)
2970 if (agent->value_size == size && memcmp (agent->value, buffer, size) == 0)
2975 emit_uvalue (logbuffer, agent->index);
2976 emit_byte (logbuffer, type);
2978 case MONO_COUNTER_INT:
2979 #if SIZEOF_VOID_P == 4
2980 case MONO_COUNTER_WORD:
2982 emit_svalue (logbuffer, *(int*)buffer - *(int*)agent->value);
2984 case MONO_COUNTER_UINT:
2985 emit_uvalue (logbuffer, *(guint*)buffer - *(guint*)agent->value);
2987 case MONO_COUNTER_TIME_INTERVAL:
2988 case MONO_COUNTER_LONG:
2989 #if SIZEOF_VOID_P == 8
2990 case MONO_COUNTER_WORD:
2992 emit_svalue (logbuffer, *(gint64*)buffer - *(gint64*)agent->value);
2994 case MONO_COUNTER_ULONG:
2995 emit_uvalue (logbuffer, *(guint64*)buffer - *(guint64*)agent->value);
2997 case MONO_COUNTER_DOUBLE:
2998 emit_double (logbuffer, *(double*)buffer);
3000 case MONO_COUNTER_STRING:
3002 emit_byte (logbuffer, 0);
3004 emit_byte (logbuffer, 1);
3005 emit_string (logbuffer, (char*)buffer, size);
3009 g_assert_not_reached ();
3012 if (type == MONO_COUNTER_STRING && size > agent->value_size) {
3013 agent->value = g_realloc (agent->value, size);
3014 agent->value_size = size;
3018 memcpy (agent->value, buffer, size);
3022 emit_value (logbuffer, 0);
3026 mono_os_mutex_unlock (&log_profiler.counters_mutex);
3030 perfcounters_emit (void)
3032 PerfCounterAgent *pcagent;
3035 EVENT_SIZE /* event */ +
3036 LEB128_SIZE /* len */
3039 for (pcagent = log_profiler.perfcounters; pcagent; pcagent = pcagent->next) {
3040 if (pcagent->emitted)
3044 LEB128_SIZE /* section */ +
3045 strlen (pcagent->category_name) + 1 /* category name */ +
3046 strlen (pcagent->name) + 1 /* name */ +
3047 BYTE_SIZE /* type */ +
3048 BYTE_SIZE /* unit */ +
3049 BYTE_SIZE /* variance */ +
3050 LEB128_SIZE /* index */
3059 ENTER_LOG (&perfcounter_descriptors_ctr, logbuffer, size);
3061 emit_event (logbuffer, TYPE_SAMPLE_COUNTERS_DESC | TYPE_SAMPLE);
3062 emit_value (logbuffer, len);
3064 for (pcagent = log_profiler.perfcounters; pcagent; pcagent = pcagent->next) {
3065 if (pcagent->emitted)
3068 emit_value (logbuffer, MONO_COUNTER_PERFCOUNTERS);
3069 emit_string (logbuffer, pcagent->category_name, strlen (pcagent->category_name) + 1);
3070 emit_string (logbuffer, pcagent->name, strlen (pcagent->name) + 1);
3071 emit_byte (logbuffer, MONO_COUNTER_LONG);
3072 emit_byte (logbuffer, MONO_COUNTER_RAW);
3073 emit_byte (logbuffer, MONO_COUNTER_VARIABLE);
3074 emit_value (logbuffer, pcagent->index);
3076 pcagent->emitted = TRUE;
3083 perfcounters_foreach (char *category_name, char *name, unsigned char type, gint64 value, gpointer user_data)
3085 PerfCounterAgent *pcagent;
3087 for (pcagent = log_profiler.perfcounters; pcagent; pcagent = pcagent->next) {
3088 if (strcmp (pcagent->category_name, category_name) != 0 || strcmp (pcagent->name, name) != 0)
3090 if (pcagent->value == value)
3093 pcagent->value = value;
3094 pcagent->updated = TRUE;
3095 pcagent->deleted = FALSE;
3099 pcagent = g_new0 (PerfCounterAgent, 1);
3100 pcagent->next = log_profiler.perfcounters;
3101 pcagent->index = log_profiler.counters_index++;
3102 pcagent->category_name = g_strdup (category_name);
3103 pcagent->name = g_strdup (name);
3104 pcagent->value = value;
3105 pcagent->emitted = FALSE;
3106 pcagent->updated = TRUE;
3107 pcagent->deleted = FALSE;
3109 log_profiler.perfcounters = pcagent;
3115 perfcounters_sample (uint64_t timestamp)
3117 PerfCounterAgent *pcagent;
3121 mono_os_mutex_lock (&log_profiler.counters_mutex);
3123 /* mark all perfcounters as deleted, foreach will unmark them as necessary */
3124 for (pcagent = log_profiler.perfcounters; pcagent; pcagent = pcagent->next)
3125 pcagent->deleted = TRUE;
3127 mono_perfcounter_foreach (perfcounters_foreach, NULL);
3129 perfcounters_emit ();
3132 EVENT_SIZE /* event */
3135 for (pcagent = log_profiler.perfcounters; pcagent; pcagent = pcagent->next) {
3136 if (pcagent->deleted || !pcagent->updated)
3140 LEB128_SIZE /* index */ +
3141 BYTE_SIZE /* type */ +
3142 LEB128_SIZE /* value */
3152 LEB128_SIZE /* stop marker */
3155 ENTER_LOG (&perfcounter_samples_ctr, logbuffer, size);
3157 emit_event_time (logbuffer, TYPE_SAMPLE_COUNTERS | TYPE_SAMPLE, timestamp);
3159 for (pcagent = log_profiler.perfcounters; pcagent; pcagent = pcagent->next) {
3160 if (pcagent->deleted || !pcagent->updated)
3162 emit_uvalue (logbuffer, pcagent->index);
3163 emit_byte (logbuffer, MONO_COUNTER_LONG);
3164 emit_svalue (logbuffer, pcagent->value);
3166 pcagent->updated = FALSE;
3169 emit_value (logbuffer, 0);
3174 mono_os_mutex_unlock (&log_profiler.counters_mutex);
3178 counters_and_perfcounters_sample (void)
3180 uint64_t now = current_time ();
3182 counters_sample (now);
3183 perfcounters_sample (now);
3187 MonoLockFreeQueueNode node;
3200 free_coverage_entry (gpointer data, gpointer userdata)
3202 CoverageEntry *entry = (CoverageEntry *)data;
3203 g_free (entry->filename);
3208 obtain_coverage_for_method (MonoProfiler *prof, const MonoProfilerCoverageData *entry)
3210 int offset = entry->il_offset - log_profiler.coverage_previous_offset;
3211 CoverageEntry *e = g_new (CoverageEntry, 1);
3213 log_profiler.coverage_previous_offset = entry->il_offset;
3216 e->counter = entry->counter;
3217 e->filename = g_strdup(entry->file_name ? entry->file_name : "");
3218 e->line = entry->line;
3219 e->column = entry->column;
3221 g_ptr_array_add (log_profiler.coverage_data, e);
3225 parse_generic_type_names(char *name)
3227 char *new_name, *ret;
3228 int within_generic_declaration = 0, generic_members = 1;
3230 if (name == NULL || *name == '\0')
3231 return g_strdup ("");
3233 if (!(ret = new_name = (char *) g_calloc (strlen (name) * 4 + 1, sizeof (char))))
3239 within_generic_declaration = 1;
3243 within_generic_declaration = 0;
3245 if (*(name - 1) != '<') {
3247 *new_name++ = '0' + generic_members;
3249 memcpy (new_name, "<>", 8);
3253 generic_members = 0;
3261 if (!within_generic_declaration)
3262 *new_name++ = *name;
3272 build_method_buffer (gpointer key, gpointer value, gpointer userdata)
3274 MonoMethod *method = (MonoMethod *)value;
3278 const char *image_name, *method_name, *sig, *first_filename;
3281 log_profiler.coverage_previous_offset = 0;
3282 log_profiler.coverage_data = g_ptr_array_new ();
3284 mono_profiler_get_coverage_data (log_profiler.handle, method, obtain_coverage_for_method);
3286 klass = mono_method_get_class (method);
3287 image = mono_class_get_image (klass);
3288 image_name = mono_image_get_name (image);
3290 sig = mono_signature_get_desc (mono_method_signature (method), TRUE);
3291 class_name = parse_generic_type_names (mono_type_get_name (mono_class_get_type (klass)));
3292 method_name = mono_method_get_name (method);
3294 if (log_profiler.coverage_data->len != 0) {
3295 CoverageEntry *entry = (CoverageEntry *)log_profiler.coverage_data->pdata[0];
3296 first_filename = entry->filename ? entry->filename : "";
3298 first_filename = "";
3300 image_name = image_name ? image_name : "";
3301 sig = sig ? sig : "";
3302 method_name = method_name ? method_name : "";
3304 ENTER_LOG (&coverage_methods_ctr, logbuffer,
3305 EVENT_SIZE /* event */ +
3306 strlen (image_name) + 1 /* image name */ +
3307 strlen (class_name) + 1 /* class name */ +
3308 strlen (method_name) + 1 /* method name */ +
3309 strlen (sig) + 1 /* signature */ +
3310 strlen (first_filename) + 1 /* first file name */ +
3311 LEB128_SIZE /* token */ +
3312 LEB128_SIZE /* method id */ +
3313 LEB128_SIZE /* entries */
3316 emit_event (logbuffer, TYPE_COVERAGE_METHOD | TYPE_COVERAGE);
3317 emit_string (logbuffer, image_name, strlen (image_name) + 1);
3318 emit_string (logbuffer, class_name, strlen (class_name) + 1);
3319 emit_string (logbuffer, method_name, strlen (method_name) + 1);
3320 emit_string (logbuffer, sig, strlen (sig) + 1);
3321 emit_string (logbuffer, first_filename, strlen (first_filename) + 1);
3323 emit_uvalue (logbuffer, mono_method_get_token (method));
3324 emit_uvalue (logbuffer, log_profiler.coverage_method_id);
3325 emit_value (logbuffer, log_profiler.coverage_data->len);
3329 for (i = 0; i < log_profiler.coverage_data->len; i++) {
3330 CoverageEntry *entry = (CoverageEntry *)log_profiler.coverage_data->pdata[i];
3332 ENTER_LOG (&coverage_statements_ctr, logbuffer,
3333 EVENT_SIZE /* event */ +
3334 LEB128_SIZE /* method id */ +
3335 LEB128_SIZE /* offset */ +
3336 LEB128_SIZE /* counter */ +
3337 LEB128_SIZE /* line */ +
3338 LEB128_SIZE /* column */
3341 emit_event (logbuffer, TYPE_COVERAGE_STATEMENT | TYPE_COVERAGE);
3342 emit_uvalue (logbuffer, log_profiler.coverage_method_id);
3343 emit_uvalue (logbuffer, entry->offset);
3344 emit_uvalue (logbuffer, entry->counter);
3345 emit_uvalue (logbuffer, entry->line);
3346 emit_uvalue (logbuffer, entry->column);
3351 log_profiler.coverage_method_id++;
3353 g_free (class_name);
3355 g_ptr_array_foreach (log_profiler.coverage_data, free_coverage_entry, NULL);
3356 g_ptr_array_free (log_profiler.coverage_data, TRUE);
3359 /* This empties the queue */
3361 count_queue (MonoLockFreeQueue *queue)
3363 MonoLockFreeQueueNode *node;
3366 while ((node = mono_lock_free_queue_dequeue (queue))) {
3368 mono_thread_hazardous_try_free (node, g_free);
3375 build_class_buffer (gpointer key, gpointer value, gpointer userdata)
3377 MonoClass *klass = (MonoClass *)key;
3378 MonoLockFreeQueue *class_methods = (MonoLockFreeQueue *)value;
3381 const char *assembly_name;
3382 int number_of_methods, partially_covered;
3383 guint fully_covered;
3385 image = mono_class_get_image (klass);
3386 assembly_name = mono_image_get_name (image);
3387 class_name = mono_type_get_name (mono_class_get_type (klass));
3389 assembly_name = assembly_name ? assembly_name : "";
3390 number_of_methods = mono_class_num_methods (klass);
3391 fully_covered = count_queue (class_methods);
3392 /* We don't handle partial covered yet */
3393 partially_covered = 0;
3395 ENTER_LOG (&coverage_classes_ctr, logbuffer,
3396 EVENT_SIZE /* event */ +
3397 strlen (assembly_name) + 1 /* assembly name */ +
3398 strlen (class_name) + 1 /* class name */ +
3399 LEB128_SIZE /* no. methods */ +
3400 LEB128_SIZE /* fully covered */ +
3401 LEB128_SIZE /* partially covered */
3404 emit_event (logbuffer, TYPE_COVERAGE_CLASS | TYPE_COVERAGE);
3405 emit_string (logbuffer, assembly_name, strlen (assembly_name) + 1);
3406 emit_string (logbuffer, class_name, strlen (class_name) + 1);
3407 emit_uvalue (logbuffer, number_of_methods);
3408 emit_uvalue (logbuffer, fully_covered);
3409 emit_uvalue (logbuffer, partially_covered);
3413 g_free (class_name);
3417 get_coverage_for_image (MonoImage *image, int *number_of_methods, guint *fully_covered, int *partially_covered)
3419 MonoLockFreeQueue *image_methods = (MonoLockFreeQueue *)mono_conc_hashtable_lookup (log_profiler.coverage_image_to_methods, image);
3421 *number_of_methods = mono_image_get_table_rows (image, MONO_TABLE_METHOD);
3423 *fully_covered = count_queue (image_methods);
3427 // FIXME: We don't handle partially covered yet.
3428 *partially_covered = 0;
3432 build_assembly_buffer (gpointer key, gpointer value, gpointer userdata)
3434 MonoAssembly *assembly = (MonoAssembly *)value;
3435 MonoImage *image = mono_assembly_get_image (assembly);
3436 const char *name, *guid, *filename;
3437 int number_of_methods = 0, partially_covered = 0;
3438 guint fully_covered = 0;
3440 name = mono_image_get_name (image);
3441 guid = mono_image_get_guid (image);
3442 filename = mono_image_get_filename (image);
3444 name = name ? name : "";
3445 guid = guid ? guid : "";
3446 filename = filename ? filename : "";
3448 get_coverage_for_image (image, &number_of_methods, &fully_covered, &partially_covered);
3450 ENTER_LOG (&coverage_assemblies_ctr, logbuffer,
3451 EVENT_SIZE /* event */ +
3452 strlen (name) + 1 /* name */ +
3453 strlen (guid) + 1 /* guid */ +
3454 strlen (filename) + 1 /* file name */ +
3455 LEB128_SIZE /* no. methods */ +
3456 LEB128_SIZE /* fully covered */ +
3457 LEB128_SIZE /* partially covered */
3460 emit_event (logbuffer, TYPE_COVERAGE_ASSEMBLY | TYPE_COVERAGE);
3461 emit_string (logbuffer, name, strlen (name) + 1);
3462 emit_string (logbuffer, guid, strlen (guid) + 1);
3463 emit_string (logbuffer, filename, strlen (filename) + 1);
3464 emit_uvalue (logbuffer, number_of_methods);
3465 emit_uvalue (logbuffer, fully_covered);
3466 emit_uvalue (logbuffer, partially_covered);
3472 dump_coverage (void)
3474 mono_os_mutex_lock (&log_profiler.coverage_mutex);
3475 mono_conc_hashtable_foreach (log_profiler.coverage_assemblies, build_assembly_buffer, NULL);
3476 mono_conc_hashtable_foreach (log_profiler.coverage_classes, build_class_buffer, NULL);
3477 mono_conc_hashtable_foreach (log_profiler.coverage_methods, build_method_buffer, NULL);
3478 mono_os_mutex_unlock (&log_profiler.coverage_mutex);
3481 static MonoLockFreeQueueNode *
3482 create_method_node (MonoMethod *method)
3484 MethodNode *node = (MethodNode *) g_malloc (sizeof (MethodNode));
3485 mono_lock_free_queue_node_init ((MonoLockFreeQueueNode *) node, FALSE);
3486 node->method = method;
3488 return (MonoLockFreeQueueNode *) node;
3492 coverage_filter (MonoProfiler *prof, MonoMethod *method)
3497 MonoAssembly *assembly;
3498 MonoMethodHeader *header;
3499 guint32 iflags, flags, code_size;
3500 char *fqn, *classname;
3501 gboolean has_positive, found;
3502 MonoLockFreeQueue *image_methods, *class_methods;
3503 MonoLockFreeQueueNode *node;
3505 flags = mono_method_get_flags (method, &iflags);
3506 if ((iflags & 0x1000 /*METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL*/) ||
3507 (flags & 0x2000 /*METHOD_ATTRIBUTE_PINVOKE_IMPL*/))
3510 // Don't need to do anything else if we're already tracking this method
3511 if (mono_conc_hashtable_lookup (log_profiler.coverage_methods, method))
3514 klass = mono_method_get_class (method);
3515 image = mono_class_get_image (klass);
3517 // Don't handle coverage for the core assemblies
3518 if (mono_conc_hashtable_lookup (log_profiler.coverage_suppressed_assemblies, (gpointer) mono_image_get_name (image)) != NULL)
3521 if (prof->coverage_filters) {
3522 /* Check already filtered classes first */
3523 if (mono_conc_hashtable_lookup (log_profiler.coverage_filtered_classes, klass))
3526 classname = mono_type_get_name (mono_class_get_type (klass));
3528 fqn = g_strdup_printf ("[%s]%s", mono_image_get_name (image), classname);
3530 // Check positive filters first
3531 has_positive = FALSE;
3533 for (guint i = 0; i < prof->coverage_filters->len; ++i) {
3534 char *filter = (char *)g_ptr_array_index (prof->coverage_filters, i);
3536 if (filter [0] == '+') {
3537 filter = &filter [1];
3539 if (strstr (fqn, filter) != NULL)
3542 has_positive = TRUE;
3546 if (has_positive && !found) {
3547 mono_os_mutex_lock (&log_profiler.coverage_mutex);
3548 mono_conc_hashtable_insert (log_profiler.coverage_filtered_classes, klass, klass);
3549 mono_os_mutex_unlock (&log_profiler.coverage_mutex);
3556 for (guint i = 0; i < prof->coverage_filters->len; ++i) {
3557 // FIXME: Is substring search sufficient?
3558 char *filter = (char *)g_ptr_array_index (prof->coverage_filters, i);
3559 if (filter [0] == '+')
3563 filter = &filter [1];
3565 if (strstr (fqn, filter) != NULL) {
3566 mono_os_mutex_lock (&log_profiler.coverage_mutex);
3567 mono_conc_hashtable_insert (log_profiler.coverage_filtered_classes, klass, klass);
3568 mono_os_mutex_unlock (&log_profiler.coverage_mutex);
3580 header = mono_method_get_header_checked (method, &error);
3581 mono_error_cleanup (&error);
3583 mono_method_header_get_code (header, &code_size, NULL);
3585 assembly = mono_image_get_assembly (image);
3587 // Need to keep the assemblies around for as long as they are kept in the hashtable
3588 // Nunit, for example, has a habit of unloading them before the coverage statistics are
3589 // generated causing a crash. See https://bugzilla.xamarin.com/show_bug.cgi?id=39325
3590 mono_assembly_addref (assembly);
3592 mono_os_mutex_lock (&log_profiler.coverage_mutex);
3593 mono_conc_hashtable_insert (log_profiler.coverage_methods, method, method);
3594 mono_conc_hashtable_insert (log_profiler.coverage_assemblies, assembly, assembly);
3595 mono_os_mutex_unlock (&log_profiler.coverage_mutex);
3597 image_methods = (MonoLockFreeQueue *)mono_conc_hashtable_lookup (log_profiler.coverage_image_to_methods, image);
3599 if (image_methods == NULL) {
3600 image_methods = (MonoLockFreeQueue *) g_malloc (sizeof (MonoLockFreeQueue));
3601 mono_lock_free_queue_init (image_methods);
3602 mono_os_mutex_lock (&log_profiler.coverage_mutex);
3603 mono_conc_hashtable_insert (log_profiler.coverage_image_to_methods, image, image_methods);
3604 mono_os_mutex_unlock (&log_profiler.coverage_mutex);
3607 node = create_method_node (method);
3608 mono_lock_free_queue_enqueue (image_methods, node);
3610 class_methods = (MonoLockFreeQueue *)mono_conc_hashtable_lookup (log_profiler.coverage_classes, klass);
3612 if (class_methods == NULL) {
3613 class_methods = (MonoLockFreeQueue *) g_malloc (sizeof (MonoLockFreeQueue));
3614 mono_lock_free_queue_init (class_methods);
3615 mono_os_mutex_lock (&log_profiler.coverage_mutex);
3616 mono_conc_hashtable_insert (log_profiler.coverage_classes, klass, class_methods);
3617 mono_os_mutex_unlock (&log_profiler.coverage_mutex);
3620 node = create_method_node (method);
3621 mono_lock_free_queue_enqueue (class_methods, node);
3626 #define LINE_BUFFER_SIZE 4096
3627 /* Max file limit of 128KB */
3628 #define MAX_FILE_SIZE 128 * 1024
3630 get_file_content (FILE *stream)
3635 int res, offset = 0;
3637 res = fseek (stream, 0, SEEK_END);
3641 filesize = ftell (stream);
3645 res = fseek (stream, 0, SEEK_SET);
3649 if (filesize > MAX_FILE_SIZE)
3652 buffer = (char *) g_malloc ((filesize + 1) * sizeof (char));
3653 while ((bytes_read = fread (buffer + offset, 1, LINE_BUFFER_SIZE, stream)) > 0)
3654 offset += bytes_read;
3656 /* NULL terminate our buffer */
3657 buffer[filesize] = '\0';
3662 get_next_line (char *contents, char **next_start)
3666 if (p == NULL || *p == '\0') {
3671 while (*p != '\n' && *p != '\0')
3676 *next_start = p + 1;
3684 init_suppressed_assemblies (void)
3690 log_profiler.coverage_suppressed_assemblies = mono_conc_hashtable_new (g_str_hash, g_str_equal);
3691 sa_file = fopen (SUPPRESSION_DIR "/mono-profiler-log.suppression", "r");
3692 if (sa_file == NULL)
3695 /* Don't need to free @content as it is referred to by the lines stored in @suppressed_assemblies */
3696 content = get_file_content (sa_file);
3697 if (content == NULL)
3698 g_error ("mono-profiler-log.suppression is greater than 128kb - aborting.");
3700 while ((line = get_next_line (content, &content))) {
3701 line = g_strchomp (g_strchug (line));
3702 /* No locking needed as we're doing initialization */
3703 mono_conc_hashtable_insert (log_profiler.coverage_suppressed_assemblies, line, line);
3710 parse_cov_filter_file (GPtrArray *filters, const char *file)
3712 FILE *filter_file = fopen (file, "r");
3714 if (filter_file == NULL) {
3715 mono_profiler_printf_err ("Could not open coverage filter file '%s'.", file);
3719 /* Don't need to free content as it is referred to by the lines stored in @filters */
3720 char *content = get_file_content (filter_file);
3722 if (content == NULL)
3723 mono_profiler_printf_err ("Coverage filter file '%s' is larger than 128kb - ignoring.", file);
3727 while ((line = get_next_line (content, &content)))
3728 g_ptr_array_add (filters, g_strchug (g_strchomp (line)));
3730 fclose (filter_file);
3734 coverage_init (void)
3736 mono_os_mutex_init (&log_profiler.coverage_mutex);
3737 log_profiler.coverage_methods = mono_conc_hashtable_new (NULL, NULL);
3738 log_profiler.coverage_assemblies = mono_conc_hashtable_new (NULL, NULL);
3739 log_profiler.coverage_classes = mono_conc_hashtable_new (NULL, NULL);
3740 log_profiler.coverage_filtered_classes = mono_conc_hashtable_new (NULL, NULL);
3741 log_profiler.coverage_image_to_methods = mono_conc_hashtable_new (NULL, NULL);
3742 init_suppressed_assemblies ();
3746 unref_coverage_assemblies (gpointer key, gpointer value, gpointer userdata)
3748 MonoAssembly *assembly = (MonoAssembly *)value;
3749 mono_assembly_close (assembly);
3753 free_sample_hit (gpointer p)
3755 mono_lock_free_free (p, SAMPLE_BLOCK_SIZE);
3759 cleanup_reusable_samples (void)
3763 while ((sample = (SampleHit *) mono_lock_free_queue_dequeue (&log_profiler.sample_reuse_queue)))
3764 mono_thread_hazardous_try_free (sample, free_sample_hit);
3768 log_shutdown (MonoProfiler *prof)
3770 InterlockedWrite (&log_profiler.in_shutdown, 1);
3772 if (ENABLED (PROFLOG_COUNTER_EVENTS))
3773 counters_and_perfcounters_sample ();
3775 if (log_config.collect_coverage)
3780 if (write (prof->pipes [1], &c, 1) != 1) {
3781 mono_profiler_printf_err ("Could not write to log profiler pipe: %s", strerror (errno));
3785 mono_native_thread_join (prof->helper_thread);
3787 mono_os_mutex_destroy (&log_profiler.counters_mutex);
3789 MonoCounterAgent *mc_next;
3791 for (MonoCounterAgent *cur = log_profiler.counters; cur; cur = mc_next) {
3792 mc_next = cur->next;
3796 PerfCounterAgent *pc_next;
3798 for (PerfCounterAgent *cur = log_profiler.perfcounters; cur; cur = pc_next) {
3799 pc_next = cur->next;
3804 * Ensure that we empty the LLS completely, even if some nodes are
3805 * not immediately removed upon calling mono_lls_remove (), by
3806 * iterating until the head is NULL.
3808 while (log_profiler.profiler_thread_list.head) {
3809 MONO_LLS_FOREACH_SAFE (&log_profiler.profiler_thread_list, MonoProfilerThread, thread) {
3810 g_assert (thread->attached && "Why is a thread in the LLS not attached?");
3812 remove_thread (thread);
3813 } MONO_LLS_FOREACH_SAFE_END
3817 * Ensure that all threads have been freed, so that we don't miss any
3818 * buffers when we shut down the writer thread below.
3820 mono_thread_hazardous_try_free_all ();
3822 InterlockedWrite (&prof->run_dumper_thread, 0);
3823 mono_os_sem_post (&prof->dumper_queue_sem);
3824 mono_native_thread_join (prof->dumper_thread);
3825 mono_os_sem_destroy (&prof->dumper_queue_sem);
3827 InterlockedWrite (&prof->run_writer_thread, 0);
3828 mono_os_sem_post (&prof->writer_queue_sem);
3829 mono_native_thread_join (prof->writer_thread);
3830 mono_os_sem_destroy (&prof->writer_queue_sem);
3833 * Free all writer queue entries, and ensure that all sample hits will be
3834 * added to the sample reuse queue.
3836 mono_thread_hazardous_try_free_all ();
3838 cleanup_reusable_samples ();
3841 * Finally, make sure that all sample hits are freed. This should cover all
3842 * hazardous data from the profiler. We can now be sure that the runtime
3843 * won't later invoke free functions in the profiler library after it has
3846 mono_thread_hazardous_try_free_all ();
3848 gint32 state = InterlockedRead (&log_profiler.buffer_lock_state);
3850 g_assert (!(state & 0xFFFF) && "Why is the reader count still non-zero?");
3851 g_assert (!(state >> 16) && "Why is the exclusive lock still held?");
3853 #if defined (HAVE_SYS_ZLIB)
3855 gzclose (prof->gzfile);
3857 if (prof->pipe_output)
3858 pclose (prof->file);
3860 fclose (prof->file);
3862 mono_conc_hashtable_destroy (prof->method_table);
3863 mono_os_mutex_destroy (&prof->method_table_mutex);
3865 if (log_config.collect_coverage) {
3866 mono_os_mutex_lock (&log_profiler.coverage_mutex);
3867 mono_conc_hashtable_foreach (log_profiler.coverage_assemblies, unref_coverage_assemblies, NULL);
3868 mono_os_mutex_unlock (&log_profiler.coverage_mutex);
3870 mono_conc_hashtable_destroy (log_profiler.coverage_methods);
3871 mono_conc_hashtable_destroy (log_profiler.coverage_assemblies);
3872 mono_conc_hashtable_destroy (log_profiler.coverage_classes);
3873 mono_conc_hashtable_destroy (log_profiler.coverage_filtered_classes);
3875 mono_conc_hashtable_destroy (log_profiler.coverage_image_to_methods);
3876 mono_conc_hashtable_destroy (log_profiler.coverage_suppressed_assemblies);
3877 mono_os_mutex_destroy (&log_profiler.coverage_mutex);
3882 g_free (prof->args);
3886 new_filename (const char* filename)
3888 time_t t = time (NULL);
3889 int pid = process_id ();
3894 int count_dates = 0;
3898 for (p = filename; *p; p++) {
3909 if (!count_dates && !count_pids)
3910 return pstrdup (filename);
3911 snprintf (pid_buf, sizeof (pid_buf), "%d", pid);
3913 snprintf (time_buf, sizeof (time_buf), "%d%02d%02d%02d%02d%02d",
3914 1900 + ts->tm_year, 1 + ts->tm_mon, ts->tm_mday, ts->tm_hour, ts->tm_min, ts->tm_sec);
3915 s_date = strlen (time_buf);
3916 s_pid = strlen (pid_buf);
3917 d = res = (char *) g_malloc (strlen (filename) + s_date * count_dates + s_pid * count_pids);
3918 for (p = filename; *p; p++) {
3925 strcpy (d, time_buf);
3928 } else if (*p == 'p') {
3929 strcpy (d, pid_buf);
3932 } else if (*p == '%') {
3945 add_to_fd_set (fd_set *set, int fd, int *max_fd)
3948 * This should only trigger for the basic FDs (server socket, pipes) at
3949 * startup if for some mysterious reason they're too large. In this case,
3950 * the profiler really can't function, and we're better off printing an
3951 * error and exiting.
3953 if (fd >= FD_SETSIZE) {
3954 mono_profiler_printf_err ("File descriptor is out of bounds for fd_set: %d", fd);
3965 helper_thread (void *arg)
3967 mono_threads_attach_tools_thread ();
3968 mono_native_thread_set_name (mono_native_thread_id_get (), "Profiler helper");
3970 MonoProfilerThread *thread = init_thread (FALSE);
3972 GArray *command_sockets = g_array_new (FALSE, FALSE, sizeof (int));
3980 add_to_fd_set (&rfds, log_profiler.server_socket, &max_fd);
3981 add_to_fd_set (&rfds, log_profiler.pipes [0], &max_fd);
3983 for (gint i = 0; i < command_sockets->len; i++)
3984 add_to_fd_set (&rfds, g_array_index (command_sockets, int, i), &max_fd);
3986 struct timeval tv = { .tv_sec = 1, .tv_usec = 0 };
3988 // Sleep for 1sec or until a file descriptor has data.
3989 if (select (max_fd + 1, &rfds, NULL, NULL, &tv) == -1) {
3993 mono_profiler_printf_err ("Could not poll in log profiler helper thread: %s", strerror (errno));
3997 if (ENABLED (PROFLOG_COUNTER_EVENTS))
3998 counters_and_perfcounters_sample ();
4000 buffer_lock_excl ();
4002 sync_point (SYNC_POINT_PERIODIC);
4004 buffer_unlock_excl ();
4006 // Are we shutting down?
4007 if (FD_ISSET (log_profiler.pipes [0], &rfds)) {
4009 read (log_profiler.pipes [0], &c, 1);
4013 for (gint i = 0; i < command_sockets->len; i++) {
4014 int fd = g_array_index (command_sockets, int, i);
4016 if (!FD_ISSET (fd, &rfds))
4020 int len = read (fd, buf, sizeof (buf) - 1);
4026 // The other end disconnected.
4027 g_array_remove_index (command_sockets, i);
4035 if (log_config.hs_mode == MONO_PROFILER_HEAPSHOT_ON_DEMAND && !strcmp (buf, "heapshot\n")) {
4036 // Rely on the finalization callback triggering a GC.
4037 InterlockedWrite (&log_profiler.heapshot_requested, 1);
4038 mono_gc_finalize_notify ();
4042 if (FD_ISSET (log_profiler.server_socket, &rfds)) {
4043 int fd = accept (log_profiler.server_socket, NULL, NULL);
4046 if (fd >= FD_SETSIZE)
4049 g_array_append_val (command_sockets, fd);
4054 for (gint i = 0; i < command_sockets->len; i++)
4055 close (g_array_index (command_sockets, int, i));
4057 g_array_free (command_sockets, TRUE);
4059 send_log_unsafe (FALSE);
4060 deinit_thread (thread);
4062 mono_thread_info_detach ();
4068 start_helper_thread (void)
4070 if (pipe (log_profiler.pipes) == -1) {
4071 mono_profiler_printf_err ("Could not create log profiler pipe: %s", strerror (errno));
4075 log_profiler.server_socket = socket (PF_INET, SOCK_STREAM, 0);
4077 if (log_profiler.server_socket == -1) {
4078 mono_profiler_printf_err ("Could not create log profiler server socket: %s", strerror (errno));
4082 struct sockaddr_in server_address;
4084 memset (&server_address, 0, sizeof (server_address));
4085 server_address.sin_family = AF_INET;
4086 server_address.sin_addr.s_addr = INADDR_ANY;
4087 server_address.sin_port = htons (log_profiler.command_port);
4089 if (bind (log_profiler.server_socket, (struct sockaddr *) &server_address, sizeof (server_address)) == -1) {
4090 mono_profiler_printf_err ("Could not bind log profiler server socket on port %d: %s", log_profiler.command_port, strerror (errno));
4091 close (log_profiler.server_socket);
4095 if (listen (log_profiler.server_socket, 1) == -1) {
4096 mono_profiler_printf_err ("Could not listen on log profiler server socket: %s", strerror (errno));
4097 close (log_profiler.server_socket);
4101 socklen_t slen = sizeof (server_address);
4103 if (getsockname (log_profiler.server_socket, (struct sockaddr *) &server_address, &slen)) {
4104 mono_profiler_printf_err ("Could not retrieve assigned port for log profiler server socket: %s", strerror (errno));
4105 close (log_profiler.server_socket);
4109 log_profiler.command_port = ntohs (server_address.sin_port);
4111 if (!mono_native_thread_create (&log_profiler.helper_thread, helper_thread, NULL)) {
4112 mono_profiler_printf_err ("Could not start log profiler helper thread");
4113 close (log_profiler.server_socket);
4119 free_writer_entry (gpointer p)
4121 mono_lock_free_free (p, WRITER_ENTRY_BLOCK_SIZE);
4125 handle_writer_queue_entry (void)
4127 WriterQueueEntry *entry;
4129 if ((entry = (WriterQueueEntry *) mono_lock_free_queue_dequeue (&log_profiler.writer_queue))) {
4130 if (!entry->methods)
4133 gboolean wrote_methods = FALSE;
4136 * Encode the method events in a temporary log buffer that we
4137 * flush to disk before the main buffer, ensuring that all
4138 * methods have metadata emitted before they're referenced.
4140 * We use a 'proper' thread-local buffer for this as opposed
4141 * to allocating and freeing a buffer by hand because the call
4142 * to mono_method_full_name () below may trigger class load
4143 * events when it retrieves the signature of the method. So a
4144 * thread-local buffer needs to exist when such events occur.
4146 for (guint i = 0; i < entry->methods->len; i++) {
4147 MethodInfo *info = (MethodInfo *) g_ptr_array_index (entry->methods, i);
4149 if (mono_conc_hashtable_lookup (log_profiler.method_table, info->method))
4150 goto free_info; // This method already has metadata emitted.
4153 * Other threads use this hash table to get a general
4154 * idea of whether a method has already been emitted to
4155 * the stream. Due to the way we add to this table, it
4156 * can easily happen that multiple threads queue up the
4157 * same methods, but that's OK since eventually all
4158 * methods will be in this table and the thread-local
4159 * method lists will just be empty for the rest of the
4162 mono_os_mutex_lock (&log_profiler.method_table_mutex);
4163 mono_conc_hashtable_insert (log_profiler.method_table, info->method, info->method);
4164 mono_os_mutex_unlock (&log_profiler.method_table_mutex);
4166 char *name = mono_method_full_name (info->method, 1);
4167 int nlen = strlen (name) + 1;
4168 void *cstart = info->ji ? mono_jit_info_get_code_start (info->ji) : NULL;
4169 int csize = info->ji ? mono_jit_info_get_code_size (info->ji) : 0;
4171 ENTER_LOG (&method_jits_ctr, logbuffer,
4172 EVENT_SIZE /* event */ +
4173 LEB128_SIZE /* method */ +
4174 LEB128_SIZE /* start */ +
4175 LEB128_SIZE /* size */ +
4179 emit_event_time (logbuffer, TYPE_JIT | TYPE_METHOD, info->time);
4180 emit_method_inner (logbuffer, info->method);
4181 emit_ptr (logbuffer, cstart);
4182 emit_value (logbuffer, csize);
4184 memcpy (logbuffer->cursor, name, nlen);
4185 logbuffer->cursor += nlen;
4187 EXIT_LOG_EXPLICIT (NO_SEND);
4191 wrote_methods = TRUE;
4197 g_ptr_array_free (entry->methods, TRUE);
4199 if (wrote_methods) {
4200 MonoProfilerThread *thread = PROF_TLS_GET ();
4202 dump_buffer_threadless (thread->buffer);
4203 init_buffer_state (thread);
4207 dump_buffer (entry->buffer);
4209 mono_thread_hazardous_try_free (entry, free_writer_entry);
4218 writer_thread (void *arg)
4220 mono_threads_attach_tools_thread ();
4221 mono_native_thread_set_name (mono_native_thread_id_get (), "Profiler writer");
4225 MonoProfilerThread *thread = init_thread (FALSE);
4227 while (InterlockedRead (&log_profiler.run_writer_thread)) {
4228 mono_os_sem_wait (&log_profiler.writer_queue_sem, MONO_SEM_FLAGS_NONE);
4229 handle_writer_queue_entry ();
4232 /* Drain any remaining entries on shutdown. */
4233 while (handle_writer_queue_entry ());
4235 free_buffer (thread->buffer, thread->buffer->size);
4236 deinit_thread (thread);
4238 mono_thread_info_detach ();
4244 start_writer_thread (void)
4246 InterlockedWrite (&log_profiler.run_writer_thread, 1);
4248 if (!mono_native_thread_create (&log_profiler.writer_thread, writer_thread, NULL)) {
4249 mono_profiler_printf_err ("Could not start log profiler writer thread");
4255 reuse_sample_hit (gpointer p)
4257 SampleHit *sample = p;
4259 mono_lock_free_queue_node_unpoison (&sample->node);
4260 mono_lock_free_queue_enqueue (&log_profiler.sample_reuse_queue, &sample->node);
4264 handle_dumper_queue_entry (void)
4268 if ((sample = (SampleHit *) mono_lock_free_queue_dequeue (&log_profiler.dumper_queue))) {
4269 for (int i = 0; i < sample->count; ++i) {
4270 MonoMethod *method = sample->frames [i].method;
4271 MonoDomain *domain = sample->frames [i].domain;
4272 void *address = sample->frames [i].base_address;
4275 g_assert (domain && "What happened to the domain pointer?");
4276 g_assert (address && "What happened to the instruction pointer?");
4278 MonoJitInfo *ji = mono_jit_info_table_find (domain, (char *) address);
4281 sample->frames [i].method = mono_jit_info_get_method (ji);
4285 ENTER_LOG (&sample_hits_ctr, logbuffer,
4286 EVENT_SIZE /* event */ +
4287 LEB128_SIZE /* tid */ +
4288 LEB128_SIZE /* count */ +
4290 LEB128_SIZE /* ip */
4292 LEB128_SIZE /* managed count */ +
4294 LEB128_SIZE /* method */
4298 emit_event_time (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_HIT, sample->time);
4299 emit_ptr (logbuffer, (void *) sample->tid);
4300 emit_value (logbuffer, 1);
4302 // TODO: Actual native unwinding.
4303 for (int i = 0; i < 1; ++i) {
4304 emit_ptr (logbuffer, sample->ip);
4305 add_code_pointer ((uintptr_t) sample->ip);
4308 /* new in data version 6 */
4309 emit_uvalue (logbuffer, sample->count);
4311 for (int i = 0; i < sample->count; ++i)
4312 emit_method (logbuffer, sample->frames [i].method);
4316 mono_thread_hazardous_try_free (sample, reuse_sample_hit);
4318 dump_unmanaged_coderefs ();
4325 dumper_thread (void *arg)
4327 mono_threads_attach_tools_thread ();
4328 mono_native_thread_set_name (mono_native_thread_id_get (), "Profiler dumper");
4330 MonoProfilerThread *thread = init_thread (FALSE);
4332 while (InterlockedRead (&log_profiler.run_dumper_thread)) {
4334 * Flush samples every second so it doesn't seem like the profiler is
4335 * not working if the program is mostly idle.
4337 if (mono_os_sem_timedwait (&log_profiler.dumper_queue_sem, 1000, MONO_SEM_FLAGS_NONE) == MONO_SEM_TIMEDWAIT_RET_TIMEDOUT)
4338 send_log_unsafe (FALSE);
4340 handle_dumper_queue_entry ();
4343 /* Drain any remaining entries on shutdown. */
4344 while (handle_dumper_queue_entry ());
4346 send_log_unsafe (FALSE);
4347 deinit_thread (thread);
4349 mono_thread_info_detach ();
4355 start_dumper_thread (void)
4357 InterlockedWrite (&log_profiler.run_dumper_thread, 1);
4359 if (!mono_native_thread_create (&log_profiler.dumper_thread, dumper_thread, NULL)) {
4360 mono_profiler_printf_err ("Could not start log profiler dumper thread");
4366 register_counter (const char *name, gint32 *counter)
4368 mono_counters_register (name, MONO_COUNTER_UINT | MONO_COUNTER_PROFILER | MONO_COUNTER_MONOTONIC, counter);
4372 runtime_initialized (MonoProfiler *profiler)
4374 InterlockedWrite (&log_profiler.runtime_inited, 1);
4376 register_counter ("Sample events allocated", &sample_allocations_ctr);
4377 register_counter ("Log buffers allocated", &buffer_allocations_ctr);
4379 register_counter ("Event: Sync points", &sync_points_ctr);
4380 register_counter ("Event: Heap objects", &heap_objects_ctr);
4381 register_counter ("Event: Heap starts", &heap_starts_ctr);
4382 register_counter ("Event: Heap ends", &heap_ends_ctr);
4383 register_counter ("Event: Heap roots", &heap_roots_ctr);
4384 register_counter ("Event: GC events", &gc_events_ctr);
4385 register_counter ("Event: GC resizes", &gc_resizes_ctr);
4386 register_counter ("Event: GC allocations", &gc_allocs_ctr);
4387 register_counter ("Event: GC moves", &gc_moves_ctr);
4388 register_counter ("Event: GC handle creations", &gc_handle_creations_ctr);
4389 register_counter ("Event: GC handle deletions", &gc_handle_deletions_ctr);
4390 register_counter ("Event: GC finalize starts", &finalize_begins_ctr);
4391 register_counter ("Event: GC finalize ends", &finalize_ends_ctr);
4392 register_counter ("Event: GC finalize object starts", &finalize_object_begins_ctr);
4393 register_counter ("Event: GC finalize object ends", &finalize_object_ends_ctr);
4394 register_counter ("Event: Image loads", &image_loads_ctr);
4395 register_counter ("Event: Image unloads", &image_unloads_ctr);
4396 register_counter ("Event: Assembly loads", &assembly_loads_ctr);
4397 register_counter ("Event: Assembly unloads", &assembly_unloads_ctr);
4398 register_counter ("Event: Class loads", &class_loads_ctr);
4399 register_counter ("Event: Class unloads", &class_unloads_ctr);
4400 register_counter ("Event: Method entries", &method_entries_ctr);
4401 register_counter ("Event: Method exits", &method_exits_ctr);
4402 register_counter ("Event: Method exception leaves", &method_exception_exits_ctr);
4403 register_counter ("Event: Method JITs", &method_jits_ctr);
4404 register_counter ("Event: Code buffers", &code_buffers_ctr);
4405 register_counter ("Event: Exception throws", &exception_throws_ctr);
4406 register_counter ("Event: Exception clauses", &exception_clauses_ctr);
4407 register_counter ("Event: Monitor events", &monitor_events_ctr);
4408 register_counter ("Event: Thread starts", &thread_starts_ctr);
4409 register_counter ("Event: Thread ends", &thread_ends_ctr);
4410 register_counter ("Event: Thread names", &thread_names_ctr);
4411 register_counter ("Event: Domain loads", &domain_loads_ctr);
4412 register_counter ("Event: Domain unloads", &domain_unloads_ctr);
4413 register_counter ("Event: Domain names", &domain_names_ctr);
4414 register_counter ("Event: Context loads", &context_loads_ctr);
4415 register_counter ("Event: Context unloads", &context_unloads_ctr);
4416 register_counter ("Event: Sample binaries", &sample_ubins_ctr);
4417 register_counter ("Event: Sample symbols", &sample_usyms_ctr);
4418 register_counter ("Event: Sample hits", &sample_hits_ctr);
4419 register_counter ("Event: Counter descriptors", &counter_descriptors_ctr);
4420 register_counter ("Event: Counter samples", &counter_samples_ctr);
4421 register_counter ("Event: Performance counter descriptors", &perfcounter_descriptors_ctr);
4422 register_counter ("Event: Performance counter samples", &perfcounter_samples_ctr);
4423 register_counter ("Event: Coverage methods", &coverage_methods_ctr);
4424 register_counter ("Event: Coverage statements", &coverage_statements_ctr);
4425 register_counter ("Event: Coverage classes", &coverage_classes_ctr);
4426 register_counter ("Event: Coverage assemblies", &coverage_assemblies_ctr);
4431 * We must start the helper thread before the writer thread. This is
4432 * because the helper thread sets up the command port which is written to
4433 * the log header by the writer thread.
4435 start_helper_thread ();
4436 start_writer_thread ();
4437 start_dumper_thread ();
4441 create_profiler (const char *args, const char *filename, GPtrArray *filters)
4445 log_profiler.args = pstrdup (args);
4446 log_profiler.command_port = log_config.command_port;
4448 //If filename begin with +, append the pid at the end
4449 if (filename && *filename == '+')
4450 filename = g_strdup_printf ("%s.%d", filename + 1, getpid ());
4453 if (log_config.do_report)
4454 filename = "|mprof-report -";
4456 filename = "output.mlpd";
4457 nf = (char*)filename;
4459 nf = new_filename (filename);
4460 if (log_config.do_report) {
4461 int s = strlen (nf) + 32;
4462 char *p = (char *) g_malloc (s);
4463 snprintf (p, s, "|mprof-report '--out=%s' -", nf);
4469 log_profiler.file = popen (nf + 1, "w");
4470 log_profiler.pipe_output = 1;
4471 } else if (*nf == '#') {
4472 int fd = strtol (nf + 1, NULL, 10);
4473 log_profiler.file = fdopen (fd, "a");
4475 log_profiler.file = fopen (nf, "wb");
4477 if (!log_profiler.file) {
4478 mono_profiler_printf_err ("Could not create log profiler output file '%s'.", nf);
4482 #if defined (HAVE_SYS_ZLIB)
4483 if (log_config.use_zip)
4484 log_profiler.gzfile = gzdopen (fileno (log_profiler.file), "wb");
4488 * If you hit this assert while increasing MAX_FRAMES, you need to increase
4489 * SAMPLE_BLOCK_SIZE as well.
4491 g_assert (SAMPLE_SLOT_SIZE (MAX_FRAMES) * 2 < LOCK_FREE_ALLOC_SB_USABLE_SIZE (SAMPLE_BLOCK_SIZE));
4493 // FIXME: We should free this stuff too.
4494 mono_lock_free_allocator_init_size_class (&log_profiler.sample_size_class, SAMPLE_SLOT_SIZE (log_config.num_frames), SAMPLE_BLOCK_SIZE);
4495 mono_lock_free_allocator_init_allocator (&log_profiler.sample_allocator, &log_profiler.sample_size_class, MONO_MEM_ACCOUNT_PROFILER);
4497 mono_lock_free_queue_init (&log_profiler.sample_reuse_queue);
4499 g_assert (sizeof (WriterQueueEntry) * 2 < LOCK_FREE_ALLOC_SB_USABLE_SIZE (WRITER_ENTRY_BLOCK_SIZE));
4501 // FIXME: We should free this stuff too.
4502 mono_lock_free_allocator_init_size_class (&log_profiler.writer_entry_size_class, sizeof (WriterQueueEntry), WRITER_ENTRY_BLOCK_SIZE);
4503 mono_lock_free_allocator_init_allocator (&log_profiler.writer_entry_allocator, &log_profiler.writer_entry_size_class, MONO_MEM_ACCOUNT_PROFILER);
4505 mono_lock_free_queue_init (&log_profiler.writer_queue);
4506 mono_os_sem_init (&log_profiler.writer_queue_sem, 0);
4508 mono_lock_free_queue_init (&log_profiler.dumper_queue);
4509 mono_os_sem_init (&log_profiler.dumper_queue_sem, 0);
4511 mono_os_mutex_init (&log_profiler.method_table_mutex);
4512 log_profiler.method_table = mono_conc_hashtable_new (NULL, NULL);
4514 if (log_config.collect_coverage)
4517 log_profiler.coverage_filters = filters;
4519 log_profiler.startup_time = current_time ();
4523 * declaration to silence the compiler: this is the entry point that
4524 * mono will load from the shared library and call.
4527 mono_profiler_init (const char *desc);
4530 mono_profiler_init_log (const char *desc);
4533 * this is the entry point that will be used when the profiler
4534 * is embedded inside the main executable.
4537 mono_profiler_init_log (const char *desc)
4539 mono_profiler_init (desc);
4543 mono_profiler_init (const char *desc)
4545 GPtrArray *filters = NULL;
4547 proflog_parse_args (&log_config, desc [3] == ':' ? desc + 4 : "");
4549 if (log_config.cov_filter_files) {
4550 filters = g_ptr_array_new ();
4552 for (i = 0; i < log_config.cov_filter_files->len; ++i) {
4553 const char *name = log_config.cov_filter_files->pdata [i];
4554 parse_cov_filter_file (filters, name);
4562 create_profiler (desc, log_config.output_filename, filters);
4564 mono_lls_init (&log_profiler.profiler_thread_list, NULL);
4566 MonoProfilerHandle handle = log_profiler.handle = mono_profiler_install (&log_profiler);
4569 * Required callbacks. These are either necessary for the profiler itself
4570 * to function, or provide metadata that's needed if other events (e.g.
4571 * allocations, exceptions) are dynamically enabled/disabled.
4574 mono_profiler_set_runtime_shutdown_end_callback (handle, log_shutdown);
4575 mono_profiler_set_runtime_initialized_callback (handle, runtime_initialized);
4577 mono_profiler_set_gc_event_callback (handle, gc_event);
4579 mono_profiler_set_thread_started_callback (handle, thread_start);
4580 mono_profiler_set_thread_stopped_callback (handle, thread_end);
4581 mono_profiler_set_thread_name_callback (handle, thread_name);
4583 mono_profiler_set_domain_loaded_callback (handle, domain_loaded);
4584 mono_profiler_set_domain_unloading_callback (handle, domain_unloaded);
4585 mono_profiler_set_domain_name_callback (handle, domain_name);
4587 mono_profiler_set_context_loaded_callback (handle, context_loaded);
4588 mono_profiler_set_context_unloaded_callback (handle, context_unloaded);
4590 mono_profiler_set_assembly_loaded_callback (handle, assembly_loaded);
4591 mono_profiler_set_assembly_unloading_callback (handle, assembly_unloaded);
4593 mono_profiler_set_image_loaded_callback (handle, image_loaded);
4594 mono_profiler_set_image_unloading_callback (handle, image_unloaded);
4596 mono_profiler_set_class_loaded_callback (handle, class_loaded);
4598 mono_profiler_set_jit_done_callback (handle, method_jitted);
4600 if (ENABLED (PROFLOG_EXCEPTION_EVENTS)) {
4601 mono_profiler_set_exception_throw_callback (handle, throw_exc);
4602 mono_profiler_set_exception_clause_callback (handle, clause_exc);
4605 if (ENABLED (PROFLOG_MONITOR_EVENTS)) {
4606 mono_profiler_set_monitor_contention_callback (handle, monitor_contention);
4607 mono_profiler_set_monitor_acquired_callback (handle, monitor_acquired);
4608 mono_profiler_set_monitor_failed_callback (handle, monitor_failed);
4611 if (ENABLED (PROFLOG_GC_EVENTS))
4612 mono_profiler_set_gc_resize_callback (handle, gc_resize);
4614 if (ENABLED (PROFLOG_GC_ALLOCATION_EVENTS)) {
4615 mono_profiler_enable_allocations ();
4616 mono_profiler_set_gc_allocation_callback (handle, gc_alloc);
4619 if (ENABLED (PROFLOG_GC_MOVE_EVENTS))
4620 mono_profiler_set_gc_moves_callback (handle, gc_moves);
4622 if (ENABLED (PROFLOG_GC_ROOT_EVENTS))
4623 mono_profiler_set_gc_roots_callback (handle, gc_roots);
4625 if (ENABLED (PROFLOG_GC_HANDLE_EVENTS)) {
4626 mono_profiler_set_gc_handle_created_callback (handle, gc_handle_created);
4627 mono_profiler_set_gc_handle_deleted_callback (handle, gc_handle_deleted);
4630 if (ENABLED (PROFLOG_FINALIZATION_EVENTS)) {
4631 mono_profiler_set_gc_finalizing_callback (handle, finalize_begin);
4632 mono_profiler_set_gc_finalized_callback (handle, finalize_end);
4633 mono_profiler_set_gc_finalizing_object_callback (handle, finalize_object_begin);
4634 mono_profiler_set_gc_finalized_object_callback (handle, finalize_object_end);
4635 } else if (log_config.hs_mode == MONO_PROFILER_HEAPSHOT_ON_DEMAND) {
4636 //On Demand heapshot uses the finalizer thread to force a collection and thus a heapshot
4637 mono_profiler_set_gc_finalized_callback (handle, finalize_end);
4640 if (ENABLED (PROFLOG_SAMPLE_EVENTS))
4641 mono_profiler_set_sample_hit_callback (handle, mono_sample_hit);
4643 if (ENABLED (PROFLOG_JIT_EVENTS))
4644 mono_profiler_set_jit_code_buffer_callback (handle, code_buffer_new);
4646 if (log_config.enter_leave) {
4647 mono_profiler_set_call_instrumentation_filter_callback (handle, method_filter);
4648 mono_profiler_set_method_enter_callback (handle, method_enter);
4649 mono_profiler_set_method_leave_callback (handle, method_leave);
4650 mono_profiler_set_method_exception_leave_callback (handle, method_exc_leave);
4653 if (log_config.collect_coverage)
4654 mono_profiler_set_coverage_filter_callback (handle, coverage_filter);
4656 mono_profiler_enable_sampling (handle);
4659 * If no sample option was given by the user, this just leaves the sampling
4660 * thread in idle mode. We do this even if no option was given so that we
4661 * can warn if another profiler controls sampling parameters.
4663 if (!mono_profiler_set_sample_mode (handle, log_config.sampling_mode, log_config.sample_freq))
4664 mono_profiler_printf_err ("Another profiler controls sampling parameters; the log profiler will not be able to modify them.");