Using DeviceIoControl with FSCTL_LOCK_VOLUME to lock a volume. Debugger issue - debugging

I'm using DeviceIoControl with FSCTL_LOCK_VOLUME to lock a USB pen drive prior to direct disk read/write. The program works - sometimes.
I am having an issue with the lock call itself. When I step the command in Visual Studio 2008 the result is correct and the lock succeeds - every time!, when running the code (debug or not) the call fails sporadically with invalid handle. The only noticable difference is when stepping there is a half second pause - which I am happy with, but when running/debugging the call fails immediately.
Please can you give me a hint as to where this is falling down.
I think this is one for the true techies!

Sounds like a timing bug. Are there other threads with access to the handle? If so, one of them may be closing it before you call DeviceIoControl.

Related

Prevent my Windows App to cause Windows Runtime Broker to run out of Memory

When my Windows 10 app runs, it causes a process called Runtime Broker to execute, which takes up a lot of Memory space.
I know my app isn't "Memory-hungry" and it hardly takes 80 MB of RAM to execute. But from the time it starts, the Memory used by Runtime Broker keeps in increasing until the PC gets stuck.
Upon killing that process, the app is force closed by Windows.
I would have posted my source code here, if only I knew which part of the code is causing this to happen.
What are the possible technical reasons for this problem to happen, and what are the possible fixes in my code to prevent this?
Is there something wrong with my code, or is it some API that I am calling?
You can easily delete RuntimeBroker.exe and any other file. I deleted RuntimeBroker.exe and Livecomm.exe by booting a live Linux Dvd and after loading go and mount the c: drive then simply navigate to the file and delete it. Done!
Runtimebroker seems to hold about 60k per file held via StorageFile objects. It's still a bad problem and the only solution is to not hold on to very many of these.
Microsoft just never does anything about this.
Update: Microsoft seems to have quietly ditched UWP. The replacement has "WinUI" and is probably called the Windows App SDK at the moment. No more runtimebroker.exe.

libusb doesn't enumerate a device if cleanup failed in previous program execution. Can I prevent this, or recover from the bad state in software?

I have code that opens a libusb device, does some asynchronous transfers, and then quits. Sometimes the cleanup code at the end works out and I can re-run the program without problems, but other times
libusb_cancel_transfer returns LIBUSB_ERROR_PIPE and thereafter the device does not appear in the list returned by libusb_get_device_list in any subsequent execution of the program.
The problem can be recovered from by unplugging the device and reinserting into the same port, but that's not acceptable. I need at the very least some way to recover from the bad state in software, but ideally this shouldn't ever happen.
In case this problem could be platform related, I'm running MacOSX 10.9.5 and the program is C++ built with the llvm compiler.
I have discovered that I was inadvertently submitting control transfers whose setup packets were uninitialized memory. (Used the wrong size constant.) When I stopped doing that, the problem no longer occurred.

Should Atollic Studio be pausing on interrupts while debugging?

I'm using Atollic TrueSTUDIO for ARM 5.0.0 Lite for debugging an STM32F3 application via the SWD debug interface. The application receives data via interrupts from a USART.
When I "step over" a relatively long function, the application doesn't pause, i.e. the program does not reach the line after the call. When I then manually pause the application, I find it to be at the entry of the USART ISR, so I concluded that the execution was paused, even though Atollic's debugger didn't recognize it.
The bigger problem is that the same happens when I simply resume: I can't run my application with the debugger attached, as every byte on the USART pauses it.
Is my analysis of the situation correct? Is this the expected behavior, and is there a way to work around it? Non-Atollic specific answers are also very welcome!
To be honest, I couldn't form a clear picture in my mind of what's really going on, but here's a possibility: you're not clearing the proper flags using the USART_ClearITPendingBit() function call from the standard peripheral library, or its equivalent in terms of direct register access. If you don't clear the proper bits, as soon as you return from the ISR, the hardware executes it again, so it looks like you're in an infinite loop inside the ISR.

Debugging kext with gdb: deadlock

I have I/O Kit driver: virtual ethernet device. After some period of work OS hangs, so looks like I have some deadlock in my driver.
I've done next steps:
- connect two macbooks via FireWire
- set up debugging environment
- initialise NMI (via power button)
- connect to the target via gdb
- grab address of my kext
- create and load symbols (this is the last point in all docs I've read)
So far so good. In case of kernel panic it would be enough. But in my case there is no kernel panic and I reside in the thread that handle the NMI.
Now the question: how can I switch to the thread of my kext?
Command showalltasks gives me listing of all tasks, the only task where my kext may be running is kernel_task, so I'm trying to examine this task via showtaskthreads and showtaskstacks but can't find anything similar to my code. Am I missing something?
I would be appreciated for any suggestions or links to the docs.
I'm not answering your question directly - but would it be possible to hit your kext code with a breakpoint? A common method of kernel debugging is to nmi the machine, attach the debugger, put a breakpoint in the code of interest, resume execution (continue) and then do whatever is needed to hit the breakpoint.
Well, I'm answering my own question.
To see the thread using code of my kext I need to switch to the process using my kext. In my case it will be probably a browser (since my kext is the NKE).
But in fact it didn't help me a lot. But old print method helped me to find the deadlock. So my advice is next: for the kernel panic - use debugger, for the deadlock - use printing, find place where lock is and analyse code.

Invoke Blue Screen of Death using Managed Code

Just curious here: is it possible to invoke a Windows Blue Screen of Death using .net managed code under Windows XP/Vista? And if it is possible, what could the example code be?
Just for the record, this is not for any malicious purpose, I am just wondering what kind of code it would take to actually kill the operating system as specified.
The keyboard thing is probably a good option, but if you need to do it by code, continue reading...
You don't really need anything to barf, per se, all you need to do is find the KeBugCheck(Ex) function and invoke that.
http://msdn.microsoft.com/en-us/library/ms801640.aspx
http://msdn.microsoft.com/en-us/library/ms801645.aspx
For manually initiated crashes, you want to used 0xE2 (MANUALLY_INITIATED_CRASH) or 0xDEADDEAD (MANUALLY_INITIATED_CRASH1) as the bug check code. They are reserved explicitly for that use.
However, finding the function may prove to be a bit tricky. The Windows DDK may help (check Ntddk.h) - I don't have it available at the moment, and I can't seem to find decisive info right now - I think it's in ntoskrnl.exe or ntkrnlpa.exe, but I'm not sure, and don't currently have the tools to verify it.
You might find it easier to just write a simple C++ app or something that calls the function, and then just running that.
Mind you, I'm assuming that Windows doesn't block you from accessing the function from user-space (.NET might have some special provisions). I have not tested it myself.
I do not know if it really works and I am sure you need Admin rights, but you could set the CrashOnCtrlScroll Registry Key and then use a SendKeys to send CTRL+Scroll Lock+Scroll Lock.
But I believe that this HAS to come from the Keyboard Driver, so I guess a simple SendKeys is not good enough and you would either need to somehow hook into the Keyboard Driver (sounds really messy) or check of that CrashDump has an API that can be called with P/Invoke.
http://support.microsoft.com/kb/244139
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\i8042prt\Parameters
Name: CrashOnCtrlScroll
Data Type: REG_DWORD
Value: 1
Restart
I would have to say no. You'd have to p/invoke and interact with a driver or other code that lives in kernel space. .NET code lives far removed from this area, although there has been some talk about managed drivers in future versions of Windows. Just wait a few more years and you can crash away just like our unmanaged friends.
As far as I know a real BSOD requires failure in kernel mode code. Vista still has BSOD's but they're less frequent because the new driver model has less drivers in kernel mode. Any user-mode failures will just result in your application being killed.
You can't run managed code in kernel mode. So if you want to BSOD you need to use PInvoke. But even this is quite difficult. You need to do some really fancy PInvokes to get something in kernel mode to barf.
But among the thousands of SO users there is probably someone who has done this :-)
You could use OSR Online's tool that triggers a kernel crash. I've never tried it myself but I imagine you could just run it via the standard .net Process class:
http://www.osronline.com/article.cfm?article=153
I once managed to generate a BSOD on Windows XP using System.Net.Sockets in .NET 1.1 irresponsibly. I could repeat it fairly regularly, but unfortunately that was a couple of years ago and I don't remember exactly how I triggered it, or have the source code around anymore.
Try live videoinput using directshow in directx8 or directx9, most of the calls go to kernel mode video drivers. I succeded in lots of blue screens when running a callback procedure from live videocaptureing source, particulary if your callback takes a long time, can halt the entire Kernel driver.
It's possible for managed code to cause a bugcheck when it has access to faulty kernel drivers. However, it would be the kernel driver that directly causes the BSOD (for example, uffe's DirectShow BSODs, Terence Lewis's socket BSODs, or BSODs seen when using BitTorrent with certain network adapters).
Direct user-mode access to privileged low-level resources may cause a bugcheck (for example, scribbling on Device\PhysicalMemory, if it doesn't corrupt your hard disk first; Vista doesn't allow user-mode access to physical memory).
If you just want a dump file, Mendelt's suggestion of using WinDbg is a much better idea than exploiting a bug in a kernel driver. Unfortunately, the .dump command is not supported for local kernel debugging, so you would need a second PC connected over serial or 1394, or a VM connected over a virtual serial port. LiveKd may be a single-PC option, if you don't need the state of the memory dump to be completely self-consistent.
This one doesn't need any kernel-mode drivers, just a SeDebugPrivilege. You can set your process critical by NtSetInformationProcess, or RtlSetProcessIsCritical and just kill your process. You will see same bugcheck code as you kill csrss.exe, because you set same "critical" flag on your process.
Unfortunately, I know how to do this as a .NET service on our server was causing a blue screen. (Note: Windows Server 2008 R2, not XP/Vista).
I could hardly believe a .NET program was the culprit, but it was. Furthermore, I've just replicated the BSOD in a virtual machine.
The offending code, causes a 0x00000f4:
string name = string.Empty; // This is the cause of the problem, should check for IsNullOrWhiteSpace
foreach (Process process in Process.GetProcesses().Where(p => p.ProcessName.StartsWith(name, StringComparison.OrdinalIgnoreCase)))
{
Check.Logging.Write("FindAndKillProcess THIS SHOULD BLUE SCREEN " + process.ProcessName);
process.Kill();
r = true;
}
If anyone's wondering why I'd want to replicate the blue screen, it's nothing malicious. I've modified our logging class to take an argument telling it to write direct to disk as the actions prior to the BSOD weren't appearing in the log despite .Flush() being called. I replicated the server crash to test the logging change. The VM duly crashed but the logging worked.
EDIT: Killing csrss.exe appears to be what causes the blue screen. As per comments, this is likely happening in kernel code.
I found that if you run taskkill /F /IM svchost.exe as an Administrator, it tries to kill just about every service host at once.

Resources