Esempio n. 1
0
  public static void createTemplate(Ruby runtime, RubyModule mASN1) {
    mTemplate = runtime.defineModuleUnder("Template", mASN1);
    RubyModule mParser = runtime.defineModuleUnder("Parser", mTemplate);
    cTemplateValue =
        mTemplate.defineClassUnder(
            "Value", runtime.getObject(), ObjectAllocator.NOT_ALLOCATABLE_ALLOCATOR);

    CODEC = runtime.newSymbol("codec");
    OPTIONS = runtime.newSymbol("options");
    DEFAULT = runtime.newSymbol("default");
    NAME = runtime.newSymbol("name");
    TYPE = runtime.newSymbol("type");
    OPTIONAL = runtime.newSymbol("optional");
    TAG = runtime.newSymbol("tag");
    TAGGING = runtime.newSymbol("tagging");
    LAYOUT = runtime.newSymbol("layout");
    MIN_SIZE = runtime.newSymbol("min_size");

    CODEC_PRIMITIVE = runtime.newSymbol("PRIMITIVE");
    CODEC_TEMPLATE = runtime.newSymbol("TEMPLATE");
    CODEC_SEQUENCE = runtime.newSymbol("SEQUENCE");
    CODEC_SET = runtime.newSymbol("SET");
    CODEC_SEQUENCE_OF = runtime.newSymbol("SEQUENCE_OF");
    CODEC_SET_OF = runtime.newSymbol("SET_OF");
    CODEC_ANY = runtime.newSymbol("ANY");
    CODEC_CHOICE = runtime.newSymbol("CHOICE");

    mTemplate.defineAnnotatedMethods(RubyAsn1Template.class);
    mParser.defineAnnotatedMethods(TemplateParser.class);
    cTemplateValue.defineAnnotatedMethods(RubyAsn1Template.class);
  }
Esempio n. 2
0
  private static void findFields(
      ThreadContext context,
      RubyModule topModule,
      IRubyObject args[],
      boolean asReader,
      boolean asWriter) {
    Map<String, String> fieldMap = getFieldListFromArgs(args);

    for (RubyModule module = topModule; module != null; module = module.getSuperClass()) {
      Class<?> javaClass = getJavaClass(context, module);

      // Hit a non-java proxy class (included Modules can be a cause of this...skip)
      if (javaClass == null) continue;

      Field[] fields = JavaClass.getDeclaredFields(javaClass);
      for (int j = 0; j < fields.length; j++) {
        installField(context, fieldMap, fields[j], module, asReader, asWriter);
      }
    }

    // We could not find all of them print out first one (we could print them all?)
    if (!fieldMap.isEmpty()) {
      throw JavaClass.undefinedFieldError(
          context.getRuntime(), topModule.getName(), fieldMap.keySet().iterator().next());
    }
  }
Esempio n. 3
0
  public static void createPKeyDSA(Ruby runtime, RubyModule mPKey) {
    RubyClass cDSA = mPKey.defineClassUnder("DSA", mPKey.getClass("PKey"), PKEYDSA_ALLOCATOR);
    RubyClass pkeyError = mPKey.getClass("PKeyError");
    mPKey.defineClassUnder("DSAError", pkeyError, pkeyError.getAllocator());

    cDSA.defineAnnotatedMethods(PKeyDSA.class);
  }
Esempio n. 4
0
  public void load(Ruby runtime, boolean wrap) throws IOException {
    RubyModule timeout = runtime.defineModule("Timeout");
    RubyClass superclass = runtime.getRuntimeError();
    RubyClass timeoutError =
        runtime.defineClassUnder("Error", superclass, superclass.getAllocator(), timeout);
    runtime.defineClassUnder(
        "ExitException", runtime.getException(), runtime.getException().getAllocator(), timeout);

    // Here we create an "anonymous" exception type used for unrolling the stack.
    // MRI creates a new one for *every call* to timeout, which can be costly.
    // We opt to use a single exception type for all cases to avoid this overhead.
    RubyClass anonEx =
        runtime.defineClassUnder(
            "AnonymousException",
            runtime.getException(),
            runtime.getException().getAllocator(),
            timeout);
    anonEx.setBaseName(null); // clear basename so it's anonymous when raising

    // These are not really used by timeout, but exposed for compatibility
    timeout.defineConstant(
        "THIS_FILE", RubyRegexp.newRegexp(runtime, "timeout\\.rb", new RegexpOptions()));
    timeout.defineConstant("CALLER_OFFSET", RubyFixnum.newFixnum(runtime, 0));

    // Timeout module methods
    timeout.defineAnnotatedMethods(Timeout.class);

    // Toplevel defines
    runtime.getObject().defineConstant("TimeoutError", timeoutError);
    runtime.getObject().defineAnnotatedMethods(TimeoutToplevel.class);
  }
 private Object cache(
     ThreadContext context,
     DynamicScope currDynScope,
     IRubyObject self,
     Object[] temp,
     Ruby runtime,
     Object constant) {
   StaticScope staticScope =
       (StaticScope) definingScope.retrieve(context, self, currDynScope, temp);
   RubyModule object = runtime.getObject();
   // SSS FIXME: IRManager objects dont have a static-scope yet, so this hack of looking up the
   // module right away
   // This IR needs fixing!
   constant =
       (staticScope == null)
           ? object.getConstant(constName)
           : staticScope.getConstantInner(runtime, constName, object);
   if (constant == null) {
     constant = UndefinedValue.UNDEFINED;
   } else {
     // recache
     generation = runtime.getConstantInvalidator().getData();
     cachedConstant = constant;
   }
   return constant;
 }
Esempio n. 6
0
  public static RubyClass createPointerClass(Ruby runtime, RubyModule module) {
    RubyClass pointerClass =
        module.defineClassUnder(
            "Pointer",
            module.getClass(AbstractMemory.ABSTRACT_MEMORY_RUBY_CLASS),
            RubyInstanceConfig.REIFY_RUBY_CLASSES
                ? new ReifyingAllocator(Pointer.class)
                : PointerAllocator.INSTANCE);

    pointerClass.defineAnnotatedMethods(Pointer.class);
    pointerClass.defineAnnotatedConstants(Pointer.class);
    pointerClass.setReifiedClass(Pointer.class);
    pointerClass.kindOf =
        new RubyModule.KindOf() {
          @Override
          public boolean isKindOf(IRubyObject obj, RubyModule type) {
            return obj instanceof Pointer && super.isKindOf(obj, type);
          }
        };

    module.defineClassUnder(
        "NullPointerError", runtime.getRuntimeError(), runtime.getRuntimeError().getAllocator());

    // Add Pointer::NULL as a constant
    Pointer nullPointer = new Pointer(runtime, pointerClass, new NullMemoryIO(runtime));
    pointerClass.setConstant("NULL", nullPointer);

    runtime
        .getNilClass()
        .addMethod("to_ptr", new NilToPointerMethod(runtime.getNilClass(), nullPointer));

    return pointerClass;
  }
Esempio n. 7
0
  public static void createX509CRL(Ruby runtime, RubyModule mX509) {
    RubyClass cX509CRL = mX509.defineClassUnder("CRL", runtime.getObject(), X509CRL_ALLOCATOR);
    RubyClass openSSLError = runtime.getModule("OpenSSL").getClass("OpenSSLError");
    mX509.defineClassUnder("CRLError", openSSLError, openSSLError.getAllocator());

    cX509CRL.defineAnnotatedMethods(X509CRL.class);
  }
  @Override
  public IRubyObject interpret(
      Ruby runtime, ThreadContext context, IRubyObject self, Block aBlock) {
    RubyModule target = Helpers.checkIsModule(leftNode.interpret(runtime, context, self, aBlock));
    IRubyObject value = getValue(context, target);

    return value != null ? value : target.getConstantFromConstMissing(name);
  }
Esempio n. 9
0
 public static void createConfig(Ruby runtime, RubyModule mOSSL) {
   RubyClass cConfig =
       mOSSL.defineClassUnder("Config", runtime.getObject(), runtime.getObject().getAllocator());
   cConfig.defineAnnotatedMethods(Config.class);
   RubyClass openSSLError = mOSSL.getClass("OpenSSLError");
   mOSSL.defineClassUnder("ConfigError", openSSLError, openSSLError.getAllocator());
   // TODO: we should define this constant with proper path. (see above)
   // cConfig.setConstant("DEFAULT_CONFIG_FILE", runtime.newString(DEFAULT_CONFIG_FILE));
 }
Esempio n. 10
0
    @JRubyMethod(name = "inspect")
    @Override
    public IRubyObject inspect() {
      RubyModule rubyClass = getMetaClass();
      StringBuilder buffer = new StringBuilder("#<");
      buffer.append(rubyClass.getName()).append(": ").append(success.inspect().toString());
      buffer.append(", ").append(failed.inspect().toString()).append(">");

      return getRuntime().newString(buffer.toString());
    }
Esempio n. 11
0
  /**
   * @param runtime
   * @param driver
   * @return
   */
  public static RubyClass createResultClass(final Ruby runtime, DriverDefinition driver) {
    RubyModule doModule = runtime.getModule(DATA_OBJECTS_MODULE_NAME);
    RubyClass superClass = doModule.getClass(RUBY_CLASS_NAME);
    RubyModule driverModule = (RubyModule) doModule.getConstant(driver.getModuleName());
    RubyClass resultClass =
        driverModule.defineClassUnder(RUBY_CLASS_NAME, superClass, RESULT_ALLOCATOR);

    resultClass.defineAnnotatedMethods(Result.class);
    return resultClass;
  }
Esempio n. 12
0
  /**
   * Used by the evaluator and the compiler to set a constant by name. This is for a Colon2 const
   * decl
   */
  public IRubyObject setConstantInModule(
      String internedName, IRubyObject target, IRubyObject result) {
    if (!(target instanceof RubyModule)) {
      throw runtime.newTypeError(target.toString() + " is not a class/module");
    }
    RubyModule module = (RubyModule) target;
    module.fastSetConstant(internedName, result);

    return result;
  }
Esempio n. 13
0
 public IRubyObject reCacheFrom(RubyModule target, ThreadContext context, String name, int index) {
   int newGeneration = context.getRuntime().getConstantGeneration();
   IRubyObject value = target.fastGetConstantFromNoConstMissing(name);
   constants[index] = value;
   if (value != null) {
     constantGenerations[index] = newGeneration;
     constantTargetHashes[index] = target.hashCode();
   }
   return value;
 }
Esempio n. 14
0
  public static void create(Ruby runtime) {
    RubyModule mNet = runtime.getModule("Net");

    RubyClass cBufferedIO = (RubyClass) mNet.getConstant("BufferedIO");
    cBufferedIO.defineAnnotatedMethods(NetProtocolBufferedIO.class);

    RubyModule mNativeImpl = cBufferedIO.defineModuleUnder("NativeImplementation");

    mNativeImpl.defineAnnotatedMethods(NativeImpl.class);
  }
Esempio n. 15
0
  /**
   * Calculate, based on given RubyModule, which class in its hierarchy should be used to determine
   * protected access.
   *
   * @param cls The class from which to calculate
   * @return The class to be used for protected access checking.
   */
  protected static RubyModule calculateProtectedClass(RubyModule cls) {
    // singleton classes don't get their own visibility domain
    if (cls.isSingleton()) cls = cls.getSuperClass();

    while (cls.isIncluded()) cls = cls.getMetaClass();

    // For visibility we need real meta class and not anonymous one from class << self
    if (cls instanceof MetaClass) cls = ((MetaClass) cls).getRealClass();

    return cls;
  }
Esempio n. 16
0
 @Override
 public Object interpret(
     ThreadContext context,
     DynamicScope currDynScope,
     IRubyObject self,
     Object[] temp,
     Block block) {
   RubyModule module = (RubyModule) receiver.retrieve(context, self, currDynScope, temp);
   return module.callMethod(
       context, "const_missing", context.getRuntime().fastNewSymbol(missingConst));
 }
Esempio n. 17
0
  /**
   * Used by the evaluator and the compiler to set a constant by name This is for a null const decl
   */
  public IRubyObject setConstantInCurrent(String internedName, IRubyObject result) {
    RubyModule module;

    if ((module = getCurrentScope().getStaticScope().getModule()) != null) {
      module.fastSetConstant(internedName, result);
      return result;
    }

    // TODO: wire into new exception handling mechanism
    throw runtime.newTypeError("no class/module to define constant");
  }
Esempio n. 18
0
 /**
  * @param runtime
  * @param factory
  * @return
  */
 public static RubyClass createCommandClass(final Ruby runtime, DriverDefinition factory) {
   RubyModule doModule = runtime.getModule(DATA_OBJECTS_MODULE_NAME);
   RubyClass superClass = doModule.getClass(RUBY_CLASS_NAME);
   RubyModule driverModule = (RubyModule) doModule.getConstant(factory.getModuleName());
   RubyClass commandClass =
       runtime.defineClassUnder("Command", superClass, COMMAND_ALLOCATOR, driverModule);
   commandClass.setInstanceVariable("@__factory", JavaEmbedUtils.javaToRuby(runtime, factory));
   commandClass.defineAnnotatedMethods(Command.class);
   setDriverDefinition(commandClass, runtime, factory);
   return commandClass;
 }
Esempio n. 19
0
  public static RubyClass createConverterTypeClass(Ruby runtime, RubyModule ffiModule) {
    RubyClass convClass =
        ffiModule
            .getClass("Type")
            .defineClassUnder(
                "Mapped", ffiModule.getClass("Type"), ObjectAllocator.NOT_ALLOCATABLE_ALLOCATOR);
    convClass.defineAnnotatedMethods(MappedType.class);
    convClass.defineAnnotatedConstants(MappedType.class);

    return convClass;
  }
Esempio n. 20
0
  public static RubyClass createBufferClass(Ruby runtime, RubyModule module) {
    RubyClass result =
        module.defineClassUnder(
            "Buffer",
            module.getClass(AbstractMemory.ABSTRACT_MEMORY_RUBY_CLASS),
            ObjectAllocator.NOT_ALLOCATABLE_ALLOCATOR);
    result.defineAnnotatedMethods(Buffer.class);
    result.defineAnnotatedConstants(Buffer.class);

    return result;
  }
Esempio n. 21
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;
      }
    }
  }
Esempio n. 22
0
  @Override
  public boolean basicLoad(final Ruby ruby) throws IOException {
    RubyModule jr_jackson = ruby.defineModule("JrJackson");

    RubyModule jr_jackson_raw = ruby.defineModuleUnder("Raw", jr_jackson);
    jr_jackson_raw.defineAnnotatedMethods(JrJacksonRaw.class);

    RubyClass runtimeError = ruby.getRuntimeError();
    RubyClass parseError =
        jr_jackson.defineClassUnder("ParseError", runtimeError, runtimeError.getAllocator());
    return true;
  }
  public IRubyObject reCache(ThreadContext context, RubyModule target) {
    Object newGeneration = invalidator(context).getData();
    IRubyObject value = target.getConstantFromNoConstMissing(name, false);

    cachedValue = value;

    if (value != null) {
      generation = newGeneration;
      hash = target.hashCode();
    }

    return value;
  }
Esempio n. 24
0
  public static void createX509Store(Ruby runtime, RubyModule mX509) {
    RubyClass cX509Store =
        mX509.defineClassUnder("Store", runtime.getObject(), X509STORE_ALLOCATOR);
    RubyClass openSSLError = runtime.getModule("OpenSSL").getClass("OpenSSLError");
    mX509.defineClassUnder("StoreError", openSSLError, openSSLError.getAllocator());
    cX509Store.addReadWriteAttribute(runtime.getCurrentContext(), "verify_callback");
    cX509Store.addReadWriteAttribute(runtime.getCurrentContext(), "error");
    cX509Store.addReadWriteAttribute(runtime.getCurrentContext(), "error_string");
    cX509Store.addReadWriteAttribute(runtime.getCurrentContext(), "chain");
    cX509Store.defineAnnotatedMethods(X509Store.class);

    X509StoreCtx.createX509StoreCtx(runtime, mX509);
  }
Esempio n. 25
0
 public static void createRubyDescriptor(Ruby runtime) {
   RubyModule protobuf = runtime.getClassFromPath("Google::Protobuf");
   RubyClass cDescriptor =
       protobuf.defineClassUnder(
           "Descriptor",
           runtime.getObject(),
           new ObjectAllocator() {
             @Override
             public IRubyObject allocate(Ruby runtime, RubyClass klazz) {
               return new RubyDescriptor(runtime, klazz);
             }
           });
   cDescriptor.includeModule(runtime.getEnumerable());
   cDescriptor.defineAnnotatedMethods(RubyDescriptor.class);
 }
 private Object cache(Ruby runtime, RubyModule module) {
   Object constant =
       noPrivateConsts
           ? module.getConstantFromNoConstMissing(constName, false)
           : module.getConstantNoConstMissing(constName);
   if (constant == null) {
     constant = UndefinedValue.UNDEFINED;
   } else {
     // recache
     generation = runtime.getConstantInvalidator(constName).getData();
     hash = module.hashCode();
     cachedConstant = constant;
   }
   return constant;
 }
Esempio n. 27
0
  DynamicMethod createMethod(
      RubyModule module, Function function, Type returnType, Type[] parameterTypes) {

    FastIntMethodFactory factory = this;
    IntParameterConverter[] parameterConverters = new IntParameterConverter[parameterTypes.length];
    IntResultConverter resultConverter = factory.getIntResultConverter(returnType);
    for (int i = 0; i < parameterConverters.length; ++i) {
      parameterConverters[i] = factory.getIntParameterConverter(parameterTypes[i]);
    }

    switch (parameterTypes.length) {
      case 0:
        return new FastIntMethodZeroArg(module, function, resultConverter, parameterConverters);
      case 1:
        return new FastIntMethodOneArg(module, function, resultConverter, parameterConverters);
      case 2:
        return new FastIntMethodTwoArg(module, function, resultConverter, parameterConverters);
      case 3:
        return new FastIntMethodThreeArg(module, function, resultConverter, parameterConverters);
      default:
        throw module
            .getRuntime()
            .newRuntimeError("Arity " + parameterTypes.length + " not implemented");
    }
  }
Esempio n. 28
0
  public static IRubyObject INTERPRET_METHOD(
      ThreadContext context,
      CFG cfg,
      InterpreterContext interp,
      String name,
      RubyModule implClass,
      boolean isTraceable) {
    Ruby runtime = interp.getRuntime();
    boolean syntheticMethod = name == null || name.equals("");

    try {
      String className = implClass.getName();
      if (!syntheticMethod)
        ThreadContext.pushBacktrace(context, className, name, context.getFile(), context.getLine());
      if (isTraceable) methodPreTrace(runtime, context, name, implClass);
      return interpret(context, cfg, interp);
    } finally {
      if (isTraceable) {
        try {
          methodPostTrace(runtime, context, name, implClass);
        } finally {
          if (!syntheticMethod) ThreadContext.popBacktrace(context);
        }
      } else {
        if (!syntheticMethod) ThreadContext.popBacktrace(context);
      }
    }
  }
Esempio n. 29
0
  public static IRubyObject inheritanceSearchConst(
      ThreadContext context,
      IRubyObject cmVal,
      MutableCallSite site,
      String constName,
      boolean noPrivateConsts)
      throws Throwable {
    Ruby runtime = context.runtime;
    RubyModule module;

    if (cmVal instanceof RubyModule) {
      module = (RubyModule) cmVal;
    } else {
      throw runtime.newTypeError(cmVal + " is not a type/class");
    }

    IRubyObject constant =
        noPrivateConsts
            ? module.getConstantFromNoConstMissing(constName, false)
            : module.getConstantNoConstMissing(constName);

    if (constant == null) {
      constant = UndefinedValue.UNDEFINED;
    }

    SwitchPoint switchPoint = (SwitchPoint) runtime.getConstantInvalidator(constName).getData();

    // bind constant until invalidated
    MethodHandle target = Binder.from(site.type()).drop(0, 2).constant(constant);
    MethodHandle fallback =
        Binder.from(site.type())
            .append(site, constName)
            .append(noPrivateConsts)
            .invokeStatic(LOOKUP, Bootstrap.class, "inheritanceSearchConst");

    // test that module is same as before
    MethodHandle test =
        Binder.from(site.type().changeReturnType(boolean.class))
            .drop(0, 1)
            .insert(1, module.id)
            .invokeStaticQuiet(LOOKUP, Bootstrap.class, "testArg0ModuleMatch");
    target = guardWithTest(test, target, fallback);
    site.setTarget(switchPoint.guardWithTest(target, fallback));

    return constant;
  }
Esempio n. 30
0
  /**
   * Output a log message
   *
   * @param logMessage
   * @param executionTime
   */
  private void debug(String logMessage, Long executionTime) {
    Ruby runtime = getRuntime();
    Connection connection_instance = (Connection) api.getInstanceVariable(this, "@connection");
    RubyModule doModule = runtime.getModule(DATA_OBJECTS_MODULE_NAME);
    RubyClass loggerClass = doModule.getClass("Logger");
    RubyClass messageClass = loggerClass.getClass("Message");

    IRubyObject loggerMsg =
        messageClass.newInstance(
            runtime.getCurrentContext(),
            runtime.newString(logMessage), // query
            runtime.newString(""), // start
            runtime.newFixnum(executionTime), // duration
            Block.NULL_BLOCK);

    api.callMethod(connection_instance, "log", loggerMsg);
  }