sample.c 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. /*
  2. * Bare bones profiler showing how a profiler module should be structured.
  3. *
  4. * Compilation:
  5. * - Linux: gcc -fPIC -shared -o libmono-profiler-sample.so sample.c `pkg-config --cflags mono-2`
  6. * - OS X: clang -undefined suppress -flat_namespace -o mono-profiler-sample.dylib sample.c `pkg-config --cflags mono-2`
  7. *
  8. * If you're using a custom prefix for your Mono installation (e.g. /opt/mono),
  9. * pkg-config must be invoked like this: PKG_CONFIG_PATH=/opt/mono pkg-config --cflags mono-2
  10. *
  11. * Install the resulting shared library where the dynamic loader can find it,
  12. * e.g. /usr/local/lib or /opt/mono (custom prefix).
  13. *
  14. * To use the module: mono --profile=sample hello.exe
  15. */
  16. #include <mono/metadata/profiler.h>
  17. /*
  18. * Defining a type called _MonoProfiler will complete the opaque MonoProfiler
  19. * type, which is used throughout the profiler API.
  20. */
  21. struct _MonoProfiler {
  22. /* Handle obtained from mono_profiler_create (). */
  23. MonoProfilerHandle handle;
  24. /* Counts the number of calls observed. */
  25. unsigned long long ncalls;
  26. };
  27. /*
  28. * Use static storage for the profiler structure for simplicity. The structure
  29. * can be allocated dynamically as well, if needed.
  30. */
  31. static MonoProfiler profiler;
  32. /*
  33. * Callback invoked after the runtime finishes shutting down. Managed code can
  34. * no longer run and most runtime services are unavailable.
  35. */
  36. static void
  37. sample_shutdown_end (MonoProfiler *prof)
  38. {
  39. printf ("Total number of calls: %llu\n", prof->ncalls);
  40. }
  41. /*
  42. * Method enter callback invoked on entry to all instrumented methods.
  43. */
  44. static void
  45. sample_method_enter (MonoProfiler *prof, MonoMethod *method, MonoProfilerCallContext *ctx)
  46. {
  47. prof->ncalls++;
  48. }
  49. /*
  50. * Filter callback that decides which methods to instrument and how.
  51. */
  52. static MonoProfilerCallInstrumentationFlags
  53. sample_call_instrumentation_filter (MonoProfiler *prof, MonoMethod *method)
  54. {
  55. return MONO_PROFILER_CALL_INSTRUMENTATION_ENTER;
  56. }
  57. /*
  58. * The entry point function invoked by the Mono runtime.
  59. */
  60. void
  61. mono_profiler_init_sample (const char *desc)
  62. {
  63. profiler.handle = mono_profiler_create (&profiler);
  64. mono_profiler_set_runtime_shutdown_end_callback (profiler.handle, sample_shutdown_end);
  65. mono_profiler_set_call_instrumentation_filter_callback (profiler.handle, sample_call_instrumentation_filter);
  66. mono_profiler_set_method_enter_callback (profiler.handle, sample_method_enter);
  67. }