quickjs 0.22.0 → 0.22.1

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.
@@ -7,6 +7,7 @@
7
7
 
8
8
  #include "quickjs.h"
9
9
  #include "quickjs-libc.h"
10
+ #include "quickjsrb_libc.h"
10
11
  #include "cutils.h"
11
12
 
12
13
  #include <pthread.h>
@@ -16,6 +17,17 @@
16
17
  #include <string.h>
17
18
  #include <time.h>
18
19
 
20
+ // The same ladder quickjs.c walks for its own allocator, mirrored rather than
21
+ // referenced: js_def_malloc_usable_size is static, and the submodule is not
22
+ // ours to change.
23
+ #if defined(__APPLE__)
24
+ #include <malloc/malloc.h>
25
+ #elif defined(__linux__) || defined(__GLIBC__)
26
+ #include <malloc.h>
27
+ #elif defined(__FreeBSD__)
28
+ #include <malloc_np.h>
29
+ #endif
30
+
19
31
  extern const uint32_t qjsc_polyfill_file_min_size;
20
32
  extern const uint8_t qjsc_polyfill_file_min;
21
33
  extern const uint32_t qjsc_polyfill_encoding_min_size;
@@ -48,7 +60,7 @@ typedef struct EvalTime
48
60
  struct timespec started_at;
49
61
  } EvalTime;
50
62
 
51
- static int64_t eval_elapsed_ms(const EvalTime *eval_time)
63
+ static inline int64_t eval_elapsed_ms(const EvalTime *eval_time)
52
64
  {
53
65
  struct timespec now;
54
66
  clock_gettime(CLOCK_MONOTONIC, &now);
@@ -134,6 +146,36 @@ typedef struct VMData
134
146
  // Captured with it, at init, so slice does not build its result by calling
135
147
  // a constructor the guest has had a chance to replace.
136
148
  JSValue j_blob_ctor;
149
+ // Number of allocations the runtime asked this extension for and did not
150
+ // get, either because the request would have crossed memory_limit or
151
+ // because the system refused. Monotonic for the life of the VM, and read
152
+ // by taking a snapshot and comparing: the question the readers ask is
153
+ // whether the allocator refused during a window they name, which is the
154
+ // one signal a guest cannot write to. Only mutated from the thread running
155
+ // JS, which is one at a time per VM.
156
+ //
157
+ // It counts a refusal QuickJS goes on to tolerate as well as one it reports:
158
+ // resize_shape_hash and compact_properties ignore what they get back and
159
+ // carry on correctly with the smaller table. A reader would then answer for
160
+ // a heap that had recovered. Reachable only where such an allocation is the
161
+ // one that fails while the ones around it do not, which 120 shapings against
162
+ // the ceiling did not produce, and every reader below is already in a
163
+ // something-has-gone-wrong path except construction, where a refusal means
164
+ // the limit cannot hold the runtime. Recorded here rather than guarded
165
+ // against, since the allocator cannot see which of its callers will care.
166
+ uint64_t alloc_refusals;
167
+ // The count as the current public API call began. What the readers compare
168
+ // against: allocator_refused asks whether the number moved inside the call
169
+ // they are reporting on, not whether this VM ever refused. A guest that
170
+ // catches an out-of-memory and returns normally is left alone, as it is
171
+ // today.
172
+ uint64_t alloc_refusals_at_scope;
173
+ // Whether the refusal that condemned this VM happened while it was being
174
+ // built, so the refusal it hands its caller can say so. "A previous
175
+ // evaluation" is not true of a VM that has never run one, and "recreate the
176
+ // VM" is advice that fails identically forever when the limit is the thing
177
+ // that is wrong.
178
+ bool condemned_at_build;
137
179
  // Once the runtime has hit JS-level "out of memory", the QuickJS heap is in
138
180
  // a fragile state where further evaluation can trigger a use-after-free in
139
181
  // the parser-error-during-OOM cascade (segfault inside js_shape_hash_unlink).
@@ -256,7 +298,9 @@ static void vm_free(void *ptr)
256
298
  VMData *data = (VMData *)ptr;
257
299
  free(data->eval_time);
258
300
 
259
- if (!data->disposed)
301
+ // NULL when the runtime could not be allocated at all: vm_alloc raises,
302
+ // and the half-built object still reaches here.
303
+ if (!data->disposed && data->context != NULL)
260
304
  {
261
305
  if (!JS_IsUndefined(data->j_file_proxy_creator))
262
306
  JS_FreeValue(data->context, data->j_file_proxy_creator);
@@ -323,19 +367,134 @@ static const rb_data_type_t vm_type = {
323
367
  .flags = RUBY_TYPED_FREE_IMMEDIATELY,
324
368
  };
325
369
 
370
+ // quickjs.c reports "out of memory" by throwing an error, and a guest can
371
+ // write that same sentence. The refusal itself cannot be written: it happens
372
+ // below the guest, in the allocator, before QuickJS has decided whether it
373
+ // can even afford an error object. So the runtime is created with our own
374
+ // JSMallocFunctions, which are js_def_malloc and friends with one line
375
+ // added, and every refusal is counted on the VM.
376
+ //
377
+ // The accounting has to be reproduced exactly rather than approximated:
378
+ // js_def_malloc is where memory_limit is enforced, and malloc_count and
379
+ // malloc_size are what JS_ComputeMemoryUsage reports through VM#memory_usage.
380
+ // Both the limit comparison and the usable-size bookkeeping below are
381
+ // therefore copied from quickjs.c as they stand.
382
+ #if defined(__APPLE__)
383
+ #define QUICKJSRB_MALLOC_OVERHEAD 0
384
+ #else
385
+ #define QUICKJSRB_MALLOC_OVERHEAD 8
386
+ #endif
387
+
388
+ static size_t quickjsrb_malloc_usable_size(const void *ptr)
389
+ {
390
+ #if defined(__APPLE__)
391
+ return malloc_size(ptr);
392
+ #elif defined(_WIN32)
393
+ return _msize((void *)ptr);
394
+ #elif defined(__EMSCRIPTEN__)
395
+ return 0;
396
+ #elif defined(__linux__) || defined(__GLIBC__)
397
+ return malloc_usable_size((void *)ptr);
398
+ #else
399
+ return malloc_usable_size((void *)ptr);
400
+ #endif
401
+ }
402
+
403
+ // The added line, in the one place both refusal paths pass through. The
404
+ // opaque is the VMData handed to JS_NewRuntime2; it is NULL-checked because
405
+ // the first allocation JS_NewRuntime2 makes is the runtime itself, before
406
+ // any runtime exists to hold it.
407
+ static void *quickjsrb_malloc_refused(JSMallocState *s)
408
+ {
409
+ VMData *data = s->opaque;
410
+ if (data != NULL)
411
+ data->alloc_refusals++;
412
+ return NULL;
413
+ }
414
+
415
+ static void *quickjsrb_malloc(JSMallocState *s, size_t size)
416
+ {
417
+ void *ptr;
418
+
419
+ if (unlikely(s->malloc_size + size > s->malloc_limit))
420
+ return quickjsrb_malloc_refused(s);
421
+
422
+ ptr = malloc(size);
423
+ if (!ptr)
424
+ return quickjsrb_malloc_refused(s);
425
+
426
+ s->malloc_count++;
427
+ s->malloc_size += quickjsrb_malloc_usable_size(ptr) + QUICKJSRB_MALLOC_OVERHEAD;
428
+ return ptr;
429
+ }
430
+
431
+ static void quickjsrb_free(JSMallocState *s, void *ptr)
432
+ {
433
+ if (!ptr)
434
+ return;
435
+
436
+ s->malloc_count--;
437
+ s->malloc_size -= quickjsrb_malloc_usable_size(ptr) + QUICKJSRB_MALLOC_OVERHEAD;
438
+ free(ptr);
439
+ }
440
+
441
+ static void *quickjsrb_realloc(JSMallocState *s, void *ptr, size_t size)
442
+ {
443
+ size_t old_size;
444
+
445
+ if (!ptr)
446
+ {
447
+ if (size == 0)
448
+ return NULL;
449
+ return quickjsrb_malloc(s, size);
450
+ }
451
+ old_size = quickjsrb_malloc_usable_size(ptr);
452
+ // A resize to zero is a free that answers NULL. Nothing was refused.
453
+ if (size == 0)
454
+ {
455
+ s->malloc_count--;
456
+ s->malloc_size -= old_size + QUICKJSRB_MALLOC_OVERHEAD;
457
+ free(ptr);
458
+ return NULL;
459
+ }
460
+ if (s->malloc_size + size - old_size > s->malloc_limit)
461
+ return quickjsrb_malloc_refused(s);
462
+
463
+ ptr = realloc(ptr, size);
464
+ if (!ptr)
465
+ return quickjsrb_malloc_refused(s);
466
+
467
+ s->malloc_size += quickjsrb_malloc_usable_size(ptr) - old_size;
468
+ return ptr;
469
+ }
470
+
471
+ static const JSMallocFunctions quickjsrb_malloc_funcs = {
472
+ quickjsrb_malloc,
473
+ quickjsrb_free,
474
+ quickjsrb_realloc,
475
+ quickjsrb_malloc_usable_size,
476
+ };
477
+
326
478
  struct vm_create_args
327
479
  {
480
+ VMData *data;
328
481
  JSContext *context;
329
482
  };
330
483
 
331
484
  static void *vm_create_no_gvl(void *p)
332
485
  {
333
486
  struct vm_create_args *args = p;
334
- args->context = JS_NewContext(JS_NewRuntime());
487
+ // JS_NewRuntime2 answers NULL when it cannot allocate the runtime, and
488
+ // JS_NewContext(NULL) dereferences it. Nothing checked this before, when
489
+ // the same NULL was reachable through JS_NewRuntime.
490
+ JSRuntime *runtime = JS_NewRuntime2(&quickjsrb_malloc_funcs, args->data);
491
+ args->context = runtime == NULL ? NULL : JS_NewContext(runtime);
492
+ if (runtime != NULL && args->context == NULL)
493
+ JS_FreeRuntime(runtime);
335
494
  return NULL;
336
495
  }
337
496
 
338
- static VALUE vm_alloc(VALUE r_self)
497
+ static inline VALUE vm_alloc(VALUE r_self)
339
498
  {
340
499
  VMData *data;
341
500
  VALUE obj = TypedData_Make_Struct(r_self, VMData, &vm_type, data);
@@ -352,6 +511,9 @@ static VALUE vm_alloc(VALUE r_self)
352
511
  data->j_file_proxy_creator = JS_UNDEFINED;
353
512
  data->j_blob_ctor = JS_UNDEFINED;
354
513
  data->proxy_class_id = 0;
514
+ data->alloc_refusals = 0;
515
+ data->alloc_refusals_at_scope = 0;
516
+ data->condemned_at_build = false;
355
517
  data->oom_poisoned = false;
356
518
  data->handle_source_broken = false;
357
519
  data->r_registrar_error = Qnil;
@@ -371,9 +533,11 @@ static VALUE vm_alloc(VALUE r_self)
371
533
  // JSRuntime / JSContext creation is pure QuickJS C work — no Ruby state
372
534
  // touched. Release the GVL so a background warmer thread can run this in
373
535
  // parallel with the main thread on multi-core hosts.
374
- struct vm_create_args args = {NULL};
536
+ struct vm_create_args args = {data, NULL};
375
537
  rb_thread_call_without_gvl(vm_create_no_gvl, &args, NULL, NULL);
376
538
  data->context = args.context;
539
+ if (data->context == NULL)
540
+ rb_raise(rb_eNoMemError, "failed to allocate a JS runtime");
377
541
 
378
542
  return obj;
379
543
  }
@@ -630,7 +794,7 @@ static inline VALUE alive_objects_register(VMData *data, VALUE r_object, bool *c
630
794
  return r_handle;
631
795
  }
632
796
 
633
- static void random_filename(char buf[QUICKJSRB_GENERATED_NAME_SIZE])
797
+ static inline void random_filename(char buf[QUICKJSRB_GENERATED_NAME_SIZE])
634
798
  {
635
799
  VALUE r_rand = rb_funcall(
636
800
  rb_const_get(rb_cClass, rb_intern("SecureRandom")),
@@ -645,7 +809,7 @@ static void random_filename(char buf[QUICKJSRB_GENERATED_NAME_SIZE])
645
809
  RB_GC_GUARD(r_rand);
646
810
  }
647
811
 
648
- static bool is_native_error_name(const char *error_name)
812
+ static inline bool is_native_error_name(const char *error_name)
649
813
  {
650
814
  for (int i = 0; i < num_native_errors; i++)
651
815
  {
@@ -657,7 +821,7 @@ static bool is_native_error_name(const char *error_name)
657
821
 
658
822
  // Constants
659
823
 
660
- static void r_define_constants(VALUE r_parent_class)
824
+ static inline void r_define_constants(VALUE r_parent_class)
661
825
  {
662
826
  rb_define_const(r_parent_class, "MODULE_STD", QUICKJSRB_SYM(featureStdId));
663
827
  rb_define_const(r_parent_class, "MODULE_OS", QUICKJSRB_SYM(featureOsId));
@@ -700,7 +864,7 @@ static VALUE r_log_m_to_s(VALUE r_self)
700
864
  return rb_funcall(r_ary, rb_intern("join"), 1, rb_str_new2(" "));
701
865
  }
702
866
 
703
- static VALUE r_define_log_class(VALUE r_parent_class)
867
+ static inline VALUE r_define_log_class(VALUE r_parent_class)
704
868
  {
705
869
  VALUE r_log_class = rb_define_class_under(r_parent_class, "Log", rb_cObject);
706
870
  rb_define_attr(r_log_class, "severity", 1, 0);
@@ -711,7 +875,7 @@ static VALUE r_define_log_class(VALUE r_parent_class)
711
875
  return r_log_class;
712
876
  }
713
877
 
714
- static VALUE r_log_new(const char *severity, VALUE r_row)
878
+ static inline VALUE r_log_new(const char *severity, VALUE r_row)
715
879
  {
716
880
  VALUE r_log_class = rb_const_get(rb_const_get(rb_const_get(rb_cClass, rb_intern("Quickjs")), rb_intern("VM")), rb_intern("Log"));
717
881
  VALUE r_log = rb_funcall(r_log_class, rb_intern("new"), 0);
@@ -720,7 +884,7 @@ static VALUE r_log_new(const char *severity, VALUE r_row)
720
884
  return r_log;
721
885
  }
722
886
 
723
- static VALUE r_log_body_new(VALUE r_raw, VALUE r_c)
887
+ static inline VALUE r_log_body_new(VALUE r_raw, VALUE r_c)
724
888
  {
725
889
  VALUE r_log_body = rb_hash_new();
726
890
  rb_hash_aset(r_log_body, ID2SYM(rb_intern("raw")), r_raw);
@@ -745,7 +909,7 @@ static VALUE vm_m_initialize_quickjs_error(VALUE self, VALUE r_message, VALUE r_
745
909
  return self;
746
910
  }
747
911
 
748
- static void r_define_exception_classes(VALUE r_parent_class)
912
+ static inline void r_define_exception_classes(VALUE r_parent_class)
749
913
  {
750
914
  VALUE r_runtime_error = rb_define_class_under(r_parent_class, QUICKJSRB_ROOT_RUNTIME_ERROR, rb_eRuntimeError);
751
915
  rb_define_method(r_runtime_error, "initialize", vm_m_initialize_quickjs_error, 2);
@@ -0,0 +1,17 @@
1
+ // quickjs-libc keeps its event loop state static and the submodule is not ours
2
+ // to change, so it is compiled as part of this unit to reach that state.
3
+ #include "quickjs-libc.c"
4
+
5
+ #include "quickjsrb_libc.h"
6
+
7
+ int quickjsrb_os_poll(JSContext *ctx)
8
+ {
9
+ return os_poll_func ? os_poll_func(ctx) : -1;
10
+ }
11
+
12
+ int quickjsrb_os_has_event_source(JSContext *ctx)
13
+ {
14
+ JSThreadState *ts = JS_GetRuntimeOpaque(JS_GetRuntime(ctx));
15
+ return !list_empty(&ts->os_timers) || !list_empty(&ts->os_rw_handlers) ||
16
+ !list_empty(&ts->port_list) || !list_empty(&ts->os_signal_handlers);
17
+ }
@@ -0,0 +1,14 @@
1
+ #ifndef QUICKJSRB_LIBC_H
2
+ #define QUICKJSRB_LIBC_H 1
3
+
4
+ #include "quickjs.h"
5
+
6
+ // One pass of quickjs-libc's event loop. Zero when it waited or ran a handler,
7
+ // nonzero when it had nothing to wait on.
8
+ int quickjsrb_os_poll(JSContext *ctx);
9
+
10
+ // Whether a timer, I/O handler, worker port or signal handler could still run
11
+ // JS on this runtime.
12
+ int quickjsrb_os_has_event_source(JSContext *ctx);
13
+
14
+ #endif
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Quickjs
4
- VERSION = "0.22.0"
4
+ VERSION = "0.22.1"
5
5
  end
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "quickjs-rb-polyfills",
3
- "version": "0.22.0",
3
+ "version": "0.22.1",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "quickjs-rb-polyfills",
9
- "version": "0.22.0",
9
+ "version": "0.22.1",
10
10
  "devDependencies": {
11
11
  "rolldown": "^1.0.0-rc.14"
12
12
  }
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "quickjs-rb-polyfills",
3
- "version": "0.22.0",
3
+ "version": "0.22.1",
4
4
  "private": true,
5
5
  "scripts": {
6
6
  "build": "rolldown -c rolldown.config.mjs"
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: quickjs
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.22.0
4
+ version: 0.22.1
5
5
  platform: ruby
6
6
  authors:
7
7
  - hmsk
@@ -83,6 +83,8 @@ files:
83
83
  - ext/quickjsrb/quickjsrb_crypto_subtle.h
84
84
  - ext/quickjsrb/quickjsrb_file.c
85
85
  - ext/quickjsrb/quickjsrb_file.h
86
+ - ext/quickjsrb/quickjsrb_libc.c
87
+ - ext/quickjsrb/quickjsrb_libc.h
86
88
  - ext/quickjsrb/vendor/polyfill-encoding.min.js
87
89
  - ext/quickjsrb/vendor/polyfill-file.min.js
88
90
  - ext/quickjsrb/vendor/polyfill-url.min.js