Merge pull request #5206 from alexrp/profiler-gc-base-init
[mono.git] / mono / metadata / profiler.c
1 /*
2  * Licensed to the .NET Foundation under one or more agreements.
3  * The .NET Foundation licenses this file to you under the MIT license.
4  * See the LICENSE file in the project root for more information.
5  */
6
7 #include <mono/metadata/assembly.h>
8 #include <mono/metadata/gc-internals.h>
9 #include <mono/metadata/mono-config-dirs.h>
10 #include <mono/metadata/mono-debug.h>
11 #include <mono/metadata/profiler-private.h>
12 #include <mono/utils/mono-dl.h>
13 #include <mono/utils/mono-error-internals.h>
14 #include <mono/utils/mono-logger-internals.h>
15
16 MonoProfilerState mono_profiler_state;
17
18 typedef void (*MonoProfilerInitializer) (const char *);
19
20 #define OLD_INITIALIZER_NAME "mono_profiler_startup"
21 #define NEW_INITIALIZER_NAME "mono_profiler_init"
22
23 static gboolean
24 load_profiler (MonoDl *module, const char *desc, const char *suffix)
25 {
26         if (!module)
27                 return FALSE;
28
29         char *old_name;
30
31         if (suffix)
32                 old_name = g_strdup_printf (OLD_INITIALIZER_NAME "_%s", suffix);
33         else
34                 old_name = g_strdup_printf (OLD_INITIALIZER_NAME);
35
36         MonoProfilerInitializer func;
37
38         char *err;
39
40         if (!(err = mono_dl_symbol (module, old_name, (gpointer) &func))) {
41                 mono_profiler_printf_err ("Found old-style startup symbol %s for %s; profiler has not been migrated to the new API.", old_name, desc);
42                 g_free (old_name);
43                 return FALSE;
44         }
45
46         g_free (err);
47         g_free (old_name);
48
49         char *new_name;
50
51         if (suffix)
52                 new_name = g_strdup_printf (NEW_INITIALIZER_NAME "_%s", suffix);
53         else
54                 new_name = g_strdup_printf (NEW_INITIALIZER_NAME);
55
56         if ((err = mono_dl_symbol (module, new_name, (gpointer *) &func))) {
57                 g_free (err);
58                 g_free (new_name);
59                 return FALSE;
60         }
61
62         g_free (new_name);
63
64         func (desc);
65
66         return TRUE;
67 }
68
69 static gboolean
70 load_profiler_from_executable (const char *desc, const char *name)
71 {
72         char *err;
73
74         /*
75          * Some profilers (such as ours) may need to call back into the runtime
76          * from their sampling callback (which is called in async-signal context).
77          * They need to be able to know that all references back to the runtime
78          * have been resolved; otherwise, calling runtime functions may result in
79          * invoking the dynamic linker which is not async-signal-safe. Passing
80          * MONO_DL_EAGER will ask the dynamic linker to resolve everything upfront.
81          */
82         MonoDl *module = mono_dl_open (NULL, MONO_DL_EAGER, &err);
83
84         if (!module) {
85                 mono_profiler_printf_err ("Could not open main executable: %s", err);
86                 g_free (err);
87                 return FALSE;
88         }
89
90         return load_profiler (module, desc, name);
91 }
92
93 static gboolean
94 load_profiler_from_directory (const char *directory, const char *libname, const char *desc)
95 {
96         char* path;
97         void *iter = NULL;
98
99         while ((path = mono_dl_build_path (directory, libname, &iter))) {
100                 // See the comment in load_embedded_profiler ().
101                 MonoDl *module = mono_dl_open (path, MONO_DL_EAGER, NULL);
102
103                 g_free (path);
104
105                 if (module)
106                         return load_profiler (module, desc, NULL);
107         }
108
109         return FALSE;
110 }
111
112 static gboolean
113 load_profiler_from_installation (const char *libname, const char *desc)
114 {
115         char *err;
116         MonoDl *module = mono_dl_open_runtime_lib (libname, MONO_DL_EAGER, &err);
117
118         g_free (err);
119
120         if (module)
121                 return load_profiler (module, desc, NULL);
122
123         return FALSE;
124 }
125
126 void
127 mono_profiler_load (const char *desc)
128 {
129         if (!desc || !strcmp ("default", desc))
130                 desc = "log:report";
131
132         const char *col = strchr (desc, ':');
133         char *mname;
134
135         if (col != NULL) {
136                 mname = (char *) g_memdup (desc, col - desc + 1);
137                 mname [col - desc] = 0;
138         } else
139                 mname = g_strdup (desc);
140
141         if (!load_profiler_from_executable (desc, mname)) {
142                 char *libname = g_strdup_printf ("mono-profiler-%s", mname);
143                 gboolean res = load_profiler_from_installation (libname, desc);
144
145                 if (!res && mono_config_get_assemblies_dir ())
146                         res = load_profiler_from_directory (mono_assembly_getrootdir (), libname, desc);
147
148                 if (!res)
149                         res = load_profiler_from_directory (NULL, libname, desc);
150
151                 if (!res)
152                         mono_profiler_printf_err ("The '%s' profiler wasn't found in the main executable nor could it be loaded from '%s'.", mname, libname);
153
154                 g_free (libname);
155         }
156
157         g_free (mname);
158 }
159
160 MonoProfilerHandle
161 mono_profiler_install (MonoProfiler *prof)
162 {
163         MonoProfilerHandle handle = g_new0 (struct _MonoProfilerDesc, 1);
164
165         handle->prof = prof;
166         handle->next = mono_profiler_state.profilers;
167
168         mono_profiler_state.profilers = handle;
169
170         return handle;
171 }
172
173 void
174 mono_profiler_set_coverage_filter_callback (MonoProfilerHandle handle, MonoProfilerCoverageFilterCallback cb)
175 {
176         InterlockedWritePointer (&handle->coverage_filter, (gpointer) cb);
177 }
178
179 static void
180 initialize_coverage (void)
181 {
182         mono_os_mutex_init (&mono_profiler_state.coverage_mutex);
183         mono_profiler_state.coverage_hash = g_hash_table_new (NULL, NULL);
184 }
185
186 static void
187 lazy_initialize_coverage (void)
188 {
189         mono_lazy_initialize (&mono_profiler_state.coverage_status, initialize_coverage);
190 }
191
192 static void
193 coverage_lock (void)
194 {
195         mono_os_mutex_lock (&mono_profiler_state.coverage_mutex);
196 }
197
198 static void
199 coverage_unlock (void)
200 {
201         mono_os_mutex_unlock (&mono_profiler_state.coverage_mutex);
202 }
203
204 void
205 mono_profiler_get_coverage_data (MonoProfilerHandle handle, MonoMethod *method, MonoProfilerCoverageCallback cb)
206 {
207         lazy_initialize_coverage ();
208
209         coverage_lock ();
210
211         MonoProfilerCoverageInfo *info = g_hash_table_lookup (mono_profiler_state.coverage_hash, method);
212
213         coverage_unlock ();
214
215         if (!info)
216                 return;
217
218         MonoError error;
219         MonoMethodHeader *header = mono_method_get_header_checked (method, &error);
220         mono_error_assert_ok (&error);
221
222         guint32 size;
223
224         const unsigned char *start = mono_method_header_get_code (header, &size, NULL);
225         const unsigned char *end = start - size;
226         MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
227
228         for (guint32 i = 0; i < info->entries; i++) {
229                 guchar *cil_code = info->data [i].cil_code;
230
231                 if (cil_code && cil_code >= start && cil_code < end) {
232                         guint32 offset = cil_code - start;
233
234                         MonoProfilerCoverageData data = {
235                                 .method = method,
236                                 .il_offset = offset,
237                                 .counter = info->data [i].count,
238                                 .line = 1,
239                                 .column = 1,
240                         };
241
242                         if (minfo) {
243                                 MonoDebugSourceLocation *loc = mono_debug_method_lookup_location (minfo, offset);
244
245                                 if (loc) {
246                                         data.file_name = g_strdup (loc->source_file);
247                                         data.line = loc->row;
248                                         data.column = loc->column;
249
250                                         mono_debug_free_source_location (loc);
251                                 }
252                         }
253
254                         cb (handle->prof, &data);
255
256                         g_free ((char *) data.file_name);
257                 }
258         }
259
260         mono_metadata_free_mh (header);
261 }
262
263 MonoProfilerCoverageInfo *
264 mono_profiler_coverage_alloc (MonoMethod *method, guint32 entries)
265 {
266         lazy_initialize_coverage ();
267
268         gboolean cover = FALSE;
269
270         for (MonoProfilerHandle handle = mono_profiler_state.profilers; handle; handle = handle->next) {
271                 MonoProfilerCoverageFilterCallback cb = handle->coverage_filter;
272
273                 if (cb)
274                         cover |= cb (handle->prof, method);
275         }
276
277         if (!cover)
278                 return NULL;
279
280         coverage_lock ();
281
282         MonoProfilerCoverageInfo *info = g_malloc0 (sizeof (MonoProfilerCoverageInfo) + SIZEOF_VOID_P * 2 * entries);
283
284         info->entries = entries;
285
286         g_hash_table_insert (mono_profiler_state.coverage_hash, method, info);
287
288         coverage_unlock ();
289
290         return info;
291 }
292
293 void
294 mono_profiler_coverage_free (MonoMethod *method)
295 {
296         lazy_initialize_coverage ();
297
298         coverage_lock ();
299
300         MonoProfilerCoverageInfo *info = g_hash_table_lookup (mono_profiler_state.coverage_hash, method);
301
302         if (info) {
303                 g_hash_table_remove (mono_profiler_state.coverage_hash, method);
304                 g_free (info);
305         }
306
307         coverage_unlock ();
308 }
309
310 mono_bool
311 mono_profiler_enable_sampling (MonoProfilerHandle handle)
312 {
313         if (mono_profiler_state.startup_done)
314                 return FALSE;
315
316         if (mono_profiler_state.sampling_owner)
317                 return TRUE;
318
319         mono_profiler_state.sampling_owner = handle;
320         mono_profiler_state.sample_mode = MONO_PROFILER_SAMPLE_MODE_NONE;
321         mono_profiler_state.sample_freq = 100;
322         mono_os_sem_init (&mono_profiler_state.sampling_semaphore, 0);
323
324         return TRUE;
325 }
326
327 mono_bool
328 mono_profiler_set_sample_mode (MonoProfilerHandle handle, MonoProfilerSampleMode mode, uint32_t freq)
329 {
330         if (handle != mono_profiler_state.sampling_owner)
331                 return FALSE;
332
333         mono_profiler_state.sample_mode = mode;
334         mono_profiler_state.sample_freq = freq;
335
336         mono_profiler_sampling_thread_post ();
337
338         return TRUE;
339 }
340
341 mono_bool
342 mono_profiler_get_sample_mode (MonoProfilerHandle handle, MonoProfilerSampleMode *mode, uint32_t *freq)
343 {
344         if (mode)
345                 *mode = mono_profiler_state.sample_mode;
346
347         if (freq)
348                 *freq = mono_profiler_state.sample_freq;
349
350         return handle == mono_profiler_state.sampling_owner;
351 }
352
353 gboolean
354 mono_profiler_sampling_enabled (void)
355 {
356         return !!mono_profiler_state.sampling_owner;
357 }
358
359 void
360 mono_profiler_sampling_thread_post (void)
361 {
362         mono_os_sem_post (&mono_profiler_state.sampling_semaphore);
363 }
364
365 void
366 mono_profiler_sampling_thread_wait (void)
367 {
368         mono_os_sem_wait (&mono_profiler_state.sampling_semaphore, MONO_SEM_FLAGS_NONE);
369 }
370
371 mono_bool
372 mono_profiler_enable_allocations (void)
373 {
374         if (mono_profiler_state.startup_done)
375                 return FALSE;
376
377         mono_profiler_state.allocations = TRUE;
378
379         return TRUE;
380 }
381
382 void
383 mono_profiler_set_call_instrumentation_filter_callback (MonoProfilerHandle handle, MonoProfilerCallInstrumentationFilterCallback cb)
384 {
385         InterlockedWritePointer (&handle->call_instrumentation_filter, (gpointer) cb);
386 }
387
388 gboolean
389 mono_profiler_should_instrument_method (MonoMethod *method, gboolean entry)
390 {
391         MonoProfilerCallInstrumentationFlags flags = MONO_PROFILER_CALL_INSTRUMENTATION_NONE;
392
393         for (MonoProfilerHandle handle = mono_profiler_state.profilers; handle; handle = handle->next) {
394                 MonoProfilerCallInstrumentationFilterCallback cb = handle->call_instrumentation_filter;
395
396                 if (cb)
397                         flags |= cb (handle->prof, method);
398         }
399
400         if (entry)
401                 return flags & MONO_PROFILER_CALL_INSTRUMENTATION_PROLOGUE;
402         else
403                 return flags & MONO_PROFILER_CALL_INSTRUMENTATION_EPILOGUE;
404 }
405
406 void
407 mono_profiler_started (void)
408 {
409         mono_profiler_state.startup_done = TRUE;
410 }
411
412 void
413 mono_profiler_cleanup (void)
414 {
415         for (MonoProfilerHandle handle = mono_profiler_state.profilers; handle; handle = handle->next) {
416 #define _MONO_PROFILER_EVENT(name) \
417         mono_profiler_set_ ## name ## _callback (handle, NULL); \
418         g_assert (!handle->name ## _cb);
419 #define MONO_PROFILER_EVENT_0(name, type) \
420         _MONO_PROFILER_EVENT(name)
421 #define MONO_PROFILER_EVENT_1(name, type, arg1_type, arg1_name) \
422         _MONO_PROFILER_EVENT(name)
423 #define MONO_PROFILER_EVENT_2(name, type, arg1_type, arg1_name, arg2_type, arg2_name) \
424         _MONO_PROFILER_EVENT(name)
425 #define MONO_PROFILER_EVENT_3(name, type, arg1_type, arg1_name, arg2_type, arg2_name, arg3_type, arg3_name) \
426         _MONO_PROFILER_EVENT(name)
427 #define MONO_PROFILER_EVENT_4(name, type, arg1_type, arg1_name, arg2_type, arg2_name, arg3_type, arg3_name, arg4_type, arg4_name) \
428         _MONO_PROFILER_EVENT(name)
429 #include <mono/metadata/profiler-events.h>
430 #undef MONO_PROFILER_EVENT_0
431 #undef MONO_PROFILER_EVENT_1
432 #undef MONO_PROFILER_EVENT_2
433 #undef MONO_PROFILER_EVENT_3
434 #undef MONO_PROFILER_EVENT_4
435 #undef _MONO_PROFILER_EVENT
436         }
437
438 #define _MONO_PROFILER_EVENT(name, type) \
439         g_assert (!mono_profiler_state.name ## _count);
440 #define MONO_PROFILER_EVENT_0(name, type) \
441         _MONO_PROFILER_EVENT(name, type)
442 #define MONO_PROFILER_EVENT_1(name, type, arg1_type, arg1_name) \
443         _MONO_PROFILER_EVENT(name, type)
444 #define MONO_PROFILER_EVENT_2(name, type, arg1_type, arg1_name, arg2_type, arg2_name) \
445         _MONO_PROFILER_EVENT(name, type)
446 #define MONO_PROFILER_EVENT_3(name, type, arg1_type, arg1_name, arg2_type, arg2_name, arg3_type, arg3_name) \
447         _MONO_PROFILER_EVENT(name, type)
448 #define MONO_PROFILER_EVENT_4(name, type, arg1_type, arg1_name, arg2_type, arg2_name, arg3_type, arg3_name, arg4_type, arg4_name) \
449         _MONO_PROFILER_EVENT(name, type)
450 #include <mono/metadata/profiler-events.h>
451 #undef MONO_PROFILER_EVENT_0
452 #undef MONO_PROFILER_EVENT_1
453 #undef MONO_PROFILER_EVENT_2
454 #undef MONO_PROFILER_EVENT_3
455 #undef MONO_PROFILER_EVENT_4
456 #undef _MONO_PROFILER_EVENT
457 }
458
459 static void
460 update_callback (volatile gpointer *location, gpointer new_, volatile gint32 *counter)
461 {
462         gpointer old;
463
464         do {
465                 old = InterlockedReadPointer (location);
466         } while (InterlockedCompareExchangePointer (location, new_, old) != old);
467
468         /*
469          * At this point, we could have installed a NULL callback while the counter
470          * is still non-zero, i.e. setting the callback and modifying the counter
471          * is not a single atomic operation. This is fine as we make sure callbacks
472          * are non-NULL before invoking them (see the code below that generates the
473          * raise functions), and besides, updating callbacks at runtime is an
474          * inherently racy operation.
475          */
476
477         if (old)
478                 InterlockedDecrement (counter);
479
480         if (new_)
481                 InterlockedIncrement (counter);
482 }
483
484 #define _MONO_PROFILER_EVENT(name, type) \
485         void \
486         mono_profiler_set_ ## name ## _callback (MonoProfilerHandle handle, MonoProfiler ## type ## Callback cb) \
487         { \
488                 update_callback (&handle->name ## _cb, (gpointer) cb, &mono_profiler_state.name ## _count); \
489         }
490 #define MONO_PROFILER_EVENT_0(name, type) \
491         _MONO_PROFILER_EVENT(name, type)
492 #define MONO_PROFILER_EVENT_1(name, type, arg1_type, arg1_name) \
493         _MONO_PROFILER_EVENT(name, type)
494 #define MONO_PROFILER_EVENT_2(name, type, arg1_type, arg1_name, arg2_type, arg2_name) \
495         _MONO_PROFILER_EVENT(name, type)
496 #define MONO_PROFILER_EVENT_3(name, type, arg1_type, arg1_name, arg2_type, arg2_name, arg3_type, arg3_name) \
497         _MONO_PROFILER_EVENT(name, type)
498 #define MONO_PROFILER_EVENT_4(name, type, arg1_type, arg1_name, arg2_type, arg2_name, arg3_type, arg3_name, arg4_type, arg4_name) \
499         _MONO_PROFILER_EVENT(name, type)
500 #include <mono/metadata/profiler-events.h>
501 #undef MONO_PROFILER_EVENT_0
502 #undef MONO_PROFILER_EVENT_1
503 #undef MONO_PROFILER_EVENT_2
504 #undef MONO_PROFILER_EVENT_3
505 #undef MONO_PROFILER_EVENT_4
506 #undef _MONO_PROFILER_EVENT
507
508 #define _MONO_PROFILER_EVENT(name, type, params, args) \
509         void \
510         mono_profiler_raise_ ## name params \
511         { \
512                 for (MonoProfilerHandle h = mono_profiler_state.profilers; h; h = h->next) { \
513                         MonoProfiler ## type ## Callback cb = h->name ## _cb; \
514                         if (cb) \
515                                 cb args; \
516                 } \
517         }
518 #define MONO_PROFILER_EVENT_0(name, type) \
519         _MONO_PROFILER_EVENT(name, type, (void), (h->prof))
520 #define MONO_PROFILER_EVENT_1(name, type, arg1_type, arg1_name) \
521         _MONO_PROFILER_EVENT(name, type, (arg1_type arg1_name), (h->prof, arg1_name))
522 #define MONO_PROFILER_EVENT_2(name, type, arg1_type, arg1_name, arg2_type, arg2_name) \
523         _MONO_PROFILER_EVENT(name, type, (arg1_type arg1_name, arg2_type arg2_name), (h->prof, arg1_name, arg2_name))
524 #define MONO_PROFILER_EVENT_3(name, type, arg1_type, arg1_name, arg2_type, arg2_name, arg3_type, arg3_name) \
525         _MONO_PROFILER_EVENT(name, type, (arg1_type arg1_name, arg2_type arg2_name, arg3_type arg3_name), (h->prof, arg1_name, arg2_name, arg3_name))
526 #define MONO_PROFILER_EVENT_4(name, type, arg1_type, arg1_name, arg2_type, arg2_name, arg3_type, arg3_name, arg4_type, arg4_name) \
527         _MONO_PROFILER_EVENT(name, type, (arg1_type arg1_name, arg2_type arg2_name, arg3_type arg3_name, arg4_type arg4_name), (h->prof, arg1_name, arg2_name, arg3_name, arg4_name))
528 #include <mono/metadata/profiler-events.h>
529 #undef MONO_PROFILER_EVENT_0
530 #undef MONO_PROFILER_EVENT_1
531 #undef MONO_PROFILER_EVENT_2
532 #undef MONO_PROFILER_EVENT_3
533 #undef MONO_PROFILER_EVENT_4
534 #undef _MONO_PROFILER_EVENT