From f975120d20d51ca11217e4abbf16cc51ab8c9290 Mon Sep 17 00:00:00 2001
From: Takashi Yano <takashi.yano@nifty.ne.jp>
Date: Sat, 22 Oct 2022 14:05:40 +0900
Subject: [PATCH 38/N] Cygwin: pty: Fix 'Bad address' error when running
 'cmd.exe /c dir'

- If the command executed is 'cmd.exe /c [...]', runpath in spawn.cc
  will be NULL. In this case, is_console_app(runpath) check causes
  access violation. This case also the command executed is obviously
  console app., therefore, treat it as console app to fix this issue.

  Addresses: https://github.com/msys2/msys2-runtime/issues/108

This is a backport of 08281cf4cc (Cygwin: pty: Fix 'Bad address' error
when running 'cmd.exe /c dir', 2022-10-22).

The original patch that was replaced by this commit had this additional
information that is now sadly lost in Cygwin's history:

In 2b4f986e49 (Cygwin: pty: Treat *.bat and *.cmd as a non-cygwin
console app., 2022-07-31), we introduced a bug fix that specifically
looks for a suffix of the command's file name.

However, that file name might be set to `NULL`, namely when
`null_app_name == true`, which is the case when we detected a
command-line `cmd /c [...]`.

But the commit mentioned above did not account for that possibility,
instead assuming that it always has to check the file name for a `.bat`
or `.cmd` suffix. As a consequence, `cmd /c [...]` invocations are
completely broken in v3.3.6, resulting in a `Bad address` error.

Signed-off-by: Johannes Schindelin <johannes.schindelin@gmx.de>
---
 winsup/cygwin/spawn.cc | 2 ++
 1 file changed, 2 insertions(+)

diff --git a/winsup/cygwin/spawn.cc b/winsup/cygwin/spawn.cc
index bc9dc5a..9636109 100644
--- a/winsup/cygwin/spawn.cc
+++ b/winsup/cygwin/spawn.cc
@@ -198,6 +198,8 @@ handle (int fd, bool writing)
 static bool
 is_console_app (WCHAR *filename)
 {
+  if (filename == NULL)
+    return true; /* The command executed is command.com or cmd.exe. */
   HANDLE h;
   const int id_offset = 92;
   h = CreateFileW (filename, GENERIC_READ, FILE_SHARE_READ,
