public Stream IncreaseSize(int value, out long offset)
        {
            lock (_lock)
            {
                while (Interlocked.Read(ref _counter) != 0)
                {
                    if (!Monitor.Wait(_lock, 10000, true))
                        throw new NotSupportedException();
                }

                FileStream file = new FileStream(_filePath, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
                try
                {
                    offset = MathEx.RoundUp(file.Length, 0x800);
                    file.SetLength(offset + value);
                    _mmf = MemoryMappedFile.CreateFromFile(file, null, 0, MemoryMappedFileAccess.ReadWrite, null, HandleInheritability.Inheritable, false);
                }
                catch
                {
                    file.SafeDispose();
                    throw;
                }

                Interlocked.Increment(ref _counter);
                DisposableStream result = new DisposableStream(_mmf.CreateViewStream(offset, value, MemoryMappedFileAccess.ReadWrite));
                result.AfterDispose.Add(new DisposableAction(Free));
                return result;
            }
        }
		public void Dispose()
		{
			if (mmf == null) return;
			mmva.Dispose();
			mmf.Dispose();
			mmf = null;
		}
        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;
        }
Exemple #4
0
        public FileHardDisk(string path)
        {
            var fi = new FileInfo(path);
            mSize = fi.Length;

            mFile = MemoryMappedFile.CreateFromFile(path, FileMode.Open);
        }
 public MainWindow()
 {
     InitializeComponent();
     videoSource = new WriteableBitmap(640, 480, 72, 72, PixelFormats.Rgb24, null);
     rectifiedTabletopMmf = MemoryMappedFile.OpenExisting("InteractiveSpaceRectifiedTabletop", MemoryMappedFileRights.Read);
     buffer = new byte[imgSize];
 }
Exemple #6
0
		/// <summary>
		/// note that a few bytes of the size will be used for a management area
		/// </summary>
		/// <param name="size"></param>
		public void Allocate(int size)
		{
			Owner = true;
			Id = SuperGloballyUniqueID.Next();
			mmf = MemoryMappedFile.CreateNew(Id, size);
			Setup(size);
		}
Exemple #7
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);
            }
        }
        public static string GetFileNameOfMemoryMappedFile(MemoryMappedFile file)
        {
            const uint size = 522;
            IntPtr path = Marshal.AllocCoTaskMem(unchecked((int)size)); // MAX_PATH + 1 char

            string result = null;
            try
            {
                // constant 0x2 = VOLUME_NAME_NT
                uint test = GetFinalPathNameByHandle(file.SafeMemoryMappedFileHandle.DangerousGetHandle(), path, size, 0x2);
                if (test != 0)
                    throw new Win32Exception();

                result = Marshal.PtrToStringAuto(path);
            }
            catch
            {
                uint test = GetMappedFileName(Process.GetCurrentProcess().Handle, file.SafeMemoryMappedFileHandle.DangerousGetHandle(), path, size);
                if (test != 0)
                    throw new Win32Exception();

                result = Marshal.PtrToStringAuto(path);
            }

            return result;
        }
 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 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);
        }
        //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;
        }
Exemple #13
0
 public Complex4Ks(long complexEntryCount)
 {
     Debug.Assert(complexEntryCount > fourK);
     Debug.Assert(complexEntryCount % 0x1000 == 0);
     Debug.Assert((complexEntryCount != 0) && ((complexEntryCount & (complexEntryCount - 1)) == 0), "complexEntryCount must be power of 2");
     this.length4ks = complexEntryCount / fourK;
     Debug.Assert(complexEntryCount == fourK * this.length4ks);
     bool ramIsLow = this.length4ks > 1024;
     if (!ramIsLow)
     {
         lock (totalRAMLock)
         {
             ramIsLow = totalRAM <= 0L;
         }
     }
     if (ramIsLow)
     {
         lock (nameSuffixLock)
         {
             this.suffix = nameSuffix++;
         }
         this.file = MemoryMappedFile.CreateFromFile(FileName, FileMode.CreateNew, namePrefix + "-" + suffix, complexEntryCount * 16L, MemoryMappedFileAccess.ReadWrite);
     }
     else
     {
         lock (totalRAMLock)
         {
             totalRAM -= this.length4ks * 4096 * 16;
         }
         this.array = new Complex[this.length4ks][];
     }
 }
 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.");
 }
Exemple #15
0
        private void InitSharedMemory()
        {
            _messageMemoryMappedFile = MemoryMappedFile.CreateOrOpen(@"messageMemory", 1024*1024, MemoryMappedFileAccess.ReadWrite);

            _collisionFlagMemoryMappedFile = MemoryMappedFile.CreateOrOpen(@"collisionFlag", 8, MemoryMappedFileAccess.ReadWrite);
            SetCollision(false);
        }
Exemple #16
0
		private void CreateFileStreams()
		{
			if (_file != null || _fileStream != null)
				throw new InvalidOperationException();

			_file = MemoryMappedFile.CreateFromFile(FileName);
			_fileStream = _file.CreateViewStream();
		}
 public MumbleLink()
 {
     if (mmFile == null)
     {
         mmFile = MemoryMappedFile.CreateOrOpen("MumbleLink", Marshal.SizeOf(data), MemoryMappedFileAccess.ReadWrite);
         mmAccessor = mmFile.CreateViewAccessor(0, Marshal.SizeOf(data));
     }
 }
Exemple #18
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();
 }
        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;
        }
        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);
        }
Exemple #21
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 );
        }
Exemple #22
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);
        }
Exemple #23
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);
		}
Exemple #24
0
 public HeurFacade(string mutName, string mmfName, int RegIterations)
 {
     // Time of listening before register
     this.Luogo1 = new Dictionary<string, Network>();
     this.threshold = RegIterations;
     this.mut = Mutex.OpenExisting(mutName); ;
     this.mmf = MemoryMappedFile.OpenExisting(mmfName, MemoryMappedFileRights.FullControl, HandleInheritability.None);
     this.stream = mmf.CreateViewStream(0, MappedFileDimension, MemoryMappedFileAccess.Read);
 }
 private IDisposable Acquire()
 {
     lock (_lock)
     {
         if (Interlocked.Increment(ref _counter) == 1)
             _mmf = MemoryMappedFile.CreateFromFile(_filePath, FileMode.Open, null, 0, MemoryMappedFileAccess.ReadWrite);
     }
     return new DisposableAction(Free);
 }
Exemple #26
0
 public SharedRingBuffer(string name, int size)
 {
     _size = size;
     _memory = MemoryMappedFile.CreateOrOpen(name, size + 1);
     _memoryStream = _memory.CreateViewStream();
     _writer = new BinaryWriter(_memoryStream);
     _reader = new BinaryReader(_memoryStream);
     _writer.Write(char.MinValue);
 }
 void UnmapContent()
 {
     if (_accessor == null) return;
     _accessor.SafeMemoryMappedViewHandle.ReleasePointer();
     _accessor.Dispose();
     _accessor = null;
     _memoryMappedFile.Dispose();
     _memoryMappedFile = null;
 }
Exemple #28
0
        public MappedFileBuffer(byte[] data)
        {
            _file = MemoryMappedFile.CreateNew(Guid.NewGuid().ToString(), data.Length);
            _stream = _file.CreateViewStream();
            _stream.Write(data, 0, data.Length);
            
			//File.WriteAllBytes(_file.Name, data);
			_size = (uint)data.Length;
		}
Exemple #29
0
        public void Create(int blockLength, int blockCount)
        {
            int fileLength = GetFileLength(blockLength, blockCount);
            _file = MemoryMappedFile.CreateNew(_fileName, fileLength);

            InitGroupInfoMutex();
            SetGroupInfo(blockLength, blockCount);
            InitBlockMutexes();
        }
 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);
     }
 }
        private void InitializeMemoryMap()
        {
            var mmf = MemoryMappedFile.CreateOrOpen(DATA_FILE, 1024 * 10);
            var view = mmf.CreateViewStream();

            MappedFile = mmf;
            ViewStream = view;
            LinkDataSize = Marshal.SizeOf(typeof(LinkData));
        }
Exemple #32
0
        public FileArchive(string filename)
        {
            using (var inputStream = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.Read))
              {
            mappedFile = MemoryMappedFile.CreateFromFile(inputStream, null, 0, MemoryMappedFileAccess.Read, null, HandleInheritability.None, true);
            ReadTableOfContents();
              }

              name = filename;
        }
 /// <summary>
 ///     Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
 /// </summary>
 /// <filterpriority>2</filterpriority>
 public void Dispose()
 {
     if (_disposed)
     {
         throw new ObjectDisposedException("Memory mapped file");
     }
     _ptr = null;
     _mmva.Dispose();
     _mmva = null;
     _mmf.Dispose();
     _mmf      = null;
     _disposed = true;
 }
 /// <summary>
 ///     Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
 /// </summary>
 /// <filterpriority>2</filterpriority>
 public void Dispose()
 {
     if (_disposed)
     {
         throw new ObjectDisposedException("Memory mapped file");
     }
     _ptr = null;
     _mmva.SafeMemoryMappedViewHandle.ReleasePointer();
     _mmva.Dispose();
     _mmva = null;
     _mmf.Dispose();
     _mmf      = null;
     _disposed = true;
 }
Exemple #35
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;
            }
        }
Exemple #36
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
                {}
            });
        }
Exemple #37
0
        public void Dispose()
        {
            try
            {
                if (ewh_Writer_ReadyToRead != null)
                {
                    //ewh_Writer_ReadyToRead.Set();
                    ewh_Writer_ReadyToRead.Close();
                    ewh_Writer_ReadyToRead.Dispose();
                    ewh_Writer_ReadyToRead = null;
                }
            }
            catch
            {
            }
            try
            {
                if (ewh_Writer_ReadyToWrite != null)
                {
                    //ewh_Writer_ReadyToWrite.Set();
                    ewh_Writer_ReadyToWrite.Close();
                    ewh_Writer_ReadyToWrite.Dispose();
                    ewh_Writer_ReadyToWrite = null;
                }
            }
            catch
            {
            }

            try
            {
                if (ewh_Reader_ReadyToRead != null)
                {
                    //ewh_Reader_ReadyToRead.Set();
                    ewh_Reader_ReadyToRead.Close();
                    ewh_Reader_ReadyToRead.Dispose();
                    ewh_Reader_ReadyToRead = null;
                }
            }
            catch
            {
            }
            try
            {
                if (ewh_Reader_ReadyToWrite != null)
                {
                    //ewh_Reader_ReadyToWrite.Set();
                    ewh_Reader_ReadyToWrite.Close();
                    ewh_Reader_ReadyToWrite.Dispose();
                    ewh_Reader_ReadyToWrite = null;
                }
            }
            catch
            {}

            try
            {
                if (Writer_accessor != null)
                {
                    Writer_accessor.Dispose();
                    Writer_accessor = null;
                }
            }
            catch
            {}
            try
            {
                if (Reader_accessor != null)
                {
                    Reader_accessor.Dispose();
                    Reader_accessor = null;
                }
            }
            catch
            { }
            try
            {
                if (Writer_mmf != null)
                {
                    Writer_mmf.Dispose();
                    Writer_mmf = null;
                }
            }
            catch
            { }
            try
            {
                if (Reader_mmf != null)
                {
                    Reader_mmf.Dispose();
                    Reader_mmf = null;
                }
            }
            catch
            { }
        }
Exemple #38
0
        public unsafe static MemoryMappedView CreateView(SafeMemoryMappedFileHandle memMappedFileHandle,
                                                         MemoryMappedFileAccess access, long offset, long size)
        {
            // MapViewOfFile can only create views that start at a multiple of the system memory allocation
            // granularity. We decided to hide this restriction from the user by creating larger views than the
            // user requested and hiding the parts that the user did not request.  extraMemNeeded is the amount of
            // extra memory we allocate before the start of the requested view. MapViewOfFile will also round the
            // capacity of the view to the nearest multiple of the system page size.  Once again, we hide this
            // from the user by preventing them from writing to any memory that they did not request.
            ulong nativeSize;
            long  extraMemNeeded, newOffset;

            ValidateSizeAndOffset(
                size, offset, GetSystemPageAllocationGranularity(),
                out nativeSize, out extraMemNeeded, out newOffset);

            // if request is >= than total virtual, then MapViewOfFile will fail with meaningless error message
            // "the parameter is incorrect"; this provides better error message in advance
            Interop.CheckForAvailableVirtualMemory(nativeSize);

            // create the view
            SafeMemoryMappedViewHandle viewHandle = Interop.MapViewOfFile(memMappedFileHandle,
                                                                          (int)MemoryMappedFile.GetFileMapAccess(access), newOffset, new UIntPtr(nativeSize));

            if (viewHandle.IsInvalid)
            {
                viewHandle.Dispose();
                throw Win32Marshal.GetExceptionForLastWin32Error();
            }

            // Query the view for its size and allocation type
            Interop.Kernel32.MEMORY_BASIC_INFORMATION viewInfo = new Interop.Kernel32.MEMORY_BASIC_INFORMATION();
            Interop.Kernel32.VirtualQuery(viewHandle, ref viewInfo, (UIntPtr)Marshal.SizeOf(viewInfo));
            ulong viewSize = (ulong)viewInfo.RegionSize;

            // Allocate the pages if we were using the MemoryMappedFileOptions.DelayAllocatePages option
            // OR check if the allocated view size is smaller than the expected native size
            // If multiple overlapping views are created over the file mapping object, the pages in a given region
            // could have different attributes(MEM_RESERVE OR MEM_COMMIT) as MapViewOfFile preserves coherence between
            // views created on a mapping object backed by same file.
            // In which case, the viewSize will be smaller than nativeSize required and viewState could be MEM_COMMIT
            // but more pages may need to be committed in the region.
            // This is because, VirtualQuery function(that internally invokes VirtualQueryEx function) returns the attributes
            // and size of the region of pages with matching attributes starting from base address.
            // VirtualQueryEx: http://msdn.microsoft.com/en-us/library/windows/desktop/aa366907(v=vs.85).aspx
            if (((viewInfo.State & Interop.Kernel32.MemOptions.MEM_RESERVE) != 0) || ((ulong)viewSize < (ulong)nativeSize))
            {
                IntPtr tempHandle = Interop.VirtualAlloc(
                    viewHandle, (UIntPtr)(nativeSize != MemoryMappedFile.DefaultSize ? nativeSize : viewSize),
                    Interop.Kernel32.MemOptions.MEM_COMMIT, MemoryMappedFile.GetPageAccess(access));
                int lastError = Marshal.GetLastWin32Error();
                if (viewHandle.IsInvalid)
                {
                    viewHandle.Dispose();
                    throw Win32Marshal.GetExceptionForWin32Error(lastError);
                }
                // again query the view for its new size
                viewInfo = new Interop.Kernel32.MEMORY_BASIC_INFORMATION();
                Interop.Kernel32.VirtualQuery(viewHandle, ref viewInfo, (UIntPtr)Marshal.SizeOf(viewInfo));
                viewSize = (ulong)viewInfo.RegionSize;
            }

            // if the user specified DefaultSize as the size, we need to get the actual size
            if (size == MemoryMappedFile.DefaultSize)
            {
                size = (long)(viewSize - (ulong)extraMemNeeded);
            }
            else
            {
                Debug.Assert(viewSize >= (ulong)size, "viewSize < size");
            }

            viewHandle.Initialize((ulong)size + (ulong)extraMemNeeded);
            return(new MemoryMappedView(viewHandle, extraMemNeeded, size, access));
        }
        internal unsafe static MemoryMappedView CreateView(SafeMemoryMappedFileHandle memMappedFileHandle,
                                                           MemoryMappedFileAccess access, Int64 offset, Int64 size)
        {
            // MapViewOfFile can only create views that start at a multiple of the system memory allocation
            // granularity. We decided to hide this restriction form the user by creating larger views than the
            // user requested and hiding the parts that the user did not request.  extraMemNeeded is the amount of
            // extra memory we allocate before the start of the requested view. MapViewOfFile will also round the
            // capacity of the view to the nearest multiple of the system page size.  Once again, we hide this
            // from the user by preventing them from writing to any memory that they did not request.
            ulong extraMemNeeded = (ulong)offset % (ulong)MemoryMappedFile.GetSystemPageAllocationGranularity();

            // newOffset takes into account the fact that we have some extra memory allocated before the requested view
            ulong newOffset = (ulong)offset - extraMemNeeded;

            Debug.Assert(newOffset >= 0, "newOffset = (offset - extraMemNeeded) < 0");

            // determine size to pass to MapViewOfFile
            ulong nativeSize;

            if (size != MemoryMappedFile.DefaultSize)
            {
                nativeSize = (ulong)size + (ulong)extraMemNeeded;
            }
            else
            {
                nativeSize = 0;
            }

            if (IntPtr.Size == 4 && nativeSize > UInt32.MaxValue)
            {
                throw new ArgumentOutOfRangeException("size", SR.GetString(SR.ArgumentOutOfRange_CapacityLargerThanLogicalAddressSpaceNotAllowed));
            }

            // if request is >= than total virtual, then MapViewOfFile will fail with meaningless error message
            // "the parameter is incorrect"; this provides better error message in advance
            UnsafeNativeMethods.MEMORYSTATUSEX memStatus = new UnsafeNativeMethods.MEMORYSTATUSEX();
            bool  result       = UnsafeNativeMethods.GlobalMemoryStatusEx(ref memStatus);
            ulong totalVirtual = memStatus.ullTotalVirtual;

            if (nativeSize >= totalVirtual)
            {
                throw new IOException(SR.GetString(SR.IO_NotEnoughMemory));
            }

            // split the Int64 into two ints
            uint offsetLow  = (uint)(newOffset & 0x00000000FFFFFFFFL);
            uint offsetHigh = (uint)(newOffset >> 32);

            // create the view
            SafeMemoryMappedViewHandle viewHandle = UnsafeNativeMethods.MapViewOfFile(memMappedFileHandle,
                                                                                      MemoryMappedFile.GetFileMapAccess(access), offsetHigh, offsetLow, new UIntPtr(nativeSize));

            if (viewHandle.IsInvalid)
            {
                __Error.WinIOError(Marshal.GetLastWin32Error(), String.Empty);
            }

            // Query the view for its size and allocation type
            UnsafeNativeMethods.MEMORY_BASIC_INFORMATION viewInfo = new UnsafeNativeMethods.MEMORY_BASIC_INFORMATION();
            UnsafeNativeMethods.VirtualQuery(viewHandle, ref viewInfo, (IntPtr)Marshal.SizeOf(viewInfo));
            ulong viewSize = (ulong)viewInfo.RegionSize;


            // Allocate the pages if we were using the MemoryMappedFileOptions.DelayAllocatePages option
            // OR check if the allocated view size is smaller than the expected native size
            // If multiple overlapping views are created over the file mapping object, the pages in a given region
            // could have different attributes(MEM_RESERVE OR MEM_COMMIT) as MapViewOfFile preserves coherence between
            // views created on a mapping object backed by same file.
            // In which case, the viewSize will be smaller than nativeSize required and viewState could be MEM_COMMIT
            // but more pages may need to be committed in the region.
            // This is because, VirtualQuery function(that internally invokes VirtualQueryEx function) returns the attributes
            // and size of the region of pages with matching attributes starting from base address.
            // VirtualQueryEx: http://msdn.microsoft.com/en-us/library/windows/desktop/aa366907(v=vs.85).aspx
            if (((viewInfo.State & UnsafeNativeMethods.MEM_RESERVE) != 0) || (viewSize < nativeSize))
            {
                ulong  allocSize  = (nativeSize == 0) ? viewSize : nativeSize;
                IntPtr tempHandle = UnsafeNativeMethods.VirtualAlloc(viewHandle, (UIntPtr)allocSize, UnsafeNativeMethods.MEM_COMMIT,
                                                                     MemoryMappedFile.GetPageAccess(access));
                int lastError = Marshal.GetLastWin32Error();
                // The following is commented out for backward compatibility.
                // Previously releases failed to check for this error so introducing this check
                // could cause new/different exceptions in existing code paths.
                // if (tempHandle == IntPtr.Zero) {
                //     __Error.WinIOError(lastError, String.Empty);
                // }

                // again query the view for its new size
                viewInfo = new UnsafeNativeMethods.MEMORY_BASIC_INFORMATION();
                UnsafeNativeMethods.VirtualQuery(viewHandle, ref viewInfo, (IntPtr)Marshal.SizeOf(viewInfo));
                viewSize = (ulong)viewInfo.RegionSize;
            }

            // if the user specified DefaultSize as the size, we need to get the actual size
            if (size == MemoryMappedFile.DefaultSize)
            {
                size = (Int64)(viewSize - extraMemNeeded);
            }
            else
            {
                Debug.Assert(viewSize >= (ulong)size, "viewSize < size");
            }

            viewHandle.Initialize((ulong)size + extraMemNeeded);
            MemoryMappedView mmv = new MemoryMappedView(viewHandle, (long)extraMemNeeded, size, access);

            return(mmv);
        }
 internal MemoryMappedFile(string path)
 {
     _mmf  = SIOMMF.MemoryMappedFile.CreateFromFile(path);
     _mmva = _mmf.CreateViewAccessor();
     _mmva.SafeMemoryMappedViewHandle.AcquirePointer(ref _ptr);
 }