lowrail-profile 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,670 @@
1
+ #define _GNU_SOURCE
2
+ #include <ruby.h>
3
+ #include <ruby/debug.h>
4
+ #include <stdint.h>
5
+ #include <stdlib.h>
6
+ #include <string.h>
7
+
8
+ /* Objects allocated per source line inside windows (lowrail/profile): a
9
+ * request (Rails::Engine#call), a job (perform_now), a mail (build or
10
+ * delivery) or an Action Cable channel action. One internal NEWOBJ hook, as
11
+ * objspace's allocation tracing uses, but it keeps counts instead of
12
+ * per-object records, so GC stays on and nothing is retained. The hook never
13
+ * allocates Ruby objects or calls Ruby; its tables use libc malloc so it
14
+ * cannot start a GC. Lines are attributed like
15
+ * ObjectSpace.allocation_sourcefile/sourceline: the nearest Ruby frame.
16
+ *
17
+ * Every function runs in the main Ractor with the GVL held (lowrail/profile
18
+ * calls none of them from another Ractor, and NEWOBJ hooks are per Ractor),
19
+ * so the process-global tables need no lock. They are not Ractor-safe. */
20
+
21
+ #define KINDS 4
22
+ /* Lowrail::Profile::API: lowrail/profile refuses an extension built from
23
+ * other sources (an older cache) before it hooks anything. */
24
+ #define API 3
25
+
26
+ typedef struct {
27
+ uint64_t key; /* via << 63 | kind << 61 | path id << 35 | line << 5 | ruby type; 0 = empty */
28
+ uint64_t count;
29
+ uint64_t requests; /* windows in which the line allocated */
30
+ uint64_t first; /* objects of its first window: the one that reached the line first */
31
+ uint64_t owner; /* that window's id, reserved at its first touch, before it closes */
32
+ } site_t;
33
+
34
+ static site_t *sites;
35
+ static size_t sites_cap, sites_len;
36
+
37
+ /* Interned strings: source paths and window names ("RoomsController#show"). */
38
+ static char **paths;
39
+ static size_t *path_lens;
40
+ static size_t paths_len, paths_cap;
41
+ static size_t *path_index; /* open addressing: path id + 1; 0 = empty */
42
+ static size_t path_index_cap;
43
+
44
+ static struct { VALUE str; size_t id; } path_cache[1024];
45
+
46
+ /* Per window name (kind, name id + 1; 0 = no name): windows, objects
47
+ * ObjectSpace can see, those of its first window in this process, and those
48
+ * allocated inside a network connect, which objects leaves out. */
49
+ typedef struct { uint64_t kind, name, windows, objects, first, net; } action_t;
50
+ static action_t *actions;
51
+ static size_t actions_cap, actions_len;
52
+
53
+ /* Attribution (the repeat run): per window name, allocating line and the
54
+ * nearest app frame (path id + 1 << 32 | line; caller 0 = none). Each window
55
+ * buffers its own pairs until it ends and its name is known. */
56
+ typedef struct { uint64_t site, caller, count; } pend_t;
57
+ typedef struct { uint64_t kind, name, site, caller, count, first; } attrib_t;
58
+ static attrib_t *attribs;
59
+ static size_t attribs_cap, attribs_len;
60
+ static int attributing;
61
+ static char *app_root;
62
+ static size_t app_root_len;
63
+
64
+ /* An open window, owned by the fiber (and its Ruby thread) that entered it,
65
+ * so overlapping threads (M:N included) and independent fibers each have
66
+ * their own. Its sites and pairs are merged once when it closes; the slot
67
+ * and its buffers are then reused, so threads that come and go leave
68
+ * nothing behind. The owner is marked (pinned) while the window is open, so
69
+ * a fiber abandoned inside a window stays alive; past MAX_OPEN open windows
70
+ * the oldest one off the current fiber is dropped (counted in dropped),
71
+ * which bounds that. (Ruby 4.0 exports no weak marking to extensions.) */
72
+ typedef struct { uint64_t key, count; } seen_t;
73
+ typedef struct {
74
+ VALUE thread, fiber; /* fiber 0 = free slot */
75
+ int depth, connect; /* connect: inside Socket.tcp (Lowrail::Profile.connect) */
76
+ uint64_t id, kind, name, objects, net;
77
+ seen_t *seen;
78
+ size_t seen_cap, seen_len;
79
+ pend_t *pend;
80
+ size_t pend_cap, pend_len;
81
+ } win_t;
82
+ static win_t *wins;
83
+ static size_t wins_cap, wins_open;
84
+ /* Buffers larger than this are freed when their window closes. */
85
+ #define KEEP_CAP (1 << 16)
86
+ #define MAX_OPEN 1024
87
+
88
+ static uint64_t windows[KINDS], objects[KINDS], dropped, window_seq;
89
+ static VALUE tracepoint = Qnil;
90
+
91
+ static uint64_t
92
+ mix(uint64_t x)
93
+ {
94
+ x ^= x >> 33; x *= 0xff51afd7ed558ccdULL; x ^= x >> 33;
95
+ return x;
96
+ }
97
+
98
+ static uint64_t
99
+ str_hash(const char *p, size_t n)
100
+ {
101
+ uint64_t h = 1469598103934665603ULL;
102
+ for (size_t i = 0; i < n; i++) h = (h ^ (unsigned char)p[i]) * 1099511628211ULL;
103
+ return h;
104
+ }
105
+
106
+ static int
107
+ path_index_grow(void)
108
+ {
109
+ size_t cap = path_index_cap ? path_index_cap * 2 : 1024;
110
+ size_t *index = calloc(cap, sizeof(size_t));
111
+ if (!index) return 0;
112
+ for (size_t id = 0; id < paths_len; id++) {
113
+ size_t i = str_hash(paths[id], path_lens[id]) & (cap - 1);
114
+ while (index[i]) i = (i + 1) & (cap - 1);
115
+ index[i] = id + 1;
116
+ }
117
+ free(path_index);
118
+ path_index = index;
119
+ path_index_cap = cap;
120
+ return 1;
121
+ }
122
+
123
+ /* SIZE_MAX when out of memory. */
124
+ static size_t
125
+ intern(const char *p, size_t n)
126
+ {
127
+ if ((paths_len + 1) * 2 > path_index_cap && !path_index_grow()) return SIZE_MAX;
128
+ size_t i = str_hash(p, n) & (path_index_cap - 1);
129
+ while (path_index[i]) {
130
+ size_t id = path_index[i] - 1;
131
+ if (path_lens[id] == n && memcmp(paths[id], p, n) == 0) return id;
132
+ i = (i + 1) & (path_index_cap - 1);
133
+ }
134
+ if (paths_len == paths_cap) {
135
+ size_t cap = paths_cap ? paths_cap * 2 : 512;
136
+ char **np = realloc(paths, cap * sizeof(char *));
137
+ if (!np) return SIZE_MAX;
138
+ paths = np;
139
+ size_t *nl = realloc(path_lens, cap * sizeof(size_t));
140
+ if (!nl) return SIZE_MAX;
141
+ path_lens = nl;
142
+ paths_cap = cap;
143
+ }
144
+ char *copy = malloc(n + 1);
145
+ if (!copy) return SIZE_MAX;
146
+ memcpy(copy, p, n);
147
+ copy[n] = 0;
148
+ paths[paths_len] = copy;
149
+ path_lens[paths_len] = n;
150
+ path_index[i] = paths_len + 1;
151
+ return paths_len++;
152
+ }
153
+
154
+ static size_t
155
+ path_id(VALUE str)
156
+ {
157
+ const char *p = RSTRING_PTR(str);
158
+ size_t n = RSTRING_LEN(str);
159
+ size_t slot = (str >> 3) & 1023;
160
+ size_t cached = path_cache[slot].id;
161
+ if (path_cache[slot].str == str && cached < paths_len && path_lens[cached] == n && memcmp(paths[cached], p, n) == 0) return cached;
162
+ size_t id = intern(p, n);
163
+ if (id != SIZE_MAX) {
164
+ path_cache[slot].str = str;
165
+ path_cache[slot].id = id;
166
+ }
167
+ return id;
168
+ }
169
+
170
+ static int
171
+ sites_grow(void)
172
+ {
173
+ size_t cap = sites_cap ? sites_cap * 2 : 1 << 14;
174
+ site_t *table = calloc(cap, sizeof(site_t));
175
+ if (!table) return 0;
176
+ for (size_t j = 0; j < sites_cap; j++) {
177
+ if (!sites[j].key) continue;
178
+ size_t i = mix(sites[j].key) & (cap - 1);
179
+ while (table[i].key) i = (i + 1) & (cap - 1);
180
+ table[i] = sites[j];
181
+ }
182
+ free(sites);
183
+ sites = table;
184
+ sites_cap = cap;
185
+ return 1;
186
+ }
187
+
188
+ static uint64_t
189
+ attrib_hash(uint64_t k, uint64_t n, uint64_t site, uint64_t caller)
190
+ {
191
+ return mix(site ^ mix(caller ^ mix((n << 2) | k)));
192
+ }
193
+
194
+ static int
195
+ attribs_grow(void)
196
+ {
197
+ size_t cap = attribs_cap ? attribs_cap * 2 : 1 << 14;
198
+ attrib_t *table = calloc(cap, sizeof(attrib_t));
199
+ if (!table) return 0;
200
+ for (size_t j = 0; j < attribs_cap; j++) {
201
+ attrib_t *a = &attribs[j];
202
+ if (!a->site) continue;
203
+ size_t i = attrib_hash(a->kind, a->name, a->site, a->caller) & (cap - 1);
204
+ while (table[i].site) i = (i + 1) & (cap - 1);
205
+ table[i] = *a;
206
+ }
207
+ free(attribs);
208
+ attribs = table;
209
+ attribs_cap = cap;
210
+ return 1;
211
+ }
212
+
213
+ /* Open addressing on {key, count} pairs (window sites, attribution pairs). */
214
+ static int
215
+ grow_pairs(void **table, size_t *cap, size_t size, size_t key_words)
216
+ {
217
+ size_t ncap = *cap ? *cap * 2 : 256;
218
+ char *next = calloc(ncap, size);
219
+ if (!next) return 0;
220
+ char *old = *table;
221
+ for (size_t j = 0; j < *cap; j++) {
222
+ uint64_t *e = (uint64_t *)(old + j * size);
223
+ if (!e[0]) continue;
224
+ uint64_t h = e[0];
225
+ for (size_t w = 1; w < key_words; w++) h ^= mix(e[w]);
226
+ size_t i = mix(h) & (ncap - 1);
227
+ while (*(uint64_t *)(next + i * size)) i = (i + 1) & (ncap - 1);
228
+ memcpy(next + i * size, e, size);
229
+ }
230
+ free(old);
231
+ *table = next;
232
+ *cap = ncap;
233
+ return 1;
234
+ }
235
+
236
+ /* The nearest frame in the app's own code: under the app root, but not gems
237
+ * vendored there (vendor/bundle, gems/) and not the test suite (test/, spec/),
238
+ * whose request calls sit under every request. No Ruby calls:
239
+ * rb_profile_frames reads frames without allocating. */
240
+ static uint64_t
241
+ app_caller(void)
242
+ {
243
+ VALUE frames[128];
244
+ int lines[128];
245
+ int n = rb_profile_frames(0, 128, frames, lines);
246
+ for (int f = 0; f < n; f++) {
247
+ VALUE fpath = rb_profile_frame_path(frames[f]);
248
+ if (!RB_TYPE_P(fpath, T_STRING) || lines[f] <= 0 || (size_t)RSTRING_LEN(fpath) <= app_root_len) continue;
249
+ if (memcmp(RSTRING_PTR(fpath), app_root, app_root_len) != 0) continue;
250
+ const char *rest = RSTRING_PTR(fpath) + app_root_len;
251
+ size_t rest_len = RSTRING_LEN(fpath) - app_root_len;
252
+ if (rest_len > 5 && (memcmp(rest, "gems/", 5) == 0 || memcmp(rest, "test/", 5) == 0 || memcmp(rest, "spec/", 5) == 0)) continue;
253
+ if (memmem(rest, rest_len, "/gems/", 6)) continue;
254
+ size_t id = path_id(fpath);
255
+ return id == SIZE_MAX ? 0 : ((uint64_t)(id + 1) << 32) | (uint32_t)lines[f];
256
+ }
257
+ return 0;
258
+ }
259
+
260
+ static void
261
+ attribute(win_t *w, uint64_t site)
262
+ {
263
+ uint64_t caller = app_caller();
264
+ if ((w->pend_len + 1) * 2 > w->pend_cap && !grow_pairs((void **)&w->pend, &w->pend_cap, sizeof(pend_t), 2)) { dropped++; return; }
265
+ size_t i = mix(site ^ mix(caller)) & (w->pend_cap - 1);
266
+ while (w->pend[i].site && (w->pend[i].site != site || w->pend[i].caller != caller)) i = (i + 1) & (w->pend_cap - 1);
267
+ if (!w->pend[i].site) { w->pend[i].site = site; w->pend[i].caller = caller; w->pend_len++; }
268
+ w->pend[i].count++;
269
+ }
270
+
271
+ static int
272
+ visible(VALUE obj)
273
+ {
274
+ switch (BUILTIN_TYPE(obj)) {
275
+ case T_NONE: case T_IMEMO: case T_NODE: case T_ICLASS: case T_ZOMBIE: case T_MOVED: return 0;
276
+ default: return 1;
277
+ }
278
+ }
279
+
280
+ static win_t *
281
+ window_of(VALUE fiber)
282
+ {
283
+ for (size_t i = 0; i < wins_cap; i++) if (wins[i].fiber == fiber) return &wins[i];
284
+ return NULL;
285
+ }
286
+
287
+ /* The current fiber's open window, or NULL. A thread with no open window
288
+ * returns before asking for its fiber: rb_fiber_current allocates a root
289
+ * fiber's object the first time. A thread with one has it already (enter
290
+ * asked, and switching to any other fiber creates the root's). */
291
+ static win_t *
292
+ current_window(void)
293
+ {
294
+ if (!wins_open) return NULL;
295
+ VALUE thread = rb_thread_current();
296
+ size_t i = 0;
297
+ while (i < wins_cap && !(wins[i].fiber && wins[i].thread == thread)) i++;
298
+ if (i == wins_cap) return NULL;
299
+ return window_of(rb_fiber_current());
300
+ }
301
+
302
+ static site_t *site_for(uint64_t key);
303
+
304
+ static void
305
+ newobj(VALUE tpval, void *data)
306
+ {
307
+ win_t *w = current_window();
308
+ if (!w) return;
309
+ rb_trace_arg_t *arg = rb_tracearg_from_tracepoint(tpval);
310
+ VALUE obj = rb_tracearg_object(arg);
311
+ VALUE path = rb_tracearg_path(arg);
312
+ /* Code evaluated from a negative line (ERB compiled at -1) counts at line 0. */
313
+ long lineno = NUM2LONG(rb_tracearg_lineno(arg));
314
+ uint64_t line = lineno > 0 ? (uint64_t)lineno : 0;
315
+ uint64_t via = 0;
316
+ /* Ruby's own <internal:...> frames (Pathname, Kernel#tap, ...) are charged
317
+ * to their nearest caller outside them, flagged in bit 63. */
318
+ if (RB_TYPE_P(path, T_STRING) && RSTRING_LEN(path) > 10 && memcmp(RSTRING_PTR(path), "<internal:", 10) == 0) {
319
+ VALUE frames[16];
320
+ int lines[16];
321
+ int n = rb_profile_frames(0, 16, frames, lines);
322
+ for (int f = 0; f < n; f++) {
323
+ VALUE fpath = rb_profile_frame_path(frames[f]);
324
+ if (!RB_TYPE_P(fpath, T_STRING) || lines[f] <= 0) continue;
325
+ if (RSTRING_LEN(fpath) > 10 && memcmp(RSTRING_PTR(fpath), "<internal:", 10) == 0) continue;
326
+ path = fpath;
327
+ line = lines[f];
328
+ via = 1ULL << 63;
329
+ break;
330
+ }
331
+ }
332
+ objects[w->kind]++;
333
+ int seen = visible(obj);
334
+ /* A connect's objects follow timing (Happy Eyeballs races its attempts on
335
+ * threads and timers): counted apart, in no line. */
336
+ if (w->connect) { if (seen) w->net++; return; }
337
+ if (seen) w->objects++;
338
+ size_t id = RB_TYPE_P(path, T_STRING) ? path_id(path) : 0;
339
+ if (id == SIZE_MAX || line >= (1ULL << 30) || id + 1 >= (1ULL << 26)) { dropped++; return; }
340
+ /* Path id 0 means no Ruby frame: real ids are shifted by one. */
341
+ uint64_t pid = RB_TYPE_P(path, T_STRING) ? id + 1 : 0;
342
+ uint64_t key = via | (w->kind << 61) | (pid << 35) | (line << 5) | (BUILTIN_TYPE(obj) & 31);
343
+ if (!key) key = 1ULL << 5; /* never collide with the empty marker */
344
+ if ((w->seen_len + 1) * 2 > w->seen_cap && !grow_pairs((void **)&w->seen, &w->seen_cap, sizeof(seen_t), 1)) { dropped++; return; }
345
+ size_t i = mix(key) & (w->seen_cap - 1);
346
+ while (w->seen[i].key && w->seen[i].key != key) i = (i + 1) & (w->seen_cap - 1);
347
+ if (!w->seen[i].key) {
348
+ w->seen[i].key = key;
349
+ w->seen_len++;
350
+ /* The first window to touch a line owns its first count, however the
351
+ * windows close; the global entry is reserved now, merged at close. */
352
+ site_t *s = site_for(key);
353
+ if (s && !s->owner && !s->requests) s->owner = w->id;
354
+ }
355
+ w->seen[i].count++;
356
+ if (attributing && seen && pid) attribute(w, (pid << 32) | line);
357
+ }
358
+
359
+ static action_t *
360
+ action_for(uint64_t k, uint64_t n)
361
+ {
362
+ if ((actions_len + 1) * 2 > actions_cap) {
363
+ size_t cap = actions_cap ? actions_cap * 2 : 256;
364
+ action_t *table = calloc(cap, sizeof(action_t));
365
+ if (!table) return NULL;
366
+ for (size_t j = 0; j < actions_cap; j++) {
367
+ if (!actions[j].windows) continue;
368
+ size_t i = mix((actions[j].name << 2) | actions[j].kind) & (cap - 1);
369
+ while (table[i].windows) i = (i + 1) & (cap - 1);
370
+ table[i] = actions[j];
371
+ }
372
+ free(actions);
373
+ actions = table;
374
+ actions_cap = cap;
375
+ }
376
+ size_t i = mix((n << 2) | k) & (actions_cap - 1);
377
+ while (actions[i].windows && (actions[i].kind != k || actions[i].name != n)) i = (i + 1) & (actions_cap - 1);
378
+ if (!actions[i].windows) { actions[i].kind = k; actions[i].name = n; actions_len++; }
379
+ return &actions[i];
380
+ }
381
+
382
+ static site_t *
383
+ site_for(uint64_t key)
384
+ {
385
+ if ((sites_len + 1) * 2 > sites_cap && !sites_grow()) return NULL;
386
+ size_t i = mix(key) & (sites_cap - 1);
387
+ while (sites[i].key && sites[i].key != key) i = (i + 1) & (sites_cap - 1);
388
+ if (!sites[i].key) { sites[i].key = key; sites_len++; }
389
+ return &sites[i];
390
+ }
391
+
392
+ static void
393
+ release(win_t *w)
394
+ {
395
+ if (w->seen_cap > KEEP_CAP) { free(w->seen); w->seen = NULL; w->seen_cap = 0; }
396
+ else if (w->seen) memset(w->seen, 0, w->seen_cap * sizeof(seen_t));
397
+ w->seen_len = 0;
398
+ if (w->pend_cap > KEEP_CAP) { free(w->pend); w->pend = NULL; w->pend_cap = 0; }
399
+ else if (w->pend) memset(w->pend, 0, w->pend_cap * sizeof(pend_t));
400
+ w->pend_len = 0;
401
+ w->fiber = w->thread = 0;
402
+ w->depth = 0;
403
+ wins_open--;
404
+ }
405
+
406
+ /* The window ended: each line it reached counts the window once, and its
407
+ * objects and attributed pairs go to its name. */
408
+ static void
409
+ close_window(win_t *w)
410
+ {
411
+ uint64_t kind = w->kind, name = w->name;
412
+ action_t *a = action_for(kind, name);
413
+ int first = a && a->windows == 0;
414
+ if (a) {
415
+ a->windows++;
416
+ a->objects += w->objects;
417
+ if (first) a->first += w->objects;
418
+ a->net += w->net;
419
+ }
420
+ for (size_t j = 0; w->seen_len && j < w->seen_cap; j++) {
421
+ seen_t *e = &w->seen[j];
422
+ if (!e->key) continue;
423
+ site_t *s = site_for(e->key);
424
+ if (!s) { dropped += e->count; continue; }
425
+ if (s->owner == w->id || (!s->owner && !s->requests)) s->first = e->count;
426
+ s->requests++;
427
+ s->count += e->count;
428
+ }
429
+ for (size_t j = 0; w->pend_len && j < w->pend_cap; j++) {
430
+ pend_t *p = &w->pend[j];
431
+ if (!p->site) continue;
432
+ if ((attribs_len + 1) * 2 > attribs_cap && !attribs_grow()) { dropped += p->count; continue; }
433
+ size_t i = attrib_hash(kind, name, p->site, p->caller) & (attribs_cap - 1);
434
+ attrib_t *e;
435
+ while ((e = &attribs[i])->site && (e->kind != kind || e->name != name || e->site != p->site || e->caller != p->caller))
436
+ i = (i + 1) & (attribs_cap - 1);
437
+ if (!e->site) { e->kind = kind; e->name = name; e->site = p->site; e->caller = p->caller; attribs_len++; }
438
+ e->count += p->count;
439
+ if (first) e->first += p->count;
440
+ }
441
+ release(w);
442
+ }
443
+
444
+ /* Lowrail::Profile.enter(kind) / leave bracket a window on the current
445
+ * fiber. Nested windows (mounted engines, a mail inside a request or job)
446
+ * count as the outermost one. Neither raises: enter returns false when it
447
+ * cannot open a window (out of memory), and the code runs uncounted. */
448
+ static VALUE
449
+ profile_enter(VALUE self, VALUE k)
450
+ {
451
+ VALUE thread = rb_thread_current();
452
+ VALUE fiber = rb_fiber_current();
453
+ win_t *w = window_of(fiber);
454
+ if (w) { w->depth++; return Qtrue; }
455
+ w = window_of(0);
456
+ if (!w && wins_open >= MAX_OPEN) {
457
+ win_t *oldest = NULL;
458
+ for (size_t i = 0; i < wins_cap; i++)
459
+ if (wins[i].fiber && wins[i].fiber != fiber && (!oldest || wins[i].id < oldest->id)) oldest = &wins[i];
460
+ /* Its objects are lost, so the capture says so (compare refuses it). */
461
+ if (oldest) { release(oldest); dropped++; w = oldest; }
462
+ }
463
+ if (!w) {
464
+ size_t cap = wins_cap ? wins_cap * 2 : 16;
465
+ win_t *next = realloc(wins, cap * sizeof(win_t));
466
+ if (!next) return Qfalse;
467
+ memset(next + wins_cap, 0, (cap - wins_cap) * sizeof(win_t));
468
+ w = next + wins_cap;
469
+ wins = next;
470
+ wins_cap = cap;
471
+ }
472
+ w->thread = thread;
473
+ w->fiber = fiber;
474
+ w->depth = 1;
475
+ w->id = ++window_seq;
476
+ w->kind = (FIXNUM_P(k) ? (uint64_t)FIX2LONG(k) : 0) % KINDS;
477
+ w->name = 0;
478
+ w->objects = 0;
479
+ w->net = 0;
480
+ w->connect = 0;
481
+ wins_open++;
482
+ windows[w->kind]++;
483
+ return Qtrue;
484
+ }
485
+
486
+ static VALUE
487
+ profile_leave(VALUE self)
488
+ {
489
+ if (!wins_open) return Qnil;
490
+ win_t *w = window_of(rb_fiber_current());
491
+ if (w && --w->depth == 0) close_window(w);
492
+ return Qnil;
493
+ }
494
+
495
+ /* Lowrail::Profile.label(klass, separator, name): the current window's name,
496
+ * "Klass#name", once per window (the outermost controller, job, mailer or
497
+ * channel). Builds no Ruby objects. */
498
+ static VALUE
499
+ profile_label(VALUE self, VALUE klass, VALUE sep, VALUE action)
500
+ {
501
+ if (!wins_open) return Qnil;
502
+ win_t *w = window_of(rb_fiber_current());
503
+ if (!w || w->name || !RB_TYPE_P(klass, T_CLASS)) return Qnil;
504
+ VALUE cname = rb_mod_name(klass);
505
+ if (!RB_TYPE_P(cname, T_STRING) || !RB_TYPE_P(sep, T_STRING)) return Qnil;
506
+ if (RB_TYPE_P(action, T_SYMBOL)) action = rb_sym2str(action);
507
+ if (!RB_TYPE_P(action, T_STRING)) return Qnil;
508
+ size_t a = RSTRING_LEN(cname), b = RSTRING_LEN(sep), c = RSTRING_LEN(action);
509
+ if (a + b + c > 4096) return Qnil;
510
+ char buf[4096];
511
+ memcpy(buf, RSTRING_PTR(cname), a);
512
+ memcpy(buf + a, RSTRING_PTR(sep), b);
513
+ memcpy(buf + a + b, RSTRING_PTR(action), c);
514
+ size_t id = intern(buf, a + b + c);
515
+ if (id != SIZE_MAX) w->name = id + 1;
516
+ return Qnil;
517
+ }
518
+
519
+ /* Lowrail::Profile.attribute(app_root): record the nearest app frame of every
520
+ * allocation, per window name. Allocates nothing, so counts stay comparable. */
521
+ static VALUE
522
+ profile_attribute(VALUE self, VALUE root)
523
+ {
524
+ StringValue(root);
525
+ char *copy = malloc(RSTRING_LEN(root) + 1);
526
+ if (!copy) rb_raise(rb_eNoMemError, "lowrail profile attribute");
527
+ memcpy(copy, RSTRING_PTR(root), RSTRING_LEN(root));
528
+ copy[RSTRING_LEN(root)] = 0;
529
+ free(app_root);
530
+ app_root = copy;
531
+ app_root_len = RSTRING_LEN(root);
532
+ attributing = 1;
533
+ return Qnil;
534
+ }
535
+
536
+ /* Lowrail::Profile.connect(inside): the current fiber's window enters
537
+ * (true) or leaves (false) a network connect. Allocates nothing. */
538
+ static VALUE
539
+ profile_connect(VALUE self, VALUE inside)
540
+ {
541
+ win_t *w = current_window();
542
+ if (!w) return Qnil;
543
+ if (RTEST(inside)) w->connect++;
544
+ else if (w->connect > 0) w->connect--;
545
+ return Qnil;
546
+ }
547
+
548
+ static void
549
+ reset(void)
550
+ {
551
+ if (sites) memset(sites, 0, sites_cap * sizeof(site_t));
552
+ sites_len = 0;
553
+ if (actions) memset(actions, 0, actions_cap * sizeof(action_t));
554
+ actions_len = 0;
555
+ if (attribs) memset(attribs, 0, attribs_cap * sizeof(attrib_t));
556
+ attribs_len = 0;
557
+ for (size_t i = 0; i < wins_cap; i++) if (wins[i].fiber) release(&wins[i]);
558
+ memset(windows, 0, sizeof(windows));
559
+ memset(objects, 0, sizeof(objects));
560
+ dropped = 0;
561
+ }
562
+
563
+ static VALUE
564
+ profile_reset(VALUE self)
565
+ {
566
+ reset();
567
+ return Qnil;
568
+ }
569
+
570
+ static void
571
+ wins_mark(void *ptr)
572
+ {
573
+ for (size_t i = 0; i < wins_cap; i++) {
574
+ if (!wins[i].fiber) continue;
575
+ rb_gc_mark(wins[i].fiber);
576
+ rb_gc_mark(wins[i].thread);
577
+ }
578
+ }
579
+
580
+ static const rb_data_type_t wins_type = { "lowrail_profile_windows", { wins_mark, NULL, NULL, }, 0, 0, 0 };
581
+
582
+ static VALUE
583
+ profile_start(VALUE self)
584
+ {
585
+ if (NIL_P(tracepoint)) {
586
+ tracepoint = rb_tracepoint_new(0, RUBY_INTERNAL_EVENT_NEWOBJ, newobj, NULL);
587
+ rb_gc_register_mark_object(tracepoint);
588
+ rb_tracepoint_enable(tracepoint);
589
+ }
590
+ return Qnil;
591
+ }
592
+
593
+ static VALUE
594
+ interned(uint64_t id)
595
+ {
596
+ return id ? rb_str_new(paths[id - 1], path_lens[id - 1]) : Qnil;
597
+ }
598
+
599
+ static VALUE
600
+ counts(uint64_t *values)
601
+ {
602
+ VALUE ary = rb_ary_new_capa(KINDS);
603
+ for (int k = 0; k < KINDS; k++) rb_ary_push(ary, ULL2NUM(values[k]));
604
+ return ary;
605
+ }
606
+
607
+ /* [windows per kind, objects per kind, dropped,
608
+ * [[path or nil, line, type, count, windows, first, via, kind], ...],
609
+ * [[kind, name or nil, windows, objects, first, network objects], ...],
610
+ * [[kind, name or nil, path, line, caller path or nil, caller line, count, first], ...]] */
611
+ static VALUE
612
+ profile_snapshot(VALUE self)
613
+ {
614
+ /* Copy first: building Ruby objects below runs outside any window, but a
615
+ * request on another thread could still grow the tables meanwhile. */
616
+ size_t n = 0, na = 0, nt = 0;
617
+ site_t *copy = malloc((sites_len + 1) * sizeof(site_t));
618
+ action_t *acopy = malloc((actions_len + 1) * sizeof(action_t));
619
+ attrib_t *tcopy = malloc((attribs_len + 1) * sizeof(attrib_t));
620
+ if (!copy || !acopy || !tcopy) { free(copy); free(acopy); free(tcopy); rb_raise(rb_eNoMemError, "lowrail profile snapshot"); }
621
+ for (size_t j = 0; j < sites_cap && n <= sites_len; j++) if (sites[j].key && sites[j].requests) copy[n++] = sites[j];
622
+ for (size_t j = 0; j < actions_cap && na <= actions_len; j++) if (actions[j].windows) acopy[na++] = actions[j];
623
+ for (size_t j = 0; j < attribs_cap && nt <= attribs_len; j++) if (attribs[j].site) tcopy[nt++] = attribs[j];
624
+ uint64_t w[KINDS], o[KINDS], d = dropped;
625
+ memcpy(w, windows, sizeof(w));
626
+ memcpy(o, objects, sizeof(o));
627
+ VALUE rows = rb_ary_new_capa(n);
628
+ for (size_t j = 0; j < n; j++) {
629
+ uint64_t key = copy[j].key, id = (key >> 35) & ((1ULL << 26) - 1);
630
+ VALUE row = rb_ary_new_from_args(8, interned(id), ULL2NUM((key >> 5) & ((1ULL << 30) - 1)), INT2FIX(key & 31),
631
+ ULL2NUM(copy[j].count), ULL2NUM(copy[j].requests), ULL2NUM(copy[j].first), (key >> 63) ? Qtrue : Qfalse,
632
+ INT2FIX((key >> 61) & 3));
633
+ rb_ary_push(rows, row);
634
+ }
635
+ VALUE arows = rb_ary_new_capa(na);
636
+ for (size_t j = 0; j < na; j++) {
637
+ action_t a = acopy[j];
638
+ rb_ary_push(arows, rb_ary_new_from_args(6, INT2FIX(a.kind), interned(a.name), ULL2NUM(a.windows),
639
+ ULL2NUM(a.objects), ULL2NUM(a.first), ULL2NUM(a.net)));
640
+ }
641
+ VALUE trows = rb_ary_new_capa(nt);
642
+ for (size_t j = 0; j < nt; j++) {
643
+ attrib_t t = tcopy[j];
644
+ rb_ary_push(trows, rb_ary_new_from_args(8, INT2FIX(t.kind), interned(t.name), interned(t.site >> 32),
645
+ ULL2NUM(t.site & 0xffffffffULL), interned(t.caller >> 32), ULL2NUM(t.caller & 0xffffffffULL),
646
+ ULL2NUM(t.count), ULL2NUM(t.first)));
647
+ }
648
+ free(copy);
649
+ free(acopy);
650
+ free(tcopy);
651
+ return rb_ary_new_from_args(6, counts(w), counts(o), ULL2NUM(d), rows, arows, trows);
652
+ }
653
+
654
+ void
655
+ Init_lowrail_profile(void)
656
+ {
657
+ VALUE lowrail = rb_define_module("Lowrail");
658
+ VALUE profile = rb_define_module_under(lowrail, "Profile");
659
+ VALUE holder = TypedData_Wrap_Struct(0, &wins_type, &wins);
660
+ rb_gc_register_mark_object(holder);
661
+ rb_define_const(profile, "API", INT2FIX(API));
662
+ rb_define_singleton_method(profile, "start", profile_start, 0);
663
+ rb_define_singleton_method(profile, "enter", profile_enter, 1);
664
+ rb_define_singleton_method(profile, "leave", profile_leave, 0);
665
+ rb_define_singleton_method(profile, "label", profile_label, 3);
666
+ rb_define_singleton_method(profile, "reset", profile_reset, 0);
667
+ rb_define_singleton_method(profile, "snapshot", profile_snapshot, 0);
668
+ rb_define_singleton_method(profile, "attribute", profile_attribute, 1);
669
+ rb_define_singleton_method(profile, "connect", profile_connect, 1);
670
+ }