protected virtual void Dispose(bool disposing) { if (!_disposed) { if (disposing) { // free managed resources } if (_loadedModuleHandle != IntPtr.Zero) { if (_loadedFromMemory) { this.MemoryFreeLibrary(_loadedModuleHandle); } else { WinBase.FreeLibrary(_loadedModuleHandle); } _loadedModuleHandle = IntPtr.Zero; } _disposed = true; } }
protected static Boolean showWindow(CWinLoadParam param, String className) { WinBase cr = (WinBase)Activator.CreateInstance(Type.GetType(className), new object[] { param }); cr.ShowDialog(); return(cr.IsOKClick); }
public void GetFileAttributes() { var fileName = new Uri(this.TestData, @"./GetFileAttributesFact").LocalPath; var attributes = WinBase.GetFileAttributes(fileName); Assert.NotEqual(WinBase.INVALID_FILE_ATTRIBUTES, (int)attributes); Assert.True((attributes & WinNT.FILE_ATTRIBUTE_DIRECTORY) == WinNT.FILE_ATTRIBUTE_DIRECTORY); }
public static Boolean ShowWindow(String name, CWinLoadParam param) { String className = getClassName(name); WinBase cr = (WinBase)Activator.CreateInstance(Type.GetType(className), new object[] { param }); cr.ShowDialog(); Boolean result = cr.IsOKClick; return(result); }
internal static void SetFocus(WinBase window) { // if (window != null && CurFocus != window) { CurFocus?.OnLoseFocus(); CurFocus = window; window?.OnFocus(); } }
private void CreateProcess(string path, string shellToLaunch) { string WindowTitleToFind = "WindowsTerminal.UIA.Tests"; job = WinBase.CreateJobObject(IntPtr.Zero, IntPtr.Zero); NativeMethods.Win32NullHelper(job, "Creating job object to hold binaries under test."); Log.Comment("Attempting to launch command-line application at '{0}'", path); string binaryToRunPath = path; string args = $"new-tab --title \"{WindowTitleToFind}\" --suppressApplicationTitle \"{shellToLaunch}\""; string launchArgs = $"{binaryToRunPath} {args}"; WinBase.STARTUPINFO si = new WinBase.STARTUPINFO(); si.cb = Marshal.SizeOf(si); WinBase.PROCESS_INFORMATION pi = new WinBase.PROCESS_INFORMATION(); NativeMethods.Win32BoolHelper(WinBase.CreateProcess(null, launchArgs, IntPtr.Zero, IntPtr.Zero, false, WinBase.CP_CreationFlags.CREATE_SUSPENDED, IntPtr.Zero, null, ref si, out pi), "Attempting to create child host window process."); Log.Comment($"Host window PID: {pi.dwProcessId}"); NativeMethods.Win32BoolHelper(WinBase.AssignProcessToJobObject(job, pi.hProcess), "Assigning new host window (suspended) to job object."); NativeMethods.Win32BoolHelper(-1 != WinBase.ResumeThread(pi.hThread), "Resume host window process now that it is attached and its launch of the child application will be caught in the job object."); Globals.WaitForTimeout(); DesiredCapabilities appCapabilities = new DesiredCapabilities(); appCapabilities.SetCapability("app", @"Root"); Session = new IOSDriver <IOSElement>(new Uri(AppDriverUrl), appCapabilities); Verify.IsNotNull(Session); Actions = new Actions(Session); Verify.IsNotNull(Session); Globals.WaitForLongTimeout(); UIRoot = Session.FindElementByName(WindowTitleToFind); // Set the timeout to 15 seconds after we found the initial window. Session.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(15); }
/// <summary> /// Initializes a new instance of the NativeLibrary class from a native module stored on disk. /// </summary> /// <param name="lpLibFileName">Native module file name.</param> public DynamicNativeLibrary(string fileName) { _loadedModuleHandle = WinBase.LoadLibrary(fileName); if (_loadedModuleHandle == IntPtr.Zero) { throw new Exception("Module could not be loaded."); } _loadedFromMemory = false; }
public static WinBase GetObject(String name, CWinLoadParam loadParam) { if (windowMaps == null) { initMap(); } String className = getClassName(name); WinBase wb = (WinBase)Activator.CreateInstance(Type.GetType(className), new object[] { loadParam }); return(wb); }
private void ExitCmdProcess() { // Release attachment to the child process console. WinCon.FreeConsole(); this.UIRoot = null; if (this.job != IntPtr.Zero) { WinBase.TerminateJobObject(this.job, 0); } this.job = IntPtr.Zero; }
/// <summary> /// Copies sections from a native module file block to the new memory location. /// </summary> /// <param name="ptr_data">Pointer to a native module byte array.</param> /// <param name="ptr_old_headers">Pointer to a source native module headers.</param> /// <param name="memory_module">Pointer to a memory module.</param> private void CopySections(byte *ptr_data, byte *ptr_old_headers, MEMORY_MODULE *memory_module) { byte *codeBase = memory_module->codeBase; WinNT.IMAGE_SECTION_HEADER *section = WinNT.IMAGE_FIRST_SECTION(memory_module->headers); ushort numberOfSections; uint sectionAlignment; if (Environment.Is64BitProcess) { WinNT.IMAGE_NT_HEADERS64 *new_headers = (WinNT.IMAGE_NT_HEADERS64 *)memory_module->headers; numberOfSections = new_headers->FileHeader.NumberOfSections; WinNT.IMAGE_NT_HEADERS64 *old_headers = (WinNT.IMAGE_NT_HEADERS64 *)ptr_old_headers; sectionAlignment = old_headers->OptionalHeader.SectionAlignment; } else { WinNT.IMAGE_NT_HEADERS32 *new_headers = (WinNT.IMAGE_NT_HEADERS32 *)memory_module->headers; numberOfSections = new_headers->FileHeader.NumberOfSections; WinNT.IMAGE_NT_HEADERS32 *old_headers = (WinNT.IMAGE_NT_HEADERS32 *)ptr_old_headers; sectionAlignment = old_headers->OptionalHeader.SectionAlignment; } uint index; byte *dest; for (index = 0; index < numberOfSections; index++, section++) { if (section->SizeOfRawData == 0) { if (sectionAlignment > 0) { dest = (byte *)WinBase.VirtualAlloc((IntPtr)(codeBase + section->VirtualAddress), sectionAlignment, WinNT.MEM_COMMIT, WinNT.PAGE_READWRITE); section->PhysicalAddress = (uint)dest; memory.memset(dest, 0, sectionAlignment); } continue; } // commit memory block and copy data from dll dest = (byte *)WinBase.VirtualAlloc((IntPtr)(codeBase + section->VirtualAddress), section->SizeOfRawData, WinNT.MEM_COMMIT, WinNT.PAGE_READWRITE); memory.memcpy(dest, ptr_data + section->PointerToRawData, section->SizeOfRawData); section->PhysicalAddress = (uint)dest; } }
private void ExitProcess() { Globals.SweepAllModules(this.context); // Release attachment to the child process console. WinCon.FreeConsole(); this.UIRoot = null; if (this.job != IntPtr.Zero) { WinBase.TerminateJobObject(this.job, 0); } this.job = IntPtr.Zero; }
public static bool IsAvailable(ImeClass imeClass) { WinApi.Ole32.CoInitialize(IntPtr.Zero); if (Thread.CurrentThread.GetApartmentState() == ApartmentState.MTA) { throw new Exception("Cannot run under Multiple Threaded Apartment mode because it will fail while creating COM object IFELanguage."); } MsIme.IFELanguage ifeLanguage = null; try { int errCode = Ole32.CLSIDFromString(s_ImeClassNames[(int)imeClass], out Guid imeGuid); WinBase.CheckError(errCode); Guid feLangIID = new Guid(MsIme.Constants.IID_IFELanguage); IntPtr ppv; errCode = Ole32.CoCreateInstance(imeGuid, IntPtr.Zero, Ole32.CLSCTX_SERVER, feLangIID, out ppv); WinBase.CheckError(errCode); ifeLanguage = Marshal.GetTypedObjectForIUnknown(ppv, typeof(MsIme.IFELanguage)) as MsIme.IFELanguage; errCode = ifeLanguage.Open(); WinBase.CheckError(errCode); IntPtr cmodeCaps; errCode = ifeLanguage.GetConversionModeCaps(out cmodeCaps); WinBase.CheckError(errCode); } catch { try { ifeLanguage?.Close(); } catch { // ignore error. } return(false); } return(true); }
private void MarkedPicture_MouseMove(object sender, MouseEventArgs e) { Point de = ShowToPos(e.Location); if (IsChangingWinNow) { if (MarkedPicture.ChangingEdge == Direction.center && CurFocus is Board) { theMarkPicture.SetXY(MouseDownDelt.X - (int)(e.Location.X / CurDisplayRate), MouseDownDelt.Y - (int)(e.Location.Y / CurDisplayRate)); } //else if ((CurFocus as MarkPoint)==null) //{ //} else { CurFocus?.ChangeRect(e.Location); } SetCursor(de); //Refresh(); } else if (e.Button == MouseButtons.Right) { } else { MouseOnWin = TheBoard?.FindMouseOnRect(de); if ((MouseOnWin == CurFocus) && (CurFocus != TheBoard)) { //鼠标移动到当前焦点的范围内时,根据相对位置设置鼠标形状指示将改变哪个边。 SetCursor(de); } else { //鼠标不在焦点范围时,显示为默认鼠标。 Cursor = Cursors.Default; } } Refresh(); }
/// <summary> /// Deattach from the process and do a cleanup. /// </summary> /// <param name="hModule">Pointer to a memory module.</param> private void MemoryFreeLibrary(IntPtr hModule) { if (hModule == IntPtr.Zero) { return; } MEMORY_MODULE *memory_module = (MEMORY_MODULE *)hModule; if (memory_module != null) { if (memory_module->initialized != 0) { this.CallDllEntryPoint(memory_module, WinNT.DLL_PROCESS_DETACH); } if (memory_module->modules != null) { // free previously opened libraries for (int index = 0; index < memory_module->numModules; index++) { if (memory_module->modules[index] != IntPtr.Zero) { WinBase.FreeLibrary(memory_module->modules[index]); } } Marshal.FreeHGlobal((IntPtr)memory_module->modules); } if ((IntPtr)memory_module->codeBase != IntPtr.Zero) { // release memory of library WinBase.VirtualFree((IntPtr)memory_module->codeBase, 0, WinNT.MEM_RELEASE); } Marshal.FreeHGlobal((IntPtr)memory_module); } }
private void OpenIFELanguage() { if (_ifeLangOpened) { CloseIFELanguage(); } if (Thread.CurrentThread.GetApartmentState() == ApartmentState.MTA) { throw new Exception("Cannot run under Multiple Threaded Apartment mode because it will fail while creating COM object IFELanguage."); } Guid imeGuid; int errCode = Ole32.CLSIDFromString(s_ImeClassNames[(int)_imeClass], out imeGuid); WinBase.CheckError(errCode); Guid feLangIID = new Guid(MsIme.Constants.IID_IFELanguage); IntPtr ppv; errCode = Ole32.CoCreateInstance(imeGuid, IntPtr.Zero, Ole32.CLSCTX_SERVER, feLangIID, out ppv); WinBase.CheckError(errCode); _ifeLanguage = Marshal.GetTypedObjectForIUnknown(ppv, typeof(MsIme.IFELanguage)) as MsIme.IFELanguage; errCode = _ifeLanguage.Open(); WinBase.CheckError(errCode); _ifeLangOpened = true; IntPtr cmodeCaps; errCode = _ifeLanguage.GetConversionModeCaps(out cmodeCaps); WinBase.CheckError(errCode); _convModeCaps = cmodeCaps.ToInt32(); }
/// <summary> /// /// </summary> /// <param name="sourceDirName"></param> /// <param name="destDirName"></param> /// <param name="overwrite"></param> public static void Copy(string sourceDirName, string destDirName, bool overwrite) { if (!Directory.Exists(sourceDirName)) { throw new DirectoryNotFoundException(string.Format(@"{0}", sourceDirName)); } if (!Directory.Exists(destDirName)) { Directory.CreateDirectory(destDirName); } //else if (!overwrite) { /* 上書きしますか? */ } if (KandaDirectory.BeforeCopy != null) { KandaDirectory.BeforeCopy(null, EventArgs.Empty); } var entries = Directory.EnumerateFileSystemEntries(sourceDirName); foreach (var entry in entries) { var attributes = WinBase.GetFileAttributes(entry); if ((attributes & WinNT.FILE_ATTRIBUTE_DIRECTORY) == WinNT.FILE_ATTRIBUTE_DIRECTORY) { KandaDirectory.Copy(entry, Path.Combine(destDirName, new DirectoryInfo(entry).Name), overwrite); } else { var destFileName = Path.Combine(destDirName, new FileInfo(entry).Name); File.Copy(entry, destFileName, overwrite); } if (KandaDirectory.AfterCopy != null) { KandaDirectory.AfterCopy(null, EventArgs.Empty); } } }
/// <summary> /// 根据当前状态获取绘制检测窗的笔 /// </summary> /// <param name="win"></param> /// <param name="width"></param> /// <returns></returns> internal static Pen GetPenByWin(WinBase win, float width = 1) { if (win == null) { return(null); } if (win == MarkedPicture.MouseOnWin || win is Board) { width = 2; } if (win == CurFocus) { return(new Pen(Color.Red, width)); } else if ((win as CheckWinBase)?.hasResult ?? false) { return(new Pen(Color.Red, width)); } else { return(new Pen(Color.Blue, width)); } }
internal static Pen GetPenByShape(ShapeBase shape, float width) { WinBase win = TheBoard?.SubWinList?.Find(p => p.ShowShape == shape); return(GetPenByWin(win, width)); }
private void CreateCmdProcess(string path, string link = "") { //string AdminPrefix = "Administrator: "; string WindowTitleToFind = "Host.Tests.UIA window under test"; job = WinBase.CreateJobObject(IntPtr.Zero, IntPtr.Zero); NativeMethods.Win32NullHelper(job, "Creating job object to hold binaries under test."); Log.Comment("Attempting to launch command-line application at '{0}'", path); string binaryToRunPath = path; #if __INSIDE_WINDOWS string launchArgs = binaryToRunPath; #else string openConsolePath = Path.Combine(this.context.TestDeploymentDir, "OpenConsole.exe"); string launchArgs = $"{openConsolePath} {binaryToRunPath}"; #endif WinBase.STARTUPINFO si = new WinBase.STARTUPINFO(); si.cb = Marshal.SizeOf(si); // If we were given a LNK file to startup with, set the STARTUPINFO structure to pass that information in to the console host. if (!string.IsNullOrEmpty(link)) { si.dwFlags |= WinBase.STARTF.STARTF_TITLEISLINKNAME; si.lpTitle = link; } WinBase.PROCESS_INFORMATION pi = new WinBase.PROCESS_INFORMATION(); NativeMethods.Win32BoolHelper(WinBase.CreateProcess(null, launchArgs, IntPtr.Zero, IntPtr.Zero, false, WinBase.CP_CreationFlags.CREATE_NEW_CONSOLE | WinBase.CP_CreationFlags.CREATE_SUSPENDED, IntPtr.Zero, null, ref si, out pi), "Attempting to create child host window process."); Log.Comment($"Host window PID: {pi.dwProcessId}"); NativeMethods.Win32BoolHelper(WinBase.AssignProcessToJobObject(job, pi.hProcess), "Assigning new host window (suspended) to job object."); NativeMethods.Win32BoolHelper(-1 != WinBase.ResumeThread(pi.hThread), "Resume host window process now that it is attached and its launch of the child application will be caught in the job object."); Globals.WaitForTimeout(); WinBase.JOBOBJECT_BASIC_PROCESS_ID_LIST list = new WinBase.JOBOBJECT_BASIC_PROCESS_ID_LIST(); list.NumberOfAssignedProcesses = 2; int listptrsize = Marshal.SizeOf(list); IntPtr listptr = Marshal.AllocHGlobal(listptrsize); Marshal.StructureToPtr(list, listptr, false); TimeSpan totalWait = TimeSpan.Zero; TimeSpan waitLimit = TimeSpan.FromSeconds(30); TimeSpan pollInterval = TimeSpan.FromMilliseconds(500); while (totalWait < waitLimit) { WinBase.QueryInformationJobObject(job, WinBase.JOBOBJECTINFOCLASS.JobObjectBasicProcessIdList, listptr, listptrsize, IntPtr.Zero); list = (WinBase.JOBOBJECT_BASIC_PROCESS_ID_LIST)Marshal.PtrToStructure(listptr, typeof(WinBase.JOBOBJECT_BASIC_PROCESS_ID_LIST)); if (list.NumberOfAssignedProcesses > 1) { break; } else if (list.NumberOfAssignedProcesses < 1) { Verify.Fail("Somehow we lost the one console host process in the job already."); } Thread.Sleep(pollInterval); totalWait += pollInterval; } Verify.IsLessThan(totalWait, waitLimit); WinBase.QueryInformationJobObject(job, WinBase.JOBOBJECTINFOCLASS.JobObjectBasicProcessIdList, listptr, listptrsize, IntPtr.Zero); list = (WinBase.JOBOBJECT_BASIC_PROCESS_ID_LIST)Marshal.PtrToStructure(listptr, typeof(WinBase.JOBOBJECT_BASIC_PROCESS_ID_LIST)); Verify.AreEqual(list.NumberOfAssignedProcesses, list.NumberOfProcessIdsInList); #if __INSIDE_WINDOWS pid = pi.dwProcessId; #else // Take whichever PID isn't the host window's PID as the child. pid = pi.dwProcessId == (int)list.ProcessId ? (int)list.ProcessId2 : (int)list.ProcessId; Log.Comment($"Child command app PID: {pid}"); #endif // Free any attached consoles and attach to the console we just created. // The driver will bind our calls to the Console APIs into the child process. // This will allow us to use the APIs to get/set the console state of the test window. NativeMethods.Win32BoolHelper(WinCon.FreeConsole(), "Free existing console bindings."); // need to wait a bit or we might not be able to reliably attach System.Threading.Thread.Sleep(Globals.Timeout); NativeMethods.Win32BoolHelper(WinCon.AttachConsole((uint)pid), "Bind to the new PID for console APIs."); // we need to wait here for a bit or else // setting the console window title will fail. System.Threading.Thread.Sleep(Globals.Timeout * 5); NativeMethods.Win32BoolHelper(WinCon.SetConsoleTitle(WindowTitleToFind), "Set the window title so AppDriver can find it."); DesiredCapabilities appCapabilities = new DesiredCapabilities(); appCapabilities.SetCapability("app", @"Root"); Session = new IOSDriver <IOSElement>(new Uri(AppDriverUrl), appCapabilities); Verify.IsNotNull(Session); Actions = new Actions(Session); Verify.IsNotNull(Session); Globals.WaitForTimeout(); // If we are running as admin, the child window title will have a prefix appended as it will also run as admin. //if (IsRunningAsAdmin()) //{ // WindowTitleToFind = $"{AdminPrefix}{WindowTitleToFind}"; //} Log.Comment($"Searching for window title '{WindowTitleToFind}'"); this.UIRoot = Session.FindElementByName(WindowTitleToFind); this.hStdOut = WinCon.GetStdHandle(WinCon.CONSOLE_STD_HANDLE.STD_OUTPUT_HANDLE); Verify.IsNotNull(this.hStdOut, "Ensure output handle is valid."); this.hStdErr = WinCon.GetStdHandle(WinCon.CONSOLE_STD_HANDLE.STD_ERROR_HANDLE); Verify.IsNotNull(this.hStdErr, "Ensure error handle is valid."); // Set the timeout to 15 seconds after we found the initial window. Session.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(15); }
/// <summary> /// Marks memory pages depending on section headers and release sections that are marked as "discardable". /// </summary> /// <param name="memory_module">Pointer to a memory module.</param> private void FinalizeSections(MEMORY_MODULE *memory_module) { WinNT.IMAGE_SECTION_HEADER *section = WinNT.IMAGE_FIRST_SECTION(memory_module->headers);; ushort number_of_sections; uint size_of_initialized_data; uint size_of_uninitialized_data; long image_offset = 0; if (Environment.Is64BitProcess) { WinNT.IMAGE_NT_HEADERS64 *headers = (WinNT.IMAGE_NT_HEADERS64 *)memory_module->headers; number_of_sections = headers->FileHeader.NumberOfSections; size_of_initialized_data = headers->OptionalHeader.SizeOfInitializedData; size_of_uninitialized_data = headers->OptionalHeader.SizeOfUninitializedData; image_offset = (long)((ulong)headers->OptionalHeader.ImageBase & 0xffffffff00000000); } else { WinNT.IMAGE_NT_HEADERS32 *headers = (WinNT.IMAGE_NT_HEADERS32 *)memory_module->headers; number_of_sections = headers->FileHeader.NumberOfSections; size_of_initialized_data = headers->OptionalHeader.SizeOfInitializedData; size_of_uninitialized_data = headers->OptionalHeader.SizeOfUninitializedData; } for (int i = 0; i < number_of_sections; i++, section++) { uint protect, oldProtect, rawDataSize; uint executable = Convert.ToUInt32((section->Characteristics & WinNT.IMAGE_SCN_MEM_EXECUTE) != 0); uint readable = Convert.ToUInt32((section->Characteristics & WinNT.IMAGE_SCN_MEM_READ) != 0); uint writeable = Convert.ToUInt32((section->Characteristics & WinNT.IMAGE_SCN_MEM_WRITE) != 0); if ((section->Characteristics & WinNT.IMAGE_SCN_MEM_DISCARDABLE) != 0) { // section is not needed any more and can safely be freed WinBase.VirtualFree((IntPtr)(void *)((long)section->PhysicalAddress | (long)image_offset), section->SizeOfRawData, WinNT.MEM_DECOMMIT); continue; } protect = _protectionFlags[executable, readable, writeable]; if ((section->Characteristics & WinNT.IMAGE_SCN_MEM_NOT_CACHED) != 0) { protect |= WinNT.PAGE_NOCACHE; } // determine size of region rawDataSize = section->SizeOfRawData; if (rawDataSize == 0) { if ((section->Characteristics & WinNT.IMAGE_SCN_CNT_INITIALIZED_DATA) != 0) { rawDataSize = size_of_initialized_data; } else if ((section->Characteristics & WinNT.IMAGE_SCN_CNT_UNINITIALIZED_DATA) != 0) { rawDataSize = size_of_uninitialized_data; } } if (rawDataSize > 0) { // change memory access flags WinBase.VirtualProtect((IntPtr)(void *)((long)section->PhysicalAddress | (long)image_offset), rawDataSize, protect, &oldProtect); } } }
/// <summary> /// Loads required dlls and adjust function table of the imports. /// </summary> /// <param name="memory_module">Pointer to a memory module.</param> /// <returns>If the function succeeds, the return value is true.</returns> private bool BuildImportTable(MEMORY_MODULE *memory_module) { bool result = true; WinNT.IMAGE_DATA_DIRECTORY *directory = this.GET_HEADER_DIRECTORY(memory_module, WinNT.IMAGE_DIRECTORY_ENTRY_IMPORT); if (directory->Size > 0) { WinNT.IMAGE_IMPORT_DESCRIPTOR *importDesc = (WinNT.IMAGE_IMPORT_DESCRIPTOR *)(memory_module->codeBase + directory->VirtualAddress); for (; importDesc->Name != 0; importDesc++) { IntPtr *thunkRef; IntPtr *funcRef; string moduleName = Marshal.PtrToStringAnsi((IntPtr)(memory_module->codeBase + importDesc->Name)); IntPtr handle = WinBase.LoadLibrary(moduleName); if (handle == IntPtr.Zero) { result = false; break; } int size_of_pointer = sizeof(IntPtr); memory_module->modules = (IntPtr *)memory.realloc((byte *)memory_module->modules, (uint)((memory_module->numModules) * size_of_pointer), (uint)((memory_module->numModules + 1) * size_of_pointer)); if (memory_module->modules == null) { result = false; break; } memory_module->modules[memory_module->numModules++] = handle; if (importDesc->Characteristics != 0) { thunkRef = (IntPtr *)(memory_module->codeBase + importDesc->Characteristics); funcRef = (IntPtr *)(memory_module->codeBase + importDesc->FirstThunk); } else { thunkRef = (IntPtr *)(memory_module->codeBase + importDesc->FirstThunk); funcRef = (IntPtr *)(memory_module->codeBase + importDesc->FirstThunk); } for (; *thunkRef != IntPtr.Zero; thunkRef++, funcRef++) { if (WinNT.IMAGE_SNAP_BY_ORDINAL(thunkRef)) { *funcRef = WinBase.GetProcAddress(handle, (byte *)WinNT.IMAGE_ORDINAL(thunkRef)); } else { WinNT.IMAGE_IMPORT_BY_NAME *thunkData = (WinNT.IMAGE_IMPORT_BY_NAME *)(memory_module->codeBase + (ulong)*thunkRef); //string procName = Marshal.PtrToStringAnsi((IntPtr)(byte*)(thunkData) + 2); IntPtr a = (IntPtr)(byte *)(thunkData); string procName = Marshal.PtrToStringAnsi(new IntPtr(a.ToInt64() + 2)); * funcRef = WinBase.GetProcAddress(handle, procName); } if (*funcRef == IntPtr.Zero) { result = false; break; } } if (!result) { break; } } } return(result); }
/// <summary> /// Loads the specified native module from a byte array into the address space of the calling process. /// </summary> /// <param name="data">Native module byte array.</param> /// <returns>If the function succeeds, the return value is a handle to the module.</returns> private IntPtr MemoryLoadLibrary(byte[] data) { fixed(byte *ptr_data = data) { WinNT.IMAGE_DOS_HEADER *dos_header = (WinNT.IMAGE_DOS_HEADER *)ptr_data; if (dos_header->e_magic != WinNT.IMAGE_DOS_SIGNATURE) { throw new NotSupportedException(); } byte * ptr_old_header; uint old_header_oh_sizeOfImage; uint old_header_oh_sizeOfHeaders; int image_nt_headers_Size; IntPtr old_header_oh_imageBase; if (Environment.Is64BitProcess) { WinNT.IMAGE_NT_HEADERS64 *old_header = (WinNT.IMAGE_NT_HEADERS64 *)(ptr_data + dos_header->e_lfanew); if (old_header->Signature != WinNT.IMAGE_NT_SIGNATURE) { throw new NotSupportedException(); } old_header_oh_sizeOfImage = old_header->OptionalHeader.SizeOfImage; old_header_oh_sizeOfHeaders = old_header->OptionalHeader.SizeOfHeaders; old_header_oh_imageBase = old_header->OptionalHeader.ImageBase; ptr_old_header = (byte *)old_header; image_nt_headers_Size = sizeof(WinNT.IMAGE_NT_HEADERS64); } else { WinNT.IMAGE_NT_HEADERS32 *old_header = (WinNT.IMAGE_NT_HEADERS32 *)(ptr_data + dos_header->e_lfanew); if (old_header->Signature != WinNT.IMAGE_NT_SIGNATURE) { throw new NotSupportedException(); } old_header_oh_sizeOfImage = old_header->OptionalHeader.SizeOfImage; old_header_oh_sizeOfHeaders = old_header->OptionalHeader.SizeOfHeaders; old_header_oh_imageBase = old_header->OptionalHeader.ImageBase; ptr_old_header = (byte *)old_header; image_nt_headers_Size = sizeof(WinNT.IMAGE_NT_HEADERS32); } IntPtr codeBase = IntPtr.Zero; if (!Environment.Is64BitProcess) { codeBase = WinBase.VirtualAlloc(old_header_oh_imageBase, old_header_oh_sizeOfImage, WinNT.MEM_RESERVE, WinNT.PAGE_READWRITE); } if (codeBase == IntPtr.Zero) { codeBase = WinBase.VirtualAlloc(IntPtr.Zero, old_header_oh_sizeOfImage, WinNT.MEM_RESERVE, WinNT.PAGE_READWRITE); } if (codeBase == IntPtr.Zero) { return(IntPtr.Zero); } MEMORY_MODULE *memory_module = (MEMORY_MODULE *)Marshal.AllocHGlobal(sizeof(MEMORY_MODULE)); memory_module->codeBase = (byte *)codeBase; memory_module->numModules = 0; memory_module->modules = null; memory_module->initialized = 0; WinBase.VirtualAlloc(codeBase, old_header_oh_sizeOfImage, WinNT.MEM_COMMIT, WinNT.PAGE_READWRITE); IntPtr headers = WinBase.VirtualAlloc(codeBase, old_header_oh_sizeOfHeaders, WinNT.MEM_COMMIT, WinNT.PAGE_READWRITE); // copy PE header to code memory.memcpy((byte *)headers, (byte *)dos_header, dos_header->e_lfanew + old_header_oh_sizeOfHeaders); memory_module->headers = &((byte *)(headers))[dos_header->e_lfanew]; if (Environment.Is64BitProcess) { WinNT.IMAGE_NT_HEADERS64 *mm_headers_64 = (WinNT.IMAGE_NT_HEADERS64 *)(memory_module->headers); mm_headers_64->OptionalHeader.ImageBase = codeBase; } else { WinNT.IMAGE_NT_HEADERS32 *mm_headers_32 = (WinNT.IMAGE_NT_HEADERS32 *)(memory_module->headers); mm_headers_32->OptionalHeader.ImageBase = codeBase; } this.CopySections(ptr_data, ptr_old_header, memory_module); ulong locationDelta = (ulong)((ulong)codeBase - (ulong)old_header_oh_imageBase); if (locationDelta != 0) { this.PerformBaseRelocation(memory_module, locationDelta); } if (!this.BuildImportTable(memory_module)) { goto error; } this.FinalizeSections(memory_module); if (!this.CallDllEntryPoint(memory_module, WinNT.DLL_PROCESS_ATTACH)) { goto error; } return((IntPtr)memory_module); error: MemoryFreeLibrary((IntPtr)memory_module); return(IntPtr.Zero); } }
/// <summary> /// Retrieves the address of an exported function or variable from loaded module. /// </summary> /// <param name="procName">The function or variable name.</param> /// <returns> /// If the function succeeds, the return value is the address of the exported function or variable. /// If the function fails, the return value is IntPtr.Zero. /// </returns> private IntPtr GetProcAddress(string procName) { if (_loadedModuleHandle == IntPtr.Zero) { return(IntPtr.Zero); } if (!_loadedFromMemory) { return(WinBase.GetProcAddress(_loadedModuleHandle, procName)); } MEMORY_MODULE *memory_module = (MEMORY_MODULE *)_loadedModuleHandle; byte *codeBase = memory_module->codeBase; int idx = -1; uint i; uint * nameRef; ushort *ordinal; WinNT.IMAGE_DATA_DIRECTORY *directory = this.GET_HEADER_DIRECTORY(memory_module, WinNT.IMAGE_DIRECTORY_ENTRY_EXPORT); if (directory->Size == 0) { // no export table found return(IntPtr.Zero); } WinNT.IMAGE_EXPORT_DIRECTORY *exports = (WinNT.IMAGE_EXPORT_DIRECTORY *)(codeBase + directory->VirtualAddress); if (exports->NumberOfNames == 0 || exports->NumberOfFunctions == 0) { // DLL doesn't export anything return(IntPtr.Zero); } // search function name in list of exported names nameRef = (uint *)(codeBase + exports->AddressOfNames); ordinal = (ushort *)(codeBase + exports->AddressOfNameOrdinals); for (i = 0; i < exports->NumberOfNames; i++, nameRef++, ordinal++) { IntPtr procNameHandle = (IntPtr)((byte *)((ulong)codeBase + *nameRef)); string testProcName = Marshal.PtrToStringAnsi(procNameHandle); if (testProcName == procName) { idx = *ordinal; break; } } if (idx == -1) { // exported symbol not found return(IntPtr.Zero); } if ((uint)idx > exports->NumberOfFunctions) { // name <-> ordinal number don't match return(IntPtr.Zero); } // AddressOfFunctions contains the RVAs to the "real" functions //return (IntPtr)((uint)codeBase + *(uint*)((uint)codeBase + exports->AddressOfFunctions + (idx * 4))); return((IntPtr)(codeBase + *(uint *)(codeBase + exports->AddressOfFunctions + (idx * 4)))); }
internal void AddComponent(WinBase win) { markedPicture1.AddWin(win); SetFocus(win); }
protected static void showWindow(CWinLoadParam param, String className) { WinBase cr = (WinBase)Activator.CreateInstance(Type.GetType(className), new object[] { param }); cr.ShowDialog(); }
internal void AddWin(WinBase win) { TheBoard?.AddWin(win, MpCenter); Refresh(); }