mruby/mruby — pull request #1000 by tsahara-iij (2013-03-13 07:11:04+00:00)
Title: DATA_TYPE must be set as soon as possible

**We must set DATA_TYPE in ``#initialize`` method as soon as possible for any MRB_TT_DATA objects.** If we have an exception in ``#initialize`` method before DATA_TYPE was set, mruby interpreter will be killed by null pointer dereference.

```
% bin/mruby -e 'Time.new(1)'
trace:
[0] -e:1
-e:1: Not a valid time. (ArgumentError)
zsh: segmentation fault (core dumped) bin/mruby -e 'Time.new(1)'
```
```
% gdb bin/mruby mruby.core
GNU gdb 6.3
...
#0 0x00000000004078e6 in obj_free (mrb=0x2100c7800, obj=0x20adb0c20)
at /d/home/tsahara/src/mruby/src/gc.c:529
529 if (d->type->dfree) {
(gdb) bt
#0 0x00000000004078e6 in obj_free (mrb=0x2100c7800, obj=0x20adb0c20)
at /home/tsahara/mruby/src/gc.c:529
#1 0x00000000004083a0 in mrb_free_heap (mrb=0x2100c7800)
at /home/tsahara/src/mruby/src/gc.c:304
#2 0x000000000041ed01 in mrb_close (mrb=0x2100c7800)
at /home/tsahara/mruby/src/state.c:114
#3 0x000000000040276c in main (argc=Variable "argc" is not available.)
at /home/tsahara/mruby/tools/mruby/mruby.c:162
(gdb)
```

``obj_free()`` assumes d->type (= DATA_TYPE) is not NULL. But it is not the case. Before DATA_TYPE(self) is set in ``#initialize``, DATA_TYPE is NULL because ``mrb_instance_new()`` set 0 on (almost) all members of self.

This pull-request addresses an issue caused by Time class. But there are other extension modules which don't set DATA_TYPE properly (I have written such modules :P and Github code search finds some more). So changing the assumption may be better way to go. The pull-request #858 adds a check if d->type is set properly.