windows system call - c++

On Linux it seems getpid() is the simplest system call to invoke to best-measure the time taken for a system call. Would somebody be able to refer me to a simple windows system call I could make to measure the time spent changing to kernel mode and back please?
I did google and found a list of Windows System calls on MSDN website, but they all referred to opening files- which seemed strange:
http://msdn.microsoft.com/en-us/library/t0wd4t32.aspx
I am on Windows 7 64 bit.

My suggestion (and this is just based on intuition) is to try something like
CloseHandle(NULL)
or
WaitForMultipleObjectsEx(0, NULL, 0, 0, FALSE)
on the grounds that it should be a no-op. However, I don't have any evidence to support this.
Update
A little benchmarking on Win8.1 x64 shows the (undocumented) NtDisplayString(NULL) function is even faster, followed by the semi-documented NtAllocateLocallyUniqueId(&some_luid). You'll have to dynamically load them from NTDLL using GetProcAddress; the signatures are:
NTSTATUS NTAPI PNtAllocateLocallyUniqueId(PLUID LUID);
NTSTATUS NTAPI PNtDisplayString(PUNICODE_STRING DisplayString);

Related

midiOutOpen on Windows 10 using Microsoft GS Wavetable Synth fails

I have an application that relies on the in built Microsoft GS Wavetable Synth. It has worked flawlessly on Windows XP, Vista, 7, 8 and 8.1. While the first call to midiOutOpen on Windows 10 works, subsequent calls result in error code 1, meaning 'Unspecified error'. The code is simple:
result = midiOutOpen(&_midiOutHandle, midiOutputDevice, NULL, 0, CALLBACK_NULL);
Any ideas regarding how to resolve this hugely appreciated.
I see it. Tracing through the machine code, I see the modMessage() function fail and return MMSYSERR_ERROR. Exactly why isn't clear to me, it looks like a missing initialization problem.
What is strange about this mishap is that there are not a lot of complaints about it, you'd expect plenty of other programs fall over as well. Or for that matter for them to be tested before Win10 shipped. Next thing I tried is adding the one thing that happens in any non-trivial audio app that I skipped in my test program. Partly inspired by seeing "ATL" back in the symbols of modMessage, although it wasn't anywhere close. I added this as the first line in main():
CoInitializeEx(NULL, COINIT_MULTITHREADED);
Badaboom, no more error. Use COINIT_APARTMENTTHREADED if you call this on the main thread of a UI thread. CoUninitialize() at the end to clean up.
Explaining it is difficult, initializing COM should not be necessary when you use MIDI. With it in place, calling midiOutOpen gets one more DLL loaded, clbcatq.dll. That's a COM+ support module. So sure looks like Win10 requires COM to be initialized.
I put a MessageBox (with nothing important to say) just before midiOutOpen, and IT WORKED!
I'm using Visual Studio 2013 C++.
WASAPI doesn't work for me anymore in sharing mode, although I think I'll be able to make it work.
When I use the CoInitializeEx(NULL, COINIT_MULTITHREADED), this helps for the midi open problem but has bad influence for using mciSendString with opening an MP3 song, which results always in error 266 in same program. Eg.:
open "d:\\music\\Fernando.mp3" type MPEGVideo alias Fernando.mp3 wait
(without the CoInitializeEx this open works and the mp3 song plays in Windows 10).
On some Windows 10 Systems the midi and mp3 open well without calling the CoInitializeEx, on others it does not play midi. It is not documented in MCI api that it must be called and causes indetermined problems. For me it is not clear when or why it must be called and when I should better not call it.
The Windows 10 incompatibility relating MCI of Microsoft is intolerable.
All Systems since XP are MCI compatible and only Windows 10 causes troubles.

SHDocVw::IShellWindowsPtr fails with IE8? (Error 0x80040154)

My program is a dll that hooks into a running instance of IE. It's worked fine for years.
Recently I dusted it off and ran it, but the last line below fails with hr = 0x80040154:
#import <mshtml.tlb> rename("value", "theValue") rename("event", "theEvent")
#import <shdocvw.dll>
// ....
SHDocVw::IShellWindowsPtr spSHWinds;
HRESULT hr = m_spSHWinds.CreateInstance(__uuidof(SHDocVw::ShellWindows));
Could it matter that IE7 has been replaced by IE8? Where else should I look?
I'm using VS2008, if that matters.
Edited to add
I don't see that it could be a 32/64 bit issue - it ran fine last year on this same machine. The only thing that's changed (as far as I have noticed) is the version of IE, from 7 to 8.
Note to the bounty hunters:
I only have access to this system for a few hours a day (around 0:00 EST), so you may not get quick responses to your suggestions, but I will look into them.
If you think there are things I should be checking (registry values, for example), be specific.
Edited to add:
I now see that the first time I call CreateInstance, it returns 0x80070002, not 0x80040154.
That's going to be very hard to diagnose. The ShellWindows coclass is special, its CLSID registry key is HKEY_CLASSES_ROOT\CLSID\{9BA05972-F6A8-11CF-A442-00A0C90A8F39}. When you look there, you'll see nothing useful registered there. The background story is that this is a leftover of an ill-fated attempt to make the Windows shell resemble a web browser. Still visible today, enumerating the shell windows returns both Windows Explorer and Internet Explorer instances.
The SysInternals' ProcMon utility is almost always the weapon of choice to debug 0x80040154 errors but it falls flat here. You can see it probing the registry, and not finding what it is looking for, but then the program knows how to load ieframe.dll anyway. This can only work by the operating system intercepting the CoCreateInstance() call. Which makes sense in general, considering the coclass enumerates shell windows.
All you got left is the trial-and-error approach. Reinstall IE first, OS next. Or to shove the machine out of a 4th story window before it eats too much of your valuable time.

Getting PEB from remote process in Win 7

Specs: Windows 7 x64, Visual C++
Objective: I'm trying to get the remote PEB from a sample program (calc.exe e.g.). I've found the proc ID and I've opened a handle to the process with all the good rights. I've now moved on to writing a class to retrieve the location of the PEB from the process using PROCESS_BASIC_INFORMATION.
Problem: I've found several posts elsewhere that seem to indicate that the NtQueryInformationProcess turned to shit at MS. One post suggests a method of dynamic-runtime-linking NtQueryInformationProcess out of ntdll.dll. However, I think this would be unstable in the long-run (MS could remove NtQueryInformationProcess tomorrow) without extensive error handling.
This idea is realized later in this thread, and it is then suggested by Mike2343 that one should "use other methods."
Questions: What would be another method to locate the PEB of a remote process that doesn't involve NtQueryInformationProcess?
Thanks to anyone who spends any time looking at this.
Method I ended up using:
I stole pretty much all of this code and fixed it up for 64-bit. I spent a ton of time wrapping my head around various documents related to all of the different headers and structs. I also ran into an issue regarding the PE32+ format, where jcopenha was kind enough to enlighten me on a few problems I might be facing. After accounting for these problems I had a functioning program that is capable of obtaining a list of all the DLL's and their respective functions loaded in by an executable along with their relative addresses.
In retrospect, I don't think I had a good handle on what I was attempting to do. I think that I thought I was going to read in a process out of memory and find the PEB related structs or something (Later I found out that image headers and the like account for the information in the PEB). Albeit that may be possible, but what I have now is an offline example that reads in exe files and works for me.

How can I create a window (HWND) without using CreateWindow(Ex)?

I'm using a proxy DLL to intercept calls to CreateWindowExA/CreateWindowExW. This works quit nicely, except that some applications (most notably some Visual Basic 6 applications) seem to be able to create windows without going through either of the two functions. Tools like Spy++ are able to show the Window, but my hooked functions didn't notice them.
My first suspicion was that maybe these (old) applications use CreateWindowA/CreateWindowW for creating windows, but at least with my compilers (MSVC6 up to MSVC10), CreateWindow is just a #define; the remarks section of the documentation confirms this.
My second idea was that I could maybe install a CBT hook using SetWindowsHookEx to detect creations of windows. However, the result is the same: this hook notices the same windows as my hooked API functions, but it doesn't notice all the windows which are visible in Spy++.
So my question is: was there maybe a time when CreateWindowA/CreateWindowW was not a #define, but a real function? Is this function still exported by user32.dll, maybe for compatibility reasons? How can I get a handle on this function to hook it?
Or is there maybe some other, possibly undocumented, function which can be used to create functions, much like e.g. NtCreateProcess can be used instead of CreateProcess?
Three simple guesses:
1) Is it possible that VB apps are really calling a "DialogBox" API (e.g. DialogBoxParam, CreateDialogIndirect, etc...) underneath the hood?
2) You are running a 64-bit OS and are hooking the 64-bit user32.dll. 32-bit apps aren't getting hooked as a result. There's a 32-bit copy of user32.dll in c:\windows\syswow64
3) You aren't hooking the user32.dll that the apps are using. Many older apps may be getting some DLL redirection. From a command prompt, do "dir /s user32.dll" from the c:\windows\winsxs directory. You'll see at least one other copy of user32.dll here. Forget when this happens, but you can Bing for "winsxs" and get some pages discussion how the side by side directory solves compat issues on newer windows OS releases.
I suspect #3 is the reason for your issue.
I think your issue might be that the VB app is using GetProcAddress() to call the CreateWindow**() function. If you hook GetProcAddress you should be able to confirm this.

How do I redirect calls to ole32.dll to my own proxy DLL?

I'm trying to detect all calls to CoCreateInstance in some process I'm starting (ideally, I'm able to detect calls in child processes as well).
To achieve this, using Microsoft Visual Studio 2008 on Windows 7, I create a proxy DLL which forwards all but one call in the standard ole32.dll library as described in various articles, e.g.
Intercepted: Windows Hacking via DLL Redirection. The resulting DLL looks fine, but I just can't make existing programs (I'm using the standard ActiveX Control Test Container (tstcon32.exe) as a test application) pick up my proxy DLL. No matter what I do, the programs always seem to pick up C:\Windows\SysWow64\ole32.dll according to Process Explorer. I tried a few things so far:
Prepend the directory which contains my proxy DLL to the PATH and then invoke the program; didn't seem to have any effect.
Copy my proxy DLL into the same directory as the invoked program; no luck.
Create a .local file in the same directory as the invoked program as described in the Dynamic-Link Library Redirection article and put my proxy DLL into the same directory - didn't work either. But then, I read that this stopped working on more recent Windows versions. Additionally, ole32.dll is a "known DLL" according to the HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\KnownDLLs registry setting, so .local-based redirection is probably not going to work anyway.
Use manifest-based redirection as described e.g. in the DLL redirection using manifests question, but that didn't seem to have any effect either. However, this approach seems to be non-trivial, so chances are I did something wrong.
Does anybody have experience with redirecting calls to standard DLLs such as ole32.dll using a stub DLL? How did you force the applications to pick up your stub DLL?
I realise this is a little late by about 6 months, but I was trying the same thing and have some additional notes:
You can take ownership of and remove ole32.dll from HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\KnownDLLs. This allows you to get around the fact Windows has locked these keys.
Creating a key SafeDllSearch with the value 0 in HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager is supposed to alter the search path.
Having applied both these techniques and rebooting, hooking still did not work. I went one further, booted up a VM with one of our rescue CDs (a Windows PE based environment) and overwrote the one in system32. Windows does not boot as a result - no symbol errors, but I never get as far as LogonUI.exe. It is possible my hooked functions are broken, so this may be the cause.
Anyway, that produced an actual, tangible hook effect - albeit one that screams "broken"!. Unfortunately it appears highly difficult to debug, and I may be resorting to the other method of hooking - namely IAT patching.
Edit another experiment I performed was to explicitly load the Dll myself into the target process' address space. A snippet of code that does this looks like this:
wchar_t* TargetPath = argv[1];
wchar_t DllPath[] = L"N:\\experiments\\ole32.dll";
STARTUPINFOW si;
PROCESS_INFORMATION pi;
memset(&si, 0, sizeof(STARTUPINFOW));
memset(&pi, 0, sizeof(PROCESS_INFORMATION));
// create process suspended
BOOL bResult = CreateProcess(NULL, TargetPath, NULL, NULL, FALSE,
CREATE_SUSPENDED, NULL, NULL, &si, &pi);
// write DLL name to remote process
void* RemoteAddr = VirtualAllocEx(pi.hProcess, NULL, sizeof(DllPath)+1,
MEM_RESERVE | MEM_COMMIT, PAGE_READONLY);
WriteProcessMemory(pi.hProcess, RemoteAddr, DllPath, sizeof(DllPath), &BytesWritten);
// get handle to LoadLibraryW
PTHREAD_START_ROUTINE pfLoadLibrary = (PTHREAD_START_ROUTINE)
GetProcAddress(GetModuleHandle(L"kernel32.dll"), "LoadLibraryW");
// create remote thread calling LoadLibraryW
HANDLE hThread = CreateRemoteThread(pi.hProcess, NULL,
0, pfLoadLibrary, RemoteAddr, 0, NULL);
// start remote process
ResumeThread(pi.hThread);
Error handling removed for brevity.
Basically, the objective was to force load my ole32.dll into the target's address space before it had chance to load ole32.dll from system32. In my case, ole32.dll was being loaded later on in the application's load routine, so this in theory should have worked. In practice, it did not. I am not sure why.
Update My original code failed because the DLL had unresolved symbol warnings at runtime. This technique does work So apparently, it loads both my ole32.dll AND the one from system32. To ensure the library was loading successfully, I added a LoadLibrary(DllPath) call to the code above.
Perhaps winapioverride can help you. It can log all win api calls without programming anything. It therefore injects dlls to the process that do the logging. If I recall it correctly it is also possible to inject own custom dlls - even before the process actually executes any code. The documentation has some information about spying com objects.