I am trapping for the execution of some old 16-bit applications that our internal folks should no longer be using. They are 1985 DOS apps, so trapping for them was easy... capture any process that launches under NTVDM.exe
Now, the problem is finding out which program NTVDM is actually running under the hood. Apparently there are a coupleof the 1985 programs that they SHOULD be allowed to run, so I need to see the actual EXE name that is hiding under NTVDM.
WqlEventQuery query =
new WqlEventQuery("__InstanceCreationEvent",
new TimeSpan(0, 0, 1),
"TargetInstance isa \"Win32_Process\"");
ManagementEventWatcher watcher = new ManagementEventWatcher(query);
watcher.EventArrived += new EventArrivedEventHandler(watcher_EventArrived);
watcher.Start();
...
static void watcher_EventArrived(object sender, EventArrivedEventArgs e)
{
ManagementBaseObject instance = (ManagementBaseObject)e.NewEvent["TargetInstance"];
ProcessInfo PI = new ProcessInfo();
PI.ProcessID = int.Parse(instance["ProcessID"].ToString());
PI.ProcessName = instance["Name"].ToString();
PI.ProcessPath = instance["ExecutablePath"].ToString();
// Here's the part I need...
PI.ActualEXE = ???;
// ... do the magic on the PI class ...
instance.Dispose();
}
When I capture the instance information, I can get the command line, but the arguments are "-f -i10" ... There is no EXE name on the command line. Is there any other method/property I should be looking at to determine the EXE name of the 16-bit application that's actually running?
UPDATE: Let me refine the question: If I can find the NTVDM process, how can I -- programatically -- know the actual path to the EXE that is being executed underneath?
Thanks.
The trick is not to use VDMEnumProcessWOW (which gives the VDMs), but to use VDMEnumTasksWOW. The enumerator function that you pass to this function will be called for each 16 bit task in the specified VDM.
I haven't checked it myself, but according to the documentation, this library of CodeProject does exactly that, if you pass in the PROC16 enum value. It's C++, if you need help compiling that code and calling it from C#, let me know and I'll give you an example.
A program that uses this technique is Process Master, it comes with full source. I suggest you run it to find out whether it gives the info you need, and if so, you can apply this method to your own application (it doesn't run on Windows Vista or 7, it uses old VB5 code, apparently it's not compatible. It should run on XP).
If things with these functions do not go as planned, you may be on Vista and may need the hotfix described in this StackOverflow question, which points to downloading a hotfix, which is in turn described here:
"An application that uses the
VDMEnumProcessWOW function to
enumerate virtual DOS machines returns
no output or incorrect output on a
computer that is running a 32-bit
version of Windows Vista"
Update: while this seems promising, I applied the patch, ran several versions of the code, including Microsoft's, and while they all work on XP, they fail silently (no error, or wrong return value) on Vista.
The "kinda" working code
Update: I experimented with (amongst others) with the following code, which compiles fine in C# (and can be written simpler, but I didn't want to run a marshal-mistake risk). When you add these functions, you can call Enum16BitProcesses, which will write the filenames of the EXE files of the 16 bit processes to the Console.
I can't run it on Vista 32 bit. But perhaps others can try and compile it, or find the error in the code. It would be nice to know whether it works on other systems:
public class YourEnumerateClass
{
public static void Enum16BitProcesses()
{
// create a delegate for the callback function
ProcessTasksExDelegate procTasksDlgt =
new ProcessTasksExDelegate(YourEnumerateClass.ProcessTasksEx);
// this part is the easy way of getting NTVDM procs
foreach (var ntvdm in Process.GetProcessesByName("ntvdm"))
{
Console.WriteLine("ntvdm id = {0}", ntvdm.Id);
int apiRet = VDMEnumTaskWOWEx(ntvdm.Id, procTasksDlgt, IntPtr.Zero);
Console.WriteLine("EnumTaskWOW returns {0}", apiRet);
}
}
// declaration of API function callback
public delegate bool ProcessTasksExDelegate(
int ThreadId,
IntPtr hMod16,
IntPtr hTask16,
IntPtr ptrModName,
IntPtr ptrFileName,
IntPtr UserDefined
);
// the actual function that fails on Vista so far
[DllImport("VdmDbg.dll", SetLastError = false, CharSet = CharSet.Auto)]
public static extern int VDMEnumTaskWOWEx(
int processId,
ProcessTasksExDelegate TaskEnumProc,
IntPtr lparam);
// the actual callback function, on Vista never gets called
public static bool ProcessTasksEx(
int ThreadId,
IntPtr hMod16,
IntPtr hTask16,
IntPtr ptrModName,
IntPtr ptrFileName,
IntPtr UserDefined
)
{
// using PtrToStringAnsi, based on Matt's comment, if it fails, try PtrToStringAuto
string filename = Marshal.PtrToStringAnsi(ptrFileName);
Console.WriteLine("Filename of WOW16 process: {0}", filename);
return false; // false continues enumeration
}
}
Update: Intriguing read by the renown Matt Pietrek. Mind the sentence, somewhere near the end:
"For starters, MS-DOS-based programs
seem to always run in separate NTVDM
sessions. I was never able to get an
MS-DOS-based program to run in the
same session as a 16-bit Windows-based
program. Nor was I able to get two
independently started MS-DOS-based
programs to run in the same NTVDM
session. In fact, NTVDM sessions
running MS-DOS programs don't show up
in VDMEnumProcessWOW enumerations."
Seems that, to find out what processes are loaded, you'll need to write a hook into NTVDM or write a listener that monitors access to the file. When the application that tries to read a certain DOS file is NTVDM.exe, it's bingo. You may want to write a DLL that's only attached to NTVDM.exe, but now we're getting a bit ahead of ourselves. Long story short: this little ride into NTVDM has shown "possibilities" that appeared real hoaxes in the end.
There's one other way, but time is too short to create an example. You can poke around in the DOS memory segments and the EXE is usually loaded at the same segment. But I'm unsure if that eventually will lead to the same result and whether it's worth the effort.
This works for me:
Follow the instructions at Description of the Software Restriction Policies in Windows XP to open the local or domain policy editor.
Under Software Restriction Policies -> Additional Rules, right click and select New Hash Rule.
Browse to (for example) edit.com. Make sure Security Level is set to Disallowed. Click OK.
Now,
C:\>edit
The system cannot execute the specified program.
(I get the same results from command.com and cmd.exe -- under Win XP)
From this link about VDMDBG functions, you may be able to P/Invoke "VDMEnumProcessWOW()", then enumerate modules within the process using PSAPI.
Note Regarding 16-bit DOS Applications:
None of the VDMDBG functions work with
16-bit DOS applications. To enumerate
DOS VDMs, you need to use another
method. First, you could use
VDMEnumProcessWOW() to make a list of
all Win16 VDMs, and then enumerate all
instances of NTVDM.exe using some
other scheme (such as PSAPI). Any
NTVDM.exe from the full enumeration
that was not in the Win16 list is a
DOS VDM. You can create and terminate
16-bit DOS applications with
CreateProcess() and
TerminateProcess().
Hope that helps...
Related
So I am trying to write a cd -like program that can be executed using cmd and after it exits the working directory of the calling cmd process should be changed.
Now before this post is flagged as a duplicate: I am aware of this and this question that were asked for pretty much this exact problem but using Linux instead of Windows as well as being pretty broad and unspecific, and I am aware that similar limitations apply to Windows as well (changing the working directory of my process will not change the parent’s working directory).
There is actually is a working solution to this for linux. However it is using gdb for this, and I would like to achieve this task using only built-in Windows utilities (WinAPI, dotNET, etc.).
What I have tried so far
I did manage to use Cheat Engine and the OpenProcess() / WriteProcessMemory() WinAPI funtions to successfully override cmd's working directory. However this solution feels sloppy and doesn't work well (or at least requires more work to be put into.)
My question
Is there a different (maybe simpler?) way on Windows to achieve this? Like a way to invoke/inject code to the cmd process to execute cd whatever\directory\I\want directly without overriding its memory? I have seen the CreateRemoteThread() functions however I didn't manage to find a way to put them to use.
FYI: I am mainly using C# but C/C++ solutions should help too as long as they are based on the native Microsoft libraries.
This post describes a Windows implementation of a function that launches a child process, creates pipes to stdin and stdout from which a command is sent, and a response is returned. Finally, once all response is captured the child process is terminated. If this sounds familiar it is similar in concept to Linux's popen() function with the exception that this implementation was specifically created to capture the response into a buffer of any command that returns one. (Also included is a variant for use when no-response is expected or needed.)
The full source can be adapted for use within a standalone executable, or as an API. (.dll) Either way, the resulting functions accept and process any command using standard Windows CMD syntax. The function cmd_rsp(...) returns the Windows response via stdout into a self-sizing buffer.
The exported prototypes are:
int __declspec(dllexport) cmd_rsp(const char *command, char **chunk, unsigned int size);
int __declspec(dllexport) cmd_no_rsp(const char *command);
A simple use case when capturing a response:
#include "cmd_rsp.h"
int main(void)
{
char *buf = {0};
buf = calloc(100, 1);//initialize to some initial size
if(!buf)return 0;
cmd_rsp("dir /s", &buf, 100);//buffer will grow to accommodate response as needed.
printf("%s", buf);
free(buf);
return 0;
}
A simple use case when response is not needed:
#include "cmd_rsp.h"
int main(void)
{
cmd_no_rsp("cd C:\\dir1\\dir2");
return 0;
}
A detailed description of purpose and usage is described in the link provided above. To illustrate, here are a few sample command inputs, each in this case change the working directory, then execute a command from that directory:
A command to change to sqlite directory, then execute a query:
cd c:\\tempExtract\\sqlite\\Tools\\sqlite-tools-win32-x86-3250300 && sqlite3.exe .\\extract.db \"select * from event, eventdata where eventType=38 and eventdata .eventid=event.eventid\
A command to change to teraterm directory, then execute a script:
"c:\\Program Files (x86)\\teraterm\" && ttpmacro c:\\DevPhys\\LPCR_2\\play\\Play.ttl
A command to change directory then execute a command to send multiple digital acquisition channel settings.
cd C:\\Dir1\\Dir2\\Dir3\\support\\Exes\\WriteDigChannel && .\\WriteDigChannel.exe P1_CH0 1 && .\\WriteDigChannel.exe P1_C H0 0 && .\\WriteDigChannel.exe P1_CH0 1
A recursive directory search from a specified location:
cd C:\\dir1\\dir2 && dir /s /b
I got it working. As was suggested SendInput finally did the trick.
I used a combination of WinAPI calls to GetForegroundWindow() / SetForegroundWindow() and the Windows Forms System.Windows.Forms.SendKeys.SendWait() Method to achieve what I wanted:
Upon calling my cd-wrapper program (sd.exe) and providing my custom target directory (~/ home) it generates the corresponding command along with the "Enter-Pressed-Event" to be sent to it's parent cmd process.
Here's the complete C# code:
if (args.Length != 1)
{
Console.WriteLine(Directory.GetCurrentDirectory());
return;
}
string targetDirectory = args[0];
string command = string.Empty;
if (targetDirectory.Equals("~"))
{
command = #"pushd C:\Users\fred\Desktop";
}
else if (!Directory.Exists(targetDirectory))
{
Console.WriteLine("I/O Error: No such file or directory.");
return;
}
else
{
command = #"cd " + targetDirectory;
}
Target target = Target.Create(Process.GetCurrentProcess().GetParentProcess());
target.SendKeys(command + "{ENTER}", true);
Note that I kind of started to write a complete Framework for this and similar problems alongside this project that contains all my different approaches to this question and the low level WinAPI calls as well as the Extension methods to get the parent process :D
As it would be a bit overkill to paste all of it's code in this answer, here's the GitHub. If I can find the time I'll go ahead and optimize the code, but for now this'll do. Hope this helps anyone encountering a similar problem :)
Edit:
An even "cleaner" way is to use dll injection to directly make cmd switch it's working directory. While it is a lot harder to get working it has the advantage of not littering the cmd command history as compared to the approach described above. In addition to that cmd seems to be aware of any changes to it's current working directory, so it automatically updates the prompt text. Once I have a fully working example, that allows to dynamically specify the target directory I will post it here :)
I'm fairly certain I'm either doing something wrong, or understanding something wrong. It's hard to give a piece of code to show my problem, so I'm going to try explaining my scenario, with the outcome.
I'm starting up several instances of a DLL, in the same console application, but in it's own app domain. I then generated a Guid.NewGuid() that I assign to a class in the instance, and set the application's folder to a new folder. This works great so far. I can see everything works great, and my instances are seperated. However... when I started changing my app's folder to the same name as the unique GUID generated for that class I started picking up anomolies.
It works fine, when I instantiate the new instances slowly, but when I hammer new ones in, the application started picking up data in its folder, when it started up. After some investigation, I found that its because that folder already exist, due to that GUID already being instantiated. On further investigation, I can see that the machine takes a bit of a pause, and then continues to generated the new instances, all with the same GUID.
I understand that the GUID generating algorithm uses the MAC as part of it, but I was under the impression that even if the same machine, at the same exact moment generates two GUIDs, it would still be unique.
Am I correct in that statement? Where am I wrong?
Code :
Guid guid = Guid.NewGuid();
string myFolder = Path.Combine(baseFolder, guid.ToString());
AppDomain ad = AppDomain.CurrentDomain;
Console.WriteLine($"{ad.Id} - {guid.ToString()}");
string newHiveDll = Path.Combine(myFolder, "HiveDriveLibrary.dll");
if (!Directory.Exists(myFolder))
{
Directory.CreateDirectory(myFolder);
}
if (!File.Exists(newHiveDll))
{
File.Copy(hiveDll, newHiveDll);
}
Directory.SetCurrentDirectory(myFolder);
var client = ServiceHelper.CreateServiceClient(serviceURL);
ElementConfig config = new ElementConfig();
ElementConfig fromFile = ElementConfigManager.GetElementConfig();
if (fromFile == null)
{
config.ElementGUID = guid;
config.LocalServiceURL = serviceURL;
config.RegisterURL = registerServiceURL;
}
else
{
config = fromFile;
}
Directory.SetCurrentDirectory is a thin wrapper atop the Kernel 32 function SetCurrentDirectory.
Unfortunately, the .NET documentation writers didn't choose to copy the warning from the native function:
Multithreaded applications and shared library code should not use the SetCurrentDirectory function and should avoid using relative path names. The current directory state written by the SetCurrentDirectory function is stored as a global variable in each process, therefore multithreaded applications cannot reliably use this value without possible data corruption from other threads that may also be reading or setting this value
It's your reliance on this function that's creating the appearance that multiple threads have magically selected exactly the same GUID value.
For Example: I have installed an application called "RivaTuner Statistics Server v6.6.0" which has made for gamers to show FPS mark on games, since WPF apps are using DirectX, this program attaches a module to my WPF app by mistake which makes it crash (without giving any exceptions) before my app gets loaded, and when I close that program, my app works just fine!
I've fixed this problem by setting RenderOptions.ProcessRenderMode = RenderMode.SoftwareOnly
I also have the same problem with BitDefender antivirus, my program is a VPN Connection software that uses Proxifier app to set global proxy.. When my app begins to start Proxifier process, my app crashes without any exceptions.. by the way BitDefender doesn't detect Proxifier or my app as a virus or threat, it just makes my app crash and Proxifier continues to work without any problem. (Which whitelisting my app got the problem solved).
What I want to know generally, is there any way to prevent DLL injection or stopping it after it attached?
Here is the provided information by EventViewer:
Version=1
EventType=APPCRASH
EventTime=131414331835897163
ReportType=2
Consent=1
UploadTime=131414331849773927
ReportStatus=393
ReportIdentifier=c52be1e0-6378-4555-bddc-cd49f22e98d4
IntegratorReportIdentifier=e415e187-7b4d-4689-92a7-5522957c6300
Wow64Host=34404
NsAppName=TurboVPN.exe
AppSessionGuid=000037d0-0001-0015-6d89-3176a3e0d201
TargetAppId=W:00065bd30e4a6caee77eb9ec126f39eeb11200000000!000072443a77ce17608085aa75f649187cf7129fd9a8!TurboVPN.exe
TargetAppVer=2017//06//08:20:58:47!0!TurboVPN.exe
BootId=4294967295
TargetAsId=3395
Response.BucketId=c2e6858b6015d605f3dea6f209e5a680
Response.BucketTable=4
Response.LegacyBucketId=120776215139
Response.type=4
Sig[0].Name=Application Name
Sig[0].Value=TurboVPN.exe
Sig[1].Name=Application Version
Sig[1].Value=8.0.0.0
Sig[2].Name=Application Timestamp
Sig[2].Value=5939ba87
Sig[3].Name=Fault Module Name
Sig[3].Value=d3d9.dll
Sig[4].Name=Fault Module Version
Sig[4].Value=10.0.15063.0
Sig[5].Name=Fault Module Timestamp
Sig[5].Value=631de416
Sig[6].Name=Exception Code
Sig[6].Value=c0000005
Sig[7].Name=Exception Offset
Sig[7].Value=000000000000fd0c
DynamicSig[1].Name=OS Version
DynamicSig[1].Value=10.0.15063.2.0.0.256.4
DynamicSig[2].Name=Locale ID
DynamicSig[2].Value=1033
DynamicSig[22].Name=Additional Information 1
DynamicSig[22].Value=9b4f
DynamicSig[23].Name=Additional Information 2
DynamicSig[23].Value=9b4f78d83ca7cfa07fe4d1531372a428
DynamicSig[24].Name=Additional Information 3
DynamicSig[24].Value=9991
DynamicSig[25].Name=Additional Information 4
DynamicSig[25].Value=99915f8f3f68939dc06e64d116ece58a
UI[2]=C:\Users\Mr\Documents\Visual Studio 2015\Projects\TurboVPN\TurboVPN\bin\Release\TurboVPN.exe
UI[3]=TurboVPN has stopped working
UI[4]=Windows can check online for a solution to the problem.
UI[5]=Check online for a solution and close the program
UI[6]=Check online for a solution later and close the program
UI[7]=Close the program
LoadedModule[0]=C:\Users\Mr\Documents\Visual Studio 2015\Projects\TurboVPN\TurboVPN\bin\Release\TurboVPN.exe
LoadedModule[1]=C:\WINDOWS\SYSTEM32\ntdll.dll
LoadedModule[2]=C:\WINDOWS\SYSTEM32\MSCOREE.DLL
LoadedModule[3]=C:\WINDOWS\System32\KERNEL32.dll
LoadedModule[4]=C:\WINDOWS\System32\KERNELBASE.dll
LoadedModule[5]=C:\Program Files\Bitdefender\Bitdefender 2017\Active Virus Control\Avc3_00125_004\avcuf64.dll
LoadedModule[6]=C:\WINDOWS\SYSTEM32\apphelp.dll
LoadedModule[7]=C:\WINDOWS\System32\ADVAPI32.dll
LoadedModule[8]=C:\WINDOWS\System32\msvcrt.dll
LoadedModule[9]=C:\WINDOWS\System32\sechost.dll
LoadedModule[10]=C:\WINDOWS\System32\RPCRT4.dll
LoadedModule[11]=C:\Windows\Microsoft.NET\Framework64\v4.0.30319\mscoreei.dll
LoadedModule[12]=C:\WINDOWS\System32\SHLWAPI.dll
LoadedModule[13]=C:\WINDOWS\System32\combase.dll
LoadedModule[14]=C:\WINDOWS\System32\ucrtbase.dll
LoadedModule[15]=C:\WINDOWS\System32\bcryptPrimitives.dll
LoadedModule[16]=C:\WINDOWS\System32\GDI32.dll
LoadedModule[17]=C:\WINDOWS\System32\gdi32full.dll
LoadedModule[18]=C:\WINDOWS\System32\msvcp_win.dll
LoadedModule[19]=C:\WINDOWS\System32\USER32.dll
LoadedModule[20]=C:\WINDOWS\System32\win32u.dll
LoadedModule[21]=C:\WINDOWS\System32\IMM32.DLL
LoadedModule[22]=C:\WINDOWS\System32\kernel.appcore.dll
LoadedModule[23]=C:\WINDOWS\SYSTEM32\VERSION.dll
LoadedModule[24]=C:\Windows\Microsoft.NET\Framework64\v4.0.30319\clr.dll
LoadedModule[25]=C:\WINDOWS\SYSTEM32\MSVCR120_CLR0400.dll
LoadedModule[26]=C:\WINDOWS\assembly\NativeImages_v4.0.30319_64\mscorlib\59ea37125345a946fbfb8868aa11ed27\mscorlib.ni.dll
LoadedModule[27]=C:\WINDOWS\System32\ole32.dll
LoadedModule[28]=C:\WINDOWS\system32\uxtheme.dll
LoadedModule[29]=C:\Program Files (x86)\RivaTuner Statistics Server\RTSSHooks64.dll
LoadedModule[30]=C:\WINDOWS\SYSTEM32\WINMM.dll
LoadedModule[31]=C:\WINDOWS\WinSxS\amd64_microsoft.vc90.crt_1fc8b3b9a1e18e3b_9.0.30729.9279_none_08e667efa83ba076\MSVCR90.dll
LoadedModule[32]=C:\WINDOWS\SYSTEM32\WINMMBASE.dll
LoadedModule[33]=C:\WINDOWS\System32\cfgmgr32.dll
LoadedModule[34]=C:\WINDOWS\assembly\NativeImages_v4.0.30319_64\System\4b4b69a2aa9b596c8b8e7a32267eac35\System.ni.dll
LoadedModule[35]=C:\WINDOWS\assembly\NativeImages_v4.0.30319_64\System.Core\d4035216edd875be919d339859343a6c\System.Core.ni.dll
LoadedModule[36]=C:\WINDOWS\assembly\NativeImages_v4.0.30319_64\WindowsBase\d6053a0b7badab04868dc6e51ab4c02e\WindowsBase.ni.dll
LoadedModule[37]=C:\WINDOWS\SYSTEM32\CRYPTSP.dll
LoadedModule[38]=C:\WINDOWS\system32\rsaenh.dll
LoadedModule[39]=C:\WINDOWS\SYSTEM32\bcrypt.dll
LoadedModule[40]=C:\WINDOWS\SYSTEM32\CRYPTBASE.dll
LoadedModule[41]=C:\WINDOWS\assembly\NativeImages_v4.0.30319_64\PresentationCore\b5bfbcf78210cf783ff665fea098ebfa\PresentationCore.ni.dll
LoadedModule[42]=C:\WINDOWS\assembly\NativeImages_v4.0.30319_64\Presentatio5ae0f00f#\73dece296df0b44862aa59e1f73825c3\PresentationFramework.ni.dll
LoadedModule[43]=C:\WINDOWS\assembly\NativeImages_v4.0.30319_64\System.Xaml\44f34f029c456762dba3d085d6b9fa9c\System.Xaml.ni.dll
LoadedModule[44]=C:\WINDOWS\SYSTEM32\dwrite.dll
LoadedModule[45]=C:\Windows\Microsoft.NET\Framework64\v4.0.30319\WPF\wpfgfx_v0400.dll
LoadedModule[46]=C:\WINDOWS\System32\OLEAUT32.dll
LoadedModule[47]=C:\WINDOWS\SYSTEM32\MSVCP120_CLR0400.dll
LoadedModule[48]=C:\WINDOWS\SYSTEM32\D3DCOMPILER_47.dll
LoadedModule[49]=C:\Windows\Microsoft.NET\Framework64\v4.0.30319\WPF\PresentationNative_v0400.dll
LoadedModule[50]=C:\Windows\Microsoft.NET\Framework64\v4.0.30319\clrjit.dll
LoadedModule[51]=C:\WINDOWS\assembly\NativeImages_v4.0.30319_64\System.Configuration\9f298b9fdf9d3d88c051ba8d0cfcdd98\System.Configuration.ni.dll
LoadedModule[52]=C:\WINDOWS\SYSTEM32\urlmon.dll
LoadedModule[53]=C:\WINDOWS\System32\shcore.dll
LoadedModule[54]=C:\WINDOWS\System32\windows.storage.dll
LoadedModule[55]=C:\WINDOWS\System32\powrprof.dll
LoadedModule[56]=C:\WINDOWS\System32\profapi.dll
LoadedModule[57]=C:\WINDOWS\SYSTEM32\iertutil.dll
LoadedModule[58]=C:\WINDOWS\SYSTEM32\SspiCli.dll
LoadedModule[59]=C:\WINDOWS\SYSTEM32\msiso.dll
LoadedModule[60]=C:\WINDOWS\SYSTEM32\PROPSYS.dll
LoadedModule[61]=C:\WINDOWS\System32\shell32.dll
LoadedModule[62]=C:\WINDOWS\assembly\NativeImages_v4.0.30319_64\System.Xml\246b8fa70f43db970414bb4119fe629f\System.Xml.ni.dll
LoadedModule[63]=C:\WINDOWS\assembly\NativeImages_v4.0.30319_64\System.Runt73a1fc9d#\9ed83e5a61548d2d78bc4b7a667e9139\System.Runtime.Remoting.ni.dll
LoadedModule[64]=C:\WINDOWS\System32\ws2_32.dll
LoadedModule[65]=C:\WINDOWS\system32\mswsock.dll
LoadedModule[66]=C:\WINDOWS\system32\dwmapi.dll
LoadedModule[67]=C:\WINDOWS\System32\MSCTF.dll
LoadedModule[68]=C:\WINDOWS\assembly\NativeImages_v4.0.30319_64\System.Drawing\763d0ca89a77cfd983874efe156a9296\System.Drawing.ni.dll
LoadedModule[69]=C:\WINDOWS\assembly\NativeImages_v4.0.30319_64\System.Windows.Forms\d63d7f874bb64e51ee0ef09cc99218f6\System.Windows.Forms.ni.dll
LoadedModule[70]=C:\WINDOWS\assembly\NativeImages_v4.0.30319_64\System.Security\35f9d2604274a3e8fbf814e10789dc51\System.Security.ni.dll
LoadedModule[71]=C:\WINDOWS\System32\crypt32.dll
LoadedModule[72]=C:\WINDOWS\System32\MSASN1.dll
LoadedModule[73]=C:\WINDOWS\SYSTEM32\DPAPI.dll
LoadedModule[74]=C:\WINDOWS\SYSTEM32\WindowsCodecs.dll
LoadedModule[75]=C:\WINDOWS\SYSTEM32\d3d9.dll
LoadedModule[76]=C:\WINDOWS\SYSTEM32\igdumdim64.dll
LoadedModule[77]=C:\WINDOWS\System32\SETUPAPI.dll
LoadedModule[78]=C:\WINDOWS\assembly\NativeImages_v4.0.30319_64\Presentatioaec034ca#\248dd0bba3037acdc2ab60513b34c3f2\PresentationFramework.Aero2.ni.dll
LoadedModule[79]=C:\WINDOWS\SYSTEM32\WtsApi32.dll
LoadedModule[80]=C:\WINDOWS\SYSTEM32\WINSTA.dll
LoadedModule[81]=C:\WINDOWS\System32\clbcatq.dll
LoadedModule[82]=C:\WINDOWS\system32\dataexchange.dll
LoadedModule[83]=C:\WINDOWS\system32\d3d11.dll
LoadedModule[84]=C:\WINDOWS\system32\dcomp.dll
LoadedModule[85]=C:\WINDOWS\system32\dxgi.dll
LoadedModule[86]=C:\WINDOWS\system32\twinapi.appcore.dll
LoadedModule[87]=C:\WINDOWS\SYSTEM32\igdusc64.dll
State[0].Key=Transport.DoneStage1
State[0].Value=1
File[0].CabName=Report.zip
File[0].Path=Report.zip
File[0].Flags=196608
File[0].Type=11
File[0].Original.Path=\\?\C:\WINDOWS\system32\Report.zip
FriendlyEventName=Stopped working
ConsentKey=APPCRASH
AppName=TurboVPN
AppPath=C:\Users\Mr\Documents\Visual Studio 2015\Projects\TurboVPN\TurboVPN\bin\Release\TurboVPN.exe
NsPartner=windows
NsGroup=windows8
ApplicationIdentity=ED5A83A5552697FBE579A0CAAEF2FF9E
MetadataHash=1411986728
If you take a look, you can see the attached module LoadedModule[29]=C:\Program Files (x86)\RivaTuner Statistics Server\RTSSHooks64.dll
Preventing the DLL injection technique that this software uses completely defeats the point of using it. It has to do this, the only way it can wire itself into the DirectX render pipeline to display the statistics. That this ends up poorly and crashes your program with a completely undiagnosable AccessViolationException is quite normal. It takes just one change in an internal function that is not part of the documented API, the kind that the utility has to "hook", and the show is over.
It could be fixable, but that has to be done by the author of this utility. It is just one guy, a Russian master-hacker. Hard to get in touch with, his life can't possibly easy lately with Win10 updates arriving at a high rate these days.
You need to consider getting ahead by uninstalling it. There are other ways to accomplish the same thing, ways that are much less brittle, supported and dedicated to WPF. Use the WPF Performance Suite.
AFAIK, there are quite a few ways of preventing other processes to attach to your process.
Basically, there are two well-known approaches to attach to external process:
Debugging the external process
Injecting a thread to that process
you can overcome the first method by implementing one of anti-debug methods(There are a lot of these methods on the internet. An example would be to debug your own process )
To prevent other processes to inject thread to your process, you can set some hooks on CreateRemoteThread or LoadLibrary and initiate a procedure before they attach to your process.
Did you tried to catch exceptions during the initializecomponents function? Since this happens during the window drawing, you can try this:
public MainWindow()
{
try{
InitializeComponent();
//you remaining code
}
catch(Exception ex){
Console.Out.Writeline(ex.Message);
}
}
Also, you can try to subscribe to _Application.DispatcherUnhandledException_ and _AppDomain.CurrentDomain.UnhandledException_ that can give you more info about the application crash exception.
i am trying to get the text in SysListView32 from another app by C#.
i can get the LVM_GETITEMCOUNT well but LVM_GETITEMW = 0x1000 + 13 always returns -1. how can i get the text by C#? i am new. thanks very much!
ParenthWnd = FindWindow(ParentClass, ParentWindow);
if (!ParenthWnd.Equals(IntPtr.Zero))
{
zWnd = FindWindowEx(ParenthWnd, zWnd, zClass, zWindow);
if (!zWnd.Equals(IntPtr.Zero))
{
int user = SendMessage(zWnd, LVM_GETITEMCOUNT, 0, 0);
}
You need to work harder to read and write the LVITEM memory since you are working with a control owned by another process. You therefore need to read and write memory in that process. You can't do that without calling ReadProcessMemory, WriteProcessMemory etc.
The most commonly cited example of the techniques involved is this Code Project article: Stealing Program's Memory. Watch out for 32/64 bit gotchas.
I'm writing an utility (http://reg2run.sf.net) which in case execution without arguments works as windows application (shows OpenFileDialog, etc), otherwise - as console application.
So, in first case I don't want to show a console window, that's why project is Windows Application.
But in second - I need to show it, and it's created with
if (ptrNew == IntPtr.Zero)
{
ptrNew = GetStdHandle(-11);
}
if (!AllocConsole())
{
throw new ExternalCallException("AllocConsole");
}
ptrNew = CreateFile("CONOUT$", 0x40000000, 2, IntPtr.Zero, 3, 0, IntPtr.Zero);
if (!SetStdHandle(-11, ptrNew))
{
throw new ExternalCallException("SetStdHandle");
}
StreamWriter newOut = new StreamWriter(Console.OpenStandardOutput());
newOut.AutoFlush = true;
Console.SetOut(newOut);
Console.SetError(newOut);
And what I want - is to grab parent process standard output and use it, if it exists (in case execution via cmd.exe or Far Manager). How can I do it?
I tried
static Process GetParentProc()
{
int pidParent = 0;
int pidCurrent = Process.GetCurrentProcess().Id;
IntPtr hSnapshot = CreateToolhelp32Snapshot(2, 0);
if (hSnapshot == IntPtr.Zero)
{
return null;
}
PROCESSENTRY32 oProcInfo = new PROCESSENTRY32();
oProcInfo.dwSize = (uint)Marshal.SizeOf(typeof(PROCESSENTRY32));
if (!Process32First(hSnapshot, ref oProcInfo))
{
return null;
}
do
{
if (pidCurrent == oProcInfo.th32ProcessID)
{
pidParent = (int)oProcInfo.th32ParentProcessID;
}
}
while (pidParent == 0 && Process32Next(hSnapshot, ref oProcInfo));
if (pidParent > 0)
{
return Process.GetProcessById(pidParent);
}
else
{
return null;
}
and
StreamWriter newOut = GetParentProc().StandardInput;
but got InvalidOperationException: StandardIn has not been redirected. Because of
GetParentProc().StartInfo.RedirectStandardOutput = false
There are several approaches for applications that need to choose whether to act as console or GUI applications, depending on context, on Windows:
Have two separate applications, and have one conditionally start the other.
A variant of the above strategy, have two applications, one called 'app.com' (i.e. just rename a console EXE with COM extension) and the other called 'app.exe', so that command-line invocations will find app.com first. Because of ancient DOS compatibility, .COM executables are found before .EXEs. (This in configurable in Windows; see the PATHEXT environment variable.)
The rxvt/Cygwin technique, which is one I haven't really seen documented anywhere else.
Let me go into a little bit of detail about how rxvt on Cygwin works. Rxvt is a terminal emulator that normally runs on the X Window system. Because of the limitations of the Win32 console, Cygwin packages it as a more fully-featured console, with support for things like lots of lines of history, dynamic resizing, per-instance configurable fonts and colour themes, non-application-freezing mouse select and copy, etc. In order to run natively on Windows, rxvt shipped with Cygwin includes a tiny X11 wrapper library for Win32. Rxvt on Windows is actually a console application for compatibility reasons with existing native Win32 executables, but most of the time you never see the console; you just see the rxvt terminal emulator window itself.
The way it works is specifically implemented in rxvt/W11/wrap/wrap.c in the rxvt source tree, in the function called hideConsole(). Basically, it opens up its console (with a CreateFile("CONOUT$" ...)), and checks to see if the cursor position is at (0,0) (using GetConsoleScreenBufferInfo() on the console handle).
If it is, then it infers that it has been started as a standalone application, rather than from a console parent application, and thus it knows the OS has created a dedicated Win32 console for the process. It proceeds to hide this console window, but it has to find it first. It uses SetConsoleTitle to set the console window's caption to a unique value based on the name of the application and the current thread ID. It then uses FindWindow to find this window's handle (periodically Sleeping for a few ms if necessary for the title to change, because the console windows are actually controlled by a different process entirely in Windows). When it eventually finds the window handle, it hides it with ShowWindowAsync, passing in SW_HIDE.
Using this approach, you can write an application that:
if started from a console parent, it can continue to use this console
if started as an application, it can optionally choose whether or not to hide the console
The only downside is a very brief flash of a console window at application startup.
You can always the following P/Invoke method:
[DllImport("kernel32.dll")]
static extern bool AttachConsole(int dwProcessId);
const int ATTACH_PARENT_PROCESS = -1;