/
mono-profiler-log.c
5020 lines (4197 loc) · 132 KB
/
mono-profiler-log.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* mono-profiler-log.c: mono log profiler
*
* Authors:
* Paolo Molaro (lupus@ximian.com)
* Alex Rønne Petersen (alexrp@xamarin.com)
*
* Copyright 2010 Novell, Inc (http://www.novell.com)
* Copyright 2011 Xamarin Inc (http://www.xamarin.com)
* Licensed under the MIT license. See LICENSE file in the project root for full license information.
*/
#include <config.h>
#include <mono/metadata/assembly.h>
#include <mono/metadata/debug-helpers.h>
#include "../metadata/metadata-internals.h"
#include <mono/metadata/mono-config.h>
#include <mono/metadata/mono-gc.h>
#include <mono/metadata/mono-perfcounters.h>
#include <mono/metadata/profiler.h>
#include <mono/utils/atomic.h>
#include <mono/utils/hazard-pointer.h>
#include <mono/utils/lock-free-alloc.h>
#include <mono/utils/lock-free-queue.h>
#include <mono/utils/mono-conc-hashtable.h>
#include <mono/utils/mono-counters.h>
#include <mono/utils/mono-linked-list-set.h>
#include <mono/utils/mono-membar.h>
#include <mono/utils/mono-mmap.h>
#include <mono/utils/mono-os-mutex.h>
#include <mono/utils/mono-os-semaphore.h>
#include <mono/utils/mono-threads.h>
#include <mono/utils/mono-threads-api.h>
#include "mono-profiler-log.h"
#ifdef HAVE_DLFCN_H
#include <dlfcn.h>
#endif
#ifdef HAVE_LINK_H
#include <link.h>
#endif
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#if defined(__APPLE__)
#include <mach/mach_time.h>
#endif
#include <netinet/in.h>
#ifdef HAVE_SYS_MMAN_H
#include <sys/mman.h>
#endif
#include <sys/socket.h>
#if defined (HAVE_SYS_ZLIB)
#include <zlib.h>
#endif
#define BUFFER_SIZE (4096 * 16)
/* Worst-case size in bytes of a 64-bit value encoded with LEB128. */
#define LEB128_SIZE 10
/* Size of a value encoded as a single byte. */
#define BYTE_SIZE 1
/* Size in bytes of the event prefix (ID + time). */
#define EVENT_SIZE (BYTE_SIZE + LEB128_SIZE)
static volatile gint32 runtime_inited;
static volatile gint32 in_shutdown;
static int nocalls = 0;
static int notraces = 0;
static int use_zip = 0;
static int do_report = 0;
static int do_heap_shot = 0;
static int max_call_depth = 100;
static int command_port = 0;
static int heapshot_requested = 0;
static int sample_freq = 0;
static int do_mono_sample = 0;
static int do_debug = 0;
static int do_counters = 0;
static int do_coverage = 0;
static gboolean debug_coverage = FALSE;
static MonoProfileSamplingMode sampling_mode = MONO_PROFILER_STAT_MODE_PROCESS;
static int max_allocated_sample_hits;
// Statistics for internal profiler data structures.
static gint32 sample_allocations_ctr,
buffer_allocations_ctr;
// Statistics for profiler events.
static gint32 sync_points_ctr,
heap_objects_ctr,
heap_starts_ctr,
heap_ends_ctr,
heap_roots_ctr,
gc_events_ctr,
gc_resizes_ctr,
gc_allocs_ctr,
gc_moves_ctr,
gc_handle_creations_ctr,
gc_handle_deletions_ctr,
finalize_begins_ctr,
finalize_ends_ctr,
finalize_object_begins_ctr,
finalize_object_ends_ctr,
image_loads_ctr,
image_unloads_ctr,
assembly_loads_ctr,
assembly_unloads_ctr,
class_loads_ctr,
class_unloads_ctr,
method_entries_ctr,
method_exits_ctr,
method_exception_exits_ctr,
method_jits_ctr,
code_buffers_ctr,
exception_throws_ctr,
exception_clauses_ctr,
monitor_contentions_ctr,
monitor_acquisitions_ctr,
monitor_failures_ctr,
thread_starts_ctr,
thread_ends_ctr,
thread_names_ctr,
domain_loads_ctr,
domain_unloads_ctr,
domain_names_ctr,
context_loads_ctr,
context_unloads_ctr,
sample_ubins_ctr,
sample_usyms_ctr,
sample_hits_ctr,
counter_descriptors_ctr,
counter_samples_ctr,
perfcounter_descriptors_ctr,
perfcounter_samples_ctr,
coverage_methods_ctr,
coverage_statements_ctr,
coverage_classes_ctr,
coverage_assemblies_ctr;
static MonoLinkedListSet profiler_thread_list;
/*
* file format:
* [header] [buffer]*
*
* The file is composed by a header followed by 0 or more buffers.
* Each buffer contains events that happened on a thread: for a given thread
* buffers that appear later in the file are guaranteed to contain events
* that happened later in time. Buffers from separate threads could be interleaved,
* though.
* Buffers are not required to be aligned.
*
* header format:
* [id: 4 bytes] constant value: LOG_HEADER_ID
* [major: 1 byte] [minor: 1 byte] major and minor version of the log profiler
* [format: 1 byte] version of the data format for the rest of the file
* [ptrsize: 1 byte] size in bytes of a pointer in the profiled program
* [startup time: 8 bytes] time in milliseconds since the unix epoch when the program started
* [timer overhead: 4 bytes] approximate overhead in nanoseconds of the timer
* [flags: 4 bytes] file format flags, should be 0 for now
* [pid: 4 bytes] pid of the profiled process
* [port: 2 bytes] tcp port for server if != 0
* [args size: 4 bytes] size of args
* [args: string] arguments passed to the profiler
* [arch size: 4 bytes] size of arch
* [arch: string] architecture the profiler is running on
* [os size: 4 bytes] size of os
* [os: string] operating system the profiler is running on
*
* The multiple byte integers are in little-endian format.
*
* buffer format:
* [buffer header] [event]*
* Buffers have a fixed-size header followed by 0 or more bytes of event data.
* Timing information and other values in the event data are usually stored
* as uleb128 or sleb128 integers. To save space, as noted for each item below,
* some data is represented as a difference between the actual value and
* either the last value of the same type (like for timing information) or
* as the difference from a value stored in a buffer header.
*
* For timing information the data is stored as uleb128, since timing
* increases in a monotonic way in each thread: the value is the number of
* nanoseconds to add to the last seen timing data in a buffer. The first value
* in a buffer will be calculated from the time_base field in the buffer head.
*
* Object or heap sizes are stored as uleb128.
* Pointer differences are stored as sleb128, instead.
*
* If an unexpected value is found, the rest of the buffer should be ignored,
* as generally the later values need the former to be interpreted correctly.
*
* buffer header format:
* [bufid: 4 bytes] constant value: BUF_ID
* [len: 4 bytes] size of the data following the buffer header
* [time_base: 8 bytes] time base in nanoseconds since an unspecified epoch
* [ptr_base: 8 bytes] base value for pointers
* [obj_base: 8 bytes] base value for object addresses
* [thread id: 8 bytes] system-specific thread ID (pthread_t for example)
* [method_base: 8 bytes] base value for MonoMethod pointers
*
* event format:
* [extended info: upper 4 bits] [type: lower 4 bits]
* [time diff: uleb128] nanoseconds since last timing
* [data]*
* The data that follows depends on type and the extended info.
* Type is one of the enum values in mono-profiler-log.h: TYPE_ALLOC, TYPE_GC,
* TYPE_METADATA, TYPE_METHOD, TYPE_EXCEPTION, TYPE_MONITOR, TYPE_HEAP.
* The extended info bits are interpreted based on type, see
* each individual event description below.
* strings are represented as a 0-terminated utf8 sequence.
*
* backtrace format:
* [num: uleb128] number of frames following
* [frame: sleb128]* mum MonoMethod* as a pointer difference from the last such
* pointer or the buffer method_base
*
* type alloc format:
* type: TYPE_ALLOC
* exinfo: flags: TYPE_ALLOC_BT
* [ptr: sleb128] class as a byte difference from ptr_base
* [obj: sleb128] object address as a byte difference from obj_base
* [size: uleb128] size of the object in the heap
* If the TYPE_ALLOC_BT flag is set, a backtrace follows.
*
* type GC format:
* type: TYPE_GC
* exinfo: one of TYPE_GC_EVENT, TYPE_GC_RESIZE, TYPE_GC_MOVE, TYPE_GC_HANDLE_CREATED[_BT],
* TYPE_GC_HANDLE_DESTROYED[_BT], TYPE_GC_FINALIZE_START, TYPE_GC_FINALIZE_END,
* TYPE_GC_FINALIZE_OBJECT_START, TYPE_GC_FINALIZE_OBJECT_END
* if exinfo == TYPE_GC_RESIZE
* [heap_size: uleb128] new heap size
* if exinfo == TYPE_GC_EVENT
* [event type: byte] GC event (MONO_GC_EVENT_* from profiler.h)
* [generation: byte] GC generation event refers to
* if exinfo == TYPE_GC_MOVE
* [num_objects: uleb128] number of object moves that follow
* [objaddr: sleb128]+ num_objects object pointer differences from obj_base
* num is always an even number: the even items are the old
* addresses, the odd numbers are the respective new object addresses
* if exinfo == TYPE_GC_HANDLE_CREATED[_BT]
* [handle_type: uleb128] GC handle type (System.Runtime.InteropServices.GCHandleType)
* upper bits reserved as flags
* [handle: uleb128] GC handle value
* [objaddr: sleb128] object pointer differences from obj_base
* If exinfo == TYPE_GC_HANDLE_CREATED_BT, a backtrace follows.
* if exinfo == TYPE_GC_HANDLE_DESTROYED[_BT]
* [handle_type: uleb128] GC handle type (System.Runtime.InteropServices.GCHandleType)
* upper bits reserved as flags
* [handle: uleb128] GC handle value
* If exinfo == TYPE_GC_HANDLE_DESTROYED_BT, a backtrace follows.
* if exinfo == TYPE_GC_FINALIZE_OBJECT_{START,END}
* [object: sleb128] the object as a difference from obj_base
*
* type metadata format:
* type: TYPE_METADATA
* exinfo: one of: TYPE_END_LOAD, TYPE_END_UNLOAD (optional for TYPE_THREAD and TYPE_DOMAIN)
* [mtype: byte] metadata type, one of: TYPE_CLASS, TYPE_IMAGE, TYPE_ASSEMBLY, TYPE_DOMAIN,
* TYPE_THREAD, TYPE_CONTEXT
* [pointer: sleb128] pointer of the metadata type depending on mtype
* if mtype == TYPE_CLASS
* [image: sleb128] MonoImage* as a pointer difference from ptr_base
* [name: string] full class name
* if mtype == TYPE_IMAGE
* [name: string] image file name
* if mtype == TYPE_ASSEMBLY
* [name: string] assembly name
* if mtype == TYPE_DOMAIN && exinfo == 0
* [name: string] domain friendly name
* if mtype == TYPE_CONTEXT
* [domain: sleb128] domain id as pointer
* if mtype == TYPE_THREAD && exinfo == 0
* [name: string] thread name
*
* type method format:
* type: TYPE_METHOD
* exinfo: one of: TYPE_LEAVE, TYPE_ENTER, TYPE_EXC_LEAVE, TYPE_JIT
* [method: sleb128] MonoMethod* as a pointer difference from the last such
* pointer or the buffer method_base
* if exinfo == TYPE_JIT
* [code address: sleb128] pointer to the native code as a diff from ptr_base
* [code size: uleb128] size of the generated code
* [name: string] full method name
*
* type exception format:
* type: TYPE_EXCEPTION
* exinfo: TYPE_THROW_BT flag or one of: TYPE_CLAUSE
* if exinfo == TYPE_CLAUSE
* [clause type: byte] MonoExceptionEnum enum value
* [clause index: uleb128] index of the current clause
* [method: sleb128] MonoMethod* as a pointer difference from the last such
* pointer or the buffer method_base
* else
* [object: sleb128] the exception object as a difference from obj_base
* if exinfo has TYPE_THROW_BT set, a backtrace follows.
*
* type runtime format:
* type: TYPE_RUNTIME
* exinfo: one of: TYPE_JITHELPER
* if exinfo == TYPE_JITHELPER
* [type: byte] MonoProfilerCodeBufferType enum value
* [buffer address: sleb128] pointer to the native code as a diff from ptr_base
* [buffer size: uleb128] size of the generated code
* if type == MONO_PROFILER_CODE_BUFFER_SPECIFIC_TRAMPOLINE
* [name: string] buffer description name
*
* type monitor format:
* type: TYPE_MONITOR
* exinfo: TYPE_MONITOR_BT flag and one of: MONO_PROFILER_MONITOR_(CONTENTION|FAIL|DONE)
* [object: sleb128] the lock object as a difference from obj_base
* if exinfo.low3bits == MONO_PROFILER_MONITOR_CONTENTION
* If the TYPE_MONITOR_BT flag is set, a backtrace follows.
*
* type heap format
* type: TYPE_HEAP
* exinfo: one of TYPE_HEAP_START, TYPE_HEAP_END, TYPE_HEAP_OBJECT, TYPE_HEAP_ROOT
* if exinfo == TYPE_HEAP_OBJECT
* [object: sleb128] the object as a difference from obj_base
* [class: sleb128] the object MonoClass* as a difference from ptr_base
* [size: uleb128] size of the object on the heap
* [num_refs: uleb128] number of object references
* each referenced objref is preceded by a uleb128 encoded offset: the
* first offset is from the object address and each next offset is relative
* to the previous one
* [objrefs: sleb128]+ object referenced as a difference from obj_base
* The same object can appear multiple times, but only the first time
* with size != 0: in the other cases this data will only be used to
* provide additional referenced objects.
* if exinfo == TYPE_HEAP_ROOT
* [num_roots: uleb128] number of root references
* [num_gc: uleb128] number of major gcs
* [object: sleb128] the object as a difference from obj_base
* [root_type: byte] the root_type: MonoProfileGCRootType (profiler.h)
* [extra_info: uleb128] the extra_info value
* object, root_type and extra_info are repeated num_roots times
*
* type sample format
* type: TYPE_SAMPLE
* exinfo: one of TYPE_SAMPLE_HIT, TYPE_SAMPLE_USYM, TYPE_SAMPLE_UBIN, TYPE_SAMPLE_COUNTERS_DESC, TYPE_SAMPLE_COUNTERS
* if exinfo == TYPE_SAMPLE_HIT
* [thread: sleb128] thread id as difference from ptr_base
* [count: uleb128] number of following instruction addresses
* [ip: sleb128]* instruction pointer as difference from ptr_base
* [mbt_count: uleb128] number of managed backtrace frames
* [method: sleb128]* MonoMethod* as a pointer difference from the last such
* pointer or the buffer method_base (the first such method can be also indentified by ip, but this is not neccessarily true)
* if exinfo == TYPE_SAMPLE_USYM
* [address: sleb128] symbol address as a difference from ptr_base
* [size: uleb128] symbol size (may be 0 if unknown)
* [name: string] symbol name
* if exinfo == TYPE_SAMPLE_UBIN
* [address: sleb128] address where binary has been loaded
* [offset: uleb128] file offset of mapping (the same file can be mapped multiple times)
* [size: uleb128] memory size
* [name: string] binary name
* if exinfo == TYPE_SAMPLE_COUNTERS_DESC
* [len: uleb128] number of counters
* for i = 0 to len
* [section: uleb128] section of counter
* if section == MONO_COUNTER_PERFCOUNTERS:
* [section_name: string] section name of counter
* [name: string] name of counter
* [type: byte] type of counter
* [unit: byte] unit of counter
* [variance: byte] variance of counter
* [index: uleb128] unique index of counter
* if exinfo == TYPE_SAMPLE_COUNTERS
* while true:
* [index: uleb128] unique index of counter
* if index == 0:
* break
* [type: byte] type of counter value
* if type == string:
* if value == null:
* [0: uleb128] 0 -> value is null
* else:
* [1: uleb128] 1 -> value is not null
* [value: string] counter value
* else:
* [value: uleb128/sleb128/double] counter value, can be sleb128, uleb128 or double (determined by using type)
*
* type coverage format
* type: TYPE_COVERAGE
* exinfo: one of TYPE_COVERAGE_METHOD, TYPE_COVERAGE_STATEMENT, TYPE_COVERAGE_ASSEMBLY, TYPE_COVERAGE_CLASS
* if exinfo == TYPE_COVERAGE_METHOD
* [assembly: string] name of assembly
* [class: string] name of the class
* [name: string] name of the method
* [signature: string] the signature of the method
* [filename: string] the file path of the file that contains this method
* [token: uleb128] the method token
* [method_id: uleb128] an ID for this data to associate with the buffers of TYPE_COVERAGE_STATEMENTS
* [len: uleb128] the number of TYPE_COVERAGE_BUFFERS associated with this method
* if exinfo == TYPE_COVERAGE_STATEMENTS
* [method_id: uleb128] an the TYPE_COVERAGE_METHOD buffer to associate this with
* [offset: uleb128] the il offset relative to the previous offset
* [counter: uleb128] the counter for this instruction
* [line: uleb128] the line of filename containing this instruction
* [column: uleb128] the column containing this instruction
* if exinfo == TYPE_COVERAGE_ASSEMBLY
* [name: string] assembly name
* [guid: string] assembly GUID
* [filename: string] assembly filename
* [number_of_methods: uleb128] the number of methods in this assembly
* [fully_covered: uleb128] the number of fully covered methods
* [partially_covered: uleb128] the number of partially covered methods
* currently partially_covered will always be 0, and fully_covered is the
* number of methods that are fully and partially covered.
* if exinfo == TYPE_COVERAGE_CLASS
* [name: string] assembly name
* [class: string] class name
* [number_of_methods: uleb128] the number of methods in this class
* [fully_covered: uleb128] the number of fully covered methods
* [partially_covered: uleb128] the number of partially covered methods
* currently partially_covered will always be 0, and fully_covered is the
* number of methods that are fully and partially covered.
*
* type meta format:
* type: TYPE_META
* exinfo: one of: TYPE_SYNC_POINT
* if exinfo == TYPE_SYNC_POINT
* [type: byte] MonoProfilerSyncPointType enum value
*/
// Pending data to be written to the log, for a single thread.
// Threads periodically flush their own LogBuffers by calling safe_send
typedef struct _LogBuffer LogBuffer;
struct _LogBuffer {
// Next (older) LogBuffer in processing queue
LogBuffer *next;
uint64_t time_base;
uint64_t last_time;
uintptr_t ptr_base;
uintptr_t method_base;
uintptr_t last_method;
uintptr_t obj_base;
uintptr_t thread_id;
// Bytes allocated for this LogBuffer
int size;
// Start of currently unused space in buffer
unsigned char* cursor;
// Pointer to start-of-structure-plus-size (for convenience)
unsigned char* buf_end;
// Start of data in buffer. Contents follow "buffer format" described above.
unsigned char buf [1];
};
typedef struct {
MonoLinkedListSetNode node;
// Convenience pointer to the profiler structure.
MonoProfiler *profiler;
// Was this thread added to the LLS?
gboolean attached;
// The current log buffer for this thread.
LogBuffer *buffer;
// Methods referenced by events in `buffer`, see `MethodInfo`.
GPtrArray *methods;
// Current call depth for enter/leave events.
int call_depth;
// Indicates whether this thread is currently writing to its `buffer`.
gboolean busy;
// Has this thread written a thread end event to `buffer`?
gboolean ended;
} MonoProfilerThread;
static uintptr_t
thread_id (void)
{
return (uintptr_t) mono_native_thread_id_get ();
}
static uintptr_t
process_id (void)
{
#ifdef HOST_WIN32
return (uintptr_t) GetCurrentProcessId ();
#else
return (uintptr_t) getpid ();
#endif
}
#ifdef __APPLE__
static mach_timebase_info_data_t timebase_info;
#elif defined (HOST_WIN32)
static LARGE_INTEGER pcounter_freq;
#endif
#define TICKS_PER_SEC 1000000000LL
static uint64_t
current_time (void)
{
#ifdef __APPLE__
uint64_t time = mach_absolute_time ();
time *= timebase_info.numer;
time /= timebase_info.denom;
return time;
#elif defined (HOST_WIN32)
LARGE_INTEGER value;
QueryPerformanceCounter (&value);
return value.QuadPart * TICKS_PER_SEC / pcounter_freq.QuadPart;
#elif defined (CLOCK_MONOTONIC)
struct timespec tspec;
clock_gettime (CLOCK_MONOTONIC, &tspec);
return ((uint64_t) tspec.tv_sec * TICKS_PER_SEC + tspec.tv_nsec);
#else
struct timeval tv;
gettimeofday (&tv, NULL);
return ((uint64_t) tv.tv_sec * TICKS_PER_SEC + tv.tv_usec * 1000);
#endif
}
static int timer_overhead;
static void
init_time (void)
{
#ifdef __APPLE__
mach_timebase_info (&timebase_info);
#elif defined (HOST_WIN32)
QueryPerformanceFrequency (&pcounter_freq);
#endif
uint64_t time_start = current_time ();
for (int i = 0; i < 256; ++i)
current_time ();
uint64_t time_end = current_time ();
timer_overhead = (time_end - time_start) / 256;
}
/*
* These macros create a scope to avoid leaking the buffer returned
* from ensure_logbuf () as it may have been invalidated by a GC
* thread during STW. If you called init_thread () with add_to_lls =
* FALSE, then don't use these macros.
*/
#define ENTER_LOG(COUNTER, BUFFER, SIZE) \
do { \
MonoProfilerThread *thread__ = PROF_TLS_GET (); \
if (thread__->attached) \
buffer_lock (); \
g_assert (!thread__->busy && "Why are we trying to write a new event while already writing one?"); \
thread__->busy = TRUE; \
InterlockedIncrement ((COUNTER)); \
LogBuffer *BUFFER = ensure_logbuf_unsafe ((SIZE))
#define EXIT_LOG_EXPLICIT(SEND, REQUESTS) \
thread__->busy = FALSE; \
if ((SEND)) \
send_log_unsafe (FALSE, TRUE); \
if (thread__->attached) \
buffer_unlock (); \
if ((REQUESTS)) \
process_requests (); \
} while (0)
#define EXIT_LOG EXIT_LOG_EXPLICIT (TRUE, TRUE)
static volatile gint32 buffer_rwlock_count;
static volatile gpointer buffer_rwlock_exclusive;
// Can be used recursively.
static void
buffer_lock (void)
{
/*
* If the thread holding the exclusive lock tries to modify the
* reader count, just make it a no-op. This way, we also avoid
* invoking the GC safe point macros below, which could break if
* done from a thread that is currently the initiator of STW.
*
* In other words, we rely on the fact that the GC thread takes
* the exclusive lock in the gc_event () callback when the world
* is about to stop.
*/
if (InterlockedReadPointer (&buffer_rwlock_exclusive) != (gpointer) thread_id ()) {
MONO_ENTER_GC_SAFE;
while (InterlockedReadPointer (&buffer_rwlock_exclusive))
mono_thread_info_yield ();
InterlockedIncrement (&buffer_rwlock_count);
MONO_EXIT_GC_SAFE;
}
mono_memory_barrier ();
}
static void
buffer_unlock (void)
{
mono_memory_barrier ();
// See the comment in buffer_lock ().
if (InterlockedReadPointer (&buffer_rwlock_exclusive) == (gpointer) thread_id ())
return;
g_assert (InterlockedRead (&buffer_rwlock_count) && "Why are we trying to decrement a zero reader count?");
InterlockedDecrement (&buffer_rwlock_count);
}
// Cannot be used recursively.
static void
buffer_lock_excl (void)
{
gpointer tid = (gpointer) thread_id ();
g_assert (InterlockedReadPointer (&buffer_rwlock_exclusive) != tid && "Why are we taking the exclusive lock twice?");
MONO_ENTER_GC_SAFE;
while (InterlockedCompareExchangePointer (&buffer_rwlock_exclusive, tid, 0))
mono_thread_info_yield ();
while (InterlockedRead (&buffer_rwlock_count))
mono_thread_info_yield ();
MONO_EXIT_GC_SAFE;
mono_memory_barrier ();
}
static void
buffer_unlock_excl (void)
{
mono_memory_barrier ();
g_assert (InterlockedReadPointer (&buffer_rwlock_exclusive) && "Why is the exclusive lock not held?");
g_assert (InterlockedReadPointer (&buffer_rwlock_exclusive) == (gpointer) thread_id () && "Why does another thread hold the exclusive lock?");
g_assert (!InterlockedRead (&buffer_rwlock_count) && "Why are there readers when the exclusive lock is held?");
InterlockedWritePointer (&buffer_rwlock_exclusive, NULL);
}
typedef struct _BinaryObject BinaryObject;
struct _BinaryObject {
BinaryObject *next;
void *addr;
char *name;
};
struct _MonoProfiler {
FILE* file;
#if defined (HAVE_SYS_ZLIB)
gzFile gzfile;
#endif
char *args;
uint64_t startup_time;
int pipe_output;
int command_port;
int server_socket;
int pipes [2];
MonoNativeThreadId helper_thread;
MonoNativeThreadId writer_thread;
MonoNativeThreadId dumper_thread;
volatile gint32 run_writer_thread;
MonoLockFreeAllocSizeClass writer_entry_size_class;
MonoLockFreeAllocator writer_entry_allocator;
MonoLockFreeQueue writer_queue;
MonoSemType writer_queue_sem;
MonoConcurrentHashTable *method_table;
mono_mutex_t method_table_mutex;
volatile gint32 run_dumper_thread;
MonoLockFreeQueue dumper_queue;
MonoSemType dumper_queue_sem;
MonoLockFreeAllocSizeClass sample_size_class;
MonoLockFreeAllocator sample_allocator;
MonoLockFreeQueue sample_reuse_queue;
BinaryObject *binary_objects;
GPtrArray *coverage_filters;
};
typedef struct {
MonoLockFreeQueueNode node;
GPtrArray *methods;
LogBuffer *buffer;
} WriterQueueEntry;
#define WRITER_ENTRY_BLOCK_SIZE (mono_pagesize ())
typedef struct {
MonoMethod *method;
MonoJitInfo *ji;
uint64_t time;
} MethodInfo;
#ifdef HOST_WIN32
#define PROF_TLS_SET(VAL) (TlsSetValue (profiler_tls, (VAL)))
#define PROF_TLS_GET() ((MonoProfilerThread *) TlsGetValue (profiler_tls))
#define PROF_TLS_INIT() (profiler_tls = TlsAlloc ())
#define PROF_TLS_FREE() (TlsFree (profiler_tls))
static DWORD profiler_tls;
#elif HAVE_KW_THREAD
#define PROF_TLS_SET(VAL) (profiler_tls = (VAL))
#define PROF_TLS_GET() (profiler_tls)
#define PROF_TLS_INIT()
#define PROF_TLS_FREE()
static __thread MonoProfilerThread *profiler_tls;
#else
#define PROF_TLS_SET(VAL) (pthread_setspecific (profiler_tls, (VAL)))
#define PROF_TLS_GET() ((MonoProfilerThread *) pthread_getspecific (profiler_tls))
#define PROF_TLS_INIT() (pthread_key_create (&profiler_tls, NULL))
#define PROF_TLS_FREE() (pthread_key_delete (&profiler_tls))
static pthread_key_t profiler_tls;
#endif
static char*
pstrdup (const char *s)
{
int len = strlen (s) + 1;
char *p = (char *)malloc (len);
memcpy (p, s, len);
return p;
}
static void *
alloc_buffer (int size)
{
return mono_valloc (NULL, size, MONO_MMAP_READ | MONO_MMAP_WRITE | MONO_MMAP_ANON | MONO_MMAP_PRIVATE, MONO_MEM_ACCOUNT_PROFILER);
}
static void
free_buffer (void *buf, int size)
{
mono_vfree (buf, size, MONO_MEM_ACCOUNT_PROFILER);
}
static LogBuffer*
create_buffer (void)
{
LogBuffer* buf = (LogBuffer *) alloc_buffer (BUFFER_SIZE);
InterlockedIncrement (&buffer_allocations_ctr);
buf->size = BUFFER_SIZE;
buf->time_base = current_time ();
buf->last_time = buf->time_base;
buf->buf_end = (unsigned char*)buf + buf->size;
buf->cursor = buf->buf;
return buf;
}
/*
* Must be called with the reader lock held if thread is the current thread, or
* the exclusive lock if thread is a different thread. However, if thread is
* the current thread, and init_thread () was called with add_to_lls = FALSE,
* then no locking is necessary.
*/
static void
init_buffer_state (MonoProfilerThread *thread)
{
thread->buffer = create_buffer ();
thread->methods = NULL;
}
static void
clear_hazard_pointers (MonoThreadHazardPointers *hp)
{
mono_hazard_pointer_clear (hp, 0);
mono_hazard_pointer_clear (hp, 1);
mono_hazard_pointer_clear (hp, 2);
}
static MonoProfilerThread *
init_thread (MonoProfiler *prof, gboolean add_to_lls)
{
MonoProfilerThread *thread = PROF_TLS_GET ();
/*
* Sometimes we may try to initialize a thread twice. One example is the
* main thread: We initialize it when setting up the profiler, but we will
* also get a thread_start () callback for it. Another example is when
* attaching new threads to the runtime: We may get a gc_alloc () callback
* for that thread's thread object (where we initialize it), soon followed
* by a thread_start () callback.
*
* These cases are harmless anyhow. Just return if we've already done the
* initialization work.
*/
if (thread)
return thread;
thread = malloc (sizeof (MonoProfilerThread));
thread->node.key = thread_id ();
thread->profiler = prof;
thread->attached = add_to_lls;
thread->call_depth = 0;
thread->busy = 0;
thread->ended = FALSE;
init_buffer_state (thread);
/*
* Some internal profiler threads don't need to be cleaned up
* by the main thread on shutdown.
*/
if (add_to_lls) {
MonoThreadHazardPointers *hp = mono_hazard_pointer_get ();
g_assert (mono_lls_insert (&profiler_thread_list, hp, &thread->node) && "Why can't we insert the thread in the LLS?");
clear_hazard_pointers (hp);
}
PROF_TLS_SET (thread);
return thread;
}
// Only valid if init_thread () was called with add_to_lls = FALSE.
static void
deinit_thread (MonoProfilerThread *thread)
{
g_assert (!thread->attached && "Why are we manually freeing an attached thread?");
free (thread);
PROF_TLS_SET (NULL);
}
static LogBuffer *
ensure_logbuf_inner (LogBuffer *old, int bytes)
{
if (old && old->cursor + bytes + 100 < old->buf_end)
return old;
LogBuffer *new_ = create_buffer ();
new_->next = old;
return new_;
}
// Only valid if init_thread () was called with add_to_lls = FALSE.
static LogBuffer *
ensure_logbuf_unsafe (int bytes)
{
MonoProfilerThread *thread = PROF_TLS_GET ();
LogBuffer *old = thread->buffer;
LogBuffer *new_ = ensure_logbuf_inner (old, bytes);
if (new_ == old)
return old; // Still enough space.
thread->buffer = new_;
return new_;
}
static void
encode_uleb128 (uint64_t value, uint8_t *buf, uint8_t **endbuf)
{
uint8_t *p = buf;
do {
uint8_t b = value & 0x7f;
value >>= 7;
if (value != 0) /* more bytes to come */
b |= 0x80;
*p ++ = b;
} while (value);
*endbuf = p;
}
static void
encode_sleb128 (intptr_t value, uint8_t *buf, uint8_t **endbuf)
{
int more = 1;
int negative = (value < 0);
unsigned int size = sizeof (intptr_t) * 8;
uint8_t byte;
uint8_t *p = buf;
while (more) {
byte = value & 0x7f;
value >>= 7;
/* the following is unnecessary if the
* implementation of >>= uses an arithmetic rather
* than logical shift for a signed left operand
*/
if (negative)
/* sign extend */
value |= - ((intptr_t) 1 <<(size - 7));
/* sign bit of byte is second high order bit (0x40) */
if ((value == 0 && !(byte & 0x40)) ||
(value == -1 && (byte & 0x40)))
more = 0;
else
byte |= 0x80;
*p ++= byte;
}
*endbuf = p;
}
static void
emit_byte (LogBuffer *logbuffer, int value)
{
logbuffer->cursor [0] = value;
logbuffer->cursor++;
g_assert (logbuffer->cursor <= logbuffer->buf_end && "Why are we writing past the buffer end?");
}
static void
emit_value (LogBuffer *logbuffer, int value)
{
encode_uleb128 (value, logbuffer->cursor, &logbuffer->cursor);
g_assert (logbuffer->cursor <= logbuffer->buf_end && "Why are we writing past the buffer end?");
}
static void
emit_time (LogBuffer *logbuffer, uint64_t value)
{
uint64_t tdiff = value - logbuffer->last_time;
encode_uleb128 (tdiff, logbuffer->cursor, &logbuffer->cursor);
logbuffer->last_time = value;
g_assert (logbuffer->cursor <= logbuffer->buf_end && "Why are we writing past the buffer end?");
}
static void
emit_event_time (LogBuffer *logbuffer, int event, uint64_t time)
{
emit_byte (logbuffer, event);
emit_time (logbuffer, time);
}
static void
emit_event (LogBuffer *logbuffer, int event)
{
emit_event_time (logbuffer, event, current_time ());
}
static void
emit_svalue (LogBuffer *logbuffer, int64_t value)
{
encode_sleb128 (value, logbuffer->cursor, &logbuffer->cursor);
g_assert (logbuffer->cursor <= logbuffer->buf_end && "Why are we writing past the buffer end?");
}
static void
emit_uvalue (LogBuffer *logbuffer, uint64_t value)
{
encode_uleb128 (value, logbuffer->cursor, &logbuffer->cursor);
g_assert (logbuffer->cursor <= logbuffer->buf_end && "Why are we writing past the buffer end?");
}
static void
emit_ptr (LogBuffer *logbuffer, void *ptr)
{
if (!logbuffer->ptr_base)
logbuffer->ptr_base = (uintptr_t) ptr;
emit_svalue (logbuffer, (intptr_t) ptr - logbuffer->ptr_base);
g_assert (logbuffer->cursor <= logbuffer->buf_end && "Why are we writing past the buffer end?");
}