Debian Codegraph @

vendor/mruby-source/doc/guides/gc-arena-howto.md

raw
1 # How to use `mrb_gc_arena_save()`/`mrb_gc_arena_restore()`/`mrb_gc_protect()`
2
3 _This is an English translation of [Matz's blog post][matz blog post]
4 written in Japanese._
5 _Some parts are updated to reflect recent changes._
6
7 [matz blog post]: <https://www.rubyist.net/~matz/20130731.html>
8
9 When you are extending mruby using C language, you may encounter
10 mysterious "arena overflow error" or memory leak or very slow
11 execution speed. This is an error indicating overflow of "GC arena"
12 implementing "conservative GC".
13
14 GC (garbage collector) must ensure that object is "alive", in other
15 words, that it is referenced by somewhere from the program. This can be
16 determined by checking if the object can be directly or indirectly
17 referenced by root. The local variables, global variables and
18 constants etc. are root.
19
20 If program execution is performed inside mruby VM, there is nothing to
21 worry about because GC can access all roots owned by the VM.
22
23 The problem arises when executing C functions. The object referenced
24 by C variable is also "alive", but mruby GC cannot aware of this, so
25 it might mistakenly recognize the objects referenced by only C
26 variables as dead.
27
28 This can be a fatal bug if the GC tries to collect a live object.
29
30 In CRuby, we scan C stack area, and use C variable as root to check
31 whether object is alive or not. Of course, because we are accessing C
32 stack just as memory region, we never know it is an integer or a
33 pointer. We work around this by assuming that if it looks like a
34 pointer, then assume it as a pointer. We call it "conservative".
35
36 By the way, CRuby's "conservative GC" has some problems.
37
38 The biggest problem is we have no way to access to the stack area in
39 portable way. Therefore, we cannot use this method if we'd like to
40 implement highly portable runtime, like mruby.
41
42 So we came up with another plan to implement "conservative GC" in mruby.
43
44 Again, the problem is when an object which was created in C function, becomes
45 no longer referenced in the Ruby world, and cannot be treated as garbage.
46
47 In mruby, we recognize all objects created in C function are alive.
48 Then we have no problem such as confusing a live object as dead.
49
50 This means that because we cannot collect a truly dead object, we may
51 lose efficiency, but as a trade-off the GC itself is highly portable.
52 We can say goodbye to the problem that GC deletes live objects due to
53 optimization which sometimes occurs in CRuby.
54
55 According to this idea, we have a table, called "GC arena", which
56 remembers objects created in C function.
57
58 The arena is stack structure, when C function execution is returned to mruby
59 VM, all objects registered in the arena are popped.
60
61 This works very well, but can cause another problem: "arena overflow error" or
62 memory leak.
63
64 As of this writing, mruby automatically extend arena to remember
65 objects (See `MRB_GC_FIXED_ARENA` and `MRB_GC_ARENA_SIZE` in
66 [doc/guides/mrbconf.md](mrbconf.md)).
67
68 If you create many objects in C functions, memory usage will increase, since
69 GC never kicks in. This memory usage may look like memory leaks, but will also
70 make execution slower as more memory will need to be allocated.
71
72 With the build time configuration, you can limit the maximum size of
73 arena (e.g., 100). Then if you create many objects, arena overflows,
74 thus you will get an "arena overflow error".
75
76 To work around these problems, we have `mrb_gc_arena_save()` and
77 `mrb_gc_arena_restore()` functions.
78
79 `int mrb_gc_arena_save(mrb)` returns the current position of the stack
80 top of GC arena, and `void mrb_gc_arena_restore(mrb, idx)` sets the
81 stack top position to back to given `idx`.
82
83 We can use them like this:
84
85 ```c
86 int arena_idx = mrb_gc_arena_save(mrb);
87
88 // ...create objects...
89 mrb_gc_arena_restore(mrb, arena_idx);
90
91 ```
92
93 In mruby, C function calls are surrounded by this save/restore, but we
94 can further optimize memory usage by surrounding save/restore, and can
95 avoid creating arena overflow bugs.
96
97 Let's take a real example. Here is the source code of `Array#inspect`:
98
99 ```c
100 static mrb_value
101 inspect_ary(mrb_state *mrb, mrb_value ary, mrb_value list)
102 {
103 mrb_int i;
104 mrb_value s, arystr;
105 char head[] = { '[' };
106 char sep[] = { ',', ' ' };
107 char tail[] = { ']' };
108
109 /* check recursive */
110 for (i=0; i<RARRAY_LEN(list); i++) {
111 if (mrb_obj_equal(mrb, ary, RARRAY_PTR(list)[i])) {
112 return mrb_str_new(mrb, "[...]", 5);
113 }
114 }
115
116 mrb_ary_push(mrb, list, ary);
117
118 arystr = mrb_str_new_capa(mrb, 64);
119 mrb_str_cat(mrb, arystr, head, sizeof(head));
120
121 for (i=0; i<RARRAY_LEN(ary); i++) {
122 int ai = mrb_gc_arena_save(mrb);
123
124 if (i > 0) {
125 mrb_str_cat(mrb, arystr, sep, sizeof(sep));
126 }
127 if (mrb_array_p(RARRAY_PTR(ary)[i])) {
128 s = inspect_ary(mrb, RARRAY_PTR(ary)[i], list);
129 }
130 else {
131 s = mrb_inspect(mrb, RARRAY_PTR(ary)[i]);
132 }
133 mrb_str_cat(mrb, arystr, RSTRING_PTR(s), RSTRING_LEN(s));
134 mrb_gc_arena_restore(mrb, ai);
135 }
136
137 mrb_str_cat(mrb, arystr, tail, sizeof(tail));
138 mrb_ary_pop(mrb, list);
139
140 return arystr;
141 }
142 ```
143
144 This is a real example, so slightly complicated, but bear with me.
145 The essence of `Array#inspect` is that after stringifying each element
146 of array using `inspect` method, we join them together so that we can
147 get `inspect` representation of the entire array.
148
149 After the `inspect` representation is created, we no longer require the
150 individual string representation. This means that we don't have to register
151 these temporal objects into GC arena.
152
153 Therefore, in order to keep the arena size small; the `ary_inspect()` function
154 will do the following:
155
156 - save the position of the stack top using `mrb_gc_arena_save()`.
157 - get `inspect` representation of each element.
158 - append it to the constructing entire `inspect` representation of array.
159 - restore stack top position using `mrb_gc_arena_restore()`.
160
161 Please note that the final `inspect` representation of entire array
162 was created before the call of `mrb_gc_arena_restore()`. Otherwise,
163 required temporal object may be deleted by GC.
164
165 We may have an usecase where after creating many temporal objects, we'd
166 like to keep some of them. In this case, we cannot use the same idea
167 in `ary_inspect()` like appending objects to existing one.
168 Instead, after `mrb_gc_arena_restore()`, we must re-register the objects we
169 want to keep in the arena using `mrb_gc_protect(mrb, obj)`.
170 Use `mrb_gc_protect()` with caution because it could also lead to an "arena
171 overflow error".
172
173 We must also mention that when `mrb_funcall` is called in top level, the return
174 value is also registered to GC arena, so repeated use of `mrb_funcall` may
175 eventually lead to an "arena overflow error".
176
177 Use `mrb_gc_arena_save()` and `mrb_gc_arena_restore()` or possible use of
178 `mrb_gc_protect()` to workaround this.