We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Memory Leak in _winconsole
Result of call to `CommandLineToArgvW` should be released by `LocalFree`.
Should probably also check for failure of that function call (`NULL` is returned).


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `click/_winconsole.py`
Content:
```
1 # -*- coding: utf-8 -*-
2 # This module is based on the excellent work by Adam Bartoš who
3 # provided a lot of what went into the implementation here in
4 # the discussion to issue1602 in the Python bug tracker.
5 #
6 # There are some general differences in regards to how this works
7 # compared to the original patches as we do not need to patch
8 # the entire interpreter but just work in our little world of
9 # echo and prmopt.
10 
11 import io
12 import os
13 import sys
14 import zlib
15 import time
16 import ctypes
17 import msvcrt
18 from ._compat import _NonClosingTextIOWrapper, text_type, PY2
19 from ctypes import byref, POINTER, c_int, c_char, c_char_p, \
20      c_void_p, py_object, c_ssize_t, c_ulong, windll, WINFUNCTYPE
21 try:
22     from ctypes import pythonapi
23     PyObject_GetBuffer = pythonapi.PyObject_GetBuffer
24     PyBuffer_Release = pythonapi.PyBuffer_Release
25 except ImportError:
26     pythonapi = None
27 from ctypes.wintypes import DWORD, LPWSTR, LPCWSTR, HANDLE
28 
29 
30 c_ssize_p = POINTER(c_ssize_t)
31 
32 kernel32 = windll.kernel32
33 GetStdHandle = kernel32.GetStdHandle
34 ReadConsoleW = kernel32.ReadConsoleW
35 WriteConsoleW = kernel32.WriteConsoleW
36 GetConsoleMode = kernel32.GetConsoleMode
37 GetLastError = kernel32.GetLastError
38 GetCommandLineW = WINFUNCTYPE(LPWSTR)(
39     ('GetCommandLineW', windll.kernel32))
40 CommandLineToArgvW = WINFUNCTYPE(
41     POINTER(LPWSTR), LPCWSTR, POINTER(c_int))(
42         ('CommandLineToArgvW', windll.shell32))
43 
44 
45 STDIN_HANDLE = GetStdHandle(-10)
46 STDOUT_HANDLE = GetStdHandle(-11)
47 STDERR_HANDLE = GetStdHandle(-12)
48 
49 
50 PyBUF_SIMPLE = 0
51 PyBUF_WRITABLE = 1
52 
53 ERROR_SUCCESS = 0
54 ERROR_NOT_ENOUGH_MEMORY = 8
55 ERROR_OPERATION_ABORTED = 995
56 
57 STDIN_FILENO = 0
58 STDOUT_FILENO = 1
59 STDERR_FILENO = 2
60 
61 EOF = b'\x1a'
62 MAX_BYTES_WRITTEN = 32767
63 
64 
65 class Py_buffer(ctypes.Structure):
66     _fields_ = [
67         ('buf', c_void_p),
68         ('obj', py_object),
69         ('len', c_ssize_t),
70         ('itemsize', c_ssize_t),
71         ('readonly', c_int),
72         ('ndim', c_int),
73         ('format', c_char_p),
74         ('shape', c_ssize_p),
75         ('strides', c_ssize_p),
76         ('suboffsets', c_ssize_p),
77         ('internal', c_void_p)
78     ]
79 
80     if PY2:
81         _fields_.insert(-1, ('smalltable', c_ssize_t * 2))
82 
83 
84 # On PyPy we cannot get buffers so our ability to operate here is
85 # serverly limited.
86 if pythonapi is None:
87     get_buffer = None
88 else:
89     def get_buffer(obj, writable=False):
90         buf = Py_buffer()
91         flags = PyBUF_WRITABLE if writable else PyBUF_SIMPLE
92         PyObject_GetBuffer(py_object(obj), byref(buf), flags)
93         try:
94             buffer_type = c_char * buf.len
95             return buffer_type.from_address(buf.buf)
96         finally:
97             PyBuffer_Release(byref(buf))
98 
99 
100 class _WindowsConsoleRawIOBase(io.RawIOBase):
101 
102     def __init__(self, handle):
103         self.handle = handle
104 
105     def isatty(self):
106         io.RawIOBase.isatty(self)
107         return True
108 
109 
110 class _WindowsConsoleReader(_WindowsConsoleRawIOBase):
111 
112     def readable(self):
113         return True
114 
115     def readinto(self, b):
116         bytes_to_be_read = len(b)
117         if not bytes_to_be_read:
118             return 0
119         elif bytes_to_be_read % 2:
120             raise ValueError('cannot read odd number of bytes from '
121                              'UTF-16-LE encoded console')
122 
123         buffer = get_buffer(b, writable=True)
124         code_units_to_be_read = bytes_to_be_read // 2
125         code_units_read = c_ulong()
126 
127         rv = ReadConsoleW(HANDLE(self.handle), buffer, code_units_to_be_read,
128                           byref(code_units_read), None)
129         if GetLastError() == ERROR_OPERATION_ABORTED:
130             # wait for KeyboardInterrupt
131             time.sleep(0.1)
132         if not rv:
133             raise OSError('Windows error: %s' % GetLastError())
134 
135         if buffer[0] == EOF:
136             return 0
137         return 2 * code_units_read.value
138 
139 
140 class _WindowsConsoleWriter(_WindowsConsoleRawIOBase):
141 
142     def writable(self):
143         return True
144 
145     @staticmethod
146     def _get_error_message(errno):
147         if errno == ERROR_SUCCESS:
148             return 'ERROR_SUCCESS'
149         elif errno == ERROR_NOT_ENOUGH_MEMORY:
150             return 'ERROR_NOT_ENOUGH_MEMORY'
151         return 'Windows error %s' % errno
152 
153     def write(self, b):
154         bytes_to_be_written = len(b)
155         buf = get_buffer(b)
156         code_units_to_be_written = min(bytes_to_be_written,
157                                        MAX_BYTES_WRITTEN) // 2
158         code_units_written = c_ulong()
159 
160         WriteConsoleW(HANDLE(self.handle), buf, code_units_to_be_written,
161                       byref(code_units_written), None)
162         bytes_written = 2 * code_units_written.value
163 
164         if bytes_written == 0 and bytes_to_be_written > 0:
165             raise OSError(self._get_error_message(GetLastError()))
166         return bytes_written
167 
168 
169 class ConsoleStream(object):
170 
171     def __init__(self, text_stream, byte_stream):
172         self._text_stream = text_stream
173         self.buffer = byte_stream
174 
175     @property
176     def name(self):
177         return self.buffer.name
178 
179     def write(self, x):
180         if isinstance(x, text_type):
181             return self._text_stream.write(x)
182         try:
183             self.flush()
184         except Exception:
185             pass
186         return self.buffer.write(x)
187 
188     def writelines(self, lines):
189         for line in lines:
190             self.write(line)
191 
192     def __getattr__(self, name):
193         return getattr(self._text_stream, name)
194 
195     def isatty(self):
196         return self.buffer.isatty()
197 
198     def __repr__(self):
199         return '<ConsoleStream name=%r encoding=%r>' % (
200             self.name,
201             self.encoding,
202         )
203 
204 
205 class WindowsChunkedWriter(object):
206     """
207     Wraps a stream (such as stdout), acting as a transparent proxy for all
208     attribute access apart from method 'write()' which we wrap to write in
209     limited chunks due to a Windows limitation on binary console streams.
210     """
211     def __init__(self, wrapped):
212         # double-underscore everything to prevent clashes with names of
213         # attributes on the wrapped stream object.
214         self.__wrapped = wrapped
215 
216     def __getattr__(self, name):
217         return getattr(self.__wrapped, name)
218 
219     def write(self, text):
220         total_to_write = len(text)
221         written = 0
222 
223         while written < total_to_write:
224             to_write = min(total_to_write - written, MAX_BYTES_WRITTEN)
225             self.__wrapped.write(text[written:written+to_write])
226             written += to_write
227 
228 
229 _wrapped_std_streams = set()
230 
231 
232 def _wrap_std_stream(name):
233     # Python 2 & Windows 7 and below
234     if PY2 and sys.getwindowsversion()[:2] <= (6, 1) and name not in _wrapped_std_streams:
235         setattr(sys, name, WindowsChunkedWriter(getattr(sys, name)))
236         _wrapped_std_streams.add(name)
237 
238 
239 def _get_text_stdin(buffer_stream):
240     text_stream = _NonClosingTextIOWrapper(
241         io.BufferedReader(_WindowsConsoleReader(STDIN_HANDLE)),
242         'utf-16-le', 'strict', line_buffering=True)
243     return ConsoleStream(text_stream, buffer_stream)
244 
245 
246 def _get_text_stdout(buffer_stream):
247     text_stream = _NonClosingTextIOWrapper(
248         io.BufferedWriter(_WindowsConsoleWriter(STDOUT_HANDLE)),
249         'utf-16-le', 'strict', line_buffering=True)
250     return ConsoleStream(text_stream, buffer_stream)
251 
252 
253 def _get_text_stderr(buffer_stream):
254     text_stream = _NonClosingTextIOWrapper(
255         io.BufferedWriter(_WindowsConsoleWriter(STDERR_HANDLE)),
256         'utf-16-le', 'strict', line_buffering=True)
257     return ConsoleStream(text_stream, buffer_stream)
258 
259 
260 if PY2:
261     def _hash_py_argv():
262         return zlib.crc32('\x00'.join(sys.argv[1:]))
263 
264     _initial_argv_hash = _hash_py_argv()
265 
266     def _get_windows_argv():
267         argc = c_int(0)
268         argv_unicode = CommandLineToArgvW(GetCommandLineW(), byref(argc))
269         argv = [argv_unicode[i] for i in range(0, argc.value)]
270 
271         if not hasattr(sys, 'frozen'):
272             argv = argv[1:]
273             while len(argv) > 0:
274                 arg = argv[0]
275                 if not arg.startswith('-') or arg == '-':
276                     break
277                 argv = argv[1:]
278                 if arg.startswith(('-c', '-m')):
279                     break
280 
281         return argv[1:]
282 
283 
284 _stream_factories = {
285     0: _get_text_stdin,
286     1: _get_text_stdout,
287     2: _get_text_stderr,
288 }
289 
290 
291 def _is_console(f):
292     if not hasattr(f, 'fileno'):
293         return False
294 
295     try:
296         fileno = f.fileno()
297     except OSError:
298         return False
299 
300     handle = msvcrt.get_osfhandle(fileno)
301     return bool(GetConsoleMode(handle, byref(DWORD())))
302 
303 
304 def _get_windows_console_stream(f, encoding, errors):
305     if get_buffer is not None and \
306        encoding in ('utf-16-le', None) \
307        and errors in ('strict', None) and \
308        _is_console(f):
309         func = _stream_factories.get(f.fileno())
310         if func is not None:
311             if not PY2:
312                 f = getattr(f, 'buffer', None)
313                 if f is None:
314                     return None
315             else:
316                 # If we are on Python 2 we need to set the stream that we
317                 # deal with to binary mode as otherwise the exercise if a
318                 # bit moot.  The same problems apply as for
319                 # get_binary_stdin and friends from _compat.
320                 msvcrt.setmode(f.fileno(), os.O_BINARY)
321             return func(f)
322
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/click/_winconsole.py b/click/_winconsole.py
--- a/click/_winconsole.py
+++ b/click/_winconsole.py
@@ -17,7 +17,8 @@
 import msvcrt
 from ._compat import _NonClosingTextIOWrapper, text_type, PY2
 from ctypes import byref, POINTER, c_int, c_char, c_char_p, \
-     c_void_p, py_object, c_ssize_t, c_ulong, windll, WINFUNCTYPE
+     c_void_p, py_object, c_ssize_t, c_ulong, windll, WINFUNCTYPE, \
+     WinError
 try:
     from ctypes import pythonapi
     PyObject_GetBuffer = pythonapi.PyObject_GetBuffer
@@ -40,6 +41,8 @@
 CommandLineToArgvW = WINFUNCTYPE(
     POINTER(LPWSTR), LPCWSTR, POINTER(c_int))(
         ('CommandLineToArgvW', windll.shell32))
+LocalFree = WINFUNCTYPE(ctypes.c_void_p, ctypes.c_void_p)(
+    ('LocalFree', windll.kernel32))
 
 
 STDIN_HANDLE = GetStdHandle(-10)
@@ -266,7 +269,13 @@
     def _get_windows_argv():
         argc = c_int(0)
         argv_unicode = CommandLineToArgvW(GetCommandLineW(), byref(argc))
-        argv = [argv_unicode[i] for i in range(0, argc.value)]
+        if not argv_unicode:
+            raise WinError()
+        try:
+            argv = [argv_unicode[i] for i in range(0, argc.value)]
+        finally:
+            LocalFree(argv_unicode)
+            del argv_unicode
 
         if not hasattr(sys, 'frozen'):
             argv = argv[1:]

{"golden_diff": "diff --git a/click/_winconsole.py b/click/_winconsole.py\n--- a/click/_winconsole.py\n+++ b/click/_winconsole.py\n@@ -17,7 +17,8 @@\n import msvcrt\n from ._compat import _NonClosingTextIOWrapper, text_type, PY2\n from ctypes import byref, POINTER, c_int, c_char, c_char_p, \\\n-     c_void_p, py_object, c_ssize_t, c_ulong, windll, WINFUNCTYPE\n+     c_void_p, py_object, c_ssize_t, c_ulong, windll, WINFUNCTYPE, \\\n+     WinError\n try:\n     from ctypes import pythonapi\n     PyObject_GetBuffer = pythonapi.PyObject_GetBuffer\n@@ -40,6 +41,8 @@\n CommandLineToArgvW = WINFUNCTYPE(\n     POINTER(LPWSTR), LPCWSTR, POINTER(c_int))(\n         ('CommandLineToArgvW', windll.shell32))\n+LocalFree = WINFUNCTYPE(ctypes.c_void_p, ctypes.c_void_p)(\n+    ('LocalFree', windll.kernel32))\n \n \n STDIN_HANDLE = GetStdHandle(-10)\n@@ -266,7 +269,13 @@\n     def _get_windows_argv():\n         argc = c_int(0)\n         argv_unicode = CommandLineToArgvW(GetCommandLineW(), byref(argc))\n-        argv = [argv_unicode[i] for i in range(0, argc.value)]\n+        if not argv_unicode:\n+            raise WinError()\n+        try:\n+            argv = [argv_unicode[i] for i in range(0, argc.value)]\n+        finally:\n+            LocalFree(argv_unicode)\n+            del argv_unicode\n \n         if not hasattr(sys, 'frozen'):\n             argv = argv[1:]\n", "issue": "Memory Leak in _winconsole\nResult of call to `CommandLineToArgvW` should be released by `LocalFree`.\nShould probably also check for failure of that function call (`NULL` is returned).\n\n", "before_files": [{"content": "# -*- coding: utf-8 -*-\n# This module is based on the excellent work by Adam Barto\u0161 who\n# provided a lot of what went into the implementation here in\n# the discussion to issue1602 in the Python bug tracker.\n#\n# There are some general differences in regards to how this works\n# compared to the original patches as we do not need to patch\n# the entire interpreter but just work in our little world of\n# echo and prmopt.\n\nimport io\nimport os\nimport sys\nimport zlib\nimport time\nimport ctypes\nimport msvcrt\nfrom ._compat import _NonClosingTextIOWrapper, text_type, PY2\nfrom ctypes import byref, POINTER, c_int, c_char, c_char_p, \\\n     c_void_p, py_object, c_ssize_t, c_ulong, windll, WINFUNCTYPE\ntry:\n    from ctypes import pythonapi\n    PyObject_GetBuffer = pythonapi.PyObject_GetBuffer\n    PyBuffer_Release = pythonapi.PyBuffer_Release\nexcept ImportError:\n    pythonapi = None\nfrom ctypes.wintypes import DWORD, LPWSTR, LPCWSTR, HANDLE\n\n\nc_ssize_p = POINTER(c_ssize_t)\n\nkernel32 = windll.kernel32\nGetStdHandle = kernel32.GetStdHandle\nReadConsoleW = kernel32.ReadConsoleW\nWriteConsoleW = kernel32.WriteConsoleW\nGetConsoleMode = kernel32.GetConsoleMode\nGetLastError = kernel32.GetLastError\nGetCommandLineW = WINFUNCTYPE(LPWSTR)(\n    ('GetCommandLineW', windll.kernel32))\nCommandLineToArgvW = WINFUNCTYPE(\n    POINTER(LPWSTR), LPCWSTR, POINTER(c_int))(\n        ('CommandLineToArgvW', windll.shell32))\n\n\nSTDIN_HANDLE = GetStdHandle(-10)\nSTDOUT_HANDLE = GetStdHandle(-11)\nSTDERR_HANDLE = GetStdHandle(-12)\n\n\nPyBUF_SIMPLE = 0\nPyBUF_WRITABLE = 1\n\nERROR_SUCCESS = 0\nERROR_NOT_ENOUGH_MEMORY = 8\nERROR_OPERATION_ABORTED = 995\n\nSTDIN_FILENO = 0\nSTDOUT_FILENO = 1\nSTDERR_FILENO = 2\n\nEOF = b'\\x1a'\nMAX_BYTES_WRITTEN = 32767\n\n\nclass Py_buffer(ctypes.Structure):\n    _fields_ = [\n        ('buf', c_void_p),\n        ('obj', py_object),\n        ('len', c_ssize_t),\n        ('itemsize', c_ssize_t),\n        ('readonly', c_int),\n        ('ndim', c_int),\n        ('format', c_char_p),\n        ('shape', c_ssize_p),\n        ('strides', c_ssize_p),\n        ('suboffsets', c_ssize_p),\n        ('internal', c_void_p)\n    ]\n\n    if PY2:\n        _fields_.insert(-1, ('smalltable', c_ssize_t * 2))\n\n\n# On PyPy we cannot get buffers so our ability to operate here is\n# serverly limited.\nif pythonapi is None:\n    get_buffer = None\nelse:\n    def get_buffer(obj, writable=False):\n        buf = Py_buffer()\n        flags = PyBUF_WRITABLE if writable else PyBUF_SIMPLE\n        PyObject_GetBuffer(py_object(obj), byref(buf), flags)\n        try:\n            buffer_type = c_char * buf.len\n            return buffer_type.from_address(buf.buf)\n        finally:\n            PyBuffer_Release(byref(buf))\n\n\nclass _WindowsConsoleRawIOBase(io.RawIOBase):\n\n    def __init__(self, handle):\n        self.handle = handle\n\n    def isatty(self):\n        io.RawIOBase.isatty(self)\n        return True\n\n\nclass _WindowsConsoleReader(_WindowsConsoleRawIOBase):\n\n    def readable(self):\n        return True\n\n    def readinto(self, b):\n        bytes_to_be_read = len(b)\n        if not bytes_to_be_read:\n            return 0\n        elif bytes_to_be_read % 2:\n            raise ValueError('cannot read odd number of bytes from '\n                             'UTF-16-LE encoded console')\n\n        buffer = get_buffer(b, writable=True)\n        code_units_to_be_read = bytes_to_be_read // 2\n        code_units_read = c_ulong()\n\n        rv = ReadConsoleW(HANDLE(self.handle), buffer, code_units_to_be_read,\n                          byref(code_units_read), None)\n        if GetLastError() == ERROR_OPERATION_ABORTED:\n            # wait for KeyboardInterrupt\n            time.sleep(0.1)\n        if not rv:\n            raise OSError('Windows error: %s' % GetLastError())\n\n        if buffer[0] == EOF:\n            return 0\n        return 2 * code_units_read.value\n\n\nclass _WindowsConsoleWriter(_WindowsConsoleRawIOBase):\n\n    def writable(self):\n        return True\n\n    @staticmethod\n    def _get_error_message(errno):\n        if errno == ERROR_SUCCESS:\n            return 'ERROR_SUCCESS'\n        elif errno == ERROR_NOT_ENOUGH_MEMORY:\n            return 'ERROR_NOT_ENOUGH_MEMORY'\n        return 'Windows error %s' % errno\n\n    def write(self, b):\n        bytes_to_be_written = len(b)\n        buf = get_buffer(b)\n        code_units_to_be_written = min(bytes_to_be_written,\n                                       MAX_BYTES_WRITTEN) // 2\n        code_units_written = c_ulong()\n\n        WriteConsoleW(HANDLE(self.handle), buf, code_units_to_be_written,\n                      byref(code_units_written), None)\n        bytes_written = 2 * code_units_written.value\n\n        if bytes_written == 0 and bytes_to_be_written > 0:\n            raise OSError(self._get_error_message(GetLastError()))\n        return bytes_written\n\n\nclass ConsoleStream(object):\n\n    def __init__(self, text_stream, byte_stream):\n        self._text_stream = text_stream\n        self.buffer = byte_stream\n\n    @property\n    def name(self):\n        return self.buffer.name\n\n    def write(self, x):\n        if isinstance(x, text_type):\n            return self._text_stream.write(x)\n        try:\n            self.flush()\n        except Exception:\n            pass\n        return self.buffer.write(x)\n\n    def writelines(self, lines):\n        for line in lines:\n            self.write(line)\n\n    def __getattr__(self, name):\n        return getattr(self._text_stream, name)\n\n    def isatty(self):\n        return self.buffer.isatty()\n\n    def __repr__(self):\n        return '<ConsoleStream name=%r encoding=%r>' % (\n            self.name,\n            self.encoding,\n        )\n\n\nclass WindowsChunkedWriter(object):\n    \"\"\"\n    Wraps a stream (such as stdout), acting as a transparent proxy for all\n    attribute access apart from method 'write()' which we wrap to write in\n    limited chunks due to a Windows limitation on binary console streams.\n    \"\"\"\n    def __init__(self, wrapped):\n        # double-underscore everything to prevent clashes with names of\n        # attributes on the wrapped stream object.\n        self.__wrapped = wrapped\n\n    def __getattr__(self, name):\n        return getattr(self.__wrapped, name)\n\n    def write(self, text):\n        total_to_write = len(text)\n        written = 0\n\n        while written < total_to_write:\n            to_write = min(total_to_write - written, MAX_BYTES_WRITTEN)\n            self.__wrapped.write(text[written:written+to_write])\n            written += to_write\n\n\n_wrapped_std_streams = set()\n\n\ndef _wrap_std_stream(name):\n    # Python 2 & Windows 7 and below\n    if PY2 and sys.getwindowsversion()[:2] <= (6, 1) and name not in _wrapped_std_streams:\n        setattr(sys, name, WindowsChunkedWriter(getattr(sys, name)))\n        _wrapped_std_streams.add(name)\n\n\ndef _get_text_stdin(buffer_stream):\n    text_stream = _NonClosingTextIOWrapper(\n        io.BufferedReader(_WindowsConsoleReader(STDIN_HANDLE)),\n        'utf-16-le', 'strict', line_buffering=True)\n    return ConsoleStream(text_stream, buffer_stream)\n\n\ndef _get_text_stdout(buffer_stream):\n    text_stream = _NonClosingTextIOWrapper(\n        io.BufferedWriter(_WindowsConsoleWriter(STDOUT_HANDLE)),\n        'utf-16-le', 'strict', line_buffering=True)\n    return ConsoleStream(text_stream, buffer_stream)\n\n\ndef _get_text_stderr(buffer_stream):\n    text_stream = _NonClosingTextIOWrapper(\n        io.BufferedWriter(_WindowsConsoleWriter(STDERR_HANDLE)),\n        'utf-16-le', 'strict', line_buffering=True)\n    return ConsoleStream(text_stream, buffer_stream)\n\n\nif PY2:\n    def _hash_py_argv():\n        return zlib.crc32('\\x00'.join(sys.argv[1:]))\n\n    _initial_argv_hash = _hash_py_argv()\n\n    def _get_windows_argv():\n        argc = c_int(0)\n        argv_unicode = CommandLineToArgvW(GetCommandLineW(), byref(argc))\n        argv = [argv_unicode[i] for i in range(0, argc.value)]\n\n        if not hasattr(sys, 'frozen'):\n            argv = argv[1:]\n            while len(argv) > 0:\n                arg = argv[0]\n                if not arg.startswith('-') or arg == '-':\n                    break\n                argv = argv[1:]\n                if arg.startswith(('-c', '-m')):\n                    break\n\n        return argv[1:]\n\n\n_stream_factories = {\n    0: _get_text_stdin,\n    1: _get_text_stdout,\n    2: _get_text_stderr,\n}\n\n\ndef _is_console(f):\n    if not hasattr(f, 'fileno'):\n        return False\n\n    try:\n        fileno = f.fileno()\n    except OSError:\n        return False\n\n    handle = msvcrt.get_osfhandle(fileno)\n    return bool(GetConsoleMode(handle, byref(DWORD())))\n\n\ndef _get_windows_console_stream(f, encoding, errors):\n    if get_buffer is not None and \\\n       encoding in ('utf-16-le', None) \\\n       and errors in ('strict', None) and \\\n       _is_console(f):\n        func = _stream_factories.get(f.fileno())\n        if func is not None:\n            if not PY2:\n                f = getattr(f, 'buffer', None)\n                if f is None:\n                    return None\n            else:\n                # If we are on Python 2 we need to set the stream that we\n                # deal with to binary mode as otherwise the exercise if a\n                # bit moot.  The same problems apply as for\n                # get_binary_stdin and friends from _compat.\n                msvcrt.setmode(f.fileno(), os.O_BINARY)\n            return func(f)\n", "path": "click/_winconsole.py"}], "after_files": [{"content": "# -*- coding: utf-8 -*-\n# This module is based on the excellent work by Adam Barto\u0161 who\n# provided a lot of what went into the implementation here in\n# the discussion to issue1602 in the Python bug tracker.\n#\n# There are some general differences in regards to how this works\n# compared to the original patches as we do not need to patch\n# the entire interpreter but just work in our little world of\n# echo and prmopt.\n\nimport io\nimport os\nimport sys\nimport zlib\nimport time\nimport ctypes\nimport msvcrt\nfrom ._compat import _NonClosingTextIOWrapper, text_type, PY2\nfrom ctypes import byref, POINTER, c_int, c_char, c_char_p, \\\n     c_void_p, py_object, c_ssize_t, c_ulong, windll, WINFUNCTYPE, \\\n     WinError\ntry:\n    from ctypes import pythonapi\n    PyObject_GetBuffer = pythonapi.PyObject_GetBuffer\n    PyBuffer_Release = pythonapi.PyBuffer_Release\nexcept ImportError:\n    pythonapi = None\nfrom ctypes.wintypes import DWORD, LPWSTR, LPCWSTR, HANDLE\n\n\nc_ssize_p = POINTER(c_ssize_t)\n\nkernel32 = windll.kernel32\nGetStdHandle = kernel32.GetStdHandle\nReadConsoleW = kernel32.ReadConsoleW\nWriteConsoleW = kernel32.WriteConsoleW\nGetConsoleMode = kernel32.GetConsoleMode\nGetLastError = kernel32.GetLastError\nGetCommandLineW = WINFUNCTYPE(LPWSTR)(\n    ('GetCommandLineW', windll.kernel32))\nCommandLineToArgvW = WINFUNCTYPE(\n    POINTER(LPWSTR), LPCWSTR, POINTER(c_int))(\n        ('CommandLineToArgvW', windll.shell32))\nLocalFree = WINFUNCTYPE(ctypes.c_void_p, ctypes.c_void_p)(\n    ('LocalFree', windll.kernel32))\n\n\nSTDIN_HANDLE = GetStdHandle(-10)\nSTDOUT_HANDLE = GetStdHandle(-11)\nSTDERR_HANDLE = GetStdHandle(-12)\n\n\nPyBUF_SIMPLE = 0\nPyBUF_WRITABLE = 1\n\nERROR_SUCCESS = 0\nERROR_NOT_ENOUGH_MEMORY = 8\nERROR_OPERATION_ABORTED = 995\n\nSTDIN_FILENO = 0\nSTDOUT_FILENO = 1\nSTDERR_FILENO = 2\n\nEOF = b'\\x1a'\nMAX_BYTES_WRITTEN = 32767\n\n\nclass Py_buffer(ctypes.Structure):\n    _fields_ = [\n        ('buf', c_void_p),\n        ('obj', py_object),\n        ('len', c_ssize_t),\n        ('itemsize', c_ssize_t),\n        ('readonly', c_int),\n        ('ndim', c_int),\n        ('format', c_char_p),\n        ('shape', c_ssize_p),\n        ('strides', c_ssize_p),\n        ('suboffsets', c_ssize_p),\n        ('internal', c_void_p)\n    ]\n\n    if PY2:\n        _fields_.insert(-1, ('smalltable', c_ssize_t * 2))\n\n\n# On PyPy we cannot get buffers so our ability to operate here is\n# serverly limited.\nif pythonapi is None:\n    get_buffer = None\nelse:\n    def get_buffer(obj, writable=False):\n        buf = Py_buffer()\n        flags = PyBUF_WRITABLE if writable else PyBUF_SIMPLE\n        PyObject_GetBuffer(py_object(obj), byref(buf), flags)\n        try:\n            buffer_type = c_char * buf.len\n            return buffer_type.from_address(buf.buf)\n        finally:\n            PyBuffer_Release(byref(buf))\n\n\nclass _WindowsConsoleRawIOBase(io.RawIOBase):\n\n    def __init__(self, handle):\n        self.handle = handle\n\n    def isatty(self):\n        io.RawIOBase.isatty(self)\n        return True\n\n\nclass _WindowsConsoleReader(_WindowsConsoleRawIOBase):\n\n    def readable(self):\n        return True\n\n    def readinto(self, b):\n        bytes_to_be_read = len(b)\n        if not bytes_to_be_read:\n            return 0\n        elif bytes_to_be_read % 2:\n            raise ValueError('cannot read odd number of bytes from '\n                             'UTF-16-LE encoded console')\n\n        buffer = get_buffer(b, writable=True)\n        code_units_to_be_read = bytes_to_be_read // 2\n        code_units_read = c_ulong()\n\n        rv = ReadConsoleW(HANDLE(self.handle), buffer, code_units_to_be_read,\n                          byref(code_units_read), None)\n        if GetLastError() == ERROR_OPERATION_ABORTED:\n            # wait for KeyboardInterrupt\n            time.sleep(0.1)\n        if not rv:\n            raise OSError('Windows error: %s' % GetLastError())\n\n        if buffer[0] == EOF:\n            return 0\n        return 2 * code_units_read.value\n\n\nclass _WindowsConsoleWriter(_WindowsConsoleRawIOBase):\n\n    def writable(self):\n        return True\n\n    @staticmethod\n    def _get_error_message(errno):\n        if errno == ERROR_SUCCESS:\n            return 'ERROR_SUCCESS'\n        elif errno == ERROR_NOT_ENOUGH_MEMORY:\n            return 'ERROR_NOT_ENOUGH_MEMORY'\n        return 'Windows error %s' % errno\n\n    def write(self, b):\n        bytes_to_be_written = len(b)\n        buf = get_buffer(b)\n        code_units_to_be_written = min(bytes_to_be_written,\n                                       MAX_BYTES_WRITTEN) // 2\n        code_units_written = c_ulong()\n\n        WriteConsoleW(HANDLE(self.handle), buf, code_units_to_be_written,\n                      byref(code_units_written), None)\n        bytes_written = 2 * code_units_written.value\n\n        if bytes_written == 0 and bytes_to_be_written > 0:\n            raise OSError(self._get_error_message(GetLastError()))\n        return bytes_written\n\n\nclass ConsoleStream(object):\n\n    def __init__(self, text_stream, byte_stream):\n        self._text_stream = text_stream\n        self.buffer = byte_stream\n\n    @property\n    def name(self):\n        return self.buffer.name\n\n    def write(self, x):\n        if isinstance(x, text_type):\n            return self._text_stream.write(x)\n        try:\n            self.flush()\n        except Exception:\n            pass\n        return self.buffer.write(x)\n\n    def writelines(self, lines):\n        for line in lines:\n            self.write(line)\n\n    def __getattr__(self, name):\n        return getattr(self._text_stream, name)\n\n    def isatty(self):\n        return self.buffer.isatty()\n\n    def __repr__(self):\n        return '<ConsoleStream name=%r encoding=%r>' % (\n            self.name,\n            self.encoding,\n        )\n\n\nclass WindowsChunkedWriter(object):\n    \"\"\"\n    Wraps a stream (such as stdout), acting as a transparent proxy for all\n    attribute access apart from method 'write()' which we wrap to write in\n    limited chunks due to a Windows limitation on binary console streams.\n    \"\"\"\n    def __init__(self, wrapped):\n        # double-underscore everything to prevent clashes with names of\n        # attributes on the wrapped stream object.\n        self.__wrapped = wrapped\n\n    def __getattr__(self, name):\n        return getattr(self.__wrapped, name)\n\n    def write(self, text):\n        total_to_write = len(text)\n        written = 0\n\n        while written < total_to_write:\n            to_write = min(total_to_write - written, MAX_BYTES_WRITTEN)\n            self.__wrapped.write(text[written:written+to_write])\n            written += to_write\n\n\n_wrapped_std_streams = set()\n\n\ndef _wrap_std_stream(name):\n    # Python 2 & Windows 7 and below\n    if PY2 and sys.getwindowsversion()[:2] <= (6, 1) and name not in _wrapped_std_streams:\n        setattr(sys, name, WindowsChunkedWriter(getattr(sys, name)))\n        _wrapped_std_streams.add(name)\n\n\ndef _get_text_stdin(buffer_stream):\n    text_stream = _NonClosingTextIOWrapper(\n        io.BufferedReader(_WindowsConsoleReader(STDIN_HANDLE)),\n        'utf-16-le', 'strict', line_buffering=True)\n    return ConsoleStream(text_stream, buffer_stream)\n\n\ndef _get_text_stdout(buffer_stream):\n    text_stream = _NonClosingTextIOWrapper(\n        io.BufferedWriter(_WindowsConsoleWriter(STDOUT_HANDLE)),\n        'utf-16-le', 'strict', line_buffering=True)\n    return ConsoleStream(text_stream, buffer_stream)\n\n\ndef _get_text_stderr(buffer_stream):\n    text_stream = _NonClosingTextIOWrapper(\n        io.BufferedWriter(_WindowsConsoleWriter(STDERR_HANDLE)),\n        'utf-16-le', 'strict', line_buffering=True)\n    return ConsoleStream(text_stream, buffer_stream)\n\n\nif PY2:\n    def _hash_py_argv():\n        return zlib.crc32('\\x00'.join(sys.argv[1:]))\n\n    _initial_argv_hash = _hash_py_argv()\n\n    def _get_windows_argv():\n        argc = c_int(0)\n        argv_unicode = CommandLineToArgvW(GetCommandLineW(), byref(argc))\n        if not argv_unicode:\n            raise WinError()\n        try:\n            argv = [argv_unicode[i] for i in range(0, argc.value)]\n        finally:\n            LocalFree(argv_unicode)\n            del argv_unicode\n\n        if not hasattr(sys, 'frozen'):\n            argv = argv[1:]\n            while len(argv) > 0:\n                arg = argv[0]\n                if not arg.startswith('-') or arg == '-':\n                    break\n                argv = argv[1:]\n                if arg.startswith(('-c', '-m')):\n                    break\n\n        return argv[1:]\n\n\n_stream_factories = {\n    0: _get_text_stdin,\n    1: _get_text_stdout,\n    2: _get_text_stderr,\n}\n\n\ndef _is_console(f):\n    if not hasattr(f, 'fileno'):\n        return False\n\n    try:\n        fileno = f.fileno()\n    except OSError:\n        return False\n\n    handle = msvcrt.get_osfhandle(fileno)\n    return bool(GetConsoleMode(handle, byref(DWORD())))\n\n\ndef _get_windows_console_stream(f, encoding, errors):\n    if get_buffer is not None and \\\n       encoding in ('utf-16-le', None) \\\n       and errors in ('strict', None) and \\\n       _is_console(f):\n        func = _stream_factories.get(f.fileno())\n        if func is not None:\n            if not PY2:\n                f = getattr(f, 'buffer', None)\n                if f is None:\n                    return None\n            else:\n                # If we are on Python 2 we need to set the stream that we\n                # deal with to binary mode as otherwise the exercise if a\n                # bit moot.  The same problems apply as for\n                # get_binary_stdin and friends from _compat.\n                msvcrt.setmode(f.fileno(), os.O_BINARY)\n            return func(f)\n", "path": "click/_winconsole.py"}]}