public void StreamAndRandomAccessReadWriteMemoryMappedProjectedFile() { string fileVirtualPath = this.Enlistment.GetVirtualPathTo("Test_EPF_WorkingDirectoryTests", "StreamAndRandomAccessReadWriteMemoryMappedProjectedFile.cs"); StringBuilder contentsBuilder = new StringBuilder(); // Length of the Byte-order-mark that will be at the start of the memory mapped file. // See https://msdn.microsoft.com/en-us/library/windows/desktop/dd374101(v=vs.85).aspx int bomOffset = 3; using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(fileVirtualPath)) { // The text length of StreamAndRandomAccessReadWriteMemoryMappedProjectedFile.cs was determined // outside of this test so that the test would not hydrate the file before we access via MemoryMappedFile int fileTextLength = 13762; int size = bomOffset + fileTextLength; int streamAccessWriteOffset = 64; int randomAccessWriteOffset = 128; string newStreamAccessContent = "**NEW_STREAM_CONTENT**"; string newRandomAccessConents = "&&NEW_RANDOM_CONTENT&&"; // Read (and modify) contents using stream accessor using (MemoryMappedViewStream streamAccessor = mmf.CreateViewStream(offset: 0, size: size)) { streamAccessor.CanRead.ShouldEqual(true); streamAccessor.CanWrite.ShouldEqual(true); for (int i = 0; i < size; ++i) { contentsBuilder.Append((char)streamAccessor.ReadByte()); } // Reset to the start of the stream (which will place the streamAccessor at offset in the memory file) streamAccessor.Seek(streamAccessWriteOffset, SeekOrigin.Begin); byte[] newContentBuffer = Encoding.ASCII.GetBytes(newStreamAccessContent); streamAccessor.Write(newContentBuffer, 0, newStreamAccessContent.Length); for (int i = 0; i < newStreamAccessContent.Length; ++i) { contentsBuilder[streamAccessWriteOffset + i] = newStreamAccessContent[i]; } } // Read (and modify) contents using random accessor using (MemoryMappedViewAccessor randomAccessor = mmf.CreateViewAccessor(offset: 0, size: size)) { randomAccessor.CanRead.ShouldEqual(true); randomAccessor.CanWrite.ShouldEqual(true); // Confirm the random accessor reads the same content that was read (and written) by the stream // accessor for (int i = 0; i < size; ++i) { ((char)randomAccessor.ReadByte(i)).ShouldEqual(contentsBuilder[i]); } // Write some new content for (int i = 0; i < newRandomAccessConents.Length; ++i) { // Convert to byte before writing rather than writing as char, because char version will write a 16-bit // unicode char randomAccessor.Write(i + randomAccessWriteOffset, Convert.ToByte(newRandomAccessConents[i])); ((char)randomAccessor.ReadByte(i + randomAccessWriteOffset)).ShouldEqual(newRandomAccessConents[i]); } for (int i = 0; i < newRandomAccessConents.Length; ++i) { contentsBuilder[randomAccessWriteOffset + i] = newRandomAccessConents[i]; } } // Verify the file one more time with a stream accessor using (MemoryMappedViewStream streamAccessor = mmf.CreateViewStream(offset: 0, size: size)) { for (int i = 0; i < size; ++i) { streamAccessor.ReadByte().ShouldEqual(contentsBuilder[i]); } } } // Remove the BOM before comparing with the contents of the file on disk contentsBuilder.Remove(0, bomOffset); // Confirm the new contents was written to the file fileVirtualPath.ShouldBeAFile(this.fileSystem).WithContents(contentsBuilder.ToString()); }
protected bool Open() { Close(); try { // Attempts to create or open the shared memory with a name of this.Name if (IsOwnerOfSharedMemory) { // Create a new shared memory mapping Mmf = MemoryMappedFile.CreateNew(Name, SharedMemorySize); // Create a view to the entire region of the shared memory View = Mmf.CreateViewAccessor(0, SharedMemorySize, MemoryMappedFileAccess.ReadWrite); View.SafeMemoryMappedViewHandle.AcquirePointer(ref ViewPtr); Header = (SharedHeader *)(ViewPtr + HeaderOffset); BufferStartPtr = ViewPtr + BufferOffset; // Initialise the header InitialiseHeader(); } else { // Open an existing shared memory mapping Mmf = MemoryMappedFile.OpenExisting(Name); // Retrieve the header from the shared memory in order to initialise the correct size using (var headerView = Mmf.CreateViewAccessor(0, HeaderOffset + Marshal.SizeOf(typeof(SharedHeader)), MemoryMappedFileAccess.Read)) { byte *headerPtr = null; headerView.SafeMemoryMappedViewHandle.AcquirePointer(ref headerPtr); var header = (SharedHeader *)(headerPtr + HeaderOffset); BufferSize = header->SharedMemorySize - Marshal.SizeOf(typeof(SharedHeader)); headerView.SafeMemoryMappedViewHandle.ReleasePointer(); } // Create a view to the entire region of the shared memory View = Mmf.CreateViewAccessor(0, SharedMemorySize, MemoryMappedFileAccess.ReadWrite); View.SafeMemoryMappedViewHandle.AcquirePointer(ref ViewPtr); Header = (SharedHeader *)(ViewPtr + HeaderOffset); BufferStartPtr = ViewPtr + HeaderOffset + Marshal.SizeOf(typeof(SharedHeader)); } } catch { Close(); throw; } // Complete any additional open logic try { if (!DoOpen()) { Close(); return(false); } else { return(true); } } catch { Close(); throw; } }
public MemoryMappedFileByteBuffer(MemoryMappedViewAccessor accessor, int mark, int pos, int lim, int cap) : base(mark, pos, lim, cap) { _accessor = accessor; }
public bool runTest() { _random = new Random(-55); _pageSize = SystemInfoHelpers.GetPageSize(); Type[] testedTypes = new Type[] { typeof(Boolean), typeof(Char), typeof(Byte), typeof(Int16), typeof(Int32), typeof(Int64), typeof(SByte), typeof(UInt16), typeof(UInt32), typeof(UInt64), typeof(Single), typeof(Double), typeof(Decimal) }; Type[] oneByteTypes = new Type[] { typeof(Boolean), typeof(Byte), typeof(SByte) }; Type[] twoByteTypes = new Type[] { typeof(Char), typeof(Int16), typeof(UInt16) }; Type[] fourByteTypes = new Type[] { typeof(Single), typeof(Int32), typeof(UInt32) }; Type[] eightByteTypes = new Type[] { typeof(Double), typeof(Int64), typeof(UInt64) }; Type[] sixteenByteTypes = new Type[] { typeof(Decimal) }; try { using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew(null, _pageSize * 10)) { // Default ViewAccessor size - whole MMF using (MemoryMappedViewAccessor view = mmf.CreateViewAccessor()) { // position = 0 VerifyWrite <Boolean>("Loc011a", view, 0, true); VerifyWrite <Byte>("Loc011b", view, 0, 234); VerifyWrite <SByte>("Loc11c", view, 0, 127); VerifyWrite <Char>("Loc011d", view, 0, (Char)23974); VerifyWrite <Int16>("Loc011e", view, 0, 12434); VerifyWrite <UInt16>("Loc011f", view, 0, 24512); VerifyWrite <Int32>("Loc011g", view, 0, 928734); VerifyWrite <UInt32>("Loc011h", view, 0, 210991212); VerifyWrite <Int64>("Loc011i", view, 0, -1029830128231); VerifyWrite <UInt64>("Loc011j", view, 0, 10293891274); VerifyWrite <Single>("Loc011k", view, 0, -0.12243098f); VerifyWrite <Double>("Loc011l", view, 0, 213.1209382093d); VerifyWrite <Decimal>("Loc011m", view, 0, 110293.1123m); // position > 0 VerifyWrite <Boolean>("Loc012a1", view, RandPos(), true); VerifyWrite <Boolean>("Loc012a2", view, RandPos(), false); VerifyWrite <Byte>("Loc012b1", view, RandPos(), 194); VerifyWrite <Byte>("Loc012b2", view, RandPos(), Byte.MinValue); VerifyWrite <Byte>("Loc012b3", view, RandPos(), Byte.MaxValue); VerifyWrite <SByte>("Loc012c1", view, RandPos(), -62); VerifyWrite <SByte>("Loc012c2", view, RandPos(), SByte.MinValue); VerifyWrite <SByte>("Loc012c3", view, RandPos(), SByte.MaxValue); VerifyWrite <Char>("Loc012d1", view, RandPos(), (Char)10690); VerifyWrite <Char>("Loc012d2", view, RandPos(), Char.MinValue); VerifyWrite <Char>("Loc012d3", view, RandPos(), Char.MaxValue); VerifyWrite <Int16>("Loc012e1", view, RandPos(), -1077); VerifyWrite <Int16>("Loc012e2", view, RandPos(), Int16.MinValue); VerifyWrite <Int16>("Loc012e3", view, RandPos(), Int16.MaxValue); VerifyWrite <UInt16>("Loc012f1", view, RandPos(), 20798); VerifyWrite <UInt16>("Loc012f2", view, RandPos(), UInt16.MinValue); VerifyWrite <UInt16>("Loc012f3", view, RandPos(), UInt16.MaxValue); VerifyWrite <Int32>("Loc012g1", view, RandPos(), 1212938472); VerifyWrite <Int32>("Loc012g2", view, RandPos(), Int32.MinValue); VerifyWrite <Int32>("Loc012g3", view, RandPos(), Int32.MaxValue); VerifyWrite <UInt32>("Loc012h1", view, RandPos(), 127983047); VerifyWrite <UInt32>("Loc012h2", view, RandPos(), UInt32.MinValue); VerifyWrite <UInt32>("Loc012h3", view, RandPos(), UInt32.MaxValue); VerifyWrite <Int64>("Loc012i1", view, RandPos(), -12039842392110123); VerifyWrite <Int64>("Loc012i2", view, RandPos(), Int64.MinValue); VerifyWrite <Int64>("Loc012i3", view, RandPos(), Int64.MaxValue); VerifyWrite <UInt64>("Loc012j1", view, RandPos(), 938059802); VerifyWrite <UInt64>("Loc012j2", view, RandPos(), UInt64.MinValue); VerifyWrite <UInt64>("Loc012j3", view, RandPos(), UInt64.MaxValue); VerifyWrite <Single>("Loc012k1", view, RandPos(), 0f); VerifyWrite <Single>("Loc012k2", view, RandPos(), Single.MinValue); VerifyWrite <Single>("Loc012k3", view, RandPos(), Single.MaxValue); VerifyWrite <Single>("Loc012k4", view, RandPos(), Single.NegativeInfinity); VerifyWrite <Single>("Loc012k5", view, RandPos(), Single.PositiveInfinity); VerifyWrite <Single>("Loc012k6", view, RandPos(), Single.NaN); VerifyWrite <Double>("Loc012l1", view, RandPos(), 0d); VerifyWrite <Double>("Loc012l2", view, RandPos(), Double.MinValue); VerifyWrite <Double>("Loc012l3", view, RandPos(), Double.MaxValue); VerifyWrite <Double>("Loc012l4", view, RandPos(), Double.NegativeInfinity); VerifyWrite <Double>("Loc012l5", view, RandPos(), Double.PositiveInfinity); VerifyWrite <Double>("Loc012l6", view, RandPos(), Double.NaN); VerifyWrite <Decimal>("Loc012m1", view, RandPos(), -1230912.12312m); VerifyWrite <Decimal>("Loc012m2", view, RandPos(), Decimal.MinValue); VerifyWrite <Decimal>("Loc012m3", view, RandPos(), Decimal.MaxValue); // position is last possible for type VerifyWrite <Boolean>("Loc014a", view, view.Capacity - 1, true); VerifyWrite <Byte>("Loc014b", view, view.Capacity - 1, 255); VerifyWrite <SByte>("Loc014c", view, view.Capacity - 1, -1); VerifyWrite <Char>("Loc014d", view, view.Capacity - 2, (Char)65280); VerifyWrite <Int16>("Loc014e", view, view.Capacity - 2, -256); VerifyWrite <UInt16>("Loc014f", view, view.Capacity - 2, 65280); VerifyWrite <Single>("Loc014k", view, view.Capacity - 4, -0.000001f); VerifyWrite <Int32>("Loc014g", view, view.Capacity - 4, 123); VerifyWrite <UInt32>("Loc014h", view, view.Capacity - 4, 19238); VerifyWrite <Double>("Loc014l", view, view.Capacity - 8, -0.00000001d); VerifyWrite <Int64>("Loc014i", view, view.Capacity - 8, 1029380); VerifyWrite <UInt64>("Loc014j", view, view.Capacity - 8, 9235); VerifyWrite <Decimal>("Loc014m", view, view.Capacity - 16, -65280m); // Exceptions foreach (Type type in testedTypes) { // position <0 VerifyWriteException("Loc031", type, view, -1, typeof(ArgumentOutOfRangeException)); // position >= view.Capacity VerifyWriteException("Loc032", type, view, view.Capacity, typeof(ArgumentOutOfRangeException)); VerifyWriteException("Loc033", type, view, view.Capacity + 1, typeof(ArgumentOutOfRangeException)); } // position+sizeof(type) >= view.Capacity foreach (Type type in twoByteTypes) { VerifyWriteException("Loc034", type, view, view.Capacity - 1, typeof(ArgumentException)); } foreach (Type type in fourByteTypes) { VerifyWriteException("Loc035", type, view, view.Capacity - 3, typeof(ArgumentException)); } foreach (Type type in eightByteTypes) { VerifyWriteException("Loc036", type, view, view.Capacity - 7, typeof(ArgumentException)); } foreach (Type type in sixteenByteTypes) { VerifyWriteException("Loc037", type, view, view.Capacity - 15, typeof(ArgumentException)); } // ViewAccessor starts at nonzero offset, spans remainder of MMF using (MemoryMappedViewAccessor view2 = mmf.CreateViewAccessor(1000, 0)) { // position = 0 VerifyWrite <Boolean>("Loc111a", view2, 0, true); VerifyWrite <Byte>("Loc111b", view2, 0, 1); VerifyWrite <SByte>("Loc111c", view2, 0, 1); VerifyWrite <Char>("Loc111d", view2, 0, (Char)1); VerifyWrite <Int16>("Loc111e", view2, 0, 1); VerifyWrite <UInt16>("Loc111f", view2, 0, 1); VerifyWrite <Int32>("Loc111g", view2, 0, 1); VerifyWrite <UInt32>("Loc111h", view2, 0, 1); VerifyWrite <Int64>("Loc111i", view2, 0, 1); VerifyWrite <UInt64>("Loc111j", view2, 0, 1); VerifyWrite <Single>("Loc111k", view2, 0, Single.Epsilon); VerifyWrite <Double>("Loc111l", view2, 0, Double.Epsilon); VerifyWrite <Decimal>("Loc111m", view2, 0, 1.00001m); // position = 0 of original view should be left untouched VerifyRead <Decimal>("Loc111y", view, 0, 110293.1123m); // Original view can read new values at offset 1000 VerifyRead <Decimal>("Loc111z", view, 1000, 1.00001m); // Exceptions foreach (Type type in testedTypes) { // position <0 VerifyWriteException("Loc131", type, view, -1, typeof(ArgumentOutOfRangeException)); // position >= view.Capacity VerifyWriteException("Loc132", type, view, view.Capacity, typeof(ArgumentOutOfRangeException)); VerifyWriteException("Loc133", type, view, view.Capacity + 1, typeof(ArgumentOutOfRangeException)); } // position+sizeof(type) >= view.Capacity foreach (Type type in twoByteTypes) { VerifyWriteException("Loc134", type, view, view.Capacity - 1, typeof(ArgumentException)); } foreach (Type type in fourByteTypes) { VerifyWriteException("Loc135", type, view, view.Capacity - 3, typeof(ArgumentException)); } foreach (Type type in eightByteTypes) { VerifyWriteException("Loc136", type, view, view.Capacity - 7, typeof(ArgumentException)); } foreach (Type type in sixteenByteTypes) { VerifyWriteException("Loc137", type, view, view.Capacity - 15, typeof(ArgumentException)); } } } // ViewAccessor starts at nonzero offset, with size shorter than MMF using (MemoryMappedViewAccessor view = mmf.CreateViewAccessor(2000, 10000)) { // position is last possible for type VerifyWrite <Boolean>("Loc214a", view, view.Capacity - 1, true); VerifyWrite <Byte>("Loc214b", view, view.Capacity - 1, (byte)251); VerifyWrite <SByte>("Loc214c", view, view.Capacity - 1, -42); VerifyWrite <Char>("Loc214d", view, view.Capacity - 2, (Char)2132); VerifyWrite <Int16>("Loc214e", view, view.Capacity - 2, -9187); VerifyWrite <UInt16>("Loc214f", view, view.Capacity - 2, 42354); VerifyWrite <Single>("Loc214k", view, view.Capacity - 4, 3409.12f); VerifyWrite <Int32>("Loc214g", view, view.Capacity - 4, 792351320); VerifyWrite <UInt32>("Loc214h", view, view.Capacity - 4, 2098312120); VerifyWrite <Double>("Loc214l", view, view.Capacity - 8, -0.12398721342d); VerifyWrite <Int64>("Loc214i", view, view.Capacity - 8, (long)98176239824); VerifyWrite <UInt64>("Loc214j", view, view.Capacity - 8, (ulong)1029831212091029); VerifyWrite <Decimal>("Loc214m", view, view.Capacity - 16, 0.216082743618029m); // Exceptions foreach (Type type in testedTypes) { // position <0 VerifyWriteException("Loc231", type, view, -1, typeof(ArgumentOutOfRangeException)); // position >= view.Capacity VerifyWriteException("Loc232", type, view, view.Capacity, typeof(ArgumentOutOfRangeException)); VerifyWriteException("Loc233", type, view, view.Capacity + 1, typeof(ArgumentOutOfRangeException)); } // position+sizeof(type) >= view.Capacity foreach (Type type in twoByteTypes) { VerifyWriteException("Loc234", type, view, view.Capacity - 1, typeof(ArgumentException)); } foreach (Type type in fourByteTypes) { VerifyWriteException("Loc235", type, view, view.Capacity - 3, typeof(ArgumentException)); } foreach (Type type in eightByteTypes) { VerifyWriteException("Loc236", type, view, view.Capacity - 7, typeof(ArgumentException)); } foreach (Type type in sixteenByteTypes) { VerifyWriteException("Loc237", type, view, view.Capacity - 15, typeof(ArgumentException)); } } // Accessor does not support reading using (MemoryMappedViewAccessor view = mmf.CreateViewAccessor(0, 0, MemoryMappedFileAccess.Read)) { foreach (Type t in testedTypes) { VerifyWriteException("Loc401_" + t.ToString(), t, view, 0, typeof(NotSupportedException)); } } // Call after view has been disposed MemoryMappedViewAccessor view1 = mmf.CreateViewAccessor(); view1.Dispose(); foreach (Type t in testedTypes) { VerifyWriteException("Loc501_" + t.ToString(), t, view1, 0, typeof(ObjectDisposedException)); } } /// END TEST CASES if (iCountErrors == 0) { return(true); } else { Console.WriteLine("Fail! iCountErrors==" + iCountErrors); return(false); } } catch (Exception ex) { Console.WriteLine("ERR999: Unexpected exception in runTest, {0}", ex); return(false); } }
private void CheckOptions(ArgumentParser parser) { if (parser.HasErrors) { runShutdown = false; exitApp = true; Current.Shutdown(1); } else if (parser.Driverinstall) { CreateBaseThread(); DS4Forms.WelcomeDialog dialog = new DS4Forms.WelcomeDialog(true); dialog.ShowDialog(); runShutdown = false; exitApp = true; Current.Shutdown(); } else if (parser.ReenableDevice) { DS4Windows.DS4Devices.reEnableDevice(parser.DeviceInstanceId); runShutdown = false; exitApp = true; Current.Shutdown(); } else if (parser.Runtask) { StartupMethods.LaunchOldTask(); runShutdown = false; exitApp = true; Current.Shutdown(); } else if (parser.Command) { IntPtr hWndDS4WindowsForm = IntPtr.Zero; hWndDS4WindowsForm = FindWindow(ReadIPCClassNameMMF(), "DS4Windows"); if (hWndDS4WindowsForm != IntPtr.Zero) { bool bDoSendMsg = true; bool bWaitResultData = false; bool bOwnsMutex = false; Mutex ipcSingleTaskMutex = null; EventWaitHandle ipcNotifyEvent = null; COPYDATASTRUCT cds; cds.lpData = IntPtr.Zero; try { if (parser.CommandArgs.ToLower().StartsWith("query.")) { // Query.device# (1..4) command returns a string result via memory mapped file. The cmd is sent to the background DS4Windows // process (via WM_COPYDATA wnd msg), then this client process waits for the availability of the result and prints it to console output pipe. // Use mutex obj to make sure that concurrent client calls won't try to write and read the same MMF result file at the same time. ipcSingleTaskMutex = new Mutex(false, "DS4Windows_IPCResultData_SingleTaskMtx"); try { bOwnsMutex = ipcSingleTaskMutex.WaitOne(10000); } catch (AbandonedMutexException) { bOwnsMutex = true; } if (bOwnsMutex) { // This process owns the inter-process sync mutex obj. Let's proceed with creating the output MMF file and waiting for a result. bWaitResultData = true; CreateIPCResultDataMMF(); ipcNotifyEvent = new EventWaitHandle(false, EventResetMode.AutoReset, "DS4Windows_IPCResultData_ReadyEvent"); } else { // If the mtx failed then something must be seriously wrong. Cannot do anything in that case because MMF file may be modified by concurrent processes. bDoSendMsg = false; } } if (bDoSendMsg) { cds.dwData = IntPtr.Zero; cds.cbData = parser.CommandArgs.Length; cds.lpData = Marshal.StringToHGlobalAnsi(parser.CommandArgs); SendMessage(hWndDS4WindowsForm, DS4Forms.MainWindow.WM_COPYDATA, IntPtr.Zero, ref cds); if (bWaitResultData) { Console.WriteLine(WaitAndReadIPCResultDataMMF(ipcNotifyEvent)); } } } finally { // Release the result MMF file in the client process before releasing the mtx and letting other client process to proceed with the same MMF file if (ipcResultDataMMA != null) { ipcResultDataMMA.Dispose(); } if (ipcResultDataMMF != null) { ipcResultDataMMF.Dispose(); } ipcResultDataMMA = null; ipcResultDataMMF = null; // If this was "Query.xxx" cmdline client call then release the inter-process mutex and let other concurrent clients to proceed (if there are anyone waiting for the MMF result file) if (bOwnsMutex && ipcSingleTaskMutex != null) { ipcSingleTaskMutex.ReleaseMutex(); } if (cds.lpData != IntPtr.Zero) { Marshal.FreeHGlobal(cds.lpData); } } } runShutdown = false; exitApp = true; Current.Shutdown(); } }
private EcmaModule AddModule(string filePath, string expectedSimpleName, byte[] moduleDataBytes, bool useForBinding) { MemoryMappedViewAccessor mappedViewAccessor = null; PdbSymbolReader pdbReader = null; try { PEReader peReader = OpenPEFile(filePath, moduleDataBytes, out mappedViewAccessor); pdbReader = OpenAssociatedSymbolFile(filePath, peReader); EcmaModule module = EcmaModule.Create(this, peReader, containingAssembly: null, pdbReader); MetadataReader metadataReader = module.MetadataReader; string simpleName = metadataReader.GetString(metadataReader.GetAssemblyDefinition().Name); ModuleData moduleData = new ModuleData() { SimpleName = simpleName, FilePath = filePath, Module = module, MappedViewAccessor = mappedViewAccessor }; lock (this) { if (useForBinding) { ModuleData actualModuleData; if (!_simpleNameHashtable.TryGetValue(moduleData.SimpleName, out actualModuleData)) { _simpleNameHashtable.Add(moduleData.SimpleName, moduleData); actualModuleData = moduleData; } if (actualModuleData != moduleData) { if (actualModuleData.FilePath != filePath) { throw new FileNotFoundException("Module with same simple name already exists " + filePath); } return(actualModuleData.Module); } } mappedViewAccessor = null; // Ownership has been transfered pdbReader = null; // Ownership has been transferred _moduleHashtable.AddOrGetExisting(moduleData); } return(module); } finally { if (mappedViewAccessor != null) { mappedViewAccessor.Dispose(); } if (pdbReader != null) { pdbReader.Dispose(); } } }
internal static FileAccess GetFileAccess(this MemoryMappedViewAccessor accessor) => (accessor.CanRead.ToInt32() + (accessor.CanWrite.ToInt32() << 1)) switch { 1 => FileAccess.Read,
/// <summary> /// Reads a 32-bit integer of a specific Endianness from the accessor and converts it to the current system Endianness. /// </summary> /// <param name="mem">The specified MemoryMappedViewAccessor.</param> /// <param name="position">The number of bytes into the accessor at which to begin reading.</param> /// <param name="convertFrom">The Endianness to convert from.</param> /// <returns>The value that was read as converted to the current system Endianness.</returns> public static int ReadInt32(this MemoryMappedViewAccessor mem, long position, Endianness convertFrom) { return(mem.ReadInt32(position).ConvertToSystemEndian(convertFrom)); }
// Use this for initialization void Start() { panelMenu = GameObject.Find("Canvas/PanelGiv/PanelLeft/PanelMenu"); panelMenu.SetActive(false); panelColor = GameObject.Find("Canvas/PanelGiv/PanelLeft/PanelColor"); panelColor.SetActive(false); panelArraw = GameObject.Find("Canvas/PanelGiv/PanelLeft/PanelArraw"); panelArraw.SetActive(false); timeNum = files.Length; menuItem1 = (GameObject)Instantiate(Resources.Load("Prefabs/Scripts/MenuItem1")); menuItem1.GetComponent <MenuItem1>().timeSum = timeNum; objects = GameObject.Find("Objects"); pre[0] = (GameObject)Instantiate(Resources.Load("Prefabs/Pres/PreContour"), objects.GetComponent <Transform>().position, objects.GetComponent <Transform>().rotation); string dir = Path.GetDirectoryName(files[0]); string[] BgPath = Directory.GetFiles(dir, "*.givb"); long sizeI = sizeof(int); long sizeV = Marshal.SizeOf(typeof(Vector3)); long sizeF = sizeof(float); float[] value_; if (BgPath.Length > 0) { BgPre = new GameObject[BgPath.Length][]; BgNum = new int[BgPath.Length]; Color[] cBg = new Color[] { new Color(0.5f, 0.5f, 0.5f, 0.5f), new Color(1, 0, 0, 0.5f), new Color(0, 1, 0, 0.5f) , new Color(0, 0, 1, 0.5f), new Color(1, 0.92f, 0.016f, 0.5f) }; Color cBgNow; for (int i = 0; i < BgPath.Length; ++i) { long jf = 0; cBgNow = cBg[i % 5]; using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(BgPath[i])) { using (MemoryMappedViewAccessor accessor = mmf.CreateViewAccessor()) { accessor.Read <int>(jf, out meshNum); jf += sizeI; BgPre[i] = new GameObject[meshNum]; BgNum[i] = meshNum; meshVNum = new int[meshNum]; meshTNum = new int[meshNum]; value_ = new float[meshNum]; for (int k = 0; k < meshNum; k++) { BgPre[i][k] = (GameObject)Instantiate(Resources.Load("Prefabs/Pres/PreTriangle"), objects.GetComponent <Transform>().position, objects.GetComponent <Transform>().rotation); BgPre[i][k].GetComponent <MeshRenderer>().materials[0].color = cBgNow; //BgPre[i][k].GetComponent<MeshRenderer>().materials[0].color = new Color(1, 1, 1, 0); } for (int j = 0; j < meshNum; j++) { accessor.Read <int>(jf, out meshVNum[j]); jf += sizeI; Vector3[] vertices = new Vector3[meshVNum[j]]; accessor.Read <int>(jf, out meshTNum[j]); jf += sizeI; int[] triangles = new int[meshTNum[j]]; accessor.ReadArray <Vector3>(jf, vertices, 0, meshVNum[j]); jf += sizeV * meshVNum[j]; accessor.ReadArray <int>(jf, triangles, 0, meshTNum[j]); jf += sizeI * meshTNum[j]; accessor.Read <float>(jf, out value_[j]); jf += sizeF; //创建预设体,赋予顶点和拓扑 BgPre[i][j].transform.parent = GetComponent <Transform>(); Mesh mesh = BgPre[i][j].GetComponent <MeshFilter>().mesh; mesh.Clear(); mesh.vertices = vertices; mesh.triangles = triangles; mesh.RecalculateNormals(); } } } } } }
internal ReadWriteMemoryMappedViewByteBuffer(MemoryMappedViewAccessor accessor, int capacity, int offset) : base(accessor, capacity, offset) { }
// Update is called once per frame void Update() { long sizeB = Marshal.SizeOf(typeof(bool)); long sizeI = sizeof(int); long sizeV = Marshal.SizeOf(typeof(Vector3)); long sizeF = sizeof(float); long jf = sizeB; //Is Color if (menuItem1.GetComponent <MenuItem1>().isColorChange) { for (int j = 0; j < meshNumOld; j++) { pre[j].GetComponent <MeshRenderer>().materials[1].color = colors[menuItem1.GetComponent <MenuItem1>().colorIndex]; } } //Is Mesh if (menuItem1.GetComponent <MenuItem1>().isMeshOnChange) { if (menuItem1.GetComponent <MenuItem1>().isMesh) { for (int j = 0; j < meshNumOld; j++) { pre[j].GetComponent <MeshRenderer>().materials[0].color = Color.black; } } else { for (int j = 0; j < meshNumOld; j++) { pre[j].GetComponent <MeshRenderer>().materials[0].color = new Color(1, 1, 1, 0); } } } //Is Bg if (menuItem1.GetComponent <MenuItem1>().isBgOnChange) { if (menuItem1.GetComponent <MenuItem1>().isBg) { for (int j = 0; j < BgNum.Length; j++) { for (int k = 0; k < BgNum[j]; ++k) { BgPre[j][k].SetActive(true); } } } else { for (int j = 0; j < BgNum.Length; j++) { for (int k = 0; k < BgNum[j]; ++k) { BgPre[j][k].SetActive(false); } } } } if (menuItem1.GetComponent <MenuItem1>().timeNow != timeNow) { timeNow = menuItem1.GetComponent <MenuItem1>().timeNow; using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(files[timeNow])) { using (MemoryMappedViewAccessor accessor = mmf.CreateViewAccessor()) { accessor.Read <int>(jf, out meshNum); jf += sizeI + sizeV * 2;//maxVertice and minVertice meshVNum = new int[meshNum]; meshTNum = new int[meshNum]; value = new float[meshNum]; if (meshNumOld < meshNum) { Array.Resize(ref pre, meshNum); for (int k = meshNumOld; k < meshNum; k++) { pre[k] = (GameObject)Instantiate(Resources.Load("Prefabs/Pres/PreContour"), objects.GetComponent <Transform>().position, objects.GetComponent <Transform>().rotation); pre[k].GetComponent <MeshRenderer>().materials[1].color = colors[menuItem1.GetComponent <MenuItem1>().colorIndex]; if (menuItem1.GetComponent <MenuItem1>().isMesh) { pre[k].GetComponent <MeshRenderer>().materials[0].color = Color.black; } else { pre[k].GetComponent <MeshRenderer>().materials[0].color = new Color(1, 1, 1, 0); } } } else if (meshNumOld > meshNum) { for (int k = meshNum; k < meshNumOld; k++) { Destroy(pre[k]); } } for (int j = 0; j < meshNum; j++) { accessor.Read <int>(jf, out meshVNum[j]); jf += sizeI; Vector3[] vertices = new Vector3[meshVNum[j]]; accessor.Read <int>(jf, out meshTNum[j]); jf += sizeI; int[] triangles = new int[meshTNum[j]]; accessor.ReadArray <Vector3>(jf, vertices, 0, meshVNum[j]); jf += sizeV * meshVNum[j]; accessor.ReadArray <int>(jf, triangles, 0, meshTNum[j]); jf += sizeI * meshTNum[j]; accessor.Read <float>(jf, out value[j]); jf += sizeF; //创建预设体,赋予顶点和拓扑 pre[j].transform.parent = GetComponent <Transform>(); Mesh mesh = pre[j].GetComponent <MeshFilter>().mesh; mesh.Clear(); mesh.vertices = vertices; mesh.triangles = triangles; mesh.RecalculateNormals(); } } } meshNumOld = meshNum; if (timeNow == 0) { Debug.Log(Time.time - ttt);//////////////////////////// ttt = Time.time; } } }
private static IReadOnlyDictionary <ImageDataDirectoryEntry, ImageDataDirectory> ReadDirectoryEntries(MemoryMappedViewAccessor view, long location, int count) { var dictionary = new Dictionary <ImageDataDirectoryEntry, ImageDataDirectory>(); var dataDirectories = new IMAGE_DATA_DIRECTORY[count]; view.ReadArray(location, dataDirectories, 0, dataDirectories.Length); for (var i = 0; i < dataDirectories.Length; i++) { var entry = new ImageDataDirectory { Size = dataDirectories[i].Size, VirtualAddress = dataDirectories[i].VirtualAddress }; dictionary.Add((ImageDataDirectoryEntry)i, entry); } return(dictionary); }
public DataStatus NewJobDataAvail(MemoryMappedViewAccessor source) { return(NewDataAvail(jobDataMarker, source, ref lastJobVal)); }
public DataStatus NewTrailerDataAvail(MemoryMappedViewAccessor source) { return(NewDataAvail(trailerDataMarker, source, ref lastTrailerVal)); }
public PEFileHelper(PEHeader header, MemoryMappedViewAccessor accessor) { Header = header; _accessor = accessor; }
/// <summary> /// Writes a 16-bit integer converted to a specific Endianness to the accessor. /// </summary> /// <param name="mem">The specified MemoryMappedViewAccessor.</param> /// <param name="position">The number of bytes into the accessor at which to begin writing.</param> /// <param name="value">The value to write.</param> /// <param name="convertTo">The Endianness to convert to.</param> public static void Write(this MemoryMappedViewAccessor mem, long position, short value, Endianness convertTo) { mem.Write(position, value.ConvertFromSystemEndian(convertTo)); }
public Mem(String mFile, uint[] BitmapArray = null, MemoryDescriptor Override = null) { GapScanSize = 0x10000000; StartOfMemory = Override != null ? Override.StartOfMemmory : 0; MapViewBase = 0; MapViewSize = MapWindowSize = (0x1000 * 0x1000 * 4); // Due to the physical page allocation algorithm a modest window is probably fine // so not even 1/2 the size of the window which was only getting < 50% hit ratio at best // PageCache may be better off than a huge window... if (PageCache == null) { PageCache = new ConcurrentDictionary <long, long[]>(8, PageCacheMax); } if (BitmapArray != null) { pfnTableIdx = new WAHBitArray(WAHBitArray.TYPE.Bitarray, BitmapArray); } else { pfnTableIdx = new WAHBitArray(); } // 32bit's of pages should be plenty? pfnTableIdx.Length = (int)(MapViewSize / 0x1000); if (File.Exists(mFile)) { MemoryDump = mFile; FileSize = new FileInfo(MemoryDump).Length; if (Override != null) { MD = Override; } else { MD = new MemoryDescriptor(FileSize); if (DetectedDescriptor != null) { MD = DetectedDescriptor; } } MapViewSize = FileSize < MapWindowSize ? FileSize : MapWindowSize; var lmindex = Interlocked.Increment(ref mindex); var mapName = Path.GetFileNameWithoutExtension(MemoryDump) + lmindex.ToString(); mapStream = new FileStream(MemoryDump, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); mappedFile = MemoryMappedFile.CreateFromFile(mapStream, mapName, 0, MemoryMappedFileAccess.Read, null, HandleInheritability.Inheritable, false); mappedAccess = mappedFile.CreateViewAccessor( MapViewBase, MapViewSize, MemoryMappedFileAccess.Read); DiscoveredGaps = new Dictionary <long, long>(); } }
/// <summary>Performs many reads and writes of various data types against the accessor.</summary> private static unsafe void AssertWritesReads(MemoryMappedViewAccessor acc) // TODO: unsafe can be removed once using C# 6 compiler { // Successful reads and writes at the beginning for each data type AssertWriteRead <bool>(false, 0, (pos, value) => acc.Write(pos, value), pos => acc.ReadBoolean(pos)); AssertWriteRead <bool>(true, 0, (pos, value) => acc.Write(pos, value), pos => acc.ReadBoolean(pos)); AssertWriteRead <byte>(42, 0, (pos, value) => acc.Write(pos, value), pos => acc.ReadByte(pos)); AssertWriteRead <char>('c', 0, (pos, value) => acc.Write(pos, value), pos => acc.ReadChar(pos)); AssertWriteRead <decimal>(9, 0, (pos, value) => acc.Write(pos, value), pos => acc.ReadDecimal(pos)); AssertWriteRead <double>(10, 0, (pos, value) => acc.Write(pos, value), pos => acc.ReadDouble(pos)); AssertWriteRead <short>(11, 0, (pos, value) => acc.Write(pos, value), pos => acc.ReadInt16(pos)); AssertWriteRead <int>(12, 0, (pos, value) => acc.Write(pos, value), pos => acc.ReadInt32(pos)); AssertWriteRead <long>(13, 0, (pos, value) => acc.Write(pos, value), pos => acc.ReadInt64(pos)); AssertWriteRead <sbyte>(14, 0, (pos, value) => acc.Write(pos, value), pos => acc.ReadSByte(pos)); AssertWriteRead <float>(15, 0, (pos, value) => acc.Write(pos, value), pos => acc.ReadSingle(pos)); AssertWriteRead <ushort>(16, 0, (pos, value) => acc.Write(pos, value), pos => acc.ReadUInt16(pos)); AssertWriteRead <uint>(17, 0, (pos, value) => acc.Write(pos, value), pos => acc.ReadUInt32(pos)); AssertWriteRead <ulong>(17, 0, (pos, value) => acc.Write(pos, value), pos => acc.ReadUInt64(pos)); // Successful reads and writes at the end for each data type long end = acc.Capacity; AssertWriteRead <bool>(false, end - sizeof(bool), (pos, value) => acc.Write(pos, value), pos => acc.ReadBoolean(pos)); AssertWriteRead <bool>(true, end - sizeof(bool), (pos, value) => acc.Write(pos, value), pos => acc.ReadBoolean(pos)); AssertWriteRead <byte>(42, end - sizeof(byte), (pos, value) => acc.Write(pos, value), pos => acc.ReadByte(pos)); AssertWriteRead <char>('c', end - sizeof(char), (pos, value) => acc.Write(pos, value), pos => acc.ReadChar(pos)); AssertWriteRead <decimal>(9, end - sizeof(decimal), (pos, value) => acc.Write(pos, value), pos => acc.ReadDecimal(pos)); AssertWriteRead <double>(10, end - sizeof(double), (pos, value) => acc.Write(pos, value), pos => acc.ReadDouble(pos)); AssertWriteRead <short>(11, end - sizeof(short), (pos, value) => acc.Write(pos, value), pos => acc.ReadInt16(pos)); AssertWriteRead <int>(12, end - sizeof(int), (pos, value) => acc.Write(pos, value), pos => acc.ReadInt32(pos)); AssertWriteRead <long>(13, end - sizeof(long), (pos, value) => acc.Write(pos, value), pos => acc.ReadInt64(pos)); AssertWriteRead <sbyte>(14, end - sizeof(sbyte), (pos, value) => acc.Write(pos, value), pos => acc.ReadSByte(pos)); AssertWriteRead <float>(15, end - sizeof(float), (pos, value) => acc.Write(pos, value), pos => acc.ReadSingle(pos)); AssertWriteRead <ushort>(16, end - sizeof(ushort), (pos, value) => acc.Write(pos, value), pos => acc.ReadUInt16(pos)); AssertWriteRead <uint>(17, end - sizeof(uint), (pos, value) => acc.Write(pos, value), pos => acc.ReadUInt32(pos)); AssertWriteRead <ulong>(17, end - sizeof(ulong), (pos, value) => acc.Write(pos, value), pos => acc.ReadUInt64(pos)); // Failed reads and writes just at the border of the end. This triggers different exception types // for some types than when we're completely beyond the end. long beyondEnd = acc.Capacity + 1; AssertExtensions.Throws <ArgumentOutOfRangeException>("position", () => acc.ReadBoolean(beyondEnd - sizeof(bool))); AssertExtensions.Throws <ArgumentOutOfRangeException>("position", () => acc.ReadByte(beyondEnd - sizeof(byte))); AssertExtensions.Throws <ArgumentOutOfRangeException>("position", () => acc.ReadSByte(beyondEnd - sizeof(sbyte))); AssertExtensions.Throws <ArgumentException>("position", () => acc.ReadChar(beyondEnd - sizeof(char))); AssertExtensions.Throws <ArgumentException>("position", () => acc.ReadDecimal(beyondEnd - sizeof(decimal))); AssertExtensions.Throws <ArgumentException>("position", () => acc.ReadDouble(beyondEnd - sizeof(double))); AssertExtensions.Throws <ArgumentException>("position", () => acc.ReadInt16(beyondEnd - sizeof(short))); AssertExtensions.Throws <ArgumentException>("position", () => acc.ReadInt32(beyondEnd - sizeof(int))); AssertExtensions.Throws <ArgumentException>("position", () => acc.ReadInt64(beyondEnd - sizeof(long))); AssertExtensions.Throws <ArgumentException>("position", () => acc.ReadSingle(beyondEnd - sizeof(float))); AssertExtensions.Throws <ArgumentException>("position", () => acc.ReadUInt16(beyondEnd - sizeof(ushort))); AssertExtensions.Throws <ArgumentException>("position", () => acc.ReadUInt32(beyondEnd - sizeof(uint))); AssertExtensions.Throws <ArgumentException>("position", () => acc.ReadUInt64(beyondEnd - sizeof(ulong))); AssertExtensions.Throws <ArgumentOutOfRangeException>("position", () => acc.Write(beyondEnd - sizeof(bool), false)); AssertExtensions.Throws <ArgumentOutOfRangeException>("position", () => acc.Write(beyondEnd - sizeof(byte), (byte)0)); AssertExtensions.Throws <ArgumentOutOfRangeException>("position", () => acc.Write(beyondEnd - sizeof(sbyte), (sbyte)0)); AssertExtensions.Throws <ArgumentException>("position", () => acc.Write(beyondEnd - sizeof(char), 'c')); AssertExtensions.Throws <ArgumentException>("position", () => acc.Write(beyondEnd - sizeof(decimal), (decimal)0)); AssertExtensions.Throws <ArgumentException>("position", () => acc.Write(beyondEnd - sizeof(double), (double)0)); AssertExtensions.Throws <ArgumentException>("position", () => acc.Write(beyondEnd - sizeof(short), (short)0)); AssertExtensions.Throws <ArgumentException>("position", () => acc.Write(beyondEnd - sizeof(int), (int)0)); AssertExtensions.Throws <ArgumentException>("position", () => acc.Write(beyondEnd - sizeof(long), (long)0)); AssertExtensions.Throws <ArgumentException>("position", () => acc.Write(beyondEnd - sizeof(float), (float)0)); AssertExtensions.Throws <ArgumentException>("position", () => acc.Write(beyondEnd - sizeof(ushort), (ushort)0)); AssertExtensions.Throws <ArgumentException>("position", () => acc.Write(beyondEnd - sizeof(uint), (uint)0)); AssertExtensions.Throws <ArgumentException>("position", () => acc.Write(beyondEnd - sizeof(ulong), (ulong)0)); // Failed reads and writes well past the end beyondEnd = acc.Capacity + 20; AssertExtensions.Throws <ArgumentOutOfRangeException>("position", () => acc.ReadBoolean(beyondEnd - sizeof(bool))); AssertExtensions.Throws <ArgumentOutOfRangeException>("position", () => acc.ReadByte(beyondEnd - sizeof(byte))); AssertExtensions.Throws <ArgumentOutOfRangeException>("position", () => acc.ReadSByte(beyondEnd - sizeof(sbyte))); AssertExtensions.Throws <ArgumentOutOfRangeException>("position", () => acc.ReadChar(beyondEnd - sizeof(char))); AssertExtensions.Throws <ArgumentOutOfRangeException>("position", () => acc.ReadDecimal(beyondEnd - sizeof(decimal))); AssertExtensions.Throws <ArgumentOutOfRangeException>("position", () => acc.ReadDouble(beyondEnd - sizeof(double))); AssertExtensions.Throws <ArgumentOutOfRangeException>("position", () => acc.ReadInt16(beyondEnd - sizeof(short))); AssertExtensions.Throws <ArgumentOutOfRangeException>("position", () => acc.ReadInt32(beyondEnd - sizeof(int))); AssertExtensions.Throws <ArgumentOutOfRangeException>("position", () => acc.ReadInt64(beyondEnd - sizeof(long))); AssertExtensions.Throws <ArgumentOutOfRangeException>("position", () => acc.ReadSingle(beyondEnd - sizeof(float))); AssertExtensions.Throws <ArgumentOutOfRangeException>("position", () => acc.ReadUInt16(beyondEnd - sizeof(ushort))); AssertExtensions.Throws <ArgumentOutOfRangeException>("position", () => acc.ReadUInt32(beyondEnd - sizeof(uint))); AssertExtensions.Throws <ArgumentOutOfRangeException>("position", () => acc.ReadUInt64(beyondEnd - sizeof(ulong))); AssertExtensions.Throws <ArgumentOutOfRangeException>("position", () => acc.Write(beyondEnd - sizeof(bool), false)); AssertExtensions.Throws <ArgumentOutOfRangeException>("position", () => acc.Write(beyondEnd - sizeof(byte), (byte)0)); AssertExtensions.Throws <ArgumentOutOfRangeException>("position", () => acc.Write(beyondEnd - sizeof(sbyte), (sbyte)0)); AssertExtensions.Throws <ArgumentOutOfRangeException>("position", () => acc.Write(beyondEnd - sizeof(char), 'c')); AssertExtensions.Throws <ArgumentOutOfRangeException>("position", () => acc.Write(beyondEnd - sizeof(decimal), (decimal)0)); AssertExtensions.Throws <ArgumentOutOfRangeException>("position", () => acc.Write(beyondEnd - sizeof(double), (double)0)); AssertExtensions.Throws <ArgumentOutOfRangeException>("position", () => acc.Write(beyondEnd - sizeof(short), (short)0)); AssertExtensions.Throws <ArgumentOutOfRangeException>("position", () => acc.Write(beyondEnd - sizeof(int), (int)0)); AssertExtensions.Throws <ArgumentOutOfRangeException>("position", () => acc.Write(beyondEnd - sizeof(long), (long)0)); AssertExtensions.Throws <ArgumentOutOfRangeException>("position", () => acc.Write(beyondEnd - sizeof(float), (float)0)); AssertExtensions.Throws <ArgumentOutOfRangeException>("position", () => acc.Write(beyondEnd - sizeof(ushort), (ushort)0)); AssertExtensions.Throws <ArgumentOutOfRangeException>("position", () => acc.Write(beyondEnd - sizeof(uint), (uint)0)); AssertExtensions.Throws <ArgumentOutOfRangeException>("position", () => acc.Write(beyondEnd - sizeof(ulong), (ulong)0)); }
public long GetPageFromFileOffset(long FileOffset, ref long[] block) { var rv = 0L; var NewMapViewBase = MapViewBase; var NewMapViewSize = MapViewSize; var CheckBase = FileOffset / MapViewSize; if (MapViewBase != CheckBase * MapViewSize) { NewMapViewBase = CheckBase * MapViewSize; } if (FileOffset > FileSize) { return(0); } if (FileOffset < NewMapViewBase) { throw new OverflowException("FileOffset must be >= than base"); } var AbsOffset = FileOffset - NewMapViewBase; var BlockOffset = AbsOffset & ~(PAGE_SIZE - 1); try { if (NewMapViewBase != MapViewBase) { cntInAccessor++; if (NewMapViewBase + MapViewSize > FileSize) { NewMapViewSize = FileSize - NewMapViewBase; } else { NewMapViewSize = MapViewSize; } mappedAccess = mappedFile.CreateViewAccessor( NewMapViewBase, NewMapViewSize, MemoryMappedFileAccess.Read); MapViewBase = NewMapViewBase; } else { cntOutAccsor++; } if (block != null) { UnsafeHelp.ReadBytes(mappedAccess, BlockOffset, ref block); } rv = mappedAccess.ReadInt64(AbsOffset); } catch (Exception ex) { block = null; throw new MemoryMapWindowFailedException("Unable to map or read into", ex); } return(rv); }
public static unsafe PEReader OpenPEFile(string filePath, byte[] moduleBytes, out MemoryMappedViewAccessor mappedViewAccessor) { // If moduleBytes is specified create PEReader from the in memory array, not from a file on disk if (moduleBytes != null) { var peReader = new PEReader(ImmutableArray.Create <byte>(moduleBytes)); mappedViewAccessor = null; return(peReader); } // System.Reflection.Metadata has heuristic that tries to save virtual address space. This heuristic does not work // well for us since it can make IL access very slow (call to OS for each method IL query). We will map the file // ourselves to get the desired performance characteristics reliably. FileStream fileStream = null; MemoryMappedFile mappedFile = null; MemoryMappedViewAccessor accessor = null; try { // Create stream because CreateFromFile(string, ...) uses FileShare.None which is too strict fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, false); mappedFile = MemoryMappedFile.CreateFromFile( fileStream, null, fileStream.Length, MemoryMappedFileAccess.Read, HandleInheritability.None, true); accessor = mappedFile.CreateViewAccessor(0, 0, MemoryMappedFileAccess.Read); var safeBuffer = accessor.SafeMemoryMappedViewHandle; var peReader = new PEReader((byte *)safeBuffer.DangerousGetHandle(), (int)safeBuffer.ByteLength); // MemoryMappedFile does not need to be kept around. MemoryMappedViewAccessor is enough. mappedViewAccessor = accessor; accessor = null; return(peReader); } finally { if (accessor != null) { accessor.Dispose(); } if (mappedFile != null) { mappedFile.Dispose(); } if (fileStream != null) { fileStream.Dispose(); } } }
public DMXController() { memoryMappedFile = MemoryMappedFile.CreateOrOpen(VIRTUALFILENAME, DATASIZE, MemoryMappedFileAccess.ReadWrite, MemoryMappedFileOptions.DelayAllocatePages, null, System.IO.HandleInheritability.Inheritable); accessor = memoryMappedFile.CreateViewAccessor(0, DATASIZE); }
public CiRSDKHeader(MemoryMappedViewAccessor mapView) { FileMapView = mapView; buffer = new CVarBuf(mapView, this); }
public MmapDefault(CodeContext /*!*/ context, int fileno, long length, string tagname = null, int access = ACCESS_WRITE, long offset = 0) { switch (access) { case ACCESS_READ: _fileAccess = MemoryMappedFileAccess.Read; break; case ACCESS_WRITE: _fileAccess = MemoryMappedFileAccess.ReadWrite; break; case ACCESS_COPY: _fileAccess = MemoryMappedFileAccess.CopyOnWrite; break; default: throw PythonOps.ValueError("mmap invalid access parameter"); } if (length < 0) { throw PythonOps.OverflowError("memory mapped size must be positive"); } if (offset < 0) { throw PythonOps.OverflowError("memory mapped offset must be positive"); } if (length > SysModule.maxsize) { throw PythonOps.OverflowError("cannot fit 'long' into an index-sized integer"); } // CPython only allows offsets that are a multiple of ALLOCATIONGRANULARITY if (offset % ALLOCATIONGRANULARITY != 0) { throw WindowsError(PythonExceptions._OSError.ERROR_MAPPED_ALIGNMENT); } // .NET throws on an empty tagname, but CPython treats it as null. _mapName = tagname == "" ? null : tagname; if (fileno == -1 || fileno == 0) { // Map anonymous memory that is not tied to a file. // Note: CPython seems to allow 0 as a file descriptor even though it represents stdin. _offset = 0; // offset is ignored without an underlying file _sourceStream = null; // work around the .NET bug whereby CreateOrOpen throws on a null mapName if (_mapName == null) { _mapName = Guid.NewGuid().ToString(); } _file = MemoryMappedFile.CreateOrOpen(_mapName, length, _fileAccess); } else { // Memory-map an actual file _offset = offset; PythonContext pContext = context.LanguageContext; if (pContext.FileManager.TryGetFileFromId(pContext, fileno, out PythonIOModule.FileIO fileio)) { if ((_sourceStream = fileio._readStream as FileStream) == null) { throw WindowsError(PythonExceptions._OSError.ERROR_INVALID_HANDLE); } } else { throw PythonOps.OSError(PythonExceptions._OSError.ERROR_INVALID_BLOCK, "Bad file descriptor"); } if (_fileAccess == MemoryMappedFileAccess.ReadWrite && !_sourceStream.CanWrite) { throw WindowsError(PythonExceptions._OSError.ERROR_ACCESS_DENIED); } if (length == 0) { length = _sourceStream.Length; if (length == 0) { throw PythonOps.ValueError("cannot mmap an empty file"); } if (_offset >= length) { throw PythonOps.ValueError("mmap offset is greater than file size"); } length -= _offset; } long capacity = checked (_offset + length); // Enlarge the file as needed. if (capacity > _sourceStream.Length) { if (_sourceStream.CanWrite) { _sourceStream.SetLength(capacity); } else { throw WindowsError(PythonExceptions._OSError.ERROR_NOT_ENOUGH_MEMORY); } } _file = CreateFromFile( _sourceStream, _mapName, _sourceStream.Length, _fileAccess, HandleInheritability.None, true); } try { _view = _file.CreateViewAccessor(_offset, length, _fileAccess); } catch { _file.Dispose(); _file = null; throw; } _position = 0L; }
private void CreateOrUpdateBitmap(bool isPopup, Rect dirtyRect, IntPtr buffer, int width, int height, Image image, ref Size currentSize, ref MemoryMappedFile mappedFile, ref MemoryMappedViewAccessor viewAccessor) { if (image.Dispatcher.HasShutdownStarted) { return; } var createNewBitmap = false; lock (lockObject) { int pixels = width * height; int numberOfBytes = pixels * BytesPerPixel; createNewBitmap = mappedFile == null || currentSize.Height != height || currentSize.Width != width; if (createNewBitmap) { ReleaseMemoryMappedView(ref mappedFile, ref viewAccessor); mappedFile = MemoryMappedFile.CreateNew(null, numberOfBytes, MemoryMappedFileAccess.ReadWrite); viewAccessor = mappedFile.CreateViewAccessor(); currentSize.Height = height; currentSize.Width = width; } //TODO: Performance analysis to determine which is the fastest memory copy function //NativeMethodWrapper.CopyMemoryUsingHandle(viewAccessor.SafeMemoryMappedViewHandle.DangerousGetHandle(), buffer, numberOfBytes); CopyMemory(viewAccessor.SafeMemoryMappedViewHandle.DangerousGetHandle(), buffer, (uint)numberOfBytes); //Take a reference to the backBufferHandle, once we're on the UI thread we need to check if it's still valid var backBufferHandle = mappedFile.SafeMemoryMappedFileHandle; //Invoke on the WPF UI Thread image.Dispatcher.BeginInvoke((Action)(() => { lock (lockObject) { if (backBufferHandle.IsClosed || backBufferHandle.IsInvalid) { return; } if (createNewBitmap) { if (image.Source != null) { image.Source = null; //TODO: Is this still required in newer versions of .Net? GC.Collect(1); } var stride = width * BytesPerPixel; var bitmap = (InteropBitmap)Imaging.CreateBitmapSourceFromMemorySection(backBufferHandle.DangerousGetHandle(), width, height, PixelFormat, stride, 0); image.Source = bitmap; } else { if (image.Source != null) { var sourceRect = new Int32Rect(dirtyRect.X, dirtyRect.Y, dirtyRect.Width, dirtyRect.Height); var bitmap = (InteropBitmap)image.Source; bitmap.Invalidate(sourceRect); } } } }), dispatcherPriority); } }
public void resize(long newsize) { using (new MmapLocker(this)) { if (_fileAccess != MemoryMappedFileAccess.ReadWrite) { throw PythonOps.TypeError("mmap can't resize a readonly or copy-on-write memory map."); } if (_sourceStream == null) { // resizing is not supported without an underlying file throw WindowsError(PythonExceptions._OSError.ERROR_INVALID_PARAMETER); } if (newsize == 0) { // resizing to an empty mapped region is not allowed throw WindowsError(_offset == 0 ? PythonExceptions._OSError.ERROR_ACCESS_DENIED : PythonExceptions._OSError.ERROR_FILE_INVALID ); } if (_view.Capacity == newsize) { // resizing to the same size return; } long capacity = checked (_offset + newsize); try { _view.Flush(); _view.Dispose(); _file.Dispose(); var leaveOpen = true; if (!_sourceStream.CanWrite) { _sourceStream = new FileStream(_sourceStream.Name, FileMode.OpenOrCreate, FileAccess.ReadWrite); leaveOpen = false; } // Resize the file as needed. if (capacity != _sourceStream.Length) { _sourceStream.SetLength(capacity); } _file = CreateFromFile( _sourceStream, _mapName, _sourceStream.Length, _fileAccess, HandleInheritability.None, leaveOpen); _view = _file.CreateViewAccessor(_offset, newsize, _fileAccess); } catch { close(); throw; } } }
public ByteBuffer(long size, long limit) { _memFile = MemoryMappedFile.CreateNew(null, limit); _accessor = _memFile.CreateViewAccessor(); Size = size; }
/// <summary> /// Reads an unsigned 24-bit integer from the accessor. /// </summary> /// <param name="mem">The specified MemoryMappedViewAccessor.</param> /// <param name="position">The number of bytes into the accessor at which to begin reading.</param> /// <returns>The value that was read as converted to the current system Endianness.</returns> public static UInt24 ReadUInt24(this MemoryMappedViewAccessor mem, long position) { return(new UInt24(mem.ReadByte(position), mem.ReadByte(position + 1), mem.ReadByte(position + 2))); }
private void CreateOrUpdateBitmap(bool isPopup, Rect dirtyRect, IntPtr buffer, int width, int height, Image image, ref Size currentSize, ref MemoryMappedFile mappedFile, ref MemoryMappedViewAccessor viewAccessor) { bool createNewBitmap = false; if (image.Dispatcher.HasShutdownStarted) { return; } lock (lockObject) { int pixels = width * height; int numberOfBytes = pixels * BytesPerPixel; createNewBitmap = mappedFile == null || currentSize.Height != height || currentSize.Width != width; if (createNewBitmap) { ReleaseMemoryMappedView(ref mappedFile, ref viewAccessor); mappedFile = MemoryMappedFile.CreateNew(null, numberOfBytes, MemoryMappedFileAccess.ReadWrite); viewAccessor = mappedFile.CreateViewAccessor(); currentSize.Height = height; currentSize.Width = width; } //TODO: Performance analysis to determine which is the fastest memory copy function //NativeMethodWrapper.CopyMemoryUsingHandle(viewAccessor.SafeMemoryMappedViewHandle.DangerousGetHandle(), buffer, numberOfBytes); CopyMemory(viewAccessor.SafeMemoryMappedViewHandle.DangerousGetHandle(), buffer, (uint)numberOfBytes); //Take a reference to the sourceBuffer that's used to update our WritableBitmap, //once we're on the UI thread we need to check if it's still valid var sourceBuffer = viewAccessor.SafeMemoryMappedViewHandle; image.Dispatcher.BeginInvoke((Action)(() => { lock (lockObject) { if (sourceBuffer.IsClosed || sourceBuffer.IsInvalid) { return; } if (createNewBitmap) { if (image.Source != null) { image.Source = null; GC.Collect(1); } image.Source = new WriteableBitmap(width, height, dpiX, dpiY, PixelFormat, null); } var stride = width * BytesPerPixel; var noOfBytes = stride * height; var bitmap = (WriteableBitmap)image.Source; //By default we'll only update the dirty rect, for those that run into a MILERR_WIN32ERROR Exception (#2035) //it's desirably to either upgrade to a newer .Net version (only client runtime needs to be installed, not compiled //against a newer version. Or invalidate the whole bitmap if (invalidateDirtyRect) { // Update the dirty region var sourceRect = new Int32Rect(dirtyRect.X, dirtyRect.Y, dirtyRect.Width, dirtyRect.Height); bitmap.Lock(); bitmap.WritePixels(sourceRect, sourceBuffer.DangerousGetHandle(), noOfBytes, stride, dirtyRect.X, dirtyRect.Y); bitmap.Unlock(); } else { // Update whole bitmap var sourceRect = new Int32Rect(0, 0, width, height); bitmap.Lock(); bitmap.WritePixels(sourceRect, sourceBuffer.DangerousGetHandle(), noOfBytes, stride); bitmap.Unlock(); } } }), dispatcherPriority); } }
/// <summary> /// Reads a structure of type T from the accessor and returns it. /// </summary> /// <typeparam name="T">The type of structure.</typeparam> /// <param name="mem">The specified MemoryMappedViewAccessor.</param> /// <param name="position">The position in the accessor at which to begin reading.</param> /// <returns>The structure containing the read data.</returns> public static T Read <T>(this MemoryMappedViewAccessor mem, long position) where T : struct { mem.Read(position, out T temp); return(temp); }
/// <summary>Performs validation on a view accessor.</summary> /// <param name="accessor">The accessor to validate.</param> /// <param name="capacity">The capacity specified when creating the accessor.</param> /// <param name="access">The access specified when creating the accessor.</param> protected static void ValidateMemoryMappedViewAccessor(MemoryMappedViewAccessor accessor, long capacity, MemoryMappedFileAccess access) { // Validate the accessor and its handle Assert.NotNull(accessor); Assert.NotNull(accessor.SafeMemoryMappedViewHandle); Assert.Same(accessor.SafeMemoryMappedViewHandle, accessor.SafeMemoryMappedViewHandle); // Ensure its properties match the criteria specified when it was created Assert.InRange(capacity, 0, accessor.Capacity); // the capacity may be rounded up to page size, so all we guarantee is that the accessor's capacity >= capacity Assert.Equal(0, accessor.PointerOffset); // If it's supposed to be readable, try to read from it. // Otherwise, verify we can't. if (IsReadable(access)) { Assert.True(accessor.CanRead); Assert.Equal(0, accessor.ReadByte(0)); Assert.Equal(0, accessor.ReadByte(capacity - 1)); } else { Assert.False(accessor.CanRead); Assert.Throws<NotSupportedException>(() => accessor.ReadByte(0)); } // If it's supposed to be writable, try to write to it if (IsWritable(access) || access == MemoryMappedFileAccess.CopyOnWrite) { Assert.True(accessor.CanWrite); // Write some data accessor.Write(0, (byte)42); accessor.Write(capacity - 1, (byte)42); // If possible, ensure we can read it back if (IsReadable(access)) { Assert.Equal(42, accessor.ReadByte(0)); Assert.Equal(42, accessor.ReadByte(capacity - 1)); } // Write 0 back where we wrote data accessor.Write(0, (byte)0); accessor.Write(capacity - 1, (byte)0); } else { Assert.False(accessor.CanWrite); Assert.Throws<NotSupportedException>(() => accessor.Write(0, (byte)0)); } }
static int Main(string[] args) { if (Registry.GetValue( @"HKEY_CURRENT_USER\SOFTWARE\CafeHaine\Windmenu", "test", string.Empty) == null) { Registry.SetValue(@"HKEY_CURRENT_USER\SOFTWARE\CafeHaine\", "", ""); Registry.SetValue( @"HKEY_CURRENT_USER\SOFTWARE\CafeHaine\Windmenu\", "", ""); } else { int pid = (int)Registry.GetValue( @"HKEY_CURRENT_USER\SOFTWARE\CafeHaine\Windmenu", "serverid", -1); if (pid != -1) { string processName = (string)Registry.GetValue( @"HKEY_CURRENT_USER\SOFTWARE\CafeHaine\Windmenu", "servername", string.Empty); Process[] procs = Process.GetProcessesByName(processName); foreach (Process proc in procs) { if (proc.Id == pid) { proc.Kill(); } } } } Process current = Process.GetCurrentProcess(); Registry.SetValue(@"HKEY_CURRENT_USER\SOFTWARE\CafeHaine\Windmenu", "serverid", current.Id); Registry.SetValue(@"HKEY_CURRENT_USER\SOFTWARE\CafeHaine\Windmenu", "servername", current.ProcessName); current.Dispose(); #if DEBUG NativeMethods.AllocConsole(); #endif LoadSettings(); Regex[] blacklist = new Regex[Regexes.Length]; for (int i = 0; i < Regexes.Length; i++) { blacklist[i] = new Regex(Regexes[i], RegexIgnoreCase ? RegexOptions.IgnoreCase : RegexOptions.None); } List <KeyValuePair <string, string> > Links = Binaries.GetBinaries( ParseStartMenu, blacklist); Links = Links.Distinct(new linksComparer()).ToList(); Links.Sort(Comparer <KeyValuePair <string, string> > .Create( (i1, i2) => i1.Key.CompareTo(i2.Key))); List <string> LinksNames = new List <string>(Links.Count); for (int i = 0; i < Links.Count; i++) { LinksNames.Add(Links[i].Key); } byte[] toWrite = Encoding.Unicode.GetBytes(string.Join("|", LinksNames)); MemoryMappedFile mmf; try { mmf = MemoryMappedFile.CreateNew("windmenu", 8 + toWrite.Length); MemoryMappedViewAccessor va = mmf.CreateViewAccessor(); va.Write(0, toWrite.LongLength); va.WriteArray(8, toWrite, 0, toWrite.Length); va.Dispose(); } catch (Exception) { MessageBox.Show("windmenu Server seems to already be running.", "windmenu Server"); return(1); } TcpListener serverSocket = new TcpListener(IPAddress.Loopback, 12321); TcpClient clientSocket = default(TcpClient); serverSocket.Start(); Console.WriteLine("Server Started"); bool shouldRun = true; while (shouldRun) { clientSocket = serverSocket.AcceptTcpClient(); Console.WriteLine("Accepted client"); NetworkStream stream = clientSocket.GetStream(); byte[] clientRequestSize = new byte[2]; stream.Read(clientRequestSize, 0, 2); int inSize = clientRequestSize[0] * 256 + clientRequestSize[1]; byte[] clientRequest = new byte[inSize]; stream.Read(clientRequest, 0, inSize); string data = Encoding.Unicode.GetString(clientRequest); Console.WriteLine("\tClient request: " + data); if (data.StartsWith("run")) { TreatRequest(Encoding.Unicode.GetString(clientRequest), ref Links); } else { Console.WriteLine("\tRequest was invalid"); } Console.WriteLine("Connexion closed"); clientSocket.Close(); } serverSocket.Stop(); mmf.Dispose(); return(0); }