module ObjectSpace

The objspace library extends the ObjectSpace module and adds several methods to get internal statistic information about object/memory management.

You need to require 'objspace' to use this extension module.

Generally, you *SHOULD NOT* use this library if you do not know about the MRI implementation. Mainly, this library is for (memory) profiler developers and MRI developers who need to know about MRI memory usage.

The ObjectSpace module contains a number of routines that interact with the garbage collection facility and allow you to traverse all living objects with an iterator.

ObjectSpace also provides support for object finalizers, procs that will be called when a specific object is about to be destroyed by garbage collection.

a = "A"
b = "B"

ObjectSpace.define_finalizer(a, proc {|id| puts "Finalizer one on #{id}" })
ObjectSpace.define_finalizer(b, proc {|id| puts "Finalizer two on #{id}" })

produces:

Finalizer two on 537763470
Finalizer one on 537763480

Public Class Methods

_id2ref(object_id) → an_object click to toggle source

Converts an object id to a reference to the object. May not be called on an object id passed as a parameter to a finalizer.

s = "I am a string"                    #=> "I am a string"
r = ObjectSpace._id2ref(s.object_id)   #=> "I am a string"
r == s                                 #=> true
static VALUE
id2ref(VALUE obj, VALUE objid)
{
#if SIZEOF_LONG == SIZEOF_VOIDP
#define NUM2PTR(x) NUM2ULONG(x)
#elif SIZEOF_LONG_LONG == SIZEOF_VOIDP
#define NUM2PTR(x) NUM2ULL(x)
#endif
    rb_objspace_t *objspace = &rb_objspace;
    VALUE ptr;
    void *p0;

    ptr = NUM2PTR(objid);
    p0 = (void *)ptr;

    if (ptr == Qtrue) return Qtrue;
    if (ptr == Qfalse) return Qfalse;
    if (ptr == Qnil) return Qnil;
    if (FIXNUM_P(ptr)) return (VALUE)ptr;
    if (FLONUM_P(ptr)) return (VALUE)ptr;
    ptr = obj_id_to_ref(objid);

    if ((ptr % sizeof(RVALUE)) == (4 << 2)) {
        ID symid = ptr / sizeof(RVALUE);
        if (rb_id2name(symid) == 0)
            rb_raise(rb_eRangeError, "%p is not symbol id value", p0);
        return ID2SYM(symid);
    }

    if (!is_id_value(objspace, ptr)) {
        rb_raise(rb_eRangeError, "%p is not id value", p0);
    }
    if (!is_live_object(objspace, ptr)) {
        rb_raise(rb_eRangeError, "%p is recycled object", p0);
    }
    if (RBASIC(ptr)->klass == 0) {
        rb_raise(rb_eRangeError, "%p is internal object", p0);
    }
    return (VALUE)ptr;
}
allocation_class_path(object) → string click to toggle source

Returns the class for the given object.

class A
  def foo
    ObjectSpace::trace_object_allocations do
      obj = Object.new
      p "#{ObjectSpace::allocation_class_path(obj)}"
    end
  end
end

A.new.foo #=> "Class"

See ::trace_object_allocations for more information and examples.

static VALUE
allocation_class_path(VALUE self, VALUE obj)
{
    struct allocation_info *info = lookup_allocation_info(obj);

    if (info && info->class_path) {
        return rb_str_new2(info->class_path);
    }
    else {
        return Qnil;
    }
}
allocation_generation(object) → Fixnum click to toggle source

Returns garbage collector generation for the given object.

class B
  include ObjectSpace

  def foo
    trace_object_allocations do
      obj = Object.new
      p "Generation is #{allocation_generation(obj)}"
    end
  end
end

B.new.foo #=> "Generation is 3"

See ::trace_object_allocations for more information and examples.

static VALUE
allocation_generation(VALUE self, VALUE obj)
{
    struct allocation_info *info = lookup_allocation_info(obj);
    if (info) {
        return SIZET2NUM(info->generation);
    }
    else {
        return Qnil;
    }
}
allocation_method_id(object) → string click to toggle source

Returns the method identifier for the given object.

class A
  include ObjectSpace

  def foo
    trace_object_allocations do
      obj = Object.new
      p "#{allocation_class_path(obj)}##{allocation_method_id(obj)}"
    end
  end
end

A.new.foo #=> "Class#new"

See ::trace_object_allocations for more information and examples.

static VALUE
allocation_method_id(VALUE self, VALUE obj)
{
    struct allocation_info *info = lookup_allocation_info(obj);
    if (info) {
        return info->mid;
    }
    else {
        return Qnil;
    }
}
allocation_sourcefile(object) → string click to toggle source

Returns the source file origin from the given object.

See ::trace_object_allocations for more information and examples.

static VALUE
allocation_sourcefile(VALUE self, VALUE obj)
{
    struct allocation_info *info = lookup_allocation_info(obj);

    if (info && info->path) {
        return rb_str_new2(info->path);
    }
    else {
        return Qnil;
    }
}
allocation_sourceline(object) → string click to toggle source

Returns the original line from source for from the given object.

See ::trace_object_allocations for more information and examples.

static VALUE
allocation_sourceline(VALUE self, VALUE obj)
{
    struct allocation_info *info = lookup_allocation_info(obj);

    if (info) {
        return INT2FIX(info->line);
    }
    else {
        return Qnil;
    }
}
count_nodes([result_hash]) → hash click to toggle source

Counts nodes for each node type.

This method is only for MRI developers interested in performance and memory usage of Ruby programs.

It returns a hash as:

{:NODE_METHOD=>2027, :NODE_FBODY=>1927, :NODE_CFUNC=>1798, ...}

If the optional argument, result_hash, is given, it is overwritten and returned. This is intended to avoid probe effect.

Note: The contents of the returned hash is implementation defined. It may be changed in future.

This method is only expected to work with C Ruby.

static VALUE
count_nodes(int argc, VALUE *argv, VALUE os)
{
    size_t nodes[NODE_LAST+1];
    size_t i;
    VALUE hash;

    if (rb_scan_args(argc, argv, "01", &hash) == 1) {
        if (!RB_TYPE_P(hash, T_HASH))
            rb_raise(rb_eTypeError, "non-hash given");
    }

    for (i = 0; i <= NODE_LAST; i++) {
        nodes[i] = 0;
    }

    rb_objspace_each_objects(cn_i, &nodes[0]);

    if (hash == Qnil) {
        hash = rb_hash_new();
    }
    else if (!RHASH_EMPTY_P(hash)) {
        st_foreach(RHASH_TBL(hash), set_zero_i, hash);
    }

    for (i=0; i<NODE_LAST; i++) {
        if (nodes[i] != 0) {
            VALUE node;
            switch (i) {
#define COUNT_NODE(n) case n: node = ID2SYM(rb_intern(#n)); break;
                COUNT_NODE(NODE_SCOPE);
                COUNT_NODE(NODE_BLOCK);
                COUNT_NODE(NODE_IF);
                COUNT_NODE(NODE_CASE);
                COUNT_NODE(NODE_WHEN);
                COUNT_NODE(NODE_OPT_N);
                COUNT_NODE(NODE_WHILE);
                COUNT_NODE(NODE_UNTIL);
                COUNT_NODE(NODE_ITER);
                COUNT_NODE(NODE_FOR);
                COUNT_NODE(NODE_BREAK);
                COUNT_NODE(NODE_NEXT);
                COUNT_NODE(NODE_REDO);
                COUNT_NODE(NODE_RETRY);
                COUNT_NODE(NODE_BEGIN);
                COUNT_NODE(NODE_RESCUE);
                COUNT_NODE(NODE_RESBODY);
                COUNT_NODE(NODE_ENSURE);
                COUNT_NODE(NODE_AND);
                COUNT_NODE(NODE_OR);
                COUNT_NODE(NODE_MASGN);
                COUNT_NODE(NODE_LASGN);
                COUNT_NODE(NODE_DASGN);
                COUNT_NODE(NODE_DASGN_CURR);
                COUNT_NODE(NODE_GASGN);
                COUNT_NODE(NODE_IASGN);
                COUNT_NODE(NODE_IASGN2);
                COUNT_NODE(NODE_CDECL);
                COUNT_NODE(NODE_CVASGN);
                COUNT_NODE(NODE_CVDECL);
                COUNT_NODE(NODE_OP_ASGN1);
                COUNT_NODE(NODE_OP_ASGN2);
                COUNT_NODE(NODE_OP_ASGN_AND);
                COUNT_NODE(NODE_OP_ASGN_OR);
                COUNT_NODE(NODE_OP_CDECL);
                COUNT_NODE(NODE_CALL);
                COUNT_NODE(NODE_FCALL);
                COUNT_NODE(NODE_VCALL);
                COUNT_NODE(NODE_SUPER);
                COUNT_NODE(NODE_ZSUPER);
                COUNT_NODE(NODE_ARRAY);
                COUNT_NODE(NODE_ZARRAY);
                COUNT_NODE(NODE_VALUES);
                COUNT_NODE(NODE_HASH);
                COUNT_NODE(NODE_RETURN);
                COUNT_NODE(NODE_YIELD);
                COUNT_NODE(NODE_LVAR);
                COUNT_NODE(NODE_DVAR);
                COUNT_NODE(NODE_GVAR);
                COUNT_NODE(NODE_IVAR);
                COUNT_NODE(NODE_CONST);
                COUNT_NODE(NODE_CVAR);
                COUNT_NODE(NODE_NTH_REF);
                COUNT_NODE(NODE_BACK_REF);
                COUNT_NODE(NODE_MATCH);
                COUNT_NODE(NODE_MATCH2);
                COUNT_NODE(NODE_MATCH3);
                COUNT_NODE(NODE_LIT);
                COUNT_NODE(NODE_STR);
                COUNT_NODE(NODE_DSTR);
                COUNT_NODE(NODE_XSTR);
                COUNT_NODE(NODE_DXSTR);
                COUNT_NODE(NODE_EVSTR);
                COUNT_NODE(NODE_DREGX);
                COUNT_NODE(NODE_DREGX_ONCE);
                COUNT_NODE(NODE_ARGS);
                COUNT_NODE(NODE_ARGS_AUX);
                COUNT_NODE(NODE_OPT_ARG);
                COUNT_NODE(NODE_KW_ARG);
                COUNT_NODE(NODE_POSTARG);
                COUNT_NODE(NODE_ARGSCAT);
                COUNT_NODE(NODE_ARGSPUSH);
                COUNT_NODE(NODE_SPLAT);
                COUNT_NODE(NODE_TO_ARY);
                COUNT_NODE(NODE_BLOCK_ARG);
                COUNT_NODE(NODE_BLOCK_PASS);
                COUNT_NODE(NODE_DEFN);
                COUNT_NODE(NODE_DEFS);
                COUNT_NODE(NODE_ALIAS);
                COUNT_NODE(NODE_VALIAS);
                COUNT_NODE(NODE_UNDEF);
                COUNT_NODE(NODE_CLASS);
                COUNT_NODE(NODE_MODULE);
                COUNT_NODE(NODE_SCLASS);
                COUNT_NODE(NODE_COLON2);
                COUNT_NODE(NODE_COLON3);
                COUNT_NODE(NODE_CREF);
                COUNT_NODE(NODE_DOT2);
                COUNT_NODE(NODE_DOT3);
                COUNT_NODE(NODE_FLIP2);
                COUNT_NODE(NODE_FLIP3);
                COUNT_NODE(NODE_SELF);
                COUNT_NODE(NODE_NIL);
                COUNT_NODE(NODE_TRUE);
                COUNT_NODE(NODE_FALSE);
                COUNT_NODE(NODE_ERRINFO);
                COUNT_NODE(NODE_DEFINED);
                COUNT_NODE(NODE_POSTEXE);
                COUNT_NODE(NODE_ALLOCA);
                COUNT_NODE(NODE_BMETHOD);
                COUNT_NODE(NODE_MEMO);
                COUNT_NODE(NODE_IFUNC);
                COUNT_NODE(NODE_DSYM);
                COUNT_NODE(NODE_ATTRASGN);
                COUNT_NODE(NODE_PRELUDE);
                COUNT_NODE(NODE_LAMBDA);
#undef COUNT_NODE
              default: node = INT2FIX(i);
            }
            rb_hash_aset(hash, node, SIZET2NUM(nodes[i]));
        }
    }
    return hash;
}
count_objects([result_hash]) → hash click to toggle source

Counts objects for each type.

It returns a hash, such as:

{
  :TOTAL=>10000,
  :FREE=>3011,
  :T_OBJECT=>6,
  :T_CLASS=>404,
  # ...
}

The contents of the returned hash are implementation specific. It may be changed in future.

If the optional argument result_hash is given, it is overwritten and returned. This is intended to avoid probe effect.

This method is only expected to work on C Ruby.

static VALUE
count_objects(int argc, VALUE *argv, VALUE os)
{
    rb_objspace_t *objspace = &rb_objspace;
    size_t counts[T_MASK+1];
    size_t freed = 0;
    size_t total = 0;
    size_t i;
    VALUE hash;

    if (rb_scan_args(argc, argv, "01", &hash) == 1) {
        if (!RB_TYPE_P(hash, T_HASH))
            rb_raise(rb_eTypeError, "non-hash given");
    }

    for (i = 0; i <= T_MASK; i++) {
        counts[i] = 0;
    }

    for (i = 0; i < heap_pages_used; i++) {
        struct heap_page *page = heap_pages_sorted[i];
        RVALUE *p, *pend;

        p = page->start; pend = p + page->limit;
        for (;p < pend; p++) {
            if (p->as.basic.flags) {
                counts[BUILTIN_TYPE(p)]++;
            }
            else {
                freed++;
            }
        }
        total += page->limit;
    }

    if (hash == Qnil) {
        hash = rb_hash_new();
    }
    else if (!RHASH_EMPTY_P(hash)) {
        st_foreach(RHASH_TBL_RAW(hash), set_zero, hash);
    }
    rb_hash_aset(hash, ID2SYM(rb_intern("TOTAL")), SIZET2NUM(total));
    rb_hash_aset(hash, ID2SYM(rb_intern("FREE")), SIZET2NUM(freed));

    for (i = 0; i <= T_MASK; i++) {
        VALUE type;
        switch (i) {
#define COUNT_TYPE(t) case (t): type = ID2SYM(rb_intern(#t)); break;
            COUNT_TYPE(T_NONE);
            COUNT_TYPE(T_OBJECT);
            COUNT_TYPE(T_CLASS);
            COUNT_TYPE(T_MODULE);
            COUNT_TYPE(T_FLOAT);
            COUNT_TYPE(T_STRING);
            COUNT_TYPE(T_REGEXP);
            COUNT_TYPE(T_ARRAY);
            COUNT_TYPE(T_HASH);
            COUNT_TYPE(T_STRUCT);
            COUNT_TYPE(T_BIGNUM);
            COUNT_TYPE(T_FILE);
            COUNT_TYPE(T_DATA);
            COUNT_TYPE(T_MATCH);
            COUNT_TYPE(T_COMPLEX);
            COUNT_TYPE(T_RATIONAL);
            COUNT_TYPE(T_NIL);
            COUNT_TYPE(T_TRUE);
            COUNT_TYPE(T_FALSE);
            COUNT_TYPE(T_SYMBOL);
            COUNT_TYPE(T_FIXNUM);
            COUNT_TYPE(T_UNDEF);
            COUNT_TYPE(T_NODE);
            COUNT_TYPE(T_ICLASS);
            COUNT_TYPE(T_ZOMBIE);
#undef COUNT_TYPE
          default:              type = INT2NUM(i); break;
        }
        if (counts[i])
            rb_hash_aset(hash, type, SIZET2NUM(counts[i]));
    }

    return hash;
}
count_objects_size([result_hash]) → hash click to toggle source

Counts objects size (in bytes) for each type.

Note that this information is incomplete. You need to deal with this information as only a HINT. Especially, total size of T_DATA may not right size.

It returns a hash as:

{:TOTAL=>1461154, :T_CLASS=>158280, :T_MODULE=>20672, :T_STRING=>527249, ...}

If the optional argument, result_hash, is given, it is overwritten and returned. This is intended to avoid probe effect.

The contents of the returned hash is implementation defined. It may be changed in future.

This method is only expected to work with C Ruby.

static VALUE
count_objects_size(int argc, VALUE *argv, VALUE os)
{
    size_t counts[T_MASK+1];
    size_t total = 0;
    enum ruby_value_type i;
    VALUE hash;

    if (rb_scan_args(argc, argv, "01", &hash) == 1) {
        if (!RB_TYPE_P(hash, T_HASH))
            rb_raise(rb_eTypeError, "non-hash given");
    }

    for (i = 0; i <= T_MASK; i++) {
        counts[i] = 0;
    }

    rb_objspace_each_objects(cos_i, &counts[0]);

    if (hash == Qnil) {
        hash = rb_hash_new();
    }
    else if (!RHASH_EMPTY_P(hash)) {
        st_foreach(RHASH_TBL(hash), set_zero_i, hash);
    }

    for (i = 0; i <= T_MASK; i++) {
        if (counts[i]) {
            VALUE type = type2sym(i);
            total += counts[i];
            rb_hash_aset(hash, type, SIZET2NUM(counts[i]));
        }
    }
    rb_hash_aset(hash, ID2SYM(rb_intern("TOTAL")), SIZET2NUM(total));
    return hash;
}
count_tdata_objects([result_hash]) → hash click to toggle source

Counts objects for each T_DATA type.

This method is only for MRI developers interested in performance and memory usage of Ruby programs.

It returns a hash as:

{RubyVM::InstructionSequence=>504, :parser=>5, :barrier=>6,
 :mutex=>6, Proc=>60, RubyVM::Env=>57, Mutex=>1, Encoding=>99,
 ThreadGroup=>1, Binding=>1, Thread=>1, RubyVM=>1, :iseq=>1,
 Random=>1, ARGF.class=>1, Data=>1, :autoload=>3, Time=>2}
# T_DATA objects existing at startup on r32276.

If the optional argument, result_hash, is given, it is overwritten and returned. This is intended to avoid probe effect.

The contents of the returned hash is implementation specific and may change in the future.

In this version, keys are Class object or Symbol object.

If object is kind of normal (accessible) object, the key is Class object. If object is not a kind of normal (internal) object, the key is symbol name, registered by rb_data_type_struct.

This method is only expected to work with C Ruby.

static VALUE
count_tdata_objects(int argc, VALUE *argv, VALUE self)
{
    VALUE hash;

    if (rb_scan_args(argc, argv, "01", &hash) == 1) {
        if (!RB_TYPE_P(hash, T_HASH))
            rb_raise(rb_eTypeError, "non-hash given");
    }

    if (hash == Qnil) {
        hash = rb_hash_new();
    }
    else if (!RHASH_EMPTY_P(hash)) {
        st_foreach(RHASH_TBL(hash), set_zero_i, hash);
    }

    rb_objspace_each_objects(cto_i, (void *)hash);

    return hash;
}
define_finalizer(obj, aProc=proc()) click to toggle source

Adds aProc as a finalizer, to be called after obj was destroyed.

static VALUE
define_final(int argc, VALUE *argv, VALUE os)
{
    VALUE obj, block;

    rb_scan_args(argc, argv, "11", &obj, &block);
    should_be_finalizable(obj);
    if (argc == 1) {
        block = rb_block_proc();
    }
    else {
        should_be_callable(block);
    }

    return define_final0(obj, block);
}
each_object([module]) {|obj| ... } → fixnum click to toggle source
each_object([module]) → an_enumerator

Calls the block once for each living, nonimmediate object in this Ruby process. If module is specified, calls the block for only those classes or modules that match (or are a subclass of) module. Returns the number of objects found. Immediate objects (Fixnums, Symbols true, false, and nil) are never returned. In the example below, each_object returns both the numbers we defined and several constants defined in the Math module.

If no block is given, an enumerator is returned instead.

a = 102.7
b = 95       # Won't be returned
c = 12345678987654321
count = ObjectSpace.each_object(Numeric) {|x| p x }
puts "Total count: #{count}"

produces:

12345678987654321
102.7
2.71828182845905
3.14159265358979
2.22044604925031e-16
1.7976931348623157e+308
2.2250738585072e-308
Total count: 7
static VALUE
os_each_obj(int argc, VALUE *argv, VALUE os)
{
    VALUE of;

    if (argc == 0) {
        of = 0;
    }
    else {
        rb_scan_args(argc, argv, "01", &of);
    }
    RETURN_ENUMERATOR(os, 1, &of);
    return os_obj_of(of);
}
start → nil click to toggle source
garbage_collect → nil
garbage_collect → nil
start(full_mark: false) → nil

Initiates garbage collection, unless manually disabled.

This method is defined with keyword arguments that default to true:

def GC.start(full_mark: true, immediate_sweep: true) end

Use full_mark: false to perform a minor GC. Use immediate_sweep: false to defer sweeping (use lazy sweep).

Note: These keyword arguments are implementation and version dependent. They are not guaranteed to be future-compatible, and may be ignored if the underlying implementation does not support them.

static VALUE
gc_start_internal(int argc, VALUE *argv, VALUE self)
{
    rb_objspace_t *objspace = &rb_objspace;
    int full_mark = TRUE, immediate_sweep = TRUE;
    VALUE opt = Qnil;
    static ID keyword_ids[2];

    rb_scan_args(argc, argv, "0:", &opt);

    if (!NIL_P(opt)) {
        VALUE kwvals[2];

        if (!keyword_ids[0]) {
            keyword_ids[0] = rb_intern("full_mark");
            keyword_ids[1] = rb_intern("immediate_sweep");
        }

        rb_get_kwargs(opt, keyword_ids, 0, 2, kwvals);

        if (kwvals[0] != Qundef)
            full_mark = RTEST(kwvals[0]);
        if (kwvals[1] != Qundef)
            immediate_sweep = RTEST(kwvals[1]);
    }

    garbage_collect(objspace, full_mark, immediate_sweep, GPR_FLAG_METHOD);
    if (!finalizing) finalize_deferred(objspace);

    return Qnil;
}
memsize_of(obj) → Integer click to toggle source

Return consuming memory size of obj.

Note that the return size is incomplete. You need to deal with this information as only a HINT. Especially, the size of T_DATA may not be correct.

This method is only expected to work with C Ruby.

static VALUE
memsize_of_m(VALUE self, VALUE obj)
{
    return SIZET2NUM(rb_obj_memsize_of(obj));
}
memsize_of_all([klass]) → Integer click to toggle source

Return consuming memory size of all living objects.

If klass (should be Class object) is given, return the total memory size of instances of the given class.

Note that the returned size is incomplete. You need to deal with this information as only a HINT. Especially, the size of T_DATA may not be correct.

Note that this method does NOT return total malloc'ed memory size.

This method can be defined by the following Ruby code:

def memsize_of_all klass = false
  total = 0
  ObjectSpace.each_object{|e|
    total += ObjectSpace.memsize_of(e) if klass == false || e.kind_of?(klass)
  }
  total
end

This method is only expected to work with C Ruby.

static VALUE
memsize_of_all_m(int argc, VALUE *argv, VALUE self)
{
    struct total_data data = {0, 0};

    if (argc > 0) {
        rb_scan_args(argc, argv, "01", &data.klass);
    }

    rb_objspace_each_objects(total_i, &data);
    return SIZET2NUM(data.total);
}
reachable_objects_from(obj) → array or nil click to toggle source
MRI specific feature

Return all reachable objects from `obj'.

This method returns all reachable objects from `obj'.

If `obj' has two or more references to the same object `x', then returned array only includes one `x' object.

If `obj' is a non-markable (non-heap management) object such as true, false, nil, symbols and Fixnums (and Flonum) then it simply returns nil.

If `obj' has references to an internal object, then it returns instances of ObjectSpace::InternalObjectWrapper class. This object contains a reference to an internal object and you can check the type of internal object with `type' method.

If `obj' is instance of ObjectSpace::InternalObjectWrapper class, then this method returns all reachable object from an internal object, which is pointed by `obj'.

With this method, you can find memory leaks.

This method is only expected to work except with C Ruby.

Example:

ObjectSpace.reachable_objects_from(['a', 'b', 'c'])
#=> [Array, 'a', 'b', 'c']

ObjectSpace.reachable_objects_from(['a', 'a', 'a'])
#=> [Array, 'a', 'a', 'a'] # all 'a' strings have different object id

ObjectSpace.reachable_objects_from([v = 'a', v, v])
#=> [Array, 'a']

ObjectSpace.reachable_objects_from(1)
#=> nil # 1 is not markable (heap managed) object
static VALUE
reachable_objects_from(VALUE self, VALUE obj)
{
    if (rb_objspace_markable_object_p(obj)) {
        VALUE ret = rb_ary_new();
        struct rof_data data;

        if (rb_typeddata_is_kind_of(obj, &iow_data_type)) {
            obj = (VALUE)DATA_PTR(obj);
        }

        data.refs = st_init_numtable();
        data.internals = rb_ary_new();

        rb_objspace_reachable_objects_from(obj, reachable_object_from_i, &data);

        st_foreach(data.refs, collect_values, (st_data_t)ret);
        return ret;
    }
    else {
        return Qnil;
    }
}
reachable_objects_from_root → hash click to toggle source
MRI specific feature

Return all reachable objects from root.

static VALUE
reachable_objects_from_root(VALUE self)
{
    struct rofr_data data;
    VALUE hash = data.categories = rb_hash_new();
    data.last_category = 0;

    rb_funcall(hash, rb_intern("compare_by_identity"), 0);
    rb_objspace_reachable_objects_from_root(reachable_object_from_root_i, &data);
    rb_hash_foreach(hash, collect_values_of_values, hash);

    return hash;
}
trace_object_allocations { block } click to toggle source

Starts tracing object allocations from the ObjectSpace extension module.

For example:

require 'objspace'

class C
  include ObjectSpace

  def foo
    trace_object_allocations do
      obj = Object.new
      p "#{allocation_sourcefile(obj)}:#{allocation_sourceline(obj)}"
    end
  end
end

C.new.foo #=> "objtrace.rb:8"

This example has included the ObjectSpace module to make it easier to read, but you can also use the ::trace_object_allocations notation (recommended).

Note that this feature introduces a huge performance decrease and huge memory consumption.

static VALUE
trace_object_allocations(VALUE self)
{
    trace_object_allocations_start(self);
    return rb_ensure(rb_yield, Qnil, trace_object_allocations_stop, self);
}
trace_object_allocations_clear click to toggle source

Clear recorded tracing information.

static VALUE
trace_object_allocations_clear(VALUE self)
{
    struct traceobj_arg *arg = get_traceobj_arg();

    /* clear tables */
    st_foreach(arg->object_table, free_values_i, 0);
    st_clear(arg->object_table);
    st_foreach(arg->str_table, free_keys_i, 0);
    st_clear(arg->str_table);

    /* do not touch TracePoints */

    return Qnil;
}
trace_object_allocations_debug_start() click to toggle source
static VALUE
trace_object_allocations_debug_start(VALUE self)
{
    tmp_keep_remains = 1;
    if (object_allocations_reporter_registered == 0) {
        object_allocations_reporter_registered = 1;
        rb_bug_reporter_add(object_allocations_reporter, 0);
    }

    return trace_object_allocations_start(self);
}
trace_object_allocations_start click to toggle source

Starts tracing object allocations.

static VALUE
trace_object_allocations_start(VALUE self)
{
    struct traceobj_arg *arg = get_traceobj_arg();

    if (arg->running++ > 0) {
        /* do nothing */
    }
    else {
        if (arg->newobj_trace == 0) {
            arg->newobj_trace = rb_tracepoint_new(0, RUBY_INTERNAL_EVENT_NEWOBJ, newobj_i, arg);
            arg->freeobj_trace = rb_tracepoint_new(0, RUBY_INTERNAL_EVENT_FREEOBJ, freeobj_i, arg);
        }
        rb_tracepoint_enable(arg->newobj_trace);
        rb_tracepoint_enable(arg->freeobj_trace);
    }

    return Qnil;
}
trace_object_allocations_stop click to toggle source

Stop tracing object allocations.

Note that if ::trace_object_allocations_start is called n-times, then tracing will stop after calling ::trace_object_allocations_stop n-times.

static VALUE
trace_object_allocations_stop(VALUE self)
{
    struct traceobj_arg *arg = get_traceobj_arg();

    if (arg->running > 0) {
        arg->running--;
    }

    if (arg->running == 0) {
        rb_tracepoint_disable(arg->newobj_trace);
        rb_tracepoint_disable(arg->freeobj_trace);
        arg->newobj_trace = 0;
        arg->freeobj_trace = 0;
    }

    return Qnil;
}
undefine_finalizer(obj) click to toggle source

Removes all finalizers for obj.

static VALUE
undefine_final(VALUE os, VALUE obj)
{
    return rb_undefine_finalizer(obj);
}