Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# error "Attempted to read or write protected memory" or "External component has thrown an exception"

Tags:

c#

I have a C# program (target framework .NET 4.0) which makes calls to COM objects (unmanaged code), all objects managed properly, destroyed when no longer required, etc.

I have also few exceptions handler, try/catch blocks without custom exceptions. However some times this program crashed, works most of the times, random behaviour. Stack traces also vary, example:

System.AccessViolationException was unhandled
  Message=Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
  Source=System.Windows.Forms
  StackTrace:
       at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
       at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.Run(Form mainForm)
       at IndexerTester.Program.Main() in D:\Tester\Program.cs:line 17
  InnerException:

In Program.cs, Line 17: Application.Run(new Form1());

System.Runtime.InteropServices.SEHException was unhandled
  Message=External component has thrown an exception.
  Source=System.Windows.Forms
  ErrorCode=-2147467259
  StackTrace:
       at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
       at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.Run(Form mainForm)
       at IndexerTester.Program.Main() in D:\Tester\Program.cs:line 17
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException:

I am in isolation stage to find out root of this error.

  • Do you have any suggestions of this error?
  • Any suggestions about catch these exceptions and exit gracefully.

Thanks for your help.

like image 697
Din Avatar asked Oct 26 '11 10:10

Din


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.

Is C language easy?

C is a general-purpose language that most programmers learn before moving on to more complex languages. From Unix and Windows to Tic Tac Toe and Photoshop, several of the most commonly used applications today have been built on C. It is easy to learn because: A simple syntax with only 32 keywords.

What is C language basics?

What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.


1 Answers

The source of the exceptions are unamanged code and most likely your COM components. The stack trace indicates that the exceptions are caught in your message loop and this might be a result of doing cross apartment calls from your .NET code into a COM object in a STA (Single Threaded Apartment). Method calls are then marshaled and sent using windows messages to the component.

There is nothing wrong about doing cross apartment calls, but I have seen some COM components not doing proper marshaling when given pointers from a different apartment and in general being ignorant about the threading rules in COM. If there is any kind of multi-threading in you application you should definitely look into this. These "broken" COM objects will behave well when called from the main STA thread but may fail when called or created on different threads.

To be more specific: Lets say that your applications UI thread on startup enters a STA (Single Threaded Apartment) and creates the COM component. You then create a new thread (which will be in another apartment) and from this thread you call a method on the COM component. This is a cross apartment call. Your COM component can only execute on the UI thread (the thread of the apartment it lives in). The COM framework will note that you are doing a cross apartment call and it will serialize the call into a buffer (marshal the call in COM lingo). This buffer is then sent to the UI thread using a Windows message. If your application doesn't have a window COM will create a hidden window to receive these messages. The message loop of your application will then unpack the marshalled call and execute it on the UI thread.

Now, lets assume that either you or the COM component doesn't understand the rules of COM apartments and marshalling. One of the arguments in the method call is a pointer or something that resolves into a pointer and this pointer isn't valid in the apartment of the COM component. Then, when the COM component derefences the pointer you get an error. The .NET runtime will detect this and throw one of the two exception types you see. However, this exception is thrown in the message loop of the UI thread, some code you don't have access to. Using a try-catch block at the caller doesn't help catching the exception as it is thrown on another thread. Anyway, you shouldn't catch the exception because it is a sign of something really bad going on in your application.

For the record the error code -2147467259 is 0x8004005 which translates to E_FAIL. Not very helpful, but the errors you experience are most likely due to invalid pointers being used in the COM component.

To fix this you will have to use the COM components correctly and/or fix any broken code in the components.

like image 90
Martin Liversage Avatar answered Sep 20 '22 15:09

Martin Liversage