Skip to content

Crash in JS_NewContext with low memory limit #1181

@bnoordhuis

Description

@bnoordhuis

Not super urgent but nice to fix.

Happens when the runtime memory limit is so low that the context cannot finish initializing. Requires many tedious tweaks to JS_NewContext and the JS_AddFeature helpers to handle out-of-memory conditions during their initialization steps.

Test:

diff --git a/api-test.c b/api-test.c
index 9bd3b63..84c99cd 100644
--- a/api-test.c
+++ b/api-test.c
@@ -631,6 +631,31 @@ static void global_object_prototype(void)
     }
 }
 
+static void low_memory_limit(void)
+{
+    unsigned base, limit;
+    JSRuntime *rt;
+    JSContext *ctx;
+    int all, ok;
+
+    all = ok = 0;
+    rt = JS_NewRuntime();
+    for (base = 512; base <= 64*1024; base = 2*base) {
+        for (limit = base; limit < 2*base; limit += base/8) {
+            JS_SetMemoryLimit(rt, limit);
+            ctx = JS_NewContext(rt); // expected to fail, not to crash
+            if (ctx) {
+                JS_FreeContext(ctx);
+                ok++;
+            }
+            all++;
+        }
+    }
+    JS_FreeRuntime(rt);
+    assert(ok > 0);     // expect some successes...
+    assert(ok < all);   // ...but not all
+}
+
 int main(void)
 {
     sync_call();
@@ -645,5 +670,6 @@ int main(void)
     dump_memory_usage();
     new_errors();
     global_object_prototype();
+    low_memory_limit();
     return 0;
 }

Example crash:

==3084694== Invalid write of size 8                                            
==3084694==    at 0x12506C: JS_NewObjectFromShape (quickjs.c:5043)
==3084694==    by 0x1252A6: JS_NewObjectProtoClass (quickjs.c:5119)
==3084694==    by 0x1C7A3F: JS_AddIntrinsicBasicObjects (quickjs.c:53423)      
==3084694==    by 0x11D26A: JS_NewContextRaw (quickjs.c:2374)                                                                                                  
==3084694==    by 0x11D2AF: JS_NewContext (quickjs.c:2383)                     
==3084694==    by 0x119C4C: small_memory_limit (api-test.c:646)                
==3084694==    by 0x119D40: main (api-test.c:673)                              
==3084694==  Address 0x0 is not stack'd, malloc'd or (recently) free'd   

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions