/// <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; } }
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); }
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); }
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(); } }
/// <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; } }
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; }
}//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); }
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); }
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; //} }
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); } }
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)); }
private static void SetupMemoryMappedFileSecurity(MemoryMappedFileSecurity customSecurity) { if (customSecurity != null) { return; } customSecurity = new MemoryMappedFileSecurity(); customSecurity.AddAccessRule(new AccessRule <MemoryMappedFileRights>("everyone", MemoryMappedFileRights.FullControl, AccessControlType.Allow)); }
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); } } } }
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(); }
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); }
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; }
public static MemoryMappedFileSecurity GetMemoryMappedFileSecurity() { MemoryMappedFileSecurity result = new MemoryMappedFileSecurity(); result.AddAccessRule(new AccessRule <MemoryMappedFileRights>( new SecurityIdentifier(WellKnownSidType.WorldSid, null), MemoryMappedFileRights.FullControl, AccessControlType.Allow ) ); return(result); }
//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(); }
/// <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); }
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 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> /// 初始化 /// </summary> /// <exception cref="DebugerExistsException"></exception> /// <exception cref="Exception"></exception> private void Init() { if (this.inited == true) { return; } var bufferReadyName = "DBWIN_BUFFER_READY"; var dataReadyName = "DBWIN_DATA_READY"; var bufferName = "DBWIN_BUFFER"; if (global == true) { var globalPrefix = "Global\\"; bufferReadyName = globalPrefix + bufferReadyName; dataReadyName = globalPrefix + dataReadyName; bufferName = globalPrefix + bufferName; } var createdNew = false; var everyone = new SecurityIdentifier(WellKnownSidType.WorldSid, null); var eventSecurity = new EventWaitHandleSecurity(); eventSecurity.AddAccessRule(new EventWaitHandleAccessRule(everyone, EventWaitHandleRights.Modify | EventWaitHandleRights.Synchronize, AccessControlType.Allow)); this.bufferReadyHandle = new EventWaitHandle(false, EventResetMode.AutoReset, bufferReadyName, out createdNew, eventSecurity); if (createdNew == false) { throw new DebugerExistsException(); } this.dataReadyHandle = new EventWaitHandle(false, EventResetMode.AutoReset, dataReadyName, out createdNew, eventSecurity); if (createdNew == false) { throw new DebugerExistsException(); } var memoryMapSecurity = new MemoryMappedFileSecurity(); memoryMapSecurity.AddAccessRule(new AccessRule <MemoryMappedFileRights>(everyone, MemoryMappedFileRights.ReadWrite, AccessControlType.Allow)); this.mappedFile = MemoryMappedFile.CreateOrOpen(bufferName, BUFFER_SIZE, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, memoryMapSecurity, HandleInheritability.None); this.inited = true; }
public static void Write(string value, string mapName, long capacity, string mutexName, out MemoryMappedFile memoryMappedFile) { var securityIdentifier = new SecurityIdentifier(WellKnownSidType.WorldSid, null); var security = new MemoryMappedFileSecurity(); security.AddAccessRule(new AccessRule <MemoryMappedFileRights>(securityIdentifier, MemoryMappedFileRights.FullControl, AccessControlType.Allow)); memoryMappedFile = MemoryMappedFile.CreateNew(mapName, capacity, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, security, HandleInheritability.Inheritable); bool mutexCreated; var mutex = new Mutex(true, mutexName, out mutexCreated); using (MemoryMappedViewStream stream = memoryMappedFile.CreateViewStream()) { var writer = new BinaryWriter(stream); writer.Write(value); } mutex.ReleaseMutex(); // HARD-CODED constant Tracer.Instance.TraceEvent(System.Diagnostics.TraceEventType.Verbose, 0, $"Memory-mapped file set to {mapName} as {value}"); }
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; } }
public void ConnectByPid(Int32 pid) { var securityMemory = new MemoryMappedFileSecurity(); var securityMutex = new MutexSecurity(); var securitySemaphore = new SemaphoreSecurity(); var securityWaiter = new SemaphoreSecurity(); securityMemory.AddAccessRule(new AccessRule <MemoryMappedFileRights>(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MemoryMappedFileRights.FullControl, AccessControlType.Allow)); securityMutex.AddAccessRule(new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow)); securitySemaphore.AddAccessRule(new SemaphoreAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), SemaphoreRights.FullControl, AccessControlType.Allow)); securityWaiter.AddAccessRule(new SemaphoreAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), SemaphoreRights.FullControl, AccessControlType.Allow)); this.ipcMemory = MemoryMappedFile.CreateNew($"Global\\dr_analyzer_buffer_{pid}", 76012); this.ipcMemory.SetAccessControl(securityMemory); this.ipcMutex = new Mutex(false, $"Global\\dr_analyzer_mutex_{pid}", out bool createdMutex, securityMutex); this.ipcSentSemaphore = new Semaphore(0, 1, $"Global\\dr_analyzer_sent_semaphore_{pid}", out bool createdSentSemaphore, securitySemaphore); this.ipcReceivedSemaphore = new Semaphore(0, 1, $"Global\\dr_analyzer_received_semaphore_{pid}", out bool createdReceivedSemaphore, securitySemaphore); this.ipcWaiterSemaphore = new Semaphore(0, 1, $"Global\\dr_analyzer_waiter_semaphore_{pid}", out bool createdWaiter, securityWaiter); if (!(createdMutex && createdSentSemaphore && createdReceivedSemaphore && createdWaiter)) { this.FreeSharedObjects(); throw new Exception("One of sync object is already created"); } this.queueSem = new Semaphore(0, 1); this.queueMutex = new Mutex(false); this.isExit = false; this.receiverThread = new Thread(this.ReceiverThreadFunc); this.queueThread = new Thread(this.QueueThreadFunc); this.queueThread.Start(); this.receiverThread.Start(); Injector.InjectByPid(pid); this.Active = true; }
private void CreateMMF(long capacity) { var security = new MemoryMappedFileSecurity(); security.AddAccessRule(new AccessRule <MemoryMappedFileRights>( new SecurityIdentifier( WellKnownSidType.WorldSid, null), MemoryMappedFileRights.FullControl, AccessControlType.Allow)); try { MMF = MemoryMappedFile.OpenExisting(AppId, MemoryMappedFileRights.FullControl, HandleInheritability.Inheritable); MMF.SetAccessControl(security); IsRunning = true; } catch (FileNotFoundException) { MMF = MemoryMappedFile.CreateNew(AppId, capacity, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, security, HandleInheritability.Inheritable); using (var accessor = MMF.CreateViewAccessor()) accessor.Write(0, 0); IsRunning = false; } }
public void Open(string mmfName, int mmfSize) { if (_map.ContainsKey(mmfName)) { return; } MemoryMappedFile mp; byte[] mmfBuf = new byte[mmfSize]; lock (lockobj) { mp = MemoryMappedFile.CreateNew(mmfName, mmfSize); MemoryMappedFileSecurity permission = mp.GetAccessControl(); permission.AddAccessRule( new AccessRule <MemoryMappedFileRights>("Everyone", MemoryMappedFileRights.FullControl, AccessControlType.Allow)); mp.SetAccessControl(permission); } _map.Add(mmfName, new Tuple <MemoryMappedFile, byte[]>(mp, mmfBuf)); return; }
private MessageRepositoryService() { _mutex = new Mutex(false, "MessengerMutex"); MemoryMappedFileSecurity CustomSecurity = new MemoryMappedFileSecurity(); CustomSecurity.AddAccessRule(new System.Security.AccessControl.AccessRule <MemoryMappedFileRights>("everyone", MemoryMappedFileRights.FullControl, System.Security.AccessControl.AccessControlType.Allow)); _pagedMemoryMappedMessages = MemoryMappedFile.CreateOrOpen( @"Messages", // Name 1024 * 1024, // Size MemoryMappedFileAccess.ReadWrite, // Access type MemoryMappedFileOptions.DelayAllocatePages, // Pseudo reserve/commit CustomSecurity, // You can customize the security HandleInheritability.Inheritable); // Inherit to child process _pagedMemoryMappedMessagesSize = MemoryMappedFile.CreateOrOpen( @"MessagesSize", // Name 32, // Size MemoryMappedFileAccess.ReadWrite, // Access type MemoryMappedFileOptions.DelayAllocatePages, // Pseudo reserve/commit CustomSecurity, // You can customize the security HandleInheritability.Inheritable); // Inherit to child process }
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(); } } }
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); } }
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; }
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); }
public static void write_file_MMF <T>(T[] data, string path_folder, string file_name) { if (!path_folder.Contains(':')) { path_folder = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + @"\" + path_folder; } if (!Directory.Exists(path_folder)) { Directory.CreateDirectory(path_folder); } MemoryMappedFileSecurity mSec = new MemoryMappedFileSecurity(); mSec.AddAccessRule(new AccessRule <MemoryMappedFileRights>(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MemoryMappedFileRights.FullControl, AccessControlType.Allow)); string file = path_folder + @"\" + file_name + ".mmf"; file = file.Replace("\\\\", "\\"); Task.Factory.StartNew((object obj) => { Tuple <string, T[]> rs = (obj as Tuple <string, T[]>); string v_file = rs.Item1; T[] v_data = rs.Item2; int buffer_size = 0; try { using (MemoryStream stream = new MemoryStream()) { BinaryFormatter bf = new BinaryFormatter(); bf.Serialize(stream, v_data); byte[] bw = stream.ToArray(); buffer_size = bw.Length; long file_size = 0; if (File.Exists(v_file)) { FileInfo fi = new FileInfo(v_file); file_size = fi.Length; } long capacity = buffer_size; if (capacity < file_size) { capacity = file_size; } using (MemoryMappedFile w = MemoryMappedFile.CreateFromFile(v_file, FileMode.OpenOrCreate, null, capacity)) { using (MemoryMappedViewAccessor mmfWriter = w.CreateViewAccessor(0, capacity)) { mmfWriter.WriteArray <byte>(0, bw, 0, buffer_size); } } } } catch (Exception ex) { string msg = ex.Message; } }, new Tuple <string, T[]>(file, data)); }//end function
/// <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); } }); }
public static void write_MMF <T>(T item, string path_folder, string file_name) where T : struct { if (!path_folder.Contains(':')) { path_folder = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + @"\" + path_folder; } if (!Directory.Exists(path_folder)) { Directory.CreateDirectory(path_folder); } MemoryMappedFileSecurity mSec = new MemoryMappedFileSecurity(); mSec.AddAccessRule(new AccessRule <MemoryMappedFileRights>(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MemoryMappedFileRights.FullControl, AccessControlType.Allow)); string filePath = path_folder + @"\" + file_name + ".mmf"; filePath = filePath.Replace("\\\\", "\\"); int buffer_size = 0; try { using (MemoryStream stream = new MemoryStream()) { int objsize = Marshal.SizeOf(typeof(T)); byte[] bw = new byte[objsize]; IntPtr buff = Marshal.AllocHGlobal(objsize); Marshal.StructureToPtr(item, buff, true); Marshal.Copy(buff, bw, 0, objsize); Marshal.FreeHGlobal(buff); buffer_size = bw.Length; long file_size = 0; if (File.Exists(filePath)) { FileInfo fi = new FileInfo(filePath); file_size = fi.Length; } long capacity = buffer_size; if (capacity < file_size) { capacity = file_size; } using (MemoryMappedFile w = MemoryMappedFile.CreateFromFile(filePath, FileMode.OpenOrCreate, null, capacity)) { using (MemoryMappedViewAccessor mmfWriter = w.CreateViewAccessor(0, capacity)) { mmfWriter.WriteArray <byte>(0, bw, 0, buffer_size); } } } } catch (Exception ex) { string msg = ex.Message; } }//end function
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); } }
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; }
public MainViewModel() { Logging.SetupLogging(); PortAudio.Pa_Initialize(); var realtimeProcesingExePath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "IrWorkshop.RealtimeProcessing.exe"); realtimeProcess = new RealtimeProcessManager(realtimeProcesingExePath); realtimeProcess.PrematureTerminationCallback = logOutput => ExceptionDialog.ShowDialog("Audio engine has died", string.Join("\r\n", logOutput)); //ensure copy dependency // ReSharper disable once UnusedVariable var ttt = typeof(RealtimeProcessing.Program); var mSec = new MemoryMappedFileSecurity(); mSec.AddAccessRule(new AccessRule <MemoryMappedFileRights>(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MemoryMappedFileRights.FullControl, AccessControlType.Allow)); try { memoryMap = MemoryMappedFile.CreateNew("Global\\IRWorkshopMap", 65536, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.None, mSec, HandleInheritability.Inheritable); mmAccessor = memoryMap.CreateViewAccessor(); } catch (IOException ex) { if (ex.Message.Contains("already exists")) { Logging.ShowMessage("IR Workshop Studio is already running", LogType.Information, true); Environment.Exit(0); } throw; } catch (Exception) { Logging.ShowMessage("This software needs to run in Administrator mode", LogType.Error, true); throw; } volumeSlider = 0.7; preset = new ImpulsePreset(); ImpulseConfig = new ObservableCollection <ImpulseConfigViewModel>(); MixingConfig = new MixingViewModel(preset.MixingConfig, preset.SamplerateTransformed) { OnUpdateCallback = () => updateRateLimiter.Pulse() }; Title = "IR Workshop - v" + Assembly.GetExecutingAssembly().GetName().Version; settingsFile = Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), "settings.json"); NewPresetCommand = new DelegateCommand(_ => NewPreset()); OpenPresetCommand = new DelegateCommand(_ => OpenPreset()); SavePresetCommand = new DelegateCommand(_ => SavePreset()); AudioSetupCommand = new DelegateCommand(_ => AudioSetup()); RestartAudioEngineCommand = new DelegateCommand(_ => RestartAudioEngine()); ExportWavCommand = new DelegateCommand(_ => ExportWav()); ShowAboutCommand = new DelegateCommand(_ => ShowAbout()); CheckForUpdatesCommand = new DelegateCommand(_ => Process.Start("https://github.com/ValdemarOrn/IRWorkshop")); AddImpulseCommand = new DelegateCommand(_ => AddImpulse()); RemoveImpulseCommand = new DelegateCommand(_ => RemoveImpulse()); MoveImpulseLeftCommand = new DelegateCommand(_ => MoveImpulseLeft()); MoveImpulseRightCommand = new DelegateCommand(_ => MoveImpulseRight()); CloneImpulseCommand = new DelegateCommand(_ => CloneImpulse()); SwitchGraphsCommand = new DelegateCommand(_ => SwitchGraphs()); selectedInputL = -1; selectedInputR = -1; selectedOutputL = -1; selectedOutputR = -1; updateRateLimiter = new LastRetainRateLimiter(100, Update); LoadSettings(); var t = new Thread(SaveSettingsLoop) { IsBackground = true }; t.Priority = ThreadPriority.Lowest; t.Start(); var t3 = new Thread(UpdateClipIndicators) { IsBackground = true }; t3.Priority = ThreadPriority.Lowest; t3.Start(); AddImpulse(); Update(); UpdateMemoryMap(); StartAudioEngine(); CheckPreviousRunException(); }