Skip to content

SEGFAULT Issue Related to Fiber Usage in ngx_mruby Development #6060

Closed

Description

@pyama86

mruby version:3.2.0

Hello. I am developing with ngx_mruby and I have encountered a SEGV issue related to Fiber and would like to consult with you about it.

  mrb_value fiber_class = mrb_obj_value(mrb_class_get(mrb, "Fiber"));
  handler_proc = mrb_obj_value(mrb_closure_new(mrb, rproc->body.irep));
  if (mrb->exc) {
    ...
  }

  fiber_proc = (mrb_value *)ngx_palloc(r->pool, sizeof(mrb_value));
  *fiber_proc = mrb_funcall_with_block(mrb, fiber_class, mrb_intern_cstr(mrb, "new"), 0, NULL, handler_proc);
  ...

  handler_result = mrb_fiber_resume(mrb, *fiber_proc, 0, NULL);

A SEGV occurs when performing operations such as redirects in Nginx, moving back and forth between the Nginx context and the mruby context. The error appears at the following location.

Program received signal SIGSEGV, Segmentation fault.
0x00005555557a1ae3 in fiber_switch (mrb=0x555555ad01c0, self=..., len=0, a=0x0, resume=true, vmexec=true) at /home/pyama/src/github.com/matsumotory/ngx_mruby/mruby/mrbgems/mruby-fiber/src/fiber.c:260
260     value = c->stbase[0] = MRB_PROC_ENV(c->cibase->proc)->stack[0];
  1. Here is the state during the first execution. At this point, c->cibase->proc->flags equals 1536.
com/matsumotory/ngx_mruby/src/http/ngx_http_mruby_module.c:841
841    if (mrb_test(ngx_mrb_start_fiber(r, state->mrb, code->proc, mrb_result))) {
(gdb) p *code
$40 = {code = {
  file = 0x555555b9bb20 "Nginx::Request.new.headers_out[\"Server\"] = \"global_ngx_mruby\"; Nginx.return Nginx::DECLINED",
  string = 0x555555b9bb20 "Nginx::Request.new.headers_out[\"Server\"] = \"global_ngx_mruby\"; Nginx.return Nginx::DECLINED"},
 code_type = NGX_MRB_CODE_TYPE_STRING, n = 0, cache = 1, proc = 0x555555b35500, ctx = 0x555555b8f0e0}


ory/ngx_mruby/mruby/mrbgems/mruby-fiber/src/fiber.c:260
260     value = c->stbase[0] = MRB_PROC_ENV(c->cibase->proc)->stack[0];
(gdb) p c->cibase->proc->flags
$42 = 1536
  1. For the second execution, c->cibase->proc->flags equals 512.
com/matsumotory/ngx_mruby/src/http/ngx_http_mruby_module.c:841
841    if (mrb_test(ngx_mrb_start_fiber(r, state->mrb, code->proc, mrb_result))) {
(gdb) p *code
$45 = {code = {
  file = 0x555555b9bb20 "Nginx::Request.new.headers_out[\"Server\"] = \"global_ngx_mruby\"; Nginx.return Nginx::DECLINED",
  string = 0x555555b9bb20 "Nginx::Request.new.headers_out[\"Server\"] = \"global_ngx_mruby\"; Nginx.return Nginx::DECLINED"},
 code_type = NGX_MRB_CODE_TYPE_STRING, n = 0, cache = 1, proc = 0x555555b35500, ctx = 0x555555b8f0e0}
(gdb) c
Continuing.

Breakpoint 2, fiber_switch (mrb=0x555555ad01c0, self=..., len=0, a=0x0, resume=true, vmexec=true) at /home/pyama/src/github.com/matsumotory/ngx_mruby/mruby/mrbgems/mruby-fiber/src/fiber.c:260
260     value = c->stbase[0] = MRB_PROC_ENV(c->cibase->proc)->stack[0];
(gdb) p c->cibase->proc->flags
$46 = 512

As a result, it seems that the following process is diverged and NULL is returned.

https://github.com/mruby/mruby/blob/master/include/mruby/proc.h#L69

#define MRB_PROC_ORPHAN 512
#define MRB_PROC_ORPHAN_P(p) (((p)->flags & MRB_PROC_ORPHAN) != 0)
#define MRB_PROC_ENVSET 1024
#define MRB_PROC_ENV_P(p) (((p)->flags & MRB_PROC_ENVSET) != 0)
#define MRB_PROC_ENV(p) (MRB_PROC_ENV_P(p) ? (p)->e.env : NULL)

If you have any information necessary to resolve this issue, please let me know

Activity

  1. matz commented on Sep 20, 2023

    @matz
    Member

    Can you please run the reproduction code with the address sanitizer?

  2. pyama86 commented on Sep 20, 2023

    @pyama86
    Author

    Matz, thank you for your response. I added enable_sanitizer 'address,undefined,leak' to the build_config.rb file and executed it. Initially, there was an error related to mruby-userdata, but after fixing that, there were no further outputs or reports from the sanitizer.

    Starting program: /home/pyama/src/github.com/matsumotory/ngx_mruby/build/nginx/sbin/nginx                                               
    [Thread debugging using libthread_db enabled]                                                                                           
    Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".                                                              
    "[3391485] init master process"                                                                                                         
    "ngx_mruby: STREAM: mruby_stream_init_code"                                                                                             
    "[3391485] init worker process from inline code"                                                                                        
    "ngx_mruby: STREAM: mruby_stream_init_worker_code"                                                                                      
    
    Program received signal SIGSEGV, Segmentation fault.
    0x000055555641b4e1 in fiber_switch (mrb=0x625000002900, self=..., len=0, a=0x0, resume=true, vmexec=true) at /home/pyama/src/github.com/
    matsumotory/ngx_mruby/mruby/mrbgems/mruby-fiber/src/fiber.c:260
    260         value = c->stbase[0] = MRB_PROC_ENV(c->cibase->proc)->stack[0];
    (gdb) p MRB_PROC_ENV(c->cibase->proc)
    $1 = (void *) 0x0
    
  3. pyama86 commented on Sep 20, 2023

    @pyama86
    Author

    Additional information:
    It appears that in cases where struct RProc *rp = mrb_closure_new(mrb, rproc->body.irep); is generated as shown, the RProc's upper becomes NULL.

    First request:

    (gdb) p *code
    $2 = {code = {file = 0x555555b9bb20 "Nginx::Request.new.headers_out[\"Server\"] = \"global_ngx_mruby\"; Nginx.return Nginx::DECLINED", 
        string = 0x555555b9bb20 "Nginx::Request.new.headers_out[\"Server\"] = \"global_ngx_mruby\"; Nginx.return Nginx::DECLINED"}, 
      code_type = NGX_MRB_CODE_TYPE_STRING, n = 0, cache = 1, proc = 0x555555b35500, ctx = 0x555555b8f0e0}
    (gdb) c
    Continuing.
    
    Breakpoint 2, ngx_mrb_start_fiber (r=0x555555ace7e0, mrb=0x555555ad01c0, rproc=0x555555b35500, result=0x555555acf6b8) at /home/pyama/src/github.com/matsumotory/ngx_mruby/src/http/ngx_http_mruby_async.c:50
    50        handler_proc = mrb_obj_value(rp);
    (gdb) p rp
    $3 = (struct RProc *) 0x555555aed150
    (gdb) p rp->upper
    $4 = (const struct RProc *) 0x555555aed210
    

    Second request:

    841       if (mrb_test(ngx_mrb_start_fiber(r, state->mrb, code->proc, mrb_result))) {
    (gdb) p *code
    $7 = {code = {file = 0x555555b9bb20 "Nginx::Request.new.headers_out[\"Server\"] = \"global_ngx_mruby\"; Nginx.return Nginx::DECLINED", 
        string = 0x555555b9bb20 "Nginx::Request.new.headers_out[\"Server\"] = \"global_ngx_mruby\"; Nginx.return Nginx::DECLINED"}, 
      code_type = NGX_MRB_CODE_TYPE_STRING, n = 0, cache = 1, proc = 0x555555b35500, ctx = 0x555555b8f0e0}
    (gdb) c
    Continuing.
    
    Breakpoint 2, ngx_mrb_start_fiber (r=0x555555ace7e0, mrb=0x555555ad01c0, rproc=0x555555b35500, result=0x555555d2ee20) at /home/pyama/src/github.com/matsumotory/ngx_mruby/src/http/ngx_http_mruby_async.c:50
    50        handler_proc = mrb_obj_value(rp);
    (gdb) p rp->upper
    $8 = (const struct RProc *) 0x0
    

    It seems that the issue is similar to the one described in this gist.

    https://gist.github.com/yyamano/603b6934cafb68d63278f2739bc21c5e

  4. matz commented on Sep 20, 2023

    @matz
    Member

    Some questions:

    • Did this code work properly in the past? Or is this code a new one?
    • Can you show us the p result from the following?
      • handler_proc
      • c
      • *c
      • *c->cibase
  5. dearblue commented on Sep 20, 2023

    @dearblue
    Contributor

    @pyama86,
    I tried the combination of ngx_mruby + mruby 3.2.0 on FreeBSD, and no SEGFAULT occurred.
    However, ngx_mruby uses Fiber#resume in mrb_funcall(), which causes a FiberError in fiber_resume() and the HTTP response returns "500 Internal Server Error".

    What will happen after applying the following patch?

    diff --git a/src/http/ngx_http_mruby_async.c b/src/http/ngx_http_mruby_async.c
    index e2bcbb6..17fb1cd 100644
    --- a/src/http/ngx_http_mruby_async.c
    +++ b/src/http/ngx_http_mruby_async.c
    @@ -53,6 +53,11 @@ mrb_value ngx_mrb_start_fiber(ngx_http_request_t *r, mrb_state *mrb, struct RPro
                       "%s NOTICE %s:%d: preparing fiber got the raise, leave the fiber", MODULE_NAME, __func__, __LINE__);
         return mrb_false_value();
       }
    +  if (!mrb_proc_p(*fiber_proc)) {
    +    ngx_log_error(NGX_LOG_NOTICE, r->connection->log, 0,
    +                  "%s NOTICE %s:%d: preparing fiber does not get a proc object, leave the fiber", MODULE_NAME, __func__, __LINE__);
    +    return mrb_false_value();
    +  }
    
       return ngx_mrb_run_fiber(mrb, fiber_proc, result);
     }
    @@ -68,7 +73,7 @@ mrb_value ngx_mrb_run_fiber(mrb_state *mrb, mrb_value *fiber_proc, mrb_value *re
       ctx = ngx_mrb_http_get_module_ctx(mrb, r);
       ctx->fiber_proc = fiber_proc;
    
    -  resume_result = mrb_funcall(mrb, *fiber_proc, "call", 0, NULL);
    +  resume_result = mrb_top_run(mrb, mrb_proc_ptr(*fiber_proc), mrb_top_self(mrb), 0);
       if (mrb->exc) {
         ngx_log_error(NGX_LOG_NOTICE, r->connection->log, 0, "%s NOTICE %s:%d: fiber got the raise, leave the fiber",
                       MODULE_NAME, __func__, __LINE__);

    If you are interested in why the changes were made to cause the FiberError, please see the following issue:

  6. pyama86 commented on Sep 20, 2023

    @pyama86
    Author

    @matz

    Did this code work properly in the past? Or is this code a new one?

    No, I am rewriting it in C because in mruby 3.2, it is no longer possible to execute across C and mruby contexts using Fiber.

    Here are the results of the print:

    (gdb) p handler_proc
    $21 = {w = 93824998394112}
    (gdb) p c
    $14 = (struct mrb_context *) 0x555555d36a40
    (gdb) p *c
    $15 = {prev = 0x555555d37a10, stbase = 0x555555abf880, stend = 0x555555abfa80, ci = 0x555555abfa90, cibase = 0x555555abfa90,
    ciend = 0x555555abfc10, status = MRB_FIBER_RUNNING, vmexec = false, fib = 0x555555b34870}
    (gdb) p *c->cibase
    $16 = {n = 0 '\000', nk = 0 '\000', cci = 0 '\000', mid = 0, proc = 0x555555b34900, blk = 0x0, stack = 0x555555abf880,
    pc = 0x555555b9d360 "\035\001\001\037\001", u = {env = 0x555555af8cd0, target_class = 0x555555af8cd0}}
    (gdb) p *c->cibase->proc
    $17 = {c = 0x555555ade5e0, gcnext = 0x555555b34930, tt = MRB_TT_PROC, color = 4, flags = 512, body = {irep = 0x555555b8ede0,
    func = 0x555555b8ede0}, upper = 0x0, e = {target_class = 0x555555af8cd0, env = 0x555555af8cd0}}
    
  7. matz commented on Sep 20, 2023

    @matz
    Member

    Thank you. Could you show us values for both cases, I mean, when proc->upper is a valid pointer, and when it is NULL?

  8. pyama86 commented on Sep 20, 2023

    @pyama86
    Author

    @dearblue
    Thank you.
    The compilation succeeds, but the tests executed with ./test.sh in the top directory of ngx_mruby did not pass.

  9. pyama86 commented on Sep 20, 2023

    @pyama86
    Author

    @matz
    The value entering proc->upper actually appears to be mrb->c->ci->proc, indicating its value.
    https://github.com/mruby/mruby/blob/master/src/proc.c#L60

    When processing successfully:

    Breakpoint 2, ngx_mrb_run (r=0x555555ace7e0, state=0x555555ac99a8, code=0x555555b9baf8, cached=1, result=0x0) at /home/pyama/src/github.
    com/matsumotory/ngx_mruby/src/http/ngx_http_mruby_module.c:841                                                                          
    841       if (mrb_test(ngx_mrb_start_fiber(r, state->mrb, code->proc, mrb_result))) {                                                   
    (gdb) p *code                                                                                                                           $6 = {code = {file = 0x555555b9bb20 "Nginx::Request.new.headers_out[\"Server\"] = \"global_ngx_mruby\"; Nginx.return Nginx::DECLINED", 
        string = 0x555555b9bb20 "Nginx::Request.new.headers_out[\"Server\"] = \"global_ngx_mruby\"; Nginx.return Nginx::DECLINED"}, 
      code_type = NGX_MRB_CODE_TYPE_STRING, n = 0, cache = 1, proc = 0x555555b35500, ctx = 0x555555b8f0e0}
    (gdb) c    
    Continuing.
                                                                                                                                            Breakpoint 1, ngx_mrb_run_fiber (mrb=0x555555ad01c0, fiber_proc=0x555555acf6c0, result=0x555555acf6b8) at /home/pyama/src/github.com/mat
    sumotory/ngx_mruby/src/http/ngx_http_mruby_async.c:78                                                                                   
    78        handler_result = mrb_fiber_resume(mrb, *fiber_proc, 0, NULL);
    (gdb) p mrb->c->ci->proc                                             
    $7 = (const struct RProc *) 0x555555aed210
    

    When SEGV occurs:

    Breakpoint 2, ngx_mrb_run (r=0x555555ace7e0, state=0x555555ac99a8, code=0x555555b9baf8, cached=1, result=0x0) at /home/pyama/src/github.com/matsumotory/ngx_mruby/src/http/ngx_http_mruby_module.c:841
    841       if (mrb_test(ngx_mrb_start_fiber(r, state->mrb, code->proc, mrb_result))) {
    (gdb) p *code
    $8 = {code = {file = 0x555555b9bb20 "Nginx::Request.new.headers_out[\"Server\"] = \"global_ngx_mruby\"; Nginx.return Nginx::DECLINED", 
        string = 0x555555b9bb20 "Nginx::Request.new.headers_out[\"Server\"] = \"global_ngx_mruby\"; Nginx.return Nginx::DECLINED"}, 
      code_type = NGX_MRB_CODE_TYPE_STRING, n = 0, cache = 1, proc = 0x555555b35500, ctx = 0x555555b8f0e0}
    (gdb) c
    Continuing.
    
    Breakpoint 1, ngx_mrb_run_fiber (mrb=0x555555ad01c0, fiber_proc=0x555555d2eff0, result=0x555555d2ee20) at /home/pyama/src/github.com/matsumotory/ngx_mruby/src/http/ngx_http_mruby_async.c:78
    78        handler_result = mrb_fiber_resume(mrb, *fiber_proc, 0, NULL);
    (gdb) p mrb->c->ci->proc
    $9 = (const struct RProc *) 0x0
    
  10. added a commit that references this issue on Sep 20, 2023
  11. pyama86 commented on Sep 20, 2023

    @pyama86
    Author

    I'm not sure if it will be helpful, but here is the code I'm currently working on: link.

  12. pyama86 commented on Sep 20, 2023

    @pyama86
    Author

    The memory address changed because of the compilation, so I'll repost the answer to the previous question.

    (gdb) p c
    $1 = (struct mrb_context *) 0x555555d36a40
    (gdb) p *c
    $2 = {prev = 0x555555d37a10, stbase = 0x555555abf880, stend = 0x555555abfa80, ci = 0x555555abfa90, cibase = 0x555555abfa90, 
      ciend = 0x555555abfc10, status = MRB_FIBER_RUNNING, vmexec = false, fib = 0x555555b34870}
    (gdb) p *c->cibase
    $3 = {n = 0 '\000', nk = 0 '\000', cci = 0 '\000', mid = 0, proc = 0x555555b34900, blk = 0x0, stack = 0x555555abf880, 
      pc = 0x555555b9d360 "\035\001\001\037\001", u = {env = 0x555555af8cd0, target_class = 0x555555af8cd0}}
    (gdb) p *c->cibase->proc
    $4 = {c = 0x555555ade5e0, gcnext = 0x555555b34930, tt = MRB_TT_PROC, color = 4, flags = 512, body = {irep = 0x555555b8ede0, 
        func = 0x555555b8ede0}, upper = 0x0, e = {target_class = 0x555555af8cd0, env = 0x555555af8cd0}}
    (gdb) p c->cibase->proc->upper
    $5 = (const struct RProc *) 0x0
    
  13. pyama86 commented on Sep 21, 2023

    @pyama86
    Author

    I have created a minimal implementation for reproducing the issue, so I'm sharing it with you.
    https://github.com/pyama86/fiber-segv

  14. pyama86 commented on Sep 21, 2023

    @pyama86
    Author

    If proc is orphaned, I was wondering if the following would be acceptable. What do you think?

    % git diff                                                                                                                              
    diff --git a/mrbgems/mruby-fiber/src/fiber.c b/mrbgems/mruby-fiber/src/fiber.c                                                          
    index 33913c108..ec5878dd6 100644                                                                                                       
    --- a/mrbgems/mruby-fiber/src/fiber.c                                                                                                   
    +++ b/mrbgems/mruby-fiber/src/fiber.c                                                                                                   
    @@ -257,7 +257,12 @@ fiber_switch(mrb_state *mrb, mrb_value self, mrb_int len, const mrb_value *a, mr                                   
           }                                                                                                                                
         }                                                                                                                                  
         c->cibase->n = (uint8_t)len;                                                                                                       
    -    value = c->stbase[0] = MRB_PROC_ENV(c->cibase->proc)->stack[0];                                                                    
    +    if(MRB_PROC_ENV_P(c->cibase->proc) != NULL) {                                                                                      
    +      value = c->stbase[0] = MRB_PROC_ENV(c->cibase->proc)->stack[0];                                                                  
    +    } else {                                                                                                                           
    +      value = c->stbase[0] = mrb_nil_value();                                                                                          
    +    }                                                                                                                                  
    +                                                                                                                                       
       }                                                                                                                                    
       else {                                                                                                                               
         value = fiber_result(mrb, a, len); 
  15. matz commented on Sep 21, 2023

    @matz
    Member

    Thank you for the reproducing code!!! That will be a great help.
    Let me investigate the real issue. Stay tuned.

  16. 4 remaining items

  17. pyama86 commented on Sep 23, 2023

    @pyama86
    Author

    I've resolved the issue regarding SEGV, but another mysterious phenomenon is occurring. When I create two fibers using the same mrb state, the second loop seems to behave strangely. Here's the reproduction code: Link to GitHub

    The output looks like this:

    ./mruby/bin/mruby ./segv.rb                                                                                                           
    Hello, World1                                                                                                                           
    --> nil                                                                                                                                 
    Hello, World1                                                                                                                           
    --> nil                                                                                                                                 
    Hello, World1                                                                                                                           
    --> nil                                                                                                                                 
    Hello, World2                                                                                                                           
    --> nil                                                                                                                                 
    --> nil                                                                                                                                 
    trace (most recent call last):                                                                                                          
            [2] ./segv.rb:1                                                                                                                 
            [1] ./segv.rb:1:in new                                                                                                          
    ./segv.rb:1:in initialize: double resume (FiberError)                                                                                   
    make: *** [Makefile:3: run] Error 1 
    

    Ideally, "Hello, World2" should be printed three times. If there's a possibility of another issue, please let me know, and we can create a separate issue for it.

  18. dearblue commented on Sep 23, 2023

    @dearblue
    Contributor

    Currently I remember that mrb_fiber_resume() is not supposed to be called from inside a C function defined as a method.

    However, calling the mrb_segv_init() function directly from main(), which is prepared separately, causes the same phenomenon.


    Instead of mrb_parse_string() + mrb_generate_code(), use mrb_load_string_cxt() with mrbc_context::no_exec = TRUE and it may work without problems.

         mrbc_context *cxt1 = mrbc_context_new(mrb);
         mrbc_context *cxt2 = mrbc_context_new(mrb);
    
    -    mrb_value str1 = mrb_str_new_cstr(mrb, code1);
    -    mrb_value str2 = mrb_str_new_cstr(mrb, code2);
    -
         mrb_value fiber_class1 = mrb_obj_value(mrb_class_get(mrb, "Fiber"));
         mrb_value fiber_class2 = mrb_obj_value(mrb_class_get(mrb, "Fiber"));
    
    -    struct mrb_parser_state *p1 = mrb_parse_string(mrb, RSTRING_PTR(str1), cxt1);
    -    struct mrb_parser_state *p2 = mrb_parse_string(mrb, RSTRING_PTR(str2), cxt2);
    +    cxt1->no_exec = TRUE;
    +    cxt2->no_exec = TRUE;
    
    -    struct RProc *proc1 = mrb_generate_code(mrb, p1);
    -    mrb_value fiber1 = mrb_funcall_with_block(mrb, fiber_class1, new, 0, NULL, mrb_obj_value(mrb_closure_new(mrb, proc1->body.irep)));
    +    mrb_value proc1 = mrb_load_string_cxt(mrb, code1, cxt1);
    +    mrb_value proc2 = mrb_load_string_cxt(mrb, code2, cxt2);
    +
    +    mrb_value fiber1 = mrb_funcall_with_block(mrb, fiber_class1, new, 0, NULL, proc1);
         p(mrb, mrb_fiber_resume(mrb, fiber1, 0, NULL));
         p(mrb, mrb_fiber_resume(mrb, fiber1, 0, NULL));
         p(mrb, mrb_fiber_resume(mrb, fiber1, 0, NULL));
    
    -    struct RProc *proc2 = mrb_generate_code(mrb, p2);
    -    mrb_value fiber2 = mrb_funcall_with_block(mrb, fiber_class2, new, 0, NULL, mrb_obj_value(mrb_closure_new(mrb, proc2->body.irep)));
    +    mrb_value fiber2 = mrb_funcall_with_block(mrb, fiber_class2, new, 0, NULL, proc2);
         p(mrb, mrb_fiber_resume(mrb, fiber2, 0, NULL));
         p(mrb, mrb_fiber_resume(mrb, fiber2, 0, NULL));
         p(mrb, mrb_fiber_resume(mrb, fiber2, 0, NULL));
  19. pyama86 commented on Sep 23, 2023

    @pyama86
    Author

    Currently I remember that mrb_fiber_resume() is not supposed to be called from inside a C function defined as a method.

    Yes, that's correct. So, up until version 3.1, we were creating and running Fibers in Ruby context. However, starting from version 3.2, when we switch back and forth between the C and Ruby contexts using Fibers, exceptions started to occur. Therefore, when transitioning to version 3.2, we are attempting to execute it only within the C context.

    Reference: Link to the source code

    In our current ngx_mruby implementation, we are generating closures from body->irep. However, when it comes to doing this successfully using the provided method, we would greatly appreciate any advice on the optimal approach.
    (In the minimal implementation, we were generating a Proc from a string for convenience.)

  20. dearblue commented on Sep 23, 2023

    @dearblue
    Contributor

    By setting mrbc_context::no_exec = TRUE and calling mrb_load_XXX_cxt(), we get a parsed and compiled executable proc object instead of an evaluated result.
    Also, by setting mrbc_context::dump_result = TRUE and calling mrb_load_XXX_cxt(), we can remove mrb_codedump_all() since we don't need to call it.

    Here is an example patch for one of the three locations found by git grep -wn mrb_generate_code.

    diff --git a/src/http/ngx_http_mruby_module.c b/src/http/ngx_http_mruby_module.c
    index 76acfbb..11cd1a6 100644
    --- a/src/http/ngx_http_mruby_module.c
    +++ b/src/http/ngx_http_mruby_module.c
    @@ -994,10 +994,11 @@ static ngx_int_t ngx_http_mruby_shared_state_init(ngx_mrb_state_t *state)
     static ngx_int_t ngx_http_mruby_shared_state_compile(ngx_conf_t *cf, ngx_mrb_state_t *state, ngx_mrb_code_t *code)
     {
       FILE *mrb_file;
    -  struct mrb_parser_state *p;
    +  mrb_value ret;
    
       NGX_MRUBY_CODE_MRBC_CONTEXT_FREE(state->mrb, code);
       code->ctx = mrbc_context_new(state->mrb);
    +  code->ctx->no_exec = TRUE;
     #ifdef NGX_MRUBY_IREP_DEBUG
       code->ctx->dump_result = TRUE;
     #endif
    @@ -1007,28 +1008,17 @@ static ngx_int_t ngx_http_mruby_shared_state_compile(ngx_conf_t *cf, ngx_mrb_sta
           return NGX_ERROR;
         }
         mrbc_filename(state->mrb, code->ctx, (char *)code->code.file);
    -    p = mrb_parse_file(state->mrb, mrb_file, code->ctx);
    +    ret = mrb_load_file_cxt(state->mrb, mrb_file, code->ctx);
         fclose(mrb_file);
       } else {
         mrbc_filename(state->mrb, code->ctx, "INLINE CODE");
    -    p = mrb_parse_string(state->mrb, (char *)code->code.string, code->ctx);
    +    ret = mrb_load_string_cxt(state->mrb, (char *)code->code.string, code->ctx);
       }
    
    -  if (p == NULL || (0 < p->nerr)) {
    -    return NGX_ERROR;
    -  }
    -
    -  code->proc = mrb_generate_code(state->mrb, p);
    -  mrb_pool_close(p->pool);
    -  if (code->proc == NULL) {
    -    return NGX_ERROR;
    +  if (!mrb_proc_p(ret)) {
    +      return NGX_ERROR;
       }
    -
    -#ifdef NGX_MRUBY_IREP_DEBUG
    -  /* mrb_codedump_all() is not declared in mruby headers. So just follows the mruby way. See mruby/src/load.c. */
    -  void mrb_codedump_all(mrb_state*, struct RProc*);
    -  mrb_codedump_all(state->mrb, code->proc);
    -#endif
    +  code->proc = mrb_proc_ptr(ret);
    
       if (code->code_type == NGX_MRB_CODE_TYPE_FILE) {
         ngx_conf_log_error(NGX_LOG_NOTICE, cf, 0, "%s NOTICE %s:%d: compile info: code->code.file=(%s) code->cache=(%d)",
  21. dearblue commented on Sep 23, 2023

    @dearblue
    Contributor

    If you must use mruby 3.2.0 as is, you can create an env object right after code->proc = mrb_proc_ptr(ret) to avoid the SEGFAULT, as far as I checked with https://github.com/pyama86/fiber-segv.

    I would like to think there are no side effects.

    #include <mruby/proc.h>
    
    static void
    proc_attach_env(mrb_state *mrb, struct RProc *proc)
    {
      struct REnv *e = MRB_OBJ_ALLOC(mrb, MRB_TT_ENV, MRB_PROC_TARGET_CLASS(proc));
      e->mid = 0;
      e->cxt = mrb->c;
      e->stack = (mrb_value *)mrb_malloc(mrb, sizeof(mrb_value));
      e->stack[0] = mrb_top_self(mrb);
      MRB_ENV_SET_LEN(e, 1);
      MRB_ENV_CLOSE(e);
      proc->e.env = e;
    }
    
    // License: Public Domain
  22. pyama86 commented on Sep 24, 2023

    @pyama86
    Author

    Thank you for your suggestion.
    However, I feel it is a bit risky to rewrite the parser part of ngx_mruby due to the fact that the Fiber implementation, which worked in mruby 3.1, no longer works in 3.2.

    I should have said this from the beginning, but in mruby 3.1, it was possible to resume a Fiber created in a ruby context in a C context like this , but why is this no longer possible in 3.2?
    ref: https://github.com/matsumotory/ngx_mruby/blob/master/mrbgems/ngx_mruby_mrblib/mrblib/mrb_nginx.rb#L134

  23. dearblue commented on Sep 24, 2023

    @dearblue
    Contributor

    However, I feel it is a bit risky to rewrite the parser part of ngx_mruby due to the fact that the Fiber implementation, which worked in mruby 3.1, no longer works in 3.2.

    The current mruby API does not appear to provide a regular means of obtaining a proc object from an irep structure.
    There is just mrb_proc_new() and mrb_closure_new() without the MRB_API modifier.

    In my opinion, the only way to turn Ruby code into a proc object is to use mrbc_context::no_exec = TRUE + mrb_load_XXX_cxt().

    I should have said this from the beginning, but in mruby 3.1, it was possible to resume a Fiber created in a ruby context in a C context like this , but why is this no longer possible in 3.2?

    The reason is that there was a problem when Fiber#resume was called like mrb_funcall(mrb, fiber_obj, "resume", 0).

  24. pyama86 commented on Sep 24, 2023

    @pyama86
    Author

    Thank you for your response. I have one more question at the end.

    In our use case, when a user writes the following configuration:

    Nginx.redirect 301

    Internally, we want to execute it as follows:

    Fiber.new {
      Nginx.redirect 301
    }

    However, with mruby 3.2 and later, since it does not allow Fibers to switch between C and Ruby contexts, am I correct in understanding that this interface is no longer usable?

    Regarding the following statement:

    In my opinion, the only way to convert Ruby code to a proc object is to use mrb_load_XXX_cxt() with mrbc_context::no_exec = TRUE+.

    This statement seems somewhat unrelated, and what we need is to execute the Ruby code written by the user within a Fiber. The reason is that we need to provide non-blocking APIs, and we require the use of Fiber's yield and resume, without wanting users to implement them themselves.

  25. dearblue commented on Sep 24, 2023

    @dearblue
    Contributor

    However, with mruby 3.2 and later, since it does not allow Fibers to switch between C and Ruby contexts, am I correct in understanding that this interface is no longer usable?

    Please note at the outset that I do not have a clear understanding of the ngx_mruby process flow, so I can't say for sure.

    From outside the mruby VM (e.g. main()), switching with mrb_fiber_resume() is no problem.
    Likewise, from outside the mruby VM (e.g. main()), there is no problem to run the proc object that does the Fiber#resume with mrb_top_run().

    It is best to assume that switching is not possible from within the mruby VM.


    # 念のため、DeepL で変換する前の日本語を以下に残します。

    僕は ngx_mruby の処理の流れを把握できているわけではないので、確かなことが言えないことを最初にご承知ください。

    mruby VM の外側 (例えば main()) から、mrb_fiber_resume() で切り替えることは問題ありません。
    同じく、mruby VM の外側 (例えば main()) から、Fiber#resume を行う proc オブジェクトを mrb_top_run() で実行させることに問題はありません。

    mruby VM の内部からは切り替えが出来ないと考えたほうが良いでしょう。

  26. pyama86 commented on Sep 24, 2023

    @pyama86
    Author

    Thank you for your response.

    To provide a bit more historical context, the issue with Fiber has been present for quite some time, as discussed in this issue. H2O and ngx_mruby had been using a workaround by encapsulating Fiber with Proc. However, starting from version 3.2, it became evident that it wouldn't work without applying some sort of patch to mruby 3.2, so we have decided to address it with a patch.

    As far as I can see, a patch that reverses this commit should suffice, at least in my preliminary assessment. This should help mitigate the impact.

    Thank you for your response.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions