CreateViewAccessor() public method

public CreateViewAccessor ( ) : System.IO.MemoryMappedFiles.MemoryMappedViewAccessor
return System.IO.MemoryMappedFiles.MemoryMappedViewAccessor
 public MemoryMappedFileMessageSender(string name)
 {
     _file = MemoryMappedFile.CreateOrOpen(name, SizeOfFile);
     _bytesWrittenAccessor = _file.CreateViewAccessor(0, SizeOfInt32);
     _messageCompletedAccessor = _file.CreateViewAccessor(SizeOfInt32, SizeOfBool);
     _stream = _file.CreateViewStream(SizeOfInt32 + SizeOfBool + SizeOfBool, SizeOfStream);
     _messageSendingEvent = new EventWaitHandle(false, EventResetMode.AutoReset, name + "_MessageSending");
     _messageReadEvent = new EventWaitHandle(false, EventResetMode.AutoReset, name + "_MessageRead");
     _messageCancelledEvent = new EventWaitHandle(false, EventResetMode.ManualReset, name + "_MessageCancelled");
     _bytesWrittenEvent = new EventWaitHandle(false, EventResetMode.AutoReset, name + "_BytesWritten");
     _bytesReadEvent = new EventWaitHandle(false, EventResetMode.AutoReset, name + "_BytesRead");
 }
        //List<CVarHeader> VarHeaders = new List<CVarHeader>();

        public bool Startup()
        {
            if (IsInitialized) return true;

            try
            {
                iRacingFile = MemoryMappedFile.OpenExisting(Defines.MemMapFileName);
                FileMapView = iRacingFile.CreateViewAccessor();
                
                VarHeaderSize = Marshal.SizeOf(typeof(VarHeader));

                var hEvent = OpenEvent(Defines.DesiredAccess, false, Defines.DataValidEventName);
                var are = new AutoResetEvent(false);
                are.Handle = hEvent;

                var wh = new WaitHandle[1];
                wh[0] = are;

                WaitHandle.WaitAny(wh);

                Header = new CiRSDKHeader(FileMapView);
                GetVarHeaders();

                IsInitialized = true;
            }
            catch (Exception)
            {
                return false;
            }
            return true;
        }
Example #3
0
        public SRHSharedData()
        {
            m_Mmf = MemoryMappedFile.CreateNew(@"SimpleROHook1008",
                Marshal.SizeOf(typeof(StSHAREDMEMORY)),
                MemoryMappedFileAccess.ReadWrite);
            if (m_Mmf == null)
                MessageBox.Show("CreateOrOpen MemoryMappedFile Failed.");
            m_Accessor = m_Mmf.CreateViewAccessor();

            byte* p = null;
            m_Accessor.SafeMemoryMappedViewHandle.AcquirePointer(ref p);
            m_pSharedMemory = (StSHAREDMEMORY*)p;

            write_packetlog = false;
            freemouse = false;
            m2e = false;
            fix_windowmode_vsyncwait = false;
            show_framerate = false;
            objectinformation = false;
            _44khz_audiomode = false;
            cpucoolerlevel = 0;
            configfilepath = "";
            musicfilename = "";
            executeorder = false;
            g_hROWindow = 0;
        }
        public MemoryMapReader(string file)
        {
            var fileInfo = new FileInfo(file);

            Length = (int)fileInfo.Length;

            // Ideally we would use the file ID in the mapName, but it is not
            // easily available from C#.
            var mapName = $"{fileInfo.FullName.Replace("\\", "-")}-{Length}";
            lock (FileLocker)
            {
                try
                {
                    _memoryMappedFile = MemoryMappedFile.OpenExisting(mapName, MemoryMappedFileRights.Read);
                }
                catch (Exception ex) when (ex is IOException || ex is NotImplementedException)
                {
                    using (
                        var stream = new FileStream(file, FileMode.Open, FileAccess.Read,
                            FileShare.Delete | FileShare.Read))
                    {
                        _memoryMappedFile = MemoryMappedFile.CreateFromFile(stream, mapName, Length,
                            MemoryMappedFileAccess.Read, null, HandleInheritability.None, false);
                    }
                }
            }

            _view = _memoryMappedFile.CreateViewAccessor(0, Length, MemoryMappedFileAccess.Read);
        }
Example #5
0
        void InitWriter()
        {
            string prefix = sm.instanceType == tiesky.com.SharmIpcInternals.eInstanceType.Master ? "1" : "2";

            if (ewh_Writer_ReadyToRead == null)
            {
                ewh_Writer_ReadyToRead  = new EventWaitHandle(false, EventResetMode.ManualReset, sm.uniqueHandlerName + prefix + "_SharmNet_ReadyToRead");
                ewh_Writer_ReadyToWrite = new EventWaitHandle(true, EventResetMode.ManualReset, sm.uniqueHandlerName + prefix + "_SharmNet_ReadyToWrite");
                ewh_Writer_ReadyToWrite.Set();
            }

            //if (sm.instanceType == tiesky.com.SharmIpc.eInstanceType.Master)
            //{
            //    Console.WriteLine("My writer handlers:");
            //    Console.WriteLine(sm.uniqueHandlerName + prefix + "_SharmNet_ReadyToRead");
            //    Console.WriteLine(sm.uniqueHandlerName + prefix + "_SharmNet_ReadyToWrite");
            //    Console.WriteLine("-------");
            //}


            if (Writer_mmf == null)
            {
                Writer_mmf      = System.IO.MemoryMappedFiles.MemoryMappedFile.CreateOrOpen(sm.uniqueHandlerName + prefix + "_SharmNet_MMF", sm.bufferCapacity, MemoryMappedFileAccess.ReadWrite);
                Writer_accessor = Writer_mmf.CreateViewAccessor(0, sm.bufferCapacity);
            }
        }
 void MapContent()
 {
     if (_accessor != null) return;
     _memoryMappedFile = MemoryMappedFile.CreateFromFile(_stream, null, 0, MemoryMappedFileAccess.ReadWrite, null, HandleInheritability.None, true);
     _accessor = _memoryMappedFile.CreateViewAccessor();
     _accessor.SafeMemoryMappedViewHandle.AcquirePointer(ref _pointer);
 }
        public MemoryMappedFileCheckpoint(string filename, string name, bool cached, bool mustExist = false, long initValue = 0)
        {
            _filename = filename;
            _name = name;
            _cached = cached;
            var old = File.Exists(_filename);
            _fileStream = new FileStream(_filename,
                                            mustExist ? FileMode.Open : FileMode.OpenOrCreate,
                                            FileAccess.ReadWrite,
                                            FileShare.ReadWrite);
            _file = MemoryMappedFile.CreateFromFile(_fileStream,
                                                    Guid.NewGuid().ToString(),
                                                    sizeof(long),
                                                    MemoryMappedFileAccess.ReadWrite,
                                                    new MemoryMappedFileSecurity(),
                                                    HandleInheritability.None,
                                                    false);
            _accessor = _file.CreateViewAccessor(0, 8);

            if (old)
                _last = _lastFlushed = ReadCurrent();
            else
            {
                _last = initValue;
                Flush();
            }
        }
 public BitmapBroadcaster()
 {
     file = MemoryMappedFile.CreateOrOpen("OpenNiVirtualCamFrameData", fileSize, MemoryMappedFileAccess.ReadWrite);
     memoryAccessor = file.CreateViewAccessor(0, fileSize, MemoryMappedFileAccess.ReadWrite);
     if (hasServer())
         throw new Exception("Only one server is allowed.");
 }
Example #9
0
 public MumbleLink()
 {
     if (mmFile == null)
     {
         mmFile = MemoryMappedFile.CreateOrOpen("MumbleLink", Marshal.SizeOf(data), MemoryMappedFileAccess.ReadWrite);
         mmAccessor = mmFile.CreateViewAccessor(0, Marshal.SizeOf(data));
     }
 }
        public MemoryMappedFileCommunicator(MemoryMappedFile rpMemoryMappedFile, long rpOffset, long rpSize, MemoryMappedFileAccess rpAccess)
        {
            r_MemoryMappedFile = rpMemoryMappedFile;
            r_ViewAccessor = rpMemoryMappedFile.CreateViewAccessor(rpOffset, rpSize, rpAccess);

            ReadPosition = -1;
            r_WritePosition = -1;
        }
Example #11
0
File: Gcf.cs Project: Frassle/Ibasa
        public Gcf(FileStream fileStream)
        {
            File = MemoryMappedFile.CreateFromFile(fileStream, System.IO.Path.GetFileNameWithoutExtension(fileStream.Name), 0,
                MemoryMappedFileAccess.Read, null, HandleInheritability.None, true);

            FileHeader = File.CreateViewAccessor(FileHeaderOffset, FileHeaderSize, MemoryMappedFileAccess.Read);
            BlockEntryHeader = File.CreateViewAccessor(BlockEntryHeaderOffset, BlockEntryHeaderSize, MemoryMappedFileAccess.Read);

            BlockEntryIndex = 0;
            BlockEntry = File.CreateViewAccessor(BlockEntryOffset, BlockEntrySize, MemoryMappedFileAccess.Read);

            FragmentationMapHeader = File.CreateViewAccessor(
                FragmentationMapHeaderOffset, FragmentationMapHeaderSize, MemoryMappedFileAccess.Read);

            FragmentationMapIndex = 0;
            FragmentationMap = File.CreateViewAccessor(FragmentationMapOffset, FragmentationMapSize, MemoryMappedFileAccess.Read);
        }
Example #12
0
 public cFileMap(FileStream stream, FileMapProtect protect, int offset, int length)
 {
     MemoryMappedFileAccess cProtect = (protect == FileMapProtect.ReadWrite) ? MemoryMappedFileAccess.ReadWrite : MemoryMappedFileAccess.Read;
     _length = length;
     _mappedFile = MemoryMappedFile.CreateFromFile(stream, stream.Name, _length, cProtect, null, HandleInheritability.None, true);
     _mappedFileAccessor = _mappedFile.CreateViewAccessor(offset, _length, cProtect);
     _addr = _mappedFileAccessor.SafeMemoryMappedViewHandle.DangerousGetHandle();
 }
        internal MemoryMappedFile(string path)
        {
            FileStream fs = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read);

            _mmf  = SIOMMF.MemoryMappedFile.CreateFromFile(fs, null, 0, SIOMMF.MemoryMappedFileAccess.Read, null, HandleInheritability.None, false);
            _mmva = _mmf.CreateViewAccessor(0, 0, SIOMMF.MemoryMappedFileAccess.Read);
            _mmva.SafeMemoryMappedViewHandle.AcquirePointer(ref _ptr);
        }
Example #14
0
		public void Allocate()
		{
			//we can't allocate 0 bytes here.. so just allocate 1 byte here if 0 was requested. it should be OK, and we dont have to handle cases where blocks havent been allocated
			int sizeToAlloc = Size;
			if (sizeToAlloc == 0) sizeToAlloc = 1;
			mmf = MemoryMappedFile.CreateNew(BlockName, sizeToAlloc);
			mmva = mmf.CreateViewAccessor();
			mmva.SafeMemoryMappedViewHandle.AcquirePointer(ref Ptr);
		}
Example #15
0
        public MappedByteBuffer(MemoryMappedFile memoryMappedFile, long offset, int length)
        {
            _memoryMappedFile = memoryMappedFile;
            byte* ptr = (byte*)0;
            _view = memoryMappedFile.CreateViewAccessor(offset, length);
            _view.SafeMemoryMappedViewHandle.AcquirePointer(ref ptr);

            Pointer = new IntPtr(ptr);
        }
Example #16
0
        public DebuggerForm()
        {
            InitializeComponent();

            m_MMF = MemoryMappedFile.CreateOrOpen( @"VoronoiDebugger", 1 << 20, MemoryMappedFileAccess.ReadWrite );
            m_View = m_MMF.CreateViewAccessor( 0, 1 << 20, MemoryMappedFileAccess.ReadWrite );	// Open in R/W even though we won't write into it, just because we need to have the same access privileges as the writer otherwise we make the writer crash when it attempts to open the file in R/W mode!

            integerTrackbarControlCell_ValueChanged( null, 0 );
        }
Example #17
0
 public object deserializeFromMemoryMappedFile(MemoryMappedFile mmf,ref int index,int length)
 {
     int createLength = (int)length;
     using (MemoryMappedViewAccessor mmfReader = mmf.CreateViewAccessor()) {
         byte[] buffer = new byte[length];
         mmfReader.ReadArray<byte>(index, buffer, 0,createLength);
         return ByteArrayToObject(buffer);
     }
 }
        public RTSSController(string appId)
        {
            _mmf = MemoryMappedFile.OpenExisting("RTSSSharedMemoryV2");
            _view = _mmf.CreateViewAccessor();
            _appId = appId;

            Refresh();

            ValidateUniqueAppId();
        }
        public MemoryMappedFileCommunicator(MemoryMappedFile mappedFile, long offset, long size, MemoryMappedFileAccess access)
        {
            MappedFile = mappedFile;
            view = mappedFile.CreateViewAccessor(offset, size, access);

            ReadPosition = -1;
            writePosition = -1;
            dataToSend = new List<byte[]>();

            callback = new SendOrPostCallback(OnDataReceivedInternal);
            operation = AsyncOperationManager.CreateOperation(null);
        }
        private void MapFile(long capacity)
        {
            if (Pointer != IntPtr.Zero)
                return;

            _file = MemoryMappedFile.CreateFromFile(Address, FileMode.Open, null, capacity, MemoryMappedFileAccess.ReadWrite);
            _accessor = _file.CreateViewAccessor();
            byte* pointer = null;
            _accessor.SafeMemoryMappedViewHandle.AcquirePointer(ref pointer);

            Pointer = new IntPtr(pointer);
        }
 /// <summary>
 ///     Creates a new memory mapped ring buffer.
 /// </summary>
 /// <param name="size">The size of the ring buffer to create.</param>
 /// <param name="location">The location to store the ring buffer at.</param>
 /// <param name="name">The name of the ring buffer.</param>
 public RingBufferMemoryMap(long size, string location, string name)
 {
     _size = size;
     _isCreated = !System.IO.File.Exists(location);
     _file = MemoryMappedFile.CreateFromFile(location, FileMode.OpenOrCreate, name, size,
         MemoryMappedFileAccess.ReadWrite);
     _view = _file.CreateViewAccessor(0, size);
     if (_isCreated)
     {
         // If created write -1 to the front of the ring buffer so it will find position 0 as the end.
         _view.Write(0, -1L);
     }
     SeekToEnd();
 }
Example #22
0
        public SharedMemoryBuffer(String baseObjectName, Int64 capacity)
            : base(baseObjectName)
        {
            Verify.NotWhitespace(baseObjectName, "baseObjectName");
            Verify.True(capacity > 0, "capacity", Localization.ValueGreaterThanZeroExpected);
            Verify.True(baseObjectName.StartsWith(@"Local\") || baseObjectName.StartsWith(@"Global\"), "baseObjectName", Localization.InvalidSharedMemoryBufferName);

            dataReadyEvent = new EventWaitHandle(false, EventResetMode.AutoReset, baseObjectName + "_DATA_READY");
            bufferReadyEvent = new EventWaitHandle(true, EventResetMode.AutoReset, baseObjectName + "_BUFFER_READY");
            bufferFile = MemoryMappedFile.CreateOrOpen(baseObjectName + "_BUFFER", capacity, MemoryMappedFileAccess.ReadWrite);
            bufferView = bufferFile.CreateViewAccessor(0, 0, MemoryMappedFileAccess.ReadWrite);

            Timeout = TimeSpan.FromSeconds(10);
        }
Example #23
0
        public Form1()
        {
            InitializeComponent();

            m_Instance = new ParametersBlock() {
            // 				SunIntensity = 100.0f,				// Should never change!
            // 				AverageGroundReflectance = 0.1f,	// Should never change!
            };
            m_StructSize = System.Runtime.InteropServices.Marshal.SizeOf(m_Instance);
            InitFromUI();

            m_MMF = MemoryMappedFile.CreateOrOpen( @"GlobalIllumination", m_StructSize, MemoryMappedFileAccess.ReadWrite );
            m_View = m_MMF.CreateViewAccessor( 0, m_StructSize, MemoryMappedFileAccess.ReadWrite );
            UpdateMMF();
        }
Example #24
0
 public void Connect()
 {
     string map = @"Local\SimTelemetryRfactor2"; // TODO: Fix this name :)
     try
     {
         _mMMF = MemoryMappedFile.CreateOrOpen(map, 16*1024, MemoryMappedFileAccess.ReadWrite);
         _mAccessor = _mMMF.CreateViewAccessor(0, 16*1024);
         Hooked = true;
     }
     catch (Exception e)
     {
         Hooked = false;
         //
     }
 }
 public MemoryMappedFileCheckpoint(string filename, string name, bool cached)
 {
     _filename = filename;
     _name = name;
     _cached = cached;
     var filestream = new FileStream(_filename, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
     _file = MemoryMappedFile.CreateFromFile(filestream,
                                             Guid.NewGuid().ToString(),
                                             8,
                                             MemoryMappedFileAccess.ReadWrite,
                                             new MemoryMappedFileSecurity(),
                                             HandleInheritability.None,
                                             false);
     _accessor = _file.CreateViewAccessor(0, 8);
     _last = _lastFlushed = ReadCurrent();
 }
Example #26
0
		public LibsnesApi(string dllPath)
		{
			InstanceName = "libsneshawk_" + Guid.NewGuid().ToString();

			var pipeName = InstanceName;

			mmf = MemoryMappedFile.CreateNew(pipeName, 1024 * 1024);
			mmva = mmf.CreateViewAccessor();
			mmva.SafeMemoryMappedViewHandle.AcquirePointer(ref mmvaPtr);

			pipe = new NamedPipeServerStream(pipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.None, 1024 * 1024, 1024);

			instanceDll = new InstanceDll(dllPath);
			var dllinit = (DllInit)Marshal.GetDelegateForFunctionPointer(instanceDll.GetProcAddress("DllInit"), typeof(DllInit));
			dllinit(pipeName);

			//TODO - start a thread to wait for process to exit and gracefully handle errors? how about the pipe?

			pipe.WaitForConnection();

			rbuf = new IPCRingBuffer();
			wbuf = new IPCRingBuffer();
			rbuf.Allocate(1024);
			wbuf.Allocate(1024);
			rbufstr = new IPCRingBufferStream(rbuf);
			wbufstr = new IPCRingBufferStream(wbuf);

			rstream = new SwitcherStream();
			wstream = new SwitcherStream();

			rstream.SetCurrStream(pipe);
			wstream.SetCurrStream(pipe);

			brPipe = new BinaryReader(rstream);
			bwPipe = new BinaryWriter(wstream);

			WritePipeMessage(eMessage.eMessage_SetBuffer);
			bwPipe.Write(1);
			WritePipeString(rbuf.Id);
			WritePipeMessage(eMessage.eMessage_SetBuffer);
			bwPipe.Write(0);
			WritePipeString(wbuf.Id);
			bwPipe.Flush();
		}
        public bool IsConnected()
        {
            if (Accessor != null)
                return true;

            var dataValidEvent = Event.OpenEvent(Event.EVENT_ALL_ACCESS | Event.EVENT_MODIFY_STATE, false, "Local\\IRSDKDataValidEvent");
            if (dataValidEvent == IntPtr.Zero)
            {
                var lastError = Marshal.GetLastWin32Error();
                if (lastError == Event.ERROR_FILE_NOT_FOUND)
                    return false;

                Trace.WriteLine(string.Format("Unable to open event Local\\IRSDKDataValidEvent - Error Code {0}", lastError), "DEBUG");
                return false;
            }

            MemoryMappedFile irsdkMappedMemory = null;
            try
            {
                irsdkMappedMemory = MemoryMappedFile.OpenExisting("Local\\IRSDKMemMapFileName");
            }
            catch (Exception e)
            {
                Trace.WriteLine("Error accessing shared memory", "DEBUG");
                Trace.WriteLine(e.Message, "DEBUG");
            }

            if (irsdkMappedMemory == null)
                return false;

            var accessor = irsdkMappedMemory.CreateViewAccessor();
            if (accessor == null)
            {
                irsdkMappedMemory.Dispose();
                Trace.WriteLine("Unable to Create View into shared memory", "DEBUG");
                return false;
            }

            this.irsdkMappedMemory = irsdkMappedMemory;
            this.dataValidEvent = dataValidEvent;
            Accessor = accessor;
            return true;
        }
Example #28
0
        public MBC5(CartHeader header, byte[] gameROM, System.IO.MemoryMappedFiles.MemoryMappedFile file)
        {
            this.gameROM = gameROM;

            ROMBankCount = this.gameROM.Length / 0x4000;
            RAMBankCount = Math.Max(1, header.RAM_Size / RAMBankSize);
            RAMBanks     = file.CreateViewAccessor(0, header.RAM_Size);

            //0x800 is the only alternative bank size
            if (header.RAM_Size == 0)
            {
                RAMBankSize = 0;
            }

            //0x800 is the only alternative bank size
            if (header.RAM_Size == 0x800)
            {
                RAMBankSize = 0x800;
            }
        }
        public ConnectImpl()
        {
            _onDataUpdatedEvent = new EventWaitHandle(true, EventResetMode.ManualReset, OnDataUpdatedEventName);
            _onWriteLockMutex = new Mutex(false, OnWriteLockMutexName);

            using (GetLock())
            {
                try
                {
                    _memoryMappedFile = MemoryMappedFile.OpenExisting(MemoryMappedFileName);
                }
                catch (FileNotFoundException)
                {
                    _memoryMappedFile = MemoryMappedFile.CreateNew(MemoryMappedFileName, MemoryMappedFileSize);
                }

                _memoryMappedViewAccessor = _memoryMappedFile.CreateViewAccessor();
                _memoryMappedViewStream = _memoryMappedFile.CreateViewStream();
                _memoryMappedViewHandle = _memoryMappedViewStream.SafeMemoryMappedViewHandle.DangerousGetHandle();
            }
        }
        private void Init()
        {
            if (!File.Exists(_fileName))
            {
                _file = MemoryMappedFile.CreateNew(_fileName, 4096);
                _accessor = _file.CreateViewAccessor();
                var begin = new Position();
                _accessor.Write(0, ref begin);
            }
            else
            {
                _file = MemoryMappedFile.CreateOrOpen(_fileName, 4096);
                _accessor = _file.CreateViewAccessor();
            }

            while (true)
            { 
                Position current;
                _accessor.Read(0, out current);

                var _lastRead = Enumerable.Empty<RecordedEvent>();

                _eventStoreConnection.ReadAllEventsForwardAsync(new ClientAPI.Position(current.Commit, current.Prepare), _batch)
                    .ContinueWith(s =>
                    {
                        Publish(s.Result.Events);

                        _lastRead = s.Result.Events;

                        int lastCount = current.Count;
                        current = new Position
                        {
                            Prepare = s.Result.Position.PreparePosition,
                            Commit = s.Result.Position.CommitPosition,
                            Count = lastCount + s.Result.Events.Count()
                        };
                        _accessor.Write(0, ref current);
                    }).Wait();

                if (_lastRead.Count() < _batch)
                    break;
            }

        }
Example #31
0
        /// <summary>
        /// Loop thread that reads the memory mapped file and adds items to the read queue.
        /// </summary>
        /// <param name="data"></param>
        private void ListenThreadImpl(object data)
        {
            try
            {
                _threadStatus.IsThreadActive = true;
                logger.Info("[" + _description + "-T] Reader active");

                try
                {

                    while (_threadStatus.IsThreadEnabled == true)
                    {
                        _threadStatus.ThreadHealthDate = DateTime.Now;

                        DateTime duplicateErrorDate = DateTime.MinValue;

                        //listening
                        try
                        {
                            /* Memory Mapped File:
                             * accessor1Len:  bytes 0-4       total length of file
                             * accessor2ID:   bytes 8-12      ID number of message
                             * accessor3Data: variable bytes  payload
                             * */

                            int msgLength;
                            int msgID;

                            //open mmf
                            mmf = MemoryMappedFile.OpenExisting(_ipcType);

                            MemoryMappedViewAccessor accessor1Len = mmf.CreateViewAccessor(0, 4);
                            MemoryMappedViewAccessor accessor2ID = mmf.CreateViewAccessor(8, 4);
                            MemoryMappedViewAccessor accessor3Data;

                            //locked section
                            using (new Niawa.Utilities.SingleGlobalInstance(1000, _ipcType)) //1000ms timeout on global lock
                            {

                                //get length, ID, and data
                                msgLength = accessor1Len.ReadInt32(0);
                                msgID = accessor2ID.ReadInt32(0);
                                accessor3Data = mmf.CreateViewAccessor(16, msgLength);
                            }

                            System.Diagnostics.Debug.WriteLine("MmfReader: MsgID: " + msgID);
                            System.Diagnostics.Debug.WriteLine("MmfReader: LastMsgID: " + _lastMsgID);

                            //check if ID changed
                            if (msgID == _lastMsgID)
                            {
                                System.Diagnostics.Debug.WriteLine("MmfReader: There is no work to do");

                                //do nothing
                                System.Threading.Thread.Sleep(10);

                            }
                            else
                            {
                                System.Diagnostics.Debug.WriteLine("MmfReader: Reading message");

                                //set ID
                                _lastMsgID = msgID;

                                //check if message is too long
                                if (msgLength + 16 > _bufferLength)
                                {
                                    logger.Error("[" + _description + "-T] Not reading message [" + msgID + "]: Message length [" + (msgLength + 16).ToString() + "] is greater than the buffer length [" + _bufferLength.ToString() + "]");
                                    _threadStatus.MessageErrorCount += 1;
                                }
                                else
                                {
                                    //get data
                                    byte[] buffer = new byte[msgLength];
                                    accessor3Data.ReadArray<byte>(0, buffer, 0, msgLength);

                                    NiawaMmfContainer msg = new NiawaMmfContainer(buffer);

                                    logger.Debug("[" + _description + "-T] Received data [" + msgID + "]: " + msg.SerialID);

                                    _threadStatus.MessageCount += 1;

                                    _receiveQueue.Enqueue(msg);
                                }

                            }
                        }
                        catch (System.IO.FileNotFoundException)
                        {
                            //file does not exist
                            System.Diagnostics.Debug.WriteLine("MmfReader [" + _ipcType + "]: File was not found");

                            //log message every 10 seconds
                            TimeSpan ts = DateTime.Now - duplicateErrorDate;
                            if (ts.TotalSeconds > 10)
                            {
                                duplicateErrorDate = DateTime.Now;
                                logger.Debug("[" + _description + "-T] Mmf not initiated by provider");
                            }

                            //sleep for 250 ms
                            System.Threading.Thread.Sleep(250);
                        }

                        catch (System.Threading.ThreadAbortException) // ex1)
                        {
                            //thread was aborted; re-enter loop
                            logger.Info("[" + _description + "-T] Thread aborted");
                            break;
                        }
                        catch (System.Threading.ThreadInterruptedException) // ex1)
                        {
                            //thread was interrupted; re-enter loop
                            logger.Info("[" + _description + "-T] Thread interrupted");
                            break;
                        }
                        catch (Exception ex)
                        {
                            //exception
                            logger.Error("[" + _description + "-T] Exception while listening for next message: " + ex.Message, ex);

                            _threadStatus.ErrorCount += 1;

                            System.Threading.Thread.Sleep(100);
                        }
                        System.Threading.Thread.Sleep(50);
                    }
                    //done listening

                }
                finally
                {
                    _threadStatus.IsThreadActive = false;
                    _threadStatus.IsThreadEnabled = false;
                    logger.Info("[" + _description + "-T] Reader inactive");
                }

            }
            catch (Exception ex)
            {
                logger.Error("[" + _description + "-T] Exception in listen thread: " + ex.Message, ex);
                if (!_ignoreExceptions)
                    throw ex;
            }
        }
Example #32
0
        /// <summary>
        ///
        /// </summary>
        void InitReader()
        {
            string prefix = sm.instanceType == eInstanceType.Slave ? "1" : "2";

            if (ewh_Reader_ReadyToRead == null)
            {
                ewh_Reader_ReadyToRead  = new EventWaitHandle(false, EventResetMode.ManualReset, sm.uniqueHandlerName + prefix + "_SharmNet_ReadyToRead");
                ewh_Reader_ReadyToWrite = new EventWaitHandle(true, EventResetMode.ManualReset, sm.uniqueHandlerName + prefix + "_SharmNet_ReadyToWrite");
                ewh_Reader_ReadyToWrite.Set();
            }

            //if (sm.instanceType == tiesky.com.SharmIpc.eInstanceType.Slave)
            //{
            //    Console.WriteLine("My reader handlers:");
            //    Console.WriteLine(sm.uniqueHandlerName + prefix + "_SharmNet_ReadyToRead");
            //    Console.WriteLine(sm.uniqueHandlerName + prefix + "_SharmNet_ReadyToWrite");
            //    Console.WriteLine("-------");
            //}


            if (Reader_mmf == null)
            {
                Reader_mmf      = System.IO.MemoryMappedFiles.MemoryMappedFile.CreateOrOpen(sm.uniqueHandlerName + prefix + "_SharmNet_MMF", sm.bufferCapacity, MemoryMappedFileAccess.ReadWrite);
                Reader_accessor = Reader_mmf.CreateViewAccessor(0, sm.bufferCapacity);
            }

            Task.Run(() =>
            {
                byte[] hdr           = null;
                byte[] ret           = null;
                ushort iCurChunk     = 0;
                ushort iTotChunk     = 0;
                ulong iMsgId         = 0;
                int iPayLoadLen      = 0;
                ulong iResponseMsgId = 0;

                eMsgType msgType = eMsgType.RpcRequest;

                try
                {
                    while (true)
                    {
                        ewh_Reader_ReadyToRead.WaitOne();
                        if (ewh_Reader_ReadyToRead == null) //Special Dispose case
                        {
                            return;
                        }
                        ewh_Reader_ReadyToRead.Reset();
                        //Reading data from MMF

                        //Reading header
                        hdr     = ReadBytes(0, protocolLen);
                        msgType = (eMsgType)hdr[0];

                        //Parsing header
                        switch (msgType)
                        {
                        case eMsgType.ErrorInRpc:

                            iPayLoadLen    = BitConverter.ToInt32(hdr, 9);   //+4
                            iResponseMsgId = BitConverter.ToUInt64(hdr, 17); //+8

                            DataArrived(msgType, iResponseMsgId, null);
                            break;

                        case eMsgType.RpcResponse:
                        case eMsgType.RpcRequest:
                        case eMsgType.Request:

                            bool zeroByte = false;
                            iMsgId        = BitConverter.ToUInt64(hdr, 1); //+8
                            iPayLoadLen   = BitConverter.ToInt32(hdr, 9);  //+4
                            if (iPayLoadLen == Int32.MaxValue)
                            {
                                zeroByte    = true;
                                iPayLoadLen = 0;
                            }
                            iCurChunk      = BitConverter.ToUInt16(hdr, 13); //+2
                            iTotChunk      = BitConverter.ToUInt16(hdr, 15); //+2
                            iResponseMsgId = BitConverter.ToUInt64(hdr, 17); //+8

                            if (iCurChunk == 1)
                            {
                                chunksCollected = null;
                                MsgId_Received  = iMsgId;
                            }
                            else if (iCurChunk != currentChunk + 1)
                            {
                                //Wrong income, sending special signal back, waiting for new MsgId
                                switch (msgType)
                                {
                                case eMsgType.RpcRequest:
                                    this.SendMessage(eMsgType.ErrorInRpc, this.GetMessageId(), null, iMsgId);
                                    break;

                                case eMsgType.RpcResponse:
                                    DataArrived(eMsgType.ErrorInRpc, iResponseMsgId, null);
                                    break;
                                }
                                break;
                            }

                            if (iTotChunk == iCurChunk)
                            {
                                if (chunksCollected == null)
                                {
                                    DataArrived(msgType, (msgType == eMsgType.RpcResponse) ? iResponseMsgId : iMsgId, iPayLoadLen == 0 ? ((zeroByte) ? new byte[0] : null) : ReadBytes(protocolLen, iPayLoadLen));
                                }
                                else
                                {
                                    ret = new byte[iPayLoadLen + chunksCollected.Length];
                                    Buffer.BlockCopy(chunksCollected, 0, ret, 0, chunksCollected.Length);
                                    Buffer.BlockCopy(ReadBytes(protocolLen, iPayLoadLen), 0, ret, chunksCollected.Length, iPayLoadLen);
                                    DataArrived(msgType, (msgType == eMsgType.RpcResponse) ? iResponseMsgId : iMsgId, ret);
                                }
                                chunksCollected = null;
                                currentChunk    = 0;
                            }
                            else
                            {
                                if (chunksCollected == null)
                                {
                                    chunksCollected = ReadBytes(protocolLen, iPayLoadLen);
                                }
                                else
                                {
                                    byte[] tmp = new byte[chunksCollected.Length + iPayLoadLen];
                                    Buffer.BlockCopy(chunksCollected, 0, tmp, 0, chunksCollected.Length);
                                    Buffer.BlockCopy(ReadBytes(protocolLen, iPayLoadLen), 0, tmp, chunksCollected.Length, iPayLoadLen);
                                    chunksCollected = tmp;
                                }

                                currentChunk = iCurChunk;
                            }
                            break;

                        default:
                            //Unknown protocol type
                            chunksCollected = null;
                            currentChunk    = 0;
                            //Wrong income, doing nothing
                            throw new Exception("tiesky.com.SharmIpc: Reading protocol contains errors");
                            //break;
                        }

                        //Setting signal
                        ewh_Reader_ReadyToWrite.Set();
                    }
                }
                catch
                {}
            });
        }
Example #33
0
        private static void Process(PeHeaderReader pe, AssemblyDefinition asm, MemoryMappedFile mappedFile)
        {
            foreach (var m in asm.MainModule.Types.SelectMany(t => t.Methods))
            {
                if (!m.HasBody)
                    continue;
                var body = m.Body;
                //Console.WriteLine("{0,-40}{1:x}{2,10:x}{3,10:x}", m.Name, m.RVA, body.LengthOnDisk, body.IndexAfterCode);

                if (RequiresFatHeader(body))
                {
                    flags.Write(body.Flags);
                    maxStack.Write((UInt16)body.MaxStackSize);
                    codeSize.Write(body.CodeSize);
                    localVar.Write(body.LocalVarToken.ToUInt32());
                }
                else
                {
                    flags.Write((byte)(0x2 | (body.CodeSize << 2)));
                }

                foreach (var instr in body.Instructions)
                {
                    if (instr.OpCode.Size == 1)
                        opcodes.Write(instr.OpCode.Op2);
                    else
                    {
                        opcodes.Write(instr.OpCode.Op1);
                        opcodes.Write(instr.OpCode.Op2);
                    }

                    var operand = instr.Operand;
                    switch (instr.OpCode.OperandType)
                    {
                        case OperandType.InlineSwitch:
                            {
                                var targets = (Instruction[])operand;
                                switches.Write(targets.Length);
                                for (int i = 0; i < targets.Length; i++)
                                    switches.Write(GetTargetOffset(body, targets[i]));
                                break;
                            }
                        case OperandType.ShortInlineBrTarget:
                            {
                                var target = (Instruction)operand;
                                sbyteBranch.Write((sbyte)GetTargetOffset(body, target));
                                break;
                            }
                        case OperandType.InlineBrTarget:
                            {
                                var target = (Instruction)operand;
                                intBranch.Write(GetTargetOffset(body, target));
                                break;
                            }
                        case OperandType.ShortInlineVar:
                            varIndex.Write((byte)((VariableDefinition)operand).Index);
                            break;
                        case OperandType.ShortInlineArg:
                            varIndex.Write((byte)GetParameterIndex(body, (ParameterDefinition)operand));
                            break;
                        case OperandType.InlineVar:
                            varIndex.Write((short)((VariableDefinition)operand).Index);
                            break;
                        case OperandType.InlineArg:
                            varIndex.Write((short)GetParameterIndex(body, (ParameterDefinition)operand));
                            break;
                        case OperandType.InlineSig:
                            sigToken.Write(((CallSite)operand).MetadataToken.ToUInt32());
                            break;
                        case OperandType.ShortInlineI:
                            if (instr.OpCode == OpCodes.Ldc_I4_S)
                                inlineInt.Write((sbyte)operand);
                            else
                                inlineInt.Write((byte)operand);
                            break;
                        case OperandType.InlineI:
                            inlineInt.Write((int)operand);
                            break;
                        case OperandType.InlineI8:
                            inlineInt.Write((long)operand);
                            break;
                        case OperandType.ShortInlineR:
                            inlieFloat.Write((float)operand);
                            break;
                        case OperandType.InlineR:
                            inlieFloat.Write((double)operand);
                            break;
                        case OperandType.InlineString:
                            strTokens.Write(instr.StringOperandToken.ToUInt32());
                            break;
                        case OperandType.InlineType:
                        case OperandType.InlineField:
                        case OperandType.InlineMethod:
                        case OperandType.InlineTok:
                            otherTokens.Write(((IMetadataTokenProvider)operand).MetadataToken.ToUInt32());
                            break;
                        case OperandType.InlineNone:
                            break;
                        default:
                            throw new ArgumentException();
                    }
                    //write some code
                }

                using (var mm = mappedFile.CreateViewAccessor(pe.GetFileOffset(m.RVA), body.LengthOnDisk, MemoryMappedFileAccess.Read))
                {
                    for (int i = body.IndexAfterCode; i < body.LengthOnDisk; i++)
                    {
                        exceptionStuff.Write(mm.ReadByte(i));
                    }

                    //do a full copy of the method
                    for (int i = 0; i < body.LengthOnDisk; i++)
                    {
                        fullMethods.Write(mm.ReadByte(i));
                    }
                }
            }
        }
 internal MemoryMappedFile(string path)
 {
     _mmf  = SIOMMF.MemoryMappedFile.CreateFromFile(path);
     _mmva = _mmf.CreateViewAccessor();
     _mmva.SafeMemoryMappedViewHandle.AcquirePointer(ref _ptr);
 }
        public SharedMemory(string name, IntPtr size)
        {
            mmf = MemoryMappedFile.OpenExisting(name + "_CONNECT_DATA");

            mmva = mmf.CreateViewAccessor();
            if (mmf.SafeMemoryMappedFileHandle.IsInvalid)
                throw new MySqlException("Cannot open file mapping " + name);
            mmvs = mmf.CreateViewStream(0L, size.ToInt64());
            mmva = mmf.CreateViewAccessor(0L, size.ToInt64());
        }