Move the detachment of the "env" object, now done by `mrb_top_run()` by #5904, to `mrb_vm_run()`.
This is because `mrb_vm_run()` can remove `mrb_env_unshare()` which is called from `bin/mirb`.
Also, even if the mruby VM is already running, either of the following conditions should be used to detach "env":
- If the `stack_keep` variable is 0.
- If the stack length of "env" is longer than `irep->nlocals`.
The reason for the change is that the stack beyond `irep->nlocals` is used inside the called method, and previously it was possible to reference and manipulate the state inside the method via "env".
env stack | |
main stack | top | m1 | m2 |
|<--------------->|
operable via env stack (including self)
If the problematic block is called from the `m2` method above, it is possible to replace `self` in `m1` and `m2` as well as the internal variables.
This change may cause compatibility problems, but I believe it is better to make `MRB_API`, `mrb_vm_run()` safe.
If a dangerous procedure is absolutely necessary, `mrb_vm_exec()` can still be called as before.
This is to keep the local variables of the previously created blocks consistent in case the `mrbc_context` passed to `mrb_load_exec()` is `NULL` or different.
Switching between `mrbc_context` pointers that are non `NULL` can be done safely by calling `mrbc_cleanup_local_variables()`.
Before this patch, the result of the following code is not as expected.
```console
% cat loadstr.c
#include <mruby.h>
#include <mruby/compile.h>
int
main(int argc, char *argv[])
{
mrb_state *mrb = mrb_open();
mrb_load_string(
mrb,
"(a, b, c, d, e, f, g) = [1, 2, 3, 4, 5, 6, 7] \n"
"$lambda = -> { p [a, b, c, d, e, f, g] }");
mrb_load_string(mrb, "$lambda.call");
mrb_close(mrb);
return 0;
}
% $(bin/mruby-config --cc --cflags --ldflags) loadstr.c $(bin/mruby-config --libs) && ./a.out
[main, nil, nil, main, nil, nil, main]
```
Also, since `mrb_env_unshare()` was not used before, the internal stack of simply detached `env` objects could show invalid addresses by `stack_extend()`.
ref. https://github.com/kou/mruby-pp/commit/ef5951aca870183d8767cb61f6414240988ca35e
The original implementations used plain Ruby strings referenced from
instance variable (`@buf`) as buffers. We replaced those buffers by C
structure (`struct mrb_io_buf`) referenced directly from `fptr`.
The result is significant improvement of both performance and memory
consumption. Our simple benchmarks (reading `README.md` 10,000 times)
runs 5+ times faster, and `mrbtest` test suites consumes 85% less
memory.
Recent changes on `mruby-io` is preparation for this improvement.