-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
proflog.c
4973 lines (4360 loc) · 133 KB
/
proflog.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
/*
* proflog.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 "../mini/jit.h"
#include "../metadata/metadata-internals.h"
#include <mono/metadata/profiler.h>
#include <mono/metadata/threads.h>
#include <mono/metadata/mono-gc.h>
#include <mono/metadata/debug-helpers.h>
#include <mono/metadata/mono-perfcounters.h>
#include <mono/metadata/appdomain.h>
#include <mono/metadata/assembly.h>
#include <mono/metadata/tokentype.h>
#include <mono/metadata/tabledefs.h>
#include <mono/utils/atomic.h>
#include <mono/utils/mono-membar.h>
#include <mono/utils/mono-mmap.h>
#include <mono/utils/mono-counters.h>
#include <mono/utils/mono-os-mutex.h>
#include <mono/utils/mono-conc-hashtable.h>
#include <mono/utils/lock-free-alloc.h>
#include <mono/utils/lock-free-queue.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <glib.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#ifdef HAVE_SCHED_GETAFFINITY
#include <sched.h>
#endif
#include <fcntl.h>
#include <errno.h>
#if defined(HOST_WIN32) || defined(DISABLE_SOCKETS)
#define DISABLE_HELPER_THREAD 1
#endif
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#ifdef HAVE_DLFCN_H
#include <dlfcn.h>
#endif
#ifdef HAVE_EXECINFO_H
#include <execinfo.h>
#endif
#ifdef HAVE_LINK_H
#include <link.h>
#endif
#ifndef DISABLE_HELPER_THREAD
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/select.h>
#endif
#ifdef HOST_WIN32
#include <windows.h>
#else
#include <pthread.h>
#endif
#ifdef HAVE_SYS_STAT_H
#include <sys/stat.h>
#endif
#include "utils.c"
#include "proflog.h"
#if defined (HAVE_SYS_ZLIB)
#include <zlib.h>
#endif
#if defined(__linux__)
#include <unistd.h>
#include <sys/syscall.h>
#ifdef ENABLE_PERF_EVENTS
#include <linux/perf_event.h>
#define USE_PERF_EVENTS 1
static int read_perf_mmap (MonoProfiler* prof, int cpu);
#endif
#endif
#define BUFFER_SIZE (4096 * 16)
/* Worst-case size in bytes of a 64-bit value encoded with LEB128. */
#define LEB128_SIZE 10
/* Size in bytes of the event ID prefix. */
#define EVENT_SIZE 1
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 volatile int runtime_inited = 0;
static int need_helper_thread = 0;
static int command_port = 0;
static int heapshot_requested = 0;
static int sample_type = 0;
static int sample_freq = 0;
static int do_mono_sample = 0;
static int in_shutdown = 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;
static gint32 sample_hits;
static gint32 sample_flushes;
static gint32 sample_allocations;
static gint32 buffer_allocations;
static gint32 thread_starts;
static gint32 thread_ends;
static gint32 domain_loads;
static gint32 domain_unloads;
static gint32 context_loads;
static gint32 context_unloads;
static gint32 assembly_loads;
static gint32 assembly_unloads;
static gint32 image_loads;
static gint32 image_unloads;
static gint32 class_loads;
static gint32 class_unloads;
typedef struct _LogBuffer LogBuffer;
/*
* 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
* [sysid: 2 bytes] operating system and architecture identifier
*
* 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] [data]*
* The data that follows depends on type and the extended info.
* Type is one of the enum values in proflog.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:
* [flags: uleb128] must be 0
* [num: uleb128] number of frames following
* [frame: sleb128]* num MonoMethod pointers as differences from ptr_base
*
* type alloc format:
* type: TYPE_ALLOC
* exinfo: flags: TYPE_ALLOC_BT
* [time diff: uleb128] nanoseconds since last timing
* [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]
* [time diff: uleb128] nanoseconds since last timing
* if exinfo == TYPE_GC_RESIZE
* [heap_size: uleb128] new heap size
* if exinfo == TYPE_GC_EVENT
* [event type: uleb128] GC event (MONO_GC_EVENT_* from profiler.h)
* [generation: uleb128] 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.
*
* type metadata format:
* type: TYPE_METADATA
* exinfo: one of: TYPE_END_LOAD, TYPE_END_UNLOAD (optional for TYPE_THREAD and TYPE_DOMAIN)
* [time diff: uleb128] nanoseconds since last timing
* [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
* [flags: uleb128] must be 0
* [name: string] full class name
* if mtype == TYPE_IMAGE
* [flags: uleb128] must be 0
* [name: string] image file name
* if mtype == TYPE_ASSEMBLY
* [flags: uleb128] must be 0
* [name: string] assembly name
* if mtype == TYPE_DOMAIN
* [flags: uleb128] must be 0
* if mtype == TYPE_DOMAIN && exinfo == 0
* [name: string] domain friendly name
* if mtype == TYPE_CONTEXT
* [flags: uleb128] must be 0
* [domain: sleb128] domain id as pointer
* if mtype == TYPE_THREAD && (format_version < 11 || (format_version > 10 && exinfo == 0))
* [flags: uleb128] must be 0
* [name: string] thread name
*
* type method format:
* type: TYPE_METHOD
* exinfo: one of: TYPE_LEAVE, TYPE_ENTER, TYPE_EXC_LEAVE, TYPE_JIT
* [time diff: uleb128] nanoseconds since last timing
* [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 runtime format:
* type: TYPE_RUNTIME
* exinfo: one of: TYPE_JITHELPER
* [time diff: uleb128] nanoseconds since last timing
* if exinfo == TYPE_JITHELPER
* [type: uleb128] 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)
* [time diff: uleb128] nanoseconds since last timing
* [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_START
* [time diff: uleb128] nanoseconds since last timing
* if exinfo == TYPE_HEAP_END
* [time diff: uleb128] nanoseconds since last timing
* 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
* if (format version > 1) 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: uleb128] 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
* [sample_type: uleb128] type of sample (SAMPLE_*)
* [timestamp: uleb128] nanoseconds since startup (note: different from other timestamps!)
* if (format_version > 10)
* [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
* if (format_version > 5)
* [mbt_count: uleb128] number of managed backtrace info triplets (method + IL offset + native offset)
* [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)
* [il_offset: sleb128]* IL offset inside method where the hit occurred
* [native_offset: sleb128]* native offset inside method where the hit occurred
* 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
* [time diff: uleb128] nanoseconds since last timing
* [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: uleb128] type of counter
* [unit: uleb128] unit of counter
* [variance: uleb128] variance of counter
* [index: uleb128] unique index of counter
* if exinfo == TYPE_SAMPLE_COUNTERS
* [timestamp: uleb128] sampling timestamp
* while true:
* [index: uleb128] unique index of counter
* if index == 0:
* break
* [type: uleb128] 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.
*/
/*
* Format oddities that we ought to fix:
*
* - Methods written in emit_bt () should be based on the buffer's base
* method instead of the base pointer.
* - The TYPE_SAMPLE_HIT event contains (currently) pointless data like
* always-one unmanaged frame count and always-zero IL offsets.
*
* These are mostly small things and are not worth a format change by
* themselves. They should be done when some other major change has to
* be done to the format.
*/
// Pending data to be written to the log, for a single thread.
// Threads periodically flush their own LogBuffers by calling safe_send
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;
int locked;
int call_depth;
// 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];
};
static inline void
ign_res (int G_GNUC_UNUSED unused, ...)
{
}
#define ENTER_LOG(lb,str) if ((lb)->locked) {ign_res (write(2, str, strlen(str))); ign_res (write(2, "\n", 1));return;} else {(lb)->locked++;}
#define EXIT_LOG(lb) (lb)->locked--;
typedef struct _BinaryObject BinaryObject;
struct _BinaryObject {
BinaryObject *next;
void *addr;
char *name;
};
struct _MonoProfiler {
FILE* file;
#if defined (HAVE_SYS_ZLIB)
gzFile gzfile;
#endif
uint64_t startup_time;
int pipe_output;
int last_gc_gen_started;
int command_port;
int server_socket;
int pipes [2];
#ifndef HOST_WIN32
pthread_t helper_thread;
pthread_t writer_thread;
pthread_t dumper_thread;
#endif
volatile gint32 run_writer_thread;
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 _WriterQueueEntry WriterQueueEntry;
struct _WriterQueueEntry {
MonoLockFreeQueueNode node;
GPtrArray *methods;
LogBuffer *buffer;
};
typedef struct _MethodInfo MethodInfo;
struct _MethodInfo {
MonoMethod *method;
MonoJitInfo *ji;
uint64_t time;
};
#ifdef TLS_INIT
#undef TLS_INIT
#endif
#ifdef HOST_WIN32
#define TLS_SET(x,y) (TlsSetValue (x, y))
#define TLS_GET(t,x) ((t *) TlsGetValue (x))
#define TLS_INIT(x) (x = TlsAlloc ())
static int tlsbuffer;
static int tlsmethodlist;
#elif HAVE_KW_THREAD
#define TLS_SET(x,y) (x = y)
#define TLS_GET(t,x) (x)
#define TLS_INIT(x)
static __thread LogBuffer* tlsbuffer = NULL;
static __thread GPtrArray* tlsmethodlist = NULL;
#else
#define TLS_SET(x,y) (pthread_setspecific (x, y))
#define TLS_GET(t,x) ((t *) pthread_getspecific (x))
#define TLS_INIT(x) (pthread_key_create (&x, NULL))
static pthread_key_t tlsbuffer;
static pthread_key_t tlsmethodlist;
#endif
static void safe_send (MonoProfiler *profiler, LogBuffer *logbuffer);
static char*
pstrdup (const char *s)
{
int len = strlen (s) + 1;
char *p = (char *)malloc (len);
memcpy (p, s, len);
return p;
}
static LogBuffer*
create_buffer (void)
{
LogBuffer* buf = (LogBuffer *)alloc_buffer (BUFFER_SIZE);
InterlockedIncrement (&buffer_allocations);
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;
}
static void
init_thread (void)
{
if (!TLS_GET (LogBuffer, tlsbuffer)) {
LogBuffer *logbuffer = create_buffer ();
TLS_SET (tlsbuffer, logbuffer);
logbuffer->thread_id = thread_id ();
}
if (!TLS_GET (GPtrArray, tlsmethodlist)) {
GPtrArray *methodlist = g_ptr_array_new ();
TLS_SET (tlsmethodlist, methodlist);
}
//printf ("thread %p at time %llu\n", (void*)logbuffer->thread_id, logbuffer->time_base);
}
static LogBuffer *
ensure_logbuf_inner (LogBuffer *old, int bytes)
{
if (old && old->cursor + bytes + 100 < old->buf_end)
return old;
LogBuffer *new_ = (LogBuffer *)create_buffer ();
new_->thread_id = thread_id ();
new_->next = old;
if (old)
new_->call_depth = old->call_depth;
return new_;
}
static LogBuffer*
ensure_logbuf (int bytes)
{
LogBuffer *old = TLS_GET (LogBuffer, tlsbuffer);
LogBuffer *new_ = ensure_logbuf_inner (old, bytes);
if (new_ == old)
return old; // Still enough space.
TLS_SET (tlsbuffer, new_);
init_thread ();
return new_;
}
static void
emit_byte (LogBuffer *logbuffer, int value)
{
logbuffer->cursor [0] = value;
logbuffer->cursor++;
assert (logbuffer->cursor <= logbuffer->buf_end);
}
static void
emit_value (LogBuffer *logbuffer, int value)
{
encode_uleb128 (value, logbuffer->cursor, &logbuffer->cursor);
assert (logbuffer->cursor <= logbuffer->buf_end);
}
static void
emit_time (LogBuffer *logbuffer, uint64_t value)
{
uint64_t tdiff = value - logbuffer->last_time;
//if (value < logbuffer->last_time)
// printf ("time went backwards\n");
//if (tdiff > 1000000)
// printf ("large time offset: %llu\n", tdiff);
encode_uleb128 (tdiff, logbuffer->cursor, &logbuffer->cursor);
/*if (tdiff != decode_uleb128 (p, &p))
printf ("incorrect encoding: %llu\n", tdiff);*/
logbuffer->last_time = value;
assert (logbuffer->cursor <= logbuffer->buf_end);
}
static void
emit_svalue (LogBuffer *logbuffer, int64_t value)
{
encode_sleb128 (value, logbuffer->cursor, &logbuffer->cursor);
assert (logbuffer->cursor <= logbuffer->buf_end);
}
static void
emit_uvalue (LogBuffer *logbuffer, uint64_t value)
{
encode_uleb128 (value, logbuffer->cursor, &logbuffer->cursor);
assert (logbuffer->cursor <= logbuffer->buf_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);
assert (logbuffer->cursor <= logbuffer->buf_end);
}
static void
emit_method_inner (LogBuffer *logbuffer, void *method)
{
if (!logbuffer->method_base) {
logbuffer->method_base = (intptr_t)method;
logbuffer->last_method = (intptr_t)method;
}
encode_sleb128 ((intptr_t)((char*)method - (char*)logbuffer->last_method), logbuffer->cursor, &logbuffer->cursor);
logbuffer->last_method = (intptr_t)method;
assert (logbuffer->cursor <= logbuffer->buf_end);
}
/*
typedef struct {
MonoMethod *method;
MonoJitInfo *found;
} MethodSearch;
static void
find_method (MonoDomain *domain, void *user_data)
{
MethodSearch *search = user_data;
if (search->found)
return;
MonoJitInfo *ji = mono_get_jit_info_from_method (domain, search->method);
// It could be AOT'd, so we need to get it from the AOT runtime's cache.
if (!ji) {
void *ip = mono_aot_get_method (domain, search->method);
// Avoid a slow path in mono_jit_info_table_find ().
if (ip)
ji = mono_jit_info_table_find (domain, ip);
}
if (ji)
search->found = ji;
}
*/
static void
register_method_local (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *ji)
{
if (!mono_conc_hashtable_lookup (prof->method_table, method)) {
/*
* FIXME: In some cases, we crash while looking up JIT info for AOT'd methods.
* This usually happens for static constructors. This code is disabled for now
* as we don't need this info for anything critical.
*
* https://bugzilla.xamarin.com/show_bug.cgi?id=35171
*/
/*
if (!ji) {
MethodSearch search = { method, NULL };
mono_domain_foreach (find_method, &search);
ji = search.found;
}
*/
/*
* FIXME: We can't always find JIT info for a generic shared method, especially
* if we obtained the MonoMethod during an async stack walk. For now, we deal
* with this by giving the generic shared method name and dummy code start/size
* information (i.e. zeroes).
*/
//g_assert (ji);
MethodInfo *info = (MethodInfo *)malloc (sizeof (MethodInfo));
info->method = method;
info->ji = ji;
info->time = current_time ();
g_ptr_array_add (TLS_GET (GPtrArray, tlsmethodlist), info);
}
}
static void
emit_method (MonoProfiler *prof, LogBuffer *logbuffer, MonoMethod *method)
{
register_method_local (prof, method, NULL);
emit_method_inner (logbuffer, method);
}
static void
emit_method_as_ptr (MonoProfiler *prof, LogBuffer *logbuffer, MonoMethod *method)
{
register_method_local (prof, method, NULL);
emit_ptr (logbuffer, method);
}
static void
emit_obj (LogBuffer *logbuffer, void *ptr)
{
if (!logbuffer->obj_base)
logbuffer->obj_base = (uintptr_t)ptr >> 3;
emit_svalue (logbuffer, ((uintptr_t)ptr >> 3) - logbuffer->obj_base);
assert (logbuffer->cursor <= logbuffer->buf_end);
}
static void
emit_string (LogBuffer *logbuffer, const char *str, size_t size)
{
size_t i = 0;
if (str) {
for (; i < size; i++) {
if (str[i] == '\0')
break;
emit_byte (logbuffer, str [i]);
}
}
emit_byte (logbuffer, '\0');
}
static void
emit_double (LogBuffer *logbuffer, double value)
{
int i;
unsigned char buffer[8];
memcpy (buffer, &value, 8);
#if G_BYTE_ORDER == G_BIG_ENDIAN
for (i = 7; i >= 0; i--)
#else
for (i = 0; i < 8; i++)
#endif
emit_byte (logbuffer, buffer[i]);
}
static char*
write_int16 (char *buf, int32_t value)
{
int i;
for (i = 0; i < 2; ++i) {
buf [i] = value;
value >>= 8;
}
return buf + 2;
}
static char*
write_int32 (char *buf, int32_t value)
{
int i;
for (i = 0; i < 4; ++i) {
buf [i] = value;
value >>= 8;
}
return buf + 4;
}
static char*
write_int64 (char *buf, int64_t value)
{
int i;
for (i = 0; i < 8; ++i) {
buf [i] = value;
value >>= 8;
}
return buf + 8;
}
static void
dump_header (MonoProfiler *profiler)
{
char hbuf [128];
char *p = hbuf;
p = write_int32 (p, LOG_HEADER_ID);
*p++ = LOG_VERSION_MAJOR;
*p++ = LOG_VERSION_MINOR;
*p++ = LOG_DATA_VERSION;
*p++ = sizeof (void*);
p = write_int64 (p, ((uint64_t)time (NULL)) * 1000); /* startup time */
p = write_int32 (p, get_timer_overhead ()); /* timer overhead */
p = write_int32 (p, 0); /* flags */
p = write_int32 (p, process_id ()); /* pid */
p = write_int16 (p, profiler->command_port); /* port */
p = write_int16 (p, 0); /* opsystem */
#if defined (HAVE_SYS_ZLIB)
if (profiler->gzfile) {
gzwrite (profiler->gzfile, hbuf, p - hbuf);
} else {
fwrite (hbuf, p - hbuf, 1, profiler->file);
}
#else
fwrite (hbuf, p - hbuf, 1, profiler->file);
fflush (profiler->file);
#endif
}
static void
send_buffer (MonoProfiler *prof, GPtrArray *methods, LogBuffer *buffer)
{
WriterQueueEntry *entry = (WriterQueueEntry *)calloc (1, sizeof (WriterQueueEntry));
mono_lock_free_queue_node_init (&entry->node, FALSE);
entry->methods = methods;
entry->buffer = buffer;
mono_lock_free_queue_enqueue (&prof->writer_queue, &entry->node);
mono_os_sem_post (&prof->writer_queue_sem);
}
static void
dump_buffer (MonoProfiler *profiler, LogBuffer *buf)
{
char hbuf [128];
char *p = hbuf;
if (buf->next)
dump_buffer (profiler, buf->next);
p = write_int32 (p, BUF_ID);
p = write_int32 (p, buf->cursor - buf->buf);
p = write_int64 (p, buf->time_base);
p = write_int64 (p, buf->ptr_base);
p = write_int64 (p, buf->obj_base);
p = write_int64 (p, buf->thread_id);
p = write_int64 (p, buf->method_base);
#if defined (HAVE_SYS_ZLIB)
if (profiler->gzfile) {
gzwrite (profiler->gzfile, hbuf, p - hbuf);
gzwrite (profiler->gzfile, buf->buf, buf->cursor - buf->buf);
} else {
#endif
fwrite (hbuf, p - hbuf, 1, profiler->file);
fwrite (buf->buf, buf->cursor - buf->buf, 1, profiler->file);
fflush (profiler->file);
#if defined (HAVE_SYS_ZLIB)
}
#endif
free_buffer (buf, buf->size);
}
static void
process_requests (MonoProfiler *profiler)
{
if (heapshot_requested)
mono_gc_collect (mono_gc_max_generation ());
}
static void counters_init (MonoProfiler *profiler);
static void counters_sample (MonoProfiler *profiler, uint64_t timestamp, gboolean threadless);
/*
* Can be called only at safe callback locations.
*/
static void
safe_send (MonoProfiler *profiler, LogBuffer *logbuffer)
{
/* We need the runtime initialized so that we have threads and hazard
* pointers available. Otherwise, the lock free queue will not work and
* there won't be a thread to process the data.
*
* While the runtime isn't initialized, we just accumulate data in the
* thread local buffer list.
*/
if (!InterlockedRead (&runtime_inited))
return;
int cd = logbuffer->call_depth;
send_buffer (profiler, TLS_GET (GPtrArray, tlsmethodlist), TLS_GET (LogBuffer, tlsbuffer));
TLS_SET (tlsbuffer, NULL);
TLS_SET (tlsmethodlist, NULL);
init_thread ();
TLS_GET (LogBuffer, tlsbuffer)->call_depth = cd;
}
static void
safe_send_threadless (MonoProfiler *prof, LogBuffer *buf)
{
for (LogBuffer *iter = buf; iter; iter = iter->next)
iter->thread_id = 0;
safe_send (prof, buf);
}
static int
gc_reference (MonoObject *obj, MonoClass *klass, uintptr_t size, uintptr_t num, MonoObject **refs, uintptr_t *offsets, void *data)
{
int i;
uintptr_t last_offset = 0;
//const char *name = mono_class_get_name (klass);
LogBuffer *logbuffer = ensure_logbuf (
EVENT_SIZE /* event */ +
LEB128_SIZE /* obj */ +
LEB128_SIZE /* klass */ +
LEB128_SIZE /* size */ +
LEB128_SIZE /* num */ +
num * (
LEB128_SIZE /* offset */ +
LEB128_SIZE /* ref */
)
);
emit_byte (logbuffer, TYPE_HEAP_OBJECT | TYPE_HEAP);
emit_obj (logbuffer, obj);
emit_ptr (logbuffer, klass);
/* account for object alignment in the heap */
size += 7;
size &= ~7;
emit_value (logbuffer, size);
emit_value (logbuffer, num);
for (i = 0; i < num; ++i) {
emit_value (logbuffer, offsets [i] - last_offset);
last_offset = offsets [i];
emit_obj (logbuffer, refs [i]);
}
//if (num)
// printf ("obj: %p, klass: %s, refs: %d, size: %d\n", obj, name, (int)num, (int)size);
return 0;
}
static unsigned int hs_mode_ms = 0;
static unsigned int hs_mode_gc = 0;
static unsigned int hs_mode_ondemand = 0;
static unsigned int gc_count = 0;
static uint64_t last_hs_time = 0;