2 * proflog.c: mono log profiler
5 * Paolo Molaro (lupus@ximian.com)
7 * Copyright 2010 Novell, Inc (http://www.novell.com)
8 * Copyright 2011 Xamarin Inc (http://www.xamarin.com)
12 #include "../mini/jit.h"
13 #include <mono/metadata/profiler.h>
14 #include <mono/metadata/threads.h>
15 #include <mono/metadata/mono-gc.h>
16 #include <mono/metadata/debug-helpers.h>
17 #include <mono/metadata/mono-perfcounters.h>
18 #include <mono/metadata/appdomain.h>
19 #include <mono/utils/atomic.h>
20 #include <mono/utils/mono-membar.h>
21 #include <mono/utils/mono-counters.h>
22 #include <mono/utils/mono-mutex.h>
23 #include <mono/utils/mono-conc-hashtable.h>
24 #include <mono/utils/lock-free-queue.h>
34 #if defined(HOST_WIN32) || defined(DISABLE_SOCKETS)
35 #define DISABLE_HELPER_THREAD 1
44 #ifdef HAVE_EXECINFO_H
51 #ifndef DISABLE_HELPER_THREAD
52 #include <sys/types.h>
53 #include <sys/socket.h>
54 #include <netinet/in.h>
55 #include <sys/select.h>
64 #ifdef HAVE_SYS_STAT_H
71 #if defined (HAVE_SYS_ZLIB)
75 #if defined(__linux__)
78 #include <sys/syscall.h>
79 #include "perf_event.h"
81 #ifdef ENABLE_PERF_EVENTS
82 #define USE_PERF_EVENTS 1
84 static int read_perf_mmap (MonoProfiler* prof, int cpu);
89 #define BUFFER_SIZE (4096 * 16)
90 static int nocalls = 0;
91 static int notraces = 0;
92 static int use_zip = 0;
93 static int do_report = 0;
94 static int do_heap_shot = 0;
95 static int max_call_depth = 100;
96 static int runtime_inited = 0;
97 static int command_port = 0;
98 static int heapshot_requested = 0;
99 static int sample_type = 0;
100 static int sample_freq = 0;
101 static int do_mono_sample = 0;
102 static int in_shutdown = 0;
103 static int do_debug = 0;
104 static int do_counters = 0;
105 static MonoProfileSamplingMode sampling_mode = MONO_PROFILER_STAT_MODE_PROCESS;
107 /* For linux compile with:
108 * gcc -fPIC -shared -o libmono-profiler-log.so proflog.c utils.c -Wall -g -lz `pkg-config --cflags --libs mono-2`
109 * gcc -o mprof-report decode.c utils.c -Wall -g -lz -lrt -lpthread `pkg-config --cflags mono-2`
111 * For osx compile with:
112 * gcc -m32 -Dmono_free=free shared -o libmono-profiler-log.dylib proflog.c utils.c -Wall -g -lz `pkg-config --cflags mono-2` -undefined suppress -flat_namespace
113 * gcc -m32 -o mprof-report decode.c utils.c -Wall -g -lz -lrt -lpthread `pkg-config --cflags mono-2`
116 * sudo cp mprof-report /usr/local/bin
117 * sudo cp libmono-profiler-log.so /usr/local/lib
121 typedef struct _LogBuffer LogBuffer;
127 * The file is composed by a header followed by 0 or more buffers.
128 * Each buffer contains events that happened on a thread: for a given thread
129 * buffers that appear later in the file are guaranteed to contain events
130 * that happened later in time. Buffers from separate threads could be interleaved,
132 * Buffers are not required to be aligned.
135 * [id: 4 bytes] constant value: LOG_HEADER_ID
136 * [major: 1 byte] [minor: 1 byte] major and minor version of the log profiler
137 * [format: 1 byte] version of the data format for the rest of the file
138 * [ptrsize: 1 byte] size in bytes of a pointer in the profiled program
139 * [startup time: 8 bytes] time in milliseconds since the unix epoch when the program started
140 * [timer overhead: 4 bytes] approximate overhead in nanoseconds of the timer
141 * [flags: 4 bytes] file format flags, should be 0 for now
142 * [pid: 4 bytes] pid of the profiled process
143 * [port: 2 bytes] tcp port for server if != 0
144 * [sysid: 2 bytes] operating system and architecture identifier
146 * The multiple byte integers are in little-endian format.
149 * [buffer header] [event]*
150 * Buffers have a fixed-size header followed by 0 or more bytes of event data.
151 * Timing information and other values in the event data are usually stored
152 * as uleb128 or sleb128 integers. To save space, as noted for each item below,
153 * some data is represented as a difference between the actual value and
154 * either the last value of the same type (like for timing information) or
155 * as the difference from a value stored in a buffer header.
157 * For timing information the data is stored as uleb128, since timing
158 * increases in a monotonic way in each thread: the value is the number of
159 * nanoseconds to add to the last seen timing data in a buffer. The first value
160 * in a buffer will be calculated from the time_base field in the buffer head.
162 * Object or heap sizes are stored as uleb128.
163 * Pointer differences are stored as sleb128, instead.
165 * If an unexpected value is found, the rest of the buffer should be ignored,
166 * as generally the later values need the former to be interpreted correctly.
168 * buffer header format:
169 * [bufid: 4 bytes] constant value: BUF_ID
170 * [len: 4 bytes] size of the data following the buffer header
171 * [time_base: 8 bytes] time base in nanoseconds since an unspecified epoch
172 * [ptr_base: 8 bytes] base value for pointers
173 * [obj_base: 8 bytes] base value for object addresses
174 * [thread id: 8 bytes] system-specific thread ID (pthread_t for example)
175 * [method_base: 8 bytes] base value for MonoMethod pointers
178 * [extended info: upper 4 bits] [type: lower 4 bits] [data]*
179 * The data that follows depends on type and the extended info.
180 * Type is one of the enum values in proflog.h: TYPE_ALLOC, TYPE_GC,
181 * TYPE_METADATA, TYPE_METHOD, TYPE_EXCEPTION, TYPE_MONITOR, TYPE_HEAP.
182 * The extended info bits are interpreted based on type, see
183 * each individual event description below.
184 * strings are represented as a 0-terminated utf8 sequence.
187 * [flags: uleb128] must be 0
188 * [num: uleb128] number of frames following
189 * [frame: sleb128]* num MonoMethod pointers as differences from ptr_base
193 * exinfo: flags: TYPE_ALLOC_BT
194 * [time diff: uleb128] nanoseconds since last timing
195 * [ptr: sleb128] class as a byte difference from ptr_base
196 * [obj: sleb128] object address as a byte difference from obj_base
197 * [size: uleb128] size of the object in the heap
198 * If the TYPE_ALLOC_BT flag is set, a backtrace follows.
202 * exinfo: one of TYPE_GC_EVENT, TYPE_GC_RESIZE, TYPE_GC_MOVE, TYPE_GC_HANDLE_CREATED,
203 * TYPE_GC_HANDLE_DESTROYED
204 * [time diff: uleb128] nanoseconds since last timing
205 * if exinfo == TYPE_GC_RESIZE
206 * [heap_size: uleb128] new heap size
207 * if exinfo == TYPE_GC_EVENT
208 * [event type: uleb128] GC event (MONO_GC_EVENT_* from profiler.h)
209 * [generation: uleb128] GC generation event refers to
210 * if exinfo == TYPE_GC_MOVE
211 * [num_objects: uleb128] number of object moves that follow
212 * [objaddr: sleb128]+ num_objects object pointer differences from obj_base
213 * num is always an even number: the even items are the old
214 * addresses, the odd numbers are the respective new object addresses
215 * if exinfo == TYPE_GC_HANDLE_CREATED
216 * [handle_type: uleb128] GC handle type (System.Runtime.InteropServices.GCHandleType)
217 * upper bits reserved as flags
218 * [handle: uleb128] GC handle value
219 * [objaddr: sleb128] object pointer differences from obj_base
220 * if exinfo == TYPE_GC_HANDLE_DESTROYED
221 * [handle_type: uleb128] GC handle type (System.Runtime.InteropServices.GCHandleType)
222 * upper bits reserved as flags
223 * [handle: uleb128] GC handle value
225 * type metadata format:
226 * type: TYPE_METADATA
227 * exinfo: flags: TYPE_LOAD_ERR
228 * [time diff: uleb128] nanoseconds since last timing
229 * [mtype: byte] metadata type, one of: TYPE_CLASS, TYPE_IMAGE, TYPE_ASSEMBLY, TYPE_DOMAIN,
231 * [pointer: sleb128] pointer of the metadata type depending on mtype
232 * if mtype == TYPE_CLASS
233 * [image: sleb128] MonoImage* as a pointer difference from ptr_base
234 * [flags: uleb128] must be 0
235 * [name: string] full class name
236 * if mtype == TYPE_IMAGE
237 * [flags: uleb128] must be 0
238 * [name: string] image file name
239 * if mtype == TYPE_THREAD
240 * [flags: uleb128] must be 0
241 * [name: string] thread name
243 * type method format:
245 * exinfo: one of: TYPE_LEAVE, TYPE_ENTER, TYPE_EXC_LEAVE, TYPE_JIT
246 * [time diff: uleb128] nanoseconds since last timing
247 * [method: sleb128] MonoMethod* as a pointer difference from the last such
248 * pointer or the buffer method_base
249 * if exinfo == TYPE_JIT
250 * [code address: sleb128] pointer to the native code as a diff from ptr_base
251 * [code size: uleb128] size of the generated code
252 * [name: string] full method name
254 * type runtime format:
256 * exinfo: one of: TYPE_JITHELPER
257 * [time diff: uleb128] nanoseconds since last timing
258 * if exinfo == TYPE_JITHELPER
259 * [type: uleb128] MonoProfilerCodeBufferType enum value
260 * [buffer address: sleb128] pointer to the native code as a diff from ptr_base
261 * [buffer size: uleb128] size of the generated code
262 * if type == MONO_PROFILER_CODE_BUFFER_SPECIFIC_TRAMPOLINE
263 * [name: string] buffer description name
265 * type monitor format:
267 * exinfo: TYPE_MONITOR_BT flag and one of: MONO_PROFILER_MONITOR_(CONTENTION|FAIL|DONE)
268 * [time diff: uleb128] nanoseconds since last timing
269 * [object: sleb128] the lock object as a difference from obj_base
270 * if exinfo.low3bits == MONO_PROFILER_MONITOR_CONTENTION
271 * If the TYPE_MONITOR_BT flag is set, a backtrace follows.
275 * exinfo: one of TYPE_HEAP_START, TYPE_HEAP_END, TYPE_HEAP_OBJECT, TYPE_HEAP_ROOT
276 * if exinfo == TYPE_HEAP_START
277 * [time diff: uleb128] nanoseconds since last timing
278 * if exinfo == TYPE_HEAP_END
279 * [time diff: uleb128] nanoseconds since last timing
280 * if exinfo == TYPE_HEAP_OBJECT
281 * [object: sleb128] the object as a difference from obj_base
282 * [class: sleb128] the object MonoClass* as a difference from ptr_base
283 * [size: uleb128] size of the object on the heap
284 * [num_refs: uleb128] number of object references
285 * if (format version > 1) each referenced objref is preceded by a
286 * uleb128 encoded offset: the first offset is from the object address
287 * and each next offset is relative to the previous one
288 * [objrefs: sleb128]+ object referenced as a difference from obj_base
289 * The same object can appear multiple times, but only the first time
290 * with size != 0: in the other cases this data will only be used to
291 * provide additional referenced objects.
292 * if exinfo == TYPE_HEAP_ROOT
293 * [num_roots: uleb128] number of root references
294 * [num_gc: uleb128] number of major gcs
295 * [object: sleb128] the object as a difference from obj_base
296 * [root_type: uleb128] the root_type: MonoProfileGCRootType (profiler.h)
297 * [extra_info: uleb128] the extra_info value
298 * object, root_type and extra_info are repeated num_roots times
302 * exinfo: one of TYPE_SAMPLE_HIT, TYPE_SAMPLE_USYM, TYPE_SAMPLE_UBIN, TYPE_SAMPLE_COUNTERS_DESC, TYPE_SAMPLE_COUNTERS
303 * if exinfo == TYPE_SAMPLE_HIT
304 * [sample_type: uleb128] type of sample (SAMPLE_*)
305 * [timestamp: uleb128] nanoseconds since startup (note: different from other timestamps!)
306 * [count: uleb128] number of following instruction addresses
307 * [ip: sleb128]* instruction pointer as difference from ptr_base
308 * if (format_version > 5)
309 * [mbt_count: uleb128] number of managed backtrace info triplets (method + IL offset + native offset)
310 * [method: sleb128]* MonoMethod* as a pointer difference from the last such
311 * pointer or the buffer method_base (the first such method can be also indentified by ip, but this is not neccessarily true)
312 * [il_offset: sleb128]* IL offset inside method where the hit occurred
313 * [native_offset: sleb128]* native offset inside method where the hit occurred
314 * if exinfo == TYPE_SAMPLE_USYM
315 * [address: sleb128] symbol address as a difference from ptr_base
316 * [size: uleb128] symbol size (may be 0 if unknown)
317 * [name: string] symbol name
318 * if exinfo == TYPE_SAMPLE_UBIN
319 * [time diff: uleb128] nanoseconds since last timing
320 * [address: sleb128] address where binary has been loaded
321 * [offset: uleb128] file offset of mapping (the same file can be mapped multiple times)
322 * [size: uleb128] memory size
323 * [name: string] binary name
324 * if exinfo == TYPE_SAMPLE_COUNTERS_DESC
325 * [len: uleb128] number of counters
327 * [section: uleb128] section of counter
328 * if section == MONO_COUNTER_PERFCOUNTERS:
329 * [section_name: string] section name of counter
330 * [name: string] name of counter
331 * [type: uleb128] type of counter
332 * [unit: uleb128] unit of counter
333 * [variance: uleb128] variance of counter
334 * [index: uleb128] unique index of counter
335 * if exinfo == TYPE_SAMPLE_COUNTERS
336 * [timestamp: uleb128] sampling timestamp
338 * [index: uleb128] unique index of counter
341 * [type: uleb128] type of counter value
344 * [0: uleb128] 0 -> value is null
346 * [1: uleb128] 1 -> value is not null
347 * [value: string] counter value
349 * [value: uleb128/sleb128/double] counter value, can be sleb128, uleb128 or double (determined by using type)
357 uintptr_t method_base;
358 uintptr_t last_method;
361 unsigned char* data_end;
366 unsigned char buf [1];
370 ign_res (int G_GNUC_UNUSED unused, ...)
374 #define ENTER_LOG(lb,str) if ((lb)->locked) {ign_res (write(2, str, strlen(str))); ign_res (write(2, "\n", 1));return;} else {(lb)->locked++;}
375 #define EXIT_LOG(lb) (lb)->locked--;
377 typedef struct _StatBuffer StatBuffer;
386 typedef struct _BinaryObject BinaryObject;
388 struct _BinaryObject {
394 struct _MonoProfiler {
395 StatBuffer *stat_buffers;
397 #if defined (HAVE_SYS_ZLIB)
400 uint64_t startup_time;
402 int last_gc_gen_started;
407 pthread_t helper_thread;
408 pthread_t writer_thread;
410 volatile gint32 run_writer_thread;
411 MonoLockFreeQueue writer_queue;
412 MonoConcurrentHashTable *method_table;
413 mono_mutex_t method_table_mutex;
414 BinaryObject *binary_objects;
417 typedef struct _WriterQueueEntry WriterQueueEntry;
418 struct _WriterQueueEntry {
419 MonoLockFreeQueueNode node;
424 typedef struct _MethodInfo MethodInfo;
435 #define TLS_SET(x,y) (TlsSetValue (x, y))
436 #define TLS_GET(t,x) ((t *) TlsGetValue (x))
437 #define TLS_INIT(x) (x = TlsAlloc ())
438 static int tlsbuffer;
439 static int tlsmethodlist;
441 #define TLS_SET(x,y) (x = y)
442 #define TLS_GET(t,x) (x)
444 static __thread LogBuffer* tlsbuffer = NULL;
445 static __thread GPtrArray* tlsmethodlist = NULL;
447 #define TLS_SET(x,y) (pthread_setspecific (x, y))
448 #define TLS_GET(t,x) ((t *) pthread_getspecific (x))
449 #define TLS_INIT(x) (pthread_key_create (&x, NULL))
450 static pthread_key_t tlsbuffer;
451 static pthread_key_t tlsmethodlist;
454 static void safe_send (MonoProfiler *profiler, LogBuffer *logbuffer);
457 pstrdup (const char *s)
459 int len = strlen (s) + 1;
460 char *p = malloc (len);
466 create_stat_buffer (void)
468 StatBuffer* buf = alloc_buffer (BUFFER_SIZE);
469 buf->size = BUFFER_SIZE;
470 buf->data_end = (uintptr_t*)((unsigned char*)buf + buf->size);
471 buf->data = buf->buf;
478 LogBuffer* buf = alloc_buffer (BUFFER_SIZE);
479 buf->size = BUFFER_SIZE;
480 buf->time_base = current_time ();
481 buf->last_time = buf->time_base;
482 buf->data_end = (unsigned char*)buf + buf->size;
483 buf->data = buf->buf;
490 if (!TLS_GET (LogBuffer, tlsbuffer)) {
491 LogBuffer *logbuffer = create_buffer ();
492 TLS_SET (tlsbuffer, logbuffer);
493 logbuffer->thread_id = thread_id ();
495 if (!TLS_GET (GPtrArray, tlsmethodlist)) {
496 GPtrArray *methodlist = g_ptr_array_new ();
497 TLS_SET (tlsmethodlist, methodlist);
500 //printf ("thread %p at time %llu\n", (void*)logbuffer->thread_id, logbuffer->time_base);
504 ensure_logbuf_inner (LogBuffer *old, int bytes)
506 if (old && old->data + bytes + 100 < old->data_end)
509 LogBuffer *new = create_buffer ();
510 new->thread_id = thread_id ();
514 new->call_depth = old->call_depth;
520 ensure_logbuf (int bytes)
522 LogBuffer *old = TLS_GET (LogBuffer, tlsbuffer);
523 LogBuffer *new = ensure_logbuf_inner (old, bytes);
526 return old; // Still enough space.
528 TLS_SET (tlsbuffer, new);
535 emit_byte (LogBuffer *logbuffer, int value)
537 logbuffer->data [0] = value;
539 assert (logbuffer->data <= logbuffer->data_end);
543 emit_value (LogBuffer *logbuffer, int value)
545 encode_uleb128 (value, logbuffer->data, &logbuffer->data);
546 assert (logbuffer->data <= logbuffer->data_end);
550 emit_time (LogBuffer *logbuffer, uint64_t value)
552 uint64_t tdiff = value - logbuffer->last_time;
553 if (value < logbuffer->last_time)
554 printf ("time went backwards\n");
555 //if (tdiff > 1000000)
556 // printf ("large time offset: %llu\n", tdiff);
557 encode_uleb128 (tdiff, logbuffer->data, &logbuffer->data);
558 /*if (tdiff != decode_uleb128 (p, &p))
559 printf ("incorrect encoding: %llu\n", tdiff);*/
560 logbuffer->last_time = value;
561 assert (logbuffer->data <= logbuffer->data_end);
565 emit_svalue (LogBuffer *logbuffer, int64_t value)
567 encode_sleb128 (value, logbuffer->data, &logbuffer->data);
568 assert (logbuffer->data <= logbuffer->data_end);
572 emit_uvalue (LogBuffer *logbuffer, uint64_t value)
574 encode_uleb128 (value, logbuffer->data, &logbuffer->data);
575 assert (logbuffer->data <= logbuffer->data_end);
579 emit_ptr (LogBuffer *logbuffer, void *ptr)
581 if (!logbuffer->ptr_base)
582 logbuffer->ptr_base = (uintptr_t)ptr;
583 emit_svalue (logbuffer, (intptr_t)ptr - logbuffer->ptr_base);
584 assert (logbuffer->data <= logbuffer->data_end);
588 emit_method_inner (LogBuffer *logbuffer, void *method)
590 if (!logbuffer->method_base) {
591 logbuffer->method_base = (intptr_t)method;
592 logbuffer->last_method = (intptr_t)method;
594 encode_sleb128 ((intptr_t)((char*)method - (char*)logbuffer->last_method), logbuffer->data, &logbuffer->data);
595 logbuffer->last_method = (intptr_t)method;
596 assert (logbuffer->data <= logbuffer->data_end);
605 find_method (MonoDomain *domain, void *user_data)
607 MethodSearch *search = user_data;
612 MonoJitInfo *ji = mono_get_jit_info_from_method (domain, search->method);
614 // It could be AOT'd, so we need to get it from the AOT runtime's cache.
616 void *ip = mono_aot_get_method (domain, search->method);
618 // Avoid a slow path in mono_jit_info_table_find ().
620 ji = mono_jit_info_table_find (domain, ip);
628 register_method_local (MonoProfiler *prof, MonoDomain *domain, MonoMethod *method, MonoJitInfo *ji)
633 if (!mono_conc_hashtable_lookup (prof->method_table, method)) {
635 MethodSearch search = { method, NULL };
637 mono_domain_foreach (find_method, &search);
644 MethodInfo *info = malloc (sizeof (MethodInfo));
646 info->method = method;
649 g_ptr_array_add (TLS_GET (GPtrArray, tlsmethodlist), info);
654 emit_method (MonoProfiler *prof, LogBuffer *logbuffer, MonoDomain *domain, MonoMethod *method)
656 register_method_local (prof, domain, method, NULL);
657 emit_method_inner (logbuffer, method);
661 emit_obj (LogBuffer *logbuffer, void *ptr)
663 if (!logbuffer->obj_base)
664 logbuffer->obj_base = (uintptr_t)ptr >> 3;
665 emit_svalue (logbuffer, ((uintptr_t)ptr >> 3) - logbuffer->obj_base);
666 assert (logbuffer->data <= logbuffer->data_end);
670 emit_string (LogBuffer *logbuffer, const char *str, size_t size)
674 for (; i < size; i++) {
677 emit_byte (logbuffer, str [i]);
680 emit_byte (logbuffer, '\0');
684 emit_double (LogBuffer *logbuffer, double value)
687 unsigned char buffer[8];
688 memcpy (buffer, &value, 8);
689 #if G_BYTE_ORDER == G_BIG_ENDIAN
690 for (i = 7; i >= 0; i--)
692 for (i = 0; i < 8; i++)
694 emit_byte (logbuffer, buffer[i]);
698 write_int16 (char *buf, int32_t value)
701 for (i = 0; i < 2; ++i) {
709 write_int32 (char *buf, int32_t value)
712 for (i = 0; i < 4; ++i) {
720 write_int64 (char *buf, int64_t value)
723 for (i = 0; i < 8; ++i) {
731 dump_header (MonoProfiler *profiler)
735 p = write_int32 (p, LOG_HEADER_ID);
736 *p++ = LOG_VERSION_MAJOR;
737 *p++ = LOG_VERSION_MINOR;
738 *p++ = LOG_DATA_VERSION;
739 *p++ = sizeof (void*);
740 p = write_int64 (p, ((uint64_t)time (NULL)) * 1000); /* startup time */
741 p = write_int32 (p, get_timer_overhead ()); /* timer overhead */
742 p = write_int32 (p, 0); /* flags */
743 p = write_int32 (p, process_id ()); /* pid */
744 p = write_int16 (p, profiler->command_port); /* port */
745 p = write_int16 (p, 0); /* opsystem */
746 #if defined (HAVE_SYS_ZLIB)
747 if (profiler->gzfile) {
748 gzwrite (profiler->gzfile, hbuf, p - hbuf);
750 fwrite (hbuf, p - hbuf, 1, profiler->file);
753 fwrite (hbuf, p - hbuf, 1, profiler->file);
754 fflush (profiler->file);
759 send_buffer (MonoProfiler *prof, GPtrArray *methods, LogBuffer *buffer)
761 WriterQueueEntry *entry = calloc (1, sizeof (WriterQueueEntry));
762 mono_lock_free_queue_node_init (&entry->node, FALSE);
763 entry->methods = methods;
764 entry->buffer = buffer;
765 mono_lock_free_queue_enqueue (&prof->writer_queue, &entry->node);
769 dump_buffer (MonoProfiler *profiler, LogBuffer *buf)
774 dump_buffer (profiler, buf->next);
775 p = write_int32 (p, BUF_ID);
776 p = write_int32 (p, buf->data - buf->buf);
777 p = write_int64 (p, buf->time_base);
778 p = write_int64 (p, buf->ptr_base);
779 p = write_int64 (p, buf->obj_base);
780 p = write_int64 (p, buf->thread_id);
781 p = write_int64 (p, buf->method_base);
782 #if defined (HAVE_SYS_ZLIB)
783 if (profiler->gzfile) {
784 gzwrite (profiler->gzfile, hbuf, p - hbuf);
785 gzwrite (profiler->gzfile, buf->buf, buf->data - buf->buf);
788 fwrite (hbuf, p - hbuf, 1, profiler->file);
789 fwrite (buf->buf, buf->data - buf->buf, 1, profiler->file);
790 fflush (profiler->file);
791 #if defined (HAVE_SYS_ZLIB)
794 free_buffer (buf, buf->size);
798 process_requests (MonoProfiler *profiler)
800 if (heapshot_requested)
801 mono_gc_collect (mono_gc_max_generation ());
804 static void counters_init (MonoProfiler *profiler);
805 static void counters_sample (MonoProfiler *profiler, uint64_t timestamp);
808 runtime_initialized (MonoProfiler *profiler)
811 #ifndef DISABLE_HELPER_THREAD
812 counters_init (profiler);
813 counters_sample (profiler, 0);
815 /* ensure the main thread data and startup are available soon */
816 safe_send (profiler, ensure_logbuf (0));
820 * Can be called only at safe callback locations.
823 safe_send (MonoProfiler *profiler, LogBuffer *logbuffer)
825 int cd = logbuffer->call_depth;
827 send_buffer (profiler, TLS_GET (GPtrArray, tlsmethodlist), TLS_GET (LogBuffer, tlsbuffer));
829 TLS_SET (tlsbuffer, NULL);
830 TLS_SET (tlsmethodlist, NULL);
834 TLS_GET (LogBuffer, tlsbuffer)->call_depth = cd;
838 gc_reference (MonoObject *obj, MonoClass *klass, uintptr_t size, uintptr_t num, MonoObject **refs, uintptr_t *offsets, void *data)
841 uintptr_t last_offset = 0;
842 //const char *name = mono_class_get_name (klass);
843 LogBuffer *logbuffer = ensure_logbuf (20 + num * 8);
844 emit_byte (logbuffer, TYPE_HEAP_OBJECT | TYPE_HEAP);
845 emit_obj (logbuffer, obj);
846 emit_ptr (logbuffer, klass);
847 /* account for object alignment in the heap */
850 emit_value (logbuffer, size);
851 emit_value (logbuffer, num);
852 for (i = 0; i < num; ++i) {
853 emit_value (logbuffer, offsets [i] - last_offset);
854 last_offset = offsets [i];
855 emit_obj (logbuffer, refs [i]);
858 // printf ("obj: %p, klass: %s, refs: %d, size: %d\n", obj, name, (int)num, (int)size);
862 static unsigned int hs_mode_ms = 0;
863 static unsigned int hs_mode_gc = 0;
864 static unsigned int hs_mode_ondemand = 0;
865 static unsigned int gc_count = 0;
866 static uint64_t last_hs_time = 0;
869 heap_walk (MonoProfiler *profiler)
873 LogBuffer *logbuffer;
876 logbuffer = ensure_logbuf (10);
877 now = current_time ();
878 if (hs_mode_ms && (now - last_hs_time)/1000000 >= hs_mode_ms)
880 else if (hs_mode_gc && (gc_count % hs_mode_gc) == 0)
882 else if (hs_mode_ondemand)
883 do_walk = heapshot_requested;
884 else if (!hs_mode_ms && !hs_mode_gc && profiler->last_gc_gen_started == mono_gc_max_generation ())
889 heapshot_requested = 0;
890 emit_byte (logbuffer, TYPE_HEAP_START | TYPE_HEAP);
891 emit_time (logbuffer, now);
892 mono_gc_walk_heap (0, gc_reference, NULL);
893 logbuffer = ensure_logbuf (10);
894 now = current_time ();
895 emit_byte (logbuffer, TYPE_HEAP_END | TYPE_HEAP);
896 emit_time (logbuffer, now);
901 gc_event (MonoProfiler *profiler, MonoGCEvent ev, int generation) {
903 LogBuffer *logbuffer = ensure_logbuf (10);
904 now = current_time ();
905 ENTER_LOG (logbuffer, "gcevent");
906 emit_byte (logbuffer, TYPE_GC_EVENT | TYPE_GC);
907 emit_time (logbuffer, now);
908 emit_value (logbuffer, ev);
909 emit_value (logbuffer, generation);
910 /* to deal with nested gen1 after gen0 started */
911 if (ev == MONO_GC_EVENT_START) {
912 profiler->last_gc_gen_started = generation;
913 if (generation == mono_gc_max_generation ())
916 if (ev == MONO_GC_EVENT_PRE_START_WORLD)
917 heap_walk (profiler);
918 EXIT_LOG (logbuffer);
919 if (ev == MONO_GC_EVENT_POST_START_WORLD)
920 safe_send (profiler, logbuffer);
921 //printf ("gc event %d for generation %d\n", ev, generation);
925 gc_resize (MonoProfiler *profiler, int64_t new_size) {
927 LogBuffer *logbuffer = ensure_logbuf (10);
928 now = current_time ();
929 ENTER_LOG (logbuffer, "gcresize");
930 emit_byte (logbuffer, TYPE_GC_RESIZE | TYPE_GC);
931 emit_time (logbuffer, now);
932 emit_value (logbuffer, new_size);
933 //printf ("gc resized to %lld\n", new_size);
934 EXIT_LOG (logbuffer);
937 #define MAX_FRAMES 32
940 MonoMethod* methods [MAX_FRAMES];
941 int32_t il_offsets [MAX_FRAMES];
942 int32_t native_offsets [MAX_FRAMES];
944 static int num_frames = MAX_FRAMES;
947 walk_stack (MonoMethod *method, int32_t native_offset, int32_t il_offset, mono_bool managed, void* data)
949 FrameData *frame = data;
950 if (method && frame->count < num_frames) {
951 frame->il_offsets [frame->count] = il_offset;
952 frame->native_offsets [frame->count] = native_offset;
953 frame->methods [frame->count++] = method;
954 //printf ("In %d %s at %d (native: %d)\n", frame->count, mono_method_get_name (method), il_offset, native_offset);
956 return frame->count == num_frames;
960 * a note about stack walks: they can cause more profiler events to fire,
961 * so we need to make sure they don't happen after we started emitting an
962 * event, hence the collect_bt/emit_bt split.
965 collect_bt (FrameData *data)
968 mono_stack_walk_no_il (walk_stack, data);
972 emit_bt (LogBuffer *logbuffer, FrameData *data)
974 /* FIXME: this is actually tons of data and we should
975 * just output it the first time and use an id the next
977 if (data->count > num_frames)
978 printf ("bad num frames: %d\n", data->count);
979 emit_value (logbuffer, 0); /* flags */
980 emit_value (logbuffer, data->count);
981 //if (*p != data.count) {
982 // printf ("bad num frames enc at %d: %d -> %d\n", count, data.count, *p); printf ("frames end: %p->%p\n", p, logbuffer->data); exit(0);}
983 while (data->count) {
984 emit_ptr (logbuffer, data->methods [--data->count]);
989 gc_alloc (MonoProfiler *prof, MonoObject *obj, MonoClass *klass)
993 int do_bt = (nocalls && runtime_inited && !notraces)? TYPE_ALLOC_BT: 0;
995 LogBuffer *logbuffer;
996 len = mono_object_get_size (obj);
997 /* account for object alignment in the heap */
1002 logbuffer = ensure_logbuf (32 + MAX_FRAMES * 8);
1003 now = current_time ();
1004 ENTER_LOG (logbuffer, "gcalloc");
1005 emit_byte (logbuffer, do_bt | TYPE_ALLOC);
1006 emit_time (logbuffer, now);
1007 emit_ptr (logbuffer, klass);
1008 emit_obj (logbuffer, obj);
1009 emit_value (logbuffer, len);
1011 emit_bt (logbuffer, &data);
1012 EXIT_LOG (logbuffer);
1013 if (logbuffer->next)
1014 safe_send (prof, logbuffer);
1015 process_requests (prof);
1016 //printf ("gc alloc %s at %p\n", mono_class_get_name (klass), obj);
1020 gc_moves (MonoProfiler *prof, void **objects, int num)
1024 LogBuffer *logbuffer = ensure_logbuf (10 + num * 8);
1025 now = current_time ();
1026 ENTER_LOG (logbuffer, "gcmove");
1027 emit_byte (logbuffer, TYPE_GC_MOVE | TYPE_GC);
1028 emit_time (logbuffer, now);
1029 emit_value (logbuffer, num);
1030 for (i = 0; i < num; ++i)
1031 emit_obj (logbuffer, objects [i]);
1032 //printf ("gc moved %d objects\n", num/2);
1033 EXIT_LOG (logbuffer);
1037 gc_roots (MonoProfiler *prof, int num, void **objects, int *root_types, uintptr_t *extra_info)
1040 LogBuffer *logbuffer = ensure_logbuf (5 + num * 18);
1041 ENTER_LOG (logbuffer, "gcroots");
1042 emit_byte (logbuffer, TYPE_HEAP_ROOT | TYPE_HEAP);
1043 emit_value (logbuffer, num);
1044 emit_value (logbuffer, mono_gc_collection_count (mono_gc_max_generation ()));
1045 for (i = 0; i < num; ++i) {
1046 emit_obj (logbuffer, objects [i]);
1047 emit_value (logbuffer, root_types [i]);
1048 emit_value (logbuffer, extra_info [i]);
1050 EXIT_LOG (logbuffer);
1054 gc_handle (MonoProfiler *prof, int op, int type, uintptr_t handle, MonoObject *obj)
1057 LogBuffer *logbuffer = ensure_logbuf (16);
1058 now = current_time ();
1059 ENTER_LOG (logbuffer, "gchandle");
1060 if (op == MONO_PROFILER_GC_HANDLE_CREATED)
1061 emit_byte (logbuffer, TYPE_GC_HANDLE_CREATED | TYPE_GC);
1062 else if (op == MONO_PROFILER_GC_HANDLE_DESTROYED)
1063 emit_byte (logbuffer, TYPE_GC_HANDLE_DESTROYED | TYPE_GC);
1066 emit_time (logbuffer, now);
1067 emit_value (logbuffer, type);
1068 emit_value (logbuffer, handle);
1069 if (op == MONO_PROFILER_GC_HANDLE_CREATED)
1070 emit_obj (logbuffer, obj);
1071 EXIT_LOG (logbuffer);
1072 process_requests (prof);
1076 push_nesting (char *p, MonoClass *klass)
1081 nesting = mono_class_get_nesting_type (klass);
1083 p = push_nesting (p, nesting);
1087 name = mono_class_get_name (klass);
1088 nspace = mono_class_get_namespace (klass);
1091 p += strlen (nspace);
1101 type_name (MonoClass *klass)
1105 push_nesting (buf, klass);
1106 p = malloc (strlen (buf) + 1);
1112 image_loaded (MonoProfiler *prof, MonoImage *image, int result)
1117 LogBuffer *logbuffer;
1118 if (result != MONO_PROFILE_OK)
1120 name = mono_image_get_filename (image);
1121 nlen = strlen (name) + 1;
1122 logbuffer = ensure_logbuf (16 + nlen);
1123 now = current_time ();
1124 ENTER_LOG (logbuffer, "image");
1125 emit_byte (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1126 emit_time (logbuffer, now);
1127 emit_byte (logbuffer, TYPE_IMAGE);
1128 emit_ptr (logbuffer, image);
1129 emit_value (logbuffer, 0); /* flags */
1130 memcpy (logbuffer->data, name, nlen);
1131 logbuffer->data += nlen;
1132 //printf ("loaded image %p (%s)\n", image, name);
1133 EXIT_LOG (logbuffer);
1134 if (logbuffer->next)
1135 safe_send (prof, logbuffer);
1136 process_requests (prof);
1140 class_loaded (MonoProfiler *prof, MonoClass *klass, int result)
1146 LogBuffer *logbuffer;
1147 if (result != MONO_PROFILE_OK)
1150 name = mono_type_get_name (mono_class_get_type (klass));
1152 name = type_name (klass);
1153 nlen = strlen (name) + 1;
1154 image = mono_class_get_image (klass);
1155 logbuffer = ensure_logbuf (24 + nlen);
1156 now = current_time ();
1157 ENTER_LOG (logbuffer, "class");
1158 emit_byte (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
1159 emit_time (logbuffer, now);
1160 emit_byte (logbuffer, TYPE_CLASS);
1161 emit_ptr (logbuffer, klass);
1162 emit_ptr (logbuffer, image);
1163 emit_value (logbuffer, 0); /* flags */
1164 memcpy (logbuffer->data, name, nlen);
1165 logbuffer->data += nlen;
1166 //printf ("loaded class %p (%s)\n", klass, name);
1171 EXIT_LOG (logbuffer);
1172 if (logbuffer->next)
1173 safe_send (prof, logbuffer);
1174 process_requests (prof);
1178 method_enter (MonoProfiler *prof, MonoMethod *method)
1181 LogBuffer *logbuffer = ensure_logbuf (16);
1182 if (logbuffer->call_depth++ > max_call_depth)
1184 now = current_time ();
1185 ENTER_LOG (logbuffer, "enter");
1186 emit_byte (logbuffer, TYPE_ENTER | TYPE_METHOD);
1187 emit_time (logbuffer, now);
1188 emit_method (prof, logbuffer, mono_domain_get (), method);
1189 EXIT_LOG (logbuffer);
1190 process_requests (prof);
1194 method_leave (MonoProfiler *prof, MonoMethod *method)
1197 LogBuffer *logbuffer = ensure_logbuf (16);
1198 if (--logbuffer->call_depth > max_call_depth)
1200 now = current_time ();
1201 ENTER_LOG (logbuffer, "leave");
1202 emit_byte (logbuffer, TYPE_LEAVE | TYPE_METHOD);
1203 emit_time (logbuffer, now);
1204 emit_method (prof, logbuffer, mono_domain_get (), method);
1205 EXIT_LOG (logbuffer);
1206 if (logbuffer->next)
1207 safe_send (prof, logbuffer);
1208 process_requests (prof);
1212 method_exc_leave (MonoProfiler *prof, MonoMethod *method)
1215 LogBuffer *logbuffer;
1218 logbuffer = ensure_logbuf (16);
1219 if (--logbuffer->call_depth > max_call_depth)
1221 now = current_time ();
1222 ENTER_LOG (logbuffer, "eleave");
1223 emit_byte (logbuffer, TYPE_EXC_LEAVE | TYPE_METHOD);
1224 emit_time (logbuffer, now);
1225 emit_method (prof, logbuffer, mono_domain_get (), method);
1226 EXIT_LOG (logbuffer);
1227 process_requests (prof);
1231 method_jitted (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *ji, int result)
1233 if (result != MONO_PROFILE_OK)
1236 register_method_local (prof, NULL, method, ji);
1240 code_buffer_new (MonoProfiler *prof, void *buffer, int size, MonoProfilerCodeBufferType type, void *data)
1245 LogBuffer *logbuffer;
1246 if (type == MONO_PROFILER_CODE_BUFFER_SPECIFIC_TRAMPOLINE) {
1248 nlen = strlen (name) + 1;
1253 logbuffer = ensure_logbuf (32 + nlen);
1254 now = current_time ();
1255 ENTER_LOG (logbuffer, "code buffer");
1256 emit_byte (logbuffer, TYPE_JITHELPER | TYPE_RUNTIME);
1257 emit_time (logbuffer, now);
1258 emit_value (logbuffer, type);
1259 emit_ptr (logbuffer, buffer);
1260 emit_value (logbuffer, size);
1262 memcpy (logbuffer->data, name, nlen);
1263 logbuffer->data += nlen;
1265 EXIT_LOG (logbuffer);
1266 process_requests (prof);
1270 throw_exc (MonoProfiler *prof, MonoObject *object)
1272 int do_bt = (nocalls && runtime_inited && !notraces)? TYPE_EXCEPTION_BT: 0;
1275 LogBuffer *logbuffer;
1278 logbuffer = ensure_logbuf (16 + MAX_FRAMES * 8);
1279 now = current_time ();
1280 ENTER_LOG (logbuffer, "throw");
1281 emit_byte (logbuffer, do_bt | TYPE_EXCEPTION);
1282 emit_time (logbuffer, now);
1283 emit_obj (logbuffer, object);
1285 emit_bt (logbuffer, &data);
1286 EXIT_LOG (logbuffer);
1287 process_requests (prof);
1291 clause_exc (MonoProfiler *prof, MonoMethod *method, int clause_type, int clause_num)
1294 LogBuffer *logbuffer = ensure_logbuf (16);
1295 now = current_time ();
1296 ENTER_LOG (logbuffer, "clause");
1297 emit_byte (logbuffer, TYPE_EXCEPTION | TYPE_CLAUSE);
1298 emit_time (logbuffer, now);
1299 emit_value (logbuffer, clause_type);
1300 emit_value (logbuffer, clause_num);
1301 emit_method (prof, logbuffer, mono_domain_get (), method);
1302 EXIT_LOG (logbuffer);
1306 monitor_event (MonoProfiler *profiler, MonoObject *object, MonoProfilerMonitorEvent event)
1308 int do_bt = (nocalls && runtime_inited && !notraces && event == MONO_PROFILER_MONITOR_CONTENTION)? TYPE_MONITOR_BT: 0;
1311 LogBuffer *logbuffer;
1314 logbuffer = ensure_logbuf (16 + MAX_FRAMES * 8);
1315 now = current_time ();
1316 ENTER_LOG (logbuffer, "monitor");
1317 emit_byte (logbuffer, (event << 4) | do_bt | TYPE_MONITOR);
1318 emit_time (logbuffer, now);
1319 emit_obj (logbuffer, object);
1321 emit_bt (logbuffer, &data);
1322 EXIT_LOG (logbuffer);
1323 process_requests (profiler);
1327 thread_start (MonoProfiler *prof, uintptr_t tid)
1329 //printf ("thread start %p\n", (void*)tid);
1334 thread_end (MonoProfiler *prof, uintptr_t tid)
1336 if (TLS_GET (LogBuffer, tlsbuffer))
1337 send_buffer (prof, TLS_GET (GPtrArray, tlsmethodlist), TLS_GET (LogBuffer, tlsbuffer));
1339 TLS_SET (tlsbuffer, NULL);
1340 TLS_SET (tlsmethodlist, NULL);
1344 thread_name (MonoProfiler *prof, uintptr_t tid, const char *name)
1346 int len = strlen (name) + 1;
1348 LogBuffer *logbuffer;
1349 logbuffer = ensure_logbuf (10 + len);
1350 now = current_time ();
1351 ENTER_LOG (logbuffer, "tname");
1352 emit_byte (logbuffer, TYPE_METADATA);
1353 emit_time (logbuffer, now);
1354 emit_byte (logbuffer, TYPE_THREAD);
1355 emit_ptr (logbuffer, (void*)tid);
1356 emit_value (logbuffer, 0); /* flags */
1357 memcpy (logbuffer->data, name, len);
1358 logbuffer->data += len;
1359 EXIT_LOG (logbuffer);
1371 AsyncFrameInfo *data;
1375 async_walk_stack (MonoMethod *method, MonoDomain *domain, void *base_address, int offset, void *data)
1377 AsyncFrameData *frame = data;
1378 if (frame->count < num_frames) {
1379 frame->data [frame->count].method = method;
1380 frame->data [frame->count].domain = domain;
1381 frame->data [frame->count].base_address = base_address;
1382 frame->data [frame->count].offset = offset;
1383 // printf ("In %d at %p (dom %p) (native: %p)\n", frame->count, method, domain, base_address);
1386 return frame->count == num_frames;
1390 (type | frame count), tid, time, ip, [method, domain, base address, offset] * frames
1392 #define SAMPLE_EVENT_SIZE_IN_SLOTS(FRAMES) (4 + (FRAMES) * 4)
1395 mono_sample_hit (MonoProfiler *profiler, unsigned char *ip, void *context)
1398 AsyncFrameInfo frames [num_frames];
1399 AsyncFrameData bt_data = { 0, &frames [0]};
1401 uintptr_t *data, *new_data, *old_data;
1407 now = current_time ();
1409 mono_stack_walk_async_safe (&async_walk_stack, context, &bt_data);
1411 elapsed = (now - profiler->startup_time) / 10000;
1415 snprintf (buf, sizeof (buf), "hit at %p in thread %p after %llu ms\n", ip, (void*)thread_id (), (unsigned long long int)elapsed/100);
1417 ign_res (write (2, buf, len));
1419 sbuf = profiler->stat_buffers;
1422 /* flush the buffer at 1 second intervals */
1423 if (sbuf->data > sbuf->buf && (elapsed - sbuf->buf [2]) > 100000) {
1426 /* overflow: 400 slots is a big enough number to reduce the chance of losing this event if many
1427 * threads hit this same spot at the same time
1429 if (timedout || (sbuf->data + 400 >= sbuf->data_end)) {
1430 StatBuffer *oldsb, *foundsb;
1431 sbuf = create_stat_buffer ();
1433 oldsb = profiler->stat_buffers;
1435 foundsb = InterlockedCompareExchangePointer ((void * volatile*)&profiler->stat_buffers, sbuf, oldsb);
1436 } while (foundsb != oldsb);
1438 ign_res (write (2, "overflow\n", 9));
1439 /* notify the helper thread */
1440 if (sbuf->next->next) {
1442 ign_res (write (profiler->pipes [1], &c, 1));
1444 ign_res (write (2, "notify\n", 7));
1448 old_data = sbuf->data;
1449 new_data = old_data + SAMPLE_EVENT_SIZE_IN_SLOTS (bt_data.count);
1450 data = InterlockedCompareExchangePointer ((void * volatile*)&sbuf->data, new_data, old_data);
1451 } while (data != old_data);
1452 if (old_data >= sbuf->data_end)
1453 return; /* lost event */
1454 old_data [0] = 1 | (sample_type << 16) | (bt_data.count << 8);
1455 old_data [1] = thread_id ();
1456 old_data [2] = elapsed;
1457 old_data [3] = (uintptr_t)ip;
1458 for (i = 0; i < bt_data.count; ++i) {
1459 old_data [4 + 4 * i + 0] = (uintptr_t)frames [i].method;
1460 old_data [4 + 4 * i + 1] = (uintptr_t)frames [i].domain;
1461 old_data [4 + 4 * i + 2] = (uintptr_t)frames [i].base_address;
1462 old_data [4 + 4 * i + 3] = (uintptr_t)frames [i].offset;
1466 static uintptr_t *code_pages = 0;
1467 static int num_code_pages = 0;
1468 static int size_code_pages = 0;
1469 #define CPAGE_SHIFT (9)
1470 #define CPAGE_SIZE (1 << CPAGE_SHIFT)
1471 #define CPAGE_MASK (~(CPAGE_SIZE - 1))
1472 #define CPAGE_ADDR(p) ((p) & CPAGE_MASK)
1475 add_code_page (uintptr_t *hash, uintptr_t hsize, uintptr_t page)
1478 uintptr_t start_pos;
1479 start_pos = (page >> CPAGE_SHIFT) % hsize;
1482 if (hash [i] && CPAGE_ADDR (hash [i]) == CPAGE_ADDR (page)) {
1484 } else if (!hash [i]) {
1491 } while (i != start_pos);
1492 /* should not happen */
1493 printf ("failed code page store\n");
1498 add_code_pointer (uintptr_t ip)
1501 if (num_code_pages * 2 >= size_code_pages) {
1503 uintptr_t old_size = size_code_pages;
1504 size_code_pages *= 2;
1505 if (size_code_pages == 0)
1506 size_code_pages = 16;
1507 n = calloc (sizeof (uintptr_t) * size_code_pages, 1);
1508 for (i = 0; i < old_size; ++i) {
1510 add_code_page (n, size_code_pages, code_pages [i]);
1516 num_code_pages += add_code_page (code_pages, size_code_pages, ip & CPAGE_MASK);
1519 #if defined(HAVE_DL_ITERATE_PHDR) && defined(ELFMAG0)
1521 dump_ubin (const char *filename, uintptr_t load_addr, uint64_t offset, uintptr_t size)
1524 LogBuffer *logbuffer;
1526 len = strlen (filename) + 1;
1527 now = current_time ();
1528 logbuffer = ensure_logbuf (20 + len);
1529 emit_byte (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_UBIN);
1530 emit_time (logbuffer, now);
1531 emit_svalue (logbuffer, load_addr);
1532 emit_uvalue (logbuffer, offset);
1533 emit_uvalue (logbuffer, size);
1534 memcpy (logbuffer->data, filename, len);
1535 logbuffer->data += len;
1540 dump_usym (const char *name, uintptr_t value, uintptr_t size)
1542 LogBuffer *logbuffer;
1544 len = strlen (name) + 1;
1545 logbuffer = ensure_logbuf (20 + len);
1546 emit_byte (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_USYM);
1547 emit_ptr (logbuffer, (void*)value);
1548 emit_value (logbuffer, size);
1549 memcpy (logbuffer->data, name, len);
1550 logbuffer->data += len;
1555 #if SIZEOF_VOID_P == 4
1556 #define ELF_WSIZE 32
1558 #define ELF_WSIZE 64
1561 #define ElfW(type) _ElfW (Elf, ELF_WSIZE, type)
1562 #define _ElfW(e,w,t) _ElfW_1 (e, w, _##t)
1563 #define _ElfW_1(e,w,t) e##w##t
1567 dump_elf_symbols (ElfW(Sym) *symbols, int num_symbols, const char *strtab, void *load_addr)
1570 for (i = 0; i < num_symbols; ++i) {
1572 sym = strtab + symbols [i].st_name;
1573 if (!symbols [i].st_name || !symbols [i].st_size || (symbols [i].st_info & 0xf) != STT_FUNC)
1575 //printf ("symbol %s at %d\n", sym, symbols [i].st_value);
1576 dump_usym (sym, (uintptr_t)load_addr + symbols [i].st_value, symbols [i].st_size);
1581 read_elf_symbols (MonoProfiler *prof, const char *filename, void *load_addr)
1588 ElfW(Shdr) *sheader;
1589 ElfW(Shdr) *shstrtabh;
1590 ElfW(Shdr) *symtabh = NULL;
1591 ElfW(Shdr) *strtabh = NULL;
1592 ElfW(Sym) *symbols = NULL;
1596 fd = open (filename, O_RDONLY);
1599 if (fstat (fd, &statb) != 0) {
1603 file_size = statb.st_size;
1604 data = mmap (NULL, file_size, PROT_READ, MAP_PRIVATE, fd, 0);
1606 if (data == MAP_FAILED)
1609 if (header->e_ident [EI_MAG0] != ELFMAG0 ||
1610 header->e_ident [EI_MAG1] != ELFMAG1 ||
1611 header->e_ident [EI_MAG2] != ELFMAG2 ||
1612 header->e_ident [EI_MAG3] != ELFMAG3 ) {
1613 munmap (data, file_size);
1616 sheader = (void*)((char*)data + header->e_shoff);
1617 shstrtabh = (void*)((char*)sheader + (header->e_shentsize * header->e_shstrndx));
1618 strtab = (const char*)data + shstrtabh->sh_offset;
1619 for (i = 0; i < header->e_shnum; ++i) {
1620 //printf ("section header: %d\n", sheader->sh_type);
1621 if (sheader->sh_type == SHT_SYMTAB) {
1623 strtabh = (void*)((char*)data + header->e_shoff + sheader->sh_link * header->e_shentsize);
1624 /*printf ("symtab section header: %d, .strstr: %d\n", i, sheader->sh_link);*/
1627 sheader = (void*)((char*)sheader + header->e_shentsize);
1629 if (!symtabh || !strtabh) {
1630 munmap (data, file_size);
1633 strtab = (const char*)data + strtabh->sh_offset;
1634 num_symbols = symtabh->sh_size / symtabh->sh_entsize;
1635 symbols = (void*)((char*)data + symtabh->sh_offset);
1636 dump_elf_symbols (symbols, num_symbols, strtab, load_addr);
1637 munmap (data, file_size);
1642 #if defined(HAVE_DL_ITERATE_PHDR) && defined(ELFMAG0)
1644 elf_dl_callback (struct dl_phdr_info *info, size_t size, void *data)
1646 MonoProfiler *prof = data;
1648 const char *filename;
1650 char *a = (void*)info->dlpi_addr;
1652 ElfW(Dyn) *dyn = NULL;
1653 ElfW(Sym) *symtab = NULL;
1654 ElfW(Word) *hash_table = NULL;
1655 ElfW(Ehdr) *header = NULL;
1656 const char* strtab = NULL;
1657 for (obj = prof->binary_objects; obj; obj = obj->next) {
1661 filename = info->dlpi_name;
1664 if (!info->dlpi_addr && !filename [0]) {
1665 int l = readlink ("/proc/self/exe", buf, sizeof (buf) - 1);
1671 obj = calloc (sizeof (BinaryObject), 1);
1672 obj->addr = (void*)info->dlpi_addr;
1673 obj->name = pstrdup (filename);
1674 obj->next = prof->binary_objects;
1675 prof->binary_objects = obj;
1676 //printf ("loaded file: %s at %p, segments: %d\n", filename, (void*)info->dlpi_addr, info->dlpi_phnum);
1678 for (i = 0; i < info->dlpi_phnum; ++i) {
1679 //printf ("segment type %d file offset: %d, size: %d\n", info->dlpi_phdr[i].p_type, info->dlpi_phdr[i].p_offset, info->dlpi_phdr[i].p_memsz);
1680 if (info->dlpi_phdr[i].p_type == PT_LOAD && !header) {
1681 header = (ElfW(Ehdr)*)(info->dlpi_addr + info->dlpi_phdr[i].p_vaddr);
1682 if (header->e_ident [EI_MAG0] != ELFMAG0 ||
1683 header->e_ident [EI_MAG1] != ELFMAG1 ||
1684 header->e_ident [EI_MAG2] != ELFMAG2 ||
1685 header->e_ident [EI_MAG3] != ELFMAG3 ) {
1688 dump_ubin (filename, info->dlpi_addr + info->dlpi_phdr[i].p_vaddr, info->dlpi_phdr[i].p_offset, info->dlpi_phdr[i].p_memsz);
1689 } else if (info->dlpi_phdr[i].p_type == PT_DYNAMIC) {
1690 dyn = (ElfW(Dyn) *)(info->dlpi_addr + info->dlpi_phdr[i].p_vaddr);
1693 if (read_elf_symbols (prof, filename, (void*)info->dlpi_addr))
1695 if (!info->dlpi_name || !info->dlpi_name[0])
1699 for (i = 0; dyn [i].d_tag != DT_NULL; ++i) {
1700 if (dyn [i].d_tag == DT_SYMTAB) {
1701 if (symtab && do_debug)
1702 printf ("multiple symtabs: %d\n", i);
1703 symtab = (ElfW(Sym) *)(a + dyn [i].d_un.d_ptr);
1704 } else if (dyn [i].d_tag == DT_HASH) {
1705 hash_table = (ElfW(Word) *)(a + dyn [i].d_un.d_ptr);
1706 } else if (dyn [i].d_tag == DT_STRTAB) {
1707 strtab = (const char*)(a + dyn [i].d_un.d_ptr);
1712 num_sym = hash_table [1];
1713 dump_elf_symbols (symtab, num_sym, strtab, (void*)info->dlpi_addr);
1718 load_binaries (MonoProfiler *prof)
1720 dl_iterate_phdr (elf_dl_callback, prof);
1725 load_binaries (MonoProfiler *prof)
1732 symbol_for (uintptr_t code)
1735 void *ip = (void*)code;
1737 if (dladdr (ip, &di)) {
1739 return di.dli_sname;
1742 names = backtrace_symbols (&ip, 1);
1744 const char* p = names [0];
1755 dump_unmanaged_coderefs (MonoProfiler *prof)
1758 const char* last_symbol;
1759 uintptr_t addr, page_end;
1761 if (load_binaries (prof))
1763 for (i = 0; i < size_code_pages; ++i) {
1765 if (!code_pages [i] || code_pages [i] & 1)
1768 addr = CPAGE_ADDR (code_pages [i]);
1769 page_end = addr + CPAGE_SIZE;
1770 code_pages [i] |= 1;
1771 /* we dump the symbols for the whole page */
1772 for (; addr < page_end; addr += 16) {
1773 sym = symbol_for (addr);
1774 if (sym && sym == last_symbol)
1779 dump_usym (sym, addr, 0); /* let's not guess the size */
1780 //printf ("found symbol at %p: %s\n", (void*)addr, sym);
1786 dump_sample_hits (MonoProfiler *prof, StatBuffer *sbuf)
1789 LogBuffer *logbuffer;
1793 dump_sample_hits (prof, sbuf->next);
1794 free_buffer (sbuf->next, sbuf->next->size);
1797 for (sample = sbuf->buf; sample < sbuf->data;) {
1799 int count = sample [0] & 0xff;
1800 int mbt_count = (sample [0] & 0xff00) >> 8;
1801 int type = sample [0] >> 16;
1802 uintptr_t *managed_sample_base = sample + count + 3;
1804 if (sample + SAMPLE_EVENT_SIZE_IN_SLOTS (mbt_count) > sbuf->data)
1807 for (i = 0; i < mbt_count; ++i) {
1808 MonoMethod *method = (MonoMethod*)managed_sample_base [i * 4 + 0];
1809 MonoDomain *domain = (MonoDomain*)managed_sample_base [i * 4 + 1];
1810 void *address = (void*)managed_sample_base [i * 4 + 2];
1813 MonoJitInfo *ji = mono_jit_info_table_find (domain, address);
1816 managed_sample_base [i * 4 + 0] = (uintptr_t)mono_jit_info_get_method (ji);
1819 logbuffer = ensure_logbuf (20 + count * 8);
1820 emit_byte (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_HIT);
1821 emit_value (logbuffer, type);
1822 emit_uvalue (logbuffer, prof->startup_time + (uint64_t)sample [2] * (uint64_t)10000);
1823 emit_value (logbuffer, count);
1824 for (i = 0; i < count; ++i) {
1825 emit_ptr (logbuffer, (void*)sample [i + 3]);
1826 add_code_pointer (sample [i + 3]);
1829 sample += count + 3;
1830 /* new in data version 6 */
1831 emit_uvalue (logbuffer, mbt_count);
1832 for (i = 0; i < mbt_count; ++i) {
1833 MonoMethod *method = (MonoMethod *) sample [i * 4 + 0];
1834 MonoDomain *domain = (MonoDomain *) sample [i * 4 + 1];
1835 uintptr_t native_offset = sample [i * 4 + 3];
1837 emit_method (prof, logbuffer, domain, method);
1838 emit_svalue (logbuffer, 0); /* il offset will always be 0 from now on */
1839 emit_svalue (logbuffer, native_offset);
1841 sample += 4 * mbt_count;
1843 dump_unmanaged_coderefs (prof);
1849 mono_cpu_count (void)
1852 #ifdef PLATFORM_ANDROID
1853 /* Android tries really hard to save power by powering off CPUs on SMP phones which
1854 * means the normal way to query cpu count returns a wrong value with userspace API.
1855 * Instead we use /sys entries to query the actual hardware CPU count.
1857 char buffer[8] = {'\0'};
1858 int present = open ("/sys/devices/system/cpu/present", O_RDONLY);
1859 /* Format of the /sys entry is a cpulist of indexes which in the case
1860 * of present is always of the form "0-(n-1)" when there is more than
1861 * 1 core, n being the number of CPU cores in the system. Otherwise
1862 * the value is simply 0
1864 if (present != -1 && read (present, (char*)buffer, sizeof (buffer)) > 3)
1865 count = strtol (((char*)buffer) + 2, NULL, 10);
1871 #ifdef _SC_NPROCESSORS_ONLN
1872 count = sysconf (_SC_NPROCESSORS_ONLN);
1879 size_t len = sizeof (int);
1882 if (sysctl (mib, 2, &count, &len, NULL, 0) == 0)
1889 GetSystemInfo (&info);
1890 return info.dwNumberOfProcessors;
1899 unsigned int prev_pos;
1901 struct perf_event_mmap_page *page_desc;
1904 static PerfData *perf_data = NULL;
1905 static int num_perf;
1906 #define PERF_PAGES_SHIFT 4
1907 static int num_pages = 1 << PERF_PAGES_SHIFT;
1908 static unsigned int mmap_mask;
1911 struct perf_event_header h;
1921 perf_event_syscall (struct perf_event_attr *attr, pid_t pid, int cpu, int group_fd, unsigned long flags)
1923 attr->size = PERF_ATTR_SIZE_VER0;
1924 //printf ("perf attr size: %d\n", attr->size);
1925 #if defined(__x86_64__)
1926 return syscall(/*__NR_perf_event_open*/ 298, attr, pid, cpu, group_fd, flags);
1927 #elif defined(__i386__)
1928 return syscall(/*__NR_perf_event_open*/ 336, attr, pid, cpu, group_fd, flags);
1929 #elif defined(__arm__) || defined (__aarch64__)
1930 return syscall(/*__NR_perf_event_open*/ 364, attr, pid, cpu, group_fd, flags);
1937 setup_perf_map (PerfData *perf)
1939 perf->mmap_base = mmap (NULL, (num_pages + 1) * getpagesize (), PROT_READ|PROT_WRITE, MAP_SHARED, perf->perf_fd, 0);
1940 if (perf->mmap_base == MAP_FAILED) {
1942 printf ("failed mmap\n");
1945 perf->page_desc = perf->mmap_base;
1947 printf ("mmap version: %d\n", perf->page_desc->version);
1952 dump_perf_hits (MonoProfiler *prof, void *buf, int size)
1954 LogBuffer *logbuffer;
1955 void *end = (char*)buf + size;
1957 int pid = getpid ();
1963 if (pid != s->pid) {
1965 printf ("event for different pid: %d\n", s->pid);
1966 buf = (char*)buf + s->h.size;
1969 /*ip = (void*)s->ip;
1970 printf ("sample: %d, size: %d, ip: %p (%s), timestamp: %llu, nframes: %llu\n",
1971 s->h.type, s->h.size, ip, symbol_for (ip), s->timestamp, s->nframes);*/
1972 logbuffer = ensure_logbuf (20 + s->nframes * 8);
1973 emit_byte (logbuffer, TYPE_SAMPLE | TYPE_SAMPLE_HIT);
1974 emit_value (logbuffer, sample_type);
1975 emit_uvalue (logbuffer, s->timestamp - prof->startup_time);
1976 emit_value (logbuffer, 1); /* count */
1977 emit_ptr (logbuffer, (void*)(uintptr_t)s->ip);
1978 /* no support here yet for the managed backtrace */
1979 emit_uvalue (logbuffer, 0);
1980 add_code_pointer (s->ip);
1981 buf = (char*)buf + s->h.size;
1985 printf ("dumped %d samples\n", samples);
1986 dump_unmanaged_coderefs (prof);
1989 /* read events from the ring buffer */
1991 read_perf_mmap (MonoProfiler* prof, int cpu)
1993 PerfData *perf = perf_data + cpu;
1995 unsigned char *data = (unsigned char*)perf->mmap_base + getpagesize ();
1996 unsigned int head = perf->page_desc->data_head;
2000 mono_memory_read_barrier ();
2002 old = perf->prev_pos;
2006 printf ("lost mmap events: old: %d, head: %d\n", old, head);
2010 if ((old & mmap_mask) + size != (head & mmap_mask)) {
2011 buf = data + (old & mmap_mask);
2012 size = mmap_mask + 1 - (old & mmap_mask);
2014 /* size bytes at buf */
2016 printf ("found1 bytes of events: %d\n", size);
2017 dump_perf_hits (prof, buf, size);
2019 buf = data + (old & mmap_mask);
2021 /* size bytes at buf */
2023 printf ("found bytes of events: %d\n", size);
2024 dump_perf_hits (prof, buf, size);
2026 perf->prev_pos = old;
2027 perf->page_desc->data_tail = old;
2032 setup_perf_event_for_cpu (PerfData *perf, int cpu)
2034 struct perf_event_attr attr;
2035 memset (&attr, 0, sizeof (attr));
2036 attr.type = PERF_TYPE_HARDWARE;
2037 switch (sample_type) {
2038 case SAMPLE_CYCLES: attr.config = PERF_COUNT_HW_CPU_CYCLES; break;
2039 case SAMPLE_INSTRUCTIONS: attr.config = PERF_COUNT_HW_INSTRUCTIONS; break;
2040 case SAMPLE_CACHE_MISSES: attr.config = PERF_COUNT_HW_CACHE_MISSES; break;
2041 case SAMPLE_CACHE_REFS: attr.config = PERF_COUNT_HW_CACHE_REFERENCES; break;
2042 case SAMPLE_BRANCHES: attr.config = PERF_COUNT_HW_BRANCH_INSTRUCTIONS; break;
2043 case SAMPLE_BRANCH_MISSES: attr.config = PERF_COUNT_HW_BRANCH_MISSES; break;
2044 default: attr.config = PERF_COUNT_HW_CPU_CYCLES; break;
2046 attr.sample_type = PERF_SAMPLE_IP | PERF_SAMPLE_TID | PERF_SAMPLE_PERIOD | PERF_SAMPLE_TIME;
2047 // attr.sample_type |= PERF_SAMPLE_CALLCHAIN;
2048 attr.read_format = PERF_FORMAT_TOTAL_TIME_ENABLED | PERF_FORMAT_TOTAL_TIME_RUNNING | PERF_FORMAT_ID;
2051 attr.sample_freq = sample_freq;
2053 perf->perf_fd = perf_event_syscall (&attr, getpid (), cpu, -1, 0);
2055 printf ("perf fd: %d, freq: %d, event: %llu\n", perf->perf_fd, sample_freq, attr.config);
2056 if (perf->perf_fd < 0) {
2057 if (perf->perf_fd == -EPERM) {
2058 fprintf (stderr, "Perf syscall denied, do \"echo 1 > /proc/sys/kernel/perf_event_paranoid\" as root to enable.\n");
2061 perror ("open perf event");
2065 if (!setup_perf_map (perf)) {
2066 close (perf->perf_fd);
2074 setup_perf_event (void)
2077 mmap_mask = num_pages * getpagesize () - 1;
2078 num_perf = mono_cpu_count ();
2079 perf_data = calloc (num_perf, sizeof (PerfData));
2080 for (i = 0; i < num_perf; ++i) {
2081 count += setup_perf_event_for_cpu (perf_data + i, i);
2090 #endif /* USE_PERF_EVENTS */
2092 #ifndef DISABLE_HELPER_THREAD
2094 typedef struct MonoCounterAgent {
2095 MonoCounter *counter;
2096 // MonoCounterAgent specific data :
2101 struct MonoCounterAgent *next;
2104 static MonoCounterAgent* counters;
2105 static gboolean counters_initialized = FALSE;
2106 static int counters_index = 1;
2107 static mono_mutex_t counters_mutex;
2110 counters_add_agent (MonoCounter *counter)
2112 MonoCounterAgent *agent, *item;
2114 if (!counters_initialized)
2117 mono_mutex_lock (&counters_mutex);
2119 for (agent = counters; agent; agent = agent->next) {
2120 if (agent->counter == counter) {
2121 agent->value_size = 0;
2123 free (agent->value);
2124 agent->value = NULL;
2126 mono_mutex_unlock (&counters_mutex);
2131 agent = malloc (sizeof (MonoCounterAgent));
2132 agent->counter = counter;
2133 agent->value = NULL;
2134 agent->value_size = 0;
2135 agent->index = counters_index++;
2148 mono_mutex_unlock (&counters_mutex);
2152 counters_init_foreach_callback (MonoCounter *counter, gpointer data)
2154 counters_add_agent (counter);
2159 counters_init (MonoProfiler *profiler)
2161 assert (!counters_initialized);
2163 mono_mutex_init (&counters_mutex);
2165 counters_initialized = TRUE;
2167 mono_counters_on_register (&counters_add_agent);
2168 mono_counters_foreach (counters_init_foreach_callback, NULL);
2172 counters_emit (MonoProfiler *profiler)
2174 MonoCounterAgent *agent;
2175 LogBuffer *logbuffer;
2176 int size = 1 + 5, len = 0;
2178 if (!counters_initialized)
2181 mono_mutex_lock (&counters_mutex);
2183 for (agent = counters; agent; agent = agent->next) {
2187 size += strlen (mono_counter_get_name (agent->counter)) + 1 + 5 * 5;
2192 mono_mutex_unlock (&counters_mutex);
2196 logbuffer = ensure_logbuf (size);
2198 ENTER_LOG (logbuffer, "counters");
2199 emit_byte (logbuffer, TYPE_SAMPLE_COUNTERS_DESC | TYPE_SAMPLE);
2200 emit_value (logbuffer, len);
2201 for (agent = counters; agent; agent = agent->next) {
2207 name = mono_counter_get_name (agent->counter);
2208 emit_value (logbuffer, mono_counter_get_section (agent->counter));
2209 emit_string (logbuffer, name, strlen (name) + 1);
2210 emit_value (logbuffer, mono_counter_get_type (agent->counter));
2211 emit_value (logbuffer, mono_counter_get_unit (agent->counter));
2212 emit_value (logbuffer, mono_counter_get_variance (agent->counter));
2213 emit_value (logbuffer, agent->index);
2217 EXIT_LOG (logbuffer);
2219 safe_send (profiler, ensure_logbuf (0));
2221 mono_mutex_unlock (&counters_mutex);
2225 counters_sample (MonoProfiler *profiler, uint64_t timestamp)
2227 MonoCounterAgent *agent;
2228 MonoCounter *counter;
2229 LogBuffer *logbuffer;
2235 if (!counters_initialized)
2238 counters_emit (profiler);
2241 buffer = calloc (1, buffer_size);
2243 mono_mutex_lock (&counters_mutex);
2246 for (agent = counters; agent; agent = agent->next)
2247 size += 10 * 2 + mono_counter_get_size (agent->counter);
2249 logbuffer = ensure_logbuf (size);
2251 ENTER_LOG (logbuffer, "counters");
2252 emit_byte (logbuffer, TYPE_SAMPLE_COUNTERS | TYPE_SAMPLE);
2253 emit_uvalue (logbuffer, timestamp);
2254 for (agent = counters; agent; agent = agent->next) {
2257 counter = agent->counter;
2259 size = mono_counter_get_size (counter);
2261 continue; // FIXME error
2262 } else if (size > buffer_size) {
2264 buffer = realloc (buffer, buffer_size);
2267 memset (buffer, 0, buffer_size);
2269 if (mono_counters_sample (counter, buffer, size) < 0)
2270 continue; // FIXME error
2272 type = mono_counter_get_type (counter);
2274 if (!agent->value) {
2275 agent->value = calloc (1, size);
2276 agent->value_size = size;
2278 if (type == MONO_COUNTER_STRING) {
2279 if (strcmp (agent->value, buffer) == 0)
2282 if (agent->value_size == size && memcmp (agent->value, buffer, size) == 0)
2287 emit_uvalue (logbuffer, agent->index);
2288 emit_uvalue (logbuffer, type);
2290 case MONO_COUNTER_INT:
2291 #if SIZEOF_VOID_P == 4
2292 case MONO_COUNTER_WORD:
2294 emit_svalue (logbuffer, *(int*)buffer - *(int*)agent->value);
2296 case MONO_COUNTER_UINT:
2297 emit_uvalue (logbuffer, *(guint*)buffer - *(guint*)agent->value);
2299 case MONO_COUNTER_TIME_INTERVAL:
2300 case MONO_COUNTER_LONG:
2301 #if SIZEOF_VOID_P == 8
2302 case MONO_COUNTER_WORD:
2304 emit_svalue (logbuffer, *(gint64*)buffer - *(gint64*)agent->value);
2306 case MONO_COUNTER_ULONG:
2307 emit_uvalue (logbuffer, *(guint64*)buffer - *(guint64*)agent->value);
2309 case MONO_COUNTER_DOUBLE:
2310 emit_double (logbuffer, *(double*)buffer);
2312 case MONO_COUNTER_STRING:
2314 emit_byte (logbuffer, 0);
2316 emit_byte (logbuffer, 1);
2317 emit_string (logbuffer, (char*)buffer, size);
2324 if (type == MONO_COUNTER_STRING && size > agent->value_size) {
2325 agent->value = realloc (agent->value, size);
2326 agent->value_size = size;
2330 memcpy (agent->value, buffer, size);
2334 emit_value (logbuffer, 0);
2335 EXIT_LOG (logbuffer);
2337 safe_send (profiler, ensure_logbuf (0));
2339 mono_mutex_unlock (&counters_mutex);
2342 typedef struct _PerfCounterAgent PerfCounterAgent;
2343 struct _PerfCounterAgent {
2344 PerfCounterAgent *next;
2346 char *category_name;
2355 static PerfCounterAgent *perfcounters = NULL;
2358 perfcounters_emit (MonoProfiler *profiler)
2360 PerfCounterAgent *pcagent;
2361 LogBuffer *logbuffer;
2362 int size = 1 + 5, len = 0;
2364 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
2365 if (pcagent->emitted)
2368 size += strlen (pcagent->name) + 1 + 5 * 5;
2375 logbuffer = ensure_logbuf (size);
2377 ENTER_LOG (logbuffer, "perfcounters");
2378 emit_byte (logbuffer, TYPE_SAMPLE_COUNTERS_DESC | TYPE_SAMPLE);
2379 emit_value (logbuffer, len);
2380 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
2381 if (pcagent->emitted)
2384 emit_value (logbuffer, MONO_COUNTER_PERFCOUNTERS);
2385 emit_string (logbuffer, pcagent->category_name, strlen (pcagent->category_name) + 1);
2386 emit_string (logbuffer, pcagent->name, strlen (pcagent->name) + 1);
2387 emit_value (logbuffer, MONO_COUNTER_LONG);
2388 emit_value (logbuffer, MONO_COUNTER_RAW);
2389 emit_value (logbuffer, MONO_COUNTER_VARIABLE);
2390 emit_value (logbuffer, pcagent->index);
2392 pcagent->emitted = 1;
2394 EXIT_LOG (logbuffer);
2396 safe_send (profiler, ensure_logbuf (0));
2400 perfcounters_foreach (char *category_name, char *name, unsigned char type, gint64 value, gpointer user_data)
2402 PerfCounterAgent *pcagent;
2404 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
2405 if (strcmp (pcagent->category_name, category_name) != 0 || strcmp (pcagent->name, name) != 0)
2407 if (pcagent->value == value)
2410 pcagent->value = value;
2411 pcagent->updated = 1;
2412 pcagent->deleted = 0;
2416 pcagent = g_new0 (PerfCounterAgent, 1);
2417 pcagent->next = perfcounters;
2418 pcagent->index = counters_index++;
2419 pcagent->category_name = g_strdup (category_name);
2420 pcagent->name = g_strdup (name);
2421 pcagent->type = (int) type;
2422 pcagent->value = value;
2423 pcagent->emitted = 0;
2424 pcagent->updated = 1;
2425 pcagent->deleted = 0;
2427 perfcounters = pcagent;
2433 perfcounters_sample (MonoProfiler *profiler, uint64_t timestamp)
2435 PerfCounterAgent *pcagent;
2436 LogBuffer *logbuffer;
2439 if (!counters_initialized)
2442 mono_mutex_lock (&counters_mutex);
2444 /* mark all perfcounters as deleted, foreach will unmark them as necessary */
2445 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next)
2446 pcagent->deleted = 1;
2448 mono_perfcounter_foreach (perfcounters_foreach, perfcounters);
2450 perfcounters_emit (profiler);
2454 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
2455 if (pcagent->deleted || !pcagent->updated)
2457 size += 10 * 2 + sizeof (gint64);
2460 logbuffer = ensure_logbuf (size);
2462 ENTER_LOG (logbuffer, "perfcounters");
2463 emit_byte (logbuffer, TYPE_SAMPLE_COUNTERS | TYPE_SAMPLE);
2464 emit_uvalue (logbuffer, timestamp);
2465 for (pcagent = perfcounters; pcagent; pcagent = pcagent->next) {
2466 if (pcagent->deleted || !pcagent->updated)
2468 emit_uvalue (logbuffer, pcagent->index);
2469 emit_uvalue (logbuffer, MONO_COUNTER_LONG);
2470 emit_svalue (logbuffer, pcagent->value);
2472 pcagent->updated = 0;
2475 emit_value (logbuffer, 0);
2476 EXIT_LOG (logbuffer);
2478 safe_send (profiler, ensure_logbuf (0));
2480 mono_mutex_unlock (&counters_mutex);
2484 counters_and_perfcounters_sample (MonoProfiler *prof)
2486 static uint64_t start = -1;
2490 start = current_time ();
2492 now = current_time ();
2493 counters_sample (prof, (now - start) / 1000/ 1000);
2494 perfcounters_sample (prof, (now - start) / 1000/ 1000);
2497 #endif /* DISABLE_HELPER_THREAD */
2500 log_shutdown (MonoProfiler *prof)
2505 #ifndef DISABLE_HELPER_THREAD
2506 counters_and_perfcounters_sample (prof);
2508 if (prof->command_port) {
2510 ign_res (write (prof->pipes [1], &c, 1));
2511 pthread_join (prof->helper_thread, &res);
2517 for (i = 0; i < num_perf; ++i)
2518 read_perf_mmap (prof, i);
2521 dump_sample_hits (prof, prof->stat_buffers);
2523 if (TLS_GET (LogBuffer, tlsbuffer))
2524 send_buffer (prof, TLS_GET (GPtrArray, tlsmethodlist), TLS_GET (LogBuffer, tlsbuffer));
2526 TLS_SET (tlsbuffer, NULL);
2527 TLS_SET (tlsmethodlist, NULL);
2529 InterlockedWrite (&prof->run_writer_thread, 0);
2530 pthread_join (prof->writer_thread, &res);
2532 #if defined (HAVE_SYS_ZLIB)
2534 gzclose (prof->gzfile);
2536 if (prof->pipe_output)
2537 pclose (prof->file);
2539 fclose (prof->file);
2541 mono_conc_hashtable_destroy (prof->method_table);
2542 mono_mutex_destroy (&prof->method_table_mutex);
2548 new_filename (const char* filename)
2550 time_t t = time (NULL);
2551 int pid = process_id ();
2556 int count_dates = 0;
2560 for (p = filename; *p; p++) {
2571 if (!count_dates && !count_pids)
2572 return pstrdup (filename);
2573 snprintf (pid_buf, sizeof (pid_buf), "%d", pid);
2575 snprintf (time_buf, sizeof (time_buf), "%d%02d%02d%02d%02d%02d",
2576 1900 + ts->tm_year, 1 + ts->tm_mon, ts->tm_mday, ts->tm_hour, ts->tm_min, ts->tm_sec);
2577 s_date = strlen (time_buf);
2578 s_pid = strlen (pid_buf);
2579 d = res = malloc (strlen (filename) + s_date * count_dates + s_pid * count_pids);
2580 for (p = filename; *p; p++) {
2587 strcpy (d, time_buf);
2590 } else if (*p == 'p') {
2591 strcpy (d, pid_buf);
2594 } else if (*p == '%') {
2606 //this is exposed by the JIT, but it's not meant to be a supported API for now.
2607 extern void mono_threads_attach_tools_thread (void);
2609 #ifndef DISABLE_HELPER_THREAD
2612 helper_thread (void* arg)
2614 MonoProfiler* prof = arg;
2618 MonoThread *thread = NULL;
2620 mono_threads_attach_tools_thread ();
2621 //fprintf (stderr, "Server listening\n");
2622 command_socket = -1;
2628 FD_SET (prof->server_socket, &rfds);
2629 max_fd = prof->server_socket;
2630 FD_SET (prof->pipes [0], &rfds);
2631 if (max_fd < prof->pipes [0])
2632 max_fd = prof->pipes [0];
2633 if (command_socket >= 0) {
2634 FD_SET (command_socket, &rfds);
2635 if (max_fd < command_socket)
2636 max_fd = command_socket;
2641 for ( i = 0; i < num_perf; ++i) {
2642 if (perf_data [i].perf_fd < 0)
2644 FD_SET (perf_data [i].perf_fd, &rfds);
2645 if (max_fd < perf_data [i].perf_fd)
2646 max_fd = perf_data [i].perf_fd;
2651 counters_and_perfcounters_sample (prof);
2655 len = select (max_fd + 1, &rfds, NULL, NULL, &tv);
2661 g_warning ("Error in proflog server: %s", strerror (errno));
2665 if (FD_ISSET (prof->pipes [0], &rfds)) {
2667 int r = read (prof->pipes [0], &c, 1);
2668 if (r == 1 && c == 0) {
2669 StatBuffer *sbufbase = prof->stat_buffers;
2671 if (!sbufbase->next)
2673 sbuf = sbufbase->next->next;
2674 sbufbase->next->next = NULL;
2676 fprintf (stderr, "stat buffer dump\n");
2678 dump_sample_hits (prof, sbuf);
2679 free_buffer (sbuf, sbuf->size);
2680 safe_send (prof, ensure_logbuf (0));
2684 /* time to shut down */
2686 mono_thread_detach (thread);
2688 fprintf (stderr, "helper shutdown\n");
2692 for ( i = 0; i < num_perf; ++i) {
2693 if (perf_data [i].perf_fd < 0)
2695 if (FD_ISSET (perf_data [i].perf_fd, &rfds))
2696 read_perf_mmap (prof, i);
2700 safe_send (prof, ensure_logbuf (0));
2706 for ( i = 0; i < num_perf; ++i) {
2707 if (perf_data [i].perf_fd < 0)
2709 if (FD_ISSET (perf_data [i].perf_fd, &rfds)) {
2710 read_perf_mmap (prof, i);
2711 safe_send (prof, ensure_logbuf (0));
2716 if (command_socket >= 0 && FD_ISSET (command_socket, &rfds)) {
2717 len = read (command_socket, buf, sizeof (buf) - 1);
2721 close (command_socket);
2722 command_socket = -1;
2726 if (strcmp (buf, "heapshot\n") == 0) {
2727 heapshot_requested = 1;
2728 //fprintf (stderr, "perform heapshot\n");
2729 if (runtime_inited && !thread) {
2730 thread = mono_thread_attach (mono_get_root_domain ());
2731 /*fprintf (stderr, "attached\n");*/
2734 process_requests (prof);
2735 mono_thread_detach (thread);
2741 if (!FD_ISSET (prof->server_socket, &rfds)) {
2744 command_socket = accept (prof->server_socket, NULL, NULL);
2745 if (command_socket < 0)
2747 //fprintf (stderr, "Accepted connection\n");
2753 start_helper_thread (MonoProfiler* prof)
2755 struct sockaddr_in server_address;
2758 if (pipe (prof->pipes) < 0) {
2759 fprintf (stderr, "Cannot create pipe\n");
2762 prof->server_socket = socket (PF_INET, SOCK_STREAM, 0);
2763 if (prof->server_socket < 0) {
2764 fprintf (stderr, "Cannot create server socket\n");
2767 memset (&server_address, 0, sizeof (server_address));
2768 server_address.sin_family = AF_INET;
2769 server_address.sin_addr.s_addr = INADDR_ANY;
2770 server_address.sin_port = htons (prof->command_port);
2771 if (bind (prof->server_socket, (struct sockaddr *) &server_address, sizeof (server_address)) < 0) {
2772 fprintf (stderr, "Cannot bind server socket, port: %d: %s\n", prof->command_port, strerror (errno));
2773 close (prof->server_socket);
2776 if (listen (prof->server_socket, 1) < 0) {
2777 fprintf (stderr, "Cannot listen server socket\n");
2778 close (prof->server_socket);
2781 slen = sizeof (server_address);
2782 if (getsockname (prof->server_socket, (struct sockaddr *)&server_address, &slen) == 0) {
2783 prof->command_port = ntohs (server_address.sin_port);
2784 /*fprintf (stderr, "Assigned server port: %d\n", prof->command_port);*/
2787 r = pthread_create (&prof->helper_thread, NULL, helper_thread, prof);
2789 close (prof->server_socket);
2797 writer_thread (void *arg)
2799 MonoProfiler *prof = arg;
2801 mono_threads_attach_tools_thread ();
2805 while (InterlockedRead (&prof->run_writer_thread)) {
2806 WriterQueueEntry *entry;
2808 while ((entry = (WriterQueueEntry *) mono_lock_free_queue_dequeue (&prof->writer_queue))) {
2809 LogBuffer *method_buffer = NULL;
2810 gboolean new_methods = FALSE;
2812 if (entry->methods->len)
2813 method_buffer = create_buffer ();
2816 * Encode the method events in a temporary log buffer that we
2817 * flush to disk before the main buffer, ensuring that all
2818 * methods have metadata emitted before they're referenced.
2820 for (guint i = 0; i < entry->methods->len; i++) {
2821 MethodInfo *info = g_ptr_array_index (entry->methods, i);
2823 if (mono_conc_hashtable_lookup (prof->method_table, info->method))
2829 * Other threads use this hash table to get a general
2830 * idea of whether a method has already been emitted to
2831 * the stream. Due to the way we add to this table, it
2832 * can easily happen that multiple threads queue up the
2833 * same methods, but that's OK since eventually all
2834 * methods will be in this table and the thread-local
2835 * method lists will just be empty for the rest of the
2838 mono_conc_hashtable_insert (prof->method_table, info->method, info->method);
2840 char *name = mono_method_full_name (info->method, 1);
2841 int nlen = strlen (name) + 1;
2842 uint64_t now = current_time ();
2844 method_buffer = ensure_logbuf_inner (method_buffer, 32 + nlen);
2846 emit_byte (method_buffer, TYPE_JIT | TYPE_METHOD);
2847 emit_time (method_buffer, now);
2848 emit_method_inner (method_buffer, info->method);
2849 emit_ptr (method_buffer, mono_jit_info_get_code_start (info->ji));
2850 emit_value (method_buffer, mono_jit_info_get_code_size (info->ji));
2852 memcpy (method_buffer->data, name, nlen);
2853 method_buffer->data += nlen;
2859 g_ptr_array_free (entry->methods, TRUE);
2862 dump_buffer (prof, method_buffer);
2863 else if (method_buffer)
2864 free_buffer (method_buffer, method_buffer->size);
2866 dump_buffer (prof, entry->buffer);
2876 start_writer_thread (MonoProfiler* prof)
2878 InterlockedWrite (&prof->run_writer_thread, 1);
2880 return !pthread_create (&prof->writer_thread, NULL, writer_thread, prof);
2883 static MonoProfiler*
2884 create_profiler (const char *filename)
2888 int force_delete = 0;
2889 int need_helper_thread = 0;
2890 prof = calloc (1, sizeof (MonoProfiler));
2892 prof->command_port = command_port;
2893 if (filename && *filename == '-') {
2899 filename = "|mprof-report -";
2901 filename = "output.mlpd";
2902 nf = (char*)filename;
2904 nf = new_filename (filename);
2906 int s = strlen (nf) + 32;
2907 char *p = malloc (s);
2908 snprintf (p, s, "|mprof-report '--out=%s' -", nf);
2914 prof->file = popen (nf + 1, "w");
2915 prof->pipe_output = 1;
2916 } else if (*nf == '#') {
2917 int fd = strtol (nf + 1, NULL, 10);
2918 prof->file = fdopen (fd, "a");
2922 prof->file = fopen (nf, "wb");
2925 fprintf (stderr, "Cannot create profiler output: %s\n", nf);
2928 #if defined (HAVE_SYS_ZLIB)
2930 prof->gzfile = gzdopen (fileno (prof->file), "wb");
2933 if (sample_type && !do_mono_sample)
2934 need_helper_thread = setup_perf_event ();
2936 /* FIXME: warn if different freq or sample type */
2940 if (do_mono_sample) {
2941 prof->stat_buffers = create_stat_buffer ();
2942 need_helper_thread = 1;
2944 if (do_counters && !need_helper_thread) {
2945 need_helper_thread = 1;
2947 #ifndef DISABLE_HELPER_THREAD
2948 if (hs_mode_ondemand || need_helper_thread) {
2949 if (!start_helper_thread (prof))
2950 prof->command_port = 0;
2953 if (hs_mode_ondemand)
2954 fprintf (stderr, "Ondemand heapshot unavailable on this arch.\n");
2957 mono_lock_free_queue_init (&prof->writer_queue);
2958 mono_mutex_init (&prof->method_table_mutex);
2959 prof->method_table = mono_conc_hashtable_new (&prof->method_table_mutex, NULL, NULL);
2961 start_writer_thread (prof);
2963 prof->startup_time = current_time ();
2970 printf ("Log profiler version %d.%d (format: %d)\n", LOG_VERSION_MAJOR, LOG_VERSION_MINOR, LOG_DATA_VERSION);
2971 printf ("Usage: mono --profile=log[:OPTION1[,OPTION2...]] program.exe\n");
2972 printf ("Options:\n");
2973 printf ("\thelp show this usage info\n");
2974 printf ("\t[no]alloc enable/disable recording allocation info\n");
2975 printf ("\t[no]calls enable/disable recording enter/leave method events\n");
2976 printf ("\theapshot[=MODE] record heap shot info (by default at each major collection)\n");
2977 printf ("\t MODE: every XXms milliseconds, every YYgc collections, ondemand\n");
2978 printf ("\tcounters sample counters every 1s\n");
2979 printf ("\tsample[=TYPE] use statistical sampling mode (by default cycles/1000)\n");
2980 printf ("\t TYPE: cycles,instr,cacherefs,cachemiss,branches,branchmiss\n");
2981 printf ("\t TYPE can be followed by /FREQUENCY\n");
2982 printf ("\ttime=fast use a faster (but more inaccurate) timer\n");
2983 printf ("\tmaxframes=NUM collect up to NUM stack frames\n");
2984 printf ("\tcalldepth=NUM ignore method events for call chain depth bigger than NUM\n");
2985 printf ("\toutput=FILENAME write the data to file FILENAME (-FILENAME to overwrite)\n");
2986 printf ("\toutput=|PROGRAM write the data to the stdin of PROGRAM\n");
2987 printf ("\t %%t is subtituted with date and time, %%p with the pid\n");
2988 printf ("\treport create a report instead of writing the raw data to a file\n");
2989 printf ("\tzip compress the output data\n");
2990 printf ("\tport=PORTNUM use PORTNUM for the listening command server\n");
2996 match_option (const char* p, const char *opt, char **rval)
2998 int len = strlen (opt);
2999 if (strncmp (p, opt, len) == 0) {
3001 if (p [len] == '=' && p [len + 1]) {
3002 const char *opt = p + len + 1;
3003 const char *end = strchr (opt, ',');
3011 val = malloc (l + 1);
3012 memcpy (val, opt, l);
3017 if (p [len] == 0 || p [len] == ',') {
3019 return p + len + (p [len] == ',');
3037 static const SampleMode sample_modes [] = {
3038 {"cycles", SAMPLE_CYCLES},
3039 {"instr", SAMPLE_INSTRUCTIONS},
3040 {"cachemiss", SAMPLE_CACHE_MISSES},
3041 {"cacherefs", SAMPLE_CACHE_REFS},
3042 {"branches", SAMPLE_BRANCHES},
3043 {"branchmiss", SAMPLE_BRANCH_MISSES},
3048 set_sample_mode (char* val, int allow_empty)
3051 char *maybe_freq = NULL;
3053 const SampleMode *smode = sample_modes;
3054 #ifndef USE_PERF_EVENTS
3057 if (allow_empty && !val) {
3058 sample_type = SAMPLE_CYCLES;
3062 if (strcmp (val, "mono") == 0) {
3064 sample_type = SAMPLE_CYCLES;
3068 for (smode = sample_modes; smode->name; smode++) {
3069 int l = strlen (smode->name);
3070 if (strncmp (val, smode->name, l) == 0) {
3071 sample_type = smode->sample_mode;
3072 maybe_freq = val + l;
3078 if (*maybe_freq == '/') {
3079 count = strtoul (maybe_freq + 1, &end, 10);
3080 if (maybe_freq + 1 == end)
3082 sample_freq = count;
3083 } else if (*maybe_freq != 0) {
3092 set_hsmode (char* val, int allow_empty)
3096 if (allow_empty && !val)
3098 if (strcmp (val, "ondemand") == 0) {
3099 hs_mode_ondemand = 1;
3103 count = strtoul (val, &end, 10);
3106 if (strcmp (end, "ms") == 0)
3108 else if (strcmp (end, "gc") == 0)
3116 * declaration to silence the compiler: this is the entry point that
3117 * mono will load from the shared library and call.
3120 mono_profiler_startup (const char *desc);
3123 mono_profiler_startup_log (const char *desc);
3126 * this is the entry point that will be used when the profiler
3127 * is embedded inside the main executable.
3130 mono_profiler_startup_log (const char *desc)
3132 mono_profiler_startup (desc);
3136 mono_profiler_startup (const char *desc)
3139 char *filename = NULL;
3143 int calls_enabled = 0;
3144 int allocs_enabled = 0;
3145 int only_counters = 0;
3146 int events = MONO_PROFILE_GC|MONO_PROFILE_ALLOCATIONS|
3147 MONO_PROFILE_GC_MOVES|MONO_PROFILE_CLASS_EVENTS|MONO_PROFILE_THREADS|
3148 MONO_PROFILE_ENTER_LEAVE|MONO_PROFILE_JIT_COMPILATION|MONO_PROFILE_EXCEPTIONS|
3149 MONO_PROFILE_MONITOR_EVENTS|MONO_PROFILE_MODULE_EVENTS|MONO_PROFILE_GC_ROOTS;
3152 if (strncmp (p, "log", 3))
3157 for (; *p; p = opt) {
3163 if ((opt = match_option (p, "help", NULL)) != p) {
3167 if ((opt = match_option (p, "calls", NULL)) != p) {
3171 if ((opt = match_option (p, "nocalls", NULL)) != p) {
3172 events &= ~MONO_PROFILE_ENTER_LEAVE;
3176 if ((opt = match_option (p, "alloc", NULL)) != p) {
3180 if ((opt = match_option (p, "noalloc", NULL)) != p) {
3181 events &= ~MONO_PROFILE_ALLOCATIONS;
3184 if ((opt = match_option (p, "time", &val)) != p) {
3185 if (strcmp (val, "fast") == 0)
3187 else if (strcmp (val, "null") == 0)
3194 if ((opt = match_option (p, "report", NULL)) != p) {
3198 if ((opt = match_option (p, "debug", NULL)) != p) {
3202 if ((opt = match_option (p, "sampling-real", NULL)) != p) {
3203 sampling_mode = MONO_PROFILER_STAT_MODE_REAL;
3206 if ((opt = match_option (p, "sampling-process", NULL)) != p) {
3207 sampling_mode = MONO_PROFILER_STAT_MODE_PROCESS;
3210 if ((opt = match_option (p, "heapshot", &val)) != p) {
3211 events &= ~MONO_PROFILE_ALLOCATIONS;
3212 events &= ~MONO_PROFILE_ENTER_LEAVE;
3215 set_hsmode (val, 1);
3218 if ((opt = match_option (p, "sample", &val)) != p) {
3219 events &= ~MONO_PROFILE_ALLOCATIONS;
3220 events &= ~MONO_PROFILE_ENTER_LEAVE;
3222 set_sample_mode (val, 1);
3225 if ((opt = match_option (p, "hsmode", &val)) != p) {
3226 fprintf (stderr, "The hsmode profiler option is obsolete, use heapshot=MODE.\n");
3227 set_hsmode (val, 0);
3230 if ((opt = match_option (p, "zip", NULL)) != p) {
3234 if ((opt = match_option (p, "output", &val)) != p) {
3238 if ((opt = match_option (p, "port", &val)) != p) {
3240 command_port = strtoul (val, &end, 10);
3244 if ((opt = match_option (p, "maxframes", &val)) != p) {
3246 num_frames = strtoul (val, &end, 10);
3247 if (num_frames > MAX_FRAMES)
3248 num_frames = MAX_FRAMES;
3250 notraces = num_frames == 0;
3253 if ((opt = match_option (p, "calldepth", &val)) != p) {
3255 max_call_depth = strtoul (val, &end, 10);
3259 if ((opt = match_option (p, "counters", NULL)) != p) {
3263 if ((opt = match_option (p, "countersonly", NULL)) != p) {
3272 if (calls_enabled) {
3273 events |= MONO_PROFILE_ENTER_LEAVE;
3277 events |= MONO_PROFILE_ALLOCATIONS;
3280 utils_init (fast_time);
3282 prof = create_profiler (filename);
3287 mono_profiler_install (prof, MONO_PROFILER_VERSION, log_shutdown);
3288 mono_profiler_install_gc (gc_event, gc_resize);
3289 mono_profiler_install_allocation (gc_alloc);
3290 mono_profiler_install_gc_moves (gc_moves);
3291 mono_profiler_install_gc_roots (gc_handle, gc_roots);
3292 mono_profiler_install_class (NULL, class_loaded, NULL, NULL);
3293 mono_profiler_install_module (NULL, image_loaded, NULL, NULL);
3294 mono_profiler_install_thread (thread_start, thread_end);
3295 mono_profiler_install_thread_name (thread_name);
3296 mono_profiler_install_enter_leave (method_enter, method_leave);
3297 mono_profiler_install_jit_end (method_jitted);
3298 mono_profiler_install_code_buffer_new (code_buffer_new);
3299 mono_profiler_install_exception (throw_exc, method_exc_leave, clause_exc);
3300 mono_profiler_install_monitor (monitor_event);
3301 mono_profiler_install_runtime_initialized (runtime_initialized);
3304 if (do_mono_sample && sample_type == SAMPLE_CYCLES && !only_counters) {
3305 events |= MONO_PROFILE_STATISTICAL;
3306 mono_profiler_set_statistical_mode (sampling_mode, 1000000 / sample_freq);
3307 mono_profiler_install_statistical (mono_sample_hit);
3310 mono_profiler_set_events (events);
3312 TLS_INIT (tlsbuffer);
3313 TLS_INIT (tlsmethodlist);