public unsafe void Append(TextAnalyzer analyzer, FontFace font, string text) { var layout = new TextLayout(); var format = new TextFormat { Font = font, Size = 32.0f }; analyzer.AppendText(text, format); analyzer.PerformLayout(0, 32, 1000, 1000, layout); var memBlock = new MemoryBlock(text.Length * 6 * PosColorTexture.Layout.Stride); var mem = (PosColorTexture*)memBlock.Data; foreach (var thing in layout.Stuff) { var width = thing.Width; var height = thing.Height; var region = new Vector4(thing.SourceX, thing.SourceY, width, height) / 4096; var origin = new Vector2(thing.DestX, thing.DestY); *mem++ = new PosColorTexture(origin + new Vector2(0, height), new Vector2(region.X, region.Y + region.W), unchecked((int)0xff000000)); *mem++ = new PosColorTexture(origin + new Vector2(width, height), new Vector2(region.X + region.Z, region.Y + region.W), unchecked((int)0xff000000)); *mem++ = new PosColorTexture(origin + new Vector2(width, 0), new Vector2(region.X + region.Z, region.Y), unchecked((int)0xff000000)); *mem++ = new PosColorTexture(origin, new Vector2(region.X, region.Y), unchecked((int)0xff000000)); count++; } vertexBuffer = new DynamicVertexBuffer(memBlock, PosColorTexture.Layout); }
public Mesh (MemoryBlock vertices, VertexLayout decl, ushort[] indices) { var group = new MeshGroup(); group.VertexBuffer = new VertexBuffer(vertices, decl); group.IndexBuffer = new IndexBuffer(MemoryBlock.FromArray(indices)); vertexDecl = decl; groups = new List<MeshGroup> { group }; }
internal SubSection( string sectionName, int offset, MemoryBlock memoryBlock) { this.SectionName = sectionName; this.Offset = (uint)offset; this.MemoryBlock = memoryBlock; }
public static void MakeArray(MemoryBlock memory, AsquellObj to, params AsquellObj[] values) { if (to.Type == AsquellObjectType.RunTimeValue) { ArrayObj array = new ArrayObj(values); memory.ModifyVariable(to, array.BaseObj); return; } throw new ArgumentException("Invalid type for modifying memory! First argument must be a variable!"); }
public static void SubtractNumbers(MemoryBlock memory, AsquellObj a, AsquellObj b, AsquellObj storeResult) { NumericObj NumA = getNumericObj(a, memory); NumericObj NumB = getNumericObj(b, memory); if (NumA != null && NumB != null) { memory.ModifyVariable(storeResult, (NumA - NumB).BaseObj); return; } throw new ArgumentException("Invalid type for subtracting!"); }
public void AssertExtent(MemoryBlock mem, int position, int maxLength, int expectedOffset, int expectedLength) { int offset; int length; NativeMethods.Ascii_GetLineExtentFromPosition( mem.Ptr, mem.Size - 1, position, maxLength, out offset, out length); Assert.AreEqual(expectedOffset, offset); Assert.AreEqual(expectedLength, length); }
public TextBuffer(int capacity) { var indexMem = new MemoryBlock(sizeof(ushort) * capacity * 6); var indices = (ushort*)indexMem.Data; for (int i = 0, v = 0; i < capacity; i++, v += 4) { *indices++ = (ushort)(v + 0); *indices++ = (ushort)(v + 1); *indices++ = (ushort)(v + 2); *indices++ = (ushort)(v + 2); *indices++ = (ushort)(v + 3); *indices++ = (ushort)(v + 0); } indexBuffer = new IndexBuffer(indexMem); }
public bool CallReflection(string embedName, string methodName, MemoryBlock block, params AsquellObj[] args) { if (embedName == null) { for (int i = 0; i < _globalMethods.Count; i++) { if (_globalMethods[i].ContainsMethod(methodName)) return _globalMethods[i].DoReflection(methodName, args, block); } } else if (_opToClass.ContainsKey(embedName)) { return _opToClass[embedName].DoReflection(methodName, args, block); } return false; }
public static void MoveMemory(MemoryBlock memory, AsquellObj to, AsquellObj from) { if (from.Type == AsquellObjectType.RunTimeValue) { if (memory.VariableInMemory(from)) { AsquellObj rawValue = memory.GetRealVariable(from); memory.ModifyVariable(to, rawValue); memory.DeleteVariable(from); return; } else { throw new KeyNotFoundException("Can not find '"+from.Value.ToString()+"' in memory!"); } } throw new ArgumentException("Invalid type for moving memory! First argument must be a variable!"); }
public static void SaveToFile( string fileName, ImageType imageType, MemoryBlock memBlock, int lineWidth, int lineCount) { if(lineCount <= 0) { return; } IntPtr memoryPtr = memBlock.ToPointer(); IntPtr tiff = Open(fileName, "w"); if (tiff == IntPtr.Zero) throw new Exception("Unable write TIFF file: " + fileName); try { int bitPerSample = (imageType == ImageType.Binary ? 1 : 8); SetIntField(tiff, FieldName.IMAGEWIDTH, lineWidth); SetIntField(tiff, FieldName.IMAGELENGTH, lineCount); SetIntField(tiff, FieldName.BITSPERSAMPLE, bitPerSample); SetIntField(tiff, FieldName.SAMPLESPERPIXEL, 1); SetIntField(tiff, FieldName.ROWSPERSTRIP, lineCount); if (imageType == ImageType.Binary) { SetIntField(tiff, FieldName.COMPRESSION, (int)CompressionType.CCITTFAX4); SetIntField(tiff, FieldName.PHOTOMETRIC, (int)Photometric.MINISWHITE); } else { SetIntField(tiff, FieldName.COMPRESSION, (int)CompressionType.LZW); SetIntField(tiff, FieldName.PHOTOMETRIC, (int)Photometric.MINISBLACK); } SetIntField(tiff, FieldName.FILLORDER, (int)Fillorder.MSB2LSB); SetIntField(tiff, FieldName.PLANARCONFIG, (int)PlanarConfig.CONTIG); SetFloatField(tiff, FieldName.XRESOLUTION, 200.0); SetFloatField(tiff, FieldName.YRESOLUTION, 200.0); SetIntField(tiff, FieldName.RESOLUTIONUNIT, (int)ResolutionUnit.INCH); WriteEncodedStrip(tiff, 0, memoryPtr, lineWidth * lineCount * bitPerSample / 8); } finally { Close(tiff); } }
public bool DoReflection(string name, AsquellObj[] args, MemoryBlock block) { if (_usableMethods.ContainsKey(name)) { MethodInfo m = _usableMethods[name]; int argCount = args.Length; if (getMethodAttr(m).NoMemoryBlock == false) argCount++; //Don't want to call a method that will throw a C# error if (m.GetParameters().Length != argCount && !methodHasParams(m)) return false; object[] methodArgs = new object[m.GetParameters().Length]; if (args.Length < argCount) { methodArgs[0] = block; } int argTrueCount = 0; for (int i = (args.Length < argCount ? 1 : 0); i < methodArgs.Length; i++) { if (i + 1 == methodArgs.Length && methodHasParams(m)) { methodArgs[i] = arrayOfArgs(args, argTrueCount); } else methodArgs[i] = args[argTrueCount]; argTrueCount++; } m.Invoke(null, methodArgs); return true; } return false; }
private void LoadFromStream(Stream stream) { blocks = new List<MemoryBlock>(); string line; bool hexFileEOF = false; var currentBlock = new MemoryBlock(); UInt64 currentExtendedAddress = 0; Size = 0; using (var reader = new StreamReader(stream)) { while (((line = reader.ReadLine()) != "") && (hexFileEOF == false)) { HexLine hexLine = ParseLine(line); switch (hexLine.recordType) { case HexRecordType.EOF: hexFileEOF = true; break; case HexRecordType.ExtendedLinearAddress: currentExtendedAddress = Convert.ToUInt64(hexLine.dataPayload, 16) << 16; // Add a new memory block section if // 1: the current block has data (size > 0) // 2: the next block has a different starting address to the current block // 3: the next block address does not already exist in the array. if ((currentBlock.size > 0) && (currentExtendedAddress != currentBlock.startAddress) && (blocks.Count(b => b.startAddress == currentExtendedAddress) == 0)) { blocks.Add(currentBlock); currentBlock = new MemoryBlock(currentExtendedAddress); } break; case HexRecordType.Data: // Calculate the maximum possible address using the given data // Actual maximum is 65536 bytes (2^16). UInt64 size = (ulong)hexLine.recordLength + (ulong)hexLine.addressField; if (size > currentBlock.size) currentBlock.size = size; // Assuming each memory block is 65K in size, // load the data buffer with data at the given address uint offset = 0; for (byte j = 0; j < hexLine.recordLength; j++ ) { uint addr = (uint)hexLine.addressField + j - offset; // Address exceeds the currently allocated data block, // create a new block at the current address if (addr >= currentBlock.data.Length) //65536 { // Limit the block size currentBlock.size = (uint)currentBlock.data.Length; // Split the memory block blocks.Add(currentBlock); currentBlock = new MemoryBlock(addr + currentExtendedAddress); // Wrap the address around into the new block offset = (uint)currentBlock.data.Length; addr -= offset; } currentBlock.data[addr] = Convert.ToByte(hexLine.dataPayload.Substring(j * 2, 2), 16); } // Note that if a data line is missing, the data bytes are simply left as '0' //TODO: are they supposed to be set to 0xFF? break; default: throw new HexFileException(String.Format("Unsupported hex record type '{0}'", hexLine.recordType.ToString())); } } } // Finally add the last block used blocks.Add(currentBlock); Size = 0; foreach (var block in blocks) Size += block.size; /*Console.WriteLine("Num blocks: {0}", blocks.Count); UInt64 totalSize = 0; foreach (var block in blocks) { //Console.WriteLine("{2}\n\tstartAddress:{0}\n\tsize:{1}", block.startAddress, block.size, block.ToString()); Console.WriteLine(block); totalSize += block.size; } Console.WriteLine("Total size:{0} bytes", totalSize);*/ }
public static void SetMemory(MemoryBlock memory, AsquellObj to, AsquellObj from) { memory.ModifyVariable(to, from); }
public GuidStreamReader(MemoryBlock block) { this.Block = block; }
public UserStringStreamReader(MemoryBlock block) { this.Block = block; }
private void ThreadFunction() { if (this.srcArgs.Surface.Scan0.MaySetAllowWrites) { this.srcArgs.Surface.Scan0.AllowWrites = false; } try { this.threadInitialized.Set(); this.effect.SetRenderInfo(this.effectTokenCopy, this.dstArgs, this.srcArgs); RendererContext context = new RendererContext(this); if (this.threadShouldStop) { this.effect.SignalCancelRequest(); } else if (this.tileCount > 0) { context.RenderNextTile(this.effectTokenCopy); } WaitCallback rcwc = new WaitCallback(context.RenderNextTileProc); for (int i = 0; i < this.tileCount; i++) { if (this.threadShouldStop) { this.effect.SignalCancelRequest(); break; } EffectConfigToken token = (this.effectTokenCopy == null) ? null : this.effectTokenCopy.CloneT <EffectConfigToken>(); this.threadPool.Enqueue(() => rcwc(token)); } this.threadPool.Join(); } catch (Exception exception) { this.exceptions.Add(exception); } finally { EffectRendererWorkItemQueue threadPool = this.threadPool; if (!this.disposed && (threadPool != null)) { try { threadPool.Join(); } catch (Exception) { } } this.OnFinishedRendering(); RenderArgs srcArgs = this.srcArgs; if (srcArgs != null) { Surface surface = srcArgs.Surface; if (surface != null) { MemoryBlock block = surface.Scan0; if (((block != null) && !this.disposed) && block.MaySetAllowWrites) { try { block.AllowWrites = true; } catch (ObjectDisposedException) { } } } } } }
private void InitializeStreamReaders( ref MemoryBlock metadataRoot, StreamHeader[] streamHeaders, out MetadataStreamKind metadataStreamKind, out MemoryBlock metadataTableStream, out MemoryBlock standalonePdbStream) { metadataTableStream = default(MemoryBlock); standalonePdbStream = default(MemoryBlock); metadataStreamKind = MetadataStreamKind.Illegal; foreach (StreamHeader streamHeader in streamHeaders) { switch (streamHeader.Name) { case COR20Constants.StringStreamName: if (metadataRoot.Length < streamHeader.Offset + streamHeader.Size) { throw new BadImageFormatException("NotEnoughSpaceForStringStream"); } break; case COR20Constants.BlobStreamName: if (metadataRoot.Length < streamHeader.Offset + streamHeader.Size) { throw new BadImageFormatException("NotEnoughSpaceForBlobStream"); } this.BlobHeap = new BlobHeap(metadataRoot.GetMemoryBlockAt((int)streamHeader.Offset, streamHeader.Size), _metadataKind); break; case COR20Constants.GUIDStreamName: if (metadataRoot.Length < streamHeader.Offset + streamHeader.Size) { throw new BadImageFormatException("NotEnoughSpaceForGUIDStream"); } break; case COR20Constants.UserStringStreamName: if (metadataRoot.Length < streamHeader.Offset + streamHeader.Size) { throw new BadImageFormatException("NotEnoughSpaceForBlobStream"); } break; case COR20Constants.CompressedMetadataTableStreamName: if (metadataRoot.Length < streamHeader.Offset + streamHeader.Size) { throw new BadImageFormatException("NotEnoughSpaceForMetadataStream"); } metadataStreamKind = MetadataStreamKind.Compressed; metadataTableStream = metadataRoot.GetMemoryBlockAt((int)streamHeader.Offset, streamHeader.Size); break; case COR20Constants.UncompressedMetadataTableStreamName: if (metadataRoot.Length < streamHeader.Offset + streamHeader.Size) { throw new BadImageFormatException("NotEnoughSpaceForMetadataStream"); } metadataStreamKind = MetadataStreamKind.Uncompressed; metadataTableStream = metadataRoot.GetMemoryBlockAt((int)streamHeader.Offset, streamHeader.Size); break; case COR20Constants.MinimalDeltaMetadataTableStreamName: if (metadataRoot.Length < streamHeader.Offset + streamHeader.Size) { throw new BadImageFormatException("NotEnoughSpaceForMetadataStream"); } // the content of the stream is ignored this.IsMinimalDelta = true; break; case COR20Constants.StandalonePdbStreamName: if (metadataRoot.Length < streamHeader.Offset + streamHeader.Size) { throw new BadImageFormatException("NotEnoughSpaceForMetadataStream"); } standalonePdbStream = metadataRoot.GetMemoryBlockAt((int)streamHeader.Offset, streamHeader.Size); break; default: // Skip unknown streams. Some obfuscators insert invalid streams. continue; } } if (IsMinimalDelta && metadataStreamKind != MetadataStreamKind.Uncompressed) { throw new BadImageFormatException("InvalidMetadataStreamFormat"); } }
private static MemoryBlock ReadHexFile(IEnumerable <string> hexRecordLines, int memorySize) { var result = new MemoryBlock(memorySize); var baseAddress = 0; var encounteredEndOfFile = false; foreach (var hexRecordLine in hexRecordLines) { var hexRecord = HexFileLineParser.ParseLine(hexRecordLine); switch (hexRecord.RecordType) { case RecordType.Data: { var nextAddress = hexRecord.Address + baseAddress; for (var i = 0; i < hexRecord.ByteCount; i++) { if (nextAddress + i > memorySize) { throw new IOException( string.Format("Trying to write to position {0} outside of memory boundaries ({1})!", nextAddress + i, memorySize)); } var cell = result.Cells[nextAddress + i]; cell.Value = hexRecord.Bytes[i]; cell.Modified = true; } break; } case RecordType.EndOfFile: { hexRecord.Assert(rec => rec.Address == 0, "Address should equal zero in EOF."); hexRecord.Assert(rec => rec.ByteCount == 0, "Byte count should be zero in EOF."); hexRecord.Assert(rec => rec.Bytes.Length == 0, "Number of bytes should be zero for EOF."); hexRecord.Assert(rec => rec.CheckSum == 0xff, "Checksum should be 0xff for EOF."); encounteredEndOfFile = true; break; } case RecordType.ExtendedSegmentAddress: { hexRecord.Assert(rec => rec.ByteCount == 2, "Byte count should be 2."); baseAddress = (hexRecord.Bytes[0] << 8 | hexRecord.Bytes[1]) << 4; break; } case RecordType.ExtendedLinearAddress: { hexRecord.Assert(rec => rec.ByteCount == 2, "Byte count should be 2."); baseAddress = (hexRecord.Bytes[0] << 8 | hexRecord.Bytes[1]) << 16; break; } case RecordType.StartSegmentAddress: { hexRecord.Assert(rec => rec.ByteCount == 4, "Byte count should be 4."); hexRecord.Assert(rec => rec.Address == 0, "Address should be zero."); result.CS = (ushort)(hexRecord.Bytes[0] << 8 + hexRecord.Bytes[1]); result.IP = (ushort)(hexRecord.Bytes[2] << 8 + hexRecord.Bytes[3]); break; } case RecordType.StartLinearAddress: hexRecord.Assert(rec => rec.ByteCount == 4, "Byte count should be 4."); hexRecord.Assert(rec => rec.Address == 0, "Address should be zero."); result.EIP = (uint)(hexRecord.Bytes[0] << 24) + (uint)(hexRecord.Bytes[1] << 16) + (uint)(hexRecord.Bytes[2] << 8) + hexRecord.Bytes[3]; break; } } if (!encounteredEndOfFile) { throw new IOException("No EndOfFile marker found!"); } return(result); }
/// <summary> /// /// </summary> /// <typeparam name="T"></typeparam> /// <param name="source"></param> /// <param name="sourceAddr"></param> /// <param name="target"></param> /// <param name="targetAddr"></param> /// <param name="size"></param> /// <returns></returns> protected override long Compress <T>(MarshalMemoryBlock source, long sourceAddr, MarshalMemoryBlock target, long targetAddr, long size) { var count = (int)(size - this.QulityOffset); var tims = source.ReadUShorts(sourceAddr, (int)count); if (mMarshalMemory == null) { mMarshalMemory = new MemoryBlock(count * 10); } if (mVarintMemory == null) { mVarintMemory = new VarintCodeMemory(count * 10); } Queue <int> emptys = GetEmpityTimers(tims); Queue <int> usedIndex; long rsize = 0; if (typeof(T) == typeof(byte)) { var cval = CompressValues <byte>(source, count * 2 + sourceAddr, count, emptys, tims, out usedIndex); target.WriteUShort(targetAddr, (ushort)usedIndex.Count); rsize += 2; var cqus = CompressQulitys(source, count * 3 + sourceAddr, count, new Queue <int>(usedIndex)); var timeData = CompressTimers(tims, usedIndex); target.Write((int)timeData.Length); target.Write(timeData); rsize += 4; rsize += timeData.Length; target.Write(cval.Length); target.Write(cval); rsize += 4; rsize += cval.Length; target.Write(cqus.Length); target.Write(cqus); rsize += 4; rsize += cqus.Length; } else if (typeof(T) == typeof(short)) { var res = CompressValues <short>(source, count * 2 + sourceAddr, count, emptys, tims, out usedIndex); target.WriteUShort(targetAddr, (ushort)usedIndex.Count); rsize += 2; var cqus = CompressQulitys(source, count * 4 + sourceAddr, count, new Queue <int>(usedIndex)); var timeData = CompressTimers(tims, usedIndex); target.Write((int)timeData.Length); target.Write(timeData); rsize += 4; rsize += timeData.Length; target.Write(res.Length); target.Write(res); rsize += 4; rsize += res.Length; target.Write(cqus.Length); target.Write(cqus); rsize += 4; rsize += cqus.Length; } else if (typeof(T) == typeof(ushort)) { var res = CompressValues <ushort>(source, count * 2 + sourceAddr, count, emptys, tims, out usedIndex); target.WriteUShort(targetAddr, (ushort)usedIndex.Count); rsize += 2; var cqus = CompressQulitys(source, count * 4 + sourceAddr, count, new Queue <int>(usedIndex)); var timeData = CompressTimers(tims, usedIndex); target.Write((int)timeData.Length); target.Write(timeData); rsize += 4; rsize += timeData.Length; target.Write(res.Length); target.Write(res); rsize += 4; rsize += res.Length; target.Write(cqus.Length); target.Write(cqus); rsize += 4; rsize += cqus.Length; } else if (typeof(T) == typeof(int)) { var res = CompressValues <int>(source, count * 2 + sourceAddr, count, emptys, tims, out usedIndex); target.WriteUShort(targetAddr, (ushort)usedIndex.Count); rsize += 2; var cqus = CompressQulitys(source, count * 6 + sourceAddr, count, new Queue <int>(usedIndex)); var timeData = CompressTimers(tims, usedIndex); target.Write((int)timeData.Length); target.Write(timeData); rsize += 4; rsize += timeData.Length; target.Write(res.Length); target.Write(res); rsize += 4; rsize += res.Length; target.Write(cqus.Length); target.Write(cqus); rsize += 4; rsize += cqus.Length; } else if (typeof(T) == typeof(uint)) { var res = CompressValues <uint>(source, count * 2 + sourceAddr, count, emptys, tims, out usedIndex); target.WriteUShort(targetAddr, (ushort)usedIndex.Count); rsize += 2; var cqus = CompressQulitys(source, count * 6 + sourceAddr, count, new Queue <int>(usedIndex)); var timeData = CompressTimers(tims, usedIndex); target.Write((int)timeData.Length); target.Write(timeData); rsize += 4; rsize += timeData.Length; target.Write(res.Length); target.Write(res); rsize += 4; rsize += res.Length; target.Write(cqus.Length); target.Write(cqus); rsize += 4; rsize += cqus.Length; } else if (typeof(T) == typeof(long)) { var res = CompressValues <long>(source, count * 2 + sourceAddr, count, emptys, tims, out usedIndex); target.WriteUShort(targetAddr, (ushort)usedIndex.Count); rsize += 2; var cqus = CompressQulitys(source, count * 10 + sourceAddr, count, new Queue <int>(usedIndex)); var timeData = CompressTimers(tims, usedIndex); target.Write((int)timeData.Length); target.Write(timeData); rsize += 4; rsize += timeData.Length; target.Write(res.Length); target.Write(res); rsize += 4; rsize += res.Length; target.Write(cqus.Length); target.Write(cqus); rsize += 4; rsize += cqus.Length; } else if (typeof(T) == typeof(ulong)) { var res = CompressValues <ulong>(source, count * 2 + sourceAddr, count, emptys, tims, out usedIndex); target.WriteUShort(targetAddr, (ushort)usedIndex.Count); rsize += 2; var cqus = CompressQulitys(source, count * 10 + sourceAddr, count, new Queue <int>(usedIndex)); var timeData = CompressTimers(tims, usedIndex); target.Write((int)timeData.Length); target.Write(timeData); rsize += 4; rsize += timeData.Length; target.Write(res.Length); target.Write(res); rsize += 4; rsize += res.Length; target.Write(cqus.Length); target.Write(cqus); rsize += 4; rsize += cqus.Length; } else if (typeof(T) == typeof(double)) { var res = CompressValues <double>(source, count * 2 + sourceAddr, count, emptys, tims, out usedIndex); target.WriteUShort(targetAddr, (ushort)usedIndex.Count); rsize += 2; var cqus = CompressQulitys(source, count * 10 + sourceAddr, count, new Queue <int>(usedIndex)); var timeData = CompressTimers(tims, usedIndex); target.Write((int)timeData.Length); target.Write(timeData); rsize += 4; rsize += timeData.Length; target.Write(res.Length); target.Write(res); rsize += 4; rsize += res.Length; target.Write(cqus.Length); target.Write(cqus); rsize += 4; rsize += cqus.Length; } else if (typeof(T) == typeof(float)) { var res = CompressValues <float>(source, count * 2 + sourceAddr, count, emptys, tims, out usedIndex); target.WriteUShort(targetAddr, (ushort)usedIndex.Count); rsize += 2; var cqus = CompressQulitys(source, count * 6 + sourceAddr, count, new Queue <int>(usedIndex)); var timeData = CompressTimers(tims, usedIndex); target.Write((int)timeData.Length); target.Write(timeData); rsize += 4; rsize += timeData.Length; target.Write(res.Length); target.Write(res); rsize += 4; rsize += res.Length; target.Write(cqus.Length); target.Write(cqus); rsize += 4; rsize += cqus.Length; } return(rsize); }
public void ShouldHaveRequestedSize() { MemoryBlock block = new MemoryBlock(1024); Assert.That(block.Size, Is.EqualTo(1024)); }
public Switch(VirtualFileSystem fileSystem, ContentManager contentManager, UserChannelPersistence userChannelPersistence, IRenderer renderer, IAalOutput audioOut) { if (renderer == null) { throw new ArgumentNullException(nameof(renderer)); } if (audioOut == null) { throw new ArgumentNullException(nameof(audioOut)); } if (userChannelPersistence == null) { throw new ArgumentNullException(nameof(userChannelPersistence)); } UserChannelPersistence = userChannelPersistence; AudioOut = audioOut; Memory = new MemoryBlock(1UL << 32); Gpu = new GpuContext(renderer); MemoryAllocator = new NvMemoryAllocator(); Host1x = new Host1xDevice(Gpu.Synchronization); var nvdec = new NvdecDevice(Gpu.MemoryManager); var vic = new VicDevice(Gpu.MemoryManager); Host1x.RegisterDevice(ClassId.Nvdec, nvdec); Host1x.RegisterDevice(ClassId.Vic, vic); nvdec.FrameDecoded += (FrameDecodedEventArgs e) => { // FIXME: // Figure out what is causing frame ordering issues on H264. // For now this is needed as workaround. if (e.CodecId == CodecId.H264) { vic.SetSurfaceOverride(e.LumaOffset, e.ChromaOffset, 0); } else { vic.DisableSurfaceOverride(); } }; FileSystem = fileSystem; System = new Horizon(this, contentManager); System.InitializeServices(); Statistics = new PerformanceStatistics(); Hid = new Hid(this, System.HidBaseAddress); Hid.InitDevices(); Application = new ApplicationLoader(this, fileSystem, contentManager); }
public PeWrapper(string moduleName, byte[] fileData, ulong destAddress) { ModuleName = moduleName; _pe = new PeFile(fileData); Size = _pe.ImageNtHeaders.OptionalHeader.SizeOfImage; Start = destAddress; if (Size < _pe.ImageSectionHeaders.Max(s => (ulong)s.VirtualSize + s.VirtualAddress)) { throw new InvalidOperationException("Image not Big Enough"); } _fileHash = WaterboxUtils.Hash(fileData); foreach (var s in _pe.ImageSectionHeaders) { ulong start = Start + s.VirtualAddress; ulong length = s.VirtualSize; MemoryBlock.Protection prot; var r = (s.Characteristics & (uint)Constants.SectionFlags.IMAGE_SCN_MEM_READ) != 0; var w = (s.Characteristics & (uint)Constants.SectionFlags.IMAGE_SCN_MEM_WRITE) != 0; var x = (s.Characteristics & (uint)Constants.SectionFlags.IMAGE_SCN_MEM_EXECUTE) != 0; if (w && x) { throw new InvalidOperationException("Write and Execute not allowed"); } prot = x ? MemoryBlock.Protection.RX : w ? MemoryBlock.Protection.RW : MemoryBlock.Protection.R; var section = new Section { // chop off possible null padding from name Name = Encoding.ASCII.GetString(s.Name, 0, (s.Name.Select((v, i) => new { v, i }).FirstOrDefault(a => a.v == 0) ?? new { v = (byte)0, i = s.Name.Length }).i), Start = start, Size = length, SavedSize = WaterboxUtils.AlignUp(length), R = r, W = w, X = x, Prot = prot, DiskStart = s.PointerToRawData, DiskSize = s.SizeOfRawData }; _sections.Add(section); _sectionsByName.Add(section.Name, section); } _sectionsByName.TryGetValue(".idata", out _imports); _sectionsByName.TryGetValue(".sealed", out _sealed); _sectionsByName.TryGetValue(".invis", out _invisible); // OK, NOW MOUNT LoadOffset = (long)Start - (long)_pe.ImageNtHeaders.OptionalHeader.ImageBase; Memory = new MemoryBlock(Start, Size); Memory.Activate(); Memory.Protect(Start, Size, MemoryBlock.Protection.RW); // copy headers Marshal.Copy(fileData, 0, Z.US(Start), (int)_pe.ImageNtHeaders.OptionalHeader.SizeOfHeaders); // copy sections foreach (var s in _sections) { ulong datalength = Math.Min(s.Size, s.DiskSize); Marshal.Copy(fileData, (int)s.DiskStart, Z.US(s.Start), (int)datalength); WaterboxUtils.ZeroMemory(Z.US(s.Start + datalength), (long)(s.SavedSize - datalength)); } // apply relocations var n32 = 0; var n64 = 0; foreach (var rel in _pe.ImageRelocationDirectory) { foreach (var to in rel.TypeOffsets) { ulong address = Start + rel.VirtualAddress + to.Offset; switch (to.Type) { // there are many other types of relocation specified, // but the only that are used is 0 (does nothing), 3 (32 bit standard), 10 (64 bit standard) case 3: // IMAGE_REL_BASED_HIGHLOW { byte[] tmp = new byte[4]; Marshal.Copy(Z.US(address), tmp, 0, 4); uint val = BitConverter.ToUInt32(tmp, 0); tmp = BitConverter.GetBytes((uint)(val + LoadOffset)); Marshal.Copy(tmp, 0, Z.US(address), 4); n32++; break; } case 10: // IMAGE_REL_BASED_DIR64 { byte[] tmp = new byte[8]; Marshal.Copy(Z.US(address), tmp, 0, 8); long val = BitConverter.ToInt64(tmp, 0); tmp = BitConverter.GetBytes(val + LoadOffset); Marshal.Copy(tmp, 0, Z.US(address), 8); n64++; break; } } } } if (IntPtr.Size == 8 && n32 > 0) { // check mcmodel, etc throw new InvalidOperationException("32 bit relocations found in 64 bit dll! This will fail."); } Console.WriteLine($"Processed {n32} 32 bit and {n64} 64 bit relocations"); ProtectMemory(); // publish exports EntryPoint = Z.US(Start + _pe.ImageNtHeaders.OptionalHeader.AddressOfEntryPoint); foreach (var export in _pe.ExportedFunctions) { if (export.Name != null) { ExportsByName.Add(export.Name, Z.US(Start + export.Address)); } ExportsByOrdinal.Add(export.Ordinal, Z.US(Start + export.Address)); } // collect information about imports // NB: Hints are not the same as Ordinals foreach (var import in _pe.ImportedFunctions) { Dictionary <string, IntPtr> module; if (!ImportsByModule.TryGetValue(import.DLL, out module)) { module = new Dictionary <string, IntPtr>(); ImportsByModule.Add(import.DLL, module); } var dest = Start + import.Thunk; if (_imports == null || dest >= _imports.Start + _imports.Size || dest < _imports.Start) { throw new InvalidOperationException("Import record outside of .idata!"); } module.Add(import.Name, Z.US(dest)); } Section midipix; if (_sectionsByName.TryGetValue(".midipix", out midipix)) { var dataOffset = midipix.DiskStart; CtorList = Z.SS(BitConverter.ToInt64(fileData, (int)(dataOffset + 0x30)) + LoadOffset); DtorList = Z.SS(BitConverter.ToInt64(fileData, (int)(dataOffset + 0x38)) + LoadOffset); } Console.WriteLine($"Mounted `{ModuleName}` @{Start:x16}"); foreach (var s in _sections.OrderBy(s => s.Start)) { Console.WriteLine(" @{0:x16} {1}{2}{3} `{4}` {5} bytes", s.Start, s.R ? "R" : " ", s.W ? "W" : " ", s.X ? "X" : " ", s.Name, s.Size); } Console.WriteLine("GDB Symbol Load:"); var symload = $"add-sym {ModuleName} {_sectionsByName[".text"].Start}"; if (_sectionsByName.ContainsKey(".data")) { symload += $" -s .data {_sectionsByName[".data"].Start}"; } if (_sectionsByName.ContainsKey(".bss")) { symload += $" -s .bss {_sectionsByName[".bss"].Start}"; } Console.WriteLine(symload); }
/// <summary>Loads a bootstrap ROM with the specified data.</summary> /// <remarks>Data integrity will be checked to ensure a correct bootstrap ROM gets loaded.</remarks> /// <param name="hardwareType">Hardware whose bootstrap ROM should be loaded.</param> /// <param name="data">Data of the specified bootstrap ROM.</param> /// <exception cref="ArgumentOutOfRangeException">The value provided for harware type is not a valid one.</exception> /// <exception cref="NotSupportedException">Loading the bootstrap ROM the specified hardware is not supported.</exception> /// <exception cref="InvalidDataException">Data integrity check failed.</exception> public unsafe void LoadBootRom(HardwareType hardwareType, byte[] data) { if (data == null) { throw new ArgumentNullException(); } if (!Enum.IsDefined(typeof(HardwareType), hardwareType)) { throw new ArgumentOutOfRangeException(); } byte[] referenceHash; int requestedLength; byte * destination; // I finally found a use for C# undocumented keywords… Yeah ! // (There are other ways to do this if really needed, but in fact it feels kinda cleaner to use this rather than another switch statement here…) TypedReference romLoadedField; switch (hardwareType) { case HardwareType.GameBoy: requestedLength = 0x100; referenceHash = dmgRomHash; destination = dmgBootMemory; romLoadedField = __makeref(dmgBootRomLoaded); break; case HardwareType.SuperGameBoy: requestedLength = 0x100; referenceHash = sgbRomHash; destination = sgbBootMemory; romLoadedField = __makeref(sgbBootRomLoaded); break; case HardwareType.GameBoyColor: // Trim the GBC rom if needed (we don't need the "decorative" empty sapce) if (data.Length == 0x900) { byte[] tempData = new byte[0x800]; Buffer.BlockCopy(data, 0, tempData, 0, 0x100); Buffer.BlockCopy(data, 0x200, tempData, 0x100, 0x700); data = tempData; } requestedLength = 0x800; referenceHash = cgbRomHash; destination = cgbBootMemory; romLoadedField = __makeref(cgbBootRomLoaded); break; default: throw new NotSupportedException(); } var md5 = MD5.Create(); if (data.Length != requestedLength || !Equals(md5.ComputeHash(data), referenceHash)) { throw new InvalidDataException(); fixed(byte *dataPointer = data) MemoryBlock.Copy((void *)destination, (void *)dataPointer, requestedLength); __refvalue(romLoadedField, bool) = true; }
public ElfLoader(string moduleName, byte[] fileData, ulong assumedStart, bool skipCoreConsistencyCheck, bool skipMemoryConsistencyCheck) { ModuleName = moduleName; _skipCoreConsistencyCheck = skipCoreConsistencyCheck; _skipMemoryConsistencyCheck = skipMemoryConsistencyCheck; _elfHash = WaterboxUtils.Hash(fileData); _elf = ELFReader.Load <ulong>(new MemoryStream(fileData, false), true); var loadsegs = _elf.Segments.Where(s => s.Type == SegmentType.Load); var start = loadsegs.Min(s => s.Address); start = WaterboxUtils.AlignDown(start); var end = loadsegs.Max(s => s.Address + s.Size); end = WaterboxUtils.AlignUp(end); var size = end - start; if (start != assumedStart) { throw new InvalidOperationException($"{nameof(assumedStart)} did not match actual origin in elf file"); } if (_elf.Sections.Any(s => s.Name.StartsWith(".rel"))) { throw new InvalidOperationException("Elf has relocations!"); } _allSymbols = ((ISymbolTable)_elf.GetSection(".symtab")) .Entries .Cast <SymbolEntry <ulong> >() .ToList(); _sectionsByName = _elf.Sections .ToDictionary(s => s.Name); _sectionsByName.TryGetValue(".wbxsyscall", out _imports); if (_imports == null) { // Likely cause: This is a valid elf file, but it was not compiled by our toolchain at all throw new InvalidOperationException("Missing .wbxsyscall section!"); } _sectionsByName.TryGetValue(".sealed", out _sealed); _sectionsByName.TryGetValue(".invis", out _invisible); _visibleSymbols = _allSymbols .Where(s => s.Binding == SymbolBinding.Global && s.Visibility == SymbolVisibility.Default) .ToDictionary(s => s.Name); _importSymbols = _allSymbols // TODO: No matter what attributes I provide, I seem to end up with Local and/or Hidden symbols in // .wbxsyscall a lot of the time on heavily optimized release builds. // Fortunately, there's nothing else in .wbxsyscall so we can just not filter at all. .Where(s => s.PointedSection == _imports) .ToList(); Memory = MemoryBlock.Create(start, size); Memory.Activate(); Memory.Protect(Memory.Start, Memory.Size, MemoryBlock.Protection.RW); foreach (var seg in loadsegs) { var data = seg.GetFileContents(); Marshal.Copy(data, 0, Z.US(seg.Address), Math.Min((int)seg.Size, (int)seg.FileSize)); } { // Compute RW boundaries var allocated = _elf.Sections .Where(s => (s.Flags & SectionFlags.Allocatable) != 0); var writable = allocated .Where(s => (s.Flags & SectionFlags.Writable) != 0); var postSealWritable = writable .Where(s => !IsSpecialReadonlySection(s)); var saveable = postSealWritable .Where(s => s != _invisible); var executable = allocated .Where(s => (s.Flags & SectionFlags.Executable) != 0); _writeStart = WaterboxUtils.AlignDown(writable.Min(s => s.LoadAddress)); _postSealWriteStart = WaterboxUtils.AlignDown(postSealWritable.Min(s => s.LoadAddress)); _execEnd = WaterboxUtils.AlignUp(executable.Max(s => s.LoadAddress + s.Size)); // validate; this may require linkscript cooperation // due to the segment limitations, the only thing we'd expect to catch is a custom eventually readonly section // in the wrong place (because the linkscript doesn't know "eventually readonly") if (_execEnd > _writeStart) { throw new InvalidOperationException($"ElfLoader: Executable data to {_execEnd:X16} overlaps writable data from {_writeStart}"); } } PrintSections(); PrintGdbData(); PrintTopSavableSymbols(); Protect(); }
public FISRegisterH2D(uint aAddress) { xAddress = aAddress; xBlock = new MemoryBlock(aAddress, 20); xBlock.Fill(0); }
public ElfRunner(string filename, long heapsize, long sealedheapsize, long invisibleheapsize) { using (var fs = new FileStream(filename, FileMode.Open, FileAccess.Read)) { _elfhash = WaterboxUtils.Hash(fs); } // todo: hack up this baby to take Streams _elf = ELFReader.Load <long>(filename); var loadsegs = _elf.Segments.Where(s => s.Type == SegmentType.Load); long orig_start = loadsegs.Min(s => s.Address); orig_start &= ~(Environment.SystemPageSize - 1); long orig_end = loadsegs.Max(s => s.Address + s.Size); if (HasRelocations()) { _base = new MemoryBlock((ulong)(orig_end - orig_start)); _loadoffset = (long)_base.Start - orig_start; Initialize(0); } else { Initialize((ulong)orig_start); _base = new MemoryBlock((ulong)orig_start, (ulong)(orig_end - orig_start)); _loadoffset = 0; Enter(); } try { _disposeList.Add(_base); AddMemoryBlock(_base, "elf"); _base.Activate(); _base.Protect(_base.Start, _base.Size, MemoryBlock.Protection.RW); foreach (var seg in loadsegs) { var data = seg.GetContents(); Marshal.Copy(data, 0, Z.SS(seg.Address + _loadoffset), data.Length); } RegisterSymbols(); ProcessRelocations(); _base.Protect(_base.Start, _base.Size, MemoryBlock.Protection.R); foreach (var sec in _elf.Sections.Where(s => (s.Flags & SectionFlags.Allocatable) != 0)) { if ((sec.Flags & SectionFlags.Executable) != 0) { _base.Protect((ulong)(sec.LoadAddress + _loadoffset), (ulong)sec.Size, MemoryBlock.Protection.RX); } else if ((sec.Flags & SectionFlags.Writable) != 0) { _base.Protect((ulong)(sec.LoadAddress + _loadoffset), (ulong)sec.Size, MemoryBlock.Protection.RW); } } ulong end = _base.End; if (heapsize > 0) { _heap = new Heap(GetHeapStart(end), (ulong)heapsize, "sbrk-heap"); _heap.Memory.Activate(); end = _heap.Memory.End; _disposeList.Add(_heap); AddMemoryBlock(_heap.Memory, "sbrk - heap"); } if (sealedheapsize > 0) { _sealedheap = new Heap(GetHeapStart(end), (ulong)sealedheapsize, "sealed-heap"); _sealedheap.Memory.Activate(); end = _sealedheap.Memory.End; _disposeList.Add(_sealedheap); AddMemoryBlock(_sealedheap.Memory, "sealed-heap"); } if (invisibleheapsize > 0) { _invisibleheap = new Heap(GetHeapStart(end), (ulong)invisibleheapsize, "invisible-heap"); _invisibleheap.Memory.Activate(); end = _invisibleheap.Memory.End; _disposeList.Add(_invisibleheap); AddMemoryBlock(_invisibleheap.Memory, "invisible-heap"); } ConnectAllClibPatches(); Console.WriteLine("Loaded {0}@{1:X16}", filename, _base.Start); foreach (var sec in _elf.Sections.Where(s => s.LoadAddress != 0)) { Console.WriteLine(" {0}@{1:X16}, size {2}", sec.Name.PadLeft(20), sec.LoadAddress + _loadoffset, sec.Size.ToString().PadLeft(12)); } PrintTopSavableSymbols(); } catch { Dispose(); throw; } finally { Exit(); } }
public static unsafe int Disassemble(MemoryBlock memoryBlock, int offset, out string instruction) { byte* pMemory = (byte*)memoryBlock.Pointer; byte opcode1, opcode2 = 0x00, opcode3 = 0x00; string opcode2String = null, opcode3String = null, register; int extraByteCount; instruction = ""; if (offset >= memoryBlock.Length) return 0; opcode1 = pMemory[offset++]; extraByteCount = GetInstructionExtraSize(opcode1); if (offset + extraByteCount > memoryBlock.Length) { instruction = "DB $" + opcode1.ToString("X2"); return 1; } if (extraByteCount >= 1) { opcode2 = pMemory[offset++]; if (opcode1 != 0xCB) opcode2String = opcode2.ToString("X2"); } if (extraByteCount >= 2) { opcode3 = pMemory[offset++]; opcode3String = opcode3.ToString("X2"); } switch (opcode1) { case 0x00: instruction = "NOP"; break; case 0x07: instruction = "RLCA"; break; case 0x0F: instruction = "RRCA"; break; case 0x17: instruction = "RLA"; break; case 0x1F: instruction = "RRA"; break; case 0x10: instruction = "STOP"; break; case 0x18: instruction = "JR\t$" + opcode2String + "\t[" + (offset + (sbyte)opcode2).ToString("X4") + "]"; break; case 0x22: instruction = "LDI\t(HL),A"; break; case 0x2A: instruction = "LDI\tA,(HL)"; break; case 0x32: instruction = "LDD\t(HL),A"; break; case 0x3A: instruction = "LDD\tA,(HL)"; break; case 0x27: instruction = "DAA"; break; case 0x2F: instruction = "CPL"; break; case 0x37: instruction = "SCF"; break; case 0x3F: instruction = "CCF"; break; case 0x76: instruction = "HALT"; break; case 0xC9: instruction = "RET"; break; case 0xD9: instruction = "RETI"; break; case 0xC3: instruction = "JP\t$" + opcode3String + opcode2String; break; case 0xCD: instruction = "CALL\t$" + opcode3String + opcode2String; break; case 0xE8: instruction = "ADD\tSP,$" + opcode2String; break; case 0xF8: instruction = "LD\t(HL),SP+$" + opcode2String; break; case 0xE0: instruction = "LD\t($FF" + opcode2String + "),A"; break; case 0xF0: instruction = "LD\tA,($FF" + opcode2String + ")"; break; case 0xE2: instruction = "LD\t(C),A"; break; case 0xF2: instruction = "LD\tA,(C)"; break; case 0xEA: instruction = "LD\t($" + opcode3String + opcode2String + "),A"; break; case 0xFA: instruction = "LD\tA,($" + opcode3String + opcode2String + ")"; break; case 0xE9: instruction = "JP\tHL"; break; case 0xF9: instruction = "LD\tSP,HL"; break; case 0xF3: instruction = "DI"; break; case 0xFB: instruction = "EI"; break; case 0xCB: if ((opcode2 & 0xC0) == 0) { switch ((opcode2 >> 3) & 0x7) { case 0: instruction = "RLC\t"; break; case 1: instruction = "RRC\t"; break; case 2: instruction = "RL\t"; break; case 3: instruction = "RR\t"; break; case 4: instruction = "SLA\t"; break; case 5: instruction = "SRA\t"; break; case 6: instruction = "SWAP\t"; break; case 7: instruction = "SRL\t"; break; } } else { switch (opcode2 >> 6) { case 1: instruction = "BIT\t"; break; case 2: instruction = "SET\t"; break; case 3: instruction = "RES\t"; break; } instruction += ((opcode2 >> 3) & 0x7).ToString() + ","; } instruction += destinations[opcode2 & 0x7]; break; default: if ((opcode1 & 0xC4) == 0 && (opcode1 & 3) != 0) { register = registers[opcode1 >> 4]; // We know that (opcode1 & 0xC0) == 0 switch (opcode1 & 0x0F) { case 0x01: instruction = "LD\t" + register + ",$" + opcode3String + opcode2String; break; case 0x09: instruction = "ADD\tHL," + register; break; case 0x02: instruction = "LD\t(" + register + "),A"; break; case 0x0A: instruction = "LD\tA,(" + register + ")"; break; case 0x03: instruction = "INC\t" + register; break; case 0x0B: instruction = "DEC\t" + register; break; } } else if ((opcode1 & 0xC4) == 0x04) { register = destinations[opcode1 >> 3]; // We still know that (opcode1 & 0xC0) == 0 if ((opcode1 & 0x02) == 0x02) // LD D,N instruction = "LD\t" + register + ",$" + opcode2String; else instruction = incdec[opcode1 & 0x01] + register; } else if ((opcode1 & 0xC0) == 0x40) // LD D,D (HALT opcode already checked) instruction = "LD\t" + destinations[(opcode1 >> 3) & 0x7] + "," + destinations[opcode1 & 0x7]; else if ((opcode1 & 0xC0) == 0x80) // ALU A,D instruction = alu[(opcode1 >> 3) & 0x7] + "\t" + "A," + destinations[opcode1 & 0x7]; else if ((opcode1 & 0xC7) == 0xC6) // ALU A,N instruction = alu[(opcode1 >> 3) & 0x7] + "\t" + "A,$" + opcode2String; else if ((opcode1 & 0xCB) == 0xC1) // PUSH R / POP R { register = registers[(opcode1 >> 4) & 0x3]; instruction = pushpop[(opcode1 >> 2) & 0x1] + register; } else if ((opcode1 & 0xC7) == 0xC7) // RST N instruction = "RST\t$" + (opcode1 & 0x38).ToString("X2"); else if ((opcode1 & 0xE7) == 0x20) // JR F,N instruction = "JR\t" + flags[(opcode1 >> 3) & 0x3] + ",$" + opcode2String + " [" + (offset + (sbyte)opcode2).ToString("X4") + "]"; else if ((opcode1 & 0xE1) == 0xC0) // Other conditional jumps { register = flags[(opcode1 >> 3) & 0x3]; switch (opcode1 & 0x3) { case 0x00: instruction = "RET\t"; break; case 0x02: instruction = "JP\t"; break; case 0x04: instruction = "CALL\t"; break; } if ((opcode1 & 0xE7) == 0xC0) // RET instruction += register; else instruction += register + ",$" + opcode3String + opcode2String; } else instruction = "DB $" + opcode1.ToString("X2"); break; } return 1 + extraByteCount; }
internal StringHeap(MemoryBlock block, MetadataKind metadataKind) { _lazyVirtualHeap = null; if (s_virtualValues == null && metadataKind != MetadataKind.Ecma335) { // Note: // Virtual values shall not contain surrogates, otherwise StartsWith might be inconsistent // when comparing to a text that ends with a high surrogate. var values = new string[(int)StringHandle.VirtualIndex.Count]; values[(int)StringHandle.VirtualIndex.System_Runtime_WindowsRuntime] = "System.Runtime.WindowsRuntime"; values[(int)StringHandle.VirtualIndex.System_Runtime] = "System.Runtime"; values[(int)StringHandle.VirtualIndex.System_ObjectModel] = "System.ObjectModel"; values[(int)StringHandle.VirtualIndex.System_Runtime_WindowsRuntime_UI_Xaml] = "System.Runtime.WindowsRuntime.UI.Xaml"; values[(int)StringHandle.VirtualIndex.System_Runtime_InteropServices_WindowsRuntime] = "System.Runtime.InteropServices.WindowsRuntime"; values[(int)StringHandle.VirtualIndex.System_Numerics_Vectors] = "System.Numerics.Vectors"; values[(int)StringHandle.VirtualIndex.Dispose] = "Dispose"; values[(int)StringHandle.VirtualIndex.AttributeTargets] = "AttributeTargets"; values[(int)StringHandle.VirtualIndex.AttributeUsageAttribute] = "AttributeUsageAttribute"; values[(int)StringHandle.VirtualIndex.Color] = "Color"; values[(int)StringHandle.VirtualIndex.CornerRadius] = "CornerRadius"; values[(int)StringHandle.VirtualIndex.DateTimeOffset] = "DateTimeOffset"; values[(int)StringHandle.VirtualIndex.Duration] = "Duration"; values[(int)StringHandle.VirtualIndex.DurationType] = "DurationType"; values[(int)StringHandle.VirtualIndex.EventHandler1] = "EventHandler`1"; values[(int)StringHandle.VirtualIndex.EventRegistrationToken] = "EventRegistrationToken"; values[(int)StringHandle.VirtualIndex.Exception] = "Exception"; values[(int)StringHandle.VirtualIndex.GeneratorPosition] = "GeneratorPosition"; values[(int)StringHandle.VirtualIndex.GridLength] = "GridLength"; values[(int)StringHandle.VirtualIndex.GridUnitType] = "GridUnitType"; values[(int)StringHandle.VirtualIndex.ICommand] = "ICommand"; values[(int)StringHandle.VirtualIndex.IDictionary2] = "IDictionary`2"; values[(int)StringHandle.VirtualIndex.IDisposable] = "IDisposable"; values[(int)StringHandle.VirtualIndex.IEnumerable] = "IEnumerable"; values[(int)StringHandle.VirtualIndex.IEnumerable1] = "IEnumerable`1"; values[(int)StringHandle.VirtualIndex.IList] = "IList"; values[(int)StringHandle.VirtualIndex.IList1] = "IList`1"; values[(int)StringHandle.VirtualIndex.INotifyCollectionChanged] = "INotifyCollectionChanged"; values[(int)StringHandle.VirtualIndex.INotifyPropertyChanged] = "INotifyPropertyChanged"; values[(int)StringHandle.VirtualIndex.IReadOnlyDictionary2] = "IReadOnlyDictionary`2"; values[(int)StringHandle.VirtualIndex.IReadOnlyList1] = "IReadOnlyList`1"; values[(int)StringHandle.VirtualIndex.KeyTime] = "KeyTime"; values[(int)StringHandle.VirtualIndex.KeyValuePair2] = "KeyValuePair`2"; values[(int)StringHandle.VirtualIndex.Matrix] = "Matrix"; values[(int)StringHandle.VirtualIndex.Matrix3D] = "Matrix3D"; values[(int)StringHandle.VirtualIndex.Matrix3x2] = "Matrix3x2"; values[(int)StringHandle.VirtualIndex.Matrix4x4] = "Matrix4x4"; values[(int)StringHandle.VirtualIndex.NotifyCollectionChangedAction] = "NotifyCollectionChangedAction"; values[(int)StringHandle.VirtualIndex.NotifyCollectionChangedEventArgs] = "NotifyCollectionChangedEventArgs"; values[(int)StringHandle.VirtualIndex.NotifyCollectionChangedEventHandler] = "NotifyCollectionChangedEventHandler"; values[(int)StringHandle.VirtualIndex.Nullable1] = "Nullable`1"; values[(int)StringHandle.VirtualIndex.Plane] = "Plane"; values[(int)StringHandle.VirtualIndex.Point] = "Point"; values[(int)StringHandle.VirtualIndex.PropertyChangedEventArgs] = "PropertyChangedEventArgs"; values[(int)StringHandle.VirtualIndex.PropertyChangedEventHandler] = "PropertyChangedEventHandler"; values[(int)StringHandle.VirtualIndex.Quaternion] = "Quaternion"; values[(int)StringHandle.VirtualIndex.Rect] = "Rect"; values[(int)StringHandle.VirtualIndex.RepeatBehavior] = "RepeatBehavior"; values[(int)StringHandle.VirtualIndex.RepeatBehaviorType] = "RepeatBehaviorType"; values[(int)StringHandle.VirtualIndex.Size] = "Size"; values[(int)StringHandle.VirtualIndex.System] = "System"; values[(int)StringHandle.VirtualIndex.System_Collections] = "System.Collections"; values[(int)StringHandle.VirtualIndex.System_Collections_Generic] = "System.Collections.Generic"; values[(int)StringHandle.VirtualIndex.System_Collections_Specialized] = "System.Collections.Specialized"; values[(int)StringHandle.VirtualIndex.System_ComponentModel] = "System.ComponentModel"; values[(int)StringHandle.VirtualIndex.System_Numerics] = "System.Numerics"; values[(int)StringHandle.VirtualIndex.System_Windows_Input] = "System.Windows.Input"; values[(int)StringHandle.VirtualIndex.Thickness] = "Thickness"; values[(int)StringHandle.VirtualIndex.TimeSpan] = "TimeSpan"; values[(int)StringHandle.VirtualIndex.Type] = "Type"; values[(int)StringHandle.VirtualIndex.Uri] = "Uri"; values[(int)StringHandle.VirtualIndex.Vector2] = "Vector2"; values[(int)StringHandle.VirtualIndex.Vector3] = "Vector3"; values[(int)StringHandle.VirtualIndex.Vector4] = "Vector4"; values[(int)StringHandle.VirtualIndex.Windows_Foundation] = "Windows.Foundation"; values[(int)StringHandle.VirtualIndex.Windows_UI] = "Windows.UI"; values[(int)StringHandle.VirtualIndex.Windows_UI_Xaml] = "Windows.UI.Xaml"; values[(int)StringHandle.VirtualIndex.Windows_UI_Xaml_Controls_Primitives] = "Windows.UI.Xaml.Controls.Primitives"; values[(int)StringHandle.VirtualIndex.Windows_UI_Xaml_Media] = "Windows.UI.Xaml.Media"; values[(int)StringHandle.VirtualIndex.Windows_UI_Xaml_Media_Animation] = "Windows.UI.Xaml.Media.Animation"; values[(int)StringHandle.VirtualIndex.Windows_UI_Xaml_Media_Media3D] = "Windows.UI.Xaml.Media.Media3D"; s_virtualValues = values; AssertFilled(); } this.Block = TrimEnd(block); }
private void LoadFromStream(Stream stream) { blocks = new List <MemoryBlock>(); string line; bool hexFileEOF = false; var currentBlock = new MemoryBlock(); UInt64 currentExtendedAddress = 0; Size = 0; using (var reader = new StreamReader(stream)) { while (((line = reader.ReadLine()) != "") && (hexFileEOF == false)) { HexLine hexLine = ParseLine(line); switch (hexLine.recordType) { case HexRecordType.EOF: hexFileEOF = true; break; case HexRecordType.ExtendedLinearAddress: currentExtendedAddress = Convert.ToUInt64(hexLine.dataPayload, 16) << 16; // Add a new memory block section if // 1: the current block has data (size > 0) // 2: the next block has a different starting address to the current block // 3: the next block address does not already exist in the array. if ((currentBlock.size > 0) && (currentExtendedAddress != currentBlock.startAddress) && (blocks.Count(b => b.startAddress == currentExtendedAddress) == 0)) { blocks.Add(currentBlock); currentBlock = new MemoryBlock(currentExtendedAddress); } break; case HexRecordType.Data: // Calculate the maximum possible address using the given data // Actual maximum is 65536 bytes (2^16). UInt64 size = (ulong)hexLine.recordLength + (ulong)hexLine.addressField; if (size > currentBlock.size) { currentBlock.size = size; } // Assuming each memory block is 65K in size, // load the data buffer with data at the given address uint offset = 0; for (byte j = 0; j < hexLine.recordLength; j++) { uint addr = (uint)hexLine.addressField + j - offset; // Address exceeds the currently allocated data block, // create a new block at the current address if (addr >= currentBlock.data.Length) //65536 { // Limit the block size currentBlock.size = (uint)currentBlock.data.Length; // Split the memory block blocks.Add(currentBlock); currentBlock = new MemoryBlock(addr + currentExtendedAddress); // Wrap the address around into the new block offset = (uint)currentBlock.data.Length; addr -= offset; } currentBlock.data[addr] = Convert.ToByte(hexLine.dataPayload.Substring(j * 2, 2), 16); } // Note that if a data line is missing, the data bytes are simply left as '0' //TODO: are they supposed to be set to 0xFF? break; default: throw new HexFileException(String.Format("Unsupported hex record type '{0}'", hexLine.recordType.ToString())); } } } // Finally add the last block used blocks.Add(currentBlock); Size = 0; foreach (var block in blocks) { Size += block.size; } /*Console.WriteLine("Num blocks: {0}", blocks.Count); * * UInt64 totalSize = 0; * foreach (var block in blocks) * { * //Console.WriteLine("{2}\n\tstartAddress:{0}\n\tsize:{1}", block.startAddress, block.size, block.ToString()); * Console.WriteLine(block); * totalSize += block.size; * } * Console.WriteLine("Total size:{0} bytes", totalSize);*/ }
public CpuTestMachine() { Registers = new RegisterField(); Memory = new MemoryBlock(0x10000); Stack = new Stack(Memory, Registers.SP); }
internal MethodIL( bool localVariablesInited, ushort maxStack, uint localSignatureToken, MemoryBlock encodedILMemoryBlock, SEHTableEntry[]/*?*/ sehTable) { this.LocalVariablesInited = localVariablesInited; this.MaxStack = maxStack; this.LocalSignatureToken = localSignatureToken; this.EncodedILMemoryBlock = encodedILMemoryBlock; this.SEHTable = sehTable; }
public void LoadSnapshot(byte[] snapshotbytes, Zilog.Z80 cpu) { List <MemoryBlock> MemoryBlocks = new List <MemoryBlock>(); int snappshotposition = 0; //Read header bytes cpu.A = snapshotbytes[0]; cpu.F = snapshotbytes[1]; cpu.C = snapshotbytes[2]; cpu.B = snapshotbytes[3]; cpu.L = snapshotbytes[4]; cpu.H = snapshotbytes[5]; cpu.PC = (snapshotbytes[7] << 8) | snapshotbytes[6]; cpu.SP = (snapshotbytes[9] << 8) | snapshotbytes[8]; cpu.I = snapshotbytes[10]; cpu.R = snapshotbytes[11]; int bytetwelve = snapshotbytes[12]; if (bytetwelve == 255) { bytetwelve = 1; } //Set border color //cpu.Out(254, ((bytetwelve >> 1) & 0x07), 0); //Set it 7 on refresh register if ((bytetwelve & 0x01) != 0) { cpu.R7 = 0x80; } //Is snapshot comressed bool isCompressed = ((bytetwelve & 0x20) != 0); cpu.E = snapshotbytes[13]; cpu.D = snapshotbytes[14]; //Load Prim registers cpu.CPrim = snapshotbytes[15]; cpu.BPrim = snapshotbytes[16]; cpu.EPrim = snapshotbytes[17]; cpu.DPrim = snapshotbytes[18]; cpu.LPrim = snapshotbytes[19]; cpu.HPrim = snapshotbytes[20]; cpu.APrim = snapshotbytes[21]; cpu.FPrim = snapshotbytes[22]; cpu.IY = snapshotbytes[23] | (snapshotbytes[24] << 8); cpu.IX = snapshotbytes[25] | (snapshotbytes[26] << 8); cpu.IFF = (snapshotbytes[27] != 0); cpu.IFF2 = (snapshotbytes[28] != 0); switch (snapshotbytes[29] & 0x03) { case 0: cpu.IM = 0; break; case 1: cpu.IM = 1; break; default: cpu.IM = 2; break; } /* * 29 1 Bit 0-1: Interrupt mode (0, 1 or 2) * Bit 2 : 1=Issue 2 emulation * Bit 3 : 1=Double interrupt frequency * Bit 4-5: 1=High video synchronisation * 3=Low video synchronisation * 0,2=Normal * Bit 6-7: 0=Cursor/Protek/AGF joystick * 1=Kempston joystick * 2=Sinclair 2 Left joystick (or user * defined, for version 3 .z80 files) * 3=Sinclair 2 Right joystick * No need to read an support all of these. */ snappshotposition = 30; if (cpu.PC == 0) {/* * Extended format * Most bytes in the extended section will be discarded since there are no support for them */ int numberofheaderbytes = snapshotbytes[snappshotposition++] | (snapshotbytes[snappshotposition++] << 8); cpu.PC = (snapshotbytes[32]) | (snapshotbytes[33] << 8); //The rest of the header information is not relevant for this emulator snappshotposition += numberofheaderbytes; while (snappshotposition < snapshotbytes.Length) { //Load memory blocks MemoryBlock mb = new MemoryBlock(); int datalength = (snapshotbytes[snappshotposition++]) | (snapshotbytes[snappshotposition++] << 8); int MemoryBlockNumber = snapshotbytes[snappshotposition++]; if (datalength == 0xffff) { //Not compressed datalength = 16384; isCompressed = false; } else { isCompressed = true; } mb = GetMemoryBlock(snapshotbytes, snappshotposition, datalength, isCompressed, MemoryBlockNumber); snappshotposition += datalength; MemoryBlocks.Add(mb); } } else //After the first 30 bytes a memory dump och the 48k Spectrum follows. { MemoryBlock mb = GetMemoryBlock(snapshotbytes, 30, snapshotbytes.Length - 30, isCompressed, -1); //Memoryblock = -1 since this is no "real" block MemoryBlocks.Add(mb); } //Debug.WriteLineIf(MemoryBlocks.Count <= 3, "48K Z80"); //Debug.WriteLineIf(MemoryBlocks.Count > 3, "128K Z80"); //Debug.WriteLineIf((snapshotbytes[29] >> 0x06) == 0, "Cursor"); //Debug.WriteLineIf((snapshotbytes[29] >> 0x06) == 1, "Kempston"); //Debug.WriteLineIf((snapshotbytes[29] >> 0x06) == 2, "Sinclair 2 Left joystick"); //Debug.WriteLineIf((snapshotbytes[29] >> 0x06) == 3, "Sinclair 2 Right joystick"); //Load Memoryblocks into memory foreach (MemoryBlock mb in MemoryBlocks) { switch (mb.MemoryBlockNumber) { case -1: //All Ram MemoryHandler.LoadBytesintoMemory(mb.MemoryData.ToArray(), 16384, cpu); break; case 0: //Rom MemoryHandler.LoadBytesintoMemory(mb.MemoryData.ToArray(), 0, cpu); break; case 1: //Interface 1 case 2: //Not used for 48 case 3: //Not used for 48 case 6: //Not used for 48 case 7: //Not used for 48 case 9: //Not used for 48 case 10: //Not used for 48 case 11: //Multiface rom //Currently no support, using a file with these blocks might result in errors break; case 4: //Normal 8000-bfff MemoryHandler.LoadBytesintoMemory(mb.MemoryData.ToArray(), 0x8000, cpu); break; case 5: //Normal c000-ffff MemoryHandler.LoadBytesintoMemory(mb.MemoryData.ToArray(), 0xc000, cpu); break; break; //case 3: case 8: //Normal 4000-7ffff //Loaded from 3 MemoryHandler.LoadBytesintoMemory(mb.MemoryData.ToArray(), 0x4000, cpu); break; } } }
public void Evaluate(MemoryBlock memory,ReflectedCommands reflect) { reflect.CallReflection(_class, _method, memory, _args.ToArray()); }
public MemoryBlock GetMemoryBlock(long addr) { MemoryBlock result; addr &= mMemoryBlockSize - 1; if (!mMemState.TryGetValue(addr, out result)) { result = new MemoryBlock(addr); mMemState[addr] = result; } return result; }
public static void DeleteMemory(MemoryBlock memory, AsquellObj block) { memory.DeleteVariable(block); }
public static bool ReadFromFile(string fileName, ref MemoryBlock memBlock, ref TiffImageInfo tiffInfo) { IntPtr tiff = Open(fileName, "r"); if (tiff == IntPtr.Zero) { throw new Exception("Unable to open TIFF file: " + fileName); } try { UInt16 i16buf = 0; // буфер для чтения параметров GetIntField(tiff, FieldName.PLANARCONFIG, ref i16buf); tiffInfo.config = (PlanarConfig)i16buf; GetIntField(tiff, FieldName.BITSPERSAMPLE, ref tiffInfo.bps); GetIntField(tiff, FieldName.SAMPLESPERPIXEL, ref tiffInfo.spp); if ((tiffInfo.bps != 1 && tiffInfo.bps != 8) || tiffInfo.spp != 1 || tiffInfo.config != PlanarConfig.CONTIG) { throw new Exception("TIFF parameters do not meet requirements: bps = " + tiffInfo.bps + ", spp = " + tiffInfo.spp + ", config = " + tiffInfo.config); } GetIntField(tiff, FieldName.IMAGEWIDTH, ref tiffInfo.width); GetIntField(tiff, FieldName.IMAGELENGTH, ref tiffInfo.height); GetIntField(tiff, FieldName.PHOTOMETRIC, ref i16buf); tiffInfo.photometric = (Photometric)i16buf; if (tiffInfo.photometric != Photometric.MINISWHITE && tiffInfo.photometric != Photometric.MINISBLACK) { tiffInfo.photometric = Photometric.MINISBLACK; } if (memBlock == null) { memBlock = new MemoryBlock(); } int nSize = (int)((tiffInfo.width * tiffInfo.height * tiffInfo.bps) / 8); if (memBlock.SizeOf < nSize) { memBlock.Free(); memBlock.Alloc(nSize); } IntPtr pMemory = memBlock.ToPointer(); int scanSize = GetScanlineSize(tiff); IntPtr bufPtr = Marshal.AllocHGlobal(scanSize); byte[] oTemp = new byte[nSize]; try { for (int row = 0; row < tiffInfo.height; row++) { ReadScanline(tiff, bufPtr, row, 0); int nDelta = (int)((tiffInfo.width * tiffInfo.bps) / 8 * row); Marshal.Copy(bufPtr, oTemp, nDelta, scanSize); } Marshal.Copy(oTemp, 0, pMemory, nSize); return true; } finally { Marshal.FreeHGlobal(bufPtr); } } finally { Close(tiff); } }
/// <summary> /// load the PE into memory /// </summary> /// <param name="org">start address</param> private void Mount() { LoadOffset = (long)Start - (long)_pe.ImageNtHeaders.OptionalHeader.ImageBase; Memory = new MemoryBlock(Start, Size); Memory.Activate(); Memory.Protect(Start, Size, MemoryBlock.Protection.RW); // copy headers Marshal.Copy(_fileData, 0, Z.US(Start), (int)_pe.ImageNtHeaders.OptionalHeader.SizeOfHeaders); // copy sections foreach (var s in _sections) { ulong datalength = Math.Min(s.Size, s.DiskSize); Marshal.Copy(_fileData, (int)s.DiskStart, Z.US(s.Start), (int)datalength); WaterboxUtils.ZeroMemory(Z.US(s.Start + datalength), (long)(s.SavedSize - datalength)); } // apply relocations var n32 = 0; var n64 = 0; foreach (var rel in _pe.ImageRelocationDirectory) { foreach (var to in rel.TypeOffsets) { ulong address = Start + rel.VirtualAddress + to.Offset; switch (to.Type) { // there are many other types of relocation specified, // but the only that are used is 0 (does nothing), 3 (32 bit standard), 10 (64 bit standard) case 3: // IMAGE_REL_BASED_HIGHLOW { byte[] tmp = new byte[4]; Marshal.Copy(Z.US(address), tmp, 0, 4); uint val = BitConverter.ToUInt32(tmp, 0); tmp = BitConverter.GetBytes((uint)(val + LoadOffset)); Marshal.Copy(tmp, 0, Z.US(address), 4); n32++; break; } case 10: // IMAGE_REL_BASED_DIR64 { byte[] tmp = new byte[8]; Marshal.Copy(Z.US(address), tmp, 0, 8); long val = BitConverter.ToInt64(tmp, 0); tmp = BitConverter.GetBytes(val + LoadOffset); Marshal.Copy(tmp, 0, Z.US(address), 8); n64++; break; } } } } if (IntPtr.Size == 8 && n32 > 0) { // check mcmodel, etc throw new InvalidOperationException("32 bit relocations found in 64 bit dll! This will fail."); } Console.WriteLine($"Processed {n32} 32 bit and {n64} 64 bit relocations"); ProtectMemory(); // publish exports EntryPoint = Z.US(Start + _pe.ImageNtHeaders.OptionalHeader.AddressOfEntryPoint); foreach (var export in _pe.ExportedFunctions) { if (export.Name != null) { ExportsByName.Add(export.Name, Z.US(Start + export.Address)); } ExportsByOrdinal.Add(export.Ordinal, Z.US(Start + export.Address)); } // collect information about imports // NB: Hints are not the same as Ordinals foreach (var import in _pe.ImportedFunctions) { Dictionary <string, IntPtr> module; if (!ImportsByModule.TryGetValue(import.DLL, out module)) { module = new Dictionary <string, IntPtr>(); ImportsByModule.Add(import.DLL, module); } var dest = Start + import.Thunk; if (_imports == null || dest >= _imports.Start + _imports.Size || dest < _imports.Start) { throw new InvalidOperationException("Import record outside of .idata!"); } module.Add(import.Name, Z.US(dest)); } Section midipix; if (_sectionsByName.TryGetValue(".midipix", out midipix)) { var dataOffset = midipix.DiskStart; CtorList = Z.SS(BitConverter.ToInt64(_fileData, (int)(dataOffset + 0x30)) + LoadOffset); DtorList = Z.SS(BitConverter.ToInt64(_fileData, (int)(dataOffset + 0x38)) + LoadOffset); } Console.WriteLine($"Mounted `{ModuleName}` @{Start:x16}"); foreach (var s in _sections.OrderBy(s => s.Start)) { Console.WriteLine(" @{0:x16} {1}{2}{3} `{4}` {5} bytes", s.Start, s.R ? "R" : " ", s.W ? "W" : " ", s.X ? "X" : " ", s.Name, s.Size); } Console.WriteLine("GDB Symbol Load:"); var symload = $"add-sym {ModuleName} {_sectionsByName[".text"].Start}"; if (_sectionsByName.ContainsKey(".data")) { symload += $" -s .data {_sectionsByName[".data"].Start}"; } if (_sectionsByName.ContainsKey(".bss")) { symload += $" -s .bss {_sectionsByName[".bss"].Start}"; } Console.WriteLine(symload); }
public static extern ushort bgfx_create_texture_3d(ushort width, ushort _height, ushort _depth, byte numMips, TextureFormat format, TextureFlags flags, MemoryBlock.DataPtr* mem);
private void InitMemoryTable() { testBlock1 = new MemoryBlock(0x0000, 0x0C00); for (int i = 0; i < testBlock1.Word_Size; i++) { this.memoryView1.Rows.Add(testBlock1.GetRowFromOffset(i)); this.memoryView2.Rows.Add(testBlock1.GetRowFromOffset(i)); } testBlock1.Update(false); }
public static extern void bgfx_update_dynamic_vertex_buffer(ushort handle, int startVertex, MemoryBlock.DataPtr* memory);
public FISRegisterD2H(uint aAddress) { xAddress = aAddress; xBlock = new MemoryBlock(aAddress, 20); }
public static extern void bgfx_update_texture_cube(ushort handle, CubeMapFace side, byte mip, ushort x, ushort y, ushort width, ushort height, MemoryBlock.DataPtr* memory, ushort pitch);
public GenericRegisters(uint aAddress) { xAddress = aAddress; xBlock = new MemoryBlock(aAddress, 0x100); }
public static extern ushort bgfx_create_index_buffer(MemoryBlock.DataPtr* memory, BufferFlags flags);
private void OnSaveImpl( Document input, Stream output, SaveConfigToken token, Surface scratchSurface, ProgressEventHandler callback) { HDPhotoSaveConfigToken hdToken = token as HDPhotoSaveConfigToken; WmpBitmapEncoder wbe = new WmpBitmapEncoder(); using (RenderArgs ra = new RenderArgs(scratchSurface)) { input.Render(ra, true); } MemoryBlock block = scratchSurface.Scan0; IntPtr scan0 = block.Pointer; double dpiX; double dpiY; switch (input.DpuUnit) { case MeasurementUnit.Centimeter: dpiX = Document.DotsPerCmToDotsPerInch(input.DpuX); dpiY = Document.DotsPerCmToDotsPerInch(input.DpuY); break; case MeasurementUnit.Inch: dpiX = input.DpuX; dpiY = input.DpuY; break; case MeasurementUnit.Pixel: dpiX = Document.GetDefaultDpu(MeasurementUnit.Inch); dpiY = Document.GetDefaultDpu(MeasurementUnit.Inch); break; default: throw new InvalidEnumArgumentException(); } BitmapSource bitmapSource = BitmapFrame.Create( scratchSurface.Width, scratchSurface.Height, dpiX, dpiY, System.Windows.Media.PixelFormats.Bgra32, null, scan0, (int)block.Length, // TODO: does not support >2GB images scratchSurface.Stride); FormatConvertedBitmap fcBitmap = new FormatConvertedBitmap( bitmapSource, hdToken.BitDepth == 24 ? PixelFormats.Bgr24 : PixelFormats.Bgra32, null, 0); BitmapFrame outputFrame0 = BitmapFrame.Create(fcBitmap); wbe.Frames.Add(outputFrame0); wbe.ImageQualityLevel = (float)hdToken.Quality / 100.0f; string tempFileName = FileSystem.GetTempFileName(); FileStream tempFileOut = new FileStream(tempFileName, FileMode.Create, FileAccess.Write, FileShare.Read); wbe.Save(tempFileOut); tempFileOut.Close(); tempFileOut = null; FileStream tempFileIn = new FileStream(tempFileName, FileMode.Open, FileAccess.ReadWrite, FileShare.Read); WmpBitmapDecoder wbd = new WmpBitmapDecoder(tempFileIn, BitmapCreateOptions.None, BitmapCacheOption.None); BitmapFrame ioFrame0 = wbd.Frames[0]; InPlaceBitmapMetadataWriter metadata2 = ioFrame0.CreateInPlaceBitmapMetadataWriter(); CopyMetadataTo(metadata2, input.Metadata); tempFileIn.Close(); tempFileIn = null; FileStream tempFileIn2 = new FileStream(tempFileName, FileMode.Open, FileAccess.ReadWrite, FileShare.Read); Utility.CopyStream(tempFileIn2, output); tempFileIn2.Close(); tempFileIn2 = null; try { File.Delete(tempFileName); } catch (Exception) { } // WPF doesn't give us an IDisposable implementation on its types Utility.GCFullCollect(); }
static unsafe void RunCompute(Sample sample, bool indirectSupported) { // build vertex layouts var quadLayout = new VertexLayout(); quadLayout.Begin() .Add(VertexAttributeUsage.Position, 2, VertexAttributeType.Float) .End(); var computeLayout = new VertexLayout(); computeLayout.Begin() .Add(VertexAttributeUsage.TexCoord0, 4, VertexAttributeType.Float) .End(); // static quad data var vb = new VertexBuffer(MemoryBlock.FromArray(QuadVertices), quadLayout); var ib = new IndexBuffer(MemoryBlock.FromArray(QuadIndices)); // create compute buffers var currPositionBuffer0 = new DynamicVertexBuffer(1 << 15, computeLayout, BufferFlags.ComputeReadWrite); var currPositionBuffer1 = new DynamicVertexBuffer(1 << 15, computeLayout, BufferFlags.ComputeReadWrite); var prevPositionBuffer0 = new DynamicVertexBuffer(1 << 15, computeLayout, BufferFlags.ComputeReadWrite); var prevPositionBuffer1 = new DynamicVertexBuffer(1 << 15, computeLayout, BufferFlags.ComputeReadWrite); // load shaders var particleProgram = ResourceLoader.LoadProgram("vs_particle", "fs_particle"); var initInstancesProgram = ResourceLoader.LoadProgram("cs_init_instances"); var updateInstancesProgram = ResourceLoader.LoadProgram("cs_update_instances"); // indirect rendering support var indirectProgram = SharpBgfx.Program.Invalid; var indirectBuffer = IndirectBuffer.Invalid; bool useIndirect = false; if (indirectSupported) { indirectProgram = ResourceLoader.LoadProgram("cs_indirect"); indirectBuffer = new IndirectBuffer(2); useIndirect = true; } // setup params uniforms var paramData = new ParamsData { TimeStep = 0.0157f, DispatchSize = 32, Gravity = 0.109f, Damping = 0.25f, ParticleIntensity = 0.64f, ParticleSize = 0.279f, BaseSeed = 57, ParticlePower = 3.5f, InitialSpeed = 3.2f, InitialShape = 1, MaxAccel = 100.0f }; // have the compute shader run initialization var u_params = new Uniform("u_params", UniformType.Vector4, 3); Bgfx.SetUniform(u_params, ¶mData, 3); Bgfx.SetComputeBuffer(0, prevPositionBuffer0, ComputeBufferAccess.Write); Bgfx.SetComputeBuffer(1, currPositionBuffer0, ComputeBufferAccess.Write); Bgfx.Dispatch(0, initInstancesProgram, MaxParticleCount / ThreadGroupUpdateSize); // start the frame clock var clock = new Clock(); clock.Start(); // main loop while (sample.ProcessEvents(ResetFlags.Vsync)) { // tick the clock var elapsed = clock.Frame(); var time = clock.TotalTime(); // write some debug text Bgfx.DebugTextClear(); Bgfx.DebugTextWrite(0, 1, DebugColor.White, DebugColor.Blue, "SharpBgfx/Samples/24-NBody"); Bgfx.DebugTextWrite(0, 2, DebugColor.White, DebugColor.Cyan, "Description: N-body simulation with compute shaders using buffers."); Bgfx.DebugTextWrite(0, 3, DebugColor.White, DebugColor.Cyan, "Frame: {0:F3} ms", elapsed * 1000); // fill the indirect buffer if we're using it if (useIndirect) { Bgfx.SetUniform(u_params, ¶mData, 3); Bgfx.SetComputeBuffer(0, indirectBuffer, ComputeBufferAccess.Write); Bgfx.Dispatch(0, indirectProgram); } // update particle positions Bgfx.SetComputeBuffer(0, prevPositionBuffer0, ComputeBufferAccess.Read); Bgfx.SetComputeBuffer(1, currPositionBuffer0, ComputeBufferAccess.Read); Bgfx.SetComputeBuffer(2, prevPositionBuffer1, ComputeBufferAccess.Write); Bgfx.SetComputeBuffer(3, currPositionBuffer1, ComputeBufferAccess.Write); Bgfx.SetUniform(u_params, ¶mData, 3); if (useIndirect) { Bgfx.Dispatch(0, updateInstancesProgram, indirectBuffer, 1); } else { Bgfx.Dispatch(0, updateInstancesProgram, paramData.DispatchSize); } // ping-pong the buffers for next frame Swap(ref currPositionBuffer0, ref currPositionBuffer1); Swap(ref prevPositionBuffer0, ref prevPositionBuffer1); // view transforms for particle rendering var viewMatrix = Matrix4x4.CreateLookAt(new Vector3(0.0f, 0.0f, -45.0f), -Vector3.UnitZ, Vector3.UnitY); var projMatrix = Matrix4x4.CreatePerspectiveFieldOfView((float)Math.PI / 4, (float)sample.WindowWidth / sample.WindowHeight, 0.1f, 10000.0f); Bgfx.SetViewTransform(0, &viewMatrix.M11, &projMatrix.M11); Bgfx.SetViewRect(0, 0, 0, sample.WindowWidth, sample.WindowHeight); // draw the particles Bgfx.SetVertexBuffer(0, vb); Bgfx.SetIndexBuffer(ib); Bgfx.SetInstanceDataBuffer(currPositionBuffer0, 0, paramData.DispatchSize * ThreadGroupUpdateSize); Bgfx.SetRenderState(RenderState.WriteRGB | RenderState.BlendAdd | RenderState.DepthTestAlways); if (useIndirect) { Bgfx.Submit(0, particleProgram, indirectBuffer); } else { Bgfx.Submit(0, particleProgram); } // done with frame Bgfx.Frame(); } // cleanup if (indirectSupported) { indirectProgram.Dispose(); indirectBuffer.Dispose(); } u_params.Dispose(); currPositionBuffer0.Dispose(); currPositionBuffer1.Dispose(); prevPositionBuffer0.Dispose(); prevPositionBuffer1.Dispose(); updateInstancesProgram.Dispose(); initInstancesProgram.Dispose(); particleProgram.Dispose(); ib.Dispose(); vb.Dispose(); }
public unsafe void ReadFromMemoryBlock() { byte[] buffer = new byte[4] { 0, 1, 0, 2 }; fixed(byte *bufferPtr = buffer) { var block = new MemoryBlock(bufferPtr, buffer.Length); Assert.Throws <BadImageFormatException>(() => block.PeekUInt32(Int32.MaxValue)); Assert.Throws <BadImageFormatException>(() => block.PeekUInt32(-1)); Assert.Throws <BadImageFormatException>(() => block.PeekUInt32(Int32.MinValue)); Assert.Throws <BadImageFormatException>(() => block.PeekUInt32(4)); Assert.Throws <BadImageFormatException>(() => block.PeekUInt32(1)); Assert.Equal(0x02000100U, block.PeekUInt32(0)); Assert.Throws <BadImageFormatException>(() => block.PeekUInt16(Int32.MaxValue)); Assert.Throws <BadImageFormatException>(() => block.PeekUInt16(-1)); Assert.Throws <BadImageFormatException>(() => block.PeekUInt16(Int32.MinValue)); Assert.Throws <BadImageFormatException>(() => block.PeekUInt16(4)); Assert.Equal(0x0200, block.PeekUInt16(2)); int bytesRead; MetadataStringDecoder stringDecoder = MetadataStringDecoder.DefaultUTF8; Assert.Throws <BadImageFormatException>(() => block.PeekUtf8NullTerminated(Int32.MaxValue, null, stringDecoder, out bytesRead)); Assert.Throws <BadImageFormatException>(() => block.PeekUtf8NullTerminated(-1, null, stringDecoder, out bytesRead)); Assert.Throws <BadImageFormatException>(() => block.PeekUtf8NullTerminated(Int32.MinValue, null, stringDecoder, out bytesRead)); Assert.Throws <BadImageFormatException>(() => block.PeekUtf8NullTerminated(5, null, stringDecoder, out bytesRead)); Assert.Throws <BadImageFormatException>(() => block.GetMemoryBlockAt(-1, 1)); Assert.Throws <BadImageFormatException>(() => block.GetMemoryBlockAt(1, -1)); Assert.Throws <BadImageFormatException>(() => block.GetMemoryBlockAt(0, -1)); Assert.Throws <BadImageFormatException>(() => block.GetMemoryBlockAt(-1, 0)); Assert.Throws <BadImageFormatException>(() => block.GetMemoryBlockAt(-Int32.MaxValue, Int32.MaxValue)); Assert.Throws <BadImageFormatException>(() => block.GetMemoryBlockAt(Int32.MaxValue, -Int32.MaxValue)); Assert.Throws <BadImageFormatException>(() => block.GetMemoryBlockAt(Int32.MaxValue, Int32.MaxValue)); Assert.Throws <BadImageFormatException>(() => block.GetMemoryBlockAt(block.Length, -1)); Assert.Throws <BadImageFormatException>(() => block.GetMemoryBlockAt(-1, block.Length)); Assert.Equal("\u0001", block.PeekUtf8NullTerminated(1, null, stringDecoder, out bytesRead)); Assert.Equal(bytesRead, 2); Assert.Equal("\u0002", block.PeekUtf8NullTerminated(3, null, stringDecoder, out bytesRead)); Assert.Equal(bytesRead, 1); Assert.Equal("", block.PeekUtf8NullTerminated(4, null, stringDecoder, out bytesRead)); Assert.Equal(bytesRead, 0); byte[] helloPrefix = Encoding.UTF8.GetBytes("Hello"); Assert.Equal("Hello\u0001", block.PeekUtf8NullTerminated(1, helloPrefix, stringDecoder, out bytesRead)); Assert.Equal(bytesRead, 2); Assert.Equal("Hello\u0002", block.PeekUtf8NullTerminated(3, helloPrefix, stringDecoder, out bytesRead)); Assert.Equal(bytesRead, 1); Assert.Equal("Hello", block.PeekUtf8NullTerminated(4, helloPrefix, stringDecoder, out bytesRead)); Assert.Equal(bytesRead, 0); } }
internal ImportDefinitionCollection(MemoryBlock block) { _block = block; }
public static extern ushort bgfx_create_texture(MemoryBlock.DataPtr* mem, TextureFlags flags, byte skip, out Texture.TextureInfo info);
internal Enumerator(MemoryBlock block) { _reader = new BlobReader(block); _current = default(ImportDefinition); }
public static extern ushort bgfx_create_texture_cube(ushort size, byte numMips, TextureFormat format, TextureFlags flags, MemoryBlock.DataPtr* mem);
public unsafe BlobReader(byte *buffer, int length) : this(MemoryBlock.CreateChecked(buffer, length)) { }
public static extern void bgfx_update_texture_3d(ushort handle, byte mip, ushort x, ushort y, ushort z, ushort width, ushort height, ushort depth, MemoryBlock.DataPtr* memory);
internal BlobHeap(MemoryBlock block, MetadataKind metadataKind) { _lazyVirtualHeap = null; Block = block; if (s_virtualValues == null && metadataKind != MetadataKind.Ecma335) { var blobs = new byte[(int)BlobHandle.VirtualIndex.Count][]; blobs[(int)BlobHandle.VirtualIndex.ContractPublicKeyToken] = new byte[] { 0xB0, 0x3F, 0x5F, 0x7F, 0x11, 0xD5, 0x0A, 0x3A }; blobs[(int)BlobHandle.VirtualIndex.ContractPublicKey] = new byte[] { 0x00, 0x24, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x94, 0x00, 0x00, 0x00, 0x06, 0x02, 0x00, 0x00, 0x00, 0x24, 0x00, 0x00, 0x52, 0x53, 0x41, 0x31, 0x00, 0x04, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x07, 0xD1, 0xFA, 0x57, 0xC4, 0xAE, 0xD9, 0xF0, 0xA3, 0x2E, 0x84, 0xAA, 0x0F, 0xAE, 0xFD, 0x0D, 0xE9, 0xE8, 0xFD, 0x6A, 0xEC, 0x8F, 0x87, 0xFB, 0x03, 0x76, 0x6C, 0x83, 0x4C, 0x99, 0x92, 0x1E, 0xB2, 0x3B, 0xE7, 0x9A, 0xD9, 0xD5, 0xDC, 0xC1, 0xDD, 0x9A, 0xD2, 0x36, 0x13, 0x21, 0x02, 0x90, 0x0B, 0x72, 0x3C, 0xF9, 0x80, 0x95, 0x7F, 0xC4, 0xE1, 0x77, 0x10, 0x8F, 0xC6, 0x07, 0x77, 0x4F, 0x29, 0xE8, 0x32, 0x0E, 0x92, 0xEA, 0x05, 0xEC, 0xE4, 0xE8, 0x21, 0xC0, 0xA5, 0xEF, 0xE8, 0xF1, 0x64, 0x5C, 0x4C, 0x0C, 0x93, 0xC1, 0xAB, 0x99, 0x28, 0x5D, 0x62, 0x2C, 0xAA, 0x65, 0x2C, 0x1D, 0xFA, 0xD6, 0x3D, 0x74, 0x5D, 0x6F, 0x2D, 0xE5, 0xF1, 0x7E, 0x5E, 0xAF, 0x0F, 0xC4, 0x96, 0x3D, 0x26, 0x1C, 0x8A, 0x12, 0x43, 0x65, 0x18, 0x20, 0x6D, 0xC0, 0x93, 0x34, 0x4D, 0x5A, 0xD2, 0x93 }; blobs[(int)BlobHandle.VirtualIndex.AttributeUsage_AllowSingle] = new byte[] { // preamble: 0x01, 0x00, // target (template parameter): 0x00, 0x00, 0x00, 0x00, // named arg count: 0x01, 0x00, // SERIALIZATION_TYPE_PROPERTY 0x54, // ELEMENT_TYPE_BOOLEAN 0x02, // "AllowMultiple".Length 0x0D, // "AllowMultiple" 0x41, 0x6C, 0x6C, 0x6F, 0x77, 0x4D, 0x75, 0x6C, 0x74, 0x69, 0x70, 0x6C, 0x65, // false 0x00 }; blobs[(int)BlobHandle.VirtualIndex.AttributeUsage_AllowMultiple] = new byte[] { // preamble: 0x01, 0x00, // target (template parameter): 0x00, 0x00, 0x00, 0x00, // named arg count: 0x01, 0x00, // SERIALIZATION_TYPE_PROPERTY 0x54, // ELEMENT_TYPE_BOOLEAN 0x02, // "AllowMultiple".Length 0x0D, // "AllowMultiple" 0x41, 0x6C, 0x6C, 0x6F, 0x77, 0x4D, 0x75, 0x6C, 0x74, 0x69, 0x70, 0x6C, 0x65, // true 0x01 }; s_virtualValues = blobs; } }
public static extern ushort bgfx_create_dynamic_vertex_buffer_mem(MemoryBlock.DataPtr* memory, ref VertexLayout.Data decl, BufferFlags flags);
public void Setup() { _memoryBlock = new MemoryBlock(MemorySize); _memoryManager = new MockVirtualMemoryManager(MemorySize, PageSize); _tracking = new MemoryTracking(_memoryManager, PageSize); }
public static extern ushort bgfx_create_shader(MemoryBlock.DataPtr* memory);
internal SequencePointCollection(MemoryBlock block, DocumentHandle document) { _block = block; _document = document; }
private static NumericObj getNumericObj(AsquellObj obj, MemoryBlock memory) { obj = memory.GetRealVariable(obj); if (obj.Type == AsquellObjectType.Number) return new NumericObj(obj); else return null; }
public UserStringHeap(MemoryBlock block) { this.Block = block; }