예제 #1
0
        public void Grow(long minCapacity)
        {
            lock (SyncRoot) {
                _fileStream?.Dispose();
                _fileStream = new FileStream(_filename, FileMode.OpenOrCreate,
                                             FileAccess.ReadWrite, FileShare.ReadWrite, 4096,
                                             FileOptions.RandomAccess);

                // NB another thread could have increase the map size and _capacity could be stale
                var bytesCapacity = Math.Max(_fileStream.Length, minCapacity);

                var sec = new MemoryMappedFileSecurity();
                _mmf?.Dispose();
                var unique = ((long)Process.GetCurrentProcess().Id << 32) | _counter++;
                // NB: map name must be unique
                var mmf = MemoryMappedFile.CreateFromFile(_fileStream,
                                                          $@"{Path.GetFileName(_filename)}.{unique}", bytesCapacity,
                                                          MemoryMappedFileAccess.ReadWrite, sec, HandleInheritability.Inheritable,
                                                          false);
                _mmf = mmf;

                unsafe
                {
                    byte *ptr = (byte *)0;
                    _va = _mmf.CreateViewAccessor(0, bytesCapacity, MemoryMappedFileAccess.ReadWrite);
                    var sh = _va.SafeMemoryMappedViewHandle;
                    sh.AcquirePointer(ref ptr);
                    var ptrV = new IntPtr(ptr);
                    _buffer = new DirectBuffer(bytesCapacity, ptrV);
                }
                _capacity = bytesCapacity;
            }
        }
        /// <summary>
        /// Open method implementation
        /// </summary>
        public void Open()
        {
            if (!isopen)
            {
                var securitySettings = new MemoryMappedFileSecurity();
                // securitySettings.AddAccessRule(new AccessRule<MemoryMappedFileRights>(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MemoryMappedFileRights.FullControl, AccessControlType.Allow));
                securitySettings.AddAccessRule(new AccessRule <MemoryMappedFileRights>(new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null), MemoryMappedFileRights.FullControl, AccessControlType.Allow));
                securitySettings.AddAccessRule(new AccessRule <MemoryMappedFileRights>(new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null), MemoryMappedFileRights.FullControl, AccessControlType.Allow));
                if (!string.IsNullOrEmpty(ClientSIDsProxy.ADFSAccountSID))
                {
                    securitySettings.AddAccessRule(new AccessRule <MemoryMappedFileRights>(new SecurityIdentifier(ClientSIDsProxy.ADFSAccountSID), MemoryMappedFileRights.FullControl, AccessControlType.Allow));
                }
                if (!string.IsNullOrEmpty(ClientSIDsProxy.ADFSServiceSID))
                {
                    securitySettings.AddAccessRule(new AccessRule <MemoryMappedFileRights>(new SecurityIdentifier(ClientSIDsProxy.ADFSServiceSID), MemoryMappedFileRights.FullControl, AccessControlType.Allow));
                }
                if (!string.IsNullOrEmpty(ClientSIDsProxy.ADFSAdminGroupSID))
                {
                    securitySettings.AddAccessRule(new AccessRule <MemoryMappedFileRights>(new SecurityIdentifier(ClientSIDsProxy.ADFSAdminGroupSID), MemoryMappedFileRights.FullControl, AccessControlType.Allow));
                }

                memoryMappedFile = MemoryMappedFile.CreateOrOpen(MemoryMapName, maxsize, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.DelayAllocatePages, securitySettings, HandleInheritability.None);
                isopen           = true;
            }
        }
예제 #3
0
        }//end function

        public static T read_MMF <T>(string path_file) where T : struct
        {
            T item = new T();

            if (File.Exists(path_file))
            {
                byte[] bufferItem;

                MemoryMappedFileSecurity mSec = new MemoryMappedFileSecurity();
                mSec.AddAccessRule(new AccessRule <MemoryMappedFileRights>(new SecurityIdentifier(WellKnownSidType.WorldSid, null),
                                                                           MemoryMappedFileRights.FullControl, AccessControlType.Allow));

                using (FileStream stream = new FileStream(path_file, FileMode.OpenOrCreate))
                {
                    using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(stream, null, stream.Length,
                                                                                  MemoryMappedFileAccess.ReadWrite, mSec, HandleInheritability.None, true))
                    {
                        using (MemoryMappedViewAccessor mmfReader = mmf.CreateViewAccessor())
                        {
                            bufferItem = new byte[mmfReader.Capacity];
                            mmfReader.ReadArray <byte>(0, bufferItem, 0, bufferItem.Length);
                        }
                    }
                }

                int    objsize = Marshal.SizeOf(typeof(T));
                IntPtr buff    = Marshal.AllocHGlobal(objsize);
                Marshal.Copy(bufferItem, 0, buff, objsize);
                item = (T)Marshal.PtrToStructure(buff, typeof(T));
                Marshal.FreeHGlobal(buff);
            }

            return(item);
        }
예제 #4
0
        public DataInterface(bool server)
        {
            try
            {
                buffer = new UInt64[bufferSize];

                if (server)
                {
                    SecurityIdentifier everyone = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
                    var security = new MemoryMappedFileSecurity();
                    security.AddAccessRule(new AccessRule <MemoryMappedFileRights>(everyone, MemoryMappedFileRights.FullControl, AccessControlType.Allow));
                    mmf = MemoryMappedFile.CreateOrOpen(mmf_path, bufferSize * 8,
                                                        MemoryMappedFileAccess.ReadWrite,
                                                        MemoryMappedFileOptions.DelayAllocatePages, security,
                                                        HandleInheritability.Inheritable);
                }
                else
                {
                    mmf = MemoryMappedFile.OpenExisting(mmf_path);
                }
            }
            catch (Exception ex)
            {
                throw new System.ApplicationException("Error initializing memory interface " + ex.Message);
            }
        }
예제 #5
0
	public void Load(int Index){
			MemoryMappedFileSecurity CustomSecurity = new MemoryMappedFileSecurity();
CustomSecurity.AddAccessRule(new System.Security.AccessControl.AccessRule<MemoryMappedFileRights>("everyone", MemoryMappedFileRights.FullControl, System.Security.AccessControl.AccessControlType
.Allow));
			using(MemoryMappedFile mmf = MemoryMappedFile.CreateOrOpen("bits", (long)Math.Ceiling(Length/8.0), MemoryMappedFileAccess.ReadWriteExecute, MemoryMappedFileOptions.None, CustomSecurity, System.IO.HandleInheritability.Inheritable)){
			using (MemoryMappedViewStream stream = mmf.CreateViewStream())
           		{
				int Amount = (int)Math.Ceiling((double)(Length/Int32.MaxValue));
				int Remainder = (int)(Length%Int32.MaxValue);
				int length = (int)(Amount==Index?Math.Ceiling(Remainder/8.0):Math.Ceiling(Int32.MaxValue/8.0));
				byte[] buffer = BitArrayToByteArray(LoadedArray,0,LoadedArray.Length);
				stream.Position=(long)Math.Ceiling((Int32.MaxValue/8.0))*LoadedArrayIndex;
                		BinaryWriter writer = new BinaryWriter(stream);
				writer.Write(buffer);
				stream.Position=0;//(long)Math.Ceiling((Int32.MaxValue/8.0))*Index;
				BinaryReader reader = new BinaryReader(stream);
				buffer = new byte[(int)Math.Ceiling((Int32.MaxValue/8.0))];
				try{reader.Read(buffer,(int)Math.Ceiling((Int32.MaxValue/8.0))*Index,(int)Math.Ceiling((Int32.MaxValue/8.0)));} catch{LoadedArray = new BitArray((int)(length*8.0));}
           		}
			}
			//int ElementIndex = (int)Math.Floor((double)(T/Int32.MaxValue));
			//int Index = (int)(T%Int32.MaxValue);
			//Elements[ElementIndex][Index]=value;
		//}
	}
예제 #6
0
        public static T[] read_file_MMF <T>(string path_file)
        {
            T[] a = new T[] { };
            if (File.Exists(path_file))
            {
                byte[] bufferItem;

                MemoryMappedFileSecurity mSec = new MemoryMappedFileSecurity();
                mSec.AddAccessRule(new AccessRule <MemoryMappedFileRights>(new SecurityIdentifier(WellKnownSidType.WorldSid, null),
                                                                           MemoryMappedFileRights.FullControl, AccessControlType.Allow));

                using (FileStream stream = new FileStream(path_file, FileMode.OpenOrCreate))
                {
                    using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(stream, null, stream.Length,
                                                                                  MemoryMappedFileAccess.ReadWrite, mSec, HandleInheritability.None, true))
                    {
                        using (MemoryMappedViewAccessor mmfReader = mmf.CreateViewAccessor())
                        {
                            bufferItem = new byte[mmfReader.Capacity];
                            mmfReader.ReadArray <byte>(0, bufferItem, 0, bufferItem.Length);
                        }
                    }
                }

                using (MemoryStream memoryStream = new MemoryStream(bufferItem))
                {
                    BinaryFormatter bf = new BinaryFormatter();
                    a = bf.Deserialize(memoryStream) as T[];
                }
            }
            return(a);
        }
        // Note: in order to be consistent with other messagings (e.g. TcpMessaging) value 0 for timeouts mean infinite time.
        public SharedMemoryReceiver(string memoryMappedFileName, bool useExistingMemoryMappedFile, TimeSpan openTimeout, int maxMessageSize, MemoryMappedFileSecurity memmoryMappedFileSecurity)
        {
            using (EneterTrace.Entering())
            {
                myOpenTimeout          = (openTimeout == TimeSpan.Zero) ? TimeSpan.FromMilliseconds(-1) : openTimeout;
                myMemoryMappedFileName = memoryMappedFileName;
                myMaxMessageSize       = maxMessageSize;

                // If true then the listener will not create the new memory shared file but will open existing one.
                // This is useful for security restrictions if the functionality is used in the windows service.
                myUseExistingMemoryMappedFile = useExistingMemoryMappedFile;

                myMemmoryMappedFileSecurity = memmoryMappedFileSecurity;

                // If the security shall be applied.
                if (myMemmoryMappedFileSecurity != null)
                {
                    // Create the security for the WaitHandle sync logic.
                    myEventWaitHandleSecurity = new EventWaitHandleSecurity();
                    myEventWaitHandleSecurity.SetSecurityDescriptorSddlForm("S:(ML;;NW;;;LW)");
                    SecurityIdentifier        aSid         = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
                    EventWaitHandleAccessRule anAccessRule = new EventWaitHandleAccessRule(aSid,
                                                                                           EventWaitHandleRights.Modify | EventWaitHandleRights.Synchronize,
                                                                                           AccessControlType.Allow);
                    myEventWaitHandleSecurity.AddAccessRule(anAccessRule);
                }
            }
        }
예제 #8
0
        private MemoryMappedFile CreateFileIfMissing(string dir, string fileName)
        {
            string filePath = Path.Combine(dir, fileName);

            if (!File.Exists(filePath))
            {
                if (!Directory.Exists(dir))
                {
                    Directory.CreateDirectory(dir);
                }
            }

            var mmfName          = CatConstants.ID_MARK_FILE_MAP + "-" + fileName;
            MemoryMappedFile mmf = null;

            try
            {
                mmf = MemoryMappedFile.OpenExisting(mmfName, MemoryMappedFileRights.ReadWrite, HandleInheritability.Inheritable);
            }
            catch (System.IO.FileNotFoundException)
            {
                var stream = File.Open(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
#if NETFULL
                MemoryMappedFileSecurity security = new MemoryMappedFileSecurity();
                mmf = MemoryMappedFile.CreateFromFile(stream, mmfName, CatConstants.ID_MARK_FILE_SIZE,
                                                      MemoryMappedFileAccess.ReadWrite, security, HandleInheritability.Inheritable, false);
#else
                mmf = MemoryMappedFile.CreateFromFile(stream, mmfName, CatConstants.ID_MARK_FILE_SIZE,
                                                      MemoryMappedFileAccess.ReadWrite, HandleInheritability.Inheritable, false);
#endif
            }
            return(mmf);
        }
예제 #9
0
        private MemoryMappedFileSecurity MMFSecurity()
        {
            MemoryMappedFileSecurity security = new MemoryMappedFileSecurity();

            security.SetAccessRule(new AccessRule <MemoryMappedFileRights>(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MemoryMappedFileRights.ReadWrite, AccessControlType.Allow));
            return(security);
        }
예제 #10
0
            internal ManagedCommunicationBlock(string @namespace, string key, int bufferSize, int bufferId, IEnumerable <string> servicePrincpal)
            {
                Namespace = @namespace;
                Key       = key;

                EventWaitHandleSecurity  open        = null;
                MemoryMappedFileSecurity transparent = null;

                var service         = servicePrincpal.FirstOrDefault();
                var currentIdentity = WindowsIdentity.GetCurrent();

                if (service != null && currentIdentity != null)
                {
                    open = new EventWaitHandleSecurity();
                    open.AddAccessRule(new EventWaitHandleAccessRule(currentIdentity.Name, EventWaitHandleRights.FullControl, AccessControlType.Allow));
                    open.AddAccessRule(new EventWaitHandleAccessRule(service, EventWaitHandleRights.FullControl, AccessControlType.Allow));

                    transparent = new MemoryMappedFileSecurity();
                    transparent.AddAccessRule(new AccessRule <MemoryMappedFileRights>(currentIdentity.Name, MemoryMappedFileRights.FullControl, AccessControlType.Allow));
                    transparent.AddAccessRule(new AccessRule <MemoryMappedFileRights>(service, MemoryMappedFileRights.ReadWrite, AccessControlType.Allow));
                }

                _memoryMappedFile = MemoryMappedFile.CreateNew(
                    MakeName(@"\OpenCover_Profiler_Communication_MemoryMapFile_", bufferId),
                    bufferSize,
                    MemoryMappedFileAccess.ReadWrite,
                    MemoryMappedFileOptions.None,
                    transparent,
                    HandleInheritability.Inheritable);

                StreamAccessorComms = _memoryMappedFile.CreateViewStream(0, bufferSize, MemoryMappedFileAccess.ReadWrite);

                bool createdNew;

                ProfilerRequestsInformation = new EventWaitHandle(
                    false,
                    EventResetMode.ManualReset,
                    MakeName(@"\OpenCover_Profiler_Communication_SendData_Event_", bufferId),
                    out createdNew,
                    open);

                InformationReadyForProfiler = new EventWaitHandle(
                    false,
                    EventResetMode.ManualReset,
                    MakeName(@"\OpenCover_Profiler_Communication_ReceiveData_Event_", bufferId),
                    out createdNew,
                    open);

                InformationReadByProfiler = new EventWaitHandle(
                    false,
                    EventResetMode.ManualReset,
                    MakeName(@"\OpenCover_Profiler_Communication_ChunkData_Event_", bufferId),
                    out createdNew,
                    open);

                DataCommunication       = new byte[bufferSize];
                PinnedDataCommunication = GCHandle.Alloc(DataCommunication, GCHandleType.Pinned);
            }
예제 #11
0
        protected override MemoryMappedFile Create()
        {
            var customSecurity = new MemoryMappedFileSecurity();

            customSecurity.AddAccessRule(new System.Security.AccessControl.AccessRule <MemoryMappedFileRights>("everyone",
                                                                                                               MemoryMappedFileRights.FullControl, System.Security.AccessControl.AccessControlType.Allow));
            return(MemoryMappedFile.CreateOrOpen("ULog.TraceSwitcherChangedFile", size, MemoryMappedFileAccess.ReadWriteExecute,
                                                 MemoryMappedFileOptions.None, customSecurity, System.IO.HandleInheritability.Inheritable));
        }
        /// <summary>
        ///     Creates the memory mapped file used for storage info synchronization
        /// </summary>
        /// <returns>Memory mapped file</returns>
        protected virtual MemoryMappedFile CreateMemoryMappedFile()
        {
            var security = new MemoryMappedFileSecurity();
            var rule     = new AccessRule <MemoryMappedFileRights>(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MemoryMappedFileRights.FullControl, AccessControlType.Allow);

            security.AddAccessRule(rule);

            return(MemoryMappedFile.CreateOrOpen($"{(IsGlobal ? "Global\\" : "")}BlobStorage-{Id}-Info", 25 * 1024 * 1024, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, security, HandleInheritability.None));
        }
예제 #13
0
        private void CreateOrOpenFile()
        {
            var fileStream = new FileStream(_fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
            MemoryMappedFileSecurity mmfs = new MemoryMappedFileSecurity();

            _map = MemoryMappedFile.CreateFromFile(fileStream, Path.GetFileName(_fileName), _fileSize,
                                                   MemoryMappedFileAccess.ReadWrite, mmfs, HandleInheritability.Inheritable,
                                                   false);
        }
예제 #14
0
 private static void SetupMemoryMappedFileSecurity(MemoryMappedFileSecurity customSecurity)
 {
     if (customSecurity != null)
     {
         return;
     }
     customSecurity = new MemoryMappedFileSecurity();
     customSecurity.AddAccessRule(new AccessRule <MemoryMappedFileRights>("everyone",
                                                                          MemoryMappedFileRights.FullControl, AccessControlType.Allow));
 }
예제 #15
0
        private void DoReportingWork(PipelineContext context, IProducerConsumerCollection <string[]> output, ManualResetEvent pause, IProgress <int> progress)
        {
            string   filepath       = context.SourceFilePath;
            Encoding encodeingToUse = m_encoding;
            char     delim;

            if (context.Delimiter.Length == 1)
            {
                delim = context.Delimiter.ToCharArray()[0];
            }
            else
            {
                throw new InvalidCastException("MmfExtractor only supports single char delimiters");
            }
            int columncount = context.ColumnNames.Count();

            MemoryMappedFileSecurity security = new MemoryMappedFileSecurity();

            security.AddAccessRule(new System.Security.AccessControl.AccessRule <MemoryMappedFileRights>("everyone", MemoryMappedFileRights.FullControl, System.Security.AccessControl.AccessControlType.Allow));

            using (FileStream fs = new FileStream(filepath, FileMode.Open, FileAccess.Read))
            {
                m_Buffer = m_Buffer > fs.Length ? fs.Length : m_Buffer;
                using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(fs, "D2SMMF", m_Buffer, MemoryMappedFileAccess.Read, security, HandleInheritability.Inheritable, true))
                {
                    using (MemoryMappedViewStream view = mmf.CreateViewStream(0, 0, MemoryMappedFileAccess.Read))
                    {
                        byte[] charArray       = new byte[byteArraySize]; //initialize a bytearray to read bytes into from the stream
                        long   length          = view.Length;             //determine how long the stream is
                        long   currentPosition = 0;                       //determine where in the stream we are
                        //determine the offset when reading a new chunk of bytes, we need to do this because we cannot guarentee that the last byte is the end of a row
                        //if it isn't then the remainder will be placed at the beginning of the array and the offset will be updated so it is not overwritten when the next batch of bytes is read from the stream
                        int offset = 0;
                        while (currentPosition < length)
                        {
                            currentPosition +=
                                view.Read(charArray, offset, byteArraySize - offset);
                            foreach (string[] line in GetStrings(ref charArray, encodeingToUse, delim, columncount))
                            {
                                output.TryAdd(line);
                            }
                            offset = m_LatestOffset;
                        }
                        //when we break out of this loop we will be left with a char array holding the last line (which wont have an end of line character so getstrings() did not append it to the result list
                        //we know that the length of this line is m_latestoffset so we can simply read it and add it before closing all resources and completing the task
                        char[] rawlastRow = encodeingToUse.GetChars(charArray, 0, m_LatestOffset);
                        //we're gonna have a bunch of null chars /0 in here so were just gonna trim those out rly quick
                        char[]   lastRow         = TrimNulls(rawlastRow);
                        string   lastRowAsString = new string(lastRow);
                        string[] finalResult     = lastRowAsString.Split(delim);
                        output.TryAdd(finalResult);
                    }
                }
            }
        }
예제 #16
0
 public SharedMemoryConnectorFactory(IProtocolFormatter protocolFormatter, TimeSpan connectTimeout, TimeSpan sendTimeout, int maxMessageSize, MemoryMappedFileSecurity memoryMappedFileSecurity)
 {
     using (EneterTrace.Entering())
     {
         myProtocolFormatter = protocolFormatter;
         myConnectTimeout    = connectTimeout;
         mySendTimeout       = sendTimeout;
         myMaxMessageSize    = maxMessageSize;
         mySecurity          = memoryMappedFileSecurity;
     }
 }
예제 #17
0
 public IMemoryMappedFile CreateOrOpen(
     string mapName,
     long capacity,
     MemoryMappedFileAccess access,
     MemoryMappedFileOptions options,
     MemoryMappedFileSecurity memoryMappedFileSecurity,
     HandleInheritability inheritability)
 {
     return new MemoryMappedFileWrapper(MemoryMappedFile.CreateOrOpen(
         mapName, capacity, access, options, memoryMappedFileSecurity, inheritability));
 }
예제 #18
0
        private void Form1_Load(object sender, EventArgs e)       //폼이 로드되면
        {
            comboBox_port.DataSource = SerialPort.GetPortNames(); //연결 가능한 시리얼포트 이름을 콤보박스에 가져오기
            MemoryMappedFileSecurity CustomSecurity = new MemoryMappedFileSecurity();
            SecurityIdentifier       sid            = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
            var acct = sid.Translate(typeof(NTAccount)) as NTAccount;

            CustomSecurity.AddAccessRule(new System.Security.AccessControl.AccessRule <MemoryMappedFileRights>(acct.ToString(), MemoryMappedFileRights.FullControl, System.Security.AccessControl.AccessControlType.Allow));
            sharedBuffer         = MemoryMappedFile.CreateOrOpen("Local\\BROKENITHM_SHARED_BUFFER", 1024, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, CustomSecurity, System.IO.HandleInheritability.Inheritable);
            sharedBufferAccessor = sharedBuffer.CreateViewAccessor();
        }
예제 #19
0
 public IMemoryMappedFile CreateOrOpen(
     string mapName,
     long capacity,
     MemoryMappedFileAccess access,
     MemoryMappedFileOptions options,
     MemoryMappedFileSecurity memoryMappedFileSecurity,
     HandleInheritability inheritability)
 {
     return(new MemoryMappedFileWrapper(MemoryMappedFile.CreateOrOpen(
                                            mapName, capacity, access, options, memoryMappedFileSecurity, inheritability)));
 }
예제 #20
0
        private MemoryMapBuffer(string file, bool useGlobalNamespace, FileInfo fileInfo) : base((int)fileInfo.Length)
        {
            // Ideally we would use the file ID in the mapName, but it is not
            // easily available from C#.
            var objectNamespace = useGlobalNamespace ? "Global" : "Local";

            string?mapName = $"{objectNamespace}\\{fileInfo.FullName.Replace("\\", "-")}-{Length}";

            lock (FileLocker)
            {
                try
                {
                    _memoryMappedFile = MemoryMappedFile.OpenExisting(mapName, MemoryMappedFileRights.Read);
                }
#if !NETSTANDARD1_4 && !NETSTANDARD2_0 && !NETSTANDARD2_1
                catch (Exception ex) when(ex is IOException || ex is NotImplementedException)
#else           // Note that PNSE is only required by .NetStandard1.0, see the subsequent comment for more context
                catch (Exception ex) when(ex is IOException || ex is NotImplementedException || ex is PlatformNotSupportedException)
#endif
                {
                    var stream = new FileStream(file, FileMode.Open, FileAccess.Read,
                                                FileShare.Delete | FileShare.Read);

#if !NETSTANDARD1_4 && !NETSTANDARD2_0 && !NETSTANDARD2_1
                    var security = new MemoryMappedFileSecurity();
                    security.AddAccessRule(
                        new System.Security.AccessControl.AccessRule <MemoryMappedFileRights>(
                            new System.Security.Principal.SecurityIdentifier(System.Security.Principal.WellKnownSidType.WorldSid, null),
                            MemoryMappedFileRights.Read,
                            System.Security.AccessControl.AccessControlType.Allow));

                    _memoryMappedFile = MemoryMappedFile.CreateFromFile(stream, mapName, Length,
                                                                        MemoryMappedFileAccess.Read, security, HandleInheritability.None, false);
#else
                    // In .NET Core, named maps are not supported for Unices yet: https://github.com/dotnet/corefx/issues/1329
                    // When executed on unsupported platform, we get the PNSE. In which case, we consruct the memory map by
                    // setting mapName to null.
                    if (ex is PlatformNotSupportedException)
                    {
                        mapName = null;
                    }

                    // In NetStandard1.0 (docs: http://bit.ly/1TOKXEw) and since .Net46 (https://msdn.microsoft.com/en-us/library/dn804422.aspx)
                    // CreateFromFile has a new overload with six arguments (modulo MemoryMappedFileSecurity). While the one with seven arguments
                    // is still available in .Net46, that has been removed from netstandard1.0.
                    _memoryMappedFile = MemoryMappedFile.CreateFromFile(stream, mapName, Length,
                                                                        MemoryMappedFileAccess.Read, HandleInheritability.None, false);
#endif
                }
            }

            _view = _memoryMappedFile.CreateViewAccessor(0, Length, MemoryMappedFileAccess.Read);
        }
예제 #21
0
        private static MemoryMappedFileSecurity CreateDefaultSecurity()
        {
            var sec = new MemoryMappedFileSecurity();

            // Deny network access (actually unnecessary, since the memory mapped file cannot be accessed over the network)
            sec.AddAccessRule(new AccessRule <MemoryMappedFileRights>(new SecurityIdentifier(WellKnownSidType.NetworkSid, null), MemoryMappedFileRights.FullControl, AccessControlType.Deny));
            // Allow everyone on the machine to connect
            sec.AddAccessRule(new AccessRule <MemoryMappedFileRights>(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MemoryMappedFileRights.Read, AccessControlType.Allow));
            // Allow the current user should have full control.
            sec.AddAccessRule(new AccessRule <MemoryMappedFileRights>(WindowsIdentity.GetCurrent().User, MemoryMappedFileRights.FullControl, AccessControlType.Allow));
            return(sec);
        }
예제 #22
0
        /// <summary>
        /// Creates a new SharedMemory instance.
        /// </summary>
        /// <param name="isOwnerProcess">Pass true only if this is the process which should own the shared memory.  E.g. the one which starts first and lives longer than all other related processes.  The owner process must prepare the shared memory before spawning other processes which will use the shared memory, and ideally keep the shared memory alive until other processes are closed.</param>
        /// <param name="uniqueId">An ID which is unique to this application.</param>
        private SharedMemoryStream(bool isOwnerProcess, string uniqueId)
        {
            this.isOwnerProcess = isOwnerProcess;
            string mmf_uniqueId  = "Global\\SHRD.SMS.MMF." + uniqueId;
            string ewh1_uniqueId = "Global\\SHRD.SMS.EWH1." + uniqueId;
            string ewh2_uniqueId = "Global\\SHRD.SMS.EWH2." + uniqueId;

            if (isOwnerProcess)
            {
                // Set up security objects
                SecurityIdentifier users       = new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null);
                SecurityIdentifier localSystem = new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null);

                MemoryMappedFileSecurity mmf_security = new MemoryMappedFileSecurity();
                mmf_security.AddAccessRule(new AccessRule <MemoryMappedFileRights>(users, MemoryMappedFileRights.FullControl, AccessControlType.Allow));
                mmf_security.AddAccessRule(new AccessRule <MemoryMappedFileRights>(localSystem, MemoryMappedFileRights.FullControl, AccessControlType.Allow));

                var ewh_security = new EventWaitHandleSecurity();
                ewh_security.AddAccessRule(new EventWaitHandleAccessRule(users, EventWaitHandleRights.FullControl, AccessControlType.Allow));
                ewh_security.AddAccessRule(new EventWaitHandleAccessRule(localSystem, EventWaitHandleRights.FullControl, AccessControlType.Allow));

                // Set up Shared Memory
                _mmf         = MemoryMappedFile.CreateOrOpen(mmf_uniqueId, memoryMappedFileSize, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.DelayAllocatePages, mmf_security, HandleInheritability.Inheritable);
                viewAccessor = _mmf.CreateViewAccessor(0, memoryMappedFileSize);

                // Set up EventWaitHandles
                bool createdNew;
                if (!EventWaitHandle.TryOpenExisting(ewh1_uniqueId, out _ewh_read))
                {
                    _ewh_read = new EventWaitHandle(false, EventResetMode.ManualReset, ewh1_uniqueId, out createdNew, ewh_security);
                }
                _ewh_read.Set();
                if (!EventWaitHandle.TryOpenExisting(ewh2_uniqueId, out _ewh_write))
                {
                    _ewh_write = new EventWaitHandle(false, EventResetMode.ManualReset, ewh2_uniqueId, out createdNew, ewh_security);
                }
                _ewh_write.Set();
                myIncomingStreamStartsAt = metadataSize;
                myOutgoingStreamStartsAt = metadataSize + bufferSize;
            }
            else
            {
                // Set up Shared Memory
                _mmf         = MemoryMappedFile.OpenExisting(mmf_uniqueId, MemoryMappedFileRights.ReadWrite);
                viewAccessor = _mmf.CreateViewAccessor(0, memoryMappedFileSize);
                // This is the "slave process" so the read and write handles are reversed.
                _ewh_write = EventWaitHandle.OpenExisting(ewh1_uniqueId);
                _ewh_read  = EventWaitHandle.OpenExisting(ewh2_uniqueId);
                myOutgoingStreamStartsAt = metadataSize;
                myIncomingStreamStartsAt = metadataSize + bufferSize;
            }
        }
예제 #23
0
        public void WriteObjectToMMF(string mmfFile, object objectData, bool createNewMmf)
        {
            // Convert .NET object to byte array
            byte[]           buffer = ObjectToByteArray(objectData);
            MemoryMappedFile mmf;

            if (createNewMmf)
            {
                var security = new MemoryMappedFileSecurity();

                security.AddAccessRule(new System.Security.AccessControl.AccessRule <MemoryMappedFileRights>(
                                           new SecurityIdentifier(WellKnownSidType.WorldSid, null),
                                           MemoryMappedFileRights.FullControl, System.Security.AccessControl.AccessControlType.Allow));
                security.AddAccessRule(new System.Security.AccessControl.AccessRule <MemoryMappedFileRights>(
                                           new SecurityIdentifier(WellKnownSidType.AnonymousSid, null),
                                           MemoryMappedFileRights.FullControl, System.Security.AccessControl.AccessControlType.Allow));
                security.AddAccessRule(new System.Security.AccessControl.AccessRule <MemoryMappedFileRights>(
                                           new SecurityIdentifier(WellKnownSidType.NullSid, null),
                                           MemoryMappedFileRights.FullControl, System.Security.AccessControl.AccessControlType.Allow));

                // printing the SID from the screensaver shows that we are running as Local Service
                security.AddAccessRule(new System.Security.AccessControl.AccessRule <MemoryMappedFileRights>(
                                           new SecurityIdentifier(WellKnownSidType.LocalServiceSid, null),
                                           MemoryMappedFileRights.FullControl, System.Security.AccessControl.AccessControlType.Allow));
                // Create a new memory mapped file
                mmf = MemoryMappedFile.CreateOrOpen(mmfFile, buffer.Length, MemoryMappedFileAccess.ReadWriteExecute, MemoryMappedFileOptions.None, security, System.IO.HandleInheritability.Inheritable);
            }
            else
            {
                try
                {
                    mmf = MemoryMappedFile.OpenExisting(mmfFile, MemoryMappedFileRights.ReadWriteExecute, System.IO.HandleInheritability.Inheritable);
                }
                catch (FileNotFoundException)
                {
                    return;
                }
            }

            bool  mutexCreated;
            Mutex mutex = new Mutex(true, "mmfMutex", out mutexCreated);
            // Create a view accessor into the file to accommmodate binary data size
            MemoryMappedViewAccessor mmfWriter = mmf.CreateViewAccessor(0, buffer.Length);

            // Write the data
            mmfWriter.WriteArray <byte>(0, buffer, 0, buffer.Length);
            mmfWriter.Flush();
            if (mutexCreated)
            {
                mutex.ReleaseMutex();
            }
        }
예제 #24
0
            internal ManagedMemoryBlock(string @namespace, string key, int bufferSize, int bufferId, IEnumerable <string> servicePrincpal)
            {
                Namespace = @namespace;
                Key       = key;

                EventWaitHandleSecurity  open        = null;
                MemoryMappedFileSecurity transparent = null;

                var service         = servicePrincpal.FirstOrDefault();
                var currentIdentity = WindowsIdentity.GetCurrent();

                if (service != null && currentIdentity != null)
                {
                    open = new EventWaitHandleSecurity();
                    open.AddAccessRule(new EventWaitHandleAccessRule(currentIdentity.Name, EventWaitHandleRights.FullControl, AccessControlType.Allow));

                    // The event handles need more than just EventWaitHandleRights.Modify | EventWaitHandleRights.Synchronize to work
                    open.AddAccessRule(new EventWaitHandleAccessRule(service, EventWaitHandleRights.FullControl, AccessControlType.Allow));

                    transparent = new MemoryMappedFileSecurity();
                    transparent.AddAccessRule(new AccessRule <MemoryMappedFileRights>(currentIdentity.Name, MemoryMappedFileRights.FullControl, AccessControlType.Allow));
                    transparent.AddAccessRule(new AccessRule <MemoryMappedFileRights>(service, MemoryMappedFileRights.ReadWrite, AccessControlType.Allow));
                }

                bool createdNew;

                ProfilerHasResults = new EventWaitHandle(
                    false,
                    EventResetMode.ManualReset,
                    MakeName(@"\OpenCover_Profiler_Communication_SendResults_Event_", bufferId),
                    out createdNew,
                    open);

                ResultsHaveBeenReceived = new EventWaitHandle(
                    false,
                    EventResetMode.ManualReset,
                    MakeName(@"\OpenCover_Profiler_Communication_ReceiveResults_Event_", bufferId),
                    out createdNew,
                    open);

                _mmfResults = MemoryMappedFile.CreateNew(
                    MakeName(@"\OpenCover_Profiler_Results_MemoryMapFile_", bufferId),
                    bufferSize,
                    MemoryMappedFileAccess.ReadWrite,
                    MemoryMappedFileOptions.None,
                    transparent,
                    HandleInheritability.Inheritable);

                StreamAccessorResults = _mmfResults.CreateViewStream(0, bufferSize, MemoryMappedFileAccess.ReadWrite);
                StreamAccessorResults.Write(BitConverter.GetBytes(0), 0, 4);
                BufferSize = bufferSize;
            }
예제 #25
0
 public BDFEDFAccessor(BDFEDFFileStream.BDFEDFFileStream bdf)
 {
     isBDF = bdf.header.isBDFFile;
     recordLength = bdf.NumberOfSamples(0) * (isBDF ? 3 : 2);
     recordSetLength = recordLength * bdf.NumberOfChannels;
     long size = (long)bdf.NumberOfRecords * recordSetLength;
     MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(bdf.baseStream, "MMF",
         size + bdf.header.headerSize, MemoryMappedFileAccess.ReadWrite, null,
         System.IO.HandleInheritability.Inheritable, false);
     _BDFEDFHeader = bdf.header;
     MemoryMappedFileSecurity mmfs = new MemoryMappedFileSecurity();
     accessor = mmf.CreateViewAccessor(bdf.header.headerSize, size);
 }
예제 #26
0
        public static MemoryMappedFileSecurity GetMemoryMappedFileSecurity()
        {
            MemoryMappedFileSecurity result = new MemoryMappedFileSecurity();

            result.AddAccessRule(new AccessRule <MemoryMappedFileRights>(
                                     new SecurityIdentifier(WellKnownSidType.WorldSid, null),
                                     MemoryMappedFileRights.FullControl,
                                     AccessControlType.Allow
                                     )
                                 );

            return(result);
        }
예제 #27
0
        private static void Initialize()
        {
            var security = new MemoryMappedFileSecurity();
            var sid      = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
            var account  = sid.Translate(typeof(NTAccount)) as NTAccount;

            Debug.Assert(account != null);
            security.AddAccessRule(new System.Security.AccessControl.AccessRule <MemoryMappedFileRights>(account.ToString(), MemoryMappedFileRights.FullControl, System.Security.AccessControl.AccessControlType.Allow));
            _buffer   = MemoryMappedFile.CreateOrOpen("Local\\BROKENITHM_SHARED_BUFFER", 1024, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, security, System.IO.HandleInheritability.Inheritable);
            _accessor = _buffer.CreateViewAccessor();

            _init = true;
        }
예제 #28
0
        //private Mutex _screenAccessLock;
        //private MemoryMappedFile _screenSharedMem;
        //private MemoryMappedViewAccessor _screenAccessor;

        public ShMem()
        {
            var newMutex      = false;
            var mutexSecurity = new MutexSecurity(); mutexSecurity.AddAccessRule(new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow));
            var memSecurity   = new MemoryMappedFileSecurity(); memSecurity.AddAccessRule(new AccessRule <MemoryMappedFileRights>(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MemoryMappedFileRights.FullControl, AccessControlType.Allow));

            _commAccessLock = new Mutex(false, "Global\\CustomHMDCommLock", out newMutex, mutexSecurity);
            _commSharedMem  = MemoryMappedFile.CreateOrOpen("CustomHMDComm", _commBufferSize, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, memSecurity, System.IO.HandleInheritability.Inheritable);
            _commAccessor   = _commSharedMem.CreateViewAccessor();

            //_screenAccessLock = new Mutex(false, "Global\\CustomHMDScreenLock", out newMutex, mutexSecurity);
            //_screenSharedMem = MemoryMappedFile.CreateOrOpen("CustomHMDLeft", _screenBufferSize, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, memSecurity, System.IO.HandleInheritability.Inheritable);
            //_screenAccessor = _screenSharedMem.CreateViewAccessor();
        }
예제 #29
0
        public static MemoryMappedFileSecurity MapSecurity(bool create)
            {
            SecurityIdentifier user = GetEveryoneSID();
            MemoryMappedFileSecurity result = new MemoryMappedFileSecurity();

            MemoryMappedFileRights rights = MemoryMappedFileRights.ReadWrite;
            if (create)
                rights |= MemoryMappedFileRights.Delete;

            AccessRule<MemoryMappedFileRights> rule = new AccessRule<MemoryMappedFileRights>(user, rights, AccessControlType.Allow);
            result.AddAccessRule(rule);

            return result;
            }
        /// <summary>
        /// Initializes security attributes for the shared memory queue.
        /// </summary>
        /// <remarks>
        /// This method initializes security attributes for creating the shared memory queues.
        /// Anyone is allowed read/write (no user specific security).
        /// </remarks>
        private static void InitializeSecurityAttributes()
        {
            sMemoryMappedFileSecurity = new MemoryMappedFileSecurity();

            var rule = (AccessRule <MemoryMappedFileRights>)sMemoryMappedFileSecurity.AccessRuleFactory(
                new SecurityIdentifier(WellKnownSidType.WorldSid, null),
                (int)MemoryMappedFileRights.ReadWrite,
                false,
                InheritanceFlags.None,
                PropagationFlags.None,
                AccessControlType.Allow);

            sMemoryMappedFileSecurity.AddAccessRule(rule);
        }
예제 #31
0
        public SharedMemoryInputConnector(string inputConnectorAddress, IProtocolFormatter protocolFormatter, TimeSpan sendResponseTimeout, int maxMessageSize, MemoryMappedFileSecurity memoryMappedFileSecurity)
        {
            using (EneterTrace.Entering())
            {
                myProtocolFormatter   = protocolFormatter;
                myMaxMessageSize      = maxMessageSize;
                mySendResponseTimeout = sendResponseTimeout;
                mySecurity            = memoryMappedFileSecurity;

                // Note: openTimeout is not used if SharedMemoryReceiver creates memory mapped file.
                TimeSpan aDummyOpenTimout = TimeSpan.Zero;
                myReceiver = new SharedMemoryReceiver(inputConnectorAddress, false, aDummyOpenTimout, myMaxMessageSize, mySecurity);
            }
        }
예제 #32
0
        void createMemoryMappedFile()
        {
            MemoryMappedFileSecurity acl = new MemoryMappedFileSecurity();

            acl.AddAccessRule(new AccessRule <MemoryMappedFileRights>(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MemoryMappedFileRights.FullControl, AccessControlType.Allow));
            MemoryMappedFile       mmfKernel  = MemoryMappedFile.CreateNew("Global\\graŻabkaMMF", 1024, MemoryMappedFileAccess.ReadWrite, 0, acl, 0);
            MemoryMappedViewStream mmvsKernel = mmfKernel.CreateViewStream(0, 1024);
            BinaryFormatter        formatter  = new BinaryFormatter();

            formatter.Serialize(mmvsKernel, "żabka ze sterownika");
            mmvsKernel.Seek(0, SeekOrigin.Begin);
            Semaphore semaphore = new Semaphore(1, 1, @"Global\graŻabkaSemaphore");

            semaphore.Release();
        }
 public SharedMemoryOutputConnector(string inputConnectorAddress, string outputConnectorAddress,
                                    IProtocolFormatter protocolFormatter,
                                    TimeSpan connectTimeout,
                                    TimeSpan sendTimeout,
                                    int maxMessageSize, MemoryMappedFileSecurity memoryMappedFileSecurity)
 {
     using (EneterTrace.Entering())
     {
         myInputConnectorAddress  = inputConnectorAddress;
         myOutputConnectorAddress = outputConnectorAddress;
         myProtocolFormatter      = protocolFormatter;
         myConnectTimeout         = connectTimeout;
         mySendTimeout            = sendTimeout;
         myMaxMessageSize         = maxMessageSize;
         mySecurity = memoryMappedFileSecurity;
     }
 }
예제 #34
0
 public IMemoryMappedFile CreateFromFile(
     FileStream fileStream,
     string mapName,
     long capacity,
     MemoryMappedFileAccess access,
     MemoryMappedFileSecurity memoryMappedFileSecurity,
     HandleInheritability inheritability,
     bool leaveOpen)
 {
     return new MemoryMappedFileWrapper(MemoryMappedFile.CreateFromFile(
         fileStream,
         mapName,
         capacity,
         access,
         memoryMappedFileSecurity,
         inheritability,
         leaveOpen));
 }
예제 #35
0
파일: Util.cs 프로젝트: harishraj/tools
        public static MemoryMappedFileSecurity MapSecurity(bool create)
        {
            SecurityIdentifier       user   = GetEveryoneSID();
            MemoryMappedFileSecurity result = new MemoryMappedFileSecurity();

            MemoryMappedFileRights rights = MemoryMappedFileRights.ReadWrite;

            if (create)
            {
                rights |= MemoryMappedFileRights.Delete;
            }

            AccessRule <MemoryMappedFileRights> rule = new AccessRule <MemoryMappedFileRights>(user, rights, AccessControlType.Allow);

            result.AddAccessRule(rule);

            return(result);
        }
예제 #36
0
	public bool this[long T]{
		get{
			MemoryMappedFileSecurity CustomSecurity = new MemoryMappedFileSecurity();
CustomSecurity.AddAccessRule(new System.Security.AccessControl.AccessRule<MemoryMappedFileRights>("everyone", MemoryMappedFileRights.FullControl, System.Security.AccessControl.AccessControlType
.Allow));
			using(MemoryMappedFile mmf = MemoryMappedFile.CreateOrOpen("bits", (long)Math.Ceiling(Length/8.0), MemoryMappedFileAccess.ReadWriteExecute, MemoryMappedFileOptions.None, CustomSecurity, System.IO.HandleInheritability.Inheritable)){
			using (MemoryMappedViewStream stream = mmf.CreateViewStream())
           		{
				byte[] buffer = new byte[1];
                		BinaryReader reader = new BinaryReader(stream);
     				try{reader.Read(buffer,(int)Math.Floor(T/8.0),1);}
				catch{return false;}
				
				BitArray bits = new BitArray(buffer);
				return bits[(int)(T%8.0)];
           		}
			}
			//int ElementIndex = (int)Math.Floor((double)(T/Int32.MaxValue));
			//int Index = (int)(T%Int32.MaxValue);
			//return Elements[ElementIndex][Index];
		}
		set{
			MemoryMappedFileSecurity CustomSecurity = new MemoryMappedFileSecurity();
CustomSecurity.AddAccessRule(new System.Security.AccessControl.AccessRule<MemoryMappedFileRights>("everyone", MemoryMappedFileRights.FullControl, System.Security.AccessControl.AccessControlType
.Allow));
			using(MemoryMappedFile mmf = MemoryMappedFile.CreateOrOpen("bits", (long)Math.Ceiling(Length/8.0), MemoryMappedFileAccess.ReadWriteExecute, MemoryMappedFileOptions.None, CustomSecurity, System.IO.HandleInheritability.Inheritable)){
			using (MemoryMappedViewStream stream = mmf.CreateViewStream(0,(long)Math.Ceiling(Length/8.0),MemoryMappedFileAccess.ReadWrite))
           		{
				byte[] ExistingByte=new byte[1]{Read(T,stream)};
				BitArray bits = new BitArray(ExistingByte);
				bits[(int)(T%8.0)]=value;
				byte[] buffer = new byte[1]{ConvertToByte(bits)};
				stream.Position=(long)Math.Floor(T/8.0);
                		BinaryWriter writer = new BinaryWriter(stream);
				writer.Write(buffer);
           		}
			}
			//int ElementIndex = (int)Math.Floor((double)(T/Int32.MaxValue));
			//int Index = (int)(T%Int32.MaxValue);
			//Elements[ElementIndex][Index]=value;
		}
	}
예제 #37
0
 ///// <summary>
 ///// Get a working view for the current thread
 ///// </summary>
 ///// <param name="threadId"></param>
 ///// <returns></returns>
 //public Stream GetView(int threadId)
 //{
 //    return Mmf.CreateViewStream();
 //}
 private static MemoryMappedFile CreateOrOpenFile(string fileName,
     long capacity, PersistenceMode persistenceMode, Mutex mutex, bool forGrowth)
 {
     try {
         mutex.WaitOne();
         switch (persistenceMode) {
             case PersistenceMode.TemporaryPersist:
                 // we are first to the party since have created the mutex, will create new file instead of previous
                 // we could avoid using semaphore here because mutex.Created = semaphore.Created
                 if (mutex.Created && !forGrowth) { DeleteBackingFileIfExists(fileName); }
                 goto case PersistenceMode.Persist;
             case PersistenceMode.Persist:
                 var fileStream = new FileStream(fileName, FileMode.OpenOrCreate,
                     FileAccess.ReadWrite, FileShare.ReadWrite);
                 var mmfs = new MemoryMappedFileSecurity();
                 capacity = Math.Max(fileStream.Length, capacity);
                 return MemoryMappedFile.CreateFromFile(fileStream,
                     Path.GetFileName(fileName), capacity,
                     MemoryMappedFileAccess.ReadWrite, mmfs, HandleInheritability.Inheritable,
                     false);
             case PersistenceMode.Ephemeral:
                 return MemoryMappedFile.CreateOrOpen(Path.GetFileName(fileName), capacity, MemoryMappedFileAccess.ReadWrite);
             default:
                 throw new ArgumentOutOfRangeException("persistenceMode");
         }
     } finally {
         mutex.ReleaseMutex();
     }
 }
예제 #38
0
파일: DbgView.cs 프로젝트: xxy1991/cozy
    private void ListenerThread(object state)
    {
        EventWaitHandle bufferReadyEvent = null;
        EventWaitHandle dataReadyEvent = null;
        MemoryMappedFile memoryMappedFile = null;

        try
        {
            bool createdNew;
            var everyone = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
            var eventSecurity = new EventWaitHandleSecurity();
            eventSecurity.AddAccessRule(new EventWaitHandleAccessRule(everyone, EventWaitHandleRights.Modify | EventWaitHandleRights.Synchronize, AccessControlType.Allow));

            bufferReadyEvent = new EventWaitHandle(false, EventResetMode.AutoReset, "DBWIN_BUFFER_READY", out createdNew, eventSecurity);
            if (!createdNew) throw new Exception("Some DbgView already running");

            dataReadyEvent = new EventWaitHandle(false, EventResetMode.AutoReset, "DBWIN_DATA_READY", out createdNew, eventSecurity);
            if (!createdNew) throw new Exception("Some DbgView already running");

            var memoryMapSecurity = new MemoryMappedFileSecurity();
            memoryMapSecurity.AddAccessRule(new AccessRule<MemoryMappedFileRights>(everyone, MemoryMappedFileRights.ReadWrite, AccessControlType.Allow));
            memoryMappedFile = MemoryMappedFile.CreateNew("DBWIN_BUFFER", 4096, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, memoryMapSecurity, System.IO.HandleInheritability.None);

            bufferReadyEvent.Set();
            this.writer.WriteLine("[DbgView] Started.");

            using (var accessor = memoryMappedFile.CreateViewAccessor())
            {
                byte[] buffer = new byte[4096];
                while (dataReadyEvent.WaitOne())
                {
                    accessor.ReadArray<byte>(0, buffer, 0, buffer.Length);
                    int processId = BitConverter.ToInt32(buffer, 0);
                    int terminator = Array.IndexOf<byte>(buffer, 0, 4);
                    string msg = Encoding.Default.GetString(buffer, 4, (terminator < 0 ? buffer.Length : terminator) - 4);
                    if (hashSet.Contains(processId))
                    {
                        if (msg == "CozyDebugOutput HideDebugPrint")
                        {
                            hashSet.Remove(processId);
                        }
                        writer.WriteLine("[{0:00000}] {1}", processId, msg);
                    }
                    else if (msg == "CozyDebugOutput ShowDebugPrint")
                    {
                        hashSet.Add(processId);
                        writer.WriteLine("[{0:00000}] {1}", processId, msg);
                    }
                    bufferReadyEvent.Set();
                }
            }
        }
        catch (ThreadInterruptedException)
        {
            this.writer.WriteLine("[DbgView] Stopped.");
        }
        catch (Exception e)
        {
            this.writer.WriteLine("[DbgView] Error: " + e.Message);
        }
        finally
        {
            foreach (var disposable in new IDisposable[] { bufferReadyEvent, dataReadyEvent, memoryMappedFile })
            {
                if (disposable != null) disposable.Dispose();
            }
        }
    }
        private unsafe static UnsafeNativeMethods.SECURITY_ATTRIBUTES GetSecAttrs(HandleInheritability inheritability, 
                                        MemoryMappedFileSecurity memoryMappedFileSecurity, out Object pinningHandle) {
            
            pinningHandle = null;
            UnsafeNativeMethods.SECURITY_ATTRIBUTES secAttrs = null;
            if ((inheritability & HandleInheritability.Inheritable) != 0 ||
                memoryMappedFileSecurity != null) {
                secAttrs = new UnsafeNativeMethods.SECURITY_ATTRIBUTES();
                secAttrs.nLength = (Int32)Marshal.SizeOf(secAttrs);

                if ((inheritability & HandleInheritability.Inheritable) != 0) {
                    secAttrs.bInheritHandle = 1;
                }

                // For ACLs, get the security descriptor from the MemoryMappedFileSecurity.
                if (memoryMappedFileSecurity != null) {
                    byte[] sd = memoryMappedFileSecurity.GetSecurityDescriptorBinaryForm();
                    pinningHandle = GCHandle.Alloc(sd, GCHandleType.Pinned);
                    fixed (byte* pSecDescriptor = sd)
                        secAttrs.pSecurityDescriptor = pSecDescriptor;
                }
            }
            return secAttrs;
        }
예제 #40
0
            internal ManagedCommunicationBlock(string @namespace, string key, int bufferSize, int bufferId, IEnumerable<string> servicePrincpal)
            {
                Namespace = @namespace;
                Key = key;

                EventWaitHandleSecurity open = null;
                MemoryMappedFileSecurity transparent = null;

                var service = servicePrincpal.FirstOrDefault();
                var currentIdentity = WindowsIdentity.GetCurrent();
                if (service != null && currentIdentity != null)
                {
                    open = new EventWaitHandleSecurity();
                    open.AddAccessRule(new EventWaitHandleAccessRule(currentIdentity.Name, EventWaitHandleRights.FullControl, AccessControlType.Allow));
                    open.AddAccessRule(new EventWaitHandleAccessRule(service, EventWaitHandleRights.FullControl, AccessControlType.Allow));

                    transparent = new MemoryMappedFileSecurity();
                    transparent.AddAccessRule(new AccessRule<MemoryMappedFileRights>(currentIdentity.Name, MemoryMappedFileRights.FullControl, AccessControlType.Allow));
                    transparent.AddAccessRule(new AccessRule<MemoryMappedFileRights>(service, MemoryMappedFileRights.ReadWrite, AccessControlType.Allow));
                }

                _memoryMappedFile = MemoryMappedFile.CreateNew(
                    MakeName(@"\OpenCover_Profiler_Communication_MemoryMapFile_", bufferId),
                    bufferSize,
                    MemoryMappedFileAccess.ReadWrite,
                    MemoryMappedFileOptions.None,
                    transparent,
                    HandleInheritability.Inheritable);

                StreamAccessorComms = _memoryMappedFile.CreateViewStream(0, bufferSize, MemoryMappedFileAccess.ReadWrite);

                bool createdNew;

                ProfilerRequestsInformation = new EventWaitHandle(
                    false,
                    EventResetMode.ManualReset,
                    MakeName(@"\OpenCover_Profiler_Communication_SendData_Event_", bufferId),
                    out createdNew,
                    open);

                InformationReadyForProfiler = new EventWaitHandle(
                    false,
                    EventResetMode.ManualReset,
                    MakeName(@"\OpenCover_Profiler_Communication_ReceiveData_Event_", bufferId),
                    out createdNew,
                    open);

                InformationReadByProfiler = new EventWaitHandle(
                    false,
                    EventResetMode.ManualReset,
                    MakeName(@"\OpenCover_Profiler_Communication_ChunkData_Event_", bufferId),
                    out createdNew,
                    open);

                DataCommunication = new byte[bufferSize];
                PinnedDataCommunication = GCHandle.Alloc(DataCommunication, GCHandleType.Pinned);
            }
예제 #41
0
        public void MainRun()
        {
            try
            {
                bool createdNew;
                SyncNamed = new Mutex(false, MutexName,out createdNew);
                if (!createdNew)
                {
                    LogHelper.WriteLog("创建同步对象意外失败,服务准备停止。");
                    this.OnStop();
                }

                var everyone = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
                var memoryMapSecurity = new MemoryMappedFileSecurity();
                memoryMapSecurity.AddAccessRule(new AccessRule<MemoryMappedFileRights>(everyone, MemoryMappedFileRights.ReadWrite, AccessControlType.Allow));
                LogHelper.WriteLog("设置内存权限....");
                LogHelper.WriteLog("创建comMMF内存...");
                MemoryMappedFile comMMF = MemoryMappedFile.CreateOrOpen("Global\\funcMMF", capacity, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, memoryMapSecurity, System.IO.HandleInheritability.None);      
                LogHelper.WriteLog("创建comOrderMMF内存....");

                MemoryMappedFile comOrderMMF = MemoryMappedFile.CreateOrOpen("Global\\funcOrderMMF", capacity, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, memoryMapSecurity, System.IO.HandleInheritability.None);                
                //通过MemoryMappedFile的CreateViewAccssor方法获得共享内存的访问器
                MemoryMappedViewAccessor comMMFViewAccessor;
                //循环写入,使在这个进程中可以向共享内存中写入不同的字符串值
                MemoryMappedViewAccessor comOrderMMFViewAccessor;
                comMMFViewAccessor = comMMF.CreateViewAccessor(0, capacity);
                comOrderMMFViewAccessor = comOrderMMF.CreateViewAccessor(0, capacity);
                string input;
                int strLength;
                char[] charsInMMf;
                //----------------------------------------------------------------
                input = XmlSerialize.SerializeXML<ComOrder>(a_comOrder);
                //向共享内存开始位置写入字符串的长度
                comOrderMMFViewAccessor.Write(0, input.Length);
                //向共享内存4位置写入字符
                comOrderMMFViewAccessor.WriteArray<char>(4, input.ToArray(), 0, input.Length);
                //----------------------------------------------------------------
                while (stopFlag=="Run")
                {
                    try
                    {      
                        SyncNamed.WaitOne();

                        input = XmlSerialize.SerializeXML<List<CustomFunc>>(CustomFunc);
                        //向共享内存开始位置写入字符串的长度
                        comMMFViewAccessor.Write(0, input.Length);
                        //向共享内存4位置写入字符
                        comMMFViewAccessor.WriteArray<char>(4, input.ToArray(), 0, input.Length);

                        //------------------------------释放同步对象
                        SyncNamed.ReleaseMutex();
                        //------------------------------

                        //-------------------------------------------------------------------------------
                        strLength = comOrderMMFViewAccessor.ReadInt32(0);
                        charsInMMf = new char[strLength];
                        //读取字符
                        comOrderMMFViewAccessor.ReadArray<char>(4, charsInMMf, 0, strLength);
                        a_comOrder = XmlSerialize.DeserializeXML<ComOrder>(new string(charsInMMf));
                        if (a_comOrder != null)
                        {
                            if (a_comOrder.order != a_comOrder2.order || a_comOrder.customFuncNum != a_comOrder2.customFuncNum)
                            {
                                a_comOrder2.order = a_comOrder.order;
                                a_comOrder2.customFuncNum = a_comOrder.customFuncNum;
                                LogHelper.WriteLog("执行命令...串口设备" + a_comOrder.customFuncNum.ToString() + "-" + a_comOrder.order);
                                if (a_comOrder.customFuncNum == 1000)
                                {
                                    if (a_comOrder.order == "Start")
                                    {
                                        foreach (CustomFunc m_CustomFunc in CustomFunc)
                                        {
                                            ParameterizedThreadStart ParStart = new ParameterizedThreadStart(m_CustomFunc.VoidRunOrder);
                                            Thread tempThread = new Thread(ParStart);
                                            tempThread.IsBackground = true;
                                            tempThread.Start((object)"Start");
                                        }
                                    }
                                    else if (a_comOrder.order == "Stop")
                                    {
                                        foreach (CustomFunc m_CustomFunc in CustomFunc)
                                        {
                                            ParameterizedThreadStart ParStart = new ParameterizedThreadStart(m_CustomFunc.VoidRunOrder);
                                            Thread tempThread = new Thread(ParStart);
                                            tempThread.IsBackground = true;
                                            tempThread.Start((object)"Stop");
                                        }
                                    }
                                    else if (a_comOrder.order == "ForceStop")
                                    {
                                        foreach (CustomFunc m_CustomFunc in CustomFunc)
                                        {
                                            ParameterizedThreadStart ParStart = new ParameterizedThreadStart(m_CustomFunc.VoidRunOrder);
                                            Thread tempThread = new Thread(ParStart);
                                            tempThread.IsBackground = true;
                                            tempThread.Start((object)"ForceStop");
                                        }
                                    }
                                    else if (a_comOrder.order == "Restart")
                                    {
                                        foreach (CustomFunc m_CustomFunc in CustomFunc)
                                        {
                                            ParameterizedThreadStart ParStart = new ParameterizedThreadStart(m_CustomFunc.VoidRunOrder);
                                            Thread tempThread = new Thread(ParStart);
                                            tempThread.IsBackground = true;
                                            tempThread.Start((object)"Restart"); ;
                                        }
                                    }
                                    else if (a_comOrder.order == "ReadSetup")
                                    {
                                        int tempEndState = 0;
                                        foreach (CustomFunc m_CustomFunc in CustomFunc)
                                        {
                                            if (m_CustomFunc.a_funcInfo.a_stateValue.runState == "End")
                                            {
                                                tempEndState += 1;
                                            };
                                        }
                                        if (tempEndState == CustomFunc.Count)
                                        {
                                            LoadSetup(); ;
                                        }
                                        else
                                        {
                                            string tempLogString;
                                            tempLogString = "检测到还有串口未停止,读取配置中止";
                                            LogHelper.WriteLog(tempLogString);
                                        }
                                    }
                                    else
                                    {
                                    }
                                }
                                else
                                {
                                    if (a_comOrder.customFuncNum <= CustomFunc.Count - 1)
                                    {
                                        if (a_comOrder.order == "Start")
                                        {
                                            ParameterizedThreadStart ParStart = new ParameterizedThreadStart(CustomFunc[a_comOrder.customFuncNum].VoidRunOrder);
                                            Thread tempThread = new Thread(ParStart);
                                            tempThread.IsBackground = true;
                                            tempThread.Start((object)"Start");
                                        }
                                        else if (a_comOrder.order == "Stop")
                                        {
                                            ParameterizedThreadStart ParStart = new ParameterizedThreadStart(CustomFunc[a_comOrder.customFuncNum].VoidRunOrder);
                                            Thread tempThread = new Thread(ParStart);
                                            tempThread.IsBackground = true;
                                            tempThread.Start((object)"Stop");
                                        }
                                        else if (a_comOrder.order == "ForceStop")
                                        {
                                            ParameterizedThreadStart ParStart = new ParameterizedThreadStart(CustomFunc[a_comOrder.customFuncNum].VoidRunOrder);
                                            Thread tempThread = new Thread(ParStart);
                                            tempThread.IsBackground = true;
                                            tempThread.Start((object)"ForceStop");
                                        }
                                        else if (a_comOrder.order == "Restart")
                                        {
                                            ParameterizedThreadStart ParStart = new ParameterizedThreadStart(CustomFunc[a_comOrder.customFuncNum].VoidRunOrder);
                                            Thread tempThread = new Thread(ParStart);
                                            tempThread.IsBackground = true;
                                            tempThread.Start((object)"Restart");
                                        }
                                        else
                                        {
                                        }
                                    }
                                    else
                                    {
                                        string tempLogString;
                                        tempLogString = "指定设备" + a_comOrder.customFuncNum + "超出实际设备数量 " + CustomFunc.Count + ",指令中止。";
                                        LogHelper.WriteLog(tempLogString);
                                    }
                                }
                            }
                        }
                        else
                        {
                            LogHelper.WriteLog("读取内存中指令出错");
                        }
                    }
                    catch (WaitHandleCannotBeOpenedException)
                    {
                        LogHelper.WriteLog("打开同步对象意外失败");
                    }
                    finally
                    {
#if DEBUG
                    Debug.Write(a_comOrder.order);
#endif
                        Thread.Sleep(new TimeSpan(0, 0, 0, 0, 1000));
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex as Exception);
            }
        }
예제 #42
0
		public static MemoryMappedFile CreateOrOpen (string mapName, long capacity, MemoryMappedFileAccess access, MemoryMappedFileOptions options, MemoryMappedFileSecurity memoryMappedFileSecurity, HandleInheritability inheritability)
		{
			return CoreShmCreate (mapName, capacity, access, options, memoryMappedFileSecurity, inheritability, FileMode.OpenOrCreate);
		}
예제 #43
0
		public static MemoryMappedFile CreateOrOpen (string mapName, long capacity, MemoryMappedFileAccess access, MemoryMappedFileOptions options, MemoryMappedFileSecurity memoryMappedFileSecurity, HandleInheritability inheritability)
#endif
		{
			throw new NotImplementedException ();
		}
        private static SafeMemoryMappedFileHandle CreateOrOpenCore(SafeFileHandle fileHandle, String mapName, 
                                                                HandleInheritability inheritability, 
                                                                MemoryMappedFileSecurity memoryMappedFileSecurity,
                                                                MemoryMappedFileAccess access, MemoryMappedFileOptions options,
                                                                Int64 capacity) {

            Debug.Assert(access != MemoryMappedFileAccess.Write, "Callers requesting write access shouldn't try to create a mmf");

            SafeMemoryMappedFileHandle handle = null;
            Object pinningHandle;
            UnsafeNativeMethods.SECURITY_ATTRIBUTES secAttrs = GetSecAttrs(inheritability, memoryMappedFileSecurity, out pinningHandle);
            
            // split the long into two ints
            Int32 capacityLow = (Int32)(capacity & 0x00000000FFFFFFFFL);
            Int32 capacityHigh = (Int32)(capacity >> 32);

            try {

                int waitRetries = 14;   //((2^13)-1)*10ms == approximately 1.4mins
                int waitSleep = 0;

                // keep looping until we've exhausted retries or break as soon we we get valid handle
                while (waitRetries > 0) {

                    // try to create
                    handle = UnsafeNativeMethods.CreateFileMapping(fileHandle, secAttrs, 
                        GetPageAccess(access) | (int)options, capacityHigh, capacityLow, mapName);

                    Int32 createErrorCode = Marshal.GetLastWin32Error();
                    if (!handle.IsInvalid) {
                        break;
                    }
                    else {
                        if (createErrorCode != UnsafeNativeMethods.ERROR_ACCESS_DENIED) {
                            __Error.WinIOError(createErrorCode, String.Empty);
                        }

                        // the mapname exists but our ACL is preventing us from opening it with CreateFileMapping.  
                        // Let's try to open it with OpenFileMapping.
                        handle.SetHandleAsInvalid();
                    }

                    // try to open
                    handle = UnsafeNativeMethods.OpenFileMapping(GetFileMapAccess(access), (inheritability &
                            HandleInheritability.Inheritable) != 0, mapName);

                    Int32 openErrorCode = Marshal.GetLastWin32Error();

                    // valid handle
                    if (!handle.IsInvalid) {
                        break;
                    }
                    // didn't get valid handle; have to retry
                    else {

                        if (openErrorCode != UnsafeNativeMethods.ERROR_FILE_NOT_FOUND) {
                            __Error.WinIOError(openErrorCode, String.Empty);
                        }

                        // increase wait time
                        --waitRetries;
                        if (waitSleep == 0) {
                            waitSleep = 10;
                        }
                        else {
                            System.Threading.Thread.Sleep(waitSleep);
                            waitSleep *= 2;
                        }
                    }
                }

                // finished retrying but couldn't create or open
                if (handle == null || handle.IsInvalid) {
                    throw new InvalidOperationException(SR.GetString(SR.InvalidOperation_CantCreateFileMapping));
                }
            }

            finally {
                if (pinningHandle != null) {
                    GCHandle pinHandle = (GCHandle)pinningHandle;
                    pinHandle.Free();
                }
            }
            return handle;
        }
예제 #45
0
		static MemoryMappedFile CoreShmCreate (string mapName, long capacity, MemoryMappedFileAccess access,
							  MemoryMappedFileOptions options, MemoryMappedFileSecurity memoryMappedFileSecurity,
							  HandleInheritability inheritability, FileMode mode)
		{
			if (mapName != null && mapName.Length == 0)
				throw new ArgumentException ("mapName");
			if (capacity < 0)
				throw new ArgumentOutOfRangeException ("capacity");

			IntPtr handle = MemoryMapImpl.OpenFile (null, mode, mapName, out capacity, access, options);
			
			return new MemoryMappedFile () {
				handle = handle,
				fileAccess = access,
				name = mapName,
				fileCapacity = capacity
			};			
		}
    public static MemoryMappedFile CreateNew(string mapName, long capacity, MemoryMappedFileAccess access, MemoryMappedFileOptions options, MemoryMappedFileSecurity memoryMappedFileSecurity, HandleInheritability inheritability)
    {
      Contract.Ensures(Contract.Result<System.IO.MemoryMappedFiles.MemoryMappedFile>() != null);

      return default(MemoryMappedFile);
    }
    public static MemoryMappedFile CreateFromFile(FileStream fileStream, string mapName, long capacity, MemoryMappedFileAccess access, MemoryMappedFileSecurity memoryMappedFileSecurity, HandleInheritability inheritability, bool leaveOpen)
    {
      Contract.Ensures(Contract.Result<System.IO.MemoryMappedFiles.MemoryMappedFile>() != null);

      return default(MemoryMappedFile);
    }
 public void SetAccessControl(MemoryMappedFileSecurity memoryMappedFileSecurity)
 {
 }
예제 #49
0
		public static MemoryMappedFile CreateFromFile (FileStream fileStream, string mapName, long capacity, MemoryMappedFileAccess access,
							       MemoryMappedFileSecurity memoryMappedFileSecurity, HandleInheritability inheritability,
							       bool leaveOpen)
#endif
		{
			if (fileStream == null)
				throw new ArgumentNullException ("fileStream");
			if (mapName != null && mapName.Length == 0)
				throw new ArgumentException ("mapName");
			if ((!MonoUtil.IsUnix && capacity == 0 && fileStream.Length == 0) || (capacity > fileStream.Length))
				throw new ArgumentException ("capacity");

			MemoryMapImpl.ConfigureFD (fileStream.Handle, inheritability);
				
			return new MemoryMappedFile () {
				stream = fileStream,
				fileAccess = access,
				name = mapName,
				fileCapacity = capacity,
				keepOpen = leaveOpen
			};
		}
        private static SafeMemoryMappedFileHandle CreateCore(SafeFileHandle fileHandle, String mapName,
                                                    HandleInheritability inheritability,
                                                    MemoryMappedFileSecurity memoryMappedFileSecurity,
                                                    MemoryMappedFileAccess access, MemoryMappedFileOptions options,
                                                    Int64 capacity) {

            SafeMemoryMappedFileHandle handle = null;
            Object pinningHandle;
            UnsafeNativeMethods.SECURITY_ATTRIBUTES secAttrs = GetSecAttrs(inheritability, memoryMappedFileSecurity, out pinningHandle);
            
            // split the long into two ints
            Int32 capacityLow = (Int32)(capacity & 0x00000000FFFFFFFFL);
            Int32 capacityHigh = (Int32)(capacity >> 32);

            try {

                handle = UnsafeNativeMethods.CreateFileMapping(fileHandle, secAttrs, GetPageAccess(access) | (int)options,
                    capacityHigh, capacityLow, mapName);

                Int32 errorCode = Marshal.GetLastWin32Error();
                if (!handle.IsInvalid && errorCode == UnsafeNativeMethods.ERROR_ALREADY_EXISTS) {
                    handle.Dispose();
                    __Error.WinIOError(errorCode, String.Empty);
                }
                else if (handle.IsInvalid) {
                    __Error.WinIOError(errorCode, String.Empty);
                }
            }
            finally {
                if (pinningHandle != null) {
                    GCHandle pinHandle = (GCHandle)pinningHandle;
                    pinHandle.Free();
                }
            }
            return handle;
        }
예제 #51
0
		public static MemoryMappedFile CreateNew (string mapName, long capacity, MemoryMappedFileAccess access,
							  MemoryMappedFileOptions options, MemoryMappedFileSecurity memoryMappedFileSecurity,
							  HandleInheritability inheritability)
#endif
		{
			return CreateFromFile (mapName, FileMode.CreateNew, mapName, capacity, access);
		}
예제 #52
0
        unsafe 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);

                var security = new MemoryMappedFileSecurity();
                security.AddAccessRule(new System.Security.AccessControl.AccessRule<MemoryMappedFileRights>(
                    new System.Security.Principal.SecurityIdentifier(System.Security.Principal.WellKnownSidType.WorldSid, null),
                    MemoryMappedFileRights.FullControl,
                    System.Security.AccessControl.AccessControlType.Allow));

                //More access rules
                //http://stackoverflow.com/questions/18067581/cant-open-memory-mapped-file-from-log-on-screen

                //Writer_mmf = System.IO.MemoryMappedFiles.MemoryMappedFile.CreateOrOpen("Global\\" + sm.uniqueHandlerName + prefix + "_SharmNet_MMF", sm.bufferCapacity,  //If started as admin
                Writer_mmf = System.IO.MemoryMappedFiles.MemoryMappedFile.CreateOrOpen(sm.uniqueHandlerName + prefix + "_SharmNet_MMF", sm.bufferCapacity,
                    MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.DelayAllocatePages, security, System.IO.HandleInheritability.Inheritable);

                Writer_accessor = Writer_mmf.CreateViewAccessor(0, sm.bufferCapacity);
                Writer_accessor.SafeMemoryMappedViewHandle.AcquirePointer(ref Writer_accessor_ptr);
            }
        }
예제 #53
0
		public void SetAccessControl (MemoryMappedFileSecurity memoryMappedFileSecurity)
		{
			throw new NotImplementedException ();
		}
예제 #54
0
        /// <summary>
        /// 
        /// </summary>
        unsafe 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);

                var security = new MemoryMappedFileSecurity();
                security.AddAccessRule(new System.Security.AccessControl.AccessRule<MemoryMappedFileRights>(
                    new System.Security.Principal.SecurityIdentifier(System.Security.Principal.WellKnownSidType.WorldSid, null),
                    MemoryMappedFileRights.FullControl,
                    System.Security.AccessControl.AccessControlType.Allow));
                //Reader_mmf = System.IO.MemoryMappedFiles.MemoryMappedFile.CreateOrOpen(@"Global\MapName1", sm.bufferCapacity,
                Reader_mmf = System.IO.MemoryMappedFiles.MemoryMappedFile.CreateOrOpen(sm.uniqueHandlerName + prefix + "_SharmNet_MMF", sm.bufferCapacity,
                    MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.DelayAllocatePages, security, System.IO.HandleInheritability.Inheritable);

                Reader_accessor = Reader_mmf.CreateViewAccessor(0, sm.bufferCapacity);
                Reader_accessor.SafeMemoryMappedViewHandle.AcquirePointer(ref Reader_accessor_ptr);
            }

            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(Reader_accessor_ptr, 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

                                this.sm.SharmIPC.InternalDataArrived(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:
                                            this.sm.SharmIPC.InternalDataArrived(eMsgType.ErrorInRpc, iResponseMsgId, null);
                                            break;
                                    }
                                    break;
                                }

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

                                        byte[] tmp = new byte[chunksCollected.Length + iPayLoadLen];
                                        Buffer.BlockCopy(chunksCollected, 0, tmp, 0, chunksCollected.Length);
                                        Buffer.BlockCopy(ReadBytes(Reader_accessor_ptr, 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(System.Exception ex)
                {
                    /*
                    System.ObjectDisposedException: Das SafeHandle wurde geschlossen. bei System.Runtime.InteropServices.SafeHandle.DangerousAddRef(Boolean& success)
                    bei System.StubHelpers.StubHelpers.SafeHandleAddRef(SafeHandle pHandle, Boolean& success)
                    bei Microsoft.Win32.Win32Native.SetEvent(SafeWaitHandle handle) bei System.Threading.EventWaitHandle.Set() bei tiesky.com.SharmIpcInternals.ReaderWriterHandler.b__28_0()
                    */
                    this.sm.SharmIPC.LogException("SharmIps.ReaderWriterHandler.InitReader LE", ex);
                }

            });
        }
예제 #55
0
            internal ManagedMemoryBlock(string @namespace, string key, int bufferSize, int bufferId, IEnumerable<string> servicePrincpal)
            {
                Namespace = @namespace;
                Key = key;

                EventWaitHandleSecurity open = null;
                MemoryMappedFileSecurity transparent = null;

                var service = servicePrincpal.FirstOrDefault();
                var currentIdentity = WindowsIdentity.GetCurrent();
                if (service != null && currentIdentity != null)
                {
                    open = new EventWaitHandleSecurity();
                    open.AddAccessRule(new EventWaitHandleAccessRule(currentIdentity.Name, EventWaitHandleRights.FullControl, AccessControlType.Allow));

                    // The event handles need more than just EventWaitHandleRights.Modify | EventWaitHandleRights.Synchronize to work
                    open.AddAccessRule(new EventWaitHandleAccessRule(service, EventWaitHandleRights.FullControl, AccessControlType.Allow));

                    transparent = new MemoryMappedFileSecurity();
                    transparent.AddAccessRule(new AccessRule<MemoryMappedFileRights>(currentIdentity.Name, MemoryMappedFileRights.FullControl, AccessControlType.Allow));
                    transparent.AddAccessRule(new AccessRule<MemoryMappedFileRights>(service, MemoryMappedFileRights.ReadWrite, AccessControlType.Allow));
                }

                bool createdNew;

                ProfilerHasResults = new EventWaitHandle(
                    false,
                    EventResetMode.ManualReset,
                    MakeName(@"\OpenCover_Profiler_Communication_SendResults_Event_", bufferId),
                    out createdNew,
                    open);

                ResultsHaveBeenReceived = new EventWaitHandle(
                    false,
                    EventResetMode.ManualReset,
                    MakeName(@"\OpenCover_Profiler_Communication_ReceiveResults_Event_", bufferId),
                    out createdNew,
                    open);

                _mmfResults = MemoryMappedFile.CreateNew(
                    MakeName(@"\OpenCover_Profiler_Results_MemoryMapFile_", bufferId),
                    bufferSize,
                    MemoryMappedFileAccess.ReadWrite,
                    MemoryMappedFileOptions.None,
                    transparent,
                    HandleInheritability.Inheritable);

                StreamAccessorResults = _mmfResults.CreateViewStream(0, bufferSize, MemoryMappedFileAccess.ReadWrite);
                StreamAccessorResults.Write(BitConverter.GetBytes(0), 0, 4);
                BufferSize = bufferSize;
            }
        public static MemoryMappedFile CreateOrOpen(String mapName, Int64 capacity,
                                                    MemoryMappedFileAccess access, MemoryMappedFileOptions options,
                                                    MemoryMappedFileSecurity memoryMappedFileSecurity, 
                                                    HandleInheritability inheritability) {

            if (mapName == null) {
                throw new ArgumentNullException("mapName", SR.GetString(SR.ArgumentNull_MapName));
            }

            if (mapName.Length == 0) {
                throw new ArgumentException(SR.GetString(SR.Argument_MapNameEmptyString));
            }

            if (capacity <= 0) {
                throw new ArgumentOutOfRangeException("capacity", SR.GetString(SR.ArgumentOutOfRange_NeedPositiveNumber));
            }

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

            if (access < MemoryMappedFileAccess.ReadWrite ||
                access > MemoryMappedFileAccess.ReadWriteExecute) {
                throw new ArgumentOutOfRangeException("access");
            }

            if (((int)options & ~((int)(MemoryMappedFileOptions.DelayAllocatePages))) != 0) {
                throw new ArgumentOutOfRangeException("options");
            }

            if (inheritability < HandleInheritability.None || inheritability > HandleInheritability.Inheritable) {
                throw new ArgumentOutOfRangeException("inheritability");
            }

            SafeMemoryMappedFileHandle handle;
            // special case for write access; create will never succeed
            if (access == MemoryMappedFileAccess.Write) {
                handle = OpenCore(mapName, inheritability, GetFileMapAccess(access), true);
            }
            else {
                handle = CreateOrOpenCore(new SafeFileHandle(new IntPtr(-1), true), mapName, inheritability,
                    memoryMappedFileSecurity, access, options, capacity);
            }

            return new MemoryMappedFile(handle);
        }
예제 #57
0
		public static MemoryMappedFile CreateFromFile (FileStream fileStream, string mapName, long capacity, MemoryMappedFileAccess access,
							       MemoryMappedFileSecurity memoryMappedFileSecurity, HandleInheritability inheritability,
							       bool leaveOpen)
		{
			if (fileStream == null)
				throw new ArgumentNullException ("fileStream");
			if (mapName != null && mapName.Length == 0)
				throw new ArgumentException ("mapName");
			if ((!MonoUtil.IsUnix && capacity == 0 && fileStream.Length == 0) || (capacity > fileStream.Length))
				throw new ArgumentException ("capacity");

			IntPtr handle = MemoryMapImpl.OpenHandle (fileStream.SafeFileHandle.DangerousGetHandle (), mapName, out capacity, access, MemoryMappedFileOptions.DelayAllocatePages);
			
			MemoryMapImpl.ConfigureHandleInheritability (handle, inheritability);
				
			return new MemoryMappedFile () {
				handle = handle,
				// fileAccess = access,
				// name = mapName,
				// fileCapacity = capacity,

				stream = fileStream,
				keepOpen = leaveOpen
			};
		}
        public static MemoryMappedFile CreateNew(String mapName, Int64 capacity, MemoryMappedFileAccess access,
                                                    MemoryMappedFileOptions options, MemoryMappedFileSecurity memoryMappedFileSecurity,
                                                    HandleInheritability inheritability) {

            if (mapName != null && mapName.Length == 0) {
                throw new ArgumentException(SR.GetString(SR.Argument_MapNameEmptyString));
            }

            if (capacity <= 0) {
                throw new ArgumentOutOfRangeException("capacity", SR.GetString(SR.ArgumentOutOfRange_NeedPositiveNumber));
            }

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

            if (access < MemoryMappedFileAccess.ReadWrite ||
                access > MemoryMappedFileAccess.ReadWriteExecute) {
                throw new ArgumentOutOfRangeException("access");
            }

            if (access == MemoryMappedFileAccess.Write) {
                throw new ArgumentException(SR.GetString(SR.Argument_NewMMFWriteAccessNotAllowed), "access");
            }

            if (((int)options & ~((int)(MemoryMappedFileOptions.DelayAllocatePages ))) != 0) {
                throw new ArgumentOutOfRangeException("options");
            }

            if (inheritability < HandleInheritability.None || inheritability > HandleInheritability.Inheritable) {
                throw new ArgumentOutOfRangeException("inheritability");
            }

            SafeMemoryMappedFileHandle handle = CreateCore(new SafeFileHandle(new IntPtr(-1), true), mapName, inheritability, 
                memoryMappedFileSecurity, access, options, capacity);

            return new MemoryMappedFile(handle);
        }
        public static MemoryMappedFile CreateFromFile(FileStream fileStream, String mapName, Int64 capacity,
                                                        MemoryMappedFileAccess access, MemoryMappedFileSecurity memoryMappedFileSecurity, 
                                                        HandleInheritability inheritability, bool leaveOpen) {

            if (fileStream == null) {
                throw new ArgumentNullException("fileStream", SR.GetString(SR.ArgumentNull_FileStream));
            }

            if (mapName != null && mapName.Length == 0) {
                throw new ArgumentException(SR.GetString(SR.Argument_MapNameEmptyString));
            }

            if (capacity < 0) {
                throw new ArgumentOutOfRangeException("capacity", SR.GetString(SR.ArgumentOutOfRange_PositiveOrDefaultCapacityRequired));
            }

            if (capacity == 0 && fileStream.Length == 0) {
                throw new ArgumentException(SR.GetString(SR.Argument_EmptyFile));
            }

            if (access < MemoryMappedFileAccess.ReadWrite ||
                access > MemoryMappedFileAccess.ReadWriteExecute) {
                throw new ArgumentOutOfRangeException("access");
            }

            if (access == MemoryMappedFileAccess.Write) {
                throw new ArgumentException(SR.GetString(SR.Argument_NewMMFWriteAccessNotAllowed), "access");
            }

            if (access == MemoryMappedFileAccess.Read && capacity > fileStream.Length) {
                throw new ArgumentException(SR.GetString(SR.Argument_ReadAccessWithLargeCapacity));
            }

            if (inheritability < HandleInheritability.None || inheritability > HandleInheritability.Inheritable) {
                throw new ArgumentOutOfRangeException("inheritability");
            }

            // flush any bytes written to the FileStream buffer so that we can see them in our MemoryMappedFile
            fileStream.Flush();

            if (capacity == DefaultSize) {
                capacity = fileStream.Length;
            }

            // one can always create a small view if they do not want to map an entire file 
            if (fileStream.Length > capacity) {
                throw new ArgumentOutOfRangeException("capacity", SR.GetString(SR.ArgumentOutOfRange_CapacityGEFileSizeRequired));
            }

            SafeMemoryMappedFileHandle handle = CreateCore(fileStream.SafeFileHandle, mapName, inheritability, memoryMappedFileSecurity, 
                access, MemoryMappedFileOptions.None, capacity);

            return new MemoryMappedFile(handle, fileStream, leaveOpen);
        }
        public void SetAccessControl(MemoryMappedFileSecurity memoryMappedFileSecurity) {

            if (memoryMappedFileSecurity == null) {
                throw new ArgumentNullException("memoryMappedFileSecurity");
            }

            if (_handle.IsClosed) {
                __Error.FileNotOpen();
            }

            memoryMappedFileSecurity.PersistHandle(_handle);
        }