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/mono-gc.h>
13 #include <mono/metadata/debug-helpers.h>
26 #if defined (HAVE_SYS_ZLIB)
30 #define BUFFER_SIZE (4096 * 16)
31 static int nocalls = 0;
32 static int notraces = 0;
33 static int use_zip = 0;
34 static int do_report = 0;
35 static int do_heap_shot = 0;
36 static int max_call_depth = 100;
37 static int runtime_inited = 0;
39 /* For linux compile with:
40 * gcc -fPIC -shared -o libmono-profiler-log.so proflog.c utils.c -Wall -g -lz `pkg-config --cflags --libs mono-2`
41 * gcc -o mprof-report decode.c utils.c -Wall -g -lz -lrt -lpthread `pkg-config --cflags mono-2`
43 * For osx compile with:
44 * 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
45 * gcc -m32 -o mprof-report decode.c utils.c -Wall -g -lz -lrt -lpthread `pkg-config --cflags mono-2`
48 * sudo cp mprof-report /usr/local/bin
49 * sudo cp libmono-profiler-log.so /usr/local/lib
53 typedef struct _LogBuffer LogBuffer;
59 * The file is composed by a header followed by 0 or more buffers.
60 * Each buffer contains events that happened on a thread: for a given thread
61 * buffers that appear later in the file are guaranteed to contain events
62 * that happened later in time. Buffers from separate threads could be interleaved,
64 * Buffers are not required to be aligned.
67 * [id: 4 bytes] constant value: LOG_HEADER_ID
68 * [major: 1 byte] [minor: 1 byte] major and minor version of the log profiler
69 * [format: 1 byte] version of the data format for the rest of the file
70 * [ptrsize: 1 byte] size in bytes of a pointer in the profiled program
71 * [startup time: 8 bytes] time in milliseconds since the unix epoch when the program started
72 * [timer overhead: 4 bytes] approximate overhead in nanoseconds of the timer
73 * [flags: 4 bytes] file format flags, should be 0 for now
74 * [pid: 4 bytes] pid of the profiled process
75 * [sysid: 4 bytes] operating system and architecture identifier
77 * The multiple byte integers are in little-endian format.
80 * [buffer header] [event]*
81 * Buffers have a fixed-size header followed by 0 or more bytes of event data.
82 * Timing information and other values in the event data are usually stored
83 * as uleb128 or sleb128 integers. To save space, as noted for each item below,
84 * some data is represented as a difference between the actual value and
85 * either the last value of the same type (like for timing information) or
86 * as the difference from a value stored in a buffer header.
88 * For timing information the data is stored as uleb128, since timing
89 * increases in a monotonic way in each thread: the value is the number of
90 * nanoseconds to add to the last seen timing data in a buffer. The first value
91 * in a buffer will be calculated from the time_base field in the buffer head.
93 * Object or heap sizes are stored as uleb128.
94 * Pointer differences are stored as sleb128, instead.
96 * If an unexpected value is found, the rest of the buffer should be ignored,
97 * as generally the later values need the former to be interpreted correctly.
99 * buffer header format:
100 * [bufid: 4 bytes] constant value: BUF_ID
101 * [len: 4 bytes] size of the data following the buffer header
102 * [time_base: 8 bytes] time base in nanoseconds since an unspecified epoch
103 * [ptr_base: 8 bytes] base value for pointers
104 * [obj_base: 8 bytes] base value for object addresses
105 * [thread id: 8 bytes] system-specific thread ID (pthread_t for example)
106 * [method_base: 8 bytes] base value for MonoMethod pointers
109 * [extended info: upper 4 bits] [type: lower 4 bits] [data]*
110 * The data that follows depends on type and the extended info.
111 * Type is one of the enum values in proflog.h: TYPE_ALLOC, TYPE_GC,
112 * TYPE_METADATA, TYPE_METHOD, TYPE_EXCEPTION, TYPE_MONITOR, TYPE_HEAP.
113 * The extended info bits are interpreted based on type, see
114 * each individual event description below.
115 * strings are represented as a 0-terminated utf8 sequence.
118 * [flags: uleb128] must be 0
119 * [num: uleb128] number of frames following
120 * [frame: sleb128]* num MonoMethod pointers as differences from ptr_base
124 * exinfo: flags: TYPE_ALLOC_BT
125 * [time diff: uleb128] nanoseconds since last timing
126 * [ptr: sleb128] class as a byte difference from ptr_base
127 * [obj: sleb128] object address as a byte difference from obj_base
128 * [size: uleb128] size of the object in the heap
129 * If the TYPE_ALLOC_BT flag is set, a backtrace follows.
133 * exinfo: one of TYPE_GC_EVENT, TYPE_GC_RESIZE, TYPE_GC_MOVE, TYPE_GC_HANDLE_CREATED,
134 * TYPE_GC_HANDLE_DESTROYED
135 * [time diff: uleb128] nanoseconds since last timing
136 * if exinfo == TYPE_GC_RESIZE
137 * [heap_size: uleb128] new heap size
138 * if exinfo == TYPE_GC_EVENT
139 * [event type: uleb128] GC event (MONO_GC_EVENT_* from profiler.h)
140 * [generation: uleb128] GC generation event refers to
141 * if exinfo == TYPE_GC_MOVE
142 * [num_objects: uleb128] number of object moves that follow
143 * [objaddr: sleb128]+ num_objects object pointer differences from obj_base
144 * num is always an even number: the even items are the old
145 * addresses, the odd numbers are the respective new object addresses
146 * if exinfo == TYPE_GC_HANDLE_CREATED
147 * [handle_type: uleb128] GC handle type (System.Runtime.InteropServices.GCHandleType)
148 * upper bits reserved as flags
149 * [handle: uleb128] GC handle value
150 * [objaddr: sleb128] object pointer differences from obj_base
151 * if exinfo == TYPE_GC_HANDLE_DESTROYED
152 * [handle_type: uleb128] GC handle type (System.Runtime.InteropServices.GCHandleType)
153 * upper bits reserved as flags
154 * [handle: uleb128] GC handle value
156 * type metadata format:
157 * type: TYPE_METADATA
158 * exinfo: flags: TYPE_LOAD_ERR
159 * [time diff: uleb128] nanoseconds since last timing
160 * [mtype: byte] metadata type, one of: TYPE_CLASS, TYPE_IMAGE, TYPE_ASSEMBLY, TYPE_DOMAIN,
162 * [pointer: sleb128] pointer of the metadata type depending on mtype
163 * if mtype == TYPE_CLASS
164 * [image: sleb128] MonoImage* as a pointer difference from ptr_base
165 * [flags: uleb128] must be 0
166 * [name: string] full class name
167 * if mtype == TYPE_IMAGE
168 * [flags: uleb128] must be 0
169 * [name: string] image file name
170 * if mtype == TYPE_THREAD
171 * [flags: uleb128] must be 0
172 * [name: string] thread name
174 * type method format:
176 * exinfo: one of: TYPE_LEAVE, TYPE_ENTER, TYPE_EXC_LEAVE, TYPE_JIT
177 * [time diff: uleb128] nanoseconds since last timing
178 * [method: sleb128] MonoMethod* as a pointer difference from the last such
179 * pointer or the buffer method_base
180 * if exinfo == TYPE_JIT
181 * [code address: sleb128] pointer to the native code as a diff from ptr_base
182 * [code size: uleb128] size of the generated code
183 * [name: string] full method name
185 * type exception format:
186 * type: TYPE_EXCEPTION
187 * exinfo: TYPE_EXCEPTION_BT flag and one of: TYPE_THROW, TYPE_CLAUSE
188 * [time diff: uleb128] nanoseconds since last timing
189 * if exinfo.low3bits == TYPE_CLAUSE
190 * [clause type: uleb128] finally/catch/fault/filter
191 * [clause num: uleb128] the clause number in the method header
192 * [method: sleb128] MonoMethod* as a pointer difference from the last such
193 * pointer or the buffer method_base
194 * if exinfo.low3bits == TYPE_THROW
195 * [object: sleb128] the object that was thrown as a difference from obj_base
196 * If the TYPE_EXCEPTION_BT flag is set, a backtrace follows.
198 * type monitor format:
200 * exinfo: TYPE_MONITOR_BT flag and one of: MONO_PROFILER_MONITOR_(CONTENTION|FAIL|DONE)
201 * [time diff: uleb128] nanoseconds since last timing
202 * [object: sleb128] the lock object as a difference from obj_base
203 * if exinfo.low3bits == MONO_PROFILER_MONITOR_CONTENTION
204 * If the TYPE_MONITOR_BT flag is set, a backtrace follows.
208 * exinfo: one of TYPE_HEAP_START, TYPE_HEAP_END, TYPE_HEAP_OBJECT
209 * if exinfo == TYPE_HEAP_START
210 * [time diff: uleb128] nanoseconds since last timing
211 * if exinfo == TYPE_HEAP_END
212 * [time diff: uleb128] nanoseconds since last timing
213 * if exinfo == TYPE_HEAP_OBJECT
214 * [object: sleb128] the object as a difference from obj_base
215 * [class: sleb128] the object MonoClass* as a difference from ptr_base
216 * [size: uleb128] size of the object on the heap
217 * [num_refs: uleb128] number of object references
218 * if (format version > 1) each referenced objref is preceded by a
219 * uleb128 encoded offset: the first offset is from the object address
220 * and each next offset is relative to the previous one
221 * [objrefs: sleb128]+ object referenced as a difference from obj_base
229 uintptr_t method_base;
230 uintptr_t last_method;
233 unsigned char* data_end;
238 unsigned char buf [1];
241 #define ENTER_LOG(lb,str) if ((lb)->locked) {write(2, str, strlen(str)); write(2, "\n", 1);return;} else {(lb)->locked++;}
242 #define EXIT_LOG(lb) (lb)->locked--;
244 struct _MonoProfiler {
247 #if defined (HAVE_SYS_ZLIB)
251 int last_gc_gen_started;
255 #define TLS_SET(x,y) TlsSetValue(x, y)
256 #define TLS_GET(x) ((LogBuffer *) TlsGetValue(x))
257 #define TLS_INIT(x) x = TlsAlloc ()
258 static int tlsbuffer;
260 #define TLS_SET(x,y) x = y
263 static __thread LogBuffer* tlsbuffer = NULL;
265 #define TLS_SET(x,y) pthread_setspecific(x, y)
266 #define TLS_GET(x) ((LogBuffer *) pthread_getspecific(x))
267 #define TLS_INIT(x) pthread_key_create(&x, NULL)
268 static pthread_key_t tlsbuffer;
272 pstrdup (const char *s)
274 int len = strlen (s) + 1;
275 char *p = malloc (len);
283 LogBuffer* buf = alloc_buffer (BUFFER_SIZE);
284 buf->size = BUFFER_SIZE;
285 buf->time_base = current_time ();
286 buf->last_time = buf->time_base;
287 buf->data_end = (unsigned char*)buf + buf->size;
288 buf->data = buf->buf;
295 LogBuffer *logbuffer;
296 if (TLS_GET (tlsbuffer))
298 logbuffer = create_buffer ();
299 TLS_SET (tlsbuffer, logbuffer);
300 logbuffer->thread_id = thread_id ();
301 //printf ("thread %p at time %llu\n", (void*)logbuffer->thread_id, logbuffer->time_base);
305 ensure_logbuf (int bytes)
307 LogBuffer *old = TLS_GET (tlsbuffer);
308 if (old && old->data + bytes + 100 < old->data_end)
310 TLS_SET (tlsbuffer, NULL);
312 TLS_GET (tlsbuffer)->next = old;
314 TLS_GET (tlsbuffer)->call_depth = old->call_depth;
315 //printf ("new logbuffer\n");
316 return TLS_GET (tlsbuffer);
320 emit_byte (LogBuffer *logbuffer, int value)
322 logbuffer->data [0] = value;
324 assert (logbuffer->data <= logbuffer->data_end);
328 emit_value (LogBuffer *logbuffer, int value)
330 encode_uleb128 (value, logbuffer->data, &logbuffer->data);
331 assert (logbuffer->data <= logbuffer->data_end);
335 emit_time (LogBuffer *logbuffer, uint64_t value)
337 uint64_t tdiff = value - logbuffer->last_time;
339 if (value < logbuffer->last_time)
340 printf ("time went backwards\n");
341 //if (tdiff > 1000000)
342 // printf ("large time offset: %llu\n", tdiff);
344 encode_uleb128 (tdiff, logbuffer->data, &logbuffer->data);
345 /*if (tdiff != decode_uleb128 (p, &p))
346 printf ("incorrect encoding: %llu\n", tdiff);*/
347 logbuffer->last_time = value;
348 assert (logbuffer->data <= logbuffer->data_end);
352 emit_svalue (LogBuffer *logbuffer, int64_t value)
354 encode_sleb128 (value, logbuffer->data, &logbuffer->data);
355 assert (logbuffer->data <= logbuffer->data_end);
359 emit_ptr (LogBuffer *logbuffer, void *ptr)
361 if (!logbuffer->ptr_base)
362 logbuffer->ptr_base = (uintptr_t)ptr;
363 emit_svalue (logbuffer, (intptr_t)ptr - logbuffer->ptr_base);
364 assert (logbuffer->data <= logbuffer->data_end);
368 emit_method (LogBuffer *logbuffer, void *method)
370 if (!logbuffer->method_base) {
371 logbuffer->method_base = (intptr_t)method;
372 logbuffer->last_method = (intptr_t)method;
374 encode_sleb128 ((intptr_t)((char*)method - (char*)logbuffer->last_method), logbuffer->data, &logbuffer->data);
375 logbuffer->last_method = (intptr_t)method;
376 assert (logbuffer->data <= logbuffer->data_end);
380 emit_obj (LogBuffer *logbuffer, void *ptr)
382 if (!logbuffer->obj_base)
383 logbuffer->obj_base = (uintptr_t)ptr >> 3;
384 emit_svalue (logbuffer, ((uintptr_t)ptr >> 3) - logbuffer->obj_base);
385 assert (logbuffer->data <= logbuffer->data_end);
389 write_int32 (char *buf, int32_t value)
392 for (i = 0; i < 4; ++i) {
400 write_int64 (char *buf, int64_t value)
403 for (i = 0; i < 8; ++i) {
411 dump_header (MonoProfiler *profiler)
415 p = write_int32 (p, LOG_HEADER_ID);
416 *p++ = LOG_VERSION_MAJOR;
417 *p++ = LOG_VERSION_MINOR;
418 *p++ = LOG_DATA_VERSION;
419 *p++ = sizeof (void*);
420 p = write_int64 (p, ((uint64_t)time (NULL)) * 1000); /* startup time */
421 p = write_int32 (p, get_timer_overhead ()); /* timer overhead */
422 p = write_int32 (p, 0); /* flags */
423 p = write_int32 (p, process_id ()); /* pid */
424 p = write_int32 (p, 0); /* opsystem */
425 #if defined (HAVE_SYS_ZLIB)
426 if (profiler->gzfile) {
427 gzwrite (profiler->gzfile, hbuf, p - hbuf);
429 fwrite (hbuf, p - hbuf, 1, profiler->file);
432 fwrite (hbuf, p - hbuf, 1, profiler->file);
437 dump_buffer (MonoProfiler *profiler, LogBuffer *buf)
442 dump_buffer (profiler, buf->next);
443 p = write_int32 (p, BUF_ID);
444 p = write_int32 (p, buf->data - buf->buf);
445 p = write_int64 (p, buf->time_base);
446 p = write_int64 (p, buf->ptr_base);
447 p = write_int64 (p, buf->obj_base);
448 p = write_int64 (p, buf->thread_id);
449 p = write_int64 (p, buf->method_base);
450 #if defined (HAVE_SYS_ZLIB)
451 if (profiler->gzfile) {
452 gzwrite (profiler->gzfile, hbuf, p - hbuf);
453 gzwrite (profiler->gzfile, buf->buf, buf->data - buf->buf);
456 fwrite (hbuf, p - hbuf, 1, profiler->file);
457 fwrite (buf->buf, buf->data - buf->buf, 1, profiler->file);
458 #if defined (HAVE_SYS_ZLIB)
461 free_buffer (buf, buf->size);
465 runtime_initialized (MonoProfiler *profiler)
471 * Can be called only at safe callback locations.
474 safe_dump (MonoProfiler *profiler, LogBuffer *logbuffer)
476 int cd = logbuffer->call_depth;
478 dump_buffer (profiler, TLS_GET (tlsbuffer));
480 TLS_SET (tlsbuffer, NULL);
482 TLS_GET (tlsbuffer)->call_depth = cd;
486 gc_reference (MonoObject *obj, MonoClass *klass, uintptr_t size, uintptr_t num, MonoObject **refs, uintptr_t *offsets, void *data)
489 uintptr_t last_offset = 0;
490 //const char *name = mono_class_get_name (klass);
491 LogBuffer *logbuffer = ensure_logbuf (20 + num * 8);
492 emit_byte (logbuffer, TYPE_HEAP_OBJECT | TYPE_HEAP);
493 emit_obj (logbuffer, obj);
494 emit_ptr (logbuffer, klass);
495 /* account for object alignment in the heap */
498 emit_value (logbuffer, size);
499 emit_value (logbuffer, num);
500 for (i = 0; i < num; ++i) {
501 emit_value (logbuffer, offsets [i] - last_offset);
502 last_offset = offsets [i];
503 emit_obj (logbuffer, refs [i]);
506 // printf ("obj: %p, klass: %s, refs: %d, size: %d\n", obj, name, (int)num, (int)size);
510 static unsigned int hs_mode_ms = 0;
511 static unsigned int hs_mode_gc = 0;
512 static unsigned int gc_count = 0;
513 static uint64_t last_hs_time = 0;
516 heap_walk (MonoProfiler *profiler)
520 LogBuffer *logbuffer;
523 logbuffer = ensure_logbuf (10);
524 now = current_time ();
525 if (hs_mode_ms && (now - last_hs_time)/1000000 >= hs_mode_ms)
527 else if (hs_mode_gc && (gc_count % hs_mode_gc) == 0)
529 else if (!hs_mode_ms && !hs_mode_gc && profiler->last_gc_gen_started == mono_gc_max_generation ())
534 emit_byte (logbuffer, TYPE_HEAP_START | TYPE_HEAP);
535 emit_time (logbuffer, now);
536 mono_gc_walk_heap (0, gc_reference, NULL);
537 logbuffer = ensure_logbuf (10);
538 now = current_time ();
539 emit_byte (logbuffer, TYPE_HEAP_END | TYPE_HEAP);
540 emit_time (logbuffer, now);
545 gc_event (MonoProfiler *profiler, MonoGCEvent ev, int generation) {
547 LogBuffer *logbuffer = ensure_logbuf (10);
548 now = current_time ();
549 ENTER_LOG (logbuffer, "gcevent");
550 emit_byte (logbuffer, TYPE_GC_EVENT | TYPE_GC);
551 emit_time (logbuffer, now);
552 emit_value (logbuffer, ev);
553 emit_value (logbuffer, generation);
554 /* to deal with nested gen1 after gen0 started */
555 if (ev == MONO_GC_EVENT_START) {
556 profiler->last_gc_gen_started = generation;
559 if (ev == MONO_GC_EVENT_PRE_START_WORLD)
560 heap_walk (profiler);
561 EXIT_LOG (logbuffer);
562 if (ev == MONO_GC_EVENT_POST_START_WORLD)
563 safe_dump (profiler, logbuffer);
564 //printf ("gc event %d for generation %d\n", ev, generation);
568 gc_resize (MonoProfiler *profiler, int64_t new_size) {
570 LogBuffer *logbuffer = ensure_logbuf (10);
571 now = current_time ();
572 ENTER_LOG (logbuffer, "gcresize");
573 emit_byte (logbuffer, TYPE_GC_RESIZE | TYPE_GC);
574 emit_time (logbuffer, now);
575 emit_value (logbuffer, new_size);
576 //printf ("gc resized to %lld\n", new_size);
577 EXIT_LOG (logbuffer);
580 #define MAX_FRAMES 16
583 MonoMethod* methods [MAX_FRAMES];
585 static int num_frames = MAX_FRAMES / 2;
588 walk_stack (MonoMethod *method, int32_t native_offset, int32_t il_offset, mono_bool managed, void* data)
590 FrameData *frame = data;
591 if (method && frame->count < num_frames) {
592 frame->methods [frame->count++] = method;
593 //printf ("In %d %s\n", frame->count, mono_method_get_name (method));
595 return frame->count == num_frames;
599 * a note about stack walks: they can cause more profiler events to fire,
600 * so we need to make sure they don't happen after we started emitting an
601 * event, hence the collect_bt/emit_bt split.
604 collect_bt (FrameData *data)
607 mono_stack_walk_no_il (walk_stack, data);
611 emit_bt (LogBuffer *logbuffer, FrameData *data)
613 /* FIXME: this is actually tons of data and we should
614 * just output it the first time and use an id the next
616 if (data->count > num_frames)
617 printf ("bad num frames: %d\n", data->count);
618 emit_value (logbuffer, 0); /* flags */
619 emit_value (logbuffer, data->count);
620 //if (*p != data.count) {
621 // 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);}
622 while (data->count) {
623 emit_ptr (logbuffer, data->methods [--data->count]);
628 gc_alloc (MonoProfiler *prof, MonoObject *obj, MonoClass *klass)
632 int do_bt = (nocalls && runtime_inited && !notraces)? TYPE_ALLOC_BT: 0;
634 LogBuffer *logbuffer;
635 len = mono_object_get_size (obj);
636 /* account for object alignment in the heap */
641 logbuffer = ensure_logbuf (32 + MAX_FRAMES * 8);
642 now = current_time ();
643 ENTER_LOG (logbuffer, "gcalloc");
644 emit_byte (logbuffer, do_bt | TYPE_ALLOC);
645 emit_time (logbuffer, now);
646 emit_ptr (logbuffer, klass);
647 emit_obj (logbuffer, obj);
648 emit_value (logbuffer, len);
650 emit_bt (logbuffer, &data);
651 EXIT_LOG (logbuffer);
653 safe_dump (prof, logbuffer);
654 //printf ("gc alloc %s at %p\n", mono_class_get_name (klass), obj);
658 gc_moves (MonoProfiler *prof, void **objects, int num)
662 LogBuffer *logbuffer = ensure_logbuf (10 + num * 8);
663 now = current_time ();
664 ENTER_LOG (logbuffer, "gcmove");
665 emit_byte (logbuffer, TYPE_GC_MOVE | TYPE_GC);
666 emit_time (logbuffer, now);
667 emit_value (logbuffer, num);
668 for (i = 0; i < num; ++i)
669 emit_obj (logbuffer, objects [i]);
670 //printf ("gc moved %d objects\n", num/2);
671 EXIT_LOG (logbuffer);
675 gc_handle (MonoProfiler *prof, int op, int type, uintptr_t handle, MonoObject *obj)
678 LogBuffer *logbuffer = ensure_logbuf (16);
679 now = current_time ();
680 ENTER_LOG (logbuffer, "gchandle");
681 if (op == MONO_PROFILER_GC_HANDLE_CREATED)
682 emit_byte (logbuffer, TYPE_GC_HANDLE_CREATED | TYPE_GC);
683 else if (op == MONO_PROFILER_GC_HANDLE_DESTROYED)
684 emit_byte (logbuffer, TYPE_GC_HANDLE_DESTROYED | TYPE_GC);
687 emit_time (logbuffer, now);
688 emit_value (logbuffer, type);
689 emit_value (logbuffer, handle);
690 if (op == MONO_PROFILER_GC_HANDLE_CREATED)
691 emit_obj (logbuffer, obj);
692 EXIT_LOG (logbuffer);
696 push_nesting (char *p, MonoClass *klass)
701 nesting = mono_class_get_nesting_type (klass);
703 p = push_nesting (p, nesting);
707 name = mono_class_get_name (klass);
708 nspace = mono_class_get_namespace (klass);
711 p += strlen (nspace);
721 type_name (MonoClass *klass)
725 push_nesting (buf, klass);
726 p = malloc (strlen (buf) + 1);
732 image_loaded (MonoProfiler *prof, MonoImage *image, int result)
737 LogBuffer *logbuffer;
738 if (result != MONO_PROFILE_OK)
740 name = mono_image_get_filename (image);
741 nlen = strlen (name) + 1;
742 logbuffer = ensure_logbuf (16 + nlen);
743 now = current_time ();
744 ENTER_LOG (logbuffer, "image");
745 emit_byte (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
746 emit_time (logbuffer, now);
747 emit_byte (logbuffer, TYPE_IMAGE);
748 emit_ptr (logbuffer, image);
749 emit_value (logbuffer, 0); /* flags */
750 memcpy (logbuffer->data, name, nlen);
751 logbuffer->data += nlen;
752 //printf ("loaded image %p (%s)\n", image, name);
753 EXIT_LOG (logbuffer);
755 safe_dump (prof, logbuffer);
759 class_loaded (MonoProfiler *prof, MonoClass *klass, int result)
765 LogBuffer *logbuffer;
766 if (result != MONO_PROFILE_OK)
769 name = mono_type_get_name (mono_class_get_type (klass));
771 name = type_name (klass);
772 nlen = strlen (name) + 1;
773 image = mono_class_get_image (klass);
774 logbuffer = ensure_logbuf (24 + nlen);
775 now = current_time ();
776 ENTER_LOG (logbuffer, "class");
777 emit_byte (logbuffer, TYPE_END_LOAD | TYPE_METADATA);
778 emit_time (logbuffer, now);
779 emit_byte (logbuffer, TYPE_CLASS);
780 emit_ptr (logbuffer, klass);
781 emit_ptr (logbuffer, image);
782 emit_value (logbuffer, 0); /* flags */
783 memcpy (logbuffer->data, name, nlen);
784 logbuffer->data += nlen;
785 //printf ("loaded class %p (%s)\n", klass, name);
790 EXIT_LOG (logbuffer);
792 safe_dump (prof, logbuffer);
796 method_enter (MonoProfiler *prof, MonoMethod *method)
799 LogBuffer *logbuffer = ensure_logbuf (16);
800 if (logbuffer->call_depth++ > max_call_depth)
802 now = current_time ();
803 ENTER_LOG (logbuffer, "enter");
804 emit_byte (logbuffer, TYPE_ENTER | TYPE_METHOD);
805 emit_time (logbuffer, now);
806 emit_method (logbuffer, method);
807 EXIT_LOG (logbuffer);
811 method_leave (MonoProfiler *prof, MonoMethod *method)
814 LogBuffer *logbuffer = ensure_logbuf (16);
815 if (--logbuffer->call_depth > max_call_depth)
817 now = current_time ();
818 ENTER_LOG (logbuffer, "leave");
819 emit_byte (logbuffer, TYPE_LEAVE | TYPE_METHOD);
820 emit_time (logbuffer, now);
821 emit_method (logbuffer, method);
822 EXIT_LOG (logbuffer);
824 safe_dump (prof, logbuffer);
828 method_exc_leave (MonoProfiler *prof, MonoMethod *method)
831 LogBuffer *logbuffer;
834 logbuffer = ensure_logbuf (16);
835 if (--logbuffer->call_depth > max_call_depth)
837 now = current_time ();
838 ENTER_LOG (logbuffer, "eleave");
839 emit_byte (logbuffer, TYPE_EXC_LEAVE | TYPE_METHOD);
840 emit_time (logbuffer, now);
841 emit_method (logbuffer, method);
842 EXIT_LOG (logbuffer);
846 method_jitted (MonoProfiler *prof, MonoMethod *method, MonoJitInfo* jinfo, int result)
851 LogBuffer *logbuffer;
852 if (result != MONO_PROFILE_OK)
854 name = mono_method_full_name (method, 1);
855 nlen = strlen (name) + 1;
856 logbuffer = ensure_logbuf (32 + nlen);
857 now = current_time ();
858 ENTER_LOG (logbuffer, "jit");
859 emit_byte (logbuffer, TYPE_JIT | TYPE_METHOD);
860 emit_time (logbuffer, now);
861 emit_method (logbuffer, method);
862 emit_ptr (logbuffer, mono_jit_info_get_code_start (jinfo));
863 emit_value (logbuffer, mono_jit_info_get_code_size (jinfo));
864 memcpy (logbuffer->data, name, nlen);
865 logbuffer->data += nlen;
867 EXIT_LOG (logbuffer);
869 safe_dump (prof, logbuffer);
873 throw_exc (MonoProfiler *prof, MonoObject *object)
875 int do_bt = (nocalls && runtime_inited && !notraces)? TYPE_EXCEPTION_BT: 0;
878 LogBuffer *logbuffer;
881 logbuffer = ensure_logbuf (16 + MAX_FRAMES * 8);
882 now = current_time ();
883 ENTER_LOG (logbuffer, "throw");
884 emit_byte (logbuffer, do_bt | TYPE_EXCEPTION);
885 emit_time (logbuffer, now);
886 emit_obj (logbuffer, object);
888 emit_bt (logbuffer, &data);
889 EXIT_LOG (logbuffer);
893 clause_exc (MonoProfiler *prof, MonoMethod *method, int clause_type, int clause_num)
896 LogBuffer *logbuffer = ensure_logbuf (16);
897 now = current_time ();
898 ENTER_LOG (logbuffer, "clause");
899 emit_byte (logbuffer, TYPE_EXCEPTION | TYPE_CLAUSE);
900 emit_time (logbuffer, now);
901 emit_value (logbuffer, clause_type);
902 emit_value (logbuffer, clause_num);
903 emit_method (logbuffer, method);
904 EXIT_LOG (logbuffer);
908 monitor_event (MonoProfiler *profiler, MonoObject *object, MonoProfilerMonitorEvent event)
910 int do_bt = (nocalls && runtime_inited && !notraces && event == MONO_PROFILER_MONITOR_CONTENTION)? TYPE_MONITOR_BT: 0;
913 LogBuffer *logbuffer;
916 logbuffer = ensure_logbuf (16 + MAX_FRAMES * 8);
917 now = current_time ();
918 ENTER_LOG (logbuffer, "monitor");
919 emit_byte (logbuffer, (event << 4) | do_bt | TYPE_MONITOR);
920 emit_time (logbuffer, now);
921 emit_obj (logbuffer, object);
923 emit_bt (logbuffer, &data);
924 EXIT_LOG (logbuffer);
928 thread_start (MonoProfiler *prof, uintptr_t tid)
930 //printf ("thread start %p\n", (void*)tid);
935 thread_end (MonoProfiler *prof, uintptr_t tid)
938 if (TLS_GET (tlsbuffer))
939 dump_buffer (prof, TLS_GET (tlsbuffer));
941 TLS_SET (tlsbuffer, NULL);
945 thread_name (MonoProfiler *prof, uintptr_t tid, const char *name)
947 int len = strlen (name) + 1;
949 LogBuffer *logbuffer;
950 logbuffer = ensure_logbuf (10 + len);
951 now = current_time ();
952 ENTER_LOG (logbuffer, "tname");
953 emit_byte (logbuffer, TYPE_METADATA);
954 emit_time (logbuffer, now);
955 emit_byte (logbuffer, TYPE_THREAD);
956 emit_ptr (logbuffer, (void*)tid);
957 emit_value (logbuffer, 0); /* flags */
958 memcpy (logbuffer->data, name, len);
959 logbuffer->data += len;
960 EXIT_LOG (logbuffer);
964 log_shutdown (MonoProfiler *prof)
967 if (TLS_GET (tlsbuffer))
968 dump_buffer (prof, TLS_GET (tlsbuffer));
969 TLS_SET (tlsbuffer, NULL);
971 #if defined (HAVE_SYS_ZLIB)
973 gzclose (prof->gzfile);
975 if (prof->pipe_output)
983 new_filename (const char* filename)
985 time_t t = time (NULL);
986 int pid = process_id ();
995 for (p = filename; *p; p++) {
1006 if (!count_dates && !count_pids)
1007 return pstrdup (filename);
1008 snprintf (pid_buf, sizeof (pid_buf), "%d", pid);
1010 snprintf (time_buf, sizeof (time_buf), "%d%02d%02d%02d%02d%02d",
1011 1900 + ts->tm_year, 1 + ts->tm_mon, ts->tm_mday, ts->tm_hour, ts->tm_min, ts->tm_sec);
1012 s_date = strlen (time_buf);
1013 s_pid = strlen (pid_buf);
1014 d = res = malloc (strlen (filename) + s_date * count_dates + s_pid * count_pids);
1015 for (p = filename; *p; p++) {
1022 strcpy (d, time_buf);
1025 } else if (*p == 'p') {
1026 strcpy (d, pid_buf);
1029 } else if (*p == '%') {
1041 static MonoProfiler*
1042 create_profiler (const char *filename)
1046 int force_delete = 0;
1047 prof = calloc (1, sizeof (MonoProfiler));
1049 if (filename && *filename == '-') {
1055 filename = "|mprof-report -";
1057 filename = "output.mlpd";
1060 nf = new_filename (filename);
1062 int s = strlen (nf) + 32;
1063 char *p = malloc (s);
1064 snprintf (p, s, "|mprof-report '--out=%s' -", nf);
1070 prof->file = popen (nf + 1, "w");
1071 prof->pipe_output = 1;
1076 if ((f = fopen (nf, "r"))) {
1078 fprintf (stderr, "The Mono profiler won't overwrite existing filename: %s.\n", nf);
1079 fprintf (stderr, "Profiling disabled: use a different name or -FILENAME to force overwrite.\n");
1083 prof->file = fopen (nf, "wb");
1086 printf ("Cannot create profiler output: %s\n", nf);
1089 #if defined (HAVE_SYS_ZLIB)
1091 prof->gzfile = gzdopen (fileno (prof->file), "wb");
1100 printf ("Log profiler version %d.%d (format: %d)\n", LOG_VERSION_MAJOR, LOG_VERSION_MINOR, LOG_DATA_VERSION);
1101 printf ("Usage: mono --profile=log[:OPTION1[,OPTION2...]] program.exe\n");
1102 printf ("Options:\n");
1103 printf ("\thelp show this usage info\n");
1104 printf ("\t[no]alloc enable/disable recording allocation info\n");
1105 printf ("\t[no]calls enable/disable recording enter/leave method events\n");
1106 printf ("\theapshot[=MODE] record heap shot info (by default at each major collection)\n");
1107 printf ("\t heapshot MODE: every XXms milliseconds or every YYgc collections\n");
1108 printf ("\ttime=fast use a faster (but more inaccurate) timer\n");
1109 printf ("\tmaxframes=NUM collect up to NUM stack frames\n");
1110 printf ("\tcalldepth=NUM ignore method events for call chain depth bigger than NUM\n");
1111 printf ("\toutput=FILENAME write the data to file FILENAME (-FILENAME to overwrite)\n");
1112 printf ("\toutput=|PROGRAM write the data to the stdin of PROGRAM\n");
1113 printf ("\t %%t is subtituted with date and time, %%p with the pid\n");
1114 printf ("\treport create a report instead of writing the raw data to a file\n");
1115 printf ("\tzip compress the output data\n");
1121 match_option (const char* p, const char *opt, char **rval)
1123 int len = strlen (opt);
1124 if (strncmp (p, opt, len) == 0) {
1126 if (p [len] == '=' && p [len + 1]) {
1127 const char *opt = p + len + 1;
1128 const char *end = strchr (opt, ',');
1136 val = malloc (l + 1);
1137 memcpy (val, opt, l);
1142 if (p [len] == 0 || p [len] == ',') {
1144 return p + len + (p [len] == ',');
1158 set_hsmode (char* val, int allow_empty)
1162 if (allow_empty && !val)
1164 count = strtoul (val, &end, 10);
1167 if (strcmp (end, "ms") == 0)
1169 else if (strcmp (end, "gc") == 0)
1177 * declaration to silence the compiler: this is the entry point that
1178 * mono will load from the shared library and call.
1181 mono_profiler_startup (const char *desc);
1184 mono_profiler_startup (const char *desc)
1187 char *filename = NULL;
1191 int calls_enabled = 0;
1192 int allocs_enabled = 0;
1193 int events = MONO_PROFILE_GC|MONO_PROFILE_ALLOCATIONS|
1194 MONO_PROFILE_GC_MOVES|MONO_PROFILE_CLASS_EVENTS|MONO_PROFILE_THREADS|
1195 MONO_PROFILE_ENTER_LEAVE|MONO_PROFILE_JIT_COMPILATION|MONO_PROFILE_EXCEPTIONS|
1196 MONO_PROFILE_MONITOR_EVENTS|MONO_PROFILE_MODULE_EVENTS|MONO_PROFILE_GC_ROOTS;
1199 if (strncmp (p, "log", 3))
1204 for (; *p; p = opt) {
1210 if ((opt = match_option (p, "help", NULL)) != p) {
1214 if ((opt = match_option (p, "calls", NULL)) != p) {
1218 if ((opt = match_option (p, "nocalls", NULL)) != p) {
1219 events &= ~MONO_PROFILE_ENTER_LEAVE;
1223 if ((opt = match_option (p, "alloc", NULL)) != p) {
1227 if ((opt = match_option (p, "noalloc", NULL)) != p) {
1228 events &= ~MONO_PROFILE_ALLOCATIONS;
1231 if ((opt = match_option (p, "time", &val)) != p) {
1232 if (strcmp (val, "fast") == 0)
1234 else if (strcmp (val, "null") == 0)
1241 if ((opt = match_option (p, "report", NULL)) != p) {
1245 if ((opt = match_option (p, "heapshot", &val)) != p) {
1246 events &= ~MONO_PROFILE_ALLOCATIONS;
1247 events &= ~MONO_PROFILE_ENTER_LEAVE;
1250 set_hsmode (val, 1);
1253 if ((opt = match_option (p, "hsmode", &val)) != p) {
1254 fprintf (stderr, "The hsmode profiler option is obsolete, use heapshot=MODE.\n");
1255 set_hsmode (val, 0);
1258 if ((opt = match_option (p, "zip", NULL)) != p) {
1262 if ((opt = match_option (p, "output", &val)) != p) {
1266 if ((opt = match_option (p, "maxframes", &val)) != p) {
1268 num_frames = strtoul (val, &end, 10);
1269 if (num_frames > MAX_FRAMES)
1270 num_frames = MAX_FRAMES;
1272 notraces = num_frames == 0;
1275 if ((opt = match_option (p, "calldepth", &val)) != p) {
1277 max_call_depth = strtoul (val, &end, 10);
1286 if (calls_enabled) {
1287 events |= MONO_PROFILE_ENTER_LEAVE;
1291 events |= MONO_PROFILE_ALLOCATIONS;
1292 utils_init (fast_time);
1294 prof = create_profiler (filename);
1299 mono_profiler_install (prof, log_shutdown);
1300 mono_profiler_install_gc (gc_event, gc_resize);
1301 mono_profiler_install_allocation (gc_alloc);
1302 mono_profiler_install_gc_moves (gc_moves);
1303 mono_profiler_install_gc_roots (gc_handle);
1304 mono_profiler_install_class (NULL, class_loaded, NULL, NULL);
1305 mono_profiler_install_module (NULL, image_loaded, NULL, NULL);
1306 mono_profiler_install_thread (thread_start, thread_end);
1307 mono_profiler_install_thread_name (thread_name);
1308 mono_profiler_install_enter_leave (method_enter, method_leave);
1309 mono_profiler_install_jit_end (method_jitted);
1310 mono_profiler_install_exception (throw_exc, method_exc_leave, clause_exc);
1311 mono_profiler_install_monitor (monitor_event);
1312 mono_profiler_install_runtime_initialized (runtime_initialized);
1314 mono_profiler_set_events (events);
1316 TLS_INIT (tlsbuffer);