Skip to content

System.IO.IOException “The parameter is incorrect” on System_Console!System.ConsolePal+ControlCHandlerRegistrar.Unregister()+0x35 #21726

Closed

Description

@TingluoHuang

initial report: https://github.com/dotnet/coreclr/issues/11550

My netcore 1.1 app crash on exit due to following exception.

0:000> .cordll -lp C:\Agent.CoreCLR\_dotnetsdk\1.0.1\shared\Microsoft.NETCore.App\1.1.1
CLR DLL status: Loaded DLL C:\Agent.CoreCLR\_dotnetsdk\1.0.1\shared\Microsoft.NETCore.App\1.1.1\mscordaccore.dll
0:000> !pe
Exception object: 0000003b30c759a0
Exception type:   System.IO.IOException
Message:          The parameter is incorrect
InnerException:   <none>
StackTrace (generated):
    SP               IP               Function
    0000003B4928CE50 00007FFE2BE65935 System_Console!System.ConsolePal+ControlCHandlerRegistrar.Unregister()+0x35
    0000003B4928CE90 00007FFE2BE65882 System_Console!System.Console.remove_CancelKeyPress(System.ConsoleCancelEventHandler)+0xc2
    0000003B4928CEE0 00007FFE2BE65782 Microsoft_VisualStudio_Services_Agent!Microsoft.VisualStudio.Services.Agent.Terminal.Dispose()+0x42
    0000003B4928CF20 00007FFE2B701CCF Agent_Worker!Microsoft.VisualStudio.Services.Agent.Worker.Program+<MainAsync>d__1.MoveNext()+0xa7f
    0000003B2DF5DD20 00007FFE8ABF4D8F System_Private_CoreLib_ni!System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()+0x1f
    0000003B2DF5DD50 00007FFE8ABEDCA6 System_Private_CoreLib_ni!System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(System.Threading.Tasks.Task)+0x46
    0000003B2DF5DD80 00007FFE2B7004A8 Agent_Worker!Microsoft.VisualStudio.Services.Agent.Worker.Program.Main(System.String[])+0x28

StackTraceString: <none>
HResult: 80070057

Before the crash, we pinvoke to cancel some child process via the following code.
we didn't get any exception trace, and the child process is able to get Ctrl-C and gracefully exit.

private async Task<bool> SendCtrlSignal(ConsoleCtrlEvent signal, TimeSpan timeout)
{
    Trace.Info($"Sending {signal} to process {_proc.Id}.");
    ConsoleCtrlDelegate ctrlEventHandler = new ConsoleCtrlDelegate(ConsoleCtrlHandler);
    try
    {
        if (!FreeConsole())
        {
            throw new Win32Exception(Marshal.GetLastWin32Error());
        }

        if (!AttachConsole(_proc.Id))
        {
            throw new Win32Exception(Marshal.GetLastWin32Error());
        }

        if (!SetConsoleCtrlHandler(ctrlEventHandler, true))
        {
            throw new Win32Exception(Marshal.GetLastWin32Error());
        }

        if (!GenerateConsoleCtrlEvent(signal, 0))
        {
            throw new Win32Exception(Marshal.GetLastWin32Error());
        }

        Trace.Info($"Successfully send {signal} to process {_proc.Id}.");
        Trace.Info($"Waiting for process exit or {timeout.TotalSeconds} seconds after {signal} signal fired.");
        var completedTask = await Task.WhenAny(Task.Delay(timeout), _processExitedCompletionSource.Task);
        if (completedTask == _processExitedCompletionSource.Task)
        {
            Trace.Info("Process exit successfully.");
            return true;
        }
        else
        {
            Trace.Info($"Process did not honor {signal} signal within {timeout.TotalSeconds} seconds.");
            return false;
        }
    }
    catch (Exception ex)
    {
        Trace.Info($"{signal} signal doesn't fire successfully.");
        Trace.Error($"Catch exception during send {signal} event to process {_proc.Id}");
        Trace.Error(ex);
        return false;
    }
    finally
    {
        FreeConsole();
        SetConsoleCtrlHandler(ctrlEventHandler, false);
    }
}

private bool ConsoleCtrlHandler(ConsoleCtrlEvent ctrlType)
{
    switch (ctrlType)
    {
        case ConsoleCtrlEvent.CTRL_C:
            Trace.Info($"Ignore Ctrl+C to current process.");
            // We return True, so the default Ctrl handler will not take action.
            return true;
        case ConsoleCtrlEvent.CTRL_BREAK:
            Trace.Info($"Ignore Ctrl+Break to current process.");
            // We return True, so the default Ctrl handler will not take action.
            return true;
    }

    // If the function handles the control signal, it should return TRUE. 
    // If it returns FALSE, the next handler function in the list of handlers for this process is used.
    return false;
}

We currently only see 2 machine hitting this exception so far. 1 win7 machine, 1 server12r2 machine, but on those machine this error is repro 100% at a time.

I still have the server12r2 VM around, i can provide access if anyone interested.

Activity

  1. danmoseley commented on May 16, 2017

    @danmoseley
    Contributor

    MSDN indicates that multiple handlers are legitimate, so the customer code above adding and removing its own handler should not affect ours.

    One might expect this if our unregister is getting called twice, but it's only called from Console.cs, and within a lock, only if not null, and then set to null within the lock. Also, it's only not null if Register() had been called.

                    lock (InternalSyncObject)
                    {
                        _cancelCallbacks -= value;
                        if (_registrar != null && _cancelCallbacks == null)
                        {
                            _registrar.Unregister();
                            _registrar = null;
                        }
                    }

    This code is the same in 1.1 as 2.0.
    So it's not something immediately obvious.

  2. TingluoHuang commented on May 16, 2017

    @TingluoHuang
    Author

    Here is the code we have: https://github.com/microsoft/vsts-agent

    public static class Program
    {
        public static int Main(string[] args)
        {
            return MainAsync(args).GetAwaiter().GetResult();
        }
    
        public static async Task<int> MainAsync(
            string[] args)
        {
            //ITerminal registers a CTRL-C handler, which keeps the Agent.Worker process running
            //and lets the Agent.Listener handle gracefully the exit.
            using (var hc = new HostContext("Worker"))
            using (var term = hc.GetService<ITerminal>())
            {
                return await RunAsync();
            }
        }
    }

    in ITerminal

    public override void Initialize(IHostContext hostContext)
    {
         base.Initialize(hostContext);
         Console.CancelKeyPress += Console_CancelKeyPress;
    }
    
    private void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
    {
        e.Cancel = true;
        CancelKeyPress?.Invoke(this, e);
    }
    
    private void Dispose(bool disposing)
    {
        if (disposing)
        {
            Console.CancelKeyPress -= Console_CancelKeyPress;
        }
    }
    
    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }
  3. karelz commented on May 16, 2017

    @karelz
    Member

    Does not seem to be critical for 2.0 - moving to Future.

  4. danmoseley commented on May 17, 2017

    @danmoseley
    Contributor

    @stephentoub do you see the defect, in a quick glance? see my note above.

  5. transferred this issue fromdotnet/corefxon Jan 31, 2020
  6. added this to the Future milestone on Jan 31, 2020
  7. carlossanlop commented on Apr 1, 2020

    @carlossanlop
    Contributor

    @TingluoHuang can you still repro this issue in a supported Windows version and in .NET Core 3.1+?

  8. adamsitnik commented on Jun 24, 2020

    @adamsitnik
    Member

    No response since April - I am closing this issue.

    If anyone can reproduce this with .NET Core 3.1+ please reopen the issue and provide a repro case.

  9. removed this from the Future milestone on Jun 24, 2020
  10. 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

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions