wasmer-napi 0.702.0-alpha.3

NAPI library for Wasmer WebAssembly runtime
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
#include "internal/napi_lifetime_tracker.h"

#include "internal/napi_deferred.h"
#include "internal/napi_env.h"
#include "internal/napi_env_cleanup_hook.h"
#include "internal/napi_external_backing_store_hint.h"
#include "internal/napi_ref.h"
#include "internal/napi_scope.h"
#include "internal/napi_value.h"
#include <napi_lifetime_tracker.h>

#include <algorithm>
#include <array>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <mutex>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>

namespace quickjs::detail
{
namespace
{
bool enabled()
{
  return napi::lifetime::env_flag_enabled("EDGE_TRACE_NAPI_LIFETIME");
}

bool periodic_stats_enabled()
{
  return napi::lifetime::env_flag_enabled_or("EDGE_TRACE_NAPI_LIFETIME_STATS", enabled());
}

int64_t monotonic_milliseconds()
{
  return napi::lifetime::monotonic_milliseconds();
}

#if defined(NAPI_ENABLE_LIFETIME_TAG_STATS) || \
    defined(NAPI_ENABLE_LIFETIME_STRING_SYMBOL_DUMP)
constexpr int k_min_known_tag = -9;
constexpr int k_max_known_tag = 8;
constexpr size_t k_known_tag_count =
    static_cast<size_t>(k_max_known_tag - k_min_known_tag + 1);
constexpr size_t k_unknown_tag_index = k_known_tag_count;
constexpr size_t k_tag_bucket_count = k_known_tag_count + 1;

size_t tag_bucket_index(int tag)
{
  if (tag < k_min_known_tag || tag > k_max_known_tag)
    return k_unknown_tag_index;
  return static_cast<size_t>(tag - k_min_known_tag);
}

const char *tag_bucket_name(size_t index)
{
  if (index == k_unknown_tag_index)
    return "unknown";

  switch (static_cast<int>(index) + k_min_known_tag)
  {
  case -9:
    return "big_int";
  case -8:
    return "symbol";
  case -7:
    return "string";
  case -6:
    return "string_rope";
  case -5:
    return "tag_-5";
  case -4:
    return "tag_-4";
  case -3:
    return "module";
  case -2:
    return "function_bytecode";
  case -1:
    return "object";
  case 0:
    return "int";
  case 1:
    return "bool";
  case 2:
    return "null";
  case 3:
    return "undefined";
  case 4:
    return "uninitialized";
  case 5:
    return "catch_offset";
  case 6:
    return "exception";
  case 7:
    return "short_big_int";
  case 8:
    return "float64";
  default:
    return "unknown";
  }
}

struct tag_counters
{
  size_t slots[k_tag_bucket_count] = {};
};

void add_tag(tag_counters &counters, int tag)
{
  ++counters.slots[tag_bucket_index(tag)];
}

void remove_tag(tag_counters &counters, int tag)
{
  size_t &slot = counters.slots[tag_bucket_index(tag)];
  if (slot > 0)
    --slot;
}

bool has_tags(const tag_counters &counters)
{
  for (size_t i = 0; i < k_tag_bucket_count; ++i)
  {
    if (counters.slots[i] != 0)
      return true;
  }
  return false;
}
#endif

#ifdef NAPI_ENABLE_LIFETIME_STRING_SYMBOL_DUMP
void clear_exception(JSContext *ctx)
{
  if (ctx == nullptr || !JS_HasException(ctx))
    return;
  JSValue exception = JS_GetException(ctx);
  JS_FreeValue(ctx, exception);
}

bool js_value_to_escaped_string(JSContext *ctx, JSValueConst value, std::string &out)
{
  size_t text_length = 0;
  const char *text = JS_ToCStringLen(ctx, &text_length, value);
  if (text == nullptr)
  {
    clear_exception(ctx);
    return false;
  }

  out = napi::lifetime::escaped_value_fragment(text, text_length);
  JS_FreeCString(ctx, text);
  return true;
}

std::string class_name_fallback(JSContext *ctx, JSValueConst value)
{
  JSRuntime *rt = JS_GetRuntime(ctx);
  JSClassID class_id = JS_GetClassID(value);
  JSAtom class_name = JS_GetClassName(rt, class_id);
  if (class_name == JS_ATOM_NULL)
    return "<object>";

  const char *text = JS_AtomToCString(ctx, class_name);
  std::string result = text == nullptr
                           ? "<object>"
                           : napi::lifetime::escaped_value_fragment(
                                 text, std::strlen(text));
  if (text != nullptr)
    JS_FreeCString(ctx, text);
  JS_FreeAtomRT(rt, class_name);
  clear_exception(ctx);
  return result.empty() ? "<object>" : result;
}

std::string object_prototype_name(napi_env env, JSValueConst value)
{
  JSContext *ctx = env->context();
  JSValue proto = JS_GetPrototype(ctx, value);
  if (JS_IsException(proto))
  {
    clear_exception(ctx);
    return class_name_fallback(ctx, value);
  }

  if (JS_IsNull(proto) || JS_IsUndefined(proto))
  {
    JS_FreeValue(ctx, proto);
    return "<null-prototype>";
  }

  JSValue ctor = JS_GetPropertyStr(ctx, proto, "constructor");
  JS_FreeValue(ctx, proto);
  if (JS_IsException(ctor))
  {
    clear_exception(ctx);
    return class_name_fallback(ctx, value);
  }

  JSValue name = JS_UNDEFINED;
  if (JS_IsObject(ctor))
    name = JS_GetPropertyStr(ctx, ctor, "name");
  JS_FreeValue(ctx, ctor);
  if (JS_IsException(name))
  {
    clear_exception(ctx);
    return class_name_fallback(ctx, value);
  }

  std::string result;
  bool has_name = !JS_IsUndefined(name) &&
                  !JS_IsNull(name) &&
                  js_value_to_escaped_string(ctx, name, result) &&
                  !result.empty();
  JS_FreeValue(ctx, name);

  return has_name ? result : class_name_fallback(ctx, value);
}
#endif

struct value_snapshot
{
  napi_env env = nullptr;
  int tag = JS_TAG_UNDEFINED;
#ifdef NAPI_ENABLE_LIFETIME_STRING_SYMBOL_DUMP
  bool has_string_symbol = false;
  std::string string_symbol_value;
  bool has_object_type = false;
  std::string object_type;
#endif
};

using basic_snapshot = napi::lifetime::basic_snapshot<napi_env>;

template <typename Snapshot>
using tracked_type_stats = napi::lifetime::tracked_type_stats<Snapshot>;

struct value_type_stats : tracked_type_stats<value_snapshot>
{
#ifdef NAPI_ENABLE_LIFETIME_TAG_STATS
  tag_counters tags;
#endif
#ifdef NAPI_ENABLE_LIFETIME_STRING_SYMBOL_DUMP
  std::vector<napi::lifetime::string_symbol_entry<int>> string_symbols;
  std::vector<napi::lifetime::object_type_entry> object_types;
#endif
};

struct lifetime_stats
{
  std::mutex mutex;
  value_type_stats values;
  value_type_stats refs;
  tracked_type_stats<basic_snapshot> cleanup_hooks;
  tracked_type_stats<basic_snapshot> deferreds;
  tracked_type_stats<basic_snapshot> external_backing_store_hints;
  size_t scope_escape_calls = 0;
  size_t scope_escape_succeeded = 0;
  size_t scope_escape_failed = 0;
  napi::lifetime::counter_history counters;
};

lifetime_stats g_lifetime;

value_snapshot capture_value_snapshot(napi_env env, JSValueConst value)
{
  value_snapshot snapshot;
  snapshot.env = env;
  snapshot.tag = JS_VALUE_GET_NORM_TAG(value);

#ifdef NAPI_ENABLE_LIFETIME_STRING_SYMBOL_DUMP
  if (env != nullptr && env->context() != nullptr)
  {
    JSContext *ctx = env->context();
    if ((snapshot.tag == JS_TAG_STRING ||
         snapshot.tag == JS_TAG_STRING_ROPE) &&
        js_value_to_escaped_string(ctx, value, snapshot.string_symbol_value))
    {
      snapshot.has_string_symbol = true;
    }

    if (snapshot.tag == JS_TAG_OBJECT)
    {
      snapshot.object_type = object_prototype_name(env, value);
      snapshot.has_object_type = true;
    }
  }
#endif

  return snapshot;
}

void add_value_snapshot(value_type_stats &stats, const value_snapshot &snapshot)
{
#ifdef NAPI_ENABLE_LIFETIME_TAG_STATS
  add_tag(stats.tags, snapshot.tag);
#endif
#ifdef NAPI_ENABLE_LIFETIME_STRING_SYMBOL_DUMP
  if (snapshot.has_string_symbol)
    napi::lifetime::add_string_symbol_entry(stats.string_symbols,
                                            snapshot.tag,
                                            snapshot.string_symbol_value);
  if (snapshot.has_object_type)
    napi::lifetime::add_object_type_entry(stats.object_types, snapshot.object_type);
#endif
}

void remove_value_snapshot(value_type_stats &stats, const value_snapshot &snapshot)
{
#ifdef NAPI_ENABLE_LIFETIME_TAG_STATS
  remove_tag(stats.tags, snapshot.tag);
#endif
#ifdef NAPI_ENABLE_LIFETIME_STRING_SYMBOL_DUMP
  if (snapshot.has_string_symbol)
    napi::lifetime::remove_string_symbol_entry(stats.string_symbols,
                                               snapshot.tag,
                                               snapshot.string_symbol_value);
  if (snapshot.has_object_type)
    napi::lifetime::remove_object_type_entry(stats.object_types, snapshot.object_type);
#endif
}

napi::lifetime::env_slot_scan scan_env_slots(napi_env env)
{
  napi::lifetime::env_slot_scan scan;
  if (env == nullptr)
    return scan;

  scan.scope_slots_total = env->scope_storage_slot_count();
  scan.active_scopes = env->active_scope_count();
  scan.ref_slots_total = env->ref_storage_slot_count();
  scan.active_refs = env->active_ref_count();
  std::unordered_map<size_t, size_t> active_values_by_scope_level;
  env->for_each_active_scope([&](const napi_scope__ &scope) {
    size_t active_values = scope.active_value_count();
    scan.value_slots_total += scope.value_storage_slot_count();
    scan.active_values += active_values;
    active_values_by_scope_level[scope.level()] += active_values;
  });
  scan.active_values_by_scope_level.reserve(active_values_by_scope_level.size());
  for (const auto &[level, count] : active_values_by_scope_level)
    scan.active_values_by_scope_level.push_back({level, count});
  std::sort(scan.active_values_by_scope_level.begin(),
            scan.active_values_by_scope_level.end(),
            [](const auto &left, const auto &right) {
              return left.first < right.first;
            });
  return scan;
}

void dump_stats_locked(napi_env env, bool include_string_symbol_values)
{
  napi::lifetime::dump_lifetime_header();
  napi::lifetime::env_slot_scan scan = scan_env_slots(env);
  napi::lifetime::dump_slots_table(g_lifetime.counters,
                                   scan,
                                   g_lifetime.values.active,
                                   g_lifetime.refs.active,
                                   g_lifetime.scope_escape_calls,
                                   g_lifetime.scope_escape_succeeded,
                                   g_lifetime.scope_escape_failed);
  napi::lifetime::dump_scope_level_table(g_lifetime.counters, scan);

  napi::lifetime::dump_type_table_header();
  napi::lifetime::dump_type_row(g_lifetime.counters, "napi_value", g_lifetime.values);
  napi::lifetime::dump_type_row(g_lifetime.counters, "napi_ref", g_lifetime.refs);
  napi::lifetime::dump_type_row(g_lifetime.counters,
                                "napi_env_cleanup_hook",
                                g_lifetime.cleanup_hooks);
  napi::lifetime::dump_type_row(g_lifetime.counters, "napi_deferred", g_lifetime.deferreds);
  napi::lifetime::dump_type_row(g_lifetime.counters,
                                "napi_external_backing_store_hint",
                                g_lifetime.external_backing_store_hints);

#ifdef NAPI_ENABLE_LIFETIME_TAG_STATS
  napi::lifetime::dump_tag_table(g_lifetime.counters,
                                 "napi_value",
                                 g_lifetime.values.tags,
                                 k_tag_bucket_count,
                                 tag_bucket_name);
  napi::lifetime::dump_tag_table(g_lifetime.counters,
                                 "napi_ref",
                                 g_lifetime.refs.tags,
                                 k_tag_bucket_count,
                                 tag_bucket_name);
#endif
#ifdef NAPI_ENABLE_LIFETIME_STRING_SYMBOL_DUMP
  if (include_string_symbol_values)
  {
    napi::lifetime::dump_string_entries(g_lifetime.counters,
                                        g_lifetime.values.string_symbols,
                                        [](int tag) {
                                          return tag == JS_TAG_STRING || tag == JS_TAG_STRING_ROPE;
                                        },
                                        "napi_value");
    napi::lifetime::dump_object_type_entries(g_lifetime.counters,
                                             g_lifetime.values.object_types,
                                             g_lifetime.refs.object_types);
  }
#else
  (void)include_string_symbol_values;
#endif
  std::fprintf(stderr, "\n");
}

void dump_summary_locked(napi_env env)
{
  napi::lifetime::dump_summary_row(scan_env_slots(env));
}

void dump_lifetime(napi_env env, const char *reason, bool include_string_symbol_values)
{
  if (reason != nullptr)
    std::fprintf(stderr, "[napi-lifetime] dump env=%p reason=%s\n", env, reason);

  std::lock_guard<std::mutex> lock{g_lifetime.mutex};
  dump_stats_locked(env, include_string_symbol_values);
}

void dump_lifetime_summary(napi_env env)
{
  std::lock_guard<std::mutex> lock{g_lifetime.mutex};
  dump_summary_locked(env);
}

#ifdef NAPI_ENABLE_LIFETIME_PERIODIC_STATS
void maybe_dump_periodic_stats(napi_env env)
{
  if (env == nullptr || !periodic_stats_enabled())
    return;

  int64_t now = monotonic_milliseconds();
  bool should_dump_summary = env->should_dump_lifetime_stats(now);
  bool should_dump_full = false;
#ifdef NAPI_ENABLE_LIFETIME_STRING_SYMBOL_DUMP
  should_dump_full = env->should_dump_lifetime_string_symbol_values(now);
#endif

  if (should_dump_full)
  {
    dump_lifetime(env, nullptr, true);
    return;
  }

  if (should_dump_summary)
    dump_lifetime_summary(env);
}
#else
void maybe_dump_periodic_stats(napi_env env)
{
  (void)env;
}
#endif

void record_value_create(value_type_stats &stats,
                         const void *handle,
                         value_snapshot snapshot)
{
  std::lock_guard<std::mutex> lock{g_lifetime.mutex};
  napi::lifetime::record_tracked_create(stats,
                                        handle,
                                        std::move(snapshot),
                                        add_value_snapshot);
}

napi_env record_value_release(value_type_stats &stats, const void *handle)
{
  std::lock_guard<std::mutex> lock{g_lifetime.mutex};
  return napi::lifetime::record_tracked_release<napi_env>(stats,
                                                          handle,
                                                          remove_value_snapshot);
}

void record_basic_create(tracked_type_stats<basic_snapshot> &stats,
                         const void *handle,
                         basic_snapshot snapshot)
{
  std::lock_guard<std::mutex> lock{g_lifetime.mutex};
  napi::lifetime::record_tracked_create(stats,
                                        handle,
                                        std::move(snapshot),
                                        napi::lifetime::add_basic_snapshot<basic_snapshot>);
}

napi_env record_basic_release(tracked_type_stats<basic_snapshot> &stats,
                              const void *handle)
{
  std::lock_guard<std::mutex> lock{g_lifetime.mutex};
  return napi::lifetime::record_tracked_release<napi_env>(
      stats,
      handle,
      napi::lifetime::remove_basic_snapshot<basic_snapshot>);
}
} // namespace

void napi_lifetime__<napi_value__>::record_create(napi_scope__ *owner, napi_value__ *val)
{
  if (owner == nullptr || val == nullptr)
    return;

  napi_env env = owner->env();
  value_snapshot snapshot = capture_value_snapshot(env, val->get_inner());
  record_value_create(g_lifetime.values, val, std::move(snapshot));
  maybe_dump_periodic_stats(env);
}

void napi_lifetime__<napi_value__>::record_release(napi_scope__ *owner, napi_value__ *val)
{
  (void)owner;
  napi_env env = record_value_release(g_lifetime.values, val);
  maybe_dump_periodic_stats(env);
}

void napi_lifetime__<napi_ref__>::record_create(napi_env__ *owner, napi_ref__ *val)
{
  if (owner == nullptr || val == nullptr)
    return;

  value_snapshot snapshot = capture_value_snapshot(owner, val->get_inner());
  napi_env env = snapshot.env;
  record_value_create(g_lifetime.refs, val, std::move(snapshot));
  maybe_dump_periodic_stats(env);
}

void napi_lifetime__<napi_ref__>::record_release(napi_env__ *owner, napi_ref__ *val)
{
  (void)owner;
  napi_env env = record_value_release(g_lifetime.refs, val);
  maybe_dump_periodic_stats(env);
}

void napi_lifetime__<napi_env_cleanup_hook__>::record_create(
    napi_env__ *owner,
    napi_env_cleanup_hook__ *val)
{
  if (owner == nullptr || val == nullptr)
    return;

  basic_snapshot snapshot{owner};
  napi_env env = snapshot.env;
  record_basic_create(g_lifetime.cleanup_hooks, val, snapshot);
  maybe_dump_periodic_stats(env);
}

void napi_lifetime__<napi_env_cleanup_hook__>::record_release(
    napi_env__ *owner,
    napi_env_cleanup_hook__ *val)
{
  (void)owner;
  napi_env env = record_basic_release(g_lifetime.cleanup_hooks, val);
  maybe_dump_periodic_stats(env);
}

void napi_lifetime__<napi_deferred__>::record_create(napi_env__ *owner, napi_deferred__ *val)
{
  if (owner == nullptr || val == nullptr)
    return;

  basic_snapshot snapshot{owner};
  napi_env env = snapshot.env;
  record_basic_create(g_lifetime.deferreds, val, snapshot);
  maybe_dump_periodic_stats(env);
}

void napi_lifetime__<napi_deferred__>::record_release(napi_env__ *owner, napi_deferred__ *val)
{
  (void)owner;
  napi_env env = record_basic_release(g_lifetime.deferreds, val);
  maybe_dump_periodic_stats(env);
}

void napi_lifetime__<napi_external_backing_store_hint__>::record_create(
    napi_env__ *owner,
    napi_external_backing_store_hint__ *val)
{
  if (owner == nullptr || val == nullptr)
    return;

  basic_snapshot snapshot{owner};
  napi_env env = snapshot.env;
  record_basic_create(g_lifetime.external_backing_store_hints, val, snapshot);
  maybe_dump_periodic_stats(env);
}

void napi_lifetime__<napi_external_backing_store_hint__>::record_release(
    napi_env__ *owner,
    napi_external_backing_store_hint__ *val)
{
  (void)owner;
  napi_env env = record_basic_release(g_lifetime.external_backing_store_hints, val);
  maybe_dump_periodic_stats(env);
}

void napi_lifetime_tracker__::record_scope_escape(napi_env env, bool succeeded)
{
  {
    std::lock_guard<std::mutex> lock{g_lifetime.mutex};
    ++g_lifetime.scope_escape_calls;
    if (succeeded)
      ++g_lifetime.scope_escape_succeeded;
    else
      ++g_lifetime.scope_escape_failed;
  }
  maybe_dump_periodic_stats(env);
}

void napi_lifetime_tracker__::dump(napi_env env, const char *reason)
{
  if (env == nullptr || (!enabled() && !periodic_stats_enabled()))
    return;

  dump_lifetime(env, reason, true);
}
} // namespace quickjs::detail

extern "C" void napi_quickjs_lifetime_dump(napi_env env, const char *reason)
{
  quickjs::detail::napi_lifetime_tracker__::dump(env, reason);
}