Exemplo n.º 1
0
        private void InternalSetKeyDown(int virtualKeyCode)
        {
            var foreignThreadId = Win32Imports.GetWindowThreadProcessId(_processWindowHandle, IntPtr.Zero);
            var localThreadId   = Win32Imports.GetCurrentThreadId();

            Win32Imports.AttachThreadInput(localThreadId, foreignThreadId, true);

            var keys = new byte[256];

            Win32Imports.GetKeyboardState(keys);
            keys[virtualKeyCode] |= 0x80;
            Win32Imports.SetKeyboardState(keys);

            Task.Delay(50).Wait();
        }
Exemplo n.º 2
0
            public static void DeallocateAVICOMPRESSOPTIONS(ref AVIWriterImports.AVICOMPRESSOPTIONS opts)
            {
#if false // test: increase stability by never freeing anything, ever
                if (opts.lpParms != IntPtr.Zero)
                {
                    Win32Imports.HeapFree(Win32Imports.GetProcessHeap(), 0, opts.lpParms);
                }
                if (opts.lpFormat != IntPtr.Zero)
                {
                    Win32Imports.HeapFree(Win32Imports.GetProcessHeap(), 0, opts.lpFormat);
                }
#endif
                opts.lpParms  = IntPtr.Zero;
                opts.lpFormat = IntPtr.Zero;
            }
Exemplo n.º 3
0
        private void InternalSetKeyUp(int virtualKeyCode)
        {
            var keys = new byte[256];

            Win32Imports.GetKeyboardState(keys);
            keys[virtualKeyCode] &= 0x00;
            Win32Imports.SetKeyboardState(keys);

            var foreignThreadId = Win32Imports.GetWindowThreadProcessId(_processWindowHandle, IntPtr.Zero);
            var localThreadId   = Win32Imports.GetCurrentThreadId();

            Win32Imports.AttachThreadInput(localThreadId, foreignThreadId, false);

            Thread.Sleep(50);
        }
Exemplo n.º 4
0
        public void CopySections(byte[] data, IMAGE_NT_HEADERS oldHeaders, IntPtr headers, IMAGE_DOS_HEADER dosHeader)
        {
            int    i;
            IntPtr codebase = module.codeBase;
            var    section  = PointerHelpers.ToStruct <IMAGE_SECTION_HEADER>(headers,
                                                                             (uint)(24 + dosHeader.e_lfanew + oldHeaders.FileHeader.SizeOfOptionalHeader));

            for (i = 0; i < module.headers.FileHeader.NumberOfSections; i++)
            {
                IntPtr dest;
                if (section.SizeOfRawData == 0)
                {
                    uint size = oldHeaders.OptionalHeader.SectionAlignment;
                    if (size > 0)
                    {
                        dest = new IntPtr((Win32Imports.VirtualAlloc((uint)(codebase + (int)section.VirtualAddress),
                                                                     size, Win32Constants.MEM_COMMIT,
                                                                     Win32Constants.PAGE_READWRITE)));

                        section.PhysicalAddress = (uint)dest;
                        var write = new IntPtr(headers.ToInt32() +
                                               (32 + dosHeader.e_lfanew + oldHeaders.FileHeader.SizeOfOptionalHeader) +
                                               (Marshal.SizeOf(typeof(IMAGE_SECTION_HEADER)) * (i)));
                        Marshal.WriteInt32(write, (int)dest);
                        var datazz = new byte[size + 1];
                        Marshal.Copy(datazz, 0, dest, (int)size);
                    }

                    section = PointerHelpers.ToStruct <IMAGE_SECTION_HEADER>(headers,
                                                                             (uint)((24 + dosHeader.e_lfanew + oldHeaders.FileHeader.SizeOfOptionalHeader) +
                                                                                    (Marshal.SizeOf(typeof(IMAGE_SECTION_HEADER)) * (i + 1))));
                    continue;
                }

                dest = new IntPtr((Win32Imports.VirtualAlloc((uint)(codebase + (int)section.VirtualAddress),
                                                             section.SizeOfRawData, Win32Constants.MEM_COMMIT,
                                                             Win32Constants.PAGE_READWRITE)));
                Marshal.Copy(data, (int)section.PointerToRawData, dest, (int)section.SizeOfRawData);
                section.PhysicalAddress = (uint)dest;
                var write2 = new IntPtr(headers.ToInt32() +
                                        (32 + dosHeader.e_lfanew + oldHeaders.FileHeader.SizeOfOptionalHeader) +
                                        (Marshal.SizeOf(typeof(IMAGE_SECTION_HEADER)) * (i)));
                Marshal.WriteInt32(write2, (int)dest);
                section = PointerHelpers.ToStruct <IMAGE_SECTION_HEADER>(headers,
                                                                         (uint)((24 + dosHeader.e_lfanew + oldHeaders.FileHeader.SizeOfOptionalHeader) +
                                                                                (Marshal.SizeOf(typeof(IMAGE_SECTION_HEADER)) * (i + 1))));
            }
        }
Exemplo n.º 5
0
        private void InternalSetPlayerFacing(Radian radian, MappedKeyAction nudgeKey)
        {
            var thread    = _process.Threads[0];
            var threadPtr = Win32Imports.OpenThread(2032639U, false, (uint)thread.Id);

            Win32Imports.SuspendThread(threadPtr);

            _reader.WriteFloat(ObjectManager.Me.BaseAddress + (uint)Offsets.WowObject.OBJECT_FIELD_ROTATION, radian.Angle);

            thread    = _process.Threads[0];
            threadPtr = Win32Imports.OpenThread(2032639U, false, (uint)thread.Id);
            Win32Imports.ResumeThread(threadPtr);

            Task.Delay(50).Wait();
            SendKey(nudgeKey);
            Task.Delay(50).Wait();
        }
Exemplo n.º 6
0
        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex == -1)
            {
                return;
            }

            var obj = (RowUnit)dataGridView1.Rows[e.RowIndex].DataBoundItem;

            _commandManager.SetTarget(obj.Address);
            //  var kcd = new KeyboardCommandDispatcher();
            //   kcd.SendG(_process);

            Win32Imports.SetForegroundWindow(_process.MainWindowHandle);

            _commandManager.SetPlayerFacing(obj.Location);
        }
Exemplo n.º 7
0
        public void SendShiftClick(Point point)
        {
            var offsetPoint = GetOffsetPoint(point);

            Cursor.Position = offsetPoint;
            var lparam = CreateMouseParam(offsetPoint);
            var flags  = MouseFlags.MK_LBUTTON | MouseFlags.MK_SHIFT;

            Win32Imports.PostMessage(_processWindowHandle, WM_KEYDOWN, 0x10, 0x002A0001);
            Task.Delay(100).Wait();
            Win32Imports.PostMessage(_processWindowHandle, WM_MOVEMOUSE, 0, lparam);
            Win32Imports.PostMessage(_processWindowHandle, 0x0020, 0x00050038, 0x02000001);
            Task.Delay(100).Wait();
            Win32Imports.PostMessage(_processWindowHandle, WM_RBUTTONDOWN, (int)flags, lparam);
            Task.Delay(100).Wait();
            Win32Imports.PostMessage(_processWindowHandle, WM_RBUTTONUP, (int)flags, lparam);
            Task.Delay(100).Wait();
            Win32Imports.PostMessage(_processWindowHandle, WM_KEYUP, 0x10, 0xC02A0001);
        }
Exemplo n.º 8
0
        public static void SetSortIcon(this ListView listViewControl, int columnIndex, SortOrder order)
        {
            if (OSTailoredCode.IsUnixHost)
            {
                return;
            }

            const int LVM_GETHEADER = 4127;
            const int HDM_GETITEM   = 4619;
            const int HDM_SETITEM   = 4620;
            var       columnHeader  = Win32Imports.SendMessage(listViewControl.Handle, LVM_GETHEADER, IntPtr.Zero, IntPtr.Zero);

            for (int columnNumber = 0, l = listViewControl.Columns.Count; columnNumber < l; columnNumber++)
            {
                var columnPtr = new IntPtr(columnNumber);
                var item      = new Win32Imports.HDITEM {
                    mask = Win32Imports.HDITEM.Mask.Format
                };
                if (Win32Imports.SendMessage(columnHeader, HDM_GETITEM, columnPtr, ref item) == IntPtr.Zero)
                {
                    throw new Win32Exception();
                }
                if (columnNumber != columnIndex || order == SortOrder.None)
                {
                    item.fmt &= ~Win32Imports.HDITEM.Format.SortDown & ~Win32Imports.HDITEM.Format.SortUp;
                }
                else if (order == SortOrder.Ascending)
                {
                    item.fmt &= ~Win32Imports.HDITEM.Format.SortDown;
                    item.fmt |= Win32Imports.HDITEM.Format.SortUp;
                }
                else if (order == SortOrder.Descending)
                {
                    item.fmt &= ~Win32Imports.HDITEM.Format.SortUp;
                    item.fmt |= Win32Imports.HDITEM.Format.SortDown;
                }
                if (Win32Imports.SendMessage(columnHeader, HDM_SETITEM, columnPtr, ref item) == IntPtr.Zero)
                {
                    throw new Win32Exception();
                }
            }
        }
Exemplo n.º 9
0
        public void SetPlayerFacing(Location destination)
        {
            var angle = GetFaceRadian(destination, ObjectManager.Me.Location);

            var thread    = _process.Threads[0];
            var threadPtr = Win32Imports.OpenThread(2032639U, false, (uint)thread.Id);

            Win32Imports.SuspendThread(threadPtr);

            _reader.WriteFloat(ObjectManager.Me.BaseAddress + (uint)Offsets.WowObject.OBJECT_FIELD_ROTATION, angle);

            thread    = _process.Threads[0];
            threadPtr = Win32Imports.OpenThread(2032639U, false, (uint)thread.Id);
            Win32Imports.ResumeThread(threadPtr);

            Thread.Sleep(50);

            Win32Imports.PostMessage(_process.MainWindowHandle, 0x100, (int)0x25, 0x14B0001);
            Win32Imports.PostMessage(_process.MainWindowHandle, 0x101, (int)0x25, (0x14B0001 + 0xC0000000));
        }
Exemplo n.º 10
0
        static GamePad360()
        {
            try
            {
                // some users won't even have xinput installed. in order to avoid spurious exceptions and possible instability, check for the library first
                var llManager     = OSTailoredCode.LinkedLibManager;
                var libraryHandle = llManager.LoadOrZero("xinput1_3.dll");
                if (libraryHandle == IntPtr.Zero)
                {
                    libraryHandle = llManager.LoadOrZero("xinput1_4.dll");
                }
                if (libraryHandle != IntPtr.Zero)
                {
                    XInputGetStateExProc = (XInputGetStateExProcDelegate)Marshal.GetDelegateForFunctionPointer(
                        Win32Imports.GetProcAddressOrdinal(libraryHandle, new IntPtr(100)),
                        typeof(XInputGetStateExProcDelegate)
                        );
                }
                else
                {
                    libraryHandle = llManager.LoadOrZero("xinput9_1_0.dll");
                }
                IsAvailable = libraryHandle != IntPtr.Zero;

                // don't remove this code. it's important to catch errors on systems with broken xinput installs.
                // (probably, checking for the library was adequate, but let's not get rid of this anyway)
                if (IsAvailable)
                {
                    _ = new Controller(UserIndex.One).IsConnected;
                }
            }
            catch
            {
                // ignored
            }
        }
Exemplo n.º 11
0
        private void CreateMutex(StartupEventArgs e)
        {
            bool createdNew;

            _mutex = new Mutex(true,
                               Utility.Md5Hash(Utility.Md5Checksum(Constants.AppDirectory) +
                                               Utility.Md5Hash(Environment.UserName)), out createdNew);
            if (!createdNew)
            {
                if (e.Args.Length > 0)
                {
                    var wnd = Win32Imports.FindWindow(IntPtr.Zero, "UOFLauncher");
                    if (wnd != IntPtr.Zero)
                    {
                        Clipboard.SetText(e.Args[0]);
                        ShowWindow(wnd, 5);
                        SetForegroundWindow(wnd);
                    }
                }

                _mutex = null;
                Environment.Exit(0);
            }
        }
Exemplo n.º 12
0
 public static void PrintCurrentFP() => Console.WriteLine($"Current FP word: 0x{Win32Imports._control87(0, 0):X8}");
Exemplo n.º 13
0
        public PeRunner(PeRunnerOptions opt)
        {
            _nextStart = opt.StartAddress;
            Initialize(_nextStart);
            using (this.EnterExit())
            {
                // load any predefined exports
                _psx = new Psx(this);
                _exports.Add("libpsxscl.so", BizExvoker.GetExvoker(_psx, CallingConventionAdapters.Waterbox));
                _emu = new Emu(this);
                _exports.Add("libemuhost.so", BizExvoker.GetExvoker(_emu, CallingConventionAdapters.Waterbox));
                _syscalls = new Syscalls(this);
                _exports.Add("__syscalls", BizExvoker.GetExvoker(_syscalls, CallingConventionAdapters.Waterbox));

                // load and connect all modules, starting with the executable
                var todoModules = new Queue <string>();
                todoModules.Enqueue(opt.Filename);

                while (todoModules.Count > 0)
                {
                    var moduleName = todoModules.Dequeue();
                    if (!_exports.ContainsKey(moduleName))
                    {
                        var    path   = Path.Combine(opt.Path, moduleName);
                        var    gzpath = path + ".gz";
                        byte[] data;
                        if (File.Exists(gzpath))
                        {
                            using (var fs = new FileStream(gzpath, FileMode.Open, FileAccess.Read))
                            {
                                data = Util.DecompressGzipFile(fs);
                            }
                        }
                        else
                        {
                            data = File.ReadAllBytes(path);
                        }

                        var module = new PeWrapper(moduleName, data, _nextStart);
                        ComputeNextStart(module.Size);
                        AddMemoryBlock(module.Memory, moduleName);
                        _savestateComponents.Add(module);
                        _disposeList.Add(module);

                        _exports.Add(moduleName, module);
                        _modules.Add(module);
                        foreach (var name in module.ImportsByModule.Keys)
                        {
                            todoModules.Enqueue(name);
                        }
                    }
                }

                _libcpatch          = new LibcPatch(this);
                _exports["libc.so"] = new PatchImportResolver(_exports["libc.so"], BizExvoker.GetExvoker(_libcpatch, CallingConventionAdapters.Waterbox));

                ConnectAllImports();

                // load all heaps
                _heap          = CreateHeapHelper(opt.SbrkHeapSizeKB, "brk-heap", true);
                _sealedheap    = CreateHeapHelper(opt.SealedHeapSizeKB, "sealed-heap", true);
                _invisibleheap = CreateHeapHelper(opt.InvisibleHeapSizeKB, "invisible-heap", false);
                _plainheap     = CreateHeapHelper(opt.PlainHeapSizeKB, "plain-heap", true);

                if (opt.MmapHeapSizeKB != 0)
                {
                    _mmapheap = new MapHeap(_nextStart, opt.MmapHeapSizeKB * 1024, "mmap-heap");
                    _mmapheap.Memory.Activate();
                    ComputeNextStart(opt.MmapHeapSizeKB * 1024);
                    AddMemoryBlock(_mmapheap.Memory, "mmap-heap");
                    _savestateComponents.Add(_mmapheap);
                    _disposeList.Add(_mmapheap);
                }

                _syscalls.Init();

                Console.WriteLine("About to enter unmanaged code");
                if (!OSTailoredCode.IsUnixHost && !System.Diagnostics.Debugger.IsAttached && Win32Imports.IsDebuggerPresent())
                {
                    // this means that GDB or another unconventional debugger is attached.
                    // if that's the case, and it's observing this core, it probably wants a break
                    System.Diagnostics.Debugger.Break();
                }

                // run unmanaged init code
                var libcEnter = _exports["libc.so"].GetProcAddrOrThrow("__libc_entry_routine");
                var psxInit   = _exports["libpsxscl.so"].GetProcAddrOrThrow("__psx_init");

                var del = (LibcEntryRoutineD)CallingConventionAdapters.Waterbox.GetDelegateForFunctionPointer(libcEnter, typeof(LibcEntryRoutineD));
                // the current mmglue code doesn't use the main pointer at all, and this just returns
                del(IntPtr.Zero, psxInit, 0);

                foreach (var m in _modules)
                {
                    m.RunGlobalCtors();
                }

                /*try
                 * {
                 *      _modules[0].RunExeEntry();
                 *      //throw new InvalidOperationException("main() returned!");
                 * }
                 * catch //(EndOfMainException)
                 * {
                 * }
                 * _modules[0].RunGlobalCtors();
                 * foreach (var m in _modules.Skip(1))
                 * {
                 *      if (!m.RunDllEntry())
                 *              throw new InvalidOperationException("DllMain() returned false");
                 *      m.RunGlobalCtors();
                 * }*/
            }
        }
Exemplo n.º 14
0
 public static void RemoveMOTW(string path) => Win32Imports.DeleteFileW($"{path}:Zone.Identifier");
Exemplo n.º 15
0
        public void FinalizeSections(IntPtr headers, IMAGE_DOS_HEADER dosHeader, IMAGE_NT_HEADERS oldHeaders)
        {
            ProtectionFlags[0]       = new Int32[2][];
            ProtectionFlags[1]       = new Int32[2][];
            ProtectionFlags[0][0]    = new Int32[2];
            ProtectionFlags[0][1]    = new Int32[2];
            ProtectionFlags[1][0]    = new Int32[2];
            ProtectionFlags[1][1]    = new Int32[2];
            ProtectionFlags[0][0][0] = 0x01;
            ProtectionFlags[0][0][1] = 0x08;
            ProtectionFlags[0][1][0] = 0x02;
            ProtectionFlags[0][1][1] = 0x04;
            ProtectionFlags[1][0][0] = 0x10;
            ProtectionFlags[1][0][1] = 0x80;
            ProtectionFlags[1][1][0] = 0x20;
            ProtectionFlags[1][1][1] = 0x40;

            IMAGE_SECTION_HEADER section = PointerHelpers.ToStruct <IMAGE_SECTION_HEADER>(headers, (UInt32)(24 + dosHeader.e_lfanew + oldHeaders.FileHeader.SizeOfOptionalHeader));

            for (Int32 i = 0; i < _module.headers.FileHeader.NumberOfSections; i++)
            {
                //Console.WriteLine("Finalizing " + Encoding.UTF8.GetString(section.Name));
                Int32 executable = (section.Characteristics & 0x20000000) != 0 ? 1 : 0;
                Int32 readable   = (section.Characteristics & 0x40000000) != 0 ? 1 : 0;
                Int32 writeable  = (section.Characteristics & 0x80000000) != 0 ? 1 : 0;

                if ((section.Characteristics & 0x02000000) > 0)
                {
                    Boolean aa = Win32Imports.VirtualFree(new IntPtr(section.PhysicalAddress), (UIntPtr)section.SizeOfRawData, 0x4000);
                    continue;
                }

                UInt32 protect = (UInt32)ProtectionFlags[executable][readable][writeable];

                if ((section.Characteristics & 0x04000000) > 0)
                {
                    protect |= 0x200;
                }
                Int32 size = (Int32)section.SizeOfRawData;
                if (size == 0)
                {
                    if ((section.Characteristics & 0x00000040) > 0)
                    {
                        size = (Int32)_module.headers.OptionalHeader.SizeOfInitializedData;
                    }
                    else if ((section.Characteristics & 0x00000080) > 0)
                    {
                        size = (Int32)_module.headers.OptionalHeader.SizeOfUninitializedData;
                    }
                }

                if (size > 0)
                {
                    UInt32 oldProtect;
                    if (!Win32Imports.VirtualProtect(new IntPtr(section.PhysicalAddress), section.SizeOfRawData, protect, out oldProtect))
                    {
                    }
                }

                section = PointerHelpers.ToStruct <IMAGE_SECTION_HEADER>(headers, (UInt32)((24 + dosHeader.e_lfanew + oldHeaders.FileHeader.SizeOfOptionalHeader) + (Marshal.SizeOf(typeof(IMAGE_SECTION_HEADER)) * (i + 1))));
            }
        }
Exemplo n.º 16
0
        public WaterboxHost(WaterboxOptions opt)
        {
            _nextStart = opt.StartAddress;
            Initialize(_nextStart);
            using (this.EnterExit())
            {
                _emu      = new EmuLibc(this);
                _syscalls = new Syscalls(this);

                _imports = new PatchImportResolver(
                    NotImplementedSyscalls.Instance,
                    BizExvoker.GetExvoker(_emu, CallingConventionAdapters.Waterbox),
                    BizExvoker.GetExvoker(_syscalls, CallingConventionAdapters.Waterbox)
                    );

                if (true)
                {
                    var moduleName = opt.Filename;

                    var    path   = Path.Combine(opt.Path, moduleName);
                    var    gzpath = path + ".gz";
                    byte[] data;
                    if (File.Exists(gzpath))
                    {
                        using var fs = new FileStream(gzpath, FileMode.Open, FileAccess.Read);
                        data         = Util.DecompressGzipFile(fs);
                    }
                    else
                    {
                        data = File.ReadAllBytes(path);
                    }

                    _module = new ElfLoader(moduleName, data, _nextStart, opt.SkipCoreConsistencyCheck, opt.SkipMemoryConsistencyCheck);

                    ComputeNextStart(_module.Memory.Size);
                    AddMemoryBlock(_module.Memory, moduleName);
                    _savestateComponents.Add(_module);
                    _disposeList.Add(_module);
                }

                ConnectAllImports();

                // load all heaps
                _heap          = CreateHeapHelper(opt.SbrkHeapSizeKB, "brk-heap", true);
                _sealedheap    = CreateHeapHelper(opt.SealedHeapSizeKB, "sealed-heap", true);
                _invisibleheap = CreateHeapHelper(opt.InvisibleHeapSizeKB, "invisible-heap", false);
                _plainheap     = CreateHeapHelper(opt.PlainHeapSizeKB, "plain-heap", true);

                if (opt.MmapHeapSizeKB != 0)
                {
                    _mmapheap = new MapHeap(_nextStart, opt.MmapHeapSizeKB * 1024, "mmap-heap");
                    _mmapheap.Memory.Activate();
                    ComputeNextStart(opt.MmapHeapSizeKB * 1024);
                    AddMemoryBlock(_mmapheap.Memory, "mmap-heap");
                    _savestateComponents.Add(_mmapheap);
                    _disposeList.Add(_mmapheap);
                }

                System.Diagnostics.Debug.WriteLine($"About to enter unmanaged code for {opt.Filename}");
                if (!OSTailoredCode.IsUnixHost && !System.Diagnostics.Debugger.IsAttached && Win32Imports.IsDebuggerPresent())
                {
                    // this means that GDB or another unconventional debugger is attached.
                    // if that's the case, and it's observing this core, it probably wants a break
                    System.Diagnostics.Debugger.Break();
                }

                _module.RunNativeInit();
            }
        }
Exemplo n.º 17
0
        /// <summary>
        /// Rebuilds the PE import table after address relocations.
        /// </summary>
        public int BuildImportTable()
        {
            int ucount = GetModuleCount();

            module.modules = Marshal.AllocHGlobal((ucount) * sizeof(int));
            int    pcount   = 0;
            int    result   = 1;
            IntPtr codeBase = module.codeBase;
            IMAGE_DATA_DIRECTORY directory = module.headers.OptionalHeader.DataDirectory[1];

            if (directory.Size > 0)
            {
                var importDesc = PointerHelpers.ToStruct <IMAGE_IMPORT_DESCRIPTOR>(codeBase, directory.VirtualAddress);
                while (importDesc.Name > 0)
                {
                    var    str = codeBase + (int)importDesc.Name;
                    string tmp = Marshal.PtrToStringAnsi(str);
                    unsafe
                    {
                        uint *thunkRef;
                        uint *funcRef;

                        int handle = Win32Imports.LoadLibrary(tmp);

                        if (handle == -1)
                        {
                            result = 0;
                            break;
                        }

                        if (importDesc.CharacteristicsOrOriginalFirstThunk > 0)
                        {
                            IntPtr thunkRefAddr = codeBase + (int)importDesc.CharacteristicsOrOriginalFirstThunk;
                            thunkRef = (uint *)thunkRefAddr;
                            funcRef  = (uint *)(codeBase + (int)importDesc.FirstThunk);
                        }
                        else
                        {
                            thunkRef = (uint *)(codeBase + (int)importDesc.FirstThunk);
                            funcRef  = (uint *)(codeBase + (int)importDesc.FirstThunk);
                        }
                        for (; *thunkRef > 0; thunkRef++, funcRef++)
                        {
                            if ((*thunkRef & 0x80000000) != 0)
                            {
                                *funcRef = (uint)Win32Imports.GetProcAddress(new IntPtr(handle), new IntPtr(*thunkRef & 0xffff));
                            }
                            else
                            {
                                var str2    = codeBase + (int)(*thunkRef) + 2;
                                var tmpaa   = Marshal.PtrToStringAnsi(str2);
                                *   funcRef = Win32Imports.GetProcAddress(new IntPtr(handle), tmpaa);
                            }
                            if (*funcRef == 0)
                            {
                                result = 0;
                                break;
                            }
                        }


                        pcount++;
                        importDesc = PointerHelpers.ToStruct <IMAGE_IMPORT_DESCRIPTOR>(codeBase, directory.VirtualAddress + (uint)(Marshal.SizeOf(typeof(IMAGE_IMPORT_DESCRIPTOR)) * pcount));
                    }
                }
            }
            return(result);
        }
Exemplo n.º 18
0
        /// <summary>
        /// Gets the version info for a given application
        /// </summary>
        /// <param name="AppName">Full path to the application to get version info</param>
        // marked with 'unsafe' because it uses pointers:
        unsafe public static VersionInfo GetVersionInfo(string AppName)
        {
            VersionInfo result = new VersionInfo();

            try
            {
                int handle = 0;
                // Figure out how much version info there is:
                int size =
                    Win32Imports.GetFileVersionInfoSize(AppName, out handle);

                if (size == 0)
                {
                    throw new Exception("Couldn't find Application: " + AppName + "." + Environment.NewLine +
                                        "Error CNF-402 in " + PROJ_FILE_NAME + ".validateData().");
                }

                byte[] buffer = new byte[size];

                if (!Win32Imports.GetFileVersionInfo(AppName, handle, size, buffer))
                {
                    throw new Exception("Failed to query file version information." + Environment.NewLine +
                                        "Error CNF-403 in " + PROJ_FILE_NAME + ".validateData().");
                }

                const int INFONUM = 10;
                string[]  InfoStr = new string[INFONUM]
                {
                    "CompanyName",
                    "FileDescription",
                    "FileVersion",
                    "InternalName",
                    "LegalCopyright",
                    "LegalTradeMarks",
                    "OriginalFileName",
                    "ProductName",
                    "ProductVersion",
                    "Comments"
                };

                short *subBlock = null;
                uint   len      = 0;
                string val;

                if (!Win32Imports.VerQueryValue(buffer, @"\VarFileInfo\Translation", out subBlock, out len))
                {
                    throw new Exception("Failed to query version information." + Environment.NewLine +
                                        "Error CNF-404 in " + PROJ_FILE_NAME + ".validateData().");
                }

                for (int i = 0; i < INFONUM; i++)
                {
                    string spv = "\\StringFileInfo\\" + subBlock[0].ToString("X4") + subBlock[1].ToString("X4") + "\\" + InfoStr[i];

                    if (Win32Imports.VerQueryValue(buffer, spv, out val, out len))
                    {
                        switch (i)
                        {
                        case 0: result.CompanyName = val; break;

                        case 1: result.FileDescription = val; break;

                        case 2: result.FileVersion = val; break;

                        case 3: result.InternalName = val; break;

                        case 4: result.LegalCopyright = val; break;

                        case 5: result.LegalTradeMarks = val; break;

                        case 6: result.OriginalFileName = val; break;

                        case 7: result.ProductName = val; break;

                        case 8: result.ProductVersion = val; break;

                        case 9: result.Comments = val; break;
                        }                 // switch i
                    }                     // if Win32Imports.VerQueryValue
                }
            }
            catch (Exception e)
            {
                throw new Exception("Error retrieving file info." + Environment.NewLine +
                                    "Error CNF-405 in " + PROJ_FILE_NAME + ".validateData(): " + e.Message);
            }

            return(result);
        }
Exemplo n.º 19
0
        /// <summary>Shows the folder browser dialog box with the specified owner window.</summary>
        public DialogResult ShowDialog(IWin32Window owner = null)
        {
            const Win32Imports.BROWSEINFO.FLAGS privateOptions = Win32Imports.BROWSEINFO.FLAGS.NewDialogStyle | Win32Imports.BROWSEINFO.FLAGS.ShowTextBox;
            const int startLocation = 0;             // = Desktop CSIDL

            int Callback(IntPtr hwnd, uint uMsg, IntPtr lParam, IntPtr lpData)
            {
                if (uMsg == 1)
                {
                    var str = Marshal.StringToHGlobalUni(SelectedPath);
                    Win32Imports.SendMessage(hwnd, 0x400 + 103, (IntPtr)1, str);
                    Marshal.FreeHGlobal(str);
                }
                return(0);
            }

            var hWndOwner = owner?.Handle ?? Win32Imports.GetActiveWindow();

            _ = Win32Imports.SHGetSpecialFolderLocation(hWndOwner, startLocation, out var pidlRoot);
            if (pidlRoot == IntPtr.Zero)
            {
                return(DialogResult.Cancel);
            }
            var mergedOptions = publicOptions | privateOptions;

            if ((mergedOptions & Win32Imports.BROWSEINFO.FLAGS.NewDialogStyle) != 0 && ApartmentState.MTA == Application.OleRequired())
            {
                mergedOptions &= ~Win32Imports.BROWSEINFO.FLAGS.NewDialogStyle;
            }

            IntPtr pidlRet = default;

            try
            {
                var buffer = Marshal.AllocHGlobal(Win32Imports.MAX_PATH);
                var bi     = new Win32Imports.BROWSEINFO
                {
                    hwndOwner      = hWndOwner,
                    pidlRoot       = pidlRoot,
                    pszDisplayName = buffer,
                    lpszTitle      = Description,
                    ulFlags        = mergedOptions,
                    lpfn           = Callback
                };
                pidlRet = Win32Imports.SHBrowseForFolder(ref bi);
                Marshal.FreeHGlobal(buffer);
                if (pidlRet == IntPtr.Zero)
                {
                    return(DialogResult.Cancel);                                        // user clicked Cancel
                }
                var sb = new StringBuilder(Win32Imports.MAX_PATH);
                if (Win32Imports.SHGetPathFromIDList(pidlRet, sb) == 0)
                {
                    return(DialogResult.Cancel);
                }
                SelectedPath = sb.ToString();
            }
            finally
            {
                _ = Win32Imports.SHGetMalloc(out var malloc);
                malloc.Free(pidlRoot);
                if (pidlRet != IntPtr.Zero)
                {
                    malloc.Free(pidlRet);
                }
            }
            return(DialogResult.OK);
        }
Exemplo n.º 20
0
 public static void SetForegroundWindow(IntPtr windowHandle)
 {
     Win32Imports.SetForegroundWindow(windowHandle);
 }
Exemplo n.º 21
0
 public static IntPtr GetForegroundWindow()
 {
     return(Win32Imports.GetForegroundWindow());
 }
Exemplo n.º 22
0
        protected override void OnStartup(StartupEventArgs e)
        {
            if (File.Exists(Updater.SetupFile))
            {
                Thread.Sleep(1000);
            }

            bool createdNew;

            _mutex = new Mutex(true, Utility.Md5Hash(Utility.Md5Checksum(Directories.LoaderFilePath) + Utility.Md5Hash(Environment.UserName)), out createdNew);
            if (!createdNew)
            {
                if (e.Args.Length > 0)
                {
                    var wnd = Win32Imports.FindWindow(IntPtr.Zero, "LeagueSharp");
                    if (wnd != IntPtr.Zero)
                    {
                        Clipboard.SetText(e.Args[0]);
                        ShowWindow(wnd, 5);
                        SetForegroundWindow(wnd);
                    }
                }

                _mutex = null;
                Environment.Exit(0);
            }

            Utility.CreateFileFromResource(Directories.ConfigFilePath, "LeagueSharp.Loader.Resources.config.xml");

            var configCorrupted = false;

            try
            {
                Config.Instance = ((Config)Utility.MapXmlFileToClass(typeof(Config), Directories.ConfigFilePath));
            }
            catch (Exception)
            {
                configCorrupted = true;
            }

            if (!configCorrupted)
            {
                try
                {
                    if (File.Exists(Directories.ConfigFilePath + ".bak"))
                    {
                        File.Delete(Directories.ConfigFilePath + ".bak");
                    }
                    File.Copy(Directories.ConfigFilePath, Directories.ConfigFilePath + ".bak");
                    File.SetAttributes(Directories.ConfigFilePath + ".bak", FileAttributes.Hidden);
                }
                catch (Exception)
                {
                    //ignore
                }
            }
            else
            {
                try
                {
                    Config.Instance = ((Config)Utility.MapXmlFileToClass(typeof(Config), Directories.ConfigFilePath + ".bak"));
                    File.Delete(Directories.ConfigFilePath);
                    File.Copy(Directories.ConfigFilePath + ".bak", Directories.ConfigFilePath);
                    File.SetAttributes(Directories.ConfigFilePath, FileAttributes.Normal);
                }
                catch (Exception)
                {
                    File.Delete(Directories.ConfigFilePath + ".bak");
                    File.Delete(Directories.ConfigFilePath);
                    MessageBox.Show("Couldn't load config.xml.");
                    Environment.Exit(0);
                }
            }

            #region Remove the old loader

            try
            {
                if (String.Compare(
                        Process.GetCurrentProcess().ProcessName, "LeagueSharp.Loader.exe",
                        StringComparison.InvariantCultureIgnoreCase) != 0 && File.Exists(Path.Combine(Directories.CurrentDirectory, "LeagueSharp.Loader.exe")))
                {
                    File.Delete(Path.Combine(Directories.CurrentDirectory, "LeagueSharp.Loader.exe"));
                    File.Delete(Path.Combine(Directories.CurrentDirectory, "LeagueSharp.Loader.exe.config"));
                }
            }
            catch (Exception ex)
            {
                //ignore
            }

            #endregion

            #region AppData randomization

            try
            {
                if (!Directory.Exists(Directories.AppDataDirectory))
                {
                    Directory.CreateDirectory(Directories.AppDataDirectory);

                    var oldPath = Path.Combine(Environment.GetFolderPath(
                                                   Environment.SpecialFolder.ApplicationData), "LeagueSharp" + Environment.UserName.GetHashCode().ToString("X"));

                    var oldPath2 = Path.Combine(Environment.GetFolderPath(
                                                    Environment.SpecialFolder.ApplicationData), "LeagueSharp");

                    if (Directory.Exists(oldPath))
                    {
                        Utility.CopyDirectory(oldPath, Directories.AppDataDirectory, true, true);
                        Utility.ClearDirectory(oldPath);
                        Directory.Delete(oldPath, true);
                    }

                    if (Directory.Exists(oldPath2))
                    {
                        Utility.CopyDirectory(oldPath2, Directories.AppDataDirectory, true, true);
                        Utility.ClearDirectory(oldPath2);
                        Directory.Delete(oldPath2, true);
                    }
                }
            }
            catch (Exception ex)
            {
                //ignore
            }

            #endregion

            //Load the language resources.
            var dict = new ResourceDictionary();

            if (Config.Instance.SelectedLanguage != null)
            {
                dict.Source = new Uri(
                    "..\\Resources\\Language\\" + Config.Instance.SelectedLanguage + ".xaml", UriKind.Relative);
            }
            else
            {
                var lid = Thread.CurrentThread.CurrentCulture.ToString().Contains("-")
                    ? Thread.CurrentThread.CurrentCulture.ToString().Split('-')[0].ToUpperInvariant()
                    : Thread.CurrentThread.CurrentCulture.ToString().ToUpperInvariant();
                switch (lid)
                {
                case "DE":
                    dict.Source = new Uri("..\\Resources\\Language\\German.xaml", UriKind.Relative);
                    break;

                case "AR":
                    dict.Source = new Uri("..\\Resources\\Language\\Arabic.xaml", UriKind.Relative);
                    break;

                case "ES":
                    dict.Source = new Uri("..\\Resources\\Language\\Spanish.xaml", UriKind.Relative);
                    break;

                case "FR":
                    dict.Source = new Uri("..\\Resources\\Language\\French.xaml", UriKind.Relative);
                    break;

                case "IT":
                    dict.Source = new Uri("..\\Resources\\Language\\Italian.xaml", UriKind.Relative);
                    break;

                case "KO":
                    dict.Source = new Uri("..\\Resources\\Language\\Korean.xaml", UriKind.Relative);
                    break;

                case "NL":
                    dict.Source = new Uri("..\\Resources\\Language\\Dutch.xaml", UriKind.Relative);
                    break;

                case "PL":
                    dict.Source = new Uri("..\\Resources\\Language\\Polish.xaml", UriKind.Relative);
                    break;

                case "PT":
                    dict.Source = new Uri("..\\Resources\\Language\\Portuguese.xaml", UriKind.Relative);
                    break;

                case "RO":
                    dict.Source = new Uri("..\\Resources\\Language\\Romanian.xaml", UriKind.Relative);
                    break;

                case "RU":
                    dict.Source = new Uri("..\\Resources\\Language\\Russian.xaml", UriKind.Relative);
                    break;

                case "SE":
                    dict.Source = new Uri("..\\Resources\\Language\\Swedish.xaml", UriKind.Relative);
                    break;

                case "TR":
                    dict.Source = new Uri("..\\Resources\\Language\\Turkish.xaml", UriKind.Relative);
                    break;

                case "VI":
                    dict.Source = new Uri("..\\Resources\\Language\\Vietnamese.xaml", UriKind.Relative);
                    break;

                case "ZH":
                    dict.Source = new Uri("..\\Resources\\Language\\Chinese.xaml", UriKind.Relative);
                    break;

                case "LT":
                    dict.Source = new Uri("..\\Resources\\Language\\Lithuanian.xaml", UriKind.Relative);
                    break;

                default:
                    dict.Source = new Uri("..\\Resources\\Language\\English.xaml", UriKind.Relative);
                    break;
                }
            }

            if (Config.Instance.SelectedColor != null)
            {
                ThemeManager.ChangeAppStyle(Application.Current, ThemeManager.GetAccent(Config.Instance.SelectedColor), ThemeManager.GetAppTheme("BaseLight"));
            }

            Resources.MergedDictionaries.Add(dict);
            base.OnStartup(e);
        }
Exemplo n.º 23
0
 public IDisposable Save()
 {
     cw = Win32Imports._control87(0, 0);
     Win32Imports._control87(0x00000, 0x30000);
     return(this);
 }
Exemplo n.º 24
0
        internal unsafe bool LoadLibrary(byte[] data)
        {
            //fnDllEntry dllEntry;
            var dosHeader = PointerHelpers.ToStruct <IMAGE_DOS_HEADER>(data);


            var oldHeader = PointerHelpers.ToStruct <IMAGE_NT_HEADERS>(data, (uint)dosHeader.e_lfanew);

            var code = (IntPtr)(Win32Imports.VirtualAlloc(oldHeader.OptionalHeader.ImageBase,
                                                          oldHeader.OptionalHeader.SizeOfImage, Win32Constants.MEM_RESERVE, Win32Constants.PAGE_READWRITE));

            if (code.ToInt32() == 0)
            {
                code = (IntPtr)(Win32Imports.VirtualAlloc((uint)code, oldHeader.OptionalHeader.SizeOfImage,
                                                          Win32Constants.MEM_RESERVE, Win32Constants.PAGE_READWRITE));
            }

            module = new MEMORYMODULE {
                codeBase = code, numModules = 0, modules = new IntPtr(0), initialized = 0
            };

            Win32Imports.VirtualAlloc((uint)code, oldHeader.OptionalHeader.SizeOfImage, Win32Constants.MEM_COMMIT,
                                      Win32Constants.PAGE_READWRITE);

            var headers = (IntPtr)(Win32Imports.VirtualAlloc((uint)code, oldHeader.OptionalHeader.SizeOfHeaders,
                                                             Win32Constants.MEM_COMMIT, Win32Constants.PAGE_READWRITE));

            Marshal.Copy(data, 0, headers, (int)(dosHeader.e_lfanew + oldHeader.OptionalHeader.SizeOfHeaders));

            module.headers = PointerHelpers.ToStruct <IMAGE_NT_HEADERS>(headers, (uint)dosHeader.e_lfanew);
            module.headers.OptionalHeader.ImageBase = (uint)code;

            CopySections(data, oldHeader, headers, dosHeader);

            var locationDelta = (uint)(code - (int)oldHeader.OptionalHeader.ImageBase);

            if (locationDelta != 0)
            {
                PerformBaseRelocation(locationDelta);
            }

            BuildImportTable();
            FinalizeSections(headers, dosHeader, oldHeader);

            bool success = false;

            try
            {
                fnDllEntry dllEntry =
                    (fnDllEntry)
                    Marshal.GetDelegateForFunctionPointer(
                        new IntPtr(module.codeBase.ToInt32() + (int)module.headers.OptionalHeader.AddressOfEntryPoint),
                        typeof(fnDllEntry));
                success = dllEntry(code.ToInt32(), 1, (void *)0);
            }
            catch (Exception ex)
            {
                return(false);
            }

            return(success);
        }
Exemplo n.º 25
0
 public void Dispose()
 {
     Win32Imports._control87(cw, 0x30000);
 }
Exemplo n.º 26
0
 public void SetFocus()
 {
     Win32Imports.SetForegroundWindow(_process.MainWindowHandle);
 }
Exemplo n.º 27
0
        /// <summary>
        /// Allocates memory pages and sets header permissions.
        /// </summary>
        /// <param name="headers">The headers to write to each section of the PE.</param>
        /// <param name="dosHeader">The current header of the PE.</param>
        /// <param name="oldHeaders">The old headers of the PE that have been overwritten.</param>
        public void FinalizeSections(IntPtr headers, IMAGE_DOS_HEADER dosHeader, IMAGE_NT_HEADERS oldHeaders)
        {
            ProtectionFlags[0]       = new int[2][];
            ProtectionFlags[1]       = new int[2][];
            ProtectionFlags[0][0]    = new int[2];
            ProtectionFlags[0][1]    = new int[2];
            ProtectionFlags[1][0]    = new int[2];
            ProtectionFlags[1][1]    = new int[2];
            ProtectionFlags[0][0][0] = 0x01;
            ProtectionFlags[0][0][1] = 0x08;
            ProtectionFlags[0][1][0] = 0x02;
            ProtectionFlags[0][1][1] = 0x04;
            ProtectionFlags[1][0][0] = 0x10;
            ProtectionFlags[1][0][1] = 0x80;
            ProtectionFlags[1][1][0] = 0x20;
            ProtectionFlags[1][1][1] = 0x40;

            var section = PointerHelpers.ToStruct <IMAGE_SECTION_HEADER>(headers, (uint)(24 + dosHeader.e_lfanew + oldHeaders.FileHeader.SizeOfOptionalHeader));

            for (int i = 0; i < module.headers.FileHeader.NumberOfSections; i++)
            {
                int executable = (section.Characteristics & 0x20000000) != 0 ? 1 : 0;
                int readable   = (section.Characteristics & 0x40000000) != 0 ? 1 : 0;
                int writeable  = (section.Characteristics & 0x80000000) != 0 ? 1 : 0;

                if ((section.Characteristics & 0x02000000) > 0)
                {
                    bool aa = Win32Imports.VirtualFree(new IntPtr(section.PhysicalAddress), (UIntPtr)section.SizeOfRawData, 0x4000);
                    continue;
                }

                var protect = (uint)ProtectionFlags[executable][readable][writeable];

                if ((section.Characteristics & 0x04000000) > 0)
                {
                    protect |= 0x200;
                }
                var size = (int)section.SizeOfRawData;
                if (size == 0)
                {
                    if ((section.Characteristics & 0x00000040) > 0)
                    {
                        size = (int)module.headers.OptionalHeader.SizeOfInitializedData;
                    }
                    else if ((section.Characteristics & 0x00000080) > 0)
                    {
                        size = (int)module.headers.OptionalHeader.SizeOfUninitializedData;
                    }
                }

                if (size > 0)
                {
                    uint oldProtect;
                    if (!Win32Imports.VirtualProtect(new IntPtr(section.PhysicalAddress), section.SizeOfRawData, protect, out oldProtect))
                    {
                    }
                }

                section = PointerHelpers.ToStruct <IMAGE_SECTION_HEADER>(headers, (uint)((24 + dosHeader.e_lfanew + oldHeaders.FileHeader.SizeOfOptionalHeader) + (Marshal.SizeOf(typeof(IMAGE_SECTION_HEADER)) * (i + 1))));
            }
        }
Exemplo n.º 28
0
 public KeyboardCommandDispatcher(Process process)
 {
     _processWindowHandle = Win32Imports.FindWindowEx(process.MainWindowHandle, IntPtr.Zero, null, null);
 }