System.Runtime.InteropServices.Marshal.GetDelegateForFunctionPointer(System.IntPtr, System.Type)

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

1627 Examples 7

19 Source : TestGame.cs
with Microsoft Public License
from 0x0ade

private T GetDelegate<T>(IntPtr ptr) where T : clreplaced
		{
			if (ptr == IntPtr.Zero)
				return null;
			return Marshal.GetDelegateForFunctionPointer(ptr, typeof(T)) as T;
		}

19 Source : PInvokeHooks.cs
with zlib License
from 0x0ade

public static IntPtr CallWindowProc(IntPtr lpPrevWndFunc, IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam) {
            if (lpPrevWndFunc == IntPtr.Zero)
                return IntPtr.Zero;
            return (IntPtr) Marshal.GetDelegateForFunctionPointer(lpPrevWndFunc, typeof(MulticastDelegate))
                .DynamicInvoke(hWnd, Msg, wParam, lParam);
        }

19 Source : X86Assembly.cs
with MIT License
from 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 Source : UnmanagedLibrary.cs
with Mozilla Public License 2.0
from agebullhu

public TDelegate GetUnmanagedFunction<TDelegate>(string functionName) where TDelegate : clreplaced
		{
			IntPtr p = Platform.LoadProcedure(_handle, functionName);

			if (p == IntPtr.Zero)
			{
				throw new MissingMethodException("Unable to find function '" + functionName + "' in dynamically loaded library.");
			}

			// Ideally, we'd just make the constraint on TDelegate be
			// System.Delegate, but compiler error CS0702 (constrained can't be System.Delegate)
			// prevents that. So we make the constraint system.object and do the cast from object-->TDelegate.
			return (TDelegate)(object)Marshal.GetDelegateForFunctionPointer(p, typeof(TDelegate));
		}

19 Source : Opcode.cs
with MIT License
from 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 Source : NVAPI.cs
with MIT License
from AlexGyver

private static void GetDelegate<T>(uint id, out T newDelegate)
      where T : clreplaced {
      IntPtr ptr = nvapi_QueryInterface(id);
      if (ptr != IntPtr.Zero) {
        newDelegate =
          Marshal.GetDelegateForFunctionPointer(ptr, typeof(T)) as T;
      } else {
        newDelegate = null;
      }
    }

19 Source : common.cs
with MIT License
from allisterb

public static global::IntelMKL.XerblaEntry MklSetXerbla(global::IntelMKL.XerblaEntry xerbla)
        {
            var __arg0 = xerbla == null ? global::System.IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(xerbla);
            var __ret = __Internal.MklSetXerbla(__arg0);
            var __ptr0 = __ret;
            return __ptr0 == IntPtr.Zero ? null : (global::IntelMKL.XerblaEntry)Marshal.GetDelegateForFunctionPointer(__ptr0, typeof(global::IntelMKL.XerblaEntry));
        }

19 Source : common.cs
with MIT License
from allisterb

public static global::IntelMKL.ProgressEntry MklSetProgress(global::IntelMKL.ProgressEntry progress)
        {
            var __arg0 = progress == null ? global::System.IntPtr.Zero : Marshal.GetFunctionPointerForDelegate(progress);
            var __ret = __Internal.MklSetProgress(__arg0);
            var __ptr0 = __ret;
            return __ptr0 == IntPtr.Zero ? null : (global::IntelMKL.ProgressEntry)Marshal.GetDelegateForFunctionPointer(__ptr0, typeof(global::IntelMKL.ProgressEntry));
        }

19 Source : UnmangedLibrary.cs
with GNU General Public License v3.0
from AndreiFedarets

public T GetFunction<T>(string functionName) where T : clreplaced
        {
            IntPtr procedurePointer = Kernel32.GetProcAddress(Library, functionName);
            if (procedurePointer == IntPtr.Zero)
            {
                return null;
            }
            Delegate procedure = Marshal.GetDelegateForFunctionPointer(procedurePointer, typeof(T));
            object procedureObject = procedure;
            return (T)procedureObject;
        }

19 Source : DemoCommandPluginNet.cs
with MIT License
from aniskop

[DllExport("RegisterCallback", CallingConvention = CallingConvention.Cdecl)]
        public static void RegisterCallback(int index, IntPtr function)
        {
            if (index == COMMAND_FEEDBACK_CALLBACK)
            {
                commandFeedbackCallback = (IdeCommandFeedback)Marshal.GetDelegateForFunctionPointer(function, typeof(IdeCommandFeedback));
            }
        }

19 Source : DemoPlugin.cs
with MIT License
from aniskop

[DllExport("RegisterCallback", CallingConvention = CallingConvention.Cdecl)]
        public static void RegisterCallback(int index, IntPtr function)
        {
            switch (index)
            {
                case CREATE_WINDOW_CALLBACK:
                    createWindowCallback = (IdeCreateWindow)Marshal.GetDelegateForFunctionPointer(function, typeof(IdeCreateWindow));
                    break;
                case SET_TEXT_CALLBACK:
                    setTextCallback = (IdeSetText)Marshal.GetDelegateForFunctionPointer(function, typeof(IdeSetText));
                    break;
            }
        }

19 Source : VPOManager.cs
with GNU General Public License v3.0
from anotak

private void ProcessingThread(object index)
		{
			// Get function pointers
			VPO_GetError GetError = (VPO_GetError)Marshal.GetDelegateForFunctionPointer(GetProcAddress(dlls[(int)index], "VPO_GetError"), typeof(VPO_GetError));
			VPO_LoadWAD LoadWAD = (VPO_LoadWAD)Marshal.GetDelegateForFunctionPointer(GetProcAddress(dlls[(int)index], "VPO_LoadWAD"), typeof(VPO_LoadWAD));
			VPO_OpenMap OpenMap = (VPO_OpenMap)Marshal.GetDelegateForFunctionPointer(GetProcAddress(dlls[(int)index], "VPO_OpenMap"), typeof(VPO_OpenMap));
			VPO_FreeWAD FreeWAD = (VPO_FreeWAD)Marshal.GetDelegateForFunctionPointer(GetProcAddress(dlls[(int)index], "VPO_FreeWAD"), typeof(VPO_FreeWAD));
			VPO_CloseMap CloseMap = (VPO_CloseMap)Marshal.GetDelegateForFunctionPointer(GetProcAddress(dlls[(int)index], "VPO_CloseMap"), typeof(VPO_CloseMap));
			VPO_OpenDoorSectors OpenDoors = (VPO_OpenDoorSectors)Marshal.GetDelegateForFunctionPointer(GetProcAddress(dlls[(int)index], "VPO_OpenDoorSectors"), typeof(VPO_OpenDoorSectors)); //mxd
			VPO_TestSpot TestSpot = (VPO_TestSpot)Marshal.GetDelegateForFunctionPointer(GetProcAddress(dlls[(int)index], "VPO_TestSpot"), typeof(VPO_TestSpot));

			try
			{
				// Load the map
				bool isHexen = General.Map.HEXEN;
                if (LoadWAD(filename) != 0)
                {
                    throw new Exception("VPO is unable to read this file: " + GetError());
                }
				if(OpenMap(mapname, ref isHexen) != 0) throw new Exception("VPO is unable to open this map: " + GetError());
				OpenDoors(BuilderPlug.InterfaceForm.OpenDoors ? 1 : -1); //mxd

				// Processing
				Queue<TilePoint> todo = new Queue<TilePoint>(POINTS_PER_ITERATION);
				Queue<PointData> done = new Queue<PointData>(POINTS_PER_ITERATION);
				while(true)
				{
					lock(points)
					{
						// Flush done points to the results
						int numdone = done.Count;
						for(int i = 0; i < numdone; i++)
							results.Enqueue(done.Dequeue());
						
						// Get points from the waiting queue into my todo queue for processing
						int numtodo = Math.Min(POINTS_PER_ITERATION, points.Count);
						for(int i = 0; i < numtodo; i++)
							todo.Enqueue(points.Dequeue());
					}

					// Don't keep locking!
					if(todo.Count == 0)
						Thread.Sleep(31);
					
					// Process the points
					while(todo.Count > 0)
					{
						TilePoint p = todo.Dequeue();
						PointData pd = new PointData();
						pd.point = p;

						for(int i = 0; i < TEST_ANGLES.Length; i++)
						{
							pd.result = (PointResult)TestSpot(p.x, p.y, TEST_HEIGHT, TEST_ANGLES[i],
								ref pd.visplanes, ref pd.drawsegs, ref pd.openings, ref pd.solidsegs);
						}

						done.Enqueue(pd);
					}
				}
			}
			catch(ThreadInterruptedException)
			{
			}
			finally
			{
				CloseMap();
				FreeWAD();
			}
		}

19 Source : UnmanagedLibrary.cs
with BSD 3-Clause "New" or "Revised" License
from anoyetta

public TDelegate GetUnmanagedFunction<TDelegate>(string functionName)
            where TDelegate : clreplaced
        {
            IntPtr p = NativeMethod.GetProcAddress(m_hLibrary, functionName);

            // Failure is a common case, especially for adaptive code.
            if (p == IntPtr.Zero)
            {
                return null;
            }

            Delegate function = Marshal.GetDelegateForFunctionPointer(
                p, typeof(TDelegate));

            // Ideally, we'd just make the constraint on TDelegate be
            // System.Delegate, but compiler error CS0702
            // (constrained can't be System.Delegate)
            // prevents that. So we make the constraint system.object and do the
            // cast from object-->TDelegate.
            object o = function;

            return (TDelegate)o;
        }

19 Source : DLLFromMemory.cs
with MIT License
from arsium

void MemoryLoadLibrary(byte[] data)
    {
        if (data.Length < Marshal.SizeOf(typeof(IMAGE_DOS_HEADER))) throw new DllException("Not a valid executable file");
        IMAGE_DOS_HEADER DosHeader = BytesReadStructAt<IMAGE_DOS_HEADER>(data, 0);
        if (DosHeader.e_magic != Win.IMAGE_DOS_SIGNATURE) throw new BadImageFormatException("Not a valid executable file");

        if (data.Length < DosHeader.e_lfanew + Marshal.SizeOf(typeof(IMAGE_NT_HEADERS))) throw new DllException("Not a valid executable file");
        IMAGE_NT_HEADERS OrgNTHeaders = BytesReadStructAt<IMAGE_NT_HEADERS>(data, DosHeader.e_lfanew);

        if (OrgNTHeaders.Signature != Win.IMAGE_NT_SIGNATURE)       throw new BadImageFormatException("Not a valid PE file");
        if (OrgNTHeaders.FileHeader.Machine != GetMachineType())    throw new BadImageFormatException("Machine type doesn't fit (i386 vs. AMD64)");
        if ((OrgNTHeaders.OptionalHeader.SectionAlignment & 1) > 0) throw new BadImageFormatException("Wrong section alignment"); //Only support multiple of 2
        if (OrgNTHeaders.OptionalHeader.AddressOfEntryPoint == 0)   throw new DllException("Module has no entry point");

        SYSTEM_INFO systemInfo;
        Win.GetNativeSystemInfo(out systemInfo);
        uint lastSectionEnd = 0;
        int ofSection = Win.IMAGE_FIRST_SECTION(DosHeader.e_lfanew, OrgNTHeaders.FileHeader.SizeOfOptionalHeader);
        for (int i = 0; i != OrgNTHeaders.FileHeader.NumberOfSections; i++, ofSection += Sz.IMAGE_SECTION_HEADER)
        {
            IMAGE_SECTION_HEADER Section = BytesReadStructAt<IMAGE_SECTION_HEADER>(data, ofSection);
            uint endOfSection = Section.VirtualAddress + (Section.SizeOfRawData > 0 ? Section.SizeOfRawData : OrgNTHeaders.OptionalHeader.SectionAlignment);
            if (endOfSection > lastSectionEnd) lastSectionEnd = endOfSection;
        }

        uint alignedImageSize   = AlignValueUp(OrgNTHeaders.OptionalHeader.SizeOfImage, systemInfo.dwPageSize);
        uint alignedLastSection = AlignValueUp(lastSectionEnd, systemInfo.dwPageSize);
        if (alignedImageSize != alignedLastSection) throw new BadImageFormatException("Wrong section alignment");

        IntPtr oldHeader_OptionalHeader_ImageBase;
        if (Is64BitProcess) oldHeader_OptionalHeader_ImageBase = (IntPtr)unchecked((long)(OrgNTHeaders.OptionalHeader.ImageBaseLong));
        else                oldHeader_OptionalHeader_ImageBase = (IntPtr)unchecked((int)(OrgNTHeaders.OptionalHeader.ImageBaseLong>>32));

        // reserve memory for image of library
        pCode = Win.VirtualAlloc(oldHeader_OptionalHeader_ImageBase, (UIntPtr)OrgNTHeaders.OptionalHeader.SizeOfImage, AllocationType.RESERVE | AllocationType.COMMIT, MemoryProtection.READWRITE);
        //pCode = IntPtr.Zero; //test relocation with this

        // try to allocate memory at arbitrary position
        if (pCode == IntPtr.Zero) pCode = Win.VirtualAlloc(IntPtr.Zero, (UIntPtr)OrgNTHeaders.OptionalHeader.SizeOfImage, AllocationType.RESERVE | AllocationType.COMMIT, MemoryProtection.READWRITE);

        if (pCode == IntPtr.Zero) throw new DllException("Out of Memory");

        if (Is64BitProcess && PtrSpanBoundary(pCode, alignedImageSize, 32))
        {
            // Memory block may not span 4 GB (32 bit) boundaries.
            System.Collections.Generic.List<IntPtr> BlockedMemory = new System.Collections.Generic.List<IntPtr>();
            while (PtrSpanBoundary(pCode, alignedImageSize, 32))
            {
                BlockedMemory.Add(pCode);
                pCode = Win.VirtualAlloc(IntPtr.Zero, (UIntPtr)alignedImageSize, AllocationType.RESERVE | AllocationType.COMMIT, MemoryProtection.READWRITE);
                if (pCode == IntPtr.Zero) break;
            }
            foreach (IntPtr ptr in BlockedMemory) Win.VirtualFree(ptr, IntPtr.Zero, AllocationType.RELEASE);
            if (pCode == IntPtr.Zero) throw new DllException("Out of Memory");
        }

        // commit memory for headers
        IntPtr headers = Win.VirtualAlloc(pCode, (UIntPtr)OrgNTHeaders.OptionalHeader.SizeOfHeaders, AllocationType.COMMIT, MemoryProtection.READWRITE);
        if (headers == IntPtr.Zero) throw new DllException("Out of Memory");

        // copy PE header to code
        Marshal.Copy(data, 0, headers, (int)(OrgNTHeaders.OptionalHeader.SizeOfHeaders));
        pNTHeaders = PtrAdd(headers, DosHeader.e_lfanew);

        IntPtr locationDelta = PtrSub(pCode, oldHeader_OptionalHeader_ImageBase);
        if (locationDelta != IntPtr.Zero)
        {
            // update relocated position
            Marshal.OffsetOf(typeof(IMAGE_NT_HEADERS), "OptionalHeader");
            Marshal.OffsetOf(typeof(IMAGE_OPTIONAL_HEADER), "ImageBaseLong");
            IntPtr pImageBase = PtrAdd(pNTHeaders, Of.IMAGE_NT_HEADERS_OptionalHeader + (Is64BitProcess ? Of64.IMAGE_OPTIONAL_HEADER_ImageBase : Of32.IMAGE_OPTIONAL_HEADER_ImageBase));
            PtrWrite(pImageBase, pCode);
        }

        // copy sections from DLL file block to new memory location
        CopySections(ref OrgNTHeaders, pCode, pNTHeaders, data);

        // adjust base address of imported data
        _isRelocated = (locationDelta != IntPtr.Zero ? PerformBaseRelocation(ref OrgNTHeaders, pCode, locationDelta) : true);

        // load required dlls and adjust function table of imports
        ImportModules = BuildImportTable(ref OrgNTHeaders, pCode);

        // mark memory pages depending on section headers and release
        // sections that are marked as "discardable"
        FinalizeSections(ref OrgNTHeaders, pCode, pNTHeaders, systemInfo.dwPageSize);

        // TLS callbacks are executed BEFORE the main loading
        ExecuteTLS(ref OrgNTHeaders, pCode, pNTHeaders);

        // get entry point of loaded library
        IsDll = ((OrgNTHeaders.FileHeader.Characteristics & Win.IMAGE_FILE_DLL) != 0);
        if (OrgNTHeaders.OptionalHeader.AddressOfEntryPoint != 0)
        {
            if (IsDll)
            {
                // notify library about attaching to process
                IntPtr dllEntryPtr = PtrAdd(pCode, OrgNTHeaders.OptionalHeader.AddressOfEntryPoint);
                _dllEntry = (DllEntryDelegate)Marshal.GetDelegateForFunctionPointer(dllEntryPtr, typeof(DllEntryDelegate));

                _initialized = (_dllEntry != null && _dllEntry(pCode, DllReason.DLL_PROCESS_ATTACH, IntPtr.Zero));
                if (!_initialized) throw new DllException("Can't attach DLL to process");
            }
            else
            {
                IntPtr exeEntryPtr = PtrAdd(pCode, OrgNTHeaders.OptionalHeader.AddressOfEntryPoint);
                _exeEntry = (ExeEntryDelegate)Marshal.GetDelegateForFunctionPointer(exeEntryPtr, typeof(ExeEntryDelegate));
            }
        }
    }

19 Source : DLLFromMemory.cs
with MIT License
from arsium

static void ExecuteTLS(ref IMAGE_NT_HEADERS OrgNTHeaders, IntPtr pCode, IntPtr pNTHeaders)
    {
        if (OrgNTHeaders.OptionalHeader.TLSTable.VirtualAddress == 0) return;
        IMAGE_TLS_DIRECTORY tlsDir = PtrRead<IMAGE_TLS_DIRECTORY>(PtrAdd(pCode, OrgNTHeaders.OptionalHeader.TLSTable.VirtualAddress));
        IntPtr pCallBack = tlsDir.AddressOfCallBacks;
        if (pCallBack != IntPtr.Zero)
        {
            for (IntPtr Callback; (Callback = PtrRead<IntPtr>(pCallBack)) != IntPtr.Zero; pCallBack = PtrAdd(pCallBack, IntPtr.Size))
            {
                ImageTlsDelegate tls = (ImageTlsDelegate)Marshal.GetDelegateForFunctionPointer(Callback, typeof(ImageTlsDelegate));
                tls(pCode, DllReason.DLL_PROCESS_ATTACH, IntPtr.Zero);
            }
        }
    }

19 Source : ShellCodeLoader.cs
with MIT License
from arsium

private void Kernel32Delegates()
        {
            IntPtr ExportedVirtualAlloc = Imports.GetProcAddress(Imports.GetModuleHandle(Imports.KERNEL32), "VirtualAlloc");
            Imports.Delegates.VirtualAlloc VirtualAlloc = (Imports.Delegates.VirtualAlloc)Marshal.GetDelegateForFunctionPointer(ExportedVirtualAlloc, typeof(Imports.Delegates.VirtualAlloc));
            this.ptr = VirtualAlloc(IntPtr.Zero, (IntPtr)ShellCode.Length, Imports.TypeAlloc.MEM_COMMIT | Imports.TypeAlloc.MEM_RESERVE, Imports.PageProtection.PAGE_EXECUTE_READWRITE);

            UIntPtr writtenBytes;
            IntPtr ExportedWriteProcessMemory = Imports.GetProcAddress(Imports.GetModuleHandle(Imports.KERNEL32), "WriteProcessMemory");
            Imports.Delegates.WriteProcessMemory WriteProcessMemory = (Imports.Delegates.WriteProcessMemory)Marshal.GetDelegateForFunctionPointer(ExportedWriteProcessMemory, typeof(Imports.Delegates.WriteProcessMemory));
            WriteProcessMemory(Imports.GetCurrentProcess(), ptr, ShellCode, (UIntPtr)ShellCode.Length, out writtenBytes);

            Imports.PageProtection flOld;
            IntPtr ExportedVirtualProtect = Imports.GetProcAddress(Imports.GetModuleHandle(Imports.KERNEL32), "VirtualProtect");
            Imports.Delegates.VirtualProtect VirtualProtect = (Imports.Delegates.VirtualProtect)Marshal.GetDelegateForFunctionPointer(ExportedVirtualProtect, typeof(Imports.Delegates.VirtualProtect));
            VirtualProtect(ptr, RegionSize, Imports.PageProtection.PAGE_EXECUTE_READ, out flOld);

            ShellCodeCaller load = (ShellCodeCaller)Marshal.GetDelegateForFunctionPointer(ptr, typeof(ShellCodeCaller));
            load();

            IntPtr ExportedVirtualFree = Imports.GetProcAddress(Imports.GetModuleHandle(Imports.KERNEL32), "VirtualFree");
            Imports.Delegates.VirtualFree VirtualFree = (Imports.Delegates.VirtualFree)Marshal.GetDelegateForFunctionPointer(ExportedVirtualFree, typeof(Imports.Delegates.VirtualFree));
            Imports.VirtualFree(ptr, (uint)0, Imports.FreeType.MEM_RELEASE);
        }

19 Source : DLLFromMemory.cs
with MIT License
from arsium

public TDelegate GetDelegateFromFuncName<TDelegate>(string funcName) where TDelegate : clreplaced
    {
        if (!typeof(Delegate).IsreplacedignableFrom(typeof(TDelegate))) throw new ArgumentException(typeof(TDelegate).Name + " is not a delegate");
        TDelegate res = Marshal.GetDelegateForFunctionPointer((IntPtr)GetPtrFromFuncName(funcName), typeof(TDelegate)) as TDelegate;
        if (res == null) throw new DllException("Unable to get managed delegate");
        return res;
    }

19 Source : DLLFromMemory.cs
with MIT License
from arsium

public Delegate GetDelegateFromFuncName(string funcName, Type delegateType)
    {
        if (delegateType == null) throw new ArgumentNullException("delegateType");
        if (!typeof(Delegate).IsreplacedignableFrom(delegateType)) throw new ArgumentException(delegateType.Name + " is not a delegate");
        Delegate res = Marshal.GetDelegateForFunctionPointer(GetPtrFromFuncName(funcName), delegateType);
        if (res == null) throw new DllException("Unable to get managed delegate");
        return res;
    }

19 Source : ShellCodeLoader.cs
with MIT License
from arsium

private void Kernel32()
        {
            this.ptr = Imports.VirtualAlloc(IntPtr.Zero, (IntPtr)ShellCode.Length, Imports.TypeAlloc.MEM_COMMIT | Imports.TypeAlloc.MEM_RESERVE, Imports.PageProtection.PAGE_EXECUTE_READWRITE);
            UIntPtr writtenBytes;
            Imports.WriteProcessMemory(Imports.GetCurrentProcess(), ptr, ShellCode, (UIntPtr)ShellCode.Length, out writtenBytes);
            Imports.PageProtection flOld;
            Imports.VirtualProtect(ptr, RegionSize, Imports.PageProtection.PAGE_EXECUTE_READ, out flOld);
            ShellCodeCaller load = (ShellCodeCaller)Marshal.GetDelegateForFunctionPointer(ptr, typeof(ShellCodeCaller));
            load();
            Imports.VirtualFree(ptr, (uint)0, Imports.FreeType.MEM_RELEASE);
        }

19 Source : ShellCodeLoader.cs
with MIT License
from arsium

private void NTDelegates()
        {
            IntPtr ExportedNtAllocateVirtualMemory = Imports.GetProcAddress(Imports.GetModuleHandle(Imports.NTDLL), "NtAllocateVirtualMemory");
            Imports.Delegates.NtAllocateVirtualMemory NtAllocateVirtualMemory = (Imports.Delegates.NtAllocateVirtualMemory)Marshal.GetDelegateForFunctionPointer(ExportedNtAllocateVirtualMemory, typeof(Imports.Delegates.NtAllocateVirtualMemory));
            NtAllocateVirtualMemory(Imports.GetCurrentProcess(), ref ptr, IntPtr.Zero, ref RegionSize, Imports.TypeAlloc.MEM_COMMIT | Imports.TypeAlloc.MEM_RESERVE, Imports.PageProtection.PAGE_EXECUTE_READWRITE);

            UIntPtr bytesWritten;
            IntPtr ExportedNtWriteVirtualMemory = Imports.GetProcAddress(Imports.GetModuleHandle(Imports.NTDLL), "NtWriteVirtualMemory");
            Imports.Delegates.NtWriteVirtualMemory NtWriteVirtualMemory = (Imports.Delegates.NtWriteVirtualMemory)Marshal.GetDelegateForFunctionPointer(ExportedNtWriteVirtualMemory, typeof(Imports.Delegates.NtWriteVirtualMemory));
            NtWriteVirtualMemory(Imports.GetCurrentProcess(), ptr, ShellCode, (UIntPtr)ShellCode.Length, out bytesWritten);

            Imports.PageProtection flOld = new Imports.PageProtection();
            IntPtr ExportedNtProtectVirtualMemory = Imports.GetProcAddress(Imports.GetModuleHandle(Imports.NTDLL), "NtProtectVirtualMemory");
            Imports.Delegates.NtProtectVirtualMemory NtProtectVirtualMemory = (Imports.Delegates.NtProtectVirtualMemory)Marshal.GetDelegateForFunctionPointer(ExportedNtProtectVirtualMemory, typeof(Imports.Delegates.NtProtectVirtualMemory));
            NtProtectVirtualMemory(Imports.GetCurrentProcess(), ref ptr, ref RegionSize, Imports.PageProtection.PAGE_EXECUTE_READ, ref flOld);

            ShellCodeCaller load = (ShellCodeCaller)Marshal.GetDelegateForFunctionPointer(ptr, typeof(ShellCodeCaller));
            load();

            IntPtr ExportedNtFreeVirtualMemory = Imports.GetProcAddress(Imports.GetModuleHandle(Imports.NTDLL), "NtFreeVirtualMemory");
            Imports.Delegates.NtFreeVirtualMemory NtFreeVirtualMemory = (Imports.Delegates.NtFreeVirtualMemory)Marshal.GetDelegateForFunctionPointer(ExportedNtFreeVirtualMemory, typeof(Imports.Delegates.NtFreeVirtualMemory));
            NtFreeVirtualMemory(Imports.GetCurrentProcess(), ref ptr, ref RegionSize, Imports.FreeType.MEM_RELEASE);
        }

19 Source : Program.cs
with MIT License
from atredispartners

private static void LoadProxyStubsForCollectorService()
        {
            var intPtr = NativeMethods.LoadLibraryEx(Environment.Is64BitProcess
                    ? @"C:\Windows\System32\DiagSvcs\DiagnosticsHub.StandardCollector.Proxy.dll"
                    : @"C:\Windows\SysWOW64\DiagSvcs\DiagnosticsHub.StandardCollector.Proxy.dll",
                IntPtr.Zero, 0);

            if (intPtr == IntPtr.Zero)
                throw new Exception("Invalid proxy dll pointer");

            var procAddress = NativeMethods.GetProcAddress(intPtr, "ManualRegisterInterfaces");
            if (procAddress == IntPtr.Zero)
                throw new Exception("Invalid ManualRegisterInterfaces pointer");

            var manualRegisterInterfacesDelegate = (ManualRegisterInterfacesDelegate)Marshal.GetDelegateForFunctionPointer(procAddress, typeof(ManualRegisterInterfacesDelegate));
            Marshal.ThrowExceptionForHR(manualRegisterInterfacesDelegate());
        }

19 Source : NativeSysCall.cs
with BSD 3-Clause "New" or "Revised" License
from b4rtik

public static NTSTATUS NtCreateFile10(out Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle,
                Int32 desiredAccess,
                ref OBJECT_ATTRIBUTES objectAttributes,
                out IO_STATUS_BLOCK ioStatusBlock,
                ref Int64 allocationSize,
                UInt32 fileAttributes,
                System.IO.FileShare shareAccess,
                UInt32 createDisposition,
                UInt32 createOptions,
                IntPtr eaBuffer,
                UInt32 eaLength)
        {
            byte[] syscall = bNtCreateFile10;

            unsafe
            {
                fixed (byte* ptr = syscall)
                {

                    IntPtr memoryAddress = (IntPtr)ptr;

                    if (!VirtualProtect( memoryAddress,
                        (UIntPtr)syscall.Length, 0x40, out uint oldprotect))
                    {
                        throw new Win32Exception();
                    }

                    Delegates.NtCreateFile myreplacedemblyFunction = (Delegates.NtCreateFile)Marshal.GetDelegateForFunctionPointer(memoryAddress, typeof(Delegates.NtCreateFile));

                    return (NTSTATUS)myreplacedemblyFunction(out fileHandle,
                 desiredAccess,
                ref objectAttributes,
                out ioStatusBlock,
                ref allocationSize,
                 fileAttributes,
                 shareAccess,
                 createDisposition,
                 createOptions,
                 eaBuffer,
                 eaLength);
                }
            }
        }

19 Source : NativeSysCall.cs
with BSD 3-Clause "New" or "Revised" License
from b4rtik

public static NTSTATUS ZwCreateSection10(ref IntPtr section, uint desiredAccess, IntPtr pAttrs, ref LARGE_INTEGER pMaxSize, uint pageProt, uint allocationAttribs, IntPtr hFile)
        {
            byte[] syscall = bZwCreateSection10;

            unsafe
            {
                fixed (byte* ptr = syscall)
                {

                    IntPtr memoryAddress = (IntPtr)ptr;

                    if (!VirtualProtect( memoryAddress,
                        (UIntPtr)syscall.Length, 0x40, out uint oldprotect))
                    {
                        throw new Win32Exception();
                    }

                    Delegates.ZwCreateSection myreplacedemblyFunction = (Delegates.ZwCreateSection)Marshal.GetDelegateForFunctionPointer(memoryAddress, typeof(Delegates.ZwCreateSection));

                    return (NTSTATUS)myreplacedemblyFunction(out section, desiredAccess,  pAttrs,  ref pMaxSize,  pageProt,  allocationAttribs, hFile);
                }
            }
        }

19 Source : NativeSysCall.cs
with BSD 3-Clause "New" or "Revised" License
from b4rtik

public static NTSTATUS ZwOpenProcess10(ref IntPtr hProcess, ProcessAccessFlags processAccess, OBJECT_ATTRIBUTES objAttribute, ref CLIENT_ID clientid)
        {
            byte[] syscall = bZwOpenProcess10;

            unsafe
            {
                fixed (byte* ptr = syscall)
                {

                    IntPtr memoryAddress = (IntPtr)ptr;

                    if (!VirtualProtect( memoryAddress,
                        (UIntPtr)syscall.Length, 0x40, out uint oldprotect))
                    {
                        throw new Win32Exception();
                    }

                    Delegates.ZwOpenProcess myreplacedemblyFunction = (Delegates.ZwOpenProcess)Marshal.GetDelegateForFunctionPointer(memoryAddress, typeof(Delegates.ZwOpenProcess));

                    return (NTSTATUS)myreplacedemblyFunction(out hProcess, processAccess, objAttribute, ref clientid);
                }
            }
        }

19 Source : NativeSysCall.cs
with BSD 3-Clause "New" or "Revised" License
from b4rtik

public static NTSTATUS ZwClose10(IntPtr handle)
        {
            byte[] syscall = bZwClose10;

            unsafe
            {
                fixed (byte* ptr = syscall)
                {

                    IntPtr memoryAddress = (IntPtr)ptr;

                    if (!VirtualProtect( memoryAddress,
                        (UIntPtr)syscall.Length, 0x40, out uint oldprotect))
                    {
                        throw new Win32Exception();
                    }

                    Delegates.ZwClose myreplacedemblyFunction = (Delegates.ZwClose)Marshal.GetDelegateForFunctionPointer(memoryAddress, typeof(Delegates.ZwClose));

                    return (NTSTATUS)myreplacedemblyFunction(handle);
                }
            }
        }

19 Source : NativeSysCall.cs
with BSD 3-Clause "New" or "Revised" License
from b4rtik

public static NTSTATUS ZwWriteVirtualMemory10(IntPtr hProcess, ref IntPtr lpBaseAddress, IntPtr lpBuffer, uint nSize, ref IntPtr lpNumberOfBytesWritten)
        {
            byte[] syscall = bZwWriteVirtualMemory10;

            unsafe
            {
                fixed (byte* ptr = syscall)
                {

                    IntPtr memoryAddress = (IntPtr)ptr;

                    if (!VirtualProtect( memoryAddress,
                        (UIntPtr)syscall.Length, 0x40, out uint oldprotect))
                    {
                        throw new Win32Exception();
                    }

                    Delegates.ZwWriteVirtualMemory myreplacedemblyFunction = (Delegates.ZwWriteVirtualMemory)Marshal.GetDelegateForFunctionPointer(memoryAddress, typeof(Delegates.ZwWriteVirtualMemory));

                    return (NTSTATUS)myreplacedemblyFunction(hProcess, lpBaseAddress, lpBuffer, nSize, ref lpNumberOfBytesWritten);
                }
            }
        }

19 Source : NativeSysCall.cs
with BSD 3-Clause "New" or "Revised" License
from b4rtik

public static NTSTATUS ZwProtectVirtualMemory10(IntPtr hProcess, ref IntPtr lpBaseAddress, ref uint NumberOfBytesToProtect, uint NewAccessProtection, ref uint lpNumberOfBytesWritten)
        {
            byte[] syscall = bZwProtectVirtualMemory10;

            unsafe
            {
                fixed (byte* ptr = syscall)
                {

                    IntPtr memoryAddress = (IntPtr)ptr;

                    if (!VirtualProtect( memoryAddress,
                        (UIntPtr)syscall.Length, 0x40, out uint oldprotect))
                    {
                        throw new Win32Exception();
                    }

                    Delegates.ZwProtectVirtualMemory myreplacedemblyFunction = (Delegates.ZwProtectVirtualMemory)Marshal.GetDelegateForFunctionPointer(memoryAddress, typeof(Delegates.ZwProtectVirtualMemory));

                    return (NTSTATUS)myreplacedemblyFunction(hProcess, ref lpBaseAddress, ref NumberOfBytesToProtect, NewAccessProtection, ref lpNumberOfBytesWritten);
                }
            }
        }

19 Source : NativeSysCall.cs
with BSD 3-Clause "New" or "Revised" License
from b4rtik

public static NTSTATUS ZwQuerySystemInformation10(SYSTEM_INFORMATION_CLreplaced SystemInformationClreplaced, IntPtr SystemInformation, uint SystemInformationLength, ref uint ReturnLength)
        {
            byte[] syscall = bZwQuerySystemInformation10;

            unsafe
            {
                fixed (byte* ptr = syscall)
                {

                    IntPtr memoryAddress = (IntPtr)ptr;

                    if (!VirtualProtect( memoryAddress,
                        (UIntPtr)syscall.Length, 0x40, out uint oldprotect))
                    {
                        throw new Win32Exception();
                    }

                    Delegates.ZwQuerySystemInformation myreplacedemblyFunction = (Delegates.ZwQuerySystemInformation)Marshal.GetDelegateForFunctionPointer(memoryAddress, typeof(Delegates.ZwQuerySystemInformation));

                    return (NTSTATUS)myreplacedemblyFunction(SystemInformationClreplaced, SystemInformation, SystemInformationLength, ref ReturnLength);
                }
            }
        }

19 Source : NativeSysCall.cs
with BSD 3-Clause "New" or "Revised" License
from b4rtik

public static NTSTATUS NtAllocateVirtualMemory10(IntPtr hProcess, ref IntPtr BaseAddress, IntPtr ZeroBits, ref IntPtr RegionSize, ulong AllocationType, ulong Protect)
        {
            byte[] syscall = bNtAllocateVirtualMemory10;

            unsafe
            {
                fixed (byte* ptr = syscall)
                {

                    IntPtr memoryAddress = (IntPtr)ptr;

                    if (!VirtualProtect( memoryAddress,
                        (UIntPtr)syscall.Length, 0x40, out uint oldprotect))
                    {
                        throw new Win32Exception();
                    }

                    Delegates.NtAllocateVirtualMemory myreplacedemblyFunction = (Delegates.NtAllocateVirtualMemory)Marshal.GetDelegateForFunctionPointer(memoryAddress, typeof(Delegates.NtAllocateVirtualMemory));

                    return (NTSTATUS)myreplacedemblyFunction(hProcess, ref BaseAddress, ZeroBits, ref RegionSize, AllocationType, Protect);
                }
            }
        }

19 Source : NativeSysCall.cs
with BSD 3-Clause "New" or "Revised" License
from b4rtik

public static NTSTATUS NtFreeVirtualMemory10(IntPtr hProcess, ref IntPtr BaseAddress, ref uint RegionSize, ulong FreeType)
        {
            byte[] syscall = bNtFreeVirtualMemory10;

            unsafe
            {
                fixed (byte* ptr = syscall)
                {

                    IntPtr memoryAddress = (IntPtr)ptr;

                    if (!VirtualProtect( memoryAddress,
                        (UIntPtr)syscall.Length, 0x40, out uint oldprotect))
                    {
                        throw new Win32Exception();
                    }

                    Delegates.NtFreeVirtualMemory myreplacedemblyFunction = (Delegates.NtFreeVirtualMemory)Marshal.GetDelegateForFunctionPointer(memoryAddress, typeof(Delegates.NtFreeVirtualMemory));

                    return (NTSTATUS)myreplacedemblyFunction(hProcess, ref BaseAddress, ref RegionSize, FreeType);
                }
            }
        }

19 Source : NativeSysCall.cs
with BSD 3-Clause "New" or "Revised" License
from b4rtik

public static NTSTATUS ZwResumeThread10(IntPtr hThread, out ulong PreviousSuspendCount)
        {
            byte[] syscall = bZwResumeThread10;

            unsafe
            {
                fixed (byte* ptr = syscall)
                {

                    IntPtr memoryAddress = (IntPtr)ptr;

                    if (!VirtualProtect( memoryAddress,
                        (UIntPtr)syscall.Length, 0x40, out uint oldprotect))
                    {
                        throw new Win32Exception();
                    }

                    Delegates.ZwResumeThread myreplacedemblyFunction = (Delegates.ZwResumeThread)Marshal.GetDelegateForFunctionPointer(memoryAddress, typeof(Delegates.ZwResumeThread));

                    return (NTSTATUS)myreplacedemblyFunction( hThread, out  PreviousSuspendCount);
                }
            }
        }

19 Source : NativeSysCall.cs
with BSD 3-Clause "New" or "Revised" License
from b4rtik

public static NTSTATUS ZwSetInformationThread10(IntPtr hThread, uint ThreadInformationClreplaced, IntPtr ThreadInformation, ulong ThreadInformationLength)
        {
            byte[] syscall = bZwSetInformationThread10;

            unsafe
            {
                fixed (byte* ptr = syscall)
                {

                    IntPtr memoryAddress = (IntPtr)ptr;

                    if (!VirtualProtect( memoryAddress,
                        (UIntPtr)syscall.Length, 0x40, out uint oldprotect))
                    {
                        throw new Win32Exception();
                    }

                    Delegates.ZwSetInformationThread myreplacedemblyFunction = (Delegates.ZwSetInformationThread)Marshal.GetDelegateForFunctionPointer(memoryAddress, typeof(Delegates.ZwSetInformationThread));

                    return (NTSTATUS)myreplacedemblyFunction( hThread,  ThreadInformationClreplaced,  ThreadInformation,  ThreadInformationLength);
                }
            }
        }

19 Source : NativeSysCall.cs
with BSD 3-Clause "New" or "Revised" License
from b4rtik

public static NTSTATUS ZwQueueApcThread10(IntPtr hThread, IntPtr pfnAPC, IntPtr dwData)
        {
            byte[] syscall = bZwQueueApcThread10;

            unsafe
            {
                fixed (byte* ptr = syscall)
                {

                    IntPtr memoryAddress = (IntPtr)ptr;

                    if (!VirtualProtect( memoryAddress,
                        (UIntPtr)syscall.Length, 0x40, out uint oldprotect))
                    {
                        throw new Win32Exception();
                    }

                    Delegates.ZwQueueApcThread myreplacedemblyFunction = (Delegates.ZwQueueApcThread)Marshal.GetDelegateForFunctionPointer(memoryAddress, typeof(Delegates.ZwQueueApcThread));

                    return (NTSTATUS)myreplacedemblyFunction( hThread,  pfnAPC,  dwData);
                }
            }
        }

19 Source : NativeSysCall.cs
with BSD 3-Clause "New" or "Revised" License
from b4rtik

public static NTSTATUS ZwUnmapViewOfSection10(IntPtr hSection, IntPtr address)
        {
            byte[] syscall = bZwUnmapViewOfSection10;

            unsafe
            {
                fixed (byte* ptr = syscall)
                {

                    IntPtr memoryAddress = (IntPtr)ptr;

                    if (!VirtualProtect( memoryAddress,
                        (UIntPtr)syscall.Length, 0x40, out uint oldprotect))
                    {
                        throw new Win32Exception();
                    }

                    Delegates.ZwUnMapViewOfSection myreplacedemblyFunction = (Delegates.ZwUnMapViewOfSection)Marshal.GetDelegateForFunctionPointer(memoryAddress, typeof(Delegates.ZwUnMapViewOfSection));

                    return (NTSTATUS)myreplacedemblyFunction( hSection,  address);
                }
            }
        }

19 Source : NativeSysCall.cs
with BSD 3-Clause "New" or "Revised" License
from b4rtik

public static NTSTATUS ZwMapViewOfSection10(IntPtr section, IntPtr process, ref IntPtr baseAddr, IntPtr zeroBits, IntPtr commitSize, IntPtr stuff, ref IntPtr viewSize, int inheritDispo, uint alloctype, uint protect)
        {
            byte[] syscall = bZwMapViewOfSection10;

            unsafe
            {
                fixed (byte* ptr = syscall)
                {

                    IntPtr memoryAddress = (IntPtr)ptr;

                    if (!VirtualProtect( memoryAddress,
                        (UIntPtr)syscall.Length, 0x40, out uint oldprotect))
                    {
                        throw new Win32Exception();
                    }

                    Delegates.ZwMapViewOfSection myreplacedemblyFunction = (Delegates.ZwMapViewOfSection)Marshal.GetDelegateForFunctionPointer(memoryAddress, typeof(Delegates.ZwMapViewOfSection));

                    return (NTSTATUS)myreplacedemblyFunction( section,  process, ref  baseAddr,  zeroBits,  commitSize,  stuff, ref  viewSize,  inheritDispo,  alloctype,  protect);
                }
            }
        }

19 Source : Natives.cs
with BSD 3-Clause "New" or "Revised" License
from b4rtik

public static UInt32 LdrLoadDll(IntPtr PathToFile, UInt32 dwFlags, ref Natives.UNICODE_STRING ModuleFileName, ref IntPtr ModuleHandle)
        {
            IntPtr proc = GetProcAddress(GetNtDll(), "LdrLoadDll");
            NativeSysCall.Delegates.LdrLoadDll LdrLoadDll = (NativeSysCall.Delegates.LdrLoadDll)Marshal.GetDelegateForFunctionPointer(proc, typeof(NativeSysCall.Delegates.LdrLoadDll));
            return (uint)LdrLoadDll(PathToFile, dwFlags, ref ModuleFileName, ref ModuleHandle);
        }

19 Source : Natives.cs
with BSD 3-Clause "New" or "Revised" License
from b4rtik

public static bool ReadFile(IntPtr hFile, [Out] byte[] lpBuffer, uint nNumberOfBytesToRead, out uint lpNumberOfBytesRead, IntPtr lpOverlapped)
        {
            IntPtr proc = GetProcAddress(GetKernelbase(), "ReadFile");
            NativeSysCall.Delegates.ReadFile ReadFile = (NativeSysCall.Delegates.ReadFile)Marshal.GetDelegateForFunctionPointer(proc, typeof(NativeSysCall.Delegates.ReadFile));
            return ReadFile(hFile, lpBuffer, nNumberOfBytesToRead, out lpNumberOfBytesRead, lpOverlapped);
        }

19 Source : Natives.cs
with BSD 3-Clause "New" or "Revised" License
from b4rtik

public static bool VirtualProtect(IntPtr lpAddress, UIntPtr dwSize, uint flNewProtect, out uint lpflOldProtect)
        {
            IntPtr proc = GetProcAddress(GetKernelbase(), "VirtualProtect");
            NativeSysCall.Delegates.VirtualProtect VirtualProtect = (NativeSysCall.Delegates.VirtualProtect)Marshal.GetDelegateForFunctionPointer(proc, typeof(NativeSysCall.Delegates.VirtualProtect));
            return VirtualProtect(lpAddress, dwSize, flNewProtect, out lpflOldProtect);
        }

19 Source : Natives.cs
with BSD 3-Clause "New" or "Revised" License
from b4rtik

public static void RtlInitUnicodeString(ref Natives.UNICODE_STRING DestinationString, [MarshalAs(UnmanagedType.LPWStr)] string SourceString)
        {
            IntPtr proc = GetProcAddress(GetNtDll(), "RtlInitUnicodeString");
            NativeSysCall.Delegates.RtlInitUnicodeString RtlInitUnicodeString = (NativeSysCall.Delegates.RtlInitUnicodeString)Marshal.GetDelegateForFunctionPointer(proc, typeof(NativeSysCall.Delegates.RtlInitUnicodeString));
            RtlInitUnicodeString(ref DestinationString, SourceString);
        }

19 Source : NativeSysCall.cs
with BSD 3-Clause "New" or "Revised" License
from b4rtik

public static NTSTATUS ZwProtectVirtualMemory10(IntPtr hProcess, ref IntPtr lpBaseAddress, ref uint NumberOfBytesToProtect, uint NewAccessProtection, ref uint lpNumberOfBytesWritten)
        {
            byte[] syscall = bZwProtectVirtualMemory10;

            unsafe
            {
                fixed (byte* ptr = syscall)
                {

                    IntPtr memoryAddress = (IntPtr)ptr;

                    if (!Natives.VirtualProtect(memoryAddress,
                        (UIntPtr)syscall.Length, 0x40, out uint oldprotect))
                    {
                        throw new Win32Exception();
                    }

                    Delegates.ZwProtectVirtualMemory myreplacedemblyFunction = (Delegates.ZwProtectVirtualMemory)Marshal.GetDelegateForFunctionPointer(memoryAddress, typeof(Delegates.ZwProtectVirtualMemory));

                    return (NTSTATUS)myreplacedemblyFunction(hProcess, ref lpBaseAddress, ref NumberOfBytesToProtect, NewAccessProtection, ref lpNumberOfBytesWritten);
                }
            }
        }

19 Source : NativeSysCall.cs
with BSD 3-Clause "New" or "Revised" License
from b4rtik

public static NTSTATUS ZwOpenProcess10(ref IntPtr hProcess, ProcessAccessFlags processAccess, OBJECT_ATTRIBUTES objAttribute, ref CLIENT_ID clientid)
        {
            byte[] syscall = bZwOpenProcess10;

            unsafe
            {
                fixed (byte* ptr = syscall)
                {

                    IntPtr memoryAddress = (IntPtr)ptr;

                    if (!Natives.VirtualProtect(memoryAddress,
                        (UIntPtr)syscall.Length, 0x40, out uint oldprotect))
                    {
                        throw new Win32Exception();
                    }

                    Delegates.ZwOpenProcess myreplacedemblyFunction = (Delegates.ZwOpenProcess)Marshal.GetDelegateForFunctionPointer(memoryAddress, typeof(Delegates.ZwOpenProcess));

                    return (NTSTATUS)myreplacedemblyFunction(out hProcess, processAccess, objAttribute, ref clientid);
                }
            }
        }

19 Source : NativeSysCall.cs
with BSD 3-Clause "New" or "Revised" License
from b4rtik

public static NTSTATUS ZwClose10(IntPtr handle)
        {
            byte[] syscall = bZwClose10;

            unsafe
            {
                fixed (byte* ptr = syscall)
                {

                    IntPtr memoryAddress = (IntPtr)ptr;

                    if (!Natives.VirtualProtect( memoryAddress,
                        (UIntPtr)syscall.Length, 0x40, out uint oldprotect))
                    {
                        throw new Win32Exception();
                    }

                    Delegates.ZwClose myreplacedemblyFunction = (Delegates.ZwClose)Marshal.GetDelegateForFunctionPointer(memoryAddress, typeof(Delegates.ZwClose));

                    return (NTSTATUS)myreplacedemblyFunction(handle);
                }
            }
        }

19 Source : NativeSysCall.cs
with BSD 3-Clause "New" or "Revised" License
from b4rtik

public static NTSTATUS ZwWriteVirtualMemory10(IntPtr hProcess, ref IntPtr lpBaseAddress, IntPtr lpBuffer, uint nSize, ref IntPtr lpNumberOfBytesWritten)
        {
            byte[] syscall = bZwWriteVirtualMemory10;

            unsafe
            {
                fixed (byte* ptr = syscall)
                {

                    IntPtr memoryAddress = (IntPtr)ptr;

                    if (!Natives.VirtualProtect( memoryAddress,
                        (UIntPtr)syscall.Length, 0x40, out uint oldprotect))
                    {
                        throw new Win32Exception();
                    }

                    Delegates.ZwWriteVirtualMemory myreplacedemblyFunction = (Delegates.ZwWriteVirtualMemory)Marshal.GetDelegateForFunctionPointer(memoryAddress, typeof(Delegates.ZwWriteVirtualMemory));

                    return (NTSTATUS)myreplacedemblyFunction(hProcess, lpBaseAddress, lpBuffer, nSize, ref lpNumberOfBytesWritten);
                }
            }
        }

19 Source : NativeSysCall.cs
with BSD 3-Clause "New" or "Revised" License
from b4rtik

public static NTSTATUS ZwQuerySystemInformation10(SYSTEM_INFORMATION_CLreplaced SystemInformationClreplaced, IntPtr SystemInformation, uint SystemInformationLength, ref uint ReturnLength)
        {
            byte[] syscall = bZwQuerySystemInformation10;

            unsafe
            {
                fixed (byte* ptr = syscall)
                {

                    IntPtr memoryAddress = (IntPtr)ptr;

                    if (!Natives.VirtualProtect(memoryAddress,
                        (UIntPtr)syscall.Length, 0x40, out uint oldprotect))
                    {
                        throw new Win32Exception();
                    }

                    Delegates.ZwQuerySystemInformation myreplacedemblyFunction = (Delegates.ZwQuerySystemInformation)Marshal.GetDelegateForFunctionPointer(memoryAddress, typeof(Delegates.ZwQuerySystemInformation));

                    return (NTSTATUS)myreplacedemblyFunction(SystemInformationClreplaced, SystemInformation, SystemInformationLength, ref ReturnLength);
                }
            }
        }

19 Source : NativeSysCall.cs
with BSD 3-Clause "New" or "Revised" License
from b4rtik

public static NTSTATUS NtAllocateVirtualMemory10(IntPtr hProcess, ref IntPtr BaseAddress, IntPtr ZeroBits, ref UIntPtr RegionSize, ulong AllocationType, ulong Protect)
        {
            byte[] syscall = bNtAllocateVirtualMemory10;

            unsafe
            {
                fixed (byte* ptr = syscall)
                {

                    IntPtr memoryAddress = (IntPtr)ptr;

                    if (!Natives.VirtualProtect(memoryAddress,
                        (UIntPtr)syscall.Length, 0x40, out uint oldprotect))
                    {
                        throw new Win32Exception();
                    }

                    Delegates.NtAllocateVirtualMemory myreplacedemblyFunction = (Delegates.NtAllocateVirtualMemory)Marshal.GetDelegateForFunctionPointer(memoryAddress, typeof(Delegates.NtAllocateVirtualMemory));

                    return (NTSTATUS)myreplacedemblyFunction(hProcess, ref BaseAddress, ZeroBits, ref RegionSize, AllocationType, Protect);
                }
            }
        }

19 Source : NativeSysCall.cs
with BSD 3-Clause "New" or "Revised" License
from b4rtik

public static NTSTATUS NtFreeVirtualMemory10(IntPtr hProcess, ref IntPtr BaseAddress, ref uint RegionSize, ulong FreeType)
        {
            byte[] syscall = bNtFreeVirtualMemory10;

            unsafe
            {
                fixed (byte* ptr = syscall)
                {

                    IntPtr memoryAddress = (IntPtr)ptr;

                    if (!Natives.VirtualProtect(memoryAddress,
                        (UIntPtr)syscall.Length, 0x40, out uint oldprotect))
                    {
                        throw new Win32Exception();
                    }

                    Delegates.NtFreeVirtualMemory myreplacedemblyFunction = (Delegates.NtFreeVirtualMemory)Marshal.GetDelegateForFunctionPointer(memoryAddress, typeof(Delegates.NtFreeVirtualMemory));

                    return (NTSTATUS)myreplacedemblyFunction(hProcess, ref BaseAddress, ref RegionSize, FreeType);
                }
            }
        }

19 Source : NativeSysCall.cs
with BSD 3-Clause "New" or "Revised" License
from b4rtik

public static NTSTATUS NtCreateFile10(out Microsoft.Win32.SafeHandles.SafeFileHandle fileHandle,
                Int32 desiredAccess,
                ref OBJECT_ATTRIBUTES objectAttributes,
                out IO_STATUS_BLOCK ioStatusBlock,
                ref Int64 allocationSize,
                UInt32 fileAttributes,
                System.IO.FileShare shareAccess,
                UInt32 createDisposition,
                UInt32 createOptions,
                IntPtr eaBuffer,
                UInt32 eaLength)
        {
            byte[] syscall = bNtCreateFile10;

            unsafe
            {
                fixed (byte* ptr = syscall)
                {

                    IntPtr memoryAddress = (IntPtr)ptr;

                    if (!Natives.VirtualProtect(memoryAddress,
                        (UIntPtr)syscall.Length, 0x40, out uint oldprotect))
                    {
                        throw new Win32Exception();
                    }

                    Delegates.NtCreateFile myreplacedemblyFunction = (Delegates.NtCreateFile)Marshal.GetDelegateForFunctionPointer(memoryAddress, typeof(Delegates.NtCreateFile));

                    return (NTSTATUS)myreplacedemblyFunction(out fileHandle,
                 desiredAccess,
                ref objectAttributes,
                out ioStatusBlock,
                ref allocationSize,
                 fileAttributes,
                 shareAccess,
                 createDisposition,
                 createOptions,
                 eaBuffer,
                 eaLength);
                }
            }
        }

19 Source : syscalls.cs
with BSD 3-Clause "New" or "Revised" License
from badBounty

public static NTSTATUS NtCreateSection(ref IntPtr section, uint desiredAccess, IntPtr pAttrs, ref LARGE_INTEGER pMaxSize, uint pageProt, uint allocationAttribs, IntPtr hFile, string os)
        {
            byte[] syscall = syscallSkeleton;
            syscall[4] = sysDic[os]["createsection"];

            unsafe
            {
                fixed (byte* ptr = syscall)
                {

                    IntPtr memoryAddress = (IntPtr)ptr;

                    if (!VirtualProtectEx(Process.GetCurrentProcess().Handle, memoryAddress,
                        (UIntPtr)syscall.Length, 0x40, out uint oldprotect))
                    {
                        throw new Win32Exception();
                    }

                    Delegates.NtCreateSection myreplacedemblyFunction = (Delegates.NtCreateSection)Marshal.GetDelegateForFunctionPointer(memoryAddress, typeof(Delegates.NtCreateSection));

                    return (NTSTATUS)myreplacedemblyFunction(ref section, desiredAccess, pAttrs, ref pMaxSize, pageProt, allocationAttribs, hFile);
                }
            }
        }

19 Source : syscalls.cs
with BSD 3-Clause "New" or "Revised" License
from badBounty

public static NTSTATUS NtMapViewOfSection(IntPtr section, IntPtr process, ref IntPtr baseAddr, IntPtr zeroBits, IntPtr commitSize, IntPtr stuff, ref IntPtr viewSize, int inheritDispo, uint alloctype, uint prot, string os)
        {
            byte[] syscall = syscallSkeleton;
            syscall[4] = sysDic[os]["mapviewofsec"];

            unsafe
            {
                fixed (byte* ptr = syscall)
                {

                    IntPtr memoryAddress = (IntPtr)ptr;

                    if (!VirtualProtectEx(Process.GetCurrentProcess().Handle, memoryAddress,
                        (UIntPtr)syscall.Length, 0x40, out uint oldprotect))
                    {
                        throw new Win32Exception();
                    }

                    Delegates.NtMapViewOfSection myreplacedemblyFunction = (Delegates.NtMapViewOfSection)Marshal.GetDelegateForFunctionPointer(memoryAddress, typeof(Delegates.NtMapViewOfSection));

                    return (NTSTATUS)myreplacedemblyFunction(section, process, ref baseAddr, zeroBits, commitSize, stuff, ref viewSize, inheritDispo, alloctype, prot);
                }
            }
        }

19 Source : syscalls.cs
with BSD 3-Clause "New" or "Revised" License
from badBounty

public static NTSTATUS NtAllocateVirtualMemory(IntPtr hProcess, ref IntPtr BaseAddress, IntPtr ZeroBits, ref UIntPtr RegionSize, ulong AllocationType, ulong Protect, string os)
        {
            byte[] syscall = syscallSkeleton;
            syscall[4] = sysDic[os]["allocatevirtualmem"];

            unsafe
            {
                fixed (byte* ptr = syscall)
                {

                    IntPtr memoryAddress = (IntPtr)ptr;

                    if (!VirtualProtectEx(Process.GetCurrentProcess().Handle, memoryAddress,
                        (UIntPtr)syscall.Length, 0x40, out uint oldprotect))
                    {
                        throw new Win32Exception();
                    }

                    Delegates.NtAllocateVirtualMemory myreplacedemblyFunction = (Delegates.NtAllocateVirtualMemory)Marshal.GetDelegateForFunctionPointer(memoryAddress, typeof(Delegates.NtAllocateVirtualMemory));

                    return (NTSTATUS)myreplacedemblyFunction(hProcess, ref BaseAddress, ZeroBits, ref RegionSize, AllocationType, Protect);
                }
            }
        }

See More Examples