private static void LrpInvoke_Simple_Constructor(int offset, MemoryBuffer buffer, Channel channel) { var component = channel.Simple; buffer.Reset(offset); var result = component.Constructor(); buffer.WriteLocalPointer(result); }
private static void LrpInvoke_LocalServerHandler_BeginLogoutRequest(int offset, MemoryBuffer buffer, Channel channel) { var component = channel.LocalServerHandler; var arg0 = buffer.ReadLocalPointer(); var arg1 = buffer.ReadInt64(); buffer.Reset(offset); component.BeginLogoutRequest(arg0, arg1); }
private static void LrpInvoke_Simple_Inverse(int offset, MemoryBuffer buffer, Channel channel) { var component = channel.Simple; var arg0 = buffer.ReadAString(); buffer.Reset(offset); var result = component.Inverse(arg0); buffer.WriteAString(result); }
private static void LrpInvoke_LocalServerHandler_BeginShutdownConnectionNotification(int offset, MemoryBuffer buffer, Channel channel) { var component = channel.LocalServerHandler; var arg0 = buffer.ReadLocalPointer(); var arg1 = buffer.ReadInt64(); buffer.Reset(offset); component.BeginShutdownConnectionNotification(arg0, arg1); }
private static void LrpInvoke_LocalServerHandler_BeginCurrenciesInfoRequest(int offset, MemoryBuffer buffer, Channel channel) { var component = channel.LocalServerHandler; var arg0 = buffer.ReadLocalPointer(); var arg1 = buffer.ReadInt64(); var arg2 = buffer.ReadAString(); buffer.Reset(offset); component.BeginCurrenciesInfoRequest(arg0, arg1, arg2); }
private static int LrpInvoke_Simple(int offset, int methodId, MemoryBuffer buffer, Channel channel) { if((methodId < 0) || (methodId >= 3)) { return MagicNumbers.LRP_INVALID_METHOD_ID; } gSimpleHandlers[methodId](offset, buffer, channel); return MagicNumbers.S_OK; }
private static void LrpInvoke_Simple_Factorial(int offset, MemoryBuffer buffer, Channel channel) { var component = channel.Simple; var arg0 = buffer.ReadInt32(); var arg1 = default(int); buffer.Reset(offset); var result = component.Factorial(arg0, out arg1); buffer.WriteInt32(arg1); buffer.WriteBoolean(result); }
/// <summary> /// /// </summary> /// <param name="componentId"></param> /// <param name="methodId"></param> /// <param name="data"></param> /// <returns></returns> public unsafe override int Invoke(ushort componentId, ushort methodId, MemoryBuffer data) { var pHeap = data.Heap; var pData = data.Data; var size = data.Position; var capacity = data.Capacity; var result = this.host.Invoke(componentId, methodId, pHeap, &size, &pData, &capacity); data.ReInitialize(capacity, size, pData); return result; }
private static void LrpInvoke_LocalServerHandler_BeginLogonRequest(int offset, MemoryBuffer buffer, Channel channel) { var component = channel.LocalServerHandler; var arg0 = buffer.ReadLocalPointer(); var arg1 = buffer.ReadInt64(); var arg2 = buffer.ReadAString(); var arg3 = buffer.ReadInt32(); var arg4 = buffer.ReadAString(); var arg5 = buffer.ReadAString(); buffer.Reset(offset); component.BeginLogonRequest(arg0, arg1, arg2, arg3, arg4, arg5); }
private static void LrpInvoke_Extended_Do(int offset, MemoryBuffer buffer, Channel channel) { var component = channel.Extended; var arg0 = buffer.ReadInType(); var arg1 = buffer.ReadInOutType(); var arg2 = default(LocalCSharp.OutType); buffer.Reset(offset); var result = component.Do(arg0, ref arg1, out arg2); buffer.WriteInOutType(arg1); buffer.WriteOutType(arg2); buffer.WriteReturnType(result); }
private static void LrpInvoke_Extended_MarketBuy(int offset, MemoryBuffer buffer, Channel channel) { var component = channel.Extended; var arg0 = buffer.ReadAString(); var arg1 = buffer.ReadDouble(); var arg2 = buffer.ReadDouble(); var arg3 = default(double); buffer.Reset(offset); var result = component.MarketBuy(arg0, arg1, ref arg2, out arg3); buffer.WriteDouble(arg2); buffer.WriteDouble(arg3); buffer.WriteInt32(result); }
public static void Throw(System.Int32 status, MemoryBuffer buffer) { if(status >= 0) { return; } if(MagicNumbers.LRP_EXCEPTION != status) { throw new System.Exception("Unexpected exception has been encountered"); } System.Int32 _id = buffer.ReadInt32(); System.String _message = buffer.ReadAString(); throw new System.Exception(_message); }
/// <summary> /// /// </summary> /// <param name="argument"></param> /// <param name="signature"></param> /// <param name="handler"></param> /// <returns></returns> public static int Initialize(string argument, string signature, LocalServerInvokeHandler handler) { var parameters = Parse(argument); var param = new IntPtr(long.Parse(parameters[Param])); var callback = new IntPtr(long.Parse(parameters[Callback])); var func = (CallBackFunc)Marshal.GetDelegateForFunctionPointer(callback, typeof(CallBackFunc)); var invoke = Marshal.GetFunctionPointerForDelegate(handler); var buffer = new MemoryBuffer(); buffer.WriteAString(signature); buffer.WriteAChar('\0'); byte* ptr = (byte*)buffer.Data; ptr += sizeof(int); func(ptr, invoke.ToPointer(), param.ToPointer()); buffer.Free(); return 0; }
public GPU_FloatData(float[] data) { _view = ILGPUMethods.Allocate(data); AxesX = Enumerable.Range(0, data.Length).ToArray(); }
private static void LrpInvoke_LocalServerHandler_BeginUnsubscribeQuotesRequest(int offset, MemoryBuffer buffer, Channel channel) { var component = channel.LocalServerHandler; var arg0 = buffer.ReadLocalPointer(); var arg1 = buffer.ReadInt64(); var arg2 = buffer.ReadAString(); var arg3 = buffer.ReadAStringArray(); buffer.Reset(offset); component.BeginUnsubscribeQuotesRequest(arg0, arg1, arg2, arg3); }
internal void deallocate(MemoryBuffer memoryBuffer) { throw new System.NotImplementedException(); }
/// <summary>Gets informations about this node to show in a tool tip.</summary> /// <param name="spot">The spot.</param> /// <param name="memory">The process memory.</param> /// <returns>The information to show in a tool tip.</returns> public override string GetToolTipText(HotSpot spot, MemoryBuffer memory) { var value = memory.ReadObject <UInt32FloatData>(Offset); return($"Int32: {value.IntValue}\nUInt32: 0x{value.UIntValue:X08}\nFloat: {value.FloatValue:0.000}"); }
public Entry(MemoryBuffer buffer) : this() { this.buffer = buffer; this.syncEvent = new AutoResetEvent(false); }
public static StatusCode UnsecureSymmetric(MemoryBuffer recvBuf, uint tokenID, uint?prevTokenID, int messageEncodedBlockStart, SLChannel.Keyset localKeyset, SLChannel.Keyset[] remoteKeysets, SecurityPolicy policy, MessageSecurityMode securityMode, out int decrSize) { decrSize = -1; int restorePos = recvBuf.Position; byte type = 0; uint messageSize = 0; UInt32 secureChannelId, securityTokenId, securitySeqNum, securityReqId; if (!recvBuf.Decode(out type)) { return(StatusCode.BadDecodingError); } if (!recvBuf.Decode(out messageSize)) { return(StatusCode.BadDecodingError); } if (!recvBuf.Decode(out secureChannelId)) { return(StatusCode.BadDecodingError); } if (!recvBuf.Decode(out securityTokenId)) { return(StatusCode.BadDecodingError); } int keysetIdx = -1; if (tokenID == securityTokenId) { keysetIdx = 0; } else if (prevTokenID.HasValue && prevTokenID.Value == securityTokenId) { keysetIdx = 1; } else { return(StatusCode.BadSecureChannelTokenUnknown); } //UInt32 respDecodeSize = messageSize; if (securityMode == MessageSecurityMode.SignAndEncrypt) { try { decrSize = UASecurity.RijndaelDecryptInplace( new ArraySegment <byte>(recvBuf.Buffer, messageEncodedBlockStart, (int)messageSize - messageEncodedBlockStart), remoteKeysets[keysetIdx].SymEncKey, remoteKeysets[keysetIdx].SymIV) + messageEncodedBlockStart; //respDecodeSize = (UInt32)(messageEncodedBlockStart + decrSize); } catch { return(StatusCode.BadSecurityChecksFailed); } } if (securityMode >= MessageSecurityMode.Sign) { try { int sigSize = SignatureSizeForSecurityPolicy(policy); var sigData = new ArraySegment <byte>(recvBuf.Buffer, 0, (int)messageSize - sigSize); var sig = new ArraySegment <byte>(recvBuf.Buffer, (int)messageSize - sigSize, sigSize).ToArray(); var sigExpect = UASecurity.SymmetricSign(remoteKeysets[keysetIdx].SymSignKey, sigData, policy); if (sig.Length != sigExpect.Length) { return(StatusCode.BadSecurityChecksFailed); } for (int i = 0; i < sig.Length; i++) { if (sig[i] != sigExpect[i]) { return(StatusCode.BadSecurityChecksFailed); } } byte padValue = (byte)(recvBuf.Buffer[messageSize - sigSize - 1] + 1); if (decrSize > 0) { decrSize -= sigSize; decrSize -= (int)padValue; if (decrSize <= 0) { return(StatusCode.BadSecurityChecksFailed); } } } catch { return(StatusCode.BadSecurityChecksFailed); } } if (!recvBuf.Decode(out securitySeqNum)) { return(StatusCode.BadDecodingError); } if (!recvBuf.Decode(out securityReqId)) { return(StatusCode.BadDecodingError); } recvBuf.Position = restorePos; return(StatusCode.Good); }
/// <summary>Gets informations about this node to show in a tool tip.</summary> /// <param name="spot">The spot.</param> /// <param name="memory">The process memory.</param> /// <returns>The information to show in a tool tip.</returns> public override string GetToolTipText(HotSpot spot, MemoryBuffer memory) { var b = memory.ReadByte(Offset); return($"Int8: {(int)b}\nUInt8: 0x{b:X02}"); }
internal static void WheightAdjustment( Action <AcceleratorStream, Index2, ArrayView3D <float>, ArrayView2D <float>, ArrayView2D <float>, ArrayView2D <float>, ArrayView <float> > action, Index2 extent, MemoryBuffer3D <float> weights, MemoryBuffer2D <float> error, MemoryBuffer2D <float> activatedPreviousLayer, MemoryBuffer2D <float> bias, MemoryBuffer <float> variables ) { action(accelerator.DefaultStream, extent, weights, error, activatedPreviousLayer, bias, variables); }
async Task <Result> ClientSingleConnectionAsync(Direction dir, AsyncManualResetEvent fireMeWhenReady, CancellationToken cancel) { Result ret = new Result(); AsyncCleanuperLady lady = new AsyncCleanuperLady(); try { var tcp = new FastPalTcpProtocolStub(lady, cancel: cancel); var sock = await tcp.ConnectAsync(ServerIP, ServerPort, cancel, ConnectTimeout); var app = sock.GetFastAppProtocolStub(); var attachHandle = app.AttachHandle; var st = app.GetStream(); if (dir == Direction.Recv) { app.AttachHandle.SetStreamReceiveTimeout(RecvTimeout); } try { var hello = await st.ReceiveAllAsync(16); Dbg.Where(); if (Encoding.ASCII.GetString(hello.Span).StartsWith("TrafficServer\r\n") == false) { throw new ApplicationException("Target server is not a Traffic Server."); } Dbg.Where(); //throw new ApplicationException("aaaa" + dir.ToString()); fireMeWhenReady.Set(); cancel.ThrowIfCancellationRequested(); await WebSocketHelper.WaitObjectsAsync( manualEvents : ClientStartEvent.ToSingleArray(), cancels : cancel.ToSingleArray() ); long tickStart = FastTick64.Now; long tickEnd = tickStart + this.TimeSpan; var sendData = new MemoryBuffer <byte>(); sendData.WriteBool8(dir == Direction.Recv); sendData.WriteUInt64(SessionId); sendData.WriteSInt64(TimeSpan); await st.SendAsync(sendData); if (dir == Direction.Recv) { RefInt totalRecvSize = new RefInt(); while (true) { long now = FastTick64.Now; if (now >= tickEnd) { break; } await WebSocketHelper.WaitObjectsAsync( tasks : st.FastReceiveAsync(totalRecvSize : totalRecvSize).ToSingleArray(), timeout : (int)(tickEnd - now), exceptions : ExceptionWhen.TaskException | ExceptionWhen.CancelException); ret.NumBytesDownload += totalRecvSize; } } else { attachHandle.SetStreamReceiveTimeout(Timeout.Infinite); while (true) { long now = FastTick64.Now; if (now >= tickEnd) { break; } /*await WebSocketHelper.WaitObjectsAsync( * tasks: st.FastSendAsync(SendData, flush: true).ToSingleArray(), * timeout: (int)(tick_end - now), * exceptions: ExceptionWhen.TaskException | ExceptionWhen.CancelException);*/ await st.FastSendAsync(SendData, flush : true); } Task recvResult = Task.Run(async() => { var recvMemory = await st.ReceiveAllAsync(8); MemoryBuffer <byte> recvMemoryBuf = recvMemory; ret.NumBytesUpload = recvMemoryBuf.ReadSInt64(); st.Disconnect(); }); Task sendSurprise = Task.Run(async() => { byte[] surprise = new byte[260]; surprise.AsSpan().Fill((byte)'!'); while (true) { await st.SendAsync(surprise); await WebSocketHelper.WaitObjectsAsync( manualEvents: sock.Pipe.OnDisconnectedEvent.ToSingleArray(), timeout: 200); } }); await WhenAll.Await(false, recvResult, sendSurprise); await recvResult; } st.Disconnect(); Dbg.Where(); return(ret); } catch (Exception ex) { Dbg.Where(ex.Message); ExceptionQueue.Add(ex); throw; } } finally { await lady; } }
/// <summary> /// Load resource from stream. May be called from a worker thread. Return true if successful. /// </summary> public override bool BeginLoad(MemoryBuffer source) { Runtime.ValidateRefCounted(this); return(Texture2D_BeginLoad_MemoryBuffer(handle, (object)source == null ? IntPtr.Zero : source.Handle)); }
public async Task RunServerAsync() { if (IsServerMode == false) { throw new ApplicationException("Client mode"); } if (Once.IsFirstCall() == false) { throw new ApplicationException("You cannot reuse the object."); } using (var sessions = new GroupManager <ulong, SessionData>( onNewGroup: (key, state) => { Dbg.Where($"New session: {key}"); return(new SessionData()); }, onDeleteGroup: (key, ctx, state) => { Dbg.Where($"Delete session: {key}"); })) { AsyncCleanuperLady glady = new AsyncCleanuperLady(); FastPalTcpListener listener = new FastPalTcpListener(glady, async(lx, sock) => { AsyncCleanuperLady lady = new AsyncCleanuperLady(); try { Console.WriteLine($"Connected {sock.Info.Tcp.RemoteIPAddress}:{sock.Info.Tcp.RemotePort} -> {sock.Info.Tcp.LocalIPAddress}:{sock.Info.Tcp.LocalPort}"); var app = sock.GetFastAppProtocolStub(); var st = app.GetStream(); var attachHandle = app.AttachHandle; attachHandle.SetStreamReceiveTimeout(RecvTimeout); await st.SendAsync(Encoding.ASCII.GetBytes("TrafficServer\r\n\0")); MemoryBuffer <byte> buf = await st.ReceiveAsync(17); Direction dir = buf.ReadBool8() ? Direction.Send : Direction.Recv; ulong sessionId = 0; long timespan = 0; try { sessionId = buf.ReadUInt64(); timespan = buf.ReadSInt64(); } catch { } long recvEndTick = FastTick64.Now + timespan; if (timespan == 0) { recvEndTick = long.MaxValue; } using (var session = sessions.Enter(sessionId)) { using (var delay = new DelayAction(lady, (int)(Math.Min(timespan * 3 + 180 * 1000, int.MaxValue)), x => app.Disconnect(new TimeoutException()))) { if (dir == Direction.Recv) { RefInt refTmp = new RefInt(); long totalSize = 0; while (true) { var ret = await st.FastReceiveAsync(totalRecvSize: refTmp); if (ret.Count == 0) { break; } totalSize += refTmp; if (ret[0].Span[0] == (byte)'!') { break; } if (FastTick64.Now >= recvEndTick) { break; } } attachHandle.SetStreamReceiveTimeout(Timeout.Infinite); attachHandle.SetStreamSendTimeout(60 * 5 * 1000); session.Context.NoMoreData = true; while (true) { MemoryBuffer <byte> sendBuf = new MemoryBuffer <byte>(); sendBuf.WriteSInt64(totalSize); await st.SendAsync(sendBuf); await Task.Delay(100); } } else { attachHandle.SetStreamReceiveTimeout(Timeout.Infinite); attachHandle.SetStreamSendTimeout(Timeout.Infinite); while (true) { if (sessionId == 0 || session.Context.NoMoreData == false) { await st.SendAsync(SendData); } else { var recvMemory = await st.ReceiveAsync(); if (recvMemory.Length == 0) { break; } } } } } } } catch (Exception ex) { WriteLine(ex.GetSingleException().Message); } finally { Dbg.Where(); await lady; Dbg.Where(); } }); try { listener.Add(this.ServerPort, IPVersion.IPv4); listener.Add(this.ServerPort, IPVersion.IPv6); WriteLine("Listening."); await WebSocketHelper.WaitObjectsAsync(cancels : this.Cancel.ToSingleArray()); } finally { await glady; } } }
public static void UpdateTexture(this Texture tex, CLAPI instance, MemoryBuffer buffer, int width, int height) { TextureLoader.Update(tex, CLAPI.ReadBuffer <byte>(instance, buffer, (int)buffer.Size), width, height); }
/// <summary>This method lets ReClass.NET print the name and the value of the node.</summary> public string ReadNodeInfo(BaseNode node, IntPtr value, MemoryBuffer memory) { return($"{node.Name} => {value.ToString("X")}"); }
private static int LrpInvokeEx(int offset, int componentId, int methodId, MemoryBuffer buffer, Channel channel) { if((componentId < 0) || (componentId >= 2)) { return MagicNumbers.LRP_INVALID_COMPONENT_ID; } int result = MagicNumbers.LRP_EXCEPTION; try { try { result = gHandlers[componentId](offset, methodId, buffer, channel); return result; } catch(System.Exception e) { buffer.Reset(offset); buffer.WriteInt32(-1); buffer.WriteAString(e.Message); } } catch(System.Exception) { result = MagicNumbers.E_FAIL; } return result; }
async Task SendLoopAsync() { try { CancellationToken cancel = this.GrandCancel; LocalTimer timer = new LocalTimer(); long nextPingTick = timer.AddTimeout(0); while (true) { await LowerStream.WaitReadyToSendAsync(cancel, Timeout.Infinite); await UpperStream.WaitReadyToReceiveAsync(cancel, timer.GetNextInterval(), noTimeoutException : true, cancelEvent : this.SendPongEvent); MemoryBuffer <byte> sendBuffer = new MemoryBuffer <byte>(); IReadOnlyList <ReadOnlyMemory <byte> > userDataList = UpperStream.FastReceiveNonBlock(out int totalRecvSize, maxSize: Options.MaxBufferSize); if (totalRecvSize >= 1) { // Send data if (Options.RespectMessageDelimiter == false) { userDataList = Util.DefragmentMemoryArrays(userDataList, Options.SendSingleFragmentSize); } foreach (ReadOnlyMemory <byte> userData in userDataList) { if (userData.Length >= 1) { BuildAndAppendFrame(sendBuffer, true, WebSocketOpcode.Bin, userData); } } } if (timer.Now >= nextPingTick) { // Send ping nextPingTick = timer.AddTimeout(Util.GenRandInterval(Options.SendPingInterval)); BuildAndAppendFrame(sendBuffer, true, WebSocketOpcode.Ping, "[WebSocketPing]"._GetBytes_Ascii()); } lock (this.PongQueueLock) { // Send pong while (true) { if (this.PongQueue.TryDequeue(out ReadOnlyMemory <byte> data) == false) { break; } BuildAndAppendFrame(sendBuffer, true, WebSocketOpcode.Pong, data); } } if (sendBuffer.Length >= 1) { LowerStream.FastSendNonBlock(sendBuffer.Memory); } } } catch (Exception ex) { this.UpperStream.Disconnect(); await this.CancelAsync(ex); } }
public ulong ReadValueFromMemory(MemoryBuffer memory) { return(memory.ReadUInt64(Offset)); }
async Task RecvLoopAsync() { try { CancellationToken cancel = this.GrandCancel; LowerStream.ReadTimeout = Options.TimeoutComm; MemoryBuffer <byte> currentRecvingMessage = new MemoryBuffer <byte>(); while (true) { byte b1 = await LowerStream.ReceiveByteAsync(cancel).FlushOtherStreamIfPending(UpperStream); WebSocketOpcode opcode = (WebSocketOpcode)(b1 & 0x0f); byte b2 = await LowerStream.ReceiveByteAsync(cancel); bool isMasked = (b2 & 0b10000000)._ToBool(); int tmp = (b2 & 0b01111111); ulong payloadLen64 = 0; if (tmp <= 125) { payloadLen64 = (ulong)tmp; } else if (tmp == 126) { payloadLen64 = await LowerStream.ReceiveUInt16Async(cancel).FlushOtherStreamIfPending(UpperStream); } else if (tmp == 127) { payloadLen64 = await LowerStream.ReceiveUInt64Async(cancel).FlushOtherStreamIfPending(UpperStream); } if (payloadLen64 > (ulong)Options.RecvMaxPayloadLenPerFrame) { throw new ApplicationException($"payloadLen64 {payloadLen64} > Options.RecvMaxPayloadLenPerFrame {Options.RecvMaxPayloadLenPerFrame}"); } int payloadLen = (int)payloadLen64; Memory <byte> maskKey = default; if (isMasked) { maskKey = await LowerStream.ReceiveAllAsync(4, cancel).FlushOtherStreamIfPending(UpperStream); } Memory <byte> data = await LowerStream.ReceiveAllAsync(payloadLen, cancel).FlushOtherStreamIfPending(UpperStream); if (isMasked) { TaskUtil.Sync(() => { Span <byte> maskKeySpan = maskKey.Span; Span <byte> dataSpan = data.Span; for (int i = 0; i < dataSpan.Length; i++) { dataSpan[i] = (byte)(dataSpan[i] ^ maskKeySpan[i % 4]); } }); } if (opcode.EqualsAny(WebSocketOpcode.Text, WebSocketOpcode.Bin, WebSocketOpcode.Continue)) { if (Options.RespectMessageDelimiter == false) { if (data.Length >= 1) { await UpperStream.WaitReadyToSendAsync(cancel, Timeout.Infinite); UpperStream.FastSendNonBlock(data, false); } } else { bool isFin = (b1 & 0b10000000)._ToBool(); if (isFin && opcode.EqualsAny(WebSocketOpcode.Text, WebSocketOpcode.Bin)) { // Single message if (data.Length >= 1) { await UpperStream.WaitReadyToSendAsync(cancel, Timeout.Infinite); UpperStream.FastSendNonBlock(data, false); } } else if (isFin == false && opcode.EqualsAny(WebSocketOpcode.Text, WebSocketOpcode.Bin)) { // First message currentRecvingMessage.Clear(); if ((currentRecvingMessage.Length + data.Length) >= Options.RecvMaxTotalFragmentSize) { throw new ApplicationException("WebSocket: Exceeding Options.RecvMaxTotalFragmentSize."); } currentRecvingMessage.Write(data); } else if (isFin && opcode == WebSocketOpcode.Continue) { // Final continuous message if ((currentRecvingMessage.Length + data.Length) >= Options.RecvMaxTotalFragmentSize) { throw new ApplicationException("WebSocket: Exceeding Options.RecvMaxTotalFragmentSize."); } currentRecvingMessage.Write(data); if (currentRecvingMessage.Length >= 1) { await UpperStream.WaitReadyToSendAsync(cancel, Timeout.Infinite); UpperStream.FastSendNonBlock(data, false); } currentRecvingMessage.Clear(); } else if (isFin == false && opcode == WebSocketOpcode.Continue) { // Intermediate continuous message if ((currentRecvingMessage.Length + data.Length) >= Options.RecvMaxTotalFragmentSize) { throw new ApplicationException("WebSocket: Exceeding Options.RecvMaxTotalFragmentSize."); } currentRecvingMessage.Write(data); } } } else if (opcode == WebSocketOpcode.Pong) { lock (this.PongQueueLock) { this.PongQueue.Enqueue(data); } this.SendPongEvent.Set(true); } else if (opcode == WebSocketOpcode.Ping) { lock (this.PongQueueLock) { this.PongQueue.Enqueue(data); } this.SendPongEvent.Set(true); } else if (opcode == WebSocketOpcode.Close) { throw new DisconnectedException(); } else { throw new ApplicationException($"WebSocket: Unknown Opcode: {(int)opcode}"); } } } catch (Exception ex) { this.UpperStream.Disconnect(); await this.CancelAsync(ex); } }
internal static void SumError( Action <AcceleratorStream, Index2, ArrayView2D <float>, ArrayView2D <float>, ArrayView3D <float>, ArrayView2D <float>, ArrayView2D <float>, ArrayView <float> > action, Index2 extent, MemoryBuffer2D <float> error, MemoryBuffer2D <float> errorNextLayer, MemoryBuffer3D <float> weightNextLayer, MemoryBuffer2D <float> derived, MemoryBuffer <float> variable ) { action(accelerator.DefaultStream, extent, error, errorNextLayer, weightNextLayer, derived, dummyBuffer2D, variable); }
public static void BuildAndAppendFrame(MemoryBuffer <byte> dest, bool clientMode, WebSocketOpcode opcode, ReadOnlyMemory <byte> data) { // Header byte b0 = (byte)(0b10000000 | (byte)opcode); dest.WriteByte(b0); // Payload size byte b1 = 0; int len = data.Length; if (len <= 125) { b1 = (byte)len; } else if (len <= 65536) { b1 = 126; } else { b1 = 127; } b1 = (byte)(b1 | (clientMode ? 0b10000000 : 0)); dest.WriteByte(b1); if (len <= 125) { } else if (len >= 126 && len <= 65536) { dest.WriteUInt16((ushort)len); } else { dest.WriteUInt64((ulong)len); } if (clientMode) { // Masked data byte[] maskKey = Util.Rand(4); dest.Write(maskKey); byte[] maskedData = new byte[data.Length]; if (data.Length >= 1) { ReadOnlySpan <byte> dataSpan = data.Span; for (int i = 0; i < data.Length; i++) { maskedData[i] = (byte)(dataSpan[i] ^ maskKey[i % 4]); } } dest.Write(maskedData); } else { // Raw data dest.Write(data); } }
public static void Throw(System.Int32 status, MemoryBuffer buffer) { if(status >= 0) { return; } if(MagicNumbers.LRP_EXCEPTION != status) { throw new System.Exception("Unexpected exception has been encountered"); } System.Int32 _id = buffer.ReadInt32(); if(0 == _id) { throw ReadArgumentNullException(buffer); } if(1 == _id) { throw ReadArgumentException(buffer); } if(2 == _id) { throw ReadInvalidHandleException(buffer); } if(3 == _id) { throw ReadRejectException(buffer); } if(4 == _id) { throw ReadTimeoutException(buffer); } if(5 == _id) { throw ReadSendException(buffer); } if(6 == _id) { throw ReadLogoutException(buffer); } if(7 == _id) { throw ReadUnsupportedFeatureException(buffer); } if(8 == _id) { throw ReadRuntimeException(buffer); } System.String _message = buffer.ReadAString(); throw new System.Exception(_message); }
public unsafe int Invoke(ushort componentId, ushort methodId, MemoryBuffer data) { var prolog = new ComponentMethodSize(componentId, methodId, data.Size); this.WriteData(&prolog, sizeof(ComponentMethodSize)); this.WriteData(data.Data, data.Size); var result = this.ReadBuffer(data); return result; }
internal void allocateMultiple(MemoryBuffer[] targetBuffers, int bufferSize) { throw new System.NotImplementedException(); }
/// <summary> /// Reads byte from the specified address. /// </summary> /// <param name="address">The address.</param> /// <param name="bits">The number of bits to interpret.</param> /// <param name="bitsOffset">The offset in bits.</param> /// <returns>Byte read from the specified address.</returns> public byte ReadByte(ulong address, int bits = 8, int bitsOffset = 0) { MemoryBuffer buffer = Debugger.ReadMemory(this, address, 1); return(UserType.ReadByte(buffer, 0, bits, bitsOffset)); }
private static void LrpInvoke_LocalServerHandler_BeginQuotesHistoryMetaInfoFileRequest(int offset, MemoryBuffer buffer, Channel channel) { var component = channel.LocalServerHandler; var arg0 = buffer.ReadLocalPointer(); var arg1 = buffer.ReadInt64(); var arg2 = buffer.ReadAString(); var arg3 = buffer.ReadAString(); var arg4 = buffer.ReadBoolean(); buffer.Reset(offset); component.BeginQuotesHistoryMetaInfoFileRequest(arg0, arg1, arg2, arg3, arg4); }
/// <summary> /// Reads signed byte from the specified address. /// </summary> /// <param name="address">The address.</param> /// <returns>Signed byte read from the specified address.</returns> public sbyte ReadSbyte(ulong address) { MemoryBuffer buffer = Debugger.ReadMemory(this, address, 1); return(UserType.ReadSbyte(buffer, 0)); }
public byte ReadValueFromMemory(MemoryBuffer memory) { return(memory.ReadUInt8(Offset)); }
/// <summary> /// Read unsigned short from the specified address. /// </summary> /// <param name="address">The address.</param> /// <param name="bits">The number of bits to interpret.</param> /// <param name="bitsOffset">The offset in bits.</param> /// <returns>Unsigned short read from the specified address.</returns> public ushort ReadUshort(ulong address, int bits = 16, int bitsOffset = 0) { MemoryBuffer buffer = Debugger.ReadMemory(this, address, 2); return(UserType.ReadUshort(buffer, 0, bits, bitsOffset)); }
public GPU_FloatData(MemoryBuffer <float> data) { _view = data; AxesX = Enumerable.Range(0, data.Length).ToArray(); }
/// <summary> /// See C++ documentation /// </summary> public void DrawTheRootAt(IVwRootBox prootb, IntPtr hdc, Rect rcpDraw, uint bkclr, bool fDrawSel, IVwGraphics pvg, Rect rcSrc, Rect rcDst, int ysTop, int dysHeight) { IVwGraphicsWin32 qvg32 = VwGraphicsWin32Class.Create(); using (Graphics screen = Graphics.FromHdc(hdc)) { Rectangle rcp = rcpDraw; Rectangle rcFill = new Rect(0, 0, rcp.Width, rcp.Height); using (var memoryBuffer = new MemoryBuffer(rcp.Width, rcp.Height)) { memoryBuffer.Graphics.FillRectangle(new SolidBrush(ColorUtil.ConvertBGRtoColor(bkclr)), rcFill); qvg32.Initialize(memoryBuffer.Graphics.GetHdc()); qvg32.XUnitsPerInch = rcDst.right - rcDst.left; qvg32.YUnitsPerInch = rcDst.bottom - rcDst.top; try { prootb.DrawRoot2(qvg32, rcSrc, rcDst, fDrawSel, ysTop, dysHeight); } catch (Exception) { qvg32.ReleaseDC(); throw; } screen.DrawImageUnscaled(memoryBuffer.Bitmap, rcp); qvg32.ReleaseDC(); } } }
public static int LrpInvoke(ushort componentId, ushort methodId, void* heap, int* pSize, void** ppData, int* pCapacity) { try { MemoryBuffer buffer = new MemoryBuffer(heap, *ppData, *pSize, *pCapacity); int result = LrpInvokeEx(0, componentId, methodId, buffer, m_channel); *pSize = buffer.Size; *ppData = buffer.Data; *pCapacity = buffer.Capacity; buffer.Heap = null; return result; } catch(System.Exception) { return MagicNumbers.E_FAIL; } }
/// <summary> /// See C++ documentation /// </summary> public void DrawTheRoot(IVwRootBox prootb, IntPtr hdc, Rect rcpDraw, uint bkclr, bool fDrawSel, IVwRootSite pvrs) { IVwSynchronizer synchronizer = prootb.Synchronizer; if (synchronizer != null) { try { if (synchronizer.IsExpandingLazyItems) { return; } } catch (Exception e) { Console.WriteLine("call to IsExpandingLazyItems caused exceptionException e ={0}", e); } } IVwGraphicsWin32 qvg = VwGraphicsWin32Class.Create(); Rectangle rcp = rcpDraw; using (Graphics screen = Graphics.FromHdc(hdc)) using (var memoryBuffer = new MemoryBuffer(rcp.Width, rcp.Height)) { memoryBuffer.Graphics.FillRectangle(new SolidBrush(ColorUtil.ConvertBGRtoColor(bkclr)), 0, 0, rcp.Width, rcp.Height); qvg.Initialize(memoryBuffer.Graphics.GetHdc()); VwPrepDrawResult xpdr = VwPrepDrawResult.kxpdrAdjust; IVwGraphics qvgDummy = null; try { Rect rcDst, rcSrc; while (xpdr == VwPrepDrawResult.kxpdrAdjust) { pvrs.GetGraphics(prootb, out qvgDummy, out rcSrc, out rcDst); Rectangle temp = rcDst; temp.Offset(-rcp.Left, -rcp.Top); rcDst = temp; qvg.XUnitsPerInch = qvgDummy.XUnitsPerInch; qvg.YUnitsPerInch = qvgDummy.YUnitsPerInch; xpdr = prootb.PrepareToDraw(qvg, rcSrc, rcDst); pvrs.ReleaseGraphics(prootb, qvgDummy); qvgDummy = null; } if (xpdr != VwPrepDrawResult.kxpdrInvalidate) { pvrs.GetGraphics(prootb, out qvgDummy, out rcSrc, out rcDst); Rectangle temp = rcDst; temp.Offset(-rcp.Left, -rcp.Top); rcDst = temp; qvg.XUnitsPerInch = qvgDummy.XUnitsPerInch; qvg.YUnitsPerInch = qvgDummy.YUnitsPerInch; try { prootb.DrawRoot(qvg, rcSrc, rcDst, fDrawSel); } catch (Exception e) { Console.WriteLine("DrawRoot e = {0} qvg = {1} rcSrc = {2} rcDst = {3} fDrawSel = {4}", e, qvg, rcSrc, rcDst, fDrawSel); } pvrs.ReleaseGraphics(prootb, qvgDummy); qvgDummy = null; } } catch (Exception) { if (qvgDummy != null) pvrs.ReleaseGraphics(prootb, qvgDummy); qvg.ReleaseDC(); throw; } if (xpdr != VwPrepDrawResult.kxpdrInvalidate) { screen.DrawImageUnscaled(memoryBuffer.Bitmap, rcp.Left, rcp.Top, rcp.Width, rcp.Height); } qvg.ReleaseDC(); } }
public GPU_FloatData(int size) { _view = ILGPUMethods.Allocate <float>(size); AxesX = Enumerable.Range(0, size).ToArray(); }
internal static void DerivativeFunction( Action <AcceleratorStream, Index2, ArrayView2D <float>, ArrayView2D <float>, ArrayView <float> > action, Index2 extent, MemoryBuffer2D <float> sumInput, MemoryBuffer2D <float> derived, MemoryBuffer <float> variable ) { action(accelerator.DefaultStream, extent, sumInput, derived, variable); }
internal static void NormalizationFunction( Action <AcceleratorStream, Index2, ArrayView2D <float>, ArrayView2D <float>, ArrayView <float> > action, Index2 extent, MemoryBuffer2D <float> outputPreviousLayerActivated, MemoryBuffer2D <float> outputActivated, MemoryBuffer <float> variable ) { action(accelerator.DefaultStream, extent, outputPreviousLayerActivated, outputActivated, variable); }
/// <summary> /// /// </summary> /// <param name="componentId"></param> /// <param name="methodId"></param> /// <param name="data"></param> /// <returns></returns> public abstract int Invoke(ushort componentId, ushort methodId, MemoryBuffer data);
internal static void SumError( Action <AcceleratorStream, Index2, ArrayView2D <float>, ArrayView2D <float>, ArrayView3D <float>, ArrayView2D <float>, ArrayView2D <float>, ArrayView <float> > action, Index2 extent, MemoryBuffer2D <float> error, MemoryBuffer2D <float> activated, MemoryBuffer2D <float> should, MemoryBuffer2D <float> derived, MemoryBuffer <float> variable ) { action(accelerator.DefaultStream, extent, error, activated, dummyBuffer3D, derived, should, variable); }
public void handleCacheCollision(DataCache cache, MemoryBuffer replacementBuffer, List<MemoryBuffer> cacheBuffers) { throw new NotSupportedException(); }
public void Swap(MemoryBuffer buffer) { MemoryBuffer.Swap(this.buffer, buffer); }
public void init(MemoryBuffer buffer, long offset, long end) { this.buffer = buffer; this.offset = offset; this.end = end; }
internal static void SumCalculate( Action <AcceleratorStream, Index2, ArrayView3D <float>, ArrayView2D <float>, ArrayView2D <float>, ArrayView2D <float>, ArrayView <float> > action, Index2 extent, MemoryBuffer3D <float> weights, MemoryBuffer2D <float> outputPreviousLayerActivated, MemoryBuffer2D <float> sumInput, MemoryBuffer2D <float> bias, MemoryBuffer <float> variables ) { action(accelerator.DefaultStream, extent, weights, outputPreviousLayerActivated, sumInput, bias, variables); }
public void setBuffer(MemoryBuffer buffer) { this.buffer = buffer; }
/// <summary> /// Read unsigned integer from the specified address. /// </summary> /// <param name="address">The address.</param> /// <param name="bits">The number of bits to interpret.</param> /// <param name="bitsOffset">The offset in bits.</param> /// <returns>Unsigned integer read from the specified address.</returns> public uint ReadUint(ulong address, int bits = 32, int bitsOffset = 0) { MemoryBuffer buffer = Debugger.ReadMemory(this, address, 4); return(UserType.ReadUint(buffer, 0, bits, bitsOffset)); }
public static void Main2() { using (var context = new Context()) { foreach (var acceleratorId in Accelerator.Accelerators) { if (acceleratorId.AcceleratorType == AcceleratorType.CPU) { continue; } using (var accelerator = Accelerator.Create(context, acceleratorId)) { CompiledKernel compiledKernel; using (Backend b = new CLBackend(context, ILGPU.Runtime.OpenCL.CLAcceleratorVendor.AMD)) { MethodInfo methodInfo = typeof(GPU).GetMethod("PixelKernel"); KernelSpecialization spec = KernelSpecialization.Empty; compiledKernel = b.Compile(EntryPointDescription.FromImplicitlyGroupedKernel(methodInfo), spec); // debug: check kernel.Source for source text } var kernel = accelerator.LoadAutoGroupedKernel(compiledKernel); // var kernel = accelerator.LoadAutoGroupedStreamKernel<Index2, ArrayView2D<FSMUnit>>(MathKernel); // kernel = accelerator.LoadAutoGroupedStreamKernel<Index2, ArrayView2D<Color3>, ArrayView<byte>, ArrayView2D<Neuron>>(PixelKernel); MemoryBuffer2D <Color3> buffer = accelerator.Allocate <Color3>(pixelMap.GetLength(0), pixelMap.GetLength(1)); MemoryBuffer <byte> buffer2 = accelerator.Allocate <byte>(imageBytes.Length); MemoryBuffer2D <Neuron> buffer3 = accelerator.Allocate <Neuron>(nrn.GetLength(0), nrn.GetLength(1)); buffer3.CopyFrom(nrn, new LongIndex2(0, 0), new LongIndex2(0, 0), new LongIndex2(nrn.GetLength(0), nrn.GetLength(1))); while (running == true) { Stopwatch sw = new Stopwatch(); sw.Start(); Index2 gridSize = new Index2(pixelMap.GetLength(0), pixelMap.GetLength(1)); //kernel(gridSize, buffer.View, buffer2.View, buffer3.View); sw.OutputDelta("Kernel"); accelerator.Synchronize(); sw.OutputDelta("Sync"); // imageBytes = buffer2.GetAsArray(); buffer2.CopyTo(imageBytes, 0, 0, imageBytes.Length); sw.OutputDelta("Copy ImageBytes"); // Resolve and verify data //pixelMap = buffer.GetAs2DArray(); // buffer.CopyTo(pixelMap, new LongIndex2(0, 0), new LongIndex2(0, 0), new LongIndex2(pixelMap.GetLength(0), pixelMap.GetLength(1))); // Color3[] pixelMap1D = buffer.GetAsArray(); //Copy1DTo2DArray(pixelMap1D, pixelMap); // ~36ms, a bit faster //Array.Copy(pixelMap1D, imageBytes, pixelMap1D.Length); // fails //Buffer.BlockCopy(pixelMap1D, 0, pixelMap, 0, pixelMap1D.Length * Marshal.SizeOf(typeof(Color3))); // fails // pixelMap = Make2DArray(pixelMap1D, pixelMap.GetLength(0), pixelMap.GetLength(1)); // still slow //sw.OutputDelta("Copy PixelMap"); // MainForm.form.DrawPixels(pixelMap); MainForm.form.DrawPixels(imageBytes, pixelMap.GetLength(0), pixelMap.GetLength(1)); Application.DoEvents(); //Debugger.Break(); sw.OutputDelta("DrawPixels"); } buffer.Dispose(); buffer2.Dispose(); buffer3.Dispose(); Application.Exit(); //Debugger.Break(); } } } }
/// <summary> /// Draws the Root into a memory buffer, then rotates it 90deg clockwise while drawing /// the memory buffer to the screen. /// See C++ documentation for more info. /// </summary> public void DrawTheRootRotated(IVwRootBox rootb, IntPtr hdc, Rect rcpDraw, uint bkclr, bool fDrawSel, IVwRootSite vrs, int nHow) { IVwGraphicsWin32 qvg32 = VwGraphicsWin32Class.Create(); Rectangle rcp = new Rectangle(rcpDraw.top, rcpDraw.left, rcpDraw.bottom, rcpDraw.right); Rectangle rcFill = new Rect(0, 0, rcp.Width, rcp.Height); using (Graphics screen = Graphics.FromHdc(hdc)) using (var memoryBuffer = new MemoryBuffer(rcp.Width, rcp.Height)) { memoryBuffer.Graphics.FillRectangle(new SolidBrush(ColorUtil.ConvertBGRtoColor(bkclr)), rcFill); qvg32.Initialize(memoryBuffer.Graphics.GetHdc()); IVwGraphics qvgDummy = null; try { Rect rcDst, rcSrc; vrs.GetGraphics(rootb, out qvgDummy, out rcSrc, out rcDst); Rectangle temp = rcDst; temp.Offset(-rcp.Left, -rcp.Top); rcDst = temp; qvg32.XUnitsPerInch = qvgDummy.XUnitsPerInch; qvg32.YUnitsPerInch = qvgDummy.YUnitsPerInch; rootb.DrawRoot(qvg32, rcSrc, rcDst, fDrawSel); vrs.ReleaseGraphics(rootb, qvgDummy); qvgDummy = null; } catch (Exception) { if (qvgDummy != null) vrs.ReleaseGraphics(rootb, qvgDummy); qvg32.ReleaseDC(); throw; } Point[] rgptTransform = new Point[3]; rgptTransform[0] = new Point(rcpDraw.right, rcpDraw.top); // upper left of actual drawing maps to top right of rotated drawing rgptTransform[1] = new Point(rcpDraw.right, rcpDraw.bottom); // upper right of actual drawing maps to bottom right of rotated drawing. rgptTransform[2] = new Point(rcpDraw.left, rcpDraw.top); // bottom left of actual drawing maps to top left of rotated drawing. screen.DrawImage((Image)memoryBuffer.Bitmap, rgptTransform, new Rectangle(0, 0, rcp.Width, rcp.Height), GraphicsUnit.Pixel); qvg32.ReleaseDC(); } }
/// <summary> /// Read unsigned long integer from the specified address. /// </summary> /// <param name="address">The address.</param> /// <param name="bits">The number of bits to interpret.</param> /// <param name="bitsOffset">The offset in bits.</param> /// <returns>Unsigned long integer read from the specified address.</returns> public ulong ReadUlong(ulong address, int bits = 64, int bitsOffset = 0) { MemoryBuffer buffer = Debugger.ReadMemory(this, address, 8); return(UserType.ReadUlong(buffer, 0, bits, bitsOffset)); }
/// <summary> /// Read float from the specified address. /// </summary> /// <param name="address">The address.</param> /// <returns>Float from the specified address.</returns> public float ReadFloat(ulong address) { MemoryBuffer buffer = Debugger.ReadMemory(this, address, 4); return(UserType.ReadFloat(buffer, 0)); }
public override string GetToolTipText(HotSpot spot, MemoryBuffer memory) { DisassembleRemoteCode(memory, spot.Address); return(string.Join("\n", instructions.Select(i => i.Instruction))); }