Search Results

Search found 9 results on 1 pages for 'methodimploptions'.

Page 1/1 | 1 

  • Is it possible to link a method marked with MethodImplOptions.InternalCall to its implementation?

    - by adrianbanks
    In trying to find the possible cause of an exception, I'm following a code path using Reflector. I've got deeper and deeper, but ended up at a method call that looks like: [MethodImpl(MethodImplOptions.InternalCall)] private extern void SomeMethod(int someParameter); This markup on the method tells the framework to call a C++ function somewhere. Is there any way to find out what method actually gets called, and in turn what else is likely to be called? NB: I don't really want to see the source code of this method, I just want to know the possible things that could throw the exception I am seeing that originates out of this method call.

    Read the article

  • CLR 4.0 inlining policy? (maybe bug with MethodImplOptions.NoInlining)

    - by ControlFlow
    I've testing some new CLR 4.0 behavior in method inlining (cross-assembly inlining) and found some strage results: Assembly ClassLib.dll: using System.Diagnostics; using System; using System.Reflection; using System.Security; using System.Runtime.CompilerServices; namespace ClassLib { public static class A { static readonly MethodInfo GetExecuting = typeof(Assembly).GetMethod("GetExecutingAssembly"); public static Assembly Foo(out StackTrace stack) // 13 bytes { // explicit call to GetExecutingAssembly() stack = new StackTrace(); return Assembly.GetExecutingAssembly(); } public static Assembly Bar(out StackTrace stack) // 25 bytes { // reflection call to GetExecutingAssembly() stack = new StackTrace(); return (Assembly) GetExecuting.Invoke(null, null); } public static Assembly Baz(out StackTrace stack) // 9 bytes { stack = new StackTrace(); return null; } public static Assembly Bob(out StackTrace stack) // 13 bytes { // call of non-inlinable method! return SomeSecurityCriticalMethod(out stack); } [SecurityCritical, MethodImpl(MethodImplOptions.NoInlining)] static Assembly SomeSecurityCriticalMethod(out StackTrace stack) { stack = new StackTrace(); return Assembly.GetExecutingAssembly(); } } } Assembly ConsoleApp.exe using System; using ClassLib; using System.Diagnostics; class Program { static void Main() { Console.WriteLine("runtime: {0}", Environment.Version); StackTrace stack; Console.WriteLine("Foo: {0}\n{1}", A.Foo(out stack), stack); Console.WriteLine("Bar: {0}\n{1}", A.Bar(out stack), stack); Console.WriteLine("Baz: {0}\n{1}", A.Baz(out stack), stack); Console.WriteLine("Bob: {0}\n{1}", A.Bob(out stack), stack); } } Results: runtime: 4.0.30128.1 Foo: ClassLib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null at ClassLib.A.Foo(StackTrace& stack) at Program.Main() Bar: ClassLib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null at ClassLib.A.Bar(StackTrace& stack) at Program.Main() Baz: at Program.Main() Bob: ClassLib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null at Program.Main() So questions are: Why JIT does not inlined Foo and Bar calls as Baz does? They are lower than 32 bytes of IL and are good candidates for inlining. Why JIT inlined call of Bob and inner call of SomeSecurityCriticalMethod that is marked with the [MethodImpl(MethodImplOptions.NoInlining)] attribute? Why GetExecutingAssembly returns a valid assembly when is called by inlined Baz and SomeSecurityCriticalMethod methods? I've expect that it performs the stack walk to detect the executing assembly, but stack will contains only Program.Main() call and no methods of ClassLib assenbly, to ConsoleApp should be returned.

    Read the article

  • Why Is Faulty Behaviour In The .NET Framework Not Fixed?

    - by Alois Kraus
    Here is the scenario: You have a Windows Form Application that calls a method via Invoke or BeginInvoke which throws exceptions. Now you want to find out where the error did occur and how the method has been called. Here is the output we do get when we call Begin/EndInvoke or simply Invoke The actual code that was executed was like this:         private void cInvoke_Click(object sender, EventArgs e)         {             InvokingFunction(CallMode.Invoke);         }            [MethodImpl(MethodImplOptions.NoInlining)]         void InvokingFunction(CallMode mode)         {             switch (mode)             {                 case CallMode.Invoke:                     this.Invoke(new MethodInvoker(GenerateError));   The faulting method is called GenerateError which does throw a NotImplementedException exception and wraps it in a NotSupportedException.           [MethodImpl(MethodImplOptions.NoInlining)]         void GenerateError()         {             F1();         }           private void F1()         {             try             {                 F2();             }             catch (Exception ex)             {                 throw new NotSupportedException("Outer Exception", ex);             }         }           private void F2()         {            throw new NotImplementedException("Inner Exception");         } It is clear that the method F2 and F1 did actually throw these exceptions but we do not see them in the call stack. If we directly call the InvokingFunction and catch and print the exception we can find out very easily how we did get into this situation. We see methods F1,F2,GenerateError and InvokingFunction directly in the stack trace and we see that actually two exceptions did occur. Here is for comparison what we get from Invoke/EndInvoke System.NotImplementedException: Inner Exception     StackTrace:    at System.Windows.Forms.Control.MarshaledInvoke(Control caller, Delegate method, Object[] args, Boolean synchronous)     at System.Windows.Forms.Control.Invoke(Delegate method, Object[] args)     at WindowsFormsApplication1.AppForm.InvokingFunction(CallMode mode)     at WindowsFormsApplication1.AppForm.cInvoke_Click(Object sender, EventArgs e)     at System.Windows.Forms.Control.OnClick(EventArgs e)     at System.Windows.Forms.Button.OnClick(EventArgs e) The exception message is kept but the stack starts running from our Invoke call and not from the faulting method F2. We have therefore no clue where this exception did occur! The stack starts running at the method MarshaledInvoke because the exception is rethrown with the throw catchedException which resets the stack trace. That is bad but things are even worse because if previously lets say 5 exceptions did occur .NET will return only the first (innermost) exception. That does mean that we do not only loose the original call stack but all other exceptions and all data contained therein as well. It is a pity that MS does know about this and simply closes this issue as not important. Programmers will play a lot more around with threads than before thanks to TPL, PLINQ that do come with .NET 4. Multithreading is hyped quit a lot in the press and everybody wants to use threads. But if the .NET Framework makes it nearly impossible to track down the easiest UI multithreading issue I have a problem with that. The problem has been reported but obviously not been solved. .NET 4 Beta 2 did not have changed that dreaded GetBaseException call in MarshaledInvoke to return only the innermost exception of the complete exception stack. It is really time to fix this. WPF on the other hand does the right thing and wraps the exceptions inside a TargetInvocationException which makes much more sense. But Not everybody uses WPF for its daily work and Windows forms applications will still be used for a long time. Below is the code to repro the issues shown and how the exceptions can be rendered in a meaningful way. The default Exception.ToString implementation generates a hard to interpret stack if several nested exceptions did occur. using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Threading; using System.Globalization; using System.Runtime.CompilerServices;   namespace WindowsFormsApplication1 {     public partial class AppForm : Form     {         enum CallMode         {             Direct = 0,             BeginInvoke = 1,             Invoke = 2         };           public AppForm()         {             InitializeComponent();             Thread.CurrentThread.CurrentUICulture = CultureInfo.InvariantCulture;             Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);         }           void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)         {             cOutput.Text = PrintException(e.Exception, 0, null).ToString();         }           private void cDirectUnhandled_Click(object sender, EventArgs e)         {             InvokingFunction(CallMode.Direct);         }           private void cDirectCall_Click(object sender, EventArgs e)         {             try             {                 InvokingFunction(CallMode.Direct);             }             catch (Exception ex)             {                 cOutput.Text = PrintException(ex, 0, null).ToString();             }         }           private void cInvoke_Click(object sender, EventArgs e)         {             InvokingFunction(CallMode.Invoke);         }           private void cBeginInvokeCall_Click(object sender, EventArgs e)         {             InvokingFunction(CallMode.BeginInvoke);         }           [MethodImpl(MethodImplOptions.NoInlining)]         void InvokingFunction(CallMode mode)         {             switch (mode)             {                 case CallMode.Direct:                     GenerateError();                     break;                 case CallMode.Invoke:                     this.Invoke(new MethodInvoker(GenerateError));                     break;                 case CallMode.BeginInvoke:                     IAsyncResult res = this.BeginInvoke(new MethodInvoker(GenerateError));                     this.EndInvoke(res);                     break;             }         }           [MethodImpl(MethodImplOptions.NoInlining)]         void GenerateError()         {             F1();         }           private void F1()         {             try             {                 F2();             }             catch (Exception ex)             {                 throw new NotSupportedException("Outer Exception", ex);             }         }           private void F2()         {            throw new NotImplementedException("Inner Exception");         }           StringBuilder PrintException(Exception ex, int identLevel, StringBuilder sb)         {             StringBuilder builtStr = sb;             if( builtStr == null )                 builtStr = new StringBuilder();               if( ex == null )                 return builtStr;                 WriteLine(builtStr, String.Format("{0}: {1}", ex.GetType().FullName, ex.Message), identLevel);             WriteLine(builtStr, String.Format("StackTrace: {0}", ShortenStack(ex.StackTrace)), identLevel + 1);             builtStr.AppendLine();               return PrintException(ex.InnerException, ++identLevel, builtStr);         }               void WriteLine(StringBuilder sb, string msg, int identLevel)         {             foreach (string trimmedLine in SplitToLines(msg)                                            .Select( (line) => line.Trim()) )             {                 for (int i = 0; i < identLevel; i++)                     sb.Append('\t');                 sb.Append(trimmedLine);                 sb.AppendLine();             }         }           string ShortenStack(string stack)         {             int nonAppFrames = 0;             // Skip stack frames not part of our app but include two foreign frames and skip the rest             // If our stack frame is encountered reset counter to 0             return SplitToLines(stack)                               .Where((line) =>                               {                                   nonAppFrames = line.Contains("WindowsFormsApplication1") ? 0 : nonAppFrames + 1;                                   return nonAppFrames < 3;                               })                              .Select((line) => line)                              .Aggregate("", (current, line) => current + line + Environment.NewLine);         }           static char[] NewLines = Environment.NewLine.ToCharArray();         string[] SplitToLines(string str)         {             return str.Split(NewLines, StringSplitOptions.RemoveEmptyEntries);         }     } }

    Read the article

  • Strange thing about .NET 4.0 filesystem enumeratation functionality

    - by codymanix
    I just read a page of "Whats new .NET Framework 4.0". I have trouble understanding the last paragraph: To remove open handles on enumerated directories or files Create a custom method (or function in Visual Basic) to contain your enumeration code. Apply the MethodImplAttribute attribute with the NoInlining option to the new method. For example: [MethodImplAttribute(MethodImplOptions.NoInlining)] Private void Enumerate() Include the following method calls, to run after your enumeration code: * The GC.Collect() method (no parameters). * The GC.WaitForPendingFinalizers() method. Why the attribute NoInlining? What harm would inlining do here? Why call the garbage collector manually, why not making the enumerator implement IDisposable in the first place? I suspect they use FindFirstFile()/FindNextFile() API calls for the imlementation, so FindClose() has to be called in any case if the enumeration is done.

    Read the article

  • Calling WebService From Same Project

    - by Yehia A.Salam
    Hi, I'm trying to call an asp.net webservice from the same project it's in: [MethodImpl(MethodImplOptions.Synchronized)] public static void OnFileCreated(object source, FileSystemEventArgs e) { trackdata_analyse rWebAnalyse = new trackdata_analyse(); rWebAnalyse.Analyse(@"pending\" + e.Name, "YOUNIVATE"); } However i always get the following "HttpContext is not available. This class can only be used in the context of an ASP.NET request." when calling Server.MapPath from the webservice: [WebMethod] public int Analyse(string fileName, string PARSING_MODULE){ int nRecords; TrackSession rTrackSession = new TrackSession() ; string filePath = Server.MapPath(@"..\data\") + fileName; do i have to add the WebReference instead, though the webservice is in the same project? Thanks In Advance

    Read the article

  • Invoke "internal extern" constructor using reflections

    - by Riz
    Hi, I have following class (as seen through reflector) public class W : IDisposable { public W(string s); public W(string s, byte[] data); // more constructors [MethodImpl(MethodImplOptions.InternalCall)] internal extern W(string s, int i); public static W Func(string s, int i); } I am trying to call "internal extern" constructor or Func using reflections MethodInfo dynMethod = typeof(W).GetMethod("Func", BindingFlags.Static); object[] argVals = new object[] { "hi", 1 }; dynMethod.Invoke(null, argVals); and Type type = typeof(W); Type[] argTypes = new Type[] { typeof(System.String), typeof(System.Int32) }; ConstructorInfo cInfo = type.GetConstructor(BindingFlags.InvokeMethod | BindingFlags.NonPublic, null, argTypes, null); object[] argVals = new object[] { "hi", 1 }; dynMethod.Invoke(null, argVals); unfortunantly both variants rise NullReferenceException when trying to Invoke, so, I must be doing something wrong?

    Read the article

  • Strange thing about .NET 4.0 filesystem enumeration functionality

    - by codymanix
    I just read a page of "Whats new .NET Framework 4.0". I have trouble understanding the last paragraph: To remove open handles on enumerated directories or files Create a custom method (or function in Visual Basic) to contain your enumeration code. Apply the MethodImplAttribute attribute with the NoInlining option to the new method. For example: [MethodImplAttribute(MethodImplOptions.NoInlining)] Private void Enumerate() Include the following method calls, to run after your enumeration code: * The GC.Collect() method (no parameters). * The GC.WaitForPendingFinalizers() method. Why the attribute NoInlining? What harm would inlining do here? Why call the garbage collector manually, why not making the enumerator implement IDisposable in the first place? I suspect they use FindFirstFile()/FindNextFile() API calls for the imlementation, so FindClose() has to be called in any case if the enumeration is done.

    Read the article

  • Thinktecture.IdentityModel: Comparing Strings without leaking Timinig Information

    - by Your DisplayName here!
    Paul Hill commented on a recent post where I was comparing HMACSHA256 signatures. In a nutshell his complaint was that I am leaking timing information while doing so – or in other words, my code returned faster with wrong (or partially wrong) signatures than with the correct signature. This can be potentially used for timing attacks like this one. I think he got a point here, especially in the era of cloud computing where you can potentially run attack code on the same physical machine as your target to do high resolution timing analysis (see here for an example). It turns out that it is not that easy to write a time-constant string comparer due to all sort of (unexpected) clever optimization mechanisms in the CLR. With the help and feedback of Paul and Shawn I came up with this: Structure the code in a way that the CLR will not try to optimize it In addition turn off optimization (just in case a future version will come up with new optimization methods) Add a random sleep when the comparison fails (using Shawn’s and Stephen’s nice Random wrapper for RNGCryptoServiceProvider). You can find the full code in the Thinktecture.IdentityModel download. [MethodImpl(MethodImplOptions.NoOptimization)] public static bool IsEqual(string s1, string s2) {     if (s1 == null && s2 == null)     {         return true;     }       if (s1 == null || s2 == null)     {         return false;     }       if (s1.Length != s2.Length)     {         return false;     }       var s1chars = s1.ToCharArray();     var s2chars = s2.ToCharArray();       int hits = 0;     for (int i = 0; i < s1.Length; i++)     {         if (s1chars[i].Equals(s2chars[i]))         {             hits += 2;         }         else         {             hits += 1;         }     }       bool same = (hits == s1.Length * 2);       if (!same)     {         var rnd = new CryptoRandom();         Thread.Sleep(rnd.Next(0, 10));     }       return same; }

    Read the article

  • Setting useLegacyV2RuntimeActivationPolicy At Runtime

    - by Reed
    Version 4.0 of the .NET Framework included a new CLR which is almost entirely backwards compatible with the 2.0 version of the CLR.  However, by default, mixed-mode assemblies targeting .NET 3.5sp1 and earlier will fail to load in a .NET 4 application.  Fixing this requires setting useLegacyV2RuntimeActivationPolicy in your app.Config for the application.  While there are many good reasons for this decision, there are times when this is extremely frustrating, especially when writing a library.  As such, there are (rare) times when it would be beneficial to set this in code, at runtime, as well as verify that it’s running correctly prior to receiving a FileLoadException. Typically, loading a pre-.NET 4 mixed mode assembly is handled simply by changing your app.Config file, and including the relevant attribute in the startup element: <?xml version="1.0" encoding="utf-8" ?> <configuration> <startup useLegacyV2RuntimeActivationPolicy="true"> <supportedRuntime version="v4.0"/> </startup> </configuration> .csharpcode { background-color: #ffffff; font-family: consolas, "Courier New", courier, monospace; color: black; font-size: small } .csharpcode pre { background-color: #ffffff; font-family: consolas, "Courier New", courier, monospace; color: black; font-size: small } .csharpcode pre { margin: 0em } .csharpcode .rem { color: #008000 } .csharpcode .kwrd { color: #0000ff } .csharpcode .str { color: #006080 } .csharpcode .op { color: #0000c0 } .csharpcode .preproc { color: #cc6633 } .csharpcode .asp { background-color: #ffff00 } .csharpcode .html { color: #800000 } .csharpcode .attr { color: #ff0000 } .csharpcode .alt { background-color: #f4f4f4; margin: 0em; width: 100% } .csharpcode .lnum { color: #606060 } This causes your application to run correctly, and load the older, mixed-mode assembly without issues. For full details on what’s happening here and why, I recommend reading Mark Miller’s detailed explanation of this attribute and the reasoning behind it. Before I show any code, let me say: I strongly recommend using the official approach of using app.config to set this policy. That being said, there are (rare) times when, for one reason or another, changing the application configuration file is less than ideal. While this is the supported approach to handling this issue, the CLR Hosting API includes a means of setting this programmatically via the ICLRRuntimeInfo interface.  Normally, this is used if you’re hosting the CLR in a native application in order to set this, at runtime, prior to loading the assemblies.  However, the F# Samples include a nice trick showing how to load this API and bind this policy, at runtime.  This was required in order to host the Managed DirectX API, which is built against an older version of the CLR. This is fairly easy to port to C#.  Instead of a direct port, I also added a little addition – by trapping the COM exception received if unable to bind (which will occur if the 2.0 CLR is already bound), I also allow a runtime check of whether this property was setup properly: public static class RuntimePolicyHelper { public static bool LegacyV2RuntimeEnabledSuccessfully { get; private set; } static RuntimePolicyHelper() { ICLRRuntimeInfo clrRuntimeInfo = (ICLRRuntimeInfo)RuntimeEnvironment.GetRuntimeInterfaceAsObject( Guid.Empty, typeof(ICLRRuntimeInfo).GUID); try { clrRuntimeInfo.BindAsLegacyV2Runtime(); LegacyV2RuntimeEnabledSuccessfully = true; } catch (COMException) { // This occurs with an HRESULT meaning // "A different runtime was already bound to the legacy CLR version 2 activation policy." LegacyV2RuntimeEnabledSuccessfully = false; } } [ComImport] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [Guid("BD39D1D2-BA2F-486A-89B0-B4B0CB466891")] private interface ICLRRuntimeInfo { void xGetVersionString(); void xGetRuntimeDirectory(); void xIsLoaded(); void xIsLoadable(); void xLoadErrorString(); void xLoadLibrary(); void xGetProcAddress(); void xGetInterface(); void xSetDefaultStartupFlags(); void xGetDefaultStartupFlags(); [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] void BindAsLegacyV2Runtime(); } } Using this, it’s possible to not only set this at runtime, but also verify, prior to loading your mixed mode assembly, whether this will succeed. In my case, this was quite useful – I am working on a library purely for internal use which uses a numerical package that is supplied with both a completely managed as well as a native solver.  The native solver uses a CLR 2 mixed-mode assembly, but is dramatically faster than the pure managed approach.  By checking RuntimePolicyHelper.LegacyV2RuntimeEnabledSuccessfully at runtime, I can decide whether to enable the native solver, and only do so if I successfully bound this policy. There are some tricks required here – To enable this sort of fallback behavior, you must make these checks in a type that doesn’t cause the mixed mode assembly to be loaded.  In my case, this forced me to encapsulate the library I was using entirely in a separate class, perform the check, then pass through the required calls to that class.  Otherwise, the library will load before the hosting process gets enabled, which in turn will fail. This code will also, of course, try to enable the runtime policy before the first time you use this class – which typically means just before the first time you check the boolean value.  As a result, checking this early on in the application is more likely to allow it to work. Finally, if you’re using a library, this has to be called prior to the 2.0 CLR loading.  This will cause it to fail if you try to use it to enable this policy in a plugin for most third party applications that don’t have their app.config setup properly, as they will likely have already loaded the 2.0 runtime. As an example, take a simple audio player.  The code below shows how this can be used to properly, at runtime, only use the “native” API if this will succeed, and fallback (or raise a nicer exception) if this will fail: public class AudioPlayer { private IAudioEngine audioEngine; public AudioPlayer() { if (RuntimePolicyHelper.LegacyV2RuntimeEnabledSuccessfully) { // This will load a CLR 2 mixed mode assembly this.audioEngine = new AudioEngineNative(); } else { this.audioEngine = new AudioEngineManaged(); } } public void Play(string filename) { this.audioEngine.Play(filename); } } Now – the warning: This approach works, but I would be very hesitant to use it in public facing production code, especially for anything other than initializing your own application.  While this should work in a library, using it has a very nasty side effect: you change the runtime policy of the executing application in a way that is very hidden and non-obvious.

    Read the article

1