public CallerDescriptor(ServiceId service, MethodId method, EventId @event, string intentId) { Service = service; Method = method; Event = @event; IntentId = intentId; }
public override int GetHashCode() { int hash = 1; if (UserId != 0) { hash ^= UserId.GetHashCode(); } if (ModuleId != global::Lspb.ModuleId.UnknownModel) { hash ^= ModuleId.GetHashCode(); } if (MethodId != global::Lspb.ClientMsgType.ErrorClientType) { hash ^= MethodId.GetHashCode(); } if (cliEnterRoom_ != null) { hash ^= CliEnterRoom.GetHashCode(); } if (cliInitOver_ != null) { hash ^= CliInitOver.GetHashCode(); } if (cliOperate_ != null) { hash ^= CliOperate.GetHashCode(); } if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return(hash); }
private async Task <ITaskResult> TryWaitForResultAsync( ServiceId serviceId, MethodId routineMethodId, string intentId, TimeSpan?waitTime) { var cts = new CancellationTokenSource(); var completionSink = new TaskCompletionSource <ITaskResult>(); var trackingToken = _routineCompletionNotifier.NotifyOnCompletion( serviceId, routineMethodId, intentId, completionSink, cts.Token); ITaskResult result; try { result = await completionSink.WithTimeout(waitTime).Task .ContinueWith(t => t.IsCanceled ? null : t.Result); } catch (TaskCanceledException) { result = null; } finally { cts.Cancel(); _routineCompletionNotifier.StopTracking(trackingToken); } return(result); }
internal TResult Invoke <TResult>(object instance, MethodId method, Func <TInterface, TResult> f) { // If the last n - 1 calls are to the same method, // call the n-th implementation. var instanceAndMethod = new InstanceAndMethod(instance, method); int n = _calls.Count; int index = 0; while ((n - index > 0) && _calls[n - index - 1].Equals(instanceAndMethod)) { index++; } if (index == _implementations.Length) { throw new InvalidOperationException(); } var item = _implementations[index]; _calls.Push(instanceAndMethod); try { return(f(item)); } finally { _calls.Pop(); } }
public Location(TypeTag typeTag, ClassId @class, MethodId method, ulong index) { TypeTag = typeTag; Class = @class; Method = method; Index = index; }
public jvmtiError GetLineNumberTable(MethodId methodId, out LineNumberData[] lines) { lines = null; int entryCount; IntPtr table; jvmtiError error = RawInterface.GetLineNumberTable(this, (jmethodID)methodId, out entryCount, out table); if (error != jvmtiError.None) { return(error); } try { List <LineNumberData> lineData = new List <LineNumberData>(); unsafe { jvmtiLineNumberEntry *entryTable = (jvmtiLineNumberEntry *)table; for (int i = 0; i < entryCount; i++) { long lineCodeIndex = entryTable[i].StartLocation.Value; LineNumberData line = new LineNumberData(lineCodeIndex, entryTable[i].LineNumber); lineData.Add(line); } } lines = lineData.ToArray(); return(jvmtiError.None); } finally { Deallocate(table); } }
private static void Init() { if (initDone) { return; } try { initDone = true; // sun JVM specific JNIEnv env = JNIEnv.ThreadEnv; dbClazz = env.FindClass("java/nio/DirectByteBuffer"); // java 7 and above ctor = env.GetMethodIDNoThrow(dbClazz, "<init>", "(IJLjava/io/FileDescriptor;Ljava/lang/Runnable;)V"); if (ctor == null) { // java 6 and below ctor = env.GetMethodIDNoThrow(dbClazz, "<init>", "(IJLjava/lang/Runnable;)V"); jdk6 = true; } } catch (Exception) { } }
private async Task <RowSet> ExecuteQueryAsync(ServiceId serviceId, MethodId methodId, string query) { var session = await Session(); @TryExecute: try { return(await session.ExecuteAsync(new SimpleStatement(query.ToString()))); } catch (InvalidQueryException ex) { if (ex.Message.StartsWith("Keyspace ")) // asumme "Keyspace {name} does not exist" { session.CreateKeyspaceIfNotExists(GetKeyspaceName(serviceId)); await CreateTableIfNotExistsAsync(session, GetKeyspaceName(serviceId), GetTableName(serviceId, methodId)); goto TryExecute; } else if (ex.Message.StartsWith("unconfigured table ")) // assume "unconfigured table {name}" { await CreateTableIfNotExistsAsync(session, GetKeyspaceName(serviceId), GetTableName(serviceId, methodId)); goto TryExecute; } else { throw; } } }
public async Task <InvokeRoutineResult> GetInvocationResultAsync( ServiceId serviceId, MethodId methodId, string intentId, Type resultValueType, CancellationToken ct) { var storage = _methodStateStorageProvider.GetStorage(serviceId, methodId, returnNullIfNotFound: true); if (storage == null) { return(new InvokeRoutineResult { Outcome = InvocationOutcome.Unknown }); } var taskResult = await storage.TryReadResultAsync(serviceId, methodId, intentId, resultValueType, ct); return(new InvokeRoutineResult { Result = taskResult, Outcome = taskResult != null ? InvocationOutcome.Complete : InvocationOutcome.Scheduled }); }
private string GetTableName(ServiceId serviceId, MethodId methodId) { return(_settings.TableName .Replace("{serviceName}", serviceId.Name) .Replace("{methodName}", methodId.Name) .ToLowerInvariant()); }
public Task WriteResultAsync(ServiceId serviceId, MethodId methodId, string intentId, ITaskResult result) { var serializedTaskResult = _serializer.SerializeToString(result); var expectedETag = (methodId as PersistedMethodId)?.ETag; lock (_entryMap) { if (!_entryMap.TryGetValue(intentId, out var entry)) { entry = new StorageEntry(); _entryMap.Add(intentId, entry); } else if (!string.IsNullOrEmpty(expectedETag) && entry.ETag != expectedETag) { throw new ETagMismatchException(expectedETag, entry.ETag); } entry["ServiceId"] = serviceId.Clone(); entry["MethodId"] = methodId.Clone(); entry["Result"] = serializedTaskResult; entry.ETag = DateTimeOffset.UtcNow.Ticks.ToString(); } return(Task.CompletedTask); }
private ServiceAndMethodDefinitions Resolve(ServiceId serviceId, MethodId methodId, bool assumeExternal = false) { var result = new ServiceAndMethodDefinitions(); if (_serviceResolver.TryResolve(serviceId, out var serviceRef)) { result.Service = serviceRef.Definition; // NOTE: system services are not unique within a multi-service ecosystem, thus must // use the configuration of the calling (proxy) service without any specific method. // Otherwise, a continuation can be sent to a wrong instance of a system service. if (result.Service.Type == ServiceType.System && !string.IsNullOrEmpty(serviceId.Proxy)) { return(Resolve(new ServiceId { Name = serviceId.Proxy }, null, assumeExternal)); } result.Method = methodId == null ? null : _methodResolver.Resolve(result.Service, methodId).Definition; } else if (assumeExternal) { var externalServiceDefinition = _externalCommunicationModel.GetOrAddService(serviceId); var externalMethodDefinition = methodId == null ? null : externalServiceDefinition.GetOrAddMethod(methodId); result.Service = externalServiceDefinition; result.Method = externalMethodDefinition; } else { throw new ServiceResolveException(serviceId); } return(result); }
public long NotifyOnCompletion(ServiceId serviceId, MethodId methodId, string intentId, TaskCompletionSource <ITaskResult> completionSink, CancellationToken ct) { if (ct.IsCancellationRequested) { return(-1); } var trackedInvocation = new TrackedInvocation { Token = Interlocked.Increment(ref _tokenCounter), ServiceId = serviceId, MethodId = methodId, IntentId = intentId, CompletionSink = completionSink, CancellationToken = ct }; SetPollingMethod(trackedInvocation); LinkedListNode <TrackedInvocation> listNode; lock (_trackedInvocations) { listNode = _trackedInvocations.AddLast(trackedInvocation); } trackedInvocation.PollTimer = new Timer(_onTimerTick, listNode, Timeout.Infinite, Timeout.Infinite); ScheduleNextPoll(trackedInvocation); return(trackedInvocation.Token); }
public jvmtiError GetBytecodes(MethodId methodId, out byte[] bytecode) { bytecode = null; int bytecodeCount; IntPtr bytecodePtr; jvmtiError error = RawInterface.GetBytecodes(this, methodId, out bytecodeCount, out bytecodePtr); if (error != jvmtiError.None) { return(error); } try { if (bytecodeCount > 0) { bytecode = new byte[bytecodeCount]; Marshal.Copy(bytecodePtr, bytecode, 0, bytecodeCount); } } finally { Deallocate(bytecodePtr); } return(jvmtiError.None); }
/// <summary> /// Returns variable information for the method, including generic signatures for the variables. The variable table includes arguments and /// locals declared within the method. For instance methods, the "this" reference is included in the table. Also, synthetic variables may be /// present. Generic signatures are described in the signature attribute section in the Java Virtual Machine Specification, 3rd Edition. /// Since JDWP version 1.5. /// </summary> public Task<List<VariableInfo>> VariableTableWithGenericAsync(ReferenceTypeId typeId, MethodId methodId) { var conn = ConnectionOrError; var t = conn.SendAsync(JdwpPacket.CreateCommand(conn, Nr, 5, typeId.Size + methodId.Size, x => { var data = x.Data; typeId.WriteTo(data); methodId.WriteTo(data); })); return t.ContinueWith(x => { x.ForwardException(); var result = x.Result; result.ThrowOnError(); var data = result.Data; var argCnt = data.GetInt(); var count = data.GetInt(); var list = new List<VariableInfo>(count); for (var i = 0; i < count; i++ ) { var codeIndex = data.GetLong(); var name = data.GetString(); var signature = data.GetString(); var genericSignature = data.GetString(); var length = data.GetInt(); var slot = data.GetInt(); list.Add(new VariableInfo(codeIndex, name, signature, genericSignature, length, slot)); } return list; }); }
public override int GetHashCode() { int hash = 1; if (ServiceId.Length != 0) { hash ^= ServiceId.GetHashCode(); } if (ServiceAliasId.Length != 0) { hash ^= ServiceAliasId.GetHashCode(); } if (MethodId.Length != 0) { hash ^= MethodId.GetHashCode(); } if (source_ != null) { hash ^= Source.GetHashCode(); } if (target_ != null) { hash ^= Target.GetHashCode(); } if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return(hash); }
// Get the latest just before or after the time t private ByteArray GetHashForDate(MethodId methodId, DateTime t, bool afterT) { if (this.cacheAccessor == null) { return(null); } return(this.cacheAccessor.GetHashForDate(methodId, t, afterT)); }
public DeclaredMethodData(MethodId methodId, string name, string signature, string genericSignature, AccessModifiers modifiers) { MethodId = methodId; Name = name; Signature = signature; GenericSignature = genericSignature; Modifiers = modifiers; }
internal T InvokeResultProvider <T>( object instance, MethodId method, Func <IDkmClrResultProvider, T> f ) { return(_resultProviders.Invoke(instance, method, f)); }
public Method(MethodId id, List <Instruction> instructions, IEnumerable <InstructionId> initialInstructions) { Id = id; Instructions = instructions ?? throw new ArgumentNullException(); var cont = new Continuation(); cont.NextInstructions.AddRange(initialInstructions ?? throw new ArgumentNullException()); InitialInstructions = cont; }
public Method(MethodId id, InstructionBlock instructionBlock = null) { Id = id; Instructions = new List <Instruction>(); InitialInstructions = new Continuation(); if (instructionBlock != null) { FillWithInstructions(instructionBlock); } }
public static Class getPrimitiveClass(string name) { JNIEnv env = JNIEnv.ThreadEnv; MethodId id = env.GetStaticMethodID(staticClass, "getPrimitiveClass", "(Ljava/lang/String;)Ljava/lang/Class;"); return(Convertor.StrongJ2CpClass(env, env.CallStaticObjectMethodPtr(staticClass, id, Convertor.ParStrongC2JString(env, name)))); }
public Method GetMethodNoThrow(string name, string signature, bool isStatic) { MethodId methodId = Env.GetMethodIDNoThrow(this, name, signature); if (methodId == null) { return(null); } return(Env.ToReflectedMethod(this, methodId, isStatic)); }
public override int GetHashCode() { unchecked { var hashCode = (MethodId != null ? MethodId.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (MethodTitle != null ? MethodTitle.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (InputMessageId != null ? InputMessageId.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (OutputMessageId != null ? OutputMessageId.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (int)MethodType; return(hashCode); } }
public override int GetHashCode() { unchecked { var hashCode = (ServiceId != null ? ServiceId.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (MethodId != null ? MethodId.GetHashCode() : 0); hashCode = (hashCode * 397) ^ ServiceAlias.GetHashCode(); hashCode = (hashCode * 397) ^ (ConsumerApplicationId != null ? ConsumerApplicationId.GetHashCode() : 0); hashCode = (hashCode * 397) ^ ConsumerConnectionId.GetHashCode(); hashCode = (hashCode * 397) ^ ConsumerApplicationInstanceId.GetHashCode(); return(hashCode); } }
public void ToMemberId_returns_the_expected_value_01() { // ARRANGE var expectedMemberId = new MethodId(s_TypeId_Class1, "Method1"); var methodReference = m_Class1.Methods.Single(x => x.Name == "Method1"); // ACT var actualMemberId = methodReference.ToMemberId(); // ASSERT Assert.Equal(expectedMemberId, actualMemberId); }
public async Task <ITaskResult> TryPollCompletionAsync(ServiceId serviceId, MethodId methodId, string intentId, CancellationToken ct) { LinkedListNode <TrackedInvocation> existingListNode = null; lock (_trackedInvocations) { for (var node = _trackedInvocations.First; node != null; node = node.Next) { if (node.Value.IntentId == intentId && node.Value.ServiceId == serviceId && node.Value.MethodId == methodId) { existingListNode = node; break; } } } TrackedInvocation trackedInvocation; if (existingListNode != null) { trackedInvocation = existingListNode.Value; } else { trackedInvocation = new TrackedInvocation { Token = -1, ServiceId = serviceId, MethodId = methodId, IntentId = intentId, CompletionSink = new TaskCompletionSource <ITaskResult>(), CancellationToken = ct }; SetPollingMethod(trackedInvocation); } if (!await PollAsync(trackedInvocation)) { return(null); } if (existingListNode != null) { StopTracking(existingListNode); } return(trackedInvocation.CompletionSink.Task.Result); }
private static MethodId GetJVMConstructor(JNIEnv env, Class proxy) { MethodId jvmConstructor = env.GetMethodIDNoThrow(proxy, "<init>", "(Lnet/sf/jni4net/inj/INJEnv;J)V"); if (jvmConstructor == null) { if (Bridge.Setup.Verbose) { Console.WriteLine("Can't find java constructor for " + proxy); } throw new JNIException("Can't find java constructor for " + proxy); } return(jvmConstructor); }
public jvmtiError IsMethodNative(MethodId methodId, out bool result) { result = false; byte native; jvmtiError error = RawInterface.IsMethodNative(this, methodId, out native); if (error != jvmtiError.None) { return(error); } result = native != 0; return(jvmtiError.None); }
public jvmtiError GetMethodDeclaringClass(JniEnvironment nativeEnvironment, MethodId methodId, out TaggedReferenceTypeId declaringClass) { declaringClass = default(TaggedReferenceTypeId); jclass classHandle; jvmtiError error = RawInterface.GetMethodDeclaringClass(this, (jmethodID)methodId, out classHandle); if (error != jvmtiError.None) { return(error); } declaringClass = VirtualMachine.TrackLocalClassReference(classHandle, this, nativeEnvironment, true); return(jvmtiError.None); }
private static void RegisterTypeOf(RegistryRecord record, JNIEnv env) { MethodId constructor = knownCLR[typeof(Type)].JVMConstructor; var h = new Value { _long = IntHandle.Alloc(record.CLRInterface) }; var clazz = Type_._class.jvmHandle; var typeInfo = new Value { _object = env.NewObjectPtr(clazz, constructor, Value.Null, h) }; env.CallStaticVoidMethod(record.JVMStatic, "InitJNI", "(Lnet/sf/jni4net/inj/INJEnv;Lsystem/Type;)V", new[] { Value.Null, typeInfo }); //record.JVMStatic.Invoke("InitJNI", "(Lnet/sf/jni4net/inj/INJEnv;Lsystem/Type;)V", null, record.CLRInterface); }
public IExternalMethodDefinition GetOrAddMethod(MethodId methodId) { lock (_methods) { var existingDefinition = FindMethod(methodId.Name); if (existingDefinition != null) { return((IExternalMethodDefinition)existingDefinition); } var newDefinition = new ExternalMethodDefinition(this, methodId); _methods.Add(newDefinition); return(newDefinition); } }
public void UpdateMethodBody(IMethodHolder <Node> owner, MethodId id, INodeBasedProgram <int> body) { var method = myProgram.GetOrCreateMethod(owner, id.Value); var mapper = GetLocalMapper(method); var identity = new IdentityTransducer <Node>(); var invocationsResolver = new InvocationsResolvingTransducer <Node>(); var assignmentsResolver = new AssignmentsResolvingTransducer <Node>(); var transducer = assignmentsResolver.Compose(invocationsResolver).Compose(identity); transducer.Transform(body, myProgram, method, mapper); //myProgram.DumpToDot("C:/work/graph.dot"); }
/// <summary> /// Try to get a type and method ID from the given node. /// </summary> private static bool TryGetTypeAndMethodId(TreeNode node, out ReferenceTypeId typeId, out MethodId methodId) { typeId = null; methodId = null; if (node == null) return false; var tag = node.Tag; if (tag is DalvikStackFrame) { typeId = ((DalvikStackFrame) tag).Location.Class; methodId = ((DalvikStackFrame) tag).Location.Method; } else if (tag is MethodInfo) { methodId = ((MethodInfo) tag).Id; TryGetTypeId(node.Parent, out typeId); } return (methodId != null) && (typeId != null); }
private void HandleBreakpoint(jvmtiEnvHandle env, JNIEnvHandle jniEnv, jthread threadHandle, jmethodID methodId, jlocation jlocation) { if (!VirtualMachine.IsAgentThread.Value) { // ignore events before VMInit if (AgentEventDispatcher == null) return; // dispatch this call to an agent thread Action<jvmtiEnvHandle, JNIEnvHandle, jthread, jmethodID, jlocation> invokeMethod = HandleBreakpoint; AgentEventDispatcher.Invoke(invokeMethod, env, jniEnv, threadHandle, methodId, jlocation); return; } JvmtiEnvironment environment = JvmtiEnvironment.GetOrCreateInstance(_service.VirtualMachine, env); JniEnvironment nativeEnvironment; JniErrorHandler.ThrowOnFailure(VirtualMachine.AttachCurrentThreadAsDaemon(environment, out nativeEnvironment, false)); ThreadId threadId = VirtualMachine.TrackLocalThreadReference(threadHandle, environment, nativeEnvironment, false); TaggedReferenceTypeId declaringClass; MethodId method = new MethodId(methodId.Handle); ulong index = (ulong)jlocation.Value; JvmtiErrorHandler.ThrowOnFailure(environment.GetMethodDeclaringClass(nativeEnvironment, method, out declaringClass)); Location location = new Location(declaringClass, method, index); EventFilter[] filters = GetEventFilters(EventKind.Breakpoint); foreach (var filter in filters) { if (filter.ProcessEvent(environment, nativeEnvironment, this, threadId, default(TaggedReferenceTypeId), location)) { ApplySuspendPolicy(environment, nativeEnvironment, filter.SuspendPolicy, threadId); Callback.Breakpoint(filter.SuspendPolicy, filter.RequestId, threadId, location); } } }
public Error InvokeObjectMethod(out Value returnValue, out TaggedObjectId thrownException, ObjectId @object, ThreadId thread, ClassId @class, MethodId method, InvokeOptions options, Value[] arguments) { if (thread == default(ThreadId)) throw new ArgumentException(); byte[] packet = new byte[HeaderSize + ObjectIdSize + ThreadIdSize + ClassIdSize + MethodIdSize + sizeof(int)]; WriteObjectId(packet, HeaderSize, @object); WriteObjectId(packet, HeaderSize + ObjectIdSize, thread); WriteReferenceTypeId(packet, HeaderSize + ObjectIdSize + ThreadIdSize, @class); WriteMethodId(packet, HeaderSize + ObjectIdSize + ThreadIdSize + ClassIdSize, method); WriteInt32(packet, HeaderSize + ObjectIdSize + ThreadIdSize + ClassIdSize + MethodIdSize, arguments.Length); List<byte> packetData = new List<byte>(packet); foreach (Value argument in arguments) { switch (argument.Tag) { case Tag.Byte: throw new NotImplementedException(); case Tag.Char: throw new NotImplementedException(); case Tag.Float: throw new NotImplementedException(); case Tag.Double: throw new NotImplementedException(); case Tag.Int: throw new NotImplementedException(); case Tag.Long: throw new NotImplementedException(); case Tag.Short: throw new NotImplementedException(); case Tag.Boolean: throw new NotImplementedException(); case Tag.Array: case Tag.Object: case Tag.String: case Tag.Thread: case Tag.ThreadGroup: case Tag.ClassLoader: case Tag.ClassObject: throw new NotImplementedException(); case Tag.Void: throw new NotImplementedException(); case Tag.Invalid: default: throw new InvalidOperationException(); } } byte[] optionsData = new byte[sizeof(int)]; WriteInt32(optionsData, 0, (int)options); packetData.AddRange(optionsData); packet = packetData.ToArray(); int id = GetMessageId(); SerializeHeader(packet, id, ObjectReferenceCommand.InvokeMethod); byte[] response = SendPacket(id, packet); Error errorCode = ReadErrorCode(response); if (errorCode != Error.None) { returnValue = default(Value); thrownException = default(TaggedObjectId); return errorCode; } int offset = HeaderSize; returnValue = ReadValue(response, ref offset); thrownException = ReadTaggedObjectId(response, ref offset); return Error.None; }
/// <summary> /// Default ctor /// </summary> internal DalvikMethod(DalvikReferenceType declaringType, MethodInfo info) { Id = info.Id; this.declaringType = declaringType; this.info = info; }
public Error GetMethodExceptionTable(ReferenceTypeId referenceType, MethodId methodId, out ExceptionTableEntry[] entries) { entries = null; JniEnvironment nativeEnvironment; JvmtiEnvironment environment; jvmtiError error = GetEnvironment(out environment, out nativeEnvironment); if (error != jvmtiError.None) return GetStandardError(error); using (var classHandle = VirtualMachine.GetLocalReferenceForClass(nativeEnvironment, referenceType)) { if (!classHandle.IsAlive) return Error.InvalidClass; bool native; error = environment.IsMethodNative(methodId, out native); if (error != jvmtiError.None) return GetStandardError(error); if (native) return Error.NativeMethod; JvmAccessModifiers modifiers; error = environment.GetMethodModifiers(methodId, out modifiers); if (error != jvmtiError.None) return GetStandardError(error); if ((modifiers & JvmAccessModifiers.Abstract) != 0) return Error.AbsentInformation; string classSignature; string classGenericSignature; error = environment.GetClassSignature(classHandle.Value, out classSignature, out classGenericSignature); if (error != jvmtiError.None) return GetStandardError(error); string methodName; string methodSignature; string methodGenericSignature; error = environment.GetMethodName(methodId, out methodName, out methodSignature, out methodGenericSignature); if (error != jvmtiError.None) return GetStandardError(error); jobject classLoader; error = environment.GetClassLoader(classHandle.Value, out classLoader); if (error != jvmtiError.None) return GetStandardError(error); long classLoaderTag; error = environment.TagClassLoader(classLoader, out classLoaderTag); if (error != jvmtiError.None) return GetStandardError(error); ReadOnlyCollection<ExceptionTableEntry> exceptionTable; error = environment.VirtualMachine.GetExceptionTable(classLoaderTag, classSignature, methodName, methodSignature, out exceptionTable); if (error != jvmtiError.None) return GetStandardError(error); entries = exceptionTable.ToArray(); return Error.None; } }
internal Method GetMirrorOf(ReferenceType declaringType, MethodId methodId) { IEnumerable<Method> methods = declaringType.GetMethods(false).Cast<Method>(); return methods.FirstOrDefault(i => i.MethodId == methodId); }
private void HandleFramePop(jvmtiEnvHandle env, JNIEnvHandle jniEnv, jthread threadHandle, jmethodID methodId, bool wasPoppedByException) { try { JvmtiEnvironment environment = JvmtiEnvironment.GetOrCreateInstance(_service.VirtualMachine, env); JniEnvironment nativeEnvironment = JniEnvironment.GetOrCreateInstance(jniEnv); TaggedReferenceTypeId declaringClass; MethodId method = new MethodId(methodId.Handle); jlocation jlocation; JvmtiErrorHandler.ThrowOnFailure(environment.GetFrameLocation(threadHandle, 1, out methodId, out jlocation)); ulong index = (ulong)jlocation.Value; JvmtiErrorHandler.ThrowOnFailure(environment.GetMethodDeclaringClass(nativeEnvironment, method, out declaringClass)); Location location = new Location(declaringClass, method, index); ThreadId threadId = VirtualMachine.TrackLocalThreadReference(threadHandle, environment, nativeEnvironment, false); EventFilter[] filters = GetEventFilters(EventKind.FramePop); foreach (var filter in filters) { if (filter.ProcessEvent(environment, nativeEnvironment, this, threadId, default(TaggedReferenceTypeId), location)) { if (filter.InternalEventKind == EventKind.SingleStep) { // remove the frame pop event JvmtiErrorHandler.ThrowOnFailure((jvmtiError)ClearEventInternal(EventKind.FramePop, filter.RequestId)); // set an actual step filter to respond when the thread arrives in the parent frame JvmtiErrorHandler.ThrowOnFailure((jvmtiError)SetEventInternal(environment, nativeEnvironment, EventKind.SingleStep, filter)); } else { SendFramePopEvent(environment, filter, threadId, location, wasPoppedByException); } } } } catch (Exception e) { string caption = "Exception while handling a frame pop event"; System.Windows.Forms.MessageBox.Show(e.Message + System.Environment.NewLine + System.Environment.NewLine + e.StackTrace, caption, MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1); throw; } }
private static void CheckExpectedHandler(Message0 msg, MethodId expectedHandler) { Assert.AreEqual( msg.HandledBy, expectedHandler ); }
public Error GetMethodVariableTable(out VariableData[] slots, ReferenceTypeId referenceType, MethodId method) { byte[] packet = new byte[HeaderSize + ReferenceTypeIdSize + MethodIdSize]; int id = GetMessageId(); SerializeHeader(packet, id, MethodCommand.VariableTableWithGeneric); WriteReferenceTypeId(packet, HeaderSize, referenceType); WriteMethodId(packet, HeaderSize + ReferenceTypeIdSize, method); byte[] response = SendPacket(id, packet); Error errorCode = ReadErrorCode(response); if (errorCode != Error.None) { slots = null; return errorCode; } int offset = HeaderSize; int argumentCount = ReadInt32(response, ref offset); int slotCount = ReadInt32(response, ref offset); slots = new VariableData[slotCount]; for (int i = 0; i < slotCount; i++) { ulong codeIndex = ReadUInt64(response, ref offset); string name = ReadString(response, ref offset); string signature = ReadString(response, ref offset); string genericSignature = ReadString(response, ref offset); uint length = ReadUInt32(response, ref offset); int slot = ReadInt32(response, ref offset); slots[i] = new VariableData(slot, codeIndex, length, name, signature, genericSignature); } return Error.None; }
private static void TestSenderMessage( IMessageHandler handler, Message0 msg, MethodId expectedHandler ) { handler.HandleMessage( msg ); CheckExpectedHandler( msg, expectedHandler ); }
public Error GetMethodBytecodes(out byte[] bytecode, ReferenceTypeId referenceType, MethodId method) { byte[] packet = new byte[HeaderSize + ReferenceTypeIdSize + MethodIdSize]; int id = GetMessageId(); SerializeHeader(packet, id, MethodCommand.Bytecodes); WriteReferenceTypeId(packet, HeaderSize, referenceType); WriteMethodId(packet, HeaderSize + ReferenceTypeIdSize, method); byte[] response = SendPacket(id, packet); Error errorCode = ReadErrorCode(response); if (errorCode != Error.None) { bytecode = null; return errorCode; } int offset = HeaderSize; int bytes = ReadInt32(response, ref offset); bytecode = new byte[bytes]; Buffer.BlockCopy(response, offset, bytecode, 0, bytes); return Error.None; }
public Error GetMethodVariableTable(ReferenceTypeId referenceType, MethodId method, out VariableData[] slots) { slots = null; JniEnvironment nativeEnvironment; JvmtiEnvironment environment; jvmtiError error = GetEnvironment(out environment, out nativeEnvironment); if (error != jvmtiError.None) return GetStandardError(error); error = environment.GetLocalVariableTable(method, out slots); return GetStandardError(error); }
public Error GetMethodBytecodes(ReferenceTypeId referenceType, MethodId method, out byte[] bytecode) { bytecode = null; JniEnvironment nativeEnvironment; JvmtiEnvironment environment; jvmtiError error = GetEnvironment(out environment, out nativeEnvironment); if (error != jvmtiError.None) return GetStandardError(error); error = environment.GetBytecodes(method, out bytecode); return GetStandardError(error); }
public Location(TaggedReferenceTypeId declaringClass, MethodId method, ulong index) : this(declaringClass.TypeTag, (ClassId)declaringClass.TypeId, method, index) { }
private void WriteMethodId(byte[] packet, int offset, MethodId methodId) { if (!_methodIdSize.HasValue) throw new InvalidOperationException(); switch (_methodIdSize.Value) { case 2: WriteInt16(packet, offset, (short)methodId.Handle); break; case 4: WriteInt32(packet, offset, (int)methodId.Handle); break; case 8: WriteInt64(packet, offset, methodId.Handle); break; default: throw new NotImplementedException(); } }
private void HandleException(jvmtiEnvHandle env, JNIEnvHandle jniEnv, jthread threadHandle, jmethodID methodId, jlocation jlocation, jobject exceptionHandle, jmethodID catchMethodId, jlocation catchjLocation) { // don't send exception events from an agent thread if (VirtualMachine.IsAgentThread.Value) return; JvmtiEnvironment environment = JvmtiEnvironment.GetOrCreateInstance(_service.VirtualMachine, env); JniEnvironment nativeEnvironment = JniEnvironment.GetOrCreateInstance(jniEnv); TaggedReferenceTypeId declaringClass; MethodId method = new MethodId(methodId.Handle); ulong index = (ulong)jlocation.Value; JvmtiErrorHandler.ThrowOnFailure(environment.GetMethodDeclaringClass(nativeEnvironment, method, out declaringClass)); Location location = new Location(declaringClass, method, index); Location catchLocation; method = new MethodId(catchMethodId.Handle); index = (ulong)catchjLocation.Value; if (catchMethodId.Handle != IntPtr.Zero) { JvmtiErrorHandler.ThrowOnFailure(environment.GetMethodDeclaringClass(nativeEnvironment, method, out declaringClass)); catchLocation = new Location(declaringClass, method, index); } else { catchLocation = default(Location); } TaggedObjectId exceptionId = VirtualMachine.TrackLocalObjectReference(exceptionHandle, environment, nativeEnvironment, false); ThreadId threadId = VirtualMachine.TrackLocalThreadReference(threadHandle, environment, nativeEnvironment, false); EventFilter[] filters = GetEventFilters(EventKind.Exception); foreach (var filter in filters) { if (filter.ProcessEvent(environment, nativeEnvironment, this, threadId, default(TaggedReferenceTypeId), location)) { SendExceptionEvent(environment, filter, threadId, location, exceptionId, catchLocation); } } ////Location location = new Location(); ////Location catchLocation = new Location(); //throw new NotImplementedException(); #if false ThreadId threadId = GetObjectId(ref threadHandle); TaggedObjectId exception = GetObjectId(ref exceptionHandle); EventFilter[] filters = GetEventFilters(EventKind.Exception); foreach (var filter in filters) { if (filter.ProcessEvent(threadId, default(TaggedReferenceTypeId))) { ApplySuspendPolicy(environment, filter.SuspendPolicy, threadId); Callback.HandleException(filter.SuspendPolicy, filter.RequestId, threadId, location, exception, catchLocation); } } #endif //JvmEnvironment environment = JvmEnvironment.GetEnvironment(env); //JvmThreadReference thread = JvmThreadReference.FromHandle(environment, jniEnv, threadHandle, true); //JvmLocation location = new JvmLocation(environment, method, jlocation); //JvmObjectReference exception = JvmObjectReference.FromHandle(environment, jniEnv, exceptionHandle, true); //JvmLocation catchLocation = new JvmLocation(environment, catchMethod, catchjLocation); //foreach (var processor in _processors) //{ // processor.HandleException(environment, thread, location, exception, catchLocation); //} }
public Error GetMethodLineTable(out long start, out long end, out LineNumberData[] lines, ReferenceTypeId referenceType, MethodId method) { byte[] packet = new byte[HeaderSize + ReferenceTypeIdSize + MethodIdSize]; int id = GetMessageId(); SerializeHeader(packet, id, MethodCommand.LineTable); WriteReferenceTypeId(packet, HeaderSize, referenceType); WriteMethodId(packet, HeaderSize + ReferenceTypeIdSize, method); byte[] response = SendPacket(id, packet); Error errorCode = ReadErrorCode(response); if (errorCode != Error.None) { start = 0; end = 0; lines = null; return errorCode; } int offset = HeaderSize; start = ReadInt64(response, ref offset); end = ReadInt64(response, ref offset); int lineCount = ReadInt32(response, ref offset); lines = new LineNumberData[lineCount]; for (int i = 0; i < lineCount; i++) { long lineCodeIndex = ReadInt64(response, ref offset); int lineNumber = ReadInt32(response, ref offset); lines[i] = new LineNumberData(lineCodeIndex, lineNumber); } return Error.None; }
private void HandleSingleStep(jvmtiEnvHandle env, JNIEnvHandle jniEnv, jthread threadHandle, jmethodID methodId, jlocation jlocation) { JvmtiEnvironment environment = JvmtiEnvironment.GetOrCreateInstance(_service.VirtualMachine, env); JniEnvironment nativeEnvironment = JniEnvironment.GetOrCreateInstance(jniEnv); ThreadId threadId = VirtualMachine.TrackLocalThreadReference(threadHandle, environment, nativeEnvironment, false); TaggedReferenceTypeId declaringClass; MethodId method = new MethodId(methodId.Handle); ulong index = (ulong)jlocation.Value; JvmtiErrorHandler.ThrowOnFailure(environment.GetMethodDeclaringClass(nativeEnvironment, method, out declaringClass)); Location location = new Location(declaringClass, method, index); EventFilter[] filters = GetEventFilters(EventKind.SingleStep); foreach (var filter in filters) { if (filter.ProcessEvent(environment, nativeEnvironment, this, threadId, default(TaggedReferenceTypeId), location)) { SendSingleStepEvent(environment, filter, threadId, location); } } }
private static void TestHubMessage( IMessageHub hub, Message0 msg, MethodId expectedHandler ) { hub.DeliverMessageToRecipients( msg ); CheckExpectedHandler( msg, expectedHandler ); }
public Error InvokeClassMethod(ClassId @class, ThreadId thread, MethodId method, InvokeOptions options, Value[] arguments, out Value returnValue, out TaggedObjectId thrownException) { returnValue = default(Value); thrownException = default(TaggedObjectId); JniEnvironment nativeEnvironment; JvmtiEnvironment environment; jvmtiError error = GetEnvironment(out environment, out nativeEnvironment); if (error != jvmtiError.None) return GetStandardError(error); string name; string signature; string genericSignature; error = environment.GetMethodName(method, out name, out signature, out genericSignature); if (error != jvmtiError.None) return GetStandardError(error); if (thread != default(ThreadId)) throw new NotImplementedException(); List<string> argumentTypeSignatures; string returnTypeSignature; SignatureHelper.ParseMethodSignature(signature, out argumentTypeSignatures, out returnTypeSignature); using (var classHandle = VirtualMachine.GetLocalReferenceForClass(nativeEnvironment, @class)) { if (!classHandle.IsAlive) return Error.InvalidClass; // don't do argument conversion if the signature is invalid switch (returnTypeSignature[0]) { case 'Z': case 'B': case 'C': case 'D': case 'F': case 'I': case 'J': case 'S': case '[': case 'L': break; case 'V': default: return Error.InvalidMethodid; } jvalue[] args = arguments.Select(value => new jvalue(VirtualMachine, environment, nativeEnvironment, value)).ToArray(); switch (returnTypeSignature[0]) { case 'Z': returnValue = nativeEnvironment.CallStaticBooleanMethodA(classHandle.Value, method, args); break; case 'B': returnValue = nativeEnvironment.CallStaticByteMethodA(classHandle.Value, method, args); break; case 'C': returnValue = nativeEnvironment.CallStaticCharMethodA(classHandle.Value, method, args); break; case 'D': returnValue = nativeEnvironment.CallStaticDoubleMethodA(classHandle.Value, method, args); break; case 'F': returnValue = nativeEnvironment.CallStaticFloatMethodA(classHandle.Value, method, args); break; case 'I': returnValue = nativeEnvironment.CallStaticIntMethodA(classHandle.Value, method, args); break; case 'J': returnValue = nativeEnvironment.CallStaticLongMethodA(classHandle.Value, method, args); break; case 'S': returnValue = nativeEnvironment.CallStaticShortMethodA(classHandle.Value, method, args); break; case '[': case 'L': jobject result = nativeEnvironment.CallStaticObjectMethodA(classHandle.Value, method, args); returnValue = VirtualMachine.TrackLocalObjectReference(result, environment, nativeEnvironment, false); VirtualMachine.AddGlobalReference(environment, nativeEnvironment, result); nativeEnvironment.DeleteLocalReference(result); break; case 'V': default: Contract.Assert(false, "not reachable"); break; } if (nativeEnvironment.ExceptionOccurred() != jthrowable.Null) { throw new NotImplementedException(); } for (int i = 0; i < arguments.Length; i++) { switch (arguments[i].Tag) { case Tag.Array: case Tag.Object: case Tag.String: case Tag.Thread: case Tag.ThreadGroup: case Tag.ClassLoader: case Tag.ClassObject: nativeEnvironment.DeleteLocalReference(args[i].ObjectValue); break; default: break; } } return Error.None; } }
public Error GetMethodIsObsolete(ReferenceTypeId referenceType, MethodId method, out bool result) { throw new NotImplementedException(); }
/// <summary> /// Returns information for each method in a reference type. Inherited methods are not included. The list of methods will include constructors /// (identified with the name "<init>"), the initialization method (identified with the name "<clinit>") if present, and any synthetic methods /// created by the compiler. Methods are returned in the order they occur in the class file. /// </summary> public Task<List<MethodInfo>> MethodsAsync(ReferenceTypeId id) { var conn = ConnectionOrError; var sizeInfo = conn.GetIdSizeInfo(); var t = conn.SendAsync(JdwpPacket.CreateCommand(conn, Nr, 15, sizeInfo.ReferenceTypeIdSize, x => id.WriteTo(x.Data))); return t.ContinueWith(x => { x.ForwardException(); var result = x.Result; result.ThrowOnError(); var data = result.Data; var count = data.GetInt(); var list = new List<MethodInfo>(count); for (var i = 0; i < count; i++) { var methodId = new MethodId(data); var name = data.GetString(); var signature = data.GetString(); var genericSignature = data.GetString(); var accessFlags = data.GetInt(); list.Add(new MethodInfo(methodId, name, signature, genericSignature, accessFlags)); } return list; }); }
public Error CreateClassInstance(out TaggedObjectId newObject, out TaggedObjectId thrownException, ClassId @class, ThreadId thread, MethodId method, InvokeOptions options, Value[] arguments) { throw new NotImplementedException(); }
public Error GetMethodLineTable(ReferenceTypeId referenceType, MethodId methodId, out long start, out long end, out LineNumberData[] lines) { start = 0; end = 0; lines = null; JniEnvironment nativeEnvironment; JvmtiEnvironment environment; jvmtiError error = GetEnvironment(out environment, out nativeEnvironment); if (error != jvmtiError.None) return GetStandardError(error); error = environment.GetLineNumberTable(methodId, out lines); if (error != jvmtiError.None) return GetStandardError(error); jlocation startLocation; jlocation endLocation; error = environment.GetMethodLocation(methodId, out startLocation, out endLocation); if (error != jvmtiError.None) return GetStandardError(error); start = startLocation.Value; end = endLocation.Value; return Error.None; }
public Error InvokeClassMethod(out Value returnValue, out TaggedObjectId thrownException, ClassId @class, ThreadId thread, MethodId method, InvokeOptions options, Value[] arguments) { throw new NotImplementedException(); }
public Error GetMethodExceptionTable(out ExceptionTableEntry[] entries, ReferenceTypeId referenceType, MethodId method) { entries = null; return Error.NotImplemented; }
public Error GetMethodIsObsolete(out bool result, ReferenceTypeId referenceType, MethodId method) { byte[] packet = new byte[HeaderSize + ReferenceTypeIdSize + MethodIdSize]; int id = GetMessageId(); SerializeHeader(packet, id, MethodCommand.Bytecodes); WriteReferenceTypeId(packet, HeaderSize, referenceType); WriteMethodId(packet, HeaderSize + ReferenceTypeIdSize, method); byte[] response = SendPacket(id, packet); Error errorCode = ReadErrorCode(response); if (errorCode != Error.None) { result = false; return errorCode; } int offset = HeaderSize; result = ReadByte(response, ref offset) != 0; return Error.None; }