Skip to content
This repository
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 798 lines (610 sloc) 25.359 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797
#include "vm/config.h"

#include "builtin/array.hpp"
#include "builtin/data.hpp"
#include "builtin/fixnum.hpp"
#include "builtin/lookuptable.hpp"
#include "builtin/module.hpp"
#include "builtin/nativemethod.hpp"
#include "builtin/object.hpp"
#include "builtin/string.hpp"
#include "builtin/symbol.hpp"
#include "builtin/system.hpp"
#include "builtin/location.hpp"
#include "builtin/block_environment.hpp"
#include "builtin/proc.hpp"

#include "call_frame.hpp"
#include "configuration.hpp"
#include "lookup_data.hpp"
#include "dispatch.hpp"
#include "arguments.hpp"

#include "exception_point.hpp"
#include "global_cache.hpp"

#include "arguments.hpp"
#include "dispatch.hpp"
#include "capi/capi.hpp"
#include "capi/18/include/ruby.h"
#include <string>
#include <vector>
#include <tr1/unordered_map>

#ifdef RBX_WINDOWS
#include <malloc.h>
#endif

namespace rubinius {
  namespace capi {

    typedef std::vector<std::string> CApiConstantNameMap;
    typedef std::tr1::unordered_map<int, VALUE> CApiConstantHandleMap;

    /**
* This looks like a complicated scheme but there is a reason for
* doing it this way. In MRI, rb_cObject, etc. are all global data.
* We need to avoid global data to better support embedding and
* other features like MVM. @see capi_get_constant().
*/
    std::string& capi_get_constant_name(int type) {
      static CApiConstantNameMap map;

      NativeMethodEnvironment* env = NativeMethodEnvironment::get();

      if(map.empty()) {
        map.resize(cCApiMaxConstant + 1);

        map[cCApiArray] = "Array";
        map[cCApiBignum] = "Bignum";
        map[cCApiClass] = "Class";
        map[cCApiComparable] = "Comparable";
        map[cCApiData] = "Data";
        map[cCApiEnumerable] = "Enumerable";
        map[cCApiFalse] = "FalseClass";
        map[cCApiFile] = "File";
        map[cCApiFixnum] = "Fixnum";
        map[cCApiFloat] = "Float";
        map[cCApiHash] = "Hash";
        map[cCApiInteger] = "Integer";
        map[cCApiIO] = "IO";
        map[cCApiKernel] = "Kernel";
        map[cCApiMatch] = "MatchData";
        map[cCApiModule] = "Module";
        map[cCApiNil] = "NilClass";
        map[cCApiNumeric] = "Numeric";
        map[cCApiObject] = "Object";
        map[cCApiRange] = "Range";
        map[cCApiRegexp] = "Regexp";
        map[cCApiRubinius] = "Rubinius";
        map[cCApiString] = "String";
        map[cCApiStruct] = "Struct";
        map[cCApiSymbol] = "Symbol";
        map[cCApiThread] = "Thread";
        map[cCApiTime] = "Time";
        map[cCApiTrue] = "TrueClass";
        map[cCApiProc] = "Proc";
        map[cCApiGC] = "GC";
        map[cCApiCAPI] = "Rubinius::CAPI";
        map[cCApiMethod] = "Method";
        map[cCApiRational] = "Rational";
        map[cCApiComplex] = "Complex";
        map[cCApiEnumerator] = "Enumerable::Enumerator";

        map[cCApiArgumentError] = "ArgumentError";
        map[cCApiEOFError] = "EOFError";
        map[cCApiErrno] = "Errno";
        map[cCApiException] = "Exception";
        map[cCApiFatal] = "FatalError";
        map[cCApiFloatDomainError] = "FloatDomainError";
        map[cCApiIndexError] = "IndexError";
        map[cCApiInterrupt] = "Interrupt";
        map[cCApiIOError] = "IOError";
        map[cCApiLoadError] = "LoadError";
        map[cCApiLocalJumpError] = "LocalJumpError";
        map[cCApiNameError] = "NameError";
        map[cCApiNoMemoryError] = "NoMemoryError";
        map[cCApiNoMethodError] = "NoMethodError";
        map[cCApiNotImplementedError] = "NotImplementedError";
        map[cCApiRangeError] = "RangeError";
        map[cCApiRegexpError] = "RegexpError";
        map[cCApiRuntimeError] = "RuntimeError";
        map[cCApiScriptError] = "ScriptError";
        map[cCApiSecurityError] = "SecurityError";
        map[cCApiSignalException] = "SignalException";
        map[cCApiStandardError] = "StandardError";
        map[cCApiSyntaxError] = "SyntaxError";
        map[cCApiSystemCallError] = "SystemCallError";
        map[cCApiSystemExit] = "SystemExit";
        map[cCApiSystemStackError] = "SystemStackError";
        map[cCApiTypeError] = "TypeError";
        map[cCApiThreadError] = "ThreadError";
        map[cCApiZeroDivisionError] = "ZeroDivisionError";

        if(!LANGUAGE_18_ENABLED(env->state())) {
          map[cCApiMathDomainError] = "Math::DomainError";
          map[cCApiEncoding] = "Encoding";
          map[cCApiEncCompatError] = "Encoding::CompatibilityError";
          map[cCApiWaitReadable] = "IO::WaitReadable";
          map[cCApiWaitWritable] = "IO::WaitWritable";
        }
      }

      if(type < 0 || type >= cCApiMaxConstant) {
        rb_raise(env->get_handle(env->state()->globals().exception.get()),
              "C-API: invalid constant index");
      }

      return map[type];
    }

    /**
* Common implementation for rb_funcall*
*/
    VALUE capi_funcall_backend(const char* file, int line,
                               VALUE receiver, ID method_name,
                               size_t arg_count, VALUE* arg_array)
    {
      NativeMethodEnvironment* env = NativeMethodEnvironment::get();
      env->flush_cached_data();

      Array* args = Array::create(env->state(), arg_count);
      for(size_t i = 0; i < arg_count; i++) {
        args->set(env->state(), i, env->get_object(arg_array[i]));
      }

      Object* blk = cNil;

      if(VALUE blk_handle = env->outgoing_block()) {
        blk = env->get_object(blk_handle);
        env->set_outgoing_block(0);
      }

      Object* recv = env->get_object(receiver);

      // Unlock, we're leaving extension code.
      LEAVE_CAPI(env->state());

      Object* ret = recv->send(env->state(), env->current_call_frame(),
          reinterpret_cast<Symbol*>(method_name), args, blk);

      // We need to get the handle for the return value before getting
      // the GEL so that ret isn't accidentally GCd while we wait.
      VALUE ret_handle = 0;
      if(ret) ret_handle = env->get_handle(ret);

      // Re-entering extension code
      ENTER_CAPI(env->state());

      env->update_cached_data();

      // An exception occurred
      if(!ret) env->current_ep()->return_to(env);

      return ret_handle;
    }

    VALUE capi_funcall_backend_native(NativeMethodEnvironment* env,
                                      const char* file, int line,
                                      Object* recv, Symbol* method,
                                      size_t arg_count,
                                      Object** args, Object* block)
    {
      int marker = 0;
      if(!env->state()->check_stack(env->current_call_frame(), &marker)) {
        env->current_ep()->return_to(env);
      }

      env->flush_cached_data();

      // Unlock, we're leaving extension code.
      LEAVE_CAPI(env->state());

      Object* ret = cNil;

      // Run in a block so objects are properly deconstructed when we
      // do a longjmp because of an exception.
      {
        LookupData lookup(recv, recv->lookup_begin(env->state()), env->state()->globals().sym_private.get());
        Arguments args_o(method, recv, block, arg_count, args);
        Dispatch dis(method);

        ret = dis.send(env->state(), env->current_call_frame(),
                      lookup, args_o);
      }

      // We need to get the handle for the return value before getting
      // the GEL so that ret isn't accidentally GCd while we wait.
      VALUE ret_handle = 0;
      if(ret) ret_handle = env->get_handle(ret);

      // Re-entering extension code
      ENTER_CAPI(env->state());

      env->update_cached_data();

      // An exception occurred
      if(!ret) env->current_ep()->return_to(env);

      return ret_handle;
    }

    VALUE capi_fast_call(VALUE receiver, ID method_name, int arg_count, ...) {
      NativeMethodEnvironment* env = NativeMethodEnvironment::get();

      va_list varargs;
      va_start(varargs, arg_count);

      Object** args = reinterpret_cast<Object**>(
                        alloca(sizeof(Object*) * arg_count));

      for(int i = 0; i < arg_count; i++) {
        args[i] = env->get_object(va_arg(varargs, VALUE));
      }

      va_end(varargs);

      // Unlock, we're leaving extension code.
      LEAVE_CAPI(env->state());

      Object* recv = env->get_object(receiver);
      Symbol* method = (Symbol*)method_name;

      Object* ret = cNil;
      // Run in block so we properly deconstruct objects allocated
      // on the stack if we do a longjmp because of an exception.
      {
        LookupData lookup(recv, recv->lookup_begin(env->state()), env->state()->globals().sym_private.get());
        Arguments args_o(method, recv, cNil, arg_count, args);
        Dispatch dis(method);

        ret = dis.send(env->state(), env->current_call_frame(),
                       lookup, args_o);
      }

      // We need to get the handle for the return value before getting
      // the GEL so that ret isn't accidentally GCd while we wait.
      VALUE ret_handle = 0;
      if(ret) ret_handle = env->get_handle(ret);

      // Re-entering extension code
      ENTER_CAPI(env->state());

      // An exception occurred
      if(!ret) env->current_ep()->return_to(env);

      return ret_handle;
    }

    VALUE capi_yield_backend(NativeMethodEnvironment* env,
                              Object* blk,
                              size_t arg_count, Object** arg_vals)
    {
      int marker = 0;
      if(!env->state()->check_stack(env->current_call_frame(), &marker)) {
        env->current_ep()->return_to(env);
      }

      env->flush_cached_data();

      // Unlock, we're leaving extension code.
      LEAVE_CAPI(env->state());

      Object* ret = cNil;
      STATE = env->state();

      CallFrame* call_frame = env->current_call_frame();

      // Run in separate block so the arguments are destructed
      // properly before we make a potential longjmp.
      {
        Arguments args(G(sym_call), blk, arg_count, arg_vals);

        if(BlockEnvironment* be = try_as<BlockEnvironment>(blk)) {
          ret = be->call(state, call_frame, args);
        } else if(Proc* proc = try_as<Proc>(blk)) {
          ret = proc->yield(state, call_frame, args);
        } else if(blk->nil_p()) {
          state->raise_exception(Exception::make_lje(state, call_frame));
          ret = NULL;
        } else {
          Dispatch dis(G(sym_call));
          ret = dis.send(state, call_frame, args);
        }
      }

      // We need to get the handle for the return value before getting
      // the GEL so that ret isn't accidentally GCd while we wait.
      VALUE ret_handle = 0;
      if(ret) ret_handle = env->get_handle(ret);

      // Re-entering extension code
      ENTER_CAPI(env->state());

      env->update_cached_data();

      // An exception occurred
      if(!ret) env->current_ep()->return_to(env);

      return ret_handle;
    }

    VALUE capi_call_super_native(NativeMethodEnvironment* env,
                                 size_t arg_count, Object** args)
    {
      int marker = 0;
      if(!env->state()->check_stack(env->current_call_frame(), &marker)) {
        env->current_ep()->return_to(env);
      }

      env->flush_cached_data();

      NativeMethodFrame* frame = NativeMethodFrame::current();

      Object* recv = env->get_object(frame->receiver());
      Module* mod = c_as<Module>(env->get_object(frame->module()));
      Symbol* name = c_as<NativeMethod>(env->get_object(frame->method()))->name();

      // Unlock, we're leaving extension code.
      LEAVE_CAPI(env->state());

      Object* ret = cNil;
      // Use a block objects on the stack are properly deconstructed when
      // we do a potential longjmp.
      {
        LookupData lookup(recv, mod->superclass(), env->state()->globals().sym_private.get());
        Arguments args_o(name, recv, arg_count, args);
        Dispatch dis(name);

        ret = dis.send(env->state(), env->current_call_frame(),
                       lookup, args_o);
      }

      // We need to get the handle for the return value before getting
      // the GEL so that ret isn't accidentally GCd while we wait.
      VALUE ret_handle = 0;
      if(ret) ret_handle = env->get_handle(ret);

      // Re-entering extension code
      ENTER_CAPI(env->state());

      env->update_cached_data();

      // An exception occurred
      if(!ret) env->current_ep()->return_to(env);

      return ret_handle;
    }

    /** Make sure the name has the given prefix. */
    Symbol* prefixed_by(std::string prefix, std::string name) {
      NativeMethodEnvironment* env = NativeMethodEnvironment::get();

      if(name.compare(0UL, prefix.size(), prefix) != 0) {
        std::ostringstream str;
        str << prefix << name;
        name.assign(str.str());
      }

      return env->state()->symbol(name.c_str());
    }

    /** Make sure the name has the given prefix. */
    Symbol* prefixed_by(STATE, const char* prefix, size_t len, ID name) {
      Symbol* sym_obj = reinterpret_cast<Symbol*>(name);
      std::string& sym = state->shared().symbols.lookup_cppstring(sym_obj);

      if(sym.compare(0UL, len, prefix) == 0) return sym_obj;

      std::ostringstream stream;
      stream << prefix << sym;

      return state->symbol(stream.str().c_str());
    }

    Symbol* prefixed_by(STATE, const char prefix, ID name) {
      Symbol* sym_obj = reinterpret_cast<Symbol*>(name);
      std::string& sym = state->shared().symbols.lookup_cppstring(sym_obj);

      if(sym.c_str()[0] == prefix) return sym_obj;

      std::ostringstream stream;
      stream << prefix << sym;

      return state->symbol(stream.str().c_str());
    }

    void capi_raise_runtime_error(const char* reason) {
      rb_raise(rb_eRuntimeError, reason);
    }

    void capi_raise_type_error(object_type type, Object* object) {
      NativeMethodEnvironment* env = NativeMethodEnvironment::get();

      TypeInfo* expected = env->state()->vm()->find_type(type);
      TypeInfo* actual = env->state()->vm()->find_type(object->get_type());

      rb_raise(rb_eTypeError, "wrong argument type %s (expected %s)",
          actual->type_name.c_str(), expected->type_name.c_str());
    }

    void capi_raise_backend(Exception* exception) {
      NativeMethodEnvironment* env = NativeMethodEnvironment::get();
      exception->locations(env->state(), Location::from_call_stack(env->state(),
                           env->current_call_frame()));
      env->state()->raise_exception(exception);

      env->current_ep()->return_to(env);
    }

    void capi_raise_backend(VALUE exception) {
      NativeMethodEnvironment* env = NativeMethodEnvironment::get();
      Exception *exc = capi::c_as<Exception>(env->get_object(exception));
      capi_raise_backend(exc);
    }

    void capi_raise_backend(VALUE klass, const char* reason) {
      NativeMethodEnvironment* env = NativeMethodEnvironment::get();
      Class* cls = c_as<Class>(env->get_object(klass));
      Exception* exc = Exception::make_exception(env->state(), cls, reason);
      capi_raise_backend(exc);
    }

    void capi_raise_break(VALUE obj) {
      NativeMethodEnvironment* env = NativeMethodEnvironment::get();
      env->state()->vm()->thread_state()->raise_break(env->get_object(obj), env->scope()->parent());
      env->current_ep()->return_to(env);
    }

    Proc* wrap_c_function(void* cb, VALUE cb_data, int arity) {
      NativeMethodEnvironment* env = NativeMethodEnvironment::get();
      NativeMethod* nm = NativeMethod::create(env->state(),
                          nil<String>(), env->state()->vm()->shared.globals.rubinius.get(),
                          env->state()->symbol("call"), cb,
                          Fixnum::from(arity));

      nm->set_ivar(env->state(), env->state()->symbol("cb_data"),
                   env->get_object(cb_data));

      Object* current_block = env->block();
      if(!current_block->nil_p()) {
        nm->set_ivar(env->state(), env->state()->symbol("original_block"),
                     current_block);
      }

      Proc* prc = Proc::create(env->state(), env->state()->vm()->shared.globals.proc.get());
      prc->bound_method(env->state(), nm);

      return prc;
    }
  }
}

using namespace rubinius;
using namespace rubinius::capi;

extern "C" {

  VALUE capi_get_constant(CApiConstant type) {
    static CApiConstantHandleMap map;

    CApiConstantHandleMap::iterator entry = map.find(type);
    if(entry == map.end()) {
      VALUE val = rb_path2class(capi_get_constant_name(type).c_str());
      capi::Handle::from(val)->ref(); // Extra ref, since we save it in the map
      map[type] = val;
      return val;
    } else {
      return entry->second;
    }
  }

  VALUE rb_call_super(int argc, const VALUE *argv) {
    NativeMethodEnvironment* env = NativeMethodEnvironment::get();

    Object** args = reinterpret_cast<Object**>(alloca(sizeof(Object*) * argc));
    for(int i = 0; i < argc; i++) {
      args[i] = env->get_object(argv[i]);
    }

    return capi_call_super_native(env, argc, args);
  }

  VALUE rb_funcall(VALUE receiver, ID method_name, int arg_count, ...) {
    NativeMethodEnvironment* env = NativeMethodEnvironment::get();

    va_list varargs;
    va_start(varargs, arg_count);

    Object** args = reinterpret_cast<Object**>(alloca(sizeof(Object*) * arg_count));

    for(int i = 0; i < arg_count; i++) {
      args[i] = env->get_object(va_arg(varargs, VALUE));
    }

    va_end(varargs);

    Object* blk = cNil;

    if(VALUE blk_handle = env->outgoing_block()) {
      blk = env->get_object(blk_handle);
      env->set_outgoing_block(0);
    }

    return capi_funcall_backend_native(env, "", 0,
        env->get_object(receiver),
        reinterpret_cast<Symbol*>(method_name),
        arg_count, args, blk);
  }

  VALUE rb_funcall2(VALUE receiver, ID method_name, int arg_count, const VALUE* v_args) {
    NativeMethodEnvironment* env = NativeMethodEnvironment::get();

    Object** args = reinterpret_cast<Object**>(alloca(sizeof(Object**) * arg_count));

    for(int i = 0; i < arg_count; i++) {
      args[i] = env->get_object(v_args[i]);
    }

    Object* blk = cNil;

    if(VALUE blk_handle = env->outgoing_block()) {
      blk = env->get_object(blk_handle);
      env->set_outgoing_block(0);
    }

    return capi_funcall_backend_native(env, "", 0,
        env->get_object(receiver),
        reinterpret_cast<Symbol*>(method_name),
        arg_count, args, blk);
  }

  VALUE rb_funcall2b(VALUE receiver, ID method_name, int arg_count,
                     const VALUE* v_args, VALUE block)
  {
    NativeMethodEnvironment* env = NativeMethodEnvironment::get();

    Object** args = reinterpret_cast<Object**>(alloca(sizeof(Object**) * arg_count));

    for(int i = 0; i < arg_count; i++) {
      args[i] = env->get_object(v_args[i]);
    }

    return capi_funcall_backend_native(env, "", 0,
        env->get_object(receiver),
        reinterpret_cast<Symbol*>(method_name),
        arg_count, args, env->get_object(block));
  }

  VALUE rb_yield(VALUE argument_handle) {
    NativeMethodEnvironment* env = NativeMethodEnvironment::get();

    Object* blk = env->block();

    if(!CBOOL(blk)) {
      rb_raise(rb_eLocalJumpError, "no block given", 0);
    }

    Object* arg = env->get_object(argument_handle);

    return capi_yield_backend(env, blk, 1, &arg);
  }

  VALUE rb_yield_values(int n, ...) {
    NativeMethodEnvironment* env = NativeMethodEnvironment::get();

    Object* blk = env->block();

    if(!CBOOL(blk)) {
      rb_raise(rb_eLocalJumpError, "no block given", 0);
    }

    if(n == 0) {
      return capi_yield_backend(env, blk, 0, 0);
    }

    Object** vars = reinterpret_cast<Object**>(alloca(sizeof(Object*) * n));

    va_list args;
    va_start(args, n);

    for(int i = 0; i < n; ++i) {
      vars[i] = env->get_object(va_arg(args, VALUE));
    }

    va_end(args);

    return capi_yield_backend(env, blk, n, vars);
  }

  VALUE rb_yield_splat(VALUE array_handle) {
    NativeMethodEnvironment* env = NativeMethodEnvironment::get();

    Object* blk = env->block();

    if(!CBOOL(blk)) {
      rb_raise(rb_eLocalJumpError, "no block given", 0);
    }

    if(Array* ary = try_as<Array>(env->get_object(array_handle))) {
      int count = ary->size();
      Object** vars = reinterpret_cast<Object**>(alloca(sizeof(Object*) * count));

      for(int i = 0; i < count; i++) {
        vars[i] = ary->get(env->state(), i);
      }

      return capi_yield_backend(env, blk, count, vars);
    }

    return capi_yield_backend(env, blk, 0, 0);
  }

  int rb_block_given_p() {
    NativeMethodEnvironment* env = NativeMethodEnvironment::get();
    return CBOOL(env->block());
  }

  void rb_need_block() {
    if (!rb_block_given_p()) {
      rb_raise(rb_eLocalJumpError, "no block given", 0);
    }
  }

  VALUE rb_block_call(VALUE obj, ID meth, int argc, VALUE* argv,
                      VALUE(*cb)(ANYARGS), VALUE cb_data) {
    NativeMethodEnvironment* env = NativeMethodEnvironment::get();

    if(cb) {
      Proc* prc = capi::wrap_c_function((void*)cb, cb_data, C_BLOCK_CALL);
      env->set_outgoing_block(env->get_handle(prc));
    } else {
      env->set_outgoing_block(env->get_handle(env->block()));
    }

    return rb_funcall2(obj, meth, argc, argv);
  }

  VALUE rb_apply(VALUE recv, ID mid, VALUE args) {
    NativeMethodEnvironment* env = NativeMethodEnvironment::get();
    env->flush_cached_data();

    Array* ary = capi::c_as<Array>(env->get_object(args));

    Object* obj = env->get_object(recv);

    // Unlock, we're leaving extension code.
    LEAVE_CAPI(env->state());

    Object* ret = obj->send(env->state(), env->current_call_frame(),
        reinterpret_cast<Symbol*>(mid), ary, cNil);

    // We need to get the handle for the return value before getting
    // the GEL so that ret isn't accidentally GCd while we wait.
    VALUE ret_handle = 0;
    if(ret) ret_handle = env->get_handle(ret);

    // Re-entering extension code
    ENTER_CAPI(env->state());

    env->update_cached_data();

    // An exception occurred
    if(!ret) env->current_ep()->return_to(env);

    return ret_handle;
  }


  void capi_infect(VALUE h, VALUE s) {
    NativeMethodEnvironment* env = NativeMethodEnvironment::get();

    Object* host = env->get_object(h);
    Object* source = env->get_object(s);

    source->infect(env->state(), host);
  }

  int capi_nil_p(VALUE expression_result) {
    NativeMethodEnvironment* env = NativeMethodEnvironment::get();

    return env->get_object(expression_result)->nil_p();
  }

  void capi_taint(VALUE obj) {
    NativeMethodEnvironment* env = NativeMethodEnvironment::get();

    env->get_object(obj)->taint(env->state());
  }

  int rb_obj_tainted(VALUE obj) {
    NativeMethodEnvironment* env = NativeMethodEnvironment::get();

    Object* tainted = env->get_object(obj)->tainted_p(env->state());

    return tainted->true_p() ? 1 : 0;
  }

  void capi_define_method(const char* file, VALUE target,
                          const char* name, CApiGenericFunction fptr,
                          int arity, CApiMethodKind kind)
  {
    NativeMethodEnvironment* env = NativeMethodEnvironment::get();

    State* state = env->state();
    Symbol* method_name = state->symbol(name);

    Module* module = NULL;

    if(kind == cCApiSingletonMethod) {
      module = c_as<Module>(env->get_object(target)->singleton_class(env->state()));
    } else {
      module = c_as<Module>(env->get_object(target));
    }

    NativeMethod* method = NULL;
    method = NativeMethod::create(state, String::create(state, file),
                                  module, method_name,
                                  (void*)fptr, Fixnum::from(arity));

    Symbol* visibility;

    switch(kind) {
    case cCApiPrivateMethod:
      visibility = state->symbol("private");
      break;

    case cCApiProtectedMethod:
      visibility = state->symbol("protected");
      break;

    default: /* Also catches singletons for now. @todo Verify OK. --rue */
      visibility = state->symbol("public");
      break;
    }

    GCTokenImpl gct;
    module->add_method(state, gct, method_name, method, visibility);
  }

  VALUE capi_class_superclass(VALUE class_handle) {
    NativeMethodEnvironment* env = NativeMethodEnvironment::get();

    Module* module = c_as<Module>(env->get_object(class_handle));
    Module* super = module->superclass();

    if(super->nil_p()) {
      /* In MRI, the superclass chain terminates with a NULL pointer.
* Since VALUE is an intptr_t in Rubinius, we use 0 instead.
*/
      return 0;
    } else {
      return env->get_handle(super);
    }
  }

  /* For debugging. */
  void __show_subtend__(VALUE obj_handle) {
    NativeMethodEnvironment* env = NativeMethodEnvironment::get();

    Object* object = env->get_object(obj_handle);
    if(!object) {
      std::cout << "the object is NULL, check if an exception was raised." << std::endl;
      return;
    }
    object->show(env->state());
  }
}
Something went wrong with that request. Please try again.