public void WriteValue(string value) { if (value is null) { WriteByte(DataBytesDefinition.StringNull); return; } if (value == string.Empty) { WriteByte(DataBytesDefinition.StringEmpty); return; } #if COMPATIBILITY var length = Encoding.UTF8.GetByteCount(value); var bufferLength = length + 5; var buffer = ArrayPool <byte> .Shared.Rent(bufferLength); var bufferSpan = buffer.AsSpan(0, bufferLength); buffer[0] = DataBytesDefinition.StringLength; MemoryMarshal.Write(bufferSpan.Slice(1, 4), ref length); Encoding.UTF8.GetBytes(value, 0, value.Length, buffer, 5); Stream.Write(buffer, 0, bufferLength); ArrayPool <byte> .Shared.Return(buffer); #else var length = Encoding.UTF8.GetByteCount(value); if (length <= 2048) { Span <byte> bufferSpan = stackalloc byte[length + 5]; bufferSpan[0] = DataBytesDefinition.StringLength; BitConverter.TryWriteBytes(bufferSpan.Slice(1, 4), length); Encoding.UTF8.GetBytes(value, bufferSpan.Slice(5)); Stream.Write(bufferSpan); } else { var buffer = ArrayPool <byte> .Shared.Rent(length + 5); var bufferSpan = buffer.AsSpan(0, length + 5); buffer[0] = DataBytesDefinition.StringLength; BitConverter.TryWriteBytes(bufferSpan.Slice(1, 4), length); Encoding.UTF8.GetBytes(value, bufferSpan.Slice(5)); Stream.Write(bufferSpan); ArrayPool <byte> .Shared.Return(buffer); } #endif }
/// <summary> /// Writes a 32 bit unsigned integer /// </summary> public void Write(UInt32 source) { EnsureBufferSize(m_bitLength + 32); // can write fast? if ((m_bitLength & 7) == 0) { MemoryMarshal.Write(new Span <byte>(Buffer, m_bitLength / 8, 4), ref source); } else { NetBitWriter.WriteUInt32(source, 32, Buffer, m_bitLength); } m_bitLength += 32; }
public int Append( int location, int collectionLength, int rowCount, NbtType type, NbtFlags flags) { if (ByteLength >= _data.Length - DbRow.Size) { Enlarge(); } var row = new DbRow(location, collectionLength, rowCount, type, flags); MemoryMarshal.Write(_data.AsSpan(ByteLength), ref row); int index = ByteLength; ByteLength += DbRow.Size; return(index); }
static async Task ProcessSocket(Socket socket, IPEndPoint endpoint) { var waypoint = new Waypoint() { MatchIndex = 3, WaypointIndex = 15, FlipY = true, X = 1.5f, Y = 1.6f }; var buffer = new byte[Marshal.SizeOf(waypoint)]; MemoryMarshal.Write(new Span <byte>(buffer), ref waypoint); while (true) { await socket .SendToAsync(buffer, SocketFlags.None, endpoint) .ConfigureAwait(false); } }
internal void Append(JsonTokenType tokenType, int startLocation, int length) { // StartArray or StartObject should have length -1, otherwise the length should not be -1. Debug.Assert( (tokenType == JsonTokenType.StartArray || tokenType == JsonTokenType.StartObject) == (length == DbRow.UnknownSize)); if (Length >= _rentedBuffer.Length - DbRow.Size) { Enlarge(); } DbRow row = new DbRow(tokenType, startLocation, length); MemoryMarshal.Write(_rentedBuffer.AsSpan(Length), ref row); Length += DbRow.Size; }
public async ValueTask CloseAsync(Exception exception, CancellationToken cancel) { byte[] payload = new byte[2]; short reason = System.Net.IPAddress.HostToNetworkOrder( (short)(exception is ObjectDisposedException ? ClosureStatusCode.Shutdown : ClosureStatusCode.Normal)); MemoryMarshal.Write(payload, ref reason); _closing = true; // Send the close frame. await SendImplAsync(OpCode.Close, new List<ArraySegment<byte>> { payload }, cancel).ConfigureAwait(false); if (exception is ConnectionClosedByPeerException) { await ReceiveFrameAsync(cancel).ConfigureAwait(false); } }
public void TestNtWriteVirtualMemory() { var syscall = new Syscall <Signatures.NtWriteVirtualMemory>(); Span <byte> bytes = stackalloc byte[sizeof(int)]; MemoryMarshal.Write(bytes, ref Unsafe.AsRef(_testValue)); var status = syscall.Method(_process.SafeHandle, _testAddress, in bytes[0], bytes.Length, out _); if (status != NtStatus.Success) { throw new Win32Exception(Ntdll.RtlNtStatusToDosError(status)); } Assert.Equal(_testValue, Marshal.ReadInt32(_testAddress)); }
public void Add <TValue>(TKey key, TValue value) where TValue : unmanaged { if (ContainsKey(key)) { throw new InvalidOperationException(); } var size = typeof(TValue).IsEnum ? Marshal.SizeOf(Enum.GetUnderlyingType(typeof(TValue))) : Marshal.SizeOf(value); var storage = new byte[size]; MemoryMarshal.Write(storage, ref value); _infos.Add(key, storage); }
public static void Write <T>(this Stream stream, ref T structure) where T : unmanaged { #if FEATURE_NATIVE_SPAN if (sizeof(T) < MaxStackLimit) { Span <byte> stack = stackalloc byte[sizeof(T)]; MemoryMarshal.Write(stack, ref structure); stream.Write(stack); } else { stream.Write(Struct.GetBytes(structure)); } #else stream.Write(Struct.GetBytes(structure)); #endif }
public static unsafe byte[] ToByteArray(List <SslApplicationProtocol> applicationProtocols) { long protocolListSize = 0; for (int i = 0; i < applicationProtocols.Count; i++) { int protocolLength = applicationProtocols[i].Protocol.Length; if (protocolLength == 0 || protocolLength > byte.MaxValue) { throw new ArgumentException(SR.net_ssl_app_protocols_invalid, nameof(applicationProtocols)); } protocolListSize += protocolLength + 1; if (protocolListSize > short.MaxValue) { throw new ArgumentException(SR.net_ssl_app_protocols_invalid, nameof(applicationProtocols)); } } Sec_Application_Protocols protocols = default; int protocolListConstSize = sizeof(Sec_Application_Protocols) - sizeof(uint) /* offsetof(Sec_Application_Protocols, ProtocolExtensionType) */; protocols.ProtocolListsSize = (uint)(protocolListConstSize + protocolListSize); protocols.ProtocolExtensionType = ApplicationProtocolNegotiationExt.ALPN; protocols.ProtocolListSize = (short)protocolListSize; byte[] buffer = new byte[sizeof(Sec_Application_Protocols) + protocolListSize]; int index = 0; MemoryMarshal.Write(buffer.AsSpan(index), ref protocols); index += sizeof(Sec_Application_Protocols); for (int i = 0; i < applicationProtocols.Count; i++) { ReadOnlySpan <byte> protocol = applicationProtocols[i].Protocol.Span; buffer[index++] = (byte)protocol.Length; protocol.CopyTo(buffer.AsSpan(index)); index += protocol.Length; } return(buffer); }
public void GlobalSetup() { Span <byte> array = new byte[Constants.PAGE_ADDRESS_SIZE * Count]; _pageAddresses = new PageAddress[Count]; Random random = new Random(); for (int i = 0; i < Count; i++) { PageAddress address = new PageAddress((uint)random.Next(0, int.MaxValue), (byte)random.Next(0, byte.MaxValue)); _pageAddresses[i] = address; MemoryMarshal.Write(array.Slice((i * Constants.PAGE_ADDRESS_SIZE)), ref address); } _array = array.ToArray(); }
private void BuildImportAddressTable() { if (_peImage.ImportDescriptors.Count == 0) { return; } foreach (var importDescriptor in _peImage.ImportDescriptors) { foreach (var function in importDescriptor.Functions) { IntPtr functionAddress; if (function.Name.Equals(string.Empty)) { // Find the module that the function is exported from in the remote process var functionModule = _processManager.Modules.First(module => module.Name.Equals(importDescriptor.Name, StringComparison.OrdinalIgnoreCase)); // Determine the name of the function using its ordinal var functionName = functionModule.PeImage.Value.ExportedFunctions.First(exportedFunction => exportedFunction.Ordinal == function.Ordinal).Name; functionAddress = _processManager.GetFunctionAddress(importDescriptor.Name, functionName); } else { functionAddress = _processManager.GetFunctionAddress(importDescriptor.Name, function.Name); } // Write the function address into the import address table in the local process if (_processManager.IsWow64) { MemoryMarshal.Write(_dllBytes.Slice(function.Offset).Span, ref Unsafe.AsRef(functionAddress.ToInt32())); } else { MemoryMarshal.Write(_dllBytes.Slice(function.Offset).Span, ref Unsafe.AsRef(functionAddress.ToInt64())); } } } }
internal static byte[] CreateRawMessageBody(MultiArray <byte> message, Guid correlationId, string name) { var nameLength = Encoding.GetByteCount(name); var body = new byte[16 + 4 + nameLength + message.Count]; var bodySpan = body.AsSpan(); #if COMPATIBILITY correlationId.ToByteArray().CopyTo(body, 0); MemoryMarshal.Write(bodySpan.Slice(16, 4), ref nameLength); Encoding.GetBytes(name).CopyTo(bodySpan.Slice(20, nameLength)); #else correlationId.TryWriteBytes(bodySpan.Slice(0, 16)); BitConverter.TryWriteBytes(bodySpan.Slice(16, 4), nameLength); Encoding.GetBytes(name, bodySpan.Slice(20, nameLength)); #endif message.CopyTo(body, 20 + nameLength); return(body); }
/// <summary> /// Write a <see cref="StringHeader"/> to a memory span /// </summary> /// <param name="to">Destination</param> /// <param name="data">String data</param> /// <returns>Number of bytes written</returns> public static int WriteStringRequest(Span <byte> to, string data) { Span <byte> unicodeData = Encoding.UTF8.GetBytes(data); // Write header StringHeader request = new StringHeader { Length = (ushort)unicodeData.Length }; MemoryMarshal.Write(to, ref request); int bytesWritten = Marshal.SizeOf(request); // Write data unicodeData.CopyTo(to.Slice(bytesWritten)); bytesWritten += unicodeData.Length; return(AddPadding(to, bytesWritten)); }
/// <summary> /// Appends a <see cref="ReadOnlyMemory{T}"/> of bytes to the end of the segment /// </summary> /// <param name="writerOffset"></param> /// <param name="bytes"></param> /// <param name="segment"></param> public static void Append(ArraySegment <byte> segment, ref int writerOffset, ReadOnlyMemory <byte> bytes) { if (segment.Array == null) { throw new ArgumentNullException(nameof(segment)); } var length = bytes.Length; MemoryMarshal.Write(segment.AsSpan(writerOffset), ref length); writerOffset += sizeof(int); if (bytes.Length > 0) { bytes.CopyTo(segment.AsMemory(writerOffset)); writerOffset += bytes.Length; } }
/// <summary> /// Write a request to evaluate an expression /// </summary> /// <param name="to">Destination</param> /// <param name="channel">Where to evaluate the expression</param> /// <param name="expression">Expression to evaluate</param> /// <returns>Number of bytes written</returns> public static int WriteEvaluateExpression(Span <byte> to, CodeChannel channel, string expression) { Span <byte> unicodeExpression = Encoding.UTF8.GetBytes(expression); // Write header CodeChannelHeader header = new CodeChannelHeader { Channel = channel }; MemoryMarshal.Write(to, ref header); int bytesWritten = Marshal.SizeOf(header); // Write expression unicodeExpression.CopyTo(to.Slice(bytesWritten)); bytesWritten += unicodeExpression.Length; return(AddPadding(to, bytesWritten)); }
private void BuildImportAddressTable() { var importDescriptors = _peImage.ImportDirectory.Value.ImportDescriptors.Concat(_peImage.DelayImportDirectory.Value.DelayImportDescriptors); foreach (var importDescriptor in importDescriptors) { var importDescriptorName = _processManager.ResolveDllName(importDescriptor.Name); foreach (var function in importDescriptor.Functions) { // Write the function address into the import address table var functionAddress = function.Name is null?_processManager.GetFunctionAddress(importDescriptorName, function.Ordinal) : _processManager.GetFunctionAddress(importDescriptorName, function.Name); MemoryMarshal.Write(_dllBytes.Slice(function.Offset).Span, ref functionAddress); } } }
/// <summary> /// Compresses a stream into a .gz stream. /// </summary> /// <param name="data"></param> /// <param name="options"></param> /// <returns></returns> public static Span <byte> Compress(Span <byte> data, CompressionOptions?options) { options ??= CompressionOptions.Default; var buffer = new Span <byte>(new byte[data.Length]); var cursor = 0; for (var i = 0; i < data.Length; i += options.BlockSize) { using var ms = new MemoryStream(options.BlockSize); using var deflateStream = new DeflateStream(ms, CompressionLevel.Optimal); var block = data.Slice(i, Math.Min(options.BlockSize, data.Length - i)); deflateStream.Write(block); deflateStream.Flush(); var write = block.Length; var compressed = false; if (0x100 < block.Length) // special case where the last block is too small to compress properly. { write = (int)ms.Position + 2; block = new Span <byte>(new byte[ms.Length]); ms.Position = 0; ms.Read(block); compressed = true; } var absWrite = write; if (compressed) { absWrite = write + 0x4000; } MemoryMarshal.Write(buffer.Slice(cursor), ref absWrite); if (compressed) { buffer[cursor + 4] = 0x78; buffer[cursor + 5] = 0xDA; } block.CopyTo(buffer.Slice(cursor + 4 + (compressed ? 2 : 0))); cursor = (cursor + write + 4 + (compressed ? 2 : 0)).Align(0x80); } return(buffer.Slice(0, cursor)); }
/// <summary> /// Rebuild multi streams as individual streams /// </summary> /// <returns></returns> public List <Memory <byte> > ReconstructAsIndividual() { switch (Header.Streams) { case 0: return(new List <Memory <byte> >()); case 1: return(new List <Memory <byte> > { FullBuffer }); } var header = Header; header.Streams = 1; header.Unknown2 = -1; header.Unknown3 = 0; header.ADPCMSize = SizeHelper.SizeOf <GCADPCMSoundInfo>(); header.ADPCMPointer = 0x38; header.PointerTablePointer = 0x98; header.SizeTablePointer = 0x9C; var buffers = new List <Memory <byte> >(); for (var index = 0; index < AudioBuffers.Count; index++) { var buffer = AudioBuffers[index]; var data = new Memory <byte>(new byte[(0xA0 + buffer.Length).Align(0x10)]); var @base = header.Base; @base.Size = data.Length; header.Base = @base; MemoryMarshal.Write(data.Span, ref header); var info = Table[index]; MemoryMarshal.Write(data.Span.Slice(header.ADPCMPointer), ref info); BinaryPrimitives.WriteUInt32LittleEndian(data.Span.Slice(header.PointerTablePointer), 0xA0); BinaryPrimitives.WriteUInt32LittleEndian(data.Span.Slice(header.SizeTablePointer), (uint)buffer.Length); buffer.CopyTo(data.Slice(0xA0)); buffers.Add(data); } return(buffers); }
private void BuildImportAddressTable() { Parallel.ForEach(_peImage.ImportDirectory.GetImportDescriptors(), importDescriptor => { foreach (var function in importDescriptor.Functions) { // Write the address of the function into the import address table var functionAddress = function.Name is null ? _processContext.GetFunctionAddress(importDescriptor.Name, function.Ordinal) : _processContext.GetFunctionAddress(importDescriptor.Name, function.Name); if (functionAddress == IntPtr.Zero) { throw new ApplicationException("Failed to resolve the address of a function in a module"); } MemoryMarshal.Write(_dllBytes.Span.Slice(function.Offset), ref functionAddress); } }); }
public unsafe static void ZeroFill(Span <byte> buff) { int num = 0; int i; for (i = 0; i < buff.Length / 4; i++) { MemoryMarshal.Write <int>(buff, ref num); } if (buff.Length % 4 == 0) { return; } while (i < buff.Length) { *buff[i] = 0; i++; } }
public async Task WriteParitionTableAsync(Stream diskStream, long diskLength) { MbrHeader header = MemoryMarshal.Cast <byte, MbrHeader>(new ReadOnlySpan <byte>(mHeader))[0]; fixupPartitionEntry(ref header.Partition1, diskLength); fixupPartitionEntry(ref header.Partition2, diskLength); fixupPartitionEntry(ref header.Partition3, diskLength); fixupPartitionEntry(ref header.Partition4, diskLength); var headerBytes = new byte[MBR_SIZE]; MemoryMarshal.Write(new Span <byte>(headerBytes), ref header); //var headerBytes = MemoryMarshal.Write diskStream.Seek(0, SeekOrigin.Begin); await diskStream.WriteAsync(headerBytes, 0, headerBytes.Length); await diskStream.FlushAsync(); }
/// <summary> /// Writes a <see cref="System.UInt64"/> value. /// </summary> /// <param name="value">Value to write.</param> /// <param name="writer">Buffer writer to write the value to.</param> internal void WritePrimitive_UInt64(ulong value, IBufferWriter <byte> writer) { if (SerializationOptimization == SerializationOptimization.Speed || !IsLeb128EncodingMoreEfficient(value)) { // use native encoding var buffer = writer.GetSpan(9); buffer[0] = (byte)PayloadType.UInt64_Native; MemoryMarshal.Write(buffer.Slice(1), ref value); writer.Advance(9); } else { // use LEB128 encoding var buffer = writer.GetSpan(1 + Leb128EncodingHelper.MaxBytesFor64BitValue); buffer[0] = (byte)PayloadType.UInt64_LEB128; int count = Leb128EncodingHelper.Write(buffer.Slice(1), value); writer.Advance(1 + count); } }
/// <summary> /// Write a <see cref="MessageHeader"/> to a memory span /// </summary> /// <param name="to">Destination</param> /// <param name="type">Message flags</param> /// <param name="message">Message content</param> /// <returns>Number of bytes written</returns> public static int WriteMessage(Span <byte> to, MessageTypeFlags type, string message) { Span <byte> unicodeMessage = Encoding.UTF8.GetBytes(message); // Write header MessageHeader request = new MessageHeader { MessageType = type, Length = (ushort)unicodeMessage.Length }; MemoryMarshal.Write(to, ref request); int bytesWritten = Marshal.SizeOf(request); // Write data unicodeMessage.CopyTo(to.Slice(bytesWritten)); bytesWritten += unicodeMessage.Length; return(AddPadding(to, bytesWritten)); }
internal async Task UpdateImageFileDirectoryNextOffsetFieldAsync(TiffStreamOffset target, TiffStreamOffset ifdOffset, CancellationToken cancellationToken) { EnsureNotDisposed(); Debug.Assert(_writer != null); Debug.Assert(_operationContext != null); // Attemps to read 8 bytes even though the size of IFD may be less then 8 bytes. byte[] buffer = ArrayPool <byte> .Shared.Rent(SmallBufferSize); try { int rwCount = await _writer !.ReadAsync(target, new ArraySegment <byte>(buffer, 0, 8), cancellationToken).ConfigureAwait(false); if (!(_useBigTiff && rwCount == 8) && !(!_useBigTiff && rwCount >= 4)) { throw new InvalidDataException(); } int count = ParseImageFileDirectoryCount(buffer.AsSpan(0, 8)); // Prepare next ifd. if (_useBigTiff) { rwCount = 8; long offset = ifdOffset; MemoryMarshal.Write(buffer, ref offset); } else { rwCount = 4; int offset32 = (int)ifdOffset; MemoryMarshal.Write(buffer, ref offset32); } // Skip over IFD entries. int entryFieldLength = _useBigTiff ? 20 : 12; await _writer.WriteAsync(target + _operationContext !.ByteCountOfImageFileDirectoryCountField + count *entryFieldLength, new ArraySegment <byte>(buffer, 0, rwCount), cancellationToken).ConfigureAwait(false); } finally { ArrayPool <byte> .Shared.Return(buffer); } }
/// <summary> /// Rebuild multi streams as individual streams /// </summary> /// <returns></returns> public List <Memory <byte> > ReconstructAsIndividual() { switch (Header.Streams) { case 0: return(new List <Memory <byte> >()); case 1: return(new List <Memory <byte> > { FullBuffer }); } var header = Header; header.Streams = 1; header.Unknown2 = -1; header.Unknown3 = 0; header.ADPCMSize = 4; header.ADPCMPointer = 0x38; header.PointerTablePointer = 0x3C; header.SizeTablePointer = 0x40; var buffers = new List <Memory <byte> >(); foreach (var buffer in AudioBuffers) { var data = new Memory <byte>(new byte[(0x50 + buffer.Length).Align(0x10)]); var @base = header.Base; @base.Size = data.Length; header.Base = @base; MemoryMarshal.Write(data.Span, ref header); BinaryPrimitives.WriteInt32LittleEndian(data.Span.Slice(header.ADPCMPointer), Header.SampleRate); BinaryPrimitives.WriteUInt32LittleEndian(data.Span.Slice(header.PointerTablePointer), 0x50); BinaryPrimitives.WriteUInt32LittleEndian(data.Span.Slice(header.SizeTablePointer), (uint)buffer.Length); buffer.CopyTo(data.Slice(0x50)); buffers.Add(data); } return(buffers); }
/// <summary> /// Write a parsed G/M/T code in binary format to a memory span /// </summary> /// <param name="to">Destination</param> /// <param name="code">Code to write</param> /// <returns>Number of bytes written</returns> /// <exception cref="ArgumentException">Unsupported data type</exception> public static int WriteCode(Span <byte> to, Code code) { int bytesWritten = 0; // Write code header CodeHeader header = new() { Channel = code.Channel, FilePosition = (uint)(code.FilePosition ?? 0xFFFFFFFF), Letter = (byte)code.Type, MajorCode = (code.Type == CodeType.Comment) ? 0 : (code.MajorNumber ?? -1), MinorCode = code.MinorNumber ?? -1, NumParameters = (byte)((code.Type == CodeType.Comment) ? 1 : code.Parameters.Count) }; if (code.Type == CodeType.Comment || code.MajorNumber != null) { header.Flags |= CodeFlags.HasMajorCommandNumber; } if (code.MinorNumber != null) { header.Flags |= CodeFlags.HasMinorCommandNumber; } if (code.FilePosition != null) { header.Flags |= CodeFlags.HasFilePosition; } if (code.Flags.HasFlag(DuetAPI.Commands.CodeFlags.EnforceAbsolutePosition)) { header.Flags |= CodeFlags.EnforceAbsolutePosition; } MemoryMarshal.Write(to, ref header); bytesWritten += Marshal.SizeOf <CodeHeader>(); // Write line number if (DataTransfer.ProtocolVersion >= 2) { int lineNumber = (int)(code.LineNumber ?? 0); MemoryMarshal.Write(to[bytesWritten..], ref lineNumber); bytesWritten += Marshal.SizeOf <int>(); }
public byte[] ToBytes(bool writeDecryptedKey) { uint magic = Magic; long size = Size; byte[] key1 = writeDecryptedKey ? DecryptedKey1 : EncryptedKey1; byte[] key2 = writeDecryptedKey ? DecryptedKey2 : EncryptedKey2; var data = new byte[0x80]; Array.Copy(Signature, data, 0x20); MemoryMarshal.Write(data.AsSpan(0x20), ref magic); Array.Copy(key1, 0, data, 0x28, 0x10); Array.Copy(key2, 0, data, 0x38, 0x10); MemoryMarshal.Write(data.AsSpan(0x48), ref size); return(data); }
internal void Append(JsonTokenType tokenType, int startLocation, int length) { // StartArray or StartObject should have length -1, otherwise the length should not be -1. Debug.Assert( (tokenType == JsonTokenType.StartArray || tokenType == JsonTokenType.StartObject) == (length == DbRow.UnknownSize)); #if DEBUG Debug.Assert(!_isLocked, "Appending to a locked database"); #endif if (Length >= _data.Length - DbRow.Size) { Enlarge(); } DbRow row = new DbRow(tokenType, startLocation, length); MemoryMarshal.Write(_data.AsSpan(Length), ref row); Length += DbRow.Size; }
/// <summary> /// Write a file chunk /// </summary> /// <param name="to">Destination</param> /// <param name="data">File chunk data</param> /// <param name="fileLength">Total length of the file in bytes</param> /// <returns>Number of bytes written</returns> public static int WriteFileChunk(Span <byte> to, Span <byte> data, long fileLength) { // Write header FileChunk header = new FileChunk { DataLength = (data != null) ? data.Length : -1, FileLength = (uint)fileLength }; MemoryMarshal.Write(to, ref header); int bytesWritten = Marshal.SizeOf(header); // Write chunk if (data != null) { data.CopyTo(to.Slice(bytesWritten)); bytesWritten += data.Length; } return(AddPadding(to, bytesWritten)); }