System.BitConverter.GetBytes(int)

Here are the examples of the csharp api System.BitConverter.GetBytes(int) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

1900 Examples 7

19 View Source File : frmMain.cs
License : GNU General Public License v3.0
Project Creator : 0x00000FF

private void btnForce_Click(object sender, EventArgs e)
        {
            uint outvar;
            int tryval;

            if(!int.TryParse(Inputs.Text, out tryval) || tryval < 0 || tryval > 99999999)
            {
                Inputs.Text = "NOT VALID VALUE!";
                return;
            }

            byte[] overscore = BitConverter.GetBytes(tryval);

            if (handle != 0)
            {
                var _try = WriteProcessMemory(handle, ScorePtr, overscore, 4, out outvar);
                if (!_try)
                {
                    MessageBox.Show("Failed to modify memory. try again.");
                    return;
                }
            }
        }

19 View Source File : GmicPipeServer.cs
License : GNU General Public License v3.0
Project Creator : 0xC0000054

private void WaitForConnectionCallback(IAsyncResult result)
        {
            if (server == null)
            {
                return;
            }

            try
            {
                server.EndWaitForConnection(result);
            }
            catch (ObjectDisposedException)
            {
                return;
            }

            byte[] replySizeBuffer = new byte[sizeof(int)];
            server.ProperRead(replySizeBuffer, 0, replySizeBuffer.Length);

            int messageLength = BitConverter.ToInt32(replySizeBuffer, 0);

            byte[] messageBytes = new byte[messageLength];

            server.ProperRead(messageBytes, 0, messageLength);

            List<string> parameters = DecodeMessageBuffer(messageBytes);

            if (!TryGetValue(parameters[0], "command=", out string command))
            {
                throw new InvalidOperationException("The first item must be a command.");
            }

            if (command.Equals("gmic_qt_get_max_layer_size", StringComparison.Ordinal))
            {
                if (!TryGetValue(parameters[1], "mode=", out string mode))
                {
                    throw new InvalidOperationException("The second item must be the input mode.");
                }

                InputMode inputMode = ParseInputMode(mode);

#if DEBUG
                System.Diagnostics.Debug.WriteLine("'gmic_qt_get_max_layer_size' received. mode=" + inputMode.ToString());
#endif
                string reply = GetMaxLayerSize(inputMode);

                SendMessage(server, reply);
            }
            else if (command.Equals("gmic_qt_get_cropped_images", StringComparison.Ordinal))
            {
                if (!TryGetValue(parameters[1], "mode=", out string mode))
                {
                    throw new InvalidOperationException("The second item must be the input mode.");
                }

                if (!TryGetValue(parameters[2], "croprect=", out string packedCropRect))
                {
                    throw new InvalidOperationException("The third item must be the crop rectangle.");
                }

                InputMode inputMode = ParseInputMode(mode);
                RectangleF cropRect = GetCropRectangle(packedCropRect);

#if DEBUG
                System.Diagnostics.Debug.WriteLine(string.Format(CultureInfo.InvariantCulture,
                                                                 "'gmic_qt_get_cropped_images' received. mode={0}, cropRect={1}",
                                                                 inputMode.ToString(), cropRect.ToString()));
#endif
                string reply = PrepareCroppedLayers(inputMode, cropRect);

                SendMessage(server, reply);
            }
            else if (command.Equals("gmic_qt_output_images", StringComparison.Ordinal))
            {
                if (!TryGetValue(parameters[1], "mode=", out string mode))
                {
                    throw new InvalidOperationException("The second item must be the output mode.");
                }

                OutputMode outputMode = ParseOutputMode(mode);

#if DEBUG
                System.Diagnostics.Debug.WriteLine("'gmic_qt_output_images' received. mode=" + outputMode.ToString());
#endif

                List<string> outputLayers = parameters.GetRange(2, parameters.Count - 2);

                string reply = ProcessOutputImage(outputLayers, outputMode);
                SendMessage(server, reply);
            }
            else if (command.Equals("gmic_qt_release_shared_memory", StringComparison.Ordinal))
            {
#if DEBUG
                System.Diagnostics.Debug.WriteLine("'gmic_qt_release_shared_memory' received.");
#endif

                for (int i = 0; i < memoryMappedFiles.Count; i++)
                {
                    memoryMappedFiles[i].Dispose();
                }
                memoryMappedFiles.Clear();

                SendMessage(server, "done");
            }
            else if (command.Equals("gmic_qt_get_max_layer_data_length", StringComparison.Ordinal))
            {
                // This command is used to prevent images larger than 4GB from being used on a 32-bit version of G'MIC.
                // Attempting to map an image that size into memory would cause an integer overflow when casting a 64-bit
                // integer to the unsigned 32-bit size_t type.
                long maxDataLength = 0;

                foreach (GmicLayer layer in layers)
                {
                    maxDataLength = Math.Max(maxDataLength, layer.Surface.Scan0.Length);
                }

                server.Write(BitConverter.GetBytes(sizeof(long)), 0, 4);
                server.Write(BitConverter.GetBytes(maxDataLength), 0, 8);
            }

            // Wait for the acknowledgment that the client is done reading.
            if (server.IsConnected)
            {
                byte[] doneMessageBuffer = new byte[4];
                int bytesRead = 0;
                int bytesToRead = doneMessageBuffer.Length;

                do
                {
                    int n = server.Read(doneMessageBuffer, bytesRead, bytesToRead);

                    bytesRead += n;
                    bytesToRead -= n;

                } while (bytesToRead > 0 && server.IsConnected);
            }

            // Start a new server and wait for the next connection.
            server.Dispose();
            server = new NamedPipeServerStream(pipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous);

            server.BeginWaitForConnection(WaitForConnectionCallback, null);
        }

19 View Source File : AesGcm.cs
License : GNU General Public License v3.0
Project Creator : 0xfd3

private IntPtr ImportKey(IntPtr hAlg, byte[] key, out IntPtr hKey)
        {
            byte[] objLength = GetProperty(hAlg, BCrypt.BCRYPT_OBJECT_LENGTH);

            int keyDataSize = BitConverter.ToInt32(objLength, 0);

            IntPtr keyDataBuffer = Marshal.AllocHGlobal(keyDataSize);

            byte[] keyBlob = Concat(BCrypt.BCRYPT_KEY_DATA_BLOB_MAGIC, BitConverter.GetBytes(0x1), BitConverter.GetBytes(key.Length), key);

            uint status = BCrypt.BCryptImportKey(hAlg, IntPtr.Zero, BCrypt.BCRYPT_KEY_DATA_BLOB, out hKey, keyDataBuffer, keyDataSize, keyBlob, keyBlob.Length, 0x0);

            if (status != BCrypt.ERROR_SUCCESS)
                throw new CryptographicException(string.Format("BCrypt.BCryptImportKey() failed with status code:{0}", status));

            return keyDataBuffer;
        }

19 View Source File : Inline_Hook.cs
License : Apache License 2.0
Project Creator : 1694439208

public static IntPtr InlineHook(int HookAddress, int Hooklen,
            byte[] HookBytes0,int Callback,int CallbackOffset,
            bool IsFront,int CallAddress,string name, Action<Methods.Register> func)
        {
            WeChetHook.DllcallBack dllcallBack = new WeChetHook.DllcallBack((de1, de2, ECX1, EAX1, EDX1, EBX1, ESP1, EBP1, ESI1, EDI1) => {
                func(new Register
                {
                    EAX = EAX1,
                    EBP = EBP1,
                    EBX = EBX1,
                    ECX = ECX1,
                    EDI = EDI1,
                    EDX = EDX1,
                    ESI = ESI1,
                    ESP = ESP1
                });
            });
            int CallHandle = ComputeHash(name);
            Methods.callBacks.Add(CallHandle, dllcallBack);

            List<byte> byteSource1 = new List<byte>();
            byteSource1.AddRange(new byte[] { 199, 134, 240, 2, 0, 0 });
            byteSource1.AddRange(BitConverter.GetBytes(CallHandle));
            byteSource1.AddRange(HookBytes0);

            byte[] hookbytes = byteSource1.ToArray();


            List<byte> byteSource = new List<byte>();
            IntPtr ptr = NativeAPI.VirtualAlloc(0, 128, 4096, 64);
            if (IsFront)
            {
                NativeAPI.WriteProcessMemory(-1, ptr, Add(new byte[] { 232 }, Inline_GetBuf(ptr, CallAddress)), 5, 0);
                NativeAPI.WriteProcessMemory(-1, ptr + 5, hookbytes, hookbytes.Length, 0);
                NativeAPI.WriteProcessMemory(-1, ptr + 5 + CallbackOffset, Inline_GetBuf(ptr + 5 + CallbackOffset - 1, Callback), 4, 0);
                NativeAPI.WriteProcessMemory(-1, ptr + 5 + hookbytes.Length, Add(new byte[] { 233 }, Inline_GetBuf(ptr + 5 + HookBytes0.Length, HookAddress + Hooklen)), 5, 0);
            }
            else {
                NativeAPI.WriteProcessMemory(-1, ptr, hookbytes, hookbytes.Length, 0);
                NativeAPI.WriteProcessMemory(-1, ptr + CallbackOffset, Inline_GetBuf(ptr + CallbackOffset - 1, Callback), 4, 0);
                NativeAPI.WriteProcessMemory(-1, ptr + hookbytes.Length,Add(new byte[] { 232 },Inline_GetBuf(ptr + hookbytes.Length, CallAddress)), Hooklen, 0);
                NativeAPI.WriteProcessMemory(-1, ptr + Hooklen + hookbytes.Length, Add(new byte[] { 233 }, Inline_GetBuf(ptr + Hooklen + HookBytes0.Length, HookAddress + Hooklen)), 5, 0);
            }
            NativeAPI.WriteProcessMemory(-1, new IntPtr(HookAddress), Add(new byte[] { 233 }, Inline_GetBuf(HookAddress, ptr.ToInt32())), 5, 0);
            for (int i = 0; i < Hooklen - 5; i++)
            {
                byteSource.Add(144);
            }
            byte[] ByteFill = byteSource.ToArray();
            NativeAPI.WriteProcessMemory(-1, new IntPtr(HookAddress + 5), ByteFill, ByteFill.Length, 0);
            return ptr;
        }

19 View Source File : Inline_Hook.cs
License : Apache License 2.0
Project Creator : 1694439208

public static IntPtr InlineHook(int HookAddress, int Hooklen,
            byte[] HookBytes0, int Callback, int CallbackOffset,string name, Action<Methods.Register> func)
        {

            WeChetHook.DllcallBack dllcallBack = new WeChetHook.DllcallBack((de1, de2, ECX1, EAX1, EDX1, EBX1, ESP1, EBP1, ESI1, EDI1) => {
                //int ECX, int EAX, int EDX, int EBX, int ESP, int EBP, int ESI, int EDI
                func(new Register
                {
                    EAX = EAX1,
                    EBP = EBP1,
                    EBX = EBX1,
                    ECX = ECX1,
                    EDI = EDI1,
                    EDX = EDX1,
                    ESI = ESI1,
                    ESP = ESP1
                });
            });
            int CallHandle = ComputeHash(name);
            System.Windows.Forms.MessageBox.Show("CallHandle:" + CallHandle.ToString());
            Methods.callBacks.Add(CallHandle, dllcallBack);

            List<byte> byteSource1 = new List<byte>();
            byteSource1.AddRange(new byte[] { 199, 134, 240, 2, 0, 0 });
            byteSource1.AddRange(BitConverter.GetBytes(CallHandle));//把标识指针绑定到寄存器我觉得不靠谱但是目前没啥问题
            byteSource1.AddRange(HookBytes0);

            byte[] hookbytes = byteSource1.ToArray();


            List<byte> byteSource = new List<byte>();
            IntPtr ptr = NativeAPI.VirtualAlloc(0, 128, 4096, 64);
            NativeAPI.WriteProcessMemory(-1, ptr, hookbytes, hookbytes.Length, 0);
            NativeAPI.WriteProcessMemory(-1, ptr + CallbackOffset, Inline_GetBuf(ptr + CallbackOffset - 1, Callback), 4, 0);
            NativeAPI.WriteProcessMemory(-1, ptr + hookbytes.Length, Add(new byte[] { 233 }, Inline_GetBuf(ptr + hookbytes.Length, HookAddress+ Hooklen)), 5, 0);

            NativeAPI.WriteProcessMemory(-1, new IntPtr(HookAddress), Add(new byte[] { 233 }, Inline_GetBuf(HookAddress, ptr.ToInt32())), 5, 0);
            for (int i = 0; i < Hooklen - 5; i++)
            {
                byteSource.Add(144);
            }
            byte[] ByteFill = byteSource.ToArray();
            NativeAPI.WriteProcessMemory(-1, new IntPtr(HookAddress + 5), ByteFill, ByteFill.Length, 0);
            return ptr;
        }

19 View Source File : NativeAPI.cs
License : Apache License 2.0
Project Creator : 1694439208

public static void WriteMemoryValue(int baseAddress, string processName, int value)
        {
            try
            {
                //打开一个已存在的进程对象  0x1F0FFF 最高权限
                IntPtr hProcess = OpenProcess(0x1F0FFF, false, GetPidByProcessName(processName));
                //从指定内存中写入字节集数据
                WriteProcessMemory(hProcess.ToInt32(), (IntPtr)baseAddress, BitConverter.GetBytes(value), 4, IntPtr.Zero.ToInt32());
                //关闭操作
                CloseHandle(hProcess);
            }
            catch { }
        }

19 View Source File : Inline_Hook.cs
License : Apache License 2.0
Project Creator : 1694439208

public static byte[] Inline_GetBuf(int Address,int jmp)
        {
            return BitConverter.GetBytes(jmp - Address - 5);
        }

19 View Source File : Inline_Hook.cs
License : Apache License 2.0
Project Creator : 1694439208

public static byte[] Inline_GetBuf(IntPtr Address, int jmp)
        {
            return BitConverter.GetBytes(jmp - Address.ToInt32() - 5);
        }

19 View Source File : Core.cs
License : MIT License
Project Creator : 1y0n

public static byte string_to_int(string str)
        {
            string temp = str.Substring(str.Length - 2, 2);
            int hex = int.Parse(temp, System.Globalization.NumberStyles.HexNumber);
            return BitConverter.GetBytes(hex)[0];
        }

19 View Source File : Globals.cs
License : MIT License
Project Creator : 1ZouLTReX1

public static byte[] SerializeLenPrefix(byte[] data)
    {
        // Get the length prefix for the message
        byte[] lengthPrefix = BitConverter.GetBytes(data.Length);

        // Concatenate the length prefix and the message
        byte[] ret = new byte[lengthPrefix.Length + data.Length];
        lengthPrefix.CopyTo(ret, 0);
        data.CopyTo(ret, lengthPrefix.Length);

        return ret;
    }

19 View Source File : NetworkUtils.cs
License : MIT License
Project Creator : 1ZouLTReX1

public static void SerializeInt(List<byte> byteList, int data)
    {
        byteList.AddRange(BitConverter.GetBytes(data));
    }

19 View Source File : Form1.cs
License : MIT License
Project Creator : 1y0n

private byte string_to_int(string str)
        {
            string temp = str.Substring(str.Length - 2, 2);
            int hex = int.Parse(temp, System.Globalization.NumberStyles.HexNumber);
            return BitConverter.GetBytes(hex)[0];
        }

19 View Source File : RdpPacket.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : 3gstudent

public void WriteLittleEndian32(int value)
        {
            base.Write(BitConverter.GetBytes(value), 0, 4);
        }

19 View Source File : ASN1.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : 3gstudent

protected static void WriteInteger(RdpPacket packet, int value)
        {
            packet.WriteByte(2);
            byte[] bytes = BitConverter.GetBytes(value);

            if (value > 0xffffff)
            {
                packet.WriteByte(4);
                packet.WriteByte(bytes[3]);
                packet.WriteByte(bytes[2]);
                packet.WriteByte(bytes[1]);
                packet.WriteByte(bytes[0]);
            }
            else if (value > 0xffff)
            {
                packet.WriteByte(3);
                packet.WriteByte(bytes[2]);
                packet.WriteByte(bytes[1]);
                packet.WriteByte(bytes[0]);
            }
            else if (value > 0xff)
            {
                packet.WriteByte(2);
                packet.WriteByte(bytes[1]);
                packet.WriteByte(bytes[0]);
            }
            else
            {
                packet.WriteByte(1);
                packet.WriteByte(bytes[0]);
            }
        }

19 View Source File : QQTea.cs
License : MIT License
Project Creator : 499116344

private static void Code(byte[] In, int inOffset, int inPos, byte[] Out, int outOffset, int outPos, byte[] key)
        {
            if (outPos > 0)
            {
                for (var i = 0; i < 8; i++)
                {
                    In[outOffset + outPos + i] =
                        BitConverter.GetBytes(In[inOffset + inPos + i] ^ Out[outOffset + outPos + i - 8])[0];
                }
            }

            var array = FormatKey(key);
            var num = ConvertByteArrayToUInt(In, outOffset + outPos);
            var num2 = ConvertByteArrayToUInt(In, outOffset + outPos + 4);
            var num3 = 0u;
            var num4 = 2654435769u;
            var num5 = 16u;
            while (num5-- > 0u)
            {
                num3 += num4;
                num += ((num2 << 4) + array[0]) ^ (num2 + num3) ^ ((num2 >> 5) + array[1]);
                num2 += ((num << 4) + array[2]) ^ (num + num3) ^ ((num >> 5) + array[3]);
            }

            Array.Copy(ConvertUIntToByteArray(num), 0, Out, outOffset + outPos, 4);
            Array.Copy(ConvertUIntToByteArray(num2), 0, Out, outOffset + outPos + 4, 4);
            if (inPos > 0)
            {
                for (var j = 0; j < 8; j++)
                {
                    Out[outOffset + outPos + j] =
                        BitConverter.GetBytes(Out[outOffset + outPos + j] ^ In[inOffset + inPos + j - 8])[0];
                }
            }
        }

19 View Source File : QQTea.cs
License : MIT License
Project Creator : 499116344

private static void Decode(byte[] In, int inOffset, int inPos, byte[] Out, int outOffset, int outPos,
            byte[] key)
        {
            if (outPos > 0)
            {
                for (var i = 0; i < 8; i++)
                {
                    Out[outOffset + outPos + i] =
                        BitConverter.GetBytes(In[inOffset + inPos + i] ^ Out[outOffset + outPos + i - 8])[0];
                }
            }
            else
            {
                Array.Copy(In, inOffset, Out, outOffset, 8);
            }

            var array = FormatKey(key);
            var num = ConvertByteArrayToUInt(Out, outOffset + outPos);
            var num2 = ConvertByteArrayToUInt(Out, outOffset + outPos + 4);
            var num3 = 3816266640u;
            var num4 = 2654435769u;
            var num5 = 16u;
            while (num5-- > 0u)
            {
                num2 -= ((num << 4) + array[2]) ^ (num + num3) ^ ((num >> 5) + array[3]);
                num -= ((num2 << 4) + array[0]) ^ (num2 + num3) ^ ((num2 >> 5) + array[1]);
                num3 -= num4;
            }

            Array.Copy(ConvertUIntToByteArray(num), 0, Out, outOffset + outPos, 4);
            Array.Copy(ConvertUIntToByteArray(num2), 0, Out, outOffset + outPos + 4, 4);
        }

19 View Source File : Util.cs
License : MIT License
Project Creator : 499116344

public static void BeWrite(this BinaryWriter bw, int v)
        {
            bw.Write(BitConverter.GetBytes(v).Reverse().ToArray());
        }

19 View Source File : Helpers.cs
License : MIT License
Project Creator : 71

public static byte[] GetJmpBytes(IntPtr destination)
        {
            switch (RuntimeInformation.ProcessArchitecture)
            {
                case Architecture.Arm:
                {
                    // LDR PC, [PC, #-4]
                    // $addr
                    byte[] result = new byte[8];

                    result[0] = 0x04;
                    result[1] = 0xF0;
                    result[2] = 0x1F;
                    result[3] = 0xE5;

                    BitConverter.GetBytes(destination.ToInt32()).CopyTo(result, 4);

                    return result;
                }

                case Architecture.Arm64:
                {
                    // LDR PC, [PC, #-4]
                    // $addr
                    byte[] result = new byte[12];

                    result[0] = 0x04;
                    result[1] = 0xF0;
                    result[2] = 0x1F;
                    result[3] = 0xE5;

                    BitConverter.GetBytes(destination.ToInt64()).CopyTo(result, 4);

                    return result;
                }

                case Architecture.X64:
                {
                    // movabs rax,$addr
                    // jmp rax
                    byte[] result = new byte[12];

                    result[0] = 0x48;
                    result[1] = 0xB8;
                    result[10] = 0xFF;
                    result[11] = 0xE0;

                    BitConverter.GetBytes(destination.ToInt64()).CopyTo(result, 2);

                    return result;
                }

                case Architecture.X86:
                {
                    // push $addr
                    // ret
                    byte[] result = new byte[6];

                    result[0] = 0x68;
                    result[5] = 0xC3;

                    BitConverter.GetBytes(destination.ToInt32()).CopyTo(result, 1);

                    return result;
                }

                default:
                    throw UnsupportedArchitecture;
            }
        }

19 View Source File : Ryder.Lightweight.cs
License : MIT License
Project Creator : 71

public static byte[] GetJmpBytes(IntPtr destination)
            {
                switch (RuntimeInformation.ProcessArchitecture)
                {
                    case Architecture.Arm:
                        {
                            // LDR PC, [PC, #-4]
                            // $addr
                            byte[] result = new byte[8];

                            result[0] = 0x04;
                            result[1] = 0xF0;
                            result[2] = 0x1F;
                            result[3] = 0xE5;

                            BitConverter.GetBytes(destination.ToInt32()).CopyTo(result, 4);

                            return result;
                        }

                    case Architecture.Arm64:
                        {
                            // LDR PC, [PC, #-4]
                            // $addr
                            byte[] result = new byte[12];

                            result[0] = 0x04;
                            result[1] = 0xF0;
                            result[2] = 0x1F;
                            result[3] = 0xE5;

                            BitConverter.GetBytes(destination.ToInt64()).CopyTo(result, 4);

                            return result;
                        }

                    case Architecture.X64:
                        {
                            // movabs rax,$addr
                            // jmp rax
                            byte[] result = new byte[12];

                            result[0] = 0x48;
                            result[1] = 0xB8;
                            result[10] = 0xFF;
                            result[11] = 0xE0;

                            BitConverter.GetBytes(destination.ToInt64()).CopyTo(result, 2);

                            return result;
                        }

                    case Architecture.X86:
                        {
                            // push $addr
                            // ret
                            byte[] result = new byte[6];

                            result[0] = 0x68;
                            result[5] = 0xC3;

                            BitConverter.GetBytes(destination.ToInt32()).CopyTo(result, 1);

                            return result;
                        }

                    default:
                        throw UnsupportedArchitecture;
                }
            }

19 View Source File : TestAmf3Reader.cs
License : MIT License
Project Creator : a1q123456

public bool TryEncodeData(ByteBuffer buffer)
        {
            var b1 = BitConverter.GetBytes(v1);
            var b2 = BitConverter.GetBytes(v2);
            buffer.WriteToBuffer(b1);
            buffer.WriteToBuffer(b2);
            return true;
        }

19 View Source File : WavUtility.cs
License : GNU General Public License v3.0
Project Creator : a2659802

private static int WriteFileFormat(ref MemoryStream stream, int channels, int sampleRate, UInt16 bitDepth)
		{
			int count = 0;
			int total = 24;

			byte[] id = Encoding.ASCII.GetBytes("fmt ");
			count += WriteBytesToMemoryStream(ref stream, id, "FMT_ID");

			int subchunk1Size = 16; // 24 - 8
			count += WriteBytesToMemoryStream(ref stream, BitConverter.GetBytes(subchunk1Size), "SUBCHUNK_SIZE");

			UInt16 audioFormat = 1;
			count += WriteBytesToMemoryStream(ref stream, BitConverter.GetBytes(audioFormat), "AUDIO_FORMAT");

			UInt16 numChannels = Convert.ToUInt16(channels);
			count += WriteBytesToMemoryStream(ref stream, BitConverter.GetBytes(numChannels), "CHANNELS");

			count += WriteBytesToMemoryStream(ref stream, BitConverter.GetBytes(sampleRate), "SAMPLE_RATE");

			int byteRate = sampleRate * channels * BytesPerSample(bitDepth);
			count += WriteBytesToMemoryStream(ref stream, BitConverter.GetBytes(byteRate), "BYTE_RATE");

			UInt16 blockAlign = Convert.ToUInt16(channels * BytesPerSample(bitDepth));
			count += WriteBytesToMemoryStream(ref stream, BitConverter.GetBytes(blockAlign), "BLOCK_ALIGN");

			count += WriteBytesToMemoryStream(ref stream, BitConverter.GetBytes(bitDepth), "BITS_PER_SAMPLE");

			// Validate format
			Debug.replacedertFormat(count == total, "Unexpected wav fmt byte count: {0} == {1}", count, total);

			return count;
		}

19 View Source File : WavUtility.cs
License : GNU General Public License v3.0
Project Creator : a2659802

private static int WriteFileHeader(ref MemoryStream stream, int fileSize)
		{
			int count = 0;
			int total = 12;

			// riff chunk id
			byte[] riff = Encoding.ASCII.GetBytes("RIFF");
			count += WriteBytesToMemoryStream(ref stream, riff, "ID");

			// riff chunk size
			int chunkSize = fileSize - 8; // total size - 8 for the other two fields in the header
			count += WriteBytesToMemoryStream(ref stream, BitConverter.GetBytes(chunkSize), "CHUNK_SIZE");

			byte[] wave = Encoding.ASCII.GetBytes("WAVE");
			count += WriteBytesToMemoryStream(ref stream, wave, "FORMAT");

			// Validate header
			Debug.replacedertFormat(count == total, "Unexpected wav descriptor byte count: {0} == {1}", count, total);

			return count;
		}

19 View Source File : WavUtility.cs
License : GNU General Public License v3.0
Project Creator : a2659802

private static int WriteFileData(ref MemoryStream stream, AudioClip audioClip, UInt16 bitDepth)
		{
			int count = 0;
			int total = 8;

			// Copy float[] data from AudioClip
			float[] data = new float[audioClip.samples * audioClip.channels];
			audioClip.GetData(data, 0);

			byte[] bytes = ConvertAudioClipDataToInt16ByteArray(data);

			byte[] id = Encoding.ASCII.GetBytes("data");
			count += WriteBytesToMemoryStream(ref stream, id, "DATA_ID");

			int subchunk2Size = Convert.ToInt32(audioClip.samples * BlockSize_16Bit); // BlockSize (bitDepth)
			count += WriteBytesToMemoryStream(ref stream, BitConverter.GetBytes(subchunk2Size), "SAMPLES");

			// Validate header
			Debug.replacedertFormat(count == total, "Unexpected wav data id byte count: {0} == {1}", count, total);

			// Write bytes to stream
			count += WriteBytesToMemoryStream(ref stream, bytes, "DATA");

			// Validate audio data
			Debug.replacedertFormat(bytes.Length == subchunk2Size, "Unexpected AudioClip to wav subchunk2 size: {0} == {1}", bytes.Length, subchunk2Size);

			return count;
		}

19 View Source File : ExternalCommunicator.cs
License : Apache License 2.0
Project Creator : A7ocin

private byte[] AppendLength(byte[] input){
        byte[] newArray = new byte[input.Length + 4];
        input.CopyTo(newArray, 4);
        System.BitConverter.GetBytes(input.Length).CopyTo(newArray, 0);
        return newArray;
    }

19 View Source File : ConnectClient.cs
License : Apache License 2.0
Project Creator : AantCoder

public void SendMessage(byte[] message)
        {
            byte[] packlength = BitConverter.GetBytes(message.Length);

            CurrentSendRequestLength = message.Length + packlength.Length;
            CurrentReceiveRequestLength = 0;
            CurrentRequestStart = DateTime.UtcNow;
            try
            {
                ClientStream.Write(packlength, 0, packlength.Length);
                ClientStream.Write(message, 0, message.Length);            
            }
            finally
            {
                CurrentRequestStart = DateTime.MinValue;
            }

            LastSend = DateTime.UtcNow;
        }

19 View Source File : MessageBuilder.cs
License : MIT License
Project Creator : Abaudat

static byte[] FlagMessage(byte[] data, NetworkingFlags.Flags flag)
    {
        byte[] flaggedData = new byte[data.Length + sizeof(int) + 1];

        Buffer.BlockCopy(BitConverter.GetBytes(data.Length), 0, flaggedData, 0, sizeof(int));
        flaggedData[sizeof(int)] = (byte)flag;
        Buffer.BlockCopy(data, 0, flaggedData, sizeof(int) + 1, data.Length);

        return flaggedData;
    }

19 View Source File : HexUtilsTests.cs
License : MIT License
Project Creator : Abc-Arbitrage

[Test]
        public void should_append_value_as_hex_1()
        {
            StringBuffer buffer = new StringBuffer(1024);
            int x = 0x1234abcd;
            var bytes = BitConverter.GetBytes(x);
            byte* x_ptr = (byte*)&x;
            HexUtils.AppendValueAsHex(buffer, x_ptr, sizeof(int));
            var s = buffer.ToString();
            var expected = BitConverter.IsLittleEndian ? "cdab3412" : "1234abcd";
            replacedert.That(s, Is.EqualTo(expected));
        }

19 View Source File : HexUtilsTests.cs
License : MIT License
Project Creator : Abc-Arbitrage

[Test]
        public void should_append_value_as_hex_2()
        {
            StringBuffer buffer = new StringBuffer(1024);
            int x = 0x01020304;
            var bytes = BitConverter.GetBytes(x);
            byte* x_ptr = (byte*)&x;
            HexUtils.AppendValueAsHex(buffer, x_ptr, sizeof(int));
            var s = buffer.ToString();
            var expected = BitConverter.IsLittleEndian ? "04030201" : "01020304";
            replacedert.That(s, Is.EqualTo(expected));
        }

19 View Source File : HexUtilsTests.cs
License : MIT License
Project Creator : Abc-Arbitrage

[Test]
        public void should_append_value_as_hex_3()
        {
            StringBuffer buffer = new StringBuffer(1024);
            int x = 0x10203040;
            var bytes = BitConverter.GetBytes(x);
            byte* x_ptr = (byte*)&x;
            HexUtils.AppendValueAsHex(buffer, x_ptr, sizeof(int));
            var s = buffer.ToString();
            var expected = BitConverter.IsLittleEndian ? "40302010" : "10203040";
            replacedert.That(s, Is.EqualTo(expected));
        }

19 View Source File : P2PManager.cs
License : MIT License
Project Creator : absurd-joy

void PackInt32(int value, byte[] buf, ref int offset)
		{
			Buffer.BlockCopy(BitConverter.GetBytes(value), 0, buf, offset, 4);
			offset = offset + 4;
		}

19 View Source File : StreamString.cs
License : MIT License
Project Creator : actions

public async Task WriteInt32Async(Int32 value, CancellationToken cancellationToken)
        {
            byte[] int32Bytes = BitConverter.GetBytes(value);
            Task op = _ioStream.WriteAsync(int32Bytes, 0, sizeof(Int32), cancellationToken);
            await op.WithCancellation(cancellationToken);
        }

19 View Source File : Serializer.cs
License : MIT License
Project Creator : ADeltaX

public static byte[] FromInt32(int data, DateTimeOffset? timestamp = null)
            => BitConverter.GetBytes(data).AppendTimestamp(timestamp);

19 View Source File : Program.cs
License : MIT License
Project Creator : adospace

private static async Task<bool> SendreplacedemblyToEmulatorAsync(string replacedemblyPath, bool debugging = true)
        {
            
            //ThreadHelper.ThrowIfNotOnUIThread();

            //outputPane.OutputString($"Sending to emulator new replacedembly (debugging={debugging})...");
            //outputPane.Activate(); // Brings this pane into view

            var client = new TcpClient
            {
                ReceiveTimeout = 15000,
                SendTimeout = 15000
            };

            try
            {
               
                await client.ConnectAsync(IPAddress.Loopback, 45820);

                var replacedemblyRaw = await FileUtil.ReadAllFileAsync(replacedemblyPath);

                var networkStream = client.GetStream();

                var lengthBytes = BitConverter.GetBytes(replacedemblyRaw.Length);
                await networkStream.WriteAsync(lengthBytes, 0, lengthBytes.Length);

                await networkStream.WriteAsync(replacedemblyRaw, 0, replacedemblyRaw.Length);

                await networkStream.FlushAsync();

                var replacedemblySymbolStorePath = Path.Combine(Path.GetDirectoryName(replacedemblyPath), Path.GetFileNameWithoutExtension(replacedemblyPath) + ".pdb");

                if (File.Exists(replacedemblySymbolStorePath) && debugging)
                {
                    var replacedemblySynmbolStoreRaw = await FileUtil.ReadAllFileAsync(replacedemblySymbolStorePath);

                    lengthBytes = BitConverter.GetBytes(replacedemblySynmbolStoreRaw.Length);

                    await networkStream.WriteAsync(lengthBytes, 0, lengthBytes.Length);

                    await networkStream.WriteAsync(replacedemblySynmbolStoreRaw, 0, replacedemblySynmbolStoreRaw.Length);

                    await networkStream.FlushAsync();
                }
                else
                {
                    lengthBytes = BitConverter.GetBytes(0);

                    await networkStream.WriteAsync(lengthBytes, 0, lengthBytes.Length);

                    await networkStream.FlushAsync();
                }

                var booleanBuffer = new byte[1];
                if (await networkStream.ReadAsync(booleanBuffer, 0, 1) == 0)
                    throw new SocketException();

                Console.WriteLine($"Sent new replacedembly ({replacedemblyRaw.Length} bytes) to emulator{Environment.NewLine}");
            }
            catch (Exception ex)
            {
                Console.WriteLine([email protected]"
Unable to connect to ReactorUI Hot Reload module
Please ensure that:
1) Only one device is running among emulators and physical devices
2) Application is running either in debug or release mode
3) RxApplication call WithHotReload()
Socket exception: {ex.Message}
");
                return false;
            }
            finally
            {
                client.Close();
            }

            return true;
        }

19 View Source File : ReloadCommand.cs
License : MIT License
Project Creator : adospace

private static async Task<bool> SendreplacedemblyToEmulatorAsync(string replacedemblyPath, IVsOutputWindowPane outputPane, bool debugging)
        {
            await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
            //ThreadHelper.ThrowIfNotOnUIThread();

            //outputPane.OutputString($"Sending to emulator new replacedembly (debugging={debugging})...");
            //outputPane.Activate(); // Brings this pane into view

            var client = new TcpClient
            {
                ReceiveTimeout = 15000,
                SendTimeout = 15000
            };

            try
            {
                await client.ConnectAsync(IPAddress.Loopback, 45820);

                var replacedemblyRaw = await FileUtil.ReadAllFileAsync(replacedemblyPath);

                var networkStream = client.GetStream();

                var lengthBytes = BitConverter.GetBytes(replacedemblyRaw.Length);
                await networkStream.WriteAsync(lengthBytes, 0, lengthBytes.Length);
                
                await networkStream.WriteAsync(replacedemblyRaw, 0, replacedemblyRaw.Length);

                await networkStream.FlushAsync();

                var replacedemblySymbolStorePath = Path.Combine(Path.GetDirectoryName(replacedemblyPath), Path.GetFileNameWithoutExtension(replacedemblyPath) + ".pdb");

                if (File.Exists(replacedemblySymbolStorePath) && debugging)
                {
                    var replacedemblySynmbolStoreRaw = await FileUtil.ReadAllFileAsync(replacedemblySymbolStorePath);

                    lengthBytes = BitConverter.GetBytes(replacedemblySynmbolStoreRaw.Length);

                    await networkStream.WriteAsync(lengthBytes, 0, lengthBytes.Length);

                    await networkStream.WriteAsync(replacedemblySynmbolStoreRaw, 0, replacedemblySynmbolStoreRaw.Length);

                    await networkStream.FlushAsync();
                }
                else
                {
                    lengthBytes = BitConverter.GetBytes(0);

                    await networkStream.WriteAsync(lengthBytes, 0, lengthBytes.Length);

                    await networkStream.FlushAsync();
                }

                var booleanBuffer = new byte[1];
                if (await networkStream.ReadAsync(booleanBuffer, 0, 1) == 0)
                    throw new SocketException();

                outputPane.OutputStringThreadSafe($"Sent new replacedembly ({replacedemblyRaw.Length} bytes) to emulator{Environment.NewLine}");
            }
            catch (Exception ex)
            {
                outputPane.OutputStringThreadSafe([email protected]"
Unable to connect to ReactorUI Hot Reload module
Please ensure that:
1) Only one device is running among emulators and physical devices
2) Application is running either in debug or release mode
3) RxApplication call WithHotReload()
Socket exception: {ex.Message}
");
                return false;
            }
            finally
            {
                client.Close();
            }

            return true;
        }

19 View Source File : HotReloadCommand.cs
License : MIT License
Project Creator : adospace

private static async Task<bool> SendreplacedemblyToEmulatorAsync(ProgressMonitor progressMonitor, string replacedemblyPath, bool debugging)
        {
            var client = new TcpClient
            {
                ReceiveTimeout = 15000,
                SendTimeout = 15000
            };

            try
            {
                await client.ConnectAsync(IPAddress.Loopback, 45820);

                var replacedemblyRaw = await FileUtil.ReadAllFileAsync(replacedemblyPath);

                var networkStream = client.GetStream();

                var lengthBytes = BitConverter.GetBytes(replacedemblyRaw.Length);
                await networkStream.WriteAsync(lengthBytes, 0, lengthBytes.Length);

                await networkStream.WriteAsync(replacedemblyRaw, 0, replacedemblyRaw.Length);

                await networkStream.FlushAsync();

                var replacedemblySymbolStorePath = Path.Combine(Path.GetDirectoryName(replacedemblyPath), Path.GetFileNameWithoutExtension(replacedemblyPath) + ".pdb");

                if (File.Exists(replacedemblySymbolStorePath) && debugging)
                {
                    var replacedemblySynmbolStoreRaw = await FileUtil.ReadAllFileAsync(replacedemblySymbolStorePath);

                    lengthBytes = BitConverter.GetBytes(replacedemblySynmbolStoreRaw.Length);

                    await networkStream.WriteAsync(lengthBytes, 0, lengthBytes.Length);

                    await networkStream.WriteAsync(replacedemblySynmbolStoreRaw, 0, replacedemblySynmbolStoreRaw.Length);

                    await networkStream.FlushAsync();
                }
                else
                {
                    lengthBytes = BitConverter.GetBytes(0);

                    await networkStream.WriteAsync(lengthBytes, 0, lengthBytes.Length);

                    await networkStream.FlushAsync();
                }

                var booleanBuffer = new byte[1];
                if (await networkStream.ReadAsync(booleanBuffer, 0, 1) == 0)
                    throw new SocketException();

                await progressMonitor.Log.WriteLineAsync($"Sent new replacedembly ({replacedemblyRaw.Length} bytes) to emulator");
            }
            catch (Exception ex)
            {
                await progressMonitor.ErrorLog.WriteLineAsync([email protected]"
Unable to connect to ReactorUI Hot Reload module
Please ensure that:
1) Only one device is running among emulators and physical devices
2) Application is running either in debug or release mode
3) RxApplication call WithHotReload()
Socket exception: {ex.Message}");

                return false;
            }
            finally
            {
                client.Close();
            }

            return true;
        }

19 View Source File : FsBufferedReaderWriter.cs
License : MIT License
Project Creator : Adoxio

protected void WriteInt(int value)
		{
			var raw = BitConverter.GetBytes(value);
			this.fileStream.Write(raw, 0, raw.Length);
		}

19 View Source File : BytesWriter.cs
License : MIT License
Project Creator : adrenak

public BytesWriter WriteInt(Int32 value) {
            var bytes = BitConverter.GetBytes(value);
            EndianUtility.EndianCorrection(bytes);
            WriteBytes(bytes);
            return this;
        }

19 View Source File : BytesWriter.cs
License : MIT License
Project Creator : adrenak

public BytesWriter WriteVector3Array(Vector3[] array) {
            var lenB = BitConverter.GetBytes(array.Length);
            EndianUtility.EndianCorrection(lenB);
            WriteBytes(lenB);

            foreach (var e in array)
                WriteVector3(e);

            return this;
        }

19 View Source File : BytesWriter.cs
License : MIT License
Project Creator : adrenak

public BytesWriter WriteVector2Array(Vector2[] array) {
            var lenB = BitConverter.GetBytes(array.Length);
            EndianUtility.EndianCorrection(lenB);
            WriteBytes(lenB);

            foreach (var e in array)
                WriteVector2(e);

            return this;
        }

19 View Source File : BytesWriter.cs
License : MIT License
Project Creator : adrenak

public BytesWriter WriteRectArray(Rect[] array) {
            var lenB = BitConverter.GetBytes(array.Length);
            EndianUtility.EndianCorrection(lenB);
            WriteBytes(lenB);

            foreach (var e in array)
                WriteRect(e);

            return this;
        }

19 View Source File : Extensions.cs
License : MIT License
Project Creator : adrenak

public static byte[] GetBytes(this int value) {
            return BitConverter.GetBytes(value);
        }

19 View Source File : testUtil.cs
License : Apache License 2.0
Project Creator : advancer68

public static void PackInInt(this byte[] self, int value, int index)
    {
        var bytes = BitConverter.GetBytes(value);
        Array.Copy(bytes, 0, self, index, bytes.Length);
    }

19 View Source File : ByteBuf.cs
License : Apache License 2.0
Project Creator : advancer68

public void WriteInt32(int value)
    {
        var bytes = BitConverter.GetBytes(value);
        WriteBytesFrom(bytes);
    }

19 View Source File : BytePacker.cs
License : Apache License 2.0
Project Creator : advancer68

public byte[] Pack(byte[] content)
    {
        pkgLengthBytes = BitConverter.GetBytes(content.Length);
        pkgLengthByteSize = pkgLengthBytes.Length;
        var buf = new byte[content.Length + pkgLengthByteSize];
        int offset = 0;
        Array.Copy(pkgLengthBytes, buf, pkgLengthBytes.Length);
        offset += pkgLengthBytes.Length;
        Array.Copy(content, 0, buf, offset, content.Length);
        return buf;
    }

19 View Source File : StringCompressor.cs
License : GNU General Public License v3.0
Project Creator : aelariane

public static string CompressString(string text)
        {
            byte[] bytes = Encoding.UTF8.GetBytes(text);
            MemoryStream memoryStream = new MemoryStream();
            using (GZipStream gzipStream = new GZipStream(memoryStream, CompressionMode.Compress, true))
            {
                gzipStream.Write(bytes, 0, bytes.Length);
            }
            memoryStream.Position = 0L;
            byte[] array = new byte[memoryStream.Length];
            memoryStream.Read(array, 0, array.Length);
            byte[] array2 = new byte[array.Length + 4];
            Buffer.BlockCopy(array, 0, array2, 4, array.Length);
            Buffer.BlockCopy(BitConverter.GetBytes(bytes.Length), 0, array2, 0, 4);
            return Convert.ToBase64String(array2);
        }

19 View Source File : NumericExtensions.cs
License : MIT License
Project Creator : AElfProject

public static byte[] ToBytes(this int n, bool bigEndian = true)
        {
            var bytes = BitConverter.GetBytes(n);
            return GetBytesWithEndian(bytes, bigEndian);
        }

19 View Source File : ManualMap.cs
License : Apache License 2.0
Project Creator : aequabit

private static bool LoadDependencies(JLibrary.PortableExecutable.PortableExecutable image, IntPtr hProcess, int processId)
        {
            List<string> list = new List<string>();
            string lpBuffer = string.Empty;
            bool flag = false;
            foreach (IMAGE_IMPORT_DESCRIPTOR image_import_descriptor in image.EnumImports())
            {
                if ((image.ReadString((long) image.GetPtrFromRVA(image_import_descriptor.Name), SeekOrigin.Begin, out lpBuffer, -1, null) && !string.IsNullOrEmpty(lpBuffer)) && GetRemoteModuleHandle(lpBuffer, processId).IsNull())
                {
                    list.Add(lpBuffer);
                }
            }
            if (list.Count > 0)
            {
                byte[] data = ExtractManifest(image);
                string str2 = string.Empty;
                if (data == null)
                {
                    if (string.IsNullOrEmpty(image.FileLocation) || !File.Exists(Path.Combine(Path.GetDirectoryName(image.FileLocation), Path.GetFileName(image.FileLocation) + ".manifest")))
                    {
                        IntPtr[] ptrArray = InjectionMethod.Create(InjectionMethodType.Standard).InjectAll(list.ToArray(), hProcess);
                        foreach (IntPtr ptr in ptrArray)
                        {
                            if (ptr.IsNull())
                            {
                                return false;
                            }
                        }
                        return true;
                    }
                    str2 = Path.Combine(Path.GetDirectoryName(image.FileLocation), Path.GetFileName(image.FileLocation) + ".manifest");
                }
                else
                {
                    str2 = Utils.WriteTempData(data);
                }
                if (string.IsNullOrEmpty(str2))
                {
                    return false;
                }
                IntPtr ptr2 = WinAPI.VirtualAllocEx(hProcess, IntPtr.Zero, (uint) RESOLVER_STUB.Length, 0x3000, 0x40);
                IntPtr lpAddress = WinAPI.CreateRemotePointer(hProcess, Encoding.ASCII.GetBytes(str2 + "\0"), 4);
                IntPtr ptr4 = WinAPI.CreateRemotePointer(hProcess, Encoding.ASCII.GetBytes(string.Join("\0", list.ToArray()) + "\0"), 4);
                if (!ptr2.IsNull())
                {
                    byte[] array = (byte[]) RESOLVER_STUB.Clone();
                    uint lpNumberOfBytesRead = 0;
                    BitConverter.GetBytes(FN_CREATEACTCTXA.Subtract(ptr2.Add(((long) 0x3fL))).ToInt32()).CopyTo(array, 0x3b);
                    BitConverter.GetBytes(FN_ACTIVATEACTCTX.Subtract(ptr2.Add(((long) 0x58L))).ToInt32()).CopyTo(array, 0x54);
                    BitConverter.GetBytes(FN_GETMODULEHANDLEA.Subtract(ptr2.Add(((long) 0x84L))).ToInt32()).CopyTo(array, 0x80);
                    BitConverter.GetBytes(FN_LOADLIBRARYA.Subtract(ptr2.Add(((long) 0x92L))).ToInt32()).CopyTo(array, 0x8e);
                    BitConverter.GetBytes(FN_DEACTIVATEACTCTX.Subtract(ptr2.Add(((long) 200L))).ToInt32()).CopyTo(array, 0xc4);
                    BitConverter.GetBytes(FN_RELEASEACTCTX.Subtract(ptr2.Add(((long) 0xd1L))).ToInt32()).CopyTo(array, 0xcd);
                    BitConverter.GetBytes(lpAddress.ToInt32()).CopyTo(array, 0x1f);
                    BitConverter.GetBytes(list.Count).CopyTo(array, 40);
                    BitConverter.GetBytes(ptr4.ToInt32()).CopyTo(array, 0x31);
                    if (WinAPI.WriteProcessMemory(hProcess, ptr2, array, array.Length, out lpNumberOfBytesRead) && (lpNumberOfBytesRead == array.Length))
                    {
                        uint num2 = WinAPI.RunThread(hProcess, ptr2, 0, 0x1388);
                        flag = (num2 != uint.MaxValue) && (num2 != 0);
                    }
                    WinAPI.VirtualFreeEx(hProcess, ptr4, 0, 0x8000);
                    WinAPI.VirtualFreeEx(hProcess, lpAddress, 0, 0x8000);
                    WinAPI.VirtualFreeEx(hProcess, ptr2, 0, 0x8000);
                }
            }
            return flag;
        }

19 View Source File : ManualMap.cs
License : Apache License 2.0
Project Creator : aequabit

private static IntPtr MapModule(JLibrary.PortableExecutable.PortableExecutable image, IntPtr hProcess, bool preserveHeaders = false)
        {
            if (hProcess.IsNull() || hProcess.Compare(-1L))
            {
                throw new ArgumentException("Invalid process handle.", "hProcess");
            }
            if (image == null)
            {
                throw new ArgumentException("Cannot map a non-existant PE Image.", "image");
            }
            int processId = WinAPI.GetProcessId(hProcess);
            if (processId == 0)
            {
                throw new ArgumentException("Provided handle doesn't have sufficient permissions to inject", "hProcess");
            }
            IntPtr zero = IntPtr.Zero;
            IntPtr ptr = IntPtr.Zero;
            uint lpNumberOfBytesRead = 0;
            try
            {
                zero = WinAPI.VirtualAllocEx(hProcess, IntPtr.Zero, image.NTHeader.OptionalHeader.SizeOfImage, 0x3000, 4);
                if (zero.IsNull())
                {
                    throw new InvalidOperationException("Unable to allocate memory in the remote process.");
                }
                PatchRelocations(image, zero);
                LoadDependencies(image, hProcess, processId);
                PatchImports(image, hProcess, processId);
                if (preserveHeaders)
                {
                    long num3 = (long) (((image.DOSHeader.e_lfanew + Marshal.SizeOf(typeof(IMAGE_FILE_HEADER))) + ((long) 4L)) + image.NTHeader.FileHeader.SizeOfOptionalHeader);
                    byte[] buffer = new byte[num3];
                    if (image.Read(0L, SeekOrigin.Begin, buffer))
                    {
                        WinAPI.WriteProcessMemory(hProcess, zero, buffer, buffer.Length, out lpNumberOfBytesRead);
                    }
                }
                MapSections(image, hProcess, zero);
                if (image.NTHeader.OptionalHeader.AddressOfEntryPoint <= 0)
                {
                    return zero;
                }
                byte[] array = (byte[]) DLLMAIN_STUB.Clone();
                BitConverter.GetBytes(zero.ToInt32()).CopyTo(array, 11);
                ptr = WinAPI.VirtualAllocEx(hProcess, IntPtr.Zero, (uint) DLLMAIN_STUB.Length, 0x3000, 0x40);
                if (ptr.IsNull() || (!WinAPI.WriteProcessMemory(hProcess, ptr, array, array.Length, out lpNumberOfBytesRead) || (lpNumberOfBytesRead != array.Length)))
                {
                    throw new InvalidOperationException("Unable to write stub to the remote process.");
                }
                IntPtr hObject = WinAPI.CreateRemoteThread(hProcess, 0, 0, ptr, (uint) zero.Add(((long) image.NTHeader.OptionalHeader.AddressOfEntryPoint)).ToInt32(), 0, 0);
                if (WinAPI.WaitForSingleObject(hObject, 0x1388) != 0L)
                {
                    return zero;
                }
                WinAPI.GetExitCodeThread(hObject, out lpNumberOfBytesRead);
                if (lpNumberOfBytesRead == 0)
                {
                    WinAPI.VirtualFreeEx(hProcess, zero, 0, 0x8000);
                    throw new Exception("Entry method of module reported a failure " + Marshal.GetLastWin32Error().ToString());
                }
                WinAPI.VirtualFreeEx(hProcess, ptr, 0, 0x8000);
                WinAPI.CloseHandle(hObject);
            }
            catch (Exception exception)
            {
                if (!zero.IsNull())
                {
                    WinAPI.VirtualFreeEx(hProcess, zero, 0, 0x8000);
                }
                if (!ptr.IsNull())
                {
                    WinAPI.VirtualFreeEx(hProcess, zero, 0, 0x8000);
                }
                zero = IntPtr.Zero;
                throw exception;
            }
            return zero;
        }

19 View Source File : StandardInjectionMethod.cs
License : Apache License 2.0
Project Creator : aequabit

protected virtual IntPtr CreateMultiLoadStub(string[] paths, IntPtr hProcess, out IntPtr pModuleBuffer, uint nullmodule = 0)
        {
            IntPtr ptr6;
            pModuleBuffer = IntPtr.Zero;
            IntPtr zero = IntPtr.Zero;
            try
            {
                IntPtr moduleHandleA = WinAPI.GetModuleHandleA("kernel32.dll");
                IntPtr procAddress = WinAPI.GetProcAddress(moduleHandleA, "LoadLibraryA");
                IntPtr ptr = WinAPI.GetProcAddress(moduleHandleA, "GetModuleHandleA");
                if (procAddress.IsNull() || ptr.IsNull())
                {
                    throw new Exception("Unable to find necessary function entry points in the remote process");
                }
                pModuleBuffer = WinAPI.VirtualAllocEx(hProcess, IntPtr.Zero, ((uint) paths.Length) << 2, 0x3000, 4);
                IntPtr ptr5 = WinAPI.CreateRemotePointer(hProcess, Encoding.ASCII.GetBytes(string.Join("\0", paths) + "\0"), 4);
                if (pModuleBuffer.IsNull() || ptr5.IsNull())
                {
                    throw new InvalidOperationException("Unable to allocate memory in the remote process");
                }
                try
                {
                    uint lpNumberOfBytesRead = 0;
                    byte[] array = new byte[paths.Length << 2];
                    for (int i = 0; i < (array.Length >> 2); i++)
                    {
                        BitConverter.GetBytes(nullmodule).CopyTo(array, (int) (i << 2));
                    }
                    WinAPI.WriteProcessMemory(hProcess, pModuleBuffer, array, array.Length, out lpNumberOfBytesRead);
                    byte[] buffer2 = (byte[]) MULTILOAD_STUB.Clone();
                    zero = WinAPI.VirtualAllocEx(hProcess, IntPtr.Zero, (uint) buffer2.Length, 0x3000, 0x40);
                    if (zero.IsNull())
                    {
                        throw new InvalidOperationException("Unable to allocate memory in the remote process");
                    }
                    BitConverter.GetBytes(ptr5.ToInt32()).CopyTo(buffer2, 7);
                    BitConverter.GetBytes(paths.Length).CopyTo(buffer2, 15);
                    BitConverter.GetBytes(pModuleBuffer.ToInt32()).CopyTo(buffer2, 0x18);
                    BitConverter.GetBytes(ptr.Subtract(zero.Add(((long) 0x38L))).ToInt32()).CopyTo(buffer2, 0x34);
                    BitConverter.GetBytes(procAddress.Subtract(zero.Add(((long) 0x45L))).ToInt32()).CopyTo(buffer2, 0x41);
                    if (!(WinAPI.WriteProcessMemory(hProcess, zero, buffer2, buffer2.Length, out lpNumberOfBytesRead) && (lpNumberOfBytesRead == buffer2.Length)))
                    {
                        throw new Exception("Error creating the remote function stub.");
                    }
                    ptr6 = zero;
                }
                finally
                {
                    WinAPI.VirtualFreeEx(hProcess, pModuleBuffer, 0, 0x8000);
                    WinAPI.VirtualFreeEx(hProcess, ptr5, 0, 0x8000);
                    if (!zero.IsNull())
                    {
                        WinAPI.VirtualFreeEx(hProcess, zero, 0, 0x8000);
                    }
                    pModuleBuffer = IntPtr.Zero;
                }
            }
            catch (Exception exception)
            {
                this.SetLastError(exception);
                ptr6 = IntPtr.Zero;
            }
            return ptr6;
        }

19 View Source File : StandardInjectionMethod.cs
License : Apache License 2.0
Project Creator : aequabit

public override bool[] UnloadAll(IntPtr[] hModules, IntPtr hProcess)
        {
            bool[] flagArray2;
            this.ClearErrors();
            IntPtr zero = IntPtr.Zero;
            IntPtr ptr = IntPtr.Zero;
            IntPtr ptr3 = IntPtr.Zero;
            try
            {
                int num2;
                uint lpNumberOfBytesRead = 0;
                IntPtr procAddress = WinAPI.GetProcAddress(WinAPI.GetModuleHandleA("kernel32.dll"), "FreeLibrary");
                if (procAddress.IsNull())
                {
                    throw new Exception("Unable to find necessary function entry points in the remote process");
                }
                zero = WinAPI.VirtualAllocEx(hProcess, IntPtr.Zero, ((uint) hModules.Length) << 2, 0x3000, 4);
                ptr = WinAPI.VirtualAllocEx(hProcess, IntPtr.Zero, (uint) ((hModules.Length + 1) << 2), 0x3000, 4);
                ptr3 = WinAPI.VirtualAllocEx(hProcess, IntPtr.Zero, (uint) MULTIUNLOAD_STUB.Length, 0x3000, 0x40);
                if ((zero.IsNull() || ptr.IsNull()) || ptr3.IsNull())
                {
                    throw new InvalidOperationException("Unable to allocate memory in the remote process");
                }
                byte[] array = new byte[(hModules.Length + 1) << 2];
                for (num2 = 0; num2 < hModules.Length; num2++)
                {
                    BitConverter.GetBytes(hModules[num2].ToInt32()).CopyTo(array, (int) (num2 << 2));
                }
                WinAPI.WriteProcessMemory(hProcess, ptr, array, array.Length, out lpNumberOfBytesRead);
                byte[] buffer2 = (byte[]) MULTIUNLOAD_STUB.Clone();
                BitConverter.GetBytes(ptr.ToInt32()).CopyTo(buffer2, 7);
                BitConverter.GetBytes(zero.ToInt32()).CopyTo(buffer2, 15);
                BitConverter.GetBytes(procAddress.Subtract(ptr3.Add(((long) 0x38L))).ToInt32()).CopyTo(buffer2, 0x34);
                if (!(WinAPI.WriteProcessMemory(hProcess, ptr3, buffer2, buffer2.Length, out lpNumberOfBytesRead) && (lpNumberOfBytesRead == buffer2.Length)))
                {
                    throw new InvalidOperationException("Unable to write the function stub to the remote process.");
                }
                if (WinAPI.RunThread(hProcess, ptr3, 0, 0x3e8) == uint.MaxValue)
                {
                    throw new InvalidOperationException("Error occurred when running remote function stub.");
                }
                byte[] buffer3 = WinAPI.ReadRemoteMemory(hProcess, zero, ((uint) hModules.Length) << 2);
                if (buffer3 == null)
                {
                    throw new Exception("Unable to read results from the remote process.");
                }
                bool[] flagArray = new bool[hModules.Length];
                for (num2 = 0; num2 < flagArray.Length; num2++)
                {
                    flagArray[num2] = BitConverter.ToInt32(buffer3, num2 << 2) != 0;
                }
                flagArray2 = flagArray;
            }
            catch (Exception exception)
            {
                this.SetLastError(exception);
                flagArray2 = null;
            }
            finally
            {
                WinAPI.VirtualFreeEx(hProcess, ptr3, 0, 0x8000);
                WinAPI.VirtualFreeEx(hProcess, zero, 0, 0x8000);
                WinAPI.VirtualFreeEx(hProcess, ptr, 0, 0x8000);
            }
            return flagArray2;
        }

See More Examples