Example #1
0
 /** match_post_match */
 @JRubyMethod(name = "post_match")
 public IRubyObject post_match(ThreadContext context) {
   check();
   if (begin == -1) return context.getRuntime().getNil();
   return makeShared(context.getRuntime(), str, end, str.getByteList().length() - end)
       .infectBy(this);
 }
  @Override
  public Object interpret(
      ThreadContext context,
      DynamicScope currDynScope,
      IRubyObject self,
      Object[] temp,
      Block block) {
    // SSS FIXME: This is ugly and needs fixing.  Is there another way of capturing this info?
    RubyModule containerModule =
        (candidateScope == null) ? null : candidateScope.getStaticScope().getModule();
    if (containerModule == null)
      containerModule = ASTInterpreter.getClassVariableBase(context, context.getRuntime());
    if (containerModule == null && object != null) {
      IRubyObject arg = (IRubyObject) object.retrieve(context, self, currDynScope, temp);
      // SSS: What is the right thing to do here?
      containerModule =
          arg
              .getMetaClass(); // (arg instanceof RubyClass) ? ((RubyClass)arg).getRealClass() :
                               // arg.getType();
    }

    if (containerModule == null)
      throw context.getRuntime().newTypeError("no class/module to define class variable");

    return containerModule;
  }
Example #3
0
  @JRubyMethod(
      name = {"call", "[]", "yield"},
      rest = true,
      frame = true,
      compat = CompatVersion.RUBY1_9)
  public IRubyObject call19(ThreadContext context, IRubyObject[] args, Block block) {
    if (isLambda()) {
      this.block.arity().checkArity(context.getRuntime(), args.length);
    }

    if (isProc()) {
      List<IRubyObject> list = new ArrayList<IRubyObject>(Arrays.asList(args));
      int required = this.block.arity().required();
      if (this.block.arity().isFixed()) {
        if (required > args.length) {
          for (int i = args.length; i < required; i++) {
            list.add(context.getRuntime().getNil());
          }
          args = list.toArray(args);
        } else if (required < args.length) {
          args = list.subList(0, required).toArray(args);
        }
      }
    }

    return call(context, args, null, block);
  }
Example #4
0
    @JRubyMethod(required = 4)
    public IRubyObject initialize(ThreadContext context, IRubyObject[] args) {
      if (!(args[2] instanceof MappedType)) {
        throw context
            .getRuntime()
            .newTypeError(
                args[2],
                context
                    .getRuntime()
                    .fastGetModule("FFI")
                    .fastGetClass("Type")
                    .fastGetClass("Mapped"));
      }

      if (!(args[3] instanceof Field)) {
        throw context
            .getRuntime()
            .newTypeError(
                args[3],
                context
                    .getRuntime()
                    .fastGetModule("FFI")
                    .fastGetClass("StructLayout")
                    .fastGetClass("Field"));
      }

      init(
          args[0],
          args[2],
          args[1],
          new MappedFieldIO((MappedType) args[2], ((Field) args[3]).getFieldIO()));

      return this;
    }
Example #5
0
 @JRubyMethod(
     name = {"create_invoker", "createInvoker"},
     required = 5)
 public IRubyObject createInvoker(ThreadContext context, IRubyObject[] args) {
   RubyArray paramTypes = (RubyArray) args[3];
   NativeParam[] nativeParamTypes = new NativeParam[paramTypes.size()];
   for (int i = 0; i < paramTypes.size(); ++i) {
     IRubyObject obj = (IRubyObject) paramTypes.entry(i);
     if (obj instanceof NativeParam) {
       nativeParamTypes[i] = (NativeParam) obj;
     } else if (obj instanceof RubyInteger) {
       nativeParamTypes[i] = NativeType.valueOf(Util.int32Value(obj));
     } else {
       context.getRuntime().newArgumentError("Invalid parameter type");
     }
   }
   try {
     return createInvoker(
         context.getRuntime(),
         args[0].isNil() ? null : args[0].toString(),
         args[1].toString(),
         NativeType.valueOf(Util.int32Value(args[2])),
         nativeParamTypes,
         args[4].toString());
   } catch (UnsatisfiedLinkError ex) {
     return context.getRuntime().getNil();
   }
 }
Example #6
0
    public final void marshal(
        ThreadContext context, InvocationBuffer buffer, IRubyObject parameter) {
      if (!(parameter instanceof Struct)) {
        throw context
            .getRuntime()
            .newTypeError(
                "wrong argument type "
                    + parameter.getMetaClass().getName()
                    + " (expected instance of FFI::Struct)");
      }

      IRubyObject memory = ((Struct) parameter).getMemory();
      if (!(memory instanceof AbstractMemory)) {
        throw context
            .getRuntime()
            .newTypeError("wrong struct memory type " + memory.getMetaClass().getName());
      }

      MemoryIO io = ((AbstractMemory) memory).getMemoryIO();
      if (io instanceof DirectMemoryIO) {
        if (io.isNull()) {
          throw context
              .getRuntime()
              .newRuntimeError("Cannot use a NULL pointer as a struct by value argument");
        }
        buffer.putStruct(((DirectMemoryIO) io).getAddress());
      } else if (io instanceof ArrayMemoryIO) {
        ArrayMemoryIO aio = (ArrayMemoryIO) io;
        buffer.putStruct(aio.array(), aio.arrayOffset());
      } else {
        throw context.getRuntime().newRuntimeError("Invalid struct memory");
      }
    }
Example #7
0
  @JRubyMethod(name = "root=")
  public IRubyObject root_set(ThreadContext context, IRubyObject newRoot_) {
    // in case of document fragment, temporary root node should be deleted.

    // Java can't have a root whose value is null. Instead of setting null,
    // the method sets user data so that other methods are able to know the root
    // should be nil.
    if (newRoot_ instanceof RubyNil) {
      getDocument().getDocumentElement().setUserData(NokogiriHelpers.VALID_ROOT_NODE, false, null);
      return newRoot_;
    }
    XmlNode newRoot = asXmlNode(context, newRoot_);

    IRubyObject root = root(context);
    if (root.isNil()) {
      Node newRootNode;
      if (getDocument() == newRoot.getOwnerDocument()) {
        newRootNode = newRoot.node;
      } else {
        // must copy otherwise newRoot may exist in two places
        // with different owner document.
        newRootNode = getDocument().importNode(newRoot.node, true);
      }
      add_child_node(context, getCachedNodeOrCreate(context.getRuntime(), newRootNode));
    } else {
      Node rootNode = asXmlNode(context, root).node;
      ((XmlNode) getCachedNodeOrCreate(context.getRuntime(), rootNode))
          .replace_node(context, newRoot);
    }

    return newRoot;
  }
Example #8
0
    public void put(
        ThreadContext context,
        StructLayout.Storage cache,
        Member m,
        IRubyObject ptr,
        IRubyObject value) {
      if (value instanceof Pointer) {
        m.getMemoryIO(ptr).putMemoryIO(m.offset, ((Pointer) value).getMemoryIO());
      } else if (value instanceof Struct) {
        MemoryIO mem = ((Struct) value).getMemoryIO();

        if (!(mem instanceof DirectMemoryIO)) {
          throw context
              .getRuntime()
              .newArgumentError("Struct memory not backed by a native pointer");
        }
        m.getMemoryIO(ptr).putMemoryIO(m.offset, mem);

      } else if (value instanceof RubyInteger) {
        m.getMemoryIO(ptr).putAddress(m.offset, Util.int64Value(ptr));
      } else if (value.respondsTo("to_ptr")) {
        IRubyObject addr = value.callMethod(context, "to_ptr");
        if (addr instanceof Pointer) {
          m.getMemoryIO(ptr).putMemoryIO(m.offset, ((Pointer) addr).getMemoryIO());
        } else {
          throw context.getRuntime().newArgumentError("Invalid pointer value");
        }
      } else if (value.isNil()) {
        m.getMemoryIO(ptr).putAddress(m.offset, 0L);
      } else {
        throw context.getRuntime().newArgumentError("Invalid pointer value");
      }
      cache.putReference(m, value);
    }
Example #9
0
 @JRubyMethod(name = {"getpeername", "__getpeername"})
 public IRubyObject getpeername(ThreadContext context) {
   SocketAddress sock = getRemoteSocket();
   if (null == sock) {
     throw context.getRuntime().newIOError("Not Supported");
   }
   return context.getRuntime().newString(sock.toString());
 }
Example #10
0
 public final IRubyObject invoke(
     ThreadContext context, Function function, HeapInvocationBuffer args) {
   final long address = invoker.invokeAddress(function, args);
   return RubyArray.newArray(
       context.getRuntime(),
       FFIUtil.getString(context.getRuntime(), address),
       new Pointer(context.getRuntime(), NativeMemoryIO.wrap(context.getRuntime(), address)));
 }
Example #11
0
  @JRubyMethod(name = "<=>", required = 1)
  public IRubyObject op_cmp(ThreadContext context, IRubyObject other) {
    if (other instanceof RubyTime) {
      return context.getRuntime().newFixnum(cmp((RubyTime) other));
    }

    return context.getRuntime().getNil();
  }
Example #12
0
 /** int_succ */
 @JRubyMethod(name = {"succ", "next"})
 public IRubyObject succ(ThreadContext context) {
   if (this instanceof RubyFixnum) {
     return RubyFixnum.newFixnum(context.getRuntime(), getLongValue() + 1L);
   } else {
     return callMethod(context, "+", RubyFixnum.one(context.getRuntime()));
   }
 }
Example #13
0
 public static IRubyObject retryJumpError(ThreadContext context) {
   throw context
       .getRuntime()
       .newLocalJumpError(
           RubyLocalJumpError.Reason.RETRY,
           context.getRuntime().getNil(),
           "retry outside of rescue not supported");
 }
Example #14
0
  @JRubyMethod(name = {"size", "length"})
  public IRubyObject size(ThreadContext context) {
    if (!isClosed()) {
      flush();
      return context.getRuntime().newFileStat(path, false).size();
    }

    return RubyFixnum.zero(context.getRuntime());
  }
Example #15
0
    public IRubyObject get(
        ThreadContext context, StructLayout.Storage cache, Member m, IRubyObject ptr) {
      MemoryIO io = m.getMemoryIO(ptr).getMemoryIO(m.getOffset(ptr));
      if (io == null || io.isNull()) {
        return context.getRuntime().getNil();
      }

      return RubyString.newStringNoCopy(context.getRuntime(), io.getZeroTerminatedByteArray(0));
    }
Example #16
0
 @JRubyMethod(meta = true)
 public static IRubyObject decode(ThreadContext ctx, IRubyObject recv, IRubyObject data) {
   try {
     byte[] bytes = data.convertToString().getBytes();
     byte[] decoded = Hex.decode(bytes);
     return ctx.getRuntime().newString(new ByteList(decoded, false));
   } catch (RuntimeException ex) {
     throw Errors.newHexError(ctx.getRuntime(), ex.getMessage());
   }
 }
Example #17
0
 /** Needed for Enumerable implementation */
 @JRubyMethod(name = "each")
 public IRubyObject each(ThreadContext context, Block block) {
   if (!block.isGiven()) {
     throw context.getRuntime().newLocalJumpErrorNoBlock();
   }
   for (int i = 0; i < arrayType.length(); ++i) {
     block.yield(context, get(context.getRuntime(), i));
   }
   return this;
 }
Example #18
0
 @Override
 public IRubyObject get(ThreadContext context, IRubyObject rbkey) {
   String key = rubyStringToString(rbkey);
   Element element = (Element) node;
   String value = element.getAttribute(key);
   if (!value.equals("")) {
     return context.getRuntime().newString(value);
   }
   return context.getRuntime().getNil();
 }
Example #19
0
  private static IRubyObject jacobToRuby(ThreadContext context, Variant value) {
    if (value == null || value.isNull()) return context.getRuntime().getNil();

    Object object = value.toJavaObject();
    if (object instanceof Dispatch)
      return new WIN32OLE(
          context.getRuntime(), context.getRuntime().getClass("WIN32OLE"), (Dispatch) object);
    else if (object instanceof SafeArray) return safeArrayToRubyArray(context, (SafeArray) object);

    return JavaUtil.convertJavaToRuby(context.getRuntime(), object);
  }
Example #20
0
 private void checkOpCoercion(ThreadContext context, IRubyObject other) {
   if (other instanceof RubyString) {
     throw context.getRuntime().newTypeError("no implicit conversion to rational from string");
   } else if (other.isNil()) {
     throw context.getRuntime().newTypeError("no implicit conversion to rational from nil");
   } else if (!other.respondsTo("to_r")) {
     throw context
         .getRuntime()
         .newTypeError("can't convert " + other.getMetaClass().getBaseName() + " into Rational");
   }
 }
Example #21
0
 void call(ThreadContext context, IRubyObject arg) {
   if (iter instanceof RubyFixnum) {
     iter = RubyFixnum.newFixnum(context.getRuntime(), ((RubyFixnum) iter).getLongValue() - 1);
   } else {
     iter = iter.callMethod(context, "-", RubyFixnum.one(context.getRuntime()));
   }
   if (iter == RubyFixnum.zero(context.getRuntime())) {
     block.yield(context, arg);
     iter = step;
   }
 }
Example #22
0
 private static Buffer allocate(
     ThreadContext context, IRubyObject recv, IRubyObject sizeArg, int count, int flags) {
   final int typeSize = calculateSize(context, sizeArg);
   final int total = typeSize * count;
   return new Buffer(
       context.getRuntime(),
       recv,
       new ArrayMemoryIO(context.getRuntime(), total),
       total,
       typeSize,
       flags);
 }
Example #23
0
 @Override
 @JRubyMethod(visibility = Visibility.PRIVATE)
 public IRubyObject get(ThreadContext context, IRubyObject rbkey) {
   if (rbkey == null || rbkey.isNil()) context.getRuntime().getNil();
   String key = rubyStringToString(rbkey);
   Element element = (Element) node;
   String value = element.getAttribute(key);
   if (!value.equals("")) {
     return context.getRuntime().newString(value);
   }
   return context.getRuntime().getNil();
 }
Example #24
0
  @JRubyMethod
  public IRubyObject encoding(ThreadContext context) {
    if (this.encoding == null) {
      if (getDocument().getXmlEncoding() == null) {
        this.encoding = context.getRuntime().getNil();
      } else {
        this.encoding = context.getRuntime().newString(getDocument().getXmlEncoding());
      }
    }

    return this.encoding;
  }
Example #25
0
  @JRubyMethod(optional = 1)
  public IRubyObject shutdown(ThreadContext context, IRubyObject[] args) {
    if (context.getRuntime().getSafeLevel() >= 4 && tainted_p(context).isFalse()) {
      throw context.getRuntime().newSecurityError("Insecure: can't shutdown socket");
    }

    int how = 2;
    if (args.length > 0) {
      how = RubyNumeric.fix2int(args[0]);
    }
    return shutdownInternal(context, how);
  }
Example #26
0
  public IRubyObject getInternalSubset(ThreadContext context) {
    IRubyObject dtd = (IRubyObject) node.getUserData(DTD_INTERNAL_SUBSET);

    if (dtd == null) {
      if (getDocument().getDoctype() == null) dtd = context.getRuntime().getNil();
      else dtd = XmlDtd.newFromInternalSubset(context.getRuntime(), getDocument());

      setInternalSubset(dtd);
    }

    return dtd;
  }
Example #27
0
  // Look through all mappings to find a match entry for this field
  private static void installField(
      ThreadContext context,
      Map<String, String> fieldMap,
      Field field,
      RubyModule module,
      boolean asReader,
      boolean asWriter) {
    boolean isFinal = Modifier.isFinal(field.getModifiers());

    for (Iterator<Map.Entry<String, String>> iter = fieldMap.entrySet().iterator();
        iter.hasNext(); ) {
      Map.Entry<String, String> entry = iter.next();
      String key = entry.getKey();
      if (key.equals(field.getName())) {
        if (Ruby.isSecurityRestricted() && !Modifier.isPublic(field.getModifiers())) {
          throw context
              .getRuntime()
              .newSecurityError(
                  "Cannot change accessibility on fields in a restricted mode: field '"
                      + field.getName()
                      + "'");
        }

        String asName = entry.getValue();

        if (Modifier.isStatic(field.getModifiers())) {
          if (asReader)
            module.getSingletonClass().addMethod(asName, new StaticFieldGetter(key, module, field));
          if (asWriter) {
            if (isFinal)
              throw context
                  .getRuntime()
                  .newSecurityError("Cannot change final field '" + field.getName() + "'");
            module
                .getSingletonClass()
                .addMethod(asName + "=", new StaticFieldSetter(key, module, field));
          }
        } else {
          if (asReader) module.addMethod(asName, new InstanceFieldGetter(key, module, field));
          if (asWriter) {
            if (isFinal)
              throw context
                  .getRuntime()
                  .newSecurityError("Cannot change final field '" + field.getName() + "'");
            module.addMethod(asName + "=", new InstanceFieldSetter(key, module, field));
          }
        }

        iter.remove();
        break;
      }
    }
  }
Example #28
0
  @JRubyMethod
  public IRubyObject getsockopt(ThreadContext context, IRubyObject lev, IRubyObject optname) {
    int level = RubyNumeric.fix2int(lev);
    int opt = RubyNumeric.fix2int(optname);
    Ruby runtime = context.getRuntime();

    try {
      switch (SocketLevel.valueOf(level)) {
        case SOL_IP:
        case SOL_SOCKET:
        case SOL_TCP:
        case SOL_UDP:
          switch (SocketOption.valueOf(opt)) {
            case SO_BROADCAST:
              return getBroadcast(runtime);
            case SO_KEEPALIVE:
              return getKeepAlive(runtime);
            case SO_LINGER:
              return getLinger(runtime);
            case SO_OOBINLINE:
              return getOOBInline(runtime);
            case SO_RCVBUF:
              return getRcvBuf(runtime);
            case SO_REUSEADDR:
              return getReuseAddr(runtime);
            case SO_SNDBUF:
              return getSndBuf(runtime);
            case SO_RCVTIMEO:
            case SO_SNDTIMEO:
              return getTimeout(runtime);
            case SO_TYPE:
              return getSoType(runtime);

              // Can't support the rest with Java
            case SO_RCVLOWAT:
              return number(runtime, 1);
            case SO_SNDLOWAT:
              return number(runtime, 2048);
            case SO_DEBUG:
            case SO_ERROR:
            case SO_DONTROUTE:
            case SO_TIMESTAMP:
              return trueFalse(runtime, false);
            default:
              throw context.getRuntime().newErrnoENOPROTOOPTError();
          }
        default:
          throw context.getRuntime().newErrnoENOPROTOOPTError();
      }
    } catch (IOException e) {
      throw context.getRuntime().newErrnoENOPROTOOPTError();
    }
  }
Example #29
0
 @JRubyMethod
 public IRubyObject root(ThreadContext context) {
   Node rootNode = getDocument().getDocumentElement();
   try {
     Boolean isValid = (Boolean) rootNode.getUserData(NokogiriHelpers.VALID_ROOT_NODE);
     if (!isValid) return context.getRuntime().getNil();
   } catch (NullPointerException e) {
     // does nothing since nil wasn't set to the root node before.
   }
   if (rootNode == null) return context.getRuntime().getNil();
   else return getCachedNodeOrCreate(context.getRuntime(), rootNode);
 }
Example #30
0
 public final void marshal(
     ThreadContext context, InvocationBuffer buffer, IRubyObject parameter) {
   if (parameter instanceof RubyString) {
     Util.checkStringSafety(context.getRuntime(), parameter);
     ByteList bl = ((RubyString) parameter).getByteList();
     buffer.putArray(
         bl.unsafeBytes(), bl.begin(), bl.length(), ArrayFlags.IN | ArrayFlags.NULTERMINATE);
   } else if (parameter.isNil()) {
     buffer.putAddress(0);
   } else {
     throw context.getRuntime().newArgumentError("Invalid string parameter");
   }
 }