public static bool?IsShiftButtonPushed() { switch (PlatformHelper.GetOperatingSystemType()) { case OperatingSystemType.WinNT: return(WinNT.IsShiftButtonPushed()); default: return(null); } }
public void LuuChuoiKetNoiVaoFile(string path) { using (StreamWriter sW = new StreamWriter(path)) { sW.WriteLine(string.Format("server = {0}", ServerName)); sW.WriteLine(string.Format("database = {0}", DatabaseName)); sW.WriteLine(string.Format("uid = {0}", Uid)); sW.WriteLine(string.Format("pwd = {0}", Pwd)); sW.Write(string.Format("winnt = {0}", WinNT.ToString())); } }
public static (bool success, string errorMsg) CreateAsBreakawayFromJob(string executeFileName, string commandLine) { switch (PlatformHelper.GetOperatingSystemType()) { case OperatingSystemType.WinNT: return(WinNT.CreateAsBreakawayFromJob(commandLine), null); default: return(ProcessStart(executeFileName), null); //return (false, $"Not implemented for OS '{pi.OperatingSystem}'"); } }
public void FormatMessage() { var messageId = Kernel32.GetLastError(); var languageId = WinNT.MAKELANGID(WinNT.LANG_NEUTRAL, WinNT.SUBLANG_DEFAULT); var buffer = default(IntPtr); var length = Kernel32.FormatMessage((WinBase.FORMAT_MESSAGE_ALLOCATE_BUFFER | WinBase.FORMAT_MESSAGE_FROM_SYSTEM | WinBase.FORMAT_MESSAGE_IGNORE_INSERTS), IntPtr.Zero, messageId, languageId, out buffer, 0, null); var message = Marshal.PtrToStringAnsi(buffer, (int)length); Assert.False(length <= 0, message); }
/// <summary> /// Returns parameter <see cref="DrCmdSettings.HelpMaxLineLength"/> as the maximum number of characters in a single line in the help. /// If it is not specified, returns the BufferWidth-1 value from <see cref="Console"/> /// Returns <see cref="DrCmdConst.SYMBOLS_LEIGHT_FOR_NONE_CONSOLE_OUT"/> value if StdOut is redirectred from console to something else /// </summary> /// <returns></returns> internal int GetSettingsHelpMaxLineLength() { int consoleBuffer = DrCmdConst.SYMBOLS_LEIGHT_FOR_NONE_CONSOLE_OUT; uint cMode; if (WinNT.GetConsoleMode(WinNT.GetStdHandle(WinNT.STD_OUTPUT_HANDLE), out cMode)) { try { consoleBuffer = Console.BufferWidth - 1; } catch { consoleBuffer = DrCmdConst.DEFAULT_CONSOLE_BUFFER; } } return(Settings.Attributes.GetValue(DrCmdSettings.HelpMaxLineLength, consoleBuffer)); }
/// <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; } }
public static void TryMessageBox_ShowError(string text, string caption) { if (IsWinNT()) { WinNT.MessageBox_ShowError(text, caption); } else { try { Extensions.MessageBox_ShowError(text, caption).Wait(); } catch (Exception ex) { Debug.WriteLine(ex); throw (new InvalidOperationException(text)); } } }
private static SafeFileHandle CreateFileHandle(string path, FileMode mode, FileAccess access, FileShare share, bool sequential) { var flags = sequential ? WinNT.FILE_FLAG_SEQUENTIAL_SCAN : 0; var fileHandle = WinNT.CreateFile(path, (uint)access, (uint)share, IntPtr.Zero, (uint)mode, (uint)flags, IntPtr.Zero); if (!fileHandle.IsInvalid) { return(fileHandle); } // Check for errors. var lastWin32Error = Marshal.GetLastWin32Error(); throw new Win32Exception( lastWin32Error, $"Error {lastWin32Error} creating file handle for file path '{path}': {new Win32Exception(lastWin32Error).Message}"); }
/// <summary> /// 创建沙盒 /// </summary> /// <param name="file">文件名称</param> /// <param name="args">启动参数</param> /// <param name="stderr">是否重定向stderr</param> /// <param name="stdin">是否重定向stdin</param> /// <returns>新的沙盒进程实例</returns> public static SandboxProcess Create(string file, string args = "", bool stderr = false, bool stdin = false, bool cd = false) { if (!File.Exists(file)) { Trace.WriteLine($"File doesn't exist: {file}"); return(null); } SandboxProcess ret; if (Environment.OSVersion.Platform == PlatformID.Unix) { ret = new Linux(); } else { ret = new WinNT(); } ret.info.RedirectStandardOutput = true; ret.info.StandardOutputEncoding = Console.Out.Encoding; ret.info.RedirectStandardError = stderr; if (stderr) { ret.info.StandardErrorEncoding = Console.Error.Encoding; } ret.info.RedirectStandardInput = stdin; ret.info.CreateNoWindow = true; ret.info.UseShellExecute = false; ret.info.FileName = file; ret.info.Arguments = args; ret.info.WorkingDirectory = cd && Directory.Exists(WorkingDirectory) ? WorkingDirectory : Environment.CurrentDirectory; return(ret); }
/// <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); }