LCOV - code coverage report
Current view: top level - gjs - profiler.cpp (source / functions) Hit Total Coverage
Test: gjs- Code Coverage Lines: 168 277 60.6 %
Date: 2024-02-27 17:05:05 Functions: 10 20 50.0 %
Legend: Lines: hit not hit | Branches: + taken - not taken # not executed Branches: 66 184 35.9 %

           Branch data     Line data    Source code
       1                 :            : // SPDX-License-Identifier: MIT OR LGPL-2.0-or-later
       2                 :            : // SPDX-FileCopyrightText: 2016 Christian Hergert <christian@hergert.me>
       3                 :            : 
       4                 :            : #include <config.h>  // for ENABLE_PROFILER, HAVE_SYS_SYSCALL_H, HAVE_UNISTD_H
       5                 :            : 
       6                 :            : #ifdef HAVE_SIGNAL_H
       7                 :            : #    include <signal.h>  // for siginfo_t, sigevent, sigaction, SIGPROF, ...
       8                 :            : #endif
       9                 :            : 
      10                 :            : #include <glib-object.h>
      11                 :            : #include <glib.h>
      12                 :            : 
      13                 :            : #ifdef ENABLE_PROFILER
      14                 :            : #    include <alloca.h>
      15                 :            : #    include <errno.h>
      16                 :            : #    include <stdint.h>
      17                 :            : #    include <stdio.h>      // for sscanf
      18                 :            : #    include <string.h>     // for memcpy, strlen
      19                 :            : #    include <sys/syscall.h>  // for __NR_gettid
      20                 :            : #    include <time.h>         // for size_t, CLOCK_MONOTONIC, itimerspec, ...
      21                 :            : #    ifdef HAVE_UNISTD_H
      22                 :            : #        include <unistd.h>  // for getpid, syscall
      23                 :            : #    endif
      24                 :            : #    include <array>
      25                 :            : #    ifdef G_OS_UNIX
      26                 :            : #        include <glib-unix.h>
      27                 :            : #    endif
      28                 :            : #    include <sysprof-capture.h>
      29                 :            : #endif
      30                 :            : 
      31                 :            : #include <js/ProfilingStack.h>  // for EnableContextProfilingStack, ...
      32                 :            : #include <js/TypeDecls.h>
      33                 :            : #include <mozilla/Atomics.h>  // for ProfilingStack operators
      34                 :            : 
      35                 :            : #include "gjs/context.h"
      36                 :            : #include "gjs/jsapi-util.h"
      37                 :            : #include "gjs/mem-private.h"
      38                 :            : #include "gjs/profiler-private.h"
      39                 :            : #include "gjs/profiler.h"
      40                 :            : 
      41                 :            : #define FLUSH_DELAY_SECONDS 3
      42                 :            : 
      43                 :            : /*
      44                 :            :  * This is mostly non-exciting code wrapping the builtin Profiler in
      45                 :            :  * mozjs. In particular, the profiler consumer is required to "bring your
      46                 :            :  * own sampler".  We do the very non-surprising thing of using POSIX
      47                 :            :  * timers to deliver SIGPROF to the thread containing the JSContext.
      48                 :            :  *
      49                 :            :  * However, we do use a Linux'ism that allows us to deliver the signal
      50                 :            :  * to only a single thread. Doing this in a generic fashion would
      51                 :            :  * require thread-registration so that we can mask SIGPROF from all
      52                 :            :  * threads except the JS thread. The gecko engine uses tgkill() to do
      53                 :            :  * this with a secondary thread instead of using POSIX timers. We could
      54                 :            :  * do this too, but it would still be Linux-only.
      55                 :            :  *
      56                 :            :  * Another option might be to use pthread_kill() and a secondary thread
      57                 :            :  * to perform the notification.
      58                 :            :  *
      59                 :            :  * From within the signal handler, we process the current stack as
      60                 :            :  * delivered to us from the JSContext. Any pointer data that comes from
      61                 :            :  * the runtime has to be copied, so we keep our own dedup'd string
      62                 :            :  * pointers for JavaScript file/line information. Non-JS instruction
      63                 :            :  * pointers are just fine, as they can be resolved by parsing the ELF for
      64                 :            :  * the file mapped on disk containing that address.
      65                 :            :  *
      66                 :            :  * As much of this code has to run from signal handlers, it is very
      67                 :            :  * important that we don't use anything that can malloc() or lock, or
      68                 :            :  * deadlocks are very likely. Most of GjsProfilerCapture is signal-safe.
      69                 :            :  */
      70                 :            : 
      71                 :            : #define SAMPLES_PER_SEC G_GUINT64_CONSTANT(1000)
      72                 :            : #define NSEC_PER_SEC G_GUINT64_CONSTANT(1000000000)
      73                 :            : 
      74   [ #  #  #  #  :          0 : G_DEFINE_POINTER_TYPE(GjsProfiler, gjs_profiler)
                   #  # ]
      75                 :            : 
      76                 :            : struct _GjsProfiler {
      77                 :            : #ifdef ENABLE_PROFILER
      78                 :            :     /* The stack for the JSContext profiler to use for current stack
      79                 :            :      * information while executing. We will look into this during our
      80                 :            :      * SIGPROF handler.
      81                 :            :      */
      82                 :            :     ProfilingStack stack;
      83                 :            : 
      84                 :            :     /* The context being profiled */
      85                 :            :     JSContext *cx;
      86                 :            : 
      87                 :            :     /* Buffers and writes our sampled stacks */
      88                 :            :     SysprofCaptureWriter* capture;
      89                 :            :     GSource* periodic_flush;
      90                 :            : 
      91                 :            :     SysprofCaptureWriter* target_capture;
      92                 :            : 
      93                 :            :     // Cache previous values of counters so that we don't overrun the output
      94                 :            :     // with counters that don't change very often
      95                 :            :     uint64_t last_counter_values[GJS_N_COUNTERS];
      96                 :            : #endif  /* ENABLE_PROFILER */
      97                 :            : 
      98                 :            :     /* The filename to write to */
      99                 :            :     char *filename;
     100                 :            : 
     101                 :            :     /* An FD to capture to */
     102                 :            :     int fd;
     103                 :            : 
     104                 :            : #ifdef ENABLE_PROFILER
     105                 :            :     /* Our POSIX timer to wakeup SIGPROF */
     106                 :            :     timer_t timer;
     107                 :            : 
     108                 :            :     /* Cached copy of our pid */
     109                 :            :     GPid pid;
     110                 :            : 
     111                 :            :     /* GLib signal handler ID for SIGUSR2 */
     112                 :            :     unsigned sigusr2_id;
     113                 :            :     unsigned counter_base;  // index of first GObject memory counter
     114                 :            :     unsigned gc_counter_base;  // index of first GC stats counter
     115                 :            : #endif  /* ENABLE_PROFILER */
     116                 :            : 
     117                 :            :     /* If we are currently sampling */
     118                 :            :     unsigned running : 1;
     119                 :            : };
     120                 :            : 
     121                 :            : static GjsContext *profiling_context;
     122                 :            : 
     123                 :            : #ifdef ENABLE_PROFILER
     124                 :            : /*
     125                 :            :  * gjs_profiler_extract_maps:
     126                 :            :  *
     127                 :            :  * This function will write the mapped section information to the
     128                 :            :  * capture file so that the callgraph builder can generate symbols
     129                 :            :  * from the stack addresses provided.
     130                 :            :  *
     131                 :            :  * Returns: %TRUE if successful; otherwise %FALSE and the profile
     132                 :            :  *   should abort.
     133                 :            :  */
     134                 :          5 : [[nodiscard]] static bool gjs_profiler_extract_maps(GjsProfiler* self) {
     135                 :          5 :     int64_t now = g_get_monotonic_time() * 1000L;
     136                 :            : 
     137                 :          5 :     g_assert(((void) "Profiler must be set up before extracting maps", self));
     138                 :            : 
     139                 :          5 :     GjsAutoChar path = g_strdup_printf("/proc/%jd/maps", intmax_t(self->pid));
     140                 :            : 
     141                 :            :     char *content_tmp;
     142                 :            :     size_t len;
     143         [ -  + ]:          5 :     if (!g_file_get_contents(path, &content_tmp, &len, nullptr))
     144                 :          0 :       return false;
     145                 :          5 :     GjsAutoChar content = content_tmp;
     146                 :            : 
     147                 :          5 :     GjsAutoStrv lines = g_strsplit(content, "\n", 0);
     148                 :            : 
     149         [ +  + ]:       1423 :     for (size_t ix = 0; lines[ix]; ix++) {
     150                 :            :         char file[256];
     151                 :            :         unsigned long start;
     152                 :            :         unsigned long end;
     153                 :            :         unsigned long offset;
     154                 :            :         unsigned long inode;
     155                 :            : 
     156                 :       1418 :         file[sizeof file - 1] = '\0';
     157                 :            : 
     158                 :       1418 :         int r = sscanf(lines[ix], "%lx-%lx %*15s %lx %*x:%*x %lu %255s",
     159                 :            :                        &start, &end, &offset, &inode, file);
     160         [ +  + ]:       1418 :         if (r != 5)
     161                 :        357 :             continue;
     162                 :            : 
     163         [ +  + ]:       1061 :         if (strcmp("[vdso]", file) == 0) {
     164                 :          5 :             offset = 0;
     165                 :          5 :             inode = 0;
     166                 :            :         }
     167                 :            : 
     168         [ -  + ]:       1061 :         if (!sysprof_capture_writer_add_map(self->capture, now, -1, self->pid,
     169                 :            :                                             start, end, offset, inode, file))
     170                 :          0 :             return false;
     171                 :            :     }
     172                 :            : 
     173                 :          5 :     return true;
     174                 :          5 : }
     175                 :            : 
     176                 :         80 : static void setup_counter_helper(SysprofCaptureCounter* counter,
     177                 :            :                                  const char* counter_name,
     178                 :            :                                  unsigned counter_base, size_t ix) {
     179                 :         80 :     g_snprintf(counter->category, sizeof counter->category, "GJS");
     180                 :         80 :     g_snprintf(counter->name, sizeof counter->name, "%s", counter_name);
     181                 :         80 :     g_snprintf(counter->description, sizeof counter->description, "%s",
     182                 :         80 :                GJS_COUNTER_DESCRIPTIONS[ix]);
     183                 :         80 :     counter->id = uint32_t(counter_base + ix);
     184                 :         80 :     counter->type = SYSPROF_CAPTURE_COUNTER_INT64;
     185                 :         80 :     counter->value.v64 = 0;
     186                 :         80 : }
     187                 :            : 
     188                 :          5 : [[nodiscard]] static bool gjs_profiler_define_counters(GjsProfiler* self) {
     189                 :          5 :     int64_t now = g_get_monotonic_time() * 1000L;
     190                 :            : 
     191                 :          5 :     g_assert(self && "Profiler must be set up before defining counters");
     192                 :            : 
     193                 :            :     std::array<SysprofCaptureCounter, GJS_N_COUNTERS> counters;
     194                 :          5 :     self->counter_base =
     195                 :          5 :         sysprof_capture_writer_request_counter(self->capture, GJS_N_COUNTERS);
     196                 :            : 
     197                 :            : #    define SETUP_COUNTER(counter_name, ix)                                    \
     198                 :            :         setup_counter_helper(&counters[ix], #counter_name, self->counter_base, \
     199                 :            :                              ix);
     200                 :          5 :     GJS_FOR_EACH_COUNTER(SETUP_COUNTER);
     201                 :            : #    undef SETUP_COUNTER
     202                 :            : 
     203         [ -  + ]:          5 :     if (!sysprof_capture_writer_define_counters(
     204                 :          5 :             self->capture, now, -1, self->pid, counters.data(), GJS_N_COUNTERS))
     205                 :          0 :         return false;
     206                 :            : 
     207                 :            :     std::array<SysprofCaptureCounter, Gjs::GCCounters::N_COUNTERS> gc_counters;
     208                 :          5 :     self->gc_counter_base = sysprof_capture_writer_request_counter(
     209                 :            :         self->capture, Gjs::GCCounters::N_COUNTERS);
     210                 :            : 
     211                 :          5 :     constexpr size_t category_size = sizeof gc_counters[0].category;
     212                 :          5 :     constexpr size_t name_size = sizeof gc_counters[0].name;
     213                 :          5 :     constexpr size_t description_size = sizeof gc_counters[0].description;
     214                 :            : 
     215         [ +  + ]:         15 :     for (size_t ix = 0; ix < Gjs::GCCounters::N_COUNTERS; ix++) {
     216                 :         10 :         g_snprintf(gc_counters[ix].category, category_size, "GJS");
     217                 :         10 :         gc_counters[ix].id = uint32_t(self->gc_counter_base + ix);
     218                 :         10 :         gc_counters[ix].type = SYSPROF_CAPTURE_COUNTER_INT64;
     219                 :         10 :         gc_counters[ix].value.v64 = 0;
     220                 :            :     }
     221                 :          5 :     g_snprintf(gc_counters[Gjs::GCCounters::GC_HEAP_BYTES].name, name_size,
     222                 :            :                "GC bytes");
     223                 :          5 :     g_snprintf(gc_counters[Gjs::GCCounters::GC_HEAP_BYTES].description,
     224                 :            :                description_size, "Bytes used in GC heap");
     225                 :          5 :     g_snprintf(gc_counters[Gjs::GCCounters::MALLOC_HEAP_BYTES].name, name_size,
     226                 :            :                "Malloc bytes");
     227                 :          5 :     g_snprintf(gc_counters[Gjs::GCCounters::MALLOC_HEAP_BYTES].description,
     228                 :            :                description_size, "Malloc bytes owned by tenured GC things");
     229                 :            : 
     230                 :          5 :     return sysprof_capture_writer_define_counters(self->capture, now, -1,
     231                 :          5 :                                                   self->pid, gc_counters.data(),
     232                 :          5 :                                                   Gjs::GCCounters::N_COUNTERS);
     233                 :            : }
     234                 :            : 
     235                 :            : #endif  /* ENABLE_PROFILER */
     236                 :            : 
     237                 :            : /*
     238                 :            :  * _gjs_profiler_new:
     239                 :            :  * @context: The #GjsContext to profile
     240                 :            :  *
     241                 :            :  * This creates a new profiler for the #JSContext. It is important that
     242                 :            :  * this instance is freed with _gjs_profiler_free() before the context is
     243                 :            :  * destroyed.
     244                 :            :  *
     245                 :            :  * Call gjs_profiler_start() to enable the profiler, and gjs_profiler_stop()
     246                 :            :  * when you have finished.
     247                 :            :  *
     248                 :            :  * The profiler works by enabling the JS profiler in spidermonkey so that
     249                 :            :  * sample information is available. A POSIX timer is used to signal SIGPROF
     250                 :            :  * to the process on a regular interval to collect the most recent profile
     251                 :            :  * sample and stash it away. It is a programming error to mask SIGPROF from
     252                 :            :  * the thread controlling the JS context.
     253                 :            :  *
     254                 :            :  * If another #GjsContext already has a profiler, or @context already has one,
     255                 :            :  * then returns %NULL instead.
     256                 :            :  *
     257                 :            :  * Returns: (transfer full) (nullable): A newly allocated #GjsProfiler
     258                 :            :  */
     259                 :            : GjsProfiler *
     260                 :          5 : _gjs_profiler_new(GjsContext *context)
     261                 :            : {
     262                 :          5 :     g_return_val_if_fail(context, nullptr);
     263                 :            : 
     264         [ -  + ]:          5 :     if (profiling_context == context) {
     265                 :          0 :         g_critical("You can only create one profiler at a time.");
     266                 :          0 :         return nullptr;
     267                 :            :     }
     268                 :            : 
     269         [ -  + ]:          5 :     if (profiling_context) {
     270                 :          0 :         g_message("Not going to profile GjsContext %p; you can only profile "
     271                 :            :                   "one context at a time.", context);
     272                 :          0 :         return nullptr;
     273                 :            :     }
     274                 :            : 
     275                 :          5 :     GjsProfiler *self = g_new0(GjsProfiler, 1);
     276                 :            : 
     277                 :            : #ifdef ENABLE_PROFILER
     278                 :          5 :     self->cx = static_cast<JSContext *>(gjs_context_get_native_context(context));
     279                 :          5 :     self->pid = getpid();
     280                 :            : #endif
     281                 :          5 :     self->fd = -1;
     282                 :            : 
     283                 :          5 :     profiling_context = context;
     284                 :            : 
     285                 :          5 :     return self;
     286                 :            : }
     287                 :            : 
     288                 :            : /*
     289                 :            :  * _gjs_profiler_free:
     290                 :            :  * @self: A #GjsProfiler
     291                 :            :  *
     292                 :            :  * Frees a profiler instance and cleans up any allocated data.
     293                 :            :  *
     294                 :            :  * If the profiler is running, it will be stopped. This may result in blocking
     295                 :            :  * to write the contents of the buffer to the underlying file-descriptor.
     296                 :            :  */
     297                 :            : void
     298                 :          5 : _gjs_profiler_free(GjsProfiler *self)
     299                 :            : {
     300         [ -  + ]:          5 :     if (!self)
     301                 :          0 :         return;
     302                 :            : 
     303         [ -  + ]:          5 :     if (self->running)
     304                 :          0 :         gjs_profiler_stop(self);
     305                 :            : 
     306                 :          5 :     profiling_context = nullptr;
     307                 :            : 
     308         [ +  + ]:          5 :     g_clear_pointer(&self->filename, g_free);
     309                 :            : #ifdef ENABLE_PROFILER
     310         [ -  + ]:          5 :     g_clear_pointer(&self->capture, sysprof_capture_writer_unref);
     311         [ -  + ]:          5 :     g_clear_pointer(&self->periodic_flush, g_source_destroy);
     312         [ -  + ]:          5 :     g_clear_pointer(&self->target_capture, sysprof_capture_writer_unref);
     313                 :            : 
     314         [ -  + ]:          5 :     if (self->fd != -1)
     315                 :          0 :         close(self->fd);
     316                 :            : 
     317                 :          5 :     self->stack.~ProfilingStack();
     318                 :            : #endif
     319                 :          5 :     g_free(self);
     320                 :            : }
     321                 :            : 
     322                 :            : /*
     323                 :            :  * _gjs_profiler_is_running:
     324                 :            :  * @self: A #GjsProfiler
     325                 :            :  *
     326                 :            :  * Checks if the profiler is currently running. This means that the JS
     327                 :            :  * profiler is enabled and POSIX signal timers are registered.
     328                 :            :  *
     329                 :            :  * Returns: %TRUE if the profiler is active.
     330                 :            :  */
     331                 :            : bool
     332                 :        104 : _gjs_profiler_is_running(GjsProfiler *self)
     333                 :            : {
     334                 :        104 :     g_return_val_if_fail(self, false);
     335                 :            : 
     336                 :        104 :     return self->running;
     337                 :            : }
     338                 :            : 
     339                 :            : #ifdef ENABLE_PROFILER
     340                 :            : 
     341                 :          2 : static void gjs_profiler_sigprof(int signum [[maybe_unused]], siginfo_t* info,
     342                 :            :                                  void*) {
     343                 :          2 :     GjsProfiler *self = gjs_context_get_profiler(profiling_context);
     344                 :            : 
     345                 :          2 :     g_assert(((void) "SIGPROF handler called with invalid signal info", info));
     346                 :          2 :     g_assert(((void) "SIGPROF handler called with other signal",
     347                 :            :               info->si_signo == SIGPROF));
     348                 :            : 
     349                 :            :     /*
     350                 :            :      * NOTE:
     351                 :            :      *
     352                 :            :      * This is the SIGPROF signal handler. Everything done in this thread
     353                 :            :      * needs to be things that are safe to do in a signal handler. One thing
     354                 :            :      * that is not okay to do, is *malloc*.
     355                 :            :      */
     356                 :            : 
     357   [ +  -  -  + ]:          2 :     if (!self || info->si_code != SI_TIMER)
     358                 :          1 :         return;
     359                 :            : 
     360                 :          2 :     uint32_t depth = self->stack.stackSize();
     361         [ +  + ]:          2 :     if (depth == 0)
     362                 :          1 :         return;
     363                 :            : 
     364                 :          1 :     int64_t now = g_get_monotonic_time() * 1000L;
     365                 :            : 
     366                 :            :     /* NOTE: cppcheck warns that alloca() is not recommended since it can
     367                 :            :      * easily overflow the stack; however, dynamic allocation is not an option
     368                 :            :      * here since we are in a signal handler.
     369                 :            :      */
     370                 :            :     SysprofCaptureAddress* addrs =
     371                 :            :         // cppcheck-suppress allocaCalled
     372                 :          1 :         static_cast<SysprofCaptureAddress*>(alloca(sizeof *addrs * depth));
     373                 :            : 
     374         [ +  + ]:          2 :     for (uint32_t ix = 0; ix < depth; ix++) {
     375                 :          1 :         js::ProfilingStackFrame& entry = self->stack.frames[ix];
     376                 :          1 :         const char *label = entry.label();
     377                 :          1 :         const char *dynamic_string = entry.dynamicString();
     378                 :          1 :         uint32_t flipped = depth - 1 - ix;
     379                 :          1 :         size_t label_length = strlen(label);
     380                 :            : 
     381                 :            :         /*
     382                 :            :          * 512 is an arbitrarily large size, very likely to be enough to
     383                 :            :          * hold the final string.
     384                 :            :          */
     385                 :            :         char final_string[512];
     386                 :          1 :         char *position = final_string;
     387                 :          1 :         size_t available_length = sizeof (final_string) - 1;
     388                 :            : 
     389         [ +  - ]:          1 :         if (label_length > 0) {
     390         [ +  - ]:          1 :             label_length = MIN(label_length, available_length);
     391                 :            : 
     392                 :            :             /* Start copying the label to the final string */
     393                 :          1 :             memcpy(position, label, label_length);
     394                 :          1 :             available_length -= label_length;
     395                 :          1 :             position += label_length;
     396                 :            : 
     397                 :            :             /*
     398                 :            :              * Add a space in between the label and the dynamic string,
     399                 :            :              * if there is one.
     400                 :            :              */
     401   [ -  +  -  - ]:          1 :             if (dynamic_string && available_length > 0) {
     402                 :          0 :                 *position++ = ' ';
     403                 :          0 :                 available_length--;
     404                 :            :             }
     405                 :            :         }
     406                 :            : 
     407                 :            :         /* Now append the dynamic string at the end of the final string.
     408                 :            :          * The string is cut in case it doesn't fit the remaining space.
     409                 :            :          */
     410         [ -  + ]:          1 :         if (dynamic_string) {
     411                 :          0 :             size_t dynamic_string_length = strlen(dynamic_string);
     412                 :            : 
     413         [ #  # ]:          0 :             if (dynamic_string_length > 0) {
     414         [ #  # ]:          0 :                 size_t remaining_length = MIN(available_length, dynamic_string_length);
     415                 :          0 :                 memcpy(position, dynamic_string, remaining_length);
     416                 :          0 :                 position += remaining_length;
     417                 :            :             }
     418                 :            :         }
     419                 :            : 
     420                 :          1 :         *position = 0;
     421                 :            : 
     422                 :            :         /*
     423                 :            :          * GeckoProfiler will put "js::RunScript" on the stack, but it has
     424                 :            :          * a stack address of "this", which is not terribly useful since
     425                 :            :          * everything will show up as [stack] when building callgraphs.
     426                 :            :          */
     427         [ +  - ]:          1 :         if (final_string[0] != '\0')
     428                 :          1 :             addrs[flipped] =
     429                 :          1 :                 sysprof_capture_writer_add_jitmap(self->capture, final_string);
     430                 :            :         else
     431                 :          0 :             addrs[flipped] = SysprofCaptureAddress(entry.stackAddress());
     432                 :            :     }
     433                 :            : 
     434         [ -  + ]:          1 :     if (!sysprof_capture_writer_add_sample(self->capture, now, -1, self->pid,
     435                 :            :                                            -1, addrs, depth)) {
     436                 :          0 :         gjs_profiler_stop(self);
     437                 :          0 :         return;
     438                 :            :     }
     439                 :            : 
     440                 :            :     unsigned ids[GJS_N_COUNTERS];
     441                 :            :     SysprofCaptureCounterValue values[GJS_N_COUNTERS];
     442                 :          1 :     size_t new_counts = 0;
     443                 :            : 
     444                 :            : #    define FETCH_COUNTERS(name, ix)                       \
     445                 :            :         {                                                  \
     446                 :            :             uint64_t count = GJS_GET_COUNTER(name);        \
     447                 :            :             if (count != self->last_counter_values[ix]) {  \
     448                 :            :                 ids[new_counts] = self->counter_base + ix; \
     449                 :            :                 values[new_counts].v64 = count;            \
     450                 :            :                 new_counts++;                              \
     451                 :            :             }                                              \
     452                 :            :             self->last_counter_values[ix] = count;         \
     453                 :            :         }
     454   [ -  +  -  +  :         16 :     GJS_FOR_EACH_COUNTER(FETCH_COUNTERS);
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
                +  -  + ]
     455                 :            : #    undef FETCH_COUNTERS
     456                 :            : 
     457   [ -  +  -  + ]:          1 :     if (new_counts > 0 &&
     458         [ #  # ]:          0 :         !sysprof_capture_writer_set_counters(self->capture, now, -1, self->pid,
     459                 :            :                                              ids, values, new_counts))
     460                 :          0 :         gjs_profiler_stop(self);
     461                 :            : }
     462                 :            : 
     463                 :          0 : static gboolean profiler_auto_flush_cb(void* user_data) {
     464                 :          0 :     auto* self = static_cast<GjsProfiler*>(user_data);
     465                 :            : 
     466         [ #  # ]:          0 :     if (!self->running)
     467                 :          0 :         return G_SOURCE_REMOVE;
     468                 :            : 
     469                 :          0 :     sysprof_capture_writer_flush(self->capture);
     470                 :            : 
     471                 :          0 :     return G_SOURCE_CONTINUE;
     472                 :            : }
     473                 :            : 
     474                 :            : #endif  /* ENABLE_PROFILER */
     475                 :            : 
     476                 :            : /**
     477                 :            :  * gjs_profiler_start:
     478                 :            :  * @self: A #GjsProfiler
     479                 :            :  *
     480                 :            :  * As expected, this starts the GjsProfiler.
     481                 :            :  *
     482                 :            :  * This will enable the underlying JS profiler and register a POSIX timer to
     483                 :            :  * deliver SIGPROF on the configured sampling frequency.
     484                 :            :  *
     485                 :            :  * To reduce sampling overhead, #GjsProfiler stashes information about the
     486                 :            :  * profile to be calculated once the profiler has been disabled. Calling
     487                 :            :  * gjs_profiler_stop() will result in that delayed work to be completed.
     488                 :            :  *
     489                 :            :  * You should call gjs_profiler_stop() when the profiler is no longer needed.
     490                 :            :  */
     491                 :            : void
     492                 :          5 : gjs_profiler_start(GjsProfiler *self)
     493                 :            : {
     494                 :          5 :     g_return_if_fail(self);
     495         [ -  + ]:          5 :     if (self->running)
     496                 :          0 :         return;
     497                 :            : 
     498                 :            : #ifdef ENABLE_PROFILER
     499                 :            : 
     500                 :          5 :     g_return_if_fail(!self->capture);
     501                 :            : 
     502                 :          5 :     struct sigaction sa = {{0}};
     503                 :          5 :     struct sigevent sev = {{0}};
     504                 :          5 :     struct itimerspec its = {{0}};
     505                 :            :     struct itimerspec old_its;
     506                 :            : 
     507         [ -  + ]:          5 :     if (self->target_capture) {
     508                 :          0 :         self->capture = sysprof_capture_writer_ref(self->target_capture);
     509         [ -  + ]:          5 :     } else if (self->fd != -1) {
     510                 :          0 :         self->capture = sysprof_capture_writer_new_from_fd(self->fd, 0);
     511                 :          0 :         self->fd = -1;
     512                 :            :     } else {
     513                 :         10 :         GjsAutoChar path = g_strdup(self->filename);
     514         [ +  + ]:          5 :         if (!path)
     515                 :          3 :             path = g_strdup_printf("gjs-%jd.syscap", intmax_t(self->pid));
     516                 :            : 
     517                 :          5 :         self->capture = sysprof_capture_writer_new(path, 0);
     518                 :          5 :     }
     519                 :            : 
     520         [ -  + ]:          5 :     if (!self->capture) {
     521                 :          0 :         g_warning("Failed to open profile capture");
     522                 :          0 :         return;
     523                 :            :     }
     524                 :            : 
     525                 :            :     /* Automatically flush to be resilient against SIGINT, etc */
     526         [ +  - ]:          5 :     if (!self->periodic_flush) {
     527                 :          5 :         self->periodic_flush =
     528                 :          5 :             g_timeout_source_new_seconds(FLUSH_DELAY_SECONDS);
     529                 :          5 :         g_source_set_name(self->periodic_flush,
     530                 :            :                           "[sysprof-capture-writer-flush]");
     531                 :          5 :         g_source_set_priority(self->periodic_flush, G_PRIORITY_LOW + 100);
     532                 :          5 :         g_source_set_callback(self->periodic_flush,
     533                 :            :                               (GSourceFunc)profiler_auto_flush_cb, self,
     534                 :            :                               nullptr);
     535                 :          5 :         g_source_attach(self->periodic_flush,
     536                 :            :                         g_main_context_get_thread_default());
     537                 :            :     }
     538                 :            : 
     539         [ -  + ]:          5 :     if (!gjs_profiler_extract_maps(self)) {
     540                 :          0 :         g_warning("Failed to extract proc maps");
     541         [ #  # ]:          0 :         g_clear_pointer(&self->capture, sysprof_capture_writer_unref);
     542         [ #  # ]:          0 :         g_clear_pointer(&self->periodic_flush, g_source_destroy);
     543                 :          0 :         return;
     544                 :            :     }
     545                 :            : 
     546         [ -  + ]:          5 :     if (!gjs_profiler_define_counters(self)) {
     547                 :          0 :         g_warning("Failed to define sysprof counters");
     548         [ #  # ]:          0 :         g_clear_pointer(&self->capture, sysprof_capture_writer_unref);
     549         [ #  # ]:          0 :         g_clear_pointer(&self->periodic_flush, g_source_destroy);
     550                 :          0 :         return;
     551                 :            :     }
     552                 :            : 
     553                 :            :     /* Setup our signal handler for SIGPROF delivery */
     554                 :          5 :     sa.sa_flags = SA_RESTART | SA_SIGINFO;
     555                 :          5 :     sa.sa_sigaction = gjs_profiler_sigprof;
     556                 :          5 :     sigemptyset(&sa.sa_mask);
     557                 :            : 
     558         [ -  + ]:          5 :     if (sigaction(SIGPROF, &sa, nullptr) == -1) {
     559                 :          0 :         g_warning("Failed to register sigaction handler: %s", g_strerror(errno));
     560         [ #  # ]:          0 :         g_clear_pointer(&self->capture, sysprof_capture_writer_unref);
     561         [ #  # ]:          0 :         g_clear_pointer(&self->periodic_flush, g_source_destroy);
     562                 :          0 :         return;
     563                 :            :     }
     564                 :            : 
     565                 :            :     /*
     566                 :            :      * Create our SIGPROF timer
     567                 :            :      *
     568                 :            :      * We want to receive a SIGPROF signal on the JS thread using our
     569                 :            :      * configured sampling frequency. Instead of allowing any thread to be
     570                 :            :      * notified, we set the _tid value to ensure that only our thread gets
     571                 :            :      * delivery of the signal. This feature is generally just for
     572                 :            :      * threading implementations, but it works for us as well and ensures
     573                 :            :      * that the thread is blocked while we capture the stack.
     574                 :            :      */
     575                 :          5 :     sev.sigev_notify = SIGEV_THREAD_ID;
     576                 :          5 :     sev.sigev_signo = SIGPROF;
     577                 :          5 :     sev._sigev_un._tid = syscall(__NR_gettid);
     578                 :            : 
     579         [ -  + ]:          5 :     if (timer_create(CLOCK_MONOTONIC, &sev, &self->timer) == -1) {
     580                 :          0 :         g_warning("Failed to create profiler timer: %s", g_strerror(errno));
     581         [ #  # ]:          0 :         g_clear_pointer(&self->capture, sysprof_capture_writer_unref);
     582         [ #  # ]:          0 :         g_clear_pointer(&self->periodic_flush, g_source_destroy);
     583                 :          0 :         return;
     584                 :            :     }
     585                 :            : 
     586                 :            :     /* Calculate sampling interval */
     587                 :          5 :     its.it_interval.tv_sec = 0;
     588                 :          5 :     its.it_interval.tv_nsec = NSEC_PER_SEC / SAMPLES_PER_SEC;
     589                 :          5 :     its.it_value.tv_sec = 0;
     590                 :          5 :     its.it_value.tv_nsec = NSEC_PER_SEC / SAMPLES_PER_SEC;
     591                 :            : 
     592                 :            :     /* Now start this timer */
     593         [ -  + ]:          5 :     if (timer_settime(self->timer, 0, &its, &old_its) != 0) {
     594                 :          0 :         g_warning("Failed to enable profiler timer: %s", g_strerror(errno));
     595                 :          0 :         timer_delete(self->timer);
     596         [ #  # ]:          0 :         g_clear_pointer(&self->capture, sysprof_capture_writer_unref);
     597         [ #  # ]:          0 :         g_clear_pointer(&self->periodic_flush, g_source_destroy);
     598                 :          0 :         return;
     599                 :            :     }
     600                 :            : 
     601                 :          5 :     self->running = true;
     602                 :            : 
     603                 :            :     /* Notify the JS runtime of where to put stack info */
     604                 :          5 :     js::SetContextProfilingStack(self->cx, &self->stack);
     605                 :            : 
     606                 :            :     /* Start recording stack info */
     607                 :          5 :     js::EnableContextProfilingStack(self->cx, true);
     608                 :            : 
     609                 :          5 :     g_message("Profiler started");
     610                 :            : 
     611                 :            : #else  /* !ENABLE_PROFILER */
     612                 :            : 
     613                 :            :     self->running = true;
     614                 :            :     g_message("Profiler is disabled. Recompile with it enabled to use.");
     615                 :            : 
     616                 :            : #endif  /* ENABLE_PROFILER */
     617                 :            : }
     618                 :            : 
     619                 :            : /**
     620                 :            :  * gjs_profiler_stop:
     621                 :            :  * @self: A #GjsProfiler
     622                 :            :  *
     623                 :            :  * Stops a currently running #GjsProfiler. If the profiler is not running,
     624                 :            :  * this function will do nothing.
     625                 :            :  *
     626                 :            :  * Some work may be delayed until the end of the capture. Such delayed work
     627                 :            :  * includes flushing the resulting samples and file location information to
     628                 :            :  * disk.
     629                 :            :  *
     630                 :            :  * This may block while writing to disk. Generally, the writes are delivered
     631                 :            :  * to a tmpfs device, and are therefore negligible.
     632                 :            :  */
     633                 :            : void
     634                 :          5 : gjs_profiler_stop(GjsProfiler *self)
     635                 :            : {
     636                 :            :     /* Note: can be called from a signal handler */
     637                 :            : 
     638                 :          5 :     g_assert(self);
     639                 :            : 
     640         [ -  + ]:          5 :     if (!self->running)
     641                 :          0 :         return;
     642                 :            : 
     643                 :            : #ifdef ENABLE_PROFILER
     644                 :            : 
     645                 :          5 :     struct itimerspec its = {{0}};
     646                 :          5 :     timer_settime(self->timer, 0, &its, nullptr);
     647                 :          5 :     timer_delete(self->timer);
     648                 :            : 
     649                 :          5 :     js::EnableContextProfilingStack(self->cx, false);
     650                 :          5 :     js::SetContextProfilingStack(self->cx, nullptr);
     651                 :            : 
     652                 :          5 :     sysprof_capture_writer_flush(self->capture);
     653                 :            : 
     654         [ +  - ]:          5 :     g_clear_pointer(&self->capture, sysprof_capture_writer_unref);
     655         [ +  - ]:          5 :     g_clear_pointer(&self->periodic_flush, g_source_destroy);
     656                 :            : 
     657                 :          5 :     g_message("Profiler stopped");
     658                 :            : 
     659                 :            : #endif  /* ENABLE_PROFILER */
     660                 :            : 
     661                 :          5 :     self->running = false;
     662                 :            : }
     663                 :            : 
     664                 :            : #ifdef ENABLE_PROFILER
     665                 :            : 
     666                 :            : static gboolean
     667                 :          0 : gjs_profiler_sigusr2(void *data)
     668                 :            : {
     669                 :          0 :     GjsContext* context = GJS_CONTEXT(data);
     670                 :          0 :     GjsProfiler *current_profiler = gjs_context_get_profiler(context);
     671                 :            : 
     672         [ #  # ]:          0 :     if (current_profiler) {
     673         [ #  # ]:          0 :         if (_gjs_profiler_is_running(current_profiler))
     674                 :          0 :             gjs_profiler_stop(current_profiler);
     675                 :            :         else
     676                 :          0 :             gjs_profiler_start(current_profiler);
     677                 :            :     }
     678                 :            : 
     679                 :          0 :     return G_SOURCE_CONTINUE;
     680                 :            : }
     681                 :            : 
     682                 :            : #endif  /* ENABLE_PROFILER */
     683                 :            : 
     684                 :            : /*
     685                 :            :  * _gjs_profiler_setup_signals:
     686                 :            :  * @context: a #GjsContext with a profiler attached
     687                 :            :  *
     688                 :            :  * If you want to simply allow profiling of your process with minimal
     689                 :            :  * fuss, simply call gjs_profiler_setup_signals(). This will allow
     690                 :            :  * enabling and disabling the profiler with SIGUSR2. You must call
     691                 :            :  * this from main() immediately when your program starts and must not
     692                 :            :  * block SIGUSR2 from your signal mask.
     693                 :            :  *
     694                 :            :  * If this is not sufficient, use gjs_profiler_chain_signal() from your
     695                 :            :  * own signal handler to pass the signal to a GjsProfiler.
     696                 :            :  */
     697                 :            : void
     698                 :          0 : _gjs_profiler_setup_signals(GjsProfiler *self,
     699                 :            :                             GjsContext  *context)
     700                 :            : {
     701                 :          0 :     g_return_if_fail(context == profiling_context);
     702                 :            : 
     703                 :            : #ifdef ENABLE_PROFILER
     704                 :            : 
     705         [ #  # ]:          0 :     if (self->sigusr2_id != 0)
     706                 :          0 :         return;
     707                 :            : 
     708                 :          0 :     self->sigusr2_id = g_unix_signal_add(SIGUSR2, gjs_profiler_sigusr2, context);
     709                 :            : 
     710                 :            : #else  /* !ENABLE_PROFILER */
     711                 :            : 
     712                 :            :     g_message("Profiler is disabled. Not setting up signals.");
     713                 :            :     (void)self;
     714                 :            : 
     715                 :            : #endif  /* ENABLE_PROFILER */
     716                 :            : }
     717                 :            : 
     718                 :            : /**
     719                 :            :  * gjs_profiler_chain_signal:
     720                 :            :  * @context: a #GjsContext with a profiler attached
     721                 :            :  * @info: #siginfo_t passed in to signal handler
     722                 :            :  *
     723                 :            :  * Use this to pass a signal info caught by another signal handler to a
     724                 :            :  * GjsProfiler. This might be needed if you have your own complex signal
     725                 :            :  * handling system for which GjsProfiler cannot simply add a SIGUSR2 handler.
     726                 :            :  *
     727                 :            :  * This function should only be called from the JS thread.
     728                 :            :  *
     729                 :            :  * Returns: %TRUE if the signal was handled.
     730                 :            :  */
     731                 :            : bool
     732                 :          0 : gjs_profiler_chain_signal(GjsContext *context,
     733                 :            :                           siginfo_t *info)
     734                 :            : {
     735                 :            : #ifdef ENABLE_PROFILER
     736                 :            : 
     737         [ #  # ]:          0 :     if (info) {
     738         [ #  # ]:          0 :         if (info->si_signo == SIGPROF) {
     739                 :          0 :             gjs_profiler_sigprof(SIGPROF, info, nullptr);
     740                 :          0 :             return true;
     741                 :            :         }
     742                 :            : 
     743         [ #  # ]:          0 :         if (info->si_signo == SIGUSR2) {
     744                 :          0 :             gjs_profiler_sigusr2(context);
     745                 :          0 :             return true;
     746                 :            :         }
     747                 :            :     }
     748                 :            : 
     749                 :            : #else  // !ENABLE_PROFILER
     750                 :            : 
     751                 :            :     (void)context;
     752                 :            :     (void)info;
     753                 :            : 
     754                 :            : #endif  /* ENABLE_PROFILER */
     755                 :            : 
     756                 :          0 :     return false;
     757                 :            : }
     758                 :            : 
     759                 :            : /**
     760                 :            :  * gjs_profiler_set_capture_writer:
     761                 :            :  * @self: A #GjsProfiler
     762                 :            :  * @capture: (nullable): A #SysprofCaptureWriter
     763                 :            :  *
     764                 :            :  * Set the capture writer to which profiling data is written when the @self
     765                 :            :  * is stopped.
     766                 :            :  */
     767                 :          0 : void gjs_profiler_set_capture_writer(GjsProfiler* self, gpointer capture) {
     768                 :          0 :     g_return_if_fail(self);
     769                 :          0 :     g_return_if_fail(!self->running);
     770                 :            : 
     771                 :            : #ifdef ENABLE_PROFILER
     772         [ #  # ]:          0 :     g_clear_pointer(&self->target_capture, sysprof_capture_writer_unref);
     773                 :          0 :     self->target_capture =
     774         [ #  # ]:          0 :         capture ? sysprof_capture_writer_ref(
     775                 :            :                       reinterpret_cast<SysprofCaptureWriter*>(capture))
     776                 :            :                 : NULL;
     777                 :            : #else
     778                 :            :     // Unused in the no-profiler case
     779                 :            :     (void)capture;
     780                 :            : #endif
     781                 :            : }
     782                 :            : 
     783                 :            : /**
     784                 :            :  * gjs_profiler_set_filename:
     785                 :            :  * @self: A #GjsProfiler
     786                 :            :  * @filename: string containing a filename
     787                 :            :  *
     788                 :            :  * Set the file to which profiling data is written when the @self is stopped.
     789                 :            :  * By default, this is `gjs-$PID.syscap` in the current directory.
     790                 :            :  */
     791                 :            : void
     792                 :          2 : gjs_profiler_set_filename(GjsProfiler *self,
     793                 :            :                           const char  *filename)
     794                 :            : {
     795                 :          2 :     g_return_if_fail(self);
     796                 :          2 :     g_return_if_fail(!self->running);
     797                 :            : 
     798                 :          2 :     g_free(self->filename);
     799                 :          2 :     self->filename = g_strdup(filename);
     800                 :            : }
     801                 :            : 
     802                 :          0 : void _gjs_profiler_add_mark(GjsProfiler* self, int64_t time_nsec,
     803                 :            :                             int64_t duration_nsec, const char* group,
     804                 :            :                             const char* name, const char* message) {
     805                 :          0 :     g_return_if_fail(self);
     806                 :          0 :     g_return_if_fail(group);
     807                 :          0 :     g_return_if_fail(name);
     808                 :            : 
     809                 :            : #ifdef ENABLE_PROFILER
     810   [ #  #  #  # ]:          0 :     if (self->running && self->capture != nullptr) {
     811                 :          0 :         sysprof_capture_writer_add_mark(self->capture, time_nsec, -1, self->pid,
     812                 :            :                                         duration_nsec, group, name, message);
     813                 :            :     }
     814                 :            : #else
     815                 :            :     // Unused in the no-profiler case
     816                 :            :     (void)time_nsec;
     817                 :            :     (void)duration_nsec;
     818                 :            :     (void)message;
     819                 :            : #endif
     820                 :            : }
     821                 :            : 
     822                 :          0 : bool _gjs_profiler_sample_gc_memory_info(
     823                 :            :     GjsProfiler* self, int64_t gc_counters[Gjs::GCCounters::N_COUNTERS]) {
     824                 :          0 :     g_return_val_if_fail(self, false);
     825                 :            : 
     826                 :            : #ifdef ENABLE_PROFILER
     827   [ #  #  #  # ]:          0 :     if (self->running && self->capture) {
     828                 :            :         unsigned ids[Gjs::GCCounters::N_COUNTERS];
     829                 :            :         SysprofCaptureCounterValue values[Gjs::GCCounters::N_COUNTERS];
     830                 :            : 
     831         [ #  # ]:          0 :         for (size_t ix = 0; ix < Gjs::GCCounters::N_COUNTERS; ix++) {
     832                 :          0 :             ids[ix] = self->gc_counter_base + ix;
     833                 :          0 :             values[ix].v64 = gc_counters[ix];
     834                 :            :         }
     835                 :            : 
     836                 :          0 :         int64_t now = g_get_monotonic_time() * 1000L;
     837         [ #  # ]:          0 :         if (!sysprof_capture_writer_set_counters(self->capture, now, -1,
     838                 :            :                                                  self->pid, ids, values,
     839                 :            :                                                  Gjs::GCCounters::N_COUNTERS))
     840                 :          0 :             return false;
     841                 :            :     }
     842                 :            : #else
     843                 :            :     // Unused in the no-profiler case
     844                 :            :     (void)gc_counters;
     845                 :            : #endif
     846                 :          0 :     return true;
     847                 :            : }
     848                 :            : 
     849                 :          0 : void gjs_profiler_set_fd(GjsProfiler* self, int fd) {
     850                 :          0 :     g_return_if_fail(self);
     851                 :          0 :     g_return_if_fail(!self->filename);
     852                 :          0 :     g_return_if_fail(!self->running);
     853                 :            : 
     854                 :            : #ifdef ENABLE_PROFILER
     855         [ #  # ]:          0 :     if (self->fd != fd) {
     856         [ #  # ]:          0 :         if (self->fd != -1)
     857                 :          0 :             close(self->fd);
     858                 :          0 :         self->fd = fd;
     859                 :            :     }
     860                 :            : #else
     861                 :            :     (void)fd;  // Unused in the no-profiler case
     862                 :            : #endif
     863                 :            : }

Generated by: LCOV version 1.14