2 * proflog.c: mono log profiler
5 * Paolo Molaro (lupus@ximian.com)
7 * Copyright 2010 Novell, Inc (http://www.novell.com)
11 #include <mono/metadata/profiler.h>
12 #include <mono/metadata/threads.h>
13 #include <mono/metadata/mono-gc.h>
14 #include <mono/metadata/debug-helpers.h>
19 #if defined(HOST_WIN32) || defined(DISABLE_SOCKETS)
20 #define DISABLE_HELPER_THREAD 1
23 #ifndef DISABLE_HELPER_THREAD
24 #include <sys/types.h>
25 #include <sys/socket.h>
26 #include <netinet/in.h>
27 #include <sys/select.h>
39 #if defined (HAVE_SYS_ZLIB)
43 #define BUFFER_SIZE (4096 * 16)
44 static int nocalls = 0;
45 static int notraces = 0;
46 static int use_zip = 0;
47 static int do_report = 0;
48 static int do_heap_shot = 0;
49 static int max_call_depth = 100;
50 static int runtime_inited = 0;
51 static int command_port = 0;
52 static int heapshot_requested = 0;
54 /* For linux compile with:
55 * gcc -fPIC -shared -o libmono-profiler-log.so proflog.c utils.c -Wall -g -lz `pkg-config --cflags --libs mono-2`
56 * gcc -o mprof-report decode.c utils.c -Wall -g -lz -lrt -lpthread `pkg-config --cflags mono-2`
58 * For osx compile with:
59 * 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
60 * gcc -m32 -o mprof-report decode.c utils.c -Wall -g -lz -lrt -lpthread `pkg-config --cflags mono-2`
63 * sudo cp mprof-report /usr/local/bin
64 * sudo cp libmono-profiler-log.so /usr/local/lib
68 typedef struct _LogBuffer LogBuffer;
74 * The file is composed by a header followed by 0 or more buffers.
75 * Each buffer contains events that happened on a thread: for a given thread
76 * buffers that appear later in the file are guaranteed to contain events
77 * that happened later in time. Buffers from separate threads could be interleaved,
79 * Buffers are not required to be aligned.
82 * [id: 4 bytes] constant value: LOG_HEADER_ID
83 * [major: 1 byte] [minor: 1 byte] major and minor version of the log profiler
84 * [format: 1 byte] version of the data format for the rest of the file
85 * [ptrsize: 1 byte] size in bytes of a pointer in the profiled program
86 * [startup time: 8 bytes] time in milliseconds since the unix epoch when the program started
87 * [timer overhead: 4 bytes] approximate overhead in nanoseconds of the timer
88 * [flags: 4 bytes] file format flags, should be 0 for now
89 * [pid: 4 bytes] pid of the profiled process
90 * [port: 2 bytes] tcp port for server if != 0
91 * [sysid: 2 bytes] operating system and architecture identifier
93 * The multiple byte integers are in little-endian format.
96 * [buffer header] [event]*
97 * Buffers have a fixed-size header followed by 0 or more bytes of event data.
98 * Timing information and other values in the event data are usually stored
99 * as uleb128 or sleb128 integers. To save space, as noted for each item below,
100 * some data is represented as a difference between the actual value and
101 * either the last value of the same type (like for timing information) or
102 * as the difference from a value stored in a buffer header.
104 * For timing information the data is stored as uleb128, since timing
105 * increases in a monotonic way in each thread: the value is the number of
106 * nanoseconds to add to the last seen timing data in a buffer. The first value
107 * in a buffer will be calculated from the time_base field in the buffer head.
109 * Object or heap sizes are stored as uleb128.
110 * Pointer differences are stored as sleb128, instead.
112 * If an unexpected value is found, the rest of the buffer should be ignored,
113 * as generally the later values need the former to be interpreted correctly.
115 * buffer header format:
116 * [bufid: 4 bytes] constant value: BUF_ID
117 * [len: 4 bytes] size of the data following the buffer header
118 * [time_base: 8 bytes] time base in nanoseconds since an unspecified epoch
119 * [ptr_base: 8 bytes] base value for pointers
120 * [obj_base: 8 bytes] base value for object addresses
121 * [thread id: 8 bytes] system-specific thread ID (pthread_t for example)
122 * [method_base: 8 bytes] base value for MonoMethod pointers
125 * [extended info: upper 4 bits] [type: lower 4 bits] [data]*
126 * The data that follows depends on type and the extended info.
127 * Type is one of the enum values in proflog.h: TYPE_ALLOC, TYPE_GC,
128 * TYPE_METADATA, TYPE_METHOD, TYPE_EXCEPTION, TYPE_MONITOR, TYPE_HEAP.
129 * The extended info bits are interpreted based on type, see
130 * each individual event description below.
131 * strings are represented as a 0-terminated utf8 sequence.
134 * [flags: uleb128] must be 0
135 * [num: uleb128] number of frames following
136 * [frame: sleb128]* num MonoMethod pointers as differences from ptr_base
140 * exinfo: flags: TYPE_ALLOC_BT
141 * [time diff: uleb128] nanoseconds since last timing
142 * [ptr: sleb128] class as a byte difference from ptr_base
143 * [obj: sleb128] object address as a byte difference from obj_base
144 * [size: uleb128] size of the object in the heap
145 * If the TYPE_ALLOC_BT flag is set, a backtrace follows.
149 * exinfo: one of TYPE_GC_EVENT, TYPE_GC_RESIZE, TYPE_GC_MOVE, TYPE_GC_HANDLE_CREATED,
150 * TYPE_GC_HANDLE_DESTROYED
151 * [time diff: uleb128] nanoseconds since last timing
152 * if exinfo == TYPE_GC_RESIZE
153 * [heap_size: uleb128] new heap size
154 * if exinfo == TYPE_GC_EVENT
155 * [event type: uleb128] GC event (MONO_GC_EVENT_* from profiler.h)
156 * [generation: uleb128] GC generation event refers to
157 * if exinfo == TYPE_GC_MOVE
158 * [num_objects: uleb128] number of object moves that follow
159 * [objaddr: sleb128]+ num_objects object pointer differences from obj_base
160 * num is always an even number: the even items are the old
161 * addresses, the odd numbers are the respective new object addresses
162 * if exinfo == TYPE_GC_HANDLE_CREATED
163 * [handle_type: uleb128] GC handle type (System.Runtime.InteropServices.GCHandleType)
164 * upper bits reserved as flags
165 * [handle: uleb128] GC handle value
166 * [objaddr: sleb128] object pointer differences from obj_base
167 * if exinfo == TYPE_GC_HANDLE_DESTROYED
168 * [handle_type: uleb128] GC handle type (System.Runtime.InteropServices.GCHandleType)
169 * upper bits reserved as flags
170 * [handle: uleb128] GC handle value
172 * type metadata format:
173 * type: TYPE_METADATA
174 * exinfo: flags: TYPE_LOAD_ERR
175 * [time diff: uleb128] nanoseconds since last timing
176 * [mtype: byte] metadata type, one of: TYPE_CLASS, TYPE_IMAGE, TYPE_ASSEMBLY, TYPE_DOMAIN,
178 * [pointer: sleb128] pointer of the metadata type depending on mtype
179 * if mtype == TYPE_CLASS
180 * [image: sleb128] MonoImage* as a pointer difference from ptr_base
181 * [flags: uleb128] must be 0
182 * [name: string] full class name
183 * if mtype == TYPE_IMAGE
184 * [flags: uleb128] must be 0
185 * [name: string] image file name
186 * if mtype == TYPE_THREAD
187 * [flags: uleb128] must be 0
188 * [name: string] thread name
190 * type method format:
192 * exinfo: one of: TYPE_LEAVE, TYPE_ENTER, TYPE_EXC_LEAVE, TYPE_JIT
193 * [time diff: uleb128] nanoseconds since last timing
194 * [method: sleb128] MonoMethod* as a pointer difference from the last such
195 * pointer or the buffer method_base
196 * if exinfo == TYPE_JIT
197 * [code address: sleb128] pointer to the native code as a diff from ptr_base
198 * [code size: uleb128] size of the generated code
199 * [name: string] full method name
201 * type exception format:
202 * type: TYPE_EXCEPTION
203 * exinfo: TYPE_EXCEPTION_BT flag and one of: TYPE_THROW, TYPE_CLAUSE
204 * [time diff: uleb128] nanoseconds since last timing
205 * if exinfo.low3bits == TYPE_CLAUSE
206 * [clause type: uleb128] finally/catch/fault/filter
207 * [clause num: uleb128] the clause number in the method header
208 * [method: sleb128] MonoMethod* as a pointer difference from the last such
209 * pointer or the buffer method_base
210 * if exinfo.low3bits == TYPE_THROW
211 * [object: sleb128] the object that was thrown as a difference from obj_base
212 * If the TYPE_EXCEPTION_BT flag is set, a backtrace follows.
214 * type monitor format:
216 * exinfo: TYPE_MONITOR_BT flag and one of: MONO_PROFILER_MONITOR_(CONTENTION|FAIL|DONE)
217 * [time diff: uleb128] nanoseconds since last timing
218 * [object: sleb128] the lock object as a difference from obj_base
219 * if exinfo.low3bits == MONO_PROFILER_MONITOR_CONTENTION
220 * If the TYPE_MONITOR_BT flag is set, a backtrace follows.
224 * exinfo: one of TYPE_HEAP_START, TYPE_HEAP_END, TYPE_HEAP_OBJECT, TYPE_HEAP_ROOT
225 * if exinfo == TYPE_HEAP_START
226 * [time diff: uleb128] nanoseconds since last timing
227 * if exinfo == TYPE_HEAP_END
228 * [time diff: uleb128] nanoseconds since last timing
229 * if exinfo == TYPE_HEAP_OBJECT
230 * [object: sleb128] the object as a difference from obj_base
231 * [class: sleb128] the object MonoClass* as a difference from ptr_base
232 * [size: uleb128] size of the object on the heap
233 * [num_refs: uleb128] number of object references
234 * if (format version > 1) each referenced objref is preceded by a
235 * uleb128 encoded offset: the first offset is from the object address
236 * and each next offset is relative to the previous one
237 * [objrefs: sleb128]+ object referenced as a difference from obj_base
238 * if exinfo == TYPE_HEAP_ROOT
239 * [num_roots: uleb128] number of root references
240 * [num_gc: uleb128] number of major gcs
241 * [object: sleb128] the object as a difference from obj_base
242 * [root_type: uleb128] the root_type
243 * [extra_info: uleb128] the extra_info value
244 * object, root_type_extra_info are repeated num_roots times
252 uintptr_t method_base;
253 uintptr_t last_method;
256 unsigned char* data_end;
261 unsigned char buf [1];
264 #define ENTER_LOG(lb,str) if ((lb)->locked) {write(2, str, strlen(str)); write(2, "\n", 1);return;} else {(lb)->locked++;}
265 #define EXIT_LOG(lb) (lb)->locked--;
267 struct _MonoProfiler {
270 #if defined (HAVE_SYS_ZLIB)
274 int last_gc_gen_started;
279 pthread_t helper_thread;
284 #define TLS_SET(x,y) TlsSetValue(x, y)
285 #define TLS_GET(x) ((LogBuffer *) TlsGetValue(x))
286 #define TLS_INIT(x) x = TlsAlloc ()
287 static int tlsbuffer;
289 #define TLS_SET(x,y) x = y
292 static __thread LogBuffer* tlsbuffer = NULL;
294 #define TLS_SET(x,y) pthread_setspecific(x, y)
295 #define TLS_GET(x) ((LogBuffer *) pthread_getspecific(x))
296 #define TLS_INIT(x) pthread_key_create(&x, NULL)
297 static pthread_key_t tlsbuffer;
301 pstrdup (const char *s)
303 int len = strlen (s) + 1;
304 char *p = malloc (len);
312 LogBuffer* buf = alloc_buffer (BUFFER_SIZE);
313 buf->size = BUFFER_SIZE;
314 buf->time_base = current_time ();
315 buf->last_time = buf->time_base;
316 buf->data_end = (unsigned char*)buf + buf->size;
317 buf->data = buf->buf;
324 LogBuffer *logbuffer;
325 if (TLS_GET (tlsbuffer))
327 logbuffer = create_buffer ();
328 TLS_SET (tlsbuffer, logbuffer);
329 logbuffer->thread_id = thread_id ();
330 //printf ("thread %p at time %llu\n", (void*)logbuffer->thread_id, logbuffer->time_base);
334 ensure_logbuf (int bytes)
336 LogBuffer *old = TLS_GET (tlsbuffer);
337 if (old && old->data + bytes + 100 < old->data_end)
339 TLS_SET (tlsbuffer, NULL);
341 TLS_GET (tlsbuffer)->next = old;
343 TLS_GET (tlsbuffer)->call_depth = old->call_depth;
344 //printf ("new logbuffer\n");
345 return TLS_GET (tlsbuffer);
349 emit_byte (LogBuffer *logbuffer, int value)
351 logbuffer->data [0] = value;
353 assert (logbuffer->data <= logbuffer->data_end);
357 emit_value (LogBuffer *logbuffer, int value)
359 encode_uleb128 (value, logbuffer->data, &logbuffer->data);
360 assert (logbuffer->data <= logbuffer->data_end);
364 emit_time (LogBuffer *logbuffer, uint64_t value)
366 uint64_t tdiff = value - logbuffer->last_time;
368 if (value < logbuffer->last_time)
369 printf ("time went backwards\n");
370 //if (tdiff > 1000000)
371 // printf ("large time offset: %llu\n", tdiff);
373 encode_uleb128 (tdiff, logbuffer->data, &logbuffer->data);
374 /*if (tdiff != decode_uleb128 (p, &p))
375 printf ("incorrect encoding: %llu\n", tdiff);*/
376 logbuffer->last_time = value;
377 assert (logbuffer->data <= logbuffer->data_end);
381 emit_svalue (LogBuffer *logbuffer, int64_t value)
383 encode_sleb128 (value, logbuffer->data, &logbuffer->data);
384 assert (logbuffer->data <= logbuffer->data_end);
388 emit_ptr (LogBuffer *logbuffer, void *ptr)
390 if (!logbuffer->ptr_base)
391 logbuffer->ptr_base = (uintptr_t)ptr;
392 emit_svalue (logbuffer, (intptr_t)ptr - logbuffer->ptr_base);
393 assert (logbuffer->data <= logbuffer->data_end);
397 emit_method (LogBuffer *logbuffer, void *method)
399 if (!logbuffer->method_base) {
400 logbuffer->method_base = (intptr_t)method;
401 logbuffer->last_method = (intptr_t)method;
403 encode_sleb128 ((intptr_t)((char*)method - (char*)logbuffer->last_method), logbuffer->data, &logbuffer->data);
404 logbuffer->last_method = (intptr_t)method;
405 assert (logbuffer->data <= logbuffer->data_end);
409 emit_obj (LogBuffer *logbuffer, void *ptr)
411 if (!logbuffer->obj_base)
412 logbuffer->obj_base = (uintptr_t)ptr >> 3;
413 emit_svalue (logbuffer, ((uintptr_t)ptr >> 3) - logbuffer->obj_base);
414 assert (logbuffer->data <= logbuffer->data_end);
418 write_int16 (char *buf, int32_t value)
421 for (i = 0; i < 2; ++i) {
429 write_int32 (char *buf, int32_t value)
432 for (i = 0; i < 4; ++i) {
440 write_int64 (char *buf, int64_t value)
443 for (i = 0; i < 8; ++i) {
451 dump_header (MonoProfiler *profiler)
455 p = write_int32 (p, LOG_HEADER_ID);
456 *p++ = LOG_VERSION_MAJOR;
457 *p++ = LOG_VERSION_MINOR;
458 *p++ = LOG_DATA_VERSION;
459 *p++ = sizeof (void*);
460 p = write_int64 (p, ((uint64_t)time (NULL)) * 1000); /* startup time */
461 p = write_int32 (p, get_timer_overhead ()); /* timer overhead */
462 p = write_int32 (p, 0); /* flags */
463 p = write_int32 (p, process_id ()); /* pid */
464 p = write_int16 (p, profiler->command_port); /* port */
465 p = write_int16 (p, 0); /* opsystem */
466 #if defined (HAVE_SYS_ZLIB)
467 if (profiler->gzfile) {
468 gzwrite (profiler->gzfile, hbuf, p - hbuf);
470 fwrite (hbuf, p - hbuf, 1, profiler->file);
473 fwrite (hbuf, p - hbuf, 1, profiler->file);
478 dump_buffer (MonoProfiler *profiler, LogBuffer *buf)
483 dump_buffer (profiler, buf->next);
484 p = write_int32 (p, BUF_ID);
485 p = write_int32 (p, buf->data - buf->buf);
486 p = write_int64 (p, buf->time_base);
487 p = write_int64 (p, buf->ptr_base);
488 p = write_int64 (p, buf->obj_base);
489 p = write_int64 (p, buf->thread_id);
490 p = write_int64 (p, buf->method_base);
491 #if defined (HAVE_SYS_ZLIB)
492 if (profiler->gzfile) {
493 gzwrite (profiler->gzfile, hbuf, p - hbuf);
494 gzwrite (profiler->gzfile, buf->buf, buf->data - buf->buf);
497 fwrite (hbuf, p - hbuf, 1, profiler->file);
498 fwrite (buf->buf, buf->data - buf->buf, 1, profiler->file);
499 #if defined (HAVE_SYS_ZLIB)
502 free_buffer (buf, buf->size);
506 process_requests (MonoProfiler *profiler)
508 if (heapshot_requested)
509 mono_gc_collect (mono_gc_max_generation ());
513 runtime_initialized (MonoProfiler *profiler)
519 * Can be called only at safe callback locations.
522 safe_dump (MonoProfiler *profiler, LogBuffer *logbuffer)
524 int cd = logbuffer->call_depth;
526 dump_buffer (profiler, TLS_GET (tlsbuffer));
528 TLS_SET (tlsbuffer, NULL);
530 TLS_GET (tlsbuffer)->call_depth = cd;
534 gc_reference (MonoObject *obj, MonoClass *klass, uintptr_t size, uintptr_t num, MonoObject **refs, uintptr_t *offsets, void *data)
537 uintptr_t last_offset = 0;
538 //const char *name = mono_class_get_name (klass);
539 LogBuffer *logbuffer = ensure_logbuf (20 + num * 8);
540 emit_byte (logbuffer, TYPE_HEAP_OBJECT | TYPE_HEAP);
541 emit_obj (logbuffer, obj);
542 emit_ptr (logbuffer, klass);
543 /* account for object alignment in the heap */
546 emit_value (logbuffer, size);
547 emit_value (logbuffer, num);
548 for (i = 0; i < num; ++i) {
549 emit_value (logbuffer, offsets [i] - last_offset);
550 last_offset = offsets [i];
551 emit_obj (logbuffer, refs [i]);
554 // printf ("obj: %p, klass: %s, refs: %d, size: %d\n", obj, name, (int)num, (int)size);
558 static unsigned int hs_mode_ms = 0;
559 static unsigned int hs_mode_gc = 0;
560 static unsigned int hs_mode_ondemand = 0;
561 static unsigned int gc_count = 0;
562 static uint64_t last_hs_time = 0;
565 heap_walk (MonoProfiler *profiler)
569 LogBuffer *logbuffer;
572 logbuffer = ensure_logbuf (10);
573 now = current_time ();
574 if (hs_mode_ms && (now - last_hs_time)/1000000 >= hs_mode_ms)
576 else if (hs_mode_gc && (gc_count % hs_mode_gc) == 0)
578 else if (hs_mode_ondemand && heapshot_requested)
580 else if (!hs_mode_ms && !hs_mode_gc && profiler->last_gc_gen_started == mono_gc_max_generation ())
585 heapshot_requested = 0;
586 emit_byte (logbuffer, TYPE_HEAP_START | TYPE_HEAP);
587 emit_time (logbuffer, now);
588 mono_gc_walk_heap (0, gc_reference, NULL);
589 logbuffer = ensure_logbuf (10);
590 now = current_time ();
591 emit_byte (logbuffer, TYPE_HEAP_END | TYPE_HEAP);
592 emit_time (logbuffer, now);
597 gc_event (MonoProfiler *profiler, MonoGCEvent ev, int generation) {
599 LogBuffer *logbuffer = ensure_logbuf (10);
600 now = current_time ();
601 ENTER_LOG (logbuffer, "gcevent");
602 emit_byte (logbuffer, TYPE_GC_EVENT | TYPE_GC);
603 emit_time (logbuffer, now);
604 emit_value (logbuffer, ev);
605 emit_value (logbuffer, generation);
606 /* to deal with nested gen1 after gen0 started */
607 if (ev == MONO_GC_EVENT_START) {
608 profiler->last_gc_gen_started = generation;
609 if (generation == mono_gc_max_generation ())
612 if (ev == MONO_GC_EVENT_PRE_START_WORLD)
613 heap_walk (profiler);
614 EXIT_LOG (logbuffer);
615 if (ev == MONO_GC_EVENT_POST_START_WORLD)
616 safe_dump (profiler, logbuffer);
617 //printf ("gc event %d for generation %d\n", ev, generation);
621 gc_resize (MonoProfiler *profiler, int64_t new_size) {
623 LogBuffer *logbuffer = ensure_logbuf (10);
624 now = current_time ();
625 ENTER_LOG (logbuffer, "gcresize");
626 emit_byte (logbuffer, TYPE_GC_RESIZE | TYPE_GC);
627 emit_time (logbuffer, now);
628 emit_value (logbuffer, new_size);
629 //printf ("gc resized to %lld\n", new_size);
630 EXIT_LOG (logbuffer);
633 #define MAX_FRAMES 16
636 MonoMethod* methods [MAX_FRAMES];
638 static int num_frames = MAX_FRAMES / 2;
641 walk_stack (MonoMethod *method, int32_t native_offset, int32_t il_offset, mono_bool managed, void* data)
643 FrameData *frame = data;
644 if (method && frame->count < num_frames) {
645 frame->methods [frame->count++] = method;
646 //printf ("In %d %s\n", frame->count, mono_method_get_name (method));
648 return frame->count == num_frames;
652 * a note about stack walks: they can cause more profiler events to fire,
653 * so we need to make sure they don't happen after we started emitting an
654 * event, hence the collect_bt/emit_bt split.
657 collect_bt (FrameData *data)
660 mono_stack_walk_no_il (walk_stack, data);
664 emit_bt (LogBuffer *logbuffer, FrameData *data)
666 /* FIXME: this is actually tons of data and we should
667 * just output it the first time and use an id the next
669 if (data->count > num_frames)
670 printf ("bad num frames: %d\n", data->count);
671 emit_value (logbuffer, 0); /* flags */
672 emit_value (logbuffer, data->count);
673 //if (*p != data.count) {
674 // 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);}
675 while (data->count) {
676 emit_ptr (logbuffer, data->methods [--data->count]);
681 gc_alloc (MonoProfiler *prof, MonoObject *obj, MonoClass *klass)
685 int do_bt = (nocalls && runtime_inited && !notraces)? TYPE_ALLOC_BT: 0;
687 LogBuffer *logbuffer;
688 len = mono_object_get_size (obj);
689 /* account for object alignment in the heap */
694 logbuffer = ensure_logbuf (32 + MAX_FRAMES * 8);
695 now = current_time ();
696 ENTER_LOG (logbuffer, "gcalloc");
697 emit_byte (logbuffer, do_bt | TYPE_ALLOC);
698 emit_time (logbuffer, now);
699 emit_ptr (logbuffer, klass);
700 emit_obj (logbuffer, obj);
701 emit_value (logbuffer, len);
703 emit_bt (logbuffer, &data);
704 EXIT_LOG (logbuffer);
706 safe_dump (prof, logbuffer);
707 process_requests (prof);
708 //printf ("gc alloc %s at %p\n", mono_class_get_name (klass), obj);
712 gc_moves (MonoProfiler *prof, void **objects, int num)
716 LogBuffer *logbuffer = ensure_logbuf (10 + num * 8);
717 now = current_time ();
718 ENTER_LOG (logbuffer, "gcmove");
719 emit_byte (logbuffer, TYPE_GC_MOVE | TYPE_GC);
720 emit_time (logbuffer, now);
721 emit_value (logbuffer, num);
722 for (i = 0; i < num; ++i)
723 emit_obj (logbuffer, objects [i]);
724 //printf ("gc moved %d objects\n", num/2);
725 EXIT_LOG (logbuffer);
729 gc_roots (MonoProfiler *prof, int num, void **objects, int *root_types, uintptr_t *extra_info)
732 LogBuffer *logbuffer = ensure_logbuf (5 + num * 18);
733 ENTER_LOG (logbuffer, "gcroots");
734 emit_byte (logbuffer, TYPE_HEAP_ROOT | TYPE_HEAP);
735 emit_value (logbuffer, num);
736 emit_value (logbuffer, mono_gc_collection_count (mono_gc_max_generation ()));
737 for (i = 0; i < num; ++i) {
738 emit_obj (logbuffer, objects [i]);
739 emit_value (logbuffer, root_types [i]);
740 emit_value (logbuffer, extra_info [i]);
742 EXIT_LOG (logbuffer);
746 gc_handle (MonoProfiler *prof, int op, int type, uintptr_t handle, MonoObject *obj)
749 LogBuffer *logbuffer = ensure_logbuf (16);
750 now = current_time ();
751 ENTER_LOG (logbuffer, "gchandle");
752 if (op == MONO_PROFILER_GC_HANDLE_CREATED)
753 emit_byte (logbuffer, TYPE_GC_HANDLE_CREATED | TYPE_GC);
754 else if (op == MONO_PROFILER_GC_HANDLE_DESTROYED)
755 emit_byte (logbuffer, TYPE_GC_HANDLE_DESTROYED | TYPE_GC);
758 emit_time (logbuffer, now);
759 emit_value (logbuffer, type);
760 emit_value (logbuffer, handle);
761 if (op == MONO_PROFILER_GC_HANDLE_CREATED)
762 emit_obj (logbuffer, obj);
763 EXIT_LOG (logbuffer);
764 process_requests (prof);
768 push_nesting (char *p, MonoClass *klass)
773 nesting = mono_class_get_nesting_type (klass);
775 p = push_nesting (p, nesting);
779 name = mono_class_get_name (klass);
780 nspace = mono_class_get_namespace (klass);
783 p += strlen (nspace);
793 type_name (MonoClass *klass)
797 push_nesting (buf, klass);
798 p = malloc (strlen (buf) + 1);
804 image_loaded (MonoProfiler *prof, MonoImage *image, int result)
809 LogBuffer *logbuffer;
810 if (result != MONO_PROFILE_OK)
812 name = mono_image_get_filename (image);
813 nlen = strlen (name) + 1;
814 logbuffer = ensure_logbuf (16 + nlen);
815 now = current_time ();
816 ENTER_LOG (logbuffer, "image");
817 emit_byte (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
818 emit_time (logbuffer, now);
819 emit_byte (logbuffer, TYPE_IMAGE);
820 emit_ptr (logbuffer, image);
821 emit_value (logbuffer, 0); /* flags */
822 memcpy (logbuffer->data, name, nlen);
823 logbuffer->data += nlen;
824 //printf ("loaded image %p (%s)\n", image, name);
825 EXIT_LOG (logbuffer);
827 safe_dump (prof, logbuffer);
828 process_requests (prof);
832 class_loaded (MonoProfiler *prof, MonoClass *klass, int result)
838 LogBuffer *logbuffer;
839 if (result != MONO_PROFILE_OK)
842 name = mono_type_get_name (mono_class_get_type (klass));
844 name = type_name (klass);
845 nlen = strlen (name) + 1;
846 image = mono_class_get_image (klass);
847 logbuffer = ensure_logbuf (24 + nlen);
848 now = current_time ();
849 ENTER_LOG (logbuffer, "class");
850 emit_byte (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
851 emit_time (logbuffer, now);
852 emit_byte (logbuffer, TYPE_CLASS);
853 emit_ptr (logbuffer, klass);
854 emit_ptr (logbuffer, image);
855 emit_value (logbuffer, 0); /* flags */
856 memcpy (logbuffer->data, name, nlen);
857 logbuffer->data += nlen;
858 //printf ("loaded class %p (%s)\n", klass, name);
863 EXIT_LOG (logbuffer);
865 safe_dump (prof, logbuffer);
866 process_requests (prof);
870 method_enter (MonoProfiler *prof, MonoMethod *method)
873 LogBuffer *logbuffer = ensure_logbuf (16);
874 if (logbuffer->call_depth++ > max_call_depth)
876 now = current_time ();
877 ENTER_LOG (logbuffer, "enter");
878 emit_byte (logbuffer, TYPE_ENTER | TYPE_METHOD);
879 emit_time (logbuffer, now);
880 emit_method (logbuffer, method);
881 EXIT_LOG (logbuffer);
882 process_requests (prof);
886 method_leave (MonoProfiler *prof, MonoMethod *method)
889 LogBuffer *logbuffer = ensure_logbuf (16);
890 if (--logbuffer->call_depth > max_call_depth)
892 now = current_time ();
893 ENTER_LOG (logbuffer, "leave");
894 emit_byte (logbuffer, TYPE_LEAVE | TYPE_METHOD);
895 emit_time (logbuffer, now);
896 emit_method (logbuffer, method);
897 EXIT_LOG (logbuffer);
899 safe_dump (prof, logbuffer);
900 process_requests (prof);
904 method_exc_leave (MonoProfiler *prof, MonoMethod *method)
907 LogBuffer *logbuffer;
910 logbuffer = ensure_logbuf (16);
911 if (--logbuffer->call_depth > max_call_depth)
913 now = current_time ();
914 ENTER_LOG (logbuffer, "eleave");
915 emit_byte (logbuffer, TYPE_EXC_LEAVE | TYPE_METHOD);
916 emit_time (logbuffer, now);
917 emit_method (logbuffer, method);
918 EXIT_LOG (logbuffer);
919 process_requests (prof);
923 method_jitted (MonoProfiler *prof, MonoMethod *method, MonoJitInfo* jinfo, int result)
928 LogBuffer *logbuffer;
929 if (result != MONO_PROFILE_OK)
931 name = mono_method_full_name (method, 1);
932 nlen = strlen (name) + 1;
933 logbuffer = ensure_logbuf (32 + nlen);
934 now = current_time ();
935 ENTER_LOG (logbuffer, "jit");
936 emit_byte (logbuffer, TYPE_JIT | TYPE_METHOD);
937 emit_time (logbuffer, now);
938 emit_method (logbuffer, method);
939 emit_ptr (logbuffer, mono_jit_info_get_code_start (jinfo));
940 emit_value (logbuffer, mono_jit_info_get_code_size (jinfo));
941 memcpy (logbuffer->data, name, nlen);
942 logbuffer->data += nlen;
944 EXIT_LOG (logbuffer);
946 safe_dump (prof, logbuffer);
947 process_requests (prof);
951 throw_exc (MonoProfiler *prof, MonoObject *object)
953 int do_bt = (nocalls && runtime_inited && !notraces)? TYPE_EXCEPTION_BT: 0;
956 LogBuffer *logbuffer;
959 logbuffer = ensure_logbuf (16 + MAX_FRAMES * 8);
960 now = current_time ();
961 ENTER_LOG (logbuffer, "throw");
962 emit_byte (logbuffer, do_bt | TYPE_EXCEPTION);
963 emit_time (logbuffer, now);
964 emit_obj (logbuffer, object);
966 emit_bt (logbuffer, &data);
967 EXIT_LOG (logbuffer);
968 process_requests (prof);
972 clause_exc (MonoProfiler *prof, MonoMethod *method, int clause_type, int clause_num)
975 LogBuffer *logbuffer = ensure_logbuf (16);
976 now = current_time ();
977 ENTER_LOG (logbuffer, "clause");
978 emit_byte (logbuffer, TYPE_EXCEPTION | TYPE_CLAUSE);
979 emit_time (logbuffer, now);
980 emit_value (logbuffer, clause_type);
981 emit_value (logbuffer, clause_num);
982 emit_method (logbuffer, method);
983 EXIT_LOG (logbuffer);
987 monitor_event (MonoProfiler *profiler, MonoObject *object, MonoProfilerMonitorEvent event)
989 int do_bt = (nocalls && runtime_inited && !notraces && event == MONO_PROFILER_MONITOR_CONTENTION)? TYPE_MONITOR_BT: 0;
992 LogBuffer *logbuffer;
995 logbuffer = ensure_logbuf (16 + MAX_FRAMES * 8);
996 now = current_time ();
997 ENTER_LOG (logbuffer, "monitor");
998 emit_byte (logbuffer, (event << 4) | do_bt | TYPE_MONITOR);
999 emit_time (logbuffer, now);
1000 emit_obj (logbuffer, object);
1002 emit_bt (logbuffer, &data);
1003 EXIT_LOG (logbuffer);
1004 process_requests (profiler);
1008 thread_start (MonoProfiler *prof, uintptr_t tid)
1010 //printf ("thread start %p\n", (void*)tid);
1015 thread_end (MonoProfiler *prof, uintptr_t tid)
1018 if (TLS_GET (tlsbuffer))
1019 dump_buffer (prof, TLS_GET (tlsbuffer));
1021 TLS_SET (tlsbuffer, NULL);
1025 thread_name (MonoProfiler *prof, uintptr_t tid, const char *name)
1027 int len = strlen (name) + 1;
1029 LogBuffer *logbuffer;
1030 logbuffer = ensure_logbuf (10 + len);
1031 now = current_time ();
1032 ENTER_LOG (logbuffer, "tname");
1033 emit_byte (logbuffer, TYPE_METADATA);
1034 emit_time (logbuffer, now);
1035 emit_byte (logbuffer, TYPE_THREAD);
1036 emit_ptr (logbuffer, (void*)tid);
1037 emit_value (logbuffer, 0); /* flags */
1038 memcpy (logbuffer->data, name, len);
1039 logbuffer->data += len;
1040 EXIT_LOG (logbuffer);
1044 log_shutdown (MonoProfiler *prof)
1046 #ifndef DISABLE_HELPER_THREAD
1047 if (prof->command_port) {
1050 write (prof->pipes [1], &c, 1);
1051 pthread_join (prof->helper_thread, &res);
1055 if (TLS_GET (tlsbuffer))
1056 dump_buffer (prof, TLS_GET (tlsbuffer));
1057 TLS_SET (tlsbuffer, NULL);
1059 #if defined (HAVE_SYS_ZLIB)
1061 gzclose (prof->gzfile);
1063 if (prof->pipe_output)
1064 pclose (prof->file);
1066 fclose (prof->file);
1071 new_filename (const char* filename)
1073 time_t t = time (NULL);
1074 int pid = process_id ();
1079 int count_dates = 0;
1083 for (p = filename; *p; p++) {
1094 if (!count_dates && !count_pids)
1095 return pstrdup (filename);
1096 snprintf (pid_buf, sizeof (pid_buf), "%d", pid);
1098 snprintf (time_buf, sizeof (time_buf), "%d%02d%02d%02d%02d%02d",
1099 1900 + ts->tm_year, 1 + ts->tm_mon, ts->tm_mday, ts->tm_hour, ts->tm_min, ts->tm_sec);
1100 s_date = strlen (time_buf);
1101 s_pid = strlen (pid_buf);
1102 d = res = malloc (strlen (filename) + s_date * count_dates + s_pid * count_pids);
1103 for (p = filename; *p; p++) {
1110 strcpy (d, time_buf);
1113 } else if (*p == 'p') {
1114 strcpy (d, pid_buf);
1117 } else if (*p == '%') {
1129 #ifndef DISABLE_HELPER_THREAD
1131 helper_thread (void* arg)
1133 MonoProfiler* prof = arg;
1137 MonoThread *thread = NULL;
1139 //fprintf (stderr, "Server listening\n");
1140 command_socket = -1;
1146 FD_SET (prof->server_socket, &rfds);
1147 max_fd = prof->server_socket;
1148 FD_SET (prof->pipes [0], &rfds);
1149 if (max_fd < prof->pipes [0])
1150 max_fd = prof->pipes [0];
1151 if (command_socket >= 0) {
1152 FD_SET (command_socket, &rfds);
1153 if (max_fd < command_socket)
1154 max_fd = command_socket;
1158 len = select (max_fd + 1, &rfds, NULL, NULL, &tv);
1159 if (FD_ISSET (prof->pipes [0], &rfds)) {
1160 /* time to shut down */
1162 mono_thread_detach (thread);
1163 /*fprintf (stderr, "helper shutdown\n");*/
1166 if (runtime_inited && !thread) {
1167 thread = mono_thread_attach (mono_get_root_domain ());
1168 /*fprintf (stderr, "attached\n");*/
1170 if (command_socket >= 0 && FD_ISSET (command_socket, &rfds)) {
1171 len = read (command_socket, buf, sizeof (buf) - 1);
1175 close (command_socket);
1176 command_socket = -1;
1180 if (strcmp (buf, "heapshot\n") == 0) {
1181 heapshot_requested = 1;
1182 //fprintf (stderr, "perform heapshot\n");
1184 process_requests (prof);
1188 if (!FD_ISSET (prof->server_socket, &rfds)) {
1191 command_socket = accept (prof->server_socket, NULL, NULL);
1192 if (command_socket < 0)
1194 //fprintf (stderr, "Accepted connection\n");
1200 start_helper_thread (MonoProfiler* prof)
1202 struct sockaddr_in server_address;
1205 if (pipe (prof->pipes) < 0) {
1206 fprintf (stderr, "Cannot create pipe\n");
1209 prof->server_socket = socket (PF_INET, SOCK_STREAM, 0);
1210 if (prof->server_socket < 0) {
1211 fprintf (stderr, "Cannot create server socket\n");
1214 memset (&server_address, 0, sizeof (server_address));
1215 server_address.sin_family = AF_INET;
1216 server_address.sin_addr.s_addr = INADDR_ANY;
1217 server_address.sin_port = htons (prof->command_port);
1218 if (bind (prof->server_socket, (struct sockaddr *) &server_address, sizeof (server_address)) < 0) {
1219 fprintf (stderr, "Cannot bind server socket, port: %d: %s\n", prof->command_port, strerror (errno));
1220 close (prof->server_socket);
1223 if (listen (prof->server_socket, 1) < 0) {
1224 fprintf (stderr, "Cannot listen server socket\n");
1225 close (prof->server_socket);
1228 if (getsockname (prof->server_socket, (struct sockaddr *)&server_address, &slen) == 0) {
1229 prof->command_port = ntohs (server_address.sin_port);
1230 /*fprintf (stderr, "Assigned server port: %d\n", prof->command_port);*/
1233 r = pthread_create (&prof->helper_thread, NULL, helper_thread, prof);
1235 close (prof->server_socket);
1242 static MonoProfiler*
1243 create_profiler (const char *filename)
1247 int force_delete = 0;
1248 prof = calloc (1, sizeof (MonoProfiler));
1250 prof->command_port = command_port;
1251 if (filename && *filename == '-') {
1257 filename = "|mprof-report -";
1259 filename = "output.mlpd";
1262 nf = new_filename (filename);
1264 int s = strlen (nf) + 32;
1265 char *p = malloc (s);
1266 snprintf (p, s, "|mprof-report '--out=%s' -", nf);
1272 prof->file = popen (nf + 1, "w");
1273 prof->pipe_output = 1;
1278 if ((f = fopen (nf, "r"))) {
1280 fprintf (stderr, "The Mono profiler won't overwrite existing filename: %s.\n", nf);
1281 fprintf (stderr, "Profiling disabled: use a different name or -FILENAME to force overwrite.\n");
1285 prof->file = fopen (nf, "wb");
1288 fprintf (stderr, "Cannot create profiler output: %s\n", nf);
1291 #if defined (HAVE_SYS_ZLIB)
1293 prof->gzfile = gzdopen (fileno (prof->file), "wb");
1295 #ifndef DISABLE_HELPER_THREAD
1296 if (hs_mode_ondemand) {
1297 if (!start_helper_thread (prof))
1298 prof->command_port = 0;
1301 if (hs_mode_ondemand)
1302 fprintf (stderr, "Ondemand heapshot unavailable on this arch.\n");
1311 printf ("Log profiler version %d.%d (format: %d)\n", LOG_VERSION_MAJOR, LOG_VERSION_MINOR, LOG_DATA_VERSION);
1312 printf ("Usage: mono --profile=log[:OPTION1[,OPTION2...]] program.exe\n");
1313 printf ("Options:\n");
1314 printf ("\thelp show this usage info\n");
1315 printf ("\t[no]alloc enable/disable recording allocation info\n");
1316 printf ("\t[no]calls enable/disable recording enter/leave method events\n");
1317 printf ("\theapshot[=MODE] record heap shot info (by default at each major collection)\n");
1318 printf ("\t MODE: every XXms milliseconds, every YYgc collections, ondemand\n");
1319 printf ("\ttime=fast use a faster (but more inaccurate) timer\n");
1320 printf ("\tmaxframes=NUM collect up to NUM stack frames\n");
1321 printf ("\tcalldepth=NUM ignore method events for call chain depth bigger than NUM\n");
1322 printf ("\toutput=FILENAME write the data to file FILENAME (-FILENAME to overwrite)\n");
1323 printf ("\toutput=|PROGRAM write the data to the stdin of PROGRAM\n");
1324 printf ("\t %%t is subtituted with date and time, %%p with the pid\n");
1325 printf ("\treport create a report instead of writing the raw data to a file\n");
1326 printf ("\tzip compress the output data\n");
1327 printf ("\tport=PORTNUM use PORTNUM for the listening command server\n");
1333 match_option (const char* p, const char *opt, char **rval)
1335 int len = strlen (opt);
1336 if (strncmp (p, opt, len) == 0) {
1338 if (p [len] == '=' && p [len + 1]) {
1339 const char *opt = p + len + 1;
1340 const char *end = strchr (opt, ',');
1348 val = malloc (l + 1);
1349 memcpy (val, opt, l);
1354 if (p [len] == 0 || p [len] == ',') {
1356 return p + len + (p [len] == ',');
1370 set_hsmode (char* val, int allow_empty)
1374 if (allow_empty && !val)
1376 if (strcmp (val, "ondemand") == 0) {
1377 hs_mode_ondemand = 1;
1381 count = strtoul (val, &end, 10);
1384 if (strcmp (end, "ms") == 0)
1386 else if (strcmp (end, "gc") == 0)
1394 * declaration to silence the compiler: this is the entry point that
1395 * mono will load from the shared library and call.
1398 mono_profiler_startup (const char *desc);
1401 mono_profiler_startup (const char *desc)
1404 char *filename = NULL;
1408 int calls_enabled = 0;
1409 int allocs_enabled = 0;
1410 int events = MONO_PROFILE_GC|MONO_PROFILE_ALLOCATIONS|
1411 MONO_PROFILE_GC_MOVES|MONO_PROFILE_CLASS_EVENTS|MONO_PROFILE_THREADS|
1412 MONO_PROFILE_ENTER_LEAVE|MONO_PROFILE_JIT_COMPILATION|MONO_PROFILE_EXCEPTIONS|
1413 MONO_PROFILE_MONITOR_EVENTS|MONO_PROFILE_MODULE_EVENTS|MONO_PROFILE_GC_ROOTS;
1416 if (strncmp (p, "log", 3))
1421 for (; *p; p = opt) {
1427 if ((opt = match_option (p, "help", NULL)) != p) {
1431 if ((opt = match_option (p, "calls", NULL)) != p) {
1435 if ((opt = match_option (p, "nocalls", NULL)) != p) {
1436 events &= ~MONO_PROFILE_ENTER_LEAVE;
1440 if ((opt = match_option (p, "alloc", NULL)) != p) {
1444 if ((opt = match_option (p, "noalloc", NULL)) != p) {
1445 events &= ~MONO_PROFILE_ALLOCATIONS;
1448 if ((opt = match_option (p, "time", &val)) != p) {
1449 if (strcmp (val, "fast") == 0)
1451 else if (strcmp (val, "null") == 0)
1458 if ((opt = match_option (p, "report", NULL)) != p) {
1462 if ((opt = match_option (p, "heapshot", &val)) != p) {
1463 events &= ~MONO_PROFILE_ALLOCATIONS;
1464 events &= ~MONO_PROFILE_ENTER_LEAVE;
1467 set_hsmode (val, 1);
1470 if ((opt = match_option (p, "hsmode", &val)) != p) {
1471 fprintf (stderr, "The hsmode profiler option is obsolete, use heapshot=MODE.\n");
1472 set_hsmode (val, 0);
1475 if ((opt = match_option (p, "zip", NULL)) != p) {
1479 if ((opt = match_option (p, "output", &val)) != p) {
1483 if ((opt = match_option (p, "port", &val)) != p) {
1485 command_port = strtoul (val, &end, 10);
1489 if ((opt = match_option (p, "maxframes", &val)) != p) {
1491 num_frames = strtoul (val, &end, 10);
1492 if (num_frames > MAX_FRAMES)
1493 num_frames = MAX_FRAMES;
1495 notraces = num_frames == 0;
1498 if ((opt = match_option (p, "calldepth", &val)) != p) {
1500 max_call_depth = strtoul (val, &end, 10);
1509 if (calls_enabled) {
1510 events |= MONO_PROFILE_ENTER_LEAVE;
1514 events |= MONO_PROFILE_ALLOCATIONS;
1515 utils_init (fast_time);
1517 prof = create_profiler (filename);
1522 mono_profiler_install (prof, log_shutdown);
1523 mono_profiler_install_gc (gc_event, gc_resize);
1524 mono_profiler_install_allocation (gc_alloc);
1525 mono_profiler_install_gc_moves (gc_moves);
1526 mono_profiler_install_gc_roots (gc_handle, gc_roots);
1527 mono_profiler_install_class (NULL, class_loaded, NULL, NULL);
1528 mono_profiler_install_module (NULL, image_loaded, NULL, NULL);
1529 mono_profiler_install_thread (thread_start, thread_end);
1530 mono_profiler_install_thread_name (thread_name);
1531 mono_profiler_install_enter_leave (method_enter, method_leave);
1532 mono_profiler_install_jit_end (method_jitted);
1533 mono_profiler_install_exception (throw_exc, method_exc_leave, clause_exc);
1534 mono_profiler_install_monitor (monitor_event);
1535 mono_profiler_install_runtime_initialized (runtime_initialized);
1537 mono_profiler_set_events (events);
1539 TLS_INIT (tlsbuffer);