osyoyu / pf2

A sampling-based profiler for Ruby
https://rubygems.org/gems/pf2
MIT License
35 stars 1 forks source link

Make CPU-time profiling possible on non-Linux platforms #19

Open osyoyu opened 1 month ago

osyoyu commented 1 month ago

Pf2 (SignalScheduler) sets sigevent.sigev_notify to SIGEV_THREAD_ID which directs signals to a specified thread to make per-thread-CPU-time profiling possible. However, SIGEV_THREAD_ID is a Linux-only feature and not available on other *nix platforms.

CPU-time profiling is important core feature and should be available at least on major platforms, such as macOS.

osyoyu commented 1 month ago

Trampolining signals

One possible strategy is to trampoline the signal to the desired thread from the signal handler. This is possible using pthread_kill or tgkill, which are capable of directing signals to a particular thread (instead of processes).

However, neither can add additional context (siginfo_t/sival_ptr) to the signal. Pf2 uses the context to pass the pointer to the profile, so we need to find a alternative way.

osyoyu commented 1 month ago

Profiling from another thread

Another strategy is to give up using signal handlers for profiling. The main reason we profile from signal handlers is because signals effectively pauses the target thread, which makes the program's state stable. The same may be acheived by ptrace, but I am not sure if that will work out.

libbacktrace probably won't work in the current manner, as it can only target the thread which backtrace_simple() was called. We'd need to give up on features relying on libbacktrace (which I do not want to do).