Skip to content

Add API to get an AssemblyName that doesn't throw on a native binary #21785

Closed

Description

@ericstj

I've seen patterns like this in countless tools:

try
{
    return AssemblyName.GetAssemblyName(sourcePath);
}
catch(BadImageFormatException)
{
    return null;
}

It would be better if we could just do:

AssemblyName name;
return AssemblyName.TryGetAssemblyName(sourcePath, out name) ? name : null;

API signature:

  public static bool TryGetAssemblyName(string assemblyFile, out AssemblyName assemblyName);

By making this a new API we don't change the behavior of the existing API. By making the API determine if a file is an assembly and returning the name we avoid having to open the file twice.

The other alternative available today requires using System.Reflection.Metadata which is not part of netstandard and requires redistributing a sizeable dependency (800KB), or writing your own PE parsing code (which requires opening the file twice).

/cc @gkhanna79

Activity

  1. danmoseley commented on May 18, 2017

    @danmoseley
    Contributor

    There is an issue somewhere with a proposed implementation, but I cannot find it right now.

  2. danmoseley commented on Aug 30, 2017

    @danmoseley
    Contributor

    @atsushikan do you support this proposal? If so please add api-ready-for-review label.

  3. ericstj commented on Aug 30, 2017

    @ericstj
    MemberAuthor

    It should throw for things like a null path, malformed path, a non-existent file, sharing violation when reading the file. If its successfully able to open the file then I'd expect it to not throw.

    Returning null as sentinel seems reasonable. Ultimately this one seems like an FxDC nit.

    I didn't have the proposed implementation. Perhaps its over in CoreCLR repo?

  4. karelz commented on Sep 9, 2017

    @karelz
    Member

    @atsushikan as area owner you are responsible for the API surface - doing first level API review, making sure it is in line with area plans.
    Once the API is approved, area owners are responsible to mark it as up-for-grabs (if appropriate) with brief notes on complexity and hint of next steps as for any other issue - see triage rules.
    When there is contributor interested in grabbing the issue, area owners are responsible to shepherd the effort, incl. guidance and code review. If the time investment is not appropriate for a particular issue, you can always discuss options/guidance with CoreFX leads (me and Dan) or your lead.

    Area owners are NOT responsible to implement every single bug fix / API request.
    However, area owners are expected to prioritize their area and make sure we keep high quality in the area via fixing the right bugs and adding/implementing the right APIs at the right moment.

    Hope that makes sense :)

  5. karelz commented on Sep 19, 2017

    @karelz
    Member

    API review: (channeling @KrzysztofCwalina's insights from history)
    Historically, we used Try* only for perf reasons. This is likely not the case here (opening assembly hits disk already), so exception is small contributor. @ericstj can you please confirm it is not perf? (having some data would help)

    If it is syntax of exception handling, we should talk to Roslyn team.
    If it is about debuggability, then we are on slippery slope road - we rejected Try* pattern in the past in such cases (mainly due to "how common is it to warrant Try*). If we want to change our guidance in general, we should discuss that.

    Actionable items:

    1. What is the primary motivation of the API? Perf vs. syntax vs. debuggability?
    2. We should discuss general guidance on exceptions from BCL in each of those cotnexts - @KrzysztofCwalina will present & organize (with C# / VS Debugger teams in the room)

    Deferring decision until we have more info.

  6. ericstj commented on Sep 19, 2017

    @ericstj
    MemberAuthor

    Primary driver was debuggability. Current API will result in an exception even in the normal case.

    See dotnet/standard#326 /cc @KirillOsenkov to add his opinion.

    Note that Try isn't a requirement in the method name. We could just as well have a different method name that returns null instead of an AssemblyName (as Ati suggested). We don't want the existing API to do that because it'd be a breaking change. So an alternative suggestion would be
    AssemblyName.GetAssemblyName(string assemblyFile, bool throwOnInvalidAssembly).

  7. KirillOsenkov commented on Sep 19, 2017

    @KirillOsenkov
    Member

    Yes, debuggability is really bad. I think we should rethink the approach of not having Try methods just because they let us avoid a first-chance exception.

    I should write a blog post about first-chance exceptions, a lot of people don't realize a few important things there. Basically in a codebase where you're disciplined about first-chance exceptions there's a magnificent way to find hidden bugs - have a FirstChanceException handler with a whitelist of known benign ones. This catches bugs like crazy.

    If the framework itself doesn't play along, it renders this entire class of bug finding ineffective. I can't tell you how many bugs and crashes in Roslyn we've prevented because we adopted this policy. It's hard to overstate.

  8. KrzysztofCwalina commented on Sep 20, 2017

    @KrzysztofCwalina
    Member

    The .NET platform was designed in a way that it does not play along with first change exceptions debugging. The technique works in C++ because of a completely different philosophy for the design of error reporting (more error codes).

    I am skeptical that we can make it first chance exceptions friendly 20 years after it was conceived. Every now and there there are people who push for various local "fixes" that IMO only make the platform inconsistent without actually solving the problem, i.e we won't be able to undo the exceptions we already throw.

  9. davkean commented on Sep 20, 2017

    @davkean
    Member

    @KrzysztofCwalina But you can move the platform forward by adding non-throwing versions of APIs - and new consumers will use them by default, and existing consumers will change to use as they churn those areas. No difference from having int.Parse in v1 and adding TryParse in future versions.

    If it is about debuggability, then we are on slippery slope road - we rejected Try* pattern in the past in such cases (mainly due to "how common is it to warrant Try*). If we want to change our guidance in general, we should discuss that.

    This doesn't match my recollection, nor past usage, here's a couple of examples:

    https://docs.microsoft.com/en-us/dotnet/api/system.threading.thread.trysetapartmentstate?view=netframework-4.7#System_Threading_Thread_TrySetApartmentState_System_Threading_ApartmentState_
    https://docs.microsoft.com/en-us/dotnet/api/system.reflection.portableexecutable.pereader.tryopenassociatedportablepdb?view=netcore-2.0#System_Reflection_PortableExecutable_PEReader_TryOpenAssociatedPortablePdb_System_String_System_Func_System_String_System_IO_Stream__System_Reflection_Metadata_MetadataReaderProvider__System_String__

    You could also put "File.Exists" in the same bucket here - as it doesn't leak any exceptions, but swallows them for convenience.

  10. nguerrera commented on Sep 20, 2017

    @nguerrera
    Contributor

    have a FirstChanceException handler with a whitelist of known benign ones. This catches bugs like crazy.

    IMHO, this catching bugs is indicative of catching all exceptions way too aggressively. Sadly, most programs are very, very guilty of that.

    But I do think it's fine to offer non-throwing alternatives as a debugging aid and not just for perf.

  11. davkean commented on Sep 20, 2017

    @davkean
    Member

    Another example is the CanXXX, SupportsXXX light-up APIs vs. catching InvalidOperationException or NotSupportedException.

  12. agocke commented on Sep 20, 2017

    @agocke
    Member

    I think it's important to note that the goal is not to eliminate exceptions, it's to eliminate exceptions on non-exceptional control paths. If a call is expected, and allowed, to fail it would be far better to utilize some other error mechanism.

  13. KirillOsenkov commented on Sep 20, 2017

    @KirillOsenkov
    Member

    Exactly. It's about non-avoidable exceptions vs. easily avoidable exceptions. I only want to reduce the easily avoidable exceptions like when Guid.TryParse was added to complement Guid.Parse.

  14. 22 remaining items

  15. KirillOsenkov commented on Oct 6, 2017

    @KirillOsenkov
    Member

    May I suggest that you start a new VS instance under debugger with first-chance exceptions on. It is educational and worth doing at least once as the best way to familiarize yourself with the problem. Try creating a C# console app, editing, building.

  16. CyrusNajmabadi commented on Oct 10, 2017

    @CyrusNajmabadi
    Contributor

    Do we have the list?

    Not of the top of my head. And I'm not really using VS anymore. But it's not hard to collect just by running the experiment.

  17. davkean commented on Oct 10, 2017

    @davkean
    Member

    These are the ones that I'm aware of:

    Exception Throw by? Notes
    FileNotFoundException Normal probing of XmlSerializer No workaround.
    BadImageFormatException/FileLoadException Assembly.GetAssemblyName
    MissingManifestResourceException Normal probing of satellite assemblies No workaround.
    MissingMethodException Binder.DefaultBinder.BindToMethod when it cannot find appropriate method Plan on working around around this by copying huge chunks of DefaultBinder and avoiding thrown exception.
    InvalidCastException/FormatException/OverflowException Convert.ChangeType when it cannot convert from type Don't know how to workaround yet, probably attempt to come up with a list of known "allowed" conversions and manually call TryParse.
  18. jnm2 commented on Oct 10, 2017

    @jnm2
    Contributor

    @davkean Lol! My list is identical.

  19. gulbanana commented on Oct 11, 2017

    @gulbanana

    there are few enough badly behaved apis which encourage throw-and-catch that i routinely rework code to avoid using them - i was reminded of this issue today when a coworker mentioned avoiding some uses of “new XmlSerializer()” for the same reason. if you can get near to 0 first-chance exceptions it’s a great aid to debuggability, and every little feature like TryGetAssemblyName helps.

    please don’t discard the idea just because it isn’t a performance issue!

  20. davkean commented on Oct 11, 2017

    @davkean
    Member

    Yes, forgot about that one, added it to the list.

  21. danmoseley commented on Feb 2, 2018

    @danmoseley
    Contributor

    -> Future as not needed for 2.1

  22. transferred this issue fromdotnet/corefxon Jan 31, 2020
  23. added this to the 5.0 milestone on Jan 31, 2020
  24. steveharter commented on Jul 7, 2020

    @steveharter
    Contributor

    Due to 5.0 schedule constraints, this is being moved to Future.

  25. modified the milestones: 5.0.0, Future on Jul 7, 2020
  26. jkotas commented on Jul 7, 2020

    @jkotas
    Member

    The other alternative available today requires using System.Reflection.Metadata which is not part of netstandard

    System.Reflection.Metadata is part of .NET Core surface now, so this is no longer concern.

    System.Reflection.Metadata is the right way to solve this going forward. Also, System.Reflection.Metadata is faster and lighter weight API than AssemblyName.GetAssemblyName that runs the full runtime assembly loader in a special mode.

  27. ghost locked as resolved and limited conversation to collaborators on Dec 23, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-needs-workarea-System.Reflection

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions