application creating muant handles and never frees them - windbg

My c++ application is creating mutant handles. I couldn't find where the handle is being created, so I used Windbg and with !htrace. It doesnt give the exact function name. All my symbol files are loaded and the application is built in debug mode.
!htrace shows open handles but the exact function where the handle is been opened,it doesnt show.
The trace looks like this
Handle = 0x00000d34 - OPEN
Thread ID = 0x00003670, Process ID = 0x00004748
0x77a0473c: ntdll!ZwCreateMutant+0x0000000c
0x75d7a0cd: KERNELBASE!CreateMutexExW+0x0000005e
0x75d7bb94: KERNELBASE!CreateMutexExA+0x0000002f
0x75d7bb5c: KERNELBASE!CreateMutexA+0x0000001d
Is there any alternative way to debug this issue?

Related

CANoe CAPL function: clear trace window

I'm currently trying to find a way to automate the clearing of the trace window in CANoe.
I've had a look on the help menu within CANoe but there's nothing apart from a manual x option available on the Trace window itself. Does anyone have any ideas?
Syntax
void traceWindowClear(char[] windowName);
Function
Clears the contents of the Trace Window.
Parameters
windowName - The name of the Trace Window.
Return Values
—
Availability
Since Version 11.0 In Measurement Setup and Simulation / Test Setup.

Openpanel and symbol communication not working

I am trying to make a patch that plays audio when a bang is pressed. I have put a symbol so that I don't need to keep reimporting the file. However it works sometimes but not all the time.
A warning in the Pd console reads: Start requested with no prior open
However I have imported an audio file
Is there something that I have done wrong?
Use [trigger] to get the order-of-execution correct.
One problem is, that whenever you send a [1( to [readsf~] you must have sent an [open ...( message directly beforehand.
Even if you have just successfully opened a file, but then stopped it (with [0() or played it through (so it has been closed automatically), you have to send the filename again.
The real problem is, that your messages are out of order: you should never have a fan-out (that is: connecting a message outlet to multiple inlets), as this will create undefined behavior.
Use [trigger] to get the order-of-execution correct.
(Mastering [trigger] is probably the single most important step in learning to program Pd)

Stop VFP from showing dialog boxes when errors occur

I am trying to call an existing VFP 6 application using Jacob which is a COM bridge for Java.
val vfp = new Application(new ActiveXComponent("VisualFoxPro.Application").getProperty("Application").toDispatch())
vfp.setVisible(false)
try {
vfp.doCmd("do my.exe with myconfig.txt")
} catch {
case t: Throwable => t.printStackTrace
} finally {
vfp.doCmd("close data")
vfp.doCmd("clear all")
vfp.doCmd("clear")
vfp.quit
vfp.safeRelease
}
When there are no error conditions this code executes well and generates the expected .dbfs. The problem is that when an error occurs (.dbf not found, file in use by another user, etc) a GUI window pops up and stops execution of the program until I use the mouse to cancel it. I want this program to run on a server with no user interaction so this won't work.
How can I gracefully handle the errors preferably without making a change to the VFP 6 program?
Since you have the source code for VFP6, I would suggest looking into
SYS(2335,0)
Sys 2335 is used to identify if the program is running in an "unattended" mode, any such popup dialog boxes will throw an error and prevent an actual "hit" ok/cancel/whatever button to continue. This includes popup window prompting user to pick a table.
I'm not positive of when it was made available as I had limited use of it. Like you, when dealing with a COM server under IIS and obviously nobody there to respond.
Start JVM in headless mode, catch HeadlessException or something. Or, write a Java program that will execute your GUI program using Runtime, and restart in a case of parsed errors in console.

How do I find the handle owner from a hang dump using windbg?

How do I find out which thread is the owner of my Event handle in windbg:
I'm running
!handle 00003aec f
and get
Handle 00003aec
Type Event
Attributes 0
GrantedAccess 0x1f0003:
Delete,ReadControl,WriteDac,WriteOwner,Synch
QueryState,ModifyState
HandleCount 2
PointerCount 4
Name <none>
No object specific information available
back, and as there is no Name I haven't figured out how to get the owner out to prove which thread my thread is waiting on
[Edit] I must work against a dump as the original process needs to be restarted on the users machine, so can't debug a live session
The best discussion on the subject I've found so far is on this blog, but unfortunately we end up using different lock methods (I end up using WaitForMultipleObjectsEx and the description is for WaitForSingleObject), and he seems to have access to a live process
the stacktrace of my thread (the one that is blocked on something and where I'm looking for the current owner) is:
0:045> k9
ChildEBP RetAddr
1130e050 7c90e9ab ntdll!KiFastSystemCallRet
1130e054 7c8094e2 ntdll!ZwWaitForMultipleObjects+0xc
1130e0f0 79ed98fd kernel32!WaitForMultipleObjectsEx+0x12c
1130e158 79ed9889 mscorwks!WaitForMultipleObjectsEx_SO_TOLERANT+0x6f
1130e178 79ed9808 mscorwks!Thread::DoAppropriateAptStateWait+0x3c
1130e1fc 79ed96c4 mscorwks!Thread::DoAppropriateWaitWorker+0x13c
1130e24c 79ed9a62 mscorwks!Thread::DoAppropriateWait+0x40
1130e2a8 79e78944 mscorwks!CLREvent::WaitEx+0xf7
1130e2bc 7a162d84 mscorwks!CLREvent::Wait+0x17
1130e33c 7a02fd94 mscorwks!CRWLock::RWWaitForSingleObject+0x6d
1130e364 79ebd3af mscorwks!CRWLock::StaticAcquireWriterLock+0x12e
1130e410 00f24557 mscorwks!CRWLock::StaticAcquireWriterLockPublic+0xc9
Looking at the callstack it appears that the stack in question is using a ReaderWriterLock locking mechanism.
1130e410 00f24557 mscorwks!CRWLock::StaticAcquireWriterLockPublic+0xc9
Change to thread 9 and using sos.dll run !dso to dump out the managed ReaderWriterLock object. Then run !do on that the ReaderWriterLock object. I believe that there is an owning thread field that you can query. I will test it and see.
The old school way to determine this is to run ~*e !clrstack and examine all of the managed threads that are waiting on a readerwriter lock and then see if you can find the thread that has entered the same function but passed through the lock (ie. different offset)
Thanks,
Aaron
Note: Not sure if there is a way to link posts but this one is very similar to
How do I find the lockholder (reader) of my ReaderWriterLock in windbg
Use the !htrace command to get the thread ID. You must first, possibly at the start of the program, enable the collection of traces with !htrace -enable.
0:001> !htrace 00003aec
--------------------------------------
Handle = 0x00003aec - OPEN
Thread ID = 0x00000b48, Process ID = 0x000011e8
...
The above output is fictional, it will be different for your system. But it will give you the piece of information you need - the thread ID (0x00000b48 in my example).
I must work against a dump as the
original process needs to be restarted
on the users machine, so can't debug a
live session.
I am not 100% sure but I think this will work:
Attach to the process and run !htrace -enable
Detach from the process with qd. The executable will continue.
You can now take a dump file and use the above command - I think you will have the described results.
You can dig that out of a kernel dump.
Now, as far as kernel debugging goes, livekd from sysinternals should be sufficient but unfortunately it is only usable on a running system.
There's also a kernel mode memory acquisition tool which might be of use to take a dump with (in windbg's stead) for later inspection.
Otherwise, enabling handle tracing (!htrace -enable) and (if code unique to particular thread), the handle ownership could be concluded from a stack trace.
Here's the definitive answer I found. Never tried myself. You'll need live debugging to determine the owner though. But it's pretty quick.
http://weblogs.thinktecture.com/ingo/2006/08/who-is-blocking-that-mutex---fun-with-windbg-cdb-and-kd.html

Output to command-line if started from command line

I'm writing an application that can be started either as a standard WinForms app or in unattended mode from the command-line. The application was built using the VS 2k5 standard WinForms template.
When the application is executed from the command-line, I want it to output information that can be captured by the script executing the application. When I do this directly from Console.WriteLine(), the output does not appear, although it can be captured by piping to a file.
On the other hand, I can force the application to pop up a second console by doing a P/Invoke on AllocConsole() from kernel32. This is not what I want, though. I want the output to appear in the same window the application was called from.
This is the salient code that allows me to pop up a console from the command line:
<STAThread()> Public Shared Sub Main()
If My.Application.CommandLineArgs.Count = 0 Then
Dim frm As New ISECMMParamUtilForm()
frm.ShowDialog()
Else
Try
ConsoleControl.AllocConsole()
Dim exMan As New UnattendedExecutionManager(ConvertArgs())
IsInConsoleMode = True
OutputMessage("Application started.")
If Not exMan.SetSettings() Then
OutputMessage("Execution failed.")
End If
Catch ex As Exception
Console.WriteLine(ex.ToString())
Finally
ConsoleControl.FreeConsole()
End Try
End If
End Sub
Public Shared Sub OutputMessage(ByVal msg As String, Optional ByVal isError As Boolean = False)
Trace.WriteLine(msg)
If IsInConsoleMode Then
Console.WriteLine(msg)
End If
If isError Then
EventLog.WriteEntry("ISE CMM Param Util", msg, EventLogEntryType.Error)
Else
EventLog.WriteEntry("ISE CMM Param Util", msg, EventLogEntryType.Information)
End If
End Sub
Raymond Chen recently posted (a month after the question was posted here on SO) a short article about this:
How do I write a program that can be run either as a console or a GUI application?
You can't, but you can try to fake it.
Each PE application contains a field
in its header that specifies which
subsystem it was designed to run
under. You can say
IMAGE_SUBSYSTEM_WINDOWS_GUI to mark
yourself as a Windows GUI application,
or you can say
IMAGE_SUBSYSTEM_WINDOWS_CUI to say
that you are a console application. If
you are GUI application, then the
program will run without a console.
The subsystem determines how the
kernel prepares the execution
environment for the program. If the
program is marked as running in the
console subsystem, then the kernel
will connect the program's console to
the console of its parent, creating a
new console if the parent doesn't have
a console. (This is an incomplete
description, but the details aren't
relevant to the discussion.) On the
other hand, if the program is marked
as running as a GUI application, then
the kernel will run the program
without any console at all.
In that article he points to another by Junfeng Zhang that discusses how a couple of programs (Visual Studio and ildasm) implement this behavior:
How to make an application as both GUI and Console application?
In VisualStudio case, there are actually two binaries: devenv.com and devenv.exe. Devenv.com is a Console app. Devenv.exe is a GUI app. When you type devenv, because of the Win32 probing rule, devenv.com is executed. If there is no input, devenv.com launches devenv.exe, and exits itself. If there are inputs, devenv.com handles them as normal Console app.
In ildasm case, there is only one binary: ildasm.exe. It is first compiled as a GUI application. Later editbin.exe is used to mark it as console subsystem. In its main method it determines if it needs to be run as console mode or GUI mode. If need to run as GUI mode, it relaunches itself as a GUI app.
In the comments to Raymond Chen's article, laonianren has this to add to Junfeng Zhang's brief description of how Visual Studio works:
devenv.com is a general purpose console-mode stub application. When it runs it creates three pipes to redirect the console's stdin, stdout and stderr. It then finds its own name (usually devenv.com), replaces the ".com" with ".exe" and launches the new app (i.e. devenv.exe) using the read end of the stdin pipe and the write ends of the stdout and stderr pipes as the standard handles. Then it just sits and waits for devenv.exe to exit and copies data between the console and the pipes.
Thus even though devenv.exe is a gui app it can read and write the "parent" console using its standard handles.
And you could use devenv.com yourself for myapp.exe by renaming it to myapp.com. But you can't in practise because it belongs to MS.
Update 1:
As said in Michael Burr answer, Raymond Chen recently posted a short article about this. I am happy to see that my guess was not totally wrong.
Update 0:
Disclaimer: This "answer" is mostly speculation. I post it only because enough time has passed to establish that not many people have the answer to what look like a fundamental question.
I think that the "decision" if the application is gui or console is made at compile time and not at runtime. So if you compile your application as gui application, even if you don't display the gui, its still a gui application and doesn't have console. If you choose to compile it as console application then at minimum you will have a console windows flashing before moving to gui "mode". And I don't know if it is possible in managed code.
The problem is fundamental, I think, Because a console application has to take "control" of the calling console application. And it has to do so before the code of the child application is running.
If you want to check if your app is started from the command line in .NET, you can use Console.GetCursorPosition().
The reason that this works is that when you start it from the command line, the cursor moves away from the initial point ((0, 0)) because you typed something in the terminal (the name of the app).
You can do this with an equality check (code in C#):
class Program
{
public static void Main
{
if (Console.GetCursorPosition() == (0, 0))
{
//something GUI
}
else
{
//something not GUI
}
}
}
Note: You must set the output type to Console Application as other output types will make Console.GetCursorPosition() throw an exception.