com.sun.jdi.Value Java Examples

The following examples show how to use com.sun.jdi.Value. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CharacterFormatterTest.java    From java-debug with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void testToString() throws Exception {
    Map<String, Object> options = formatter.getDefaultOptions();
    Value charVar = getVM().mirrorOf('c');
    assertEquals("Should be able to format char type.", "c",
        formatter.toString(charVar, options));

    charVar = getVM().mirrorOf('C');
    assertEquals("Should be able to format char type.", "C",
        formatter.toString(charVar, options));

    charVar = getVM().mirrorOf('?');
    assertEquals("Should be able to format char type.", "?",
        formatter.toString(charVar, options));

    charVar = getVM().mirrorOf('中');
    assertEquals("Should be able to format char type.", "中",
        formatter.toString(charVar, options));
}
 
Example #2
Source File: JdtEvaluationProvider.java    From java-debug with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public CompletableFuture<Value> evaluateForBreakpoint(IEvaluatableBreakpoint breakpoint, ThreadReference thread) {
    if (breakpoint == null) {
        throw new IllegalArgumentException("The breakpoint is null.");
    }

    if (!breakpoint.containsEvaluatableExpression()) {
        throw new IllegalArgumentException("The breakpoint doesn't contain the evaluatable expression.");
    }

    if (StringUtils.isNotBlank(breakpoint.getLogMessage())) {
        return evaluate(logMessageToExpression(breakpoint.getLogMessage()), thread, 0, breakpoint);
    } else {
        return evaluate(breakpoint.getCondition(), thread, 0, breakpoint);
    }
}
 
Example #3
Source File: NumericFormatter.java    From java-debug with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Get the string representations for an object.
 *
 * @param obj the value object
 * @param options extra information for printing
 * @return the string representations.
 */
@Override
public String toString(Object obj, Map<String, Object> options) {
    Value value = (Value) obj;
    char signature0 = value.type().signature().charAt(0);
    if (signature0 == LONG
            || signature0 == INT
            || signature0 == SHORT
            || signature0 == BYTE) {
        return formatNumber(Long.parseLong(value.toString()), options);
    } else if (hasFraction(signature0)) {
        return formatFloatDouble(Double.parseDouble(value.toString()), options);
    }

    throw new UnsupportedOperationException(String.format("%s is not a numeric type.", value.type().name()));
}
 
Example #4
Source File: ObjectTranslation.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private Object createTranslation (Object o, Object v) {
    switch (translationID) {
        case LOCALS_ID:
            if (o instanceof LocalVariable && (v == null || v instanceof Value)) {
                LocalVariable lv = (LocalVariable) o;
                org.netbeans.api.debugger.jpda.LocalVariable local;
                if (v instanceof ObjectReference || v == null) {
                    local = new ObjectLocalVariable (
                        debugger, 
                        (ObjectReference) v, 
                        null, 
                        lv, 
                        JPDADebuggerImpl.getGenericSignature (lv), 
                        null
                    );
                } else {
                    local = new Local (debugger, (PrimitiveValue) v, null, lv, null);
                }
                return local;
            }
        default:
            throw new IllegalStateException(""+o);
    }
}
 
Example #5
Source File: AWTGrabHandler.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void ungrabWindowFX(ClassType WindowClass, ObjectReference w, ThreadReference tr) throws Exception {
    // javafx.stage.Window w
    // w.focusGrabCounter
    // while (focusGrabCounter-- > 0) {
    //     w.impl_getPeer().ungrabFocus(); OR: w.impl_peer.ungrabFocus();
    // }
    Field focusGrabCounterField = WindowClass.fieldByName("focusGrabCounter");
    if (focusGrabCounterField == null) {
        logger.info("Unable to release FX X grab, no focusGrabCounter field in "+w);
        return ;
    }
    Value focusGrabCounterValue = w.getValue(focusGrabCounterField);
    if (!(focusGrabCounterValue instanceof IntegerValue)) {
        logger.info("Unable to release FX X grab, focusGrabCounter does not have an integer value in "+w);
        return ;
    }
    int focusGrabCounter = ((IntegerValue) focusGrabCounterValue).intValue();
    if (logger.isLoggable(Level.FINE)) {
        logger.fine("Focus grab counter of "+w+" is: "+focusGrabCounter);
    }
    while (focusGrabCounter-- > 0) {
        //Method impl_getPeerMethod = WindowClass.concreteMethodByName("impl_getPeer", "");
        Field impl_peerField = WindowClass.fieldByName("impl_peer");
        if (impl_peerField == null) {
            logger.info("Unable to release FX X grab, no impl_peer field in "+w);
            return ;
        }
        ObjectReference impl_peer = (ObjectReference) w.getValue(impl_peerField);
        if (impl_peer == null) {
            continue;
        }
        InterfaceType TKStageClass = (InterfaceType) w.virtualMachine().classesByName("com.sun.javafx.tk.TKStage").get(0);
        Method ungrabFocusMethod = TKStageClass.methodsByName("ungrabFocus", "()V").get(0);
        impl_peer.invokeMethod(tr, ungrabFocusMethod, Collections.<Value>emptyList(), ObjectReference.INVOKE_SINGLE_THREADED);
        if (logger.isLoggable(Level.FINE)) {
            logger.fine("FX Window "+w+" was successfully ungrabbed.");
        }
    }
}
 
Example #6
Source File: CallStackFrameImpl.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private static MethodArgument[] checkArgumentCount(MethodArgument[] argumentNames, List<Value> argValues, int size) {
    if (argumentNames == null || argumentNames.length != size) {
        argumentNames = new MethodArgument[size];
        for (int i = 0; i < argumentNames.length; i++) {
            Value v = argValues.get(i);
            String type;
            if (v != null) {
                type = v.type().name();
            } else {
                type = Object.class.getName();
            }
            argumentNames[i] = new MethodArgument(NbBundle.getMessage(CallStackFrameImpl.class, "CTL_MethodArgument", (i+1)), type, null, null);
        }
    }
    return argumentNames;
}
 
Example #7
Source File: BooleanFormatterTest.java    From java-debug with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void testValueOf() throws Exception {
    Map<String, Object> options = formatter.getDefaultOptions();
    Value boolVar = getVM().mirrorOf(true);
    Value newValue = formatter.valueOf("true", boolVar.type(), options);
    assertTrue("should return boolean type", newValue instanceof BooleanValue);
    assertTrue("should return boolean type", ((BooleanValue)newValue).value());
    assertEquals("Should be able to restore boolean value.", "true",
        formatter.toString(newValue, options));

    newValue = formatter.valueOf("True", boolVar.type(), options);
    assertTrue("should return boolean type", newValue instanceof BooleanValue);
    assertTrue("should return boolean type", ((BooleanValue)newValue).value());

    newValue = formatter.valueOf("false", boolVar.type(), options);
    assertTrue("should return boolean type", newValue instanceof BooleanValue);
    assertFalse("should return boolean 'false'", ((BooleanValue)newValue).value());

    newValue = formatter.valueOf("False", boolVar.type(), options);
    assertTrue("should return boolean type", newValue instanceof BooleanValue);
    assertFalse("should return boolean 'false'", ((BooleanValue)newValue).value());

    newValue = formatter.valueOf("abc", boolVar.type(), options);
    assertTrue("should return boolean type", newValue instanceof BooleanValue);
    assertFalse("should return boolean 'false'", ((BooleanValue)newValue).value());
}
 
Example #8
Source File: JPDAObjectWatchImpl.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
* Sets string representation of value of this variable.
*
* @param value string representation of value of this variable.
*
public void setValue (String expression) throws InvalidExpressionException {
    // evaluate expression to Value
    Value value = model.getDebugger ().evaluateIn (expression);
    // set new value to remote veriable
    setValue (value);
    // set new value to this model
    setInnerValue (value);
    // refresh tree
    model.fireTableValueChangedChanged (this, null);
}
 */

protected void setValue (final Value value) 
throws InvalidExpressionException {
    EvaluationContext.VariableInfo vi = getInfo(debugger, getInnerValue());
    if (vi != null) {
        try {
            vi.setValue(value);
        } catch (IllegalStateException isex) {
            if (isex.getCause() instanceof InvalidExpressionException) {
                throw (InvalidExpressionException) isex.getCause();
            } else {
                throw new InvalidExpressionException(isex);
            }
        }
    } else {
        throw new InvalidExpressionException (
                NbBundle.getMessage(JPDAWatchImpl.class, "MSG_CanNotSetValue", getExpression()));
    }
}
 
Example #9
Source File: JavaLogicalStructure.java    From java-debug with Eclipse Public License 1.0 6 votes vote down vote up
private static Value getValue(ObjectReference thisObject, LogicalStructureExpression expression, ThreadReference thread,
        IEvaluationProvider evaluationEngine) throws CancellationException, IllegalArgumentException, InterruptedException, ExecutionException {
    if (expression.type == LogicalStructureExpressionType.METHOD) {
        if (expression.value == null || expression.value.length < 2) {
            throw new IllegalArgumentException("The method expression should contain at least methodName and methodSignature!");
        }
        return evaluationEngine.invokeMethod(thisObject, expression.value[0], expression.value[1], null, thread, false).get();
    } else if (expression.type == LogicalStructureExpressionType.FIELD) {
        if (expression.value == null || expression.value.length < 1) {
            throw new IllegalArgumentException("The field expression should contain the field name!");
        }
        return getValueByField(thisObject, expression.value[0], thread);
    } else {
        if (expression.value == null || expression.value.length < 1) {
            throw new IllegalArgumentException("The evaluation expression should contain a valid expression statement!");
        }
        return evaluationEngine.evaluate(expression.value[0], thisObject, thread).get();
    }
}
 
Example #10
Source File: InvocationExceptionTranslated.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private String getMessageFromField() throws InternalExceptionWrapper,
                                            VMDisconnectedExceptionWrapper,
                                            ObjectCollectedExceptionWrapper,
                                            ClassNotPreparedExceptionWrapper {
    List<ReferenceType> throwableClasses = VirtualMachineWrapper.classesByName(exeption.virtualMachine(), Throwable.class.getName());
    if (throwableClasses.isEmpty()) {
        return null;
    }
    Field detailMessageField = ReferenceTypeWrapper.fieldByName(throwableClasses.get(0), "detailMessage");
    if (detailMessageField != null) {
        Value messageValue = ObjectReferenceWrapper.getValue(exeption, detailMessageField);
        if (messageValue instanceof StringReference) {
            message = StringReferenceWrapper.value((StringReference) messageValue);
            if (invocationMessage != null) {
                return invocationMessage + ": " + message;
            } else {
                return message;
            }
        }
    }
    return null;
}
 
Example #11
Source File: BreakpointImpl.java    From netbeans with Apache License 2.0 5 votes vote down vote up
boolean processCondition(
        Event event,
        String condition,
        ThreadReference threadReference,
        Value returnValue) {
    
    return processCondition(event, condition, threadReference, returnValue, null);
}
 
Example #12
Source File: InvokableTypeImpl.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Method invocation support.
 * Shared by ClassType and InterfaceType
 * @param threadIntf the thread in which to invoke.
 * @param methodIntf method the {@link Method} to invoke.
 * @param origArguments the list of {@link Value} arguments bound to the
 * invoked method. Values from the list are assigned to arguments
 * in the order they appear in the method signature.
 * @param options the integer bit flag options.
 * @return a {@link Value} mirror of the invoked method's return value.
 * @throws java.lang.IllegalArgumentException if the method is not
 * a member of this type, if the size of the argument list
 * does not match the number of declared arguments for the method, or
 * if the method is not static or is a static initializer.
 * @throws {@link InvalidTypeException} if any argument in the
 * argument list is not assignable to the corresponding method argument
 * type.
 * @throws ClassNotLoadedException if any argument type has not yet been loaded
 * through the appropriate class loader.
 * @throws IncompatibleThreadStateException if the specified thread has not
 * been suspended by an event.
 * @throws InvocationException if the method invocation resulted in
 * an exception in the target VM.
 * @throws InvalidTypeException If the arguments do not meet this requirement --
 *         Object arguments must be assignment compatible with the argument
 *         type.  This implies that the argument type must be
 *         loaded through the enclosing class's class loader.
 *         Primitive arguments must be either assignment compatible with the
 *         argument type or must be convertible to the argument type without loss
 *         of information. See JLS section 5.2 for more information on assignment
 *         compatibility.
 * @throws VMCannotBeModifiedException if the VirtualMachine is read-only - see {@link VirtualMachine#canBeModified()}.
 */
final public Value invokeMethod(ThreadReference threadIntf, Method methodIntf,
                                List<? extends Value> origArguments, int options)
                                    throws InvalidTypeException,
                                           ClassNotLoadedException,
                                           IncompatibleThreadStateException,
                                           InvocationException {
    validateMirror(threadIntf);
    validateMirror(methodIntf);
    validateMirrorsOrNulls(origArguments);
    MethodImpl method = (MethodImpl) methodIntf;
    ThreadReferenceImpl thread = (ThreadReferenceImpl) threadIntf;
    validateMethodInvocation(method);
    List<? extends Value> arguments = method.validateAndPrepareArgumentsForInvoke(origArguments);
    ValueImpl[] args = arguments.toArray(new ValueImpl[0]);
    InvocationResult ret;
    try {
        PacketStream stream = sendInvokeCommand(thread, method, args, options);
        ret = waitForReply(stream);
    } catch (JDWPException exc) {
        if (exc.errorCode() == JDWP.Error.INVALID_THREAD) {
            throw new IncompatibleThreadStateException();
        } else {
            throw exc.toJDIException();
        }
    }
    /*
     * There is an implict VM-wide suspend at the conclusion
     * of a normal (non-single-threaded) method invoke
     */
    if ((options & ClassType.INVOKE_SINGLE_THREADED) == 0) {
        vm.notifySuspend();
    }
    if (ret.getException() != null) {
        throw new InvocationException(ret.getException());
    } else {
        return ret.getResult();
    }
}
 
Example #13
Source File: OomDebugTest.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings({ "rawtypes", "unchecked" })
void invoke(String methodName, String methodSig, Value value)
        throws Exception {
    List args = new ArrayList(1);
    args.add(value);
    invoke(methodName, methodSig, args, value);
}
 
Example #14
Source File: JPDADebuggerImpl.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public Value evaluateIn (EvaluatorExpression expression, CallStackFrame csf, ObjectVariable var) throws InvalidExpressionException {
    Variable variable = evaluateGeneric(expression, csf, var);
    if (variable instanceof JDIVariable) {
        return ((JDIVariable) variable).getJDIValue();
    } else {
        return null;
    }
}
 
Example #15
Source File: RemoteServices.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static ArrayReference createTargetBytes(VirtualMachine vm, byte[] bytes,
                                                ByteValue[] mirrorBytesCache) throws InvalidTypeException,
                                                                                     ClassNotLoadedException,
                                                                                     InternalExceptionWrapper,
                                                                                     VMDisconnectedExceptionWrapper,
                                                                                     ObjectCollectedExceptionWrapper,
                                                                                     UnsupportedOperationExceptionWrapper {
    ArrayType bytesArrayClass = getArrayClass(vm, "byte[]");
    ArrayReference array = null;
    boolean disabledCollection = false;
    while (!disabledCollection) {
        array = ArrayTypeWrapper.newInstance(bytesArrayClass, bytes.length);
        try {
            ObjectReferenceWrapper.disableCollection(array);
            disabledCollection = true;
        } catch (ObjectCollectedExceptionWrapper ocex) {
            // Collected too soon, try again...
        }
    }
    List<Value> values = new ArrayList<Value>(bytes.length);
    for (int i = 0; i < bytes.length; i++) {
        byte b = bytes[i];
        ByteValue mb = mirrorBytesCache[128 + b];
        if (mb == null) {
            mb = VirtualMachineWrapper.mirrorOf(vm, b);
            mirrorBytesCache[128 + b] = mb;
        }
        values.add(mb);
    }
    ArrayReferenceWrapper.setValues(array, values);
    return array;
}
 
Example #16
Source File: InvokableTypeImpl.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Method invocation support.
 * Shared by ClassType and InterfaceType
 * @param threadIntf the thread in which to invoke.
 * @param methodIntf method the {@link Method} to invoke.
 * @param origArguments the list of {@link Value} arguments bound to the
 * invoked method. Values from the list are assigned to arguments
 * in the order they appear in the method signature.
 * @param options the integer bit flag options.
 * @return a {@link Value} mirror of the invoked method's return value.
 * @throws java.lang.IllegalArgumentException if the method is not
 * a member of this type, if the size of the argument list
 * does not match the number of declared arguments for the method, or
 * if the method is not static or is a static initializer.
 * @throws {@link InvalidTypeException} if any argument in the
 * argument list is not assignable to the corresponding method argument
 * type.
 * @throws ClassNotLoadedException if any argument type has not yet been loaded
 * through the appropriate class loader.
 * @throws IncompatibleThreadStateException if the specified thread has not
 * been suspended by an event.
 * @throws InvocationException if the method invocation resulted in
 * an exception in the target VM.
 * @throws InvalidTypeException If the arguments do not meet this requirement --
 *         Object arguments must be assignment compatible with the argument
 *         type.  This implies that the argument type must be
 *         loaded through the enclosing class's class loader.
 *         Primitive arguments must be either assignment compatible with the
 *         argument type or must be convertible to the argument type without loss
 *         of information. See JLS section 5.2 for more information on assignment
 *         compatibility.
 * @throws VMCannotBeModifiedException if the VirtualMachine is read-only - see {@link VirtualMachine#canBeModified()}.
 */
final public Value invokeMethod(ThreadReference threadIntf, Method methodIntf,
                                List<? extends Value> origArguments, int options)
                                    throws InvalidTypeException,
                                           ClassNotLoadedException,
                                           IncompatibleThreadStateException,
                                           InvocationException {
    validateMirror(threadIntf);
    validateMirror(methodIntf);
    validateMirrorsOrNulls(origArguments);
    MethodImpl method = (MethodImpl) methodIntf;
    ThreadReferenceImpl thread = (ThreadReferenceImpl) threadIntf;
    validateMethodInvocation(method);
    List<? extends Value> arguments = method.validateAndPrepareArgumentsForInvoke(origArguments);
    ValueImpl[] args = arguments.toArray(new ValueImpl[0]);
    InvocationResult ret;
    try {
        PacketStream stream = sendInvokeCommand(thread, method, args, options);
        ret = waitForReply(stream);
    } catch (JDWPException exc) {
        if (exc.errorCode() == JDWP.Error.INVALID_THREAD) {
            throw new IncompatibleThreadStateException();
        } else {
            throw exc.toJDIException();
        }
    }
    /*
     * There is an implict VM-wide suspend at the conclusion
     * of a normal (non-single-threaded) method invoke
     */
    if ((options & ClassType.INVOKE_SINGLE_THREADED) == 0) {
        vm.notifySuspend();
    }
    if (ret.getException() != null) {
        throw new InvocationException(ret.getException());
    } else {
        return ret.getResult();
    }
}
 
Example #17
Source File: VariableDetailUtils.java    From java-debug with Eclipse Public License 1.0 5 votes vote down vote up
private static String findInheritedType(Value value, Set<String> typeNames) {
    if (!(value instanceof ObjectReference)) {
        return null;
    }

    Type variableType = ((ObjectReference) value).type();
    if (!(variableType instanceof ClassType)) {
        return null;
    }

    ClassType classType = (ClassType) variableType;
    while (classType != null) {
        if (typeNames.contains(classType.name())) {
            return classType.name();
        }

        classType = classType.superclass();
    }

    List<InterfaceType> interfaceTypes = ((ClassType) variableType).allInterfaces();
    for (InterfaceType interfaceType : interfaceTypes) {
        if (typeNames.contains(interfaceType.name())) {
            return interfaceType.name();
        }
    }

    return null;
}
 
Example #18
Source File: JPDADebuggerImpl.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public Value invokeMethod (
    ObjectReference reference,
    Method method,
    Value[] arguments,
    int maxLength
) throws InvalidExpressionException {
    return invokeMethod(null, reference, null, method, arguments, maxLength, null);
}
 
Example #19
Source File: TruffleDebugManager.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void submitExistingEnginesProbe(final JPDADebugger debugger, List<JPDAClassType> enginePe) {
    synchronized (haveExistingEnginesTrigger) {
        if (Boolean.TRUE.equals(haveExistingEnginesTrigger.get(debugger))) {
            return ;
        }
        haveExistingEnginesTrigger.put(debugger, Boolean.TRUE);
    }
    MethodBreakpoint execTrigger = MethodBreakpoint.create(EXISTING_ENGINES_TRIGGER, "*");
    execTrigger.setHidden(true);
    execTrigger.setSession(debugger);
    execTrigger.addJPDABreakpointListener((event) -> {
        DebuggerManager.getDebuggerManager().removeBreakpoint(execTrigger);
        try {
            JPDAThreadImpl thread = (JPDAThreadImpl) event.getThread();
            boolean haveSomeEngine = false;
            for (JPDAClassType pe : enginePe) {
                List<ObjectVariable> instances = pe.getInstances(0);
                for (ObjectVariable obj : instances) {
                    Value value = ((JDIVariable) obj).getJDIValue();
                    if (value instanceof ObjectReference) {
                        haveNewPE(debugger, thread, (ObjectReference) value);
                        haveSomeEngine = true;
                    }
                }
            }
            if (haveSomeEngine) {
                for (ActionsProvider ap : ((JPDADebuggerImpl) debugger).getSession().lookup(null, ActionsProvider.class)) {
                    if (ap.getActions().contains(PauseInGraalScriptActionProvider.NAME)) {
                        // Trigger the enabling of the action as there are engines now:
                        ap.isEnabled(PauseInGraalScriptActionProvider.NAME);
                    }
                }
            }
        } finally {
            event.resume();
        }
    });
    DebuggerManager.getDebuggerManager().addBreakpoint(execTrigger);
}
 
Example #20
Source File: JPDADebuggerImpl.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Used by AbstractVariable.
 */
public Value invokeMethod (
    JPDAThreadImpl thread,
    ObjectReference reference,
    Method method,
    Value[] arguments
) throws InvalidExpressionException {
    return invokeMethod(thread, reference, method, arguments, null);
}
 
Example #21
Source File: JPDADebuggerImpl.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public Value invokeMethod (
    JPDAThreadImpl thread,
    ObjectReference reference,
    Method method,
    Value[] arguments,
    InvocationExceptionTranslated existingInvocationException
) throws InvalidExpressionException {
    return invokeMethod(thread, reference, null, method, arguments, 0, existingInvocationException);
}
 
Example #22
Source File: JPDADebuggerImpl.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private Variable createVariable(Value v) {
    if (v instanceof ObjectReference || v == null) {
        return new AbstractObjectVariable (
            this,
            (ObjectReference) v,
            null
        );
    } else {
        return new AbstractVariable (this, v, null);
    }
}
 
Example #23
Source File: AbstractVariable.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public Object createMirrorObject() {
    Value v = getJDIValue();
    if (v == null) {
        return null;
    }
    return VariableMirrorTranslator.createMirrorObject(v);
}
 
Example #24
Source File: VariableMirrorTranslator.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static Object setFieldsValues(Object newInstance, Class clazz, Map<Field, Value> fieldValues, Map<Value, Object> mirrorsMap) throws InternalExceptionWrapper, VMDisconnectedExceptionWrapper {
    for (Field f : fieldValues.keySet()) {
        String name = TypeComponentWrapper.name(f);
        java.lang.reflect.Field field = getDeclaredOrInheritedField(clazz, name);
        if (field == null) {
            logger.log(Level.CONFIG, "No Such Field({0}) of class {1}", new Object[]{name, clazz});
            return null;
        }
        field.setAccessible(true);
        Value v = fieldValues.get(f);
        try {
            if (v == null) {
                field.set(newInstance, null);
            } else {
                Object mv = mirrorsMap.get(v);
                if (mv == null) {
                    mv = createMirrorObject(v, mirrorsMap);
                }
                if (mv != null) {
                    field.set(newInstance, mv);
                } else {
                    logger.log(Level.CONFIG, "Unable to translate field {0} of class {1}", new Object[]{name, clazz});
                    return null;
                }
            }
        } catch (IllegalAccessException ex) {
            logger.log(Level.CONFIG, "IllegalAccessException({0}) of field {1}", new Object[]{ex.getLocalizedMessage(), field});
            return null;
        }
    }
    return newInstance;
}
 
Example #25
Source File: VariableMirrorTranslator.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static Map<Field, Value> getFieldValues(ObjectReference value, ReferenceType type, String... names) throws InternalExceptionWrapper, VMDisconnectedExceptionWrapper, ObjectCollectedExceptionWrapper, ClassNotPreparedExceptionWrapper {
    final int n = names.length;
    List<Field> fieldsToAskFor = new ArrayList<Field>(n);
    for (String name : names) {
        Field field = ReferenceTypeWrapper.fieldByName(type, name);
        if (field == null) {
            return null;
        }
        fieldsToAskFor.add(field);
    }
    Map<Field, Value> fieldValues = ObjectReferenceWrapper.getValues(value, fieldsToAskFor);
    return fieldValues;
}
 
Example #26
Source File: NumericFormatterTest.java    From java-debug with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void testToHexOctString() throws Exception {
    Value i = this.getLocalValue("i");

    Map<String, Object> options = formatter.getDefaultOptions();
    options.put(NUMERIC_FORMAT_OPTION, NumericFormatEnum.HEX);
    assertEquals("NumericFormatter should be able to format an hex integer.",
        "0x" + Integer.toHexString(111), formatter.toString(i, options));


    options.put(NUMERIC_FORMAT_OPTION, NumericFormatEnum.OCT);
    assertEquals("NumericFormatter should be able to format an oct integer.",
        "0" +Integer.toOctalString(111), formatter.toString(i, options));
}
 
Example #27
Source File: StringObjectFormatter.java    From java-debug with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public Value valueOf(String value, Type type, Map<String, Object> options) {
    if (value == null || NullObjectFormatter.NULL_STRING.equals(value)) {
        return null;
    }
    if (value.length() >= 2
            && value.startsWith(QUOTE_STRING)
            && value.endsWith(QUOTE_STRING)) {
        return type.virtualMachine().mirrorOf(StringUtils.substring(value, 1, -1));
    }
    return type.virtualMachine().mirrorOf(value);
}
 
Example #28
Source File: InvokableTypeImpl.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Method invocation support.
 * Shared by ClassType and InterfaceType
 * @param threadIntf the thread in which to invoke.
 * @param methodIntf method the {@link Method} to invoke.
 * @param origArguments the list of {@link Value} arguments bound to the
 * invoked method. Values from the list are assigned to arguments
 * in the order they appear in the method signature.
 * @param options the integer bit flag options.
 * @return a {@link Value} mirror of the invoked method's return value.
 * @throws java.lang.IllegalArgumentException if the method is not
 * a member of this type, if the size of the argument list
 * does not match the number of declared arguments for the method, or
 * if the method is not static or is a static initializer.
 * @throws {@link InvalidTypeException} if any argument in the
 * argument list is not assignable to the corresponding method argument
 * type.
 * @throws ClassNotLoadedException if any argument type has not yet been loaded
 * through the appropriate class loader.
 * @throws IncompatibleThreadStateException if the specified thread has not
 * been suspended by an event.
 * @throws InvocationException if the method invocation resulted in
 * an exception in the target VM.
 * @throws InvalidTypeException If the arguments do not meet this requirement --
 *         Object arguments must be assignment compatible with the argument
 *         type.  This implies that the argument type must be
 *         loaded through the enclosing class's class loader.
 *         Primitive arguments must be either assignment compatible with the
 *         argument type or must be convertible to the argument type without loss
 *         of information. See JLS section 5.2 for more information on assignment
 *         compatibility.
 * @throws VMCannotBeModifiedException if the VirtualMachine is read-only - see {@link VirtualMachine#canBeModified()}.
 */
final public Value invokeMethod(ThreadReference threadIntf, Method methodIntf,
                                List<? extends Value> origArguments, int options)
                                    throws InvalidTypeException,
                                           ClassNotLoadedException,
                                           IncompatibleThreadStateException,
                                           InvocationException {
    validateMirror(threadIntf);
    validateMirror(methodIntf);
    validateMirrorsOrNulls(origArguments);
    MethodImpl method = (MethodImpl) methodIntf;
    ThreadReferenceImpl thread = (ThreadReferenceImpl) threadIntf;
    validateMethodInvocation(method);
    List<? extends Value> arguments = method.validateAndPrepareArgumentsForInvoke(origArguments);
    ValueImpl[] args = arguments.toArray(new ValueImpl[0]);
    InvocationResult ret;
    try {
        PacketStream stream = sendInvokeCommand(thread, method, args, options);
        ret = waitForReply(stream);
    } catch (JDWPException exc) {
        if (exc.errorCode() == JDWP.Error.INVALID_THREAD) {
            throw new IncompatibleThreadStateException();
        } else {
            throw exc.toJDIException();
        }
    }
    /*
     * There is an implict VM-wide suspend at the conclusion
     * of a normal (non-single-threaded) method invoke
     */
    if ((options & ClassType.INVOKE_SINGLE_THREADED) == 0) {
        vm.notifySuspend();
    }
    if (ret.getException() != null) {
        throw new InvocationException(ret.getException());
    } else {
        return ret.getResult();
    }
}
 
Example #29
Source File: EvaluationContext.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public void setValue(Value value) {
    try {
        context.getFrame().setValue(var, value);
    } catch (InvalidTypeException itex) {
        throw new IllegalStateException(new InvalidExpressionException (itex));
    } catch (ClassNotLoadedException cnlex) {
        throw new IllegalStateException(cnlex);
    }
}
 
Example #30
Source File: AbstractVariable.java    From netbeans with Apache License 2.0 5 votes vote down vote up
static String getValue (Value v) {
    if (v == null) {
        return "null";
    }
    if (v instanceof VoidValue) {
        return "void";
    }
    if (v instanceof CharValue) {
        return "\'" + v.toString () + "\'";
    }
    if (v instanceof PrimitiveValue) {
        return v.toString ();
    }
    try {
        if (v instanceof StringReference) {
            String str = ShortenedStrings.getStringWithLengthControl((StringReference) v);
            return "\"" + str + "\"";
        }
        if (v instanceof ClassObjectReference) {
            return "class " + ReferenceTypeWrapper.name(ClassObjectReferenceWrapper.reflectedType((ClassObjectReference) v));
        }
        if (v instanceof ArrayReference) {
            return "#" + ObjectReferenceWrapper.uniqueID((ArrayReference) v) +
                "(length=" + ArrayReferenceWrapper.length((ArrayReference) v) + ")";
        }
        return "#" + ObjectReferenceWrapper.uniqueID((ObjectReference) v);
    } catch (InternalExceptionWrapper iex) {
        return "";
    } catch (ObjectCollectedExceptionWrapper oex) {
        return "";
    } catch (VMDisconnectedExceptionWrapper dex) {
        return "";
    }
}